{"input": "", "context": "/*\n * This file is part of Gaia Sky, which is released under the Mozilla Public License 2.0.\n * See the file LICENSE.md in the project root for full license details.\n */\n\npackage gaiasky.util.math;\n\n/*******************************************************************************\n * Copyright 2011 See AUTHORS file.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not\n * use this file except in compliance with the License. You may obtain a copy of\n * the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n * License for the specific language governing permissions and limitations under\n * the License.\n ******************************************************************************/\n\nimport com.badlogic.gdx.math.Matrix3;\nimport com.badlogic.gdx.math.Matrix4;\nimport com.badlogic.gdx.math.Vector3;\n\nimport java.io.Serializable;\n\n/**\n * Encapsulates a column\n * major 4 by 4 matrix. Like the {@link Vector3d} class it allows the\n * chaining of methods by returning a reference to itself. For example:\n *\n *
\n * Matrix4d mat = new Matrix4d().trn(position).mul(camera.combined);\n * 
\n *\n * @author badlogicgames@gmail.com\n */\npublic class Matrix4d implements Serializable {\n private static final long serialVersionUID = -2717655254359579617L;\n /**\n * XX: Typically the unrotated X component for scaling, also the cosine of\n * the angle when rotated on the Y and/or Z axis. On Vector3d multiplication\n * this value is multiplied with the source X component and added to the\n * target X component.\n */\n public static final int M00 = 0;\n /**\n * XY: Typically the negative sine of the angle when rotated on the Z axis.\n * On Vector3d multiplication this value is multiplied with the source Y\n * component and added to the target X component.\n */\n public static final int M01 = 4;\n /**\n * XZ: Typically the sine of the angle when rotated on the Y axis. On\n * Vector3d multiplication this value is multiplied with the source Z\n * component and added to the target X component.\n */\n public static final int M02 = 8;\n /**\n * XW: Typically the translation of the X component. On Vector3d\n * multiplication this value is added to the target X component.\n */\n public static final int M03 = 12;\n /**\n * YX: Typically the sine of the angle when rotated on the Z axis. On\n * Vector3d multiplication this value is multiplied with the source X\n * component and added to the target Y component.\n */\n public static final int M10 = 1;\n /**\n * YY: Typically the unrotated Y component for scaling, also the cosine of\n * the angle when rotated on the X and/or Z axis. On Vector3d multiplication\n * this value is multiplied with the source Y component and added to the\n * target Y component.\n */\n public static final int M11 = 5;\n /**\n * YZ: Typically the negative sine of the angle when rotated on the X axis.\n * On Vector3d multiplication this value is multiplied with the source Z\n * component and added to the target Y component.\n */\n public static final int M12 = 9;\n /**\n * YW: Typically the translation of the Y component. On Vector3d\n * multiplication this value is added to the target Y component.\n */\n public static final int M13 = 13;\n /**\n * ZX: Typically the negative sine of the angle when rotated on the Y axis.\n * On Vector3d multiplication this value is multiplied with the source X\n * component and added to the target Z component.\n */\n public static final int M20 = 2;\n /**\n * ZY: Typical the sine of the angle when rotated on the X axis. On Vector3d\n * multiplication this value is multiplied with the source Y component and\n * added to the target Z component.\n */\n public static final int M21 = 6;\n /**\n * ZZ: Typically the unrotated Z component for scaling, also the cosine of\n * the angle when rotated on the X and/or Y axis. On Vector3d multiplication\n * this value is multiplied with the source Z component and added to the\n * target Z component.\n */\n public static final int M22 = 10;\n /**\n * ZW: Typically the translation of the Z component. On Vector3d\n * multiplication this value is added to the target Z component.\n */\n public static final int M23 = 14;\n /**\n * WX: Typically the value zero. On Vector3d multiplication this value is\n * ignored.\n */\n public static final int M30 = 3;\n /**\n * WY: Typically the value zero. On Vector3d multiplication this value is\n * ignored.\n */\n public static final int M31 = 7;\n /**\n * WZ: Typically the value zero. On Vector3d multiplication this value is\n * ignored.\n */\n public static final int M32 = 11;\n /**\n * WW: Typically the value one. On Vector3d multiplication this value is\n * ignored.\n */\n public static final int M33 = 15;\n\n public final static double[] stmp = new double[16];\n public final double[] tmp = new double[16];\n public final double[] val = new double[16];\n\n /** Constructs an identity matrix */\n public Matrix4d() {\n val[M00] = 1f;\n val[M11] = 1f;\n val[M22] = 1f;\n val[M33] = 1f;\n }\n\n /**\n * Constructs a matrix from the given matrix.\n *\n * @param matrix The matrix to copy. (This matrix is not modified)\n */\n public Matrix4d(Matrix4d matrix) {\n this.set(matrix);\n }\n\n /**\n * Constructs a matrix from the given double array. The array must have at\n * least 16 elements; the first 16 will be copied.\n *\n * @param values The double array to copy. Remember that this matrix is in\n * column\n * major order. (The double array is not modified.)\n */\n public Matrix4d(double[] values) {\n this.set(values);\n }\n\n public Matrix4d(float[] values) {\n this.set(values);\n }\n\n /**\n * Constructs a rotation matrix from the given {@link Quaterniond}.\n *\n * @param quaternion The quaternion to be copied. (The quaternion is not modified)\n */\n public Matrix4d(Quaterniond quaternion) {\n this.set(quaternion);\n }\n\n /**\n * Construct a matrix from the given translation, rotation and scale.\n *\n * @param position The translation\n * @param rotation The rotation, must be normalized\n * @param scale The scale\n */\n public Matrix4d(Vector3d position, Quaterniond rotation, Vector3d scale) {\n set(position, rotation, scale);\n }\n\n /**\n * Sets the matrix to the given matrix.\n *\n * @param matrix The matrix that is to be copied. (The given matrix is not\n * modified)\n *\n * @return This matrix for the purpose of chaining methods together.\n */\n public Matrix4d set(Matrix4d matrix) {\n return this.set(matrix.val);\n }\n\n public Matrix4d set(Matrix4 matrix) {\n return this.set(matrix.val);\n }\n\n /**\n * Sets the matrix to the given matrix as a double array. The double array\n * must have at least 16 elements; the first 16 will be copied.\n *\n * @param values The matrix, in double form, that is to be copied. Remember\n * that this matrix is in column\n * major order.\n *\n * @return This matrix for the purpose of chaining methods together.\n */\n public Matrix4d set(double[] values) {\n System.arraycopy(values, 0, val, 0, val.length);\n return this;\n }\n\n public Matrix4d set(float[] values) {\n for (int i = 0; i < val.length; i++) {\n val[i] = values[i];\n }\n return this;\n }\n\n /**\n * Sets the matrix to a rotation matrix representing the quaternion.\n *\n * @param quaternion The quaternion that is to be used to set this matrix.\n *\n * @return This matrix for the purpose of chaining methods together.\n */\n public Matrix4d set(Quaterniond quaternion) {\n return set(quaternion.x, quaternion.y, quaternion.z, quaternion.w);\n }\n\n /**\n * Sets the matrix to a rotation matrix representing the quaternion.\n *\n * @param quaternionX The X component of the quaternion that is to be used to set\n * this matrix.\n * @param quaternionY The Y component of the quaternion that is to be used to set\n * this matrix.\n * @param quaternionZ The Z component of the quaternion that is to be used to set\n * this matrix.\n * @param quaternionW The W component of the quaternion that is to be used to set\n * this matrix.\n *\n * @return This matrix for the purpose of chaining methods together.\n */\n public Matrix4d set(double quaternionX, double quaternionY, double quaternionZ, double quaternionW) {\n return set(0f, 0f, 0f, quaternionX, quaternionY, quaternionZ, quaternionW);\n }\n\n /**\n * Set this matrix to the specified translation and rotation.\n *\n * @param position The translation\n * @param orientation The rotation, must be normalized\n *\n * @return This matrix for chaining\n */\n public Matrix4d set(Vector3d position, Quaterniond orientation) {\n return set(position.x, position.y, position.z, orientation.x, orientation.y, orientation.z, orientation.w);\n }\n\n /**\n * Sets the matrix to a rotation matrix representing the translation and\n * quaternion.\n *\n * @param translationX The X component of the translation that is to be used to set\n * this matrix.\n * @param translationY The Y component of the translation that is to be used to set\n * this matrix.\n * @param translationZ The Z component of the translation that is to be used to set\n * this matrix.\n * @param quaternionX The X component of the quaternion that is to be used to set\n * this matrix.\n * @param quaternionY The Y component of the quaternion that is to be used to set\n * this matrix.\n * @param quaternionZ The Z component of the quaternion that is to be used to set\n * this matrix.\n * @param quaternionW The W component of the quaternion that is to be used to set\n * this matrix.\n *\n * @return This matrix for the purpose of chaining methods together.\n */\n public Matrix4d set(double translationX, double translationY, double translationZ, double quaternionX, double quaternionY, double quaternionZ, double quaternionW) {\n final double xs = quaternionX * 2f, ys = quaternionY * 2f, zs = quaternionZ * 2f;\n final double wx = quaternionW * xs, wy = quaternionW * ys, wz = quaternionW * zs;\n final double xx = quaternionX * xs, xy = quaternionX * ys, xz = quaternionX * zs;\n final double yy = quaternionY * ys, yz = quaternionY * zs, zz = quaternionZ * zs;\n\n val[M00] = (1.0f - (yy + zz));\n val[M01] = (xy - wz);\n val[M02] = (xz + wy);\n val[M03] = translationX;\n\n val[M10] = (xy + wz);\n val[M11] = (1.0f - (xx + zz));\n val[M12] = (yz - wx);\n val[M13] = translationY;\n\n val[M20] = (xz - wy);\n val[M21] = (yz + wx);\n val[M22] = (1.0f - (xx + yy));\n val[M23] = translationZ;\n\n val[M30] = 0.f;\n val[M31] = 0.f;\n val[M32] = 0.f;\n val[M33] = 1.0f;\n return this;\n }\n\n /**\n * Set this matrix to the specified translation, rotation and scale.\n *\n * @param position The translation\n * @param orientation The rotation, must be normalized\n * @param scale The scale\n *\n * @return This matrix for chaining\n */\n public Matrix4d set(Vector3d position, Quaterniond orientation, Vector3d scale) {\n return set(position.x, position.y, position.z, orientation.x, orientation.y, orientation.z, orientation.w, scale.x, scale.y, scale.z);\n }\n\n /**\n * Sets the matrix to a rotation matrix representing the translation and\n * quaternion.\n *\n * @param translationX The X component of the translation that is to be used to set\n * this matrix.\n * @param translationY The Y component of the translation that is to be used to set\n * this matrix.\n * @param translationZ The Z component of the translation that is to be used to set\n * this matrix.\n * @param quaternionX The X component of the quaternion that is to be used to set\n * this matrix.\n * @param quaternionY The Y component of the quaternion that is to be used to set\n * this matrix.\n * @param quaternionZ The Z component of the quaternion that is to be used to set\n * this matrix.\n * @param quaternionW The W component of the quaternion that is to be used to set\n * this matrix.\n * @param scaleX The X component of the scaling that is to be used to set this\n * matrix.\n * @param scaleY The Y component of the scaling that is to be used to set this\n * matrix.\n * @param scaleZ The Z component of the scaling that is to be used to set this\n * matrix.\n *\n * @return This matrix for the purpose of chaining methods together.\n */\n public Matrix4d set(double translationX, double translationY, double translationZ, double quaternionX, double quaternionY, double quaternionZ, double quaternionW, double scaleX, double scaleY, double scaleZ) {\n final double xs = quaternionX * 2f, ys = quaternionY * 2f, zs = quaternionZ * 2f;\n final double wx = quaternionW * xs, wy = quaternionW * ys, wz = quaternionW * zs;\n final double xx = quaternionX * xs, xy = quaternionX * ys, xz = quaternionX * zs;\n final double yy = quaternionY * ys, yz = quaternionY * zs, zz = quaternionZ * zs;\n\n val[M00] = scaleX * (1.0f - (yy + zz));\n val[M01] = scaleY * (xy - wz);\n val[M02] = scaleZ * (xz + wy);\n val[M03] = translationX;\n\n val[M10] = scaleX * (xy + wz);\n val[M11] = scaleY * (1.0f - (xx + zz));\n val[M12] = scaleZ * (yz - wx);\n val[M13] = translationY;\n\n val[M20] = scaleX * (xz - wy);\n val[M21] = scaleY * (yz + wx);\n val[M22] = scaleZ * (1.0f - (xx + yy));\n val[M23] = translationZ;\n\n val[M30] = 0.f;\n val[M31] = 0.f;\n val[M32] = 0.f;\n val[M33] = 1.0f;\n return this;\n }\n\n /**\n * Sets the four columns of the matrix which correspond to the x-, y- and\n * z-axis of the vector space this matrix creates as well as the 4th column\n * representing the translation of any point that is multiplied by this\n * matrix.\n *\n * @param xAxis The x-axis.\n * @param yAxis The y-axis.\n * @param zAxis The z-axis.\n * @param pos The translation vector.\n */\n public Matrix4d set(Vector3d xAxis, Vector3d yAxis, Vector3d zAxis, Vector3d pos) {\n val[M00] = xAxis.x;\n val[M01] = xAxis.y;\n val[M02] = xAxis.z;\n val[M10] = yAxis.x;\n val[M11] = yAxis.y;\n val[M12] = yAxis.z;\n val[M20] = -zAxis.x;\n val[M21] = -zAxis.y;\n val[M22] = -zAxis.z;\n val[M03] = pos.x;\n val[M13] = pos.y;\n val[M23] = pos.z;\n val[M30] = 0;\n val[M31] = 0;\n val[M32] = 0;\n val[M33] = 1;\n return this;\n }\n\n /** @return a copy of this matrix */\n public Matrix4d cpy() {\n return new Matrix4d(this);\n }\n\n /**\n * Adds a translational component to the matrix in the 4th column. The other\n * columns are untouched.\n *\n * @param vector The translation vector to add to the current matrix. (This\n * vector is not modified)\n *\n * @return This matrix for the purpose of chaining methods together.\n */\n public Matrix4d trn(Vector3d vector) {\n val[M03] += vector.x;\n val[M13] += vector.y;\n val[M23] += vector.z;\n return this;\n }\n\n /**\n * Adds a translational component to the matrix in the 4th column. The other\n * columns are untouched.\n *\n * @param x The x-component of the translation vector.\n * @param y The y-component of the translation vector.\n * @param z The z-component of the translation vector.\n *\n * @return This matrix for the purpose of chaining methods together.\n */\n public Matrix4d trn(double x, double y, double z) {\n val[M03] += x;\n val[M13] += y;\n val[M23] += z;\n return this;\n }\n\n /** @return the backing double array */\n public double[] getValues() {\n return val;\n }\n\n public float[] getValuesFloat() {\n float[] res = new float[val.length];\n for (int i = 0; i < val.length; i++)\n res[i] = (float) val[i];\n return res;\n }\n\n /**\n * Postmultiplies this matrix with the given matrix, storing the result in\n * this matrix. For example:\n *\n *
\n     * A.mul(B) results in A := AB.\n     * 
\n *\n * @param matrix The other matrix to multiply by.\n *\n * @return This matrix for the purpose of chaining operations together.\n */\n public Matrix4d mul(Matrix4d matrix) {\n matrix4_mul(val, matrix.val);\n return this;\n }\n\n /**\n * Premultiplies this matrix with the given matrix, storing the result in\n * this matrix. For example:\n *\n *
\n     * A.mulLeft(B) results in A := BA.\n     * 
\n *\n * @param matrix The other matrix to multiply by.\n *\n * @return This matrix for the purpose of chaining operations together.\n */\n public Matrix4d mulLeft(Matrix4d matrix) {\n tmpMat.set(matrix);\n // mul(tmpMat.val, this.val);\n tmpMat.mul(this);\n return set(tmpMat);\n }\n\n /**\n * Transposes the matrix.\n *\n * @return This matrix for the purpose of chaining methods together.\n */\n public Matrix4d tra() {\n tmp[M00] = val[M00];\n tmp[M01] = val[M10];\n tmp[M02] = val[M20];\n tmp[M03] = val[M30];\n tmp[M10] = val[M01];\n tmp[M11] = val[M11];\n tmp[M12] = val[M21];\n tmp[M13] = val[M31];\n tmp[M20] = val[M02];\n tmp[M21] = val[M12];\n tmp[M22] = val[M22];\n tmp[M23] = val[M32];\n tmp[M30] = val[M03];\n tmp[M31] = val[M13];\n tmp[M32] = val[M23];\n tmp[M33] = val[M33];\n return set(tmp);\n }\n\n /**\n * Sets the matrix to an identity matrix.\n *\n * @return This matrix for the purpose of chaining methods together.\n */\n public Matrix4d idt() {\n val[M00] = 1;\n val[M01] = 0;\n val[M02] = 0;\n val[M03] = 0;\n val[M10] = 0;\n val[M11] = 1;\n val[M12] = 0;\n val[M13] = 0;\n val[M20] = 0;\n val[M21] = 0;\n val[M22] = 1;\n val[M23] = 0;\n val[M30] = 0;\n val[M31] = 0;\n val[M32] = 0;\n val[M33] = 1;\n return this;\n }\n\n public Matrix4d inv() {\n matrix4_inv(val);\n return this;\n }\n\n /**\n * Computes the inverse of the given matrix. The matrix array is assumed to\n * hold a 4x4 column major matrix as you can get from {@link Matrix4#val}.\n *\n * @param values the matrix values.\n *\n * @return false in case the inverse could not be calculated, true\n * otherwise.\n */\n public static boolean inv(double[] values) {\n return matrix4_inv(values);\n }\n\n /** @return The determinant of this matrix */\n public double det() {\n return val[M30] * val[M21] * val[M12] * val[M03] - val[M20] * val[M31] * val[M12] * val[M03] - val[M30] * val[M11] * val[M22] * val[M03] + val[M10] * val[M31] * val[M22] * val[M03] + val[M20] * val[M11] * val[M32] * val[M03] - val[M10] * val[M21] * val[M32] * val[M03] - val[M30] * val[M21] * val[M02] * val[M13] + val[M20] * val[M31] * val[M02] * val[M13] + val[M30] * val[M01] * val[M22] * val[M13] - val[M00] * val[M31] * val[M22] * val[M13] - val[M20] * val[M01] * val[M32] * val[M13]\n + val[M00] * val[M21] * val[M32] * val[M13] + val[M30] * val[M11] * val[M02] * val[M23] - val[M10] * val[M31] * val[M02] * val[M23] - val[M30] * val[M01] * val[M12] * val[M23] + val[M00] * val[M31] * val[M12] * val[M23] + val[M10] * val[M01] * val[M32] * val[M23] - val[M00] * val[M11] * val[M32] * val[M23] - val[M20] * val[M11] * val[M02] * val[M33] + val[M10] * val[M21] * val[M02] * val[M33] + val[M20] * val[M01] * val[M12] * val[M33] - val[M00] * val[M21] * val[M12] * val[M33]\n - val[M10] * val[M01] * val[M22] * val[M33] + val[M00] * val[M11] * val[M22] * val[M33];\n }\n\n /** @return The determinant of the 3x3 upper left matrix */\n public double det3x3() {\n return val[M00] * val[M11] * val[M22] + val[M01] * val[M12] * val[M20] + val[M02] * val[M10] * val[M21] - val[M00] * val[M12] * val[M21] - val[M01] * val[M10] * val[M22] - val[M02] * val[M11] * val[M20];\n }\n\n /**\n * Sets the matrix to a projection matrix with a near- and far plane, a\n * field of view in degrees and an aspect ratio.\n *\n * @param near The near plane\n * @param far The far plane\n * @param fov The field of view in degrees\n * @param aspectRatio The \"width over height\" aspect ratio\n *\n * @return This matrix for the purpose of chaining methods together.\n */\n public Matrix4d setToProjection(double near, double far, double fov, double aspectRatio) {\n idt();\n double l_fd = 1.0 / Math.tan((fov * (Math.PI / 180)) / 2.0);\n double l_a1 = (far + near) / (near - far);\n double l_a2 = (2 * far * near) / (near - far);\n val[M00] = l_fd / aspectRatio;\n val[M10] = 0;\n val[M20] = 0;\n val[M30] = 0;\n val[M01] = 0;\n val[M11] = l_fd;\n val[M21] = 0;\n val[M31] = 0;\n val[M02] = 0;\n val[M12] = 0;\n val[M22] = l_a1;\n val[M32] = -1;\n val[M03] = 0;\n val[M13] = 0;\n val[M23] = l_a2;\n val[M33] = 0;\n\n return this;\n }\n\n /**\n * Sets this matrix to an orthographic projection matrix with the origin at\n * (x,y) extending by width and height. The near plane is set to 0, the far\n * plane is set to 1.\n *\n * @param x The x-coordinate of the origin\n * @param y The y-coordinate of the origin\n * @param width The width\n * @param height The height\n *\n * @return This matrix for the purpose of chaining methods together.\n */\n public Matrix4d setToOrtho2D(double x, double y, double width, double height) {\n setToOrtho(x, x + width, y, y + height, 0, 1);\n return this;\n }\n\n /**\n * Sets this matrix to an orthographic projection matrix with the origin at\n * (x,y) extending by width and height, having a near and far plane.\n *\n * @param x The x-coordinate of the origin\n * @param y The y-coordinate of the origin\n * @param width The width\n * @param height The height\n * @param near The near plane\n * @param far The far plane\n *\n * @return This matrix for the purpose of chaining methods together.\n */\n public Matrix4d setToOrtho2D(double x, double y, double width, double height, double near, double far) {\n setToOrtho(x, x + width, y, y + height, near, far);\n return this;\n }\n\n /**\n * Sets the matrix to an orthographic projection like glOrtho\n * (http://www.opengl.org/sdk/docs/man/xhtml/glOrtho.xml) following the\n * OpenGL equivalent\n *\n * @param left The left clipping plane\n * @param right The right clipping plane\n * @param bottom The bottom clipping plane\n * @param top The top clipping plane\n * @param near The near clipping plane\n * @param far The far clipping plane\n *\n * @return This matrix for the purpose of chaining methods together.\n */\n public Matrix4d setToOrtho(double left, double right, double bottom, double top, double near, double far) {\n\n this.idt();\n double x_orth = 2 / (right - left);\n double y_orth = 2 / (top - bottom);\n double z_orth = -2 / (far - near);\n\n double tx = -(right + left) / (right - left);\n double ty = -(top + bottom) / (top - bottom);\n double tz = -(far + near) / (far - near);\n\n val[M00] = x_orth;\n val[M10] = 0;\n val[M20] = 0;\n val[M30] = 0;\n val[M01] = 0;\n val[M11] = y_orth;\n val[M21] = 0;\n val[M31] = 0;\n val[M02] = 0;\n val[M12] = 0;\n val[M22] = z_orth;\n val[M32] = 0;\n val[M03] = tx;\n val[M13] = ty;\n val[M23] = tz;\n val[M33] = 1;\n\n return this;\n }\n\n /**\n * Sets the 4th column to the translation vector.\n *\n * @param vector The translation vector\n *\n * @return This matrix for the purpose of chaining methods together.\n */\n public Matrix4d setTranslation(Vector3d vector) {\n val[M03] = vector.x;\n val[M13] = vector.y;\n val[M23] = vector.z;\n return this;\n }\n\n /**\n * Sets the 4th column to the translation vector.\n *\n * @param x The X coordinate of the translation vector\n * @param y The Y coordinate of the translation vector\n * @param z The Z coordinate of the translation vector\n *\n * @return This matrix for the purpose of chaining methods together.\n */\n public Matrix4d setTranslation(double x, double y, double z) {\n val[M03] = x;\n val[M13] = y;\n val[M23] = z;\n return this;\n }\n\n /**\n * Sets this matrix to a translation matrix, overwriting it first by an\n * identity matrix and then setting the 4th column to the translation\n * vector.\n *\n * @param vector The translation vector\n *\n * @return This matrix for the purpose of chaining methods together.\n */\n public Matrix4d setToTranslation(Vector3d vector) {\n idt();\n val[M03] = vector.x;\n val[M13] = vector.y;\n val[M23] = vector.z;\n return this;\n }\n\n public Matrix4d setToTranslation(Vector3 vector) {\n idt();\n val[M03] = vector.x;\n val[M13] = vector.y;\n val[M23] = vector.z;\n return this;\n }\n\n /**\n * Sets this matrix to a translation matrix, overwriting it first by an\n * identity matrix and then setting the 4th column to the translation\n * vector.\n *\n * @param x The x-component of the translation vector.\n * @param y The y-component of the translation vector.\n * @param z The z-component of the translation vector.\n *\n * @return This matrix for the purpose of chaining methods together.\n */\n public Matrix4d setToTranslation(double x, double y, double z) {\n idt();\n val[M03] = x;\n val[M13] = y;\n val[M23] = z;\n return this;\n }\n\n /**\n * Sets this matrix to a translation and scaling matrix by first overwriting\n * it with an identity and then setting the translation vector in the 4th\n * column and the scaling vector in the diagonal.\n *\n * @param translation The translation vector\n * @param scaling The scaling vector\n *\n * @return This matrix for the purpose of chaining methods together.\n */\n public Matrix4d setToTranslationAndScaling(Vector3d translation, Vector3d scaling) {\n idt();\n val[M03] = translation.x;\n val[M13] = translation.y;\n val[M23] = translation.z;\n val[M00] = scaling.x;\n val[M11] = scaling.y;\n val[M22] = scaling.z;\n return this;\n }\n\n /**\n * Sets this matrix to a translation and scaling matrix by first overwriting\n * it with an identity and then setting the translation vector in the 4th\n * column and the scaling vector in the diagonal.\n *\n * @param translationX The x-component of the translation vector\n * @param translationY The y-component of the translation vector\n * @param translationZ The z-component of the translation vector\n * @param scalingX The x-component of the scaling vector\n * @param scalingY The x-component of the scaling vector\n * @param scalingZ The x-component of the scaling vector\n *\n * @return This matrix for the purpose of chaining methods together.\n */\n public Matrix4d setToTranslationAndScaling(double translationX, double translationY, double translationZ, double scalingX, double scalingY, double scalingZ) {\n idt();\n val[M03] = translationX;\n val[M13] = translationY;\n val[M23] = translationZ;\n val[M00] = scalingX;\n val[M11] = scalingY;\n val[M22] = scalingZ;\n return this;\n }\n\n static Quaterniond quat = new Quaterniond();\n\n /**\n * Sets the matrix to a rotation matrix around the given axis.\n *\n * @param axis The axis\n * @param degrees The angle in degrees\n *\n * @return This matrix for the purpose of chaining methods together.\n */\n public Matrix4d setToRotation(Vector3d axis, double degrees) {\n if (degrees == 0) {\n idt();\n return this;\n }\n return set(quat.set(axis, degrees));\n }\n\n /**\n * Sets the matrix to a rotation matrix around the given axis.\n *\n * @param axis The axis\n * @param radians The angle in radians\n *\n * @return This matrix for the purpose of chaining methods together.\n */\n public Matrix4d setToRotationRad(Vector3d axis, double radians) {\n if (radians == 0) {\n idt();\n return this;\n }\n return set(quat.setFromAxisRad(axis, radians));\n }\n\n /**\n * Sets the matrix to a rotation matrix around the given axis.\n *\n * @param axisX The x-component of the axis\n * @param axisY The y-component of the axis\n * @param axisZ The z-component of the axis\n * @param degrees The angle in degrees\n *\n * @return This matrix for the purpose of chaining methods together.\n */\n public Matrix4d setToRotation(double axisX, double axisY, double axisZ, double degrees) {\n if (degrees == 0) {\n idt();\n return this;\n }\n return set(quat.setFromAxis(axisX, axisY, axisZ, degrees));\n }\n\n /**\n * Sets the matrix to a rotation matrix around the given axis.\n *\n * @param axisX The x-component of the axis\n * @param axisY The y-component of the axis\n * @param axisZ The z-component of the axis\n * @param radians The angle in radians\n *\n * @return This matrix for the purpose of chaining methods together.\n */\n public Matrix4d setToRotationRad(double axisX, double axisY, double axisZ, double radians) {\n if (radians == 0) {\n idt();\n return this;\n }\n return set(quat.setFromAxisRad(axisX, axisY, axisZ, radians));\n }\n\n /**\n * Set the matrix to a rotation matrix between two vectors.\n *\n * @param v1 The base vector\n * @param v2 The target vector\n *\n * @return This matrix for the purpose of chaining methods together\n */\n public Matrix4d setToRotation(final Vector3d v1, final Vector3d v2) {\n return set(quat.setFromCross(v1, v2));\n }\n\n /**\n * Set the matrix to a rotation matrix between two vectors.\n *\n * @param x1 The base vectors x value\n * @param y1 The base vectors y value\n * @param z1 The base vectors z value\n * @param x2 The target vector x value\n * @param y2 The target vector y value\n * @param z2 The target vector z value\n *\n * @return This matrix for the purpose of chaining methods together\n */\n public Matrix4d setToRotation(final double x1, final double y1, final double z1, final double x2, final double y2, final double z2) {\n return set(quat.setFromCross(x1, y1, z1, x2, y2, z2));\n }\n\n /**\n * Sets this matrix to a rotation matrix from the given euler angles.\n *\n * @param yaw the yaw in degrees\n * @param pitch the pitch in degrees\n * @param roll the roll in degrees\n *\n * @return This matrix\n */\n public Matrix4d setFromEulerAngles(double yaw, double pitch, double roll) {\n quat.setEulerAngles(yaw, pitch, roll);\n return set(quat);\n }\n\n /**\n * Sets this matrix to a scaling matrix\n *\n * @param vector The scaling vector\n *\n * @return This matrix for chaining.\n */\n public Matrix4d setToScaling(Vector3d vector) {\n idt();\n val[M00] = vector.x;\n val[M11] = vector.y;\n val[M22] = vector.z;\n return this;\n }\n\n /**\n * Sets this matrix to a scaling matrix\n *\n * @param x The x-component of the scaling vector\n * @param y The y-component of the scaling vector\n * @param z The z-component of the scaling vector\n *\n * @return This matrix for chaining.\n */\n public Matrix4d setToScaling(double x, double y, double z) {\n idt();\n val[M00] = x;\n val[M11] = y;\n val[M22] = z;\n return this;\n }\n\n static final Vector3d l_vez = new Vector3d();\n static final Vector3d l_vex = new Vector3d();\n static final Vector3d l_vey = new Vector3d();\n static final Vector3b l_vezb = new Vector3b();\n static final Vector3b l_vexb = new Vector3b();\n static final Vector3b l_veyb = new Vector3b();\n\n /**\n * Sets the matrix to a look at matrix with a direction and an up vector.\n * Multiply with a translation matrix to get a camera model view matrix.\n *\n * @param direction The direction vector\n * @param up The up vector\n *\n * @return This matrix for the purpose of chaining methods together.\n */\n public Matrix4d setToLookAt(Vector3d direction, Vector3d up) {\n l_vez.set(direction).nor();\n l_vex.set(direction).nor();\n l_vex.crs(up).nor();\n l_vey.set(l_vex).crs(l_vez).nor();\n idt();\n val[M00] = l_vex.x;\n val[M01] = l_vex.y;\n val[M02] = l_vex.z;\n val[M10] = l_vey.x;\n val[M11] = l_vey.y;\n val[M12] = l_vey.z;\n val[M20] = -l_vez.x;\n val[M21] = -l_vez.y;\n val[M22] = -l_vez.z;\n\n return this;\n }\n\n public Matrix4d setToLookAt(Vector3b direction, Vector3b up) {\n l_vezb.set(direction).nor();\n l_vexb.set(direction).nor();\n l_vexb.crs(up).nor();\n l_veyb.set(l_vexb).crs(l_vezb).nor();\n idt();\n val[M00] = l_vexb.x.doubleValue();\n val[M01] = l_vexb.y.doubleValue();\n val[M02] = l_vexb.z.doubleValue();\n val[M10] = l_veyb.x.doubleValue();\n val[M11] = l_veyb.y.doubleValue();\n val[M12] = l_veyb.z.doubleValue();\n val[M20] = -l_vezb.x.doubleValue();\n val[M21] = -l_vezb.y.doubleValue();\n val[M22] = -l_vezb.z.doubleValue();\n\n return this;\n }\n\n static final Vector3d tmpVec = new Vector3d();\n static final Vector3b tmpVecb = new Vector3b();\n static final Matrix4d tmpMat = new Matrix4d();\n\n /**\n * Sets this matrix to a look at matrix with the given position, target and\n * up vector.\n *\n * @param position the position\n * @param target the target\n * @param up the up vector\n *\n * @return This matrix\n */\n public Matrix4d setToLookAt(Vector3d position, Vector3d target, Vector3d up) {\n tmpVec.set(target).sub(position);\n setToLookAt(tmpVec, up);\n this.mul(tmpMat.setToTranslation(-position.x, -position.y, -position.z));\n\n return this;\n }\n\n public Matrix4d setToLookAt(Vector3b position, Vector3b target, Vector3b up) {\n tmpVecb.set(target).sub(position);\n setToLookAt(tmpVecb, up);\n this.mul(tmpMat.setToTranslation(-position.x.doubleValue(), -position.y.doubleValue(), -position.z.doubleValue()));\n\n return this;\n }\n\n static final Vector3d right = new Vector3d();\n static final Vector3d tmpForward = new Vector3d();\n static final Vector3d tmpUp = new Vector3d();\n\n public Matrix4d setToWorld(Vector3d position, Vector3d forward, Vector3d up) {\n tmpForward.set(forward).nor();\n right.set(tmpForward).crs(up).nor();\n tmpUp.set(right).crs(tmpForward).nor();\n\n this.set(right, tmpUp, tmpForward, position);\n return this;\n }\n\n public String toString() {\n return \"[\" + val[M00] + \"|\" + val[M01] + \"|\" + val[M02] + \"|\" + val[M03] + \"]\\n\" + \"[\" + val[M10] + \"|\" + val[M11] + \"|\" + val[M12] + \"|\" + val[M13] + \"]\\n\" + \"[\" + val[M20] + \"|\" + val[M21] + \"|\" + val[M22] + \"|\" + val[M23] + \"]\\n\" + \"[\" + val[M30] + \"|\" + val[M31] + \"|\" + val[M32] + \"|\" + val[M33] + \"]\\n\";\n }\n\n /**\n * Linearly interpolates between this matrix and the given matrix mixing by\n * alpha\n *\n * @param matrix the matrix\n * @param alpha the alpha value in the range [0,1]\n *\n * @return This matrix for the purpose of chaining methods together.\n */\n public Matrix4d lerp(Matrix4d matrix, double alpha) {\n for (int i = 0; i < 16; i++)\n this.val[i] = this.val[i] * (1 - alpha) + matrix.val[i] * alpha;\n return this;\n }\n\n /**\n * Sets this matrix to the given 3x3 matrix. The third column of this matrix\n * is set to (0,0,1,0).\n *\n * @param mat the matrix\n */\n public Matrix4d set(Matrix3 mat) {\n val[0] = mat.val[0];\n val[1] = mat.val[1];\n val[2] = mat.val[2];\n val[3] = 0;\n val[4] = mat.val[3];\n val[5] = mat.val[4];\n val[6] = mat.val[5];\n val[7] = 0;\n val[8] = 0;\n val[9] = 0;\n val[10] = 1;\n val[11] = 0;\n val[12] = mat.val[6];\n val[13] = mat.val[7];\n val[14] = 0;\n val[15] = mat.val[8];\n return this;\n }\n\n public Matrix4d scl(Vector3d scale) {\n val[M00] *= scale.x;\n val[M11] *= scale.y;\n val[M22] *= scale.z;\n return this;\n }\n\n public Matrix4d scl(double x, double y, double z) {\n val[M00] *= x;\n val[M11] *= y;\n val[M22] *= z;\n return this;\n }\n\n public Matrix4d scl(double scale) {\n val[M00] *= scale;\n val[M11] *= scale;\n val[M22] *= scale;\n return this;\n }\n\n public Vector3d getTranslation(Vector3d position) {\n position.x = val[M03];\n position.y = val[M13];\n position.z = val[M23];\n return position;\n }\n\n public Vector3 getTranslationf(Vector3 position) {\n position.x = (float) val[M03];\n position.y = (float) val[M13];\n position.z = (float) val[M23];\n return position;\n }\n\n public double[] getTranslation() {\n return new double[] { val[M03], val[M13], val[M23] };\n }\n\n public float[] getTranslationf() {\n return new float[] { (float) val[M03], (float) val[M13], (float) val[M23] };\n }\n\n public void getTranslationf(float[] vec) {\n vec[0] = (float) val[M03];\n vec[1] = (float) val[M13];\n vec[2] = (float) val[M23];\n }\n\n public Vector3d addTranslationTo(Vector3d position) {\n position.x += val[M03];\n position.y += val[M13];\n position.z += val[M23];\n return position;\n }\n\n /** @return the squared scale factor on the X axis */\n public double getScaleXSquared() {\n return val[Matrix4d.M00] * val[Matrix4d.M00] + val[Matrix4d.M01] * val[Matrix4d.M01] + val[Matrix4d.M02] * val[Matrix4d.M02];\n }\n\n /** @return the squared scale factor on the Y axis */\n public double getScaleYSquared() {\n return val[Matrix4d.M10] * val[Matrix4d.M10] + val[Matrix4d.M11] * val[Matrix4d.M11] + val[Matrix4d.M12] * val[Matrix4d.M12];\n }\n\n /** @return the squared scale factor on the Z axis */\n public double getScaleZSquared() {\n return val[Matrix4d.M20] * val[Matrix4d.M20] + val[Matrix4d.M21] * val[Matrix4d.M21] + val[Matrix4d.M22] * val[Matrix4d.M22];\n }\n\n /** @return the scale factor on the X axis (non-negative) */\n public double getScaleX() {\n return (MathUtilsd.isZero(val[Matrix4d.M01]) && MathUtilsd.isZero(val[Matrix4d.M02])) ? val[Matrix4d.M00] : Math.sqrt(getScaleXSquared());\n }\n\n /** @return the scale factor on the Y axis (non-negative) */\n public double getScaleY() {\n return (MathUtilsd.isZero(val[Matrix4d.M10]) && MathUtilsd.isZero(val[Matrix4d.M12])) ? val[Matrix4d.M11] : Math.sqrt(getScaleYSquared());\n }\n\n /** @return the scale factor on the X axis (non-negative) */\n public double getScaleZ() {\n return (MathUtilsd.isZero(val[Matrix4d.M20]) && MathUtilsd.isZero(val[Matrix4d.M21])) ? val[Matrix4d.M22] : Math.sqrt(getScaleZSquared());\n }\n\n public Vector3d getScale(Vector3d scale) {\n return scale.set(getScaleX(), getScaleY(), getScaleZ());\n }\n\n /** removes the translational part and transposes the matrix. */\n public Matrix4d toNormalMatrix() {\n val[M03] = 0;\n val[M13] = 0;\n val[M23] = 0;\n return inv().tra();\n }\n\n /**\n * Multiplies the vector with the given matrix, performing a division by w.\n * The matrix array is assumed to hold a 4x4 column major matrix as you can\n * get from {@link Matrix4d#val}. The vector array is assumed to hold a\n * 3-component vector, with x being the first element, y being the second\n * and z being the last component. The result is stored in the vector array.\n * This is the same as {@link Vector3d#prj(Matrix4d)}.\n *\n * @param mat the matrix\n * @param vec the vector.\n */\n public static void prj(double[] mat, double[] vec) {\n matrix4_proj(mat, vec, 0);\n }\n\n /**\n * Multiplies the vectors with the given matrix, , performing a division by\n * w. The matrix array is assumed to hold a 4x4 column major matrix as you\n * can get from {@link Matrix4#val}. The vectors array is assumed to hold\n * 3-component vectors. Offset specifies the offset into the array where the\n * x-component of the first vector is located. The numVecs parameter\n * specifies the number of vectors stored in the vectors array. The stride\n * parameter specifies the number of floats between subsequent vectors and\n * must be >= 3. This is the same as {@link Vector3#prj(Matrix4)} applied to\n * multiple vectors.\n *\n * @param mat the matrix\n * @param vecs the vectors\n * @param offset the offset into the vectors array\n * @param numVecs the number of vectors\n * @param stride the stride between vectors in floats\n */\n public static void prj(double[] mat, double[] vecs, int offset, int numVecs, int stride) {\n for (int i = 0; i < numVecs; i++) {\n matrix4_proj(mat, vecs, offset);\n offset += stride;\n }\n }\n\n static void matrix4_mul(double[] mata, double[] matb) {\n stmp[M00] = mata[M00] * matb[M00] + mata[M01] * matb[M10] + mata[M02] * matb[M20] + mata[M03] * matb[M30];\n stmp[M01] = mata[M00] * matb[M01] + mata[M01] * matb[M11] + mata[M02] * matb[M21] + mata[M03] * matb[M31];\n stmp[M02] = mata[M00] * matb[M02] + mata[M01] * matb[M12] + mata[M02] * matb[M22] + mata[M03] * matb[M32];\n stmp[M03] = mata[M00] * matb[M03] + mata[M01] * matb[M13] + mata[M02] * matb[M23] + mata[M03] * matb[M33];\n stmp[M10] = mata[M10] * matb[M00] + mata[M11] * matb[M10] + mata[M12] * matb[M20] + mata[M13] * matb[M30];\n stmp[M11] = mata[M10] * matb[M01] + mata[M11] * matb[M11] + mata[M12] * matb[M21] + mata[M13] * matb[M31];\n stmp[M12] = mata[M10] * matb[M02] + mata[M11] * matb[M12] + mata[M12] * matb[M22] + mata[M13] * matb[M32];\n stmp[M13] = mata[M10] * matb[M03] + mata[M11] * matb[M13] + mata[M12] * matb[M23] + mata[M13] * matb[M33];\n stmp[M20] = mata[M20] * matb[M00] + mata[M21] * matb[M10] + mata[M22] * matb[M20] + mata[M23] * matb[M30];\n stmp[M21] = mata[M20] * matb[M01] + mata[M21] * matb[M11] + mata[M22] * matb[M21] + mata[M23] * matb[M31];\n stmp[M22] = mata[M20] * matb[M02] + mata[M21] * matb[M12] + mata[M22] * matb[M22] + mata[M23] * matb[M32];\n stmp[M23] = mata[M20] * matb[M03] + mata[M21] * matb[M13] + mata[M22] * matb[M23] + mata[M23] * matb[M33];\n stmp[M30] = mata[M30] * matb[M00] + mata[M31] * matb[M10] + mata[M32] * matb[M20] + mata[M33] * matb[M30];\n stmp[M31] = mata[M30] * matb[M01] + mata[M31] * matb[M11] + mata[M32] * matb[M21] + mata[M33] * matb[M31];\n stmp[M32] = mata[M30] * matb[M02] + mata[M31] * matb[M12] + mata[M32] * matb[M22] + mata[M33] * matb[M32];\n stmp[M33] = mata[M30] * matb[M03] + mata[M31] * matb[M13] + mata[M32] * matb[M23] + mata[M33] * matb[M33];\n System.arraycopy(stmp, 0, mata, 0, 16);\n }\n\n static double matrix4_det(double[] val) {\n return val[M30] * val[M21] * val[M12] * val[M03] - val[M20] * val[M31] * val[M12] * val[M03] - val[M30] * val[M11] * val[M22] * val[M03] + val[M10] * val[M31] * val[M22] * val[M03] + val[M20] * val[M11] * val[M32] * val[M03] - val[M10] * val[M21] * val[M32] * val[M03] - val[M30] * val[M21] * val[M02] * val[M13] + val[M20] * val[M31] * val[M02] * val[M13] + val[M30] * val[M01] * val[M22] * val[M13] - val[M00] * val[M31] * val[M22] * val[M13] - val[M20] * val[M01] * val[M32] * val[M13]\n + val[M00] * val[M21] * val[M32] * val[M13] + val[M30] * val[M11] * val[M02] * val[M23] - val[M10] * val[M31] * val[M02] * val[M23] - val[M30] * val[M01] * val[M12] * val[M23] + val[M00] * val[M31] * val[M12] * val[M23] + val[M10] * val[M01] * val[M32] * val[M23] - val[M00] * val[M11] * val[M32] * val[M23] - val[M20] * val[M11] * val[M02] * val[M33] + val[M10] * val[M21] * val[M02] * val[M33] + val[M20] * val[M01] * val[M12] * val[M33] - val[M00] * val[M21] * val[M12] * val[M33]\n - val[M10] * val[M01] * val[M22] * val[M33] + val[M00] * val[M11] * val[M22] * val[M33];\n }\n\n static boolean matrix4_inv(double[] val) {\n double[] tmp = new double[16];\n double l_det = matrix4_det(val);\n if (l_det == 0)\n return false;\n stmp[M00] = val[M12] * val[M23] * val[M31] - val[M13] * val[M22] * val[M31] + val[M13] * val[M21] * val[M32] - val[M11] * val[M23] * val[M32] - val[M12] * val[M21] * val[M33] + val[M11] * val[M22] * val[M33];\n stmp[M01] = val[M03] * val[M22] * val[M31] - val[M02] * val[M23] * val[M31] - val[M03] * val[M21] * val[M32] + val[M01] * val[M23] * val[M32] + val[M02] * val[M21] * val[M33] - val[M01] * val[M22] * val[M33];\n stmp[M02] = val[M02] * val[M13] * val[M31] - val[M03] * val[M12] * val[M31] + val[M03] * val[M11] * val[M32] - val[M01] * val[M13] * val[M32] - val[M02] * val[M11] * val[M33] + val[M01] * val[M12] * val[M33];\n stmp[M03] = val[M03] * val[M12] * val[M21] - val[M02] * val[M13] * val[M21] - val[M03] * val[M11] * val[M22] + val[M01] * val[M13] * val[M22] + val[M02] * val[M11] * val[M23] - val[M01] * val[M12] * val[M23];\n stmp[M10] = val[M13] * val[M22] * val[M30] - val[M12] * val[M23] * val[M30] - val[M13] * val[M20] * val[M32] + val[M10] * val[M23] * val[M32] + val[M12] * val[M20] * val[M33] - val[M10] * val[M22] * val[M33];\n stmp[M11] = val[M02] * val[M23] * val[M30] - val[M03] * val[M22] * val[M30] + val[M03] * val[M20] * val[M32] - val[M00] * val[M23] * val[M32] - val[M02] * val[M20] * val[M33] + val[M00] * val[M22] * val[M33];\n stmp[M12] = val[M03] * val[M12] * val[M30] - val[M02] * val[M13] * val[M30] - val[M03] * val[M10] * val[M32] + val[M00] * val[M13] * val[M32] + val[M02] * val[M10] * val[M33] - val[M00] * val[M12] * val[M33];\n stmp[M13] = val[M02] * val[M13] * val[M20] - val[M03] * val[M12] * val[M20] + val[M03] * val[M10] * val[M22] - val[M00] * val[M13] * val[M22] - val[M02] * val[M10] * val[M23] + val[M00] * val[M12] * val[M23];\n stmp[M20] = val[M11] * val[M23] * val[M30] - val[M13] * val[M21] * val[M30] + val[M13] * val[M20] * val[M31] - val[M10] * val[M23] * val[M31] - val[M11] * val[M20] * val[M33] + val[M10] * val[M21] * val[M33];\n stmp[M21] = val[M03] * val[M21] * val[M30] - val[M01] * val[M23] * val[M30] - val[M03] * val[M20] * val[M31] + val[M00] * val[M23] * val[M31] + val[M01] * val[M20] * val[M33] - val[M00] * val[M21] * val[M33];\n stmp[M22] = val[M01] * val[M13] * val[M30] - val[M03] * val[M11] * val[M30] + val[M03] * val[M10] * val[M31] - val[M00] * val[M13] * val[M31] - val[M01] * val[M10] * val[M33] + val[M00] * val[M11] * val[M33];\n stmp[M23] = val[M03] * val[M11] * val[M20] - val[M01] * val[M13] * val[M20] - val[M03] * val[M10] * val[M21] + val[M00] * val[M13] * val[M21] + val[M01] * val[M10] * val[M23] - val[M00] * val[M11] * val[M23];\n stmp[M30] = val[M12] * val[M21] * val[M30] - val[M11] * val[M22] * val[M30] - val[M12] * val[M20] * val[M31] + val[M10] * val[M22] * val[M31] + val[M11] * val[M20] * val[M32] - val[M10] * val[M21] * val[M32];\n stmp[M31] = val[M01] * val[M22] * val[M30] - val[M02] * val[M21] * val[M30] + val[M02] * val[M20] * val[M31] - val[M00] * val[M22] * val[M31] - val[M01] * val[M20] * val[M32] + val[M00] * val[M21] * val[M32];\n stmp[M32] = val[M02] * val[M11] * val[M30] - val[M01] * val[M12] * val[M30] - val[M02] * val[M10] * val[M31] + val[M00] * val[M12] * val[M31] + val[M01] * val[M10] * val[M32] - val[M00] * val[M11] * val[M32];\n stmp[M33] = val[M01] * val[M12] * val[M20] - val[M02] * val[M11] * val[M20] + val[M02] * val[M10] * val[M21] - val[M00] * val[M12] * val[M21] - val[M01] * val[M10] * val[M22] + val[M00] * val[M11] * val[M22];\n\n double inv_det = 1.0 / l_det;\n val[M00] = stmp[M00] * inv_det;\n val[M01] = stmp[M01] * inv_det;\n val[M02] = stmp[M02] * inv_det;\n val[M03] = stmp[M03] * inv_det;\n val[M10] = stmp[M10] * inv_det;\n val[M11] = stmp[M11] * inv_det;\n val[M12] = stmp[M12] * inv_det;\n val[M13] = stmp[M13] * inv_det;\n val[M20] = stmp[M20] * inv_det;\n val[M21] = stmp[M21] * inv_det;\n val[M22] = stmp[M22] * inv_det;\n val[M23] = stmp[M23] * inv_det;\n val[M30] = stmp[M30] * inv_det;\n val[M31] = stmp[M31] * inv_det;\n val[M32] = stmp[M32] * inv_det;\n val[M33] = stmp[M33] * inv_det;\n return true;\n }\n\n static void matrix4_mulVec(double[] mat, double[] vec, int offset) {\n double x = vec[offset + 0] * mat[M00] + vec[offset + 1] * mat[M01] + vec[offset + 2] * mat[M02] + mat[M03];\n double y = vec[offset + 0] * mat[M10] + vec[offset + 1] * mat[M11] + vec[offset + 2] * mat[M12] + mat[M13];\n double z = vec[offset + 0] * mat[M20] + vec[offset + 1] * mat[M21] + vec[offset + 2] * mat[M22] + mat[M23];\n vec[offset + 0] = x;\n vec[offset + 1] = y;\n vec[offset + 2] = z;\n }\n", "answers": [" static void matrix4_proj(double[] mat, double[] vec, int offset) {"], "length": 7318, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "ae5735d7-ff75-4689-b021-2d022600076c", "reasoning": "The code ends with the definition of matrix4_mulVec. In the original library, the next utility method defined after this is the projection helper matrix4_proj, which takes a matrix, a vector array, and an offset. Therefore the next line is the method signature for matrix4_proj.", "reasoning_model_answer": "static void matrix4_proj(double[] mat, double[] vec, int offset) {", "assistant_with_reasoning": "\nThe code ends with the definition of matrix4_mulVec. In the original library, the next utility method defined after this is the projection helper matrix4_proj, which takes a matrix, a vector array, and an offset. Therefore the next line is the method signature for matrix4_proj.\n\nstatic void matrix4_proj(double[] mat, double[] vec, int offset) {", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 5.138, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 48004, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "static void matrix4_proj(double[] mat, double[] vec, int offset) {", "score": 0.97, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/*\n * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * This code is free software; you can redistribute it and/or modify it\n * under the terms of the GNU General Public License version 2 only, as\n * published by the Free Software Foundation. Oracle designates this\n * particular file as subject to the \"Classpath\" exception as provided\n * by Oracle in the LICENSE file that accompanied this code.\n *\n * This code is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License\n * version 2 for more details (a copy is included in the LICENSE file that\n * accompanied this code).\n *\n * You should have received a copy of the GNU General Public License version\n * 2 along with this work; if not, write to the Free Software Foundation,\n * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.\n *\n * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA\n * or visit www.oracle.com if you need additional information or have any\n * questions.\n */\n\npackage java.util;\nimport java.io.Serializable;\nimport java.io.ObjectOutputStream;\nimport java.io.IOException;\nimport java.lang.reflect.Array;\n\n/**\n * This class consists exclusively of static methods that operate on or return\n * collections. It contains polymorphic algorithms that operate on\n * collections, \"wrappers\", which return a new collection backed by a\n * specified collection, and a few other odds and ends.\n *\n *

The methods of this class all throw a NullPointerException\n * if the collections or class objects provided to them are null.\n *\n *

The documentation for the polymorphic algorithms contained in this class\n * generally includes a brief description of the implementation. Such\n * descriptions should be regarded as implementation notes, rather than\n * parts of the specification. Implementors should feel free to\n * substitute other algorithms, so long as the specification itself is adhered\n * to. (For example, the algorithm used by sort does not have to be\n * a mergesort, but it does have to be stable.)\n *\n *

The \"destructive\" algorithms contained in this class, that is, the\n * algorithms that modify the collection on which they operate, are specified\n * to throw UnsupportedOperationException if the collection does not\n * support the appropriate mutation primitive(s), such as the set\n * method. These algorithms may, but are not required to, throw this\n * exception if an invocation would have no effect on the collection. For\n * example, invoking the sort method on an unmodifiable list that is\n * already sorted may or may not throw UnsupportedOperationException.\n *\n *

This class is a member of the\n * \n * Java Collections Framework.\n *\n * @author Josh Bloch\n * @author Neal Gafter\n * @see Collection\n * @see Set\n * @see List\n * @see Map\n * @since 1.2\n */\n\npublic class Collections {\n // Suppresses default constructor, ensuring non-instantiability.\n private Collections() {\n }\n\n // Algorithms\n\n /*\n * Tuning parameters for algorithms - Many of the List algorithms have\n * two implementations, one of which is appropriate for RandomAccess\n * lists, the other for \"sequential.\" Often, the random access variant\n * yields better performance on small sequential access lists. The\n * tuning parameters below determine the cutoff point for what constitutes\n * a \"small\" sequential access list for each algorithm. The values below\n * were empirically determined to work well for LinkedList. Hopefully\n * they should be reasonable for other sequential access List\n * implementations. Those doing performance work on this code would\n * do well to validate the values of these parameters from time to time.\n * (The first word of each tuning parameter name is the algorithm to which\n * it applies.)\n */\n private static final int BINARYSEARCH_THRESHOLD = 5000;\n private static final int REVERSE_THRESHOLD = 18;\n private static final int SHUFFLE_THRESHOLD = 5;\n private static final int FILL_THRESHOLD = 25;\n private static final int ROTATE_THRESHOLD = 100;\n private static final int COPY_THRESHOLD = 10;\n private static final int REPLACEALL_THRESHOLD = 11;\n private static final int INDEXOFSUBLIST_THRESHOLD = 35;\n\n /**\n * Sorts the specified list into ascending order, according to the\n * {@linkplain Comparable natural ordering} of its elements.\n * All elements in the list must implement the {@link Comparable}\n * interface. Furthermore, all elements in the list must be\n * mutually comparable (that is, {@code e1.compareTo(e2)}\n * must not throw a {@code ClassCastException} for any elements\n * {@code e1} and {@code e2} in the list).\n *\n *

This sort is guaranteed to be stable: equal elements will\n * not be reordered as a result of the sort.\n *\n *

The specified list must be modifiable, but need not be resizable.\n *\n *

Implementation note: This implementation is a stable, adaptive,\n * iterative mergesort that requires far fewer than n lg(n) comparisons\n * when the input array is partially sorted, while offering the\n * performance of a traditional mergesort when the input array is\n * randomly ordered. If the input array is nearly sorted, the\n * implementation requires approximately n comparisons. Temporary\n * storage requirements vary from a small constant for nearly sorted\n * input arrays to n/2 object references for randomly ordered input\n * arrays.\n *\n *

The implementation takes equal advantage of ascending and\n * descending order in its input array, and can take advantage of\n * ascending and descending order in different parts of the same\n * input array. It is well-suited to merging two or more sorted arrays:\n * simply concatenate the arrays and sort the resulting array.\n *\n *

The implementation was adapted from Tim Peters's list sort for Python\n * (\n * TimSort). It uses techiques from Peter McIlroy's \"Optimistic\n * Sorting and Information Theoretic Complexity\", in Proceedings of the\n * Fourth Annual ACM-SIAM Symposium on Discrete Algorithms, pp 467-474,\n * January 1993.\n *\n *

This implementation dumps the specified list into an array, sorts\n * the array, and iterates over the list resetting each element\n * from the corresponding position in the array. This avoids the\n * n2 log(n) performance that would result from attempting\n * to sort a linked list in place.\n *\n * @param list the list to be sorted.\n * @throws ClassCastException if the list contains elements that are not\n * mutually comparable (for example, strings and integers).\n * @throws UnsupportedOperationException if the specified list's\n * list-iterator does not support the {@code set} operation.\n * @throws IllegalArgumentException (optional) if the implementation\n * detects that the natural ordering of the list elements is\n * found to violate the {@link Comparable} contract\n */\n public static > void sort(List list) {\n Object[] a = list.toArray();\n Arrays.sort(a);\n ListIterator i = list.listIterator();\n for (int j=0; jmutually\n * comparable using the specified comparator (that is,\n * {@code c.compare(e1, e2)} must not throw a {@code ClassCastException}\n * for any elements {@code e1} and {@code e2} in the list).\n *\n *

This sort is guaranteed to be stable: equal elements will\n * not be reordered as a result of the sort.\n *\n *

The specified list must be modifiable, but need not be resizable.\n *\n *

Implementation note: This implementation is a stable, adaptive,\n * iterative mergesort that requires far fewer than n lg(n) comparisons\n * when the input array is partially sorted, while offering the\n * performance of a traditional mergesort when the input array is\n * randomly ordered. If the input array is nearly sorted, the\n * implementation requires approximately n comparisons. Temporary\n * storage requirements vary from a small constant for nearly sorted\n * input arrays to n/2 object references for randomly ordered input\n * arrays.\n *\n *

The implementation takes equal advantage of ascending and\n * descending order in its input array, and can take advantage of\n * ascending and descending order in different parts of the same\n * input array. It is well-suited to merging two or more sorted arrays:\n * simply concatenate the arrays and sort the resulting array.\n *\n *

The implementation was adapted from Tim Peters's list sort for Python\n * (\n * TimSort). It uses techiques from Peter McIlroy's \"Optimistic\n * Sorting and Information Theoretic Complexity\", in Proceedings of the\n * Fourth Annual ACM-SIAM Symposium on Discrete Algorithms, pp 467-474,\n * January 1993.\n *\n *

This implementation dumps the specified list into an array, sorts\n * the array, and iterates over the list resetting each element\n * from the corresponding position in the array. This avoids the\n * n2 log(n) performance that would result from attempting\n * to sort a linked list in place.\n *\n * @param list the list to be sorted.\n * @param c the comparator to determine the order of the list. A\n * {@code null} value indicates that the elements' natural\n * ordering should be used.\n * @throws ClassCastException if the list contains elements that are not\n * mutually comparable using the specified comparator.\n * @throws UnsupportedOperationException if the specified list's\n * list-iterator does not support the {@code set} operation.\n * @throws IllegalArgumentException (optional) if the comparator is\n * found to violate the {@link Comparator} contract\n */\n public static void sort(List list, Comparator c) {\n Object[] a = list.toArray();\n Arrays.sort(a, (Comparator)c);\n ListIterator i = list.listIterator();\n for (int j=0; jThis method runs in log(n) time for a \"random access\" list (which\n * provides near-constant-time positional access). If the specified list\n * does not implement the {@link RandomAccess} interface and is large,\n * this method will do an iterator-based binary search that performs\n * O(n) link traversals and O(log n) element comparisons.\n *\n * @param list the list to be searched.\n * @param key the key to be searched for.\n * @return the index of the search key, if it is contained in the list;\n * otherwise, (-(insertion point) - 1). The\n * insertion point is defined as the point at which the\n * key would be inserted into the list: the index of the first\n * element greater than the key, or list.size() if all\n * elements in the list are less than the specified key. Note\n * that this guarantees that the return value will be >= 0 if\n * and only if the key is found.\n * @throws ClassCastException if the list contains elements that are not\n * mutually comparable (for example, strings and\n * integers), or the search key is not mutually comparable\n * with the elements of the list.\n */\n public static \n int binarySearch(List> list, T key) {\n if (list instanceof RandomAccess || list.size()\n int indexedBinarySearch(List> list, T key)\n {\n int low = 0;\n int high = list.size()-1;\n\n while (low <= high) {\n int mid = (low + high) >>> 1;\n Comparable midVal = list.get(mid);\n int cmp = midVal.compareTo(key);\n\n if (cmp < 0)\n low = mid + 1;\n else if (cmp > 0)\n high = mid - 1;\n else\n return mid; // key found\n }\n return -(low + 1); // key not found\n }\n\n private static \n int iteratorBinarySearch(List> list, T key)\n {\n int low = 0;\n int high = list.size()-1;\n ListIterator> i = list.listIterator();\n\n while (low <= high) {\n int mid = (low + high) >>> 1;\n Comparable midVal = get(i, mid);\n int cmp = midVal.compareTo(key);\n\n if (cmp < 0)\n low = mid + 1;\n else if (cmp > 0)\n high = mid - 1;\n else\n return mid; // key found\n }\n return -(low + 1); // key not found\n }\n\n /**\n * Gets the ith element from the given list by repositioning the specified\n * list listIterator.\n */\n private static T get(ListIterator i, int index) {\n T obj = null;\n int pos = i.nextIndex();\n if (pos <= index) {\n do {\n obj = i.next();\n } while (pos++ < index);\n } else {\n do {\n obj = i.previous();\n } while (--pos > index);\n }\n return obj;\n }\n\n /**\n * Searches the specified list for the specified object using the binary\n * search algorithm. The list must be sorted into ascending order\n * according to the specified comparator (as by the\n * {@link #sort(List, Comparator) sort(List, Comparator)}\n * method), prior to making this call. If it is\n * not sorted, the results are undefined. If the list contains multiple\n * elements equal to the specified object, there is no guarantee which one\n * will be found.\n *\n *

This method runs in log(n) time for a \"random access\" list (which\n * provides near-constant-time positional access). If the specified list\n * does not implement the {@link RandomAccess} interface and is large,\n * this method will do an iterator-based binary search that performs\n * O(n) link traversals and O(log n) element comparisons.\n *\n * @param list the list to be searched.\n * @param key the key to be searched for.\n * @param c the comparator by which the list is ordered.\n * A null value indicates that the elements'\n * {@linkplain Comparable natural ordering} should be used.\n * @return the index of the search key, if it is contained in the list;\n * otherwise, (-(insertion point) - 1). The\n * insertion point is defined as the point at which the\n * key would be inserted into the list: the index of the first\n * element greater than the key, or list.size() if all\n * elements in the list are less than the specified key. Note\n * that this guarantees that the return value will be >= 0 if\n * and only if the key is found.\n * @throws ClassCastException if the list contains elements that are not\n * mutually comparable using the specified comparator,\n * or the search key is not mutually comparable with the\n * elements of the list using this comparator.\n */\n public static int binarySearch(List list, T key, Comparator c) {\n if (c==null)\n return binarySearch((List) list, key);\n\n if (list instanceof RandomAccess || list.size() int indexedBinarySearch(List l, T key, Comparator c) {\n int low = 0;\n int high = l.size()-1;\n\n while (low <= high) {\n int mid = (low + high) >>> 1;\n T midVal = l.get(mid);\n int cmp = c.compare(midVal, key);\n\n if (cmp < 0)\n low = mid + 1;\n else if (cmp > 0)\n high = mid - 1;\n else\n return mid; // key found\n }\n return -(low + 1); // key not found\n }\n\n private static int iteratorBinarySearch(List l, T key, Comparator c) {\n int low = 0;\n int high = l.size()-1;\n ListIterator i = l.listIterator();\n\n while (low <= high) {\n int mid = (low + high) >>> 1;\n T midVal = get(i, mid);\n int cmp = c.compare(midVal, key);\n\n if (cmp < 0)\n low = mid + 1;\n else if (cmp > 0)\n high = mid - 1;\n else\n return mid; // key found\n }\n return -(low + 1); // key not found\n }\n\n private interface SelfComparable extends Comparable {}\n\n\n /**\n * Reverses the order of the elements in the specified list.

\n *\n * This method runs in linear time.\n *\n * @param list the list whose elements are to be reversed.\n * @throws UnsupportedOperationException if the specified list or\n * its list-iterator does not support the set operation.\n */\n public static void reverse(List list) {\n int size = list.size();\n if (size < REVERSE_THRESHOLD || list instanceof RandomAccess) {\n for (int i=0, mid=size>>1, j=size-1; i>1; i\n *\n * The hedge \"approximately\" is used in the foregoing description because\n * default source of randomness is only approximately an unbiased source\n * of independently chosen bits. If it were a perfect source of randomly\n * chosen bits, then the algorithm would choose permutations with perfect\n * uniformity.

\n *\n * This implementation traverses the list backwards, from the last element\n * up to the second, repeatedly swapping a randomly selected element into\n * the \"current position\". Elements are randomly selected from the\n * portion of the list that runs from the first element to the current\n * position, inclusive.

\n *\n * This method runs in linear time. If the specified list does not\n * implement the {@link RandomAccess} interface and is large, this\n * implementation dumps the specified list into an array before shuffling\n * it, and dumps the shuffled array back into the list. This avoids the\n * quadratic behavior that would result from shuffling a \"sequential\n * access\" list in place.\n *\n * @param list the list to be shuffled.\n * @throws UnsupportedOperationException if the specified list or\n * its list-iterator does not support the set operation.\n */\n public static void shuffle(List list) {\n Random rnd = r;\n if (rnd == null)\n r = rnd = new Random();\n shuffle(list, rnd);\n }\n private static Random r;\n\n /**\n * Randomly permute the specified list using the specified source of\n * randomness. All permutations occur with equal likelihood\n * assuming that the source of randomness is fair.

\n *\n * This implementation traverses the list backwards, from the last element\n * up to the second, repeatedly swapping a randomly selected element into\n * the \"current position\". Elements are randomly selected from the\n * portion of the list that runs from the first element to the current\n * position, inclusive.

\n *\n * This method runs in linear time. If the specified list does not\n * implement the {@link RandomAccess} interface and is large, this\n * implementation dumps the specified list into an array before shuffling\n * it, and dumps the shuffled array back into the list. This avoids the\n * quadratic behavior that would result from shuffling a \"sequential\n * access\" list in place.\n *\n * @param list the list to be shuffled.\n * @param rnd the source of randomness to use to shuffle the list.\n * @throws UnsupportedOperationException if the specified list or its\n * list-iterator does not support the set operation.\n */\n public static void shuffle(List list, Random rnd) {\n int size = list.size();\n if (size < SHUFFLE_THRESHOLD || list instanceof RandomAccess) {\n for (int i=size; i>1; i--)\n swap(list, i-1, rnd.nextInt(i));\n } else {\n Object arr[] = list.toArray();\n\n // Shuffle array\n for (int i=size; i>1; i--)\n swap(arr, i-1, rnd.nextInt(i));\n\n // Dump array back into list\n ListIterator it = list.listIterator();\n for (int i=0; ii or j\n * is out of range (i < 0 || i >= list.size()\n * || j < 0 || j >= list.size()).\n * @since 1.4\n */\n public static void swap(List list, int i, int j) {\n final List l = list;\n l.set(i, l.set(j, l.get(i)));\n }\n\n /**\n * Swaps the two specified elements in the specified array.\n */\n private static void swap(Object[] arr, int i, int j) {\n Object tmp = arr[i];\n arr[i] = arr[j];\n arr[j] = tmp;\n }\n\n /**\n * Replaces all of the elements of the specified list with the specified\n * element.

\n *\n * This method runs in linear time.\n *\n * @param list the list to be filled with the specified element.\n * @param obj The element with which to fill the specified list.\n * @throws UnsupportedOperationException if the specified list or its\n * list-iterator does not support the set operation.\n */\n public static void fill(List list, T obj) {\n int size = list.size();\n\n if (size < FILL_THRESHOLD || list instanceof RandomAccess) {\n for (int i=0; i itr = list.listIterator();\n for (int i=0; i\n *\n * This method runs in linear time.\n *\n * @param dest The destination list.\n * @param src The source list.\n * @throws IndexOutOfBoundsException if the destination list is too small\n * to contain the entire source List.\n * @throws UnsupportedOperationException if the destination list's\n * list-iterator does not support the set operation.\n */\n public static void copy(List dest, List src) {\n int srcSize = src.size();\n if (srcSize > dest.size())\n throw new IndexOutOfBoundsException(\"Source does not fit in dest\");\n\n if (srcSize < COPY_THRESHOLD ||\n (src instanceof RandomAccess && dest instanceof RandomAccess)) {\n for (int i=0; i di=dest.listIterator();\n ListIterator si=src.listIterator();\n for (int i=0; inatural ordering of its elements. All elements in the\n * collection must implement the Comparable interface.\n * Furthermore, all elements in the collection must be mutually\n * comparable (that is, e1.compareTo(e2) must not throw a\n * ClassCastException for any elements e1 and\n * e2 in the collection).

\n *\n * This method iterates over the entire collection, hence it requires\n * time proportional to the size of the collection.\n *\n * @param coll the collection whose minimum element is to be determined.\n * @return the minimum element of the given collection, according\n * to the natural ordering of its elements.\n * @throws ClassCastException if the collection contains elements that are\n * not mutually comparable (for example, strings and\n * integers).\n * @throws NoSuchElementException if the collection is empty.\n * @see Comparable\n */\n public static > T min(Collection coll) {\n Iterator i = coll.iterator();\n T candidate = i.next();\n\n while (i.hasNext()) {\n T next = i.next();\n if (next.compareTo(candidate) < 0)\n candidate = next;\n }\n return candidate;\n }\n\n /**\n * Returns the minimum element of the given collection, according to the\n * order induced by the specified comparator. All elements in the\n * collection must be mutually comparable by the specified\n * comparator (that is, comp.compare(e1, e2) must not throw a\n * ClassCastException for any elements e1 and\n * e2 in the collection).

\n *\n * This method iterates over the entire collection, hence it requires\n * time proportional to the size of the collection.\n *\n * @param coll the collection whose minimum element is to be determined.\n * @param comp the comparator with which to determine the minimum element.\n * A null value indicates that the elements' natural\n * ordering should be used.\n * @return the minimum element of the given collection, according\n * to the specified comparator.\n * @throws ClassCastException if the collection contains elements that are\n * not mutually comparable using the specified comparator.\n * @throws NoSuchElementException if the collection is empty.\n * @see Comparable\n */\n public static T min(Collection coll, Comparator comp) {\n if (comp==null)\n return (T)min((Collection) (Collection) coll);\n\n Iterator i = coll.iterator();\n T candidate = i.next();\n\n while (i.hasNext()) {\n T next = i.next();\n if (comp.compare(next, candidate) < 0)\n candidate = next;\n }\n return candidate;\n }\n\n /**\n * Returns the maximum element of the given collection, according to the\n * natural ordering of its elements. All elements in the\n * collection must implement the Comparable interface.\n * Furthermore, all elements in the collection must be mutually\n * comparable (that is, e1.compareTo(e2) must not throw a\n * ClassCastException for any elements e1 and\n * e2 in the collection).

\n *\n * This method iterates over the entire collection, hence it requires\n * time proportional to the size of the collection.\n *\n * @param coll the collection whose maximum element is to be determined.\n * @return the maximum element of the given collection, according\n * to the natural ordering of its elements.\n * @throws ClassCastException if the collection contains elements that are\n * not mutually comparable (for example, strings and\n * integers).\n * @throws NoSuchElementException if the collection is empty.\n * @see Comparable\n */\n public static > T max(Collection coll) {\n Iterator i = coll.iterator();\n T candidate = i.next();\n\n while (i.hasNext()) {\n T next = i.next();\n if (next.compareTo(candidate) > 0)\n candidate = next;\n }\n return candidate;\n }\n\n /**\n * Returns the maximum element of the given collection, according to the\n * order induced by the specified comparator. All elements in the\n * collection must be mutually comparable by the specified\n * comparator (that is, comp.compare(e1, e2) must not throw a\n * ClassCastException for any elements e1 and\n * e2 in the collection).

\n *\n * This method iterates over the entire collection, hence it requires\n * time proportional to the size of the collection.\n *\n * @param coll the collection whose maximum element is to be determined.\n * @param comp the comparator with which to determine the maximum element.\n * A null value indicates that the elements' natural\n * ordering should be used.\n * @return the maximum element of the given collection, according\n * to the specified comparator.\n * @throws ClassCastException if the collection contains elements that are\n * not mutually comparable using the specified comparator.\n * @throws NoSuchElementException if the collection is empty.\n * @see Comparable\n */\n public static T max(Collection coll, Comparator comp) {\n if (comp==null)\n return (T)max((Collection) (Collection) coll);\n\n Iterator i = coll.iterator();\n T candidate = i.next();\n\n while (i.hasNext()) {\n T next = i.next();\n if (comp.compare(next, candidate) > 0)\n candidate = next;\n }\n return candidate;\n }\n\n /**\n * Rotates the elements in the specified list by the specified distance.\n * After calling this method, the element at index i will be\n * the element previously at index (i - distance) mod\n * list.size(), for all values of i between 0\n * and list.size()-1, inclusive. (This method has no effect on\n * the size of the list.)\n *\n *

For example, suppose list comprises [t, a, n, k, s].\n * After invoking Collections.rotate(list, 1) (or\n * Collections.rotate(list, -4)), list will comprise\n * [s, t, a, n, k].\n *\n *

Note that this method can usefully be applied to sublists to\n * move one or more elements within a list while preserving the\n * order of the remaining elements. For example, the following idiom\n * moves the element at index j forward to position\n * k (which must be greater than or equal to j):\n *

\n     *     Collections.rotate(list.subList(j, k+1), -1);\n     * 
\n * To make this concrete, suppose list comprises\n * [a, b, c, d, e]. To move the element at index 1\n * (b) forward two positions, perform the following invocation:\n *
\n     *     Collections.rotate(l.subList(1, 4), -1);\n     * 
\n * The resulting list is [a, c, d, b, e].\n *\n *

To move more than one element forward, increase the absolute value\n * of the rotation distance. To move elements backward, use a positive\n * shift distance.\n *\n *

If the specified list is small or implements the {@link\n * RandomAccess} interface, this implementation exchanges the first\n * element into the location it should go, and then repeatedly exchanges\n * the displaced element into the location it should go until a displaced\n * element is swapped into the first element. If necessary, the process\n * is repeated on the second and successive elements, until the rotation\n * is complete. If the specified list is large and doesn't implement the\n * RandomAccess interface, this implementation breaks the\n * list into two sublist views around index -distance mod size.\n * Then the {@link #reverse(List)} method is invoked on each sublist view,\n * and finally it is invoked on the entire list. For a more complete\n * description of both algorithms, see Section 2.3 of Jon Bentley's\n * Programming Pearls (Addison-Wesley, 1986).\n *\n * @param list the list to be rotated.\n * @param distance the distance to rotate the list. There are no\n * constraints on this value; it may be zero, negative, or\n * greater than list.size().\n * @throws UnsupportedOperationException if the specified list or\n * its list-iterator does not support the set operation.\n * @since 1.4\n */\n public static void rotate(List list, int distance) {\n if (list instanceof RandomAccess || list.size() < ROTATE_THRESHOLD)\n rotate1(list, distance);\n else\n rotate2(list, distance);\n }\n\n private static void rotate1(List list, int distance) {\n int size = list.size();\n if (size == 0)\n return;\n distance = distance % size;\n if (distance < 0)\n distance += size;\n if (distance == 0)\n return;\n\n for (int cycleStart = 0, nMoved = 0; nMoved != size; cycleStart++) {\n T displaced = list.get(cycleStart);\n int i = cycleStart;\n do {\n i += distance;\n if (i >= size)\n i -= size;\n displaced = list.set(i, displaced);\n nMoved ++;\n } while (i != cycleStart);\n }\n }\n\n private static void rotate2(List list, int distance) {\n int size = list.size();\n if (size == 0)\n return;\n int mid = -distance % size;\n if (mid < 0)\n mid += size;\n if (mid == 0)\n return;\n\n reverse(list.subList(0, mid));\n reverse(list.subList(mid, size));\n reverse(list);\n }\n\n /**\n * Replaces all occurrences of one specified value in a list with another.\n * More formally, replaces with newVal each element e\n * in list such that\n * (oldVal==null ? e==null : oldVal.equals(e)).\n * (This method has no effect on the size of the list.)\n *\n * @param list the list in which replacement is to occur.\n * @param oldVal the old value to be replaced.\n * @param newVal the new value with which oldVal is to be\n * replaced.\n * @return true if list contained one or more elements\n * e such that\n * (oldVal==null ? e==null : oldVal.equals(e)).\n * @throws UnsupportedOperationException if the specified list or\n * its list-iterator does not support the set operation.\n * @since 1.4\n */\n public static boolean replaceAll(List list, T oldVal, T newVal) {\n boolean result = false;\n int size = list.size();\n if (size < REPLACEALL_THRESHOLD || list instanceof RandomAccess) {\n if (oldVal==null) {\n for (int i=0; i itr=list.listIterator();\n if (oldVal==null) {\n for (int i=0; ii\n * such that source.subList(i, i+target.size()).equals(target),\n * or -1 if there is no such index. (Returns -1 if\n * target.size() > source.size().)\n *\n *

This implementation uses the \"brute force\" technique of scanning\n * over the source list, looking for a match with the target at each\n * location in turn.\n *\n * @param source the list in which to search for the first occurrence\n * of target.\n * @param target the list to search for as a subList of source.\n * @return the starting position of the first occurrence of the specified\n * target list within the specified source list, or -1 if there\n * is no such occurrence.\n * @since 1.4\n */\n public static int indexOfSubList(List source, List target) {\n int sourceSize = source.size();\n int targetSize = target.size();\n int maxCandidate = sourceSize - targetSize;\n\n if (sourceSize < INDEXOFSUBLIST_THRESHOLD ||\n (source instanceof RandomAccess&&target instanceof RandomAccess)) {\n nextCand:\n for (int candidate = 0; candidate <= maxCandidate; candidate++) {\n for (int i=0, j=candidate; i si = source.listIterator();\n nextCand:\n for (int candidate = 0; candidate <= maxCandidate; candidate++) {\n ListIterator ti = target.listIterator();\n for (int i=0; ii\n * such that source.subList(i, i+target.size()).equals(target),\n * or -1 if there is no such index. (Returns -1 if\n * target.size() > source.size().)\n *\n *

This implementation uses the \"brute force\" technique of iterating\n * over the source list, looking for a match with the target at each\n * location in turn.\n *\n * @param source the list in which to search for the last occurrence\n * of target.\n * @param target the list to search for as a subList of source.\n * @return the starting position of the last occurrence of the specified\n * target list within the specified source list, or -1 if there\n * is no such occurrence.\n * @since 1.4\n */\n public static int lastIndexOfSubList(List source, List target) {\n int sourceSize = source.size();\n int targetSize = target.size();\n int maxCandidate = sourceSize - targetSize;\n\n if (sourceSize < INDEXOFSUBLIST_THRESHOLD ||\n source instanceof RandomAccess) { // Index access version\n nextCand:\n for (int candidate = maxCandidate; candidate >= 0; candidate--) {\n for (int i=0, j=candidate; i si = source.listIterator(maxCandidate);\n nextCand:\n for (int candidate = maxCandidate; candidate >= 0; candidate--) {\n ListIterator ti = target.listIterator();\n for (int i=0; iUnsupportedOperationException.

\n *\n * The returned collection does not pass the hashCode and equals\n * operations through to the backing collection, but relies on\n * Object's equals and hashCode methods. This\n * is necessary to preserve the contracts of these operations in the case\n * that the backing collection is a set or a list.

\n *\n * The returned collection will be serializable if the specified collection\n * is serializable.\n *\n * @param c the collection for which an unmodifiable view is to be\n * returned.\n * @return an unmodifiable view of the specified collection.\n */\n public static Collection unmodifiableCollection(Collection c) {\n return new UnmodifiableCollection<>(c);\n }\n\n /**\n * @serial include\n */\n static class UnmodifiableCollection implements Collection, Serializable {\n private static final long serialVersionUID = 1820017752578914078L;\n\n final Collection c;\n\n UnmodifiableCollection(Collection c) {\n if (c==null)\n throw new NullPointerException();\n this.c = c;\n }\n\n public int size() {return c.size();}\n public boolean isEmpty() {return c.isEmpty();}\n public boolean contains(Object o) {return c.contains(o);}\n public Object[] toArray() {return c.toArray();}\n public T[] toArray(T[] a) {return c.toArray(a);}\n public String toString() {return c.toString();}\n\n public Iterator iterator() {\n return new Iterator() {\n private final Iterator i = c.iterator();\n\n public boolean hasNext() {return i.hasNext();}\n public E next() {return i.next();}\n public void remove() {\n throw new UnsupportedOperationException();\n }\n };\n }\n\n public boolean add(E e) {\n throw new UnsupportedOperationException();\n }\n public boolean remove(Object o) {\n throw new UnsupportedOperationException();\n }\n\n public boolean containsAll(Collection coll) {\n return c.containsAll(coll);\n }\n public boolean addAll(Collection coll) {\n throw new UnsupportedOperationException();\n }\n public boolean removeAll(Collection coll) {\n throw new UnsupportedOperationException();\n }\n public boolean retainAll(Collection coll) {\n throw new UnsupportedOperationException();\n }\n public void clear() {\n throw new UnsupportedOperationException();\n }\n }\n\n /**\n * Returns an unmodifiable view of the specified set. This method allows\n * modules to provide users with \"read-only\" access to internal sets.\n * Query operations on the returned set \"read through\" to the specified\n * set, and attempts to modify the returned set, whether direct or via its\n * iterator, result in an UnsupportedOperationException.

\n *\n * The returned set will be serializable if the specified set\n * is serializable.\n *\n * @param s the set for which an unmodifiable view is to be returned.\n * @return an unmodifiable view of the specified set.\n */\n public static Set unmodifiableSet(Set s) {\n return new UnmodifiableSet<>(s);\n }\n\n /**\n * @serial include\n */\n static class UnmodifiableSet extends UnmodifiableCollection\n implements Set, Serializable {\n private static final long serialVersionUID = -9215047833775013803L;\n\n UnmodifiableSet(Set s) {super(s);}\n public boolean equals(Object o) {return o == this || c.equals(o);}\n public int hashCode() {return c.hashCode();}\n }\n\n /**\n * Returns an unmodifiable view of the specified sorted set. This method\n * allows modules to provide users with \"read-only\" access to internal\n * sorted sets. Query operations on the returned sorted set \"read\n * through\" to the specified sorted set. Attempts to modify the returned\n * sorted set, whether direct, via its iterator, or via its\n * subSet, headSet, or tailSet views, result in\n * an UnsupportedOperationException.

\n *\n * The returned sorted set will be serializable if the specified sorted set\n * is serializable.\n *\n * @param s the sorted set for which an unmodifiable view is to be\n * returned.\n * @return an unmodifiable view of the specified sorted set.\n */\n public static SortedSet unmodifiableSortedSet(SortedSet s) {\n return new UnmodifiableSortedSet<>(s);\n }\n\n /**\n * @serial include\n */\n static class UnmodifiableSortedSet\n extends UnmodifiableSet\n implements SortedSet, Serializable {\n private static final long serialVersionUID = -4929149591599911165L;\n private final SortedSet ss;\n\n UnmodifiableSortedSet(SortedSet s) {super(s); ss = s;}\n\n public Comparator comparator() {return ss.comparator();}\n\n public SortedSet subSet(E fromElement, E toElement) {\n return new UnmodifiableSortedSet<>(ss.subSet(fromElement,toElement));\n }\n public SortedSet headSet(E toElement) {\n return new UnmodifiableSortedSet<>(ss.headSet(toElement));\n }\n public SortedSet tailSet(E fromElement) {\n return new UnmodifiableSortedSet<>(ss.tailSet(fromElement));\n }\n\n public E first() {return ss.first();}\n public E last() {return ss.last();}\n }\n\n /**\n * Returns an unmodifiable view of the specified list. This method allows\n * modules to provide users with \"read-only\" access to internal\n * lists. Query operations on the returned list \"read through\" to the\n * specified list, and attempts to modify the returned list, whether\n * direct or via its iterator, result in an\n * UnsupportedOperationException.

\n *\n * The returned list will be serializable if the specified list\n * is serializable. Similarly, the returned list will implement\n * {@link RandomAccess} if the specified list does.\n *\n * @param list the list for which an unmodifiable view is to be returned.\n * @return an unmodifiable view of the specified list.\n */\n public static List unmodifiableList(List list) {\n return (list instanceof RandomAccess ?\n new UnmodifiableRandomAccessList<>(list) :\n new UnmodifiableList<>(list));\n }\n\n /**\n * @serial include\n */\n static class UnmodifiableList extends UnmodifiableCollection\n implements List {\n private static final long serialVersionUID = -283967356065247728L;\n final List list;\n\n UnmodifiableList(List list) {\n super(list);\n this.list = list;\n }\n\n public boolean equals(Object o) {return o == this || list.equals(o);}\n public int hashCode() {return list.hashCode();}\n\n public E get(int index) {return list.get(index);}\n public E set(int index, E element) {\n throw new UnsupportedOperationException();\n }\n public void add(int index, E element) {\n throw new UnsupportedOperationException();\n }\n public E remove(int index) {\n throw new UnsupportedOperationException();\n }\n public int indexOf(Object o) {return list.indexOf(o);}\n public int lastIndexOf(Object o) {return list.lastIndexOf(o);}\n public boolean addAll(int index, Collection c) {\n throw new UnsupportedOperationException();\n }\n public ListIterator listIterator() {return listIterator(0);}\n\n public ListIterator listIterator(final int index) {\n return new ListIterator() {\n private final ListIterator i\n = list.listIterator(index);\n\n public boolean hasNext() {return i.hasNext();}\n public E next() {return i.next();}\n public boolean hasPrevious() {return i.hasPrevious();}\n public E previous() {return i.previous();}\n public int nextIndex() {return i.nextIndex();}\n public int previousIndex() {return i.previousIndex();}\n\n public void remove() {\n throw new UnsupportedOperationException();\n }\n public void set(E e) {\n throw new UnsupportedOperationException();\n }\n public void add(E e) {\n throw new UnsupportedOperationException();\n }\n };\n }\n\n public List subList(int fromIndex, int toIndex) {\n return new UnmodifiableList<>(list.subList(fromIndex, toIndex));\n }\n\n /**\n * UnmodifiableRandomAccessList instances are serialized as\n * UnmodifiableList instances to allow them to be deserialized\n * in pre-1.4 JREs (which do not have UnmodifiableRandomAccessList).\n * This method inverts the transformation. As a beneficial\n * side-effect, it also grafts the RandomAccess marker onto\n * UnmodifiableList instances that were serialized in pre-1.4 JREs.\n *\n * Note: Unfortunately, UnmodifiableRandomAccessList instances\n * serialized in 1.4.1 and deserialized in 1.4 will become\n * UnmodifiableList instances, as this method was missing in 1.4.\n */\n private Object readResolve() {\n return (list instanceof RandomAccess\n ? new UnmodifiableRandomAccessList<>(list)\n : this);\n }\n }\n\n /**\n * @serial include\n */\n static class UnmodifiableRandomAccessList extends UnmodifiableList\n implements RandomAccess\n {\n UnmodifiableRandomAccessList(List list) {\n super(list);\n }\n\n public List subList(int fromIndex, int toIndex) {\n return new UnmodifiableRandomAccessList<>(\n list.subList(fromIndex, toIndex));\n }\n\n private static final long serialVersionUID = -2542308836966382001L;\n\n /**\n * Allows instances to be deserialized in pre-1.4 JREs (which do\n * not have UnmodifiableRandomAccessList). UnmodifiableList has\n * a readResolve method that inverts this transformation upon\n * deserialization.\n */\n private Object writeReplace() {\n return new UnmodifiableList<>(list);\n }\n }\n\n /**\n * Returns an unmodifiable view of the specified map. This method\n * allows modules to provide users with \"read-only\" access to internal\n * maps. Query operations on the returned map \"read through\"\n * to the specified map, and attempts to modify the returned\n * map, whether direct or via its collection views, result in an\n * UnsupportedOperationException.

\n *\n * The returned map will be serializable if the specified map\n * is serializable.\n *\n * @param m the map for which an unmodifiable view is to be returned.\n * @return an unmodifiable view of the specified map.\n */\n public static Map unmodifiableMap(Map m) {\n return new UnmodifiableMap<>(m);\n }\n\n /**\n * @serial include\n */\n private static class UnmodifiableMap implements Map, Serializable {\n private static final long serialVersionUID = -1034234728574286014L;\n\n private final Map m;\n\n UnmodifiableMap(Map m) {\n if (m==null)\n throw new NullPointerException();\n this.m = m;\n }\n\n public int size() {return m.size();}\n public boolean isEmpty() {return m.isEmpty();}\n public boolean containsKey(Object key) {return m.containsKey(key);}\n public boolean containsValue(Object val) {return m.containsValue(val);}\n public V get(Object key) {return m.get(key);}\n\n public V put(K key, V value) {\n throw new UnsupportedOperationException();\n }\n public V remove(Object key) {\n throw new UnsupportedOperationException();\n }\n public void putAll(Map m) {\n throw new UnsupportedOperationException();\n }\n public void clear() {\n throw new UnsupportedOperationException();\n }\n\n private transient Set keySet = null;\n private transient Set> entrySet = null;\n private transient Collection values = null;\n\n public Set keySet() {\n if (keySet==null)\n keySet = unmodifiableSet(m.keySet());\n return keySet;\n }\n\n public Set> entrySet() {\n if (entrySet==null)\n entrySet = new UnmodifiableEntrySet<>(m.entrySet());\n return entrySet;\n }\n\n public Collection values() {\n if (values==null)\n values = unmodifiableCollection(m.values());\n return values;\n }\n\n public boolean equals(Object o) {return o == this || m.equals(o);}\n public int hashCode() {return m.hashCode();}\n public String toString() {return m.toString();}\n\n /**\n * We need this class in addition to UnmodifiableSet as\n * Map.Entries themselves permit modification of the backing Map\n * via their setValue operation. This class is subtle: there are\n * many possible attacks that must be thwarted.\n *\n * @serial include\n */\n static class UnmodifiableEntrySet\n extends UnmodifiableSet> {\n private static final long serialVersionUID = 7854390611657943733L;\n\n UnmodifiableEntrySet(Set> s) {\n super((Set)s);\n }\n public Iterator> iterator() {\n return new Iterator>() {\n private final Iterator> i = c.iterator();\n\n public boolean hasNext() {\n return i.hasNext();\n }\n public Map.Entry next() {\n return new UnmodifiableEntry<>(i.next());\n }\n public void remove() {\n throw new UnsupportedOperationException();\n }\n };\n }\n\n public Object[] toArray() {\n Object[] a = c.toArray();\n for (int i=0; i((Map.Entry)a[i]);\n return a;\n }\n\n public T[] toArray(T[] a) {\n // We don't pass a to c.toArray, to avoid window of\n // vulnerability wherein an unscrupulous multithreaded client\n // could get his hands on raw (unwrapped) Entries from c.\n Object[] arr = c.toArray(a.length==0 ? a : Arrays.copyOf(a, 0));\n\n for (int i=0; i((Map.Entry)arr[i]);\n\n if (arr.length > a.length)\n return (T[])arr;\n\n System.arraycopy(arr, 0, a, 0, arr.length);\n if (a.length > arr.length)\n a[arr.length] = null;\n return a;\n }\n\n /**\n * This method is overridden to protect the backing set against\n * an object with a nefarious equals function that senses\n * that the equality-candidate is Map.Entry and calls its\n * setValue method.\n */\n public boolean contains(Object o) {\n if (!(o instanceof Map.Entry))\n return false;\n return c.contains(\n new UnmodifiableEntry<>((Map.Entry) o));\n }\n\n /**\n * The next two methods are overridden to protect against\n * an unscrupulous List whose contains(Object o) method senses\n * when o is a Map.Entry, and calls o.setValue.\n */\n public boolean containsAll(Collection coll) {\n for (Object e : coll) {\n if (!contains(e)) // Invokes safe contains() above\n return false;\n }\n return true;\n }\n public boolean equals(Object o) {\n if (o == this)\n return true;\n\n if (!(o instanceof Set))\n return false;\n Set s = (Set) o;\n if (s.size() != c.size())\n return false;\n return containsAll(s); // Invokes safe containsAll() above\n }\n\n /**\n * This \"wrapper class\" serves two purposes: it prevents\n * the client from modifying the backing Map, by short-circuiting\n * the setValue method, and it protects the backing Map against\n * an ill-behaved Map.Entry that attempts to modify another\n * Map Entry when asked to perform an equality check.\n */\n private static class UnmodifiableEntry implements Map.Entry {\n private Map.Entry e;\n\n UnmodifiableEntry(Map.Entry e) {this.e = e;}\n\n public K getKey() {return e.getKey();}\n public V getValue() {return e.getValue();}\n public V setValue(V value) {\n throw new UnsupportedOperationException();\n }\n public int hashCode() {return e.hashCode();}\n public boolean equals(Object o) {\n if (this == o)\n return true;\n if (!(o instanceof Map.Entry))\n return false;\n Map.Entry t = (Map.Entry)o;\n return eq(e.getKey(), t.getKey()) &&\n eq(e.getValue(), t.getValue());\n }\n public String toString() {return e.toString();}\n }\n }\n }\n\n /**\n * Returns an unmodifiable view of the specified sorted map. This method\n * allows modules to provide users with \"read-only\" access to internal\n * sorted maps. Query operations on the returned sorted map \"read through\"\n * to the specified sorted map. Attempts to modify the returned\n * sorted map, whether direct, via its collection views, or via its\n * subMap, headMap, or tailMap views, result in\n * an UnsupportedOperationException.

\n *\n * The returned sorted map will be serializable if the specified sorted map\n * is serializable.\n *\n * @param m the sorted map for which an unmodifiable view is to be\n * returned.\n * @return an unmodifiable view of the specified sorted map.\n */\n public static SortedMap unmodifiableSortedMap(SortedMap m) {\n return new UnmodifiableSortedMap<>(m);\n }\n\n /**\n * @serial include\n */\n static class UnmodifiableSortedMap\n extends UnmodifiableMap\n implements SortedMap, Serializable {\n private static final long serialVersionUID = -8806743815996713206L;\n\n private final SortedMap sm;\n\n UnmodifiableSortedMap(SortedMap m) {super(m); sm = m;}\n\n public Comparator comparator() {return sm.comparator();}\n\n public SortedMap subMap(K fromKey, K toKey) {\n return new UnmodifiableSortedMap<>(sm.subMap(fromKey, toKey));\n }\n public SortedMap headMap(K toKey) {\n return new UnmodifiableSortedMap<>(sm.headMap(toKey));\n }\n public SortedMap tailMap(K fromKey) {\n return new UnmodifiableSortedMap<>(sm.tailMap(fromKey));\n }\n\n public K firstKey() {return sm.firstKey();}\n public K lastKey() {return sm.lastKey();}\n }\n\n\n // Synch Wrappers\n\n /**\n * Returns a synchronized (thread-safe) collection backed by the specified\n * collection. In order to guarantee serial access, it is critical that\n * all access to the backing collection is accomplished\n * through the returned collection.

\n *\n * It is imperative that the user manually synchronize on the returned\n * collection when iterating over it:\n *

\n     *  Collection c = Collections.synchronizedCollection(myCollection);\n     *     ...\n     *  synchronized (c) {\n     *      Iterator i = c.iterator(); // Must be in the synchronized block\n     *      while (i.hasNext())\n     *         foo(i.next());\n     *  }\n     * 
\n * Failure to follow this advice may result in non-deterministic behavior.\n *\n *

The returned collection does not pass the hashCode\n * and equals operations through to the backing collection, but\n * relies on Object's equals and hashCode methods. This is\n * necessary to preserve the contracts of these operations in the case\n * that the backing collection is a set or a list.

\n *\n * The returned collection will be serializable if the specified collection\n * is serializable.\n *\n * @param c the collection to be \"wrapped\" in a synchronized collection.\n * @return a synchronized view of the specified collection.\n */\n public static Collection synchronizedCollection(Collection c) {\n return new SynchronizedCollection<>(c);\n }\n\n static Collection synchronizedCollection(Collection c, Object mutex) {\n return new SynchronizedCollection<>(c, mutex);\n }\n\n /**\n * @serial include\n */\n static class SynchronizedCollection implements Collection, Serializable {\n private static final long serialVersionUID = 3053995032091335093L;\n\n final Collection c; // Backing Collection\n final Object mutex; // Object on which to synchronize\n\n SynchronizedCollection(Collection c) {\n if (c==null)\n throw new NullPointerException();\n this.c = c;\n mutex = this;\n }\n SynchronizedCollection(Collection c, Object mutex) {\n this.c = c;\n this.mutex = mutex;\n }\n\n public int size() {\n synchronized (mutex) {return c.size();}\n }\n public boolean isEmpty() {\n synchronized (mutex) {return c.isEmpty();}\n }\n public boolean contains(Object o) {\n synchronized (mutex) {return c.contains(o);}\n }\n public Object[] toArray() {\n synchronized (mutex) {return c.toArray();}\n }\n public T[] toArray(T[] a) {\n synchronized (mutex) {return c.toArray(a);}\n }\n\n public Iterator iterator() {\n return c.iterator(); // Must be manually synched by user!\n }\n\n public boolean add(E e) {\n synchronized (mutex) {return c.add(e);}\n }\n public boolean remove(Object o) {\n synchronized (mutex) {return c.remove(o);}\n }\n\n public boolean containsAll(Collection coll) {\n synchronized (mutex) {return c.containsAll(coll);}\n }\n public boolean addAll(Collection coll) {\n synchronized (mutex) {return c.addAll(coll);}\n }\n public boolean removeAll(Collection coll) {\n synchronized (mutex) {return c.removeAll(coll);}\n }\n public boolean retainAll(Collection coll) {\n synchronized (mutex) {return c.retainAll(coll);}\n }\n public void clear() {\n synchronized (mutex) {c.clear();}\n }\n public String toString() {\n synchronized (mutex) {return c.toString();}\n }\n private void writeObject(ObjectOutputStream s) throws IOException {\n synchronized (mutex) {s.defaultWriteObject();}\n }\n }\n\n /**\n * Returns a synchronized (thread-safe) set backed by the specified\n * set. In order to guarantee serial access, it is critical that\n * all access to the backing set is accomplished\n * through the returned set.

\n *\n * It is imperative that the user manually synchronize on the returned\n * set when iterating over it:\n *

\n     *  Set s = Collections.synchronizedSet(new HashSet());\n     *      ...\n     *  synchronized (s) {\n     *      Iterator i = s.iterator(); // Must be in the synchronized block\n     *      while (i.hasNext())\n     *          foo(i.next());\n     *  }\n     * 
\n * Failure to follow this advice may result in non-deterministic behavior.\n *\n *

The returned set will be serializable if the specified set is\n * serializable.\n *\n * @param s the set to be \"wrapped\" in a synchronized set.\n * @return a synchronized view of the specified set.\n */\n public static Set synchronizedSet(Set s) {\n return new SynchronizedSet<>(s);\n }\n\n static Set synchronizedSet(Set s, Object mutex) {\n return new SynchronizedSet<>(s, mutex);\n }\n\n /**\n * @serial include\n */\n static class SynchronizedSet\n extends SynchronizedCollection\n implements Set {\n private static final long serialVersionUID = 487447009682186044L;\n\n SynchronizedSet(Set s) {\n super(s);\n }\n SynchronizedSet(Set s, Object mutex) {\n super(s, mutex);\n }\n\n public boolean equals(Object o) {\n if (this == o)\n return true;\n synchronized (mutex) {return c.equals(o);}\n }\n public int hashCode() {\n synchronized (mutex) {return c.hashCode();}\n }\n }\n\n /**\n * Returns a synchronized (thread-safe) sorted set backed by the specified\n * sorted set. In order to guarantee serial access, it is critical that\n * all access to the backing sorted set is accomplished\n * through the returned sorted set (or its views).

\n *\n * It is imperative that the user manually synchronize on the returned\n * sorted set when iterating over it or any of its subSet,\n * headSet, or tailSet views.\n *

\n     *  SortedSet s = Collections.synchronizedSortedSet(new TreeSet());\n     *      ...\n     *  synchronized (s) {\n     *      Iterator i = s.iterator(); // Must be in the synchronized block\n     *      while (i.hasNext())\n     *          foo(i.next());\n     *  }\n     * 
\n * or:\n *
\n     *  SortedSet s = Collections.synchronizedSortedSet(new TreeSet());\n     *  SortedSet s2 = s.headSet(foo);\n     *      ...\n     *  synchronized (s) {  // Note: s, not s2!!!\n     *      Iterator i = s2.iterator(); // Must be in the synchronized block\n     *      while (i.hasNext())\n     *          foo(i.next());\n     *  }\n     * 
\n * Failure to follow this advice may result in non-deterministic behavior.\n *\n *

The returned sorted set will be serializable if the specified\n * sorted set is serializable.\n *\n * @param s the sorted set to be \"wrapped\" in a synchronized sorted set.\n * @return a synchronized view of the specified sorted set.\n */\n public static SortedSet synchronizedSortedSet(SortedSet s) {\n return new SynchronizedSortedSet<>(s);\n }\n\n /**\n * @serial include\n */\n static class SynchronizedSortedSet\n extends SynchronizedSet\n implements SortedSet\n {\n private static final long serialVersionUID = 8695801310862127406L;\n\n private final SortedSet ss;\n\n SynchronizedSortedSet(SortedSet s) {\n super(s);\n ss = s;\n }\n SynchronizedSortedSet(SortedSet s, Object mutex) {\n super(s, mutex);\n ss = s;\n }\n\n public Comparator comparator() {\n synchronized (mutex) {return ss.comparator();}\n }\n\n public SortedSet subSet(E fromElement, E toElement) {\n synchronized (mutex) {\n return new SynchronizedSortedSet<>(\n ss.subSet(fromElement, toElement), mutex);\n }\n }\n public SortedSet headSet(E toElement) {\n synchronized (mutex) {\n return new SynchronizedSortedSet<>(ss.headSet(toElement), mutex);\n }\n }\n public SortedSet tailSet(E fromElement) {\n synchronized (mutex) {\n return new SynchronizedSortedSet<>(ss.tailSet(fromElement),mutex);\n }\n }\n\n public E first() {\n synchronized (mutex) {return ss.first();}\n }\n public E last() {\n synchronized (mutex) {return ss.last();}\n }\n }\n\n /**\n * Returns a synchronized (thread-safe) list backed by the specified\n * list. In order to guarantee serial access, it is critical that\n * all access to the backing list is accomplished\n * through the returned list.

\n *\n * It is imperative that the user manually synchronize on the returned\n * list when iterating over it:\n *

\n     *  List list = Collections.synchronizedList(new ArrayList());\n     *      ...\n     *  synchronized (list) {\n     *      Iterator i = list.iterator(); // Must be in synchronized block\n     *      while (i.hasNext())\n     *          foo(i.next());\n     *  }\n     * 
\n * Failure to follow this advice may result in non-deterministic behavior.\n *\n *

The returned list will be serializable if the specified list is\n * serializable.\n *\n * @param list the list to be \"wrapped\" in a synchronized list.\n * @return a synchronized view of the specified list.\n */\n public static List synchronizedList(List list) {\n return (list instanceof RandomAccess ?\n new SynchronizedRandomAccessList<>(list) :\n new SynchronizedList<>(list));\n }\n\n static List synchronizedList(List list, Object mutex) {\n return (list instanceof RandomAccess ?\n new SynchronizedRandomAccessList<>(list, mutex) :\n new SynchronizedList<>(list, mutex));\n }\n\n /**\n * @serial include\n */\n static class SynchronizedList\n extends SynchronizedCollection\n implements List {\n private static final long serialVersionUID = -7754090372962971524L;\n\n final List list;", "answers": [" SynchronizedList(List list) {"], "length": 9302, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "5aaaaaf5-a7b1-46ef-9b2b-e5f5f8c71940", "reasoning": "Within the Collections class, the inner class SynchronizedList extends SynchronizedCollection and declares a field `final List list;`. The next logical line defines the constructor that initializes this field and calls the superclass constructor, matching the pattern used for other synchronized wrappers. Therefore the next line is the constructor declaration `SynchronizedList(List list) {`.", "reasoning_model_answer": "SynchronizedList(List list) {", "assistant_with_reasoning": "\nWithin the Collections class, the inner class SynchronizedList extends SynchronizedCollection and declares a field `final List list;`. The next logical line defines the constructor that initializes this field and calls the superclass constructor, matching the pattern used for other synchronized wrappers. Therefore the next line is the constructor declaration `SynchronizedList(List list) {`.\n\nSynchronizedList(List list) {", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 7.608, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 48004, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "SynchronizedList(List list) {", "score": 0.89, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "# #\n# Copyright 2009-2016 Ghent University\n#\n# This file is part of EasyBuild,\n# originally created by the HPC team of Ghent University (http://ugent.be/hpc/en),\n# with support of Ghent University (http://ugent.be/hpc),\n# the Flemish Supercomputer Centre (VSC) (https://www.vscentrum.be),\n# Flemish Research Foundation (FWO) (http://www.fwo.be/en)\n# and the Department of Economy, Science and Innovation (EWI) (http://www.ewi-vlaanderen.be/en).\n#\n# http://github.com/hpcugent/easybuild\n#\n# EasyBuild is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation v2.\n#\n# EasyBuild is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with EasyBuild. If not, see .\n# #\n\"\"\"\nGeneric EasyBuild support for building and installing software.\nThe EasyBlock class should serve as a base class for all easyblocks.\n\n:author: Stijn De Weirdt (Ghent University)\n:author: Dries Verdegem (Ghent University)\n:author: Kenneth Hoste (Ghent University)\n:author: Pieter De Baets (Ghent University)\n:author: Jens Timmerman (Ghent University)\n:author: Toon Willems (Ghent University)\n:author: Ward Poelmans (Ghent University)\n:author: Fotis Georgatos (Uni.Lu, NTUA)\n\"\"\"\n\nimport copy\nimport glob\nimport inspect\nimport os\nimport re\nimport shutil\nimport stat\nimport tempfile\nimport time\nimport traceback\nfrom distutils.version import LooseVersion\nfrom vsc.utils import fancylogger\nfrom vsc.utils.missing import get_class_for\n\nimport easybuild.tools.environment as env\nfrom easybuild.tools import config, filetools\nfrom easybuild.framework.easyconfig import EASYCONFIGS_PKG_SUBDIR\nfrom easybuild.framework.easyconfig.easyconfig import ITERATE_OPTIONS, EasyConfig, ActiveMNS, get_easyblock_class\nfrom easybuild.framework.easyconfig.easyconfig import get_module_path, letter_dir_for, resolve_template\nfrom easybuild.framework.easyconfig.parser import fetch_parameters_from_easyconfig\nfrom easybuild.framework.easyconfig.tools import get_paths_for\nfrom easybuild.framework.easyconfig.templates import TEMPLATE_NAMES_EASYBLOCK_RUN_STEP\nfrom easybuild.tools.build_details import get_build_stats\nfrom easybuild.tools.build_log import EasyBuildError, dry_run_msg, dry_run_warning, dry_run_set_dirs\nfrom easybuild.tools.build_log import print_error, print_msg\nfrom easybuild.tools.config import build_option, build_path, get_log_filename, get_repository, get_repositorypath\nfrom easybuild.tools.config import install_path, log_path, package_path, source_paths\nfrom easybuild.tools.environment import restore_env, sanitize_env\nfrom easybuild.tools.filetools import DEFAULT_CHECKSUM\nfrom easybuild.tools.filetools import adjust_permissions, apply_patch, convert_name, derive_alt_pypi_url\nfrom easybuild.tools.filetools import compute_checksum, download_file, encode_class_name, extract_file\nfrom easybuild.tools.filetools import is_alt_pypi_url, mkdir, move_logs, read_file, remove_file, rmtree2, write_file\nfrom easybuild.tools.filetools import verify_checksum, weld_paths\nfrom easybuild.tools.run import run_cmd\nfrom easybuild.tools.jenkins import write_to_xml\nfrom easybuild.tools.module_generator import ModuleGeneratorLua, ModuleGeneratorTcl, module_generator\nfrom easybuild.tools.module_naming_scheme.utilities import det_full_ec_version\nfrom easybuild.tools.modules import ROOT_ENV_VAR_NAME_PREFIX, VERSION_ENV_VAR_NAME_PREFIX, DEVEL_ENV_VAR_NAME_PREFIX\nfrom easybuild.tools.modules import invalidate_module_caches_for, get_software_root, get_software_root_env_var_name\nfrom easybuild.tools.modules import get_software_version_env_var_name\nfrom easybuild.tools.package.utilities import package\nfrom easybuild.tools.repository.repository import init_repository\nfrom easybuild.tools.toolchain import DUMMY_TOOLCHAIN_NAME\nfrom easybuild.tools.systemtools import det_parallelism, use_group\nfrom easybuild.tools.utilities import remove_unwanted_chars\nfrom easybuild.tools.version import this_is_easybuild, VERBOSE_VERSION, VERSION\n\n\nBUILD_STEP = 'build'\nCLEANUP_STEP = 'cleanup'\nCONFIGURE_STEP = 'configure'\nEXTENSIONS_STEP = 'extensions'\nFETCH_STEP = 'fetch'\nMODULE_STEP = 'module'\nPACKAGE_STEP = 'package'\nPATCH_STEP = 'patch'\nPERMISSIONS_STEP = 'permissions'\nPOSTPROC_STEP = 'postproc'\nPREPARE_STEP = 'prepare'\nREADY_STEP = 'ready'\nSANITYCHECK_STEP = 'sanitycheck'\nSOURCE_STEP = 'source'\nTEST_STEP = 'test'\nTESTCASES_STEP = 'testcases'\n\nMODULE_ONLY_STEPS = [MODULE_STEP, PREPARE_STEP, READY_STEP, SANITYCHECK_STEP]\n\n# string part of URL for Python packages on PyPI that indicates needs to be rewritten (see derive_alt_pypi_url)\nPYPI_PKG_URL_PATTERN = 'pypi.python.org/packages/source/'\n\n\n_log = fancylogger.getLogger('easyblock')\n\n\nclass EasyBlock(object):\n \"\"\"Generic support for building and installing software, base class for actual easyblocks.\"\"\"\n\n # static class method for extra easyconfig parameter definitions\n # this makes it easy to access the information without needing an instance\n # subclasses of EasyBlock should call this method with a dictionary\n @staticmethod\n def extra_options(extra=None):\n \"\"\"\n Extra options method which will be passed to the EasyConfig constructor.\n \"\"\"\n if extra is None:\n extra = {}\n\n if not isinstance(extra, dict):\n _log.nosupport(\"Obtained 'extra' value of type '%s' in extra_options, should be 'dict'\" % type(extra), '2.0')\n\n return extra\n\n #\n # INIT\n #\n def __init__(self, ec):\n \"\"\"\n Initialize the EasyBlock instance.\n :param ec: a parsed easyconfig file (EasyConfig instance)\n \"\"\"\n\n # keep track of original working directory, so we can go back there\n self.orig_workdir = os.getcwd()\n\n # list of patch/source files, along with checksums\n self.patches = []\n self.src = []\n self.checksums = []\n\n # build/install directories\n self.builddir = None\n self.installdir = None # software\n self.installdir_mod = None # module file\n\n # extensions\n self.exts = None\n self.exts_all = None\n self.ext_instances = []\n self.skip = None\n self.module_extra_extensions = '' # extra stuff for module file required by extensions\n\n # easyconfig for this application\n if isinstance(ec, EasyConfig):\n self.cfg = ec\n else:\n raise EasyBuildError(\"Value of incorrect type passed to EasyBlock constructor: %s ('%s')\", type(ec), ec)\n\n # modules interface with default MODULEPATH\n self.modules_tool = self.cfg.modules_tool\n # module generator\n self.module_generator = module_generator(self, fake=True)\n self.mod_filepath = self.module_generator.get_module_filepath()\n\n # modules footer/header\n self.modules_footer = None\n modules_footer_path = build_option('modules_footer')\n if modules_footer_path is not None:\n self.modules_footer = read_file(modules_footer_path)\n\n self.modules_header = None\n modules_header_path = build_option('modules_header')\n if modules_header_path is not None:\n self.modules_header = read_file(modules_header_path)\n\n # determine install subdirectory, based on module name\n self.install_subdir = None\n\n # indicates whether build should be performed in installation dir\n self.build_in_installdir = self.cfg['buildininstalldir']\n\n # list of locations to include in RPATH filter used by toolchain\n self.rpath_filter_dirs = []\n\n # logging\n self.log = None\n self.logfile = None\n self.logdebug = build_option('debug')\n self.postmsg = '' # allow a post message to be set, which can be shown as last output\n\n # list of loaded modules\n self.loaded_modules = []\n\n # iterate configure/build/options\n self.iter_idx = 0\n self.iter_opts = {}\n\n # sanity check fail error messages to report (if any)\n self.sanity_check_fail_msgs = []\n\n # robot path\n self.robot_path = build_option('robot_path')\n\n # original module path\n self.orig_modulepath = os.getenv('MODULEPATH')\n\n # keep track of initial environment we start in, so we can restore it if needed\n self.initial_environ = copy.deepcopy(os.environ)\n\n # should we keep quiet?\n self.silent = build_option('silent')\n\n # are we doing a dry run?\n self.dry_run = build_option('extended_dry_run')\n\n # initialize logger\n self._init_log()\n\n # try and use the specified group (if any)\n group_name = build_option('group')\n if self.cfg['group'] is not None:\n self.log.warning(\"Group spec '%s' is overriding config group '%s'.\" % (self.cfg['group'], group_name))\n group_name = self.cfg['group']\n\n self.group = None\n if group_name is not None:\n self.group = use_group(group_name)\n\n # generate build/install directories\n self.gen_builddir()\n self.gen_installdir()\n\n self.ignored_errors = False\n\n if self.dry_run:\n self.init_dry_run()\n\n self.log.info(\"Init completed for application name %s version %s\" % (self.name, self.version))\n\n # INIT/CLOSE LOG\n def _init_log(self):\n \"\"\"\n Initialize the logger.\n \"\"\"\n if not self.log is None:\n return\n\n self.logfile = get_log_filename(self.name, self.version, add_salt=True)\n fancylogger.logToFile(self.logfile)\n\n self.log = fancylogger.getLogger(name=self.__class__.__name__, fname=False)\n\n self.log.info(this_is_easybuild())\n\n this_module = inspect.getmodule(self)\n eb_class = self.__class__.__name__\n eb_mod_name = this_module.__name__\n eb_mod_loc = this_module.__file__\n self.log.info(\"This is easyblock %s from module %s (%s)\", eb_class, eb_mod_name, eb_mod_loc)\n\n if self.dry_run:\n self.dry_run_msg(\"*** DRY RUN using '%s' easyblock (%s @ %s) ***\\n\", eb_class, eb_mod_name, eb_mod_loc)\n\n def close_log(self):\n \"\"\"\n Shutdown the logger.\n \"\"\"\n self.log.info(\"Closing log for application name %s version %s\" % (self.name, self.version))\n fancylogger.logToFile(self.logfile, enable=False)\n\n #\n # DRY RUN UTILITIES\n #\n def init_dry_run(self):\n \"\"\"Initialise easyblock instance for performing a dry run.\"\"\"\n # replace build/install dirs with temporary directories in dry run mode\n tmp_root_dir = os.path.realpath(os.path.join(tempfile.gettempdir(), '__ROOT__'))\n self.builddir = os.path.join(tmp_root_dir, self.builddir.lstrip(os.path.sep))\n self.installdir = os.path.join(tmp_root_dir, self.installdir.lstrip(os.path.sep))\n self.installdir_mod = os.path.join(tmp_root_dir, self.installdir_mod.lstrip(os.path.sep))\n\n # register fake build/install dirs so the original values can be printed during dry run\n dry_run_set_dirs(tmp_root_dir, self.builddir, self.installdir, self.installdir_mod)\n\n def dry_run_msg(self, msg, *args):\n \"\"\"Print dry run message.\"\"\"\n if args:\n msg = msg % args\n dry_run_msg(msg, silent=self.silent)\n\n #\n # FETCH UTILITY FUNCTIONS\n #\n def get_checksum_for(self, checksums, filename=None, index=None):\n \"\"\"\n Obtain checksum for given filename.\n\n :param checksums: a list or tuple of checksums (or None)\n :param filename: name of the file to obtain checksum for\n :param index: index of file in list\n \"\"\"\n # if checksums are provided as a dict, lookup by source filename as key\n if isinstance(checksums, (list, tuple)):\n if index is not None and index < len(checksums) and (index >= 0 or abs(index) <= len(checksums)):\n return checksums[index]\n else:\n return None\n elif checksums is None:\n return None\n else:\n raise EasyBuildError(\"Invalid type for checksums (%s), should be list, tuple or None.\", type(checksums))\n\n def fetch_sources(self, list_of_sources, checksums=None):\n \"\"\"\n Add a list of source files (can be tarballs, isos, urls).\n All source files will be checked if a file exists (or can be located)\n \"\"\"\n\n for index, src_entry in enumerate(list_of_sources):\n if isinstance(src_entry, (list, tuple)):\n cmd = src_entry[1]\n source = src_entry[0]\n elif isinstance(src_entry, basestring):\n cmd = None\n source = src_entry\n\n # check if the sources can be located\n path = self.obtain_file(source)\n if path:\n self.log.debug('File %s found for source %s' % (path, source))\n self.src.append({\n 'name': source,\n 'path': path,\n 'cmd': cmd,\n 'checksum': self.get_checksum_for(checksums, filename=source, index=index),\n # always set a finalpath\n 'finalpath': self.builddir,\n })\n else:\n raise EasyBuildError('No file found for source %s', source)\n\n self.log.info(\"Added sources: %s\" % self.src)\n\n def fetch_patches(self, patch_specs=None, extension=False, checksums=None):\n \"\"\"\n Add a list of patches.\n All patches will be checked if a file exists (or can be located)\n \"\"\"\n if patch_specs is None:\n patch_specs = self.cfg['patches']\n\n patches = []\n for index, patch_spec in enumerate(patch_specs):\n\n # check if the patches can be located\n copy_file = False\n suff = None\n level = None\n if isinstance(patch_spec, (list, tuple)):\n if not len(patch_spec) == 2:\n raise EasyBuildError(\"Unknown patch specification '%s', only 2-element lists/tuples are supported!\",\n str(patch_spec))\n patch_file = patch_spec[0]\n\n # this *must* be of typ int, nothing else\n # no 'isinstance(..., int)', since that would make True/False also acceptable\n if type(patch_spec[1]) == int:\n level = patch_spec[1]\n elif isinstance(patch_spec[1], basestring):\n # non-patch files are assumed to be files to copy\n if not patch_spec[0].endswith('.patch'):\n copy_file = True\n suff = patch_spec[1]\n else:\n raise EasyBuildError(\"Wrong patch spec '%s', only int/string are supported as 2nd element\",\n str(patch_spec))\n else:\n patch_file = patch_spec\n\n path = self.obtain_file(patch_file, extension=extension)\n if path:\n self.log.debug('File %s found for patch %s' % (path, patch_spec))\n patchspec = {\n 'name': patch_file,\n 'path': path,\n 'checksum': self.get_checksum_for(checksums, filename=patch_file, index=index),\n }\n if suff:\n if copy_file:\n patchspec['copy'] = suff\n else:\n patchspec['sourcepath'] = suff\n if level is not None:\n patchspec['level'] = level\n\n if extension:\n patches.append(patchspec)\n else:\n self.patches.append(patchspec)\n else:\n raise EasyBuildError('No file found for patch %s', patch_spec)\n\n if extension:\n self.log.info(\"Fetched extension patches: %s\" % patches)\n return [patch['path'] for patch in patches]\n else:\n self.log.info(\"Added patches: %s\" % self.patches)\n\n def fetch_extension_sources(self):\n \"\"\"\n Find source file for extensions.\n \"\"\"\n exts_sources = []\n self.cfg.enable_templating = False\n exts_list = self.cfg['exts_list']\n self.cfg.enable_templating = True\n\n if self.dry_run:\n self.dry_run_msg(\"\\nList of sources/patches for extensions:\")\n\n for ext in exts_list:\n if (isinstance(ext, list) or isinstance(ext, tuple)) and ext:\n\n # expected format: (name, version, options (dict))\n\n ext_name = ext[0]\n if len(ext) == 1:\n exts_sources.append({'name': ext_name})\n else:\n ext_version = ext[1]\n ext_options = {}\n\n def_src_tmpl = \"%(name)s-%(version)s.tar.gz\"\n\n if len(ext) == 3:\n ext_options = ext[2]\n\n if not isinstance(ext_options, dict):\n raise EasyBuildError(\"Unexpected type (non-dict) for 3rd element of %s\", ext)\n elif len(ext) > 3:\n raise EasyBuildError('Extension specified in unknown format (list/tuple too long)')\n\n ext_src = {\n 'name': ext_name,\n 'version': ext_version,\n 'options': ext_options,\n }\n\n checksums = ext_options.get('checksums', None)\n\n if ext_options.get('source_tmpl', None):\n fn = resolve_template(ext_options['source_tmpl'], ext_src)\n else:\n fn = resolve_template(def_src_tmpl, ext_src)\n\n if ext_options.get('nosource', None):\n exts_sources.append(ext_src)\n else:\n source_urls = [resolve_template(url, ext_src) for url in ext_options.get('source_urls', [])]\n src_fn = self.obtain_file(fn, extension=True, urls=source_urls)\n\n if src_fn:\n ext_src.update({'src': src_fn})\n\n if checksums:\n fn_checksum = self.get_checksum_for(checksums, filename=src_fn, index=0)\n if verify_checksum(src_fn, fn_checksum):\n self.log.info('Checksum for ext source %s verified' % fn)\n else:\n raise EasyBuildError('Checksum for ext source %s failed', fn)\n\n ext_patches = self.fetch_patches(patch_specs=ext_options.get('patches', []), extension=True)\n if ext_patches:\n self.log.debug('Found patches for extension %s: %s' % (ext_name, ext_patches))\n ext_src.update({'patches': ext_patches})\n\n if checksums:\n self.log.debug('Verifying checksums for extension patches...')\n for index, ext_patch in enumerate(ext_patches):\n checksum = self.get_checksum_for(checksums[1:], filename=ext_patch, index=index)\n if verify_checksum(ext_patch, checksum):\n self.log.info('Checksum for extension patch %s verified' % ext_patch)\n else:\n raise EasyBuildError('Checksum for extension patch %s failed', ext_patch)\n else:\n self.log.debug('No patches found for extension %s.' % ext_name)\n\n exts_sources.append(ext_src)\n\n else:\n raise EasyBuildError(\"Source for extension %s not found.\", ext)\n\n elif isinstance(ext, basestring):\n exts_sources.append({'name': ext})\n\n else:\n raise EasyBuildError(\"Extension specified in unknown format (not a string/list/tuple)\")\n\n return exts_sources\n\n def obtain_file(self, filename, extension=False, urls=None):\n \"\"\"\n Locate the file with the given name\n - searches in different subdirectories of source path\n - supports fetching file from the web if path is specified as an url (i.e. starts with \"http://:\")\n \"\"\"\n srcpaths = source_paths()\n\n # should we download or just try and find it?\n if filename.startswith(\"http://\") or filename.startswith(\"ftp://\"):\n\n # URL detected, so let's try and download it\n\n url = filename\n filename = url.split('/')[-1]\n\n # figure out where to download the file to\n filepath = os.path.join(srcpaths[0], letter_dir_for(self.name), self.name)\n if extension:\n filepath = os.path.join(filepath, \"extensions\")\n self.log.info(\"Creating path %s to download file to\" % filepath)\n mkdir(filepath, parents=True)\n\n try:\n fullpath = os.path.join(filepath, filename)\n\n # only download when it's not there yet\n if os.path.exists(fullpath):\n self.log.info(\"Found file %s at %s, no need to download it.\" % (filename, filepath))\n return fullpath\n\n else:\n if download_file(filename, url, fullpath):\n return fullpath\n\n except IOError, err:\n raise EasyBuildError(\"Downloading file %s from url %s to %s failed: %s\", filename, url, fullpath, err)\n\n else:\n # try and find file in various locations\n foundfile = None\n failedpaths = []\n\n # always look first in the dir of the current eb file\n ebpath = [os.path.dirname(self.cfg.path)]\n\n # always consider robot + easyconfigs install paths as a fall back (e.g. for patch files, test cases, ...)\n common_filepaths = []\n if self.robot_path:\n common_filepaths.extend(self.robot_path)\n common_filepaths.extend(get_paths_for(subdir=EASYCONFIGS_PKG_SUBDIR, robot_path=self.robot_path))\n\n for path in ebpath + common_filepaths + srcpaths:\n # create list of candidate filepaths\n namepath = os.path.join(path, self.name)\n letterpath = os.path.join(path, letter_dir_for(self.name), self.name)\n\n # most likely paths\n candidate_filepaths = [\n letterpath, # easyblocks-style subdir\n namepath, # subdir with software name\n path, # directly in directory\n ]\n\n # see if file can be found at that location\n for cfp in candidate_filepaths:\n\n fullpath = os.path.join(cfp, filename)\n\n # also check in 'extensions' subdir for extensions\n if extension:\n fullpaths = [\n os.path.join(cfp, \"extensions\", filename),\n os.path.join(cfp, \"packages\", filename), # legacy\n fullpath\n ]\n else:\n fullpaths = [fullpath]\n\n for fp in fullpaths:\n if os.path.isfile(fp):\n self.log.info(\"Found file %s at %s\" % (filename, fp))\n foundfile = os.path.abspath(fp)\n break # no need to try further\n else:\n failedpaths.append(fp)\n\n if foundfile:\n break # no need to try other source paths\n\n if foundfile:\n if self.dry_run:\n self.dry_run_msg(\" * %s found at %s\", filename, foundfile)\n return foundfile\n else:\n # try and download source files from specified source URLs\n if urls:\n source_urls = urls\n else:\n source_urls = []\n source_urls.extend(self.cfg['source_urls'])\n\n targetdir = os.path.join(srcpaths[0], self.name.lower()[0], self.name)\n mkdir(targetdir, parents=True)\n\n for url in source_urls:\n\n if extension:\n targetpath = os.path.join(targetdir, \"extensions\", filename)\n else:\n targetpath = os.path.join(targetdir, filename)\n\n if isinstance(url, basestring):\n if url[-1] in ['=', '/']:\n fullurl = \"%s%s\" % (url, filename)\n else:\n fullurl = \"%s/%s\" % (url, filename)\n elif isinstance(url, tuple):\n # URLs that require a suffix, e.g., SourceForge download links\n # e.g. http://sourceforge.net/projects/math-atlas/files/Stable/3.8.4/atlas3.8.4.tar.bz2/download\n fullurl = \"%s/%s/%s\" % (url[0], filename, url[1])\n else:\n self.log.warning(\"Source URL %s is of unknown type, so ignoring it.\" % url)\n continue\n\n # PyPI URLs may need to be converted due to change in format of these URLs,\n # cfr. https://bitbucket.org/pypa/pypi/issues/438\n if PYPI_PKG_URL_PATTERN in fullurl and not is_alt_pypi_url(fullurl):\n alt_url = derive_alt_pypi_url(fullurl)\n if alt_url:\n _log.debug(\"Using alternate PyPI URL for %s: %s\", fullurl, alt_url)\n fullurl = alt_url\n else:\n _log.debug(\"Failed to derive alternate PyPI URL for %s, so retaining the original\", fullurl)\n\n if self.dry_run:\n self.dry_run_msg(\" * %s will be downloaded to %s\", filename, targetpath)\n if extension and urls:\n # extensions typically have custom source URLs specified, only mention first\n self.dry_run_msg(\" (from %s, ...)\", fullurl)\n downloaded = True\n\n else:\n self.log.debug(\"Trying to download file %s from %s to %s ...\" % (filename, fullurl, targetpath))\n downloaded = False\n try:\n if download_file(filename, fullurl, targetpath):\n downloaded = True\n\n except IOError, err:\n self.log.debug(\"Failed to download %s from %s: %s\" % (filename, url, err))\n failedpaths.append(fullurl)\n continue\n\n if downloaded:\n # if fetching from source URL worked, we're done\n self.log.info(\"Successfully downloaded source file %s from %s\" % (filename, fullurl))\n return targetpath\n else:\n failedpaths.append(fullurl)\n\n if self.dry_run:\n self.dry_run_msg(\" * %s (MISSING)\", filename)\n return filename\n else:\n raise EasyBuildError(\"Couldn't find file %s anywhere, and downloading it didn't work either... \"\n \"Paths attempted (in order): %s \", filename, ', '.join(failedpaths))\n\n #\n # GETTER/SETTER UTILITY FUNCTIONS\n #\n @property\n def name(self):\n \"\"\"\n Shortcut the get the module name.\n \"\"\"\n return self.cfg['name']\n\n @property\n def version(self):\n \"\"\"\n Shortcut the get the module version.\n \"\"\"\n return self.cfg['version']\n\n @property\n def toolchain(self):\n \"\"\"\n Toolchain used to build this easyblock\n \"\"\"\n return self.cfg.toolchain\n\n @property\n def full_mod_name(self):\n \"\"\"\n Full module name (including subdirectory in module install path)\n \"\"\"\n return self.cfg.full_mod_name\n\n @property\n def short_mod_name(self):\n \"\"\"\n Short module name (not including subdirectory in module install path)\n \"\"\"\n return self.cfg.short_mod_name\n\n @property\n def mod_subdir(self):\n \"\"\"\n Subdirectory in module install path\n \"\"\"\n return self.cfg.mod_subdir\n\n @property\n def moduleGenerator(self):\n \"\"\"\n Module generator (DEPRECATED, use self.module_generator instead).\n \"\"\"\n self.log.nosupport(\"self.moduleGenerator is replaced by self.module_generator\", '2.0')\n\n #\n # DIRECTORY UTILITY FUNCTIONS\n #\n def gen_builddir(self):\n \"\"\"Generate the (unique) name for the builddir\"\"\"\n clean_name = remove_unwanted_chars(self.name)\n\n # if a toolchain version starts with a -, remove the - so prevent a -- in the path name\n tc = self.cfg['toolchain']\n tcversion = tc['version'].lstrip('-')\n lastdir = \"%s%s-%s%s\" % (self.cfg['versionprefix'], tc['name'], tcversion, self.cfg['versionsuffix'])\n\n builddir = os.path.join(os.path.abspath(build_path()), clean_name, self.version, lastdir)\n\n # make sure build dir is unique if cleanupoldbuild is False or not set\n if not self.cfg.get('cleanupoldbuild', False):\n uniq_builddir = builddir\n suff = 0\n while(os.path.isdir(uniq_builddir)):\n uniq_builddir = \"%s.%d\" % (builddir, suff)\n suff += 1\n builddir = uniq_builddir\n\n self.builddir = builddir\n self.log.info(\"Build dir set to %s\" % self.builddir)\n\n def make_builddir(self):\n \"\"\"\n Create the build directory.\n \"\"\"\n if not self.build_in_installdir:\n # self.builddir should be already set by gen_builddir()\n if not self.builddir:\n raise EasyBuildError(\"self.builddir not set, make sure gen_builddir() is called first!\")\n self.log.debug(\"Creating the build directory %s (cleanup: %s)\", self.builddir, self.cfg['cleanupoldbuild'])\n else:\n self.log.info(\"Changing build dir to %s\" % self.installdir)\n self.builddir = self.installdir\n\n self.log.info(\"Overriding 'cleanupoldinstall' (to False), 'cleanupoldbuild' (to True) \"\n \"and 'keeppreviousinstall' because we're building in the installation directory.\")\n # force cleanup before installation\n if build_option('module_only'):\n self.log.debug(\"Disabling cleanupoldbuild because we run as module-only\")\n self.cfg['cleanupoldbuild'] = False\n else:\n self.cfg['cleanupoldbuild'] = True\n\n self.cfg['keeppreviousinstall'] = False\n # avoid cleanup after installation\n self.cfg['cleanupoldinstall'] = False\n\n # always make build dir\n self.make_dir(self.builddir, self.cfg['cleanupoldbuild'])\n\n def gen_installdir(self):\n \"\"\"\n Generate the name of the installation directory.\n \"\"\"\n basepath = install_path()\n if basepath:\n self.install_subdir = ActiveMNS().det_install_subdir(self.cfg)\n self.installdir = os.path.join(os.path.abspath(basepath), self.install_subdir)\n self.log.info(\"Software install dir set to %s\" % self.installdir)\n\n mod_basepath = install_path('mod')\n mod_path_suffix = build_option('suffix_modules_path')\n self.installdir_mod = os.path.join(os.path.abspath(mod_basepath), mod_path_suffix)\n self.log.info(\"Module install dir set to %s\" % self.installdir_mod)\n else:\n raise EasyBuildError(\"Can't set installation directory\")\n\n def make_installdir(self, dontcreate=None):\n \"\"\"\n Create the installation directory.\n \"\"\"\n self.log.debug(\"Creating the installation directory %s (cleanup: %s)\" % (self.installdir,\n self.cfg['cleanupoldinstall']))\n if self.build_in_installdir:\n self.cfg['keeppreviousinstall'] = True\n dontcreate = (dontcreate is None and self.cfg['dontcreateinstalldir']) or dontcreate\n self.make_dir(self.installdir, self.cfg['cleanupoldinstall'], dontcreateinstalldir=dontcreate)\n\n def make_dir(self, dir_name, clean, dontcreateinstalldir=False):\n \"\"\"\n Create the directory.\n \"\"\"\n if os.path.exists(dir_name):\n self.log.info(\"Found old directory %s\" % dir_name)\n if self.cfg['keeppreviousinstall']:\n self.log.info(\"Keeping old directory %s (hopefully you know what you are doing)\" % dir_name)\n return\n elif clean:\n try:\n rmtree2(dir_name)\n self.log.info(\"Removed old directory %s\" % dir_name)\n except OSError, err:\n raise EasyBuildError(\"Removal of old directory %s failed: %s\", dir_name, err)\n elif build_option('module_only'):\n self.log.info(\"Not touching existing directory %s in module-only mode...\", dir_name)\n else:\n self.log.info(\"Moving existing directory %s out of the way...\", dir_name)\n try:\n timestamp = time.strftime(\"%Y%m%d-%H%M%S\")\n backupdir = \"%s.%s\" % (dir_name, timestamp)\n shutil.move(dir_name, backupdir)\n self.log.info(\"Moved old directory %s to %s\" % (dir_name, backupdir))\n except OSError, err:\n raise EasyBuildError(\"Moving old directory to backup %s %s failed: %s\", dir_name, backupdir, err)\n\n if dontcreateinstalldir:\n olddir = dir_name\n dir_name = os.path.dirname(dir_name)\n self.log.info(\"Cleaning only, no actual creation of %s, only verification/defining of dirname %s\" % (olddir, dir_name))\n if os.path.exists(dir_name):\n return\n # if not, create dir as usual\n\n mkdir(dir_name, parents=True)\n\n #\n # MODULE UTILITY FUNCTIONS\n #\n\n def make_devel_module(self, create_in_builddir=False):\n \"\"\"\n Create a develop module file which sets environment based on the build\n Usage: module load name, which loads the module you want to use. $EBDEVELNAME should then be the full path\n to the devel module file. So now you can module load $EBDEVELNAME.\n\n WARNING: you cannot unload using $EBDEVELNAME (for now: use module unload `basename $EBDEVELNAME`)\n \"\"\"\n\n self.log.info(\"Making devel module...\")\n\n # load fake module\n fake_mod_data = self.load_fake_module(purge=True)\n\n header = self.module_generator.MODULE_SHEBANG\n if header:\n header += '\\n'\n\n load_lines = []\n # capture all the EBDEVEL vars\n # these should be all the dependencies and we should load them\n recursive_unload = self.cfg['recursive_module_unload']\n for key in os.environ:\n # legacy support\n if key.startswith(DEVEL_ENV_VAR_NAME_PREFIX):\n if not key.endswith(convert_name(self.name, upper=True)):\n path = os.environ[key]\n if os.path.isfile(path):\n mod_name = path.rsplit(os.path.sep, 1)[-1]\n load_statement = self.module_generator.load_module(mod_name, recursive_unload=recursive_unload)\n load_lines.append(load_statement)\n elif key.startswith('SOFTDEVEL'):\n self.log.nosupport(\"Environment variable SOFTDEVEL* being relied on\", '2.0')\n\n env_lines = []\n for (key, val) in env.get_changes().items():\n # check if non-empty string\n # TODO: add unset for empty vars?\n if val.strip():\n env_lines.append(self.module_generator.set_environment(key, val))\n\n if create_in_builddir:\n output_dir = self.builddir\n else:\n output_dir = os.path.join(self.installdir, log_path())\n mkdir(output_dir, parents=True)\n\n filename = os.path.join(output_dir, ActiveMNS().det_devel_module_filename(self.cfg))\n self.log.debug(\"Writing devel module to %s\" % filename)\n\n txt = ''.join([header] + load_lines + env_lines)\n write_file(filename, txt)\n\n # cleanup: unload fake module, remove fake module dir\n self.clean_up_fake_module(fake_mod_data)\n\n def make_module_dep(self, unload_info=None):\n \"\"\"\n Make the dependencies for the module file.\n\n :param unload_info: dictionary with full module names as keys and module name to unload first as corr. value\n \"\"\"\n deps = []\n mns = ActiveMNS()\n unload_info = unload_info or {}\n\n # include load statements for toolchain, either directly or for toolchain dependencies\n if self.toolchain.name != DUMMY_TOOLCHAIN_NAME:\n if mns.expand_toolchain_load():\n mod_names = self.toolchain.toolchain_dep_mods\n deps.extend(mod_names)\n self.log.debug(\"Adding toolchain components as module dependencies: %s\" % mod_names)\n else:\n deps.append(self.toolchain.det_short_module_name())\n self.log.debug(\"Adding toolchain %s as a module dependency\" % deps[-1])\n\n # include load/unload statements for dependencies\n self.log.debug(\"List of deps considered to load in generated module: %s\", self.toolchain.dependencies)\n for dep in self.toolchain.dependencies:\n if dep['build_only']:\n self.log.debug(\"Skipping build dependency %s\", dep)\n else:\n modname = dep['short_mod_name']\n self.log.debug(\"Adding %s as a module dependency\" % modname)\n deps.append(modname)\n\n self.log.debug(\"List of deps to load in generated module (before excluding any): %s\", deps)\n\n # exclude dependencies that extend $MODULEPATH and form the path to the top of the module tree (if any)\n full_mod_subdir = os.path.join(self.installdir_mod, self.mod_subdir)\n init_modpaths = mns.det_init_modulepaths(self.cfg)\n top_paths = [self.installdir_mod] + [os.path.join(self.installdir_mod, p) for p in init_modpaths]\n excluded_deps = self.modules_tool.path_to_top_of_module_tree(top_paths, self.cfg.short_mod_name,\n full_mod_subdir, deps)\n self.log.debug(\"List of excluded deps: %s\", excluded_deps)\n\n deps = [d for d in deps if d not in excluded_deps]\n self.log.debug(\"List of retained deps to load in generated module: %s\" % deps)\n recursive_unload = self.cfg['recursive_module_unload']\n\n loads = []\n for dep in deps:\n unload_modules = []\n if dep in unload_info:\n unload_modules.append(unload_info[dep])\n loads.append(self.module_generator.load_module(dep, recursive_unload=recursive_unload,\n unload_modules=unload_modules))\n\n # Force unloading any other modules\n if self.cfg['moduleforceunload']:\n unloads = [self.module_generator.unload_module(d) for d in deps[::-1]]\n return ''.join(unloads) + ''.join(loads)\n else:\n return ''.join(loads)\n\n def make_module_description(self):\n \"\"\"\n Create the module description.\n \"\"\"\n return self.module_generator.get_description()\n\n def make_module_extra(self, altroot=None, altversion=None):\n \"\"\"\n Set extra stuff in module file, e.g. $EBROOT*, $EBVERSION*, etc.\n\n :param altroot: path to use to define $EBROOT*\n :param altversion: version to use to define $EBVERSION*\n \"\"\"\n lines = ['']\n\n env_name = convert_name(self.name, upper=True)\n\n # $EBROOT\n root_envvar = ROOT_ENV_VAR_NAME_PREFIX + env_name\n if altroot:\n set_root_envvar = self.module_generator.set_environment(root_envvar, altroot)\n else:\n set_root_envvar = self.module_generator.set_environment(root_envvar, '', relpath=True)\n lines.append(set_root_envvar)\n\n # $EBVERSION\n version_envvar = VERSION_ENV_VAR_NAME_PREFIX + env_name\n lines.append(self.module_generator.set_environment(version_envvar, altversion or self.version))\n\n # $EBDEVEL\n devel_path = os.path.join(log_path(), ActiveMNS().det_devel_module_filename(self.cfg))\n devel_path_envvar = DEVEL_ENV_VAR_NAME_PREFIX + env_name\n lines.append(self.module_generator.set_environment(devel_path_envvar, devel_path, relpath=True))\n\n lines.append('\\n')\n for (key, value) in self.cfg['modextravars'].items():\n lines.append(self.module_generator.set_environment(key, value))\n\n for (key, value) in self.cfg['modextrapaths'].items():\n if isinstance(value, basestring):\n value = [value]\n elif not isinstance(value, (tuple, list)):\n raise EasyBuildError(\"modextrapaths dict value %s (type: %s) is not a list or tuple\",\n value, type(value))\n lines.append(self.module_generator.prepend_paths(key, value))\n\n if self.cfg['modloadmsg']:\n lines.append(self.module_generator.msg_on_load(self.cfg['modloadmsg']))\n\n if self.cfg['modtclfooter']:\n if isinstance(self.module_generator, ModuleGeneratorTcl):\n self.log.debug(\"Including Tcl footer in module: %s\", self.cfg['modtclfooter'])\n lines.extend([self.cfg['modtclfooter'], '\\n'])\n else:\n self.log.warning(\"Not including footer in Tcl syntax in non-Tcl module file: %s\",\n self.cfg['modtclfooter'])\n\n if self.cfg['modluafooter']:\n if isinstance(self.module_generator, ModuleGeneratorLua):\n self.log.debug(\"Including Lua footer in module: %s\", self.cfg['modluafooter'])\n lines.extend([self.cfg['modluafooter'], '\\n'])\n else:\n self.log.warning(\"Not including footer in Lua syntax in non-Lua module file: %s\",\n self.cfg['modluafooter'])\n\n for (key, value) in self.cfg['modaliases'].items():\n lines.append(self.module_generator.set_alias(key, value))\n\n txt = ''.join(lines)\n self.log.debug(\"make_module_extra added this: %s\", txt)\n\n return txt\n\n def make_module_extra_extensions(self):\n \"\"\"\n Sets optional variables for extensions.\n \"\"\"\n # add stuff specific to individual extensions\n lines = [self.module_extra_extensions]\n\n # set environment variable that specifies list of extensions\n if self.exts_all:\n exts_list = ','.join(['%s-%s' % (ext['name'], ext.get('version', '')) for ext in self.exts_all])\n env_var_name = convert_name(self.name, upper=True)\n lines.append(self.module_generator.set_environment('EBEXTSLIST%s' % env_var_name, exts_list))\n\n return ''.join(lines)\n\n def make_module_footer(self):\n \"\"\"\n Insert a footer section in the module file, primarily meant for contextual information\n \"\"\"\n footer = [self.module_generator.comment(\"Built with EasyBuild version %s\" % VERBOSE_VERSION)]\n\n # add extra stuff for extensions (if any)\n if self.cfg['exts_list']:\n footer.append(self.make_module_extra_extensions())\n\n # include modules footer if one is specified\n if self.modules_footer is not None:\n self.log.debug(\"Including specified footer into module: '%s'\" % self.modules_footer)\n footer.append(self.modules_footer)\n\n return ''.join(footer)\n\n def make_module_extend_modpath(self):\n \"\"\"\n Include prepend-path statements for extending $MODULEPATH.\n \"\"\"\n txt = ''\n if self.cfg['include_modpath_extensions']:\n modpath_exts = ActiveMNS().det_modpath_extensions(self.cfg)\n self.log.debug(\"Including module path extensions returned by module naming scheme: %s\", modpath_exts)\n full_path_modpath_extensions = [os.path.join(self.installdir_mod, ext) for ext in modpath_exts]\n # module path extensions must exist, otherwise loading this module file will fail\n for modpath_extension in full_path_modpath_extensions:\n mkdir(modpath_extension, parents=True)\n txt = self.module_generator.use(full_path_modpath_extensions)\n\n # add user-specific module path; use statement will be guarded so no need to create the directories\n user_modpath = build_option('subdir_user_modules')\n if user_modpath:\n user_modpath_exts = ActiveMNS().det_user_modpath_extensions(self.cfg)\n user_modpath_exts = [os.path.join(user_modpath, e) for e in user_modpath_exts]\n self.log.debug(\"Including user module path extensions returned by naming scheme: %s\", user_modpath_exts)\n txt += self.module_generator.use(user_modpath_exts, prefix=self.module_generator.getenv_cmd('HOME'),\n guarded=True)\n else:\n self.log.debug(\"Not including module path extensions, as specified.\")\n return txt\n\n def make_module_req(self):\n \"\"\"\n Generate the environment-variables to run the module.\n \"\"\"\n requirements = self.make_module_req_guess()\n\n lines = []\n if os.path.isdir(self.installdir):\n try:\n os.chdir(self.installdir)\n except OSError, err:\n raise EasyBuildError(\"Failed to change to %s: %s\", self.installdir, err)\n\n lines.append('\\n')\n\n if self.dry_run:\n self.dry_run_msg(\"List of paths that would be searched and added to module file:\\n\")\n note = \"note: glob patterns are not expanded and existence checks \"\n note += \"for paths are skipped for the statements below due to dry run\"\n lines.append(self.module_generator.comment(note))\n\n for key in sorted(requirements):\n if self.dry_run:\n self.dry_run_msg(\" $%s: %s\" % (key, ', '.join(requirements[key])))\n reqs = requirements[key]\n if isinstance(reqs, basestring):\n self.log.warning(\"Hoisting string value %s into a list before iterating over it\", reqs)\n reqs = [reqs]\n\n for path in reqs:\n # only use glob if the string is non-empty\n if path and not self.dry_run:\n paths = sorted(glob.glob(path))\n else:\n # empty string is a valid value here (i.e. to prepend the installation prefix, cfr $CUDA_HOME)\n paths = [path]\n\n lines.append(self.module_generator.prepend_paths(key, paths))\n if self.dry_run:\n self.dry_run_msg('')\n try:\n os.chdir(self.orig_workdir)\n except OSError, err:\n raise EasyBuildError(\"Failed to change back to %s: %s\", self.orig_workdir, err)\n\n return ''.join(lines)\n\n def make_module_req_guess(self):\n \"\"\"\n A dictionary of possible directories to look for.\n \"\"\"\n return {\n 'PATH': ['bin', 'sbin'],\n 'LD_LIBRARY_PATH': ['lib', 'lib32', 'lib64'],\n 'LIBRARY_PATH': ['lib', 'lib32', 'lib64'],\n 'CPATH': ['include'],\n 'MANPATH': ['man', os.path.join('share', 'man')],\n 'PKG_CONFIG_PATH': [os.path.join(x, 'pkgconfig') for x in ['lib', 'lib32', 'lib64', 'share']],\n 'ACLOCAL_PATH': [os.path.join('share', 'aclocal')],\n 'CLASSPATH': ['*.jar'],\n }\n\n def load_module(self, mod_paths=None, purge=True):\n \"\"\"\n Load module for this software package/version, after purging all currently loaded modules.\n \"\"\"\n # self.full_mod_name might not be set (e.g. during unit tests)\n if self.full_mod_name is not None:\n if mod_paths is None:\n mod_paths = []\n all_mod_paths = mod_paths + ActiveMNS().det_init_modulepaths(self.cfg)\n\n # for flat module naming schemes, we can load the module directly;\n # for non-flat (hierarchical) module naming schemes, we may need to load the toolchain module first\n # to update $MODULEPATH such that the module can be loaded using the short module name\n mods = [self.short_mod_name]\n if self.mod_subdir and self.toolchain.name != DUMMY_TOOLCHAIN_NAME:\n mods.insert(0, self.toolchain.det_short_module_name())\n\n self.modules_tool.load(mods, mod_paths=all_mod_paths, purge=purge, init_env=self.initial_environ)\n else:\n self.log.warning(\"Not loading module, since self.full_mod_name is not set.\")\n\n def load_fake_module(self, purge=False):\n \"\"\"\n Create and load fake module.\n \"\"\"\n # take a copy of the current environment before loading the fake module, so we can restore it\n env = copy.deepcopy(os.environ)\n\n # create fake module\n fake_mod_path = self.make_module_step(fake=True)\n\n # load fake module\n self.modules_tool.prepend_module_path(os.path.join(fake_mod_path, self.mod_subdir))\n self.load_module(purge=purge)\n\n return (fake_mod_path, env)\n\n def clean_up_fake_module(self, fake_mod_data):\n \"\"\"\n Clean up fake module.\n \"\"\"\n fake_mod_path, env = fake_mod_data\n # unload module and remove temporary module directory\n # self.short_mod_name might not be set (e.g. during unit tests)\n if fake_mod_path and self.short_mod_name is not None:\n try:\n self.modules_tool.unload([self.short_mod_name])\n self.modules_tool.remove_module_path(os.path.join(fake_mod_path, self.mod_subdir))\n rmtree2(os.path.dirname(fake_mod_path))\n except OSError, err:\n raise EasyBuildError(\"Failed to clean up fake module dir %s: %s\", fake_mod_path, err)\n elif self.short_mod_name is None:\n self.log.warning(\"Not unloading module, since self.short_mod_name is not set.\")\n\n # restore original environment\n restore_env(env)\n\n def load_dependency_modules(self):\n \"\"\"Load dependency modules.\"\"\"\n self.modules_tool.load([ActiveMNS().det_full_module_name(dep) for dep in self.cfg.dependencies()])\n\n #\n # EXTENSIONS UTILITY FUNCTIONS\n #\n\n def prepare_for_extensions(self):\n \"\"\"\n Also do this before (eg to set the template)\n \"\"\"\n pass\n\n def skip_extensions(self):\n \"\"\"\n Called when self.skip is True\n - use this to detect existing extensions and to remove them from self.exts\n - based on initial R version\n \"\"\"\n # disabling templating is required here to support legacy string templates like name/version\n self.cfg.enable_templating = False\n exts_filter = self.cfg['exts_filter']\n self.cfg.enable_templating = True\n\n if not exts_filter or len(exts_filter) == 0:\n raise EasyBuildError(\"Skipping of extensions, but no exts_filter set in easyconfig\")\n elif isinstance(exts_filter, basestring) or len(exts_filter) != 2:\n raise EasyBuildError('exts_filter should be a list or tuple of (\"command\",\"input\")')\n cmdtmpl = exts_filter[0]\n cmdinputtmpl = exts_filter[1]\n if not self.exts:\n self.exts = []\n\n res = []\n for ext in self.exts:\n name = ext['name']\n if 'options' in ext and 'modulename' in ext['options']:\n modname = ext['options']['modulename']\n else:\n modname = name\n tmpldict = {\n 'ext_name': modname,\n 'ext_version': ext.get('version'),\n 'src': ext.get('source'),\n }\n\n try:\n cmd = cmdtmpl % tmpldict\n except KeyError, err:\n msg = \"KeyError occured on completing extension filter template: %s; \"\n msg += \"'name'/'version' keys are no longer supported, should use 'ext_name'/'ext_version' instead\"\n self.log.nosupport(msg, '2.0')\n\n if cmdinputtmpl:\n stdin = cmdinputtmpl % tmpldict\n (cmdstdouterr, ec) = run_cmd(cmd, log_all=False, log_ok=False, simple=False, inp=stdin, regexp=False)\n else:\n (cmdstdouterr, ec) = run_cmd(cmd, log_all=False, log_ok=False, simple=False, regexp=False)\n self.log.info(\"exts_filter result %s %s\", cmdstdouterr, ec)\n if ec:\n self.log.info(\"Not skipping %s\" % name)\n self.log.debug(\"exit code: %s, stdout/err: %s\" % (ec, cmdstdouterr))\n res.append(ext)\n else:\n self.log.info(\"Skipping %s\" % name)\n self.exts = res\n\n #\n # MISCELLANEOUS UTILITY FUNCTIONS\n #\n\n def guess_start_dir(self):\n \"\"\"\n Return the directory where to start the whole configure/make/make install cycle from\n - typically self.src[0]['finalpath']\n - start_dir option\n -- if abspath: use that\n -- else, treat it as subdir for regular procedure\n \"\"\"\n start_dir = ''\n # do not use the specified 'start_dir' when running as --module-only as\n # the directory will not exist (extract_step is skipped)\n if self.cfg['start_dir'] and not build_option('module_only'):\n start_dir = self.cfg['start_dir']\n\n if not os.path.isabs(start_dir):\n if len(self.src) > 0 and not self.skip and self.src[0]['finalpath']:\n topdir = self.src[0]['finalpath']\n else:\n topdir = self.builddir\n\n # during dry run, use subdirectory that would likely result from unpacking\n if self.dry_run and os.path.samefile(topdir, self.builddir):\n topdir = os.path.join(self.builddir, '%s-%s' % (self.name, self.version))\n self.log.info(\"Modified parent directory of start dir in dry run mode to likely path %s\", topdir)\n # make sure start_dir subdir exists (cfr. check below)\n mkdir(os.path.join(topdir, start_dir), parents=True)\n\n abs_start_dir = os.path.join(topdir, start_dir)\n if topdir.endswith(start_dir) and not os.path.exists(abs_start_dir):\n self.cfg['start_dir'] = topdir\n else:\n if os.path.exists(abs_start_dir):\n self.cfg['start_dir'] = abs_start_dir\n else:\n raise EasyBuildError(\"Specified start dir %s does not exist\", abs_start_dir)\n\n self.log.info(\"Using %s as start dir\", self.cfg['start_dir'])\n\n try:\n os.chdir(self.cfg['start_dir'])\n self.log.debug(\"Changed to real build directory %s (start_dir)\" % self.cfg['start_dir'])\n except OSError, err:\n raise EasyBuildError(\"Can't change to real build directory %s: %s\", self.cfg['start_dir'], err)\n\n def handle_iterate_opts(self):\n \"\"\"Handle options relevant during iterated part of build/install procedure.\"\"\"\n\n # disable templating in this function, since we're messing about with values in self.cfg\n self.cfg.enable_templating = False\n\n # handle configure/build/install options that are specified as lists\n # set first element to be used, keep track of list in self.iter_opts\n # this will only be done during first iteration, since after that the options won't be lists anymore\n for opt in ITERATE_OPTIONS:\n # keep track of list, supply first element as first option to handle\n if isinstance(self.cfg[opt], (list, tuple)):\n self.iter_opts[opt] = self.cfg[opt] # copy\n self.log.debug(\"Found list for %s: %s\", opt, self.iter_opts[opt])\n\n if self.iter_opts:\n self.log.info(\"Current iteration index: %s\", self.iter_idx)\n\n # pop first element from all *_list options as next value to use\n for opt in self.iter_opts:\n if len(self.iter_opts[opt]) > self.iter_idx:\n self.cfg[opt] = self.iter_opts[opt][self.iter_idx]\n else:\n self.cfg[opt] = '' # empty list => empty option as next value\n self.log.debug(\"Next value for %s: %s\" % (opt, str(self.cfg[opt])))\n\n # re-enable templating before self.cfg values are used\n self.cfg.enable_templating = True\n\n # prepare for next iteration (if any)\n self.iter_idx += 1\n\n def restore_iterate_opts(self):\n \"\"\"Restore options that were iterated over\"\"\"\n # disable templating, since we're messing about with values in self.cfg\n self.cfg.enable_templating = False\n\n for opt in self.iter_opts:\n self.cfg[opt] = self.iter_opts[opt]\n self.log.debug(\"Restored value of '%s' that was iterated over: %s\", opt, self.cfg[opt])\n\n # re-enable templating before self.cfg values are used\n self.cfg.enable_templating = True\n\n def det_iter_cnt(self):\n \"\"\"Determine iteration count based on configure/build/install options that may be lists.\"\"\"\n iter_cnt = max([1] + [len(self.cfg[opt]) for opt in ITERATE_OPTIONS\n if isinstance(self.cfg[opt], (list, tuple))])\n return iter_cnt\n\n #\n # STEP FUNCTIONS\n #\n def check_readiness_step(self):\n \"\"\"\n Verify if all is ok to start build.\n \"\"\"\n # set level of parallelism for build\n par = build_option('parallel')\n if self.cfg['parallel']:\n if par is None:\n par = self.cfg['parallel']\n self.log.debug(\"Desired parallelism specified via 'parallel' easyconfig parameter: %s\", par)\n else:\n par = min(int(par), int(self.cfg['parallel']))\n self.log.debug(\"Desired parallelism: minimum of 'parallel' build option/easyconfig parameter: %s\", par)\n else:\n self.log.debug(\"Desired parallelism specified via 'parallel' build option: %s\", par)\n\n self.cfg['parallel'] = det_parallelism(par=par, maxpar=self.cfg['maxparallel'])\n self.log.info(\"Setting parallelism: %s\" % self.cfg['parallel'])\n\n # check whether modules are loaded\n loadedmods = self.modules_tool.loaded_modules()\n if len(loadedmods) > 0:\n self.log.warning(\"Loaded modules detected: %s\" % loadedmods)\n\n # do all dependencies have a toolchain version?\n self.toolchain.add_dependencies(self.cfg.dependencies())\n if not len(self.cfg.dependencies()) == len(self.toolchain.dependencies):\n self.log.debug(\"dep %s (%s)\" % (len(self.cfg.dependencies()), self.cfg.dependencies()))\n self.log.debug(\"tc.dep %s (%s)\" % (len(self.toolchain.dependencies), self.toolchain.dependencies))\n raise EasyBuildError('Not all dependencies have a matching toolchain version')\n\n # check if the application is not loaded at the moment\n (root, env_var) = get_software_root(self.name, with_env_var=True)\n if root:\n raise EasyBuildError(\"Module is already loaded (%s is set), installation cannot continue.\", env_var)\n\n # check if main install needs to be skipped\n # - if a current module can be found, skip is ok\n # -- this is potentially very dangerous\n if self.cfg['skip']:\n if self.modules_tool.exist([self.full_mod_name], skip_avail=True)[0]:\n self.skip = True\n self.log.info(\"Module %s found.\" % self.full_mod_name)\n self.log.info(\"Going to skip actual main build and potential existing extensions. Expert only.\")\n else:\n self.log.info(\"No module %s found. Not skipping anything.\" % self.full_mod_name)\n\n # remove existing module file under --force (but only if --skip is not used)\n elif build_option('force') or build_option('rebuild'):\n if os.path.exists(self.mod_filepath):\n self.log.info(\"Removing existing module file %s\", self.mod_filepath)\n remove_file(self.mod_filepath)\n\n def fetch_step(self, skip_checksums=False):\n \"\"\"Fetch source files and patches (incl. extensions).\"\"\"\n\n # check EasyBuild version\n easybuild_version = self.cfg['easybuild_version']\n if not easybuild_version:\n self.log.warn(\"Easyconfig does not specify an EasyBuild-version (key 'easybuild_version')! \"\n \"Assuming the latest version\")\n else:\n if LooseVersion(easybuild_version) < VERSION:\n self.log.warn(\"EasyBuild-version %s is older than the currently running one. Proceed with caution!\",\n easybuild_version)\n elif LooseVersion(easybuild_version) > VERSION:\n raise EasyBuildError(\"EasyBuild-version %s is newer than the currently running one. Aborting!\",\n easybuild_version)\n\n if self.dry_run:\n\n self.dry_run_msg(\"Available download URLs for sources/patches:\")\n if self.cfg['source_urls']:\n for source_url in self.cfg['source_urls']:\n self.dry_run_msg(\" * %s/$source\", source_url)\n else:\n self.dry_run_msg('(none)')\n\n # actual list of sources is printed via _obtain_file_dry_run method\n self.dry_run_msg(\"\\nList of sources:\")\n\n # fetch sources\n if self.cfg['sources']:\n self.fetch_sources(self.cfg['sources'], checksums=self.cfg['checksums'])\n else:\n self.log.info('no sources provided')\n\n if self.dry_run:\n # actual list of patches is printed via _obtain_file_dry_run method\n self.dry_run_msg(\"\\nList of patches:\")\n\n # fetch patches\n if self.cfg['patches']:\n if isinstance(self.cfg['checksums'], (list, tuple)):\n # if checksums are provided as a list, first entries are assumed to be for sources\n patches_checksums = self.cfg['checksums'][len(self.cfg['sources']):]\n else:\n patches_checksums = self.cfg['checksums']\n self.fetch_patches(checksums=patches_checksums)\n else:\n self.log.info('no patches provided')\n if self.dry_run:\n self.dry_run_msg('(none)')\n\n # compute checksums for all source and patch files\n if not (skip_checksums or self.dry_run):\n for fil in self.src + self.patches:\n check_sum = compute_checksum(fil['path'], checksum_type=DEFAULT_CHECKSUM)\n fil[DEFAULT_CHECKSUM] = check_sum\n self.log.info(\"%s checksum for %s: %s\" % (DEFAULT_CHECKSUM, fil['path'], fil[DEFAULT_CHECKSUM]))\n\n # fetch extensions\n if self.cfg['exts_list']:\n self.exts = self.fetch_extension_sources()\n\n # create parent dirs in install and modules path already\n # this is required when building in parallel\n mod_symlink_paths = ActiveMNS().det_module_symlink_paths(self.cfg)\n parent_subdir = os.path.dirname(self.install_subdir)\n pardirs = [\n self.installdir,\n os.path.join(self.installdir_mod, parent_subdir),\n ]\n for mod_symlink_path in mod_symlink_paths:\n pardirs.append(os.path.join(install_path('mod'), mod_symlink_path, parent_subdir))\n\n self.log.info(\"Checking dirs that need to be created: %s\" % pardirs)\n for pardir in pardirs:\n mkdir(pardir, parents=True)\n\n def checksum_step(self):\n \"\"\"Verify checksum of sources and patches, if a checksum is available.\"\"\"\n for fil in self.src + self.patches:\n if self.dry_run:\n # dry run mode: only report checksums, don't actually verify them\n filename = os.path.basename(fil['path'])\n expected_checksum = fil['checksum'] or '(none)'\n self.dry_run_msg(\"* expected checksum for %s: %s\", filename, expected_checksum)\n else:\n if not verify_checksum(fil['path'], fil['checksum']):\n raise EasyBuildError(\"Checksum verification for %s using %s failed.\", fil['path'], fil['checksum'])\n else:\n self.log.info(\"Checksum verification for %s using %s passed.\" % (fil['path'], fil['checksum']))\n\n def extract_step(self):\n \"\"\"\n Unpack the source files.\n \"\"\"\n for src in self.src:\n self.log.info(\"Unpacking source %s\" % src['name'])\n srcdir = extract_file(src['path'], self.builddir, cmd=src['cmd'], extra_options=self.cfg['unpack_options'])\n if srcdir:\n self.src[self.src.index(src)]['finalpath'] = srcdir\n else:\n raise EasyBuildError(\"Unpacking source %s failed\", src['name'])\n\n def patch_step(self, beginpath=None):\n \"\"\"\n Apply the patches\n \"\"\"\n for patch in self.patches:\n self.log.info(\"Applying patch %s\" % patch['name'])\n\n # patch source at specified index (first source if not specified)\n srcind = patch.get('source', 0)\n # if patch level is specified, use that (otherwise let apply_patch derive patch level)\n level = patch.get('level', None)\n # determine suffix of source path to apply patch in (if any)\n srcpathsuffix = patch.get('sourcepath', patch.get('copy', ''))\n # determine whether 'patch' file should be copied rather than applied\n copy_patch = 'copy' in patch and not 'sourcepath' in patch\n\n self.log.debug(\"Source index: %s; patch level: %s; source path suffix: %s; copy patch: %s\",\n srcind, level, srcpathsuffix, copy)\n\n if beginpath is None:\n try:\n beginpath = self.src[srcind]['finalpath']\n self.log.debug(\"Determine begin path for patch %s: %s\" % (patch['name'], beginpath))\n except IndexError, err:\n raise EasyBuildError(\"Can't apply patch %s to source at index %s of list %s: %s\",\n patch['name'], srcind, self.src, err)\n else:\n self.log.debug(\"Using specified begin path for patch %s: %s\" % (patch['name'], beginpath))\n\n # detect partial overlap between paths\n src = os.path.abspath(weld_paths(beginpath, srcpathsuffix))\n self.log.debug(\"Applying patch %s in path %s\", patch, src)\n\n if not apply_patch(patch['path'], src, copy=copy_patch, level=level):\n raise EasyBuildError(\"Applying patch %s failed\", patch['name'])\n\n def prepare_step(self, start_dir=True):\n \"\"\"\n Pre-configure step. Set's up the builddir just before starting configure\n\n :param start_dir: guess start directory based on unpacked sources\n \"\"\"\n if self.dry_run:\n self.dry_run_msg(\"Defining build environment, based on toolchain (options) and specified dependencies...\\n\")\n\n # clean environment, undefine any unwanted environment variables that may be harmful\n self.cfg['unwanted_env_vars'] = env.unset_env_vars(self.cfg['unwanted_env_vars'])\n\n # list of paths to include in RPATH filter;\n # only include builddir if we're not building in installation directory\n self.rpath_filter_dirs.append(tempfile.gettempdir())\n if not self.build_in_installdir:", "answers": [" self.rpath_filter_dirs.append(self.builddir)"], "length": 6017, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "9ac0e542-5fe0-4104-a905-10d9d2a48e28", "reasoning": "The prepare_step method is setting up the build environment. After adding the temporary directory to the RPATH filter, it checks if the build is not happening inside the installation directory. In that case, the build directory itself should also be added to the RPATH filter. Therefore, the next line adds self.builddir to self.rpath_filter_dirs.", "reasoning_model_answer": "self.rpath_filter_dirs.append(self.builddir)", "assistant_with_reasoning": "\nThe prepare_step method is setting up the build environment. After adding the temporary directory to the RPATH filter, it checks if the build is not happening inside the installation directory. In that case, the build directory itself should also be added to the RPATH filter. Therefore, the next line adds self.builddir to self.rpath_filter_dirs.\n\nself.rpath_filter_dirs.append(self.builddir)", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.664, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 48004, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "self.rpath_filter_dirs.append(self.builddir)", "score": 0.88, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\nusing System.Net;\n\nusing Server;\nusing Server.Accounting;\nusing Server.ContextMenus;\nusing Server.Events;\nusing Server.Gumps;\nusing Server.Items;\nusing Server.Mobiles;\nusing Server.Prompts;\nusing Server.Targeting;\nusing CV = Server.ClientVersion;\nusing CT = Server.ClientType;\n\nnamespace Server.Network\n{\n\tpublic enum MessageType\n\t{\n\t\tRegular = 0x00,\n\t\tSystem = 0x01,\n\t\tEmote = 0x02,\n\t\tLabel = 0x06,\n\t\tFocus = 0x07,\n\t\tWhisper = 0x08,\n\t\tYell = 0x09,\n\t\tSpell = 0x0A,\n\n\t\tGuild = 0x0D,\n\t\tAlliance = 0x0E,\n\t\tGM = 0x0F,\n\n\t\tEncoded = 0xC0\n\t}\n\n\tpublic static class PacketHandlers\n\t{\n\t\tprivate static readonly ILog log = LogManager.GetLogger( System.Reflection.MethodBase.GetCurrentMethod().DeclaringType );\n\n\t\tprivate static readonly PacketHandler[] m_ExtendedHandlersLow;\n\t\tprivate static readonly Dictionary m_ExtendedHandlersHigh;\n\n\t\tprivate static readonly EncodedPacketHandler[] m_EncodedHandlersLow;\n\t\tprivate static readonly Dictionary m_EncodedHandlersHigh;\n\n\t\tpublic static PacketHandler[] Handlers { get; }\n\n\t\tstatic PacketHandlers()\n\t\t{\n\t\t\tHandlers = new PacketHandler[0x100];\n\n\t\t\tm_ExtendedHandlersLow = new PacketHandler[0x100];\n\t\t\tm_ExtendedHandlersHigh = new Dictionary();\n\n\t\t\tm_EncodedHandlersLow = new EncodedPacketHandler[0x100];\n\t\t\tm_EncodedHandlersHigh = new Dictionary();\n\n\t\t\tRegister( 0x00, 104, false, new OnPacketReceive( CreateCharacter ) );\n\t\t\tRegister( 0x01, 5, false, new OnPacketReceive( Disconnect ) );\n\t\t\tRegister( 0x02, 7, true, new OnPacketReceive( MovementReq ) );\n\t\t\tRegister( 0x03, 0, true, new OnPacketReceive( AsciiSpeech ) );\n\t\t\tRegister( 0x04, 2, true, new OnPacketReceive( GodModeRequest ) );\n\t\t\tRegister( 0x05, 5, true, new OnPacketReceive( AttackReq ) );\n\t\t\tRegister( 0x06, 5, true, new OnPacketReceive( UseReq ) );\n\t\t\tRegister( 0x07, 7, true, new OnPacketReceive( LiftReq ) );\n\t\t\tRegister( 0x08, 15, true, new OnPacketReceive( DropReq ) );\n\t\t\tRegister( 0x09, 5, true, new OnPacketReceive( LookReq ) );\n\t\t\tRegister( 0x0A, 11, true, new OnPacketReceive( Edit ) );\n\t\t\tRegister( 0x12, 0, true, new OnPacketReceive( TextCommand ) );\n\t\t\tRegister( 0x13, 10, true, new OnPacketReceive( EquipReq ) );\n\t\t\tRegister( 0x14, 6, true, new OnPacketReceive( ChangeZ ) );\n\t\t\tRegister( 0x22, 3, true, new OnPacketReceive( Resynchronize ) );\n\t\t\tRegister( 0x2C, 2, true, new OnPacketReceive( DeathStatusResponse ) );\n\t\t\tRegister( 0x34, 10, true, new OnPacketReceive( MobileQuery ) );\n\t\t\tRegister( 0x3A, 0, true, new OnPacketReceive( ChangeSkillLock ) );\n\t\t\tRegister( 0x3B, 0, true, new OnPacketReceive( VendorBuyReply ) );\n\t\t\tRegister( 0x47, 11, true, new OnPacketReceive( NewTerrain ) );\n\t\t\tRegister( 0x48, 73, true, new OnPacketReceive( NewAnimData ) );\n\t\t\tRegister( 0x58, 106, true, new OnPacketReceive( NewRegion ) );\n\t\t\tRegister( 0x5D, 73, false, new OnPacketReceive( PlayCharacter ) );\n\t\t\tRegister( 0x61, 9, true, new OnPacketReceive( DeleteStatic ) );\n\t\t\tRegister( 0x6C, 19, true, new OnPacketReceive( TargetResponse ) );\n\t\t\tRegister( 0x6F, 0, true, new OnPacketReceive( SecureTrade ) );\n\t\t\tRegister( 0x72, 5, true, new OnPacketReceive( SetWarMode ) );\n\t\t\tRegister( 0x73, 2, false, new OnPacketReceive( PingReq ) );\n\t\t\tRegister( 0x75, 35, true, new OnPacketReceive( RenameRequest ) );\n\t\t\tRegister( 0x79, 9, true, new OnPacketReceive( ResourceQuery ) );\n\t\t\tRegister( 0x7E, 2, true, new OnPacketReceive( GodviewQuery ) );\n\t\t\tRegister( 0x7D, 13, true, new OnPacketReceive( MenuResponse ) );\n\t\t\tRegister( 0x80, 62, false, new OnPacketReceive( AccountLogin ) );\n\t\t\tRegister( 0x83, 39, false, new OnPacketReceive( DeleteCharacter ) );\n\t\t\tRegister( 0x8D, 0, false, new OnPacketReceive( CreateCharacterEnhanced ) );\n\t\t\tRegister( 0x91, 65, false, new OnPacketReceive( GameLogin ) );\n\t\t\tRegister( 0x95, 9, true, new OnPacketReceive( HuePickerResponse ) );\n\t\t\tRegister( 0x96, 0, true, new OnPacketReceive( GameCentralMoniter ) );\n\t\t\tRegister( 0x98, 0, true, new OnPacketReceive( MobileNameRequest ) );\n\t\t\tRegister( 0x9A, 0, true, new OnPacketReceive( AsciiPromptResponse ) );\n\t\t\tRegister( 0x9B, 258, true, new OnPacketReceive( HelpRequest ) );\n\t\t\tRegister( 0x9D, 51, true, new OnPacketReceive( GMSingle ) );\n\t\t\tRegister( 0x9F, 0, true, new OnPacketReceive( VendorSellReply ) );\n\t\t\tRegister( 0xA0, 3, false, new OnPacketReceive( PlayServer ) );\n\t\t\tRegister( 0xA4, 149, false, new OnPacketReceive( SystemInfo ) );\n\t\t\tRegister( 0xA7, 4, true, new OnPacketReceive( RequestScrollWindow ) );\n\t\t\tRegister( 0xAD, 0, true, new OnPacketReceive( UnicodeSpeech ) );\n\t\t\tRegister( 0xB1, 0, true, new OnPacketReceive( DisplayGumpResponse ) );\n\t\t\tRegister( 0xB5, 64, true, new OnPacketReceive( ChatRequest ) );\n\t\t\tRegister( 0xB6, 9, true, new OnPacketReceive( ObjectHelpRequest ) );\n\t\t\tRegister( 0xB8, 0, true, new OnPacketReceive( ProfileReq ) );\n\t\t\tRegister( 0xBB, 9, false, new OnPacketReceive( AccountID ) );\n\t\t\tRegister( 0xBD, 0, false, new OnPacketReceive( ClientVersion ) );\n\t\t\tRegister( 0xBE, 0, true, new OnPacketReceive( AssistVersion ) );\n\t\t\tRegister( 0xBF, 0, true, new OnPacketReceive( ExtendedCommand ) );\n\t\t\tRegister( 0xC2, 0, true, new OnPacketReceive( UnicodePromptResponse ) );\n\t\t\tRegister( 0xC8, 2, true, new OnPacketReceive( SetUpdateRange ) );\n\t\t\tRegister( 0xC9, 6, true, new OnPacketReceive( TripTime ) );\n\t\t\tRegister( 0xCA, 6, true, new OnPacketReceive( UTripTime ) );\n\t\t\tRegister( 0xCF, 0, false, new OnPacketReceive( AccountLogin ) );\n\t\t\tRegister( 0xD0, 0, true, new OnPacketReceive( ConfigurationFile ) );\n\t\t\tRegister( 0xD1, 2, true, new OnPacketReceive( LogoutReq ) );\n\t\t\tRegister( 0xD6, 0, true, new OnPacketReceive( BatchQueryProperties ) );\n\t\t\tRegister( 0xD7, 0, true, new OnPacketReceive( EncodedCommand ) );\n\t\t\tRegister( 0xE1, 0, false, new OnPacketReceive( ClientType ) );\n\t\t\tRegister( 0xEC, 0, false, new OnPacketReceive( EquipMacro ) );\n\t\t\tRegister( 0xED, 0, false, new OnPacketReceive( UnequipMacro ) );\n\t\t\tRegister( 0xEF, 21, false, new OnPacketReceive( LoginServerSeed ) );\n\t\t\tRegister( 0xF8, 106, false, new OnPacketReceive( CreateCharacterNew ) );\n\n\t\t\tRegisterExtended( 0x05, false, new OnPacketReceive( ScreenSize ) );\n\t\t\tRegisterExtended( 0x06, true, new OnPacketReceive( PartyMessage ) );\n\t\t\tRegisterExtended( 0x07, true, new OnPacketReceive( QuestArrow ) );\n\t\t\tRegisterExtended( 0x09, true, new OnPacketReceive( DisarmRequest ) );\n\t\t\tRegisterExtended( 0x0A, true, new OnPacketReceive( StunRequest ) );\n\t\t\tRegisterExtended( 0x0B, false, new OnPacketReceive( Language ) );\n\t\t\tRegisterExtended( 0x0C, true, new OnPacketReceive( CloseStatus ) );\n\t\t\tRegisterExtended( 0x0E, true, new OnPacketReceive( Animate ) );\n\t\t\tRegisterExtended( 0x0F, false, new OnPacketReceive( Empty ) ); // What's this?\n\t\t\tRegisterExtended( 0x10, true, new OnPacketReceive( QueryProperties ) );\n\t\t\tRegisterExtended( 0x13, true, new OnPacketReceive( ContextMenuRequest ) );\n\t\t\tRegisterExtended( 0x15, true, new OnPacketReceive( ContextMenuResponse ) );\n\t\t\tRegisterExtended( 0x1A, true, new OnPacketReceive( StatLockChange ) );\n\t\t\tRegisterExtended( 0x1C, true, new OnPacketReceive( CastSpell ) );\n\t\t\tRegisterExtended( 0x24, false, new OnPacketReceive( UnhandledBF ) );\n\t\t\tRegisterExtended( 0x2C, true, new OnPacketReceive( TargetedItemUse ) );\n\t\t\tRegisterExtended( 0x2D, true, new OnPacketReceive( TargetedCastSpell ) );\n\t\t\tRegisterExtended( 0x2E, true, new OnPacketReceive( TargetedSkillUse ) );\n\t\t\tRegisterExtended( 0x30, true, new OnPacketReceive( TargetByResourceMacro ) );\n\t\t\tRegisterExtended( 0x32, true, new OnPacketReceive( RacialAbility ) );\n\t\t\tRegisterExtended( 0x33, true, new OnPacketReceive( MouseBoatMovement ) );\n\n\t\t\tRegisterEncoded( 0x19, true, new OnEncodedPacketReceive( SetAbility ) );\n\t\t\tRegisterEncoded( 0x28, true, new OnEncodedPacketReceive( GuildGumpRequest ) );\n\n\t\t\tRegisterEncoded( 0x32, true, new OnEncodedPacketReceive( QuestGumpRequest ) );\n\t\t\tRegisterEncoded( 0x1E, true, new OnEncodedPacketReceive( EquipLastWeaponMacro ) );\n\t\t}\n\n\t\tpublic static void Register( int packetId, int length, bool ingame, OnPacketReceive onReceive )\n\t\t{\n\t\t\tHandlers[packetId] = new PacketHandler( packetId, length, ingame, onReceive );\n\t\t}\n\n\t\tpublic static PacketHandler GetHandler( int packetID )\n\t\t{\n\t\t\treturn Handlers[packetID];\n\t\t}\n\n\t\tpublic static void RegisterExtended( int packetID, bool ingame, OnPacketReceive onReceive )\n\t\t{\n\t\t\tif ( packetID >= 0 && packetID < 0x100 )\n\t\t\t\tm_ExtendedHandlersLow[packetID] = new PacketHandler( packetID, 0, ingame, onReceive );\n\t\t\telse\n\t\t\t\tm_ExtendedHandlersHigh[packetID] = new PacketHandler( packetID, 0, ingame, onReceive );\n\t\t}\n\n\t\tpublic static PacketHandler GetExtendedHandler( int packetID )\n\t\t{\n\t\t\tif ( packetID >= 0 && packetID < 0x100 )\n\t\t\t\treturn m_ExtendedHandlersLow[packetID];\n\t\t\telse\n\t\t\t\treturn m_ExtendedHandlersHigh[packetID];\n\t\t}\n\n\t\tpublic static void RemoveExtendedHandler( int packetID )\n\t\t{\n\t\t\tif ( packetID >= 0 && packetID < 0x100 )\n\t\t\t\tm_ExtendedHandlersLow[packetID] = null;\n\t\t\telse\n\t\t\t\tm_ExtendedHandlersHigh.Remove( packetID );\n\t\t}\n\n\t\tpublic static void RegisterEncoded( int packetID, bool ingame, OnEncodedPacketReceive onReceive )\n\t\t{\n\t\t\tif ( packetID >= 0 && packetID < 0x100 )\n\t\t\t\tm_EncodedHandlersLow[packetID] = new EncodedPacketHandler( packetID, ingame, onReceive );\n\t\t\telse\n\t\t\t\tm_EncodedHandlersHigh[packetID] = new EncodedPacketHandler( packetID, ingame, onReceive );\n\t\t}\n\n\t\tpublic static EncodedPacketHandler GetEncodedHandler( int packetID )\n\t\t{\n\t\t\tif ( packetID >= 0 && packetID < 0x100 )\n\t\t\t\treturn m_EncodedHandlersLow[packetID];\n\t\t\telse\n\t\t\t\treturn m_EncodedHandlersHigh[packetID];\n\t\t}\n\n\t\tpublic static void RemoveEncodedHandler( int packetID )\n\t\t{\n\t\t\tif ( packetID >= 0 && packetID < 0x100 )\n\t\t\t\tm_EncodedHandlersLow[packetID] = null;\n\t\t\telse\n\t\t\t\tm_EncodedHandlersHigh.Remove( packetID );\n\t\t}\n\n\t\tprivate static void UnhandledBF( NetState state, PacketReader pvSrc )\n\t\t{\n\t\t}\n\n\t\tpublic static void Empty( NetState state, PacketReader pvSrc )\n\t\t{\n\t\t}\n\n\t\tpublic static void SetAbility( NetState state, IEntity e, EncodedReader reader )\n\t\t{\n\t\t\tEventSink.InvokeSetAbility( new SetAbilityEventArgs( state.Mobile, reader.ReadInt32() ) );\n\t\t}\n\n\t\tpublic static void EquipLastWeaponMacro( NetState state, IEntity e, EncodedReader reader )\n\t\t{\n\t\t\tEventSink.InvokeEquipLastWeaponMacroUsed( new EquipLastWeaponMacroEventArgs( state.Mobile ) );\n\t\t}\n\n\t\tpublic static void GuildGumpRequest( NetState state, IEntity e, EncodedReader reader )\n\t\t{\n\t\t\tEventSink.InvokeGuildGumpRequest( new GuildGumpRequestArgs( state.Mobile ) );\n\t\t}\n\n\t\tpublic static void QuestGumpRequest( NetState state, IEntity e, EncodedReader reader )\n\t\t{\n\t\t\tEventSink.InvokeQuestGumpRequest( new QuestGumpRequestArgs( state.Mobile ) );\n\t\t}\n\n\t\tpublic static void EncodedCommand( NetState state, PacketReader pvSrc )\n\t\t{\n\t\t\tvar e = World.FindEntity( pvSrc.ReadInt32() );\n\t\t\tint packetID = pvSrc.ReadUInt16();\n\n\t\t\tvar ph = GetEncodedHandler( packetID );\n\n\t\t\tif ( ph != null )\n\t\t\t{\n\t\t\t\tif ( ph.Ingame && state.Mobile == null )\n\t\t\t\t{\n\t\t\t\t\tlog.Info( \"Client: {0}: Sent ingame packet (0xD7x{1:X2}) before having been attached to a mobile\", state, packetID );\n\t\t\t\t\tstate.Dispose();\n\t\t\t\t}\n\t\t\t\telse if ( ph.Ingame && state.Mobile.Deleted )\n\t\t\t\t{\n\t\t\t\t\tstate.Dispose();\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tph.OnReceive( state, e, new EncodedReader( pvSrc ) );\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tpvSrc.Trace( state );\n\t\t\t}\n\t\t}\n\n\t\tpublic static void RenameRequest( NetState state, PacketReader pvSrc )\n\t\t{\n\t\t\tvar from = state.Mobile;\n\t\t\tvar targ = World.FindMobile( pvSrc.ReadInt32() );\n\n\t\t\tif ( targ != null )\n\t\t\t\tEventSink.InvokeRenameRequest( new RenameRequestEventArgs( from, targ, pvSrc.ReadStringSafe() ) );\n\t\t}\n\n\t\tpublic static void ChatRequest( NetState state, PacketReader pvSrc )\n\t\t{\n\t\t\tEventSink.InvokeChatRequest( new ChatRequestEventArgs( state.Mobile ) );\n\t\t}\n\n\t\tpublic static void SecureTrade( NetState state, PacketReader pvSrc )\n\t\t{\n\t\t\tswitch ( pvSrc.ReadByte() )\n\t\t\t{\n\t\t\t\tcase 1: // Cancel\n\t\t\t\t\t{\n\t\t\t\t\t\tSerial serial = pvSrc.ReadInt32();\n\n\t\t\t\t\t\tvar cont = World.FindItem( serial ) as SecureTradeContainer;\n\n\t\t\t\t\t\tif ( cont != null && cont.Trade != null && ( cont.Trade.From.Mobile == state.Mobile || cont.Trade.To.Mobile == state.Mobile ) )\n\t\t\t\t\t\t\tcont.Trade.Cancel();\n\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\tcase 2: // Check\n\t\t\t\t\t{\n\t\t\t\t\t\tSerial serial = pvSrc.ReadInt32();\n\n\t\t\t\t\t\tvar cont = World.FindItem( serial ) as SecureTradeContainer;\n\n\t\t\t\t\t\tif ( cont != null )\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tvar trade = cont.Trade;\n\n\t\t\t\t\t\t\tvar value = ( pvSrc.ReadInt32() != 0 );\n\n\t\t\t\t\t\t\tif ( trade != null && trade.From.Mobile == state.Mobile )\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\ttrade.From.Accepted = value;\n\t\t\t\t\t\t\t\ttrade.Update();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse if ( trade != null && trade.To.Mobile == state.Mobile )\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\ttrade.To.Accepted = value;\n\t\t\t\t\t\t\t\ttrade.Update();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tpublic static void VendorBuyReply( NetState state, PacketReader pvSrc )\n\t\t{\n\t\t\tpvSrc.Seek( 1, SeekOrigin.Begin );\n\n\t\t\tint msgSize = pvSrc.ReadUInt16();\n\t\t\tvar vendor = World.FindMobile( pvSrc.ReadInt32() );\n\t\t\tvar flag = pvSrc.ReadByte();\n\n\t\t\tif ( vendor == null )\n\t\t\t{\n\t\t\t\treturn;\n\t\t\t}\n\t\t\telse if ( vendor.Deleted || !Utility.RangeCheck( vendor.Location, state.Mobile.Location, 10 ) )\n\t\t\t{\n\t\t\t\tstate.Send( new EndVendorBuy( vendor ) );\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif ( flag == 0x02 )\n\t\t\t{\n\t\t\t\tmsgSize -= 1 + 2 + 4 + 1;\n\n\t\t\t\tif ( ( msgSize / 7 ) > 100 )\n\t\t\t\t\treturn;\n\n\t\t\t\tvar buyList = new List( msgSize / 7 );\n\t\t\t\tfor ( ; msgSize > 0; msgSize -= 7 )\n\t\t\t\t{\n\t\t\t\t\t/*byte layer = */\n\t\t\t\t\tpvSrc.ReadByte();\n\t\t\t\t\tSerial serial = pvSrc.ReadInt32();\n\t\t\t\t\tint amount = pvSrc.ReadInt16();\n\n\t\t\t\t\tbuyList.Add( new BuyItemResponse( serial, amount ) );\n\t\t\t\t}\n\n\t\t\t\tif ( buyList.Count > 0 )\n\t\t\t\t{\n\t\t\t\t\tvar v = vendor as IVendor;\n\n\t\t\t\t\tif ( v != null && v.OnBuyItems( state.Mobile, buyList ) )\n\t\t\t\t\t\tstate.Send( new EndVendorBuy( vendor ) );\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tstate.Send( new EndVendorBuy( vendor ) );\n\t\t\t}\n\t\t}\n\n\t\tpublic static void VendorSellReply( NetState state, PacketReader pvSrc )\n\t\t{\n\t\t\tSerial serial = pvSrc.ReadInt32();\n\t\t\tvar vendor = World.FindMobile( serial );\n\n\t\t\tif ( vendor == null )\n\t\t\t{\n\t\t\t\treturn;\n\t\t\t}\n\t\t\telse if ( vendor.Deleted || !Utility.RangeCheck( vendor.Location, state.Mobile.Location, 10 ) )\n\t\t\t{\n\t\t\t\tstate.Send( new EndVendorSell( vendor ) );\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tint count = pvSrc.ReadUInt16();\n\t\t\tif ( count < 100 && pvSrc.Size == ( 1 + 2 + 4 + 2 + ( count * 6 ) ) )\n\t\t\t{\n\t\t\t\tvar sellList = new List( count );\n\n\t\t\t\tfor ( var i = 0; i < count; i++ )\n\t\t\t\t{\n\t\t\t\t\tvar item = World.FindItem( pvSrc.ReadInt32() );\n\t\t\t\t\tint Amount = pvSrc.ReadInt16();\n\n\t\t\t\t\tif ( item != null && Amount > 0 )\n\t\t\t\t\t\tsellList.Add( new SellItemResponse( item, Amount ) );\n\t\t\t\t}\n\n\t\t\t\tif ( sellList.Count > 0 )\n\t\t\t\t{\n\t\t\t\t\tvar v = vendor as IVendor;\n\n\t\t\t\t\tif ( v != null && v.OnSellItems( state.Mobile, sellList ) )\n\t\t\t\t\t\tstate.Send( new EndVendorSell( vendor ) );\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tpublic static void DeleteCharacter( NetState state, PacketReader pvSrc )\n\t\t{\n\t\t\tpvSrc.Seek( 30, SeekOrigin.Current );\n\t\t\tvar index = pvSrc.ReadInt32();\n\n\t\t\tEventSink.InvokeDeleteRequest( new DeleteRequestEventArgs( state, index ) );\n\t\t}\n\n\t\tpublic static void ResourceQuery( NetState state, PacketReader pvSrc )\n\t\t{\n\t\t\tif ( VerifyGC( state ) )\n\t\t\t{\n\t\t\t}\n\t\t}\n\n\t\tpublic static void GameCentralMoniter( NetState state, PacketReader pvSrc )\n\t\t{\n\t\t\tif ( VerifyGC( state ) )\n\t\t\t{\n\t\t\t\tint type = pvSrc.ReadByte();\n\t\t\t\tvar num1 = pvSrc.ReadInt32();\n\n\t\t\t\tlog.Info( \"God Client: {0}: Game central moniter\", state );\n\t\t\t\tlog.Info( \" - Type: {0}\", type );\n\t\t\t\tlog.Info( \" - Number: {0}\", num1 );\n\n\t\t\t\tpvSrc.Trace( state );\n\t\t\t}\n\t\t}\n\n\t\tpublic static void GodviewQuery( NetState state, PacketReader pvSrc )\n\t\t{\n\t\t\tif ( VerifyGC( state ) )\n\t\t\t{\n\t\t\t\tlog.Info( \"God Client: {0}: Godview query 0x{1:X}\", state, pvSrc.ReadByte() );\n\t\t\t}\n\t\t}\n\n\t\tpublic static void GMSingle( NetState state, PacketReader pvSrc )\n\t\t{\n\t\t\tif ( VerifyGC( state ) )\n\t\t\t\tpvSrc.Trace( state );\n\t\t}\n\n\t\tpublic static void DeathStatusResponse( NetState state, PacketReader pvSrc )\n\t\t{\n\t\t\t// Ignored\n\t\t}\n\n\t\tpublic static void ObjectHelpRequest( NetState state, PacketReader pvSrc )\n\t\t{\n\t\t\tvar from = state.Mobile;\n\n\t\t\tSerial serial = pvSrc.ReadInt32();\n\t\t\t/*int unk = */\n\t\t\tpvSrc.ReadByte();\n\t\t\t/*string lang = */\n\t\t\tpvSrc.ReadString( 3 );\n\n\t\t\tif ( serial.IsItem )\n\t\t\t{\n\t\t\t\tvar item = World.FindItem( serial );\n\n\t\t\t\tif ( item != null && from.Map == item.Map && item.GetWorldLocation().InUpdateRange( from.Location ) && from.CanSee( item ) )\n\t\t\t\t\titem.OnHelpRequest( from );\n\t\t\t}\n\t\t\telse if ( serial.IsMobile )\n\t\t\t{\n\t\t\t\tvar m = World.FindMobile( serial );\n\n\t\t\t\tif ( m != null && from.Map == m.Map && m.Location.InUpdateRange( from.Location ) && from.CanSee( m ) )\n\t\t\t\t\tm.OnHelpRequest( m );\n\t\t\t}\n\t\t}\n\n\t\tpublic static void MobileNameRequest( NetState state, PacketReader pvSrc )\n\t\t{\n\t\t\tvar m = World.FindMobile( pvSrc.ReadInt32() );\n\n\t\t\tif ( m != null && state.Mobile.InUpdateRange( m ) && state.Mobile.CanSee( m ) )\n\t\t\t\tstate.Send( new MobileName( m ) );\n\t\t}\n\n\t\tpublic static void RequestScrollWindow( NetState state, PacketReader pvSrc )\n\t\t{\n\t\t\t/*int lastTip = */\n\t\t\tpvSrc.ReadInt16();\n\t\t\t/*int type = */\n\t\t\tpvSrc.ReadByte();\n\t\t}\n\n\t\tpublic static void AttackReq( NetState state, PacketReader pvSrc )\n\t\t{\n\t\t\tvar from = state.Mobile;\n\t\t\tvar m = World.FindMobile( pvSrc.ReadInt32() );\n\n\t\t\tif ( m != null )\n\t\t\t\tfrom.Attack( m );\n\t\t}\n\n\t\tpublic static void HuePickerResponse( NetState state, PacketReader pvSrc )\n\t\t{\n\t\t\tvar serial = pvSrc.ReadInt32();\n\t\t\t/*int value = */\n\t\t\tpvSrc.ReadInt16();\n\t\t\tvar hue = pvSrc.ReadInt16() & 0x3FFF;\n\t\t\thue = Utility.ClipDyedHue( hue );\n\n\t\t\tvar picker = state.HuePickers.Where( p => p.Serial == serial ).FirstOrDefault();\n\n\t\t\tif ( picker != null )\n\t\t\t{\n\t\t\t\tstate.RemoveHuePicker( picker );\n\t\t\t\tpicker.OnResponse( hue );\n\t\t\t}\n\t\t}\n\n\t\tpublic static void TripTime( NetState state, PacketReader pvSrc )\n\t\t{\n\t\t\tint unk1 = pvSrc.ReadByte();\n\t\t\t/*int unk2 = */\n\t\t\tpvSrc.ReadInt32();\n\n\t\t\tstate.Send( new TripTimeResponse( unk1 ) );\n\t\t}\n\n\t\tpublic static void UTripTime( NetState state, PacketReader pvSrc )\n\t\t{\n\t\t\tint unk1 = pvSrc.ReadByte();\n\t\t\t/*int unk2 = */\n\t\t\tpvSrc.ReadInt32();\n\n\t\t\tstate.Send( new UTripTimeResponse( unk1 ) );\n\t\t}\n\n\t\tpublic static void ChangeZ( NetState state, PacketReader pvSrc )\n\t\t{\n\t\t\tif ( VerifyGC( state ) )\n\t\t\t{\n\t\t\t\tint x = pvSrc.ReadInt16();\n\t\t\t\tint y = pvSrc.ReadInt16();\n\t\t\t\tint z = pvSrc.ReadSByte();\n\n\t\t\t\tlog.Info( \"God Client: {0}: Change Z ({1}, {2}, {3})\", state, x, y, z );\n\t\t\t}\n\t\t}\n\n\t\tpublic static void SystemInfo( NetState state, PacketReader pvSrc )\n\t\t{\n\t\t\t/*int v1 = */\n\t\t\tpvSrc.ReadByte();\n\t\t\t/*int v2 = */\n\t\t\tpvSrc.ReadUInt16();\n\t\t\t/*int v3 = */\n\t\t\tpvSrc.ReadByte();\n\t\t\t/*string s1 = */\n\t\t\tpvSrc.ReadString( 32 );\n\t\t\t/*string s2 = */\n\t\t\tpvSrc.ReadString( 32 );\n\t\t\t/*string s3 = */\n\t\t\tpvSrc.ReadString( 32 );\n\t\t\t/*string s4 = */\n\t\t\tpvSrc.ReadString( 32 );\n\t\t\t/*int v4 = */\n\t\t\tpvSrc.ReadUInt16();\n\t\t\t/*int v5 = */\n\t\t\tpvSrc.ReadUInt16();\n\t\t\t/*int v6 = */\n\t\t\tpvSrc.ReadInt32();\n\t\t\t/*int v7 = */\n\t\t\tpvSrc.ReadInt32();\n\t\t\t/*int v8 = */\n\t\t\tpvSrc.ReadInt32();\n\t\t}\n\n\t\tpublic static void Edit( NetState state, PacketReader pvSrc )\n\t\t{\n\t\t\tif ( VerifyGC( state ) )\n\t\t\t{\n\t\t\t\tint type = pvSrc.ReadByte(); // 10 = static, 7 = npc, 4 = dynamic\n\t\t\t\tint x = pvSrc.ReadInt16();\n\t\t\t\tint y = pvSrc.ReadInt16();\n\t\t\t\tint id = pvSrc.ReadInt16();\n\t\t\t\tint z = pvSrc.ReadSByte();\n\t\t\t\tint hue = pvSrc.ReadUInt16();\n\n\t\t\t\tlog.Info( \"God Client: {0}: Edit {6} ({1}, {2}, {3}) 0x{4:X} (0x{5:X})\", state, x, y, z, id, hue, type );\n\t\t\t}\n\t\t}\n\n\t\tpublic static void DeleteStatic( NetState state, PacketReader pvSrc )\n\t\t{\n\t\t\tif ( VerifyGC( state ) )\n\t\t\t{\n\t\t\t\tint x = pvSrc.ReadInt16();\n\t\t\t\tint y = pvSrc.ReadInt16();\n\t\t\t\tint z = pvSrc.ReadInt16();\n\t\t\t\tint id = pvSrc.ReadUInt16();\n\n\t\t\t\tlog.Info( \"God Client: {0}: Delete Static ({1}, {2}, {3}) 0x{4:X}\", state, x, y, z, id );\n\t\t\t}\n\t\t}\n\n\t\tpublic static void NewAnimData( NetState state, PacketReader pvSrc )\n\t\t{\n\t\t\tif ( VerifyGC( state ) )\n\t\t\t{\n\t\t\t\tlog.Info( \"God Client: {0}: New tile animation\", state );\n\n\t\t\t\tpvSrc.Trace( state );\n\t\t\t}\n\t\t}\n\n\t\tpublic static void NewTerrain( NetState state, PacketReader pvSrc )\n\t\t{\n\t\t\tif ( VerifyGC( state ) )\n\t\t\t{\n\t\t\t\tint x = pvSrc.ReadInt16();\n\t\t\t\tint y = pvSrc.ReadInt16();\n\t\t\t\tint id = pvSrc.ReadUInt16();\n\t\t\t\tint width = pvSrc.ReadInt16();\n\t\t\t\tint height = pvSrc.ReadInt16();\n\n\t\t\t\tlog.Info( \"God Client: {0}: New Terrain ({1}, {2})+({3}, {4}) 0x{5:X4}\", state, x, y, width, height, id );\n\t\t\t}\n\t\t}\n\n\t\tpublic static void NewRegion( NetState state, PacketReader pvSrc )\n\t\t{\n\t\t\tif ( VerifyGC( state ) )\n\t\t\t{\n\t\t\t\tvar name = pvSrc.ReadString( 40 );\n\t\t\t\t/*int unk = */\n\t\t\t\tpvSrc.ReadInt32();\n\t\t\t\t/*int x = */\n\t\t\t\tpvSrc.ReadInt16();\n\t\t\t\t/*int y = */\n\t\t\t\tpvSrc.ReadInt16();\n\t\t\t\t/*int width = */\n\t\t\t\tpvSrc.ReadInt16();\n\t\t\t\t/*int height = */\n\t\t\t\tpvSrc.ReadInt16();\n\t\t\t\t/*int zStart = */\n\t\t\t\tpvSrc.ReadInt16();\n\t\t\t\t/*int zEnd = */\n\t\t\t\tpvSrc.ReadInt16();\n\t\t\t\tvar desc = pvSrc.ReadString( 40 );\n\t\t\t\t/*int soundFX = */\n\t\t\t\tpvSrc.ReadInt16();\n\t\t\t\t/*int music = */\n\t\t\t\tpvSrc.ReadInt16();\n\t\t\t\t/*int nightFX = */\n\t\t\t\tpvSrc.ReadInt16();\n\t\t\t\t/*int dungeon = */\n\t\t\t\tpvSrc.ReadByte();\n\t\t\t\t/*int light = */\n\t\t\t\tpvSrc.ReadInt16();\n\n\t\t\t\tlog.Info( \"God Client: {0}: New Region '{1}' ('{2}')\", state, name, desc );\n\t\t\t}\n\t\t}\n\n\t\tpublic static void AccountID( NetState state, PacketReader pvSrc )\n\t\t{\n\t\t}\n\n\t\tpublic static bool VerifyGC( NetState state )\n\t\t{\n\t\t\tif ( state.Mobile == null || state.Mobile.AccessLevel <= AccessLevel.Counselor )\n\t\t\t{\n\t\t\t\tlog.Info( \"Warning: {0}: Player using godclient, disconnecting\", state );\n\t\t\t\tstate.Dispose();\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\n\t\tpublic static void TextCommand( NetState state, PacketReader pvSrc )\n\t\t{\n\t\t\tint type = pvSrc.ReadByte();\n\t\t\tvar command = pvSrc.ReadString();\n\n\t\t\tvar m = state.Mobile;\n\n\t\t\tswitch ( type )\n\t\t\t{\n\t\t\t\tcase 0x00: // Go\n\t\t\t\t\t{\n\t\t\t\t\t\tif ( VerifyGC( state ) )\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttry\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tvar split = command.Split( ' ' );\n\n\t\t\t\t\t\t\t\tvar x = Utility.ToInt32( split[0] );\n\t\t\t\t\t\t\t\tvar y = Utility.ToInt32( split[1] );\n\n\t\t\t\t\t\t\t\tint z;\n\n\t\t\t\t\t\t\t\tif ( split.Length >= 3 )\n\t\t\t\t\t\t\t\t\tz = Utility.ToInt32( split[2] );\n\t\t\t\t\t\t\t\telse if ( m.Map != null )\n\t\t\t\t\t\t\t\t\tz = m.Map.GetAverageZ( x, y );\n\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t\tz = 0;\n\n\t\t\t\t\t\t\t\tm.Location = new Point3D( x, y, z );\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tcatch\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\tcase 0xC7: // Animate\n\t\t\t\t\t{\n\t\t\t\t\t\tEventSink.InvokeAnimateRequest( new AnimateRequestEventArgs( m, command ) );\n\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\tcase 0x24: // Use skill\n\t\t\t\t\t{\n\t\t\t\t\t\tint skillIndex;\n\n\t\t\t\t\t\ttry { skillIndex = Convert.ToInt32( command.Split( ' ' )[0] ); }\n\t\t\t\t\t\tcatch { break; }\n\n\t\t\t\t\t\ttry\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tm.UseSkill( skillIndex );\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcatch ( Exception e )\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tlog.Error( \"Exception disarmed in UseSkill {0} > {1}: {2}\", state.Mobile, skillIndex, e );\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\tcase 0x43: // Open spellbook\n\t\t\t\t\t{\n\t\t\t\t\t\tint booktype;\n\n\t\t\t\t\t\ttry { booktype = Convert.ToInt32( command ); }\n\t\t\t\t\t\tcatch { booktype = 1; }\n\n\t\t\t\t\t\tEventSink.InvokeOpenSpellbookRequest( new OpenSpellbookRequestEventArgs( m, booktype ) );\n\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\tcase 0x27: // Cast spell from book\n\t\t\t\t\t{\n\t\t\t\t\t\tvar split = command.Split( ' ' );\n\n\t\t\t\t\t\tif ( split.Length > 0 )\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tvar spellId = Utility.ToInt32( split[0] ) - 1;\n\t\t\t\t\t\t\tvar serial = split.Length > 1 ? Utility.ToInt32( split[1] ) : -1;\n\n\t\t\t\t\t\t\ttry\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tm.CastSpell( spellId, book: World.FindItem( serial ) );\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tcatch ( Exception e )\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tlog.Error( \"Exception disarmed in CastSpell I {0}, spell {1}: {2}\", state.Mobile, spellId, e );\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\tcase 0x58: // Open door\n\t\t\t\t\t{\n\t\t\t\t\t\ttry\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tEventSink.InvokeOpenDoorMacroUsed( new OpenDoorMacroEventArgs( m ) );\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcatch ( Exception e )\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tlog.Error( \"Exception disarmed in OpenDoor {0}: {1}\", state.Mobile, e );\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\tcase 0x56: // Cast spell from macro\n\t\t\t\t\t{\n\t\t\t\t\t\tvar spellId = Utility.ToInt32( command ) - 1;\n\n\t\t\t\t\t\ttry\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tm.CastSpell( spellId );\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcatch ( Exception e )\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tlog.Error( \"Exception disarmed in CastSpell II {0}, spell {1}: {2}\", state.Mobile, spellId, e );\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\tcase 0xF4: // Invoke virtues from macro\n\t\t\t\t\t{\n\t\t\t\t\t\tvar virtueID = Utility.ToInt32( command );\n\n\t\t\t\t\t\ttry\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tEventSink.InvokeVirtueMacroUsed( new VirtueMacroEventArgs( m, virtueID ) );\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcatch ( Exception e )\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tlog.Error( \"Exception disarmed in VirtueMacroUsed {0}, virtueid: {1}, {2}\", state.Mobile, virtueID, e );\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\tdefault:\n\t\t\t\t\t{\n\t\t\t\t\t\tlog.Info( \"Client: {0}: Unknown text-command type 0x{1:X2}: {2}\", state, type, command );\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tpublic static void GodModeRequest( NetState state, PacketReader pvSrc )\n\t\t{\n\t\t\tif ( VerifyGC( state ) )\n\t\t\t\tstate.Send( new GodModeReply( pvSrc.ReadBoolean() ) );\n\t\t}\n\n\t\tpublic static void AsciiPromptResponse( NetState state, PacketReader pvSrc )\n\t\t{\n\t\t\tvar from = state.Mobile;\n\t\t\tvar p = from.Prompt;\n\n\t\t\tvar senderSerial = pvSrc.ReadInt32();\n\t\t\tvar promptId = pvSrc.ReadInt32();\n\t\t\tvar type = pvSrc.ReadInt32();\n\t\t\tvar text = pvSrc.ReadStringSafe();\n\n\t\t\tif ( text.Length > 128 )\n\t\t\t\treturn;\n\n\t\t\tif ( p != null && p.Sender.Serial == senderSerial && p.TypeId == promptId )\n\t\t\t{\n\t\t\t\tfrom.Prompt = null;\n\n\t\t\t\ttry\n\t\t\t\t{\n\t\t\t\t\tif ( type == 0 )\n\t\t\t\t\t\tp.OnCancel( from );\n\t\t\t\t\telse\n\t\t\t\t\t\tp.OnResponse( from, text );\n\t\t\t\t}\n\t\t\t\tcatch ( Exception e )\n\t\t\t\t{\n\t\t\t\t\tlog.Error( \"Exception disarmed in AsciiPrompt response {0}, type {1}: {2}\", state.Mobile, type, e );\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tpublic static void UnicodePromptResponse( NetState state, PacketReader pvSrc )\n\t\t{\n\t\t\tvar from = state.Mobile;\n\t\t\tvar p = from.Prompt;\n\n\t\t\tvar senderSerial = pvSrc.ReadInt32();\n\t\t\tvar promptId = pvSrc.ReadInt32();\n\t\t\tvar type = pvSrc.ReadInt32();\n\t\t\t/*string lang = */\n\t\t\tpvSrc.ReadString( 4 );\n\t\t\tvar text = pvSrc.ReadUnicodeStringLESafe();\n\n\t\t\tif ( text.Length > 128 )\n\t\t\t\treturn;\n\n\t\t\tvar promptSerial = ( p != null && p.Sender != null ) ? p.Sender.Serial.Value : from.Serial.Value;\n\n\t\t\tif ( p != null && promptSerial == senderSerial && p.TypeId == promptId )\n\t\t\t{\n\t\t\t\tfrom.Prompt = null;\n\n\t\t\t\ttry\n\t\t\t\t{\n\t\t\t\t\tif ( type == 0 )\n\t\t\t\t\t\tp.OnCancel( from );\n\t\t\t\t\telse\n\t\t\t\t\t\tp.OnResponse( from, text );\n\t\t\t\t}\n\t\t\t\tcatch ( Exception e )\n\t\t\t\t{\n\t\t\t\t\tlog.Error( \"Exception disarmed in UnicodePrompt response {0}, type {1}: {2}\", state.Mobile, type, e );\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tpublic static void MenuResponse( NetState state, PacketReader pvSrc )\n\t\t{\n\t\t\tvar serial = pvSrc.ReadInt32();\n\t\t\t/*int menuID = */\n\t\t\tpvSrc.ReadInt16(); // unused in our implementation\n\t\t\tint index = pvSrc.ReadInt16();\n\t\t\t/*int itemID = */\n\t\t\tpvSrc.ReadInt16();\n\t\t\t/*int hue = */\n\t\t\tpvSrc.ReadInt16();\n\n\t\t\tvar menu = state.Menus.Where( m => m.Serial == serial ).FirstOrDefault();\n\n\t\t\tif ( menu != null )\n\t\t\t{\n\t\t\t\ttry\n\t\t\t\t{\n\t\t\t\t\tif ( index > 0 && index <= menu.EntryLength )\n\t\t\t\t\t\tmenu.OnResponse( state, index - 1 );\n\t\t\t\t\telse\n\t\t\t\t\t\tmenu.OnCancel( state );\n\t\t\t\t}\n\t\t\t\tcatch ( Exception e )\n\t\t\t\t{\n\t\t\t\t\tlog.Error( \"Exception disarmed in menu response {0} > {1}[index]: {2}\", state.Mobile, menu, e );\n\t\t\t\t}\n\n\t\t\t\tstate.RemoveMenu( menu );\n\t\t\t}\n\t\t}\n\n\t\tpublic static void ProfileReq( NetState state, PacketReader pvSrc )\n\t\t{\n\t\t\tint type = pvSrc.ReadByte();\n\t\t\tSerial serial = pvSrc.ReadInt32();\n\n\t\t\tvar beholder = state.Mobile;\n\t\t\tvar beheld = World.FindMobile( serial );\n\n\t\t\tif ( beheld == null )\n\t\t\t\treturn;\n\n\t\t\tswitch ( type )\n\t\t\t{\n\t\t\t\tcase 0x00: // display request\n\t\t\t\t\t{\n\t\t\t\t\t\tEventSink.InvokeProfileRequest( new ProfileRequestEventArgs( beholder, beheld ) );\n\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\tcase 0x01: // edit request\n\t\t\t\t\t{\n\t\t\t\t\t\tpvSrc.ReadInt16(); // Skip\n\t\t\t\t\t\tint length = pvSrc.ReadUInt16();\n\n\t\t\t\t\t\tif ( length > 511 )\n\t\t\t\t\t\t\treturn;\n\n\t\t\t\t\t\tvar text = pvSrc.ReadUnicodeString( length );\n\n\t\t\t\t\t\tEventSink.InvokeChangeProfileRequest( new ChangeProfileRequestEventArgs( beholder, beheld, text ) );\n\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tpublic static void Disconnect( NetState state, PacketReader pvSrc )\n\t\t{\n\t\t\t/*int minusOne = */\n\t\t\tpvSrc.ReadInt32();\n\t\t}\n\n\t\tpublic static void LiftReq( NetState state, PacketReader pvSrc )\n\t\t{\n\t\t\tSerial serial = pvSrc.ReadInt32();\n\t\t\tint amount = pvSrc.ReadUInt16();\n\t\t\tvar item = World.FindItem( serial );\n\n\t\t\tbool rejected;\n\t\t\tLRReason reject;\n\n\t\t\ttry\n\t\t\t{\n\t\t\t\tstate.Mobile.Lift( item, amount, out rejected, out reject );\n\t\t\t}\n\t\t\tcatch ( Exception e )\n\t\t\t{\n\t\t\t\tlog.Error( \"Exception disarmed in lift {0}, {1} x {2}: {3}\", state.Mobile, item, amount, e );\n\t\t\t}\n\t\t}\n\n\t\tpublic static void EquipReq( NetState state, PacketReader pvSrc )\n\t\t{\n\t\t\tvar from = state.Mobile;\n\t\t\tvar item = from.Holding;\n\n\t\t\tif ( item == null )\n\t\t\t\treturn;\n\n\t\t\tfrom.Holding = null;\n\n\t\t\tpvSrc.Seek( 5, SeekOrigin.Current );\n\t\t\tvar to = World.FindMobile( pvSrc.ReadInt32() );\n\n\t\t\tif ( to == null )\n\t\t\t\tto = from;\n\n\t\t\tvar success = false;\n\n\t\t\ttry\n\t\t\t{\n\t\t\t\tif ( to.AllowEquipFrom( from ) )\n\t\t\t\t\tsuccess = to.EquipItem( item );\n\t\t\t}\n\t\t\tcatch ( Exception e )\n\t\t\t{\n\t\t\t\tlog.Error( \"Exception disarmed in equip {0} < {1}: {2}\", to, item, e );\n\t\t\t}\n\n\t\t\tif ( !success )\n\t\t\t{\n\t\t\t\titem.Bounce( from );\n\t\t\t\tfrom.Send( new InvalidDrop( item.Serial ) );\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tfrom.Send( ConfirmDrop.Instance );\n\t\t\t}\n\n\t\t\titem.ClearBounce();\n\t\t}\n\n\t\tpublic static void DropReq( NetState state, PacketReader pvSrc )\n\t\t{\n\t\t\tvar serial = (Serial) pvSrc.ReadInt32();\n\n\t\t\tint x = pvSrc.ReadInt16();\n\t\t\tint y = pvSrc.ReadInt16();\n\t\t\tint z = pvSrc.ReadSByte();\n\n\t\t\tvar gridloc = pvSrc.ReadByte(); // grid location\n\n\t\t\tSerial dest = pvSrc.ReadInt32();\n\n\t\t\tvar loc = new Point3D( x, y, z );\n\n\t\t\tvar from = state.Mobile;\n\n\t\t\tif ( dest.IsMobile )\n\t\t\t{\n\t\t\t\tvar m = World.FindMobile( dest );\n\n\t\t\t\ttry\n\t\t\t\t{\n\t\t\t\t\tif ( m != null )\n\t\t\t\t\t\tif ( from.Drop( m, loc ) )\n\t\t\t\t\t\t\tstate.Send( ConfirmDrop.Instance );\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tstate.Send( new InvalidDrop( serial ) );\n\t\t\t\t}\n\t\t\t\tcatch ( Exception e )\n\t\t\t\t{\n\t\t\t\t\tlog.Error( \"Exception disarmed in drop {0} > {1}: {2}\", from, m, e );\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if ( dest.IsItem )\n\t\t\t{\n\t\t\t\tvar i = World.FindItem( dest );\n\n\t\t\t\ttry\n\t\t\t\t{\n\t\t\t\t\tif ( i != null )\n\t\t\t\t\t\tif ( from.Drop( i, loc, gridloc ) )\n\t\t\t\t\t\t\tstate.Send( ConfirmDrop.Instance );\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tstate.Send( new InvalidDrop( serial ) );\n\t\t\t\t}\n\t\t\t\tcatch ( Exception e )\n\t\t\t\t{\n\t\t\t\t\tlog.Error( \"Exception disarmed in drop {0} > {1}: {2}\", from, i, e );\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tif ( from.Drop( loc ) )\n\t\t\t\t\tstate.Send( ConfirmDrop.Instance );\n\t\t\t\telse\n\t\t\t\t\tstate.Send( new InvalidDrop( serial ) );\n\t\t\t}\n\t\t}\n\n\t\tpublic static void ConfigurationFile( NetState state, PacketReader pvSrc )\n\t\t{\n\t\t}\n\n\t\tpublic static void LogoutReq( NetState state, PacketReader pvSrc )\n\t\t{\n\t\t\tstate.Send( LogoutAck.Instance );\n\t\t}\n\n\t\tpublic static void ChangeSkillLock( NetState state, PacketReader pvSrc )\n\t\t{\n\t\t\tvar s = state.Mobile.Skills[pvSrc.ReadInt16()];\n\n\t\t\tif ( s != null )\n\t\t\t\ts.SetLockNoRelay( (SkillLock) pvSrc.ReadByte() );\n\t\t}\n\n\t\tpublic static void HelpRequest( NetState state, PacketReader pvSrc )\n\t\t{\n\t\t\tEventSink.InvokeHelpRequest( new HelpRequestEventArgs( state.Mobile ) );\n\t\t}\n\n\t\tpublic static void TargetResponse( NetState state, PacketReader pvSrc )\n\t\t{\n\t\t\tint type = pvSrc.ReadByte();\n\t\t\t/*int targetID = */\n\t\t\tpvSrc.ReadInt32();\n\t\t\t/*int flags = */\n\t\t\tpvSrc.ReadByte();\n\t\t\tSerial serial = pvSrc.ReadInt32();\n\t\t\tint x = pvSrc.ReadInt16(), y = pvSrc.ReadInt16(), z = pvSrc.ReadInt16();\n\t\t\tint graphic = pvSrc.ReadInt16();\n\n\t\t\tvar from = state.Mobile;\n\n\t\t\tvar t = from.Target;\n\n\t\t\tif ( t == null )\n\t\t\t{\n\t\t\t\tstate.NullTargets++;\n\n\t\t\t\tif ( state.NullTargets > NetState.MaxNullTargets )\n\t\t\t\t{\n\t\t\t\t\tstate.Dispose();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tstate.NullTargets = 0;\n\n\t\t\t\tif ( x == -1 && y == -1 && !serial.IsValid )\n\t\t\t\t{\n\t\t\t\t\t// User pressed escape\n\t\t\t\t\tt.Cancel( from, TargetCancelType.Canceled );\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tobject toTarget;\n\n\t\t\t\t\tif ( type == 1 )\n\t\t\t\t\t{\n\t\t\t\t\t\tif ( graphic == 0 )\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttoTarget = new LandTarget( new Point3D( x, y, z ), from.Map );\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tvar map = from.Map;\n\n\t\t\t\t\t\t\tif ( map == null || map == Map.Internal )\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tt.Cancel( from, TargetCancelType.Canceled );\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tvar tiles = map.Tiles.GetStaticTiles( x, y, !t.DisallowMultis );\n\n\t\t\t\t\t\t\t\tvar valid = false;\n\n\t\t\t\t\t\t\t\tfor ( var i = 0; !valid && i < tiles.Length; ++i )\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tvar surface = ( TileData.ItemTable[tiles[i].ID & TileData.MaxItemValue].Flags & TileFlag.Surface ) != 0;\n\t\t\t\t\t\t\t\t\tvar zOffset = surface ? tiles[i].Height : 0;\n\n\t\t\t\t\t\t\t\t\tif ( ( tiles[i].Z + zOffset ) == z && ( tiles[i].ID & TileData.MaxItemValue ) == ( graphic & TileData.MaxItemValue ) )\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tvalid = true;\n\t\t\t\t\t\t\t\t\t\tz -= zOffset;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\tif ( !valid )\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tt.Cancel( from, TargetCancelType.Canceled );\n\t\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\ttoTarget = new StaticTarget( new Point3D( x, y, z ), graphic );\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse if ( serial.IsMobile )\n\t\t\t\t\t{\n\t\t\t\t\t\ttoTarget = World.FindMobile( serial );\n\t\t\t\t\t}\n\t\t\t\t\telse if ( serial.IsItem )\n\t\t\t\t\t{\n\t\t\t\t\t\ttoTarget = World.FindItem( serial );\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tt.Cancel( from, TargetCancelType.Canceled );\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\ttry\n\t\t\t\t\t{\n\t\t\t\t\t\tt.Invoke( from, toTarget );\n\t\t\t\t\t}\n\t\t\t\t\tcatch ( Exception e )\n\t\t\t\t\t{\n\t\t\t\t\t\tlog.Error( \"Exception disarmed in target {0} > {1} > {2}: {3}\", from, t, toTarget, e );\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tpublic static void DisplayGumpResponse( NetState state, PacketReader pvSrc )\n\t\t{\n\t\t\tvar serial = pvSrc.ReadInt32();\n\t\t\tvar typeID = pvSrc.ReadInt32();\n\t\t\tvar buttonID = pvSrc.ReadInt32();\n\n\t\t\tforeach ( var gump in state.Gumps )\n\t\t\t{\n\t\t\t\tif ( gump.Serial == serial && gump.TypeID == typeID )\n\t\t\t\t{\n\t\t\t\t\tvar switchCount = pvSrc.ReadInt32();\n\n\t\t\t\t\tif ( switchCount < 0 || switchCount > gump.m_Switches )\n\t\t\t\t\t{\n\t\t\t\t\t\tlog.Info( \"Client: {0}: Invalid gump response, disconnecting...\", state );\n\t\t\t\t\t\tstate.Dispose();\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tvar switches = new int[switchCount];\n\n\t\t\t\t\tfor ( var j = 0; j < switches.Length; ++j )\n\t\t\t\t\t\tswitches[j] = pvSrc.ReadInt32();\n\n\t\t\t\t\tvar textCount = pvSrc.ReadInt32();\n\n\t\t\t\t\tif ( textCount < 0 || textCount > gump.m_TextEntries )\n\t\t\t\t\t{\n\t\t\t\t\t\tlog.Info( \"Client: {0}: Invalid gump response, disconnecting...\", state );\n\t\t\t\t\t\tstate.Dispose();\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tvar textEntries = new TextRelay[textCount];\n\n\t\t\t\t\tfor ( var j = 0; j < textEntries.Length; ++j )\n\t\t\t\t\t{\n\t\t\t\t\t\tint entryID = pvSrc.ReadUInt16();\n\t\t\t\t\t\tint textLength = pvSrc.ReadUInt16();\n\n\t\t\t\t\t\tif ( textLength > 239 )\n\t\t\t\t\t\t\treturn;\n\n\t\t\t\t\t\tvar text = pvSrc.ReadUnicodeStringSafe( textLength );\n\t\t\t\t\t\ttextEntries[j] = new TextRelay( entryID, text );\n\t\t\t\t\t}\n\n\t\t\t\t\ttry\n\t\t\t\t\t{\n\t\t\t\t\t\tgump.OnResponse( state, new RelayInfo( buttonID, switches, textEntries ) );\n\t\t\t\t\t}\n\t\t\t\t\tcatch ( Exception e )\n\t\t\t\t\t{\n\t\t\t\t\t\tlog.Error( \"Exception disarmed in gump response of {0}: {1}\", gump, e );\n\t\t\t\t\t}\n\n\t\t\t\t\tstate.RemoveGump( gump );\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif ( typeID == 461 )\n\t\t\t{ // Virtue gump\n\t\t\t\tvar switchCount = pvSrc.ReadInt32();\n\n\t\t\t\tif ( buttonID == 1 && switchCount > 0 )\n\t\t\t\t{\n\t\t\t\t\tvar beheld = World.FindMobile( pvSrc.ReadInt32() );\n\n\t\t\t\t\tif ( beheld != null )\n\t\t\t\t\t\tEventSink.InvokeVirtueGumpRequest( new VirtueGumpRequestEventArgs( state.Mobile, beheld ) );\n\t\t\t\t}\n\t\t\t\telse if ( buttonID == 1971 )\n\t\t\t\t{\n\t\t\t\t\tEventSink.InvokeVirtueGumpRequest( new VirtueGumpRequestEventArgs( state.Mobile, state.Mobile ) );\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tvar beheld = World.FindMobile( serial );\n\n\t\t\t\t\tif ( beheld != null )\n\t\t\t\t\t\tEventSink.InvokeVirtueItemRequest( new VirtueItemRequestEventArgs( state.Mobile, beheld, buttonID ) );\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tpublic static void SetWarMode( NetState state, PacketReader pvSrc )\n\t\t{\n\t\t\tstate.Mobile.DelayChangeWarmode( pvSrc.ReadBoolean() );\n\t\t}\n\n\t\tpublic static void Resynchronize( NetState state, PacketReader pvSrc )\n\t\t{\n\t\t\tvar m = state.Mobile;\n\n\t\t\tstate.Send( new MobileUpdate( m ) );\n\t\t\tstate.Send( new MobileIncoming( m, m ) );\n\n\t\t\tm.SendEverything();\n\n\t\t\tstate.Sequence = 0;\n\n\t\t\tm.ClearFastwalkStack();\n\t\t}\n\n\t\tprivate static readonly int[] m_EmptyInts = new int[0];\n\n\t\tpublic static void AsciiSpeech( NetState state, PacketReader pvSrc )\n\t\t{\n\t\t\tvar from = state.Mobile;\n\n\t\t\tvar type = (MessageType) pvSrc.ReadByte();\n\t\t\tint hue = pvSrc.ReadInt16();\n\t\t\tpvSrc.ReadInt16(); // font\n\t\t\tvar text = pvSrc.ReadStringSafe().Trim();\n\n\t\t\tif ( text.Length <= 0 || text.Length > 128 )\n\t\t\t\treturn;\n\n\t\t\tif ( !Enum.IsDefined( typeof( MessageType ), type ) )\n\t\t\t\ttype = MessageType.Regular;\n\n\t\t\tfrom.DoSpeech( text, m_EmptyInts, type, Utility.ClipDyedHue( hue ) );\n\t\t}\n\n\t\tprivate static readonly KeywordList m_KeywordList = new KeywordList();\n\n\t\tpublic static void UnicodeSpeech( NetState state, PacketReader pvSrc )\n\t\t{\n\t\t\tvar from = state.Mobile;\n\n\t\t\tvar type = (MessageType) pvSrc.ReadByte();\n\t\t\tint hue = pvSrc.ReadInt16();\n\t\t\tpvSrc.ReadInt16(); // font\n\t\t\tvar lang = pvSrc.ReadString( 4 );\n\t\t\tstring text;\n\n\t\t\tvar isEncoded = ( type & MessageType.Encoded ) != 0;\n\t\t\tint[] keywords;\n\n\t\t\tif ( isEncoded )\n\t\t\t{\n\t\t\t\tint value = pvSrc.ReadInt16();\n\t\t\t\tvar count = ( value & 0xFFF0 ) >> 4;\n\t\t\t\tvar hold = value & 0xF;\n\n\t\t\t\tif ( count < 0 || count > 50 )\n\t\t\t\t\treturn;\n\n\t\t\t\tvar keyList = m_KeywordList;\n\n\t\t\t\tfor ( var i = 0; i < count; ++i )\n\t\t\t\t{\n\t\t\t\t\tint speechID;\n\n\t\t\t\t\tif ( ( i & 1 ) == 0 )\n\t\t\t\t\t{\n\t\t\t\t\t\thold <<= 8;\n\t\t\t\t\t\thold |= pvSrc.ReadByte();\n\t\t\t\t\t\tspeechID = hold;\n\t\t\t\t\t\thold = 0;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tvalue = pvSrc.ReadInt16();\n\t\t\t\t\t\tspeechID = ( value & 0xFFF0 ) >> 4;\n\t\t\t\t\t\thold = value & 0xF;\n\t\t\t\t\t}\n\n\t\t\t\t\tif ( !keyList.Contains( speechID ) )\n\t\t\t\t\t\tkeyList.Add( speechID );\n\t\t\t\t}\n\n\t\t\t\ttext = pvSrc.ReadUTF8StringSafe();\n\n\t\t\t\tkeywords = keyList.ToArray();\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\ttext = pvSrc.ReadUnicodeStringSafe();\n\n\t\t\t\tkeywords = m_EmptyInts;\n\t\t\t}\n\n\t\t\ttext = text.Trim();\n\n\t\t\tif ( text.Length <= 0 || text.Length > 128 )\n\t\t\t\treturn;\n\n\t\t\ttype &= ~MessageType.Encoded;\n\n\t\t\tif ( !Enum.IsDefined( typeof( MessageType ), type ) )\n\t\t\t\ttype = MessageType.Regular;\n\n\t\t\tfrom.Language = lang;\n\t\t\tfrom.DoSpeech( text, keywords, type, Utility.ClipDyedHue( hue ) );\n\t\t}\n\n\t\tpublic static void UseReq( NetState state, PacketReader pvSrc )\n\t\t{\n\t\t\tvar from = state.Mobile;\n\n\t\t\tif ( from.AccessLevel >= AccessLevel.GameMaster || DateTime.UtcNow >= from.NextActionTime )\n\t\t\t{\n\t\t\t\tvar value = pvSrc.ReadInt32();\n\n\t\t\t\tif ( ( value & ~0x7FFFFFFF ) != 0 )\n\t\t\t\t{\n\t\t\t\t\tfrom.OnPaperdollRequest();\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tSerial s = value;\n\n\t\t\t\t\tif ( s.IsMobile )\n\t\t\t\t\t{\n\t\t\t\t\t\tvar m = World.FindMobile( s );\n\n\t\t\t\t\t\ttry\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tif ( m != null && !m.Deleted )\n\t\t\t\t\t\t\t\tfrom.Use( m );\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcatch ( Exception e )\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tlog.Error( \"Exception disarmed in use {0} > {1}: {2}\", from, m, e );\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse if ( s.IsItem )\n\t\t\t\t\t{\n\t\t\t\t\t\tvar item = World.FindItem( s );\n\n\t\t\t\t\t\ttry\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tif ( item != null && !item.Deleted )\n\t\t\t\t\t\t\t\tfrom.Use( item );\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcatch ( Exception e )\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tlog.Error( \"Exception disarmed in use {0} > {1}: {2}\", from, item, e );\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tfrom.NextActionTime = DateTime.UtcNow + TimeSpan.FromSeconds( 0.5 );\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tfrom.SendActionMessage();\n\t\t\t}\n\t\t}\n\n\t\tpublic static void LookReq( NetState state, PacketReader pvSrc )\n\t\t{\n\t\t\tvar from = state.Mobile;\n\n\t\t\tSerial s = pvSrc.ReadInt32();\n\n\t\t\tif ( s.IsMobile )\n\t\t\t{\n\t\t\t\tvar m = World.FindMobile( s );\n\n\t\t\t\tif ( m != null && from.CanSee( m ) && m.InUpdateRange( from ) )\n\t\t\t\t\tm.OnAosSingleClick( from );\n\t\t\t}\n\t\t\telse if ( s.IsItem )\n\t\t\t{\n\t\t\t\tvar item = World.FindItem( s );\n\n\t\t\t\tif ( item != null && !item.Deleted && from.CanSee( item ) && from.InUpdateRange( item.GetWorldLocation() ) )\n\t\t\t\t\titem.OnAosSingleClick( from );\n\t\t\t}\n\t\t}\n\n\t\tpublic static void PingReq( NetState state, PacketReader pvSrc )\n\t\t{\n\t\t\tstate.Send( PingAck.Instantiate( pvSrc.ReadByte() ) );\n\t\t}\n\n\t\tpublic static void SetUpdateRange( NetState state, PacketReader pvSrc )\n\t\t{\n\t\t\tstate.Send( ChangeUpdateRange.Instantiate( 18 ) );\n\t\t}\n\n\t\tpublic static void MovementReq( NetState state, PacketReader pvSrc )\n\t\t{\n\t\t\tvar dir = (Direction) pvSrc.ReadByte();\n\t\t\tint seq = pvSrc.ReadByte();\n\t\t\t/*int key = */\n\t\t\tpvSrc.ReadInt32();\n\n\t\t\tvar m = state.Mobile;\n\n\t\t\tif ( ( state.Sequence == 0 && seq != 0 ) || !m.Move( dir ) )\n\t\t\t{\n\t\t\t\tstate.Send( new MovementRej( seq, m ) );\n\t\t\t\tstate.Sequence = 0;\n\n\t\t\t\tm.ClearFastwalkStack();\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t++seq;\n\n\t\t\t\tif ( seq == 256 )\n\t\t\t\t\tseq = 1;\n\n\t\t\t\tstate.Sequence = seq;\n\t\t\t}\n\t\t}\n\n\t\tpublic static int[] m_ValidAnimations = {\n\t\t\t\t6, 21, 32, 33,\n\t\t\t\t100, 101, 102,\n\t\t\t\t103, 104, 105,\n\t\t\t\t106, 107, 108,\n\t\t\t\t109, 110, 111,\n\t\t\t\t112, 113, 114,\n\t\t\t\t115, 116, 117,\n\t\t\t\t118, 119, 120,\n\t\t\t\t121, 123, 124,\n\t\t\t\t125, 126, 127,\n\t\t\t\t128\n\t\t\t};\n\n\t\tpublic static int[] ValidAnimations\n\t\t{\n\t\t\tget { return m_ValidAnimations; }\n\t\t\tset { m_ValidAnimations = value; }\n\t\t}\n\n\t\tpublic static void Animate( NetState state, PacketReader pvSrc )\n\t\t{\n\t\t\tvar from = state.Mobile;\n\t\t\tvar action = pvSrc.ReadInt32();\n\n\t\t\tvar isValidAnimation = ValidAnimations.Contains( action );\n\n\t\t\tif ( isValidAnimation && from.Alive && from.Body.IsHuman && !from.Mounted )\n\t\t\t\tfrom.Animate( action, 7, 1, true, false, 0 );\n\t\t}\n\n\t\tpublic static void QuestArrow( NetState state, PacketReader pvSrc )\n\t\t{\n\t\t\tvar from = state.Mobile;\n\n\t\t\tvar rightClick = pvSrc.ReadBoolean();\n\n\t\t\tif ( from.QuestArrow != null )\n\t\t\t\tfrom.QuestArrow.OnClick( rightClick );\n\t\t}\n\n\t\tpublic static void ExtendedCommand( NetState state, PacketReader pvSrc )\n\t\t{\n\t\t\tint packetId = pvSrc.ReadUInt16();\n\n\t\t\tvar ph = GetExtendedHandler( packetId );\n\n\t\t\tif ( ph != null )\n\t\t\t{\n\t\t\t\tif ( ph.Ingame && state.Mobile == null )\n\t\t\t\t{\n\t\t\t\t\tlog.Info( \"Client: {0}: Sent ingame packet (0xBFx{1:X2}) before having been attached to a mobile\", state, packetId );\n\t\t\t\t\tstate.Dispose();\n\t\t\t\t}\n\t\t\t\telse if ( ph.Ingame && state.Mobile.Deleted )\n\t\t\t\t{\n\t\t\t\t\tstate.Dispose();\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tph.OnReceive( state, pvSrc );\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tpvSrc.Trace( state );\n\t\t\t}\n\t\t}\n\n\t\tpublic static void CastSpell( NetState state, PacketReader pvSrc )\n\t\t{\n\t\t\tvar from = state.Mobile;\n\n\t\t\tItem spellbook = null;\n\n\t\t\tif ( pvSrc.ReadInt16() == 1 )\n\t\t\t\tspellbook = World.FindItem( pvSrc.ReadInt32() );\n\n\t\t\tvar spellId = pvSrc.ReadInt16() - 1;\n\n\t\t\tfrom.CastSpell( spellId, spellbook );\n\t\t}\n\n\t\tpublic static void TargetedCastSpell( NetState state, PacketReader pvSrc )\n\t\t{\n\t\t\tvar from = state.Mobile;\n\n\t\t\tvar spellId = pvSrc.ReadInt16() - 1;\n\n\t\t\tfrom.CastSpell( spellId, target: World.FindEntity( pvSrc.ReadInt32() ) );\n\t\t}\n\n\t\tpublic static void TargetedSkillUse( NetState state, PacketReader pvSrc )\n\t\t{\n\t\t\tvar from = state.Mobile;\n\n\t\t\tint skillId = pvSrc.ReadInt16();\n\t\t\tvar target = World.FindEntity( pvSrc.ReadInt32() );\n\n\t\t\tvar oldTarget = from.Target;\n\t\t\tfrom.TargetLocked = true;\n\n\t\t\tfrom.UseSkill( skillId );\n\n\t\t\tvar newTarget = from.Target;\n\n\t\t\tif ( oldTarget != newTarget && newTarget != null && target != null )\n\t\t\t\tnewTarget.Invoke( from, target );\n\n\t\t\tfrom.TargetLocked = false;\n\t\t}\n\n\t\tpublic static void TargetedItemUse( NetState state, PacketReader pvSrc )\n\t\t{\n\t\t\tvar from = state.Mobile;\n\n\t\t\tvar item = World.FindItem( pvSrc.ReadInt32() );\n\t\t\tvar target = World.FindEntity( pvSrc.ReadInt32() );\n\n\t\t\tif ( item != null )\n\t\t\t{\n\t\t\t\tvar oldTarget = from.Target;\n\t\t\t\tfrom.TargetLocked = true;\n\n\t\t\t\tfrom.Use( item );\n\n\t\t\t\tvar newTarget = from.Target;\n\n\t\t\t\tif ( oldTarget != newTarget && newTarget != null && target != null )\n\t\t\t\t\tnewTarget.Invoke( from, target );\n\n\t\t\t\tfrom.TargetLocked = false;\n\t\t\t}\n\t\t}\n\n\t\tpublic static void EquipMacro( NetState ns, PacketReader pvSrc )\n\t\t{\n\t\t\tint count = pvSrc.ReadByte();\n\n\t\t\tvar serialList = new List( count );\n\n\t\t\tfor ( var i = 0; i < count; ++i )\n\t\t\t{\n\t\t\t\tSerial s = pvSrc.ReadInt32();\n\t\t\t\tserialList.Add( s );\n\t\t\t}\n\n\t\t\tEventSink.InvokeEquipMacro( new EquipMacroEventArgs( ns, serialList ) );\n\t\t}\n\n\t\tpublic static void UnequipMacro( NetState ns, PacketReader pvSrc )\n\t\t{\n\t\t\tint count = pvSrc.ReadByte();\n\n\t\t\tvar layers = new List( count );\n\n\t\t\tfor ( var i = 0; i < count; ++i )\n\t\t\t{\n\t\t\t\tint s = pvSrc.ReadInt16();\n\t\t\t\tlayers.Add( s );\n\t\t\t}\n\n\t\t\tEventSink.InvokeUnequipMacro( new UnequipMacroEventArgs( ns, layers ) );\n\t\t}\n\n\t\tpublic static void TargetByResourceMacro( NetState ns, PacketReader pvSrc )\n\t\t{\n\t\t\t/*int command = */\n\t\t\tpvSrc.ReadInt16();\n\t\t\tSerial serial = pvSrc.ReadInt32();\n\t\t\tint resourceType = pvSrc.ReadInt16();\n\n\t\t\tif ( serial.IsItem )\n\t\t\t{\n\t\t\t\tvar e = new TargetByResourceMacroEventArgs( ns, World.FindItem( serial ), resourceType );\n\t\t\t\tEventSink.InvokeTargetByResourceMacro( e );\n\t\t\t}\n\t\t}\n\n\t\tpublic static void BatchQueryProperties( NetState state, PacketReader pvSrc )\n\t\t{\n\t\t\tif ( !ObjectPropertyListPacket.Enabled )\n\t\t\t\treturn;\n\n\t\t\tvar from = state.Mobile;\n\n\t\t\tvar length = pvSrc.Size - 3;\n\n\t\t\tif ( length < 0 || ( length % 4 ) != 0 )\n\t\t\t\treturn;\n\n\t\t\tvar count = length / 4;\n\n\t\t\tfor ( var i = 0; i < count; ++i )\n\t\t\t{\n\t\t\t\tSerial s = pvSrc.ReadInt32();\n\n\t\t\t\tif ( s.IsMobile )\n\t\t\t\t{", "answers": ["\t\t\t\t\tvar m = World.FindMobile( s );"], "length": 6029, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "cb6e28a4-9d3a-471e-a57b-37e8d50b4f4e", "reasoning": "The method BatchQueryProperties processes a batch of object serials. After reading a Serial s, the code checks if s.IsMobile. The next logical step is to retrieve the Mobile object for that serial, following the pattern used elsewhere (e.g., LookReq). Therefore the next line should declare a variable holding the mobile via World.FindMobile(s).", "reasoning_model_answer": "var m = World.FindMobile( s );", "assistant_with_reasoning": "\nThe method BatchQueryProperties processes a batch of object serials. After reading a Serial s, the code checks if s.IsMobile. The next logical step is to retrieve the Mobile object for that serial, following the pattern used elsewhere (e.g., LookReq). Therefore the next line should declare a variable holding the mobile via World.FindMobile(s).\n\nvar m = World.FindMobile( s );", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 6.799, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 45314, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "var m = World.FindMobile( s );", "score": 0.92, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "# ----------------------------------------------------------------------------\n# pyglet\n# Copyright (c) 2006-2008 Alex Holkner\n# Copyright (c) 2008-2021 pyglet contributors\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions\n# are met:\n#\n# * Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n# * Redistributions in binary form must reproduce the above copyright\n# notice, this list of conditions and the following disclaimer in\n# the documentation and/or other materials provided with the\n# distribution.\n# * Neither the name of pyglet nor the names of its\n# contributors may be used to endorse or promote products\n# derived from this software without specific prior written\n# permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.\n# ----------------------------------------------------------------------------\nimport sys\n\n# Most of this file is win32con.py from Python for Windows Extensions:\n# http://www.python.net/crew/mhammond/win32/\n\n# From Windows 2000 API SuperBible:\n\nVK_OEM_1 = 0xba\nVK_OEM_PLUS = 0xbb\nVK_OEM_COMMA = 0xbc\nVK_OEM_MINUS = 0xbd\nVK_OEM_PERIOD = 0xbe\nVK_OEM_2 = 0xbf\nVK_OEM_3 = 0xc0\nVK_OEM_4 = 0xdb\nVK_OEM_5 = 0xdc\nVK_OEM_6 = 0xdd\nVK_OEM_7 = 0xde\nVK_OEM_8 = 0xdf\nVK_OEM_102 = 0xe2\n\n# Copyright (c) 1994-2001, Mark Hammond \n# All rights reserved.\n# \n# Redistribution and use in source and binary forms, with or without \n# modification, are permitted provided that the following conditions \n# are met:\n# \n# Redistributions of source code must retain the above copyright notice, \n# this list of conditions and the following disclaimer.\n# \n# Redistributions in binary form must reproduce the above copyright \n# notice, this list of conditions and the following disclaimer in \n# the documentation and/or other materials provided with the distribution.\n# \n# Neither name of Mark Hammond nor the name of contributors may be used \n# to endorse or promote products derived from this software without \n# specific prior written permission. \n# \n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS\n# IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED\n# TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n# PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR\n# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. P\n\n# From WinGDI.h\nPFD_TYPE_RGBA = 0\nPFD_TYPE_COLORINDEX = 1\nPFD_MAIN_PLANE = 0\nPFD_OVERLAY_PLANE = 1\nPFD_UNDERLAY_PLANE = (-1)\nPFD_DOUBLEBUFFER = 0x00000001\nPFD_STEREO = 0x00000002\nPFD_DRAW_TO_WINDOW = 0x00000004\nPFD_DRAW_TO_BITMAP = 0x00000008\nPFD_SUPPORT_GDI = 0x00000010\nPFD_SUPPORT_OPENGL = 0x00000020\nPFD_GENERIC_FORMAT = 0x00000040\nPFD_NEED_PALETTE = 0x00000080\nPFD_NEED_SYSTEM_PALETTE = 0x00000100\nPFD_SWAP_EXCHANGE = 0x00000200\nPFD_SWAP_COPY = 0x00000400\nPFD_SWAP_LAYER_BUFFERS = 0x00000800\nPFD_GENERIC_ACCELERATED = 0x00001000\nPFD_SUPPORT_DIRECTDRAW = 0x00002000\nPFD_DEPTH_DONTCARE = 0x20000000\nPFD_DOUBLEBUFFER_DONTCARE = 0x40000000\nPFD_STEREO_DONTCARE = 0x80000000\n\n# Generated by h2py from commdlg.h (plus modifications 4jan98)\nWINVER = 1280\nWM_USER = 1024\nPY_0U = 0\nOFN_READONLY = 1\nOFN_OVERWRITEPROMPT = 2\nOFN_HIDEREADONLY = 4\nOFN_NOCHANGEDIR = 8\nOFN_SHOWHELP = 16\nOFN_ENABLEHOOK = 32\nOFN_ENABLETEMPLATE = 64\nOFN_ENABLETEMPLATEHANDLE = 128\nOFN_NOVALIDATE = 256\nOFN_ALLOWMULTISELECT = 512\nOFN_EXTENSIONDIFFERENT = 1024\nOFN_PATHMUSTEXIST = 2048\nOFN_FILEMUSTEXIST = 4096\nOFN_CREATEPROMPT = 8192\nOFN_SHAREAWARE = 16384\nOFN_NOREADONLYRETURN = 32768\nOFN_NOTESTFILECREATE = 65536\nOFN_NONETWORKBUTTON = 131072\nOFN_NOLONGNAMES = 262144\nOFN_EXPLORER = 524288 # new look commdlg\nOFN_NODEREFERENCELINKS = 1048576\nOFN_LONGNAMES = 2097152 # force long names for 3.x modules\nOFN_ENABLEINCLUDENOTIFY = 4194304 # send include message to callback\nOFN_ENABLESIZING = 8388608\nOFN_DONTADDTORECENT = 33554432\nOFN_FORCESHOWHIDDEN = 268435456 # Show All files including System and hidden files\nOFN_EX_NOPLACESBAR = 1\nOFN_SHAREFALLTHROUGH = 2\nOFN_SHARENOWARN = 1\nOFN_SHAREWARN = 0\nCDN_FIRST = (PY_0U-601)\nCDN_LAST = (PY_0U-699)\nCDN_INITDONE = (CDN_FIRST - 0)\nCDN_SELCHANGE = (CDN_FIRST - 1)\nCDN_FOLDERCHANGE = (CDN_FIRST - 2)\nCDN_SHAREVIOLATION = (CDN_FIRST - 3)\nCDN_HELP = (CDN_FIRST - 4)\nCDN_FILEOK = (CDN_FIRST - 5)\nCDN_TYPECHANGE = (CDN_FIRST - 6)\nCDN_INCLUDEITEM = (CDN_FIRST - 7)\nCDM_FIRST = (WM_USER + 100)\nCDM_LAST = (WM_USER + 200)\nCDM_GETSPEC = (CDM_FIRST + 0)\nCDM_GETFILEPATH = (CDM_FIRST + 1)\nCDM_GETFOLDERPATH = (CDM_FIRST + 2)\nCDM_GETFOLDERIDLIST = (CDM_FIRST + 3)\nCDM_SETCONTROLTEXT = (CDM_FIRST + 4)\nCDM_HIDECONTROL = (CDM_FIRST + 5)\nCDM_SETDEFEXT = (CDM_FIRST + 6)\nCC_RGBINIT = 1\nCC_FULLOPEN = 2\nCC_PREVENTFULLOPEN = 4\nCC_SHOWHELP = 8\nCC_ENABLEHOOK = 16\nCC_ENABLETEMPLATE = 32\nCC_ENABLETEMPLATEHANDLE = 64\nCC_SOLIDCOLOR = 128\nCC_ANYCOLOR = 256\nFR_DOWN = 1\nFR_WHOLEWORD = 2\nFR_MATCHCASE = 4\nFR_FINDNEXT = 8\nFR_REPLACE = 16\nFR_REPLACEALL = 32\nFR_DIALOGTERM = 64\nFR_SHOWHELP = 128\nFR_ENABLEHOOK = 256\nFR_ENABLETEMPLATE = 512\nFR_NOUPDOWN = 1024\nFR_NOMATCHCASE = 2048\nFR_NOWHOLEWORD = 4096\nFR_ENABLETEMPLATEHANDLE = 8192\nFR_HIDEUPDOWN = 16384\nFR_HIDEMATCHCASE = 32768\nFR_HIDEWHOLEWORD = 65536\nCF_SCREENFONTS = 1\nCF_PRINTERFONTS = 2\nCF_BOTH = (CF_SCREENFONTS | CF_PRINTERFONTS)\nCF_SHOWHELP = 4\nCF_ENABLEHOOK = 8\nCF_ENABLETEMPLATE = 16\nCF_ENABLETEMPLATEHANDLE = 32\nCF_INITTOLOGFONTSTRUCT = 64\nCF_USESTYLE = 128\nCF_EFFECTS = 256\nCF_APPLY = 512\nCF_ANSIONLY = 1024\nCF_SCRIPTSONLY = CF_ANSIONLY\nCF_NOVECTORFONTS = 2048\nCF_NOOEMFONTS = CF_NOVECTORFONTS\nCF_NOSIMULATIONS = 4096\nCF_LIMITSIZE = 8192\nCF_FIXEDPITCHONLY = 16384\nCF_WYSIWYG = 32768 # must also have CF_SCREENFONTS & CF_PRINTERFONTS\nCF_FORCEFONTEXIST = 65536\nCF_SCALABLEONLY = 131072\nCF_TTONLY = 262144\nCF_NOFACESEL = 524288\nCF_NOSTYLESEL = 1048576\nCF_NOSIZESEL = 2097152\nCF_SELECTSCRIPT = 4194304\nCF_NOSCRIPTSEL = 8388608\nCF_NOVERTFONTS = 16777216\nSIMULATED_FONTTYPE = 32768\nPRINTER_FONTTYPE = 16384\nSCREEN_FONTTYPE = 8192\nBOLD_FONTTYPE = 256\nITALIC_FONTTYPE = 512\nREGULAR_FONTTYPE = 1024\nOPENTYPE_FONTTYPE = 65536\nTYPE1_FONTTYPE = 131072\nDSIG_FONTTYPE = 262144\nWM_CHOOSEFONT_GETLOGFONT = (WM_USER + 1)\nWM_CHOOSEFONT_SETLOGFONT = (WM_USER + 101)\nWM_CHOOSEFONT_SETFLAGS = (WM_USER + 102)\nLBSELCHSTRINGA = \"commdlg_LBSelChangedNotify\"\nSHAREVISTRINGA = \"commdlg_ShareViolation\"\nFILEOKSTRINGA = \"commdlg_FileNameOK\"\nCOLOROKSTRINGA = \"commdlg_ColorOK\"\nSETRGBSTRINGA = \"commdlg_SetRGBColor\"\nHELPMSGSTRINGA = \"commdlg_help\"\nFINDMSGSTRINGA = \"commdlg_FindReplace\"\nLBSELCHSTRING = LBSELCHSTRINGA\nSHAREVISTRING = SHAREVISTRINGA\nFILEOKSTRING = FILEOKSTRINGA\nCOLOROKSTRING = COLOROKSTRINGA\nSETRGBSTRING = SETRGBSTRINGA\nHELPMSGSTRING = HELPMSGSTRINGA\nFINDMSGSTRING = FINDMSGSTRINGA\nCD_LBSELNOITEMS = -1\nCD_LBSELCHANGE = 0\nCD_LBSELSUB = 1\nCD_LBSELADD = 2\nPD_ALLPAGES = 0\nPD_SELECTION = 1\nPD_PAGENUMS = 2\nPD_NOSELECTION = 4\nPD_NOPAGENUMS = 8\nPD_COLLATE = 16\nPD_PRINTTOFILE = 32\nPD_PRINTSETUP = 64\nPD_NOWARNING = 128\nPD_RETURNDC = 256\nPD_RETURNIC = 512\nPD_RETURNDEFAULT = 1024\nPD_SHOWHELP = 2048\nPD_ENABLEPRINTHOOK = 4096\nPD_ENABLESETUPHOOK = 8192\nPD_ENABLEPRINTTEMPLATE = 16384\nPD_ENABLESETUPTEMPLATE = 32768\nPD_ENABLEPRINTTEMPLATEHANDLE = 65536\nPD_ENABLESETUPTEMPLATEHANDLE = 131072\nPD_USEDEVMODECOPIES = 262144\nPD_DISABLEPRINTTOFILE = 524288\nPD_HIDEPRINTTOFILE = 1048576\nPD_NONETWORKBUTTON = 2097152\nDN_DEFAULTPRN = 1\nWM_PSD_PAGESETUPDLG = (WM_USER )\nWM_PSD_FULLPAGERECT = (WM_USER+1)\nWM_PSD_MINMARGINRECT = (WM_USER+2)\nWM_PSD_MARGINRECT = (WM_USER+3)\nWM_PSD_GREEKTEXTRECT = (WM_USER+4)\nWM_PSD_ENVSTAMPRECT = (WM_USER+5)\nWM_PSD_YAFULLPAGERECT = (WM_USER+6)\nPSD_DEFAULTMINMARGINS = 0 # default (printer's)\nPSD_INWININIINTLMEASURE = 0 # 1st of 4 possible\nPSD_MINMARGINS = 1 # use caller's\nPSD_MARGINS = 2 # use caller's\nPSD_INTHOUSANDTHSOFINCHES = 4 # 2nd of 4 possible\nPSD_INHUNDREDTHSOFMILLIMETERS = 8 # 3rd of 4 possible\nPSD_DISABLEMARGINS = 16\nPSD_DISABLEPRINTER = 32\nPSD_NOWARNING = 128 # must be same as PD_*\nPSD_DISABLEORIENTATION = 256\nPSD_RETURNDEFAULT = 1024 # must be same as PD_*\nPSD_DISABLEPAPER = 512\nPSD_SHOWHELP = 2048 # must be same as PD_*\nPSD_ENABLEPAGESETUPHOOK = 8192 # must be same as PD_*\nPSD_ENABLEPAGESETUPTEMPLATE = 32768 # must be same as PD_*\nPSD_ENABLEPAGESETUPTEMPLATEHANDLE = 131072 # must be same as PD_*\nPSD_ENABLEPAGEPAINTHOOK = 262144\nPSD_DISABLEPAGEPAINTING = 524288\nPSD_NONETWORKBUTTON = 2097152 # must be same as PD_*\n\n# Generated by h2py from winreg.h\nHKEY_CLASSES_ROOT = -2147483648\nHKEY_CURRENT_USER = -2147483647\nHKEY_LOCAL_MACHINE = -2147483646\nHKEY_USERS = -2147483645\nHKEY_PERFORMANCE_DATA = -2147483644\nHKEY_CURRENT_CONFIG = -2147483643\nHKEY_DYN_DATA = -2147483642\nHKEY_PERFORMANCE_TEXT = -2147483568 # ?? 4Jan98\nHKEY_PERFORMANCE_NLSTEXT = -2147483552 # ?? 4Jan98\n\n# Generated by h2py from winuser.h\nHWND_BROADCAST = 65535\nHWND_DESKTOP = 0\nHWND_TOP = 0\nHWND_BOTTOM = 1\nHWND_TOPMOST = -1\nHWND_NOTOPMOST = -2\nHWND_MESSAGE = -3\n\n# winuser.h line 4601\nSM_CXSCREEN = 0\nSM_CYSCREEN = 1\nSM_CXVSCROLL = 2\nSM_CYHSCROLL = 3\nSM_CYCAPTION = 4\nSM_CXBORDER = 5\nSM_CYBORDER = 6\nSM_CXDLGFRAME = 7\nSM_CYDLGFRAME = 8\nSM_CYVTHUMB = 9\nSM_CXHTHUMB = 10\nSM_CXICON = 11\nSM_CYICON = 12\nSM_CXCURSOR = 13\nSM_CYCURSOR = 14\nSM_CYMENU = 15\nSM_CXFULLSCREEN = 16\nSM_CYFULLSCREEN = 17\nSM_CYKANJIWINDOW = 18\nSM_MOUSEPRESENT = 19\nSM_CYVSCROLL = 20\nSM_CXHSCROLL = 21\nSM_DEBUG = 22\nSM_SWAPBUTTON = 23\nSM_RESERVED1 = 24\nSM_RESERVED2 = 25\nSM_RESERVED3 = 26\nSM_RESERVED4 = 27\nSM_CXMIN = 28\nSM_CYMIN = 29\nSM_CXSIZE = 30\nSM_CYSIZE = 31\nSM_CXFRAME = 32\nSM_CYFRAME = 33\nSM_CXMINTRACK = 34\nSM_CYMINTRACK = 35\nSM_CXDOUBLECLK = 36\nSM_CYDOUBLECLK = 37\nSM_CXICONSPACING = 38\nSM_CYICONSPACING = 39\nSM_MENUDROPALIGNMENT = 40\nSM_PENWINDOWS = 41\nSM_DBCSENABLED = 42\nSM_CMOUSEBUTTONS = 43\nSM_CXFIXEDFRAME = SM_CXDLGFRAME\nSM_CYFIXEDFRAME = SM_CYDLGFRAME\nSM_CXSIZEFRAME = SM_CXFRAME\nSM_CYSIZEFRAME = SM_CYFRAME\nSM_SECURE = 44\nSM_CXEDGE = 45\nSM_CYEDGE = 46\nSM_CXMINSPACING = 47\nSM_CYMINSPACING = 48\nSM_CXSMICON = 49\nSM_CYSMICON = 50\nSM_CYSMCAPTION = 51\nSM_CXSMSIZE = 52\nSM_CYSMSIZE = 53\nSM_CXMENUSIZE = 54\nSM_CYMENUSIZE = 55\nSM_ARRANGE = 56\nSM_CXMINIMIZED = 57\nSM_CYMINIMIZED = 58\nSM_CXMAXTRACK = 59\nSM_CYMAXTRACK = 60\nSM_CXMAXIMIZED = 61\nSM_CYMAXIMIZED = 62\nSM_NETWORK = 63\nSM_CLEANBOOT = 67\nSM_CXDRAG = 68\nSM_CYDRAG = 69\nSM_SHOWSOUNDS = 70\nSM_CXMENUCHECK = 71\nSM_CYMENUCHECK = 72\nSM_SLOWMACHINE = 73\nSM_MIDEASTENABLED = 74\nSM_MOUSEWHEELPRESENT = 75\nSM_XVIRTUALSCREEN = 76\nSM_YVIRTUALSCREEN = 77\nSM_CXVIRTUALSCREEN = 78\nSM_CYVIRTUALSCREEN = 79\nSM_CMONITORS = 80\nSM_SAMEDISPLAYFORMAT = 81\nSM_CMETRICS = 83\nMNC_IGNORE = 0\nMNC_CLOSE = 1\nMNC_EXECUTE = 2\nMNC_SELECT = 3\nMNS_NOCHECK = -2147483648\nMNS_MODELESS = 1073741824\nMNS_DRAGDROP = 536870912\nMNS_AUTODISMISS = 268435456\nMNS_NOTIFYBYPOS = 134217728\nMNS_CHECKORBMP = 67108864\nMIM_MAXHEIGHT = 1\nMIM_BACKGROUND = 2\nMIM_HELPID = 4\nMIM_MENUDATA = 8\nMIM_STYLE = 16\nMIM_APPLYTOSUBMENUS = -2147483648\nMND_CONTINUE = 0\nMND_ENDMENU = 1\nMNGOF_GAP = 3\nMNGO_NOINTERFACE = 0\nMNGO_NOERROR = 1\nMIIM_STATE = 1\nMIIM_ID = 2\nMIIM_SUBMENU = 4\nMIIM_CHECKMARKS = 8\nMIIM_TYPE = 16\nMIIM_DATA = 32\nMIIM_STRING = 64\nMIIM_BITMAP = 128\nMIIM_FTYPE = 256\nHBMMENU_CALLBACK = -1\nHBMMENU_SYSTEM = 1\nHBMMENU_MBAR_RESTORE = 2\nHBMMENU_MBAR_MINIMIZE = 3\nHBMMENU_MBAR_CLOSE = 5\nHBMMENU_MBAR_CLOSE_D = 6\nHBMMENU_MBAR_MINIMIZE_D = 7\nHBMMENU_POPUP_CLOSE = 8\nHBMMENU_POPUP_RESTORE = 9\nHBMMENU_POPUP_MAXIMIZE = 10\nHBMMENU_POPUP_MINIMIZE = 11\nGMDI_USEDISABLED = 1\nGMDI_GOINTOPOPUPS = 2\nTPM_LEFTBUTTON = 0\nTPM_RIGHTBUTTON = 2\nTPM_LEFTALIGN = 0\nTPM_CENTERALIGN = 4\nTPM_RIGHTALIGN = 8\nTPM_TOPALIGN = 0\nTPM_VCENTERALIGN = 16\nTPM_BOTTOMALIGN = 32\nTPM_HORIZONTAL = 0\nTPM_VERTICAL = 64\nTPM_NONOTIFY = 128\nTPM_RETURNCMD = 256\nTPM_RECURSE = 1\nDOF_EXECUTABLE = 32769\nDOF_DOCUMENT = 32770\nDOF_DIRECTORY = 32771\nDOF_MULTIPLE = 32772\nDOF_PROGMAN = 1\nDOF_SHELLDATA = 2\nDO_DROPFILE = 1162627398\nDO_PRINTFILE = 1414419024\nDT_TOP = 0\nDT_LEFT = 0\nDT_CENTER = 1\nDT_RIGHT = 2\nDT_VCENTER = 4\nDT_BOTTOM = 8\nDT_WORDBREAK = 16\nDT_SINGLELINE = 32\nDT_EXPANDTABS = 64\nDT_TABSTOP = 128\nDT_NOCLIP = 256\nDT_EXTERNALLEADING = 512\nDT_CALCRECT = 1024\nDT_NOPREFIX = 2048\nDT_INTERNAL = 4096\nDT_EDITCONTROL = 8192\nDT_PATH_ELLIPSIS = 16384\nDT_END_ELLIPSIS = 32768\nDT_MODIFYSTRING = 65536\nDT_RTLREADING = 131072\nDT_WORD_ELLIPSIS = 262144\nDST_COMPLEX = 0\nDST_TEXT = 1\nDST_PREFIXTEXT = 2\nDST_ICON = 3\nDST_BITMAP = 4\nDSS_NORMAL = 0\nDSS_UNION = 16\nDSS_DISABLED = 32\nDSS_MONO = 128\nDSS_RIGHT = 32768\nDCX_WINDOW = 1\nDCX_CACHE = 2\nDCX_NORESETATTRS = 4\nDCX_CLIPCHILDREN = 8\nDCX_CLIPSIBLINGS = 16\nDCX_PARENTCLIP = 32\nDCX_EXCLUDERGN = 64\nDCX_INTERSECTRGN = 128\nDCX_EXCLUDEUPDATE = 256\nDCX_INTERSECTUPDATE = 512\nDCX_LOCKWINDOWUPDATE = 1024\nDCX_VALIDATE = 2097152\nCUDR_NORMAL = 0\nCUDR_NOSNAPTOGRID = 1\nCUDR_NORESOLVEPOSITIONS = 2\nCUDR_NOCLOSEGAPS = 4\nCUDR_NEGATIVECOORDS = 8\nCUDR_NOPRIMARY = 16\nRDW_INVALIDATE = 1\nRDW_INTERNALPAINT = 2\nRDW_ERASE = 4\nRDW_VALIDATE = 8\nRDW_NOINTERNALPAINT = 16\nRDW_NOERASE = 32\nRDW_NOCHILDREN = 64\nRDW_ALLCHILDREN = 128\nRDW_UPDATENOW = 256\nRDW_ERASENOW = 512\nRDW_FRAME = 1024\nRDW_NOFRAME = 2048\nSW_SCROLLCHILDREN = 1\nSW_INVALIDATE = 2\nSW_ERASE = 4\nSW_SMOOTHSCROLL = 16 # Use smooth scrolling\nESB_ENABLE_BOTH = 0\nESB_DISABLE_BOTH = 3\nESB_DISABLE_LEFT = 1\nESB_DISABLE_RIGHT = 2\nESB_DISABLE_UP = 1\nESB_DISABLE_DOWN = 2\nESB_DISABLE_LTUP = ESB_DISABLE_LEFT\nESB_DISABLE_RTDN = ESB_DISABLE_RIGHT\nHELPINFO_WINDOW = 1\nHELPINFO_MENUITEM = 2\nMB_OK = 0\nMB_OKCANCEL = 1\nMB_ABORTRETRYIGNORE = 2\nMB_YESNOCANCEL = 3\nMB_YESNO = 4\nMB_RETRYCANCEL = 5\nMB_ICONHAND = 16\nMB_ICONQUESTION = 32\nMB_ICONEXCLAMATION = 48\nMB_ICONASTERISK = 64\nMB_ICONWARNING = MB_ICONEXCLAMATION\nMB_ICONERROR = MB_ICONHAND\nMB_ICONINFORMATION = MB_ICONASTERISK\nMB_ICONSTOP = MB_ICONHAND\nMB_DEFBUTTON1 = 0\nMB_DEFBUTTON2 = 256\nMB_DEFBUTTON3 = 512\nMB_DEFBUTTON4 = 768\nMB_APPLMODAL = 0\nMB_SYSTEMMODAL = 4096\nMB_TASKMODAL = 8192\nMB_HELP = 16384\nMB_NOFOCUS = 32768\nMB_SETFOREGROUND = 65536\nMB_DEFAULT_DESKTOP_ONLY = 131072\nMB_TOPMOST = 262144\nMB_RIGHT = 524288\nMB_RTLREADING = 1048576\nMB_SERVICE_NOTIFICATION = 2097152\nMB_TYPEMASK = 15\nMB_USERICON = 128\nMB_ICONMASK = 240\nMB_DEFMASK = 3840\nMB_MODEMASK = 12288\nMB_MISCMASK = 49152\n# winuser.h line 6373\nCWP_ALL = 0\nCWP_SKIPINVISIBLE = 1\nCWP_SKIPDISABLED = 2\nCWP_SKIPTRANSPARENT = 4\nCTLCOLOR_MSGBOX = 0\nCTLCOLOR_EDIT = 1\nCTLCOLOR_LISTBOX = 2\nCTLCOLOR_BTN = 3\nCTLCOLOR_DLG = 4\nCTLCOLOR_SCROLLBAR = 5\nCTLCOLOR_STATIC = 6\nCTLCOLOR_MAX = 7\nCOLOR_SCROLLBAR = 0\nCOLOR_BACKGROUND = 1\nCOLOR_ACTIVECAPTION = 2\nCOLOR_INACTIVECAPTION = 3\nCOLOR_MENU = 4\nCOLOR_WINDOW = 5\nCOLOR_WINDOWFRAME = 6\nCOLOR_MENUTEXT = 7\nCOLOR_WINDOWTEXT = 8\nCOLOR_CAPTIONTEXT = 9\nCOLOR_ACTIVEBORDER = 10\nCOLOR_INACTIVEBORDER = 11\nCOLOR_APPWORKSPACE = 12\nCOLOR_HIGHLIGHT = 13\nCOLOR_HIGHLIGHTTEXT = 14\nCOLOR_BTNFACE = 15\nCOLOR_BTNSHADOW = 16\nCOLOR_GRAYTEXT = 17\nCOLOR_BTNTEXT = 18\nCOLOR_INACTIVECAPTIONTEXT = 19\nCOLOR_BTNHIGHLIGHT = 20\nCOLOR_3DDKSHADOW = 21\nCOLOR_3DLIGHT = 22\nCOLOR_INFOTEXT = 23\nCOLOR_INFOBK = 24\nCOLOR_HOTLIGHT = 26\nCOLOR_GRADIENTACTIVECAPTION = 27\nCOLOR_GRADIENTINACTIVECAPTION = 28\nCOLOR_DESKTOP = COLOR_BACKGROUND\nCOLOR_3DFACE = COLOR_BTNFACE\nCOLOR_3DSHADOW = COLOR_BTNSHADOW\nCOLOR_3DHIGHLIGHT = COLOR_BTNHIGHLIGHT\nCOLOR_3DHILIGHT = COLOR_BTNHIGHLIGHT\nCOLOR_BTNHILIGHT = COLOR_BTNHIGHLIGHT\nGW_HWNDFIRST = 0\nGW_HWNDLAST = 1\nGW_HWNDNEXT = 2\nGW_HWNDPREV = 3\nGW_OWNER = 4\nGW_CHILD = 5\nGW_ENABLEDPOPUP = 6\nGW_MAX = 6\nMF_INSERT = 0\nMF_CHANGE = 128\nMF_APPEND = 256\nMF_DELETE = 512\nMF_REMOVE = 4096\nMF_BYCOMMAND = 0\nMF_BYPOSITION = 1024\nMF_SEPARATOR = 2048\nMF_ENABLED = 0\nMF_GRAYED = 1\nMF_DISABLED = 2\nMF_UNCHECKED = 0\nMF_CHECKED = 8\nMF_USECHECKBITMAPS = 512\nMF_STRING = 0\nMF_BITMAP = 4\nMF_OWNERDRAW = 256\nMF_POPUP = 16\nMF_MENUBARBREAK = 32\nMF_MENUBREAK = 64\nMF_UNHILITE = 0\nMF_HILITE = 128\nMF_DEFAULT = 4096\nMF_SYSMENU = 8192\nMF_HELP = 16384\nMF_RIGHTJUSTIFY = 16384\nMF_MOUSESELECT = 32768\nMF_END = 128\nMFT_STRING = MF_STRING\nMFT_BITMAP = MF_BITMAP\nMFT_MENUBARBREAK = MF_MENUBARBREAK\nMFT_MENUBREAK = MF_MENUBREAK\nMFT_OWNERDRAW = MF_OWNERDRAW\nMFT_RADIOCHECK = 512\nMFT_SEPARATOR = MF_SEPARATOR\nMFT_RIGHTORDER = 8192\nMFT_RIGHTJUSTIFY = MF_RIGHTJUSTIFY\nMFS_GRAYED = 3\nMFS_DISABLED = MFS_GRAYED\nMFS_CHECKED = MF_CHECKED\nMFS_HILITE = MF_HILITE\nMFS_ENABLED = MF_ENABLED\nMFS_UNCHECKED = MF_UNCHECKED\nMFS_UNHILITE = MF_UNHILITE\nMFS_DEFAULT = MF_DEFAULT\nMFS_MASK = 4235\nMFS_HOTTRACKDRAWN = 268435456\nMFS_CACHEDBMP = 536870912\nMFS_BOTTOMGAPDROP = 1073741824\nMFS_TOPGAPDROP = -2147483648\nMFS_GAPDROP = -1073741824\nSC_SIZE = 61440\nSC_MOVE = 61456\nSC_MINIMIZE = 61472\nSC_MAXIMIZE = 61488\nSC_NEXTWINDOW = 61504\nSC_PREVWINDOW = 61520\nSC_CLOSE = 61536\nSC_VSCROLL = 61552\nSC_HSCROLL = 61568\nSC_MOUSEMENU = 61584\nSC_KEYMENU = 61696\nSC_ARRANGE = 61712\nSC_RESTORE = 61728\nSC_TASKLIST = 61744\nSC_SCREENSAVE = 61760\nSC_HOTKEY = 61776\nSC_DEFAULT = 61792\nSC_MONITORPOWER = 61808\nSC_CONTEXTHELP = 61824\nSC_SEPARATOR = 61455\nSC_ICON = SC_MINIMIZE\nSC_ZOOM = SC_MAXIMIZE\nIDC_ARROW = 32512\nIDC_IBEAM = 32513\nIDC_WAIT = 32514\nIDC_CROSS = 32515\nIDC_UPARROW = 32516\nIDC_SIZE = 32640 # OBSOLETE: use IDC_SIZEALL\nIDC_ICON = 32641 # OBSOLETE: use IDC_ARROW\nIDC_SIZENWSE = 32642\nIDC_SIZENESW = 32643\nIDC_SIZEWE = 32644\nIDC_SIZENS = 32645\nIDC_SIZEALL = 32646\nIDC_NO = 32648\nIDC_HAND = 32649\nIDC_APPSTARTING = 32650\nIDC_HELP = 32651\nIMAGE_BITMAP = 0\nIMAGE_ICON = 1\nIMAGE_CURSOR = 2\nIMAGE_ENHMETAFILE = 3\nLR_DEFAULTCOLOR = 0\nLR_MONOCHROME = 1\nLR_COLOR = 2\nLR_COPYRETURNORG = 4\nLR_COPYDELETEORG = 8\nLR_LOADFROMFILE = 16\nLR_LOADTRANSPARENT = 32\nLR_DEFAULTSIZE = 64\nLR_LOADREALSIZE = 128\nLR_LOADMAP3DCOLORS = 4096\nLR_CREATEDIBSECTION = 8192\nLR_COPYFROMRESOURCE = 16384\nLR_SHARED = 32768\nDI_MASK = 1\nDI_IMAGE = 2\nDI_NORMAL = 3\nDI_COMPAT = 4\nDI_DEFAULTSIZE = 8\nRES_ICON = 1\nRES_CURSOR = 2\nOBM_CLOSE = 32754\nOBM_UPARROW = 32753\nOBM_DNARROW = 32752\nOBM_RGARROW = 32751\nOBM_LFARROW = 32750\nOBM_REDUCE = 32749\nOBM_ZOOM = 32748\nOBM_RESTORE = 32747\nOBM_REDUCED = 32746\nOBM_ZOOMD = 32745\nOBM_RESTORED = 32744\nOBM_UPARROWD = 32743\nOBM_DNARROWD = 32742\nOBM_RGARROWD = 32741\nOBM_LFARROWD = 32740\nOBM_MNARROW = 32739\nOBM_COMBO = 32738\nOBM_UPARROWI = 32737\nOBM_DNARROWI = 32736\nOBM_RGARROWI = 32735\nOBM_LFARROWI = 32734\nOBM_OLD_CLOSE = 32767\nOBM_SIZE = 32766\nOBM_OLD_UPARROW = 32765\nOBM_OLD_DNARROW = 32764\nOBM_OLD_RGARROW = 32763\nOBM_OLD_LFARROW = 32762\nOBM_BTSIZE = 32761\nOBM_CHECK = 32760\nOBM_CHECKBOXES = 32759\nOBM_BTNCORNERS = 32758\nOBM_OLD_REDUCE = 32757\nOBM_OLD_ZOOM = 32756\nOBM_OLD_RESTORE = 32755\nOCR_NORMAL = 32512\nOCR_IBEAM = 32513\nOCR_WAIT = 32514\nOCR_CROSS = 32515\nOCR_UP = 32516\nOCR_SIZE = 32640\nOCR_ICON = 32641\nOCR_SIZENWSE = 32642\nOCR_SIZENESW = 32643\nOCR_SIZEWE = 32644\nOCR_SIZENS = 32645\nOCR_SIZEALL = 32646\nOCR_ICOCUR = 32647\nOCR_NO = 32648\nOCR_HAND = 32649\nOCR_APPSTARTING = 32650\n# winuser.h line 7455\nOIC_SAMPLE = 32512\nOIC_HAND = 32513\nOIC_QUES = 32514\nOIC_BANG = 32515\nOIC_NOTE = 32516\nOIC_WINLOGO = 32517\nOIC_WARNING = OIC_BANG\nOIC_ERROR = OIC_HAND\nOIC_INFORMATION = OIC_NOTE\nORD_LANGDRIVER = 1\nIDI_APPLICATION = 32512\nIDI_HAND = 32513\nIDI_QUESTION = 32514\nIDI_EXCLAMATION = 32515\nIDI_ASTERISK = 32516\nIDI_WINLOGO = 32517\nIDI_WARNING = IDI_EXCLAMATION\nIDI_ERROR = IDI_HAND\nIDI_INFORMATION = IDI_ASTERISK\nIDOK = 1\nIDCANCEL = 2\nIDABORT = 3\nIDRETRY = 4\nIDIGNORE = 5\nIDYES = 6\nIDNO = 7\nIDCLOSE = 8\nIDHELP = 9\nES_LEFT = 0\nES_CENTER = 1\nES_RIGHT = 2\nES_MULTILINE = 4\nES_UPPERCASE = 8\nES_LOWERCASE = 16\nES_PASSWORD = 32\nES_AUTOVSCROLL = 64\nES_AUTOHSCROLL = 128\nES_NOHIDESEL = 256\nES_OEMCONVERT = 1024\nES_READONLY = 2048\nES_WANTRETURN = 4096\nES_NUMBER = 8192\nEN_SETFOCUS = 256\nEN_KILLFOCUS = 512\nEN_CHANGE = 768\nEN_UPDATE = 1024\nEN_ERRSPACE = 1280\nEN_MAXTEXT = 1281\nEN_HSCROLL = 1537\nEN_VSCROLL = 1538\nEC_LEFTMARGIN = 1\nEC_RIGHTMARGIN = 2\nEC_USEFONTINFO = 65535\nEMSIS_COMPOSITIONSTRING = 1\nEIMES_GETCOMPSTRATONCE = 1\nEIMES_CANCELCOMPSTRINFOCUS = 2\nEIMES_COMPLETECOMPSTRKILLFOCUS = 4\nEM_GETSEL = 176\nEM_SETSEL = 177\nEM_GETRECT = 178\nEM_SETRECT = 179\nEM_SETRECTNP = 180\nEM_SCROLL = 181\nEM_LINESCROLL = 182\nEM_SCROLLCARET = 183\nEM_GETMODIFY = 184\nEM_SETMODIFY = 185\nEM_GETLINECOUNT = 186\nEM_LINEINDEX = 187\nEM_SETHANDLE = 188\nEM_GETHANDLE = 189\nEM_GETTHUMB = 190\nEM_LINELENGTH = 193\nEM_REPLACESEL = 194\nEM_GETLINE = 196\nEM_LIMITTEXT = 197\nEM_CANUNDO = 198\nEM_UNDO = 199\nEM_FMTLINES = 200\nEM_LINEFROMCHAR = 201\nEM_SETTABSTOPS = 203\nEM_SETPASSWORDCHAR = 204\nEM_EMPTYUNDOBUFFER = 205\nEM_GETFIRSTVISIBLELINE = 206\nEM_SETREADONLY = 207\nEM_SETWORDBREAKPROC = 208\nEM_GETWORDBREAKPROC = 209\nEM_GETPASSWORDCHAR = 210\nEM_SETMARGINS = 211\nEM_GETMARGINS = 212\nEM_SETLIMITTEXT = EM_LIMITTEXT\nEM_GETLIMITTEXT = 213\nEM_POSFROMCHAR = 214\nEM_CHARFROMPOS = 215\nEM_SETIMESTATUS = 216\nEM_GETIMESTATUS = 217\nWB_LEFT = 0\nWB_RIGHT = 1\nWB_ISDELIMITER = 2\nBS_PUSHBUTTON = 0\nBS_DEFPUSHBUTTON = 1\nBS_CHECKBOX = 2\nBS_AUTOCHECKBOX = 3\nBS_RADIOBUTTON = 4\nBS_3STATE = 5\nBS_AUTO3STATE = 6\nBS_GROUPBOX = 7\nBS_USERBUTTON = 8\nBS_AUTORADIOBUTTON = 9\nBS_OWNERDRAW = 11\nBS_LEFTTEXT = 32\nBS_TEXT = 0\nBS_ICON = 64\nBS_BITMAP = 128\nBS_LEFT = 256\nBS_RIGHT = 512\nBS_CENTER = 768\nBS_TOP = 1024\nBS_BOTTOM = 2048\nBS_VCENTER = 3072\nBS_PUSHLIKE = 4096\nBS_MULTILINE = 8192\nBS_NOTIFY = 16384\nBS_FLAT = 32768\nBS_RIGHTBUTTON = BS_LEFTTEXT\nBN_CLICKED = 0\nBN_PAINT = 1\nBN_HILITE = 2\nBN_UNHILITE = 3\nBN_DISABLE = 4\nBN_DOUBLECLICKED = 5\nBN_PUSHED = BN_HILITE\nBN_UNPUSHED = BN_UNHILITE\nBN_DBLCLK = BN_DOUBLECLICKED\nBN_SETFOCUS = 6\nBN_KILLFOCUS = 7\nBM_GETCHECK = 240\nBM_SETCHECK = 241\nBM_GETSTATE = 242\nBM_SETSTATE = 243\nBM_SETSTYLE = 244\nBM_CLICK = 245\nBM_GETIMAGE = 246\nBM_SETIMAGE = 247\nBST_UNCHECKED = 0\nBST_CHECKED = 1\nBST_INDETERMINATE = 2\nBST_PUSHED = 4\nBST_FOCUS = 8\nSS_LEFT = 0\nSS_CENTER = 1\nSS_RIGHT = 2\nSS_ICON = 3\nSS_BLACKRECT = 4\nSS_GRAYRECT = 5\nSS_WHITERECT = 6\nSS_BLACKFRAME = 7\nSS_GRAYFRAME = 8\nSS_WHITEFRAME = 9\nSS_USERITEM = 10\nSS_SIMPLE = 11\nSS_LEFTNOWORDWRAP = 12\nSS_BITMAP = 14\nSS_OWNERDRAW = 13\nSS_ENHMETAFILE = 15\nSS_ETCHEDHORZ = 16\nSS_ETCHEDVERT = 17\nSS_ETCHEDFRAME = 18\nSS_TYPEMASK = 31\nSS_NOPREFIX = 128\nSS_NOTIFY = 256\nSS_CENTERIMAGE = 512\nSS_RIGHTJUST = 1024\nSS_REALSIZEIMAGE = 2048\nSS_SUNKEN = 4096\nSS_ENDELLIPSIS = 16384\nSS_PATHELLIPSIS = 32768\nSS_WORDELLIPSIS = 49152\nSS_ELLIPSISMASK = 49152\nSTM_SETICON = 368\nSTM_GETICON = 369\nSTM_SETIMAGE = 370\nSTM_GETIMAGE = 371\nSTN_CLICKED = 0\nSTN_DBLCLK = 1\nSTN_ENABLE = 2\nSTN_DISABLE = 3\nSTM_MSGMAX = 372\nDWL_MSGRESULT = 0\nDWL_DLGPROC = 4\nDWL_USER = 8\nDDL_READWRITE = 0\nDDL_READONLY = 1\nDDL_HIDDEN = 2\nDDL_SYSTEM = 4\nDDL_DIRECTORY = 16\nDDL_ARCHIVE = 32\nDDL_POSTMSGS = 8192\nDDL_DRIVES = 16384\nDDL_EXCLUSIVE = 32768\n\n#from winuser.h line 153\nRT_CURSOR = 1\nRT_BITMAP = 2\nRT_ICON = 3\nRT_MENU = 4\nRT_DIALOG = 5\nRT_STRING = 6\nRT_FONTDIR = 7\nRT_FONT = 8\nRT_ACCELERATOR = 9\nRT_RCDATA = 10\nRT_MESSAGETABLE = 11\nDIFFERENCE = 11\nRT_GROUP_CURSOR = (RT_CURSOR + DIFFERENCE)\nRT_GROUP_ICON = (RT_ICON + DIFFERENCE)\nRT_VERSION = 16\nRT_DLGINCLUDE = 17\nRT_PLUGPLAY = 19\nRT_VXD = 20\nRT_ANICURSOR = 21\nRT_ANIICON = 22\nRT_HTML = 23\n# from winuser.h line 218\nSB_HORZ = 0\nSB_VERT = 1\nSB_CTL = 2\nSB_BOTH = 3\nSB_LINEUP = 0\nSB_LINELEFT = 0\nSB_LINEDOWN = 1\nSB_LINERIGHT = 1\nSB_PAGEUP = 2\nSB_PAGELEFT = 2\nSB_PAGEDOWN = 3\nSB_PAGERIGHT = 3\nSB_THUMBPOSITION = 4\nSB_THUMBTRACK = 5\nSB_TOP = 6\nSB_LEFT = 6\nSB_BOTTOM = 7\nSB_RIGHT = 7\nSB_ENDSCROLL = 8\nSW_HIDE = 0\nSW_SHOWNORMAL = 1\nSW_NORMAL = 1\nSW_SHOWMINIMIZED = 2\nSW_SHOWMAXIMIZED = 3\nSW_MAXIMIZE = 3\nSW_SHOWNOACTIVATE = 4\nSW_SHOW = 5\nSW_MINIMIZE = 6\nSW_SHOWMINNOACTIVE = 7\nSW_SHOWNA = 8\nSW_RESTORE = 9\nSW_SHOWDEFAULT = 10\nSW_FORCEMINIMIZE = 11\nSW_MAX = 11\nHIDE_WINDOW = 0\nSHOW_OPENWINDOW = 1\nSHOW_ICONWINDOW = 2\nSHOW_FULLSCREEN = 3\nSHOW_OPENNOACTIVATE = 4\nSW_PARENTCLOSING = 1\nSW_OTHERZOOM = 2\nSW_PARENTOPENING = 3\nSW_OTHERUNZOOM = 4\nAW_HOR_POSITIVE = 1\nAW_HOR_NEGATIVE = 2\nAW_VER_POSITIVE = 4\nAW_VER_NEGATIVE = 8\nAW_CENTER = 16\nAW_HIDE = 65536\nAW_ACTIVATE = 131072\nAW_SLIDE = 262144\nAW_BLEND = 524288\nKF_EXTENDED = 256\nKF_DLGMODE = 2048\nKF_MENUMODE = 4096\nKF_ALTDOWN = 8192\nKF_REPEAT = 16384\nKF_UP = 32768\nVK_LBUTTON = 1\nVK_RBUTTON = 2\nVK_CANCEL = 3\nVK_MBUTTON = 4\nVK_BACK = 8\nVK_TAB = 9\nVK_CLEAR = 12\nVK_RETURN = 13\nVK_SHIFT = 16\nVK_CONTROL = 17\nVK_MENU = 18\nVK_PAUSE = 19\nVK_CAPITAL = 20\nVK_KANA = 21\nVK_HANGEUL = 21 # old name - should be here for compatibility\nVK_HANGUL = 21\nVK_JUNJA = 23\nVK_FINAL = 24\nVK_HANJA = 25\nVK_KANJI = 25\nVK_ESCAPE = 27\nVK_CONVERT = 28\nVK_NONCONVERT = 29\nVK_ACCEPT = 30\nVK_MODECHANGE = 31\nVK_SPACE = 32\nVK_PRIOR = 33\nVK_NEXT = 34\nVK_END = 35\nVK_HOME = 36\nVK_LEFT = 37\nVK_UP = 38\nVK_RIGHT = 39\nVK_DOWN = 40\nVK_SELECT = 41\nVK_PRINT = 42\nVK_EXECUTE = 43\nVK_SNAPSHOT = 44\nVK_INSERT = 45\nVK_DELETE = 46\nVK_HELP = 47\nVK_LWIN = 91\nVK_RWIN = 92\nVK_APPS = 93\nVK_NUMPAD0 = 96\nVK_NUMPAD1 = 97\nVK_NUMPAD2 = 98\nVK_NUMPAD3 = 99\nVK_NUMPAD4 = 100\nVK_NUMPAD5 = 101\nVK_NUMPAD6 = 102\nVK_NUMPAD7 = 103\nVK_NUMPAD8 = 104\nVK_NUMPAD9 = 105\nVK_MULTIPLY = 106\nVK_ADD = 107\nVK_SEPARATOR = 108\nVK_SUBTRACT = 109\nVK_DECIMAL = 110\nVK_DIVIDE = 111\nVK_F1 = 112\nVK_F2 = 113\nVK_F3 = 114\nVK_F4 = 115\nVK_F5 = 116\nVK_F6 = 117\nVK_F7 = 118\nVK_F8 = 119\nVK_F9 = 120\nVK_F10 = 121\nVK_F11 = 122\nVK_F12 = 123\nVK_F13 = 124\nVK_F14 = 125\nVK_F15 = 126\nVK_F16 = 127\nVK_F17 = 128\nVK_F18 = 129\nVK_F19 = 130\nVK_F20 = 131\nVK_F21 = 132\nVK_F22 = 133\nVK_F23 = 134\nVK_F24 = 135\nVK_NUMLOCK = 144\nVK_SCROLL = 145\nVK_LSHIFT = 160\nVK_RSHIFT = 161\nVK_LCONTROL = 162\nVK_RCONTROL = 163\nVK_LMENU = 164\nVK_RMENU = 165\nVK_PROCESSKEY = 229\nVK_ATTN = 246\nVK_CRSEL = 247\nVK_EXSEL = 248\nVK_EREOF = 249\nVK_PLAY = 250\nVK_ZOOM = 251\nVK_NONAME = 252\nVK_PA1 = 253\nVK_OEM_CLEAR = 254\n# multi-media related \"keys\"\nMOUSEEVENTF_XDOWN = 0x0080\nMOUSEEVENTF_XUP = 0x0100\nMOUSEEVENTF_WHEEL = 0x0800\nVK_XBUTTON1 = 0x05\nVK_XBUTTON2 = 0x06\nVK_VOLUME_MUTE = 0xAD\nVK_VOLUME_DOWN = 0xAE\nVK_VOLUME_UP = 0xAF\nVK_MEDIA_NEXT_TRACK = 0xB0\nVK_MEDIA_PREV_TRACK = 0xB1\nVK_MEDIA_PLAY_PAUSE = 0xB3\nVK_LAUNCH_MAIL = 0xB4\nVK_LAUNCH_MEDIA_SELECT = 0xB5\nVK_LAUNCH_APP1 = 0xB6\nVK_LAUNCH_APP2 = 0xB\nVK_BROWSER_BACK = 0xA6\nVK_BROWSER_FORWARD = 0xA7\nVK_BROWSER_REFRESH = 0xA8\nVK_BROWSER_STOP = 0xA9\nVK_BROWSER_SEARCH = 0xAA\nVK_BROWSER_FAVORITES = 0xAB\nVK_BROWSER_HOME = 0xAC\nWH_MIN = (-1)\nWH_MSGFILTER = (-1)\nWH_JOURNALRECORD = 0\nWH_JOURNALPLAYBACK = 1\nWH_KEYBOARD = 2\nWH_GETMESSAGE = 3\nWH_CALLWNDPROC = 4\nWH_CBT = 5\nWH_SYSMSGFILTER = 6\nWH_MOUSE = 7\nWH_HARDWARE = 8\nWH_DEBUG = 9\nWH_SHELL = 10\nWH_FOREGROUNDIDLE = 11\nWH_CALLWNDPROCRET = 12\nWH_KEYBOARD_LL = 13\nWH_MOUSE_LL = 14\nWH_MAX = 14\nWH_MINHOOK = WH_MIN\nWH_MAXHOOK = WH_MAX\nHC_ACTION = 0\nHC_GETNEXT = 1\nHC_SKIP = 2\nHC_NOREMOVE = 3\nHC_NOREM = HC_NOREMOVE\nHC_SYSMODALON = 4\nHC_SYSMODALOFF = 5\nHCBT_MOVESIZE = 0\nHCBT_MINMAX = 1\nHCBT_QS = 2\nHCBT_CREATEWND = 3\nHCBT_DESTROYWND = 4\nHCBT_ACTIVATE = 5\nHCBT_CLICKSKIPPED = 6\nHCBT_KEYSKIPPED = 7\nHCBT_SYSCOMMAND = 8\nHCBT_SETFOCUS = 9\nMSGF_DIALOGBOX = 0\nMSGF_MESSAGEBOX = 1\nMSGF_MENU = 2\n#MSGF_MOVE = 3\n#MSGF_SIZE = 4\nMSGF_SCROLLBAR = 5\nMSGF_NEXTWINDOW = 6\n#MSGF_MAINLOOP = 8\nMSGF_MAX = 8\nMSGF_USER = 4096\nHSHELL_WINDOWCREATED = 1\nHSHELL_WINDOWDESTROYED = 2\nHSHELL_ACTIVATESHELLWINDOW = 3\nHSHELL_WINDOWACTIVATED = 4\nHSHELL_GETMINRECT = 5\nHSHELL_REDRAW = 6\nHSHELL_TASKMAN = 7\nHSHELL_LANGUAGE = 8\nHSHELL_ACCESSIBILITYSTATE = 11\nACCESS_STICKYKEYS = 1\nACCESS_FILTERKEYS = 2\nACCESS_MOUSEKEYS = 3\n# winuser.h line 624\nLLKHF_EXTENDED = 1\nLLKHF_INJECTED = 16\nLLKHF_ALTDOWN = 32\nLLKHF_UP = 128\nLLMHF_INJECTED = 1\n# line 692\nHKL_PREV = 0\nHKL_NEXT = 1\nKLF_ACTIVATE = 1\nKLF_SUBSTITUTE_OK = 2\nKLF_UNLOADPREVIOUS = 4\nKLF_REORDER = 8\nKLF_REPLACELANG = 16\nKLF_NOTELLSHELL = 128\nKLF_SETFORPROCESS = 256\nKL_NAMELENGTH = 9\nDESKTOP_READOBJECTS = 1\nDESKTOP_CREATEWINDOW = 2\nDESKTOP_CREATEMENU = 4\nDESKTOP_HOOKCONTROL = 8\nDESKTOP_JOURNALRECORD = 16\nDESKTOP_JOURNALPLAYBACK = 32\nDESKTOP_ENUMERATE = 64\nDESKTOP_WRITEOBJECTS = 128\nDESKTOP_SWITCHDESKTOP = 256\nDF_ALLOWOTHERACCOUNTHOOK = 1\nWINSTA_ENUMDESKTOPS = 1\nWINSTA_READATTRIBUTES = 2\nWINSTA_ACCESSCLIPBOARD = 4\nWINSTA_CREATEDESKTOP = 8\nWINSTA_WRITEATTRIBUTES = 16\nWINSTA_ACCESSGLOBALATOMS = 32\nWINSTA_EXITWINDOWS = 64\nWINSTA_ENUMERATE = 256\nWINSTA_READSCREEN = 512\nWSF_VISIBLE = 1\nUOI_FLAGS = 1\nUOI_NAME = 2\nUOI_TYPE = 3\nUOI_USER_SID = 4\nGWL_WNDPROC = (-4)\nGWL_HINSTANCE = (-6)\nGWL_HWNDPARENT = (-8)\nGWL_STYLE = (-16)\nGWL_EXSTYLE = (-20)\nGWL_USERDATA = (-21)\nGWL_ID = (-12)\nGCL_MENUNAME = (-8)\nGCL_HBRBACKGROUND = (-10)\nGCL_HCURSOR = (-12)\nGCL_HICON = (-14)\nGCL_HMODULE = (-16)\nGCL_CBWNDEXTRA = (-18)\nGCL_CBCLSEXTRA = (-20)\nGCL_WNDPROC = (-24)\nGCL_STYLE = (-26)\nGCW_ATOM = (-32)\nGCL_HICONSM = (-34)\n# line 1291\nWM_NULL = 0\nWM_CREATE = 1\nWM_DESTROY = 2\nWM_MOVE = 3\nWM_SIZE = 5\nWM_ACTIVATE = 6\nWA_INACTIVE = 0\nWA_ACTIVE = 1\nWA_CLICKACTIVE = 2\nWM_SETFOCUS = 7\nWM_KILLFOCUS = 8\nWM_ENABLE = 10\nWM_SETREDRAW = 11\nWM_SETTEXT = 12\nWM_GETTEXT = 13\nWM_GETTEXTLENGTH = 14\nWM_PAINT = 15\nWM_CLOSE = 16\nWM_QUERYENDSESSION = 17\nWM_QUIT = 18\nWM_QUERYOPEN = 19\nWM_ERASEBKGND = 20\nWM_SYSCOLORCHANGE = 21\nWM_ENDSESSION = 22\nWM_SHOWWINDOW = 24\nWM_WININICHANGE = 26\nWM_SETTINGCHANGE = WM_WININICHANGE\nWM_DEVMODECHANGE = 27\nWM_ACTIVATEAPP = 28\nWM_FONTCHANGE = 29\nWM_TIMECHANGE = 30\nWM_CANCELMODE = 31\nWM_SETCURSOR = 32\nWM_MOUSEACTIVATE = 33\nWM_CHILDACTIVATE = 34\nWM_QUEUESYNC = 35\nWM_GETMINMAXINFO = 36\nWM_PAINTICON = 38\nWM_ICONERASEBKGND = 39\nWM_NEXTDLGCTL = 40\nWM_SPOOLERSTATUS = 42\nWM_DRAWITEM = 43\nWM_MEASUREITEM = 44\nWM_DELETEITEM = 45\nWM_VKEYTOITEM = 46\nWM_CHARTOITEM = 47\nWM_SETFONT = 48\nWM_GETFONT = 49\nWM_SETHOTKEY = 50\nWM_GETHOTKEY = 51\nWM_QUERYDRAGICON = 55\nWM_COMPAREITEM = 57\nWM_GETOBJECT = 61\nWM_COMPACTING = 65\nWM_COMMNOTIFY = 68\nWM_WINDOWPOSCHANGING = 70\nWM_WINDOWPOSCHANGED = 71\nWM_POWER = 72\nWM_COPYGLOBALDATA = 73\nPWR_OK = 1\nPWR_FAIL = (-1)\nPWR_SUSPENDREQUEST = 1\nPWR_SUSPENDRESUME = 2\nPWR_CRITICALRESUME = 3\nWM_COPYDATA = 74\nWM_CANCELJOURNAL = 75\nWM_NOTIFY = 78\nWM_INPUTLANGCHANGEREQUEST = 80\nWM_INPUTLANGCHANGE = 81\nWM_TCARD = 82\nWM_HELP = 83\nWM_USERCHANGED = 84\nWM_NOTIFYFORMAT = 85\nNFR_ANSI = 1\nNFR_UNICODE = 2\nNF_QUERY = 3\nNF_REQUERY = 4\nWM_CONTEXTMENU = 123\nWM_STYLECHANGING = 124\nWM_STYLECHANGED = 125\nWM_DISPLAYCHANGE = 126\nWM_GETICON = 127\nWM_SETICON = 128\nWM_NCCREATE = 129\nWM_NCDESTROY = 130\nWM_NCCALCSIZE = 131\nWM_NCHITTEST = 132\nWM_NCPAINT = 133\nWM_NCACTIVATE = 134\nWM_GETDLGCODE = 135\nWM_SYNCPAINT = 136\nWM_NCMOUSEMOVE = 160\nWM_NCLBUTTONDOWN = 161\nWM_NCLBUTTONUP = 162\nWM_NCLBUTTONDBLCLK = 163\nWM_NCRBUTTONDOWN = 164\nWM_NCRBUTTONUP = 165\nWM_NCRBUTTONDBLCLK = 166\nWM_NCMBUTTONDOWN = 167\nWM_NCMBUTTONUP = 168\nWM_NCMBUTTONDBLCLK = 169\nWM_KEYFIRST = 256\nWM_KEYDOWN = 256\nWM_KEYUP = 257\nWM_CHAR = 258\nWM_DEADCHAR = 259\nWM_SYSKEYDOWN = 260\nWM_SYSKEYUP = 261\nWM_SYSCHAR = 262\nWM_SYSDEADCHAR = 263\nWM_KEYLAST = 264\nWM_IME_STARTCOMPOSITION = 269\nWM_IME_ENDCOMPOSITION = 270\nWM_IME_COMPOSITION = 271\nWM_IME_KEYLAST = 271\nWM_INITDIALOG = 272\nWM_COMMAND = 273\nWM_SYSCOMMAND = 274\nWM_TIMER = 275\nWM_HSCROLL = 276\nWM_VSCROLL = 277\nWM_INITMENU = 278\nWM_INITMENUPOPUP = 279\nWM_MENUSELECT = 287\nWM_MENUCHAR = 288\nWM_ENTERIDLE = 289\nWM_MENURBUTTONUP = 290\nWM_MENUDRAG = 291\nWM_MENUGETOBJECT = 292\nWM_UNINITMENUPOPUP = 293\nWM_MENUCOMMAND = 294\nWM_CTLCOLORMSGBOX = 306\nWM_CTLCOLOREDIT = 307\nWM_CTLCOLORLISTBOX = 308\nWM_CTLCOLORBTN = 309\nWM_CTLCOLORDLG = 310\nWM_CTLCOLORSCROLLBAR = 311\nWM_CTLCOLORSTATIC = 312\nWM_MOUSEFIRST = 512\nWM_MOUSEMOVE = 512\nWM_LBUTTONDOWN = 513\nWM_LBUTTONUP = 514\nWM_LBUTTONDBLCLK = 515\nWM_RBUTTONDOWN = 516\nWM_RBUTTONUP = 517\nWM_RBUTTONDBLCLK = 518\nWM_MBUTTONDOWN = 519\nWM_MBUTTONUP = 520\nWM_MBUTTONDBLCLK = 521\nWM_MOUSEWHEEL = 522\nWM_MOUSELAST = 522\nWHEEL_DELTA = 120 # Value for rolling one detent\nWHEEL_PAGESCROLL = -1 # Scroll one page\nWM_PARENTNOTIFY = 528\nMENULOOP_WINDOW = 0\nMENULOOP_POPUP = 1\nWM_ENTERMENULOOP = 529\nWM_EXITMENULOOP = 530\nWM_NEXTMENU = 531\nWM_SIZING = 532\nWM_CAPTURECHANGED = 533\nWM_MOVING = 534\nWM_POWERBROADCAST = 536\nPBT_APMQUERYSUSPEND = 0\nPBT_APMQUERYSTANDBY = 1\nPBT_APMQUERYSUSPENDFAILED = 2\nPBT_APMQUERYSTANDBYFAILED = 3\nPBT_APMSUSPEND = 4\nPBT_APMSTANDBY = 5\nPBT_APMRESUMECRITICAL = 6\nPBT_APMRESUMESUSPEND = 7\nPBT_APMRESUMESTANDBY = 8\nPBTF_APMRESUMEFROMFAILURE = 1\nPBT_APMBATTERYLOW = 9\nPBT_APMPOWERSTATUSCHANGE = 10\nPBT_APMOEMEVENT = 11\nPBT_APMRESUMEAUTOMATIC = 18\nWM_DEVICECHANGE = 537\nWM_MDICREATE = 544\nWM_MDIDESTROY = 545\nWM_MDIACTIVATE = 546\nWM_MDIRESTORE = 547\nWM_MDINEXT = 548\nWM_MDIMAXIMIZE = 549\nWM_MDITILE = 550\nWM_MDICASCADE = 551\nWM_MDIICONARRANGE = 552\nWM_MDIGETACTIVE = 553\nWM_MDISETMENU = 560\nWM_ENTERSIZEMOVE = 561\nWM_EXITSIZEMOVE = 562\nWM_DROPFILES = 563\nWM_MDIREFRESHMENU = 564\nWM_IME_SETCONTEXT = 641\nWM_IME_NOTIFY = 642\nWM_IME_CONTROL = 643\nWM_IME_COMPOSITIONFULL = 644\nWM_IME_SELECT = 645\nWM_IME_CHAR = 646\nWM_IME_REQUEST = 648\nWM_IME_KEYDOWN = 656\nWM_IME_KEYUP = 657\nWM_MOUSEHOVER = 673\nWM_MOUSELEAVE = 675\nWM_CUT = 768\nWM_COPY = 769\nWM_PASTE = 770\nWM_CLEAR = 771\nWM_UNDO = 772\nWM_RENDERFORMAT = 773\nWM_RENDERALLFORMATS = 774\nWM_DESTROYCLIPBOARD = 775\nWM_DRAWCLIPBOARD = 776\nWM_PAINTCLIPBOARD = 777\nWM_VSCROLLCLIPBOARD = 778\nWM_SIZECLIPBOARD = 779\nWM_ASKCBFORMATNAME = 780\nWM_CHANGECBCHAIN = 781\nWM_HSCROLLCLIPBOARD = 782\nWM_QUERYNEWPALETTE = 783\nWM_PALETTEISCHANGING = 784\nWM_PALETTECHANGED = 785\nWM_HOTKEY = 786\nWM_PRINT = 791\nWM_PRINTCLIENT = 792\nWM_HANDHELDFIRST = 856\nWM_HANDHELDLAST = 863\nWM_AFXFIRST = 864\nWM_AFXLAST = 895\nWM_PENWINFIRST = 896\nWM_PENWINLAST = 911\nWM_APP = 32768\nWM_INPUT = 0x00FF\nWMSZ_LEFT = 1\nWMSZ_RIGHT = 2\nWMSZ_TOP = 3\nWMSZ_TOPLEFT = 4\nWMSZ_TOPRIGHT = 5\nWMSZ_BOTTOM = 6\nWMSZ_BOTTOMLEFT = 7\nWMSZ_BOTTOMRIGHT = 8\n#ST_BEGINSWP = 0\n#ST_ENDSWP = 1\nHTERROR = (-2)\nHTTRANSPARENT = (-1)\nHTNOWHERE = 0\nHTCLIENT = 1\nHTCAPTION = 2\nHTSYSMENU = 3\nHTGROWBOX = 4\nHTSIZE = HTGROWBOX\nHTMENU = 5\nHTHSCROLL = 6\nHTVSCROLL = 7\nHTMINBUTTON = 8\nHTMAXBUTTON = 9\nHTLEFT = 10\nHTRIGHT = 11\nHTTOP = 12\nHTTOPLEFT = 13\nHTTOPRIGHT = 14\nHTBOTTOM = 15\nHTBOTTOMLEFT = 16\nHTBOTTOMRIGHT = 17\nHTBORDER = 18\nHTREDUCE = HTMINBUTTON\nHTZOOM = HTMAXBUTTON\nHTSIZEFIRST = HTLEFT\nHTSIZELAST = HTBOTTOMRIGHT\nHTOBJECT = 19\nHTCLOSE = 20\nHTHELP = 21\nSMTO_NORMAL = 0\nSMTO_BLOCK = 1\nSMTO_ABORTIFHUNG = 2\nSMTO_NOTIMEOUTIFNOTHUNG = 8\nMA_ACTIVATE = 1\nMA_ACTIVATEANDEAT = 2\nMA_NOACTIVATE = 3\nMA_NOACTIVATEANDEAT = 4\nICON_SMALL = 0\nICON_BIG = 1\nSIZE_RESTORED = 0\nSIZE_MINIMIZED = 1\nSIZE_MAXIMIZED = 2\nSIZE_MAXSHOW = 3\nSIZE_MAXHIDE = 4\nSIZENORMAL = SIZE_RESTORED\nSIZEICONIC = SIZE_MINIMIZED\nSIZEFULLSCREEN = SIZE_MAXIMIZED\nSIZEZOOMSHOW = SIZE_MAXSHOW\nSIZEZOOMHIDE = SIZE_MAXHIDE\nWVR_ALIGNTOP = 16\nWVR_ALIGNLEFT = 32\nWVR_ALIGNBOTTOM = 64\nWVR_ALIGNRIGHT = 128\nWVR_HREDRAW = 256\nWVR_VREDRAW = 512\nWVR_REDRAW = (WVR_HREDRAW | WVR_VREDRAW)\nWVR_VALIDRECTS = 1024\nMK_LBUTTON = 1\nMK_RBUTTON = 2\nMK_SHIFT = 4\nMK_CONTROL = 8\nMK_MBUTTON = 16\nTME_HOVER = 1\nTME_LEAVE = 2\nTME_QUERY = 1073741824\nTME_CANCEL = -2147483648\nHOVER_DEFAULT = -1\nWS_OVERLAPPED = 0\nWS_POPUP = -2147483648\nWS_CHILD = 1073741824\nWS_MINIMIZE = 536870912\nWS_VISIBLE = 268435456\nWS_DISABLED = 134217728\nWS_CLIPSIBLINGS = 67108864\nWS_CLIPCHILDREN = 33554432\nWS_MAXIMIZE = 16777216\nWS_CAPTION = 12582912\nWS_BORDER = 8388608\nWS_DLGFRAME = 4194304\nWS_VSCROLL = 2097152\nWS_HSCROLL = 1048576\nWS_SYSMENU = 524288\nWS_THICKFRAME = 262144\nWS_GROUP = 131072\nWS_TABSTOP = 65536\nWS_MINIMIZEBOX = 131072\nWS_MAXIMIZEBOX = 65536\nWS_TILED = WS_OVERLAPPED\nWS_ICONIC = WS_MINIMIZE\nWS_SIZEBOX = WS_THICKFRAME\nWS_OVERLAPPEDWINDOW = (WS_OVERLAPPED | \\\n WS_CAPTION | \\\n WS_SYSMENU | \\\n WS_THICKFRAME | \\\n WS_MINIMIZEBOX | \\\n WS_MAXIMIZEBOX)\nWS_POPUPWINDOW = (WS_POPUP | \\\n WS_BORDER | \\\n WS_SYSMENU)\nWS_CHILDWINDOW = (WS_CHILD)\nWS_TILEDWINDOW = WS_OVERLAPPEDWINDOW\nWS_EX_DLGMODALFRAME = 1\nWS_EX_NOPARENTNOTIFY = 4\nWS_EX_TOPMOST = 8\nWS_EX_ACCEPTFILES = 16\nWS_EX_TRANSPARENT = 32\nWS_EX_MDICHILD = 64\nWS_EX_TOOLWINDOW = 128\nWS_EX_WINDOWEDGE = 256\nWS_EX_CLIENTEDGE = 512\nWS_EX_CONTEXTHELP = 1024\nWS_EX_RIGHT = 4096\nWS_EX_LEFT = 0\nWS_EX_RTLREADING = 8192\nWS_EX_LTRREADING = 0\nWS_EX_LEFTSCROLLBAR = 16384\nWS_EX_RIGHTSCROLLBAR = 0\nWS_EX_CONTROLPARENT = 65536\nWS_EX_STATICEDGE = 131072\nWS_EX_APPWINDOW = 262144\nWS_EX_OVERLAPPEDWINDOW = (WS_EX_WINDOWEDGE | WS_EX_CLIENTEDGE)\nWS_EX_PALETTEWINDOW = (WS_EX_WINDOWEDGE | WS_EX_TOOLWINDOW | WS_EX_TOPMOST)\nWS_EX_LAYERED = 0x00080000\nWS_EX_NOINHERITLAYOUT = 0x00100000\nWS_EX_LAYOUTRTL = 0x00400000\nWS_EX_COMPOSITED = 0x02000000\nWS_EX_NOACTIVATE = 0x08000000\n\nCS_VREDRAW = 1\nCS_HREDRAW = 2\n#CS_KEYCVTWINDOW = 0x0004\nCS_DBLCLKS = 8\nCS_OWNDC = 32\nCS_CLASSDC = 64\nCS_PARENTDC = 128\n#CS_NOKEYCVT = 0x0100\nCS_NOCLOSE = 512\nCS_SAVEBITS = 2048\nCS_BYTEALIGNCLIENT = 4096\nCS_BYTEALIGNWINDOW = 8192\nCS_GLOBALCLASS = 16384\nCS_IME = 65536\nPRF_CHECKVISIBLE = 1\nPRF_NONCLIENT = 2\nPRF_CLIENT = 4\nPRF_ERASEBKGND = 8\nPRF_CHILDREN = 16\nPRF_OWNED = 32\nBDR_RAISEDOUTER = 1\nBDR_SUNKENOUTER = 2\nBDR_RAISEDINNER = 4\nBDR_SUNKENINNER = 8\nBDR_OUTER = 3\nBDR_INNER = 12\n#BDR_RAISED = 0x0005\n#BDR_SUNKEN = 0x000a\nEDGE_RAISED = (BDR_RAISEDOUTER | BDR_RAISEDINNER)\nEDGE_SUNKEN = (BDR_SUNKENOUTER | BDR_SUNKENINNER)\nEDGE_ETCHED = (BDR_SUNKENOUTER | BDR_RAISEDINNER)\nEDGE_BUMP = (BDR_RAISEDOUTER | BDR_SUNKENINNER)\n\n# winuser.h line 2879\nISMEX_NOSEND = 0\nISMEX_SEND = 1\nISMEX_NOTIFY = 2\nISMEX_CALLBACK = 4\nISMEX_REPLIED = 8\nCW_USEDEFAULT = -2147483648\nFLASHW_STOP = 0\nFLASHW_CAPTION = 1\nFLASHW_TRAY = 2\nFLASHW_ALL = (FLASHW_CAPTION | FLASHW_TRAY)\nFLASHW_TIMER = 4\nFLASHW_TIMERNOFG = 12\n\n# winuser.h line 7963\nDS_ABSALIGN = 1\nDS_SYSMODAL = 2\nDS_LOCALEDIT = 32\nDS_SETFONT = 64\nDS_MODALFRAME = 128\nDS_NOIDLEMSG = 256\nDS_SETFOREGROUND = 512\nDS_3DLOOK = 4\nDS_FIXEDSYS = 8\nDS_NOFAILCREATE = 16\nDS_CONTROL = 1024\nDS_CENTER = 2048\nDS_CENTERMOUSE = 4096\nDS_CONTEXTHELP = 8192\nDM_GETDEFID = (WM_USER+0)\nDM_SETDEFID = (WM_USER+1)\nDM_REPOSITION = (WM_USER+2)\n#PSM_PAGEINFO = (WM_USER+100)\n#PSM_SHEETINFO = (WM_USER+101)\n#PSI_SETACTIVE = 0x0001\n#PSI_KILLACTIVE = 0x0002\n#PSI_APPLY = 0x0003\n#PSI_RESET = 0x0004\n#PSI_HASHELP = 0x0005\n#PSI_HELP = 0x0006\n#PSI_CHANGED = 0x0001\n#PSI_GUISTART = 0x0002\n#PSI_REBOOT = 0x0003\n#PSI_GETSIBLINGS = 0x0004\nDC_HASDEFID = 21323\nDLGC_WANTARROWS = 1\nDLGC_WANTTAB = 2\nDLGC_WANTALLKEYS = 4\nDLGC_WANTMESSAGE = 4\nDLGC_HASSETSEL = 8\nDLGC_DEFPUSHBUTTON = 16\nDLGC_UNDEFPUSHBUTTON = 32\nDLGC_RADIOBUTTON = 64\nDLGC_WANTCHARS = 128\nDLGC_STATIC = 256\nDLGC_BUTTON = 8192\nLB_CTLCODE = 0\nLB_OKAY = 0\nLB_ERR = (-1)\nLB_ERRSPACE = (-2)\nLBN_ERRSPACE = (-2)\nLBN_SELCHANGE = 1\nLBN_DBLCLK = 2\nLBN_SELCANCEL = 3\nLBN_SETFOCUS = 4\nLBN_KILLFOCUS = 5\nLB_ADDSTRING = 384\nLB_INSERTSTRING = 385\nLB_DELETESTRING = 386\nLB_SELITEMRANGEEX = 387\nLB_RESETCONTENT = 388\nLB_SETSEL = 389\nLB_SETCURSEL = 390\nLB_GETSEL = 391\nLB_GETCURSEL = 392\nLB_GETTEXT = 393\nLB_GETTEXTLEN = 394\nLB_GETCOUNT = 395\nLB_SELECTSTRING = 396\nLB_DIR = 397\nLB_GETTOPINDEX = 398\nLB_FINDSTRING = 399\nLB_GETSELCOUNT = 400\nLB_GETSELITEMS = 401\nLB_SETTABSTOPS = 402\nLB_GETHORIZONTALEXTENT = 403\nLB_SETHORIZONTALEXTENT = 404\nLB_SETCOLUMNWIDTH = 405\nLB_ADDFILE = 406\nLB_SETTOPINDEX = 407\nLB_GETITEMRECT = 408\nLB_GETITEMDATA = 409\nLB_SETITEMDATA = 410\nLB_SELITEMRANGE = 411\nLB_SETANCHORINDEX = 412\nLB_GETANCHORINDEX = 413\nLB_SETCARETINDEX = 414\nLB_GETCARETINDEX = 415\nLB_SETITEMHEIGHT = 416\nLB_GETITEMHEIGHT = 417\nLB_FINDSTRINGEXACT = 418\nLB_SETLOCALE = 421\nLB_GETLOCALE = 422\nLB_SETCOUNT = 423\nLB_INITSTORAGE = 424\nLB_ITEMFROMPOINT = 425\nLB_MSGMAX = 432\nLBS_NOTIFY = 1\nLBS_SORT = 2\nLBS_NOREDRAW = 4\nLBS_MULTIPLESEL = 8\nLBS_OWNERDRAWFIXED = 16\nLBS_OWNERDRAWVARIABLE = 32\nLBS_HASSTRINGS = 64\nLBS_USETABSTOPS = 128\nLBS_NOINTEGRALHEIGHT = 256\nLBS_MULTICOLUMN = 512\nLBS_WANTKEYBOARDINPUT = 1024\nLBS_EXTENDEDSEL = 2048\nLBS_DISABLENOSCROLL = 4096\nLBS_NODATA = 8192\nLBS_NOSEL = 16384\nLBS_STANDARD = (LBS_NOTIFY | LBS_SORT | WS_VSCROLL | WS_BORDER)\nCB_OKAY = 0\nCB_ERR = (-1)\nCB_ERRSPACE = (-2)\nCBN_ERRSPACE = (-1)\nCBN_SELCHANGE = 1\nCBN_DBLCLK = 2\nCBN_SETFOCUS = 3\nCBN_KILLFOCUS = 4\nCBN_EDITCHANGE = 5\nCBN_EDITUPDATE = 6\nCBN_DROPDOWN = 7\nCBN_CLOSEUP = 8\nCBN_SELENDOK = 9\nCBN_SELENDCANCEL = 10\nCBS_SIMPLE = 1\nCBS_DROPDOWN = 2\nCBS_DROPDOWNLIST = 3\nCBS_OWNERDRAWFIXED = 16\nCBS_OWNERDRAWVARIABLE = 32\nCBS_AUTOHSCROLL = 64\nCBS_OEMCONVERT = 128\nCBS_SORT = 256\nCBS_HASSTRINGS = 512\nCBS_NOINTEGRALHEIGHT = 1024\nCBS_DISABLENOSCROLL = 2048\nCBS_UPPERCASE = 8192\nCBS_LOWERCASE = 16384\nCB_GETEDITSEL = 320\nCB_LIMITTEXT = 321\nCB_SETEDITSEL = 322\nCB_ADDSTRING = 323\nCB_DELETESTRING = 324\nCB_DIR = 325\nCB_GETCOUNT = 326\nCB_GETCURSEL = 327\nCB_GETLBTEXT = 328\nCB_GETLBTEXTLEN = 329\nCB_INSERTSTRING = 330\nCB_RESETCONTENT = 331\nCB_FINDSTRING = 332\nCB_SELECTSTRING = 333\nCB_SETCURSEL = 334\nCB_SHOWDROPDOWN = 335\nCB_GETITEMDATA = 336\nCB_SETITEMDATA = 337\nCB_GETDROPPEDCONTROLRECT = 338\nCB_SETITEMHEIGHT = 339\nCB_GETITEMHEIGHT = 340\nCB_SETEXTENDEDUI = 341\nCB_GETEXTENDEDUI = 342\nCB_GETDROPPEDSTATE = 343\nCB_FINDSTRINGEXACT = 344\nCB_SETLOCALE = 345\nCB_GETLOCALE = 346\nCB_GETTOPINDEX = 347\nCB_SETTOPINDEX = 348\nCB_GETHORIZONTALEXTENT = 349\nCB_SETHORIZONTALEXTENT = 350\nCB_GETDROPPEDWIDTH = 351\nCB_SETDROPPEDWIDTH = 352\nCB_INITSTORAGE = 353\nCB_MSGMAX = 354\nSBS_HORZ = 0\nSBS_VERT = 1\nSBS_TOPALIGN = 2\nSBS_LEFTALIGN = 2\nSBS_BOTTOMALIGN = 4\nSBS_RIGHTALIGN = 4\nSBS_SIZEBOXTOPLEFTALIGN = 2\nSBS_SIZEBOXBOTTOMRIGHTALIGN = 4\nSBS_SIZEBOX = 8\nSBS_SIZEGRIP = 16\nSBM_SETPOS = 224\nSBM_GETPOS = 225\nSBM_SETRANGE = 226\nSBM_SETRANGEREDRAW = 230\nSBM_GETRANGE = 227\nSBM_ENABLE_ARROWS = 228\nSBM_SETSCROLLINFO = 233\nSBM_GETSCROLLINFO = 234\nSIF_RANGE = 1\nSIF_PAGE = 2\nSIF_POS = 4\nSIF_DISABLENOSCROLL = 8\nSIF_TRACKPOS = 16\nSIF_ALL = (SIF_RANGE | SIF_PAGE | SIF_POS | SIF_TRACKPOS)\nMDIS_ALLCHILDSTYLES = 1\nMDITILE_VERTICAL = 0\nMDITILE_HORIZONTAL = 1\nMDITILE_SKIPDISABLED = 2\n\nIMC_GETCANDIDATEPOS = 7\nIMC_SETCANDIDATEPOS = 8\nIMC_GETCOMPOSITIONFONT = 9\nIMC_SETCOMPOSITIONFONT = 10\nIMC_GETCOMPOSITIONWINDOW = 11\nIMC_SETCOMPOSITIONWINDOW = 12\nIMC_GETSTATUSWINDOWPOS = 15\nIMC_SETSTATUSWINDOWPOS = 16\nIMC_CLOSESTATUSWINDOW = 33\nIMC_OPENSTATUSWINDOW = 34\n# Generated by h2py from \\msvc20\\include\\winnt.h\n# hacked and split by mhammond.\nDELETE = (65536)\nREAD_CONTROL = (131072)\nWRITE_DAC = (262144)\nWRITE_OWNER = (524288)\nSYNCHRONIZE = (1048576)\nSTANDARD_RIGHTS_REQUIRED = (983040)\nSTANDARD_RIGHTS_READ = (READ_CONTROL)\nSTANDARD_RIGHTS_WRITE = (READ_CONTROL)\nSTANDARD_RIGHTS_EXECUTE = (READ_CONTROL)\nSTANDARD_RIGHTS_ALL = (2031616)\nSPECIFIC_RIGHTS_ALL = (65535)\nACCESS_SYSTEM_SECURITY = (16777216)\nMAXIMUM_ALLOWED = (33554432)\nGENERIC_READ = (-2147483648)\nGENERIC_WRITE = (1073741824)\nGENERIC_EXECUTE = (536870912)\nGENERIC_ALL = (268435456)\n\nSERVICE_KERNEL_DRIVER = 1\nSERVICE_FILE_SYSTEM_DRIVER = 2\nSERVICE_ADAPTER = 4\nSERVICE_RECOGNIZER_DRIVER = 8\nSERVICE_DRIVER = (SERVICE_KERNEL_DRIVER | \\\n SERVICE_FILE_SYSTEM_DRIVER | \\\n SERVICE_RECOGNIZER_DRIVER)\nSERVICE_WIN32_OWN_PROCESS = 16\nSERVICE_WIN32_SHARE_PROCESS = 32\nSERVICE_WIN32 = (SERVICE_WIN32_OWN_PROCESS | \\\n SERVICE_WIN32_SHARE_PROCESS)\nSERVICE_INTERACTIVE_PROCESS = 256\nSERVICE_TYPE_ALL = (SERVICE_WIN32 | \\\n SERVICE_ADAPTER | \\\n SERVICE_DRIVER | \\\n SERVICE_INTERACTIVE_PROCESS)\nSERVICE_BOOT_START = 0\nSERVICE_SYSTEM_START = 1\nSERVICE_AUTO_START = 2\nSERVICE_DEMAND_START = 3\nSERVICE_DISABLED = 4\nSERVICE_ERROR_IGNORE = 0\nSERVICE_ERROR_NORMAL = 1\nSERVICE_ERROR_SEVERE = 2\nSERVICE_ERROR_CRITICAL = 3\nTAPE_ERASE_SHORT = 0\nTAPE_ERASE_LONG = 1\nTAPE_LOAD = 0\nTAPE_UNLOAD = 1\nTAPE_TENSION = 2\nTAPE_LOCK = 3\nTAPE_UNLOCK = 4\nTAPE_FORMAT = 5\nTAPE_SETMARKS = 0\nTAPE_FILEMARKS = 1\nTAPE_SHORT_FILEMARKS = 2\nTAPE_LONG_FILEMARKS = 3\nTAPE_ABSOLUTE_POSITION = 0\nTAPE_LOGICAL_POSITION = 1\nTAPE_PSEUDO_LOGICAL_POSITION = 2\nTAPE_REWIND = 0\nTAPE_ABSOLUTE_BLOCK = 1\nTAPE_LOGICAL_BLOCK = 2\nTAPE_PSEUDO_LOGICAL_BLOCK = 3\nTAPE_SPACE_END_OF_DATA = 4\nTAPE_SPACE_RELATIVE_BLOCKS = 5\nTAPE_SPACE_FILEMARKS = 6\nTAPE_SPACE_SEQUENTIAL_FMKS = 7\nTAPE_SPACE_SETMARKS = 8\nTAPE_SPACE_SEQUENTIAL_SMKS = 9\nTAPE_DRIVE_FIXED = 1\nTAPE_DRIVE_SELECT = 2\nTAPE_DRIVE_INITIATOR = 4\nTAPE_DRIVE_ERASE_SHORT = 16\nTAPE_DRIVE_ERASE_LONG = 32\nTAPE_DRIVE_ERASE_BOP_ONLY = 64\nTAPE_DRIVE_ERASE_IMMEDIATE = 128\nTAPE_DRIVE_TAPE_CAPACITY = 256\nTAPE_DRIVE_TAPE_REMAINING = 512\nTAPE_DRIVE_FIXED_BLOCK = 1024\nTAPE_DRIVE_VARIABLE_BLOCK = 2048\nTAPE_DRIVE_WRITE_PROTECT = 4096\nTAPE_DRIVE_EOT_WZ_SIZE = 8192\nTAPE_DRIVE_ECC = 65536\nTAPE_DRIVE_COMPRESSION = 131072\nTAPE_DRIVE_PADDING = 262144\nTAPE_DRIVE_REPORT_SMKS = 524288\nTAPE_DRIVE_GET_ABSOLUTE_BLK = 1048576\nTAPE_DRIVE_GET_LOGICAL_BLK = 2097152\nTAPE_DRIVE_SET_EOT_WZ_SIZE = 4194304\nTAPE_DRIVE_LOAD_UNLOAD = -2147483647\nTAPE_DRIVE_TENSION = -2147483646\nTAPE_DRIVE_LOCK_UNLOCK = -2147483644\nTAPE_DRIVE_REWIND_IMMEDIATE = -2147483640\nTAPE_DRIVE_SET_BLOCK_SIZE = -2147483632\nTAPE_DRIVE_LOAD_UNLD_IMMED = -2147483616\nTAPE_DRIVE_TENSION_IMMED = -2147483584\nTAPE_DRIVE_LOCK_UNLK_IMMED = -2147483520\nTAPE_DRIVE_SET_ECC = -2147483392\nTAPE_DRIVE_SET_COMPRESSION = -2147483136\nTAPE_DRIVE_SET_PADDING = -2147482624\nTAPE_DRIVE_SET_REPORT_SMKS = -2147481600\nTAPE_DRIVE_ABSOLUTE_BLK = -2147479552\nTAPE_DRIVE_ABS_BLK_IMMED = -2147475456\nTAPE_DRIVE_LOGICAL_BLK = -2147467264\nTAPE_DRIVE_LOG_BLK_IMMED = -2147450880\nTAPE_DRIVE_END_OF_DATA = -2147418112\nTAPE_DRIVE_RELATIVE_BLKS = -2147352576\nTAPE_DRIVE_FILEMARKS = -2147221504\nTAPE_DRIVE_SEQUENTIAL_FMKS = -2146959360\nTAPE_DRIVE_SETMARKS = -2146435072\nTAPE_DRIVE_SEQUENTIAL_SMKS = -2145386496\nTAPE_DRIVE_REVERSE_POSITION = -2143289344\nTAPE_DRIVE_SPACE_IMMEDIATE = -2139095040\nTAPE_DRIVE_WRITE_SETMARKS = -2130706432\nTAPE_DRIVE_WRITE_FILEMARKS = -2113929216\nTAPE_DRIVE_WRITE_SHORT_FMKS = -2080374784\nTAPE_DRIVE_WRITE_LONG_FMKS = -2013265920\nTAPE_DRIVE_WRITE_MARK_IMMED = -1879048192\nTAPE_DRIVE_FORMAT = -1610612736\nTAPE_DRIVE_FORMAT_IMMEDIATE = -1073741824\nTAPE_FIXED_PARTITIONS = 0\nTAPE_SELECT_PARTITIONS = 1\nTAPE_INITIATOR_PARTITIONS = 2\n# Generated by h2py from \\msvc20\\include\\winnt.h\n# hacked and split by mhammond.\n\nAPPLICATION_ERROR_MASK = 536870912\nERROR_SEVERITY_SUCCESS = 0\nERROR_SEVERITY_INFORMATIONAL = 1073741824\nERROR_SEVERITY_WARNING = -2147483648\nERROR_SEVERITY_ERROR = -1073741824\nMINCHAR = 128\nMAXCHAR = 127\nMINSHORT = 32768\nMAXSHORT = 32767\nMINLONG = -2147483648\nMAXLONG = 2147483647\nMAXBYTE = 255\nMAXWORD = 65535\nMAXDWORD = -1\nLANG_NEUTRAL = 0\nLANG_BULGARIAN = 2\nLANG_CHINESE = 4\nLANG_CROATIAN = 26\nLANG_CZECH = 5\nLANG_DANISH = 6\nLANG_DUTCH = 19\nLANG_ENGLISH = 9\nLANG_FINNISH = 11\nLANG_FRENCH = 12\nLANG_GERMAN = 7\nLANG_GREEK = 8\nLANG_HUNGARIAN = 14\nLANG_ICELANDIC = 15", "answers": ["LANG_ITALIAN = 16"], "length": 6849, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "efca3b56-502b-40a5-a83a-5e246b58e0f0", "reasoning": "The code is defining language identifier constants from Windows headers. The last defined constant is LANG_ICELANDIC = 15, and the next sequential language constant in the original header is LANG_ITALIAN with value 16. So the next line should define LANG_ITALIAN = 16.", "reasoning_model_answer": "LANG_ITALIAN = 16", "assistant_with_reasoning": "\nThe code is defining language identifier constants from Windows headers. The last defined constant is LANG_ICELANDIC = 15, and the next sequential language constant in the original header is LANG_ITALIAN with value 16. So the next line should define LANG_ITALIAN = 16.\n\nLANG_ITALIAN = 16", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.363, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 47614, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "LANG_ITALIAN = 16", "score": 1.0, "is_full_score": true, "is_nonzero_score": true}} {"input": "", "context": "/*\n * Licensed to Elasticsearch under one or more contributor\n * license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright\n * ownership. Elasticsearch licenses this file to you under\n * the Apache License, Version 2.0 (the \"License\"); you may\n * not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\npackage org.elasticsearch.index.mapper;\n\nimport com.carrotsearch.hppc.ObjectHashSet;\nimport com.carrotsearch.hppc.cursors.ObjectCursor;\n\nimport org.apache.logging.log4j.message.ParameterizedMessage;\nimport org.apache.lucene.analysis.Analyzer;\nimport org.apache.lucene.analysis.DelegatingAnalyzerWrapper;\nimport org.apache.lucene.index.Term;\nimport org.elasticsearch.ElasticsearchGenerationException;\nimport org.elasticsearch.Version;\nimport org.elasticsearch.cluster.metadata.IndexMetaData;\nimport org.elasticsearch.cluster.metadata.MappingMetaData;\nimport org.elasticsearch.common.Nullable;\nimport org.elasticsearch.common.compress.CompressedXContent;\nimport org.elasticsearch.common.logging.DeprecationLogger;\nimport org.elasticsearch.common.logging.Loggers;\nimport org.elasticsearch.common.regex.Regex;\nimport org.elasticsearch.common.settings.Setting;\nimport org.elasticsearch.common.settings.Setting.Property;\nimport org.elasticsearch.common.xcontent.NamedXContentRegistry;\nimport org.elasticsearch.common.xcontent.XContentFactory;\nimport org.elasticsearch.common.xcontent.XContentParser;\nimport org.elasticsearch.common.xcontent.XContentType;\nimport org.elasticsearch.index.AbstractIndexComponent;\nimport org.elasticsearch.index.IndexSettings;\nimport org.elasticsearch.index.IndexSortConfig;\nimport org.elasticsearch.index.analysis.IndexAnalyzers;\nimport org.elasticsearch.index.analysis.NamedAnalyzer;\nimport org.elasticsearch.index.mapper.Mapper.BuilderContext;\nimport org.elasticsearch.index.query.QueryShardContext;\nimport org.elasticsearch.index.similarity.SimilarityService;\nimport org.elasticsearch.indices.InvalidTypeNameException;\nimport org.elasticsearch.indices.mapper.MapperRegistry;\n\nimport java.io.Closeable;\nimport java.io.IOException;\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.LinkedHashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.function.Function;\nimport java.util.function.Supplier;\nimport java.util.stream.Collectors;\n\nimport static java.util.Collections.emptyMap;\nimport static java.util.Collections.emptySet;\nimport static java.util.Collections.unmodifiableMap;\n\npublic class MapperService extends AbstractIndexComponent implements Closeable {\n\n /**\n * The reason why a mapping is being merged.\n */\n public enum MergeReason {\n /**\n * Create or update a mapping.\n */\n MAPPING_UPDATE,\n /**\n * Recovery of an existing mapping, for instance because of a restart,\n * if a shard was moved to a different node or for administrative\n * purposes.\n */\n MAPPING_RECOVERY;\n }\n\n public static final String DEFAULT_MAPPING = \"_default_\";\n public static final String SINGLE_MAPPING_NAME = \"_doc\";\n public static final Setting INDEX_MAPPING_NESTED_FIELDS_LIMIT_SETTING =\n Setting.longSetting(\"index.mapping.nested_fields.limit\", 50L, 0, Property.Dynamic, Property.IndexScope);\n // maximum allowed number of nested json objects across all fields in a single document\n public static final Setting INDEX_MAPPING_NESTED_DOCS_LIMIT_SETTING =\n Setting.longSetting(\"index.mapping.nested_objects.limit\", 10000L, 0, Property.Dynamic, Property.IndexScope);\n public static final Setting INDEX_MAPPING_TOTAL_FIELDS_LIMIT_SETTING =\n Setting.longSetting(\"index.mapping.total_fields.limit\", 1000L, 0, Property.Dynamic, Property.IndexScope);\n public static final Setting INDEX_MAPPING_DEPTH_LIMIT_SETTING =\n Setting.longSetting(\"index.mapping.depth.limit\", 20L, 1, Property.Dynamic, Property.IndexScope);\n public static final boolean INDEX_MAPPER_DYNAMIC_DEFAULT = true;\n @Deprecated\n public static final Setting INDEX_MAPPER_DYNAMIC_SETTING =\n Setting.boolSetting(\"index.mapper.dynamic\", INDEX_MAPPER_DYNAMIC_DEFAULT,\n Property.Dynamic, Property.IndexScope, Property.Deprecated);\n\n //TODO this needs to be cleaned up: _timestamp and _ttl are not supported anymore, _field_names, _seq_no, _version and _source are\n //also missing, not sure if on purpose. See IndicesModule#getMetadataMappers\n private static ObjectHashSet META_FIELDS = ObjectHashSet.from(\n \"_uid\", \"_id\", \"_type\", \"_parent\", \"_routing\", \"_index\",\n \"_size\", \"_timestamp\", \"_ttl\"\n );\n\n private static final DeprecationLogger DEPRECATION_LOGGER = new DeprecationLogger(Loggers.getLogger(MapperService.class));\n\n private final IndexAnalyzers indexAnalyzers;\n\n private volatile String defaultMappingSource;\n\n private volatile Map mappers = emptyMap();\n\n private volatile FieldTypeLookup fieldTypes;\n private volatile Map fullPathObjectMappers = emptyMap();\n private boolean hasNested = false; // updated dynamically to true when a nested object is added\n\n private final DocumentMapperParser documentParser;\n\n private final MapperAnalyzerWrapper indexAnalyzer;\n private final MapperAnalyzerWrapper searchAnalyzer;\n private final MapperAnalyzerWrapper searchQuoteAnalyzer;\n\n private volatile Map unmappedFieldTypes = emptyMap();\n\n private volatile Set parentTypes = emptySet();\n\n final MapperRegistry mapperRegistry;\n\n public MapperService(IndexSettings indexSettings, IndexAnalyzers indexAnalyzers, NamedXContentRegistry xContentRegistry,\n SimilarityService similarityService, MapperRegistry mapperRegistry,\n Supplier queryShardContextSupplier) {\n super(indexSettings);\n this.indexAnalyzers = indexAnalyzers;\n this.fieldTypes = new FieldTypeLookup();\n this.documentParser = new DocumentMapperParser(indexSettings, this, indexAnalyzers, xContentRegistry, similarityService,\n mapperRegistry, queryShardContextSupplier);\n this.indexAnalyzer = new MapperAnalyzerWrapper(indexAnalyzers.getDefaultIndexAnalyzer(), p -> p.indexAnalyzer());\n this.searchAnalyzer = new MapperAnalyzerWrapper(indexAnalyzers.getDefaultSearchAnalyzer(), p -> p.searchAnalyzer());\n this.searchQuoteAnalyzer = new MapperAnalyzerWrapper(indexAnalyzers.getDefaultSearchQuoteAnalyzer(), p -> p.searchQuoteAnalyzer());\n this.mapperRegistry = mapperRegistry;\n\n if (INDEX_MAPPER_DYNAMIC_SETTING.exists(indexSettings.getSettings()) &&\n indexSettings.getIndexVersionCreated().onOrAfter(Version.V_7_0_0_alpha1)) {\n throw new IllegalArgumentException(\"Setting \" + INDEX_MAPPER_DYNAMIC_SETTING.getKey() + \" was removed after version 6.0.0\");\n }\n\n defaultMappingSource = \"{\\\"_default_\\\":{}}\";\n\n if (logger.isTraceEnabled()) {\n logger.trace(\"default mapping source[{}]\", defaultMappingSource);\n }\n }\n\n public boolean hasNested() {\n return this.hasNested;\n }\n\n /**\n * returns an immutable iterator over current document mappers.\n *\n * @param includingDefaultMapping indicates whether the iterator should contain the {@link #DEFAULT_MAPPING} document mapper.\n * As is this not really an active type, you would typically set this to false\n */\n public Iterable docMappers(final boolean includingDefaultMapping) {\n return () -> {\n final Collection documentMappers;\n if (includingDefaultMapping) {\n documentMappers = mappers.values();\n } else {\n documentMappers = mappers.values().stream().filter(mapper -> !DEFAULT_MAPPING.equals(mapper.type())).collect(Collectors.toList());\n }\n return Collections.unmodifiableCollection(documentMappers).iterator();\n };\n }\n\n public IndexAnalyzers getIndexAnalyzers() {\n return this.indexAnalyzers;\n }\n\n public NamedAnalyzer getNamedAnalyzer(String analyzerName) {\n return this.indexAnalyzers.get(analyzerName);\n }\n\n public DocumentMapperParser documentMapperParser() {\n return this.documentParser;\n }\n\n /**\n * Parses the mappings (formatted as JSON) into a map\n */\n public static Map parseMapping(NamedXContentRegistry xContentRegistry, String mappingSource) throws Exception {\n try (XContentParser parser = XContentType.JSON.xContent().createParser(xContentRegistry, mappingSource)) {\n return parser.map();\n }\n }\n\n /**\n * Update mapping by only merging the metadata that is different between received and stored entries\n */\n public boolean updateMapping(IndexMetaData indexMetaData) throws IOException {\n assert indexMetaData.getIndex().equals(index()) : \"index mismatch: expected \" + index() + \" but was \" + indexMetaData.getIndex();\n // go over and add the relevant mappings (or update them)\n final Set existingMappers = new HashSet<>(mappers.keySet());\n final Map updatedEntries;\n try {\n // only update entries if needed\n updatedEntries = internalMerge(indexMetaData, MergeReason.MAPPING_RECOVERY, true);\n } catch (Exception e) {\n logger.warn((org.apache.logging.log4j.util.Supplier) () -> new ParameterizedMessage(\"[{}] failed to apply mappings\", index()), e);\n throw e;\n }\n\n boolean requireRefresh = false;\n\n for (DocumentMapper documentMapper : updatedEntries.values()) {\n String mappingType = documentMapper.type();\n CompressedXContent incomingMappingSource = indexMetaData.mapping(mappingType).source();\n\n String op = existingMappers.contains(mappingType) ? \"updated\" : \"added\";\n if (logger.isDebugEnabled() && incomingMappingSource.compressed().length < 512) {\n logger.debug(\"[{}] {} mapping [{}], source [{}]\", index(), op, mappingType, incomingMappingSource.string());\n } else if (logger.isTraceEnabled()) {\n logger.trace(\"[{}] {} mapping [{}], source [{}]\", index(), op, mappingType, incomingMappingSource.string());\n } else {\n logger.debug(\"[{}] {} mapping [{}] (source suppressed due to length, use TRACE level if needed)\", index(), op, mappingType);\n }\n\n // refresh mapping can happen when the parsing/merging of the mapping from the metadata doesn't result in the same\n // mapping, in this case, we send to the master to refresh its own version of the mappings (to conform with the\n // merge version of it, which it does when refreshing the mappings), and warn log it.\n if (documentMapper(mappingType).mappingSource().equals(incomingMappingSource) == false) {\n logger.debug(\"[{}] parsed mapping [{}], and got different sources\\noriginal:\\n{}\\nparsed:\\n{}\", index(), mappingType,\n incomingMappingSource, documentMapper(mappingType).mappingSource());\n\n requireRefresh = true;\n }\n }\n\n return requireRefresh;\n }\n\n public void merge(Map> mappings, MergeReason reason) {\n Map mappingSourcesCompressed = new LinkedHashMap<>(mappings.size());\n for (Map.Entry> entry : mappings.entrySet()) {\n try {\n mappingSourcesCompressed.put(entry.getKey(), new CompressedXContent(XContentFactory.jsonBuilder().map(entry.getValue()).string()));\n } catch (Exception e) {\n throw new MapperParsingException(\"Failed to parse mapping [{}]: {}\", e, entry.getKey(), e.getMessage());\n }\n }\n\n internalMerge(mappingSourcesCompressed, reason);\n }\n\n public void merge(IndexMetaData indexMetaData, MergeReason reason) {\n internalMerge(indexMetaData, reason, false);\n }\n\n public DocumentMapper merge(String type, CompressedXContent mappingSource, MergeReason reason) {\n return internalMerge(Collections.singletonMap(type, mappingSource), reason).get(type);\n }\n\n private synchronized Map internalMerge(IndexMetaData indexMetaData, MergeReason reason, boolean onlyUpdateIfNeeded) {\n Map map = new LinkedHashMap<>();\n for (ObjectCursor cursor : indexMetaData.getMappings().values()) {\n MappingMetaData mappingMetaData = cursor.value;\n if (onlyUpdateIfNeeded) {\n DocumentMapper existingMapper = documentMapper(mappingMetaData.type());\n if (existingMapper == null || mappingMetaData.source().equals(existingMapper.mappingSource()) == false) {\n map.put(mappingMetaData.type(), mappingMetaData.source());\n }\n } else {\n map.put(mappingMetaData.type(), mappingMetaData.source());\n }\n }\n return internalMerge(map, reason);\n }\n\n private synchronized Map internalMerge(Map mappings, MergeReason reason) {\n DocumentMapper defaultMapper = null;\n String defaultMappingSource = null;\n\n if (mappings.containsKey(DEFAULT_MAPPING)) {\n // verify we can parse it\n // NOTE: never apply the default here\n try {\n defaultMapper = documentParser.parse(DEFAULT_MAPPING, mappings.get(DEFAULT_MAPPING));\n } catch (Exception e) {\n throw new MapperParsingException(\"Failed to parse mapping [{}]: {}\", e, DEFAULT_MAPPING, e.getMessage());\n }\n try {\n defaultMappingSource = mappings.get(DEFAULT_MAPPING).string();\n } catch (IOException e) {\n throw new ElasticsearchGenerationException(\"failed to un-compress\", e);\n }\n }\n\n final String defaultMappingSourceOrLastStored;\n if (defaultMappingSource != null) {\n defaultMappingSourceOrLastStored = defaultMappingSource;\n } else {\n defaultMappingSourceOrLastStored = this.defaultMappingSource;\n }\n\n List documentMappers = new ArrayList<>();\n for (Map.Entry entry : mappings.entrySet()) {\n String type = entry.getKey();\n if (type.equals(DEFAULT_MAPPING)) {\n continue;\n }\n\n final boolean applyDefault =\n // the default was already applied if we are recovering\n reason != MergeReason.MAPPING_RECOVERY\n // only apply the default mapping if we don't have the type yet\n && mappers.containsKey(type) == false;\n\n try {\n DocumentMapper documentMapper =\n documentParser.parse(type, entry.getValue(), applyDefault ? defaultMappingSourceOrLastStored : null);\n documentMappers.add(documentMapper);\n } catch (Exception e) {\n throw new MapperParsingException(\"Failed to parse mapping [{}]: {}\", e, entry.getKey(), e.getMessage());\n }\n }\n\n return internalMerge(defaultMapper, defaultMappingSource, documentMappers, reason);\n }\n\n static void validateTypeName(String type) {\n if (type.length() == 0) {\n throw new InvalidTypeNameException(\"mapping type name is empty\");\n }\n if (type.length() > 255) {\n throw new InvalidTypeNameException(\"mapping type name [\" + type + \"] is too long; limit is length 255 but was [\" + type.length() + \"]\");\n }\n if (type.charAt(0) == '_' && SINGLE_MAPPING_NAME.equals(type) == false) {\n throw new InvalidTypeNameException(\"mapping type name [\" + type + \"] can't start with '_' unless it is called [\" + SINGLE_MAPPING_NAME + \"]\");\n }\n if (type.contains(\"#\")) {\n throw new InvalidTypeNameException(\"mapping type name [\" + type + \"] should not include '#' in it\");\n }\n if (type.contains(\",\")) {\n throw new InvalidTypeNameException(\"mapping type name [\" + type + \"] should not include ',' in it\");\n }\n if (type.charAt(0) == '.') {\n throw new IllegalArgumentException(\"mapping type name [\" + type + \"] must not start with a '.'\");\n }\n }\n\n private synchronized Map internalMerge(@Nullable DocumentMapper defaultMapper, @Nullable String defaultMappingSource,\n List documentMappers, MergeReason reason) {\n boolean hasNested = this.hasNested;\n Map fullPathObjectMappers = this.fullPathObjectMappers;\n FieldTypeLookup fieldTypes = this.fieldTypes;\n Set parentTypes = this.parentTypes;\n Map mappers = new HashMap<>(this.mappers);\n\n Map results = new LinkedHashMap<>(documentMappers.size() + 1);\n\n if (defaultMapper != null) {\n if (indexSettings.getIndexVersionCreated().onOrAfter(Version.V_6_0_0_beta1)\n && reason == MergeReason.MAPPING_UPDATE) { // only log in case of explicit mapping updates\n DEPRECATION_LOGGER.deprecated(\"[_default_] mapping is deprecated since it is not useful anymore now that indexes \" +\n \"cannot have more than one type\");\n }\n assert defaultMapper.type().equals(DEFAULT_MAPPING);\n mappers.put(DEFAULT_MAPPING, defaultMapper);\n results.put(DEFAULT_MAPPING, defaultMapper);\n }\n\n for (DocumentMapper mapper : documentMappers) {\n // check naming\n validateTypeName(mapper.type());\n if (mapper.type().equals(mapper.parentFieldMapper().type())) {\n throw new IllegalArgumentException(\"The [_parent.type] option can't point to the same type\");\n }\n\n // compute the merged DocumentMapper\n DocumentMapper oldMapper = mappers.get(mapper.type());\n DocumentMapper newMapper;\n if (oldMapper != null) {\n newMapper = oldMapper.merge(mapper.mapping());\n } else {\n newMapper = mapper;\n }\n\n // check basic sanity of the new mapping\n List objectMappers = new ArrayList<>();\n List fieldMappers = new ArrayList<>();\n Collections.addAll(fieldMappers, newMapper.mapping().metadataMappers);\n MapperUtils.collect(newMapper.mapping().root(), objectMappers, fieldMappers);\n checkFieldUniqueness(newMapper.type(), objectMappers, fieldMappers, fullPathObjectMappers, fieldTypes);\n checkObjectsCompatibility(objectMappers, fullPathObjectMappers);\n checkPartitionedIndexConstraints(newMapper);\n\n // update lookup data-structures\n // this will in particular make sure that the merged fields are compatible with other types\n fieldTypes = fieldTypes.copyAndAddAll(newMapper.type(), fieldMappers);\n\n for (ObjectMapper objectMapper : objectMappers) {\n if (fullPathObjectMappers == this.fullPathObjectMappers) {\n // first time through the loops\n fullPathObjectMappers = new HashMap<>(this.fullPathObjectMappers);\n }\n fullPathObjectMappers.put(objectMapper.fullPath(), objectMapper);\n\n if (objectMapper.nested().isNested()) {\n hasNested = true;\n }\n }\n\n if (indexSettings.getIndexVersionCreated().onOrAfter(Version.V_6_0_0_beta1)) {\n validateCopyTo(fieldMappers, fullPathObjectMappers, fieldTypes);\n }\n\n if (reason == MergeReason.MAPPING_UPDATE) {\n // this check will only be performed on the master node when there is\n // a call to the update mapping API. For all other cases like\n // the master node restoring mappings from disk or data nodes\n // deserializing cluster state that was sent by the master node,\n // this check will be skipped.\n checkTotalFieldsLimit(objectMappers.size() + fieldMappers.size());\n }\n\n if (oldMapper == null && newMapper.parentFieldMapper().active()) {\n if (parentTypes == this.parentTypes) {\n // first time through the loop\n parentTypes = new HashSet<>(this.parentTypes);\n }\n parentTypes.add(mapper.parentFieldMapper().type());\n }\n\n results.put(newMapper.type(), newMapper);\n mappers.put(newMapper.type(), newMapper);\n }\n\n if (reason == MergeReason.MAPPING_UPDATE) {\n // this check will only be performed on the master node when there is\n // a call to the update mapping API. For all other cases like\n // the master node restoring mappings from disk or data nodes\n // deserializing cluster state that was sent by the master node,\n // this check will be skipped.\n checkNestedFieldsLimit(fullPathObjectMappers);\n checkDepthLimit(fullPathObjectMappers.keySet());\n }\n checkIndexSortCompatibility(indexSettings.getIndexSortConfig(), hasNested);\n\n for (Map.Entry entry : mappers.entrySet()) {\n if (entry.getKey().equals(DEFAULT_MAPPING)) {\n continue;\n }\n DocumentMapper documentMapper = entry.getValue();\n // apply changes to the field types back\n DocumentMapper updatedDocumentMapper = documentMapper.updateFieldType(fieldTypes.fullNameToFieldType);\n if (updatedDocumentMapper != documentMapper) {\n // update both mappers and result\n entry.setValue(updatedDocumentMapper);\n if (results.containsKey(updatedDocumentMapper.type())) {\n results.put(updatedDocumentMapper.type(), updatedDocumentMapper);\n }\n }\n }\n\n if (indexSettings.isSingleType()) {\n Set actualTypes = new HashSet<>(mappers.keySet());\n actualTypes.remove(DEFAULT_MAPPING);\n if (actualTypes.size() > 1) {\n throw new IllegalArgumentException(\n \"Rejecting mapping update to [\" + index().getName() + \"] as the final mapping would have more than 1 type: \" + actualTypes);\n }\n }\n\n // make structures immutable\n mappers = Collections.unmodifiableMap(mappers);\n results = Collections.unmodifiableMap(results);\n\n // only need to immutably rewrap these if the previous reference was changed.\n // if not then they are already implicitly immutable.\n if (fullPathObjectMappers != this.fullPathObjectMappers) {\n fullPathObjectMappers = Collections.unmodifiableMap(fullPathObjectMappers);\n }\n if (parentTypes != this.parentTypes) {\n parentTypes = Collections.unmodifiableSet(parentTypes);\n }\n\n // commit the change\n if (defaultMappingSource != null) {\n this.defaultMappingSource = defaultMappingSource;\n }\n this.mappers = mappers;\n this.fieldTypes = fieldTypes;\n this.hasNested = hasNested;\n this.fullPathObjectMappers = fullPathObjectMappers;\n this.parentTypes = parentTypes;\n\n assert assertMappersShareSameFieldType();\n assert results.values().stream().allMatch(this::assertSerialization);\n\n return results;\n }\n\n private boolean assertMappersShareSameFieldType() {\n for (DocumentMapper mapper : docMappers(false)) {\n List fieldMappers = new ArrayList<>();\n Collections.addAll(fieldMappers, mapper.mapping().metadataMappers);\n MapperUtils.collect(mapper.root(), new ArrayList<>(), fieldMappers);\n for (FieldMapper fieldMapper : fieldMappers) {\n assert fieldMapper.fieldType() == fieldTypes.get(fieldMapper.name()) : fieldMapper.name();\n }\n }\n return true;\n }\n\n private boolean assertSerialization(DocumentMapper mapper) {\n // capture the source now, it may change due to concurrent parsing\n final CompressedXContent mappingSource = mapper.mappingSource();\n DocumentMapper newMapper = parse(mapper.type(), mappingSource, false);\n\n if (newMapper.mappingSource().equals(mappingSource) == false) {\n throw new IllegalStateException(\"DocumentMapper serialization result is different from source. \\n--> Source [\"\n + mappingSource + \"]\\n--> Result [\"\n + newMapper.mappingSource() + \"]\");\n }\n return true;\n }\n\n private static void checkFieldUniqueness(String type, Collection objectMappers, Collection fieldMappers,\n Map fullPathObjectMappers, FieldTypeLookup fieldTypes) {\n\n // first check within mapping\n final Set objectFullNames = new HashSet<>();\n for (ObjectMapper objectMapper : objectMappers) {\n final String fullPath = objectMapper.fullPath();\n if (objectFullNames.add(fullPath) == false) {\n throw new IllegalArgumentException(\"Object mapper [\" + fullPath + \"] is defined twice in mapping for type [\" + type + \"]\");\n }\n }\n\n final Set fieldNames = new HashSet<>();\n for (FieldMapper fieldMapper : fieldMappers) {\n final String name = fieldMapper.name();\n if (objectFullNames.contains(name)) {\n throw new IllegalArgumentException(\"Field [\" + name + \"] is defined both as an object and a field in [\" + type + \"]\");\n } else if (fieldNames.add(name) == false) {\n throw new IllegalArgumentException(\"Field [\" + name + \"] is defined twice in [\" + type + \"]\");\n }\n }\n\n // then check other types\n for (String fieldName : fieldNames) {\n if (fullPathObjectMappers.containsKey(fieldName)) {\n throw new IllegalArgumentException(\"[\" + fieldName + \"] is defined as a field in mapping [\" + type\n + \"] but this name is already used for an object in other types\");\n }\n }\n\n for (String objectPath : objectFullNames) {\n if (fieldTypes.get(objectPath) != null) {\n throw new IllegalArgumentException(\"[\" + objectPath + \"] is defined as an object in mapping [\" + type\n + \"] but this name is already used for a field in other types\");\n }\n }\n }\n\n private static void checkObjectsCompatibility(Collection objectMappers,\n Map fullPathObjectMappers) {\n for (ObjectMapper newObjectMapper : objectMappers) {\n ObjectMapper existingObjectMapper = fullPathObjectMappers.get(newObjectMapper.fullPath());\n if (existingObjectMapper != null) {\n // simulate a merge and ignore the result, we are just interested\n // in exceptions here\n existingObjectMapper.merge(newObjectMapper);\n }\n }\n }\n\n private void checkNestedFieldsLimit(Map fullPathObjectMappers) {\n long allowedNestedFields = indexSettings.getValue(INDEX_MAPPING_NESTED_FIELDS_LIMIT_SETTING);\n long actualNestedFields = 0;\n for (ObjectMapper objectMapper : fullPathObjectMappers.values()) {\n if (objectMapper.nested().isNested()) {\n actualNestedFields++;\n }\n }\n if (actualNestedFields > allowedNestedFields) {\n throw new IllegalArgumentException(\"Limit of nested fields [\" + allowedNestedFields + \"] in index [\" + index().getName() + \"] has been exceeded\");\n }\n }\n\n private void checkTotalFieldsLimit(long totalMappers) {\n long allowedTotalFields = indexSettings.getValue(INDEX_MAPPING_TOTAL_FIELDS_LIMIT_SETTING);\n if (allowedTotalFields < totalMappers) {\n throw new IllegalArgumentException(\"Limit of total fields [\" + allowedTotalFields + \"] in index [\" + index().getName() + \"] has been exceeded\");\n }\n }\n\n private void checkDepthLimit(Collection objectPaths) {\n final long maxDepth = indexSettings.getValue(INDEX_MAPPING_DEPTH_LIMIT_SETTING);\n for (String objectPath : objectPaths) {\n checkDepthLimit(objectPath, maxDepth);\n }\n }\n\n private void checkDepthLimit(String objectPath, long maxDepth) {\n int numDots = 0;\n for (int i = 0; i < objectPath.length(); ++i) {\n if (objectPath.charAt(i) == '.') {\n numDots += 1;\n }\n }\n final int depth = numDots + 2;\n if (depth > maxDepth) {\n throw new IllegalArgumentException(\"Limit of mapping depth [\" + maxDepth + \"] in index [\" + index().getName()\n + \"] has been exceeded due to object field [\" + objectPath + \"]\");\n }\n }\n\n private void checkPartitionedIndexConstraints(DocumentMapper newMapper) {\n if (indexSettings.getIndexMetaData().isRoutingPartitionedIndex()) {\n if (newMapper.parentFieldMapper().active()) {\n throw new IllegalArgumentException(\"mapping type name [\" + newMapper.type() + \"] cannot have a \"\n + \"_parent field for the partitioned index [\" + indexSettings.getIndex().getName() + \"]\");\n }\n\n if (!newMapper.routingFieldMapper().required()) {\n throw new IllegalArgumentException(\"mapping type [\" + newMapper.type() + \"] must have routing \"\n + \"required for partitioned index [\" + indexSettings.getIndex().getName() + \"]\");\n }\n }\n }\n\n private static void checkIndexSortCompatibility(IndexSortConfig sortConfig, boolean hasNested) {\n if (sortConfig.hasIndexSort() && hasNested) {\n throw new IllegalArgumentException(\"cannot have nested fields when index sort is activated\");\n }\n }\n\n private static void validateCopyTo(List fieldMappers, Map fullPathObjectMappers,\n FieldTypeLookup fieldTypes) {\n for (FieldMapper mapper : fieldMappers) {\n if (mapper.copyTo() != null && mapper.copyTo().copyToFields().isEmpty() == false) {\n String sourceParent = parentObject(mapper.name());\n if (sourceParent != null && fieldTypes.get(sourceParent) != null) {\n throw new IllegalArgumentException(\"[copy_to] may not be used to copy from a multi-field: [\" + mapper.name() + \"]\");\n }\n\n final String sourceScope = getNestedScope(mapper.name(), fullPathObjectMappers);\n for (String copyTo : mapper.copyTo().copyToFields()) {\n String copyToParent = parentObject(copyTo);\n if (copyToParent != null && fieldTypes.get(copyToParent) != null) {\n throw new IllegalArgumentException(\"[copy_to] may not be used to copy to a multi-field: [\" + copyTo + \"]\");\n }\n\n if (fullPathObjectMappers.containsKey(copyTo)) {\n throw new IllegalArgumentException(\"Cannot copy to field [\" + copyTo + \"] since it is mapped as an object\");\n }\n\n final String targetScope = getNestedScope(copyTo, fullPathObjectMappers);\n checkNestedScopeCompatibility(sourceScope, targetScope);\n }\n }\n }\n }\n\n private static String getNestedScope(String path, Map fullPathObjectMappers) {\n for (String parentPath = parentObject(path); parentPath != null; parentPath = parentObject(parentPath)) {\n ObjectMapper objectMapper = fullPathObjectMappers.get(parentPath);\n if (objectMapper != null && objectMapper.nested().isNested()) {\n return parentPath;\n }\n }\n return null;\n }\n\n private static void checkNestedScopeCompatibility(String source, String target) {\n boolean targetIsParentOfSource;\n if (source == null || target == null) {\n targetIsParentOfSource = target == null;\n } else {\n targetIsParentOfSource = source.equals(target) || source.startsWith(target + \".\");\n }\n if (targetIsParentOfSource == false) {\n throw new IllegalArgumentException(\n \"Illegal combination of [copy_to] and [nested] mappings: [copy_to] may only copy data to the current nested \" +\n \"document or any of its parents, however one [copy_to] directive is trying to copy data from nested object [\" +\n source + \"] to [\" + target + \"]\");\n }\n }\n\n private static String parentObject(String field) {\n int lastDot = field.lastIndexOf('.');\n if (lastDot == -1) {\n return null;\n }\n return field.substring(0, lastDot);\n }\n\n public DocumentMapper parse(String mappingType, CompressedXContent mappingSource, boolean applyDefault) throws MapperParsingException {\n return documentParser.parse(mappingType, mappingSource, applyDefault ? defaultMappingSource : null);\n }\n\n public boolean hasMapping(String mappingType) {\n return mappers.containsKey(mappingType);\n }\n\n /**\n * Return the set of concrete types that have a mapping.\n * NOTE: this does not return the default mapping.\n */\n public Collection types() {\n final Set types = new HashSet<>(mappers.keySet());\n types.remove(DEFAULT_MAPPING);\n return Collections.unmodifiableSet(types);\n }\n\n /**\n * Return the {@link DocumentMapper} for the given type. By using the special\n * {@value #DEFAULT_MAPPING} type, you can get a {@link DocumentMapper} for\n * the default mapping.\n */", "answers": [" public DocumentMapper documentMapper(String type) {"], "length": 3053, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "0a103031-52f2-4c57-bdff-42f3db4b6444", "reasoning": "The Javadoc comment describes a method that returns a DocumentMapper for a given type, mentioning the special DEFAULT_MAPPING. The class already uses a method named documentMapper(String) elsewhere (e.g., in updateMapping). Therefore the next line should be the method signature that begins this method.", "reasoning_model_answer": "public DocumentMapper documentMapper(String type) {", "assistant_with_reasoning": "\nThe Javadoc comment describes a method that returns a DocumentMapper for a given type, mentioning the special DEFAULT_MAPPING. The class already uses a method named documentMapper(String) elsewhere (e.g., in updateMapping). Therefore the next line should be the method signature that begins this method.\n\npublic DocumentMapper documentMapper(String type) {", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.162, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 35369, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "public DocumentMapper documentMapper(String type) {", "score": 0.96, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/*\n * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * This code is free software; you can redistribute it and/or modify it\n * under the terms of the GNU General Public License version 2 only, as\n * published by the Free Software Foundation. Oracle designates this\n * particular file as subject to the \"Classpath\" exception as provided\n * by Oracle in the LICENSE file that accompanied this code.\n *\n * This code is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License\n * version 2 for more details (a copy is included in the LICENSE file that\n * accompanied this code).\n *\n * You should have received a copy of the GNU General Public License version\n * 2 along with this work; if not, write to the Free Software Foundation,\n * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.\n *\n * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA\n * or visit www.oracle.com if you need additional information or have any\n * questions.\n */\n\npackage jdk.nashorn.internal.runtime.linker;\n\nimport static jdk.internal.org.objectweb.asm.Opcodes.ACC_FINAL;\nimport static jdk.internal.org.objectweb.asm.Opcodes.ACC_PRIVATE;\nimport static jdk.internal.org.objectweb.asm.Opcodes.ACC_PUBLIC;\nimport static jdk.internal.org.objectweb.asm.Opcodes.ACC_STATIC;\nimport static jdk.internal.org.objectweb.asm.Opcodes.ACC_SUPER;\nimport static jdk.internal.org.objectweb.asm.Opcodes.ACC_VARARGS;\nimport static jdk.internal.org.objectweb.asm.Opcodes.ACONST_NULL;\nimport static jdk.internal.org.objectweb.asm.Opcodes.ALOAD;\nimport static jdk.internal.org.objectweb.asm.Opcodes.ASTORE;\nimport static jdk.internal.org.objectweb.asm.Opcodes.DUP;\nimport static jdk.internal.org.objectweb.asm.Opcodes.IFNONNULL;\nimport static jdk.internal.org.objectweb.asm.Opcodes.ILOAD;\nimport static jdk.internal.org.objectweb.asm.Opcodes.ISTORE;\nimport static jdk.internal.org.objectweb.asm.Opcodes.POP;\nimport static jdk.internal.org.objectweb.asm.Opcodes.RETURN;\nimport static jdk.nashorn.internal.lookup.Lookup.MH;\nimport static jdk.nashorn.internal.runtime.linker.AdaptationResult.Outcome.ERROR_NO_ACCESSIBLE_CONSTRUCTOR;\n\nimport java.lang.invoke.MethodHandle;\nimport java.lang.invoke.MethodType;\nimport java.lang.reflect.AccessibleObject;\nimport java.lang.reflect.Constructor;\nimport java.lang.reflect.Method;\nimport java.lang.reflect.Modifier;\nimport java.security.AccessControlContext;\nimport java.security.AccessController;\nimport java.security.PrivilegedAction;\nimport java.util.Arrays;\nimport java.util.Collection;\nimport java.util.HashSet;\nimport java.util.Iterator;\nimport java.util.LinkedHashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\nimport jdk.internal.org.objectweb.asm.ClassWriter;\nimport jdk.internal.org.objectweb.asm.Handle;\nimport jdk.internal.org.objectweb.asm.Label;\nimport jdk.internal.org.objectweb.asm.Opcodes;\nimport jdk.internal.org.objectweb.asm.Type;\nimport jdk.internal.org.objectweb.asm.commons.InstructionAdapter;\nimport jdk.nashorn.internal.objects.Global;\nimport jdk.nashorn.internal.runtime.Context;\nimport jdk.nashorn.internal.runtime.JSType;\nimport jdk.nashorn.internal.runtime.ScriptFunction;\nimport jdk.nashorn.internal.runtime.ScriptObject;\nimport jdk.nashorn.internal.runtime.linker.AdaptationResult.Outcome;\nimport sun.reflect.CallerSensitive;\n\n/**\n * Generates bytecode for a Java adapter class. Used by the {@link JavaAdapterFactory}.\n *

\n * For every protected or public constructor in the extended class, the adapter class will have either one or two\n * public constructors (visibility of protected constructors in the extended class is promoted to public).\n *

  • \n *
  • For adapter classes with instance-level overrides, a constructor taking a trailing ScriptObject argument preceded\n * by original constructor arguments is always created on the adapter class. When such a constructor is invoked, the\n * passed ScriptObject's member functions are used to implement and/or override methods on the original class,\n * dispatched by name. A single JavaScript function will act as the implementation for all overloaded methods of the\n * same name. When methods on an adapter instance are invoked, the functions are invoked having the ScriptObject passed\n * in the instance constructor as their \"this\". Subsequent changes to the ScriptObject (reassignment or removal of its\n * functions) are not reflected in the adapter instance; the method implementations are bound to functions at\n * constructor invocation time.\n * {@code java.lang.Object} methods {@code equals}, {@code hashCode}, and {@code toString} can also be overridden. The\n * only restriction is that since every JavaScript object already has a {@code toString} function through the\n * {@code Object.prototype}, the {@code toString} in the adapter is only overridden if the passed ScriptObject has a\n * {@code toString} function as its own property, and not inherited from a prototype. All other adapter methods can be\n * implemented or overridden through a prototype-inherited function of the ScriptObject passed to the constructor too.\n *
  • \n *
  • \n * If the original types collectively have only one abstract method, or have several of them, but all share the\n * same name, an additional constructor for instance-level override adapter is provided for every original constructor;\n * this one takes a ScriptFunction as its last argument preceded by original constructor arguments. This constructor\n * will use the passed function as the implementation for all abstract methods. For consistency, any concrete methods\n * sharing the single abstract method name will also be overridden by the function. When methods on the adapter instance\n * are invoked, the ScriptFunction is invoked with UNDEFINED or Global as its \"this\" depending whether the function is\n * strict or not.\n *
  • \n *
  • \n * If the adapter being generated can have class-level overrides, constructors taking same arguments as the superclass\n * constructors are created. These constructors simply delegate to the superclass constructor. They are simply used to\n * create instances of the adapter class, with no instance-level overrides, as they don't have them.\n *
  • \n * \n *

    \n * For adapter methods that return values, all the JavaScript-to-Java conversions supported by Nashorn will be in effect\n * to coerce the JavaScript function return value to the expected Java return type.\n *

    \n * Since we are adding a trailing argument to the generated constructors in the adapter class, they will never be\n * declared as variable arity, even if the original constructor in the superclass was declared as variable arity. The\n * reason we are passing the additional argument at the end of the argument list instead at the front is that the\n * source-level script expression new X(a, b) { ... } (which is a proprietary syntax extension Nashorn uses\n * to resemble Java anonymous classes) is actually equivalent to new X(a, b, { ... }).\n *

    \n * It is possible to create two different adapter classes: those that can have class-level overrides, and those that can\n * have instance-level overrides. When {@link JavaAdapterFactory#getAdapterClassFor(Class[], ScriptObject)} is invoked\n * with non-null {@code classOverrides} parameter, an adapter class is created that can have class-level overrides, and\n * the passed script object will be used as the implementations for its methods, just as in the above case of the\n * constructor taking a script object. Note that in the case of class-level overrides, a new adapter class is created on\n * every invocation, and the implementation object is bound to the class, not to any instance. All created instances\n * will share these functions. If it is required to have both class-level overrides and instance-level overrides, the\n * class-level override adapter class should be subclassed with an instance-override adapter. Since adapters delegate to\n * super class when an overriding method handle is not specified, this will behave as expected. It is not possible to\n * have both class-level and instance-level overrides in the same class for security reasons: adapter classes are\n * defined with a protection domain of their creator code, and an adapter class that has both class and instance level\n * overrides would need to have two potentially different protection domains: one for class-based behavior and one for\n * instance-based behavior; since Java classes can only belong to a single protection domain, this could not be\n * implemented securely.\n */\nfinal class JavaAdapterBytecodeGenerator {\n private static final Type CONTEXT_TYPE = Type.getType(Context.class);\n private static final Type OBJECT_TYPE = Type.getType(Object.class);\n private static final Type SCRIPT_OBJECT_TYPE = Type.getType(ScriptObject.class);\n private static final Type GLOBAL_TYPE = Type.getType(Global.class);\n private static final Type CLASS_TYPE = Type.getType(Class.class);\n\n static final String CONTEXT_TYPE_NAME = CONTEXT_TYPE.getInternalName();\n static final String OBJECT_TYPE_NAME = OBJECT_TYPE.getInternalName();\n\n static final String INIT = \"\";\n\n static final String GLOBAL_FIELD_NAME = \"global\";\n\n static final String SCRIPT_OBJECT_TYPE_DESCRIPTOR = SCRIPT_OBJECT_TYPE.getDescriptor();\n static final String GLOBAL_TYPE_DESCRIPTOR = GLOBAL_TYPE.getDescriptor();\n\n\n static final String SET_GLOBAL_METHOD_DESCRIPTOR = Type.getMethodDescriptor(Type.VOID_TYPE, GLOBAL_TYPE);\n static final String VOID_NOARG_METHOD_DESCRIPTOR = Type.getMethodDescriptor(Type.VOID_TYPE);\n\n private static final Type SCRIPT_FUNCTION_TYPE = Type.getType(ScriptFunction.class);\n private static final Type STRING_TYPE = Type.getType(String.class);\n private static final Type METHOD_TYPE_TYPE = Type.getType(MethodType.class);\n private static final Type METHOD_HANDLE_TYPE = Type.getType(MethodHandle.class);\n private static final String GET_HANDLE_OBJECT_DESCRIPTOR = Type.getMethodDescriptor(METHOD_HANDLE_TYPE,\n OBJECT_TYPE, STRING_TYPE, METHOD_TYPE_TYPE);\n private static final String GET_HANDLE_FUNCTION_DESCRIPTOR = Type.getMethodDescriptor(METHOD_HANDLE_TYPE,\n SCRIPT_FUNCTION_TYPE, METHOD_TYPE_TYPE);\n private static final String GET_CLASS_INITIALIZER_DESCRIPTOR = Type.getMethodDescriptor(SCRIPT_OBJECT_TYPE);\n private static final Type RUNTIME_EXCEPTION_TYPE = Type.getType(RuntimeException.class);\n private static final Type THROWABLE_TYPE = Type.getType(Throwable.class);\n private static final Type UNSUPPORTED_OPERATION_TYPE = Type.getType(UnsupportedOperationException.class);\n\n private static final String SERVICES_CLASS_TYPE_NAME = Type.getInternalName(JavaAdapterServices.class);\n private static final String RUNTIME_EXCEPTION_TYPE_NAME = RUNTIME_EXCEPTION_TYPE.getInternalName();\n private static final String ERROR_TYPE_NAME = Type.getInternalName(Error.class);\n private static final String THROWABLE_TYPE_NAME = THROWABLE_TYPE.getInternalName();\n private static final String UNSUPPORTED_OPERATION_TYPE_NAME = UNSUPPORTED_OPERATION_TYPE.getInternalName();\n\n private static final String METHOD_HANDLE_TYPE_DESCRIPTOR = METHOD_HANDLE_TYPE.getDescriptor();\n private static final String GET_GLOBAL_METHOD_DESCRIPTOR = Type.getMethodDescriptor(GLOBAL_TYPE);\n private static final String GET_CLASS_METHOD_DESCRIPTOR = Type.getMethodDescriptor(CLASS_TYPE);\n private static final String EXPORT_RETURN_VALUE_METHOD_DESCRIPTOR = Type.getMethodDescriptor(OBJECT_TYPE, OBJECT_TYPE);\n private static final String GET_CONVERTER_METHOD_DESCRIPTOR = Type.getMethodDescriptor(METHOD_HANDLE_TYPE, CLASS_TYPE);\n private static final String TO_CHAR_PRIMITIVE_METHOD_DESCRIPTOR = Type.getMethodDescriptor(Type.CHAR_TYPE, OBJECT_TYPE);\n private static final String TO_STRING_METHOD_DESCRIPTOR = Type.getMethodDescriptor(STRING_TYPE, OBJECT_TYPE);\n\n // Package used when the adapter can't be defined in the adaptee's package (either because it's sealed, or because\n // it's a java.* package.\n private static final String ADAPTER_PACKAGE_PREFIX = \"jdk/nashorn/javaadapters/\";\n // Class name suffix used to append to the adaptee class name, when it can be defined in the adaptee's package.\n private static final String ADAPTER_CLASS_NAME_SUFFIX = \"$$NashornJavaAdapter\";\n private static final String JAVA_PACKAGE_PREFIX = \"java/\";\n private static final int MAX_GENERATED_TYPE_NAME_LENGTH = 255;\n\n private static final String CLASS_INIT = \"\";\n static final String CONVERTER_INIT = \"\";\n\n // Method name prefix for invoking super-methods\n static final String SUPER_PREFIX = \"super$\";\n\n /**\n * Collection of methods we never override: Object.clone(), Object.finalize().\n */\n private static final Collection EXCLUDED = getExcludedMethods();\n\n // This is the superclass for our generated adapter.\n private final Class superClass;\n // Class loader used as the parent for the class loader we'll create to load the generated class. It will be a class\n // loader that has the visibility of all original types (class to extend and interfaces to implement) and of the\n // Nashorn classes.\n private final ClassLoader commonLoader;\n // Is this a generator for the version of the class that can have overrides on the class level?\n private final boolean classOverride;\n // Binary name of the superClass\n private final String superClassName;\n // Binary name of the generated class.\n private final String generatedClassName;\n private final Set usedFieldNames = new HashSet<>();\n private final Set abstractMethodNames = new HashSet<>();\n private final String samName;\n private final Set finalMethods = new HashSet<>(EXCLUDED);\n private final Set methodInfos = new HashSet<>();\n private boolean autoConvertibleFromFunction = false;\n private boolean hasExplicitFinalizer = false;\n\n /**\n * Names of static fields holding type converter method handles for return value conversion. We are emitting code\n * for invoking these explicitly after the delegate handle is invoked, instead of doing an asType or\n * filterReturnValue on the delegate handle, as that would create a new converter handle wrapping the function's\n * handle for every instance of the adapter, causing the handle.invokeExact() call sites to become megamorphic.\n */\n private Map, String> converterFields = new LinkedHashMap<>();\n\n /**\n * Subset of possible return types for all methods; namely, all possible return types of the SAM methods (we\n * identify SAM types by having all of their abstract methods share a single name, so there can be multiple\n * overloads with multiple return types. We use this set when emitting the constructor taking a ScriptFunction (the\n * SAM initializer) to avoid populating converter fields that will never be used by SAM methods.\n */\n private Set> samReturnTypes = new HashSet<>();\n\n private final ClassWriter cw;\n\n /**\n * Creates a generator for the bytecode for the adapter for the specified superclass and interfaces.\n * @param superClass the superclass the adapter will extend.\n * @param interfaces the interfaces the adapter will implement.\n * @param commonLoader the class loader that can see all of superClass, interfaces, and Nashorn classes.\n * @param classOverride true to generate the bytecode for the adapter that has class-level overrides, false to\n * generate the bytecode for the adapter that has instance-level overrides.\n * @throws AdaptationException if the adapter can not be generated for some reason.\n */\n JavaAdapterBytecodeGenerator(final Class superClass, final List> interfaces,\n final ClassLoader commonLoader, final boolean classOverride) throws AdaptationException {\n assert superClass != null && !superClass.isInterface();\n assert interfaces != null;\n\n this.superClass = superClass;\n this.classOverride = classOverride;\n this.commonLoader = commonLoader;\n cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS) {\n @Override\n protected String getCommonSuperClass(final String type1, final String type2) {\n // We need to override ClassWriter.getCommonSuperClass to use this factory's commonLoader as a class\n // loader to find the common superclass of two types when needed.\n return JavaAdapterBytecodeGenerator.this.getCommonSuperClass(type1, type2);\n }\n };\n superClassName = Type.getInternalName(superClass);\n generatedClassName = getGeneratedClassName(superClass, interfaces);\n\n cw.visit(Opcodes.V1_7, ACC_PUBLIC | ACC_SUPER, generatedClassName, null, superClassName, getInternalTypeNames(interfaces));\n generateGlobalFields();\n\n gatherMethods(superClass);\n gatherMethods(interfaces);\n samName = abstractMethodNames.size() == 1 ? abstractMethodNames.iterator().next() : null;\n generateHandleFields();\n generateConverterFields();\n if(classOverride) {\n generateClassInit();\n }\n generateConstructors();\n generateMethods();\n generateSuperMethods();\n if (hasExplicitFinalizer) {\n generateFinalizerMethods();\n }\n // }\n cw.visitEnd();\n }\n\n private void generateGlobalFields() {\n cw.visitField(ACC_PRIVATE | ACC_FINAL | (classOverride ? ACC_STATIC : 0), GLOBAL_FIELD_NAME, GLOBAL_TYPE_DESCRIPTOR, null, null).visitEnd();\n usedFieldNames.add(GLOBAL_FIELD_NAME);\n }\n\n JavaAdapterClassLoader createAdapterClassLoader() {\n return new JavaAdapterClassLoader(generatedClassName, cw.toByteArray());\n }\n\n boolean isAutoConvertibleFromFunction() {\n return autoConvertibleFromFunction;\n }\n\n private static String getGeneratedClassName(final Class superType, final List> interfaces) {\n // The class we use to primarily name our adapter is either the superclass, or if it is Object (meaning we're\n // just implementing interfaces or extending Object), then the first implemented interface or Object.\n final Class namingType = superType == Object.class ? (interfaces.isEmpty()? Object.class : interfaces.get(0)) : superType;\n final Package pkg = namingType.getPackage();\n final String namingTypeName = Type.getInternalName(namingType);\n final StringBuilder buf = new StringBuilder();\n if (namingTypeName.startsWith(JAVA_PACKAGE_PREFIX) || pkg == null || pkg.isSealed()) {\n // Can't define new classes in java.* packages\n buf.append(ADAPTER_PACKAGE_PREFIX).append(namingTypeName);\n } else {\n buf.append(namingTypeName).append(ADAPTER_CLASS_NAME_SUFFIX);\n }\n final Iterator> it = interfaces.iterator();\n if(superType == Object.class && it.hasNext()) {\n it.next(); // Skip first interface, it was used to primarily name the adapter\n }\n // Append interface names to the adapter name\n while(it.hasNext()) {\n buf.append(\"$$\").append(it.next().getSimpleName());\n }\n return buf.toString().substring(0, Math.min(MAX_GENERATED_TYPE_NAME_LENGTH, buf.length()));\n }\n\n /**\n * Given a list of class objects, return an array with their binary names. Used to generate the array of interface\n * names to implement.\n * @param classes the classes\n * @return an array of names\n */\n private static String[] getInternalTypeNames(final List> classes) {\n final int interfaceCount = classes.size();\n final String[] interfaceNames = new String[interfaceCount];\n for(int i = 0; i < interfaceCount; ++i) {\n interfaceNames[i] = Type.getInternalName(classes.get(i));\n }\n return interfaceNames;\n }\n\n private void generateHandleFields() {\n final int flags = ACC_PRIVATE | ACC_FINAL | (classOverride ? ACC_STATIC : 0);\n for (final MethodInfo mi: methodInfos) {\n cw.visitField(flags, mi.methodHandleFieldName, METHOD_HANDLE_TYPE_DESCRIPTOR, null, null).visitEnd();\n }\n }\n\n private void generateConverterFields() {\n final int flags = ACC_PRIVATE | ACC_FINAL | (classOverride ? ACC_STATIC : 0);\n for (final MethodInfo mi: methodInfos) {\n final Class returnType = mi.type.returnType();\n // Handle primitive types, Object, and String specially\n if(!returnType.isPrimitive() && returnType != Object.class && returnType != String.class) {\n if(!converterFields.containsKey(returnType)) {\n final String name = nextName(\"convert\");\n converterFields.put(returnType, name);\n if(mi.getName().equals(samName)) {\n samReturnTypes.add(returnType);\n }\n cw.visitField(flags, name, METHOD_HANDLE_TYPE_DESCRIPTOR, null, null).visitEnd();\n }\n }\n }\n }\n\n private void generateClassInit() {\n final InstructionAdapter mv = new InstructionAdapter(cw.visitMethod(ACC_STATIC, CLASS_INIT,\n Type.getMethodDescriptor(Type.VOID_TYPE), null, null));\n\n mv.invokestatic(SERVICES_CLASS_TYPE_NAME, \"getClassOverrides\", GET_CLASS_INITIALIZER_DESCRIPTOR, false);\n final Label initGlobal;\n if(samName != null) {\n // If the class is a SAM, allow having a ScriptFunction passed as class overrides\n final Label notAFunction = new Label();\n mv.dup();\n mv.instanceOf(SCRIPT_FUNCTION_TYPE);\n mv.ifeq(notAFunction);\n mv.checkcast(SCRIPT_FUNCTION_TYPE);\n\n // Assign MethodHandle fields through invoking getHandle() for a ScriptFunction, only assigning the SAM\n // method(s).\n for (final MethodInfo mi : methodInfos) {\n if(mi.getName().equals(samName)) {\n mv.dup();\n loadMethodTypeAndGetHandle(mv, mi, GET_HANDLE_FUNCTION_DESCRIPTOR);\n } else {\n mv.visitInsn(ACONST_NULL);\n }\n mv.putstatic(generatedClassName, mi.methodHandleFieldName, METHOD_HANDLE_TYPE_DESCRIPTOR);\n }\n initGlobal = new Label();\n mv.goTo(initGlobal);\n mv.visitLabel(notAFunction);\n } else {\n initGlobal = null;\n }\n // Assign MethodHandle fields through invoking getHandle() for a ScriptObject\n for (final MethodInfo mi : methodInfos) {\n mv.dup();\n mv.aconst(mi.getName());\n loadMethodTypeAndGetHandle(mv, mi, GET_HANDLE_OBJECT_DESCRIPTOR);\n mv.putstatic(generatedClassName, mi.methodHandleFieldName, METHOD_HANDLE_TYPE_DESCRIPTOR);\n }\n\n if(initGlobal != null) {\n mv.visitLabel(initGlobal);\n }\n // Assign \"global = Context.getGlobal()\"\n invokeGetGlobalWithNullCheck(mv);\n mv.putstatic(generatedClassName, GLOBAL_FIELD_NAME, GLOBAL_TYPE_DESCRIPTOR);\n\n generateConverterInit(mv, false);\n endInitMethod(mv);\n }\n\n private void generateConverterInit(final InstructionAdapter mv, final boolean samOnly) {\n assert !samOnly || !classOverride;\n for(Map.Entry, String> converterField: converterFields.entrySet()) {\n final Class returnType = converterField.getKey();\n if(!classOverride) {\n mv.visitVarInsn(ALOAD, 0);\n }\n\n if(samOnly && !samReturnTypes.contains(returnType)) {\n mv.visitInsn(ACONST_NULL);\n } else {\n mv.aconst(Type.getType(converterField.getKey()));\n mv.invokestatic(SERVICES_CLASS_TYPE_NAME, \"getObjectConverter\", GET_CONVERTER_METHOD_DESCRIPTOR, false);\n }\n\n if(classOverride) {\n mv.putstatic(generatedClassName, converterField.getValue(), METHOD_HANDLE_TYPE_DESCRIPTOR);\n } else {\n mv.putfield(generatedClassName, converterField.getValue(), METHOD_HANDLE_TYPE_DESCRIPTOR);\n }\n }\n }\n\n private static void loadMethodTypeAndGetHandle(final InstructionAdapter mv, final MethodInfo mi, final String getHandleDescriptor) {\n // NOTE: we're using generic() here because we'll be linking to the \"generic\" invoker version of\n // the functions anyway, so we cut down on megamorphism in the invokeExact() calls in adapter\n // bodies. Once we start linking to type-specializing invokers, this should be changed.\n mv.aconst(Type.getMethodType(mi.type.generic().toMethodDescriptorString()));\n mv.invokestatic(SERVICES_CLASS_TYPE_NAME, \"getHandle\", getHandleDescriptor, false);\n }\n\n private static void invokeGetGlobalWithNullCheck(final InstructionAdapter mv) {\n invokeGetGlobal(mv);\n mv.dup();\n mv.invokevirtual(OBJECT_TYPE_NAME, \"getClass\", GET_CLASS_METHOD_DESCRIPTOR, false); // check against null Context\n mv.pop();\n }\n\n private void generateConstructors() throws AdaptationException {\n boolean gotCtor = false;\n for (final Constructor ctor: superClass.getDeclaredConstructors()) {\n final int modifier = ctor.getModifiers();\n if((modifier & (Modifier.PUBLIC | Modifier.PROTECTED)) != 0 && !isCallerSensitive(ctor)) {\n generateConstructors(ctor);\n gotCtor = true;\n }\n }\n if(!gotCtor) {\n throw new AdaptationException(ERROR_NO_ACCESSIBLE_CONSTRUCTOR, superClass.getCanonicalName());\n }\n }\n\n private void generateConstructors(final Constructor ctor) {\n if(classOverride) {\n // Generate a constructor that just delegates to ctor. This is used with class-level overrides, when we want\n // to create instances without further per-instance overrides.\n generateDelegatingConstructor(ctor);\n } else {\n // Generate a constructor that delegates to ctor, but takes an additional ScriptObject parameter at the\n // beginning of its parameter list.\n generateOverridingConstructor(ctor, false);\n\n if (samName != null) {\n if (!autoConvertibleFromFunction && ctor.getParameterTypes().length == 0) {\n // If the original type only has a single abstract method name, as well as a default ctor, then it can\n // be automatically converted from JS function.\n autoConvertibleFromFunction = true;\n }\n // If all our abstract methods have a single name, generate an additional constructor, one that takes a\n // ScriptFunction as its first parameter and assigns it as the implementation for all abstract methods.\n generateOverridingConstructor(ctor, true);\n }\n }\n }\n\n private void generateDelegatingConstructor(final Constructor ctor) {\n final Type originalCtorType = Type.getType(ctor);\n final Type[] argTypes = originalCtorType.getArgumentTypes();\n\n // All constructors must be public, even if in the superclass they were protected.\n final InstructionAdapter mv = new InstructionAdapter(cw.visitMethod(ACC_PUBLIC, INIT,\n Type.getMethodDescriptor(originalCtorType.getReturnType(), argTypes), null, null));\n\n mv.visitCode();\n // Invoke super constructor with the same arguments.\n mv.visitVarInsn(ALOAD, 0);\n int offset = 1; // First arg is at position 1, after this.\n for (Type argType: argTypes) {\n mv.load(offset, argType);\n offset += argType.getSize();\n }\n mv.invokespecial(superClassName, INIT, originalCtorType.getDescriptor(), false);\n\n endInitMethod(mv);\n }\n\n /**\n * Generates a constructor for the instance adapter class. This constructor will take the same arguments as the supertype\n * constructor passed as the argument here, and delegate to it. However, it will take an additional argument of\n * either ScriptObject or ScriptFunction type (based on the value of the \"fromFunction\" parameter), and initialize\n * all the method handle fields of the adapter instance with functions from the script object (or the script\n * function itself, if that's what's passed). There is one method handle field in the adapter class for every method\n * that can be implemented or overridden; the name of every field is same as the name of the method, with a number\n * suffix that makes it unique in case of overloaded methods. The generated constructor will invoke\n * {@link #getHandle(ScriptFunction, MethodType, boolean)} or {@link #getHandle(Object, String, MethodType,\n * boolean)} to obtain the method handles; these methods make sure to add the necessary conversions and arity\n * adjustments so that the resulting method handles can be invoked from generated methods using {@code invokeExact}.\n * The constructor that takes a script function will only initialize the methods with the same name as the single\n * abstract method. The constructor will also store the Nashorn global that was current at the constructor\n * invocation time in a field named \"global\". The generated constructor will be public, regardless of whether the\n * supertype constructor was public or protected. The generated constructor will not be variable arity, even if the\n * supertype constructor was.\n * @param ctor the supertype constructor that is serving as the base for the generated constructor.\n * @param fromFunction true if we're generating a constructor that initializes SAM types from a single\n * ScriptFunction passed to it, false if we're generating a constructor that initializes an arbitrary type from a\n * ScriptObject passed to it.\n */\n private void generateOverridingConstructor(final Constructor ctor, final boolean fromFunction) {\n final Type originalCtorType = Type.getType(ctor);\n final Type[] originalArgTypes = originalCtorType.getArgumentTypes();\n final int argLen = originalArgTypes.length;\n final Type[] newArgTypes = new Type[argLen + 1];\n\n // Insert ScriptFunction|Object as the last argument to the constructor\n final Type extraArgumentType = fromFunction ? SCRIPT_FUNCTION_TYPE : OBJECT_TYPE;\n newArgTypes[argLen] = extraArgumentType;\n System.arraycopy(originalArgTypes, 0, newArgTypes, 0, argLen);\n\n // All constructors must be public, even if in the superclass they were protected.\n // Existing super constructor (this, args...) triggers generating (this, scriptObj, args...).\n final InstructionAdapter mv = new InstructionAdapter(cw.visitMethod(ACC_PUBLIC, INIT,\n Type.getMethodDescriptor(originalCtorType.getReturnType(), newArgTypes), null, null));\n\n mv.visitCode();\n // First, invoke super constructor with original arguments. If the form of the constructor we're generating is\n // (this, args..., scriptFn), then we're invoking super.(this, args...).\n mv.visitVarInsn(ALOAD, 0);\n final Class[] argTypes = ctor.getParameterTypes();\n int offset = 1; // First arg is at position 1, after this.\n for (int i = 0; i < argLen; ++i) {\n final Type argType = Type.getType(argTypes[i]);\n mv.load(offset, argType);\n offset += argType.getSize();\n }\n mv.invokespecial(superClassName, INIT, originalCtorType.getDescriptor(), false);\n\n // Get a descriptor to the appropriate \"JavaAdapterFactory.getHandle\" method.", "answers": [" final String getHandleDescriptor = fromFunction ? GET_HANDLE_FUNCTION_DESCRIPTOR : GET_HANDLE_OBJECT_DESCRIPTOR;"], "length": 3434, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "e2c57f9b-acf9-4841-8758-55f08f1e18ff", "reasoning": "Within generateOverridingConstructor, after invoking the superclass constructor, the code needs to decide which getHandle method descriptor to use based on whether the constructor is from a ScriptFunction (SAM) or a generic ScriptObject. The class already defines constants GET_HANDLE_FUNCTION_DESCRIPTOR and GET_HANDLE_OBJECT_DESCRIPTOR. The comment indicates we should obtain the appropriate descriptor, so the next line declares a local variable selecting the correct constant via a ternary expression.", "reasoning_model_answer": "String getHandleDescriptor = fromFunction ? GET_HANDLE_FUNCTION_DESCRIPTOR : GET_HANDLE_OBJECT_DESCRIPTOR;", "assistant_with_reasoning": "\nWithin generateOverridingConstructor, after invoking the superclass constructor, the code needs to decide which getHandle method descriptor to use based on whether the constructor is from a ScriptFunction (SAM) or a generic ScriptObject. The class already defines constants GET_HANDLE_FUNCTION_DESCRIPTOR and GET_HANDLE_OBJECT_DESCRIPTOR. The comment indicates we should obtain the appropriate descriptor, so the next line declares a local variable selecting the correct constant via a ternary expression.\n\nString getHandleDescriptor = fromFunction ? GET_HANDLE_FUNCTION_DESCRIPTOR : GET_HANDLE_OBJECT_DESCRIPTOR;", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.097, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 2, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 32375, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "String getHandleDescriptor = fromFunction ? GET_HANDLE_FUNCTION_DESCRIPTOR : GET_HANDLE_OBJECT_DESCRIPTOR;", "score": 0.94, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "import json\nimport logging\n\nfrom unittest import mock\n\nfrom django.conf import settings\nfrom django.contrib.auth.models import Group, Permission\nfrom django.core import mail\nfrom django.core.mail import EmailMultiAlternatives\nfrom django.test import TestCase, override_settings\nfrom django.urls import reverse\nfrom freezegun import freeze_time\n\nfrom wagtail.core.models import (\n GroupApprovalTask, Page, Task, TaskState, Workflow, WorkflowPage, WorkflowState, WorkflowTask)\nfrom wagtail.core.signals import page_published\nfrom wagtail.tests.testapp.models import SimplePage, SimpleTask\nfrom wagtail.tests.utils import WagtailTestUtils\nfrom wagtail.users.models import UserProfile\n\n\ndef delete_existing_workflows():\n WorkflowPage.objects.all().delete()\n Workflow.objects.all().delete()\n Task.objects.all().delete()\n WorkflowTask.objects.all().delete()\n\n\nclass TestWorkflowsIndexView(TestCase, WagtailTestUtils):\n\n def setUp(self):\n delete_existing_workflows()\n self.login()\n\n self.editor = self.create_user(\n username='editor',\n email='editor@email.com',\n password='password',\n )\n editors = Group.objects.get(name='Editors')\n editors.user_set.add(self.editor)\n\n self.moderator = self.create_user(\n username='moderator',\n email='moderator@email.com',\n password='password',\n )\n moderators = Group.objects.get(name='Moderators')\n moderators.user_set.add(self.moderator)\n moderators.permissions.add(Permission.objects.get(codename=\"add_workflow\"))\n\n def get(self, params={}):\n return self.client.get(reverse('wagtailadmin_workflows:index'), params)\n\n def test_simple(self):\n response = self.get()\n self.assertEqual(response.status_code, 200)\n self.assertTemplateUsed(response, 'wagtailadmin/workflows/index.html')\n\n # Initially there should be no workflows listed\n self.assertContains(response, \"There are no enabled workflows.\")\n\n Workflow.objects.create(name=\"test_workflow\", active=True)\n\n # Now the listing should contain our workflow\n response = self.get()\n self.assertEqual(response.status_code, 200)\n self.assertTemplateUsed(response, 'wagtailadmin/workflows/index.html')\n self.assertNotContains(response, \"There are no enabled workflows.\")\n self.assertContains(response, \"test_workflow\")\n\n def test_deactivated(self):\n Workflow.objects.create(name=\"test_workflow\", active=False)\n\n # The listing should contain our workflow, as well as marking it as disabled\n response = self.get(params={'show_disabled': 'true'})\n self.assertEqual(response.status_code, 200)\n self.assertNotContains(response, \"No workflows have been created.\")\n self.assertContains(response, \"test_workflow\")\n self.assertContains(response, 'Disabled', html=True)\n\n # If we set 'show_disabled' to 'False', the workflow should not be displayed\n response = self.get(params={})\n self.assertEqual(response.status_code, 200)\n self.assertContains(response, \"There are no enabled workflows.\")\n\n def test_permissions(self):\n self.login(user=self.editor)\n response = self.get()\n self.assertEqual(response.status_code, 302)\n full_context = {key: value for context in response.context for key, value in context.items()}\n self.assertEqual(full_context['message'], 'Sorry, you do not have permission to access this area.')\n\n self.login(user=self.moderator)\n response = self.get()\n self.assertEqual(response.status_code, 200)\n\n\nclass TestWorkflowsCreateView(TestCase, WagtailTestUtils):\n\n def setUp(self):\n delete_existing_workflows()\n self.login()\n self.task_1 = SimpleTask.objects.create(name=\"first_task\")\n self.task_2 = SimpleTask.objects.create(name=\"second_task\")\n\n self.editor = self.create_user(\n username='editor',\n email='editor@email.com',\n password='password',\n )\n editors = Group.objects.get(name='Editors')\n editors.user_set.add(self.editor)\n\n self.moderator = self.create_user(\n username='moderator',\n email='moderator@email.com',\n password='password',\n )\n moderators = Group.objects.get(name='Moderators')\n moderators.user_set.add(self.moderator)\n moderators.permissions.add(Permission.objects.get(codename=\"add_workflow\"))\n\n self.root_page = Page.objects.get(depth=1)\n\n def get(self, params={}):\n return self.client.get(reverse('wagtailadmin_workflows:add'), params)\n\n def post(self, post_data={}):\n return self.client.post(reverse('wagtailadmin_workflows:add'), post_data)\n\n def test_get(self):\n response = self.get()\n self.assertEqual(response.status_code, 200)\n self.assertTemplateUsed(response, 'wagtailadmin/workflows/create.html')\n\n def test_post(self):\n response = self.post({\n 'name': ['test_workflow'],\n 'active': ['on'],\n 'workflow_tasks-TOTAL_FORMS': ['2'],\n 'workflow_tasks-INITIAL_FORMS': ['0'],\n 'workflow_tasks-MIN_NUM_FORMS': ['0'],\n 'workflow_tasks-MAX_NUM_FORMS': ['1000'],\n 'workflow_tasks-0-task': [str(self.task_1.id)],\n 'workflow_tasks-0-id': [''],\n 'workflow_tasks-0-ORDER': ['1'],\n 'workflow_tasks-0-DELETE': [''],\n 'workflow_tasks-1-task': [str(self.task_2.id)],\n 'workflow_tasks-1-id': [''],\n 'workflow_tasks-1-ORDER': ['2'],\n 'workflow_tasks-1-DELETE': [''],\n 'pages-TOTAL_FORMS': ['2'],\n 'pages-INITIAL_FORMS': ['1'],\n 'pages-MIN_NUM_FORMS': ['0'],\n 'pages-MAX_NUM_FORMS': ['1000'],\n 'pages-0-page': [str(self.root_page.id)],\n 'pages-0-DELETE': [''],\n 'pages-1-page': [''],\n 'pages-1-DELETE': [''],\n })\n\n # Should redirect back to index\n self.assertRedirects(response, reverse('wagtailadmin_workflows:index'))\n\n # Check that the workflow was created\n workflows = Workflow.objects.filter(name=\"test_workflow\", active=True)\n self.assertEqual(workflows.count(), 1)\n\n workflow = workflows.first()\n\n # Check that the tasks are associated with the workflow\n self.assertEqual([self.task_1.task_ptr, self.task_2.task_ptr], list(workflow.tasks))\n\n # Check that the tasks have sort_order set on WorkflowTask correctly\n self.assertEqual(WorkflowTask.objects.get(workflow=workflow, task=self.task_1.task_ptr).sort_order, 0)\n self.assertEqual(WorkflowTask.objects.get(workflow=workflow, task=self.task_2.task_ptr).sort_order, 1)\n\n def test_permissions(self):\n self.login(user=self.editor)\n response = self.get()\n self.assertEqual(response.status_code, 302)\n full_context = {key: value for context in response.context for key, value in context.items()}\n self.assertEqual(full_context['message'], 'Sorry, you do not have permission to access this area.')\n\n self.login(user=self.moderator)\n response = self.get()\n self.assertEqual(response.status_code, 200)\n\n def test_page_already_has_workflow_check(self):\n workflow = Workflow.objects.create(name=\"existing_workflow\")\n WorkflowPage.objects.create(workflow=workflow, page=self.root_page)\n\n response = self.post({\n 'name': ['test_workflow'],\n 'active': ['on'],\n 'workflow_tasks-TOTAL_FORMS': ['2'],\n 'workflow_tasks-INITIAL_FORMS': ['0'],\n 'workflow_tasks-MIN_NUM_FORMS': ['0'],\n 'workflow_tasks-MAX_NUM_FORMS': ['1000'],\n 'workflow_tasks-0-task': [str(self.task_1.id)],\n 'workflow_tasks-0-id': [''],\n 'workflow_tasks-0-ORDER': ['1'],\n 'workflow_tasks-0-DELETE': [''],\n 'workflow_tasks-1-task': [str(self.task_2.id)],\n 'workflow_tasks-1-id': [''],\n 'workflow_tasks-1-ORDER': ['2'],\n 'workflow_tasks-1-DELETE': [''],\n 'pages-TOTAL_FORMS': ['2'],\n 'pages-INITIAL_FORMS': ['1'],\n 'pages-MIN_NUM_FORMS': ['0'],\n 'pages-MAX_NUM_FORMS': ['1000'],\n 'pages-0-page': [str(self.root_page.id)],\n 'pages-0-DELETE': [''],\n 'pages-1-page': [''],\n 'pages-1-DELETE': [''],\n })\n\n self.assertEqual(response.status_code, 200)\n self.assertFormsetError(response, 'pages_formset', 0, 'page', [\"This page already has workflow 'existing_workflow' assigned.\"])\n\n\nclass TestWorkflowsEditView(TestCase, WagtailTestUtils):\n\n def setUp(self):\n delete_existing_workflows()\n self.login()\n self.workflow = Workflow.objects.create(name=\"workflow_to_edit\")\n self.task_1 = SimpleTask.objects.create(name=\"first_task\")\n self.task_2 = SimpleTask.objects.create(name=\"second_task\")\n self.inactive_task = SimpleTask.objects.create(name=\"inactive_task\", active=False)\n self.workflow_task = WorkflowTask.objects.create(workflow=self.workflow, task=self.task_1.task_ptr, sort_order=0)\n self.page = Page.objects.first()\n WorkflowPage.objects.create(workflow=self.workflow, page=self.page)\n\n self.editor = self.create_user(\n username='editor',\n email='editor@email.com',\n password='password',\n )\n editors = Group.objects.get(name='Editors')\n editors.user_set.add(self.editor)\n\n self.moderator = self.create_user(\n username='moderator',\n email='moderator@email.com',\n password='password',\n )\n moderators = Group.objects.get(name='Moderators')\n moderators.user_set.add(self.moderator)\n moderators.permissions.add(Permission.objects.get(codename=\"change_workflow\"))\n\n def get(self, params={}):\n return self.client.get(reverse('wagtailadmin_workflows:edit', args=[self.workflow.id]), params)\n\n def post(self, post_data={}):\n return self.client.post(reverse('wagtailadmin_workflows:edit', args=[self.workflow.id]), post_data)\n\n def test_get(self):\n response = self.get()\n self.assertEqual(response.status_code, 200)\n self.assertTemplateUsed(response, 'wagtailadmin/workflows/edit.html')\n\n # Check that the list of pages has the page to which this workflow is assigned\n self.assertContains(response, self.page.title)\n\n def test_post(self):\n response = self.post({\n 'name': [str(self.workflow.name)],\n 'active': ['on'],\n 'workflow_tasks-TOTAL_FORMS': ['2'],\n 'workflow_tasks-INITIAL_FORMS': ['1'],\n 'workflow_tasks-MIN_NUM_FORMS': ['0'],\n 'workflow_tasks-MAX_NUM_FORMS': ['1000'],\n 'workflow_tasks-0-task': [str(self.task_1.id)],\n 'workflow_tasks-0-id': [str(self.workflow_task.id)],\n 'workflow_tasks-0-ORDER': ['1'],\n 'workflow_tasks-0-DELETE': [''],\n 'workflow_tasks-1-task': [str(self.task_2.id)],\n 'workflow_tasks-1-id': [''],\n 'workflow_tasks-1-ORDER': ['2'],\n 'workflow_tasks-1-DELETE': [''],\n 'pages-TOTAL_FORMS': ['2'],\n 'pages-INITIAL_FORMS': ['1'],\n 'pages-MIN_NUM_FORMS': ['0'],\n 'pages-MAX_NUM_FORMS': ['1000'],\n 'pages-0-page': [str(self.page.id)],\n 'pages-0-DELETE': [''],\n 'pages-1-page': [''],\n 'pages-1-DELETE': [''],\n })\n\n # Should redirect back to index\n self.assertRedirects(response, reverse('wagtailadmin_workflows:index'))\n\n # Check that the workflow was created\n workflows = Workflow.objects.filter(name=\"workflow_to_edit\", active=True)\n self.assertEqual(workflows.count(), 1)\n\n workflow = workflows.first()\n\n # Check that the tasks are associated with the workflow\n self.assertEqual([self.task_1.task_ptr, self.task_2.task_ptr], list(workflow.tasks))\n\n # Check that the tasks have sort_order set on WorkflowTask correctly\n self.assertEqual(WorkflowTask.objects.get(workflow=workflow, task=self.task_1.task_ptr).sort_order, 0)\n self.assertEqual(WorkflowTask.objects.get(workflow=workflow, task=self.task_2.task_ptr).sort_order, 1)\n\n def test_permissions(self):\n self.login(user=self.editor)\n response = self.get()\n self.assertEqual(response.status_code, 302)\n full_context = {key: value for context in response.context for key, value in context.items()}\n self.assertEqual(full_context['message'], 'Sorry, you do not have permission to access this area.')\n\n self.login(user=self.moderator)\n response = self.get()\n self.assertEqual(response.status_code, 200)\n\n def test_duplicate_page_check(self):\n response = self.post({\n 'name': [str(self.workflow.name)],\n 'active': ['on'],\n 'workflow_tasks-TOTAL_FORMS': ['2'],\n 'workflow_tasks-INITIAL_FORMS': ['1'],\n 'workflow_tasks-MIN_NUM_FORMS': ['0'],\n 'workflow_tasks-MAX_NUM_FORMS': ['1000'],\n 'workflow_tasks-0-task': [str(self.task_1.id)],\n 'workflow_tasks-0-id': [str(self.workflow_task.id)],\n 'workflow_tasks-0-ORDER': ['1'],\n 'workflow_tasks-0-DELETE': [''],\n 'workflow_tasks-1-task': [str(self.task_2.id)],\n 'workflow_tasks-1-id': [''],\n 'workflow_tasks-1-ORDER': ['2'],\n 'workflow_tasks-1-DELETE': [''],\n 'pages-TOTAL_FORMS': ['2'],\n 'pages-INITIAL_FORMS': ['1'],\n 'pages-MIN_NUM_FORMS': ['0'],\n 'pages-MAX_NUM_FORMS': ['1000'],\n 'pages-0-page': [str(self.page.id)],\n 'pages-0-DELETE': [''],\n 'pages-1-page': [str(self.page.id)],\n 'pages-1-DELETE': [''],\n })\n\n self.assertEqual(response.status_code, 200)\n self.assertFormsetError(response, 'pages_formset', None, None, ['You cannot assign this workflow to the same page multiple times.'])\n\n def test_pages_ignored_if_workflow_disabled(self):\n self.workflow.active = False\n self.workflow.save()\n self.workflow.workflow_pages.all().delete()\n\n response = self.post({\n 'name': [str(self.workflow.name)],\n 'active': ['on'],\n 'workflow_tasks-TOTAL_FORMS': ['2'],\n 'workflow_tasks-INITIAL_FORMS': ['1'],\n 'workflow_tasks-MIN_NUM_FORMS': ['0'],\n 'workflow_tasks-MAX_NUM_FORMS': ['1000'],\n 'workflow_tasks-0-task': [str(self.task_1.id)],\n 'workflow_tasks-0-id': [str(self.workflow_task.id)],\n 'workflow_tasks-0-ORDER': ['1'],\n 'workflow_tasks-0-DELETE': [''],\n 'workflow_tasks-1-task': [str(self.task_2.id)],\n 'workflow_tasks-1-id': [''],\n 'workflow_tasks-1-ORDER': ['2'],\n 'workflow_tasks-1-DELETE': [''],\n 'pages-TOTAL_FORMS': ['2'],\n 'pages-INITIAL_FORMS': ['1'],\n 'pages-MIN_NUM_FORMS': ['0'],\n 'pages-MAX_NUM_FORMS': ['1000'],\n 'pages-0-page': [str(self.page.id)],\n 'pages-0-DELETE': [''],\n 'pages-1-page': [''],\n 'pages-1-DELETE': [''],\n })\n\n # Should redirect back to index\n self.assertRedirects(response, reverse('wagtailadmin_workflows:index'))\n\n # Check that the pages weren't added to the workflow\n self.workflow.refresh_from_db()\n self.assertFalse(self.workflow.workflow_pages.exists())\n\n\nclass TestRemoveWorkflow(TestCase, WagtailTestUtils):\n fixtures = ['test.json']\n\n def setUp(self):\n delete_existing_workflows()\n self.login()\n self.workflow = Workflow.objects.create(name=\"workflow\")\n self.page = Page.objects.first()\n WorkflowPage.objects.create(workflow=self.workflow, page=self.page)\n\n self.editor = self.create_user(\n username='editor',\n email='editor@email.com',\n password='password',\n )\n editors = Group.objects.get(name='Editors')\n editors.user_set.add(self.editor)\n\n self.moderator = self.create_user(\n username='moderator',\n email='moderator@email.com',\n password='password',\n )\n moderators = Group.objects.get(name='Moderators')\n moderators.user_set.add(self.moderator)\n moderators.permissions.add(Permission.objects.get(codename=\"change_workflow\"))\n\n def post(self, post_data={}):\n return self.client.post(reverse('wagtailadmin_workflows:remove', args=[self.page.id, self.workflow.id]), post_data)\n\n def test_post(self):\n # Check that a WorkflowPage instance is removed correctly\n self.post()\n self.assertEqual(WorkflowPage.objects.filter(workflow=self.workflow, page=self.page).count(), 0)\n\n def test_no_permissions(self):\n self.login(user=self.editor)\n response = self.post()\n self.assertEqual(response.status_code, 302)\n\n def test_post_with_permission(self):\n self.login(user=self.moderator)\n response = self.post()\n self.assertEqual(response.status_code, 302)\n\n\nclass TestTaskIndexView(TestCase, WagtailTestUtils):\n\n def setUp(self):\n delete_existing_workflows()\n self.login()\n\n self.editor = self.create_user(\n username='editor',\n email='editor@email.com',\n password='password',\n )\n editors = Group.objects.get(name='Editors')\n editors.user_set.add(self.editor)\n\n self.moderator = self.create_user(\n username='moderator',\n email='moderator@email.com',\n password='password',\n )\n moderators = Group.objects.get(name='Moderators')\n moderators.user_set.add(self.moderator)\n moderators.permissions.add(Permission.objects.get(codename=\"change_task\"))\n\n def get(self, params={}):\n return self.client.get(reverse('wagtailadmin_workflows:task_index'), params)\n\n def test_simple(self):\n response = self.get()\n self.assertEqual(response.status_code, 200)\n self.assertTemplateUsed(response, 'wagtailadmin/workflows/task_index.html')\n\n # Initially there should be no tasks listed\n self.assertContains(response, \"There are no enabled tasks\")\n\n SimpleTask.objects.create(name=\"test_task\", active=True)\n\n # Now the listing should contain our task\n response = self.get()\n self.assertEqual(response.status_code, 200)\n self.assertTemplateUsed(response, 'wagtailadmin/workflows/task_index.html')\n self.assertNotContains(response, \"There are no enabled tasks\")\n self.assertContains(response, \"test_task\")\n\n def test_deactivated(self):\n Task.objects.create(name=\"test_task\", active=False)\n\n # The listing should contain our task, as well as marking it as disabled\n response = self.get(params={'show_disabled': 'true'})\n self.assertEqual(response.status_code, 200)\n self.assertNotContains(response, \"No tasks have been created.\")\n self.assertContains(response, \"test_task\")\n self.assertContains(response, 'Disabled', html=True)\n\n # The listing should not contain task if show_disabled query parameter is 'False'\n response = self.get(params={})\n self.assertEqual(response.status_code, 200)\n self.assertContains(response, \"There are no enabled tasks\")\n self.assertNotContains(response, \"test_task\")\n\n def test_permissions(self):\n self.login(user=self.editor)\n response = self.get()\n self.assertEqual(response.status_code, 302)\n full_context = {key: value for context in response.context for key, value in context.items()}\n self.assertEqual(full_context['message'], 'Sorry, you do not have permission to access this area.')\n\n self.login(user=self.moderator)\n response = self.get()\n self.assertEqual(response.status_code, 200)\n\n\nclass TestCreateTaskView(TestCase, WagtailTestUtils):\n\n def setUp(self):\n delete_existing_workflows()\n self.login()\n\n self.editor = self.create_user(\n username='editor',\n email='editor@email.com',\n password='password',\n )\n editors = Group.objects.get(name='Editors')\n editors.user_set.add(self.editor)\n\n self.moderator = self.create_user(\n username='moderator',\n email='moderator@email.com',\n password='password',\n )\n moderators = Group.objects.get(name='Moderators')\n moderators.user_set.add(self.moderator)\n moderators.permissions.add(Permission.objects.get(codename=\"add_task\"))\n\n def get(self, url_kwargs=None, params={}):\n url_kwargs = url_kwargs or {}\n url_kwargs.setdefault('app_label', SimpleTask._meta.app_label)\n url_kwargs.setdefault('model_name', SimpleTask._meta.model_name)\n return self.client.get(reverse('wagtailadmin_workflows:add_task', kwargs=url_kwargs), params)\n\n def post(self, post_data={}):\n return self.client.post(reverse('wagtailadmin_workflows:add_task', kwargs={'app_label': SimpleTask._meta.app_label, 'model_name': SimpleTask._meta.model_name}), post_data)\n\n def test_get(self):\n response = self.get()\n self.assertEqual(response.status_code, 200)\n self.assertTemplateUsed(response, 'wagtailadmin/workflows/create_task.html')\n\n def test_get_with_non_task_model(self):\n response = self.get(url_kwargs={'app_label': 'wagtailcore', 'model_name': 'Site'})\n self.assertEqual(response.status_code, 404)\n\n def test_get_with_base_task_model(self):\n response = self.get(url_kwargs={'app_label': 'wagtailcore', 'model_name': 'Task'})\n self.assertEqual(response.status_code, 404)\n\n def test_post(self):\n response = self.post({'name': 'test_task', 'active': 'on'})\n\n # Should redirect back to index\n self.assertRedirects(response, reverse('wagtailadmin_workflows:task_index'))\n\n # Check that the task was created\n tasks = Task.objects.filter(name=\"test_task\", active=True)\n self.assertEqual(tasks.count(), 1)\n\n def test_permissions(self):\n self.login(user=self.editor)\n response = self.get()\n self.assertEqual(response.status_code, 302)\n full_context = {key: value for context in response.context for key, value in context.items()}\n self.assertEqual(full_context['message'], 'Sorry, you do not have permission to access this area.')\n\n self.login(user=self.moderator)\n response = self.get()\n self.assertEqual(response.status_code, 200)\n\n\nclass TestSelectTaskTypeView(TestCase, WagtailTestUtils):\n\n def setUp(self):\n delete_existing_workflows()\n self.login()\n\n def get(self):\n return self.client.get(reverse('wagtailadmin_workflows:select_task_type'))\n\n def test_get(self):\n response = self.get()\n self.assertEqual(response.status_code, 200)\n self.assertTemplateUsed(response, 'wagtailadmin/workflows/select_task_type.html')\n\n # Check that the list of available task types includes SimpleTask and GroupApprovalTask\n self.assertContains(response, SimpleTask.get_verbose_name())\n self.assertContains(response, GroupApprovalTask.get_verbose_name())\n self.assertContains(response, GroupApprovalTask.get_description())\n\n\nclass TestEditTaskView(TestCase, WagtailTestUtils):\n\n def setUp(self):\n delete_existing_workflows()\n self.login()\n self.task = GroupApprovalTask.objects.create(name=\"test_task\")\n\n self.editor = self.create_user(\n username='editor',\n email='editor@email.com',\n password='password',\n )\n editors = Group.objects.get(name='Editors')\n editors.user_set.add(self.editor)\n\n self.moderator = self.create_user(\n username='moderator',\n email='moderator@email.com',\n password='password',\n )\n moderators = Group.objects.get(name='Moderators')\n moderators.user_set.add(self.moderator)\n moderators.permissions.add(Permission.objects.get(codename=\"change_task\"))\n\n def get(self, params={}):\n return self.client.get(reverse('wagtailadmin_workflows:edit_task', args=[self.task.id]), params)\n\n def post(self, post_data={}):\n return self.client.post(reverse('wagtailadmin_workflows:edit_task', args=[self.task.id]), post_data)\n\n def test_get(self):\n response = self.get()\n self.assertEqual(response.status_code, 200)\n self.assertTemplateUsed(response, 'wagtailadmin/workflows/edit_task.html')\n\n def test_post(self):\n self.assertEqual(self.task.groups.count(), 0)\n editors = Group.objects.get(name='Editors')\n\n response = self.post({'name': 'test_task_modified', 'active': 'on', 'groups': [str(editors.id)]})\n\n # Should redirect back to index\n self.assertRedirects(response, reverse('wagtailadmin_workflows:task_index'))\n\n # Check that the task was updated\n task = GroupApprovalTask.objects.get(id=self.task.id)\n\n # The task name cannot be changed\n self.assertEqual(task.name, \"test_task\")\n\n # This request should've added a group to the task\n self.assertEqual(task.groups.count(), 1)\n self.assertTrue(task.groups.filter(id=editors.id).exists())\n\n def test_permissions(self):\n self.login(user=self.editor)\n response = self.get()\n self.assertEqual(response.status_code, 302)\n full_context = {key: value for context in response.context for key, value in context.items()}\n self.assertEqual(full_context['message'], 'Sorry, you do not have permission to access this area.')\n\n self.login(user=self.moderator)\n response = self.get()\n self.assertEqual(response.status_code, 200)\n\n\nclass TestSubmitToWorkflow(TestCase, WagtailTestUtils):\n def setUp(self):\n delete_existing_workflows()\n self.submitter = self.create_user(\n username='submitter',\n email='submitter@email.com',\n password='password',\n )\n editors = Group.objects.get(name='Editors')\n editors.user_set.add(self.submitter)\n self.moderator = self.create_user(\n username='moderator',\n email='moderator@email.com',\n password='password',\n )\n moderators = Group.objects.get(name='Moderators')\n moderators.user_set.add(self.moderator)\n\n self.superuser = self.create_superuser(\n username='superuser',\n email='superuser@email.com',\n password='password',\n )\n\n self.login(user=self.submitter)\n\n # Create a page\n root_page = Page.objects.get(id=2)\n self.page = SimplePage(\n title=\"Hello world!\",\n slug='hello-world',\n content=\"hello\",\n live=False,\n has_unpublished_changes=True,\n )\n root_page.add_child(instance=self.page)\n self.page.save_revision()\n\n self.workflow, self.task_1, self.task_2 = self.create_workflow_and_tasks()\n\n WorkflowPage.objects.create(workflow=self.workflow, page=self.page)\n\n def create_workflow_and_tasks(self):\n workflow = Workflow.objects.create(name='test_workflow')\n task_1 = GroupApprovalTask.objects.create(name='test_task_1')\n task_2 = GroupApprovalTask.objects.create(name='test_task_2')\n task_1.groups.set(Group.objects.filter(name='Moderators'))\n task_2.groups.set(Group.objects.filter(name='Moderators'))\n WorkflowTask.objects.create(workflow=workflow, task=task_1, sort_order=1)\n WorkflowTask.objects.create(workflow=workflow, task=task_2, sort_order=2)\n return workflow, task_1, task_2\n\n def submit(self):\n post_data = {\n 'title': str(self.page.title),\n 'slug': str(self.page.slug),\n 'content': str(self.page.content),\n 'action-submit': \"True\",\n }\n return self.client.post(reverse('wagtailadmin_pages:edit', args=(self.page.id,)), post_data)\n\n def test_submit_for_approval_creates_states(self):\n \"\"\"Test that WorkflowState and TaskState objects are correctly created when a Page is submitted for approval\"\"\"\n\n self.submit()\n\n workflow_state = self.page.current_workflow_state\n\n self.assertEqual(type(workflow_state), WorkflowState)\n self.assertEqual(workflow_state.workflow, self.workflow)\n self.assertEqual(workflow_state.status, workflow_state.STATUS_IN_PROGRESS)\n self.assertEqual(workflow_state.requested_by, self.submitter)\n\n task_state = workflow_state.current_task_state\n\n self.assertEqual(type(task_state), TaskState)\n self.assertEqual(task_state.task.specific, self.task_1)\n self.assertEqual(task_state.status, task_state.STATUS_IN_PROGRESS)\n\n def test_submit_for_approval_changes_status_in_header_meta(self):\n edit_url = reverse('wagtailadmin_pages:edit', args=(self.page.id, ))\n\n response = self.client.get(edit_url)\n self.assertContains(response, 'Draft', count=1)\n\n # submit for approval\n self.submit()\n\n response = self.client.get(edit_url)\n workflow_status_url = reverse('wagtailadmin_pages:workflow_status', args=(self.page.id, ))\n self.assertContains(response, workflow_status_url)\n self.assertRegex(response.content.decode('utf-8'), r'Awaiting[\\s|\\n]+{}'.format(self.page.current_workflow_task.name))\n self.assertNotContains(response, 'Draft')\n\n @mock.patch.object(EmailMultiAlternatives, 'send', side_effect=IOError('Server down'))\n def test_email_send_error(self, mock_fn):\n logging.disable(logging.CRITICAL)\n\n response = self.submit()\n logging.disable(logging.NOTSET)\n\n # An email that fails to send should return a message rather than crash the page\n self.assertEqual(response.status_code, 302)\n response = self.client.get(reverse('wagtailadmin_home'))\n\n def test_resume_rejected_workflow(self):\n # test that an existing workflow can be resumed by submitting when rejected\n self.workflow.start(self.page, user=self.submitter)\n workflow_state = self.page.current_workflow_state\n workflow_state.current_task_state.approve(user=self.superuser)\n workflow_state.refresh_from_db()\n workflow_state.current_task_state.reject(user=self.superuser)\n workflow_state.refresh_from_db()\n self.assertEqual(workflow_state.current_task_state.task.specific, self.task_2)\n self.assertEqual(workflow_state.status, WorkflowState.STATUS_NEEDS_CHANGES)\n\n self.submit()\n workflow_state.refresh_from_db()\n\n # check that the same workflow state's status is now in progress\n self.assertEqual(workflow_state.status, WorkflowState.STATUS_IN_PROGRESS)\n\n # check that the workflow remains on the rejecting task, rather than resetting\n self.assertEqual(workflow_state.current_task_state.task.specific, self.task_2)\n\n def test_restart_rejected_workflow(self):\n # test that an existing workflow can be restarted when rejected\n self.workflow.start(self.page, user=self.submitter)\n workflow_state = self.page.current_workflow_state\n workflow_state.current_task_state.approve(user=self.superuser)\n workflow_state.refresh_from_db()\n workflow_state.current_task_state.reject(user=self.superuser)\n workflow_state.refresh_from_db()\n self.assertEqual(workflow_state.current_task_state.task.specific, self.task_2)\n self.assertEqual(workflow_state.status, WorkflowState.STATUS_NEEDS_CHANGES)\n\n post_data = {\n 'title': str(self.page.title),\n 'slug': str(self.page.slug),\n 'content': str(self.page.content),\n 'action-restart-workflow': \"True\",\n }\n self.client.post(reverse('wagtailadmin_pages:edit', args=(self.page.id,)), post_data)\n workflow_state.refresh_from_db()\n\n # check that the same workflow state's status is now cancelled\n self.assertEqual(workflow_state.status, WorkflowState.STATUS_CANCELLED)\n\n # check that the new workflow has started on the first task\n new_workflow_state = self.page.current_workflow_state\n self.assertEqual(new_workflow_state.status, WorkflowState.STATUS_IN_PROGRESS)\n self.assertEqual(new_workflow_state.current_task_state.task.specific, self.task_1)\n\n def test_cancel_workflow(self):\n # test that an existing workflow can be cancelled after submission by the submitter\n self.workflow.start(self.page, user=self.submitter)\n workflow_state = self.page.current_workflow_state\n self.assertEqual(workflow_state.current_task_state.task.specific, self.task_1)\n self.assertEqual(workflow_state.status, WorkflowState.STATUS_IN_PROGRESS)\n post_data = {\n 'title': str(self.page.title),\n 'slug': str(self.page.slug),\n 'content': str(self.page.content),\n 'action-cancel-workflow': \"True\",\n }\n self.client.post(reverse('wagtailadmin_pages:edit', args=(self.page.id,)), post_data)\n workflow_state.refresh_from_db()\n\n # check that the workflow state's status is now cancelled\n self.assertEqual(workflow_state.status, WorkflowState.STATUS_CANCELLED)\n self.assertEqual(workflow_state.current_task_state.status, TaskState.STATUS_CANCELLED)\n\n def test_email_headers(self):\n # Submit\n self.submit()\n\n msg_headers = set(mail.outbox[0].message().items())\n headers = {('Auto-Submitted', 'auto-generated')}\n self.assertTrue(headers.issubset(msg_headers), msg='Message is missing the Auto-Submitted header.',)\n\n\n@freeze_time(\"2020-03-31 12:00:00\")\nclass TestApproveRejectWorkflow(TestCase, WagtailTestUtils):\n def setUp(self):\n delete_existing_workflows()\n self.submitter = self.create_user(\n username='submitter',\n first_name='Sebastian',\n last_name='Mitter',\n email='submitter@email.com',\n password='password',\n )\n editors = Group.objects.get(name='Editors')\n editors.user_set.add(self.submitter)\n self.moderator = self.create_user(\n username='moderator',\n email='moderator@email.com',\n password='password',\n )\n moderators = Group.objects.get(name='Moderators')\n moderators.user_set.add(self.moderator)\n\n self.superuser = self.create_superuser(\n username='superuser',\n email='superuser@email.com',\n password='password',\n )\n\n self.login(user=self.submitter)\n\n # Create a page\n root_page = Page.objects.get(id=2)\n self.page = SimplePage(\n title=\"Hello world!\",\n slug='hello-world',\n content=\"hello\",\n live=False,\n has_unpublished_changes=True,\n )\n root_page.add_child(instance=self.page)\n\n self.workflow, self.task_1 = self.create_workflow_and_tasks()\n\n WorkflowPage.objects.create(workflow=self.workflow, page=self.page)\n\n self.submit()\n\n self.login(user=self.moderator)\n\n def create_workflow_and_tasks(self):\n workflow = Workflow.objects.create(name='test_workflow')\n task_1 = GroupApprovalTask.objects.create(name='test_task_1')\n task_1.groups.set(Group.objects.filter(name='Moderators'))\n WorkflowTask.objects.create(workflow=workflow, task=task_1, sort_order=1)\n return workflow, task_1\n\n def submit(self):\n post_data = {\n 'title': str(self.page.title),\n 'slug': str(self.page.slug),\n 'content': str(self.page.content),\n 'action-submit': \"True\",\n }\n return self.client.post(reverse('wagtailadmin_pages:edit', args=(self.page.id,)), post_data)\n\n @override_settings(WAGTAIL_FINISH_WORKFLOW_ACTION='')\n def test_approve_task_and_workflow(self):\n \"\"\"\n This posts to the approve task view and checks that the page was approved and published\n \"\"\"\n # Unset WAGTAIL_FINISH_WORKFLOW_ACTION - default action should be to publish\n del settings.WAGTAIL_FINISH_WORKFLOW_ACTION\n # Connect a mock signal handler to page_published signal\n mock_handler = mock.MagicMock()\n page_published.connect(mock_handler)\n\n # Post\n self.client.post(reverse('wagtailadmin_pages:workflow_action', args=(self.page.id, 'approve', self.page.current_workflow_task_state.id)), {'comment': 'my comment'})\n\n # Check that the workflow was approved\n\n workflow_state = WorkflowState.objects.get(page=self.page, requested_by=self.submitter)\n\n self.assertEqual(workflow_state.status, workflow_state.STATUS_APPROVED)\n\n # Check that the task was approved\n\n task_state = workflow_state.current_task_state\n\n self.assertEqual(task_state.status, task_state.STATUS_APPROVED)\n\n # Check that the comment was added to the task state correctly\n\n self.assertEqual(task_state.comment, 'my comment')\n\n page = Page.objects.get(id=self.page.id)\n # Page must be live\n self.assertTrue(page.live, \"Approving moderation failed to set live=True\")\n # Page should now have no unpublished changes\n self.assertFalse(\n page.has_unpublished_changes,\n \"Approving moderation failed to set has_unpublished_changes=False\"\n )\n\n # Check that the page_published signal was fired\n self.assertEqual(mock_handler.call_count, 1)\n mock_call = mock_handler.mock_calls[0][2]\n\n self.assertEqual(mock_call['sender'], self.page.specific_class)\n self.assertEqual(mock_call['instance'], self.page)\n self.assertIsInstance(mock_call['instance'], self.page.specific_class)\n\n def test_workflow_action_get(self):\n \"\"\"\n This tests that a GET request to the workflow action view (for the approve action) returns a modal with a form for extra data entry:\n adding a comment\n \"\"\"\n response = self.client.get(reverse('wagtailadmin_pages:workflow_action', args=(self.page.id, 'approve', self.page.current_workflow_task_state.id)))\n self.assertEqual(response.status_code, 200)\n self.assertTemplateUsed(response, 'wagtailadmin/pages/workflow_action_modal.html')\n html = json.loads(response.content)['html']\n self.assertTagInHTML('

    ', html)\n self.assertIn('Comment', html)\n\n def test_workflow_action_view_bad_page_id(self):\n \"\"\"\n This tests that the workflow action view handles invalid page ids correctly\n \"\"\"\n # Post\n response = self.client.post(reverse('wagtailadmin_pages:workflow_action', args=(127777777777, 'approve', self.page.current_workflow_task_state.id)))\n\n # Check that the user received a 404 response\n self.assertEqual(response.status_code, 404)\n\n def test_workflow_action_view_not_in_group(self):\n \"\"\"\n This tests that the workflow action view for a GroupApprovalTask won't allow approval from a user not in the\n specified group/a superuser\n \"\"\"\n # Remove privileges from user\n self.login(user=self.submitter)\n\n # Post\n response = self.client.post(reverse('wagtailadmin_pages:workflow_action', args=(self.page.id, 'approve', self.page.current_workflow_task_state.id)))\n # Check that the user received a permission denied response\n self.assertRedirects(response, '/admin/')\n\n def test_edit_view_workflow_cancellation_not_in_group(self):\n \"\"\"\n This tests that the page edit view for a GroupApprovalTask, locked to a user not in the\n specified group/a superuser, still allows the submitter to cancel workflows\n \"\"\"\n self.login(user=self.submitter)\n\n # Post\n response = self.client.post(reverse('wagtailadmin_pages:edit', args=(self.page.id, )), {'action-cancel-workflow': 'True'})\n\n # Check that the user received a 200 response\n self.assertEqual(response.status_code, 200)\n\n # Check that the workflow state was marked as cancelled\n workflow_state = WorkflowState.objects.get(page=self.page, requested_by=self.submitter)\n self.assertEqual(workflow_state.status, WorkflowState.STATUS_CANCELLED)\n\n def test_reject_task_and_workflow(self):\n \"\"\"\n This posts to the reject task view and checks that the page was rejected and not published\n \"\"\"\n # Post\n self.client.post(reverse('wagtailadmin_pages:workflow_action', args=(self.page.id, 'reject', self.page.current_workflow_task_state.id)))\n\n # Check that the workflow was marked as needing changes\n\n workflow_state = WorkflowState.objects.get(page=self.page, requested_by=self.submitter)\n\n self.assertEqual(workflow_state.status, workflow_state.STATUS_NEEDS_CHANGES)\n\n # Check that the task was rejected\n\n task_state = workflow_state.current_task_state\n\n self.assertEqual(task_state.status, task_state.STATUS_REJECTED)\n\n page = Page.objects.get(id=self.page.id)\n # Page must not be live\n self.assertFalse(page.live)\n\n def test_workflow_action_view_rejection_not_in_group(self):\n \"\"\"\n This tests that the workflow action view for a GroupApprovalTask won't allow rejection from a user not in the\n specified group/a superuser\n \"\"\"\n # Remove privileges from user\n self.login(user=self.submitter)\n\n # Post\n response = self.client.post(reverse('wagtailadmin_pages:workflow_action', args=(self.page.id, 'reject', self.page.current_workflow_task_state.id)))\n\n # Check that the user received a permission denied response\n self.assertRedirects(response, '/admin/')\n\n def test_collect_workflow_action_data_get(self):\n \"\"\"\n This tests that a GET request to the collect_workflow_action_data view (for the approve action) returns a modal with a form for extra data entry:\n adding a comment\n \"\"\"\n response = self.client.get(reverse('wagtailadmin_pages:collect_workflow_action_data', args=(self.page.id, 'approve', self.page.current_workflow_task_state.id)))\n self.assertEqual(response.status_code, 200)\n self.assertTemplateUsed(response, 'wagtailadmin/pages/workflow_action_modal.html')\n html = json.loads(response.content)['html']\n self.assertTagInHTML('', html)\n self.assertIn('Comment', html)\n\n def test_collect_workflow_action_data_post(self):\n \"\"\"\n This tests that a POST request to the collect_workflow_action_data view (for the approve action) returns a modal response with the validated data\n \"\"\"\n response = self.client.post(\n reverse('wagtailadmin_pages:collect_workflow_action_data', args=(self.page.id, 'approve', self.page.current_workflow_task_state.id)),\n {'comment': \"This is my comment\"}\n )\n self.assertEqual(response.status_code, 200)\n response_json = json.loads(response.content)\n self.assertEqual(response_json['step'], 'success')\n self.assertEqual(response_json['cleaned_data'], {'comment': \"This is my comment\"})\n\n def test_workflow_action_via_edit_view(self):\n \"\"\"\n Posting to the 'edit' view with 'action-workflow-action' set should perform the given workflow action in addition to updating page content\n \"\"\"\n # Post\n self.client.post(reverse('wagtailadmin_pages:edit', args=(self.page.id,)), {\n 'title': \"This title was edited while approving\",\n 'slug': str(self.page.slug),\n 'content': str(self.page.content),\n 'action-workflow-action': \"True\",\n 'workflow-action-name': 'approve',\n 'workflow-action-extra-data': '{\"comment\": \"my comment\"}'\n })\n\n # Check that the workflow was approved\n\n workflow_state = WorkflowState.objects.get(page=self.page, requested_by=self.submitter)\n\n self.assertEqual(workflow_state.status, workflow_state.STATUS_APPROVED)\n\n # Check that the task was approved\n\n task_state = workflow_state.current_task_state\n\n self.assertEqual(task_state.status, task_state.STATUS_APPROVED)\n\n # Check that the comment was added to the task state correctly\n\n self.assertEqual(task_state.comment, 'my comment')\n\n # Check that page edits made at the same time as the action have been saved\n page = Page.objects.get(id=self.page.id)\n self.assertEqual(page.get_latest_revision_as_page().title, \"This title was edited while approving\")\n\n def test_workflow_report(self):\n response = self.client.get(reverse('wagtailadmin_reports:workflow'))\n self.assertEqual(response.status_code, 200)\n self.assertContains(response, \"Hello world!\")\n self.assertContains(response, \"test_workflow\")\n self.assertContains(response, \"Sebastian Mitter\")\n self.assertContains(response, \"March 31, 2020\")\n\n response = self.client.get(reverse('wagtailadmin_reports:workflow_tasks'))\n self.assertEqual(response.status_code, 200)\n self.assertContains(response, \"Hello world!\")\n\n def test_workflow_report_filtered(self):\n # the moderator can review the task, so the workflow state should show up even when reports are filtered by reviewable\n response = self.client.get(reverse('wagtailadmin_reports:workflow'), {'reviewable': 'true'})\n self.assertEqual(response.status_code, 200)\n self.assertContains(response, \"Hello world!\")\n self.assertContains(response, \"test_workflow\")\n self.assertContains(response, \"Sebastian Mitter\")\n self.assertContains(response, \"March 31, 2020\")\n\n response = self.client.get(reverse('wagtailadmin_reports:workflow_tasks'), {'reviewable': 'true'})\n self.assertEqual(response.status_code, 200)\n self.assertContains(response, \"Hello world!\")\n\n # the submitter cannot review the task, so the workflow state shouldn't show up when reports are filtered by reviewable\n self.login(self.submitter)\n response = self.client.get(reverse('wagtailadmin_reports:workflow'), {'reviewable': 'true'})\n self.assertEqual(response.status_code, 200)\n self.assertNotContains(response, \"Hello world!\")\n self.assertNotContains(response, \"Sebastian Mitter\")\n self.assertNotContains(response, \"March 31, 2020\")\n\n response = self.client.get(reverse('wagtailadmin_reports:workflow_tasks'), {'reviewable': 'true'})\n self.assertEqual(response.status_code, 200)\n self.assertNotContains(response, \"Hello world!\")\n\n\nclass TestNotificationPreferences(TestCase, WagtailTestUtils):\n def setUp(self):\n delete_existing_workflows()\n self.submitter = self.create_user(\n username='submitter',\n email='submitter@email.com',\n password='password',\n )\n editors = Group.objects.get(name='Editors')\n editors.user_set.add(self.submitter)\n self.moderator = self.create_user(", "answers": [" username='moderator',"], "length": 2875, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "152f83f6-74d3-4df2-901f-c70408e4a469", "reasoning": "In the setUp method of TestNotificationPreferences, a moderator user is being created similarly to other user creations earlier in the file. The pattern is a multi-line call to self.create_user with username, email, and password arguments. The snippet ends right after the opening parenthesis, so the next line should be the first argument: the username assignment.", "reasoning_model_answer": "username='moderator',", "assistant_with_reasoning": "\nIn the setUp method of TestNotificationPreferences, a moderator user is being created similarly to other user creations earlier in the file. The pattern is a multi-line call to self.create_user with username, email, and password arguments. The snippet ends right after the opening parenthesis, so the next line should be the first argument: the username assignment.\n\nusername='moderator',", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.423, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 48004, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "username='moderator',", "score": 0.78, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/*\n * Copyright 2010-2020 Alfresco Software, Ltd.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n\npackage org.activiti.engine.test.api.task;\n\nimport static java.util.Arrays.asList;\nimport static java.util.Collections.emptyList;\nimport static java.util.Collections.emptyMap;\nimport static java.util.Collections.singletonList;\nimport static java.util.Collections.singletonMap;\nimport static org.assertj.core.api.Assertions.assertThat;\nimport static org.assertj.core.api.Assertions.assertThatExceptionOfType;\n\nimport java.text.SimpleDateFormat;\nimport java.util.Collections;\nimport java.util.Date;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport org.activiti.engine.ActivitiException;\nimport org.activiti.engine.ActivitiIllegalArgumentException;\nimport org.activiti.engine.ActivitiObjectNotFoundException;\nimport org.activiti.engine.ActivitiOptimisticLockingException;\nimport org.activiti.engine.ActivitiTaskAlreadyClaimedException;\nimport org.activiti.engine.history.HistoricActivityInstance;\nimport org.activiti.engine.history.HistoricDetail;\nimport org.activiti.engine.history.HistoricTaskInstance;\nimport org.activiti.engine.history.HistoricVariableUpdate;\nimport org.activiti.engine.impl.TaskServiceImpl;\nimport org.activiti.engine.impl.history.HistoryLevel;\nimport org.activiti.engine.impl.identity.Authentication;\nimport org.activiti.engine.impl.persistence.entity.CommentEntity;\nimport org.activiti.engine.impl.persistence.entity.HistoricDetailVariableInstanceUpdateEntity;\nimport org.activiti.engine.impl.test.PluggableActivitiTestCase;\nimport org.activiti.engine.runtime.ProcessInstance;\nimport org.activiti.engine.task.Attachment;\nimport org.activiti.engine.task.Comment;\nimport org.activiti.engine.task.DelegationState;\nimport org.activiti.engine.task.Event;\nimport org.activiti.engine.task.IdentityLink;\nimport org.activiti.engine.task.IdentityLinkType;\nimport org.activiti.engine.task.Task;\nimport org.activiti.engine.test.Deployment;\n\npublic class TaskServiceTest extends PluggableActivitiTestCase {\n\n public void testSaveTaskUpdate() throws Exception {\n\n SimpleDateFormat sdf = new SimpleDateFormat(\"dd/MM/yyyy hh:mm:ss\");\n Task task = taskService.newTask();\n task.setDescription(\"description\");\n task.setName(\"taskname\");\n task.setPriority(0);\n task.setAssignee(\"taskassignee\");\n task.setOwner(\"taskowner\");\n Date dueDate = sdf.parse(\"01/02/2003 04:05:06\");\n task.setDueDate(dueDate);\n taskService.saveTask(task);\n\n // Fetch the task again and update\n task = taskService.createTaskQuery().taskId(task.getId()).singleResult();\n assertThat(task.getDescription()).isEqualTo(\"description\");\n assertThat(task.getName()).isEqualTo(\"taskname\");\n assertThat(task.getAssignee()).isEqualTo(\"taskassignee\");\n assertThat(task.getOwner()).isEqualTo(\"taskowner\");\n assertThat(task.getDueDate()).isEqualTo(dueDate);\n assertThat(task.getPriority()).isEqualTo(0);\n\n task.setName(\"updatedtaskname\");\n task.setDescription(\"updateddescription\");\n task.setPriority(1);\n task.setAssignee(\"updatedassignee\");\n task.setOwner(\"updatedowner\");\n dueDate = sdf.parse(\"01/02/2003 04:05:06\");\n task.setDueDate(dueDate);\n taskService.saveTask(task);\n\n task = taskService.createTaskQuery().taskId(task.getId()).singleResult();\n assertThat(task.getName()).isEqualTo(\"updatedtaskname\");\n assertThat(task.getDescription()).isEqualTo(\"updateddescription\");\n assertThat(task.getAssignee()).isEqualTo(\"updatedassignee\");\n assertThat(task.getOwner()).isEqualTo(\"updatedowner\");\n assertThat(task.getDueDate()).isEqualTo(dueDate);\n assertThat(task.getPriority()).isEqualTo(1);\n\n if (processEngineConfiguration.getHistoryLevel().isAtLeast(HistoryLevel.AUDIT)) {\n HistoricTaskInstance historicTaskInstance = historyService.createHistoricTaskInstanceQuery().taskId(task.getId()).singleResult();\n assertThat(historicTaskInstance.getName()).isEqualTo(\"updatedtaskname\");\n assertThat(historicTaskInstance.getDescription()).isEqualTo(\"updateddescription\");\n assertThat(historicTaskInstance.getAssignee()).isEqualTo(\"updatedassignee\");\n assertThat(historicTaskInstance.getOwner()).isEqualTo(\"updatedowner\");\n assertThat(historicTaskInstance.getDueDate()).isEqualTo(dueDate);\n assertThat(historicTaskInstance.getPriority()).isEqualTo(1);\n }\n\n // Finally, delete task\n taskService.deleteTask(task.getId(), true);\n }\n\n public void testTaskOwner() {\n Task task = taskService.newTask();\n task.setOwner(\"johndoe\");\n taskService.saveTask(task);\n\n // Fetch the task again and update\n task = taskService.createTaskQuery().taskId(task.getId()).singleResult();\n assertThat(task.getOwner()).isEqualTo(\"johndoe\");\n\n task.setOwner(\"joesmoe\");\n taskService.saveTask(task);\n\n task = taskService.createTaskQuery().taskId(task.getId()).singleResult();\n assertThat(task.getOwner()).isEqualTo(\"joesmoe\");\n\n // Finally, delete task\n taskService.deleteTask(task.getId(), true);\n }\n\n public void testTaskComments() {\n if (processEngineConfiguration.getHistoryLevel().isAtLeast(HistoryLevel.ACTIVITY)) {\n Task task = taskService.newTask();\n task.setOwner(\"johndoe\");\n taskService.saveTask(task);\n String taskId = task.getId();\n\n Authentication.setAuthenticatedUserId(\"johndoe\");\n // Fetch the task again and update\n taskService\n .addComment(\n taskId,\n null,\n \"look at this \\n isn't this great? slkdjf sldkfjs ldkfjs ldkfjs ldkfj sldkfj sldkfj sldkjg laksfg sdfgsd;flgkj ksajdhf skjdfh ksjdhf skjdhf kalskjgh lskh dfialurhg kajsh dfuieqpgkja rzvkfnjviuqerhogiuvysbegkjz lkhf ais liasduh flaisduh ajiasudh vaisudhv nsfd\");\n Comment comment = taskService.getTaskComments(taskId).get(0);\n assertThat(comment.getUserId()).isEqualTo(\"johndoe\");\n assertThat(comment.getTaskId()).isEqualTo(taskId);\n assertThat(comment.getProcessInstanceId()).isNull();\n assertThat(((Event) comment).getMessage())\n .isEqualTo(\"look at this isn't this great? slkdjf sldkfjs ldkfjs ldkfjs ldkfj sldkfj sldkfj sldkjg laksfg sdfgsd;flgkj ksajdhf skjdfh ksjdhf skjdhf kalskjgh lskh dfialurhg ...\");\n assertThat(comment.getFullMessage())\n .isEqualTo(\"look at this \\n isn't this great? slkdjf sldkfjs ldkfjs ldkfjs ldkfj sldkfj sldkfj sldkjg laksfg sdfgsd;flgkj ksajdhf skjdfh ksjdhf skjdhf kalskjgh lskh dfialurhg kajsh dfuieqpgkja rzvkfnjviuqerhogiuvysbegkjz lkhf ais liasduh flaisduh ajiasudh vaisudhv nsfd\");\n assertThat(comment.getTime()).isNotNull();\n\n // Finally, delete task\n taskService.deleteTask(taskId, true);\n }\n }\n\n public void testCustomTaskComments() {\n if (processEngineConfiguration.getHistoryLevel().isAtLeast(HistoryLevel.ACTIVITY)) {\n Task task = taskService.newTask();\n task.setOwner(\"johndoe\");\n taskService.saveTask(task);\n String taskId = task.getId();\n\n Authentication.setAuthenticatedUserId(\"johndoe\");\n String customType1 = \"Type1\";\n String customType2 = \"Type2\";\n\n Comment comment = taskService.addComment(taskId,\n null,\n \"This is a regular comment\");\n Comment customComment1 = taskService.addComment(taskId,\n null,\n customType1,\n \"This is a custom comment of type Type1\");\n Comment customComment2 = taskService.addComment(taskId,\n null,\n customType1,\n \"This is another Type1 comment\");\n Comment customComment3 = taskService.addComment(taskId,\n null,\n customType2,\n \"This is another custom comment. Type2 this time!\");\n\n assertThat(comment.getType()).isEqualTo(CommentEntity.TYPE_COMMENT);\n assertThat(customComment1.getType()).isEqualTo(customType1);\n assertThat(customComment3.getType()).isEqualTo(customType2);\n\n assertThat(taskService.getComment(comment.getId())).isNotNull();\n assertThat(taskService.getComment(customComment1.getId())).isNotNull();\n\n List regularComments = taskService.getTaskComments(taskId);\n assertThat(regularComments).hasSize(1);\n assertThat(regularComments.get(0).getFullMessage()).isEqualTo(\"This is a regular comment\");\n\n List allComments = taskService.getTaskEvents(taskId);\n assertThat(allComments).hasSize(4);\n\n List type2Comments = taskService.getCommentsByType(customType2);\n assertThat(type2Comments).hasSize(1);\n assertThat(type2Comments.get(0).getFullMessage()).isEqualTo(\"This is another custom comment. Type2 this time!\");\n\n List taskTypeComments = taskService.getTaskComments(taskId, customType1);\n assertThat(taskTypeComments).hasSize(2);\n\n // Clean up\n taskService.deleteTask(taskId, true);\n }\n }\n\n public void testTaskAttachments() {\n if (processEngineConfiguration.getHistoryLevel().isAtLeast(HistoryLevel.ACTIVITY)) {\n Task task = taskService.newTask();\n task.setOwner(\"johndoe\");\n taskService.saveTask(task);\n String taskId = task.getId();\n Authentication.setAuthenticatedUserId(\"johndoe\");\n // Fetch the task again and update\n taskService.createAttachment(\"web page\",\n taskId,\n null,\n \"weatherforcast\",\n \"temperatures and more\",\n \"http://weather.com\");\n Attachment attachment = taskService.getTaskAttachments(taskId).get(0);\n assertThat(attachment.getName()).isEqualTo(\"weatherforcast\");\n assertThat(attachment.getDescription()).isEqualTo(\"temperatures and more\");\n assertThat(attachment.getType()).isEqualTo(\"web page\");\n assertThat(attachment.getTaskId()).isEqualTo(taskId);\n assertThat(attachment.getProcessInstanceId()).isNull();\n assertThat(attachment.getUrl()).isEqualTo(\"http://weather.com\");\n assertThat(taskService.getAttachmentContent(attachment.getId())).isNull();\n\n // Finally, clean up\n taskService.deleteTask(taskId);\n\n assertThat(taskService.getTaskComments(taskId)).hasSize(0);\n assertThat(historyService.createHistoricTaskInstanceQuery().taskId(taskId).list()).hasSize(1);\n\n taskService.deleteTask(taskId,\n true);\n }\n }\n\n public void testSaveTaskAttachment() {\n if (processEngineConfiguration.getHistoryLevel().isAtLeast(HistoryLevel.ACTIVITY)) {\n Task task = taskService.newTask();\n task.setOwner(\"johndoe\");\n taskService.saveTask(task);\n String taskId = task.getId();\n Authentication.setAuthenticatedUserId(\"johndoe\");\n\n // Fetch attachment and update its name\n taskService.createAttachment(\"web page\",\n taskId,\n null,\n \"weatherforcast\",\n \"temperatures and more\",\n \"http://weather.com\");\n Attachment attachment = taskService.getTaskAttachments(taskId).get(0);\n attachment.setName(\"UpdatedName\");\n taskService.saveAttachment(attachment);\n\n // Refetch and verify\n attachment = taskService.getTaskAttachments(taskId).get(0);\n assertThat(attachment.getName()).isEqualTo(\"UpdatedName\");\n\n // Finally, clean up\n taskService.deleteTask(taskId);\n\n assertThat(taskService.getTaskComments(taskId)).hasSize(0);\n assertThat(historyService.createHistoricTaskInstanceQuery().taskId(taskId).list()).hasSize(1);\n\n taskService.deleteTask(taskId,\n true);\n }\n }\n\n @Deployment(resources = {\"org/activiti/engine/test/api/oneTaskProcess.bpmn20.xml\"})\n public void testTaskAttachmentWithProcessInstanceId() {\n if (processEngineConfiguration.getHistoryLevel().isAtLeast(HistoryLevel.ACTIVITY)) {\n\n ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(\"oneTaskProcess\");\n\n String processInstanceId = processInstance.getId();\n taskService.createAttachment(\"web page\",\n null,\n processInstanceId,\n \"weatherforcast\",\n \"temperatures and more\",\n \"http://weather.com\");\n Attachment attachment = taskService.getProcessInstanceAttachments(processInstanceId).get(0);\n assertThat(attachment.getName()).isEqualTo(\"weatherforcast\");\n assertThat(attachment.getDescription()).isEqualTo(\"temperatures and more\");\n assertThat(attachment.getType()).isEqualTo(\"web page\");\n assertThat(attachment.getProcessInstanceId()).isEqualTo(processInstanceId);\n assertThat(attachment.getTaskId()).isNull();\n assertThat(attachment.getUrl()).isEqualTo(\"http://weather.com\");\n assertThat(taskService.getAttachmentContent(attachment.getId())).isNull();\n\n // Finally, clean up\n taskService.deleteAttachment(attachment.getId());\n\n // TODO: Bad API design. Need to fix attachment/comment properly\n ((TaskServiceImpl) taskService).deleteComments(null,\n processInstanceId);\n }\n }\n\n @Deployment(resources = {\"org/activiti/engine/test/api/oneTaskProcess.bpmn20.xml\"})\n public void testMultipleProcessesStarted() {\n\n // Start a few process instances\n for (int i = 0; i < 20; i++) {\n processEngine.getRuntimeService().startProcessInstanceByKey(\"oneTaskProcess\");\n }\n\n // See if there are tasks for kermit\n List tasks = processEngine.getTaskService().createTaskQuery().list();\n assertThat(tasks).hasSize(20);\n }\n\n public void testTaskDelegation() {\n Task task = taskService.newTask();\n task.setOwner(\"johndoe\");\n taskService.saveTask(task);\n taskService.delegateTask(task.getId(), \"joesmoe\");\n String taskId = task.getId();\n\n task = taskService.createTaskQuery().taskId(taskId).singleResult();\n assertThat(task.getOwner()).isEqualTo(\"johndoe\");\n assertThat(task.getAssignee()).isEqualTo(\"joesmoe\");\n assertThat(task.getDelegationState()).isEqualTo(DelegationState.PENDING);\n\n // try to complete (should fail)\n Task exceptionTask = task;\n assertThatExceptionOfType(ActivitiException.class)\n .isThrownBy(() -> taskService.complete(exceptionTask.getId()));\n\n taskService.resolveTask(taskId);\n task = taskService.createTaskQuery().taskId(taskId).singleResult();\n assertThat(task.getOwner()).isEqualTo(\"johndoe\");\n assertThat(task.getAssignee()).isEqualTo(\"johndoe\");\n assertThat(task.getDelegationState()).isEqualTo(DelegationState.RESOLVED);\n\n task.setAssignee(null);\n task.setDelegationState(null);\n taskService.saveTask(task);\n task = taskService.createTaskQuery().taskId(taskId).singleResult();\n assertThat(task.getOwner()).isEqualTo(\"johndoe\");\n assertThat(task.getAssignee()).isNull();\n assertThat(task.getDelegationState()).isNull();\n\n task.setAssignee(\"jackblack\");\n task.setDelegationState(DelegationState.RESOLVED);\n taskService.saveTask(task);\n task = taskService.createTaskQuery().taskId(taskId).singleResult();\n assertThat(task.getOwner()).isEqualTo(\"johndoe\");\n assertThat(task.getAssignee()).isEqualTo(\"jackblack\");\n assertThat(task.getDelegationState()).isEqualTo(DelegationState.RESOLVED);\n\n // Finally, delete task\n taskService.deleteTask(taskId,\n true);\n }\n\n public void testTaskDelegationThroughServiceCall() {\n Task task = taskService.newTask();\n task.setOwner(\"johndoe\");\n taskService.saveTask(task);\n String taskId = task.getId();\n\n // Fetch the task again and update\n task = taskService.createTaskQuery().taskId(taskId).singleResult();\n\n taskService.delegateTask(task.getId(),\n \"joesmoe\");\n\n task = taskService.createTaskQuery().taskId(taskId).singleResult();\n assertThat(task.getOwner()).isEqualTo(\"johndoe\");\n assertThat(task.getAssignee()).isEqualTo(\"joesmoe\");\n assertThat(task.getDelegationState()).isEqualTo(DelegationState.PENDING);\n\n taskService.resolveTask(taskId);\n\n task = taskService.createTaskQuery().taskId(taskId).singleResult();\n assertThat(task.getOwner()).isEqualTo(\"johndoe\");\n assertThat(task.getAssignee()).isEqualTo(\"johndoe\");\n assertThat(task.getDelegationState()).isEqualTo(DelegationState.RESOLVED);\n\n // Finally, delete task\n taskService.deleteTask(taskId,\n true);\n }\n\n public void testTaskAssignee() {\n Task task = taskService.newTask();\n task.setAssignee(\"johndoe\");\n taskService.saveTask(task);\n\n // Fetch the task again and update\n task = taskService.createTaskQuery().taskId(task.getId()).singleResult();\n assertThat(task.getAssignee()).isEqualTo(\"johndoe\");\n\n task.setAssignee(\"joesmoe\");\n taskService.saveTask(task);\n\n task = taskService.createTaskQuery().taskId(task.getId()).singleResult();\n assertThat(task.getAssignee()).isEqualTo(\"joesmoe\");\n\n // Finally, delete task\n taskService.deleteTask(task.getId(),\n true);\n }\n\n public void testSaveTaskNullTask() {\n assertThatExceptionOfType(ActivitiIllegalArgumentException.class)\n .isThrownBy(() -> taskService.saveTask(null))\n .withMessageContaining(\"task is null\");\n }\n\n public void testDeleteTaskNullTaskId() {\n assertThatExceptionOfType(ActivitiIllegalArgumentException.class)\n .isThrownBy(() -> taskService.deleteTask(null));\n }\n\n public void testDeleteTaskUnexistingTaskId() {\n // Deleting unexisting task should be silently ignored\n taskService.deleteTask(\"unexistingtaskid\");\n }\n\n public void testDeleteTasksNullTaskIds() {\n assertThatExceptionOfType(ActivitiIllegalArgumentException.class)\n .isThrownBy(() -> taskService.deleteTasks(null));\n }\n\n public void testDeleteTasksTaskIdsUnexistingTaskId() {\n\n Task existingTask = taskService.newTask();\n taskService.saveTask(existingTask);\n\n // The unexisting taskId's should be silently ignored. Existing task should have been deleted.\n taskService.deleteTasks(asList(\"unexistingtaskid1\", existingTask.getId()), true);\n\n existingTask = taskService.createTaskQuery().taskId(existingTask.getId()).singleResult();\n assertThat(existingTask).isNull();\n }\n\n public void testDeleteTaskIdentityLink() {\n Task task = null;\n try {\n task = taskService.newTask();\n task.setName(\"test\");\n taskService.saveTask(task);\n\n taskService.addCandidateGroup(task.getId(),\n \"sales\");\n taskService.addCandidateUser(task.getId(),\n \"kermit\");\n\n assertThat(taskService.createTaskQuery().taskCandidateGroup(\"sales\").singleResult()).isNotNull();\n assertThat(taskService.createTaskQuery().taskCandidateUser(\"kermit\").singleResult()).isNotNull();\n\n // Delete identity link for group\n taskService.deleteGroupIdentityLink(task.getId(),\n \"sales\",\n \"candidate\");\n\n // Link should be removed\n assertThat(taskService.createTaskQuery().taskCandidateGroup(\"sales\").singleResult()).isNull();\n\n // User link should remain unaffected\n assertThat(taskService.createTaskQuery().taskCandidateUser(\"kermit\").singleResult()).isNotNull();\n } finally {\n // Adhoc task not part of deployment, cleanup\n if (task != null && task.getId() != null) {\n taskService.deleteTask(task.getId());\n if (processEngineConfiguration.getHistoryLevel().isAtLeast(HistoryLevel.AUDIT)) {\n historyService.deleteHistoricTaskInstance(task.getId());\n }\n }\n }\n }\n\n public void testClaimNullArguments() {\n assertThatExceptionOfType(ActivitiIllegalArgumentException.class)\n .isThrownBy(() -> taskService.claim(null, \"userid\"))\n .withMessageContaining(\"taskId is null\");\n }\n\n public void testClaimUnexistingTaskId() {\n assertThatExceptionOfType(ActivitiObjectNotFoundException.class)\n .isThrownBy(() -> taskService.claim(\"unexistingtaskid\", \"user\"))\n .withMessageContaining(\"Cannot find task with id unexistingtaskid\")\n .satisfies(ae -> assertThat(ae.getObjectClass()).isEqualTo(Task.class));\n }\n\n public void testClaimAlreadyClaimedTaskByOtherUser() {\n Task task = taskService.newTask();\n taskService.saveTask(task);\n\n // Claim task the first time\n taskService.claim(task.getId(), \"firstuser\");\n\n assertThatExceptionOfType(ActivitiTaskAlreadyClaimedException.class)\n .isThrownBy(() -> taskService.claim(task.getId(), \"seconduser\"))\n .withMessageContaining(\"Task '\" + task.getId() + \"' is already claimed by someone else.\");\n\n taskService.deleteTask(task.getId(), true);\n }\n\n public void testClaimAlreadyClaimedTaskBySameUser() {\n Task task = taskService.newTask();\n taskService.saveTask(task);\n\n // Claim task the first time\n taskService.claim(task.getId(), \"user\");\n task = taskService.createTaskQuery().taskId(task.getId()).singleResult();\n\n // Claim the task again with the same user. No exception should be thrown\n taskService.claim(task.getId(), \"user\");\n\n taskService.deleteTask(task.getId(), true);\n }\n\n public void testUnClaimTask() {\n Task task = taskService.newTask();\n taskService.saveTask(task);\n\n // Claim task the first time\n taskService.claim(task.getId(), \"user\");\n task = taskService.createTaskQuery().taskId(task.getId()).singleResult();\n assertThat(task.getAssignee()).isEqualTo(\"user\");\n\n // Unclaim the task\n taskService.unclaim(task.getId());\n\n task = taskService.createTaskQuery().taskId(task.getId()).singleResult();\n assertThat(task.getAssignee()).isNull();\n\n taskService.deleteTask(task.getId(), true);\n }\n\n public void testCompleteTaskNullTaskId() {\n assertThatExceptionOfType(ActivitiIllegalArgumentException.class)\n .isThrownBy(() -> taskService.complete(null))\n .withMessageContaining(\"taskId is null\");\n }\n\n public void testCompleteTaskUnexistingTaskId() {\n assertThatExceptionOfType(ActivitiObjectNotFoundException.class)\n .isThrownBy(() -> taskService.complete(\"unexistingtask\"))\n .withMessageContaining(\"Cannot find task with id unexistingtask\")\n .satisfies(ae -> assertThat(ae.getObjectClass()).isEqualTo(Task.class));\n }\n\n public void testCompleteTaskWithParametersNullTaskId() {\n assertThatExceptionOfType(ActivitiIllegalArgumentException.class)\n .isThrownBy(() -> taskService.complete(null))\n .withMessageContaining(\"taskId is null\");\n }\n\n public void testCompleteTaskWithParametersUnexistingTaskId() {\n assertThatExceptionOfType(ActivitiObjectNotFoundException.class)\n .isThrownBy(() -> taskService.complete(\"unexistingtask\"))\n .withMessageContaining(\"Cannot find task with id unexistingtask\")\n .satisfies(ae -> assertThat(ae.getObjectClass()).isEqualTo(Task.class));\n }\n\n public void testCompleteTaskWithParametersNullParameters() {\n Task task = taskService.newTask();\n taskService.saveTask(task);\n\n String taskId = task.getId();\n taskService.complete(taskId, null);\n\n if (processEngineConfiguration.getHistoryLevel().isAtLeast(HistoryLevel.AUDIT)) {\n historyService.deleteHistoricTaskInstance(taskId);\n }\n\n // Fetch the task again\n task = taskService.createTaskQuery().taskId(taskId).singleResult();\n assertThat(task).isNull();\n }\n\n @SuppressWarnings(\"unchecked\")\n public void testCompleteTaskWithParametersEmptyParameters() {\n Task task = taskService.newTask();\n taskService.saveTask(task);\n\n String taskId = task.getId();\n taskService.complete(taskId,\n Collections.EMPTY_MAP);\n\n if (processEngineConfiguration.getHistoryLevel().isAtLeast(HistoryLevel.AUDIT)) {\n historyService.deleteHistoricTaskInstance(taskId);\n }\n\n // Fetch the task again\n task = taskService.createTaskQuery().taskId(taskId).singleResult();\n assertThat(task).isNull();\n }\n\n @Deployment(resources = {\"org/activiti/engine/test/api/twoTasksProcess.bpmn20.xml\"})\n public void testCompleteWithParametersTask() {\n ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(\"twoTasksProcess\");\n\n // Fetch first task\n Task task = taskService.createTaskQuery().singleResult();\n assertThat(task.getName()).isEqualTo(\"First task\");\n\n // Complete first task\n Map taskParams = new HashMap();\n taskParams.put(\"myParam\",\n \"myValue\");\n taskService.complete(task.getId(),\n taskParams);\n\n // Fetch second task\n task = taskService.createTaskQuery().singleResult();\n assertThat(task.getName()).isEqualTo(\"Second task\");\n\n // Verify task parameters set on execution\n Map variables = runtimeService.getVariables(processInstance.getId());\n assertThat(variables).hasSize(1);\n assertThat(variables.get(\"myParam\")).isEqualTo(\"myValue\");\n }\n\n @Deployment(resources = {\"org/activiti/engine/test/api/twoTasksProcess.bpmn20.xml\"})\n public void testCompleteWithParametersTask2() {\n ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(\"twoTasksProcess\");\n\n // Fetch first task\n Task task = taskService.createTaskQuery().singleResult();\n assertThat(task.getName()).isEqualTo(\"First task\");\n\n // Complete first task\n Map taskParams = new HashMap();\n taskParams.put(\"myParam\", \"myValue\");\n taskService.complete(task.getId(), taskParams, false); // Only\n // difference with previous test\n\n // Fetch second task\n task = taskService.createTaskQuery().singleResult();\n assertThat(task.getName()).isEqualTo(\"Second task\");\n\n // Verify task parameters set on execution\n Map variables = runtimeService.getVariables(processInstance.getId());\n assertThat(variables).hasSize(1);\n assertThat(variables.get(\"myParam\")).isEqualTo(\"myValue\");\n }\n\n @Deployment\n public void testCompleteWithTaskLocalParameters() {\n ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(\"testTaskLocalVars\");\n\n // Fetch first task\n Task task = taskService.createTaskQuery().singleResult();\n\n // Complete first task\n Map taskParams = new HashMap();\n taskParams.put(\"a\", 1);\n taskParams.put(\"b\", 1);\n taskService.complete(task.getId(), taskParams, true);\n\n // Verify vars are not stored process instance wide\n assertThat(runtimeService.getVariable(processInstance.getId(), \"a\")).isNull();\n assertThat(runtimeService.getVariable(processInstance.getId(), \"b\")).isNull();\n\n // verify script listener has done its job\n assertThat(runtimeService.getVariable(processInstance.getId(), \"sum\")).isEqualTo(Integer.valueOf(2));\n\n // Fetch second task\n taskService.createTaskQuery().singleResult();\n }\n\n @Deployment(resources = {\"org/activiti/engine/test/api/oneTaskWithFormKeyProcess.bpmn20.xml\"})\n public void testCompleteTaskWithFormKey() {\n ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(\"oneTaskWithFormProcess\");\n\n // Fetch task\n Task task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();\n assertThat(task.getName()).isEqualTo(\"my task\");\n assertThat(task.getFormKey()).isEqualTo(\"myFormKey\");\n assertThat(task.getAssignee()).isEqualTo(\"myAssignee\");\n assertThat(task.getOwner()).isEqualTo(\"myOwner\");\n assertThat(task.getCategory()).isEqualTo(\"myCategory\");\n assertThat(task.getPriority()).isEqualTo(60);\n assertThat(task.getDueDate()).isNotNull();\n\n // Complete task\n taskService.complete(task.getId());\n\n if (processEngineConfiguration.getHistoryLevel().isAtLeast(HistoryLevel.ACTIVITY)) {\n HistoricTaskInstance historicTask = historyService.createHistoricTaskInstanceQuery().taskId(task.getId()).singleResult();\n assertThat(historicTask.getName()).isEqualTo(\"my task\");\n assertThat(historicTask.getFormKey()).isEqualTo(\"myFormKey\");\n assertThat(historicTask.getAssignee()).isEqualTo(\"myAssignee\");\n assertThat(historicTask.getOwner()).isEqualTo(\"myOwner\");\n assertThat(historicTask.getCategory()).isEqualTo(\"myCategory\");\n assertThat(historicTask.getPriority()).isEqualTo(60);\n assertThat(historicTask.getDueDate()).isNotNull();\n }\n }\n\n public void testSetAssignee() {\n\n Task task = taskService.newTask();\n assertThat(task.getAssignee()).isNull();\n taskService.saveTask(task);\n\n // Set assignee\n taskService.setAssignee(task.getId(), \"user\");\n\n // Fetch task again\n task = taskService.createTaskQuery().taskId(task.getId()).singleResult();\n assertThat(task.getAssignee()).isEqualTo(\"user\");\n\n // Set assignee to null\n taskService.setAssignee(task.getId(), null);\n\n taskService.deleteTask(task.getId(), true);\n }\n\n public void testSetAssigneeNullTaskId() {\n assertThatExceptionOfType(ActivitiIllegalArgumentException.class)\n .isThrownBy(() -> taskService.setAssignee(null, \"userId\"))\n .withMessageContaining(\"taskId is null\");\n }\n\n public void testSetAssigneeUnexistingTask() {\n assertThatExceptionOfType(ActivitiObjectNotFoundException.class)\n .isThrownBy(() -> taskService.setAssignee(\"unexistingTaskId\", \"user\"))\n .withMessageContaining(\"Cannot find task with id unexistingTaskId\")\n .satisfies(ae -> assertThat(ae.getObjectClass()).isEqualTo(Task.class));\n }\n\n public void testAddCandidateUserDuplicate() {\n // Check behavior when adding the same user twice as candidate\n\n Task task = taskService.newTask();\n taskService.saveTask(task);\n\n taskService.addCandidateUser(task.getId(), \"user\");\n\n // Add as candidate the second time\n taskService.addCandidateUser(task.getId(), \"user\");\n\n taskService.deleteTask(task.getId(), true);\n }\n\n public void testAddCandidateUserNullTaskId() {\n assertThatExceptionOfType(ActivitiIllegalArgumentException.class)\n .isThrownBy(() -> taskService.addCandidateUser(null, \"userId\"))\n .withMessageContaining(\"taskId is null\");\n }\n\n public void testAddCandidateUserNullUserId() {\n assertThatExceptionOfType(ActivitiIllegalArgumentException.class)\n .isThrownBy(() -> taskService.addCandidateUser(\"taskId\", null))\n .withMessageContaining(\"identityId is null\");\n }\n\n public void testAddCandidateUserUnexistingTask() {\n assertThatExceptionOfType(ActivitiObjectNotFoundException.class)\n .isThrownBy(() -> taskService.addCandidateUser(\"unexistingTaskId\", \"user\"))\n .withMessageContaining(\"Cannot find task with id unexistingTaskId\")\n .satisfies(ae -> assertThat(ae.getObjectClass()).isEqualTo(Task.class));\n }\n\n public void testAddCandidateGroupNullTaskId() {\n assertThatExceptionOfType(ActivitiIllegalArgumentException.class)\n .isThrownBy(() -> taskService.addCandidateGroup(null, \"groupId\"))\n .withMessageContaining(\"taskId is null\");\n }\n\n public void testAddCandidateGroupNullGroupId() {\n assertThatExceptionOfType(ActivitiIllegalArgumentException.class)\n .isThrownBy(() -> taskService.addCandidateGroup(\"taskId\", null))\n .withMessageContaining(\"identityId is null\");\n }\n\n public void testAddCandidateGroupUnexistingTask() {\n assertThatExceptionOfType(ActivitiObjectNotFoundException.class)\n .isThrownBy(() -> taskService.addCandidateGroup(\"unexistingTaskId\", \"group\"))\n .withMessageContaining(\"Cannot find task with id unexistingTaskId\")\n .satisfies(ae -> assertThat(ae.getObjectClass()).isEqualTo(Task.class));\n }\n\n public void testAddGroupIdentityLinkNullTaskId() {\n assertThatExceptionOfType(ActivitiIllegalArgumentException.class)\n .isThrownBy(() -> taskService.addGroupIdentityLink(null, \"groupId\", IdentityLinkType.CANDIDATE))\n .withMessageContaining(\"taskId is null\");\n }\n\n public void testAddGroupIdentityLinkNullUserId() {\n assertThatExceptionOfType(ActivitiIllegalArgumentException.class)\n .isThrownBy(() -> taskService.addGroupIdentityLink(\"taskId\", null, IdentityLinkType.CANDIDATE))\n .withMessageContaining(\"identityId is null\");\n }\n\n public void testAddGroupIdentityLinkUnexistingTask() {\n assertThatExceptionOfType(ActivitiObjectNotFoundException.class)\n .isThrownBy(() -> taskService.addGroupIdentityLink(\"unexistingTaskId\", \"user\", IdentityLinkType.CANDIDATE))\n .withMessageContaining(\"Cannot find task with id unexistingTaskId\")\n .satisfies(ae -> assertThat(ae.getObjectClass()).isEqualTo(Task.class));\n }\n\n public void testAddUserIdentityLinkNullTaskId() {\n assertThatExceptionOfType(ActivitiIllegalArgumentException.class)\n .isThrownBy(() -> taskService.addUserIdentityLink(null, \"userId\", IdentityLinkType.CANDIDATE))\n .withMessageContaining(\"taskId is null\");\n }\n\n public void testAddUserIdentityLinkNullUserId() {\n assertThatExceptionOfType(ActivitiIllegalArgumentException.class)\n .isThrownBy(() -> taskService.addUserIdentityLink(\"taskId\", null, IdentityLinkType.CANDIDATE))\n .withMessageContaining(\"identityId is null\");\n }\n\n public void testAddUserIdentityLinkUnexistingTask() {\n assertThatExceptionOfType(ActivitiObjectNotFoundException.class)\n .isThrownBy(() -> taskService.addUserIdentityLink(\"unexistingTaskId\", \"user\", IdentityLinkType.CANDIDATE))\n .withMessageContaining(\"Cannot find task with id unexistingTaskId\")\n .satisfies(ae -> assertThat(ae.getObjectClass()).isEqualTo(Task.class));\n }\n\n public void testGetIdentityLinksWithCandidateUser() {\n Task task = taskService.newTask();\n taskService.saveTask(task);\n String taskId = task.getId();\n\n taskService.addCandidateUser(taskId, \"kermit\");\n List identityLinks = taskService.getIdentityLinksForTask(taskId);\n assertThat(identityLinks).hasSize(1);\n assertThat(identityLinks.get(0).getUserId()).isEqualTo(\"kermit\");\n assertThat(identityLinks.get(0).getGroupId()).isNull();\n assertThat(identityLinks.get(0).getType()).isEqualTo(IdentityLinkType.CANDIDATE);\n\n // cleanup\n taskService.deleteTask(taskId, true);\n }\n\n public void testGetIdentityLinksWithCandidateGroup() {\n Task task = taskService.newTask();\n taskService.saveTask(task);\n String taskId = task.getId();\n\n taskService.addCandidateGroup(taskId,\n \"muppets\");\n List identityLinks = taskService.getIdentityLinksForTask(taskId);\n assertThat(identityLinks).hasSize(1);\n assertThat(identityLinks.get(0).getGroupId()).isEqualTo(\"muppets\");\n assertThat(identityLinks.get(0).getUserId()).isNull();\n assertThat(identityLinks.get(0).getType()).isEqualTo(IdentityLinkType.CANDIDATE);\n\n // cleanup\n taskService.deleteTask(taskId,\n true);\n }\n\n public void testGetIdentityLinksWithAssignee() {\n Task task = taskService.newTask();\n taskService.saveTask(task);\n String taskId = task.getId();\n\n taskService.claim(taskId,\n \"kermit\");\n List identityLinks = taskService.getIdentityLinksForTask(taskId);\n assertThat(identityLinks).hasSize(1);\n assertThat(identityLinks.get(0).getUserId()).isEqualTo(\"kermit\");\n assertThat(identityLinks.get(0).getGroupId()).isNull();\n assertThat(identityLinks.get(0).getType()).isEqualTo(IdentityLinkType.ASSIGNEE);\n\n // cleanup\n taskService.deleteTask(taskId,\n true);\n }\n\n public void testGetIdentityLinksWithNonExistingAssignee() {\n Task task = taskService.newTask();\n taskService.saveTask(task);\n String taskId = task.getId();\n\n taskService.claim(taskId,\n \"nonExistingAssignee\");\n List identityLinks = taskService.getIdentityLinksForTask(taskId);\n assertThat(identityLinks).hasSize(1);\n assertThat(identityLinks.get(0).getUserId()).isEqualTo(\"nonExistingAssignee\");\n assertThat(identityLinks.get(0).getGroupId()).isNull();\n assertThat(identityLinks.get(0).getType()).isEqualTo(IdentityLinkType.ASSIGNEE);\n\n // cleanup\n taskService.deleteTask(taskId,\n true);\n }\n\n public void testGetIdentityLinksWithOwner() {\n Task task = taskService.newTask();\n taskService.saveTask(task);\n String taskId = task.getId();\n\n taskService.claim(taskId,\n \"kermit\");\n taskService.delegateTask(taskId,\n \"fozzie\");\n\n List identityLinks = taskService.getIdentityLinksForTask(taskId);\n assertThat(identityLinks).hasSize(2);\n\n IdentityLink assignee = identityLinks.get(0);\n assertThat(assignee.getUserId()).isEqualTo(\"fozzie\");\n assertThat(assignee.getGroupId()).isNull();\n assertThat(assignee.getType()).isEqualTo(IdentityLinkType.ASSIGNEE);\n\n IdentityLink owner = identityLinks.get(1);\n assertThat(owner.getUserId()).isEqualTo(\"kermit\");\n assertThat(owner.getGroupId()).isNull();\n assertThat(owner.getType()).isEqualTo(IdentityLinkType.OWNER);\n\n // cleanup\n taskService.deleteTask(taskId,\n true);\n }\n\n public void testGetIdentityLinksWithNonExistingOwner() {\n Task task = taskService.newTask();\n taskService.saveTask(task);\n String taskId = task.getId();\n\n taskService.claim(taskId,\n \"nonExistingOwner\");\n taskService.delegateTask(taskId,\n \"nonExistingAssignee\");\n List identityLinks = taskService.getIdentityLinksForTask(taskId);\n assertThat(identityLinks).hasSize(2);\n\n IdentityLink assignee = identityLinks.get(0);\n assertThat(assignee.getUserId()).isEqualTo(\"nonExistingAssignee\");\n assertThat(assignee.getGroupId()).isNull();\n assertThat(assignee.getType()).isEqualTo(IdentityLinkType.ASSIGNEE);\n\n IdentityLink owner = identityLinks.get(1);\n assertThat(owner.getUserId()).isEqualTo(\"nonExistingOwner\");\n assertThat(owner.getGroupId()).isNull();\n assertThat(owner.getType()).isEqualTo(IdentityLinkType.OWNER);\n\n // cleanup\n taskService.deleteTask(taskId,\n true);\n }\n\n public void testSetPriority() {\n Task task = taskService.newTask();\n taskService.saveTask(task);\n\n taskService.setPriority(task.getId(),\n 12345);\n\n // Fetch task again to check if the priority is set\n task = taskService.createTaskQuery().taskId(task.getId()).singleResult();\n assertThat(task.getPriority()).isEqualTo(12345);\n\n taskService.deleteTask(task.getId(),\n true);\n }\n\n public void testSetPriorityUnexistingTaskId() {\n assertThatExceptionOfType(ActivitiObjectNotFoundException.class)\n .isThrownBy(() -> taskService.setPriority(\"unexistingtask\", 12345))\n .withMessageContaining(\"Cannot find task with id unexistingtask\")\n .satisfies(ae -> assertThat(ae.getObjectClass()).isEqualTo(Task.class));\n }\n\n public void testSetPriorityNullTaskId() {\n assertThatExceptionOfType(ActivitiIllegalArgumentException.class)\n .isThrownBy(() -> taskService.setPriority(null, 12345))\n .withMessageContaining(\"taskId is null\");\n }\n\n public void testSetDueDate() {\n Task task = taskService.newTask();\n taskService.saveTask(task);\n\n // Set the due date to a non-null value\n Date now = new Date();\n taskService.setDueDate(task.getId(),\n now);\n\n // Fetch task to check if the due date was persisted\n task = taskService.createTaskQuery().taskId(task.getId()).singleResult();\n assertThat(task.getDueDate()).isNotNull();\n\n // Set the due date to null\n taskService.setDueDate(task.getId(),\n null);\n\n // Re-fetch the task to make sure the due date was set to null\n task = taskService.createTaskQuery().taskId(task.getId()).singleResult();\n assertThat(task.getDueDate()).isNull();\n\n taskService.deleteTask(task.getId(),\n true);\n }\n\n public void testSetDueDateUnexistingTaskId() {\n assertThatExceptionOfType(ActivitiException.class)\n .isThrownBy(() -> taskService.setDueDate(\"unexistingtask\", new Date()))\n .withMessageContaining(\"Cannot find task with id unexistingtask\");\n }\n\n public void testSetDueDateNullTaskId() {\n assertThatExceptionOfType(ActivitiException.class)\n .isThrownBy(() -> taskService.setDueDate(null, new Date()))\n .withMessageContaining(\"taskId is null\");\n }\n\n /**\n * @see https://activiti.atlassian.net/browse/ACT-1059\n */\n public void testSetDelegationState() {\n Task task = taskService.newTask();\n task.setOwner(\"wuzh\");\n taskService.saveTask(task);\n taskService.delegateTask(task.getId(),\n \"other\");\n String taskId = task.getId();\n\n task = taskService.createTaskQuery().taskId(taskId).singleResult();\n assertThat(task.getOwner()).isEqualTo(\"wuzh\");\n assertThat(task.getAssignee()).isEqualTo(\"other\");\n assertThat(task.getDelegationState()).isEqualTo(DelegationState.PENDING);\n\n task.setDelegationState(DelegationState.RESOLVED);\n taskService.saveTask(task);\n\n task = taskService.createTaskQuery().taskId(taskId).singleResult();\n assertThat(task.getOwner()).isEqualTo(\"wuzh\");\n assertThat(task.getAssignee()).isEqualTo(\"other\");\n assertThat(task.getDelegationState()).isEqualTo(DelegationState.RESOLVED);\n\n taskService.deleteTask(taskId,\n true);\n }\n\n private void checkHistoricVariableUpdateEntity(String variableName,\n String processInstanceId) {\n if (processEngineConfiguration.getHistoryLevel().isAtLeast(HistoryLevel.FULL)) {\n boolean deletedVariableUpdateFound = false;\n\n List resultSet = historyService.createHistoricDetailQuery().processInstanceId(processInstanceId).list();\n for (HistoricDetail currentHistoricDetail : resultSet) {\n assertThat(currentHistoricDetail).isInstanceOf(HistoricDetailVariableInstanceUpdateEntity.class);\n HistoricDetailVariableInstanceUpdateEntity historicVariableUpdate = (HistoricDetailVariableInstanceUpdateEntity) currentHistoricDetail;\n\n if (historicVariableUpdate.getName().equals(variableName)) {\n if (historicVariableUpdate.getValue() == null) {\n if (deletedVariableUpdateFound) {\n fail(\"Mismatch: A HistoricVariableUpdateEntity with a null value already found\");\n } else {\n deletedVariableUpdateFound = true;\n }\n }\n }\n }\n\n assertThat(deletedVariableUpdateFound).isTrue();\n }\n }\n\n @Deployment(resources = {\"org/activiti/engine/test/api/oneTaskProcess.bpmn20.xml\"})\n public void testRemoveVariable() {\n ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(\"oneTaskProcess\");\n\n Task currentTask = taskService.createTaskQuery().singleResult();\n\n taskService.setVariable(currentTask.getId(), \"variable1\", \"value1\");\n assertThat(taskService.getVariable(currentTask.getId(), \"variable1\")).isEqualTo(\"value1\");\n assertThat(taskService.getVariableLocal(currentTask.getId(), \"variable1\")).isNull();\n\n taskService.removeVariable(currentTask.getId(), \"variable1\");\n\n assertThat(taskService.getVariable(currentTask.getId(), \"variable1\")).isNull();\n\n checkHistoricVariableUpdateEntity(\"variable1\", processInstance.getId());\n }\n\n public void testRemoveVariableNullTaskId() {\n assertThatExceptionOfType(ActivitiIllegalArgumentException.class)\n .isThrownBy(() -> taskService.removeVariable(null, \"variable\"))\n .withMessageContaining(\"taskId is null\");\n }\n\n @Deployment(resources = {\"org/activiti/engine/test/api/oneTaskProcess.bpmn20.xml\"})\n public void testGetVariableByHistoricActivityInstance() {\n if (processEngineConfiguration.getHistoryLevel().isAtLeast(HistoryLevel.FULL)) {\n ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(\"oneTaskProcess\");\n assertThat(processInstance).isNotNull();\n Task task = taskService.createTaskQuery().singleResult();\n\n taskService.setVariable(task.getId(),\n \"variable1\",\n \"value1\");\n taskService.setVariable(task.getId(),\n \"variable1\",\n \"value2\");\n\n HistoricActivityInstance historicActivitiInstance = historyService.createHistoricActivityInstanceQuery().processInstanceId(processInstance.getId())\n .activityId(\"theTask\").singleResult();\n assertThat(historicActivitiInstance).isNotNull();\n\n List resultSet = historyService.createHistoricDetailQuery().variableUpdates().activityInstanceId(historicActivitiInstance.getId())\n .list();\n\n assertThat(resultSet).hasSize(2);\n assertThat(resultSet)\n .extracting(h -> ((HistoricVariableUpdate) h).getValue())\n .containsExactlyInAnyOrder(\"value1\", \"value2\");\n assertThat(resultSet)\n .extracting(h -> ((HistoricVariableUpdate) h).getVariableName())\n .containsOnly(\"variable1\");\n }\n }\n\n @Deployment(resources = {\"org/activiti/engine/test/api/oneTaskProcess.bpmn20.xml\"})\n public void testRemoveVariables() {\n ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(\"oneTaskProcess\");\n\n Task currentTask = taskService.createTaskQuery().singleResult();\n\n Map varsToDelete = new HashMap();\n varsToDelete.put(\"variable1\", \"value1\");\n varsToDelete.put(\"variable2\", \"value2\");\n taskService.setVariables(currentTask.getId(), varsToDelete);\n taskService.setVariable(currentTask.getId(), \"variable3\", \"value3\");\n\n assertThat(taskService.getVariable(currentTask.getId(), \"variable1\")).isEqualTo(\"value1\");\n assertThat(taskService.getVariable(currentTask.getId(), \"variable2\")).isEqualTo(\"value2\");\n assertThat(taskService.getVariable(currentTask.getId(), \"variable3\")).isEqualTo(\"value3\");\n assertThat(taskService.getVariableLocal(currentTask.getId(), \"variable1\")).isNull();\n assertThat(taskService.getVariableLocal(currentTask.getId(), \"variable2\")).isNull();\n assertThat(taskService.getVariableLocal(currentTask.getId(), \"variable3\")).isNull();\n\n taskService.removeVariables(currentTask.getId(), varsToDelete.keySet());\n\n assertThat(taskService.getVariable(currentTask.getId(), \"variable1\")).isNull();\n assertThat(taskService.getVariable(currentTask.getId(), \"variable2\")).isNull();\n assertThat(taskService.getVariable(currentTask.getId(), \"variable3\")).isEqualTo(\"value3\");\n\n assertThat(taskService.getVariableLocal(currentTask.getId(), \"variable1\")).isNull();\n assertThat(taskService.getVariableLocal(currentTask.getId(), \"variable2\")).isNull();\n assertThat(taskService.getVariableLocal(currentTask.getId(), \"variable3\")).isNull();\n\n checkHistoricVariableUpdateEntity(\"variable1\", processInstance.getId());\n checkHistoricVariableUpdateEntity(\"variable2\", processInstance.getId());\n }\n\n public void testRemoveVariablesNullTaskId() {\n assertThatExceptionOfType(ActivitiIllegalArgumentException.class)\n .isThrownBy(() -> taskService.removeVariables(null, emptyList()))\n .withMessageContaining(\"taskId is null\");\n }\n\n @Deployment(resources = {\"org/activiti/engine/test/api/oneTaskProcess.bpmn20.xml\"})\n public void testRemoveVariableLocal() {\n ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(\"oneTaskProcess\");\n\n Task currentTask = taskService.createTaskQuery().singleResult();\n\n taskService.setVariableLocal(currentTask.getId(), \"variable1\", \"value1\");\n assertThat(taskService.getVariable(currentTask.getId(), \"variable1\")).isEqualTo(\"value1\");\n assertThat(taskService.getVariableLocal(currentTask.getId(), \"variable1\")).isEqualTo(\"value1\");\n\n taskService.removeVariableLocal(currentTask.getId(), \"variable1\");\n\n assertThat(taskService.getVariable(currentTask.getId(), \"variable1\")).isNull();\n assertThat(taskService.getVariableLocal(currentTask.getId(), \"variable1\")).isNull();\n\n checkHistoricVariableUpdateEntity(\"variable1\", processInstance.getId());\n }\n\n public void testRemoveVariableLocalNullTaskId() {\n assertThatExceptionOfType(ActivitiException.class)\n .isThrownBy(() -> taskService.removeVariableLocal(null, \"variable\"))\n .withMessageContaining(\"taskId is null\");\n }\n\n @Deployment(resources = {\"org/activiti/engine/test/api/oneTaskProcess.bpmn20.xml\"})\n public void testRemoveVariablesLocal() {\n ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(\"oneTaskProcess\");\n\n Task currentTask = taskService.createTaskQuery().singleResult();\n\n Map varsToDelete = new HashMap();\n varsToDelete.put(\"variable1\", \"value1\");\n varsToDelete.put(\"variable2\", \"value2\");\n taskService.setVariablesLocal(currentTask.getId(), varsToDelete);\n taskService.setVariableLocal(currentTask.getId(), \"variable3\", \"value3\");\n\n assertThat(taskService.getVariable(currentTask.getId(), \"variable1\")).isEqualTo(\"value1\");\n assertThat(taskService.getVariable(currentTask.getId(), \"variable2\")).isEqualTo(\"value2\");\n assertThat(taskService.getVariable(currentTask.getId(), \"variable3\")).isEqualTo(\"value3\");\n assertThat(taskService.getVariableLocal(currentTask.getId(), \"variable1\")).isEqualTo(\"value1\");\n assertThat(taskService.getVariableLocal(currentTask.getId(), \"variable2\")).isEqualTo(\"value2\");\n assertThat(taskService.getVariableLocal(currentTask.getId(), \"variable3\")).isEqualTo(\"value3\");\n\n taskService.removeVariables(currentTask.getId(), varsToDelete.keySet());\n\n assertThat(taskService.getVariable(currentTask.getId(), \"variable1\")).isNull();\n assertThat(taskService.getVariable(currentTask.getId(), \"variable2\")).isNull();\n assertThat(taskService.getVariable(currentTask.getId(), \"variable3\")).isEqualTo(\"value3\");\n\n assertThat(taskService.getVariableLocal(currentTask.getId(), \"variable1\")).isNull();\n assertThat(taskService.getVariableLocal(currentTask.getId(), \"variable2\")).isNull();\n assertThat(taskService.getVariableLocal(currentTask.getId(), \"variable3\")).isEqualTo(\"value3\");\n\n checkHistoricVariableUpdateEntity(\"variable1\", processInstance.getId());\n checkHistoricVariableUpdateEntity(\"variable2\", processInstance.getId());\n }\n\n public void testRemoveVariablesLocalNullTaskId() {\n assertThatExceptionOfType(ActivitiIllegalArgumentException.class)\n .isThrownBy(() -> taskService.removeVariablesLocal(null, emptyList()))\n .withMessageContaining(\"taskId is null\");\n }\n\n @Deployment(resources = {\"org/activiti/engine/test/api/oneTaskProcess.bpmn20.xml\"})\n public void testUserTaskOptimisticLocking() {\n runtimeService.startProcessInstanceByKey(\"oneTaskProcess\");\n\n Task task1 = taskService.createTaskQuery().singleResult();\n Task task2 = taskService.createTaskQuery().singleResult();\n\n task1.setDescription(\"test description one\");\n taskService.saveTask(task1);\n\n assertThatExceptionOfType(ActivitiOptimisticLockingException.class)\n .isThrownBy(() -> {\n task2.setDescription(\"test description two\");\n taskService.saveTask(task2);\n });\n }\n\n public void testDeleteTaskWithDeleteReason() {\n // ACT-900: deleteReason can be manually specified - can only be\n // validated when historyLevel > ACTIVITY\n if (processEngineConfiguration.getHistoryLevel().isAtLeast(HistoryLevel.ACTIVITY)) {\n\n Task task = taskService.newTask();\n task.setName(\"test task\");\n taskService.saveTask(task);\n\n assertThat(task.getId()).isNotNull();\n\n taskService.deleteTask(task.getId(),\n \"deleted for testing purposes\");\n\n HistoricTaskInstance historicTaskInstance = historyService.createHistoricTaskInstanceQuery().taskId(task.getId()).singleResult();\n\n assertThat(historicTaskInstance).isNotNull();\n assertThat(historicTaskInstance.getDeleteReason()).isEqualTo(\"deleted for testing purposes\");\n\n // Delete historic task that is left behind, will not be cleaned up\n // because this is not part of a process\n taskService.deleteTask(task.getId(),\n true);\n }\n }\n\n public void testResolveTaskNullTaskId() {\n assertThatExceptionOfType(ActivitiException.class)\n .isThrownBy(() -> taskService.resolveTask(null))\n .withMessageContaining(\"taskId is null\");\n }\n\n public void testResolveTaskUnexistingTaskId() {\n assertThatExceptionOfType(ActivitiException.class)\n .isThrownBy(() -> taskService.resolveTask(\"blergh\"))\n .withMessageContaining(\"Cannot find task with id\");\n }\n\n public void testResolveTaskWithParametersNullParameters() {\n Task task = taskService.newTask();\n task.setDelegationState(DelegationState.PENDING);\n taskService.saveTask(task);\n\n String taskId = task.getId();\n taskService.resolveTask(taskId,\n null);\n\n if (processEngineConfiguration.getHistoryLevel().isAtLeast(HistoryLevel.AUDIT)) {\n historyService.deleteHistoricTaskInstance(taskId);\n }\n\n // Fetch the task again\n task = taskService.createTaskQuery().taskId(taskId).singleResult();\n assertThat(task.getDelegationState()).isEqualTo(DelegationState.RESOLVED);\n\n taskService.deleteTask(taskId,\n true);\n }\n\n public void testResolveTaskWithParametersEmptyParameters() {\n Task task = taskService.newTask();\n task.setDelegationState(DelegationState.PENDING);\n taskService.saveTask(task);\n\n String taskId = task.getId();\n taskService.resolveTask(taskId, emptyMap());\n\n if (processEngineConfiguration.getHistoryLevel().isAtLeast(HistoryLevel.AUDIT)) {\n historyService.deleteHistoricTaskInstance(taskId);\n }\n\n // Fetch the task again\n task = taskService.createTaskQuery().taskId(taskId).singleResult();\n assertThat(task.getDelegationState()).isEqualTo(DelegationState.RESOLVED);\n\n taskService.deleteTask(taskId, true);\n }\n\n @Deployment(resources = {\"org/activiti/engine/test/api/twoTasksProcess.bpmn20.xml\"})\n public void testResolveWithParametersTask() {\n ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(\"twoTasksProcess\");\n\n // Fetch first task\n Task task = taskService.createTaskQuery().singleResult();\n assertThat(task.getName()).isEqualTo(\"First task\");\n\n taskService.delegateTask(task.getId(), \"johndoe\");\n\n // Resolve first task\n Map taskParams = new HashMap();\n taskParams.put(\"myParam\", \"myValue\");\n taskService.resolveTask(task.getId(), taskParams);\n\n // Verify that task is resolved\n task = taskService.createTaskQuery().taskDelegationState(DelegationState.RESOLVED).singleResult();\n assertThat(task.getName()).isEqualTo(\"First task\");\n\n // Verify task parameters set on execution\n Map variables = runtimeService.getVariables(processInstance.getId());\n assertThat(variables).hasSize(1);\n assertThat(variables.get(\"myParam\")).isEqualTo(\"myValue\");\n }\n\n @Deployment(resources = {\"org/activiti/engine/test/api/oneTaskProcess.bpmn20.xml\"})\n public void testDeleteTaskPartOfProcess() {\n runtimeService.startProcessInstanceByKey(\"oneTaskProcess\");\n Task task = taskService.createTaskQuery().singleResult();\n assertThat(task).isNotNull();\n\n assertThatExceptionOfType(ActivitiException.class)\n .isThrownBy(() -> taskService.deleteTask(task.getId()))\n .withMessage(\"The task cannot be deleted because is part of a running process\");\n\n assertThatExceptionOfType(ActivitiException.class)\n .isThrownBy(() -> taskService.deleteTask(task.getId(), true))\n .withMessage(\"The task cannot be deleted because is part of a running process\");\n\n assertThatExceptionOfType(ActivitiException.class)\n .isThrownBy(() -> taskService.deleteTask(task.getId(), \"test\"))\n .withMessage(\"The task cannot be deleted because is part of a running process\");\n\n assertThatExceptionOfType(ActivitiException.class)\n .isThrownBy(() -> taskService.deleteTasks(singletonList(task.getId())))\n .withMessage(\"The task cannot be deleted because is part of a running process\");\n\n assertThatExceptionOfType(ActivitiException.class)", "answers": [" .isThrownBy(() -> taskService.deleteTasks(singletonList(task.getId()), true))"], "length": 2955, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "9731d51b-fef0-4499-bc66-49bcdd3736aa", "reasoning": "The test method is checking that deleting a task that is part of a running process throws an ActivitiException. After the previous assertThatExceptionOfType block, the next assertion starts with the same pattern but tests the overload deleteTasks(List, boolean). Therefore the next line continues the chain with the isThrownBy lambda calling deleteTasks with the task id and cascade=true.", "reasoning_model_answer": ".isThrownBy(() -> taskService.deleteTasks(singletonList(task.getId()), true))", "assistant_with_reasoning": "\nThe test method is checking that deleting a task that is part of a running process throws an ActivitiException. After the previous assertThatExceptionOfType block, the next assertion starts with the same pattern but tests the overload deleteTasks(List, boolean). Therefore the next line continues the chain with the isThrownBy lambda calling deleteTasks with the task id and cascade=true.\n\n.isThrownBy(() -> taskService.deleteTasks(singletonList(task.getId()), true))", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 7.239, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 48004, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": ".isThrownBy(() -> taskService.deleteTasks(singletonList(task.getId()), true))", "score": 0.93, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "# -*- coding: utf-8 -*-\n# Copyright 2022 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\nfrom collections import OrderedDict\nimport os\nimport re\nfrom typing import Dict, Optional, Sequence, Tuple, Type, Union\nimport pkg_resources\n\nfrom google.api_core import client_options as client_options_lib\nfrom google.api_core import exceptions as core_exceptions\nfrom google.api_core import gapic_v1\nfrom google.api_core import retry as retries\nfrom google.auth import credentials as ga_credentials # type: ignore\nfrom google.auth.transport import mtls # type: ignore\nfrom google.auth.transport.grpc import SslCredentials # type: ignore\nfrom google.auth.exceptions import MutualTLSChannelError # type: ignore\nfrom google.oauth2 import service_account # type: ignore\n\ntry:\n OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault]\nexcept AttributeError: # pragma: NO COVER\n OptionalRetry = Union[retries.Retry, object] # type: ignore\n\nfrom google.api_core import operation as gac_operation # type: ignore\nfrom google.api_core import operation_async # type: ignore\nfrom google.cloud.aiplatform_v1.services.specialist_pool_service import pagers\nfrom google.cloud.aiplatform_v1.types import operation as gca_operation\nfrom google.cloud.aiplatform_v1.types import specialist_pool\nfrom google.cloud.aiplatform_v1.types import specialist_pool as gca_specialist_pool\nfrom google.cloud.aiplatform_v1.types import specialist_pool_service\nfrom google.protobuf import empty_pb2 # type: ignore\nfrom google.protobuf import field_mask_pb2 # type: ignore\nfrom .transports.base import SpecialistPoolServiceTransport, DEFAULT_CLIENT_INFO\nfrom .transports.grpc import SpecialistPoolServiceGrpcTransport\nfrom .transports.grpc_asyncio import SpecialistPoolServiceGrpcAsyncIOTransport\n\n\nclass SpecialistPoolServiceClientMeta(type):\n \"\"\"Metaclass for the SpecialistPoolService client.\n\n This provides class-level methods for building and retrieving\n support objects (e.g. transport) without polluting the client instance\n objects.\n \"\"\"\n\n _transport_registry = (\n OrderedDict()\n ) # type: Dict[str, Type[SpecialistPoolServiceTransport]]\n _transport_registry[\"grpc\"] = SpecialistPoolServiceGrpcTransport\n _transport_registry[\"grpc_asyncio\"] = SpecialistPoolServiceGrpcAsyncIOTransport\n\n def get_transport_class(\n cls, label: str = None,\n ) -> Type[SpecialistPoolServiceTransport]:\n \"\"\"Returns an appropriate transport class.\n\n Args:\n label: The name of the desired transport. If none is\n provided, then the first transport in the registry is used.\n\n Returns:\n The transport class to use.\n \"\"\"\n # If a specific transport is requested, return that one.\n if label:\n return cls._transport_registry[label]\n\n # No transport is requested; return the default (that is, the first one\n # in the dictionary).\n return next(iter(cls._transport_registry.values()))\n\n\nclass SpecialistPoolServiceClient(metaclass=SpecialistPoolServiceClientMeta):\n \"\"\"A service for creating and managing Customer SpecialistPools.\n When customers start Data Labeling jobs, they can reuse/create\n Specialist Pools to bring their own Specialists to label the\n data. Customers can add/remove Managers for the Specialist Pool\n on Cloud console, then Managers will get email notifications to\n manage Specialists and tasks on CrowdCompute console.\n \"\"\"\n\n @staticmethod\n def _get_default_mtls_endpoint(api_endpoint):\n \"\"\"Converts api endpoint to mTLS endpoint.\n\n Convert \"*.sandbox.googleapis.com\" and \"*.googleapis.com\" to\n \"*.mtls.sandbox.googleapis.com\" and \"*.mtls.googleapis.com\" respectively.\n Args:\n api_endpoint (Optional[str]): the api endpoint to convert.\n Returns:\n str: converted mTLS api endpoint.\n \"\"\"\n if not api_endpoint:\n return api_endpoint\n\n mtls_endpoint_re = re.compile(\n r\"(?P[^.]+)(?P\\.mtls)?(?P\\.sandbox)?(?P\\.googleapis\\.com)?\"\n )\n\n m = mtls_endpoint_re.match(api_endpoint)\n name, mtls, sandbox, googledomain = m.groups()\n if mtls or not googledomain:\n return api_endpoint\n\n if sandbox:\n return api_endpoint.replace(\n \"sandbox.googleapis.com\", \"mtls.sandbox.googleapis.com\"\n )\n\n return api_endpoint.replace(\".googleapis.com\", \".mtls.googleapis.com\")\n\n DEFAULT_ENDPOINT = \"aiplatform.googleapis.com\"\n DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore\n DEFAULT_ENDPOINT\n )\n\n @classmethod\n def from_service_account_info(cls, info: dict, *args, **kwargs):\n \"\"\"Creates an instance of this client using the provided credentials\n info.\n\n Args:\n info (dict): The service account private key info.\n args: Additional arguments to pass to the constructor.\n kwargs: Additional arguments to pass to the constructor.\n\n Returns:\n SpecialistPoolServiceClient: The constructed client.\n \"\"\"\n credentials = service_account.Credentials.from_service_account_info(info)\n kwargs[\"credentials\"] = credentials\n return cls(*args, **kwargs)\n\n @classmethod\n def from_service_account_file(cls, filename: str, *args, **kwargs):\n \"\"\"Creates an instance of this client using the provided credentials\n file.\n\n Args:\n filename (str): The path to the service account private key json\n file.\n args: Additional arguments to pass to the constructor.\n kwargs: Additional arguments to pass to the constructor.\n\n Returns:\n SpecialistPoolServiceClient: The constructed client.\n \"\"\"\n credentials = service_account.Credentials.from_service_account_file(filename)\n kwargs[\"credentials\"] = credentials\n return cls(*args, **kwargs)\n\n from_service_account_json = from_service_account_file\n\n @property\n def transport(self) -> SpecialistPoolServiceTransport:\n \"\"\"Returns the transport used by the client instance.\n\n Returns:\n SpecialistPoolServiceTransport: The transport used by the client\n instance.\n \"\"\"\n return self._transport\n\n @staticmethod\n def specialist_pool_path(project: str, location: str, specialist_pool: str,) -> str:\n \"\"\"Returns a fully-qualified specialist_pool string.\"\"\"\n return \"projects/{project}/locations/{location}/specialistPools/{specialist_pool}\".format(\n project=project, location=location, specialist_pool=specialist_pool,\n )\n\n @staticmethod\n def parse_specialist_pool_path(path: str) -> Dict[str, str]:\n \"\"\"Parses a specialist_pool path into its component segments.\"\"\"\n m = re.match(\n r\"^projects/(?P.+?)/locations/(?P.+?)/specialistPools/(?P.+?)$\",\n path,\n )\n return m.groupdict() if m else {}\n\n @staticmethod\n def common_billing_account_path(billing_account: str,) -> str:\n \"\"\"Returns a fully-qualified billing_account string.\"\"\"\n return \"billingAccounts/{billing_account}\".format(\n billing_account=billing_account,\n )\n\n @staticmethod\n def parse_common_billing_account_path(path: str) -> Dict[str, str]:\n \"\"\"Parse a billing_account path into its component segments.\"\"\"\n m = re.match(r\"^billingAccounts/(?P.+?)$\", path)\n return m.groupdict() if m else {}\n\n @staticmethod\n def common_folder_path(folder: str,) -> str:\n \"\"\"Returns a fully-qualified folder string.\"\"\"\n return \"folders/{folder}\".format(folder=folder,)\n\n @staticmethod\n def parse_common_folder_path(path: str) -> Dict[str, str]:\n \"\"\"Parse a folder path into its component segments.\"\"\"\n m = re.match(r\"^folders/(?P.+?)$\", path)\n return m.groupdict() if m else {}\n\n @staticmethod\n def common_organization_path(organization: str,) -> str:\n \"\"\"Returns a fully-qualified organization string.\"\"\"\n return \"organizations/{organization}\".format(organization=organization,)\n\n @staticmethod\n def parse_common_organization_path(path: str) -> Dict[str, str]:\n \"\"\"Parse a organization path into its component segments.\"\"\"\n m = re.match(r\"^organizations/(?P.+?)$\", path)\n return m.groupdict() if m else {}\n\n @staticmethod\n def common_project_path(project: str,) -> str:\n \"\"\"Returns a fully-qualified project string.\"\"\"\n return \"projects/{project}\".format(project=project,)\n\n @staticmethod\n def parse_common_project_path(path: str) -> Dict[str, str]:\n \"\"\"Parse a project path into its component segments.\"\"\"\n m = re.match(r\"^projects/(?P.+?)$\", path)\n return m.groupdict() if m else {}\n\n @staticmethod\n def common_location_path(project: str, location: str,) -> str:\n \"\"\"Returns a fully-qualified location string.\"\"\"\n return \"projects/{project}/locations/{location}\".format(\n project=project, location=location,\n )\n\n @staticmethod\n def parse_common_location_path(path: str) -> Dict[str, str]:\n \"\"\"Parse a location path into its component segments.\"\"\"\n m = re.match(r\"^projects/(?P.+?)/locations/(?P.+?)$\", path)\n return m.groupdict() if m else {}\n\n @classmethod\n def get_mtls_endpoint_and_cert_source(\n cls, client_options: Optional[client_options_lib.ClientOptions] = None\n ):\n \"\"\"Return the API endpoint and client cert source for mutual TLS.\n\n The client cert source is determined in the following order:\n (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not \"true\", the\n client cert source is None.\n (2) if `client_options.client_cert_source` is provided, use the provided one; if the\n default client cert source exists, use the default one; otherwise the client cert\n source is None.\n\n The API endpoint is determined in the following order:\n (1) if `client_options.api_endpoint` if provided, use the provided one.\n (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is \"always\", use the\n default mTLS endpoint; if the environment variabel is \"never\", use the default API\n endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise\n use the default API endpoint.\n\n More details can be found at https://google.aip.dev/auth/4114.\n\n Args:\n client_options (google.api_core.client_options.ClientOptions): Custom options for the\n client. Only the `api_endpoint` and `client_cert_source` properties may be used\n in this method.\n\n Returns:\n Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the\n client cert source to use.\n\n Raises:\n google.auth.exceptions.MutualTLSChannelError: If any errors happen.\n \"\"\"\n if client_options is None:\n client_options = client_options_lib.ClientOptions()\n use_client_cert = os.getenv(\"GOOGLE_API_USE_CLIENT_CERTIFICATE\", \"false\")\n use_mtls_endpoint = os.getenv(\"GOOGLE_API_USE_MTLS_ENDPOINT\", \"auto\")\n if use_client_cert not in (\"true\", \"false\"):\n raise ValueError(\n \"Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`\"\n )\n if use_mtls_endpoint not in (\"auto\", \"never\", \"always\"):\n raise MutualTLSChannelError(\n \"Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`\"\n )\n\n # Figure out the client cert source to use.\n client_cert_source = None\n if use_client_cert == \"true\":\n if client_options.client_cert_source:\n client_cert_source = client_options.client_cert_source\n elif mtls.has_default_client_cert_source():\n client_cert_source = mtls.default_client_cert_source()\n\n # Figure out which api endpoint to use.\n if client_options.api_endpoint is not None:\n api_endpoint = client_options.api_endpoint\n elif use_mtls_endpoint == \"always\" or (\n use_mtls_endpoint == \"auto\" and client_cert_source\n ):\n api_endpoint = cls.DEFAULT_MTLS_ENDPOINT\n else:\n api_endpoint = cls.DEFAULT_ENDPOINT\n\n return api_endpoint, client_cert_source\n\n def __init__(\n self,\n *,\n credentials: Optional[ga_credentials.Credentials] = None,\n transport: Union[str, SpecialistPoolServiceTransport, None] = None,\n client_options: Optional[client_options_lib.ClientOptions] = None,\n client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,\n ) -> None:\n \"\"\"Instantiates the specialist pool service client.\n\n Args:\n credentials (Optional[google.auth.credentials.Credentials]): The\n authorization credentials to attach to requests. These\n credentials identify the application to the service; if none\n are specified, the client will attempt to ascertain the\n credentials from the environment.\n transport (Union[str, SpecialistPoolServiceTransport]): The\n transport to use. If set to None, a transport is chosen\n automatically.\n client_options (google.api_core.client_options.ClientOptions): Custom options for the\n client. It won't take effect if a ``transport`` instance is provided.\n (1) The ``api_endpoint`` property can be used to override the\n default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT\n environment variable can also be used to override the endpoint:\n \"always\" (always use the default mTLS endpoint), \"never\" (always\n use the default regular endpoint) and \"auto\" (auto switch to the\n default mTLS endpoint if client certificate is present, this is\n the default value). However, the ``api_endpoint`` property takes\n precedence if provided.\n (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable\n is \"true\", then the ``client_cert_source`` property can be used\n to provide client certificate for mutual TLS transport. If\n not provided, the default SSL client certificate will be used if\n present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is \"false\" or not\n set, no client certificate will be used.\n client_info (google.api_core.gapic_v1.client_info.ClientInfo):\n The client info used to send a user-agent string along with\n API requests. If ``None``, then default info will be used.\n Generally, you only need to set this if you're developing\n your own client library.\n\n Raises:\n google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport\n creation failed for any reason.\n \"\"\"\n if isinstance(client_options, dict):\n client_options = client_options_lib.from_dict(client_options)\n if client_options is None:\n client_options = client_options_lib.ClientOptions()\n\n api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(\n client_options\n )\n\n api_key_value = getattr(client_options, \"api_key\", None)\n if api_key_value and credentials:\n raise ValueError(\n \"client_options.api_key and credentials are mutually exclusive\"\n )\n\n # Save or instantiate the transport.\n # Ordinarily, we provide the transport, but allowing a custom transport\n # instance provides an extensibility point for unusual situations.\n if isinstance(transport, SpecialistPoolServiceTransport):\n # transport is a SpecialistPoolServiceTransport instance.\n if credentials or client_options.credentials_file or api_key_value:\n raise ValueError(\n \"When providing a transport instance, \"\n \"provide its credentials directly.\"\n )\n if client_options.scopes:\n raise ValueError(\n \"When providing a transport instance, provide its scopes \"\n \"directly.\"\n )\n self._transport = transport\n else:\n import google.auth._default # type: ignore\n\n if api_key_value and hasattr(\n google.auth._default, \"get_api_key_credentials\"\n ):\n credentials = google.auth._default.get_api_key_credentials(\n api_key_value\n )\n\n Transport = type(self).get_transport_class(transport)\n self._transport = Transport(\n credentials=credentials,\n credentials_file=client_options.credentials_file,\n host=api_endpoint,\n scopes=client_options.scopes,\n client_cert_source_for_mtls=client_cert_source_func,\n quota_project_id=client_options.quota_project_id,\n client_info=client_info,\n always_use_jwt_access=True,\n )\n\n def create_specialist_pool(\n self,\n request: Union[\n specialist_pool_service.CreateSpecialistPoolRequest, dict\n ] = None,\n *,\n parent: str = None,\n specialist_pool: gca_specialist_pool.SpecialistPool = None,\n retry: OptionalRetry = gapic_v1.method.DEFAULT,\n timeout: float = None,\n metadata: Sequence[Tuple[str, str]] = (),\n ) -> gac_operation.Operation:\n r\"\"\"Creates a SpecialistPool.\n\n .. code-block:: python\n\n from google.cloud import aiplatform_v1\n\n def sample_create_specialist_pool():\n # Create a client\n client = aiplatform_v1.SpecialistPoolServiceClient()\n\n # Initialize request argument(s)\n specialist_pool = aiplatform_v1.SpecialistPool()\n specialist_pool.name = \"name_value\"\n specialist_pool.display_name = \"display_name_value\"\n\n request = aiplatform_v1.CreateSpecialistPoolRequest(\n parent=\"parent_value\",\n specialist_pool=specialist_pool,\n )\n\n # Make the request\n operation = client.create_specialist_pool(request=request)\n\n print(\"Waiting for operation to complete...\")\n\n response = operation.result()\n\n # Handle the response\n print(response)\n\n Args:\n request (Union[google.cloud.aiplatform_v1.types.CreateSpecialistPoolRequest, dict]):\n The request object. Request message for\n [SpecialistPoolService.CreateSpecialistPool][google.cloud.aiplatform.v1.SpecialistPoolService.CreateSpecialistPool].\n parent (str):\n Required. The parent Project name for the new\n SpecialistPool. The form is\n ``projects/{project}/locations/{location}``.\n\n This corresponds to the ``parent`` field\n on the ``request`` instance; if ``request`` is provided, this\n should not be set.\n specialist_pool (google.cloud.aiplatform_v1.types.SpecialistPool):\n Required. The SpecialistPool to\n create.\n\n This corresponds to the ``specialist_pool`` field\n on the ``request`` instance; if ``request`` is provided, this\n should not be set.\n retry (google.api_core.retry.Retry): Designation of what errors, if any,\n should be retried.\n timeout (float): The timeout for this request.\n metadata (Sequence[Tuple[str, str]]): Strings which should be\n sent along with the request as metadata.\n\n Returns:\n google.api_core.operation.Operation:\n An object representing a long-running operation.\n\n The result type for the operation will be :class:`google.cloud.aiplatform_v1.types.SpecialistPool` SpecialistPool represents customers' own workforce to work on their data\n labeling jobs. It includes a group of specialist\n managers and workers. Managers are responsible for\n managing the workers in this pool as well as\n customers' data labeling jobs associated with this\n pool. Customers create specialist pool as well as\n start data labeling jobs on Cloud, managers and\n workers handle the jobs using CrowdCompute console.\n\n \"\"\"\n # Create or coerce a protobuf request object.\n # Quick check: If we got a request object, we should *not* have\n # gotten any keyword arguments that map to the request.\n has_flattened_params = any([parent, specialist_pool])\n if request is not None and has_flattened_params:\n raise ValueError(\n \"If the `request` argument is set, then none of \"\n \"the individual field arguments should be set.\"\n )\n\n # Minor optimization to avoid making a copy if the user passes\n # in a specialist_pool_service.CreateSpecialistPoolRequest.\n # There's no risk of modifying the input as we've already verified\n # there are no flattened fields.\n if not isinstance(request, specialist_pool_service.CreateSpecialistPoolRequest):\n request = specialist_pool_service.CreateSpecialistPoolRequest(request)\n # If we have keyword arguments corresponding to fields on the\n # request, apply these.\n if parent is not None:\n request.parent = parent\n if specialist_pool is not None:\n request.specialist_pool = specialist_pool\n\n # Wrap the RPC method; this adds retry and timeout information,\n # and friendly error handling.\n rpc = self._transport._wrapped_methods[self._transport.create_specialist_pool]\n\n # Certain fields should be provided within the metadata header;\n # add these here.\n metadata = tuple(metadata) + (\n gapic_v1.routing_header.to_grpc_metadata(((\"parent\", request.parent),)),\n )\n\n # Send the request.\n response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,)\n\n # Wrap the response in an operation future.\n response = gac_operation.from_gapic(\n response,\n self._transport.operations_client,\n gca_specialist_pool.SpecialistPool,\n metadata_type=specialist_pool_service.CreateSpecialistPoolOperationMetadata,\n )\n\n # Done; return the response.\n return response\n\n def get_specialist_pool(\n self,\n request: Union[specialist_pool_service.GetSpecialistPoolRequest, dict] = None,\n *,\n name: str = None,\n retry: OptionalRetry = gapic_v1.method.DEFAULT,\n timeout: float = None,\n metadata: Sequence[Tuple[str, str]] = (),\n ) -> specialist_pool.SpecialistPool:\n r\"\"\"Gets a SpecialistPool.\n\n .. code-block:: python\n\n from google.cloud import aiplatform_v1\n\n def sample_get_specialist_pool():\n # Create a client\n client = aiplatform_v1.SpecialistPoolServiceClient()\n\n # Initialize request argument(s)\n request = aiplatform_v1.GetSpecialistPoolRequest(\n name=\"name_value\",\n )\n\n # Make the request\n response = client.get_specialist_pool(request=request)\n\n # Handle the response\n print(response)\n\n Args:\n request (Union[google.cloud.aiplatform_v1.types.GetSpecialistPoolRequest, dict]):\n The request object. Request message for\n [SpecialistPoolService.GetSpecialistPool][google.cloud.aiplatform.v1.SpecialistPoolService.GetSpecialistPool].\n name (str):\n Required. The name of the SpecialistPool resource. The\n form is\n ``projects/{project}/locations/{location}/specialistPools/{specialist_pool}``.\n\n This corresponds to the ``name`` field\n on the ``request`` instance; if ``request`` is provided, this\n should not be set.\n retry (google.api_core.retry.Retry): Designation of what errors, if any,\n should be retried.\n timeout (float): The timeout for this request.\n metadata (Sequence[Tuple[str, str]]): Strings which should be\n sent along with the request as metadata.\n\n Returns:\n google.cloud.aiplatform_v1.types.SpecialistPool:\n SpecialistPool represents customers'\n own workforce to work on their data\n labeling jobs. It includes a group of\n specialist managers and workers.\n Managers are responsible for managing\n the workers in this pool as well as\n customers' data labeling jobs associated\n with this pool. Customers create\n specialist pool as well as start data\n labeling jobs on Cloud, managers and\n workers handle the jobs using\n CrowdCompute console.\n\n \"\"\"\n # Create or coerce a protobuf request object.\n # Quick check: If we got a request object, we should *not* have\n # gotten any keyword arguments that map to the request.\n has_flattened_params = any([name])\n if request is not None and has_flattened_params:\n raise ValueError(\n \"If the `request` argument is set, then none of \"\n \"the individual field arguments should be set.\"\n )\n\n # Minor optimization to avoid making a copy if the user passes\n # in a specialist_pool_service.GetSpecialistPoolRequest.\n # There's no risk of modifying the input as we've already verified\n # there are no flattened fields.\n if not isinstance(request, specialist_pool_service.GetSpecialistPoolRequest):\n request = specialist_pool_service.GetSpecialistPoolRequest(request)\n # If we have keyword arguments corresponding to fields on the\n # request, apply these.\n if name is not None:\n request.name = name\n\n # Wrap the RPC method; this adds retry and timeout information,\n # and friendly error handling.\n rpc = self._transport._wrapped_methods[self._transport.get_specialist_pool]\n\n # Certain fields should be provided within the metadata header;\n # add these here.\n metadata = tuple(metadata) + (\n gapic_v1.routing_header.to_grpc_metadata(((\"name\", request.name),)),\n )\n\n # Send the request.\n response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,)\n\n # Done; return the response.\n return response\n\n def list_specialist_pools(\n self,\n request: Union[specialist_pool_service.ListSpecialistPoolsRequest, dict] = None,\n *,\n parent: str = None,\n retry: OptionalRetry = gapic_v1.method.DEFAULT,\n timeout: float = None,\n metadata: Sequence[Tuple[str, str]] = (),\n ) -> pagers.ListSpecialistPoolsPager:\n r\"\"\"Lists SpecialistPools in a Location.\n\n .. code-block:: python\n\n from google.cloud import aiplatform_v1\n\n def sample_list_specialist_pools():\n # Create a client\n client = aiplatform_v1.SpecialistPoolServiceClient()\n\n # Initialize request argument(s)\n request = aiplatform_v1.ListSpecialistPoolsRequest(\n parent=\"parent_value\",\n )\n\n # Make the request\n page_result = client.list_specialist_pools(request=request)\n\n # Handle the response\n for response in page_result:\n print(response)\n\n Args:\n request (Union[google.cloud.aiplatform_v1.types.ListSpecialistPoolsRequest, dict]):\n The request object. Request message for\n [SpecialistPoolService.ListSpecialistPools][google.cloud.aiplatform.v1.SpecialistPoolService.ListSpecialistPools].\n parent (str):\n Required. The name of the SpecialistPool's parent\n resource. Format:\n ``projects/{project}/locations/{location}``\n\n This corresponds to the ``parent`` field\n on the ``request`` instance; if ``request`` is provided, this\n should not be set.\n retry (google.api_core.retry.Retry): Designation of what errors, if any,\n should be retried.\n timeout (float): The timeout for this request.\n metadata (Sequence[Tuple[str, str]]): Strings which should be\n sent along with the request as metadata.\n\n Returns:\n google.cloud.aiplatform_v1.services.specialist_pool_service.pagers.ListSpecialistPoolsPager:\n Response message for\n [SpecialistPoolService.ListSpecialistPools][google.cloud.aiplatform.v1.SpecialistPoolService.ListSpecialistPools].\n\n Iterating over this object will yield results and\n resolve additional pages automatically.\n\n \"\"\"\n # Create or coerce a protobuf request object.\n # Quick check: If we got a request object, we should *not* have\n # gotten any keyword arguments that map to the request.\n has_flattened_params = any([parent])\n if request is not None and has_flattened_params:\n raise ValueError(\n \"If the `request` argument is set, then none of \"\n \"the individual field arguments should be set.\"\n )\n\n # Minor optimization to avoid making a copy if the user passes\n # in a specialist_pool_service.ListSpecialistPoolsRequest.\n # There's no risk of modifying the input as we've already verified\n # there are no flattened fields.\n if not isinstance(request, specialist_pool_service.ListSpecialistPoolsRequest):\n request = specialist_pool_service.ListSpecialistPoolsRequest(request)\n # If we have keyword arguments corresponding to fields on the\n # request, apply these.\n if parent is not None:\n request.parent = parent\n\n # Wrap the RPC method; this adds retry and timeout information,\n # and friendly error handling.\n rpc = self._transport._wrapped_methods[self._transport.list_specialist_pools]\n\n # Certain fields should be provided within the metadata header;\n # add these here.\n metadata = tuple(metadata) + (\n gapic_v1.routing_header.to_grpc_metadata(((\"parent\", request.parent),)),\n )\n\n # Send the request.\n response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,)\n\n # This method is paged; wrap the response in a pager, which provides\n # an `__iter__` convenience method.\n response = pagers.ListSpecialistPoolsPager(\n method=rpc, request=request, response=response, metadata=metadata,\n )\n\n # Done; return the response.\n return response\n\n def delete_specialist_pool(\n self,\n request: Union[\n specialist_pool_service.DeleteSpecialistPoolRequest, dict\n ] = None,\n *,\n name: str = None,\n retry: OptionalRetry = gapic_v1.method.DEFAULT,\n timeout: float = None,\n metadata: Sequence[Tuple[str, str]] = (),\n ) -> gac_operation.Operation:\n r\"\"\"Deletes a SpecialistPool as well as all Specialists\n in the pool.\n\n\n .. code-block:: python\n\n from google.cloud import aiplatform_v1\n\n def sample_delete_specialist_pool():\n # Create a client\n client = aiplatform_v1.SpecialistPoolServiceClient()\n\n # Initialize request argument(s)\n request = aiplatform_v1.DeleteSpecialistPoolRequest(\n name=\"name_value\",\n )\n\n # Make the request\n operation = client.delete_specialist_pool(request=request)\n\n print(\"Waiting for operation to complete...\")", "answers": [" response = operation.result()"], "length": 2950, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "1ed7acc5-efa4-4a2b-af7c-44cc4c6109c4", "reasoning": "The sample code for delete_specialist_pool follows the same pattern as other sample methods: after initiating the operation and printing a waiting message, the next step is to retrieve the result of the long-running operation. This is done by calling operation.result() and assigning it to a variable, typically named response.", "reasoning_model_answer": "response = operation.result()", "assistant_with_reasoning": "\nThe sample code for delete_specialist_pool follows the same pattern as other sample methods: after initiating the operation and printing a waiting message, the next step is to retrieve the result of the long-running operation. This is done by calling operation.result() and assigning it to a variable, typically named response.\n\nresponse = operation.result()", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 8.466, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 33685, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "response = operation.result()", "score": 0.78, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "using Microsoft.IdentityModel;\nusing Microsoft.IdentityModel.S2S.Protocols.OAuth2;\nusing Microsoft.IdentityModel.S2S.Tokens;\nusing Microsoft.SharePoint.Client;\nusing Microsoft.SharePoint.Client.EventReceivers;\nusing System;\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.Globalization;\nusing System.IdentityModel.Selectors;\nusing System.IdentityModel.Tokens;\nusing System.IO;\nusing System.Linq;\nusing System.Net;\nusing System.Security.Cryptography.X509Certificates;\nusing System.Security.Principal;\nusing System.ServiceModel;\nusing System.Text;\nusing System.Web;\nusing System.Web.Configuration;\nusing System.Web.Script.Serialization;\nusing AudienceRestriction = Microsoft.IdentityModel.Tokens.AudienceRestriction;\nusing AudienceUriValidationFailedException = Microsoft.IdentityModel.Tokens.AudienceUriValidationFailedException;\nusing SecurityTokenHandlerConfiguration = Microsoft.IdentityModel.Tokens.SecurityTokenHandlerConfiguration;\nusing X509SigningCredentials = Microsoft.IdentityModel.SecurityTokenService.X509SigningCredentials;\n\nnamespace MVCTaxonomyPickerWeb\n{\n public static class TokenHelper\n {\n #region public fields\n\n /// \n /// SharePoint principal.\n /// \n public const string SharePointPrincipal = \"00000003-0000-0ff1-ce00-000000000000\";\n\n /// \n /// Lifetime of HighTrust access token, 12 hours.\n /// \n public static readonly TimeSpan HighTrustAccessTokenLifetime = TimeSpan.FromHours(12.0);\n\n #endregion public fields\n\n #region public methods\n\n /// \n /// Retrieves the context token string from the specified request by looking for well-known parameter names in the \n /// POSTed form parameters and the querystring. Returns null if no context token is found.\n /// \n /// HttpRequest in which to look for a context token\n /// The context token string\n public static string GetContextTokenFromRequest(HttpRequest request)\n {\n return GetContextTokenFromRequest(new HttpRequestWrapper(request));\n }\n\n /// \n /// Retrieves the context token string from the specified request by looking for well-known parameter names in the \n /// POSTed form parameters and the querystring. Returns null if no context token is found.\n /// \n /// HttpRequest in which to look for a context token\n /// The context token string\n public static string GetContextTokenFromRequest(HttpRequestBase request)\n {\n string[] paramNames = { \"AppContext\", \"AppContextToken\", \"AccessToken\", \"SPAppToken\" };\n foreach (string paramName in paramNames)\n {\n if (!string.IsNullOrEmpty(request.Form[paramName]))\n {\n return request.Form[paramName];\n }\n if (!string.IsNullOrEmpty(request.QueryString[paramName]))\n {\n return request.QueryString[paramName];\n }\n }\n return null;\n }\n\n /// \n /// Validate that a specified context token string is intended for this application based on the parameters \n /// specified in web.config. Parameters used from web.config used for validation include ClientId, \n /// HostedAppHostNameOverride, HostedAppHostName, ClientSecret, and Realm (if it is specified). If HostedAppHostNameOverride is present,\n /// it will be used for validation. Otherwise, if the is not \n /// null, it is used for validation instead of the web.config's HostedAppHostName. If the token is invalid, an \n /// exception is thrown. If the token is valid, TokenHelper's static STS metadata url is updated based on the token contents\n /// and a JsonWebSecurityToken based on the context token is returned.\n /// \n /// The context token to validate\n /// The URL authority, consisting of Domain Name System (DNS) host name or IP address and the port number, to use for token audience validation.\n /// If null, HostedAppHostName web.config setting is used instead. HostedAppHostNameOverride web.config setting, if present, will be used \n /// for validation instead of .\n /// A JsonWebSecurityToken based on the context token.\n public static SharePointContextToken ReadAndValidateContextToken(string contextTokenString, string appHostName = null)\n {\n JsonWebSecurityTokenHandler tokenHandler = CreateJsonWebSecurityTokenHandler();\n SecurityToken securityToken = tokenHandler.ReadToken(contextTokenString);\n JsonWebSecurityToken jsonToken = securityToken as JsonWebSecurityToken;\n SharePointContextToken token = SharePointContextToken.Create(jsonToken);\n\n string stsAuthority = (new Uri(token.SecurityTokenServiceUri)).Authority;\n int firstDot = stsAuthority.IndexOf('.');\n\n GlobalEndPointPrefix = stsAuthority.Substring(0, firstDot);\n AcsHostUrl = stsAuthority.Substring(firstDot + 1);\n\n tokenHandler.ValidateToken(jsonToken);\n\n string[] acceptableAudiences;\n if (!String.IsNullOrEmpty(HostedAppHostNameOverride))\n {\n acceptableAudiences = HostedAppHostNameOverride.Split(';');\n }\n else if (appHostName == null)\n {\n acceptableAudiences = new[] { HostedAppHostName };\n }\n else\n {\n acceptableAudiences = new[] { appHostName };\n }\n\n bool validationSuccessful = false;\n string realm = Realm ?? token.Realm;\n foreach (var audience in acceptableAudiences)\n {\n string principal = GetFormattedPrincipal(ClientId, audience, realm);\n if (StringComparer.OrdinalIgnoreCase.Equals(token.Audience, principal))\n {\n validationSuccessful = true;\n break;\n }\n }\n\n if (!validationSuccessful)\n {\n throw new AudienceUriValidationFailedException(\n String.Format(CultureInfo.CurrentCulture,\n \"\\\"{0}\\\" is not the intended audience \\\"{1}\\\"\", String.Join(\";\", acceptableAudiences), token.Audience));\n }\n\n return token;\n }\n\n /// \n /// Retrieves an access token from ACS to call the source of the specified context token at the specified \n /// targetHost. The targetHost must be registered for the principal that sent the context token.\n /// \n /// Context token issued by the intended access token audience\n /// Url authority of the target principal\n /// An access token with an audience matching the context token's source\n public static OAuth2AccessTokenResponse GetAccessToken(SharePointContextToken contextToken, string targetHost)\n {\n string targetPrincipalName = contextToken.TargetPrincipalName;\n\n // Extract the refreshToken from the context token\n string refreshToken = contextToken.RefreshToken;\n\n if (String.IsNullOrEmpty(refreshToken))\n {\n return null;\n }\n\n string targetRealm = Realm ?? contextToken.Realm;\n\n return GetAccessToken(refreshToken,\n targetPrincipalName,\n targetHost,\n targetRealm);\n }\n\n /// \n /// Uses the specified authorization code to retrieve an access token from ACS to call the specified principal \n /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is \n /// null, the \"Realm\" setting in web.config will be used instead.\n /// \n /// Authorization code to exchange for access token\n /// Name of the target principal to retrieve an access token for\n /// Url authority of the target principal\n /// Realm to use for the access token's nameid and audience\n /// Redirect URI registered for this add-in\n /// An access token with an audience of the target principal\n public static OAuth2AccessTokenResponse GetAccessToken(\n string authorizationCode,\n string targetPrincipalName,\n string targetHost,\n string targetRealm,\n Uri redirectUri)\n {\n if (targetRealm == null)\n {\n targetRealm = Realm;\n }\n\n string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);\n string clientId = GetFormattedPrincipal(ClientId, null, targetRealm);\n\n // Create request for token. The RedirectUri is null here. This will fail if redirect uri is registered\n OAuth2AccessTokenRequest oauth2Request =\n OAuth2MessageFactory.CreateAccessTokenRequestWithAuthorizationCode(\n clientId,\n ClientSecret,\n authorizationCode,\n redirectUri,\n resource);\n\n // Get token\n OAuth2S2SClient client = new OAuth2S2SClient();\n OAuth2AccessTokenResponse oauth2Response;\n try\n {\n oauth2Response =\n client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;\n }\n catch (WebException wex)\n {\n using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))\n {\n string responseText = sr.ReadToEnd();\n throw new WebException(wex.Message + \" - \" + responseText, wex);\n }\n }\n\n return oauth2Response;\n }\n\n /// \n /// Uses the specified refresh token to retrieve an access token from ACS to call the specified principal \n /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is \n /// null, the \"Realm\" setting in web.config will be used instead.\n /// \n /// Refresh token to exchange for access token\n /// Name of the target principal to retrieve an access token for\n /// Url authority of the target principal\n /// Realm to use for the access token's nameid and audience\n /// An access token with an audience of the target principal\n public static OAuth2AccessTokenResponse GetAccessToken(\n string refreshToken,\n string targetPrincipalName,\n string targetHost,\n string targetRealm)\n {\n if (targetRealm == null)\n {\n targetRealm = Realm;\n }\n\n string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);\n string clientId = GetFormattedPrincipal(ClientId, null, targetRealm);\n\n OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithRefreshToken(clientId, ClientSecret, refreshToken, resource);\n\n // Get token\n OAuth2S2SClient client = new OAuth2S2SClient();\n OAuth2AccessTokenResponse oauth2Response;\n try\n {\n oauth2Response =\n client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;\n }\n catch (WebException wex)\n {\n using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))\n {\n string responseText = sr.ReadToEnd();\n throw new WebException(wex.Message + \" - \" + responseText, wex);\n }\n }\n\n return oauth2Response;\n }\n\n /// \n /// Retrieves an app-only access token from ACS to call the specified principal \n /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is \n /// null, the \"Realm\" setting in web.config will be used instead.\n /// \n /// Name of the target principal to retrieve an access token for\n /// Url authority of the target principal\n /// Realm to use for the access token's nameid and audience\n /// An access token with an audience of the target principal\n public static OAuth2AccessTokenResponse GetAppOnlyAccessToken(\n string targetPrincipalName,\n string targetHost,\n string targetRealm)\n {\n\n if (targetRealm == null)\n {\n targetRealm = Realm;\n }\n\n string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);\n string clientId = GetFormattedPrincipal(ClientId, HostedAppHostName, targetRealm);\n\n OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithClientCredentials(clientId, ClientSecret, resource);\n oauth2Request.Resource = resource;\n\n // Get token\n OAuth2S2SClient client = new OAuth2S2SClient();\n\n OAuth2AccessTokenResponse oauth2Response;\n try\n {\n oauth2Response =\n client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;\n }\n catch (WebException wex)\n {\n using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))\n {\n string responseText = sr.ReadToEnd();\n throw new WebException(wex.Message + \" - \" + responseText, wex);\n }\n }\n\n return oauth2Response;\n }\n\n /// \n /// Creates a client context based on the properties of a remote event receiver\n /// \n /// Properties of a remote event receiver\n /// A ClientContext ready to call the web where the event originated\n public static ClientContext CreateRemoteEventReceiverClientContext(SPRemoteEventProperties properties)\n {\n Uri sharepointUrl;\n if (properties.ListEventProperties != null)\n {\n sharepointUrl = new Uri(properties.ListEventProperties.WebUrl);\n }\n else if (properties.ItemEventProperties != null)\n {\n sharepointUrl = new Uri(properties.ItemEventProperties.WebUrl);\n }\n else if (properties.WebEventProperties != null)\n {\n sharepointUrl = new Uri(properties.WebEventProperties.FullUrl);\n }\n else\n {\n return null;\n }\n\n if (IsHighTrustApp())\n {\n return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null);\n }\n\n return CreateAcsClientContextForUrl(properties, sharepointUrl);\n }\n\n /// \n /// Creates a client context based on the properties of an add-in event\n /// \n /// Properties of an add-in event\n /// True to target the app web, false to target the host web\n /// A ClientContext ready to call the app web or the parent web\n public static ClientContext CreateAppEventClientContext(SPRemoteEventProperties properties, bool useAppWeb)\n {\n if (properties.AppEventProperties == null)\n {\n return null;\n }\n\n Uri sharepointUrl = useAppWeb ? properties.AppEventProperties.AppWebFullUrl : properties.AppEventProperties.HostWebFullUrl;\n if (IsHighTrustApp())\n {\n return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null);\n }\n\n return CreateAcsClientContextForUrl(properties, sharepointUrl);\n }\n\n /// \n /// Retrieves an access token from ACS using the specified authorization code, and uses that access token to \n /// create a client context\n /// \n /// Url of the target SharePoint site\n /// Authorization code to use when retrieving the access token from ACS\n /// Redirect URI registered for this add-in\n /// A ClientContext ready to call targetUrl with a valid access token\n public static ClientContext GetClientContextWithAuthorizationCode(\n string targetUrl,\n string authorizationCode,\n Uri redirectUri)\n {\n return GetClientContextWithAuthorizationCode(targetUrl, SharePointPrincipal, authorizationCode, GetRealmFromTargetUrl(new Uri(targetUrl)), redirectUri);\n }\n\n /// \n /// Retrieves an access token from ACS using the specified authorization code, and uses that access token to \n /// create a client context\n /// \n /// Url of the target SharePoint site\n /// Name of the target SharePoint principal\n /// Authorization code to use when retrieving the access token from ACS\n /// Realm to use for the access token's nameid and audience\n /// Redirect URI registered for this add-in\n /// A ClientContext ready to call targetUrl with a valid access token\n public static ClientContext GetClientContextWithAuthorizationCode(\n string targetUrl,\n string targetPrincipalName,\n string authorizationCode,\n string targetRealm,\n Uri redirectUri)\n {\n Uri targetUri = new Uri(targetUrl);\n\n string accessToken =\n GetAccessToken(authorizationCode, targetPrincipalName, targetUri.Authority, targetRealm, redirectUri).AccessToken;\n\n return GetClientContextWithAccessToken(targetUrl, accessToken);\n }\n\n /// \n /// Uses the specified access token to create a client context\n /// \n /// Url of the target SharePoint site\n /// Access token to be used when calling the specified targetUrl\n /// A ClientContext ready to call targetUrl with the specified access token\n public static ClientContext GetClientContextWithAccessToken(string targetUrl, string accessToken)\n {\n ClientContext clientContext = new ClientContext(targetUrl);\n\n clientContext.AuthenticationMode = ClientAuthenticationMode.Anonymous;\n clientContext.FormDigestHandlingEnabled = false;\n clientContext.ExecutingWebRequest +=\n delegate(object oSender, WebRequestEventArgs webRequestEventArgs)\n {\n webRequestEventArgs.WebRequestExecutor.RequestHeaders[\"Authorization\"] =\n \"Bearer \" + accessToken;\n };\n\n return clientContext;\n }\n\n /// \n /// Retrieves an access token from ACS using the specified context token, and uses that access token to create\n /// a client context\n /// \n /// Url of the target SharePoint site\n /// Context token received from the target SharePoint site\n /// Url authority of the hosted add-in. If this is null, the value in the HostedAppHostName\n /// of web.config will be used instead\n /// A ClientContext ready to call targetUrl with a valid access token\n public static ClientContext GetClientContextWithContextToken(\n string targetUrl,\n string contextTokenString,\n string appHostUrl)\n {\n SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, appHostUrl);\n\n Uri targetUri = new Uri(targetUrl);\n\n string accessToken = GetAccessToken(contextToken, targetUri.Authority).AccessToken;\n\n return GetClientContextWithAccessToken(targetUrl, accessToken);\n }\n\n /// \n /// Returns the SharePoint url to which the add-in should redirect the browser to request consent and get back\n /// an authorization code.\n /// \n /// Absolute Url of the SharePoint site\n /// Space-delimited permissions to request from the SharePoint site in \"shorthand\" format \n /// (e.g. \"Web.Read Site.Write\")\n /// Url of the SharePoint site's OAuth authorization page\n public static string GetAuthorizationUrl(string contextUrl, string scope)\n {\n return string.Format(\n \"{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code\",\n EnsureTrailingSlash(contextUrl),\n AuthorizationPage,\n ClientId,\n scope);\n }\n\n /// \n /// Returns the SharePoint url to which the add-in should redirect the browser to request consent and get back\n /// an authorization code.\n /// \n /// Absolute Url of the SharePoint site\n /// Space-delimited permissions to request from the SharePoint site in \"shorthand\" format\n /// (e.g. \"Web.Read Site.Write\")\n /// Uri to which SharePoint should redirect the browser to after consent is \n /// granted\n /// Url of the SharePoint site's OAuth authorization page\n public static string GetAuthorizationUrl(string contextUrl, string scope, string redirectUri)\n {\n return string.Format(\n \"{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code&redirect_uri={4}\",\n EnsureTrailingSlash(contextUrl),\n AuthorizationPage,\n ClientId,\n scope,\n redirectUri);\n }\n\n /// \n /// Returns the SharePoint url to which the add-in should redirect the browser to request a new context token.\n /// \n /// Absolute Url of the SharePoint site\n /// Uri to which SharePoint should redirect the browser to with a context token\n /// Url of the SharePoint site's context token redirect page\n public static string GetAppContextTokenRequestUrl(string contextUrl, string redirectUri)\n {\n return string.Format(\n \"{0}{1}?client_id={2}&redirect_uri={3}\",\n EnsureTrailingSlash(contextUrl),\n RedirectPage,\n ClientId,\n redirectUri);\n }\n\n /// \n /// Retrieves an S2S access token signed by the application's private certificate on behalf of the specified \n /// WindowsIdentity and intended for the SharePoint at the targetApplicationUri. If no Realm is specified in \n /// web.config, an auth challenge will be issued to the targetApplicationUri to discover it.\n /// \n /// Url of the target SharePoint site\n /// Windows identity of the user on whose behalf to create the access token\n /// An access token with an audience of the target principal\n public static string GetS2SAccessTokenWithWindowsIdentity(\n Uri targetApplicationUri,\n WindowsIdentity identity)\n {\n string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm;\n\n JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null;\n\n return GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims);\n }\n\n /// \n /// Retrieves an S2S client context with an access token signed by the application's private certificate on \n /// behalf of the specified WindowsIdentity and intended for application at the targetApplicationUri using the \n /// targetRealm. If no Realm is specified in web.config, an auth challenge will be issued to the \n /// targetApplicationUri to discover it.\n /// \n /// Url of the target SharePoint site\n /// Windows identity of the user on whose behalf to create the access token\n /// A ClientContext using an access token with an audience of the target application\n public static ClientContext GetS2SClientContextWithWindowsIdentity(\n Uri targetApplicationUri,\n WindowsIdentity identity)\n {\n string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm;\n\n JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null;\n\n string accessToken = GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims);\n\n return GetClientContextWithAccessToken(targetApplicationUri.ToString(), accessToken);\n }\n\n /// \n /// Get authentication realm from SharePoint\n /// \n /// Url of the target SharePoint site\n /// String representation of the realm GUID\n public static string GetRealmFromTargetUrl(Uri targetApplicationUri)\n {\n WebRequest request = WebRequest.Create(targetApplicationUri + \"/_vti_bin/client.svc\");\n request.Headers.Add(\"Authorization: Bearer \");\n\n try\n {\n using (request.GetResponse())\n {\n }\n }\n catch (WebException e)\n {\n if (e.Response == null)\n {\n return null;\n }\n\n string bearerResponseHeader = e.Response.Headers[\"WWW-Authenticate\"];\n if (string.IsNullOrEmpty(bearerResponseHeader))\n {\n return null;\n }\n\n const string bearer = \"Bearer realm=\\\"\";\n int bearerIndex = bearerResponseHeader.IndexOf(bearer, StringComparison.Ordinal);\n if (bearerIndex < 0)\n {\n return null;\n }\n\n int realmIndex = bearerIndex + bearer.Length;\n\n if (bearerResponseHeader.Length >= realmIndex + 36)\n {\n string targetRealm = bearerResponseHeader.Substring(realmIndex, 36);\n\n Guid realmGuid;\n\n if (Guid.TryParse(targetRealm, out realmGuid))\n {\n return targetRealm;\n }\n }\n }\n return null;\n }\n\n /// \n /// Determines if this is a high trust add-in.\n /// \n /// True if this is a high trust add-in.\n public static bool IsHighTrustApp()\n {\n return SigningCredentials != null;\n }\n\n /// \n /// Ensures that the specified URL ends with '/' if it is not null or empty.\n /// \n /// The url.\n /// The url ending with '/' if it is not null or empty.\n public static string EnsureTrailingSlash(string url)\n {\n if (!string.IsNullOrEmpty(url) && url[url.Length - 1] != '/')\n {\n return url + \"/\";\n }\n\n return url;\n }\n\n #endregion\n\n #region private fields\n\n //\n // Configuration Constants\n // \n\n private const string AuthorizationPage = \"_layouts/15/OAuthAuthorize.aspx\";\n private const string RedirectPage = \"_layouts/15/AppRedirect.aspx\";\n private const string AcsPrincipalName = \"00000001-0000-0000-c000-000000000000\";\n private const string AcsMetadataEndPointRelativeUrl = \"metadata/json/1\";\n private const string S2SProtocol = \"OAuth2\";\n private const string DelegationIssuance = \"DelegationIssuance1.0\";\n private const string NameIdentifierClaimType = JsonWebTokenConstants.ReservedClaims.NameIdentifier;\n private const string TrustedForImpersonationClaimType = \"trustedfordelegation\";\n private const string ActorTokenClaimType = JsonWebTokenConstants.ReservedClaims.ActorToken;\n\n //\n // Environment Constants\n //\n\n private static string GlobalEndPointPrefix = \"accounts\";\n private static string AcsHostUrl = \"accesscontrol.windows.net\";\n\n //\n // Hosted add-in configuration\n //\n private static readonly string ClientId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get(\"ClientId\")) ? WebConfigurationManager.AppSettings.Get(\"HostedAppName\") : WebConfigurationManager.AppSettings.Get(\"ClientId\");\n private static readonly string IssuerId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get(\"IssuerId\")) ? ClientId : WebConfigurationManager.AppSettings.Get(\"IssuerId\");\n private static readonly string HostedAppHostNameOverride = WebConfigurationManager.AppSettings.Get(\"HostedAppHostNameOverride\");\n private static readonly string HostedAppHostName = WebConfigurationManager.AppSettings.Get(\"HostedAppHostName\");\n private static readonly string ClientSecret = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get(\"ClientSecret\")) ? WebConfigurationManager.AppSettings.Get(\"HostedAppSigningKey\") : WebConfigurationManager.AppSettings.Get(\"ClientSecret\");\n private static readonly string SecondaryClientSecret = WebConfigurationManager.AppSettings.Get(\"SecondaryClientSecret\");\n private static readonly string Realm = WebConfigurationManager.AppSettings.Get(\"Realm\");\n private static readonly string ServiceNamespace = WebConfigurationManager.AppSettings.Get(\"Realm\");\n\n private static readonly string ClientSigningCertificatePath = WebConfigurationManager.AppSettings.Get(\"ClientSigningCertificatePath\");\n private static readonly string ClientSigningCertificatePassword = WebConfigurationManager.AppSettings.Get(\"ClientSigningCertificatePassword\");\n private static readonly X509Certificate2 ClientCertificate = (string.IsNullOrEmpty(ClientSigningCertificatePath) || string.IsNullOrEmpty(ClientSigningCertificatePassword)) ? null : new X509Certificate2(ClientSigningCertificatePath, ClientSigningCertificatePassword);\n private static readonly X509SigningCredentials SigningCredentials = (ClientCertificate == null) ? null : new X509SigningCredentials(ClientCertificate, SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest);\n\n #endregion\n\n #region private methods\n\n private static ClientContext CreateAcsClientContextForUrl(SPRemoteEventProperties properties, Uri sharepointUrl)\n {\n string contextTokenString = properties.ContextToken;\n\n if (String.IsNullOrEmpty(contextTokenString))\n {\n return null;\n }\n\n SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, OperationContext.Current.IncomingMessageHeaders.To.Host);\n string accessToken = GetAccessToken(contextToken, sharepointUrl.Authority).AccessToken;\n\n return GetClientContextWithAccessToken(sharepointUrl.ToString(), accessToken);\n }\n\n private static string GetAcsMetadataEndpointUrl()\n {\n return Path.Combine(GetAcsGlobalEndpointUrl(), AcsMetadataEndPointRelativeUrl);\n }\n\n private static string GetFormattedPrincipal(string principalName, string hostName, string realm)\n {\n if (!String.IsNullOrEmpty(hostName))\n {\n return String.Format(CultureInfo.InvariantCulture, \"{0}/{1}@{2}\", principalName, hostName, realm);\n }\n\n return String.Format(CultureInfo.InvariantCulture, \"{0}@{1}\", principalName, realm);\n }\n\n private static string GetAcsPrincipalName(string realm)\n {\n return GetFormattedPrincipal(AcsPrincipalName, new Uri(GetAcsGlobalEndpointUrl()).Host, realm);\n }\n\n private static string GetAcsGlobalEndpointUrl()\n {\n return String.Format(CultureInfo.InvariantCulture, \"https://{0}.{1}/\", GlobalEndPointPrefix, AcsHostUrl);\n }\n\n private static JsonWebSecurityTokenHandler CreateJsonWebSecurityTokenHandler()\n {\n JsonWebSecurityTokenHandler handler = new JsonWebSecurityTokenHandler();\n handler.Configuration = new SecurityTokenHandlerConfiguration();\n handler.Configuration.AudienceRestriction = new AudienceRestriction(AudienceUriMode.Never);\n handler.Configuration.CertificateValidator = X509CertificateValidator.None;\n\n List securityKeys = new List();\n securityKeys.Add(Convert.FromBase64String(ClientSecret));\n if (!string.IsNullOrEmpty(SecondaryClientSecret))\n {\n securityKeys.Add(Convert.FromBase64String(SecondaryClientSecret));\n }\n\n List securityTokens = new List();\n securityTokens.Add(new MultipleSymmetricKeySecurityToken(securityKeys));\n\n handler.Configuration.IssuerTokenResolver =\n SecurityTokenResolver.CreateDefaultSecurityTokenResolver(\n new ReadOnlyCollection(securityTokens),\n false);\n SymmetricKeyIssuerNameRegistry issuerNameRegistry = new SymmetricKeyIssuerNameRegistry();\n foreach (byte[] securitykey in securityKeys)\n {\n issuerNameRegistry.AddTrustedIssuer(securitykey, GetAcsPrincipalName(ServiceNamespace));\n }\n handler.Configuration.IssuerNameRegistry = issuerNameRegistry;\n return handler;\n }\n\n private static string GetS2SAccessTokenWithClaims(\n string targetApplicationHostName,\n string targetRealm,\n IEnumerable claims)\n {\n return IssueToken(\n ClientId,\n IssuerId,\n targetRealm,\n SharePointPrincipal,\n targetRealm,\n targetApplicationHostName,\n true,\n claims,\n claims == null);\n }\n\n private static JsonWebTokenClaim[] GetClaimsWithWindowsIdentity(WindowsIdentity identity)\n {\n JsonWebTokenClaim[] claims = new JsonWebTokenClaim[]\n {\n new JsonWebTokenClaim(NameIdentifierClaimType, identity.User.Value.ToLower()),\n new JsonWebTokenClaim(\"nii\", \"urn:office:idp:activedirectory\")\n };\n return claims;\n }\n\n private static string IssueToken(\n string sourceApplication,\n string issuerApplication,\n string sourceRealm,\n string targetApplication,\n string targetRealm,\n string targetApplicationHostName,\n bool trustedForDelegation,\n IEnumerable claims,\n bool appOnly = false)\n {\n if (null == SigningCredentials)\n {\n throw new InvalidOperationException(\"SigningCredentials was not initialized\");\n }\n\n #region Actor token\n\n string issuer = string.IsNullOrEmpty(sourceRealm) ? issuerApplication : string.Format(\"{0}@{1}\", issuerApplication, sourceRealm);\n string nameid = string.IsNullOrEmpty(sourceRealm) ? sourceApplication : string.Format(\"{0}@{1}\", sourceApplication, sourceRealm);\n string audience = string.Format(\"{0}/{1}@{2}\", targetApplication, targetApplicationHostName, targetRealm);\n\n List actorClaims = new List();\n actorClaims.Add(new JsonWebTokenClaim(JsonWebTokenConstants.ReservedClaims.NameIdentifier, nameid));\n if (trustedForDelegation && !appOnly)\n {\n actorClaims.Add(new JsonWebTokenClaim(TrustedForImpersonationClaimType, \"true\"));\n }\n\n // Create token\n JsonWebSecurityToken actorToken = new JsonWebSecurityToken(\n issuer: issuer,\n audience: audience,\n validFrom: DateTime.UtcNow,\n validTo: DateTime.UtcNow.Add(HighTrustAccessTokenLifetime),\n signingCredentials: SigningCredentials,\n claims: actorClaims);\n\n string actorTokenString = new JsonWebSecurityTokenHandler().WriteTokenAsString(actorToken);\n\n if (appOnly)\n {\n // App-only token is the same as actor token for delegated case\n return actorTokenString;\n }\n\n #endregion Actor token\n\n #region Outer token\n\n List outerClaims = null == claims ? new List() : new List(claims);\n outerClaims.Add(new JsonWebTokenClaim(ActorTokenClaimType, actorTokenString));\n\n JsonWebSecurityToken jsonToken = new JsonWebSecurityToken(\n nameid, // outer token issuer should match actor token nameid\n audience,\n DateTime.UtcNow,\n DateTime.UtcNow.Add(HighTrustAccessTokenLifetime),\n outerClaims);\n\n string accessToken = new JsonWebSecurityTokenHandler().WriteTokenAsString(jsonToken);\n\n #endregion Outer token\n\n return accessToken;\n }\n\n #endregion\n\n #region AcsMetadataParser\n\n // This class is used to get MetaData document from the global STS endpoint. It contains\n // methods to parse the MetaData document and get endpoints and STS certificate.\n public static class AcsMetadataParser\n {\n public static X509Certificate2 GetAcsSigningCert(string realm)\n {\n JsonMetadataDocument document = GetMetadataDocument(realm);\n\n if (null != document.keys && document.keys.Count > 0)\n {\n JsonKey signingKey = document.keys[0];\n\n if (null != signingKey && null != signingKey.keyValue)\n {\n return new X509Certificate2(Encoding.UTF8.GetBytes(signingKey.keyValue.value));\n }\n }\n\n throw new Exception(\"Metadata document does not contain ACS signing certificate.\");\n }\n\n public static string GetDelegationServiceUrl(string realm)\n {\n JsonMetadataDocument document = GetMetadataDocument(realm);\n\n JsonEndpoint delegationEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == DelegationIssuance);\n\n if (null != delegationEndpoint)\n {\n return delegationEndpoint.location;\n }\n throw new Exception(\"Metadata document does not contain Delegation Service endpoint Url\");\n }\n\n private static JsonMetadataDocument GetMetadataDocument(string realm)\n {\n string acsMetadataEndpointUrlWithRealm = String.Format(CultureInfo.InvariantCulture, \"{0}?realm={1}\",\n GetAcsMetadataEndpointUrl(),\n realm);\n byte[] acsMetadata;\n using (WebClient webClient = new WebClient())\n {\n\n acsMetadata = webClient.DownloadData(acsMetadataEndpointUrlWithRealm);\n }\n string jsonResponseString = Encoding.UTF8.GetString(acsMetadata);\n\n JavaScriptSerializer serializer = new JavaScriptSerializer();\n JsonMetadataDocument document = serializer.Deserialize(jsonResponseString);\n\n if (null == document)\n {\n throw new Exception(\"No metadata document found at the global endpoint \" + acsMetadataEndpointUrlWithRealm);\n }\n\n return document;\n }\n\n public static string GetStsUrl(string realm)\n {\n JsonMetadataDocument document = GetMetadataDocument(realm);\n\n JsonEndpoint s2sEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == S2SProtocol);\n\n if (null != s2sEndpoint)\n {\n return s2sEndpoint.location;\n }\n\n throw new Exception(\"Metadata document does not contain STS endpoint url\");\n }\n\n private class JsonMetadataDocument\n {\n public string serviceName { get; set; }\n public List endpoints { get; set; }\n public List keys { get; set; }\n }\n\n private class JsonEndpoint\n {\n public string location { get; set; }\n public string protocol { get; set; }\n public string usage { get; set; }\n }\n\n private class JsonKeyValue\n {\n public string type { get; set; }\n public string value { get; set; }\n }\n\n private class JsonKey\n {\n public string usage { get; set; }\n public JsonKeyValue keyValue { get; set; }\n }\n }\n\n #endregion\n }\n\n /// \n /// A JsonWebSecurityToken generated by SharePoint to authenticate to a 3rd party application and allow callbacks using a refresh token\n /// \n public class SharePointContextToken : JsonWebSecurityToken\n {\n public static SharePointContextToken Create(JsonWebSecurityToken contextToken)\n {\n return new SharePointContextToken(contextToken.Issuer, contextToken.Audience, contextToken.ValidFrom, contextToken.ValidTo, contextToken.Claims);\n }\n\n public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable claims)\n : base(issuer, audience, validFrom, validTo, claims)\n {\n }\n\n public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable claims, SecurityToken issuerToken, JsonWebSecurityToken actorToken)\n : base(issuer, audience, validFrom, validTo, claims, issuerToken, actorToken)\n {\n }\n\n public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable claims, SigningCredentials signingCredentials)\n : base(issuer, audience, validFrom, validTo, claims, signingCredentials)\n {\n }\n\n public string NameId\n {\n get\n {\n return GetClaimValue(this, \"nameid\");\n }\n }\n\n /// \n /// The principal name portion of the context token's \"appctxsender\" claim\n /// \n public string TargetPrincipalName\n {\n get\n {\n string appctxsender = GetClaimValue(this, \"appctxsender\");\n\n if (appctxsender == null)\n {\n return null;\n }\n\n return appctxsender.Split('@')[0];\n }\n }\n\n /// \n /// The context token's \"refreshtoken\" claim\n /// \n public string RefreshToken\n {\n get\n {\n return GetClaimValue(this, \"refreshtoken\");\n }\n }\n\n /// \n /// The context token's \"CacheKey\" claim\n /// \n public string CacheKey\n {\n get\n {\n string appctx = GetClaimValue(this, \"appctx\");\n if (appctx == null)\n {\n return null;\n }\n\n ClientContext ctx = new ClientContext(\"http://tempuri.org\");\n Dictionary dict = (Dictionary)ctx.ParseObjectFromJsonString(appctx);\n string cacheKey = (string)dict[\"CacheKey\"];\n\n return cacheKey;\n }\n }\n\n /// \n /// The context token's \"SecurityTokenServiceUri\" claim\n /// ", "answers": [" public string SecurityTokenServiceUri"], "length": 3703, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "3ec69550-af2a-46cb-a17e-46ab91860b4b", "reasoning": "The comment just introduced a property for the SecurityTokenServiceUri claim. In the SharePointContextToken class, the next line defines the property header before its getter block. Therefore the next line of code is the property declaration line.", "reasoning_model_answer": "public string SecurityTokenServiceUri", "assistant_with_reasoning": "\nThe comment just introduced a property for the SecurityTokenServiceUri claim. In the SharePointContextToken class, the next line defines the property header before its getter block. Therefore the next line of code is the property declaration line.\n\npublic string SecurityTokenServiceUri", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 6.164, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 46915, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "public string SecurityTokenServiceUri", "score": 0.9, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/*\n Solar Recharge Platform (SRP)\n\nCopyright 2015 Nick West\nReleased under CC0 1.0 Universal (Public Domain)\n ^ This licenses lets you do pretty much whatever you want with the below code without credit or anything\n\nPurpose:\n Automated alignment of Solar Recharge Platform (SRP for short, which is basically any ship with solar panels) with sun for optimal power production.\n Also includes battery management with automated charging of batteries that are docked to the SRP.\n Works on both large and small ships, can be used on satelites/antenna relays/probes/etc.\n\nSolar Alignment\n Ship self aligns to point solar panels toward the sun\n Averages the power across multiple solar panels when aligning for optimization\n Uses all Gyros on the ship to make the alignment (Requires Gyros set to \"overide\" for auto-alignment to work)\n Adjustable minimum value for power (Large solar panel max of 120 kW, default set to 118 kW, small solar panel max out of 22 kW, default is set to 20.5).\n Adjustable turn speed (higher numbers mean faster turns but also lower accuracy for alignment, if speed is high keep min val lower).\n\nBattery management:\n Batteries that are attached to the SRP will be used to suppliment solar power when charging docked Batteries for maximum charging speed\n Any battery on a ship that docks with the SRP will be set to recharge or off upon docking (optional with config below)\n All docked batteries will fully charge and have charging priority over SRP batteries\n When all docked batteries are charged, or there is extra solar power, SRP batteries will be set to recharge automatically (but only if the solar array is optimal)\n Battery management can be turned off with a config option below\n\n\nRequired for alignment:\n 1 or more Gyroscopes (TODO??if multiple gyros they all have to be facing the same way??)\n 1 or more Solar Panels\n 1 Programmable Block\n 1 Timer Block\n * Set for 2 seconds (you can play with different interval speeds, 2 works well though)\n * Have it run the Programmable Block and start its own timer. (to make the program loop)\n\nOptional:\n 1 or more batteries on the station\n 1 or more batteries docked to the station (via a connector, piston, or rotor)\n * Merged blocks show up as being owned by the main grid, whereas docked blocks show as being seperate\n * Blocks attached via landing gear only will not show on the grid and cannot have their batteries charged\n\nInstructions for use:\n 1. You must own all parts (solar panels, gyros, batteries, programmable block, timer, etc).\n 2. Install the script onto your programmable block\n 3. Customize the Custom Variables below (read notes next to them for more info)\n 4. Set the following actions to the timer block\n a. Run programmable block\n b. start timer on this timer block\n 5. (optional, but recommended) Position your array so it's pointed toward the sun rather than away it\n depending on ship config, it could get stuck faced away from the sun if it doesn't start facing it\n 6. Set all gyros to \"overide\" (unless you changed automaticGyroControl to true, then this step is not necessary)\n 7. Bask in the glory as your Solar Recharge Platform moves to face the sun, and your power generation reaches peak values and sustains them.\n\nNotes:\n I recommend leaving the autoGyroOverride set to false and then manually toggling your gyros from override to not.\n This leaves you in control of when the ship will be controllable and not. Otherwise you have to stop the timer to take contorl of the ship\n All solar panels should point the same way OR adjust the minPwr variable lower to compensate since it's impossible to get all panels at 98% if they can't all face the sun at once\n No custom names for blocks are needed, and this script will not rename any of your blocks :)\n If you're not running the game in English, locate the regex strings (not far below) and adjust them to match your language (I'll look for a better way to do this)\n\nCredit:\n This script was inspired by Kir's \"Self-Aligning Solar Panels For Ships With Gyros\" script\n Found here: http://steamcommunity.com/sharedfiles/filedetails/?id=369286464\n\n Thanks to Me 10 Jin's regex example for extracting detailed data from solar panels and batteries\n Found here: http://forum.keenswh.com/threads/regular-expressions-example-reactor-usage.7226038/\n*/\n\n//***********************************************************************************************************************************\n//**************************************************** Custom Variables *************************************************************\n//***********************************************************************************************************************************\n\n// TODO: Auto detect if possible\nconst string shipType = \"large\"; // Can be \"large\" or \"small\", used to calculate solar power efficiency (small panels have a different max output)\nconst double minPwrPercent = 98; // Minimum power percentage [Note: going over 100% will make the SRP constantly seek the sun. Similarly any percent close to 100 could result in constant seeking if percentage is not achievable with Solar Panel Configuration]\nconst float turnSpeed = 2.5f; // Turn speed of craft, slower means more precision, you can adjust timer block to faster tick if you set this to be faster\n\n/********************************\n * INFO ABOUT SELECTING CONTROLS:\n * - For optimal alignment speed you don't want your solar panels to spin flat\n * For bottom/top facing solar panels - Roll + Pitch should be used\n * For front/back facing solar panels - Pitch + Yaw should be used\n * Fot right/left facing solar panels - Roll + Yaw should be used\n ********************************/\nconst string control1 = \"Roll\"; // First control to use on the Gyro to position\nconst string control2 = \"Pitch\"; // Second control to use on the Gyro to position\n\nconst bool autoGyroOverride = false; // When set to true, the script will turn all gyros to override automatically while aligning to the sun\n // It will also then release the override when alignment is optimal (restoring pilot control of gyros)\n // The alternate to this is to manually control the overide (leave it on, except when you want to \"drive\") <- I prefer this way\n\nconst bool batteryManagement = true; // If this is set to false, battery management won't happen, but Gyro positioning still will\nconst bool chargeDockedBatteries = true; // If batteryManagement is set to false, this does nothing. Otherwise it allows this script to manage docked batteries as well (useful for SRPs)\nconst bool keepBatteriesOn = true; // Keep batteries on and discharging except when solar is full power [Note: recommended to prevent complete power failures]\n\n//***********************************************************************************************************************************\n//********************************************** Shouldn't need to edit below here but might ****************************************\n//***********************************************************************************************************************************\n\n//-- Constants & Debug flags\n\n// Don't change these unless a game update changes them (Watts) //TODO: Verify these values and/or get them automatically\nconst int smallBatteryMax = 4320000;\nconst int largeBatteryMax = 12000000;\nconst int smallSolarPanelMax = 30000;\nconst int largeSolarPanelMax = 120000;\n\n// Flipping these to true will Echo out various debug info (I didn't bother to pull this out, but you'll have to look at code to see what it's echoing exactly)\nbool debugMain = false;\nbool debugAlignment = false;\nbool debugBat = false;\n\n//-- These probably need to be adjusted based on localization (just change the English words to whatever matches the language you're using)\n\n// TODO: Fix localization issues with these Regex patterns. Instead, assume positions based on line\n// Example: someBlock.DetailedInfo.Split(new string[] { \"\\r\\n\", \"\\n\", \"\\r\" }, StringSplitOptions.None);\n\n// regex to get max and current output from solar panel details\nSystem.Text.RegularExpressions.Regex solarPwrRegex = new System.Text.RegularExpressions.Regex(\n \"Max Output: (\\\\d+\\\\.?\\\\d*) (\\\\w?)W.*Current Output: (\\\\d+\\\\.?\\\\d*) (\\\\w?)W\",\n System.Text.RegularExpressions.RegexOptions.Singleline\n);\n\n// regex to get power data from battery details.\nSystem.Text.RegularExpressions.Regex batteryRegex = new System.Text.RegularExpressions.Regex(\n \"Max Output: (\\\\d+\\\\.?\\\\d*) (\\\\w?)W.*Max Required Input: (\\\\d+\\\\.?\\\\d*) (\\\\w?)W.*Max Stored Power: (\\\\d+\\\\.?\\\\d*) (\\\\w?)Wh.*Current Input: (\\\\d+\\\\.?\\\\d*) (\\\\w?)W.*Current Output: (\\\\d+\\\\.?\\\\d*) (\\\\w?)W.*Stored power: (\\\\d+\\\\.?\\\\d*) (\\\\w?)Wh\",\n System.Text.RegularExpressions.RegexOptions.Singleline\n);\n\n// Global variables until this all becomes a class\nList srpSolarBlocks = null; // Local grid only\nList srpGyroBlocks = null; // Local grid only\nList srpBatteryBlocks = null; // Local grid only\nList dockedBatteryBlocks = null; // Non-Local grid only\n\nIMyProgrammableBlock thisProgrammableBlock = null; // This programmable block (used for identifying local grid)\n\ndouble currentPwr; // Stores the current power generated by the solar panel\ndouble lastPwr; // Stores the power generated by the solar panel at the previous alignment\ndouble highestPwr = 0; // Stores highest power value\ndouble minPwr; // Minimum acceptable power (based on percentage & ship type defined above)\n\n/**\n *\tEntry point of script\n *\n * \t@return void\n */\nvoid Main()\n{\n // Get the ProgrammableBlock this is running on\n thisProgrammableBlock = getSelf();\n\n // Instantiate Lists\n srpSolarBlocks = new List();\n srpGyroBlocks = new List();\n srpBatteryBlocks = new List();\n dockedBatteryBlocks = new List();\n\n // Populate Lists\n GridTerminalSystem.GetBlocksOfType(srpSolarBlocks, filterSRPSolarPanels); // Find all the SRP solar panels\n GridTerminalSystem.GetBlocksOfType(srpGyroBlocks, filterSRPGyros); // Find all the SRP gyros\n GridTerminalSystem.GetBlocksOfType(srpBatteryBlocks, filterSRPBatteries); // Find all the SRP batteries\n GridTerminalSystem.GetBlocksOfType(dockedBatteryBlocks, filterDockedBatteries);// Find all the docked batteries\n\n // If there aren't Gyros, we can't position, so throw an exception\n if(srpGyroBlocks.Count <= 0){\n throw new System.ArgumentException(\"No Gyros Found, Cannot Position!\", \"CAT\");\n }\n\n // Calculate the minimum solar panel output we'll accept\n minPwr = minPwrPercent / 100 * (shipType == \"large\" ? largeSolarPanelMax : smallSolarPanelMax) / 1000; // KW\n\n // Check if Solar panels exist (if not, we can't align them)\n if (srpSolarBlocks.Count > 0) {\n // Get current average power across all solar panels\n double totalPanelPwr = 0;\n double countPanels = 0;\n\n for (int i = 0; i < srpSolarBlocks.Count ; i++ ){\n countPanels++;\n\n System.Text.RegularExpressions.Match match = solarPwrRegex.Match(srpSolarBlocks[i].DetailedInfo);\n double n;\n if(match.Success ){\n // Max output of the solar panel\n if(double.TryParse( match.Groups[1].Value, out n )){\n totalPanelPwr += n * Math.Pow( 1000.0, \".kMGTPEZY\".IndexOf( match.Groups[2].Value));\n }\n }\n }\n\n // Set the current average power generated by the panels\n currentPwr = totalPanelPwr / countPanels / 1000; // KW\n\n myDebug(\"Min=\"+minPwr.ToString(), debugAlignment);\n myDebug(\"Curr=\"+currentPwr.ToString(), debugMain);\n\n // Align the solar array\n AlignSolar();\n\n }else{\n throw new System.ArgumentException(\"No Solar Panels Found\", \"CAT\");\n }\n\n // Manage the batteries if that option is seleted\n if(batteryManagement){\n manageBatteries();\n }\n\n}\n\n/**\n *\tAlign the solar array using gyros\n * TODO: Make it so this can flip 180 when it's stuck with the wrong side facing the sun\n *\n * \t@return void\n */\nvoid AlignSolar(){\n // Set the GyroState variables\n setGyroState(control1);\n setGyroState(control2);\n\n // Get the last and highest power from storage\n lastPwr = getVar(\"currentPower\");\n highestPwr = getVar(\"highestPower\");\n\n myDebug(\"Last=\"+lastPwr.ToString(), debugAlignment);\n myDebug(\"High=\"+highestPwr.ToString(), debugAlignment);\n\n // Make sure only one Gyro control is set to move and that all gyros are functioning the same way\n if(!verifyGyros()){\n myDebug(\"Reset Gyros\", debugAlignment);\n // Stop moving\n zeroGyros();\n\n // Clear last and highest vars\n saveVars(0,0);\n\n return;\n }\n\n // If we hit optimal power then just stay put.\n if(currentPwr >= minPwr){\n myDebug(\"SUCCESS\", debugAlignment);\n\n // Stop moving\n zeroGyros();\n\n // Clear last and highest vars\n saveVars(0,0);\n\n // Return Gyro control (if we're doing that sort of thing)\n if(autoGyroOverride){\n overrideGyros(false);\n }\n\n return;\n }else{\n // Always set the currentPower to Storage (this will be lastPwr next tick)\n saveVar(\"currentPower\", currentPwr);\n\n // Take control of Gyros (if we're doing that)\n if(autoGyroOverride){\n overrideGyros(true);\n }\n\n // Not moving, power is not optimal\n if(getGyroState(control1) == 0 & getGyroState(control2) == 0){\n myDebug(\"Just Starting (0)\", debugAlignment);\n\n // Zero out highest Power\n saveVar(\"highestPower\", 0);\n\n // Make sure the gyros reflect the known state\n zeroGyros();\n\n // Start moving in the first direction\n GyroRotation(control1, 1);\n\n return;\n }\n // Control 1 was active\n else if(getGyroState(control1) != 0){\n if(highestPwr == 0 & lastPwr == 0){ // This condition shouldn't really ever be met\n myDebug(\"Start Going (1)\", debugAlignment);\n\n return;\n }\n else if(highestPwr == 0 & currentPwr < lastPwr){\n myDebug(\"Reverse direction (1)\", debugAlignment);\n\n GyroRotation(control1, -1 * getGyroState(control1));\n\n return;\n }\n else if(currentPwr >= lastPwr){\n myDebug(\"Keep Going (1)\", debugAlignment);\n\n // Save highest power\n highestPwr = currentPwr;\n saveVar(\"highestPower\", highestPwr);\n\n return;\n }\n else{\n myDebug(\"Switch to (2)\", debugAlignment);\n\n GyroRotation(control1, 0);\n GyroRotation(control2, 1);\n\n // Clear last and highest vars\n saveVars(0,0);\n\n return;\n }\n }\n // Control 2 was active\n else if(getGyroState(control2) != 0){\n if(highestPwr == 0 & lastPwr == 0){\n myDebug(\"Start Going (2)\", debugAlignment);\n\n return;\n }\n else if(highestPwr == 0 & currentPwr < lastPwr){\n myDebug(\"Reverse direction (2)\", debugAlignment);\n\n GyroRotation(control2, -1 * getGyroState(control2));\n\n return;\n }\n else if(currentPwr >= lastPwr){\n myDebug(\"Keep Going (2)\", debugAlignment);\n\n // Save highest power\n highestPwr = currentPwr;\n saveVar(\"highestPower\", highestPwr);\n\n return;\n }\n else{\n myDebug(\"Switch to (1)\", debugAlignment);\n\n GyroRotation(control2, 0);\n GyroRotation(control1, 1);\n\n // Clear last and highest vars\n saveVars(0,0);\n\n return;\n }\n\n }\n }\n}\n\n/**\n *\tSet the gyro state based on the values in the first gyro found in gyroBlocks\n *\n * control = [\"Yaw\" | \"Pitch | \"Roll\"]\n *\n * @param string control\n * \t@return void\n */\nvoid setGyroState(string control){\n // Pick one of the gyros to look at\n IMyGyro gyroBlock = srpGyroBlocks[0] as IMyGyro;\n\n switch(control){\n case \"Yaw\":\n yaw_state = gyroBlock.Yaw == 0 ? 0 : gyroBlock.Yaw > 0 ? 1 : -1;\n break;\n case \"Roll\":\n roll_state = gyroBlock.Roll == 0 ? 0 : gyroBlock.Roll > 0 ? 1 : -1;\n break;\n case \"Pitch\":\n pitch_state = gyroBlock.Pitch == 0 ? 0 : gyroBlock.Pitch > 0 ? 1 : -1;\n break;\n }\n}\n\n/**\n *\tSet all the gyro controls to 0 so we start fresh\n *\n * \t@return void\n */\nvoid zeroGyros(){\n GyroRotation(\"Yaw\", 0);\n GyroRotation(\"Roll\", 0);\n GyroRotation(\"Pitch\", 0);\n}\n\n/**\n *\tCheck all gyros, if there are conflicting controls set, or more than 1 return false\n *\n * \t@return bool\n */\nbool verifyGyros(){\n IMyGyro tmpGyro;\n\n string type = \"\";\n float val = 0;\n for ( int i = 0; i < srpGyroBlocks.Count ; i++ ){\n tmpGyro = srpGyroBlocks[i] as IMyGyro;\n if(tmpGyro.Yaw != 0){\n if(type != \"\" & type != \"Yaw\"){\n return false;\n }else{\n if(val != 0 & tmpGyro.Yaw != val){\n return false;\n }\n type = \"Yaw\";\n val = tmpGyro.Yaw;\n }\n }\n if(tmpGyro.Pitch != 0){\n if(type != \"\" & type != \"Pitch\"){\n return false;\n }else{\n if(val != 0 & tmpGyro.Pitch != val){\n return false;\n }\n type = \"Pitch\";\n val = tmpGyro.Pitch;\n }\n }\n if(tmpGyro.Roll != 0){\n if(type != \"\" & type != \"Roll\"){\n return false;\n }else{\n if(val != 0 & tmpGyro.Roll != val){\n return false;\n }\n type = \"Roll\";\n val = tmpGyro.Roll;\n }\n }\n }\n\n return true;\n}\n\n/**\n *\tSet override on all gyros\n *\n * @param bool setOverride\n * \t@return void\n */\nvoid overrideGyros(bool setOverride){\n IMyGyro tmpGyro;\n\n for ( int i = 0; i < srpGyroBlocks.Count ; i++ ){\n tmpGyro = srpGyroBlocks[i] as IMyGyro;\n if((!tmpGyro.GyroOverride & setOverride) | (tmpGyro.GyroOverride & !setOverride)){\n tmpGyro.GetActionWithName(\"Override\").Apply(tmpGyro);\n }\n }\n}\n\n/**\n *\tGet the gyro state based on the state variables\n *\n * control = [\"Yaw\" | \"Pitch | \"Roll\"]\n *\n * @param string control\n * \t@return int\n */\nint getGyroState(string control){\n switch(control){\n case \"Yaw\":\n return yaw_state;\n break;\n case \"Roll\":\n return roll_state;\n break;\n case \"Pitch\":\n return pitch_state;\n break;\n default:\n throw new System.ArgumentException(\"Invalid control in config (must be proper case)\", \"CAT\");\n break;\n }\n return 0;\n}\n\n// More globals because this isn't encapsulated\nint yaw_state = 0;\nint pitch_state = 0;\nint roll_state = 0;\n\n/**\n *\tSet all gyros to on the given rotation control (rotation) at the given speed (val)\n *\n * rotation = [\"Yaw\" | \"Pitch | \"Roll\"]\n * val = negative or positive int\n *\n * @param string rotation\n * @param int val\n * \t@return int\n */\nvoid GyroRotation(string rotation, int val){\n switch(rotation){\n case \"Pitch\":\n pitch_state = val;\n break;\n case \"Yaw\":\n yaw_state = val;\n break;\n case \"Roll\":\n roll_state = val;\n break;\n }\n\n float speed = 0.01f * turnSpeed * val;\n for (int i = 0; i < srpGyroBlocks.Count ; i++ ){\n (srpGyroBlocks[i] as IMyGyro).SetValueFloat(rotation, speed);\n }\n}\n\n// Temp global variables\ndouble temp_output_max = 0.0;\ndouble temp_output_cur = 0.0;\ndouble temp_input_max = 0.0;\ndouble temp_input_cur = 0.0;\ndouble temp_storage_max = 0.0;\ndouble temp_storage_cur = 0.0;\n\n/**\n *\tSet battery variables from the Details tring to the temp vars\n *\n * tempBlock = any powered IMyTerminalBlock\n *\n * @param IMyTerminalBlock tempBlock\n * \t@return bool\n */\nbool setTempBatteryData(IMyTerminalBlock tempBlock){\n // If it's not a battery, get out of here\n if(!(tempBlock is IMyBatteryBlock)){\n return false;\n }\n\n // Get all the juicy info about the battery (yes this comment is a play on the word juicy)\n System.Text.RegularExpressions.Match match = batteryRegex.Match(tempBlock.DetailedInfo);\n if(match.Success){\n Double n;\n if(Double.TryParse(match.Groups[1].Value, out n)){ // max output\n temp_output_max = n * Math.Pow( 1000.0, \".kMGTPEZY\".IndexOf(match.Groups[2].Value));\n }\n if(Double.TryParse(match.Groups[3].Value, out n)){ // max input\n temp_input_max = n * Math.Pow( 1000.0, \".kMGTPEZY\".IndexOf(match.Groups[4].Value));\n }\n if(Double.TryParse(match.Groups[5].Value, out n)){ // max output\n temp_storage_max = n * Math.Pow( 1000.0, \".kMGTPEZY\".IndexOf(match.Groups[6].Value));\n }\n if(Double.TryParse(match.Groups[7].Value, out n)){ // current input\n temp_input_cur = n * Math.Pow( 1000.0, \".kMGTPEZY\".IndexOf(match.Groups[8].Value));\n }\n if(Double.TryParse(match.Groups[9].Value, out n)){ // current output\n temp_output_cur = n * Math.Pow( 1000.0, \".kMGTPEZY\".IndexOf(match.Groups[10].Value));\n }\n if(Double.TryParse(match.Groups[11].Value, out n)){ // current output\n temp_storage_cur = n * Math.Pow( 1000.0, \".kMGTPEZY\".IndexOf(match.Groups[12].Value));\n }\n return true;\n }\n return false;\n}\n\n/**\n *\tRun the battery management routine\n *\n * \t@return void\n */\nvoid manageBatteries(){\n if(srpSolarBlocks.Count > 0 & (srpBatteryBlocks.Count > 0 | dockedBatteryBlocks.Count > 0)){\n // Solar array output info\n double solarr_output_cur = 0.0;\n double solarr_output_max = 0.0;\n double solarr_output_avail = 0.0;\n\n // Solar Batteries output info\n double solbat_output_cur = 0.0;\n double solbat_output_max = 0.0;\n double solbat_output_avail = 0.0;\n double solbat_output_avail_idle = 0.0;\n\n // Solar Batteries input info\n double solbat_input_cur = 0.0;\n double solbat_input_max = 0.0;\n double solbat_input_needed = 0.0;\n\n // Ship Batteries input info\n double shipbat_input_cur = 0.0;\n double shipbat_input_max = 0.0;\n double shipbat_input_needed = 0.0;\n\n // Flags\n bool we_done = false;\n bool ship_needs_charge = false;\n bool solbat_needs_charge = false;\n\n // Math variable\n double pwrDeficit = 0;\n\n // Get Solar Array values\n for(int i = 0; i < srpSolarBlocks.Count ; i++){\n System.Text.RegularExpressions.Match match = solarPwrRegex.Match(srpSolarBlocks[i].DetailedInfo);\n Double n;\n if(match.Success ){\n // Max output of the solar panel\n if(Double.TryParse( match.Groups[1].Value, out n )){\n solarr_output_max += n * Math.Pow( 1000.0, \".kMGTPEZY\".IndexOf( match.Groups[2].Value));\n }\n // Current output of the solar panel\n if(Double.TryParse( match.Groups[3].Value, out n )){\n solarr_output_cur += n * Math.Pow( 1000.0, \".kMGTPEZY\".IndexOf( match.Groups[4].Value));\n }\n }\n }\n solarr_output_avail = solarr_output_max - solarr_output_cur; // Available power\n\n // Get docked battery info\n for(int i = 0; i < dockedBatteryBlocks.Count; i++){\n // Get the detailed power data and put it in the temp vars\n if(setTempBatteryData(dockedBatteryBlocks[i])){\n // Ship batteries are always set to recharge\n if(!dockedBatteryBlocks[i].DetailedInfo.Contains(\"recharged\")){\n dockedBatteryBlocks[i].GetActionWithName(\"Recharge\").Apply(dockedBatteryBlocks[i]);\n // Turn it off so we don't overload the array by adding a lot of new batteries at once.\n if((dockedBatteryBlocks[i] as IMyFunctionalBlock).Enabled){\n dockedBatteryBlocks[i].GetActionWithName(\"OnOff_Off\").Apply(dockedBatteryBlocks[i]);\n }\n }\n\n // If it's on and set to recharge, and it's not full, and it's functional, include it\n if((dockedBatteryBlocks[i] as IMyFunctionalBlock).Enabled & dockedBatteryBlocks[i].DetailedInfo.Contains(\"recharged\") & temp_storage_max > temp_storage_cur){\n shipbat_input_max += temp_input_max;\n shipbat_input_cur += temp_input_cur;\n }\n // If it's not full and not set to recharge, make note that we have batteries still needing charge\n else if(temp_storage_max > temp_storage_cur & !(dockedBatteryBlocks[i] as IMyFunctionalBlock).Enabled){\n ship_needs_charge = true;\n }\n }\n }\n\n // Get SRP Battery info\n for(int i = 0; i < srpBatteryBlocks.Count; i++){\n // Get the detailed power data and put it in the temp vars\n if(setTempBatteryData(srpBatteryBlocks[i])){\n // If the battery has juice avabile, then include it in the total\n if(temp_storage_cur > 0 & (srpBatteryBlocks[i] as IMyFunctionalBlock).Enabled & !srpBatteryBlocks[i].DetailedInfo.Contains(\"recharged\")){\n solbat_output_max += temp_output_max;\n solbat_output_cur += temp_output_cur;\n }else if(temp_storage_cur > 0){\n solbat_output_avail_idle += temp_output_max;\n }\n\n // If it's on and set to recharge and it's not full\n if((srpBatteryBlocks[i] as IMyFunctionalBlock).Enabled & srpBatteryBlocks[i].DetailedInfo.Contains(\"recharged\") & temp_storage_max > temp_storage_cur){\n solbat_input_max += temp_input_max;\n solbat_input_cur += temp_input_cur;\n }else if(temp_storage_max > temp_storage_cur){\n solbat_needs_charge = true;\n }\n }\n }\n\n solbat_output_avail = solbat_output_max - solbat_output_cur;\n solbat_input_needed = solbat_input_max - solbat_input_max;\n shipbat_input_needed = shipbat_input_max - shipbat_input_cur;\n\n myDebug(\"solbat_out_max: \"+solbat_output_max.ToString(), debugBat);\n myDebug(\"solarr_out_max: \"+solarr_output_max.ToString(), debugBat);", "answers": [" myDebug(\"solbat_input_max: \"+solbat_input_max.ToString(), debugBat);"], "length": 3145, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "23a9bf76-0bdf-45fc-91e9-3d89e13ee79b", "reasoning": "The code is inside the manageBatteries() function. After calculating values, it prints debug info for maximum outputs of the SRP batteries and solar array. The next logical step is to output the current output of the SRP batteries, following the same pattern of debug statements. Therefore the next line should be a myDebug call for solbat_output_cur.", "reasoning_model_answer": "myDebug(\"solbat_out_cur: \"+solbat_output_cur.ToString(), debugBat);", "assistant_with_reasoning": "\nThe code is inside the manageBatteries() function. After calculating values, it prints debug info for maximum outputs of the SRP batteries and solar array. The next logical step is to output the current output of the SRP batteries, following the same pattern of debug statements. Therefore the next line should be a myDebug call for solbat_output_cur.\n\nmyDebug(\"solbat_out_cur: \"+solbat_output_cur.ToString(), debugBat);", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 5.194, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 27617, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "myDebug(\"solbat_out_cur: \"+solbat_output_cur.ToString(), debugBat);", "score": 0.8, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "// Copyright 2015 The Bazel Authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\npackage com.google.devtools.build.lib.syntax;\n\nimport static com.google.common.truth.Truth.assertThat;\nimport static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.assertTrue;\n\nimport com.google.common.collect.ImmutableCollection;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.devtools.build.lib.actions.Artifact;\nimport com.google.devtools.build.lib.actions.Artifact.SpecialArtifact;\nimport com.google.devtools.build.lib.analysis.FileConfiguredTarget;\nimport com.google.devtools.build.lib.analysis.RuleConfiguredTarget;\nimport com.google.devtools.build.lib.analysis.TransitiveInfoCollection;\nimport com.google.devtools.build.lib.collect.nestedset.NestedSetBuilder;\nimport com.google.devtools.build.lib.skylarkinterface.Param;\nimport com.google.devtools.build.lib.skylarkinterface.SkylarkCallable;\nimport com.google.devtools.build.lib.skylarkinterface.SkylarkModule;\nimport com.google.devtools.build.lib.skylarkinterface.SkylarkSignature;\nimport com.google.devtools.build.lib.syntax.SkylarkList.MutableList;\nimport com.google.devtools.build.lib.testutil.TestMode;\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.junit.runners.JUnit4;\n\n/**\n * Evaluation tests with Skylark Environment.\n */\n@RunWith(JUnit4.class)\npublic class SkylarkEvaluationTest extends EvaluationTest {\n\n @Before\n public final void setup() throws Exception {\n setMode(TestMode.SKYLARK);\n }\n\n /**\n * Creates an instance of {@code SkylarkTest} in order to run the tests from the base class in a\n * Skylark context\n */\n @Override\n protected ModalTestCase newTest() {\n return new SkylarkTest();\n }\n\n static class Bad {\n Bad () {\n }\n }\n\n @SkylarkSignature(name = \"foobar\", returnType = String.class, documented = false)\n static BuiltinFunction foobar = new BuiltinFunction(\"foobar\") {\n public String invoke() throws EvalException {\n return \"foobar\";\n }\n };\n\n @SkylarkModule(name = \"Mock\", doc = \"\")\n static class Mock {\n @SkylarkCallable(doc = \"\")\n public static Integer valueOf(String str) {\n return Integer.valueOf(str);\n }\n @SkylarkCallable(doc = \"\")\n public Boolean isEmpty(String str) {\n return str.isEmpty();\n }\n public void value() {}\n @SkylarkCallable(doc = \"\")\n public Bad returnBad() {\n return new Bad();\n }\n @SkylarkCallable(name = \"struct_field\", doc = \"\", structField = true)\n public String structField() {\n return \"a\";\n }\n @SkylarkCallable(name = \"struct_field_callable\", doc = \"\", structField = true)\n public BuiltinFunction structFieldCallable() {\n return foobar;\n }\n @SkylarkCallable(name = \"function\", doc = \"\", structField = false)\n public String function() {\n return \"a\";\n }\n @SuppressWarnings(\"unused\")\n @SkylarkCallable(name = \"nullfunc_failing\", doc = \"\", allowReturnNones = false)\n public Object nullfuncFailing(String p1, Integer p2) {\n return null;\n }\n @SkylarkCallable(name = \"nullfunc_working\", doc = \"\", allowReturnNones = true)\n public Object nullfuncWorking() {\n return null;\n }\n @SkylarkCallable(name = \"voidfunc\", doc = \"\")\n public void voidfunc() {}\n @SkylarkCallable(name = \"string_list\", doc = \"\")\n public ImmutableList stringList() {\n return ImmutableList.of(\"a\", \"b\");\n }\n @SkylarkCallable(name = \"string\", doc = \"\")\n public String string() {\n return \"a\";\n }\n\n @SkylarkCallable(\n name = \"with_params\",\n doc = \"\",\n mandatoryPositionals = 1,\n parameters = {\n @Param(name = \"pos2\", defaultValue = \"False\", type = Boolean.class),\n @Param(\n name = \"posOrNamed\",\n defaultValue = \"False\",\n type = Boolean.class,\n positional = true,\n named = true\n ),\n @Param(name = \"named\", type = Boolean.class, positional = false, named = true),\n @Param(\n name = \"optionalNamed\",\n type = Boolean.class,\n defaultValue = \"False\",\n positional = false,\n named = true\n ),\n @Param(\n name = \"nonNoneable\",\n type = Object.class,\n defaultValue = \"\\\"a\\\"\",\n positional = false,\n named = true\n ),\n @Param(\n name = \"noneable\",\n type = Integer.class,\n defaultValue = \"None\",\n noneable = true,\n positional = false,\n named = true\n ),\n }\n )\n public String withParams(\n Integer pos1,\n boolean pos2,\n boolean posOrNamed,\n boolean named,\n boolean optionalNamed,\n Object nonNoneable,\n Object noneable) {\n return \"with_params(\"\n + pos1\n + \", \"\n + pos2\n + \", \"\n + posOrNamed\n + \", \"\n + named\n + \", \"\n + optionalNamed\n + \", \"\n + nonNoneable.toString()\n + \")\";\n }\n\n @Override\n public String toString() {\n return \"\";\n }\n }\n\n @SkylarkModule(name = \"MockInterface\", doc = \"\")\n static interface MockInterface {\n @SkylarkCallable(doc = \"\")\n public Boolean isEmptyInterface(String str);\n }\n\n static final class MockSubClass extends Mock implements MockInterface {\n @Override\n public Boolean isEmpty(String str) {\n return str.isEmpty();\n }\n @Override\n public Boolean isEmptyInterface(String str) {\n return str.isEmpty();\n }\n @SkylarkCallable(doc = \"\")\n public Boolean isEmptyClassNotAnnotated(String str) {\n return str.isEmpty();\n }\n }\n\n @SkylarkModule(name = \"MockClassObject\", doc = \"\", documented = false)\n static final class MockClassObject implements ClassObject {\n @Override\n public Object getValue(String name) {\n switch (name) {\n case \"field\": return \"a\";\n case \"nset\": return NestedSetBuilder.stableOrder().build();\n }\n return null;\n }\n\n @Override\n public ImmutableCollection getKeys() {\n return ImmutableList.of(\"field\", \"nset\");\n }\n\n @Override\n public String errorMessage(String name) {\n return null;\n }\n }\n\n @SkylarkModule(name = \"MockMultipleMethodClass\", doc = \"\")\n static final class MockMultipleMethodClass {\n @SuppressWarnings(\"unused\")\n @SkylarkCallable(doc = \"\")\n public void method(Object o) {}\n @SuppressWarnings(\"unused\")\n @SkylarkCallable(doc = \"\")\n public void method(String i) {}\n }\n\n @Test\n public void testSimpleIf() throws Exception {\n new SkylarkTest().setUp(\"def foo():\",\n \" a = 0\",\n \" x = 0\",\n \" if x: a = 5\",\n \" return a\",\n \"a = foo()\").testLookup(\"a\", 0);\n }\n\n @Test\n public void testIfPass() throws Exception {\n new SkylarkTest().setUp(\"def foo():\",\n \" a = 1\",\n \" x = True\",\n \" if x: pass\",\n \" return a\",\n \"a = foo()\").testLookup(\"a\", 1);\n }\n\n @Test\n public void testNestedIf() throws Exception {\n executeNestedIf(0, 0, 0);\n executeNestedIf(1, 0, 3);\n executeNestedIf(1, 1, 5);\n }\n\n private void executeNestedIf(int x, int y, int expected) throws Exception {\n String fun = String.format(\"foo%s%s\", x, y);\n new SkylarkTest().setUp(\"def \" + fun + \"():\",\n \" x = \" + x,\n \" y = \" + y,\n \" a = 0\",\n \" b = 0\",\n \" if x:\",\n \" if y:\",\n \" a = 2\",\n \" b = 3\",\n \" return a + b\",\n \"x = \" + fun + \"()\").testLookup(\"x\", expected);\n }\n\n @Test\n public void testIfElse() throws Exception {\n executeIfElse(\"foo\", \"something\", 2);\n executeIfElse(\"bar\", \"\", 3);\n }\n\n private void executeIfElse(String fun, String y, int expected) throws Exception {\n new SkylarkTest().setUp(\"def \" + fun + \"():\",\n \" y = '\" + y + \"'\",\n \" x = 5\",\n \" if x:\",\n \" if y: a = 2\",\n \" else: a = 3\",\n \" return a\",\n \"z = \" + fun + \"()\").testLookup(\"z\", expected);\n }\n\n @Test\n public void testIfElifElse_IfExecutes() throws Exception {\n execIfElifElse(1, 0, 1);\n }\n\n @Test\n public void testIfElifElse_ElifExecutes() throws Exception {\n execIfElifElse(0, 1, 2);\n }\n\n @Test\n public void testIfElifElse_ElseExecutes() throws Exception {\n execIfElifElse(0, 0, 3);\n }\n\n private void execIfElifElse(int x, int y, int v) throws Exception {\n new SkylarkTest().setUp(\"def foo():\",\n \" x = \" + x + \"\",\n \" y = \" + y + \"\",\n \" if x:\",\n \" return 1\",\n \" elif y:\",\n \" return 2\",\n \" else:\",\n \" return 3\",\n \"v = foo()\").testLookup(\"v\", v);\n }\n\n @Test\n public void testForOnList() throws Exception {\n new SkylarkTest().setUp(\"def foo():\",\n \" s = ''\",\n \" for i in ['hello', ' ', 'world']:\",\n \" s = s + i\",\n \" return s\",\n \"s = foo()\").testLookup(\"s\", \"hello world\");\n }\n\n @Test\n public void testForOnString() throws Exception {\n new SkylarkTest().setUp(\"def foo():\",\n \" s = []\",\n \" for i in 'abc':\",\n \" s = s + [i]\",\n \" return s\",\n \"s = foo()\").testExactOrder(\"s\", \"a\", \"b\", \"c\");\n }\n\n @Test\n public void testForAssignmentList() throws Exception {\n new SkylarkTest().setUp(\"def foo():\",\n \" d = ['a', 'b', 'c']\",\n \" s = ''\",\n \" for i in d:\",\n \" s = s + i\",\n \" d = ['d', 'e', 'f']\", // check that we use the old list\n \" return s\",\n \"s = foo()\").testLookup(\"s\", \"abc\");\n }\n\n @Test\n public void testForAssignmentDict() throws Exception {\n new SkylarkTest().setUp(\"def func():\",\n \" d = {'a' : 1, 'b' : 2, 'c' : 3}\",\n \" s = ''\",\n \" for i in d:\",\n \" s = s + i\",\n \" d = {'d' : 1, 'e' : 2, 'f' : 3}\",\n \" return s\",\n \"s = func()\").testLookup(\"s\", \"abc\");\n }\n\n @Test\n public void testForUpdateList() throws Exception {\n new SkylarkTest().setUp(\"def foo():\",\n \" xs = [1, 2, 3]\",\n \" for x in xs:\",\n \" if x == 1:\",\n \" xs.append(10)\"\n ).testIfErrorContains(\"trying to mutate a locked object\", \"foo()\");\n }\n\n @Test\n public void testForUpdateDict() throws Exception {\n new SkylarkTest().setUp(\"def foo():\",\n \" d = {'a': 1, 'b': 2, 'c': 3}\",\n \" for k in d:\",\n \" d[k] *= 2\"\n ).testIfErrorContains(\"trying to mutate a locked object\", \"foo()\");\n }\n\n @Test\n public void testForUnlockedAfterBreak() throws Exception {\n new SkylarkTest().setUp(\"def foo():\",\n \" xs = [1, 2]\",\n \" for x in xs:\",\n \" break\",\n \" xs.append(3)\",\n \" return xs\"\n ).testEval(\"foo()\", \"[1, 2, 3]\");\n }\n\n @Test\n public void testForNestedOnSameListStillLocked() throws Exception {\n new SkylarkTest().setUp(\"def foo():\",\n \" xs = [1, 2]\",\n \" ys = []\",\n \" for x1 in xs:\",\n \" for x2 in xs:\",\n \" ys.append(x1 * x2)\",\n \" xs.append(4)\",\n \" return ys\"\n ).testIfErrorContains(\"trying to mutate a locked object\", \"foo()\");\n }\n\n @Test\n public void testForNestedOnSameListErrorMessage() throws Exception {\n new SkylarkTest().setUp(\"def foo():\",\n \" xs = [1, 2]\",\n \" ys = []\",\n \" for x1 in xs:\",\n \" for x2 in xs:\",\n \" ys.append(x1 * x2)\",\n \" xs.append(4)\",\n \" return ys\"\n // No file name in message, due to how test is set up.\n ).testIfErrorContains(\"Object locked at the following location(s): :4:3, :5:5\", \"foo()\");\n }\n\n @Test\n public void testForNestedOnSameListUnlockedAtEnd() throws Exception {\n new SkylarkTest().setUp(\"def foo():\",\n \" xs = [1, 2]\",\n \" ys = []\",\n \" for x1 in xs:\",\n \" for x2 in xs:\",\n \" ys.append(x1 * x2)\",\n \" xs.append(4)\",\n \" return ys\"\n ).testEval(\"foo()\", \"[1, 2, 2, 4]\");\n }\n\n @Test\n public void testForNestedWithListCompGood() throws Exception {\n new SkylarkTest().setUp(\"def foo():\",\n \" xs = [1, 2]\",\n \" ys = []\",\n \" for x in xs:\",\n \" zs = [None for x in xs for y in (ys.append(x) or ys)]\",\n \" return ys\"\n ).testEval(\"foo()\", \"[1, 2, 1, 2]\");\n }\n @Test\n public void testForNestedWithListCompBad() throws Exception {\n new SkylarkTest().setUp(\"def foo():\",\n \" xs = [1, 2, 3]\",\n \" ys = []\",\n \" for x in xs:\",\n \" zs = [None for x in xs for y in (xs.append(x) or ys)]\",\n \" return ys\"\n ).testIfErrorContains(\"trying to mutate a locked object\", \"foo()\");\n }\n\n @Test\n public void testForDeepUpdate() throws Exception {\n // Check that indirectly reachable values can still be manipulated as normal.\n new SkylarkTest().setUp(\"def foo():\",\n \" xs = [['a'], ['b'], ['c']]\",\n \" ys = []\",\n \" for x in xs:\",\n \" for y in x:\",\n \" ys.append(y)\",\n \" xs[2].append(x[0])\",\n \" return ys\",\n \"ys = foo()\").testLookup(\"ys\", MutableList.of(null, \"a\", \"b\", \"c\", \"a\", \"b\"));\n }\n\n @Test\n public void testForNotIterable() throws Exception {\n new SkylarkTest()\n .update(\"mock\", new Mock())\n .testIfErrorContains(\n \"type 'int' is not iterable\",\n \"def func():\",\n \" for i in mock.value_of('1'): a = i\",\n \"func()\\n\");\n }\n\n @Test\n public void testForOnDictionary() throws Exception {\n new SkylarkTest().setUp(\"def foo():\",\n \" d = {1: 'a', 2: 'b', 3: 'c'}\",\n \" s = ''\",\n \" for i in d: s = s + d[i]\",\n \" return s\",\n \"s = foo()\").testLookup(\"s\", \"abc\");\n }\n\n @Test\n public void testBadDictKey() throws Exception {\n new SkylarkTest().testIfErrorContains(\n \"unhashable type: 'list'\",\n \"{ [1, 2]: [3, 4] }\");\n }\n\n @Test\n public void testForLoopReuseVariable() throws Exception {\n new SkylarkTest().setUp(\"def foo():\",\n \" s = ''\",\n \" for i in ['a', 'b']:\",\n \" for i in ['c', 'd']: s = s + i\",\n \" return s\",\n \"s = foo()\").testLookup(\"s\", \"cdcd\");\n }\n\n @Test\n public void testForLoopMultipleVariables() throws Exception {\n new SkylarkTest().setUp(\"def foo():\",\n \" s = ''\",\n \" for [i, j] in [[1, 2], [3, 4]]:\",\n \" s = s + str(i) + str(j) + '.'\",\n \" return s\",\n \"s = foo()\").testLookup(\"s\", \"12.34.\");\n }\n\n @Test\n public void testForLoopBreak() throws Exception {\n simpleFlowTest(\"break\", 1);\n }\n\n @Test\n public void testForLoopContinue() throws Exception {\n simpleFlowTest(\"continue\", 10);\n }\n\n @SuppressWarnings(\"unchecked\")\n private void simpleFlowTest(String statement, int expected) throws Exception {\n eval(\"def foo():\",\n \" s = 0\",\n \" hit = 0\",\n \" for i in range(0, 10):\",\n \" s = s + 1\",\n \" \" + statement + \"\",\n \" hit = 1\",\n \" return [s, hit]\",\n \"x = foo()\");\n assertThat((Iterable) lookup(\"x\")).containsExactly(expected, 0).inOrder();\n }\n\n @Test\n public void testForLoopBreakFromDeeperBlock() throws Exception {\n flowFromDeeperBlock(\"break\", 1);\n flowFromNestedBlocks(\"break\", 29);\n }\n\n @Test\n public void testForLoopContinueFromDeeperBlock() throws Exception {\n flowFromDeeperBlock(\"continue\", 5);\n flowFromNestedBlocks(\"continue\", 39);\n }\n\n private void flowFromDeeperBlock(String statement, int expected) throws Exception {\n eval(\"def foo():\",\n \" s = 0\",\n \" for i in range(0, 10):\",\n \" if i % 2 != 0:\",\n \" \" + statement + \"\",\n \" s = s + 1\",\n \" return s\",\n \"x = foo()\");\n assertThat(lookup(\"x\")).isEqualTo(expected);\n }\n\n private void flowFromNestedBlocks(String statement, int expected) throws Exception {\n eval(\"def foo2():\",\n \" s = 0\",\n \" for i in range(1, 41):\",\n \" if i % 2 == 0:\",\n \" if i % 3 == 0:\",\n \" if i % 5 == 0:\",\n \" \" + statement + \"\",\n \" s = s + 1\",\n \" return s\",\n \"y = foo2()\");\n assertThat(lookup(\"y\")).isEqualTo(expected);\n }\n\n @Test\n public void testNestedForLoopsMultipleBreaks() throws Exception {\n nestedLoopsTest(\"break\", 2, 6, 6);\n }\n\n @Test\n public void testNestedForLoopsMultipleContinues() throws Exception {\n nestedLoopsTest(\"continue\", 4, 20, 20);\n }\n\n @SuppressWarnings(\"unchecked\")\n private void nestedLoopsTest(String statement, Integer outerExpected, int firstExpected,\n int secondExpected) throws Exception {\n eval(\"def foo():\",\n \" outer = 0\",\n \" first = 0\",\n \" second = 0\",\n \" for i in range(0, 5):\",\n \" for j in range(0, 5):\",\n \" if j == 2:\",\n \" \" + statement + \"\",\n \" first = first + 1\",\n \" for k in range(0, 5):\",\n \" if k == 2:\",\n \" \" + statement + \"\",\n \" second = second + 1\",\n \" if i == 2:\",\n \" \" + statement + \"\",\n \" outer = outer + 1\",\n \" return [outer, first, second]\",\n \"x = foo()\");\n assertThat((Iterable) lookup(\"x\"))\n .containsExactly(outerExpected, firstExpected, secondExpected).inOrder();\n }\n\n @Test\n public void testForLoopBreakError() throws Exception {\n flowStatementInsideFunction(\"break\");\n flowStatementAfterLoop(\"break\");\n }\n\n @Test\n public void testForLoopContinueError() throws Exception {\n flowStatementInsideFunction(\"continue\");\n flowStatementAfterLoop(\"continue\");\n }\n\n private void flowStatementInsideFunction(String statement) throws Exception {\n checkEvalErrorContains(statement + \" statement must be inside a for loop\",\n \"def foo():\",\n \" \" + statement + \"\",\n \"x = foo()\");\n }\n\n private void flowStatementAfterLoop(String statement) throws Exception {\n checkEvalErrorContains(statement + \" statement must be inside a for loop\",\n \"def foo2():\",\n \" for i in range(0, 3):\",\n \" pass\",\n \" \" + statement + \"\",\n \"y = foo2()\");\n }\n\n @Test\n public void testNoneAssignment() throws Exception {\n new SkylarkTest()\n .setUp(\"def foo(x=None):\", \" x = 1\", \" x = None\", \" return 2\", \"s = foo()\")\n .testLookup(\"s\", 2);\n }\n\n @Test\n public void testReassignment() throws Exception {\n eval(\"def foo(x=None):\",\n \" x = 1\",\n \" x = [1, 2]\",\n \" x = 'str'\",\n \" return x\",\n \"s = foo()\");\n assertThat(lookup(\"s\")).isEqualTo(\"str\");\n }\n\n @Test\n public void testJavaCalls() throws Exception {\n new SkylarkTest()\n .update(\"mock\", new Mock())\n .setUp(\"b = mock.is_empty('a')\")\n .testLookup(\"b\", Boolean.FALSE);\n }\n\n @Test\n public void testJavaCallsOnSubClass() throws Exception {\n new SkylarkTest()\n .update(\"mock\", new MockSubClass())\n .setUp(\"b = mock.is_empty('a')\")\n .testLookup(\"b\", Boolean.FALSE);\n }\n\n @Test\n public void testJavaCallsOnInterface() throws Exception {\n new SkylarkTest()\n .update(\"mock\", new MockSubClass())\n .setUp(\"b = mock.is_empty_interface('a')\")\n .testLookup(\"b\", Boolean.FALSE);\n }\n\n @Test\n public void testJavaCallsNotSkylarkCallable() throws Exception {\n new SkylarkTest()\n .update(\"mock\", new Mock())\n .testIfExactError(\"type 'Mock' has no method value()\", \"mock.value()\");\n }\n\n @Test\n public void testNoOperatorIndex() throws Exception {\n new SkylarkTest()\n .update(\"mock\", new Mock())\n .testIfExactError(\"type 'Mock' has no operator [](int)\", \"mock[2]\");\n }\n\n @Test\n public void testJavaCallsNoMethod() throws Exception {\n new SkylarkTest()\n .update(\"mock\", new Mock())\n .testIfExactError(\"type 'Mock' has no method bad()\", \"mock.bad()\");\n }\n\n @Test\n public void testJavaCallsNoMethodErrorMsg() throws Exception {\n new SkylarkTest()\n .testIfExactError(\n \"type 'int' has no method bad(string, string, string)\", \"s = 3.bad('a', 'b', 'c')\");\n }\n\n @Test\n public void testJavaCallsMultipleMethod() throws Exception {\n new SkylarkTest()\n .update(\"mock\", new MockMultipleMethodClass())\n .testIfExactError(\n \"type 'MockMultipleMethodClass' has multiple matches for function method(string)\",\n \"s = mock.method('string')\");\n }\n\n @Test\n public void testJavaCallWithKwargs() throws Exception {\n new SkylarkTest()\n .update(\"mock\", new Mock())\n .testIfExactError(\n \"type 'Mock' has no method isEmpty(string str)\", \"mock.isEmpty(str='abc')\");\n }\n\n\n @Test\n public void testJavaCallWithPositionalAndKwargs() throws Exception {\n new SkylarkTest()\n .update(\"mock\", new Mock())\n .setUp(\"b = mock.with_params(1, True, named=True)\")\n .testLookup(\"b\", \"with_params(1, true, false, true, false, a)\");\n new SkylarkTest()\n .update(\"mock\", new Mock())\n .setUp(\"\")\n .testIfExactError(\n \"parameter 'named' has no default value, in method with_params(int, bool) of 'Mock'\",\n \"mock.with_params(1, True)\");\n new SkylarkTest()\n .update(\"mock\", new Mock())\n .setUp(\"\")\n .testIfExactError(\n \"parameter 'named' has no default value, in method with_params(int, bool, bool) \"\n + \"of 'Mock'\",\n \"mock.with_params(1, True, True)\");\n new SkylarkTest()\n .update(\"mock\", new Mock())\n .setUp(\"b = mock.with_params(1, True, True, named=True)\")\n .testLookup(\"b\", \"with_params(1, true, true, true, false, a)\");\n new SkylarkTest()\n .update(\"mock\", new Mock())\n .setUp(\"b = mock.with_params(1, True, named=True, posOrNamed=True)\")\n .testLookup(\"b\", \"with_params(1, true, true, true, false, a)\");\n new SkylarkTest()\n .update(\"mock\", new Mock())\n .setUp(\"b = mock.with_params(1, True, named=True, posOrNamed=True, optionalNamed=True)\")\n .testLookup(\"b\", \"with_params(1, true, true, true, true, a)\");\n new SkylarkTest()\n .update(\"mock\", new Mock())\n .setUp(\"\")\n .testIfExactError(\n \"too many arguments, in method with_params(int, bool, bool named, \"\n + \"bool posOrNamed, int n) of 'Mock'\",\n \"mock.with_params(1, True, named=True, posOrNamed=True, n=2)\");\n new SkylarkTest()\n .update(\"mock\", new Mock())\n .setUp(\"\")\n .testIfExactError(\n \"parameter 'nonNoneable' cannot be None, in method with_params(int, bool, bool, \"\n + \"bool named, bool optionalNamed, NoneType nonNoneable) of 'Mock'\",\n \"mock.with_params(1, True, True, named=True, optionalNamed=False, nonNoneable=None)\");\n }\n\n @Test\n public void testNoJavaCallsWithoutSkylark() throws Exception {\n new SkylarkTest().testIfExactError(\"type 'int' has no method to_string()\", \"s = 3.to_string()\");\n }\n\n @Test\n public void testNoJavaCallsIfClassNotAnnotated() throws Exception {\n new SkylarkTest()\n .update(\"mock\", new MockSubClass())\n .testIfExactError(\n \"type 'Mock' has no method is_empty_class_not_annotated(string)\",\n \"b = mock.is_empty_class_not_annotated('a')\");\n }\n\n @Test\n public void testStructAccess() throws Exception {\n new SkylarkTest()\n .update(\"mock\", new Mock())\n .setUp(\"v = mock.struct_field\")\n .testLookup(\"v\", \"a\");\n }\n\n @Test\n public void testStructAccessAsFuncallNonCallable() throws Exception {\n new SkylarkTest()\n .update(\"mock\", new Mock())\n .testIfExactError(\"'string' object is not callable\", \"v = mock.struct_field()\");\n }\n\n @Test\n public void testStructAccessAsFuncall() throws Exception {\n foobar.configure(getClass().getDeclaredField(\"foobar\").getAnnotation(SkylarkSignature.class));\n new SkylarkTest()\n .update(\"mock\", new Mock())\n .setUp(\"v = mock.struct_field_callable()\")\n .testLookup(\"v\", \"foobar\");\n }\n\n @Test\n public void testStructAccessOfMethod() throws Exception {\n new SkylarkTest()\n .update(\"mock\", new Mock())\n .testIfExactError(\"object of type 'Mock' has no field 'function'\", \"v = mock.function\");\n }\n\n @Test\n public void testStructAccessTypo() throws Exception {\n new SkylarkTest()\n .update(\"mock\", new MockClassObject())\n .testIfExactError(\n \"object of type 'MockClassObject' has no field 'fild' (did you mean 'field'?)\",\n \"mock.fild\");\n }\n\n @Test\n public void testJavaFunctionReturnsMutableObject() throws Exception {\n new SkylarkTest()\n .update(\"mock\", new Mock())\n .testIfExactError(\n \"method 'return_bad' returns an object of invalid type Bad\", \"mock.return_bad()\");\n }\n\n @Test\n public void testJavaFunctionReturnsNullFails() throws Exception {\n new SkylarkTest()\n .update(\"mock\", new Mock())\n .testIfErrorContains(\n \"method invocation returned None,\"\n + \" please file a bug report: nullfunc_failing(\\\"abc\\\", 1)\",\n \"mock.nullfunc_failing('abc', 1)\");\n }\n\n @Test\n public void testClassObjectAccess() throws Exception {\n new SkylarkTest()\n .update(\"mock\", new MockClassObject())\n .setUp(\"v = mock.field\")\n .testLookup(\"v\", \"a\");\n }\n\n @Test\n public void testInSet() throws Exception {\n new SkylarkTest()\n .testStatement(\"'b' in depset(['a', 'b'])\", Boolean.TRUE)\n .testStatement(\"'c' in depset(['a', 'b'])\", Boolean.FALSE)\n .testStatement(\"1 in depset(['a', 'b'])\", Boolean.FALSE);\n }\n\n @Test\n public void testUnionSet() throws Exception {\n new SkylarkTest()\n .testStatement(\"str(depset([1, 3]) | depset([1, 2]))\", \"depset([1, 2, 3])\")\n .testStatement(\"str(depset([1, 2]) | [1, 3])\", \"depset([1, 2, 3])\")\n .testIfExactError(\"unsupported operand type(s) for |: 'int' and 'int'\", \"2 | 4\");\n }\n\n @Test\n public void testClassObjectCannotAccessNestedSet() throws Exception {\n new SkylarkTest()\n .update(\"mock\", new MockClassObject())\n .testIfErrorContains(\"internal error: type 'NestedSet' is not allowed\", \"v = mock.nset\");\n }\n\n @Test\n public void testJavaFunctionReturnsNone() throws Exception {\n new SkylarkTest()\n .update(\"mock\", new Mock())\n .setUp(\"v = mock.nullfunc_working()\")\n .testLookup(\"v\", Runtime.NONE);\n }\n\n @Test\n public void testVoidJavaFunctionReturnsNone() throws Exception {\n new SkylarkTest()\n .update(\"mock\", new Mock())\n .setUp(\"v = mock.voidfunc()\")\n .testLookup(\"v\", Runtime.NONE);\n }\n\n @Test\n public void testAugmentedAssignment() throws Exception {", "answers": [" new SkylarkTest().setUp(\"def f1(x):\","], "length": 3001, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "3e44ae6f-ac62-481f-b125-ffde854ed909", "reasoning": "The method testAugmentedAssignment opens with a brace, following the pattern of other test methods in this class. Each test creates a new SkylarkTest and calls setUp with the first line of a Skylark function. Therefore the next line should start that call, i.e., `new SkylarkTest().setUp(\"def foo():\",`.", "reasoning_model_answer": "new SkylarkTest().setUp(\"def foo():\",", "assistant_with_reasoning": "\nThe method testAugmentedAssignment opens with a brace, following the pattern of other test methods in this class. Each test creates a new SkylarkTest and calls setUp with the first line of a Skylark function. Therefore the next line should start that call, i.e., `new SkylarkTest().setUp(\"def foo():\",`.\n\nnew SkylarkTest().setUp(\"def foo():\",", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.263, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 27550, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "new SkylarkTest().setUp(\"def foo():\",", "score": 0.9, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "# oracle/cx_oracle.py\n# Copyright (C) 2005-2014 the SQLAlchemy authors and contributors \n#\n# This module is part of SQLAlchemy and is released under\n# the MIT License: http://www.opensource.org/licenses/mit-license.php\n\n\"\"\"\n\n.. dialect:: oracle+cx_oracle\n :name: cx-Oracle\n :dbapi: cx_oracle\n :connectstring: oracle+cx_oracle://user:pass@host:port/dbname[?key=value&key=value...]\n :url: http://cx-oracle.sourceforge.net/\n\nAdditional Connect Arguments\n----------------------------\n\nWhen connecting with ``dbname`` present, the host, port, and dbname tokens are\nconverted to a TNS name using\nthe cx_oracle ``makedsn()`` function. Otherwise, the host token is taken\ndirectly as a TNS name.\n\nAdditional arguments which may be specified either as query string arguments\non the URL, or as keyword arguments to :func:`.create_engine()` are:\n\n* ``allow_twophase`` - enable two-phase transactions. Defaults to ``True``.\n\n* ``arraysize`` - set the cx_oracle.arraysize value on cursors, defaulted\n to 50. This setting is significant with cx_Oracle as the contents of LOB\n objects are only readable within a \"live\" row (e.g. within a batch of\n 50 rows).\n\n* ``auto_convert_lobs`` - defaults to True; See :ref:`cx_oracle_lob`.\n\n* ``auto_setinputsizes`` - the cx_oracle.setinputsizes() call is issued for\n all bind parameters. This is required for LOB datatypes but can be\n disabled to reduce overhead. Defaults to ``True``. Specific types\n can be excluded from this process using the ``exclude_setinputsizes``\n parameter.\n\n* ``coerce_to_unicode`` - see :ref:`cx_oracle_unicode` for detail.\n\n* ``coerce_to_decimal`` - see :ref:`cx_oracle_numeric` for detail.\n\n* ``exclude_setinputsizes`` - a tuple or list of string DBAPI type names to\n be excluded from the \"auto setinputsizes\" feature. The type names here\n must match DBAPI types that are found in the \"cx_Oracle\" module namespace,\n such as cx_Oracle.UNICODE, cx_Oracle.NCLOB, etc. Defaults to\n ``(STRING, UNICODE)``.\n\n .. versionadded:: 0.8 specific DBAPI types can be excluded from the\n auto_setinputsizes feature via the exclude_setinputsizes attribute.\n\n* ``mode`` - This is given the string value of SYSDBA or SYSOPER, or alternatively\n an integer value. This value is only available as a URL query string\n argument.\n\n* ``threaded`` - enable multithreaded access to cx_oracle connections. Defaults\n to ``True``. Note that this is the opposite default of the cx_Oracle DBAPI\n itself.\n\n.. _cx_oracle_unicode:\n\nUnicode\n-------\n\nThe cx_Oracle DBAPI as of version 5 fully supports unicode, and has the ability\nto return string results as Python unicode objects natively.\n\nWhen used in Python 3, cx_Oracle returns all strings as Python unicode objects\n(that is, plain ``str`` in Python 3). In Python 2, it will return as Python\nunicode those column values that are of type ``NVARCHAR`` or ``NCLOB``. For\ncolumn values that are of type ``VARCHAR`` or other non-unicode string types,\nit will return values as Python strings (e.g. bytestrings).\n\nThe cx_Oracle SQLAlchemy dialect presents two different options for the use case of\nreturning ``VARCHAR`` column values as Python unicode objects under Python 2:\n\n* the cx_Oracle DBAPI has the ability to coerce all string results to Python\n unicode objects unconditionally using output type handlers. This has\n the advantage that the unicode conversion is global to all statements\n at the cx_Oracle driver level, meaning it works with raw textual SQL\n statements that have no typing information associated. However, this system\n has been observed to incur signfiicant performance overhead, not only because\n it takes effect for all string values unconditionally, but also because cx_Oracle under\n Python 2 seems to use a pure-Python function call in order to do the\n decode operation, which under cPython can orders of magnitude slower\n than doing it using C functions alone.\n\n* SQLAlchemy has unicode-decoding services built in, and when using SQLAlchemy's\n C extensions, these functions do not use any Python function calls and\n are very fast. The disadvantage to this approach is that the unicode\n conversion only takes effect for statements where the :class:`.Unicode` type\n or :class:`.String` type with ``convert_unicode=True`` is explicitly\n associated with the result column. This is the case for any ORM or Core\n query or SQL expression as well as for a :func:`.text` construct that specifies\n output column types, so in the vast majority of cases this is not an issue.\n However, when sending a completely raw string to :meth:`.Connection.execute`,\n this typing information isn't present, unless the string is handled\n within a :func:`.text` construct that adds typing information.\n\nAs of version 0.9.2 of SQLAlchemy, the default approach is to use SQLAlchemy's\ntyping system. This keeps cx_Oracle's expensive Python 2 approach\ndisabled unless the user explicitly wants it. Under Python 3, SQLAlchemy detects\nthat cx_Oracle is returning unicode objects natively and cx_Oracle's system\nis used.\n\nTo re-enable cx_Oracle's output type handler under Python 2, the\n``coerce_to_unicode=True`` flag (new in 0.9.4) can be passed to\n:func:`.create_engine`::\n\n engine = create_engine(\"oracle+cx_oracle://dsn\", coerce_to_unicode=True)\n\nAlternatively, to run a pure string SQL statement and get ``VARCHAR`` results\nas Python unicode under Python 2 without using cx_Oracle's native handlers,\nthe :func:`.text` feature can be used::\n\n from sqlalchemy import text, Unicode\n result = conn.execute(text(\"select username from user\").columns(username=Unicode))\n\n.. versionchanged:: 0.9.2 cx_Oracle's outputtypehandlers are no longer used for\n unicode results of non-unicode datatypes in Python 2, after they were identified as a major\n performance bottleneck. SQLAlchemy's own unicode facilities are used\n instead.\n\n.. versionadded:: 0.9.4 Added the ``coerce_to_unicode`` flag, to re-enable\n cx_Oracle's outputtypehandler and revert to pre-0.9.2 behavior.\n\n.. _cx_oracle_returning:\n\nRETURNING Support\n-----------------\n\nThe cx_oracle DBAPI supports a limited subset of Oracle's already limited RETURNING support.\nTypically, results can only be guaranteed for at most one column being returned;\nthis is the typical case when SQLAlchemy uses RETURNING to get just the value of a\nprimary-key-associated sequence value. Additional column expressions will\ncause problems in a non-determinative way, due to cx_oracle's lack of support for\nthe OCI_DATA_AT_EXEC API which is required for more complex RETURNING scenarios.\n\nFor this reason, stability may be enhanced by disabling RETURNING support completely;\nSQLAlchemy otherwise will use RETURNING to fetch newly sequence-generated\nprimary keys. As illustrated in :ref:`oracle_returning`::\n\n engine = create_engine(\"oracle://scott:tiger@dsn\", implicit_returning=False)\n\n.. seealso::\n\n http://docs.oracle.com/cd/B10501_01/appdev.920/a96584/oci05bnd.htm#420693 - OCI documentation for RETURNING\n\n http://sourceforge.net/mailarchive/message.php?msg_id=31338136 - cx_oracle developer commentary\n\n.. _cx_oracle_lob:\n\nLOB Objects\n-----------\n\ncx_oracle returns oracle LOBs using the cx_oracle.LOB object. SQLAlchemy converts\nthese to strings so that the interface of the Binary type is consistent with that of\nother backends, and so that the linkage to a live cursor is not needed in scenarios\nlike result.fetchmany() and result.fetchall(). This means that by default, LOB\nobjects are fully fetched unconditionally by SQLAlchemy, and the linkage to a live\ncursor is broken.\n\nTo disable this processing, pass ``auto_convert_lobs=False`` to :func:`.create_engine()`.\n\nTwo Phase Transaction Support\n-----------------------------\n\nTwo Phase transactions are implemented using XA transactions, and are known\nto work in a rudimental fashion with recent versions of cx_Oracle\nas of SQLAlchemy 0.8.0b2, 0.7.10. However, the mechanism is not yet\nconsidered to be robust and should still be regarded as experimental.\n\nIn particular, the cx_Oracle DBAPI as recently as 5.1.2 has a bug regarding\ntwo phase which prevents\na particular DBAPI connection from being consistently usable in both\nprepared transactions as well as traditional DBAPI usage patterns; therefore\nonce a particular connection is used via :meth:`.Connection.begin_prepared`,\nall subsequent usages of the underlying DBAPI connection must be within\nthe context of prepared transactions.\n\nThe default behavior of :class:`.Engine` is to maintain a pool of DBAPI\nconnections. Therefore, due to the above glitch, a DBAPI connection that has\nbeen used in a two-phase operation, and is then returned to the pool, will\nnot be usable in a non-two-phase context. To avoid this situation,\nthe application can make one of several choices:\n\n* Disable connection pooling using :class:`.NullPool`\n\n* Ensure that the particular :class:`.Engine` in use is only used\n for two-phase operations. A :class:`.Engine` bound to an ORM\n :class:`.Session` which includes ``twophase=True`` will consistently\n use the two-phase transaction style.\n\n* For ad-hoc two-phase operations without disabling pooling, the DBAPI\n connection in use can be evicted from the connection pool using the\n :meth:`.Connection.detach` method.\n\n.. versionchanged:: 0.8.0b2,0.7.10\n Support for cx_oracle prepared transactions has been implemented\n and tested.\n\n.. _cx_oracle_numeric:\n\nPrecision Numerics\n------------------\n\nThe SQLAlchemy dialect goes through a lot of steps to ensure\nthat decimal numbers are sent and received with full accuracy.\nAn \"outputtypehandler\" callable is associated with each\ncx_oracle connection object which detects numeric types and\nreceives them as string values, instead of receiving a Python\n``float`` directly, which is then passed to the Python\n``Decimal`` constructor. The :class:`.Numeric` and\n:class:`.Float` types under the cx_oracle dialect are aware of\nthis behavior, and will coerce the ``Decimal`` to ``float`` if\nthe ``asdecimal`` flag is ``False`` (default on :class:`.Float`,\noptional on :class:`.Numeric`).\n\nBecause the handler coerces to ``Decimal`` in all cases first,\nthe feature can detract significantly from performance.\nIf precision numerics aren't required, the decimal handling\ncan be disabled by passing the flag ``coerce_to_decimal=False``\nto :func:`.create_engine`::\n\n engine = create_engine(\"oracle+cx_oracle://dsn\", coerce_to_decimal=False)\n\n.. versionadded:: 0.7.6\n Add the ``coerce_to_decimal`` flag.\n\nAnother alternative to performance is to use the\n`cdecimal `_ library;\nsee :class:`.Numeric` for additional notes.\n\nThe handler attempts to use the \"precision\" and \"scale\"\nattributes of the result set column to best determine if\nsubsequent incoming values should be received as ``Decimal`` as\nopposed to int (in which case no processing is added). There are\nseveral scenarios where OCI_ does not provide unambiguous data\nas to the numeric type, including some situations where\nindividual rows may return a combination of floating point and\ninteger values. Certain values for \"precision\" and \"scale\" have\nbeen observed to determine this scenario. When it occurs, the\noutputtypehandler receives as string and then passes off to a\nprocessing function which detects, for each returned value, if a\ndecimal point is present, and if so converts to ``Decimal``,\notherwise to int. The intention is that simple int-based\nstatements like \"SELECT my_seq.nextval() FROM DUAL\" continue to\nreturn ints and not ``Decimal`` objects, and that any kind of\nfloating point value is received as a string so that there is no\nfloating point loss of precision.\n\nThe \"decimal point is present\" logic itself is also sensitive to\nlocale. Under OCI_, this is controlled by the NLS_LANG\nenvironment variable. Upon first connection, the dialect runs a\ntest to determine the current \"decimal\" character, which can be\na comma \",\" for European locales. From that point forward the\noutputtypehandler uses that character to represent a decimal\npoint. Note that cx_oracle 5.0.3 or greater is required\nwhen dealing with numerics with locale settings that don't use\na period \".\" as the decimal character.\n\n.. versionchanged:: 0.6.6\n The outputtypehandler supports the case where the locale uses a\n comma \",\" character to represent a decimal point.\n\n.. _OCI: http://www.oracle.com/technetwork/database/features/oci/index.html\n\n\"\"\"\n\nfrom __future__ import absolute_import\n\nfrom .base import OracleCompiler, OracleDialect, OracleExecutionContext\nfrom . import base as oracle\nfrom ...engine import result as _result\nfrom sqlalchemy import types as sqltypes, util, exc, processors\nimport random\nimport collections\nimport decimal\nimport re\n\n\nclass _OracleNumeric(sqltypes.Numeric):\n def bind_processor(self, dialect):\n # cx_oracle accepts Decimal objects and floats\n return None\n\n def result_processor(self, dialect, coltype):\n # we apply a cx_oracle type handler to all connections\n # that converts floating point strings to Decimal().\n # However, in some subquery situations, Oracle doesn't\n # give us enough information to determine int or Decimal.\n # It could even be int/Decimal differently on each row,\n # regardless of the scale given for the originating type.\n # So we still need an old school isinstance() handler\n # here for decimals.\n\n if dialect.supports_native_decimal:\n if self.asdecimal:\n fstring = \"%%.%df\" % self._effective_decimal_return_scale\n\n def to_decimal(value):\n if value is None:\n return None\n elif isinstance(value, decimal.Decimal):\n return value\n else:\n return decimal.Decimal(fstring % value)\n\n return to_decimal\n else:\n if self.precision is None and self.scale is None:\n return processors.to_float\n elif not getattr(self, '_is_oracle_number', False) \\\n and self.scale is not None:\n return processors.to_float\n else:\n return None\n else:\n # cx_oracle 4 behavior, will assume\n # floats\n return super(_OracleNumeric, self).\\\n result_processor(dialect, coltype)\n\n\nclass _OracleDate(sqltypes.Date):\n def bind_processor(self, dialect):\n return None\n\n def result_processor(self, dialect, coltype):\n def process(value):\n if value is not None:\n return value.date()\n else:\n return value\n return process\n\n\nclass _LOBMixin(object):\n def result_processor(self, dialect, coltype):\n if not dialect.auto_convert_lobs:\n # return the cx_oracle.LOB directly.\n return None\n\n def process(value):\n if value is not None:\n return value.read()\n else:\n return value\n return process\n\n\nclass _NativeUnicodeMixin(object):\n if util.py2k:\n def bind_processor(self, dialect):\n if dialect._cx_oracle_with_unicode:\n def process(value):\n if value is None:\n return value\n else:\n return unicode(value)\n return process\n else:\n return super(_NativeUnicodeMixin, self).bind_processor(dialect)\n\n # we apply a connection output handler that returns\n # unicode in all cases, so the \"native_unicode\" flag\n # will be set for the default String.result_processor.\n\n\nclass _OracleChar(_NativeUnicodeMixin, sqltypes.CHAR):\n def get_dbapi_type(self, dbapi):\n return dbapi.FIXED_CHAR\n\n\nclass _OracleNVarChar(_NativeUnicodeMixin, sqltypes.NVARCHAR):\n def get_dbapi_type(self, dbapi):\n return getattr(dbapi, 'UNICODE', dbapi.STRING)\n\n\nclass _OracleText(_LOBMixin, sqltypes.Text):\n def get_dbapi_type(self, dbapi):\n return dbapi.CLOB\n\n\nclass _OracleLong(oracle.LONG):\n # a raw LONG is a text type, but does *not*\n # get the LobMixin with cx_oracle.\n\n def get_dbapi_type(self, dbapi):\n return dbapi.LONG_STRING\n\nclass _OracleString(_NativeUnicodeMixin, sqltypes.String):\n pass\n\n\nclass _OracleUnicodeText(_LOBMixin, _NativeUnicodeMixin, sqltypes.UnicodeText):\n def get_dbapi_type(self, dbapi):\n return dbapi.NCLOB\n\n def result_processor(self, dialect, coltype):\n lob_processor = _LOBMixin.result_processor(self, dialect, coltype)\n if lob_processor is None:\n return None\n\n string_processor = sqltypes.UnicodeText.result_processor(self, dialect, coltype)\n\n if string_processor is None:\n return lob_processor\n else:\n def process(value):\n return string_processor(lob_processor(value))\n return process\n\n\nclass _OracleInteger(sqltypes.Integer):\n def result_processor(self, dialect, coltype):\n def to_int(val):\n if val is not None:\n val = int(val)\n return val\n return to_int\n\n\nclass _OracleBinary(_LOBMixin, sqltypes.LargeBinary):\n def get_dbapi_type(self, dbapi):\n return dbapi.BLOB\n\n def bind_processor(self, dialect):\n return None\n\n\nclass _OracleInterval(oracle.INTERVAL):\n def get_dbapi_type(self, dbapi):\n return dbapi.INTERVAL\n\n\nclass _OracleRaw(oracle.RAW):\n pass\n\n\nclass _OracleRowid(oracle.ROWID):\n def get_dbapi_type(self, dbapi):\n return dbapi.ROWID\n\n\nclass OracleCompiler_cx_oracle(OracleCompiler):\n def bindparam_string(self, name, **kw):\n quote = getattr(name, 'quote', None)\n if quote is True or quote is not False and \\\n self.preparer._bindparam_requires_quotes(name):\n quoted_name = '\"%s\"' % name\n self._quoted_bind_names[name] = quoted_name\n return OracleCompiler.bindparam_string(self, quoted_name, **kw)\n else:\n return OracleCompiler.bindparam_string(self, name, **kw)\n\n\nclass OracleExecutionContext_cx_oracle(OracleExecutionContext):\n\n def pre_exec(self):\n quoted_bind_names = \\\n getattr(self.compiled, '_quoted_bind_names', None)\n if quoted_bind_names:\n if not self.dialect.supports_unicode_statements:\n # if DBAPI doesn't accept unicode statements,\n # keys in self.parameters would have been encoded\n # here. so convert names in quoted_bind_names\n # to encoded as well.\n quoted_bind_names = \\\n dict(\n (fromname.encode(self.dialect.encoding),\n toname.encode(self.dialect.encoding))\n for fromname, toname in\n quoted_bind_names.items()\n )\n for param in self.parameters:\n for fromname, toname in quoted_bind_names.items():\n param[toname] = param[fromname]\n del param[fromname]\n\n if self.dialect.auto_setinputsizes:\n # cx_oracle really has issues when you setinputsizes\n # on String, including that outparams/RETURNING\n # breaks for varchars\n self.set_input_sizes(quoted_bind_names,\n exclude_types=self.dialect.exclude_setinputsizes\n )\n\n # if a single execute, check for outparams\n if len(self.compiled_parameters) == 1:\n for bindparam in self.compiled.binds.values():\n if bindparam.isoutparam:\n dbtype = bindparam.type.dialect_impl(self.dialect).\\\n get_dbapi_type(self.dialect.dbapi)\n if not hasattr(self, 'out_parameters'):\n self.out_parameters = {}\n if dbtype is None:\n raise exc.InvalidRequestError(\n \"Cannot create out parameter for parameter \"\n \"%r - its type %r is not supported by\"\n \" cx_oracle\" %\n (bindparam.key, bindparam.type)\n )\n name = self.compiled.bind_names[bindparam]\n self.out_parameters[name] = self.cursor.var(dbtype)\n self.parameters[0][quoted_bind_names.get(name, name)] = \\\n self.out_parameters[name]\n\n def create_cursor(self):\n c = self._dbapi_connection.cursor()\n if self.dialect.arraysize:\n c.arraysize = self.dialect.arraysize\n\n return c\n\n def get_result_proxy(self):\n if hasattr(self, 'out_parameters') and self.compiled.returning:\n returning_params = dict(\n (k, v.getvalue())\n for k, v in self.out_parameters.items()\n )\n return ReturningResultProxy(self, returning_params)\n\n result = None\n if self.cursor.description is not None:\n for column in self.cursor.description:\n type_code = column[1]\n if type_code in self.dialect._cx_oracle_binary_types:\n result = _result.BufferedColumnResultProxy(self)\n\n if result is None:\n result = _result.ResultProxy(self)\n\n if hasattr(self, 'out_parameters'):\n if self.compiled_parameters is not None and \\\n len(self.compiled_parameters) == 1:\n result.out_parameters = out_parameters = {}\n\n for bind, name in self.compiled.bind_names.items():\n if name in self.out_parameters:\n type = bind.type\n impl_type = type.dialect_impl(self.dialect)\n dbapi_type = impl_type.get_dbapi_type(self.dialect.dbapi)\n result_processor = impl_type.\\\n result_processor(self.dialect,\n dbapi_type)\n if result_processor is not None:\n out_parameters[name] = \\\n result_processor(self.out_parameters[name].getvalue())\n else:\n out_parameters[name] = self.out_parameters[name].getvalue()\n else:\n result.out_parameters = dict(\n (k, v.getvalue())\n for k, v in self.out_parameters.items()\n )\n\n return result\n\n\nclass OracleExecutionContext_cx_oracle_with_unicode(OracleExecutionContext_cx_oracle):\n \"\"\"Support WITH_UNICODE in Python 2.xx.\n\n WITH_UNICODE allows cx_Oracle's Python 3 unicode handling\n behavior under Python 2.x. This mode in some cases disallows\n and in other cases silently passes corrupted data when\n non-Python-unicode strings (a.k.a. plain old Python strings)\n are passed as arguments to connect(), the statement sent to execute(),\n or any of the bind parameter keys or values sent to execute().\n This optional context therefore ensures that all statements are\n passed as Python unicode objects.\n\n \"\"\"\n def __init__(self, *arg, **kw):\n OracleExecutionContext_cx_oracle.__init__(self, *arg, **kw)\n self.statement = util.text_type(self.statement)\n\n def _execute_scalar(self, stmt):\n return super(OracleExecutionContext_cx_oracle_with_unicode, self).\\\n _execute_scalar(util.text_type(stmt))\n\n\nclass ReturningResultProxy(_result.FullyBufferedResultProxy):\n \"\"\"Result proxy which stuffs the _returning clause + outparams into the fetch.\"\"\"\n\n def __init__(self, context, returning_params):\n self._returning_params = returning_params\n super(ReturningResultProxy, self).__init__(context)\n\n def _cursor_description(self):\n returning = self.context.compiled.returning\n return [\n (\"ret_%d\" % i, None)\n for i, col in enumerate(returning)\n ]\n\n def _buffer_rows(self):\n return collections.deque([tuple(self._returning_params[\"ret_%d\" % i]\n for i, c in enumerate(self._returning_params))])\n\n\nclass OracleDialect_cx_oracle(OracleDialect):\n execution_ctx_cls = OracleExecutionContext_cx_oracle\n statement_compiler = OracleCompiler_cx_oracle\n\n driver = \"cx_oracle\"\n\n colspecs = colspecs = {\n sqltypes.Numeric: _OracleNumeric,\n sqltypes.Date: _OracleDate, # generic type, assume datetime.date is desired\n sqltypes.LargeBinary: _OracleBinary,\n sqltypes.Boolean: oracle._OracleBoolean,\n sqltypes.Interval: _OracleInterval,\n oracle.INTERVAL: _OracleInterval,\n sqltypes.Text: _OracleText,\n sqltypes.String: _OracleString,\n sqltypes.UnicodeText: _OracleUnicodeText,\n sqltypes.CHAR: _OracleChar,\n\n # a raw LONG is a text type, but does *not*\n # get the LobMixin with cx_oracle.\n oracle.LONG: _OracleLong,\n\n # this is only needed for OUT parameters.\n # it would be nice if we could not use it otherwise.\n sqltypes.Integer: _OracleInteger,\n\n oracle.RAW: _OracleRaw,\n sqltypes.Unicode: _OracleNVarChar,\n sqltypes.NVARCHAR: _OracleNVarChar,\n oracle.ROWID: _OracleRowid,\n }\n\n execute_sequence_format = list\n\n def __init__(self,\n auto_setinputsizes=True,\n exclude_setinputsizes=(\"STRING\", \"UNICODE\"),\n auto_convert_lobs=True,\n threaded=True,\n allow_twophase=True,\n coerce_to_decimal=True,\n coerce_to_unicode=False,\n arraysize=50, **kwargs):\n OracleDialect.__init__(self, **kwargs)\n self.threaded = threaded\n self.arraysize = arraysize\n self.allow_twophase = allow_twophase\n self.supports_timestamp = self.dbapi is None or \\\n hasattr(self.dbapi, 'TIMESTAMP')\n self.auto_setinputsizes = auto_setinputsizes\n self.auto_convert_lobs = auto_convert_lobs\n\n if hasattr(self.dbapi, 'version'):\n self.cx_oracle_ver = tuple([int(x) for x in\n self.dbapi.version.split('.')])\n else:\n self.cx_oracle_ver = (0, 0, 0)\n\n def types(*names):\n return set(\n getattr(self.dbapi, name, None) for name in names\n ).difference([None])\n\n self.exclude_setinputsizes = types(*(exclude_setinputsizes or ()))\n self._cx_oracle_string_types = types(\"STRING\", \"UNICODE\",\n \"NCLOB\", \"CLOB\")\n self._cx_oracle_unicode_types = types(\"UNICODE\", \"NCLOB\")\n self._cx_oracle_binary_types = types(\"BFILE\", \"CLOB\", \"NCLOB\", \"BLOB\")\n self.supports_unicode_binds = self.cx_oracle_ver >= (5, 0)\n\n self.coerce_to_unicode = (\n self.cx_oracle_ver >= (5, 0) and\n coerce_to_unicode\n )\n\n self.supports_native_decimal = (\n self.cx_oracle_ver >= (5, 0) and\n coerce_to_decimal\n )\n\n self._cx_oracle_native_nvarchar = self.cx_oracle_ver >= (5, 0)\n\n if self.cx_oracle_ver is None:\n # this occurs in tests with mock DBAPIs\n self._cx_oracle_string_types = set()\n self._cx_oracle_with_unicode = False\n elif self.cx_oracle_ver >= (5,) and not hasattr(self.dbapi, 'UNICODE'):\n # cx_Oracle WITH_UNICODE mode. *only* python\n # unicode objects accepted for anything\n self.supports_unicode_statements = True\n self.supports_unicode_binds = True\n self._cx_oracle_with_unicode = True\n\n if util.py2k:\n # There's really no reason to run with WITH_UNICODE under Python 2.x.\n # Give the user a hint.\n util.warn(\n \"cx_Oracle is compiled under Python 2.xx using the \"\n \"WITH_UNICODE flag. Consider recompiling cx_Oracle \"\n \"without this flag, which is in no way necessary for full \"\n \"support of Unicode. Otherwise, all string-holding bind \"\n \"parameters must be explicitly typed using SQLAlchemy's \"\n \"String type or one of its subtypes,\"\n \"or otherwise be passed as Python unicode. \"\n \"Plain Python strings passed as bind parameters will be \"\n \"silently corrupted by cx_Oracle.\"\n )\n self.execution_ctx_cls = \\\n OracleExecutionContext_cx_oracle_with_unicode\n else:\n self._cx_oracle_with_unicode = False\n\n if self.cx_oracle_ver is None or \\\n not self.auto_convert_lobs or \\\n not hasattr(self.dbapi, 'CLOB'):\n self.dbapi_type_map = {}\n else:\n # only use this for LOB objects. using it for strings, dates\n # etc. leads to a little too much magic, reflection doesn't know if it should\n # expect encoded strings or unicodes, etc.\n self.dbapi_type_map = {\n self.dbapi.CLOB: oracle.CLOB(),\n self.dbapi.NCLOB: oracle.NCLOB(),", "answers": [" self.dbapi.BLOB: oracle.BLOB(),"], "length": 3054, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "9c5183c7-03ad-4e45-bdd2-e6679a7b0d68", "reasoning": "The code is defining a mapping of DBAPI types to SQLAlchemy Oracle type objects. After mapping CLOB and NCLOB, the next logical entry is to map the BLOB type. Therefore the next line adds the BLOB mapping.", "reasoning_model_answer": "self.dbapi.BLOB: oracle.BLOB(),", "assistant_with_reasoning": "\nThe code is defining a mapping of DBAPI types to SQLAlchemy Oracle type objects. After mapping CLOB and NCLOB, the next logical entry is to map the BLOB type. Therefore the next line adds the BLOB mapping.\n\nself.dbapi.BLOB: oracle.BLOB(),", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.019, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 30151, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "self.dbapi.BLOB: oracle.BLOB(),", "score": 0.79, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "\"\"\"This module contains tests which are supposed to run on both root Marathon and Marathon on Marathon (MoM).\"\"\"\n\nimport apps\nimport common\nimport groups\nimport os\nimport os.path\nimport pytest\nimport retrying\nimport scripts\nimport shakedown\nimport time\n\nfrom datetime import timedelta\nfrom dcos import http, marathon\nfrom shakedown import dcos_version_less_than, marthon_version_less_than, required_private_agents # NOQA\n\n\ndef test_launch_mesos_container():\n \"\"\"Launches a Mesos container with a simple command.\"\"\"\n\n app_def = apps.mesos_app()\n\n client = marathon.create_client()\n client.add_app(app_def)\n shakedown.deployment_wait()\n\n tasks = client.get_tasks(app_def[\"id\"])\n app = client.get_app(app_def[\"id\"])\n\n assert len(tasks) == 1, \"The number of tasks is {} after deployment, but only 1 was expected\".format(len(tasks))\n assert app['container']['type'] == 'MESOS', \"The container type is not MESOS\"\n\n\ndef test_launch_docker_container():\n \"\"\"Launches a Docker container on Marathon.\"\"\"\n\n app_def = apps.docker_http_server()\n app_id = app_def[\"id\"]\n\n client = marathon.create_client()\n client.add_app(app_def)\n shakedown.deployment_wait(app_id=app_id)\n\n tasks = client.get_tasks(app_id)\n app = client.get_app(app_id)\n\n assert len(tasks) == 1, \"The number of tasks is {} after deployment, but only 1 was expected\".format(len(tasks))\n assert app['container']['type'] == 'DOCKER', \"The container type is not DOCKER\"\n\n\ndef test_launch_mesos_container_with_docker_image():\n \"\"\"Launches a Mesos container with a Docker image.\"\"\"\n\n app_def = apps.ucr_docker_http_server()\n app_id = app_def[\"id\"]\n\n client = marathon.create_client()\n client.add_app(app_def)\n shakedown.deployment_wait(app_id=app_id)\n\n tasks = client.get_tasks(app_id)\n app = client.get_app(app_id)\n\n assert len(tasks) == 1, \"The number of tasks is {} after deployment, but only 1 was expected\".format(len(tasks))\n assert app['container']['type'] == 'MESOS', \"The container type is not MESOS\"\n\n\n# This fails on DC/OS 1.7, it is likely the version of Marathon in Universe for 1.7, is 1.1.5.\n@shakedown.dcos_1_8\ndef test_launch_mesos_grace_period(marathon_service_name):\n \"\"\"Tests 'taskKillGracePeriodSeconds' option using a Mesos container in a Marathon environment.\n Read more details about this test in `test_root_marathon.py::test_launch_mesos_root_marathon_grace_period`\n \"\"\"\n\n app_def = apps.mesos_app()\n\n default_grace_period = 3\n grace_period = 20\n\n app_def['fetch'] = [{\"uri\": \"https://downloads.mesosphere.com/testing/test.py\"}]\n app_def['cmd'] = '/opt/mesosphere/bin/python test.py'\n app_def['taskKillGracePeriodSeconds'] = grace_period\n app_id = app_def['id'].lstrip('/')\n\n client = marathon.create_client()\n client.add_app(app_def)\n shakedown.deployment_wait(app_id=app_id)\n\n tasks = shakedown.get_service_task(marathon_service_name, app_id)\n assert tasks is not None\n\n client.scale_app(app_id, 0)\n tasks = shakedown.get_service_task(marathon_service_name, app_id)\n assert tasks is not None\n\n # tasks should still be here after the default_grace_period\n time.sleep(default_grace_period + 1)\n tasks = shakedown.get_service_task(marathon_service_name, app_id)\n assert tasks is not None\n\n # but not after the set grace_period\n time.sleep(grace_period)\n tasks = shakedown.get_service_task(marathon_service_name, app_id)\n assert tasks is None\n\n\ndef test_launch_docker_grace_period(marathon_service_name):\n \"\"\"Tests 'taskKillGracePeriodSeconds' option using a Docker container in a Marathon environment.\n Read more details about this test in `test_root_marathon.py::test_launch_mesos_root_marathon_grace_period`\n \"\"\"\n\n app_def = apps.docker_http_server()\n app_def['container']['docker']['image'] = 'kensipe/python-test'\n\n default_grace_period = 3\n grace_period = 20\n app_def['taskKillGracePeriodSeconds'] = grace_period\n app_def['cmd'] = 'python test.py'\n app_id = app_def['id'].lstrip('/')\n\n client = marathon.create_client()\n client.add_app(app_def)\n shakedown.deployment_wait(app_id=app_id)\n\n tasks = shakedown.get_service_task(marathon_service_name, app_id)\n assert tasks is not None\n\n client.scale_app(app_id, 0)\n tasks = shakedown.get_service_task(marathon_service_name, app_id)\n assert tasks is not None\n\n # tasks should still be here after the default_graceperiod\n time.sleep(default_grace_period + 1)\n tasks = shakedown.get_service_task(marathon_service_name, app_id)\n assert tasks is not None\n\n # but not after the set grace_period\n time.sleep(grace_period)\n tasks = shakedown.get_service_task(marathon_service_name, app_id)\n assert tasks is None\n\n\ndef test_docker_port_mappings():\n \"\"\"Tests that Docker ports are mapped and are accessible from the host.\"\"\"\n\n app_def = apps.docker_http_server()\n\n client = marathon.create_client()\n client.add_app(app_def)\n shakedown.deployment_wait(app_id=app_def[\"id\"])\n\n tasks = client.get_tasks(app_def[\"id\"])\n host = tasks[0]['host']\n port = tasks[0]['ports'][0]\n cmd = r'curl -s -w \"%{http_code}\"'\n cmd = cmd + ' {}:{}/.dockerenv'.format(host, port)\n status, output = shakedown.run_command_on_agent(host, cmd)\n\n assert status\n assert output == \"200\", \"HTTP status code is {}, but 200 was expected\".format(output)\n\n\ndef test_docker_dns_mapping(marathon_service_name):\n \"\"\"Tests that a running Docker task is accessible via DNS.\"\"\"\n\n app_def = apps.docker_http_server()\n\n client = marathon.create_client()\n client.add_app(app_def)\n shakedown.deployment_wait(app_id=app_def[\"id\"])\n\n bad_cmd = 'ping -c 1 docker-test.marathon-user.mesos-bad'\n status, output = shakedown.run_command_on_master(bad_cmd)\n assert not status\n\n @retrying.retry(wait_fixed=1000, stop_max_attempt_number=30, retry_on_exception=common.ignore_exception)\n def check_dns():\n dnsname = '{}.{}.mesos'.format(app_def[\"id\"].lstrip('/'), marathon_service_name)\n cmd = 'ping -c 1 {}'.format(dnsname)\n shakedown.wait_for_dns(dnsname)\n status, output = shakedown.run_command_on_master(cmd)\n assert status, \"ping failed for app using DNS lookup: {}\".format(dnsname)\n\n check_dns()\n\n\ndef test_launch_app_timed():\n \"\"\"Most tests wait until a task is launched with no reference to time.\n This test verifies that if a app is launched on marathon that within 3 secs there is a task spawned.\n \"\"\"\n\n app_def = apps.mesos_app()\n\n client = marathon.create_client()\n client.add_app(app_def)\n\n # if not launched in 3 sec fail\n time.sleep(3)\n tasks = client.get_tasks(app_def[\"id\"])\n\n assert len(tasks) == 1, \"The number of tasks is {} after deployment, but 1 was expected\".format(len(tasks))\n\n\ndef test_ui_available(marathon_service_name):\n \"\"\"Simply verifies that a request to the UI endpoint is successful if Marathon is launched.\"\"\"\n\n response = http.get(\"{}/ui/\".format(shakedown.dcos_service_url(marathon_service_name)))\n assert response.status_code == 200, \"HTTP status code is {}, but 200 was expected\".format(response.status_code)\n\n\ndef test_task_failure_recovers():\n \"\"\"Tests that if a task is KILLED, another one will be launched with a different ID.\"\"\"\n\n app_def = apps.sleep_app()\n app_def['cmd'] = 'sleep 1000'\n\n client = marathon.create_client()\n client.add_app(app_def)\n shakedown.deployment_wait(app_id=app_def[\"id\"])\n\n tasks = client.get_tasks(app_def[\"id\"])\n old_task_id = tasks[0]['id']\n host = tasks[0]['host']\n\n common.kill_process_on_host(host, '[s]leep 1000')\n shakedown.deployment_wait()\n\n @retrying.retry(wait_fixed=1000, stop_max_attempt_number=30, retry_on_exception=common.ignore_exception)\n def check_new_task_id():\n tasks = client.get_tasks(app_def[\"id\"])\n new_task_id = tasks[0]['id']\n assert old_task_id != new_task_id, \"The task ID has not changed: {}\".format(old_task_id)\n\n check_new_task_id()\n\n\n@pytest.mark.skipif(\"shakedown.ee_version() == 'strict'\")\ndef test_run_app_with_specified_user():\n \"\"\"Runs an app with a given user (core). CoreOS is expected, since it has core user by default.\"\"\"\n\n app_def = apps.sleep_app()\n app_def['user'] = 'core'\n app_id = app_def['id']\n\n client = marathon.create_client()\n client.add_app(app_def)\n shakedown.deployment_wait(app_id=app_id)\n\n tasks = client.get_tasks(app_id)\n task = tasks[0]\n assert task['state'] == 'TASK_RUNNING', \"The task is not running: {}\".format(task['state'])\n\n app = client.get_app(app_def[\"id\"])\n assert app['user'] == 'core', \"The app's user is not core: {}\".format(app['user'])\n\n\n@pytest.mark.skipif(\"shakedown.ee_version() == 'strict'\")\ndef test_run_app_with_non_existing_user():\n \"\"\"Runs an app with a non-existing user, which should be failing.\"\"\"\n\n app_def = apps.sleep_app()\n app_def['user'] = 'bad'\n\n client = marathon.create_client()\n client.add_app(app_def)\n\n @retrying.retry(wait_fixed=1000, stop_max_attempt_number=30, retry_on_exception=common.ignore_exception)\n def check_failure_message():\n app = client.get_app(app_def[\"id\"])\n message = app['lastTaskFailure']['message']\n error = \"No such user 'bad'\"\n assert error in message, f\"Did not receive expected error messsage \\\"{error}\\\" but \\\"{message}\\\"\" # noqa E999\n\n check_failure_message()\n\n\ndef test_run_app_with_non_downloadable_artifact():\n \"\"\"Runs an app with a non-downloadable artifact.\"\"\"\n\n app_def = apps.sleep_app()\n app_def['fetch'] = [{\"uri\": \"http://localhost/missing-artifact\"}]\n\n client = marathon.create_client()\n client.add_app(app_def)\n\n @retrying.retry(wait_fixed=1000, stop_max_attempt_number=30, retry_on_exception=common.ignore_exception)\n def check_failure_message():\n app = client.get_app(app_def[\"id\"])\n message = app['lastTaskFailure']['message']\n error = \"Failed to fetch all URIs for container\"\n assert error in message, \"Launched an app with a non-downloadable artifact\"\n\n check_failure_message()\n\n\ndef test_launch_group():\n \"\"\"Launches a group of 2 apps.\"\"\"\n\n group_def = groups.sleep_group()\n groups_id = group_def[\"groups\"][0][\"id\"]\n\n client = marathon.create_client()\n client.create_group(group_def)\n\n shakedown.deployment_wait()\n\n group_apps = client.get_group(groups_id)\n apps = group_apps['apps']\n assert len(apps) == 2, \"The numbers of apps is {} after deployment, but 2 is expected\".format(len(apps))\n\n\n@shakedown.private_agents(2)\ndef test_launch_and_scale_group():\n \"\"\"Launches and scales a group.\"\"\"\n\n group_def = groups.sleep_group()\n groups_id = group_def[\"groups\"][0][\"id\"]\n\n client = marathon.create_client()\n client.create_group(group_def)\n\n shakedown.deployment_wait()\n\n group_apps = client.get_group(groups_id)\n apps = group_apps['apps']\n assert len(apps) == 2, \"The number of apps is {}, but 2 was expected\".format(len(apps))\n\n app1_id = group_def[\"groups\"][0][\"apps\"][0][\"id\"]\n app2_id = group_def[\"groups\"][0][\"apps\"][1][\"id\"]\n tasks1 = client.get_tasks(app1_id)\n tasks2 = client.get_tasks(app2_id)\n assert len(tasks1) == 1, \"The number of tasks #1 is {} after deployment, but 1 was expected\".format(len(tasks1))\n assert len(tasks2) == 1, \"The number of tasks #2 is {} after deployment, but 1 was expected\".format(len(tasks2))\n\n # scale by 2 for the entire group\n client.scale_group(groups_id, 2)\n shakedown.deployment_wait()\n\n tasks1 = client.get_tasks(app1_id)\n tasks2 = client.get_tasks(app2_id)\n assert len(tasks1) == 2, \"The number of tasks #1 is {} after scale, but 2 was expected\".format(len(tasks1))\n assert len(tasks2) == 2, \"The number of tasks #2 is {} after scale, but 2 was expected\".format(len(tasks2))\n\n\n@shakedown.private_agents(2)\ndef test_scale_app_in_group():\n \"\"\"Scales an individual app in a group.\"\"\"\n\n group_def = groups.sleep_group()\n groups_id = group_def[\"groups\"][0][\"id\"]\n\n client = marathon.create_client()\n client.create_group(group_def)\n\n shakedown.deployment_wait()\n\n group_apps = client.get_group(groups_id)\n apps = group_apps['apps']\n assert len(apps) == 2, \"The number of apps is {}, but 2 was expected\".format(len(apps))\n\n app1_id = group_def[\"groups\"][0][\"apps\"][0][\"id\"]\n app2_id = group_def[\"groups\"][0][\"apps\"][1][\"id\"]\n tasks1 = client.get_tasks(app1_id)\n tasks2 = client.get_tasks(app2_id)\n assert len(tasks1) == 1, \"The number of tasks #1 is {} after deployment, but 1 was expected\".format(len(tasks1))\n assert len(tasks2) == 1, \"The number of tasks #2 is {} after deployment, but 1 was expected\".format(len(tasks2))\n\n # scaling just one app in the group\n client.scale_app(app1_id, 2)\n shakedown.deployment_wait()\n\n tasks1 = client.get_tasks(app1_id)\n tasks2 = client.get_tasks(app2_id)\n assert len(tasks1) == 2, \"The number of tasks #1 is {} after scale, but 2 was expected\".format(len(tasks1))\n assert len(tasks2) == 1, \"The number of tasks #2 is {} after scale, but 1 was expected\".format(len(tasks2))\n\n\n@shakedown.private_agents(2)\ndef test_scale_app_in_group_then_group():\n \"\"\"First scales an app in a group, then scales the group itself.\"\"\"\n\n group_def = groups.sleep_group()\n groups_id = group_def[\"groups\"][0][\"id\"]\n\n client = marathon.create_client()\n client.create_group(group_def)\n\n shakedown.deployment_wait()\n\n group_apps = client.get_group(groups_id)\n apps = group_apps['apps']\n assert len(apps) == 2, \"The number of apps is {}, but 2 was expected\".format(len(apps))\n\n app1_id = group_def[\"groups\"][0][\"apps\"][0][\"id\"]\n app2_id = group_def[\"groups\"][0][\"apps\"][1][\"id\"]\n tasks1 = client.get_tasks(app1_id)\n tasks2 = client.get_tasks(app2_id)\n assert len(tasks1) == 1, \"The number of tasks #1 is {} after deployment, but 1 was expected\".format(len(tasks1))\n assert len(tasks2) == 1, \"The number of tasks #2 is {} after deployment, but 1 was expected\".format(len(tasks2))\n\n # scaling just one app in the group\n client.scale_app(app1_id, 2)\n shakedown.deployment_wait()\n\n tasks1 = client.get_tasks(app1_id)\n tasks2 = client.get_tasks(app2_id)\n assert len(tasks1) == 2, \"The number of tasks #1 is {} after scale, but 2 was expected\".format(len(tasks1))\n assert len(tasks2) == 1, \"The number of tasks #2 is {} after scale, but 1 was expected\".format(len(tasks2))\n shakedown.deployment_wait()\n\n # scaling the group after one app in the group was scaled\n client.scale_group(groups_id, 2)\n shakedown.deployment_wait()\n\n tasks1 = client.get_tasks(app1_id)\n tasks2 = client.get_tasks(app2_id)\n assert len(tasks1) == 4, \"The number of tasks #1 is {} after scale, but 4 was expected\".format(len(tasks1))\n assert len(tasks2) == 2, \"The number of tasks #2 is {} after scale, but 2 was expected\".format(len(tasks2))\n\n\ndef assert_app_healthy(client, app_def, health_check):\n app_def['healthChecks'] = [health_check]\n instances = app_def['instances']\n\n print('Testing {} health check protocol.'.format(health_check['protocol']))\n client.add_app(app_def)\n\n shakedown.deployment_wait(timeout=timedelta(minutes=5).total_seconds())\n\n app = client.get_app(app_def[\"id\"])\n assert app['tasksRunning'] == instances, \\\n \"The number of running tasks is {}, but {} was expected\".format(app['tasksRunning'], instances)\n assert app['tasksHealthy'] == instances, \\\n \"The number of healthy tasks is {}, but {} was expected\".format(app['tasksHealthy'], instances)\n\n\n@shakedown.dcos_1_9\n@pytest.mark.parametrize('protocol', ['HTTP', 'MESOS_HTTP', 'TCP', 'MESOS_TCP'])\ndef test_http_health_check_healthy(protocol):\n \"\"\"Tests HTTP, MESOS_HTTP, TCP and MESOS_TCP health checks against a web-server in Python.\"\"\"\n\n app_def = apps.http_server()\n client = marathon.create_client()\n assert_app_healthy(client, app_def, common.health_check(protocol=protocol))\n\n\ndef test_app_with_no_health_check_not_healthy():\n \"\"\"Makes sure that no task is marked as healthy if no health check is defined for the corresponding app.\"\"\"\n\n app_def = apps.sleep_app()\n app_id = app_def[\"id\"]\n client = marathon.create_client()\n client.add_app(app_def)\n\n shakedown.deployment_wait(app_id=app_id)\n\n app = client.get_app(app_id)\n\n assert app['tasksRunning'] == 1, \\\n \"The number of running tasks is {}, but 1 was expected\".format(app['tasksRunning'])\n assert app['tasksHealthy'] == 0, \\\n \"The number of healthy tasks is {}, but 0 was expected\".format(app['tasksHealthy'])\n\n\ndef test_command_health_check_healthy():\n \"\"\"Tests COMMAND health check\"\"\"\n\n app_def = apps.sleep_app()\n client = marathon.create_client()\n assert_app_healthy(client, app_def, common.command_health_check())\n\n\n@shakedown.dcos_1_9\n@pytest.mark.parametrize('protocol', ['HTTPS', 'MESOS_HTTPS'])\ndef test_https_health_check_healthy(protocol):\n \"\"\"Tests HTTPS and MESOS_HTTPS health checks using a prepared nginx image that enables\n SSL (using self-signed certificate) and listens on 443.\n \"\"\"\n # marathon version captured here will work for root and mom\n requires_marathon_version('1.4.2')\n\n client = marathon.create_client()\n app_def = apps.docker_nginx_ssl()\n assert_app_healthy(client, app_def, common.health_check(protocol=protocol, port_index=1))\n\n\ndef test_failing_health_check_results_in_unhealthy_app():\n \"\"\"Tests failed health checks of an app. The health check is meant to never pass.\"\"\"\n\n app_def = apps.http_server()\n app_def['healthChecks'] = [common.health_check('/bad-url', 'HTTP', failures=0, timeout=3)]\n\n client = marathon.create_client()\n client.add_app(app_def)\n\n @retrying.retry(wait_fixed=1000, stop_max_attempt_number=30, retry_on_exception=common.ignore_exception)\n def check_failure_message():\n app = client.get_app(app_def[\"id\"])\n print(\"{}, {}, {}\".format(app['tasksRunning'], app['tasksHealthy'], app['tasksUnhealthy']))\n assert app['tasksRunning'] == 1, \\\n \"The number of running tasks is {}, but 1 was expected\".format(app['tasksRunning'])\n assert app['tasksHealthy'] == 0, \\\n \"The number of healthy tasks is {}, but 0 was expected\".format(app['tasksHealthy'])\n assert app['tasksUnhealthy'] == 1, \\\n \"The number of unhealthy tasks is {}, but 1 was expected\".format(app['tasksUnhealthy'])\n\n check_failure_message()\n\n\n@shakedown.private_agents(2)\ndef test_task_gets_restarted_due_to_network_split():\n \"\"\"Verifies that a health check fails in presence of a network partition.\"\"\"\n\n app_def = apps.http_server()\n app_def['healthChecks'] = [common.health_check()]\n common.pin_to_host(app_def, common.ip_other_than_mom())\n\n client = marathon.create_client()\n client.add_app(app_def)\n\n shakedown.deployment_wait()\n\n app = client.get_app(app_def[\"id\"])\n assert app['tasksRunning'] == 1, \\\n \"The number of running tasks is {}, but 1 was expected\".format(app['tasksRunning'])\n assert app['tasksHealthy'] == 1, \\\n \"The number of healthy tasks is {}, but 1 was expected\".format(app['tasksHealthy'])\n\n tasks = client.get_tasks(app_def[\"id\"])\n task_id = tasks[0]['id']\n host = tasks[0]['host']\n port = tasks[0]['ports'][0]\n\n # introduce a network partition\n common.block_iptable_rules_for_seconds(host, port, sleep_seconds=10, block_input=True, block_output=False)\n\n shakedown.deployment_wait()\n\n app = client.get_app(app_def[\"id\"])\n tasks = client.get_tasks(app_def[\"id\"])\n new_task_id = tasks[0]['id']\n assert task_id != new_task_id, \"The task didn't get killed because of a failed health check\"\n\n assert app['tasksRunning'] == 1, \\\n \"The number of running tasks is {}, but 1 was expected\".format(app['tasksRunning'])\n assert app['tasksHealthy'] == 1, \\\n \"The number of healthy tasks is {}, but 0 was expected\".format(app['tasksHealthy'])\n\n # network partition should cause a task restart\n @retrying.retry(wait_fixed=1000, stop_max_attempt_number=30, retry_on_exception=common.ignore_exception)\n def check_health_message():\n tasks = client.get_tasks(app_def[\"id\"])\n new_task_id = tasks[0]['id']\n assert task_id != new_task_id, \"The task has not been restarted: {}\".format(task_id)\n\n app = client.get_app(app_def[\"id\"])\n assert app['tasksRunning'] == 1, \\\n \"The number of running tasks is {}, but 1 was expected\".format(app['tasksRunning'])\n assert app['tasksHealthy'] == 1, \\\n \"The number of healthy tasks is {}, but 1 was expected\".format(app['tasksHealthy'])\n\n check_health_message()\n\n\ndef test_health_check_works_with_resident_task():\n \"\"\"Verifies that resident tasks (common for Persistent Volumes) do not fail health checks.\n Marathon bug: https://jira.mesosphere.com/browse/MARATHON-7050\n \"\"\"\n\n app_def = apps.resident_docker_app()\n\n client = marathon.create_client()\n client.add_app(app_def)\n\n shakedown.deployment_wait(timeout=timedelta(minutes=10).total_seconds())\n tasks = client.get_tasks(app_def[\"id\"])\n assert len(tasks) == 1, \"The number of tasks is {}, but 1 was expected\".format(len(tasks))\n\n app = client.get_app(app_def[\"id\"])\n assert app['tasksHealthy'] == 1, \\\n \"The number of healthy tasks is {}, but 1 was expected\".format(app['tasksHealthy'])\n\n\n@shakedown.private_agents(2)\ndef test_pinned_task_scales_on_host_only():\n \"\"\"Tests that a pinned app scales only on the pinned node.\"\"\"\n\n app_def = apps.sleep_app()\n host = common.ip_other_than_mom()\n common.pin_to_host(app_def, host)\n\n client = marathon.create_client()\n client.add_app(app_def)\n\n shakedown.deployment_wait()\n\n tasks = client.get_tasks(app_def[\"id\"])\n assert len(tasks) == 1, \"The number of tasks is {} after deployment, but 1 was expected\".format(len(tasks))\n assert tasks[0]['host'] == host, \\\n \"The task is on {}, but it is supposed to be on {}\".format(tasks[0]['host'], host)\n\n client.scale_app(app_def[\"id\"], 10)\n shakedown.deployment_wait()\n\n tasks = client.get_tasks(app_def[\"id\"])\n assert len(tasks) == 10, \"The number of tasks is {} after scale, but 10 was expected\".format(len(tasks))\n for task in tasks:\n assert task['host'] == host, \"The task is on {}, but it is supposed to be on {}\".format(task['host'], host)\n\n\n@shakedown.private_agents(2)\ndef test_pinned_task_recovers_on_host():\n \"\"\"Tests that when a pinned task gets killed, it recovers on the node it was pinned to.\"\"\"\n\n app_def = apps.sleep_app()\n host = common.ip_other_than_mom()\n common.pin_to_host(app_def, host)\n\n client = marathon.create_client()\n client.add_app(app_def)\n\n shakedown.deployment_wait()\n tasks = client.get_tasks(app_def[\"id\"])\n\n common.kill_process_on_host(host, '[s]leep')\n shakedown.deployment_wait()\n\n @retrying.retry(wait_fixed=1000, stop_max_attempt_number=30, retry_on_exception=common.ignore_exception)\n def check_for_new_task():\n new_tasks = client.get_tasks(app_def[\"id\"])\n assert tasks[0]['id'] != new_tasks[0]['id'], \"The task did not get killed: {}\".format(tasks[0]['id'])\n assert new_tasks[0]['host'] == host, \\\n \"The task got restarted on {}, but it was supposed to stay on {}\".format(new_tasks[0]['host'], host)\n\n check_for_new_task()\n\n\n@shakedown.private_agents(2)\ndef test_pinned_task_does_not_scale_to_unpinned_host():\n \"\"\"Tests when a task lands on a pinned node (and barely fits) and it is asked to scale past\n the resources of that node, no tasks will be launched on any other node.\n \"\"\"\n\n app_def = apps.sleep_app()\n app_id = app_def['id']\n\n host = common.ip_other_than_mom()\n print('Constraint set to host: {}'.format(host))\n # the size of cpus is designed to be greater than 1/2 of a node\n # such that only 1 task can land on the node.\n cores = common.cpus_on_agent(host)\n app_def['cpus'] = max(0.6, cores - 0.5)\n common.pin_to_host(app_def, host)\n\n client = marathon.create_client()\n client.add_app(app_def)\n\n shakedown.deployment_wait(app_id=app_id)\n client.scale_app(app_id, 2)\n\n time.sleep(5)\n deployments = client.get_deployments(app_id=app_id)\n tasks = client.get_tasks(app_id)\n\n # still deploying\n assert len(deployments) == 1, \"The number of deployments is {}, but 1 was expected\".format(len(deployments))\n assert len(tasks) == 1, \"The number of tasks is {}, but 1 was expected\".format(len(tasks))\n\n\n@shakedown.private_agents(2)\ndef test_pinned_task_does_not_find_unknown_host():\n \"\"\"Tests that a task pinned to an unknown host will not launch.\n Within 10 secs it should still be in deployment and 0 tasks should be running.\n \"\"\"\n\n app_def = apps.sleep_app()\n common.pin_to_host(app_def, '10.255.255.254')\n\n client = marathon.create_client()\n client.add_app(app_def)\n\n # apps deploy within secs\n # assuming that after 10 no tasks meets criteria\n time.sleep(10)\n\n tasks = client.get_tasks(app_def[\"id\"])\n assert len(tasks) == 0, \"The number of tasks is {}, 0 was expected\".format(len(tasks))\n\n\n@shakedown.dcos_1_8\ndef test_restart_container_with_persistent_volume():\n \"\"\"A task with a persistent volume, which writes to a file in the persistent volume, is launched.\n The app is killed and restarted and we can still read from the persistent volume what was written to it.\n \"\"\"\n\n app_def = apps.persistent_volume_app()\n app_id = app_def['id']\n\n client = marathon.create_client()\n client.add_app(app_def)\n\n common.deployment_wait(service_id=app_id)\n\n tasks = client.get_tasks(app_id)\n assert len(tasks) == 1, \"The number of tasks is {} after deployment, but 1 was expected\".format(len(tasks))\n\n host = tasks[0]['host']\n port = tasks[0]['ports'][0]\n cmd = \"curl {}:{}/data/foo\".format(host, port)\n\n @retrying.retry(wait_fixed=1000, stop_max_attempt_number=30, retry_on_exception=common.ignore_exception)\n def check_task(cmd, target_data):\n run, data = shakedown.run_command_on_master(cmd)\n\n assert run, \"{} did not succeed\".format(cmd)\n assert data == target_data, \"'{}' was not equal to {}\".format(data, target_data)\n\n check_task(cmd, target_data='hello\\n')\n\n client.restart_app(app_id)\n common.deployment_wait(service_id=app_id)\n\n @retrying.retry(wait_fixed=1000, stop_max_attempt_number=30, retry_on_exception=common.ignore_exception)\n def check_task_recovery():\n tasks = client.get_tasks(app_id)\n assert len(tasks) == 1, \"The number of tasks is {} after recovery, but 1 was expected\".format(len(tasks))\n\n check_task_recovery()\n\n host = tasks[0]['host']\n port = tasks[0]['ports'][0]\n cmd = \"curl {}:{}/data/foo\".format(host, port)\n\n check_task(cmd, target_data='hello\\nhello\\n')\n\n\n@shakedown.dcos_1_8\ndef test_app_with_persistent_volume_recovers():\n \"\"\"Tests that when an app task with a persistent volume gets killed,\n it recovers on the node it was launched on, and it gets attached\n to the same persistent-volume.\"\"\"\n\n app_def = apps.persistent_volume_app()\n app_id = app_def['id']\n\n client = marathon.create_client()\n client.add_app(app_def)\n\n common.deployment_wait(service_id=app_id)\n\n tasks = client.get_tasks(app_id)\n assert len(tasks) == 1, \"The number of tasks is {} after deployment, but 1 was expected\".format(len(tasks))\n\n task_id = tasks[0]['id']\n port = tasks[0]['ports'][0]\n host = tasks[0]['host']\n cmd = \"curl {}:{}/data/foo\".format(host, port)\n\n @retrying.retry(wait_fixed=1000, stop_max_attempt_number=30, retry_on_exception=common.ignore_exception)\n def check_task(cmd, target_data):\n run, data = shakedown.run_command_on_master(cmd)\n\n assert run, \"{} did not succeed\".format(cmd)\n assert target_data in data, \"'{}' not found in {}\".format(target_data, data)\n\n check_task(cmd, target_data='hello\\n')\n\n @retrying.retry(wait_fixed=1000, stop_max_attempt_number=30, retry_on_exception=common.ignore_exception)\n def kill_task(host, pattern):\n pids = common.kill_process_on_host(host, pattern)\n assert len(pids) != 0, \"no task got killed on {} for pattern {}\".format(host, pattern)\n\n kill_task(host, '[h]ttp\\\\.server')\n\n @retrying.retry(wait_fixed=1000, stop_max_attempt_number=30, retry_on_exception=common.ignore_exception)\n def check_task_recovery():\n tasks = client.get_tasks(app_id)\n assert len(tasks) == 1, \"The number of tasks is {} after recovery, but 1 was expected\".format(len(tasks))\n\n new_task_id = tasks[0]['id']\n assert task_id != new_task_id, \"The task ID has not changed, and is still {}\".format(task_id)\n\n check_task_recovery()\n\n port = tasks[0]['ports'][0]\n host = tasks[0]['host']\n cmd = \"curl {}:{}/data/foo\".format(host, port)\n\n check_task(cmd, target_data='hello\\nhello\\n')\n\n\ndef test_app_update():\n \"\"\"Tests that an app gets successfully updated.\"\"\"\n\n app_def = apps.mesos_app()\n\n client = marathon.create_client()\n client.add_app(app_def)\n\n shakedown.deployment_wait()\n\n tasks = client.get_tasks(app_def[\"id\"])\n assert len(tasks) == 1, \"The number of tasks is {} after deployment, but 1 was expected\".format(len(tasks))\n\n app_def['cpus'] = 1\n app_def['instances'] = 2\n\n client.update_app(app_def[\"id\"], app_def)\n shakedown.deployment_wait()\n\n tasks = client.get_tasks(app_def[\"id\"])\n assert len(tasks) == 2, \"The number of tasks is {} after deployment, but 2 was expected\".format(len(tasks))\n\n\ndef test_app_update_rollback():\n \"\"\"Tests that an updated app can be rolled back to its initial version.\"\"\"\n\n app_def = apps.readiness_and_health_app()\n app_id = app_def[\"id\"]\n\n client = marathon.create_client()\n client.add_app(app_def)\n shakedown.deployment_wait()\n\n tasks = client.get_tasks(app_id)\n assert len(tasks) == 1, \"The number of tasks is {} after deployment, but 1 was expected\".format(len(tasks))\n\n app_def['instances'] = 2\n client.update_app(app_id, app_def)\n shakedown.deployment_wait()\n\n tasks = client.get_tasks(app_id)\n assert len(tasks) == 2, \"The number of tasks is {} after update, but 2 was expected\".format(len(tasks))\n\n # provides a testing delay to rollback in the meantime\n app_def['readinessChecks'][0]['intervalSeconds'] = 30\n app_def['instances'] = 1\n deployment_id = client.update_app(app_id, app_def)\n client.rollback_deployment(deployment_id)\n shakedown.deployment_wait()\n\n # update to 1 instance is rollback to 2\n tasks = client.get_tasks(app_id)\n assert len(tasks) == 2, \"The number of tasks is {} after rollback, but 2 was expected\".format(len(tasks))\n\n\ndef test_unhealthy_app_can_be_rolled_back():\n \"\"\"Verifies that an updated app gets rolled back due to being unhealthy.\"\"\"\n\n app_def = apps.readiness_and_health_app()\n app_id = app_def[\"id\"]\n\n client = marathon.create_client()\n client.add_app(app_def)\n shakedown.deployment_wait()\n\n tasks = client.get_tasks(app_id)\n assert len(tasks) == 1, \"The number of tasks is {} after deployment, but 1 was expected\".format(len(tasks))\n\n app_def['healthChecks'][0]['path'] = '/non-existent'\n app_def['instances'] = 2\n deployment_id = client.update_app(app_id, app_def)\n\n try:\n shakedown.deployment_wait()\n except Exception:\n client.rollback_deployment(deployment_id)\n shakedown.deployment_wait()\n\n tasks = client.get_tasks(app_id)\n assert len(tasks) == 1, \"The number of tasks is {} after rollback, but 1 was expected\".format(len(tasks))\n\n\n@shakedown.private_agents(2)\ndef test_marathon_with_master_process_failure(marathon_service_name):\n \"\"\"Launches an app and restarts the master. It is expected that the service endpoint eventually comes back and\n the task ID stays the same.\n \"\"\"\n\n app_def = apps.sleep_app()\n host = common.ip_other_than_mom()\n common.pin_to_host(app_def, host)\n\n client = marathon.create_client()\n client.add_app(app_def)\n shakedown.deployment_wait()\n\n tasks = client.get_tasks(app_def[\"id\"])\n original_task_id = tasks[0]['id']\n\n common.systemctl_master('restart')\n shakedown.wait_for_service_endpoint(marathon_service_name)\n\n @retrying.retry(wait_fixed=1000, stop_max_attempt_number=30, retry_on_exception=common.ignore_exception)\n def check_task_recovery():\n tasks = client.get_tasks(app_def[\"id\"])\n assert len(tasks) == 1, \"The number of tasks is {} after master restart, but 1 was expected\".format(len(tasks))\n assert tasks[0]['id'] == original_task_id, \\\n \"Task {} has not recovered, it got replaced with another one: {}\".format(original_task_id, tasks[0]['id'])\n\n check_task_recovery()\n\n\n@shakedown.private_agents(2)\ndef test_marathon_when_disconnected_from_zk():\n \"\"\"Launches an app from Marathon, then knocks out access to ZK from Marathon.\n Verifies the task is preserved.\n \"\"\"\n\n app_def = apps.sleep_app()\n host = common.ip_other_than_mom()\n common.pin_to_host(app_def, host)\n\n client = marathon.create_client()\n client.add_app(app_def)\n\n shakedown.deployment_wait()\n tasks = client.get_tasks(app_def[\"id\"])\n original_task_id = tasks[0]['id']\n\n common.block_iptable_rules_for_seconds(host, 2181, sleep_seconds=10, block_input=True, block_output=False)\n\n @retrying.retry(wait_fixed=1000, stop_max_attempt_number=30, retry_on_exception=common.ignore_exception)\n def check_task_is_back():\n tasks = client.get_tasks(app_def[\"id\"])\n assert tasks[0]['id'] == original_task_id, \\\n \"The task {} got replaced with {}\".format(original_task_id, tasks[0]['id'])\n\n check_task_is_back()\n\n\n@shakedown.private_agents(2)\ndef test_marathon_when_task_agent_bounced():\n \"\"\"Launch an app and restart the node the task is running on.\"\"\"\n\n app_def = apps.sleep_app()\n host = common.ip_other_than_mom()\n common.pin_to_host(app_def, host)\n", "answers": [" client = marathon.create_client()"], "length": 3195, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "b89bf335-18f4-40c5-bf31-08d6046822ec", "reasoning": "The function test_marathon_when_task_agent_bounced is being defined. After setting up the app definition and pinning it to a host, the next logical step is to create a Marathon client to interact with the Marathon service, as done in similar test functions earlier in the file.", "reasoning_model_answer": "client = marathon.create_client()", "assistant_with_reasoning": "\nThe function test_marathon_when_task_agent_bounced is being defined. After setting up the app definition and pinning it to a host, the next logical step is to create a Marathon client to interact with the Marathon service, as done in similar test functions earlier in the file.\n\nclient = marathon.create_client()", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.105, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 2, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 34243, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "client = marathon.create_client()", "score": 0.94, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "# -*- coding: utf-8 -*-\n##############################################################################\n#\n# OpenERP, Open Source Management Solution\n# Copyright (C) 2004-2009 Tiny SPRL ().\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Affero General Public License as\n# published by the Free Software Foundation, either version 3 of the\n# License, or (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU Affero General Public License for more details.\n#\n# You should have received a copy of the GNU Affero General Public License\n# along with this program. If not, see .\n#\n##############################################################################\n\n\"\"\" Fields:\n - simple\n - relations (one2many, many2one, many2many)\n - function\n\n Fields Attributes:\n * _classic_read: is a classic sql fields\n * _type : field type\n * _auto_join: for one2many and many2one fields, tells whether select\n queries will join the relational table instead of replacing the\n field condition by an equivalent-one based on a search.\n * readonly\n * required\n * size\n\"\"\"\n\nimport base64\nimport datetime as DT\nimport functools\nimport logging\nimport pytz\nimport re\nimport xmlrpclib\nfrom psycopg2 import Binary\n\nimport openerp\nimport openerp.tools as tools\nfrom openerp.tools.translate import _\nfrom openerp.tools import float_round, float_repr\nfrom openerp.tools import html_sanitize\nimport simplejson\nfrom openerp import SUPERUSER_ID\n\n_logger = logging.getLogger(__name__)\n\ndef _symbol_set(symb):\n if symb is None or symb == False:\n return None\n elif isinstance(symb, unicode):\n return symb.encode('utf-8')\n return str(symb)\n\n\nclass _column(object):\n \"\"\" Base of all fields, a database column\n\n An instance of this object is a *description* of a database column. It will\n not hold any data, but only provide the methods to manipulate data of an\n ORM record or even prepare/update the database to hold such a field of data.\n \"\"\"\n _classic_read = True\n _classic_write = True\n _auto_join = False\n _prefetch = True\n _properties = False\n _type = 'unknown'\n _obj = None\n _multi = False\n _symbol_c = '%s'\n _symbol_f = _symbol_set\n _symbol_set = (_symbol_c, _symbol_f)\n _symbol_get = None\n _deprecated = False\n copy = True # whether the field is copied by BaseModel.copy()\n\n def __init__(self, string='unknown', required=False, readonly=False, domain=None, context=None, states=None, priority=0, change_default=False, size=None, ondelete=None, translate=False, select=False, manual=False, **args):\n \"\"\"\n\n The 'manual' keyword argument specifies if the field is a custom one.\n It corresponds to the 'state' column in ir_model_fields.\n\n \"\"\"\n if domain is None:\n domain = []\n if context is None:\n context = {}\n self.states = states or {}\n self.string = string\n self.readonly = readonly\n self.required = required\n self.size = size\n self.help = args.get('help', '')\n self.priority = priority\n self.change_default = change_default\n self.ondelete = ondelete.lower() if ondelete else None # defaults to 'set null' in ORM\n self.translate = translate\n self._domain = domain\n self._context = context\n self.write = False\n self.read = False\n self.select = select\n self.manual = manual\n self.selectable = True\n self.group_operator = args.get('group_operator', False)\n self.groups = False # CSV list of ext IDs of groups that can access this field\n self.deprecated = False # Optional deprecation warning\n for a in args:\n setattr(self, a, args[a])\n\n # prefetch only if self._classic_write, not self.groups, and not\n # self.deprecated\n if not self._classic_write or self.deprecated:\n self._prefetch = False\n\n def to_field(self):\n \"\"\" convert column `self` to a new-style field \"\"\"\n from openerp.fields import Field\n return Field.by_type[self._type](**self.to_field_args())\n\n def to_field_args(self):\n \"\"\" return a dictionary with all the arguments to pass to the field \"\"\"\n items = [\n ('_origin', self), # field interfaces self\n ('copy', self.copy),\n ('index', self.select),\n ('manual', self.manual),\n ('string', self.string),\n ('help', self.help),\n ('readonly', self.readonly),\n ('required', self.required),\n ('states', self.states),\n ('groups', self.groups),\n ('size', self.size),\n ('ondelete', self.ondelete),\n ('translate', self.translate),\n ('domain', self._domain),\n ('context', self._context),\n ('change_default', self.change_default),\n ('deprecated', self.deprecated),\n ]\n return dict(item for item in items if item[1])\n\n def restart(self):\n pass\n\n def set(self, cr, obj, id, name, value, user=None, context=None):\n cr.execute('update '+obj._table+' set '+name+'='+self._symbol_set[0]+' where id=%s', (self._symbol_set[1](value), id))\n\n def get(self, cr, obj, ids, name, user=None, offset=0, context=None, values=None):\n raise Exception(_('undefined get method !'))\n\n def search(self, cr, obj, args, name, value, offset=0, limit=None, uid=None, context=None):\n ids = obj.search(cr, uid, args+self._domain+[(name, 'ilike', value)], offset, limit, context=context)\n res = obj.read(cr, uid, ids, [name], context=context)\n return [x[name] for x in res]\n\n def as_display_name(self, cr, uid, obj, value, context=None):\n \"\"\"Converts a field value to a suitable string representation for a record,\n e.g. when this field is used as ``rec_name``.\n\n :param obj: the ``BaseModel`` instance this column belongs to \n :param value: a proper value as returned by :py:meth:`~openerp.orm.osv.BaseModel.read`\n for this column\n \"\"\"\n # delegated to class method, so a column type A can delegate\n # to a column type B. \n return self._as_display_name(self, cr, uid, obj, value, context=None)\n\n @classmethod\n def _as_display_name(cls, field, cr, uid, obj, value, context=None):\n # This needs to be a class method, in case a column type A as to delegate\n # to a column type B.\n return tools.ustr(value)\n\n# ---------------------------------------------------------\n# Simple fields\n# ---------------------------------------------------------\nclass boolean(_column):\n _type = 'boolean'\n _symbol_c = '%s'\n _symbol_f = bool\n _symbol_set = (_symbol_c, _symbol_f)\n\n def __init__(self, string='unknown', required=False, **args):\n super(boolean, self).__init__(string=string, required=required, **args)\n if required:\n _logger.debug(\n \"required=True is deprecated: making a boolean field\"\n \" `required` has no effect, as NULL values are \"\n \"automatically turned into False. args: %r\",args)\n\nclass integer(_column):\n _type = 'integer'\n _symbol_c = '%s'\n _symbol_f = lambda x: int(x or 0)\n _symbol_set = (_symbol_c, _symbol_f)\n _symbol_get = lambda self,x: x or 0\n\n def __init__(self, string='unknown', required=False, **args):\n super(integer, self).__init__(string=string, required=required, **args)\n\nclass reference(_column):\n _type = 'reference'\n _classic_read = False # post-process to handle missing target\n\n def __init__(self, string, selection, size=None, **args):\n if callable(selection):\n from openerp import api\n selection = api.expected(api.cr_uid_context, selection)\n _column.__init__(self, string=string, size=size, selection=selection, **args)\n\n def to_field_args(self):\n args = super(reference, self).to_field_args()\n args['selection'] = self.selection\n return args\n\n def get(self, cr, obj, ids, name, uid=None, context=None, values=None):\n result = {}\n # copy initial values fetched previously.\n for value in values:\n result[value['id']] = value[name]\n if value[name]:\n model, res_id = value[name].split(',')\n if not obj.pool[model].exists(cr, uid, [int(res_id)], context=context):\n result[value['id']] = False\n return result\n\n @classmethod\n def _as_display_name(cls, field, cr, uid, obj, value, context=None):\n if value:\n # reference fields have a 'model,id'-like value, that we need to convert\n # to a real name\n model_name, res_id = value.split(',')\n if model_name in obj.pool and res_id:\n model = obj.pool[model_name]\n names = model.name_get(cr, uid, [int(res_id)], context=context)\n return names[0][1] if names else False\n return tools.ustr(value)\n\n# takes a string (encoded in utf8) and returns a string (encoded in utf8)\ndef _symbol_set_char(self, symb):\n\n #TODO:\n # * we need to remove the \"symb==False\" from the next line BUT\n # for now too many things rely on this broken behavior\n # * the symb==None test should be common to all data types\n if symb is None or symb == False:\n return None\n\n # we need to convert the string to a unicode object to be able\n # to evaluate its length (and possibly truncate it) reliably\n u_symb = tools.ustr(symb)\n return u_symb[:self.size].encode('utf8')\n\nclass char(_column):\n _type = 'char'\n\n def __init__(self, string=\"unknown\", size=None, **args):\n _column.__init__(self, string=string, size=size or None, **args)\n # self._symbol_set_char defined to keep the backward compatibility\n self._symbol_f = self._symbol_set_char = lambda x: _symbol_set_char(self, x)\n self._symbol_set = (self._symbol_c, self._symbol_f)\n\nclass text(_column):\n _type = 'text'\n\n\nclass html(text):\n _type = 'html'\n _symbol_c = '%s'\n\n def _symbol_set_html(self, value):\n if value is None or value is False:\n return None\n if not self._sanitize:\n return value\n return html_sanitize(value)\n\n def __init__(self, string='unknown', sanitize=True, **args):\n super(html, self).__init__(string=string, **args)\n self._sanitize = sanitize\n # symbol_set redefinition because of sanitize specific behavior\n self._symbol_f = self._symbol_set_html\n self._symbol_set = (self._symbol_c, self._symbol_f)\n\n def to_field_args(self):\n args = super(html, self).to_field_args()\n args['sanitize'] = self._sanitize\n return args\n\nimport __builtin__\n\nclass float(_column):\n _type = 'float'\n _symbol_c = '%s'\n _symbol_f = lambda x: __builtin__.float(x or 0.0)\n _symbol_set = (_symbol_c, _symbol_f)\n _symbol_get = lambda self,x: x or 0.0\n\n def __init__(self, string='unknown', digits=None, digits_compute=None, required=False, **args):\n _column.__init__(self, string=string, required=required, **args)\n self.digits = digits\n # synopsis: digits_compute(cr) -> (precision, scale)\n self.digits_compute = digits_compute\n\n def to_field_args(self):\n args = super(float, self).to_field_args()\n args['digits'] = self.digits_compute or self.digits\n return args\n\n def digits_change(self, cr):\n if self.digits_compute:\n self.digits = self.digits_compute(cr)\n if self.digits:\n precision, scale = self.digits\n self._symbol_set = ('%s', lambda x: float_repr(float_round(__builtin__.float(x or 0.0),\n precision_digits=scale),\n precision_digits=scale))\n\nclass date(_column):\n _type = 'date'\n\n MONTHS = [\n ('01', 'January'),\n ('02', 'February'),\n ('03', 'March'),\n ('04', 'April'),\n ('05', 'May'),\n ('06', 'June'),\n ('07', 'July'),\n ('08', 'August'),\n ('09', 'September'),\n ('10', 'October'),\n ('11', 'November'),\n ('12', 'December')\n ]\n\n @staticmethod\n def today(*args):\n \"\"\" Returns the current date in a format fit for being a\n default value to a ``date`` field.\n\n This method should be provided as is to the _defaults dict, it\n should not be called.\n \"\"\"\n return DT.date.today().strftime(\n tools.DEFAULT_SERVER_DATE_FORMAT)\n\n @staticmethod\n def context_today(model, cr, uid, context=None, timestamp=None):\n \"\"\"Returns the current date as seen in the client's timezone\n in a format fit for date fields.\n This method may be passed as value to initialize _defaults.\n\n :param Model model: model (osv) for which the date value is being\n computed - automatically passed when used in\n _defaults.\n :param datetime timestamp: optional datetime value to use instead of\n the current date and time (must be a\n datetime, regular dates can't be converted\n between timezones.)\n :param dict context: the 'tz' key in the context should give the\n name of the User/Client timezone (otherwise\n UTC is used)\n :rtype: str \n \"\"\"\n today = timestamp or DT.datetime.now()\n context_today = None\n if context and context.get('tz'):\n tz_name = context['tz'] \n else:\n user = model.pool['res.users'].browse(cr, SUPERUSER_ID, uid)\n tz_name = user.tz\n if tz_name:\n try:\n utc = pytz.timezone('UTC')\n context_tz = pytz.timezone(tz_name)\n utc_today = utc.localize(today, is_dst=False) # UTC = no DST\n context_today = utc_today.astimezone(context_tz)\n except Exception:\n _logger.debug(\"failed to compute context/client-specific today date, \"\n \"using the UTC value for `today`\",\n exc_info=True)\n return (context_today or today).strftime(tools.DEFAULT_SERVER_DATE_FORMAT)\n\n @staticmethod\n def date_to_datetime(model, cr, uid, userdate, context=None):\n \"\"\" Convert date values expressed in user's timezone to\n server-side UTC timestamp, assuming a default arbitrary\n time of 12:00 AM - because a time is needed.\n\n :param str userdate: date string in in user time zone\n :return: UTC datetime string for server-side use\n \"\"\"\n user_date = DT.datetime.strptime(userdate, tools.DEFAULT_SERVER_DATE_FORMAT)\n if context and context.get('tz'):\n tz_name = context['tz']\n else:\n tz_name = model.pool.get('res.users').read(cr, SUPERUSER_ID, uid, ['tz'])['tz']\n if tz_name:\n utc = pytz.timezone('UTC')\n context_tz = pytz.timezone(tz_name)\n user_datetime = user_date + DT.timedelta(hours=12.0)\n local_timestamp = context_tz.localize(user_datetime, is_dst=False)\n user_datetime = local_timestamp.astimezone(utc)\n return user_datetime.strftime(tools.DEFAULT_SERVER_DATETIME_FORMAT)\n return user_date.strftime(tools.DEFAULT_SERVER_DATETIME_FORMAT)\n\n\nclass datetime(_column):\n _type = 'datetime'\n\n MONTHS = [\n ('01', 'January'),\n ('02', 'February'),\n ('03', 'March'),\n ('04', 'April'),\n ('05', 'May'),\n ('06', 'June'),\n ('07', 'July'),\n ('08', 'August'),\n ('09', 'September'),\n ('10', 'October'),\n ('11', 'November'),\n ('12', 'December')\n ]\n\n @staticmethod\n def now(*args):\n \"\"\" Returns the current datetime in a format fit for being a\n default value to a ``datetime`` field.\n\n This method should be provided as is to the _defaults dict, it\n should not be called.\n \"\"\"\n return DT.datetime.now().strftime(\n tools.DEFAULT_SERVER_DATETIME_FORMAT)\n\n @staticmethod\n def context_timestamp(cr, uid, timestamp, context=None):\n \"\"\"Returns the given timestamp converted to the client's timezone.\n This method is *not* meant for use as a _defaults initializer,\n because datetime fields are automatically converted upon\n display on client side. For _defaults you :meth:`fields.datetime.now`\n should be used instead.\n\n :param datetime timestamp: naive datetime value (expressed in UTC)\n to be converted to the client timezone\n :param dict context: the 'tz' key in the context should give the\n name of the User/Client timezone (otherwise\n UTC is used)\n :rtype: datetime\n :return: timestamp converted to timezone-aware datetime in context\n timezone\n \"\"\"\n assert isinstance(timestamp, DT.datetime), 'Datetime instance expected'\n if context and context.get('tz'):\n tz_name = context['tz'] \n else:\n registry = openerp.modules.registry.RegistryManager.get(cr.dbname)\n user = registry['res.users'].browse(cr, SUPERUSER_ID, uid)\n tz_name = user.tz\n utc_timestamp = pytz.utc.localize(timestamp, is_dst=False) # UTC = no DST\n if tz_name:\n try:\n context_tz = pytz.timezone(tz_name)\n return utc_timestamp.astimezone(context_tz)\n except Exception:\n _logger.debug(\"failed to compute context/client-specific timestamp, \"\n \"using the UTC value\",\n exc_info=True)\n return utc_timestamp\n\nclass binary(_column):\n _type = 'binary'\n _symbol_c = '%s'\n\n # Binary values may be byte strings (python 2.6 byte array), but\n # the legacy OpenERP convention is to transfer and store binaries\n # as base64-encoded strings. The base64 string may be provided as a\n # unicode in some circumstances, hence the str() cast in symbol_f.\n # This str coercion will only work for pure ASCII unicode strings,\n # on purpose - non base64 data must be passed as a 8bit byte strings.\n _symbol_f = lambda symb: symb and Binary(str(symb)) or None\n\n _symbol_set = (_symbol_c, _symbol_f)\n _symbol_get = lambda self, x: x and str(x)\n\n _classic_read = False\n _prefetch = False\n\n def __init__(self, string='unknown', filters=None, **args):\n _column.__init__(self, string=string, **args)\n self.filters = filters\n\n def get(self, cr, obj, ids, name, user=None, context=None, values=None):\n if not context:\n context = {}\n if not values:\n values = []\n res = {}\n for i in ids:\n val = None\n for v in values:\n if v['id'] == i:\n val = v[name]\n break\n\n # If client is requesting only the size of the field, we return it instead\n # of the content. Presumably a separate request will be done to read the actual\n # content if it's needed at some point.\n # TODO: after 6.0 we should consider returning a dict with size and content instead of\n # having an implicit convention for the value\n if val and context.get('bin_size_%s' % name, context.get('bin_size')):\n res[i] = tools.human_size(long(val))\n else:\n res[i] = val\n return res\n\nclass selection(_column):\n _type = 'selection'\n\n def __init__(self, selection, string='unknown', **args):\n if callable(selection):\n from openerp import api\n selection = api.expected(api.cr_uid_context, selection)\n _column.__init__(self, string=string, **args)\n self.selection = selection\n\n def to_field_args(self):\n args = super(selection, self).to_field_args()\n args['selection'] = self.selection\n return args\n\n @classmethod\n def reify(cls, cr, uid, model, field, context=None):\n \"\"\" Munges the field's ``selection`` attribute as necessary to get\n something useable out of it: calls it if it's a function, applies\n translations to labels if it's not.\n\n A callable ``selection`` is considered translated on its own.\n\n :param orm.Model model:\n :param _column field:\n \"\"\"\n if callable(field.selection):\n return field.selection(model, cr, uid, context)\n\n if not (context and 'lang' in context):\n return field.selection\n\n # field_to_dict isn't given a field name, only a field object, we\n # need to get the name back in order to perform the translation lookup\n field_name = next(\n name for name, column in model._columns.iteritems()\n if column == field)\n\n translation_filter = \"%s,%s\" % (model._name, field_name)\n translate = functools.partial(\n model.pool['ir.translation']._get_source,\n cr, uid, translation_filter, 'selection', context['lang'])\n\n return [\n (value, translate(label))\n for value, label in field.selection\n ]\n\n# ---------------------------------------------------------\n# Relationals fields\n# ---------------------------------------------------------\n\n#\n# Values: (0, 0, { fields }) create\n# (1, ID, { fields }) update\n# (2, ID) remove (delete)\n# (3, ID) unlink one (target id or target of relation)\n# (4, ID) link\n# (5) unlink all (only valid for one2many)\n#\n\nclass many2one(_column):\n _classic_read = False\n _classic_write = True\n _type = 'many2one'\n _symbol_c = '%s'\n _symbol_f = lambda x: x or None\n _symbol_set = (_symbol_c, _symbol_f)\n\n def __init__(self, obj, string='unknown', auto_join=False, **args):\n _column.__init__(self, string=string, **args)\n self._obj = obj\n self._auto_join = auto_join\n\n def to_field_args(self):\n args = super(many2one, self).to_field_args()\n args['comodel_name'] = self._obj\n args['auto_join'] = self._auto_join\n return args\n\n def set(self, cr, obj_src, id, field, values, user=None, context=None):\n if not context:\n context = {}\n obj = obj_src.pool[self._obj]\n self._table = obj._table\n if type(values) == type([]):\n for act in values:\n if act[0] == 0:\n id_new = obj.create(cr, act[2])\n cr.execute('update '+obj_src._table+' set '+field+'=%s where id=%s', (id_new, id))\n elif act[0] == 1:\n obj.write(cr, [act[1]], act[2], context=context)\n elif act[0] == 2:\n cr.execute('delete from '+self._table+' where id=%s', (act[1],))\n elif act[0] == 3 or act[0] == 5:\n cr.execute('update '+obj_src._table+' set '+field+'=null where id=%s', (id,))\n elif act[0] == 4:\n cr.execute('update '+obj_src._table+' set '+field+'=%s where id=%s', (act[1], id))\n else:\n if values:\n cr.execute('update '+obj_src._table+' set '+field+'=%s where id=%s', (values, id))\n else:\n cr.execute('update '+obj_src._table+' set '+field+'=null where id=%s', (id,))\n\n def search(self, cr, obj, args, name, value, offset=0, limit=None, uid=None, context=None):\n return obj.pool[self._obj].search(cr, uid, args+self._domain+[('name', 'like', value)], offset, limit, context=context)\n\n @classmethod\n def _as_display_name(cls, field, cr, uid, obj, value, context=None):\n return value[1] if isinstance(value, tuple) else tools.ustr(value) \n\n\nclass one2many(_column):\n _classic_read = False\n _classic_write = False\n _prefetch = False\n _type = 'one2many'\n\n # one2many columns are not copied by default\n copy = False\n\n def __init__(self, obj, fields_id, string='unknown', limit=None, auto_join=False, **args):\n _column.__init__(self, string=string, **args)\n self._obj = obj\n self._fields_id = fields_id\n self._limit = limit\n self._auto_join = auto_join\n #one2many can't be used as condition for defaults\n assert(self.change_default != True)\n\n def to_field_args(self):\n args = super(one2many, self).to_field_args()\n args['comodel_name'] = self._obj\n args['inverse_name'] = self._fields_id\n args['auto_join'] = self._auto_join\n args['limit'] = self._limit\n return args\n\n def get(self, cr, obj, ids, name, user=None, offset=0, context=None, values=None):\n if self._context:\n context = dict(context or {})\n context.update(self._context)\n\n comodel = obj.pool[self._obj].browse(cr, user, [], context)\n inverse = self._fields_id\n domain = self._domain(obj) if callable(self._domain) else self._domain\n domain = domain + [(inverse, 'in', ids)]\n\n records = comodel.search(domain, limit=self._limit)\n record_ids = map(int, records)\n\n res = dict((id, []) for id in ids)\n if record_ids:\n cr.execute('SELECT id, %(inverse)s \\\n FROM %(rel)s \\\n WHERE id in %%s ' % {\n 'inverse': inverse,\n 'rel': comodel._table,\n }, (tuple(record_ids),))\n record_value_id = dict(cr.fetchall())\n # match the result per id, preserving the order\n for record in records:\n key = record_value_id[record.id]\n res[key].append(record.id)\n\n return res\n\n def set(self, cr, obj, id, field, values, user=None, context=None):\n result = []\n context = dict(context or {})\n context.update(self._context)\n context['recompute'] = False # recomputation is done by outer create/write\n if not values:\n return\n obj = obj.pool[self._obj]\n _table = obj._table\n for act in values:\n if act[0] == 0:\n act[2][self._fields_id] = id\n id_new = obj.create(cr, user, act[2], context=context)\n result += obj._store_get_values(cr, user, [id_new], act[2].keys(), context)\n elif act[0] == 1:\n obj.write(cr, user, [act[1]], act[2], context=context)\n elif act[0] == 2:\n obj.unlink(cr, user, [act[1]], context=context)\n elif act[0] == 3:\n reverse_rel = obj._all_columns.get(self._fields_id)\n assert reverse_rel, 'Trying to unlink the content of a o2m but the pointed model does not have a m2o'\n # if the model has on delete cascade, just delete the row\n if reverse_rel.column.ondelete == \"cascade\":\n obj.unlink(cr, user, [act[1]], context=context)\n else:\n cr.execute('update '+_table+' set '+self._fields_id+'=null where id=%s', (act[1],))\n elif act[0] == 4:\n # table of the field (parent_model in case of inherit)\n field_model = self._fields_id in obj.pool[self._obj]._columns and self._obj or obj.pool[self._obj]._all_columns[self._fields_id].parent_model\n field_table = obj.pool[field_model]._table\n cr.execute(\"select 1 from {0} where id=%s and {1}=%s\".format(field_table, self._fields_id), (act[1], id))\n if not cr.fetchone():\n # Must use write() to recompute parent_store structure if needed and check access rules\n obj.write(cr, user, [act[1]], {self._fields_id:id}, context=context or {})\n elif act[0] == 5:\n reverse_rel = obj._all_columns.get(self._fields_id)\n assert reverse_rel, 'Trying to unlink the content of a o2m but the pointed model does not have a m2o'\n # if the o2m has a static domain we must respect it when unlinking\n domain = self._domain(obj) if callable(self._domain) else self._domain\n extra_domain = domain or []\n ids_to_unlink = obj.search(cr, user, [(self._fields_id,'=',id)] + extra_domain, context=context)\n # If the model has cascade deletion, we delete the rows because it is the intended behavior,\n # otherwise we only nullify the reverse foreign key column.\n if reverse_rel.column.ondelete == \"cascade\":\n obj.unlink(cr, user, ids_to_unlink, context=context)\n else:\n obj.write(cr, user, ids_to_unlink, {self._fields_id: False}, context=context)\n elif act[0] == 6:\n # Must use write() to recompute parent_store structure if needed\n obj.write(cr, user, act[2], {self._fields_id:id}, context=context or {})\n ids2 = act[2] or [0]\n cr.execute('select id from '+_table+' where '+self._fields_id+'=%s and id <> ALL (%s)', (id,ids2))\n ids3 = map(lambda x:x[0], cr.fetchall())\n obj.write(cr, user, ids3, {self._fields_id:False}, context=context or {})\n return result\n\n def search(self, cr, obj, args, name, value, offset=0, limit=None, uid=None, operator='like', context=None):\n domain = self._domain(obj) if callable(self._domain) else self._domain\n return obj.pool[self._obj].name_search(cr, uid, value, domain, operator, context=context,limit=limit)\n\n @classmethod\n def _as_display_name(cls, field, cr, uid, obj, value, context=None):\n raise NotImplementedError('One2Many columns should not be used as record name (_rec_name)') \n\n#\n# Values: (0, 0, { fields }) create\n# (1, ID, { fields }) update (write fields to ID)\n# (2, ID) remove (calls unlink on ID, that will also delete the relationship because of the ondelete)\n# (3, ID) unlink (delete the relationship between the two objects but does not delete ID)\n# (4, ID) link (add a relationship)\n# (5, ID) unlink all\n# (6, ?, ids) set a list of links\n#\nclass many2many(_column):\n \"\"\"Encapsulates the logic of a many-to-many bidirectional relationship, handling the\n low-level details of the intermediary relationship table transparently.\n A many-to-many relationship is always symmetrical, and can be declared and accessed\n from either endpoint model.\n If ``rel`` (relationship table name), ``id1`` (source foreign key column name)\n or id2 (destination foreign key column name) are not specified, the system will\n provide default values. This will by default only allow one single symmetrical\n many-to-many relationship between the source and destination model.\n For multiple many-to-many relationship between the same models and for\n relationships where source and destination models are the same, ``rel``, ``id1``\n and ``id2`` should be specified explicitly.\n\n :param str obj: destination model\n :param str rel: optional name of the intermediary relationship table. If not specified,\n a canonical name will be derived based on the alphabetically-ordered\n model names of the source and destination (in the form: ``amodel_bmodel_rel``).\n Automatic naming is not possible when the source and destination are\n the same, for obvious ambiguity reasons.\n :param str id1: optional name for the column holding the foreign key to the current\n model in the relationship table. If not specified, a canonical name\n will be derived based on the model name (in the form: `src_model_id`).\n :param str id2: optional name for the column holding the foreign key to the destination\n model in the relationship table. If not specified, a canonical name\n will be derived based on the model name (in the form: `dest_model_id`)\n :param str string: field label\n \"\"\"\n _classic_read = False\n _classic_write = False\n _prefetch = False\n _type = 'many2many'\n\n def __init__(self, obj, rel=None, id1=None, id2=None, string='unknown', limit=None, **args):\n \"\"\"\n \"\"\"\n _column.__init__(self, string=string, **args)\n self._obj = obj\n if rel and '.' in rel:\n raise Exception(_('The second argument of the many2many field %s must be a SQL table !'\\\n 'You used %s, which is not a valid SQL table name.')% (string,rel))\n self._rel = rel\n self._id1 = id1\n self._id2 = id2\n self._limit = limit\n\n def to_field_args(self):\n args = super(many2many, self).to_field_args()\n args['comodel_name'] = self._obj\n args['relation'] = self._rel\n args['column1'] = self._id1\n args['column2'] = self._id2\n args['limit'] = self._limit\n return args\n\n def _sql_names(self, source_model):\n \"\"\"Return the SQL names defining the structure of the m2m relationship table\n\n :return: (m2m_table, local_col, dest_col) where m2m_table is the table name,\n local_col is the name of the column holding the current model's FK, and\n dest_col is the name of the column holding the destination model's FK, and\n \"\"\"\n tbl, col1, col2 = self._rel, self._id1, self._id2\n if not all((tbl, col1, col2)):\n # the default table name is based on the stable alphabetical order of tables\n dest_model = source_model.pool[self._obj]\n tables = tuple(sorted([source_model._table, dest_model._table]))\n if not tbl:\n assert tables[0] != tables[1], 'Implicit/Canonical naming of m2m relationship table '\\\n 'is not possible when source and destination models are '\\\n 'the same'\n tbl = '%s_%s_rel' % tables\n if not col1:\n col1 = '%s_id' % source_model._table\n if not col2:\n col2 = '%s_id' % dest_model._table\n return tbl, col1, col2\n\n def _get_query_and_where_params(self, cr, model, ids, values, where_params):\n \"\"\" Extracted from ``get`` to facilitate fine-tuning of the generated\n query. \"\"\"\n query = 'SELECT %(rel)s.%(id2)s, %(rel)s.%(id1)s \\\n FROM %(rel)s, %(from_c)s \\\n WHERE %(rel)s.%(id1)s IN %%s \\\n AND %(rel)s.%(id2)s = %(tbl)s.id \\\n %(where_c)s \\\n %(order_by)s \\\n %(limit)s \\\n OFFSET %(offset)d' \\\n % values\n return query, where_params\n\n def get(self, cr, model, ids, name, user=None, offset=0, context=None, values=None):\n if not context:\n context = {}\n if not values:\n values = {}\n res = {}\n if not ids:\n return res\n for id in ids:\n res[id] = []\n if offset:\n _logger.warning(\n \"Specifying offset at a many2many.get() is deprecated and may\"\n \" produce unpredictable results.\")\n obj = model.pool[self._obj]\n rel, id1, id2 = self._sql_names(model)\n\n # static domains are lists, and are evaluated both here and on client-side, while string\n # domains supposed by dynamic and evaluated on client-side only (thus ignored here)\n # FIXME: make this distinction explicit in API!\n domain = isinstance(self._domain, list) and self._domain or []\n\n wquery = obj._where_calc(cr, user, domain, context=context)\n obj._apply_ir_rules(cr, user, wquery, 'read', context=context)\n from_c, where_c, where_params = wquery.get_sql()\n if where_c:\n where_c = ' AND ' + where_c\n\n order_by = ' ORDER BY \"%s\".%s' %(obj._table, obj._order.split(',')[0])\n\n limit_str = ''\n if self._limit is not None:\n limit_str = ' LIMIT %d' % self._limit\n\n query, where_params = self._get_query_and_where_params(cr, model, ids, {'rel': rel,\n 'from_c': from_c,\n 'tbl': obj._table,\n 'id1': id1,\n 'id2': id2,\n 'where_c': where_c,\n 'limit': limit_str,\n 'order_by': order_by,\n 'offset': offset,\n }, where_params)\n\n cr.execute(query, [tuple(ids),] + where_params)\n for r in cr.fetchall():\n res[r[1]].append(r[0])\n return res\n\n def set(self, cr, model, id, name, values, user=None, context=None):\n if not context:\n context = {}\n if not values:\n return\n rel, id1, id2 = self._sql_names(model)\n obj = model.pool[self._obj]\n for act in values:\n if not (isinstance(act, list) or isinstance(act, tuple)) or not act:\n continue\n if act[0] == 0:\n idnew = obj.create(cr, user, act[2], context=context)\n cr.execute('insert into '+rel+' ('+id1+','+id2+') values (%s,%s)', (id, idnew))\n elif act[0] == 1:\n obj.write(cr, user, [act[1]], act[2], context=context)\n elif act[0] == 2:\n obj.unlink(cr, user, [act[1]], context=context)\n elif act[0] == 3:\n cr.execute('delete from '+rel+' where ' + id1 + '=%s and '+ id2 + '=%s', (id, act[1]))\n elif act[0] == 4:\n # following queries are in the same transaction - so should be relatively safe\n cr.execute('SELECT 1 FROM '+rel+' WHERE '+id1+' = %s and '+id2+' = %s', (id, act[1]))\n if not cr.fetchone():\n cr.execute('insert into '+rel+' ('+id1+','+id2+') values (%s,%s)', (id, act[1]))\n elif act[0] == 5:\n cr.execute('delete from '+rel+' where ' + id1 + ' = %s', (id,))\n elif act[0] == 6:\n\n d1, d2,tables = obj.pool.get('ir.rule').domain_get(cr, user, obj._name, context=context)\n if d1:\n d1 = ' and ' + ' and '.join(d1)\n else:\n d1 = ''\n cr.execute('delete from '+rel+' where '+id1+'=%s AND '+id2+' IN (SELECT '+rel+'.'+id2+' FROM '+rel+', '+','.join(tables)+' WHERE '+rel+'.'+id1+'=%s AND '+rel+'.'+id2+' = '+obj._table+'.id '+ d1 +')', [id, id]+d2)\n\n for act_nbr in act[2]:\n cr.execute('insert into '+rel+' ('+id1+','+id2+') values (%s, %s)', (id, act_nbr))\n\n #\n # TODO: use a name_search\n #\n def search(self, cr, obj, args, name, value, offset=0, limit=None, uid=None, operator='like', context=None):\n return obj.pool[self._obj].search(cr, uid, args+self._domain+[('name', operator, value)], offset, limit, context=context)\n\n @classmethod\n def _as_display_name(cls, field, cr, uid, obj, value, context=None):\n raise NotImplementedError('Many2Many columns should not be used as record name (_rec_name)') \n\n\ndef get_nice_size(value):\n size = 0\n if isinstance(value, (int,long)):\n size = value\n elif value: # this is supposed to be a string\n size = len(value)\n return tools.human_size(size)\n\n# See http://www.w3.org/TR/2000/REC-xml-20001006#NT-Char\n# and http://bugs.python.org/issue10066\ninvalid_xml_low_bytes = re.compile(r'[\\x00-\\x08\\x0b-\\x0c\\x0e-\\x1f]')\n\ndef sanitize_binary_value(value):\n # binary fields should be 7-bit ASCII base64-encoded data,\n # but we do additional sanity checks to make sure the values\n # are not something else that won't pass via XML-RPC\n if isinstance(value, (xmlrpclib.Binary, tuple, list, dict)):\n # these builtin types are meant to pass untouched\n return value\n\n # Handle invalid bytes values that will cause problems\n # for XML-RPC. See for more info:\n # - http://bugs.python.org/issue10066\n # - http://www.w3.org/TR/2000/REC-xml-20001006#NT-Char\n\n # Coercing to unicode would normally allow it to properly pass via\n # XML-RPC, transparently encoded as UTF-8 by xmlrpclib.\n # (this works for _any_ byte values, thanks to the fallback\n # to latin-1 passthrough encoding when decoding to unicode)\n value = tools.ustr(value)\n\n # Due to Python bug #10066 this could still yield invalid XML\n # bytes, specifically in the low byte range, that will crash\n # the decoding side: [\\x00-\\x08\\x0b-\\x0c\\x0e-\\x1f]\n # So check for low bytes values, and if any, perform\n # base64 encoding - not very smart or useful, but this is\n # our last resort to avoid crashing the request.\n if invalid_xml_low_bytes.search(value):\n # b64-encode after restoring the pure bytes with latin-1\n # passthrough encoding\n value = base64.b64encode(value.encode('latin-1'))", "answers": [" return value"], "length": 4412, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "bbda2fae-9cbc-400c-8985-6e3ed575b29f", "reasoning": "In the sanitize_binary_value function, after converting the input to a unicode string and handling low‑byte characters by base64‑encoding them, the function should output the processed value. The next logical line is to return the (possibly encoded) value to the caller.", "reasoning_model_answer": "return value", "assistant_with_reasoning": "\nIn the sanitize_binary_value function, after converting the input to a unicode string and handling low‑byte characters by base64‑encoding them, the function should output the processed value. The next logical line is to return the (possibly encoded) value to the caller.\n\nreturn value", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 2.364, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 42136, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "return value", "score": 0.86, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "//\n// JsonDeserializer.cs\n//\n// Author:\n// Marek Habersack \n//\n// (C) 2008 Novell, Inc. http://novell.com/\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n// \n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n// \n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n// Code is based on JSON_checker (http://www.json.org/JSON_checker/) and JSON_parser\n// (http://fara.cs.uni-potsdam.de/~jsg/json_parser/) C sources. License for the original code\n// follows:\n\n#region Original License\n/*\nCopyright (c) 2005 JSON.org\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nThe Software shall be used for Good, not Evil.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n*/\n#endregion\n\nnamespace Nancy.Json\n{\n using System;\n using System.Collections;\n using System.Collections.Generic;\n using System.Globalization;\n using System.IO;\n using System.Text;\n\n\tinternal sealed class JsonDeserializer\n\t{\n\t\t/* Universal error constant */\n\t\tconst int __ = -1;\n\t\tconst int UNIVERSAL_ERROR = __;\n\t\t\n\t\t/*\n\t\t Characters are mapped into these 31 character classes. This allows for\n\t\t a significant reduction in the size of the state transition table.\n\t\t*/\n\t\tconst int C_SPACE = 0x00; /* space */\n\t\tconst int C_WHITE = 0x01; /* other whitespace */\n\t\tconst int C_LCURB = 0x02; /* { */\n\t\tconst int C_RCURB = 0x03; /* } */\n\t\tconst int C_LSQRB = 0x04; /* [ */\n\t\tconst int C_RSQRB = 0x05; /* ] */\n\t\tconst int C_COLON = 0x06; /* : */\n\t\tconst int C_COMMA = 0x07; /* , */\n\t\tconst int C_QUOTE = 0x08; /* \" */\n\t\tconst int C_BACKS = 0x09; /* \\ */\n\t\tconst int C_SLASH = 0x0A; /* / */\n\t\tconst int C_PLUS = 0x0B; /* + */\n\t\tconst int C_MINUS = 0x0C; /* - */\n\t\tconst int C_POINT = 0x0D; /* . */\n\t\tconst int C_ZERO = 0x0E; /* 0 */\n\t\tconst int C_DIGIT = 0x0F; /* 123456789 */\n\t\tconst int C_LOW_A = 0x10; /* a */\n\t\tconst int C_LOW_B = 0x11; /* b */\n\t\tconst int C_LOW_C = 0x12; /* c */\n\t\tconst int C_LOW_D = 0x13; /* d */\n\t\tconst int C_LOW_E = 0x14; /* e */\n\t\tconst int C_LOW_F = 0x15; /* f */\n\t\tconst int C_LOW_L = 0x16; /* l */\n\t\tconst int C_LOW_N = 0x17; /* n */\n\t\tconst int C_LOW_R = 0x18; /* r */\n\t\tconst int C_LOW_S = 0x19; /* s */\n\t\tconst int C_LOW_T = 0x1A; /* t */\n\t\tconst int C_LOW_U = 0x1B; /* u */\n\t\tconst int C_ABCDF = 0x1C; /* ABCDF */\n\t\tconst int C_E = 0x1D; /* E */\n\t\tconst int C_ETC = 0x1E; /* everything else */\n\t\tconst int C_STAR = 0x1F; /* * */\n\t\tconst int C_I = 0x20; /* I */\n\t\tconst int C_LOW_I = 0x21; /* i */\n\t\tconst int C_LOW_Y = 0x22; /* y */\n\t\tconst int C_N = 0x23; /* N */\n\t\t\n\t\t/* The state codes. */\n\t\tconst int GO = 0x00; /* start */\n\t\tconst int OK = 0x01; /* ok */\n\t\tconst int OB = 0x02; /* object */\n\t\tconst int KE = 0x03; /* key */\n\t\tconst int CO = 0x04; /* colon */\n\t\tconst int VA = 0x05; /* value */\n\t\tconst int AR = 0x06; /* array */\n\t\tconst int ST = 0x07; /* string */\n\t\tconst int ES = 0x08; /* escape */\n\t\tconst int U1 = 0x09; /* u1 */\n\t\tconst int U2 = 0x0A; /* u2 */\n\t\tconst int U3 = 0x0B; /* u3 */\n\t\tconst int U4 = 0x0C; /* u4 */\n\t\tconst int MI = 0x0D; /* minus */\n\t\tconst int ZE = 0x0E; /* zero */\n\t\tconst int IN = 0x0F; /* integer */\n\t\tconst int FR = 0x10; /* fraction */\n\t\tconst int E1 = 0x11; /* e */\n\t\tconst int E2 = 0x12; /* ex */\n\t\tconst int E3 = 0x13; /* exp */\n\t\tconst int T1 = 0x14; /* tr */\n\t\tconst int T2 = 0x15; /* tru */\n\t\tconst int T3 = 0x16; /* true */\n\t\tconst int F1 = 0x17; /* fa */\n\t\tconst int F2 = 0x18; /* fal */\n\t\tconst int F3 = 0x19; /* fals */\n\t\tconst int F4 = 0x1A; /* false */\n\t\tconst int N1 = 0x1B; /* nu */\n\t\tconst int N2 = 0x1C; /* nul */\n\t\tconst int N3 = 0x1D; /* null */\n\t\tconst int FX = 0x1E; /* *.* *eE* */\n\t\tconst int IV = 0x1F; /* invalid input */\n\t\tconst int UK = 0x20; /* unquoted key name */\n\t\tconst int UI = 0x21; /* ignore during unquoted key name construction */\n\t\tconst int I1 = 0x22; /* In */\n\t\tconst int I2 = 0x23; /* Inf */\n\t\tconst int I3 = 0x24; /* Infi */\n\t\tconst int I4 = 0x25; /* Infin */\n\t\tconst int I5 = 0x26; /* Infini */\n\t\tconst int I6 = 0x27; /* Infinit */\n\t\tconst int I7 = 0x28; /* Infinity */\n\t\tconst int V1 = 0x29; /* Na */\n\t\tconst int V2 = 0x2A; /* NaN */\n\t\t\n\t\t/* Actions */\n\t\tconst int FA = -10; /* false */\n\t\tconst int TR = -11; /* false */\n\t\tconst int NU = -12; /* null */\n\t\tconst int DE = -13; /* double detected by exponent e E */\n\t\tconst int DF = -14; /* double detected by fraction . */\n\t\tconst int SB = -15; /* string begin */\n\t\tconst int MX = -16; /* integer detected by minus */\n\t\tconst int ZX = -17; /* integer detected by zero */\n\t\tconst int IX = -18; /* integer detected by 1-9 */\n\t\tconst int EX = -19; /* next char is escaped */\n\t\tconst int UC = -20; /* Unicode character read */\n\t\tconst int SE = -4; /* string end */\n\t\tconst int AB = -5; /* array begin */\n\t\tconst int AE = -7; /* array end */\n\t\tconst int OS = -6; /* object start */\n\t\tconst int OE = -8; /* object end */\n\t\tconst int EO = -9; /* empty object */\n\t\tconst int CM = -3; /* comma */\n\t\tconst int CA = -2; /* colon action */\n\t\tconst int PX = -21; /* integer detected by plus */\n\t\tconst int KB = -22; /* unquoted key name begin */\n\t\tconst int UE = -23; /* unquoted key name end */\n\t\tconst int IF = -25; /* Infinity */\n\t\tconst int NN = -26; /* NaN */\n\t\t\n\t\t\n\t\tenum JsonMode {\n\t\t\tNONE,\n\t\t\tARRAY,\n\t\t\tDONE,\n\t\t\tKEY,\n\t\t\tOBJECT\n\t\t};\n\n\t\tenum JsonType {\n\t\t\tNONE = 0,\n\t\t\tARRAY_BEGIN,\n\t\t\tARRAY_END,\n\t\t\tOBJECT_BEGIN,\n\t\t\tOBJECT_END,\n\t\t\tINTEGER,\n\t\t\tFLOAT,\n\t\t\tNULL,\n\t\t\tTRUE,\n\t\t\tFALSE,\n\t\t\tSTRING,\n\t\t\tKEY,\n\t\t\tMAX\n\t\t};\n\t\t\n\t\t/*\n\t\t This array maps the 128 ASCII characters into character classes.\n\t\t The remaining Unicode characters should be mapped to C_ETC.\n\t\t Non-whitespace control characters are errors.\n\t\t*/\n\t\tstatic readonly int[] ascii_class = {\n\t\t\t__, __, __, __, __, __, __, __,\n\t\t\t__, C_WHITE, C_WHITE, __, __, C_WHITE, __, __,\n\t\t\t__, __, __, __, __, __, __, __,\n\t\t\t__, __, __, __, __, __, __, __,\n\n\t\t\tC_SPACE, C_ETC, C_QUOTE, C_ETC, C_ETC, C_ETC, C_ETC, C_QUOTE,\n\t\t\tC_ETC, C_ETC, C_STAR, C_PLUS, C_COMMA, C_MINUS, C_POINT, C_SLASH,\n\t\t\tC_ZERO, C_DIGIT, C_DIGIT, C_DIGIT, C_DIGIT, C_DIGIT, C_DIGIT, C_DIGIT,\n\t\t\tC_DIGIT, C_DIGIT, C_COLON, C_ETC, C_ETC, C_ETC, C_ETC, C_ETC,\n\n\t\t\tC_ETC, C_ABCDF, C_ABCDF, C_ABCDF, C_ABCDF, C_E, C_ABCDF, C_ETC,\n\t\t\tC_ETC, C_I, C_ETC, C_ETC, C_ETC, C_ETC, C_N, C_ETC,\n\t\t\tC_ETC, C_ETC, C_ETC, C_ETC, C_ETC, C_ETC, C_ETC, C_ETC,\n\t\t\tC_ETC, C_ETC, C_ETC, C_LSQRB, C_BACKS, C_RSQRB, C_ETC, C_ETC,\n\n\t\t\tC_ETC, C_LOW_A, C_LOW_B, C_LOW_C, C_LOW_D, C_LOW_E, C_LOW_F, C_ETC,\n\t\t\tC_ETC, C_LOW_I, C_ETC, C_ETC, C_LOW_L, C_ETC, C_LOW_N, C_ETC,\n\t\t\tC_ETC, C_ETC, C_LOW_R, C_LOW_S, C_LOW_T, C_LOW_U, C_ETC, C_ETC,\n\t\t\tC_ETC, C_LOW_Y, C_ETC, C_LCURB, C_ETC, C_RCURB, C_ETC, C_ETC\n\t\t};\n\n\t\tstatic readonly int[,] state_transition_table = {\n\t\t/*\n\t\t The state transition table takes the current state and the current symbol,\n\t\t and returns either a new state or an action. An action is represented as a\n\t\t negative number. A JSON text is accepted if at the end of the text the\n\t\t state is OK and if the mode is MODE_DONE.\n\n\t\t white ' 1-9 ABCDF etc\n\t\t space | { } [ ] : , \" \\ / + - . 0 | a b c d e f l n r s t u | E | * I i y N */\n\t\t\t/*start GO*/ {GO,GO,OS,__,AB,__,__,__,SB,__,__,PX,MX,__,ZX,IX,__,__,__,__,__,FA,__,__,__,__,TR,__,__,__,__,__,I1,__,__,V1},\n\t\t\t/*ok OK*/ {OK,OK,__,OE,__,AE,__,CM,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__},\n\t\t\t/*object OB*/ {OB,OB,__,EO,__,__,__,__,SB,__,__,__,KB,__,KB,KB,KB,KB,KB,KB,KB,KB,KB,KB,KB,KB,KB,KB,KB,KB,KB,__,KB,KB,KB,KB},\n\t\t\t/*key KE*/ {KE,KE,__,__,__,__,__,__,SB,__,__,__,KB,__,KB,KB,KB,KB,KB,KB,KB,KB,KB,KB,KB,KB,KB,KB,KB,KB,KB,__,KB,KB,KB,KB},\n\t\t\t/*colon CO*/ {CO,CO,__,__,__,__,CA,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__},\n\t\t\t/*value VA*/ {VA,VA,OS,__,AB,__,__,__,SB,__,__,PX,MX,__,ZX,IX,__,__,__,__,__,FA,__,NU,__,__,TR,__,__,__,__,__,I1,__,__,V1},\n\t\t\t/*array AR*/ {AR,AR,OS,__,AB,AE,__,__,SB,__,__,PX,MX,__,ZX,IX,__,__,__,__,__,FA,__,NU,__,__,TR,__,__,__,__,__,I1,__,__,V1},\n\t\t\t/*string ST*/ {ST,__,ST,ST,ST,ST,ST,ST,SE,EX,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST},\n\t\t\t/*escape ES*/ {__,__,__,__,__,__,__,__,ST,ST,ST,__,__,__,__,__,__,ST,__,__,__,ST,__,ST,ST,__,ST,U1,__,__,__,__,__,__,__,__},\n\t\t\t/*u1 U1*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,U2,U2,U2,U2,U2,U2,U2,U2,__,__,__,__,__,__,U2,U2,__,__,__,__,__,__},\n\t\t\t/*u2 U2*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,U3,U3,U3,U3,U3,U3,U3,U3,__,__,__,__,__,__,U3,U3,__,__,__,__,__,__},\n\t\t\t/*u3 U3*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,U4,U4,U4,U4,U4,U4,U4,U4,__,__,__,__,__,__,U4,U4,__,__,__,__,__,__},\n\t\t\t/*u4 U4*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,UC,UC,UC,UC,UC,UC,UC,UC,__,__,__,__,__,__,UC,UC,__,__,__,__,__,__},\n\t\t\t/*minus MI*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,ZE,IN,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,I1,__,__,__},\n\t\t\t/*zero ZE*/ {OK,OK,__,OE,__,AE,__,CM,__,__,__,__,__,DF,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__},\n\t\t\t/*int IN*/ {OK,OK,__,OE,__,AE,__,CM,__,__,__,__,__,DF,IN,IN,__,__,__,__,DE,__,__,__,__,__,__,__,__,DE,__,__,__,__,__,__},\n\t\t\t/*frac FR*/ {OK,OK,__,OE,__,AE,__,CM,__,__,__,__,__,__,FR,FR,__,__,__,__,E1,__,__,__,__,__,__,__,__,E1,__,__,__,__,__,__},\n\t\t\t/*e E1*/ {__,__,__,__,__,__,__,__,__,__,__,E2,E2,__,E3,E3,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__},\n\t\t\t/*ex E2*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,E3,E3,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__},\n\t\t\t/*exp E3*/ {OK,OK,__,OE,__,AE,__,CM,__,__,__,__,__,__,E3,E3,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__},\n\t\t\t/*tr T1*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,T2,__,__,__,__,__,__,__,__,__,__,__},\n\t\t\t/*tru T2*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,T3,__,__,__,__,__,__,__,__},\n\t\t\t/*true T3*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,OK,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__},\n\t\t\t/*fa F1*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,F2,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__},\n\t\t\t/*fal F2*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,F3,__,__,__,__,__,__,__,__,__,__,__,__,__},\n\t\t\t/*fals F3*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,F4,__,__,__,__,__,__,__,__,__,__},\n\t\t\t/*false F4*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,OK,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__},\n\t\t\t/*nu N1*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,N2,__,__,__,__,__,__,__,__},\n\t\t\t/*nul N2*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,N3,__,__,__,__,__,__,__,__,__,__,__,__,__},\n\t\t\t/*null N3*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,OK,__,__,__,__,__,__,__,__,__,__,__,__,__},\n\t\t\t/*_. FX*/ {OK,OK,__,OE,__,AE,__,CM,__,__,__,__,__,__,FR,FR,__,__,__,__,E1,__,__,__,__,__,__,__,__,E1,__,__,__,__,__,__},\n\t\t\t/*inval. IV*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__},\n\t\t\t/*unq.key UK*/ {UI,UI,__,__,__,__,UE,__,__,__,__,UK,UK,UK,UK,UK,UK,UK,UK,UK,UK,UK,UK,UK,UK,UK,UK,UK,UK,UK,UK,__,UK,UK,UK,UK},\n\t\t\t/*unq.ign. UI*/ {UI,UI,__,__,__,__,UE,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__},\n\t\t\t/*i1 I1*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,I2,__,__,__,__,__,__,__,__,__,__,__,__},\n\t\t\t/*i2 I2*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,I3,__,__,__,__,__,__,__,__,__,__,__,__,__,__},\n\t\t\t/*i3 I3*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,I4,__,__},\n\t\t\t/*i4 I4*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,I5,__,__,__,__,__,__,__,__,__,__,__,__},\n\t\t\t/*i5 I5*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,I6,__,__},\n\t\t\t/*i6 I6*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,I7,__,__,__,__,__,__,__,__,__},\n\t\t\t/*i7 I7*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,IF,__},\n\t\t\t/*v1 V1*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,V2,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__},\n\t\t\t/*v2 V2*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,NN},\n\t\t};\n\n\t\tJavaScriptSerializer serializer;\n\t\tJavaScriptTypeResolver typeResolver;\n\t\tint maxJsonLength;\n\t\tint currentPosition;\n\t\tint recursionLimit;\n\t\tint recursionDepth;\n\t\t\n\t\tStack modes;\n\t\tStack returnValue;\n\t\tJsonType jsonType;\n\t\t\n\t\tbool escaped;\n\t\tint state;\n\t\tStack currentKey;\n\t\tStringBuilder buffer;\n\t\tchar quoteChar;\n\t\t\n\t\tpublic JsonDeserializer (JavaScriptSerializer serializer)\n\t\t{\n\t\t\tthis.serializer = serializer;\n\t\t\tthis.maxJsonLength = serializer.MaxJsonLength;\n\t\t\tthis.recursionLimit = serializer.RecursionLimit;\n\t\t\tthis.typeResolver = serializer.TypeResolver;\n\t\t\tthis.modes = new Stack ();\n\t\t\tthis.currentKey = new Stack ();\n\t\t\tthis.returnValue = new Stack ();\n\t\t\tthis.state = GO;\n\t\t\tthis.currentPosition = 0;\n\t\t\tthis.recursionDepth = 0;\n\t\t}\n\n\t\tpublic object Deserialize (string input)\n\t\t{\n\t\t\tif (input == null)\n\t\t\t\tthrow new ArgumentNullException (\"input\");\n\n\t\t\treturn Deserialize (new StringReader (input));\n\t\t}\n\t\t\n\t\tpublic object Deserialize (TextReader input)\n\t\t{\n\t\t\tif (input == null)\n\t\t\t\tthrow new ArgumentNullException (\"input\");\n\t\t\t\n\t\t\tint value;\n\t\t\tbuffer = new StringBuilder ();\n\t\t\t\n\t\t\twhile (true) {\n\t\t\t\tvalue = input.Read ();\n\t\t\t\tif (value < 0)\n\t\t\t\t\tbreak;\n\n\t\t\t\tcurrentPosition++;\n\t\t\t\tif (currentPosition > maxJsonLength)\n\t\t\t\t\tthrow new ArgumentException (\"Maximum JSON input length has been exceeded.\");\n\n\t\t\t\tif (!ProcessCharacter ((char) value))\n\t\t\t\t\tthrow new InvalidOperationException (\"JSON syntax error.\");\n\t\t\t}\n\n\t\t\tobject topObject = PeekObject ();\n\t\t\tif (buffer.Length > 0) {\n\t\t\t\tobject result;\n\n\t\t\t\tif (ParseBuffer (out result)) {\n\t\t\t\t\tif (topObject != null)\n\t\t\t\t\t\tStoreValue (result);\n\t\t\t\t\telse\n\t\t\t\t\t\tPushObject (result);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (returnValue.Count > 1)\n\t\t\t\tthrow new InvalidOperationException (\"JSON syntax error.\");\n\n\t\t\tobject ret = PopObject ();\n\t\t\treturn ret;\n\t\t}\n\n#if DEBUG\n\t\tvoid DumpObject (string indent, object obj)\n\t\t{\n\t\t\tif (obj is Dictionary ) {\n\t\t\t\tConsole.WriteLine (indent + \"{\");\n\t\t\t\tforeach (KeyValuePair kvp in (Dictionary )obj) {\n\t\t\t\t\tConsole.WriteLine (indent + \"\\t\\\"{0}\\\": \", kvp.Key);\n\t\t\t\t\tDumpObject (indent + \"\\t\\t\", kvp.Value);\n\t\t\t\t}\n\t\t\t\tConsole.WriteLine (indent + \"}\");\n\t\t\t} else if (obj is object[]) {\n\t\t\t\tConsole.WriteLine (indent + \"[\");\n\t\t\t\tforeach (object o in (object[])obj)\n\t\t\t\t\tDumpObject (indent + \"\\t\", o);\n\t\t\t\tConsole.WriteLine (indent + \"]\");\n\t\t\t} else if (obj != null)\n\t\t\t\tConsole.WriteLine (indent + obj.ToString ());\n\t\t\telse\n\t\t\t\tConsole.WriteLine (\"null\");\n\t\t}\n#endif\n\t\t\n\t\tvoid DecodeUnicodeChar ()\n\t\t{\n\t\t\tint len = buffer.Length;\n\t\t\tif (len < 6)\n\t\t\t\tthrow new ArgumentException (\"Invalid escaped unicode character specification (\" + currentPosition + \")\");\n\n\t\t\tint code = Int32.Parse (buffer.ToString ().Substring (len - 4), NumberStyles.HexNumber);\n\t\t\tbuffer.Length = len - 6;\n\t\t\tbuffer.Append ((char)code);\n\t\t}\n\n\t\tstring GetModeMessage (JsonMode expectedMode)\n\t\t{\n\t\t\tswitch (expectedMode) {\n\t\t\t\tcase JsonMode.ARRAY:\n\t\t\t\t\treturn \"Invalid array passed in, ',' or ']' expected (\" + currentPosition + \")\";\n\n\t\t\t\tcase JsonMode.KEY:\n\t\t\t\t\treturn \"Invalid object passed in, key name or ':' expected (\" + currentPosition + \")\";\n\n\t\t\t\tcase JsonMode.OBJECT:\n\t\t\t\t\treturn \"Invalid object passed in, key value expected (\" + currentPosition + \")\";\n\t\t\t\t\t\n\t\t\t\tdefault:\n\t\t\t\t\treturn \"Invalid JSON string\";\n\t\t\t}\n\t\t}\n\t\t\n\t\tvoid PopMode (JsonMode expectedMode)\n\t\t{\n\t\t\tJsonMode mode = PeekMode ();\n\t\t\tif (mode != expectedMode)\n\t\t\t\tthrow new ArgumentException (GetModeMessage (mode));\n\n\t\t\tmodes.Pop ();\n\t\t}\n\n\t\tvoid PushMode (JsonMode newMode)\n\t\t{\n\t\t\tmodes.Push (newMode);\n\t\t}\n\n\t\tJsonMode PeekMode ()\n\t\t{\n\t\t\tif (modes.Count == 0)\n\t\t\t\treturn JsonMode.NONE;\n\n\t\t\treturn modes.Peek ();\n\t\t}\n\n\t\tvoid PushObject (object o)\n\t\t{\n\t\t\treturnValue.Push (o);\n\t\t}\n\n\t\tobject PopObject (bool notIfLast)\n\t\t{\n\t\t\tint count = returnValue.Count;\n\t\t\tif (count == 0)\n\t\t\t\treturn null;\n\n\t\t\tif (notIfLast && count == 1)\n\t\t\t\treturn null;\n\t\t\t\n\t\t\treturn returnValue.Pop ();\n\t\t}\n\n\t\tobject PopObject ()\n\t\t{\n\t\t\treturn PopObject (false);\n\t\t}\n\t\t\n\t\tobject PeekObject ()\n\t\t{\n\t\t\tif (returnValue.Count == 0)\n\t\t\t\treturn null;\n\n\t\t\treturn returnValue.Peek ();\n\t\t}\n\t\t\n\t\tvoid RemoveLastCharFromBuffer ()\n\t\t{\n\t\t\tint len = buffer.Length;\n\t\t\tif (len == 0)\n\t\t\t\treturn;\n\t\t\tbuffer.Length = len - 1;\n\t\t}\n\n\t\tbool ParseBuffer (out object result)\n\t\t{\n\t\t\tresult = null;\n\t\t\t\n\t\t\tif (jsonType == JsonType.NONE) {\n\t\t\t\tbuffer.Length = 0;\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tstring s = buffer.ToString ();\n\t\t\tbool converted = true;\n\t\t\tint intValue;\n\t\t\tlong longValue;\n\t\t\tdecimal decimalValue;\n\t\t\tdouble doubleValue;\n\t\t\t\n\t\t\tswitch (jsonType) {\n\t\t\t\tcase JsonType.INTEGER:\n\t\t\t\t\t/* MS AJAX.NET JSON parser promotes big integers to double */\n\t\t\t\t\t\n\t\t\t\t\tif (Int32.TryParse (s, out intValue))\n\t\t\t\t\t\tresult = intValue;\n\t\t\t\t\telse if (Int64.TryParse (s, out longValue))\n\t\t\t\t\t\tresult = longValue;\n\t\t\t\t\telse if (Decimal.TryParse (s, out decimalValue))\n\t\t\t\t\t\tresult = decimalValue;\n\t\t\t\t\telse if (Double.TryParse (s, out doubleValue))\n\t\t\t\t\t\tresult = doubleValue;\n\t\t\t\t\telse\n\t\t\t\t\t\tconverted = false;\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase JsonType.FLOAT:\n\t\t\t\t\tif (Decimal.TryParse(s,NumberStyles.Any, Json.DefaultNumberFormatInfo, out decimalValue))\n\t\t\t\t\t\tresult = decimalValue;\n\t\t\t\t\telse if (Double.TryParse (s,NumberStyles.Any, Json.DefaultNumberFormatInfo, out doubleValue))\n\t\t\t\t\t\tresult = doubleValue;\n\t\t\t\t\telse\n\t\t\t\t\t\tconverted = false;\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase JsonType.TRUE:\n\t\t\t\t\tif (String.Compare (s, \"true\", StringComparison.Ordinal) == 0)\n\t\t\t\t\t\tresult = true;\n\t\t\t\t\telse\n\t\t\t\t\t\tconverted = false;\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase JsonType.FALSE:\n\t\t\t\t\tif (String.Compare (s, \"false\", StringComparison.Ordinal) == 0)\n\t\t\t\t\t\tresult = false;\n\t\t\t\t\telse\n\t\t\t\t\t\tconverted = false;\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase JsonType.NULL:\n\t\t\t\t\tif (String.Compare (s, \"null\", StringComparison.Ordinal) != 0)\n\t\t\t\t\t\tconverted = false;\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase JsonType.STRING:\n\t\t\t\t\tif (s.StartsWith (\"/Date(\", StringComparison.Ordinal) && s.EndsWith (\")/\", StringComparison.Ordinal)) {\n\t\t\t\t\t\tlong javaScriptTicks = Convert.ToInt64 (s.Substring (6, s.Length - 8));\n\t\t\t\t\t\tresult = new DateTime ((javaScriptTicks * 10000) + JsonSerializer.InitialJavaScriptDateTicks, DateTimeKind.Utc);\n\t\t\t\t\t} else\n\t\t\t\t\t\tresult = s;\n\t\t\t\t\tbreak;\n\n\t\t\t\tdefault:\n\t\t\t\t\tthrow new InvalidOperationException (String.Format (\"Internal error: unexpected JsonType ({0})\", jsonType));\n\t\t\t\t\t\n\t\t\t}\n\n\t\t\tif (!converted)\n\t\t\t\tthrow new ArgumentException (\"Invalid JSON primitive: \" + s);\n\n\t\t\tbuffer.Length = 0;\n\t\t\treturn true;\n\t\t}\n\t\t\n\t\tbool ProcessCharacter (char ch)\n\t\t{\n\t\t\tint next_class, next_state;\n\n\t\t\tif (ch >= 128)\n\t\t\t\tnext_class = C_ETC;\n\t\t\telse {\n\t\t\t\tnext_class = ascii_class [ch];\n\t\t\t\tif (next_class <= UNIVERSAL_ERROR)\n\t\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tif (escaped) {\n\t\t\t\tescaped = false;\n\t\t\t\tRemoveLastCharFromBuffer ();\n\t\t\t\t\n\t\t\t\tswitch (ch) {\n\t\t\t\t\tcase 'b':\n\t\t\t\t\t\tbuffer.Append ('\\b');\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 'f':\n\t\t\t\t\t\tbuffer.Append ('\\f');\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 'n':\n\t\t\t\t\t\tbuffer.Append ('\\n');\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 'r':\n\t\t\t\t\t\tbuffer.Append ('\\r');\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 't':\n\t\t\t\t\t\tbuffer.Append ('\\t');\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase '\"':\n\t\t\t\t\tcase '\\\\':\n\t\t\t\t\tcase '/':\n\t\t\t\t\t\tbuffer.Append (ch);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 'u':\n\t\t\t\t\t\tbuffer.Append (\"\\\\u\");\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tdefault:\n\t\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t} else if (jsonType != JsonType.NONE || !(next_class == C_SPACE || next_class == C_WHITE))\n\t\t\t\tbuffer.Append (ch);\n\n\t\t\tnext_state = state_transition_table [state, next_class];\n\t\t\tif (next_state >= 0) {\n\t\t\t\tstate = next_state;\n\t\t\t\treturn true;\n\t\t\t}\n\n\t\t\tobject result;\n\t\t\t/* An action to perform */\n\t\t\tswitch (next_state) {\n\t\t\t\tcase UC: /* Unicode character */\n\t\t\t\t\tDecodeUnicodeChar ();\n\t\t\t\t\tstate = ST;\n\t\t\t\t\tbreak;\n\t\t\t\t\t\n\t\t\t\tcase EX: /* Escaped character */\n\t\t\t\t\tescaped = true;\n\t\t\t\t\tstate = ES;\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase MX: /* integer detected by minus */\n\t\t\t\t\tjsonType = JsonType.INTEGER;\n\t\t\t\t\tstate = MI;\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase PX: /* integer detected by plus */\n\t\t\t\t\tjsonType = JsonType.INTEGER;\n\t\t\t\t\tstate = MI;\n\t\t\t\t\tbreak;\n\t\t\t\t\t\n\t\t\t\tcase ZX: /* integer detected by zero */\n\t\t\t\t\tjsonType = JsonType.INTEGER;\n\t\t\t\t\tstate = ZE;\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase IX: /* integer detected by 1-9 */\n\t\t\t\t\tjsonType = JsonType.INTEGER;\n\t\t\t\t\tstate = IN;\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase DE: /* floating point number detected by exponent*/\n\t\t\t\t\tjsonType = JsonType.FLOAT;\n\t\t\t\t\tstate = E1;\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase DF: /* floating point number detected by fraction */\n\t\t\t\t\tjsonType = JsonType.FLOAT;\n\t\t\t\t\tstate = FX;\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase SB: /* string begin \" or ' */\n\t\t\t\t\tbuffer.Length = 0;\n\t\t\t\t\tquoteChar = ch;\n\t\t\t\t\tjsonType = JsonType.STRING;\n\t\t\t\t\tstate = ST;\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase KB: /* unquoted key name begin */\n\t\t\t\t\tjsonType = JsonType.STRING;\n\t\t\t\t\tstate = UK;\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase UE: /* unquoted key name end ':' */\n\t\t\t\t\tRemoveLastCharFromBuffer ();\n\t\t\t\t\tif (ParseBuffer (out result))\n\t\t\t\t\t\tStoreKey (result);\n\t\t\t\t\tjsonType = JsonType.NONE;\n\t\t\t\t\t\n\t\t\t\t\tPopMode (JsonMode.KEY);\n\t\t\t\t\tPushMode (JsonMode.OBJECT);\n\t\t\t\t\tstate = VA;\n\t\t\t\t\tbuffer.Length = 0;\n\t\t\t\t\tbreak;\n\t\t\t\t\t\n\t\t\t\tcase NU: /* n */\n\t\t\t\t\tjsonType = JsonType.NULL;\n\t\t\t\t\tstate = N1;\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase FA: /* f */\n\t\t\t\t\tjsonType = JsonType.FALSE;\n\t\t\t\t\tstate = F1;\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase TR: /* t */\n\t\t\t\t\tjsonType = JsonType.TRUE;\n\t\t\t\t\tstate = T1;\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase EO: /* empty } */\n\t\t\t\t\tresult = PopObject (true);\n\t\t\t\t\tif (result != null)\n\t\t\t\t\t\tStoreValue (result);\n\t\t\t\t\tPopMode (JsonMode.KEY);\n\t\t\t\t\tstate = OK;\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase OE: /* } */\n\t\t\t\t\tRemoveLastCharFromBuffer ();\n\n\t\t\t\t\tif (ParseBuffer (out result))\n\t\t\t\t\t\tStoreValue (result);\n\n\t\t\t\t\tresult = PopObject (true);\n\t\t\t\t\tif (result != null)\n\t\t\t\t\t\tStoreValue (result);\n\n\t\t\t\t\tPopMode (JsonMode.OBJECT);\n\n\t\t\t\t\tjsonType = JsonType.NONE;\n\t\t\t\t\tstate = OK;\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase AE: /* ] */\n\t\t\t\t\tRemoveLastCharFromBuffer ();\n\t\t\t\t\tif (ParseBuffer (out result))\n\t\t\t\t\t\tStoreValue (result);\n\t\t\t\t\tPopMode (JsonMode.ARRAY);\n\t\t\t\t\tresult = PopObject (true);\n\t\t\t\t\tif (result != null)\n\t\t\t\t\t\tStoreValue (result);\n\t\t\t\t\t\n\t\t\t\t\tjsonType = JsonType.NONE;\n\t\t\t\t\tstate = OK;\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase OS: /* { */\n\t\t\t\t\tRemoveLastCharFromBuffer ();\n\t\t\t\t\tCreateObject ();", "answers": ["\t\t\t\t\tPushMode (JsonMode.KEY);"], "length": 2952, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "1ff31bd5-40c6-4ad8-ac9d-90a0d1ac2922", "reasoning": "In the ProcessCharacter switch, the OS case handles a '{' opening a new JSON object. After removing the brace and creating the object, the parser must set the parsing mode to expect a key inside the new object. The code therefore pushes the KEY mode onto the mode stack. The next line after CreateObject(); is the push of JsonMode.KEY.", "reasoning_model_answer": "PushMode (JsonMode.KEY);", "assistant_with_reasoning": "\nIn the ProcessCharacter switch, the OS case handles a '{' opening a new JSON object. After removing the brace and creating the object, the parser must set the parsing mode to expect a key inside the new object. The code therefore pushes the KEY mode onto the mode stack. The next line after CreateObject(); is the push of JsonMode.KEY.\n\nPushMode (JsonMode.KEY);", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 8.118, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 25269, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "PushMode (JsonMode.KEY);", "score": 0.91, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\nusing Xunit;\n\nnamespace System.Linq.Expressions.Tests\n{\n public static class ArrayArrayLengthTests\n {\n #region Boolean tests\n\n [Theory]\n [ClassData(typeof(CompilationTypes))]\n public static void CheckBoolArrayArrayLengthTest(bool useInterpreter)\n {\n CheckBoolArrayArrayLengthExpression(GenerateBoolArrayArray(0), useInterpreter);\n CheckBoolArrayArrayLengthExpression(GenerateBoolArrayArray(1), useInterpreter);\n CheckBoolArrayArrayLengthExpression(GenerateBoolArrayArray(5), useInterpreter);\n }\n\n [Theory]\n [ClassData(typeof(CompilationTypes))]\n public static void CheckExceptionBoolArrayArrayLengthTest(bool useInterpreter)\n {\n CheckExceptionBoolArrayArrayLength(null, useInterpreter);\n }\n\n #endregion\n\n #region Byte tests\n\n [Theory]\n [ClassData(typeof(CompilationTypes))]\n public static void CheckByteArrayArrayLengthTest(bool useInterpreter)\n {\n CheckByteArrayArrayLengthExpression(GenerateByteArrayArray(0), useInterpreter);\n CheckByteArrayArrayLengthExpression(GenerateByteArrayArray(1), useInterpreter);\n CheckByteArrayArrayLengthExpression(GenerateByteArrayArray(5), useInterpreter);\n }\n\n [Theory]\n [ClassData(typeof(CompilationTypes))]\n public static void CheckExceptionByteArrayArrayLengthTest(bool useInterpreter)\n {\n CheckExceptionByteArrayArrayLength(null, useInterpreter);\n }\n\n #endregion\n\n #region Custom tests\n\n [Theory]\n [ClassData(typeof(CompilationTypes))]\n public static void CheckCustomArrayArrayLengthTest(bool useInterpreter)\n {\n CheckCustomArrayArrayLengthExpression(GenerateCustomArrayArray(0), useInterpreter);\n CheckCustomArrayArrayLengthExpression(GenerateCustomArrayArray(1), useInterpreter);\n CheckCustomArrayArrayLengthExpression(GenerateCustomArrayArray(5), useInterpreter);\n }\n\n [Theory]\n [ClassData(typeof(CompilationTypes))]\n public static void CheckExceptionCustomArrayArrayLengthTest(bool useInterpreter)\n {\n CheckExceptionCustomArrayArrayLength(null, useInterpreter);\n }\n\n #endregion\n\n #region Char tests\n\n [Theory]\n [ClassData(typeof(CompilationTypes))]\n public static void CheckCharArrayArrayLengthTest(bool useInterpreter)\n {\n CheckCharArrayArrayLengthExpression(GenerateCharArrayArray(0), useInterpreter);\n CheckCharArrayArrayLengthExpression(GenerateCharArrayArray(1), useInterpreter);\n CheckCharArrayArrayLengthExpression(GenerateCharArrayArray(5), useInterpreter);\n }\n\n [Theory]\n [ClassData(typeof(CompilationTypes))]\n public static void CheckExceptionCharArrayArrayLengthTest(bool useInterpreter)\n {\n CheckExceptionCharArrayArrayLength(null, useInterpreter);\n }\n\n #endregion\n\n #region Custom2 tests\n\n [Theory]\n [ClassData(typeof(CompilationTypes))]\n public static void CheckCustom2ArrayArrayLengthTest(bool useInterpreter)\n {\n CheckCustom2ArrayArrayLengthExpression(GenerateCustom2ArrayArray(0), useInterpreter);\n CheckCustom2ArrayArrayLengthExpression(GenerateCustom2ArrayArray(1), useInterpreter);\n CheckCustom2ArrayArrayLengthExpression(GenerateCustom2ArrayArray(5), useInterpreter);\n }\n\n [Theory]\n [ClassData(typeof(CompilationTypes))]\n public static void CheckExceptionCustom2ArrayArrayLengthTest(bool useInterpreter)\n {\n CheckExceptionCustom2ArrayArrayLength(null, useInterpreter);\n }\n\n #endregion\n\n #region Decimal tests\n\n [Theory]\n [ClassData(typeof(CompilationTypes))]\n public static void CheckDecimalArrayArrayLengthTest(bool useInterpreter)\n {\n CheckDecimalArrayArrayLengthExpression(GenerateDecimalArrayArray(0), useInterpreter);\n CheckDecimalArrayArrayLengthExpression(GenerateDecimalArrayArray(1), useInterpreter);\n CheckDecimalArrayArrayLengthExpression(GenerateDecimalArrayArray(5), useInterpreter);\n }\n\n [Theory]\n [ClassData(typeof(CompilationTypes))]\n public static void CheckExceptionDecimalArrayArrayLengthTest(bool useInterpreter)\n {\n CheckExceptionDecimalArrayArrayLength(null, useInterpreter);\n }\n\n #endregion\n\n #region Delegate tests\n\n [Theory]\n [ClassData(typeof(CompilationTypes))]\n public static void CheckDelegateArrayArrayLengthTest(bool useInterpreter)\n {\n CheckDelegateArrayArrayLengthExpression(GenerateDelegateArrayArray(0), useInterpreter);\n CheckDelegateArrayArrayLengthExpression(GenerateDelegateArrayArray(1), useInterpreter);\n CheckDelegateArrayArrayLengthExpression(GenerateDelegateArrayArray(5), useInterpreter);\n }\n\n [Theory]\n [ClassData(typeof(CompilationTypes))]\n public static void CheckExceptionDelegateArrayArrayLengthTest(bool useInterpreter)\n {\n CheckExceptionDelegateArrayArrayLength(null, useInterpreter);\n }\n\n #endregion\n\n #region Double tests\n\n [Theory]\n [ClassData(typeof(CompilationTypes))]\n public static void CheckDoubleArrayArrayLengthTest(bool useInterpreter)\n {\n CheckDoubleArrayArrayLengthExpression(GenerateDoubleArrayArray(0), useInterpreter);\n CheckDoubleArrayArrayLengthExpression(GenerateDoubleArrayArray(1), useInterpreter);\n CheckDoubleArrayArrayLengthExpression(GenerateDoubleArrayArray(5), useInterpreter);\n }\n\n [Theory]\n [ClassData(typeof(CompilationTypes))]\n public static void CheckExceptionDoubleArrayArrayLengthTest(bool useInterpreter)\n {\n CheckExceptionDoubleArrayArrayLength(null, useInterpreter);\n }\n\n #endregion\n\n #region Enum tests\n\n [Theory]\n [ClassData(typeof(CompilationTypes))]\n public static void CheckEnumArrayArrayLengthTest(bool useInterpreter)\n {\n CheckEnumArrayArrayLengthExpression(GenerateEnumArrayArray(0), useInterpreter);\n CheckEnumArrayArrayLengthExpression(GenerateEnumArrayArray(1), useInterpreter);\n CheckEnumArrayArrayLengthExpression(GenerateEnumArrayArray(5), useInterpreter);\n }\n\n [Theory]\n [ClassData(typeof(CompilationTypes))]\n public static void CheckExceptionEnumArrayArrayLengthTest(bool useInterpreter)\n {\n CheckExceptionEnumArrayArrayLength(null, useInterpreter);\n }\n\n #endregion\n\n #region EnumLong tests\n\n [Theory]\n [ClassData(typeof(CompilationTypes))]\n public static void CheckEnumLongArrayArrayLengthTest(bool useInterpreter)\n {\n CheckEnumLongArrayArrayLengthExpression(GenerateEnumLongArrayArray(0), useInterpreter);\n CheckEnumLongArrayArrayLengthExpression(GenerateEnumLongArrayArray(1), useInterpreter);\n CheckEnumLongArrayArrayLengthExpression(GenerateEnumLongArrayArray(5), useInterpreter);\n }\n\n [Theory]\n [ClassData(typeof(CompilationTypes))]\n public static void CheckExceptionEnumLongArrayArrayLengthTest(bool useInterpreter)\n {\n CheckExceptionEnumLongArrayArrayLength(null, useInterpreter);\n }\n\n #endregion\n\n #region Float tests\n\n [Theory]\n [ClassData(typeof(CompilationTypes))]\n public static void CheckFloatArrayArrayLengthTest(bool useInterpreter)\n {\n CheckFloatArrayArrayLengthExpression(GenerateFloatArrayArray(0), useInterpreter);\n CheckFloatArrayArrayLengthExpression(GenerateFloatArrayArray(1), useInterpreter);\n CheckFloatArrayArrayLengthExpression(GenerateFloatArrayArray(5), useInterpreter);\n }\n\n [Theory]\n [ClassData(typeof(CompilationTypes))]\n public static void CheckExceptionFloatArrayArrayLengthTest(bool useInterpreter)\n {\n CheckExceptionFloatArrayArrayLength(null, useInterpreter);\n }\n\n #endregion\n\n #region Func tests\n\n [Theory]\n [ClassData(typeof(CompilationTypes))]\n public static void CheckFuncArrayArrayLengthTest(bool useInterpreter)\n {\n CheckFuncArrayArrayLengthExpression(GenerateFuncArrayArray(0), useInterpreter);\n CheckFuncArrayArrayLengthExpression(GenerateFuncArrayArray(1), useInterpreter);\n CheckFuncArrayArrayLengthExpression(GenerateFuncArrayArray(5), useInterpreter);\n }\n\n [Theory]\n [ClassData(typeof(CompilationTypes))]\n public static void CheckExceptionFuncArrayArrayLengthTest(bool useInterpreter)\n {\n CheckExceptionFuncArrayArrayLength(null, useInterpreter);\n }\n\n #endregion\n\n #region Interface tests\n\n [Theory]\n [ClassData(typeof(CompilationTypes))]\n public static void CheckInterfaceArrayArrayLengthTest(bool useInterpreter)\n {\n CheckInterfaceArrayArrayLengthExpression(GenerateInterfaceArrayArray(0), useInterpreter);\n CheckInterfaceArrayArrayLengthExpression(GenerateInterfaceArrayArray(1), useInterpreter);\n CheckInterfaceArrayArrayLengthExpression(GenerateInterfaceArrayArray(5), useInterpreter);\n }\n\n [Theory]\n [ClassData(typeof(CompilationTypes))]\n public static void CheckExceptionInterfaceArrayArrayLengthTest(bool useInterpreter)\n {\n CheckExceptionInterfaceArrayArrayLength(null, useInterpreter);\n }\n\n #endregion\n\n #region IEquatableCustom tests\n\n [Theory]\n [ClassData(typeof(CompilationTypes))]\n public static void CheckIEquatableCustomArrayArrayLengthTest(bool useInterpreter)\n {\n CheckIEquatableCustomArrayArrayLengthExpression(GenerateIEquatableCustomArrayArray(0), useInterpreter);\n CheckIEquatableCustomArrayArrayLengthExpression(GenerateIEquatableCustomArrayArray(1), useInterpreter);\n CheckIEquatableCustomArrayArrayLengthExpression(GenerateIEquatableCustomArrayArray(5), useInterpreter);\n }\n\n [Theory]\n [ClassData(typeof(CompilationTypes))]\n public static void CheckExceptionIEquatableCustomArrayArrayLengthTest(bool useInterpreter)\n {\n CheckExceptionIEquatableCustomArrayArrayLength(null, useInterpreter);\n }\n\n #endregion\n\n #region IEquatableCustom2 tests\n\n [Theory]\n [ClassData(typeof(CompilationTypes))]\n public static void CheckIEquatableCustom2ArrayArrayLengthTest(bool useInterpreter)\n {\n CheckIEquatableCustom2ArrayArrayLengthExpression(GenerateIEquatableCustom2ArrayArray(0), useInterpreter);\n CheckIEquatableCustom2ArrayArrayLengthExpression(GenerateIEquatableCustom2ArrayArray(1), useInterpreter);\n CheckIEquatableCustom2ArrayArrayLengthExpression(GenerateIEquatableCustom2ArrayArray(5), useInterpreter);\n }\n\n [Theory]\n [ClassData(typeof(CompilationTypes))]\n public static void CheckExceptionIEquatableCustom2ArrayArrayLengthTest(bool useInterpreter)\n {\n CheckExceptionIEquatableCustom2ArrayArrayLength(null, useInterpreter);\n }\n\n #endregion\n\n #region Int tests\n\n [Theory]\n [ClassData(typeof(CompilationTypes))]\n public static void CheckIntArrayArrayLengthTest(bool useInterpreter)\n {\n CheckIntArrayArrayLengthExpression(GenerateIntArrayArray(0), useInterpreter);\n CheckIntArrayArrayLengthExpression(GenerateIntArrayArray(1), useInterpreter);\n CheckIntArrayArrayLengthExpression(GenerateIntArrayArray(5), useInterpreter);\n }\n\n [Theory]\n [ClassData(typeof(CompilationTypes))]\n public static void CheckExceptionIntArrayArrayLengthTest(bool useInterpreter)\n {\n CheckExceptionIntArrayArrayLength(null, useInterpreter);\n }\n\n #endregion\n\n #region Long tests\n\n [Theory]\n [ClassData(typeof(CompilationTypes))]\n public static void CheckLongArrayArrayLengthTest(bool useInterpreter)\n {\n CheckLongArrayArrayLengthExpression(GenerateLongArrayArray(0), useInterpreter);\n CheckLongArrayArrayLengthExpression(GenerateLongArrayArray(1), useInterpreter);\n CheckLongArrayArrayLengthExpression(GenerateLongArrayArray(5), useInterpreter);\n }\n\n [Theory]\n [ClassData(typeof(CompilationTypes))]\n public static void CheckExceptionLongArrayArrayLengthTest(bool useInterpreter)\n {\n CheckExceptionLongArrayArrayLength(null, useInterpreter);\n }\n\n #endregion\n\n #region Object tests\n\n [Theory]\n [ClassData(typeof(CompilationTypes))]\n public static void CheckObjectArrayArrayLengthTest(bool useInterpreter)\n {\n CheckObjectArrayArrayLengthExpression(GenerateObjectArrayArray(0), useInterpreter);\n CheckObjectArrayArrayLengthExpression(GenerateObjectArrayArray(1), useInterpreter);\n CheckObjectArrayArrayLengthExpression(GenerateObjectArrayArray(5), useInterpreter);\n }\n\n [Theory]\n [ClassData(typeof(CompilationTypes))]\n public static void CheckExceptionObjectArrayArrayLengthTest(bool useInterpreter)\n {\n CheckExceptionObjectArrayArrayLength(null, useInterpreter);\n }\n\n #endregion\n\n #region Struct tests\n\n [Theory]\n [ClassData(typeof(CompilationTypes))]\n public static void CheckStructArrayArrayLengthTest(bool useInterpreter)\n {\n CheckStructArrayArrayLengthExpression(GenerateStructArrayArray(0), useInterpreter);\n CheckStructArrayArrayLengthExpression(GenerateStructArrayArray(1), useInterpreter);\n CheckStructArrayArrayLengthExpression(GenerateStructArrayArray(5), useInterpreter);\n }\n\n [Theory]\n [ClassData(typeof(CompilationTypes))]\n public static void CheckExceptionStructArrayArrayLengthTest(bool useInterpreter)\n {\n CheckExceptionStructArrayArrayLength(null, useInterpreter);\n }\n\n #endregion\n\n #region SByte tests\n\n [Theory]\n [ClassData(typeof(CompilationTypes))]\n public static void CheckSByteArrayArrayLengthTest(bool useInterpreter)\n {\n CheckSByteArrayArrayLengthExpression(GenerateSByteArrayArray(0), useInterpreter);\n CheckSByteArrayArrayLengthExpression(GenerateSByteArrayArray(1), useInterpreter);\n CheckSByteArrayArrayLengthExpression(GenerateSByteArrayArray(5), useInterpreter);\n }\n\n [Theory]\n [ClassData(typeof(CompilationTypes))]\n public static void CheckExceptionSByteArrayArrayLengthTest(bool useInterpreter)\n {\n CheckExceptionSByteArrayArrayLength(null, useInterpreter);\n }\n\n #endregion\n\n #region StructWithString tests\n\n [Theory]\n [ClassData(typeof(CompilationTypes))]\n public static void CheckStructWithStringArrayArrayLengthTest(bool useInterpreter)\n {\n CheckStructWithStringArrayArrayLengthExpression(GenerateStructWithStringArrayArray(0), useInterpreter);\n CheckStructWithStringArrayArrayLengthExpression(GenerateStructWithStringArrayArray(1), useInterpreter);\n CheckStructWithStringArrayArrayLengthExpression(GenerateStructWithStringArrayArray(5), useInterpreter);\n }\n\n [Theory]\n [ClassData(typeof(CompilationTypes))]\n public static void CheckExceptionStructWithStringArrayArrayLengthTest(bool useInterpreter)\n {\n CheckExceptionStructWithStringArrayArrayLength(null, useInterpreter);\n }\n\n #endregion\n\n #region StructWithStringAndValue tests\n\n [Theory]\n [ClassData(typeof(CompilationTypes))]\n public static void CheckStructWithStringAndValueArrayArrayLengthTest(bool useInterpreter)\n {\n CheckStructWithStringAndValueArrayArrayLengthExpression(GenerateStructWithStringAndValueArrayArray(0), useInterpreter);\n CheckStructWithStringAndValueArrayArrayLengthExpression(GenerateStructWithStringAndValueArrayArray(1), useInterpreter);\n CheckStructWithStringAndValueArrayArrayLengthExpression(GenerateStructWithStringAndValueArrayArray(5), useInterpreter);\n }\n\n [Theory]\n [ClassData(typeof(CompilationTypes))]\n public static void CheckExceptionStructWithStringAndValueArrayArrayLengthTest(bool useInterpreter)\n {\n CheckExceptionStructWithStringAndValueArrayArrayLength(null, useInterpreter);\n }\n\n #endregion\n\n #region Short tests\n\n [Theory]\n [ClassData(typeof(CompilationTypes))]\n public static void CheckShortArrayArrayLengthTest(bool useInterpreter)\n {\n CheckShortArrayArrayLengthExpression(GenerateShortArrayArray(0), useInterpreter);\n CheckShortArrayArrayLengthExpression(GenerateShortArrayArray(1), useInterpreter);\n CheckShortArrayArrayLengthExpression(GenerateShortArrayArray(5), useInterpreter);\n }\n\n [Theory]\n [ClassData(typeof(CompilationTypes))]\n public static void CheckExceptionShortArrayArrayLengthTest(bool useInterpreter)\n {\n CheckExceptionShortArrayArrayLength(null, useInterpreter);\n }\n\n #endregion\n\n #region StructWithTwoValues tests\n\n [Theory]\n [ClassData(typeof(CompilationTypes))]\n public static void CheckStructWithTwoValuesArrayArrayLengthTest(bool useInterpreter)\n {\n CheckStructWithTwoValuesArrayArrayLengthExpression(GenerateStructWithTwoValuesArrayArray(0), useInterpreter);\n CheckStructWithTwoValuesArrayArrayLengthExpression(GenerateStructWithTwoValuesArrayArray(1), useInterpreter);\n CheckStructWithTwoValuesArrayArrayLengthExpression(GenerateStructWithTwoValuesArrayArray(5), useInterpreter);\n }\n\n [Theory]\n [ClassData(typeof(CompilationTypes))]\n public static void CheckExceptionStructWithTwoValuesArrayArrayLengthTest(bool useInterpreter)\n {\n CheckExceptionStructWithTwoValuesArrayArrayLength(null, useInterpreter);\n }\n\n #endregion\n\n #region StructWithValue tests\n\n [Theory]\n [ClassData(typeof(CompilationTypes))]\n public static void CheckStructWithValueArrayArrayLengthTest(bool useInterpreter)\n {\n CheckStructWithValueArrayArrayLengthExpression(GenerateStructWithValueArrayArray(0), useInterpreter);\n CheckStructWithValueArrayArrayLengthExpression(GenerateStructWithValueArrayArray(1), useInterpreter);\n CheckStructWithValueArrayArrayLengthExpression(GenerateStructWithValueArrayArray(5), useInterpreter);\n }\n\n [Theory]\n [ClassData(typeof(CompilationTypes))]\n public static void CheckExceptionStructWithValueArrayArrayLengthTest(bool useInterpreter)\n {\n CheckExceptionStructWithValueArrayArrayLength(null, useInterpreter);\n }\n\n #endregion\n\n #region String tests\n\n [Theory]\n [ClassData(typeof(CompilationTypes))]\n public static void CheckStringArrayArrayLengthTest(bool useInterpreter)\n {\n CheckStringArrayArrayLengthExpression(GenerateStringArrayArray(0), useInterpreter);\n CheckStringArrayArrayLengthExpression(GenerateStringArrayArray(1), useInterpreter);\n CheckStringArrayArrayLengthExpression(GenerateStringArrayArray(5), useInterpreter);\n }\n\n [Theory]\n [ClassData(typeof(CompilationTypes))]\n public static void CheckExceptionStringArrayArrayLengthTest(bool useInterpreter)\n {\n CheckExceptionStringArrayArrayLength(null, useInterpreter);\n }\n\n #endregion\n\n #region UInt tests\n\n [Theory]\n [ClassData(typeof(CompilationTypes))]\n public static void CheckUIntArrayArrayLengthTest(bool useInterpreter)\n {\n CheckUIntArrayArrayLengthExpression(GenerateUIntArrayArray(0), useInterpreter);\n CheckUIntArrayArrayLengthExpression(GenerateUIntArrayArray(1), useInterpreter);\n CheckUIntArrayArrayLengthExpression(GenerateUIntArrayArray(5), useInterpreter);\n }\n\n [Theory]\n [ClassData(typeof(CompilationTypes))]\n public static void CheckExceptionUIntArrayArrayLengthTest(bool useInterpreter)\n {\n CheckExceptionUIntArrayArrayLength(null, useInterpreter);\n }\n\n #endregion\n\n #region ULong tests\n\n [Theory]\n [ClassData(typeof(CompilationTypes))]\n public static void CheckULongArrayArrayLengthTest(bool useInterpreter)\n {\n CheckULongArrayArrayLengthExpression(GenerateULongArrayArray(0), useInterpreter);\n CheckULongArrayArrayLengthExpression(GenerateULongArrayArray(1), useInterpreter);\n CheckULongArrayArrayLengthExpression(GenerateULongArrayArray(5), useInterpreter);\n }\n\n [Theory]\n [ClassData(typeof(CompilationTypes))]\n public static void CheckExceptionULongArrayArrayLengthTest(bool useInterpreter)\n {\n CheckExceptionULongArrayArrayLength(null, useInterpreter);\n }\n\n #endregion\n\n #region UShort tests\n\n [Theory]\n [ClassData(typeof(CompilationTypes))]\n public static void CheckUShortArrayArrayLengthTest(bool useInterpreter)\n {\n CheckUShortArrayArrayLengthExpression(GenerateUShortArrayArray(0), useInterpreter);\n CheckUShortArrayArrayLengthExpression(GenerateUShortArrayArray(1), useInterpreter);\n CheckUShortArrayArrayLengthExpression(GenerateUShortArrayArray(5), useInterpreter);\n }\n\n [Theory]\n [ClassData(typeof(CompilationTypes))]\n public static void CheckExceptionUShortArrayArrayLengthTest(bool useInterpreter)\n {\n CheckExceptionUShortArrayArrayLength(null, useInterpreter);\n }\n\n #endregion\n\n #region Generic tests\n\n [Theory]\n [ClassData(typeof(CompilationTypes))]\n public static void CheckGenericCustomArrayArrayLengthTest(bool useInterpreter)\n {\n CheckGenericArrayArrayLengthTestHelper(useInterpreter);\n }\n\n [Theory]\n [ClassData(typeof(CompilationTypes))]\n public static void CheckExceptionGenericCustomArrayArrayLengthTest(bool useInterpreter)\n {\n CheckExceptionGenericArrayArrayLengthTestHelper(useInterpreter);\n }\n\n [Theory]\n [ClassData(typeof(CompilationTypes))]\n public static void CheckGenericEnumArrayArrayLengthTest(bool useInterpreter)\n {\n CheckGenericArrayArrayLengthTestHelper(useInterpreter);\n }\n\n [Theory]\n [ClassData(typeof(CompilationTypes))]\n public static void CheckExceptionGenericEnumArrayArrayLengthTest(bool useInterpreter)\n {\n CheckExceptionGenericArrayArrayLengthTestHelper(useInterpreter);\n }\n\n [Theory]\n [ClassData(typeof(CompilationTypes))]\n public static void CheckGenericObjectArrayArrayLengthTest(bool useInterpreter)\n {\n CheckGenericArrayArrayLengthTestHelper(useInterpreter);\n }\n\n [Theory]\n [ClassData(typeof(CompilationTypes))]\n public static void CheckExceptionGenericObjectArrayArrayLengthTest(bool useInterpreter)\n {\n CheckExceptionGenericArrayArrayLengthTestHelper(useInterpreter);\n }\n\n [Theory]\n [ClassData(typeof(CompilationTypes))]\n public static void CheckGenericStructArrayArrayLengthTest(bool useInterpreter)\n {\n CheckGenericArrayArrayLengthTestHelper(useInterpreter);\n }\n\n [Theory]\n [ClassData(typeof(CompilationTypes))]\n public static void CheckExceptionGenericStructArrayArrayLengthTest(bool useInterpreter)\n {\n CheckExceptionGenericArrayArrayLengthTestHelper(useInterpreter);\n }\n\n [Theory]\n [ClassData(typeof(CompilationTypes))]\n public static void CheckGenericStructWithStringAndValueArrayArrayLengthTest(bool useInterpreter)\n {\n CheckGenericArrayArrayLengthTestHelper(useInterpreter);\n }\n\n [Theory]\n [ClassData(typeof(CompilationTypes))]\n public static void CheckExceptionGenericStructWithStringAndValueArrayArrayLengthTest(bool useInterpreter)\n {\n CheckExceptionGenericArrayArrayLengthTestHelper(useInterpreter);\n }\n\n [Theory]\n [ClassData(typeof(CompilationTypes))]\n public static void CheckGenericCustomWithClassRestrictionArrayArrayLengthTest(bool useInterpreter)\n {\n CheckGenericWithClassRestrictionArrayArrayLengthTestHelper(useInterpreter);\n }\n\n [Theory]\n [ClassData(typeof(CompilationTypes))]\n public static void CheckExceptionGenericCustomWithClassRestrictionArrayArrayLengthTest(bool useInterpreter)\n {\n CheckExceptionGenericWithClassRestrictionArrayArrayLengthTestHelper(useInterpreter);\n }\n\n [Theory]\n [ClassData(typeof(CompilationTypes))]\n public static void CheckGenericObjectWithClassRestrictionArrayArrayLengthTest(bool useInterpreter)\n {\n CheckGenericWithClassRestrictionArrayArrayLengthTestHelper(useInterpreter);\n }\n\n [Theory]\n [ClassData(typeof(CompilationTypes))]\n public static void CheckExceptionGenericObjectWithClassRestrictionArrayArrayLengthTest(bool useInterpreter)\n {\n CheckExceptionGenericWithClassRestrictionArrayArrayLengthTestHelper(useInterpreter);\n }\n\n [Theory]\n [ClassData(typeof(CompilationTypes))]\n public static void CheckGenericCustomWithSubClassRestrictionArrayArrayLengthTest(bool useInterpreter)\n {\n CheckGenericWithSubClassRestrictionArrayArrayLengthTestHelper(useInterpreter);\n }\n\n [Theory]\n [ClassData(typeof(CompilationTypes))]\n public static void CheckExceptionGenericCustomWithSubClassRestrictionArrayArrayLengthTest(bool useInterpreter)\n {\n CheckExceptionGenericWithSubClassRestrictionArrayArrayLengthTestHelper(useInterpreter);\n }\n\n [Theory]\n [ClassData(typeof(CompilationTypes))]\n public static void CheckGenericCustomWithClassAndNewRestrictionArrayArrayLengthTest(bool useInterpreter)\n {\n CheckGenericWithClassAndNewRestrictionArrayArrayLengthTestHelper(useInterpreter);\n }\n\n [Theory]\n [ClassData(typeof(CompilationTypes))]\n public static void CheckExceptionGenericCustomWithClassAndNewRestrictionArrayArrayLengthTest(bool useInterpreter)\n {\n CheckExceptionGenericWithClassAndNewRestrictionArrayArrayLengthTestHelper(useInterpreter);\n }\n\n [Theory]\n [ClassData(typeof(CompilationTypes))]\n public static void CheckGenericObjectWithClassAndNewRestrictionArrayArrayLengthTest(bool useInterpreter)\n {\n CheckGenericWithClassAndNewRestrictionArrayArrayLengthTestHelper(useInterpreter);\n }\n\n [Theory]\n [ClassData(typeof(CompilationTypes))]\n public static void CheckExceptionGenericObjectWithClassAndNewRestrictionArrayArrayLengthTest(bool useInterpreter)\n {\n CheckExceptionGenericWithClassAndNewRestrictionArrayArrayLengthTestHelper(useInterpreter);\n }\n\n [Theory]\n [ClassData(typeof(CompilationTypes))]\n public static void CheckGenericCustomWithSubClassAndNewRestrictionArrayArrayLengthTest(bool useInterpreter)\n {\n CheckGenericWithSubClassAndNewRestrictionArrayArrayLengthTestHelper(useInterpreter);\n }\n\n [Theory]\n [ClassData(typeof(CompilationTypes))]\n public static void CheckExceptionGenericCustomWithSubClassAndNewRestrictionArrayArrayLengthTest(bool useInterpreter)\n {\n CheckExceptionGenericWithSubClassAndNewRestrictionArrayArrayLengthTestHelper(useInterpreter);\n }\n\n [Theory]\n [ClassData(typeof(CompilationTypes))]\n public static void CheckGenericEnumWithStructRestrictionArrayArrayLengthTest(bool useInterpreter)\n {\n CheckGenericWithStructRestrictionArrayArrayLengthTestHelper(useInterpreter);\n }\n\n [Theory]\n [ClassData(typeof(CompilationTypes))]\n public static void CheckExceptionGenericEnumWithStructRestrictionArrayArrayLengthTest(bool useInterpreter)\n {\n CheckExceptionGenericWithStructRestrictionArrayArrayLengthTestHelper(useInterpreter);\n }\n\n [Theory]\n [ClassData(typeof(CompilationTypes))]\n public static void CheckGenericStructWithStructRestrictionArrayArrayLengthTest(bool useInterpreter)\n {\n CheckGenericWithStructRestrictionArrayArrayLengthTestHelper(useInterpreter);\n }\n\n [Theory]\n [ClassData(typeof(CompilationTypes))]\n public static void CheckExceptionGenericStructWithStructRestrictionArrayArrayLengthTest(bool useInterpreter)\n {\n CheckExceptionGenericWithStructRestrictionArrayArrayLengthTestHelper(useInterpreter);\n }\n\n [Theory]\n [ClassData(typeof(CompilationTypes))]\n public static void CheckGenericStructWithStringAndValueWithStructRestrictionArrayArrayLengthTest(bool useInterpreter)\n {\n CheckGenericWithStructRestrictionArrayArrayLengthTestHelper(useInterpreter);\n }\n\n [Theory]\n [ClassData(typeof(CompilationTypes))]\n public static void CheckExceptionGenericStructWithStringAndValueWithStructRestrictionArrayArrayLengthTest(bool useInterpreter)\n {\n CheckExceptionGenericWithStructRestrictionArrayArrayLengthTestHelper(useInterpreter);\n }\n\n #endregion\n\n #region Generic helpers\n\n private static void CheckGenericArrayArrayLengthTestHelper(bool useInterpreter)\n {\n CheckGenericArrayArrayLengthExpression(GenerateGenericArrayArray(0), useInterpreter);\n CheckGenericArrayArrayLengthExpression(GenerateGenericArrayArray(1), useInterpreter);\n CheckGenericArrayArrayLengthExpression(GenerateGenericArrayArray(5), useInterpreter);\n }\n\n private static void CheckExceptionGenericArrayArrayLengthTestHelper(bool useInterpreter)\n {\n CheckExceptionGenericArrayArrayLength(null, useInterpreter);\n }\n\n private static void CheckGenericWithClassRestrictionArrayArrayLengthTestHelper(bool useInterpreter) where Tc : class\n {\n CheckGenericWithClassRestrictionArrayArrayLengthExpression(GenerateGenericWithClassRestrictionArrayArray(0), useInterpreter);\n CheckGenericWithClassRestrictionArrayArrayLengthExpression(GenerateGenericWithClassRestrictionArrayArray(1), useInterpreter);\n CheckGenericWithClassRestrictionArrayArrayLengthExpression(GenerateGenericWithClassRestrictionArrayArray(5), useInterpreter);\n }\n\n private static void CheckExceptionGenericWithClassRestrictionArrayArrayLengthTestHelper(bool useInterpreter) where Tc : class\n {\n CheckExceptionGenericWithClassRestrictionArrayArrayLength(null, useInterpreter);\n }\n\n private static void CheckGenericWithSubClassRestrictionArrayArrayLengthTestHelper(bool useInterpreter) where TC : C\n {\n CheckGenericWithSubClassRestrictionArrayArrayLengthExpression(GenerateGenericWithSubClassRestrictionArrayArray(0), useInterpreter);\n CheckGenericWithSubClassRestrictionArrayArrayLengthExpression(GenerateGenericWithSubClassRestrictionArrayArray(1), useInterpreter);\n CheckGenericWithSubClassRestrictionArrayArrayLengthExpression(GenerateGenericWithSubClassRestrictionArrayArray(5), useInterpreter);\n }\n\n private static void CheckExceptionGenericWithSubClassRestrictionArrayArrayLengthTestHelper(bool useInterpreter) where TC : C\n {\n CheckExceptionGenericWithSubClassRestrictionArrayArrayLength(null, useInterpreter);\n }\n\n private static void CheckGenericWithClassAndNewRestrictionArrayArrayLengthTestHelper(bool useInterpreter) where Tcn : class, new()\n {\n CheckGenericWithClassAndNewRestrictionArrayArrayLengthExpression(GenerateGenericWithClassAndNewRestrictionArrayArray(0), useInterpreter);\n CheckGenericWithClassAndNewRestrictionArrayArrayLengthExpression(GenerateGenericWithClassAndNewRestrictionArrayArray(1), useInterpreter);\n CheckGenericWithClassAndNewRestrictionArrayArrayLengthExpression(GenerateGenericWithClassAndNewRestrictionArrayArray(5), useInterpreter);\n }\n\n private static void CheckExceptionGenericWithClassAndNewRestrictionArrayArrayLengthTestHelper(bool useInterpreter) where Tcn : class, new()\n {\n CheckExceptionGenericWithClassAndNewRestrictionArrayArrayLength(null, useInterpreter);\n }\n\n private static void CheckGenericWithSubClassAndNewRestrictionArrayArrayLengthTestHelper(bool useInterpreter) where TCn : C, new()\n {\n CheckGenericWithSubClassAndNewRestrictionArrayArrayLengthExpression(GenerateGenericWithSubClassAndNewRestrictionArrayArray(0), useInterpreter);\n CheckGenericWithSubClassAndNewRestrictionArrayArrayLengthExpression(GenerateGenericWithSubClassAndNewRestrictionArrayArray(1), useInterpreter);\n CheckGenericWithSubClassAndNewRestrictionArrayArrayLengthExpression(GenerateGenericWithSubClassAndNewRestrictionArrayArray(5), useInterpreter);\n }\n\n private static void CheckExceptionGenericWithSubClassAndNewRestrictionArrayArrayLengthTestHelper(bool useInterpreter) where TCn : C, new()\n {\n CheckExceptionGenericWithSubClassAndNewRestrictionArrayArrayLength(null, useInterpreter);\n }\n\n private static void CheckGenericWithStructRestrictionArrayArrayLengthTestHelper(bool useInterpreter) where Ts : struct\n {\n CheckGenericWithStructRestrictionArrayArrayLengthExpression(GenerateGenericWithStructRestrictionArrayArray(0), useInterpreter);\n CheckGenericWithStructRestrictionArrayArrayLengthExpression(GenerateGenericWithStructRestrictionArrayArray(1), useInterpreter);\n CheckGenericWithStructRestrictionArrayArrayLengthExpression(GenerateGenericWithStructRestrictionArrayArray(5), useInterpreter);\n }\n\n private static void CheckExceptionGenericWithStructRestrictionArrayArrayLengthTestHelper(bool useInterpreter) where Ts : struct\n {\n CheckExceptionGenericWithStructRestrictionArrayArrayLength(null, useInterpreter);\n }\n\n #endregion\n\n #region Generate array\n\n private static bool[][] GenerateBoolArrayArray(int size)\n {\n bool[][] array = new bool[][] { null, new bool[0], new bool[] { true, false }, new bool[100] };\n bool[][] result = new bool[size][];\n for (int i = 0; i < size; i++)\n {\n result[i] = array[i % array.Length];\n }\n\n return result;\n }\n\n private static byte[][] GenerateByteArrayArray(int size)\n {\n byte[][] array = new byte[][] { null, new byte[0], new byte[] { 0, 1, byte.MaxValue }, new byte[100] };\n byte[][] result = new byte[size][];\n for (int i = 0; i < size; i++)\n {\n result[i] = array[i % array.Length];\n }\n\n return result;\n }\n\n private static C[][] GenerateCustomArrayArray(int size)\n {\n C[][] array = new C[][] { null, new C[0], new C[] { null, new C(), new D(), new D(0), new D(5) }, new C[100] };\n C[][] result = new C[size][];\n for (int i = 0; i < size; i++)\n {\n result[i] = array[i % array.Length];\n }\n\n return result;\n }\n\n private static char[][] GenerateCharArrayArray(int size)\n {\n char[][] array = new char[][] { null, new char[0], new char[] { '\\0', '\\b', 'A', '\\uffff' }, new char[100] };\n char[][] result = new char[size][];\n for (int i = 0; i < size; i++)\n {\n result[i] = array[i % array.Length];\n }\n\n return result;\n }\n\n private static D[][] GenerateCustom2ArrayArray(int size)\n {\n D[][] array = new D[][] { null, new D[0], new D[] { null, new D(), new D(0), new D(5) }, new D[100] };\n D[][] result = new D[size][];\n for (int i = 0; i < size; i++)\n {\n result[i] = array[i % array.Length];\n }\n\n return result;\n }\n\n private static decimal[][] GenerateDecimalArrayArray(int size)\n {\n decimal[][] array = new decimal[][] { null, new decimal[0], new decimal[] { decimal.Zero, decimal.One, decimal.MinusOne, decimal.MinValue, decimal.MaxValue }, new decimal[100] };\n decimal[][] result = new decimal[size][];\n for (int i = 0; i < size; i++)\n {\n result[i] = array[i % array.Length];\n }\n\n return result;\n }\n\n private static Delegate[][] GenerateDelegateArrayArray(int size)\n {\n Delegate[][] array = new Delegate[][] { null, new Delegate[0], new Delegate[] { null, (Func)delegate () { return null; }, (Func)delegate (int i) { return i + 1; }, (Action)delegate { } }, new Delegate[100] };\n Delegate[][] result = new Delegate[size][];\n for (int i = 0; i < size; i++)\n {\n result[i] = array[i % array.Length];\n }\n\n return result;\n }\n\n private static double[][] GenerateDoubleArrayArray(int size)\n {\n double[][] array = new double[][] { null, new double[0], new double[] { 0, 1, -1, double.MinValue, double.MaxValue, double.Epsilon, double.NegativeInfinity, double.PositiveInfinity, double.NaN }, new double[100] };\n double[][] result = new double[size][];\n for (int i = 0; i < size; i++)\n {\n result[i] = array[i % array.Length];\n }\n\n return result;\n }\n\n private static E[][] GenerateEnumArrayArray(int size)\n {\n E[][] array = new E[][] { null, new E[0], new E[] { (E)0, E.A, E.B, (E)int.MaxValue, (E)int.MinValue }, new E[100] };\n E[][] result = new E[size][];\n for (int i = 0; i < size; i++)\n {\n result[i] = array[i % array.Length];\n }\n\n return result;\n }\n\n private static El[][] GenerateEnumLongArrayArray(int size)\n {\n El[][] array = new El[][] { null, new El[0], new El[] { (El)0, El.A, El.B, (El)long.MaxValue, (El)long.MinValue }, new El[100] };\n El[][] result = new El[size][];\n for (int i = 0; i < size; i++)\n {\n result[i] = array[i % array.Length];\n }\n\n return result;\n }\n\n private static float[][] GenerateFloatArrayArray(int size)\n {\n float[][] array = new float[][] { null, new float[0], new float[] { 0, 1, -1, float.MinValue, float.MaxValue, float.Epsilon, float.NegativeInfinity, float.PositiveInfinity, float.NaN }, new float[100] };\n float[][] result = new float[size][];\n for (int i = 0; i < size; i++)\n {\n result[i] = array[i % array.Length];\n }\n\n return result;\n }\n\n private static Func[][] GenerateFuncArrayArray(int size)\n {\n Func[][] array = new Func[][] { null, new Func[0], new Func[] { null, (Func)delegate () { return null; } }, new Func[100] };\n Func[][] result = new Func[size][];\n for (int i = 0; i < size; i++)\n {\n result[i] = array[i % array.Length];\n }\n\n return result;\n }\n\n private static I[][] GenerateInterfaceArrayArray(int size)\n {\n I[][] array = new I[][] { null, new I[0], new I[] { null, new C(), new D(), new D(0), new D(5) }, new I[100] };\n I[][] result = new I[size][];\n for (int i = 0; i < size; i++)\n {\n result[i] = array[i % array.Length];\n }\n\n return result;\n }\n\n private static IEquatable[][] GenerateIEquatableCustomArrayArray(int size)\n {\n IEquatable[][] array = new IEquatable[][] { null, new IEquatable[0], new IEquatable[] { null, new C(), new D(), new D(0), new D(5) }, new IEquatable[100] };\n IEquatable[][] result = new IEquatable[size][];\n for (int i = 0; i < size; i++)\n {\n result[i] = array[i % array.Length];\n }\n\n return result;\n }\n\n private static IEquatable[][] GenerateIEquatableCustom2ArrayArray(int size)\n {\n IEquatable[][] array = new IEquatable[][] { null, new IEquatable[0], new IEquatable[] { null, new D(), new D(0), new D(5) }, new IEquatable[100] };\n IEquatable[][] result = new IEquatable[size][];\n for (int i = 0; i < size; i++)\n {\n result[i] = array[i % array.Length];\n }\n\n return result;\n }\n\n private static int[][] GenerateIntArrayArray(int size)\n {\n int[][] array = new int[][] { null, new int[0], new int[] { 0, 1, -1, int.MinValue, int.MaxValue }, new int[100] };\n int[][] result = new int[size][];\n for (int i = 0; i < size; i++)\n {\n result[i] = array[i % array.Length];\n }\n\n return result;\n }\n\n private static long[][] GenerateLongArrayArray(int size)\n {\n long[][] array = new long[][] { null, new long[0], new long[] { 0, 1, -1, long.MinValue, long.MaxValue }, new long[100] };\n long[][] result = new long[size][];\n for (int i = 0; i < size; i++)\n {\n result[i] = array[i % array.Length];\n }\n\n return result;\n }\n\n private static object[][] GenerateObjectArrayArray(int size)\n {\n object[][] array = new object[][] { null, new object[0], new object[] { null, new object(), new C(), new D(3) }, new object[100] };\n object[][] result = new object[size][];\n for (int i = 0; i < size; i++)\n {\n result[i] = array[i % array.Length];\n }\n\n return result;\n }\n\n private static S[][] GenerateStructArrayArray(int size)\n {\n S[][] array = new S[][] { null, new S[0], new S[] { default(S), new S() }, new S[100] };\n S[][] result = new S[size][];\n for (int i = 0; i < size; i++)\n {\n result[i] = array[i % array.Length];\n }\n\n return result;\n }\n\n private static sbyte[][] GenerateSByteArrayArray(int size)\n {\n sbyte[][] array = new sbyte[][] { null, new sbyte[0], new sbyte[] { 0, 1, -1, sbyte.MinValue, sbyte.MaxValue }, new sbyte[100] };\n sbyte[][] result = new sbyte[size][];\n for (int i = 0; i < size; i++)\n {\n result[i] = array[i % array.Length];\n }\n\n return result;\n }\n\n private static Sc[][] GenerateStructWithStringArrayArray(int size)\n {\n Sc[][] array = new Sc[][] { null, new Sc[0], new Sc[] { default(Sc), new Sc(), new Sc(null) }, new Sc[100] };\n Sc[][] result = new Sc[size][];\n for (int i = 0; i < size; i++)\n {\n result[i] = array[i % array.Length];\n }\n\n return result;\n }\n\n private static Scs[][] GenerateStructWithStringAndValueArrayArray(int size)\n {\n Scs[][] array = new Scs[][] { null, new Scs[0], new Scs[] { default(Scs), new Scs(), new Scs(null, new S()) }, new Scs[100] };\n Scs[][] result = new Scs[size][];\n for (int i = 0; i < size; i++)\n {\n result[i] = array[i % array.Length];\n }\n\n return result;\n }\n\n private static short[][] GenerateShortArrayArray(int size)\n {\n short[][] array = new short[][] { null, new short[0], new short[] { 0, 1, -1, short.MinValue, short.MaxValue }, new short[100] };\n short[][] result = new short[size][];\n for (int i = 0; i < size; i++)\n {\n result[i] = array[i % array.Length];\n }\n\n return result;\n }\n\n private static Sp[][] GenerateStructWithTwoValuesArrayArray(int size)\n {\n Sp[][] array = new Sp[][] { null, new Sp[0], new Sp[] { default(Sp), new Sp(), new Sp(5, 5.0) }, new Sp[100] };\n Sp[][] result = new Sp[size][];\n for (int i = 0; i < size; i++)\n {\n result[i] = array[i % array.Length];\n }\n\n return result;\n }\n\n private static Ss[][] GenerateStructWithValueArrayArray(int size)\n {\n Ss[][] array = new Ss[][] { null, new Ss[0], new Ss[] { default(Ss), new Ss(), new Ss(new S()) }, new Ss[100] };\n Ss[][] result = new Ss[size][];\n for (int i = 0; i < size; i++)\n {\n result[i] = array[i % array.Length];\n }\n\n return result;\n }\n\n private static string[][] GenerateStringArrayArray(int size)\n {\n string[][] array = new string[][] { null, new string[0], new string[] { null, \"\", \"a\", \"foo\" }, new string[100] };\n string[][] result = new string[size][];\n for (int i = 0; i < size; i++)\n {\n result[i] = array[i % array.Length];\n }\n\n return result;\n }\n\n private static uint[][] GenerateUIntArrayArray(int size)\n {\n uint[][] array = new uint[][] { null, new uint[0], new uint[] { 0, 1, uint.MaxValue }, new uint[100] };\n uint[][] result = new uint[size][];\n for (int i = 0; i < size; i++)\n {\n result[i] = array[i % array.Length];\n }\n\n return result;\n }\n\n private static ulong[][] GenerateULongArrayArray(int size)\n {\n ulong[][] array = new ulong[][] { null, new ulong[0], new ulong[] { 0, 1, ulong.MaxValue }, new ulong[100] };\n ulong[][] result = new ulong[size][];\n for (int i = 0; i < size; i++)\n {\n result[i] = array[i % array.Length];\n }\n\n return result;\n }\n\n private static ushort[][] GenerateUShortArrayArray(int size)\n {\n ushort[][] array = new ushort[][] { null, new ushort[0], new ushort[] { 0, 1, ushort.MaxValue }, new ushort[100] };\n ushort[][] result = new ushort[size][];\n for (int i = 0; i < size; i++)\n {\n result[i] = array[i % array.Length];\n }\n\n return result;\n }\n\n private static T[][] GenerateGenericArrayArray(int size)\n {\n T[][] array = new T[][] { null, new T[0], new T[] { default(T) }, new T[100] };\n T[][] result = new T[size][];\n for (int i = 0; i < size; i++)\n {\n result[i] = array[i % array.Length];\n }\n\n return result;\n }\n\n private static Tc[][] GenerateGenericWithClassRestrictionArrayArray(int size) where Tc : class\n {\n Tc[][] array = new Tc[][] { null, new Tc[0], new Tc[] { null, default(Tc) }, new Tc[100] };\n Tc[][] result = new Tc[size][];\n for (int i = 0; i < size; i++)\n {\n result[i] = array[i % array.Length];\n }\n\n return result;\n }\n\n private static TC[][] GenerateGenericWithSubClassRestrictionArrayArray(int size) where TC : C\n {\n TC[][] array = new TC[][] { null, new TC[0], new TC[] { null, default(TC), (TC)new C() }, new TC[100] };\n TC[][] result = new TC[size][];\n for (int i = 0; i < size; i++)\n {\n result[i] = array[i % array.Length];\n }\n\n return result;\n }\n\n private static Tcn[][] GenerateGenericWithClassAndNewRestrictionArrayArray(int size) where Tcn : class, new()\n {\n Tcn[][] array = new Tcn[][] { null, new Tcn[0], new Tcn[] { null, default(Tcn), new Tcn() }, new Tcn[100] };\n Tcn[][] result = new Tcn[size][];\n for (int i = 0; i < size; i++)\n {\n result[i] = array[i % array.Length];\n }\n\n return result;\n }\n\n private static TCn[][] GenerateGenericWithSubClassAndNewRestrictionArrayArray(int size) where TCn : C, new()\n {\n TCn[][] array = new TCn[][] { null, new TCn[0], new TCn[] { null, default(TCn), new TCn(), (TCn)new C() }, new TCn[100] };", "answers": [" TCn[][] result = new TCn[size][];"], "length": 3140, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "f093dfbe-942e-4a34-a859-f670ff538c09", "reasoning": "The method is defining a helper to generate a jagged array for a generic type with subclass and new constraints. Following the pattern of previous Generate methods, after initializing the 'array' variable, the next step is to allocate a 'result' jagged array of the requested size before filling it in a loop. Therefore the next line should declare and instantiate the result array.", "reasoning_model_answer": "TCn[][] result = new TCn[size][];", "assistant_with_reasoning": "\nThe method is defining a helper to generate a jagged array for a generic type with subclass and new constraints. Following the pattern of previous Generate methods, after initializing the 'array' variable, the next step is to allocate a 'result' jagged array of the requested size before filling it in a loop. Therefore the next line should declare and instantiate the result array.\n\nTCn[][] result = new TCn[size][];", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 5.053, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 48004, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "TCn[][] result = new TCn[size][];", "score": 0.85, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "# Copyright 2008-2015 Nokia Solutions and Networks\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom robotide.lib.robot.api import logger\nfrom robotide.lib.robot.utils import (is_dict_like, is_string, is_truthy, plural_or_not,\n seq2str, seq2str2, type_name, unic, Matcher)\nfrom robotide.lib.robot.utils.asserts import assert_equals\nfrom robotide.lib.robot.version import get_version\n\n\nclass _List(object):\n\n def convert_to_list(self, item):\n \"\"\"Converts the given ``item`` to a Python ``list`` type.\n\n Mainly useful for converting tuples and other iterable to lists.\n Use `Create List` from the BuiltIn library for constructing new lists.\n \"\"\"\n return list(item)\n\n def append_to_list(self, list_, *values):\n \"\"\"Adds ``values`` to the end of ``list``.\n\n Example:\n | Append To List | ${L1} | xxx | | |\n | Append To List | ${L2} | x | y | z |\n =>\n | ${L1} = ['a', 'xxx']\n | ${L2} = ['a', 'b', 'x', 'y', 'z']\n \"\"\"\n for value in values:\n list_.append(value)\n\n def insert_into_list(self, list_, index, value):\n \"\"\"Inserts ``value`` into ``list`` to the position specified with ``index``.\n\n Index ``0`` adds the value into the first position, ``1`` to the second,\n and so on. Inserting from right works with negative indices so that\n ``-1`` is the second last position, ``-2`` third last, and so on. Use\n `Append To List` to add items to the end of the list.\n\n If the absolute value of the index is greater than\n the length of the list, the value is added at the end\n (positive index) or the beginning (negative index). An index\n can be given either as an integer or a string that can be\n converted to an integer.\n\n Example:\n | Insert Into List | ${L1} | 0 | xxx |\n | Insert Into List | ${L2} | ${-1} | xxx |\n =>\n | ${L1} = ['xxx', 'a']\n | ${L2} = ['a', 'xxx', 'b']\n \"\"\"\n list_.insert(self._index_to_int(index), value)\n\n def combine_lists(self, *lists):\n \"\"\"Combines the given ``lists`` together and returns the result.\n\n The given lists are not altered by this keyword.\n\n Example:\n | ${x} = | Combine List | ${L1} | ${L2} | |\n | ${y} = | Combine List | ${L1} | ${L2} | ${L1} |\n =>\n | ${x} = ['a', 'a', 'b']\n | ${y} = ['a', 'a', 'b', 'a']\n | ${L1} and ${L2} are not changed.\n \"\"\"\n ret = []\n for item in lists:\n ret.extend(item)\n return ret\n\n def set_list_value(self, list_, index, value):\n \"\"\"Sets the value of ``list`` specified by ``index`` to the given ``value``.\n\n Index ``0`` means the first position, ``1`` the second and so on.\n Similarly, ``-1`` is the last position, ``-2`` second last, and so on.\n Using an index that does not exist on the list causes an error.\n The index can be either an integer or a string that can be converted to\n an integer.\n\n Example:\n | Set List Value | ${L3} | 1 | xxx |\n | Set List Value | ${L3} | -1 | yyy |\n =>\n | ${L3} = ['a', 'xxx', 'yyy']\n \"\"\"\n try:\n list_[self._index_to_int(index)] = value\n except IndexError:\n self._index_error(list_, index)\n\n def remove_values_from_list(self, list_, *values):\n \"\"\"Removes all occurrences of given ``values`` from ``list``.\n\n It is not an error if a value does not exist in the list at all.\n\n Example:\n | Remove Values From List | ${L4} | a | c | e | f |\n =>\n | ${L4} = ['b', 'd']\n \"\"\"\n for value in values:\n while value in list_:\n list_.remove(value)\n\n def remove_from_list(self, list_, index):\n \"\"\"Removes and returns the value specified with an ``index`` from ``list``.\n\n Index ``0`` means the first position, ``1`` the second and so on.\n Similarly, ``-1`` is the last position, ``-2`` the second last, and so on.\n Using an index that does not exist on the list causes an error.\n The index can be either an integer or a string that can be converted\n to an integer.\n\n Example:\n | ${x} = | Remove From List | ${L2} | 0 |\n =>\n | ${x} = 'a'\n | ${L2} = ['b']\n \"\"\"\n try:\n return list_.pop(self._index_to_int(index))\n except IndexError:\n self._index_error(list_, index)\n\n def remove_duplicates(self, list_):\n \"\"\"Returns a list without duplicates based on the given ``list``.\n\n Creates and returns a new list that contains all items in the given\n list so that one item can appear only once. Order of the items in\n the new list is the same as in the original except for missing\n duplicates. Number of the removed duplicates is logged.\n\n New in Robot Framework 2.7.5.\n \"\"\"\n ret = []\n for item in list_:\n if item not in ret:\n ret.append(item)\n removed = len(list_) - len(ret)\n logger.info('%d duplicate%s removed.' % (removed, plural_or_not(removed)))\n return ret\n\n def get_from_list(self, list_, index):\n \"\"\"Returns the value specified with an ``index`` from ``list``.\n\n The given list is never altered by this keyword.\n\n Index ``0`` means the first position, ``1`` the second, and so on.\n Similarly, ``-1`` is the last position, ``-2`` the second last, and so on.\n Using an index that does not exist on the list causes an error.\n The index can be either an integer or a string that can be converted\n to an integer.\n\n Examples (including Python equivalents in comments):\n | ${x} = | Get From List | ${L5} | 0 | # L5[0] |\n | ${y} = | Get From List | ${L5} | -2 | # L5[-2] |\n =>\n | ${x} = 'a'\n | ${y} = 'd'\n | ${L5} is not changed\n \"\"\"\n try:\n return list_[self._index_to_int(index)]\n except IndexError:\n self._index_error(list_, index)\n\n def get_slice_from_list(self, list_, start=0, end=None):\n \"\"\"Returns a slice of the given list between ``start`` and ``end`` indexes.\n\n The given list is never altered by this keyword.\n\n If both ``start`` and ``end`` are given, a sublist containing values\n from ``start`` to ``end`` is returned. This is the same as\n ``list[start:end]`` in Python. To get all items from the beginning,\n use 0 as the start value, and to get all items until and including\n the end, use ``None`` (default) as the end value.\n\n Using ``start`` or ``end`` not found on the list is the same as using\n the largest (or smallest) available index.\n\n Examples (incl. Python equivalents in comments):\n | ${x} = | Get Slice From List | ${L5} | 2 | 4 | # L5[2:4] |\n | ${y} = | Get Slice From List | ${L5} | 1 | | # L5[1:None] |\n | ${z} = | Get Slice From List | ${L5} | | -2 | # L5[0:-2] |\n =>\n | ${x} = ['c', 'd']\n | ${y} = ['b', 'c', 'd', 'e']\n | ${z} = ['a', 'b', 'c']\n | ${L5} is not changed\n \"\"\"\n start = self._index_to_int(start, True)\n if end is not None:\n end = self._index_to_int(end)\n return list_[start:end]\n\n def count_values_in_list(self, list_, value, start=0, end=None):\n \"\"\"Returns the number of occurrences of the given ``value`` in ``list``.\n\n The search can be narrowed to the selected sublist by the ``start`` and\n ``end`` indexes having the same semantics as with `Get Slice From List`\n keyword. The given list is never altered by this keyword.\n\n Example:\n | ${x} = | Count Values In List | ${L3} | b |\n =>\n | ${x} = 1\n | ${L3} is not changed\n \"\"\"\n return self.get_slice_from_list(list_, start, end).count(value)\n\n def get_index_from_list(self, list_, value, start=0, end=None):\n \"\"\"Returns the index of the first occurrence of the ``value`` on the list.\n\n The search can be narrowed to the selected sublist by the ``start`` and\n ``end`` indexes having the same semantics as with `Get Slice From List`\n keyword. In case the value is not found, -1 is returned. The given list\n is never altered by this keyword.\n\n Example:\n | ${x} = | Get Index From List | ${L5} | d |\n =>\n | ${x} = 3\n | ${L5} is not changed\n \"\"\"\n if start == '':\n start = 0\n list_ = self.get_slice_from_list(list_, start, end)\n try:\n return int(start) + list_.index(value)\n except ValueError:\n return -1\n\n def copy_list(self, list_):\n \"\"\"Returns a copy of the given list.\n\n The given list is never altered by this keyword.\n \"\"\"\n return list_[:]\n\n def reverse_list(self, list_):\n \"\"\"Reverses the given list in place.\n\n Note that the given list is changed and nothing is returned. Use\n `Copy List` first, if you need to keep also the original order.\n\n | Reverse List | ${L3} |\n =>\n | ${L3} = ['c', 'b', 'a']\n \"\"\"\n list_.reverse()\n\n def sort_list(self, list_):\n \"\"\"Sorts the given list in place.\n\n The strings are sorted alphabetically and the numbers numerically.\n\n Note that the given list is changed and nothing is returned. Use\n `Copy List` first, if you need to keep also the original order.\n\n ${L} = [2,1,'a','c','b']\n | Sort List | ${L} |\n =>\n | ${L} = [1, 2, 'a', 'b', 'c']\n \"\"\"\n list_.sort()\n\n def list_should_contain_value(self, list_, value, msg=None):\n \"\"\"Fails if the ``value`` is not found from ``list``.\n\n If the keyword fails, the default error messages is `` does\n not contain value ''``. A custom message can be given using\n the ``msg`` argument.\n \"\"\"\n default = \"%s does not contain value '%s'.\" % (seq2str2(list_), value)\n _verify_condition(value in list_, default, msg)\n\n def list_should_not_contain_value(self, list_, value, msg=None):\n \"\"\"Fails if the ``value`` is not found from ``list``.\n\n See `List Should Contain Value` for an explanation of ``msg``.\n \"\"\"\n default = \"%s contains value '%s'.\" % (seq2str2(list_), value)\n _verify_condition(value not in list_, default, msg)\n\n def list_should_not_contain_duplicates(self, list_, msg=None):\n \"\"\"Fails if any element in the ``list`` is found from it more than once.\n\n The default error message lists all the elements that were found\n from the ``list`` multiple times, but it can be overridden by giving\n a custom ``msg``. All multiple times found items and their counts are\n also logged.\n\n This keyword works with all iterables that can be converted to a list.\n The original iterable is never altered.\n \"\"\"\n if not isinstance(list_, list):\n list_ = list(list_)\n dupes = []\n for item in list_:\n if item not in dupes:\n count = list_.count(item)\n if count > 1:\n logger.info(\"'%s' found %d times.\" % (item, count))\n dupes.append(item)\n if dupes:\n raise AssertionError(msg or\n '%s found multiple times.' % seq2str(dupes))\n\n def lists_should_be_equal(self, list1, list2, msg=None, values=True,\n names=None):\n \"\"\"Fails if given lists are unequal.\n\n The keyword first verifies that the lists have equal lengths, and then\n it checks are all their values equal. Possible differences between the\n values are listed in the default error message like ``Index 4: ABC !=\n Abc``.\n\n The error message can be configured using ``msg`` and ``values``\n arguments:\n - If ``msg`` is not given, the default error message is used.\n - If ``msg`` is given and ``values`` gets a value considered true\n (see `Boolean arguments`), the error message starts with the given\n ``msg`` followed by a newline and the default message.\n - If ``msg`` is given and ``values`` is not given a true value,\n the error message is just the given ``msg``.\n\n Optional ``names`` argument can be used for naming the indices shown in\n the default error message. It can either be a list of names matching\n the indices in the lists or a dictionary where keys are indices that\n need to be named. It is not necessary to name all of the indices. When\n using a dictionary, keys can be either integers or strings that can be\n converted to integers.\n\n Examples:\n | ${names} = | Create List | First Name | Family Name | Email |\n | Lists Should Be Equal | ${people1} | ${people2} | names=${names} |\n | ${names} = | Create Dictionary | 0=First Name | 2=Email |\n | Lists Should Be Equal | ${people1} | ${people2} | names=${names} |\n\n If the items in index 2 would differ in the above examples, the error\n message would contain a row like ``Index 2 (email): name@foo.com !=\n name@bar.com``.\n \"\"\"\n len1 = len(list1)\n len2 = len(list2)\n default = 'Lengths are different: %d != %d' % (len1, len2)\n _verify_condition(len1 == len2, default, msg, values)\n names = self._get_list_index_name_mapping(names, len1)\n diffs = list(self._yield_list_diffs(list1, list2, names))\n default = 'Lists are different:\\n' + '\\n'.join(diffs)\n _verify_condition(diffs == [], default, msg, values)\n\n def _get_list_index_name_mapping(self, names, list_length):\n if not names:\n return {}\n if is_dict_like(names):\n return dict((int(index), names[index]) for index in names)\n return dict(zip(range(list_length), names))\n\n def _yield_list_diffs(self, list1, list2, names):\n for index, (item1, item2) in enumerate(zip(list1, list2)):\n name = ' (%s)' % names[index] if index in names else ''\n try:\n assert_equals(item1, item2, msg='Index %d%s' % (index, name))\n except AssertionError as err:\n yield unic(err)\n\n def list_should_contain_sub_list(self, list1, list2, msg=None, values=True):\n \"\"\"Fails if not all of the elements in ``list2`` are found in ``list1``.\n\n The order of values and the number of values are not taken into\n account.\n\n See `Lists Should Be Equal` for more information about configuring\n the error message with ``msg`` and ``values`` arguments.\n \"\"\"\n diffs = ', '.join(unic(item) for item in list2 if item not in list1)\n default = 'Following values were not found from first list: ' + diffs\n _verify_condition(not diffs, default, msg, values)\n\n def log_list(self, list_, level='INFO'):\n \"\"\"Logs the length and contents of the ``list`` using given ``level``.\n\n Valid levels are TRACE, DEBUG, INFO (default), and WARN.\n\n If you only want to the length, use keyword `Get Length` from\n the BuiltIn library.\n \"\"\"\n logger.write('\\n'.join(self._log_list(list_)), level)\n\n def _log_list(self, list_):\n if not list_:\n yield 'List is empty.'\n elif len(list_) == 1:\n yield 'List has one item:\\n%s' % list_[0]\n else:\n yield 'List length is %d and it contains following items:' % len(list_)\n for index, item in enumerate(list_):\n yield '%s: %s' % (index, item)\n\n def _index_to_int(self, index, empty_to_zero=False):\n if empty_to_zero and not index:\n return 0\n try:\n return int(index)\n except ValueError:\n raise ValueError(\"Cannot convert index '%s' to an integer.\" % index)\n\n def _index_error(self, list_, index):\n raise IndexError('Given index %s is out of the range 0-%d.'\n % (index, len(list_)-1))\n\n\nclass _Dictionary(object):\n\n def convert_to_dictionary(self, item):\n \"\"\"Converts the given ``item`` to a Python ``dict`` type.\n\n Mainly useful for converting other mappings to dictionaries. Use\n `Create Dictionary` from the BuiltIn library for constructing new\n dictionaries.\n\n New in Robot Framework 2.9.\n \"\"\"\n return dict(item)\n\n def set_to_dictionary(self, dictionary, *key_value_pairs, **items):\n \"\"\"Adds the given ``key_value_pairs`` and ``items`` to the ``dictionary``.\n\n Giving items as ``key_value_pairs`` means giving keys and values\n as separate arguments:\n\n | Set To Dictionary | ${D1} | key | value | second | ${2} |\n =>\n | ${D1} = {'a': 1, 'key': 'value', 'second': 2}\n\n Starting from Robot Framework 2.8.1, items can also be given as kwargs\n using ``key=value`` syntax:\n\n | Set To Dictionary | ${D1} | key=value | second=${2} |\n\n The latter syntax is typically more convenient to use, but it has\n a limitation that keys must be strings.\n\n If given keys already exist in the dictionary, their values are updated.\n \"\"\"\n if len(key_value_pairs) % 2 != 0:\n raise ValueError(\"Adding data to a dictionary failed. There \"\n \"should be even number of key-value-pairs.\")\n for i in range(0, len(key_value_pairs), 2):\n dictionary[key_value_pairs[i]] = key_value_pairs[i+1]\n dictionary.update(items)\n return dictionary\n\n def remove_from_dictionary(self, dictionary, *keys):\n \"\"\"Removes the given ``keys`` from the ``dictionary``.\n\n If the given ``key`` cannot be found from the ``dictionary``, it\n is ignored.\n\n Example:\n | Remove From Dictionary | ${D3} | b | x | y |\n =>\n | ${D3} = {'a': 1, 'c': 3}\n \"\"\"\n for key in keys:\n if key in dictionary:\n value = dictionary.pop(key)\n logger.info(\"Removed item with key '%s' and value '%s'.\" % (key, value))\n else:\n logger.info(\"Key '%s' not found.\" % key)\n\n def keep_in_dictionary(self, dictionary, *keys):\n \"\"\"Keeps the given ``keys`` in the ``dictionary`` and removes all other.\n\n If the given ``key`` cannot be found from the ``dictionary``, it\n is ignored.\n\n Example:\n | Keep In Dictionary | ${D5} | b | x | d |\n =>\n | ${D5} = {'b': 2, 'd': 4}\n \"\"\"\n remove_keys = [k for k in dictionary if k not in keys]\n self.remove_from_dictionary(dictionary, *remove_keys)\n\n def copy_dictionary(self, dictionary):\n \"\"\"Returns a copy of the given dictionary.\n\n The given dictionary is never altered by this keyword.\n \"\"\"\n return dictionary.copy()\n\n def get_dictionary_keys(self, dictionary):\n \"\"\"Returns keys of the given ``dictionary``.\n\n Keys are returned in sorted order. The given ``dictionary`` is never\n altered by this keyword.\n\n Example:\n | ${keys} = | Get Dictionary Keys | ${D3} |\n =>\n | ${keys} = ['a', 'b', 'c']\n \"\"\"\n # TODO: Possibility to disable sorting. Can be handy with OrderedDicts.\n return sorted(dictionary)\n\n def get_dictionary_values(self, dictionary):\n \"\"\"Returns values of the given dictionary.\n\n Values are returned sorted according to keys. The given dictionary is\n never altered by this keyword.\n\n Example:\n | ${values} = | Get Dictionary Values | ${D3} |\n =>\n | ${values} = [1, 2, 3]\n \"\"\"\n return [dictionary[k] for k in self.get_dictionary_keys(dictionary)]\n\n def get_dictionary_items(self, dictionary):\n \"\"\"Returns items of the given ``dictionary``.\n\n Items are returned sorted by keys. The given ``dictionary`` is not\n altered by this keyword.\n\n Example:\n | ${items} = | Get Dictionary Items | ${D3} |\n =>\n | ${items} = ['a', 1, 'b', 2, 'c', 3]\n \"\"\"\n ret = []\n for key in self.get_dictionary_keys(dictionary):\n ret.extend((key, dictionary[key]))\n return ret\n\n def get_from_dictionary(self, dictionary, key):\n \"\"\"Returns a value from the given ``dictionary`` based on the given ``key``.\n\n If the given ``key`` cannot be found from the ``dictionary``, this\n keyword fails.\n\n The given dictionary is never altered by this keyword.\n\n Example:\n | ${value} = | Get From Dictionary | ${D3} | b |\n =>\n | ${value} = 2\n \"\"\"\n try:\n return dictionary[key]\n except KeyError:\n raise RuntimeError(\"Dictionary does not contain key '%s'.\" % key)\n\n def dictionary_should_contain_key(self, dictionary, key, msg=None):\n \"\"\"Fails if ``key`` is not found from ``dictionary``.\n\n See `List Should Contain Value` for an explanation of ``msg``.\n\n The given dictionary is never altered by this keyword.\n \"\"\"\n default = \"Dictionary does not contain key '%s'.\" % key\n _verify_condition(key in dictionary, default, msg)\n\n def dictionary_should_not_contain_key(self, dictionary, key, msg=None):\n \"\"\"Fails if ``key`` is found from ``dictionary``.\n\n See `List Should Contain Value` for an explanation of ``msg``.\n\n The given dictionary is never altered by this keyword.\n \"\"\"\n default = \"Dictionary contains key '%s'.\" % key\n _verify_condition(key not in dictionary, default, msg)\n\n def dictionary_should_contain_item(self, dictionary, key, value, msg=None):\n \"\"\"An item of ``key``/``value`` must be found in a `dictionary`.\n\n Value is converted to unicode for comparison.\n\n See `Lists Should Be Equal` for an explanation of ``msg``.\n The given dictionary is never altered by this keyword.\n \"\"\"\n self.dictionary_should_contain_key(dictionary, key, msg)\n actual, expected = unicode(dictionary[key]), unicode(value)\n default = \"Value of dictionary key '%s' does not match: %s != %s\" % (key, actual, expected)\n _verify_condition(actual == expected, default, msg)\n\n def dictionary_should_contain_value(self, dictionary, value, msg=None):\n \"\"\"Fails if ``value`` is not found from ``dictionary``.\n\n See `List Should Contain Value` for an explanation of ``msg``.\n\n The given dictionary is never altered by this keyword.\n \"\"\"\n default = \"Dictionary does not contain value '%s'.\" % value\n _verify_condition(value in dictionary.values(), default, msg)\n\n def dictionary_should_not_contain_value(self, dictionary, value, msg=None):\n \"\"\"Fails if ``value`` is found from ``dictionary``.\n\n See `List Should Contain Value` for an explanation of ``msg``.\n\n The given dictionary is never altered by this keyword.\n \"\"\"\n default = \"Dictionary contains value '%s'.\" % value\n _verify_condition(not value in dictionary.values(), default, msg)", "answers": [" def dictionaries_should_be_equal(self, dict1, dict2, msg=None, values=True):"], "length": 3117, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "5663a907-d56c-4657-9956-881dd2efe0d6", "reasoning": "The class _Dictionary defines a series of keyword methods for dictionary operations. The last defined method is `dictionary_should_not_contain_value`. In the original Robot Framework Collections library, the next keyword after this is `Dictionaries Should Be Equal`, implemented as the method `dictionaries_should_be_equal`. Therefore the next line of code is the method definition header for this keyword.", "reasoning_model_answer": "def dictionaries_should_be_equal(self, dict1, dict2, msg=None, values=True, names=None):", "assistant_with_reasoning": "\nThe class _Dictionary defines a series of keyword methods for dictionary operations. The last defined method is `dictionary_should_not_contain_value`. In the original Robot Framework Collections library, the next keyword after this is `Dictionaries Should Be Equal`, implemented as the method `dictionaries_should_be_equal`. Therefore the next line of code is the method definition header for this keyword.\n\ndef dictionaries_should_be_equal(self, dict1, dict2, msg=None, values=True, names=None):", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 7.212, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 23996, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "def dictionaries_should_be_equal(self, dict1, dict2, msg=None, values=True, names=None):", "score": 0.9, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "# -*- coding: utf-8 -*-\n#\n# Copyright (C) 2010-2014 Chris Nelson \n# All rights reserved.\n#\n# This software is licensed as described in the file COPYING, which\n# you should have received as part of this distribution.\n\nimport re\nimport time\nfrom datetime import timedelta, datetime\nfrom operator import itemgetter, attrgetter\n\nfrom trac.util.datefmt import localtz\ntry:\n from trac.util.datefmt import to_utimestamp\nexcept ImportError:\n from trac.util.datefmt import to_timestamp as to_utimestamp\nfrom trac.util.text import to_unicode\nfrom trac.util.html import Markup\nfrom trac.wiki.macros import WikiMacroBase\nfrom trac.web.chrome import Chrome\nimport copy\nfrom trac.ticket.query import Query\n\nfrom trac.config import IntOption, Option\nfrom trac.core import implements, Component, TracError\nfrom trac.web.api import IRequestFilter\nfrom trac.web.chrome import ITemplateProvider, add_script, add_stylesheet\nfrom pkg_resources import resource_filename\n\nfrom trac.wiki.api import parse_args\n\nfrom tracpm import TracPM\n\ntry:\n from trac.util.text import javascript_quote\nexcept ImportError:\n # Fallback for Trac<0.11.3 - verbatim copy from Trac 1.0\n _js_quote = {'\\\\': '\\\\\\\\', '\"': '\\\\\"', '\\b': '\\\\b', '\\f': '\\\\f',\n '\\n': '\\\\n', '\\r': '\\\\r', '\\t': '\\\\t', \"'\": \"\\\\'\"}\n for i in range(0x20) + [ord(c) for c in '&<>']:\n _js_quote.setdefault(chr(i), '\\\\u%04x' % i)\n _js_quote_re = re.compile(r'[\\x00-\\x1f\\\\\"\\b\\f\\n\\r\\t\\'&<>]')\n\n def javascript_quote(text):\n \"\"\"Quote strings for inclusion in javascript\"\"\"\n if not text:\n return ''\n def replace(match):\n return _js_quote[match.group(0)]\n return _js_quote_re.sub(replace, text)\n\n# ========================================================================\nclass TracJSGanttSupport(Component):\n implements(IRequestFilter, ITemplateProvider)\n\n Option('trac-jsgantt', 'option.format', 'day',\n \"\"\"Initial format of Gantt chart\"\"\")\n Option('trac-jsgantt', 'option.formats', 'day|week|month|quarter',\n \"\"\"Formats to show for Gantt chart\"\"\")\n IntOption('trac-jsgantt', 'option.sample', 0,\n \"\"\"Show sample Gantt\"\"\")\n IntOption('trac-jsgantt', 'option.res', 1,\n \"\"\"Show resource column\"\"\")\n IntOption('trac-jsgantt', 'option.dur', 1,\n \"\"\"Show duration column\"\"\")\n IntOption('trac-jsgantt', 'option.comp', 1,\n \"\"\"Show percent complete column\"\"\")\n Option('trac-jsgantt', 'option.caption', 'Resource',\n \"\"\"Caption to follow task in Gantt\"\"\")\n IntOption('trac-jsgantt', 'option.startDate', 1,\n \"\"\"Show start date column\"\"\")\n IntOption('trac-jsgantt', 'option.endDate', 1,\n \"\"\"Show finish date column\"\"\")\n Option('trac-jsgantt', 'option.dateDisplay', 'mm/dd/yyyy',\n \"\"\"Format to display dates\"\"\")\n IntOption('trac-jsgantt', 'option.openLevel', 999,\n \"\"\"How many levels of task hierarchy to show open\"\"\")\n IntOption('trac-jsgantt', 'option.expandClosedTickets', 1,\n \"\"\"Show children of closed tasks in the task hierarchy\"\"\")\n Option('trac-jsgantt', 'option.colorBy', 'priority',\n \"\"\"Field to use to color tasks\"\"\")\n IntOption('trac-jsgantt', 'option.lwidth', None,\n \"\"\"Width (in pixels) of left table\"\"\")\n IntOption('trac-jsgantt', 'option.showdep', 1,\n \"\"\"Show dependencies in Gantt\"\"\")\n IntOption('trac-jsgantt', 'option.userMap', 1,\n \"\"\"Map user IDs to user names\"\"\")\n IntOption('trac-jsgantt', 'option.omitMilestones', 0,\n \"\"\"Omit milestones\"\"\")\n Option('trac-jsgantt', 'option.schedule', 'alap',\n \"\"\"Schedule algorithm: alap or asap\"\"\")\n IntOption('trac-jsgantt', 'option.doResourceLeveling', 0,\n \"\"\"Resource level (1) or not (0)\"\"\")\n # This seems to be the first floating point option.\n Option('trac-jsgantt', 'option.hoursPerDay', '8.0',\n \"\"\"Hours worked per day\"\"\")\n Option('trac-jsgantt', 'option.display', None,\n \"\"\"Display filter for tickets in the form 'field1:value1|field2:value2' or 'field:value1|value2'; displays tickets where field1==value1, etc.\"\"\")\n Option('trac-jsgantt', 'option.order', 'wbs',\n \"\"\"Fields to sort tasks by before display. May include tickets fields (including custom fields) or 'wbs'.\"\"\")\n Option('trac-jsgantt', 'option.scrollTo', None,\n \"\"\"Date to scroll chart to (yyyy-mm--dd or 'today')\"\"\")\n\n Option('trac-jsGantt', 'option.linkStyle', 'standard',\n \"\"\"Style for ticket links; jsgantt (new window) or standard browser behavior like ticket links.\"\"\")\n\n\n # ITemplateProvider methods\n def get_htdocs_dirs(self):\n return [('tracjsgantt', resource_filename(__name__, 'htdocs'))]\n\n def get_templates_dirs(self):\n return []\n\n # IRequestFilter methods\n def pre_process_request(self, req, handler):\n # I think we should look for a TracJSGantt on the page and set\n # a flag for the post_process_request handler if found\n return handler\n\n def post_process_request(self, req, template, data, content_type):\n add_script(req, 'tracjsgantt/jsgantt.js')\n add_stylesheet(req, 'tracjsgantt/jsgantt.css')\n add_stylesheet(req, 'tracjsgantt/tracjsgantt.css')\n return template, data, content_type\n\n\nclass TracJSGanttChart(WikiMacroBase):\n \"\"\"\nDisplays a Gantt chart for the specified tickets.\n\nThe chart display can be controlled with a number of macro arguments:\n\n||'''Argument'''||'''Description'''||'''Default'''||\n|| `formats`||What to display in the format control. A pipe-separated list of `minute`, `hour`, `day`, `week`, `month`, and `quarter` (though `minute` may not be very useful). ||'day|week|month|quarter'||\n|| `format`||Initial display format, one of those listed in `formats` || First format ||\n|| `sample`||Display sample tasks (1) or not (0) || 0 ||\n|| `res`||Show resource column (1) or not (0) || 1 ||\n|| `dur`||Show duration colunn (1) or not (0) || 1 ||\n|| `comp`||Show percent complete column (1) or not (0) || 1 ||\n|| `caption`||Caption to place to right of tasks: None, Caption, Resource, Duration, %Complete || Resource ||\n|| `startDate`||Show start date column (1) or not (0) || 1 ||\n|| `endDate`||Show end date column (1) or not (0) || 1 ||\n|| `dateDisplay`||Date display format: 'mm/dd/yyyy', 'dd/mm/yyyy', or 'yyyy-mm-dd' || 'mm/dd/yyyy' ||\n|| `openLevel`||Number of levels of tasks to show. 1 = only top level task. || 999 ||\n|| `colorBy`||Field to use to choose task colors. Each unique value of the field will have a different color task. Other likely useful values are owner and milestone but any field can be used. || priority ||\n|| `root`||When using something like Subtickets plugin to maintain a tree of tickets and subtickets, you may create a Gantt showing a ticket and all of its descendants with `root=`. The macro uses the configured `parent` field to find all descendant tasks and build an `id=` argument for Trac's native query handler.[[br]][[br]]Multiple roots may be provided like `root=1|12|32`.[[br]][[br]]When used in a ticket description or comment, `root=self` will display the current ticket's descendants.||None||\n|| `goal`||When using something like MasterTickets plugin to maintain ticket dependencies, you may create a Gantt showing a ticket and all of its predecessors with `goal=`. The macro uses the configured `succ` field to find all predecessor tasks and build an `id=` argument for Trac's native query handler.[[br]][[br]]Multiple goals may be provided like `goal=1|12|32`.[[br]][[br]]When used in a ticket description or comment, `goal=self` will display the current ticket's predecessors.||None||\n|| `lwidth`||The width, in pixels, of the table of task names, etc. on the left of the Gantt. || ||\n|| `showdep`||Show dependencies (1) or not (0)||1||\n|| `userMap`||Map user !IDs to full names (1) or not (0).||1||\n|| `omitMilestones`||Show milestones for displayed tickets (0) or only those specified by `milestone=` (1)||0||\n|| `schedule`||Schedule tasks based on dependenies and estimates. Either as soon as possible (asap) or as late as possible (alap)||alap||\n||`doResourceLeveling`||Resolve resource conflicts (1) or not (0) when scheduling tickets.||0||\n||`display`||Filter for limiting display of tickets. `owner:fred` shows only tickets owned by fred. `status:closed` shows only closed tickets.||None||\n||`order`||Order of fields used to sort tickets before display. `order=milestone` sorts by milestone. May include ticket fields, including custom fields, or \"wbs\" (work breakdown structure).||wbs||\n\nSite-wide defaults for macro arguments may be set in the `trac-jsgantt` section of `trac.ini`. `option.` overrides the built-in default for `` from the table above.\n\nAll other macro arguments are treated as TracQuery specification (e.g., milestone=ms1|ms2) to control which tickets are displayed.\n\n \"\"\"\n\n pm = None\n options = {}\n\n # The date part of these formats has to be in sync. Including\n # hour and minute in the pyDateFormat makes the plugin easier to\n # debug at times because that's how the date shows up in page\n # source.\n #\n # jsDateFormat is the date format that the JavaScript expects\n # dates in. It can be one of 'mm/dd/yyyy', 'dd/mm/yyyy', or\n # 'yyyy-mm-dd'. pyDateFormat is a strptime() format that matches\n # jsDateFormat. As long as they are in sync, there's no real\n # reason to change them.\n jsDateFormat = 'yyyy-mm-dd'\n pyDateFormat = '%Y-%m-%d %H:%M'\n\n # User map (login -> realname) is loaded on demand, once.\n # Initialization to None means it is not yet initialized.\n user_map = None\n\n def __init__(self):\n # Instantiate the PM component\n self.pm = TracPM(self.env)\n\n self.GanttID = 'g'\n\n\n # All the macro's options with default values.\n # Anything else passed to the macro is a TracQuery field.\n options = ('format', 'formats', 'sample', 'res', 'dur', 'comp',\n 'caption', 'startDate', 'endDate', 'dateDisplay',\n 'openLevel', 'expandClosedTickets', 'colorBy', 'lwidth',\n 'showdep', 'userMap', 'omitMilestones',\n 'schedule', 'hoursPerDay', 'doResourceLeveling',\n 'display', 'order', 'scrollTo', 'linkStyle')\n\n for opt in options:\n self.options[opt] = self.config.get('trac-jsgantt',\n 'option.%s' % opt)\n\n\n def _begin_gantt(self, options):\n if options['format']:\n defaultFormat = options['format']\n else:\n defaultFormat = options['formats'].split('|')[0]\n showdep = options['showdep']\n text = ''\n text += '
    \\n'\n text += '\\n'\n return chart\n\n def _gantt_options(self, options):\n opt = ''\n if (options['linkStyle']):\n linkStyle = options['linkStyle']\n else:\n linkStyle = 'standard'\n opt += self.GanttID+'.setLinkStyle(\"%s\")\\n' % linkStyle\n opt += self.GanttID+'.setShowRes(%s);\\n' % options['res']\n opt += self.GanttID+'.setShowDur(%s);\\n' % options['dur']\n opt += self.GanttID+'.setShowComp(%s);\\n' % options['comp']\n if (options['scrollTo']):\n opt += self.GanttID+'.setScrollDate(\"%s\");\\n' % options['scrollTo']\n w = options['lwidth']\n if w:\n opt += self.GanttID+'.setLeftWidth(%s);\\n' % w\n\n\n opt += self.GanttID+'.setCaptionType(\"%s\");\\n' % \\\n javascript_quote(options['caption'])\n\n opt += self.GanttID+'.setShowStartDate(%s);\\n' % options['startDate']\n opt += self.GanttID+'.setShowEndDate(%s);\\n' % options['endDate']\n\n opt += self.GanttID+'.setDateInputFormat(\"%s\");\\n' % \\\n javascript_quote(self.jsDateFormat)\n\n opt += self.GanttID+'.setDateDisplayFormat(\"%s\");\\n' % \\\n javascript_quote(options['dateDisplay'])\n\n opt += self.GanttID+'.setFormatArr(%s);\\n' % ','.join(\n '\"%s\"' % javascript_quote(f) for f in options['formats'].split('|'))\n opt += self.GanttID+'.setPopupFeatures(\"location=1,scrollbars=1\");\\n'\n return opt\n\n # TODO - use ticket-classN styles instead of colors?\n def _add_sample_tasks(self):\n task= ''\n tasks = self.GanttID+'.setDateInputFormat(\"mm/dd/yyyy\");\\n'\n\n # ID Name Start End Display Link MS Res Pct Gr Par Open Dep Cap\n tasks += self.GanttID+'.AddTaskItem(new JSGantt.TaskItem('+self.GanttID+',1, \"Define Chart API\", \"\", \"\", \"#ff0000\", \"http://help.com\", 0, \"Brian\", 0, 1, 0, 1));\\n'\n tasks += self.GanttID+'.AddTaskItem(new JSGantt.TaskItem('+self.GanttID+',11, \"Chart Object\", \"2/20/2011\", \"2/20/2011\", \"#ff00ff\", \"http://www.yahoo.com\", 1, \"Shlomy\", 100, 0, 1, 1));\\n'\n tasks += self.GanttID+'.AddTaskItem(new JSGantt.TaskItem('+self.GanttID+',12, \"Task Objects\", \"\", \"\", \"#00ff00\", \"\", 0, \"Shlomy\", 40, 1, 1, 1));\\n'\n tasks += self.GanttID+'.AddTaskItem(new JSGantt.TaskItem('+self.GanttID+',121, \"Constructor Proc\", \"2/21/2011\", \"3/9/2011\", \"#00ffff\", \"http://www.yahoo.com\", 0, \"Brian T.\", 60, 0, 12, 1));\\n'\n tasks += self.GanttID+'.AddTaskItem(new JSGantt.TaskItem('+self.GanttID+',122, \"Task Variables\", \"3/6/2011\", \"3/11/2011\", \"#ff0000\", \"http://help.com\", 0, \"\", 60, 0, 12, 1,121));\\n'\n tasks += self.GanttID+'.AddTaskItem(new JSGantt.TaskItem('+self.GanttID+',123, \"Task Functions\", \"3/9/2011\", \"3/29/2011\", \"#ff0000\", \"http://help.com\", 0, \"Anyone\", 60, 0, 12, 1, 0, \"This is another caption\"));\\n'\n tasks += self.GanttID+'.AddTaskItem(new JSGantt.TaskItem('+self.GanttID+',2, \"Create HTML Shell\", \"3/24/2011\", \"3/25/2011\", \"#ffff00\", \"http://help.com\", 0, \"Brian\", 20, 0, 0, 1,122));\\n'\n tasks += self.GanttID+'.AddTaskItem(new JSGantt.TaskItem('+self.GanttID+',3, \"Code Javascript\", \"\", \"\", \"#ff0000\", \"http://help.com\", 0, \"Brian\", 0, 1, 0, 1));\\n'\n tasks += self.GanttID+'.AddTaskItem(new JSGantt.TaskItem('+self.GanttID+',31, \"Define Variables\", \"2/25/2011\", \"3/17/2011\", \"#ff00ff\", \"http://help.com\", 0, \"Brian\", 30, 0, 3, 1, 0,\"Caption 1\"));\\n'\n tasks += self.GanttID+'.AddTaskItem(new JSGantt.TaskItem('+self.GanttID+',32, \"Calculate Chart Size\", \"3/15/2011\", \"3/24/2011\", \"#00ff00\", \"http://help.com\", 0, \"Shlomy\", 40, 0, 3, 1));\\n'\n tasks += self.GanttID+'.AddTaskItem(new JSGantt.TaskItem('+self.GanttID+',33, \"Draw Taks Items\", \"\", \"\", \"#00ff00\", \"http://help.com\", 0, \"Someone\", 40, 1, 3, 1));\\n'\n tasks += self.GanttID+'.AddTaskItem(new JSGantt.TaskItem('+self.GanttID+',332, \"Task Label Table\", \"3/6/2011\", \"3/11/2011\", \"#0000ff\", \"http://help.com\", 0, \"Brian\", 60, 0, 33, 1));\\n'\n tasks += self.GanttID+'.AddTaskItem(new JSGantt.TaskItem('+self.GanttID+',333, \"Task Scrolling Grid\", \"3/9/2011\", \"3/20/2011\", \"#0000ff\", \"http://help.com\", 0, \"Brian\", 60, 0, 33, 1));\\n'\n tasks += self.GanttID+'.AddTaskItem(new JSGantt.TaskItem('+self.GanttID+',34, \"Draw Task Bars\", \"\", \"\", \"#990000\", \"http://help.com\", 0, \"Anybody\", 60, 1, 3, 1));\\n'\n tasks += self.GanttID+'.AddTaskItem(new JSGantt.TaskItem('+self.GanttID+',341, \"Loop each Task\", \"3/26/2011\", \"4/11/2011\", \"#ff0000\", \"http://help.com\", 0, \"Brian\", 60, 0, 34, 1, \"332,333\"));\\n'\n tasks += self.GanttID+'.AddTaskItem(new JSGantt.TaskItem('+self.GanttID+',342, \"Calculate Start/Stop\", \"4/12/2011\", \"5/18/2011\", \"#ff6666\", \"http://help.com\", 0, \"Brian\", 60, 0, 34, 1));\\n'\n tasks += self.GanttID+'.AddTaskItem(new JSGantt.TaskItem('+self.GanttID+',343, \"Draw Task Div\", \"5/13/2011\", \"5/17/2011\", \"#ff0000\", \"http://help.com\", 0, \"Brian\", 60, 0, 34, 1));\\n'\n tasks += self.GanttID+'.AddTaskItem(new JSGantt.TaskItem('+self.GanttID+',344, \"Draw Completion Div\", \"5/17/2011\", \"6/04/2011\", \"#ff0000\", \"http://help.com\", 0, \"Brian\", 60, 0, 34, 1));\\n'\n tasks += self.GanttID+'.AddTaskItem(new JSGantt.TaskItem('+self.GanttID+',35, \"Make Updates\", \"10/17/2011\",\"12/04/2011\",\"#f600f6\", \"http://help.com\", 0, \"Brian\", 30, 0, 3, 1));\\n'\n return tasks\n\n # Get the required columns for the tickets which match the\n # criteria in options.\n def _query_tickets(self, options):\n query_options = {}\n for key in options.keys():\n if not key in self.options:\n query_options[key] = options[key]\n\n # The fields always needed by the Gantt\n fields = set([\n 'description',\n 'owner',\n 'type',\n 'status',\n 'summary',\n 'milestone',\n 'priority'])\n\n # Make sure the coloring field is included\n if 'colorBy' in options:\n fields.add(str(options['colorBy']))\n\n rawtickets = self.pm.query(query_options, fields, self.req)\n\n # Do permissions check on tickets\n tickets = [t for t in rawtickets\n if 'TICKET_VIEW' in self.req.perm('ticket', t['id'])]\n\n return tickets\n\n def _compare_tickets(self, t1, t2):\n # If t2 depends on t1, t2 is first\n if t1['id'] in self.pm.successors(t2):\n return 1\n # If t1 depends on t2, t1 is first\n elif t2['id'] in self.pm.successors(t1):\n return -1\n # If t1 ends first, it's first\n elif self.pm.finish(t1) < self.pm.finish(t2):\n return -1\n # If t2 ends first, it's first\n elif self.pm.finish(t1) > self.pm.finish(t2):\n return 1\n # End dates are same. If t1 starts later, it's later\n elif self.pm.start(t1) > self.pm.start(t2):\n return 1\n # Otherwise, preserve order (assume t1 is before t2 when called)\n else:\n return 0\n\n # Compute WBS for sorting and figure out the tickets' levels for\n # controlling how many levels are open.\n #\n # WBS is a list like [ 2, 4, 1] (the first child of the fourth\n # child of the second top-level element).\n def _compute_wbs(self):\n # Set the ticket's level and wbs then recurse to children.\n def _setLevel(tid, wbs, level):\n # Update this node\n self.ticketsByID[tid]['level'] = level\n self.ticketsByID[tid]['wbs'] = copy.copy(wbs)\n\n # Recurse to children\n childIDs = self.pm.children(self.ticketsByID[tid])\n if childIDs:\n childTickets = [self.ticketsByID[cid] for cid in childIDs]\n childTickets.sort(self._compare_tickets)\n childIDs = [ct['id'] for ct in childTickets]\n\n # Add another level\n wbs.append(1)\n for c in childIDs:\n wbs = _setLevel(c, wbs, level+1)\n # Remove the level we added\n wbs.pop()\n\n\n # Increment last element of wbs\n wbs[len(wbs)-1] += 1\n\n return wbs\n\n # Set WBS and level on all top level tickets (and recurse) If\n # a ticket's parent is not in the viewed tickets, consider it\n # top-level\n wbs = [ 1 ]\n roots = self.pm.roots(self.ticketsByID)\n for t in self.tickets:\n if t['id'] in roots:\n wbs = _setLevel(t['id'], wbs, 1)\n\n\n def _task_display(self, t, options):\n def _buildMap(field):\n self.classMap = {}\n i = 0\n for t in self.tickets:\n if t[field] not in self.classMap:\n i = i + 1\n self.classMap[t[field]] = i\n\n def _buildEnumMap(field):\n self.classMap = {}\n db = self.env.get_db_cnx()\n cursor = db.cursor()\n cursor.execute(\"SELECT name,\" +\n db.cast('value', 'int') +\n \" FROM enum WHERE type=%s\", (field,))\n for name, value in cursor:\n self.classMap[name] = value\n\n display = None\n colorBy = options['colorBy']\n\n # Build the map the first time we need it\n if self.classMap == None:\n # Enums (TODO: what others should I list?)\n if options['colorBy'] in ['priority', 'severity']:\n _buildEnumMap(colorBy)\n else:\n _buildMap(colorBy)\n\n # Set display based on class map\n if t[colorBy] in self.classMap:\n display = 'class=ticket-class%d' % self.classMap[t[colorBy]]\n\n # Add closed status for strike through\n if t['status'] == 'closed':\n if display == None:\n display = 'class=ticket-closed'\n else:\n display += ' ticket-closed'\n\n if display == None:\n display = '#ff7f3f'\n return display\n\n\n # Format a ticket into JavaScript source to display the\n # task. ticket is expected to have:\n # children - child ticket IDs or None\n # description - ticket description.\n # id - ticket ID, an integer\n # level - levels from root (0)\n # link - What to link to\n # owner - Used as resource name.\n # percent - integer percent complete, 0..100 (or \"act/est\")\n # priority - used to color the task\n # calc_finish - end date (ignored if children is not None)\n # self.fields[parent] - parent ticket ID\n # self.fields[pred] - predecessor ticket IDs\n # calc_start - start date (ignored if children is not None)\n # status - string displayed in tool tip ; FIXME - not displayed yet\n # summary - ticket summary\n # type - string displayed in tool tip FIXME - not displayed yet\n def _format_ticket(self, ticket, options):\n # Translate owner to full name\n def _owner(ticket):\n if self.pm.isMilestone(ticket):\n owner_name = ''\n else:\n owner_name = ticket['owner']\n if options['userMap']:\n # Build the map the first time we use it\n if self.user_map is None:\n self.user_map = {}\n for username, name, email in self.env.get_known_users():\n self.user_map[username] = name\n # Map the user name\n if self.user_map.get(owner_name):\n owner_name = self.user_map[owner_name]\n return owner_name\n\n task = ''\n\n # pID, pName\n if self.pm.isMilestone(ticket):\n if ticket['id'] > 0:\n # Put ID number on inchpebbles\n name = 'MS:%s (#%s)' % (ticket['summary'], ticket['id'])\n else:\n # Don't show bogus ID of milestone pseudo tickets.\n name = 'MS:%s' % ticket['summary']\n else:\n name = \"#%d:%s (%s %s)\" % \\\n (ticket['id'], ticket['summary'],\n ticket['status'], ticket['type'])\n task += 't = new JSGantt.TaskItem(%s,%d,\"%s\",' % \\\n (self.GanttID, ticket['id'], javascript_quote(name))\n\n # pStart, pEnd\n task += '\"%s\",' % self.pm.start(ticket).strftime(self.pyDateFormat)\n task += '\"%s\",' % self.pm.finish(ticket).strftime(self.pyDateFormat)\n\n # pDisplay\n task += '\"%s\",' % javascript_quote(self._task_display(ticket, options))\n\n # pLink\n task += '\"%s\",' % javascript_quote(ticket['link'])\n\n # pMile\n if self.pm.isMilestone(ticket):\n task += '1,'\n else:\n task += '0,'\n\n # pRes (owner)\n task += '\"%s\",' % javascript_quote(_owner(ticket))\n\n # pComp (percent complete); integer 0..100\n task += '\"%s\",' % self.pm.percentComplete(ticket)\n\n # pGroup (has children)\n if self.pm.children(ticket):\n task += '%s,' % 1\n else:\n task += '%s,' % 0\n\n # pParent (parent task ID)\n # If there's no parent, don't link to it\n if self.pm.parent(ticket) == None:\n task += '%s,' % 0\n else:\n task += '%s,' % self.pm.parent(ticket)\n\n # open\n if int(ticket['level']) < int(options['openLevel']) and \\\n ((options['expandClosedTickets'] != 0) or \\\n (ticket['status'] != 'closed')):\n openGroup = 1\n else:\n openGroup = 0\n task += '%d,' % openGroup\n\n # predecessors\n pred = [str(s) for s in self.pm.predecessors(ticket)]\n if len(pred):\n task += '\"%s\",' % javascript_quote(','.join(pred))\n else:\n task += '\"%s\",' % javascript_quote(','.join(''))\n\n # caption\n # FIXME - if caption isn't set to caption, use \"\" because the\n # description could be quite long and take a long time to make\n # safe and display.\n task += '\"%s (%s %s)\"' % (javascript_quote(ticket['description']),\n javascript_quote(ticket['status']),\n javascript_quote(ticket['type']))\n task += ');\\n'\n task += self.GanttID+'.AddTaskItem(t);\\n'\n return task\n\n def _filter_tickets(self, options, tickets):\n # Build the list of display filters from the configured value\n if not options.get('display') or options['display'] == '':\n displayFilter = {}\n else:\n # The general form is\n # 'display=field:value|field:value...'. Split on pipe to\n # get each part\n displayList = options['display'].split('|')\n\n # Process each part into the display filter\n displayFilter = {}\n field = None\n for f in displayList:\n parts = f.split(':')\n # Just one part, it's a value for the previous field\n if len(parts) == 1:\n if field == None:\n raise TracError(('display option error in \"%s\".' +\n ' Should be \"display=f1:v1|f2:v2\"' +\n ' or \"display=f:v1|v2\".') %\n options['display'])\n else:\n value = parts[0]\n else:\n field = parts[0]\n value = parts[1]\n\n if field in displayFilter:\n displayFilter[field].append(value)\n else:\n displayFilter[field] = [ value ]\n\n # If present and 1, true, otherwise false.\n if options.get('omitMilestones') \\\n and int(options['omitMilestones']) == 1:\n omitMilestones = True\n else:\n omitMilestones = False\n\n # Filter the tickets\n filteredTickets = []\n for ticket in tickets:\n # Default to showing every ticket\n fieldDisplay = True\n\n if omitMilestones and \\\n self.pm.isTracMilestone(ticket):\n fieldDisplay = False\n else:\n # Process each element and disable display if all\n # filters fail to match. ((or) disjunction)\n for f in displayFilter:\n display = True\n for v in displayFilter[f]:\n if ticket[f] == v:\n display = True\n break\n display = False\n fieldDisplay = fieldDisplay & display\n\n if fieldDisplay:", "answers": [" filteredTickets.append(ticket)"], "length": 2982, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "8b0166fa-65d8-49b8-91de-62190fbb8931", "reasoning": "In the _filter_tickets method, after evaluating each ticket against the display filters, the code determines a boolean fieldDisplay. When fieldDisplay is true, the ticket should be kept in the result list. The typical action is to append the ticket to the filteredTickets list. Therefore the next line after the conditional is the append statement.", "reasoning_model_answer": "filteredTickets.append(ticket)", "assistant_with_reasoning": "\nIn the _filter_tickets method, after evaluating each ticket against the display filters, the code determines a boolean fieldDisplay. When fieldDisplay is true, the ticket should be kept in the result list. The typical action is to append the ticket to the filteredTickets list. Therefore the next line after the conditional is the append statement.\n\nfilteredTickets.append(ticket)", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 2.436, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 29394, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "filteredTickets.append(ticket)", "score": 0.79, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/* This file is part of VoltDB.\n * Copyright (C) 2008-2017 VoltDB Inc.\n *\n * Permission is hereby granted, free of charge, to any person obtaining\n * a copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR\n * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,\n * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n * OTHER DEALINGS IN THE SOFTWARE.\n */\n\npackage org.voltdb_testfuncs;\n\nimport java.math.BigDecimal;\nimport java.util.Arrays;\nimport java.util.Date;\nimport java.util.List;\n\nimport org.voltdb.VoltType;\nimport org.voltdb.VoltTypeException;\nimport org.voltdb.types.GeographyPointValue;\nimport org.voltdb.types.GeographyValue;\nimport org.voltdb.types.TimestampType;\n\n/** Contains a bunch of UDF's (user-defined functions) used for testing. */\npublic class UserDefinedTestFunctions {\n // Change this to true, to get a very altered version of most of these\n // UDF's (specifically, the ones with \"add\" or \"concat\" in their names);\n // useful for testing of @UpdateClasses (see ENG-12856)\n private boolean USE_ALTERNATIVE_VERSION = false;\n\n /** A simple user-defined (runtime) exception, used to test UDF's\n * (user-defined exceptions) that throw such exceptions. */\n public class UserDefinedTestException extends RuntimeException {\n private static final long serialVersionUID = 1L;\n\n public UserDefinedTestException() {\n }\n public UserDefinedTestException(String message) {\n super(message);\n }\n public UserDefinedTestException(Throwable cause) {\n super(cause);\n }\n public UserDefinedTestException(String message, Throwable cause) {\n super(message, cause);\n }\n }\n\n // We start with private methods that are called by (some of) the test\n // UDF's (user-defined functions) below:\n\n /**\n * Returns the VoltDB null value that corresponds to the data type\n * of the input value; for example, -128 for a TINYINT (byte) value,\n * or -32768 for a SMALLINT (short) value. However, if useTrueNullValue\n * is true, or if the value is not of a recognized numeric type, a\n * true Java null is returned.\n */\n private Number getNullValue(Number value, boolean useTrueNullValue) {\n if (useTrueNullValue) {\n return null;\n }\n\n switch (value.getClass().toString()) {\n case \"class java.lang.Byte\": return VoltType.NULL_TINYINT; // the TINYINT (byte) null value (-128)\n case \"class java.lang.Short\": return VoltType.NULL_SMALLINT; // the SMALLINT (short) null value (-32768)\n case \"class java.lang.Integer\": return VoltType.NULL_INTEGER; // the INTEGER (int) null value (-2147483648)\n case \"class java.lang.Long\": return VoltType.NULL_BIGINT; // the BIGINT (long) null value (-9223372036854775808L)\n case \"class java.lang.Double\": return VoltType.NULL_FLOAT; // the FLOAT (double) null value (-1.7E+308D)\n default: return null;\n }\n }\n\n public static class UDF_TEST {\n public static final int RETURN_DATA_TYPE_NULL = -100;\n public static final int RETURN_JAVA_NULL = -101;\n public static final int RETURN_TINYINT_NULL = -102;\n public static final int RETURN_SMALLINT_NULL = -103;\n public static final int RETURN_INTEGER_NULL = -104;\n public static final int RETURN_BIGINT_NULL = -105;\n public static final int RETURN_FLOAT_NULL = -106;\n public static final int RETURN_DECIMAL_MIN = -107;\n public static final int RETURN_DECIMAL_MAX = -108;\n public static final int RETURN_NaN = -109;\n public static final int THROW_NullPointerException = -110;\n public static final int THROW_IllegalArgumentException = -111;\n public static final int THROW_NumberFormatException = -112;\n public static final int THROW_ArrayIndexOutOfBoundsException = -113;\n public static final int THROW_ClassCastException = -114;\n public static final int THROW_ArithmeticException = -115;\n public static final int THROW_UnsupportedOperationException = -116;\n public static final int THROW_VoltTypeException = -117;\n public static final int THROW_UserDefinedTestException = -118;\n }\n\n /** Usually just returns the input value; but certain special input values\n * (generally between -100 and -120) trigger an exception to be thrown,\n * or special VoltDB \"null\" values to be returned. */\n private Number testExceptionsByValue(Number value) {\n return testExceptionsByValue(value, false);\n }\n\n /** Usually just returns the input value; but certain special input values\n * (generally between -100 and -120) trigger an exception to be thrown,\n * or special VoltDB \"null\" values to be returned. When useTrueNullValue\n * is true, and the special input value -100 is given, a true Java null\n * is returned. */\n @SuppressWarnings(\"null\")\n private Number testExceptionsByValue(Number value, boolean useTrueNullValue) {\n if (value == null) {\n return null;\n }\n Integer uninitialized = null;\n Integer[] array = {1, 2, 3, 4, 5};\n int intValue = value.intValue();\n\n switch (intValue) {\n case UDF_TEST.RETURN_DATA_TYPE_NULL: return getNullValue(value, useTrueNullValue);\n case UDF_TEST.RETURN_JAVA_NULL: return null;\n case UDF_TEST.RETURN_TINYINT_NULL: return VoltType.NULL_TINYINT; // the TINYINT (byte) null value (-128)\n case UDF_TEST.RETURN_SMALLINT_NULL: return VoltType.NULL_SMALLINT; // the SMALLINT (short) null value (-32768)\n case UDF_TEST.RETURN_INTEGER_NULL: return VoltType.NULL_INTEGER; // the INTEGER (int) null value (-2147483648)\n case UDF_TEST.RETURN_BIGINT_NULL: return VoltType.NULL_BIGINT; // the BIGINT (long) null value (-9223372036854775808L)\n case UDF_TEST.RETURN_FLOAT_NULL: return VoltType.NULL_FLOAT; // the FLOAT (double) null value (-1.7E+308D)\n case UDF_TEST.RETURN_DECIMAL_MIN: return new BigDecimal(\"-99999999999999999999999999.999999999999\"); // the DECIMAL (BigDecimal) minimum value\n case UDF_TEST.RETURN_DECIMAL_MAX: return new BigDecimal( \"99999999999999999999999999.999999999999\"); // the DECIMAL (BigDecimal) maximum value\n case UDF_TEST.RETURN_NaN: return Math.log(value.doubleValue()); // Return NaN\n case UDF_TEST.THROW_NullPointerException: return uninitialized.intValue(); // Throw a NullPointerException (NPE)\n case UDF_TEST.THROW_IllegalArgumentException: Character.toChars(intValue); // Throw an IllegalArgumentException\n case UDF_TEST.THROW_NumberFormatException: return new Byte(\"nonnumeric\"); // Throw a NumberFormatException\n case UDF_TEST.THROW_ArrayIndexOutOfBoundsException: return array[-1]; // Throw an ArrayIndexOutOfBoundsException\n case UDF_TEST.THROW_ClassCastException: return (Byte) value + (Short) value; // Throw a ClassCastException\n case UDF_TEST.THROW_ArithmeticException: return intValue / 0; // Throw an ArithmeticException (/ by zero)\n case UDF_TEST.THROW_UnsupportedOperationException: Arrays.asList(array).add(0); // Throw an UnsupportedOperationException\n case UDF_TEST.THROW_VoltTypeException: throw new VoltTypeException(\"Test UDF's that throw a VoltTypeException.\");\n case UDF_TEST.THROW_UserDefinedTestException: throw new UserDefinedTestException(\"Test UDF's that throw a user-defined (runtime) exception.\");\n default: return value;\n }\n }\n\n /** Usually just returns the input value; but certain special input values\n * (generally between -100 and -120) trigger an exception to be thrown,\n * or special VoltDB \"null\" values to be returned. When useTrueNullValue\n * is true, and the special input value -100 is given, a true Java null\n * is returned. */\n private Byte testExceptions(Byte value, boolean useTrueNullValue) {\n Number result = testExceptionsByValue(value, useTrueNullValue);\n return (result == null ? null : result.byteValue());\n }\n\n /** Usually just returns the input value; but certain special input values\n * (generally between -100 and -120) trigger an exception to be thrown,\n * or special VoltDB \"null\" values to be returned. */\n private Byte testExceptions(Byte value) {\n return testExceptions(value, false);\n }\n\n /** Usually just returns the input value; but certain special input values\n * (generally between -100 and -120) trigger an exception to be thrown,\n * or special VoltDB \"null\" values to be returned. */\n private Short testExceptions(Short value) {\n Number result = testExceptionsByValue(value);\n return (result == null ? null : result.shortValue());\n }\n\n /** Usually just returns the input value; but certain special input values\n * (generally between -100 and -120) trigger an exception to be thrown,\n * or special VoltDB \"null\" values to be returned. When useTrueNullValue\n * is true, and the special input value -100 is given, a true Java null\n * is returned. */\n private Integer testExceptions(Integer value, boolean useTrueNullValue) {\n Number result = testExceptionsByValue(value, useTrueNullValue);\n return (result == null ? null : result.intValue());\n }\n\n /** Usually just returns the input value; but certain special input values\n * (generally between -100 and -120) trigger an exception to be thrown,\n * or special VoltDB \"null\" values to be returned. */\n private Integer testExceptions(Integer value) {\n return testExceptions(value, false);\n }\n\n /** Usually just returns the input value; but certain special input values\n * (generally between -100 and -120) trigger an exception to be thrown,\n * or special VoltDB \"null\" values to be returned. */\n private Long testExceptions(Long value) {\n Number result = testExceptionsByValue(value);\n return (result == null ? null : result.longValue());\n }\n\n /** Usually just returns the input value; but certain special input values\n * (generally between -100 and -120) trigger an exception to be thrown,\n * or special VoltDB \"null\" values to be returned. When useTrueNullValue\n * is true, and the special input value -100 is given, a true Java null\n * is returned. */\n private Double testExceptions(Double value, boolean useTrueNullValue) {\n Number result = testExceptionsByValue(value, useTrueNullValue);\n return (result == null ? null : result.doubleValue());\n }\n\n /** Usually just returns the input value; but certain special input values\n * (generally between -100 and -120) trigger an exception to be thrown,\n * or special VoltDB \"null\" values to be returned. */\n private Double testExceptions(Double value) {\n return testExceptions(value, false);\n }\n\n /** Usually just returns the input value; but certain special input values\n * (generally between -100 and -120) trigger an exception to be thrown,\n * or special VoltDB \"null\" values to be returned. */\n private BigDecimal testExceptions(BigDecimal value) {\n Number n = testExceptionsByValue(value);\n if (n == null) {\n return null;\n } else if (n.getClass() == BigDecimal.class) {\n return (BigDecimal) n;\n } else if (n.getClass() == Integer.class) {\n return new BigDecimal (n.intValue());\n } else if (n.getClass() == Long.class) {\n return new BigDecimal (n.longValue());\n } else {\n return new BigDecimal (n.doubleValue());\n }\n }\n\n /** Usually just returns the input value; but certain special input (int)\n * values (generally between -100 and -120) trigger an exception to be\n * thrown, or special VoltDB \"null\" values to be returned. */\n private String testExceptions(String value) {\n if (value == null) {\n return null;\n }\n try {\n Integer intValue = testExceptions(Integer.parseInt(value), true);\n return (intValue == null ? null : intValue.toString());\n } catch (NumberFormatException e) {\n return value;\n }\n }\n\n /** Usually just returns the input value; but certain special values within\n * the input array (generally between -100 and -120) trigger an exception\n * to be thrown, or special VoltDB \"null\" values to be returned. */\n private byte[] testExceptions(byte[] value) {\n if (value == null) {\n return null;\n }\n byte[] result = new byte[value.length];\n for (int i=0; i < value.length; i++) {\n Byte test_i = testExceptions(value[i], true);\n if (test_i == null) {\n return null;\n } else {\n result[i] = test_i;\n }\n }\n return result;\n }\n\n /** Usually just returns the input value; but certain special values within\n * the input array (generally between -100 and -120) trigger an exception\n * to be thrown, or special VoltDB \"null\" values to be returned. */\n // TODO: I'm not certain whether Byte[] (as opposed to byte[]) is a valid\n // way to represent VARBINARY\n private Byte[] testExceptions(Byte[] value) {\n if (value == null) {\n return null;\n }\n Byte[] result = new Byte[value.length];\n for (int i=0; i < value.length; i++) {\n Byte test_i = testExceptions(value[i], true);\n if (test_i == null) {\n return null;\n } else {\n result[i] = test_i;\n }\n }\n return result;\n }\n\n /** Usually just returns the input value; but input values with certain\n * special years (generally between 1780 and 1800) trigger an exception\n * to be thrown, or special VoltDB \"null\" values to be returned. */\n private TimestampType testExceptions(TimestampType value) {\n if (value == null) {\n return null;\n }\n Date date = value.asExactJavaDate();\n Integer year = testExceptions(date.getYear(), true);\n if (year == null) {\n return null;\n }\n date.setYear(year);\n return new TimestampType(date);\n }\n\n /** Usually just returns the input value; but input values with certain\n * special years (generally between 1780 and 1800) trigger an exception\n * to be thrown, or special VoltDB \"null\" values to be returned. */\n private TimestampType testExceptions(Date value) {\n if (value == null) {\n return null;\n }\n return testExceptions(new TimestampType(value));\n }\n\n /** Usually just returns the input value; but input values with certain\n * special longitude values (generally between -100 and -120) trigger\n * an exception to be thrown, or special VoltDB \"null\" values to be\n * returned. */\n private GeographyPointValue testExceptions(GeographyPointValue value) {\n if (value == null) {\n return null;\n }\n // We don't bother to \"test\" Latitude, because it must be between -90\n // and 90, so it cannot have any of the \"interesting\" values, such as\n // -100, -101, etc.\n Double longitude = testExceptions(value.getLongitude(), true);\n return (longitude == null ? null : new GeographyPointValue(Math.min(180, Math.max(-180, longitude)), value.getLatitude() ) );\n }\n\n /** Usually just returns the input value; but input values with certain\n * special longitude values (generally between -100 and -120) trigger\n * an exception to be thrown, or special VoltDB \"null\" values to be\n * returned. */\n private GeographyValue testExceptions(GeographyValue value) {\n if (value == null) {\n return null;\n }\n // We \"test\" every GeographyPoint in the Geography (polygon), but again,\n // we don't bother to \"test\" Latitude, because it must be between -90\n // and 90, so it cannot have any of the \"interesting\" values, such as\n // -100, -101, etc.\n List> rings = value.getRings();\n for (int i=0; i < rings.size(); i++) {\n List ring = rings.get(i);\n for (int j=0; j < ring.size(); j++) {\n if (testExceptions(ring.get(j).getLongitude(), true) == null) {\n return null;\n }\n }\n }\n return value;\n }\n\n /** Private method called by the various test UDF's that involve addition\n * of two integers; note that there is no null checking. However, if\n * USE_ALTERNATIVE_VERSION is true, it subtracts, rather than adds, the\n * two integers. */\n private Long add(Long i, Long j) {\n if (USE_ALTERNATIVE_VERSION) {\n return i - j;\n }\n return i + j;\n }\n\n // More private methods, using various integer data types, that simply call\n // the method above, with the necessary conversions:\n private Byte add(Byte i, Byte j) {\n return add(i.longValue(), j.longValue()).byteValue();\n }\n private Short add(Short i, Short j) {\n return add(i.longValue(), j.longValue()).shortValue();\n }\n private Integer add(Integer i, Integer j) {\n return add(i.longValue(), j.longValue()).intValue();\n }\n\n /** Private method called by the various test UDF's that involve addition\n * of two (Double) numbers; note that there is no null checking. However,\n * if USE_ALTERNATIVE_VERSION is true, it subtracts, rather than adds, the\n * two integers. */\n private Double add(Double x, Double y) {\n if (USE_ALTERNATIVE_VERSION) {\n return x - y;\n }\n return x + y;\n }\n\n /** Private method called by the test UDF that involves addition of two\n * (BigDecimal) numbers; note that there is no null checking. However,\n * if USE_ALTERNATIVE_VERSION is true, it subtracts, rather than adds,\n * the two integers. */\n private BigDecimal add(BigDecimal x, BigDecimal y) {\n if (USE_ALTERNATIVE_VERSION) {\n return x.subtract(y);\n }\n return x.add(y);\n }\n\n /** Private method called by the test UDF that involves \"addition\" of a\n * GeographyPointValue to a GeographyValue; note that there is no null\n * checking. However, if USE_ALTERNATIVE_VERSION is true, it \"subtracts\",\n * rather than \"adds\", the GeographyPointValue. */\n private GeographyValue add(GeographyValue g, GeographyPointValue p) {\n if (USE_ALTERNATIVE_VERSION) {\n GeographyPointValue p2 = new GeographyPointValue(0.0 - p.getLongitude(),\n 0.0 - p.getLatitude());\n return g.add(p2);\n }\n return g.add(p);\n }\n\n /** Private method called by the various test UDF's that involve\n * concatenation of two or more strings. However, if\n * USE_ALTERNATIVE_VERSION is true, it concatenates them in\n * reverse order. */\n private String concatenate(String... s) {\n if (s == null) {\n return null;\n }\n StringBuffer result = new StringBuffer();\n int len = s.length;\n for (int i=0; i < len; i++) {\n if (s[i] == null) {\n return null;\n }\n if (USE_ALTERNATIVE_VERSION) {\n result.append(s[len-1 - i]);\n } else {\n result.append(s[i]);\n }\n }\n return result.toString();\n }\n\n\n // Test UDF's (user-defined functions) that can be used to test UDF's that\n // throw various exceptions, or return various null values (including the\n // various numerical VoltDB null values, like -128 and -32768), when certain\n // special input values (generally between -100 and -120) are used; most\n // of these simply add or concatenate two input values:\n\n\n /** Simple test UDF (user-defined function) that adds two TINYINT\n * (primitive, or unboxed, byte) values; except, certain special input\n * values (generally between -100 and -120) trigger an exception to be\n * thrown, or special VoltDB \"null\" values to be used. */\n public byte add2Tinyint(byte i, byte j) {\n if (i == VoltType.NULL_TINYINT || j == VoltType.NULL_TINYINT) {\n return VoltType.NULL_TINYINT;\n }\n return (byte) add(testExceptions(i), testExceptions(j));\n }\n\n /** Simple test UDF (user-defined function) that adds two TINYINT\n * (boxed Byte) values; except, certain special input values (generally\n * between -100 and -120) trigger an exception to be thrown, or special\n * VoltDB \"null\" values to be used. */\n public Byte add2TinyintBoxed(Byte i, Byte j) {\n Byte test_i = testExceptions(i);\n Byte test_j = testExceptions(j);\n if (test_i == null || test_j == null || test_i.equals(VoltType.NULL_TINYINT)\n || test_j.equals(VoltType.NULL_TINYINT)) {\n return null;\n }\n return (byte) add(test_i, test_j);\n }\n\n /** Simple test UDF (user-defined function) that adds two SMALLINT\n * (primitive, or unboxed, short) values; except, certain special input\n * values (generally between -100 and -120) trigger an exception to be\n * thrown, or special VoltDB \"null\" values to be used. */\n public short add2Smallint(short i, short j) {\n if (i == VoltType.NULL_SMALLINT || j == VoltType.NULL_SMALLINT) {\n return VoltType.NULL_SMALLINT;\n }\n return (short) add(testExceptions(i), testExceptions(j));\n }\n\n /** Simple test UDF (user-defined function) that adds two SMALLINT\n * (boxed Short) values; except, certain special input values (generally\n * between -100 and -120) trigger an exception to be thrown, or special\n * VoltDB \"null\" values to be used. */\n public Short add2SmallintBoxed(Short i, Short j) {\n Short test_i = testExceptions(i);\n Short test_j = testExceptions(j);\n if (test_i == null || test_j == null || test_i.equals(VoltType.NULL_SMALLINT)\n || test_j.equals(VoltType.NULL_SMALLINT)) {\n return null;\n }\n return (short) add(test_i, test_j);\n }\n\n /** Simple test UDF (user-defined function) that adds two INTEGER\n * (primitive, or unboxed, int) values; except, certain special input\n * values (generally between -100 and -120) trigger an exception to be\n * thrown, or special VoltDB \"null\" values to be used. */\n public int add2Integer(int i, int j) {\n if (i == VoltType.NULL_INTEGER || j == VoltType.NULL_INTEGER) {\n return VoltType.NULL_INTEGER;\n }\n return add(testExceptions(i), testExceptions(j));\n }\n\n /** Simple test UDF (user-defined function) that adds two INTEGER\n * (boxed Integer) values; except, certain special input values (generally\n * between -100 and -120) trigger an exception to be thrown, or special\n * VoltDB \"null\" values to be used. */\n public Integer add2IntegerBoxed(Integer i, Integer j) {\n Integer test_i = testExceptions(i);\n Integer test_j = testExceptions(j);\n if (test_i == null || test_j == null || test_i.equals(VoltType.NULL_INTEGER)\n || test_j.equals(VoltType.NULL_INTEGER)) {\n return null;\n }\n return add(test_i, test_j);\n }\n\n /** Simple test UDF (user-defined function) that adds two BIGINT\n * (primitive, or unboxed, long) values; except, certain special input\n * values (generally between -100 and -120) trigger an exception to be\n * thrown, or special VoltDB \"null\" values to be used. */\n public long add2Bigint(long i, long j) {\n if (i == VoltType.NULL_BIGINT || j == VoltType.NULL_BIGINT) {\n return VoltType.NULL_BIGINT;\n }\n return add(testExceptions(i), testExceptions(j));\n }\n\n /** Simple test UDF (user-defined function) that adds two BIGINT\n * (boxed Long) values; except, certain special input values (generally\n * between -100 and -120) trigger an exception to be thrown, or special\n * VoltDB \"null\" values to be used. */\n public Long add2BigintBoxed(Long i, Long j) {\n Long test_i = testExceptions(i);\n Long test_j = testExceptions(j);\n if (test_i == null || test_j == null || test_i.equals(VoltType.NULL_BIGINT)\n || test_j.equals(VoltType.NULL_BIGINT)) {\n return null;\n }\n return add(test_i, test_j);\n }\n\n /** Simple test UDF (user-defined function) that adds two FLOAT\n * (primitive, or unboxed, double) values; except, certain special input\n * values (generally between -100 and -120) trigger an exception to be\n * thrown, or special VoltDB \"null\" values to be used. */\n public double add2Float(double x, double y) {\n if (x <= VoltType.NULL_FLOAT || y <= VoltType.NULL_FLOAT) {\n return VoltType.NULL_FLOAT;\n }\n return add(testExceptions(x), testExceptions(y));\n }\n\n /** Simple test UDF (user-defined function) that adds two FLOAT\n * (boxed Double) values; except, certain special input values (generally\n * between -100 and -120) trigger an exception to be thrown, or special\n * VoltDB \"null\" values to be used. */\n public Double add2FloatBoxed(Double x, Double y) {\n Double test_x = testExceptions(x);\n Double test_y = testExceptions(y);\n if (test_x == null || test_y == null || test_x <= VoltType.NULL_FLOAT\n || test_y <= VoltType.NULL_FLOAT) {\n return null;\n }\n return add(test_x, test_y);\n }\n\n /** Simple test UDF (user-defined function) that adds two DECIMAL\n * (BigDecimal) values; except, certain special input values (generally\n * between -100 and -120) trigger an exception to be thrown, or special\n * VoltDB \"null\" values to be used. */\n public BigDecimal add2Decimal(BigDecimal x, BigDecimal y) {\n BigDecimal test_x = testExceptions(x);\n BigDecimal test_y = testExceptions(y);\n if (test_x == null || test_y == null) {\n return null;\n }\n return add(test_x, test_y);\n }\n\n /** Simple test UDF (user-defined function) that concatenates two VARCHAR\n * (String) values; except, certain special input (int) values (generally\n * between -100 and -120) trigger an exception to be thrown, or special\n * VoltDB \"null\" values to be used. */\n public String add2Varchar(String s, String t) {\n return concatenate(testExceptions(s), testExceptions(t));\n }\n\n /** Simple test UDF (user-defined function) that \"adds\" two VARBINARY\n * (primitive, or unboxed, byte array) values; that is, it adds each byte\n * value in the two arrays; except, certain special input values (generally\n * between -100 and -120) trigger an exception to be thrown, or special\n * VoltDB \"null\" values to be used. */\n public byte[] add2Varbinary(byte[] a, byte[] b) {\n byte[] test_a = testExceptions(a);\n byte[] test_b = testExceptions(b);\n if (test_a == null || test_b == null) {\n return null;\n }\n int length = Math.max(a.length, b.length);\n byte[] result = new byte[length];\n for (int i=0; i < length; i++) {\n result[i] = (byte) add( (i < a.length ? test_a[i] : 0),\n (i < b.length ? test_b[i] : 0) );\n }\n return result;\n }\n\n /** Simple test UDF (user-defined function) that adds two VARBINARY\n * (boxed Byte array) values; that is, it adds each byte value in the\n * two arrays; except, certain special input values (generally between\n * -100 and -120) trigger an exception to be thrown, or special VoltDB\n * \"null\" values to be used. */\n // TODO: I'm not certain whether Byte[] (as opposed to byte[]) is a valid\n // way to represent VARBINARY\n public Byte[] add2VarbinaryBoxed(Byte[] a, Byte[] b) {\n Byte[] test_a = testExceptions(a);\n Byte[] test_b = testExceptions(b);\n if (test_a == null || test_b == null) {\n return null;\n }\n int length = Math.max(a.length, b.length);\n Byte[] result = new Byte[length];\n for (int i=0; i < length; i++) {\n result[i] = (byte) add( (i < a.length ? test_a[i] : 0),\n (i < b.length ? test_b[i] : 0) );\n }\n return result;\n }\n\n /** Simple test UDF (user-defined function) that adds a specified number\n * of years to a (VoltDB) Timestamp value; except, certain special input\n * year values (generally between 1780 and 1800) trigger an exception to\n * be thrown, or special VoltDB \"null\" values to be used. */\n public TimestampType addYearsToTimestamp(TimestampType t, Integer numYears) {\n TimestampType t2 = testExceptions(t);\n if (t2 == null || numYears == null) {\n return null;\n }\n Date d = t2.asExactJavaDate();\n d.setYear(add(d.getYear(), numYears));\n return new TimestampType(d);\n }\n\n /** A convenience method, allowing the above method to be called using a Date\n * value, and it will construct a (VoltDB) Timestamp value to be used. */\n private TimestampType addYearsToTimestamp(Date d, int numYears) {\n return addYearsToTimestamp(new TimestampType(d), numYears);\n }\n\n /** Simple test UDF (user-defined function) that \"adds\" two (VoltDB)\n * GeographyPoint values; that is, it adds their longitudes and latitudes;\n * except, certain special longitude input values (generally between -100\n * and -120) trigger an exception to be thrown, or special VoltDB \"null\"\n * values to be used. */\n public GeographyPointValue add2GeographyPoint(GeographyPointValue p, GeographyPointValue q) {\n if (p == null || q == null) {\n return null;\n }\n // We don't bother to \"test\" Latitude, because it must be between -90\n // and 90, so it cannot have any of the \"interesting\" values, such as\n // -101, -102, etc.\n Double p_long = testExceptions(p.getLongitude(), true);\n Double q_long = testExceptions(q.getLongitude(), true);\n if (p_long == null || q_long == null) {\n return null;\n }\n return new GeographyPointValue( Math.min(180, Math.max(-180, add(p_long, q_long))), add(p.getLatitude(), q.getLatitude()) );\n }\n\n /** Simple test UDF (user-defined function) that \"adds\" a (VoltDB)\n * GeographyPoint to a (VoltDB) Geography; that is, it adds the\n * GeographyPoint's longitude and latitude to each vertex of the\n * Geography; except, certain special longitude input values (generally\n * between -100 and -120) trigger an exception to be thrown, or special\n * VoltDB \"null\" values to be used. */\n public GeographyValue addGeographyPointToGeography(GeographyValue g, GeographyPointValue p) {\n GeographyValue g2 = testExceptions(g);\n if (g2 == null || p == null) {\n return null;\n }\n return add(g2, p);\n }\n\n\n // Test UDF's (user-defined functions) that are similar to (some of) the\n // above UDF's, but without null checking, so slightly odd things can happen,\n // such as null plus one equals a number\n\n /** Simple test UDF (user-defined function) that adds two TINYINT\n * (primitive, or unboxed, byte) values; except, certain special input\n * values (generally between -100 and -120) trigger an exception to be\n * thrown, or special VoltDB \"null\" values to be used; but this version\n * has no null checking. */\n public byte add2TinyintWithoutNullCheck(byte i, byte j) {\n return (byte) add(testExceptions(i), testExceptions(j));\n }\n /** Simple test UDF (user-defined function) that adds two TINYINT\n * (boxed Byte) values; except, certain special input values (generally\n * between -100 and -120) trigger an exception to be thrown, or special\n * VoltDB \"null\" values to be used; but this version has no null\n * checking. */\n public Byte add2TinyintBoxedWithoutNullCheck(Byte i, Byte j) {\n return (byte) add(testExceptions(i), testExceptions(j));\n }\n /** Simple test UDF (user-defined function) that adds two SMALLINT\n * (primitive, or unboxed, short) values; except, certain special input\n * values (generally between -100 and -120) trigger an exception to be\n * thrown, or special VoltDB \"null\" values to be used; but this version\n * has no null checking. */\n public short add2SmallintWithoutNullCheck(short i, short j) {", "answers": [" return (short) add(testExceptions(i), testExceptions(j));"], "length": 4214, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "8ab790e5-73b8-442a-84e9-13cfd38a7041", "reasoning": "The method add2SmallintWithoutNullCheck mirrors the earlier without‑null‑check methods. It should simply return the result of adding the two short inputs after passing them through testExceptions, casting the Long result to short. Hence the next line is the return statement with the appropriate cast.", "reasoning_model_answer": "return (short) add(testExceptions(i), testExceptions(j));", "assistant_with_reasoning": "\nThe method add2SmallintWithoutNullCheck mirrors the earlier without‑null‑check methods. It should simply return the result of adding the two short inputs after passing them through testExceptions, casting the Long result to short. Hence the next line is the return statement with the appropriate cast.\n\nreturn (short) add(testExceptions(i), testExceptions(j));", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.679, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 34102, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "return (short) add(testExceptions(i), testExceptions(j));", "score": 0.93, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/*! ******************************************************************************\n *\n * Pentaho Data Integration\n *\n * Copyright (C) 2002-2016 by Pentaho : http://www.pentaho.com\n *\n *******************************************************************************\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n ******************************************************************************/\n\npackage org.pentaho.di.trans.steps.valuemapper;\n\nimport java.util.ArrayList;\nimport java.util.Iterator;\nimport java.util.List;\n\nimport org.pentaho.di.core.KettleEnvironment;\nimport org.pentaho.di.core.RowMetaAndData;\nimport org.pentaho.di.core.exception.KettleException;\nimport org.pentaho.di.core.exception.KettleValueException;\nimport org.pentaho.di.core.plugins.PluginRegistry;\nimport org.pentaho.di.core.plugins.StepPluginType;\nimport org.pentaho.di.core.row.RowMeta;\nimport org.pentaho.di.core.row.RowMetaInterface;\nimport org.pentaho.di.core.row.ValueMetaInterface;\nimport org.pentaho.di.core.row.value.ValueMetaString;\nimport org.pentaho.di.trans.RowProducer;\nimport org.pentaho.di.trans.RowStepCollector;\nimport org.pentaho.di.trans.Trans;\nimport org.pentaho.di.trans.TransHopMeta;\nimport org.pentaho.di.trans.TransMeta;\nimport org.pentaho.di.trans.step.StepInterface;\nimport org.pentaho.di.trans.step.StepMeta;\nimport org.pentaho.di.trans.steps.dummytrans.DummyTransMeta;\nimport org.pentaho.di.trans.steps.injector.InjectorMeta;\n\nimport junit.framework.TestCase;\n\n/**\n * Test class for the ValueMapper step.\n *\n * @author Sven Boden\n */\npublic class ValueMapperIT extends TestCase {\n public RowMetaInterface createRowMetaInterface() {\n RowMetaInterface rm = new RowMeta();\n\n ValueMetaInterface[] valuesMeta = { new ValueMetaString( \"field1\" ), };\n\n for ( int i = 0; i < valuesMeta.length; i++ ) {\n rm.addValueMeta( valuesMeta[i] );\n }\n\n return rm;\n }\n\n public List createData() {\n List list = new ArrayList();\n\n RowMetaInterface rm = createRowMetaInterface();\n\n Object[] r1 = new Object[] { \"abc\" };\n Object[] r2 = new Object[] { \"ABC\" };\n Object[] r3 = new Object[] { \"def\" };\n Object[] r4 = new Object[] { \"def\" };\n Object[] r5 = new Object[] { \"ghij\" };\n Object[] r6 = new Object[] { \"zzz\" };\n Object[] r7 = new Object[] { \"\" };\n Object[] r8 = new Object[] { null };\n Object[] r9 = new Object[] { \"abc\" };\n\n list.add( new RowMetaAndData( rm, r1 ) );\n list.add( new RowMetaAndData( rm, r2 ) );\n list.add( new RowMetaAndData( rm, r3 ) );\n list.add( new RowMetaAndData( rm, r4 ) );\n list.add( new RowMetaAndData( rm, r5 ) );\n list.add( new RowMetaAndData( rm, r6 ) );\n list.add( new RowMetaAndData( rm, r7 ) );\n list.add( new RowMetaAndData( rm, r8 ) );\n list.add( new RowMetaAndData( rm, r9 ) );\n\n return list;\n }\n\n /**\n * Create the meta data for the results of test case 1.\n */\n public RowMetaInterface createRowMetaInterface1() {\n RowMetaInterface rm = new RowMeta();\n\n ValueMetaInterface[] valuesMeta =\n { new ValueMetaString( \"field1\" ), new ValueMetaString( \"new_field\" ), };\n\n for ( int i = 0; i < valuesMeta.length; i++ ) {\n rm.addValueMeta( valuesMeta[i] );\n }\n\n return rm;\n }\n\n /**\n * Create result data for test case 1.\n */\n public List createResultData1() {\n List list = new ArrayList();\n\n RowMetaInterface rm = createRowMetaInterface1();\n\n Object[] r1 = new Object[] { \"abc\", \"begin\" };\n Object[] r2 = new Object[] { \"ABC\", \"BEG_LONGER\" };\n Object[] r3 = new Object[] { \"def\", \"test\" };\n Object[] r4 = new Object[] { \"def\", \"test\" };\n Object[] r5 = new Object[] { \"ghij\", null };\n Object[] r6 = new Object[] { \"zzz\", null };\n Object[] r7 = new Object[] { \"\", null };\n Object[] r8 = new Object[] { null, null };\n Object[] r9 = new Object[] { \"abc\", \"begin\" };\n\n list.add( new RowMetaAndData( rm, r1 ) );\n list.add( new RowMetaAndData( rm, r2 ) );\n list.add( new RowMetaAndData( rm, r3 ) );\n list.add( new RowMetaAndData( rm, r4 ) );\n list.add( new RowMetaAndData( rm, r5 ) );\n list.add( new RowMetaAndData( rm, r6 ) );\n list.add( new RowMetaAndData( rm, r7 ) );\n list.add( new RowMetaAndData( rm, r8 ) );\n list.add( new RowMetaAndData( rm, r9 ) );\n\n return list;\n }\n\n /**\n * Create result data for test case 2.\n */\n public List createResultData2() {\n List list = new ArrayList();\n\n RowMetaInterface rm = createRowMetaInterface();\n\n Object[] r1 = new Object[] { \"begin\" };\n Object[] r2 = new Object[] { \"BEG_LONGER\" };\n Object[] r3 = new Object[] { \"test\" };\n Object[] r4 = new Object[] { \"test\" };\n Object[] r5 = new Object[] { null };\n Object[] r6 = new Object[] { \"zzz\" };\n Object[] r7 = new Object[] { null };\n Object[] r8 = new Object[] { null };\n Object[] r9 = new Object[] { \"begin\" };\n\n list.add( new RowMetaAndData( rm, r1 ) );\n list.add( new RowMetaAndData( rm, r2 ) );\n list.add( new RowMetaAndData( rm, r3 ) );\n list.add( new RowMetaAndData( rm, r4 ) );\n list.add( new RowMetaAndData( rm, r5 ) );\n list.add( new RowMetaAndData( rm, r6 ) );\n list.add( new RowMetaAndData( rm, r7 ) );\n list.add( new RowMetaAndData( rm, r8 ) );\n list.add( new RowMetaAndData( rm, r9 ) );\n\n return list;\n }\n\n /**\n * Create result data for test case 3.\n */\n public List createResultData3() {\n List list = new ArrayList();\n\n RowMetaInterface rm = createRowMetaInterface();\n\n Object[] r1 = new Object[] { \"begin\" };\n Object[] r2 = new Object[] { \"BEG_LONGER\" };\n Object[] r3 = new Object[] { \"test\" };\n Object[] r4 = new Object[] { \"test\" };\n Object[] r5 = new Object[] { null };\n Object[] r6 = new Object[] { \"zzz\" };\n Object[] r7 = new Object[] { \"emptyField\" };\n Object[] r8 = new Object[] { \"emptyField\" };\n Object[] r9 = new Object[] { \"begin\" };\n\n list.add( new RowMetaAndData( rm, r1 ) );\n list.add( new RowMetaAndData( rm, r2 ) );\n list.add( new RowMetaAndData( rm, r3 ) );\n list.add( new RowMetaAndData( rm, r4 ) );\n list.add( new RowMetaAndData( rm, r5 ) );\n list.add( new RowMetaAndData( rm, r6 ) );\n list.add( new RowMetaAndData( rm, r7 ) );\n list.add( new RowMetaAndData( rm, r8 ) );\n list.add( new RowMetaAndData( rm, r9 ) );\n\n return list;\n }\n\n /**\n * Create result data for test case 4.\n */\n public List createResultData4() {\n List list = new ArrayList();\n\n RowMetaInterface rm = createRowMetaInterface1();\n\n Object[] r1 = new Object[] { \"abc\", \"begin\" };\n Object[] r2 = new Object[] { \"ABC\", \"BEG_LONGER\" };\n Object[] r3 = new Object[] { \"def\", \"test\" };\n Object[] r4 = new Object[] { \"def\", \"test\" };\n Object[] r5 = new Object[] { \"ghij\", null };\n Object[] r6 = new Object[] { \"zzz\", \"default\" };\n Object[] r7 = new Object[] { \"\", null };\n Object[] r8 = new Object[] { null, null };\n Object[] r9 = new Object[] { \"abc\", \"begin\" };\n\n list.add( new RowMetaAndData( rm, r1 ) );\n list.add( new RowMetaAndData( rm, r2 ) );\n list.add( new RowMetaAndData( rm, r3 ) );\n list.add( new RowMetaAndData( rm, r4 ) );\n list.add( new RowMetaAndData( rm, r5 ) );\n list.add( new RowMetaAndData( rm, r6 ) );\n list.add( new RowMetaAndData( rm, r7 ) );\n list.add( new RowMetaAndData( rm, r8 ) );\n list.add( new RowMetaAndData( rm, r9 ) );\n\n return list;\n }\n\n /**\n * Create result data for test case 5.\n */\n public List createResultData5() {\n List list = new ArrayList();\n\n RowMetaInterface rm = createRowMetaInterface();\n\n Object[] r1 = new Object[] { \"begin\" };\n Object[] r2 = new Object[] { \"BEG_LONGER\" };\n Object[] r3 = new Object[] { \"test\" };\n Object[] r4 = new Object[] { \"test\" };\n Object[] r5 = new Object[] { null };\n Object[] r6 = new Object[] { \"default\" };\n Object[] r7 = new Object[] { null };\n Object[] r8 = new Object[] { null };\n Object[] r9 = new Object[] { \"begin\" };\n\n list.add( new RowMetaAndData( rm, r1 ) );\n list.add( new RowMetaAndData( rm, r2 ) );\n list.add( new RowMetaAndData( rm, r3 ) );\n list.add( new RowMetaAndData( rm, r4 ) );\n list.add( new RowMetaAndData( rm, r5 ) );\n list.add( new RowMetaAndData( rm, r6 ) );\n list.add( new RowMetaAndData( rm, r7 ) );\n list.add( new RowMetaAndData( rm, r8 ) );\n list.add( new RowMetaAndData( rm, r9 ) );\n\n return list;\n }\n\n /**\n * Create result data for test case 6.\n */\n public List createResultData6() {\n List list = new ArrayList();\n\n RowMetaInterface rm = createRowMetaInterface();\n\n Object[] r1 = new Object[] { \"begin\" };\n Object[] r2 = new Object[] { \"BEG_LONGER\" };\n Object[] r3 = new Object[] { \"test\" };\n Object[] r4 = new Object[] { \"test\" };\n Object[] r5 = new Object[] { \"default\" };\n Object[] r6 = new Object[] { \"default\" };\n Object[] r7 = new Object[] { \"emptyField\" };\n Object[] r8 = new Object[] { \"emptyField\" };\n Object[] r9 = new Object[] { \"begin\" };\n\n list.add( new RowMetaAndData( rm, r1 ) );\n list.add( new RowMetaAndData( rm, r2 ) );\n list.add( new RowMetaAndData( rm, r3 ) );\n list.add( new RowMetaAndData( rm, r4 ) );\n list.add( new RowMetaAndData( rm, r5 ) );\n list.add( new RowMetaAndData( rm, r6 ) );\n list.add( new RowMetaAndData( rm, r7 ) );\n list.add( new RowMetaAndData( rm, r8 ) );\n list.add( new RowMetaAndData( rm, r9 ) );\n\n return list;\n }\n\n /**\n * Check the 2 lists comparing the rows in order. If they are not the same fail the test.\n */\n public void checkRows( List rows1, List rows2 ) {\n int idx = 1;\n if ( rows1.size() != rows2.size() ) {\n fail( \"Number of rows is not the same: \" + rows1.size() + \" and \" + rows2.size() );\n }\n Iterator it1 = rows1.iterator();\n Iterator it2 = rows2.iterator();\n\n while ( it1.hasNext() && it2.hasNext() ) {\n RowMetaAndData rm1 = it1.next();\n RowMetaAndData rm2 = it2.next();\n\n Object[] r1 = rm1.getData();\n Object[] r2 = rm2.getData();\n\n if ( rm1.size() != rm2.size() ) {\n fail( \"row nr \" + idx + \" is not equal\" );\n }\n int[] fields = new int[r1.length];\n for ( int ydx = 0; ydx < r1.length; ydx++ ) {\n fields[ydx] = ydx;\n }\n try {\n if ( rm1.getRowMeta().compare( r1, r2, fields ) != 0 ) {\n fail( \"row nr \" + idx + \" is not equal\" );\n }\n } catch ( KettleValueException e ) {\n fail( \"row nr \" + idx + \" is not equal\" );\n }\n\n idx++;\n }\n }\n\n /**\n * Test case for valuemapper step. Injector step to a valuemapper step to a dummy step. Rows go in and should be\n * mapped accordingly.\n *\n * This test will write the mappings in a new field.\n */\n public void testValueMapper1() throws Exception {\n KettleEnvironment.init();\n\n //\n // Create a new transformation...\n //\n TransMeta transMeta = new TransMeta();\n transMeta.setName( \"valuemappertest1\" );\n\n PluginRegistry registry = PluginRegistry.getInstance();\n\n //\n // create an injector step...\n //\n String injectorStepname = \"injector step\";\n InjectorMeta im = new InjectorMeta();\n\n // Set the information of the injector.\n String injectorPid = registry.getPluginId( StepPluginType.class, im );\n StepMeta injectorStep = new StepMeta( injectorPid, injectorStepname, im );\n transMeta.addStep( injectorStep );\n\n //\n // Create a dummy step 1\n //\n String dummyStepname1 = \"dummy step 1\";\n DummyTransMeta dm1 = new DummyTransMeta();\n\n String dummyPid1 = registry.getPluginId( StepPluginType.class, dm1 );\n StepMeta dummyStep1 = new StepMeta( dummyPid1, dummyStepname1, dm1 );\n transMeta.addStep( dummyStep1 );\n\n TransHopMeta hi = new TransHopMeta( injectorStep, dummyStep1 );\n transMeta.addTransHop( hi );\n\n //\n // Create a ValueMapper step\n //\n String valueMapperName = \"valuemapper step\";\n ValueMapperMeta vm = new ValueMapperMeta();\n\n vm.setFieldToUse( \"field1\" );\n vm.setTargetField( \"new_field\" );\n vm.setSourceValue( new String[] { \"abc\", \"ABC\", \"def\", \"ghij\" } );\n vm.setTargetValue( new String[] { \"begin\", \"BEG_LONGER\", \"test\", \"\" } );\n\n String valueMapperPid = registry.getPluginId( StepPluginType.class, vm );\n StepMeta valueMapperStep = new StepMeta( valueMapperPid, valueMapperName, vm );\n transMeta.addStep( valueMapperStep );\n\n TransHopMeta hi2 = new TransHopMeta( dummyStep1, valueMapperStep );\n transMeta.addTransHop( hi2 );\n\n //\n // Create a dummy step 2\n //\n String dummyStepname2 = \"dummy step 2\";\n DummyTransMeta dm2 = new DummyTransMeta();\n\n String dummyPid2 = registry.getPluginId( StepPluginType.class, dm2 );\n StepMeta dummyStep2 = new StepMeta( dummyPid2, dummyStepname2, dm2 );\n transMeta.addStep( dummyStep2 );\n\n TransHopMeta hi3 = new TransHopMeta( valueMapperStep, dummyStep2 );\n transMeta.addTransHop( hi3 );\n\n // Now execute the transformation...\n Trans trans = new Trans( transMeta );\n\n trans.prepareExecution( null );\n\n StepInterface si = trans.getStepInterface( dummyStepname1, 0 );\n RowStepCollector dummyRc1 = new RowStepCollector();\n si.addRowListener( dummyRc1 );\n\n si = trans.getStepInterface( valueMapperName, 0 );\n RowStepCollector valueMapperRc = new RowStepCollector();\n si.addRowListener( valueMapperRc );\n\n si = trans.getStepInterface( dummyStepname2, 0 );\n RowStepCollector dummyRc = new RowStepCollector();\n si.addRowListener( dummyRc );\n\n RowProducer rp = trans.addRowProducer( injectorStepname, 0 );\n trans.startThreads();\n\n // add rows\n List inputList = createData();\n Iterator it = inputList.iterator();\n while ( it.hasNext() ) {\n RowMetaAndData rm = it.next();\n rp.putRow( rm.getRowMeta(), rm.getData() );\n }\n rp.finished();\n\n trans.waitUntilFinished();\n\n // Compare the results\n List resultRows = dummyRc.getRowsWritten();\n List goldenImageRows = createResultData1();\n\n checkRows( goldenImageRows, resultRows );\n }\n\n /**\n * Test case for valuemapper step. Injector step to a valuemapper step to a dummy step. Rows go in and should be\n * mapped accordingly.\n *\n * This test will write the mappings in the same field.\n */\n public void testValueMapper2() throws Exception {\n KettleEnvironment.init();\n\n //\n // Create a new transformation...\n //\n TransMeta transMeta = new TransMeta();\n transMeta.setName( \"valuemappertest2\" );\n\n PluginRegistry registry = PluginRegistry.getInstance();\n\n //\n // create an injector step...\n //\n String injectorStepname = \"injector step\";\n InjectorMeta im = new InjectorMeta();\n\n // Set the information of the injector.\n String injectorPid = registry.getPluginId( StepPluginType.class, im );\n StepMeta injectorStep = new StepMeta( injectorPid, injectorStepname, im );\n transMeta.addStep( injectorStep );\n\n //\n // Create a dummy step 1\n //\n String dummyStepname1 = \"dummy step 1\";\n DummyTransMeta dm1 = new DummyTransMeta();\n\n String dummyPid1 = registry.getPluginId( StepPluginType.class, dm1 );\n StepMeta dummyStep1 = new StepMeta( dummyPid1, dummyStepname1, dm1 );\n transMeta.addStep( dummyStep1 );\n\n TransHopMeta hi = new TransHopMeta( injectorStep, dummyStep1 );\n transMeta.addTransHop( hi );\n\n //\n // Create a step\n //\n String valueMapperName = \"valuemapper step\";\n ValueMapperMeta vm = new ValueMapperMeta();\n\n vm.setFieldToUse( \"field1\" );\n vm.setTargetField( \"\" );\n vm.setSourceValue( new String[] { \"abc\", \"ABC\", \"def\", \"ghij\" } );\n vm.setTargetValue( new String[] { \"begin\", \"BEG_LONGER\", \"test\", \"\" } );\n\n String valueMapperPid = registry.getPluginId( StepPluginType.class, vm );\n StepMeta valueMapperStep = new StepMeta( valueMapperPid, valueMapperName, vm );\n transMeta.addStep( valueMapperStep );\n\n TransHopMeta hi2 = new TransHopMeta( dummyStep1, valueMapperStep );\n transMeta.addTransHop( hi2 );\n\n //\n // Create a dummy step 2\n //\n String dummyStepname2 = \"dummy step 2\";\n DummyTransMeta dm2 = new DummyTransMeta();\n\n String dummyPid2 = registry.getPluginId( StepPluginType.class, dm2 );\n StepMeta dummyStep2 = new StepMeta( dummyPid2, dummyStepname2, dm2 );\n transMeta.addStep( dummyStep2 );\n\n TransHopMeta hi3 = new TransHopMeta( valueMapperStep, dummyStep2 );\n transMeta.addTransHop( hi3 );\n\n // Now execute the transformation...\n Trans trans = new Trans( transMeta );\n\n trans.prepareExecution( null );\n\n StepInterface si = trans.getStepInterface( dummyStepname1, 0 );\n RowStepCollector dummyRc1 = new RowStepCollector();\n si.addRowListener( dummyRc1 );\n\n si = trans.getStepInterface( valueMapperName, 0 );\n RowStepCollector valueMapperRc = new RowStepCollector();\n si.addRowListener( valueMapperRc );\n\n si = trans.getStepInterface( dummyStepname2, 0 );\n RowStepCollector dummyRc = new RowStepCollector();\n si.addRowListener( dummyRc );\n\n RowProducer rp = trans.addRowProducer( injectorStepname, 0 );\n trans.startThreads();\n\n // add rows\n List inputList = createData();\n Iterator it = inputList.iterator();\n while ( it.hasNext() ) {\n RowMetaAndData rm = it.next();\n rp.putRow( rm.getRowMeta(), rm.getData() );\n }\n rp.finished();\n\n trans.waitUntilFinished();\n\n // Compare the results\n List resultRows = dummyRc.getRowsWritten();\n List goldenImageRows = createResultData2();\n\n checkRows( goldenImageRows, resultRows );\n }\n\n /**\n * Test case for valuemapper step. Injector step to a valuemapper step to a dummy step. Rows go in and should be\n * mapped accordingly.\n *\n * This test will explicitly test the empty field processing.\n */\n public void testValueMapper3() throws Exception {\n KettleEnvironment.init();\n\n //\n // Create a new transformation...\n //\n TransMeta transMeta = new TransMeta();\n transMeta.setName( \"valuemappertest3\" );\n\n PluginRegistry registry = PluginRegistry.getInstance();\n\n //\n // create an injector step...\n //\n String injectorStepname = \"injector step\";\n InjectorMeta im = new InjectorMeta();\n\n // Set the information of the injector.\n String injectorPid = registry.getPluginId( StepPluginType.class, im );\n StepMeta injectorStep = new StepMeta( injectorPid, injectorStepname, im );\n transMeta.addStep( injectorStep );\n\n //\n // Create a dummy step 1\n //\n String dummyStepname1 = \"dummy step 1\";\n DummyTransMeta dm1 = new DummyTransMeta();\n\n String dummyPid1 = registry.getPluginId( StepPluginType.class, dm1 );\n StepMeta dummyStep1 = new StepMeta( dummyPid1, dummyStepname1, dm1 );\n transMeta.addStep( dummyStep1 );\n\n TransHopMeta hi = new TransHopMeta( injectorStep, dummyStep1 );\n transMeta.addTransHop( hi );\n\n //\n // Create a step\n //\n String valueMapperName = \"valuemapper step\";\n ValueMapperMeta vm = new ValueMapperMeta();\n\n vm.setFieldToUse( \"field1\" );\n vm.setTargetField( \"\" );\n vm.setSourceValue( new String[] { \"abc\", \"ABC\", \"def\", \"ghij\", null } );\n vm.setTargetValue( new String[] { \"begin\", \"BEG_LONGER\", \"test\", \"\", \"emptyField\" } );\n\n String valueMapperPid = registry.getPluginId( StepPluginType.class, vm );\n StepMeta valueMapperStep = new StepMeta( valueMapperPid, valueMapperName, vm );\n transMeta.addStep( valueMapperStep );\n\n TransHopMeta hi2 = new TransHopMeta( dummyStep1, valueMapperStep );\n transMeta.addTransHop( hi2 );\n\n //\n // Create a dummy step 2\n //\n String dummyStepname2 = \"dummy step 2\";\n DummyTransMeta dm2 = new DummyTransMeta();\n\n String dummyPid2 = registry.getPluginId( StepPluginType.class, dm2 );\n StepMeta dummyStep2 = new StepMeta( dummyPid2, dummyStepname2, dm2 );\n transMeta.addStep( dummyStep2 );\n\n TransHopMeta hi3 = new TransHopMeta( valueMapperStep, dummyStep2 );\n transMeta.addTransHop( hi3 );\n\n // Now execute the transformation...\n Trans trans = new Trans( transMeta );\n\n trans.prepareExecution( null );\n\n StepInterface si = trans.getStepInterface( dummyStepname1, 0 );\n RowStepCollector dummyRc1 = new RowStepCollector();\n si.addRowListener( dummyRc1 );\n\n si = trans.getStepInterface( valueMapperName, 0 );\n RowStepCollector valueMapperRc = new RowStepCollector();\n si.addRowListener( valueMapperRc );\n\n si = trans.getStepInterface( dummyStepname2, 0 );\n RowStepCollector dummyRc = new RowStepCollector();\n si.addRowListener( dummyRc );\n\n RowProducer rp = trans.addRowProducer( injectorStepname, 0 );\n trans.startThreads();\n\n // add rows\n List inputList = createData();\n Iterator it = inputList.iterator();\n while ( it.hasNext() ) {\n RowMetaAndData rm = it.next();\n rp.putRow( rm.getRowMeta(), rm.getData() );\n }\n rp.finished();\n\n trans.waitUntilFinished();\n\n // Compare the results\n List resultRows = dummyRc.getRowsWritten();\n List goldenImageRows = createResultData3();\n\n checkRows( goldenImageRows, resultRows );\n }\n\n /*----------------- TODO */\n /**\n * Test case for valuemapper step. Injector step to a valuemapper step to a dummy step. Rows go in and should be\n * mapped accordingly.\n *\n * This test will write the mappings in a new field, using a non matching default.\n */\n public void testValueMapper4() throws Exception {\n KettleEnvironment.init();\n\n //\n // Create a new transformation...\n //\n TransMeta transMeta = new TransMeta();\n transMeta.setName( \"valuemappertest4\" );\n\n PluginRegistry registry = PluginRegistry.getInstance();\n\n //\n // create an injector step...\n //\n String injectorStepname = \"injector step\";\n InjectorMeta im = new InjectorMeta();\n\n // Set the information of the injector.\n String injectorPid = registry.getPluginId( StepPluginType.class, im );\n StepMeta injectorStep = new StepMeta( injectorPid, injectorStepname, im );\n transMeta.addStep( injectorStep );\n\n //\n // Create a dummy step 1\n //\n String dummyStepname1 = \"dummy step 1\";\n DummyTransMeta dm1 = new DummyTransMeta();\n\n String dummyPid1 = registry.getPluginId( StepPluginType.class, dm1 );\n StepMeta dummyStep1 = new StepMeta( dummyPid1, dummyStepname1, dm1 );\n transMeta.addStep( dummyStep1 );\n\n TransHopMeta hi = new TransHopMeta( injectorStep, dummyStep1 );\n transMeta.addTransHop( hi );\n\n //\n // Create a step\n //\n String valueMapperName = \"valuemapper step\";\n ValueMapperMeta vm = new ValueMapperMeta();\n\n vm.setFieldToUse( \"field1\" );\n vm.setTargetField( \"new_field\" );\n vm.setNonMatchDefault( \"default\" );\n vm.setSourceValue( new String[] { \"abc\", \"ABC\", \"def\", \"ghij\" } );\n vm.setTargetValue( new String[] { \"begin\", \"BEG_LONGER\", \"test\", \"\" } );\n\n String valueMapperPid = registry.getPluginId( StepPluginType.class, vm );\n StepMeta valueMapperStep = new StepMeta( valueMapperPid, valueMapperName, vm );\n transMeta.addStep( valueMapperStep );\n\n TransHopMeta hi2 = new TransHopMeta( dummyStep1, valueMapperStep );\n transMeta.addTransHop( hi2 );\n\n //\n // Create a dummy step 2\n //\n String dummyStepname2 = \"dummy step 2\";\n DummyTransMeta dm2 = new DummyTransMeta();\n\n String dummyPid2 = registry.getPluginId( StepPluginType.class, dm2 );\n StepMeta dummyStep2 = new StepMeta( dummyPid2, dummyStepname2, dm2 );\n transMeta.addStep( dummyStep2 );\n\n TransHopMeta hi3 = new TransHopMeta( valueMapperStep, dummyStep2 );\n transMeta.addTransHop( hi3 );\n\n // Now execute the transformation...\n Trans trans = new Trans( transMeta );\n\n trans.prepareExecution( null );\n\n StepInterface si = trans.getStepInterface( dummyStepname1, 0 );\n RowStepCollector dummyRc1 = new RowStepCollector();\n si.addRowListener( dummyRc1 );\n\n si = trans.getStepInterface( valueMapperName, 0 );\n RowStepCollector valueMapperRc = new RowStepCollector();\n si.addRowListener( valueMapperRc );\n\n si = trans.getStepInterface( dummyStepname2, 0 );\n RowStepCollector dummyRc = new RowStepCollector();\n si.addRowListener( dummyRc );\n\n RowProducer rp = trans.addRowProducer( injectorStepname, 0 );\n trans.startThreads();\n\n // add rows\n List inputList = createData();\n Iterator it = inputList.iterator();\n while ( it.hasNext() ) {\n RowMetaAndData rm = it.next();\n rp.putRow( rm.getRowMeta(), rm.getData() );\n }\n rp.finished();\n\n trans.waitUntilFinished();\n\n // Compare the results\n List resultRows = dummyRc.getRowsWritten();\n List goldenImageRows = createResultData4();\n\n checkRows( goldenImageRows, resultRows );\n }\n\n /**\n * Test case for valuemapper step. Injector step to a valuemapper step to a dummy step. Rows go in and should be\n * mapped accordingly.\n *\n * This test will write the mappings in the same field. Using a non matching default.\n */\n public void testValueMapper5() throws Exception {\n KettleEnvironment.init();\n\n //\n // Create a new transformation...\n //\n TransMeta transMeta = new TransMeta();\n transMeta.setName( \"valuemappertest5\" );\n\n PluginRegistry registry = PluginRegistry.getInstance();\n\n //\n // create an injector step...\n //\n String injectorStepname = \"injector step\";\n InjectorMeta im = new InjectorMeta();\n\n // Set the information of the injector.\n String injectorPid = registry.getPluginId( StepPluginType.class, im );\n StepMeta injectorStep = new StepMeta( injectorPid, injectorStepname, im );\n transMeta.addStep( injectorStep );\n\n //\n // Create a dummy step 1\n //\n String dummyStepname1 = \"dummy step 1\";\n DummyTransMeta dm1 = new DummyTransMeta();\n\n String dummyPid1 = registry.getPluginId( StepPluginType.class, dm1 );\n StepMeta dummyStep1 = new StepMeta( dummyPid1, dummyStepname1, dm1 );\n transMeta.addStep( dummyStep1 );\n\n TransHopMeta hi = new TransHopMeta( injectorStep, dummyStep1 );\n transMeta.addTransHop( hi );\n\n //\n // Create a step\n //\n String valueMapperName = \"valuemapper step\";\n ValueMapperMeta vm = new ValueMapperMeta();\n\n vm.setFieldToUse( \"field1\" );", "answers": [" vm.setTargetField( \"\" );"], "length": 3337, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "d70fd016-4557-4d01-86d2-f74e0dacb70f", "reasoning": "In testValueMapper5, after configuring the ValueMapperMeta instance, the code follows the same pattern as earlier tests. The first configuration call is vm.setFieldToUse(\"field1\");. Since this test writes mappings back to the same field, the next configuration should specify an empty target field, i.e., vm.setTargetField( \"\" );. This matches the ordering seen in similar test methods.", "reasoning_model_answer": "vm.setTargetField( \"\" );", "assistant_with_reasoning": "\nIn testValueMapper5, after configuring the ValueMapperMeta instance, the code follows the same pattern as earlier tests. The first configuration call is vm.setFieldToUse(\"field1\");. Since this test writes mappings back to the same field, the next configuration should specify an empty target field, i.e., vm.setTargetField( \"\" );. This matches the ordering seen in similar test methods.\n\nvm.setTargetField( \"\" );", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.875, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 27369, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "vm.setTargetField( \"\" );", "score": 0.92, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "import ctypes\nimport itertools\nimport json\nimport pickle\nimport random\nfrom binascii import a2b_hex\nfrom io import BytesIO\nfrom unittest import mock, skipIf\n\nfrom django.contrib.gis import gdal\nfrom django.contrib.gis.geos import (\n GeometryCollection, GEOSException, GEOSGeometry, LinearRing, LineString,\n MultiLineString, MultiPoint, MultiPolygon, Point, Polygon, fromfile,\n fromstr,\n)\nfrom django.contrib.gis.geos.libgeos import geos_version_tuple\nfrom django.contrib.gis.shortcuts import numpy\nfrom django.template import Context\nfrom django.template.engine import Engine\nfrom django.test import SimpleTestCase\n\nfrom ..test_data import TestDataMixin\n\n\nclass GEOSTest(SimpleTestCase, TestDataMixin):\n\n def test_wkt(self):\n \"Testing WKT output.\"\n for g in self.geometries.wkt_out:\n geom = fromstr(g.wkt)\n if geom.hasz:\n self.assertEqual(g.ewkt, geom.wkt)\n\n def test_hex(self):\n \"Testing HEX output.\"\n for g in self.geometries.hex_wkt:\n geom = fromstr(g.wkt)\n self.assertEqual(g.hex, geom.hex.decode())\n\n def test_hexewkb(self):\n \"Testing (HEX)EWKB output.\"\n # For testing HEX(EWKB).\n ogc_hex = b'01010000000000000000000000000000000000F03F'\n ogc_hex_3d = b'01010000800000000000000000000000000000F03F0000000000000040'\n # `SELECT ST_AsHEXEWKB(ST_GeomFromText('POINT(0 1)', 4326));`\n hexewkb_2d = b'0101000020E61000000000000000000000000000000000F03F'\n # `SELECT ST_AsHEXEWKB(ST_GeomFromEWKT('SRID=4326;POINT(0 1 2)'));`\n hexewkb_3d = b'01010000A0E61000000000000000000000000000000000F03F0000000000000040'\n\n pnt_2d = Point(0, 1, srid=4326)\n pnt_3d = Point(0, 1, 2, srid=4326)\n\n # OGC-compliant HEX will not have SRID value.\n self.assertEqual(ogc_hex, pnt_2d.hex)\n self.assertEqual(ogc_hex_3d, pnt_3d.hex)\n\n # HEXEWKB should be appropriate for its dimension -- have to use an\n # a WKBWriter w/dimension set accordingly, else GEOS will insert\n # garbage into 3D coordinate if there is none.\n self.assertEqual(hexewkb_2d, pnt_2d.hexewkb)\n self.assertEqual(hexewkb_3d, pnt_3d.hexewkb)\n self.assertIs(GEOSGeometry(hexewkb_3d).hasz, True)\n\n # Same for EWKB.\n self.assertEqual(memoryview(a2b_hex(hexewkb_2d)), pnt_2d.ewkb)\n self.assertEqual(memoryview(a2b_hex(hexewkb_3d)), pnt_3d.ewkb)\n\n # Redundant sanity check.\n self.assertEqual(4326, GEOSGeometry(hexewkb_2d).srid)\n\n def test_kml(self):\n \"Testing KML output.\"\n for tg in self.geometries.wkt_out:\n geom = fromstr(tg.wkt)\n kml = getattr(tg, 'kml', False)\n if kml:\n self.assertEqual(kml, geom.kml)\n\n def test_errors(self):\n \"Testing the Error handlers.\"\n # string-based\n for err in self.geometries.errors:\n with self.assertRaises((GEOSException, ValueError)):\n fromstr(err.wkt)\n\n # Bad WKB\n with self.assertRaises(GEOSException):\n GEOSGeometry(memoryview(b'0'))\n\n class NotAGeometry:\n pass\n\n # Some other object\n with self.assertRaises(TypeError):\n GEOSGeometry(NotAGeometry())\n # None\n with self.assertRaises(TypeError):\n GEOSGeometry(None)\n\n def test_wkb(self):\n \"Testing WKB output.\"\n for g in self.geometries.hex_wkt:\n geom = fromstr(g.wkt)\n wkb = geom.wkb\n self.assertEqual(wkb.hex().upper(), g.hex)\n\n def test_create_hex(self):\n \"Testing creation from HEX.\"\n for g in self.geometries.hex_wkt:\n geom_h = GEOSGeometry(g.hex)\n # we need to do this so decimal places get normalized\n geom_t = fromstr(g.wkt)\n self.assertEqual(geom_t.wkt, geom_h.wkt)\n\n def test_create_wkb(self):\n \"Testing creation from WKB.\"\n for g in self.geometries.hex_wkt:\n wkb = memoryview(bytes.fromhex(g.hex))\n geom_h = GEOSGeometry(wkb)\n # we need to do this so decimal places get normalized\n geom_t = fromstr(g.wkt)\n self.assertEqual(geom_t.wkt, geom_h.wkt)\n\n def test_ewkt(self):\n \"Testing EWKT.\"\n srids = (-1, 32140)\n for srid in srids:\n for p in self.geometries.polygons:\n ewkt = 'SRID=%d;%s' % (srid, p.wkt)\n poly = fromstr(ewkt)\n self.assertEqual(srid, poly.srid)\n self.assertEqual(srid, poly.shell.srid)\n self.assertEqual(srid, fromstr(poly.ewkt).srid) # Checking export\n\n def test_json(self):\n \"Testing GeoJSON input/output (via GDAL).\"\n for g in self.geometries.json_geoms:\n geom = GEOSGeometry(g.wkt)\n if not hasattr(g, 'not_equal'):\n # Loading jsons to prevent decimal differences\n self.assertEqual(json.loads(g.json), json.loads(geom.json))\n self.assertEqual(json.loads(g.json), json.loads(geom.geojson))\n self.assertEqual(GEOSGeometry(g.wkt, 4326), GEOSGeometry(geom.json))\n\n def test_json_srid(self):\n geojson_data = {\n \"type\": \"Point\",\n \"coordinates\": [2, 49],\n \"crs\": {\n \"type\": \"name\",\n \"properties\": {\n \"name\": \"urn:ogc:def:crs:EPSG::4322\"\n }\n }\n }\n self.assertEqual(GEOSGeometry(json.dumps(geojson_data)), Point(2, 49, srid=4322))\n\n def test_fromfile(self):\n \"Testing the fromfile() factory.\"\n ref_pnt = GEOSGeometry('POINT(5 23)')\n\n wkt_f = BytesIO()\n wkt_f.write(ref_pnt.wkt.encode())\n wkb_f = BytesIO()\n wkb_f.write(bytes(ref_pnt.wkb))\n\n # Other tests use `fromfile()` on string filenames so those\n # aren't tested here.\n for fh in (wkt_f, wkb_f):\n fh.seek(0)\n pnt = fromfile(fh)\n self.assertEqual(ref_pnt, pnt)\n\n def test_eq(self):\n \"Testing equivalence.\"\n p = fromstr('POINT(5 23)')\n self.assertEqual(p, p.wkt)\n self.assertNotEqual(p, 'foo')\n ls = fromstr('LINESTRING(0 0, 1 1, 5 5)')\n self.assertEqual(ls, ls.wkt)\n self.assertNotEqual(p, 'bar')\n self.assertEqual(p, 'POINT(5.0 23.0)')\n # Error shouldn't be raise on equivalence testing with\n # an invalid type.\n for g in (p, ls):\n self.assertIsNotNone(g)\n self.assertNotEqual(g, {'foo': 'bar'})\n self.assertIsNot(g, False)\n\n def test_hash(self):\n point_1 = Point(5, 23)\n point_2 = Point(5, 23, srid=4326)\n point_3 = Point(5, 23, srid=32632)\n multipoint_1 = MultiPoint(point_1, srid=4326)\n multipoint_2 = MultiPoint(point_2)\n multipoint_3 = MultiPoint(point_3)\n self.assertNotEqual(hash(point_1), hash(point_2))\n self.assertNotEqual(hash(point_1), hash(point_3))\n self.assertNotEqual(hash(point_2), hash(point_3))\n self.assertNotEqual(hash(multipoint_1), hash(multipoint_2))\n self.assertEqual(hash(multipoint_2), hash(multipoint_3))\n self.assertNotEqual(hash(multipoint_1), hash(point_1))\n self.assertNotEqual(hash(multipoint_2), hash(point_2))\n self.assertNotEqual(hash(multipoint_3), hash(point_3))\n\n def test_eq_with_srid(self):\n \"Testing non-equivalence with different srids.\"\n p0 = Point(5, 23)\n p1 = Point(5, 23, srid=4326)\n p2 = Point(5, 23, srid=32632)\n # GEOS\n self.assertNotEqual(p0, p1)\n self.assertNotEqual(p1, p2)\n # EWKT\n self.assertNotEqual(p0, p1.ewkt)\n self.assertNotEqual(p1, p0.ewkt)\n self.assertNotEqual(p1, p2.ewkt)\n # Equivalence with matching SRIDs\n self.assertEqual(p2, p2)\n self.assertEqual(p2, p2.ewkt)\n # WKT contains no SRID so will not equal\n self.assertNotEqual(p2, p2.wkt)\n # SRID of 0\n self.assertEqual(p0, 'SRID=0;POINT (5 23)')\n self.assertNotEqual(p1, 'SRID=0;POINT (5 23)')\n\n def test_points(self):\n \"Testing Point objects.\"\n prev = fromstr('POINT(0 0)')\n for p in self.geometries.points:\n # Creating the point from the WKT\n pnt = fromstr(p.wkt)\n self.assertEqual(pnt.geom_type, 'Point')\n self.assertEqual(pnt.geom_typeid, 0)\n self.assertEqual(pnt.dims, 0)\n self.assertEqual(p.x, pnt.x)\n self.assertEqual(p.y, pnt.y)\n self.assertEqual(pnt, fromstr(p.wkt))\n self.assertIs(pnt == prev, False) # Use assertIs() to test __eq__.\n\n # Making sure that the point's X, Y components are what we expect\n self.assertAlmostEqual(p.x, pnt.tuple[0], 9)\n self.assertAlmostEqual(p.y, pnt.tuple[1], 9)\n\n # Testing the third dimension, and getting the tuple arguments\n if hasattr(p, 'z'):\n self.assertIs(pnt.hasz, True)\n self.assertEqual(p.z, pnt.z)\n self.assertEqual(p.z, pnt.tuple[2], 9)\n tup_args = (p.x, p.y, p.z)\n set_tup1 = (2.71, 3.14, 5.23)\n set_tup2 = (5.23, 2.71, 3.14)\n else:\n self.assertIs(pnt.hasz, False)\n self.assertIsNone(pnt.z)\n tup_args = (p.x, p.y)\n set_tup1 = (2.71, 3.14)\n set_tup2 = (3.14, 2.71)\n\n # Centroid operation on point should be point itself\n self.assertEqual(p.centroid, pnt.centroid.tuple)\n\n # Now testing the different constructors\n pnt2 = Point(tup_args) # e.g., Point((1, 2))\n pnt3 = Point(*tup_args) # e.g., Point(1, 2)\n self.assertEqual(pnt, pnt2)\n self.assertEqual(pnt, pnt3)\n\n # Now testing setting the x and y\n pnt.y = 3.14\n pnt.x = 2.71\n self.assertEqual(3.14, pnt.y)\n self.assertEqual(2.71, pnt.x)\n\n # Setting via the tuple/coords property\n pnt.tuple = set_tup1\n self.assertEqual(set_tup1, pnt.tuple)\n pnt.coords = set_tup2\n self.assertEqual(set_tup2, pnt.coords)\n\n prev = pnt # setting the previous geometry\n\n def test_point_reverse(self):\n point = GEOSGeometry('POINT(144.963 -37.8143)', 4326)\n self.assertEqual(point.srid, 4326)\n point.reverse()\n self.assertEqual(point.ewkt, 'SRID=4326;POINT (-37.8143 144.963)')\n\n def test_multipoints(self):\n \"Testing MultiPoint objects.\"\n for mp in self.geometries.multipoints:\n mpnt = fromstr(mp.wkt)\n self.assertEqual(mpnt.geom_type, 'MultiPoint')\n self.assertEqual(mpnt.geom_typeid, 4)\n self.assertEqual(mpnt.dims, 0)\n\n self.assertAlmostEqual(mp.centroid[0], mpnt.centroid.tuple[0], 9)\n self.assertAlmostEqual(mp.centroid[1], mpnt.centroid.tuple[1], 9)\n\n with self.assertRaises(IndexError):\n mpnt.__getitem__(len(mpnt))\n self.assertEqual(mp.centroid, mpnt.centroid.tuple)\n self.assertEqual(mp.coords, tuple(m.tuple for m in mpnt))\n for p in mpnt:\n self.assertEqual(p.geom_type, 'Point')\n self.assertEqual(p.geom_typeid, 0)\n self.assertIs(p.empty, False)\n self.assertIs(p.valid, True)\n\n def test_linestring(self):\n \"Testing LineString objects.\"\n prev = fromstr('POINT(0 0)')\n for line in self.geometries.linestrings:\n ls = fromstr(line.wkt)\n self.assertEqual(ls.geom_type, 'LineString')\n self.assertEqual(ls.geom_typeid, 1)\n self.assertEqual(ls.dims, 1)\n self.assertIs(ls.empty, False)\n self.assertIs(ls.ring, False)\n if hasattr(line, 'centroid'):\n self.assertEqual(line.centroid, ls.centroid.tuple)\n if hasattr(line, 'tup'):\n self.assertEqual(line.tup, ls.tuple)\n\n self.assertEqual(ls, fromstr(line.wkt))\n self.assertIs(ls == prev, False) # Use assertIs() to test __eq__.\n with self.assertRaises(IndexError):\n ls.__getitem__(len(ls))\n prev = ls\n\n # Creating a LineString from a tuple, list, and numpy array\n self.assertEqual(ls, LineString(ls.tuple)) # tuple\n self.assertEqual(ls, LineString(*ls.tuple)) # as individual arguments\n self.assertEqual(ls, LineString([list(tup) for tup in ls.tuple])) # as list\n # Point individual arguments\n self.assertEqual(ls.wkt, LineString(*tuple(Point(tup) for tup in ls.tuple)).wkt)\n if numpy:\n self.assertEqual(ls, LineString(numpy.array(ls.tuple))) # as numpy array\n\n with self.assertRaisesMessage(TypeError, 'Each coordinate should be a sequence (list or tuple)'):\n LineString((0, 0))\n\n with self.assertRaisesMessage(ValueError, 'LineString requires at least 2 points, got 1.'):\n LineString([(0, 0)])\n\n if numpy:\n with self.assertRaisesMessage(ValueError, 'LineString requires at least 2 points, got 1.'):\n LineString(numpy.array([(0, 0)]))\n\n with mock.patch('django.contrib.gis.geos.linestring.numpy', False):\n with self.assertRaisesMessage(TypeError, 'Invalid initialization input for LineStrings.'):\n LineString('wrong input')\n\n # Test __iter__().\n self.assertEqual(list(LineString((0, 0), (1, 1), (2, 2))), [(0, 0), (1, 1), (2, 2)])\n\n def test_linestring_reverse(self):\n line = GEOSGeometry('LINESTRING(144.963 -37.8143,151.2607 -33.887)', 4326)\n self.assertEqual(line.srid, 4326)\n line.reverse()\n self.assertEqual(line.ewkt, 'SRID=4326;LINESTRING (151.2607 -33.887, 144.963 -37.8143)')\n\n def _test_is_counterclockwise(self):\n lr = LinearRing((0, 0), (1, 0), (0, 1), (0, 0))\n self.assertIs(lr.is_counterclockwise, True)\n lr.reverse()\n self.assertIs(lr.is_counterclockwise, False)\n msg = 'Orientation of an empty LinearRing cannot be determined.'\n with self.assertRaisesMessage(ValueError, msg):\n LinearRing().is_counterclockwise\n\n @skipIf(geos_version_tuple() < (3, 7), 'GEOS >= 3.7.0 is required')\n def test_is_counterclockwise(self):\n self._test_is_counterclockwise()\n\n @skipIf(geos_version_tuple() < (3, 7), 'GEOS >= 3.7.0 is required')\n def test_is_counterclockwise_geos_error(self):\n with mock.patch('django.contrib.gis.geos.prototypes.cs_is_ccw') as mocked:\n mocked.return_value = 0\n mocked.func_name = 'GEOSCoordSeq_isCCW'\n msg = 'Error encountered in GEOS C function \"GEOSCoordSeq_isCCW\".'\n with self.assertRaisesMessage(GEOSException, msg):\n LinearRing((0, 0), (1, 0), (0, 1), (0, 0)).is_counterclockwise\n\n @mock.patch('django.contrib.gis.geos.libgeos.geos_version', lambda: b'3.6.9')\n def test_is_counterclockwise_fallback(self):\n self._test_is_counterclockwise()\n\n def test_multilinestring(self):\n \"Testing MultiLineString objects.\"\n prev = fromstr('POINT(0 0)')\n for line in self.geometries.multilinestrings:\n ml = fromstr(line.wkt)\n self.assertEqual(ml.geom_type, 'MultiLineString')\n self.assertEqual(ml.geom_typeid, 5)\n self.assertEqual(ml.dims, 1)\n\n self.assertAlmostEqual(line.centroid[0], ml.centroid.x, 9)\n self.assertAlmostEqual(line.centroid[1], ml.centroid.y, 9)\n\n self.assertEqual(ml, fromstr(line.wkt))\n self.assertIs(ml == prev, False) # Use assertIs() to test __eq__.\n prev = ml\n\n for ls in ml:\n self.assertEqual(ls.geom_type, 'LineString')\n self.assertEqual(ls.geom_typeid, 1)\n self.assertIs(ls.empty, False)\n\n with self.assertRaises(IndexError):\n ml.__getitem__(len(ml))\n self.assertEqual(ml.wkt, MultiLineString(*tuple(s.clone() for s in ml)).wkt)\n self.assertEqual(ml, MultiLineString(*tuple(LineString(s.tuple) for s in ml)))\n\n def test_linearring(self):\n \"Testing LinearRing objects.\"\n for rr in self.geometries.linearrings:\n lr = fromstr(rr.wkt)\n self.assertEqual(lr.geom_type, 'LinearRing')\n self.assertEqual(lr.geom_typeid, 2)\n self.assertEqual(lr.dims, 1)\n self.assertEqual(rr.n_p, len(lr))\n self.assertIs(lr.valid, True)\n self.assertIs(lr.empty, False)\n\n # Creating a LinearRing from a tuple, list, and numpy array\n self.assertEqual(lr, LinearRing(lr.tuple))\n self.assertEqual(lr, LinearRing(*lr.tuple))\n self.assertEqual(lr, LinearRing([list(tup) for tup in lr.tuple]))\n if numpy:\n self.assertEqual(lr, LinearRing(numpy.array(lr.tuple)))\n\n with self.assertRaisesMessage(ValueError, 'LinearRing requires at least 4 points, got 3.'):\n LinearRing((0, 0), (1, 1), (0, 0))\n\n with self.assertRaisesMessage(ValueError, 'LinearRing requires at least 4 points, got 1.'):\n LinearRing([(0, 0)])\n\n if numpy:\n with self.assertRaisesMessage(ValueError, 'LinearRing requires at least 4 points, got 1.'):\n LinearRing(numpy.array([(0, 0)]))\n\n def test_linearring_json(self):\n self.assertJSONEqual(\n LinearRing((0, 0), (0, 1), (1, 1), (0, 0)).json,\n '{\"coordinates\": [[0, 0], [0, 1], [1, 1], [0, 0]], \"type\": \"LineString\"}',\n )\n\n def test_polygons_from_bbox(self):\n \"Testing `from_bbox` class method.\"\n bbox = (-180, -90, 180, 90)\n p = Polygon.from_bbox(bbox)\n self.assertEqual(bbox, p.extent)\n\n # Testing numerical precision\n x = 3.14159265358979323\n bbox = (0, 0, 1, x)\n p = Polygon.from_bbox(bbox)\n y = p.extent[-1]\n self.assertEqual(format(x, '.13f'), format(y, '.13f'))\n\n def test_polygons(self):\n \"Testing Polygon objects.\"\n\n prev = fromstr('POINT(0 0)')\n for p in self.geometries.polygons:\n # Creating the Polygon, testing its properties.\n poly = fromstr(p.wkt)\n self.assertEqual(poly.geom_type, 'Polygon')\n self.assertEqual(poly.geom_typeid, 3)\n self.assertEqual(poly.dims, 2)\n self.assertIs(poly.empty, False)\n self.assertIs(poly.ring, False)\n self.assertEqual(p.n_i, poly.num_interior_rings)\n self.assertEqual(p.n_i + 1, len(poly)) # Testing __len__\n self.assertEqual(p.n_p, poly.num_points)\n\n # Area & Centroid\n self.assertAlmostEqual(p.area, poly.area, 9)\n self.assertAlmostEqual(p.centroid[0], poly.centroid.tuple[0], 9)\n self.assertAlmostEqual(p.centroid[1], poly.centroid.tuple[1], 9)\n\n # Testing the geometry equivalence\n self.assertEqual(poly, fromstr(p.wkt))\n # Should not be equal to previous geometry\n self.assertIs(poly == prev, False) # Use assertIs() to test __eq__.\n self.assertIs(poly != prev, True) # Use assertIs() to test __ne__.\n\n # Testing the exterior ring\n ring = poly.exterior_ring\n self.assertEqual(ring.geom_type, 'LinearRing')\n self.assertEqual(ring.geom_typeid, 2)\n if p.ext_ring_cs:\n self.assertEqual(p.ext_ring_cs, ring.tuple)\n self.assertEqual(p.ext_ring_cs, poly[0].tuple) # Testing __getitem__\n\n # Testing __getitem__ and __setitem__ on invalid indices\n with self.assertRaises(IndexError):\n poly.__getitem__(len(poly))\n with self.assertRaises(IndexError):\n poly.__setitem__(len(poly), False)\n with self.assertRaises(IndexError):\n poly.__getitem__(-1 * len(poly) - 1)\n\n # Testing __iter__\n for r in poly:\n self.assertEqual(r.geom_type, 'LinearRing')\n self.assertEqual(r.geom_typeid, 2)\n\n # Testing polygon construction.\n with self.assertRaises(TypeError):\n Polygon(0, [1, 2, 3])\n with self.assertRaises(TypeError):\n Polygon('foo')\n\n # Polygon(shell, (hole1, ... holeN))\n ext_ring, *int_rings = poly\n self.assertEqual(poly, Polygon(ext_ring, int_rings))\n\n # Polygon(shell_tuple, hole_tuple1, ... , hole_tupleN)\n ring_tuples = tuple(r.tuple for r in poly)\n self.assertEqual(poly, Polygon(*ring_tuples))\n\n # Constructing with tuples of LinearRings.\n self.assertEqual(poly.wkt, Polygon(*tuple(r for r in poly)).wkt)\n self.assertEqual(poly.wkt, Polygon(*tuple(LinearRing(r.tuple) for r in poly)).wkt)\n\n def test_polygons_templates(self):\n # Accessing Polygon attributes in templates should work.\n engine = Engine()\n template = engine.from_string('{{ polygons.0.wkt }}')\n polygons = [fromstr(p.wkt) for p in self.geometries.multipolygons[:2]]\n content = template.render(Context({'polygons': polygons}))\n self.assertIn('MULTIPOLYGON (((100', content)\n\n def test_polygon_comparison(self):\n p1 = Polygon(((0, 0), (0, 1), (1, 1), (1, 0), (0, 0)))\n p2 = Polygon(((0, 0), (0, 1), (1, 0), (0, 0)))\n self.assertGreater(p1, p2)\n self.assertLess(p2, p1)\n\n p3 = Polygon(((0, 0), (0, 1), (1, 1), (2, 0), (0, 0)))\n p4 = Polygon(((0, 0), (0, 1), (2, 2), (1, 0), (0, 0)))\n self.assertGreater(p4, p3)\n self.assertLess(p3, p4)\n\n def test_multipolygons(self):\n \"Testing MultiPolygon objects.\"\n fromstr('POINT (0 0)')\n for mp in self.geometries.multipolygons:\n mpoly = fromstr(mp.wkt)\n self.assertEqual(mpoly.geom_type, 'MultiPolygon')\n self.assertEqual(mpoly.geom_typeid, 6)\n self.assertEqual(mpoly.dims, 2)\n self.assertEqual(mp.valid, mpoly.valid)\n\n if mp.valid:\n self.assertEqual(mp.num_geom, mpoly.num_geom)\n self.assertEqual(mp.n_p, mpoly.num_coords)\n self.assertEqual(mp.num_geom, len(mpoly))\n with self.assertRaises(IndexError):\n mpoly.__getitem__(len(mpoly))\n for p in mpoly:\n self.assertEqual(p.geom_type, 'Polygon')\n self.assertEqual(p.geom_typeid, 3)\n self.assertIs(p.valid, True)\n self.assertEqual(mpoly.wkt, MultiPolygon(*tuple(poly.clone() for poly in mpoly)).wkt)\n\n def test_memory_hijinks(self):\n \"Testing Geometry __del__() on rings and polygons.\"\n # #### Memory issues with rings and poly\n\n # These tests are needed to ensure sanity with writable geometries.\n\n # Getting a polygon with interior rings, and pulling out the interior rings\n poly = fromstr(self.geometries.polygons[1].wkt)\n ring1 = poly[0]\n ring2 = poly[1]\n\n # These deletes should be 'harmless' since they are done on child geometries\n del ring1\n del ring2\n ring1 = poly[0]\n ring2 = poly[1]\n\n # Deleting the polygon\n del poly\n\n # Access to these rings is OK since they are clones.\n str(ring1)\n str(ring2)\n\n def test_coord_seq(self):\n \"Testing Coordinate Sequence objects.\"\n for p in self.geometries.polygons:\n if p.ext_ring_cs:\n # Constructing the polygon and getting the coordinate sequence\n poly = fromstr(p.wkt)\n cs = poly.exterior_ring.coord_seq\n\n self.assertEqual(p.ext_ring_cs, cs.tuple) # done in the Polygon test too.\n self.assertEqual(len(p.ext_ring_cs), len(cs)) # Making sure __len__ works\n\n # Checks __getitem__ and __setitem__\n for i in range(len(p.ext_ring_cs)):\n c1 = p.ext_ring_cs[i] # Expected value\n c2 = cs[i] # Value from coordseq\n self.assertEqual(c1, c2)\n\n # Constructing the test value to set the coordinate sequence with\n if len(c1) == 2:\n tset = (5, 23)\n else:\n tset = (5, 23, 8)\n cs[i] = tset\n\n # Making sure every set point matches what we expect\n for j in range(len(tset)):\n cs[i] = tset\n self.assertEqual(tset[j], cs[i][j])\n\n def test_relate_pattern(self):\n \"Testing relate() and relate_pattern().\"\n g = fromstr('POINT (0 0)')\n with self.assertRaises(GEOSException):\n g.relate_pattern(0, 'invalid pattern, yo')\n for rg in self.geometries.relate_geoms:\n a = fromstr(rg.wkt_a)\n b = fromstr(rg.wkt_b)\n self.assertEqual(rg.result, a.relate_pattern(b, rg.pattern))\n self.assertEqual(rg.pattern, a.relate(b))\n\n def test_intersection(self):\n \"Testing intersects() and intersection().\"\n for i in range(len(self.geometries.topology_geoms)):\n a = fromstr(self.geometries.topology_geoms[i].wkt_a)\n b = fromstr(self.geometries.topology_geoms[i].wkt_b)\n i1 = fromstr(self.geometries.intersect_geoms[i].wkt)\n self.assertIs(a.intersects(b), True)\n i2 = a.intersection(b)\n self.assertTrue(i1.equals(i2))\n self.assertTrue(i1.equals(a & b)) # __and__ is intersection operator\n a &= b # testing __iand__\n self.assertTrue(i1.equals(a))\n\n def test_union(self):\n \"Testing union().\"\n for i in range(len(self.geometries.topology_geoms)):\n a = fromstr(self.geometries.topology_geoms[i].wkt_a)\n b = fromstr(self.geometries.topology_geoms[i].wkt_b)\n u1 = fromstr(self.geometries.union_geoms[i].wkt)\n u2 = a.union(b)\n self.assertTrue(u1.equals(u2))\n self.assertTrue(u1.equals(a | b)) # __or__ is union operator\n a |= b # testing __ior__\n self.assertTrue(u1.equals(a))\n\n def test_unary_union(self):\n \"Testing unary_union.\"\n for i in range(len(self.geometries.topology_geoms)):\n a = fromstr(self.geometries.topology_geoms[i].wkt_a)\n b = fromstr(self.geometries.topology_geoms[i].wkt_b)\n u1 = fromstr(self.geometries.union_geoms[i].wkt)\n u2 = GeometryCollection(a, b).unary_union\n self.assertTrue(u1.equals(u2))\n\n def test_difference(self):\n \"Testing difference().\"\n for i in range(len(self.geometries.topology_geoms)):\n a = fromstr(self.geometries.topology_geoms[i].wkt_a)\n b = fromstr(self.geometries.topology_geoms[i].wkt_b)\n d1 = fromstr(self.geometries.diff_geoms[i].wkt)\n d2 = a.difference(b)\n self.assertTrue(d1.equals(d2))\n self.assertTrue(d1.equals(a - b)) # __sub__ is difference operator\n a -= b # testing __isub__\n self.assertTrue(d1.equals(a))\n\n def test_symdifference(self):\n \"Testing sym_difference().\"\n for i in range(len(self.geometries.topology_geoms)):\n a = fromstr(self.geometries.topology_geoms[i].wkt_a)\n b = fromstr(self.geometries.topology_geoms[i].wkt_b)\n d1 = fromstr(self.geometries.sdiff_geoms[i].wkt)\n d2 = a.sym_difference(b)\n self.assertTrue(d1.equals(d2))\n self.assertTrue(d1.equals(a ^ b)) # __xor__ is symmetric difference operator\n a ^= b # testing __ixor__\n self.assertTrue(d1.equals(a))\n\n def test_buffer(self):\n bg = self.geometries.buffer_geoms[0]\n g = fromstr(bg.wkt)\n\n # Can't use a floating-point for the number of quadsegs.\n with self.assertRaises(ctypes.ArgumentError):\n g.buffer(bg.width, quadsegs=1.1)\n\n self._test_buffer(self.geometries.buffer_geoms, 'buffer')\n\n def test_buffer_with_style(self):\n bg = self.geometries.buffer_with_style_geoms[0]\n g = fromstr(bg.wkt)\n\n # Can't use a floating-point for the number of quadsegs.\n with self.assertRaises(ctypes.ArgumentError):\n g.buffer_with_style(bg.width, quadsegs=1.1)\n\n # Can't use a floating-point for the end cap style.\n with self.assertRaises(ctypes.ArgumentError):\n g.buffer_with_style(bg.width, end_cap_style=1.2)\n # Can't use a end cap style that is not in the enum.\n with self.assertRaises(GEOSException):\n g.buffer_with_style(bg.width, end_cap_style=55)\n\n # Can't use a floating-point for the join style.\n with self.assertRaises(ctypes.ArgumentError):\n g.buffer_with_style(bg.width, join_style=1.3)\n # Can't use a join style that is not in the enum.\n with self.assertRaises(GEOSException):\n g.buffer_with_style(bg.width, join_style=66)\n\n self._test_buffer(\n itertools.chain(self.geometries.buffer_geoms, self.geometries.buffer_with_style_geoms),\n 'buffer_with_style',\n )\n\n def _test_buffer(self, geometries, buffer_method_name):\n for bg in geometries:\n g = fromstr(bg.wkt)\n\n # The buffer we expect\n exp_buf = fromstr(bg.buffer_wkt)\n\n # Constructing our buffer\n buf_kwargs = {\n kwarg_name: getattr(bg, kwarg_name)\n for kwarg_name in ('width', 'quadsegs', 'end_cap_style', 'join_style', 'mitre_limit')\n if hasattr(bg, kwarg_name)\n }\n buf = getattr(g, buffer_method_name)(**buf_kwargs)\n self.assertEqual(exp_buf.num_coords, buf.num_coords)\n self.assertEqual(len(exp_buf), len(buf))\n\n # Now assuring that each point in the buffer is almost equal\n for j in range(len(exp_buf)):\n exp_ring = exp_buf[j]\n buf_ring = buf[j]\n self.assertEqual(len(exp_ring), len(buf_ring))\n for k in range(len(exp_ring)):\n # Asserting the X, Y of each point are almost equal (due to floating point imprecision)\n self.assertAlmostEqual(exp_ring[k][0], buf_ring[k][0], 9)\n self.assertAlmostEqual(exp_ring[k][1], buf_ring[k][1], 9)\n\n def test_covers(self):\n poly = Polygon(((0, 0), (0, 10), (10, 10), (10, 0), (0, 0)))\n self.assertTrue(poly.covers(Point(5, 5)))\n self.assertFalse(poly.covers(Point(100, 100)))\n\n def test_closed(self):\n ls_closed = LineString((0, 0), (1, 1), (0, 0))\n ls_not_closed = LineString((0, 0), (1, 1))\n self.assertFalse(ls_not_closed.closed)\n self.assertTrue(ls_closed.closed)\n\n def test_srid(self):\n \"Testing the SRID property and keyword.\"\n # Testing SRID keyword on Point\n pnt = Point(5, 23, srid=4326)\n self.assertEqual(4326, pnt.srid)\n pnt.srid = 3084\n self.assertEqual(3084, pnt.srid)\n with self.assertRaises(ctypes.ArgumentError):\n pnt.srid = '4326'\n\n # Testing SRID keyword on fromstr(), and on Polygon rings.\n poly = fromstr(self.geometries.polygons[1].wkt, srid=4269)\n self.assertEqual(4269, poly.srid)\n for ring in poly:\n self.assertEqual(4269, ring.srid)\n poly.srid = 4326\n self.assertEqual(4326, poly.shell.srid)\n\n # Testing SRID keyword on GeometryCollection\n gc = GeometryCollection(Point(5, 23), LineString((0, 0), (1.5, 1.5), (3, 3)), srid=32021)\n self.assertEqual(32021, gc.srid)\n for i in range(len(gc)):\n self.assertEqual(32021, gc[i].srid)\n\n # GEOS may get the SRID from HEXEWKB\n # 'POINT(5 23)' at SRID=4326 in hex form -- obtained from PostGIS\n # using `SELECT GeomFromText('POINT (5 23)', 4326);`.\n hex = '0101000020E610000000000000000014400000000000003740'\n p1 = fromstr(hex)\n self.assertEqual(4326, p1.srid)\n\n p2 = fromstr(p1.hex)\n self.assertIsNone(p2.srid)\n p3 = fromstr(p1.hex, srid=-1) # -1 is intended.\n self.assertEqual(-1, p3.srid)\n\n # Testing that geometry SRID could be set to its own value\n pnt_wo_srid = Point(1, 1)\n pnt_wo_srid.srid = pnt_wo_srid.srid\n\n # Input geometries that have an SRID.\n self.assertEqual(GEOSGeometry(pnt.ewkt, srid=pnt.srid).srid, pnt.srid)\n self.assertEqual(GEOSGeometry(pnt.ewkb, srid=pnt.srid).srid, pnt.srid)\n with self.assertRaisesMessage(ValueError, 'Input geometry already has SRID: %d.' % pnt.srid):\n GEOSGeometry(pnt.ewkt, srid=1)\n with self.assertRaisesMessage(ValueError, 'Input geometry already has SRID: %d.' % pnt.srid):\n GEOSGeometry(pnt.ewkb, srid=1)\n\n def test_custom_srid(self):\n \"\"\"Test with a null srid and a srid unknown to GDAL.\"\"\"\n for srid in [None, 999999]:\n pnt = Point(111200, 220900, srid=srid)\n self.assertTrue(pnt.ewkt.startswith((\"SRID=%s;\" % srid if srid else '') + \"POINT (111200\"))\n self.assertIsInstance(pnt.ogr, gdal.OGRGeometry)\n self.assertIsNone(pnt.srs)\n\n # Test conversion from custom to a known srid\n c2w = gdal.CoordTransform(\n gdal.SpatialReference(\n '+proj=mill +lat_0=0 +lon_0=0 +x_0=0 +y_0=0 +R_A +ellps=WGS84 '\n '+datum=WGS84 +units=m +no_defs'\n ),\n gdal.SpatialReference(4326))\n new_pnt = pnt.transform(c2w, clone=True)\n self.assertEqual(new_pnt.srid, 4326)\n self.assertAlmostEqual(new_pnt.x, 1, 1)\n self.assertAlmostEqual(new_pnt.y, 2, 1)\n\n def test_mutable_geometries(self):\n \"Testing the mutability of Polygons and Geometry Collections.\"\n # ### Testing the mutability of Polygons ###\n for p in self.geometries.polygons:\n poly = fromstr(p.wkt)\n\n # Should only be able to use __setitem__ with LinearRing geometries.\n with self.assertRaises(TypeError):\n poly.__setitem__(0, LineString((1, 1), (2, 2)))\n\n # Constructing the new shell by adding 500 to every point in the old shell.\n shell_tup = poly.shell.tuple\n new_coords = []\n for point in shell_tup:\n new_coords.append((point[0] + 500., point[1] + 500.))\n new_shell = LinearRing(*tuple(new_coords))\n\n # Assigning polygon's exterior ring w/the new shell\n poly.exterior_ring = new_shell\n str(new_shell) # new shell is still accessible\n self.assertEqual(poly.exterior_ring, new_shell)\n self.assertEqual(poly[0], new_shell)\n\n # ### Testing the mutability of Geometry Collections\n for tg in self.geometries.multipoints:\n mp = fromstr(tg.wkt)\n for i in range(len(mp)):\n # Creating a random point.\n pnt = mp[i]\n new = Point(random.randint(21, 100), random.randint(21, 100))\n # Testing the assignment\n mp[i] = new\n str(new) # what was used for the assignment is still accessible\n self.assertEqual(mp[i], new)\n self.assertEqual(mp[i].wkt, new.wkt)\n self.assertNotEqual(pnt, mp[i])\n\n # MultiPolygons involve much more memory management because each\n # Polygon w/in the collection has its own rings.\n for tg in self.geometries.multipolygons:\n mpoly = fromstr(tg.wkt)\n for i in range(len(mpoly)):\n poly = mpoly[i]\n old_poly = mpoly[i]\n # Offsetting the each ring in the polygon by 500.\n for j in range(len(poly)):\n r = poly[j]\n for k in range(len(r)):\n r[k] = (r[k][0] + 500., r[k][1] + 500.)\n poly[j] = r\n\n self.assertNotEqual(mpoly[i], poly)\n # Testing the assignment\n mpoly[i] = poly\n str(poly) # Still accessible\n self.assertEqual(mpoly[i], poly)\n self.assertNotEqual(mpoly[i], old_poly)\n\n # Extreme (!!) __setitem__ -- no longer works, have to detect\n # in the first object that __setitem__ is called in the subsequent\n # objects -- maybe mpoly[0, 0, 0] = (3.14, 2.71)?\n # mpoly[0][0][0] = (3.14, 2.71)\n # self.assertEqual((3.14, 2.71), mpoly[0][0][0])\n # Doing it more slowly..\n # self.assertEqual((3.14, 2.71), mpoly[0].shell[0])\n # del mpoly\n\n def test_point_list_assignment(self):\n p = Point(0, 0)\n\n p[:] = (1, 2, 3)\n self.assertEqual(p, Point(1, 2, 3))\n\n p[:] = ()\n self.assertEqual(p.wkt, Point())\n\n p[:] = (1, 2)\n self.assertEqual(p.wkt, Point(1, 2))\n\n with self.assertRaises(ValueError):\n p[:] = (1,)\n with self.assertRaises(ValueError):\n p[:] = (1, 2, 3, 4, 5)\n\n def test_linestring_list_assignment(self):\n ls = LineString((0, 0), (1, 1))\n\n ls[:] = ()\n self.assertEqual(ls, LineString())\n\n ls[:] = ((0, 0), (1, 1), (2, 2))\n self.assertEqual(ls, LineString((0, 0), (1, 1), (2, 2)))\n\n with self.assertRaises(ValueError):\n ls[:] = (1,)\n\n def test_linearring_list_assignment(self):\n ls = LinearRing((0, 0), (0, 1), (1, 1), (0, 0))\n\n ls[:] = ()\n self.assertEqual(ls, LinearRing())\n\n ls[:] = ((0, 0), (0, 1), (1, 1), (1, 0), (0, 0))\n self.assertEqual(ls, LinearRing((0, 0), (0, 1), (1, 1), (1, 0), (0, 0)))\n\n with self.assertRaises(ValueError):\n ls[:] = ((0, 0), (1, 1), (2, 2))\n\n def test_polygon_list_assignment(self):\n pol = Polygon()\n\n pol[:] = (((0, 0), (0, 1), (1, 1), (1, 0), (0, 0)),)\n self.assertEqual(pol, Polygon(((0, 0), (0, 1), (1, 1), (1, 0), (0, 0)),))\n\n pol[:] = ()\n self.assertEqual(pol, Polygon())\n\n def test_geometry_collection_list_assignment(self):\n p = Point()\n gc = GeometryCollection()\n\n gc[:] = [p]\n self.assertEqual(gc, GeometryCollection(p))\n\n gc[:] = ()\n self.assertEqual(gc, GeometryCollection())\n\n def test_threed(self):\n \"Testing three-dimensional geometries.\"\n # Testing a 3D Point\n pnt = Point(2, 3, 8)\n self.assertEqual((2., 3., 8.), pnt.coords)\n with self.assertRaises(TypeError):\n pnt.tuple = (1., 2.)\n pnt.coords = (1., 2., 3.)\n self.assertEqual((1., 2., 3.), pnt.coords)\n\n # Testing a 3D LineString\n ls = LineString((2., 3., 8.), (50., 250., -117.))\n self.assertEqual(((2., 3., 8.), (50., 250., -117.)), ls.tuple)\n with self.assertRaises(TypeError):\n ls.__setitem__(0, (1., 2.))\n ls[0] = (1., 2., 3.)\n self.assertEqual((1., 2., 3.), ls[0])\n\n def test_distance(self):\n \"Testing the distance() function.\"\n # Distance to self should be 0.\n pnt = Point(0, 0)\n self.assertEqual(0.0, pnt.distance(Point(0, 0)))\n\n # Distance should be 1\n self.assertEqual(1.0, pnt.distance(Point(0, 1)))\n\n # Distance should be ~ sqrt(2)\n self.assertAlmostEqual(1.41421356237, pnt.distance(Point(1, 1)), 11)\n\n # Distances are from the closest vertex in each geometry --\n # should be 3 (distance from (2, 2) to (5, 2)).\n ls1 = LineString((0, 0), (1, 1), (2, 2))\n ls2 = LineString((5, 2), (6, 1), (7, 0))\n self.assertEqual(3, ls1.distance(ls2))\n\n def test_length(self):\n \"Testing the length property.\"\n # Points have 0 length.\n pnt = Point(0, 0)\n self.assertEqual(0.0, pnt.length)\n\n # Should be ~ sqrt(2)\n ls = LineString((0, 0), (1, 1))\n self.assertAlmostEqual(1.41421356237, ls.length, 11)\n\n # Should be circumference of Polygon\n poly = Polygon(LinearRing((0, 0), (0, 1), (1, 1), (1, 0), (0, 0)))\n self.assertEqual(4.0, poly.length)\n\n # Should be sum of each element's length in collection.\n mpoly = MultiPolygon(poly.clone(), poly)\n self.assertEqual(8.0, mpoly.length)\n\n def test_emptyCollections(self):\n \"Testing empty geometries and collections.\"\n geoms = [\n GeometryCollection([]),\n fromstr('GEOMETRYCOLLECTION EMPTY'),\n GeometryCollection(),\n fromstr('POINT EMPTY'),\n Point(),\n fromstr('LINESTRING EMPTY'),\n LineString(),\n fromstr('POLYGON EMPTY'),\n Polygon(),\n fromstr('MULTILINESTRING EMPTY'),\n MultiLineString(),\n fromstr('MULTIPOLYGON EMPTY'),\n MultiPolygon(()),\n MultiPolygon(),\n ]\n\n if numpy:\n geoms.append(LineString(numpy.array([])))\n\n for g in geoms:\n self.assertIs(g.empty, True)\n\n # Testing len() and num_geom.\n if isinstance(g, Polygon):\n self.assertEqual(1, len(g)) # Has one empty linear ring\n self.assertEqual(1, g.num_geom)\n self.assertEqual(0, len(g[0]))\n elif isinstance(g, (Point, LineString)):\n self.assertEqual(1, g.num_geom)\n self.assertEqual(0, len(g))\n else:\n self.assertEqual(0, g.num_geom)\n self.assertEqual(0, len(g))\n\n # Testing __getitem__ (doesn't work on Point or Polygon)\n if isinstance(g, Point):\n with self.assertRaises(IndexError):\n g.x\n elif isinstance(g, Polygon):\n lr = g.shell\n self.assertEqual('LINEARRING EMPTY', lr.wkt)\n self.assertEqual(0, len(lr))\n self.assertIs(lr.empty, True)\n with self.assertRaises(IndexError):\n lr.__getitem__(0)\n else:\n with self.assertRaises(IndexError):\n g.__getitem__(0)\n\n def test_collection_dims(self):\n gc = GeometryCollection([])\n self.assertEqual(gc.dims, -1)\n\n gc = GeometryCollection(Point(0, 0))\n self.assertEqual(gc.dims, 0)\n\n gc = GeometryCollection(LineString((0, 0), (1, 1)), Point(0, 0))\n self.assertEqual(gc.dims, 1)\n\n gc = GeometryCollection(LineString((0, 0), (1, 1)), Polygon(((0, 0), (0, 1), (1, 1), (0, 0))), Point(0, 0))\n self.assertEqual(gc.dims, 2)\n\n def test_collections_of_collections(self):\n \"Testing GeometryCollection handling of other collections.\"\n # Creating a GeometryCollection WKT string composed of other\n # collections and polygons.\n coll = [mp.wkt for mp in self.geometries.multipolygons if mp.valid]\n coll.extend(mls.wkt for mls in self.geometries.multilinestrings)\n coll.extend(p.wkt for p in self.geometries.polygons)\n coll.extend(mp.wkt for mp in self.geometries.multipoints)\n gc_wkt = 'GEOMETRYCOLLECTION(%s)' % ','.join(coll)\n\n # Should construct ok from WKT\n gc1 = GEOSGeometry(gc_wkt)\n\n # Should also construct ok from individual geometry arguments.\n gc2 = GeometryCollection(*tuple(g for g in gc1))\n\n # And, they should be equal.\n self.assertEqual(gc1, gc2)\n\n def test_gdal(self):\n \"Testing `ogr` and `srs` properties.\"\n g1 = fromstr('POINT(5 23)')\n self.assertIsInstance(g1.ogr, gdal.OGRGeometry)\n self.assertIsNone(g1.srs)\n\n g1_3d = fromstr('POINT(5 23 8)')\n self.assertIsInstance(g1_3d.ogr, gdal.OGRGeometry)\n self.assertEqual(g1_3d.ogr.z, 8)\n\n g2 = fromstr('LINESTRING(0 0, 5 5, 23 23)', srid=4326)\n self.assertIsInstance(g2.ogr, gdal.OGRGeometry)\n self.assertIsInstance(g2.srs, gdal.SpatialReference)\n self.assertEqual(g2.hex, g2.ogr.hex)\n self.assertEqual('WGS 84', g2.srs.name)\n\n def test_copy(self):\n \"Testing use with the Python `copy` module.\"\n import copy\n poly = GEOSGeometry('POLYGON((0 0, 0 23, 23 23, 23 0, 0 0), (5 5, 5 10, 10 10, 10 5, 5 5))')\n cpy1 = copy.copy(poly)\n cpy2 = copy.deepcopy(poly)\n self.assertNotEqual(poly._ptr, cpy1._ptr)\n self.assertNotEqual(poly._ptr, cpy2._ptr)\n\n def test_transform(self):\n \"Testing `transform` method.\"\n orig = GEOSGeometry('POINT (-104.609 38.255)', 4326)\n trans = GEOSGeometry('POINT (992385.4472045 481455.4944650)', 2774)\n\n # Using a srid, a SpatialReference object, and a CoordTransform object\n # for transformations.\n t1, t2, t3 = orig.clone(), orig.clone(), orig.clone()\n t1.transform(trans.srid)\n t2.transform(gdal.SpatialReference('EPSG:2774'))\n ct = gdal.CoordTransform(gdal.SpatialReference('WGS84'), gdal.SpatialReference(2774))\n t3.transform(ct)\n\n # Testing use of the `clone` keyword.\n k1 = orig.clone()\n k2 = k1.transform(trans.srid, clone=True)\n self.assertEqual(k1, orig)\n self.assertNotEqual(k1, k2)\n\n # Different PROJ versions use different transformations, all are\n # correct as having a 1 meter accuracy.\n prec = -1\n for p in (t1, t2, t3, k2):\n self.assertAlmostEqual(trans.x, p.x, prec)\n self.assertAlmostEqual(trans.y, p.y, prec)\n\n def test_transform_3d(self):\n p3d = GEOSGeometry('POINT (5 23 100)', 4326)\n p3d.transform(2774)\n self.assertAlmostEqual(p3d.z, 100, 3)\n\n def test_transform_noop(self):\n \"\"\" Testing `transform` method (SRID match) \"\"\"\n # transform() should no-op if source & dest SRIDs match,\n # regardless of whether GDAL is available.\n g = GEOSGeometry('POINT (-104.609 38.255)', 4326)\n gt = g.tuple\n g.transform(4326)\n self.assertEqual(g.tuple, gt)\n self.assertEqual(g.srid, 4326)\n\n g = GEOSGeometry('POINT (-104.609 38.255)', 4326)\n g1 = g.transform(4326, clone=True)\n self.assertEqual(g1.tuple, g.tuple)\n self.assertEqual(g1.srid, 4326)\n self.assertIsNot(g1, g, \"Clone didn't happen\")\n\n def test_transform_nosrid(self):\n \"\"\" Testing `transform` method (no SRID or negative SRID) \"\"\"\n\n g = GEOSGeometry('POINT (-104.609 38.255)', srid=None)\n with self.assertRaises(GEOSException):\n g.transform(2774)\n\n g = GEOSGeometry('POINT (-104.609 38.255)', srid=None)\n with self.assertRaises(GEOSException):\n g.transform(2774, clone=True)\n\n g = GEOSGeometry('POINT (-104.609 38.255)', srid=-1)\n with self.assertRaises(GEOSException):\n g.transform(2774)\n\n g = GEOSGeometry('POINT (-104.609 38.255)', srid=-1)\n with self.assertRaises(GEOSException):\n g.transform(2774, clone=True)\n\n def test_extent(self):\n \"Testing `extent` method.\"\n # The xmin, ymin, xmax, ymax of the MultiPoint should be returned.\n mp = MultiPoint(Point(5, 23), Point(0, 0), Point(10, 50))\n self.assertEqual((0.0, 0.0, 10.0, 50.0), mp.extent)\n pnt = Point(5.23, 17.8)\n # Extent of points is just the point itself repeated.\n self.assertEqual((5.23, 17.8, 5.23, 17.8), pnt.extent)\n # Testing on the 'real world' Polygon.\n poly = fromstr(self.geometries.polygons[3].wkt)\n ring = poly.shell\n x, y = ring.x, ring.y\n xmin, ymin = min(x), min(y)\n xmax, ymax = max(x), max(y)\n self.assertEqual((xmin, ymin, xmax, ymax), poly.extent)\n\n def test_pickle(self):\n \"Testing pickling and unpickling support.\"\n # Creating a list of test geometries for pickling,\n # and setting the SRID on some of them.\n def get_geoms(lst, srid=None):\n return [GEOSGeometry(tg.wkt, srid) for tg in lst]\n tgeoms = get_geoms(self.geometries.points)\n tgeoms.extend(get_geoms(self.geometries.multilinestrings, 4326))\n tgeoms.extend(get_geoms(self.geometries.polygons, 3084))\n tgeoms.extend(get_geoms(self.geometries.multipolygons, 3857))\n tgeoms.append(Point(srid=4326))\n tgeoms.append(Point())\n for geom in tgeoms:\n s1 = pickle.dumps(geom)\n g1 = pickle.loads(s1)\n self.assertEqual(geom, g1)\n self.assertEqual(geom.srid, g1.srid)\n\n def test_prepared(self):\n \"Testing PreparedGeometry support.\"\n # Creating a simple multipolygon and getting a prepared version.\n mpoly = GEOSGeometry('MULTIPOLYGON(((0 0,0 5,5 5,5 0,0 0)),((5 5,5 10,10 10,10 5,5 5)))')\n prep = mpoly.prepared\n\n # A set of test points.\n pnts = [Point(5, 5), Point(7.5, 7.5), Point(2.5, 7.5)]\n for pnt in pnts:\n # Results should be the same (but faster)\n self.assertEqual(mpoly.contains(pnt), prep.contains(pnt))\n self.assertEqual(mpoly.intersects(pnt), prep.intersects(pnt))\n self.assertEqual(mpoly.covers(pnt), prep.covers(pnt))\n\n self.assertTrue(prep.crosses(fromstr('LINESTRING(1 1, 15 15)')))\n self.assertTrue(prep.disjoint(Point(-5, -5)))\n poly = Polygon(((-1, -1), (1, 1), (1, 0), (-1, -1)))\n self.assertTrue(prep.overlaps(poly))\n poly = Polygon(((-5, 0), (-5, 5), (0, 5), (-5, 0)))", "answers": [" self.assertTrue(prep.touches(poly))"], "length": 4099, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "f46a60cf-7da7-475d-b101-e7053cb4a44e", "reasoning": "The test_prepared method is checking various spatial relationships using a prepared geometry. After testing overlaps with a polygon, the next logical check is for a polygon that only touches the multipolygon (sharing a boundary). The defined triangle (-5,0), (-5,5), (0,5) touches the multipolygon at (0,5), so the appropriate assertion is that the prepared geometry reports a touch relationship.", "reasoning_model_answer": "self.assertTrue(prep.touches(poly))", "assistant_with_reasoning": "\nThe test_prepared method is checking various spatial relationships using a prepared geometry. After testing overlaps with a polygon, the next logical check is for a polygon that only touches the multipolygon (sharing a boundary). The defined triangle (-5,0), (-5,5), (0,5) touches the multipolygon at (0,5), so the appropriate assertion is that the prepared geometry reports a touch relationship.\n\nself.assertTrue(prep.touches(poly))", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 8.605, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 48004, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "self.assertTrue(prep.touches(poly))", "score": 0.9, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "import os\n\ndef add_source_files(self, sources, filetype, lib_env = None, shared = False):\n\timport glob;\n\timport string;\n\t#if not lib_objects:\n\tif not lib_env:\n\t\tlib_env = self\n\tif type(filetype) == type(\"\"):\n\n\t\tdir = self.Dir('.').abspath\n\t\tlist = glob.glob(dir + \"/\"+filetype)\n\t\tfor f in list:\n\t\t\tsources.append( self.Object(f) )\n\telse:\n\t\tfor f in filetype:\n\t\t\tsources.append(self.Object(f))\n\n\ndef build_shader_header( target, source, env ):\n\n\tfor x in source:\n\t\tprint x\n\n\t\tname = str(x)\n\t\tname = name[ name.rfind(\"/\")+1: ]\n\t\tname = name[ name.rfind(\"\\\\\")+1: ]\n\t\tname = name.replace(\".\",\"_\")\n\n\n\t\tfs = open(str(x),\"r\")\n\t\tfd = open(str(x)+\".h\",\"w\")\n\t\tfd.write(\"/* this file has been generated by SCons, do not edit! */\\n\")\n\t\tfd.write(\"static const char *\"+name+\"=\\n\")\n\t\tline=fs.readline()\n\t\twhile(line):\n\t\t\tline=line.replace(\"\\r\",\"\")\n\t\t\tline=line.replace(\"\\n\",\"\")\n\t\t\tline=line.replace(\"\\\\\",\"\\\\\\\\\")\n\t\t\tline=line.replace(\"\\\"\",\"\\\\\\\"\")\n\t\t\tfd.write(\"\\\"\"+line+\"\\\\n\\\"\\n\")\n\t\t\tline=fs.readline()\n\n\t\tfd.write(\";\\n\")\n\n\treturn 0\n\n\ndef build_glsl_header( filename ):\n\n\tfs = open(filename,\"r\")\n\tline=fs.readline()\n\n\tvertex_lines=[]\n\tfragment_lines=[]\n\tuniforms=[]\n\tattributes=[]\n\tfbos=[]\n\tconditionals=[]\n\ttexunits=[]\n\ttexunit_names=[]\n\tubos=[]\n\tubo_names=[]\n\n\treading=\"\"\n\tline_offset=0\n\tvertex_offset=0\n\tfragment_offset=0\n\n\twhile(line):\n\n\t\tif (line.find(\"[vertex]\")!=-1):\n\t\t\treading=\"vertex\"\n\t\t\tline=fs.readline()\n\t\t\tline_offset+=1\n\t\t\tvertex_offset=line_offset\n\t\t\tcontinue\n\n\t\tif (line.find(\"[fragment]\")!=-1):\n\t\t\treading=\"fragment\"\n\t\t\tline=fs.readline()\n\t\t\tline_offset+=1\n\t\t\tfragment_offset=line_offset\n\t\t\tcontinue\n\n\t\tif (line.find(\"#ifdef \")!=-1):\n\t\t\tifdefline = line.replace(\"#ifdef \",\"\").strip()\n\t\t\tif (not ifdefline in conditionals):\n\t\t\t\tconditionals+=[ifdefline]\n\n\t\tif (line.find(\"#elif defined(\")!=-1):\n\t\t\tifdefline = line.replace(\"#elif defined(\",\"\").strip()\n\t\t\tifdefline = ifdefline.replace(\")\",\"\").strip()\n\t\t\tif (not ifdefline in conditionals):\n\t\t\t\tconditionals+=[ifdefline]\n\n\n\t\timport re\n\t\tif re.search(r\"^\\s*uniform\", line):\n\n\t\t\tif (line.lower().find(\"texunit:\")!=-1):\n\t\t\t\t#texture unit\n\t\t\t\ttexunit = str(int( line[line.find(\":\")+1:].strip() ))\n\t\t\t\tuline=line[:line.lower().find(\"//\")]\n\t\t\t\tuline = uline.replace(\"uniform\",\"\");\n\t\t\t\tuline = uline.replace(\";\",\"\");\n\t\t\t\tlines = uline.split(\",\")\n\t\t\t\tfor x in lines:\n\n\t\t\t\t\tx = x.strip()\n\t\t\t\t\tx = x[ x.rfind(\" \")+1: ]\n\t\t\t\t\tif (x.find(\"[\")!=-1):\n\t\t\t\t\t\t#unfiorm array\n\t\t\t\t\t\tx = x[ :x.find(\"[\") ]\n\n\t\t\t\t\tif (not x in texunit_names):\n\t\t\t\t\t\ttexunits+=[(x,texunit)]\n\t\t\t\t\t\ttexunit_names+=[x]\n\n\t\t\telif (line.lower().find(\"ubo:\")!=-1):\n\t\t\t\t#ubo\n\t\t\t\tuboidx = str(int( line[line.find(\":\")+1:].strip() ))\n\t\t\t\tuline=line[:line.lower().find(\"//\")]\n\t\t\t\tuline = uline[uline.find(\"uniform\")+len(\"uniform\"):];\n\t\t\t\tuline = uline.replace(\";\",\"\");\n\t\t\t\tuline = uline.replace(\"{\",\"\");\n\t\t\t\tlines = uline.split(\",\")\n\t\t\t\tfor x in lines:\n\n\t\t\t\t\tx = x.strip()\n\t\t\t\t\tx = x[ x.rfind(\" \")+1: ]\n\t\t\t\t\tif (x.find(\"[\")!=-1):\n\t\t\t\t\t\t#unfiorm array\n\t\t\t\t\t\tx = x[ :x.find(\"[\") ]\n\n\t\t\t\t\tif (not x in ubo_names):\n\t\t\t\t\t\tubos+=[(x,uboidx)]\n\t\t\t\t\t\tubo_names+=[x]\n\n\n\n\t\t\telse:\n\t\t\t\tuline = line.replace(\"uniform\",\"\");\n\t\t\t\tuline = uline.replace(\";\",\"\");\n\t\t\t\tlines = uline.split(\",\")\n\t\t\t\tfor x in lines:\n\n\t\t\t\t\tx = x.strip()\n\t\t\t\t\tx = x[ x.rfind(\" \")+1: ]\n\t\t\t\t\tif (x.find(\"[\")!=-1):\n\t\t\t\t\t\t#unfiorm array\n\t\t\t\t\t\tx = x[ :x.find(\"[\") ]\n\n\t\t\t\t\tif (not x in uniforms):\n\t\t\t\t\t\tuniforms+=[x]\n\n\t\tif ((line.strip().find(\"in \")==0 or line.strip().find(\"attribute \")==0) and line.find(\"attrib:\")!=-1):\n\t\t\tuline = line.replace(\"in \",\"\");\n\t\t\tuline = uline.replace(\"attribute \",\"\");\n\t\t\tuline = uline.replace(\";\",\"\");\n\t\t\tuline = uline[ uline.find(\" \"): ].strip()\n\n\n\t\t\tif (uline.find(\"//\")!=-1):\n\t\t\t\tname,bind = uline.split(\"//\")\n\t\t\t\tif (bind.find(\"attrib:\")!=-1):\n\t\t\t\t\tname=name.strip()\n\t\t\t\t\tbind=bind.replace(\"attrib:\",\"\").strip()\n\t\t\t\t\tattributes+=[(name,bind)]\n\n\t\tif (line.strip().find(\"out \")==0):\n\t\t\tuline = line.replace(\"out\",\"\").strip();\n\t\t\tuline = uline.replace(\";\",\"\");\n\t\t\tuline = uline[ uline.find(\" \"): ].strip()\n\n\n\t\t\tif (uline.find(\"//\")!=-1):\n\t\t\t\tname,bind = uline.split(\"//\")\n\t\t\t\tif (bind.find(\"drawbuffer:\")!=-1):\n\t\t\t\t\tname=name.strip()\n\t\t\t\t\tbind=bind.replace(\"drawbuffer:\",\"\").strip()\n\t\t\t\t\tfbos+=[(name,bind)]\n\n\t\tline=line.replace(\"\\r\",\"\")\n\t\tline=line.replace(\"\\n\",\"\")\n\t\tline=line.replace(\"\\\\\",\"\\\\\\\\\")\n\t\tline=line.replace(\"\\\"\",\"\\\\\\\"\")\n\t\t#line=line+\"\\\\n\\\\\" no need to anymore\n\n\t\tif (reading==\"vertex\"):\n\t\t\tvertex_lines+=[line]\n\t\tif (reading==\"fragment\"):\n\t\t\tfragment_lines+=[line]\n\n\t\tline=fs.readline()\n\t\tline_offset+=1\n\n\tfs.close();\n\n\tout_file = filename+\".h\"\n\tfd = open(out_file,\"w\")\n\n\tfd.write(\"/* WARNING, THIS FILE WAS GENERATED, DO NOT EDIT */\\n\");\n\n\tout_file_base = out_file\n\tout_file_base = out_file_base[ out_file_base.rfind(\"/\")+1: ]\n\tout_file_base = out_file_base[ out_file_base.rfind(\"\\\\\")+1: ]\n#\tprint(\"out file \"+out_file+\" base \" +out_file_base)\n\tout_file_ifdef = out_file_base.replace(\".\",\"_\").upper()\n\tfd.write(\"#ifndef \"+out_file_ifdef+\"\\n\")\n\tfd.write(\"#define \"+out_file_ifdef+\"\\n\")\n\n\tout_file_class = out_file_base.replace(\".glsl.h\",\"\").title().replace(\"_\",\"\").replace(\".\",\"\")+\"ShaderGL\";\n\tfd.write(\"\\n\\n\");\n\tfd.write(\"#include \\\"drivers/opengl/shader_gl.h\\\"\\n\\n\\n\");\n\tfd.write(\"class \"+out_file_class+\" : public ShaderGL {\\n\\n\");\n\tfd.write(\"\\t virtual String get_shader_name() const { return \\\"\"+out_file_class+\"\\\"; }\\n\");\n\tfd.write(\"public:\\n\\n\");\n\n\tif (len(conditionals)):\n\t\tfd.write(\"\\tenum Conditionals {\\n\");\n\t\tfor x in conditionals:\n\t\t\tfd.write(\"\\t\\t\"+x+\",\\n\");\n\t\tfd.write(\"\\t};\\n\\n\");\n\tif (len(uniforms)):\n\t\tfd.write(\"\\tenum Uniforms {\\n\");\n\t\tfor x in uniforms:\n\t\t\tfd.write(\"\\t\\t\"+x.upper()+\",\\n\");\n\t\tfd.write(\"\\t};\\n\\n\");\n\n\tfd.write(\"\\t_FORCE_INLINE_ int get_uniform(Uniforms p_uniform) const { return _get_uniform(p_uniform); }\\n\\n\");\n\tif (len(conditionals)):\n\n\t\tfd.write(\"\\t_FORCE_INLINE_ void set_conditional(Conditionals p_conditional,bool p_enable) { _set_conditional(p_conditional,p_enable); }\\n\\n\");\n\tfd.write(\"\\t#define _FU if (get_uniform(p_uniform)<0) return; ERR_FAIL_COND( get_active()!=this );\\n\\n \");\n\tfd.write(\"\\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, float p_value) { _FU glUniform1f(get_uniform(p_uniform),p_value); }\\n\\n\");\n\tfd.write(\"\\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, double p_value) { _FU glUniform1f(get_uniform(p_uniform),p_value); }\\n\\n\");\n\tfd.write(\"\\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, uint8_t p_value) { _FU glUniform1i(get_uniform(p_uniform),p_value); }\\n\\n\");\n\tfd.write(\"\\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, int8_t p_value) { _FU glUniform1i(get_uniform(p_uniform),p_value); }\\n\\n\");\n\tfd.write(\"\\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, uint16_t p_value) { _FU glUniform1i(get_uniform(p_uniform),p_value); }\\n\\n\");\n\tfd.write(\"\\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, int16_t p_value) { _FU glUniform1i(get_uniform(p_uniform),p_value); }\\n\\n\");\n\tfd.write(\"\\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, uint32_t p_value) { _FU glUniform1i(get_uniform(p_uniform),p_value); }\\n\\n\");\n\tfd.write(\"\\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, int32_t p_value) { _FU glUniform1i(get_uniform(p_uniform),p_value); }\\n\\n\");\n\t#fd.write(\"\\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, uint64_t p_value) { _FU glUniform1i(get_uniform(p_uniform),p_value); }\\n\\n\");\n\t#fd.write(\"\\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, int64_t p_value) { _FU glUniform1i(get_uniform(p_uniform),p_value); }\\n\\n\");\n\tfd.write(\"\\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, unsigned long p_value) { _FU glUniform1i(get_uniform(p_uniform),p_value); }\\n\\n\");\n\tfd.write(\"\\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, long p_value) { _FU glUniform1i(get_uniform(p_uniform),p_value); }\\n\\n\");\n\tfd.write(\"\\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, const Color& p_color) { _FU GLfloat col[4]={p_color.r,p_color.g,p_color.b,p_color.a}; glUniform4fv(get_uniform(p_uniform),1,col); }\\n\\n\");\n\tfd.write(\"\\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, const Vector2& p_vec2) { _FU GLfloat vec2[2]={p_vec2.x,p_vec2.y}; glUniform2fv(get_uniform(p_uniform),1,vec2); }\\n\\n\");\n\tfd.write(\"\\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, const Vector3& p_vec3) { _FU GLfloat vec3[3]={p_vec3.x,p_vec3.y,p_vec3.z}; glUniform3fv(get_uniform(p_uniform),1,vec3); }\\n\\n\");\n\tfd.write(\"\\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, float p_a, float p_b) { _FU glUniform2f(get_uniform(p_uniform),p_a,p_b); }\\n\\n\");\n\tfd.write(\"\\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, float p_a, float p_b, float p_c) { _FU glUniform3f(get_uniform(p_uniform),p_a,p_b,p_c); }\\n\\n\");\n\tfd.write(\"\\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, float p_a, float p_b, float p_c, float p_d) { _FU glUniform4f(get_uniform(p_uniform),p_a,p_b,p_c,p_d); }\\n\\n\");\n\n\tfd.write(\"\"\"\\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, const Transform& p_transform) { _FU\n\n\t\tconst Transform &tr = p_transform;\n\n\t\tGLfloat matrix[16]={ /* build a 16x16 matrix */\n\t\t\ttr.basis.elements[0][0],\n\t\t\ttr.basis.elements[1][0],\n\t\t\ttr.basis.elements[2][0],\n\t\t\t0,\n\t\t\ttr.basis.elements[0][1],\n\t\t\ttr.basis.elements[1][1],\n\t\t\ttr.basis.elements[2][1],\n\t\t\t0,\n\t\t\ttr.basis.elements[0][2],\n\t\t\ttr.basis.elements[1][2],\n\t\t\ttr.basis.elements[2][2],\n\t\t\t0,\n\t\t\ttr.origin.x,\n\t\t\ttr.origin.y,\n\t\t\ttr.origin.z,\n\t\t\t1\n\t\t};\n\n\n\tglUniformMatrix4fv(get_uniform(p_uniform),1,false,matrix);\n\n\n\t}\n\n\t\"\"\");\n\n\tfd.write(\"\"\"\\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, const Matrix32& p_transform) { _FU\n\n\t\tconst Matrix32 &tr = p_transform;\n\n\t\tGLfloat matrix[16]={ /* build a 16x16 matrix */\n\t\t\ttr.elements[0][0],\n\t\t\ttr.elements[0][1],\n\t\t\t0,\n\t\t\t0,\n\t\t\ttr.elements[1][0],\n\t\t\ttr.elements[1][1],\n\t\t\t0,\n\t\t\t0,\n\t\t\t0,\n\t\t\t0,\n\t\t\t1,\n\t\t\t0,\n\t\t\ttr.elements[2][0],\n\t\t\ttr.elements[2][1],\n\t\t\t0,\n\t\t\t1\n\t\t};\n\n\n\tglUniformMatrix4fv(get_uniform(p_uniform),1,false,matrix);\n\n\n\t}\n\n\t\"\"\");\n\n\tfd.write(\"\"\"\\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, const CameraMatrix& p_matrix) { _FU\n\n\t\tGLfloat matrix[16];\n\n\t\tfor (int i=0;i<4;i++) {\n\t\t\tfor (int j=0;j<4;j++) {\n\n\t\t\t\tmatrix[i*4+j]=p_matrix.matrix[i][j];\n\t\t\t}\n\t\t}\n\n\t\tglUniformMatrix4fv(get_uniform(p_uniform),1,false,matrix);\n\t}; \"\"\");\n\n\tfd.write(\"\\n\\n#undef _FU\\n\\n\\n\");\n\n\n\tfd.write(\"\\tvirtual void init() {\\n\\n\");\n\tif (len(conditionals)):\n\n\t\tfd.write(\"\\t\\tstatic const char* _conditional_strings[]={\\n\")\n\t\tif (len(conditionals)):\n\t\t\tfor x in conditionals:\n\t\t\t\tfd.write(\"\\t\\t\\t\\\"#define \"+x+\"\\\\n\\\",\\n\");\n\t\tfd.write(\"\\t\\t};\\n\\n\");\n\telse:\n\t\tfd.write(\"\\t\\tstatic const char **_conditional_strings=NULL;\\n\")\n\n\tif (len(uniforms)):\n\n\t\tfd.write(\"\\t\\tstatic const char* _uniform_strings[]={\\n\")\n\t\tif (len(uniforms)):\n\t\t\tfor x in uniforms:\n\t\t\t\tfd.write(\"\\t\\t\\t\\\"\"+x+\"\\\",\\n\");\n\t\tfd.write(\"\\t\\t};\\n\\n\");\n\telse:\n\t\tfd.write(\"\\t\\tstatic const char **_uniform_strings=NULL;\\n\")\n\n\tif (len(attributes)):\n\n\t\tfd.write(\"\\t\\tstatic AttributePair _attribute_pairs[]={\\n\")\n\t\tfor x in attributes:\n\t\t\tfd.write(\"\\t\\t\\t{\\\"\"+x[0]+\"\\\",\"+x[1]+\"},\\n\");\n\t\tfd.write(\"\\t\\t};\\n\\n\");\n\telse:\n\t\tfd.write(\"\\t\\tstatic AttributePair *_attribute_pairs=NULL;\\n\")\n\n\n\n\tif (len(fbos)):\n\t\tfd.write(\"\\t\\tstatic FBOPair _fbo_pairs[]={\\n\")\n\t\tfor x in fbos:\n\t\t\tfd.write(\"\\t\\t\\t{\\\"\"+x[0]+\"\\\",\"+x[1]+\"},\\n\");\n\t\tfd.write(\"\\t\\t};\\n\\n\");\n\telse:\n\t\tfd.write(\"\\t\\tstatic FBOPair *_fbo_pairs=NULL;\\n\")\n\n\tif (len(ubos)):\n\t\tfd.write(\"\\t\\tstatic UBOPair _ubo_pairs[]={\\n\")\n\t\tfor x in ubos:\n\t\t\tfd.write(\"\\t\\t\\t{\\\"\"+x[0]+\"\\\",\"+x[1]+\"},\\n\");\n\t\tfd.write(\"\\t\\t};\\n\\n\");\n\telse:\n\t\tfd.write(\"\\t\\tstatic UBOPair *_ubo_pairs=NULL;\\n\")\n\n\tif (len(texunits)):\n\t\tfd.write(\"\\t\\tstatic TexUnitPair _texunit_pairs[]={\\n\")\n\t\tfor x in texunits:\n\t\t\tfd.write(\"\\t\\t\\t{\\\"\"+x[0]+\"\\\",\"+x[1]+\"},\\n\");\n\t\tfd.write(\"\\t\\t};\\n\\n\");\n\telse:\n\t\tfd.write(\"\\t\\tstatic TexUnitPair *_texunit_pairs=NULL;\\n\")\n\n\tfd.write(\"\\t\\tstatic const char* _vertex_code=\\\"\\\\\\n\")\n\tfor x in vertex_lines:\n\t\tfd.write(\"\\t\\t\\t\"+x+\"\\n\");\n\tfd.write(\"\\t\\t\\\";\\n\\n\");\n\n\tfd.write(\"\\t\\tstatic const int _vertex_code_start=\"+str(vertex_offset)+\";\\n\")\n\n\n\tfd.write(\"\\t\\tstatic const char* _fragment_code=\\\"\\\\\\n\")\n\tfor x in fragment_lines:\n\t\tfd.write(\"\\t\\t\\t\"+x+\"\\n\");\n\tfd.write(\"\\t\\t\\\";\\n\\n\");\n\n\tfd.write(\"\\t\\tstatic const int _fragment_code_start=\"+str(fragment_offset)+\";\\n\")\n\n\tfd.write(\"\\t\\tsetup(_conditional_strings,\"+str(len(conditionals))+\",_uniform_strings,\"+str(len(uniforms))+\",_attribute_pairs,\"+str(len(attributes))+\",_fbo_pairs,\"+str(len(fbos))+\",_ubo_pairs,\"+str(len(ubos))+\",_texunit_pairs,\"+str(len(texunits))+\",_vertex_code,_fragment_code,_vertex_code_start,_fragment_code_start);\\n\")\n\tfd.write(\"\\t};\\n\\n\")\n\n\tfd.write(\"};\\n\\n\");\n\tfd.write(\"#endif\\n\\n\");\n\tfd.close();\n\n\ndef build_glsl_headers( target, source, env ):\n\n\tfor x in source:\n\n\t\tbuild_glsl_header(str(x));\n\n\n\treturn 0\n\n\n\ndef build_hlsl_dx9_header( filename ):\n\n\tfs = open(filename,\"r\")\n\tline=fs.readline()\n\n\tvertex_lines=[]\n\tfragment_lines=[]\n\tuniforms=[]\n\tfragment_uniforms=[]\n\tattributes=[]\n\tfbos=[]\n\tconditionals=[]\n\n\treading=\"\"\n\tline_offset=0\n\tvertex_offset=0\n\tfragment_offset=0\n\n\twhile(line):\n\n\t\tif (line.find(\"[vertex]\")!=-1):\n\t\t\treading=\"vertex\"\n\t\t\tline=fs.readline()\n\t\t\tline_offset+=1\n\t\t\tvertex_offset=line_offset\n\t\t\tcontinue\n\n\t\tif (line.find(\"[fragment]\")!=-1):\n\t\t\treading=\"fragment\"\n\t\t\tline=fs.readline()\n\t\t\tline_offset+=1\n\t\t\tfragment_offset=line_offset\n\t\t\tcontinue\n\n\t\tif (line.find(\"#ifdef \")!=-1):\n\t\t\tifdefline = line.replace(\"#ifdef \",\"\").strip()\n\t\t\tif (not ifdefline in conditionals):\n\t\t\t\tconditionals+=[ifdefline]\n\n\t\tif (line.find(\"#elif defined(\")!=-1):\n\t\t\tifdefline = line.replace(\"#elif defined(\",\"\").strip()\n\t\t\tifdefline = ifdefline.replace(\")\",\"\").strip()\n\t\t\tif (not ifdefline in conditionals):\n\t\t\t\tconditionals+=[ifdefline]\n\t\tif (line.find(\"uniform\")!=-1):\n\t\t\tuline = line.replace(\"uniform\",\"\");\n\t\t\tuline = uline.replace(\";\",\"\");\n\t\t\tlines = uline.split(\",\")\n\t\t\tfor x in lines:\n\n\t\t\t\tx = x.strip()\n\t\t\t\tx = x[ x.rfind(\" \")+1: ]\n\t\t\t\tif (x.find(\"[\")!=-1):\n\t\t\t\t\t#unfiorm array\n\t\t\t\t\tx = x[ :x.find(\"[\") ]\n\n\t\t\t\tif (not x in uniforms):\n\t\t\t\t\tuniforms+=[x]\n\t\t\t\t\tfragment_uniforms+=[reading==\"fragment\"]\n\t\tline=line.replace(\"\\r\",\"\")\n\t\tline=line.replace(\"\\n\",\"\")\n\t\tline=line.replace(\"\\\\\",\"\\\\\\\\\")\n\t\tline=line.replace(\"\\\"\",\"\\\\\\\"\")\n\t\tline=line+\"\\\\n\\\\\"\n\n\t\tif (reading==\"vertex\"):\n\t\t\tvertex_lines+=[line]\n\t\tif (reading==\"fragment\"):\n\t\t\tfragment_lines+=[line]\n\n\t\tline=fs.readline()\n\t\tline_offset+=1\n\n\tfs.close();\n\n\tout_file = filename+\".h\"\n\tfd = open(out_file,\"w\")\n\n\tfd.write(\"/* WARNING, THIS FILE WAS GENERATED, DO NOT EDIT */\\n\");\n\n\tout_file_base = out_file\n\tout_file_base = out_file_base[ out_file_base.rfind(\"/\")+1: ]\n\tout_file_base = out_file_base[ out_file_base.rfind(\"\\\\\")+1: ]\n#\tprint(\"out file \"+out_file+\" base \" +out_file_base)\n\tout_file_ifdef = out_file_base.replace(\".\",\"_\").upper()\n\tfd.write(\"#ifndef \"+out_file_ifdef+\"\\n\")\n\tfd.write(\"#define \"+out_file_ifdef+\"\\n\")\n\n\tout_file_class = out_file_base.replace(\".hlsl.h\",\"\").title().replace(\"_\",\"\").replace(\".\",\"\")+\"ShaderDX9\";\n\tfd.write(\"\\n\\n\");\n\tfd.write(\"#include \\\"drivers/directx9/shader_dx9.h\\\"\\n\\n\\n\");\n\tfd.write(\"class \"+out_file_class+\" : public ShaderDX9 {\\n\\n\");\n\tfd.write(\"\\t virtual String get_shader_name() const { return \\\"\"+out_file_class+\"\\\"; }\\n\");\n\tfd.write(\"public:\\n\\n\");\n\n\tif (len(conditionals)):\n\t\tfd.write(\"\\tenum Conditionals {\\n\");\n\t\tfor x in conditionals:\n\t\t\tfd.write(\"\\t\\t\"+x+\",\\n\");\n\t\tfd.write(\"\\t};\\n\\n\");\n\tif (len(uniforms)):\n\t\tfd.write(\"\\tenum Uniforms {\\n\");\n\t\tfor x in uniforms:\n\t\t\tfd.write(\"\\t\\t\"+x.upper()+\",\\n\");\n\t\tfd.write(\"\\t};\\n\\n\");\n\n\n\tif (len(conditionals)):\n\t\tfd.write(\"\\t_FORCE_INLINE_ void set_conditional(Conditionals p_conditional,bool p_enable) { _set_conditional(p_conditional,p_enable); }\\n\\n\");\n\n\tfd.write(\"\\t#define _FU if (!_uniform_valid(p_uniform)) return; ERR_FAIL_COND( get_active()!=this );\\n\\n \");\n\tfd.write(\"\\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, bool p_value) { _FU set_uniformb(p_uniform,p_value); }\\n\\n\");\n\tfd.write(\"\\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, float p_value) { _FU set_uniformf(p_uniform,p_value); }\\n\\n\");\n\tfd.write(\"\\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, double p_value) { _FU set_uniformf(p_uniform,p_value); }\\n\\n\");\n\tfd.write(\"\\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, uint8_t p_value) { _FU set_uniformi(p_uniform,p_value); }\\n\\n\");\n\tfd.write(\"\\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, int8_t p_value) { _FU set_uniformi(p_uniform,p_value); }\\n\\n\");\n\tfd.write(\"\\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, uint16_t p_value) { _FU set_uniformi(p_uniform,p_value); }\\n\\n\");\n\tfd.write(\"\\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, int16_t p_value) { _FU set_uniformi(p_uniform,p_value); }\\n\\n\");\n\tfd.write(\"\\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, uint32_t p_value) { _FU set_uniformi(p_uniform,p_value); }\\n\\n\");\n\tfd.write(\"\\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, int32_t p_value) { _FU set_uniformi(p_uniform,p_value); }\\n\\n\");\n\t#fd.write(\"\\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, uint64_t p_value) { _FU set_uniformi(p_uniform,p_value); }\\n\\n\");\n\t#fd.write(\"\\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, int64_t p_value) { _FU set_uniformi(p_uniform,p_value); }\\n\\n\");\n\tfd.write(\"\\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, unsigned long p_value) { _FU set_uniformi(p_uniform,p_value); }\\n\\n\");\n\tfd.write(\"\\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, long p_value) { _FU set_uniformi(p_uniform,p_value); }\\n\\n\");\n\tfd.write(\"\\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, const Color& p_color) { _FU float col[4]={p_color.r,p_color.g,p_color.b,p_color.a}; set_uniformfv(p_uniform,col); }\\n\\n\");\n\tfd.write(\"\\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, const Vector2& p_vec2) { _FU float vec2[4]={p_vec2.x,p_vec2.y,0,0}; set_uniformfv(p_uniform,vec2); }\\n\\n\");\n\tfd.write(\"\\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, const Vector3& p_vec3) { _FU float vec3[4]={p_vec3.x,p_vec3.y,p_vec3.z,0}; set_uniformfv(p_uniform,vec3); }\\n\\n\");\n\tfd.write(\"\\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, float p_a, float p_b) { _FU float vec2[4]={p_a,p_b,0,0}; set_uniformfv(p_uniform,vec2); }\\n\\n\");\n\tfd.write(\"\\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, float p_a, float p_b, float p_c) { _FU float vec3[4]={p_a,p_b,p_c,0}; set_uniformfv(p_uniform,vec3); }\\n\\n\");\n\tfd.write(\"\\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, float p_a, float p_b, float p_c, float p_d) { _FU float vec4[4]={p_a,p_b,p_c,p_d}; set_uniformfv(p_uniform,vec4); }\\n\\n\");\n\n\tfd.write(\"\"\"\\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, const Transform& p_transform) { _FU\n\n\t\tconst Transform &tr = p_transform;\n\n\t\tfloat matrix[16]={ /* build a 16x16 matrix */\n\t\t\ttr.basis.elements[0][0],\n\t\t\ttr.basis.elements[0][1],\n\t\t\ttr.basis.elements[0][2],\n\t\t\ttr.origin.x,\n\t\t\ttr.basis.elements[1][0],\n\t\t\ttr.basis.elements[1][1],\n\t\t\ttr.basis.elements[1][2],\n\t\t\ttr.origin.y,\n\t\t\ttr.basis.elements[2][0],\n\t\t\ttr.basis.elements[2][1],\n\t\t\ttr.basis.elements[2][2],\n\t\t\ttr.origin.z,\n\t\t\t0,\n\t\t\t0,\n\t\t\t0,\n\t\t\t1\n\t\t};\n\n\t\tset_uniformfv(p_uniform,&matrix[0],4);\n\n\t}\n\n\t\"\"\");\n\n\tfd.write(\"\"\"\\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, const CameraMatrix& p_matrix) { _FU\n\n\t\tfloat matrix[16];\n\n\t\tfor (int i=0;i<4;i++) {\n\t\t\tfor (int j=0;j<4;j++) {\n\n\t\t\t\tmatrix[i*4+j]=p_matrix.matrix[j][i];\n\t\t\t}\n\t\t}\n\n\t\tset_uniformfv(p_uniform,&matrix[0],4);\n\t}; \"\"\");\n\n\tfd.write(\"\\n\\n#undef _FU\\n\\n\\n\");\n\n\n\tfd.write(\"\\tvirtual void init(IDirect3DDevice9 *p_device,ShaderSupport p_version) {\\n\\n\");\n\tif (len(conditionals)):\n\n\t\tfd.write(\"\\t\\tstatic const char* _conditional_strings[]={\\n\")\n\t\tif (len(conditionals)):\n\t\t\tfor x in conditionals:\n\t\t\t\tfd.write(\"\\t\\t\\t\\\"\"+x+\"\\\",\\n\");\n\t\tfd.write(\"\\t\\t};\\n\\n\");\n\telse:\n\t\tfd.write(\"\\t\\tstatic const char **_conditional_strings=NULL;\\n\")\n\n\tif (len(uniforms)):\n\n\t\tfd.write(\"\\t\\tstatic const char* _uniform_strings[]={\\n\")\n\t\tif (len(uniforms)):\n\t\t\tfor x in uniforms:\n\t\t\t\tfd.write(\"\\t\\t\\t\\\"\"+x+\"\\\",\\n\");\n\t\tfd.write(\"\\t\\t};\\n\\n\");\n\n\t\tfd.write(\"\\t\\tstatic const bool _fragment_uniforms[]={\\n\")\n\n\t\tif (len(uniforms)):\n\t\t\tfor x in fragment_uniforms:\n\t\t\t\tif (x):\n\t\t\t\t\tfd.write(\"\\t\\t\\ttrue,\\n\");\n\t\t\t\telse:\n\t\t\t\t\tfd.write(\"\\t\\t\\tfalse,\\n\");\n\t\tfd.write(\"\\t\\t};\\n\\n\");\n\telse:\n\t\tfd.write(\"\\t\\tstatic const char **_uniform_strings=NULL;\\n\")\n\t\tfd.write(\"\\t\\tstatic const bool *_fragment_uniforms=NULL;\\n\")\n\n\n\tfd.write(\"\\t\\tstatic const char* _vertex_code=\\\"\\\\\\n\")\n\tfor x in vertex_lines:\n\t\tfd.write(\"\\t\\t\\t\"+x+\"\\n\");\n\tfd.write(\"\\t\\t\\\";\\n\\n\");\n\n\tfd.write(\"\\t\\tstatic const int _vertex_code_start=\"+str(vertex_offset)+\";\\n\")\n\n\n\tfd.write(\"\\t\\tstatic const char* _fragment_code=\\\"\\\\\\n\")\n\tfor x in fragment_lines:\n\t\tfd.write(\"\\t\\t\\t\"+x+\"\\n\");\n\tfd.write(\"\\t\\t\\\";\\n\\n\");\n\n\tfd.write(\"\\t\\tstatic const int _fragment_code_start=\"+str(fragment_offset)+\";\\n\")\n\n\tfd.write(\"\\t\\tsetup(p_device,p_version,_conditional_strings,\"+str(len(conditionals))+\",_uniform_strings,\"+str(len(uniforms))+\",_fragment_uniforms,_vertex_code,_fragment_code,_vertex_code_start,_fragment_code_start);\\n\")\n\tfd.write(\"\\t};\\n\\n\")\n\n\tfd.write(\"};\\n\\n\");\n\tfd.write(\"#endif\\n\\n\");\n\tfd.close();\n\n\ndef build_hlsl_dx9_headers( target, source, env ):\n\n\tfor x in source:\n\n\t\tbuild_hlsl_dx9_header(str(x));\n\n\n\treturn 0\n\n\nclass LegacyGLHeaderStruct:\n\tdef __init__(self):\n\t\tself.vertex_lines=[]\n\t\tself.fragment_lines=[]\n\t\tself.uniforms=[]\n\t\tself.attributes=[]\n\t\tself.fbos=[]\n\t\tself.conditionals=[]\n\t\tself.enums={}\n\t\tself.texunits=[]\n\t\tself.texunit_names=[]\n\t\tself.ubos=[]\n\t\tself.ubo_names=[]\n\t\t\n\t\tself.vertex_included_files=[]\n\t\tself.fragment_included_files=[]\n\t\t\n\t\tself.reading=\"\"\n\t\tself.line_offset=0\n\t\tself.vertex_offset=0\n\t\tself.fragment_offset=0\n\t\ndef include_file_in_legacygl_header( filename, header_data, depth ):\n\tfs = open(filename,\"r\")\n\tline=fs.readline()\n\n\twhile(line):\n\n\t\tif (line.find(\"[vertex]\")!=-1):\n\t\t\theader_data.reading=\"vertex\"\n\t\t\tline=fs.readline()\n\t\t\theader_data.line_offset+=1\n\t\t\theader_data.vertex_offset=header_data.line_offset\n\t\t\tcontinue\n\n\t\tif (line.find(\"[fragment]\")!=-1):\n\t\t\theader_data.reading=\"fragment\"\n\t\t\tline=fs.readline()\n\t\t\theader_data.line_offset+=1\n\t\t\theader_data.fragment_offset=header_data.line_offset\n\t\t\tcontinue\n\t\t\t\n\t\twhile(line.find(\"#include \")!=-1):\n\t\t\tincludeline = line.replace(\"#include \",\"\").strip()[1:-1]\n\t\t\t\n\t\t\timport os.path\n\t\t\t\n\t\t\tincluded_file = os.path.relpath(os.path.dirname(filename) + \"/\" + includeline)\n\t\t\tif (not included_file in header_data.vertex_included_files and header_data.reading==\"vertex\"):\n\t\t\t\theader_data.vertex_included_files+=[included_file]\n\t\t\t\tif(include_file_in_legacygl_header( included_file, header_data, depth + 1 ) == None):\n\t\t\t\t\t print \"Error in file '\" + filename + \"': #include \" + includeline + \"could not be found!\"\n\t\t\telif (not included_file in header_data.fragment_included_files and header_data.reading==\"fragment\"):\n\t\t\t\theader_data.fragment_included_files+=[included_file]\n\t\t\t\tif(include_file_in_legacygl_header( included_file, header_data, depth + 1 ) == None):\n\t\t\t\t\t print \"Error in file '\" + filename + \"': #include \" + includeline + \"could not be found!\"\n\t\t\t\n\t\t\tline=fs.readline()\n\n\t\tif (line.find(\"#ifdef \")!=-1 or line.find(\"#elif defined(\")!=-1):\n\t\t\tif (line.find(\"#ifdef \")!=-1):\n\t\t\t\tifdefline = line.replace(\"#ifdef \",\"\").strip()\n\t\t\telse:\n\t\t\t\tifdefline = line.replace(\"#elif defined(\",\"\").strip()\n\t\t\t\tifdefline = ifdefline.replace(\")\",\"\").strip()\n\n\t\t\tif (line.find(\"_EN_\")!=-1):\n\t\t\t\tenumbase = ifdefline[:ifdefline.find(\"_EN_\")];\n\t\t\t\tifdefline = ifdefline.replace(\"_EN_\",\"_\")\n\t\t\t\tline = line.replace(\"_EN_\",\"_\")\n#\t\t\t\tprint(enumbase+\":\"+ifdefline);\n\t\t\t\tif (enumbase not in header_data.enums):\n\t\t\t\t\theader_data.enums[enumbase]=[]\n\t\t\t\tif (ifdefline not in header_data.enums[enumbase]):\n\t\t\t\t\theader_data.enums[enumbase].append(ifdefline);\n\n\t\t\telif (not ifdefline in header_data.conditionals):\n\t\t\t\theader_data.conditionals+=[ifdefline]\n\n\t\tif (line.find(\"uniform\")!=-1 and line.lower().find(\"texunit:\")!=-1):\n\t\t\t#texture unit\n\t\t\ttexunitstr = line[line.find(\":\")+1:].strip()\n\t\t\tif (texunitstr==\"auto\"):\n\t\t\t\ttexunit=\"-1\"\n\t\t\telse:\n\t\t\t\ttexunit = str(int(texunitstr ))\n\t\t\tuline=line[:line.lower().find(\"//\")]\n\t\t\tuline = uline.replace(\"uniform\",\"\");\n\t\t\tuline = uline.replace(\"highp\",\"\");\n\t\t\tuline = uline.replace(\";\",\"\");\n\t\t\tlines = uline.split(\",\")\n\t\t\tfor x in lines:\n\n\t\t\t\tx = x.strip()\n\t\t\t\tx = x[ x.rfind(\" \")+1: ]\n\t\t\t\tif (x.find(\"[\")!=-1):\n\t\t\t\t\t#unfiorm array\n\t\t\t\t\tx = x[ :x.find(\"[\") ]\n\n\t\t\t\tif (not x in header_data.texunit_names):\n\t\t\t\t\theader_data.texunits+=[(x,texunit)]\n\t\t\t\t\theader_data.texunit_names+=[x]\n\n\n\n\t\telif (line.find(\"uniform\")!=-1):\n\t\t\tuline = line.replace(\"uniform\",\"\");\n\t\t\tuline = uline.replace(\";\",\"\");\n\t\t\tlines = uline.split(\",\")\n\t\t\tfor x in lines:\n\n\t\t\t\tx = x.strip()\n\t\t\t\tx = x[ x.rfind(\" \")+1: ]\n\t\t\t\tif (x.find(\"[\")!=-1):\n\t\t\t\t\t#unfiorm array\n\t\t\t\t\tx = x[ :x.find(\"[\") ]\n\n\t\t\t\tif (not x in header_data.uniforms):\n\t\t\t\t\theader_data.uniforms+=[x]\n\n\n\t\tif ((line.strip().find(\"in \")==0 or line.strip().find(\"attribute \")==0) and line.find(\"attrib:\")!=-1):\n\t\t\tuline = line.replace(\"in \",\"\");\n\t\t\tuline = uline.replace(\"attribute \",\"\");\n\t\t\tuline = uline.replace(\"highp \",\"\");\n\t\t\tuline = uline.replace(\";\",\"\");\n\t\t\tuline = uline[ uline.find(\" \"): ].strip()\n\n\n\t\t\tif (uline.find(\"//\")!=-1):\n\t\t\t\tname,bind = uline.split(\"//\")\n\t\t\t\tif (bind.find(\"attrib:\")!=-1):\n\t\t\t\t\tname=name.strip()\n\t\t\t\t\tbind=bind.replace(\"attrib:\",\"\").strip()\n\t\t\t\t\theader_data.attributes+=[(name,bind)]\n\n\n\t\tline=line.replace(\"\\r\",\"\")\n\t\tline=line.replace(\"\\n\",\"\")\n\t\t#line=line.replace(\"\\\\\",\"\\\\\\\\\")\n\t\t#line=line.replace(\"\\\"\",\"\\\\\\\"\")\n\t\t#line=line+\"\\\\n\\\\\"\n\n\t\tif (header_data.reading==\"vertex\"):\n\t\t\theader_data.vertex_lines+=[line]\n\t\tif (header_data.reading==\"fragment\"):\n\t\t\theader_data.fragment_lines+=[line]\n\n\t\tline=fs.readline()\n\t\theader_data.line_offset+=1\n\t\t\n\tfs.close();\n\t\n\treturn header_data\n\n\n\t\ndef build_legacygl_header( filename, include, class_suffix, output_attribs ):\n\t\n\theader_data = LegacyGLHeaderStruct()\n\tinclude_file_in_legacygl_header( filename, header_data, 0 )\n\n\tout_file = filename+\".h\"\n\tfd = open(out_file,\"w\")\n\t\n\tenum_constants=[]\n\n\tfd.write(\"/* WARNING, THIS FILE WAS GENERATED, DO NOT EDIT */\\n\");\n\n\tout_file_base = out_file\n\tout_file_base = out_file_base[ out_file_base.rfind(\"/\")+1: ]\n\tout_file_base = out_file_base[ out_file_base.rfind(\"\\\\\")+1: ]\n#\tprint(\"out file \"+out_file+\" base \" +out_file_base)\n\tout_file_ifdef = out_file_base.replace(\".\",\"_\").upper()\n\tfd.write(\"#ifndef \"+out_file_ifdef+class_suffix+\"_120\\n\")\n\tfd.write(\"#define \"+out_file_ifdef+class_suffix+\"_120\\n\")\n\n\tout_file_class = out_file_base.replace(\".glsl.h\",\"\").title().replace(\"_\",\"\").replace(\".\",\"\")+\"Shader\"+class_suffix;\n\tfd.write(\"\\n\\n\");\n\tfd.write(\"#include \\\"\" + include + \"\\\"\\n\\n\\n\");\n\tfd.write(\"class \"+out_file_class+\" : public Shader\"+class_suffix+\" {\\n\\n\");\n\tfd.write(\"\\t virtual String get_shader_name() const { return \\\"\"+out_file_class+\"\\\"; }\\n\");\n\n\n\tfd.write(\"public:\\n\\n\");\n\n\tif (len(header_data.conditionals)):\n\t\tfd.write(\"\\tenum Conditionals {\\n\");\n\t\tfor x in header_data.conditionals:\n\t\t\tfd.write(\"\\t\\t\"+x.upper()+\",\\n\");\n\t\tfd.write(\"\\t};\\n\\n\");\n\n\n\tif (len(header_data.uniforms)):\n\t\tfd.write(\"\\tenum Uniforms {\\n\");\n\t\tfor x in header_data.uniforms:\n\t\t\tfd.write(\"\\t\\t\"+x.upper()+\",\\n\");\n\t\tfd.write(\"\\t};\\n\\n\");\n\n\tfd.write(\"\\t_FORCE_INLINE_ int get_uniform(Uniforms p_uniform) const { return _get_uniform(p_uniform); }\\n\\n\");\n\tif (len(header_data.conditionals)):\n\n\t\tfd.write(\"\\t_FORCE_INLINE_ void set_conditional(Conditionals p_conditional,bool p_enable) { _set_conditional(p_conditional,p_enable); }\\n\\n\");\n\tfd.write(\"\\t#define _FU if (get_uniform(p_uniform)<0) return; ERR_FAIL_COND( get_active()!=this );\\n\\n \");\n\tfd.write(\"\\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, float p_value) { _FU glUniform1f(get_uniform(p_uniform),p_value); }\\n\\n\");\n\tfd.write(\"\\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, double p_value) { _FU glUniform1f(get_uniform(p_uniform),p_value); }\\n\\n\");\n\tfd.write(\"\\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, uint8_t p_value) { _FU glUniform1i(get_uniform(p_uniform),p_value); }\\n\\n\");\n\tfd.write(\"\\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, int8_t p_value) { _FU glUniform1i(get_uniform(p_uniform),p_value); }\\n\\n\");\n\tfd.write(\"\\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, uint16_t p_value) { _FU glUniform1i(get_uniform(p_uniform),p_value); }\\n\\n\");\n\tfd.write(\"\\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, int16_t p_value) { _FU glUniform1i(get_uniform(p_uniform),p_value); }\\n\\n\");\n\tfd.write(\"\\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, uint32_t p_value) { _FU glUniform1i(get_uniform(p_uniform),p_value); }\\n\\n\");\n\tfd.write(\"\\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, int32_t p_value) { _FU glUniform1i(get_uniform(p_uniform),p_value); }\\n\\n\");\n\t#fd.write(\"\\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, uint64_t p_value) { _FU glUniform1i(get_uniform(p_uniform),p_value); }\\n\\n\");\n\t#fd.write(\"\\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, int64_t p_value) { _FU glUniform1i(get_uniform(p_uniform),p_value); }\\n\\n\");\n\t#fd.write(\"\\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, unsigned long p_value) { _FU glUniform1i(get_uniform(p_uniform),p_value); }\\n\\n\");\n\t#fd.write(\"\\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, long p_value) { _FU glUniform1i(get_uniform(p_uniform),p_value); }\\n\\n\");\n\tfd.write(\"\\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, const Color& p_color) { _FU GLfloat col[4]={p_color.r,p_color.g,p_color.b,p_color.a}; glUniform4fv(get_uniform(p_uniform),1,col); }\\n\\n\");\n\tfd.write(\"\\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, const Vector2& p_vec2) { _FU GLfloat vec2[2]={p_vec2.x,p_vec2.y}; glUniform2fv(get_uniform(p_uniform),1,vec2); }\\n\\n\");\n\tfd.write(\"\\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, const Vector3& p_vec3) { _FU GLfloat vec3[3]={p_vec3.x,p_vec3.y,p_vec3.z}; glUniform3fv(get_uniform(p_uniform),1,vec3); }\\n\\n\");\n\tfd.write(\"\\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, float p_a, float p_b) { _FU glUniform2f(get_uniform(p_uniform),p_a,p_b); }\\n\\n\");\n\tfd.write(\"\\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, float p_a, float p_b, float p_c) { _FU glUniform3f(get_uniform(p_uniform),p_a,p_b,p_c); }\\n\\n\");\n\tfd.write(\"\\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, float p_a, float p_b, float p_c, float p_d) { _FU glUniform4f(get_uniform(p_uniform),p_a,p_b,p_c,p_d); }\\n\\n\");\n\n\tfd.write(\"\"\"\\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, const Transform& p_transform) { _FU\n\n\t\tconst Transform &tr = p_transform;\n\n\t\tGLfloat matrix[16]={ /* build a 16x16 matrix */\n\t\t\ttr.basis.elements[0][0],\n\t\t\ttr.basis.elements[1][0],\n\t\t\ttr.basis.elements[2][0],\n\t\t\t0,\n\t\t\ttr.basis.elements[0][1],\n\t\t\ttr.basis.elements[1][1],\n\t\t\ttr.basis.elements[2][1],\n\t\t\t0,\n\t\t\ttr.basis.elements[0][2],\n\t\t\ttr.basis.elements[1][2],\n\t\t\ttr.basis.elements[2][2],\n\t\t\t0,\n\t\t\ttr.origin.x,\n\t\t\ttr.origin.y,\n\t\t\ttr.origin.z,\n\t\t\t1\n\t\t};\n\n\n\tglUniformMatrix4fv(get_uniform(p_uniform),1,false,matrix);\n\n\n\t}\n\n\t\"\"\");\n\n\tfd.write(\"\"\"\\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, const Matrix32& p_transform) { _FU\n\n\t\tconst Matrix32 &tr = p_transform;\n\n\t\tGLfloat matrix[16]={ /* build a 16x16 matrix */\n\t\t\ttr.elements[0][0],\n\t\t\ttr.elements[0][1],\n\t\t\t0,\n\t\t\t0,\n\t\t\ttr.elements[1][0],\n\t\t\ttr.elements[1][1],\n\t\t\t0,\n\t\t\t0,\n\t\t\t0,\n\t\t\t0,\n\t\t\t1,\n\t\t\t0,\n\t\t\ttr.elements[2][0],\n\t\t\ttr.elements[2][1],\n\t\t\t0,\n\t\t\t1\n\t\t};\n\n\n\tglUniformMatrix4fv(get_uniform(p_uniform),1,false,matrix);\n\n\n\t}\n\n\t\"\"\");\n\n\tfd.write(\"\"\"\\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, const CameraMatrix& p_matrix) { _FU\n\n\t\tGLfloat matrix[16];\n\n\t\tfor (int i=0;i<4;i++) {\n\t\t\tfor (int j=0;j<4;j++) {\n\n\t\t\t\tmatrix[i*4+j]=p_matrix.matrix[i][j];\n\t\t\t}\n\t\t}\n\n\t\tglUniformMatrix4fv(get_uniform(p_uniform),1,false,matrix);\n\t}; \"\"\");\n\n\tfd.write(\"\\n\\n#undef _FU\\n\\n\\n\");\n\n\n\tfd.write(\"\\tvirtual void init() {\\n\\n\");\n\n\n\tenum_value_count=0;\n\n\tif (len(header_data.enums)):\n\n\t\tfd.write(\"\\t\\t//Written using math, given nonstandarity of 64 bits integer constants..\\n\");\n\t\tfd.write(\"\\t\\tstatic const Enum _enums[]={\\n\")\n\n\t\tbitofs=len(header_data.conditionals)\n\t\tenum_vals=[]\n\n\t\tfor xv in header_data.enums:\n\t\t\tx=header_data.enums[xv]\n\t\t\tbits=1\n\t\t\tamt = len(x);\n#\t\t\tprint(x)\n\t\t\twhile(2**bits < amt):\n\t\t\t\tbits+=1\n#\t\t\tprint(\"amount: \"+str(amt)+\" bits \"+str(bits));\n\t\t\tstrs=\"{\"\n\t\t\tfor i in range(amt):\n\t\t\t\tstrs+=\"\\\"#define \"+x[i]+\"\\\\n\\\",\"\n\n\t\t\t\tv={}\n\t\t\t\tv[\"set_mask\"]=\"uint64_t(\"+str(i)+\")<<\"+str(bitofs)\n\t\t\t\tv[\"clear_mask\"]=\"((uint64_t(1)<<40)-1) ^ (((uint64_t(1)<<\"+str(bits)+\") - 1)<<\"+str(bitofs)+\")\"\n\t\t\t\tenum_vals.append(v)\n\t\t\t\tenum_constants.append(x[i])\n\n\t\t\tstrs+=\"NULL}\"\n\n\t\t\tfd.write(\"\\t\\t\\t{(uint64_t(1<<\"+str(bits)+\")-1)<<\"+str(bitofs)+\",\"+str(bitofs)+\",\"+strs+\"},\\n\");\n\t\t\tbitofs+=bits\n\n\n\t\tfd.write(\"\\t\\t};\\n\\n\");\n\n\t\tfd.write(\"\\t\\tstatic const EnumValue _enum_values[]={\\n\")\n\n\t\tenum_value_count=len(enum_vals);\n\t\tfor x in enum_vals:\n\t\t\tfd.write(\"\\t\\t\\t{\"+x[\"set_mask\"]+\",\"+x[\"clear_mask\"]+\"},\\n\");\n\n\t\tfd.write(\"\\t\\t};\\n\\n\");\n\telse:\n\t\tfd.write(\"\\t\\tstatic const Enum *_enums=NULL;\\n\")\n\t\tfd.write(\"\\t\\tstatic const EnumValue *_enum_values=NULL;\\n\")\n\n\tif (len(header_data.conditionals)):\n\n\t\tfd.write(\"\\t\\tstatic const char* _conditional_strings[]={\\n\")\n\t\tif (len(header_data.conditionals)):\n\t\t\tfor x in header_data.conditionals:\n\t\t\t\tfd.write(\"\\t\\t\\t\\\"#define \"+x+\"\\\\n\\\",\\n\");\n\t\tfd.write(\"\\t\\t};\\n\\n\");\n\telse:\n\t\tfd.write(\"\\t\\tstatic const char **_conditional_strings=NULL;\\n\")\n\n\tif (len(header_data.uniforms)):\n\n\t\tfd.write(\"\\t\\tstatic const char* _uniform_strings[]={\\n\")\n\t\tif (len(header_data.uniforms)):\n\t\t\tfor x in header_data.uniforms:\n\t\t\t\tfd.write(\"\\t\\t\\t\\\"\"+x+\"\\\",\\n\");\n\t\tfd.write(\"\\t\\t};\\n\\n\");\n\telse:\n\t\tfd.write(\"\\t\\tstatic const char **_uniform_strings=NULL;\\n\")\n\n\tif output_attribs:\n\t\tif (len(header_data.attributes)):\n\n\t\t\tfd.write(\"\\t\\tstatic AttributePair _attribute_pairs[]={\\n\")\n\t\t\tfor x in header_data.attributes:\n\t\t\t\tfd.write(\"\\t\\t\\t{\\\"\"+x[0]+\"\\\",\"+x[1]+\"},\\n\");\n\t\t\tfd.write(\"\\t\\t};\\n\\n\");\n\t\telse:\n\t\t\tfd.write(\"\\t\\tstatic AttributePair *_attribute_pairs=NULL;\\n\")\n\n\n\tif (len(header_data.texunits)):\n\t\tfd.write(\"\\t\\tstatic TexUnitPair _texunit_pairs[]={\\n\")\n\t\tfor x in header_data.texunits:\n\t\t\tfd.write(\"\\t\\t\\t{\\\"\"+x[0]+\"\\\",\"+x[1]+\"},\\n\");\n\t\tfd.write(\"\\t\\t};\\n\\n\");\n\telse:\n\t\tfd.write(\"\\t\\tstatic TexUnitPair *_texunit_pairs=NULL;\\n\")\n\n\tfd.write(\"\\t\\tstatic const char _vertex_code[]={\\n\")\n\tfor x in header_data.vertex_lines:\n\t\tfor i in range(len(x)):\n\t\t\tfd.write(str(ord(x[i]))+\",\");\n\n\t\tfd.write(str(ord('\\n'))+\",\");\n\tfd.write(\"\\t\\t0};\\n\\n\");\n\n\tfd.write(\"\\t\\tstatic const int _vertex_code_start=\"+str(header_data.vertex_offset)+\";\\n\")\n\n\n\tfd.write(\"\\t\\tstatic const char _fragment_code[]={\\n\")\n\tfor x in header_data.fragment_lines:\n\t\tfor i in range(len(x)):\n\t\t\tfd.write(str(ord(x[i]))+\",\");\n\n\t\tfd.write(str(ord('\\n'))+\",\");\n\tfd.write(\"\\t\\t0};\\n\\n\");\n\n\tfd.write(\"\\t\\tstatic const int _fragment_code_start=\"+str(header_data.fragment_offset)+\";\\n\")\n\n\tif output_attribs:\n\t\tfd.write(\"\\t\\tsetup(_conditional_strings,\"+str(len(header_data.conditionals))+\",_uniform_strings,\"+str(len(header_data.uniforms))+\",_attribute_pairs,\"+str(len(header_data.attributes))+\", _texunit_pairs,\"+str(len(header_data.texunits))+\",_vertex_code,_fragment_code,_vertex_code_start,_fragment_code_start);\\n\")\n\telse:\n\t\tfd.write(\"\\t\\tsetup(_conditional_strings,\"+str(len(header_data.conditionals))+\",_uniform_strings,\"+str(len(header_data.uniforms))+\",_texunit_pairs,\"+str(len(header_data.texunits))+\",_enums,\"+str(len(header_data.enums))+\",_enum_values,\"+str(enum_value_count)+\",_vertex_code,_fragment_code,_vertex_code_start,_fragment_code_start);\\n\")\n\n\tfd.write(\"\\t};\\n\\n\")\n\n\n\tif (len(enum_constants)):\n\n\t\tfd.write(\"\\tenum EnumConditionals {\\n\")\n\t\tfor x in enum_constants:\n\t\t\tfd.write(\"\\t\\t\"+x.upper()+\",\\n\");\n\t\tfd.write(\"\\t};\\n\\n\");\n\t\tfd.write(\"\\tvoid set_enum_conditional(EnumConditionals p_cond) { _set_enum_conditional(p_cond); }\\n\")\n\n\n\tfd.write(\"};\\n\\n\");\n\tfd.write(\"#endif\\n\\n\");\n\tfd.close();\n\n\ndef build_legacygl_headers( target, source, env ):\n\n\tfor x in source:\n\n\t\tbuild_legacygl_header(str(x), include = \"drivers/legacygl/shader_lgl.h\", class_suffix = \"LGL\", output_attribs = False);\n\n\n\treturn 0\n\ndef build_gles2_headers( target, source, env ):\n\n\tfor x in source:\n\t\tbuild_legacygl_header(str(x), include=\"drivers/gles2/shader_gles2.h\", class_suffix = \"GLES2\", output_attribs = True)\n\ndef update_version():\n\n\trev = \"custom_build\"\n\n\tif (os.getenv(\"BUILD_REVISION\")!=None):\n\t\trev=os.getenv(\"BUILD_REVISION\")\n\t\tprint(\"Using custom revision: \"+rev)\n\timport version\n\n\n\tf=open(\"core/version.h\",\"wb\")\n\tf.write(\"#define VERSION_SHORT_NAME \"+str(version.short_name)+\"\\n\")\n\tf.write(\"#define VERSION_NAME \"+str(version.name)+\"\\n\")\n\tf.write(\"#define VERSION_MAJOR \"+str(version.major)+\"\\n\")\n\tf.write(\"#define VERSION_MINOR \"+str(version.minor)+\"\\n\")\n\tif (hasattr(version, 'patch')):\n\t f.write(\"#define VERSION_PATCH \"+str(version.patch)+\"\\n\")\n\tf.write(\"#define VERSION_REVISION \"+str(rev)+\"\\n\")\n\tf.write(\"#define VERSION_STATUS \"+str(version.status)+\"\\n\")\n\timport datetime\n\tf.write(\"#define VERSION_YEAR \"+str(datetime.datetime.now().year)+\"\\n\")\n\ndef parse_cg_file(fname, uniforms, sizes, conditionals):\n\n\timport re\n\tfs = open(fname, \"r\")\n\tline=fs.readline()\n\n\twhile line:\n\n\t\tif re.match(r\"^\\s*uniform\", line):\n\n\t\t\tres = re.match(r\"uniform ([\\d\\w]*) ([\\d\\w]*)\")\n\t\t\ttype = res.groups(1)\n\t\t\tname = res.groups(2)\n\n\t\t\tuniforms.append(name);\n\n\t\t\tif (type.find(\"texobj\") != -1):\n\t\t\t\tsizes.append(1);\n\t\t\telse:\n\t\t\t\tt = re.match(r\"float(\\d)x(\\d)\", type);\n\t\t\t\tif t:\n\t\t\t\t\tsizes.append(int(t.groups(1)) * int(t.groups(2)))\n\t\t\t\telse:\n\t\t\t\t\tt = re.match(r\"float(\\d)\", type);\n\t\t\t\t\tsizes.append(int(t.groups(1)))\n\n\t\t\tif line.find(\"[branch]\") != -1:\n\t\t\t\tconditionals.append(name);\n\n\t\tline = fs.readline();\n\n\ndef build_cg_shader(sname):\n\n\tvp_uniforms = []\n\tvp_uniform_sizes = []\n\tvp_conditionals = []\n\n\tparse_cg_file(\"vp_\"+sname+\".cg\", vp_uniforms, vp_uniform_sizes, vp_conditionals);\n\n\tfp_uniforms = []\n\tfp_uniform_sizes = []\n\tfp_conditionals = []\n\n\tparse_cg_file(\"fp_\"+sname+\".cg\", fp_uniforms, fp_uniform_sizes, fp_conditionals);\n\n\tfd = open(\"shader_\"+sname+\".cg.h\", \"w\");\n\n\tfd.write('\\n#include \"shader_cell.h\"\\n');\n\tfd.write(\"\\nclass Shader_\" + sname + \" : public ShaderCell {\\n\");\n\tfd.write(\"\\n\\tstatic struct VertexUniforms[] = {\\n\");\n\n\toffset = 0;\n\tfor i in range(0, len(vp_uniforms)):\n\n\t\tfd.write('\\t\\t{ \"%s\", %d, %d },\\n' % (vp_uniforms[i], offset, vp_uniform_sizes[i]))\n\t\toffset = offset + vp_uniform_sizes[i];\n\tfd.write(\"\\t};\\n\\n\");\n\n\tfd.write(\"public:\\n\\n\");\n\n\tfd.write(\"\\tenum {\\n\");\n\n\tfor i in range(0, len(vp_uniforms)):\n\n\t\tfd.write('\\t\\tVP_%s,\\n' % vp_uniforms[i].upper())\n\n\tfd.write(\"\\t};\\n\");\n\n\n\nimport glob\ndef detect_modules():\n\n\tmodule_list=[]\n\tincludes_cpp=\"\"\n\tregister_cpp=\"\"\n\tunregister_cpp=\"\"\n\n\tfor x in glob.glob(\"modules/*\"):\n\t\tif (not os.path.isdir(x)):\n\t\t\tcontinue\n\t\tx=x.replace(\"modules/\",\"\") # rest of world\n\t\tx=x.replace(\"modules\\\\\",\"\") # win32\n\t\tmodule_list.append(x)\n\t\ttry:\n\t\t\twith open(\"modules/\"+x+\"/register_types.h\"):\n\t\t\t\tincludes_cpp+='#include \"modules/'+x+'/register_types.h\"\\n'\n\t\t\t\tregister_cpp+='#ifdef MODULE_'+x.upper()+'_ENABLED\\n'\n\t\t\t\tregister_cpp+='\\tregister_'+x+'_types();\\n'\n\t\t\t\tregister_cpp+='#endif\\n'\n\t\t\t\tunregister_cpp+='#ifdef MODULE_'+x.upper()+'_ENABLED\\n'\n\t\t\t\tunregister_cpp+='\\tunregister_'+x+'_types();\\n'\n\t\t\t\tunregister_cpp+='#endif\\n'\n\t\texcept IOError:\n\t\t\tpass\n\n\tmodules_cpp=\"\"\"\n// modules.cpp - THIS FILE IS GENERATED, DO NOT EDIT!!!!!!!\n#include \"register_module_types.h\"\n\n\n\"\"\"+includes_cpp+\"\"\"\n\nvoid register_module_types() {\n\n\"\"\"+register_cpp+\"\"\"\n\n}\n\nvoid unregister_module_types() {\n", "answers": ["\"\"\"+unregister_cpp+\"\"\""], "length": 2891, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "23b601b7-e098-45d2-b271-34a888d4a962", "reasoning": "The code is constructing a C++ source file as a Python multi-line string. After opening the 'unregister_module_types' function, the next line should insert the previously built 'unregister_cpp' string that contains the per‑module unregistration calls. Therefore the next line is the concatenation of that variable into the string.", "reasoning_model_answer": "\"\"\"+unregister_cpp+\"\"\"", "assistant_with_reasoning": "\nThe code is constructing a C++ source file as a Python multi-line string. After opening the 'unregister_module_types' function, the next line should insert the previously built 'unregister_cpp' string that contains the per‑module unregistration calls. Therefore the next line is the concatenation of that variable into the string.\n\n\"\"\"+unregister_cpp+\"\"\"", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 5.778, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 39526, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "\"\"\"+unregister_cpp+\"\"\"", "score": 1.0, "is_full_score": true, "is_nonzero_score": true}} {"input": "", "context": "#region MIT License\n/*\n * Copyright (c) 2005-2007 Jonathan Mark Porter. http://physics2d.googlepages.com/\n * \n * Permission is hereby granted, free of charge, to any person obtaining a copy \n * of this software and associated documentation files (the \"Software\"), to deal \n * in the Software without restriction, including without limitation the rights to \n * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of \n * the Software, and to permit persons to whom the Software is furnished to do so, \n * subject to the following conditions:\n * \n * The above copyright notice and this permission notice shall be \n * included in all copies or substantial portions of the Software.\n * \n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR\n * PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE \n * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n * OTHER DEALINGS IN THE SOFTWARE.\n */\n#endregion\n\n\n#if UseDouble\nusing Scalar = System.Double;\n#else\nusing Scalar = System.Single;\n#endif\nusing System;\nusing System.Runtime.InteropServices;\nusing System.Diagnostics;\nusing System.Xml.Serialization;\nusing AdvanceMath.Design;\nnamespace AdvanceMath\n{\n /// \n /// (NOT USED BY PHYSICS2D)\n /// \n /// \n //[StructLayout(LayoutKind.Sequential), Serializable]\n [StructLayout(LayoutKind.Sequential, Size = Vector4D.Size, Pack = 0), Serializable]\n [AdvBrowsableOrder(\"X,Y,Z,W\")]\n [System.ComponentModel.TypeConverter(typeof(AdvTypeConverter))]\n public struct Vector4D : IVector\n {\n #region const fields\n /// \n /// The number of Scalar values in the class.\n /// \n public const int Count = 4;\n /// \n /// The Size of the class in bytes;\n /// \n public const int Size = sizeof(Scalar) * Count;\n #endregion\n #region readonly fields\n /// \n /// Vector4D(0,0,0,0)\n /// \n public static readonly Vector4D Origin = new Vector4D();\n /// \n /// Vector4D(0,0,0,0)\n /// \n public static readonly Vector4D Zero = new Vector4D();\n /// \n /// Vector4D(1,0,0,0)\n /// \n public static readonly Vector4D XAxis = new Vector4D(1, 0, 0, 0);\n /// \n /// Vector4D(0,1,0,0)\n /// \n public static readonly Vector4D YAxis = new Vector4D(0, 1, 0, 0);\n /// \n /// Vector4D(0,0,1,0)\n /// \n public static readonly Vector4D ZAxis = new Vector4D(0, 0, 1, 0);\n /// \n /// Vector4D(0,0,0,1)\n /// \n public static readonly Vector4D WAxis = new Vector4D(0, 0, 0, 1);\n\n private static readonly string FormatString = MatrixHelper.CreateVectorFormatString(Count);\n private readonly static string FormatableString = MatrixHelper.CreateVectorFormatableString(Count);\n\n #endregion\n #region static methods\n public static void Copy(ref Vector4D vector, Scalar[] destArray)\n {\n Copy(ref vector, destArray, 0);\n }\n public static void Copy(ref Vector4D vector, Scalar[] destArray, int index)\n {\n ThrowHelper.CheckCopy(destArray, index, Count);\n\n destArray[index] = vector.X;\n destArray[++index] = vector.Y;\n destArray[++index] = vector.Z;\n destArray[++index] = vector.W;\n }\n public static void Copy(Scalar[] sourceArray, out Vector4D result)\n {\n Copy(sourceArray, 0, out result);\n }\n public static void Copy(Scalar[] sourceArray, int index, out Vector4D result)\n {\n ThrowHelper.CheckCopy(sourceArray, index, Count);\n\n result.X = sourceArray[index];\n result.Y = sourceArray[++index];\n result.Z = sourceArray[++index];\n result.W = sourceArray[++index];\n }\n public static void Copy(ref Vector3D source, ref Vector4D dest)\n {\n dest.X = source.X;\n dest.Y = source.Y;\n dest.Z = source.Z;\n }\n public static void Copy(ref Vector2D source, ref Vector4D dest)\n {\n dest.X = source.X;\n dest.Y = source.Y;\n }\n\n public static Vector4D Clamp(Vector4D value, Vector4D lower, Vector4D upper)\n {\n Vector4D result;\n MathHelper.Clamp(ref value.X, ref lower.X, ref upper.X, out result.X);\n MathHelper.Clamp(ref value.Y, ref lower.Y, ref upper.Y, out result.Y);\n MathHelper.Clamp(ref value.Z, ref lower.Z, ref upper.Z, out result.Z);\n MathHelper.Clamp(ref value.W, ref lower.W, ref upper.W, out result.W);\n return result;\n }\n public static void Clamp(ref Vector4D value, ref Vector4D lower, ref Vector4D upper, out Vector4D result)\n {\n MathHelper.Clamp(ref value.X, ref lower.X, ref upper.X, out result.X);\n MathHelper.Clamp(ref value.Y, ref lower.Y, ref upper.Y, out result.Y);\n MathHelper.Clamp(ref value.Z, ref lower.Z, ref upper.Z, out result.Z);\n MathHelper.Clamp(ref value.W, ref lower.W, ref upper.W, out result.W);\n }\n\n\n public static Vector4D Lerp( Vector4D left, Vector4D right, Scalar amount)\n {\n Vector4D result;\n Lerp(ref left,ref right,ref amount,out result);\n return result;\n }\n public static void Lerp(ref Vector4D left, ref Vector4D right, ref Scalar amount, out Vector4D result)\n {\n result.X = (right.X - left.X) * amount + left.X;\n result.Y = (right.Y - left.Y) * amount + left.Y;\n result.Z = (right.Z - left.Z) * amount + left.Z;\n result.W = (right.W - left.W) * amount + left.W;\n }\n public static Vector4D Lerp(Vector4D left, Vector4D right, Vector4D amount)\n {\n Vector4D result;\n Lerp(ref left, ref right, ref amount, out result);\n return result;\n }\n public static void Lerp(ref Vector4D left, ref Vector4D right, ref Vector4D amount, out Vector4D result)\n {\n result.X = (right.X - left.X) * amount.X + left.X;\n result.Y = (right.Y - left.Y) * amount.Y + left.Y;\n result.Z = (right.Z - left.Z) * amount.Z + left.Z;\n result.W = (right.W - left.W) * amount.W + left.W;\n }\n\n\n public static Vector4D FromArray(Scalar[] array)\n {\n return FromArray(array, 0);\n }\n public static Vector4D FromArray(Scalar[] array, int index)\n {\n Vector4D result;\n Copy(array, index, out result);\n return result;\n }\n /// \n /// Adds 2 Vectors2Ds.\n /// \n /// The left Vector4D operand.\n /// The right Vector4D operand.\n /// The Sum of the 2 Vector4Ds.\n /// \n public static Vector4D Add(Vector4D left, Vector4D right)\n {\n Vector4D result;\n result.X = left.X + right.X;\n result.Y = left.Y + right.Y;\n result.Z = left.Z + right.Z;\n result.W = left.W + right.W;\n return result;\n }\n public static void Add(ref Vector4D left, ref Vector4D right, out Vector4D result)\n {\n result.X = left.X + right.X;\n result.Y = left.Y + right.Y;\n result.Z = left.Z + right.Z;\n result.W = left.W + right.W;\n }\n\n public static Vector4D Add(Vector3D left, Vector4D right)\n {\n Vector4D result;\n Add(ref left, ref right, out result);\n return result;\n }\n public static void Add(ref Vector3D left, ref Vector4D right, out Vector4D result)\n {\n result.X = left.X + right.X;\n result.Y = left.Y + right.Y;\n result.Z = left.Z + right.Z;\n result.W = right.W;\n }\n public static Vector4D Add(Vector2D left, Vector4D right)\n {\n Vector4D result;\n Add(ref left, ref right, out result);\n return result;\n }\n public static void Add(ref Vector2D left, ref Vector4D right, out Vector4D result)\n {\n result.X = left.X + right.X;\n result.Y = left.Y + right.Y;\n result.Z = right.Z;\n result.W = right.W;\n }\n public static Vector4D Add(Vector4D left, Vector3D right)\n {\n Vector4D result;\n Add(ref left, ref right, out result);\n return result;\n }\n public static void Add(ref Vector4D left, ref Vector3D right, out Vector4D result)\n {\n result.X = left.X + right.X;\n result.Y = left.Y + right.Y;\n result.Z = left.Z + right.Z;\n result.W = left.W ;\n }\n public static Vector4D Add(Vector4D left, Vector2D right)\n {\n Vector4D result;\n Add(ref left, ref right, out result);\n return result;\n }\n public static void Add(ref Vector4D left, ref Vector2D right, out Vector4D result)\n {\n result.X = left.X + right.X;\n result.Y = left.Y + right.Y;\n result.Z = left.Z;\n result.W = left.W;\n }\n\n\n\n /// \n /// Subtracts 2 Vector4Ds.\n /// \n /// The left Vector4D operand.\n /// The right Vector4D operand.\n /// The Difference of the 2 Vector4Ds.\n /// \n public static Vector4D Subtract(Vector4D left, Vector4D right)\n {\n Vector4D result;\n result.X = left.X - right.X;\n result.Y = left.Y - right.Y;\n result.Z = left.Z - right.Z;\n result.W = left.W - right.W;\n return result;\n }\n public static void Subtract(ref Vector4D left, ref Vector4D right, out Vector4D result)\n {\n result.X = left.X - right.X;\n result.Y = left.Y - right.Y;\n result.Z = left.Z - right.Z;\n result.W = left.W - right.W;\n }\n\n\n public static Vector4D Subtract(Vector3D left, Vector4D right)\n {\n Vector4D result;\n Subtract(ref left, ref right, out result);\n return result;\n }\n public static void Subtract(ref Vector3D left, ref Vector4D right, out Vector4D result)\n {\n result.X = left.X - right.X;\n result.Y = left.Y - right.Y;\n result.Z = left.Z - right.Z;\n result.W = -right.W;\n }\n public static Vector4D Subtract(Vector2D left, Vector4D right)\n {\n Vector4D result;\n Subtract(ref left, ref right, out result);\n return result;\n }\n public static void Subtract(ref Vector2D left, ref Vector4D right, out Vector4D result)\n {\n result.X = left.X - right.X;\n result.Y = left.Y - right.Y;\n result.Z = -right.Z;\n result.W = -right.W;\n }\n public static Vector4D Subtract(Vector4D left, Vector3D right)\n {\n Vector4D result;\n Subtract(ref left, ref right, out result);\n return result;\n }\n public static void Subtract(ref Vector4D left, ref Vector3D right, out Vector4D result)\n {\n result.X = left.X - right.X;\n result.Y = left.Y - right.Y;\n result.Z = left.Z - right.Z;\n result.W = left.W;\n }\n public static Vector4D Subtract(Vector4D left, Vector2D right)\n {\n Vector4D result;\n Subtract(ref left, ref right, out result);\n return result;\n }\n public static void Subtract(ref Vector4D left, ref Vector2D right, out Vector4D result)\n {\n result.X = left.X - right.X;\n result.Y = left.Y - right.Y;\n result.Z = left.Z;\n result.W = left.W;\n }\n\n\n /// \n /// Does Scaler Multiplication on a Vector4D.\n /// \n /// The Vector4D to be multiplied.\n /// The scalar value that will multiply the Vector4D.\n /// The Product of the Scaler Multiplication.\n /// \n public static Vector4D Multiply(Vector4D source, Scalar scalar)\n {\n Vector4D result;\n result.X = source.X * scalar;\n result.Y = source.Y * scalar;\n result.Z = source.Z * scalar;\n result.W = source.W * scalar;\n return result;\n }\n public static void Multiply(ref Vector4D source, ref Scalar scalar, out Vector4D result)\n {\n result.X = source.X * scalar;\n result.Y = source.Y * scalar;\n result.Z = source.Z * scalar;\n result.W = source.W * scalar;\n }\n\n\n public static Vector4D Transform(Matrix4x4 matrix, Vector4D vector)\n {\n Vector4D result;\n\n result.X = vector.X * matrix.m00 + vector.Y * matrix.m01 + vector.Z * matrix.m02 + vector.W * matrix.m03;\n result.Y = vector.X * matrix.m10 + vector.Y * matrix.m11 + vector.Z * matrix.m12 + vector.W * matrix.m13;\n result.Z = vector.X * matrix.m20 + vector.Y * matrix.m21 + vector.Z * matrix.m22 + vector.W * matrix.m23;\n result.W = vector.X * matrix.m30 + vector.Y * matrix.m31 + vector.Z * matrix.m32 + vector.W * matrix.m33;\n\n return result;\n }\n public static void Transform(ref Matrix4x4 matrix, ref Vector4D vector, out Vector4D result)\n {\n Scalar X = vector.X;\n Scalar Y = vector.Y;\n Scalar Z = vector.Z;\n result.X = X * matrix.m00 + Y * matrix.m01 + Z * matrix.m02 + vector.W * matrix.m03;\n result.Y = X * matrix.m10 + Y * matrix.m11 + Z * matrix.m12 + vector.W * matrix.m13;\n result.Z = X * matrix.m20 + Y * matrix.m21 + Z * matrix.m22 + vector.W * matrix.m23;\n result.W = X * matrix.m30 + Y * matrix.m31 + Z * matrix.m32 + vector.W * matrix.m33;\n }\n\n public static Vector4D Transform(Vector4D vector, Matrix4x4 matrix)\n {\n Vector4D result;\n\n result.X = vector.X * matrix.m00 + vector.Y * matrix.m10 + vector.Z * matrix.m20 + vector.W * matrix.m30;\n result.Y = vector.X * matrix.m01 + vector.Y * matrix.m11 + vector.Z * matrix.m21 + vector.W * matrix.m31;\n result.Z = vector.X * matrix.m02 + vector.Y * matrix.m12 + vector.Z * matrix.m22 + vector.W * matrix.m32;\n result.W = vector.X * matrix.m03 + vector.Y * matrix.m13 + vector.Z * matrix.m23 + vector.W * matrix.m33;\n\n return result;\n }\n public static void Transform(ref Vector4D vector, ref Matrix4x4 matrix, out Vector4D result)\n {\n Scalar X = vector.X;\n Scalar Y = vector.Y;\n Scalar Z = vector.Z;\n result.X = X * matrix.m00 + Y * matrix.m10 + Z * matrix.m20 + vector.W * matrix.m30;\n result.Y = X * matrix.m01 + Y * matrix.m11 + Z * matrix.m21 + vector.W * matrix.m31;\n result.Z = X * matrix.m02 + Y * matrix.m12 + Z * matrix.m22 + vector.W * matrix.m32;\n result.W = X * matrix.m03 + Y * matrix.m13 + Z * matrix.m23 + vector.W * matrix.m33;\n }\n\n /// \n /// Does a Dot Operation Also know as an Inner Product.\n /// \n /// The left Vector4D operand.\n /// The right Vector4D operand.\n /// The Dot Product (Inner Product).\n /// \n public static Scalar Dot(Vector4D left, Vector4D right)\n {\n return left.Y * right.Y + left.X * right.X + left.Z * right.Z + left.W * right.W;\n }\n public static void Dot(ref Vector4D left, ref Vector4D right, out Scalar result)\n {\n result = left.Y * right.Y + left.X * right.X + left.Z * right.Z + left.W * right.W;\n }\n /// \n /// Gets the Squared of the Vector4D that is passed.\n /// \n /// The Vector4D whos Squared Magnitude is te be returned.\n /// The Squared Magnitude.\n public static Scalar GetMagnitudeSq(Vector4D source)\n {\n return source.X * source.X + source.Y * source.Y + source.Z * source.Z + source.W * source.W;\n }\n public static void GetMagnitudeSq(ref Vector4D source, out Scalar result)\n {\n result = source.X * source.X + source.Y * source.Y + source.Z * source.Z + source.W * source.W;\n }\n /// \n /// Gets the of the Vector4D that is passed.\n /// \n /// The Vector4D whos Magnitude is te be returned.\n /// The Magnitude.\n public static Scalar GetMagnitude(Vector4D source)\n {\n return MathHelper.Sqrt(source.X * source.X + source.Y * source.Y + source.Z * source.Z + source.W * source.W);\n }\n public static void GetMagnitude(ref Vector4D source, out Scalar result)\n {\n result = MathHelper.Sqrt(source.X * source.X + source.Y * source.Y + source.Z * source.Z + source.W * source.W);\n }\n /// \n /// Sets the of a Vector4D.\n /// \n /// The Vector4D whose Magnitude is to be changed.\n /// The Magnitude.\n /// A Vector4D with the new Magnitude\n public static Vector4D SetMagnitude(Vector4D source, Scalar magnitude)\n {\n Vector4D result;\n SetMagnitude(ref source, ref magnitude, out result);\n return result;\n }\n public static void SetMagnitude(ref Vector4D source, ref Scalar magnitude, out Vector4D result)\n {\n Scalar oldmagnitude;\n GetMagnitude(ref source, out oldmagnitude);\n if (oldmagnitude > 0 && magnitude != 0)\n {\n oldmagnitude = (magnitude / oldmagnitude);\n Multiply(ref source, ref oldmagnitude, out result);\n }\n else\n {\n result = Zero;\n }\n }\n /// \n /// Negates a Vector4D.\n /// \n /// The Vector4D to be Negated.\n /// The Negated Vector4D.\n public static Vector4D Negate(Vector4D source)\n {\n Vector4D result;\n result.X = -source.X;\n result.Y = -source.Y;\n result.Z = -source.Z;\n result.W = -source.W;\n return result;\n }\n [CLSCompliant(false)]\n public static void Negate(ref Vector4D source)\n {\n Negate(ref source, out source);\n }\n public static void Negate(ref Vector4D source, out Vector4D result)\n {\n result.X = -source.X;\n result.Y = -source.Y;\n result.Z = -source.Z;\n result.W = -source.W;\n }\n /// \n /// This returns the Normalized Vector4D that is passed. This is also known as a Unit Vector.\n /// \n /// The Vector4D to be Normalized.\n /// The Normalized Vector4D. (Unit Vector)\n /// \n public static Vector4D Normalize(Vector4D source)\n {\n Vector4D result;\n SetMagnitude(ref source, ref MathHelper.One, out result);\n return result;\n }\n public static void Normalize(ref Vector4D source, out Vector4D result)\n {\n SetMagnitude(ref source, ref MathHelper.One, out result);\n }\n [CLSCompliant(false)]\n public static void Normalize(ref Vector4D source)\n {\n SetMagnitude(ref source, ref MathHelper.One, out source);\n }\n /// \n /// Thie Projects the left Vector4D onto the Right Vector4D.\n /// \n /// The left Vector4D operand.\n /// The right Vector4D operand.\n /// The Projected Vector4D.\n /// \n public static Vector4D Project(Vector4D left, Vector4D right)\n {\n Vector4D result;\n Project(ref left, ref right, out result);\n return result;\n }\n public static void Project(ref Vector4D left, ref Vector4D right, out Vector4D result)\n {\n Scalar tmp, magsq;\n Dot(ref left, ref right, out tmp);\n GetMagnitudeSq(ref right, out magsq);\n tmp /= magsq;\n Multiply(ref right, ref tmp, out result);\n }\n\n\n\n public static Vector4D TripleCross(Vector4D top, Vector4D middle, Vector4D bottom)\n {\n Vector4D result;\n\n result.X = Matrix3x3.GetDeterminant(\n top.Y, top.Z, top.W,\n middle.Y, middle.Z, middle.W,\n bottom.Y, bottom.Z, bottom.W);\n\n result.Y = -Matrix3x3.GetDeterminant(\n top.X, top.Z, top.W,\n middle.X, middle.Z, middle.W,\n bottom.X, bottom.Z, bottom.W);\n\n result.Z = Matrix3x3.GetDeterminant(\n top.X, top.Y, top.W,\n middle.X, middle.Y, middle.W,\n bottom.X, bottom.Y, bottom.W);\n\n result.W = -Matrix3x3.GetDeterminant(\n top.X, top.Y, top.Z,\n middle.X, middle.Y, middle.Z,\n bottom.X, bottom.Y, bottom.Z);\n\n return result;\n }\n\n\n #endregion\n #region fields\n /// \n /// This is the X value. \n /// \n [XmlAttribute]\n [AdvBrowsable]\n [System.ComponentModel.Description(\"The Magnitude on the X-Axis\")]\n public Scalar X;\n /// \n /// This is the Y value. \n /// \n [XmlAttribute]\n [AdvBrowsable]\n [System.ComponentModel.Description(\"The Magnitude on the Y-Axis\")]\n public Scalar Y;\n /// \n /// This is the Z value. \n /// \n [XmlAttribute]\n [AdvBrowsable]\n [System.ComponentModel.Description(\"The Magnitude on the Z-Axis\")]\n public Scalar Z;\n /// \n /// This is the W value. \n /// \n [XmlAttribute]\n [AdvBrowsable]\n [System.ComponentModel.Description(\"The Magnitude on the W-Axis\")]\n public Scalar W;\n\n #endregion\n #region constructors\n /// \n /// Creates a New Vector4D Instance on the Stack.\n /// \n /// The X value.\n /// The Y value.\n /// The Z value.\n /// The W value.\n [InstanceConstructor(\"X,Y,Z,W\")]\n public Vector4D(Scalar X, Scalar Y, Scalar Z, Scalar W)\n {\n this.X = X;\n this.Y = Y;\n this.Z = Z;\n this.W = W;\n }\n public Vector4D(Scalar[] vals) : this(vals, 0) { }\n public Vector4D(Scalar[] vals, int index)\n {\n Copy(vals, index, out this);\n }\n #endregion\n #region indexers\n /// \n ///\t\tAllows the Vector to be accessed linearly (v[0] -> v[Count-1]). \n /// \n /// \n /// This indexer is only provided as a convenience, and is not recommended for use in\n /// intensive applications. \n /// \n public Scalar this[int index]\n {\n get\n {\n ThrowHelper.CheckIndex(\"index\", index, Count);\n unsafe\n {\n fixed (Scalar* ptr = &this.X)\n {\n return ptr[index];\n }\n }\n }\n set\n {\n ThrowHelper.CheckIndex(\"index\", index, Count);\n unsafe\n {\n fixed (Scalar* ptr = &this.X)\n {\n ptr[index] = value;\n }\n }\n }\n }\n #endregion\n #region public properties\n\n\n /// \n /// Gets or Sets the Magnitude (Length) of the Vector4D. \n /// \n /// \n [XmlIgnore]\n public Scalar Magnitude\n {\n get\n {\n return MathHelper.Sqrt(this.X * this.X + this.Y * this.Y + this.Z * this.Z + this.W * this.W);\n }\n set\n {\n this = SetMagnitude(this, value);\n }\n }\n /// \n /// Gets the Squared Magnitude of the Vector4D.\n /// \n public Scalar MagnitudeSq\n {\n get\n {\n return this.X * this.X + this.Y * this.Y + this.Z * this.Z + this.W * this.W;\n }\n }\n /// \n /// Gets the Normalized Vector4D. (Unit Vector)\n /// \n /// \n public Vector4D Normalized\n {\n get\n {\n return Normalize(this);\n }\n }\n /// \n /// The Number of Variables accesable though the indexer.\n /// \n int IAdvanceValueType.Count { get { return Count; } }\n #endregion\n #region public methods\n public Scalar[] ToArray()\n {\n Scalar[] array = new Scalar[Count];\n Copy(ref this, array, 0);\n return array;\n }\n public void CopyFrom(Scalar[] array, int index)\n {\n Copy(array, index, out this);\n }\n public void CopyTo(Scalar[] array, int index)\n {\n Copy(ref this, array, index);\n }\n #endregion\n #region operators\n /// \n /// Adds 2 Vectors2Ds.\n /// \n /// The left Vector4D operand.\n /// The right Vector4D operand.\n /// The Sum of the 2 Vector4Ds.\n /// \n public static Vector4D operator +(Vector4D left, Vector4D right)\n {\n Vector4D result;\n result.X = left.X + right.X;\n result.Y = left.Y + right.Y;\n result.Z = left.Z + right.Z;\n result.W = left.W + right.W;\n return result;\n }\n public static Vector4D operator +(Vector3D left, Vector4D right)\n {\n Vector4D result;\n Add(ref left, ref right, out result);\n return result;\n }\n public static Vector4D operator +(Vector2D left, Vector4D right)\n {\n Vector4D result;\n Add(ref left, ref right, out result);\n return result;\n }\n public static Vector4D operator +(Vector4D left, Vector3D right)\n {\n Vector4D result;\n Add(ref left, ref right, out result);\n return result;\n }\n public static Vector4D operator +(Vector4D left, Vector2D right)\n {\n Vector4D result;\n Add(ref left, ref right, out result);\n return result;\n }\n /// \n /// Subtracts 2 Vector4Ds.\n /// \n /// The left Vector4D operand.\n /// The right Vector4D operand.\n /// The Difference of the 2 Vector4Ds.\n /// \n public static Vector4D operator -(Vector4D left, Vector4D right)\n {\n Vector4D result;\n result.X = left.X - right.X;\n result.Y = left.Y - right.Y;\n result.Z = left.Z - right.Z;\n result.W = left.W - right.W;\n return result;\n }\n public static Vector4D operator -(Vector3D left, Vector4D right)\n {\n Vector4D result;\n Subtract(ref left, ref right, out result);\n return result;\n }\n public static Vector4D operator -(Vector2D left, Vector4D right)\n {\n Vector4D result;\n Subtract(ref left, ref right, out result);\n return result;\n }\n public static Vector4D operator -(Vector4D left, Vector3D right)\n {\n Vector4D result;\n Subtract(ref left, ref right, out result);\n return result;\n }\n public static Vector4D operator -(Vector4D left, Vector2D right)\n {\n Vector4D result;\n Subtract(ref left, ref right, out result);\n return result;\n }\n /// \n /// Does Scaler Multiplication on a Vector4D.\n /// \n /// The Vector4D to be multiplied.\n /// The scalar value that will multiply the Vector4D.\n /// The Product of the Scaler Multiplication.\n /// \n public static Vector4D operator *(Vector4D source, Scalar scalar)\n {\n Vector4D result;\n result.X = source.X * scalar;\n result.Y = source.Y * scalar;\n result.Z = source.Z * scalar;\n result.W = source.W * scalar;\n return result;\n }\n /// \n /// Does Scaler Multiplication on a Vector4D.\n /// \n /// The scalar value that will multiply the Vector4D.\n /// The Vector4D to be multiplied.\n /// The Product of the Scaler Multiplication.\n /// \n public static Vector4D operator *(Scalar scalar, Vector4D source)\n {\n Vector4D result;\n result.X = scalar * source.X;\n result.Y = scalar * source.Y;\n result.Z = scalar * source.Z;\n result.W = scalar * source.W;\n return result;\n }\n /// \n /// Does a Dot Operation Also know as an Inner Product.\n /// \n /// The left Vector4D operand.\n /// The right Vector4D operand.\n /// The Dot Product (Inner Product).\n /// \n public static Scalar operator *(Vector4D left, Vector4D right)\n {\n return left.X * right.X + left.Y * right.Y + left.Z * right.Z + left.W * right.W;\n }\n\n\n public static Vector4D operator *(Matrix4x4 matrix, Vector4D vector)\n {\n Vector4D result;\n\n result.X = vector.X * matrix.m00 + vector.Y * matrix.m01 + vector.Z * matrix.m02 + vector.W * matrix.m03;\n result.Y = vector.X * matrix.m10 + vector.Y * matrix.m11 + vector.Z * matrix.m12 + vector.W * matrix.m13;\n result.Z = vector.X * matrix.m20 + vector.Y * matrix.m21 + vector.Z * matrix.m22 + vector.W * matrix.m23;\n result.W = vector.X * matrix.m30 + vector.Y * matrix.m31 + vector.Z * matrix.m32 + vector.W * matrix.m33;\n\n return result;\n }\n\n public static Vector4D operator *(Vector4D vector, Matrix4x4 matrix)\n {\n Vector4D result;\n", "answers": [" result.X = vector.X * matrix.m00 + vector.Y * matrix.m10 + vector.Z * matrix.m20 + vector.W * matrix.m30;"], "length": 3537, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "b778ade2-1e8a-490c-a881-2fad218df68b", "reasoning": "The code is defining the operator overload for multiplying a Vector4D by a Matrix4x4 on the right side. The previous overload (Matrix4x4 * Vector4D) computed the result using the matrix rows. For Vector4D * Matrix4x4, the multiplication uses the matrix columns, matching the Transform method defined earlier. Therefore the next line after declaring the result variable should compute the X component using the first column of the matrix.", "reasoning_model_answer": "result.X = vector.X * matrix.m00 + vector.Y * matrix.m10 + vector.Z * matrix.m20 + vector.W * matrix.m30;", "assistant_with_reasoning": "\nThe code is defining the operator overload for multiplying a Vector4D by a Matrix4x4 on the right side. The previous overload (Matrix4x4 * Vector4D) computed the result using the matrix rows. For Vector4D * Matrix4x4, the multiplication uses the matrix columns, matching the Transform method defined earlier. Therefore the next line after declaring the result variable should compute the X component using the first column of the matrix.\n\nresult.X = vector.X * matrix.m00 + vector.Y * matrix.m10 + vector.Z * matrix.m20 + vector.W * matrix.m30;", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 8.051, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 33863, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "result.X = vector.X * matrix.m00 + vector.Y * matrix.m10 + vector.Z * matrix.m20 + vector.W * matrix.m30;", "score": 0.95, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to you under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.apache.calcite.linq4j;\n\nimport org.apache.calcite.linq4j.function.Function1;\n\nimport com.google.common.collect.Lists;\n\nimport java.lang.reflect.Method;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collection;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.NoSuchElementException;\nimport java.util.RandomAccess;\n\n/**\n * Utility and factory methods for Linq4j.\n */\npublic abstract class Linq4j {\n private Linq4j() {}\n\n private static final Object DUMMY = new Object();\n\n public static Method getMethod(String className, String methodName,\n Class... parameterTypes) {\n try {\n return Class.forName(className).getMethod(methodName, parameterTypes);\n } catch (NoSuchMethodException e) {\n return null;\n } catch (ClassNotFoundException e) {\n return null;\n }\n }\n\n /**\n * Query provider that simply executes a {@link Queryable} by calling its\n * enumerator method; does not attempt optimization.\n */\n public static final QueryProvider DEFAULT_PROVIDER = new QueryProviderImpl() {\n public Enumerator executeQuery(Queryable queryable) {\n return queryable.enumerator();\n }\n };\n\n private static final Enumerator EMPTY_ENUMERATOR =\n new Enumerator() {\n public Object current() {\n throw new NoSuchElementException();\n }\n\n public boolean moveNext() {\n return false;\n }\n\n public void reset() {\n }\n\n public void close() {\n }\n };\n\n public static final Enumerable EMPTY_ENUMERABLE =\n new AbstractEnumerable() {\n public Enumerator enumerator() {\n return EMPTY_ENUMERATOR;\n }\n };\n\n /**\n * Adapter that converts an enumerator into an iterator.\n *\n *

    WARNING: The iterator returned by this method does not call\n * {@link org.apache.calcite.linq4j.Enumerator#close()}, so it is not safe to\n * use with an enumerator that allocates resources.

    \n *\n * @param enumerator Enumerator\n * @param Element type\n *\n * @return Iterator\n */\n public static Iterator enumeratorIterator(Enumerator enumerator) {\n return new EnumeratorIterator<>(enumerator);\n }\n\n /**\n * Adapter that converts an iterable into an enumerator.\n *\n * @param iterable Iterable\n * @param Element type\n *\n * @return enumerator\n */\n public static Enumerator iterableEnumerator(\n final Iterable iterable) {\n if (iterable instanceof Enumerable) {\n @SuppressWarnings(\"unchecked\") final Enumerable enumerable =\n (Enumerable) iterable;\n return enumerable.enumerator();\n }\n return new IterableEnumerator<>(iterable);\n }\n\n /**\n * Adapter that converts an {@link List} into an {@link Enumerable}.\n *\n * @param list List\n * @param Element type\n *\n * @return enumerable\n */\n public static Enumerable asEnumerable(final List list) {\n return new ListEnumerable<>(list);\n }\n\n /**\n * Adapter that converts an {@link Collection} into an {@link Enumerable}.\n *\n *

    It uses more efficient implementations if the iterable happens to\n * be a {@link List}.

    \n *\n * @param collection Collection\n * @param Element type\n *\n * @return enumerable\n */\n public static Enumerable asEnumerable(final Collection collection) {\n if (collection instanceof List) {\n //noinspection unchecked\n return asEnumerable((List) collection);\n }\n return new CollectionEnumerable<>(collection);\n }\n\n /**\n * Adapter that converts an {@link Iterable} into an {@link Enumerable}.\n *\n *

    It uses more efficient implementations if the iterable happens to\n * be a {@link Collection} or a {@link List}.

    \n *\n * @param iterable Iterable\n * @param Element type\n *\n * @return enumerable\n */\n public static Enumerable asEnumerable(final Iterable iterable) {\n if (iterable instanceof Collection) {\n //noinspection unchecked\n return asEnumerable((Collection) iterable);\n }\n return new IterableEnumerable<>(iterable);\n }\n\n /**\n * Adapter that converts an array into an enumerable.\n *\n * @param ts Array\n * @param Element type\n *\n * @return enumerable\n */\n public static Enumerable asEnumerable(final T[] ts) {\n return new ListEnumerable<>(Arrays.asList(ts));\n }\n\n /**\n * Adapter that converts a collection into an enumerator.\n *\n * @param values Collection\n * @param Element type\n *\n * @return Enumerator over the collection\n */\n public static Enumerator enumerator(Collection values) {\n if (values instanceof List && values instanceof RandomAccess) {\n //noinspection unchecked\n return listEnumerator((List) values);\n }\n return iterableEnumerator(values);\n }\n\n private static Enumerator listEnumerator(List list) {\n return new ListEnumerator<>(list);\n }\n\n /** Applies a function to each element of an Enumerator.\n *\n * @param enumerator Backing enumerator\n * @param func Transform function\n * @param Backing element type\n * @param Element type\n * @return Enumerator\n */\n public static Enumerator transform(Enumerator enumerator,\n final Function1 func) {\n return new TransformedEnumerator(enumerator) {\n protected E transform(F from) {\n return func.apply(from);\n }\n };\n }\n\n /**\n * Converts the elements of a given Iterable to the specified type.\n *\n *

    This method is implemented by using deferred execution. The immediate\n * return value is an object that stores all the information that is\n * required to perform the action. The query represented by this method is\n * not executed until the object is enumerated either by calling its\n * {@link Enumerable#enumerator} method directly or by using\n * {@code for (... in ...)}.\n *\n *

    Since standard Java {@link Collection} objects implement the\n * {@link Iterable} interface, the {@code cast} method enables the standard\n * query operators to be invoked on collections\n * (including {@link java.util.List} and {@link java.util.Set}) by supplying\n * the necessary type information. For example, {@link ArrayList} does not\n * implement {@link Enumerable}<F>, but you can invoke\n *\n *

    Linq4j.cast(list, Integer.class)
    \n *\n *

    to convert the list of an enumerable that can be queried using the\n * standard query operators.\n *\n *

    If an element cannot be cast to type <TResult>, this method will\n * throw a {@link ClassCastException}. To obtain only those elements that\n * can be cast to type TResult, use the {@link #ofType} method instead.\n *\n * @see Enumerable#cast(Class)\n * @see #ofType\n * @see #asEnumerable(Iterable)\n */\n public static Enumerable cast(\n Iterable source, Class clazz) {\n return asEnumerable(source).cast(clazz);\n }\n\n /**\n * Returns elements of a given {@link Iterable} that are of the specified\n * type.\n *\n *

    This method is implemented by using deferred execution. The immediate\n * return value is an object that stores all the information that is\n * required to perform the action. The query represented by this method is\n * not executed until the object is enumerated either by calling its\n * {@link Enumerable#enumerator} method directly or by using\n * {@code for (... in ...)}.\n *\n *

    The {@code ofType} method returns only those elements in source that\n * can be cast to type TResult. To instead receive an exception if an\n * element cannot be cast to type TResult, use\n * {@link #cast(Iterable, Class)}.

    \n *\n *

    Since standard Java {@link Collection} objects implement the\n * {@link Iterable} interface, the {@code cast} method enables the standard\n * query operators to be invoked on collections\n * (including {@link java.util.List} and {@link java.util.Set}) by supplying\n * the necessary type information. For example, {@link ArrayList} does not\n * implement {@link Enumerable}<F>, but you can invoke\n *\n *

    Linq4j.ofType(list, Integer.class)
    \n *\n *

    to convert the list of an enumerable that can be queried using the\n * standard query operators.\n *\n * @see Enumerable#cast(Class)\n * @see #cast\n */\n public static Enumerable ofType(\n Iterable source, Class clazz) {\n return asEnumerable(source).ofType(clazz);\n }\n\n /**\n * Returns an {@link Enumerable} that has one element.\n *\n * @param Element type\n *\n * @return Singleton enumerable\n */\n public static Enumerable singletonEnumerable(final T element) {\n return new AbstractEnumerable() {\n public Enumerator enumerator() {\n return singletonEnumerator(element);\n }\n };\n }\n\n /**\n * Returns an {@link Enumerator} that has one element.\n *\n * @param Element type\n *\n * @return Singleton enumerator\n */\n public static Enumerator singletonEnumerator(T element) {\n return new SingletonEnumerator<>(element);\n }\n\n /**\n * Returns an {@link Enumerator} that has one null element.\n *\n * @param Element type\n *\n * @return Singleton enumerator\n */\n public static Enumerator singletonNullEnumerator() {\n return new SingletonNullEnumerator<>();\n }\n\n /**\n * Returns an {@link Enumerable} that has no elements.\n *\n * @param Element type\n *\n * @return Empty enumerable\n */\n public static Enumerable emptyEnumerable() {\n //noinspection unchecked\n return (Enumerable) EMPTY_ENUMERABLE;\n }\n\n /**\n * Returns an {@link Enumerator} that has no elements.\n *\n * @param Element type\n *\n * @return Empty enumerator\n */\n public static Enumerator emptyEnumerator() {\n //noinspection unchecked\n return (Enumerator) EMPTY_ENUMERATOR;\n }\n\n /**\n * Concatenates two or more {@link Enumerable}s to form a composite\n * enumerable that contains the union of their elements.\n *\n * @param enumerableList List of enumerable objects\n * @param Element type\n *\n * @return Composite enumerator\n */\n public static Enumerable concat(\n final List> enumerableList) {\n return new CompositeEnumerable<>(enumerableList);\n }\n\n /**\n * Returns an enumerator that is the cartesian product of the given\n * enumerators.\n *\n *

    For example, given enumerator A that returns {\"a\", \"b\", \"c\"} and\n * enumerator B that returns {\"x\", \"y\"}, product(List(A, B)) will return\n * {List(\"a\", \"x\"), List(\"a\", \"y\"),\n * List(\"b\", \"x\"), List(\"b\", \"y\"),\n * List(\"c\", \"x\"), List(\"c\", \"y\")}.

    \n *\n *

    Notice that the cardinality of the result is the product of the\n * cardinality of the inputs. The enumerators A and B have 3 and 2\n * elements respectively, and the result has 3 * 2 = 6 elements.\n * This is always the case. In\n * particular, if any of the enumerators is empty, the result is empty.

    \n *\n * @param enumerators List of enumerators\n * @param Element type\n *\n * @return Enumerator over the cartesian product\n */\n public static Enumerator> product(\n List> enumerators) {\n return new CartesianProductListEnumerator<>(enumerators);\n }\n\n /** Returns the cartesian product of an iterable of iterables. */\n public static Iterable> product(\n final Iterable> iterables) {\n return new Iterable>() {\n public Iterator> iterator() {\n final List> enumerators = Lists.newArrayList();\n for (Iterable iterable : iterables) {\n enumerators.add(iterableEnumerator(iterable));\n }\n return enumeratorIterator(\n new CartesianProductListEnumerator<>(enumerators));\n }\n };\n }\n\n /**\n * Returns whether the arguments are equal to each other.\n *\n *

    Equivalent to {@link java.util.Objects#equals} in JDK 1.7 and above.\n */\n @Deprecated // to be removed before 2.0\n public static boolean equals(T t0, T t1) {\n return t0 == t1 || t0 != null && t0.equals(t1);\n }\n\n /**\n * Throws {@link NullPointerException} if argument is null, otherwise\n * returns argument.\n *\n *

    Equivalent to {@link java.util.Objects#requireNonNull} in JDK 1.7 and\n * above.\n */\n @Deprecated // to be removed before 2.0\n public static T requireNonNull(T o) {\n if (o == null) {\n throw new NullPointerException();\n }\n return o;\n }\n\n /** Closes an iterator, if it can be closed. */\n private static void closeIterator(Iterator iterator) {\n if (iterator instanceof AutoCloseable) {\n try {\n ((AutoCloseable) iterator).close();\n } catch (RuntimeException e) {\n throw e;\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }\n }\n\n /** Iterable enumerator.\n *\n * @param element type */\n @SuppressWarnings(\"unchecked\")\n static class IterableEnumerator implements Enumerator {\n private final Iterable iterable;\n Iterator iterator;\n T current;\n\n IterableEnumerator(Iterable iterable) {\n this.iterable = iterable;\n iterator = iterable.iterator();\n current = (T) DUMMY;\n }\n\n public T current() {\n if (current == DUMMY) {\n throw new NoSuchElementException();\n }\n return current;\n }\n\n public boolean moveNext() {\n if (iterator.hasNext()) {\n current = iterator.next();\n return true;\n }\n current = (T) DUMMY;\n return false;\n }\n\n public void reset() {\n iterator = iterable.iterator();\n current = (T) DUMMY;\n }\n\n public void close() {\n final Iterator iterator1 = this.iterator;\n this.iterator = null;\n closeIterator(iterator1);\n }\n }\n\n /** Composite enumerable.\n *\n * @param element type */\n static class CompositeEnumerable extends AbstractEnumerable {\n private final Enumerator> enumerableEnumerator;\n\n CompositeEnumerable(List> enumerableList) {\n enumerableEnumerator = iterableEnumerator(enumerableList);\n }\n\n public Enumerator enumerator() {\n return new Enumerator() {\n // Never null.\n Enumerator current = emptyEnumerator();\n\n public E current() {\n return current.current();\n }\n\n public boolean moveNext() {\n for (;;) {\n if (current.moveNext()) {\n return true;\n }\n current.close();\n if (!enumerableEnumerator.moveNext()) {\n current = emptyEnumerator();\n return false;\n }\n current = enumerableEnumerator.current().enumerator();\n }\n }\n\n public void reset() {\n enumerableEnumerator.reset();\n current = emptyEnumerator();\n }\n\n public void close() {\n current.close();\n current = emptyEnumerator();\n }\n };\n }\n }\n\n /** Iterable enumerable.\n *\n * @param element type */\n static class IterableEnumerable extends AbstractEnumerable2 {\n protected final Iterable iterable;\n\n IterableEnumerable(Iterable iterable) {\n this.iterable = iterable;\n }\n\n public Iterator iterator() {\n return iterable.iterator();\n }\n\n @Override public boolean any() {\n return iterable.iterator().hasNext();\n }\n }\n\n /** Collection enumerable.\n *\n * @param element type */\n static class CollectionEnumerable extends IterableEnumerable {\n CollectionEnumerable(Collection iterable) {\n super(iterable);\n }\n\n protected Collection getCollection() {\n return (Collection) iterable;\n }\n\n @Override public int count() {\n return getCollection().size();\n }\n\n @Override public long longCount() {\n return getCollection().size();\n }\n\n @Override public boolean contains(T element) {\n return getCollection().contains(element);\n }\n\n @Override public boolean any() {\n return !getCollection().isEmpty();\n }\n }\n\n /** List enumerable.\n *\n * @param element type */\n static class ListEnumerable extends CollectionEnumerable {\n ListEnumerable(List list) {\n super(list);\n }\n\n @Override public Enumerator enumerator() {\n if (iterable instanceof RandomAccess) {\n //noinspection unchecked\n return new ListEnumerator<>((List) iterable);\n }\n return super.enumerator();\n }\n\n @Override public List toList() {\n return (List) iterable;\n }\n\n @Override public Enumerable skip(int count) {\n final List list = toList();\n if (count >= list.size()) {\n return Linq4j.emptyEnumerable();\n }\n return new ListEnumerable<>(list.subList(count, list.size()));\n }\n\n @Override public Enumerable take(int count) {\n final List list = toList();\n if (count >= list.size()) {\n return this;\n }\n return new ListEnumerable<>(list.subList(0, count));\n }\n\n @Override public T elementAt(int index) {", "answers": [" return toList().get(index);"], "length": 2202, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "d43f99a5-725f-45df-abbd-e7a679f35451", "reasoning": "The code is inside the ListEnumerable class, which provides list‑specific implementations of Enumerable methods. After the method header `public T elementAt(int index) {`, the logical implementation is to retrieve the element at the given position from the underlying list. The class already has a `toList()` helper that returns the underlying list, so the next line should simply return `toList().get(index);`. This matches the typical behavior of `elementAt` in Linq4j, delegating to `List.get` (which throws IndexOutOfBoundsException for invalid indices).", "reasoning_model_answer": "return toList().get(index);", "assistant_with_reasoning": "\nThe code is inside the ListEnumerable class, which provides list‑specific implementations of Enumerable methods. After the method header `public T elementAt(int index) {`, the logical implementation is to retrieve the element at the given position from the underlying list. The class already has a `toList()` helper that returns the underlying list, so the next line should simply return `toList().get(index);`. This matches the typical behavior of `elementAt` in Linq4j, delegating to `List.get` (which throws IndexOutOfBoundsException for invalid indices).\n\nreturn toList().get(index);", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.712, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 18283, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "return toList().get(index);", "score": 0.9, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "package com.pgmacdesign.pgmactips.misc;\n\nimport com.google.gson.reflect.TypeToken;\n\nimport java.lang.reflect.Type;\n\n/**\n * Created by pmacdowell on 8/12/2016.\n */\npublic class PGMacTipsConstants {\n\n\t///////////////\n\t//Misc Values//\n\t///////////////\n\t\n\t// TODO: 2018-02-13 refactor this into preferences setup\n\tpublic static final String PGMACTIPS_PACKAGE_ID = \"com.pgmacdesign.pgmactips\";\n\tpublic static final String PGMACTIPS_CONTEXT_PROVIDER = \"PGMacContextProvider\";\n\tpublic static final String PGMACTIPS_STRING = \"PGMacTips\";\n\n /////////////////\n //Misc Booleans//\n /////////////////\n\n // TODO: 2018-02-13 refactor this into preferences setup\n public static final boolean ATTEMPT_TO_PARSE_HTML = false;\n\n ////////////////\n //Misc Strings//\n ////////////////\n\n public static final String PHONE_URI_TO_WRITE_TO = \"/storage/emulated/0/Download/\";\n public static final String FILE_NAME = \"debugLoggingData.txt\";\n public static final String URL_GOOGLE = \"https://www.google.com\";\n\tpublic static final String FILE_PREFIX = \"file://\";\n public static final String NO_INTERNET_STRING = \"It looks like you do not have a stable internet connection. Please check for connectivity and try again\";\n public static final String ARRAY_PAGER_ADAPTER_ERROR_1 = \"Error: Null fragment in passed map.\";\n public static final String HEX = \"0123456789ABCDEF\";\n public static final String UTF8 = \"UTF-8\";\n public static final String COOKIE_1 = \"Cookie\";\n public static final String COOKIE_2 = \"Set-Cookie\";\n \n /////////////////////////////////////////////////////////////\n //Custom Tags (There is no specific order to these numbers)//\n /////////////////////////////////////////////////////////////\n\n //Request codes used for permission requests\n public static final int TAG_PERMISSIONS_ACCESS_NETWORK_STATE = 3398;\n //public static final int TAG_PERMISSIONS_REQUEST_GALLERY = 4399;\n public static final int TAG_PERMISSIONS_REQUEST_BASE_CALL = 3300;\n public static final int TAG_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE = 3301;\n public static final int TAG_PERMISSIONS_REQUEST_CAMERA = 3302;\n public static final int TAG_PERMISSIONS_REQUEST_ALL = 3303;\n public static final int TAG_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE = 3304;\n public static final int TAG_PERMISSIONS_REQUEST_READ_PHONE_STATE = 3305;\n public static final int TAG_PERMISSIONS_REQUEST_CONTACTS = 3306;\n public static final int TAG_PERMISSIONS_ACCESS_WIFI_STATE = 3307;\n public static final int TAG_PERMISSIONS_ACCESS_FINE_LOCATION = 3308;\n public static final int TAG_PERMISSIONS_ACCESS_COARSE_LOCATION = 3309;\n public static final int TAG_PERMISSIONS_RECEIVE_BOOT_COMPLETED = 3310;\n public static final int TAG_RETROFIT_PARSE_ERROR = 3311;\n public static final int TAG_RETROFIT_CALL_ERROR = 3312;\n public static final int TAG_PERMISSIONS_FINGERPRINT = 3313;\n public static final int TAG_PERMISSIONS_BIOMETRICS = 3314;\n public static final int TAG_PERMISSIONS_BLUETOOTH = 3315;\n public static final int TAG_PERMISSIONS_BLUETOOTH_ADMIN = 3316;\n public static final int TAG_RETROFIT_CALL_ERROR_OLD = 3317;\n public static final int TAG_TBD7 = 3318;\n public static final int TAG_TBD8 = 3319;\n public static final int TAG_TBD9 = 3320;\n\n //File Creation Tags\n public static final int TAG_TXT_FILE_CREATION = 3400;\n //Date Formatting Tags, used for comparison and formatting\n /**\n * Sample: Wed Oct 16 15:21:20 PST 2018\n */\n public static final int DATE_EEEE_MMM_dd_HH_mm_ss_z_yyyy = 4403;\n /**\n * Sample: 2018-10-16\n */\n public static final int DATE_YYYY_MM_DD_T_HH_MM_SS_SSS_Z = 4403;\n public static final int DATE_YYYY_MM_DD_T_HH_MM_SS_Z = 4404;\n public static final int DATE_MM_DD_YYYY = 4405;\n public static final int DATE_MM_DD_YY = 4406;\n public static final int DATE_YYYY_MM_DD = 4407;\n public static final int DATE_MM_DD = 4408;\n public static final int DATE_MM_YY = 4409;\n public static final int DATE_MM_YYYY = 4410;\n public static final int DATE_MILLISECONDS = 4411;\n public static final int DATE_EPOCH = 4412;\n public static final int DATE_MM_DD_YYYY_HH_MM = 4413;\n\n public static int[] ALL_DATE_TYPES = {DATE_YYYY_MM_DD_T_HH_MM_SS_SSS_Z,\n DATE_YYYY_MM_DD_T_HH_MM_SS_Z, DATE_MM_DD_YYYY, DATE_MM_DD_YY, DATE_YYYY_MM_DD,\n DATE_MM_DD, DATE_MM_YY, DATE_MM_YYYY, DATE_MM_DD_YYYY_HH_MM};\n\n //More Misc Tags\n public static final int TAG_OAUTH_DATA_OBJECT = 4414;\n public static final int TAG_OAUTH_ERROR = 4415;\n public static final int TAG_PHOTO_BAD_URL = 4416;\n public static final int TAG_FILE_DOWNLOADED = 4417;\n public static final int TAG_DIALOG_POPUP_YES = 4418;\n public static final int TAG_DIALOG_POPUP_NO = 4419;\n public static final int TAG_DIALOG_POPUP_CANCEL = 4420;\n public static final int TAG_PHONE_QUERY_REGEX_FAIL = 4421;\n public static final int TAG_PHONE_QUERY_REGEX_SUCCESS = 4422;\n public static final int TAG_CONTACT_QUERY_EMAIL = 4423;\n public static final int TAG_CONTACT_QUERY_PHONE = 4424;\n public static final int TAG_CONTACT_QUERY_ADDRESS = 4425;\n public static final int TAG_CONTACT_QUERY_NAME = 4426;\n public static final int TAG_TAKE_PICTURE_WITH_CAMERA = 4427;\n public static final int TAG_PHOTO_FROM_GALLERY = 4428;\n public static final int TAG_CROP_PHOTO = 4429;\n public static final int TAG_RETURN_IMAGE_URL = 4430;\n public static final int TAG_TAKE_VIDEO_WITH_RECORDER = 4431;\n public static final int TAG_MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE = 4432;\n public static final int TAG_MY_PERMISSIONS_REQUEST_CAMERA = 4433;\n public static final int TAG_PHOTO_UNKNOWN_ERROR = 4434;\n public static final int TAG_CROP_ERROR = 4435;\n public static final int TAG_CROP_SUCCESS = 4436;\n public static final int TAG_PHOTO_CANCEL = 4437;\n public static final int TAG_UPLOAD_ERROR = 4438;\n public static final int TAG_UPLOAD_SUCCESS = 4439;\n public static final int TAG_CLICK_NO_TAG_SENT = 4440;\n public static final int TAG_LONG_CLICK_NO_TAG_SENT = 4441;\n public static final int TAG_RETROFIT_CALL_FAILED = 4442;\n public static final int TAG_RETROFIT_CALL_SUCCESS_BOOLEAN = 4443;\n public static final int TAG_RETROFIT_CALL_SUCCESS_STRING = 4444;\n public static final int TAG_RETROFIT_CALL_SUCCESS_OBJECT = 4445;\n public static final int TAG_TAKE_SELF_PHOTO = 4446;\n public static final int TAG_TAKE_SELF_PHOTO_SUCCESS = 4447;\n public static final int TAG_TAKE_SELF_PHOTO_FAILURE = 4448;\n public static final int TAG_FRAGMENT_SWITCHER_ERROR = 4449;\n public static final int TAG_FRAGMENT_SWITCHER_OBJECT = 4450;\n public static final int TAG_FRAGMENT_SWITCHER_NO_OBJECT = 4451;\n public static final int TAG_TIMER_UTILITIES_FINISHED = 4452;\n public static final int TAG_TIMER_UTILITIES_FINISHED_WITH_DATA = 4453;\n public static final int TAG_SMS_RECEIVED_BROADCAST_RECEIVER = 4454;\n public static final int TAG_SMS_RECEIVED_BROADCAST_RECEIVER_EMPTY = 4455;\n public static final int TAG_VIEW_PARAMS_LOADED = 4456;\n public static final int TAG_VIEW_PARAMS_LOADING_FAILED = 4457;\n public static final int TAG_VIEW_FINISHED_DRAWING = 4458;\n public static final int TAG_FCM_SUCCESS_RESPONSE = 4459;\n public static final int TAG_FCM_FAIL_RESPONSE = 4460;\n public static final int TAG_NO_INTERNET = 4461;\n public static final int TAG_BASE64_IMAGE_ENCODE_SUCCESS = 4462;\n public static final int TAG_BASE64_IMAGE_ENCODE_FAIL = 4463;\n public static final int TAG_MULTIPURPOSE_CHOICE_CLICK_ADAPTER = 4464;\n public static final int TAG_MULTIPURPOSE_CHOICE_LONG_CLICK_ADAPTER = 4465;\n\tpublic static final int TAG_MAP_STRING_INTEGER = 4466;\n\tpublic static final int TAG_STRING = 4467;\n\tpublic static final int TAG_SIMPLE_TEXT_ICON_ADAPTER_CLICK = 4468;\n\tpublic static final int TAG_GENERIC_FILTER_RESULTS = 4469;\n\tpublic static final int TAG_CONTACT_QUERY_PROGRESS_UPDATE = 4470;\n public static final int TAG_CONTACT_QUERY_NO_RESULTS = 4471;\n public static final int TAG_CONTACT_QUERY_MISSING_CONTACT_PERMISSION = 4472;\n public static final int TAG_CONTACT_QUERY_UNKNOWN_ERROR = 4473;\n public static final int TAG_CONTACT_QUERY_ALL_MERGED_RESULTS = 4474;\n public static final int TAG_INVALID_BASE_64_IMAGE = 4475;\n public static final int TAG_GOOGLE_VISION_SUCCESS_RESULT = 4476;\n public static final int TAG_GOOGLE_VISION_FAIL_RESULT = 4477;\n public static final int TAG_GOOGLE_VISION_UNKNOWN_ERROR = 4478;\n public static final int TAG_INVALID_BITMAP_IMAGE = 4479;\n public static final int TAG_BITMAP_BASE64_CONVERSION_FAIL = 4480;\n public static final int TAG_LIFE_CYCLE_LISTENER = 4481;\n public static final int TAG_COOKIES_HASHSET_RESPONSE = 4482;\n public static final int TBD2 = 4483;\n public static final int TBD3 = 4484;\n\n //String Tags\n public static final String TAG_SELF_PHOTO_URI = \"tag_self_photo_uri\";\n\n ///////////////////////////////////////////\n //Database / Shared Preferences Constants//\n ///////////////////////////////////////////\n\n public static final String DB_NAME = \"PGMacTips.DB\";\n public static final boolean DELETE_DB_IF_NEEDED = true;\n public static final int DB_VERSION = 1;\n public static final String SHARED_PREFS_NAME = \"PGMacTips.SP\";\n\n ////////////////\n //Time Values //\n ////////////////\n\n //Time values in milliseconds\n public static final long ONE_SECOND = (long)(1000L);\n public static final long ONE_MINUTE = (long)(1000L*60L);\n public static final long ONE_HOUR = (long)(1000L*60L*60L);\n public static final long ONE_DAY = (long)(1000L*60L*60L*24L);\n public static final long ONE_WEEK = (long)(1000L*60L*60L*24L*7L);\n public static final long ONE_MONTH = (long)(1000L*60L*60L*24L*30L);\n public static final long ONE_YEAR = (long)(1000L*60L*60L*24L*365L);\n\n //Size Values\n public static final long ONE_BYTE = 1L;\n public static final long ONE_KILOBYTE = 1024L;\n public static final long ONE_MEGABYTE = 1024L * 1024L;\n public static final long ONE_GIGABYTE = 1024L * 1024L * 1024L;\n public static final long ONE_TERABYTE = 1024L * 1024L * 1024L * 1024L;\n public static final long ONE_PETABYTE = 1024L * 1024L * 1024L * 1024L * 1024L;\n public static final long ONE_EXABYTE = 1024L * 1024L * 1024L * 1024L * 1024L * 1024L;\n// public static final long ONE_ZETTABYTE = 1024L * 1024L * 1024L * 1024L * 1024L * 1024L * 1024L;\n// public static final long ONE_YOTTABYTE = 1024L * 1024L * 1024L * 1024L * 1024L * 1024L * 1024L * 1024L;\n\n\n //Default Date Formats\n public static final String DEFAULT_ISO_FORMAT = \"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'\";\n public static final String DEFAULT_ISO_FORMAT_WITHOUT_MILLISECONDS = \"yyyy-MM-dd'T'HH:mm:ss'Z'\";\n //This is the string format received when calling Date date = new Date().toString(); //<---\n public static final String DEFAULT_JAVA_DATE_FORMAT = \"EEEE MMM dd HH:mm:ss z yyyy\";\n public static final String DATE_STRING_PATTERN_24_HOUR_TIME = \"HH:mm\";\n public static final String DATE_STRING_PATTERN_12_HOUR_TIME = \"hh:mm a\";\n\n //////////\n //Colors//\n //////////\n\n //Color Strings\n public static final String COLOR_TRANSPARENT = \"#00000000\";\n public static final String COLOR_WHITE = \"#FFFFFF\";\n public static final String COLOR_BLACK = \"#000000\";\n public static final String COLOR_YELLOW = \"#FFFF00\";\n public static final String COLOR_FUCHSIA = \"#FF00FF\";\n public static final String COLOR_RED = \"#FF0000\";\n public static final String COLOR_SILVER = \"#C0C0C0\";\n public static final String COLOR_GRAY = \"#808080\";\n public static final String COLOR_LIGHT_GRAY = \"#D3D3D3\";\n public static final String COLOR_DARK_GRAY = \"#666666\";\n public static final String COLOR_OLIVE = \"#808000\";\n public static final String COLOR_PURPLE = \"#800080\";\n public static final String COLOR_MAROON = \"#800000\";\n public static final String COLOR_AQUA = \"#00FFFF\";\n public static final String COLOR_LIME = \"#00FF00\";\n public static final String COLOR_TEAL = \"#008080\";\n public static final String COLOR_GREEN = \"#008000\";\n public static final String COLOR_PINK = \"#FFC0CB\";\n public static final String COLOR_BLUE = \"#0000FF\";\n public static final String COLOR_NAVY_BLUE = \"#000080\";\n //For the Semi transparent colors, the higher the number, the darker (less opaque) the color\n public static final String COLOR_SEMI_TRANSPARENT_1 = \"#20111111\";\n public static final String COLOR_SEMI_TRANSPARENT_2 = \"#30111111\";\n public static final String COLOR_SEMI_TRANSPARENT_3 = \"#40111111\";\n public static final String COLOR_SEMI_TRANSPARENT_4 = \"#50111111\";\n public static final String COLOR_SEMI_TRANSPARENT_5 = \"#69111111\";\n public static final String COLOR_SEMI_TRANSPARENT_6 = \"#79111111\";\n public static final String COLOR_SEMI_TRANSPARENT_7 = \"#89111111\";\n public static final String COLOR_SEMI_TRANSPARENT_8 = \"#99111111\";\n public static final String COLOR_SEMI_TRANSPARENT_9 = \"#A9111111\";\n\n /////////////\n //Raw Types//\n /////////////\n\n public static final Type TYPE_BOOLEAN = Boolean.TYPE;\n public static final Type TYPE_DOUBLE = Double.TYPE;\n public static final Type TYPE_INTEGER = Integer.TYPE;\n public static final Type TYPE_STRING = new TypeToken(){}.getType();\n\n ///////////////////////\n //Regular Expressions//\n ///////////////////////\n\n //Credit Card Regular Expressions\n public static final String REGEX_CREDIT_CARD_VISA = \"^4[0-9]{12}(?:[0-9]{3})?$\";\n public static final String REGEX_CREDIT_CARD_MASTERCARD = \"^5[1-5][0-9]{14}$\";\n public static final String REGEX_CREDIT_CARD_AMERICAN_EXPRESS = \"^3[47][0-9]{13}$\";\n public static final String REGEX_CREDIT_CARD_DINERS_CLUB = \"^3(?:0[0-5]|[68][0-9])[0-9]{11}$\";\n public static final String REGEX_CREDIT_CARD_DISCOVER = \"^6(?:011|5[0-9]{2})[0-9]{12}$\";\n public static final String REGEX_CREDIT_CARD_JCB = \"^(?:2131|1800|35\\\\d{3})\\\\d{11}$\";\n public static final String REGEX_CREDIT_CARD_UNKNOWN = \"^unknown$\";\n\n //Misc Regexs\n public static final String REGEX_WEB_URL_ENCODING = \"\\\\b(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]\";\n public static final String REGEX_HTML = \"<(\\\\\\\"[^\\\\\\\"]*\\\\\\\"|'[^']*'|[^'\\\\\\\">])*>\";\n public static final String REGEX_HTML2 = \"\";\n public static final String REGEX_PASSWORD_PATTERN = \"^\\\\S*(?=\\\\S*[a-zA-Z])(?=\\\\S*[0-9])\\\\S*$\";\n public static final String REGEX_INTEGER = \"^[0-9]+$\";\n public static final String REGEX_DECIMAL = \"^[0-9]+(?:\\\\.[0-9]+)?$\";\n public static final String REGEX_MONEY = \"^[0-9]+(?:\\\\.[0-9]{0,2})?$\";\n public static final String REGEX_MONEY_SIGNED = \"^[-+]?[0-9]+(?:\\\\.[0-9]{0,2})?$\";\n public static final String REGEX_PHONE = \"^ *\\\\(?[0-9]{3,3}[-\\\\.\\\\)]? ?[0-9]{3,3}[-\\\\. ]?[0-9]{4,4} *$\";\n public static final String REGEX_COLOR = \"^#[0-9a-fA-F]{6,6}$\";\n public static final String REGEX_DATE = \"^[0-9]{1,2}[-/][0-9]{1,2}[-/][0-9]{2,4}$\";\n public static final String REGEX_EMAIL = \"^\\\\s*[^@\\\\s]+@(?:[^@\\\\.\\\\s]+\\\\.[^@\\\\.\\\\s]+)+\\\\s*$\";\n public static final String REGEX_NEW_LINE = \"[\\\\r\\\\n]+\";\n// public static final String REGEX_IPADDRESS = \"^[0-9]{1,3}\\\\.[0-9]{1,3}\\\\.[0-9]{1,3}\\\\.[0-9]{1,3}$\";\n //Updated as per: https://www.mkyong.com/regular-expressions/how-to-validate-ip-address-with-regular-expression/\n public static final String REGEX_IPADDRESS = \"^([01]?\\\\\\\\d\\\\\\\\d?|2[0-4]\\\\\\\\d|25[0-5])\\\\\\\\.([01]?\\\\\\\\d\\\\\\\\d?|2[0-4]\\\\\\\\d|25[0-5])\\\\\\\\.\\n\" +\n \"([01]?\\\\\\\\d\\\\\\\\d?|2[0-4]\\\\\\\\d|25[0-5])\\\\\\\\.([01]?\\\\\\\\d\\\\\\\\d?|2[0-4]\\\\\\\\d|25[0-5])$\\n\";\n\n ////////////////////////////////\n //Animation Constants and Tags//\n ////////////////////////////////\n\n /**\n * Animation Techniques (From the library com.daimajia.androidanimations:library:1.1.3@aar).\n * In means it brings them into sight while out takes them out of sight\n *\n * Note, removing these for now as they are causing an exception to be thrown if the end developer\n * does not include the animations library\n *\n *\n\n public static final Techniques IN_ZOOM_UP = Techniques.ZoomInUp; //Fun one, opposite of ZoomOutDown, zooms it up and then in\n public static final Techniques OUT_ZOOM_DOWN = Techniques.ZoomOutDown; //Fun one, zooms away (back) and then down, useful for getting rid of things\n public static final Techniques IN_ROLL = Techniques.RollIn;//Fly in effect looks nice for new views popping in\n public static final Techniques IN_PULSE = Techniques.Pulse; //Pops the view front and back, good for a focuser\n public static final Techniques OUT_HINGE = Techniques.Hinge; //Looks like broken hinge on view and it falls off, fun looking\n public static final Techniques IN_RUBBERBAND = Techniques.RubberBand; //Good for a 'de-select' kind of effect\n public static final Techniques OUT_FLIP_Y = Techniques.FlipOutY; //Clean looking flip out on y Axis, good for deletion/ removal\n public static final Techniques IN_FLIP_X = Techniques.FlipInX; //Clean flip look. Looks like it's rotating on the X axis in\n public static final Techniques OUT_FLIP_X = Techniques.FlipOutX; //Opposite of FlipInX, good for deletetion / removal\n public static final Techniques OUT_SLIDE = Techniques.SlideOutUp; //Using SlideOutUp in conjunction with SlideInUp would look kinda cool...\n public static final Techniques IN_RIGHT_SLIDE = Techniques.SlideInRight; //Using SlideOutUp in conjunction with SlideInUp would look kinda cool...\n public static final Techniques IN_LEFT_SLIDE = Techniques.SlideInLeft; //Using SlideOutUp in conjunction with SlideInUp would look kinda cool...\n public static final Techniques IN_SLIDE = Techniques.SlideInUp; //Using SlideOutUp in conjunction with SlideInUp would look kinda cool...\n public static final Techniques IN_FADE_DOWN = Techniques.FadeInDown; //Simple fade in and down animation\n public static final Techniques IN_FADE_UP = Techniques.FadeInUp; //Simple fade in and up animation\n public static final Techniques IN_DROP = Techniques.DropOut; //Looks cool, falls down from top and bounces\n public static final Techniques IN_TADA = Techniques.Tada; //Fun one, seems useful for focusing on a view\n public static final Techniques OUT_ROLL = Techniques.RollOut;\n public static final Techniques OUT_ZOOM = Techniques.ZoomOut;\n public static final Techniques IN_FLASH = Techniques.Flash; //Quick flash\n\n */\n\n \n //////////////////////\n //Misc Useful Values//\n //////////////////////\n\n /**\n * List of States for dropdown menus or other GUI-related uses\n */\n public static final String[] ALL_US_STATES = {\"California\", \"Alabama\", \"Arkansas\", \"Arizona\", \"Alaska\",\n \"Colorado\", \"Connecticut\", \"Delaware\", \"Florida\", \"Georgia\", \"Hawaii\", \"Idaho\", \"Illinois\",\n \"Indiana\", \"Iowa\", \"Kansas\", \"Kentucky\", \"Louisiana\", \"Maine\", \"Maryland\", \"Massachusetts\",\n \"Michigan\", \"Minnesota\", \"Mississippi\", \"Missouri\", \"Montana\", \"Nebraska\", \"Nevada\", \"New Hampshire\",\n \"New Jersey\", \"New Mexico\", \"New York\", \"North Carolina\", \"North Dakota\", \"Ohio\", \"Oklahoma\", \"Oregon\",\n \"Pennsylvania\", \"Rhode Island\", \"South Carolina\", \"South Dakota\", \"Tennessee\", \"Texas\", \"Utah\", \"Vermont\",\n \"Virginia\", \"Washington\", \"Washington DC\", \"West Virginia\", \"Wisconsin\", \"Wyoming\"\n };\n\n /**\n * USA Territories. List obtained from:\n * https://www.50states.com/abbreviations.htm\n */\n public static enum USATerritories {\n Alabama(\"Alabama\", \"AL\"),\n Alaska(\"Alaska\", \"AK\"),\n Arizona(\"Arizona\", \"AZ\"),\n Arkansas(\"Arkansas\", \"AR\"),\n California(\"California\", \"CA\"),\n Colorado(\"Colorado\", \"CO\"),\n Connecticut(\"Connecticut\", \"CT\"),\n Delaware(\"Delaware\", \"DE\"),\n Florida(\"Florida\", \"FL\"),\n Georgia(\"Georgia\", \"GA\"),\n Hawaii(\"Hawaii\", \"HI\"),\n Idaho(\"Idaho\", \"ID\"),\n Illinois(\"Illinois\", \"IL\"),\n Indiana(\"Indiana\", \"IN\"),\n Iowa(\"Iowa\", \"IA\"),\n Kansas(\"Kansas\", \"KS\"),\n Kentucky(\"Kentucky\", \"KY\"),", "answers": [" Louisiana(\"Louisiana\", \"LA\"),"], "length": 2195, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "ad483867-c6dc-4776-96a7-5d87aebb2704", "reasoning": "The enum USATerritories lists US states with name and abbreviation. After the Kentucky entry, the next state alphabetically is Louisiana. Enum constants continue separated by commas, so the next line should define Louisiana.", "reasoning_model_answer": "Louisiana(\"Louisiana\", \"LA\"),", "assistant_with_reasoning": "\nThe enum USATerritories lists US states with name and abbreviation. After the Kentucky entry, the next state alphabetically is Louisiana. Enum constants continue separated by commas, so the next line should define Louisiana.\n\nLouisiana(\"Louisiana\", \"LA\"),", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 2.339, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 20365, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "Louisiana(\"Louisiana\", \"LA\"),", "score": 0.88, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "\"\"\"\nCode generator script to make the Cython BLAS and LAPACK wrappers\nfrom the files \"cython_blas_signatures.txt\" and\n\"cython_lapack_signatures.txt\" which contain the signatures for\nall the BLAS/LAPACK routines that should be included in the wrappers.\n\"\"\"\n\nfrom collections import defaultdict\nfrom operator import itemgetter\nimport os\n\nBASE_DIR = os.path.abspath(os.path.dirname(__file__))\n\nfortran_types = {'int': 'integer',\n 'c': 'complex',\n 'd': 'double precision',\n 's': 'real',\n 'z': 'complex*16',\n 'char': 'character',\n 'bint': 'logical'}\n\nc_types = {'int': 'int',\n 'c': 'npy_complex64',\n 'd': 'double',\n 's': 'float',\n 'z': 'npy_complex128',\n 'char': 'char',\n 'bint': 'int',\n 'cselect1': '_cselect1',\n 'cselect2': '_cselect2',\n 'dselect2': '_dselect2',\n 'dselect3': '_dselect3',\n 'sselect2': '_sselect2',\n 'sselect3': '_sselect3',\n 'zselect1': '_zselect1',\n 'zselect2': '_zselect2'}\n\n\ndef arg_names_and_types(args):\n return zip(*[arg.split(' *') for arg in args.split(', ')])\n\n\npyx_func_template = \"\"\"\ncdef extern from \"{header_name}\":\n void _fortran_{name} \"F_FUNC({name}wrp, {upname}WRP)\"({ret_type} *out, {fort_args}) nogil\ncdef {ret_type} {name}({args}) nogil:\n cdef {ret_type} out\n _fortran_{name}(&out, {argnames})\n return out\n\"\"\"\n\nnpy_types = {'c': 'npy_complex64', 'z': 'npy_complex128',\n 'cselect1': '_cselect1', 'cselect2': '_cselect2',\n 'dselect2': '_dselect2', 'dselect3': '_dselect3',\n 'sselect2': '_sselect2', 'sselect3': '_sselect3',\n 'zselect1': '_zselect1', 'zselect2': '_zselect2'}\n\n\ndef arg_casts(arg):\n if arg in ['npy_complex64', 'npy_complex128', '_cselect1', '_cselect2',\n '_dselect2', '_dselect3', '_sselect2', '_sselect3',\n '_zselect1', '_zselect2']:\n return '<{0}*>'.format(arg)\n return ''\n\n\ndef pyx_decl_func(name, ret_type, args, header_name):\n argtypes, argnames = arg_names_and_types(args)\n # Fix the case where one of the arguments has the same name as the\n # abbreviation for the argument type.\n # Otherwise the variable passed as an argument is considered overwrites\n # the previous typedef and Cython compilation fails.\n if ret_type in argnames:\n argnames = [n if n != ret_type else ret_type + '_' for n in argnames]\n argnames = [n if n not in ['lambda', 'in'] else n + '_'\n for n in argnames]\n args = ', '.join([' *'.join([n, t])\n for n, t in zip(argtypes, argnames)])\n argtypes = [npy_types.get(t, t) for t in argtypes]\n fort_args = ', '.join([' *'.join([n, t])\n for n, t in zip(argtypes, argnames)])\n argnames = [arg_casts(t) + n for n, t in zip(argnames, argtypes)]\n argnames = ', '.join(argnames)\n c_ret_type = c_types[ret_type]\n args = args.replace('lambda', 'lambda_')\n return pyx_func_template.format(name=name, upname=name.upper(), args=args,\n fort_args=fort_args, ret_type=ret_type,\n c_ret_type=c_ret_type, argnames=argnames,\n header_name=header_name)\n\n\npyx_sub_template = \"\"\"cdef extern from \"{header_name}\":\n void _fortran_{name} \"F_FUNC({name},{upname})\"({fort_args}) nogil\ncdef void {name}({args}) nogil:\n _fortran_{name}({argnames})\n\"\"\"\n\n\ndef pyx_decl_sub(name, args, header_name):\n argtypes, argnames = arg_names_and_types(args)\n argtypes = [npy_types.get(t, t) for t in argtypes]\n argnames = [n if n not in ['lambda', 'in'] else n + '_' for n in argnames]\n fort_args = ', '.join([' *'.join([n, t])\n for n, t in zip(argtypes, argnames)])\n argnames = [arg_casts(t) + n for n, t in zip(argnames, argtypes)]\n argnames = ', '.join(argnames)\n args = args.replace('*lambda,', '*lambda_,').replace('*in,', '*in_,')\n return pyx_sub_template.format(name=name, upname=name.upper(),\n args=args, fort_args=fort_args,\n argnames=argnames, header_name=header_name)\n\n\nblas_pyx_preamble = '''# cython: boundscheck = False\n# cython: wraparound = False\n# cython: cdivision = True\n\n\"\"\"\nBLAS Functions for Cython\n=========================\n\nUsable from Cython via::\n\n cimport scipy.linalg.cython_blas\n\nThese wrappers do not check for alignment of arrays.\nAlignment should be checked before these wrappers are used.\n\nRaw function pointers (Fortran-style pointer arguments):\n\n- {}\n\n\n\"\"\"\n\n# Within SciPy, these wrappers can be used via relative or absolute cimport.\n# Examples:\n# from ..linalg cimport cython_blas\n# from scipy.linalg cimport cython_blas\n# cimport scipy.linalg.cython_blas as cython_blas\n# cimport ..linalg.cython_blas as cython_blas\n\n# Within SciPy, if BLAS functions are needed in C/C++/Fortran,\n# these wrappers should not be used.\n# The original libraries should be linked directly.\n\ncdef extern from \"fortran_defs.h\":\n pass\n\nfrom numpy cimport npy_complex64, npy_complex128\n\n'''\n\n\ndef make_blas_pyx_preamble(all_sigs):\n names = [sig[0] for sig in all_sigs]\n return blas_pyx_preamble.format(\"\\n- \".join(names))\n\n\nlapack_pyx_preamble = '''\"\"\"\nLAPACK functions for Cython\n===========================\n\nUsable from Cython via::\n\n cimport scipy.linalg.cython_lapack\n\nThis module provides Cython-level wrappers for all primary routines included\nin LAPACK 3.4.0 except for ``zcgesv`` since its interface is not consistent\nfrom LAPACK 3.4.0 to 3.6.0. It also provides some of the\nfixed-api auxiliary routines.\n\nThese wrappers do not check for alignment of arrays.\nAlignment should be checked before these wrappers are used.\n\nRaw function pointers (Fortran-style pointer arguments):\n\n- {}\n\n\n\"\"\"\n\n# Within SciPy, these wrappers can be used via relative or absolute cimport.\n# Examples:\n# from ..linalg cimport cython_lapack\n# from scipy.linalg cimport cython_lapack\n# cimport scipy.linalg.cython_lapack as cython_lapack\n# cimport ..linalg.cython_lapack as cython_lapack\n\n# Within SciPy, if LAPACK functions are needed in C/C++/Fortran,\n# these wrappers should not be used.\n# The original libraries should be linked directly.\n\ncdef extern from \"fortran_defs.h\":\n pass\n\nfrom numpy cimport npy_complex64, npy_complex128\n\ncdef extern from \"_lapack_subroutines.h\":\n # Function pointer type declarations for\n # gees and gges families of functions.\n ctypedef bint _cselect1(npy_complex64*)\n ctypedef bint _cselect2(npy_complex64*, npy_complex64*)\n ctypedef bint _dselect2(d*, d*)\n ctypedef bint _dselect3(d*, d*, d*)\n ctypedef bint _sselect2(s*, s*)\n ctypedef bint _sselect3(s*, s*, s*)\n ctypedef bint _zselect1(npy_complex128*)\n ctypedef bint _zselect2(npy_complex128*, npy_complex128*)\n\n'''\n\n\ndef make_lapack_pyx_preamble(all_sigs):\n names = [sig[0] for sig in all_sigs]\n return lapack_pyx_preamble.format(\"\\n- \".join(names))\n\n\nblas_py_wrappers = \"\"\"\n\n# Python-accessible wrappers for testing:\n\ncdef inline bint _is_contiguous(double[:,:] a, int axis) nogil:\n return (a.strides[axis] == sizeof(a[0,0]) or a.shape[axis] == 1)\n\ncpdef float complex _test_cdotc(float complex[:] cx, float complex[:] cy) nogil:\n cdef:\n int n = cx.shape[0]\n int incx = cx.strides[0] // sizeof(cx[0])\n int incy = cy.strides[0] // sizeof(cy[0])\n return cdotc(&n, &cx[0], &incx, &cy[0], &incy)\n\ncpdef float complex _test_cdotu(float complex[:] cx, float complex[:] cy) nogil:\n cdef:\n int n = cx.shape[0]\n int incx = cx.strides[0] // sizeof(cx[0])\n int incy = cy.strides[0] // sizeof(cy[0])\n return cdotu(&n, &cx[0], &incx, &cy[0], &incy)\n\ncpdef double _test_dasum(double[:] dx) nogil:\n cdef:\n int n = dx.shape[0]\n int incx = dx.strides[0] // sizeof(dx[0])\n return dasum(&n, &dx[0], &incx)\n\ncpdef double _test_ddot(double[:] dx, double[:] dy) nogil:\n cdef:\n int n = dx.shape[0]\n int incx = dx.strides[0] // sizeof(dx[0])\n int incy = dy.strides[0] // sizeof(dy[0])\n return ddot(&n, &dx[0], &incx, &dy[0], &incy)\n\ncpdef int _test_dgemm(double alpha, double[:,:] a, double[:,:] b, double beta,\n double[:,:] c) nogil except -1:\n cdef:\n char *transa\n char *transb\n int m, n, k, lda, ldb, ldc\n double *a0=&a[0,0]\n double *b0=&b[0,0]\n double *c0=&c[0,0]\n # In the case that c is C contiguous, swap a and b and\n # swap whether or not each of them is transposed.\n # This can be done because a.dot(b) = b.T.dot(a.T).T.\n if _is_contiguous(c, 1):\n if _is_contiguous(a, 1):\n transb = 'n'\n ldb = (&a[1,0]) - a0 if a.shape[0] > 1 else 1\n elif _is_contiguous(a, 0):\n transb = 't'\n ldb = (&a[0,1]) - a0 if a.shape[1] > 1 else 1\n else:\n with gil:\n raise ValueError(\"Input 'a' is neither C nor Fortran contiguous.\")\n if _is_contiguous(b, 1):\n transa = 'n'\n lda = (&b[1,0]) - b0 if b.shape[0] > 1 else 1\n elif _is_contiguous(b, 0):\n transa = 't'\n lda = (&b[0,1]) - b0 if b.shape[1] > 1 else 1\n else:\n with gil:\n raise ValueError(\"Input 'b' is neither C nor Fortran contiguous.\")\n k = b.shape[0]\n if k != a.shape[1]:\n with gil:\n raise ValueError(\"Shape mismatch in input arrays.\")\n m = b.shape[1]\n n = a.shape[0]\n if n != c.shape[0] or m != c.shape[1]:\n with gil:\n raise ValueError(\"Output array does not have the correct shape.\")\n ldc = (&c[1,0]) - c0 if c.shape[0] > 1 else 1\n dgemm(transa, transb, &m, &n, &k, &alpha, b0, &lda, a0,\n &ldb, &beta, c0, &ldc)\n elif _is_contiguous(c, 0):\n if _is_contiguous(a, 1):\n transa = 't'\n lda = (&a[1,0]) - a0 if a.shape[0] > 1 else 1\n elif _is_contiguous(a, 0):\n transa = 'n'\n lda = (&a[0,1]) - a0 if a.shape[1] > 1 else 1\n else:\n with gil:\n raise ValueError(\"Input 'a' is neither C nor Fortran contiguous.\")\n if _is_contiguous(b, 1):\n transb = 't'\n ldb = (&b[1,0]) - b0 if b.shape[0] > 1 else 1\n elif _is_contiguous(b, 0):\n transb = 'n'\n ldb = (&b[0,1]) - b0 if b.shape[1] > 1 else 1\n else:\n with gil:\n raise ValueError(\"Input 'b' is neither C nor Fortran contiguous.\")\n m = a.shape[0]\n k = a.shape[1]\n if k != b.shape[0]:\n with gil:\n raise ValueError(\"Shape mismatch in input arrays.\")\n n = b.shape[1]\n if m != c.shape[0] or n != c.shape[1]:\n with gil:\n raise ValueError(\"Output array does not have the correct shape.\")\n ldc = (&c[0,1]) - c0 if c.shape[1] > 1 else 1\n dgemm(transa, transb, &m, &n, &k, &alpha, a0, &lda, b0,\n &ldb, &beta, c0, &ldc)\n else:\n with gil:\n raise ValueError(\"Input 'c' is neither C nor Fortran contiguous.\")\n return 0\n\ncpdef double _test_dnrm2(double[:] x) nogil:\n cdef:\n int n = x.shape[0]\n int incx = x.strides[0] // sizeof(x[0])\n return dnrm2(&n, &x[0], &incx)\n\ncpdef double _test_dzasum(double complex[:] zx) nogil:\n cdef:\n int n = zx.shape[0]\n int incx = zx.strides[0] // sizeof(zx[0])\n return dzasum(&n, &zx[0], &incx)\n\ncpdef double _test_dznrm2(double complex[:] x) nogil:\n cdef:\n int n = x.shape[0]\n int incx = x.strides[0] // sizeof(x[0])\n return dznrm2(&n, &x[0], &incx)\n\ncpdef int _test_icamax(float complex[:] cx) nogil:\n cdef:\n int n = cx.shape[0]\n int incx = cx.strides[0] // sizeof(cx[0])\n return icamax(&n, &cx[0], &incx)\n\ncpdef int _test_idamax(double[:] dx) nogil:\n cdef:\n int n = dx.shape[0]\n int incx = dx.strides[0] // sizeof(dx[0])\n return idamax(&n, &dx[0], &incx)\n\ncpdef int _test_isamax(float[:] sx) nogil:\n cdef:\n int n = sx.shape[0]\n int incx = sx.strides[0] // sizeof(sx[0])\n return isamax(&n, &sx[0], &incx)\n\ncpdef int _test_izamax(double complex[:] zx) nogil:\n cdef:\n int n = zx.shape[0]\n int incx = zx.strides[0] // sizeof(zx[0])\n return izamax(&n, &zx[0], &incx)\n\ncpdef float _test_sasum(float[:] sx) nogil:\n cdef:\n int n = sx.shape[0]\n int incx = sx.shape[0] // sizeof(sx[0])\n return sasum(&n, &sx[0], &incx)\n\ncpdef float _test_scasum(float complex[:] cx) nogil:\n cdef:\n int n = cx.shape[0]\n int incx = cx.strides[0] // sizeof(cx[0])\n return scasum(&n, &cx[0], &incx)\n\ncpdef float _test_scnrm2(float complex[:] x) nogil:\n cdef:\n int n = x.shape[0]\n int incx = x.strides[0] // sizeof(x[0])\n return scnrm2(&n, &x[0], &incx)\n\ncpdef float _test_sdot(float[:] sx, float[:] sy) nogil:\n cdef:\n int n = sx.shape[0]\n int incx = sx.strides[0] // sizeof(sx[0])\n int incy = sy.strides[0] // sizeof(sy[0])\n return sdot(&n, &sx[0], &incx, &sy[0], &incy)\n\ncpdef float _test_snrm2(float[:] x) nogil:\n cdef:\n int n = x.shape[0]\n int incx = x.shape[0] // sizeof(x[0])\n return snrm2(&n, &x[0], &incx)\n\ncpdef double complex _test_zdotc(double complex[:] zx, double complex[:] zy) nogil:\n cdef:\n int n = zx.shape[0]\n int incx = zx.strides[0] // sizeof(zx[0])\n int incy = zy.strides[0] // sizeof(zy[0])\n return zdotc(&n, &zx[0], &incx, &zy[0], &incy)\n\ncpdef double complex _test_zdotu(double complex[:] zx, double complex[:] zy) nogil:\n cdef:\n int n = zx.shape[0]\n int incx = zx.strides[0] // sizeof(zx[0])\n int incy = zy.strides[0] // sizeof(zy[0])\n return zdotu(&n, &zx[0], &incx, &zy[0], &incy)\n\"\"\"\n\n\ndef generate_blas_pyx(func_sigs, sub_sigs, all_sigs, header_name):\n funcs = \"\\n\".join(pyx_decl_func(*(s+(header_name,))) for s in func_sigs)\n subs = \"\\n\" + \"\\n\".join(pyx_decl_sub(*(s[::2]+(header_name,)))\n for s in sub_sigs)\n return make_blas_pyx_preamble(all_sigs) + funcs + subs + blas_py_wrappers\n\n\nlapack_py_wrappers = \"\"\"\n\n# Python accessible wrappers for testing:\n\ndef _test_dlamch(cmach):\n # This conversion is necessary to handle Python 3 strings.\n cmach_bytes = bytes(cmach)\n # Now that it is a bytes representation, a non-temporary variable\n # must be passed as a part of the function call.\n cdef char* cmach_char = cmach_bytes\n return dlamch(cmach_char)\n\ndef _test_slamch(cmach):\n # This conversion is necessary to handle Python 3 strings.\n cmach_bytes = bytes(cmach)\n # Now that it is a bytes representation, a non-temporary variable\n # must be passed as a part of the function call.\n cdef char* cmach_char = cmach_bytes\n return slamch(cmach_char)\n\"\"\"\n\n\ndef generate_lapack_pyx(func_sigs, sub_sigs, all_sigs, header_name):\n funcs = \"\\n\".join(pyx_decl_func(*(s+(header_name,))) for s in func_sigs)\n subs = \"\\n\" + \"\\n\".join(pyx_decl_sub(*(s[::2]+(header_name,)))\n for s in sub_sigs)\n preamble = make_lapack_pyx_preamble(all_sigs)\n return preamble + funcs + subs + lapack_py_wrappers\n\n\npxd_template = \"\"\"ctypedef {ret_type} {name}_t({args}) nogil\ncdef {name}_t *{name}_f\n\"\"\"\npxd_template = \"\"\"cdef {ret_type} {name}({args}) nogil\n\"\"\"\n\n\ndef pxd_decl(name, ret_type, args):\n args = args.replace('lambda', 'lambda_').replace('*in,', '*in_,')\n return pxd_template.format(name=name, ret_type=ret_type, args=args)\n\n\nblas_pxd_preamble = \"\"\"# Within scipy, these wrappers can be used via relative or absolute cimport.\n# Examples:\n# from ..linalg cimport cython_blas\n# from scipy.linalg cimport cython_blas\n# cimport scipy.linalg.cython_blas as cython_blas\n# cimport ..linalg.cython_blas as cython_blas\n\n# Within SciPy, if BLAS functions are needed in C/C++/Fortran,\n# these wrappers should not be used.\n# The original libraries should be linked directly.\n\nctypedef float s\nctypedef double d\nctypedef float complex c\nctypedef double complex z\n\n\"\"\"\n\n\ndef generate_blas_pxd(all_sigs):\n body = '\\n'.join(pxd_decl(*sig) for sig in all_sigs)\n return blas_pxd_preamble + body\n\n\nlapack_pxd_preamble = \"\"\"# Within SciPy, these wrappers can be used via relative or absolute cimport.\n# Examples:\n# from ..linalg cimport cython_lapack\n# from scipy.linalg cimport cython_lapack\n# cimport scipy.linalg.cython_lapack as cython_lapack\n# cimport ..linalg.cython_lapack as cython_lapack\n\n# Within SciPy, if LAPACK functions are needed in C/C++/Fortran,\n# these wrappers should not be used.\n# The original libraries should be linked directly.\n\nctypedef float s\nctypedef double d\nctypedef float complex c\nctypedef double complex z\n\n# Function pointer type declarations for\n# gees and gges families of functions.\nctypedef bint cselect1(c*)\nctypedef bint cselect2(c*, c*)\nctypedef bint dselect2(d*, d*)\nctypedef bint dselect3(d*, d*, d*)\nctypedef bint sselect2(s*, s*)\nctypedef bint sselect3(s*, s*, s*)\nctypedef bint zselect1(z*)\nctypedef bint zselect2(z*, z*)\n\n\"\"\"\n\n\ndef generate_lapack_pxd(all_sigs):\n return lapack_pxd_preamble + '\\n'.join(pxd_decl(*sig) for sig in all_sigs)\n\n\nfortran_template = \"\"\" subroutine {name}wrp(\n + ret,\n + {argnames}\n + )\n external {wrapper}\n {ret_type} {wrapper}\n {ret_type} ret\n {argdecls}\n ret = {wrapper}(\n + {argnames}\n + )\n end\n\"\"\"\n\ndims = {'work': '(*)', 'ab': '(ldab,*)', 'a': '(lda,*)', 'dl': '(*)',\n 'd': '(*)', 'du': '(*)', 'ap': '(*)', 'e': '(*)', 'lld': '(*)'}\n\nxy_specialized_dims = {'x': '', 'y': ''}\na_specialized_dims = {'a': '(*)'}\nspecial_cases = defaultdict(dict,\n ladiv = xy_specialized_dims,\n lanhf = a_specialized_dims,\n lansf = a_specialized_dims,\n lapy2 = xy_specialized_dims,\n lapy3 = xy_specialized_dims)\n\n\ndef process_fortran_name(name, funcname):\n if 'inc' in name:\n return name\n special = special_cases[funcname[1:]]\n if 'x' in name or 'y' in name:\n suffix = special.get(name, '(n)')\n else:\n suffix = special.get(name, '')\n return name + suffix\n\n\ndef called_name(name):\n included = ['cdotc', 'cdotu', 'zdotc', 'zdotu', 'cladiv', 'zladiv']\n if name in included:\n return \"w\" + name\n return name\n\n\ndef fort_subroutine_wrapper(name, ret_type, args):\n wrapper = called_name(name)\n types, names = arg_names_and_types(args)\n argnames = ',\\n + '.join(names)\n\n names = [process_fortran_name(n, name) for n in names]\n argdecls = '\\n '.join('{0} {1}'.format(fortran_types[t], n)\n for n, t in zip(names, types))\n return fortran_template.format(name=name, wrapper=wrapper,\n argnames=argnames, argdecls=argdecls,\n ret_type=fortran_types[ret_type])\n\n\ndef generate_fortran(func_sigs):\n return \"\\n\".join(fort_subroutine_wrapper(*sig) for sig in func_sigs)\n\n\ndef make_c_args(args):", "answers": [" types, names = arg_names_and_types(args)"], "length": 2215, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "c4441857-3118-4aeb-9ab8-e17aa132e397", "reasoning": "The function make_c_args is meant to process a string of argument specifications. The first step is to split the string into types and names, just like other helper functions in the script (e.g., pyx_decl_func and fort_subroutine_wrapper). Therefore the next line should call arg_names_and_types to obtain the separate lists.", "reasoning_model_answer": "argtypes, argnames = arg_names_and_types(args)", "assistant_with_reasoning": "\nThe function make_c_args is meant to process a string of argument specifications. The first step is to split the string into types and names, just like other helper functions in the script (e.g., pyx_decl_func and fort_subroutine_wrapper). Therefore the next line should call arg_names_and_types to obtain the separate lists.\n\nargtypes, argnames = arg_names_and_types(args)", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 7.676, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 19464, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "argtypes, argnames = arg_names_and_types(args)", "score": 0.89, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "// leveldb-sharp\n//\n// Copyright (c) 2011 The LevelDB Authors\n// Copyright (c) 2012-2013, Mirco Bauer \n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n// * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n// * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n// * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nusing System;\nusing System.Text;\nusing System.Runtime.InteropServices;\n\nnamespace LevelDB\n{\n ///

    \n /// Native method P/Invoke declarations for LevelDB\n /// \n public static class Native\n {\n public static void CheckError(string error)\n {\n if (String.IsNullOrEmpty(error)) {\n return;\n }\n\n throw new ApplicationException(error);\n }\n\n public static void CheckError(IntPtr error)\n {\n if (error == IntPtr.Zero) {\n return;\n }\n\n CheckError(GetAndReleaseString(error));\n }\n\n public static UIntPtr GetStringLength(string value)\n {\n if (value == null || value.Length == 0) {\n return UIntPtr.Zero;\n }\n return new UIntPtr((uint) Encoding.UTF8.GetByteCount(value));\n }\n\n public static string GetAndReleaseString(IntPtr ptr)\n {\n if (ptr == IntPtr.Zero) {\n return null;\n }\n\n var str = Marshal.PtrToStringAnsi(ptr);\n leveldb_free(ptr);\n return str;\n }\n\n#region DB operations\n #region leveldb_open\n // extern leveldb_t* leveldb_open(const leveldb_options_t* options, const char* name, char** errptr);\n [DllImport(\"leveldb\", CallingConvention = CallingConvention.Cdecl)]\n public static extern IntPtr leveldb_open(IntPtr options, string name, out IntPtr error);\n\n public static IntPtr leveldb_open(IntPtr options, string name, out string error)\n {\n IntPtr errorPtr;\n var db = leveldb_open(options, name, out errorPtr);\n error = GetAndReleaseString(errorPtr);\n return db;\n }\n\n public static IntPtr leveldb_open(IntPtr options, string name)\n {\n string error;\n var db = leveldb_open(options, name, out error);\n CheckError(error);\n return db;\n }\n #endregion\n\n // extern void leveldb_close(leveldb_t* db);\n [DllImport(\"leveldb\", CallingConvention = CallingConvention.Cdecl)]\n public static extern void leveldb_close(IntPtr db);\n\n #region leveldb_put\n // extern void leveldb_put(leveldb_t* db, const leveldb_writeoptions_t* options, const char* key, size_t keylen, const char* val, size_t vallen, char** errptr);\n [DllImport(\"leveldb\", CallingConvention = CallingConvention.Cdecl)]\n public static extern void leveldb_put(IntPtr db,\n IntPtr writeOptions,\n string key,\n UIntPtr keyLength,\n string value,\n UIntPtr valueLength,\n out IntPtr error);\n\n public static void leveldb_put(IntPtr db,\n IntPtr writeOptions,\n string key,\n UIntPtr keyLength,\n string value,\n UIntPtr valueLength,\n out string error)\n {\n IntPtr errorPtr;\n leveldb_put(db, writeOptions, key, keyLength, value, valueLength,\n out errorPtr);\n error = GetAndReleaseString(errorPtr);\n }\n\n public static void leveldb_put(IntPtr db,\n IntPtr writeOptions,\n string key,\n string value)\n {\n string error;\n var keyLength = GetStringLength(key);\n var valueLength = GetStringLength(value);\n Native.leveldb_put(db, writeOptions,\n key, keyLength,\n value, valueLength, out error);\n CheckError(error);\n }\n #endregion\n\n #region leveldb_delete\n // extern void leveldb_delete(leveldb_t* db, const leveldb_writeoptions_t* options, const char* key, size_t keylen, char** errptr);\n [DllImport(\"leveldb\", CallingConvention = CallingConvention.Cdecl)]\n public static extern void leveldb_delete(IntPtr db, IntPtr writeOptions, string key, UIntPtr keylen, out IntPtr error);\n\n public static void leveldb_delete(IntPtr db, IntPtr writeOptions, string key, UIntPtr keylen, out string error)\n {\n IntPtr errorPtr;\n leveldb_delete(db, writeOptions, key, keylen, out errorPtr);\n error = GetAndReleaseString(errorPtr);\n }\n\n public static void leveldb_delete(IntPtr db, IntPtr writeOptions, string key)\n {\n string error;\n var keyLength = GetStringLength(key);\n leveldb_delete(db, writeOptions, key, keyLength, out error);\n CheckError(error);\n }\n #endregion\n\n #region leveldb_write\n // extern void leveldb_write(leveldb_t* db, const leveldb_writeoptions_t* options, leveldb_writebatch_t* batch, char** errptr);\n [DllImport(\"leveldb\", CallingConvention = CallingConvention.Cdecl)]\n public static extern void leveldb_write(IntPtr db, IntPtr writeOptions, IntPtr writeBatch, out IntPtr error);\n\n public static void leveldb_write(IntPtr db, IntPtr writeOptions, IntPtr writeBatch, out string error)\n {\n IntPtr errorPtr;\n leveldb_write(db, writeOptions, writeBatch, out errorPtr);\n error = GetAndReleaseString(errorPtr);\n }\n\n public static void leveldb_write(IntPtr db, IntPtr writeOptions, IntPtr writeBatch)\n {\n string error;\n leveldb_write(db, writeOptions, writeBatch, out error);\n CheckError(error);\n }\n #endregion\n\n #region leveldb_get\n // extern char* leveldb_get(leveldb_t* db, const leveldb_readoptions_t* options, const char* key, size_t keylen, size_t* vallen, char** errptr);\n [DllImport(\"leveldb\", CallingConvention = CallingConvention.Cdecl)]\n public static extern IntPtr leveldb_get(IntPtr db,\n IntPtr readOptions,\n string key,\n UIntPtr keyLength,\n out UIntPtr valueLength,\n out IntPtr error);\n\n public static IntPtr leveldb_get(IntPtr db,\n IntPtr readOptions,\n string key,\n UIntPtr keyLength,\n out UIntPtr valueLength,\n out string error)\n {\n IntPtr errorPtr;\n var valuePtr = leveldb_get(db, readOptions, key, keyLength,\n out valueLength, out errorPtr);\n error = GetAndReleaseString(errorPtr);\n return valuePtr;\n }\n\n public static string leveldb_get(IntPtr db,\n IntPtr readOptions,\n string key)\n {\n UIntPtr valueLength;\n string error;\n var keyLength = GetStringLength(key);\n var valuePtr = leveldb_get(db, readOptions, key, keyLength,\n out valueLength, out error);\n CheckError(error);\n if (valuePtr == IntPtr.Zero || valueLength == UIntPtr.Zero) {\n return null;\n }\n var value = Marshal.PtrToStringAnsi(valuePtr, (int) valueLength);\n leveldb_free(valuePtr);\n return value;\n }\n #endregion\n\n // extern leveldb_iterator_t* leveldb_create_iterator(leveldb_t* db, const leveldb_readoptions_t* options);\n [DllImport(\"leveldb\", CallingConvention = CallingConvention.Cdecl)]\n public static extern IntPtr leveldb_create_iterator(IntPtr db, IntPtr readOptions);\n\n // extern const leveldb_snapshot_t* leveldb_create_snapshot(leveldb_t* db);\n [DllImport(\"leveldb\", CallingConvention = CallingConvention.Cdecl)]\n public static extern IntPtr leveldb_create_snapshot(IntPtr db);\n\n // extern void leveldb_release_snapshot(leveldb_t* db, const leveldb_snapshot_t* snapshot);\n [DllImport(\"leveldb\", CallingConvention = CallingConvention.Cdecl)]\n public static extern void leveldb_release_snapshot(IntPtr db, IntPtr snapshot);\n\n /// \n /// Returns NULL if property name is unknown.\n /// Else returns a pointer to a malloc()-ed null-terminated value.\n /// \n // extern char* leveldb_property_value(leveldb_t* db, const char* propname);\n [DllImport(\"leveldb\", EntryPoint=\"leveldb_property_value\", CallingConvention = CallingConvention.Cdecl)]\n public static extern IntPtr leveldb_property_value_native(IntPtr db, string propname);\n public static string leveldb_property_value(IntPtr db, string propname)\n {\n var valuePtr = leveldb_property_value_native(db, propname);\n if (valuePtr == IntPtr.Zero) {\n return null;\n }\n var value = Marshal.PtrToStringAnsi(valuePtr);\n leveldb_free(valuePtr);\n return value;\n }\n\n // extern void leveldb_approximate_sizes(\n // leveldb_t* db, int num_ranges,\n // const char* const* range_start_key,\n // const size_t* range_start_key_len,\n // const char* const* range_limit_key,\n // const size_t* range_limit_key_len,\n // uint64_t* sizes);\n\n /// \n /// Compact the underlying storage for the key range [startKey,limitKey].\n /// In particular, deleted and overwritten versions are discarded,\n /// and the data is rearranged to reduce the cost of operations\n /// needed to access the data. This operation should typically only\n /// be invoked by users who understand the underlying implementation.\n ///\n /// startKey==null is treated as a key before all keys in the database.\n /// limitKey==null is treated as a key after all keys in the database.\n /// Therefore the following call will compact the entire database:\n /// leveldb_compact_range(db, null, null);\n /// \n // extern void leveldb_compact_range(leveldb_t* db,\n // const char* start_key, size_t start_key_len,\n // const char* limit_key, size_t limit_key_len);\n [DllImport(\"leveldb\", CallingConvention = CallingConvention.Cdecl)]\n public static extern void leveldb_compact_range(IntPtr db,\n string startKey,\n UIntPtr startKeyLen,\n string limitKey,\n UIntPtr limitKeyLen);\n public static void leveldb_compact_range(IntPtr db,\n string startKey,\n string limitKey)\n {\n leveldb_compact_range(db,\n startKey, GetStringLength(startKey),\n limitKey, GetStringLength(limitKey));\n }\n#endregion\n\n#region Management operations\n #region leveldb_destroy_db\n // extern void leveldb_destroy_db(const leveldb_options_t* options, const char* name, char** errptr);\n [DllImport(\"leveldb\", CallingConvention = CallingConvention.Cdecl)]\n public static extern void leveldb_destroy_db(IntPtr options, string path, out IntPtr error);\n\n public static void leveldb_destroy_db(IntPtr options, string path, out string error)\n {\n IntPtr errorPtr;\n leveldb_destroy_db(options, path, out errorPtr);\n error = GetAndReleaseString(errorPtr);\n }\n\n public static void leveldb_destroy_db(IntPtr options, string path)\n {\n string error;\n leveldb_destroy_db(options, path, out error);\n CheckError(error);\n }\n #endregion\n\n #region leveldb_repair_db\n // extern void leveldb_repair_db(const leveldb_options_t* options, const char* name, char** errptr);\n [DllImport(\"leveldb\", CallingConvention = CallingConvention.Cdecl)]\n public static extern void leveldb_repair_db(IntPtr options, string path, out IntPtr error);\n\n public static void leveldb_repair_db(IntPtr options, string path, out string error)\n {\n IntPtr errorPtr;\n leveldb_repair_db(options, path, out errorPtr);\n error = GetAndReleaseString(errorPtr);\n }\n\n public static void leveldb_repair_db(IntPtr options, string path)\n {\n string error;\n leveldb_repair_db(options, path, out error);\n CheckError(error);\n }\n #endregion\n#endregion\n\n#region Write batch\n // extern leveldb_writebatch_t* leveldb_writebatch_create();\n [DllImport(\"leveldb\", CallingConvention = CallingConvention.Cdecl)]\n public static extern IntPtr leveldb_writebatch_create();\n\n // extern void leveldb_writebatch_destroy(leveldb_writebatch_t*);\n [DllImport(\"leveldb\", CallingConvention = CallingConvention.Cdecl)]\n public static extern void leveldb_writebatch_destroy(IntPtr writeBatch);\n\n // extern void leveldb_writebatch_clear(leveldb_writebatch_t*);\n [DllImport(\"leveldb\", CallingConvention = CallingConvention.Cdecl)]\n public static extern void leveldb_writebatch_clear(IntPtr writeBatch);\n\n // extern void leveldb_writebatch_put(leveldb_writebatch_t*, const char* key, size_t klen, const char* val, size_t vlen);\n [DllImport(\"leveldb\", CallingConvention = CallingConvention.Cdecl)]\n public static extern void leveldb_writebatch_put(IntPtr writeBatch,\n string key,\n UIntPtr keyLength,\n string value,\n UIntPtr valueLength);\n public static void leveldb_writebatch_put(IntPtr writeBatch,\n string key,\n string value)\n {\n var keyLength = GetStringLength(key);\n var valueLength = GetStringLength(value);\n Native.leveldb_writebatch_put(writeBatch,\n key, keyLength,\n value, valueLength);\n }\n\n // extern void leveldb_writebatch_delete(leveldb_writebatch_t*, const char* key, size_t klen);\n [DllImport(\"leveldb\", CallingConvention = CallingConvention.Cdecl)]\n public static extern void leveldb_writebatch_delete(IntPtr writeBatch, string key, UIntPtr keylen);\n public static void leveldb_writebatch_delete(IntPtr writeBatch, string key)\n {\n var keyLength = GetStringLength(key);\n leveldb_writebatch_delete(writeBatch, key, keyLength);\n }\n\n // TODO:\n // extern void leveldb_writebatch_iterate(leveldb_writebatch_t*, void* state, void (*put)(void*, const char* k, size_t klen, const char* v, size_t vlen), void (*deleted)(void*, const char* k, size_t klen));\n\n#endregion\n\n#region Options\n // extern leveldb_options_t* leveldb_options_create();\n [DllImport(\"leveldb\", CallingConvention = CallingConvention.Cdecl)]\n public static extern IntPtr leveldb_options_create();\n\n // extern void leveldb_options_destroy(leveldb_options_t*);\n [DllImport(\"leveldb\", CallingConvention = CallingConvention.Cdecl)]\n public static extern void leveldb_options_destroy(IntPtr options);\n\n // extern void leveldb_options_set_comparator(leveldb_options_t*, leveldb_comparator_t*);\n [DllImport(\"leveldb\", CallingConvention = CallingConvention.Cdecl)]\n public static extern void leveldb_options_set_comparator(IntPtr options, IntPtr comparator);\n\n /// \n /// If true, the database will be created if it is missing.\n /// Default: false\n /// \n // extern void leveldb_options_set_create_if_missing(leveldb_options_t*, unsigned char);\n [DllImport(\"leveldb\", CallingConvention = CallingConvention.Cdecl)]\n public static extern void leveldb_options_set_create_if_missing(IntPtr options, bool value);\n\n /// \n /// If true, an error is raised if the database already exists.\n /// Default: false\n /// \n // extern void leveldb_options_set_error_if_exists(leveldb_options_t*, unsigned char);\n [DllImport(\"leveldb\", CallingConvention = CallingConvention.Cdecl)]\n public static extern void leveldb_options_set_error_if_exists(IntPtr options, bool value);\n\n /// \n /// If true, the implementation will do aggressive checking of the\n /// data it is processing and will stop early if it detects any\n /// errors. This may have unforeseen ramifications: for example, a\n /// corruption of one DB entry may cause a large number of entries to\n /// become unreadable or for the entire DB to become unopenable.\n /// Default: false\n /// \n // extern void leveldb_options_set_paranoid_checks(leveldb_options_t*, unsigned char);\n [DllImport(\"leveldb\", CallingConvention = CallingConvention.Cdecl)]\n public static extern void leveldb_options_set_paranoid_checks(IntPtr options, bool value);\n\n /// \n /// Number of open files that can be used by the DB. You may need to\n /// increase this if your database has a large working set (budget\n /// one open file per 2MB of working set).\n /// Default: 1000\n /// \n // extern void leveldb_options_set_max_open_files(leveldb_options_t*, int);\n [DllImport(\"leveldb\", CallingConvention = CallingConvention.Cdecl)]\n public static extern void leveldb_options_set_max_open_files(IntPtr options, int value);\n\n /// \n /// Each block is individually compressed before being written to\n /// persistent storage. Compression is on by default since the default\n /// compression method is very fast, and is automatically disabled for\n /// uncompressible data. In rare cases, applications may want to\n /// disable compression entirely, but should only do so if benchmarks\n /// show a performance improvement.\n /// Default: 1 (SnappyCompression)\n /// \n /// \n // extern void leveldb_options_set_compression(leveldb_options_t*, int);\n [DllImport(\"leveldb\", CallingConvention = CallingConvention.Cdecl)]\n public static extern void leveldb_options_set_compression(IntPtr options, int value);\n\n /// \n /// Control over blocks (user data is stored in a set of blocks, and\n /// a block is the unit of reading from disk).\n ///\n /// If non-NULL, use the specified cache for blocks.\n /// If NULL, leveldb will automatically create and use an 8MB internal cache.\n /// Default: NULL\n /// \n // extern void leveldb_options_set_cache(leveldb_options_t*, leveldb_cache_t*);\n [DllImport(\"leveldb\", CallingConvention = CallingConvention.Cdecl)]\n public static extern void leveldb_options_set_cache(IntPtr options, IntPtr cache);\n public static void leveldb_options_set_cache_size(IntPtr options, int capacity)\n {\n var cache = leveldb_cache_create_lru((UIntPtr) capacity);\n leveldb_options_set_cache(options, cache);\n }\n\n /// \n /// Approximate size of user data packed per block. Note that the\n /// block size specified here corresponds to uncompressed data. The\n /// actual size of the unit read from disk may be smaller if\n /// compression is enabled. This parameter can be changed dynamically.\n ///\n /// Default: 4K\n /// \n // extern void leveldb_options_set_block_size(leveldb_options_t*, size_t);\n [DllImport(\"leveldb\", CallingConvention = CallingConvention.Cdecl)]\n public static extern void leveldb_options_set_block_size(IntPtr options, UIntPtr size);\n public static void leveldb_options_set_block_size(IntPtr options, int size)\n {\n leveldb_options_set_block_size(options, (UIntPtr) size);\n }\n\n /// \n /// Amount of data to build up in memory (backed by an unsorted log\n /// on disk) before converting to a sorted on-disk file.\n ///\n /// Larger values increase performance, especially during bulk loads.\n /// Up to two write buffers may be held in memory at the same time,\n /// so you may wish to adjust this parameter to control memory usage.\n /// Also, a larger write buffer will result in a longer recovery time\n /// the next time the database is opened.\n ///\n /// Default: 4MB\n /// \n // extern void leveldb_options_set_write_buffer_size(leveldb_options_t*, size_t);\n [DllImport(\"leveldb\", CallingConvention = CallingConvention.Cdecl)]\n public static extern void leveldb_options_set_write_buffer_size(IntPtr options, UIntPtr size);\n public static void leveldb_options_set_write_buffer_size(IntPtr options, int size)\n {\n leveldb_options_set_write_buffer_size(options, (UIntPtr) size);\n }\n\n /// \n /// Number of keys between restart points for delta encoding of keys.\n /// This parameter can be changed dynamically. Most clients should\n /// leave this parameter alone.\n /// Default: 16\n /// \n // extern void leveldb_options_set_block_restart_interval(leveldb_options_t*, int);\n [DllImport(\"leveldb\", CallingConvention = CallingConvention.Cdecl)]\n public static extern void leveldb_options_set_block_restart_interval(IntPtr options, int interval);\n#endregion\n\n#region Read Options\n // extern leveldb_readoptions_t* leveldb_readoptions_create();\n [DllImport(\"leveldb\", CallingConvention = CallingConvention.Cdecl)]\n public static extern IntPtr leveldb_readoptions_create();\n\n // extern void leveldb_readoptions_destroy(leveldb_readoptions_t*);\n [DllImport(\"leveldb\", CallingConvention = CallingConvention.Cdecl)]\n public static extern void leveldb_readoptions_destroy(IntPtr readOptions);\n\n // extern void leveldb_readoptions_set_verify_checksums(leveldb_readoptions_t*, unsigned char);\n [DllImport(\"leveldb\", CallingConvention = CallingConvention.Cdecl)]\n public static extern void leveldb_readoptions_set_verify_checksums(IntPtr readOptions, bool value);\n\n // extern void leveldb_readoptions_set_fill_cache(leveldb_readoptions_t*, unsigned char);\n [DllImport(\"leveldb\", CallingConvention = CallingConvention.Cdecl)]\n public static extern void leveldb_readoptions_set_fill_cache(IntPtr readOptions, bool value);\n\n // extern void leveldb_readoptions_set_snapshot(leveldb_readoptions_t*, const leveldb_snapshot_t*);\n [DllImport(\"leveldb\", CallingConvention = CallingConvention.Cdecl)]\n public static extern void leveldb_readoptions_set_snapshot(IntPtr readOptions, IntPtr snapshot);\n#endregion\n\n#region Write Options\n // extern leveldb_writeoptions_t* leveldb_writeoptions_create();", "answers": [" [DllImport(\"leveldb\", CallingConvention = CallingConvention.Cdecl)]"], "length": 2260, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "3ea28371-d7ad-45ce-93c5-749b234454b8", "reasoning": "The code is defining P/Invoke signatures for LevelDB native functions. Following the pattern used for read options, after the comment for the write options create function, the next line should be the DllImport declaration that maps to leveldb_writeoptions_create, returning an IntPtr.", "reasoning_model_answer": "[DllImport(\"leveldb\", CallingConvention = CallingConvention.Cdecl)]\npublic static extern IntPtr leveldb_writeoptions_create();", "assistant_with_reasoning": "\nThe code is defining P/Invoke signatures for LevelDB native functions. Following the pattern used for read options, after the comment for the write options create function, the next line should be the DllImport declaration that maps to leveldb_writeoptions_create, returning an IntPtr.\n\n[DllImport(\"leveldb\", CallingConvention = CallingConvention.Cdecl)]\npublic static extern IntPtr leveldb_writeoptions_create();", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.359, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 25972, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "[DllImport(\"leveldb\", CallingConvention = CallingConvention.Cdecl)]\npublic static extern IntPtr leveldb_writeoptions_create();", "score": 0.94, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n// Generated by the protocol buffer compiler. DO NOT EDIT!\n// source: google/cloud/vision/v1p4beta1/image_annotator.proto\n\npackage com.google.cloud.vision.v1p4beta1;\n\n/**\n *\n *\n *
    \n * Multiple async file annotation requests are batched into a single service\n * call.\n * 
    \n *\n * Protobuf type {@code google.cloud.vision.v1p4beta1.AsyncBatchAnnotateFilesRequest}\n */\npublic final class AsyncBatchAnnotateFilesRequest extends com.google.protobuf.GeneratedMessageV3\n implements\n // @@protoc_insertion_point(message_implements:google.cloud.vision.v1p4beta1.AsyncBatchAnnotateFilesRequest)\n AsyncBatchAnnotateFilesRequestOrBuilder {\n private static final long serialVersionUID = 0L;\n // Use AsyncBatchAnnotateFilesRequest.newBuilder() to construct.\n private AsyncBatchAnnotateFilesRequest(\n com.google.protobuf.GeneratedMessageV3.Builder builder) {\n super(builder);\n }\n\n private AsyncBatchAnnotateFilesRequest() {\n requests_ = java.util.Collections.emptyList();\n }\n\n @java.lang.Override\n @SuppressWarnings({\"unused\"})\n protected java.lang.Object newInstance(UnusedPrivateParameter unused) {\n return new AsyncBatchAnnotateFilesRequest();\n }\n\n @java.lang.Override\n public final com.google.protobuf.UnknownFieldSet getUnknownFields() {\n return this.unknownFields;\n }\n\n private AsyncBatchAnnotateFilesRequest(\n com.google.protobuf.CodedInputStream input,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws com.google.protobuf.InvalidProtocolBufferException {\n this();\n if (extensionRegistry == null) {\n throw new java.lang.NullPointerException();\n }\n int mutable_bitField0_ = 0;\n com.google.protobuf.UnknownFieldSet.Builder unknownFields =\n com.google.protobuf.UnknownFieldSet.newBuilder();\n try {\n boolean done = false;\n while (!done) {\n int tag = input.readTag();\n switch (tag) {\n case 0:\n done = true;\n break;\n case 10:\n {\n if (!((mutable_bitField0_ & 0x00000001) != 0)) {\n requests_ =\n new java.util.ArrayList<\n com.google.cloud.vision.v1p4beta1.AsyncAnnotateFileRequest>();\n mutable_bitField0_ |= 0x00000001;\n }\n requests_.add(\n input.readMessage(\n com.google.cloud.vision.v1p4beta1.AsyncAnnotateFileRequest.parser(),\n extensionRegistry));\n break;\n }\n default:\n {\n if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) {\n done = true;\n }\n break;\n }\n }\n }\n } catch (com.google.protobuf.InvalidProtocolBufferException e) {\n throw e.setUnfinishedMessage(this);\n } catch (java.io.IOException e) {\n throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this);\n } finally {\n if (((mutable_bitField0_ & 0x00000001) != 0)) {\n requests_ = java.util.Collections.unmodifiableList(requests_);\n }\n this.unknownFields = unknownFields.build();\n makeExtensionsImmutable();\n }\n }\n\n public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {\n return com.google.cloud.vision.v1p4beta1.ImageAnnotatorProto\n .internal_static_google_cloud_vision_v1p4beta1_AsyncBatchAnnotateFilesRequest_descriptor;\n }\n\n @java.lang.Override\n protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable\n internalGetFieldAccessorTable() {\n return com.google.cloud.vision.v1p4beta1.ImageAnnotatorProto\n .internal_static_google_cloud_vision_v1p4beta1_AsyncBatchAnnotateFilesRequest_fieldAccessorTable\n .ensureFieldAccessorsInitialized(\n com.google.cloud.vision.v1p4beta1.AsyncBatchAnnotateFilesRequest.class,\n com.google.cloud.vision.v1p4beta1.AsyncBatchAnnotateFilesRequest.Builder.class);\n }\n\n public static final int REQUESTS_FIELD_NUMBER = 1;\n private java.util.List requests_;\n /**\n *\n *\n *
    \n   * Required. Individual async file annotation requests for this batch.\n   * 
    \n *\n * \n * repeated .google.cloud.vision.v1p4beta1.AsyncAnnotateFileRequest requests = 1 [(.google.api.field_behavior) = REQUIRED];\n * \n */\n @java.lang.Override\n public java.util.List\n getRequestsList() {\n return requests_;\n }\n /**\n *\n *\n *
    \n   * Required. Individual async file annotation requests for this batch.\n   * 
    \n *\n * \n * repeated .google.cloud.vision.v1p4beta1.AsyncAnnotateFileRequest requests = 1 [(.google.api.field_behavior) = REQUIRED];\n * \n */\n @java.lang.Override\n public java.util.List<\n ? extends com.google.cloud.vision.v1p4beta1.AsyncAnnotateFileRequestOrBuilder>\n getRequestsOrBuilderList() {\n return requests_;\n }\n /**\n *\n *\n *
    \n   * Required. Individual async file annotation requests for this batch.\n   * 
    \n *\n * \n * repeated .google.cloud.vision.v1p4beta1.AsyncAnnotateFileRequest requests = 1 [(.google.api.field_behavior) = REQUIRED];\n * \n */\n @java.lang.Override\n public int getRequestsCount() {\n return requests_.size();\n }\n /**\n *\n *\n *
    \n   * Required. Individual async file annotation requests for this batch.\n   * 
    \n *\n * \n * repeated .google.cloud.vision.v1p4beta1.AsyncAnnotateFileRequest requests = 1 [(.google.api.field_behavior) = REQUIRED];\n * \n */\n @java.lang.Override\n public com.google.cloud.vision.v1p4beta1.AsyncAnnotateFileRequest getRequests(int index) {\n return requests_.get(index);\n }\n /**\n *\n *\n *
    \n   * Required. Individual async file annotation requests for this batch.\n   * 
    \n *\n * \n * repeated .google.cloud.vision.v1p4beta1.AsyncAnnotateFileRequest requests = 1 [(.google.api.field_behavior) = REQUIRED];\n * \n */\n @java.lang.Override\n public com.google.cloud.vision.v1p4beta1.AsyncAnnotateFileRequestOrBuilder getRequestsOrBuilder(\n int index) {\n return requests_.get(index);\n }\n\n private byte memoizedIsInitialized = -1;\n\n @java.lang.Override\n public final boolean isInitialized() {\n byte isInitialized = memoizedIsInitialized;\n if (isInitialized == 1) return true;\n if (isInitialized == 0) return false;\n\n memoizedIsInitialized = 1;\n return true;\n }\n\n @java.lang.Override\n public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {\n for (int i = 0; i < requests_.size(); i++) {\n output.writeMessage(1, requests_.get(i));\n }\n unknownFields.writeTo(output);\n }\n\n @java.lang.Override\n public int getSerializedSize() {\n int size = memoizedSize;\n if (size != -1) return size;\n\n size = 0;\n for (int i = 0; i < requests_.size(); i++) {\n size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, requests_.get(i));\n }\n size += unknownFields.getSerializedSize();\n memoizedSize = size;\n return size;\n }\n\n @java.lang.Override\n public boolean equals(final java.lang.Object obj) {\n if (obj == this) {\n return true;\n }\n if (!(obj instanceof com.google.cloud.vision.v1p4beta1.AsyncBatchAnnotateFilesRequest)) {\n return super.equals(obj);\n }\n com.google.cloud.vision.v1p4beta1.AsyncBatchAnnotateFilesRequest other =\n (com.google.cloud.vision.v1p4beta1.AsyncBatchAnnotateFilesRequest) obj;\n\n if (!getRequestsList().equals(other.getRequestsList())) return false;\n if (!unknownFields.equals(other.unknownFields)) return false;\n return true;\n }\n\n @java.lang.Override\n public int hashCode() {\n if (memoizedHashCode != 0) {\n return memoizedHashCode;\n }\n int hash = 41;\n hash = (19 * hash) + getDescriptor().hashCode();\n if (getRequestsCount() > 0) {\n hash = (37 * hash) + REQUESTS_FIELD_NUMBER;\n hash = (53 * hash) + getRequestsList().hashCode();\n }\n hash = (29 * hash) + unknownFields.hashCode();\n memoizedHashCode = hash;\n return hash;\n }\n\n public static com.google.cloud.vision.v1p4beta1.AsyncBatchAnnotateFilesRequest parseFrom(\n java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {\n return PARSER.parseFrom(data);\n }\n\n public static com.google.cloud.vision.v1p4beta1.AsyncBatchAnnotateFilesRequest parseFrom(\n java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws com.google.protobuf.InvalidProtocolBufferException {\n return PARSER.parseFrom(data, extensionRegistry);\n }\n\n public static com.google.cloud.vision.v1p4beta1.AsyncBatchAnnotateFilesRequest parseFrom(\n com.google.protobuf.ByteString data)\n throws com.google.protobuf.InvalidProtocolBufferException {\n return PARSER.parseFrom(data);\n }\n\n public static com.google.cloud.vision.v1p4beta1.AsyncBatchAnnotateFilesRequest parseFrom(\n com.google.protobuf.ByteString data,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws com.google.protobuf.InvalidProtocolBufferException {\n return PARSER.parseFrom(data, extensionRegistry);\n }\n\n public static com.google.cloud.vision.v1p4beta1.AsyncBatchAnnotateFilesRequest parseFrom(\n byte[] data) throws com.google.protobuf.InvalidProtocolBufferException {\n return PARSER.parseFrom(data);\n }\n\n public static com.google.cloud.vision.v1p4beta1.AsyncBatchAnnotateFilesRequest parseFrom(\n byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws com.google.protobuf.InvalidProtocolBufferException {\n return PARSER.parseFrom(data, extensionRegistry);\n }\n\n public static com.google.cloud.vision.v1p4beta1.AsyncBatchAnnotateFilesRequest parseFrom(\n java.io.InputStream input) throws java.io.IOException {\n return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);\n }\n\n public static com.google.cloud.vision.v1p4beta1.AsyncBatchAnnotateFilesRequest parseFrom(\n java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws java.io.IOException {\n return com.google.protobuf.GeneratedMessageV3.parseWithIOException(\n PARSER, input, extensionRegistry);\n }\n\n public static com.google.cloud.vision.v1p4beta1.AsyncBatchAnnotateFilesRequest parseDelimitedFrom(\n java.io.InputStream input) throws java.io.IOException {\n return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);\n }\n\n public static com.google.cloud.vision.v1p4beta1.AsyncBatchAnnotateFilesRequest parseDelimitedFrom(\n java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws java.io.IOException {\n return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(\n PARSER, input, extensionRegistry);\n }\n\n public static com.google.cloud.vision.v1p4beta1.AsyncBatchAnnotateFilesRequest parseFrom(\n com.google.protobuf.CodedInputStream input) throws java.io.IOException {\n return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);\n }\n\n public static com.google.cloud.vision.v1p4beta1.AsyncBatchAnnotateFilesRequest parseFrom(\n com.google.protobuf.CodedInputStream input,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws java.io.IOException {\n return com.google.protobuf.GeneratedMessageV3.parseWithIOException(\n PARSER, input, extensionRegistry);\n }\n\n @java.lang.Override\n public Builder newBuilderForType() {\n return newBuilder();\n }\n\n public static Builder newBuilder() {\n return DEFAULT_INSTANCE.toBuilder();\n }\n\n public static Builder newBuilder(\n com.google.cloud.vision.v1p4beta1.AsyncBatchAnnotateFilesRequest prototype) {\n return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);\n }\n\n @java.lang.Override\n public Builder toBuilder() {\n return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);\n }\n\n @java.lang.Override\n protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {\n Builder builder = new Builder(parent);\n return builder;\n }\n /**\n *\n *\n *
    \n   * Multiple async file annotation requests are batched into a single service\n   * call.\n   * 
    \n *\n * Protobuf type {@code google.cloud.vision.v1p4beta1.AsyncBatchAnnotateFilesRequest}\n */\n public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder\n implements\n // @@protoc_insertion_point(builder_implements:google.cloud.vision.v1p4beta1.AsyncBatchAnnotateFilesRequest)\n com.google.cloud.vision.v1p4beta1.AsyncBatchAnnotateFilesRequestOrBuilder {\n public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {\n return com.google.cloud.vision.v1p4beta1.ImageAnnotatorProto\n .internal_static_google_cloud_vision_v1p4beta1_AsyncBatchAnnotateFilesRequest_descriptor;\n }\n\n @java.lang.Override\n protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable\n internalGetFieldAccessorTable() {\n return com.google.cloud.vision.v1p4beta1.ImageAnnotatorProto\n .internal_static_google_cloud_vision_v1p4beta1_AsyncBatchAnnotateFilesRequest_fieldAccessorTable\n .ensureFieldAccessorsInitialized(\n com.google.cloud.vision.v1p4beta1.AsyncBatchAnnotateFilesRequest.class,\n com.google.cloud.vision.v1p4beta1.AsyncBatchAnnotateFilesRequest.Builder.class);\n }\n\n // Construct using com.google.cloud.vision.v1p4beta1.AsyncBatchAnnotateFilesRequest.newBuilder()\n private Builder() {\n maybeForceBuilderInitialization();\n }\n\n private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {\n super(parent);\n maybeForceBuilderInitialization();\n }\n\n private void maybeForceBuilderInitialization() {\n if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {\n getRequestsFieldBuilder();\n }\n }\n\n @java.lang.Override\n public Builder clear() {\n super.clear();\n if (requestsBuilder_ == null) {\n requests_ = java.util.Collections.emptyList();\n bitField0_ = (bitField0_ & ~0x00000001);\n } else {\n requestsBuilder_.clear();\n }\n return this;\n }\n\n @java.lang.Override\n public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {\n return com.google.cloud.vision.v1p4beta1.ImageAnnotatorProto\n .internal_static_google_cloud_vision_v1p4beta1_AsyncBatchAnnotateFilesRequest_descriptor;\n }\n\n @java.lang.Override\n public com.google.cloud.vision.v1p4beta1.AsyncBatchAnnotateFilesRequest\n getDefaultInstanceForType() {\n return com.google.cloud.vision.v1p4beta1.AsyncBatchAnnotateFilesRequest.getDefaultInstance();\n }\n\n @java.lang.Override\n public com.google.cloud.vision.v1p4beta1.AsyncBatchAnnotateFilesRequest build() {\n com.google.cloud.vision.v1p4beta1.AsyncBatchAnnotateFilesRequest result = buildPartial();\n if (!result.isInitialized()) {\n throw newUninitializedMessageException(result);\n }\n return result;\n }\n\n @java.lang.Override\n public com.google.cloud.vision.v1p4beta1.AsyncBatchAnnotateFilesRequest buildPartial() {\n com.google.cloud.vision.v1p4beta1.AsyncBatchAnnotateFilesRequest result =\n new com.google.cloud.vision.v1p4beta1.AsyncBatchAnnotateFilesRequest(this);\n int from_bitField0_ = bitField0_;\n if (requestsBuilder_ == null) {\n if (((bitField0_ & 0x00000001) != 0)) {\n requests_ = java.util.Collections.unmodifiableList(requests_);\n bitField0_ = (bitField0_ & ~0x00000001);\n }\n result.requests_ = requests_;\n } else {\n result.requests_ = requestsBuilder_.build();\n }\n onBuilt();\n return result;\n }\n\n @java.lang.Override\n public Builder clone() {\n return super.clone();\n }\n\n @java.lang.Override\n public Builder setField(\n com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {\n return super.setField(field, value);\n }\n\n @java.lang.Override\n public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {\n return super.clearField(field);\n }\n\n @java.lang.Override\n public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {\n return super.clearOneof(oneof);\n }\n\n @java.lang.Override\n public Builder setRepeatedField(\n com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {\n return super.setRepeatedField(field, index, value);\n }\n\n @java.lang.Override\n public Builder addRepeatedField(\n com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {\n return super.addRepeatedField(field, value);\n }\n\n @java.lang.Override\n public Builder mergeFrom(com.google.protobuf.Message other) {\n if (other instanceof com.google.cloud.vision.v1p4beta1.AsyncBatchAnnotateFilesRequest) {\n return mergeFrom((com.google.cloud.vision.v1p4beta1.AsyncBatchAnnotateFilesRequest) other);\n } else {\n super.mergeFrom(other);\n return this;\n }\n }\n\n public Builder mergeFrom(\n com.google.cloud.vision.v1p4beta1.AsyncBatchAnnotateFilesRequest other) {\n if (other\n == com.google.cloud.vision.v1p4beta1.AsyncBatchAnnotateFilesRequest.getDefaultInstance())\n return this;\n if (requestsBuilder_ == null) {\n if (!other.requests_.isEmpty()) {\n if (requests_.isEmpty()) {\n requests_ = other.requests_;\n bitField0_ = (bitField0_ & ~0x00000001);\n } else {\n ensureRequestsIsMutable();\n requests_.addAll(other.requests_);\n }\n onChanged();\n }\n } else {\n if (!other.requests_.isEmpty()) {\n if (requestsBuilder_.isEmpty()) {\n requestsBuilder_.dispose();\n requestsBuilder_ = null;\n requests_ = other.requests_;\n bitField0_ = (bitField0_ & ~0x00000001);\n requestsBuilder_ =\n com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders\n ? getRequestsFieldBuilder()\n : null;\n } else {\n requestsBuilder_.addAllMessages(other.requests_);\n }\n }\n }\n this.mergeUnknownFields(other.unknownFields);\n onChanged();\n return this;\n }\n\n @java.lang.Override\n public final boolean isInitialized() {\n return true;\n }\n\n @java.lang.Override\n public Builder mergeFrom(\n com.google.protobuf.CodedInputStream input,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws java.io.IOException {\n com.google.cloud.vision.v1p4beta1.AsyncBatchAnnotateFilesRequest parsedMessage = null;\n try {\n parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);\n } catch (com.google.protobuf.InvalidProtocolBufferException e) {\n parsedMessage =\n (com.google.cloud.vision.v1p4beta1.AsyncBatchAnnotateFilesRequest)\n e.getUnfinishedMessage();\n throw e.unwrapIOException();\n } finally {\n if (parsedMessage != null) {\n mergeFrom(parsedMessage);\n }\n }\n return this;\n }\n\n private int bitField0_;\n\n private java.util.List requests_ =\n java.util.Collections.emptyList();\n\n private void ensureRequestsIsMutable() {\n if (!((bitField0_ & 0x00000001) != 0)) {\n requests_ =\n new java.util.ArrayList(\n requests_);\n bitField0_ |= 0x00000001;\n }\n }\n\n private com.google.protobuf.RepeatedFieldBuilderV3<\n com.google.cloud.vision.v1p4beta1.AsyncAnnotateFileRequest,\n com.google.cloud.vision.v1p4beta1.AsyncAnnotateFileRequest.Builder,\n com.google.cloud.vision.v1p4beta1.AsyncAnnotateFileRequestOrBuilder>\n requestsBuilder_;\n\n /**\n *\n *\n *
    \n     * Required. Individual async file annotation requests for this batch.\n     * 
    \n *\n * \n * repeated .google.cloud.vision.v1p4beta1.AsyncAnnotateFileRequest requests = 1 [(.google.api.field_behavior) = REQUIRED];\n * \n */\n public java.util.List\n getRequestsList() {\n if (requestsBuilder_ == null) {\n return java.util.Collections.unmodifiableList(requests_);\n } else {\n return requestsBuilder_.getMessageList();\n }\n }\n /**\n *\n *\n *
    \n     * Required. Individual async file annotation requests for this batch.\n     * 
    \n *\n * \n * repeated .google.cloud.vision.v1p4beta1.AsyncAnnotateFileRequest requests = 1 [(.google.api.field_behavior) = REQUIRED];\n * \n */\n public int getRequestsCount() {\n if (requestsBuilder_ == null) {\n return requests_.size();\n } else {\n return requestsBuilder_.getCount();\n }\n }\n /**\n *\n *\n *
    \n     * Required. Individual async file annotation requests for this batch.\n     * 
    \n *\n * \n * repeated .google.cloud.vision.v1p4beta1.AsyncAnnotateFileRequest requests = 1 [(.google.api.field_behavior) = REQUIRED];\n * \n */\n public com.google.cloud.vision.v1p4beta1.AsyncAnnotateFileRequest getRequests(int index) {\n if (requestsBuilder_ == null) {\n return requests_.get(index);\n } else {\n return requestsBuilder_.getMessage(index);\n }\n }\n /**\n *\n *\n *
    \n     * Required. Individual async file annotation requests for this batch.\n     * 
    \n *\n * \n * repeated .google.cloud.vision.v1p4beta1.AsyncAnnotateFileRequest requests = 1 [(.google.api.field_behavior) = REQUIRED];\n * \n */\n public Builder setRequests(\n int index, com.google.cloud.vision.v1p4beta1.AsyncAnnotateFileRequest value) {\n if (requestsBuilder_ == null) {\n if (value == null) {\n throw new NullPointerException();\n }\n ensureRequestsIsMutable();\n requests_.set(index, value);\n onChanged();\n } else {\n requestsBuilder_.setMessage(index, value);\n }\n return this;\n }\n /**\n *\n *\n *
    \n     * Required. Individual async file annotation requests for this batch.\n     * 
    \n *\n * \n * repeated .google.cloud.vision.v1p4beta1.AsyncAnnotateFileRequest requests = 1 [(.google.api.field_behavior) = REQUIRED];\n * \n */\n public Builder setRequests(\n int index,\n com.google.cloud.vision.v1p4beta1.AsyncAnnotateFileRequest.Builder builderForValue) {\n if (requestsBuilder_ == null) {\n ensureRequestsIsMutable();\n requests_.set(index, builderForValue.build());\n onChanged();\n } else {\n requestsBuilder_.setMessage(index, builderForValue.build());\n }\n return this;\n }\n /**\n *\n *\n *
    \n     * Required. Individual async file annotation requests for this batch.\n     * 
    \n *\n * \n * repeated .google.cloud.vision.v1p4beta1.AsyncAnnotateFileRequest requests = 1 [(.google.api.field_behavior) = REQUIRED];\n * \n */\n public Builder addRequests(com.google.cloud.vision.v1p4beta1.AsyncAnnotateFileRequest value) {\n if (requestsBuilder_ == null) {\n if (value == null) {\n throw new NullPointerException();\n }\n ensureRequestsIsMutable();\n requests_.add(value);\n onChanged();\n } else {\n requestsBuilder_.addMessage(value);\n }\n return this;\n }\n /**\n *\n *\n *
    \n     * Required. Individual async file annotation requests for this batch.\n     * 
    \n *\n * \n * repeated .google.cloud.vision.v1p4beta1.AsyncAnnotateFileRequest requests = 1 [(.google.api.field_behavior) = REQUIRED];\n * \n */\n public Builder addRequests(\n int index, com.google.cloud.vision.v1p4beta1.AsyncAnnotateFileRequest value) {\n if (requestsBuilder_ == null) {\n if (value == null) {\n throw new NullPointerException();\n }\n ensureRequestsIsMutable();\n requests_.add(index, value);\n onChanged();\n } else {\n requestsBuilder_.addMessage(index, value);\n }\n return this;\n }\n /**\n *\n *\n *
    \n     * Required. Individual async file annotation requests for this batch.\n     * 
    \n *\n * \n * repeated .google.cloud.vision.v1p4beta1.AsyncAnnotateFileRequest requests = 1 [(.google.api.field_behavior) = REQUIRED];\n * \n */\n public Builder addRequests(\n com.google.cloud.vision.v1p4beta1.AsyncAnnotateFileRequest.Builder builderForValue) {\n if (requestsBuilder_ == null) {\n ensureRequestsIsMutable();\n requests_.add(builderForValue.build());\n onChanged();\n } else {\n requestsBuilder_.addMessage(builderForValue.build());\n }\n return this;\n }\n /**\n *\n *\n *
    \n     * Required. Individual async file annotation requests for this batch.\n     * 
    \n *\n * \n * repeated .google.cloud.vision.v1p4beta1.AsyncAnnotateFileRequest requests = 1 [(.google.api.field_behavior) = REQUIRED];\n * \n */\n public Builder addRequests(\n int index,\n com.google.cloud.vision.v1p4beta1.AsyncAnnotateFileRequest.Builder builderForValue) {\n if (requestsBuilder_ == null) {\n ensureRequestsIsMutable();\n requests_.add(index, builderForValue.build());\n onChanged();\n } else {\n requestsBuilder_.addMessage(index, builderForValue.build());\n }\n return this;\n }\n /**\n *\n *\n *
    \n     * Required. Individual async file annotation requests for this batch.\n     * 
    \n *\n * \n * repeated .google.cloud.vision.v1p4beta1.AsyncAnnotateFileRequest requests = 1 [(.google.api.field_behavior) = REQUIRED];\n * \n */\n public Builder addAllRequests(\n java.lang.Iterable\n values) {\n if (requestsBuilder_ == null) {\n ensureRequestsIsMutable();\n com.google.protobuf.AbstractMessageLite.Builder.addAll(values, requests_);\n onChanged();\n } else {\n requestsBuilder_.addAllMessages(values);\n }\n return this;\n }\n /**\n *\n *\n *
    \n     * Required. Individual async file annotation requests for this batch.\n     * 
    \n *\n * \n * repeated .google.cloud.vision.v1p4beta1.AsyncAnnotateFileRequest requests = 1 [(.google.api.field_behavior) = REQUIRED];\n * \n */\n public Builder clearRequests() {\n if (requestsBuilder_ == null) {\n requests_ = java.util.Collections.emptyList();\n bitField0_ = (bitField0_ & ~0x00000001);\n onChanged();\n } else {\n requestsBuilder_.clear();\n }\n return this;\n }\n /**\n *\n *\n *
    \n     * Required. Individual async file annotation requests for this batch.\n     * 
    \n *\n * \n * repeated .google.cloud.vision.v1p4beta1.AsyncAnnotateFileRequest requests = 1 [(.google.api.field_behavior) = REQUIRED];\n * \n */\n public Builder removeRequests(int index) {\n if (requestsBuilder_ == null) {\n ensureRequestsIsMutable();\n requests_.remove(index);\n onChanged();\n } else {\n requestsBuilder_.remove(index);\n }\n return this;\n }\n /**\n *\n *\n *
    \n     * Required. Individual async file annotation requests for this batch.\n     * 
    \n *\n * \n * repeated .google.cloud.vision.v1p4beta1.AsyncAnnotateFileRequest requests = 1 [(.google.api.field_behavior) = REQUIRED];\n * \n */\n public com.google.cloud.vision.v1p4beta1.AsyncAnnotateFileRequest.Builder getRequestsBuilder(\n int index) {\n return getRequestsFieldBuilder().getBuilder(index);\n }\n /**\n *\n *\n *
    \n     * Required. Individual async file annotation requests for this batch.\n     * 
    \n *\n * \n * repeated .google.cloud.vision.v1p4beta1.AsyncAnnotateFileRequest requests = 1 [(.google.api.field_behavior) = REQUIRED];\n * \n */\n public com.google.cloud.vision.v1p4beta1.AsyncAnnotateFileRequestOrBuilder getRequestsOrBuilder(\n int index) {\n if (requestsBuilder_ == null) {\n return requests_.get(index);\n } else {\n return requestsBuilder_.getMessageOrBuilder(index);\n }\n }\n /**\n *\n *\n *
    \n     * Required. Individual async file annotation requests for this batch.\n     * 
    \n *\n * \n * repeated .google.cloud.vision.v1p4beta1.AsyncAnnotateFileRequest requests = 1 [(.google.api.field_behavior) = REQUIRED];\n * \n */\n public java.util.List<\n ? extends com.google.cloud.vision.v1p4beta1.AsyncAnnotateFileRequestOrBuilder>\n getRequestsOrBuilderList() {", "answers": [" if (requestsBuilder_ != null) {"], "length": 2261, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "616b095d-6931-4a5d-8a6e-e0cace30179f", "reasoning": "The code is inside the Builder class of a protobuf-generated message. After the method signature for getRequestsOrBuilderList(), the typical implementation checks whether the repeated field builder (requestsBuilder_) is null and returns either an unmodifiable list of the raw requests or the builder's message-or-builder list. Therefore the next line is the conditional check: if (requestsBuilder_ == null) {", "reasoning_model_answer": "if (requestsBuilder_ == null) {", "assistant_with_reasoning": "\nThe code is inside the Builder class of a protobuf-generated message. After the method signature for getRequestsOrBuilderList(), the typical implementation checks whether the repeated field builder (requestsBuilder_) is null and returns either an unmodifiable list of the raw requests or the builder's message-or-builder list. Therefore the next line is the conditional check: if (requestsBuilder_ == null) {\n\nif (requestsBuilder_ == null) {", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 6.028, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 30332, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "if (requestsBuilder_ == null) {", "score": 0.88, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "\npackage quickfix.fix42;\nimport quickfix.FieldNotFound;\n\nimport quickfix.Group;\n\npublic class SecurityDefinitionRequest extends Message\n{\n\n static final long serialVersionUID = 20050617;\n public static final String MSGTYPE = \"c\";\n \n\n public SecurityDefinitionRequest()\n {\n super();\n getHeader().setField(new quickfix.field.MsgType(MSGTYPE));\n }\n \n public SecurityDefinitionRequest(quickfix.field.SecurityReqID securityReqID, quickfix.field.SecurityRequestType securityRequestType) {\n this();\n setField(securityReqID);\n setField(securityRequestType);\n }\n \n public void set(quickfix.field.SecurityReqID value)\n {\n setField(value);\n }\n\n public quickfix.field.SecurityReqID get(quickfix.field.SecurityReqID value) throws FieldNotFound\n {\n getField(value);\n return value;\n }\n\n public quickfix.field.SecurityReqID getSecurityReqID() throws FieldNotFound\n {\n quickfix.field.SecurityReqID value = new quickfix.field.SecurityReqID();\n getField(value);\n return value;\n }\n\n public boolean isSet(quickfix.field.SecurityReqID field)\n {\n return isSetField(field);\n }\n\n public boolean isSetSecurityReqID()\n {\n return isSetField(320);\n }\n \n public void set(quickfix.field.SecurityRequestType value)\n {\n setField(value);\n }\n\n public quickfix.field.SecurityRequestType get(quickfix.field.SecurityRequestType value) throws FieldNotFound\n {\n getField(value);\n return value;\n }\n\n public quickfix.field.SecurityRequestType getSecurityRequestType() throws FieldNotFound\n {\n quickfix.field.SecurityRequestType value = new quickfix.field.SecurityRequestType();\n getField(value);\n return value;\n }\n\n public boolean isSet(quickfix.field.SecurityRequestType field)\n {\n return isSetField(field);\n }\n\n public boolean isSetSecurityRequestType()\n {\n return isSetField(321);\n }\n \n public void set(quickfix.field.Symbol value)\n {\n setField(value);\n }\n\n public quickfix.field.Symbol get(quickfix.field.Symbol value) throws FieldNotFound\n {\n getField(value);\n return value;\n }\n\n public quickfix.field.Symbol getSymbol() throws FieldNotFound\n {\n quickfix.field.Symbol value = new quickfix.field.Symbol();\n getField(value);\n return value;\n }\n\n public boolean isSet(quickfix.field.Symbol field)\n {\n return isSetField(field);\n }\n\n public boolean isSetSymbol()\n {\n return isSetField(55);\n }\n \n public void set(quickfix.field.SymbolSfx value)\n {\n setField(value);\n }\n\n public quickfix.field.SymbolSfx get(quickfix.field.SymbolSfx value) throws FieldNotFound\n {\n getField(value);\n return value;\n }\n\n public quickfix.field.SymbolSfx getSymbolSfx() throws FieldNotFound\n {\n quickfix.field.SymbolSfx value = new quickfix.field.SymbolSfx();\n getField(value);\n return value;\n }\n\n public boolean isSet(quickfix.field.SymbolSfx field)\n {\n return isSetField(field);\n }\n\n public boolean isSetSymbolSfx()\n {\n return isSetField(65);\n }\n \n public void set(quickfix.field.SecurityID value)\n {\n setField(value);\n }\n\n public quickfix.field.SecurityID get(quickfix.field.SecurityID value) throws FieldNotFound\n {\n getField(value);\n return value;\n }\n\n public quickfix.field.SecurityID getSecurityID() throws FieldNotFound\n {\n quickfix.field.SecurityID value = new quickfix.field.SecurityID();\n getField(value);\n return value;\n }\n\n public boolean isSet(quickfix.field.SecurityID field)\n {\n return isSetField(field);\n }\n\n public boolean isSetSecurityID()\n {\n return isSetField(48);\n }\n \n public void set(quickfix.field.IDSource value)\n {\n setField(value);\n }\n\n public quickfix.field.IDSource get(quickfix.field.IDSource value) throws FieldNotFound\n {\n getField(value);\n return value;\n }\n\n public quickfix.field.IDSource getIDSource() throws FieldNotFound\n {\n quickfix.field.IDSource value = new quickfix.field.IDSource();\n getField(value);\n return value;\n }\n\n public boolean isSet(quickfix.field.IDSource field)\n {\n return isSetField(field);\n }\n\n public boolean isSetIDSource()\n {\n return isSetField(22);\n }\n \n public void set(quickfix.field.SecurityType value)\n {\n setField(value);\n }\n\n public quickfix.field.SecurityType get(quickfix.field.SecurityType value) throws FieldNotFound\n {\n getField(value);\n return value;\n }\n\n public quickfix.field.SecurityType getSecurityType() throws FieldNotFound\n {\n quickfix.field.SecurityType value = new quickfix.field.SecurityType();\n getField(value);\n return value;\n }\n\n public boolean isSet(quickfix.field.SecurityType field)\n {\n return isSetField(field);\n }\n\n public boolean isSetSecurityType()\n {\n return isSetField(167);\n }\n \n public void set(quickfix.field.MaturityMonthYear value)\n {\n setField(value);\n }\n\n public quickfix.field.MaturityMonthYear get(quickfix.field.MaturityMonthYear value) throws FieldNotFound\n {\n getField(value);\n return value;\n }\n\n public quickfix.field.MaturityMonthYear getMaturityMonthYear() throws FieldNotFound\n {\n quickfix.field.MaturityMonthYear value = new quickfix.field.MaturityMonthYear();\n getField(value);\n return value;\n }\n\n public boolean isSet(quickfix.field.MaturityMonthYear field)\n {\n return isSetField(field);\n }\n\n public boolean isSetMaturityMonthYear()\n {\n return isSetField(200);\n }\n \n public void set(quickfix.field.MaturityDay value)\n {\n setField(value);\n }\n\n public quickfix.field.MaturityDay get(quickfix.field.MaturityDay value) throws FieldNotFound\n {\n getField(value);\n return value;\n }\n\n public quickfix.field.MaturityDay getMaturityDay() throws FieldNotFound\n {\n quickfix.field.MaturityDay value = new quickfix.field.MaturityDay();\n getField(value);\n return value;\n }\n\n public boolean isSet(quickfix.field.MaturityDay field)\n {\n return isSetField(field);\n }\n\n public boolean isSetMaturityDay()\n {\n return isSetField(205);\n }\n \n public void set(quickfix.field.PutOrCall value)\n {\n setField(value);\n }\n\n public quickfix.field.PutOrCall get(quickfix.field.PutOrCall value) throws FieldNotFound\n {\n getField(value);\n return value;\n }\n\n public quickfix.field.PutOrCall getPutOrCall() throws FieldNotFound\n {\n quickfix.field.PutOrCall value = new quickfix.field.PutOrCall();\n getField(value);\n return value;\n }\n\n public boolean isSet(quickfix.field.PutOrCall field)\n {\n return isSetField(field);\n }\n\n public boolean isSetPutOrCall()\n {\n return isSetField(201);\n }\n \n public void set(quickfix.field.StrikePrice value)\n {\n setField(value);\n }\n\n public quickfix.field.StrikePrice get(quickfix.field.StrikePrice value) throws FieldNotFound\n {\n getField(value);\n return value;\n }\n\n public quickfix.field.StrikePrice getStrikePrice() throws FieldNotFound\n {\n quickfix.field.StrikePrice value = new quickfix.field.StrikePrice();\n getField(value);\n return value;\n }\n\n public boolean isSet(quickfix.field.StrikePrice field)\n {\n return isSetField(field);\n }\n\n public boolean isSetStrikePrice()\n {\n return isSetField(202);\n }\n \n public void set(quickfix.field.OptAttribute value)\n {\n setField(value);\n }\n\n public quickfix.field.OptAttribute get(quickfix.field.OptAttribute value) throws FieldNotFound\n {\n getField(value);\n return value;\n }\n\n public quickfix.field.OptAttribute getOptAttribute() throws FieldNotFound\n {\n quickfix.field.OptAttribute value = new quickfix.field.OptAttribute();\n getField(value);\n return value;\n }\n\n public boolean isSet(quickfix.field.OptAttribute field)\n {\n return isSetField(field);\n }\n\n public boolean isSetOptAttribute()\n {\n return isSetField(206);\n }\n \n public void set(quickfix.field.ContractMultiplier value)\n {\n setField(value);\n }\n\n public quickfix.field.ContractMultiplier get(quickfix.field.ContractMultiplier value) throws FieldNotFound\n {\n getField(value);\n return value;\n }\n\n public quickfix.field.ContractMultiplier getContractMultiplier() throws FieldNotFound\n {\n quickfix.field.ContractMultiplier value = new quickfix.field.ContractMultiplier();\n getField(value);\n return value;\n }\n\n public boolean isSet(quickfix.field.ContractMultiplier field)\n {\n return isSetField(field);\n }\n\n public boolean isSetContractMultiplier()\n {\n return isSetField(231);\n }\n \n public void set(quickfix.field.CouponRate value)\n {\n setField(value);\n }\n\n public quickfix.field.CouponRate get(quickfix.field.CouponRate value) throws FieldNotFound\n {\n getField(value);\n return value;\n }\n\n public quickfix.field.CouponRate getCouponRate() throws FieldNotFound\n {\n quickfix.field.CouponRate value = new quickfix.field.CouponRate();\n getField(value);\n return value;\n }\n\n public boolean isSet(quickfix.field.CouponRate field)\n {\n return isSetField(field);\n }\n\n public boolean isSetCouponRate()\n {\n return isSetField(223);\n }\n \n public void set(quickfix.field.SecurityExchange value)\n {\n setField(value);\n }\n\n public quickfix.field.SecurityExchange get(quickfix.field.SecurityExchange value) throws FieldNotFound\n {\n getField(value);\n return value;\n }\n\n public quickfix.field.SecurityExchange getSecurityExchange() throws FieldNotFound\n {\n quickfix.field.SecurityExchange value = new quickfix.field.SecurityExchange();\n getField(value);\n return value;\n }\n\n public boolean isSet(quickfix.field.SecurityExchange field)\n {\n return isSetField(field);\n }\n\n public boolean isSetSecurityExchange()\n {\n return isSetField(207);\n }\n \n public void set(quickfix.field.Issuer value)\n {\n setField(value);\n }\n\n public quickfix.field.Issuer get(quickfix.field.Issuer value) throws FieldNotFound\n {\n getField(value);\n return value;\n }\n\n public quickfix.field.Issuer getIssuer() throws FieldNotFound\n {\n quickfix.field.Issuer value = new quickfix.field.Issuer();\n getField(value);\n return value;\n }\n\n public boolean isSet(quickfix.field.Issuer field)\n {\n return isSetField(field);\n }\n\n public boolean isSetIssuer()\n {\n return isSetField(106);\n }\n \n public void set(quickfix.field.EncodedIssuerLen value)\n {\n setField(value);\n }\n\n public quickfix.field.EncodedIssuerLen get(quickfix.field.EncodedIssuerLen value) throws FieldNotFound\n {\n getField(value);\n return value;\n }\n\n public quickfix.field.EncodedIssuerLen getEncodedIssuerLen() throws FieldNotFound\n {\n quickfix.field.EncodedIssuerLen value = new quickfix.field.EncodedIssuerLen();\n getField(value);\n return value;\n }\n\n public boolean isSet(quickfix.field.EncodedIssuerLen field)\n {\n return isSetField(field);\n }\n\n public boolean isSetEncodedIssuerLen()\n {\n return isSetField(348);\n }\n \n public void set(quickfix.field.EncodedIssuer value)\n {\n setField(value);\n }\n\n public quickfix.field.EncodedIssuer get(quickfix.field.EncodedIssuer value) throws FieldNotFound\n {\n getField(value);\n return value;\n }\n\n public quickfix.field.EncodedIssuer getEncodedIssuer() throws FieldNotFound\n {\n quickfix.field.EncodedIssuer value = new quickfix.field.EncodedIssuer();\n getField(value);\n return value;\n }\n\n public boolean isSet(quickfix.field.EncodedIssuer field)\n {\n return isSetField(field);\n }\n\n public boolean isSetEncodedIssuer()\n {\n return isSetField(349);\n }\n \n public void set(quickfix.field.SecurityDesc value)\n {\n setField(value);\n }\n\n public quickfix.field.SecurityDesc get(quickfix.field.SecurityDesc value) throws FieldNotFound\n {\n getField(value);\n return value;\n }\n\n public quickfix.field.SecurityDesc getSecurityDesc() throws FieldNotFound\n {\n quickfix.field.SecurityDesc value = new quickfix.field.SecurityDesc();\n getField(value);\n return value;\n }\n\n public boolean isSet(quickfix.field.SecurityDesc field)\n {\n return isSetField(field);\n }\n\n public boolean isSetSecurityDesc()\n {\n return isSetField(107);\n }\n \n public void set(quickfix.field.EncodedSecurityDescLen value)\n {\n setField(value);\n }\n\n public quickfix.field.EncodedSecurityDescLen get(quickfix.field.EncodedSecurityDescLen value) throws FieldNotFound\n {\n getField(value);\n return value;\n }\n\n public quickfix.field.EncodedSecurityDescLen getEncodedSecurityDescLen() throws FieldNotFound\n {\n quickfix.field.EncodedSecurityDescLen value = new quickfix.field.EncodedSecurityDescLen();\n getField(value);\n return value;\n }\n\n public boolean isSet(quickfix.field.EncodedSecurityDescLen field)\n {\n return isSetField(field);\n }\n\n public boolean isSetEncodedSecurityDescLen()\n {\n return isSetField(350);\n }\n \n public void set(quickfix.field.EncodedSecurityDesc value)\n {\n setField(value);\n }\n\n public quickfix.field.EncodedSecurityDesc get(quickfix.field.EncodedSecurityDesc value) throws FieldNotFound\n {\n getField(value);\n return value;\n }\n\n public quickfix.field.EncodedSecurityDesc getEncodedSecurityDesc() throws FieldNotFound\n {\n quickfix.field.EncodedSecurityDesc value = new quickfix.field.EncodedSecurityDesc();\n getField(value);\n return value;\n }\n\n public boolean isSet(quickfix.field.EncodedSecurityDesc field)\n {\n return isSetField(field);\n }\n\n public boolean isSetEncodedSecurityDesc()\n {\n return isSetField(351);\n }\n \n public void set(quickfix.field.Currency value)\n {\n setField(value);\n }\n\n public quickfix.field.Currency get(quickfix.field.Currency value) throws FieldNotFound\n {\n getField(value);\n return value;\n }\n\n public quickfix.field.Currency getCurrency() throws FieldNotFound\n {\n quickfix.field.Currency value = new quickfix.field.Currency();\n getField(value);\n return value;\n }\n\n public boolean isSet(quickfix.field.Currency field)\n {\n return isSetField(field);\n }\n\n public boolean isSetCurrency()\n {\n return isSetField(15);\n }\n \n public void set(quickfix.field.Text value)\n {\n setField(value);\n }\n\n public quickfix.field.Text get(quickfix.field.Text value) throws FieldNotFound\n {\n getField(value);\n return value;\n }\n\n public quickfix.field.Text getText() throws FieldNotFound\n {\n quickfix.field.Text value = new quickfix.field.Text();\n getField(value);\n return value;\n }\n\n public boolean isSet(quickfix.field.Text field)\n {\n return isSetField(field);\n }\n\n public boolean isSetText()\n {\n return isSetField(58);\n }\n \n public void set(quickfix.field.EncodedTextLen value)\n {\n setField(value);\n }\n\n public quickfix.field.EncodedTextLen get(quickfix.field.EncodedTextLen value) throws FieldNotFound\n {\n getField(value);\n return value;\n }\n\n public quickfix.field.EncodedTextLen getEncodedTextLen() throws FieldNotFound\n {\n quickfix.field.EncodedTextLen value = new quickfix.field.EncodedTextLen();\n getField(value);\n return value;\n }\n\n public boolean isSet(quickfix.field.EncodedTextLen field)\n {\n return isSetField(field);\n }\n\n public boolean isSetEncodedTextLen()\n {\n return isSetField(354);\n }\n \n public void set(quickfix.field.EncodedText value)\n {\n setField(value);\n }\n\n public quickfix.field.EncodedText get(quickfix.field.EncodedText value) throws FieldNotFound\n {\n getField(value);\n return value;\n }\n\n public quickfix.field.EncodedText getEncodedText() throws FieldNotFound\n {\n quickfix.field.EncodedText value = new quickfix.field.EncodedText();\n getField(value);\n return value;\n }\n\n public boolean isSet(quickfix.field.EncodedText field)\n {\n return isSetField(field);\n }\n\n public boolean isSetEncodedText()\n {\n return isSetField(355);\n }\n \n public void set(quickfix.field.TradingSessionID value)\n {\n setField(value);\n }\n\n public quickfix.field.TradingSessionID get(quickfix.field.TradingSessionID value) throws FieldNotFound\n {\n getField(value);\n return value;\n }\n\n public quickfix.field.TradingSessionID getTradingSessionID() throws FieldNotFound\n {\n quickfix.field.TradingSessionID value = new quickfix.field.TradingSessionID();\n getField(value);\n return value;\n }\n\n public boolean isSet(quickfix.field.TradingSessionID field)\n {\n return isSetField(field);\n }\n\n public boolean isSetTradingSessionID()\n {\n return isSetField(336);\n }\n \n public void set(quickfix.field.NoRelatedSym value)\n {\n setField(value);\n }\n\n public quickfix.field.NoRelatedSym get(quickfix.field.NoRelatedSym value) throws FieldNotFound\n {\n getField(value);\n return value;\n }\n\n public quickfix.field.NoRelatedSym getNoRelatedSym() throws FieldNotFound\n {\n quickfix.field.NoRelatedSym value = new quickfix.field.NoRelatedSym();\n getField(value);\n return value;\n }\n\n public boolean isSet(quickfix.field.NoRelatedSym field)\n {\n return isSetField(field);\n }\n\n public boolean isSetNoRelatedSym()\n {\n return isSetField(146);\n }\n \n public static class NoRelatedSym extends Group {\n static final long serialVersionUID = 20050617;\n public NoRelatedSym() {\n super(146, 311,\n new int[] {311, 312, 309, 305, 310, 313, 314, 315, 316, 317, 436, 435, 308, 306, 362, 363, 307, 364, 365, 319, 54, 318, 0 } );\n }\n \n public void set(quickfix.field.UnderlyingSymbol value)\n {\n setField(value);\n }\n\n public quickfix.field.UnderlyingSymbol get(quickfix.field.UnderlyingSymbol value) throws FieldNotFound\n {\n getField(value);\n return value;\n }\n\n public quickfix.field.UnderlyingSymbol getUnderlyingSymbol() throws FieldNotFound\n {\n quickfix.field.UnderlyingSymbol value = new quickfix.field.UnderlyingSymbol();\n getField(value);\n return value;\n }\n\n public boolean isSet(quickfix.field.UnderlyingSymbol field)\n {\n return isSetField(field);\n }\n\n public boolean isSetUnderlyingSymbol()\n {\n return isSetField(311);\n }\n \n public void set(quickfix.field.UnderlyingSymbolSfx value)\n {\n setField(value);\n }\n\n public quickfix.field.UnderlyingSymbolSfx get(quickfix.field.UnderlyingSymbolSfx value) throws FieldNotFound\n {\n getField(value);\n return value;\n }\n\n public quickfix.field.UnderlyingSymbolSfx getUnderlyingSymbolSfx() throws FieldNotFound\n {\n quickfix.field.UnderlyingSymbolSfx value = new quickfix.field.UnderlyingSymbolSfx();\n getField(value);\n return value;\n }\n\n public boolean isSet(quickfix.field.UnderlyingSymbolSfx field)\n {\n return isSetField(field);\n }\n\n public boolean isSetUnderlyingSymbolSfx()\n {\n return isSetField(312);\n }\n \n public void set(quickfix.field.UnderlyingSecurityID value)\n {\n setField(value);\n }\n\n public quickfix.field.UnderlyingSecurityID get(quickfix.field.UnderlyingSecurityID value) throws FieldNotFound\n {\n getField(value);\n return value;\n }\n\n public quickfix.field.UnderlyingSecurityID getUnderlyingSecurityID() throws FieldNotFound\n {\n quickfix.field.UnderlyingSecurityID value = new quickfix.field.UnderlyingSecurityID();\n getField(value);\n return value;\n }\n\n public boolean isSet(quickfix.field.UnderlyingSecurityID field)\n {\n return isSetField(field);\n }\n\n public boolean isSetUnderlyingSecurityID()\n {\n return isSetField(309);\n }\n \n public void set(quickfix.field.UnderlyingIDSource value)\n {\n setField(value);\n }\n\n public quickfix.field.UnderlyingIDSource get(quickfix.field.UnderlyingIDSource value) throws FieldNotFound\n {\n getField(value);\n return value;\n }\n\n public quickfix.field.UnderlyingIDSource getUnderlyingIDSource() throws FieldNotFound\n {\n quickfix.field.UnderlyingIDSource value = new quickfix.field.UnderlyingIDSource();\n getField(value);\n return value;\n }\n\n public boolean isSet(quickfix.field.UnderlyingIDSource field)\n {\n return isSetField(field);\n }\n\n public boolean isSetUnderlyingIDSource()\n {\n return isSetField(305);\n }\n \n public void set(quickfix.field.UnderlyingSecurityType value)\n {\n setField(value);\n }\n\n public quickfix.field.UnderlyingSecurityType get(quickfix.field.UnderlyingSecurityType value) throws FieldNotFound\n {\n getField(value);\n return value;\n }\n\n public quickfix.field.UnderlyingSecurityType getUnderlyingSecurityType() throws FieldNotFound\n {\n quickfix.field.UnderlyingSecurityType value = new quickfix.field.UnderlyingSecurityType();\n getField(value);\n return value;\n }\n\n public boolean isSet(quickfix.field.UnderlyingSecurityType field)\n {\n return isSetField(field);\n }\n\n public boolean isSetUnderlyingSecurityType()\n {\n return isSetField(310);\n }\n \n public void set(quickfix.field.UnderlyingMaturityMonthYear value)\n {\n setField(value);\n }\n\n public quickfix.field.UnderlyingMaturityMonthYear get(quickfix.field.UnderlyingMaturityMonthYear value) throws FieldNotFound\n {\n getField(value);\n return value;\n }\n\n public quickfix.field.UnderlyingMaturityMonthYear getUnderlyingMaturityMonthYear() throws FieldNotFound\n {\n quickfix.field.UnderlyingMaturityMonthYear value = new quickfix.field.UnderlyingMaturityMonthYear();\n getField(value);\n return value;\n }\n\n public boolean isSet(quickfix.field.UnderlyingMaturityMonthYear field)\n {\n return isSetField(field);\n }\n\n public boolean isSetUnderlyingMaturityMonthYear()\n {\n return isSetField(313);\n }\n \n public void set(quickfix.field.UnderlyingMaturityDay value)\n {\n setField(value);\n }\n\n public quickfix.field.UnderlyingMaturityDay get(quickfix.field.UnderlyingMaturityDay value) throws FieldNotFound\n {\n getField(value);\n return value;\n }\n\n public quickfix.field.UnderlyingMaturityDay getUnderlyingMaturityDay() throws FieldNotFound\n {\n quickfix.field.UnderlyingMaturityDay value = new quickfix.field.UnderlyingMaturityDay();\n getField(value);\n return value;\n }\n\n public boolean isSet(quickfix.field.UnderlyingMaturityDay field)\n {\n return isSetField(field);\n }\n\n public boolean isSetUnderlyingMaturityDay()\n {\n return isSetField(314);\n }\n \n public void set(quickfix.field.UnderlyingPutOrCall value)\n {\n setField(value);\n }\n\n public quickfix.field.UnderlyingPutOrCall get(quickfix.field.UnderlyingPutOrCall value) throws FieldNotFound\n {\n getField(value);\n return value;\n }\n\n public quickfix.field.UnderlyingPutOrCall getUnderlyingPutOrCall() throws FieldNotFound\n {\n quickfix.field.UnderlyingPutOrCall value = new quickfix.field.UnderlyingPutOrCall();\n getField(value);\n return value;\n }\n\n public boolean isSet(quickfix.field.UnderlyingPutOrCall field)\n {\n return isSetField(field);\n }\n\n public boolean isSetUnderlyingPutOrCall()\n {\n return isSetField(315);\n }\n \n public void set(quickfix.field.UnderlyingStrikePrice value)\n {\n setField(value);\n }\n\n public quickfix.field.UnderlyingStrikePrice get(quickfix.field.UnderlyingStrikePrice value) throws FieldNotFound\n {\n getField(value);\n return value;\n }\n\n public quickfix.field.UnderlyingStrikePrice getUnderlyingStrikePrice() throws FieldNotFound\n {\n quickfix.field.UnderlyingStrikePrice value = new quickfix.field.UnderlyingStrikePrice();\n getField(value);\n return value;\n }\n\n public boolean isSet(quickfix.field.UnderlyingStrikePrice field)\n {\n return isSetField(field);\n }\n\n public boolean isSetUnderlyingStrikePrice()\n {\n return isSetField(316);\n }\n \n public void set(quickfix.field.UnderlyingOptAttribute value)\n {\n setField(value);\n }\n\n public quickfix.field.UnderlyingOptAttribute get(quickfix.field.UnderlyingOptAttribute value) throws FieldNotFound\n {\n getField(value);\n return value;\n }\n\n public quickfix.field.UnderlyingOptAttribute getUnderlyingOptAttribute() throws FieldNotFound\n {\n quickfix.field.UnderlyingOptAttribute value = new quickfix.field.UnderlyingOptAttribute();\n getField(value);\n return value;\n }\n\n public boolean isSet(quickfix.field.UnderlyingOptAttribute field)\n {\n return isSetField(field);\n }\n\n public boolean isSetUnderlyingOptAttribute()\n {\n return isSetField(317);\n }\n \n public void set(quickfix.field.UnderlyingContractMultiplier value)\n {\n setField(value);\n }\n\n public quickfix.field.UnderlyingContractMultiplier get(quickfix.field.UnderlyingContractMultiplier value) throws FieldNotFound\n {\n getField(value);\n return value;\n }\n\n public quickfix.field.UnderlyingContractMultiplier getUnderlyingContractMultiplier() throws FieldNotFound\n {\n quickfix.field.UnderlyingContractMultiplier value = new quickfix.field.UnderlyingContractMultiplier();\n getField(value);\n return value;\n }\n\n public boolean isSet(quickfix.field.UnderlyingContractMultiplier field)\n {\n return isSetField(field);\n }\n\n public boolean isSetUnderlyingContractMultiplier()\n {\n return isSetField(436);\n }\n \n public void set(quickfix.field.UnderlyingCouponRate value)\n {\n setField(value);\n }\n\n public quickfix.field.UnderlyingCouponRate get(quickfix.field.UnderlyingCouponRate value) throws FieldNotFound\n {\n getField(value);\n return value;\n }\n\n public quickfix.field.UnderlyingCouponRate getUnderlyingCouponRate() throws FieldNotFound\n {\n quickfix.field.UnderlyingCouponRate value = new quickfix.field.UnderlyingCouponRate();\n getField(value);\n return value;\n }\n\n public boolean isSet(quickfix.field.UnderlyingCouponRate field)\n {\n return isSetField(field);\n }\n\n public boolean isSetUnderlyingCouponRate()\n {\n return isSetField(435);\n }\n \n public void set(quickfix.field.UnderlyingSecurityExchange value)\n {\n setField(value);\n }\n\n public quickfix.field.UnderlyingSecurityExchange get(quickfix.field.UnderlyingSecurityExchange value) throws FieldNotFound\n {\n getField(value);\n return value;\n }\n\n public quickfix.field.UnderlyingSecurityExchange getUnderlyingSecurityExchange() throws FieldNotFound\n {\n quickfix.field.UnderlyingSecurityExchange value = new quickfix.field.UnderlyingSecurityExchange();\n getField(value);\n return value;\n }\n\n public boolean isSet(quickfix.field.UnderlyingSecurityExchange field)\n {\n return isSetField(field);\n }\n\n public boolean isSetUnderlyingSecurityExchange()\n {\n return isSetField(308);\n }\n \n public void set(quickfix.field.UnderlyingIssuer value)\n {\n setField(value);\n }\n\n public quickfix.field.UnderlyingIssuer get(quickfix.field.UnderlyingIssuer value) throws FieldNotFound\n {\n getField(value);\n return value;\n }\n\n public quickfix.field.UnderlyingIssuer getUnderlyingIssuer() throws FieldNotFound\n {\n quickfix.field.UnderlyingIssuer value = new quickfix.field.UnderlyingIssuer();\n getField(value);\n return value;\n }\n\n public boolean isSet(quickfix.field.UnderlyingIssuer field)\n {\n return isSetField(field);\n }\n\n public boolean isSetUnderlyingIssuer()\n {\n return isSetField(306);\n }\n \n public void set(quickfix.field.EncodedUnderlyingIssuerLen value)\n {\n setField(value);\n }\n\n public quickfix.field.EncodedUnderlyingIssuerLen get(quickfix.field.EncodedUnderlyingIssuerLen value) throws FieldNotFound\n {\n getField(value);\n return value;\n }\n\n public quickfix.field.EncodedUnderlyingIssuerLen getEncodedUnderlyingIssuerLen() throws FieldNotFound\n {\n quickfix.field.EncodedUnderlyingIssuerLen value = new quickfix.field.EncodedUnderlyingIssuerLen();\n getField(value);\n return value;\n }\n\n public boolean isSet(quickfix.field.EncodedUnderlyingIssuerLen field)\n {\n return isSetField(field);\n }\n\n public boolean isSetEncodedUnderlyingIssuerLen()\n {\n return isSetField(362);\n }\n \n public void set(quickfix.field.EncodedUnderlyingIssuer value)\n {\n setField(value);\n }\n\n public quickfix.field.EncodedUnderlyingIssuer get(quickfix.field.EncodedUnderlyingIssuer value) throws FieldNotFound\n {\n getField(value);\n return value;\n }\n\n public quickfix.field.EncodedUnderlyingIssuer getEncodedUnderlyingIssuer() throws FieldNotFound\n {\n quickfix.field.EncodedUnderlyingIssuer value = new quickfix.field.EncodedUnderlyingIssuer();\n getField(value);\n return value;\n }\n\n public boolean isSet(quickfix.field.EncodedUnderlyingIssuer field)\n {\n return isSetField(field);\n }\n\n public boolean isSetEncodedUnderlyingIssuer()\n {\n return isSetField(363);\n }\n \n public void set(quickfix.field.UnderlyingSecurityDesc value)\n {\n setField(value);\n }\n\n public quickfix.field.UnderlyingSecurityDesc get(quickfix.field.UnderlyingSecurityDesc value) throws FieldNotFound\n {\n getField(value);\n return value;\n }\n\n public quickfix.field.UnderlyingSecurityDesc getUnderlyingSecurityDesc() throws FieldNotFound\n {\n quickfix.field.UnderlyingSecurityDesc value = new quickfix.field.UnderlyingSecurityDesc();\n getField(value);\n return value;\n }\n\n public boolean isSet(quickfix.field.UnderlyingSecurityDesc field)\n {\n return isSetField(field);\n }\n\n public boolean isSetUnderlyingSecurityDesc()\n {\n return isSetField(307);\n }\n \n public void set(quickfix.field.EncodedUnderlyingSecurityDescLen value)\n {\n setField(value);\n }\n\n public quickfix.field.EncodedUnderlyingSecurityDescLen get(quickfix.field.EncodedUnderlyingSecurityDescLen value) throws FieldNotFound\n {\n getField(value);\n return value;\n }\n", "answers": [" public quickfix.field.EncodedUnderlyingSecurityDescLen getEncodedUnderlyingSecurityDescLen() throws FieldNotFound"], "length": 2223, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "348233a6-d261-4653-b974-5d517d85f203", "reasoning": "The code follows a repetitive pattern for each FIX field: a set method, a get method that takes a field instance, then a convenience get method that creates a new field, followed by isSet overloads. After the set and get methods for EncodedUnderlyingSecurityDescLen, the next line should be the convenience getter method signature for that field, matching earlier patterns.", "reasoning_model_answer": "public quickfix.field.EncodedUnderlyingSecurityDescLen getEncodedUnderlyingSecurityDescLen() throws FieldNotFound", "assistant_with_reasoning": "\nThe code follows a repetitive pattern for each FIX field: a set method, a get method that takes a field instance, then a convenience get method that creates a new field, followed by isSet overloads. After the set and get methods for EncodedUnderlyingSecurityDescLen, the next line should be the convenience getter method signature for that field, matching earlier patterns.\n\npublic quickfix.field.EncodedUnderlyingSecurityDescLen getEncodedUnderlyingSecurityDescLen() throws FieldNotFound", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 8.593, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 2, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 29254, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "public quickfix.field.EncodedUnderlyingSecurityDescLen getEncodedUnderlyingSecurityDescLen() throws FieldNotFound", "score": 0.99, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.apache.geode.internal.cache;\n\nimport java.io.File;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.net.URL;\nimport java.util.Collection;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Optional;\nimport java.util.Properties;\nimport java.util.Set;\nimport java.util.concurrent.Executor;\nimport java.util.concurrent.TimeUnit;\n\nimport javax.naming.Context;\nimport javax.transaction.TransactionManager;\n\nimport io.micrometer.core.instrument.MeterRegistry;\n\nimport org.apache.geode.CancelCriterion;\nimport org.apache.geode.LogWriter;\nimport org.apache.geode.cache.Cache;\nimport org.apache.geode.cache.CacheClosedException;\nimport org.apache.geode.cache.CacheTransactionManager;\nimport org.apache.geode.cache.CacheWriterException;\nimport org.apache.geode.cache.Declarable;\nimport org.apache.geode.cache.DiskStore;\nimport org.apache.geode.cache.DiskStoreFactory;\nimport org.apache.geode.cache.DynamicRegionFactory;\nimport org.apache.geode.cache.GatewayException;\nimport org.apache.geode.cache.Region;\nimport org.apache.geode.cache.RegionAttributes;\nimport org.apache.geode.cache.RegionExistsException;\nimport org.apache.geode.cache.RegionFactory;\nimport org.apache.geode.cache.RegionShortcut;\nimport org.apache.geode.cache.TimeoutException;\nimport org.apache.geode.cache.asyncqueue.AsyncEventQueue;\nimport org.apache.geode.cache.asyncqueue.AsyncEventQueueFactory;\nimport org.apache.geode.cache.asyncqueue.internal.AsyncEventQueueImpl;\nimport org.apache.geode.cache.client.internal.ClientMetadataService;\nimport org.apache.geode.cache.control.ResourceManager;\nimport org.apache.geode.cache.query.QueryService;\nimport org.apache.geode.cache.query.internal.InternalQueryService;\nimport org.apache.geode.cache.query.internal.QueryMonitor;\nimport org.apache.geode.cache.query.internal.cq.CqService;\nimport org.apache.geode.cache.server.CacheServer;\nimport org.apache.geode.cache.snapshot.CacheSnapshotService;\nimport org.apache.geode.cache.util.GatewayConflictResolver;\nimport org.apache.geode.cache.wan.GatewayReceiver;\nimport org.apache.geode.cache.wan.GatewayReceiverFactory;\nimport org.apache.geode.cache.wan.GatewaySender;\nimport org.apache.geode.cache.wan.GatewaySenderFactory;\nimport org.apache.geode.distributed.DistributedLockService;\nimport org.apache.geode.distributed.DistributedMember;\nimport org.apache.geode.distributed.DistributedSystem;\nimport org.apache.geode.distributed.internal.DistributionAdvisor;\nimport org.apache.geode.distributed.internal.DistributionManager;\nimport org.apache.geode.distributed.internal.InternalDistributedSystem;\nimport org.apache.geode.distributed.internal.membership.InternalDistributedMember;\nimport org.apache.geode.i18n.LogWriterI18n;\nimport org.apache.geode.internal.SystemTimer;\nimport org.apache.geode.internal.admin.ClientHealthMonitoringRegion;\nimport org.apache.geode.internal.cache.InitialImageOperation.Entry;\nimport org.apache.geode.internal.cache.backup.BackupService;\nimport org.apache.geode.internal.cache.control.InternalResourceManager;\nimport org.apache.geode.internal.cache.control.ResourceAdvisor;\nimport org.apache.geode.internal.cache.event.EventTrackerExpiryTask;\nimport org.apache.geode.internal.cache.extension.ExtensionPoint;\nimport org.apache.geode.internal.cache.persistence.PersistentMemberManager;\nimport org.apache.geode.internal.cache.tier.sockets.CacheClientNotifier;\nimport org.apache.geode.internal.cache.tier.sockets.ClientProxyMembershipID;\nimport org.apache.geode.internal.logging.InternalLogWriter;\nimport org.apache.geode.internal.offheap.MemoryAllocator;\nimport org.apache.geode.internal.security.SecurityService;\nimport org.apache.geode.management.internal.JmxManagerAdvisor;\nimport org.apache.geode.management.internal.RestAgent;\nimport org.apache.geode.pdx.JSONFormatter;\nimport org.apache.geode.pdx.PdxInstance;\nimport org.apache.geode.pdx.PdxInstanceFactory;\nimport org.apache.geode.pdx.PdxSerializer;\nimport org.apache.geode.pdx.internal.TypeRegistry;\nimport org.apache.geode.security.NotAuthorizedException;\n\n/**\n * This class delegates all methods to the InternalCache instance\n * it wraps. Any regions returned will be checked and if they are\n * internal an exception is thrown if they are.\n * Note: an instance of this class should be used by servers that\n * process requests from clients that contains region names to prevent\n * the client from directly accessing internal regions.\n */\npublic class InternalCacheForClientAccess implements InternalCache {\n\n private final InternalCache delegate;\n\n public InternalCacheForClientAccess(InternalCache delegate) {\n this.delegate = delegate;\n }\n\n private void checkForInternalRegion(Region r) {\n if (r == null) {\n return;\n }\n InternalRegion ir = (InternalRegion) r;\n if (ir.isInternalRegion()\n && !r.getName().equals(DynamicRegionFactory.DYNAMIC_REGION_LIST_NAME)\n && !r.getName().equals(ClientHealthMonitoringRegion.ADMIN_REGION_NAME)) {\n throw new NotAuthorizedException(\"The region \" + r.getName()\n + \" is an internal region that a client is never allowed to access\");\n }\n }\n\n @SuppressWarnings(\"unchecked\")\n private void checkSetOfRegions(@SuppressWarnings(\"rawtypes\") Set regions) {\n for (InternalRegion r : (Set) regions) {\n checkForInternalRegion(r);\n }\n }\n\n @Override\n public Region getRegion(String path) {\n Region result = delegate.getRegion(path);\n checkForInternalRegion(result);\n return result;\n }\n\n /**\n * This method can be used to locate an internal region.\n * It should not be invoked with a region name obtained\n * from a client.\n */\n public Region getInternalRegion(String path) {\n return delegate.getRegion(path);\n }\n\n @Override\n public Region getRegion(String path, boolean returnDestroyedRegion) {\n Region result = delegate.getRegion(path, returnDestroyedRegion);\n checkForInternalRegion(result);\n return result;\n }\n\n @Override\n public InternalRegion getReinitializingRegion(String fullPath) {\n InternalRegion result = delegate.getReinitializingRegion(fullPath);\n checkForInternalRegion(result);\n return result;\n }\n\n @Override\n public InternalRegion getRegionByPath(String path) {\n InternalRegion result = delegate.getRegionByPath(path);\n checkForInternalRegion(result);\n return result;\n }\n\n @Override\n public InternalRegion getRegionByPathForProcessing(String path) {\n InternalRegion result = delegate.getRegionByPathForProcessing(path);\n checkForInternalRegion(result);\n return result;\n }\n\n @Override\n public DistributedRegion getRegionInDestroy(String path) {\n DistributedRegion result = delegate.getRegionInDestroy(path);\n checkForInternalRegion(result);\n return result;\n }\n\n @Override\n public Set getPartitionedRegions() {\n Set result = delegate.getPartitionedRegions();\n checkSetOfRegions(result);\n return result;\n }\n\n @Override\n public Set> rootRegions() {\n Set> result = delegate.rootRegions();\n checkSetOfRegions(result);\n return result;\n }\n\n @Override\n public Set> rootRegions(boolean includePRAdminRegions) {\n Set> result = delegate.rootRegions(includePRAdminRegions);\n checkSetOfRegions(result);\n return result;\n }\n\n @Override\n public Set getAllRegions() {\n Set result = delegate.getAllRegions();\n checkSetOfRegions(result);\n return result;\n }\n\n @Override\n public Region createVMRegion(String name, RegionAttributes p_attrs,\n InternalRegionArguments internalRegionArgs)\n throws RegionExistsException, TimeoutException, IOException, ClassNotFoundException {\n if (internalRegionArgs != null) {\n if (internalRegionArgs.isInternalRegion()\n || internalRegionArgs.isUsedForPartitionedRegionBucket()\n || internalRegionArgs.isUsedForMetaRegion()\n || internalRegionArgs.isUsedForSerialGatewaySenderQueue()\n || internalRegionArgs.isUsedForParallelGatewaySenderQueue()) {\n throw new NotAuthorizedException(\"The region \" + name\n + \" is an internal region that a client is never allowed to create\");\n }\n }\n return delegate.createVMRegion(name, p_attrs, internalRegionArgs);\n }\n\n /**\n * This method allows server-side code to create an internal region. It should\n * not be invoked with a region name obtained from a client.\n */\n public Region createInternalRegion(String name, RegionAttributes p_attrs,\n InternalRegionArguments internalRegionArgs)\n throws RegionExistsException, TimeoutException, IOException, ClassNotFoundException {\n return delegate.createVMRegion(name, p_attrs, internalRegionArgs);\n }\n\n @Override\n public Cache getReconnectedCache() {\n Cache reconnectedCache = delegate.getReconnectedCache();\n if (reconnectedCache != null) {\n return new InternalCacheForClientAccess((InternalCache) reconnectedCache);\n } else {\n return null;\n }\n }\n\n @Override\n public FilterProfile getFilterProfile(String regionName) {\n InternalRegion r = (InternalRegion) getRegion(regionName, true);\n if (r != null) {\n return r.getFilterProfile();\n }\n return null;\n }\n\n @Override\n public Region basicCreateRegion(String name, RegionAttributes attrs)\n throws RegionExistsException, TimeoutException {\n return delegate.basicCreateRegion(name, attrs);\n }\n\n @Override\n public Region createVMRegion(String name, RegionAttributes aRegionAttributes)\n throws RegionExistsException, TimeoutException {\n return delegate.createVMRegion(name, aRegionAttributes);\n }\n\n @Override\n public Region createRegion(String name, RegionAttributes aRegionAttributes)\n throws RegionExistsException, TimeoutException {\n return delegate.createRegion(name, aRegionAttributes);\n }\n\n @Override\n public RegionFactory createRegionFactory() {\n return delegate.createRegionFactory();\n }\n\n @Override\n public RegionFactory createRegionFactory(RegionShortcut shortcut) {\n return delegate.createRegionFactory(shortcut);\n }\n\n @Override\n public RegionFactory createRegionFactory(String regionAttributesId) {\n return delegate.createRegionFactory(regionAttributesId);\n }\n\n @Override\n public RegionFactory createRegionFactory(RegionAttributes regionAttributes) {\n return delegate.createRegionFactory(regionAttributes);\n }\n\n @Override\n public void close(boolean keepAlive) {\n delegate.close(keepAlive);\n }\n\n @Override\n public LogWriterI18n getLoggerI18n() {\n return delegate.getLoggerI18n();\n }\n\n @Override\n public LogWriterI18n getSecurityLoggerI18n() {\n return delegate.getSecurityLoggerI18n();\n }\n\n @Override\n public int getLockTimeout() {\n return delegate.getLockTimeout();\n }\n\n @Override\n public void setLockTimeout(int seconds) {\n delegate.setLockTimeout(seconds);\n }\n\n @Override\n public int getMessageSyncInterval() {\n return delegate.getMessageSyncInterval();\n }\n\n @Override\n public void setMessageSyncInterval(int seconds) {\n delegate.setMessageSyncInterval(seconds);\n }\n\n @Override\n public int getLockLease() {\n return delegate.getLockLease();\n }\n\n @Override\n public void setLockLease(int seconds) {\n delegate.setLockLease(seconds);\n }\n\n @Override\n public int getSearchTimeout() {\n return delegate.getSearchTimeout();\n }\n\n @Override\n public void setSearchTimeout(int seconds) {\n delegate.setSearchTimeout(seconds);\n }\n\n @Override\n public CacheServer addCacheServer() {\n return delegate.addCacheServer();\n }\n\n @Override\n public List getCacheServers() {\n return delegate.getCacheServers();\n }\n\n @Override\n public void setGatewayConflictResolver(GatewayConflictResolver resolver) {\n delegate.setGatewayConflictResolver(resolver);\n }\n\n @Override\n public GatewayConflictResolver getGatewayConflictResolver() {\n return delegate.getGatewayConflictResolver();\n }\n\n @Override\n public void setIsServer(boolean isServer) {\n delegate.setIsServer(isServer);\n }\n\n @Override\n public boolean isServer() {\n return delegate.isServer();\n }\n\n @Override\n public void readyForEvents() {\n delegate.readyForEvents();\n }\n\n @Override\n public GatewaySenderFactory createGatewaySenderFactory() {\n return delegate.createGatewaySenderFactory();\n }\n\n @Override\n public AsyncEventQueueFactory createAsyncEventQueueFactory() {\n return delegate.createAsyncEventQueueFactory();\n }\n\n @Override\n public GatewayReceiverFactory createGatewayReceiverFactory() {\n return delegate.createGatewayReceiverFactory();\n }\n\n @Override\n public Set getGatewaySenders() {\n return delegate.getGatewaySenders();\n }\n\n @Override\n public GatewaySender getGatewaySender(String id) {\n return delegate.getGatewaySender(id);\n }\n\n @Override\n public Set getGatewayReceivers() {\n return delegate.getGatewayReceivers();\n }\n\n @Override\n public Set getAsyncEventQueues() {\n return delegate.getAsyncEventQueues();\n }\n\n @Override\n public AsyncEventQueue getAsyncEventQueue(String id) {\n return delegate.getAsyncEventQueue(id);\n }\n\n @Override\n public Set getMembers() {\n return delegate.getMembers();\n }\n\n @Override\n public Set getAdminMembers() {\n return delegate.getAdminMembers();\n }\n\n @Override\n public Set getMembers(Region region) {\n return delegate.getMembers(region);\n }\n\n @Override\n public CacheSnapshotService getSnapshotService() {\n return delegate.getSnapshotService();\n }\n\n @Override\n public boolean isReconnecting() {\n return delegate.isReconnecting();\n }\n\n @Override\n public boolean waitUntilReconnected(long time, TimeUnit units) throws InterruptedException {\n return delegate.waitUntilReconnected(time, units);\n }\n\n @Override\n public void stopReconnecting() {\n delegate.stopReconnecting();\n }\n\n @Override\n public String getName() {\n return delegate.getName();\n }\n\n @Override\n public DistributedSystem getDistributedSystem() {\n return delegate.getDistributedSystem();\n }\n\n @Override\n public ResourceManager getResourceManager() {\n return delegate.getResourceManager();\n }\n\n @Override\n public void setCopyOnRead(boolean copyOnRead) {\n delegate.setCopyOnRead(copyOnRead);\n }\n\n @Override\n public boolean getCopyOnRead() {\n return delegate.getCopyOnRead();\n }\n\n @Override\n public RegionAttributes getRegionAttributes(String id) {\n return delegate.getRegionAttributes(id);\n }\n\n @Override\n public void setRegionAttributes(String id, RegionAttributes attrs) {\n delegate.setRegionAttributes(id, attrs);\n }\n\n @Override\n public Map> listRegionAttributes() {\n return delegate.listRegionAttributes();\n }\n\n @Override\n public void loadCacheXml(InputStream is)\n throws TimeoutException, CacheWriterException, GatewayException, RegionExistsException {\n delegate.loadCacheXml(is);\n }\n\n @Override\n public LogWriter getLogger() {\n return delegate.getLogger();\n }\n\n @Override\n public LogWriter getSecurityLogger() {\n return delegate.getSecurityLogger();\n }\n\n @Override\n public DiskStore findDiskStore(String name) {\n return delegate.findDiskStore(name);\n }\n\n @Override\n public DiskStoreFactory createDiskStoreFactory() {\n return delegate.createDiskStoreFactory();\n }\n\n @Override\n public boolean getPdxReadSerialized() {\n return delegate.getPdxReadSerialized();\n }\n\n @Override\n public PdxSerializer getPdxSerializer() {\n return delegate.getPdxSerializer();\n }\n\n @Override\n public String getPdxDiskStore() {\n return delegate.getPdxDiskStore();\n }\n\n @Override\n public boolean getPdxPersistent() {\n return delegate.getPdxPersistent();\n }\n\n @Override\n public boolean getPdxIgnoreUnreadFields() {\n return delegate.getPdxIgnoreUnreadFields();\n }\n\n @Override\n public void registerPdxMetaData(Object instance) {\n delegate.registerPdxMetaData(instance);\n }\n\n @Override\n public CacheTransactionManager getCacheTransactionManager() {\n return delegate.getCacheTransactionManager();\n }\n\n @Override\n public Context getJNDIContext() {\n return delegate.getJNDIContext();\n }\n\n @Override\n public Declarable getInitializer() {\n return delegate.getInitializer();\n }\n\n @Override\n public Properties getInitializerProps() {\n return delegate.getInitializerProps();\n }\n\n @Override\n public CancelCriterion getCancelCriterion() {\n return delegate.getCancelCriterion();\n }\n\n @Override\n public PdxInstanceFactory createPdxInstanceFactory(String className) {\n return delegate.createPdxInstanceFactory(className);\n }\n\n @Override\n public PdxInstance createPdxEnum(String className, String enumName, int enumOrdinal) {\n return delegate.createPdxEnum(className, enumName, enumOrdinal);\n }\n\n @Override\n public void close() {\n delegate.close();\n }\n\n @Override\n public boolean isClosed() {\n return delegate.isClosed();\n }\n\n @Override\n public ExtensionPoint getExtensionPoint() {\n return delegate.getExtensionPoint();\n }\n\n @Override\n public InternalDistributedMember getMyId() {\n return delegate.getMyId();\n }\n\n @Override\n public Collection listDiskStores() {\n return delegate.listDiskStores();\n }\n\n @Override\n public Collection listDiskStoresIncludingRegionOwned() {\n return delegate.listDiskStoresIncludingRegionOwned();\n }\n\n @Override\n public CqService getCqService() {\n return delegate.getCqService();\n }\n\n @Override\n public T getService(Class clazz) {\n return delegate.getService(clazz);\n }\n\n @Override\n public Collection getServices() {\n return delegate.getServices();\n }\n\n @Override\n public SystemTimer getCCPTimer() {\n return delegate.getCCPTimer();\n }\n\n @Override\n public void cleanupForClient(CacheClientNotifier ccn, ClientProxyMembershipID client) {\n delegate.cleanupForClient(ccn, client);\n }\n\n @Override\n public void purgeCCPTimer() {\n delegate.purgeCCPTimer();\n }\n\n @Override\n public MemoryAllocator getOffHeapStore() {\n return delegate.getOffHeapStore();\n }\n\n @Override\n public DistributedLockService getPartitionedRegionLockService() {\n return delegate.getPartitionedRegionLockService();\n }\n\n @Override\n public PersistentMemberManager getPersistentMemberManager() {\n return delegate.getPersistentMemberManager();\n }\n\n @Override\n public Set getAllGatewaySenders() {\n return delegate.getAllGatewaySenders();\n }\n\n @Override\n public CachePerfStats getCachePerfStats() {\n return delegate.getCachePerfStats();\n }\n\n @Override\n public DistributionManager getDistributionManager() {\n return delegate.getDistributionManager();\n }\n\n @Override\n public void regionReinitialized(Region region) {\n delegate.regionReinitialized(region);\n }\n\n @Override\n public void setRegionByPath(String path, InternalRegion r) {\n delegate.setRegionByPath(path, r);\n }\n\n @Override\n public InternalResourceManager getInternalResourceManager() {\n return delegate.getInternalResourceManager();\n }\n\n @Override\n public ResourceAdvisor getResourceAdvisor() {\n return delegate.getResourceAdvisor();\n }\n\n @Override\n public boolean isCacheAtShutdownAll() {\n return delegate.isCacheAtShutdownAll();\n }\n\n @Override\n public boolean requiresNotificationFromPR(PartitionedRegion r) {\n return delegate.requiresNotificationFromPR(r);\n }\n\n @Override\n public RegionAttributes invokeRegionBefore(InternalRegion parent, String name,\n RegionAttributes attrs, InternalRegionArguments internalRegionArgs) {\n return delegate.invokeRegionBefore(parent, name, attrs, internalRegionArgs);\n }\n\n @Override\n public void invokeRegionAfter(InternalRegion region) {\n delegate.invokeRegionAfter(region);\n }\n\n @Override\n public void invokeBeforeDestroyed(InternalRegion region) {\n delegate.invokeBeforeDestroyed(region);\n }\n\n @Override\n public void invokeCleanupFailedInitialization(InternalRegion region) {\n delegate.invokeCleanupFailedInitialization(region);\n }\n\n @Override\n public TXManagerImpl getTXMgr() {\n return delegate.getTXMgr();\n }\n\n @Override\n public boolean forcedDisconnect() {\n return delegate.forcedDisconnect();\n }\n\n @Override\n public InternalResourceManager getInternalResourceManager(boolean checkCancellationInProgress) {\n return delegate.getInternalResourceManager();\n }\n\n @Override\n public boolean isCopyOnRead() {\n return delegate.isCopyOnRead();\n }\n\n @Override\n public TombstoneService getTombstoneService() {\n return delegate.getTombstoneService();\n }\n\n @Override\n public QueryService getLocalQueryService() {\n return delegate.getLocalQueryService();\n }\n\n @Override\n public void registerInterestStarted() {\n delegate.registerInterestStarted();\n }\n\n @Override\n public void registerInterestCompleted() {\n delegate.registerInterestCompleted();\n }\n\n @Override\n public void regionReinitializing(String fullPath) {\n delegate.regionReinitializing(fullPath);\n }\n\n @Override\n public void unregisterReinitializingRegion(String fullPath) {\n delegate.unregisterReinitializingRegion(fullPath);\n }\n\n @Override\n public boolean removeRoot(InternalRegion rootRgn) {\n return delegate.removeRoot(rootRgn);\n }\n\n @Override\n public Executor getEventThreadPool() {\n return delegate.getEventThreadPool();\n }\n\n @Override\n public boolean keepDurableSubscriptionsAlive() {\n return delegate.keepDurableSubscriptionsAlive();\n }\n\n @Override\n public CacheClosedException getCacheClosedException(String reason) {\n return delegate.getCacheClosedException(reason);\n }\n\n @Override\n public CacheClosedException getCacheClosedException(String reason, Throwable cause) {\n return delegate.getCacheClosedException(reason, cause);\n }\n\n @Override\n public TypeRegistry getPdxRegistry() {\n return delegate.getPdxRegistry();\n }\n\n @Override\n public DiskStoreImpl getOrCreateDefaultDiskStore() {\n return delegate.getOrCreateDefaultDiskStore();\n }\n\n @Override\n public ExpirationScheduler getExpirationScheduler() {\n return delegate.getExpirationScheduler();\n }\n\n @Override\n public TransactionManager getJTATransactionManager() {\n return delegate.getJTATransactionManager();\n }\n\n @Override\n public TXManagerImpl getTxManager() {\n return delegate.getTxManager();\n }\n\n @Override\n public void beginDestroy(String path, DistributedRegion region) {\n delegate.beginDestroy(path, region);\n }\n\n @Override\n public void endDestroy(String path, DistributedRegion region) {\n delegate.endDestroy(path, region);\n }\n\n @Override\n public ClientMetadataService getClientMetadataService() {\n return delegate.getClientMetadataService();\n }\n\n @Override\n public long cacheTimeMillis() {\n return delegate.cacheTimeMillis();\n }\n\n @Override\n public URL getCacheXmlURL() {\n return delegate.getCacheXmlURL();\n }\n\n @Override\n public List getBackupFiles() {\n return delegate.getBackupFiles();\n }\n\n @Override\n public boolean isClient() {\n return delegate.isClient();\n }\n\n @Override\n public InternalDistributedSystem getInternalDistributedSystem() {\n return delegate.getInternalDistributedSystem();\n }\n\n @Override\n public void addRegionListener(RegionListener regionListener) {\n delegate.addRegionListener(regionListener);\n }\n\n @Override\n public void removeRegionListener(RegionListener regionListener) {\n delegate.removeRegionListener(regionListener);\n }\n\n @Override\n public Set getRegionListeners() {\n return delegate.getRegionListeners();\n }\n\n @Override\n public CacheConfig getCacheConfig() {\n return delegate.getCacheConfig();\n }\n\n @Override\n public boolean getPdxReadSerializedByAnyGemFireServices() {\n return delegate.getPdxReadSerializedByAnyGemFireServices();\n }\n\n @Override\n public void setDeclarativeCacheConfig(CacheConfig cacheConfig) {\n delegate.setDeclarativeCacheConfig(cacheConfig);\n }\n\n @Override\n public void initializePdxRegistry() {\n delegate.initializePdxRegistry();\n }\n\n @Override\n public void readyDynamicRegionFactory() {\n delegate.readyDynamicRegionFactory();\n }\n\n @Override\n public void setBackupFiles(List backups) {\n delegate.setBackupFiles(backups);\n }\n\n @Override\n public void addDeclarableProperties(Map mapOfNewDeclarableProps) {\n delegate.addDeclarableProperties(mapOfNewDeclarableProps);\n }\n\n @Override\n public void setInitializer(Declarable initializer, Properties initializerProps) {\n delegate.setInitializer(initializer, initializerProps);\n }\n\n @Override\n public boolean hasPool() {\n return delegate.hasPool();\n }\n\n @Override\n public DiskStoreFactory createDiskStoreFactory(DiskStoreAttributes attrs) {\n return delegate.createDiskStoreFactory(attrs);\n }\n\n @Override\n public void determineDefaultPool() {\n delegate.determineDefaultPool();\n }\n\n @Override\n public BackupService getBackupService() {\n return delegate.getBackupService();\n }\n\n @Override\n public Throwable getDisconnectCause() {\n return delegate.getDisconnectCause();\n }\n\n @Override\n public void addPartitionedRegion(PartitionedRegion region) {\n delegate.addPartitionedRegion(region);\n }\n\n @Override\n public void removePartitionedRegion(PartitionedRegion region) {\n delegate.removePartitionedRegion(region);\n }\n\n @Override\n public void addDiskStore(DiskStoreImpl dsi) {\n delegate.addDiskStore(dsi);\n }\n\n @Override\n public TXEntryStateFactory getTXEntryStateFactory() {\n return delegate.getTXEntryStateFactory();\n }\n\n @Override\n public EventTrackerExpiryTask getEventTrackerTask() {\n return delegate.getEventTrackerTask();\n }\n\n @Override\n public void removeDiskStore(DiskStoreImpl diskStore) {\n delegate.removeDiskStore(diskStore);\n }\n\n @Override\n public void addGatewaySender(GatewaySender sender) {\n delegate.addGatewaySender(sender);\n }\n\n @Override\n public void addAsyncEventQueue(AsyncEventQueueImpl asyncQueue) {\n delegate.addAsyncEventQueue(asyncQueue);\n }\n\n @Override\n public void removeAsyncEventQueue(AsyncEventQueue asyncQueue) {\n delegate.removeAsyncEventQueue(asyncQueue);\n }\n\n @Override\n public QueryMonitor getQueryMonitor() {\n return delegate.getQueryMonitor();\n }\n\n @Override\n public void close(String reason, Throwable systemFailureCause, boolean keepAlive,\n boolean keepDS) {\n delegate.close(reason, systemFailureCause, keepAlive, keepDS);\n }\n\n @Override\n public JmxManagerAdvisor getJmxManagerAdvisor() {\n return delegate.getJmxManagerAdvisor();\n }\n\n @Override\n public List getDeclarableProperties(String className) {\n return delegate.getDeclarableProperties(className);\n }\n\n @Override\n public int getUpTime() {\n return delegate.getUpTime();\n }\n\n @Override\n public void addRegionOwnedDiskStore(DiskStoreImpl dsi) {\n delegate.addRegionOwnedDiskStore(dsi);\n }\n\n @Override\n public DiskStoreMonitor getDiskStoreMonitor() {\n return delegate.getDiskStoreMonitor();\n }\n\n @Override\n public void close(String reason, Throwable optionalCause) {\n delegate.close(reason, optionalCause);\n }\n\n @Override\n public List getCacheServersAndGatewayReceiver() {\n return delegate.getCacheServersAndGatewayReceiver();\n }\n\n @Override\n public boolean isGlobalRegionInitializing(String fullPath) {\n return delegate.isGlobalRegionInitializing(fullPath);\n }\n\n @Override\n public DistributionAdvisor getDistributionAdvisor() {\n return delegate.getDistributionAdvisor();\n }\n\n @Override\n public void setQueryMonitorRequiredForResourceManager(boolean required) {\n delegate.setQueryMonitorRequiredForResourceManager(required);\n }\n\n @Override\n public boolean isQueryMonitorDisabledForLowMemory() {\n return delegate.isQueryMonitorDisabledForLowMemory();\n }\n\n @Override\n public boolean isRESTServiceRunning() {\n return delegate.isRESTServiceRunning();\n }\n\n @Override\n public InternalLogWriter getInternalLogWriter() {\n return delegate.getInternalLogWriter();\n }\n\n @Override\n public InternalLogWriter getSecurityInternalLogWriter() {\n return delegate.getSecurityInternalLogWriter();\n }\n\n @Override\n public Set getApplicationRegions() {\n return delegate.getApplicationRegions();\n }\n\n @Override\n public void removeGatewaySender(GatewaySender sender) {\n delegate.removeGatewaySender(sender);\n }", "answers": [" @Override"], "length": 2242, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "26f30e68-c827-49a3-9818-e4383857830e", "reasoning": "The class continues implementing InternalCache methods. After the removeGatewaySender method, the next method typically starts with the @Override annotation for the following method (e.g., removeGatewayReceiver). Therefore, the immediate next line is the @Override annotation.", "reasoning_model_answer": "@Override", "assistant_with_reasoning": "\nThe class continues implementing InternalCache methods. After the removeGatewaySender method, the next method typically starts with the @Override annotation for the following method (e.g., removeGatewayReceiver). Therefore, the immediate next line is the @Override annotation.\n\n@Override", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 6.423, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 29686, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "@Override", "score": 0.9, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "\nfrom PyQt5.QtCore import *\nfrom PyQt5.QtGui import *\nfrom PyQt5.QtWidgets import *\nimport sys, struct, socket, time, os\n\nimport disassemble\n\n\nclass Message:\n DSI = 0\n ISI = 1\n Program = 2\n GetStat = 3\n OpenFile = 4\n ReadFile = 5\n CloseFile = 6\n SetPosFile = 7\n GetStatFile = 8\n\n Continue = 0\n Step = 1\n StepOver = 2\n\n def __init__(self, type, data, arg):\n self.type = type\n self.data = data\n self.arg = arg\n\n\nclass EventHolder(QObject):\n Exception = pyqtSignal()\n Connected = pyqtSignal()\n Closed = pyqtSignal()\n BreakPointChanged = pyqtSignal()\n Continue = pyqtSignal()\nevents = EventHolder()\n\n\n#I don't want to deal with the whole threading trouble to complete big\n#file transfers without the UI becoming unresponsive. There probably is\n#a better way to code this, but this is what I came up with.\nclass TaskMgr:\n def __init__(self):\n self.taskQueue = []\n\n def add(self, task):\n if not self.taskQueue:\n window.mainWidget.statusWidget.disconnectButton.setEnabled(True)\n self.taskQueue.append(task)\n\n def pop(self, task):\n assert task == self.taskQueue.pop()\n\n if not self.taskQueue:\n window.mainWidget.tabWidget.setEnabled(True)\n window.mainWidget.statusWidget.cancelButton.setEnabled(True)\n window.mainWidget.statusWidget.disconnectButton.setEnabled(True)\n window.mainWidget.statusWidget.progressBar.setValue(0)\n window.mainWidget.statusWidget.progressInfo.setText(\"Connected\")\n else:\n self.taskQueue[-1].resume()\n\n def isBlocking(self):\n if not self.taskQueue:\n return False\n return self.taskQueue[-1].blocking\n\n def cancel(self):\n self.taskQueue[-1].canceled = True\ntaskMgr = TaskMgr()\n\n\nclass Task:\n def __init__(self, blocking, cancelable):\n taskMgr.add(self)\n\n self.canceled = False\n self.blocking = blocking\n self.cancelable = cancelable\n window.mainWidget.tabWidget.setEnabled(not blocking)\n window.mainWidget.statusWidget.cancelButton.setEnabled(cancelable)\n\n def setInfo(self, info, maxValue):\n self.info = info\n self.maxValue = maxValue\n window.mainWidget.statusWidget.progressInfo.setText(info)\n window.mainWidget.statusWidget.progressBar.setRange(0, maxValue)\n\n def update(self, progress):\n self.progress = progress\n window.mainWidget.statusWidget.progressBar.setValue(progress)\n app.processEvents()\n\n def resume(self):\n window.mainWidget.tabWidget.setEnabled(not self.blocking)\n window.mainWidget.statusWidget.cancelButton.setEnabled(self.cancelable)\n window.mainWidget.statusWidget.progressInfo.setText(self.info)\n window.mainWidget.statusWidget.progressBar.setRange(0, self.maxValue)\n window.mainWidget.statusWidget.progressBar.setValue(self.progress)\n\n def end(self):\n taskMgr.pop(self)\n\n\nclass Thread:\n\n cores = {\n 1: \"Core 0\",\n 2: \"Core 1\",\n 4: \"Core 2\"\n }\n\n def __init__(self, data, offs=0):\n self.core = self.cores[struct.unpack_from(\">I\", data, offs)[0]]\n self.priority = struct.unpack_from(\">I\", data, offs + 4)[0]\n self.stackBase = struct.unpack_from(\">I\", data, offs + 8)[0]\n self.stackEnd = struct.unpack_from(\">I\", data, offs + 12)[0]\n self.entryPoint = struct.unpack_from(\">I\", data, offs + 16)[0]\n\n namelen = struct.unpack_from(\">I\", data, offs + 20)[0]\n self.name = data[offs + 24 : offs + 24 + namelen].decode(\"ascii\")\n\n\nclass DirEntry:\n def __init__(self, flags, size, name):\n self.flags = flags\n self.size = size\n self.name = name\n\n def isDir(self):\n return self.flags & 0x80000000\n\n\nclass PyBugger:\n def __init__(self):\n super().__init__()\n self.connected = False\n self.breakPoints = []\n\n self.basePath = b\"\"\n self.currentHandle = 0x12345678\n self.files = {}\n\n self.messageHandlers = {\n Message.DSI: self.handleException,\n Message.ISI: self.handleException,\n Message.Program: self.handleException,\n Message.GetStat: self.handleGetStat,\n Message.OpenFile: self.handleOpenFile,\n Message.ReadFile: self.handleReadFile,\n Message.CloseFile: self.handleCloseFile,\n Message.SetPosFile: self.handleSetPosFile,\n Message.GetStatFile: self.handleGetStatFile\n }\n\n def handleException(self, msg):\n exceptionState.load(msg.data, msg.type)\n events.Exception.emit()\n\n def handleGetStat(self, msg):\n gamePath = msg.data.decode(\"ascii\")\n path = os.path.join(self.basePath, gamePath.strip(\"/vol\"))\n print(\"GetStat: %s\" %gamePath)\n self.sendFileMessage(os.path.getsize(path))\n\n def handleOpenFile(self, msg):\n mode = struct.pack(\">I\", msg.arg).decode(\"ascii\").strip(\"\\x00\") + \"b\"\n path = msg.data.decode(\"ascii\")\n print(\"Open: %s\" %path)\n\n f = open(os.path.join(self.basePath, path.strip(\"/vol\")), mode)\n self.files[self.currentHandle] = f\n self.sendFileMessage(self.currentHandle)\n self.currentHandle += 1\n\n def handleReadFile(self, msg):\n print(\"Read\")\n task = Task(blocking=False, cancelable=False)\n bufferAddr, size, count, handle = struct.unpack(\">IIII\", msg.data)\n\n data = self.files[handle].read(size * count)\n task.setInfo(\"Sending file\", len(data))\n\n bytesSent = 0\n while bytesSent < len(data):\n length = min(len(data) - bytesSent, 0x8000)\n self.sendall(b\"\\x03\")\n self.sendall(struct.pack(\">II\", bufferAddr, length))\n self.sendall(data[bytesSent : bytesSent + length])\n bufferAddr += length\n bytesSent += length\n task.update(bytesSent)\n self.sendFileMessage(bytesSent // size)\n task.end()\n\n def handleCloseFile(self, msg):\n print(\"Close\")\n self.files.pop(msg.arg).close()\n self.sendFileMessage()\n\n def handleSetPosFile(self, msg):\n print(\"SetPos\")\n handle, pos = struct.unpack(\">II\", msg.data)\n self.files[handle].seek(pos)\n self.sendFileMessage()\n\n def handleGetStatFile(self, msg):\n print(\"GetStatFile\")\n f = self.files[msg.arg]\n pos = f.tell()\n f.seek(0, 2)\n size = f.tell()\n f.seek(pos)\n self.sendFileMessage(size)\n\n def connect(self, host):\n self.s = socket.socket()\n self.s.connect((host, 1559))\n self.connected = True\n self.closeRequest = False\n events.Connected.emit()\n\n def close(self):\n self.sendall(b\"\\x01\")\n self.s.close()\n self.connected = False\n self.breakPoints = []\n events.Closed.emit()\n\n def updateMessages(self):\n self.sendall(b\"\\x07\")\n count = struct.unpack(\">I\", self.recvall(4))[0]\n for i in range(count):\n type, ptr, length, arg = struct.unpack(\">IIII\", self.recvall(16))\n data = None\n if length:\n data = self.recvall(length)\n self.messageHandlers[type](Message(type, data, arg))\n\n def read(self, addr, num):\n self.sendall(b\"\\x02\")\n self.sendall(struct.pack(\">II\", addr, num))\n data = self.recvall(num)\n return data\n\n def write(self, addr, data):\n self.sendall(b\"\\x03\")\n self.sendall(struct.pack(\">II\", addr, len(data)))\n self.sendall(data)\n\n def writeCode(self, addr, instr):\n self.sendall(b\"\\x04\")\n self.sendall(struct.pack(\">II\", addr, instr))\n\n def getThreadList(self):\n self.sendall(b\"\\x05\")\n length = struct.unpack(\">I\", self.recvall(4))[0]\n data = self.recvall(length)\n\n offset = 0\n threads = []\n while offset < length:\n thread = Thread(data, offset)\n threads.append(thread)\n offset += 24 + len(thread.name)\n return threads\n\n def toggleBreakPoint(self, addr):\n if addr in self.breakPoints: self.breakPoints.remove(addr)\n else:\n if len(self.breakPoints) >= 10:\n return\n self.breakPoints.append(addr)\n\n self.sendall(b\"\\x0A\")\n self.sendall(struct.pack(\">I\", addr))\n events.BreakPointChanged.emit()\n\n def continueBreak(self): self.sendCrashMessage(Message.Continue)\n def stepBreak(self): self.sendCrashMessage(Message.Step)\n def stepOver(self): self.sendCrashMessage(Message.StepOver)\n\n def sendCrashMessage(self, message):\n self.sendMessage(message)\n events.Continue.emit()\n\n def sendMessage(self, message, data0=0, data1=0, data2=0):\n self.sendall(b\"\\x06\")\n self.sendall(struct.pack(\">IIII\", message, data0, data1, data2))\n\n def sendFileMessage(self, data0=0, data1=0, data2=0):\n self.sendall(b\"\\x0F\")\n self.sendall(struct.pack(\">IIII\", 0, data0, data1, data2))\n\n def getStackTrace(self):\n self.sendall(b\"\\x08\")\n count = struct.unpack(\">I\", self.recvall(4))[0]\n trace = struct.unpack(\">%iI\" %count, self.recvall(4 * count))\n return trace\n\n def pokeExceptionRegisters(self):\n self.sendall(b\"\\x09\")\n data = struct.pack(\">32I32d\", *exceptionState.gpr, *exceptionState.fpr)\n self.sendall(data)\n\n def readDirectory(self, path):\n self.sendall(b\"\\x0B\")\n self.sendall(struct.pack(\">I\", len(path)))\n self.sendall(path.encode(\"ascii\"))\n\n entries = []\n namelen = struct.unpack(\">I\", self.recvall(4))[0]\n while namelen != 0:\n flags = struct.unpack(\">I\", self.recvall(4))[0]\n\n size = -1\n if not flags & 0x80000000:\n size = struct.unpack(\">I\", self.recvall(4))[0]\n\n name = self.recvall(namelen).decode(\"ascii\")\n entries.append(DirEntry(flags, size, name))\n\n namelen = struct.unpack(\">I\", self.recvall(4))[0]\n return entries\n\n def dumpFile(self, gamePath, outPath, task):\n if task.canceled:\n return\n\n self.sendall(b\"\\x0C\")\n self.sendall(struct.pack(\">I\", len(gamePath)))\n self.sendall(gamePath.encode(\"ascii\"))\n\n length = struct.unpack(\">I\", self.recvall(4))[0]\n task.setInfo(\"Dumping %s\" %gamePath, length)\n\n with open(outPath, \"wb\") as f:\n bytesDumped = 0\n while bytesDumped < length:\n data = self.s.recv(length - bytesDumped)\n f.write(data)\n bytesDumped += len(data)\n task.update(bytesDumped)\n\n def getModuleName(self):\n self.sendall(b\"\\x0D\")\n length = struct.unpack(\">I\", self.recvall(4))[0]\n return self.recvall(length).decode(\"ascii\") + \".rpx\"\n\n def setPatchFiles(self, fileList, basePath):\n self.basePath = basePath\n self.sendall(b\"\\x0E\")\n\n fileBuffer = struct.pack(\">I\", len(fileList))\n for path in fileList:\n fileBuffer += struct.pack(\">H\", len(path))\n fileBuffer += path.encode(\"ascii\")\n\n self.sendall(struct.pack(\">I\", len(fileBuffer)))\n self.sendall(fileBuffer)\n\n def clearPatchFiles(self):\n self.sendall(b\"\\x10\")\n\n def sendall(self, data):\n try:\n self.s.sendall(data)\n except socket.error:\n self.connected = False\n events.Closed.emit()\n\n def recvall(self, num):\n try:\n data = b\"\"\n while len(data) < num:\n data += self.s.recv(num - len(data))\n except socket.error:\n self.connected = False\n events.Closed.emit()\n return b\"\\x00\" * num\n\n return data\n\n\nclass HexSpinBox(QAbstractSpinBox):\n def __init__(self, parent, stepSize = 1):\n super().__init__(parent)\n self._value = 0\n self.stepSize = stepSize\n\n def validate(self, text, pos):\n if all([char in \"0123456789abcdefABCDEF\" for char in text]):\n if not text:\n return QValidator.Intermediate, text.upper(), pos\n\n value = int(text, 16)\n if value <= 0xFFFFFFFF:\n self._value = value\n if value % self.stepSize:\n self._value -= value % self.stepSize\n return QValidator.Acceptable, text.upper(), pos\n return QValidator.Acceptable, text.upper(), pos\n\n return QValidator.Invalid, text.upper(), pos\n\n def stepBy(self, steps):\n self._value = min(max(self._value + steps * self.stepSize, 0), 0x100000000 - self.stepSize)\n self.lineEdit().setText(\"%X\" %self._value)\n\n def stepEnabled(self):\n return QAbstractSpinBox.StepUpEnabled | QAbstractSpinBox.StepDownEnabled\n\n def setValue(self, value):\n self._value = value\n self.lineEdit().setText(\"%X\" %self._value)\n\n def value(self):\n return self._value\n\n\nclass ExceptionState:\n\n exceptionNames = [\"DSI\", \"ISI\", \"Program\"]\n\n def load(self, context, type):\n #Convert tuple to list to make it mutable\n self.gpr = list(struct.unpack_from(\">32I\", context, 8))\n self.cr, self.lr, self.ctr, self.xer = struct.unpack_from(\">4I\", context, 0x88)\n self.srr0, self.srr1, self.ex0, self.ex1 = struct.unpack_from(\">4I\", context, 0x98)\n self.fpr = list(struct.unpack_from(\">32d\", context, 0xB8))\n self.gqr = list(struct.unpack_from(\">8I\", context, 0x1BC))\n self.psf = list(struct.unpack_from(\">32d\", context, 0x1E0))\n\n self.exceptionName = self.exceptionNames[type]\n\n def isBreakPoint(self):\n return self.exceptionName == \"Program\" and self.srr1 & 0x20000\n\n\ndef format_hex(blob, offs):\n return \"%02X\" %blob[offs]\n\ndef format_ascii(blob, offs):\n if 0x30 <= blob[offs] <= 0x39 or 0x41 <= blob[offs] <= 0x5A or 0x61 <= blob[offs] <= 0x7A:\n return chr(blob[offs])\n return \"?\"\n\ndef format_float(blob, offs):\n value = struct.unpack_from(\">f\", blob, offs)[0]\n if abs(value) >= 1000000 or 0 < abs(value) < 0.000001:\n return \"%e\" %value\n return (\"%.8f\" %value).rstrip(\"0\")\n\n\nclass MemoryViewer(QWidget):\n\n class Format:\n Hex = 0\n Ascii = 1\n Float = 2\n\n Width = 1, 1, 4\n Funcs = format_hex, format_ascii, format_float\n\n def __init__(self, parent):\n super().__init__(parent)\n\n self.layout = QGridLayout()\n\n for i in range(16):\n self.layout.addWidget(QLabel(\"%X\" %i, self), 0, i + 1)\n self.addrLabels = []\n for i in range(16):\n label = QLabel(\"%X\" %(i * 0x10), self)\n self.layout.addWidget(label, i + 1, 0)\n self.addrLabels.append(label)\n self.dataCells = []\n\n self.base = 0\n self.format = self.Format.Hex\n self.updateData()\n\n self.setLayout(self.layout)\n\n events.Connected.connect(self.connected)\n\n def connected(self):\n self.setBase(0x10000000)\n\n def setFormat(self, format):\n self.format = format\n self.updateData()\n\n def setBase(self, base):\n window.mainWidget.tabWidget.memoryTab.memoryInfo.baseBox.setValue(base)\n self.base = base\n for i in range(16):\n self.addrLabels[i].setText(\"%X\" %(self.base + i * 0x10))\n self.updateData()\n\n def updateData(self):\n for cell in self.dataCells:\n self.layout.removeWidget(cell)\n cell.setParent(None)\n\n if bugger.connected:\n blob = bugger.read(self.base, 0x100)\n else:\n blob = b\"\\x00\" * 0x100\n\n width = self.Width[self.format]\n func = self.Funcs[self.format]\n for i in range(16 // width):\n for j in range(16):\n label = QLabel(func(blob, j * 0x10 + i * width), self)\n self.layout.addWidget(label, j + 1, i * width + 1, 1, width)\n self.dataCells.append(label)\n\n\nclass MemoryInfo(QWidget):\n def __init__(self, parent):\n super().__init__(parent)\n self.dataTypeLabel = QLabel(\"Data type:\")\n self.dataTypeBox = QComboBox(self)\n self.dataTypeBox.addItems([\"Hex\", \"Ascii\", \"Float\"])\n self.dataTypeBox.currentIndexChanged.connect(self.updateDataType)\n\n self.baseLabel = QLabel(\"Address:\")\n self.baseBox = HexSpinBox(self, 0x10)\n self.baseButton = QPushButton(\"Update\", self)\n self.baseButton.clicked.connect(self.updateMemoryBase)\n\n self.pokeAddr = HexSpinBox(self, 4)\n self.pokeValue = HexSpinBox(self)\n self.pokeButton = QPushButton(\"Poke\", self)\n self.pokeButton.clicked.connect(self.pokeMemory)\n\n self.layout = QGridLayout()\n self.layout.addWidget(self.baseLabel, 0, 0)\n self.layout.addWidget(self.baseBox, 0, 1)\n self.layout.addWidget(self.baseButton, 0, 2)\n self.layout.addWidget(self.pokeAddr, 1, 0)\n self.layout.addWidget(self.pokeValue, 1, 1)\n self.layout.addWidget(self.pokeButton, 1, 2)\n self.layout.addWidget(self.dataTypeLabel, 2, 0)\n self.layout.addWidget(self.dataTypeBox, 2, 1, 1, 2)\n self.setLayout(self.layout)\n\n def updateDataType(self, index):\n window.mainWidget.tabWidget.memoryTab.memoryViewer.setFormat(index)\n\n def updateMemoryBase(self):\n window.mainWidget.tabWidget.memoryTab.memoryViewer.setBase(self.baseBox.value())\n\n def pokeMemory(self):\n bugger.write(self.pokeAddr.value(), struct.pack(\">I\", self.pokeValue.value()))\n window.mainWidget.tabWidget.memoryTab.memoryViewer.updateData()\n\n\nclass MemoryTab(QWidget):\n def __init__(self, parent):\n super().__init__(parent)\n self.memoryInfo = MemoryInfo(self)\n self.memoryViewer = MemoryViewer(self)\n self.layout = QHBoxLayout()\n self.layout.addWidget(self.memoryInfo)\n self.layout.addWidget(self.memoryViewer)\n self.button = QPushButton(\"Dump\", self)\n self.button.clicked.connect(self.dump)\n self.setLayout(self.layout)\n\n def dump(self):\n dumpStart = 0x1AB00000\n dumpLength = 0x600000\n dumpFile = \"dump.bin\"\n with open(dumpFile, 'wb') as f:\n f.write(bugger.read(dumpStart, dumpLength))\n\nclass DisassemblyWidget(QTextEdit):\n def __init__(self, parent):\n super().__init__(parent)\n self.setTextInteractionFlags(Qt.NoTextInteraction)\n\n self.currentInstruction = None\n self.selectedAddress = 0\n self.setBase(0)\n\n events.BreakPointChanged.connect(self.updateHighlight)\n events.Continue.connect(self.handleContinue)\n\n def handleContinue(self):\n self.currentInstruction = None\n self.updateHighlight()\n\n def setCurrentInstruction(self, instr):\n self.currentInstruction = instr\n self.setBase(instr - 0x20)\n\n def setBase(self, base):\n self.base = base\n self.updateText()\n self.updateHighlight()\n\n def updateText(self):\n if bugger.connected:\n blob = bugger.read(self.base, 0x60)\n else:\n blob = b\"\\x00\" * 0x60\n\n text = \"\"\n for i in range(24):\n address = self.base + i * 4\n value = struct.unpack_from(\">I\", blob, i * 4)[0]\n instr = disassemble.disassemble(value, address)\n text += \"%08X: %08X %s\\n\" %(address, value, instr)\n self.setPlainText(text)\n\n def updateHighlight(self):\n selections = []\n for i in range(24):\n address = self.base + i * 4\n\n color = self.getColor(address)\n if color:\n cursor = self.textCursor()\n cursor.movePosition(QTextCursor.Down, n=i)\n cursor.select(QTextCursor.LineUnderCursor)\n format = QTextCharFormat()\n format.setBackground(QBrush(QColor(color)))\n selection = QTextEdit.ExtraSelection()\n selection.cursor = cursor\n selection.format = format\n selections.append(selection)\n self.setExtraSelections(selections)\n\n def getColor(self, addr):\n colors = []\n if addr in bugger.breakPoints:\n colors.append((255, 0, 0))\n if addr == self.currentInstruction:\n colors.append((0, 255, 0))\n if addr == self.selectedAddress:\n colors.append((0, 0, 255))\n\n if not colors:\n return None\n\n color = [sum(l)//len(colors) for l in zip(*colors)]\n return \"#%02X%02X%02X\" %tuple(color)\n\n def mousePressEvent(self, e):\n super().mousePressEvent(e)\n line = self.cursorForPosition(e.pos()).blockNumber()\n self.selectedAddress = self.base + line * 4\n if e.button() == Qt.MidButton:\n bugger.toggleBreakPoint(self.selectedAddress)\n self.updateHighlight()\n\n\nclass DisassemblyInfo(QWidget):\n def __init__(self, parent):\n super().__init__(parent)\n self.baseLabel = QLabel(\"Address:\")\n self.baseBox = HexSpinBox(self, 4)\n self.baseButton = QPushButton(\"Update\", self)\n self.baseButton.clicked.connect(self.updateDisassemblyBase)\n\n self.pokeBox = HexSpinBox(self)\n self.pokeButton = QPushButton(\"Poke\", self)\n self.pokeButton.clicked.connect(self.poke)\n\n self.layout = QGridLayout()\n self.layout.addWidget(self.baseLabel, 0, 0)\n self.layout.addWidget(self.baseBox, 0, 1)\n self.layout.addWidget(self.baseButton, 0, 2)\n self.layout.addWidget(self.pokeBox, 1, 0)\n self.layout.addWidget(self.pokeButton, 1, 1, 1, 2)\n self.setLayout(self.layout)\n self.setMinimumWidth(300)\n\n def updateDisassemblyBase(self):\n window.mainWidget.tabWidget.disassemblyTab.disassemblyWidget.setBase(self.baseBox.value())\n\n def poke(self):\n disassembly = window.mainWidget.tabWidget.disassemblyTab.disassemblyWidget\n if disassembly.selectedAddress:\n bugger.writeCode(disassembly.selectedAddress, self.pokeBox.value())\n disassembly.updateText()\n\n\nclass DisassemblyTab(QWidget):\n def __init__(self, parent):\n super().__init__(parent)\n self.disassemblyInfo = DisassemblyInfo(self)\n self.disassemblyWidget = DisassemblyWidget(self)\n self.layout = QHBoxLayout()\n self.layout.addWidget(self.disassemblyInfo)\n self.layout.addWidget(self.disassemblyWidget)\n self.setLayout(self.layout)\n\n events.Connected.connect(self.connected)\n\n def connected(self):\n self.disassemblyWidget.setBase(0x10000000)\n\n\nclass ThreadList(QTableWidget):\n def __init__(self, parent):\n super().__init__(0, 5, parent)\n self.setHorizontalHeaderLabels([\"Name\", \"Priority\", \"Core\", \"Stack\", \"Entry Point\"])\n self.setEditTriggers(self.NoEditTriggers)\n self.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)\n\n events.Connected.connect(self.updateThreads)\n\n def updateThreads(self):\n threads = bugger.getThreadList()\n self.setRowCount(len(threads))\n for i in range(len(threads)):\n thread = threads[i]\n self.setItem(i, 0, QTableWidgetItem(thread.name))\n self.setItem(i, 1, QTableWidgetItem(str(thread.priority)))\n self.setItem(i, 2, QTableWidgetItem(thread.core))\n self.setItem(i, 3, QTableWidgetItem(\"0x%x - 0x%x\" %(thread.stackEnd, thread.stackBase)))\n self.setItem(i, 4, QTableWidgetItem(hex(thread.entryPoint)))\n\n\nclass ThreadingTab(QTableWidget):\n def __init__(self, parent):\n super().__init__(parent)\n self.threadList = ThreadList(self)\n self.updateButton = QPushButton(\"Update\", self)\n self.updateButton.clicked.connect(self.threadList.updateThreads)\n self.layout = QVBoxLayout()\n self.layout.addWidget(self.threadList)\n self.layout.addWidget(self.updateButton)\n self.setLayout(self.layout)\n\n\nclass BreakPointList(QListWidget):\n def __init__(self, parent):\n super().__init__(parent)\n self.itemDoubleClicked.connect(self.goToDisassembly)\n events.BreakPointChanged.connect(self.updateList)\n\n def updateList(self):\n self.clear()\n for bp in bugger.breakPoints:\n self.addItem(\"0x%08X\" %bp)\n\n def goToDisassembly(self, item):\n address = bugger.breakPoints[self.row(item)]\n window.mainWidget.tabWidget.disassemblyTab.disassemblyWidget.setBase(address)\n window.mainWidget.tabWidget.setCurrentIndex(1)\n\n\nclass BreakPointTab(QWidget):\n def __init__(self, parent):\n super().__init__(parent)\n self.list = BreakPointList(self)\n self.button = QPushButton(\"Remove\", self)\n self.button.clicked.connect(self.removeBreakPoint)\n self.layout = QVBoxLayout()\n self.layout.addWidget(self.list)\n self.layout.addWidget(self.button)\n self.setLayout(self.layout)\n\n def removeBreakPoint(self):\n if self.list.currentRow() != -1:\n bugger.toggleBreakPoint(bugger.breakPoints[self.list.currentRow()])\n\n\nclass RegisterTab(QWidget):\n def __init__(self, parent):\n super().__init__(parent)\n self.gprLabels = []\n self.gprBoxes = []\n self.fprLabels = []\n self.fprBoxes = []\n for i in range(32):\n self.gprLabels.append(QLabel(\"r%i\" %i, self))\n self.fprLabels.append(QLabel(\"f%i\" % i, self))\n gprBox = HexSpinBox(self)\n fprBox = QDoubleSpinBox(self)\n fprBox.setRange(float(\"-inf\"), float(\"inf\"))\n self.gprBoxes.append(gprBox)\n self.fprBoxes.append(fprBox)\n\n self.layout = QGridLayout()\n for i in range(32):\n self.layout.addWidget(self.gprLabels[i], i % 16, i // 16 * 2)\n self.layout.addWidget(self.gprBoxes[i], i % 16, i // 16 * 2 + 1)\n self.layout.addWidget(self.fprLabels[i], i % 16, i // 16 * 2 + 4)\n self.layout.addWidget(self.fprBoxes[i], i % 16, i // 16 * 2 + 5)\n self.setLayout(self.layout)\n\n self.pokeButton = QPushButton(\"Poke\", self)\n self.resetButton = QPushButton(\"Reset\", self)\n self.pokeButton.clicked.connect(self.pokeRegisters)\n self.resetButton.clicked.connect(self.updateRegisters)\n self.layout.addWidget(self.pokeButton, 16, 0, 1, 4)\n self.layout.addWidget(self.resetButton, 16, 4, 1, 4)\n\n self.setEditEnabled(False)\n\n events.Exception.connect(self.exceptionOccurred)\n events.Continue.connect(lambda: self.setEditEnabled(False))\n\n def setEditEnabled(self, enabled):\n for i in range(32):\n self.gprBoxes[i].setEnabled(enabled)\n self.fprBoxes[i].setEnabled(enabled)\n self.pokeButton.setEnabled(enabled)\n self.resetButton.setEnabled(enabled)\n\n def exceptionOccurred(self):\n self.updateRegisters()\n self.setEditEnabled(exceptionState.isBreakPoint())\n\n def updateRegisters(self):\n for i in range(32):\n self.gprBoxes[i].setValue(exceptionState.gpr[i])\n self.fprBoxes[i].setValue(exceptionState.fpr[i])\n\n def pokeRegisters(self):\n for i in range(32):\n exceptionState.gpr[i] = self.gprBoxes[i].value()\n exceptionState.fpr[i] = self.fprBoxes[i].value()\n bugger.pokeExceptionRegisters()\n\n\nclass ExceptionInfo(QGroupBox):\n def __init__(self, parent):\n super().__init__(\"Info\", parent)\n self.typeLabel = QLabel(self)\n self.layout = QVBoxLayout()\n self.layout.addWidget(self.typeLabel)\n self.setLayout(self.layout)\n\n events.Exception.connect(self.updateInfo)\n\n def updateInfo(self):\n self.typeLabel.setText(\"Type: %s\" %exceptionState.exceptionName)\n\n\nclass SpecialRegisters(QGroupBox):\n def __init__(self, parent):\n super().__init__(\"Special registers\", parent)\n self.cr = QLabel(self)\n self.lr = QLabel(self)\n self.ctr = QLabel(self)\n self.xer = QLabel(self)\n self.srr0 = QLabel(self)\n self.srr1 = QLabel(self)\n self.ex0 = QLabel(self)\n self.ex1 = QLabel(self)\n\n self.layout = QHBoxLayout()\n self.userLayout = QFormLayout()\n self.kernelLayout = QFormLayout()\n\n self.userLayout.addRow(\"CR:\", self.cr)\n self.userLayout.addRow(\"LR:\", self.lr)\n self.userLayout.addRow(\"CTR:\", self.ctr)\n self.userLayout.addRow(\"XER:\", self.xer)\n\n self.kernelLayout = QFormLayout()\n self.kernelLayout.addRow(\"SRR0:\", self.srr0)\n self.kernelLayout.addRow(\"SRR1:\", self.srr1)\n self.kernelLayout.addRow(\"EX0:\", self.ex0)\n self.kernelLayout.addRow(\"EX1:\", self.ex1)\n\n self.layout.addLayout(self.userLayout)\n self.layout.addLayout(self.kernelLayout)\n self.setLayout(self.layout)\n\n events.Exception.connect(self.updateRegisters)\n\n def updateRegisters(self):\n self.cr.setText(\"%X\" %exceptionState.cr)\n self.lr.setText(\"%X\" %exceptionState.lr)\n self.ctr.setText(\"%X\" %exceptionState.ctr)\n self.xer.setText(\"%X\" %exceptionState.xer)\n self.srr0.setText(\"%X\" %exceptionState.srr0)\n self.srr1.setText(\"%X\" %exceptionState.srr1)\n self.ex0.setText(\"%X\" %exceptionState.ex0)\n self.ex1.setText(\"%X\" %exceptionState.ex1)\n\n\nclass ExceptionInfoTab(QWidget):\n def __init__(self, parent):\n super().__init__(parent)\n self.exceptionInfo = ExceptionInfo(self)\n self.specialRegisters = SpecialRegisters(self)\n self.layout = QGridLayout()\n self.layout.addWidget(self.exceptionInfo, 0, 0)\n self.layout.addWidget(self.specialRegisters, 0, 1)\n self.setLayout(self.layout)\n\n\nclass StackTrace(QListWidget):\n def __init__(self, parent):\n super().__init__(parent)\n events.Exception.connect(self.updateTrace)\n\n def updateTrace(self):\n self.clear()\n stackTrace = bugger.getStackTrace()\n for address in (exceptionState.srr0, exceptionState.lr) + stackTrace:\n self.addItem(\"%X\" %address)\n\n\nclass BreakPointActions(QWidget):\n def __init__(self, parent):\n super().__init__(parent)\n self.continueButton = QPushButton(\"Continue\", self)\n self.stepButton = QPushButton(\"Step\", self)\n self.stepOverButton = QPushButton(\"Step over\", self)\n self.continueButton.clicked.connect(bugger.continueBreak)\n self.stepButton.clicked.connect(bugger.stepBreak)\n self.stepOverButton.clicked.connect(bugger.stepOver)\n\n self.layout = QHBoxLayout()\n self.layout.addWidget(self.continueButton)\n self.layout.addWidget(self.stepButton)\n self.layout.addWidget(self.stepOverButton)\n self.setLayout(self.layout)\n\n events.Exception.connect(self.updateButtons)\n events.Continue.connect(self.disableButtons)\n\n def disableButtons(self):\n self.setButtonsEnabled(False)\n\n def updateButtons(self):\n self.setButtonsEnabled(exceptionState.isBreakPoint())\n\n def setButtonsEnabled(self, enabled):\n self.continueButton.setEnabled(enabled)\n self.stepButton.setEnabled(enabled)\n self.stepOverButton.setEnabled(enabled)\n\n\nclass StackTraceTab(QWidget):\n def __init__(self, parent):\n super().__init__(parent)\n self.stackTrace = StackTrace(self)\n self.disassembly = DisassemblyWidget(self)\n self.breakPointActions = BreakPointActions(self)\n self.layout = QVBoxLayout()\n hlayout = QHBoxLayout()\n hlayout.addWidget(self.stackTrace)\n hlayout.addWidget(self.disassembly)\n self.layout.addLayout(hlayout)\n self.layout.addWidget(self.breakPointActions)\n self.setLayout(self.layout)\n\n self.stackTrace.itemDoubleClicked.connect(self.jumpDisassembly)\n events.Exception.connect(self.exceptionOccurred)\n\n def exceptionOccurred(self):\n self.disassembly.setCurrentInstruction(exceptionState.srr0)\n\n def jumpDisassembly(self, item):\n self.disassembly.setBase(int(item.text(), 16) - 0x20)\n\n\nclass ExceptionTab(QTabWidget):\n def __init__(self, parent):\n super().__init__(parent)\n self.infoTab = ExceptionInfoTab(self)\n self.registerTab = RegisterTab(self)\n self.stackTab = StackTraceTab(self)\n self.addTab(self.infoTab, \"General\")\n self.addTab(self.registerTab, \"Registers\")\n self.addTab(self.stackTab, \"Stack trace\")\n\n events.Exception.connect(self.exceptionOccurred)\n\n def exceptionOccurred(self):\n self.setCurrentIndex(2) #Stack trace\n\n\ndef formatFileSize(size):\n if size >= 1024 ** 3:\n return \"%.1f GiB\" %(size / (1024 ** 3))\n if size >= 1024 ** 2:\n return \"%.1f MiB\" %(size / (1024 ** 2))\n if size >= 1024:\n return \"%.1f KiB\" %(size / 1024)\n return \"%i B\" %size\n\nclass FileTreeNode(QTreeWidgetItem):\n def __init__(self, parent, name, size, path):\n super().__init__(parent)\n self.name = name\n self.size = size\n self.path = path\n\n self.setText(0, name)\n if size == -1: #It's a folder\n self.loaded = False\n else: #It's a file\n self.setText(1, formatFileSize(size))\n self.loaded = True\n\n def loadChildren(self):\n if not self.loaded:\n for i in range(self.childCount()):\n child = self.child(i)\n if not child.loaded:\n self.child(i).loadContent()\n self.loaded = True\n\n def loadContent(self):\n entries = bugger.readDirectory(self.path)\n for entry in entries:\n FileTreeNode(self, entry.name, entry.size, self.path + \"/\" + entry.name)\n\n def dump(self, outdir, task):\n if task.canceled:\n return\n\n outpath = os.path.join(outdir, self.name)\n if self.size == -1:\n if os.path.isfile(outpath):\n os.remove(outpath)\n if not os.path.exists(outpath):\n os.mkdir(outpath)\n\n self.loadChildren()\n for i in range(self.childCount()):\n self.child(i).dump(outpath, task)\n else:\n bugger.dumpFile(self.path, outpath, task)\n\n\nclass FileTreeWidget(QTreeWidget):\n def __init__(self, parent):\n super().__init__(parent)\n self.setHeaderLabels([\"Name\", \"Size\"])\n self.itemExpanded.connect(self.handleItemExpanded)\n events.Connected.connect(self.initFileTree)\n\n def initFileTree(self):\n self.clear()\n rootItem = FileTreeNode(self, \"content\", -1, \"/vol/content\")\n rootItem.loadContent()\n self.resizeColumnToContents(0)\n\n def handleItemExpanded(self, item):\n item.loadChildren()\n self.resizeColumnToContents(0)\n\n\nclass FileSystemTab(QWidget):\n def __init__(self, parent):\n super().__init__(parent)\n self.fileTree = FileTreeWidget(self)\n self.dumpButton = QPushButton(\"Dump\", self)\n self.dumpButton.clicked.connect(self.dump)\n self.patchButton = QPushButton(\"Load patch\", self)\n self.patchButton.clicked.connect(self.loadPatch)\n self.clearButton = QPushButton(\"Clear patch\", self)\n self.clearButton.clicked.connect(self.clearPatch)\n self.clearButton.setEnabled(True)\n\n self.layout = QVBoxLayout()\n hlayout = QHBoxLayout()\n hlayout.addWidget(self.dumpButton)\n hlayout.addWidget(self.patchButton)\n hlayout.addWidget(self.clearButton)\n self.layout.addWidget(self.fileTree)", "answers": [" self.layout.addLayout(hlayout)"], "length": 2394, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "8083ff3c-6696-450a-988e-f06912830186", "reasoning": "In the FileSystemTab __init__, after creating a vertical layout and adding the file tree widget, the code builds a horizontal layout (hlayout) containing the dump, patch, and clear buttons. The next logical step is to add this horizontal layout to the main vertical layout before setting the layout on the widget. Therefore, the next line should add hlayout to self.layout.", "reasoning_model_answer": "self.layout.addLayout(hlayout)", "assistant_with_reasoning": "\nIn the FileSystemTab __init__, after creating a vertical layout and adding the file tree widget, the code builds a horizontal layout (hlayout) containing the dump, patch, and clear buttons. The next logical step is to add this horizontal layout to the main vertical layout before setting the layout on the widget. Therefore, the next line should add hlayout to self.layout.\n\nself.layout.addLayout(hlayout)", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 6.127, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 35743, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "self.layout.addLayout(hlayout)", "score": 0.88, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "from __future__ import division\nfrom functools import wraps\nimport pandas as pd\nfrom base.uber_model import UberModel, ModelSharedInputs\nfrom .trex_functions import TrexFunctions\nimport time\n\n\ndef timefn(fn):\n @wraps(fn)\n def measure_time(*args, **kwargs):\n t1 = time.time()\n result = fn(*args, **kwargs)\n t2 = time.time()\n print(\"trex_model_rest.py@timefn: \" + fn.func_name + \" took \" + \"{:.6f}\".format(t2 - t1) + \" seconds\")\n return result\n return measure_time\n\n\nclass TrexInputs(ModelSharedInputs):\n \"\"\"\n Required inputs class for Trex.\n \"\"\"\n\n def __init__(self):\n \"\"\"Class representing the inputs for Trex\"\"\"\n super(TrexInputs, self).__init__()\n # Inputs: Assign object attribute variables from the input Pandas DataFrame\n self.use = pd.Series([], dtype=\"object\")\n self.formu_name = pd.Series([], dtype=\"object\")\n self.percent_act_ing = pd.Series([], dtype=\"float\")\n self.application_type = pd.Series([], dtype=\"object\")\n self.seed_treatment_formulation_name = pd.Series([], dtype=\"object\")\n self.seed_crop = pd.Series([], dtype=\"object\")\n self.max_seed_rate = pd.Series([], dtype=\"float\") # maximum seeding rate per use\n # ??what is the seed_crop_v,\n # not listed in the crosswalk table, not referenced in code\n #self.seed_crop_v = pd.Series([], dtype=\"float\")\n self.row_spacing = pd.Series([], dtype=\"float\")\n self.bandwidth = pd.Series([], dtype=\"float\")\n self.percent_incorp = pd.Series([], dtype=\"float\")\n self.density = pd.Series([], dtype=\"float\")\n self.foliar_diss_hlife = pd.Series([], dtype=\"float\")\n self.num_apps = pd.Series([], dtype=\"int\") # number of applications per model simulation run\n # could calculate self.num_apps = len(self.app_rates) # should at least check if user supplied value is consistent\n self.app_rates = pd.Series([], dtype=\"object\") #Series of lists, each list contains app_rates of a model simulation run\n self.day_out = pd.Series([], dtype=\"object\") #Series of lists, each list contains day #'s of applications within a model simulaiton run\n self.mineau_sca_fact = pd.Series([], dtype=\"float\")\n\n self.ld50_bird = pd.Series([], dtype=\"float\")\n self.lc50_bird = pd.Series([], dtype=\"float\")\n self.noaec_bird = pd.Series([], dtype=\"float\")\n self.noael_bird = pd.Series([], dtype=\"float\")\n self.aw_bird_sm = pd.Series([], dtype=\"float\") # body weight of assessed bird (small)\n self.aw_bird_md = pd.Series([], dtype=\"float\") # body weight of assessed bird (medium)\n self.aw_bird_lg = pd.Series([], dtype=\"float\") # body weight of assessed bird (large)\n self.tw_bird_ld50 = pd.Series([], dtype=\"float\")\n self.tw_bird_lc50 = pd.Series([], dtype=\"float\")\n self.tw_bird_noaec = pd.Series([], dtype=\"float\")\n self.tw_bird_noael = pd.Series([], dtype=\"float\")\n\n self.species_of_the_tested_bird_avian_ld50 = pd.Series([], dtype=\"object\")\n self.species_of_the_tested_bird_avian_lc50 = pd.Series([], dtype=\"object\")\n self.species_of_the_tested_bird_avian_noaec = pd.Series([], dtype=\"object\")\n self.species_of_the_tested_bird_avian_noael = pd.Series([], dtype=\"object\")\n\n self.ld50_mamm = pd.Series([], dtype=\"float\")\n self.lc50_mamm = pd.Series([], dtype=\"float\")\n self.noaec_mamm = pd.Series([], dtype=\"float\")\n self.noael_mamm = pd.Series([], dtype=\"float\")\n self.aw_mamm_sm = pd.Series([], dtype=\"float\") # body weight of assessed mammal (small)\n self.aw_mamm_md = pd.Series([], dtype=\"float\") # body weight of assessed mammal (medium)\n self.aw_mamm_lg = pd.Series([], dtype=\"float\") # body weight of assessed mammal (large)\n self.tw_mamm = pd.Series([], dtype=\"float\") # body weight of tested mammal\n\n\nclass TrexOutputs(object):\n \"\"\"\n Output class for Trex.\n \"\"\"\n\n def __init__(self):\n \"\"\"Class representing the outputs for Trex\"\"\"\n super(TrexOutputs, self).__init__()\n\n # ??do the following 15 variables need to be included in the crosswalk table\n # initial concentrations for different food types\n self.out_c_0_sg = pd.Series([], dtype='float', name=\"out_c_0_sg\") # short grass\n self.out_c_0_tg = pd.Series([], dtype='float', name=\"out_c_0_tg\") # tall grass\n self.out_c_0_blp = pd.Series([], dtype='float', name=\"out_c_0_blp\") # broad-leafed plants\n self.out_c_0_fp = pd.Series([], dtype='float', name=\"out_c_0_fp\") # fruits/pods\n self.out_c_0_arthro = pd.Series([], dtype='float', name=\"out_c_0_arthro\") # arthropods\n\n # mean concentration estimate based on first application rate\n self.out_c_mean_sg = pd.Series([], dtype='float', name=\"out_c_mean_sg\") # short grass\n self.out_c_mean_tg = pd.Series([], dtype='float', name=\"out_c_mean_tg\") # tall grass\n self.out_c_mean_blp = pd.Series([], dtype='float', name=\"out_c_mean_blp\") # broad-leafed plants\n self.out_c_mean_fp = pd.Series([], dtype='float', name=\"out_c_mean_fp\") # fruits/pods\n self.out_c_mean_arthro = pd.Series([], dtype='float', name=\"out_c_mean_arthro\") # arthropods\n\n # TODO: Add these back in after deciding how to handle the numpy arrays\n # time series of concentrations per food source\n # self.out_c_ts_sg = pd.Series([], dtype='float', name=\"out_c_ts_sg\") # short grass\n # self.out_c_ts_tg = pd.Series([], dtype='float', name=\"out_c_ts_tg\") # tall grass\n # self.out_c_ts_blp = pd.Series([], dtype='float', name=\"out_c_ts_blp\") # broad-leafed plants\n # self.out_c_ts_fp = pd.Series([], dtype='float', name=\"out_c_ts_fp\") # fruits/pods\n # self.out_c_ts_arthro = pd.Series([], dtype='float', name=\"out_c_ts_arthro\") # arthropods\n\n # Table5\n self.out_sa_bird_1_s = pd.Series([], dtype='float', name=\"out_sa_bird_1_s\")\n self.out_sa_bird_2_s = pd.Series([], dtype='float', name=\"out_sa_bird_2_s\")\n self.out_sc_bird_s = pd.Series([], dtype='float', name=\"out_sc_bird_s\")\n self.out_sa_mamm_1_s = pd.Series([], dtype='float', name=\"out_sa_mamm_1_s\")\n self.out_sa_mamm_2_s = pd.Series([], dtype='float', name=\"out_sa_mamm_2_s\")\n self.out_sc_mamm_s = pd.Series([], dtype='float', name=\"out_sc_mamm_s\")\n\n self.out_sa_bird_1_m = pd.Series([], dtype='float', name=\"out_sa_bird_1_m\")\n self.out_sa_bird_2_m = pd.Series([], dtype='float', name=\"out_sa_bird_2_m\")\n self.out_sc_bird_m = pd.Series([], dtype='float', name=\"out_sc_bird_m\")\n self.out_sa_mamm_1_m = pd.Series([], dtype='float', name=\"out_sa_mamm_1_m\")\n self.out_sa_mamm_2_m = pd.Series([], dtype='float', name=\"out_sa_mamm_2_m\")\n self.out_sc_mamm_m = pd.Series([], dtype='float', name=\"out_sc_mamm_m\")\n\n self.out_sa_bird_1_l = pd.Series([], dtype='float', name=\"out_sa_bird_1_l\")\n self.out_sa_bird_2_l = pd.Series([], dtype='float', name=\"out_sa_bird_2_l\")\n self.out_sc_bird_l = pd.Series([], dtype='float', name=\"out_sc_bird_l\")\n self.out_sa_mamm_1_l = pd.Series([], dtype='float', name=\"out_sa_mamm_1_l\")\n self.out_sa_mamm_2_l = pd.Series([], dtype='float', name=\"out_sa_mamm_2_l\")\n self.out_sc_mamm_l = pd.Series([], dtype='float', name=\"out_sc_mamm_l\")\n\n # Table 6\n self.out_eec_diet_sg = pd.Series([], dtype='float', name=\"out_eec_diet_sg\")\n self.out_eec_diet_tg = pd.Series([], dtype='float', name=\"out_eec_diet_tg\")\n self.out_eec_diet_bp = pd.Series([], dtype='float', name=\"out_eec_diet_bp\")\n self.out_eec_diet_fr = pd.Series([], dtype='float', name=\"out_eec_diet_fr\")\n self.out_eec_diet_ar = pd.Series([], dtype='float', name=\"out_eec_diet_ar\")\n\n # Table 7\n self.out_eec_dose_bird_sg_sm = pd.Series([], dtype='float', name=\"out_eec_dose_bird_sg_sm\")\n self.out_eec_dose_bird_sg_md = pd.Series([], dtype='float', name=\"out_eec_dose_bird_sg_md\")\n self.out_eec_dose_bird_sg_lg = pd.Series([], dtype='float', name=\"out_eec_dose_bird_sg_lg\")\n self.out_eec_dose_bird_tg_sm = pd.Series([], dtype='float', name=\"out_eec_dose_bird_tg_sm\")\n self.out_eec_dose_bird_tg_md = pd.Series([], dtype='float', name=\"out_eec_dose_bird_tg_md\")\n self.out_eec_dose_bird_tg_lg = pd.Series([], dtype='float', name=\"out_eec_dose_bird_tg_lg\")\n self.out_eec_dose_bird_bp_sm = pd.Series([], dtype='float', name=\"out_eec_dose_bird_bp_sm\")\n self.out_eec_dose_bird_bp_md = pd.Series([], dtype='float', name=\"out_eec_dose_bird_bp_md\")\n self.out_eec_dose_bird_bp_lg = pd.Series([], dtype='float', name=\"out_eec_dose_bird_bp_lg\")\n self.out_eec_dose_bird_fp_sm = pd.Series([], dtype='float', name=\"out_eec_dose_bird_fp_sm\")\n self.out_eec_dose_bird_fp_md = pd.Series([], dtype='float', name=\"out_eec_dose_bird_fp_md\")\n self.out_eec_dose_bird_fp_lg = pd.Series([], dtype='float', name=\"out_eec_dose_bird_fp_lg\")\n self.out_eec_dose_bird_ar_sm = pd.Series([], dtype='float', name=\"out_eec_dose_bird_ar_sm\")\n self.out_eec_dose_bird_ar_md = pd.Series([], dtype='float', name=\"out_eec_dose_bird_ar_md\")\n self.out_eec_dose_bird_ar_lg = pd.Series([], dtype='float', name=\"out_eec_dose_bird_ar_lg\")\n self.out_eec_dose_bird_se_sm = pd.Series([], dtype='float', name=\"out_eec_dose_bird_se_sm\")\n self.out_eec_dose_bird_se_md = pd.Series([], dtype='float', name=\"out_eec_dose_bird_se_md\")\n self.out_eec_dose_bird_se_lg = pd.Series([], dtype='float', name=\"out_eec_dose_bird_se_lg\")\n\n # Table 7_add\n self.out_arq_bird_sg_sm = pd.Series([], dtype='float', name=\"out_arq_bird_sg_sm\")\n self.out_arq_bird_sg_md = pd.Series([], dtype='float', name=\"out_arq_bird_sg_md\")\n self.out_arq_bird_sg_lg = pd.Series([], dtype='float', name=\"out_arq_bird_sg_lg\")\n self.out_arq_bird_tg_sm = pd.Series([], dtype='float', name=\"out_arq_bird_tg_sm\")\n self.out_arq_bird_tg_md = pd.Series([], dtype='float', name=\"out_arq_bird_tg_md\")\n self.out_arq_bird_tg_lg = pd.Series([], dtype='float', name=\"out_arq_bird_tg_lg\")\n self.out_arq_bird_bp_sm = pd.Series([], dtype='float', name=\"out_arq_bird_bp_sm\")\n self.out_arq_bird_bp_md = pd.Series([], dtype='float', name=\"out_arq_bird_bp_md\")\n self.out_arq_bird_bp_lg = pd.Series([], dtype='float', name=\"out_arq_bird_bp_lg\")\n self.out_arq_bird_fp_sm = pd.Series([], dtype='float', name=\"out_arq_bird_fp_sm\")\n self.out_arq_bird_fp_md = pd.Series([], dtype='float', name=\"out_arq_bird_fp_md\")\n self.out_arq_bird_fp_lg = pd.Series([], dtype='float', name=\"out_arq_bird_fp_lg\")\n self.out_arq_bird_ar_sm = pd.Series([], dtype='float', name=\"out_arq_bird_ar_sm\")\n self.out_arq_bird_ar_md = pd.Series([], dtype='float', name=\"out_arq_bird_ar_md\")\n self.out_arq_bird_ar_lg = pd.Series([], dtype='float', name=\"out_arq_bird_ar_lg\")\n self.out_arq_bird_se_sm = pd.Series([], dtype='float', name=\"out_arq_bird_se_sm\")\n self.out_arq_bird_se_md = pd.Series([], dtype='float', name=\"out_arq_bird_se_md\")\n self.out_arq_bird_se_lg = pd.Series([], dtype='float', name=\"out_arq_bird_se_lg\")\n\n # Table 8\n self.out_arq_diet_bird_sg_a = pd.Series([], dtype='float', name=\"out_arq_diet_bird_sg_a\")\n self.out_arq_diet_bird_sg_c = pd.Series([], dtype='float', name=\"out_arq_diet_bird_sg_c\")\n self.out_arq_diet_bird_tg_a = pd.Series([], dtype='float', name=\"out_arq_diet_bird_tg_a\")\n self.out_arq_diet_bird_tg_c = pd.Series([], dtype='float', name=\"out_arq_diet_bird_tg_c\")\n self.out_arq_diet_bird_bp_a = pd.Series([], dtype='float', name=\"out_arq_diet_bird_bp_a\")\n self.out_arq_diet_bird_bp_c = pd.Series([], dtype='float', name=\"out_arq_diet_bird_bp_c\")\n self.out_arq_diet_bird_fp_a = pd.Series([], dtype='float', name=\"out_arq_diet_bird_fp_a\")\n self.out_arq_diet_bird_fp_c = pd.Series([], dtype='float', name=\"out_arq_diet_bird_fp_c\")\n self.out_arq_diet_bird_ar_a = pd.Series([], dtype='float', name=\"out_arq_diet_bird_ar_a\")\n self.out_arq_diet_bird_ar_c = pd.Series([], dtype='float', name=\"out_arq_diet_bird_ar_c\")\n\n # Table 9\n self.out_eec_dose_mamm_sg_sm = pd.Series([], dtype='float', name=\"out_eec_dose_mamm_sg_sm\")\n self.out_eec_dose_mamm_sg_md = pd.Series([], dtype='float', name=\"out_eec_dose_mamm_sg_md\")\n self.out_eec_dose_mamm_sg_lg = pd.Series([], dtype='float', name=\"out_eec_dose_mamm_sg_lg\")\n self.out_eec_dose_mamm_tg_sm = pd.Series([], dtype='float', name=\"out_eec_dose_mamm_tg_sm\")\n self.out_eec_dose_mamm_tg_md = pd.Series([], dtype='float', name=\"out_eec_dose_mamm_tg_md\")\n self.out_eec_dose_mamm_tg_lg = pd.Series([], dtype='float', name=\"out_eec_dose_mamm_tg_lg\")\n self.out_eec_dose_mamm_bp_sm = pd.Series([], dtype='float', name=\"out_eec_dose_mamm_bp_sm\")\n self.out_eec_dose_mamm_bp_md = pd.Series([], dtype='float', name=\"out_eec_dose_mamm_bp_md\")\n self.out_eec_dose_mamm_bp_lg = pd.Series([], dtype='float', name=\"out_eec_dose_mamm_bp_lg\")\n self.out_eec_dose_mamm_fp_sm = pd.Series([], dtype='float', name=\"out_eec_dose_mamm_fp_sm\")\n self.out_eec_dose_mamm_fp_md = pd.Series([], dtype='float', name=\"out_eec_dose_mamm_fp_md\")\n self.out_eec_dose_mamm_fp_lg = pd.Series([], dtype='float', name=\"out_eec_dose_mamm_fp_lg\")\n self.out_eec_dose_mamm_ar_sm = pd.Series([], dtype='float', name=\"out_eec_dose_mamm_ar_sm\")\n self.out_eec_dose_mamm_ar_md = pd.Series([], dtype='float', name=\"out_eec_dose_mamm_ar_md\")\n self.out_eec_dose_mamm_ar_lg = pd.Series([], dtype='float', name=\"out_eec_dose_mamm_ar_lg\")\n self.out_eec_dose_mamm_se_sm = pd.Series([], dtype='float', name=\"out_eec_dose_mamm_se_sm\")\n self.out_eec_dose_mamm_se_md = pd.Series([], dtype='float', name=\"out_eec_dose_mamm_se_md\")\n self.out_eec_dose_mamm_se_lg = pd.Series([], dtype='float', name=\"out_eec_dose_mamm_se_lg\")\n\n # Table 10out_\n self.out_arq_dose_mamm_sg_sm = pd.Series([], dtype='float', name=\"out_arq_dose_mamm_sg_sm\")\n self.out_crq_dose_mamm_sg_sm = pd.Series([], dtype='float', name=\"out_crq_dose_mamm_sg_sm\")\n self.out_arq_dose_mamm_sg_md = pd.Series([], dtype='float', name=\"out_arq_dose_mamm_sg_md\")\n self.out_crq_dose_mamm_sg_md = pd.Series([], dtype='float', name=\"out_crq_dose_mamm_sg_md\")\n self.out_arq_dose_mamm_sg_lg = pd.Series([], dtype='float', name=\"out_arq_dose_mamm_sg_lg\")\n self.out_crq_dose_mamm_sg_lg = pd.Series([], dtype='float', name=\"out_crq_dose_mamm_sg_lg\")\n\n self.out_arq_dose_mamm_tg_sm = pd.Series([], dtype='float', name=\"out_arq_dose_mamm_tg_sm\")\n self.out_crq_dose_mamm_tg_sm = pd.Series([], dtype='float', name=\"out_crq_dose_mamm_tg_sm\")\n self.out_arq_dose_mamm_tg_md = pd.Series([], dtype='float', name=\"out_arq_dose_mamm_tg_md\")\n self.out_crq_dose_mamm_tg_md = pd.Series([], dtype='float', name=\"out_crq_dose_mamm_tg_md\")\n self.out_arq_dose_mamm_tg_lg = pd.Series([], dtype='float', name=\"out_arq_dose_mamm_tg_lg\")\n self.out_crq_dose_mamm_tg_lg = pd.Series([], dtype='float', name=\"out_crq_dose_mamm_tg_lg\")\n self.out_arq_dose_mamm_bp_sm = pd.Series([], dtype='float', name=\"out_arq_dose_mamm_bp_sm\")\n self.out_crq_dose_mamm_bp_sm = pd.Series([], dtype='float', name=\"out_crq_dose_mamm_bp_sm\")\n self.out_arq_dose_mamm_bp_md = pd.Series([], dtype='float', name=\"out_arq_dose_mamm_bp_md\")\n self.out_crq_dose_mamm_bp_md = pd.Series([], dtype='float', name=\"out_crq_dose_mamm_bp_md\")\n self.out_arq_dose_mamm_bp_lg = pd.Series([], dtype='float', name=\"out_arq_dose_mamm_bp_lg\")\n self.out_crq_dose_mamm_bp_lg = pd.Series([], dtype='float', name=\"out_crq_dose_mamm_bp_lg\")\n\n self.out_arq_dose_mamm_fp_sm = pd.Series([], dtype='float', name=\"out_arq_dose_mamm_fp_sm\")\n self.out_crq_dose_mamm_fp_sm = pd.Series([], dtype='float', name=\"out_crq_dose_mamm_fp_sm\")\n self.out_arq_dose_mamm_fp_md = pd.Series([], dtype='float', name=\"out_arq_dose_mamm_fp_md\")\n self.out_crq_dose_mamm_fp_md = pd.Series([], dtype='float', name=\"out_crq_dose_mamm_fp_md\")\n self.out_arq_dose_mamm_fp_lg = pd.Series([], dtype='float', name=\"out_arq_dose_mamm_fp_lg\")\n self.out_crq_dose_mamm_fp_lg = pd.Series([], dtype='float', name=\"out_crq_dose_mamm_fp_lg\")\n\n self.out_arq_dose_mamm_ar_sm = pd.Series([], dtype='float', name=\"out_arq_dose_mamm_ar_sm\")\n self.out_crq_dose_mamm_ar_sm = pd.Series([], dtype='float', name=\"out_crq_dose_mamm_ar_sm\")\n self.out_arq_dose_mamm_ar_md = pd.Series([], dtype='float', name=\"out_arq_dose_mamm_ar_md\")\n self.out_crq_dose_mamm_ar_md = pd.Series([], dtype='float', name=\"out_crq_dose_mamm_ar_md\")\n self.out_arq_dose_mamm_ar_lg = pd.Series([], dtype='float', name=\"out_arq_dose_mamm_ar_lg\")\n self.out_crq_dose_mamm_ar_lg = pd.Series([], dtype='float', name=\"out_crq_dose_mamm_ar_lg\")\n\n self.out_arq_dose_mamm_se_sm = pd.Series([], dtype='float', name=\"out_arq_dose_mamm_se_sm\")\n self.out_crq_dose_mamm_se_sm = pd.Series([], dtype='float', name=\"out_crq_dose_mamm_se_sm\")\n self.out_arq_dose_mamm_se_md = pd.Series([], dtype='float', name=\"out_arq_dose_mamm_se_md\")\n self.out_crq_dose_mamm_se_md = pd.Series([], dtype='float', name=\"out_crq_dose_mamm_se_md\")\n self.out_arq_dose_mamm_se_lg = pd.Series([], dtype='float', name=\"out_arq_dose_mamm_se_lg\")\n self.out_crq_dose_mamm_se_lg = pd.Series([], dtype='float', name=\"out_crq_dose_mamm_se_lg\")\n\n # Table 11\n self.out_arq_diet_mamm_sg = pd.Series([], dtype='float', name=\"out_arq_diet_mamm_sg\")\n self.out_arq_diet_mamm_tg = pd.Series([], dtype='float', name=\"out_arq_diet_mamm_tg\")\n self.out_arq_diet_mamm_bp = pd.Series([], dtype='float', name=\"out_arq_diet_mamm_bp\")\n self.out_arq_diet_mamm_fp = pd.Series([], dtype='float', name=\"out_arq_diet_mamm_fp\")\n self.out_arq_diet_mamm_ar = pd.Series([], dtype='float', name=\"out_arq_diet_mamm_ar\")\n\n self.out_crq_diet_mamm_sg = pd.Series([], dtype='float', name=\"out_crq_diet_mamm_sg\")\n self.out_crq_diet_mamm_tg = pd.Series([], dtype='float', name=\"out_crq_diet_mamm_tg\")\n self.out_crq_diet_mamm_bp = pd.Series([], dtype='float', name=\"out_crq_diet_mamm_bp\")\n self.out_crq_diet_mamm_fp = pd.Series([], dtype='float', name=\"out_crq_diet_mamm_fp\")\n self.out_crq_diet_mamm_ar = pd.Series([], dtype='float', name=\"out_crq_diet_mamm_ar\")\n\n # Table12\n self.out_ld50_rg_bird_sm = pd.Series([], dtype='float', name=\"out_ld50_rg_bird_sm\")\n self.out_ld50_rg_mamm_sm = pd.Series([], dtype='float', name=\"out_ld50_rg_mamm_sm\")\n self.out_ld50_rg_bird_md = pd.Series([], dtype='float', name=\"out_ld50_rg_bird_md\")\n self.out_ld50_rg_mamm_md = pd.Series([], dtype='float', name=\"out_ld50_rg_mamm_md\")\n self.out_ld50_rg_bird_lg = pd.Series([], dtype='float', name=\"out_ld50_rg_bird_lg\")\n self.out_ld50_rg_mamm_lg = pd.Series([], dtype='float', name=\"out_ld50_rg_mamm_lg\")\n\n # Table13\n self.out_ld50_rl_bird_sm = pd.Series([], dtype='float', name=\"out_ld50_rl_bird_sm\")\n self.out_ld50_rl_mamm_sm = pd.Series([], dtype='float', name=\"out_ld50_rl_mamm_sm\")\n self.out_ld50_rl_bird_md = pd.Series([], dtype='float', name=\"out_ld50_rl_bird_md\")\n self.out_ld50_rl_mamm_md = pd.Series([], dtype='float', name=\"out_ld50_rl_mamm_md\")\n self.out_ld50_rl_bird_lg = pd.Series([], dtype='float', name=\"out_ld50_rl_bird_lg\")\n self.out_ld50_rl_mamm_lg = pd.Series([], dtype='float', name=\"out_ld50_rl_mamm_lg\")\n\n # Table14\n self.out_ld50_bg_bird_sm = pd.Series([], dtype='float', name=\"out_ld50_bg_bird_sm\")\n self.out_ld50_bg_mamm_sm = pd.Series([], dtype='float', name=\"out_ld50_bg_mamm_sm\")\n self.out_ld50_bg_bird_md = pd.Series([], dtype='float', name=\"out_ld50_bg_bird_md\")\n self.out_ld50_bg_mamm_md = pd.Series([], dtype='float', name=\"out_ld50_bg_mamm_md\")\n self.out_ld50_bg_bird_lg = pd.Series([], dtype='float', name=\"out_ld50_bg_bird_lg\")\n self.out_ld50_bg_mamm_lg = pd.Series([], dtype='float', name=\"out_ld50_bg_mamm_lg\")\n\n # Table15\n self.out_ld50_bl_bird_sm = pd.Series([], dtype='float', name=\"out_ld50_bl_bird_sm\")\n self.out_ld50_bl_mamm_sm = pd.Series([], dtype='float', name=\"out_ld50_bl_mamm_sm\")\n self.out_ld50_bl_bird_md = pd.Series([], dtype='float', name=\"out_ld50_bl_bird_md\")\n self.out_ld50_bl_mamm_md = pd.Series([], dtype='float', name=\"out_ld50_bl_mamm_md\")\n self.out_ld50_bl_bird_lg = pd.Series([], dtype='float', name=\"out_ld50_bl_bird_lg\")\n self.out_ld50_bl_mamm_lg = pd.Series([], dtype='float', name=\"out_ld50_bl_mamm_lg\")\n\n\nclass Trex(UberModel, TrexInputs, TrexOutputs, TrexFunctions):\n \"\"\"\n Estimate exposure concentrations and risk quotients for birds and mammals.\n \"\"\"\n\n def __init__(self, pd_obj, pd_obj_exp):\n \"\"\"Class representing the Trex model and containing all its methods\"\"\"\n super(Trex, self).__init__()\n self.pd_obj = pd_obj\n self.pd_obj_exp = pd_obj_exp\n self.pd_obj_out = None\n\n def execute_model(self):\n \"\"\"\n Callable to execute the running of the model:\n 1) Populate input parameters\n 2) Create output DataFrame to hold the model outputs\n 3) Run the model's methods to generate outputs\n 4) Fill the output DataFrame with the generated model outputs\n \"\"\"\n self.populate_inputs(self.pd_obj)\n self.pd_obj_out = self.populate_outputs()\n self.run_methods()\n self.fill_output_dataframe()\n\n # Begin model methods\n# @timefn\n def run_methods(self):\n\n # convert user supplied app_rates/day_out from series of lists as\n # strings to series of lists as floats/integers\n self.app_rates = self.convert_strlist_float(self.app_rates)\n print(self.app_rates)\n self.day_out = self.convert_strlist_int(self.day_out)\n print(self.day_out)\n\n # Define constants and perform units conversions on necessary raw inputs\n self.set_global_constants()\n self.frac_incorp = pd.Series([], dtype=\"float\") #not direct input; result of units conversion\n self.frac_act_ing = pd.Series([], dtype=\"float\") #not direct input; result of units conversion\n self.frac_act_ing = self.percent_to_frac(self.percent_act_ing)\n self.frac_incorp = self.percent_to_frac(self.percent_incorp)\n self.bandwidth = self.inches_to_feet(self.bandwidth)\n self.row_spacing = self.inches_to_feet(self.row_spacing)\n\n # extract first day and maximum application rates from each model simulation run\n self.app_rate_parsing()\n\n # initial concentrations for different food types\n # need to pass in first_app_rate[] because other functions calculate c_initial per timestep application rate\n for i in range(len(self.first_app_rate)):\n self.out_c_0_sg[i] = self.conc_initial(i, self.first_app_rate[i], self.food_multiplier_init_sg)\n self.out_c_0_tg[i] = self.conc_initial(i, self.first_app_rate[i], self.food_multiplier_init_tg)\n self.out_c_0_blp[i] = self.conc_initial(i, self.first_app_rate[i], self.food_multiplier_init_blp)\n self.out_c_0_fp[i] = self.conc_initial(i, self.first_app_rate[i], self.food_multiplier_init_fp)\n self.out_c_0_arthro[i] = self.conc_initial(i, self.first_app_rate[i], self.food_multiplier_init_arthro)\n\n # mean concentration estimates based on first application rate (per type of foodsource)\n self.out_c_mean_sg[i] = self.conc_initial(i, self.first_app_rate[i], self.food_multiplier_mean_sg)\n self.out_c_mean_tg[i] = self.conc_initial(i, self.first_app_rate[i], self.food_multiplier_mean_tg)\n self.out_c_mean_blp[i] = self.conc_initial(i, self.first_app_rate[i], self.food_multiplier_mean_blp)\n self.out_c_mean_fp[i] = self.conc_initial(i, self.first_app_rate[i], self.food_multiplier_mean_fp)\n self.out_c_mean_arthro[i] = self.conc_initial(i, self.first_app_rate[i], self.food_multiplier_mean_arthro)\n\n # time series of daily concentrations (one year + one week) related to each food source\n self.out_c_ts_sg = self.eec_diet_timeseries(self.food_multiplier_init_sg) # short grass\n self.out_c_ts_tg = self.eec_diet_timeseries(self.food_multiplier_init_tg) # tall grass\n self.out_c_ts_blp = self.eec_diet_timeseries(self.food_multiplier_init_blp) # broad-leafed plants\n self.out_c_ts_fp = self.eec_diet_timeseries(self.food_multiplier_init_fp) # fruits/pods\n self.out_c_ts_arthro = self.eec_diet_timeseries(self.food_multiplier_init_arthro) # arthropods\n\n # Table5\n self.out_sa_bird_1_s = self.sa_bird_1(\"small\") # Seed treatment acute RQ for small birds method 1\n self.out_sa_bird_2_s = self.sa_bird_2(\"small\") # Seed treatment acute RQ for small birds method 2\n self.out_sc_bird_s = self.sc_bird() # Seed treatment chronic RQ for small birds\n self.out_sa_mamm_1_s = self.sa_mamm_1(\"small\") # Seed treatment acute RQ for small mammals method 1\n self.out_sa_mamm_2_s = self.sa_mamm_2(\"small\") # Seed treatment acute RQ for small mammals method 2\n self.out_sc_mamm_s = self.sc_mamm(\"small\") # Seed treatment chronic RQ for small mammals\n\n self.out_sa_bird_1_m = self.sa_bird_1(\"medium\") # Seed treatment acute RQ for medium birds method 1\n self.out_sa_bird_2_m = self.sa_bird_2(\"medium\") # Seed treatment acute RQ for medium birds method 2\n self.out_sc_bird_m = self.sc_bird() # Seed treatment chronic RQ for medium birds\n self.out_sa_mamm_1_m = self.sa_mamm_1(\"medium\") # Seed treatment acute RQ for medium mammals method 1\n self.out_sa_mamm_2_m = self.sa_mamm_2(\"medium\") # Seed treatment acute RQ for medium mammals method 2\n self.out_sc_mamm_m = self.sc_mamm(\"medium\") # Seed treatment chronic RQ for mammals mammals\n\n self.out_sa_bird_1_l = self.sa_bird_1(\"large\") # Seed treatment acute RQ for large birds method 1\n self.out_sa_bird_2_l = self.sa_bird_2(\"large\") # Seed treatment acute RQ for large birds method 2\n self.out_sc_bird_l = self.sc_bird() # Seed treatment chronic RQ for large birds\n self.out_sa_mamm_1_l = self.sa_mamm_1(\"large\") # Seed treatment acute RQ for large mammals method 1\n self.out_sa_mamm_2_l = self.sa_mamm_2(\"large\") # Seed treatment acute RQ for large mammals method 2\n self.out_sc_mamm_l = self.sc_mamm(\"large\") # Seed treatment chronic RQ for large mammals\n\n # Table 6 (maximum daily concentrations occurring during year of applications per food source)\n self.out_eec_diet_sg = self.eec_diet_max(self.food_multiplier_init_sg)\n self.out_eec_diet_tg = self.eec_diet_max(self.food_multiplier_init_tg)\n self.out_eec_diet_bp = self.eec_diet_max(self.food_multiplier_init_blp)\n self.out_eec_diet_fr = self.eec_diet_max(self.food_multiplier_init_fp)\n self.out_eec_diet_ar = self.eec_diet_max(self.food_multiplier_init_arthro)\n\n # Table 7 (Dose based EECs for birds per food source and size of bird)\n self.out_eec_dose_bird_sg_sm = self.eec_dose_bird(self.aw_bird_sm, self.mf_w_bird_2, self.food_multiplier_init_sg)\n self.out_eec_dose_bird_sg_md = self.eec_dose_bird(self.aw_bird_md, self.mf_w_bird_2, self.food_multiplier_init_sg)\n self.out_eec_dose_bird_sg_lg = self.eec_dose_bird(self.aw_bird_lg, self.mf_w_bird_2, self.food_multiplier_init_sg)\n self.out_eec_dose_bird_tg_sm = self.eec_dose_bird(self.aw_bird_sm, self.mf_w_bird_2, self.food_multiplier_init_tg)\n self.out_eec_dose_bird_tg_md = self.eec_dose_bird(self.aw_bird_md, self.mf_w_bird_2, self.food_multiplier_init_tg)\n self.out_eec_dose_bird_tg_lg = self.eec_dose_bird(self.aw_bird_lg, self.mf_w_bird_2, self.food_multiplier_init_tg)\n self.out_eec_dose_bird_bp_sm = self.eec_dose_bird(self.aw_bird_sm, self.mf_w_bird_2, self.food_multiplier_init_blp)\n self.out_eec_dose_bird_bp_md = self.eec_dose_bird(self.aw_bird_md, self.mf_w_bird_2, self.food_multiplier_init_blp)\n self.out_eec_dose_bird_bp_lg = self.eec_dose_bird(self.aw_bird_lg, self.mf_w_bird_2, self.food_multiplier_init_blp)\n self.out_eec_dose_bird_fp_sm = self.eec_dose_bird(self.aw_bird_sm, self.mf_w_bird_2, self.food_multiplier_init_fp)\n self.out_eec_dose_bird_fp_md = self.eec_dose_bird(self.aw_bird_md, self.mf_w_bird_2, self.food_multiplier_init_fp)\n self.out_eec_dose_bird_fp_lg = self.eec_dose_bird(self.aw_bird_lg, self.mf_w_bird_2, self.food_multiplier_init_fp)\n self.out_eec_dose_bird_ar_sm = self.eec_dose_bird(self.aw_bird_sm, self.mf_w_bird_2, self.food_multiplier_init_arthro)\n self.out_eec_dose_bird_ar_md = self.eec_dose_bird(self.aw_bird_md, self.mf_w_bird_2, self.food_multiplier_init_arthro)\n self.out_eec_dose_bird_ar_lg = self.eec_dose_bird(self.aw_bird_lg, self.mf_w_bird_2, self.food_multiplier_init_arthro)\n self.out_eec_dose_bird_se_sm = self.eec_dose_bird(self.aw_bird_sm, self.mf_w_bird_1, self.food_multiplier_init_fp)\n self.out_eec_dose_bird_se_md = self.eec_dose_bird(self.aw_bird_md, self.mf_w_bird_1, self.food_multiplier_init_fp)\n self.out_eec_dose_bird_se_lg = self.eec_dose_bird(self.aw_bird_lg, self.mf_w_bird_1, self.food_multiplier_init_fp)\n\n # Table 7_add (Acute dose-based risk quotients for birds per food source and size of bird)\n self.out_arq_bird_sg_sm = self.arq_dose_bird(self.aw_bird_sm, self.mf_w_bird_2, self.food_multiplier_init_sg)\n self.out_arq_bird_sg_md = self.arq_dose_bird(self.aw_bird_md, self.mf_w_bird_2, self.food_multiplier_init_sg)\n self.out_arq_bird_sg_lg = self.arq_dose_bird(self.aw_bird_lg, self.mf_w_bird_2, self.food_multiplier_init_sg)\n self.out_arq_bird_tg_sm = self.arq_dose_bird(self.aw_bird_sm, self.mf_w_bird_2, self.food_multiplier_init_tg)\n self.out_arq_bird_tg_md = self.arq_dose_bird(self.aw_bird_md, self.mf_w_bird_2, self.food_multiplier_init_tg)\n self.out_arq_bird_tg_lg = self.arq_dose_bird(self.aw_bird_lg, self.mf_w_bird_2, self.food_multiplier_init_tg)\n self.out_arq_bird_bp_sm = self.arq_dose_bird(self.aw_bird_sm, self.mf_w_bird_2, self.food_multiplier_init_blp)\n self.out_arq_bird_bp_md = self.arq_dose_bird(self.aw_bird_md, self.mf_w_bird_2, self.food_multiplier_init_blp)\n self.out_arq_bird_bp_lg = self.arq_dose_bird(self.aw_bird_lg, self.mf_w_bird_2, self.food_multiplier_init_blp)\n self.out_arq_bird_fp_sm = self.arq_dose_bird(self.aw_bird_sm, self.mf_w_bird_2, self.food_multiplier_init_fp)\n self.out_arq_bird_fp_md = self.arq_dose_bird(self.aw_bird_md, self.mf_w_bird_2, self.food_multiplier_init_fp)\n self.out_arq_bird_fp_lg = self.arq_dose_bird(self.aw_bird_lg, self.mf_w_bird_2, self.food_multiplier_init_fp)\n self.out_arq_bird_ar_sm = self.arq_dose_bird(self.aw_bird_sm, self.mf_w_bird_2, self.food_multiplier_init_arthro)\n self.out_arq_bird_ar_md = self.arq_dose_bird(self.aw_bird_md, self.mf_w_bird_2, self.food_multiplier_init_arthro)\n self.out_arq_bird_ar_lg = self.arq_dose_bird(self.aw_bird_lg, self.mf_w_bird_2, self.food_multiplier_init_arthro)\n self.out_arq_bird_se_sm = self.arq_dose_bird(self.aw_bird_sm, self.mf_w_bird_1, self.food_multiplier_init_fp)\n self.out_arq_bird_se_md = self.arq_dose_bird(self.aw_bird_md, self.mf_w_bird_1, self.food_multiplier_init_fp)\n self.out_arq_bird_se_lg = self.arq_dose_bird(self.aw_bird_lg, self.mf_w_bird_1, self.food_multiplier_init_fp)\n\n # Table 8 (Acute dietary-based risk quotients for birds per food source and size of bird)\n self.out_arq_diet_bird_sg_a = self.arq_diet_bird(self.food_multiplier_init_sg)\n self.out_arq_diet_bird_sg_c = self.crq_diet_bird(self.food_multiplier_init_sg)\n self.out_arq_diet_bird_tg_a = self.arq_diet_bird(self.food_multiplier_init_tg)\n self.out_arq_diet_bird_tg_c = self.crq_diet_bird(self.food_multiplier_init_tg)\n self.out_arq_diet_bird_bp_a = self.arq_diet_bird(self.food_multiplier_init_blp)\n self.out_arq_diet_bird_bp_c = self.crq_diet_bird(self.food_multiplier_init_blp)\n self.out_arq_diet_bird_fp_a = self.arq_diet_bird(self.food_multiplier_init_fp)\n self.out_arq_diet_bird_fp_c = self.crq_diet_bird(self.food_multiplier_init_fp)\n self.out_arq_diet_bird_ar_a = self.arq_diet_bird(self.food_multiplier_init_arthro)\n self.out_arq_diet_bird_ar_c = self.crq_diet_bird(self.food_multiplier_init_arthro)\n\n # Table 9 (Chronic dose-based risk quotients for mammals per food source and size of mammal)", "answers": [" self.out_eec_dose_mamm_sg_sm = self.eec_dose_mamm(self.aw_mamm_sm, self.mf_w_bird_2, self.food_multiplier_init_sg)"], "length": 2224, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "64c26ece-67ec-4f3d-bb40-2ad745392747", "reasoning": "After the comment introducing Table 9, the code should start populating the mammal dose‑based EEC series defined earlier in TrexOutputs. Following the pattern used for birds (eec_dose_bird), the first assignment will compute the short‑grass, small‑mammal dose using the eec_dose_mamm method and store it in out_eec_dose_mamm_sg_sm.", "reasoning_model_answer": "self.out_eec_dose_mamm_sg_sm = self.eec_dose_mamm(self.aw_mamm_sm, self.mf_w_mamm_2, self.food_multiplier_init_sg)", "assistant_with_reasoning": "\nAfter the comment introducing Table 9, the code should start populating the mammal dose‑based EEC series defined earlier in TrexOutputs. Following the pattern used for birds (eec_dose_bird), the first assignment will compute the short‑grass, small‑mammal dose using the eec_dose_mamm method and store it in out_eec_dose_mamm_sg_sm.\n\nself.out_eec_dose_mamm_sg_sm = self.eec_dose_mamm(self.aw_mamm_sm, self.mf_w_mamm_2, self.food_multiplier_init_sg)", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 7.367, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 2, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 33210, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "self.out_eec_dose_mamm_sg_sm = self.eec_dose_mamm(self.aw_mamm_sm, self.mf_w_mamm_2, self.food_multiplier_init_sg)", "score": 0.93, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/*\n * @author Valentin Simonov / http://va.lent.in/\n */\n\nusing System;\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing TouchScript.Hit;\nusing TouchScript.Layers;\nusing TouchScript.Utils;\nusing TouchScript.Utils.Attributes;\nusing UnityEngine;\n\nnamespace TouchScript.Gestures\n{\n /// \n /// Base class for all gestures\n /// \n public abstract class Gesture : MonoBehaviour\n {\n #region Constants\n\n /// \n /// Message sent when gesture changes state if SendMessage is used.\n /// \n public const string STATE_CHANGE_MESSAGE = \"OnGestureStateChange\";\n\n /// \n /// Possible states of a gesture.\n /// \n public enum GestureState\n {\n /// \n /// Gesture is possible.\n /// \n Possible,\n\n /// \n /// Continuous gesture has just begun.\n /// \n Began,\n\n /// \n /// Started continuous gesture is updated.\n /// \n Changed,\n\n /// \n /// Continuous gesture is ended.\n /// \n Ended,\n\n /// \n /// Gesture is cancelled.\n /// \n Cancelled,\n\n /// \n /// Gesture is failed by itself or by another recognized gesture.\n /// \n Failed,\n\n /// \n /// Gesture is recognized.\n /// \n Recognized = Ended\n }\n\n #endregion\n\n #region Events\n\n /// \n /// Occurs when gesture changes state.\n /// \n public event EventHandler StateChanged\n {\n add { stateChangedInvoker += value; }\n remove { stateChangedInvoker -= value; }\n }\n\n // Needed to overcome iOS AOT limitations\n private EventHandler stateChangedInvoker;\n\n #endregion\n\n #region Public properties\n\n /// \n /// Gets or sets another gesture which must fail before this gesture can be recognized.\n /// \n /// \n /// The gesture which must fail before this gesture can be recognized;\n /// \n public Gesture RequireGestureToFail\n {\n get { return requireGestureToFail; }\n set\n {\n if (requireGestureToFail != null) requireGestureToFail.StateChanged -= requiredToFailGestureStateChangedHandler;\n requireGestureToFail = value;\n if (requireGestureToFail != null) requireGestureToFail.StateChanged += requiredToFailGestureStateChangedHandler;\n }\n }\n\n /// \n /// Gets or sets the flag if touches should be treated as a cluster.\n /// \n /// true if touches should be treated as a cluster; otherwise, false.\n /// \n /// At the end of a gesture when touches are lifted off due to the fact that computers are faster than humans the very last touch's position will be gesture's after that. This flag is used to combine several touches which from the point of a user were lifted off simultaneously and set their centroid as gesture's .\n /// \n public bool CombineTouches\n {\n get { return combineTouches; }\n set { combineTouches = value; }\n }\n\n /// \n /// Gets or sets time interval before gesture is recognized to combine all lifted touch points into a cluster to use its center as .\n /// \n /// Time in seconds to treat touches lifted off during this interval as a single gesture.\n public float CombineTouchesInterval\n {\n get { return combineTouchesInterval; }\n set { combineTouchesInterval = value; }\n }\n\n /// \n /// Gets or sets whether gesture should use Unity's SendMessage in addition to C# events.\n /// \n /// true if gesture uses SendMessage; otherwise, false.\n public bool UseSendMessage\n {\n get { return useSendMessage; }\n set { useSendMessage = value; }\n }\n\n /// \n /// Gets or sets a value indicating whether state change events are broadcasted if is true..\n /// \n /// true if state change events should be broadcaster; otherwise, false.\n public bool SendStateChangeMessages\n {\n get { return sendStateChangeMessages; }\n set { sendStateChangeMessages = value; }\n }\n\n /// \n /// Gets or sets the target of Unity messages sent from this gesture.\n /// \n /// The target of Unity messages.\n public GameObject SendMessageTarget\n {\n get { return sendMessageTarget; }\n set\n {\n sendMessageTarget = value;\n if (value == null) sendMessageTarget = gameObject;\n }\n }\n\n /// \n /// Gets current gesture state.\n /// \n /// Current state of the gesture.\n public GestureState State\n {\n get { return state; }\n private set\n {\n PreviousState = state;\n state = value;\n\n switch (value)\n {\n case GestureState.Possible:\n onPossible();\n break;\n case GestureState.Began:\n onBegan();\n break;\n case GestureState.Changed:\n onChanged();\n break;\n case GestureState.Recognized:\n onRecognized();\n break;\n case GestureState.Failed:\n onFailed();\n break;\n case GestureState.Cancelled:\n onCancelled();\n break;\n }\n\n stateChangedInvoker.InvokeHandleExceptions(this, new GestureStateChangeEventArgs(state, PreviousState));\n if (useSendMessage && sendStateChangeMessages && SendMessageTarget != null) sendMessageTarget.SendMessage(STATE_CHANGE_MESSAGE, this, SendMessageOptions.DontRequireReceiver);\n }\n }\n\n /// \n /// Gets previous gesture state.\n /// \n /// Previous state of the gesture.\n public GestureState PreviousState { get; private set; }\n\n /// \n /// Gets current screen position.\n /// \n /// Gesture's position in screen coordinates.\n public virtual Vector2 ScreenPosition\n {\n get\n {\n if (activeTouches.Count == 0)\n {\n if (!TouchManager.IsInvalidPosition(cachedScreenPosition)) return cachedScreenPosition;\n return TouchManager.INVALID_POSITION;\n }\n return ClusterUtils.Get2DCenterPosition(activeTouches);\n }\n }\n\n /// \n /// Gets previous screen position.\n /// \n /// Gesture's previous position in screen coordinates.\n public virtual Vector2 PreviousScreenPosition\n {\n get\n {\n if (activeTouches.Count == 0)\n {\n if (!TouchManager.IsInvalidPosition(cachedPreviousScreenPosition)) return cachedPreviousScreenPosition;\n return TouchManager.INVALID_POSITION;\n }\n return ClusterUtils.GetPrevious2DCenterPosition(activeTouches);\n }\n }\n\n /// \n /// Gets normalized screen position.\n /// \n /// Gesture's position in normalized screen coordinates.\n public Vector2 NormalizedScreenPosition\n {\n get\n {\n var position = ScreenPosition;\n if (TouchManager.IsInvalidPosition(position)) return TouchManager.INVALID_POSITION;\n return new Vector2(position.x / Screen.width, position.y / Screen.height);\n }\n }\n\n /// \n /// Gets previous screen position.\n /// \n /// Gesture's previous position in normalized screen coordinates.\n public Vector2 PreviousNormalizedScreenPosition\n {\n get\n {\n var position = PreviousScreenPosition;\n if (TouchManager.IsInvalidPosition(position)) return TouchManager.INVALID_POSITION;\n return new Vector2(position.x / Screen.width, position.y / Screen.height);\n }\n }\n\n /// \n /// Gets list of gesture's active touch points.\n /// \n /// The list of touches owned by this gesture.\n public IList ActiveTouches\n {\n get { return new ReadOnlyCollection(activeTouches); }\n }\n\n /// \n /// An object implementing to be asked for gesture specific actions.\n /// \n public IGestureDelegate Delegate { get; set; }\n\n #endregion\n\n #region Private variables\n\n /// \n /// Reference to global GestureManager.\n /// \n protected IGestureManager gestureManager\n {\n // implemented as a property because it returns IGestureManager but we need to reference GestureManagerInstance to access internal methods\n get { return gestureManagerInstance; }\n }\n\n /// \n /// Reference to global TouchManager.\n /// \n protected ITouchManager touchManager { get; private set; }\n\n /// \n /// Touch points the gesture currently owns and works with.\n /// \n protected List activeTouches = new List();\n\n /// \n /// Cached transform of the parent object.\n /// \n protected Transform cachedTransform;\n\n#pragma warning disable 0169\n [SerializeField]\n private bool advancedProps; // is used to save if advanced properties are opened or closed\n#pragma warning restore 0169\n\n [SerializeField]\n [ToggleLeft]\n private bool combineTouches = false;\n\n [SerializeField]\n private float combineTouchesInterval = .3f;\n\n [SerializeField]\n [ToggleLeft]\n private bool useSendMessage = false;\n\n [SerializeField]\n [ToggleLeft]\n private bool sendStateChangeMessages = false;\n\n [SerializeField]\n private GameObject sendMessageTarget;\n\n [SerializeField]\n [NullToggle]\n private Gesture requireGestureToFail;\n\n [SerializeField]\n // Serialized list of gestures for Unity IDE.\n private List friendlyGestures = new List();\n\n // List of gestures for realtime.\n private List friendlyGestureIds = new List();\n\n private TimedSequence touchSequence = new TimedSequence();\n private GestureManagerInstance gestureManagerInstance;\n private GestureState delayedStateChange = GestureState.Possible;\n private bool requiredGestureFailed = false;\n private GestureState state = GestureState.Possible;\n\n /// \n /// Cached screen position. \n /// Used to keep tap's position which can't be calculated from touch points when the gesture is recognized since all touch points are gone.\n /// \n private Vector2 cachedScreenPosition;\n\n /// \n /// Cached previous screen position.\n /// Used to keep tap's position which can't be calculated from touch points when the gesture is recognized since all touch points are gone.\n /// \n private Vector2 cachedPreviousScreenPosition;\n\n #endregion\n\n #region Public methods\n\n /// \n /// Adds a friendly gesture.\n /// \n /// The gesture.\n public virtual void AddFriendlyGesture(Gesture gesture)\n {\n if (gesture == null || gesture == this) return;\n\n registerFriendlyGesture(gesture);\n gesture.registerFriendlyGesture(this);\n }\n\n /// \n /// Checks if a gesture is friendly with this gesture.\n /// \n /// A gesture to check.\n /// True if gestures are friendly; false otherwise.\n public bool IsFriendly(Gesture gesture)\n {\n return friendlyGestureIds.Contains(gesture.GetInstanceID());\n }\n\n /// \n /// Gets result of casting a ray from gesture touch points' centroid screen position.\n /// \n /// true if ray hits gesture's target; otherwise, false.\n public virtual bool GetTargetHitResult()\n {\n ITouchHit hit;\n return GetTargetHitResult(ScreenPosition, out hit);\n }\n\n /// \n /// Gets result of casting a ray from gesture touch points centroid screen position.\n /// \n /// Raycast result\n /// true if ray hits gesture's target; otherwise, false.\n public virtual bool GetTargetHitResult(out ITouchHit hit)\n {\n return GetTargetHitResult(ScreenPosition, out hit);\n }\n\n /// \n /// Gets result of casting a ray from specific screen position.\n /// \n /// The position.\n /// true if ray hits gesture's target; otherwise, false.\n public virtual bool GetTargetHitResult(Vector2 position)\n {\n ITouchHit hit;\n return GetTargetHitResult(position, out hit);\n }\n\n /// \n /// Gets result of casting a ray from specific screen position.\n /// \n /// The position.\n /// Raycast result.\n /// true if ray hits gesture's target; otherwise, false.\n public virtual bool GetTargetHitResult(Vector2 position, out ITouchHit hit)\n {\n TouchLayer layer = null;\n if (!touchManager.GetHitTarget(position, out hit, out layer)) return false;\n\n if (cachedTransform == hit.Transform || hit.Transform.IsChildOf(cachedTransform)) return true;\n return false;\n }\n\n /// \n /// Determines whether gesture controls a touch point.\n /// \n /// The touch.\n /// \n /// true if gesture controls the touch point; otherwise, false.\n /// \n public bool HasTouch(ITouch touch)\n {\n return activeTouches.Contains(touch);\n }\n\n /// \n /// Determines whether this instance can prevent the specified gesture.\n /// \n /// The gesture.\n /// \n /// true if this instance can prevent the specified gesture; otherwise, false.\n /// \n public virtual bool CanPreventGesture(Gesture gesture)\n {\n if (Delegate == null)\n {\n if (gesture.CanBePreventedByGesture(this)) return !IsFriendly(gesture);\n return false;\n }\n return !Delegate.ShouldRecognizeSimultaneously(this, gesture);\n }\n\n /// \n /// Determines whether this instance can be prevented by specified gesture.\n /// \n /// The gesture.\n /// \n /// true if this instance can be prevented by specified gesture; otherwise, false.\n /// \n public virtual bool CanBePreventedByGesture(Gesture gesture)\n {\n if (Delegate == null) return !IsFriendly(gesture);\n return !Delegate.ShouldRecognizeSimultaneously(this, gesture);\n }\n\n /// \n /// Specifies if gesture can receive this specific touch point.\n /// \n /// The touch.\n /// true if this touch should be received by the gesture; otherwise, false.\n public virtual bool ShouldReceiveTouch(ITouch touch)\n {\n if (Delegate == null) return true;\n return Delegate.ShouldReceiveTouch(this, touch);\n }\n\n /// \n /// Specifies if gesture can begin or recognize.\n /// \n /// true if gesture should begin; otherwise, false.\n public virtual bool ShouldBegin()\n {\n if (Delegate == null) return true;\n return Delegate.ShouldBegin(this);\n }\n\n #endregion\n\n #region Unity methods\n\n /// \n protected virtual void Awake()\n {\n cachedTransform = GetComponent();\n\n foreach (var gesture in friendlyGestures)\n {\n AddFriendlyGesture(gesture);\n }\n RequireGestureToFail = requireGestureToFail;\n }\n\n /// \n /// Unity3d Start handler.\n /// \n protected virtual void OnEnable()\n {\n // TouchManager might be different in another scene\n touchManager = TouchManager.Instance;\n gestureManagerInstance = GestureManager.Instance as GestureManagerInstance;\n\n if (touchManager == null) Debug.LogError(\"No TouchManager found! Please add an instance of TouchManager to the scene!\");\n if (gestureManagerInstance == null) Debug.LogError(\"No GesturehManager found! Please add an instance of GesturehManager to the scene!\");\n\n if (sendMessageTarget == null) sendMessageTarget = gameObject;\n Reset();\n }\n\n /// \n /// Unity3d OnDisable handler.\n /// \n protected virtual void OnDisable()\n {\n setState(GestureState.Failed);\n }\n\n /// \n /// Unity3d OnDestroy handler.\n /// \n protected virtual void OnDestroy()\n {\n var copy = new List(friendlyGestures);\n foreach (var gesture in copy)\n {\n RemoveFriendlyGesture(gesture);\n }\n RequireGestureToFail = null;\n }\n\n #endregion\n\n #region Internal functions\n\n internal void SetState(GestureState value)\n {\n setState(value);\n }\n\n internal void Reset()\n {\n activeTouches.Clear();\n delayedStateChange = GestureState.Possible;\n requiredGestureFailed = false;\n reset();\n }\n\n internal void TouchesBegan(IList touches)\n {\n activeTouches.AddRange(touches);\n touchesBegan(touches);\n }\n\n internal void TouchesMoved(IList touches)\n {\n touchesMoved(touches);\n }\n\n internal void TouchesEnded(IList touches)\n {\n for (var i = 0; i < touches.Count; i++) activeTouches.Remove(touches[i]);\n touchesEnded(touches);\n }\n\n internal void TouchesCancelled(IList touches)\n {\n for (var i = 0; i < touches.Count; i++) activeTouches.Remove(touches[i]);\n touchesCancelled(touches);\n }\n\n internal virtual void RemoveFriendlyGesture(Gesture gesture)\n {\n if (gesture == null || gesture == this) return;\n\n unregisterFriendlyGesture(gesture);\n gesture.unregisterFriendlyGesture(this);\n }\n\n #endregion\n\n #region Protected methods\n\n /// \n /// Should the gesture cache this touch to use it later in calculation of .\n /// \n /// Touch to cache.\n /// true if touch should be cached; false otherwise.\n protected virtual bool shouldCacheTouchPosition(ITouch value)\n {\n return true;\n }\n\n /// \n /// Tries to change gesture state.\n /// \n /// New state.\n /// true if state was changed; otherwise, false.\n protected bool setState(GestureState value)\n {\n if (gestureManagerInstance == null) return false;\n if (requireGestureToFail != null)\n {\n switch (value)\n {\n case GestureState.Recognized:\n case GestureState.Began:\n if (!requiredGestureFailed)\n {\n delayedStateChange = value;\n return false;\n }\n break;\n case GestureState.Possible:\n case GestureState.Failed:\n case GestureState.Cancelled:\n delayedStateChange = GestureState.Possible;\n break;\n }\n }\n\n var newState = gestureManagerInstance.GestureChangeState(this, value);\n State = newState;\n\n return value == newState;\n }\n\n #endregion\n\n #region Callbacks\n\n /// \n /// Called when new touches appear.\n /// \n /// The touches.\n protected virtual void touchesBegan(IList touches) {}\n\n /// \n /// Called for moved touches.\n /// \n /// The touches.\n protected virtual void touchesMoved(IList touches) {}\n\n /// \n /// Called if touches are removed.\n /// \n /// The touches.\n protected virtual void touchesEnded(IList touches)\n {\n if (combineTouches)\n {\n foreach (var touch in touches)\n {\n touchSequence.Add(touch);\n }\n\n if (activeTouches.Count == 0)\n {\n // Checking which points were removed in clusterExistenceTime seconds to set their centroid as cached screen position\n var cluster = touchSequence.FindElementsLaterThan(Time.time - combineTouchesInterval, shouldCacheTouchPosition);\n cachedScreenPosition = ClusterUtils.Get2DCenterPosition(cluster);\n cachedPreviousScreenPosition = ClusterUtils.GetPrevious2DCenterPosition(cluster);\n }\n }\n else\n {\n if (activeTouches.Count == 0)\n {\n var lastPoint = touches[touches.Count - 1];\n if (shouldCacheTouchPosition(lastPoint))\n {\n cachedScreenPosition = lastPoint.Position;\n cachedPreviousScreenPosition = lastPoint.PreviousPosition;\n }\n else\n {\n cachedScreenPosition = TouchManager.INVALID_POSITION;\n cachedPreviousScreenPosition = TouchManager.INVALID_POSITION;\n }\n }\n }\n }\n\n /// \n /// Called when touches are cancelled.\n /// \n /// The touches.\n protected virtual void touchesCancelled(IList touches) {}\n\n /// \n /// Called to reset gesture state after it fails or recognizes.\n /// \n protected virtual void reset()\n {", "answers": [" cachedScreenPosition = TouchManager.INVALID_POSITION;"], "length": 2205, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "498d686a-3834-425a-8027-dafea35b5d33", "reasoning": "In the internal Reset() method, after clearing activeTouches and resetting delayedStateChange and requiredGestureFailed, it calls the protected virtual reset() to finish resetting the gesture. The typical next operation is to clear cached screen positions, setting them to the invalid sentinel value from TouchManager. Therefore the first line inside reset() should assign TouchManager.INVALID_POSITION to cachedScreenPosition.", "reasoning_model_answer": "cachedScreenPosition = TouchManager.INVALID_POSITION;", "assistant_with_reasoning": "\nIn the internal Reset() method, after clearing activeTouches and resetting delayedStateChange and requiredGestureFailed, it calls the protected virtual reset() to finish resetting the gesture. The typical next operation is to clear cached screen positions, setting them to the invalid sentinel value from TouchManager. Therefore the first line inside reset() should assign TouchManager.INVALID_POSITION to cachedScreenPosition.\n\ncachedScreenPosition = TouchManager.INVALID_POSITION;", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 5.574, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 25160, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "cachedScreenPosition = TouchManager.INVALID_POSITION;", "score": 0.9, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/*\nCopyright 2010 Google Inc\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nusing System;\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.ComponentModel;\nusing System.IO;\nusing System.Net;\nusing System.Text;\nusing System.Threading;\nusing Google.Apis.Authentication;\nusing Google.Apis.Discovery;\nusing Google.Apis.Logging;\nusing Google.Apis.Testing;\nusing Google.Apis.Util;\n\n#if !SILVERLIGHT\nusing System.IO.Compression;\n#endif\n\nnamespace Google.Apis.Requests\n{\n /// \n /// Request to a service.\n /// \n /// \n /// Features which are not (yet) supported on SilverLight:\n /// - The UserAgent header.\n /// - GZip Compression\n /// \n public class Request : IRequest\n {\n private const string UserAgent = \"{0} google-api-dotnet-client/{1} {2}/{3}\";\n private const string GZipUserAgentSuffix = \" (gzip)\";\n private const string GZipEncoding = \"gzip\";\n\n /// \n /// The charset used for content encoding.\n /// \n public static readonly Encoding ContentCharset = Encoding.UTF8;\n\n private static readonly ILogger logger = ApplicationContext.Logger.ForType();\n\n public const string DELETE = \"DELETE\";\n public const string GET = \"GET\";\n public const string PATCH = \"PATCH\";\n public const string POST = \"POST\";\n public const string PUT = \"PUT\";\n\n /// \n /// Defines the maximum number of retries which should be made if a request fails.\n /// \n public int MaximumRetries { get; set; }\n\n /// \n /// Defines the factor by which the waiting time is multiplied between retry attempts.\n /// \n public double RetryWaitTimeIncreaseFactor { get; set; }\n\n /// \n /// Defines the initial waiting time, which is used once the first retry has failed.\n /// \n public int RetryInitialWaitTime { get; set; }\n\n private static readonly String ApiVersion = Utilities.GetLibraryVersion();\n\n public static readonly ReadOnlyCollection SupportedHttpMethods =\n new List { POST, PUT, DELETE, GET, PATCH }.AsReadOnly();\n\n private string applicationName;\n\n public Request()\n {\n applicationName = Utilities.GetAssemblyTitle() ?? \"Unknown_Application\";\n Authenticator = new NullAuthenticator();\n WebRequestFactory = new HttpRequestFactory();\n Parameters = new ParameterCollection();\n\n MaximumRetries = 3;\n RetryWaitTimeIncreaseFactor = 2.0;\n RetryInitialWaitTime = 1000;\n }\n\n /// \n /// The authenticator used for this request.\n /// \n internal IAuthenticator Authenticator { get; private set; }\n\n /// \n /// The developer API Key sent along with the request.\n /// \n internal String DeveloperKey { get; private set; }\n\n /// \n /// Set of method parameters.\n /// \n [VisibleForTestOnly]\n internal ParameterCollection Parameters { get; set; }\n\n /// \n /// The application name used within the user agent string.\n /// \n [VisibleForTestOnly]\n internal string ApplicationName\n {\n get { return applicationName; }\n }\n\n private IService Service { get; set; }\n private IMethod Method { get; set; }\n private Uri BaseURI { get; set; }\n private string RPCName { get; set; } // note: this property is apparently never used\n private string Body { get; set; }\n private ReturnType ReturnType { get; set; }\n private ETagAction ETagAction { get; set; }\n private string ETag { get; set; }\n private string FieldsMask { get; set; }\n private string UserIp { get; set; }\n private string QuotaUser { get; set; }\n\n /// \n /// Defines whether this request can be sent multiple times.\n /// \n public bool SupportsRetry\n {\n get { return true; }\n }\n\n #region IRequest Members\n\n /// \n /// The method to call\n /// \n /// \n /// A \n /// \n public IRequest On(string rpcName)\n {\n RPCName = rpcName;\n\n return this;\n }\n\n /// \n /// Sets the type of data that is expected to be returned from the request.\n /// \n /// Defaults to Json.\n /// \n /// \n /// A \n /// \n /// \n /// A \n /// \n public IRequest Returning(ReturnType returnType)\n {\n ReturnType = returnType;\n return this;\n }\n\n /// \n /// Adds the parameters to the request.\n /// \n /// \n /// A \n /// \n public IRequest WithParameters(IDictionary parameters)\n {\n Parameters = ParameterCollection.FromDictionary(parameters);\n return this;\n }\n\n /// \n /// Adds the parameters to the request.\n /// \n /// \n /// A \n /// \n public IRequest WithParameters(IEnumerable> parameters)\n {\n Parameters = new ParameterCollection(parameters);\n return this;\n }\n\n /// \n /// Parses the specified querystring and adds these parameters to the request\n /// \n public IRequest WithParameters(string parameters)\n {\n Parameters = ParameterCollection.FromQueryString(parameters);\n return this;\n }\n\n /// \n /// Uses the string provied as the body of the request.\n /// \n public IRequest WithBody(string body)\n {\n Body = body;\n return this;\n }\n\n /// \n /// Uses the provided authenticator to add authentication information to this request.\n /// \n public IRequest WithAuthentication(IAuthenticator authenticator)\n {\n authenticator.ThrowIfNull(\"Authenticator\");\n Authenticator = authenticator;\n return this;\n }\n\n /// \n /// Adds the developer key to this request.\n /// \n public IRequest WithKey(string key)\n {\n DeveloperKey = key;\n return this;\n }\n\n /// \n /// Sets the ETag-behavior of this request.\n /// \n public IRequest WithETagAction(ETagAction action)\n {\n ETagAction = action;\n return this;\n }\n\n /// \n /// Adds an ETag to this request.\n /// \n public IRequest WithETag(string etag)\n {\n ETag = etag;\n return this;\n }\n\n /// \n /// Container struct for the asynchronous execution of a request.\n /// \n private struct AsyncExecutionState\n {\n /// \n /// The current try we are in. 1 based.\n /// \n public int Try;\n\n /// \n /// The time we will wait between the current and the next request if the current one fails.\n /// \n public double WaitTime;\n\n /// \n /// The method which will be called once the request has been completed.\n /// \n public Action ResponseHandler;\n\n /// \n /// The request which is currently being executed.\n /// \n public WebRequest CurrentRequest;\n }\n\n /// \n /// Represents the result of an asynchronous Request.\n /// \n private class AsyncRequestResult : IAsyncRequestResult\n {\n private readonly IResponse response;\n private readonly GoogleApiRequestException exception;\n\n public AsyncRequestResult(IResponse response)\n {\n this.response = response;\n }\n\n public AsyncRequestResult(GoogleApiRequestException exception)\n {\n this.exception = exception;\n }\n\n public IResponse GetResponse()\n {\n if (exception != null) // Request failed.\n {\n throw exception;\n }\n\n return response; // Request succeeded.\n }\n }\n\n /// \n /// Begins executing a request based upon the current execution state.\n /// \n /// Does not check preconditions.\n private void InternalBeginExecuteRequest(AsyncExecutionState state)\n {\n state.CurrentRequest.BeginGetResponse(InternalEndExecuteRequest, state);\n }\n\n /// \n /// Ends executing an asynchronous request.\n /// \n private void InternalEndExecuteRequest(IAsyncResult asyncResult)\n {\n AsyncExecutionState state = (AsyncExecutionState)asyncResult.AsyncState;\n AsyncRequestResult asyncRequestResult = null;\n bool retried = false;\n try\n {\n asyncRequestResult = new AsyncRequestResult(new Response(\n state.CurrentRequest.EndGetResponse(asyncResult)));\n }\n catch (WebException ex)\n {\n // Returns null if the attempt was retried.\n retried = HandleFailedRequest(state, ex, out asyncRequestResult);\n }\n catch (Exception ex) // Unknown exception.\n {\n asyncRequestResult = new AsyncRequestResult(\n new GoogleApiRequestException(Service, this, null, ex));\n }\n finally\n {\n // If the async result is null, this indicates that the request was retried.\n // Another handler will be executed to respond to that attempt, so do not\n // call the handler yet.\n if (!retried)\n state.ResponseHandler(asyncRequestResult);\n }\n }\n\n /// \n /// Handles a failed request, and tries to fix it if possible.\n /// \n /// \n /// Can not throw an exception.\n /// \n /// \n /// Returns true if the request was handled and is being retried.\n /// Returns false if the request could not be retried.\n /// \n private bool HandleFailedRequest(AsyncExecutionState state,\n WebException exception, out AsyncRequestResult asyncRequestResult)\n {\n try\n {\n RequestError error = null;\n // Try to get an error response object.\n if (exception.Response != null)\n {\n IResponse errorResponse = new Response(exception.Response);\n error = Service.DeserializeError(errorResponse);\n }\n\n // Try to handle the response somehow.\n if (SupportsRetry && state.Try < MaximumRetries)\n {\n // Wait some time before sending another request.\n Thread.Sleep((int)state.WaitTime);\n state.WaitTime *= RetryWaitTimeIncreaseFactor;\n state.Try++;\n\n foreach (IErrorResponseHandler handler in GetErrorResponseHandlers())\n {\n if (handler.CanHandleErrorResponse(exception, error))\n {\n // The provided handler was able to handle this error. Retry sending the request.\n handler.HandleErrorResponse(exception, error, state.CurrentRequest);\n logger.Warning(\"Retrying request [{0}]\", this);\n\n // Begin a new request and when it is completed being assembled, execute it \n // asynchronously.\n state.CurrentRequest = CreateWebRequest((request) =>\n {\n InternalBeginExecuteRequest(state);\n });\n // Signal that this begin/end request pair has no result because it has been retried.\n asyncRequestResult = null;\n return true;\n }\n }\n }\n\n // Retrieve additional information about the http response (if applicable).\n HttpStatusCode status = 0;\n HttpWebResponse httpResponse = exception.Response as HttpWebResponse;\n if (httpResponse != null)\n {\n status = httpResponse.StatusCode;\n }\n\n // We were unable to handle the exception. Throw it wrapped in a GoogleApiRequestException.\n asyncRequestResult = new AsyncRequestResult(\n new GoogleApiRequestException(Service, this, error, exception) { HttpStatusCode = status });\n }\n catch (Exception)\n {\n asyncRequestResult = new AsyncRequestResult(\n new GoogleApiRequestException(Service, this, null, exception));\n }\n return false;\n }\n\n /// \n /// Executes the request asynchronously, and calls the specified delegate once done.\n /// \n /// The method to call once a response has been received.\n public void ExecuteRequestAsync(Action responseHandler)\n {\n // Validate the input.\n var validator = new MethodValidator(Method, Parameters);\n if (validator.ValidateAllParameters() == false)\n {\n throw new InvalidOperationException(\"Request parameter validation failed for [\" + this + \"]\");\n }\n\n // Begin a new request and when it is completed being assembled, execute it asynchronously.\n CreateWebRequest((request) =>\n {\n // When the request is completed constructing, execute it.\n var state = new AsyncExecutionState()\n {\n ResponseHandler = responseHandler,\n Try = 1,\n WaitTime = RetryInitialWaitTime,\n CurrentRequest = request\n };\n InternalBeginExecuteRequest(state);\n });\n }\n\n /// \n /// Executes a request given the configuration options supplied.\n /// \n /// \n /// A \n /// \n public IResponse ExecuteRequest()\n {\n AutoResetEvent waitHandle = new AutoResetEvent(false);\n IAsyncRequestResult result = null;\n ExecuteRequestAsync(r =>\n {\n result = r;\n waitHandle.Set();\n });\n waitHandle.WaitOne();\n return result.GetResponse();\n }\n\n #endregion\n\n /// \n /// Returns all error response handlers associated with this request.\n /// \n [VisibleForTestOnly]\n internal IEnumerable GetErrorResponseHandlers()\n {\n // Check if the current authenticator can handle error responses.\n IErrorResponseHandler authenticator = Authenticator as IErrorResponseHandler;\n if (authenticator != null)\n {\n yield return authenticator;\n }\n }\n\n /// \n /// Given an API method, create the appropriate Request for it.\n /// \n public static IRequest CreateRequest(IService service, IMethod method)\n {\n switch (method.HttpMethod)\n {\n case GET:\n case PUT:\n case POST:\n case DELETE:\n case PATCH:\n return new Request { Service = service, Method = method, BaseURI = service.BaseUri };\n default:\n throw new NotSupportedException(\n string.Format(\n \"The HttpMethod[{0}] of Method[{1}] in Service[{2}] was not supported\", method.HttpMethod,\n method.Name, service.Name));\n }\n }\n\n /// \n /// Sets the Application name on the UserAgent String.\n /// \n /// \n /// A \n /// \n public IRequest WithAppName(string name)\n {\n applicationName = name;\n return this;\n }\n\n /// \n /// Specifies the partial field mask of this method. \n /// The response of this request will only contain the fields specified in this mask.\n /// \n /// Selector specifying which fields to include in a partial response.\n public IRequest WithFields(string mask)\n {\n FieldsMask = mask;\n return this;\n }\n\n /// \n /// IP address of the site where the request originates. Use this if you want to enforce per-user limits.\n /// \n public IRequest WithUserIp(string userIp)\n {\n UserIp = userIp;\n return this;\n }\n\n /// \n /// Available to use for quota purposes for server-side applications.\n /// Can be any arbitrary string assigned to a user, but should not exceed 40 characters.\n /// Overrides UserIp if both are provided.\n /// \n public IRequest WithQuotaUser(string quotaUser)\n {\n QuotaUser = quotaUser;\n return this;\n }\n\n /// \n /// Builds the resulting Url for the whole request.\n /// \n [VisibleForTestOnly]\n internal HttpWebRequest BuildRequest()\n {\n var requestBuilder = new HttpWebRequestBuilder()\n {\n BaseUri = Service.BaseUri,\n Path = Method.RestPath,\n Method = Method.HttpMethod,\n };\n\n requestBuilder.AddParameter(RequestParameterType.Query, \"alt\",\n ReturnType == ReturnType.Json?\"json\":\"atom\");\n\n requestBuilder.AddParameter(RequestParameterType.Query, \"key\", DeveloperKey);\n requestBuilder.AddParameter(RequestParameterType.Query, \"fields\", FieldsMask);\n requestBuilder.AddParameter(RequestParameterType.Query, \"userIp\", UserIp);\n requestBuilder.AddParameter(RequestParameterType.Query, \"quotaUser\", QuotaUser);\n\n // Replace the substitution parameters.\n foreach (var parameter in Parameters)\n {\n IParameter parameterDefinition;// = Method.Parameters[parameter.Key];\n\n if (!(Method.Parameters.TryGetValue(parameter.Key, out parameterDefinition)\n || Service.Parameters.TryGetValue(parameter.Key, out parameterDefinition)\n ))\n {\n throw new GoogleApiException(Service,\n String.Format(\"Invalid parameter \\\"{0}\\\" specified.\", parameter.Key));\n }\n \n string value = parameter.Value;\n if (value.IsNullOrEmpty()) // If the parameter is present and has no value, use the default.\n {\n value = parameterDefinition.DefaultValue;\n }\n switch (parameterDefinition.ParameterType)\n {\n case \"path\":\n requestBuilder.AddParameter(RequestParameterType.Path, parameter.Key, value);\n break;\n case \"query\":\n // If the parameter is optional and no value is given, don't add to url.\n if (parameterDefinition.IsRequired && String.IsNullOrEmpty(value))\n {\n throw new GoogleApiException(Service,\n String.Format(\"Required parameter \\\"{0}\\\" missing.\", parameter.Key));\n }\n requestBuilder.AddParameter(RequestParameterType.Query, \n parameter.Key, value);\n break;\n default:\n throw new NotSupportedException(\n \"Found an unsupported Parametertype [\" + parameterDefinition.ParameterType + \"]\");\n }\n }\n\n return requestBuilder.GetWebRequest();\n }\n\n private static string GetReturnMimeType(ReturnType returnType)\n {\n switch (returnType)\n {\n case ReturnType.Atom:\n return \"application/atom+xml\";\n case ReturnType.Json:\n return \"application/json\";\n default:\n throw new ArgumentOutOfRangeException(\"returnType\", \"Unknown Return-type: \" + returnType);\n }\n }\n\n /// \n /// Returns the default ETagAction for a specific http verb.\n /// \n [VisibleForTestOnly]\n internal static ETagAction GetDefaultETagAction(string httpVerb)\n {\n switch (httpVerb)\n {\n default:\n return ETagAction.Ignore;\n\n case GET: // Incoming data should only be updated if it has been changed on the server.\n return ETagAction.IfNoneMatch;\n\n case PUT: // Outgoing data should only be commited if it hasn't been changed on the server.\n case POST:\n case PATCH:\n case DELETE:\n return ETagAction.IfMatch;\n }\n }\n\n private ICreateHttpRequest webRequestFactory;\n\n /// \n /// Factory used to create HttpWebRequest objects.\n /// \n public ICreateHttpRequest WebRequestFactory \n {\n get\n {\n return this.webRequestFactory;\n }\n set\n {\n value.ThrowIfNull(\"HttpRequestFactory\");\n this.webRequestFactory = value;\n }\n }\n\n /// \n /// Creates the ready-to-send WebRequest containing all the data specified in this request class.\n /// \n /// An action to execute when the request has been prepared.\n [VisibleForTestOnly]\n internal WebRequest CreateWebRequest(Action onRequestReady)\n {\n HttpWebRequest request = BuildRequest();\n\n // Create the request.\n Authenticator.ApplyAuthenticationToRequest(request);\n\n // Insert the content type and user agent.\n request.ContentType = string.Format(\n \"{0}; charset={1}\", GetReturnMimeType(ReturnType), ContentCharset.WebName);\n string appName = FormatForUserAgent(ApplicationName);\n string apiVersion = FormatForUserAgent(ApiVersion);\n string platform = FormatForUserAgent(Environment.OSVersion.Platform.ToString());\n string platformVer = FormatForUserAgent(Environment.OSVersion.Version.ToString());\n\n // The UserAgent header can only be set on a non-Silverlight platform.\n // Silverlight uses the user agent of the browser instead.\n#if !SILVERLIGHT\n request.UserAgent = String.Format(UserAgent, appName, apiVersion, platform, platformVer);\n#endif\n\n // Add the E-tag header:", "answers": [" if (!string.IsNullOrEmpty(ETag))"], "length": 2274, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "2730aa61-be2b-4ba9-99c4-9dd68818cb7f", "reasoning": "After setting content type, user agent, the code needs to add any ETag header before sending the request. The typical pattern is to check if an ETag value is present and then add the appropriate header based on the ETagAction. Therefore the next line starts the conditional that checks for a non‑empty ETag.", "reasoning_model_answer": "if (!string.IsNullOrEmpty(ETag))", "assistant_with_reasoning": "\nAfter setting content type, user agent, the code needs to add any ETag header before sending the request. The typical pattern is to check if an ETag value is present and then add the appropriate header based on the ETagAction. Therefore the next line starts the conditional that checks for a non‑empty ETag.\n\nif (!string.IsNullOrEmpty(ETag))", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 6.95, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 25366, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "if (!string.IsNullOrEmpty(ETag))", "score": 0.84, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/*\n *\n * * Copyright 2010-2016 OrientDB LTD (http://orientdb.com)\n * *\n * * Licensed under the Apache License, Version 2.0 (the \"License\");\n * * you may not use this file except in compliance with the License.\n * * You may obtain a copy of the License at\n * *\n * * http://www.apache.org/licenses/LICENSE-2.0\n * *\n * * Unless required by applicable law or agreed to in writing, software\n * * distributed under the License is distributed on an \"AS IS\" BASIS,\n * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * * See the License for the specific language governing permissions and\n * * limitations under the License.\n * *\n * * For more information: http://orientdb.com\n *\n */\npackage com.orientechnologies.orient.server.distributed.impl;\n\nimport static com.orientechnologies.orient.core.config.OGlobalConfiguration.DISTRIBUTED_ATOMIC_LOCK_TIMEOUT;\nimport static com.orientechnologies.orient.core.config.OGlobalConfiguration.DISTRIBUTED_TRANSACTION_SEQUENCE_SET_SIZE;\nimport static com.orientechnologies.orient.server.distributed.ODistributedServerLog.DIRECTION.OUT;\n\nimport com.orientechnologies.common.concur.OOfflineNodeException;\nimport com.orientechnologies.common.concur.lock.OInterruptedException;\nimport com.orientechnologies.common.log.OLogManager;\nimport com.orientechnologies.common.profiler.OAbstractProfiler;\nimport com.orientechnologies.common.profiler.OProfiler;\nimport com.orientechnologies.common.util.OCallable;\nimport com.orientechnologies.orient.core.Orient;\nimport com.orientechnologies.orient.core.config.OGlobalConfiguration;\nimport com.orientechnologies.orient.core.db.ODatabaseDocumentInternal;\nimport com.orientechnologies.orient.core.db.OSystemDatabase;\nimport com.orientechnologies.orient.core.db.OrientDBDistributed;\nimport com.orientechnologies.orient.core.id.ORID;\nimport com.orientechnologies.orient.core.storage.impl.local.OAbstractPaginatedStorage;\nimport com.orientechnologies.orient.core.storage.impl.local.OSyncSource;\nimport com.orientechnologies.orient.core.tx.OTransactionId;\nimport com.orientechnologies.orient.core.tx.OTransactionSequenceStatus;\nimport com.orientechnologies.orient.core.tx.OTxMetadataHolder;\nimport com.orientechnologies.orient.core.tx.ValidationResult;\nimport com.orientechnologies.orient.server.OServer;\nimport com.orientechnologies.orient.server.distributed.*;\nimport com.orientechnologies.orient.server.distributed.ODistributedServerLog.DIRECTION;\nimport com.orientechnologies.orient.server.distributed.ODistributedServerManager.DB_STATUS;\nimport com.orientechnologies.orient.server.distributed.impl.lock.OFreezeGuard;\nimport com.orientechnologies.orient.server.distributed.impl.lock.OLockGuard;\nimport com.orientechnologies.orient.server.distributed.impl.lock.OLockManager;\nimport com.orientechnologies.orient.server.distributed.impl.lock.OLockManagerImpl;\nimport com.orientechnologies.orient.server.distributed.impl.lock.OTxPromiseManager;\nimport com.orientechnologies.orient.server.distributed.impl.lock.OnLocksAcquired;\nimport com.orientechnologies.orient.server.distributed.impl.task.OLockKeySource;\nimport com.orientechnologies.orient.server.distributed.impl.task.OUnreachableServerLocalTask;\nimport com.orientechnologies.orient.server.distributed.impl.task.transaction.OTransactionUniqueKey;\nimport com.orientechnologies.orient.server.distributed.task.ORemoteTask;\nimport java.util.Collections;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Optional;\nimport java.util.Set;\nimport java.util.SortedSet;\nimport java.util.TimerTask;\nimport java.util.concurrent.ConcurrentHashMap;\nimport java.util.concurrent.LinkedBlockingQueue;\nimport java.util.concurrent.RejectedExecutionException;\nimport java.util.concurrent.ThreadFactory;\nimport java.util.concurrent.ThreadPoolExecutor;\nimport java.util.concurrent.TimeUnit;\nimport java.util.concurrent.atomic.AtomicLong;\n\n/**\n * Distributed database implementation. There is one instance per database. Each node creates own\n * instance to talk with each others.\n *\n * @author Luca Garulli (l.garulli--at--orientechnologies.com)\n */\npublic class ODistributedDatabaseImpl implements ODistributedDatabase {\n public static final String DISTRIBUTED_SYNC_JSON_FILENAME = \"distributed-sync.json\";\n protected final ODistributedPlugin manager;\n protected final ODistributedMessageServiceImpl msgService;\n protected final String databaseName;\n private final String localNodeName;\n private final OTxPromiseManager recordPromiseManager;\n private final OTxPromiseManager indexKeyPromiseManager;\n private final AtomicLong pending = new AtomicLong();\n private final ODistributedConfigurationManager configurationManager;\n protected Map activeTxContexts =\n new ConcurrentHashMap<>(64);\n private AtomicLong totalSentRequests = new AtomicLong();\n private AtomicLong totalReceivedRequests = new AtomicLong();\n private TimerTask txTimeoutTask = null;\n private volatile boolean running = true;\n private volatile boolean parsing = true;\n private AtomicLong operationsRunnig = new AtomicLong(0);\n private ODistributedSynchronizedSequence sequenceManager;\n private ThreadPoolExecutor requestExecutor;\n private OLockManager lockManager = new OLockManagerImpl();\n private Set inQueue = Collections.newSetFromMap(new ConcurrentHashMap<>());\n private OSyncSource lastValidBackup;\n private volatile DB_STATUS freezePrevStatus;\n private OFreezeGuard freezeGuard;\n\n public ODistributedDatabaseImpl(\n final ODistributedPlugin manager,\n final ODistributedMessageServiceImpl msgService,\n final String iDatabaseName,\n OServer server) {\n this.manager = manager;\n this.msgService = msgService;\n this.databaseName = iDatabaseName;\n this.localNodeName = manager.getLocalNodeName();\n this.configurationManager = new ODistributedConfigurationManager(manager, iDatabaseName);\n\n // SELF REGISTERING ITSELF HERE BECAUSE IT'S NEEDED FURTHER IN THE CALL CHAIN\n final ODistributedDatabaseImpl prev = msgService.databases.put(iDatabaseName, this);\n if (prev != null) {\n // KILL THE PREVIOUS ONE\n prev.shutdown();\n }\n\n startAcceptingRequests();\n\n if (iDatabaseName.equals(OSystemDatabase.SYSTEM_DB_NAME)) {\n recordPromiseManager = null;\n indexKeyPromiseManager = null;\n return;\n }\n\n startTxTimeoutTimerTask();\n\n Orient.instance()\n .getProfiler()\n .registerHookValue(\n \"distributed.db.\" + databaseName + \".msgSent\",\n \"Number of replication messages sent from current node\",\n OProfiler.METRIC_TYPE.COUNTER,\n new OAbstractProfiler.OProfilerHookValue() {\n @Override\n public Object getValue() {\n return totalSentRequests.get();\n }\n },\n \"distributed.db.*.msgSent\");\n\n Orient.instance()\n .getProfiler()\n .registerHookValue(\n \"distributed.db.\" + databaseName + \".msgReceived\",\n \"Number of replication messages received from external nodes\",\n OProfiler.METRIC_TYPE.COUNTER,\n new OAbstractProfiler.OProfilerHookValue() {\n @Override\n public Object getValue() {\n return totalReceivedRequests.get();\n }\n },\n \"distributed.db.*.msgReceived\");\n\n Orient.instance()\n .getProfiler()\n .registerHookValue(\n \"distributed.db.\" + databaseName + \".activeContexts\",\n \"Number of active distributed transactions\",\n OProfiler.METRIC_TYPE.COUNTER,\n new OAbstractProfiler.OProfilerHookValue() {\n @Override\n public Object getValue() {\n return (long) activeTxContexts.size();\n }\n },\n \"distributed.db.*.activeContexts\");\n\n Orient.instance()\n .getProfiler()\n .registerHookValue(\n \"distributed.db.\" + databaseName + \".workerThreads\",\n \"Number of worker threads\",\n OProfiler.METRIC_TYPE.COUNTER,\n new OAbstractProfiler.OProfilerHookValue() {\n @Override\n public Object getValue() {\n return (long) requestExecutor.getPoolSize();\n }\n },\n \"distributed.db.*.workerThreads\");\n\n Orient.instance()\n .getProfiler()\n .registerHookValue(\n \"distributed.db.\" + databaseName + \".recordLocks\",\n \"Number of records locked\",\n OProfiler.METRIC_TYPE.COUNTER,\n new OAbstractProfiler.OProfilerHookValue() {\n @Override\n public Object getValue() {\n return recordPromiseManager.size() + indexKeyPromiseManager.size();\n }\n },\n \"distributed.db.*.recordLocks\");\n\n long timeout =\n manager\n .getServerInstance()\n .getContextConfiguration()\n .getValueAsLong(DISTRIBUTED_ATOMIC_LOCK_TIMEOUT);\n int sequenceSize =\n manager\n .getServerInstance()\n .getContextConfiguration()\n .getValueAsInteger(DISTRIBUTED_TRANSACTION_SEQUENCE_SET_SIZE);\n recordPromiseManager = new OTxPromiseManager<>();\n indexKeyPromiseManager = new OTxPromiseManager<>();\n sequenceManager = new ODistributedSynchronizedSequence(localNodeName, sequenceSize);\n }\n\n public static boolean sendResponseBack(\n final Object current,\n final ODistributedServerManager manager,\n final ODistributedRequestId iRequestId,\n Object responsePayload) {\n\n if (iRequestId.getMessageId() < 0)\n // INTERNAL MSG\n return true;\n\n final String local = manager.getLocalNodeName();\n\n final String sender = manager.getNodeNameById(iRequestId.getNodeId());\n\n final ODistributedResponse response =\n new ODistributedResponse(null, iRequestId, local, sender, responsePayload);\n\n // TODO: check if using remote channel for local node still makes sense\n // if (!senderNodeName.equalsIgnoreCase(manager.getLocalNodeName()))\n try {\n // GET THE SENDER'S RESPONSE QUEUE\n final ORemoteServerController remoteSenderServer = manager.getRemoteServer(sender);\n\n ODistributedServerLog.debug(\n current, local, sender, OUT, \"Sending response %s back (reqId=%s)\", response, iRequestId);\n\n remoteSenderServer.sendResponse(response);\n\n } catch (Exception e) {\n ODistributedServerLog.debug(\n current,\n local,\n sender,\n OUT,\n \"Error on sending response '%s' back (reqId=%s err=%s)\",\n response,\n iRequestId,\n e.toString());\n return false;\n }\n\n return true;\n }\n\n public OTxPromiseManager getRecordPromiseManager() {\n return recordPromiseManager;\n }\n\n public OTxPromiseManager getIndexKeyPromiseManager() {\n return indexKeyPromiseManager;\n }\n\n public void startOperation() {\n waitDistributedIsReady();\n operationsRunnig.incrementAndGet();\n }\n\n public void endOperation() {\n operationsRunnig.decrementAndGet();\n }\n\n @Override\n public void waitForOnline() {\n try {\n synchronized (this) {\n if (!this.parsing) {\n this.wait(OGlobalConfiguration.DISTRIBUTED_MAX_STARTUP_DELAY.getValueAsLong());\n if (!this.parsing) {\n throw new OOfflineNodeException(\"Node is offline\");\n }\n }\n }\n } catch (InterruptedException e) {\n Thread.currentThread().interrupt();\n // IGNORE IT\n }\n }\n\n public void reEnqueue(\n final int senderNodeId,\n final long msgSequence,\n final String databaseName,\n final ORemoteTask payload,\n int retryCount,\n int autoRetryDelay) {\n pending.incrementAndGet();\n Orient.instance()\n .scheduleTask(\n () -> {\n try {\n processRequest(\n new ODistributedRequest(\n getManager(), senderNodeId, msgSequence, databaseName, payload),\n false);\n } finally {\n pending.decrementAndGet();\n }\n },\n autoRetryDelay * retryCount,\n 0);\n }\n\n /**\n * Distributed requests against the available workers by using one queue per worker. This\n * guarantee the sequence of the operations against the same record cluster.\n */\n public void processRequest(\n final ODistributedRequest request, final boolean waitForAcceptingRequests) {\n if (!running) {\n throw new ODistributedException(\n \"Server is going down or is removing the database:'\"\n + getDatabaseName()\n + \"' discarding\");\n }\n\n final ORemoteTask task = request.getTask();\n if (waitForAcceptingRequests) {\n waitIsReady(task);\n\n if (!running) {\n throw new ODistributedException(\n \"Server is going down or is removing the database:'\"\n + getDatabaseName()\n + \"' discarding\");\n }\n }\n synchronized (this) {\n task.received(request, this);\n manager.messageReceived(request);\n\n totalReceivedRequests.incrementAndGet();\n if (task instanceof OLockKeySource) {\n SortedSet rids = ((OLockKeySource) task).getRids();\n SortedSet uniqueKeys = ((OLockKeySource) task).getUniqueKeys();\n OTransactionId txId = ((OLockKeySource) task).getTransactionId();\n\n OnLocksAcquired acquired =\n (guards) -> {\n Runnable executeTask =\n () -> {\n try {\n execute(request);\n } finally {\n this.lockManager.unlock(guards);\n }\n };\n try {\n this.requestExecutor.submit(executeTask);\n } catch (RejectedExecutionException e) {\n task.finished(this);\n this.lockManager.unlock(guards);\n throw e;\n }\n };\n try {\n this.lockManager.lock(rids, uniqueKeys, txId, acquired);\n } catch (OOfflineNodeException e) {\n task.finished(this);\n throw e;\n }\n } else {\n try {\n this.requestExecutor.submit(\n () -> {\n execute(request);\n });\n } catch (RejectedExecutionException e) {\n task.finished(this);\n throw e;\n }\n }\n }\n }\n\n public void trackTransactions(OTransactionId id) {\n inQueue.add(id);\n }\n\n public void untrackTransactions(OTransactionId id) {\n inQueue.remove(id);\n }\n\n private void execute(ODistributedRequest request) {\n ORemoteTask task = request.getTask();\n try {\n manager.messageProcessStart(request);\n Object response;\n if (task.isUsingDatabase()) {\n try (ODatabaseDocumentInternal db =\n this.manager.getServerInstance().getDatabases().openNoAuthorization(databaseName)) {\n response = this.manager.executeOnLocalNode(request.getId(), task, db);\n }\n } else {\n response = this.manager.executeOnLocalNode(request.getId(), task, null);\n }\n if (task.hasResponse()) {\n sendResponseBack(this, this.manager, request.getId(), response);\n }\n manager.messageProcessEnd(request, response);\n } finally {\n task.finished(this);\n }\n }\n\n public void waitIsReady(ORemoteTask task) {\n if (task.isNodeOnlineRequired()) waitDistributedIsReady();\n }\n\n public void waitDistributedIsReady() {\n synchronized (this) {\n if (!parsing) {\n // WAIT FOR PARSING REQUESTS\n while (!parsing && running) {\n try {\n this.wait(1000);\n } catch (InterruptedException e) {\n break;\n }\n }\n }\n }\n }\n\n @Override\n public void setOnline() {\n fillStatus();\n ODistributedServerLog.info(\n this,\n localNodeName,\n null,\n DIRECTION.NONE,\n \"Publishing ONLINE status for database %s.%s...\",\n localNodeName,\n databaseName);\n\n // SET THE NODE.DB AS ONLINE\n manager.setDatabaseStatus(\n localNodeName, databaseName, ODistributedServerManager.DB_STATUS.ONLINE);\n resume();\n }\n\n public void fillStatus() {\n OAbstractPaginatedStorage storage =\n (OAbstractPaginatedStorage)\n ((OrientDBDistributed) manager.getServerInstance().getDatabases())\n .getStorage(databaseName);\n\n if (storage != null) {\n sequenceManager.fill(storage.getLastMetadata());\n }\n }\n\n @Override\n public void unlockResourcesOfServer(\n final ODatabaseDocumentInternal database, final String serverName) {\n final int nodeLeftId = manager.getNodeIdByName(serverName);\n\n final Iterator pendingReqIterator = activeTxContexts.values().iterator();\n while (pendingReqIterator.hasNext()) {\n final ODistributedTxContext pReq = pendingReqIterator.next();\n if (pReq != null && pReq.getReqId().getNodeId() == nodeLeftId) {\n\n ODistributedServerLog.debug(\n this,\n manager.getLocalNodeName(),\n null,\n DIRECTION.NONE,\n \"Distributed transaction: rolling back transaction (req=%s)\",\n pReq.getReqId());\n\n try {\n pReq.rollback(database);\n pReq.destroy();\n } catch (Exception | Error t) {\n // IGNORE IT\n ODistributedServerLog.error(\n this,\n manager.getLocalNodeName(),\n null,\n DIRECTION.NONE,\n \"Distributed transaction: error on rolling back transaction (req=%s)\",\n pReq.getReqId());\n }\n pendingReqIterator.remove();\n }\n }\n }\n\n public ValidationResult validate(OTransactionId id) {\n // this check should happen only of destination nodes\n return sequenceManager.validateTransactionId(id);\n }\n\n @Override\n public OTxMetadataHolder commit(OTransactionId id) {\n return sequenceManager.notifySuccess(id);\n }\n\n @Override\n public void rollback(OTransactionId id) {\n sequenceManager.notifyFailure(id);\n }\n\n @Override\n public ODistributedTxContext registerTxContext(\n final ODistributedRequestId reqId, ODistributedTxContext ctx) {\n final ODistributedTxContext prevCtx = activeTxContexts.put(reqId, ctx);\n if (prevCtx != ctx && prevCtx != null) {\n prevCtx.destroy();\n }\n return ctx;\n }\n\n @Override\n public Optional nextId() {\n return sequenceManager.next();\n }\n\n @Override\n public List missingTransactions(OTransactionSequenceStatus lastState) {\n return sequenceManager.missingTransactions(lastState);\n }\n\n @Override\n public ODistributedTxContext popTxContext(final ODistributedRequestId requestId) {\n final ODistributedTxContext ctx = activeTxContexts.remove(requestId);\n ODistributedServerLog.debug(\n this,\n localNodeName,\n null,\n DIRECTION.NONE,\n \"Distributed transaction: pop request %s for database %s -> %s\",\n requestId,\n databaseName,\n ctx);\n return ctx;\n }\n\n @Override\n public ODistributedTxContext getTxContext(final ODistributedRequestId requestId) {\n final ODistributedTxContext ctx = activeTxContexts.get(requestId);\n ODistributedServerLog.debug(\n this,\n localNodeName,\n null,\n DIRECTION.NONE,\n \"Distributed transaction: pop request %s for database %s -> %s\",\n requestId,\n databaseName,\n ctx);\n return ctx;\n }\n\n @Override\n public ODistributedServerManager getManager() {\n return manager;\n }\n\n public boolean exists() {\n return manager.getServerInstance().existsDatabase(databaseName);\n }\n\n @Override\n public void handleUnreachableNode(final String nodeName) {\n if (!running) {\n return;\n }\n ODistributedServerLog.debug(\n this,\n manager.getLocalNodeName(),\n nodeName,\n DIRECTION.IN,\n \"Distributed transaction: rolling back all the pending transactions coordinated by the unreachable server '%s'\",\n nodeName);\n\n final OUnreachableServerLocalTask task = new OUnreachableServerLocalTask(nodeName);\n final ODistributedRequest rollbackRequest =\n new ODistributedRequest(\n null, manager.getLocalNodeId(), manager.getNextMessageIdCounter(), null, task);\n processRequest(rollbackRequest, false);\n }\n\n @Override\n public String getDatabaseName() {\n return databaseName;\n }\n\n @Override\n public ODatabaseDocumentInternal getDatabaseInstance() {\n return manager.getServerInstance().getDatabases().openNoAuthorization(databaseName);\n }\n\n @Override\n public long getReceivedRequests() {\n return totalReceivedRequests.get();\n }\n\n @Override\n public long getProcessedRequests() {\n return requestExecutor.getCompletedTaskCount();\n }\n\n public void onDropShutdown() {\n // Drop is often called directly from the exeutor so it cannot wait itself to finish\n shutdown(false);\n }\n\n public void shutdown() {\n shutdown(true);\n }\n\n public void shutdown(boolean wait) {\n waitPending();\n running = false;\n\n try {\n if (txTimeoutTask != null) txTimeoutTask.cancel();\n requestExecutor.shutdown();\n if (wait) {\n try {\n requestExecutor.awaitTermination(1, TimeUnit.MINUTES);\n } catch (InterruptedException e) {\n }\n }\n\n activeTxContexts.clear();\n\n Orient.instance()\n .getProfiler()\n .unregisterHookValue(\"distributed.db.\" + databaseName + \".msgSent\");\n Orient.instance()\n .getProfiler()\n .unregisterHookValue(\"distributed.db.\" + databaseName + \".msgReceived\");\n Orient.instance()\n .getProfiler()\n .unregisterHookValue(\"distributed.db.\" + databaseName + \".activeContexts\");\n Orient.instance()\n .getProfiler()\n .unregisterHookValue(\"distributed.db.\" + databaseName + \".workerThreads\");\n Orient.instance()\n .getProfiler()\n .unregisterHookValue(\"distributed.db.\" + databaseName + \".recordLocks\");\n\n } finally {\n\n final ODistributedServerManager.DB_STATUS serverStatus =\n manager.getDatabaseStatus(manager.getLocalNodeName(), databaseName);\n\n if (serverStatus == ODistributedServerManager.DB_STATUS.ONLINE\n || serverStatus == ODistributedServerManager.DB_STATUS.SYNCHRONIZING) {\n try {\n manager.setDatabaseStatus(\n manager.getLocalNodeName(),\n databaseName,\n ODistributedServerManager.DB_STATUS.NOT_AVAILABLE);\n } catch (Exception e) {\n // IGNORE IT\n }\n }\n }\n }\n\n private void waitPending() {\n while (pending.get() > 0) {\n try {\n Thread.sleep(100);\n } catch (InterruptedException e) {\n Thread.currentThread().interrupt();\n return;\n }\n }\n }\n\n public void checkNodeInConfiguration(final String serverName, ODistributedConfiguration cfg) {\n manager.executeInDistributedDatabaseLock(\n databaseName,\n 20000,\n cfg != null ? cfg.modify() : null,\n new OCallable() {\n @Override\n public Void call(final OModifiableDistributedConfiguration lastCfg) {\n // GET LAST VERSION IN LOCK\n final List foundPartition = lastCfg.addNewNodeInServerList(serverName);\n if (foundPartition != null) {\n ODistributedServerLog.info(\n this,\n localNodeName,\n null,\n DIRECTION.NONE,\n \"Adding node '%s' in partition: %s db=%s v=%d\",\n serverName,\n foundPartition,\n databaseName,\n lastCfg.getVersion());\n }\n return null;\n }\n });\n }\n\n @Override\n public void checkNodeInConfiguration(final String serverName) {\n ODistributedConfiguration cfg = getDistributedConfiguration();\n checkNodeInConfiguration(serverName, cfg);\n }\n\n protected String getLocalNodeName() {\n return localNodeName;\n }\n\n private void startAcceptingRequests() {\n // START ALL THE WORKER THREADS (CONFIGURABLE)\n int totalWorkers = OGlobalConfiguration.DISTRIBUTED_DB_WORKERTHREADS.getValueAsInteger();\n if (totalWorkers < 0)\n throw new ODistributedException(\n \"Cannot create configured distributed workers (\" + totalWorkers + \")\");\n else if (totalWorkers == 0) {\n // AUTOMATIC\n final int totalDatabases = manager.getManagedDatabases().size() + 1;\n\n final int cpus = Runtime.getRuntime().availableProcessors();\n\n if (cpus > 1) totalWorkers = cpus / totalDatabases;\n\n if (totalWorkers == 0) totalWorkers = 1;\n }\n\n synchronized (this) {\n this.requestExecutor =\n new ThreadPoolExecutor(\n 0,\n totalWorkers,\n 1,\n TimeUnit.HOURS,\n new LinkedBlockingQueue<>(),\n new ThreadFactory() {\n @Override\n public Thread newThread(Runnable r) {\n Thread thread = new Thread(r);\n thread.setName(\n \"OrientDB DistributedWorker node=\"\n + getLocalNodeName()\n + \" db=\"\n + databaseName);\n thread.setUncaughtExceptionHandler(\n new Thread.UncaughtExceptionHandler() {\n @Override\n public void uncaughtException(Thread t, Throwable e) {\n OLogManager.instance().error(t, \"Exception in distributed executor\", e);\n }\n });\n return thread;\n }\n });\n }\n }\n\n private void startTxTimeoutTimerTask() {\n txTimeoutTask =\n new TimerTask() {\n @Override\n public void run() {\n ODatabaseDocumentInternal database = null;\n try {\n final long now = System.currentTimeMillis();\n final long timeout =\n OGlobalConfiguration.DISTRIBUTED_TX_EXPIRE_TIMEOUT.getValueAsLong();\n\n for (final Iterator it = activeTxContexts.values().iterator();\n it.hasNext(); ) {\n if (!isRunning()) break;\n\n final ODistributedTxContext ctx = it.next();\n if (ctx != null) {\n final long started = ctx.getStartedOn();\n final long elapsed = now - started;\n if (elapsed > timeout) {\n // TRANSACTION EXPIRED, ROLLBACK IT\n\n if (database == null)\n // GET THE DATABASE THE FIRST TIME\n database = getDatabaseInstance();\n\n ODistributedServerLog.debug(\n this,\n localNodeName,\n null,\n DIRECTION.NONE,\n \"Distributed transaction %s on database '%s' is expired after %dms\",\n ctx.getReqId(),\n databaseName,\n elapsed);\n\n if (database != null) database.activateOnCurrentThread();\n\n try {\n ctx.cancel(manager, database);\n\n if (ctx.getReqId().getNodeId() == manager.getLocalNodeId())\n // REQUEST WAS ORIGINATED FROM CURRENT SERVER\n msgService.timeoutRequest(ctx.getReqId().getMessageId());\n\n } catch (Exception t) {\n ODistributedServerLog.info(\n this,\n localNodeName,\n null,\n DIRECTION.NONE,\n \"Error on rolling back distributed transaction %s on database '%s' (err=%s)\",\n ctx.getReqId(),\n databaseName,\n t);\n } finally {\n it.remove();\n }\n }\n }\n }\n\n } catch (Exception t) {\n // CATCH EVERYTHING TO AVOID THE TIMER IS CANCELED\n ODistributedServerLog.info(\n this,\n localNodeName,\n null,\n DIRECTION.NONE,\n \"Error on checking for expired distributed transaction on database '%s'\",\n databaseName);\n } finally {\n if (database != null) {\n database.activateOnCurrentThread();\n database.close();\n }\n }\n }\n };\n }\n\n private boolean isRunning() {\n return running;\n }\n\n public void suspend() {\n boolean parsing;\n synchronized (this) {\n parsing = this.parsing;\n this.parsing = false;\n }\n if (parsing) {\n while (operationsRunnig.get() != 0) {\n try {\n\n Thread.sleep(300);\n } catch (InterruptedException e) {\n break;\n }\n }\n\n recordPromiseManager.reset();\n indexKeyPromiseManager.reset();\n }\n LinkedBlockingQueue latch = new LinkedBlockingQueue(1);\n this.lockManager.freeze(\n (guards) -> {\n try {\n latch.put(guards);\n } catch (InterruptedException e) {\n throw new OInterruptedException(e.getMessage());\n }\n });\n try {\n this.freezeGuard = latch.take();\n } catch (InterruptedException e) {\n throw new OInterruptedException(e.getMessage());\n }\n }\n\n public void resume() {\n synchronized (this) {\n this.parsing = true;", "answers": [" this.notifyAll();"], "length": 2200, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "d3cd1929-d50c-4189-ac91-41fe61adeb1e", "reasoning": "In the resume() method, after re‑enabling parsing by setting this.parsing = true, the code needs to wake any threads waiting for parsing to become true. The typical pattern is to call notifyAll() inside the synchronized block. Therefore the next line is the notifyAll() call.", "reasoning_model_answer": "this.notifyAll();", "assistant_with_reasoning": "\nIn the resume() method, after re‑enabling parsing by setting this.parsing = true, the code needs to wake any threads waiting for parsing to become true. The typical pattern is to call notifyAll() inside the synchronized block. Therefore the next line is the notifyAll() call.\n\nthis.notifyAll();", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 7.3, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 30174, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "this.notifyAll();", "score": 0.85, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/*\n Copyright (c) 2003-2006 Niels Kokholm and Peter Sestoft\n Permission is hereby granted, free of charge, to any person obtaining a copy\n of this software and associated documentation files (the \"Software\"), to deal\n in the Software without restriction, including without limitation the rights\n to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n copies of the Software, and to permit persons to whom the Software is\n furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included in\n all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n SOFTWARE.\n*/\nusing System;\nusing RazorDBx.C5;\nusing NUnit.Framework;\nusing SCG = System.Collections.Generic;\n\nnamespace C5UnitTests.Templates.Events\n{\n\tpublic abstract class CollectionValueTester : GenericCollectionTester\n where TCollection : ICollectionValue\n\t{\n\t\tprotected TCollection collection;\n\t\tprotected CollectionEventList seen;\n\t\tprotected EventTypeEnum listenTo;\n\n\t\tprotected void listen ()\n\t\t{\n\t\t\tseen.Listen (collection, listenTo);\n\t\t}\n\n\t\tpublic override void SetUp (TCollection list, EventTypeEnum testSpec)\n\t\t{\n\t\t\tthis.collection = list;\n\t\t\tlistenTo = testSpec;\n\t\t\tseen = new CollectionEventList (EqualityComparer.Default);\n\t\t}\n\n\t\tpublic SCG.IEnumerable SpecsBasic {\n\t\t\tget {\n\t\t\t\tCircularQueue specs = new CircularQueue ();\n\t\t\t\t//foreach (EventTypeEnum listenTo in Enum.GetValues(typeof(EventTypeEnum)))\n\t\t\t\t// if ((listenTo & ~EventTypeEnum.Basic) == 0)\n\t\t\t\t// specs.Enqueue(listenTo);\n\t\t\t\t//specs.Enqueue(EventTypeEnum.Added | EventTypeEnum.Removed);\n\t\t\t\tfor (int spec = 0; spec <= (int)EventTypeEnum.Basic; spec++)\n\t\t\t\t\tspecs.Enqueue ((EventTypeEnum)spec);\n\t\t\t\treturn specs;\n\t\t\t}\n\t\t}\n\n\t\tpublic SCG.IEnumerable SpecsAll {\n\t\t\tget {\n\t\t\t\tCircularQueue specs = new CircularQueue ();\n\t\t\t\t//foreach (EventTypeEnum listenTo in Enum.GetValues(typeof(EventTypeEnum)))\n\t\t\t\t// specs.Enqueue(listenTo);\n\t\t\t\t//specs.Enqueue(EventTypeEnum.Added | EventTypeEnum.Removed);\n\n\t\t\t\tfor (int spec = 0; spec <= (int)EventTypeEnum.All; spec++)\n\t\t\t\t\tspecs.Enqueue ((EventTypeEnum)spec);\n\t\t\t\treturn specs;\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic abstract class CollectionValueTester : CollectionValueTester where U : ICollectionValue\n\t{\n\t}\n\n\tpublic class ExtensibleTester : CollectionValueTester where U : IExtensible\n\t{\n\t\tpublic override SCG.IEnumerable GetSpecs ()\n\t\t{\n\t\t\treturn SpecsBasic;\n\t\t}\n\n\t\tpublic virtual void Listenable ()\n\t\t{\n\t\t\tAssert.AreEqual (EventTypeEnum.Basic, collection.ListenableEvents);\n\t\t\tAssert.AreEqual (EventTypeEnum.None, collection.ActiveEvents);\n\t\t\tlisten ();\n\t\t\tAssert.AreEqual (listenTo, collection.ActiveEvents);\n\t\t}\n\n\t\tpublic void Add ()\n\t\t{\n\t\t\tlisten ();\n\t\t\tseen.Check (new CollectionEvent[0]);\n\t\t\tcollection.Add (23);\n\t\t\tseen.Check (new CollectionEvent[] {\n\t\t\t\tnew CollectionEvent(EventTypeEnum.Added, new ItemCountEventArgs(23, 1), collection),\n\t\t\t\tnew CollectionEvent(EventTypeEnum.Changed, new EventArgs(), collection)\n\t\t\t});\n\t\t}\n\n\t\tpublic void AddAll ()\n\t\t{\n\t\t\tfor (int i = 0; i < 10; i++) {\n\t\t\t\tcollection.Add (10 * i + 5);\n\t\t\t}\n\t\t\tlisten ();\n\t\t\tcollection.AddAll (new int[] { 45, 200, 56, 67 });\n\t\t\tseen.Check (collection.AllowsDuplicates ?\n collection.DuplicatesByCounting ?\n new CollectionEvent[] {\n\t\t\t\tnew CollectionEvent(EventTypeEnum.Added, new ItemCountEventArgs(45, 1), collection),\n\t\t\t\tnew CollectionEvent(EventTypeEnum.Added, new ItemCountEventArgs(200, 1), collection),\n\t\t\t\tnew CollectionEvent(EventTypeEnum.Added, new ItemCountEventArgs(55, 1), collection),\n\t\t\t\tnew CollectionEvent(EventTypeEnum.Added, new ItemCountEventArgs(65, 1), collection),\n\t\t\t\tnew CollectionEvent(EventTypeEnum.Changed, new EventArgs(), collection)\n\t\t\t}\n :\n new CollectionEvent[] {\n\t\t\t\tnew CollectionEvent(EventTypeEnum.Added, new ItemCountEventArgs(45, 1), collection),\n\t\t\t\tnew CollectionEvent(EventTypeEnum.Added, new ItemCountEventArgs(200, 1), collection),\n\t\t\t\tnew CollectionEvent(EventTypeEnum.Added, new ItemCountEventArgs(56, 1), collection),\n\t\t\t\tnew CollectionEvent(EventTypeEnum.Added, new ItemCountEventArgs(67, 1), collection),\n\t\t\t\tnew CollectionEvent(EventTypeEnum.Changed, new EventArgs(), collection)\n\t\t\t}\n :\n new CollectionEvent[] {\n\t\t\t\tnew CollectionEvent(EventTypeEnum.Added, new ItemCountEventArgs(200, 1), collection),\n\t\t\t\tnew CollectionEvent(EventTypeEnum.Changed, new EventArgs(), collection)\n\t\t\t});\n\t\t\tcollection.AddAll (new int[] { });\n seen.Check(new CollectionEvent[] { });\n }\n\n }\n\n public class CollectionTester : ExtensibleTester where U : ICollection\n {\n public void Update()\n {\n collection.Add(4); collection.Add(54); collection.Add(56); collection.Add(8);\n listen();\n collection.Update(53);\n seen.Check(\n collection.AllowsDuplicates ?\n collection.DuplicatesByCounting ?\n new CollectionEvent[] {\n new CollectionEvent(EventTypeEnum.Removed, new ItemCountEventArgs(54, 2), collection),\n new CollectionEvent(EventTypeEnum.Added, new ItemCountEventArgs(53, 2), collection),\n new CollectionEvent(EventTypeEnum.Changed, new EventArgs(), collection)\n }\n : new CollectionEvent[] {\n new CollectionEvent(EventTypeEnum.Removed, new ItemCountEventArgs(54, 1), collection),\n new CollectionEvent(EventTypeEnum.Added, new ItemCountEventArgs(53, 1), collection),\n new CollectionEvent(EventTypeEnum.Changed, new EventArgs(), collection)\n }\n : new CollectionEvent[] {\n new CollectionEvent(EventTypeEnum.Removed, new ItemCountEventArgs(54, 1), collection),\n new CollectionEvent(EventTypeEnum.Added, new ItemCountEventArgs(53, 1), collection),\n new CollectionEvent(EventTypeEnum.Changed, new EventArgs(), collection)\n });\n collection.Update(67);\n seen.Check(new CollectionEvent[] { });\n }\n\n public void FindOrAdd()\n {\n collection.Add(4); collection.Add(56); collection.Add(8);\n listen();\n int val = 53;\n collection.FindOrAdd(ref val);\n seen.Check(new CollectionEvent[] { });\n val = 67;\n collection.FindOrAdd(ref val);\n seen.Check(new CollectionEvent[] {\n new CollectionEvent(EventTypeEnum.Added, new ItemCountEventArgs(67, 1), collection),\n new CollectionEvent(EventTypeEnum.Changed, new EventArgs(), collection)\n });\n }\n\n public void UpdateOrAdd()\n {\n collection.Add(4); collection.Add(56); collection.Add(8);\n listen();\n int val = 53;\n collection.UpdateOrAdd(val);\n seen.Check(new CollectionEvent[] {\n new CollectionEvent(EventTypeEnum.Removed, new ItemCountEventArgs(56, 1), collection),\n new CollectionEvent(EventTypeEnum.Added, new ItemCountEventArgs(53, 1), collection),\n new CollectionEvent(EventTypeEnum.Changed, new EventArgs(), collection)\n });\n val = 67;\n collection.UpdateOrAdd(val);\n seen.Check(new CollectionEvent[] {\n new CollectionEvent(EventTypeEnum.Added, new ItemCountEventArgs(67, 1), collection),\n new CollectionEvent(EventTypeEnum.Changed, new EventArgs(), collection)\n });\n collection.UpdateOrAdd(51, out val);\n seen.Check(new CollectionEvent[] {\n new CollectionEvent(EventTypeEnum.Removed, new ItemCountEventArgs(53, 1), collection),\n new CollectionEvent(EventTypeEnum.Added, new ItemCountEventArgs(51, 1), collection),\n new CollectionEvent(EventTypeEnum.Changed, new EventArgs(), collection)\n });\n val = 67;\n collection.UpdateOrAdd(81, out val);\n seen.Check(new CollectionEvent[] {\n new CollectionEvent(EventTypeEnum.Added, new ItemCountEventArgs(81, 1), collection),\n new CollectionEvent(EventTypeEnum.Changed, new EventArgs(), collection)\n });\n }\n\n public void RemoveItem()\n {\n collection.Add(4); collection.Add(56); collection.Add(18);\n listen();\n collection.Remove(53);\n seen.Check(new CollectionEvent[] {\n new CollectionEvent(EventTypeEnum.Removed, new ItemCountEventArgs(56, 1), collection),\n new CollectionEvent(EventTypeEnum.Changed, new EventArgs(), collection)});\n collection.Remove(11);\n seen.Check(new CollectionEvent[] {\n new CollectionEvent(EventTypeEnum.Removed, new ItemCountEventArgs(18, 1), collection),\n new CollectionEvent(EventTypeEnum.Changed, new EventArgs(), collection)});\n }\n\n public void RemoveAll()\n {\n for (int i = 0; i < 10; i++)\n {\n collection.Add(10 * i + 5);\n }\n listen();\n collection.RemoveAll(new int[] { 32, 187, 45 });\n //TODO: the order depends on internals of the HashSet\n seen.Check(new CollectionEvent[] {\n new CollectionEvent(EventTypeEnum.Removed, new ItemCountEventArgs(35, 1), collection),\n new CollectionEvent(EventTypeEnum.Removed, new ItemCountEventArgs(45, 1), collection),\n new CollectionEvent(EventTypeEnum.Changed, new EventArgs(), collection)});\n collection.RemoveAll(new int[] { 200, 300 });\n seen.Check(new CollectionEvent[] { });\n }\n\n public void RetainAll()\n {\n for (int i = 0; i < 10; i++)\n {\n collection.Add(10 * i + 5);\n }\n listen();\n collection.RetainAll(new int[] { 32, 187, 45, 62, 75, 82, 95, 2 });\n seen.Check(new CollectionEvent[] {\n new CollectionEvent(EventTypeEnum.Removed, new ItemCountEventArgs(15, 1), collection),\n new CollectionEvent(EventTypeEnum.Removed, new ItemCountEventArgs(25, 1), collection),\n new CollectionEvent(EventTypeEnum.Removed, new ItemCountEventArgs(55, 1), collection),\n //new CollectionEvent(EventTypeEnum.Removed, new ItemCountEventArgs(75, 1), collection),\n new CollectionEvent(EventTypeEnum.Changed, new EventArgs(), collection)});\n collection.RetainAll(new int[] { 32, 187, 45, 62, 75, 82, 95, 2 });\n seen.Check(new CollectionEvent[] { });\n }\n\n public void RemoveAllCopies()\n {\n for (int i = 0; i < 10; i++)\n {\n collection.Add(3 * i + 5);\n }\n listen();\n collection.RemoveAllCopies(14);\n seen.Check(\n collection.AllowsDuplicates ?\n collection.DuplicatesByCounting ?\n new CollectionEvent[] {\n new CollectionEvent(EventTypeEnum.Removed, new ItemCountEventArgs(11, 3), collection),\n new CollectionEvent(EventTypeEnum.Changed, new EventArgs(), collection)}\n :\n new CollectionEvent[] {\n new CollectionEvent(EventTypeEnum.Removed, new ItemCountEventArgs(11, 1), collection),\n new CollectionEvent(EventTypeEnum.Removed, new ItemCountEventArgs(14, 1), collection),\n new CollectionEvent(EventTypeEnum.Removed, new ItemCountEventArgs(17, 1), collection),\n new CollectionEvent(EventTypeEnum.Changed, new EventArgs(), collection)}\n :\n new CollectionEvent[] {\n new CollectionEvent(EventTypeEnum.Removed, new ItemCountEventArgs(11, 1), collection),\n new CollectionEvent(EventTypeEnum.Changed, new EventArgs(), collection)});\n collection.RemoveAllCopies(14);\n seen.Check(new CollectionEvent[] { });\n }\n\n public virtual void Clear()\n {\n collection.Add(4); collection.Add(56); collection.Add(8);\n listen();\n collection.Clear();\n seen.Check(new CollectionEvent[] {\n new CollectionEvent(EventTypeEnum.Cleared, new ClearedEventArgs(true, collection.AllowsDuplicates ? 3 : 2), collection),\n new CollectionEvent(EventTypeEnum.Changed, new EventArgs(), collection)\n });\n collection.Clear();\n seen.Check(new CollectionEvent[] { });\n }\n\n }\n\n public class IndexedTester : CollectionTester where U : IIndexed\n {\n public void RemoveAt()\n {\n collection.Add(4); collection.Add(16); collection.Add(28);\n listen();\n collection.RemoveAt(1);\n seen.Check(new CollectionEvent[] {\n new CollectionEvent(EventTypeEnum.RemovedAt, new ItemAtEventArgs(16,1), collection),\n new CollectionEvent(EventTypeEnum.Removed, new ItemCountEventArgs(16, 1), collection),\n new CollectionEvent(EventTypeEnum.Changed, new EventArgs(), collection)});\n }\n\n public void RemoveInterval()\n {\n collection.Add(4); collection.Add(56); collection.Add(18);\n listen();\n collection.RemoveInterval(1, 2);\n seen.Check(new CollectionEvent[] {\n collection is IList ?\n new CollectionEvent(EventTypeEnum.Cleared, new ClearedRangeEventArgs(false,2,1), collection):\n new CollectionEvent(EventTypeEnum.Cleared, new ClearedEventArgs(false,2), collection),\n new CollectionEvent(EventTypeEnum.Changed, new EventArgs(), collection)\n });\n collection.RemoveInterval(1, 0);\n seen.Check(new CollectionEvent[] { });\n }\n }\n\n public class SortedIndexedTester : IndexedTester where U : IIndexedSorted\n {\n public void DeleteMinMax()\n {\n collection.Add(34);\n collection.Add(56);\n collection.Add(34);\n collection.Add(12);\n listen();\n collection.DeleteMax();\n seen.Check(new CollectionEvent[] {\n new CollectionEvent(EventTypeEnum.Removed, new ItemCountEventArgs(56, 1), collection),\n new CollectionEvent(EventTypeEnum.Changed, new EventArgs(), collection),\n });\n collection.DeleteMin();\n seen.Check(new CollectionEvent[] {\n new CollectionEvent(EventTypeEnum.Removed, new ItemCountEventArgs(12, 1), collection),\n new CollectionEvent(EventTypeEnum.Changed, new EventArgs(), collection),\n });\n }\n\n public void AddSorted()\n {\n listen();\n collection.AddSorted(collection.AllowsDuplicates ? new int[] { 31, 62, 63, 93 } : new int[] { 31, 62, 93 });\n seen.Check(collection.AllowsDuplicates ?\n collection.DuplicatesByCounting ?\n new CollectionEvent[] {\n new CollectionEvent(EventTypeEnum.Added, new ItemCountEventArgs(31, 1), collection),\n new CollectionEvent(EventTypeEnum.Added, new ItemCountEventArgs(62, 1), collection),\n new CollectionEvent(EventTypeEnum.Added, new ItemCountEventArgs(62, 1), collection),\n new CollectionEvent(EventTypeEnum.Added, new ItemCountEventArgs(93, 1), collection),\n new CollectionEvent(EventTypeEnum.Changed, new EventArgs(), collection)}\n :\n new CollectionEvent[] {\n new CollectionEvent(EventTypeEnum.Added, new ItemCountEventArgs(31, 1), collection),\n new CollectionEvent(EventTypeEnum.Added, new ItemCountEventArgs(62, 1), collection),\n new CollectionEvent(EventTypeEnum.Added, new ItemCountEventArgs(63, 1), collection),\n new CollectionEvent(EventTypeEnum.Added, new ItemCountEventArgs(93, 1), collection),\n new CollectionEvent(EventTypeEnum.Changed, new EventArgs(), collection)}\n :\n new CollectionEvent[] {\n new CollectionEvent(EventTypeEnum.Added, new ItemCountEventArgs(31, 1), collection),\n new CollectionEvent(EventTypeEnum.Added, new ItemCountEventArgs(62, 1), collection),\n new CollectionEvent(EventTypeEnum.Added, new ItemCountEventArgs(93, 1), collection),\n new CollectionEvent(EventTypeEnum.Changed, new EventArgs(), collection)});\n collection.AddSorted(new int[] { });\n seen.Check(new CollectionEvent[] { });\n }\n\n public void RemoveRange()\n {\n for (int i = 0; i < 20; i++)\n collection.Add(i * 10 + 5);\n listen();\n collection.RemoveRangeFrom(173);\n //TODO: fix order to remove in:\n seen.Check(\n new CollectionEvent[] {\n new CollectionEvent(EventTypeEnum.Removed, new ItemCountEventArgs(195, 1), collection),\n new CollectionEvent(EventTypeEnum.Removed, new ItemCountEventArgs(185, 1), collection),\n new CollectionEvent(EventTypeEnum.Removed, new ItemCountEventArgs(175, 1), collection),\n new CollectionEvent(EventTypeEnum.Changed, new EventArgs(), collection)});\n collection.RemoveRangeFromTo(83, 113);\n seen.Check(\n new CollectionEvent[] {\n new CollectionEvent(EventTypeEnum.Removed, new ItemCountEventArgs(105, 1), collection),\n new CollectionEvent(EventTypeEnum.Removed, new ItemCountEventArgs(95, 1), collection),\n new CollectionEvent(EventTypeEnum.Removed, new ItemCountEventArgs(85, 1), collection),\n new CollectionEvent(EventTypeEnum.Changed, new EventArgs(), collection)});\n collection.RemoveRangeTo(33);\n seen.Check(\n new CollectionEvent[] {\n new CollectionEvent(EventTypeEnum.Removed, new ItemCountEventArgs(5, 1), collection),\n new CollectionEvent(EventTypeEnum.Removed, new ItemCountEventArgs(15, 1), collection),\n new CollectionEvent(EventTypeEnum.Removed, new ItemCountEventArgs(25, 1), collection),\n new CollectionEvent(EventTypeEnum.Changed, new EventArgs(), collection)});\n collection.RemoveRangeFrom(173);\n seen.Check(new CollectionEvent[] { });\n collection.RemoveRangeFromTo(83, 113);\n seen.Check(new CollectionEvent[] { });\n collection.RemoveRangeTo(33);\n seen.Check(new CollectionEvent[] { });\n }\n }\n\n public class ListTester : IndexedTester where U : IList\n {\n public override SCG.IEnumerable GetSpecs()\n {\n return SpecsAll;\n }\n\n public override void Listenable()\n {\n Assert.AreEqual(EventTypeEnum.All, collection.ListenableEvents);\n Assert.AreEqual(EventTypeEnum.None, collection.ActiveEvents);\n listen();\n Assert.AreEqual(listenTo, collection.ActiveEvents);\n }\n public void SetThis()\n {\n collection.Add(4); collection.Add(56); collection.Add(8);\n listen();\n collection[1] = 45;\n seen.Check(new CollectionEvent[] {\n new CollectionEvent(EventTypeEnum.Removed, new ItemCountEventArgs(56, 1), collection),\n new CollectionEvent(EventTypeEnum.RemovedAt, new ItemAtEventArgs(56,1), collection),\n new CollectionEvent(EventTypeEnum.Added, new ItemCountEventArgs(45, 1), collection),\n new CollectionEvent(EventTypeEnum.Inserted, new ItemAtEventArgs(45,1), collection),\n new CollectionEvent(EventTypeEnum.Changed, new EventArgs(), collection)\n });\n }\n\n public void Insert()\n {\n collection.Add(4); collection.Add(56); collection.Add(8);\n listen();\n collection.Insert(1, 45);\n seen.Check(new CollectionEvent[] {\n new CollectionEvent(EventTypeEnum.Inserted, new ItemAtEventArgs(45,1), collection),\n new CollectionEvent(EventTypeEnum.Added, new ItemCountEventArgs(45, 1), collection),\n new CollectionEvent(EventTypeEnum.Changed, new EventArgs(), collection)\n });\n }\n\n public void InsertAll()\n {\n collection.Add(4); collection.Add(56); collection.Add(8);\n listen();\n collection.InsertAll(1, new int[] { 666, 777, 888 });\n //seen.Print(Console.Error);\n seen.Check(new CollectionEvent[] {\n new CollectionEvent(EventTypeEnum.Inserted, new ItemAtEventArgs(666,1), collection),\n new CollectionEvent(EventTypeEnum.Added, new ItemCountEventArgs(666, 1), collection),\n new CollectionEvent(EventTypeEnum.Inserted, new ItemAtEventArgs(777,2), collection),\n new CollectionEvent(EventTypeEnum.Added, new ItemCountEventArgs(777, 1), collection),\n new CollectionEvent(EventTypeEnum.Inserted, new ItemAtEventArgs(888,3), collection),\n new CollectionEvent(EventTypeEnum.Added, new ItemCountEventArgs(888, 1), collection),\n new CollectionEvent(EventTypeEnum.Changed, new EventArgs(), collection)\n });\n collection.InsertAll(1, new int[] { });\n seen.Check(new CollectionEvent[] { });\n }\n\n public void InsertFirstLast()\n {\n collection.Add(4); collection.Add(56); collection.Add(18);\n listen();\n collection.InsertFirst(45);\n seen.Check(new CollectionEvent[] {\n new CollectionEvent(EventTypeEnum.Inserted, new ItemAtEventArgs(45,0), collection),\n new CollectionEvent(EventTypeEnum.Added, new ItemCountEventArgs(45, 1), collection),\n new CollectionEvent(EventTypeEnum.Changed, new EventArgs(), collection)\n });\n collection.InsertLast(88);\n seen.Check(new CollectionEvent[] {\n new CollectionEvent(EventTypeEnum.Inserted, new ItemAtEventArgs(88,4), collection),\n new CollectionEvent(EventTypeEnum.Added, new ItemCountEventArgs(88, 1), collection),\n new CollectionEvent(EventTypeEnum.Changed, new EventArgs(), collection)\n });\n }\n\n public void Remove()\n {\n collection.FIFO = false;\n collection.Add(4); collection.Add(56); collection.Add(18);\n listen();\n collection.Remove();\n seen.Check(new CollectionEvent[] {\n new CollectionEvent(EventTypeEnum.Removed, new ItemCountEventArgs(18, 1), collection),\n new CollectionEvent(EventTypeEnum.Changed, new EventArgs(), collection)});\n collection.FIFO = true;\n collection.Remove();\n seen.Check(new CollectionEvent[] {\n new CollectionEvent(EventTypeEnum.Removed, new ItemCountEventArgs(4, 1), collection),\n new CollectionEvent(EventTypeEnum.Changed, new EventArgs(), collection)});\n }\n\n public void RemoveFirst()\n {\n collection.Add(4); collection.Add(56); collection.Add(18);\n listen();\n collection.RemoveFirst();\n seen.Check(new CollectionEvent[] {\n new CollectionEvent(EventTypeEnum.RemovedAt, new ItemAtEventArgs(4,0), collection),\n new CollectionEvent(EventTypeEnum.Removed, new ItemCountEventArgs(4, 1), collection),\n new CollectionEvent(EventTypeEnum.Changed, new EventArgs(), collection)});\n }\n\n public void RemoveLast()\n {\n collection.Add(4); collection.Add(56); collection.Add(18);\n listen();\n collection.RemoveLast();\n seen.Check(new CollectionEvent[] {\n new CollectionEvent(EventTypeEnum.RemovedAt, new ItemAtEventArgs(18,2), collection),\n new CollectionEvent(EventTypeEnum.Removed, new ItemCountEventArgs(18, 1), collection),\n new CollectionEvent(EventTypeEnum.Changed, new EventArgs(), collection)});\n }\n\n public void Reverse()\n {\n collection.Add(4); collection.Add(56); collection.Add(8);\n listen();\n collection.Reverse();\n seen.Check(new CollectionEvent[] {\n new CollectionEvent(EventTypeEnum.Changed, new EventArgs(), collection)\n });\n collection.View(1, 0).Reverse();\n seen.Check(new CollectionEvent[] { });\n }\n\n\n public void Sort()\n {\n collection.Add(4); collection.Add(56); collection.Add(8);\n listen();\n collection.Sort();\n seen.Check(new CollectionEvent[] {\n new CollectionEvent(EventTypeEnum.Changed, new EventArgs(), collection)\n });\n collection.View(1, 0).Sort();\n seen.Check(new CollectionEvent[] { });\n }\n\n public void Shuffle()\n {\n collection.Add(4); collection.Add(56); collection.Add(8);\n listen();\n collection.Shuffle();\n seen.Check(new CollectionEvent[] {\n new CollectionEvent(EventTypeEnum.Changed, new EventArgs(), collection)\n });\n collection.View(1, 0).Shuffle();\n seen.Check(new CollectionEvent[] { });\n }\n\n public override void Clear()\n {\n collection.Add(4); collection.Add(56); collection.Add(18);\n listen();\n collection.View(1, 1).Clear();\n seen.Check(new CollectionEvent[] {\n new CollectionEvent(EventTypeEnum.Cleared, new ClearedRangeEventArgs(false,1,1), collection),\n new CollectionEvent(EventTypeEnum.Changed, new EventArgs(), collection)\n });\n collection.Clear();\n seen.Check(new CollectionEvent[] {\n new CollectionEvent(EventTypeEnum.Cleared, new ClearedRangeEventArgs(true,2,0), collection),\n new CollectionEvent(EventTypeEnum.Changed, new EventArgs(), collection)\n });\n collection.Clear();\n seen.Check(new CollectionEvent[] { });\n }\n\n public void ListDispose()\n {\n collection.Add(4); collection.Add(56); collection.Add(18);\n listen();\n collection.View(1, 1).Dispose();\n seen.Check(new CollectionEvent[] { });\n collection.Dispose();\n seen.Check(new CollectionEvent[] {\n new CollectionEvent(EventTypeEnum.Cleared, new ClearedRangeEventArgs(true,3,0), collection),\n new CollectionEvent(EventTypeEnum.Changed, new EventArgs(), collection)\n });\n collection.Dispose();\n seen.Check(new CollectionEvent[] { });\n }\n\n /*\n\n * /\n //[TearDown]\n //public void Dispose() { list = null; seen = null; }\n /*\n [Test]\n [ExpectedException(typeof(UnlistenableEventException))]\n public void ViewChanged()\n {\n IList w = collection.View(0, 0);\n w.CollectionChanged += new CollectionChangedHandler(w_CollectionChanged);\n }\n\n [Test]\n [ExpectedException(typeof(UnlistenableEventException))]\n public void ViewCleared()\n {\n IList w = collection.View(0, 0);\n w.CollectionCleared += new CollectionClearedHandler(w_CollectionCleared);\n }\n\n [Test]\n [ExpectedException(typeof(UnlistenableEventException))]\n public void ViewAdded()\n {\n IList w = collection.View(0, 0);\n w.ItemsAdded += new ItemsAddedHandler(w_ItemAdded);\n }\n\n [Test]\n [ExpectedException(typeof(UnlistenableEventException))]\n public void ViewInserted()\n {\n IList w = collection.View(0, 0);\n w.ItemInserted += new ItemInsertedHandler(w_ItemInserted);\n }\n\n [Test]\n [ExpectedException(typeof(UnlistenableEventException))]\n public void ViewRemoved()\n {\n IList w = collection.View(0, 0);\n w.ItemsRemoved += new ItemsRemovedHandler(w_ItemRemoved);\n }\n\n [Test]\n [ExpectedException(typeof(UnlistenableEventException))]\n public void ViewRemovedAt()\n {\n IList w = collection.View(0, 0);\n w.ItemRemovedAt += new ItemRemovedAtHandler(w_ItemRemovedAt);\n }\n\n void w_CollectionChanged(object sender)\n {\n throw new NotImplementedException();\n }\n\n void w_CollectionCleared(object sender, ClearedEventArgs eventArgs)\n {\n throw new NotImplementedException();\n }\n\n void w_ItemAdded(object sender, ItemCountEventArgs eventArgs)\n {\n throw new NotImplementedException();\n }\n\n void w_ItemInserted(object sender, ItemAtEventArgs eventArgs)\n {\n throw new NotImplementedException();\n }\n\n void w_ItemRemoved(object sender, ItemCountEventArgs eventArgs)\n {\n throw new NotImplementedException();\n }\n\n void w_ItemRemovedAt(object sender, ItemAtEventArgs eventArgs)\n {\n throw new NotImplementedException();\n }*/\n }\n\n public class StackTester : CollectionValueTester where U : IStack\n {\n public override SCG.IEnumerable GetSpecs()\n {\n return SpecsBasic;\n }\n\n public void PushPop()\n {\n listen();\n seen.Check(new CollectionEvent[0]);\n collection.Push(23);\n seen.Check(new CollectionEvent[] {\n new CollectionEvent(EventTypeEnum.Inserted, new ItemAtEventArgs(23,0), collection),\n new CollectionEvent(EventTypeEnum.Added, new ItemCountEventArgs(23, 1), collection),\n new CollectionEvent(EventTypeEnum.Changed, new EventArgs(), collection)});\n collection.Push(-12);\n seen.Check(new CollectionEvent[] {\n new CollectionEvent(EventTypeEnum.Inserted, new ItemAtEventArgs(-12,1), collection),\n new CollectionEvent(EventTypeEnum.Added, new ItemCountEventArgs(-12, 1), collection),\n new CollectionEvent(EventTypeEnum.Changed, new EventArgs(), collection)});\n collection.Pop();\n seen.Check(new CollectionEvent[] {\n new CollectionEvent(EventTypeEnum.RemovedAt, new ItemAtEventArgs(-12,1), collection),\n new CollectionEvent(EventTypeEnum.Removed, new ItemCountEventArgs(-12, 1), collection),\n new CollectionEvent(EventTypeEnum.Changed, new EventArgs(), collection)});\n collection.Pop();\n seen.Check(new CollectionEvent[] {\n new CollectionEvent(EventTypeEnum.RemovedAt, new ItemAtEventArgs(23,0), collection),\n new CollectionEvent(EventTypeEnum.Removed, new ItemCountEventArgs(23, 1), collection),\n new CollectionEvent(EventTypeEnum.Changed, new EventArgs(), collection)});\n }\n }\n\n public class QueueTester : CollectionValueTester where U : IQueue\n {\n public override SCG.IEnumerable GetSpecs()\n {\n return SpecsBasic;\n }\n\n public void EnqueueDequeue()\n {\n listen();\n collection.Enqueue(67);\n seen.Check(new CollectionEvent[] {\n new CollectionEvent(EventTypeEnum.Inserted, new ItemAtEventArgs(67,0), collection),\n new CollectionEvent(EventTypeEnum.Added, new ItemCountEventArgs(67, 1), collection),\n new CollectionEvent(EventTypeEnum.Changed, new EventArgs(), collection)});\n collection.Enqueue(2);\n seen.Check(new CollectionEvent[] {\n new CollectionEvent(EventTypeEnum.Inserted, new ItemAtEventArgs(2,1), collection),\n new CollectionEvent(EventTypeEnum.Added, new ItemCountEventArgs(2, 1), collection),\n new CollectionEvent(EventTypeEnum.Changed, new EventArgs(), collection)});\n collection.Dequeue();\n seen.Check(new CollectionEvent[] {\n new CollectionEvent(EventTypeEnum.RemovedAt, new ItemAtEventArgs(67,0), collection),\n new CollectionEvent(EventTypeEnum.Removed, new ItemCountEventArgs(67, 1), collection),\n new CollectionEvent(EventTypeEnum.Changed, new EventArgs(), collection)});\n collection.Dequeue();\n seen.Check(new CollectionEvent[] {\n new CollectionEvent(EventTypeEnum.RemovedAt, new ItemAtEventArgs(2,0), collection),\n new CollectionEvent(EventTypeEnum.Removed, new ItemCountEventArgs(2, 1), collection),\n new CollectionEvent(EventTypeEnum.Changed, new EventArgs(), collection)});\n }\n\n }\n\n public class PriorityQueueTester : ExtensibleTester where U : IPriorityQueue\n {\n public override System.Collections.Generic.IEnumerable GetSpecs()\n {\n return SpecsBasic;\n }\n\n public void Direct()\n {\n listen();\n collection.Add(34);\n seen.Check(new CollectionEvent[] {", "answers": [" new CollectionEvent(EventTypeEnum.Added, new ItemCountEventArgs(34, 1), collection),"], "length": 2365, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "cb88fd0f-6abf-4b96-8c3f-89492b042a30", "reasoning": "The Direct method adds an element to a priority queue and then checks the raised events. Following the pattern used elsewhere (e.g., ExtensibleTester.Add), the first event recorded after adding 34 is an Added event with count 1, followed by a Changed event. The next line should therefore be the first element of the array passed to seen.Check, i.e., the Added event entry.", "reasoning_model_answer": "new CollectionEvent(EventTypeEnum.Added, new ItemCountEventArgs(34, 1), collection),", "assistant_with_reasoning": "\nThe Direct method adds an element to a priority queue and then checks the raised events. Following the pattern used elsewhere (e.g., ExtensibleTester.Add), the first event recorded after adding 34 is an Added event with count 1, followed by a Changed event. The next line should therefore be the first element of the array passed to seen.Check, i.e., the Added event entry.\n\nnew CollectionEvent(EventTypeEnum.Added, new ItemCountEventArgs(34, 1), collection),", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 5.62, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 35500, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "new CollectionEvent(EventTypeEnum.Added, new ItemCountEventArgs(34, 1), collection),", "score": 0.96, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Web;\nusing System.Threading;\nusing BeastClientPlugIn;\nusing System.Diagnostics;\nusing System.Text;\nusing System.Reflection;\nusing System.Configuration;\nusing VCM.Common.Log;\nusing OpenBeast.Beast.ProductImages;\n\n/// \n/// Summary description for BeastConn\n/// \n/// \npublic class BeastConn : IProductImageFactory\n{\n #region Private Variable\n\n private ServerAgent _sa;\n private static volatile BeastConn instance = null;\n private static object syncRoot = new Object();\n\n public bool isConnection = false;\n private bool isForceUnload = false;\n\n //private swapService ss;\n private Dictionary _dirBeastImg;\n #endregion\n\n #region Constructor\n public BeastConn()\n {\n _sa = new ServerAgent();\n isConnection = false;\n\n isForceUnload = false;\n //ss = new swapService();\n _dirBeastImg = new Dictionary();\n }\n #endregion\n\n #region Beast Connection\n\n [LoaderOptimization(LoaderOptimization.MultiDomain)]\n void runPlugIn()\n {\n string userName = string.Empty;\n string Password = string.Empty;\n string ServerName = string.Empty;\n string ServerName2 = string.Empty;\n string RetryCount = string.Empty;\n try\n {\n isConnection = false;\n isForceUnload = false;\n userName = ConfigurationManager.AppSettings[\"UserName\"].ToString();\n Password = ConfigurationManager.AppSettings[\"Password\"].ToString();\n ServerName = ConfigurationManager.AppSettings[\"ServerName\"].ToString();\n ServerName2 = ConfigurationManager.AppSettings[\"ServerName2\"].ToString();\n RetryCount = ConfigurationManager.AppSettings[\"RetryCount\"].ToString();\n\n Scripting.Dictionary props = new Scripting.Dictionary();\n _sa.StatusChanged += new _IServerAgentEvents_StatusChangedEventHandler(_sa_StatusChanged);\n _sa.AuthenticationFailed += new _IServerAgentEvents_AuthenticationFailedEventHandler(_sa_AuthenticationFailed);\n _sa.ConnectionLost += new _IServerAgentEvents_ConnectionLostEventHandler(_sa_ConnectionLost);\n _sa.ConnectionRestored += new _IServerAgentEvents_ConnectionRestoredEventHandler(_sa_ConnectionRestored);\n _sa.ForcedUnLoad += new _IServerAgentEvents_ForcedUnLoadEventHandler(_sa_ForcedUnLoad);\n _sa.ForceUpdate += new _IServerAgentEvents_ForceUpdateEventHandler(_sa_ForceUpdate);\n _sa.NotifyHost += new _IServerAgentEvents_NotifyHostEventHandler(_sa_NotifyHost);\n\n\n Object key = \"Server0\";\n Object value = ServerName;\n props.Add(ref key, ref value);\n key = \"Port0\";\n value = Convert.ToString(System.Configuration.ConfigurationManager.AppSettings[\"Port\"]);\n props.Add(ref key, ref value);\n key = \"retry0\";\n value = RetryCount;\n props.Add(ref key, ref value);\n\n //key = \"Server1\";\n //value = ServerName2;\n //props.Add(ref key, ref value);\n //key = \"Port1\";\n //value = \"8200\";\n //props.Add(ref key, ref value);\n //key = \"retry1\";\n //value = RetryCount;\n //props.Add(ref key, ref value);\n\n _sa.Connect(userName, Password, props);\n\n string strlogDesc = \"UserName: \" + userName + \"; \" + \"ServerName: \" + ServerName + \"; run Plug In\";\n LogUtility.Info(\"BeastConn.cs\", \"runPlugIn()\", strlogDesc);\n }\n catch (Exception ex)\n {\n //Debug.WriteLine(\"********************************Run Plugin \" + ex.Message);\n //ss.SubmitUserLoginNotification_BeastPlugin(\"BeastConnection - runPlugIn() ERROR\", ex.Message);\n\n string strErrorDesc = \"UserName: \" + userName + \"; \" + \"ServerName: \" + ServerName + \"; \" + ex.Message;\n LogUtility.Error(\"BeastConn.cs\", \"runPlugIn()\", strErrorDesc, ex);\n }\n }\n\n void _sa_NotifyHost(Scripting.Dictionary props)\n {\n try\n {\n\n //////ss.SubmitUserLoginNotification_BeastPlugin(\"BeastConnection - _sa_NotifyHost() :\", \"status:\");\n\n StringBuilder sb = new StringBuilder();\n foreach (object key in props)\n {\n object rkey = key;\n sb.Append(key.ToString() + \":\" + props.get_Item(ref rkey).ToString() + \" \");\n }\n //Debug.WriteLine(\"*************************_sa_NotifyHost: \" + sb);\n\n //ss.SubmitUserLoginNotification_BeastPlugin(\"BeastConnection - _sa_NotifyHost()\", sb.ToString());\n\n Dictionary items = new Dictionary();\n List keys = new List();\n List vals = new List();\n foreach (object key in props)\n {\n keys.Add((string)key);\n object rkey = key;\n vals.Add(Convert.ToString(props.get_Item(ref rkey)));\n }\n\n for (int i = 0; i < props.Count; i++)\n {\n items.Add(keys[i], vals[i]);\n }\n string typeKey = \"Type\";\n if (items.ContainsKey(typeKey) == true)\n {\n string type = items[typeKey];\n if (type == \"Message\")\n {\n string message = \"\";\n if (items[\"ErrorMessage\"] != null)\n message = items[\"ErrorMessage\"];\n object opt = items[\"MessageBoxOption\"];\n\n string strmsg = message.Replace(\"! Would you like to download?\", \".\");\n //ss.AlertVersionMismatchMail(strmsg, \"BeastConn\");\n //ss.SubmitUserLoginNotification_BeastPlugin(\"BeastConnection - _sa_NotifyHost() --- ERROR \" + message, \"_sa_NotifyHost\");\n //MessageBoxResult res = MessageBox.Show(message, \"BeastLite Update\", MessageBoxButton.YesNo);\n //props.Add(\"ReturnCode\", (int)res);\n }\n else if (type == \"LoadStatus\")\n {\n object key = \"ReturnCode\";\n object returnVal = 1;\n props.Add(ref key, ref returnVal);\n }\n }\n\n LogUtility.Info(\"BeastConn.cs\", \"_sa_NotifyHost()\", \"Sa Notify Host\");\n }\n catch (Exception ex)\n {\n LogUtility.Error(\"BeastConn.cs\", \"_sa_NotifyHost()\", ex.Message, ex);\n }\n }\n\n void _sa_ForceUpdate(string exeName)\n {\n //Debug.WriteLine(\"*************************_sa_ForceUpdate: status:\" + exeName);\n\n LogUtility.Info(\"BeastConn.cs\", \"_sa_ForceUpdate()\", exeName + \"_sa_ForceUpdate\");\n //ss.SubmitUserLoginNotification_BeastPlugin(\"BeastConnection - _sa_ForceUpdate()\", exeName);\n }\n\n void _sa_ForcedUnLoad()\n {\n //Debug.WriteLine(\"*************************_sa_ForcedUnLoad\");\n\n isForceUnload = true;\n\n //ss.SubmitUserLoginNotification_BeastPlugin(\"BeastConnection - _sa_ForcedUnLoad()\", \"_sa_ForcedUnLoad\");\n\n LogUtility.Info(\"BeastConn.cs\", \"_sa_ForcedUnLoad()\", \"sa Forced UnLoad\");\n }\n\n void _sa_ConnectionRestored()\n {\n //Debug.WriteLine(\"*************************_sa_ConnectionRestored: status:\");\n\n LogUtility.Info(\"BeastConn.cs\", \"_sa_ConnectionRestored()\", \"_sa_ConnectionRestored\");\n //ss.SubmitUserLoginNotification_BeastPlugin(\"BeastConnection - _sa_ConnectionRestored()\", \"_sa_ConnectionRestored: status:\");\n }\n\n void _sa_ConnectionLost()\n {\n //Debug.WriteLine(\"*************************_sa_ConnectionLost:\");\n\n isConnection = false;\n\n LogUtility.Info(\"BeastConn.cs\", \"_sa_ConnectionLost()\", \"_sa_ConnectionLost\");\n //ss.SubmitUserLoginNotification_BeastPlugin(\"BeastConnection - _sa_ConnectionLost()\", \"_sa_ConnectionLost\");\n }\n\n void _sa_AuthenticationFailed(string info)\n {\n //Debug.WriteLine(\"*************************_sa_AuthenticationFailed: status:\" + info);\n\n LogUtility.Info(\"BeastConn.cs\", \"_sa_AuthenticationFailed()\", info + \"; sa AuthenticationFailed\");\n\n //ss.SubmitUserLoginNotification_BeastPlugin(\"BeastConnection - _sa_AuthenticationFailed()\", info);\n }\n void _sa_StatusChanged(BeastClientPlugIn.ServerConnectionStatus Status, string info)\n {\n //Debug.WriteLine(\"*************************_sa_StatusChanged: status:\" + Status + \" :\" + info);\n\n if (Status == BeastClientPlugIn.ServerConnectionStatus.CONNECTIONSTATUS_ACTIVE)\n isConnection = true;\n else if (Status == BeastClientPlugIn.ServerConnectionStatus.CONNECTIONSTATUS_INACTIVE)\n {\n string sMailSubject = \"BeastClientPlugIn - Inactive Connection\";\n string sMailBody = \"
    \"\n + \"

    Beast Connection is INACTIVE. Detail is as below:

    \"\n + \"

    Status: \" + Status + \"

    \"\n + \"

    Method: sa _sa_StatusChanged

    \"\n + \"

    Information: \" + info + \"

    \"\n + \"

    Please contact us if you have any questions.

    \"\n + UtilityHandler.VCM_MailAddress_In_Html\n + \"
    \";\n\n string sMailTo = System.Configuration.ConfigurationManager.AppSettings[\"FromEmail\"].ToString();\n string sMailToCC = \"\"; // System.Configuration.ConfigurationManager.AppSettings[\"\"].ToString();\n string sMailToBCC = \"\";\n\n UtilityHandler.SendMail(sMailTo, sMailToCC, sMailToBCC, sMailSubject, sMailBody, false);\n }\n\n LogUtility.Info(\"BeastConn.cs\", \"_sa_StatusChanged()\", Status + \";\" + info + \"; sa _sa_StatusChanged\");\n //ss.SubmitUserLoginNotification_BeastPlugin(\"BeastConnection - _sa_StatusChanged()\", \"status:\" + Status + \" :\" + info);\n }\n #endregion\n\n #region Public Methods\n\n public static BeastConn Instance\n {\n get\n {\n if (instance == null)\n {\n lock (syncRoot)\n {\n if (instance == null)\n {\n\n instance = new BeastConn();\n Thread trd = new Thread(new ThreadStart(instance.runPlugIn));\n trd.Start();\n }\n }\n }\n\n return instance;\n }\n set // for resetting the singleton object\n {\n instance = value;\n }\n }\n\n public ServerAgent SA\n {\n get\n {\n if (_sa == null)\n {\n if (_sa == null)\n {\n _sa = new ServerAgent();\n }\n }\n\n return _sa;\n }\n }\n\n public int CreateBeastImage(string ProductID, string ConnectionID, string UserID, string CustomerID, string SpeacialImageID, string ActualProductID, bool IsSharedImage = false, string InstanceID = \"\", string username = \"\")\n {\n try\n {\n Thread.Sleep(1000);\n\n int iCount = 0;\n while (iCount < 15)\n {\n Thread.Sleep(1000);\n if (_sa.Status == ServerConnectionStatus.CONNECTIONSTATUS_ACTIVE)\n break;\n\n if ((_sa.Status != ServerConnectionStatus.CONNECTIONSTATUS_AUTHENTICATING && _sa.Status != ServerConnectionStatus.CONNECTIONSTATUS_CONNECTING) && _sa.Status == ServerConnectionStatus.CONNECTIONSTATUS_INACTIVE)\n break;\n\n if (isForceUnload)\n break;\n\n iCount++;\n }\n\n if (isForceUnload)\n {\n return 3; // incompatible Beast Version\n }\n if (_sa.Status == ServerConnectionStatus.CONNECTIONSTATUS_INACTIVE) // if connection is inactive then return false\n {\n return 2; // connection inactive\n }\n\n #region create the beast image\n string imageKey = getUserProductKeyForImage(ProductID, ConnectionID, UserID, CustomerID, SpeacialImageID);\n bool isImageAvail = isImageAvailable(imageKey);\n //--------------------------------------------------------\n\n if (!isImageAvail)\n {\n IProductImage bi = createProductImage(ProductID, ConnectionID, UserID, CustomerID, SpeacialImageID, ActualProductID, IsSharedImage, InstanceID, username); // create the beast image.\n\n if (bi.DocImage.Status == DOMDataDocStatus.DATADOCSTATUS_NA)\n {\n //ss.SubmitUserLoginNotification_BeastPlugin(\"BeastConnection - CreateBeastImage() ERROR \", \"Unable to create TheBeast Image.\");\n return 4; // Beast image creatin Failed\n }\n else\n {\n bi.refCount = 1;\n _dirBeastImg.Add(imageKey, bi); \n }\n }\n #endregion\n\n string strlogDesc = \"ProductId: \" + ProductID + \"; \" + \"UserId: \" + UserID + \"; \" + \"CustomerId: \" + CustomerID + \"; \" + \"ConnectionId: \" + ConnectionID + \"; SpeacialImageID :\" + SpeacialImageID +\"; Create Beast Image\";\n LogUtility.Info(\"BeastConn.cs\", \"CreateBeastImage()\", strlogDesc);\n\n //ss.SubmitUserLoginNotification_BeastPlugin(\"BeastConnection - CreateBeastImage()\", \"CREATE BEAST IMAGE SUCCESS\");\n return 1;// successful creation of beast image\n }\n catch (Exception ex)\n {\n string strErrorDesc = \"ProductId: \" + ProductID + \"; \" + \"UserId: \" + UserID + \"; \" + \"CustomerId: \" + CustomerID + \"; \" + \"ConnectionId: \" + ConnectionID + \"; SpeacialImageID :\" + SpeacialImageID + \"; \" + ex.Message;\n LogUtility.Error(\"BeastConn.cs\", \"CreateBeastImage()\", strErrorDesc, ex);\n throw;\n }\n finally\n {\n isForceUnload = false;\n }\n //return 1;\n }\n\n public IProductImage getBeastImage(string ProductID, string ConnectionID, string UserID, string CustomerID, string SpeacialImageID, string ActualProductID, bool IsSharedImage = false, string InstanceID = \"\", string username = \"\")\n {\n try\n {\n string imageKey = getUserProductKeyForImage(ProductID, ConnectionID, UserID, CustomerID, SpeacialImageID);\n if (_dirBeastImg.ContainsKey(imageKey))\n {\n return _dirBeastImg[imageKey];\n }\n else\n {\n CreateBeastImage(ProductID, ConnectionID, UserID, CustomerID, SpeacialImageID, ActualProductID, IsSharedImage, InstanceID, username);\n return getBeastImage(ProductID, ConnectionID, UserID, CustomerID, SpeacialImageID, ActualProductID, IsSharedImage, InstanceID, username);\n }\n\n string strlogDesc = \"ProductId: \" + ProductID + \"; \" + \"UserId: \" + UserID + \"; \" + \"CustomerId: \" + CustomerID + \"; \" + \"ConnectionId: \" + ConnectionID + \"; SpeacialImageID :\" + SpeacialImageID + \"; get Beast Image\";\n LogUtility.Info(\"BeastConn.cs\", \"getBeastImage()\", strlogDesc);\n }\n catch (Exception ex)\n {\n string strErrorDesc = \"ProductId: \" + ProductID + \"; \" + \"UserId: \" + UserID + \"; \" + \"CustomerId: \" + CustomerID + \"; \" + \"ConnectionId: \" + ConnectionID + \"; SpeacialImageID :\" + SpeacialImageID + \"; \" + ex.Message;\n LogUtility.Error(\"BeastConn.cs\", \"getBeastImage()\", strErrorDesc, ex);\n }\n return null;\n }\n\n public void RemoveBeastImage(string ProductID, string ConnectionID, string UserID, string CustomerID, string SpeacialImageID, bool createImage, string ActualProductID)\n {\n try\n {\n string imageKey = getUserProductKeyForImage(ProductID, ConnectionID, UserID, CustomerID, SpeacialImageID);\n\n _dirBeastImg.Remove(imageKey);\n\n if (createImage == true)\n CreateBeastImage(ProductID, ConnectionID, UserID, CustomerID, SpeacialImageID, ActualProductID);\n\n string strlogDesc = \"ProductId: \" + ProductID + \"; \" + \"UserId: \" + UserID + \"; \" + \"CustomerId: \" + CustomerID + \"; \" + \"ConnectionId: \" + ConnectionID + \"; SpeacialImageID :\" + SpeacialImageID + \"; Removed Beast Image\";\n LogUtility.Info(\"BeastConn.cs\", \"RemoveBeastImage()\", strlogDesc);\n }\n catch (Exception ex)\n {\n string strErrorDesc = \"ProductId: \" + ProductID + \"; \" + \"UserId: \" + UserID + \"; \" + \"CustomerId: \" + CustomerID + \"; \" + \"ConnectionId: \" + ConnectionID + \"; SpeacialImageID :\" + SpeacialImageID + \"; \" + ex.Message;\n LogUtility.Error(\"BeastConn.cs\", \"RemoveBeastImage()\", strErrorDesc, ex);\n }\n }\n\n public void DisconnectConnection()\n {\n //Debug.WriteLine(\"$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ Disconnect\");\n try\n {\n ////new\n _dirBeastImg.Clear();\n ////new\n _sa.Disconnect();\n Instance = null;\n LogUtility.Info(\"BeastConn.cs\", \"DisconnectConnection()\", \"Disconnect Connection\");\n }\n catch (Exception ex)\n {\n string errorMessage = ex.Message + \"
    \" + ex.Source + \"
    \" + ex.Source;\n UtilityHandler.SendEmailForError(\"BeastConn.cs:: DisconnectConnection :: \" + errorMessage.ToString());\n LogUtility.Error(\"BeastConn.cs\", \"DisconnectConnection()\", ex.Message, ex);\n }\n }\n\n public string getUserProductKeyForImage(string ProductID, string ConnectionID, string UserID, string CustomerID, string SpeacialImageID)\n {\n return ProductID + \"_\" + ConnectionID + \"_\" + UserID + \"_\" + CustomerID + \"_\" + SpeacialImageID;\n }\n public void CloseImageBeastConn(string ProductID, string ConnectionID, string UserID, string CustomerID, string SpecialImageID)\n {\n try\n {\n\n string imageKey = getUserProductKeyForImage(ProductID, ConnectionID, UserID, CustomerID, SpecialImageID);\n if (_dirBeastImg.ContainsKey(imageKey))\n {\n _dirBeastImg[imageKey].refCount = _dirBeastImg[imageKey].refCount - 1;\n if (_dirBeastImg[imageKey].refCount == 0)\n {\n if (_dirBeastImg[imageKey].InstanceID != \"\")\n {\n _dirBeastImg[imageKey].distoryBeastImage();\n _sa.CloseDocument(\"instid:\" + _dirBeastImg[imageKey].InstanceID.Split(':')[1].Trim() + \"\", null);\n _dirBeastImg.Remove(imageKey);\n }\n }\n }\n }\n catch (Exception ex)\n {\n string errorMessage = ex.Message + \"
    \" + ex.Source + \"
    \" + ex.Source;\n // UtilityHandler.SendEmailForError(\"BeastConn.cs:: CloseImageBeastConn :: \" + errorMessage.ToString());\n LogUtility.Error(\"BeastConn.cs\", \"CloseImageBeastConn()\", ex.Message, ex);\n }\n\n }\n public void CloseInitiatorImageForExcel(string ConnectionID, string UserID)\n {\n try\n {\n var filterImages = from img in _dirBeastImg\n where (img.Value.ConnectionID.Equals(ConnectionID) || img.Value.UserID.Equals(UserID))\n select img;\n\n foreach (var img in filterImages.ToList())\n {\n img.Value.refCount = img.Value.refCount - 1;\n if (img.Value.refCount == 0)\n {\n if (img.Value.InstanceID != \"\")\n {\n _sa.CloseDocument(\"instid:\" + img.Value.InstanceID.Split(':')[1].Trim() + \"\", null);\n RemoveBeastImage(img.Value.ProductID, img.Value.ConnectionID, img.Value.UserID, img.Value.CustomerID, img.Value.SpecialImageID, false, img.Value.ActualProductID);\n }\n }\n }\n\n }\n catch (Exception ex)\n {\n string errorMessage = ex.Message + \"
    \" + ex.Source + \"
    \" + ex.Source;\n // UtilityHandler.SendEmailForError(\"BeastConn.cs:: CloseInitiatorImageForExcel :: \" + errorMessage.ToString());\n LogUtility.Error(\"BeastConn.cs\", \"CloseInitiatorImageForExcel()\", ex.Message, ex);\n }\n\n }\n public bool isImageAvailable(string imageKey)\n {\n return _dirBeastImg.ContainsKey(imageKey);\n }\n\n public IProductImage createProductImage(string ProductID, string ConnectionID, string UserID, string CustomerID, string SpeacialImageID, string ActualProductID, bool IsSharedImage, string InstanceID, string username)\n {\n string strlogDesc = \"ProductId: \" + ProductID + \"; UserId: \" + UserID + \"; CustomerId: \" + CustomerID + \"; SpecialImageId: \" + SpeacialImageID + \"; ActualProductId: \" + ActualProductID + \"; IsSharedImage: \" + IsSharedImage + \"; InstanceID: \" + InstanceID + \"; ConnectionId: \" + ConnectionID + \"; \";\n\n try\n {\n if (AppsInfo.Instance._dirImgSID.ContainsKey(ActualProductID))\n {\n\n //Removable code start\n //if (AppsInfo.Instance._dirImgSID.ContainsKey(\"vcm_calc_swaptionVolPremStrike\") && ProductID == Convert.ToString(AppsInfo.Instance._dirImgSID[\"vcm_calc_swaptionVolPremStrike\"]))\n //{\n // LogUtility.Info(\"BeastConn.cs\", \"createProductImage()\", strlogDesc + \"::SWAPTIONVOLPREMSTRIKE::\");\n // return new SwaptionVolPrem(ProductID, ConnectionID, UserID, CustomerID, SpeacialImageID, ActualProductID, ref _sa, IsSharedImage, InstanceID, username);\n //}\n //else if (AppsInfo.Instance._dirImgSID.ContainsKey(\"vcm_calc_cmefuture\") && ProductID == Convert.ToString(AppsInfo.Instance._dirImgSID[\"vcm_calc_cmefuture\"]))\n //{\n // LogUtility.Info(\"BeastConn.cs\", \"createProductImage()\", strlogDesc + \"::CMEFUTURE::\");\n // return new CMEFuture(ProductID, ConnectionID, UserID, CustomerID, SpeacialImageID, ActualProductID, ref _sa, IsSharedImage, InstanceID, username);\n //}\n //else if (AppsInfo.Instance._dirImgSID.ContainsKey(\"vcm_calc_excelshare\") && AppsInfo.Instance.GetPropertyInfo(AppsInfo.Properties.IsGridImage, AppsInfo.Properties.SIF_Id, ProductID) == \"1\" && ProductID == Convert.ToString(AppsInfo.Instance._dirImgSID[\"vcm_calc_excelshare\"]))\n //{\n // LogUtility.Info(\"BeastConn.cs\", \"createProductImage()\", strlogDesc + \"::EXCELSHARE::\");\n // return new ExcelShare(ProductID, ConnectionID, UserID, CustomerID, SpeacialImageID, ActualProductID, ref _sa, IsSharedImage, InstanceID, username);\n //}\n //else if (AppsInfo.Instance.GetPropertyInfo(AppsInfo.Properties.IsGridImage, AppsInfo.Properties.SIF_Id, ProductID) == \"1\")\n //{\n // LogUtility.Info(\"BeastConn.cs\", \"createProductImage()\", strlogDesc + \"::GRIDIMAGE::\");\n // return new GridImages(ProductID, ConnectionID, UserID, CustomerID, SpeacialImageID, ActualProductID, ref _sa, IsSharedImage, InstanceID, username);\n //}\n //else if (AppsInfo.Instance._dirImgSID.ContainsKey(\"vcm_calc_geoTrackerDashboard\") && (ProductID == Convert.ToString(AppsInfo.Instance._dirImgSID[\"vcm_calc_geoTrackerDashboard\"]) || ProductID == Convert.ToString(AppsInfo.Instance._dirImgSID[\"2125\"])))\n //{\n // LogUtility.Info(\"BeastConn.cs\", \"createProductImage()\", strlogDesc + \"::PERSISTANTIMAGE::\");\n // return new SingleInstanceApp(ProductID, ConnectionID, UserID, CustomerID, SpeacialImageID, ActualProductID, ref _sa, IsSharedImage, InstanceID, username);\n //}\n //else if (AppsInfo.Instance._dirImgSID.ContainsKey(\"trumid_client\") && ProductID == Convert.ToString(AppsInfo.Instance._dirImgSID[\"trumid_client\"]))\n //{\n // LogUtility.Info(\"BeastConn.cs\", \"createProductImage()\", strlogDesc + \"::PERSISTANTIMAGE::\");\n // return new TradingGeneric(ProductID, ConnectionID, UserID, CustomerID, SpeacialImageID, ActualProductID, ref _sa, IsSharedImage, InstanceID, username);\n //}\n //Removable code end\n //else\n {\n LogUtility.Info(\"BeastConn.cs\", \"createProductImage()\", strlogDesc + \"::GENERICIMAGE::\");\n return new ProductClassGeneric(ProductID, ConnectionID, UserID, CustomerID, SpeacialImageID, ActualProductID, ref _sa, IsSharedImage, InstanceID, username);\n }\n }\n else\n {\n LogUtility.Info(\"BeastConn.cs\", \"createProductImage()\", strlogDesc + \"::Given product id is not found. Product ID: \" + ProductID);\n }\n }\n catch (Exception ex)\n {\n string errorMessage = ex.Message + \"
    \" + ex.Source + \"
    \" + ex.Source;\n UtilityHandler.SendEmailForError(\"BeastConn.cs:: createProductImage :: \" + errorMessage.ToString());\n\n string strErrorDesc = \"ProductId: \" + ProductID + \"; UserId: \" + UserID + \"; CustomerId: \" + CustomerID + \"; ConnectionId: \" + ConnectionID + \"; \" + ex.Message;\n LogUtility.Error(\"BeastConn.cs\", \"createProductImage()\", ex.Message, ex);\n }\n\n return null;\n }\n\n public void openProductImage(string ProductID, string ConnectionID, string UserID, string CustomerID, string SpeacialImageID, string ConnectionIDSignalR, string ActualProductID, string UserMode, string username)\n {\n try\n {\n //string instanceID = \"\";\n\n string imageKey = getUserProductKeyForImage(ProductID, ConnectionID, UserID, CustomerID, SpeacialImageID);\n if (_dirBeastImg.ContainsKey(imageKey))\n {\n _dirBeastImg[imageKey].openBeastImage(ProductID, ConnectionID, UserID, CustomerID, SpeacialImageID, ActualProductID, ref _sa, ConnectionIDSignalR, username);\n //instanceID = _dirBeastImg[imageKey].InstanceID;\n _dirBeastImg[imageKey].refCount = _dirBeastImg[imageKey].refCount + 1;\n }\n else\n {\n IProductImage iProdImg = BeastConn.Instance.getBeastImage(ProductID, ConnectionID, UserID, CustomerID, SpeacialImageID, ActualProductID, false, \"\", username);\n //instanceID = iProdImg.InstanceID;\n }\n //string instanceInfo = UserID + \"#\" + CustomerID + \"#\" + UserMode\n //2006149#100601#conn~vcm_calc_bondYield~2315f830-376b-4aec-b685-923383a0938a\n\n string strlogDesc = \"ProductId: \" + ProductID + \"; \" + \"UserId: \" + UserID + \"; \" + \"CustomerId: \" + CustomerID + \"; \" + \"ConnectionId: \" + ConnectionID + \"; open Product Image\";\n LogUtility.Info(\"BeastConn.cs\", \"openProductImage()\", strlogDesc);\n }\n catch (Exception ex)\n {\n string errorMessage = ex.Message + \"
    \" + ex.Source + \"
    \" + ex.Source;\n UtilityHandler.SendEmailForError(\"BeastConn.cs:: openProductImage :: \" + errorMessage.ToString());\n\n string strErrorDesc = \"ProductId: \" + ProductID + \"; UserId: \" + UserID + \"; CustomerId: \" + CustomerID + \"; ConnectionId: \" + ConnectionID + \"; \" + ex.Message;\n LogUtility.Error(\"BeastConn.cs\", \"openProductImage()\", ex.Message, ex);\n }\n }\n\n public void shareProductImage(string ProductID, string ConnectionID, string UserID, string CustomerID, string SpeacialImageID, string ConnectionIDSignalR, string InstanceID, string ActualProductID, string username)\n {\n try\n {\n string imageKey = getUserProductKeyForImage(ProductID, ConnectionID, UserID, CustomerID, SpeacialImageID);", "answers": [" if (_dirBeastImg.ContainsKey(imageKey))"], "length": 2225, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "17f3884f-d6e4-451d-bde9-f2537919d6b6", "reasoning": "The method shareProductImage starts by computing the imageKey. The next logical step, following patterns in other methods (e.g., openProductImage), is to check whether the dictionary _dirBeastImg already contains this key. Therefore the next line should be an if statement testing the presence of imageKey in _dirBeastImg.", "reasoning_model_answer": "if (_dirBeastImg.ContainsKey(imageKey))", "assistant_with_reasoning": "\nThe method shareProductImage starts by computing the imageKey. The next logical step, following patterns in other methods (e.g., openProductImage), is to check whether the dictionary _dirBeastImg already contains this key. Therefore the next line should be an if statement testing the presence of imageKey in _dirBeastImg.\n\nif (_dirBeastImg.ContainsKey(imageKey))", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 8.268, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 28308, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "if (_dirBeastImg.ContainsKey(imageKey))", "score": 0.87, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/*\n * To change this template, choose Tools | Templates\n * and open the template in the editor.\n */\npackage gov.hhs.fha.nhinc.transform.subdisc;\n\nimport javax.xml.bind.JAXBElement;\nimport junit.framework.Assert;\nimport org.hl7.v3.MCCIMT000100UV01Device;\nimport org.hl7.v3.MCCIMT000100UV01Receiver;\nimport org.hl7.v3.MCCIMT000100UV01Sender;\nimport org.hl7.v3.PRPAIN201305UV02;\nimport org.hl7.v3.PRPAIN201306UV02;\nimport org.hl7.v3.PRPAMT201301UV02Patient;\nimport org.junit.After;\nimport org.junit.AfterClass;\nimport org.junit.Before;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\nimport static org.junit.Assert.*;\nimport org.apache.commons.logging.Log;\nimport org.apache.commons.logging.LogFactory;\nimport org.hl7.v3.ActRelationshipMitigates;\nimport org.hl7.v3.CS;\nimport org.hl7.v3.II;\nimport org.hl7.v3.MCAIMT900001UV01DetectedIssueEvent;\nimport org.hl7.v3.MCAIMT900001UV01DetectedIssueManagement;\nimport org.hl7.v3.PRPAMT201301UV02Person;\nimport org.hl7.v3.TSExplicit;\nimport org.hl7.v3.XActMoodDefEvn;\nimport org.jmock.Expectations;\nimport org.jmock.Mockery;\nimport org.jmock.lib.legacy.ClassImposteriser;\n\n/**\n *\n * @author dunnek\n */\npublic class HL7PRPA201306TransformsTest {\n\n private Mockery context;\n\n private static Log log = LogFactory.getLog(HL7PRPA201306TransformsTest.class);\n private String localDeviceId = \"2.16.840.1.113883.3.200.1\";\n private String senderOID = \"2.16.840.1.113883.3.200\";\n private String receiverOID = \"2.16.840.1.113883.3.184\";\n private String patientFirstName = \"Thomas\";\n private String patientLastName = \"Kirtland\";\n private String gender = \"M\";\n private String birthTime = \"19261225\";\n private String ssn = \"134679852\";\n private String patId = \"46821564\";\n\n @BeforeClass\n public static void setUpClass() throws Exception {\n }\n\n @AfterClass\n public static void tearDownClass() throws Exception {\n }\n\n @Before\n public void setUp() {\n context = new Mockery() {\n\n {\n setImposteriser(ClassImposteriser.INSTANCE);\n }\n };\n }\n\n @After\n public void tearDown() {\n }\n\n @Test\n public void testCreatePRPA201306() {\n final Log mockLogger = context.mock(Log.class);\n HL7PRPA201306Transforms testSubject = new HL7PRPA201306Transforms() {\n\n @Override\n protected Log createLogger() {\n return mockLogger;\n }\n };\n context.checking(new Expectations() {\n\n {\n allowing(mockLogger).debug(with(any(String.class)));\n will(returnValue(with(any(PRPAIN201306UV02.class))));\n }\n });\n log.info(\"testCreatePRPA201306\");\n\n JAXBElement person = HL7PatientTransforms.create201301PatientPerson(patientFirstName, patientLastName, gender, birthTime, ssn);\n PRPAMT201301UV02Patient patient = HL7PatientTransforms.create201301Patient(person, patId, localDeviceId);\n\n PRPAIN201305UV02 query = HL7PRPA201305Transforms.createPRPA201305(patient, senderOID, receiverOID, localDeviceId);\n PRPAIN201306UV02 result = HL7PRPA201306Transforms.createPRPA201306(patient, senderOID, receiverOID, receiverOID, localDeviceId, query);\n\n context.assertIsSatisfied();\n\n TestHelper.assertReceiverIdEquals(receiverOID, result);\n TestHelper.assertSenderIdEquals(senderOID, result);\n /*\n TestHelper.assertPatientIdEquals(patId, localDeviceId, result);\n TestHelper.assertBirthTimeEquals(birthTime, result);\n TestHelper.assertPatientNameEquals(patientFirstName, patientLastName, result);\n TestHelper.assertGenderEquals(gender, result);\n */\n }\n\n @Test\n public void testcreatePRPA201306ForPatientNotFoundWillPass() {\n final Log mockLogger = context.mock(Log.class);\n HL7PRPA201306Transforms testSubject = new HL7PRPA201306Transforms() {\n\n @Override\n protected Log createLogger() {\n return mockLogger;\n }\n\n protected String getReceiverOIDFromPRPAIN201305UV02Request(PRPAIN201305UV02 oRequest) {\n return receiverOID;\n }\n\n protected String getSenderOIDFromPRPAIN201305UV02Request(PRPAIN201305UV02 oRequest) {\n return senderOID;\n }\n\n protected II getHL7MessageId(String receiverOID) {\n II oII = new II();\n oII.setRoot(receiverOID);\n\n return oII;\n }\n\n protected TSExplicit getHL7CreationTime() {\n return new TSExplicit();\n }\n\n protected II getHL7InteractionId() {\n return new II();\n }\n\n protected CS getHL7ProcessingCode() {\n return new CS();\n }\n\n protected CS getHL7ProcessingModeCode() {\n return new CS();\n }\n\n protected CS getHL7AcceptAckCode() {\n return new CS();\n }\n \n };\n context.checking(new Expectations() {\n\n {\n allowing(mockLogger).debug(with(any(String.class)));\n will(returnValue(with(any(PRPAIN201306UV02.class))));\n }\n });\n log.info(\"testcreatePRPA201306ForPatientNotFoundWillPass\");\n\n JAXBElement person = HL7PatientTransforms.create201301PatientPerson(patientFirstName, patientLastName, gender, birthTime, ssn);\n PRPAMT201301UV02Patient patient = HL7PatientTransforms.create201301Patient(person, patId, localDeviceId);\n\n PRPAIN201305UV02 query = HL7PRPA201305Transforms.createPRPA201305(patient, senderOID, receiverOID, localDeviceId);\n PRPAIN201306UV02 result = testSubject.createPRPA201306ForPatientNotFound(query);\n\n context.assertIsSatisfied();\n\n //reverse the sender and receiver expectations\n TestHelper.assertReceiverIdEquals(senderOID, result);\n TestHelper.assertSenderIdEquals(receiverOID, result);\n\n //AA (application accept) is returned in Acknowledgement.typeCode (transmission wrapper).\n Assert.assertNotNull(result.getAcknowledgement());\n Assert.assertEquals(\"AA\", result.getAcknowledgement().get(0).getTypeCode().getCode());\n //OK (data found, no errors) is returned in QueryAck.queryResponseCode (control act wrapper)\n Assert.assertNotNull(result.getControlActProcess());\n Assert.assertNotNull(result.getControlActProcess().getQueryAck());\n Assert.assertEquals(\"OK\", result.getControlActProcess().getQueryAck().getQueryResponseCode().getCode());\n //There is no RegistrationEvent returned in the response\n Assert.assertNotNull(result.getControlActProcess().getSubject());\n Assert.assertNotNull(result.getControlActProcess().getSubject().get(0));\n Assert.assertNull(result.getControlActProcess().getSubject().get(0).getRegistrationEvent());\n\n }\n\n @Test\n public void testcreatePRPA201306ForPatientNotFoundWillFailForNullRequest() {\n final Log mockLogger = context.mock(Log.class);\n HL7PRPA201306Transforms testSubject = new HL7PRPA201306Transforms() {\n\n @Override\n protected Log createLogger() {\n return mockLogger;\n }\n\n };\n context.checking(new Expectations() {\n\n {\n allowing(mockLogger).debug(with(any(String.class)));\n one(mockLogger).error(\"The incomming patient discovery request, PRPAIN201305UV02, message was null.\");\n will(returnValue(null));\n }\n });\n log.info(\"testcreatePRPA201306ForPatientNotFoundWillPass\");\n\n PRPAIN201306UV02 result = testSubject.createPRPA201306ForPatientNotFound(null);\n\n context.assertIsSatisfied();\n\n Assert.assertNull(result);\n\n }\n\n @Test\n public void testcreatePRPA201306ForPatientNotFoundWillFailForNullRequiredFields() {\n final Log mockLogger = context.mock(Log.class);\n HL7PRPA201306Transforms testSubject = new HL7PRPA201306Transforms() {\n\n @Override\n protected Log createLogger() {\n return mockLogger;\n }\n\n protected boolean areIncommingRequiredPRPAIN201305FieldsNull(PRPAIN201305UV02 oRequest) {\n return true;\n }\n\n };\n context.checking(new Expectations() {\n\n {\n allowing(mockLogger).debug(with(any(String.class)));\n one(mockLogger).error(\"One or more required fields from the patient discovery request \" +\n \"for the patient not found scenario are null.\");\n will(returnValue(null));\n }\n });\n log.info(\"testcreatePRPA201306ForPatientNotFoundWillPass\");\n\n PRPAIN201305UV02 query = new PRPAIN201305UV02();\n PRPAIN201306UV02 result = testSubject.createPRPA201306ForPatientNotFound(query);\n\n context.assertIsSatisfied();\n\n Assert.assertNull(result);\n\n }\n\n @Test\n public void testAreRequiredPRPAIN201305FieldsForPatientNotFoundNullWillFailForNullReceiver() {\n final Log mockLogger = context.mock(Log.class);\n HL7PRPA201306Transforms testSubject = new HL7PRPA201306Transforms() {\n\n @Override\n protected Log createLogger() {\n return mockLogger;\n }\n\n protected boolean areReceiverFieldsNull(PRPAIN201305UV02 oRequest){\n return true;\n }\n\n\n };\n context.checking(new Expectations() {\n\n {\n allowing(mockLogger).debug(with(any(String.class)));\n one(mockLogger).error(\"One or more request receiver fields are null or empty.\");\n one(mockLogger).error(\"One or more required fields from the patient discovery request \" +\n \"for the patient not found scenario are null.\");\n will(returnValue(null));\n }\n });\n log.info(\"testcreatePRPA201306ForPatientNotFoundWillPass\");\n\n PRPAIN201305UV02 query = new PRPAIN201305UV02();\n PRPAIN201306UV02 result = testSubject.createPRPA201306ForPatientNotFound(query);\n\n context.assertIsSatisfied();\n\n Assert.assertNull(result);\n\n }\n\n @Test\n public void testAreRequiredPRPAIN201305FieldsForPatientNotFoundNullWillFailForNullSender() {\n final Log mockLogger = context.mock(Log.class);\n HL7PRPA201306Transforms testSubject = new HL7PRPA201306Transforms() {\n\n @Override\n protected Log createLogger() {\n return mockLogger;\n }\n\n protected boolean areReceiverFieldsNull(PRPAIN201305UV02 oRequest){\n return false;\n }\n protected boolean areSenderFieldsNull(PRPAIN201305UV02 oRequest){\n return true;\n }\n\n };\n context.checking(new Expectations() {\n\n {\n allowing(mockLogger).debug(with(any(String.class)));\n one(mockLogger).error(\"One or more request sender fields are null or empty.\");\n one(mockLogger).error(\"One or more required fields from the patient discovery request \" +\n \"for the patient not found scenario are null.\");\n will(returnValue(null));\n }\n });\n log.info(\"testcreatePRPA201306ForPatientNotFoundWillPass\");\n\n PRPAIN201305UV02 query = new PRPAIN201305UV02();\n PRPAIN201306UV02 result = testSubject.createPRPA201306ForPatientNotFound(query);\n\n context.assertIsSatisfied();\n\n Assert.assertNull(result);\n\n }\n\n @Test\n public void testAreRequiredPRPAIN201305FieldsForPatientNotFoundNullWillFailForNullControlActProcess() {\n final Log mockLogger = context.mock(Log.class);\n HL7PRPA201306Transforms testSubject = new HL7PRPA201306Transforms() {\n\n @Override\n protected Log createLogger() {\n return mockLogger;\n }\n\n protected boolean areReceiverFieldsNull(PRPAIN201305UV02 oRequest){\n return false;\n }\n protected boolean areSenderFieldsNull(PRPAIN201305UV02 oRequest){\n return false;\n }\n\n protected boolean areControlActProcessFieldsNull (PRPAIN201305UV02 oRequest){\n return true;\n }\n\n };\n context.checking(new Expectations() {\n\n {\n allowing(mockLogger).debug(with(any(String.class)));\n one(mockLogger).error(\"One or more ControlActProcess fields from the incomming request were null.\");\n one(mockLogger).error(\"One or more required fields from the patient discovery request \" +\n \"for the patient not found scenario are null.\");\n will(returnValue(null));\n }\n });\n log.info(\"testcreatePRPA201306ForPatientNotFoundWillPass\");\n\n PRPAIN201305UV02 query = new PRPAIN201305UV02();\n PRPAIN201306UV02 result = testSubject.createPRPA201306ForPatientNotFound(query);\n\n context.assertIsSatisfied();\n\n Assert.assertNull(result);\n\n }\n\n @Test\n public void testAreRequiredPRPAIN201305FieldsForPatientNotFoundNullWillFailForNullInteractionId() {\n final Log mockLogger = context.mock(Log.class);\n HL7PRPA201306Transforms testSubject = new HL7PRPA201306Transforms() {\n\n @Override\n protected Log createLogger() {\n return mockLogger;\n }\n\n protected boolean areReceiverFieldsNull(PRPAIN201305UV02 oRequest){\n return false;\n }\n protected boolean areSenderFieldsNull(PRPAIN201305UV02 oRequest){\n return false;\n }\n\n protected boolean areControlActProcessFieldsNull (PRPAIN201305UV02 oRequest){\n return false;\n }\n\n };\n context.checking(new Expectations() {\n\n {\n allowing(mockLogger).debug(with(any(String.class)));\n one(mockLogger).error(\"The InteractionId object from the incomming request message is null.\");\n one(mockLogger).error(\"One or more required fields from the patient discovery request \" +\n \"for the patient not found scenario are null.\");\n will(returnValue(null));\n }\n });\n log.info(\"testcreatePRPA201306ForPatientNotFoundWillPass\");\n\n PRPAIN201305UV02 query = new PRPAIN201305UV02();\n PRPAIN201306UV02 result = testSubject.createPRPA201306ForPatientNotFound(query);\n\n context.assertIsSatisfied();\n\n Assert.assertNull(result);\n\n }\n\n @Test\n public void testAreReceiverFieldsNullWillFailForEmptyReceiverList() {\n final Log mockLogger = context.mock(Log.class);\n HL7PRPA201306Transforms testSubject = new HL7PRPA201306Transforms() {\n\n @Override\n protected Log createLogger() {\n return mockLogger;\n }\n\n };\n context.checking(new Expectations() {\n\n {\n allowing(mockLogger).debug(with(any(String.class)));\n one(mockLogger).error(\"The list of receiver objects from the incomming request message were null or empty.\");\n one(mockLogger).error(\"One or more request receiver fields are null or empty.\");\n one(mockLogger).error(\"One or more required fields from the patient discovery request \" +\n \"for the patient not found scenario are null.\");\n will(returnValue(null));\n }\n });\n\n PRPAIN201305UV02 query = new PRPAIN201305UV02();\n query.getReceiver().clear();\n PRPAIN201306UV02 result = testSubject.createPRPA201306ForPatientNotFound(query);\n\n context.assertIsSatisfied();\n\n Assert.assertNull(result);\n\n }\n\n @Test\n public void testAreReceiverFieldsNullWillFailForNullReceiver() {\n final Log mockLogger = context.mock(Log.class);\n HL7PRPA201306Transforms testSubject = new HL7PRPA201306Transforms() {\n\n @Override\n protected Log createLogger() {\n return mockLogger;\n }\n\n };\n context.checking(new Expectations() {\n\n {\n allowing(mockLogger).debug(with(any(String.class)));\n one(mockLogger).error(\"The request's receiver object is null.\");\n one(mockLogger).error(\"One or more request receiver fields are null or empty.\");\n one(mockLogger).error(\"One or more required fields from the patient discovery request \" +\n \"for the patient not found scenario are null.\");\n will(returnValue(null));\n }\n });\n\n PRPAIN201305UV02 query = new PRPAIN201305UV02();\n query.getReceiver().add(null);\n PRPAIN201306UV02 result = testSubject.createPRPA201306ForPatientNotFound(query);\n\n context.assertIsSatisfied();\n\n Assert.assertNull(result);\n\n }\n\n @Test\n public void testAreReceiverFieldsNullWillFailForNullReceiverDevice() {\n final Log mockLogger = context.mock(Log.class);\n HL7PRPA201306Transforms testSubject = new HL7PRPA201306Transforms() {\n\n @Override\n protected Log createLogger() {\n return mockLogger;\n }\n\n };\n context.checking(new Expectations() {\n\n {\n allowing(mockLogger).debug(with(any(String.class)));\n one(mockLogger).error(\"The request's receiver device object is null.\");\n one(mockLogger).error(\"One or more request receiver fields are null or empty.\");\n one(mockLogger).error(\"One or more required fields from the patient discovery request \" +\n \"for the patient not found scenario are null.\");\n will(returnValue(null));\n }\n });\n\n PRPAIN201305UV02 query = new PRPAIN201305UV02();\n MCCIMT000100UV01Device oDevice = null;\n MCCIMT000100UV01Receiver oReceiver = new MCCIMT000100UV01Receiver();\n oReceiver.setDevice(oDevice);\n query.getReceiver().add(oReceiver);\n PRPAIN201306UV02 result = testSubject.createPRPA201306ForPatientNotFound(query);\n\n context.assertIsSatisfied();\n\n Assert.assertNull(result);\n\n }\n\n @Test\n public void testAreReceiverFieldsNullWillFailForEmptyReceiverDeviceIds() {\n final Log mockLogger = context.mock(Log.class);\n HL7PRPA201306Transforms testSubject = new HL7PRPA201306Transforms() {\n\n @Override\n protected Log createLogger() {\n return mockLogger;\n }\n\n };\n context.checking(new Expectations() {\n\n {\n allowing(mockLogger).debug(with(any(String.class)));\n one(mockLogger).error(\"The list of device ids from the receiver object were null or empty.\");\n one(mockLogger).error(\"One or more request receiver fields are null or empty.\");\n one(mockLogger).error(\"One or more required fields from the patient discovery request \" +\n \"for the patient not found scenario are null.\");\n will(returnValue(null));\n }\n });\n\n PRPAIN201305UV02 query = new PRPAIN201305UV02();\n MCCIMT000100UV01Device oDevice = new MCCIMT000100UV01Device();\n oDevice.getId().clear();\n MCCIMT000100UV01Receiver oReceiver = new MCCIMT000100UV01Receiver();\n oReceiver.setDevice(oDevice);\n query.getReceiver().add(oReceiver);\n PRPAIN201306UV02 result = testSubject.createPRPA201306ForPatientNotFound(query);\n\n context.assertIsSatisfied();\n\n Assert.assertNull(result);\n\n }\n\n @Test\n public void testAreReceiverFieldsNullWillFailForNullReceiverDeviceId() {\n final Log mockLogger = context.mock(Log.class);\n HL7PRPA201306Transforms testSubject = new HL7PRPA201306Transforms() {\n\n @Override\n protected Log createLogger() {\n return mockLogger;\n }\n\n };\n context.checking(new Expectations() {\n\n {\n allowing(mockLogger).debug(with(any(String.class)));\n one(mockLogger).error(\"The device II id object is null.\");\n one(mockLogger).error(\"One or more request receiver fields are null or empty.\");\n one(mockLogger).error(\"One or more required fields from the patient discovery request \" +\n \"for the patient not found scenario are null.\");\n will(returnValue(null));\n }\n });\n\n PRPAIN201305UV02 query = new PRPAIN201305UV02();\n MCCIMT000100UV01Device oDevice = new MCCIMT000100UV01Device();\n II oII = null;\n oDevice.getId().add(oII);\n MCCIMT000100UV01Receiver oReceiver = new MCCIMT000100UV01Receiver();\n oReceiver.setDevice(oDevice);\n query.getReceiver().add(oReceiver);\n PRPAIN201306UV02 result = testSubject.createPRPA201306ForPatientNotFound(query);\n\n context.assertIsSatisfied();\n\n Assert.assertNull(result);\n\n }\n\n @Test\n public void testAreReceiverFieldsNullWillFailForNullReceiverDeviceIdGetRoot() {\n final Log mockLogger = context.mock(Log.class);\n HL7PRPA201306Transforms testSubject = new HL7PRPA201306Transforms() {\n\n @Override\n protected Log createLogger() {\n return mockLogger;\n }\n\n };\n context.checking(new Expectations() {\n\n {\n allowing(mockLogger).debug(with(any(String.class)));\n one(mockLogger).error(\"The device II id getRoot value is null.\");\n one(mockLogger).error(\"One or more request receiver fields are null or empty.\");\n one(mockLogger).error(\"One or more required fields from the patient discovery request \" +\n \"for the patient not found scenario are null.\");\n will(returnValue(null));\n }\n });\n\n PRPAIN201305UV02 query = new PRPAIN201305UV02();\n MCCIMT000100UV01Device oDevice = new MCCIMT000100UV01Device();\n II oII = new II();\n oDevice.getId().add(oII);\n MCCIMT000100UV01Receiver oReceiver = new MCCIMT000100UV01Receiver();\n oReceiver.setDevice(oDevice);\n query.getReceiver().add(oReceiver);\n PRPAIN201306UV02 result = testSubject.createPRPA201306ForPatientNotFound(query);\n\n context.assertIsSatisfied();\n\n Assert.assertNull(result);\n\n }\n\n @Test\n public void testAreSenderFieldsNullWillFailForNullSender() {\n final Log mockLogger = context.mock(Log.class);\n HL7PRPA201306Transforms testSubject = new HL7PRPA201306Transforms() {\n\n @Override\n protected Log createLogger() {\n return mockLogger;\n }\n\n protected boolean areReceiverFieldsNull(PRPAIN201305UV02 oRequest){\n return false;\n }\n\n };\n context.checking(new Expectations() {\n\n {\n allowing(mockLogger).debug(with(any(String.class)));\n one(mockLogger).error(\"The sender object from the incomming request message was null.\");\n one(mockLogger).error(\"One or more request sender fields are null or empty.\");\n one(mockLogger).error(\"One or more required fields from the patient discovery request \" +\n \"for the patient not found scenario are null.\");\n will(returnValue(null));\n }\n });\n\n PRPAIN201305UV02 query = new PRPAIN201305UV02();\n query.setSender(null);\n PRPAIN201306UV02 result = testSubject.createPRPA201306ForPatientNotFound(query);\n\n context.assertIsSatisfied();\n\n Assert.assertNull(result);\n\n }\n\n @Test\n public void testAreSenderFieldsNullWillFailForNullSenderDevice() {\n final Log mockLogger = context.mock(Log.class);\n HL7PRPA201306Transforms testSubject = new HL7PRPA201306Transforms() {\n\n @Override\n protected Log createLogger() {\n return mockLogger;\n }\n\n protected boolean areReceiverFieldsNull(PRPAIN201305UV02 oRequest){\n return false;\n }\n\n };\n context.checking(new Expectations() {\n\n {\n allowing(mockLogger).debug(with(any(String.class)));\n one(mockLogger).error(\"The request's sender device object is null.\");\n one(mockLogger).error(\"One or more request sender fields are null or empty.\");\n one(mockLogger).error(\"One or more required fields from the patient discovery request \" +\n \"for the patient not found scenario are null.\");\n will(returnValue(null));\n }\n });\n\n PRPAIN201305UV02 query = new PRPAIN201305UV02();\n MCCIMT000100UV01Sender oSender = new MCCIMT000100UV01Sender();\n query.setSender(oSender);\n PRPAIN201306UV02 result = testSubject.createPRPA201306ForPatientNotFound(query);\n\n context.assertIsSatisfied();\n\n Assert.assertNull(result);\n\n }\n\n @Test\n public void testAreSenderFieldsNullWillFailForEmptySenderDeviceIds() {\n final Log mockLogger = context.mock(Log.class);\n HL7PRPA201306Transforms testSubject = new HL7PRPA201306Transforms() {\n\n @Override\n protected Log createLogger() {\n return mockLogger;\n }\n\n protected boolean areReceiverFieldsNull(PRPAIN201305UV02 oRequest){\n return false;\n }\n\n };\n context.checking(new Expectations() {\n\n {\n allowing(mockLogger).debug(with(any(String.class)));\n one(mockLogger).error(\"The list of device ids from the sender object were null or empty.\");\n one(mockLogger).error(\"One or more request sender fields are null or empty.\");\n one(mockLogger).error(\"One or more required fields from the patient discovery request \" +\n \"for the patient not found scenario are null.\");\n will(returnValue(null));\n }\n });\n\n PRPAIN201305UV02 query = new PRPAIN201305UV02();\n MCCIMT000100UV01Device oDevice = new MCCIMT000100UV01Device();\n oDevice.getId().clear();\n MCCIMT000100UV01Sender oSender = new MCCIMT000100UV01Sender();\n oSender.setDevice(oDevice);\n query.setSender(oSender);\n PRPAIN201306UV02 result = testSubject.createPRPA201306ForPatientNotFound(query);\n\n context.assertIsSatisfied();\n\n Assert.assertNull(result);\n\n }\n\n @Test\n public void testAreSenderFieldsNullWillFailForNullSenderDeviceId() {\n final Log mockLogger = context.mock(Log.class);\n HL7PRPA201306Transforms testSubject = new HL7PRPA201306Transforms() {\n\n @Override\n protected Log createLogger() {\n return mockLogger;\n }\n\n protected boolean areReceiverFieldsNull(PRPAIN201305UV02 oRequest){\n return false;\n }\n\n };\n context.checking(new Expectations() {\n\n {\n allowing(mockLogger).debug(with(any(String.class)));\n one(mockLogger).error(\"The sender device id (II) object is null.\");\n one(mockLogger).error(\"One or more request sender fields are null or empty.\");\n one(mockLogger).error(\"One or more required fields from the patient discovery request \" +\n \"for the patient not found scenario are null.\");\n will(returnValue(null));\n }\n });\n\n PRPAIN201305UV02 query = new PRPAIN201305UV02();\n MCCIMT000100UV01Device oDevice = new MCCIMT000100UV01Device();\n II oII = null;\n oDevice.getId().add(oII);\n MCCIMT000100UV01Sender oSender = new MCCIMT000100UV01Sender();\n oSender.setDevice(oDevice);\n query.setSender(oSender);\n PRPAIN201306UV02 result = testSubject.createPRPA201306ForPatientNotFound(query);\n\n context.assertIsSatisfied();\n\n Assert.assertNull(result);\n\n }\n\n @Test\n public void testAreSenderFieldsNullWillFailForNullSenderDeviceIdGetRoot() {\n final Log mockLogger = context.mock(Log.class);\n HL7PRPA201306Transforms testSubject = new HL7PRPA201306Transforms() {\n\n @Override\n protected Log createLogger() {\n return mockLogger;\n }\n\n protected boolean areReceiverFieldsNull(PRPAIN201305UV02 oRequest){\n return false;\n }\n };\n context.checking(new Expectations() {\n\n {\n allowing(mockLogger).debug(with(any(String.class)));\n one(mockLogger).error(\"The device id value (i.e. II.getRoot() or \" +\n \"oRequest.getSender().getDevice().getId().get(0).getRoot()) is null.\");\n one(mockLogger).error(\"One or more request sender fields are null or empty.\");\n one(mockLogger).error(\"One or more required fields from the patient discovery request \" +\n \"for the patient not found scenario are null.\");\n will(returnValue(null));\n }\n });\n\n PRPAIN201305UV02 query = new PRPAIN201305UV02();\n MCCIMT000100UV01Device oDevice = new MCCIMT000100UV01Device();\n II oII = new II();\n oDevice.getId().add(oII);\n MCCIMT000100UV01Sender oSender = new MCCIMT000100UV01Sender();\n oSender.setDevice(oDevice);\n query.setSender(oSender);\n PRPAIN201306UV02 result = testSubject.createPRPA201306ForPatientNotFound(query);\n\n context.assertIsSatisfied();\n\n Assert.assertNull(result);\n\n }\n\n @Test\n public void testCreatePRPA201306ForErrorsWillPass()\n {\n\n final Log mockLogger = context.mock(Log.class);\n HL7PRPA201306Transforms testSubject = new HL7PRPA201306Transforms() {\n\n @Override\n protected Log createLogger() {\n return mockLogger;\n }\n\n protected String getReceiverOIDFromPRPAIN201305UV02Request(PRPAIN201305UV02 oRequest) {\n return receiverOID;\n }\n\n protected String getSenderOIDFromPRPAIN201305UV02Request(PRPAIN201305UV02 oRequest) {\n return senderOID;\n }\n\n protected II getHL7MessageId(String receiverOID) {\n II oII = new II();\n oII.setRoot(receiverOID);\n\n return oII;\n }\n\n protected TSExplicit getHL7CreationTime() {\n return new TSExplicit();\n }\n\n protected II getHL7InteractionId() {\n return new II();\n }\n\n protected CS getHL7ProcessingCode() {\n return new CS();\n }\n\n protected CS getHL7ProcessingModeCode() {\n return new CS();\n }\n\n protected CS getHL7AcceptAckCode() {\n return new CS();\n }\n\n };\n context.checking(new Expectations() {\n\n {\n allowing(mockLogger).debug(with(any(String.class)));\n will(returnValue(with(any(PRPAIN201306UV02.class))));\n }\n });\n log.info(\"testcreatePRPA201306ForPatientNotFoundWillPass\");\n\n JAXBElement person = HL7PatientTransforms.create201301PatientPerson(patientFirstName, patientLastName, gender, birthTime, ssn);\n PRPAMT201301UV02Patient patient = HL7PatientTransforms.create201301Patient(person, patId, localDeviceId);\n\n MCAIMT900001UV01DetectedIssueEvent oDetectedIssueEvent = new MCAIMT900001UV01DetectedIssueEvent();\n //\n oDetectedIssueEvent.getClassCode().add(HL7Constants.DETECTED_ISSUE_CLASSCODE_ALRT);\n oDetectedIssueEvent.getMoodCode().add(HL7Constants.DETECTED_ISSUE_MOODCODE_EVN);\n MCAIMT900001UV01DetectedIssueManagement oDetectedIssueManagement = new MCAIMT900001UV01DetectedIssueManagement();\n oDetectedIssueManagement.getClassCode().add(HL7Constants.DETECTEDISSUEMANAGEMENT_CLASSCODE);\n\n PRPAIN201305UV02 query = HL7PRPA201305Transforms.createPRPA201305(patient, senderOID, receiverOID, localDeviceId);\n PRPAIN201306UV02 result = testSubject.createPRPA201306ForErrors(query,HL7Constants.DETECTEDISSUEMANAGEMENT_CODE_RESPONDER_BUSY);\n\n context.assertIsSatisfied();\n\n //reverse the sender and receiver expectations\n TestHelper.assertReceiverIdEquals(senderOID, result);\n TestHelper.assertSenderIdEquals(receiverOID, result);\n\n //AA (application accept) is returned in Acknowledgement.typeCode (transmission wrapper).\n Assert.assertNotNull(result.getAcknowledgement());\n Assert.assertEquals(\"AA\", result.getAcknowledgement().get(0).getTypeCode().getCode());\n //QE (application error) is returned in QueryAck.queryResponseCode (control act wrapper)\n Assert.assertNotNull(result.getControlActProcess());\n Assert.assertNotNull(result.getControlActProcess().getQueryAck());\n Assert.assertEquals(\"QE\", result.getControlActProcess().getQueryAck().getQueryResponseCode().getCode());\n //There is no RegistrationEvent returned in the response\n Assert.assertNotNull(result.getControlActProcess().getSubject());\n Assert.assertNotNull(result.getControlActProcess().getSubject().get(0));\n Assert.assertNull(result.getControlActProcess().getSubject().get(0).getRegistrationEvent());\n\n // verify that the responderBusy code is returned\n Assert.assertNotNull(result.getControlActProcess().getReasonOf());\n Assert.assertNotNull(result.getControlActProcess().getReasonOf().get(0));\n Assert.assertNotNull(result.getControlActProcess().getReasonOf().get(0)\n .getDetectedIssueEvent());\n Assert.assertNotNull(result.getControlActProcess().getReasonOf().get(0)\n .getDetectedIssueEvent().getClassCode());\n Assert.assertEquals(oDetectedIssueEvent.getClassCode(),\n result.getControlActProcess().getReasonOf().get(0).getDetectedIssueEvent()\n .getClassCode());\n Assert.assertNotNull(result.getControlActProcess().getReasonOf().get(0)\n .getDetectedIssueEvent().getMoodCode());\n Assert.assertEquals(oDetectedIssueEvent.getMoodCode(),\n result.getControlActProcess().getReasonOf().get(0).getDetectedIssueEvent()\n .getMoodCode());\n Assert.assertNotNull(result.getControlActProcess().getReasonOf().get(0)\n .getDetectedIssueEvent().getCode());\n Assert.assertEquals(HL7Constants.DETECTED_ISSUE_CODE_ADMINISTRATIVE,result.getControlActProcess().getReasonOf().get(0)\n .getDetectedIssueEvent().getCode().getCode());\n Assert.assertNotNull(result.getControlActProcess().getReasonOf().get(0)\n .getDetectedIssueEvent().getCode().getCodeSystem());\n Assert.assertEquals(HL7Constants.DETECTED_ISSUE_CODESYSTEM_ERROR_CODE,result.getControlActProcess().getReasonOf().get(0)\n .getDetectedIssueEvent().getCode().getCodeSystem());\n Assert.assertNotNull(result.getControlActProcess().getReasonOf().get(0)\n .getDetectedIssueEvent().getMitigatedBy());\n Assert.assertNotNull(result.getControlActProcess().getReasonOf().get(0)\n .getDetectedIssueEvent().getMitigatedBy().get(0));\n Assert.assertNotNull(result.getControlActProcess().getReasonOf().get(0)\n .getDetectedIssueEvent().getMitigatedBy().get(0).getTypeCode());", "answers": [" Assert.assertEquals(ActRelationshipMitigates.MITGT, result.getControlActProcess()"], "length": 2250, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "49bd09e0-16ea-43e5-a0b2-cf2c6fc0c813", "reasoning": "The test method ends by asserting that the MitigatedBy element's typeCode is present. The next logical assertion checks that this typeCode has the expected enum value (MIT). In the HL7 model the enum XActRelationshipMitigates defines this value, so the next line should compare the retrieved typeCode to XActRelationshipMitigates.MIT.", "reasoning_model_answer": "Assert.assertEquals(XActRelationshipMitigates.MIT, result.getControlActProcess().getReasonOf().get(0)\n .getDetectedIssueEvent().getMitigatedBy().get(0).getTypeCode());", "assistant_with_reasoning": "\nThe test method ends by asserting that the MitigatedBy element's typeCode is present. The next logical assertion checks that this typeCode has the expected enum value (MIT). In the HL7 model the enum XActRelationshipMitigates defines this value, so the next line should compare the retrieved typeCode to XActRelationshipMitigates.MIT.\n\nAssert.assertEquals(XActRelationshipMitigates.MIT, result.getControlActProcess().getReasonOf().get(0)\n .getDetectedIssueEvent().getMitigatedBy().get(0).getTypeCode());", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.99, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 36118, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "Assert.assertEquals(XActRelationshipMitigates.MIT, result.getControlActProcess().getReasonOf().get(0)\n .getDetectedIssueEvent().getMitigatedBy().get(0).getTypeCode());", "score": 0.83, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "#!/usr/bin/python\n#\n# This file is part of Ansible\n#\n# Ansible is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# Ansible is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with Ansible. If not, see .\n#\n\nANSIBLE_METADATA = {'metadata_version': '1.1',\n 'status': ['preview'],\n 'supported_by': 'community'}\n\nDOCUMENTATION = '''\n---\nmodule: ce_stp\nversion_added: \"2.4\"\nshort_description: Manages STP configuration on HUAWEI CloudEngine switches.\ndescription:\n - Manages STP configurations on HUAWEI CloudEngine switches.\nauthor:\n - wangdezhuang (@CloudEngine-Ansible)\noptions:\n state:\n description:\n - Specify desired state of the resource.\n required: false\n default: present\n choices: ['present', 'absent']\n stp_mode:\n description:\n - Set an operation mode for the current MSTP process.\n The mode can be STP, RSTP, or MSTP.\n required: false\n default: null\n choices: ['stp', 'rstp', 'mstp']\n stp_enable:\n description:\n - Enable or disable STP on a switch.\n required: false\n default: null\n choices: ['enable', 'disable']\n stp_converge:\n description:\n - STP convergence mode.\n Fast means set STP aging mode to Fast.\n Normal means set STP aging mode to Normal.\n required: false\n default: null\n choices: ['fast', 'normal']\n bpdu_protection:\n description:\n - Configure BPDU protection on an edge port.\n This function prevents network flapping caused by attack packets.\n required: false\n default: null\n choices: ['enable', 'disable']\n tc_protection:\n description:\n - Configure the TC BPDU protection function for an MSTP process.\n required: false\n default: null\n choices: ['enable', 'disable']\n tc_protection_interval:\n description:\n - Set the time the MSTP device takes to handle the maximum number of TC BPDUs\n and immediately refresh forwarding entries.\n The value is an integer ranging from 1 to 600, in seconds.\n required: false\n default: null\n tc_protection_threshold:\n description:\n - Set the maximum number of TC BPDUs that the MSTP can handle.\n The value is an integer ranging from 1 to 255. The default value is 1 on the switch.\n required: false\n default: null\n interface:\n description:\n - Interface name.\n If the value is C(all), will apply configuration to all interfaces.\n if the value is a special name, only support input the full name.\n required: false\n default: null\n edged_port:\n description:\n - Set the current port as an edge port.\n required: false\n default: null\n choices: ['enable', 'disable']\n bpdu_filter:\n description:\n - Specify a port as a BPDU filter port.\n required: false\n default: null\n choices: ['enable', 'disable']\n cost:\n description:\n - Set the path cost of the current port.\n The default instance is 0.\n required: false\n default: null\n root_protection:\n description:\n - Enable root protection on the current port.\n required: false\n default: null\n choices: ['enable', 'disable']\n loop_protection:\n description:\n - Enable loop protection on the current port.\n required: false\n default: null\n choices: ['enable', 'disable']\n'''\n\nEXAMPLES = '''\n\n- name: CloudEngine stp test\n hosts: cloudengine\n connection: local\n gather_facts: no\n vars:\n cli:\n host: \"{{ inventory_hostname }}\"\n port: \"{{ ansible_ssh_port }}\"\n username: \"{{ username }}\"\n password: \"{{ password }}\"\n transport: cli\n\n tasks:\n\n - name: \"Config stp mode\"\n ce_stp:\n state: present\n stp_mode: stp\n provider: \"{{ cli }}\"\n\n - name: \"Undo stp mode\"\n ce_stp:\n state: absent\n stp_mode: stp\n provider: \"{{ cli }}\"\n\n - name: \"Enable bpdu protection\"\n ce_stp:\n state: present\n bpdu_protection: enable\n provider: \"{{ cli }}\"\n\n - name: \"Disable bpdu protection\"\n ce_stp:\n state: present\n bpdu_protection: disable\n provider: \"{{ cli }}\"\n'''\n\nRETURN = '''\nchanged:\n description: check to see if a change was made on the device\n returned: always\n type: boolean\n sample: true\nproposed:\n description: k/v pairs of parameters passed into module\n returned: always\n type: dict\n sample: {\"bpdu_protection\": \"enable\",\n \"state\": \"present\"}\nexisting:\n description: k/v pairs of existing aaa server\n returned: always\n type: dict\n sample: {\"bpdu_protection\": \"disable\"}\nend_state:\n description: k/v pairs of aaa params after module execution\n returned: always\n type: dict\n sample: {\"bpdu_protection\": \"enable\"}\nupdates:\n description: command sent to the device\n returned: always\n type: list\n sample: [\"stp bpdu-protection\"]\n'''\n\nimport re\nfrom ansible.module_utils.basic import AnsibleModule\nfrom ansible.module_utils.ce import get_config, load_config, ce_argument_spec\n\n\nclass Stp(object):\n \"\"\" Manages stp/rstp/mstp configuration \"\"\"\n\n def __init__(self, **kwargs):\n \"\"\" Stp module init \"\"\"\n\n # module\n argument_spec = kwargs[\"argument_spec\"]\n self.spec = argument_spec\n self.module = AnsibleModule(argument_spec=self.spec, supports_check_mode=True)\n\n # config\n self.cur_cfg = dict()\n self.stp_cfg = None\n self.interface_stp_cfg = None\n\n # module args\n self.state = self.module.params['state'] or None\n self.stp_mode = self.module.params['stp_mode'] or None\n self.stp_enable = self.module.params['stp_enable'] or None\n self.stp_converge = self.module.params['stp_converge'] or None\n self.interface = self.module.params['interface'] or None\n self.edged_port = self.module.params['edged_port'] or None\n self.bpdu_filter = self.module.params['bpdu_filter'] or None\n self.cost = self.module.params['cost'] or None\n self.bpdu_protection = self.module.params['bpdu_protection'] or None\n self.tc_protection = self.module.params['tc_protection'] or None\n self.tc_protection_interval = self.module.params['tc_protection_interval'] or None\n self.tc_protection_threshold = self.module.params['tc_protection_threshold'] or None\n self.root_protection = self.module.params['root_protection'] or None\n self.loop_protection = self.module.params['loop_protection'] or None\n\n # state\n self.changed = False\n self.updates_cmd = list()\n self.results = dict()\n self.proposed = dict()\n self.existing = dict()\n self.end_state = dict()\n\n def cli_load_config(self, commands):\n \"\"\" Cli load configuration \"\"\"\n\n if not self.module.check_mode:\n load_config(self.module, commands)\n\n def cli_get_stp_config(self):\n \"\"\" Cli get stp configuration \"\"\"\n\n regular = \"| include stp\"\n\n flags = list()\n flags.append(regular)\n self.stp_cfg = get_config(self.module, flags)\n\n def cli_get_interface_stp_config(self):\n \"\"\" Cli get interface's stp configuration \"\"\"\n\n if self.interface:\n regular = \"| ignore-case section include ^interface %s$\" % self.interface\n flags = list()\n flags.append(regular)\n tmp_cfg = get_config(self.module, flags)\n\n if not tmp_cfg:\n self.module.fail_json(\n msg='Error: The interface %s is not exist.' % self.interface)\n\n if \"undo portswitch\" in tmp_cfg:\n self.module.fail_json(\n msg='Error: The interface %s is not switch mode.' % self.interface)\n\n self.interface_stp_cfg = tmp_cfg\n\n def check_params(self):\n \"\"\" Check module params \"\"\"\n\n if self.cost:\n if self.cost.isdigit():\n if int(self.cost) < 1 or int(self.cost) > 200000000:\n self.module.fail_json(\n msg='Error: The value of cost is out of [1 - 200000000].')\n else:\n self.module.fail_json(\n msg='Error: The cost is not digit.')\n\n if self.tc_protection_interval:\n if self.tc_protection_interval.isdigit():\n if int(self.tc_protection_interval) < 1 or int(self.tc_protection_interval) > 600:\n self.module.fail_json(\n msg='Error: The value of tc_protection_interval is out of [1 - 600].')\n else:\n self.module.fail_json(\n msg='Error: The tc_protection_interval is not digit.')\n\n if self.tc_protection_threshold:\n if self.tc_protection_threshold.isdigit():\n if int(self.tc_protection_threshold) < 1 or int(self.tc_protection_threshold) > 255:\n self.module.fail_json(\n msg='Error: The value of tc_protection_threshold is out of [1 - 255].')\n else:\n self.module.fail_json(\n msg='Error: The tc_protection_threshold is not digit.')\n\n if self.root_protection or self.loop_protection or self.cost:\n if not self.interface:\n self.module.fail_json(\n msg='Error: Please input interface.')\n elif self.interface == \"all\":\n self.module.fail_json(\n msg='Error: Interface can not be all when config root_protection or loop_protection or cost.')\n\n if self.root_protection and self.root_protection == \"enable\":\n if self.loop_protection and self.loop_protection == \"enable\":\n self.module.fail_json(\n msg='Error: Can not enable root_protection and loop_protection at the same interface.')\n\n if self.edged_port or self.bpdu_filter:\n if not self.interface:\n self.module.fail_json(\n msg='Error: Please input interface.')\n\n def get_proposed(self):\n \"\"\" Get module proposed \"\"\"\n\n self.proposed[\"state\"] = self.state\n\n if self.stp_mode:\n self.proposed[\"stp_mode\"] = self.stp_mode\n if self.stp_enable:\n self.proposed[\"stp_enable\"] = self.stp_enable\n if self.stp_converge:\n self.proposed[\"stp_converge\"] = self.stp_converge\n if self.interface:\n self.proposed[\"interface\"] = self.interface\n if self.edged_port:\n self.proposed[\"edged_port\"] = self.edged_port\n if self.bpdu_filter:\n self.proposed[\"bpdu_filter\"] = self.bpdu_filter\n if self.cost:\n self.proposed[\"cost\"] = self.cost\n if self.bpdu_protection:\n self.proposed[\"bpdu_protection\"] = self.bpdu_protection\n if self.tc_protection:\n self.proposed[\"tc_protection\"] = self.tc_protection\n if self.tc_protection_interval:\n self.proposed[\"tc_protection_interval\"] = self.tc_protection_interval\n if self.tc_protection_threshold:\n self.proposed[\"tc_protection_threshold\"] = self.tc_protection_threshold\n if self.root_protection:\n self.proposed[\"root_protection\"] = self.root_protection\n if self.loop_protection:\n self.proposed[\"loop_protection\"] = self.loop_protection\n\n def get_existing(self):\n \"\"\" Get existing configuration \"\"\"\n\n self.cli_get_stp_config()\n if self.interface and self.interface != \"all\":\n self.cli_get_interface_stp_config()\n\n if self.stp_mode:\n if \"stp mode stp\" in self.stp_cfg:\n self.cur_cfg[\"stp_mode\"] = \"stp\"\n self.existing[\"stp_mode\"] = \"stp\"\n elif \"stp mode rstp\" in self.stp_cfg:\n self.cur_cfg[\"stp_mode\"] = \"rstp\"\n self.existing[\"stp_mode\"] = \"rstp\"\n else:\n self.cur_cfg[\"stp_mode\"] = \"mstp\"\n self.existing[\"stp_mode\"] = \"mstp\"\n\n if self.stp_enable:\n if \"stp disable\" in self.stp_cfg:\n self.cur_cfg[\"stp_enable\"] = \"disable\"\n self.existing[\"stp_enable\"] = \"disable\"\n else:\n self.cur_cfg[\"stp_enable\"] = \"enable\"\n self.existing[\"stp_enable\"] = \"enable\"\n\n if self.stp_converge:\n if \"stp converge fast\" in self.stp_cfg:\n self.cur_cfg[\"stp_converge\"] = \"fast\"\n self.existing[\"stp_converge\"] = \"fast\"\n else:\n self.cur_cfg[\"stp_converge\"] = \"normal\"\n self.existing[\"stp_converge\"] = \"normal\"\n\n if self.edged_port:\n if self.interface == \"all\":\n if \"stp edged-port default\" in self.stp_cfg:\n self.cur_cfg[\"edged_port\"] = \"enable\"\n self.existing[\"edged_port\"] = \"enable\"\n else:\n self.cur_cfg[\"edged_port\"] = \"disable\"\n self.existing[\"edged_port\"] = \"disable\"\n else:\n if \"stp edged-port enable\" in self.interface_stp_cfg:\n self.cur_cfg[\"edged_port\"] = \"enable\"\n self.existing[\"edged_port\"] = \"enable\"\n else:\n self.cur_cfg[\"edged_port\"] = \"disable\"\n self.existing[\"edged_port\"] = \"disable\"\n\n if self.bpdu_filter:\n if self.interface == \"all\":\n if \"stp bpdu-filter default\" in self.stp_cfg:\n self.cur_cfg[\"bpdu_filter\"] = \"enable\"\n self.existing[\"bpdu_filter\"] = \"enable\"\n else:\n self.cur_cfg[\"bpdu_filter\"] = \"disable\"\n self.existing[\"bpdu_filter\"] = \"disable\"\n else:\n if \"stp bpdu-filter enable\" in self.interface_stp_cfg:\n self.cur_cfg[\"bpdu_filter\"] = \"enable\"\n self.existing[\"bpdu_filter\"] = \"enable\"\n else:\n self.cur_cfg[\"bpdu_filter\"] = \"disable\"\n self.existing[\"bpdu_filter\"] = \"disable\"\n\n if self.bpdu_protection:\n if \"stp bpdu-protection\" in self.stp_cfg:\n self.cur_cfg[\"bpdu_protection\"] = \"enable\"\n self.existing[\"bpdu_protection\"] = \"enable\"\n else:\n self.cur_cfg[\"bpdu_protection\"] = \"disable\"\n self.existing[\"bpdu_protection\"] = \"disable\"\n\n if self.tc_protection:\n if \"stp tc-protection\" in self.stp_cfg:\n self.cur_cfg[\"tc_protection\"] = \"enable\"\n self.existing[\"tc_protection\"] = \"enable\"\n else:\n self.cur_cfg[\"tc_protection\"] = \"disable\"\n self.existing[\"tc_protection\"] = \"disable\"\n\n if self.tc_protection_interval:\n if \"stp tc-protection interval\" in self.stp_cfg:\n tmp_value = re.findall(r'stp tc-protection interval (.*)', self.stp_cfg)\n if not tmp_value:\n self.module.fail_json(\n msg='Error: Can not find tc-protection interval on the device.')\n self.cur_cfg[\"tc_protection_interval\"] = tmp_value[0]\n self.existing[\"tc_protection_interval\"] = tmp_value[0]\n else:\n self.cur_cfg[\"tc_protection_interval\"] = \"null\"\n self.existing[\"tc_protection_interval\"] = \"null\"\n\n if self.tc_protection_threshold:\n if \"stp tc-protection threshold\" in self.stp_cfg:\n tmp_value = re.findall(r'stp tc-protection threshold (.*)', self.stp_cfg)\n if not tmp_value:\n self.module.fail_json(\n msg='Error: Can not find tc-protection threshold on the device.')\n self.cur_cfg[\"tc_protection_threshold\"] = tmp_value[0]\n self.existing[\"tc_protection_threshold\"] = tmp_value[0]\n else:\n self.cur_cfg[\"tc_protection_threshold\"] = \"1\"\n self.existing[\"tc_protection_threshold\"] = \"1\"\n\n if self.cost:\n tmp_value = re.findall(r'stp instance (.*) cost (.*)', self.interface_stp_cfg)\n if not tmp_value:\n self.cur_cfg[\"cost\"] = \"null\"\n self.existing[\"cost\"] = \"null\"\n else:\n self.cur_cfg[\"cost\"] = tmp_value[0][1]\n self.existing[\"cost\"] = tmp_value[0][1]\n\n # root_protection and loop_protection should get configuration at the same time\n if self.root_protection or self.loop_protection:\n if \"stp root-protection\" in self.interface_stp_cfg:\n self.cur_cfg[\"root_protection\"] = \"enable\"\n self.existing[\"root_protection\"] = \"enable\"\n else:\n self.cur_cfg[\"root_protection\"] = \"disable\"\n self.existing[\"root_protection\"] = \"disable\"\n\n if \"stp loop-protection\" in self.interface_stp_cfg:\n self.cur_cfg[\"loop_protection\"] = \"enable\"\n self.existing[\"loop_protection\"] = \"enable\"\n else:\n self.cur_cfg[\"loop_protection\"] = \"disable\"\n self.existing[\"loop_protection\"] = \"disable\"\n\n def get_end_state(self):\n \"\"\" Get end state \"\"\"\n\n self.cli_get_stp_config()\n if self.interface and self.interface != \"all\":\n self.cli_get_interface_stp_config()\n\n if self.stp_mode:\n if \"stp mode stp\" in self.stp_cfg:\n self.end_state[\"stp_mode\"] = \"stp\"\n elif \"stp mode rstp\" in self.stp_cfg:\n self.end_state[\"stp_mode\"] = \"rstp\"\n else:\n self.end_state[\"stp_mode\"] = \"mstp\"\n\n if self.stp_enable:\n if \"stp disable\" in self.stp_cfg:\n self.end_state[\"stp_enable\"] = \"disable\"\n else:\n self.end_state[\"stp_enable\"] = \"enable\"\n\n if self.stp_converge:\n if \"stp converge fast\" in self.stp_cfg:\n self.end_state[\"stp_converge\"] = \"fast\"\n else:\n self.end_state[\"stp_converge\"] = \"normal\"\n\n if self.edged_port:\n if self.interface == \"all\":\n if \"stp edged-port default\" in self.stp_cfg:\n self.end_state[\"edged_port\"] = \"enable\"\n else:\n self.end_state[\"edged_port\"] = \"disable\"\n else:\n if \"stp edged-port enable\" in self.interface_stp_cfg:\n self.end_state[\"edged_port\"] = \"enable\"\n else:\n self.end_state[\"edged_port\"] = \"disable\"\n\n if self.bpdu_filter:\n if self.interface == \"all\":\n if \"stp bpdu-filter default\" in self.stp_cfg:\n self.end_state[\"bpdu_filter\"] = \"enable\"\n else:\n self.end_state[\"bpdu_filter\"] = \"disable\"\n else:\n if \"stp bpdu-filter enable\" in self.interface_stp_cfg:\n self.end_state[\"bpdu_filter\"] = \"enable\"\n else:\n self.end_state[\"bpdu_filter\"] = \"disable\"\n\n if self.bpdu_protection:\n if \"stp bpdu-protection\" in self.stp_cfg:\n self.end_state[\"bpdu_protection\"] = \"enable\"\n else:\n self.end_state[\"bpdu_protection\"] = \"disable\"\n\n if self.tc_protection:\n if \"stp tc-protection\" in self.stp_cfg:\n self.end_state[\"tc_protection\"] = \"enable\"\n else:\n self.end_state[\"tc_protection\"] = \"disable\"\n\n if self.tc_protection_interval:\n if \"stp tc-protection interval\" in self.stp_cfg:\n tmp_value = re.findall(r'stp tc-protection interval (.*)', self.stp_cfg)\n if not tmp_value:\n self.module.fail_json(\n msg='Error: Can not find tc-protection interval on the device.')\n self.end_state[\"tc_protection_interval\"] = tmp_value[0]\n else:\n self.end_state[\"tc_protection_interval\"] = \"null\"\n\n if self.tc_protection_threshold:\n if \"stp tc-protection threshold\" in self.stp_cfg:\n tmp_value = re.findall(r'stp tc-protection threshold (.*)', self.stp_cfg)\n if not tmp_value:\n self.module.fail_json(\n msg='Error: Can not find tc-protection threshold on the device.')\n self.end_state[\"tc_protection_threshold\"] = tmp_value[0]\n else:\n self.end_state[\"tc_protection_threshold\"] = \"1\"\n\n if self.cost:\n tmp_value = re.findall(r'stp instance (.*) cost (.*)', self.interface_stp_cfg)\n if not tmp_value:\n self.end_state[\"cost\"] = \"null\"\n else:\n self.end_state[\"cost\"] = tmp_value[0][1]\n\n if self.root_protection:\n if \"stp root-protection\" in self.interface_stp_cfg:\n self.end_state[\"root_protection\"] = \"enable\"\n else:\n self.end_state[\"root_protection\"] = \"disable\"\n\n if self.loop_protection:\n if \"stp loop-protection\" in self.interface_stp_cfg:\n self.end_state[\"loop_protection\"] = \"enable\"\n else:\n self.end_state[\"loop_protection\"] = \"disable\"\n\n def present_stp(self):\n \"\"\" Present stp configuration \"\"\"\n\n cmds = list()\n\n # cofig stp global\n if self.stp_mode:\n if self.stp_mode != self.cur_cfg[\"stp_mode\"]:\n cmd = \"stp mode %s\" % self.stp_mode\n cmds.append(cmd)\n self.updates_cmd.append(cmd)\n\n if self.stp_enable:\n if self.stp_enable != self.cur_cfg[\"stp_enable\"]:\n cmd = \"stp %s\" % self.stp_enable\n cmds.append(cmd)\n self.updates_cmd.append(cmd)\n\n if self.stp_converge:\n if self.stp_converge != self.cur_cfg[\"stp_converge\"]:\n cmd = \"stp converge %s\" % self.stp_converge\n cmds.append(cmd)\n self.updates_cmd.append(cmd)\n\n if self.edged_port:\n if self.interface == \"all\":\n if self.edged_port != self.cur_cfg[\"edged_port\"]:\n if self.edged_port == \"enable\":\n cmd = \"stp edged-port default\"\n cmds.append(cmd)\n self.updates_cmd.append(cmd)\n else:\n cmd = \"undo stp edged-port default\"\n cmds.append(cmd)\n self.updates_cmd.append(cmd)\n\n if self.bpdu_filter:\n if self.interface == \"all\":\n if self.bpdu_filter != self.cur_cfg[\"bpdu_filter\"]:\n if self.bpdu_filter == \"enable\":\n cmd = \"stp bpdu-filter default\"\n cmds.append(cmd)\n self.updates_cmd.append(cmd)\n else:\n cmd = \"undo stp bpdu-filter default\"\n cmds.append(cmd)\n self.updates_cmd.append(cmd)\n\n if self.bpdu_protection:\n if self.bpdu_protection != self.cur_cfg[\"bpdu_protection\"]:\n if self.bpdu_protection == \"enable\":\n cmd = \"stp bpdu-protection\"\n cmds.append(cmd)\n self.updates_cmd.append(cmd)\n else:\n cmd = \"undo stp bpdu-protection\"\n cmds.append(cmd)\n self.updates_cmd.append(cmd)\n\n if self.tc_protection:\n if self.tc_protection != self.cur_cfg[\"tc_protection\"]:\n if self.tc_protection == \"enable\":\n cmd = \"stp tc-protection\"\n cmds.append(cmd)\n self.updates_cmd.append(cmd)\n else:\n cmd = \"undo stp tc-protection\"\n cmds.append(cmd)\n self.updates_cmd.append(cmd)\n\n if self.tc_protection_interval:\n if self.tc_protection_interval != self.cur_cfg[\"tc_protection_interval\"]:\n cmd = \"stp tc-protection interval %s\" % self.tc_protection_interval\n cmds.append(cmd)\n self.updates_cmd.append(cmd)\n\n if self.tc_protection_threshold:\n if self.tc_protection_threshold != self.cur_cfg[\"tc_protection_threshold\"]:\n cmd = \"stp tc-protection threshold %s\" % self.tc_protection_threshold\n cmds.append(cmd)\n self.updates_cmd.append(cmd)\n\n # config interface stp\n if self.interface and self.interface != \"all\":\n tmp_changed = False\n\n cmd = \"interface %s\" % self.interface\n cmds.append(cmd)\n self.updates_cmd.append(cmd)\n\n if self.edged_port:\n if self.edged_port != self.cur_cfg[\"edged_port\"]:\n if self.edged_port == \"enable\":\n cmd = \"stp edged-port enable\"\n cmds.append(cmd)\n self.updates_cmd.append(cmd)\n tmp_changed = True\n else:\n cmd = \"undo stp edged-port\"\n cmds.append(cmd)\n self.updates_cmd.append(cmd)\n tmp_changed = True\n\n if self.bpdu_filter:\n if self.bpdu_filter != self.cur_cfg[\"bpdu_filter\"]:\n if self.bpdu_filter == \"enable\":\n cmd = \"stp bpdu-filter enable\"\n cmds.append(cmd)\n self.updates_cmd.append(cmd)\n tmp_changed = True\n else:\n cmd = \"undo stp bpdu-filter\"\n cmds.append(cmd)\n self.updates_cmd.append(cmd)\n tmp_changed = True\n\n if self.root_protection:\n if self.root_protection == \"enable\" and self.cur_cfg[\"loop_protection\"] == \"enable\":\n self.module.fail_json(\n msg='Error: The interface has enable loop_protection, can not enable root_protection.')\n if self.root_protection != self.cur_cfg[\"root_protection\"]:\n if self.root_protection == \"enable\":\n cmd = \"stp root-protection\"\n cmds.append(cmd)\n self.updates_cmd.append(cmd)\n tmp_changed = True\n else:\n cmd = \"undo stp root-protection\"\n cmds.append(cmd)\n self.updates_cmd.append(cmd)\n tmp_changed = True\n\n if self.loop_protection:\n if self.loop_protection == \"enable\" and self.cur_cfg[\"root_protection\"] == \"enable\":\n self.module.fail_json(\n msg='Error: The interface has enable root_protection, can not enable loop_protection.')\n if self.loop_protection != self.cur_cfg[\"loop_protection\"]:\n if self.loop_protection == \"enable\":\n cmd = \"stp loop-protection\"\n cmds.append(cmd)\n self.updates_cmd.append(cmd)\n tmp_changed = True\n else:\n cmd = \"undo stp loop-protection\"\n cmds.append(cmd)\n self.updates_cmd.append(cmd)\n tmp_changed = True\n\n if self.cost:\n if self.cost != self.cur_cfg[\"cost\"]:\n cmd = \"stp cost %s\" % self.cost\n cmds.append(cmd)\n self.updates_cmd.append(cmd)\n tmp_changed = True\n\n if not tmp_changed:\n cmd = \"interface %s\" % self.interface\n self.updates_cmd.remove(cmd)\n cmds.remove(cmd)\n\n if cmds:\n self.cli_load_config(cmds)\n self.changed = True\n\n def absent_stp(self):\n \"\"\" Absent stp configuration \"\"\"\n\n cmds = list()\n\n if self.stp_mode:\n if self.stp_mode == self.cur_cfg[\"stp_mode\"]:\n if self.stp_mode != \"mstp\":\n cmd = \"undo stp mode\"\n cmds.append(cmd)\n self.updates_cmd.append(cmd)\n self.changed = True\n\n if self.stp_enable:\n if self.stp_enable != self.cur_cfg[\"stp_enable\"]:\n cmd = \"stp %s\" % self.stp_enable\n cmds.append(cmd)\n self.updates_cmd.append(cmd)\n\n if self.stp_converge:\n if self.stp_converge == self.cur_cfg[\"stp_converge\"]:\n cmd = \"undo stp converge\"\n cmds.append(cmd)\n self.updates_cmd.append(cmd)\n self.changed = True\n\n if self.edged_port:\n if self.interface == \"all\":\n if self.edged_port != self.cur_cfg[\"edged_port\"]:\n if self.edged_port == \"enable\":\n cmd = \"stp edged-port default\"\n cmds.append(cmd)\n self.updates_cmd.append(cmd)\n else:\n cmd = \"undo stp edged-port default\"\n cmds.append(cmd)\n self.updates_cmd.append(cmd)\n\n if self.bpdu_filter:\n if self.interface == \"all\":\n if self.bpdu_filter != self.cur_cfg[\"bpdu_filter\"]:\n if self.bpdu_filter == \"enable\":\n cmd = \"stp bpdu-filter default\"\n cmds.append(cmd)\n self.updates_cmd.append(cmd)\n else:\n cmd = \"undo stp bpdu-filter default\"\n cmds.append(cmd)\n self.updates_cmd.append(cmd)\n\n if self.bpdu_protection:\n if self.bpdu_protection != self.cur_cfg[\"bpdu_protection\"]:\n if self.bpdu_protection == \"enable\":\n cmd = \"stp bpdu-protection\"\n cmds.append(cmd)\n self.updates_cmd.append(cmd)\n else:\n cmd = \"undo stp bpdu-protection\"\n cmds.append(cmd)\n self.updates_cmd.append(cmd)\n\n if self.tc_protection:\n if self.tc_protection != self.cur_cfg[\"tc_protection\"]:\n if self.tc_protection == \"enable\":\n cmd = \"stp tc-protection\"\n cmds.append(cmd)\n self.updates_cmd.append(cmd)\n else:\n cmd = \"undo stp tc-protection\"\n cmds.append(cmd)\n self.updates_cmd.append(cmd)\n\n if self.tc_protection_interval:\n if self.tc_protection_interval == self.cur_cfg[\"tc_protection_interval\"]:\n cmd = \"undo stp tc-protection interval\"\n cmds.append(cmd)\n self.updates_cmd.append(cmd)\n self.changed = True\n\n if self.tc_protection_threshold:", "answers": [" if self.tc_protection_threshold == self.cur_cfg[\"tc_protection_threshold\"]:"], "length": 2420, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "c905d067-7edc-48c5-8848-698a1152c28d", "reasoning": "In the absent_stp method, after handling tc_protection_interval, the next logical block handles tc_protection_threshold similarly. The existing line ends with 'if self.tc_protection_threshold:' and the next line should start the inner condition checking whether the current config matches the desired threshold, i.e., 'if self.tc_protection_threshold == self.cur_cfg[\"tc_protection_threshold\"]:'.", "reasoning_model_answer": "if self.tc_protection_threshold == self.cur_cfg[\"tc_protection_threshold\"]:", "assistant_with_reasoning": "\nIn the absent_stp method, after handling tc_protection_interval, the next logical block handles tc_protection_threshold similarly. The existing line ends with 'if self.tc_protection_threshold:' and the next line should start the inner condition checking whether the current config matches the desired threshold, i.e., 'if self.tc_protection_threshold == self.cur_cfg[\"tc_protection_threshold\"]:'.\n\nif self.tc_protection_threshold == self.cur_cfg[\"tc_protection_threshold\"]:", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.956, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 32273, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "if self.tc_protection_threshold == self.cur_cfg[\"tc_protection_threshold\"]:", "score": 0.93, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License. See License.txt in the project root for license information.\n// \n// Code generated by Microsoft (R) AutoRest Code Generator.\n// Changes may cause incorrect behavior and will be lost if the code is\n// regenerated.\n\n//\n// This file was autogenerated by a tool.\n// Do not modify it.\n//\n\nnamespace Microsoft.Azure.Batch\n{\n using Models = Microsoft.Azure.Batch.Protocol.Models;\n using System;\n using System.Collections.Generic;\n using System.Linq;\n\n /// \n /// A pool in the Azure Batch service.\n /// \n public partial class CloudPool : ITransportObjectProvider, IInheritedBehaviors, IPropertyMetadata\n {\n private class PropertyContainer : PropertyCollection\n {\n public readonly PropertyAccessor AllocationStateProperty;\n public readonly PropertyAccessor AllocationStateTransitionTimeProperty;\n public readonly PropertyAccessor> ApplicationLicensesProperty;\n public readonly PropertyAccessor> ApplicationPackageReferencesProperty;\n public readonly PropertyAccessor AutoScaleEnabledProperty;\n public readonly PropertyAccessor AutoScaleEvaluationIntervalProperty;\n public readonly PropertyAccessor AutoScaleFormulaProperty;\n public readonly PropertyAccessor AutoScaleRunProperty;\n public readonly PropertyAccessor> CertificateReferencesProperty;\n public readonly PropertyAccessor CloudServiceConfigurationProperty;\n public readonly PropertyAccessor CreationTimeProperty;\n public readonly PropertyAccessor CurrentDedicatedComputeNodesProperty;\n public readonly PropertyAccessor CurrentLowPriorityComputeNodesProperty;\n public readonly PropertyAccessor DisplayNameProperty;\n public readonly PropertyAccessor ETagProperty;\n public readonly PropertyAccessor IdProperty;\n public readonly PropertyAccessor IdentityProperty;\n public readonly PropertyAccessor InterComputeNodeCommunicationEnabledProperty;\n public readonly PropertyAccessor LastModifiedProperty;\n public readonly PropertyAccessor> MetadataProperty;\n public readonly PropertyAccessor> MountConfigurationProperty;\n public readonly PropertyAccessor NetworkConfigurationProperty;\n public readonly PropertyAccessor> ResizeErrorsProperty;\n public readonly PropertyAccessor ResizeTimeoutProperty;\n public readonly PropertyAccessor StartTaskProperty;\n public readonly PropertyAccessor StateProperty;\n public readonly PropertyAccessor StateTransitionTimeProperty;\n public readonly PropertyAccessor StatisticsProperty;\n public readonly PropertyAccessor TargetDedicatedComputeNodesProperty;\n public readonly PropertyAccessor TargetLowPriorityComputeNodesProperty;\n public readonly PropertyAccessor TaskSchedulingPolicyProperty;\n public readonly PropertyAccessor TaskSlotsPerNodeProperty;\n public readonly PropertyAccessor UrlProperty;\n public readonly PropertyAccessor> UserAccountsProperty;\n public readonly PropertyAccessor VirtualMachineConfigurationProperty;\n public readonly PropertyAccessor VirtualMachineSizeProperty;\n\n public PropertyContainer() : base(BindingState.Unbound)\n {\n this.AllocationStateProperty = this.CreatePropertyAccessor(nameof(AllocationState), BindingAccess.None);\n this.AllocationStateTransitionTimeProperty = this.CreatePropertyAccessor(nameof(AllocationStateTransitionTime), BindingAccess.None);\n this.ApplicationLicensesProperty = this.CreatePropertyAccessor>(nameof(ApplicationLicenses), BindingAccess.Read | BindingAccess.Write);\n this.ApplicationPackageReferencesProperty = this.CreatePropertyAccessor>(nameof(ApplicationPackageReferences), BindingAccess.Read | BindingAccess.Write);\n this.AutoScaleEnabledProperty = this.CreatePropertyAccessor(nameof(AutoScaleEnabled), BindingAccess.Read | BindingAccess.Write);\n this.AutoScaleEvaluationIntervalProperty = this.CreatePropertyAccessor(nameof(AutoScaleEvaluationInterval), BindingAccess.Read | BindingAccess.Write);\n this.AutoScaleFormulaProperty = this.CreatePropertyAccessor(nameof(AutoScaleFormula), BindingAccess.Read | BindingAccess.Write);\n this.AutoScaleRunProperty = this.CreatePropertyAccessor(nameof(AutoScaleRun), BindingAccess.None);\n this.CertificateReferencesProperty = this.CreatePropertyAccessor>(nameof(CertificateReferences), BindingAccess.Read | BindingAccess.Write);\n this.CloudServiceConfigurationProperty = this.CreatePropertyAccessor(nameof(CloudServiceConfiguration), BindingAccess.Read | BindingAccess.Write);\n this.CreationTimeProperty = this.CreatePropertyAccessor(nameof(CreationTime), BindingAccess.None);\n this.CurrentDedicatedComputeNodesProperty = this.CreatePropertyAccessor(nameof(CurrentDedicatedComputeNodes), BindingAccess.None);\n this.CurrentLowPriorityComputeNodesProperty = this.CreatePropertyAccessor(nameof(CurrentLowPriorityComputeNodes), BindingAccess.None);\n this.DisplayNameProperty = this.CreatePropertyAccessor(nameof(DisplayName), BindingAccess.Read | BindingAccess.Write);\n this.ETagProperty = this.CreatePropertyAccessor(nameof(ETag), BindingAccess.None);\n this.IdProperty = this.CreatePropertyAccessor(nameof(Id), BindingAccess.Read | BindingAccess.Write);\n this.IdentityProperty = this.CreatePropertyAccessor(nameof(Identity), BindingAccess.Read | BindingAccess.Write);\n this.InterComputeNodeCommunicationEnabledProperty = this.CreatePropertyAccessor(nameof(InterComputeNodeCommunicationEnabled), BindingAccess.Read | BindingAccess.Write);\n this.LastModifiedProperty = this.CreatePropertyAccessor(nameof(LastModified), BindingAccess.None);\n this.MetadataProperty = this.CreatePropertyAccessor>(nameof(Metadata), BindingAccess.Read | BindingAccess.Write);\n this.MountConfigurationProperty = this.CreatePropertyAccessor>(nameof(MountConfiguration), BindingAccess.Read | BindingAccess.Write);\n this.NetworkConfigurationProperty = this.CreatePropertyAccessor(nameof(NetworkConfiguration), BindingAccess.Read | BindingAccess.Write);\n this.ResizeErrorsProperty = this.CreatePropertyAccessor>(nameof(ResizeErrors), BindingAccess.None);\n this.ResizeTimeoutProperty = this.CreatePropertyAccessor(nameof(ResizeTimeout), BindingAccess.Read | BindingAccess.Write);\n this.StartTaskProperty = this.CreatePropertyAccessor(nameof(StartTask), BindingAccess.Read | BindingAccess.Write);\n this.StateProperty = this.CreatePropertyAccessor(nameof(State), BindingAccess.None);\n this.StateTransitionTimeProperty = this.CreatePropertyAccessor(nameof(StateTransitionTime), BindingAccess.None);\n this.StatisticsProperty = this.CreatePropertyAccessor(nameof(Statistics), BindingAccess.None);\n this.TargetDedicatedComputeNodesProperty = this.CreatePropertyAccessor(nameof(TargetDedicatedComputeNodes), BindingAccess.Read | BindingAccess.Write);\n this.TargetLowPriorityComputeNodesProperty = this.CreatePropertyAccessor(nameof(TargetLowPriorityComputeNodes), BindingAccess.Read | BindingAccess.Write);\n this.TaskSchedulingPolicyProperty = this.CreatePropertyAccessor(nameof(TaskSchedulingPolicy), BindingAccess.Read | BindingAccess.Write);\n this.TaskSlotsPerNodeProperty = this.CreatePropertyAccessor(nameof(TaskSlotsPerNode), BindingAccess.Read | BindingAccess.Write);\n this.UrlProperty = this.CreatePropertyAccessor(nameof(Url), BindingAccess.None);\n this.UserAccountsProperty = this.CreatePropertyAccessor>(nameof(UserAccounts), BindingAccess.Read | BindingAccess.Write);\n this.VirtualMachineConfigurationProperty = this.CreatePropertyAccessor(nameof(VirtualMachineConfiguration), BindingAccess.Read | BindingAccess.Write);\n this.VirtualMachineSizeProperty = this.CreatePropertyAccessor(nameof(VirtualMachineSize), BindingAccess.Read | BindingAccess.Write);\n }\n\n public PropertyContainer(Models.CloudPool protocolObject) : base(BindingState.Bound)\n {\n this.AllocationStateProperty = this.CreatePropertyAccessor(\n UtilitiesInternal.MapNullableEnum(protocolObject.AllocationState),\n nameof(AllocationState),\n BindingAccess.Read);\n this.AllocationStateTransitionTimeProperty = this.CreatePropertyAccessor(\n protocolObject.AllocationStateTransitionTime,\n nameof(AllocationStateTransitionTime),\n BindingAccess.Read);\n this.ApplicationLicensesProperty = this.CreatePropertyAccessor(\n UtilitiesInternal.CollectionToThreadSafeCollection(protocolObject.ApplicationLicenses, o => o),\n nameof(ApplicationLicenses),\n BindingAccess.Read);\n this.ApplicationPackageReferencesProperty = this.CreatePropertyAccessor(\n ApplicationPackageReference.ConvertFromProtocolCollection(protocolObject.ApplicationPackageReferences),\n nameof(ApplicationPackageReferences),\n BindingAccess.Read | BindingAccess.Write);\n this.AutoScaleEnabledProperty = this.CreatePropertyAccessor(\n protocolObject.EnableAutoScale,\n nameof(AutoScaleEnabled),\n BindingAccess.Read);\n this.AutoScaleEvaluationIntervalProperty = this.CreatePropertyAccessor(\n protocolObject.AutoScaleEvaluationInterval,\n nameof(AutoScaleEvaluationInterval),\n BindingAccess.Read);\n this.AutoScaleFormulaProperty = this.CreatePropertyAccessor(\n protocolObject.AutoScaleFormula,\n nameof(AutoScaleFormula),\n BindingAccess.Read);\n this.AutoScaleRunProperty = this.CreatePropertyAccessor(\n UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.AutoScaleRun, o => new AutoScaleRun(o).Freeze()),\n nameof(AutoScaleRun),\n BindingAccess.Read);\n this.CertificateReferencesProperty = this.CreatePropertyAccessor(\n CertificateReference.ConvertFromProtocolCollection(protocolObject.CertificateReferences),\n nameof(CertificateReferences),\n BindingAccess.Read | BindingAccess.Write);\n this.CloudServiceConfigurationProperty = this.CreatePropertyAccessor(\n UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.CloudServiceConfiguration, o => new CloudServiceConfiguration(o).Freeze()),\n nameof(CloudServiceConfiguration),\n BindingAccess.Read);\n this.CreationTimeProperty = this.CreatePropertyAccessor(\n protocolObject.CreationTime,\n nameof(CreationTime),\n BindingAccess.Read);\n this.CurrentDedicatedComputeNodesProperty = this.CreatePropertyAccessor(\n protocolObject.CurrentDedicatedNodes,\n nameof(CurrentDedicatedComputeNodes),\n BindingAccess.Read);\n this.CurrentLowPriorityComputeNodesProperty = this.CreatePropertyAccessor(\n protocolObject.CurrentLowPriorityNodes,\n nameof(CurrentLowPriorityComputeNodes),\n BindingAccess.Read);\n this.DisplayNameProperty = this.CreatePropertyAccessor(\n protocolObject.DisplayName,\n nameof(DisplayName),\n BindingAccess.Read);\n this.ETagProperty = this.CreatePropertyAccessor(\n protocolObject.ETag,\n nameof(ETag),\n BindingAccess.Read);\n this.IdProperty = this.CreatePropertyAccessor(\n protocolObject.Id,\n nameof(Id),\n BindingAccess.Read);\n this.IdentityProperty = this.CreatePropertyAccessor(\n UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.Identity, o => new BatchPoolIdentity(o)),\n nameof(Identity),\n BindingAccess.Read | BindingAccess.Write);\n this.InterComputeNodeCommunicationEnabledProperty = this.CreatePropertyAccessor(\n protocolObject.EnableInterNodeCommunication,\n nameof(InterComputeNodeCommunicationEnabled),\n BindingAccess.Read);\n this.LastModifiedProperty = this.CreatePropertyAccessor(\n protocolObject.LastModified,\n nameof(LastModified),\n BindingAccess.Read);\n this.MetadataProperty = this.CreatePropertyAccessor(\n MetadataItem.ConvertFromProtocolCollection(protocolObject.Metadata),\n nameof(Metadata),\n BindingAccess.Read | BindingAccess.Write);\n this.MountConfigurationProperty = this.CreatePropertyAccessor(\n Batch.MountConfiguration.ConvertFromProtocolCollectionAndFreeze(protocolObject.MountConfiguration),\n nameof(MountConfiguration),\n BindingAccess.Read);\n this.NetworkConfigurationProperty = this.CreatePropertyAccessor(\n UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.NetworkConfiguration, o => new NetworkConfiguration(o).Freeze()),\n nameof(NetworkConfiguration),\n BindingAccess.Read);\n this.ResizeErrorsProperty = this.CreatePropertyAccessor(\n ResizeError.ConvertFromProtocolCollectionReadOnly(protocolObject.ResizeErrors),\n nameof(ResizeErrors),\n BindingAccess.Read);\n this.ResizeTimeoutProperty = this.CreatePropertyAccessor(\n protocolObject.ResizeTimeout,\n nameof(ResizeTimeout),\n BindingAccess.Read);\n this.StartTaskProperty = this.CreatePropertyAccessor(\n UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.StartTask, o => new StartTask(o)),\n nameof(StartTask),\n BindingAccess.Read | BindingAccess.Write);\n this.StateProperty = this.CreatePropertyAccessor(\n UtilitiesInternal.MapNullableEnum(protocolObject.State),\n nameof(State),\n BindingAccess.Read);\n this.StateTransitionTimeProperty = this.CreatePropertyAccessor(\n protocolObject.StateTransitionTime,\n nameof(StateTransitionTime),\n BindingAccess.Read);\n this.StatisticsProperty = this.CreatePropertyAccessor(\n UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.Stats, o => new PoolStatistics(o).Freeze()),\n nameof(Statistics),\n BindingAccess.Read);\n this.TargetDedicatedComputeNodesProperty = this.CreatePropertyAccessor(\n protocolObject.TargetDedicatedNodes,\n nameof(TargetDedicatedComputeNodes),\n BindingAccess.Read);\n this.TargetLowPriorityComputeNodesProperty = this.CreatePropertyAccessor(\n protocolObject.TargetLowPriorityNodes,\n nameof(TargetLowPriorityComputeNodes),\n BindingAccess.Read);\n this.TaskSchedulingPolicyProperty = this.CreatePropertyAccessor(\n UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.TaskSchedulingPolicy, o => new TaskSchedulingPolicy(o).Freeze()),\n nameof(TaskSchedulingPolicy),\n BindingAccess.Read);\n this.TaskSlotsPerNodeProperty = this.CreatePropertyAccessor(\n protocolObject.TaskSlotsPerNode,\n nameof(TaskSlotsPerNode),\n BindingAccess.Read);\n this.UrlProperty = this.CreatePropertyAccessor(\n protocolObject.Url,\n nameof(Url),\n BindingAccess.Read);\n this.UserAccountsProperty = this.CreatePropertyAccessor(\n UserAccount.ConvertFromProtocolCollectionAndFreeze(protocolObject.UserAccounts),\n nameof(UserAccounts),\n BindingAccess.Read);\n this.VirtualMachineConfigurationProperty = this.CreatePropertyAccessor(\n UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.VirtualMachineConfiguration, o => new VirtualMachineConfiguration(o).Freeze()),\n nameof(VirtualMachineConfiguration),\n BindingAccess.Read);\n this.VirtualMachineSizeProperty = this.CreatePropertyAccessor(\n protocolObject.VmSize,\n nameof(VirtualMachineSize),\n BindingAccess.Read);\n }\n }\n\n private PropertyContainer propertyContainer;\n\n private readonly BatchClient parentBatchClient;\n\n #region Constructors\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The parent to use.\n /// The base behaviors to use.\n internal CloudPool(\n BatchClient parentBatchClient,\n IEnumerable baseBehaviors)\n {\n this.propertyContainer = new PropertyContainer();\n this.parentBatchClient = parentBatchClient;\n InheritUtil.InheritClientBehaviorsAndSetPublicProperty(this, baseBehaviors);\n }\n\n internal CloudPool(\n BatchClient parentBatchClient,\n Models.CloudPool protocolObject,\n IEnumerable baseBehaviors)\n {\n this.parentBatchClient = parentBatchClient;\n InheritUtil.InheritClientBehaviorsAndSetPublicProperty(this, baseBehaviors);\n this.propertyContainer = new PropertyContainer(protocolObject);\n }\n\n #endregion Constructors\n\n #region IInheritedBehaviors\n\n /// \n /// Gets or sets a list of behaviors that modify or customize requests to the Batch service\n /// made via this .\n /// \n /// \n /// These behaviors are inherited by child objects.\n /// Modifications are applied in the order of the collection. The last write wins.\n /// \n public IList CustomBehaviors { get; set; }\n\n #endregion IInheritedBehaviors\n\n #region CloudPool\n\n /// \n /// Gets an which indicates what node allocation activity is occurring on the \n /// pool.\n /// \n public Common.AllocationState? AllocationState\n {\n get { return this.propertyContainer.AllocationStateProperty.Value; }\n }\n\n /// \n /// Gets the time at which the pool entered its current .\n /// \n public DateTime? AllocationStateTransitionTime\n {\n get { return this.propertyContainer.AllocationStateTransitionTimeProperty.Value; }\n }\n\n /// \n /// Gets or sets the list of application licenses the Batch service will make available on each compute node in the \n /// pool.\n /// \n /// \n /// The list of application licenses must be a subset of available Batch service application licenses.The \n /// permitted licenses available on the pool are 'maya', 'vray', '3dsmax', 'arnold'. An additional charge applies \n /// for each application license added to the pool.\n /// \n public IList ApplicationLicenses\n {\n get { return this.propertyContainer.ApplicationLicensesProperty.Value; }\n set\n {\n this.propertyContainer.ApplicationLicensesProperty.Value = ConcurrentChangeTrackedList.TransformEnumerableToConcurrentList(value);\n }\n }\n\n /// \n /// Gets or sets a list of application packages to be installed on each compute node in the pool.\n /// \n /// \n /// Changes to application package references affect all new compute nodes joining the pool, but do not affect compute \n /// nodes that are already in the pool until they are rebooted or reimaged. There is a maximum of 10 application \n /// package references on any given pool.\n /// \n public IList ApplicationPackageReferences\n {\n get { return this.propertyContainer.ApplicationPackageReferencesProperty.Value; }\n set\n {\n this.propertyContainer.ApplicationPackageReferencesProperty.Value = ConcurrentChangeTrackedModifiableList.TransformEnumerableToConcurrentModifiableList(value);\n }\n }\n\n /// \n /// Gets or sets whether the pool size should automatically adjust according to the .\n /// \n /// \n /// If true, the property is required, the pool automatically resizes according \n /// to the formula, and and \n /// must be null. If false, one of the or \n /// properties is required.The default value is false.\n /// \n public bool? AutoScaleEnabled\n {\n get { return this.propertyContainer.AutoScaleEnabledProperty.Value; }\n set { this.propertyContainer.AutoScaleEnabledProperty.Value = value; }\n }\n\n /// \n /// Gets or sets a time interval at which to automatically adjust the pool size according to the .\n /// \n /// \n /// The default value is 15 minutes. The minimum allowed value is 5 minutes.\n /// \n public TimeSpan? AutoScaleEvaluationInterval\n {\n get { return this.propertyContainer.AutoScaleEvaluationIntervalProperty.Value; }\n set { this.propertyContainer.AutoScaleEvaluationIntervalProperty.Value = value; }\n }\n\n /// \n /// Gets or sets a formula for the desired number of compute nodes in the pool.\n /// \n /// \n /// For how to write autoscale formulas, see https://azure.microsoft.com/documentation/articles/batch-automatic-scaling/. \n /// This property is required if is set to true. It must be null if AutoScaleEnabled \n /// is false.The formula is checked for validity before the pool is created. If the formula is not valid, \n /// an exception is thrown when you try to commit the .\n /// \n public string AutoScaleFormula\n {\n get { return this.propertyContainer.AutoScaleFormulaProperty.Value; }\n set { this.propertyContainer.AutoScaleFormulaProperty.Value = value; }\n }\n\n /// \n /// Gets the results and errors from the last execution of the .\n /// \n public AutoScaleRun AutoScaleRun\n {\n get { return this.propertyContainer.AutoScaleRunProperty.Value; }\n }\n\n /// \n /// Gets or sets a list of certificates to be installed on each compute node in the pool.\n /// \n public IList CertificateReferences\n {\n get { return this.propertyContainer.CertificateReferencesProperty.Value; }\n set\n {\n this.propertyContainer.CertificateReferencesProperty.Value = ConcurrentChangeTrackedModifiableList.TransformEnumerableToConcurrentModifiableList(value);\n }\n }\n\n /// \n /// Gets or sets the for the pool.\n /// \n public CloudServiceConfiguration CloudServiceConfiguration\n {\n get { return this.propertyContainer.CloudServiceConfigurationProperty.Value; }\n set { this.propertyContainer.CloudServiceConfigurationProperty.Value = value; }\n }\n\n /// \n /// Gets the creation time for the pool.\n /// \n public DateTime? CreationTime\n {\n get { return this.propertyContainer.CreationTimeProperty.Value; }\n }\n\n /// \n /// Gets the number of dedicated compute nodes currently in the pool.\n /// \n public int? CurrentDedicatedComputeNodes\n {\n get { return this.propertyContainer.CurrentDedicatedComputeNodesProperty.Value; }\n }\n\n /// \n /// Gets the number of low-priority compute nodes currently in the pool.\n /// \n /// \n /// Low-priority compute nodes which have been preempted are included in this count.\n /// \n public int? CurrentLowPriorityComputeNodes\n {\n get { return this.propertyContainer.CurrentLowPriorityComputeNodesProperty.Value; }\n }\n\n /// \n /// Gets or sets the display name of the pool.\n /// \n public string DisplayName\n {\n get { return this.propertyContainer.DisplayNameProperty.Value; }\n set { this.propertyContainer.DisplayNameProperty.Value = value; }\n }\n\n /// \n /// Gets the ETag for the pool.\n /// \n public string ETag\n {\n get { return this.propertyContainer.ETagProperty.Value; }\n }\n\n /// \n /// Gets or sets the id of the pool.\n /// \n public string Id\n {\n get { return this.propertyContainer.IdProperty.Value; }\n set { this.propertyContainer.IdProperty.Value = value; }\n }\n\n /// \n /// Gets or sets the identity of the Batch pool, if configured.\n /// \n /// \n /// The list of user identities associated with the Batch pool. The user identity dictionary key references will \n /// be ARM resource ids in the form: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}'.\n /// \n public BatchPoolIdentity Identity\n {\n get { return this.propertyContainer.IdentityProperty.Value; }\n set { this.propertyContainer.IdentityProperty.Value = value; }\n }\n\n /// \n /// Gets or sets whether the pool permits direct communication between its compute nodes.\n /// \n /// \n /// Enabling inter-node communication limits the maximum size of the pool due to deployment restrictions on the nodes \n /// of the pool. This may result in the pool not reaching its desired size.\n /// \n public bool? InterComputeNodeCommunicationEnabled\n {\n get { return this.propertyContainer.InterComputeNodeCommunicationEnabledProperty.Value; }\n set { this.propertyContainer.InterComputeNodeCommunicationEnabledProperty.Value = value; }\n }\n\n /// \n /// Gets the last modified time of the pool.\n /// \n public DateTime? LastModified\n {\n get { return this.propertyContainer.LastModifiedProperty.Value; }\n }\n\n /// \n /// Gets or sets a list of name-value pairs associated with the pool as metadata.\n /// \n public IList Metadata\n {\n get { return this.propertyContainer.MetadataProperty.Value; }\n set\n {\n this.propertyContainer.MetadataProperty.Value = ConcurrentChangeTrackedModifiableList.TransformEnumerableToConcurrentModifiableList(value);\n }\n }\n\n /// \n /// Gets or sets a list of file systems to mount on each node in the pool.\n /// \n /// \n /// This supports Azure Files, NFS, CIFS/SMB, and Blobfuse.\n /// \n public IList MountConfiguration\n {\n get { return this.propertyContainer.MountConfigurationProperty.Value; }\n set\n {\n this.propertyContainer.MountConfigurationProperty.Value = ConcurrentChangeTrackedModifiableList.TransformEnumerableToConcurrentModifiableList(value);\n }\n }\n\n /// \n /// Gets or sets the network configuration of the pool.\n /// \n public NetworkConfiguration NetworkConfiguration\n {\n get { return this.propertyContainer.NetworkConfigurationProperty.Value; }\n set { this.propertyContainer.NetworkConfigurationProperty.Value = value; }\n }\n\n /// \n /// Gets a list of errors encountered while performing the last resize on the . Errors are \n /// returned only when the Batch service encountered an error while resizing the pool, and when the pool's \n /// is Steady.\n /// \n public IReadOnlyList ResizeErrors\n {\n get { return this.propertyContainer.ResizeErrorsProperty.Value; }\n }\n\n /// \n /// Gets or sets the timeout for allocation of compute nodes to the pool.\n /// \n public TimeSpan? ResizeTimeout\n {\n get { return this.propertyContainer.ResizeTimeoutProperty.Value; }\n set { this.propertyContainer.ResizeTimeoutProperty.Value = value; }\n }\n\n /// \n /// Gets or sets a task to run on each compute node as it joins the pool. The task runs when the node is added to \n /// the pool or when the node is restarted.\n /// \n public StartTask StartTask\n {\n get { return this.propertyContainer.StartTaskProperty.Value; }\n set { this.propertyContainer.StartTaskProperty.Value = value; }\n }\n\n /// \n /// Gets the current state of the pool.\n /// \n public Common.PoolState? State\n {\n get { return this.propertyContainer.StateProperty.Value; }\n }\n\n /// \n /// Gets the time at which the pool entered its current state.\n /// \n public DateTime? StateTransitionTime\n {\n get { return this.propertyContainer.StateTransitionTimeProperty.Value; }\n }\n\n /// \n /// Gets the resource usage statistics for the pool.\n /// \n /// \n /// This property is populated only if the was retrieved with an \n /// including the 'stats' attribute; otherwise it is null. The statistics may not be immediately available. The Batch \n /// service performs periodic roll-up of statistics. The typical delay is about 30 minutes.\n /// \n public PoolStatistics Statistics\n {\n get { return this.propertyContainer.StatisticsProperty.Value; }\n }\n\n /// \n /// Gets or sets the desired number of dedicated compute nodes in the pool.\n /// \n /// \n /// This setting cannot be specified if is set to true. At least one of this property \n /// and must be specified if is false. \n /// If not specified, the default is 0.\n /// ", "answers": [" public int? TargetDedicatedComputeNodes"], "length": 2209, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "06fb3617-5138-46cb-b8c6-d1470ed05d2d", "reasoning": "The code is defining properties of CloudPool. After the comment describing the TargetDedicatedComputeNodes property, the next line should start the property declaration, matching the pattern used for other properties (e.g., TargetLowPriorityComputeNodes). Therefore the next line is the property signature: public int? TargetDedicatedComputeNodes", "reasoning_model_answer": "public int? TargetDedicatedComputeNodes", "assistant_with_reasoning": "\nThe code is defining properties of CloudPool. After the comment describing the TargetDedicatedComputeNodes property, the next line should start the property declaration, matching the pattern used for other properties (e.g., TargetLowPriorityComputeNodes). Therefore the next line is the property signature: public int? TargetDedicatedComputeNodes\n\npublic int? TargetDedicatedComputeNodes", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.339, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 34777, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "public int? TargetDedicatedComputeNodes", "score": 0.91, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/*******************************************************************************\n * Copyright (c) 2012 IBM Corporation and others.\n * All rights reserved. This program and the accompanying materials\n * are made available under the terms of the Eclipse Public License v1.0\n * which accompanies this distribution, and is available at\n * http://www.eclipse.org/legal/epl-v10.html\n *\n * Contributors:\n * IBM Corporation - initial API and implementation\n *******************************************************************************/\npackage com.ibm.ws.sib.api.jms.impl;\n\nimport java.io.UnsupportedEncodingException;\nimport java.util.Arrays;\nimport java.util.Enumeration;\n\nimport javax.jms.JMSException;\nimport javax.jms.MapMessage;\nimport javax.jms.MessageFormatException;\n\nimport com.ibm.websphere.sib.api.jms.ApiJmsConstants;\nimport com.ibm.ws.sib.mfp.JsJmsMapMessage;\nimport com.ibm.ws.sib.mfp.JsJmsMessage;\nimport com.ibm.ws.sib.mfp.MessageCreateFailedException;\nimport com.ibm.ws.sib.utils.ras.SibTr;\nimport com.ibm.websphere.ras.TraceComponent;\n\n\n/**\n * @author matrober\n *\n * This class implements the requirements of a JMS MapMessage\n */\npublic class JmsMapMessageImpl extends JmsMessageImpl implements MapMessage\n{\n\n /**\n * This svUID assigned at version 1.30\n */\n private static final long serialVersionUID = -5270211659893353729L;\n\n // ******************* PRIVATE STATE VARIABLES *******************\n\n /**\n * MFP message object representing a JMS TextMessage\n * Note: Do not initialise this to null here, otherwise it will overwrite\n * the setup done by instantiateMessage!\n */\n private JsJmsMapMessage mapMsg;\n\n /**\n * This variable holds a cache of the message toString at the Message level.\n * A separate cache holds the subclass information. The cache is invalidated\n * by changing any property of the message.\n */\n private transient String cachedMapToString = null;\n\n // *************************** TRACE INITIALIZATION **************************\n private static TraceComponent tc = SibTr.register(JmsMapMessageImpl.class, ApiJmsConstants.MSG_GROUP_EXT, ApiJmsConstants.MSG_BUNDLE_EXT);\n\n // ************************ CONSTRUCTORS *************************\n\n /**\n * Constructor used to create a new message object.\n */\n public JmsMapMessageImpl() throws JMSException {\n // Calling the superclass no-args constructor in turn leads to the\n // instantiateMessage method being called, which we override to return\n // a map message.\n super();\n if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, \"JmsMapMessageImpl\");\n messageClass = CLASS_MAP;\n if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, \"JmsMapMessageImpl\");\n }\n\n\n /**\n * This constructor is used by the JmsMessage.inboundJmsInstance method (static)\n * in order to provide the inbound message path from MFP component to JMS component.\n */\n JmsMapMessageImpl(JsJmsMapMessage newMsg, JmsSessionImpl newSess) {\n\n // Pass this object to the parent class so that it can keep a reference.\n super(newMsg, newSess);\n if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, \"JmsMapMessageImpl\", new Object[]{newMsg, newSess});\n\n // Store the reference we are given, and inform the parent class.\n mapMsg = newMsg;\n messageClass = CLASS_MAP;\n\n // Note that we do NOT initialize the defaults for inbound messages.\n\n if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, \"JmsMapMessageImpl\");\n }\n\n\n /**\n * Construct a jetstream jms message from a (possibly non-jetstream)\n * vanilla jms message.\n */\n JmsMapMessageImpl(MapMessage mapMessage) throws JMSException {\n // copy message headers and properties.\n super(mapMessage);\n\n if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, \"JmsMapMessageImpl\", mapMessage);\n\n // set-up this class's state (i.e. do what this() does).\n // nothing to do.\n\n // copy map.\n Enumeration mapNames = mapMessage.getMapNames();\n if (mapNames != null) {\n while (mapNames.hasMoreElements()) {\n String name = (String) mapNames.nextElement();\n Object value = mapMessage.getObject(name);\n setObject(name, value);\n }\n }\n if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, \"JmsMapMessageImpl\");\n }\n\n\n // ********************* INTERFACE METHODS ***********************\n\n /**\n * @see javax.jms.MapMessage#getBoolean(String)\n */\n public boolean getBoolean(String name) throws JMSException {\n if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, \"getBoolean\", name);\n\n Object obj=null;\n try {\n obj = mapMsg.getObject(name);\n }\n catch (UnsupportedEncodingException e) {\n // No FFDC Code Needed\n throw (JMSException) JmsErrorUtils.newThrowable(\n JMSException.class,\n \"EXCEPTION_RECEIVED_CWSIA0022\",\n new Object[] {e, \"JmsMapMessageImpl.getBoolean\"},\n e, \"JmsMapMessageImpl#1\", this, tc);\n }\n\n boolean value = false;\n try {\n value = JmsMessageImpl.parseBoolean(obj, name);\n }\n catch (JMSException e) {\n // No FFDC code needed\n // d238447 FFDC review. Don't call processThrowable - this is an app' error.\n if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(this, tc, \"Error parsing object\", e);\n throw e;\n }\n\n if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, \"getBoolean\", value);\n return value;\n }\n\n /**\n * @see javax.jms.MapMessage#getByte(String)\n */\n public byte getByte(String name) throws JMSException {\n if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, \"getByte\", name);\n\n Object obj=null;\n try {\n obj = mapMsg.getObject(name);\n }\n catch (UnsupportedEncodingException e) {\n // No FFDC Code Needed\n throw (JMSException) JmsErrorUtils.newThrowable(\n JMSException.class,\n \"EXCEPTION_RECEIVED_CWSIA0022\",\n new Object[] {e, \"JmsMapMessageImpl.getByte\"},\n e, \"JmsMapMessageImpl#2\", this, tc);\n }\n\n byte value = 0;\n try {\n value = JmsMessageImpl.parseByte(obj, name);\n }\n catch (JMSException e) {\n // No FFDC code needed\n // 238447 don't call processThrowable for app' errors\n if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(this, tc, \"Error parsing object\", e);\n throw e;\n }\n\n if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, \"getByte\", value);\n return value;\n }\n\n /**\n * @see javax.jms.MapMessage#getShort(String)\n */\n public short getShort(String name) throws JMSException {\n if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, \"getShort\", name);\n\n Object obj=null;\n try {\n obj = mapMsg.getObject(name);\n }\n catch (UnsupportedEncodingException e) {\n // No FFDC Code Needed\n throw (JMSException) JmsErrorUtils.newThrowable(\n JMSException.class,\n \"EXCEPTION_RECEIVED_CWSIA0022\",\n new Object[] {e, \"JmsMapMessageImpl.getShort\"},\n e, \"JmsMapMessageImpl#3\", this, tc);\n }\n\n short value = 0;\n try {\n value = JmsMessageImpl.parseShort(obj, name);\n }\n catch (JMSException e) {\n // No FFDC code needed\n // 238447 Don't generate FFDCs for app' errors.\n if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(this, tc, \"Error parsing object\", e);\n throw e;\n }\n\n if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, \"getShort\", value);\n return value;\n }\n\n /**\n * @see javax.jms.MapMessage#getChar(String)\n */\n public char getChar(String name) throws JMSException {\n if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, \"getChar\", name);\n\n Object obj=null;\n try {\n obj = mapMsg.getObject(name);\n }\n catch (UnsupportedEncodingException e) {\n // No FFDC Code Needed\n throw (JMSException) JmsErrorUtils.newThrowable(\n JMSException.class,\n \"EXCEPTION_RECEIVED_CWSIA0022\",\n new Object[] {e, \"JmsMapMessageImpl.getChar\"},\n e, \"JmsMapMessageImpl#4\", this, tc);\n }\n\n char value = 0;\n\n // This logic is not part of a Message.parseCharacter because there is no\n // equivalent Message.getCharProperty method which would share it.\n if (obj instanceof Character) {\n value = ((Character)obj).charValue();\n }\n else if (obj == null) {\n RuntimeException e = (RuntimeException)JmsErrorUtils.newThrowable(NullPointerException.class,\n \"FIELD_NOT_SET_CWSIA0105\", new Object[] { name }, tc);\n if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(this, tc, \"Field has not been set\", e);\n throw e;\n }\n else {\n // Boolean can only be retrieved as boolean and String (see 3.5.4).\n JMSException e = newBadConvertException(obj, name, \"Character\", tc);\n if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(this, tc, \"Invalid convert\", e);\n throw e;\n }\n\n if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, \"getChar\", value);\n return value;\n }\n\n /**\n * @see javax.jms.MapMessage#getInt(String)\n */\n public int getInt(String name) throws JMSException {\n if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, \"getInt\", name);\n\n Object obj=null;\n try {\n obj = mapMsg.getObject(name);\n }\n catch (UnsupportedEncodingException e) {\n // No FFDC Code Needed\n throw (JMSException) JmsErrorUtils.newThrowable(\n JMSException.class,\n \"EXCEPTION_RECEIVED_CWSIA0022\",\n new Object[] {e, \"JmsMapMessageImpl.getInt\"},\n e, \"JmsMapMessageImpl#5\", this, tc);\n }\n\n int value = 0;\n try {\n value = JmsMessageImpl.parseInt(obj, name);\n }\n catch (JMSException e) {\n // No FFDC code needed\n // 238447 Don't generate FFDCs for app' errors.\n if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(this, tc, \"Error parsing object\", e);\n throw e;\n }\n\n if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, \"getInt\", value);\n return value;\n }\n\n /**\n * @see javax.jms.MapMessage#getLong(String)\n */\n public long getLong(String name) throws JMSException {\n if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, \"getLong\", name);\n\n Object obj=null;\n try {\n obj = mapMsg.getObject(name);\n }\n catch (UnsupportedEncodingException e) {\n // No FFDC Code Needed\n throw (JMSException) JmsErrorUtils.newThrowable(\n JMSException.class,\n \"EXCEPTION_RECEIVED_CWSIA0022\",\n new Object[] {e, \"JmsMapMessageImpl.getLong\"},\n e, \"JmsMapMessageImpl#6\", this, tc);\n }\n\n long value = 0;\n try {\n value = JmsMessageImpl.parseLong(obj, name);\n }\n catch (JMSException e) {\n // No FFDC code needed\n // 238447 Don't generate FFDCs for app' errors.\n if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(this, tc, \"Error parsing object\", e);\n throw e;\n }\n\n if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, \"getLong\", value);\n return value;\n }\n\n /**\n * @see javax.jms.MapMessage#getFloat(String)\n */\n public float getFloat(String name) throws JMSException {\n if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, \"getFloat\", name);\n\n Object obj=null;\n try {\n obj = mapMsg.getObject(name);\n }\n catch (UnsupportedEncodingException e) {\n // No FFDC Code Needed\n throw (JMSException) JmsErrorUtils.newThrowable(\n JMSException.class,\n \"EXCEPTION_RECEIVED_CWSIA0022\",\n new Object[] {e, \"JmsMapMessageImpl.getFloat\"},\n e, \"JmsMapMessageImpl#7\", this, tc);\n }\n\n float value = 0;\n\n try {\n value = JmsMessageImpl.parseFloat(obj, name);\n }\n catch (JMSException e) {\n // No FFDC code needed\n // 238447 Don't generate FFDCs for app' errors.\n if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(this, tc, \"Error parsing object\", e);\n throw e;\n }\n\n if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, \"getFloat\", value);\n return value;\n }\n\n /**\n * @see javax.jms.MapMessage#getDouble(String)\n */\n public double getDouble(String name) throws JMSException {\n if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, \"getDouble\", name);\n\n Object obj=null;\n try {\n obj = mapMsg.getObject(name);\n } catch (UnsupportedEncodingException e) {\n // No FFDC Code Needed\n throw (JMSException) JmsErrorUtils.newThrowable(\n JMSException.class,\n \"EXCEPTION_RECEIVED_CWSIA0022\",\n new Object[] {e, \"JmsMapMessageImpl.getDouble\"},\n e, \"JmsMapMessageImpl#8\", this, tc);\n }\n\n double value = 0;\n try {\n value = JmsMessageImpl.parseDouble(obj, name);\n }\n catch (JMSException e) {\n // No FFDC code needed\n // 238447 Don't generate FFDCs for app' errors.\n if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(this, tc, \"Error parsing object\", e);\n throw e;\n }\n\n if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, \"getDouble\", value);\n return value;\n }\n\n /**\n * @see javax.jms.MapMessage#getString(String)\n */\n public String getString(String name) throws JMSException {\n if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, \"getString\", name);\n\n Object obj=null;\n try {\n obj = mapMsg.getObject(name);\n }\n catch (UnsupportedEncodingException e) {\n // No FFDC Code Needed\n throw (JMSException) JmsErrorUtils.newThrowable(\n JMSException.class,\n \"EXCEPTION_RECEIVED_CWSIA0022\",\n new Object[] {e, \"JmsMapMessageImpl.getString\"},\n e, \"JmsMapMessageImpl#9\", this, tc);\n }\n\n String value = null;\n\n if ((obj instanceof String) || (obj == null)) {\n value = (String)obj;\n }\n else if (obj instanceof byte[]) {\n JMSException e = newBadConvertException(obj, name, \"String\", tc);\n if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(this, tc, \"invalid convert\", e);\n throw e;\n }\n else {\n // Every type of property can be returned as a String\n value = obj.toString();\n }\n\n if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, \"getString\", value);\n return value;\n }\n\n /**\n * @see javax.jms.MapMessage#getBytes(String)\n */\n public byte[] getBytes(String name) throws JMSException {\n if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, \"getBytes\", name);\n\n Object obj=null;\n try {\n obj = mapMsg.getObject(name);\n }\n catch (UnsupportedEncodingException e) {\n // No FFDC Code Needed\n throw (JMSException) JmsErrorUtils.newThrowable(\n JMSException.class,\n \"EXCEPTION_RECEIVED_CWSIA0022\",\n new Object[] {e, \"JmsMapMessageImpl.getBytes\"},\n e, \"JmsMapMessageImpl#10\", this, tc);\n }\n\n byte[] value = null;\n if (obj instanceof byte[]) {\n // Take a copy to prevent an application from altering the data in the message\n byte[] objB = (byte[])obj;\n value = new byte[objB.length];\n System.arraycopy(objB, 0, value, 0, objB.length);\n }\n else if (obj == null) {\n // This property had not been set. The Javadoc for getBytes says we return null\n // if there is no item by this name. Note that this is compatible with applications\n // having set the bytes to null explicitly.\n value = null;\n }\n else {\n JMSException e = newBadConvertException(obj, name, \"Byte[]\", tc);\n if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(this, tc, \"Invalid convert\", e);\n throw e;\n }\n\n if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, \"getBytes\", Arrays.toString(value));\n return value;\n }\n\n /**\n * @see javax.jms.MapMessage#getObject(String)\n */\n public Object getObject(String name) throws JMSException {\n if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, \"getObject\", name);\n\n Object result = null;\n Object obj = null;\n try {\n obj = mapMsg.getObject(name);\n }\n catch (UnsupportedEncodingException e) {\n // No FFDC Code Needed\n throw (JMSException) JmsErrorUtils.newThrowable(\n JMSException.class,\n \"EXCEPTION_RECEIVED_CWSIA0022\",\n new Object[] {e, \"JmsMapMessageImpl.getObject\"},\n e, \"JmsMapMessageImpl#11\", this, tc);\n }\n if (obj instanceof byte[]) {\n // Take a copy to prevent an application from altering the data in the message\n byte[] objB = (byte[])obj;\n byte[] value = new byte[objB.length];\n System.arraycopy(objB, 0, value, 0, objB.length);\n result = value;\n }\n else {\n result = obj;\n }\n\n if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, \"getObject\", result);\n return result;\n }\n\n /**\n * @see javax.jms.MapMessage#getMapNames()\n */\n public Enumeration getMapNames() throws JMSException {\n if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, \"getMapNames\");\n\n Enumeration map=null;\n try {\n map = mapMsg.getMapNames();\n } catch (UnsupportedEncodingException e) {\n // No FFDC Code Needed\n throw (JMSException) JmsErrorUtils.newThrowable(\n JMSException.class,\n \"EXCEPTION_RECEIVED_CWSIA0022\",\n new Object[] {e, \"JmsMapMessageImpl.getMapNames\"},\n e, \"JmsMapMessageImpl#12\", this, tc);\n }\n\n if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, \"getMapNames\", map);\n return map;\n }\n\n /**\n * @see javax.jms.MapMessage#setBoolean(String, boolean)\n */\n public void setBoolean(String name, boolean value) throws JMSException {\n if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, \"setBoolean\", new Object[]{name, value});\n\n checkBodyWriteable(\"setBoolean\");\n checkPropName(name, \"setBoolean\");\n try {\n mapMsg.setBoolean(name, value);\n }\n catch (UnsupportedEncodingException e) {\n // No FFDC Code Needed\n throw (JMSException) JmsErrorUtils.newThrowable(\n JMSException.class,\n \"EXCEPTION_RECEIVED_CWSIA0022\",\n new Object[] {e, \"JmsMapMessageImpl.setBoolean\"},\n e, \"JmsMapMessageImpl#13\", this, tc);\n }\n // Invalidate the cached toString object.\n cachedMapToString = null;\n\n if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, \"setBoolean\");\n }\n\n /**\n * @see javax.jms.MapMessage#setByte(String, byte)\n */\n public void setByte(String name, byte value) throws JMSException {\n if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, \"setByte\", new Object[]{name, value});\n\n checkBodyWriteable(\"setByte\");\n checkPropName(name, \"setByte\");\n try {\n mapMsg.setByte(name, value);\n }\n catch (UnsupportedEncodingException e) {\n // No FFDC Code Needed\n throw (JMSException) JmsErrorUtils.newThrowable(\n JMSException.class,\n \"EXCEPTION_RECEIVED_CWSIA0022\",\n new Object[] {e, \"JmsMapMessageImpl.setByte\"},\n e, \"JmsMapMessageImpl#14\", this, tc);\n }\n // Invalidate the cached toString object.\n cachedMapToString = null;\n\n if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, \"setByte\");\n }\n\n /**\n * @see javax.jms.MapMessage#setBytes(String, byte[])\n */\n public void setBytes(String name, byte[] value) throws JMSException {\n if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, \"setBytes\", new Object[]{name, value});\n\n int length = 0;\n if (value != null) length = value.length;\n setBytes(name, value, 0, length);\n\n if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, \"setBytes\");\n }\n\n /**\n * @see javax.jms.MapMessage#setBytes(String, byte[], int, int)\n */\n public void setBytes(String name, byte[] value, int start, int length) throws JMSException {\n if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, \"setBytes\", new Object[]{name, value, start, length});\n\n checkBodyWriteable(\"setBytes\");\n checkPropName(name, \"setBytes\");\n\n // carry out the deep copy & defend against nulls\n // (should be able to set a null without any problems).\n byte[] deepCopy = null;\n if (value != null) {\n deepCopy = new byte[length];\n System.arraycopy(value, start, deepCopy, 0, length);\n }\n\n try {\n // pass the copy of the array in to the message object.\n mapMsg.setBytes(name, deepCopy);\n }\n catch (UnsupportedEncodingException e) {\n // No FFDC Code Needed\n throw (JMSException) JmsErrorUtils.newThrowable(\n JMSException.class,\n \"EXCEPTION_RECEIVED_CWSIA0022\",\n new Object[] {e, \"JmsMapMessageImpl.setBytes\"},\n e, \"JmsMapMessageImpl#15\", this, tc);\n }\n\n // Invalidate the cached toString object.\n cachedMapToString = null;\n\n if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, \"setBytes\");\n }\n\n /**\n * @see javax.jms.MapMessage#setChar(String, char)\n */\n public void setChar(String name, char value) throws JMSException {\n if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, \"setChar\", new Object[]{name, value});\n\n checkBodyWriteable(\"setChar\");\n checkPropName(name, \"setChar\");\n try {\n mapMsg.setChar(name, value);\n }", "answers": [" catch (UnsupportedEncodingException e) {"], "length": 2181, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "8613770a-a722-4b75-8f22-f293aaa2a729", "reasoning": "The setChar method follows the same pattern as other setter methods (setBoolean, setByte, setBytes). After the try block that calls mapMsg.setChar(name, value), the next line is the catch clause handling UnsupportedEncodingException, matching the existing code style.", "reasoning_model_answer": "catch (UnsupportedEncodingException e) {", "assistant_with_reasoning": "\nThe setChar method follows the same pattern as other setter methods (setBoolean, setByte, setBytes). After the try block that calls mapMsg.setChar(name, value), the next line is the catch clause handling UnsupportedEncodingException, matching the existing code style.\n\ncatch (UnsupportedEncodingException e) {", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.938, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 22465, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "catch (UnsupportedEncodingException e) {", "score": 0.95, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/*******************************************************************************\n * Copyright (c) 2012 IBM Corporation and others.\n * All rights reserved. This program and the accompanying materials\n * are made available under the terms of the Eclipse Public License v1.0\n * which accompanies this distribution, and is available at\n * http://www.eclipse.org/legal/epl-v10.html\n *\n * Contributors:\n * IBM Corporation - initial API and implementation\n *******************************************************************************/\npackage com.ibm.ws.sib.api.jms.impl;\n\nimport java.io.UnsupportedEncodingException;\nimport java.util.Arrays;\nimport java.util.Enumeration;\n\nimport javax.jms.JMSException;\nimport javax.jms.MapMessage;\nimport javax.jms.MessageFormatException;\n\nimport com.ibm.websphere.sib.api.jms.ApiJmsConstants;\nimport com.ibm.ws.sib.mfp.JsJmsMapMessage;\nimport com.ibm.ws.sib.mfp.JsJmsMessage;\nimport com.ibm.ws.sib.mfp.MessageCreateFailedException;\nimport com.ibm.ws.sib.utils.ras.SibTr;\nimport com.ibm.websphere.ras.TraceComponent;\n\n\n/**\n * @author matrober\n *\n * This class implements the requirements of a JMS MapMessage\n */\npublic class JmsMapMessageImpl extends JmsMessageImpl implements MapMessage\n{\n\n /**\n * This svUID assigned at version 1.30\n */\n private static final long serialVersionUID = -5270211659893353729L;\n\n // ******************* PRIVATE STATE VARIABLES *******************\n\n /**\n * MFP message object representing a JMS TextMessage\n * Note: Do not initialise this to null here, otherwise it will overwrite\n * the setup done by instantiateMessage!\n */\n private JsJmsMapMessage mapMsg;\n\n /**\n * This variable holds a cache of the message toString at the Message level.\n * A separate cache holds the subclass information. The cache is invalidated\n * by changing any property of the message.\n */\n private transient String cachedMapToString = null;\n\n // *************************** TRACE INITIALIZATION **************************\n private static TraceComponent tc = SibTr.register(JmsMapMessageImpl.class, ApiJmsConstants.MSG_GROUP_EXT, ApiJmsConstants.MSG_BUNDLE_EXT);\n\n // ************************ CONSTRUCTORS *************************\n\n /**\n * Constructor used to create a new message object.\n */\n public JmsMapMessageImpl() throws JMSException {\n // Calling the superclass no-args constructor in turn leads to the\n // instantiateMessage method being called, which we override to return\n // a map message.\n super();\n if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, \"JmsMapMessageImpl\");\n messageClass = CLASS_MAP;\n if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, \"JmsMapMessageImpl\");\n }\n\n\n /**\n * This constructor is used by the JmsMessage.inboundJmsInstance method (static)\n * in order to provide the inbound message path from MFP component to JMS component.\n */\n JmsMapMessageImpl(JsJmsMapMessage newMsg, JmsSessionImpl newSess) {\n\n // Pass this object to the parent class so that it can keep a reference.\n super(newMsg, newSess);\n if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, \"JmsMapMessageImpl\", new Object[]{newMsg, newSess});\n\n // Store the reference we are given, and inform the parent class.\n mapMsg = newMsg;\n messageClass = CLASS_MAP;\n\n // Note that we do NOT initialize the defaults for inbound messages.\n\n if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, \"JmsMapMessageImpl\");\n }\n\n\n /**\n * Construct a jetstream jms message from a (possibly non-jetstream)\n * vanilla jms message.\n */\n JmsMapMessageImpl(MapMessage mapMessage) throws JMSException {\n // copy message headers and properties.\n super(mapMessage);\n\n if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, \"JmsMapMessageImpl\", mapMessage);\n\n // set-up this class's state (i.e. do what this() does).\n // nothing to do.\n\n // copy map.\n Enumeration mapNames = mapMessage.getMapNames();\n if (mapNames != null) {\n while (mapNames.hasMoreElements()) {\n String name = (String) mapNames.nextElement();\n Object value = mapMessage.getObject(name);\n setObject(name, value);\n }\n }\n if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, \"JmsMapMessageImpl\");\n }\n\n\n // ********************* INTERFACE METHODS ***********************\n\n /**\n * @see javax.jms.MapMessage#getBoolean(String)\n */\n public boolean getBoolean(String name) throws JMSException {\n if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, \"getBoolean\", name);\n\n Object obj=null;\n try {\n obj = mapMsg.getObject(name);\n }\n catch (UnsupportedEncodingException e) {\n // No FFDC Code Needed\n throw (JMSException) JmsErrorUtils.newThrowable(\n JMSException.class,\n \"EXCEPTION_RECEIVED_CWSIA0022\",\n new Object[] {e, \"JmsMapMessageImpl.getBoolean\"},\n e, \"JmsMapMessageImpl#1\", this, tc);\n }\n\n boolean value = false;\n try {\n value = JmsMessageImpl.parseBoolean(obj, name);\n }\n catch (JMSException e) {\n // No FFDC code needed\n // d238447 FFDC review. Don't call processThrowable - this is an app' error.\n if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(this, tc, \"Error parsing object\", e);\n throw e;\n }\n\n if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, \"getBoolean\", value);\n return value;\n }\n\n /**\n * @see javax.jms.MapMessage#getByte(String)\n */\n public byte getByte(String name) throws JMSException {\n if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, \"getByte\", name);\n\n Object obj=null;\n try {\n obj = mapMsg.getObject(name);\n }\n catch (UnsupportedEncodingException e) {\n // No FFDC Code Needed\n throw (JMSException) JmsErrorUtils.newThrowable(\n JMSException.class,\n \"EXCEPTION_RECEIVED_CWSIA0022\",\n new Object[] {e, \"JmsMapMessageImpl.getByte\"},\n e, \"JmsMapMessageImpl#2\", this, tc);\n }\n\n byte value = 0;\n try {\n value = JmsMessageImpl.parseByte(obj, name);\n }\n catch (JMSException e) {\n // No FFDC code needed\n // 238447 don't call processThrowable for app' errors\n if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(this, tc, \"Error parsing object\", e);\n throw e;\n }\n\n if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, \"getByte\", value);\n return value;\n }\n\n /**\n * @see javax.jms.MapMessage#getShort(String)\n */\n public short getShort(String name) throws JMSException {\n if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, \"getShort\", name);\n\n Object obj=null;\n try {\n obj = mapMsg.getObject(name);\n }\n catch (UnsupportedEncodingException e) {\n // No FFDC Code Needed\n throw (JMSException) JmsErrorUtils.newThrowable(\n JMSException.class,\n \"EXCEPTION_RECEIVED_CWSIA0022\",\n new Object[] {e, \"JmsMapMessageImpl.getShort\"},\n e, \"JmsMapMessageImpl#3\", this, tc);\n }\n\n short value = 0;\n try {\n value = JmsMessageImpl.parseShort(obj, name);\n }\n catch (JMSException e) {\n // No FFDC code needed\n // 238447 Don't generate FFDCs for app' errors.\n if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(this, tc, \"Error parsing object\", e);\n throw e;\n }\n\n if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, \"getShort\", value);\n return value;\n }\n\n /**\n * @see javax.jms.MapMessage#getChar(String)\n */\n public char getChar(String name) throws JMSException {\n if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, \"getChar\", name);\n\n Object obj=null;\n try {\n obj = mapMsg.getObject(name);\n }\n catch (UnsupportedEncodingException e) {\n // No FFDC Code Needed\n throw (JMSException) JmsErrorUtils.newThrowable(\n JMSException.class,\n \"EXCEPTION_RECEIVED_CWSIA0022\",\n new Object[] {e, \"JmsMapMessageImpl.getChar\"},\n e, \"JmsMapMessageImpl#4\", this, tc);\n }\n\n char value = 0;\n\n // This logic is not part of a Message.parseCharacter because there is no\n // equivalent Message.getCharProperty method which would share it.\n if (obj instanceof Character) {\n value = ((Character)obj).charValue();\n }\n else if (obj == null) {\n RuntimeException e = (RuntimeException)JmsErrorUtils.newThrowable(NullPointerException.class,\n \"FIELD_NOT_SET_CWSIA0105\", new Object[] { name }, tc);\n if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(this, tc, \"Field has not been set\", e);\n throw e;\n }\n else {\n // Boolean can only be retrieved as boolean and String (see 3.5.4).\n JMSException e = newBadConvertException(obj, name, \"Character\", tc);\n if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(this, tc, \"Invalid convert\", e);\n throw e;\n }\n\n if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, \"getChar\", value);\n return value;\n }\n\n /**\n * @see javax.jms.MapMessage#getInt(String)\n */\n public int getInt(String name) throws JMSException {\n if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, \"getInt\", name);\n\n Object obj=null;\n try {\n obj = mapMsg.getObject(name);\n }\n catch (UnsupportedEncodingException e) {\n // No FFDC Code Needed\n throw (JMSException) JmsErrorUtils.newThrowable(\n JMSException.class,\n \"EXCEPTION_RECEIVED_CWSIA0022\",\n new Object[] {e, \"JmsMapMessageImpl.getInt\"},\n e, \"JmsMapMessageImpl#5\", this, tc);\n }\n\n int value = 0;\n try {\n value = JmsMessageImpl.parseInt(obj, name);\n }\n catch (JMSException e) {\n // No FFDC code needed\n // 238447 Don't generate FFDCs for app' errors.\n if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(this, tc, \"Error parsing object\", e);\n throw e;\n }\n\n if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, \"getInt\", value);\n return value;\n }\n\n /**\n * @see javax.jms.MapMessage#getLong(String)\n */\n public long getLong(String name) throws JMSException {\n if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, \"getLong\", name);\n\n Object obj=null;\n try {\n obj = mapMsg.getObject(name);\n }\n catch (UnsupportedEncodingException e) {\n // No FFDC Code Needed\n throw (JMSException) JmsErrorUtils.newThrowable(\n JMSException.class,\n \"EXCEPTION_RECEIVED_CWSIA0022\",\n new Object[] {e, \"JmsMapMessageImpl.getLong\"},\n e, \"JmsMapMessageImpl#6\", this, tc);\n }\n\n long value = 0;\n try {\n value = JmsMessageImpl.parseLong(obj, name);\n }\n catch (JMSException e) {\n // No FFDC code needed\n // 238447 Don't generate FFDCs for app' errors.\n if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(this, tc, \"Error parsing object\", e);\n throw e;\n }\n\n if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, \"getLong\", value);\n return value;\n }\n\n /**\n * @see javax.jms.MapMessage#getFloat(String)\n */\n public float getFloat(String name) throws JMSException {\n if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, \"getFloat\", name);\n\n Object obj=null;\n try {\n obj = mapMsg.getObject(name);\n }\n catch (UnsupportedEncodingException e) {\n // No FFDC Code Needed\n throw (JMSException) JmsErrorUtils.newThrowable(\n JMSException.class,\n \"EXCEPTION_RECEIVED_CWSIA0022\",\n new Object[] {e, \"JmsMapMessageImpl.getFloat\"},\n e, \"JmsMapMessageImpl#7\", this, tc);\n }\n\n float value = 0;\n\n try {\n value = JmsMessageImpl.parseFloat(obj, name);\n }\n catch (JMSException e) {\n // No FFDC code needed\n // 238447 Don't generate FFDCs for app' errors.\n if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(this, tc, \"Error parsing object\", e);\n throw e;\n }\n\n if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, \"getFloat\", value);\n return value;\n }\n\n /**\n * @see javax.jms.MapMessage#getDouble(String)\n */\n public double getDouble(String name) throws JMSException {\n if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, \"getDouble\", name);\n\n Object obj=null;\n try {\n obj = mapMsg.getObject(name);\n } catch (UnsupportedEncodingException e) {\n // No FFDC Code Needed\n throw (JMSException) JmsErrorUtils.newThrowable(\n JMSException.class,\n \"EXCEPTION_RECEIVED_CWSIA0022\",\n new Object[] {e, \"JmsMapMessageImpl.getDouble\"},\n e, \"JmsMapMessageImpl#8\", this, tc);\n }\n\n double value = 0;\n try {\n value = JmsMessageImpl.parseDouble(obj, name);\n }\n catch (JMSException e) {\n // No FFDC code needed\n // 238447 Don't generate FFDCs for app' errors.\n if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(this, tc, \"Error parsing object\", e);\n throw e;\n }\n\n if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, \"getDouble\", value);\n return value;\n }\n\n /**\n * @see javax.jms.MapMessage#getString(String)\n */\n public String getString(String name) throws JMSException {\n if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, \"getString\", name);\n\n Object obj=null;\n try {\n obj = mapMsg.getObject(name);\n }\n catch (UnsupportedEncodingException e) {\n // No FFDC Code Needed\n throw (JMSException) JmsErrorUtils.newThrowable(\n JMSException.class,\n \"EXCEPTION_RECEIVED_CWSIA0022\",\n new Object[] {e, \"JmsMapMessageImpl.getString\"},\n e, \"JmsMapMessageImpl#9\", this, tc);\n }\n\n String value = null;\n\n if ((obj instanceof String) || (obj == null)) {\n value = (String)obj;\n }\n else if (obj instanceof byte[]) {\n JMSException e = newBadConvertException(obj, name, \"String\", tc);\n if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(this, tc, \"invalid convert\", e);\n throw e;\n }\n else {\n // Every type of property can be returned as a String\n value = obj.toString();\n }\n\n if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, \"getString\", value);\n return value;\n }\n\n /**\n * @see javax.jms.MapMessage#getBytes(String)\n */\n public byte[] getBytes(String name) throws JMSException {\n if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, \"getBytes\", name);\n\n Object obj=null;\n try {\n obj = mapMsg.getObject(name);\n }\n catch (UnsupportedEncodingException e) {\n // No FFDC Code Needed\n throw (JMSException) JmsErrorUtils.newThrowable(\n JMSException.class,\n \"EXCEPTION_RECEIVED_CWSIA0022\",\n new Object[] {e, \"JmsMapMessageImpl.getBytes\"},\n e, \"JmsMapMessageImpl#10\", this, tc);\n }\n\n byte[] value = null;\n if (obj instanceof byte[]) {\n // Take a copy to prevent an application from altering the data in the message\n byte[] objB = (byte[])obj;\n value = new byte[objB.length];\n System.arraycopy(objB, 0, value, 0, objB.length);\n }\n else if (obj == null) {\n // This property had not been set. The Javadoc for getBytes says we return null\n // if there is no item by this name. Note that this is compatible with applications\n // having set the bytes to null explicitly.\n value = null;\n }\n else {\n JMSException e = newBadConvertException(obj, name, \"Byte[]\", tc);\n if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(this, tc, \"Invalid convert\", e);\n throw e;\n }\n\n if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, \"getBytes\", Arrays.toString(value));\n return value;\n }\n\n /**\n * @see javax.jms.MapMessage#getObject(String)\n */\n public Object getObject(String name) throws JMSException {\n if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, \"getObject\", name);\n\n Object result = null;\n Object obj = null;\n try {\n obj = mapMsg.getObject(name);\n }\n catch (UnsupportedEncodingException e) {\n // No FFDC Code Needed\n throw (JMSException) JmsErrorUtils.newThrowable(\n JMSException.class,\n \"EXCEPTION_RECEIVED_CWSIA0022\",\n new Object[] {e, \"JmsMapMessageImpl.getObject\"},\n e, \"JmsMapMessageImpl#11\", this, tc);\n }\n if (obj instanceof byte[]) {\n // Take a copy to prevent an application from altering the data in the message\n byte[] objB = (byte[])obj;\n byte[] value = new byte[objB.length];\n System.arraycopy(objB, 0, value, 0, objB.length);\n result = value;\n }\n else {\n result = obj;\n }\n\n if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, \"getObject\", result);\n return result;\n }\n\n /**\n * @see javax.jms.MapMessage#getMapNames()\n */\n public Enumeration getMapNames() throws JMSException {\n if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, \"getMapNames\");\n\n Enumeration map=null;\n try {\n map = mapMsg.getMapNames();\n } catch (UnsupportedEncodingException e) {\n // No FFDC Code Needed\n throw (JMSException) JmsErrorUtils.newThrowable(\n JMSException.class,\n \"EXCEPTION_RECEIVED_CWSIA0022\",\n new Object[] {e, \"JmsMapMessageImpl.getMapNames\"},\n e, \"JmsMapMessageImpl#12\", this, tc);\n }\n\n if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, \"getMapNames\", map);\n return map;\n }\n\n /**\n * @see javax.jms.MapMessage#setBoolean(String, boolean)\n */\n public void setBoolean(String name, boolean value) throws JMSException {\n if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, \"setBoolean\", new Object[]{name, value});\n\n checkBodyWriteable(\"setBoolean\");\n checkPropName(name, \"setBoolean\");\n try {\n mapMsg.setBoolean(name, value);\n }\n catch (UnsupportedEncodingException e) {\n // No FFDC Code Needed\n throw (JMSException) JmsErrorUtils.newThrowable(\n JMSException.class,\n \"EXCEPTION_RECEIVED_CWSIA0022\",\n new Object[] {e, \"JmsMapMessageImpl.setBoolean\"},\n e, \"JmsMapMessageImpl#13\", this, tc);\n }\n // Invalidate the cached toString object.\n cachedMapToString = null;\n\n if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, \"setBoolean\");\n }\n\n /**\n * @see javax.jms.MapMessage#setByte(String, byte)\n */\n public void setByte(String name, byte value) throws JMSException {\n if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, \"setByte\", new Object[]{name, value});\n\n checkBodyWriteable(\"setByte\");\n checkPropName(name, \"setByte\");\n try {\n mapMsg.setByte(name, value);\n }\n catch (UnsupportedEncodingException e) {\n // No FFDC Code Needed\n throw (JMSException) JmsErrorUtils.newThrowable(\n JMSException.class,\n \"EXCEPTION_RECEIVED_CWSIA0022\",\n new Object[] {e, \"JmsMapMessageImpl.setByte\"},\n e, \"JmsMapMessageImpl#14\", this, tc);\n }\n // Invalidate the cached toString object.\n cachedMapToString = null;\n\n if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, \"setByte\");\n }\n\n /**\n * @see javax.jms.MapMessage#setBytes(String, byte[])\n */\n public void setBytes(String name, byte[] value) throws JMSException {\n if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, \"setBytes\", new Object[]{name, value});\n\n int length = 0;\n if (value != null) length = value.length;\n setBytes(name, value, 0, length);\n\n if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, \"setBytes\");\n }\n\n /**\n * @see javax.jms.MapMessage#setBytes(String, byte[], int, int)\n */\n public void setBytes(String name, byte[] value, int start, int length) throws JMSException {\n if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, \"setBytes\", new Object[]{name, value, start, length});\n\n checkBodyWriteable(\"setBytes\");\n checkPropName(name, \"setBytes\");\n\n // carry out the deep copy & defend against nulls\n // (should be able to set a null without any problems).\n byte[] deepCopy = null;\n if (value != null) {\n deepCopy = new byte[length];\n System.arraycopy(value, start, deepCopy, 0, length);\n }\n\n try {\n // pass the copy of the array in to the message object.\n mapMsg.setBytes(name, deepCopy);\n }\n catch (UnsupportedEncodingException e) {\n // No FFDC Code Needed\n throw (JMSException) JmsErrorUtils.newThrowable(\n JMSException.class,\n \"EXCEPTION_RECEIVED_CWSIA0022\",\n new Object[] {e, \"JmsMapMessageImpl.setBytes\"},\n e, \"JmsMapMessageImpl#15\", this, tc);\n }\n\n // Invalidate the cached toString object.\n cachedMapToString = null;\n\n if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, \"setBytes\");\n }\n\n /**\n * @see javax.jms.MapMessage#setChar(String, char)\n */\n public void setChar(String name, char value) throws JMSException {\n if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, \"setChar\", new Object[]{name, value});\n\n checkBodyWriteable(\"setChar\");\n checkPropName(name, \"setChar\");\n try {\n mapMsg.setChar(name, value);\n }\n catch (UnsupportedEncodingException e) {\n // No FFDC Code Needed", "answers": [" throw (JMSException) JmsErrorUtils.newThrowable("], "length": 2190, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "0bb60a39-831a-4aaa-b21f-0ccb55e709a5", "reasoning": "The method setChar follows the same pattern as setBoolean and setByte: after catching UnsupportedEncodingException, it throws a JMSException using JmsErrorUtils.newThrowable with the appropriate identifier. The very next line after the comment is the start of that throw statement.", "reasoning_model_answer": "throw (JMSException) JmsErrorUtils.newThrowable(", "assistant_with_reasoning": "\nThe method setChar follows the same pattern as setBoolean and setByte: after catching UnsupportedEncodingException, it throws a JMSException using JmsErrorUtils.newThrowable with the appropriate identifier. The very next line after the comment is the start of that throw statement.\n\nthrow (JMSException) JmsErrorUtils.newThrowable(", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 6.215, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 22539, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "throw (JMSException) JmsErrorUtils.newThrowable(", "score": 0.94, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/*\n * Copyright 2001-2009 The Apache Software Foundation.\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.apache.juddi.v3.tck;\n\nimport java.util.ArrayList;\nimport java.util.Calendar;\nimport java.util.GregorianCalendar;\nimport java.util.List;\nimport javax.xml.datatype.DatatypeConfigurationException;\nimport javax.xml.datatype.DatatypeFactory;\nimport javax.xml.datatype.XMLGregorianCalendar;\nimport javax.xml.soap.SOAPFault;\nimport javax.xml.ws.BindingProvider;\nimport javax.xml.ws.Holder;\nimport org.apache.commons.configuration.ConfigurationException;\nimport org.apache.commons.logging.Log;\nimport org.apache.commons.logging.LogFactory;\nimport org.apache.juddi.v3.client.UDDIConstants;\nimport org.apache.juddi.v3.client.config.UDDIClient;\nimport org.apache.juddi.v3.client.transport.Transport;\nimport org.junit.AfterClass;\nimport org.junit.Assert;\nimport org.junit.Assume;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\nimport org.uddi.api_v3.AddPublisherAssertions;\nimport org.uddi.api_v3.BusinessDetail;\nimport org.uddi.api_v3.BusinessEntity;\nimport org.uddi.api_v3.BusinessService;\nimport org.uddi.api_v3.CompletionStatus;\nimport org.uddi.api_v3.DeletePublisherAssertions;\nimport org.uddi.api_v3.FindBusiness;\nimport org.uddi.api_v3.FindQualifiers;\nimport org.uddi.api_v3.FindService;\nimport org.uddi.api_v3.GetAssertionStatusReport;\nimport org.uddi.api_v3.KeyedReference;\nimport org.uddi.api_v3.Name;\nimport org.uddi.api_v3.PublisherAssertion;\nimport org.uddi.api_v3.SaveBusiness;\nimport org.uddi.api_v3.SaveService;\nimport org.uddi.sub_v3.CoveragePeriod;\nimport org.uddi.sub_v3.GetSubscriptionResults;\nimport org.uddi.sub_v3.Subscription;\nimport org.uddi.sub_v3.SubscriptionFilter;\nimport org.uddi.sub_v3.SubscriptionResultsList;\nimport org.uddi.v3_service.UDDIInquiryPortType;\nimport org.uddi.v3_service.UDDIPublicationPortType;\nimport org.uddi.v3_service.UDDISecurityPortType;\nimport org.uddi.v3_service.UDDISubscriptionPortType;\n\n/**\n * @author Jeff Faath\n * @author Kurt T Stam\n * @author Alex O'Ree\n */\npublic class UDDI_080_SubscriptionIntegrationTest {\n\n private static Log logger = LogFactory.getLog(UDDI_080_SubscriptionIntegrationTest.class);\n private static TckTModel tckTModelJoe = null;\n private static TckBusiness tckBusinessJoe = null;\n private static TckBusinessService tckBusinessServiceJoe = null;\n private static TckBindingTemplate tckBindingTemplateJoe = null;\n private static TckSubscription tckSubscriptionJoe = null;\n private static TckTModel tckTModelSam = null;\n private static TckBusiness tckBusinessSam = null;\n private static TckBusinessService tckBusinessServiceSam = null;\n// private static TckBindingTemplate tckBindingTemplateSam = null;\n private static TckSubscription tckSubscriptionSam = null;\n private static String authInfoJoe = null;\n private static String authInfoSam = null;\n private static UDDIClient manager;\n static UDDIPublicationPortType publicationJoe = null;\n static UDDIPublicationPortType publicationSam = null;\n static UDDISubscriptionPortType subscriptionJoe = null;\n\n @AfterClass\n public static void stopManager() throws ConfigurationException {\n Assume.assumeTrue(TckPublisher.isEnabled());\n tckTModelJoe.deleteCreatedTModels(authInfoJoe);\n tckTModelSam.deleteCreatedTModels(authInfoSam);\n manager.stop();\n }\n\n @BeforeClass\n public static void startManager() throws ConfigurationException {\n Assume.assumeTrue(TckPublisher.isEnabled());\n manager = new UDDIClient();\n manager.start();\n\n logger.debug(\"Getting auth tokens..\");\n try {\n Transport transport = manager.getTransport(\"uddiv3\");\n UDDISecurityPortType security = transport.getUDDISecurityService();\n authInfoJoe = TckSecurity.getAuthToken(security, TckPublisher.getJoePublisherId(), TckPublisher.getJoePassword());\n authInfoSam = TckSecurity.getAuthToken(security, TckPublisher.getSamPublisherId(), TckPublisher.getSamPassword());\n\n //Assert.assertNotNull(authInfoJoe);\n UDDISubscriptionPortType subscription = transport.getUDDISubscriptionService();\n\n publicationJoe = transport.getUDDIPublishService();\n UDDIInquiryPortType inquiry = transport.getUDDIInquiryService();\n\n if (!TckPublisher.isUDDIAuthMode()) {\n TckSecurity.setCredentials((BindingProvider) publicationJoe, TckPublisher.getJoePublisherId(), TckPublisher.getJoePassword());\n TckSecurity.setCredentials((BindingProvider) subscription, TckPublisher.getJoePublisherId(), TckPublisher.getJoePassword());\n TckSecurity.setCredentials((BindingProvider) inquiry, TckPublisher.getJoePublisherId(), TckPublisher.getJoePassword());\n }\n\n tckTModelJoe = new TckTModel(publicationJoe, inquiry);\n tckBusinessJoe = new TckBusiness(publicationJoe, inquiry);\n tckBusinessServiceJoe = new TckBusinessService(publicationJoe, inquiry);\n tckBindingTemplateJoe = new TckBindingTemplate(publicationJoe, inquiry);\n subscriptionJoe = subscription;\n tckSubscriptionJoe = new TckSubscription(subscription, security, inquiry);\n\n\n transport = manager.getTransport(\"uddiv3\");\n publicationSam = transport.getUDDIPublishService();\n inquiry = transport.getUDDIInquiryService();\n subscription = transport.getUDDISubscriptionService();\n if (!TckPublisher.isUDDIAuthMode()) {\n TckSecurity.setCredentials((BindingProvider) publicationSam, TckPublisher.getSamPublisherId(), TckPublisher.getSamPassword());\n TckSecurity.setCredentials((BindingProvider) subscription, TckPublisher.getSamPublisherId(), TckPublisher.getSamPassword());\n TckSecurity.setCredentials((BindingProvider) inquiry, TckPublisher.getSamPublisherId(), TckPublisher.getSamPassword());\n }\n tckTModelSam = new TckTModel(publicationSam, inquiry);\n tckBusinessSam = new TckBusiness(publicationSam, inquiry);\n tckBusinessServiceSam = new TckBusinessService(publicationSam, inquiry);\n //tckBindingTemplateSam = new TckBindingTemplate(publicationSam, inquiry);\n tckSubscriptionSam = new TckSubscription(subscription, security, inquiry);\n\n\n String authInfoUDDI = TckSecurity.getAuthToken(security, TckPublisher.getUDDIPublisherId(), TckPublisher.getUDDIPassword());\n transport = manager.getTransport(\"uddiv3\");\n UDDIPublicationPortType publication = transport.getUDDIPublishService();\n inquiry = transport.getUDDIInquiryService();\n\n if (!TckPublisher.isUDDIAuthMode()) {\n TckSecurity.setCredentials((BindingProvider) publication, TckPublisher.getUDDIPublisherId(), TckPublisher.getUDDIPassword());\n\n TckSecurity.setCredentials((BindingProvider) inquiry, TckPublisher.getUDDIPublisherId(), TckPublisher.getUDDIPassword());\n }\n\n TckTModel tckTModelUDDI = new TckTModel(publication, inquiry);\n tckTModelUDDI.saveUDDIPublisherTmodel(authInfoUDDI);\n tckTModelUDDI.saveTModels(authInfoUDDI, TckTModel.TMODELS_XML);\n } catch (Exception e) {\n logger.error(e.getMessage(), e);\n Assert.fail(\"Could not obtain authInfo token.\");\n }\n }\n static final String TRANS = \"The transaction has been rolled back\";\n static final String MISSING_RESOURCE = \"Can't find resource for bundle\";\n\n static void HandleException(Exception ex) {\n System.err.println(\"Error caught of type \" + ex.getClass().getCanonicalName());\n ex.printStackTrace();\n if (ex.getMessage() != null) {\n Assert.assertFalse(ex.getMessage().contains(TRANS));\n Assert.assertFalse(ex.getMessage().contains(MISSING_RESOURCE));\n }\n if (ex instanceof SOAPFault) {\n SOAPFault sf = (SOAPFault) ex;\n if (!sf.getTextContent().contains(\"org.apache.juddi.v3.error.ValueNotAllowedException\")) {\n Assert.fail();\n }\n }\n }\n\n @Test\n public void joePublisher() {\n Assume.assumeTrue(TckPublisher.isEnabled());\n Assume.assumeTrue(TckPublisher.isSubscriptionEnabled());\n try {\n TckCommon.removeAllExistingSubscriptions(authInfoJoe, subscriptionJoe);\n tckTModelJoe.saveJoePublisherTmodel(authInfoJoe);\n tckBusinessJoe.saveJoePublisherBusiness(authInfoJoe);\n tckBusinessServiceJoe.saveJoePublisherService(authInfoJoe);\n tckBindingTemplateJoe.saveJoePublisherBinding(authInfoJoe);\n tckSubscriptionJoe.saveJoePublisherSubscription(authInfoJoe);\n tckSubscriptionJoe.getJoePublisherSubscriptionResults(authInfoJoe);\n } finally {\n tckSubscriptionJoe.deleteJoePublisherSubscription(authInfoJoe);\n tckBindingTemplateJoe.deleteJoePublisherBinding(authInfoJoe);\n tckBusinessServiceJoe.deleteJoePublisherService(authInfoJoe);\n tckBusinessJoe.deleteJoePublisherBusiness(authInfoJoe);\n tckTModelJoe.deleteJoePublisherTmodel(authInfoJoe);\n }\n }\n\n @Test\n public void samSyndicator() {\n Assume.assumeTrue(TckPublisher.isEnabled());\n Assume.assumeTrue(TckPublisher.isSubscriptionEnabled());\n try {\n tckTModelSam.saveSamSyndicatorTmodel(authInfoSam);\n tckBusinessSam.saveSamSyndicatorBusiness(authInfoSam);\n tckBusinessServiceSam.saveSamSyndicatorService(authInfoSam);\n tckSubscriptionSam.saveSamSyndicatorSubscription(authInfoSam);\n tckSubscriptionSam.getSamSyndicatorSubscriptionResults(authInfoSam);\n } finally {\n tckSubscriptionSam.deleteSamSyndicatorSubscription(authInfoSam);\n tckBusinessServiceSam.deleteSamSyndicatorService(authInfoSam);\n tckBusinessSam.deleteSamSyndicatorBusiness(authInfoSam);\n tckTModelSam.deleteSamSyndicatorTmodel(authInfoSam);\n }\n\n }\n\n @Test\n public void samSyndicatorWithChunkingOnFind() {\n Assume.assumeTrue(TckPublisher.isEnabled());\n \n Assume.assumeTrue(TckPublisher.isSubscriptionEnabled());\n try {\n tckTModelSam.saveSamSyndicatorTmodel(authInfoSam);\n tckBusinessSam.saveSamSyndicatorBusiness(authInfoSam);\n tckBusinessServiceSam.saveSamSyndicatorService(authInfoSam);\n tckSubscriptionSam.saveSamSyndicatorSubscriptionWithChunkingOnFind(authInfoSam);\n tckSubscriptionSam.getSamSyndicatorSubscriptionResultsWithChunkingOnFind(authInfoSam);\n } finally {\n tckSubscriptionSam.deleteSamSyndicatorSubscriptionWithChunkingOnFind(authInfoSam);\n tckBusinessServiceSam.deleteSamSyndicatorService(authInfoSam);\n tckBusinessSam.deleteSamSyndicatorBusiness(authInfoSam);\n tckTModelSam.deleteSamSyndicatorTmodel(authInfoSam);\n }\n\n }\n\n @Test\n public void samSyndicatorWithChunkingOnGet() {\n Assume.assumeTrue(TckPublisher.isEnabled());\n Assume.assumeTrue(TckPublisher.isSubscriptionEnabled());\n try {\n tckTModelSam.saveSamSyndicatorTmodel(authInfoSam);\n tckBusinessSam.saveSamSyndicatorBusiness(authInfoSam);\n tckBusinessServiceSam.saveSamSyndicatorService(authInfoSam);\n tckSubscriptionSam.saveSamSyndicatorSubscriptionWithChunkingOnGet(authInfoSam);\n tckSubscriptionSam.getSamSyndicatorSubscriptionResultsWithChunkingOnGet(authInfoSam);\n } finally {\n tckSubscriptionSam.deleteSamSyndicatorSubscriptionWithChunkingOnGet(authInfoSam);\n tckBusinessServiceSam.deleteSamSyndicatorService(authInfoSam);\n tckBusinessSam.deleteSamSyndicatorBusiness(authInfoSam);\n tckTModelSam.deleteSamSyndicatorTmodel(authInfoSam);\n }\n\n }\n\n /**\n * Null expiration time, the server should set the expiration time\n */\n @Test\n public void JUDDI_606_1() {\n Assume.assumeTrue(TckPublisher.isEnabled());\n System.out.println(\"JUDDI_606_1\");\n Assume.assumeTrue(TckPublisher.isSubscriptionEnabled());\n // Null expiration time\n\n Subscription sub = new Subscription();\n Holder> data = new Holder>();\n data.value = new ArrayList();\n sub.setBrief(true);\n sub.setExpiresAfter(null);\n sub.setMaxEntities(1);\n sub.setNotificationInterval(null);\n sub.setBindingKey(null);\n sub.setSubscriptionFilter(new SubscriptionFilter());\n sub.getSubscriptionFilter().setFindService(new FindService());\n sub.getSubscriptionFilter().getFindService().setFindQualifiers(new FindQualifiers());\n sub.getSubscriptionFilter().getFindService().getFindQualifiers().getFindQualifier().add(UDDIConstants.APPROXIMATE_MATCH);\n sub.getSubscriptionFilter().getFindService().getName().add(new Name(\"%\", null));\n data.value.add(sub);\n try {\n tckSubscriptionJoe.subscription.saveSubscription(authInfoJoe, data);\n Assert.assertNotNull(data.value.get(0).getExpiresAfter());\n } catch (Exception ex) {\n HandleException(ex);\n Assert.fail();\n }\n }\n\n /**\n * invalid expiration time\n *\n * @throws DatatypeConfigurationException\n */\n @Test\n public void JUDDI_606_2() throws DatatypeConfigurationException {\n Assume.assumeTrue(TckPublisher.isEnabled());\n System.out.println(\"JUDDI_606_2\");\n Assume.assumeTrue(TckPublisher.isSubscriptionEnabled());\n // invalid expiration time\n DatatypeFactory df = DatatypeFactory.newInstance();\n GregorianCalendar gcal = new GregorianCalendar();\n gcal.setTimeInMillis(System.currentTimeMillis());\n gcal.add(Calendar.DATE, -1);\n XMLGregorianCalendar newXMLGregorianCalendar = df.newXMLGregorianCalendar(gcal);\n\n Subscription sub = new Subscription();\n Holder> data = new Holder>();\n data.value = new ArrayList();\n sub.setBrief(true);\n sub.setExpiresAfter(newXMLGregorianCalendar);\n sub.setMaxEntities(1);\n sub.setNotificationInterval(null);\n sub.setBindingKey(null);\n sub.setSubscriptionFilter(new SubscriptionFilter());\n sub.getSubscriptionFilter().setFindService(new FindService());\n sub.getSubscriptionFilter().getFindService().setFindQualifiers(new FindQualifiers());\n sub.getSubscriptionFilter().getFindService().getFindQualifiers().getFindQualifier().add(UDDIConstants.APPROXIMATE_MATCH);\n sub.getSubscriptionFilter().getFindService().getName().add(new Name(\"%\", null));\n data.value.add(sub);\n try {\n tckSubscriptionJoe.subscription.saveSubscription(authInfoJoe, data);\n Assert.fail();\n } catch (Exception ex) {\n //HandleException(ex);\n logger.info(\"Expected exception: \" + ex.getMessage());\n }\n }\n\n /**\n * confirm a subscription key is returned when not specified\n */\n @Test\n public void JUDDI_606_3() {\n Assume.assumeTrue(TckPublisher.isEnabled());\n System.out.println(\"JUDDI_606_3\");\n Assume.assumeTrue(TckPublisher.isSubscriptionEnabled());\n //\n\n Subscription sub = new Subscription();\n Holder> data = new Holder>();\n data.value = new ArrayList();\n sub.setBrief(true);\n sub.setExpiresAfter(null);\n sub.setMaxEntities(1);\n sub.setNotificationInterval(null);\n sub.setBindingKey(null);\n sub.setSubscriptionFilter(new SubscriptionFilter());\n sub.getSubscriptionFilter().setFindService(new FindService());\n sub.getSubscriptionFilter().getFindService().setFindQualifiers(new FindQualifiers());\n sub.getSubscriptionFilter().getFindService().getFindQualifiers().getFindQualifier().add(UDDIConstants.APPROXIMATE_MATCH);\n sub.getSubscriptionFilter().getFindService().getName().add(new Name(\"%\", null));\n data.value.add(sub);\n try {\n tckSubscriptionJoe.subscription.saveSubscription(authInfoJoe, data);\n Assert.assertNotNull(data.value.get(0).getSubscriptionKey());\n Assert.assertTrue(data.value.get(0).getSubscriptionKey().length() > 0);\n } catch (Exception ex) {\n HandleException(ex);\n Assert.fail();\n }\n }\n\n /**\n * null subscription filter\n */\n @Test\n public void JUDDI_606_4() {\n Assume.assumeTrue(TckPublisher.isEnabled());\n System.out.println(\"JUDDI_606_4\");\n //\n Assume.assumeTrue(TckPublisher.isSubscriptionEnabled());\n\n Subscription sub = new Subscription();\n Holder> data = new Holder>();\n data.value = new ArrayList();\n sub.setBrief(true);\n sub.setExpiresAfter(null);\n sub.setMaxEntities(1);\n sub.setNotificationInterval(null);\n sub.setBindingKey(null);\n sub.setSubscriptionFilter(null);\n\n try {\n tckSubscriptionJoe.subscription.saveSubscription(authInfoJoe, data);\n Assert.fail();\n } catch (Exception ex) {\n //HandleException(ex);\n logger.info(\"Expected exception: \" + ex.getMessage());\n }\n }\n\n /**\n * empty subscription filter\n */\n @Test\n public void JUDDI_606_5() {\n Assume.assumeTrue(TckPublisher.isEnabled());\n System.out.println(\"JUDDI_606_5\");\n //\n Assume.assumeTrue(TckPublisher.isSubscriptionEnabled());\n\n Subscription sub = new Subscription();\n Holder> data = new Holder>();\n data.value = new ArrayList();\n sub.setBrief(true);\n sub.setExpiresAfter(null);\n sub.setMaxEntities(1);\n sub.setNotificationInterval(null);\n sub.setBindingKey(null);\n sub.setSubscriptionFilter(new SubscriptionFilter());\n\n data.value.add(sub);\n try {\n tckSubscriptionJoe.subscription.saveSubscription(authInfoJoe, data);\n Assert.fail();\n } catch (Exception ex) {\n //HandleException(ex);\n logger.info(\"Expected exception: \" + ex.getMessage());\n }\n }\n\n /**\n * negative max entities\n */\n @Test\n public void JUDDI_606_6() {\n Assume.assumeTrue(TckPublisher.isEnabled());\n System.out.println(\"JUDDI_606_6\");\n //\n Assume.assumeTrue(TckPublisher.isSubscriptionEnabled());\n\n Subscription sub = new Subscription();\n Holder> data = new Holder>();\n data.value = new ArrayList();\n sub.setBrief(true);\n sub.setExpiresAfter(null);\n sub.setMaxEntities(-1);\n sub.setNotificationInterval(null);\n sub.setBindingKey(null);\n sub.setSubscriptionFilter(new SubscriptionFilter());\n sub.getSubscriptionFilter().setFindService(new FindService());\n sub.getSubscriptionFilter().getFindService().setFindQualifiers(new FindQualifiers());\n sub.getSubscriptionFilter().getFindService().getFindQualifiers().getFindQualifier().add(UDDIConstants.APPROXIMATE_MATCH);\n sub.getSubscriptionFilter().getFindService().getName().add(new Name(\"%\", null));\n data.value.add(sub);\n try {\n tckSubscriptionJoe.subscription.saveSubscription(authInfoJoe, data);\n Assert.assertTrue(data.value.get(0).getMaxEntities() > 0);\n } catch (Exception ex) {\n //HandleException(ex);\n //this is ok as well\n logger.info(\"Expected exception: \" + ex.getMessage());\n }\n }\n\n /**\n * more filters that expected\n *\n * @throws DatatypeConfigurationException\n */\n @Test\n public void JUDDI_606_7() throws DatatypeConfigurationException {\n Assume.assumeTrue(TckPublisher.isEnabled());\n System.out.println(\"JUDDI_606_7\");\n Assume.assumeTrue(TckPublisher.isSubscriptionEnabled());\n //\n DatatypeFactory df = DatatypeFactory.newInstance();\n try {\n\n Holder> data = new Holder>();\n data.value = new ArrayList();\n Subscription sub = new Subscription();\n sub.setBrief(false);\n sub.setExpiresAfter(null);\n sub.setMaxEntities(null);\n sub.setNotificationInterval(null);\n sub.setBindingKey(null);\n sub.setSubscriptionFilter(new SubscriptionFilter());\n sub.getSubscriptionFilter().setFindBusiness(new FindBusiness());\n sub.getSubscriptionFilter().getFindBusiness().setFindQualifiers(new FindQualifiers());\n sub.getSubscriptionFilter().getFindBusiness().getFindQualifiers().getFindQualifier().add(UDDIConstants.APPROXIMATE_MATCH);\n sub.getSubscriptionFilter().getFindBusiness().getName().add(new Name(\"%\", null));\n sub.getSubscriptionFilter().setFindService(new FindService());\n sub.getSubscriptionFilter().getFindService().setFindQualifiers(new FindQualifiers());\n sub.getSubscriptionFilter().getFindService().getFindQualifiers().getFindQualifier().add(UDDIConstants.APPROXIMATE_MATCH);\n sub.getSubscriptionFilter().getFindService().getName().add(new Name(\"%\", null));\n\n data.value.add(sub);\n\n tckSubscriptionJoe.subscription.saveSubscription(authInfoJoe, data);\n Assert.fail();\n } catch (Exception ex) {\n logger.info(ex.getMessage());\n\n }\n }\n\n /**\n * testing reset expiration. i.e. save, wait a second then resave it,\n * the expiration time should be further into the future\n */\n @Test\n public void JUDDI_606_8() {\n Assume.assumeTrue(TckPublisher.isEnabled());\n System.out.println(\"JUDDI_606_8\");\n Assume.assumeTrue(TckPublisher.isSubscriptionEnabled());\n //\n\n try {\n\n Holder> data = new Holder>();\n data.value = new ArrayList();\n Subscription sub = new Subscription();\n sub.setBrief(true);\n sub.setExpiresAfter(null);\n sub.setMaxEntities(null);\n sub.setNotificationInterval(null);\n sub.setBindingKey(null);\n sub.setSubscriptionFilter(new SubscriptionFilter());\n sub.getSubscriptionFilter().setFindService(new FindService());\n sub.getSubscriptionFilter().getFindService().setFindQualifiers(new FindQualifiers());\n sub.getSubscriptionFilter().getFindService().getFindQualifiers().getFindQualifier().add(UDDIConstants.APPROXIMATE_MATCH);\n sub.getSubscriptionFilter().getFindService().getName().add(new Name(\"%\", null));\n data.value.add(sub);\n\n tckSubscriptionJoe.subscription.saveSubscription(authInfoJoe, data);\n Assert.assertNotNull(data.value.get(0).getExpiresAfter());\n XMLGregorianCalendar xcal = data.value.get(0).getExpiresAfter();\n\n Thread.sleep(5000);\n data.value.get(0).setExpiresAfter(null);\n tckSubscriptionJoe.subscription.saveSubscription(authInfoJoe, data);\n Assert.assertNotNull(data.value.get(0).getExpiresAfter());\n Assert.assertNotSame(xcal, data.value.get(0).getExpiresAfter());\n long initial = xcal.toGregorianCalendar().getTimeInMillis();\n long finaltime = data.value.get(0).getExpiresAfter().toGregorianCalendar().getTimeInMillis();\n Assert.assertTrue(finaltime > initial);\n\n } catch (Exception ex) {\n HandleException(ex);\n Assert.fail();\n }\n }\n\n /**\n * asynch subscriptions , binding key doesn't exist\n *\n * @throws DatatypeConfigurationException\n */\n @Test\n public void JUDDI_606_9() throws DatatypeConfigurationException {\n Assume.assumeTrue(TckPublisher.isEnabled());\n System.out.println(\"JUDDI_606_9\");\n Assume.assumeTrue(TckPublisher.isSubscriptionEnabled());\n //\n\n DatatypeFactory df = DatatypeFactory.newInstance();\n\n try {\n\n Holder> data = new Holder>();\n data.value = new ArrayList();\n Subscription sub = new Subscription();\n sub.setBrief(true);\n sub.setExpiresAfter(null);\n sub.setMaxEntities(null);\n sub.setNotificationInterval(df.newDuration(5000));\n sub.setBindingKey(\"uddi:uddi.joepublisher.com:mykey\");\n sub.setSubscriptionFilter(new SubscriptionFilter());\n sub.getSubscriptionFilter().setFindService(new FindService());\n sub.getSubscriptionFilter().getFindService().setFindQualifiers(new FindQualifiers());\n sub.getSubscriptionFilter().getFindService().getFindQualifiers().getFindQualifier().add(UDDIConstants.APPROXIMATE_MATCH);\n sub.getSubscriptionFilter().getFindService().getName().add(new Name(\"%\", null));\n data.value.add(sub);\n\n tckSubscriptionJoe.subscription.saveSubscription(authInfoJoe, data);\n Assert.fail();\n } catch (Exception ex) {\n logger.info(\"Expected exception: \" + ex.getMessage());\n }\n }\n\n /**\n * asynch subscriptions, key exists , null interval\n *\n * @throws DatatypeConfigurationException\n */\n @Test\n public void JUDDI_606_10() throws DatatypeConfigurationException {\n Assume.assumeTrue(TckPublisher.isEnabled());\n System.out.println(\"JUDDI_606_10\");\n Assume.assumeTrue(TckPublisher.isSubscriptionEnabled());\n //\n try {\n\n tckTModelJoe.saveJoePublisherTmodel(authInfoJoe);\n tckBusinessJoe.saveJoePublisherBusiness(authInfoJoe);\n tckBusinessServiceJoe.saveJoePublisherService(authInfoJoe);\n tckBindingTemplateJoe.saveJoePublisherBinding(authInfoJoe);\n\n Holder> data = new Holder>();\n data.value = new ArrayList();\n Subscription sub = new Subscription();\n sub.setBrief(true);\n sub.setExpiresAfter(null);\n sub.setMaxEntities(null);\n sub.setNotificationInterval(null);\n sub.setBindingKey(TckBindingTemplate.JOE_BINDING_KEY);\n sub.setSubscriptionFilter(new SubscriptionFilter());\n sub.getSubscriptionFilter().setFindService(new FindService());\n sub.getSubscriptionFilter().getFindService().setFindQualifiers(new FindQualifiers());\n sub.getSubscriptionFilter().getFindService().getFindQualifiers().getFindQualifier().add(UDDIConstants.APPROXIMATE_MATCH);\n sub.getSubscriptionFilter().getFindService().getName().add(new Name(\"%\", null));\n data.value.add(sub);\n\n tckSubscriptionJoe.subscription.saveSubscription(authInfoJoe, data);\n Assert.fail();\n } catch (Exception ex) {\n //HandleException(ex);\n logger.info(\"Expected exception: \" + ex.getMessage());\n } finally {\n tckBindingTemplateJoe.deleteJoePublisherBinding(authInfoJoe);\n tckBusinessServiceJoe.deleteJoePublisherService(authInfoJoe);\n tckBusinessJoe.deleteJoePublisherBusiness(authInfoJoe);\n tckTModelJoe.deleteJoePublisherTmodel(authInfoJoe);\n }\n }\n\n /**\n * set subscription, make a change as the same user, get subscription\n * results no key specified\n *\n * @throws DatatypeConfigurationException\n */\n @Test\n public void JUDDI_606_11() throws DatatypeConfigurationException {\n Assume.assumeTrue(TckPublisher.isEnabled());\n System.out.println(\"JUDDI_606_11\");\n Assume.assumeTrue(TckPublisher.isSubscriptionEnabled());\n\n String key = null;\n DatatypeFactory df = DatatypeFactory.newInstance();\n try {\n\n Holder> data = new Holder>();\n data.value = new ArrayList();\n Subscription sub = new Subscription();\n sub.setBrief(false);\n sub.setExpiresAfter(null);\n sub.setMaxEntities(null);\n sub.setNotificationInterval(null);\n sub.setBindingKey(null);\n sub.setSubscriptionFilter(new SubscriptionFilter());\n sub.getSubscriptionFilter().setFindBusiness(new FindBusiness());\n sub.getSubscriptionFilter().getFindBusiness().setFindQualifiers(new FindQualifiers());\n sub.getSubscriptionFilter().getFindBusiness().getFindQualifiers().getFindQualifier().add(UDDIConstants.APPROXIMATE_MATCH);\n sub.getSubscriptionFilter().getFindBusiness().getName().add(new Name(\"%\", null));\n data.value.add(sub);\n\n tckSubscriptionJoe.subscription.saveSubscription(authInfoJoe, data);\n SaveBusiness sb = new SaveBusiness();\n sb.setAuthInfo(authInfoJoe);\n BusinessEntity be = new BusinessEntity();\n be.getName().add(new Name(\"Test business\", null));\n sb.getBusinessEntity().add(be);\n BusinessDetail saveBusiness = publicationJoe.saveBusiness(sb);\n\n key = saveBusiness.getBusinessEntity().get(0).getBusinessKey();\n\n GetSubscriptionResults gsr = new GetSubscriptionResults();\n gsr.setAuthInfo(authInfoJoe);\n gsr.setSubscriptionKey(null);\n gsr.setCoveragePeriod(new CoveragePeriod());\n GregorianCalendar gcal = new GregorianCalendar();\n gcal.setTimeInMillis(System.currentTimeMillis());\n gcal.add(Calendar.HOUR, -1);\n gsr.getCoveragePeriod().setStartPoint(df.newXMLGregorianCalendar(gcal));\n gcal = new GregorianCalendar();\n gcal.setTimeInMillis(System.currentTimeMillis());\n gsr.getCoveragePeriod().setEndPoint(df.newXMLGregorianCalendar(gcal));\n tckSubscriptionJoe.subscription.getSubscriptionResults(gsr);\n Assert.fail();\n } catch (Exception ex) {\n //HandleException(ex);\n //Assert.fail();\n logger.info(\"Expected exception: \" + ex.getMessage());\n } finally {\n TckCommon.DeleteBusiness(key, authInfoJoe, publicationJoe);\n }\n }\n\n /**\n *\n * @throws DatatypeConfigurationException set subscription, make a\n * change as the same user, get subscription results no period specified\n */\n @Test\n public void JUDDI_606_12() throws DatatypeConfigurationException {\n Assume.assumeTrue(TckPublisher.isEnabled());\n System.out.println(\"JUDDI_606_12\");\n Assume.assumeTrue(TckPublisher.isSubscriptionEnabled());\n //\n String key = null;\n try {\n\n tckTModelJoe.saveJoePublisherTmodel(authInfoJoe);\n tckBusinessJoe.saveJoePublisherBusiness(authInfoJoe);\n tckBusinessServiceJoe.saveJoePublisherService(authInfoJoe);\n tckBindingTemplateJoe.saveJoePublisherBinding(authInfoJoe);\n\n Holder> data = new Holder>();\n data.value = new ArrayList();\n Subscription sub = new Subscription();\n sub.setBrief(false);\n sub.setExpiresAfter(null);\n sub.setMaxEntities(null);\n sub.setNotificationInterval(null);\n sub.setBindingKey(null);\n sub.setSubscriptionFilter(new SubscriptionFilter());\n sub.getSubscriptionFilter().setFindBusiness(new FindBusiness());\n sub.getSubscriptionFilter().getFindBusiness().setFindQualifiers(new FindQualifiers());\n sub.getSubscriptionFilter().getFindBusiness().getFindQualifiers().getFindQualifier().add(UDDIConstants.APPROXIMATE_MATCH);\n sub.getSubscriptionFilter().getFindBusiness().getName().add(new Name(\"%\", null));\n data.value.add(sub);\n\n tckSubscriptionJoe.subscription.saveSubscription(authInfoJoe, data);\n SaveBusiness sb = new SaveBusiness();\n sb.setAuthInfo(authInfoJoe);\n BusinessEntity be = new BusinessEntity();\n be.getName().add(new Name(\"Test business\", null));\n sb.getBusinessEntity().add(be);\n BusinessDetail saveBusiness = publicationJoe.saveBusiness(sb);\n\n key = saveBusiness.getBusinessEntity().get(0).getBusinessKey();\n GetSubscriptionResults gsr = new GetSubscriptionResults();\n gsr.setAuthInfo(authInfoJoe);\n gsr.setSubscriptionKey(data.value.get(0).getSubscriptionKey());\n gsr.setCoveragePeriod(null);\n tckSubscriptionJoe.subscription.getSubscriptionResults(gsr);\n Assert.fail();\n } catch (Exception ex) {\n //HandleException(ex);\n //Assert.fail();\n logger.info(\"Expected exception: \" + ex.getMessage());\n } finally {\n TckCommon.DeleteBusiness(key, authInfoJoe, publicationJoe);\n tckBindingTemplateJoe.deleteJoePublisherBinding(authInfoJoe);\n tckBusinessServiceJoe.deleteJoePublisherService(authInfoJoe);\n tckBusinessJoe.deleteJoePublisherBusiness(authInfoJoe);\n tckTModelJoe.deleteJoePublisherTmodel(authInfoJoe);\n \n\n }\n }\n\n /**\n * set subscription, make a change as the same user, get subscription\n * results valid find_Business\n *\n * @throws DatatypeConfigurationException\n */\n @Test\n public void JUDDI_606_13() throws DatatypeConfigurationException {\n Assume.assumeTrue(TckPublisher.isEnabled());\n System.out.println(\"JUDDI_606_13\");\n Assume.assumeTrue(TckPublisher.isSubscriptionEnabled());\n\n String key = null;\n DatatypeFactory df = DatatypeFactory.newInstance();\n try {\n\n Holder> data = new Holder>();\n data.value = new ArrayList();\n Subscription sub = new Subscription();\n sub.setBrief(false);\n sub.setExpiresAfter(null);\n sub.setMaxEntities(null);\n sub.setNotificationInterval(null);\n sub.setBindingKey(null);\n sub.setSubscriptionFilter(new SubscriptionFilter());\n sub.getSubscriptionFilter().setFindBusiness(new FindBusiness());\n sub.getSubscriptionFilter().getFindBusiness().setFindQualifiers(new FindQualifiers());\n sub.getSubscriptionFilter().getFindBusiness().getFindQualifiers().getFindQualifier().add(UDDIConstants.APPROXIMATE_MATCH);\n sub.getSubscriptionFilter().getFindBusiness().getName().add(new Name(\"%\", null));\n data.value.add(sub);\n\n tckSubscriptionJoe.subscription.saveSubscription(authInfoJoe, data);\n SaveBusiness sb = new SaveBusiness();\n sb.setAuthInfo(authInfoJoe);\n BusinessEntity be = new BusinessEntity();\n be.getName().add(new Name(\"Test business\", null));\n sb.getBusinessEntity().add(be);\n BusinessDetail saveBusiness = publicationJoe.saveBusiness(sb);\n key = saveBusiness.getBusinessEntity().get(0).getBusinessKey();\n\n GetSubscriptionResults gsr = new GetSubscriptionResults();\n gsr.setAuthInfo(authInfoJoe);\n gsr.setSubscriptionKey(data.value.get(0).getSubscriptionKey());\n gsr.setCoveragePeriod(new CoveragePeriod());\n GregorianCalendar gcal = new GregorianCalendar();\n gcal.setTimeInMillis(System.currentTimeMillis());\n gcal.add(Calendar.HOUR, -1);\n gsr.getCoveragePeriod().setStartPoint(df.newXMLGregorianCalendar(gcal));\n gcal = new GregorianCalendar();\n gcal.setTimeInMillis(System.currentTimeMillis());\n gsr.getCoveragePeriod().setEndPoint(df.newXMLGregorianCalendar(gcal));\n SubscriptionResultsList subscriptionResults = tckSubscriptionJoe.subscription.getSubscriptionResults(gsr);\n Assert.assertNotNull(subscriptionResults);\n Assert.assertNotNull(subscriptionResults.getBusinessList());\n Assert.assertNotNull(subscriptionResults.getCoveragePeriod());\n Assert.assertNotNull(subscriptionResults.getBusinessList().getBusinessInfos());\n Assert.assertNotNull(subscriptionResults.getBusinessList().getBusinessInfos().getBusinessInfo().get(0));\n Assert.assertNotNull(subscriptionResults.getBusinessList().getBusinessInfos().getBusinessInfo().get(0).getBusinessKey());\n Assert.assertNotNull(subscriptionResults.getBusinessList().getBusinessInfos().getBusinessInfo().get(0).getName().get(0));\n\n } catch (Exception ex) {\n HandleException(ex);\n Assert.fail();\n } finally {\n TckCommon.DeleteBusiness(key, authInfoJoe, publicationJoe);\n }\n }\n\n /**\n * set subscription, make a change as the same user, get subscription\n * results valid find_services\n *\n * @throws DatatypeConfigurationException\n */\n @Test\n public void JUDDI_606_14() throws DatatypeConfigurationException {\n Assume.assumeTrue(TckPublisher.isEnabled());\n System.out.println(\"JUDDI_606_14\");\n Assume.assumeTrue(TckPublisher.isSubscriptionEnabled());\n\n DatatypeFactory df = DatatypeFactory.newInstance();\n try {\n\n\n Holder> data = new Holder>();\n data.value = new ArrayList();\n Subscription sub = new Subscription();\n sub.setBrief(false);\n sub.setExpiresAfter(null);\n sub.setMaxEntities(null);\n sub.setNotificationInterval(null);\n sub.setBindingKey(null);\n sub.setSubscriptionFilter(new SubscriptionFilter());\n sub.getSubscriptionFilter().setFindService(new FindService());\n sub.getSubscriptionFilter().getFindService().setFindQualifiers(new FindQualifiers());\n sub.getSubscriptionFilter().getFindService().getFindQualifiers().getFindQualifier().add(UDDIConstants.APPROXIMATE_MATCH);\n sub.getSubscriptionFilter().getFindService().getName().add(new Name(\"%\", null));\n data.value.add(sub);\n\n tckSubscriptionJoe.subscription.saveSubscription(authInfoJoe, data);\n tckTModelJoe.saveJoePublisherTmodel(authInfoJoe);\n tckBusinessJoe.saveJoePublisherBusiness(authInfoJoe);\n tckBusinessServiceJoe.saveJoePublisherService(authInfoJoe);\n /*SaveService sb = new SaveService();\n sb.setAuthInfo(authInfoJoe);\n BusinessService bs = new BusinessService();\n bs.getName().add(new Name(\"svc\", null));\n sb.getBusinessService().add(bs);\n publicationJoe.saveService(sb);*/\n\n GetSubscriptionResults gsr = new GetSubscriptionResults();\n gsr.setAuthInfo(authInfoJoe);\n gsr.setSubscriptionKey(data.value.get(0).getSubscriptionKey());\n gsr.setCoveragePeriod(new CoveragePeriod());\n GregorianCalendar gcal = new GregorianCalendar();\n gcal.setTimeInMillis(System.currentTimeMillis());\n gcal.add(Calendar.HOUR, -1);\n gsr.getCoveragePeriod().setStartPoint(df.newXMLGregorianCalendar(gcal));\n gcal = new GregorianCalendar();\n gcal.setTimeInMillis(System.currentTimeMillis());\n gsr.getCoveragePeriod().setEndPoint(df.newXMLGregorianCalendar(gcal));\n SubscriptionResultsList subscriptionResults = tckSubscriptionJoe.subscription.getSubscriptionResults(gsr);\n Assert.assertNotNull(subscriptionResults);\n Assert.assertNull(subscriptionResults.getBusinessList());\n Assert.assertNotNull(subscriptionResults.getCoveragePeriod());\n Assert.assertNotNull(subscriptionResults.getServiceList());\n Assert.assertNotNull(subscriptionResults.getServiceList().getServiceInfos().getServiceInfo().get(0));\n Assert.assertNotNull(subscriptionResults.getServiceList().getServiceInfos().getServiceInfo().get(0).getBusinessKey());\n Assert.assertNotNull(subscriptionResults.getServiceList().getServiceInfos().getServiceInfo().get(0).getName().get(0));\n\n } catch (Exception ex) {\n HandleException(ex);\n Assert.fail(ex.getMessage());\n } finally {\n tckBusinessJoe.deleteJoePublisherBusiness(authInfoJoe);\n tckTModelJoe.deleteJoePublisherTmodel(authInfoJoe);\n }\n }\n\n /**\n * //set subscription, make a change as the same user, get subscription\n * results. valid. publisher assertion, incomplete\n *\n * @throws DatatypeConfigurationException\n */\n @Test\n public void JUDDI_606_15() throws DatatypeConfigurationException {\n Assume.assumeTrue(TckPublisher.isEnabled());\n System.out.println(\"JUDDI_606_15\");\n Assume.assumeTrue(TckPublisher.isSubscriptionEnabled());\n\n DatatypeFactory df = DatatypeFactory.newInstance();\n try {\n\n tckTModelJoe.saveJoePublisherTmodel(authInfoJoe);\n tckBusinessJoe.saveJoePublisherBusiness(authInfoJoe);\n tckTModelSam.saveSamSyndicatorTmodel(authInfoSam);\n tckBusinessSam.saveSamSyndicatorBusiness(authInfoSam);\n \n \n Holder> data = new Holder>();\n data.value = new ArrayList();\n Subscription sub = new Subscription();\n sub.setBrief(false);\n sub.setExpiresAfter(null);\n sub.setMaxEntities(null);\n sub.setNotificationInterval(null);\n sub.setBindingKey(null);\n sub.setSubscriptionFilter(new SubscriptionFilter());\n sub.getSubscriptionFilter().setGetAssertionStatusReport(new GetAssertionStatusReport());\n sub.getSubscriptionFilter().getGetAssertionStatusReport().setCompletionStatus(CompletionStatus.STATUS_TO_KEY_INCOMPLETE);\n data.value.add(sub);\n\n tckSubscriptionJoe.subscription.saveSubscription(authInfoJoe, data);\n\n AddPublisherAssertions r = new AddPublisherAssertions();\n r.setAuthInfo(authInfoJoe);\n PublisherAssertion pa = new PublisherAssertion();\n pa.setFromKey(TckBusiness.JOE_BUSINESS_KEY);\n pa.setToKey(TckBusiness.SAM_BUSINESS_KEY);\n pa.setKeyedReference(new KeyedReference());\n pa.getKeyedReference().setKeyName(\"Subsidiary\");\n pa.getKeyedReference().setKeyValue(\"parent-child\");\n\n pa.getKeyedReference().setTModelKey(\"uddi:uddi.org:relationships\");\n\n r.getPublisherAssertion().add(pa);\n publicationJoe.addPublisherAssertions(r);\n\n GetSubscriptionResults gsr = new GetSubscriptionResults();\n gsr.setAuthInfo(authInfoJoe);\n gsr.setSubscriptionKey(data.value.get(0).getSubscriptionKey());\n gsr.setCoveragePeriod(new CoveragePeriod());\n GregorianCalendar gcal = new GregorianCalendar();\n gcal.setTimeInMillis(System.currentTimeMillis());\n gcal.add(Calendar.HOUR, -1);\n gsr.getCoveragePeriod().setStartPoint(df.newXMLGregorianCalendar(gcal));\n gcal = new GregorianCalendar();\n gcal.setTimeInMillis(System.currentTimeMillis());\n gsr.getCoveragePeriod().setEndPoint(df.newXMLGregorianCalendar(gcal));\n SubscriptionResultsList subscriptionResults = tckSubscriptionJoe.subscription.getSubscriptionResults(gsr);\n Assert.assertNotNull(subscriptionResults);\n Assert.assertNull(subscriptionResults.getBusinessList());\n Assert.assertNotNull(subscriptionResults.getCoveragePeriod());\n Assert.assertNull(subscriptionResults.getServiceList());\n Assert.assertNotNull(subscriptionResults.getAssertionStatusReport());\n Assert.assertNotNull(subscriptionResults.getAssertionStatusReport().getAssertionStatusItem());\n Assert.assertFalse(subscriptionResults.getAssertionStatusReport().getAssertionStatusItem().isEmpty());\n Assert.assertEquals(subscriptionResults.getAssertionStatusReport().getAssertionStatusItem().get(0).getFromKey(), TckBusiness.JOE_BUSINESS_KEY);\n Assert.assertEquals(subscriptionResults.getAssertionStatusReport().getAssertionStatusItem().get(0).getToKey(), TckBusiness.SAM_BUSINESS_KEY);\n Assert.assertNotNull(subscriptionResults.getAssertionStatusReport().getAssertionStatusItem().get(0).getCompletionStatus());\n Assert.assertEquals(subscriptionResults.getAssertionStatusReport().getAssertionStatusItem().get(0).getCompletionStatus(), CompletionStatus.STATUS_TO_KEY_INCOMPLETE);\n Assert.assertNotNull(subscriptionResults.getAssertionStatusReport().getAssertionStatusItem().get(0).getKeyedReference());\n } catch (Exception ex) {\n HandleException(ex);\n Assert.fail(ex.getMessage());\n }\n finally{\n \n tckBusinessJoe.saveJoePublisherBusiness(authInfoJoe);\n tckTModelJoe.saveJoePublisherTmodel(authInfoJoe);\n \n tckBusinessSam.deleteSamSyndicatorBusiness(authInfoSam);\n tckTModelSam.deleteSamSyndicatorTmodel(authInfoSam);\n \n }\n }\n\n /**\n * set subscription, make a change as the same user, get subscription\n * results valid publisher assertion, complete\n *\n * @throws DatatypeConfigurationException\n */\n @Test\n public void JUDDI_606_16() throws DatatypeConfigurationException {\n Assume.assumeTrue(TckPublisher.isEnabled());\n System.out.println(\"JUDDI_606_16\");\n Assume.assumeTrue(TckPublisher.isSubscriptionEnabled());\n\n DatatypeFactory df = DatatypeFactory.newInstance();\n try {\n tckTModelJoe.saveJoePublisherTmodel(authInfoJoe);\n tckBusinessJoe.saveJoePublisherBusiness(authInfoJoe);\n tckTModelSam.saveSamSyndicatorTmodel(authInfoSam);\n tckBusinessSam.saveSamSyndicatorBusiness(authInfoSam);\n \n\n Holder> data = new Holder>();\n data.value = new ArrayList();\n Subscription sub = new Subscription();\n sub.setBrief(false);\n sub.setExpiresAfter(null);\n sub.setMaxEntities(null);\n sub.setNotificationInterval(null);\n sub.setBindingKey(null);\n sub.setSubscriptionFilter(new SubscriptionFilter());\n sub.getSubscriptionFilter().setGetAssertionStatusReport(new GetAssertionStatusReport());\n sub.getSubscriptionFilter().getGetAssertionStatusReport().setCompletionStatus(CompletionStatus.STATUS_COMPLETE);\n data.value.add(sub);\n\n tckSubscriptionJoe.subscription.saveSubscription(authInfoJoe, data);\n\n AddPublisherAssertions r = new AddPublisherAssertions();\n r.setAuthInfo(authInfoJoe);\n PublisherAssertion pa = new PublisherAssertion();\n pa.setFromKey(TckBusiness.JOE_BUSINESS_KEY);\n pa.setToKey(TckBusiness.SAM_BUSINESS_KEY);\n pa.setKeyedReference(new KeyedReference());\n pa.getKeyedReference().setKeyName(\"Subsidiary\");\n pa.getKeyedReference().setKeyValue(\"parent-child\");\n pa.getKeyedReference().setTModelKey(\"uddi:uddi.org:relationships\");\n r.getPublisherAssertion().add(pa);\n publicationJoe.addPublisherAssertions(r);\n\n\n r = new AddPublisherAssertions();\n r.setAuthInfo(authInfoSam);\n pa = new PublisherAssertion();\n pa.setFromKey(TckBusiness.JOE_BUSINESS_KEY);\n pa.setToKey(TckBusiness.SAM_BUSINESS_KEY);\n pa.setKeyedReference(new KeyedReference());\n pa.getKeyedReference().setKeyName(\"Subsidiary\");\n pa.getKeyedReference().setKeyValue(\"parent-child\");\n pa.getKeyedReference().setTModelKey(\"uddi:uddi.org:relationships\");\n r.getPublisherAssertion().add(pa);\n publicationJoe.addPublisherAssertions(r);\n\n\n\n GetSubscriptionResults gsr = new GetSubscriptionResults();\n gsr.setAuthInfo(authInfoJoe);\n gsr.setSubscriptionKey(data.value.get(0).getSubscriptionKey());\n gsr.setCoveragePeriod(new CoveragePeriod());\n GregorianCalendar gcal = new GregorianCalendar();", "answers": [" gcal.setTimeInMillis(System.currentTimeMillis());"], "length": 2254, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "09e3793d-b850-4432-9233-f2c0ee8bcfdd", "reasoning": "The code is constructing a GetSubscriptionResults object and needs to define the coverage period. In similar test methods, after creating a GregorianCalendar instance the next step is to set its time to the current system time before adjusting it. Therefore the next line after `GregorianCalendar gcal = new GregorianCalendar();` is `gcal.setTimeInMillis(System.currentTimeMillis());`.", "reasoning_model_answer": "gcal.setTimeInMillis(System.currentTimeMillis());", "assistant_with_reasoning": "\nThe code is constructing a GetSubscriptionResults object and needs to define the coverage period. In similar test methods, after creating a GregorianCalendar instance the next step is to set its time to the current system time before adjusting it. Therefore the next line after `GregorianCalendar gcal = new GregorianCalendar();` is `gcal.setTimeInMillis(System.currentTimeMillis());`.\n\ngcal.setTimeInMillis(System.currentTimeMillis());", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 5.08, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 48004, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "gcal.setTimeInMillis(System.currentTimeMillis());", "score": 0.8, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "import numpy as np\n\n\n\"\"\"\nThis file defines layer types that are commonly used for recurrent neural\nnetworks.\n\"\"\"\n\n\ndef rnn_step_forward(x, prev_h, Wx, Wh, b):\n \"\"\"\n Run the forward pass for a single timestep of a vanilla RNN that uses a tanh\n activation function.\n\n The input data has dimension D, the hidden state has dimension H, and we use\n a minibatch size of N.\n\n Inputs:\n - x: Input data for this timestep, of shape (N, D).\n - prev_h: Hidden state from previous timestep, of shape (N, H)\n - Wx: Weight matrix for input-to-hidden connections, of shape (D, H)\n - Wh: Weight matrix for hidden-to-hidden connections, of shape (H, H)\n - b: Biases of shape (H,)\n\n Returns a tuple of:\n - next_h: Next hidden state, of shape (N, H)\n - cache: Tuple of values needed for the backward pass.\n \"\"\"\n\n next_h = np.tanh(np.dot(x, Wx) + np.dot(prev_h, Wh) + b)\n cache = (x, prev_h, Wx, Wh, next_h)\n\n return next_h, cache\n\n\ndef rnn_step_backward(dnext_h, cache):\n \"\"\"\n Backward pass for a single timestep of a vanilla RNN.\n\n Inputs:\n - dnext_h: Gradient of loss with respect to next hidden state\n - cache: Cache object from the forward pass\n\n Returns a tuple of:\n - dx: Gradients of input data, of shape (N, D)\n - dprev_h: Gradients of previous hidden state, of shape (N, H)\n - dWx: Gradients of input-to-hidden weights, of shape (N, H)\n - dWh: Gradients of hidden-to-hidden weights, of shape (H, H)\n - db: Gradients of bias vector, of shape (H,)\n \"\"\"\n\n x, prev_h, Wx, Wh, next_h = cache\n\n daffine = dnext_h * (1 - np.square(next_h))\n\n db = np.sum(daffine, axis=0)\n dWx = np.dot(x.T, daffine)\n dx = np.dot(daffine, Wx.T)\n dWh = np.dot(prev_h.T, daffine)\n dprev_h = np.dot(daffine, Wh.T)\n\n return dx, dprev_h, dWx, dWh, db\n\n\ndef rnn_forward(x, h0, Wx, Wh, b):\n \"\"\"\n Run a vanilla RNN forward on an entire sequence of data. We assume an input\n sequence composed of T vectors, each of dimension D. The RNN uses a hidden\n size of H, and we work over a minibatch containing N sequences. After running\n the RNN forward, we return the hidden states for all timesteps.\n\n Inputs:\n - x: Input data for the entire timeseries, of shape (N, T, D).\n - h0: Initial hidden state, of shape (N, H)\n - Wx: Weight matrix for input-to-hidden connections, of shape (D, H)\n - Wh: Weight matrix for hidden-to-hidden connections, of shape (H, H)\n - b: Biases of shape (H,)\n\n Returns a tuple of:\n - h: Hidden states for the entire timeseries, of shape (N, T, H).\n - cache: Values needed in the backward pass\n \"\"\"\n cache = []\n N, T, D = x.shape\n _, H = h0.shape\n\n h = np.zeros((N, T, H))\n\n h[:, 0, :], c = rnn_step_forward(x[:, 0, :], h0, Wx, Wh, b)\n cache.append(c)\n for i in np.arange(1, T):\n h[:, i, :], c = rnn_step_forward(x[:, i, :], h[:, i - 1, :], Wx, Wh, b)\n cache.append(c)\n\n return h, cache\n\n\ndef rnn_backward(dh, cache):\n \"\"\"\n Compute the backward pass for a vanilla RNN over an entire sequence of data.\n\n Inputs:\n - dh: Upstream gradients of all hidden states, of shape (N, T, H)\n\n Returns a tuple of:\n - dx: Gradient of inputs, of shape (N, T, D)\n - dh0: Gradient of initial hidden state, of shape (N, H)\n - dWx: Gradient of input-to-hidden weights, of shape (D, H)\n - dWh: Gradient of hidden-to-hidden weights, of shape (H, H)\n - db: Gradient of biases, of shape (H,)\n \"\"\"\n\n N, T, H = dh.shape\n (_, D), dtype = cache[0][0].shape, cache[0][0].dtype\n dx = np.zeros((N, T, D), dtype=dtype)\n\n dx[:, T - 1, :], dh_prev, dWx, dWh, db = \\\n rnn_step_backward(dh[:, T - 1, :], cache[T - 1])\n for i in np.arange(T - 2, -1, -1):\n dx[:, i, :], dh_prev, dWx_temp, dWh_temp, db_temp = \\\n rnn_step_backward(dh[:, i, :] + dh_prev, cache[i])\n dWx += dWx_temp\n dWh += dWh_temp\n db += db_temp\n\n return dx, dh_prev, dWx, dWh, db\n\n\ndef word_embedding_forward(x, W):\n \"\"\"\n Forward pass for word embeddings. We operate on minibatches of size N where\n each sequence has length T. We assume a vocabulary of V words, assigning each\n to a vector of dimension D.\n\n Inputs:\n - x: Integer array of shape (N, T) giving indices of words. Each element idx\n of x muxt be in the range 0 <= idx < V.\n - W: Weight matrix of shape (V, D) giving word vectors for all words.\n\n Returns a tuple of:\n - out: Array of shape (N, T, D) giving word vectors for all input words.\n - cache: Values needed for the backward pass\n \"\"\"\n\n out = W[x]\n cache = (x, W)\n\n return out, cache\n\n\ndef word_embedding_backward(dout, cache):\n \"\"\"\n Backward pass for word embeddings. We cannot back-propagate into the words\n since they are integers, so we only return gradient for the word embedding\n matrix.\n\n HINT: Look up the function np.add.at\n\n Inputs:\n - dout: Upstream gradients of shape (N, T, D)\n - cache: Values from the forward pass\n\n Returns:\n - dW: Gradient of word embedding matrix, of shape (V, D).\n \"\"\"\n\n x, W = cache\n\n dW = np.zeros_like(W)\n\n np.add.at(dW, x, dout)\n\n return dW\n\n\ndef sigmoid(x):\n \"\"\"\n A numerically stable version of the logistic sigmoid function.\n \"\"\"\n pos_mask = (x >= 0)\n neg_mask = (x < 0)\n z = np.zeros_like(x)\n z[pos_mask] = np.exp(-x[pos_mask])\n z[neg_mask] = np.exp(x[neg_mask])\n top = np.ones_like(x)\n top[neg_mask] = z[neg_mask]\n return top / (1 + z)\n\n\ndef lstm_step_forward(x, prev_h, prev_c, Wx, Wh, b):\n \"\"\"\n Forward pass for a single timestep of an LSTM.\n\n The input data has dimension D, the hidden state has dimension H, and we use\n a minibatch size of N.\n\n Inputs:\n - x: Input data, of shape (N, D)\n - prev_h: Previous hidden state, of shape (N, H)\n - prev_c: previous cell state, of shape (N, H)\n - Wx: Input-to-hidden weights, of shape (D, 4H)\n - Wh: Hidden-to-hidden weights, of shape (H, 4H)\n - b: Biases, of shape (4H,)\n\n Returns a tuple of:\n - next_h: Next hidden state, of shape (N, H)\n - next_c: Next cell state, of shape (N, H)\n - cache: Tuple of values needed for backward pass.\n \"\"\"\n \n affine = np.dot(x, Wx) + np.dot(prev_h, Wh) + b\n [i, f, o, g] = np.split(affine, 4, axis=1)\n \n i = sigmoid(i)\n f = sigmoid(f)\n o = sigmoid(o)\n g = np.tanh(g)\n \n next_c = f * prev_c + i * g\n tanh_next_c = np.tanh(next_c)\n next_h = o * tanh_next_c\n \n cache = (x, prev_h, prev_c, Wx, Wh, b, i, f, o, g, tanh_next_c)\n\n return next_h, next_c, cache\n\n\ndef lstm_step_backward(dnext_h, dnext_c, cache):\n \"\"\"\n Backward pass for a single timestep of an LSTM.\n\n Inputs:\n - dnext_h: Gradients of next hidden state, of shape (N, H)\n - dnext_c: Gradients of next cell state, of shape (N, H)\n - cache: Values from the forward pass\n\n Returns a tuple of:\n - dx: Gradient of input data, of shape (N, D)\n - dprev_h: Gradient of previous hidden state, of shape (N, H)\n - dprev_c: Gradient of previous cell state, of shape (N, H)\n - dWx: Gradient of input-to-hidden weights, of shape (D, 4H)\n - dWh: Gradient of hidden-to-hidden weights, of shape (H, 4H)\n - db: Gradient of biases, of shape (4H,)\n \"\"\"\n \n x, prev_h, prev_c, Wx, Wh, b, i, f, o, g, tanh_next_c = cache\n \n dnext_c = dnext_c + dnext_h * o * (1 - np.square(tanh_next_c))\n \n di = dnext_c * g \n df = dnext_c * prev_c\n do = dnext_h * tanh_next_c\n dg = dnext_c * i\n \n daffine_i = di * i * (1 - i)\n daffine_f = df * f * (1 - f)\n daffine_o = do * o * (1 - o)\n daffine_g = dg * (1 - np.square(g))\n \n daffine = np.concatenate((daffine_i, daffine_f, daffine_o, daffine_g), axis=1)\n \n dx = np.dot(daffine, Wx.T)\n dprev_h = np.dot(daffine, Wh.T)\n dprev_c = dnext_c * f\n dWx = np.dot(x.T, daffine)\n dWh = np.dot(prev_h.T, daffine)\n db = np.sum(daffine, axis=0)\n\n return dx, dprev_h, dprev_c, dWx, dWh, db\n\n\ndef lstm_forward(x, h0, Wx, Wh, b):\n \"\"\"\n Forward pass for an LSTM over an entire sequence of data. We assume an input\n sequence composed of T vectors, each of dimension D. The LSTM uses a hidden\n size of H, and we work over a minibatch containing N sequences. After running\n the LSTM forward, we return the hidden states for all timesteps.\n\n Note that the initial cell state is passed as input, but the initial cell\n state is set to zero. Also note that the cell state is not returned; it is\n an internal variable to the LSTM and is not accessed from outside.\n\n Inputs:\n - x: Input data of shape (N, T, D)\n - h0: Initial hidden state of shape (N, H)\n - Wx: Weights for input-to-hidden connections, of shape (D, 4H)\n - Wh: Weights for hidden-to-hidden connections, of shape (H, 4H)\n - b: Biases of shape (4H,)\n\n Returns a tuple of:\n - h: Hidden states for all timesteps of all sequences, of shape (N, T, H)\n - cache: Values needed for the backward pass.\n \"\"\"\n\n cache = []\n N, T, D = x.shape\n _, H = h0.shape\n c0 = np.zeros_like(h0)\n\n h = np.zeros((N, T, H))\n c = np.zeros((N, T, H))\n\n h[:, 0, :], c[:, 0, :], temp = lstm_step_forward(x[:, 0, :], h0, c0, Wx, Wh, b)\n cache.append(temp)\n for i in np.arange(1, T):\n h[:, i, :], c[:, i, :], temp = \\\n lstm_step_forward(x[:, i, :], h[:, i - 1, :], c[:, i - 1, :], Wx, Wh, b)\n cache.append(temp)\n", "answers": [" return h, cache"], "length": 1539, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "cdc06b2e-256b-41d0-a9ae-cefb3ce00dac", "reasoning": "The lstm_forward function builds hidden states h and cell states c across timesteps, storing intermediate caches. After completing the loop over all timesteps, the function should output the computed hidden states and the cache list, matching its docstring and the pattern of similar forward functions (e.g., rnn_forward). Therefore the next line is the return statement returning h and cache.", "reasoning_model_answer": "return h, cache", "assistant_with_reasoning": "\nThe lstm_forward function builds hidden states h and cell states c across timesteps, storing intermediate caches. After completing the loop over all timesteps, the function should output the computed hidden states and the cache list, matching its docstring and the pattern of similar forward functions (e.g., rnn_forward). Therefore the next line is the return statement returning h and cache.\n\nreturn h, cache", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.27, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 9570, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "return h, cache", "score": 0.88, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/**\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.apache.hadoop.hive.serde2.objectinspector;\n\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Map;\n\nimport org.apache.hadoop.hive.serde2.objectinspector.primitive.JavaStringObjectInspector;\nimport org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorConverter;\nimport org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory;\nimport org.apache.hadoop.hive.serde2.objectinspector.primitive.SettableBinaryObjectInspector;\nimport org.apache.hadoop.hive.serde2.objectinspector.primitive.SettableBooleanObjectInspector;\nimport org.apache.hadoop.hive.serde2.objectinspector.primitive.SettableByteObjectInspector;\nimport org.apache.hadoop.hive.serde2.objectinspector.primitive.SettableDateObjectInspector;\nimport org.apache.hadoop.hive.serde2.objectinspector.primitive.SettableDoubleObjectInspector;\nimport org.apache.hadoop.hive.serde2.objectinspector.primitive.SettableFloatObjectInspector;\nimport org.apache.hadoop.hive.serde2.objectinspector.primitive.SettableHiveCharObjectInspector;\nimport org.apache.hadoop.hive.serde2.objectinspector.primitive.SettableHiveDecimalObjectInspector;\nimport org.apache.hadoop.hive.serde2.objectinspector.primitive.SettableHiveIntervalDayTimeObjectInspector;\nimport org.apache.hadoop.hive.serde2.objectinspector.primitive.SettableHiveIntervalYearMonthObjectInspector;\nimport org.apache.hadoop.hive.serde2.objectinspector.primitive.SettableHiveVarcharObjectInspector;\nimport org.apache.hadoop.hive.serde2.objectinspector.primitive.SettableIntObjectInspector;\nimport org.apache.hadoop.hive.serde2.objectinspector.primitive.SettableLongObjectInspector;\nimport org.apache.hadoop.hive.serde2.objectinspector.primitive.SettableShortObjectInspector;\nimport org.apache.hadoop.hive.serde2.objectinspector.primitive.SettableTimestampObjectInspector;\nimport org.apache.hadoop.hive.serde2.objectinspector.primitive.VoidObjectInspector;\nimport org.apache.hadoop.hive.serde2.objectinspector.primitive.WritableStringObjectInspector;\nimport org.apache.hadoop.hive.serde2.typeinfo.PrimitiveTypeInfo;\n\n/**\n * ObjectInspectorConverters.\n *\n */\npublic final class ObjectInspectorConverters {\n\n /**\n * A converter which will convert objects with one ObjectInspector to another.\n */\n public static interface Converter {\n Object convert(Object input);\n }\n\n /**\n * IdentityConverter.\n *\n */\n public static class IdentityConverter implements Converter {\n @Override\n public Object convert(Object input) {\n return input;\n }\n }\n\n private static Converter getConverter(PrimitiveObjectInspector inputOI,\n PrimitiveObjectInspector outputOI) {\n switch (outputOI.getPrimitiveCategory()) {\n case BOOLEAN:\n return new PrimitiveObjectInspectorConverter.BooleanConverter(\n inputOI,\n (SettableBooleanObjectInspector) outputOI);\n case BYTE:\n return new PrimitiveObjectInspectorConverter.ByteConverter(\n inputOI,\n (SettableByteObjectInspector) outputOI);\n case SHORT:\n return new PrimitiveObjectInspectorConverter.ShortConverter(\n inputOI,\n (SettableShortObjectInspector) outputOI);\n case INT:\n return new PrimitiveObjectInspectorConverter.IntConverter(\n inputOI,\n (SettableIntObjectInspector) outputOI);\n case LONG:\n return new PrimitiveObjectInspectorConverter.LongConverter(\n inputOI,\n (SettableLongObjectInspector) outputOI);\n case FLOAT:\n return new PrimitiveObjectInspectorConverter.FloatConverter(\n inputOI,\n (SettableFloatObjectInspector) outputOI);\n case DOUBLE:\n return new PrimitiveObjectInspectorConverter.DoubleConverter(\n inputOI,\n (SettableDoubleObjectInspector) outputOI);\n case STRING:\n if (outputOI instanceof WritableStringObjectInspector) {\n return new PrimitiveObjectInspectorConverter.TextConverter(\n inputOI);\n } else if (outputOI instanceof JavaStringObjectInspector) {\n return new PrimitiveObjectInspectorConverter.StringConverter(\n inputOI);\n }\n case CHAR:\n return new PrimitiveObjectInspectorConverter.HiveCharConverter(\n inputOI,\n (SettableHiveCharObjectInspector) outputOI);\n case VARCHAR:\n return new PrimitiveObjectInspectorConverter.HiveVarcharConverter(\n inputOI,\n (SettableHiveVarcharObjectInspector) outputOI);\n case DATE:\n return new PrimitiveObjectInspectorConverter.DateConverter(\n inputOI,\n (SettableDateObjectInspector) outputOI);\n case TIMESTAMP:\n return new PrimitiveObjectInspectorConverter.TimestampConverter(\n inputOI,\n (SettableTimestampObjectInspector) outputOI);\n case INTERVAL_YEAR_MONTH:\n return new PrimitiveObjectInspectorConverter.HiveIntervalYearMonthConverter(\n inputOI,\n (SettableHiveIntervalYearMonthObjectInspector) outputOI);\n case INTERVAL_DAY_TIME:\n return new PrimitiveObjectInspectorConverter.HiveIntervalDayTimeConverter(\n inputOI,\n (SettableHiveIntervalDayTimeObjectInspector) outputOI);\n case BINARY:\n return new PrimitiveObjectInspectorConverter.BinaryConverter(\n inputOI,\n (SettableBinaryObjectInspector)outputOI);\n case DECIMAL:\n return new PrimitiveObjectInspectorConverter.HiveDecimalConverter(\n inputOI,\n (SettableHiveDecimalObjectInspector) outputOI);\n default:\n throw new RuntimeException(\"Hive internal error: conversion of \"\n + inputOI.getTypeName() + \" to \" + outputOI.getTypeName()\n + \" not supported yet.\");\n }\n }\n\n /**\n * Returns a converter that converts objects from one OI to another OI. The\n * returned (converted) object belongs to this converter, so that it can be\n * reused across different calls.\n */\n public static Converter getConverter(ObjectInspector inputOI,\n ObjectInspector outputOI) {\n // If the inputOI is the same as the outputOI, just return an\n // IdentityConverter.\n if (inputOI.equals(outputOI)) {\n return new IdentityConverter();\n }\n switch (outputOI.getCategory()) {\n case PRIMITIVE:\n return getConverter((PrimitiveObjectInspector) inputOI, (PrimitiveObjectInspector) outputOI);\n case STRUCT:\n return new StructConverter(inputOI,\n (SettableStructObjectInspector) outputOI);\n case LIST:\n return new ListConverter(inputOI,\n (SettableListObjectInspector) outputOI);\n case MAP:\n return new MapConverter(inputOI,\n (SettableMapObjectInspector) outputOI);\n case UNION:\n return new UnionConverter(inputOI,\n (SettableUnionObjectInspector) outputOI);\n default:\n throw new RuntimeException(\"Hive internal error: conversion of \"\n + inputOI.getTypeName() + \" to \" + outputOI.getTypeName()\n + \" not supported yet.\");\n }\n }\n\n /*\n * getConvertedOI with caching to store settable properties of the object\n * inspector. Caching might help when the object inspector\n * contains complex nested data types. Caching is not explicitly required for\n * the returned object inspector across multiple invocations since the\n * ObjectInspectorFactory already takes care of it.\n */\n public static ObjectInspector getConvertedOI(\n ObjectInspector inputOI, ObjectInspector outputOI,\n Map oiSettableProperties\n ) {\n return getConvertedOI(inputOI, outputOI, oiSettableProperties, true);\n }\n\n /*\n * getConvertedOI without any caching.\n */\n public static ObjectInspector getConvertedOI(\n ObjectInspector inputOI,\n ObjectInspector outputOI\n ) {\n return getConvertedOI(inputOI, outputOI, null, true);\n }\n\n /**\n * Utility function to convert from one object inspector type to another.\n * The output object inspector type should have all fields as settableOI type.\n * The above condition can be violated only if equalsCheck is true and inputOI is\n * equal to outputOI.\n * @param inputOI : input object inspector\n * @param outputOI : output object inspector\n * @param oiSettableProperties : The object inspector to isSettable mapping used to cache\n * intermediate results.\n * @param equalsCheck : Do we need to check if the inputOI and outputOI are the same?\n * true : If they are the same, we return the object inspector directly.\n * false : Do not perform an equality check on inputOI and outputOI\n * @return : The output object inspector containing all settable fields. The return value\n * can contain non-settable fields only if inputOI equals outputOI and equalsCheck is\n * true.\n */\n public static ObjectInspector getConvertedOI(\n ObjectInspector inputOI,\n ObjectInspector outputOI,\n Map oiSettableProperties,\n boolean equalsCheck) {\n // 1. If equalsCheck is true and the inputOI is the same as the outputOI OR\n // 2. If the outputOI has all fields settable, return it\n if ((equalsCheck && inputOI.equals(outputOI)) ||\n ObjectInspectorUtils.hasAllFieldsSettable(outputOI, oiSettableProperties) == true) {\n return outputOI;\n }\n // Return the settable equivalent object inspector for primitive categories\n // For eg: for table T containing partitions p1 and p2 (possibly different\n // from the table T), return the settable inspector for T. The inspector for\n // T is settable recursively i.e all the nested fields are also settable.\n switch (outputOI.getCategory()) {\n case PRIMITIVE:\n // Create a writable object inspector for primitive type and return it.\n PrimitiveObjectInspector primOutputOI = (PrimitiveObjectInspector) outputOI;\n return PrimitiveObjectInspectorFactory.getPrimitiveWritableObjectInspector(\n primOutputOI.getTypeInfo());\n case STRUCT:\n StructObjectInspector structOutputOI = (StructObjectInspector) outputOI;\n // create a standard settable struct object inspector.\n List listFields = structOutputOI.getAllStructFieldRefs();\n List structFieldNames = new ArrayList(listFields.size());\n List structFieldObjectInspectors = new ArrayList(\n listFields.size());\n\n for (StructField listField : listFields) {\n structFieldNames.add(listField.getFieldName());\n // We need to make sure that the underlying fields are settable as well.\n // Hence, the recursive call for each field.\n // Note that equalsCheck is false while invoking getConvertedOI() because\n // we need to bypass the initial inputOI.equals(outputOI) check.\n structFieldObjectInspectors.add(getConvertedOI(listField.getFieldObjectInspector(),\n listField.getFieldObjectInspector(), oiSettableProperties, false));\n }\n return ObjectInspectorFactory.getStandardStructObjectInspector(\n structFieldNames,\n structFieldObjectInspectors);\n case LIST:\n ListObjectInspector listOutputOI = (ListObjectInspector) outputOI;\n // We need to make sure that the list element type is settable.\n return ObjectInspectorFactory.getStandardListObjectInspector(\n getConvertedOI(listOutputOI.getListElementObjectInspector(),\n listOutputOI.getListElementObjectInspector(), oiSettableProperties, false));\n case MAP:\n MapObjectInspector mapOutputOI = (MapObjectInspector) outputOI;\n // We need to make sure that the key type and the value types are settable.\n return ObjectInspectorFactory.getStandardMapObjectInspector(\n getConvertedOI(mapOutputOI.getMapKeyObjectInspector(),\n mapOutputOI.getMapKeyObjectInspector(), oiSettableProperties, false),\n getConvertedOI(mapOutputOI.getMapValueObjectInspector(),\n mapOutputOI.getMapValueObjectInspector(), oiSettableProperties, false));\n case UNION:\n UnionObjectInspector unionOutputOI = (UnionObjectInspector) outputOI;\n // create a standard settable union object inspector\n List unionListFields = unionOutputOI.getObjectInspectors();\n List unionFieldObjectInspectors = new ArrayList(\n unionListFields.size());\n for (ObjectInspector listField : unionListFields) {\n // We need to make sure that all the field associated with the union are settable.\n unionFieldObjectInspectors.add(getConvertedOI(listField, listField, oiSettableProperties,\n false));\n }\n return ObjectInspectorFactory.getStandardUnionObjectInspector(unionFieldObjectInspectors);\n default:\n // Unsupported in-memory structure.\n throw new RuntimeException(\"Hive internal error: conversion of \"\n + inputOI.getTypeName() + \" to \" + outputOI.getTypeName()\n + \" not supported yet.\");\n }\n }\n\n /**\n * A converter class for List.\n */\n public static class ListConverter implements Converter {\n\n ListObjectInspector inputOI;\n SettableListObjectInspector outputOI;\n\n ObjectInspector inputElementOI;\n ObjectInspector outputElementOI;\n\n ArrayList elementConverters;\n\n Object output;\n\n public ListConverter(ObjectInspector inputOI,\n SettableListObjectInspector outputOI) {\n if (inputOI instanceof ListObjectInspector) {\n this.inputOI = (ListObjectInspector)inputOI;\n this.outputOI = outputOI;\n inputElementOI = this.inputOI.getListElementObjectInspector();\n outputElementOI = outputOI.getListElementObjectInspector();\n output = outputOI.create(0);\n elementConverters = new ArrayList();\n } else if (!(inputOI instanceof VoidObjectInspector)) {\n throw new RuntimeException(\"Hive internal error: conversion of \" +\n inputOI.getTypeName() + \" to \" + outputOI.getTypeName() +\n \"not supported yet.\");\n }\n }\n\n @Override\n public Object convert(Object input) {\n if (input == null) {\n return null;\n }\n // Create enough elementConverters\n // NOTE: we have to have a separate elementConverter for each element,\n // because the elementConverters can reuse the internal object.\n // So it's not safe to use the same elementConverter to convert multiple\n // elements.\n int size = inputOI.getListLength(input);\n while (elementConverters.size() < size) {\n elementConverters.add(getConverter(inputElementOI, outputElementOI));\n }\n\n // Convert the elements\n outputOI.resize(output, size);\n for (int index = 0; index < size; index++) {\n Object inputElement = inputOI.getListElement(input, index);\n Object outputElement = elementConverters.get(index).convert(\n inputElement);\n outputOI.set(output, index, outputElement);\n }\n return output;\n }\n\n }\n\n /**\n * A converter class for Struct.\n */\n public static class StructConverter implements Converter {\n\n StructObjectInspector inputOI;\n SettableStructObjectInspector outputOI;\n\n List inputFields;\n List outputFields;\n\n ArrayList fieldConverters;\n\n Object output;\n\n public StructConverter(ObjectInspector inputOI,\n SettableStructObjectInspector outputOI) {\n if (inputOI instanceof StructObjectInspector) {\n this.inputOI = (StructObjectInspector)inputOI;\n this.outputOI = outputOI;\n inputFields = this.inputOI.getAllStructFieldRefs();\n outputFields = outputOI.getAllStructFieldRefs();\n\n // If the output has some extra fields, set them to NULL.\n int minFields = Math.min(inputFields.size(), outputFields.size());\n fieldConverters = new ArrayList(minFields);\n for (int f = 0; f < minFields; f++) {\n fieldConverters.add(getConverter(inputFields.get(f)\n .getFieldObjectInspector(), outputFields.get(f)\n .getFieldObjectInspector()));\n }\n output = outputOI.create();\n } else if (!(inputOI instanceof VoidObjectInspector)) {\n throw new RuntimeException(\"Hive internal error: conversion of \" +\n inputOI.getTypeName() + \" to \" + outputOI.getTypeName() +\n \"not supported yet.\");\n }\n }\n\n @Override\n public Object convert(Object input) {\n if (input == null) {\n return null;\n }\n\n int minFields = Math.min(inputFields.size(), outputFields.size());\n // Convert the fields\n for (int f = 0; f < minFields; f++) {\n Object inputFieldValue = inputOI.getStructFieldData(input, inputFields.get(f));\n Object outputFieldValue = fieldConverters.get(f).convert(inputFieldValue);\n outputOI.setStructFieldData(output, outputFields.get(f), outputFieldValue);\n }\n\n // set the extra fields to null\n for (int f = minFields; f < outputFields.size(); f++) {\n outputOI.setStructFieldData(output, outputFields.get(f), null);\n }\n\n return output;\n }\n }\n\n /**\n * A converter class for Union.\n */\n public static class UnionConverter implements Converter {", "answers": [" UnionObjectInspector inputOI;"], "length": 1537, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "8e199f51-b25d-4144-8232-196208c5bb09", "reasoning": "Following the pattern of the other converter classes (ListConverter, StructConverter), the UnionConverter class will start by declaring its member fields. The first field should be the input UnionObjectInspector, matching the naming convention used elsewhere. Therefore the next line is the declaration of the inputOI field of type UnionObjectInspector.", "reasoning_model_answer": "UnionObjectInspector inputOI;", "assistant_with_reasoning": "\nFollowing the pattern of the other converter classes (ListConverter, StructConverter), the UnionConverter class will start by declaring its member fields. The first field should be the input UnionObjectInspector, matching the naming convention used elsewhere. Therefore the next line is the declaration of the inputOI field of type UnionObjectInspector.\n\nUnionObjectInspector inputOI;", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 7.655, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 18188, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "UnionObjectInspector inputOI;", "score": 0.94, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "# Copyright (c) 2012, Cloudscaling\n# All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nimport ast\nimport re\n\nimport pep8\n\n\"\"\"\nGuidelines for writing new hacking checks\n\n - Use only for Nova specific tests. OpenStack general tests\n should be submitted to the common 'hacking' module.\n - Pick numbers in the range N3xx. Find the current test with\n the highest allocated number and then pick the next value.\n - Keep the test method code in the source file ordered based\n on the N3xx value.\n - List the new rule in the top level HACKING.rst file\n - Add test cases for each new rule to nova/tests/test_hacking.py\n\n\"\"\"\n\nUNDERSCORE_IMPORT_FILES = []\n\nsession_check = re.compile(r\"\\w*def [a-zA-Z0-9].*[(].*session.*[)]\")\ncfg_re = re.compile(r\".*\\scfg\\.\")\nvi_header_re = re.compile(r\"^#\\s+vim?:.+\")\nvirt_file_re = re.compile(r\"\\./nova/(?:tests/)?virt/(\\w+)/\")\nvirt_import_re = re.compile(\n r\"^\\s*(?:import|from) nova\\.(?:tests\\.)?virt\\.(\\w+)\")\nvirt_config_re = re.compile(\n r\"CONF\\.import_opt\\('.*?', 'nova\\.virt\\.(\\w+)('|.)\")\nauthor_tag_re = (re.compile(\"^\\s*#\\s*@?(a|A)uthor:\"),\n re.compile(\"^\\.\\.\\s+moduleauthor::\"))\nasse_trueinst_re = re.compile(\n r\"(.)*assertTrue\\(isinstance\\((\\w|\\.|\\'|\\\"|\\[|\\])+, \"\n \"(\\w|\\.|\\'|\\\"|\\[|\\])+\\)\\)\")\nasse_equal_type_re = re.compile(\n r\"(.)*assertEqual\\(type\\((\\w|\\.|\\'|\\\"|\\[|\\])+\\), \"\n \"(\\w|\\.|\\'|\\\"|\\[|\\])+\\)\")\nasse_equal_end_with_none_re = re.compile(\n r\"assertEqual\\(.*?,\\s+None\\)$\")\nasse_equal_start_with_none_re = re.compile(\n r\"assertEqual\\(None,\")\n# NOTE(snikitin): Next two regexes weren't united to one for more readability.\n# asse_true_false_with_in_or_not_in regex checks\n# assertTrue/False(A in B) cases where B argument has no spaces\n# asse_true_false_with_in_or_not_in_spaces regex checks cases\n# where B argument has spaces and starts/ends with [, ', \".\n# For example: [1, 2, 3], \"some string\", 'another string'.\n# We have to separate these regexes to escape a false positives\n# results. B argument should have spaces only if it starts\n# with [, \", '. Otherwise checking of string\n# \"assertFalse(A in B and C in D)\" will be false positives.\n# In this case B argument is \"B and C in D\".\nasse_true_false_with_in_or_not_in = re.compile(r\"assert(True|False)\\(\"\n r\"(\\w|[][.'\\\"])+( not)? in (\\w|[][.'\\\",])+(, .*)?\\)\")\nasse_true_false_with_in_or_not_in_spaces = re.compile(r\"assert(True|False)\"\n r\"\\((\\w|[][.'\\\"])+( not)? in [\\[|'|\\\"](\\w|[][.'\\\", ])+\"\n r\"[\\[|'|\\\"](, .*)?\\)\")\nasse_raises_regexp = re.compile(r\"assertRaisesRegexp\\(\")\nconf_attribute_set_re = re.compile(r\"CONF\\.[a-z0-9_.]+\\s*=\\s*\\w\")\nlog_translation = re.compile(\n r\"(.)*LOG\\.(audit|error|critical)\\(\\s*('|\\\")\")\nlog_translation_info = re.compile(\n r\"(.)*LOG\\.(info)\\(\\s*(_\\(|'|\\\")\")\nlog_translation_exception = re.compile(\n r\"(.)*LOG\\.(exception)\\(\\s*(_\\(|'|\\\")\")\nlog_translation_LW = re.compile(\n r\"(.)*LOG\\.(warning)\\(\\s*(_\\(|'|\\\")\")\nlog_warn = re.compile(\n r\"(.)*LOG\\.(warn)\\(\\s*('|\\\"|_)\")\ntranslated_log = re.compile(\n r\"(.)*LOG\\.(audit|error|info|critical|exception)\"\n \"\\(\\s*_\\(\\s*('|\\\")\")\nmutable_default_args = re.compile(r\"^\\s*def .+\\((.+=\\{\\}|.+=\\[\\])\")\nstring_translation = re.compile(r\"[^_]*_\\(\\s*('|\\\")\")\nunderscore_import_check = re.compile(r\"(.)*import _(.)*\")\n# We need this for cases where they have created their own _ function.\ncustom_underscore_check = re.compile(r\"(.)*_\\s*=\\s*(.)*\")\napi_version_re = re.compile(r\"@.*api_version\")\n\n# TODO(dims): When other oslo libraries switch over non-namespace'd\n# imports, we need to add them to the regexp below.\noslo_namespace_imports = re.compile(r\"from[\\s]*oslo[.](concurrency)\")\n\n\nclass BaseASTChecker(ast.NodeVisitor):\n \"\"\"Provides a simple framework for writing AST-based checks.\n\n Subclasses should implement visit_* methods like any other AST visitor\n implementation. When they detect an error for a particular node the\n method should call ``self.add_error(offending_node)``. Details about\n where in the code the error occurred will be pulled from the node\n object.\n\n Subclasses should also provide a class variable named CHECK_DESC to\n be used for the human readable error message.\n\n \"\"\"\n\n def __init__(self, tree, filename):\n \"\"\"This object is created automatically by pep8.\n\n :param tree: an AST tree\n :param filename: name of the file being analyzed\n (ignored by our checks)\n \"\"\"\n self._tree = tree\n self._errors = []\n\n def run(self):\n \"\"\"Called automatically by pep8.\"\"\"\n self.visit(self._tree)\n return self._errors\n\n def add_error(self, node, message=None):\n \"\"\"Add an error caused by a node to the list of errors for pep8.\"\"\"\n message = message or self.CHECK_DESC\n error = (node.lineno, node.col_offset, message, self.__class__)\n self._errors.append(error)\n\n def _check_call_names(self, call_node, names):\n if isinstance(call_node, ast.Call):\n if isinstance(call_node.func, ast.Name):\n if call_node.func.id in names:\n return True\n return False\n\n\ndef import_no_db_in_virt(logical_line, filename):\n \"\"\"Check for db calls from nova/virt\n\n As of grizzly-2 all the database calls have been removed from\n nova/virt, and we want to keep it that way.\n\n N307\n \"\"\"\n if \"nova/virt\" in filename and not filename.endswith(\"fake.py\"):\n if logical_line.startswith(\"from nova import db\"):\n yield (0, \"N307: nova.db import not allowed in nova/virt/*\")\n\n\ndef no_db_session_in_public_api(logical_line, filename):\n if \"db/api.py\" in filename:\n if session_check.match(logical_line):\n yield (0, \"N309: public db api methods may not accept session\")\n\n\ndef use_timeutils_utcnow(logical_line, filename):\n # tools are OK to use the standard datetime module\n if \"/tools/\" in filename:\n return\n\n msg = \"N310: timeutils.utcnow() must be used instead of datetime.%s()\"\n\n datetime_funcs = ['now', 'utcnow']\n for f in datetime_funcs:\n pos = logical_line.find('datetime.%s' % f)\n if pos != -1:\n yield (pos, msg % f)\n\n\ndef _get_virt_name(regex, data):\n m = regex.match(data)\n if m is None:\n return None\n driver = m.group(1)\n # Ignore things we mis-detect as virt drivers in the regex\n if driver in [\"test_virt_drivers\", \"driver\", \"firewall\",\n \"disk\", \"api\", \"imagecache\", \"cpu\", \"hardware\"]:\n return None\n # TODO(berrange): remove once bugs 1261826 and 126182 are\n # fixed, or baremetal driver is removed, which is first.\n if driver == \"baremetal\":\n return None\n return driver\n\n\ndef import_no_virt_driver_import_deps(physical_line, filename):\n \"\"\"Check virt drivers' modules aren't imported by other drivers\n\n Modules under each virt driver's directory are\n considered private to that virt driver. Other drivers\n in Nova must not access those drivers. Any code that\n is to be shared should be refactored into a common\n module\n\n N311\n \"\"\"\n thisdriver = _get_virt_name(virt_file_re, filename)\n thatdriver = _get_virt_name(virt_import_re, physical_line)\n if (thatdriver is not None and\n thisdriver is not None and\n thisdriver != thatdriver):\n return (0, \"N311: importing code from other virt drivers forbidden\")\n\n\ndef import_no_virt_driver_config_deps(physical_line, filename):\n \"\"\"Check virt drivers' config vars aren't used by other drivers\n\n Modules under each virt driver's directory are\n considered private to that virt driver. Other drivers\n in Nova must not use their config vars. Any config vars\n that are to be shared should be moved into a common module\n\n N312\n \"\"\"\n thisdriver = _get_virt_name(virt_file_re, filename)\n thatdriver = _get_virt_name(virt_config_re, physical_line)\n if (thatdriver is not None and\n thisdriver is not None and\n thisdriver != thatdriver):\n return (0, \"N312: using config vars from other virt drivers forbidden\")\n\n\ndef capital_cfg_help(logical_line, tokens):\n msg = \"N313: capitalize help string\"\n\n if cfg_re.match(logical_line):\n for t in range(len(tokens)):\n if tokens[t][1] == \"help\":\n txt = tokens[t + 2][1]\n if len(txt) > 1 and txt[1].islower():\n yield(0, msg)\n\n\ndef no_vi_headers(physical_line, line_number, lines):\n \"\"\"Check for vi editor configuration in source files.\n\n By default vi modelines can only appear in the first or\n last 5 lines of a source file.\n\n N314\n \"\"\"\n # NOTE(gilliard): line_number is 1-indexed\n if line_number <= 5 or line_number > len(lines) - 5:\n if vi_header_re.match(physical_line):\n return 0, \"N314: Don't put vi configuration in source files\"\n\n\ndef assert_true_instance(logical_line):\n \"\"\"Check for assertTrue(isinstance(a, b)) sentences\n\n N316\n \"\"\"\n if asse_trueinst_re.match(logical_line):\n yield (0, \"N316: assertTrue(isinstance(a, b)) sentences not allowed\")\n\n\ndef assert_equal_type(logical_line):\n \"\"\"Check for assertEqual(type(A), B) sentences\n\n N317\n \"\"\"\n if asse_equal_type_re.match(logical_line):\n yield (0, \"N317: assertEqual(type(A), B) sentences not allowed\")\n\n\ndef assert_equal_none(logical_line):\n \"\"\"Check for assertEqual(A, None) or assertEqual(None, A) sentences\n\n N318\n \"\"\"\n res = (asse_equal_start_with_none_re.search(logical_line) or\n asse_equal_end_with_none_re.search(logical_line))\n if res:\n yield (0, \"N318: assertEqual(A, None) or assertEqual(None, A) \"\n \"sentences not allowed\")\n\n\ndef no_translate_debug_logs(logical_line, filename):\n \"\"\"Check for 'LOG.debug(_('\n\n As per our translation policy,\n https://wiki.openstack.org/wiki/LoggingStandards#Log_Translation\n we shouldn't translate debug level logs.\n\n * This check assumes that 'LOG' is a logger.\n * Use filename so we can start enforcing this in specific folders instead\n of needing to do so all at once.\n\n N319\n \"\"\"\n if logical_line.startswith(\"LOG.debug(_(\"):\n yield(0, \"N319 Don't translate debug level logs\")\n\n\ndef no_setting_conf_directly_in_tests(logical_line, filename):\n \"\"\"Check for setting CONF.* attributes directly in tests\n\n The value can leak out of tests affecting how subsequent tests run.\n Using self.flags(option=value) is the preferred method to temporarily\n set config options in tests.\n\n N320\n \"\"\"\n if 'nova/tests/' in filename:\n res = conf_attribute_set_re.match(logical_line)\n if res:\n yield (0, \"N320: Setting CONF.* attributes directly in tests is \"\n \"forbidden. Use self.flags(option=value) instead\")\n\n\ndef validate_log_translations(logical_line, physical_line, filename):\n # Translations are not required in the test directory\n # and the Xen utilities\n if (\"nova/tests\" in filename or\n \"plugins/xenserver/xenapi/etc/xapi.d\" in filename or\n # TODO(Mike_D):Needs to be remove with:\n # I075ab2a522272f2082c292dfedc877abd8ebe328\n \"nova/virt/libvirt\" in filename):\n return\n if pep8.noqa(physical_line):\n return\n msg = \"N328: LOG.info messages require translations `_LI()`!\"\n if log_translation_info.match(logical_line):\n yield (0, msg)\n msg = \"N329: LOG.exception messages require translations `_LE()`!\"\n if log_translation_exception.match(logical_line):\n yield (0, msg)\n msg = \"N330: LOG.warning messages require translations `_LW()`!\"\n if log_translation_LW.match(logical_line):\n yield (0, msg)\n msg = \"N331: Use LOG.warning due to compatibility with py3\"\n if log_warn.match(logical_line):\n yield (0, msg)\n msg = \"N321: Log messages require translations!\"\n if log_translation.match(logical_line):\n yield (0, msg)\n\n\ndef no_mutable_default_args(logical_line):\n msg = \"N322: Method's default argument shouldn't be mutable!\"\n if mutable_default_args.match(logical_line):\n yield (0, msg)\n\n\ndef check_explicit_underscore_import(logical_line, filename):\n \"\"\"Check for explicit import of the _ function\n\n We need to ensure that any files that are using the _() function\n to translate logs are explicitly importing the _ function. We\n can't trust unit test to catch whether the import has been\n added so we need to check for it here.\n \"\"\"\n\n # Build a list of the files that have _ imported. No further\n # checking needed once it is found.\n if filename in UNDERSCORE_IMPORT_FILES:\n pass\n elif (underscore_import_check.match(logical_line) or\n custom_underscore_check.match(logical_line)):\n UNDERSCORE_IMPORT_FILES.append(filename)\n elif (translated_log.match(logical_line) or\n string_translation.match(logical_line)):\n yield(0, \"N323: Found use of _() without explicit import of _ !\")\n\n\ndef use_jsonutils(logical_line, filename):\n # the code below that path is not meant to be executed from neutron\n # tree where jsonutils module is present, so don't enforce its usage\n # for this subdirectory\n if \"plugins/xenserver\" in filename:\n return\n\n # tools are OK to use the standard json module\n if \"/tools/\" in filename:\n return\n\n msg = \"N324: jsonutils.%(fun)s must be used instead of json.%(fun)s\"\n\n if \"json.\" in logical_line:\n json_funcs = ['dumps(', 'dump(', 'loads(', 'load(']", "answers": [" for f in json_funcs:"], "length": 1555, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "f860fa7b-7d74-46e5-878f-562db4d50053", "reasoning": "The function use_jsonutils is checking for usage of the standard json module. After detecting \"json.\" in the line, it defines a list of json functions to look for. The next logical step is to iterate over that list to check each function in the line, so the next line should start a for-loop over json_funcs.", "reasoning_model_answer": "for fun in json_funcs:", "assistant_with_reasoning": "\nThe function use_jsonutils is checking for usage of the standard json module. After detecting \"json.\" in the line, it defines a list of json functions to look for. The next logical step is to iterate over that list to check each function in the line, so the next line should start a for-loop over json_funcs.\n\nfor fun in json_funcs:", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.356, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 14435, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "for fun in json_funcs:", "score": 0.8, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/*\n * Licensed to Elasticsearch under one or more contributor\n * license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright\n * ownership. Elasticsearch licenses this file to you under\n * the Apache License, Version 2.0 (the \"License\"); you may\n * not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\npackage org.elasticsearch.action.termvectors;\n\nimport com.google.common.collect.Maps;\nimport com.google.common.collect.Sets;\nimport org.elasticsearch.ElasticsearchException;\nimport org.elasticsearch.ElasticsearchParseException;\nimport org.elasticsearch.action.ActionRequestValidationException;\nimport org.elasticsearch.action.DocumentRequest;\nimport org.elasticsearch.action.ValidateActions;\nimport org.elasticsearch.action.get.MultiGetRequest;\nimport org.elasticsearch.action.support.single.shard.SingleShardOperationRequest;\nimport org.elasticsearch.common.bytes.BytesReference;\nimport org.elasticsearch.common.io.stream.StreamInput;\nimport org.elasticsearch.common.io.stream.StreamOutput;\nimport org.elasticsearch.common.lucene.uid.Versions;\nimport org.elasticsearch.common.xcontent.XContentBuilder;\nimport org.elasticsearch.common.xcontent.XContentParser;\nimport org.elasticsearch.index.VersionType;\n\nimport java.io.IOException;\nimport java.util.*;\nimport java.util.concurrent.atomic.AtomicInteger;\n\nimport static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;\n\n/**\n * Request returning the term vector (doc frequency, positions, offsets) for a\n * document.\n *

    \n * Note, the {@link #index()}, {@link #type(String)} and {@link #id(String)} are\n * required.\n */\npublic class TermVectorsRequest extends SingleShardOperationRequest implements DocumentRequest {\n\n private String type;\n\n private String id;\n\n private BytesReference doc;\n\n private String routing;\n\n private VersionType versionType = VersionType.INTERNAL;\n\n private long version = Versions.MATCH_ANY;\n\n protected String preference;\n\n private static final AtomicInteger randomInt = new AtomicInteger(0);\n\n // TODO: change to String[]\n private Set selectedFields;\n\n Boolean realtime;\n\n private Map perFieldAnalyzer;\n\n private EnumSet flagsEnum = EnumSet.of(Flag.Positions, Flag.Offsets, Flag.Payloads,\n Flag.FieldStatistics);\n\n long startTime;\n\n public TermVectorsRequest() {\n }\n\n /**\n * Constructs a new term vector request for a document that will be fetch\n * from the provided index. Use {@link #type(String)} and\n * {@link #id(String)} to specify the document to load.\n */\n public TermVectorsRequest(String index, String type, String id) {\n super(index);\n this.id = id;\n this.type = type;\n }\n\n /**\n * Constructs a new term vector request for a document that will be fetch\n * from the provided index. Use {@link #type(String)} and\n * {@link #id(String)} to specify the document to load.\n */\n public TermVectorsRequest(TermVectorsRequest other) {\n super(other.index());\n this.id = other.id();\n this.type = other.type();\n if (this.doc != null) {\n this.doc = other.doc().copyBytesArray();\n }\n this.flagsEnum = other.getFlags().clone();\n this.preference = other.preference();\n this.routing = other.routing();\n if (other.selectedFields != null) {\n this.selectedFields = new HashSet<>(other.selectedFields);\n }\n if (other.perFieldAnalyzer != null) {\n this.perFieldAnalyzer = new HashMap<>(other.perFieldAnalyzer);\n }\n this.realtime = other.realtime();\n this.version = other.version();\n this.versionType = VersionType.fromValue(other.versionType().getValue());\n this.startTime = other.startTime();\n }\n\n public TermVectorsRequest(MultiGetRequest.Item item) {\n super(item.index());\n this.id = item.id();\n this.type = item.type();\n this.selectedFields(item.fields());\n this.routing(item.routing());\n }\n\n public EnumSet getFlags() {\n return flagsEnum;\n }\n\n /**\n * Sets the type of document to get the term vector for.\n */\n public TermVectorsRequest type(String type) {\n this.type = type;\n return this;\n }\n\n /**\n * Returns the type of document to get the term vector for.\n */\n @Override\n public String type() {\n return type;\n }\n\n /**\n * Returns the id of document the term vector is requested for.\n */\n @Override\n public String id() {\n return id;\n }\n \n /**\n * Sets the id of document the term vector is requested for.\n */\n public TermVectorsRequest id(String id) {\n this.id = id;\n return this;\n }\n\n /**\n * Returns the artificial document from which term vectors are requested for.\n */\n public BytesReference doc() {\n return doc;\n }\n\n /**\n * Sets an artificial document from which term vectors are requested for.\n */\n public TermVectorsRequest doc(XContentBuilder documentBuilder) {\n return this.doc(documentBuilder.bytes(), true);\n }\n\n /**\n * Sets an artificial document from which term vectors are requested for.\n */\n public TermVectorsRequest doc(BytesReference doc, boolean generateRandomId) {\n // assign a random id to this artificial document, for routing\n if (generateRandomId) {\n this.id(String.valueOf(randomInt.getAndAdd(1)));\n }\n this.doc = doc;\n return this;\n }\n\n /**\n * @return The routing for this request.\n */\n @Override\n public String routing() {\n return routing;\n }\n\n @Override\n public TermVectorsRequest routing(String routing) {\n this.routing = routing;\n return this;\n }\n\n /**\n * Sets the parent id of this document. Will simply set the routing to this\n * value, as it is only used for routing with delete requests.\n */\n public TermVectorsRequest parent(String parent) {\n if (routing == null) {\n routing = parent;\n }\n return this;\n }\n\n public String preference() {\n return this.preference;\n }\n\n /**\n * Sets the preference to execute the search. Defaults to randomize across\n * shards. Can be set to _local to prefer local shards,\n * _primary to execute only on primary shards, or a custom value,\n * which guarantees that the same order will be used across different\n * requests.\n */\n public TermVectorsRequest preference(String preference) {\n this.preference = preference;\n return this;\n }\n\n /**\n * Return the start and stop offsets for each term if they were stored or\n * skip offsets.\n */\n public TermVectorsRequest offsets(boolean offsets) {\n setFlag(Flag.Offsets, offsets);\n return this;\n }\n\n /**\n * @return true if term offsets should be returned. Otherwise\n * false\n */\n public boolean offsets() {\n return flagsEnum.contains(Flag.Offsets);\n }\n\n /**\n * Return the positions for each term if stored or skip.\n */\n public TermVectorsRequest positions(boolean positions) {\n setFlag(Flag.Positions, positions);\n return this;\n }\n\n /**\n * @return Returns if the positions for each term should be returned if\n * stored or skip.\n */\n public boolean positions() {\n return flagsEnum.contains(Flag.Positions);\n }\n\n /**\n * @return true if term payloads should be returned. Otherwise\n * false\n */\n public boolean payloads() {\n return flagsEnum.contains(Flag.Payloads);\n }\n\n /**\n * Return the payloads for each term or skip.\n */\n public TermVectorsRequest payloads(boolean payloads) {\n setFlag(Flag.Payloads, payloads);\n return this;\n }\n\n /**\n * @return true if term statistics should be returned.\n * Otherwise false\n */\n public boolean termStatistics() {\n return flagsEnum.contains(Flag.TermStatistics);\n }\n\n /**\n * Return the term statistics for each term in the shard or skip.\n */\n public TermVectorsRequest termStatistics(boolean termStatistics) {\n setFlag(Flag.TermStatistics, termStatistics);\n return this;\n }\n\n /**\n * @return true if field statistics should be returned.\n * Otherwise false\n */\n public boolean fieldStatistics() {\n return flagsEnum.contains(Flag.FieldStatistics);\n }\n\n /**\n * Return the field statistics for each term in the shard or skip.\n */\n public TermVectorsRequest fieldStatistics(boolean fieldStatistics) {\n setFlag(Flag.FieldStatistics, fieldStatistics);\n return this;\n }\n\n /**\n * @return true if distributed frequencies should be returned. Otherwise\n * false\n */\n public boolean dfs() {\n return flagsEnum.contains(Flag.Dfs);\n }\n\n /**\n * Use distributed frequencies instead of shard statistics.\n */\n public TermVectorsRequest dfs(boolean dfs) {\n setFlag(Flag.Dfs, dfs);\n return this;\n }\n\n /**\n * Return only term vectors for special selected fields. Returns for term\n * vectors for all fields if selectedFields == null\n */\n public Set selectedFields() {\n return selectedFields;\n }\n\n /**\n * Return only term vectors for special selected fields. Returns the term\n * vectors for all fields if selectedFields == null\n */\n public TermVectorsRequest selectedFields(String... fields) {\n selectedFields = fields != null && fields.length != 0 ? Sets.newHashSet(fields) : null;\n return this;\n }\n\n /**\n * Return whether term vectors should be generated real-time (default to true).\n */\n public boolean realtime() {\n return this.realtime == null ? true : this.realtime;\n }\n\n /**\n * Choose whether term vectors be generated real-time.\n */\n public TermVectorsRequest realtime(Boolean realtime) {\n this.realtime = realtime;\n return this;\n }\n\n /**\n * Return the overridden analyzers at each field.\n */\n public Map perFieldAnalyzer() {\n return perFieldAnalyzer;\n }\n\n /**\n * Override the analyzer used at each field when generating term vectors.\n */\n public TermVectorsRequest perFieldAnalyzer(Map perFieldAnalyzer) {\n this.perFieldAnalyzer = perFieldAnalyzer != null && perFieldAnalyzer.size() != 0 ? Maps.newHashMap(perFieldAnalyzer) : null;\n return this;\n }\n\n public long version() {\n return version;\n }\n\n public TermVectorsRequest version(long version) {\n this.version = version;\n return this;\n }\n\n public VersionType versionType() {\n return versionType;\n }\n\n public TermVectorsRequest versionType(VersionType versionType) {\n this.versionType = versionType;\n return this;\n }\n\n private void setFlag(Flag flag, boolean set) {\n if (set && !flagsEnum.contains(flag)) {\n flagsEnum.add(flag);\n } else if (!set) {\n flagsEnum.remove(flag);\n assert (!flagsEnum.contains(flag));\n }\n }\n\n public long startTime() {\n return this.startTime;\n }\n\n @Override\n public ActionRequestValidationException validate() {\n ActionRequestValidationException validationException = super.validate();\n if (type == null) {\n validationException = ValidateActions.addValidationError(\"type is missing\", validationException);\n }\n if (id == null && doc == null) {\n validationException = ValidateActions.addValidationError(\"id or doc is missing\", validationException);\n }\n return validationException;\n }\n\n public static TermVectorsRequest readTermVectorsRequest(StreamInput in) throws IOException {\n TermVectorsRequest termVectorsRequest = new TermVectorsRequest();\n termVectorsRequest.readFrom(in);\n return termVectorsRequest;\n }\n\n\n @Override\n public void readFrom(StreamInput in) throws IOException {\n super.readFrom(in);\n type = in.readString();\n id = in.readString();\n\n if (in.readBoolean()) {\n doc = in.readBytesReference();\n }\n routing = in.readOptionalString();\n preference = in.readOptionalString();\n long flags = in.readVLong();\n\n flagsEnum.clear();\n for (Flag flag : Flag.values()) {", "answers": [" if ((flags & (1 << flag.ordinal())) != 0) {"], "length": 1380, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "76c8c21f-a8c5-46ac-9b3d-db131c9bcadd", "reasoning": "In the readFrom method, after reading a long 'flags' that encodes which Flag enum values are set, the code clears the existing flagsEnum set and iterates over all Flag values. Inside the loop it must test whether each flag's bit is set in the 'flags' bitmask and, if so, add the flag to flagsEnum. The typical pattern is to use a bitwise AND with a shifted 1 based on the flag's ordinal. Therefore the next line should be the conditional that checks the bit: if ((flags & (1L << flag.ordinal())) != 0) {", "reasoning_model_answer": "if ((flags & (1L << flag.ordinal())) != 0) {", "assistant_with_reasoning": "\nIn the readFrom method, after reading a long 'flags' that encodes which Flag enum values are set, the code clears the existing flagsEnum set and iterates over all Flag values. Inside the loop it must test whether each flag's bit is set in the 'flags' bitmask and, if so, add the flag to flagsEnum. The typical pattern is to use a bitwise AND with a shifted 1 based on the flag's ordinal. Therefore the next line should be the conditional that checks the bit: if ((flags & (1L << flag.ordinal())) != 0) {\n\nif ((flags & (1L << flag.ordinal())) != 0) {", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.202, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 13286, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "if ((flags & (1L << flag.ordinal())) != 0) {", "score": 0.87, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "// SPDX-License-Identifier: BSD-3-Clause\npackage org.xbill.DNS.dnssec;\n\nimport static org.junit.jupiter.api.Assertions.assertEquals;\nimport static org.mockito.Mockito.when;\n\nimport java.io.File;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.security.Security;\nimport java.text.ParseException;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Map.Entry;\nimport java.util.Properties;\nimport org.bouncycastle.jce.provider.BouncyCastleProvider;\nimport org.junit.jupiter.api.Disabled;\nimport org.junit.jupiter.api.Test;\nimport org.xbill.DNS.CNAMERecord;\nimport org.xbill.DNS.DNAMERecord;\nimport org.xbill.DNS.DNSSEC;\nimport org.xbill.DNS.Flags;\nimport org.xbill.DNS.Message;\nimport org.xbill.DNS.Name;\nimport org.xbill.DNS.RRSIGRecord;\nimport org.xbill.DNS.RRset;\nimport org.xbill.DNS.Rcode;\nimport org.xbill.DNS.Record;\nimport org.xbill.DNS.Section;\nimport org.xbill.DNS.Type;\n\nclass UnboundTests extends TestBase {\n void runUnboundTest() throws ParseException, IOException {\n InputStream data = getClass().getResourceAsStream(\"/unbound/\" + testName + \".rpl\");\n RplParser p = new RplParser(data);\n Rpl rpl = p.parse();\n Properties config = new Properties();\n if (rpl.nsec3iterations != null) {\n for (Entry e : rpl.nsec3iterations.entrySet()) {\n config.put(\"dnsjava.dnssec.nsec3.iterations.\" + e.getKey(), e.getValue());\n }\n }\n\n if (rpl.digestPreference != null) {\n config.put(ValUtils.DIGEST_PREFERENCE, rpl.digestPreference);\n }\n\n config.put(ValUtils.DIGEST_HARDEN_DOWNGRADE, Boolean.toString(rpl.hardenAlgoDowngrade));\n\n if (rpl.enableSha1) {\n config.put(ValUtils.DIGEST_ENABLED + \".\" + DNSSEC.Digest.SHA1, Boolean.TRUE.toString());\n }\n\n if (rpl.enableDsa || rpl.enableSha1) {\n config.put(ValUtils.ALGORITHM_ENABLED + \".\" + DNSSEC.Algorithm.DSA, Boolean.TRUE.toString());\n config.put(\n ValUtils.ALGORITHM_ENABLED + \".\" + DNSSEC.Algorithm.DSA_NSEC3_SHA1,\n Boolean.TRUE.toString());\n }\n\n if (rpl.loadBouncyCastle) {\n Security.addProvider(new BouncyCastleProvider());\n }\n\n for (Message m : rpl.replays) {\n add(m);\n }\n\n // merge xNAME queries into one\n List copy = new ArrayList<>(rpl.replays.size());\n copy.addAll(rpl.replays);\n List copiedTargets = new ArrayList<>(5);\n for (Message m : copy) {\n Name target = null;\n for (RRset s : m.getSectionRRsets(Section.ANSWER)) {\n if (s.getType() == Type.CNAME) {\n target = ((CNAMERecord) s.first()).getTarget();\n } else if (s.getType() == Type.DNAME) {\n target = ((DNAMERecord) s.first()).getTarget();\n }\n\n while (target != null) {\n Message a = get(target, m.getQuestion().getType());\n if (a == null) {\n a = get(target, Type.CNAME);\n }\n\n if (a == null) {\n a = get(target, Type.DNAME);\n }\n\n if (a != null) {\n target = add(m, a);\n if (copiedTargets.contains(target)) {\n break;\n }\n\n copiedTargets.add(target);\n rpl.replays.remove(a);\n } else {\n target = null;\n }\n }\n }\n }\n\n // promote any DS records in auth. sections to real queries\n copy = new ArrayList<>(rpl.replays.size());\n copy.addAll(rpl.replays);\n for (Message m : copy) {\n for (RRset s : m.getSectionRRsets(Section.AUTHORITY)) {\n if (s.getType() == Type.DS) {\n Message ds = new Message();\n ds.addRecord(Record.newRecord(s.getName(), s.getType(), s.getDClass()), Section.QUESTION);\n for (Record rr : s.rrs()) {\n ds.addRecord(rr, Section.ANSWER);\n }\n\n for (RRSIGRecord sig : s.sigs()) {\n ds.addRecord(sig, Section.ANSWER);\n }\n\n rpl.replays.add(ds);\n }\n }\n }\n\n clear();\n for (Message m : rpl.replays) {\n add(m);\n }\n\n if (rpl.date != null) {\n try {\n when(resolverClock.instant()).thenReturn(rpl.date);\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }\n\n if (rpl.trustAnchors != null) {\n resolver.getTrustAnchors().clear();\n for (SRRset rrset : rpl.trustAnchors) {\n resolver.getTrustAnchors().store(rrset);\n }\n }\n\n resolver.init(config);\n\n for (Check c : rpl.checks.values()) {\n Message s = resolver.send(c.query);\n Security.removeProvider(BouncyCastleProvider.PROVIDER_NAME);\n assertEquals(\n c.response.getHeader().getFlag(Flags.AD),\n s.getHeader().getFlag(Flags.AD),\n \"AD Flag must match\");\n assertEquals(\n Rcode.string(c.response.getRcode()), Rcode.string(s.getRcode()), \"RCode must match\");\n }\n }\n\n private Name add(Message target, Message source) {\n Name next = null;\n target.getHeader().setRcode(source.getRcode());\n for (Record r : source.getSection(Section.ANSWER)) {\n target.addRecord(r, Section.ANSWER);\n if (r.getType() == Type.CNAME) {\n next = ((CNAMERecord) r).getTarget();\n } else if (r.getType() == Type.DNAME) {\n next = ((DNAMERecord) r).getTarget();\n }\n }\n\n for (Record r : source.getSection(Section.AUTHORITY)) {\n if (r.getType() != Type.NS) {\n target.addRecord(r, Section.AUTHORITY);\n }\n }\n\n return next;\n }\n\n static void xmain(String[] xargs) {\n Map ignored =\n new HashMap() {\n {\n put(\"val_faildnskey_ok.rpl\", \"tests an unbound specific config option\");\n put(\"val_nsec3_nods_negcache.rpl\", \"we don't do negative caching\");\n put(\"val_unsecds_negcache.rpl\", \"we don't do negative caching\");\n put(\"val_negcache_dssoa.rpl\", \"we don't do negative caching\");\n put(\"val_negcache_nodata.rpl\", \"aggressive NSEC is not supported\");\n put(\"val_negcache_nxdomain.rpl\", \"aggressive NSEC is not supported\");\n put(\"val_nsec3_b3_optout_negcache.rpl\", \"we don't do negative caching\");\n put(\"val_dsnsec.rpl\", \"we don't do negative caching\");\n put(\"val_refer_unsignadd.rpl\", \"we don't do negative caching\");\n put(\"val_referglue.rpl\", \"we don't do negative caching\");\n put(\n \"val_noadwhennodo.rpl\",\n \"irrelevant - if we wouldn't want AD, we wouldn't be using this stuff\");\n put(\"val_fwdds.rpl\", \"irrelevant, we're not a recursive resolver\");\n put(\"val_referd.rpl\", \"NSEC records missing for validation, tests caching stuff\");\n put(\"val_stubds.rpl\", \"tests unbound specific config (stub zones)\");\n put(\"val_cnametonsec.rpl\", \"incomplete CNAME answer\");\n put(\"val_cnametooptin.rpl\", \"incomplete CNAME answer\");\n put(\"val_cnametoinsecure.rpl\", \"incomplete CNAME answer\");\n put(\"val_nsec3_optout_cache.rpl\", \"more cache stuff\");\n put(\"val_unsecds_qtypeds.rpl\", \"tests the iterative resolver\");\n put(\"val_anchor_nx.rpl\", \"tests caching of NX from a parent resolver\");\n put(\"val_anchor_nx_nosig.rpl\", \"tests caching of NX from a parent resolver\");\n put(\"val_negcache_nta.rpl\", \"tests unbound option domain-insecure, not available here\");\n }\n };\n\n for (String f : new File(\"./src/test/resources/unbound\").list()) {\n String comment = ignored.get(f);\n if (comment != null) {\n System.out.println(\" @Disabled(\\\"\" + comment + \"\\\")\");\n }\n\n System.out.println(\" @Test\");\n System.out.println(\n \" void \" + f.split(\"\\\\.\")[0] + \"() throws ParseException, IOException {\");\n System.out.println(\" runUnboundTest();\");\n System.out.println(\" }\");\n System.out.println();\n }\n }\n\n @Test\n void val_adbit() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_adcopy() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Disabled(\"tests caching of NX from a parent resolver\")\n @Test\n void val_anchor_nx() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Disabled(\"tests caching of NX from a parent resolver\")\n @Test\n void val_anchor_nx_nosig() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_ans_dsent() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_ans_nx() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_any() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_any_cname() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_any_dname() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_cnameinsectopos() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_cnamenx_dblnsec() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_cnamenx_rcodenx() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_cnameqtype() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_cnametocloser() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_cnametocloser_nosig() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_cnametocnamewctoposwc() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_cnametodname() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_cnametodnametocnametopos() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Disabled(\"incomplete CNAME answer\")\n @Test\n void val_cnametoinsecure() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_cnametonodata() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_cnametonodata_nonsec() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Disabled(\"incomplete CNAME answer\")\n @Test\n void val_cnametonsec() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_cnametonx() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Disabled(\"incomplete CNAME answer\")\n @Test\n void val_cnametooptin() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_cnametooptout() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_cnametopos() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_cnametoposnowc() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_cnametoposwc() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_cnamewctonodata() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_cnamewctonx() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_cnamewctoposwc() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_cname_loop1() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_cname_loop2() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_cname_loop3() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_dnametoolong() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_dnametopos() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_dnametoposwc() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_dnamewc() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Disabled(\"we don't do negative caching\")\n @Test\n void val_dsnsec() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_ds_afterprime() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_ds_cname() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_ds_cnamesub() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_ds_cnamesubbogus() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_ds_gost() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_ds_gost_downgrade() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_ds_sha2() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_ds_sha2_downgrade() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_ds_sha2_downgrade_override() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_ds_sha2_lenient() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_entds() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_faildnskey() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Disabled(\"tests an unbound specific config option\")\n @Test\n void val_faildnskey_ok() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Disabled(\"irrelevant, we're not a recursive resolver\")\n @Test\n void val_fwdds() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_keyprefetch() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_keyprefetch_verify() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_mal_wc() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_negcache_ds() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Disabled(\"we don't do negative caching\")\n @Test\n void val_negcache_dssoa() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Disabled(\"aggressive NSEC is not supported\")\n @Test\n void val_negcache_nodata() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Disabled(\"tests unbound option domain-insecure, not available here\")\n @Test\n void val_negcache_nta() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Disabled(\"aggressive NSEC is not supported\")\n @Test\n void val_negcache_nxdomain() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Disabled(\"irrelevant - if we wouldn't want AD, we wouldn't be using this stuff\")\n @Test\n void val_noadwhennodo() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_nodata() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_nodatawc() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_nodatawc_badce() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_nodatawc_nodeny() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_nodatawc_one() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_nodatawc_wcns() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_nodatawc_wrongdeleg() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_nodata_ent() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_nodata_entnx() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_nodata_entwc() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_nodata_failsig() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_nodata_failwc() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_nodata_hasdata() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_nodata_zonecut() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_nokeyprime() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_nsec3_b1_nameerror() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_nsec3_b1_nameerror_noce() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_nsec3_b1_nameerror_nonc() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_nsec3_b1_nameerror_nowc() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_nsec3_b21_nodataent() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_nsec3_b21_nodataent_wr() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_nsec3_b2_nodata() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_nsec3_b2_nodata_nons() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_nsec3_b3_optout() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Disabled(\"we don't do negative caching\")\n @Test\n void val_nsec3_b3_optout_negcache() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_nsec3_b3_optout_noce() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_nsec3_b3_optout_nonc() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_nsec3_b4_wild() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_nsec3_b4_wild_wr() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_nsec3_b5_wcnodata() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_nsec3_b5_wcnodata_noce() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_nsec3_b5_wcnodata_nonc() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_nsec3_b5_wcnodata_nowc() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_nsec3_cnametocnamewctoposwc() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_nsec3_cname_ds() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_nsec3_cname_par() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_nsec3_cname_sub() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_nsec3_entnodata_optout() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_nsec3_entnodata_optout_badopt() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_nsec3_entnodata_optout_match() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_nsec3_iter_high() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_nsec3_nodatawccname() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_nsec3_nods() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_nsec3_nods_badopt() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_nsec3_nods_badsig() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Disabled(\"we don't do negative caching\")", "answers": [" @Test"], "length": 1731, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "409a3d0e-7e7f-4a01-b55e-505ce79fd1bf", "reasoning": "The code ends with a @Disabled annotation, which in this file is always followed by an @Test annotation and a method definition. Following the established pattern, the next line should be the @Test annotation.", "reasoning_model_answer": "@Test", "assistant_with_reasoning": "\nThe code ends with a @Disabled annotation, which in this file is always followed by an @Test annotation and a method definition. Following the established pattern, the next line should be the @Test annotation.\n\n@Test", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 2.838, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 19502, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "@Test", "score": 0.83, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "# -*- coding: utf-8 -*-\n#\n# Copyright 2012-2015 Spotify AB\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\n''' Parameters are one of the core concepts of Luigi.\nAll Parameters sit on :class:`~luigi.task.Task` classes.\nSee :ref:`Parameter` for more info on how to define parameters.\n'''\n\nimport abc\nimport datetime\nimport warnings\ntry:\n from ConfigParser import NoOptionError, NoSectionError\nexcept ImportError:\n from configparser import NoOptionError, NoSectionError\n\nfrom luigi import task_register\nfrom luigi import six\n\nfrom luigi import configuration\nfrom luigi.deprecate_kwarg import deprecate_kwarg\nfrom datetime import timedelta\n\n_no_value = object()\n\n\nclass ParameterException(Exception):\n \"\"\"\n Base exception.\n \"\"\"\n pass\n\n\nclass MissingParameterException(ParameterException):\n \"\"\"\n Exception signifying that there was a missing Parameter.\n \"\"\"\n pass\n\n\nclass UnknownParameterException(ParameterException):\n \"\"\"\n Exception signifying that an unknown Parameter was supplied.\n \"\"\"\n pass\n\n\nclass DuplicateParameterException(ParameterException):\n \"\"\"\n Exception signifying that a Parameter was specified multiple times.\n \"\"\"\n pass\n\n\nclass UnknownConfigException(ParameterException):\n \"\"\"\n Exception signifying that the ``config_path`` for the Parameter could not be found.\n \"\"\"\n pass\n\n\nclass Parameter(object):\n \"\"\"\n An untyped Parameter\n\n Parameters are objects set on the Task class level to make it possible to parameterize tasks.\n For instance:\n\n class MyTask(luigi.Task):\n foo = luigi.Parameter()\n\n This makes it possible to instantiate multiple tasks, eg ``MyTask(foo='bar')`` and\n ``MyTask(foo='baz')``. The task will then have the ``foo`` attribute set appropriately.\n\n There are subclasses of ``Parameter`` that define what type the parameter has. This is not\n enforced within Python, but are used for command line interaction.\n\n When a task is instantiated, it will first use any argument as the value of the parameter, eg.\n if you instantiate a = TaskA(x=44) then a.x == 44. If this does not exist, it will use the value\n of the Parameter object, which is defined on a class level. This will be resolved in this\n order of falling priority:\n\n * Any value provided on the command line on the class level (eg. ``--TaskA-param xyz``)\n * Any value provided via config (using the ``config_path`` argument)\n * Any default value set using the ``default`` flag.\n \"\"\"\n counter = 0\n \"\"\"non-atomically increasing counter used for ordering parameters.\"\"\"\n\n @deprecate_kwarg('is_boolean', 'is_bool', False)\n def __init__(self, default=_no_value, is_boolean=False, is_global=False, significant=True, description=None,\n config_path=None, positional=True):\n \"\"\"\n :param default: the default value for this parameter. This should match the type of the\n Parameter, i.e. ``datetime.date`` for ``DateParameter`` or ``int`` for\n ``IntParameter``. By default, no default is stored and\n the value must be specified at runtime.\n :param bool is_bool: specify ``True`` if the parameter is a bool value. Default:\n ``False``. Bool's have an implicit default value of ``False``.\n :param bool significant: specify ``False`` if the parameter should not be treated as part of\n the unique identifier for a Task. An insignificant Parameter might\n also be used to specify a password or other sensitive information\n that should not be made public via the scheduler. Default:\n ``True``.\n :param str description: A human-readable string describing the purpose of this Parameter.\n For command-line invocations, this will be used as the `help` string\n shown to users. Default: ``None``.\n :param dict config_path: a dictionary with entries ``section`` and ``name``\n specifying a config file entry from which to read the\n default value for this parameter. DEPRECATED.\n Default: ``None``.\n :param bool positional: If true, you can set the argument as a\n positional argument. Generally we recommend ``positional=False``\n as positional arguments become very tricky when\n you have inheritance and whatnot.\n \"\"\"\n # The default default is no default\n self.__default = default\n self.__global = _no_value\n\n self.is_bool = is_boolean # Only BoolParameter should ever use this. TODO(erikbern): should we raise some kind of exception?\n if is_global:\n warnings.warn(\"is_global support is removed. Assuming positional=False\",\n DeprecationWarning,\n stacklevel=2)\n positional = False\n self.significant = significant # Whether different values for this parameter will differentiate otherwise equal tasks\n self.positional = positional\n\n self.description = description\n\n if config_path is not None and ('section' not in config_path or 'name' not in config_path):\n raise ParameterException('config_path must be a hash containing entries for section and name')\n self.__config = config_path\n\n self.counter = Parameter.counter # We need to keep track of this to get the order right (see Task class)\n Parameter.counter += 1\n\n def _get_value_from_config(self, section, name):\n \"\"\"Loads the default from the config. Returns _no_value if it doesn't exist\"\"\"\n\n conf = configuration.get_config()\n\n try:\n value = conf.get(section, name)\n except (NoSectionError, NoOptionError):\n return _no_value\n\n return self.parse(value)\n\n def _get_value(self, task_name, param_name):\n for value, warn in self._value_iterator(task_name, param_name):\n if value != _no_value:\n if warn:\n warnings.warn(warn, DeprecationWarning, stacklevel=2)\n return value\n return _no_value\n\n def _value_iterator(self, task_name, param_name):\n \"\"\"\n Yield the parameter values, with optional deprecation warning as second tuple value.\n\n The parameter value will be whatever non-_no_value that is yielded first.\n \"\"\"\n yield (self.__global, None)\n yield (self._get_value_from_config(task_name, param_name), None)\n yield (self._get_value_from_config(task_name, param_name.replace('_', '-')),\n 'Configuration [{}] {} (with dashes) should be avoided. Please use underscores.'.format(\n task_name, param_name))\n if self.__config:\n yield (self._get_value_from_config(self.__config['section'], self.__config['name']),\n 'The use of the configuration [{}] {} is deprecated. Please use [{}] {}'.format(\n self.__config['section'], self.__config['name'], task_name, param_name))\n yield (self.__default, None)\n\n def has_task_value(self, task_name, param_name):\n return self._get_value(task_name, param_name) != _no_value\n\n def task_value(self, task_name, param_name):\n value = self._get_value(task_name, param_name)\n if value == _no_value:\n raise MissingParameterException(\"No default specified\")\n else:\n return value\n\n def _set_global(self, value):\n \"\"\"\n Set the global value of this Parameter.\n\n :param value: the new global value.\n \"\"\"\n self.__global = value\n\n def _reset_global(self):\n self.__global = _no_value\n\n def parse(self, x):\n \"\"\"\n Parse an individual value from the input.\n\n The default implementation is an identify (it returns ``x``), but subclasses should override\n this method for specialized parsing. This method is called by :py:meth:`parse_from_input`\n if ``x`` exists.\n\n :param str x: the value to parse.\n :return: the parsed value.\n \"\"\"\n return x # default impl\n\n def serialize(self, x): # opposite of parse\n \"\"\"\n Opposite of :py:meth:`parse`.\n\n Converts the value ``x`` to a string.\n\n :param x: the value to serialize.\n \"\"\"\n return str(x)\n\n @classmethod\n def next_in_enumeration(_cls, _value):\n \"\"\"\n If your Parameter type has an enumerable ordering of values. You can\n choose to override this method. This method is used by the\n :py:mod:`luigi.execution_summary` module for pretty printing\n purposes. Enabling it to pretty print tasks like ``MyTask(num=1),\n MyTask(num=2), MyTask(num=3)`` to ``MyTask(num=1..3)``.\n\n :param value: The value\n :return: The next value, like \"value + 1\". Or ``None`` if there's no enumerable ordering.\n \"\"\"\n return None\n\n def parse_from_input(self, param_name, x, task_name=None):\n \"\"\"\n Parses the parameter value from input ``x``, handling defaults.\n\n :param param_name: the name of the parameter. This is used for the message in\n ``MissingParameterException``.\n :param x: the input value to parse.\n :raises MissingParameterException: if x is false-y and no default is specified.\n \"\"\"\n if not x:\n if self.has_task_value(param_name=param_name, task_name=task_name):\n return self.task_value(param_name=param_name, task_name=task_name)\n elif self.is_bool:\n return False\n else:\n raise MissingParameterException(\"No value for '%s' (%s) submitted and no default value has been assigned.\" %\n (param_name, \"--\" + param_name.replace('_', '-')))\n else:\n return self.parse(x)\n\n def _parser_dest(self, param_name, task_name, glob=False, is_without_section=False):\n if is_without_section:\n if glob:\n return param_name\n else:\n return None\n else:\n if glob:\n return task_name + '_' + param_name\n else:\n return param_name\n\n def add_to_cmdline_parser(self, parser, param_name, task_name, glob=False, is_without_section=False):\n \"\"\"\n Internally used from interface.py, this method will probably be removed.\n \"\"\"\n dest = self._parser_dest(param_name, task_name, glob, is_without_section=is_without_section)\n if not dest:\n return\n flag = '--' + dest.replace('_', '-')\n\n description = []\n description.append('%s.%s' % (task_name, param_name))\n if glob:\n description.append('for all instances of class %s' % task_name)\n elif self.description:\n description.append(self.description)\n if self.has_task_value(param_name=param_name, task_name=task_name):\n value = self.task_value(param_name=param_name, task_name=task_name)\n description.append(\" [default: %s]\" % (value,))\n\n if self.is_bool:\n action = \"store_true\"\n else:\n action = \"store\"\n\n parser.add_argument(flag,\n help=' '.join(description),\n action=action,\n dest=dest)\n\n def parse_from_args(self, param_name, task_name, args, params):\n \"\"\"\n Internally used from interface.py, this method will probably be removed.\n \"\"\"\n # Note: modifies arguments\n dest = self._parser_dest(param_name, task_name, glob=False)\n if dest is not None:\n value = getattr(args, dest, None)\n params[param_name] = self.parse_from_input(param_name, value, task_name=task_name)\n\n def set_global_from_args(self, param_name, task_name, args, is_without_section=False):\n \"\"\"\n Internally used from interface.py, this method will probably be removed.\n \"\"\"\n # Note: side effects\n dest = self._parser_dest(param_name, task_name, glob=True, is_without_section=is_without_section)\n if dest is not None:\n value = getattr(args, dest, None)\n if value:\n self._set_global(self.parse_from_input(param_name, value, task_name=task_name))\n else: # either False (bools) or None (everything else)\n self._reset_global()\n\n\nclass DateParameterBase(Parameter):\n \"\"\"\n Base class Parameter for dates. Code reuse is made possible since all date\n parameters are serialized in the same way.\n \"\"\"\n @abc.abstractproperty\n def date_format(self):\n \"\"\"\n Override me with a :py:meth:`~datetime.date.strftime` string.\n \"\"\"\n pass\n\n @abc.abstractproperty\n def _timedelta(self):\n \"\"\"\n Either override me with a :py:class:`~datetime.timedelta` value or\n implement :py:meth:`~Parameter.next_in_enumeration` to return ``None``.\n \"\"\"\n pass\n\n def serialize(self, dt):\n \"\"\"\n Converts the date to a string using the :py:attr:`~DateParameterBase.date_format`.\n \"\"\"\n if dt is None:\n return str(dt)\n return dt.strftime(self.date_format)\n\n @classmethod\n def next_in_enumeration(cls, value):\n return value + cls._timedelta\n\n\nclass DateParameter(DateParameterBase):\n \"\"\"\n Parameter whose value is a :py:class:`~datetime.date`.\n\n A DateParameter is a Date string formatted ``YYYY-MM-DD``. For example, ``2013-07-10`` specifies\n July 10, 2013.\n \"\"\"\n\n date_format = '%Y-%m-%d'\n _timedelta = timedelta(days=1)\n\n def parse(self, s):\n \"\"\"\n Parses a date string formatted as ``YYYY-MM-DD``.\n \"\"\"\n return datetime.datetime.strptime(s, self.date_format).date()\n\n\nclass MonthParameter(DateParameter):\n \"\"\"\n Parameter whose value is a :py:class:`~datetime.date`, specified to the month\n (day of :py:class:`~datetime.date` is \"rounded\" to first of the month).\n\n A MonthParameter is a Date string formatted ``YYYY-MM``. For example, ``2013-07`` specifies\n July of 2013.\n \"\"\"\n\n date_format = '%Y-%m'\n\n @staticmethod\n def next_in_enumeration(_value):\n return None\n\n\nclass YearParameter(DateParameter):\n \"\"\"\n Parameter whose value is a :py:class:`~datetime.date`, specified to the year\n (day and month of :py:class:`~datetime.date` is \"rounded\" to first day of the year).\n\n A YearParameter is a Date string formatted ``YYYY``.\n \"\"\"\n\n date_format = '%Y'\n\n @staticmethod\n def next_in_enumeration(_value):\n return None\n\n\nclass DateHourParameter(DateParameterBase):\n \"\"\"\n Parameter whose value is a :py:class:`~datetime.datetime` specified to the hour.\n\n A DateHourParameter is a `ISO 8601 `_ formatted\n date and time specified to the hour. For example, ``2013-07-10T19`` specifies July 10, 2013 at\n 19:00.\n \"\"\"\n\n date_format = '%Y-%m-%dT%H' # ISO 8601 is to use 'T'\n\n def parse(self, s):\n \"\"\"\n Parses a string to a :py:class:`~datetime.datetime` using the format string ``%Y-%m-%dT%H``.\n \"\"\"\n return datetime.datetime.strptime(s, self.date_format)\n\n\nclass DateMinuteParameter(DateHourParameter):\n \"\"\"\n Parameter whose value is a :py:class:`~datetime.datetime` specified to the minute.\n\n A DateMinuteParameter is a `ISO 8601 `_ formatted\n date and time specified to the minute. For example, ``2013-07-10T1907`` specifies July 10, 2013 at\n 19:07.\n \"\"\"\n\n date_format = '%Y-%m-%dT%H%M'\n _timedelta = timedelta(minutes=1)\n deprecated_date_format = '%Y-%m-%dT%HH%M'\n\n def parse(self, s):\n try:\n value = datetime.datetime.strptime(s, self.deprecated_date_format)\n warnings.warn(\n 'Using \"H\" between hours and minutes is deprecated, omit it instead.',\n DeprecationWarning,\n stacklevel=2\n )\n return value", "answers": [" except ValueError:"], "length": 1729, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "9e2445b6-333e-469a-a409-15f42834ec39", "reasoning": "The parse method for DateMinuteParameter attempts to parse using a deprecated format inside a try block. After returning the parsed value, the typical pattern is to handle the failure case with an except clause that falls back to the correct format. Therefore, the next line after the broken \"return value\" line is the except clause: \"except ValueError:\".", "reasoning_model_answer": "except ValueError:", "assistant_with_reasoning": "\nThe parse method for DateMinuteParameter attempts to parse using a deprecated format inside a try block. After returning the parsed value, the typical pattern is to handle the failure case with an except clause that falls back to the correct format. Therefore, the next line after the broken \"return value\" line is the except clause: \"except ValueError:\".\n\nexcept ValueError:", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 5.403, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 16994, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "except ValueError:", "score": 0.82, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/*\n * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\"). You may not use this file except in compliance with\n * the License. A copy of the License is located at\n * \n * http://aws.amazon.com/apache2.0\n * \n * or in the \"license\" file accompanying this file. This file is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR\n * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions\n * and limitations under the License.\n */\npackage com.amazonaws.services.alexaforbusiness.model;\n\nimport java.io.Serializable;\nimport javax.annotation.Generated;\nimport com.amazonaws.protocol.StructuredPojo;\nimport com.amazonaws.protocol.ProtocolMarshaller;\n\n/**\n *

    \n * A device with attributes.\n *

    \n * \n * @see AWS API\n * Documentation\n */\n@Generated(\"com.amazonaws:aws-java-sdk-code-generator\")\npublic class Device implements Serializable, Cloneable, StructuredPojo {\n\n /**\n *

    \n * The ARN of a device.\n *

    \n */\n private String deviceArn;\n /**\n *

    \n * The serial number of a device.\n *

    \n */\n private String deviceSerialNumber;\n /**\n *

    \n * The type of a device.\n *

    \n */\n private String deviceType;\n /**\n *

    \n * The name of a device.\n *

    \n */\n private String deviceName;\n /**\n *

    \n * The software version of a device.\n *

    \n */\n private String softwareVersion;\n /**\n *

    \n * The MAC address of a device.\n *

    \n */\n private String macAddress;\n /**\n *

    \n * The room ARN of a device.\n *

    \n */\n private String roomArn;\n /**\n *

    \n * The status of a device. If the status is not READY, check the DeviceStatusInfo value for details.\n *

    \n */\n private String deviceStatus;\n /**\n *

    \n * Detailed information about a device's status.\n *

    \n */\n private DeviceStatusInfo deviceStatusInfo;\n /**\n *

    \n * Detailed information about a device's network profile.\n *

    \n */\n private DeviceNetworkProfileInfo networkProfileInfo;\n\n /**\n *

    \n * The ARN of a device.\n *

    \n * \n * @param deviceArn\n * The ARN of a device.\n */\n\n public void setDeviceArn(String deviceArn) {\n this.deviceArn = deviceArn;\n }\n\n /**\n *

    \n * The ARN of a device.\n *

    \n * \n * @return The ARN of a device.\n */\n\n public String getDeviceArn() {\n return this.deviceArn;\n }\n\n /**\n *

    \n * The ARN of a device.\n *

    \n * \n * @param deviceArn\n * The ARN of a device.\n * @return Returns a reference to this object so that method calls can be chained together.\n */\n\n public Device withDeviceArn(String deviceArn) {\n setDeviceArn(deviceArn);\n return this;\n }\n\n /**\n *

    \n * The serial number of a device.\n *

    \n * \n * @param deviceSerialNumber\n * The serial number of a device.\n */\n\n public void setDeviceSerialNumber(String deviceSerialNumber) {\n this.deviceSerialNumber = deviceSerialNumber;\n }\n\n /**\n *

    \n * The serial number of a device.\n *

    \n * \n * @return The serial number of a device.\n */\n\n public String getDeviceSerialNumber() {\n return this.deviceSerialNumber;\n }\n\n /**\n *

    \n * The serial number of a device.\n *

    \n * \n * @param deviceSerialNumber\n * The serial number of a device.\n * @return Returns a reference to this object so that method calls can be chained together.\n */\n\n public Device withDeviceSerialNumber(String deviceSerialNumber) {\n setDeviceSerialNumber(deviceSerialNumber);\n return this;\n }\n\n /**\n *

    \n * The type of a device.\n *

    \n * \n * @param deviceType\n * The type of a device.\n */\n\n public void setDeviceType(String deviceType) {\n this.deviceType = deviceType;\n }\n\n /**\n *

    \n * The type of a device.\n *

    \n * \n * @return The type of a device.\n */\n\n public String getDeviceType() {\n return this.deviceType;\n }\n\n /**\n *

    \n * The type of a device.\n *

    \n * \n * @param deviceType\n * The type of a device.\n * @return Returns a reference to this object so that method calls can be chained together.\n */\n\n public Device withDeviceType(String deviceType) {\n setDeviceType(deviceType);\n return this;\n }\n\n /**\n *

    \n * The name of a device.\n *

    \n * \n * @param deviceName\n * The name of a device.\n */\n\n public void setDeviceName(String deviceName) {\n this.deviceName = deviceName;\n }\n\n /**\n *

    \n * The name of a device.\n *

    \n * \n * @return The name of a device.\n */\n\n public String getDeviceName() {\n return this.deviceName;\n }\n\n /**\n *

    \n * The name of a device.\n *

    \n * \n * @param deviceName\n * The name of a device.\n * @return Returns a reference to this object so that method calls can be chained together.\n */\n\n public Device withDeviceName(String deviceName) {\n setDeviceName(deviceName);\n return this;\n }\n\n /**\n *

    \n * The software version of a device.\n *

    \n * \n * @param softwareVersion\n * The software version of a device.\n */\n\n public void setSoftwareVersion(String softwareVersion) {\n this.softwareVersion = softwareVersion;\n }\n\n /**\n *

    \n * The software version of a device.\n *

    \n * \n * @return The software version of a device.\n */\n\n public String getSoftwareVersion() {\n return this.softwareVersion;\n }\n\n /**\n *

    \n * The software version of a device.\n *

    \n * \n * @param softwareVersion\n * The software version of a device.\n * @return Returns a reference to this object so that method calls can be chained together.\n */\n\n public Device withSoftwareVersion(String softwareVersion) {\n setSoftwareVersion(softwareVersion);\n return this;\n }\n\n /**\n *

    \n * The MAC address of a device.\n *

    \n * \n * @param macAddress\n * The MAC address of a device.\n */\n\n public void setMacAddress(String macAddress) {\n this.macAddress = macAddress;\n }\n\n /**\n *

    \n * The MAC address of a device.\n *

    \n * \n * @return The MAC address of a device.\n */\n\n public String getMacAddress() {\n return this.macAddress;\n }\n\n /**\n *

    \n * The MAC address of a device.\n *

    \n * \n * @param macAddress\n * The MAC address of a device.\n * @return Returns a reference to this object so that method calls can be chained together.\n */\n\n public Device withMacAddress(String macAddress) {\n setMacAddress(macAddress);\n return this;\n }\n\n /**\n *

    \n * The room ARN of a device.\n *

    \n * \n * @param roomArn\n * The room ARN of a device.\n */\n\n public void setRoomArn(String roomArn) {\n this.roomArn = roomArn;\n }\n\n /**\n *

    \n * The room ARN of a device.\n *

    \n * \n * @return The room ARN of a device.\n */\n\n public String getRoomArn() {\n return this.roomArn;\n }\n\n /**\n *

    \n * The room ARN of a device.\n *

    \n * \n * @param roomArn\n * The room ARN of a device.\n * @return Returns a reference to this object so that method calls can be chained together.\n */\n\n public Device withRoomArn(String roomArn) {\n setRoomArn(roomArn);\n return this;\n }\n\n /**\n *

    \n * The status of a device. If the status is not READY, check the DeviceStatusInfo value for details.\n *

    \n * \n * @param deviceStatus\n * The status of a device. If the status is not READY, check the DeviceStatusInfo value for details.\n * @see DeviceStatus\n */\n\n public void setDeviceStatus(String deviceStatus) {\n this.deviceStatus = deviceStatus;\n }\n\n /**\n *

    \n * The status of a device. If the status is not READY, check the DeviceStatusInfo value for details.\n *

    \n * \n * @return The status of a device. If the status is not READY, check the DeviceStatusInfo value for details.\n * @see DeviceStatus\n */\n\n public String getDeviceStatus() {\n return this.deviceStatus;\n }\n\n /**\n *

    \n * The status of a device. If the status is not READY, check the DeviceStatusInfo value for details.\n *

    \n * \n * @param deviceStatus\n * The status of a device. If the status is not READY, check the DeviceStatusInfo value for details.\n * @return Returns a reference to this object so that method calls can be chained together.\n * @see DeviceStatus\n */\n\n public Device withDeviceStatus(String deviceStatus) {\n setDeviceStatus(deviceStatus);\n return this;\n }\n\n /**\n *

    \n * The status of a device. If the status is not READY, check the DeviceStatusInfo value for details.\n *

    \n * \n * @param deviceStatus\n * The status of a device. If the status is not READY, check the DeviceStatusInfo value for details.\n * @return Returns a reference to this object so that method calls can be chained together.\n * @see DeviceStatus\n */\n\n public Device withDeviceStatus(DeviceStatus deviceStatus) {\n this.deviceStatus = deviceStatus.toString();\n return this;\n }\n\n /**\n *

    \n * Detailed information about a device's status.\n *

    \n * \n * @param deviceStatusInfo\n * Detailed information about a device's status.\n */\n\n public void setDeviceStatusInfo(DeviceStatusInfo deviceStatusInfo) {\n this.deviceStatusInfo = deviceStatusInfo;\n }\n\n /**\n *

    \n * Detailed information about a device's status.\n *

    \n * \n * @return Detailed information about a device's status.\n */\n\n public DeviceStatusInfo getDeviceStatusInfo() {\n return this.deviceStatusInfo;\n }\n\n /**\n *

    \n * Detailed information about a device's status.\n *

    \n * \n * @param deviceStatusInfo\n * Detailed information about a device's status.\n * @return Returns a reference to this object so that method calls can be chained together.\n */\n\n public Device withDeviceStatusInfo(DeviceStatusInfo deviceStatusInfo) {\n setDeviceStatusInfo(deviceStatusInfo);\n return this;\n }\n\n /**\n *

    \n * Detailed information about a device's network profile.\n *

    \n * \n * @param networkProfileInfo\n * Detailed information about a device's network profile.\n */\n", "answers": [" public void setNetworkProfileInfo(DeviceNetworkProfileInfo networkProfileInfo) {"], "length": 1465, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "3ed83781-a485-4c4a-9a8a-27d43fefc5ab", "reasoning": "The code follows a consistent pattern for each field: a setter, a getter, and a with-method. After the Javadoc comment for the networkProfileInfo field, the next logical line is the beginning of its setter method declaration, matching the style of earlier setters.", "reasoning_model_answer": "public void setNetworkProfileInfo(DeviceNetworkProfileInfo networkProfileInfo) {", "assistant_with_reasoning": "\nThe code follows a consistent pattern for each field: a setter, a getter, and a with-method. After the Javadoc comment for the networkProfileInfo field, the next logical line is the beginning of its setter method declaration, matching the style of earlier setters.\n\npublic void setNetworkProfileInfo(DeviceNetworkProfileInfo networkProfileInfo) {", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 2.25, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 11255, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "public void setNetworkProfileInfo(DeviceNetworkProfileInfo networkProfileInfo) {", "score": 0.98, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Runtime.InteropServices;\nusing System.Threading;\n\nnamespace System.IO\n{\n /// Provides an implementation of FileSystem for Unix systems.\n internal sealed partial class UnixFileSystem : FileSystem\n {\n public override int MaxPath { get { return Interop.Sys.MaxPath; } }\n\n public override int MaxDirectoryPath { get { return Interop.Sys.MaxPath; } }\n\n public override FileStreamBase Open(string fullPath, FileMode mode, FileAccess access, FileShare share, int bufferSize, FileOptions options, FileStream parent)\n {\n return new UnixFileStream(fullPath, mode, access, share, bufferSize, options, parent);\n }\n\n public override void CopyFile(string sourceFullPath, string destFullPath, bool overwrite)\n {\n // The destination path may just be a directory into which the file should be copied.\n // If it is, append the filename from the source onto the destination directory\n if (DirectoryExists(destFullPath))\n {\n destFullPath = Path.Combine(destFullPath, Path.GetFileName(sourceFullPath));\n }\n\n // Copy the contents of the file from the source to the destination, creating the destination in the process\n using (var src = new FileStream(sourceFullPath, FileMode.Open, FileAccess.Read, FileShare.Read, FileStream.DefaultBufferSize, FileOptions.None))\n using (var dst = new FileStream(destFullPath, overwrite ? FileMode.Create : FileMode.CreateNew, FileAccess.ReadWrite, FileShare.None, FileStream.DefaultBufferSize, FileOptions.None))\n {\n Interop.CheckIo(Interop.Sys.CopyFile(src.SafeFileHandle, dst.SafeFileHandle));\n }\n }\n\n public override void MoveFile(string sourceFullPath, string destFullPath)\n {\n // The desired behavior for Move(source, dest) is to not overwrite the destination file\n // if it exists. Since rename(source, dest) will replace the file at 'dest' if it exists,\n // link/unlink are used instead. Note that the Unix FileSystemWatcher will treat a Move \n // as a Creation and Deletion instead of a Rename and thus differ from Windows.\n if (Interop.Sys.Link(sourceFullPath, destFullPath) < 0)\n {\n // If link fails, we can fall back to doing a full copy, but we'll only do so for\n // cases where we expect link could fail but such a copy could succeed. We don't\n // want to do so for all errors, because the copy could incur a lot of cost\n // even if we know it'll eventually fail, e.g. EROFS means that the source file\n // system is read-only and couldn't support the link being added, but if it's\n // read-only, then the move should fail any way due to an inability to delete\n // the source file.\n Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo();\n if (errorInfo.Error == Interop.Error.EXDEV || // rename fails across devices / mount points\n errorInfo.Error == Interop.Error.EPERM || // permissions might not allow creating hard links even if a copy would work\n errorInfo.Error == Interop.Error.EOPNOTSUPP || // links aren't supported by the source file system\n errorInfo.Error == Interop.Error.EMLINK) // too many hard links to the source file\n {\n CopyFile(sourceFullPath, destFullPath, overwrite: false);\n }\n else\n {\n // The operation failed. Within reason, try to determine which path caused the problem \n // so we can throw a detailed exception.\n string path = null;\n bool isDirectory = false;\n if (errorInfo.Error == Interop.Error.ENOENT)\n {\n if (!Directory.Exists(Path.GetDirectoryName(destFullPath)))\n {\n // The parent directory of destFile can't be found.\n // Windows distinguishes between whether the directory or the file isn't found,\n // and throws a different exception in these cases. We attempt to approximate that\n // here; there is a race condition here, where something could change between\n // when the error occurs and our checks, but it's the best we can do, and the\n // worst case in such a race condition (which could occur if the file system is\n // being manipulated concurrently with these checks) is that we throw a\n // FileNotFoundException instead of DirectoryNotFoundexception.\n path = destFullPath;\n isDirectory = true;\n }\n else\n {\n path = sourceFullPath;\n }\n }\n else if (errorInfo.Error == Interop.Error.EEXIST)\n {\n path = destFullPath;\n }\n\n throw Interop.GetExceptionForIoErrno(errorInfo, path, isDirectory);\n }\n }\n DeleteFile(sourceFullPath);\n }\n\n public override void DeleteFile(string fullPath)\n {\n if (Interop.Sys.Unlink(fullPath) < 0)\n {\n Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo();\n // ENOENT means it already doesn't exist; nop\n if (errorInfo.Error != Interop.Error.ENOENT)\n {\n if (errorInfo.Error == Interop.Error.EISDIR)\n errorInfo = Interop.Error.EACCES.Info();\n throw Interop.GetExceptionForIoErrno(errorInfo, fullPath);\n }\n }\n }\n\n public override void CreateDirectory(string fullPath)\n {\n // NOTE: This logic is primarily just carried forward from Win32FileSystem.CreateDirectory.\n\n int length = fullPath.Length;\n\n // We need to trim the trailing slash or the code will try to create 2 directories of the same name.\n if (length >= 2 && PathHelpers.EndsInDirectorySeparator(fullPath))\n {\n length--;\n }\n\n // For paths that are only // or /// \n if (length == 2 && PathInternal.IsDirectorySeparator(fullPath[1]))\n {\n throw new IOException(SR.Format(SR.IO_CannotCreateDirectory, fullPath));\n }\n\n // We can save a bunch of work if the directory we want to create already exists.\n if (DirectoryExists(fullPath))\n {\n return;\n }\n\n // Attempt to figure out which directories don't exist, and only create the ones we need.\n bool somepathexists = false;\n Stack stackDir = new Stack();\n int lengthRoot = PathInternal.GetRootLength(fullPath);\n if (length > lengthRoot)\n {\n int i = length - 1;\n while (i >= lengthRoot && !somepathexists)\n {\n string dir = fullPath.Substring(0, i + 1);\n if (!DirectoryExists(dir)) // Create only the ones missing\n {\n stackDir.Push(dir);\n }\n else\n {\n somepathexists = true;\n }\n\n while (i > lengthRoot && !PathInternal.IsDirectorySeparator(fullPath[i]))\n {\n i--;\n }\n i--;\n }\n }\n\n int count = stackDir.Count;\n if (count == 0 && !somepathexists)\n {\n string root = Directory.InternalGetDirectoryRoot(fullPath);\n if (!DirectoryExists(root))\n {\n throw Interop.GetExceptionForIoErrno(Interop.Error.ENOENT.Info(), fullPath, isDirectory: true);\n }\n return;\n }\n\n // Create all the directories\n int result = 0;\n Interop.ErrorInfo firstError = default(Interop.ErrorInfo);\n string errorString = fullPath;\n while (stackDir.Count > 0)\n {\n string name = stackDir.Pop();\n if (name.Length >= MaxDirectoryPath)\n {\n throw new PathTooLongException(SR.IO_PathTooLong);\n }\n\n // The mkdir command uses 0777 by default (it'll be AND'd with the process umask internally).\n // We do the same.\n result = Interop.Sys.MkDir(name, (int)Interop.Sys.Permissions.Mask);\n if (result < 0 && firstError.Error == 0)\n {\n Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo();\n\n // While we tried to avoid creating directories that don't\n // exist above, there are a few cases that can fail, e.g.\n // a race condition where another process or thread creates\n // the directory first, or there's a file at the location.\n if (errorInfo.Error != Interop.Error.EEXIST)\n {\n firstError = errorInfo;\n }\n else if (FileExists(name) || (!DirectoryExists(name, out errorInfo) && errorInfo.Error == Interop.Error.EACCES))\n {\n // If there's a file in this directory's place, or if we have ERROR_ACCESS_DENIED when checking if the directory already exists throw.\n firstError = errorInfo;\n errorString = name;\n }\n }\n }\n\n // Only throw an exception if creating the exact directory we wanted failed to work correctly.\n if (result < 0 && firstError.Error != 0)\n {\n throw Interop.GetExceptionForIoErrno(firstError, errorString, isDirectory: true);\n }\n }\n\n public override void MoveDirectory(string sourceFullPath, string destFullPath)\n {\n if (Interop.Sys.Rename(sourceFullPath, destFullPath) < 0)\n {\n Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo();\n switch (errorInfo.Error)\n {\n case Interop.Error.EACCES: // match Win32 exception\n throw new IOException(SR.Format(SR.UnauthorizedAccess_IODenied_Path, sourceFullPath), errorInfo.RawErrno);\n default:\n throw Interop.GetExceptionForIoErrno(errorInfo, sourceFullPath, isDirectory: true);\n }\n }\n }\n\n public override void RemoveDirectory(string fullPath, bool recursive)\n {\n var di = new DirectoryInfo(fullPath);\n if (!di.Exists)\n {\n throw Interop.GetExceptionForIoErrno(Interop.Error.ENOENT.Info(), fullPath, isDirectory: true);\n }\n RemoveDirectoryInternal(di, recursive, throwOnTopLevelDirectoryNotFound: true);\n }\n\n private void RemoveDirectoryInternal(DirectoryInfo directory, bool recursive, bool throwOnTopLevelDirectoryNotFound)\n {\n Exception firstException = null;\n\n if ((directory.Attributes & FileAttributes.ReparsePoint) != 0)\n {\n DeleteFile(directory.FullName);\n return;\n }\n\n if (recursive)\n {\n try\n {\n foreach (string item in EnumeratePaths(directory.FullName, \"*\", SearchOption.TopDirectoryOnly, SearchTarget.Both))\n {\n if (!ShouldIgnoreDirectory(Path.GetFileName(item)))\n {\n try\n {\n var childDirectory = new DirectoryInfo(item);\n if (childDirectory.Exists)\n {\n RemoveDirectoryInternal(childDirectory, recursive, throwOnTopLevelDirectoryNotFound: false);\n }\n else\n {\n DeleteFile(item);\n }\n }\n catch (Exception exc)\n {\n if (firstException != null)\n {\n firstException = exc;\n }\n }\n }\n }\n }\n catch (Exception exc)\n {\n if (firstException != null)\n {\n firstException = exc;\n }\n }\n\n if (firstException != null)\n {\n throw firstException;\n }\n }\n\n if (Interop.Sys.RmDir(directory.FullName) < 0)\n {\n Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo();\n switch (errorInfo.Error)\n {\n case Interop.Error.EACCES:\n case Interop.Error.EPERM:\n case Interop.Error.EROFS:\n case Interop.Error.EISDIR:\n throw new IOException(SR.Format(SR.UnauthorizedAccess_IODenied_Path, directory.FullName)); // match Win32 exception\n case Interop.Error.ENOENT:\n if (!throwOnTopLevelDirectoryNotFound)\n {\n return;\n }\n goto default;\n default:\n throw Interop.GetExceptionForIoErrno(errorInfo, directory.FullName, isDirectory: true);\n }\n }\n }\n\n public override bool DirectoryExists(string fullPath)\n {\n Interop.ErrorInfo ignored;\n return DirectoryExists(fullPath, out ignored);\n }\n\n private static bool DirectoryExists(string fullPath, out Interop.ErrorInfo errorInfo)\n {\n return FileExists(fullPath, Interop.Sys.FileTypes.S_IFDIR, out errorInfo);\n }\n\n public override bool FileExists(string fullPath)\n {\n Interop.ErrorInfo ignored;\n return FileExists(fullPath, Interop.Sys.FileTypes.S_IFREG, out ignored);\n }\n\n private static bool FileExists(string fullPath, int fileType, out Interop.ErrorInfo errorInfo)\n {\n Debug.Assert(fileType == Interop.Sys.FileTypes.S_IFREG || fileType == Interop.Sys.FileTypes.S_IFDIR);\n\n Interop.Sys.FileStatus fileinfo;\n errorInfo = default(Interop.ErrorInfo);\n\n // First use stat, as we want to follow symlinks. If that fails, it could be because the symlink\n // is broken, we don't have permissions, etc., in which case fall back to using LStat to evaluate\n // based on the symlink itself.\n if (Interop.Sys.Stat(fullPath, out fileinfo) < 0 &&\n Interop.Sys.LStat(fullPath, out fileinfo) < 0)\n {\n errorInfo = Interop.Sys.GetLastErrorInfo();\n return false;\n }\n\n // Something exists at this path. If the caller is asking for a directory, return true if it's\n // a directory and false for everything else. If the caller is asking for a file, return false for\n // a directory and true for everything else.\n return\n (fileType == Interop.Sys.FileTypes.S_IFDIR) ==\n ((fileinfo.Mode & Interop.Sys.FileTypes.S_IFMT) == Interop.Sys.FileTypes.S_IFDIR);\n }\n\n public override IEnumerable EnumeratePaths(string path, string searchPattern, SearchOption searchOption, SearchTarget searchTarget)\n {\n return new FileSystemEnumerable(path, searchPattern, searchOption, searchTarget, (p, _) => p);\n }\n\n public override IEnumerable EnumerateFileSystemInfos(string fullPath, string searchPattern, SearchOption searchOption, SearchTarget searchTarget)\n {\n switch (searchTarget)\n {\n case SearchTarget.Files:\n return new FileSystemEnumerable(fullPath, searchPattern, searchOption, searchTarget, (path, isDir) =>\n new FileInfo(path, null));\n case SearchTarget.Directories:\n return new FileSystemEnumerable(fullPath, searchPattern, searchOption, searchTarget, (path, isDir) =>\n new DirectoryInfo(path, null));\n default:\n return new FileSystemEnumerable(fullPath, searchPattern, searchOption, searchTarget, (path, isDir) => isDir ?\n (FileSystemInfo)new DirectoryInfo(path, null) :\n (FileSystemInfo)new FileInfo(path, null));\n }\n }\n\n private sealed class FileSystemEnumerable : IEnumerable\n {\n private readonly PathPair _initialDirectory;\n private readonly string _searchPattern;\n private readonly SearchOption _searchOption;\n private readonly bool _includeFiles;\n private readonly bool _includeDirectories;\n private readonly Func _translateResult;\n private IEnumerator _firstEnumerator;\n\n internal FileSystemEnumerable(\n string userPath, string searchPattern,\n SearchOption searchOption, SearchTarget searchTarget,", "answers": [" Func translateResult)"], "length": 1602, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "f650bb08-31ae-4f74-8a0b-4a7d6deed6d1", "reasoning": "The code is defining the constructor for the nested FileSystemEnumerable class. The parameter list currently ends with a trailing comma after SearchTarget searchTarget, so the next line should complete the parameter list with the final argument, which is a Func named translateResult, followed by the closing parenthesis.", "reasoning_model_answer": "Func translateResult)", "assistant_with_reasoning": "\nThe code is defining the constructor for the nested FileSystemEnumerable class. The parameter list currently ends with a trailing comma after SearchTarget searchTarget, so the next line should complete the parameter list with the final argument, which is a Func named translateResult, followed by the closing parenthesis.\n\nFunc translateResult)", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 8.037, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 18797, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "Func translateResult)", "score": 0.83, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "#!/usr/bin/python\n# -*- coding: utf-8 -*-\n# ramaplot.AmberForceField.py\n#\n# Copyright (C) 2015 Karl T Debiec\n# All rights reserved.\n#\n# This software may be modified and distributed under the terms of the\n# BSD license. See the LICENSE file for details.\n\"\"\"\nReads and represents AMBER-format force fields\n\"\"\"\n################################### MODULES ###################################\nfrom __future__ import absolute_import,division,print_function,unicode_literals\nimport re\nfrom .ForceField import ForceField\n################################### CLASSES ###################################\nclass AmberForceField(ForceField):\n \"\"\"\n Reads and represents AMBER-format force fields\n \"\"\"\n\n @staticmethod\n def get_cache_key(parm=None, *args, **kwargs):\n \"\"\"\n Generates tuple of arguments to be used as key for dataset\n cache.\n \"\"\"\n from os.path import expandvars\n\n return (AmberForceField, expandvars(parm))\n\n @staticmethod\n def get_cache_message(cache_key):\n return \"previously loaded from '{0}'\".format(cache_key[1])\n\n par_re = dict(\n blank = \"^\\s*$\",\n mass = \"^(?P{t}){w}\"\n \"(?P{f})\"\n \"(?P{w}{f}|{w})\"\n \"(?P.*$)\",\n atomlist = \"^({t}{w})*$\",\n bond = \"^(?P{t})-\"\n \"(?P{t}){w}\"\n \"(?P{f}){w}\"\n \"(?P{f}){w}\"\n \"(?P.*$)\",\n angle = \"^(?P{t})-\"\n \"(?P{t})-\"\n \"(?P{t}){w}\"\n \"(?P{f}){w}\"\n \"(?P{f}){w}\"\n \"(?P.*$)\",\n dihedral = \"^(?P{t})-\"\n \"(?P{t})-\"\n \"(?P{t})-\"\n \"(?P{t}){w}\"\n \"(?P{i}){w}\"\n \"(?P{sf}){w}\"\n \"(?P{sf}){w}\"\n \"(?P{sf}){w}\"\n \"(?P.*$)\",\n improper = \"^(?P{t})-\"\n \"(?P{t})-\"\n \"(?P{t})-\"\n \"(?P{t}){w}\"\n \"(?P{sf}){w}\"\n \"(?P{sf}){w}\"\n \"(?P{sf}){w}\"\n \"(?P.*$)\",\n hbond = \"^{w}(?P{t}){w}\"\n \"(?P{t}){w}\"\n \"(?P{f}){w}\"\n \"(?P{f}){w}\"\n \"(?P{f}){w}\"\n \"(?P.*$)\",\n vdw_format = \"^.+{w}(?PSK|RE|AC).*$\",\n vdw = \"^{w}(?P{t}){w}\"\n \"(?P{f}){w}\"\n \"(?P{f}){w}\"\n \"(?P.*$)\",\n ljedit_title = \"^LJEDIT$\",\n ljedit = \"^{w}(?P{t}){w}\"\n \"(?P{t}){w}\"\n \"(?P{f}){w}\"\n \"(?P{f}){w}\"\n \"(?P{f}){w}\"\n \"(?P{f}){w}\"\n \"(?P.*$)\",\n end = \"^END$\")\n\n lib_re = dict(\n blank = \"^\\s*$\",\n atoms = \"^\\s*\\\"(?P{a})\\\"{w}\"\n \"\\\"(?P{t})\\\"{w}\"\n \"(?P{i}){w}\"\n \"(?P{i}){w}\"\n \"(?P{i}){w}\"\n \"(?P{i}){w}\"\n \"(?P{i}){w}\"\n \"(?P{sf}){w}\"\n \"(?P.*$)\",\n atom_edits = \"^\\s*\\\"(?P{a})\\\"{w}\"\n \"\\\"(?P{t})\\\"{w}\"\n \"(?P{i}){w}\"\n \"(?P{si}{w})\"\n \"(?P{sf}{w})\"\n \"(?P.*$)\",\n box = \"^\\s*(?P{sf}){w}\"\n \"(?P.*$)\",\n res_seq = \"^\\s*(?P{i}){w}\"\n \"(?P.*$)\",\n res_connect = \"^\\s*(?P{i}){w}\"\n \"(?P.*$)\",\n bonds = \"^\\s*(?P{i}){w}\"\n \"(?P{t}){w}\"\n \"(?P{i}){w}\"\n \"(?P.*$)\",\n hierarchy = \"^\\s*\\\"(?PU|R|A)\\\"{w}\"\n \"(?P{i}){w}\"\n \"\\\"(?PU|R|A)\\\"{w}\"\n \"(?P{i}){w}\"\n \"(?P.*$)\",\n name = \"^\\s*\\\"(?P{r})\\\"\"\n \"(?P.*$)\",\n coordinates = \"^\\s*(?P{sfe}){w}\"\n \"(?P{sfe}){w}\"\n \"(?P{sfe}){w}\"\n \"(?P.*$)\",\n res_connect2 = \"^\\s*(?P{i}){w}\"\n \"(?P{i}){w}\"\n \"(?P{i}){w}\"\n \"(?P{i}){w}\"\n \"(?P{i}){w}\"\n \"(?P{i}){w}\"\n \"(?P.*$)\",\n residues = \"^\\s*\\\"(?P{r})\\\"{w}\"\n \"(?P{i}){w}\"\n \"(?P{i}){w}\"\n \"(?P{i}){w}\"\n \"\\\"(?Pp|n|w|\\?)\\\"{w}\"\n \"(?P.*$)\",\n pdb_seq = \"^\\s*(?P{i}){w}\"\n \"(?P.*$)\",\n solventcap = \"^\\s*(?P{sf}){w}\"\n \"(?P.*$)\",\n velocities = \"^\\s*(?P{sfe}){w}\"\n \"(?P{sfe}){w}\"\n \"(?P{sfe}){w}\"\n \"(?P.*$)\")\n\n def __init__(self, parm=None, **kwargs):\n \"\"\"\n \"\"\"\n\n if parm is not None:\n self.parameters = self.read_parm(parm, **kwargs)\n\n @staticmethod\n def amber_regex(regex, title=False):\n \"\"\"\n Prepares regex for matching AMBER fields\n\n Arguments:\n regex (string): regular expression\n\n Returns:\n (string): regular expression\n \"\"\"\n if title:\n regex = \"^!entry\\.(?P{r})\\.unit\\.\" + regex + \"{w}.*$\"\n return re.compile(regex.format(\n r = \"[\\w][\\w][\\w][\\w]?\", # Residue\n a = \"[\\w][\\w]?[\\w]?[\\w]?\", # Atom name\n t = \"[\\w][\\w \\*]?\", # Atom type\n i = \"\\d+\", # Integer\n si = \"[-]?\\d+\", # Signed Integer\n f = \"\\d+\\.?\\d*?\", # Float\n sf = \"[-]?\\d+\\.?\\d*?\", # Signed float\n sfe = \"[-]?\\d+\\.?\\d*?[E]?[-]?\\d*?\", # Signed float in E notation\n w = \"\\s+\")) # Whitespace\n\n @staticmethod\n def strip_dict(dictionary):\n \"\"\"\n Strips each string in a dict, and deletes if empty\n\n Arguements:\n dictionary (dict): dictionary to strip\n\n Returns:\n (dict): dictionary with each element stripped\n \"\"\"\n for key, value in dictionary.items():\n value = value.strip()\n if value == \"\":\n del dictionary[key]\n else:\n dictionary[key] = value\n return dictionary\n\n @staticmethod\n def read_parm(infile, verbose=1, debug=0, **kwargs):\n \"\"\"\n Reads a parm file\n\n Arguments:\n infile (str): Path to input parm file\n verbose (int): Enable verbose output\n debug (int): Enable debug output\n kwargs (dict): Additional keyword arguments\n \"\"\"\n import pandas as pd\n\n if verbose >= 1:\n print(\"READING PARM: {0}\".format(infile))\n\n strip_dict = AmberForceField.strip_dict\n amber_regex = AmberForceField.amber_regex\n par_re = AmberForceField.par_re\n\n re_blank = amber_regex(par_re[\"blank\"])\n re_mass = amber_regex(par_re[\"mass\"])\n re_atomlist = amber_regex(par_re[\"atomlist\"])\n re_bond = amber_regex(par_re[\"bond\"])\n re_angle = amber_regex(par_re[\"angle\"])\n re_dihedral = amber_regex(par_re[\"dihedral\"])\n re_improper = amber_regex(par_re[\"improper\"])\n re_hbond = amber_regex(par_re[\"hbond\"])\n re_vdw_format = amber_regex(par_re[\"vdw_format\"])\n re_vdw = amber_regex(par_re[\"vdw\"])\n re_ljedit_title = amber_regex(par_re[\"ljedit_title\"])\n re_ljedit = amber_regex(par_re[\"ljedit\"])\n re_end = amber_regex(par_re[\"end\"])\n\n mass_types = pd.DataFrame(columns=[\"type\", \"mass\",\n \"polarizability\", \"note\"])\n hydrophobic_types = pd.DataFrame(columns=[\"type\"])\n bonds = pd.DataFrame(columns=[\"type_1\", \"type_2\",\n \"force_constant\", \"length\", \"note\"])\n angles = pd.DataFrame(columns=[\"type_1\", \"type_2\", \"type_3\",\n \"force_constant\", \"angle\", \"note\"])\n dihedrals = pd.DataFrame(columns=[\"type_1\", \"type_2\", \"type_3\",\n \"type_4\", \"divider\", \"barrier\", \"phase\",\n \"periodicity\", \"note\"])\n impropers = pd.DataFrame(columns=[\"type_1\", \"type_2\", \"type_3\",\n \"type_4\", \"barrier\", \"phase\",\n \"periodicity\", \"note\"])\n hbonds = pd.DataFrame(columns=[\"type_1\", \"type_2\", \"A\", \"B\",\n \"ASOLN\"])\n vdw_eq_types = pd.DataFrame()\n vdw_types = pd.DataFrame(columns= [\"type\", \"radius\",\n \"well_depth\", \"note\"])\n ljedits = pd.DataFrame(columns= [\"type_1\", \"type_2\",\n \"radius_1\", \"well_depth_1\", \"radius_2\",\n \"well_depth_2\"])\n\n section = 1\n\n with open(infile, \"r\") as open_infile:\n line = open_infile.readline()\n while line:\n # BLANK\n if re.match(re_blank, line):\n if verbose >= 1:\n print(\"BLANK |{0}\".format(line.strip()))\n # 1: TITLE\n elif section <= 1 and not re.match(re_mass, line):\n if verbose >= 1:\n print(\"TITLE |{0}\".format(line.strip()))\n # 2: MASS\n elif section <= 2 and re.match(re_mass, line):\n section = 2\n if verbose >= 1:\n print(\"MASS |{0}\".format(line.strip()))\n fields = strip_dict(re.match(re_mass, line).groupdict())\n mass_types = mass_types.append(fields, ignore_index=True)\n # 3: HYDROPHIC (list of types)\n elif section <= 3 and re.match(re_atomlist, line):\n section = 3\n if verbose >= 1:\n print(\"HYDROPHOBIC |{0}\".format(line.rstrip()))\n fields = [{\"type\": v} for v in\n amber_regex(\"{t}\").findall(line)]\n hydrophobic_types = hydrophobic_types.append(fields,\n ignore_index=True)\n # 4: BOND\n elif section <= 4 and re.match(re_bond, line):\n section = 4\n if verbose >= 1:\n print(\"BOND |{0}\".format(line.rstrip()))\n fields = strip_dict(re.match(re_bond, line).groupdict())\n bonds = bonds.append(fields, ignore_index=True)\n # 5: ANGLE\n elif section <= 5 and re.match(re_angle, line):\n section = 5\n if verbose >= 1:\n print(\"ANGLE |{0}\".format(line.rstrip()))\n fields = strip_dict(re.match(re_angle, line).groupdict())\n angles = angles.append(fields, ignore_index=True)\n # 6: DIHEDRAL\n elif section <= 6 and re.match(re_dihedral, line):\n section = 6\n if verbose >= 1:\n print(\"DIHEDRAL |{0}\".format(line.rstrip()))\n fields = strip_dict(re.match(re_dihedral,\n line).groupdict())\n dihedrals = dihedrals.append(fields, ignore_index=True)\n # 7: IMPROPER\n elif section <= 7 and re.match(re_improper, line):\n section = 7\n if verbose >= 1:\n print(\"IMPROPER |{0}\".format(line.rstrip()))\n fields = strip_dict(re.match(re_improper,\n line).groupdict())\n impropers = impropers.append(fields, ignore_index=True)\n # 8: HBOND\n elif section <= 8 and re.match(re_hbond, line):\n section = 8\n if verbose >= 1:\n print(\"HBOND |{0}\".format(line.rstrip()))\n fields = strip_dict(re.match(re_hbond, line).groupdict())\n hbonds = hbonds.append(fields, ignore_index=True)\n # 9: VDW (equivalent types)\n elif section <= 9 and re.match(re_atomlist, line):\n section = 9\n if verbose >= 1:\n print(\"VDW EQUIVALENT |{0}\".format(line.rstrip()))\n fields = [{\"type_{0}\".format(i): v for i, v in\n enumerate(re.compile(amber_regex(\"{t}\")).findall(line))}]\n vdw_eq_types = vdw_eq_types.append(fields,\n ignore_index=True)\n # 10: VDW (format)\n elif section <= 10.3 and re.match(re_vdw_format, line):\n if verbose >= 1:\n print(\"VDW FORMAT |{0}\".format(line.rstrip()))\n # 10.2: VDW (radius and well depth)\n elif section <= 10.2 and re.match(re_vdw, line):\n section = 10.2\n if verbose >= 1:\n print(\"VDW |{0}\".format(line.rstrip()))\n fields = strip_dict(re.match(re_vdw, line).groupdict())\n vdw_types = vdw_types.append(fields, ignore_index=True)\n # 11: LJEDIT (title)\n elif (section <= 11 and re.match(re_ljedit_title, line)):\n section = 11\n if verbose >= 1:\n print(\"LJEDIT |{0}\".format(line.rstrip()))\n # 11.1: LJEDIT (atom types, radii, and well depth)\n elif (section <= 11.1 and re.match(re_ljedit, line)):\n section = 11.1\n if verbose >= 1:\n print(\"LJEDIT |{0}\".format(line.rstrip()))\n fields = strip_dict(re.match(re_ljedit, line).groupdict())\n ljedits = ljedits.append(fields, ignore_index=True)\n # END\n elif re.match(re_end, line):\n if verbose >= 1:\n print(\"END |{0}\".format(line.rstrip()))\n break\n # NO MATCH\n else:\n if verbose >= 1:\n print(\"NOMATCH |{0}\".format(line.rstrip()))\n line = open_infile.readline()\n if debug >= 1:\n print(mass_types)\n print(hydrophobic_types)\n print(bonds)\n print(angles)\n print(dihedrals)\n print(impropers)\n print(hbonds)\n print(vdw_eq_types)\n print(vdw_types)\n print(ljedits)\n parameters = dict(\n mass_types = mass_types,\n hydrophobic_types = hydrophobic_types,\n bonds = bonds,\n angles = angles,\n dihedrals = dihedrals,\n impropers = impropers,\n hbonds = hbonds,\n vdw_eq_types = vdw_eq_types,\n vdw_types = vdw_types,\n ljedits = ljedits)\n return parameters\n\n# def read_frcmod(self, infile, verbose=1, debug=0, **kwargs):\n# \"\"\"\n# Arguments:\n# infile (str): Path to input lib file\n# verbose (int): Enable verbose output\n# debug (int): Enable debug output\n# kwargs (dict): Additional keyword arguments\n# \"\"\"\n# if verbose >= 1:\n# print(\"READING FRCMOD: {0}\".format(infile))\n#\n# are = self.amber_regex\n# strip_dict = self.strip_dict\n# re_blank = are(\"^\\s*$\")\n#\n# section = 1\n# with open(infile, \"r\") as open_infile:\n# line = open_infile.readline()\n# while line:\n# # BLANK\n# if re.match(re_blank, line):\n# if verbose >= 1:\n# print(\"BLANK |{0}\".format(line.strip()))\n# # 1: TITLE\n# elif section <= 1 and not re.match(re_mass, line):\n# if verbose >= 1:\n# print(\"TITLE |{0}\".format(line.strip()))\n# # 2: MASS\n# elif section <= 2 and re.match(re_mass, line):\n# section = 2\n# if verbose >= 1:\n# print(\"MASS |{0}\".format(line.strip()))\n# fields = strip_dict(re.match(re_mass, line).groupdict())\n# mass_types = mass_types.append(fields, ignore_index=True)\n# # 3: HYDROPHIC (list of types)\n# elif section <= 3 and re.match(re_atomlist, line):\n# section = 3\n# if verbose >= 1:\n# print(\"HYDROPHOBIC |{0}\".format(line.rstrip()))\n# fields = [{\"type\": v} for v in are(\"{t}\").findall(line)]\n# hydrophobic_types = hydrophobic_types.append(fields,\n# ignore_index=True)\n# # 4: BOND\n# elif section <= 4 and re.match(re_bond, line):\n# section = 4\n# if verbose >= 1:\n# print(\"BOND |{0}\".format(line.rstrip()))\n# fields = strip_dict(re.match(re_bond, line).groupdict())\n# bonds = bonds.append(fields, ignore_index=True)\n# # 5: ANGLE\n# elif section <= 5 and re.match(re_angle, line):\n# section = 5\n# if verbose >= 1:\n# print(\"ANGLE |{0}\".format(line.rstrip()))\n# fields = strip_dict(re.match(re_angle, line).groupdict())\n# angles = angles.append(fields, ignore_index=True)\n# # 6: DIHEDRAL\n# elif section <= 6 and re.match(re_dihedral, line):\n# section = 6\n# if verbose >= 1:\n# print(\"DIHEDRAL |{0}\".format(line.rstrip()))\n# fields = strip_dict(re.match(re_dihedral,\n# line).groupdict())\n# dihedrals = dihedrals.append(fields, ignore_index=True)\n# # 7: IMPROPER\n# elif section <= 7 and re.match(re_improper, line):\n# section = 7\n# if verbose >= 1:\n# print(\"IMPROPER |{0}\".format(line.rstrip()))\n# fields = strip_dict(re.match(re_improper,\n# line).groupdict())\n# impropers = impropers.append(fields, ignore_index=True)\n# # 8: HBOND\n# elif section <= 8 and re.match(re_hbond, line):\n# section = 8\n# if verbose >= 1:\n# print(\"HBOND |{0}\".format(line.rstrip()))\n# fields = strip_dict(re.match(re_hbond, line).groupdict())\n# hbonds = hbonds.append(fields, ignore_index=True)\n# # 9: VDW (equivalent types)\n# elif section <= 9 and re.match(re_atomlist, line):\n# section = 9\n# if verbose >= 1:\n# print(\"VDW EQUIVALENT |{0}\".format(line.rstrip()))\n# fields = [{\"type_{0}\".format(i): v for i, v in\n# enumerate(re.compile(are(\"{t}\")).findall(line))}]\n# vdw_eq_types = vdw_eq_types.append(fields,\n# ignore_index=True)\n# # 10: VDW (format)\n# elif section <= 10.3 and re.match(re_vdw_format, line):\n# if verbose >= 1:\n# print(\"VDW FORMAT |{0}\".format(line.rstrip()))\n# # 10.2: VDW (radius and well depth)\n# elif section <= 10.2 and re.match(re_vdw, line):\n# section = 10.2\n# if verbose >= 1:\n# print(\"VDW |{0}\".format(line.rstrip()))\n# fields = strip_dict(re.match(re_vdw, line).groupdict())", "answers": ["# vdw_types = vdw_types.append(fields, ignore_index=True)"], "length": 1514, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "8b58deea-3574-4dad-ba65-33ad27d36e90", "reasoning": "The commented read_frcmod method mirrors the logic of read_parm. In the VDW (radius and well depth) block, after extracting fields with strip_dict, the next step is to add those fields to the vdw_types DataFrame, just as in read_parm. Therefore the next line should append the fields to vdw_types.", "reasoning_model_answer": "vdw_types = vdw_types.append(fields, ignore_index=True)", "assistant_with_reasoning": "\nThe commented read_frcmod method mirrors the logic of read_parm. In the VDW (radius and well depth) block, after extracting fields with strip_dict, the next step is to add those fields to the vdw_types DataFrame, just as in read_parm. Therefore the next line should append the fields to vdw_types.\n\nvdw_types = vdw_types.append(fields, ignore_index=True)", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.301, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 22131, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "vdw_types = vdw_types.append(fields, ignore_index=True)", "score": 0.84, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "# -*- coding: utf-8 -*-\n# Unit and doctests for specific database backends.\nfrom __future__ import absolute_import\n\nimport datetime\nimport threading\n\nfrom django.conf import settings\nfrom django.core.management.color import no_style\nfrom django.core.exceptions import ImproperlyConfigured\nfrom django.db import (backend, connection, connections, DEFAULT_DB_ALIAS,\n IntegrityError, transaction)\nfrom django.db.backends.signals import connection_created\nfrom django.db.backends.postgresql_psycopg2 import version as pg_version\nfrom django.db.utils import ConnectionHandler, DatabaseError, load_backend\nfrom django.test import (TestCase, skipUnlessDBFeature, skipIfDBFeature,\n TransactionTestCase)\nfrom django.test.utils import override_settings\nfrom django.utils import unittest\n\nfrom . import models\n\n\nclass OracleChecks(unittest.TestCase):\n\n @unittest.skipUnless(connection.vendor == 'oracle',\n \"No need to check Oracle cursor semantics\")\n def test_dbms_session(self):\n # If the backend is Oracle, test that we can call a standard\n # stored procedure through our cursor wrapper.\n convert_unicode = backend.convert_unicode\n cursor = connection.cursor()\n cursor.callproc(convert_unicode('DBMS_SESSION.SET_IDENTIFIER'),\n [convert_unicode('_django_testing!'),])\n\n @unittest.skipUnless(connection.vendor == 'oracle',\n \"No need to check Oracle cursor semantics\")\n def test_cursor_var(self):\n # If the backend is Oracle, test that we can pass cursor variables\n # as query parameters.\n cursor = connection.cursor()\n var = cursor.var(backend.Database.STRING)\n cursor.execute(\"BEGIN %s := 'X'; END; \", [var])\n self.assertEqual(var.getvalue(), 'X')\n\n @unittest.skipUnless(connection.vendor == 'oracle',\n \"No need to check Oracle cursor semantics\")\n def test_long_string(self):\n # If the backend is Oracle, test that we can save a text longer\n # than 4000 chars and read it properly\n c = connection.cursor()\n c.execute('CREATE TABLE ltext (\"TEXT\" NCLOB)')\n long_str = ''.join([unicode(x) for x in xrange(4000)])\n c.execute('INSERT INTO ltext VALUES (%s)',[long_str])\n c.execute('SELECT text FROM ltext')\n row = c.fetchone()\n self.assertEqual(long_str, row[0].read())\n c.execute('DROP TABLE ltext')\n\n @unittest.skipUnless(connection.vendor == 'oracle',\n \"No need to check Oracle connection semantics\")\n def test_client_encoding(self):\n # If the backend is Oracle, test that the client encoding is set\n # correctly. This was broken under Cygwin prior to r14781.\n connection.cursor() # Ensure the connection is initialized.\n self.assertEqual(connection.connection.encoding, \"UTF-8\")\n self.assertEqual(connection.connection.nencoding, \"UTF-8\")\n\nclass MySQLTests(TestCase):\n @unittest.skipUnless(connection.vendor == 'mysql',\n \"Test valid only for MySQL\")\n def test_autoincrement(self):\n \"\"\"\n Check that auto_increment fields are reset correctly by sql_flush().\n Before MySQL version 5.0.13 TRUNCATE did not do auto_increment reset.\n Refs #16961.\n \"\"\"\n statements = connection.ops.sql_flush(no_style(),\n tables=['test'],\n sequences=[{\n 'table': 'test',\n 'col': 'somecol',\n }])\n found_reset = False\n for sql in statements:\n found_reset = found_reset or 'ALTER TABLE' in sql\n if connection.mysql_version < (5,0,13):\n self.assertTrue(found_reset)\n else:\n self.assertFalse(found_reset)\n\n\nclass DateQuotingTest(TestCase):\n\n def test_django_date_trunc(self):\n \"\"\"\n Test the custom ``django_date_trunc method``, in particular against\n fields which clash with strings passed to it (e.g. 'year') - see\n #12818__.\n\n __: http://code.djangoproject.com/ticket/12818\n\n \"\"\"\n updated = datetime.datetime(2010, 2, 20)\n models.SchoolClass.objects.create(year=2009, last_updated=updated)\n years = models.SchoolClass.objects.dates('last_updated', 'year')\n self.assertEqual(list(years), [datetime.datetime(2010, 1, 1, 0, 0)])\n\n def test_django_extract(self):\n \"\"\"\n Test the custom ``django_extract method``, in particular against fields\n which clash with strings passed to it (e.g. 'day') - see #12818__.\n\n __: http://code.djangoproject.com/ticket/12818\n\n \"\"\"\n updated = datetime.datetime(2010, 2, 20)\n models.SchoolClass.objects.create(year=2009, last_updated=updated)\n classes = models.SchoolClass.objects.filter(last_updated__day=20)\n self.assertEqual(len(classes), 1)\n\nclass LastExecutedQueryTest(TestCase):\n\n def setUp(self):\n # connection.queries will not be filled in without this\n settings.DEBUG = True\n\n def tearDown(self):\n settings.DEBUG = False\n\n # There are no tests for the sqlite backend because it does not\n # implement paramater escaping. See #14091.\n\n @unittest.skipUnless(connection.vendor in ('oracle', 'postgresql'),\n \"These backends use the standard parameter escaping rules\")\n def test_parameter_escaping(self):\n # check that both numbers and string are properly quoted\n list(models.Tag.objects.filter(name=\"special:\\\\\\\"':\", object_id=12))\n sql = connection.queries[-1]['sql']\n self.assertTrue(\"= 'special:\\\\\\\"'':' \" in sql)\n self.assertTrue(\"= 12 \" in sql)\n\n @unittest.skipUnless(connection.vendor == 'mysql',\n \"MySQL uses backslashes to escape parameters.\")\n def test_parameter_escaping(self):\n list(models.Tag.objects.filter(name=\"special:\\\\\\\"':\", object_id=12))\n sql = connection.queries[-1]['sql']\n # only this line is different from the test above\n self.assertTrue(\"= 'special:\\\\\\\\\\\\\\\"\\\\':' \" in sql)\n self.assertTrue(\"= 12 \" in sql)\n\nclass ParameterHandlingTest(TestCase):\n def test_bad_parameter_count(self):\n \"An executemany call with too many/not enough parameters will raise an exception (Refs #12612)\"\n cursor = connection.cursor()\n query = ('INSERT INTO %s (%s, %s) VALUES (%%s, %%s)' % (\n connection.introspection.table_name_converter('backends_square'),\n connection.ops.quote_name('root'),\n connection.ops.quote_name('square')\n ))\n self.assertRaises(Exception, cursor.executemany, query, [(1,2,3),])\n self.assertRaises(Exception, cursor.executemany, query, [(1,),])\n\n# Unfortunately, the following tests would be a good test to run on all\n# backends, but it breaks MySQL hard. Until #13711 is fixed, it can't be run\n# everywhere (although it would be an effective test of #13711).\nclass LongNameTest(TestCase):\n \"\"\"Long primary keys and model names can result in a sequence name\n that exceeds the database limits, which will result in truncation\n on certain databases (e.g., Postgres). The backend needs to use\n the correct sequence name in last_insert_id and other places, so\n check it is. Refs #8901.\n \"\"\"\n\n @skipUnlessDBFeature('supports_long_model_names')\n def test_sequence_name_length_limits_create(self):\n \"\"\"Test creation of model with long name and long pk name doesn't error. Ref #8901\"\"\"\n models.VeryLongModelNameZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ.objects.create()\n\n @skipUnlessDBFeature('supports_long_model_names')\n def test_sequence_name_length_limits_m2m(self):\n \"\"\"Test an m2m save of a model with a long name and a long m2m field name doesn't error as on Django >=1.2 this now uses object saves. Ref #8901\"\"\"\n obj = models.VeryLongModelNameZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ.objects.create()\n rel_obj = models.Person.objects.create(first_name='Django', last_name='Reinhardt')\n obj.m2m_also_quite_long_zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz.add(rel_obj)\n\n @skipUnlessDBFeature('supports_long_model_names')\n def test_sequence_name_length_limits_flush(self):\n \"\"\"Test that sequence resetting as part of a flush with model with long name and long pk name doesn't error. Ref #8901\"\"\"\n # A full flush is expensive to the full test, so we dig into the\n # internals to generate the likely offending SQL and run it manually\n\n # Some convenience aliases\n VLM = models.VeryLongModelNameZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ\n VLM_m2m = VLM.m2m_also_quite_long_zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz.through\n tables = [\n VLM._meta.db_table,\n VLM_m2m._meta.db_table,\n ]\n sequences = [\n {\n 'column': VLM._meta.pk.column,\n 'table': VLM._meta.db_table\n },\n ]\n cursor = connection.cursor()\n for statement in connection.ops.sql_flush(no_style(), tables, sequences):\n cursor.execute(statement)\n\nclass SequenceResetTest(TestCase):\n def test_generic_relation(self):\n \"Sequence names are correct when resetting generic relations (Ref #13941)\"\n # Create an object with a manually specified PK\n models.Post.objects.create(id=10, name='1st post', text='hello world')\n\n # Reset the sequences for the database\n cursor = connection.cursor()\n commands = connections[DEFAULT_DB_ALIAS].ops.sequence_reset_sql(no_style(), [models.Post])\n for sql in commands:\n cursor.execute(sql)\n\n # If we create a new object now, it should have a PK greater\n # than the PK we specified manually.\n obj = models.Post.objects.create(name='New post', text='goodbye world')\n self.assertTrue(obj.pk > 10)\n\nclass PostgresVersionTest(TestCase):\n def assert_parses(self, version_string, version):\n self.assertEqual(pg_version._parse_version(version_string), version)\n\n def test_parsing(self):\n \"\"\"Test PostgreSQL version parsing from `SELECT version()` output\"\"\"\n self.assert_parses(\"PostgreSQL 8.3 beta4\", 80300)\n self.assert_parses(\"PostgreSQL 8.3\", 80300)\n self.assert_parses(\"EnterpriseDB 8.3\", 80300)\n self.assert_parses(\"PostgreSQL 8.3.6\", 80306)\n self.assert_parses(\"PostgreSQL 8.4beta1\", 80400)\n self.assert_parses(\"PostgreSQL 8.3.1 on i386-apple-darwin9.2.2, compiled by GCC i686-apple-darwin9-gcc-4.0.1 (GCC) 4.0.1 (Apple Inc. build 5478)\", 80301)\n\n def test_version_detection(self):\n \"\"\"Test PostgreSQL version detection\"\"\"\n\n # Helper mocks\n class CursorMock(object):\n \"Very simple mock of DB-API cursor\"\n def execute(self, arg):\n pass\n\n def fetchone(self):\n return [\"PostgreSQL 8.3\"]\n\n class OlderConnectionMock(object):\n \"Mock of psycopg2 (< 2.0.12) connection\"\n def cursor(self):\n return CursorMock()\n\n # psycopg2 < 2.0.12 code path\n conn = OlderConnectionMock()\n self.assertEqual(pg_version.get_version(conn), 80300)\n\nclass PostgresNewConnectionTest(TestCase):\n \"\"\"\n #17062: PostgreSQL shouldn't roll back SET TIME ZONE, even if the first\n transaction is rolled back.\n \"\"\"\n @unittest.skipUnless(\n connection.vendor == 'postgresql' and connection.isolation_level > 0,\n \"This test applies only to PostgreSQL without autocommit\")\n def test_connect_and_rollback(self):\n new_connections = ConnectionHandler(settings.DATABASES)\n new_connection = new_connections[DEFAULT_DB_ALIAS]\n try:\n # Ensure the database default time zone is different than\n # the time zone in new_connection.settings_dict. We can\n # get the default time zone by reset & show.\n cursor = new_connection.cursor()\n cursor.execute(\"RESET TIMEZONE\")\n cursor.execute(\"SHOW TIMEZONE\")\n db_default_tz = cursor.fetchone()[0]\n new_tz = 'Europe/Paris' if db_default_tz == 'UTC' else 'UTC'\n new_connection.close()\n\n # Fetch a new connection with the new_tz as default\n # time zone, run a query and rollback.\n new_connection.settings_dict['TIME_ZONE'] = new_tz\n new_connection.enter_transaction_management()\n cursor = new_connection.cursor()\n new_connection.rollback()\n\n # Now let's see if the rollback rolled back the SET TIME ZONE.\n cursor.execute(\"SHOW TIMEZONE\")\n tz = cursor.fetchone()[0]\n self.assertEqual(new_tz, tz)\n finally:\n try:\n new_connection.close()\n except DatabaseError:\n pass\n\n\n# Unfortunately with sqlite3 the in-memory test database cannot be\n# closed, and so it cannot be re-opened during testing, and so we\n# sadly disable this test for now.\nclass ConnectionCreatedSignalTest(TestCase):\n @skipUnlessDBFeature('test_db_allows_multiple_connections')\n def test_signal(self):\n data = {}\n def receiver(sender, connection, **kwargs):\n data[\"connection\"] = connection\n\n connection_created.connect(receiver)\n connection.close()\n cursor = connection.cursor()\n self.assertTrue(data[\"connection\"].connection is connection.connection)\n\n connection_created.disconnect(receiver)\n data.clear()\n cursor = connection.cursor()\n self.assertTrue(data == {})\n\n\nclass EscapingChecks(TestCase):\n\n @unittest.skipUnless(connection.vendor == 'sqlite',\n \"This is a sqlite-specific issue\")\n def test_parameter_escaping(self):\n #13648: '%s' escaping support for sqlite3\n cursor = connection.cursor()\n response = cursor.execute(\n \"select strftime('%%s', date('now'))\").fetchall()[0][0]\n self.assertNotEqual(response, None)\n # response should be an non-zero integer\n self.assertTrue(int(response))\n\n\nclass BackendTestCase(TestCase):\n\n def create_squares_with_executemany(self, args):\n cursor = connection.cursor()\n opts = models.Square._meta\n tbl = connection.introspection.table_name_converter(opts.db_table)\n f1 = connection.ops.quote_name(opts.get_field('root').column)\n f2 = connection.ops.quote_name(opts.get_field('square').column)\n query = 'INSERT INTO %s (%s, %s) VALUES (%%s, %%s)' % (tbl, f1, f2)\n cursor.executemany(query, args)\n\n def test_cursor_executemany(self):\n #4896: Test cursor.executemany\n args = [(i, i**2) for i in range(-5, 6)]\n self.create_squares_with_executemany(args)\n self.assertEqual(models.Square.objects.count(), 11)\n for i in range(-5, 6):\n square = models.Square.objects.get(root=i)\n self.assertEqual(square.square, i**2)\n\n def test_cursor_executemany_with_empty_params_list(self):\n #4765: executemany with params=[] does nothing\n args = []\n self.create_squares_with_executemany(args)\n self.assertEqual(models.Square.objects.count(), 0)\n\n def test_cursor_executemany_with_iterator(self):\n #10320: executemany accepts iterators\n args = iter((i, i**2) for i in range(-3, 2))\n self.create_squares_with_executemany(args)\n self.assertEqual(models.Square.objects.count(), 5)\n\n args = iter((i, i**2) for i in range(3, 7))\n with override_settings(DEBUG=True):\n # same test for DebugCursorWrapper\n self.create_squares_with_executemany(args)\n self.assertEqual(models.Square.objects.count(), 9)\n\n\n def test_unicode_fetches(self):\n #6254: fetchone, fetchmany, fetchall return strings as unicode objects\n qn = connection.ops.quote_name\n models.Person(first_name=\"John\", last_name=\"Doe\").save()\n models.Person(first_name=\"Jane\", last_name=\"Doe\").save()\n models.Person(first_name=\"Mary\", last_name=\"Agnelline\").save()\n models.Person(first_name=\"Peter\", last_name=\"Parker\").save()\n models.Person(first_name=\"Clark\", last_name=\"Kent\").save()\n opts2 = models.Person._meta\n f3, f4 = opts2.get_field('first_name'), opts2.get_field('last_name')\n query2 = ('SELECT %s, %s FROM %s ORDER BY %s'\n % (qn(f3.column), qn(f4.column), connection.introspection.table_name_converter(opts2.db_table),\n qn(f3.column)))\n cursor = connection.cursor()\n cursor.execute(query2)\n self.assertEqual(cursor.fetchone(), (u'Clark', u'Kent'))\n self.assertEqual(list(cursor.fetchmany(2)), [(u'Jane', u'Doe'), (u'John', u'Doe')])\n self.assertEqual(list(cursor.fetchall()), [(u'Mary', u'Agnelline'), (u'Peter', u'Parker')])\n\n def test_database_operations_helper_class(self):\n # Ticket #13630\n self.assertTrue(hasattr(connection, 'ops'))\n self.assertTrue(hasattr(connection.ops, 'connection'))\n self.assertEqual(connection, connection.ops.connection)\n\n def test_duplicate_table_error(self):\n \"\"\" Test that creating an existing table returns a DatabaseError \"\"\"\n cursor = connection.cursor()\n query = 'CREATE TABLE %s (id INTEGER);' % models.Article._meta.db_table\n with self.assertRaises(DatabaseError):\n cursor.execute(query)\n\n# We don't make these tests conditional because that means we would need to\n# check and differentiate between:\n# * MySQL+InnoDB, MySQL+MYISAM (something we currently can't do).\n# * if sqlite3 (if/once we get #14204 fixed) has referential integrity turned\n# on or not, something that would be controlled by runtime support and user\n# preference.\n# verify if its type is django.database.db.IntegrityError.\n\nclass FkConstraintsTests(TransactionTestCase):\n\n def setUp(self):\n # Create a Reporter.", "answers": [" self.r = models.Reporter.objects.create(first_name='John', last_name='Smith')"], "length": 1537, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "0e05f128-d398-4f17-b87f-62cc2afc49e6", "reasoning": "The setUp method is initializing test data. The comment indicates a Reporter object should be created. In Django tests, this is done via the model's manager. The typical fields are first_name and last_name, so the next line creates and assigns the Reporter instance.", "reasoning_model_answer": "self.reporter = models.Reporter.objects.create(first_name='John', last_name='Doe')", "assistant_with_reasoning": "\nThe setUp method is initializing test data. The comment indicates a Reporter object should be created. In Django tests, this is done via the model's manager. The typical fields are first_name and last_name, so the next line creates and assigns the Reporter instance.\n\nself.reporter = models.Reporter.objects.create(first_name='John', last_name='Doe')", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.774, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 18331, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "self.reporter = models.Reporter.objects.create(first_name='John', last_name='Doe')", "score": 0.86, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\npackage org.apache.tinkerpop.gremlin.process.traversal.step.map;\n\nimport org.apache.commons.lang3.exception.ExceptionUtils;\nimport org.apache.tinkerpop.gremlin.LoadGraphWith;\nimport org.apache.tinkerpop.gremlin.process.AbstractGremlinProcessTest;\nimport org.apache.tinkerpop.gremlin.process.GremlinProcessRunner;\nimport org.apache.tinkerpop.gremlin.process.IgnoreEngine;\nimport org.apache.tinkerpop.gremlin.process.computer.traversal.step.map.PageRank;\nimport org.apache.tinkerpop.gremlin.process.computer.traversal.step.map.TraversalVertexProgramStep;\nimport org.apache.tinkerpop.gremlin.process.traversal.P;\nimport org.apache.tinkerpop.gremlin.process.traversal.Step;\nimport org.apache.tinkerpop.gremlin.process.traversal.Traversal;\nimport org.apache.tinkerpop.gremlin.process.traversal.TraversalEngine;\nimport org.apache.tinkerpop.gremlin.process.traversal.Traverser;\nimport org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__;\nimport org.apache.tinkerpop.gremlin.process.traversal.step.Profiling;\nimport org.apache.tinkerpop.gremlin.process.traversal.step.util.ProfileStep;\nimport org.apache.tinkerpop.gremlin.process.traversal.strategy.optimization.CountStrategy;\nimport org.apache.tinkerpop.gremlin.process.traversal.strategy.optimization.LazyBarrierStrategy;\nimport org.apache.tinkerpop.gremlin.process.traversal.strategy.optimization.RepeatUnrollStrategy;\nimport org.apache.tinkerpop.gremlin.process.traversal.strategy.verification.ComputerVerificationStrategy;\nimport org.apache.tinkerpop.gremlin.process.traversal.strategy.verification.VerificationException;\nimport org.apache.tinkerpop.gremlin.process.traversal.util.Metrics;\nimport org.apache.tinkerpop.gremlin.process.traversal.util.MutableMetrics;\nimport org.apache.tinkerpop.gremlin.process.traversal.util.TraversalHelper;\nimport org.apache.tinkerpop.gremlin.process.traversal.util.TraversalMetrics;\nimport org.apache.tinkerpop.gremlin.structure.Graph;\nimport org.apache.tinkerpop.gremlin.structure.Vertex;\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\n\nimport java.util.ArrayList;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.concurrent.TimeUnit;\n\nimport static org.apache.tinkerpop.gremlin.LoadGraphWith.GraphData.GRATEFUL;\nimport static org.apache.tinkerpop.gremlin.LoadGraphWith.GraphData.MODERN;\nimport static org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__.both;\nimport static org.hamcrest.core.IsEqual.equalTo;\nimport static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.assertFalse;\nimport static org.junit.Assert.assertNotEquals;\nimport static org.junit.Assert.assertTrue;\nimport static org.junit.Assert.fail;\nimport static org.junit.Assume.assumeThat;\n\n/**\n * @author Bob Briody (http://bobbriody.com)\n * @author Marko A. Rodriguez (http://markorodriguez.com)\n */\n@RunWith(GremlinProcessRunner.class)\npublic abstract class ProfileTest extends AbstractGremlinProcessTest {\n private static final String METRICS_KEY = \"metrics\";\n\n public abstract Traversal get_g_V_out_out_profile();\n\n public abstract Traversal get_g_V_repeatXbothX_timesX3X_profile();\n\n public abstract Traversal get_g_V_sideEffectXThread_sleepX10XX_sideEffectXThread_sleepX5XX_profile();\n\n public abstract Traversal get_g_V_whereXinXcreatedX_count_isX1XX_name_profile();\n\n public abstract Traversal get_g_V_matchXa_created_b__b_in_count_isXeqX1XXX_selectXa_bX_profile();\n\n public abstract Traversal get_g_V_out_out_profileXmetricsX();\n\n public abstract Traversal get_g_V_repeatXbothX_timesX3X_profileXmetricsX();\n\n public abstract Traversal get_g_V_sideEffectXThread_sleepX10XX_sideEffectXThread_sleepX5XX_profileXmetricsX();\n\n public abstract Traversal get_g_V_whereXinXcreatedX_count_isX1XX_name_profileXmetricsX();\n\n public abstract Traversal> get_g_V_matchXa_created_b__b_in_count_isXeqX1XXX_selectXa_bX_profileXmetricsX();\n\n public abstract Traversal get_g_V_hasLabelXpersonX_pageRank_withXpropertyName_rankX_withXedges_bothEX_rank_profile();\n\n public abstract Traversal get_g_V_groupXmX_profile();\n\n @Override\n protected void afterLoadGraphWith(final Graph graph) throws Exception {\n // profile() does some explicit counting which goes off with LazyBarrierStrategy in place.\n g = g.withoutStrategies(LazyBarrierStrategy.class);\n }\n\n @Test\n @LoadGraphWith(MODERN)\n public void modern_V_out_out_profile() {\n final Traversal traversal = get_g_V_out_out_profile();\n printTraversalForm(traversal);\n validate_g_V_out_out_profile_modern(traversal, traversal.next());\n }\n\n @Test\n @LoadGraphWith(MODERN)\n public void modern_V_out_out_profileXmetricsX() {\n final Traversal traversal = get_g_V_out_out_profileXmetricsX();\n printTraversalForm(traversal);\n traversal.iterate();\n validate_g_V_out_out_profile_modern(traversal, traversal.asAdmin().getSideEffects().get(METRICS_KEY));\n }\n\n private void validate_g_V_out_out_profile_modern(final Traversal traversal, final TraversalMetrics traversalMetrics) {\n traversalMetrics.toString(); // ensure no exceptions are thrown\n\n assumeThat(\"The following assertions apply to TinkerGraph only as provider strategies can alter the steps to not comply with expectations\",\n graph.getClass().getSimpleName(), equalTo(\"TinkerGraph\"));\n\n Metrics metrics = traversalMetrics.getMetrics(0);\n assertEquals(6, metrics.getCount(TraversalMetrics.TRAVERSER_COUNT_ID).longValue());\n assertEquals(6, metrics.getCount(TraversalMetrics.ELEMENT_COUNT_ID).longValue());\n\n metrics = traversalMetrics.getMetrics(1);\n assertEquals(6, metrics.getCount(TraversalMetrics.ELEMENT_COUNT_ID).longValue());\n assertNotEquals(0, metrics.getCount(TraversalMetrics.TRAVERSER_COUNT_ID).longValue());\n\n metrics = traversalMetrics.getMetrics(2);\n assertEquals(2, metrics.getCount(TraversalMetrics.ELEMENT_COUNT_ID).longValue());\n assertNotEquals(0, metrics.getCount(TraversalMetrics.TRAVERSER_COUNT_ID).longValue());\n\n if (!onGraphComputer(traversal.asAdmin())) {\n // Every other step should be a Profile step\n List steps = traversal.asAdmin().getSteps();\n for (int ii = 1; ii <= 6; ii += 2) {\n assertEquals(\"Every other Step should be a ProfileStep.\", ProfileStep.class, steps.get(ii).getClass());\n }\n }\n }\n\n ////////////////////\n\n @Test\n @LoadGraphWith(GRATEFUL)\n public void grateful_V_out_out_profile() {\n final Traversal traversal = get_g_V_out_out_profile();\n printTraversalForm(traversal);\n final TraversalMetrics traversalMetrics = traversal.next();\n validate_g_V_out_out_profile_grateful(traversalMetrics);\n }\n\n @Test\n @LoadGraphWith(GRATEFUL)\n public void grateful_V_out_out_profileXmetricsX() {\n final Traversal traversal = get_g_V_out_out_profileXmetricsX();\n printTraversalForm(traversal);\n traversal.iterate();\n final TraversalMetrics traversalMetrics = traversal.asAdmin().getSideEffects().get(METRICS_KEY);\n validate_g_V_out_out_profile_grateful(traversalMetrics);\n }\n\n private void validate_g_V_out_out_profile_grateful(final TraversalMetrics traversalMetrics) {\n traversalMetrics.toString(); // ensure no exceptions are thrown\n\n assumeThat(\"The following assertions apply to TinkerGraph only as provider strategies can alter the steps to not comply with expectations\",\n graph.getClass().getSimpleName(), equalTo(\"TinkerGraph\"));\n\n Metrics metrics = traversalMetrics.getMetrics(0);\n assertEquals(808, metrics.getCount(TraversalMetrics.TRAVERSER_COUNT_ID).longValue());\n assertEquals(808, metrics.getCount(TraversalMetrics.ELEMENT_COUNT_ID).longValue());\n assertTrue(\"Percent duration should be positive.\", (Double) metrics.getAnnotation(TraversalMetrics.PERCENT_DURATION_KEY) >= 0);\n assertTrue(\"Times should be positive.\", metrics.getDuration(TimeUnit.MICROSECONDS) >= 0);\n\n metrics = traversalMetrics.getMetrics(1);\n assertEquals(8049, metrics.getCount(TraversalMetrics.ELEMENT_COUNT_ID).longValue());\n assertNotEquals(0, metrics.getCount(TraversalMetrics.TRAVERSER_COUNT_ID).longValue());\n assertTrue(\"Percent duration should be positive.\", (Double) metrics.getAnnotation(TraversalMetrics.PERCENT_DURATION_KEY) >= 0);\n assertTrue(\"Times should be positive.\", metrics.getDuration(TimeUnit.MICROSECONDS) >= 0);\n\n metrics = traversalMetrics.getMetrics(2);\n assertEquals(327370, metrics.getCount(TraversalMetrics.ELEMENT_COUNT_ID).longValue());\n assertNotEquals(0, metrics.getCount(TraversalMetrics.TRAVERSER_COUNT_ID).longValue());\n assertTrue(\"Percent duration should be positive.\", (Double) metrics.getAnnotation(TraversalMetrics.PERCENT_DURATION_KEY) >= 0);\n assertTrue(\"Times should be positive.\", metrics.getDuration(TimeUnit.MICROSECONDS) >= 0);\n\n double totalPercentDuration = 0;\n for (Metrics m : traversalMetrics.getMetrics()) {\n totalPercentDuration += (Double) m.getAnnotation(TraversalMetrics.PERCENT_DURATION_KEY);\n }\n assertEquals(100, totalPercentDuration, 0.000001);\n }\n\n ///////////////////\n\n @Test\n @LoadGraphWith(MODERN)\n @IgnoreEngine(TraversalEngine.Type.COMPUTER)\n public void g_V_sideEffectXThread_sleepX10XX_sideEffectXThread_sleepX5XX_profile() {\n final Traversal traversal = get_g_V_sideEffectXThread_sleepX10XX_sideEffectXThread_sleepX5XX_profile();\n printTraversalForm(traversal);\n\n // This assertion is really only meant for tinkergraph\n if (graph.getClass().getSimpleName().equals(\"TinkerGraph\"))\n assertEquals(\"There should be 8 steps in this traversal (counting injected profile steps).\", 8, traversal.asAdmin().getSteps().size());\n\n final TraversalMetrics traversalMetrics = traversal.next();\n validate_g_V_sideEffectXThread_sleepX10XX_sideEffectXThread_sleepX5XX_profile(traversalMetrics);\n }\n\n @Test\n @LoadGraphWith(MODERN)\n @IgnoreEngine(TraversalEngine.Type.COMPUTER)\n public void g_V_sideEffectXThread_sleepX10XX_sideEffectXThread_sleepX5XX_profileXmetricsX() {\n final Traversal traversal = get_g_V_sideEffectXThread_sleepX10XX_sideEffectXThread_sleepX5XX_profileXmetricsX();\n printTraversalForm(traversal);\n traversal.iterate();\n\n // This assertion is really only meant for tinkergraph\n if (graph.getClass().getSimpleName().equals(\"TinkerGraph\"))\n assertEquals(\"There should be 7 steps in this traversal (counting injected profile steps).\", 7, traversal.asAdmin().getSteps().size());\n\n final TraversalMetrics traversalMetrics = traversal.asAdmin().getSideEffects().get(METRICS_KEY);\n validate_g_V_sideEffectXThread_sleepX10XX_sideEffectXThread_sleepX5XX_profile(traversalMetrics);\n }\n\n private void validate_g_V_sideEffectXThread_sleepX10XX_sideEffectXThread_sleepX5XX_profile(final TraversalMetrics traversalMetrics) {\n traversalMetrics.toString(); // ensure no exceptions are thrown\n\n assumeThat(\"The following assertions apply to TinkerGraph only as provider strategies can alter the steps to not comply with expectations\",\n graph.getClass().getSimpleName(), equalTo(\"TinkerGraph\"));\n\n // Grab the second (sideEffect{sleep}) step and check the times.\n Metrics metrics = traversalMetrics.getMetrics(1);\n // 6 elements w/ a 10ms sleep each = 60ms with 10ms for other computation.\n assertTrue(\"Duration should be at least the length of the sleep (59ms): \" + metrics.getDuration(TimeUnit.MILLISECONDS),\n metrics.getDuration(TimeUnit.MILLISECONDS) >= 59);\n\n // 6 elements w/ a 5ms sleep each = 30ms plus 20ms for other computation\n metrics = traversalMetrics.getMetrics(2);\n assertTrue(\"Duration should be at least the length of the sleep (29ms): \" + metrics.getDuration(TimeUnit.MILLISECONDS),\n metrics.getDuration(TimeUnit.MILLISECONDS) >= 29);\n\n double totalPercentDuration = 0;\n for (Metrics m : traversalMetrics.getMetrics()) {\n totalPercentDuration += (Double) m.getAnnotation(TraversalMetrics.PERCENT_DURATION_KEY);\n }\n assertEquals(100, totalPercentDuration, 0.000001);\n }\n\n ///////////////////\n\n @Test\n @LoadGraphWith(MODERN)\n public void g_V_repeat_both_profile() {\n final Traversal traversal = get_g_V_repeatXbothX_timesX3X_profile();\n printTraversalForm(traversal);\n\n final TraversalMetrics traversalMetrics = traversal.next();\n validate_g_V_repeat_both_modern_profile(traversalMetrics,\n traversal.asAdmin().getStrategies().getStrategy(RepeatUnrollStrategy.class).isPresent() &&\n !traversal.asAdmin().getStrategies().getStrategy(ComputerVerificationStrategy.class).isPresent());\n }\n\n @Test\n @LoadGraphWith(MODERN)\n public void g_V_repeat_both_profileXmetricsX() {\n final Traversal traversal = get_g_V_repeatXbothX_timesX3X_profileXmetricsX();\n printTraversalForm(traversal);\n traversal.iterate();\n final TraversalMetrics traversalMetrics = traversal.asAdmin().getSideEffects().get(METRICS_KEY);\n validate_g_V_repeat_both_modern_profile(traversalMetrics,\n traversal.asAdmin().getStrategies().getStrategy(RepeatUnrollStrategy.class).isPresent() &&\n !traversal.asAdmin().getStrategies().getStrategy(ComputerVerificationStrategy.class).isPresent());\n }\n\n private void validate_g_V_repeat_both_modern_profile(final TraversalMetrics traversalMetrics, final boolean withRepeatUnrollStrategy) {\n traversalMetrics.toString(); // ensure no exceptions are thrown\n\n assumeThat(\"The following assertions apply to TinkerGraph only as provider strategies can alter the steps to not comply with expectations\",\n graph.getClass().getSimpleName(), equalTo(\"TinkerGraph\"));\n\n Metrics metrics = traversalMetrics.getMetrics(0);\n assertEquals(6, metrics.getCount(TraversalMetrics.TRAVERSER_COUNT_ID).longValue());\n assertEquals(6, metrics.getCount(TraversalMetrics.ELEMENT_COUNT_ID).longValue());\n\n metrics = traversalMetrics.getMetrics(1);\n assertEquals(withRepeatUnrollStrategy ? 12 : 72, metrics.getCount(TraversalMetrics.ELEMENT_COUNT_ID).longValue());\n assertNotEquals(0, metrics.getCount(TraversalMetrics.TRAVERSER_COUNT_ID).longValue());\n if (!withRepeatUnrollStrategy)\n assertTrue(\"Count should be greater than traversers.\", metrics.getCount(TraversalMetrics.ELEMENT_COUNT_ID) > metrics.getCount(TraversalMetrics.TRAVERSER_COUNT_ID).longValue());\n assertTrue(\"Percent duration should be positive.\", (Double) metrics.getAnnotation(TraversalMetrics.PERCENT_DURATION_KEY) >= 0);\n assertTrue(\"Times should be positive.\", metrics.getDuration(TimeUnit.MICROSECONDS) >= 0);\n\n // Test the nested global metrics of the repeat step\n if (!withRepeatUnrollStrategy) {\n final Metrics vertexStepNestedInRepeat = (Metrics) metrics.getNested().toArray()[0];\n assertEquals(114, vertexStepNestedInRepeat.getCount(TraversalMetrics.ELEMENT_COUNT_ID).longValue());\n assertNotEquals(0, vertexStepNestedInRepeat.getCount(TraversalMetrics.TRAVERSER_COUNT_ID).longValue());\n assertTrue(\"Count should be greater than traversers.\", vertexStepNestedInRepeat.getCount(TraversalMetrics.ELEMENT_COUNT_ID) > vertexStepNestedInRepeat.getCount(TraversalMetrics.TRAVERSER_COUNT_ID).longValue());\n assertTrue(\"Times should be positive.\", vertexStepNestedInRepeat.getDuration(TimeUnit.MICROSECONDS) >= 0);\n }\n\n double totalPercentDuration = 0;\n for (Metrics m : traversalMetrics.getMetrics()) {\n totalPercentDuration += (Double) m.getAnnotation(TraversalMetrics.PERCENT_DURATION_KEY);\n }\n assertEquals(100, totalPercentDuration, 0.000001);\n }\n\n /////////////\n\n private void validate_g_V_whereXinXcreatedX_count_isX1XX_name_profile(final Traversal traversal, final TraversalMetrics traversalMetrics) {\n traversalMetrics.toString(); // ensure no exceptions are thrown\n\n assumeThat(\"The following assertions apply to TinkerGraph only as provider strategies can alter the steps to not comply with expectations\",\n graph.getClass().getSimpleName(), equalTo(\"TinkerGraph\"));\n\n assertEquals(\"There should be 3 top-level metrics.\", 3, traversalMetrics.getMetrics().size());\n\n Metrics metrics = traversalMetrics.getMetrics(0);\n assertEquals(6, metrics.getCount(TraversalMetrics.TRAVERSER_COUNT_ID).longValue());\n assertEquals(6, metrics.getCount(TraversalMetrics.ELEMENT_COUNT_ID).longValue());\n\n metrics = traversalMetrics.getMetrics(1);\n assertEquals(1, metrics.getCount(TraversalMetrics.TRAVERSER_COUNT_ID).longValue());\n assertEquals(1, metrics.getCount(TraversalMetrics.ELEMENT_COUNT_ID).longValue());\n\n if (traversal.asAdmin().getStrategies().getStrategy(CountStrategy.class).isPresent()) {\n assertEquals(\"Metrics 1 should have 4 nested metrics.\", 4, metrics.getNested().size());\n } else {\n assertEquals(\"Metrics 1 should have 3 nested metrics.\", 3, metrics.getNested().size());\n }\n }\n\n @Test\n @LoadGraphWith(MODERN)\n public void g_V_whereXinXcreatedX_count_isX1XX_name_profile() {\n final Traversal traversal = get_g_V_whereXinXcreatedX_count_isX1XX_name_profile();\n printTraversalForm(traversal);\n final TraversalMetrics traversalMetrics = traversal.next();\n validate_g_V_whereXinXcreatedX_count_isX1XX_name_profile(traversal, traversalMetrics);\n }\n\n @Test\n @LoadGraphWith(MODERN)\n public void g_V_whereXinXcreatedX_count_isX1XX_name_profileXmetricsX() {\n final Traversal traversal = get_g_V_whereXinXcreatedX_count_isX1XX_name_profileXmetricsX();\n printTraversalForm(traversal);\n traversal.iterate();\n final TraversalMetrics traversalMetrics = traversal.asAdmin().getSideEffects().get(METRICS_KEY);\n validate_g_V_whereXinXcreatedX_count_isX1XX_name_profile(traversal, traversalMetrics);\n }\n\n /**\n * ProfileStrategy callback test. Goal: ensure that a step that implements Profileable gets a callback to setMetrics\n */\n\n // Setup a \"mock\" step to test the strategy\n static public class MockStep extends FlatMapStep implements Profiling {\n public static boolean callbackCalled = false;\n\n public MockStep(final Traversal.Admin traversal) {\n super(traversal);\n }\n\n @Override\n protected Iterator flatMap(final Traverser.Admin traverser) {\n List l = new ArrayList<>();\n l.add(traverser.get());\n return l.iterator();\n }\n\n @Override\n public void setMetrics(final MutableMetrics parentMetrics) {\n if (parentMetrics != null) {\n callbackCalled = true;\n parentMetrics.setCount(\"bogusCount\", 100);\n }\n }\n }\n\n @Test\n @LoadGraphWith(MODERN)\n public void testProfileStrategyCallback() {\n final Traversal t = get_g_V_out_out_profile();\n MockStep mockStep = new MockStep(t.asAdmin());\n t.asAdmin().addStep(3, mockStep);\n TraversalMetrics traversalMetrics = t.next();\n assertTrue(mockStep.callbackCalled);\n\n if (!onGraphComputer(t.asAdmin())) {\n assertEquals(100, traversalMetrics.getMetrics(3).getCount(\"bogusCount\").longValue());\n }\n }\n\n @Test\n @LoadGraphWith(MODERN)\n public void testProfileStrategyCallbackSideEffect() {\n final Traversal t = get_g_V_out_out_profileXmetricsX();\n MockStep mockStep = new MockStep(t.asAdmin());\n t.asAdmin().addStep(3, mockStep);\n t.iterate();\n assertTrue(mockStep.callbackCalled);\n\n if (!onGraphComputer(t.asAdmin())) {\n final TraversalMetrics traversalMetrics = t.asAdmin().getSideEffects().get(METRICS_KEY);", "answers": [" assertEquals(100, traversalMetrics.getMetrics(3).getCount(\"bogusCount\").longValue());"], "length": 1342, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "faf80336-d9da-459e-8782-dfde5631183b", "reasoning": "In the testProfileStrategyCallbackSideEffect method, after iterating the traversal and confirming the mock step's callback was called, the code retrieves the TraversalMetrics from side effects. The next logical step is to assert that the mock step correctly set the bogusCount metric, mirroring the earlier test that used t.next(). Therefore the next line should assert the count value of \"bogusCount\" at index 3 equals 100.", "reasoning_model_answer": "assertEquals(100, traversalMetrics.getMetrics(3).getCount(\"bogusCount\").longValue());", "assistant_with_reasoning": "\nIn the testProfileStrategyCallbackSideEffect method, after iterating the traversal and confirming the mock step's callback was called, the code retrieves the TraversalMetrics from side effects. The next logical step is to assert that the mock step correctly set the bogusCount metric, mirroring the earlier test that used t.next(). Therefore the next line should assert the count value of \"bogusCount\" at index 3 equals 100.\n\nassertEquals(100, traversalMetrics.getMetrics(3).getCount(\"bogusCount\").longValue());", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.961, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 21757, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "assertEquals(100, traversalMetrics.getMetrics(3).getCount(\"bogusCount\").longValue());", "score": 0.93, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/*\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.facebook.presto.sql.analyzer;\n\nimport com.facebook.presto.Session;\nimport com.facebook.presto.metadata.Metadata;\nimport com.facebook.presto.metadata.MetadataUtil;\nimport com.facebook.presto.metadata.QualifiedTableName;\nimport com.facebook.presto.metadata.TableHandle;\nimport com.facebook.presto.spi.ColumnMetadata;\nimport com.facebook.presto.spi.CreateTableOption;\nimport com.facebook.presto.spi.InsertOption;\nimport com.facebook.presto.spi.SchemaTableName;\nimport com.facebook.presto.spi.type.Type;\nimport com.facebook.presto.sql.parser.SqlParser;\nimport com.facebook.presto.sql.tree.AllColumns;\nimport com.facebook.presto.sql.tree.BooleanLiteral;\nimport com.facebook.presto.sql.tree.Cast;\nimport com.facebook.presto.sql.tree.CreateTableAsSelect;\nimport com.facebook.presto.sql.tree.CreateView;\nimport com.facebook.presto.sql.tree.DefaultTraversalVisitor;\nimport com.facebook.presto.sql.tree.Delete;\nimport com.facebook.presto.sql.tree.DoubleLiteral;\nimport com.facebook.presto.sql.tree.Explain;\nimport com.facebook.presto.sql.tree.ExplainFormat;\nimport com.facebook.presto.sql.tree.ExplainOption;\nimport com.facebook.presto.sql.tree.ExplainType;\nimport com.facebook.presto.sql.tree.Expression;\nimport com.facebook.presto.sql.tree.GenericLiteral;\nimport com.facebook.presto.sql.tree.Insert;\nimport com.facebook.presto.sql.tree.LikePredicate;\nimport com.facebook.presto.sql.tree.LongLiteral;\nimport com.facebook.presto.sql.tree.PartitionElement;\nimport com.facebook.presto.sql.tree.QualifiedName;\nimport com.facebook.presto.sql.tree.Query;\nimport com.facebook.presto.sql.tree.Relation;\nimport com.facebook.presto.sql.tree.SelectItem;\nimport com.facebook.presto.sql.tree.ShowCatalogs;\nimport com.facebook.presto.sql.tree.ShowColumns;\nimport com.facebook.presto.sql.tree.ShowFunctions;\nimport com.facebook.presto.sql.tree.ShowPartitions;\nimport com.facebook.presto.sql.tree.ShowSchemas;\nimport com.facebook.presto.sql.tree.ShowSession;\nimport com.facebook.presto.sql.tree.ShowTables;\nimport com.facebook.presto.sql.tree.SingleColumn;\nimport com.facebook.presto.sql.tree.SortItem;\nimport com.facebook.presto.sql.tree.Statement;\nimport com.facebook.presto.sql.tree.StringLiteral;\nimport com.facebook.presto.sql.tree.TimeLiteral;\nimport com.facebook.presto.sql.tree.TimestampLiteral;\nimport com.facebook.presto.sql.tree.Use;\nimport com.facebook.presto.sql.tree.Values;\nimport com.facebook.presto.sql.tree.With;\nimport com.facebook.presto.sql.tree.WithQuery;\nimport com.facebook.presto.util.DateTimeUtils;\nimport com.google.common.base.Joiner;\nimport com.google.common.collect.FluentIterable;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.primitives.Ints;\n\nimport java.util.Date;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.Iterator;\nimport java.util.LinkedHashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Map.Entry;\nimport java.util.Optional;\nimport java.util.Set;\nimport java.util.TreeMap;\n\nimport static com.facebook.presto.connector.informationSchema.InformationSchemaMetadata.TABLE_COLUMNS;\nimport static com.facebook.presto.connector.informationSchema.InformationSchemaMetadata.TABLE_INTERNAL_FUNCTIONS;\nimport static com.facebook.presto.connector.informationSchema.InformationSchemaMetadata.TABLE_INTERNAL_PARTITIONS;\nimport static com.facebook.presto.connector.informationSchema.InformationSchemaMetadata.TABLE_SCHEMATA;\nimport static com.facebook.presto.connector.informationSchema.InformationSchemaMetadata.TABLE_TABLES;\nimport static com.facebook.presto.spi.type.BigintType.BIGINT;\nimport static com.facebook.presto.sql.QueryUtil.aliased;\nimport static com.facebook.presto.sql.QueryUtil.aliasedName;\nimport static com.facebook.presto.sql.QueryUtil.aliasedNullToEmpty;\nimport static com.facebook.presto.sql.QueryUtil.aliasedYesNoToBoolean;\nimport static com.facebook.presto.sql.QueryUtil.ascending;\nimport static com.facebook.presto.sql.QueryUtil.caseWhen;\nimport static com.facebook.presto.sql.QueryUtil.equal;\nimport static com.facebook.presto.sql.QueryUtil.functionCall;\nimport static com.facebook.presto.sql.QueryUtil.logicalAnd;\nimport static com.facebook.presto.sql.QueryUtil.nameReference;\nimport static com.facebook.presto.sql.QueryUtil.ordering;\nimport static com.facebook.presto.sql.QueryUtil.row;\nimport static com.facebook.presto.sql.QueryUtil.selectAll;\nimport static com.facebook.presto.sql.QueryUtil.selectList;\nimport static com.facebook.presto.sql.QueryUtil.simpleQuery;\nimport static com.facebook.presto.sql.QueryUtil.subquery;\nimport static com.facebook.presto.sql.QueryUtil.table;\nimport static com.facebook.presto.sql.QueryUtil.unaliasedName;\nimport static com.facebook.presto.sql.QueryUtil.values;\nimport static com.facebook.presto.sql.analyzer.SemanticErrorCode.COLUMN_NAME_NOT_SPECIFIED;\nimport static com.facebook.presto.sql.analyzer.SemanticErrorCode.DUPLICATE_COLUMN_NAME;\nimport static com.facebook.presto.sql.analyzer.SemanticErrorCode.DUPLICATE_RELATION;\nimport static com.facebook.presto.sql.analyzer.SemanticErrorCode.INVALID_ORDINAL;\nimport static com.facebook.presto.sql.analyzer.SemanticErrorCode.INVALID_SCHEMA_NAME;\nimport static com.facebook.presto.sql.analyzer.SemanticErrorCode.MISMATCHED_SET_COLUMN_TYPES;\nimport static com.facebook.presto.sql.analyzer.SemanticErrorCode.MISSING_TABLE;\nimport static com.facebook.presto.sql.analyzer.SemanticErrorCode.NOT_SUPPORTED;\nimport static com.facebook.presto.sql.analyzer.SemanticErrorCode.TABLE_ALREADY_EXISTS;\nimport static com.facebook.presto.sql.analyzer.SemanticErrorCode.UNSUPPORTED_PARTITION_TYPE;\nimport static com.facebook.presto.sql.analyzer.SemanticErrorCode.INVALID_PARTITION_VALUE;\nimport static com.facebook.presto.sql.analyzer.SemanticErrorCode.MISSING_PARTITION;\nimport static com.facebook.presto.sql.analyzer.SemanticErrorCode.MISMATCHED_PARTITION_NAME;\nimport static com.facebook.presto.sql.analyzer.SemanticErrorCode.DUPLICATE_PARTITION_NAME;\nimport static com.facebook.presto.sql.tree.BooleanLiteral.FALSE_LITERAL;\nimport static com.facebook.presto.sql.tree.BooleanLiteral.TRUE_LITERAL;\nimport static com.facebook.presto.sql.tree.ExplainFormat.Type.TEXT;\nimport static com.facebook.presto.sql.tree.ExplainType.Type.LOGICAL;\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Preconditions.checkState;\nimport static com.google.common.collect.Iterables.elementsEqual;\nimport static com.google.common.collect.Iterables.transform;\nimport static com.google.common.collect.Iterables.contains;\nimport static java.util.stream.Collectors.toList;\n\nclass StatementAnalyzer\n extends DefaultTraversalVisitor\n{\n private final Analysis analysis;\n private final Metadata metadata;\n private final Session session;\n private final Optional queryExplainer;\n private final boolean experimentalSyntaxEnabled;\n private final SqlParser sqlParser;\n\n public StatementAnalyzer(\n Analysis analysis,\n Metadata metadata,\n SqlParser sqlParser,\n Session session,\n boolean experimentalSyntaxEnabled,\n Optional queryExplainer)\n {\n this.analysis = checkNotNull(analysis, \"analysis is null\");\n this.metadata = checkNotNull(metadata, \"metadata is null\");\n this.sqlParser = checkNotNull(sqlParser, \"sqlParser is null\");\n this.session = checkNotNull(session, \"session is null\");\n this.experimentalSyntaxEnabled = experimentalSyntaxEnabled;\n this.queryExplainer = checkNotNull(queryExplainer, \"queryExplainer is null\");\n }\n\n @Override\n protected TupleDescriptor visitShowTables(ShowTables showTables, AnalysisContext context)\n {\n String catalogName = session.getCatalog();\n String schemaName = session.getSchema();\n\n Optional schema = showTables.getSchema();\n if (schema.isPresent()) {\n List parts = schema.get().getParts();\n if (parts.size() > 2) {\n throw new SemanticException(INVALID_SCHEMA_NAME, showTables, \"too many parts in schema name: %s\", schema);\n }\n if (parts.size() == 2) {\n catalogName = parts.get(0);\n }\n schemaName = schema.get().getSuffix();\n }\n\n // TODO: throw SemanticException if schema does not exist\n\n Expression predicate = equal(nameReference(\"table_schema\"), new StringLiteral(schemaName));\n\n Optional likePattern = showTables.getLikePattern();\n if (likePattern.isPresent()) {\n Expression likePredicate = new LikePredicate(nameReference(\"table_name\"), new StringLiteral(likePattern.get()), null);\n predicate = logicalAnd(predicate, likePredicate);\n }\n\n Query query = simpleQuery(\n selectList(aliasedName(\"table_name\", \"Table\")),\n from(catalogName, TABLE_TABLES),\n predicate,\n ordering(ascending(\"table_name\")));\n\n return process(query, context);\n }\n\n @Override\n protected TupleDescriptor visitShowSchemas(ShowSchemas node, AnalysisContext context)\n {\n Query query = simpleQuery(\n selectList(aliasedName(\"schema_name\", \"Schema\")),\n from(node.getCatalog().orElse(session.getCatalog()), TABLE_SCHEMATA),\n ordering(ascending(\"schema_name\")));\n\n return process(query, context);\n }\n\n @Override\n protected TupleDescriptor visitShowCatalogs(ShowCatalogs node, AnalysisContext context)\n {\n List rows = metadata.getCatalogNames().keySet().stream()\n .map(name -> row(new StringLiteral(name)))\n .collect(toList());\n\n Query query = simpleQuery(\n selectList(new AllColumns()),\n aliased(new Values(rows), \"catalogs\", ImmutableList.of(\"Catalog\")));\n\n return process(query, context);\n }\n\n @Override\n protected TupleDescriptor visitShowColumns(ShowColumns showColumns, AnalysisContext context)\n {\n QualifiedTableName tableName = MetadataUtil.createQualifiedTableName(session, showColumns.getTable());\n\n if (!metadata.getView(session, tableName).isPresent() &&\n !metadata.getTableHandle(session, tableName).isPresent()) {\n throw new SemanticException(MISSING_TABLE, showColumns, \"Table '%s' does not exist\", tableName);\n }\n\n Query query = simpleQuery(\n selectList(\n aliasedName(\"column_name\", \"Column\"),\n aliasedName(\"data_type\", \"Type\"),\n aliasedYesNoToBoolean(\"is_nullable\", \"Null\"),\n aliasedYesNoToBoolean(\"is_partition_key\", \"Partition Key\"),\n aliasedNullToEmpty(\"comment\", \"Comment\")),\n from(tableName.getCatalogName(), TABLE_COLUMNS),\n logicalAnd(\n equal(nameReference(\"table_schema\"), new StringLiteral(tableName.getSchemaName())),\n equal(nameReference(\"table_name\"), new StringLiteral(tableName.getTableName()))),\n ordering(ascending(\"ordinal_position\")));\n\n return process(query, context);\n }\n\n @Override\n protected TupleDescriptor visitUse(Use node, AnalysisContext context)\n {\n analysis.setUpdateType(\"USE\");\n throw new SemanticException(NOT_SUPPORTED, node, \"USE statement is not supported\");\n }\n\n @Override\n protected TupleDescriptor visitShowPartitions(ShowPartitions showPartitions, AnalysisContext context)\n {\n QualifiedTableName table = MetadataUtil.createQualifiedTableName(session, showPartitions.getTable());\n Optional tableHandle = metadata.getTableHandle(session, table);\n if (!tableHandle.isPresent()) {\n throw new SemanticException(MISSING_TABLE, showPartitions, \"Table '%s' does not exist\", table);\n }\n\n /*\n Generate a dynamic pivot to output one column per partition key.\n For example, a table with two partition keys (ds, cluster_name)\n would generate the following query:\n\n SELECT\n partition_number\n , max(CASE WHEN partition_key = 'ds' THEN partition_value END) ds\n , max(CASE WHEN partition_key = 'cluster_name' THEN partition_value END) cluster_name\n FROM ...\n GROUP BY partition_number\n\n The values are also cast to the type of the partition column.\n The query is then wrapped to allow custom filtering and ordering.\n */\n\n ImmutableList.Builder selectList = ImmutableList.builder();\n ImmutableList.Builder wrappedList = ImmutableList.builder();\n selectList.add(unaliasedName(\"partition_number\"));\n for (ColumnMetadata column : metadata.getTableMetadata(tableHandle.get()).getColumns()) {\n if (!column.isPartitionKey()) {\n continue;\n }\n Expression key = equal(nameReference(\"partition_key\"), new StringLiteral(column.getName()));\n Expression value = caseWhen(key, nameReference(\"partition_value\"));\n value = new Cast(value, column.getType().getTypeSignature().toString());\n Expression function = functionCall(\"max\", value);\n selectList.add(new SingleColumn(function, column.getName()));\n wrappedList.add(unaliasedName(column.getName()));\n }\n\n Query query = simpleQuery(\n selectAll(selectList.build()),\n from(table.getCatalogName(), TABLE_INTERNAL_PARTITIONS),\n Optional.of(logicalAnd(\n equal(nameReference(\"table_schema\"), new StringLiteral(table.getSchemaName())),\n equal(nameReference(\"table_name\"), new StringLiteral(table.getTableName())))),\n ImmutableList.of(nameReference(\"partition_number\")),\n Optional.empty(),\n ImmutableList.of(),\n Optional.empty());\n\n query = simpleQuery(\n selectAll(wrappedList.build()),\n subquery(query),\n showPartitions.getWhere(),\n ImmutableList.of(),\n Optional.empty(),\n ImmutableList.builder()\n .addAll(showPartitions.getOrderBy())\n .add(ascending(\"partition_number\"))\n .build(),\n showPartitions.getLimit());\n\n return process(query, context);\n }\n\n @Override\n protected TupleDescriptor visitShowFunctions(ShowFunctions node, AnalysisContext context)\n {\n Query query = simpleQuery(selectList(\n aliasedName(\"function_name\", \"Function\"),\n aliasedName(\"return_type\", \"Return Type\"),\n aliasedName(\"argument_types\", \"Argument Types\"),\n aliasedName(\"function_type\", \"Function Type\"),\n aliasedName(\"deterministic\", \"Deterministic\"),\n aliasedName(\"description\", \"Description\")),\n from(session.getCatalog(), TABLE_INTERNAL_FUNCTIONS),\n ordering(\n ascending(\"function_name\"),\n ascending(\"return_type\"),\n ascending(\"argument_types\"),\n ascending(\"function_type\")));\n\n return process(query, context);\n }\n\n @Override\n protected TupleDescriptor visitShowSession(ShowSession node, AnalysisContext context)\n {\n ImmutableList.Builder rows = ImmutableList.builder();\n for (Entry property : new TreeMap<>(session.getSystemProperties()).entrySet()) {\n rows.add(row(\n new StringLiteral(property.getKey()),\n new StringLiteral(property.getValue()),\n TRUE_LITERAL));\n }\n for (Entry> entry : new TreeMap<>(session.getCatalogProperties()).entrySet()) {\n String catalog = entry.getKey();\n for (Entry property : new TreeMap<>(entry.getValue()).entrySet()) {\n rows.add(row(\n new StringLiteral(catalog + \".\" + property.getKey()),\n new StringLiteral(property.getValue()),\n TRUE_LITERAL));\n }\n }\n\n // add bogus row so we can support empty sessions\n rows.add(row(new StringLiteral(\"\"), new StringLiteral(\"\"), FALSE_LITERAL));\n\n Query query = simpleQuery(\n selectList(\n aliasedName(\"name\", \"Name\"),\n aliasedName(\"value\", \"Value\")),\n aliased(\n new Values(rows.build()),\n \"session\",\n ImmutableList.of(\"name\", \"value\", \"include\")),\n nameReference(\"include\"));\n\n return process(query, context);\n }\n\n @Override\n protected TupleDescriptor visitInsert(Insert insert, AnalysisContext context)\n {\n analysis.setUpdateType(\"INSERT\");\n\n // analyze the query that creates the data\n TupleDescriptor descriptor = process(insert.getQuery(), context);\n\n QualifiedTableName targetTable = MetadataUtil.createQualifiedTableName(session, insert.getTarget());\n Optional targetTableHandle = metadata.getTableHandle(session, targetTable);\n if (!targetTableHandle.isPresent()) {\n throw new SemanticException(MISSING_TABLE, insert, \"Table '%s' does not exist\", targetTable);\n }\n analysis.setInsertTarget(targetTableHandle.get());\n\n List columns = metadata.getTableMetadata(targetTableHandle.get()).getColumns();\n\n analyzeInsertOption(insert, columns, targetTable);\n\n // verify the insert destination columns match the query\n Iterable tableTypes = FluentIterable.from(columns)\n .filter(column -> !column.isHidden())\n .transform(ColumnMetadata::getType);\n\n Iterable queryTypes = transform(descriptor.getVisibleFields(), Field::getType);\n\n if (!elementsEqual(tableTypes, queryTypes)) {\n throw new SemanticException(MISMATCHED_SET_COLUMN_TYPES, insert, \"Insert query has mismatched column types: \" +\n \"Table: (\" + Joiner.on(\", \").join(tableTypes) + \"), \" +\n \"Query: (\" + Joiner.on(\", \").join(queryTypes) + \")\");\n }\n\n return new TupleDescriptor(Field.newUnqualified(\"rows\", BIGINT));\n }\n\n @Override\n protected TupleDescriptor visitDelete(Delete node, AnalysisContext context)\n {\n analysis.setUpdateType(\"DELETE\");\n\n analysis.setDelete(node);\n\n TupleAnalyzer analyzer = new TupleAnalyzer(analysis, session, metadata, sqlParser, experimentalSyntaxEnabled);\n TupleDescriptor descriptor = analyzer.process(node.getTable(), context);\n node.getWhere().ifPresent(where -> analyzer.analyzeWhere(node, descriptor, context, where));\n\n return new TupleDescriptor(Field.newUnqualified(\"rows\", BIGINT));\n }\n\n private void analyzeInsertOption(Insert insert, List columns, QualifiedTableName targetTable)\n {\n boolean dynamicPartition = false;\n List targetPartitionNames = columns.stream()\n .filter(column -> column.isPartitionKey())\n .map(ColumnMetadata::getName)\n .collect(toList());\n List targetPartitionTypes = columns.stream()\n .filter(column -> column.isPartitionKey())\n .map(ColumnMetadata::getType)\n .collect(toList());\n\n if (!targetPartitionNames.isEmpty() && !insert.isPartition()) {\n throw new SemanticException(MISSING_PARTITION, insert, \"Target table '%s' is partitioned but insert query does not specifty the partition\", targetTable);\n }\n\n if (insert.isPartition() && targetPartitionNames.isEmpty()) {\n throw new SemanticException(MISSING_PARTITION, insert, \"Target table '%s' is not partitioned but insert query speciftys the partition\", targetTable);\n }\n\n HashMap partitionKeyValue = new HashMap();\n HashMap partitionTypes = new HashMap();\n LinkedHashMap partitionKeyValueInorder = new LinkedHashMap();\n\n if (insert.isPartition()) {\n dynamicPartition = analyzePartitionElements(insert, targetTable, partitionKeyValue, partitionTypes);\n }\n if (partitionKeyValue.size() != targetPartitionNames.size()) {\n throw new SemanticException(MISMATCHED_PARTITION_NAME, insert, \"Insert query has mismatched partition names\", targetTable);\n }\n else {\n int index = 0;\n for (Iterator it = targetPartitionNames.iterator(); it.hasNext(); ) {\n String partitionName = it.next();\n if (!partitionKeyValue.containsKey(partitionName)) {\n throw new SemanticException(MISMATCHED_PARTITION_NAME, insert, \"Insert query has mismatched partition names\", targetTable);\n }\n\n if (!dynamicPartition) {\n String targetPartitionType = targetPartitionTypes.get(index++).getTypeSignature().toString();\n String insertPartitionType = partitionTypes.get(partitionName);\n if (!insertPartitionType.equalsIgnoreCase(targetPartitionType)) {\n throw new SemanticException(INVALID_PARTITION_VALUE,\n insert, \"Insert query has invalid partition value, \"\n + \"partition \" + partitionName\n + \" should be of type \"\n + targetPartitionType + \" but is of type \"\n + insertPartitionType, targetTable);\n }\n }\n // reorder the partitionKeyValue as the order of select query order\n partitionKeyValueInorder.put(partitionName, partitionKeyValue.get(partitionName));\n }\n }\n analysis.setInsertOption(new InsertOption(insert.isOverwrite(), insert.isPartition(), dynamicPartition, partitionKeyValueInorder));\n }\n\n private boolean analyzePartitionElements(Insert insert, QualifiedTableName targetTable, HashMap partitionKeyValue, HashMap partitionTypes)\n {\n boolean dynamicPartition = false;\n for (PartitionElement element : insert.getPartitionElements()) {\n String partitionName = element.getName();\n String partitionValue = \"\";\n String partitionType = \"\";\n if (!element.getValue().isPresent()) {\n dynamicPartition = true;\n partitionTypes.put(partitionName, partitionType);\n partitionKeyValue.put(partitionName, partitionValue);\n continue;\n }\n Expression exp = element.getValue().get();\n\n if (partitionKeyValue.containsKey(partitionName)) {\n throw new SemanticException(DUPLICATE_PARTITION_NAME, insert, \"Insert query has duplicate partition names\", targetTable);\n }\n\n if (exp instanceof BooleanLiteral) {\n partitionType = \"boolean\";\n partitionValue = String.valueOf(((BooleanLiteral) exp).getValue());\n }\n else if (exp instanceof DoubleLiteral) {\n partitionType = \"double\";\n partitionValue = String.valueOf(((DoubleLiteral) exp).getValue());\n }\n else if (exp instanceof LongLiteral) {\n partitionType = \"bigint\";\n partitionValue = String.valueOf(((LongLiteral) exp).getValue());\n }\n else if (exp instanceof StringLiteral) {\n partitionType = \"varchar\";\n partitionValue = ((StringLiteral) exp).getValue();\n }\n else if (exp instanceof TimeLiteral) {\n partitionType = \"time\";\n long value = DateTimeUtils.parseTime(session.getTimeZoneKey(), ((TimeLiteral) exp).getValue());\n partitionValue = new java.text.SimpleDateFormat(\"HH:mm:ss.SSS\").format(new Date(value));\n }\n else if (exp instanceof TimestampLiteral) {\n partitionType = \"timestamp\";\n long value = DateTimeUtils.parseTimestamp(session.getTimeZoneKey(), ((TimestampLiteral) exp).getValue());\n partitionValue = new java.text.SimpleDateFormat(\"yyyy-MM-dd HH:mm:ss.SSS\").format(new Date(value));\n }\n else if (exp instanceof GenericLiteral) {\n GenericLiteral genericLiteral = (GenericLiteral) exp;\n partitionType = genericLiteral.getType();\n partitionValue = genericLiteral.getValue();\n if (!isPartitionTypeSupported(partitionType)) {\n throw new SemanticException(UNSUPPORTED_PARTITION_TYPE, insert, \"Unsupported partition type\", targetTable);\n }\n if (partitionType.equalsIgnoreCase(\"time\")) {\n long value = DateTimeUtils.parseTime(session.getTimeZoneKey(), partitionValue);\n partitionValue = new java.text.SimpleDateFormat(\"HH:mm:ss.SSS\").format(new Date(value));\n }\n else if (partitionType.equalsIgnoreCase(\"timestamp\")) {\n long value = DateTimeUtils.parseTimestamp(session.getTimeZoneKey(), partitionValue);\n partitionValue = new java.text.SimpleDateFormat(\"yyyy-MM-dd HH:mm:ss.SSS\").format(new Date(value));\n }\n }\n else {\n throw new SemanticException(UNSUPPORTED_PARTITION_TYPE, insert, \"Unsupported partition type\", targetTable);\n }\n\n partitionTypes.put(partitionName, partitionType);\n partitionKeyValue.put(partitionName, partitionValue);\n }\n return dynamicPartition;\n }", "answers": [" private boolean isPartitionTypeSupported(String type)"], "length": 1643, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "478d1a66-1055-4a67-bde6-8cd4aa053680", "reasoning": "The provided code ends with the closing brace of the private method analyzePartitionElements. In the original Presto StatementAnalyzer class, the next method defined after this is a helper that checks if a partition type is supported. Therefore, the next line is the method signature for that helper.", "reasoning_model_answer": "private static boolean isPartitionTypeSupported(String type)", "assistant_with_reasoning": "\nThe provided code ends with the closing brace of the private method analyzePartitionElements. In the original Presto StatementAnalyzer class, the next method defined after this is a helper that checks if a partition type is supported. Therefore, the next line is the method signature for that helper.\n\nprivate static boolean isPartitionTypeSupported(String type)", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 5.842, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 27107, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "private static boolean isPartitionTypeSupported(String type)", "score": 0.91, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "#!/usr/bin/env python\n#\n# Copyright 2007 Google Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\n\n\nfrom google.net.proto import ProtocolBuffer\nimport array\nimport dummy_thread as thread\n\n__pychecker__ = \"\"\"maxreturns=0 maxbranches=0 no-callinit\n unusednames=printElemNumber,debug_strs no-special\"\"\"\n\nif hasattr(ProtocolBuffer, 'ExtendableProtocolMessage'):\n _extension_runtime = True\n _ExtendableProtocolMessage = ProtocolBuffer.ExtendableProtocolMessage\nelse:\n _extension_runtime = False\n _ExtendableProtocolMessage = ProtocolBuffer.ProtocolMessage\n\nfrom google.appengine.datastore.datastore_v3_pb import *\nimport google.appengine.datastore.datastore_v3_pb\nfrom google.appengine.datastore.entity_pb import *\nimport google.appengine.datastore.entity_pb\nclass Request(ProtocolBuffer.ProtocolMessage):\n has_service_name_ = 0\n service_name_ = \"\"\n has_method_ = 0\n method_ = \"\"\n has_request_ = 0\n request_ = \"\"\n has_request_id_ = 0\n request_id_ = \"\"\n\n def __init__(self, contents=None):\n if contents is not None: self.MergeFromString(contents)\n\n def service_name(self): return self.service_name_\n\n def set_service_name(self, x):\n self.has_service_name_ = 1\n self.service_name_ = x\n\n def clear_service_name(self):\n if self.has_service_name_:\n self.has_service_name_ = 0\n self.service_name_ = \"\"\n\n def has_service_name(self): return self.has_service_name_\n\n def method(self): return self.method_\n\n def set_method(self, x):\n self.has_method_ = 1\n self.method_ = x\n\n def clear_method(self):\n if self.has_method_:\n self.has_method_ = 0\n self.method_ = \"\"\n\n def has_method(self): return self.has_method_\n\n def request(self): return self.request_\n\n def set_request(self, x):\n self.has_request_ = 1\n self.request_ = x\n\n def clear_request(self):\n if self.has_request_:\n self.has_request_ = 0\n self.request_ = \"\"\n\n def has_request(self): return self.has_request_\n\n def request_id(self): return self.request_id_\n\n def set_request_id(self, x):\n self.has_request_id_ = 1\n self.request_id_ = x\n\n def clear_request_id(self):\n if self.has_request_id_:\n self.has_request_id_ = 0\n self.request_id_ = \"\"\n\n def has_request_id(self): return self.has_request_id_\n\n\n def MergeFrom(self, x):\n assert x is not self\n if (x.has_service_name()): self.set_service_name(x.service_name())\n if (x.has_method()): self.set_method(x.method())\n if (x.has_request()): self.set_request(x.request())\n if (x.has_request_id()): self.set_request_id(x.request_id())\n\n def Equals(self, x):\n if x is self: return 1\n if self.has_service_name_ != x.has_service_name_: return 0\n if self.has_service_name_ and self.service_name_ != x.service_name_: return 0\n if self.has_method_ != x.has_method_: return 0\n if self.has_method_ and self.method_ != x.method_: return 0\n if self.has_request_ != x.has_request_: return 0\n if self.has_request_ and self.request_ != x.request_: return 0\n if self.has_request_id_ != x.has_request_id_: return 0\n if self.has_request_id_ and self.request_id_ != x.request_id_: return 0\n return 1\n\n def IsInitialized(self, debug_strs=None):\n initialized = 1\n if (not self.has_service_name_):\n initialized = 0\n if debug_strs is not None:\n debug_strs.append('Required field: service_name not set.')\n if (not self.has_method_):\n initialized = 0\n if debug_strs is not None:\n debug_strs.append('Required field: method not set.')\n if (not self.has_request_):\n initialized = 0\n if debug_strs is not None:\n debug_strs.append('Required field: request not set.')\n return initialized\n\n def ByteSize(self):\n n = 0\n n += self.lengthString(len(self.service_name_))\n n += self.lengthString(len(self.method_))\n n += self.lengthString(len(self.request_))\n if (self.has_request_id_): n += 1 + self.lengthString(len(self.request_id_))\n return n + 3\n\n def ByteSizePartial(self):\n n = 0\n if (self.has_service_name_):\n n += 1\n n += self.lengthString(len(self.service_name_))\n if (self.has_method_):\n n += 1\n n += self.lengthString(len(self.method_))\n if (self.has_request_):\n n += 1\n n += self.lengthString(len(self.request_))\n if (self.has_request_id_): n += 1 + self.lengthString(len(self.request_id_))\n return n\n\n def Clear(self):\n self.clear_service_name()\n self.clear_method()\n self.clear_request()\n self.clear_request_id()\n\n def OutputUnchecked(self, out):\n out.putVarInt32(18)\n out.putPrefixedString(self.service_name_)\n out.putVarInt32(26)\n out.putPrefixedString(self.method_)\n out.putVarInt32(34)\n out.putPrefixedString(self.request_)\n if (self.has_request_id_):\n out.putVarInt32(42)\n out.putPrefixedString(self.request_id_)\n\n def OutputPartial(self, out):\n if (self.has_service_name_):\n out.putVarInt32(18)\n out.putPrefixedString(self.service_name_)\n if (self.has_method_):\n out.putVarInt32(26)\n out.putPrefixedString(self.method_)\n if (self.has_request_):\n out.putVarInt32(34)\n out.putPrefixedString(self.request_)\n if (self.has_request_id_):\n out.putVarInt32(42)\n out.putPrefixedString(self.request_id_)\n\n def TryMerge(self, d):\n while d.avail() > 0:\n tt = d.getVarInt32()\n if tt == 18:\n self.set_service_name(d.getPrefixedString())\n continue\n if tt == 26:\n self.set_method(d.getPrefixedString())\n continue\n if tt == 34:\n self.set_request(d.getPrefixedString())\n continue\n if tt == 42:\n self.set_request_id(d.getPrefixedString())\n continue\n\n\n if (tt == 0): raise ProtocolBuffer.ProtocolBufferDecodeError\n d.skipData(tt)\n\n\n def __str__(self, prefix=\"\", printElemNumber=0):\n res=\"\"\n if self.has_service_name_: res+=prefix+(\"service_name: %s\\n\" % self.DebugFormatString(self.service_name_))\n if self.has_method_: res+=prefix+(\"method: %s\\n\" % self.DebugFormatString(self.method_))\n if self.has_request_: res+=prefix+(\"request: %s\\n\" % self.DebugFormatString(self.request_))\n if self.has_request_id_: res+=prefix+(\"request_id: %s\\n\" % self.DebugFormatString(self.request_id_))\n return res\n\n\n def _BuildTagLookupTable(sparse, maxtag, default=None):\n return tuple([sparse.get(i, default) for i in xrange(0, 1+maxtag)])\n\n kservice_name = 2\n kmethod = 3\n krequest = 4\n krequest_id = 5\n\n _TEXT = _BuildTagLookupTable({\n 0: \"ErrorCode\",\n 2: \"service_name\",\n 3: \"method\",\n 4: \"request\",\n 5: \"request_id\",\n }, 5)\n\n _TYPES = _BuildTagLookupTable({\n 0: ProtocolBuffer.Encoder.NUMERIC,\n 2: ProtocolBuffer.Encoder.STRING,\n 3: ProtocolBuffer.Encoder.STRING,\n 4: ProtocolBuffer.Encoder.STRING,\n 5: ProtocolBuffer.Encoder.STRING,\n }, 5, ProtocolBuffer.Encoder.MAX_TYPE)\n\n\n _STYLE = \"\"\"\"\"\"\n _STYLE_CONTENT_TYPE = \"\"\"\"\"\"\n _PROTO_DESCRIPTOR_NAME = 'apphosting.ext.remote_api.Request'\nclass ApplicationError(ProtocolBuffer.ProtocolMessage):\n has_code_ = 0\n code_ = 0\n has_detail_ = 0\n detail_ = \"\"\n\n def __init__(self, contents=None):\n if contents is not None: self.MergeFromString(contents)\n\n def code(self): return self.code_\n\n def set_code(self, x):\n self.has_code_ = 1\n self.code_ = x\n\n def clear_code(self):\n if self.has_code_:\n self.has_code_ = 0\n self.code_ = 0\n\n def has_code(self): return self.has_code_\n\n def detail(self): return self.detail_\n\n def set_detail(self, x):\n self.has_detail_ = 1\n self.detail_ = x\n\n def clear_detail(self):\n if self.has_detail_:\n self.has_detail_ = 0\n self.detail_ = \"\"\n\n def has_detail(self): return self.has_detail_\n\n\n def MergeFrom(self, x):\n assert x is not self\n if (x.has_code()): self.set_code(x.code())\n if (x.has_detail()): self.set_detail(x.detail())\n\n def Equals(self, x):\n if x is self: return 1\n if self.has_code_ != x.has_code_: return 0\n if self.has_code_ and self.code_ != x.code_: return 0\n if self.has_detail_ != x.has_detail_: return 0\n if self.has_detail_ and self.detail_ != x.detail_: return 0\n return 1\n\n def IsInitialized(self, debug_strs=None):\n initialized = 1\n if (not self.has_code_):\n initialized = 0\n if debug_strs is not None:\n debug_strs.append('Required field: code not set.')\n if (not self.has_detail_):\n initialized = 0\n if debug_strs is not None:\n debug_strs.append('Required field: detail not set.')\n return initialized\n\n def ByteSize(self):\n n = 0\n n += self.lengthVarInt64(self.code_)\n n += self.lengthString(len(self.detail_))\n return n + 2\n\n def ByteSizePartial(self):\n n = 0\n if (self.has_code_):\n n += 1\n n += self.lengthVarInt64(self.code_)\n if (self.has_detail_):\n n += 1\n n += self.lengthString(len(self.detail_))\n return n\n\n def Clear(self):\n self.clear_code()\n self.clear_detail()\n\n def OutputUnchecked(self, out):\n out.putVarInt32(8)\n out.putVarInt32(self.code_)\n out.putVarInt32(18)\n out.putPrefixedString(self.detail_)\n\n def OutputPartial(self, out):\n if (self.has_code_):\n out.putVarInt32(8)\n out.putVarInt32(self.code_)\n if (self.has_detail_):\n out.putVarInt32(18)\n out.putPrefixedString(self.detail_)\n\n def TryMerge(self, d):\n while d.avail() > 0:\n tt = d.getVarInt32()\n if tt == 8:\n self.set_code(d.getVarInt32())\n continue\n if tt == 18:\n self.set_detail(d.getPrefixedString())\n continue\n\n\n if (tt == 0): raise ProtocolBuffer.ProtocolBufferDecodeError\n d.skipData(tt)\n\n\n def __str__(self, prefix=\"\", printElemNumber=0):\n res=\"\"\n if self.has_code_: res+=prefix+(\"code: %s\\n\" % self.DebugFormatInt32(self.code_))\n if self.has_detail_: res+=prefix+(\"detail: %s\\n\" % self.DebugFormatString(self.detail_))\n return res\n\n\n def _BuildTagLookupTable(sparse, maxtag, default=None):\n return tuple([sparse.get(i, default) for i in xrange(0, 1+maxtag)])\n\n kcode = 1\n kdetail = 2\n\n _TEXT = _BuildTagLookupTable({\n 0: \"ErrorCode\",\n 1: \"code\",\n 2: \"detail\",\n }, 2)\n\n _TYPES = _BuildTagLookupTable({\n 0: ProtocolBuffer.Encoder.NUMERIC,\n 1: ProtocolBuffer.Encoder.NUMERIC,\n 2: ProtocolBuffer.Encoder.STRING,\n }, 2, ProtocolBuffer.Encoder.MAX_TYPE)\n\n\n _STYLE = \"\"\"\"\"\"\n _STYLE_CONTENT_TYPE = \"\"\"\"\"\"\n _PROTO_DESCRIPTOR_NAME = 'apphosting.ext.remote_api.ApplicationError'\nclass Response(ProtocolBuffer.ProtocolMessage):\n has_response_ = 0\n response_ = \"\"\n has_exception_ = 0\n exception_ = \"\"\n has_application_error_ = 0\n application_error_ = None\n has_java_exception_ = 0\n java_exception_ = \"\"\n\n def __init__(self, contents=None):\n self.lazy_init_lock_ = thread.allocate_lock()\n if contents is not None: self.MergeFromString(contents)\n\n def response(self): return self.response_\n\n def set_response(self, x):\n self.has_response_ = 1\n self.response_ = x\n\n def clear_response(self):\n if self.has_response_:\n self.has_response_ = 0\n self.response_ = \"\"\n\n def has_response(self): return self.has_response_\n\n def exception(self): return self.exception_\n\n def set_exception(self, x):\n self.has_exception_ = 1\n self.exception_ = x\n\n def clear_exception(self):\n if self.has_exception_:\n self.has_exception_ = 0\n self.exception_ = \"\"\n\n def has_exception(self): return self.has_exception_\n\n def application_error(self):\n if self.application_error_ is None:\n self.lazy_init_lock_.acquire()\n try:\n if self.application_error_ is None: self.application_error_ = ApplicationError()\n finally:\n self.lazy_init_lock_.release()\n return self.application_error_\n\n def mutable_application_error(self): self.has_application_error_ = 1; return self.application_error()\n\n def clear_application_error(self):\n\n if self.has_application_error_:\n self.has_application_error_ = 0;\n if self.application_error_ is not None: self.application_error_.Clear()\n\n def has_application_error(self): return self.has_application_error_\n\n def java_exception(self): return self.java_exception_\n\n def set_java_exception(self, x):\n self.has_java_exception_ = 1\n self.java_exception_ = x\n\n def clear_java_exception(self):\n if self.has_java_exception_:\n self.has_java_exception_ = 0\n self.java_exception_ = \"\"\n\n def has_java_exception(self): return self.has_java_exception_\n\n\n def MergeFrom(self, x):\n assert x is not self\n if (x.has_response()): self.set_response(x.response())\n if (x.has_exception()): self.set_exception(x.exception())\n if (x.has_application_error()): self.mutable_application_error().MergeFrom(x.application_error())\n if (x.has_java_exception()): self.set_java_exception(x.java_exception())\n\n def Equals(self, x):\n if x is self: return 1\n if self.has_response_ != x.has_response_: return 0\n if self.has_response_ and self.response_ != x.response_: return 0\n if self.has_exception_ != x.has_exception_: return 0\n if self.has_exception_ and self.exception_ != x.exception_: return 0\n if self.has_application_error_ != x.has_application_error_: return 0\n if self.has_application_error_ and self.application_error_ != x.application_error_: return 0\n if self.has_java_exception_ != x.has_java_exception_: return 0\n if self.has_java_exception_ and self.java_exception_ != x.java_exception_: return 0\n return 1\n\n def IsInitialized(self, debug_strs=None):\n initialized = 1\n if (self.has_application_error_ and not self.application_error_.IsInitialized(debug_strs)): initialized = 0\n return initialized\n\n def ByteSize(self):\n n = 0\n if (self.has_response_): n += 1 + self.lengthString(len(self.response_))\n if (self.has_exception_): n += 1 + self.lengthString(len(self.exception_))\n if (self.has_application_error_): n += 1 + self.lengthString(self.application_error_.ByteSize())\n if (self.has_java_exception_): n += 1 + self.lengthString(len(self.java_exception_))\n return n\n\n def ByteSizePartial(self):\n n = 0\n if (self.has_response_): n += 1 + self.lengthString(len(self.response_))\n if (self.has_exception_): n += 1 + self.lengthString(len(self.exception_))\n if (self.has_application_error_): n += 1 + self.lengthString(self.application_error_.ByteSizePartial())\n if (self.has_java_exception_): n += 1 + self.lengthString(len(self.java_exception_))\n return n\n\n def Clear(self):\n self.clear_response()\n self.clear_exception()\n self.clear_application_error()\n self.clear_java_exception()\n\n def OutputUnchecked(self, out):\n if (self.has_response_):\n out.putVarInt32(10)\n out.putPrefixedString(self.response_)\n if (self.has_exception_):\n out.putVarInt32(18)\n out.putPrefixedString(self.exception_)\n if (self.has_application_error_):\n out.putVarInt32(26)\n out.putVarInt32(self.application_error_.ByteSize())\n self.application_error_.OutputUnchecked(out)\n if (self.has_java_exception_):\n out.putVarInt32(34)\n out.putPrefixedString(self.java_exception_)\n\n def OutputPartial(self, out):\n if (self.has_response_):\n out.putVarInt32(10)\n out.putPrefixedString(self.response_)\n if (self.has_exception_):\n out.putVarInt32(18)\n out.putPrefixedString(self.exception_)\n if (self.has_application_error_):\n out.putVarInt32(26)\n out.putVarInt32(self.application_error_.ByteSizePartial())\n self.application_error_.OutputPartial(out)\n if (self.has_java_exception_):\n out.putVarInt32(34)\n out.putPrefixedString(self.java_exception_)\n\n def TryMerge(self, d):\n while d.avail() > 0:\n tt = d.getVarInt32()\n if tt == 10:\n self.set_response(d.getPrefixedString())\n continue\n if tt == 18:\n self.set_exception(d.getPrefixedString())\n continue\n if tt == 26:\n length = d.getVarInt32()\n tmp = ProtocolBuffer.Decoder(d.buffer(), d.pos(), d.pos() + length)\n d.skip(length)\n self.mutable_application_error().TryMerge(tmp)\n continue\n if tt == 34:\n self.set_java_exception(d.getPrefixedString())\n continue\n\n\n if (tt == 0): raise ProtocolBuffer.ProtocolBufferDecodeError\n d.skipData(tt)\n\n\n def __str__(self, prefix=\"\", printElemNumber=0):\n res=\"\"\n if self.has_response_: res+=prefix+(\"response: %s\\n\" % self.DebugFormatString(self.response_))\n if self.has_exception_: res+=prefix+(\"exception: %s\\n\" % self.DebugFormatString(self.exception_))\n if self.has_application_error_:\n res+=prefix+\"application_error <\\n\"\n res+=self.application_error_.__str__(prefix + \" \", printElemNumber)\n res+=prefix+\">\\n\"\n if self.has_java_exception_: res+=prefix+(\"java_exception: %s\\n\" % self.DebugFormatString(self.java_exception_))\n return res\n\n\n def _BuildTagLookupTable(sparse, maxtag, default=None):\n return tuple([sparse.get(i, default) for i in xrange(0, 1+maxtag)])\n\n kresponse = 1\n kexception = 2\n kapplication_error = 3\n kjava_exception = 4\n\n _TEXT = _BuildTagLookupTable({\n 0: \"ErrorCode\",\n 1: \"response\",\n 2: \"exception\",\n 3: \"application_error\",\n 4: \"java_exception\",\n }, 4)\n\n _TYPES = _BuildTagLookupTable({\n 0: ProtocolBuffer.Encoder.NUMERIC,\n 1: ProtocolBuffer.Encoder.STRING,\n 2: ProtocolBuffer.Encoder.STRING,\n 3: ProtocolBuffer.Encoder.STRING,\n 4: ProtocolBuffer.Encoder.STRING,\n }, 4, ProtocolBuffer.Encoder.MAX_TYPE)\n\n\n _STYLE = \"\"\"\"\"\"\n _STYLE_CONTENT_TYPE = \"\"\"\"\"\"\n _PROTO_DESCRIPTOR_NAME = 'apphosting.ext.remote_api.Response'\nclass TransactionRequest_Precondition(ProtocolBuffer.ProtocolMessage):\n has_key_ = 0\n has_hash_ = 0\n hash_ = \"\"\n\n def __init__(self, contents=None):\n self.key_ = Reference()\n if contents is not None: self.MergeFromString(contents)\n\n def key(self): return self.key_\n\n def mutable_key(self): self.has_key_ = 1; return self.key_\n\n def clear_key(self):self.has_key_ = 0; self.key_.Clear()\n\n def has_key(self): return self.has_key_\n\n def hash(self): return self.hash_\n\n def set_hash(self, x):\n self.has_hash_ = 1\n self.hash_ = x\n\n def clear_hash(self):\n if self.has_hash_:\n self.has_hash_ = 0\n self.hash_ = \"\"\n\n def has_hash(self): return self.has_hash_\n\n\n def MergeFrom(self, x):\n assert x is not self\n if (x.has_key()): self.mutable_key().MergeFrom(x.key())\n if (x.has_hash()): self.set_hash(x.hash())\n\n def Equals(self, x):\n if x is self: return 1\n if self.has_key_ != x.has_key_: return 0\n if self.has_key_ and self.key_ != x.key_: return 0\n if self.has_hash_ != x.has_hash_: return 0\n if self.has_hash_ and self.hash_ != x.hash_: return 0\n return 1\n\n def IsInitialized(self, debug_strs=None):\n initialized = 1\n if (not self.has_key_):\n initialized = 0\n if debug_strs is not None:\n debug_strs.append('Required field: key not set.')\n elif not self.key_.IsInitialized(debug_strs): initialized = 0\n return initialized\n\n def ByteSize(self):\n n = 0\n n += self.lengthString(self.key_.ByteSize())\n if (self.has_hash_): n += 1 + self.lengthString(len(self.hash_))\n return n + 1\n\n def ByteSizePartial(self):\n n = 0\n if (self.has_key_):\n n += 1\n n += self.lengthString(self.key_.ByteSizePartial())\n if (self.has_hash_): n += 1 + self.lengthString(len(self.hash_))\n return n\n\n def Clear(self):\n self.clear_key()\n self.clear_hash()\n\n def OutputUnchecked(self, out):\n out.putVarInt32(18)\n out.putVarInt32(self.key_.ByteSize())\n self.key_.OutputUnchecked(out)\n if (self.has_hash_):\n out.putVarInt32(26)\n out.putPrefixedString(self.hash_)\n\n def OutputPartial(self, out):\n if (self.has_key_):\n out.putVarInt32(18)\n out.putVarInt32(self.key_.ByteSizePartial())\n self.key_.OutputPartial(out)\n if (self.has_hash_):\n out.putVarInt32(26)\n out.putPrefixedString(self.hash_)\n\n def TryMerge(self, d):\n while 1:\n tt = d.getVarInt32()\n if tt == 12: break\n if tt == 18:\n length = d.getVarInt32()\n tmp = ProtocolBuffer.Decoder(d.buffer(), d.pos(), d.pos() + length)\n d.skip(length)\n self.mutable_key().TryMerge(tmp)\n continue\n if tt == 26:\n self.set_hash(d.getPrefixedString())\n continue\n\n\n if (tt == 0): raise ProtocolBuffer.ProtocolBufferDecodeError\n d.skipData(tt)\n\n\n def __str__(self, prefix=\"\", printElemNumber=0):\n res=\"\"\n if self.has_key_:\n res+=prefix+\"key <\\n\"\n res+=self.key_.__str__(prefix + \" \", printElemNumber)\n res+=prefix+\">\\n\"\n if self.has_hash_: res+=prefix+(\"hash: %s\\n\" % self.DebugFormatString(self.hash_))\n return res\n\nclass TransactionRequest(ProtocolBuffer.ProtocolMessage):\n has_puts_ = 0\n puts_ = None\n has_deletes_ = 0\n deletes_ = None\n has_allow_multiple_eg_ = 0\n allow_multiple_eg_ = 0\n\n def __init__(self, contents=None):\n self.precondition_ = []\n self.lazy_init_lock_ = thread.allocate_lock()\n if contents is not None: self.MergeFromString(contents)\n\n def precondition_size(self): return len(self.precondition_)\n def precondition_list(self): return self.precondition_\n\n def precondition(self, i):\n return self.precondition_[i]\n\n def mutable_precondition(self, i):\n return self.precondition_[i]\n\n def add_precondition(self):\n x = TransactionRequest_Precondition()\n self.precondition_.append(x)\n return x\n\n def clear_precondition(self):\n self.precondition_ = []\n def puts(self):\n if self.puts_ is None:\n self.lazy_init_lock_.acquire()\n try:\n if self.puts_ is None: self.puts_ = PutRequest()\n finally:\n self.lazy_init_lock_.release()\n return self.puts_\n\n def mutable_puts(self): self.has_puts_ = 1; return self.puts()\n\n def clear_puts(self):\n\n if self.has_puts_:\n self.has_puts_ = 0;\n if self.puts_ is not None: self.puts_.Clear()\n\n def has_puts(self): return self.has_puts_\n\n def deletes(self):\n if self.deletes_ is None:\n self.lazy_init_lock_.acquire()\n try:\n if self.deletes_ is None: self.deletes_ = DeleteRequest()\n finally:\n self.lazy_init_lock_.release()\n return self.deletes_\n\n def mutable_deletes(self): self.has_deletes_ = 1; return self.deletes()\n\n def clear_deletes(self):\n\n if self.has_deletes_:\n self.has_deletes_ = 0;\n if self.deletes_ is not None: self.deletes_.Clear()\n\n def has_deletes(self): return self.has_deletes_\n\n def allow_multiple_eg(self): return self.allow_multiple_eg_\n\n def set_allow_multiple_eg(self, x):\n self.has_allow_multiple_eg_ = 1\n self.allow_multiple_eg_ = x\n\n def clear_allow_multiple_eg(self):\n if self.has_allow_multiple_eg_:\n self.has_allow_multiple_eg_ = 0\n self.allow_multiple_eg_ = 0\n\n def has_allow_multiple_eg(self): return self.has_allow_multiple_eg_\n", "answers": [" def MergeFrom(self, x):"], "length": 1997, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "28d73a85-2fdf-4e16-86c3-d4b80d0e222c", "reasoning": "The class TransactionRequest ends with the accessor methods for its fields, the last being has_allow_multiple_eg. Following the pattern used in earlier ProtocolBuffer classes, the next method defined is MergeFrom, which merges data from another instance. Therefore the next line should start the definition of that method.", "reasoning_model_answer": "def MergeFrom(self, x):", "assistant_with_reasoning": "\nThe class TransactionRequest ends with the accessor methods for its fields, the last being has_allow_multiple_eg. Following the pattern used in earlier ProtocolBuffer classes, the next method defined is MergeFrom, which merges data from another instance. Therefore the next line should start the definition of that method.\n\ndef MergeFrom(self, x):", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 2.989, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 23480, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "def MergeFrom(self, x):", "score": 0.96, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "using System;\nusing System.Collections.Generic;\nusing System.Data;\nusing System.Reflection;\nusing ServiceStack.Common.Utils;\nusing System.Text;\nusing FirebirdSql.Data.FirebirdClient;\nusing ServiceStack.Common.Extensions;\n\nnamespace ServiceStack.OrmLite.Firebird\n{\n public class FirebirdOrmLiteDialectProvider : OrmLiteDialectProviderBase\n\t{\n\t\tprivate readonly List RESERVED = new List(new[] {\n\t\t\t\"USER\",\"ORDER\",\"PASSWORD\", \"ACTIVE\",\"LEFT\",\"DOUBLE\", \"FLOAT\", \"DECIMAL\",\"STRING\", \"DATE\",\"DATETIME\", \"TYPE\",\"TIMESTAMP\",\n\t\t\t\"INDEX\",\"UNIQUE\", \"PRIMARY\", \"KEY\", \"ALTER\", \"DROP\", \"CREATE\", \"DELETE\"\n\t\t});\n\t\t\n\t\tpublic static FirebirdOrmLiteDialectProvider Instance = new FirebirdOrmLiteDialectProvider();\n\t\t\n\t\tinternal long LastInsertId { get; set; }\n\t\tprotected bool CompactGuid;\n\n\t\tinternal const string DefaultGuidDefinition = \"VARCHAR(37)\";\n\t\tinternal const string CompactGuidDefinition = \"CHAR(16) CHARACTER SET OCTETS\";\n\n\t\tpublic FirebirdOrmLiteDialectProvider()\n\t\t\t: this(false)\n\t\t{\n\t\t}\n\n\t\tpublic FirebirdOrmLiteDialectProvider(bool compactGuid)\n\t\t{\n\t\t\tCompactGuid = compactGuid;\n\t\t\tbase.BoolColumnDefinition = base.IntColumnDefinition;\n\t\t\tbase.GuidColumnDefinition = CompactGuid ? CompactGuidDefinition : DefaultGuidDefinition;\n\t\t\tbase.AutoIncrementDefinition= string.Empty;\n\t\t\tbase.DateTimeColumnDefinition=\"TIMESTAMP\";\n\t\t\tbase.TimeColumnDefinition = \"TIME\";\n\t\t\tbase.RealColumnDefinition= \"FLOAT\";\n\t\t\tbase.DefaultStringLength=128;\n\t\t\tbase.InitColumnTypeMap();\n\t\t}\n\t\t\n\t\tpublic override IDbConnection CreateConnection(string connectionString, Dictionary options)\n\t\t{\n\t\t\tif (options != null)\n\t\t\t{\n\t\t\t\tforeach (var option in options)\n\t\t\t\t{\n\t\t\t\t\tconnectionString += option.Key + \"=\" + option.Value + \";\";\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\treturn new FbConnection(connectionString);\n\t\t}\n\t\t\n\t\tpublic override long GetLastInsertId(IDbCommand dbCmd)\n\t\t{\n\t\t\treturn LastInsertId;\t\t\t\n\t\t}\n\t\t\n\t\tpublic override object ConvertDbValue(object value, Type type)\n\t\t{\n\t\t\tif (value == null || value is DBNull) return null;\n\n\t\t\tif (type == typeof(bool))\n\t\t\t{\n\t\t\t\tvar intVal = int.Parse(value.ToString());\n\t\t\t\treturn intVal != 0;\n\t\t\t}\n\t\t\t\n\t\t\tif(type == typeof(System.Double))\n\t\t\t\treturn double.Parse(value.ToString());\n\n\t\t\tif (type == typeof(Guid) && BitConverter.IsLittleEndian) // TODO: check big endian\n\t\t\t{\n\t\t\t\tif (CompactGuid)\n\t\t\t\t{\n\t\t\t\t\tbyte[] raw = ((Guid)value).ToByteArray();\n\t\t\t\t\treturn new Guid(System.Net.IPAddress.NetworkToHostOrder(BitConverter.ToInt32(raw, 0)),\n\t\t\t\t\t\tSystem.Net.IPAddress.NetworkToHostOrder(BitConverter.ToInt16(raw, 4)),\n\t\t\t\t\t\tSystem.Net.IPAddress.NetworkToHostOrder(BitConverter.ToInt16(raw, 6)),\n\t\t\t\t\t\traw[8], raw[9], raw[10], raw[11], raw[12], raw[13], raw[14], raw[15]);\n\t\t\t\t}\n\t\t\t\treturn new Guid(value.ToString());\n\t\t\t}\n\n\t\t\ttry\n\t\t\t{\n\t\t\t\treturn base.ConvertDbValue(value, type);\n\t\t\t}\n\t\t\tcatch (Exception )\n\t\t\t{\t\t\t\t\n\t\t\t\tthrow;\n\t\t\t}\n\t\t}\n\n\t\tpublic override string GetQuotedValue(object value, Type fieldType)\n\t\t{\n\t\t\t\t\t\t\n\t\t\tif (value == null) return \"NULL\";\n\n\t\t\tif (fieldType == typeof(Guid))\n\t\t\t{\n\t\t\t\tif (CompactGuid)\n\t\t\t\t\treturn \"X'\" + ((Guid)value).ToString(\"N\") + \"'\";\n\t\t\t\telse\n\t\t\t\t\treturn string.Format(\"CAST('{0}' AS {1})\", (Guid)value, DefaultGuidDefinition); // TODO : check this !!!\n\t\t\t}\n\t\t\tif (fieldType == typeof(DateTime) || fieldType == typeof( DateTime?) )\n\t\t\t{\n\t\t\t\tvar dateValue = (DateTime)value;\n\t\t\t\tstring iso8601Format= dateValue.ToString(\"yyyy-MM-dd HH:mm:ss.fff\").EndsWith(\"00:00:00.000\")?\n\t\t\t\t\t\t\"yyyy-MM-dd\"\n\t\t\t\t\t\t:\"yyyy-MM-dd HH:mm:ss.fff\";\t\t\n\t\t\t\treturn base.GetQuotedValue(dateValue.ToString(iso8601Format), typeof(string));\n\t\t\t}\n\t\t\tif (fieldType == typeof(bool ?) || fieldType == typeof(bool))\n\t\t\t{\n\t\t\t\tvar boolValue = (bool)value;\n\t\t\t\treturn base.GetQuotedValue(boolValue ? \"1\" : \"0\", typeof(string));\n\t\t\t}\n\t\t\t\n\t\t\tif (fieldType == typeof(decimal ?) || fieldType == typeof(decimal) ||\n\t\t\t\tfieldType == typeof(double ?) || fieldType == typeof(double) ||\n\t\t\t\tfieldType == typeof(float ?) || fieldType == typeof(float) ){\n\t\t\t\tvar s = base.GetQuotedValue( value, fieldType);\n\t\t\t\tif (s.Length>20) s= s.Substring(0,20);\n\t\t\t\treturn \"'\" + s + \"'\"; // when quoted exception is more clear!\n\t\t\t}\n\t\t\t\n\t\t\treturn base.GetQuotedValue(value, fieldType);\n\t\t}\n\t\t\n\t\tpublic override string ToSelectStatement(Type tableType, string sqlFilter, params object[] filterParams)\n\t\t{\n\t\t\tvar sql = new StringBuilder();\n\t\t\tconst string SelectStatement = \"SELECT \";\n\t\t\tvar modelDef = GetModel(tableType);\n\t\t\tvar isFullSelectStatement = \n\t\t\t\t!string.IsNullOrEmpty(sqlFilter)\n\t\t\t\t&& sqlFilter.Length > SelectStatement.Length\n\t\t\t\t&& sqlFilter.Substring(0, SelectStatement.Length).ToUpper().Equals(SelectStatement);\n\n\t\t\tif (isFullSelectStatement) \treturn sqlFilter.SqlFormat(filterParams);\n\t\t\t\n\t\t\tsql.AppendFormat(\"SELECT {0} \\nFROM {1}\", \n\t\t\t GetColumnNames(modelDef), \n\t\t\t GetQuotedTableName(modelDef));\n\t\t\tif (!string.IsNullOrEmpty(sqlFilter))\n\t\t\t{\n\t\t\t\tsqlFilter = sqlFilter.SqlFormat(filterParams);\n\t\t\t\tif (!sqlFilter.StartsWith(\"\\nORDER \", StringComparison.InvariantCultureIgnoreCase)\n\t\t\t\t\t&& !sqlFilter.StartsWith(\"\\nROWS \", StringComparison.InvariantCultureIgnoreCase)) // ROWS [TO ])\n\t\t\t\t{\n\t\t\t\t\tsql.Append(\"\\nWHERE \");\n\t\t\t\t}\n\t\t\t\tsql.Append(sqlFilter);\n\t\t\t}\n\t\t\treturn sql.ToString();\n\t\t}\n\t\t\n\t\tpublic override string ToInsertRowStatement(object objWithProperties, IList insertFields, IDbCommand dbCommand)\n\t\t{\n\t\t\tvar sbColumnNames = new StringBuilder();\n\t\t\tvar sbColumnValues = new StringBuilder();\n\n\t\t\tvar tableType = objWithProperties.GetType();\n\t\t\tvar modelDef= GetModel(tableType);\n\t\t\t\n\t\t\tforeach (var fieldDef in modelDef.FieldDefinitions)\n\t\t\t{\n\t\t\t\t\n\t\t\t\tif( fieldDef.IsComputed ) continue;\n\t\t\t\tif( insertFields.Count>0 && ! insertFields.Contains( fieldDef.Name )) continue;\n\t\t\t\t\n\t\t\t\tif( (fieldDef.AutoIncrement || ! string.IsNullOrEmpty(fieldDef.Sequence)\n\t\t\t\t\t|| fieldDef.Name == OrmLiteConfig.IdField) \n\t\t\t\t\t&& dbCommand != null) \n\t\t\t\t{\n\t\n\t\t\t\t\tif (fieldDef.AutoIncrement && string.IsNullOrEmpty(fieldDef.Sequence))\n\t\t\t\t\t{\n\t\t\t\t\t\tfieldDef.Sequence = Sequence(\n\t\t\t\t\t\t\t(modelDef.IsInSchema\n\t\t\t\t\t\t\t\t? modelDef.Schema+\"_\"+NamingStrategy.GetTableName(modelDef.ModelName)\n\t\t\t\t\t\t\t\t: NamingStrategy.GetTableName(modelDef.ModelName)), \n\t\t\t\t\t\t\tfieldDef.FieldName, fieldDef.Sequence);\n\t\t\t\t\t}\n\t\t\t\t\n\t\t\t\t\tPropertyInfo pi = tableType.GetProperty(fieldDef.Name, \n BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.FlattenHierarchy);\n\n\t\t\t\t\tvar result = GetNextValue(dbCommand, fieldDef.Sequence, pi.GetValue(objWithProperties, new object[] { }) );\n\t\t\t\t\tif (pi.PropertyType == typeof(String))\n\t\t\t\t\t\tReflectionUtils.SetProperty(objWithProperties, pi, result.ToString());\t\n\t\t\t\t\telse if(pi.PropertyType == typeof(Int16))\n\t\t\t\t\t\tReflectionUtils.SetProperty(objWithProperties, pi, Convert.ToInt16(result));\t\n\t\t\t\t\telse if(pi.PropertyType == typeof(Int32))\n\t\t\t\t\t\tReflectionUtils.SetProperty(objWithProperties, pi, Convert.ToInt32(result));\t\n\t\t\t\t\telse if(pi.PropertyType == typeof(Guid))\n\t\t\t\t\t\tReflectionUtils.SetProperty(objWithProperties, pi, result);\n\t\t\t\t\telse\n\t\t\t\t\t\tReflectionUtils.SetProperty(objWithProperties, pi, Convert.ToInt64(result));\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif (sbColumnNames.Length > 0) sbColumnNames.Append(\",\");\n\t\t\t\tif (sbColumnValues.Length > 0) sbColumnValues.Append(\",\");\n\n\t\t\t\ttry\n\t\t\t\t{\n\t\t\t\t\tsbColumnNames.Append(string.Format(\"{0}\",GetQuotedColumnName(fieldDef.FieldName)));\n\t\t\t\t\tif (!string.IsNullOrEmpty(fieldDef.Sequence) && dbCommand==null)\n\t\t\t\t\t\tsbColumnValues.Append(string.Format(\"@{0}\",fieldDef.Name));\n\t\t\t\t\telse\n\t\t\t\t\t\tsbColumnValues.Append(fieldDef.GetQuotedValue(objWithProperties));\n\t\t\t\t}\n\t\t\t\tcatch (Exception)\n\t\t\t\t{\n\t\t\t\t\tthrow;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tvar sql = string.Format(\"INSERT INTO {0} ({1}) VALUES ({2});\",\n\t\t\t\t\t\t\t\t\tGetQuotedTableName(modelDef), sbColumnNames, sbColumnValues);\n\t\t\t\t\t\t\n\t\t\treturn sql;\n\t\t}\n\n\t\t\n\t\tpublic override string ToUpdateRowStatement(object objWithProperties, IList updateFields)\n\t\t{\n\t\t\tvar sqlFilter = new StringBuilder();\n\t\t\tvar sql = new StringBuilder();\n\t\t\tvar tableType = objWithProperties.GetType();\n\t\t\tvar modelDef = GetModel(tableType);\n\t\t\t\t\t\t\t\t\t\n\t\t\tforeach (var fieldDef in modelDef.FieldDefinitions)\n\t\t\t{\n\t\t\t\tif( fieldDef.IsComputed) continue;\n\t\t\t\t\n\t\t\t\ttry\n\t\t\t\t{\n\t\t\t\t\tif ((fieldDef.IsPrimaryKey || fieldDef.Name == OrmLiteConfig.IdField) \n\t\t\t\t\t\t&& updateFields.Count == 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tif (sqlFilter.Length > 0) sqlFilter.Append(\" AND \");\n\n\t\t\t\t\t\tsqlFilter.AppendFormat(\"{0} = {1}\", \n\t\t\t\t\t\t\tGetQuotedColumnName(fieldDef.FieldName),\n\t\t\t\t\t\t\tfieldDef.GetQuotedValue(objWithProperties));\n\t\t\t\t\t\t\t\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tif (updateFields.Count>0 && !updateFields.Contains(fieldDef.Name)) continue;\n\t\t\t\t\tif (sql.Length > 0) sql.Append(\",\");\n\t\t\t\t\tsql.AppendFormat(\"{0} = {1}\", \n\t\t\t\t\t\tGetQuotedColumnName(fieldDef.FieldName), \n\t\t\t\t\t\tfieldDef.GetQuotedValue(objWithProperties));\n\t\t\t\t}\n\t\t\t\tcatch (Exception)\n\t\t\t\t{\n\t\t\t\t\tthrow;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tvar updateSql = string.Format(\"UPDATE {0} \\nSET {1} {2}\",\n\t\t\t\tGetQuotedTableName(modelDef), sql, (sqlFilter.Length>0? \"\\nWHERE \"+ sqlFilter:\"\"));\n\n\t\t\treturn updateSql;\n\t\t}\n\t\t\t\t\n\t\t\n\t\tpublic override string ToDeleteRowStatement(object objWithProperties)\n\t\t{\n\t\t\tvar tableType = objWithProperties.GetType();\n\t\t\tvar modelDef = GetModel(tableType);\n\t\t\t\n\t\t\tvar sqlFilter = new StringBuilder();\n\t\t\t\n\t\t\tforeach (var fieldDef in modelDef.FieldDefinitions)\n\t\t\t{\n\t\t\t\ttry\n\t\t\t\t{\n\t\t\t\t\tif (fieldDef.IsPrimaryKey || fieldDef.Name == OrmLiteConfig.IdField)\n\t\t\t\t\t{\n\t\t\t\t\t\tif (sqlFilter.Length > 0) sqlFilter.Append(\" AND \");\n\t\t\t\t\t\tsqlFilter.AppendFormat(\"{0} = {1}\", \n\t\t\t\t\t\t\tGetQuotedColumnName(fieldDef.FieldName), \n\t\t\t\t\t\t\tfieldDef.GetQuotedValue(objWithProperties));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcatch (Exception)\n\t\t\t\t{\n\t\t\t\t\tthrow;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tvar deleteSql = string.Format(\"DELETE FROM {0} WHERE {1}\",\n\t\t\t\tGetQuotedTableName(modelDef), sqlFilter);\n\n\t\t\treturn deleteSql;\n\t\t}\n\t\t\n\t\tpublic override string ToCreateTableStatement(Type tableType)\n\t\t{\n\t\t\tvar sbColumns = new StringBuilder();\n var sbConstraints = new StringBuilder();\n\t\t\tvar sbPk= new StringBuilder();\t\t\t\n\t\t\t\t\t\t\n var modelDef = GetModel(tableType);\n foreach (var fieldDef in modelDef.FieldDefinitions)\n {\n\t\t\t\tif (fieldDef.IsPrimaryKey) \n\t\t\t\t{\n\t\t\t\t\tsbPk.AppendFormat(sbPk.Length != 0 ? \",{0}\" : \"{0}\", GetQuotedColumnName(fieldDef.FieldName));\n\t\t\t\t}\n\t\t\t\n if (sbColumns.Length != 0) sbColumns.Append(\", \\n \");\n\n var columnDefinition = GetColumnDefinition(\n fieldDef.FieldName,\n fieldDef.FieldType,\n fieldDef.IsPrimaryKey,\n fieldDef.AutoIncrement,\n fieldDef.IsNullable,\n fieldDef.FieldLength,\n\t\t\t\t\tfieldDef.Scale,\n fieldDef.DefaultValue);\n\n sbColumns.Append(columnDefinition);\n\n if (fieldDef.ForeignKey == null) continue;\n\n var refModelDef = GetModel(fieldDef.ForeignKey.ReferenceType);\n\t\t\t\t\n\t\t\t\tvar modelName= modelDef.IsInSchema\n\t\t\t\t\t? modelDef.Schema + \"_\" + NamingStrategy.GetTableName(modelDef.ModelName)\n\t\t\t\t\t: NamingStrategy.GetTableName(modelDef.ModelName);\n\t\t\t\t\n\t\t\t\tvar refModelName= refModelDef.IsInSchema\n\t\t\t\t\t? refModelDef.Schema + \"_\" + NamingStrategy.GetTableName(refModelDef.ModelName)\n\t\t\t\t\t: NamingStrategy.GetTableName(refModelDef.ModelName);\n\t\t\t\t\n sbConstraints.AppendFormat(\", \\n\\n CONSTRAINT {0} FOREIGN KEY ({1}) REFERENCES {2} ({3})\",\n GetQuotedName(fieldDef.ForeignKey.GetForeignKeyName(modelDef, refModelDef, NamingStrategy, fieldDef)),\n\t\t\t\t\tGetQuotedColumnName(fieldDef.FieldName), \n\t\t\t\t\tGetQuotedTableName(refModelDef), \n\t\t\t\t\tGetQuotedColumnName(refModelDef.PrimaryKey.FieldName));\n }\n\t\t\t\n\t\t\tif (sbPk.Length !=0) sbColumns.AppendFormat(\", \\n PRIMARY KEY({0})\", sbPk);\n\t\t\t\n var sql = new StringBuilder(string.Format(\n \"CREATE TABLE {0} \\n(\\n {1}{2} \\n); \\n\",\n\t\t\t\tGetQuotedTableName(modelDef),\n\t\t\t\tsbColumns,\n\t\t\t\tsbConstraints));\n\t\t\t\n\t\t\treturn sql.ToString();\n\t\t\t\n\t\t}\n\t\t\n\t\tpublic override List ToCreateSequenceStatements(Type tableType){\n\t\t\tvar gens = new List();\t\t\t\n\t\t\tvar modelDef = GetModel(tableType);\n\t\t\t\n foreach (var fieldDef in modelDef.FieldDefinitions)\n {\n\t\t\t\tif (fieldDef.AutoIncrement || ! fieldDef.Sequence.IsNullOrEmpty())\n\t\t\t\t{\n\t\t\t\t \t gens.Add(\"CREATE GENERATOR \" \n\t\t\t\t\t\t + Sequence( (modelDef.IsInSchema\n\t\t\t\t\t\t\t? modelDef.Schema+\"_\" + NamingStrategy.GetTableName(modelDef.ModelName)\n\t\t\t\t\t\t\t: NamingStrategy.GetTableName(modelDef.ModelName)), fieldDef.FieldName, fieldDef.Sequence) +\";\" );\t\t\t\t\t\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn gens;\n\t\t}\n\t\t\n\t\tpublic override string GetColumnDefinition (string fieldName, Type fieldType, \n\t\t\tbool isPrimaryKey, bool autoIncrement, bool isNullable, \n\t\t\tint? fieldLength, int? scale, string defaultValue)\n\t\t{\n\t\t\tstring fieldDefinition;\n\n if (fieldType == typeof(string))\n {\n fieldDefinition = string.Format(StringLengthColumnDefinitionFormat,\n\t\t\t\t fieldLength.GetValueOrDefault(DefaultStringLength));\n }\n else if( fieldType==typeof(Decimal) ){\n\t\t\t\tfieldDefinition= string.Format(\"{0} ({1},{2})\", DecimalColumnDefinition, \n\t\t\t\t\tfieldLength.GetValueOrDefault(DefaultDecimalPrecision),\n\t\t\t\t\tscale.GetValueOrDefault(DefaultDecimalScale) );\n\t\t\t}\n else \n\t\t\t{\n\t\t\t\tfieldDefinition = GetColumnTypeDefinition(fieldType);\n\t\t\t}\n\n var sql = new StringBuilder();\n sql.AppendFormat(\"{0} {1}\", GetQuotedColumnName(fieldName), fieldDefinition);\n\t\t\t\n if (!isNullable)\n {\n sql.Append(\" NOT NULL\");\n }\n\n if (!string.IsNullOrEmpty(defaultValue))\n {\n sql.AppendFormat(DefaultValueFormat, defaultValue);\n }\n\n return sql.ToString();\n\t\t}\n\t\t\n\t\t\n\t\tpublic override List ToCreateIndexStatements(Type tableType)\n {\n var sqlIndexes = new List();\n\n var modelDef = GetModel(tableType);\n foreach (var fieldDef in modelDef.FieldDefinitions)\n {\n if (!fieldDef.IsIndexed) continue;\n\n var indexName = GetIndexName(\n\t\t\t\t\tfieldDef.IsUnique,\n\t\t\t\t\t(modelDef.IsInSchema \n\t\t\t\t\t\t? modelDef.Schema + \"_\" + modelDef.ModelName\n\t\t\t\t\t\t: modelDef.ModelName).SafeVarName(), \n\t\t\t\t\tfieldDef.FieldName);\n\n sqlIndexes.Add(\n ToCreateIndexStatement(fieldDef.IsUnique, indexName, modelDef, fieldDef.FieldName,false));\n }\n\n foreach (var compositeIndex in modelDef.CompositeIndexes)\n {\n var indexName = GetIndexName(compositeIndex.Unique,\n\t\t\t\t\t(modelDef.IsInSchema ?\n\t\t\t\t \t\tmodelDef.Schema +\"_\"+ GetQuotedTableName(modelDef):\n\t\t\t\t \t\tGetQuotedTableName(modelDef) ).SafeVarName(),\n string.Join(\"_\", compositeIndex.FieldNames.ToArray()));\n\n var indexNames = string.Join(\",\", compositeIndex.FieldNames.ToArray());\n\n sqlIndexes.Add(\n ToCreateIndexStatement(compositeIndex.Unique, indexName, modelDef, indexNames,false));\n }\n\n return sqlIndexes;\n }\n\t\t\n\t\tprotected override string ToCreateIndexStatement(bool isUnique, string indexName, ModelDefinition modelDef, string fieldName, bool isCombined)\n {\n return string.Format(\"CREATE {0} INDEX {1} ON {2} ({3} ); \\n\",\n\t\t\t\tisUnique ? \"UNIQUE\" : \"\", \n\t\t\t\tindexName, \n\t\t\t\tGetQuotedTableName(modelDef),\n\t\t\t\tGetQuotedColumnName(fieldName));\n }\n\t\t\n\t\t\n\t\tpublic override string ToExistStatement( Type fromTableType,\n\t\t\tobject objWithProperties,\n\t\t\tstring sqlFilter,\n\t\t\tparams object[] filterParams)\n\t\t{\n\t\t\t\n\t\t\tvar fromModelDef = GetModel(fromTableType);\n\t\t\tvar sql = new StringBuilder();\n\t\t\tsql.AppendFormat(\"SELECT 1 \\nFROM {0}\", GetQuotedTableName(fromModelDef));\n\t\t\t\n\t\t\tvar filter = new StringBuilder();\n\t\t\t\n\t\t\tif(objWithProperties!=null){\n\t\t\t\tvar tableType = objWithProperties.GetType();\n\t\t\t\t\n\t\t\t\tif(fromTableType!=tableType){\n\t\t\t\t\tint i=0;\n\t\t\t\t\tvar fpk= new List();\t\t\t\t\t\n\t\t\t\t\tvar modelDef = GetModel(tableType);\n\t\t\t\t\t\n\t\t\t\t\tforeach (var def in modelDef.FieldDefinitions)\n\t\t\t\t\t{\n\t\t\t\t\t\tif (def.IsPrimaryKey) fpk.Add(def);\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tforeach (var fieldDef in fromModelDef.FieldDefinitions)\n\t\t\t\t\t{\n\t\t\t\t\t\tif (fieldDef.IsComputed) continue;\n\t\t\t\t\t\ttry\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tif (fieldDef.ForeignKey !=null\n\t\t\t\t\t\t\t\t&& GetModel(fieldDef.ForeignKey.ReferenceType).ModelName == modelDef.ModelName)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tif (filter.Length > 0) filter.Append(\" AND \");\n\t\t\t\t\t\t\t\tfilter.AppendFormat(\"{0} = {1}\", GetQuotedColumnName(fieldDef.FieldName),\n\t\t\t\t\t\t\t\t\tfpk[i].GetQuotedValue(objWithProperties));\t\n\t\t\t\t\t\t\t\ti++;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\t\n\t\t\t\t\t\tcatch (Exception)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tthrow;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\t\n\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tvar modelDef = GetModel(tableType);\n\t\t\t\t\tforeach (var fieldDef in modelDef.FieldDefinitions)\n\t\t\t\t\t{\n\t\t\t\t\t\tif (fieldDef.IsComputed) continue;\n\t\t\t\t\t\ttry\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tif (fieldDef.IsPrimaryKey)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tif (filter.Length > 0) filter.Append(\" AND \");\n\t\t\t\t\t\t\t\tfilter.AppendFormat(\"{0} = {1}\",\n\t\t\t\t\t\t\t\t\tGetQuotedColumnName(fieldDef.FieldName),\n\t\t\t\t\t\t\t\t\tfieldDef.GetQuotedValue(objWithProperties));\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcatch (Exception)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tthrow;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\tif (filter.Length>0) sql.AppendFormat(\"\\nWHERE {0} \", filter);\n\t\t\t}\t\n\t\t\t\n\t\t\tif (!string.IsNullOrEmpty(sqlFilter))\n\t\t\t{\n\t\t\t\tsqlFilter = sqlFilter.SqlFormat(filterParams);\n\t\t\t\tif (!sqlFilter.StartsWith(\"\\nORDER \", StringComparison.InvariantCultureIgnoreCase)\n\t\t\t\t\t&& !sqlFilter.StartsWith(\"\\nROWS \", StringComparison.InvariantCultureIgnoreCase)) // ROWS [TO ])\n\t\t\t\t{\n\t\t\t\t\tsql.Append( filter.Length>0? \" AND \": \"\\nWHERE \");\n\t\t\t\t}\n\t\t\t\tsql.Append(sqlFilter);\n\t\t\t}\n\t\t\t \t\t\n\t\t\tvar sb = new StringBuilder(\"select 1 from RDB$DATABASE where\");\n\t\t\tsb.AppendFormat(\" exists ({0})\", sql.ToString() );\n\t\t\treturn sb.ToString();\n\t\t}\n\t\t\n\t\tpublic override string ToSelectFromProcedureStatement(\n\t\t\tobject fromObjWithProperties,\n\t\t\tType outputModelType, \n\t\t\tstring sqlFilter, \n\t\t\tparams object[] filterParams)\t\t\n\t\t{\n\t\t\t\t\t\t\n\t\t\tvar sbColumnValues = new StringBuilder();\n\t\t\t\n\t\t\tType fromTableType = fromObjWithProperties.GetType();\n\t\t\t\n\t\t\tvar modelDef = GetModel(fromTableType);\n\t\t\t\n\t\t\tforeach (var fieldDef in modelDef.FieldDefinitions)\n\t\t\t{\t\n\t\t\t\tif (sbColumnValues.Length > 0) sbColumnValues.Append(\",\");\n\n\t\t\t\ttry\n\t\t\t\t{\n\t\t\t\t\tsbColumnValues.Append( fieldDef.GetQuotedValue(fromObjWithProperties) );\t\n\t\t\t\t}\n\t\t\t\tcatch (Exception)\n\t\t\t\t{\t\n\t\t\t\t\tthrow;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tvar sql = new StringBuilder();\n\t\t\tsql.AppendFormat(\"SELECT {0} \\nFROM {1} {2}{3}{4} \\n\",\n\t\t\t\tGetColumnNames(GetModel(outputModelType)),\n\t\t\t\tGetQuotedTableName(modelDef),\n\t\t\t\tsbColumnValues.Length > 0 ? \"(\" : \"\",\n\t\t\t\tsbColumnValues,\n\t\t\t\tsbColumnValues.Length > 0 ? \")\" : \"\");\n\t\t\t\n\t\t\tif (!string.IsNullOrEmpty(sqlFilter))\n\t\t\t{\n\t\t\t\tsqlFilter = sqlFilter.SqlFormat(filterParams);\n\t\t\t\tif (!sqlFilter.StartsWith(\"\\nORDER \", StringComparison.InvariantCultureIgnoreCase)\n\t\t\t\t\t&& !sqlFilter.StartsWith(\"\\nROWS \", StringComparison.InvariantCultureIgnoreCase)) // ROWS [TO ]\n\t\t\t\t{\n\t\t\t\t\tsql.Append(\"\\nWHERE \");\n\t\t\t\t}\n\t\t\t\tsql.Append(sqlFilter);\n\t\t\t}", "answers": ["\t\t\treturn sql.ToString();\t\t"], "length": 1481, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "87730307-608e-4dc0-8875-33b99d4ea28d", "reasoning": "The method ToSelectFromProcedureStatement builds a SQL string in the variable 'sql'. After handling optional sqlFilter, the method should finish by returning the constructed query. Consistent with other methods (e.g., ToSelectStatement) that end with 'return sql.ToString();', the next line is the return statement.", "reasoning_model_answer": "return sql.ToString();", "assistant_with_reasoning": "\nThe method ToSelectFromProcedureStatement builds a SQL string in the variable 'sql'. After handling optional sqlFilter, the method should finish by returning the constructed query. Consistent with other methods (e.g., ToSelectStatement) that end with 'return sql.ToString();', the next line is the return statement.\n\nreturn sql.ToString();", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.365, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 19427, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "return sql.ToString();", "score": 0.9, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "\"\"\"Common IO api utilities\"\"\"\n\nimport os\nimport csv\nimport codecs\nimport mmap\nfrom contextlib import contextmanager, closing\n\nfrom pandas.compat import StringIO, BytesIO, string_types, text_type\nfrom pandas import compat\nfrom pandas.io.formats.printing import pprint_thing\nfrom pandas.core.common import AbstractMethodError\nfrom pandas.core.dtypes.common import is_number, is_file_like\n\n# compat\nfrom pandas.errors import (ParserError, DtypeWarning, # noqa\n EmptyDataError, ParserWarning)\n\n# gh-12665: Alias for now and remove later.\nCParserError = ParserError\n\n# common NA values\n# no longer excluding inf representations\n# '1.#INF','-1.#INF', '1.#INF000000',\n_NA_VALUES = set([\n '-1.#IND', '1.#QNAN', '1.#IND', '-1.#QNAN', '#N/A N/A', '#N/A',\n 'N/A', 'n/a', 'NA', '#NA', 'NULL', 'null', 'NaN', '-NaN', 'nan', '-nan', ''\n])\n\n\nif compat.PY3:\n from urllib.request import urlopen, pathname2url\n _urlopen = urlopen\n from urllib.parse import urlparse as parse_url\n from urllib.parse import (uses_relative, uses_netloc, uses_params,\n urlencode, urljoin)\n from urllib.error import URLError\n from http.client import HTTPException # noqa\nelse:\n from urllib2 import urlopen as _urlopen\n from urllib import urlencode, pathname2url # noqa\n from urlparse import urlparse as parse_url\n from urlparse import uses_relative, uses_netloc, uses_params, urljoin\n from urllib2 import URLError # noqa\n from httplib import HTTPException # noqa\n from contextlib import contextmanager, closing # noqa\n from functools import wraps # noqa\n\n # @wraps(_urlopen)\n @contextmanager\n def urlopen(*args, **kwargs):\n with closing(_urlopen(*args, **kwargs)) as f:\n yield f\n\n\n_VALID_URLS = set(uses_relative + uses_netloc + uses_params)\n_VALID_URLS.discard('')\n\n\nclass BaseIterator(object):\n \"\"\"Subclass this and provide a \"__next__()\" method to obtain an iterator.\n Useful only when the object being iterated is non-reusable (e.g. OK for a\n parser, not for an in-memory table, yes for its iterator).\"\"\"\n\n def __iter__(self):\n return self\n\n def __next__(self):\n raise AbstractMethodError(self)\n\n\nif not compat.PY3:\n BaseIterator.next = lambda self: self.__next__()\n\n\ndef _is_url(url):\n \"\"\"Check to see if a URL has a valid protocol.\n\n Parameters\n ----------\n url : str or unicode\n\n Returns\n -------\n isurl : bool\n If `url` has a valid protocol return True otherwise False.\n \"\"\"\n try:\n return parse_url(url).scheme in _VALID_URLS\n except:\n return False\n\n\ndef _is_s3_url(url):\n \"\"\"Check for an s3, s3n, or s3a url\"\"\"\n try:\n return parse_url(url).scheme in ['s3', 's3n', 's3a']\n except:\n return False\n\n\ndef _expand_user(filepath_or_buffer):\n \"\"\"Return the argument with an initial component of ~ or ~user\n replaced by that user's home directory.\n\n Parameters\n ----------\n filepath_or_buffer : object to be converted if possible\n\n Returns\n -------\n expanded_filepath_or_buffer : an expanded filepath or the\n input if not expandable\n \"\"\"\n if isinstance(filepath_or_buffer, string_types):\n return os.path.expanduser(filepath_or_buffer)\n return filepath_or_buffer\n\n\ndef _validate_header_arg(header):\n if isinstance(header, bool):\n raise TypeError(\"Passing a bool to header is invalid. \"\n \"Use header=None for no header or \"\n \"header=int or list-like of ints to specify \"\n \"the row(s) making up the column names\")\n\n\ndef _stringify_path(filepath_or_buffer):\n \"\"\"Attempt to convert a path-like object to a string.\n\n Parameters\n ----------\n filepath_or_buffer : object to be converted\n\n Returns\n -------\n str_filepath_or_buffer : maybe a string version of the object\n\n Notes\n -----\n Objects supporting the fspath protocol (python 3.6+) are coerced\n according to its __fspath__ method.\n\n For backwards compatibility with older pythons, pathlib.Path and\n py.path objects are specially coerced.\n\n Any other object is passed through unchanged, which includes bytes,\n strings, buffers, or anything else that's not even path-like.\n \"\"\"\n try:\n import pathlib\n _PATHLIB_INSTALLED = True\n except ImportError:\n _PATHLIB_INSTALLED = False\n\n try:\n from py.path import local as LocalPath\n _PY_PATH_INSTALLED = True\n except ImportError:\n _PY_PATH_INSTALLED = False\n\n if hasattr(filepath_or_buffer, '__fspath__'):\n return filepath_or_buffer.__fspath__()\n if _PATHLIB_INSTALLED and isinstance(filepath_or_buffer, pathlib.Path):\n return text_type(filepath_or_buffer)\n if _PY_PATH_INSTALLED and isinstance(filepath_or_buffer, LocalPath):\n return filepath_or_buffer.strpath\n return filepath_or_buffer\n\n\ndef get_filepath_or_buffer(filepath_or_buffer, encoding=None,\n compression=None):\n \"\"\"\n If the filepath_or_buffer is a url, translate and return the buffer.\n Otherwise passthrough.\n\n Parameters\n ----------\n filepath_or_buffer : a url, filepath (str, py.path.local or pathlib.Path),\n or buffer\n encoding : the encoding to use to decode py3 bytes, default is 'utf-8'\n\n Returns\n -------\n a filepath_or_buffer, the encoding, the compression\n \"\"\"\n filepath_or_buffer = _stringify_path(filepath_or_buffer)\n\n if _is_url(filepath_or_buffer):\n req = _urlopen(filepath_or_buffer)\n content_encoding = req.headers.get('Content-Encoding', None)\n if content_encoding == 'gzip':\n # Override compression based on Content-Encoding header\n compression = 'gzip'\n reader = BytesIO(req.read())\n return reader, encoding, compression\n\n if _is_s3_url(filepath_or_buffer):\n from pandas.io import s3\n return s3.get_filepath_or_buffer(filepath_or_buffer,\n encoding=encoding,\n compression=compression)\n\n if isinstance(filepath_or_buffer, (compat.string_types,\n compat.binary_type,\n mmap.mmap)):\n return _expand_user(filepath_or_buffer), None, compression\n\n if not is_file_like(filepath_or_buffer):\n msg = \"Invalid file path or buffer object type: {_type}\"\n raise ValueError(msg.format(_type=type(filepath_or_buffer)))\n\n return filepath_or_buffer, None, compression\n\n\ndef file_path_to_url(path):\n \"\"\"\n converts an absolute native path to a FILE URL.\n\n Parameters\n ----------\n path : a path in native format\n\n Returns\n -------\n a valid FILE URL\n \"\"\"\n return urljoin('file:', pathname2url(path))\n\n\n_compression_to_extension = {\n 'gzip': '.gz',\n 'bz2': '.bz2',\n 'zip': '.zip',\n 'xz': '.xz',\n}\n\n\ndef _infer_compression(filepath_or_buffer, compression):\n \"\"\"\n Get the compression method for filepath_or_buffer. If compression='infer',\n the inferred compression method is returned. Otherwise, the input\n compression method is returned unchanged, unless it's invalid, in which\n case an error is raised.\n\n Parameters\n ----------\n filepath_or_buf :\n a path (str) or buffer\n compression : str or None\n the compression method including None for no compression and 'infer'\n\n Returns\n -------\n string or None :\n compression method\n\n Raises\n ------\n ValueError on invalid compression specified\n \"\"\"\n\n # No compression has been explicitly specified\n if compression is None:\n return None\n\n # Infer compression\n if compression == 'infer':\n # Convert all path types (e.g. pathlib.Path) to strings\n filepath_or_buffer = _stringify_path(filepath_or_buffer)\n if not isinstance(filepath_or_buffer, compat.string_types):\n # Cannot infer compression of a buffer, assume no compression\n return None\n\n # Infer compression from the filename/URL extension\n for compression, extension in _compression_to_extension.items():\n if filepath_or_buffer.endswith(extension):\n return compression\n return None\n\n # Compression has been specified. Check that it's valid\n if compression in _compression_to_extension:\n return compression\n\n msg = 'Unrecognized compression type: {}'.format(compression)\n valid = ['infer', None] + sorted(_compression_to_extension)\n msg += '\\nValid compression types are {}'.format(valid)\n raise ValueError(msg)\n\n\ndef _get_handle(path_or_buf, mode, encoding=None, compression=None,\n memory_map=False, is_text=True):\n \"\"\"\n Get file handle for given path/buffer and mode.\n\n Parameters\n ----------\n path_or_buf :\n a path (str) or buffer\n mode : str\n mode to open path_or_buf with\n encoding : str or None\n compression : str or None\n Supported compression protocols are gzip, bz2, zip, and xz\n memory_map : boolean, default False\n See parsers._parser_params for more information.\n is_text : boolean, default True\n whether file/buffer is in text format (csv, json, etc.), or in binary\n mode (pickle, etc.)\n Returns\n -------\n f : file-like\n A file-like object\n handles : list of file-like objects\n A list of file-like object that were openned in this function.\n \"\"\"\n try:\n from s3fs import S3File\n need_text_wrapping = (BytesIO, S3File)\n except ImportError:\n need_text_wrapping = (BytesIO,)\n\n handles = list()\n f = path_or_buf\n\n # Convert pathlib.Path/py.path.local or string\n path_or_buf = _stringify_path(path_or_buf)\n is_path = isinstance(path_or_buf, compat.string_types)\n\n if compression:\n\n if compat.PY2 and not is_path and encoding:\n msg = 'compression with encoding is not yet supported in Python 2'\n raise ValueError(msg)\n\n # GZ Compression\n if compression == 'gzip':\n import gzip\n if is_path:\n f = gzip.open(path_or_buf, mode)\n else:\n f = gzip.GzipFile(fileobj=path_or_buf)\n\n # BZ Compression\n elif compression == 'bz2':\n import bz2\n if is_path:\n f = bz2.BZ2File(path_or_buf, mode)\n elif compat.PY2:\n # Python 2's bz2 module can't take file objects, so have to\n # run through decompress manually\n f = StringIO(bz2.decompress(path_or_buf.read()))\n path_or_buf.close()\n else:\n f = bz2.BZ2File(path_or_buf)\n\n # ZIP Compression\n elif compression == 'zip':\n import zipfile\n zip_file = zipfile.ZipFile(path_or_buf)\n zip_names = zip_file.namelist()\n if len(zip_names) == 1:\n f = zip_file.open(zip_names.pop())\n elif len(zip_names) == 0:\n raise ValueError('Zero files found in ZIP file {}'\n .format(path_or_buf))\n else:\n raise ValueError('Multiple files found in ZIP file.'\n ' Only one file per ZIP: {}'\n .format(zip_names))\n\n # XZ Compression\n elif compression == 'xz':\n lzma = compat.import_lzma()\n f = lzma.LZMAFile(path_or_buf, mode)\n\n # Unrecognized Compression\n else:\n msg = 'Unrecognized compression type: {}'.format(compression)\n raise ValueError(msg)\n\n handles.append(f)\n\n elif is_path:\n if compat.PY2:\n # Python 2\n f = open(path_or_buf, mode)\n elif encoding:\n # Python 3 and encoding\n f = open(path_or_buf, mode, encoding=encoding)\n elif is_text:\n # Python 3 and no explicit encoding\n f = open(path_or_buf, mode, errors='replace')\n else:\n # Python 3 and binary mode\n f = open(path_or_buf, mode)\n handles.append(f)\n\n # in Python 3, convert BytesIO or fileobjects passed with an encoding\n if compat.PY3 and is_text and\\\n (compression or isinstance(f, need_text_wrapping)):\n from io import TextIOWrapper\n f = TextIOWrapper(f, encoding=encoding)\n handles.append(f)\n\n if memory_map and hasattr(f, 'fileno'):\n try:\n g = MMapWrapper(f)\n f.close()\n f = g\n except Exception:\n # we catch any errors that may have occurred\n # because that is consistent with the lower-level\n # functionality of the C engine (pd.read_csv), so\n # leave the file handler as is then\n pass\n\n return f, handles\n\n\nclass MMapWrapper(BaseIterator):\n \"\"\"\n Wrapper for the Python's mmap class so that it can be properly read in\n by Python's csv.reader class.\n\n Parameters\n ----------\n f : file object\n File object to be mapped onto memory. Must support the 'fileno'\n method or have an equivalent attribute\n\n \"\"\"\n", "answers": [" def __init__(self, f):"], "length": 1360, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "6e0cd3b0-fead-4cc4-b8d4-9e326c671323", "reasoning": "The class MMapWrapper is being defined. After the docstring, the next logical line is the initializer method that takes the file object to wrap. In pandas' implementation, the first method defined inside the class is __init__(self, f). Therefore the next line should be the definition of that method.", "reasoning_model_answer": "def __init__(self, f):", "assistant_with_reasoning": "\nThe class MMapWrapper is being defined. After the docstring, the next logical line is the initializer method that takes the file object to wrap. In pandas' implementation, the first method defined inside the class is __init__(self, f). Therefore the next line should be the definition of that method.\n\ndef __init__(self, f):", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.215, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 13416, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "def __init__(self, f):", "score": 0.92, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/*\nCopyright 2010 Google Inc\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nusing System;\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Diagnostics;\n\nnamespace Google.Apis.Util\n{\n /// \n /// Provides the base class for a generic read-only dictionary.\n /// \n /// \n /// The type of keys in the dictionary.\n /// \n /// \n /// The type of values in the dictionary.\n /// \n /// \n /// \n /// An instance of the ReadOnlyDictionary generic class is\n /// always read-only. A dictionary that is read-only is simply a\n /// dictionary with a wrapper that prevents modifying the\n /// dictionary; therefore, if changes are made to the underlying\n /// dictionary, the read-only dictionary reflects those changes. \n /// See for a modifiable version of \n /// this class.\n /// \n /// \n /// Notes to Implementers This base class is provided to \n /// make it easier for implementers to create a generic read-only\n /// custom dictionary. Implementers are encouraged to extend this\n /// base class instead of creating their own. \n /// \n /// \n [DebuggerDisplay(\"Count = {Count}\")]\n [DebuggerTypeProxy(typeof(ReadOnlyDictionaryDebugView<,>))]\n#if !SILVERLIGHT \n [Serializable]\n#endif\n public class ReadOnlyDictionary : IDictionary, IDictionary\n {\n private readonly IDictionary source;\n\n /// \n /// Initializes a new instance of the\n /// class that wraps\n /// the supplied .\n /// \n /// The \n /// that will be wrapped.\n /// \n /// Thrown when the dictionary is null.\n /// \n public ReadOnlyDictionary(IDictionary dictionaryToWrap)\n {\n if (dictionaryToWrap == null)\n {\n throw new ArgumentNullException(\"dictionaryToWrap\");\n }\n\n source = dictionaryToWrap;\n }\n\n #region IDictionary Members\n\n /// Gets a value indicating whether the \n /// dictionary has a fixed size. This property will\n /// always return true.\n bool IDictionary.IsFixedSize\n {\n get { return true; }\n }\n\n /// Gets a value indicating whether the \n /// dictionary is read-only.This property will\n /// always return true.\n bool IDictionary.IsReadOnly\n {\n get { return true; }\n }\n\n /// Gets an object \n /// containing the keys of the dictionary object.\n ICollection IDictionary.Keys\n {\n get { return ((IDictionary) source).Keys; }\n }\n\n /// \n /// Gets an ICollection object containing the values in the DictionaryBase object.\n /// \n ICollection IDictionary.Values\n {\n get { return ((IDictionary) source).Values; }\n }\n\n /// \n /// Gets a value indicating whether access to the dictionary\n /// is synchronized (thread safe).\n /// \n bool ICollection.IsSynchronized\n {\n get { return ((ICollection) source).IsSynchronized; }\n }\n\n /// \n /// Gets an object that can be used to synchronize access to dictionary.\n /// \n object ICollection.SyncRoot\n {\n get { return ((ICollection) source).SyncRoot; }\n }\n\n /// \n /// Gets or sets the element with the specified key. \n /// \n /// The key of the element to get or set.\n /// The element with the specified key. \n /// \n /// Thrown when a value is set.\n /// \n /// \n /// Thrown when the key is a null reference (Nothing in Visual Basic).\n /// \n object IDictionary.this[object key]\n {\n get { return ((IDictionary) source)[key]; }\n set { ThrowNotSupportedException(); }\n }\n\n /// \n /// This method is not supported by the .\n /// \n /// \n /// The System.Object to use as the key of the element to add.\n /// \n /// \n /// The System.Object to use as the value of the element to add.\n /// \n void IDictionary.Add(object key, object value)\n {\n ThrowNotSupportedException();\n }\n\n /// \n /// This method is not supported by the .\n /// \n void IDictionary.Clear()\n {\n ThrowNotSupportedException();\n }\n\n /// \n /// Determines whether the IDictionary object contains an element\n /// with the specified key.\n /// \n /// \n /// The key to locate in the IDictionary object.\n /// \n /// \n /// true if the IDictionary contains an element with the key;\n /// otherwise, false.\n /// \n bool IDictionary.Contains(object key)\n {\n return ((IDictionary) source).Contains(key);\n }\n\n /// \n /// Returns an for the\n /// . \n /// \n /// \n /// An IDictionaryEnumerator for the IDictionary.\n /// \n IDictionaryEnumerator IDictionary.GetEnumerator()\n {\n return ((IDictionary) source).GetEnumerator();\n }\n\n /// \n /// This method is not supported by the .\n /// \n /// \n /// Gets an object containing the keys of the \n /// object.\n /// \n void IDictionary.Remove(object key)\n {\n ThrowNotSupportedException();\n }\n\n /// \n /// For a description of this member, see . \n /// \n /// \n /// The one-dimensional Array that is the destination of the elements copied from \n /// ICollection. The Array must have zero-based indexing.\n /// \n /// \n /// The zero-based index in Array at which copying begins.\n /// \n void ICollection.CopyTo(Array array, int index)\n {\n ((ICollection) source).CopyTo(array, index);\n }\n\n #endregion\n\n #region IDictionary Members\n\n /// \n /// Gets the number of key/value pairs contained in the\n /// .\n /// \n /// The number of key/value pairs.\n /// The number of key/value pairs contained in the\n /// .\n public int Count\n {\n get { return source.Count; }\n }\n\n /// Gets a collection containing the keys in the\n /// .\n /// A \n /// containing the keys.\n /// A\n /// \n /// containing the keys in the\n /// .\n /// \n public ICollection Keys\n {\n get { return source.Keys; }\n }\n\n /// \n /// Gets a collection containing the values of the\n /// .\n /// \n /// The collection of values.\n public ICollection Values\n {\n get { return source.Values; }\n }\n\n /// Gets a value indicating whether the dictionary is read-only.\n /// This value will always be true.\n bool ICollection>.IsReadOnly\n {\n get { return true; }\n }\n\n /// \n /// Gets or sets the value associated with the specified key.\n /// \n /// \n /// The value associated with the specified key. If the specified key\n /// is not found, a get operation throws a \n /// ,\n /// and a set operation creates a new element with the specified key.\n /// \n /// The key of the value to get or set.\n /// \n /// Thrown when the key is null.\n /// \n /// \n /// The property is retrieved and key does not exist in the collection.\n /// \n public TValue this[TKey key]\n {\n get { return source[key]; }\n set { ThrowNotSupportedException(); }\n }\n\n /// This method is not supported by the \n /// .\n /// \n /// The object to use as the key of the element to add.\n /// \n /// The object to use as the value of the element to add.\n void IDictionary.Add(TKey key, TValue value)\n {\n ThrowNotSupportedException();\n }\n\n /// Determines whether the \n /// contains the specified key.\n /// \n /// True if the contains\n /// an element with the specified key; otherwise, false.\n /// \n /// The key to locate in the\n /// .\n /// \n /// Thrown when the key is null.\n /// \n public bool ContainsKey(TKey key)\n {\n return source.ContainsKey(key);\n }\n\n /// \n /// This method is not supported by the .\n /// \n /// The key of the element to remove.\n /// \n /// True if the element is successfully removed; otherwise, false.\n /// \n bool IDictionary.Remove(TKey key)\n {\n ThrowNotSupportedException();\n return false;\n }\n\n /// \n /// Gets the value associated with the specified key.\n /// \n /// The key of the value to get.\n /// When this method returns, contains the value\n /// associated with the specified key, if the key is found;\n /// otherwise, the default value for the type of the value parameter.\n /// This parameter is passed uninitialized.\n /// \n /// true if the contains\n /// an element with the specified key; otherwise, false.\n /// ", "answers": [" public bool TryGetValue(TKey key, out TValue value)"], "length": 1357, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "c76f5a1a-18a3-4d66-9fdf-bea7a12ac4a9", "reasoning": "The code is inside the IDictionary region of a read‑only dictionary implementation. After the XML comment describing a method that returns a bool indicating whether a key exists and outputs its value, the next member is the TryGetValue method signature. The appropriate line is the public method declaration matching IDictionary.TryGetValue.", "reasoning_model_answer": "public bool TryGetValue(TKey key, out TValue value)", "assistant_with_reasoning": "\nThe code is inside the IDictionary region of a read‑only dictionary implementation. After the XML comment describing a method that returns a bool indicating whether a key exists and outputs its value, the next member is the TryGetValue method signature. The appropriate line is the public method declaration matching IDictionary.TryGetValue.\n\npublic bool TryGetValue(TKey key, out TValue value)", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 2.652, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 12747, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "public bool TryGetValue(TKey key, out TValue value)", "score": 0.93, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "# coding=utf-8\n# Copyright 2015 Pants project contributors (see CONTRIBUTORS.md).\n# Licensed under the Apache License, Version 2.0 (see LICENSE).\n\nfrom __future__ import (absolute_import, division, generators, nested_scopes, print_function,\n unicode_literals, with_statement)\n\nimport os\n\nfrom pants.base.build_environment import get_buildroot\nfrom pants.base.exceptions import TaskError\nfrom pants.build_graph.files import Files\nfrom pants.cache.cache_setup import CacheSetup\nfrom pants.option.arg_splitter import GLOBAL_SCOPE\nfrom pants.subsystem.subsystem import Subsystem\nfrom pants.subsystem.subsystem_client_mixin import SubsystemDependency\nfrom pants.task.task import Task\nfrom pants.util.dirutil import safe_rmtree\nfrom pants_test.tasks.task_test_base import TaskTestBase\n\n\nclass DummyTask(Task):\n \"\"\"A task that appends the content of a Files's sources into its results_dir.\"\"\"\n\n _implementation_version = 0\n _force_fail = False\n\n @property\n def incremental(self):\n return self._incremental\n\n @property\n def cache_target_dirs(self):\n return True\n\n @classmethod\n def implementation_version_str(cls):\n # NB: Intentionally ignoring `super` and returning a simplified version.\n return str(cls._implementation_version)\n\n # Enforces a single VT and returns a tuple of (vt, was_valid).\n def execute(self):\n with self.invalidated(self.context.targets()) as invalidation:\n assert len(invalidation.all_vts) == 1\n vt = invalidation.all_vts[0]\n was_valid = vt.valid\n if not was_valid:\n if vt.is_incremental:\n assert os.path.isdir(vt.previous_results_dir)\n for source in vt.target.sources_relative_to_buildroot():\n with open(os.path.join(get_buildroot(), source), 'r') as infile:\n outfile_name = os.path.join(vt.results_dir, source)\n with open(outfile_name, 'a') as outfile:\n outfile.write(infile.read())\n if self._force_fail:\n raise TaskError('Task forced to fail before updating vt state.')\n vt.update()\n return vt, was_valid\n\n\nclass FakeTask(Task):\n _impls = []\n\n @classmethod\n def implementation_version(cls):\n return super(FakeTask, cls).implementation_version() + cls._impls\n\n @classmethod\n def supports_passthru_args(cls):\n return True\n\n options_scope = 'fake-task'\n\n _deps = ()\n\n @classmethod\n def subsystem_dependencies(cls):\n return super(FakeTask, cls).subsystem_dependencies() + cls._deps\n\n def execute(self): pass\n\n\nclass OtherFakeTask(FakeTask):\n _other_impls = []\n\n @classmethod\n def supports_passthru_args(cls):\n return False\n\n @classmethod\n def implementation_version(cls):\n return super(OtherFakeTask, cls).implementation_version() + cls._other_impls\n\n options_scope = 'other-fake-task'\n\n\nclass FakeSubsystem(Subsystem):\n options_scope = 'fake-subsystem'\n\n @classmethod\n def register_options(cls, register):\n super(FakeSubsystem, cls).register_options(register)\n register('--fake-option', type=bool)\n\n\nclass AnotherFakeTask(Task):\n options_scope = 'another-fake-task'\n\n @classmethod\n def supports_passthru_args(cls):\n return True\n\n @classmethod\n def subsystem_dependencies(cls):\n return super(AnotherFakeTask, cls).subsystem_dependencies() + (FakeSubsystem.scoped(cls),)\n\n def execute(self): pass\n\n\nclass YetAnotherFakeTask(AnotherFakeTask):\n options_scope = 'yet-another-fake-task'\n\n @classmethod\n def supports_passthru_args(cls):\n return False\n\n\nclass TaskTest(TaskTestBase):\n\n _filename = 'f'\n _file_contents = 'results_string\\n'\n _cachedir = 'local_artifact_cache'\n\n @classmethod\n def task_type(cls):\n return DummyTask\n\n def assertContent(self, vt, content):\n with open(os.path.join(vt.current_results_dir, self._filename), 'r') as f:\n self.assertEquals(f.read(), content)\n\n def _toggle_cache(self, enable_artifact_cache):\n cache_dir = self.create_dir(self._cachedir)\n self.set_options_for_scope(\n CacheSetup.options_scope,\n write_to=[cache_dir],\n read_from=[cache_dir],\n write=enable_artifact_cache,\n read=enable_artifact_cache,\n )\n\n def _fixture(self, incremental, options=None):\n target = self.make_target(':t', target_type=Files, sources=[self._filename])\n context = self.context(options=options, target_roots=[target])\n task = self.create_task(context)\n task._incremental = incremental\n return task, target\n\n def _run_fixture(self, content=None, incremental=False, artifact_cache=False, options=None):\n content = content or self._file_contents\n self._toggle_cache(artifact_cache)\n\n task, target = self._fixture(incremental=incremental, options=options)\n self._create_clean_file(target, content)\n vtA, was_valid = task.execute()\n return task, vtA, was_valid\n\n def _create_clean_file(self, target, content):\n self.create_file(self._filename, content)\n target.mark_invalidation_hash_dirty()\n\n def _cache_ignore_options(self, globally=False):\n return {\n 'cache' + ('' if globally else '.' + self.options_scope): {\n 'ignore': True\n }\n }\n\n def _synthesize_subtype(self, name='A', scope=None, cls=FakeTask, **kwargs):\n \"\"\"Generate a synthesized subtype of `cls`.\"\"\"\n if scope is None:\n scope = cls.options_scope\n subclass_name = b'test_{0}_{1}_{2}'.format(cls.__name__, scope, name)\n kwargs['options_scope'] = scope\n return type(subclass_name, (cls,), kwargs)\n\n def _instantiate_synthesized_type(self, task_type, **kwargs):\n \"\"\"Generate a new instance of the synthesized type `task_type`.\"\"\"\n ctx = super(TaskTestBase, self).context(for_task_types=[task_type], **kwargs)\n return task_type(ctx, self.test_workdir)\n\n def _task_type_to_fp(self, task_type, **kwargs):\n \"\"\"Instantiate the `task_type` and return its fingerprint.\"\"\"\n task_object = self._instantiate_synthesized_type(task_type, **kwargs)\n return task_object.fingerprint\n\n def _synth_fp(self, scope=None, cls=FakeTask, options_fingerprintable=None, **kwargs):\n \"\"\"Synthesize a subtype of `cls`, instantiate it, and take its\n fingerprint. `options_fingerprintable` describes the registered options in\n their respective scopes which can contribute to the task fingerprint.\"\"\"\n task_type = self._synthesize_subtype(scope=scope, cls=cls, **kwargs)\n return self._task_type_to_fp(\n task_type, options_fingerprintable=options_fingerprintable)\n\n def test_revert_after_failure(self):\n # Regression test to catch the following scenario:\n #\n # 1) In state A: Task suceeds and writes some output. Key is recorded by the invalidator.\n # 2) In state B: Task fails, but writes some output. Key is not recorded.\n # 3) After reverting back to state A: The current key is the same as the one recorded at the\n # end of step 1), so it looks like no work needs to be done, but actually the task\n # must re-run, to overwrite the output written in step 2.\n\n good_content = \"good_content\"\n bad_content = \"bad_content\"\n task, target = self._fixture(incremental=False)\n\n # Clean run succeeds.\n self._create_clean_file(target, good_content)\n vt, was_valid = task.execute()\n self.assertFalse(was_valid)\n self.assertContent(vt, good_content)\n\n # Change causes the task to fail.\n self._create_clean_file(target, bad_content)\n task._force_fail = True\n self.assertRaises(TaskError, task.execute)\n task._force_fail = False\n\n # Reverting to the previous content should invalidate, so the task\n # can reset any state created by the failed run.\n self._create_clean_file(target, good_content)\n vt, was_valid = task.execute()\n self.assertFalse(was_valid)\n self.assertContent(vt, good_content)\n\n def test_incremental(self):\n \"\"\"Run three times with two unique fingerprints.\"\"\"\n\n one = '1\\n'\n two = '2\\n'\n three = '3\\n'\n task, target = self._fixture(incremental=True)\n\n # Clean - this is the first run so the VT is invalid.\n self._create_clean_file(target, one)\n vtA, was_A_valid = task.execute()\n self.assertFalse(was_A_valid)\n self.assertContent(vtA, one)\n\n # Changed the source file, so it copies the results from vtA.\n self._create_clean_file(target, two)\n vtB, was_B_valid = task.execute()\n self.assertFalse(was_B_valid)\n self.assertEqual(vtB.previous_cache_key, vtA.cache_key)\n self.assertContent(vtB, one + two)\n self.assertTrue(vtB.has_previous_results_dir)\n\n # Another changed source means a new cache_key. The previous_results_dir is copied.\n self._create_clean_file(target, three)\n vtC, was_C_valid = task.execute()\n self.assertFalse(was_C_valid)\n self.assertTrue(vtC.has_previous_results_dir)\n self.assertEqual(vtC.previous_results_dir, vtB.current_results_dir)\n self.assertContent(vtC, one + two + three)\n\n # Again create a clean file but this time reuse an old cache key - in this case vtB.\n self._create_clean_file(target, two)\n\n # This VT will be invalid, since there is no cache hit and it doesn't match the immediately\n # previous run. It will wipe the invalid vtB.current_results_dir and followup by copying in the\n # most recent results_dir, from vtC.\n vtD, was_D_valid = task.execute()\n self.assertFalse(was_D_valid)\n self.assertTrue(vtD.has_previous_results_dir)\n self.assertEqual(vtD.previous_results_dir, vtC.current_results_dir)\n self.assertContent(vtD, one + two + three + two)\n\n # And that the results_dir was stable throughout.\n self.assertEqual(vtA.results_dir, vtB.results_dir)\n self.assertEqual(vtB.results_dir, vtD.results_dir)\n\n def test_non_incremental(self):\n \"\"\"Non-incremental should be completely unassociated.\"\"\"\n\n one = '1\\n'\n two = '2\\n'\n task, target = self._fixture(incremental=False)\n\n # Run twice.\n self._create_clean_file(target, one)\n vtA, _ = task.execute()\n self.assertContent(vtA, one)\n self._create_clean_file(target, two)\n vtB, _ = task.execute()\n\n # Confirm two unassociated current directories with a stable results_dir.\n self.assertContent(vtA, one)\n self.assertContent(vtB, two)\n self.assertNotEqual(vtA.current_results_dir, vtB.current_results_dir)\n self.assertEqual(vtA.results_dir, vtB.results_dir)\n\n def test_implementation_version(self):\n \"\"\"When the implementation version changes, previous artifacts are not available.\"\"\"\n\n one = '1\\n'\n two = '2\\n'\n task, target = self._fixture(incremental=True)\n\n # Run twice, with a different implementation version the second time.\n DummyTask._implementation_version = 0\n self._create_clean_file(target, one)\n vtA, _ = task.execute()\n self.assertContent(vtA, one)\n DummyTask._implementation_version = 1\n self._create_clean_file(target, two)\n vtB, _ = task.execute()\n\n # No incrementalism.\n self.assertFalse(vtA.is_incremental)\n self.assertFalse(vtB.is_incremental)\n\n # Confirm two unassociated current directories, and unassociated stable directories.\n self.assertContent(vtA, one)\n self.assertContent(vtB, two)\n self.assertNotEqual(vtA.current_results_dir, vtB.current_results_dir)\n self.assertNotEqual(vtA.results_dir, vtB.results_dir)\n\n def test_execute_cleans_invalid_result_dirs(self):\n # Regression test to protect task.execute() from returning invalid dirs.\n task, vt, _ = self._run_fixture()\n self.assertNotEqual(os.listdir(vt.results_dir), [])\n self.assertTrue(os.path.islink(vt.results_dir))\n\n # Mimic the failure case, where an invalid task is run twice, due to failed download or\n # something.\n vt.force_invalidate()\n\n # But if this VT is invalid for a second run, the next invalidation deletes and recreates.\n self.assertTrue(os.path.islink(vt.results_dir))\n self.assertTrue(os.path.isdir(vt.current_results_dir))\n\n def test_cache_hit_short_circuits_incremental_copy(self):\n # Tasks should only copy over previous results if there is no cache hit, otherwise the copy is\n # wasted.\n first_contents = 'staid country photo'\n second_contents = 'shocking tabloid secret'\n\n self.assertFalse(self.buildroot_files(self._cachedir))\n # Initial run will have been invalid no cache hit, and with no previous_results_dir.\n task, vtA, was_A_valid = self._run_fixture(content=first_contents, incremental=True,\n artifact_cache=True)\n\n self.assertTrue(self.buildroot_files(self._cachedir))\n self.assertTrue(task.incremental)\n self.assertFalse(was_A_valid)\n\n # Invalidate and then execute with the same cache key.\n # Should be valid due to the artifact cache hit. No previous_results_dir will have been copied.\n vtA.force_invalidate()\n vtB, was_B_valid = task.execute()\n self.assertEqual(vtA.cache_key.hash, vtB.cache_key.hash)\n self.assertTrue(was_B_valid)\n self.assertFalse(vtB.has_previous_results_dir)\n\n # Change the cache_key and disable the cache_reads.\n # This results in an invalid vt, with no cache hit. It will then copy the vtB.previous_results\n # into vtC.results_dir.\n self._toggle_cache(False)\n self._create_clean_file(vtB.target, second_contents)\n\n vtC, was_C_valid = task.execute()\n self.assertNotEqual(vtB.cache_key.hash, vtC.cache_key.hash)\n self.assertEqual(vtC.previous_cache_key, vtB.cache_key)\n self.assertFalse(was_C_valid)\n\n self.assertTrue(vtC.has_previous_results_dir)\n self.assertEqual(vtB.current_results_dir, vtC.previous_results_dir)\n\n # Verify the content. The task was invalid twice - the initial run and the run with the changed\n # source file. Only vtC (previous sucessful runs + cache miss) resulted in copying the\n # previous_results.\n self.assertContent(vtC, first_contents + second_contents)\n\n # live_dirs() is in cache_manager, but like all of these tests, only makes sense to test as a\n # sequence of task runs.\n def test_live_dirs(self):\n task, vtA, _ = self._run_fixture(incremental=True)\n\n vtA_live = list(vtA.live_dirs())\n self.assertIn(vtA.results_dir, vtA_live)\n self.assertIn(vtA.current_results_dir, vtA_live)\n self.assertEqual(len(vtA_live), 2)\n\n self._create_clean_file(vtA.target, 'bar')\n vtB, _ = task.execute()\n vtB_live = list(vtB.live_dirs())\n\n # This time it contains the previous_results_dir.\n self.assertIn(vtB.results_dir, vtB_live)\n self.assertIn(vtB.current_results_dir, vtB_live)\n self.assertIn(vtA.current_results_dir, vtB_live)\n self.assertEqual(len(vtB_live), 3)\n\n # Delete vtB results_dir. live_dirs() should only return existing dirs, even if it knows the\n # previous_cache_key.\n safe_rmtree(vtB.current_results_dir)\n\n self._create_clean_file(vtB.target, 'baz')\n vtC, _ = task.execute()\n vtC_live = list(vtC.live_dirs())\n self.assertNotIn(vtB.current_results_dir, vtC_live)\n self.assertEqual(len(vtC_live), 2)\n\n def test_ignore_global(self):\n _, vtA, was_valid = self._run_fixture()\n self.assertFalse(was_valid)\n self.assertTrue(vtA.cacheable)\n\n self.reset_build_graph()\n _, vtA, was_valid = self._run_fixture()\n self.assertTrue(was_valid)\n self.assertTrue(vtA.cacheable)\n\n self.reset_build_graph()\n _, vtA, was_valid = self._run_fixture(options=self._cache_ignore_options(globally=True))\n self.assertFalse(was_valid)\n self.assertFalse(vtA.cacheable)\n\n def test_ignore(self):\n _, vtA, was_valid = self._run_fixture()\n self.assertFalse(was_valid)\n self.assertTrue(vtA.cacheable)", "answers": [" self.reset_build_graph()"], "length": 1359, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "8fa86ca3-1007-4f0b-9eaf-fb7614395079", "reasoning": "The test_ignore method mirrors test_ignore_global, which after asserting cacheable resets the build graph before running with ignore options. The next logical line is resetting the graph.", "reasoning_model_answer": "self.reset_build_graph()", "assistant_with_reasoning": "\nThe test_ignore method mirrors test_ignore_global, which after asserting cacheable resets the build graph before running with ignore options. The next logical line is resetting the graph.\n\nself.reset_build_graph()", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 5.81, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 15558, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "self.reset_build_graph()", "score": 0.92, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "from datetime import timedelta\nimport operator\n\nimport numpy as np\nimport pytest\nimport pytz\n\nfrom pandas._libs.tslibs import IncompatibleFrequency\n\nimport pandas as pd\nfrom pandas import Categorical, Index, Series, bdate_range, date_range, isna\nimport pandas._testing as tm\nfrom pandas.core import nanops, ops\n\n\ndef _permute(obj):\n return obj.take(np.random.permutation(len(obj)))\n\n\nclass TestSeriesFlexArithmetic:\n @pytest.mark.parametrize(\n \"ts\",\n [\n (lambda x: x, lambda x: x * 2, False),\n (lambda x: x, lambda x: x[::2], False),\n (lambda x: x, lambda x: 5, True),\n (lambda x: tm.makeFloatSeries(), lambda x: tm.makeFloatSeries(), True),\n ],\n )\n @pytest.mark.parametrize(\n \"opname\", [\"add\", \"sub\", \"mul\", \"floordiv\", \"truediv\", \"pow\"]\n )\n def test_flex_method_equivalence(self, opname, ts):\n # check that Series.{opname} behaves like Series.__{opname}__,\n tser = tm.makeTimeSeries().rename(\"ts\")\n\n series = ts[0](tser)\n other = ts[1](tser)\n check_reverse = ts[2]\n\n op = getattr(Series, opname)\n alt = getattr(operator, opname)\n\n result = op(series, other)\n expected = alt(series, other)\n tm.assert_almost_equal(result, expected)\n if check_reverse:\n rop = getattr(Series, \"r\" + opname)\n result = rop(series, other)\n expected = alt(other, series)\n tm.assert_almost_equal(result, expected)\n\n def test_flex_method_subclass_metadata_preservation(self, all_arithmetic_operators):\n # GH 13208\n class MySeries(Series):\n _metadata = [\"x\"]\n\n @property\n def _constructor(self):\n return MySeries\n\n opname = all_arithmetic_operators\n op = getattr(Series, opname)\n m = MySeries([1, 2, 3], name=\"test\")\n m.x = 42\n result = op(m, 1)\n assert result.x == 42\n\n def test_flex_add_scalar_fill_value(self):\n # GH12723\n s = Series([0, 1, np.nan, 3, 4, 5])\n\n exp = s.fillna(0).add(2)\n res = s.add(2, fill_value=0)\n tm.assert_series_equal(res, exp)\n\n pairings = [(Series.div, operator.truediv, 1), (Series.rdiv, ops.rtruediv, 1)]\n for op in [\"add\", \"sub\", \"mul\", \"pow\", \"truediv\", \"floordiv\"]:\n fv = 0\n lop = getattr(Series, op)\n lequiv = getattr(operator, op)\n rop = getattr(Series, \"r\" + op)\n # bind op at definition time...\n requiv = lambda x, y, op=op: getattr(operator, op)(y, x)\n pairings.append((lop, lequiv, fv))\n pairings.append((rop, requiv, fv))\n\n @pytest.mark.parametrize(\"op, equiv_op, fv\", pairings)\n def test_operators_combine(self, op, equiv_op, fv):\n def _check_fill(meth, op, a, b, fill_value=0):\n exp_index = a.index.union(b.index)\n a = a.reindex(exp_index)\n b = b.reindex(exp_index)\n\n amask = isna(a)\n bmask = isna(b)\n\n exp_values = []\n for i in range(len(exp_index)):\n with np.errstate(all=\"ignore\"):\n if amask[i]:\n if bmask[i]:\n exp_values.append(np.nan)\n continue\n exp_values.append(op(fill_value, b[i]))\n elif bmask[i]:\n if amask[i]:\n exp_values.append(np.nan)\n continue\n exp_values.append(op(a[i], fill_value))\n else:\n exp_values.append(op(a[i], b[i]))\n\n result = meth(a, b, fill_value=fill_value)\n expected = Series(exp_values, exp_index)\n tm.assert_series_equal(result, expected)\n\n a = Series([np.nan, 1.0, 2.0, 3.0, np.nan], index=np.arange(5))\n b = Series([np.nan, 1, np.nan, 3, np.nan, 4.0], index=np.arange(6))\n\n result = op(a, b)\n exp = equiv_op(a, b)\n tm.assert_series_equal(result, exp)\n _check_fill(op, equiv_op, a, b, fill_value=fv)\n # should accept axis=0 or axis='rows'\n op(a, b, axis=0)\n\n\nclass TestSeriesArithmetic:\n # Some of these may end up in tests/arithmetic, but are not yet sorted\n\n def test_add_series_with_period_index(self):\n rng = pd.period_range(\"1/1/2000\", \"1/1/2010\", freq=\"A\")\n ts = Series(np.random.randn(len(rng)), index=rng)\n\n result = ts + ts[::2]\n expected = ts + ts\n expected.iloc[1::2] = np.nan\n tm.assert_series_equal(result, expected)\n\n result = ts + _permute(ts[::2])\n tm.assert_series_equal(result, expected)\n\n msg = \"Input has different freq=D from PeriodIndex\\\\(freq=A-DEC\\\\)\"\n with pytest.raises(IncompatibleFrequency, match=msg):\n ts + ts.asfreq(\"D\", how=\"end\")\n\n @pytest.mark.parametrize(\n \"target_add,input_value,expected_value\",\n [\n (\"!\", [\"hello\", \"world\"], [\"hello!\", \"world!\"]),\n (\"m\", [\"hello\", \"world\"], [\"hellom\", \"worldm\"]),\n ],\n )\n def test_string_addition(self, target_add, input_value, expected_value):\n # GH28658 - ensure adding 'm' does not raise an error\n a = Series(input_value)\n\n result = a + target_add\n expected = Series(expected_value)\n tm.assert_series_equal(result, expected)\n\n def test_divmod(self):\n # GH#25557\n a = Series([1, 1, 1, np.nan], index=[\"a\", \"b\", \"c\", \"d\"])\n b = Series([2, np.nan, 1, np.nan], index=[\"a\", \"b\", \"d\", \"e\"])\n\n result = a.divmod(b)\n expected = divmod(a, b)\n tm.assert_series_equal(result[0], expected[0])\n tm.assert_series_equal(result[1], expected[1])\n\n result = a.rdivmod(b)\n expected = divmod(b, a)\n tm.assert_series_equal(result[0], expected[0])\n tm.assert_series_equal(result[1], expected[1])\n\n @pytest.mark.parametrize(\"index\", [None, range(9)])\n def test_series_integer_mod(self, index):\n # GH#24396\n s1 = Series(range(1, 10))\n s2 = Series(\"foo\", index=index)\n\n msg = \"not all arguments converted during string formatting\"\n\n with pytest.raises(TypeError, match=msg):\n s2 % s1\n\n def test_add_with_duplicate_index(self):\n # GH14227\n s1 = Series([1, 2], index=[1, 1])\n s2 = Series([10, 10], index=[1, 2])\n result = s1 + s2\n expected = pd.Series([11, 12, np.nan], index=[1, 1, 2])\n tm.assert_series_equal(result, expected)\n\n def test_add_na_handling(self):\n from decimal import Decimal\n from datetime import date\n\n s = Series(\n [Decimal(\"1.3\"), Decimal(\"2.3\")], index=[date(2012, 1, 1), date(2012, 1, 2)]\n )\n\n result = s + s.shift(1)\n result2 = s.shift(1) + s\n assert isna(result[0])\n assert isna(result2[0])\n\n def test_add_corner_cases(self, datetime_series):\n empty = Series([], index=Index([]), dtype=np.float64)\n\n result = datetime_series + empty\n assert np.isnan(result).all()\n\n result = empty + empty.copy()\n assert len(result) == 0\n\n # FIXME: dont leave commented-out\n # TODO: this returned NotImplemented earlier, what to do?\n # deltas = Series([timedelta(1)] * 5, index=np.arange(5))\n # sub_deltas = deltas[::2]\n # deltas5 = deltas * 5\n # deltas = deltas + sub_deltas\n\n # float + int\n int_ts = datetime_series.astype(int)[:-5]\n added = datetime_series + int_ts\n expected = Series(\n datetime_series.values[:-5] + int_ts.values,\n index=datetime_series.index[:-5],\n name=\"ts\",\n )\n tm.assert_series_equal(added[:-5], expected)\n\n def test_mul_empty_int_corner_case(self):\n s1 = Series([], [], dtype=np.int32)\n s2 = Series({\"x\": 0.0})\n tm.assert_series_equal(s1 * s2, Series([np.nan], index=[\"x\"]))\n\n def test_sub_datetimelike_align(self):\n # GH#7500\n # datetimelike ops need to align\n dt = Series(date_range(\"2012-1-1\", periods=3, freq=\"D\"))\n dt.iloc[2] = np.nan\n dt2 = dt[::-1]\n\n expected = Series([timedelta(0), timedelta(0), pd.NaT])\n # name is reset\n result = dt2 - dt\n tm.assert_series_equal(result, expected)\n\n expected = Series(expected, name=0)\n result = (dt2.to_frame() - dt.to_frame())[0]\n tm.assert_series_equal(result, expected)\n\n\n# ------------------------------------------------------------------\n# Comparisons\n\n\nclass TestSeriesFlexComparison:\n def test_comparison_flex_basic(self):\n left = pd.Series(np.random.randn(10))\n right = pd.Series(np.random.randn(10))\n\n tm.assert_series_equal(left.eq(right), left == right)\n tm.assert_series_equal(left.ne(right), left != right)\n tm.assert_series_equal(left.le(right), left < right)\n tm.assert_series_equal(left.lt(right), left <= right)\n tm.assert_series_equal(left.gt(right), left > right)\n tm.assert_series_equal(left.ge(right), left >= right)\n\n # axis\n for axis in [0, None, \"index\"]:\n tm.assert_series_equal(left.eq(right, axis=axis), left == right)\n tm.assert_series_equal(left.ne(right, axis=axis), left != right)\n tm.assert_series_equal(left.le(right, axis=axis), left < right)\n tm.assert_series_equal(left.lt(right, axis=axis), left <= right)\n tm.assert_series_equal(left.gt(right, axis=axis), left > right)\n tm.assert_series_equal(left.ge(right, axis=axis), left >= right)\n\n #\n msg = \"No axis named 1 for object type\"\n for op in [\"eq\", \"ne\", \"le\", \"le\", \"gt\", \"ge\"]:\n with pytest.raises(ValueError, match=msg):\n getattr(left, op)(right, axis=1)\n\n def test_comparison_flex_alignment(self):\n left = Series([1, 3, 2], index=list(\"abc\"))\n right = Series([2, 2, 2], index=list(\"bcd\"))\n\n exp = pd.Series([False, False, True, False], index=list(\"abcd\"))\n tm.assert_series_equal(left.eq(right), exp)\n\n exp = pd.Series([True, True, False, True], index=list(\"abcd\"))\n tm.assert_series_equal(left.ne(right), exp)\n\n exp = pd.Series([False, False, True, False], index=list(\"abcd\"))\n tm.assert_series_equal(left.le(right), exp)\n\n exp = pd.Series([False, False, False, False], index=list(\"abcd\"))\n tm.assert_series_equal(left.lt(right), exp)\n\n exp = pd.Series([False, True, True, False], index=list(\"abcd\"))\n tm.assert_series_equal(left.ge(right), exp)\n\n exp = pd.Series([False, True, False, False], index=list(\"abcd\"))\n tm.assert_series_equal(left.gt(right), exp)\n\n def test_comparison_flex_alignment_fill(self):\n left = Series([1, 3, 2], index=list(\"abc\"))\n right = Series([2, 2, 2], index=list(\"bcd\"))\n\n exp = pd.Series([False, False, True, True], index=list(\"abcd\"))\n tm.assert_series_equal(left.eq(right, fill_value=2), exp)\n\n exp = pd.Series([True, True, False, False], index=list(\"abcd\"))\n tm.assert_series_equal(left.ne(right, fill_value=2), exp)\n\n exp = pd.Series([False, False, True, True], index=list(\"abcd\"))\n tm.assert_series_equal(left.le(right, fill_value=0), exp)\n\n exp = pd.Series([False, False, False, True], index=list(\"abcd\"))\n tm.assert_series_equal(left.lt(right, fill_value=0), exp)\n\n exp = pd.Series([True, True, True, False], index=list(\"abcd\"))\n tm.assert_series_equal(left.ge(right, fill_value=0), exp)\n\n exp = pd.Series([True, True, False, False], index=list(\"abcd\"))\n tm.assert_series_equal(left.gt(right, fill_value=0), exp)\n\n\nclass TestSeriesComparison:\n def test_comparison_different_length(self):\n a = Series([\"a\", \"b\", \"c\"])\n b = Series([\"b\", \"a\"])\n msg = \"only compare identically-labeled Series\"\n with pytest.raises(ValueError, match=msg):\n a < b\n\n a = Series([1, 2])\n b = Series([2, 3, 4])\n with pytest.raises(ValueError, match=msg):\n a == b\n\n @pytest.mark.parametrize(\"opname\", [\"eq\", \"ne\", \"gt\", \"lt\", \"ge\", \"le\"])\n def test_ser_flex_cmp_return_dtypes(self, opname):\n # GH#15115\n ser = Series([1, 3, 2], index=range(3))\n const = 2\n result = getattr(ser, opname)(const).dtypes\n expected = np.dtype(\"bool\")\n assert result == expected\n\n @pytest.mark.parametrize(\"opname\", [\"eq\", \"ne\", \"gt\", \"lt\", \"ge\", \"le\"])\n def test_ser_flex_cmp_return_dtypes_empty(self, opname):\n # GH#15115 empty Series case\n ser = Series([1, 3, 2], index=range(3))\n empty = ser.iloc[:0]\n const = 2\n result = getattr(empty, opname)(const).dtypes\n expected = np.dtype(\"bool\")\n assert result == expected\n\n @pytest.mark.parametrize(\n \"op\",\n [operator.eq, operator.ne, operator.le, operator.lt, operator.ge, operator.gt],\n )\n @pytest.mark.parametrize(\n \"names\", [(None, None, None), (\"foo\", \"bar\", None), (\"baz\", \"baz\", \"baz\")]\n )\n def test_ser_cmp_result_names(self, names, op):\n # datetime64 dtype\n dti = pd.date_range(\"1949-06-07 03:00:00\", freq=\"H\", periods=5, name=names[0])\n ser = Series(dti).rename(names[1])\n result = op(ser, dti)\n assert result.name == names[2]\n\n # datetime64tz dtype\n dti = dti.tz_localize(\"US/Central\")\n dti = pd.DatetimeIndex(dti, freq=\"infer\") # freq not preserved by tz_localize\n ser = Series(dti).rename(names[1])\n result = op(ser, dti)\n assert result.name == names[2]\n\n # timedelta64 dtype\n tdi = dti - dti.shift(1)\n ser = Series(tdi).rename(names[1])\n result = op(ser, tdi)\n assert result.name == names[2]\n\n # interval dtype\n if op in [operator.eq, operator.ne]:\n # interval dtype comparisons not yet implemented\n ii = pd.interval_range(start=0, periods=5, name=names[0])\n ser = Series(ii).rename(names[1])\n result = op(ser, ii)\n assert result.name == names[2]\n\n # categorical\n if op in [operator.eq, operator.ne]:\n # categorical dtype comparisons raise for inequalities\n cidx = tdi.astype(\"category\")\n ser = Series(cidx).rename(names[1])\n result = op(ser, cidx)\n assert result.name == names[2]\n\n def test_comparisons(self):\n left = np.random.randn(10)\n right = np.random.randn(10)\n left[:3] = np.nan\n\n result = nanops.nangt(left, right)\n with np.errstate(invalid=\"ignore\"):\n expected = (left > right).astype(\"O\")\n expected[:3] = np.nan\n\n tm.assert_almost_equal(result, expected)\n\n s = Series([\"a\", \"b\", \"c\"])\n s2 = Series([False, True, False])\n\n # it works!\n exp = Series([False, False, False])\n tm.assert_series_equal(s == s2, exp)\n tm.assert_series_equal(s2 == s, exp)\n\n # -----------------------------------------------------------------\n # Categorical Dtype Comparisons\n\n def test_categorical_comparisons(self):\n # GH#8938\n # allow equality comparisons\n a = Series(list(\"abc\"), dtype=\"category\")\n b = Series(list(\"abc\"), dtype=\"object\")\n c = Series([\"a\", \"b\", \"cc\"], dtype=\"object\")\n d = Series(list(\"acb\"), dtype=\"object\")\n e = Categorical(list(\"abc\"))\n f = Categorical(list(\"acb\"))\n\n # vs scalar\n assert not (a == \"a\").all()\n assert ((a != \"a\") == ~(a == \"a\")).all()\n\n assert not (\"a\" == a).all()\n assert (a == \"a\")[0]\n assert (\"a\" == a)[0]\n assert not (\"a\" != a)[0]\n\n # vs list-like\n assert (a == a).all()\n assert not (a != a).all()\n\n assert (a == list(a)).all()\n assert (a == b).all()\n assert (b == a).all()\n assert ((~(a == b)) == (a != b)).all()\n assert ((~(b == a)) == (b != a)).all()\n\n assert not (a == c).all()\n assert not (c == a).all()\n assert not (a == d).all()\n assert not (d == a).all()\n\n # vs a cat-like\n assert (a == e).all()\n assert (e == a).all()\n assert not (a == f).all()\n assert not (f == a).all()\n\n assert (~(a == e) == (a != e)).all()\n assert (~(e == a) == (e != a)).all()\n assert (~(a == f) == (a != f)).all()\n assert (~(f == a) == (f != a)).all()\n\n # non-equality is not comparable\n msg = \"can only compare equality or not\"\n with pytest.raises(TypeError, match=msg):\n a < b\n with pytest.raises(TypeError, match=msg):\n b < a\n with pytest.raises(TypeError, match=msg):\n a > b\n with pytest.raises(TypeError, match=msg):\n b > a\n\n def test_unequal_categorical_comparison_raises_type_error(self):\n # unequal comparison should raise for unordered cats\n cat = Series(Categorical(list(\"abc\")))\n msg = \"can only compare equality or not\"\n with pytest.raises(TypeError, match=msg):\n cat > \"b\"\n\n cat = Series(Categorical(list(\"abc\"), ordered=False))\n with pytest.raises(TypeError, match=msg):\n cat > \"b\"\n\n # https://github.com/pandas-dev/pandas/issues/9836#issuecomment-92123057\n # and following comparisons with scalars not in categories should raise\n # for unequal comps, but not for equal/not equal\n cat = Series(Categorical(list(\"abc\"), ordered=True))\n\n msg = \"Cannot compare a Categorical for op.+with a scalar\"\n with pytest.raises(TypeError, match=msg):\n cat < \"d\"\n with pytest.raises(TypeError, match=msg):\n cat > \"d\"\n with pytest.raises(TypeError, match=msg):\n \"d\" < cat\n with pytest.raises(TypeError, match=msg):\n \"d\" > cat\n\n tm.assert_series_equal(cat == \"d\", Series([False, False, False]))\n tm.assert_series_equal(cat != \"d\", Series([True, True, True]))\n\n # -----------------------------------------------------------------\n\n def test_comparison_tuples(self):\n # GH#11339\n # comparisons vs tuple\n s = Series([(1, 1), (1, 2)])\n\n result = s == (1, 2)\n expected = Series([False, True])\n tm.assert_series_equal(result, expected)\n\n result = s != (1, 2)\n expected = Series([True, False])", "answers": [" tm.assert_series_equal(result, expected)"], "length": 1707, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "f44c17cd-c2ae-41ca-b201-046805e80241", "reasoning": "The test method is checking comparisons against a tuple. After computing `result = s != (1, 2)` and defining the expected Series, the typical pattern in these tests is to assert that the result matches the expectation using `tm.assert_series_equal`. Therefore the next line should be that assertion.", "reasoning_model_answer": "tm.assert_series_equal(result, expected)", "assistant_with_reasoning": "\nThe test method is checking comparisons against a tuple. After computing `result = s != (1, 2)` and defining the expected Series, the typical pattern in these tests is to assert that the result matches the expectation using `tm.assert_series_equal`. Therefore the next line should be that assertion.\n\ntm.assert_series_equal(result, expected)", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.036, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 18635, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "tm.assert_series_equal(result, expected)", "score": 0.91, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "// Copyright (c) Microsoft. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nusing Xunit;\n\nnamespace System.Threading.Tasks.Channels.Tests\n{\n public class CaseBuilderTests : TestBase\n {\n [Fact]\n public void CaseRead_Sync_InvalidArguments_ThrowsArgumentException()\n {\n CaseBuilder cb = Channel.CaseRead(Channel.CreateUnbounded(), i => { });\n Assert.Throws(\"channel\", () => cb.CaseRead(null, (Action)null));\n Assert.Throws(\"channel\", () => cb.CaseRead(null, i => { }));\n Assert.Throws(\"action\", () => cb.CaseRead(Channel.CreateUnbounded(), (Action)null));\n }\n\n [Fact]\n public void CaseRead_Async_InvalidArguments_ThrowsArgumentException()\n {\n CaseBuilder cb = Channel.CaseRead(Channel.CreateUnbounded(), i => { });\n Assert.Throws(\"channel\", () => cb.CaseRead(null, (Func)null));\n Assert.Throws(\"channel\", () => cb.CaseRead(null, i => Task.CompletedTask));\n Assert.Throws(\"func\", () => cb.CaseRead(Channel.CreateUnbounded(), (Func)null));\n }\n\n [Fact]\n public void CaseWrite_Sync_InvalidArguments_ThrowsArgumentException()\n {\n CaseBuilder cb = Channel.CaseRead(Channel.CreateUnbounded(), i => { });\n Assert.Throws(\"channel\", () => cb.CaseWrite(null, 0, (Action)null));\n Assert.Throws(\"channel\", () => cb.CaseWrite(null, 0, (Action)delegate { }));\n Assert.Throws(\"action\", () => cb.CaseWrite(Channel.CreateUnbounded(), 0, (Action)null));\n }\n\n [Fact]\n public void CaseWrite_Async_InvalidArguments_ThrowsArgumentException()\n {\n CaseBuilder cb = Channel.CaseRead(Channel.CreateUnbounded(), i => { });\n Assert.Throws(\"channel\", () => cb.CaseWrite(null, 0, (Func)null));\n Assert.Throws(\"channel\", () => cb.CaseWrite(null, 0, delegate { return Task.CompletedTask; }));\n Assert.Throws(\"func\", () => cb.CaseWrite(Channel.CreateUnbounded(), 0, (Func)null));\n }\n\n [Fact]\n public void CaseDefault_Sync_InvalidAction_ThrowsException()\n {\n CaseBuilder builder1 = Channel.CaseRead(Channel.CreateUnbounded(), i => { });\n Assert.Throws(() => builder1.CaseDefault((Action)null));\n }\n [Fact]\n public void CaseDefault_Async_InvalidAction_ThrowsException()\n {\n CaseBuilder builder1 = Channel.CaseRead(Channel.CreateUnbounded(), i => Task.CompletedTask);\n Assert.Throws(() => builder1.CaseDefault((Func)null));\n }\n\n [Fact]\n public void CaseReadWrite_Sync_CallMultipleTimes_IdempotentResult()\n {\n CaseBuilder builder1 = Channel.CaseRead(Channel.CreateUnbounded(), i => { });\n Assert.Same(builder1, builder1.CaseRead(Channel.CreateUnbounded(), i => { }));\n Assert.Same(builder1, builder1.CaseWrite(Channel.CreateUnbounded(), \"\", () => { }));\n Assert.Same(builder1, builder1.CaseDefault(() => { }));\n\n CaseBuilder builder2 = Channel.CaseWrite(Channel.CreateUnbounded(), 0, () => { });\n Assert.Same(builder2, builder2.CaseRead(Channel.CreateUnbounded(), i => { }));\n Assert.Same(builder2, builder2.CaseWrite(Channel.CreateUnbounded(), \"\", () => { }));\n Assert.Same(builder2, builder2.CaseDefault(() => { }));\n }\n\n [Fact]\n public void CaseReadWrite_Async_CallMultipleTimes_IdempotentResult()\n {\n CaseBuilder builder1 = Channel.CaseRead(Channel.CreateUnbounded(), i => Task.CompletedTask);\n Assert.Same(builder1, builder1.CaseRead(Channel.CreateUnbounded(), i => Task.CompletedTask));\n Assert.Same(builder1, builder1.CaseWrite(Channel.CreateUnbounded(), \"\", () => Task.CompletedTask));\n Assert.Same(builder1, builder1.CaseDefault(() => Task.CompletedTask));\n\n CaseBuilder builder2 = Channel.CaseWrite(Channel.CreateUnbounded(), 0, () => Task.CompletedTask);\n Assert.Same(builder2, builder2.CaseRead(Channel.CreateUnbounded(), i => Task.CompletedTask));\n Assert.Same(builder2, builder2.CaseWrite(Channel.CreateUnbounded(), \"\", () => Task.CompletedTask));\n Assert.Same(builder2, builder2.CaseDefault(() => Task.CompletedTask));\n }\n\n [Fact]\n public void CaseDefault_AlreadyExists_ThrowsException()\n {\n CaseBuilder cb = Channel.CaseRead(Channel.CreateUnbounded(), i => { }).CaseDefault(() => { });\n Assert.Throws(() => cb.CaseDefault(() => { }));\n Assert.Throws(() => cb.CaseDefault(() => Task.CompletedTask));\n }\n\n [Fact]\n public void SelectAsync_Precanceled_ThrowsCancellationException()\n {\n Channel c = Channel.CreateUnbounded();\n Assert.True(c.Out.TryWrite(42));\n\n var cts = new CancellationTokenSource();\n cts.Cancel();\n\n Task select = Channel\n .CaseRead(c, i => { throw new InvalidOperationException(); })\n .SelectAsync(cts.Token);\n AssertSynchronouslyCanceled(select, cts.Token);\n }\n\n [Fact]\n public async Task SelectAsync_CanceledAfterSelectBeforeData_ThrowsCancellationException()\n {\n Channel c = Channel.CreateUnbounded();\n var cts = new CancellationTokenSource();\n\n Task select = Channel\n .CaseRead(c, i => { throw new InvalidOperationException(); })\n .SelectAsync(cts.Token);\n\n cts.Cancel();\n\n await AssertCanceled(select, cts.Token);\n }\n\n [Fact]\n public void SelectAsync_NoChannelsAvailable_SyncDefault_CompletesSynchronously()\n {\n Channel c1 = Channel.CreateUnbounded();\n Channel c2 = Channel.CreateUnbuffered();\n\n var tcs = new TaskCompletionSource();\n Task select = Channel\n .CaseRead(c1, i => { throw new InvalidOperationException(); })\n .CaseWrite(c2, 42, () => { throw new InvalidOperationException(); })\n .CaseDefault(() => tcs.SetResult(84))\n .SelectAsync();\n\n Assert.Equal(TaskStatus.RanToCompletion, select.Status);\n Assert.Equal(TaskStatus.RanToCompletion, tcs.Task.Status);\n Assert.True(select.Result);\n Assert.Equal(84, tcs.Task.Result);\n }\n\n [Fact]\n public void SelectAsync_NoChannelsAvailable_AsyncDefault_CompletesSynchronously()\n {\n Channel c1 = Channel.CreateUnbounded();\n Channel c2 = Channel.CreateUnbuffered();\n\n var tcs = new TaskCompletionSource();\n Task select = Channel\n .CaseRead(c1, i => { throw new InvalidOperationException(); })\n .CaseWrite(c2, 42, () => { throw new InvalidOperationException(); })\n .CaseDefault(() => { tcs.SetResult(84); return Task.CompletedTask; })\n .SelectAsync();\n\n Assert.Equal(TaskStatus.RanToCompletion, select.Status);\n Assert.Equal(TaskStatus.RanToCompletion, tcs.Task.Status);\n Assert.True(select.Result);\n Assert.Equal(84, tcs.Task.Result);\n }\n\n [Fact]\n public async Task SelectAsync_NoChannelsAvailable_AsyncDefault_CompletesAsynchronously()\n {\n Channel c1 = Channel.CreateUnbounded();\n Channel c2 = Channel.CreateUnbuffered();\n\n var tcs = new TaskCompletionSource();\n Task select = Channel\n .CaseRead(c1, i => { throw new InvalidOperationException(); })\n .CaseWrite(c2, 42, () => { throw new InvalidOperationException(); })\n .CaseDefault(async () => { await Task.Yield(); tcs.SetResult(84); })\n .SelectAsync();\n\n Assert.True(await select);\n Assert.Equal(84, tcs.Task.Result);\n }\n\n [Fact]\n public async Task SelectAsync_NoChannelsAvailable_SyncDefault_ThrowsSynchronously()\n {\n Channel c1 = Channel.CreateUnbounded();\n Channel c2 = Channel.CreateUnbuffered();\n\n Task select = Channel\n .CaseRead(c1, i => { throw new InvalidOperationException(); })\n .CaseWrite(c2, 42, () => { throw new InvalidOperationException(); })\n .CaseDefault(new Action(() => { throw new FormatException(); }))\n .SelectAsync();\n\n Assert.True(select.IsCompleted);\n await Assert.ThrowsAsync(() => select);\n }\n\n [Fact]\n public async Task SelectAsync_NoChannelsAvailable_AsyncDefault_ThrowsSynchronously()\n {\n Channel c1 = Channel.CreateUnbounded();\n Channel c2 = Channel.CreateUnbuffered();\n\n Task select = Channel\n .CaseRead(c1, i => { throw new InvalidOperationException(); })\n .CaseWrite(c2, 42, () => { throw new InvalidOperationException(); })\n .CaseDefault(new Func(() => { throw new FormatException(); }))\n .SelectAsync();\n\n Assert.True(select.IsCompleted);\n await Assert.ThrowsAsync(() => select);\n }\n\n [Fact]\n public async Task SelectAsync_NoChannelsAvailable_AsyncDefault_ThrowsAsynchronously()\n {\n Channel c1 = Channel.CreateUnbounded();\n Channel c2 = Channel.CreateUnbuffered();\n\n Task select = Channel\n .CaseRead(c1, i => { throw new InvalidOperationException(); })\n .CaseWrite(c2, 42, () => { throw new InvalidOperationException(); })\n .CaseDefault(async () => { await Task.Yield(); throw new FormatException(); })\n .SelectAsync();\n\n await Assert.ThrowsAsync(() => select);\n }\n\n [Fact]\n public async Task SelectAsync_AllChannelsCompletedBefore_ReturnsFalse()\n {\n Channel c1 = Channel.CreateUnbounded();\n Channel c2 = Channel.CreateUnbuffered();\n c1.Out.Complete();\n c2.Out.Complete();\n\n Task select = Channel\n .CaseRead(c1, i => { throw new InvalidOperationException(); })\n .CaseWrite(c2, 42, () => { throw new InvalidOperationException(); })\n .SelectAsync();\n Assert.False(await select);\n }\n\n [Fact]\n public async Task SelectAsync_AllChannelsCompletedAfter_ReturnsFalse()\n {\n Channel c1 = Channel.CreateUnbounded();\n Channel c2 = Channel.CreateUnbuffered();\n\n Task select = Channel\n .CaseRead(c1, i => { throw new InvalidOperationException(); })\n .CaseWrite(c2, 42, () => { throw new InvalidOperationException(); })\n .SelectAsync();\n\n c1.Out.Complete();\n c2.Out.Complete();\n\n Assert.False(await select);\n }\n\n [Fact]\n public async Task SelectAsync_SingleCaseRead_Sync_DataAlreadyAvailable()\n {\n Channel c = Channel.CreateUnbounded();\n Assert.True(c.Out.TryWrite(42));\n\n var tcs = new TaskCompletionSource();\n Task select = Channel.CaseRead(c, i => tcs.SetResult(i)).SelectAsync();\n\n Assert.True(select.IsCompleted);\n Assert.True(await select);\n\n Assert.Equal(TaskStatus.RanToCompletion, tcs.Task.Status);\n Assert.Equal(42, await tcs.Task);\n }\n\n [Fact]\n public async Task SelectAsync_SingleCaseRead_Async_DataAlreadyAvailable_CompletesSynchronously()\n {\n Channel c = Channel.CreateUnbounded();\n Assert.True(c.Out.TryWrite(42));\n\n var tcs = new TaskCompletionSource();\n Task select = Channel.CaseRead(c, i => { tcs.SetResult(i); return Task.CompletedTask; }).SelectAsync();\n\n Assert.True(select.IsCompleted);\n Assert.True(await select);\n\n Assert.Equal(TaskStatus.RanToCompletion, tcs.Task.Status);\n Assert.Equal(42, await tcs.Task);\n }\n\n [Fact]\n public async Task SelectAsync_SingleCaseRead_Async_DataAlreadyAvailable_CompletesAsynchronously()\n {\n Channel c = Channel.CreateUnbounded();\n Assert.True(c.Out.TryWrite(42));\n\n var tcs = new TaskCompletionSource();\n Task select = Channel.CaseRead(c, async i => { await Task.Yield(); tcs.SetResult(i); }).SelectAsync();\n\n Assert.True(await select);\n\n Assert.Equal(TaskStatus.RanToCompletion, tcs.Task.Status);\n Assert.Equal(42, await tcs.Task);\n }\n\n [Fact]\n public async Task SelectAsync_SingleCaseRead_Sync_DataNotAlreadyAvailable()\n {\n Channel c = Channel.CreateUnbuffered();\n\n var tcs = new TaskCompletionSource();\n Task select = Channel.CaseRead(c, i => tcs.SetResult(i)).SelectAsync();\n Assert.False(select.IsCompleted);\n\n Task write = c.Out.WriteAsync(42);\n\n Assert.True(await select);\n Assert.Equal(42, await tcs.Task);\n }\n\n [Fact]\n public async Task SelectAsync_SingleCaseRead_Async_DataNotAlreadyAvailable_CompletesSynchronously()\n {\n Channel c = Channel.CreateUnbuffered();\n\n var tcs = new TaskCompletionSource();\n Task select = Channel.CaseRead(c, i => { tcs.SetResult(i); return Task.CompletedTask; }).SelectAsync();\n Assert.False(select.IsCompleted);\n\n Task write = c.Out.WriteAsync(42);\n\n Assert.True(await select);\n Assert.Equal(42, await tcs.Task);\n }\n\n [Fact]\n public async Task SelectAsync_SingleCaseRead_Async_DataNotAlreadyAvailable_CompletesAsynchronously()\n {\n Channel c = Channel.CreateUnbuffered();\n\n var tcs = new TaskCompletionSource();\n Task select = Channel.CaseRead(c, async i => { await Task.Yield(); tcs.SetResult(i); }).SelectAsync();\n Assert.False(select.IsCompleted);\n\n Task write = c.Out.WriteAsync(42);\n\n Assert.True(await select);\n Assert.Equal(42, await tcs.Task);\n }\n\n [Fact]\n public async Task SelectAsync_SingleCaseWrite_Sync_SpaceAlreadyAvailable_CompletesSynchronously()\n {\n Channel c = Channel.CreateUnbounded();\n\n var tcs = new TaskCompletionSource();\n Task select = Channel.CaseWrite(c, 42, () => tcs.SetResult(1)).SelectAsync();\n\n Assert.True(select.IsCompleted);\n Assert.True(await select);\n\n Assert.Equal(TaskStatus.RanToCompletion, tcs.Task.Status);\n Assert.Equal(1, await tcs.Task);\n\n int result;\n Assert.True(c.In.TryRead(out result));\n Assert.Equal(42, result);\n }\n\n [Fact]\n public async Task SelectAsync_SingleCaseWrite_Async_SpaceAlreadyAvailable_CompletesSynchronously()\n {\n Channel c = Channel.CreateUnbounded();\n\n var tcs = new TaskCompletionSource();\n Task select = Channel.CaseWrite(c, 42, () => { tcs.SetResult(1); return Task.CompletedTask; }).SelectAsync();\n\n Assert.True(select.IsCompleted);\n Assert.True(await select);\n\n Assert.Equal(TaskStatus.RanToCompletion, tcs.Task.Status);\n Assert.Equal(1, await tcs.Task);\n\n int result;\n Assert.True(c.In.TryRead(out result));\n Assert.Equal(42, result);\n }\n\n [Fact]\n public async Task SelectAsync_SingleCaseWrite_Async_SpaceAlreadyAvailable_CompletesAsynchronously()\n {\n Channel c = Channel.CreateUnbounded();\n\n var tcs = new TaskCompletionSource();\n Task select = Channel.CaseWrite(c, 42, async () => { await Task.Yield(); tcs.SetResult(1); }).SelectAsync();\n\n Assert.True(await select);\n\n Assert.Equal(TaskStatus.RanToCompletion, tcs.Task.Status);\n Assert.Equal(1, await tcs.Task);\n\n int result;\n Assert.True(c.In.TryRead(out result));\n Assert.Equal(42, result);\n }\n\n [Fact]\n public async Task SelectAsync_SingleCaseWrite_Sync_SpaceNotAlreadyAvailable()\n {\n Channel c = Channel.CreateUnbuffered();\n\n var tcs = new TaskCompletionSource();\n Task select = Channel.CaseWrite(c, 42, () => tcs.SetResult(1)).SelectAsync();\n\n Assert.False(select.IsCompleted);\n\n Task read = c.In.ReadAsync().AsTask();\n\n Assert.True(await select);\n Assert.Equal(42, await read);\n Assert.Equal(1, await tcs.Task);\n }\n\n [Fact]\n public async Task SelectAsync_SingleCaseWrite_Async_SpaceNotAlreadyAvailable_CompletesSynchronously()\n {\n Channel c = Channel.CreateUnbuffered();\n\n var tcs = new TaskCompletionSource();\n Task select = Channel.CaseWrite(c, 42, () => { tcs.SetResult(1); return Task.CompletedTask; }).SelectAsync();\n\n Assert.False(select.IsCompleted);\n\n Task read = c.In.ReadAsync().AsTask();\n\n Assert.True(await select);\n Assert.Equal(42, await read);\n Assert.Equal(1, await tcs.Task);\n }\n\n [Fact]\n public async Task SelectAsync_SingleCaseWrite_Async_SpaceNotAlreadyAvailable_CompletesAsynchronously()\n {\n Channel c = Channel.CreateUnbuffered();\n\n var tcs = new TaskCompletionSource();\n Task select = Channel.CaseWrite(c, 42, async () => { await Task.Yield(); tcs.SetResult(1); }).SelectAsync();\n\n Assert.False(select.IsCompleted);\n\n Task read = c.In.ReadAsync().AsTask();\n\n Assert.True(await select);\n Assert.Equal(42, await read);\n Assert.Equal(1, await tcs.Task);\n }\n\n [Theory]\n [InlineData(false)]\n [InlineData(true)]\n public async Task SelectAsync_CaseRead_Sync_ThrowsSynchronously(bool before)\n {\n Channel c = Channel.CreateUnbuffered();\n Task write;\n if (before)\n write = c.Out.WriteAsync(42);\n Task t = Channel.CaseRead(c, new Action(i => { throw new FormatException(); })).SelectAsync();\n if (!before)\n write = c.Out.WriteAsync(42);\n await Assert.ThrowsAsync(() => t);\n }\n\n [Theory]\n [InlineData(false)]\n [InlineData(true)]\n public async Task SelectAsync_CaseRead_Async_DataAlreadyAvailable_ThrowsSynchronously(bool before)\n {\n Channel c = Channel.CreateUnbuffered();\n Task write;\n if (before)\n write = c.Out.WriteAsync(42);\n Task t = Channel.CaseRead(c, new Func(i => { throw new FormatException(); })).SelectAsync();\n if (!before)\n write = c.Out.WriteAsync(42);\n await Assert.ThrowsAsync(() => t);\n }\n\n [Theory]\n [InlineData(false)]\n [InlineData(true)]\n public async Task SelectAsync_CaseRead_Async_DataAlreadyAvailable_ThrowsAsynchronously(bool before)\n {\n Channel c = Channel.CreateUnbuffered();\n Task write;\n if (before)\n write = c.Out.WriteAsync(42);\n Task t = Channel.CaseRead(c, async i => { await Task.Yield(); throw new FormatException(); }).SelectAsync();\n if (!before)", "answers": [" write = c.Out.WriteAsync(42);"], "length": 1379, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "7b855963-e792-4e1a-80e2-eaa0a3e891dd", "reasoning": "The test method follows the same structure as the previous two similar tests. After the conditional 'if (!before)' it should start the write operation on the channel, assigning the task to the variable 'write'. The line is therefore 'write = c.Out.WriteAsync(42);'.", "reasoning_model_answer": "write = c.Out.WriteAsync(42);", "assistant_with_reasoning": "\nThe test method follows the same structure as the previous two similar tests. After the conditional 'if (!before)' it should start the write operation on the channel, assigning the task to the variable 'write'. The line is therefore 'write = c.Out.WriteAsync(42);'.\n\nwrite = c.Out.WriteAsync(42);", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 5.314, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 21155, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "write = c.Out.WriteAsync(42);", "score": 0.78, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "//-----------------------------------------------------------------------------\n// Copyright (c) Microsoft Corporation. All rights reserved.\n//-----------------------------------------------------------------------------\n\nnamespace System.Activities.Statements\n{\n using System;\n using System.Activities.DynamicUpdate;\n using System.Activities.Validation;\n using System.Collections.Generic;\n using System.ComponentModel;\n using System.Runtime.Collections;\n using System.Windows.Markup;\n using System.Collections.ObjectModel;\n\n [ContentProperty(\"Action\")]\n public sealed class InvokeAction : NativeActivity\n {\n IList actionArguments;\n\n public InvokeAction()\n {\n this.actionArguments = new ValidatingCollection\n {\n // disallow null values\n OnAddValidationCallback = item =>\n {\n if (item == null)\n {\n throw FxTrace.Exception.ArgumentNull(\"item\");\n }\n }\n };\n }\n\n [DefaultValue(null)]\n public ActivityAction Action\n {\n get;\n set;\n }\n\n protected override void CacheMetadata(NativeActivityMetadata metadata)\n {\n metadata.AddDelegate(this.Action);\n }\n protected override void Execute(NativeActivityContext context)\n {\n if (Action == null || Action.Handler == null)\n {\n return;\n }\n\n context.ScheduleAction(Action);\n }\n\n }\n\n [ContentProperty(\"Action\")]\n public sealed class InvokeAction : NativeActivity\n {\n public InvokeAction()\n {\n }\n\n [RequiredArgument]\n public InArgument Argument\n {\n get;\n set;\n }\n\n [DefaultValue(null)]\n public ActivityAction Action\n {\n get;\n set;\n }\n\n protected override void OnCreateDynamicUpdateMap(NativeActivityUpdateMapMetadata metadata, Activity originalActivity)\n {\n metadata.AllowUpdateInsideThisActivity();\n }\n\n protected override void CacheMetadata(NativeActivityMetadata metadata)\n {\n metadata.AddDelegate(this.Action);\n\n RuntimeArgument runtimeArgument = new RuntimeArgument(\"Argument\", typeof(T), ArgumentDirection.In, true);\n metadata.Bind(this.Argument, runtimeArgument);\n\n metadata.SetArgumentsCollection(new Collection { runtimeArgument });\n }\n protected override void Execute(NativeActivityContext context)\n {\n if (Action == null || Action.Handler == null) // no-op\n {\n return;\n }\n\n context.ScheduleAction(Action, Argument.Get(context));\n }\n }\n\n [ContentProperty(\"Action\")]\n public sealed class InvokeAction : NativeActivity\n {\n public InvokeAction()\n {\n }\n\n [RequiredArgument]\n public InArgument Argument1\n {\n get;\n set;\n }\n\n [RequiredArgument]\n public InArgument Argument2\n {\n get;\n set;\n }\n\n [DefaultValue(null)]\n public ActivityAction Action\n {\n get;\n set;\n }\n\n protected override void OnCreateDynamicUpdateMap(NativeActivityUpdateMapMetadata metadata, Activity originalActivity)\n {\n metadata.AllowUpdateInsideThisActivity();\n }\n\n protected override void Execute(NativeActivityContext context)\n {\n if (Action == null || Action.Handler == null) // no-op\n {\n return;\n }\n\n context.ScheduleAction(Action, Argument1.Get(context), Argument2.Get(context));\n }\n }\n\n [ContentProperty(\"Action\")]\n public sealed class InvokeAction : NativeActivity\n {\n public InvokeAction()\n {\n }\n\n [RequiredArgument]\n public InArgument Argument1\n {\n get;\n set;\n }\n\n [RequiredArgument]\n public InArgument Argument2\n {\n get;\n set;\n }\n\n [RequiredArgument]\n public InArgument Argument3\n {\n get;\n set;\n }\n\n [DefaultValue(null)]\n public ActivityAction Action\n {\n get;\n set;\n }\n\n protected override void OnCreateDynamicUpdateMap(NativeActivityUpdateMapMetadata metadata, Activity originalActivity)\n {\n metadata.AllowUpdateInsideThisActivity();\n }\n\n protected override void Execute(NativeActivityContext context)\n {\n if (Action == null || Action.Handler == null)\n {\n return;\n }\n\n context.ScheduleAction(Action, Argument1.Get(context), Argument2.Get(context), Argument3.Get(context));\n }\n }\n\n [ContentProperty(\"Action\")]\n public sealed class InvokeAction : NativeActivity\n {\n public InvokeAction()\n {\n }\n\n [RequiredArgument]\n public InArgument Argument1\n {\n get;\n set;\n }\n\n [RequiredArgument]\n public InArgument Argument2\n {\n get;\n set;\n }\n\n [RequiredArgument]\n public InArgument Argument3\n {\n get;\n set;\n }\n\n [RequiredArgument]\n public InArgument Argument4\n {\n get;\n set;\n }\n\n [DefaultValue(null)]\n public ActivityAction Action\n {\n get;\n set;\n }\n\n protected override void OnCreateDynamicUpdateMap(NativeActivityUpdateMapMetadata metadata, Activity originalActivity)\n {\n metadata.AllowUpdateInsideThisActivity();\n }\n\n protected override void Execute(NativeActivityContext context)\n {\n if (Action == null || Action.Handler == null)\n {\n return;\n }\n\n context.ScheduleAction(Action, Argument1.Get(context), Argument2.Get(context), Argument3.Get(context), \n Argument4.Get(context));\n }\n }\n\n [ContentProperty(\"Action\")]\n public sealed class InvokeAction : NativeActivity\n {\n public InvokeAction()\n {\n }\n\n [RequiredArgument]\n public InArgument Argument1\n {\n get;\n set;\n }\n\n [RequiredArgument]\n public InArgument Argument2\n {\n get;\n set;\n }\n\n [RequiredArgument]\n public InArgument Argument3\n {\n get;\n set;\n }\n\n [RequiredArgument]\n public InArgument Argument4\n {\n get;\n set;\n }\n\n [RequiredArgument]\n public InArgument Argument5\n {\n get;\n set;\n }\n\n [DefaultValue(null)]\n public ActivityAction Action\n {\n get;\n set;\n }\n\n protected override void OnCreateDynamicUpdateMap(NativeActivityUpdateMapMetadata metadata, Activity originalActivity)\n {\n metadata.AllowUpdateInsideThisActivity();\n }\n\n protected override void Execute(NativeActivityContext context)\n {\n if (Action == null || Action.Handler == null)\n {\n return;\n }\n\n context.ScheduleAction(Action, Argument1.Get(context), Argument2.Get(context), Argument3.Get(context),\n Argument4.Get(context), Argument5.Get(context));\n }\n }\n\n [ContentProperty(\"Action\")]\n public sealed class InvokeAction : NativeActivity\n {\n public InvokeAction()\n {\n }\n\n [RequiredArgument]\n public InArgument Argument1\n {\n get;\n set;\n }\n\n [RequiredArgument]\n public InArgument Argument2\n {\n get;\n set;\n }\n\n [RequiredArgument]\n public InArgument Argument3\n {\n get;\n set;\n }\n\n [RequiredArgument]\n public InArgument Argument4\n {\n get;\n set;\n }\n\n [RequiredArgument]\n public InArgument Argument5\n {\n get;\n set;\n }\n\n [RequiredArgument]\n public InArgument Argument6\n {\n get;\n set;\n }\n\n [DefaultValue(null)]\n public ActivityAction Action\n {\n get;\n set;\n }\n\n protected override void OnCreateDynamicUpdateMap(NativeActivityUpdateMapMetadata metadata, Activity originalActivity)\n {\n metadata.AllowUpdateInsideThisActivity();\n }\n\n protected override void Execute(NativeActivityContext context)\n {\n if (Action == null || Action.Handler == null)\n {\n return;\n }\n\n context.ScheduleAction(Action, Argument1.Get(context), Argument2.Get(context), Argument3.Get(context),\n Argument4.Get(context), Argument5.Get(context), Argument6.Get(context));\n }\n }\n\n [ContentProperty(\"Action\")]\n public sealed class InvokeAction : NativeActivity\n {\n public InvokeAction()\n {\n }\n\n [RequiredArgument]\n public InArgument Argument1\n {\n get;\n set;\n }\n\n [RequiredArgument]\n public InArgument Argument2\n {\n get;\n set;\n }\n\n [RequiredArgument]\n public InArgument Argument3\n {\n get;\n set;\n }\n\n [RequiredArgument]\n public InArgument Argument4\n {\n get;\n set;\n }\n\n [RequiredArgument]\n public InArgument Argument5\n {\n get;\n set;\n }\n\n [RequiredArgument]\n public InArgument Argument6\n {\n get;\n set;\n }\n\n [RequiredArgument]\n public InArgument Argument7\n {\n get;\n set;\n }\n\n [DefaultValue(null)]\n public ActivityAction Action\n {\n get;\n set;\n }\n\n protected override void OnCreateDynamicUpdateMap(NativeActivityUpdateMapMetadata metadata, Activity originalActivity)\n {\n metadata.AllowUpdateInsideThisActivity();\n }\n\n protected override void Execute(NativeActivityContext context)\n {\n if (Action == null || Action.Handler == null)\n {\n return;\n }\n\n context.ScheduleAction(Action, Argument1.Get(context), Argument2.Get(context), Argument3.Get(context),\n Argument4.Get(context), Argument5.Get(context), Argument6.Get(context), Argument7.Get(context));\n }\n }\n\n [ContentProperty(\"Action\")]\n public sealed class InvokeAction : NativeActivity\n {\n public InvokeAction()\n {\n }\n\n [RequiredArgument]\n public InArgument Argument1\n {\n get;\n set;\n }\n\n [RequiredArgument]\n public InArgument Argument2\n {\n get;\n set;\n }\n\n [RequiredArgument]\n public InArgument Argument3\n {\n get;\n set;\n }\n\n [RequiredArgument]\n public InArgument Argument4\n {\n get;\n set;\n }\n\n [RequiredArgument]\n public InArgument Argument5\n {\n get;\n set;\n }\n\n [RequiredArgument]\n public InArgument Argument6\n {\n get;\n set;\n }\n\n [RequiredArgument]\n public InArgument Argument7\n {\n get;\n set;\n }\n\n [RequiredArgument]\n public InArgument Argument8\n {\n get;\n set;\n }\n\n [DefaultValue(null)]\n public ActivityAction Action\n {\n get;\n set;\n }\n\n protected override void OnCreateDynamicUpdateMap(NativeActivityUpdateMapMetadata metadata, Activity originalActivity)\n {\n metadata.AllowUpdateInsideThisActivity();\n }\n\n protected override void Execute(NativeActivityContext context)\n {\n if (Action == null || Action.Handler == null)\n {\n return;\n }\n\n context.ScheduleAction(Action, Argument1.Get(context), Argument2.Get(context), Argument3.Get(context),\n Argument4.Get(context), Argument5.Get(context), Argument6.Get(context), Argument7.Get(context),\n Argument8.Get(context));\n }\n }\n\n [ContentProperty(\"Action\")]\n public sealed class InvokeAction : NativeActivity\n {\n public InvokeAction()\n {\n }\n\n [RequiredArgument]\n public InArgument Argument1\n {\n get;\n set;\n }\n\n [RequiredArgument]\n public InArgument Argument2\n {\n get;\n set;\n }\n\n [RequiredArgument]\n public InArgument Argument3\n {\n get;\n set;\n }\n\n [RequiredArgument]\n public InArgument Argument4\n {\n get;\n set;\n }\n\n [RequiredArgument]\n public InArgument Argument5\n {\n get;\n set;\n }\n\n [RequiredArgument]\n public InArgument Argument6\n {\n get;\n set;\n }\n\n [RequiredArgument]\n public InArgument Argument7\n {\n get;\n set;\n }\n\n [RequiredArgument]\n public InArgument Argument8\n {\n get;\n set;\n }\n\n [RequiredArgument]\n public InArgument Argument9\n {\n get;\n set;\n }\n\n [DefaultValue(null)]\n public ActivityAction Action\n {\n get;\n set;\n }\n\n protected override void OnCreateDynamicUpdateMap(NativeActivityUpdateMapMetadata metadata, Activity originalActivity)\n {\n metadata.AllowUpdateInsideThisActivity();\n }\n\n protected override void Execute(NativeActivityContext context)\n {\n if (Action == null || Action.Handler == null)\n {\n return;\n }\n\n context.ScheduleAction(Action, Argument1.Get(context), Argument2.Get(context), Argument3.Get(context),\n Argument4.Get(context), Argument5.Get(context), Argument6.Get(context), Argument7.Get(context),\n Argument8.Get(context), Argument9.Get(context));\n }\n }\n\n [ContentProperty(\"Action\")]\n public sealed class InvokeAction : NativeActivity\n {\n public InvokeAction()\n {\n }\n\n [RequiredArgument]\n public InArgument Argument1\n {\n get;\n set;\n }\n\n [RequiredArgument]\n public InArgument Argument2\n {\n get;\n set;\n }\n\n [RequiredArgument]\n public InArgument Argument3\n {\n get;\n set;\n }\n\n [RequiredArgument]\n public InArgument Argument4\n {\n get;\n set;\n }\n\n [RequiredArgument]\n public InArgument Argument5\n {\n get;\n set;\n }\n\n [RequiredArgument]\n public InArgument Argument6\n {\n get;\n set;\n }\n\n [RequiredArgument]\n public InArgument Argument7\n {\n get;\n set;\n }\n\n [RequiredArgument]\n public InArgument Argument8\n {\n get;\n set;\n }\n\n [RequiredArgument]\n public InArgument Argument9\n {\n get;\n set;\n }\n\n [RequiredArgument]\n public InArgument Argument10\n {\n get;\n set;\n }\n\n [DefaultValue(null)]\n public ActivityAction Action\n {\n get;\n set;\n }\n\n protected override void OnCreateDynamicUpdateMap(NativeActivityUpdateMapMetadata metadata, Activity originalActivity)\n {\n metadata.AllowUpdateInsideThisActivity();\n }\n\n protected override void Execute(NativeActivityContext context)\n {\n if (Action == null || Action.Handler == null)\n {\n return;\n }\n\n context.ScheduleAction(Action, Argument1.Get(context), Argument2.Get(context), Argument3.Get(context),\n Argument4.Get(context), Argument5.Get(context), Argument6.Get(context), Argument7.Get(context),\n Argument8.Get(context), Argument9.Get(context), Argument10.Get(context));\n }\n }\n\n [ContentProperty(\"Action\")]\n public sealed class InvokeAction : NativeActivity\n {\n public InvokeAction()\n {\n }\n\n [RequiredArgument]\n public InArgument Argument1\n {\n get;\n set;\n }\n\n [RequiredArgument]\n public InArgument Argument2\n {\n get;\n set;\n }\n\n [RequiredArgument]\n public InArgument Argument3\n {\n get;\n set;\n }\n\n [RequiredArgument]\n public InArgument Argument4\n {\n get;\n set;\n }\n\n [RequiredArgument]\n public InArgument Argument5\n {\n get;\n set;\n }\n\n [RequiredArgument]\n public InArgument Argument6\n {\n get;\n set;\n }\n\n [RequiredArgument]\n public InArgument Argument7\n {\n get;\n set;\n }\n\n [RequiredArgument]\n public InArgument Argument8\n {\n get;\n set;\n }\n\n [RequiredArgument]\n public InArgument Argument9\n {\n get;\n set;\n }\n\n [RequiredArgument]\n public InArgument Argument10\n {\n get;\n set;\n }\n\n [RequiredArgument]\n public InArgument Argument11\n {\n get;\n set;\n }\n\n [DefaultValue(null)]\n public ActivityAction Action\n {\n get;\n set;\n }\n\n protected override void OnCreateDynamicUpdateMap(NativeActivityUpdateMapMetadata metadata, Activity originalActivity)\n {\n metadata.AllowUpdateInsideThisActivity();\n }\n\n protected override void Execute(NativeActivityContext context)\n {\n if (Action == null || Action.Handler == null)\n {\n return;\n }\n\n context.ScheduleAction(Action, Argument1.Get(context), Argument2.Get(context), Argument3.Get(context),\n Argument4.Get(context), Argument5.Get(context), Argument6.Get(context), Argument7.Get(context),\n Argument8.Get(context), Argument9.Get(context), Argument10.Get(context), Argument11.Get(context));\n }\n }\n\n [ContentProperty(\"Action\")]\n public sealed class InvokeAction : NativeActivity\n {\n public InvokeAction()\n {\n }\n\n [RequiredArgument]\n public InArgument Argument1\n {\n get;\n set;\n }\n\n [RequiredArgument]\n public InArgument Argument2\n {\n get;\n set;\n }\n\n [RequiredArgument]\n public InArgument Argument3\n {\n get;\n set;\n }\n\n [RequiredArgument]\n public InArgument Argument4\n {\n get;\n set;\n }\n\n [RequiredArgument]\n public InArgument Argument5\n {\n get;\n set;\n }\n\n [RequiredArgument]\n public InArgument Argument6\n {\n get;\n set;\n }\n\n [RequiredArgument]\n public InArgument Argument7\n {\n get;\n set;\n }\n\n [RequiredArgument]\n public InArgument Argument8\n {\n get;\n set;\n }\n\n [RequiredArgument]\n public InArgument Argument9\n {\n get;\n set;\n }\n\n [RequiredArgument]\n public InArgument Argument10\n {\n get;\n set;\n }\n\n [RequiredArgument]\n public InArgument Argument11\n {\n get;\n set;\n }\n\n [RequiredArgument]\n public InArgument Argument12\n {\n get;\n set;\n }\n\n [DefaultValue(null)]\n public ActivityAction Action\n {\n get;\n set;\n }\n\n protected override void OnCreateDynamicUpdateMap(NativeActivityUpdateMapMetadata metadata, Activity originalActivity)\n {\n metadata.AllowUpdateInsideThisActivity();\n }\n\n protected override void Execute(NativeActivityContext context)\n {\n if (Action == null || Action.Handler == null)\n {\n return;\n }\n\n context.ScheduleAction(Action, Argument1.Get(context), Argument2.Get(context), Argument3.Get(context),\n Argument4.Get(context), Argument5.Get(context), Argument6.Get(context), Argument7.Get(context),\n Argument8.Get(context), Argument9.Get(context), Argument10.Get(context), Argument11.Get(context),\n Argument12.Get(context));\n }\n }\n\n [ContentProperty(\"Action\")]\n public sealed class InvokeAction : NativeActivity\n {\n public InvokeAction()\n {\n }\n\n [RequiredArgument]\n public InArgument Argument1\n {\n get;\n set;\n }\n\n [RequiredArgument]\n public InArgument Argument2\n {\n get;\n set;\n }\n\n [RequiredArgument]\n public InArgument Argument3\n {\n get;\n set;\n }\n\n [RequiredArgument]\n public InArgument Argument4\n {\n get;\n set;\n }\n\n [RequiredArgument]\n public InArgument Argument5\n {\n get;\n set;\n }\n\n [RequiredArgument]\n public InArgument Argument6\n {\n get;\n set;\n }\n\n [RequiredArgument]\n public InArgument Argument7\n {\n get;\n set;\n }\n\n [RequiredArgument]\n public InArgument Argument8\n {\n get;\n set;\n }\n\n [RequiredArgument]\n public InArgument Argument9\n {\n get;\n set;\n }\n\n [RequiredArgument]\n public InArgument Argument10\n {\n get;\n set;\n }\n\n [RequiredArgument]\n public InArgument Argument11\n {\n get;\n set;\n }\n\n [RequiredArgument]\n public InArgument Argument12\n {\n get;\n set;\n }\n\n [RequiredArgument]\n public InArgument Argument13\n {\n get;\n set;\n }\n\n [DefaultValue(null)]\n public ActivityAction Action\n {\n get;\n set;\n }\n\n protected override void OnCreateDynamicUpdateMap(NativeActivityUpdateMapMetadata metadata, Activity originalActivity)\n {\n metadata.AllowUpdateInsideThisActivity();\n }\n\n protected override void Execute(NativeActivityContext context)\n {\n if (Action == null || Action.Handler == null)\n {\n return;\n }\n\n context.ScheduleAction(Action, Argument1.Get(context), Argument2.Get(context), Argument3.Get(context),\n Argument4.Get(context), Argument5.Get(context), Argument6.Get(context), Argument7.Get(context),\n Argument8.Get(context), Argument9.Get(context), Argument10.Get(context), Argument11.Get(context),\n Argument12.Get(context), Argument13.Get(context));\n }\n }\n\n [ContentProperty(\"Action\")]\n public sealed class InvokeAction : NativeActivity\n {\n public InvokeAction()\n {\n }\n\n [RequiredArgument]\n public InArgument Argument1\n {\n get;\n set;\n }\n\n [RequiredArgument]\n public InArgument Argument2\n {\n get;\n set;\n }\n\n [RequiredArgument]\n public InArgument Argument3\n {\n get;\n set;\n }\n\n [RequiredArgument]\n public InArgument Argument4\n {\n get;\n set;\n }\n\n [RequiredArgument]\n public InArgument Argument5\n {\n get;\n set;\n }\n\n [RequiredArgument]\n public InArgument Argument6\n {\n get;\n set;\n }\n\n [RequiredArgument]\n public InArgument Argument7\n {\n get;\n set;\n }\n\n [RequiredArgument]\n public InArgument Argument8\n {\n get;\n set;\n }\n\n [RequiredArgument]\n public InArgument Argument9\n {\n get;\n set;\n }\n\n [RequiredArgument]\n public InArgument Argument10\n {\n get;\n set;\n }\n\n [RequiredArgument]\n public InArgument Argument11\n {\n get;\n set;\n }\n\n [RequiredArgument]\n public InArgument Argument12\n {\n get;\n set;\n }\n\n [RequiredArgument]\n public InArgument Argument13\n {\n get;\n set;\n }\n\n [RequiredArgument]\n public InArgument Argument14\n {\n get;\n set;\n }\n\n [DefaultValue(null)]\n public ActivityAction Action\n {\n get;\n set;\n }\n\n protected override void OnCreateDynamicUpdateMap(NativeActivityUpdateMapMetadata metadata, Activity originalActivity)\n {\n metadata.AllowUpdateInsideThisActivity();\n }\n\n protected override void Execute(NativeActivityContext context)\n {\n if (Action == null || Action.Handler == null)\n {\n return;\n }\n\n context.ScheduleAction(Action, Argument1.Get(context), Argument2.Get(context), Argument3.Get(context),\n Argument4.Get(context), Argument5.Get(context), Argument6.Get(context), Argument7.Get(context),\n Argument8.Get(context), Argument9.Get(context), Argument10.Get(context), Argument11.Get(context),\n Argument12.Get(context), Argument13.Get(context), Argument14.Get(context));\n }\n }\n\n [ContentProperty(\"Action\")]\n public sealed class InvokeAction : NativeActivity\n {\n public InvokeAction()\n {\n }\n\n [RequiredArgument]\n public InArgument Argument1\n {\n get;\n set;\n }\n\n [RequiredArgument]\n public InArgument Argument2\n {\n get;\n set;\n }\n\n [RequiredArgument]\n public InArgument Argument3\n {\n get;\n set;\n }\n\n [RequiredArgument]\n public InArgument Argument4\n {\n get;\n set;\n }\n\n [RequiredArgument]\n public InArgument Argument5\n {\n get;\n set;\n }\n\n [RequiredArgument]\n public InArgument Argument6\n {\n get;\n set;\n }\n\n [RequiredArgument]\n public InArgument Argument7\n {\n get;\n set;\n }\n\n [RequiredArgument]\n public InArgument Argument8\n {\n get;\n set;\n }\n\n [RequiredArgument]\n public InArgument Argument9\n {\n get;\n set;\n }\n\n [RequiredArgument]\n public InArgument Argument10\n {\n get;\n set;\n }\n\n [RequiredArgument]\n public InArgument Argument11\n {\n get;\n set;\n }\n\n [RequiredArgument]\n public InArgument Argument12\n {\n get;\n set;\n }\n\n [RequiredArgument]\n public InArgument Argument13\n {\n get;\n set;\n }\n\n [RequiredArgument]\n public InArgument Argument14\n {\n get;\n set;\n }\n\n [RequiredArgument]\n public InArgument Argument15\n {\n get;\n set;\n }\n\n [DefaultValue(null)]\n public ActivityAction Action\n {\n get;\n set;\n }\n\n protected override void OnCreateDynamicUpdateMap(NativeActivityUpdateMapMetadata metadata, Activity originalActivity)\n {\n metadata.AllowUpdateInsideThisActivity();\n }\n", "answers": [" protected override void Execute(NativeActivityContext context)"], "length": 2140, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "afe8a254-3874-487b-a6af-9b25aedeec2c", "reasoning": "The class InvokeAction follows the same pattern as the previous generic InvokeAction classes. After the OnCreateDynamicUpdateMap method, the next member is the Execute method override. All earlier classes define it with the signature 'protected override void Execute(NativeActivityContext context)'. Therefore the next line of code is that method signature.", "reasoning_model_answer": "protected override void Execute(NativeActivityContext context)", "assistant_with_reasoning": "\nThe class InvokeAction follows the same pattern as the previous generic InvokeAction classes. After the OnCreateDynamicUpdateMap method, the next member is the Execute method override. All earlier classes define it with the signature 'protected override void Execute(NativeActivityContext context)'. Therefore the next line of code is that method signature.\n\nprotected override void Execute(NativeActivityContext context)", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.155, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 31237, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "protected override void Execute(NativeActivityContext context)", "score": 0.94, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "import hashlib\nimport io\nimport mimetypes\nimport os\nimport shutil\nimport socket\nimport sys\nimport tempfile\nfrom cgi import parse_header\nfrom http.client import BadStatusLine\nfrom urllib.parse import unquote\n\nfrom loguru import logger\nfrom requests import RequestException\n\nfrom flexget import options, plugin\nfrom flexget.event import event\nfrom flexget.utils.pathscrub import pathscrub\nfrom flexget.utils.template import RenderError\nfrom flexget.utils.tools import decode_html\n\nlogger = logger.bind(name='download')\n\n\nclass PluginDownload:\n \"\"\"\n Downloads content from entry url and writes it into a file.\n\n Example::\n\n download: ~/torrents/\n\n Allow HTML content:\n\n By default download plugin reports failure if received content\n is a html. Usually this is some sort of custom error page without\n proper http code and thus entry is assumed to be downloaded\n incorrectly.\n\n In the rare case you actually need to retrieve html-pages you must\n disable this feature.\n\n Example::\n\n download:\n path: ~/something/\n fail_html: no\n\n You may use commandline parameter --dl-path to temporarily override\n all paths to another location.\n \"\"\"\n\n schema = {\n 'oneOf': [\n {\n 'title': 'specify options',\n 'type': 'object',\n 'properties': {\n 'path': {'type': 'string', 'format': 'path'},\n 'fail_html': {'type': 'boolean', 'default': True},\n 'overwrite': {'type': 'boolean', 'default': False},\n 'temp': {'type': 'string', 'format': 'path'},\n 'filename': {'type': 'string'},\n },\n 'additionalProperties': False,\n },\n {'title': 'specify path', 'type': 'string', 'format': 'path'},\n {'title': 'no options', 'type': 'boolean', 'enum': [True]},\n ]\n }\n\n def process_config(self, config):\n \"\"\"Return plugin configuration in advanced form\"\"\"\n if isinstance(config, str):\n config = {'path': config}\n if not isinstance(config, dict):\n config = {}\n if not config.get('path'):\n config['require_path'] = True\n config.setdefault('fail_html', True)\n return config\n\n def on_task_download(self, task, config):\n config = self.process_config(config)\n\n # set temporary download path based on user's config setting or use fallback\n tmp = config.get('temp', os.path.join(task.manager.config_base, 'temp'))\n\n self.get_temp_files(\n task,\n require_path=config.get('require_path', False),\n fail_html=config['fail_html'],\n tmp_path=tmp,\n )\n\n def get_temp_file(\n self,\n task,\n entry,\n require_path=False,\n handle_magnets=False,\n fail_html=True,\n tmp_path=tempfile.gettempdir(),\n ):\n \"\"\"\n Download entry content and store in temporary folder.\n Fails entry with a reason if there was problem.\n\n :param bool require_path:\n whether or not entries without 'path' field are ignored\n :param bool handle_magnets:\n when used any of urls containing magnet link will replace url,\n otherwise warning is printed.\n :param fail_html:\n fail entries which url respond with html content\n :param tmp_path:\n path to use for temporary files while downloading\n \"\"\"\n if entry.get('urls'):\n urls = entry.get('urls')\n else:\n urls = [entry['url']]\n errors = []\n for url in urls:\n if url.startswith('magnet:'):\n if handle_magnets:\n # Set magnet link as main url, so a torrent client plugin can grab it\n logger.debug('Accepting magnet url for {}', entry['title'])\n entry['url'] = url\n break\n else:\n logger.warning('Can\\'t download magnet url')\n errors.append('Magnet URL')\n continue\n if require_path and 'path' not in entry:\n # Don't fail here, there might be a magnet later in the list of urls\n logger.debug('Skipping url {} because there is no path for download', url)\n continue\n error = self.process_entry(task, entry, url, tmp_path)\n\n # disallow html content\n html_mimes = ['html', 'text/html']\n if entry.get('mime-type') in html_mimes and fail_html:\n error = (\n 'Unexpected html content received from `%s` - maybe a login page?'\n % entry['url']\n )\n self.cleanup_temp_file(entry)\n\n if not error:\n # Set the main url, so we know where this file actually came from\n logger.debug('Successfully retrieved {} from {}', entry['title'], url)\n entry['url'] = url\n break\n else:\n errors.append(error)\n else:\n # check if entry must have a path (download: yes)\n if require_path and 'path' not in entry:\n logger.error(\"{} can't be downloaded, no path specified for entry\", entry['title'])\n entry.fail('no path specified for entry')\n else:\n entry.fail(', '.join(errors))\n\n def save_error_page(self, entry, task, page):\n received = os.path.join(task.manager.config_base, 'received', task.name)\n if not os.path.isdir(received):\n os.makedirs(received)\n filename = os.path.join(received, pathscrub('%s.error' % entry['title'], filename=True))\n logger.error(\n 'Error retrieving {}, the error page has been saved to {}', entry['title'], filename\n )\n with io.open(filename, 'wb') as outfile:\n outfile.write(page)\n\n def get_temp_files(\n self,\n task,\n require_path=False,\n handle_magnets=False,\n fail_html=True,\n tmp_path=tempfile.gettempdir(),\n ):\n \"\"\"Download all task content and store in temporary folder.\n\n :param bool require_path:\n whether or not entries without 'path' field are ignored\n :param bool handle_magnets:\n when used any of urls containing magnet link will replace url,\n otherwise warning is printed.\n :param fail_html:\n fail entries which url respond with html content\n :param tmp_path:\n path to use for temporary files while downloading\n \"\"\"\n for entry in task.accepted:\n self.get_temp_file(task, entry, require_path, handle_magnets, fail_html, tmp_path)\n\n # TODO: a bit silly method, should be get rid of now with simplier exceptions ?\n def process_entry(self, task, entry, url, tmp_path):\n \"\"\"\n Processes `entry` by using `url`. Does not use entry['url'].\n Does not fail the `entry` if there is a network issue, instead just logs and returns a string error.\n\n :param task: Task\n :param entry: Entry\n :param url: Url to try download\n :param tmp_path: Path to store temporary files\n :return: String error, if failed.\n \"\"\"\n try:\n if task.options.test:\n logger.info('Would download: {}', entry['title'])\n else:\n if not task.manager.unit_test:\n logger.info('Downloading: {}', entry['title'])\n self.download_entry(task, entry, url, tmp_path)\n except RequestException as e:\n logger.warning('RequestException {}, while downloading {}', e, url)\n return 'Network error during request: %s' % e\n except BadStatusLine as e:\n logger.warning('Failed to reach server. Reason: {}', getattr(e, 'message', 'N/A'))\n return 'BadStatusLine'\n except IOError as e:\n if hasattr(e, 'reason'):\n logger.warning('Failed to reach server. Reason: {}', e.reason)\n elif hasattr(e, 'code'):\n logger.warning(\"The server couldn't fulfill the request. Error code: {}\", e.code)\n logger.opt(exception=True).debug('IOError')\n return 'IOError'\n except ValueError as e:\n # Probably unknown url type\n msg = 'ValueError %s' % e\n logger.warning(msg)\n logger.opt(exception=True).debug(msg)\n return msg\n\n def download_entry(self, task, entry, url, tmp_path):\n \"\"\"Downloads `entry` by using `url`.\n\n :raises: Several types of exceptions ...\n :raises: PluginWarning\n \"\"\"\n\n logger.debug(\"Downloading url '{}'\", url)\n\n # get content\n auth = None\n if 'download_auth' in entry:\n auth = entry['download_auth']\n logger.debug(\n 'Custom auth enabled for {} download: {}', entry['title'], entry['download_auth']\n )\n\n headers = task.requests.headers\n if 'download_headers' in entry:\n headers.update(entry['download_headers'])\n logger.debug(\n 'Custom headers enabled for {} download: {}',\n entry['title'],\n entry['download_headers'],\n )\n\n try:\n response = task.requests.get(url, auth=auth, raise_status=False, headers=headers)\n except UnicodeError:\n logger.error('Unicode error while encoding url {}', url)\n return\n if response.status_code != 200:\n logger.debug('Got {} response from server. Saving error page.', response.status_code)\n # Save the error page\n if response.content:\n self.save_error_page(entry, task, response.content)\n # Raise the error\n response.raise_for_status()\n return\n\n # expand ~ in temp path\n # TODO jinja?\n try:\n tmp_path = os.path.expanduser(tmp_path)\n except RenderError as e:\n entry.fail('Could not set temp path. Error during string replacement: %s' % e)\n return\n\n # Clean illegal characters from temp path name\n tmp_path = pathscrub(tmp_path)\n\n # create if missing\n if not os.path.isdir(tmp_path):\n logger.debug('creating tmp_path {}', tmp_path)\n os.mkdir(tmp_path)\n\n # check for write-access\n if not os.access(tmp_path, os.W_OK):\n raise plugin.PluginError('Not allowed to write to temp directory `%s`' % tmp_path)\n\n # download and write data into a temp file\n tmp_dir = tempfile.mkdtemp(dir=tmp_path)\n fname = hashlib.md5(url.encode('utf-8', 'replace')).hexdigest()\n datafile = os.path.join(tmp_dir, fname)\n outfile = io.open(datafile, 'wb')\n try:\n for chunk in response.iter_content(chunk_size=150 * 1024, decode_unicode=False):\n outfile.write(chunk)\n except Exception as e:\n # don't leave futile files behind\n # outfile has to be closed before we can delete it on Windows\n outfile.close()\n logger.debug('Download interrupted, removing datafile')\n os.remove(datafile)\n if isinstance(e, socket.timeout):\n logger.error('Timeout while downloading file')\n else:\n raise\n else:\n outfile.close()\n # Do a sanity check on downloaded file\n if os.path.getsize(datafile) == 0:\n entry.fail('File %s is 0 bytes in size' % datafile)\n os.remove(datafile)\n return\n # store temp filename into entry so other plugins may read and modify content\n # temp file is moved into final destination at self.output\n entry['file'] = datafile\n logger.debug('{} field file set to: {}', entry['title'], entry['file'])\n\n if 'content-type' in response.headers:\n entry['mime-type'] = str(parse_header(response.headers['content-type'])[0])\n else:\n entry['mime-type'] = \"unknown/unknown\"\n\n content_encoding = response.headers.get('content-encoding', '')\n decompress = 'gzip' in content_encoding or 'deflate' in content_encoding\n if 'content-length' in response.headers and not decompress:\n entry['content-length'] = int(response.headers['content-length'])\n\n # prefer content-disposition naming, note: content-disposition can be disabled completely\n # by setting entry field `content-disposition` to False\n if entry.get('content-disposition', True):\n self.filename_from_headers(entry, response)\n else:\n logger.info('Content-disposition disabled for {}', entry['title'])\n self.filename_ext_from_mime(entry)\n\n if not entry.get('filename'):\n filename = unquote(url.rsplit('/', 1)[1])\n logger.debug('No filename - setting from url: {}', filename)\n entry['filename'] = filename\n logger.debug('Finishing download_entry() with filename {}', entry.get('filename'))\n\n def filename_from_headers(self, entry, response):\n \"\"\"Checks entry filename if it's found from content-disposition\"\"\"\n if not response.headers.get('content-disposition'):\n # No content disposition header, nothing we can do\n return\n filename = parse_header(response.headers['content-disposition'])[1].get('filename')\n\n if filename:\n filename = decode_html(filename)\n logger.debug('Found filename from headers: {}', filename)\n if 'filename' in entry:\n logger.debug(\n 'Overriding filename {} with {} from content-disposition',\n entry['filename'],\n filename,\n )\n entry['filename'] = filename\n\n def filename_ext_from_mime(self, entry):\n \"\"\"Tries to set filename extension from mime-type\"\"\"\n extensions = mimetypes.guess_all_extensions(entry['mime-type'], strict=False)\n if extensions:\n logger.debug('Mimetype guess for {} is {} ', entry['mime-type'], extensions)\n if entry.get('filename'):\n if any(entry['filename'].endswith(extension) for extension in extensions):\n logger.debug('Filename {} extension matches to mime-type', entry['filename'])\n else:\n # mimetypes library has no concept of a 'prefered' extension when there are multiple possibilites\n # this causes the first to be used which is not always desirable, e.g. 'ksh' for 'text/plain'\n extension = mimetypes.guess_extension(entry['mime-type'], strict=False)\n logger.debug(\n 'Adding mime-type extension {} to {}', extension, entry['filename']\n )\n entry['filename'] = entry['filename'] + extension\n else:\n logger.debug(\"Python doesn't know extension for mime-type: {}\", entry['mime-type'])\n\n def on_task_output(self, task, config):\n \"\"\"Move downloaded content from temp folder to final destination\"\"\"\n config = self.process_config(config)\n for entry in task.accepted:\n try:\n self.output(task, entry, config)\n except plugin.PluginWarning as e:\n entry.fail()\n logger.error('Plugin error while writing: {}', e)\n except Exception as e:\n entry.fail()\n logger.exception('Exception while writing: {}', e)\n\n def output(self, task, entry, config):\n \"\"\"Moves temp-file into final destination\n\n Raises:\n PluginError if operation fails\n \"\"\"\n\n if 'file' not in entry and not task.options.test:\n logger.debug('file missing, entry: {}', entry)\n raise plugin.PluginError(\n 'Entry `%s` has no temp file associated with' % entry['title'], logger\n )\n\n try:\n # use path from entry if has one, otherwise use from download definition parameter", "answers": [" path = entry.get('path', config.get('path'))"], "length": 1509, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "f3c49b15-f2eb-406f-8da8-5e7b9aa9f7a7", "reasoning": "In the output method, after checking that a temporary file exists, the plugin needs to determine where to move the file. It should use a path specified directly on the entry if present, otherwise fall back to the path defined in the plugin configuration. The next line therefore assigns a variable (e.g., `path`) to `entry.get('path', config.get('path'))` to select the appropriate destination directory.", "reasoning_model_answer": "path = entry.get('path', config.get('path'))", "assistant_with_reasoning": "\nIn the output method, after checking that a temporary file exists, the plugin needs to determine where to move the file. It should use a path specified directly on the entry if present, otherwise fall back to the path defined in the plugin configuration. The next line therefore assigns a variable (e.g., `path`) to `entry.get('path', config.get('path'))` to select the appropriate destination directory.\n\npath = entry.get('path', config.get('path'))", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.456, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 16412, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "path = entry.get('path', config.get('path'))", "score": 0.88, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/*\n * This file is part of Sponge, licensed under the MIT License (MIT).\n *\n * Copyright (c) SpongePowered \n * Copyright (c) contributors\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\npackage org.spongepowered.common.mixin.core.world.storage;\n\nimport net.minecraft.entity.player.EntityPlayer;\nimport net.minecraft.nbt.CompressedStreamTools;\nimport net.minecraft.nbt.NBTTagCompound;\nimport net.minecraft.util.datafix.FixTypes;\nimport net.minecraft.world.storage.SaveHandler;\nimport net.minecraft.world.storage.WorldInfo;\nimport org.apache.logging.log4j.Logger;\nimport org.spongepowered.api.Sponge;\nimport org.spongepowered.api.util.annotation.NonnullByDefault;\nimport org.spongepowered.api.world.SerializationBehaviors;\nimport org.spongepowered.api.world.storage.WorldProperties;\nimport org.spongepowered.asm.mixin.Final;\nimport org.spongepowered.asm.mixin.Mixin;\nimport org.spongepowered.asm.mixin.Shadow;\nimport org.spongepowered.asm.mixin.injection.At;\nimport org.spongepowered.asm.mixin.injection.Inject;\nimport org.spongepowered.asm.mixin.injection.ModifyArg;\nimport org.spongepowered.asm.mixin.injection.Redirect;\nimport org.spongepowered.asm.mixin.injection.callback.CallbackInfo;\nimport org.spongepowered.asm.mixin.injection.callback.LocalCapture;\nimport org.spongepowered.asm.util.PrettyPrinter;\nimport org.spongepowered.common.SpongeImpl;\nimport org.spongepowered.common.bridge.world.WorldInfoBridge;\nimport org.spongepowered.common.bridge.world.storage.SaveHandlerBridge;\nimport org.spongepowered.common.data.util.DataUtil;\nimport org.spongepowered.common.event.tracking.IPhaseState;\nimport org.spongepowered.common.event.tracking.PhaseTracker;\nimport org.spongepowered.common.util.Constants;\nimport org.spongepowered.common.world.WorldManager;\nimport org.spongepowered.common.world.storage.SpongePlayerDataHandler;\n\nimport java.io.File;\nimport java.io.FileInputStream;\nimport java.io.FileNotFoundException;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.nio.file.Files;\nimport java.nio.file.Path;\nimport java.nio.file.attribute.BasicFileAttributes;\nimport java.time.Instant;\nimport java.time.format.DateTimeFormatter;\nimport java.util.HashSet;\nimport java.util.Optional;\nimport java.util.Set;\nimport java.util.UUID;\n\nimport javax.annotation.Nullable;\n\n@NonnullByDefault\n@Mixin(SaveHandler.class)\npublic abstract class SaveHandlerMixin implements SaveHandlerBridge {\n\n @Shadow @Final private File worldDirectory;\n @Shadow @Final private File playersDirectory;\n\n @Shadow protected abstract void shadow$setSessionLock();\n\n @Nullable private Exception impl$capturedException;\n // player join stuff\n @Nullable private Path impl$file;\n private Set impl$directoriesToCreate = new HashSet<>();\n\n @Redirect(method = \"\", at = @At(value = \"INVOKE\", target = \"Ljava/io/File;mkdirs()Z\", remap = false))\n @SuppressWarnings({\"rawtypes\", \"unchecked\"})\n private boolean impl$createDirectoryIfSavingFiles(final File dir) {\n final IPhaseState state = PhaseTracker.getInstance().getCurrentState();\n if (!state.shouldCreateWorldDirectories(PhaseTracker.getInstance().getCurrentContext())) {\n this.impl$directoriesToCreate.add(dir);\n return false;\n }\n return dir.mkdirs();\n }\n\n @Redirect(method = \"\",\n at = @At(value = \"INVOKE\",\n target = \"Lnet/minecraft/world/storage/SaveHandler;setSessionLock()V\"\n )\n )\n @SuppressWarnings({\"rawtypes\", \"unchecked\"})\n private void impl$setSessionLockIfCreatingFiles(final SaveHandler self) {\n final IPhaseState state = PhaseTracker.getInstance().getCurrentState();\n if (state.shouldCreateWorldDirectories(PhaseTracker.getInstance().getCurrentContext())) {\n this.shadow$setSessionLock();\n }\n }\n\n @Redirect(method = \"checkSessionLock\",\n at = @At(value = \"NEW\", target = \"java/io/FileInputStream\", remap = false))\n private FileInputStream impl$createSessionLockAndCreateDirectories(final File file) throws FileNotFoundException {\n if (!file.exists()) {\n final WorldProperties props = Sponge.getServer().getWorldProperties(this.worldDirectory.getName()).get();\n if (props.getSerializationBehavior() == SerializationBehaviors.NONE) {\n throw new IllegalStateException(\"Should not be saving with SerializationBehaviors.NONE\");\n }\n for (File dir : this.impl$directoriesToCreate) {\n dir.mkdirs();\n }\n this.impl$directoriesToCreate.clear();\n this.shadow$setSessionLock();\n }\n return new FileInputStream(file);\n }\n\n @ModifyArg(method = \"checkSessionLock\",\n at = @At(value = \"INVOKE\", target = \"Lnet/minecraft/world/MinecraftException;(Ljava/lang/String;)V\", ordinal = 0, remap = false))\n private String modifyMinecraftExceptionOutputIfNotInitializationTime(final String message) {\n return \"The save folder for world \" + this.worldDirectory + \" is being accessed from another location, aborting\";\n }\n\n @ModifyArg(method = \"checkSessionLock\",\n at = @At(value = \"INVOKE\", target = \"Lnet/minecraft/world/MinecraftException;(Ljava/lang/String;)V\", ordinal = 1, remap = false))\n private String modifyMinecraftExceptionOutputIfIOException(final String message) {\n return \"Failed to check session lock for world \" + this.worldDirectory + \", aborting\";\n }\n\n @Inject(method = \"saveWorldInfoWithPlayer\", at = @At(\"RETURN\"))\n private void impl$saveLevelSpongeDataFile(final WorldInfo worldInformation, final NBTTagCompound tagCompound, final CallbackInfo ci) {\n boolean performChecks = SpongeImpl.getGlobalConfigAdapter().getConfig().getGeneral().isCheckFileWhenSavingSpongeDataFile();\n try {\n // If the returned NBT is empty, then we should warn the user.\n NBTTagCompound spongeRootLevelNBT = ((WorldInfoBridge) worldInformation).bridge$getSpongeRootLevelNbt();\n if (spongeRootLevelNBT.isEmpty()) {\n Integer dimensionId = ((WorldInfoBridge) worldInformation).bridge$getDimensionId();\n String dimensionIdString = dimensionId == null ? \"unknown\" : String.valueOf(dimensionId);\n\n // We should warn the user about the NBT being empty, but not saving it.\n new PrettyPrinter().add(\"Sponge Root Level NBT for world %s is empty!\", worldInformation.getWorldName()).centre().hr()\n .add(\"When trying to save Sponge data for the world %s, an empty NBT compound was provided. The old Sponge data file was \"\n + \"left intact.\",\n worldInformation.getWorldName())\n .add()\n .add(\"The following information may be useful in debugging:\")\n .add()\n .add(\"UUID: \", ((WorldInfoBridge) worldInformation).bridge$getAssignedId())\n .add(\"Dimension ID: \", dimensionIdString)\n .add(\"Is Modded: \", ((WorldInfoBridge) worldInformation).bridge$getIsMod())\n .add(\"Valid flag: \", ((WorldInfoBridge) worldInformation).bridge$isValid())\n .add()\n .add(\"Stack trace:\")\n .add(new Exception())\n .print(System.err);\n return;\n }\n\n final File newDataFile = new File(this.worldDirectory, Constants.Sponge.World.LEVEL_SPONGE_DAT_NEW);\n final File oldDataFile = new File(this.worldDirectory, Constants.Sponge.World.LEVEL_SPONGE_DAT_OLD);\n final File dataFile = new File(this.worldDirectory, Constants.Sponge.World.LEVEL_SPONGE_DAT);\n try (final FileOutputStream stream = new FileOutputStream(newDataFile)) {\n CompressedStreamTools.writeCompressed(spongeRootLevelNBT, stream);\n }\n\n if (performChecks) {\n // Before we continue, is the file zero length?\n if (newDataFile.length() == 0) {\n Integer dimensionId = ((WorldInfoBridge) worldInformation).bridge$getDimensionId();\n String dimensionIdString = dimensionId == null ? \"unknown\" : String.valueOf(dimensionId);\n // Then we just delete the file and tell the user that we didn't save properly.\n new PrettyPrinter().add(\"Zero length level_sponge.dat file was created for %s!\", worldInformation.getWorldName()).centre().hr()\n .add(\"When saving the data file for the world %s, a zero length file was written. Sponge has discarded this file.\",\n worldInformation.getWorldName())\n .add()\n .add(\"The following information may be useful in debugging:\")\n .add()\n .add(\"UUID: \", ((WorldInfoBridge) worldInformation).bridge$getAssignedId())\n .add(\"Dimension ID: \", dimensionIdString)\n .add(\"Is Modded: \", ((WorldInfoBridge) worldInformation).bridge$getIsMod())\n .add(\"Valid flag: \", ((WorldInfoBridge) worldInformation).bridge$isValid())\n .add()\n .add(\"Stack trace:\")\n .add(new Exception())\n .print(System.err);\n newDataFile.delete();\n return;\n }\n\n // Check the file starts with 0x1F 0x8B - it must be gzipped\n boolean shouldDelete = false;\n try (final InputStream reader = Files.newInputStream(newDataFile.toPath())) {\n int byte1 = reader.read();\n int byte2 = reader.read();\n if (byte1 != Constants.GZip.GZIP_BYTE_1 || byte2 != Constants.GZip.GZIP_BYTE_2) {\n // The file is not a gzip file, and is therefore not a valid file.\n shouldDelete = true;\n int next = 1;\n if (byte1 == 0 && byte2 == 0) {\n // We might as well check to see if it's zero filled.\n do {\n next = reader.read();\n } while (next == 0);\n }\n\n // If we get next = -1, the entire file is zeroes. Else, we encountered a non-zero entry. We'll keep that as a corrupted\n // file and if someone reports it, we can ask for it.\n //\n // If it's zero filled, we'll just delete it - we have no use for it.\n Integer dimensionId = ((WorldInfoBridge) worldInformation).bridge$getDimensionId();\n String dimensionIdString = dimensionId == null ? \"unknown\" : String.valueOf(dimensionId);\n String copyText = null;\n if (next != -1) {\n try {\n Path dataFilePath = newDataFile.toPath();\n Path corrupted = dataFilePath.resolveSibling(newDataFile.getName() + \".corrupted-\" +\n DateTimeFormatter.ISO_INSTANT.format(Instant.now()).replaceAll(\":\", \"\") + \".dat\");\n Files.copy(dataFilePath, corrupted);\n copyText =\n String.format(\n \"We have backed up the corrupted file to %s. Please keep hold of this, it may be useful to Sponge \"\n + \"developers.\", corrupted.getFileName());\n } catch (IOException e) {\n // could not copy, that's okay\n }\n\n }\n\n // Then we just delete the file and tell the user that we didn't save properly.\n PrettyPrinter prettyPrinter = new PrettyPrinter(100)\n .add(\"Badly formatted level_sponge.dat file was created for %s!\", worldInformation.getWorldName())\n .centre()\n .hr()\n .addWrapped(\n \"When saving the data file for the world %s, the file was not saved with the correct magic header. Sponge \"\n + \"has discarded this file.\", worldInformation.getWorldName())\n .add();\n\n if (copyText != null) {\n prettyPrinter.addWrapped(copyText).add();\n }\n\n prettyPrinter.add(\"The following information may be useful in debugging:\")\n .add()\n .add(\"Magic header: %x %x (expected %x %x)\", byte1, byte2, Constants.GZip.GZIP_BYTE_1, Constants.GZip.GZIP_BYTE_2)\n .add(\"File size: %d bytes\", newDataFile.length())\n .add(\"UUID: \", ((WorldInfoBridge) worldInformation).bridge$getAssignedId())\n .add(\"Dimension ID: \", dimensionIdString)\n .add(\"Is Modded: \", ((WorldInfoBridge) worldInformation).bridge$getIsMod())\n .add(\"Valid flag: \", ((WorldInfoBridge) worldInformation).bridge$isValid())\n .add()\n .add(\"Stack trace:\")\n .add(new Exception())\n .print(System.err);\n }\n }\n\n // The delete call is here because we've closed the file stream\n // for said file by this point.\n if (shouldDelete) {\n newDataFile.delete();\n return;\n }\n }\n\n if (dataFile.exists()) {\n if (oldDataFile.exists()) {\n oldDataFile.delete();\n }\n\n dataFile.renameTo(oldDataFile);\n dataFile.delete();\n }\n\n newDataFile.renameTo(dataFile);\n\n if (newDataFile.exists()) {\n newDataFile.delete();\n }\n } catch (Exception exception) {\n exception.printStackTrace();\n }\n }\n\n @Override\n public void bridge$loadSpongeDatData(final WorldInfo info) {\n final File spongeFile = new File(this.worldDirectory, Constants.Sponge.World.LEVEL_SPONGE_DAT);\n final File spongeOldFile = new File(this.worldDirectory, Constants.Sponge.World.LEVEL_SPONGE_DAT_OLD);\n\n boolean exceptionRaised = false;\n if (spongeFile.exists()) {\n if (impl$loadSpongeDatFile(info, spongeFile, true)) {\n return;\n }\n\n exceptionRaised = true;\n }\n\n if (spongeOldFile.exists()) {\n if (impl$loadSpongeDatFile(info, spongeOldFile, false)) {\n if (exceptionRaised) {\n // Tell the user we successfully loaded a backup\n SpongeImpl.getLogger().warn(\"Successfully loaded backup data file {} for world {}.\", spongeFile.getName(), info.getWorldName());\n\n // Delete the \"current\" file so we don't accidentally make it the backup file.\n spongeFile.delete();\n }\n return;\n }\n\n exceptionRaised = true;\n }\n\n if (exceptionRaised) {\n throw new RuntimeException(\"Unable to load sponge data for world [\" + info.getWorldName() + \"]\");\n }\n }\n\n /**\n * Redirects the {@link File#exists()} checking that if the file exists, grab\n * the file for later usage to read the file attributes for pre-existing data.\n *\n * @param localfile The local file\n * @return True if the file exists\n */\n @Redirect(method = \"readPlayerData(Lnet/minecraft/entity/player/EntityPlayer;)Lnet/minecraft/nbt/NBTTagCompound;\",", "answers": [" at = @At(value = \"INVOKE\", target = \"Ljava/io/File;isFile()Z\", remap = false))"], "length": 1408, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "c7460196-fad5-46e1-bb97-c148fe1969c9", "reasoning": "The code is defining a @Redirect annotation for the readPlayerData method. The annotation needs the 'at' element specifying which method call to redirect. Following the pattern used earlier, the next line should provide the at = @At(...) part, targeting the File.exists() call. So the next line completes the annotation with at = @At(value = \"INVOKE\", target = \"Ljava/io/File;exists()Z\"))", "reasoning_model_answer": "at = @At(value = \"INVOKE\", target = \"Ljava/io/File;exists()Z\"))", "assistant_with_reasoning": "\nThe code is defining a @Redirect annotation for the readPlayerData method. The annotation needs the 'at' element specifying which method call to redirect. Following the pattern used earlier, the next line should provide the at = @At(...) part, targeting the File.exists() call. So the next line completes the annotation with at = @At(value = \"INVOKE\", target = \"Ljava/io/File;exists()Z\"))\n\nat = @At(value = \"INVOKE\", target = \"Ljava/io/File;exists()Z\"))", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 5.345, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 17594, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "at = @At(value = \"INVOKE\", target = \"Ljava/io/File;exists()Z\"))", "score": 0.79, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "#!/usr/bin/python\n#\n# Author: Jashua R. Cloutier (contact via sourceforge username:senexcanis)\n#\n# Copyright (C) 2010, Jashua R. Cloutier\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions\n# are met:\n#\n# * Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n#\n# * Redistributions in binary form must reproduce the above copyright\n# notice, this list of conditions and the following disclaimer in\n# the documentation and/or other materials provided with the\n# distribution.\n#\n# * Neither the name of Jashua R. Cloutier nor the names of its\n# contributors may be used to endorse or promote products derived from\n# this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.\n#\n#\n# The CppHeaderParser.py script is written in Python 2.4 and released to\n# the open source community for continuous improvements under the BSD\n# 2.0 new license, which can be found at:\n#\n# http://www.opensource.org/licenses/bsd-license.php\n#\n\"\"\"Parse C++ header files and generate a data structure\nrepresenting the class\n\"\"\"\n\nimport ply.lex as lex\nimport os\nimport sys\nimport re\n\nimport inspect\n\ndef lineno():\n \"\"\"Returns the current line number in our program.\"\"\"\n return inspect.currentframe().f_back.f_lineno\n\n\n__version__ = \"1.9\"\nversion = \"1.9\"\ntokens = [\n 'NUMBER',\n 'NAME',\n 'OPEN_PAREN',\n 'CLOSE_PAREN',\n 'OPEN_BRACE',\n 'CLOSE_BRACE',\n 'COLON',\n 'SEMI_COLON',\n 'COMMA',\n 'COMMENT_SINGLELINE',\n 'COMMENT_MULTILINE',\n 'PRECOMP_MACRO',\n 'PRECOMP_MACRO_CONT', \n 'ASTERISK',\n 'AMPERSTAND',\n 'EQUALS',\n 'MINUS',\n 'PLUS', \n 'DIVIDE', \n 'CHAR_LITERAL', \n 'STRING_LITERAL',\n 'OPERATOR_DIVIDE_OVERLOAD', \n 'NEW_LINE',\n]\n\nt_ignore = \" \\t\\r[].|!?%@\"\nt_NUMBER = r'[0-9][0-9XxA-Fa-f]*'\nt_NAME = r'[<>A-Za-z_~][A-Za-z0-9_]*'\nt_OPERATOR_DIVIDE_OVERLOAD = r'/='\nt_OPEN_PAREN = r'\\('\nt_CLOSE_PAREN = r'\\)'\nt_OPEN_BRACE = r'{'\nt_CLOSE_BRACE = r'}'\nt_SEMI_COLON = r';'\nt_COLON = r':'\nt_COMMA = r','\nt_PRECOMP_MACRO = r'\\#.*'\nt_PRECOMP_MACRO_CONT = r'.*\\\\\\n'\ndef t_COMMENT_SINGLELINE(t):\n r'\\/\\/.*\\n'\n global doxygenCommentCache\n if t.value.startswith(\"///\") or t.value.startswith(\"//!\"):\n if doxygenCommentCache:\n doxygenCommentCache += \"\\n\"\n if t.value.endswith(\"\\n\"):\n doxygenCommentCache += t.value[:-1]\n else:\n doxygenCommentCache += t.value\nt_ASTERISK = r'\\*'\nt_MINUS = r'\\-'\nt_PLUS = r'\\+'\nt_DIVIDE = r'/[^/]'\nt_AMPERSTAND = r'&'\nt_EQUALS = r'='\nt_CHAR_LITERAL = \"'.'\"\n#found at http://wordaligned.org/articles/string-literals-and-regular-expressions\n#TODO: This does not work with the string \"bla \\\" bla\"\nt_STRING_LITERAL = r'\"([^\"\\\\]|\\\\.)*\"'\n#Found at http://ostermiller.org/findcomment.html\ndef t_COMMENT_MULTILINE(t):\n r'/\\*([^*]|[\\r\\n]|(\\*+([^*/]|[\\r\\n])))*\\*+/'\n global doxygenCommentCache\n if t.value.startswith(\"/**\") or t.value.startswith(\"/*!\"):\n #not sure why, but get double new lines\n v = t.value.replace(\"\\n\\n\", \"\\n\")\n #strip prefixing whitespace\n v = re.sub(\"\\n[\\s]+\\*\", \"\\n*\", v)\n doxygenCommentCache += v\ndef t_NEWLINE(t):\n r'\\n+'\n t.lexer.lineno += len(t.value)\n\ndef t_error(v):\n print \"Lex error: \", v\n\nlex.lex()\ndebug = 0\n\nsupportedAccessSpecifier = [\n 'public',\n 'protected', \n 'private'\n]\n\ndoxygenCommentCache = \"\"\n\ndef is_namespace(nameStack):\n \"\"\"Determines if a namespace is being specified\"\"\"\n if len(nameStack) == 0:\n return False\n if nameStack[0] == \"namespace\":\n return True\n return False\n\ndef is_enum_namestack(nameStack):\n \"\"\"Determines if a namestack is an enum namestack\"\"\"\n if len(nameStack) == 0:\n return False\n if nameStack[0] == \"enum\":\n return True\n if len(nameStack) > 1 and nameStack[0] == \"typedef\" and nameStack[1] == \"enum\":\n return True\n return False\n\nclass CppParseError(Exception): pass\n \nclass CppClass(dict):\n \"\"\"Takes a name stack and turns it into a class\n \n Contains the following Keys:\n self['name'] - Name of the class\n self['doxygen'] - Doxygen comments associated with the class if they exist\n self['inherits'] - List of Classes that this one inherits where the values\n are of the form {\"access\": Anything in supportedAccessSpecifier\n \"class\": Name of the class\n self['methods'] - Dictionary where keys are from supportedAccessSpecifier\n and values are a lists of CppMethod's\n self['properties'] - Dictionary where keys are from supportedAccessSpecifier\n and values are lists of CppVariable's \n self['enums'] - Dictionary where keys are from supportedAccessSpecifier and\n values are lists of CppEnum's\n \n An example of how this could look is as follows:\n #self =\n {\n 'name': \"\"\n 'inherits':[]\n 'methods':\n {\n 'public':[],\n 'protected':[], \n 'private':[]\n }, \n 'properties':\n {\n 'public':[],\n 'protected':[], \n 'private':[]\n },\n 'enums':\n {\n 'public':[],\n 'protected':[], \n 'private':[]\n }\n }\n \"\"\"\n def __init__(self, nameStack):\n if (debug): print \"Class: \", nameStack\n if (len(nameStack) < 2):\n print \"Error detecting class\"\n return\n global doxygenCommentCache\n if len(doxygenCommentCache):\n self[\"doxygen\"] = doxygenCommentCache\n doxygenCommentCache = \"\"\n self[\"name\"] = nameStack[1]\n inheritList = []\n if \":\" in nameStack:\n nameStack = nameStack[nameStack.index(\":\") + 1:]\n while len(nameStack):\n tmpStack = []\n tmpInheritClass = {\"access\":\"private\"}\n if \",\" in nameStack:\n tmpStack = nameStack[:nameStack.index(\",\")]\n nameStack = nameStack[nameStack.index(\",\") + 1:]\n else:\n tmpStack = nameStack\n nameStack = []\n if len(tmpStack) == 0:\n break;\n elif len(tmpStack) == 1:\n tmpInheritClass[\"class\"] = tmpStack[0]\n elif len(tmpStack) == 2:\n tmpInheritClass[\"access\"] = tmpStack[0]\n tmpInheritClass[\"class\"] = tmpStack[1]\n else:\n print \"Warning: Cant figure out class inheriting %s\\n\"%(\" \".join(tmpStack))\n continue\n inheritList.append(tmpInheritClass)\n methodAccessSpecificList = {}\n propertyAccessSpecificList = {}\n enumAccessSpecificList = {}\n \n for accessSpecifier in supportedAccessSpecifier:\n methodAccessSpecificList[accessSpecifier] = []\n propertyAccessSpecificList[accessSpecifier] = []\n enumAccessSpecificList[accessSpecifier] = []\n self['inherits'] = inheritList\n self['methods'] = methodAccessSpecificList\n self['properties'] = propertyAccessSpecificList\n self['enums'] = enumAccessSpecificList\n self['namespace'] = \"\"\n\n def __repr__(self):\n \"\"\"Convert class to a string\"\"\"\n namespace_prefix = \"\"\n if self[\"namespace\"]: namespace_prefix = self[\"namespace\"] + \"::\"\n rtn = \"class %s\\n\"%(namespace_prefix + self[\"name\"])\n try:\n print self[\"doxygen\"], \n except: pass\n if \"inherits\" in self.keys():\n rtn += \"Inherits: \"\n for inheritClass in self[\"inherits\"]:\n rtn += \"%s %s, \"%(inheritClass[\"access\"], inheritClass[\"class\"])\n rtn += \"\\n\"\n rtn += \"{\\n\"\n for accessSpecifier in supportedAccessSpecifier:\n rtn += \"%s\\n\"%(accessSpecifier)\n #Enums\n if (len(self[\"enums\"][accessSpecifier])):\n rtn += \" // Enums\\n\"\n for enum in self[\"enums\"][accessSpecifier]:\n rtn += \" %s\\n\"%(repr(enum))\n #Properties\n if (len(self[\"properties\"][accessSpecifier])):\n rtn += \" // Properties\\n\"\n for property in self[\"properties\"][accessSpecifier]:\n rtn += \" %s\\n\"%(repr(property))\n #Methods\n if (len(self[\"methods\"][accessSpecifier])):\n rtn += \" // Method\\n\"\n for method in self[\"methods\"][accessSpecifier]:\n rtn += \" %s\\n\"%(repr(method))\n rtn += \"}\\n\"\n return rtn\n\nclass CppMethod(dict):\n \"\"\"Takes a name stack and turns it into a method\n \n Contains the following Keys:\n self['rtnType'] - Return type of the method (ex. \"int\")\n self['name'] - Name of the method (ex. \"getSize\")\n self['doxygen'] - Doxygen comments associated with the method if they exist\n self['parameters'] - List of CppVariables\n \"\"\"\n def __init__(self, nameStack, curClass):\n if (debug): print \"Method: \", nameStack\n global doxygenCommentCache\n if len(doxygenCommentCache):\n self[\"doxygen\"] = doxygenCommentCache\n doxygenCommentCache = \"\"\n if \"operator\" in nameStack:\n self[\"rtnType\"] = \" \".join(nameStack[:nameStack.index('operator')])\n self[\"name\"] = \"\".join(nameStack[nameStack.index('operator'):nameStack.index('(')])\n else:\n self[\"rtnType\"] = \" \".join(nameStack[:nameStack.index('(') - 1])\n self[\"name\"] = \" \".join(nameStack[nameStack.index('(') - 1:nameStack.index('(')])\n if len(self[\"rtnType\"]) == 0 or self[\"name\"] == curClass:\n self[\"rtnType\"] = \"void\"\n paramsStack = nameStack[nameStack.index('(') + 1: ]\n #Remove things from the stack till we hit the last paren, this helps handle abstract and normal methods\n while (paramsStack[-1] != \")\"):\n paramsStack.pop()\n paramsStack.pop()\n params = []\n #See if there is a doxygen comment for the variable\n doxyVarDesc = {}\n #TODO: Put this into a class\n if self.has_key(\"doxygen\"):\n doxyLines = self[\"doxygen\"].split(\"\\n\")\n lastParamDesc = \"\"\n for doxyLine in doxyLines:\n if \" @param \" in doxyLine or \" \\param \" in doxyLine:\n try:\n #Strip out the param\n doxyLine = doxyLine[doxyLine.find(\"param \") + 6:]\n (var, desc) = doxyLine.split(\" \", 1)\n doxyVarDesc[var] = desc.strip()\n lastParamDesc = var\n except: pass\n elif \" @return \" in doxyLine or \" \\return \" in doxyLine:\n lastParamDesc = \"\"\n # not handled for now\n elif lastParamDesc:\n try:\n doxyLine = doxyLine.strip()\n if \" \" not in doxyLine:\n lastParamDesc = \"\"\n continue\n doxyLine = doxyLine[doxyLine.find(\" \") + 1:]\n doxyVarDesc[lastParamDesc] += \" \" + doxyLine\n except: pass\n \n #Create the variable now\n while (len(paramsStack)):\n if (',' in paramsStack):\n params.append(CppVariable(paramsStack[0:paramsStack.index(',')], doxyVarDesc=doxyVarDesc))\n paramsStack = paramsStack[paramsStack.index(',') + 1:]\n else:\n param = CppVariable(paramsStack, doxyVarDesc=doxyVarDesc)\n if len(param.keys()):\n params.append(param)\n break\n self[\"parameters\"] = params\n\n\nclass CppVariable(dict):\n \"\"\"Takes a name stack and turns it into a method\n \n Contains the following Keys:\n self['type'] - Type for the variable (ex. \"const string &\")\n self['name'] - Name of the variable (ex. \"numItems\")\n self['namespace'] - Namespace containing the enum\n self['desc'] - Description of the variable if part of a method (optional)\n self['doxygen'] - Doxygen comments associated with the method if they exist\n self['defaltValue'] - Default value of the variable, this key will only\n exist if there is a default value\n \"\"\"\n def __init__(self, nameStack, **kwargs):\n if (debug): print \"Variable: \", nameStack\n if (len(nameStack) < 2):\n return\n global doxygenCommentCache\n if len(doxygenCommentCache):\n self[\"doxygen\"] = doxygenCommentCache\n doxygenCommentCache = \"\"\n if (\"=\" in nameStack):\n self[\"type\"] = \" \".join(nameStack[:nameStack.index(\"=\") - 1])\n self[\"name\"] = nameStack[nameStack.index(\"=\") - 1]\n self[\"defaltValue\"] = \" \".join(nameStack[nameStack.index(\"=\") + 1:])\n else:\n self[\"type\"] = \" \".join(nameStack[:-1])\n self[\"name\"] = nameStack[-1]\n self[\"type\"] = self[\"type\"].replace(\" :\",\":\")\n self[\"type\"] = self[\"type\"].replace(\": \",\":\")\n self[\"type\"] = self[\"type\"].replace(\" <\",\"<\")\n self[\"type\"] = self[\"type\"].replace(\" >\",\">\")\n #Optional doxygen description\n try:\n self[\"desc\"] = kwargs[\"doxyVarDesc\"][self[\"name\"]]\n except: pass\n\nclass CppEnum(dict):\n \"\"\"Takes a name stack and turns it into an Enum\n \n Contains the following Keys:\n self['name'] - Name of the enum (ex. \"ItemState\")\n self['namespace'] - Namespace containing the enum\n self['values'] - List of values where the values are a dictionary of the\n form {\"name\": name of the key (ex. \"PARSING_HEADER\"),\n \"value\": Specified value of the enum, this key will only exist\n if a value for a given enum value was defined\n }\n \"\"\"\n def __init__(self, nameStack):\n if len(nameStack) < 4 or \"{\" not in nameStack or \"}\" not in nameStack:\n #Not enough stuff for an enum\n return\n global doxygenCommentCache\n if len(doxygenCommentCache):\n self[\"doxygen\"] = doxygenCommentCache\n doxygenCommentCache = \"\"\n valueList = []\n #Figure out what values it has\n valueStack = nameStack[nameStack.index('{') + 1: nameStack.index('}')]\n while len(valueStack):\n tmpStack = []\n if \",\" in valueStack:", "answers": [" tmpStack = valueStack[:valueStack.index(\",\")]"], "length": 1576, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "30ff9251-600e-47ce-8859-fc4efd87f3da", "reasoning": "The code is inside the CppEnum __init__ method, processing enum values. After checking if a comma exists in valueStack, the next step is to extract the segment before the comma into tmpStack, mirroring similar parsing logic elsewhere in the file. Hence the appropriate next line is the slice assignment.", "reasoning_model_answer": "tmpStack = valueStack[:valueStack.index(',')]", "assistant_with_reasoning": "\nThe code is inside the CppEnum __init__ method, processing enum values. After checking if a comma exists in valueStack, the next step is to extract the segment before the comma into tmpStack, mirroring similar parsing logic elsewhere in the file. Hence the appropriate next line is the slice assignment.\n\ntmpStack = valueStack[:valueStack.index(',')]", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 7.133, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 15473, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "tmpStack = valueStack[:valueStack.index(',')]", "score": 0.81, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\nusing System.Collections.Generic;\nusing System.Reflection;\nusing Xunit;\n\nnamespace System.Globalization.Tests\n{\n public class TextInfoMiscTests\n {\n public static IEnumerable TextInfo_TestData()\n {\n yield return new object[] { \"\", 0x7f, 0x4e4, 0x25, 0x2710, 0x1b5, false };\n yield return new object[] { \"en-US\", 0x409, 0x4e4, 0x25, 0x2710, 0x1b5, false };\n yield return new object[] { \"ja-JP\", 0x411, 0x3a4, 0x4f42, 0x2711, 0x3a4, false };\n yield return new object[] { \"zh-CN\", 0x804, 0x3a8, 0x1f4, 0x2718, 0x3a8, false };\n yield return new object[] { \"ar-SA\", 0x401, 0x4e8, 0x4fc4, 0x2714, 0x2d0, true };\n yield return new object[] { \"ko-KR\", 0x412, 0x3b5, 0x5161, 0x2713, 0x3b5, false };\n yield return new object[] { \"he-IL\", 0x40d, 0x4e7, 0x1f4, 0x2715, 0x35e, true };\n }\n\n [Theory]\n [MemberData(nameof(TextInfo_TestData))]\n public void MiscTest(string cultureName, int lcid, int ansiCodePage, int ebcdiCCodePage, int macCodePage, int oemCodePage, bool isRightToLeft)\n {\n TextInfo ti = CultureInfo.GetCultureInfo(cultureName).TextInfo;\n Assert.Equal(lcid, ti.LCID);\n Assert.Equal(ansiCodePage, ti.ANSICodePage);\n Assert.Equal(ebcdiCCodePage, ti.EBCDICCodePage);\n Assert.Equal(macCodePage, ti.MacCodePage);\n Assert.Equal(oemCodePage, ti.OEMCodePage);\n Assert.Equal(isRightToLeft, ti.IsRightToLeft);\n }\n\n [Fact]\n public void ReadOnlyTest()\n {\n TextInfo ti = CultureInfo.GetCultureInfo(\"en-US\").TextInfo;\n Assert.True(ti.IsReadOnly, \"IsReadOnly should be true with cached TextInfo object\");\n\n ti = (TextInfo) ti.Clone();\n Assert.False(ti.IsReadOnly, \"IsReadOnly should be false with cloned TextInfo object\");\n \n ti = TextInfo.ReadOnly(ti);\n Assert.True(ti.IsReadOnly, \"IsReadOnly should be true with created read-nly TextInfo object\");\n }\n\n [Fact]\n public void ToTitleCaseTest()\n {\n TextInfo ti = CultureInfo.GetCultureInfo(\"en-US\").TextInfo;\n Assert.Equal(\"A Tale Of Two Cities\", ti.ToTitleCase(\"a tale of two cities\"));\n Assert.Equal(\"Growl To The Rescue\", ti.ToTitleCase(\"gROWL to the rescue\"));\n Assert.Equal(\"Inside The US Government\", ti.ToTitleCase(\"inside the US government\"));\n Assert.Equal(\"Sports And MLB Baseball\", ti.ToTitleCase(\"sports and MLB baseball\"));\n Assert.Equal(\"The Return Of Sherlock Holmes\", ti.ToTitleCase(\"The Return of Sherlock Holmes\"));\n Assert.Equal(\"UNICEF And Children\", ti.ToTitleCase(\"UNICEF and children\"));\n\n AssertExtensions.Throws(\"str\", () => ti.ToTitleCase(null));\n }\n\n public static IEnumerable DutchTitleCaseInfo_TestData()\n {\n yield return new object[] { \"nl-NL\", \"IJ IJ IJ IJ\", \"ij iJ Ij IJ\" };\n yield return new object[] { \"nl-be\", \"IJzeren Eigenschappen\", \"ijzeren eigenschappen\" };\n yield return new object[] { \"NL-NL\", \"Lake IJssel\", \"lake iJssel\" };\n yield return new object[] { \"NL-BE\", \"Boba N' IJango Fett PEW PEW\", \"Boba n' Ijango fett PEW PEW\" };\n yield return new object[] { \"en-us\", \"Ijill And Ijack\", \"ijill and ijack\" };\n yield return new object[] { \"de-DE\", \"Ij Ij IJ Ij\", \"ij ij IJ ij\" };\n yield return new object[] { \"he-il\", \"Ijon't Know What Will Happen.\", \"Ijon't know what Will happen.\" };\n }\n\n [Theory]\n [MemberData(nameof(DutchTitleCaseInfo_TestData))]\n [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, \"Desktop Framework hasn't received the fix for dotnet/corefx#16770 yet.\")]\n public void ToTitleCaseDutchTest(string cultureName, string expected, string actual)\n {\n TextInfo ti = CultureInfo.GetCultureInfo(cultureName).TextInfo;\n Assert.Equal(expected, ti.ToTitleCase(actual));\n }\n\n [Theory]\n public static IEnumerable CultureName_TestData()\n {\n yield return new object[] { CultureInfo.InvariantCulture.TextInfo, \"\" };\n yield return new object[] { new CultureInfo(\"\").TextInfo, \"\" };\n yield return new object[] { new CultureInfo(\"en-US\").TextInfo, \"en-US\" };\n yield return new object[] { new CultureInfo(\"fr-FR\").TextInfo, \"fr-FR\" };\n yield return new object[] { new CultureInfo(\"EN-us\").TextInfo, \"en-US\" };\n yield return new object[] { new CultureInfo(\"FR-fr\").TextInfo, \"fr-FR\" };\n }\n\n [Theory]\n [MemberData(nameof(CultureName_TestData))]\n public void CultureName(TextInfo textInfo, string expected)\n {\n Assert.Equal(expected, textInfo.CultureName);\n }\n\n public static IEnumerable IsReadOnly_TestData()\n {\n yield return new object[] { CultureInfo.ReadOnly(new CultureInfo(\"en-US\")).TextInfo, true };\n yield return new object[] { CultureInfo.InvariantCulture.TextInfo, true };\n yield return new object[] { new CultureInfo(\"\").TextInfo, false };\n yield return new object[] { new CultureInfo(\"en-US\").TextInfo, false };\n yield return new object[] { new CultureInfo(\"fr-FR\").TextInfo, false };\n }\n\n [Theory]\n [MemberData(nameof(IsReadOnly_TestData))]\n public void IsReadOnly(TextInfo textInfo, bool expected)\n {\n Assert.Equal(expected, textInfo.IsReadOnly);\n }\n\n [Theory]\n [InlineData(\"en-US\", false)]\n [InlineData(\"ar\", true)]\n public void IsRightToLeft(string name, bool expected)\n {\n Assert.Equal(expected, new CultureInfo(name).TextInfo.IsRightToLeft);\n }\n\n [Fact]\n public void ListSeparator_EnUS()\n {\n Assert.NotEqual(string.Empty, new CultureInfo(\"en-US\").TextInfo.ListSeparator);\n }\n \n [Theory]\n [InlineData(\"\")]\n [InlineData(\" \")]\n [InlineData(\"abcdef\")]\n public void ListSeparator_Set(string newListSeparator)\n {\n TextInfo textInfo = new CultureInfo(\"en-US\").TextInfo;\n textInfo.ListSeparator = newListSeparator;\n Assert.Equal(newListSeparator, textInfo.ListSeparator);\n }\n\n [Fact]\n public void ListSeparator_Set_Invalid()\n {\n Assert.Throws(() => CultureInfo.InvariantCulture.TextInfo.ListSeparator = \"\");\n AssertExtensions.Throws(\"value\", () => new CultureInfo(\"en-US\").TextInfo.ListSeparator = null);\n }\n\n public static IEnumerable Equals_TestData()\n {\n yield return new object[] { CultureInfo.InvariantCulture.TextInfo, CultureInfo.InvariantCulture.TextInfo, true };\n yield return new object[] { CultureInfo.InvariantCulture.TextInfo, new CultureInfo(\"\").TextInfo, true };\n yield return new object[] { CultureInfo.InvariantCulture.TextInfo, new CultureInfo(\"en-US\"), false };\n\n yield return new object[] { new CultureInfo(\"en-US\").TextInfo, new CultureInfo(\"en-US\").TextInfo, true };\n yield return new object[] { new CultureInfo(\"en-US\").TextInfo, new CultureInfo(\"fr-FR\").TextInfo, false };\n\n yield return new object[] { new CultureInfo(\"en-US\").TextInfo, null, false };\n yield return new object[] { new CultureInfo(\"en-US\").TextInfo, new object(), false };\n yield return new object[] { new CultureInfo(\"en-US\").TextInfo, 123, false };\n yield return new object[] { new CultureInfo(\"en-US\").TextInfo, \"en-US\", false };\n \n }\n\n [Theory]\n [MemberData(nameof(Equals_TestData))]\n public void Equals(TextInfo textInfo, object obj, bool expected)\n {\n Assert.Equal(expected, textInfo.Equals(obj));\n if (obj is TextInfo)\n {\n Assert.Equal(expected, textInfo.GetHashCode().Equals(obj.GetHashCode()));\n }\n }\n\n private static readonly string [] s_cultureNames = new string[] { \"\", \"en-US\", \"fr\", \"fr-FR\" };\n\n // ToLower_TestData_netcore has the data which is specific to netcore framework \n public static IEnumerable ToLower_TestData_netcore()\n {\n foreach (string cultureName in s_cultureNames)\n {\n // DESERT CAPITAL LETTER LONG I has a lower case variant (but not on Windows 7).\n yield return new object[] { cultureName, \"\\U00010400\", PlatformDetection.IsWindows7 ? \"\\U00010400\" : \"\\U00010428\" };\n }\n }\n\n public static IEnumerable ToLower_TestData()\n {\n foreach (string cultureName in s_cultureNames)\n {\n yield return new object[] { cultureName, \"\", \"\" };\n\n yield return new object[] { cultureName, \"A\", \"a\" };\n yield return new object[] { cultureName, \"a\", \"a\" };\n yield return new object[] { cultureName, \"ABC\", \"abc\" };\n yield return new object[] { cultureName, \"abc\", \"abc\" };\n\n yield return new object[] { cultureName, \"1\", \"1\" };\n yield return new object[] { cultureName, \"123\", \"123\" };\n yield return new object[] { cultureName, \"!\", \"!\" };\n\n yield return new object[] { cultureName, \"HELLOWOR!LD123\", \"hellowor!ld123\" };\n yield return new object[] { cultureName, \"HelloWor!ld123\", \"hellowor!ld123\" };\n yield return new object[] { cultureName, \"Hello\\n\\0World\\u0009!\", \"hello\\n\\0world\\t!\" };\n\n yield return new object[] { cultureName, \"THIS IS A LONGER TEST CASE\", \"this is a longer test case\" };\n yield return new object[] { cultureName, \"this Is A LONGER mIXEd casE test case\", \"this is a longer mixed case test case\" };\n\n yield return new object[] { cultureName, \"THIS \\t hAs \\t SOMe \\t tabs\", \"this \\t has \\t some \\t tabs\" };\n yield return new object[] { cultureName, \"EMBEDDED\\0NuLL\\0Byte\\0\", \"embedded\\0null\\0byte\\0\" };\n\n // LATIN CAPITAL LETTER O WITH ACUTE, which has a lower case variant.\n yield return new object[] { cultureName, \"\\u00D3\", \"\\u00F3\" };\n\n // SNOWMAN, which does not have a lower case variant.\n yield return new object[] { cultureName, \"\\u2603\", \"\\u2603\" };\n\n // RAINBOW (outside the BMP and does not case)\n yield return new object[] { cultureName, \"\\U0001F308\", \"\\U0001F308\" };\n\n // Unicode defines some codepoints which expand into multiple codepoints\n // when cased (see SpecialCasing.txt from UNIDATA for some examples). We have never done\n // these sorts of expansions, since it would cause string lengths to change when cased,\n // which is non-intuitive. In addition, there are some context sensitive mappings which\n // we also don't preform.\n // Greek Capital Letter Sigma (does not to case to U+03C2 with \"final sigma\" rule).\n yield return new object[] { cultureName, \"\\u03A3\", \"\\u03C3\" };\n }\n\n foreach (string cultureName in new string[] { \"tr\", \"tr-TR\", \"az\", \"az-Latn-AZ\" })\n {\n yield return new object[] { cultureName, \"\\u0130\", \"i\" };\n yield return new object[] { cultureName, \"i\", \"i\" };\n yield return new object[] { cultureName, \"I\", \"\\u0131\" };\n yield return new object[] { cultureName, \"HI!\", \"h\\u0131!\" };\n yield return new object[] { cultureName, \"HI\\n\\0H\\u0130\\t!\", \"h\\u0131\\n\\0hi\\u0009!\" };\n }\n\n // ICU has special tailoring for the en-US-POSIX locale which treats \"i\" and \"I\" as different letters\n // instead of two letters with a case difference during collation. Make sure this doesn't confuse our\n // casing implementation, which uses collation to understand if we need to do Turkish casing or not.\n if (!PlatformDetection.IsWindows)\n {\n yield return new object[] { \"en-US-POSIX\", \"I\", \"i\" };\n }\n }\n\n public void TestToLower(string name, string str, string expected)\n {\n Assert.Equal(expected, new CultureInfo(name).TextInfo.ToLower(str));\n if (str.Length == 1)\n {\n Assert.Equal(expected[0], new CultureInfo(name).TextInfo.ToLower(str[0]));\n }\n }\n\n [Theory]\n [MemberData(nameof(ToLower_TestData))]\n public void ToLower(string name, string str, string expected)\n {\n TestToLower(name, str, expected);\n }\n\n [Theory]\n [MemberData(nameof(ToLower_TestData_netcore))]\n [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)]\n public void ToLower_Netcore(string name, string str, string expected)\n {\n TestToLower(name, str, expected);\n }\n \n [Fact]\n public void ToLower_InvalidSurrogates()\n {\n // Invalid UTF-16 in a string (mismatched surrogate pairs) should be unchanged.\n foreach (string cultureName in new string[] { \"\", \"en-US\", \"fr\" })\n {\n ToLower(cultureName, \"BE CAREFUL, \\uD83C\\uD83C, THIS ONE IS TRICKY\", \"be careful, \\uD83C\\uD83C, this one is tricky\");\n ToLower(cultureName, \"BE CAREFUL, \\uDF08\\uD83C, THIS ONE IS TRICKY\", \"be careful, \\uDF08\\uD83C, this one is tricky\");\n ToLower(cultureName, \"BE CAREFUL, \\uDF08\\uDF08, THIS ONE IS TRICKY\", \"be careful, \\uDF08\\uDF08, this one is tricky\");\n }\n }\n\n [Theory]\n [InlineData(\"\")]\n [InlineData(\"en-US\")]\n [InlineData(\"fr\")]\n public void ToLower_Null_ThrowsArgumentNullException(string cultureName)\n {\n AssertExtensions.Throws(\"str\", () => new CultureInfo(cultureName).TextInfo.ToLower(null));\n }\n\n // ToUpper_TestData_netcore has the data which is specific to netcore framework \n public static IEnumerable ToUpper_TestData_netcore()\n {\n foreach (string cultureName in s_cultureNames)\n {\n // DESERT SMALL LETTER LONG I has an upper case variant (but not on Windows 7).", "answers": [" yield return new object[] { cultureName, \"\\U00010428\", PlatformDetection.IsWindows7 ? \"\\U00010428\" : \"\\U00010400\" };"], "length": 1446, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "2ab06372-c85d-4d36-aef7-c21fd415ec04", "reasoning": "The method ToUpper_TestData_netcore mirrors ToLower_TestData_netcore, which yields a test case for the Desert Long I characters. After the comment, the next line should provide a yield return with the small letter as input and the expected upper case result, handling the Windows 7 special case just like the lower‑case version.", "reasoning_model_answer": "yield return new object[] { cultureName, \"\\U00010428\", PlatformDetection.IsWindows7 ? \"\\U00010428\" : \"\\U00010400\" };", "assistant_with_reasoning": "\nThe method ToUpper_TestData_netcore mirrors ToLower_TestData_netcore, which yields a test case for the Desert Long I characters. After the comment, the next line should provide a yield return with the small letter as input and the expected upper case result, handling the Windows 7 special case just like the lower‑case version.\n\nyield return new object[] { cultureName, \"\\U00010428\", PlatformDetection.IsWindows7 ? \"\\U00010428\" : \"\\U00010400\" };", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.384, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 14930, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "yield return new object[] { cultureName, \"\\U00010428\", PlatformDetection.IsWindows7 ? \"\\U00010428\" : \"\\U00010400\" };", "score": 0.94, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/*\n Matali Physics Demo\n Copyright (c) 2013 KOMIRES Sp. z o. o.\n */\nusing System;\nusing System.Collections.Generic;\nusing OpenTK;\nusing OpenTK.Graphics.OpenGL;\nusing Komires.MataliPhysics;\n\nnamespace MataliPhysicsDemo\n{\n /// \n /// This is the main type for your game\n /// \n public class Ragdoll1\n {\n Demo demo;\n PhysicsScene scene;\n string instanceIndexName;\n\n public Ragdoll1(Demo demo, int instanceIndex)\n {\n this.demo = demo;\n instanceIndexName = \" \" + instanceIndex.ToString();\n }\n\n public void Initialize(PhysicsScene scene)\n {\n this.scene = scene;\n }\n\n public static void CreateShapes(Demo demo, PhysicsScene scene)\n {\n }\n\n public void Create(Vector3 objectPosition, Vector3 objectScale, Quaternion objectOrientation, bool enableControl, bool enableControlWithDeformation, float minAngleDeformationVelocity)\n {\n Shape box = scene.Factory.ShapeManager.Find(\"Box\");\n\n PhysicsObject objectRoot = null;\n PhysicsObject objectBase = null;\n\n Vector3 position1 = Vector3.Zero;\n Vector3 position2 = Vector3.Zero;\n Quaternion orientation1 = Quaternion.Identity;\n Quaternion orientation2 = Quaternion.Identity;\n\n objectRoot = scene.Factory.PhysicsObjectManager.Create(\"Ragdoll 1\" + instanceIndexName);\n\n objectBase = scene.Factory.PhysicsObjectManager.Create(\"Ragdoll 1 Head\" + instanceIndexName);\n objectRoot.AddChildPhysicsObject(objectBase);\n objectBase.Shape = box;\n objectBase.UserDataStr = \"Box\";\n objectBase.InitLocalTransform.SetPosition(0.0f, 42.7f, 20.0f);\n objectBase.InitLocalTransform.SetScale(0.7f);\n objectBase.Integral.SetDensity(1.64f);\n\n objectBase = scene.Factory.PhysicsObjectManager.Create(\"Ragdoll 1 Upper Torso\" + instanceIndexName);\n objectRoot.AddChildPhysicsObject(objectBase);\n objectBase.Shape = box;\n objectBase.UserDataStr = \"Box\";\n objectBase.CreateSound(true);\n objectBase.Sound.HitVolume = 0.25f;\n objectBase.Sound.RollVolume = 0.25f;\n objectBase.Sound.SlideVolume = 0.25f;\n objectBase.Sound.MinFirstImpactForce = 100.0f;\n objectBase.InitLocalTransform.SetPosition(0.0f, 41.0f, 20.0f);\n objectBase.Integral.SetDensity(1.44f);\n\n objectBase = scene.Factory.PhysicsObjectManager.Create(\"Ragdoll 1 Lower Torso\" + instanceIndexName);\n objectRoot.AddChildPhysicsObject(objectBase);\n objectBase.Shape = box;\n objectBase.UserDataStr = \"Box\";\n objectBase.CreateSound(true);\n objectBase.Sound.HitVolume = 0.25f;\n objectBase.Sound.RollVolume = 0.25f;\n objectBase.Sound.SlideVolume = 0.25f;\n objectBase.Sound.MinFirstImpactForce = 100.0f; \n objectBase.InitLocalTransform.SetPosition(0.0f, 39.0f, 20.0f);\n objectBase.Integral.SetDensity(1.84f);\n\n objectBase = scene.Factory.PhysicsObjectManager.Create(\"Ragdoll 1 Right Upper Arm\" + instanceIndexName);\n objectRoot.AddChildPhysicsObject(objectBase);\n objectBase.Shape = box;\n objectBase.UserDataStr = \"Box\";\n objectBase.InitLocalTransform.SetPosition(2.0f, 41.5f, 20.0f);\n objectBase.InitLocalTransform.SetScale(1.0f, 0.5f, 0.5f);\n objectBase.Integral.SetDensity(2.145f);\n\n objectBase = scene.Factory.PhysicsObjectManager.Create(\"Ragdoll 1 Right Lower Arm\" + instanceIndexName);\n objectRoot.AddChildPhysicsObject(objectBase);\n objectBase.Shape = box;\n objectBase.UserDataStr = \"Box\";\n objectBase.InitLocalTransform.SetPosition(4.0f, 41.5f, 20.0f);\n objectBase.InitLocalTransform.SetScale(1.0f, 0.5f, 0.5f);\n objectBase.Integral.SetDensity(2.145f);\n\n objectBase = scene.Factory.PhysicsObjectManager.Create(\"Ragdoll 1 Right Hand\" + instanceIndexName);\n objectRoot.AddChildPhysicsObject(objectBase);\n objectBase.Shape = box;\n objectBase.UserDataStr = \"Box\";\n objectBase.CreateSound(true);\n objectBase.Sound.HitVolume = 0.25f;\n objectBase.Sound.RollVolume = 0.25f;\n objectBase.Sound.SlideVolume = 0.25f;\n objectBase.Sound.MinFirstImpactForce = 100.0f;\n objectBase.InitLocalTransform.SetPosition(5.5f, 41.5f, 20.0f);\n objectBase.InitLocalTransform.SetScale(0.5f, 0.4f, 0.2f);\n objectBase.Integral.SetDensity(2.145f);\n\n objectBase = scene.Factory.PhysicsObjectManager.Create(\"Ragdoll 1 Left Upper Arm\" + instanceIndexName);\n objectRoot.AddChildPhysicsObject(objectBase);\n objectBase.Shape = box;\n objectBase.UserDataStr = \"Box\";\n objectBase.InitLocalTransform.SetPosition(-2.0f, 41.5f, 20.0f);\n objectBase.InitLocalTransform.SetScale(1.0f, 0.5f, 0.5f);\n objectBase.Integral.SetDensity(2.145f);\n\n objectBase = scene.Factory.PhysicsObjectManager.Create(\"Ragdoll 1 Left Lower Arm\" + instanceIndexName);\n objectRoot.AddChildPhysicsObject(objectBase);\n objectBase.Shape = box;\n objectBase.UserDataStr = \"Box\";\n objectBase.InitLocalTransform.SetPosition(-4.0f, 41.5f, 20.0f);\n objectBase.InitLocalTransform.SetScale(1.0f, 0.5f, 0.5f);\n objectBase.Integral.SetDensity(2.145f);\n\n objectBase = scene.Factory.PhysicsObjectManager.Create(\"Ragdoll 1 Left Hand\" + instanceIndexName);\n objectRoot.AddChildPhysicsObject(objectBase);\n objectBase.Shape = box;\n objectBase.UserDataStr = \"Box\";\n objectBase.CreateSound(true);\n objectBase.Sound.HitVolume = 0.25f;\n objectBase.Sound.RollVolume = 0.25f;\n objectBase.Sound.SlideVolume = 0.25f;\n objectBase.Sound.MinFirstImpactForce = 100.0f;\n objectBase.InitLocalTransform.SetPosition(-5.5f, 41.5f, 20.0f);\n objectBase.InitLocalTransform.SetScale(0.5f, 0.4f, 0.2f);\n objectBase.Integral.SetDensity(2.145f);\n\n objectBase = scene.Factory.PhysicsObjectManager.Create(\"Ragdoll 1 Right Upper Leg\" + instanceIndexName);\n objectRoot.AddChildPhysicsObject(objectBase);\n objectBase.Shape = box;\n objectBase.UserDataStr = \"Box\";\n objectBase.InitLocalTransform.SetPosition(0.6f, 36.75f, 20.0f);\n objectBase.InitLocalTransform.SetScale(0.5f, 1.25f, 0.5f);\n objectBase.Integral.SetDensity(2.145f);\n\n objectBase = scene.Factory.PhysicsObjectManager.Create(\"Ragdoll 1 Right Lower Leg\" + instanceIndexName);\n objectRoot.AddChildPhysicsObject(objectBase);\n objectBase.Shape = box;\n objectBase.UserDataStr = \"Box\";\n objectBase.InitLocalTransform.SetPosition(0.6f, 34.25f, 20.0f);\n objectBase.InitLocalTransform.SetScale(0.5f, 1.25f, 0.5f);\n objectBase.Integral.SetDensity(2.145f);\n\n objectBase = scene.Factory.PhysicsObjectManager.Create(\"Ragdoll 1 Right Foot\" + instanceIndexName);\n objectRoot.AddChildPhysicsObject(objectBase);\n objectBase.Shape = box;\n objectBase.UserDataStr = \"Box\";\n objectBase.CreateSound(true);\n objectBase.Sound.HitVolume = 0.25f;\n objectBase.Sound.RollVolume = 0.25f;\n objectBase.Sound.SlideVolume = 0.25f;\n objectBase.Sound.MinFirstImpactForce = 100.0f;\n objectBase.InitLocalTransform.SetPosition(0.6f, 32.8f, 19.7f);\n objectBase.InitLocalTransform.SetScale(0.4f, 0.2f, 0.8f);\n objectBase.Integral.SetDensity(2.145f);\n\n objectBase = scene.Factory.PhysicsObjectManager.Create(\"Ragdoll 1 Left Upper Leg\" + instanceIndexName);\n objectRoot.AddChildPhysicsObject(objectBase);\n objectBase.Shape = box;\n objectBase.UserDataStr = \"Box\";\n objectBase.InitLocalTransform.SetPosition(-0.6f, 36.75f, 20.0f);\n objectBase.InitLocalTransform.SetScale(0.5f, 1.25f, 0.5f);\n objectBase.Integral.SetDensity(2.145f);\n\n objectBase = scene.Factory.PhysicsObjectManager.Create(\"Ragdoll 1 Left Lower Leg\" + instanceIndexName);\n objectRoot.AddChildPhysicsObject(objectBase);\n objectBase.Shape = box;\n objectBase.UserDataStr = \"Box\";\n objectBase.InitLocalTransform.SetPosition(-0.6f, 34.25f, 20.0f);\n objectBase.InitLocalTransform.SetScale(0.5f, 1.25f, 0.5f);\n objectBase.Integral.SetDensity(2.145f);\n\n objectBase = scene.Factory.PhysicsObjectManager.Create(\"Ragdoll 1 Left Foot\" + instanceIndexName);\n objectRoot.AddChildPhysicsObject(objectBase);\n objectBase.Shape = box;\n objectBase.UserDataStr = \"Box\";\n objectBase.CreateSound(true);\n objectBase.Sound.HitVolume = 0.25f;\n objectBase.Sound.RollVolume = 0.25f;\n objectBase.Sound.SlideVolume = 0.25f;\n objectBase.Sound.MinFirstImpactForce = 100.0f;\n objectBase.InitLocalTransform.SetPosition(-0.6f, 32.8f, 19.7f);\n objectBase.InitLocalTransform.SetScale(0.4f, 0.2f, 0.8f);\n objectBase.Integral.SetDensity(2.145f);\n\n objectRoot.UpdateFromInitLocalTransform();\n\n Constraint constraint = null;\n constraint = scene.Factory.ConstraintManager.Create(\"Ragdoll 1 Constraint 1\" + instanceIndexName);\n constraint.PhysicsObject1 = scene.Factory.PhysicsObjectManager.Find(\"Ragdoll 1 Head\" + instanceIndexName);\n constraint.PhysicsObject2 = scene.Factory.PhysicsObjectManager.Find(\"Ragdoll 1 Upper Torso\" + instanceIndexName);\n constraint.PhysicsObject1.MainWorldTransform.GetPosition(ref position1);\n constraint.PhysicsObject1.MainWorldTransform.GetOrientation(ref orientation1);\n constraint.PhysicsObject2.MainWorldTransform.GetOrientation(ref orientation2);\n constraint.SetAnchor1(position1 - new Vector3(0.0f, 0.7f, 0.0f));\n constraint.SetAnchor2(position1 - new Vector3(0.0f, 0.7f, 0.0f));\n constraint.SetInitWorldOrientation1(ref orientation1);\n constraint.SetInitWorldOrientation2(ref orientation2);\n constraint.EnableBreak = true;\n constraint.MinBreakVelocity = 300.0f;\n constraint.EnableLimitAngleX = true;\n constraint.EnableLimitAngleY = true;\n constraint.EnableLimitAngleZ = true;\n constraint.MinLimitDegAngleX = -20.0f;\n constraint.MaxLimitDegAngleX = 20.0f;\n constraint.MinLimitDegAngleY = -60.0f;\n constraint.MaxLimitDegAngleY = 60.0f;\n constraint.LimitAngleMode = LimitAngleMode.EulerYZX;\n\n if (enableControl)\n {\n constraint.EnableControlAngleX = true;\n constraint.EnableControlAngleY = true;\n constraint.EnableControlAngleZ = true;\n }\n else\n if (enableControlWithDeformation)\n {\n constraint.EnableControlAngleX = true;\n constraint.EnableControlAngleY = true;\n constraint.EnableControlAngleZ = true;\n\n constraint.EnableControlAngleWithDeformation = true;\n constraint.MinAngleDeformationVelocity = minAngleDeformationVelocity;\n constraint.AngularDamping = 1.0f;\n }\n\n constraint.Update();\n\n constraint = scene.Factory.ConstraintManager.Create(\"Ragdoll 1 Constraint 2\" + instanceIndexName);\n constraint.PhysicsObject1 = scene.Factory.PhysicsObjectManager.Find(\"Ragdoll 1 Upper Torso\" + instanceIndexName);\n constraint.PhysicsObject2 = scene.Factory.PhysicsObjectManager.Find(\"Ragdoll 1 Lower Torso\" + instanceIndexName);\n constraint.PhysicsObject1.MainWorldTransform.GetPosition(ref position1);\n constraint.PhysicsObject1.MainWorldTransform.GetOrientation(ref orientation1);\n constraint.PhysicsObject2.MainWorldTransform.GetOrientation(ref orientation2);\n constraint.SetAnchor1(position1 - new Vector3(0.0f, 1.0f, 0.0f));\n constraint.SetAnchor2(position1 - new Vector3(0.0f, 1.0f, 0.0f));\n constraint.SetInitWorldOrientation1(ref orientation1);\n constraint.SetInitWorldOrientation2(ref orientation2);\n constraint.EnableBreak = true;\n constraint.MinBreakVelocity = 300.0f;\n constraint.EnableLimitAngleX = true;\n constraint.EnableLimitAngleY = true;\n constraint.EnableLimitAngleZ = true;\n constraint.MinLimitDegAngleX = -10.0f;\n constraint.MaxLimitDegAngleX = 45.0f;\n constraint.MinLimitDegAngleZ = -10.0f;\n constraint.MaxLimitDegAngleZ = 10.0f;\n constraint.LimitAngleMode = LimitAngleMode.EulerYZX;\n\n if (enableControl)\n {\n constraint.EnableControlAngleX = true;\n constraint.EnableControlAngleY = true;\n constraint.EnableControlAngleZ = true;\n }\n else\n if (enableControlWithDeformation)\n {\n constraint.EnableControlAngleX = true;\n constraint.EnableControlAngleY = true;\n constraint.EnableControlAngleZ = true;\n\n constraint.EnableControlAngleWithDeformation = true;\n constraint.MinAngleDeformationVelocity = minAngleDeformationVelocity;\n constraint.AngularDamping = 1.0f;\n }\n\n constraint.Update();\n\n constraint = scene.Factory.ConstraintManager.Create(\"Ragdoll 1 Constraint 3\" + instanceIndexName);\n constraint.PhysicsObject1 = scene.Factory.PhysicsObjectManager.Find(\"Ragdoll 1 Upper Torso\" + instanceIndexName);\n constraint.PhysicsObject2 = scene.Factory.PhysicsObjectManager.Find(\"Ragdoll 1 Right Upper Arm\" + instanceIndexName);\n constraint.PhysicsObject2.MainWorldTransform.GetPosition(ref position2);\n constraint.PhysicsObject1.MainWorldTransform.GetOrientation(ref orientation1);\n constraint.PhysicsObject2.MainWorldTransform.GetOrientation(ref orientation2);\n constraint.SetAnchor1(position2 - new Vector3(1.0f, 0.0f, 0.0f));\n constraint.SetAnchor2(position2 - new Vector3(1.0f, 0.0f, 0.0f));\n constraint.SetInitWorldOrientation1(ref orientation1);\n constraint.SetInitWorldOrientation2(ref orientation2);\n constraint.EnableBreak = true;\n constraint.MinBreakVelocity = 300.0f;\n constraint.EnableLimitAngleX = true;\n constraint.EnableLimitAngleY = true;\n constraint.EnableLimitAngleZ = true;\n constraint.MinLimitDegAngleY = -20.0f;\n constraint.MaxLimitDegAngleY = 90.0f;\n constraint.MinLimitDegAngleZ = -90.0f;\n constraint.MaxLimitDegAngleZ = 45.0f;\n constraint.LimitAngleMode = LimitAngleMode.EulerYZX;\n\n if (enableControl)\n {\n constraint.EnableControlAngleX = true;\n constraint.EnableControlAngleY = true;\n constraint.EnableControlAngleZ = true;\n }\n else\n if (enableControlWithDeformation)\n {\n constraint.EnableControlAngleX = true;\n constraint.EnableControlAngleY = true;\n constraint.EnableControlAngleZ = true;\n\n constraint.EnableControlAngleWithDeformation = true;\n constraint.MinAngleDeformationVelocity = minAngleDeformationVelocity;\n constraint.AngularDamping = 1.0f;\n }\n\n constraint.Update();\n\n constraint = scene.Factory.ConstraintManager.Create(\"Ragdoll 1 Constraint 4\" + instanceIndexName);\n constraint.PhysicsObject1 = scene.Factory.PhysicsObjectManager.Find(\"Ragdoll 1 Upper Torso\" + instanceIndexName);\n constraint.PhysicsObject2 = scene.Factory.PhysicsObjectManager.Find(\"Ragdoll 1 Left Upper Arm\" + instanceIndexName);\n constraint.PhysicsObject2.MainWorldTransform.GetPosition(ref position2);\n constraint.PhysicsObject1.MainWorldTransform.GetOrientation(ref orientation1);\n constraint.PhysicsObject2.MainWorldTransform.GetOrientation(ref orientation2);\n constraint.SetAnchor1(position2 + new Vector3(1.0f, 0.0f, 0.0f));\n constraint.SetAnchor2(position2 + new Vector3(1.0f, 0.0f, 0.0f));\n constraint.SetInitWorldOrientation1(ref orientation1);\n constraint.SetInitWorldOrientation2(ref orientation2);\n constraint.EnableBreak = true;\n constraint.MinBreakVelocity = 300.0f;\n constraint.EnableLimitAngleX = true;\n constraint.EnableLimitAngleY = true;\n constraint.EnableLimitAngleZ = true;\n constraint.MinLimitDegAngleY = -90.0f;\n constraint.MaxLimitDegAngleY = 20.0f;\n constraint.MinLimitDegAngleZ = -45.0f;\n constraint.MaxLimitDegAngleZ = 90.0f;\n constraint.LimitAngleMode = LimitAngleMode.EulerYZX;\n\n if (enableControl)\n {\n constraint.EnableControlAngleX = true;\n constraint.EnableControlAngleY = true;\n constraint.EnableControlAngleZ = true;\n }\n else\n if (enableControlWithDeformation)\n {\n constraint.EnableControlAngleX = true;\n constraint.EnableControlAngleY = true;\n constraint.EnableControlAngleZ = true;\n\n constraint.EnableControlAngleWithDeformation = true;\n constraint.MinAngleDeformationVelocity = minAngleDeformationVelocity;\n constraint.AngularDamping = 1.0f;\n }\n\n constraint.Update();\n\n constraint = scene.Factory.ConstraintManager.Create(\"Ragdoll 1 Constraint 5\" + instanceIndexName);\n constraint.PhysicsObject1 = scene.Factory.PhysicsObjectManager.Find(\"Ragdoll 1 Lower Torso\" + instanceIndexName);\n constraint.PhysicsObject2 = scene.Factory.PhysicsObjectManager.Find(\"Ragdoll 1 Right Upper Leg\" + instanceIndexName);\n constraint.PhysicsObject2.MainWorldTransform.GetPosition(ref position2);\n constraint.PhysicsObject1.MainWorldTransform.GetOrientation(ref orientation1);\n constraint.PhysicsObject2.MainWorldTransform.GetOrientation(ref orientation2);\n constraint.SetAnchor1(position2 + new Vector3(0.0f, 1.25f, 0.0f));\n constraint.SetAnchor2(position2 + new Vector3(0.0f, 1.25f, 0.0f));\n constraint.SetInitWorldOrientation1(ref orientation1);\n constraint.SetInitWorldOrientation2(ref orientation2);\n constraint.EnableBreak = true;\n constraint.MinBreakVelocity = 300.0f;\n constraint.EnableLimitAngleX = true;\n constraint.EnableLimitAngleY = true;\n constraint.EnableLimitAngleZ = true;\n constraint.MinLimitDegAngleX = -10.0f;\n constraint.MaxLimitDegAngleX = 100.0f;\n constraint.MinLimitDegAngleY = -20.0f;\n constraint.MaxLimitDegAngleY = 0.0f;\n constraint.MinLimitDegAngleZ = -45.0f;\n constraint.MaxLimitDegAngleZ = 45.0f;\n constraint.LimitAngleMode = LimitAngleMode.EulerYZX;\n\n if (enableControl)\n {\n constraint.EnableControlAngleX = true;\n constraint.EnableControlAngleY = true;\n constraint.EnableControlAngleZ = true;\n }\n else\n if (enableControlWithDeformation)\n {\n constraint.EnableControlAngleX = true;\n constraint.EnableControlAngleY = true;\n constraint.EnableControlAngleZ = true;\n\n constraint.EnableControlAngleWithDeformation = true;\n constraint.MinAngleDeformationVelocity = minAngleDeformationVelocity;\n constraint.AngularDamping = 1.0f;\n }\n\n constraint.Update();\n\n constraint = scene.Factory.ConstraintManager.Create(\"Ragdoll 1 Constraint 6\" + instanceIndexName);\n constraint.PhysicsObject1 = scene.Factory.PhysicsObjectManager.Find(\"Ragdoll 1 Lower Torso\" + instanceIndexName);\n constraint.PhysicsObject2 = scene.Factory.PhysicsObjectManager.Find(\"Ragdoll 1 Left Upper Leg\" + instanceIndexName);\n constraint.PhysicsObject2.MainWorldTransform.GetPosition(ref position2);\n constraint.PhysicsObject1.MainWorldTransform.GetOrientation(ref orientation1);\n constraint.PhysicsObject2.MainWorldTransform.GetOrientation(ref orientation2);\n constraint.SetAnchor1(position2 + new Vector3(0.0f, 1.25f, 0.0f));\n constraint.SetAnchor2(position2 + new Vector3(0.0f, 1.25f, 0.0f));\n constraint.SetInitWorldOrientation1(ref orientation1);\n constraint.SetInitWorldOrientation2(ref orientation2);\n constraint.EnableBreak = true;\n constraint.MinBreakVelocity = 300.0f;\n constraint.EnableLimitAngleX = true;\n constraint.EnableLimitAngleY = true;\n constraint.EnableLimitAngleZ = true;\n constraint.MinLimitDegAngleX = -10.0f;\n constraint.MaxLimitDegAngleX = 100.0f;\n constraint.MinLimitDegAngleY = -20.0f;\n constraint.MaxLimitDegAngleY = 0.0f;\n constraint.MinLimitDegAngleZ = -45.0f;\n constraint.MaxLimitDegAngleZ = 45.0f;\n constraint.LimitAngleMode = LimitAngleMode.EulerYZX;\n\n if (enableControl)\n {\n constraint.EnableControlAngleX = true;\n constraint.EnableControlAngleY = true;\n constraint.EnableControlAngleZ = true;\n }\n else\n if (enableControlWithDeformation)\n {\n constraint.EnableControlAngleX = true;\n constraint.EnableControlAngleY = true;\n constraint.EnableControlAngleZ = true;\n\n constraint.EnableControlAngleWithDeformation = true;\n constraint.MinAngleDeformationVelocity = minAngleDeformationVelocity;\n constraint.AngularDamping = 1.0f;\n }\n\n constraint.Update();\n\n constraint = scene.Factory.ConstraintManager.Create(\"Ragdoll 1 Constraint 7\" + instanceIndexName);\n constraint.PhysicsObject1 = scene.Factory.PhysicsObjectManager.Find(\"Ragdoll 1 Right Upper Arm\" + instanceIndexName);\n constraint.PhysicsObject2 = scene.Factory.PhysicsObjectManager.Find(\"Ragdoll 1 Right Lower Arm\" + instanceIndexName);\n constraint.PhysicsObject1.MainWorldTransform.GetPosition(ref position1);\n constraint.PhysicsObject1.MainWorldTransform.GetOrientation(ref orientation1);\n constraint.PhysicsObject2.MainWorldTransform.GetOrientation(ref orientation2);\n constraint.SetAnchor1(position1 + new Vector3(1.0f, 0.0f, 0.0f));\n constraint.SetAnchor2(position1 + new Vector3(1.0f, 0.0f, 0.0f));\n constraint.SetInitWorldOrientation1(ref orientation1);\n constraint.SetInitWorldOrientation2(ref orientation2);\n constraint.EnableBreak = true;\n constraint.MinBreakVelocity = 300.0f;\n constraint.EnableLimitAngleX = true;\n constraint.EnableLimitAngleY = true;\n constraint.EnableLimitAngleZ = true;\n constraint.MinLimitDegAngleY = -2.0f;\n constraint.MaxLimitDegAngleY = 135.0f;\n constraint.LimitAngleMode = LimitAngleMode.EulerYZX;\n\n if (enableControl)\n {\n constraint.EnableControlAngleX = true;\n constraint.EnableControlAngleY = true;\n constraint.EnableControlAngleZ = true;\n }\n else\n if (enableControlWithDeformation)\n {\n constraint.EnableControlAngleX = true;\n constraint.EnableControlAngleY = true;\n constraint.EnableControlAngleZ = true;\n\n constraint.EnableControlAngleWithDeformation = true;\n constraint.MinAngleDeformationVelocity = minAngleDeformationVelocity;\n constraint.AngularDamping = 1.0f;\n }\n\n constraint.Update();\n\n constraint = scene.Factory.ConstraintManager.Create(\"Ragdoll 1 Constraint 8\" + instanceIndexName);\n constraint.PhysicsObject1 = scene.Factory.PhysicsObjectManager.Find(\"Ragdoll 1 Right Lower Arm\" + instanceIndexName);\n constraint.PhysicsObject2 = scene.Factory.PhysicsObjectManager.Find(\"Ragdoll 1 Right Hand\" + instanceIndexName);\n constraint.PhysicsObject1.MainWorldTransform.GetPosition(ref position1);\n constraint.PhysicsObject1.MainWorldTransform.GetOrientation(ref orientation1);\n constraint.PhysicsObject2.MainWorldTransform.GetOrientation(ref orientation2);\n constraint.SetAnchor1(position1 + new Vector3(1.0f, 0.0f, 0.0f));", "answers": [" constraint.SetAnchor2(position1 + new Vector3(1.0f, 0.0f, 0.0f));"], "length": 1388, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "8cd1ac49-5657-4ba9-8329-0130b31c9950", "reasoning": "In each constraint definition, after setting the first anchor with SetAnchor1, the code always sets the second anchor with SetAnchor2 using the same position expression. The snippet ends right after SetAnchor1 for Constraint 8, so the next logical line is the corresponding SetAnchor2 call.", "reasoning_model_answer": "constraint.SetAnchor2(position1 + new Vector3(1.0f, 0.0f, 0.0f));", "assistant_with_reasoning": "\nIn each constraint definition, after setting the first anchor with SetAnchor1, the code always sets the second anchor with SetAnchor2 using the same position expression. The snippet ends right after SetAnchor1 for Constraint 8, so the next logical line is the corresponding SetAnchor2 call.\n\nconstraint.SetAnchor2(position1 + new Vector3(1.0f, 0.0f, 0.0f));", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 6.324, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 25871, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "constraint.SetAnchor2(position1 + new Vector3(1.0f, 0.0f, 0.0f));", "score": 0.92, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\nusing System.Diagnostics;\nusing System.Runtime.Intrinsics;\nusing System.Runtime.Intrinsics.X86;\nusing System.Numerics;\nusing Internal.Runtime.CompilerServices;\n\n#pragma warning disable SA1121 // explicitly using type aliases instead of built-in types\n#if BIT64\nusing nint = System.Int64;\nusing nuint = System.UInt64;\n#else // BIT64\nusing nint = System.Int32;\nusing nuint = System.UInt32;\n#endif // BIT64\n\nnamespace System.Text.Unicode\n{\n internal static unsafe partial class Utf16Utility\n {\n#if DEBUG\n static Utf16Utility()\n {\n Debug.Assert(sizeof(nint) == IntPtr.Size && nint.MinValue < 0, \"nint is defined incorrectly.\");\n Debug.Assert(sizeof(nuint) == IntPtr.Size && nuint.MinValue == 0, \"nuint is defined incorrectly.\");\n }\n#endif // DEBUG\n\n // Returns &inputBuffer[inputLength] if the input buffer is valid.\n /// \n /// Given an input buffer of char length ,\n /// returns a pointer to where the first invalid data appears in .\n /// \n /// \n /// Returns a pointer to the end of if the buffer is well-formed.\n /// \n public static char* GetPointerToFirstInvalidChar(char* pInputBuffer, int inputLength, out long utf8CodeUnitCountAdjustment, out int scalarCountAdjustment)\n {\n Debug.Assert(inputLength >= 0, \"Input length must not be negative.\");\n Debug.Assert(pInputBuffer != null || inputLength == 0, \"Input length must be zero if input buffer pointer is null.\");\n\n // First, we'll handle the common case of all-ASCII. If this is able to\n // consume the entire buffer, we'll skip the remainder of this method's logic.\n\n int numAsciiCharsConsumedJustNow = (int)ASCIIUtility.GetIndexOfFirstNonAsciiChar(pInputBuffer, (uint)inputLength);\n Debug.Assert(0 <= numAsciiCharsConsumedJustNow && numAsciiCharsConsumedJustNow <= inputLength);\n\n pInputBuffer += (uint)numAsciiCharsConsumedJustNow;\n inputLength -= numAsciiCharsConsumedJustNow;\n\n if (inputLength == 0)\n {\n utf8CodeUnitCountAdjustment = 0;\n scalarCountAdjustment = 0;\n return pInputBuffer;\n }\n\n // If we got here, it means we saw some non-ASCII data, so within our\n // vectorized code paths below we'll handle all non-surrogate UTF-16\n // code points branchlessly. We'll only branch if we see surrogates.\n //\n // We still optimistically assume the data is mostly ASCII. This means that the\n // number of UTF-8 code units and the number of scalars almost matches the number\n // of UTF-16 code units. As we go through the input and find non-ASCII\n // characters, we'll keep track of these \"adjustment\" fixups. To get the\n // total number of UTF-8 code units required to encode the input data, add\n // the UTF-8 code unit count adjustment to the number of UTF-16 code units\n // seen. To get the total number of scalars present in the input data,\n // add the scalar count adjustment to the number of UTF-16 code units seen.\n\n long tempUtf8CodeUnitCountAdjustment = 0;\n int tempScalarCountAdjustment = 0;\n\n if (Sse2.IsSupported)\n {\n if (inputLength >= Vector128.Count)\n {\n Vector128 vector0080 = Vector128.Create((ushort)0x80);\n Vector128 vectorA800 = Vector128.Create((ushort)0xA800);\n Vector128 vector8800 = Vector128.Create(unchecked((short)0x8800));\n Vector128 vectorZero = Vector128.Zero;\n\n do\n {\n Vector128 utf16Data = Sse2.LoadVector128((ushort*)pInputBuffer); // unaligned\n uint mask;\n\n // The 'charIsNonAscii' vector we're about to build will have the 0x8000 or the 0x0080\n // bit set (but not both!) only if the corresponding input char is non-ASCII. Which of\n // the two bits is set doesn't matter, as will be explained in the diagram a few lines\n // below.\n\n Vector128 charIsNonAscii;\n if (Sse41.IsSupported)\n {\n // sets 0x0080 bit if corresponding char element is >= 0x0080\n charIsNonAscii = Sse41.Min(utf16Data, vector0080);\n }\n else\n {\n // sets 0x8000 bit if corresponding char element is >= 0x0080\n charIsNonAscii = Sse2.AndNot(vector0080, Sse2.Subtract(vectorZero, Sse2.ShiftRightLogical(utf16Data, 7)));\n }\n\n#if DEBUG\n // Quick check to ensure we didn't accidentally set both 0x8080 bits in any element.\n uint debugMask = (uint)Sse2.MoveMask(charIsNonAscii.AsByte());\n Debug.Assert((debugMask & (debugMask << 1)) == 0, \"Two set bits shouldn't occur adjacent to each other in this mask.\");\n#endif // DEBUG\n\n // sets 0x8080 bits if corresponding char element is >= 0x0800\n Vector128 charIsThreeByteUtf8Encoded = Sse2.Subtract(vectorZero, Sse2.ShiftRightLogical(utf16Data, 11));\n\n mask = (uint)Sse2.MoveMask(Sse2.Or(charIsNonAscii, charIsThreeByteUtf8Encoded).AsByte());\n\n // Each odd bit of mask will be 1 only if the char was >= 0x0080,\n // and each even bit of mask will be 1 only if the char was >= 0x0800.\n //\n // Example for UTF-16 input \"[ 0123 ] [ 1234 ] ...\":\n //\n // ,-- set if char[1] is non-ASCII\n // | ,-- set if char[0] is non-ASCII\n // v v\n // mask = ... 1 1 1 0\n // ^ ^-- set if char[0] is >= 0x0800\n // `-- set if char[1] is >= 0x0800\n //\n // (If the SSE4.1 code path is taken above, the meaning of the odd and even\n // bits are swapped, but the logic below otherwise holds.)\n //\n // This means we can popcnt the number of set bits, and the result is the\n // number of *additional* UTF-8 bytes that each UTF-16 code unit requires as\n // it expands. This results in the wrong count for UTF-16 surrogate code\n // units (we just counted that each individual code unit expands to 3 bytes,\n // but in reality a well-formed UTF-16 surrogate pair expands to 4 bytes).\n // We'll handle this in just a moment.\n //\n // For now, compute the popcnt but squirrel it away. We'll fold it in to the\n // cumulative UTF-8 adjustment factor once we determine that there are no\n // unpaired surrogates in our data. (Unpaired surrogates would invalidate\n // our computed result and we'd have to throw it away.)\n\n uint popcnt = (uint)BitOperations.PopCount(mask);\n\n // Surrogates need to be special-cased for two reasons: (a) we need\n // to account for the fact that we over-counted in the addition above;\n // and (b) they require separate validation.\n\n utf16Data = Sse2.Add(utf16Data, vectorA800);\n mask = (uint)Sse2.MoveMask(Sse2.CompareLessThan(utf16Data.AsInt16(), vector8800).AsByte());\n\n if (mask != 0)\n {\n // There's at least one UTF-16 surrogate code unit present.\n // Since we performed a pmovmskb operation on the result of a 16-bit pcmpgtw,\n // the resulting bits of 'mask' will occur in pairs:\n // - 00 if the corresponding UTF-16 char was not a surrogate code unit;\n // - 11 if the corresponding UTF-16 char was a surrogate code unit.\n //\n // A UTF-16 high/low surrogate code unit has the bit pattern [ 11011q## ######## ],\n // where # is any bit; q = 0 represents a high surrogate, and q = 1 represents\n // a low surrogate. Since we added 0xA800 in the vectorized operation above,\n // our surrogate pairs will now have the bit pattern [ 10000q## ######## ].\n // If we logical right-shift each word by 3, we'll end up with the bit pattern\n // [ 00010000 q####### ], which means that we can immediately use pmovmskb to\n // determine whether a given char was a high or a low surrogate.\n //\n // Therefore the resulting bits of 'mask2' will occur in pairs:\n // - 00 if the corresponding UTF-16 char was a high surrogate code unit;\n // - 01 if the corresponding UTF-16 char was a low surrogate code unit;\n // - ## (garbage) if the corresponding UTF-16 char was not a surrogate code unit.\n // Since 'mask' already has 00 in these positions (since the corresponding char\n // wasn't a surrogate), \"mask AND mask2 == 00\" holds for these positions.\n\n uint mask2 = (uint)Sse2.MoveMask(Sse2.ShiftRightLogical(utf16Data, 3).AsByte());\n\n // 'lowSurrogatesMask' has its bits occur in pairs:\n // - 01 if the corresponding char was a low surrogate char,\n // - 00 if the corresponding char was a high surrogate char or not a surrogate at all.\n\n uint lowSurrogatesMask = mask2 & mask;\n\n // 'highSurrogatesMask' has its bits occur in pairs:\n // - 01 if the corresponding char was a high surrogate char,\n // - 00 if the corresponding char was a low surrogate char or not a surrogate at all.\n\n uint highSurrogatesMask = (mask2 ^ 0b_0101_0101_0101_0101u /* flip all even-numbered bits 00 <-> 01 */) & mask;\n\n Debug.Assert((highSurrogatesMask & lowSurrogatesMask) == 0,\n \"A char cannot simultaneously be both a high and a low surrogate char.\");\n\n Debug.Assert(((highSurrogatesMask | lowSurrogatesMask) & 0b_1010_1010_1010_1010u) == 0,\n \"Only even bits (no odd bits) of the masks should be set.\");\n\n // Now check that each high surrogate is followed by a low surrogate and that each\n // low surrogate follows a high surrogate. We make an exception for the case where\n // the final char of the vector is a high surrogate, since we can't perform validation\n // on it until the next iteration of the loop when we hope to consume the matching\n // low surrogate.\n\n highSurrogatesMask <<= 2;\n if ((ushort)highSurrogatesMask != lowSurrogatesMask)\n {\n goto NonVectorizedLoop; // error: mismatched surrogate pair; break out of vectorized logic\n }\n\n if (highSurrogatesMask > ushort.MaxValue)\n {\n // There was a standalone high surrogate at the end of the vector.\n // We'll adjust our counters so that we don't consider this char consumed.\n\n highSurrogatesMask = (ushort)highSurrogatesMask; // don't allow stray high surrogate to be consumed by popcnt\n popcnt -= 2; // the '0xC000_0000' bits in the original mask are shifted out and discarded, so account for that here\n pInputBuffer--;\n inputLength++;\n }\n\n // If we're 64-bit, we can perform the zero-extension of the surrogate pairs count for\n // free right now, saving the extension step a few lines below. If we're 32-bit, the\n // convertion to nuint immediately below is a no-op, and we'll pay the cost of the real\n // 64 -bit extension a few lines below.\n nuint surrogatePairsCountNuint = (uint)BitOperations.PopCount(highSurrogatesMask);\n\n // 2 UTF-16 chars become 1 Unicode scalar\n\n tempScalarCountAdjustment -= (int)surrogatePairsCountNuint;\n\n // Since each surrogate code unit was >= 0x0800, we eagerly assumed\n // it'd be encoded as 3 UTF-8 code units, so our earlier popcnt computation\n // assumes that the pair is encoded as 6 UTF-8 code units. Since each\n // pair is in reality only encoded as 4 UTF-8 code units, we need to\n // perform this adjustment now.\n\n if (IntPtr.Size == 8)\n {\n // Since we've already zero-extended surrogatePairsCountNuint, we can directly\n // sub + sub. It's more efficient than shl + sub.\n tempUtf8CodeUnitCountAdjustment -= (long)surrogatePairsCountNuint;\n tempUtf8CodeUnitCountAdjustment -= (long)surrogatePairsCountNuint;\n }\n else\n {\n // Take the hit of the 64-bit extension now.\n tempUtf8CodeUnitCountAdjustment -= 2 * (uint)surrogatePairsCountNuint;\n }\n }\n\n tempUtf8CodeUnitCountAdjustment += popcnt;\n pInputBuffer += Vector128.Count;\n inputLength -= Vector128.Count;", "answers": [" } while (inputLength >= Vector128.Count);"], "length": 1661, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "86853510-1a4c-434d-a3af-2c69fab045c3", "reasoning": "The code is inside a do‑while loop that processes Vector128.Count characters each iteration. After updating the pointers and counters, the loop needs its closing condition. The typical pattern is a closing brace followed by the while condition checking that enough input remains. Hence the next line should close the loop with the condition.", "reasoning_model_answer": "} while (inputLength >= Vector128.Count);", "assistant_with_reasoning": "\nThe code is inside a do‑while loop that processes Vector128.Count characters each iteration. After updating the pointers and counters, the loop needs its closing condition. The typical pattern is a closing brace followed by the while condition checking that enough input remains. Hence the next line should close the loop with the condition.\n\n} while (inputLength >= Vector128.Count);", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.244, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 15451, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "} while (inputLength >= Vector128.Count);", "score": 0.83, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "using System;\nusing System.Globalization;\nusing System.Collections.Generic;\n\nusing Sasoma.Utils;\nusing Sasoma.Microdata.Interfaces;\nusing Sasoma.Languages.Core;\nusing Sasoma.Microdata.Properties;\n\nnamespace Sasoma.Microdata.Types\n{\n\t/// \n\t/// Web page type: Image gallery page.\n\t/// \n\tpublic class ImageGallery_Core : TypeCore, ICollectionPage\n\t{\n\t\tpublic ImageGallery_Core()\n\t\t{\n\t\t\tthis._TypeId = 135;\n\t\t\tthis._Id = \"ImageGallery\";\n\t\t\tthis._Schema_Org_Url = \"http://schema.org/ImageGallery\";\n\t\t\tstring label = \"\";\n\t\t\tGetLabel(out label, \"ImageGallery\", typeof(ImageGallery_Core));\n\t\t\tthis._Label = label;\n\t\t\tthis._Ancestors = new int[]{266,78,293,64};\n\t\t\tthis._SubTypes = new int[0];\n\t\t\tthis._SuperTypes = new int[]{64};\n\t\t\tthis._Properties = new int[]{67,108,143,229,0,2,10,12,18,20,24,26,21,50,51,54,57,58,59,61,62,64,70,72,81,97,100,110,115,116,126,138,151,178,179,180,199,211,219,230,231,38,117,133,169,208};\n\n\t\t}\n\n\t\t/// \n\t\t/// The subject matter of the content.\n\t\t/// \n\t\tprivate About_Core about;\n\t\tpublic About_Core About\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn about;\n\t\t\t}\n\t\t\tset\n\t\t\t{\n\t\t\t\tabout = value;\n\t\t\t\tSetPropertyInstance(about);\n\t\t\t}\n\t\t}\n\n\t\t/// \n\t\t/// Specifies the Person that is legally accountable for the CreativeWork.\n\t\t/// \n\t\tprivate AccountablePerson_Core accountablePerson;\n\t\tpublic AccountablePerson_Core AccountablePerson\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn accountablePerson;\n\t\t\t}\n\t\t\tset\n\t\t\t{\n\t\t\t\taccountablePerson = value;\n\t\t\t\tSetPropertyInstance(accountablePerson);\n\t\t\t}\n\t\t}\n\n\t\t/// \n\t\t/// The overall rating, based on a collection of reviews or ratings, of the item.\n\t\t/// \n\t\tprivate Properties.AggregateRating_Core aggregateRating;\n\t\tpublic Properties.AggregateRating_Core AggregateRating\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn aggregateRating;\n\t\t\t}\n\t\t\tset\n\t\t\t{\n\t\t\t\taggregateRating = value;\n\t\t\t\tSetPropertyInstance(aggregateRating);\n\t\t\t}\n\t\t}\n\n\t\t/// \n\t\t/// A secondary title of the CreativeWork.\n\t\t/// \n\t\tprivate AlternativeHeadline_Core alternativeHeadline;\n\t\tpublic AlternativeHeadline_Core AlternativeHeadline\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn alternativeHeadline;\n\t\t\t}\n\t\t\tset\n\t\t\t{\n\t\t\t\talternativeHeadline = value;\n\t\t\t\tSetPropertyInstance(alternativeHeadline);\n\t\t\t}\n\t\t}\n\n\t\t/// \n\t\t/// The media objects that encode this creative work. This property is a synonym for encodings.\n\t\t/// \n\t\tprivate AssociatedMedia_Core associatedMedia;\n\t\tpublic AssociatedMedia_Core AssociatedMedia\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn associatedMedia;\n\t\t\t}\n\t\t\tset\n\t\t\t{\n\t\t\t\tassociatedMedia = value;\n\t\t\t\tSetPropertyInstance(associatedMedia);\n\t\t\t}\n\t\t}\n\n\t\t/// \n\t\t/// An embedded audio object.\n\t\t/// \n\t\tprivate Audio_Core audio;\n\t\tpublic Audio_Core Audio\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn audio;\n\t\t\t}\n\t\t\tset\n\t\t\t{\n\t\t\t\taudio = value;\n\t\t\t\tSetPropertyInstance(audio);\n\t\t\t}\n\t\t}\n\n\t\t/// \n\t\t/// The author of this content. Please note that author is special in that HTML 5 provides a special mechanism for indicating authorship via the rel tag. That is equivalent to this and may be used interchangabely.\n\t\t/// \n\t\tprivate Author_Core author;\n\t\tpublic Author_Core Author\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn author;\n\t\t\t}\n\t\t\tset\n\t\t\t{\n\t\t\t\tauthor = value;\n\t\t\t\tSetPropertyInstance(author);\n\t\t\t}\n\t\t}\n\n\t\t/// \n\t\t/// Awards won by this person or for this creative work.\n\t\t/// \n\t\tprivate Awards_Core awards;\n\t\tpublic Awards_Core Awards\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn awards;\n\t\t\t}\n\t\t\tset\n\t\t\t{\n\t\t\t\tawards = value;\n\t\t\t\tSetPropertyInstance(awards);\n\t\t\t}\n\t\t}\n\n\t\t/// \n\t\t/// A set of links that can help a user understand and navigate a website hierarchy.\n\t\t/// \n\t\tprivate Breadcrumb_Core breadcrumb;\n\t\tpublic Breadcrumb_Core Breadcrumb\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn breadcrumb;\n\t\t\t}\n\t\t\tset\n\t\t\t{\n\t\t\t\tbreadcrumb = value;\n\t\t\t\tSetPropertyInstance(breadcrumb);\n\t\t\t}\n\t\t}\n\n\t\t/// \n\t\t/// Comments, typically from users, on this CreativeWork.\n\t\t/// \n\t\tprivate Comment_Core comment;\n\t\tpublic Comment_Core Comment\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn comment;\n\t\t\t}\n\t\t\tset\n\t\t\t{\n\t\t\t\tcomment = value;\n\t\t\t\tSetPropertyInstance(comment);\n\t\t\t}\n\t\t}\n\n\t\t/// \n\t\t/// The location of the content.\n\t\t/// \n\t\tprivate ContentLocation_Core contentLocation;\n\t\tpublic ContentLocation_Core ContentLocation\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn contentLocation;\n\t\t\t}\n\t\t\tset\n\t\t\t{\n\t\t\t\tcontentLocation = value;\n\t\t\t\tSetPropertyInstance(contentLocation);\n\t\t\t}\n\t\t}\n\n\t\t/// \n\t\t/// Official rating of a piece of content\\u2014for example,'MPAA PG-13'.\n\t\t/// \n\t\tprivate ContentRating_Core contentRating;\n\t\tpublic ContentRating_Core ContentRating\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn contentRating;\n\t\t\t}\n\t\t\tset\n\t\t\t{\n\t\t\t\tcontentRating = value;\n\t\t\t\tSetPropertyInstance(contentRating);\n\t\t\t}\n\t\t}\n\n\t\t/// \n\t\t/// A secondary contributor to the CreativeWork.\n\t\t/// \n\t\tprivate Contributor_Core contributor;\n\t\tpublic Contributor_Core Contributor\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn contributor;\n\t\t\t}\n\t\t\tset\n\t\t\t{\n\t\t\t\tcontributor = value;\n\t\t\t\tSetPropertyInstance(contributor);\n\t\t\t}\n\t\t}\n\n\t\t/// \n\t\t/// The party holding the legal copyright to the CreativeWork.\n\t\t/// \n\t\tprivate CopyrightHolder_Core copyrightHolder;\n\t\tpublic CopyrightHolder_Core CopyrightHolder\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn copyrightHolder;\n\t\t\t}\n\t\t\tset\n\t\t\t{\n\t\t\t\tcopyrightHolder = value;\n\t\t\t\tSetPropertyInstance(copyrightHolder);\n\t\t\t}\n\t\t}\n\n\t\t/// \n\t\t/// The year during which the claimed copyright for the CreativeWork was first asserted.\n\t\t/// \n\t\tprivate CopyrightYear_Core copyrightYear;\n\t\tpublic CopyrightYear_Core CopyrightYear\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn copyrightYear;\n\t\t\t}\n\t\t\tset\n\t\t\t{\n\t\t\t\tcopyrightYear = value;\n\t\t\t\tSetPropertyInstance(copyrightYear);\n\t\t\t}\n\t\t}\n\n\t\t/// \n\t\t/// The creator/author of this CreativeWork or UserComments. This is the same as the Author property for CreativeWork.\n\t\t/// \n\t\tprivate Creator_Core creator;\n\t\tpublic Creator_Core Creator\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn creator;\n\t\t\t}\n\t\t\tset\n\t\t\t{\n\t\t\t\tcreator = value;\n\t\t\t\tSetPropertyInstance(creator);\n\t\t\t}\n\t\t}\n\n\t\t/// \n\t\t/// The date on which the CreativeWork was created.\n\t\t/// \n\t\tprivate DateCreated_Core dateCreated;\n\t\tpublic DateCreated_Core DateCreated\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn dateCreated;\n\t\t\t}\n\t\t\tset\n\t\t\t{\n\t\t\t\tdateCreated = value;\n\t\t\t\tSetPropertyInstance(dateCreated);\n\t\t\t}\n\t\t}\n\n\t\t/// \n\t\t/// The date on which the CreativeWork was most recently modified.\n\t\t/// \n\t\tprivate DateModified_Core dateModified;\n\t\tpublic DateModified_Core DateModified\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn dateModified;\n\t\t\t}\n\t\t\tset\n\t\t\t{\n\t\t\t\tdateModified = value;\n\t\t\t\tSetPropertyInstance(dateModified);\n\t\t\t}\n\t\t}\n\n\t\t/// \n\t\t/// Date of first broadcast/publication.\n\t\t/// \n\t\tprivate DatePublished_Core datePublished;\n\t\tpublic DatePublished_Core DatePublished\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn datePublished;\n\t\t\t}\n\t\t\tset\n\t\t\t{\n\t\t\t\tdatePublished = value;\n\t\t\t\tSetPropertyInstance(datePublished);\n\t\t\t}\n\t\t}\n\n\t\t/// \n\t\t/// A short description of the item.\n\t\t/// \n\t\tprivate Description_Core description;\n\t\tpublic Description_Core Description\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn description;\n\t\t\t}\n\t\t\tset\n\t\t\t{\n\t\t\t\tdescription = value;\n\t\t\t\tSetPropertyInstance(description);\n\t\t\t}\n\t\t}\n\n\t\t/// \n\t\t/// A link to the page containing the comments of the CreativeWork.\n\t\t/// \n\t\tprivate DiscussionURL_Core discussionURL;\n\t\tpublic DiscussionURL_Core DiscussionURL\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn discussionURL;\n\t\t\t}\n\t\t\tset\n\t\t\t{\n\t\t\t\tdiscussionURL = value;\n\t\t\t\tSetPropertyInstance(discussionURL);\n\t\t\t}\n\t\t}\n\n\t\t/// \n\t\t/// Specifies the Person who edited the CreativeWork.\n\t\t/// \n\t\tprivate Editor_Core editor;\n\t\tpublic Editor_Core Editor\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn editor;\n\t\t\t}\n\t\t\tset\n\t\t\t{\n\t\t\t\teditor = value;\n\t\t\t\tSetPropertyInstance(editor);\n\t\t\t}\n\t\t}\n\n\t\t/// \n\t\t/// The media objects that encode this creative work\n\t\t/// \n\t\tprivate Encodings_Core encodings;\n\t\tpublic Encodings_Core Encodings\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn encodings;\n\t\t\t}\n\t\t\tset\n\t\t\t{\n\t\t\t\tencodings = value;\n\t\t\t\tSetPropertyInstance(encodings);\n\t\t\t}\n\t\t}\n\n\t\t/// \n\t\t/// Genre of the creative work\n\t\t/// \n\t\tprivate Genre_Core genre;\n\t\tpublic Genre_Core Genre\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn genre;\n\t\t\t}\n\t\t\tset\n\t\t\t{\n\t\t\t\tgenre = value;\n\t\t\t\tSetPropertyInstance(genre);\n\t\t\t}\n\t\t}\n\n\t\t/// \n\t\t/// Headline of the article\n\t\t/// \n\t\tprivate Headline_Core headline;\n\t\tpublic Headline_Core Headline\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn headline;\n\t\t\t}\n\t\t\tset\n\t\t\t{\n\t\t\t\theadline = value;\n\t\t\t\tSetPropertyInstance(headline);\n\t\t\t}\n\t\t}\n\n\t\t/// \n\t\t/// URL of an image of the item.\n\t\t/// \n\t\tprivate Image_Core image;\n\t\tpublic Image_Core Image\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn image;\n\t\t\t}\n\t\t\tset\n\t\t\t{\n\t\t\t\timage = value;\n\t\t\t\tSetPropertyInstance(image);\n\t\t\t}\n\t\t}\n\n\t\t/// \n\t\tprivate InLanguage_Core inLanguage;\n\t\tpublic InLanguage_Core InLanguage\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn inLanguage;\n\t\t\t}\n\t\t\tset\n\t\t\t{\n\t\t\t\tinLanguage = value;\n\t\t\t\tSetPropertyInstance(inLanguage);\n\t\t\t}\n\t\t}\n\n\t\t/// \n\t\t/// A count of a specific user interactions with this item\\u2014for example, 20 UserLikes, 5 UserComments, or 300 UserDownloads. The user interaction type should be one of the sub types of UserInteraction.\n\t\t/// \n\t\tprivate InteractionCount_Core interactionCount;\n\t\tpublic InteractionCount_Core InteractionCount\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn interactionCount;\n\t\t\t}\n\t\t\tset\n\t\t\t{\n\t\t\t\tinteractionCount = value;\n\t\t\t\tSetPropertyInstance(interactionCount);\n\t\t\t}\n\t\t}\n\n\t\t/// \n\t\t/// Indicates whether this content is family friendly.\n\t\t/// \n\t\tprivate IsFamilyFriendly_Core isFamilyFriendly;\n\t\tpublic IsFamilyFriendly_Core IsFamilyFriendly\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn isFamilyFriendly;\n\t\t\t}\n\t\t\tset\n\t\t\t{\n\t\t\t\tisFamilyFriendly = value;\n\t\t\t\tSetPropertyInstance(isFamilyFriendly);\n\t\t\t}\n\t\t}\n\n\t\t/// \n\t\t/// Indicates the collection or gallery to which the item belongs.\n\t\t/// \n\t\tprivate IsPartOf_Core isPartOf;\n\t\tpublic IsPartOf_Core IsPartOf\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn isPartOf;\n\t\t\t}\n\t\t\tset\n\t\t\t{\n\t\t\t\tisPartOf = value;\n\t\t\t\tSetPropertyInstance(isPartOf);\n\t\t\t}\n\t\t}\n\n\t\t/// \n\t\t/// The keywords/tags used to describe this content.\n\t\t/// \n\t\tprivate Keywords_Core keywords;\n\t\tpublic Keywords_Core Keywords\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn keywords;\n\t\t\t}\n\t\t\tset\n\t\t\t{\n\t\t\t\tkeywords = value;\n\t\t\t\tSetPropertyInstance(keywords);\n\t\t\t}\n\t\t}\n\n\t\t/// \n\t\t/// Indicates if this web page element is the main subject of the page.\n\t\t/// \n\t\tprivate MainContentOfPage_Core mainContentOfPage;\n\t\tpublic MainContentOfPage_Core MainContentOfPage\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn mainContentOfPage;\n\t\t\t}\n\t\t\tset\n\t\t\t{\n\t\t\t\tmainContentOfPage = value;\n\t\t\t\tSetPropertyInstance(mainContentOfPage);\n\t\t\t}\n\t\t}\n\n\t\t/// \n\t\t/// Indicates that the CreativeWork contains a reference to, but is not necessarily about a concept.\n\t\t/// \n\t\tprivate Mentions_Core mentions;\n\t\tpublic Mentions_Core Mentions\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn mentions;\n\t\t\t}\n\t\t\tset\n\t\t\t{\n\t\t\t\tmentions = value;\n\t\t\t\tSetPropertyInstance(mentions);\n\t\t\t}\n\t\t}\n\n\t\t/// \n\t\t/// The name of the item.\n\t\t/// \n\t\tprivate Name_Core name;\n\t\tpublic Name_Core Name\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn name;\n\t\t\t}\n\t\t\tset\n\t\t\t{\n\t\t\t\tname = value;\n\t\t\t\tSetPropertyInstance(name);\n\t\t\t}\n\t\t}\n\n\t\t/// \n\t\t/// An offer to sell this item\\u2014for example, an offer to sell a product, the DVD of a movie, or tickets to an event.\n\t\t/// \n\t\tprivate Offers_Core offers;\n\t\tpublic Offers_Core Offers\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn offers;\n\t\t\t}\n\t\t\tset\n\t\t\t{\n\t\t\t\toffers = value;\n\t\t\t\tSetPropertyInstance(offers);\n\t\t\t}\n\t\t}\n\n\t\t/// \n\t\t/// Indicates the main image on the page\n\t\t/// \n\t\tprivate PrimaryImageOfPage_Core primaryImageOfPage;\n\t\tpublic PrimaryImageOfPage_Core PrimaryImageOfPage\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn primaryImageOfPage;\n\t\t\t}\n\t\t\tset\n\t\t\t{\n\t\t\t\tprimaryImageOfPage = value;", "answers": ["\t\t\t\tSetPropertyInstance(primaryImageOfPage);"], "length": 1367, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "5bb6d172-c0e9-47f5-8222-1680a38e09d6", "reasoning": "Each property setter assigns the field and then calls SetPropertyInstance on that field before closing the setter. The current setter for PrimaryImageOfPage ends with assigning primaryImageOfPage = value; so the next line should be the call to SetPropertyInstance(primaryImageOfPage);", "reasoning_model_answer": "SetPropertyInstance(primaryImageOfPage);", "assistant_with_reasoning": "\nEach property setter assigns the field and then calls SetPropertyInstance on that field before closing the setter. The current setter for PrimaryImageOfPage ends with assigning primaryImageOfPage = value; so the next line should be the call to SetPropertyInstance(primaryImageOfPage);\n\nSetPropertyInstance(primaryImageOfPage);", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.065, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 12301, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "SetPropertyInstance(primaryImageOfPage);", "score": 0.95, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "using System;\nusing UnityEngine;\nusing System.Collections;\nusing System.Runtime.InteropServices;\n\nnamespace MMT\n{\n public class MobileMovieTexture : MonoBehaviour\n {\n #region Types\n\n public delegate void OnFinished(MobileMovieTexture sender);\n\n #endregion\n\n #region Editor Variables\n\n /// \n /// File path to the video file, includes the extension, usually .ogg or .ogv\n /// \n#if UNITY_EDITOR\n#if UNITY_3_5 || UNITY_4_0 || UNITY_4_1 || UNITY_4_2 || UNITY_4_3 || UNITY_4_5 || UNITY_4_6\n\t\t[StreamingAssetsLinkAttribute(typeof(MovieTexture), \"Movie\")]\n#else\n [StreamingAssetsLinkAttribute(typeof(UnityEngine.Object), \"Movie\")]\n#endif\n#endif\n\t\t[SerializeField]\n private string m_path;\n\n /// \n /// Material(s) to decode the movie on to, MMT sets up the textures and the texture scale/offset\n /// \n [SerializeField]\n private Material[] m_movieMaterials;\n\n /// \n /// Whether to start playing automatically, be careful to set advance\n /// \n [SerializeField]\n private bool m_playAutomatically = true;\n\n /// \n /// Whether the movie should advance, used to pause, or also to just decode the first frame\n /// \n [SerializeField]\n private bool m_advance = true;\n\n /// \n /// How many times to loop, -1 == infinite\n /// \n [SerializeField]\n private int m_loopCount = -1;\n\n /// \n /// Playback speed, has to be positive, can't play backwards\n /// \n [SerializeField]\n private float m_playSpeed = 1.0f;\n\n /// \n /// Whether to scan the duration of the movie on opening. This makes opening movies more expensive as it reads the whole file. Ideally cache this off if you need it\n /// \n [SerializeField]\n private bool m_scanDuration = true;\n\n /// \n /// When seeking, it tries to find a keyframe to seek to, however it often fails. If this is set, after a seek, it will decode till it hits a keyframe. Without it set, you may see artifacts on a seek\n /// \n [SerializeField]\n private bool m_seekKeyFrame = false;\n\n #endregion\n\n #region Other Variables\n\n private IntPtr m_nativeContext = IntPtr.Zero;\n private IntPtr m_nativeTextureContext = IntPtr.Zero;\n\n private int m_picX = 0;\n private int m_picY = 0;\n\n private int m_yStride = 0;\n private int m_yHeight = 0;\n private int m_uvStride = 0;\n private int m_uvHeight = 0;\n\n private Vector2 m_uvYScale;\n private Vector2 m_uvYOffset;\n \n private Vector2 m_uvCrCbScale;\n private Vector2 m_uvCrCbOffset;\n\n private const int CHANNELS = 3; //Y,Cb,Cr\n private Texture2D[] m_ChannelTextures = new Texture2D[CHANNELS];\n\n private double m_elapsedTime;\n\n private bool m_hasFinished = true;\n\n public MobileMovieTexture()\n {\n Height = 0;\n Width = 0;\n }\n\n #endregion\n\n /// \n /// Function to call on finish\n /// \n public event OnFinished onFinished;\n\n #region Properties\n\n /// \n /// File path to the video file, includes the extension, usually .ogg or .ogv\n /// \n public string Path { get { return m_path; } set { m_path = value; } }\n\n /// \n /// Whether the path is absolute or in the streaming assets directory\n /// \n\t\tpublic bool AbsolutePath { get; set; }\n\n /// \n /// Material to decode the movie on to, MMT sets up the textures and the texture scale/offset\n /// \n public Material[] MovieMaterial { get { return m_movieMaterials; } }\n\n /// \n /// Whether to start playing automatically, be careful to set advance\n /// \n public bool PlayAutomatically { set { m_playAutomatically = value; } }\n\n /// \n /// How many times to loop, -1 == infinite\n /// \n public int LoopCount { get { return m_loopCount; } set { m_loopCount = value; } }\n\n /// \n /// Playback speed, has to be positive, can't play backwards\n /// \n public float PlaySpeed { get { return m_playSpeed; } set { m_playSpeed = value; } }\n\n /// \n /// Whether to scan the duration of the movie on opening. This makes opening movies more expensive as it reads the whole file. Ideally cache this off if you need it\n /// \n public bool ScanDuration { get { return m_scanDuration; } set { m_scanDuration = value; } }\n\n /// \n /// When seeking, it tries to find a keyframe to seek to, however it often fails. If this is set, after a seek, it will decode till it hits a keyframe. Without it set, you may see artifacts on a seek\n /// \n public bool SeekKeyFrame { get { return m_seekKeyFrame; } set { m_seekKeyFrame = value; } }\n\n /// \n /// Width of the movie in pixels\n /// \n public int Width { get; private set; }\n\n /// \n /// Height of the movie in pixels\n /// \n public int Height { get; private set; }\n\n /// \n /// Aspect ratio (width/height) of movie\n /// \n public float AspectRatio\n {\n get\n {\n if (m_nativeContext != IntPtr.Zero)\n {\n return GetAspectRatio(m_nativeContext);\n }\n else\n {\n return 1.0f;\n }\n }\n }\n\n /// \n /// Frames per second of movie\n /// \n public double FPS\n {\n get\n {\n if (m_nativeContext != IntPtr.Zero)\n {\n return GetVideoFPS(m_nativeContext);\n }\n else\n {\n return 1.0;\n }\n }\n }\n\n /// \n /// Is the movie currently playing\n /// \n public bool IsPlaying\n {\n get { return m_nativeContext != IntPtr.Zero && !m_hasFinished && m_advance; }\n }\n\n public bool Pause { get { return !m_advance; } set { m_advance = !value; } }\n\n /// \n /// Use this to retrieve the play position and to seek. NB after you seek, the play position will not be exactly what you seeked to, as it is tries to find a key frame\n /// \n public double PlayPosition\n {\n get { return m_elapsedTime; }\n set \n {\n if (m_nativeContext != IntPtr.Zero)\n {\n m_elapsedTime = Seek(m_nativeContext, value, m_seekKeyFrame);\n }\n }\n }\n\n /// \n /// The length of the movie, this is only valid if you have ScanDuration set\n /// \n public double Duration\n {\n get { return m_nativeContext != IntPtr.Zero ? GetDuration(m_nativeContext) : 0.0; }\n }\n\n #endregion\n\n #region Native Interface\n\n#if UNITY_IPHONE && !UNITY_EDITOR\n private const string PLATFORM_DLL = \"__Internal\";\n#else\n private const string PLATFORM_DLL = \"theorawrapper\";\n#endif\n [DllImport(PLATFORM_DLL)]\n private static extern IntPtr CreateContext();\n\n [DllImport(PLATFORM_DLL)]\n private static extern void DestroyContext(IntPtr context);\n\n [DllImport(PLATFORM_DLL)]\n private static extern bool OpenStream(IntPtr context, string path, int offset, int size, bool pot, bool scanDuration, int maxSkipFrames);\n\n [DllImport(PLATFORM_DLL)]\n private static extern void CloseStream(IntPtr context);\n\n [DllImport(PLATFORM_DLL)]\n private static extern int GetPicWidth(IntPtr context);\n\n [DllImport(PLATFORM_DLL)]\n private static extern int GetPicHeight(IntPtr context);\n\n [DllImport(PLATFORM_DLL)]\n private static extern int GetPicX(IntPtr context);\n\n [DllImport(PLATFORM_DLL)]\n private static extern int GetPicY(IntPtr context);\n\n [DllImport(PLATFORM_DLL)]\n private static extern int GetYStride(IntPtr context);\n\n [DllImport(PLATFORM_DLL)]\n private static extern int GetYHeight(IntPtr context);\n\n [DllImport(PLATFORM_DLL)]\n private static extern int GetUVStride(IntPtr context);\n\n [DllImport(PLATFORM_DLL)]\n private static extern int GetUVHeight(IntPtr context);\n\n [DllImport(PLATFORM_DLL)]\n private static extern bool HasFinished(IntPtr context);\n\n [DllImport(PLATFORM_DLL)]\n private static extern double GetDecodedFrameTime(IntPtr context);\n\n\t\t[DllImport(PLATFORM_DLL)]\n\t\tprivate static extern double GetUploadedFrameTime(IntPtr context);\n\n\t\t[DllImport(PLATFORM_DLL)]\n\t\tprivate static extern double GetTargetDecodeFrameTime(IntPtr context);\n \n [DllImport(PLATFORM_DLL)]\n private static extern void SetTargetDisplayDecodeTime(IntPtr context, double targetTime);\n\n [DllImport(PLATFORM_DLL)]\n private static extern double GetVideoFPS(IntPtr context);\n\n [DllImport(PLATFORM_DLL)]\n private static extern float GetAspectRatio(IntPtr context);\n\n [DllImport(PLATFORM_DLL)]\n private static extern double Seek(IntPtr context, double seconds, bool waitKeyFrame);\n\n [DllImport(PLATFORM_DLL)]\n private static extern double GetDuration(IntPtr context);\n\n [DllImport(PLATFORM_DLL)]\n private static extern IntPtr GetNativeHandle(IntPtr context, int planeIndex);\n\n [DllImport(PLATFORM_DLL)]\n private static extern IntPtr GetNativeTextureContext(IntPtr context);\n\n [DllImport(PLATFORM_DLL)]\n private static extern void SetPostProcessingLevel(IntPtr context, int level);\n\n #endregion\n\n #region Behaviour Overrides\n\n void Start()\n {\n m_nativeContext = CreateContext();\n\n if (m_nativeContext == IntPtr.Zero)\n {\n Debug.LogError(\"Unable to create Mobile Movie Texture native context\");\n return;\n }\n\n if (m_playAutomatically)\n {\n Play();\n }\n }\n\n void OnDestroy()\n {\n DestroyTextures();\n DestroyContext(m_nativeContext);\n }\n\n void Update()\n {\n if (m_nativeContext != IntPtr.Zero && !m_hasFinished)\n {\n //Texture context can change when resizing windows\n //when put into the background etc\n var textureContext = GetNativeTextureContext(m_nativeContext);\n\n if (textureContext != m_nativeTextureContext)\n {\n DestroyTextures();\n AllocateTexures();\n\n m_nativeTextureContext = textureContext;\n }\n\n m_hasFinished = HasFinished(m_nativeContext);\n\n if (!m_hasFinished)\n {\n if (m_advance)\n {\n m_elapsedTime += Time.deltaTime * Mathf.Max(m_playSpeed, 0.0f);\n }\n }\n else\n {\n if ((m_loopCount - 1) > 0 || m_loopCount == -1)\n {\n if (m_loopCount != -1)\n {\n m_loopCount--;\n }\n\n m_elapsedTime = m_elapsedTime % GetDecodedFrameTime(m_nativeContext);\n\n Seek(m_nativeContext, 0, false);\n\n m_hasFinished = false;\n }\n else if (onFinished != null)\n {\n\t\t\t\t\t\tm_elapsedTime = GetDecodedFrameTime(m_nativeContext);\n\n onFinished(this);\n }\n\n }\n\n SetTargetDisplayDecodeTime(m_nativeContext, m_elapsedTime);\n\n }\n }\n\n\n #endregion\n\n #region Methods\n\n public void Play()\n {\n m_elapsedTime = 0.0;\n\n Open();\n\n m_hasFinished = false;\n\n //Create a manager if we don't have one\n if (MobileMovieManager.Instance == null)\n {\n gameObject.AddComponent();\n }\n }\n\n public void Stop()\n {\n CloseStream(m_nativeContext);\n\t\t\tm_hasFinished = true;\n }\n\n private void Open()\n {\n string path = m_path;\n long offset = 0;\n long length = 0;\n\n if (!AbsolutePath)\n {\n switch (Application.platform)\n {\n case RuntimePlatform.Android:\n path = Application.dataPath;\n\n if (!AssetStream.GetZipFileOffsetLength(Application.dataPath, m_path, out offset, out length))\n {\n return;\n }\n break;\n default:\n path = Application.streamingAssetsPath + \"/\" + m_path;\n break;\n }\n }\n\n\n //No platform should need power of 2 textures anymore\n const bool powerOf2Textures = false;\n\n //This is maximum frames decoded before a frame is uploaded\n const int maxSkipFrames = 16;\n\n if (m_nativeContext != IntPtr.Zero && OpenStream(m_nativeContext, path, (int)offset, (int)length, powerOf2Textures, m_scanDuration, maxSkipFrames))\n {\n Width = GetPicWidth(m_nativeContext);\n Height = GetPicHeight(m_nativeContext);\n", "answers": [" m_picX = GetPicX(m_nativeContext);"], "length": 1398, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "111c9ec8-8d62-455f-ae08-6904928eb5b6", "reasoning": "After opening the native stream, the code sets Width and Height using GetPicWidth/Height. The next logical step is to retrieve the picture offset X coordinate from the native context, stored in the m_picX field. This follows the pattern of initializing other related fields (picY, strides, etc.) after Width/Height.", "reasoning_model_answer": "m_picX = GetPicX(m_nativeContext);", "assistant_with_reasoning": "\nAfter opening the native stream, the code sets Width and Height using GetPicWidth/Height. The next logical step is to retrieve the picture offset X coordinate from the native context, stored in the m_picX field. This follows the pattern of initializing other related fields (picY, strides, etc.) after Width/Height.\n\nm_picX = GetPicX(m_nativeContext);", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.724, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 14354, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "m_picX = GetPicX(m_nativeContext);", "score": 0.81, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "// Copyright 2010 The Noda Time Authors. All rights reserved.\n// Use of this source code is governed by the Apache License 2.0,\n// as found in the LICENSE.txt file.\n\nusing System;\nusing System.IO;\nusing NUnit.Framework;\n\nnamespace NodaTime.Test.TimeZones.IO\n{\n /// \n /// Provides a simple, fized-size, pipe-like stream that has a writer and a reader.\n /// \n /// \n /// When the buffer fills up an exception is thrown and currently the buffer is fixed at 4096. The write\n /// pointer does not wrap so only a total of 4096 bytes can ever be written to the stream. This is designed\n /// for testing purposes and not real-world uses.\n /// \n internal class IoStream\n {\n private readonly byte[] buffer = new byte[4096];\n private int readIndex;\n private Stream? readStream;\n private int writeIndex;\n private Stream? writeStream;\n\n /// \n /// Returns the next byte from the stream if there is one.\n /// \n /// The next byte.\n /// There are no more bytes in the buffer.\n private byte GetByte()\n {\n if (readIndex >= writeIndex)\n {\n throw new IOException(\"IoStream buffer empty in GetByte()\");\n }\n return buffer[readIndex++];\n }\n\n public void AssertEndOfStream()\n {\n Assert.AreEqual(readIndex, writeIndex);\n }\n\n public void AssertUnreadContents(byte[] expected)\n {\n Assert.AreEqual(expected.Length, writeIndex - readIndex);\n var actual = new byte[expected.Length];\n Array.Copy(buffer, readIndex, actual, 0, writeIndex - readIndex);\n Assert.AreEqual(expected, actual);\n readIndex = writeIndex;\n }\n\n /// \n /// Returns a that can be used to read from the buffer.\n /// \n /// \n /// This can only be called once for each instance i.e. only one reader is permitted per buffer.\n /// \n /// The read-only .\n /// A reader was already requested.\n public Stream GetReadStream()\n {\n if (readStream != null)\n {\n throw new InvalidOperationException(\"Cannot call GetReadStream() twice on the same object.\");\n }\n readStream = new ReadStreamImpl(this);\n return readStream;\n }\n\n /// \n /// Returns a that can be used to write to the buffer.\n /// \n /// \n /// This can only be called once for each instance i.e. only one writer is permitted per buffer.\n /// \n /// The write-only .\n /// A writer was already requested.\n public Stream GetWriteStream()\n {\n if (writeStream != null)\n {\n throw new InvalidOperationException(\"Cannot call GetWriteStream() twice on the same object.\");\n }\n writeStream = new WriteStreamImpl(this);\n return writeStream;\n }\n\n /// \n /// Adds a byte to the buffer.\n /// \n /// The byte to add.\n /// The buffer has been filled.\n private void PutByte(byte value)\n {\n if (writeIndex >= buffer.Length)\n {\n throw new IOException(\"Exceeded the IoStream buffer size of \" + buffer.Length);\n }\n buffer[writeIndex++] = value;\n }\n\n /// \n /// Resets the stream to be empty.\n /// \n internal void Reset()\n {\n writeIndex = 0;\n readIndex = 0;\n }\n\n #region Nested type: ReadStreamImpl\n /// \n /// Provides a read-only implementaion for reading from the buffer.\n /// \n private class ReadStreamImpl : Stream\n {\n private readonly IoStream ioStream;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The to read from.\n public ReadStreamImpl(IoStream stream)\n {\n ioStream = stream;\n }\n\n /// \n /// When overridden in a derived class, gets a value indicating whether the current stream supports reading.\n /// \n /// \n /// true if the stream supports reading; otherwise, false.\n /// \n /// 1\n public override bool CanRead => true;\n\n /// \n /// When overridden in a derived class, gets a value indicating whether the current stream supports seeking.\n /// \n /// \n /// true if the stream supports seeking; otherwise, false.\n /// \n /// 1\n public override bool CanSeek => false;\n\n /// \n /// When overridden in a derived class, gets a value indicating whether the current stream supports writing.\n /// \n /// \n /// true if the stream supports writing; otherwise, false.\n /// \n /// 1\n public override bool CanWrite => false;\n\n /// \n /// When overridden in a derived class, gets the length in bytes of the stream.\n /// \n /// \n /// A long value representing the length of the stream in bytes.\n /// \n /// A class derived from Stream does not support seeking. \n /// \n /// Methods were called after the stream was closed. \n /// \n /// 1\n public override long Length\n {\n get { throw new NotSupportedException(); }\n }\n\n /// \n /// When overridden in a derived class, gets or sets the position within the current stream.\n /// \n /// \n /// The current position within the stream.\n /// \n /// An I/O error occurs. \n /// \n /// The stream does not support seeking. \n /// \n /// Methods were called after the stream was closed. \n /// \n /// 1\n public override long Position\n {\n get { throw new NotSupportedException(); }\n set { throw new NotSupportedException(); }\n }\n\n /// \n /// When overridden in a derived class, clears all buffers for this stream and causes any buffered data to be written to the underlying device.\n /// \n /// An I/O error occurs. \n /// \n /// 2\n public override void Flush()\n {\n }\n\n /// \n /// When overridden in a derived class, reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read.\n /// \n /// \n /// The total number of bytes read into the buffer. This can be less than the number of bytes requested if that many bytes are not currently available, or zero (0) if the end of the stream has been reached.\n /// \n /// An array of bytes. When this method returns, the buffer contains the specified byte array with the values between and ( + - 1) replaced by the bytes read from the current source. \n /// \n /// The zero-based byte offset in at which to begin storing the data read from the current stream. \n /// \n /// The maximum number of bytes to be read from the current stream. \n /// \n /// The sum of and is larger than the buffer length. \n /// \n /// is null. \n /// \n /// or is negative. \n /// \n /// An I/O error occurs. \n /// \n /// The stream does not support reading. \n /// \n /// Methods were called after the stream was closed. \n /// \n /// 1\n public override int Read(byte[] buffer, int offset, int count)\n {\n count = Math.Min(count, ioStream.writeIndex - ioStream.readIndex);\n for (int i = 0; i < count; i++)\n {\n buffer[i + offset] = ioStream.GetByte();\n }\n return count;\n }\n\n /// \n /// When overridden in a derived class, sets the position within the current stream.\n /// \n /// \n /// The new position within the current stream.\n /// \n /// A byte offset relative to the parameter. \n /// \n /// A value of type indicating the reference point used to obtain the new position. \n /// \n /// An I/O error occurs. \n /// \n /// The stream does not support seeking, such as if the stream is constructed from a pipe or console output. \n /// \n /// Methods were called after the stream was closed. \n /// \n /// 1\n public override long Seek(long offset, SeekOrigin origin)\n {\n throw new NotSupportedException();\n }\n\n /// \n /// When overridden in a derived class, sets the length of the current stream.\n /// \n /// The desired length of the current stream in bytes. \n /// \n /// An I/O error occurs. \n /// \n /// The stream does not support both writing and seeking, such as if the stream is constructed from a pipe or console output. \n /// \n /// Methods were called after the stream was closed. \n /// \n /// 2\n public override void SetLength(long value)\n {\n throw new NotSupportedException();\n }\n\n /// \n /// When overridden in a derived class, writes a sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written.\n /// \n /// An array of bytes. This method copies bytes from to the current stream. \n /// \n /// The zero-based byte offset in at which to begin copying bytes to the current stream. \n /// \n /// The number of bytes to be written to the current stream. \n /// \n /// The sum of and is greater than the buffer length. \n /// \n /// is null. \n /// \n /// or is negative. \n /// \n /// An I/O error occurs. \n /// \n /// The stream does not support writing. \n /// \n /// Methods were called after the stream was closed. \n /// \n /// 1\n public override void Write(byte[] buffer, int offset, int count)\n {\n throw new NotSupportedException();\n }\n }\n #endregion\n\n #region Nested type: WriteStreamImpl\n /// \n /// Provides a write-only implementaion for writing to the buffer.\n /// \n private class WriteStreamImpl : Stream\n {\n private readonly IoStream ioStream;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The to read from.\n public WriteStreamImpl(IoStream stream)\n {\n ioStream = stream;\n }\n\n /// \n /// When overridden in a derived class, gets a value indicating whether the current stream supports reading.\n /// \n /// \n /// true if the stream supports reading; otherwise, false.\n /// \n /// 1", "answers": [" public override bool CanRead => false;"], "length": 1647, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "2347de3b-29a1-4e6a-a7bf-001ff9ba3fb4", "reasoning": "Within the WriteStreamImpl class, after the XML comment describing the CanRead property, the next line should implement that property. Since this stream is write‑only, CanRead must return false. The pattern follows the ReadStreamImpl implementation, so the line is the override returning false.", "reasoning_model_answer": "public override bool CanRead => false;", "assistant_with_reasoning": "\nWithin the WriteStreamImpl class, after the XML comment describing the CanRead property, the next line should implement that property. Since this stream is write‑only, CanRead must return false. The pattern follows the ReadStreamImpl implementation, so the line is the override returning false.\n\npublic override bool CanRead => false;", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 2.203, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 15666, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "public override bool CanRead => false;", "score": 0.86, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "# Copyright 2010 Jacob Kaplan-Moss\n# Copyright 2011 OpenStack Foundation\n# All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\n\"\"\"\nCommand-line interface to the OpenStack Nova API.\n\"\"\"\n\nfrom __future__ import print_function\nimport argparse\nimport getpass\nimport glob\nimport imp\nimport itertools\nimport logging\nimport os\nimport pkgutil\nimport sys\n\nfrom keystoneclient.auth.identity.generic import password\nfrom keystoneclient.auth.identity.generic import token\nfrom keystoneclient.auth.identity import v3 as identity\nfrom keystoneclient import session as ksession\nfrom oslo_utils import encodeutils\nfrom oslo_utils import strutils\nimport pkg_resources\nimport six\n\nHAS_KEYRING = False\nall_errors = ValueError\ntry:\n import keyring\n HAS_KEYRING = True\nexcept ImportError:\n pass\n\nimport novaclient\nimport novaclient.auth_plugin\nfrom novaclient import client\nfrom novaclient import exceptions as exc\nimport novaclient.extension\nfrom novaclient.openstack.common import cliutils\nfrom novaclient.openstack.common.gettextutils import _\nfrom novaclient import utils\nfrom novaclient.v1_1 import shell as shell_v1_1\nfrom novaclient.v3 import shell as shell_v3\n\nDEFAULT_OS_COMPUTE_API_VERSION = \"1.1\"\nDEFAULT_NOVA_ENDPOINT_TYPE = 'publicURL'\n# NOTE(cyeoh): Having the service type dependent on the API version\n# is pretty ugly, but we have to do this because traditionally the\n# catalog entry for compute points directly to the V2 API rather than\n# the root, and then doing version discovery.\nDEFAULT_NOVA_SERVICE_TYPE_MAP = {'1.1': 'compute',\n '2': 'compute',\n '3': 'computev3'}\n\nlogger = logging.getLogger(__name__)\n\n\ndef positive_non_zero_float(text):\n if text is None:\n return None\n try:\n value = float(text)\n except ValueError:\n msg = _(\"%s must be a float\") % text\n raise argparse.ArgumentTypeError(msg)\n if value <= 0:\n msg = _(\"%s must be greater than 0\") % text\n raise argparse.ArgumentTypeError(msg)\n return value\n\n\nclass SecretsHelper(object):\n def __init__(self, args, client):\n self.args = args\n self.client = client\n self.key = None\n self._password = None\n\n def _validate_string(self, text):\n if text is None or len(text) == 0:\n return False\n return True\n\n def _make_key(self):\n if self.key is not None:\n return self.key\n keys = [\n self.client.auth_url,\n self.client.projectid,\n self.client.user,\n self.client.region_name,\n self.client.endpoint_type,\n self.client.service_type,\n self.client.service_name,\n self.client.volume_service_name,\n ]\n for (index, key) in enumerate(keys):\n if key is None:\n keys[index] = '?'\n else:\n keys[index] = str(keys[index])\n self.key = \"/\".join(keys)\n return self.key\n\n def _prompt_password(self, verify=True):\n pw = None\n if hasattr(sys.stdin, 'isatty') and sys.stdin.isatty():\n # Check for Ctl-D\n try:\n while True:\n pw1 = getpass.getpass('OS Password: ')\n if verify:\n pw2 = getpass.getpass('Please verify: ')\n else:\n pw2 = pw1\n if pw1 == pw2 and self._validate_string(pw1):\n pw = pw1\n break\n except EOFError:\n pass\n return pw\n\n def save(self, auth_token, management_url, tenant_id):\n if not HAS_KEYRING or not self.args.os_cache:\n return\n if (auth_token == self.auth_token and\n management_url == self.management_url):\n # Nothing changed....\n return\n if not all([management_url, auth_token, tenant_id]):\n raise ValueError(_(\"Unable to save empty management url/auth \"\n \"token\"))\n value = \"|\".join([str(auth_token),\n str(management_url),\n str(tenant_id)])\n keyring.set_password(\"novaclient_auth\", self._make_key(), value)\n\n @property\n def password(self):\n # Cache password so we prompt user at most once\n if self._password:\n pass\n elif self._validate_string(self.args.os_password):\n self._password = self.args.os_password\n else:\n verify_pass = strutils.bool_from_string(\n utils.env(\"OS_VERIFY_PASSWORD\", default=False), True)\n self._password = self._prompt_password(verify_pass)\n if not self._password:\n raise exc.CommandError(\n 'Expecting a password provided via either '\n '--os-password, env[OS_PASSWORD], or '\n 'prompted response')\n return self._password\n\n @property\n def management_url(self):\n if not HAS_KEYRING or not self.args.os_cache:\n return None\n management_url = None\n try:\n block = keyring.get_password('novaclient_auth', self._make_key())\n if block:\n _token, management_url, _tenant_id = block.split('|', 2)\n except all_errors:\n pass\n return management_url\n\n @property\n def auth_token(self):\n # Now is where it gets complicated since we\n # want to look into the keyring module, if it\n # exists and see if anything was provided in that\n # file that we can use.\n if not HAS_KEYRING or not self.args.os_cache:\n return None\n token = None\n try:\n block = keyring.get_password('novaclient_auth', self._make_key())\n if block:\n token, _management_url, _tenant_id = block.split('|', 2)\n except all_errors:\n pass\n return token\n\n @property\n def tenant_id(self):\n if not HAS_KEYRING or not self.args.os_cache:\n return None\n tenant_id = None\n try:\n block = keyring.get_password('novaclient_auth', self._make_key())\n if block:\n _token, _management_url, tenant_id = block.split('|', 2)\n except all_errors:\n pass\n return tenant_id\n\n\nclass NovaClientArgumentParser(argparse.ArgumentParser):\n\n def __init__(self, *args, **kwargs):\n super(NovaClientArgumentParser, self).__init__(*args, **kwargs)\n\n def error(self, message):\n \"\"\"error(message: string)\n\n Prints a usage message incorporating the message to stderr and\n exits.\n \"\"\"\n self.print_usage(sys.stderr)\n # FIXME(lzyeval): if changes occur in argparse.ArgParser._check_value\n choose_from = ' (choose from'\n progparts = self.prog.partition(' ')\n self.exit(2, _(\"error: %(errmsg)s\\nTry '%(mainp)s help %(subp)s'\"\n \" for more information.\\n\") %\n {'errmsg': message.split(choose_from)[0],\n 'mainp': progparts[0],\n 'subp': progparts[2]})\n\n\nclass OpenStackComputeShell(object):\n\n def get_base_parser(self):\n parser = NovaClientArgumentParser(\n prog='nova',\n description=__doc__.strip(),\n epilog='See \"nova help COMMAND\" '\n 'for help on a specific command.',\n add_help=False,\n formatter_class=OpenStackHelpFormatter,\n )\n\n # Global arguments\n parser.add_argument('-h', '--help',\n action='store_true',\n help=argparse.SUPPRESS,\n )\n\n parser.add_argument('--version',\n action='version',\n version=novaclient.__version__)\n\n parser.add_argument('--debug',\n default=False,\n action='store_true',\n help=_(\"Print debugging output\"))\n\n parser.add_argument('--os-cache',\n default=strutils.bool_from_string(\n utils.env('OS_CACHE', default=False), True),\n action='store_true',\n help=_(\"Use the auth token cache. Defaults to False if \"\n \"env[OS_CACHE] is not set.\"))\n\n parser.add_argument('--timings',\n default=False,\n action='store_true',\n help=_(\"Print call timing info\"))\n\n parser.add_argument('--timeout',\n default=600,\n metavar='',\n type=positive_non_zero_float,\n help=_(\"Set HTTP call timeout (in seconds)\"))\n\n parser.add_argument('--os-auth-token',\n default=utils.env('OS_AUTH_TOKEN'),\n help='Defaults to env[OS_AUTH_TOKEN]')\n\n parser.add_argument('--os-username',\n metavar='',\n default=utils.env('OS_USERNAME', 'NOVA_USERNAME'),\n help=_('Defaults to env[OS_USERNAME].'))\n parser.add_argument('--os_username',\n help=argparse.SUPPRESS)\n\n parser.add_argument('--os-user-id',\n metavar='',\n default=utils.env('OS_USER_ID'),\n help=_('Defaults to env[OS_USER_ID].'))\n\n parser.add_argument('--os-password',\n metavar='',\n default=utils.env('OS_PASSWORD', 'NOVA_PASSWORD'),\n help=_('Defaults to env[OS_PASSWORD].'))\n parser.add_argument('--os_password',\n help=argparse.SUPPRESS)\n\n parser.add_argument('--os-tenant-name',\n metavar='',\n default=utils.env('OS_TENANT_NAME', 'NOVA_PROJECT_ID'),\n help=_('Defaults to env[OS_TENANT_NAME].'))\n parser.add_argument('--os_tenant_name',\n help=argparse.SUPPRESS)\n\n parser.add_argument('--os-tenant-id',\n metavar='',\n default=utils.env('OS_TENANT_ID'),\n help=_('Defaults to env[OS_TENANT_ID].'))\n\n parser.add_argument('--os-auth-url',\n metavar='',\n default=utils.env('OS_AUTH_URL', 'NOVA_URL'),\n help=_('Defaults to env[OS_AUTH_URL].'))\n parser.add_argument('--os_auth_url',\n help=argparse.SUPPRESS)\n\n parser.add_argument('--os-region-name',\n metavar='',\n default=utils.env('OS_REGION_NAME', 'NOVA_REGION_NAME'),\n help=_('Defaults to env[OS_REGION_NAME].'))\n parser.add_argument('--os_region_name',\n help=argparse.SUPPRESS)\n\n parser.add_argument('--os-auth-system',\n metavar='',\n default=utils.env('OS_AUTH_SYSTEM'),\n help='Defaults to env[OS_AUTH_SYSTEM].')\n parser.add_argument('--os_auth_system',\n help=argparse.SUPPRESS)\n\n parser.add_argument('--service-type',\n metavar='',\n help=_('Defaults to compute for most actions'))\n parser.add_argument('--service_type',\n help=argparse.SUPPRESS)\n\n parser.add_argument('--service-name',\n metavar='',\n default=utils.env('NOVA_SERVICE_NAME'),\n help=_('Defaults to env[NOVA_SERVICE_NAME]'))\n parser.add_argument('--service_name',\n help=argparse.SUPPRESS)\n\n parser.add_argument('--volume-service-name',\n metavar='',\n default=utils.env('NOVA_VOLUME_SERVICE_NAME'),\n help=_('Defaults to env[NOVA_VOLUME_SERVICE_NAME]'))\n parser.add_argument('--volume_service_name',\n help=argparse.SUPPRESS)\n\n parser.add_argument('--endpoint-type',\n metavar='',\n default=utils.env('NOVA_ENDPOINT_TYPE',\n default=DEFAULT_NOVA_ENDPOINT_TYPE),\n help=_('Defaults to env[NOVA_ENDPOINT_TYPE] or ')\n + DEFAULT_NOVA_ENDPOINT_TYPE + '.')\n # NOTE(dtroyer): We can't add --endpoint_type here due to argparse\n # thinking usage-list --end is ambiguous; but it\n # works fine with only --endpoint-type present\n # Go figure. I'm leaving this here for doc purposes.\n # parser.add_argument('--endpoint_type',\n # help=argparse.SUPPRESS)\n\n parser.add_argument('--os-compute-api-version',\n metavar='',\n default=utils.env('OS_COMPUTE_API_VERSION',\n default=DEFAULT_OS_COMPUTE_API_VERSION),\n help=_('Accepts 1.1 or 3, '\n 'defaults to env[OS_COMPUTE_API_VERSION].'))\n parser.add_argument('--os_compute_api_version',\n help=argparse.SUPPRESS)\n\n parser.add_argument('--os-cacert',\n metavar='',\n default=utils.env('OS_CACERT', default=None),\n help='Specify a CA bundle file to use in '\n 'verifying a TLS (https) server certificate. '\n 'Defaults to env[OS_CACERT]')\n\n parser.add_argument('--insecure',\n default=utils.env('NOVACLIENT_INSECURE', default=False),\n action='store_true',\n help=_(\"Explicitly allow novaclient to perform \\\"insecure\\\" \"\n \"SSL (https) requests. The server's certificate will \"\n \"not be verified against any certificate authorities. \"\n \"This option should be used with caution.\"))\n\n parser.add_argument('--bypass-url',\n metavar='',\n dest='bypass_url',\n default=utils.env('NOVACLIENT_BYPASS_URL'),\n help=\"Use this API endpoint instead of the Service Catalog. \"\n \"Defaults to env[NOVACLIENT_BYPASS_URL]\")\n parser.add_argument('--bypass_url',\n help=argparse.SUPPRESS)\n\n # The auth-system-plugins might require some extra options\n novaclient.auth_plugin.load_auth_system_opts(parser)\n\n return parser\n\n def get_subcommand_parser(self, version):\n parser = self.get_base_parser()\n\n self.subcommands = {}\n subparsers = parser.add_subparsers(metavar='')\n\n try:\n actions_module = {\n '1.1': shell_v1_1,\n '2': shell_v1_1,\n '3': shell_v3,\n }[version]\n except KeyError:\n actions_module = shell_v1_1\n\n self._find_actions(subparsers, actions_module)\n self._find_actions(subparsers, self)\n\n for extension in self.extensions:\n self._find_actions(subparsers, extension.module)\n\n self._add_bash_completion_subparser(subparsers)\n\n return parser\n\n def _discover_extensions(self, version):\n extensions = []\n for name, module in itertools.chain(\n self._discover_via_python_path(),\n self._discover_via_contrib_path(version),\n self._discover_via_entry_points()):\n\n extension = novaclient.extension.Extension(name, module)\n extensions.append(extension)\n\n return extensions\n\n def _discover_via_python_path(self):\n for (module_loader, name, _ispkg) in pkgutil.iter_modules():\n if name.endswith('_python_novaclient_ext'):\n if not hasattr(module_loader, 'load_module'):\n # Python 2.6 compat: actually get an ImpImporter obj\n module_loader = module_loader.find_module(name)\n\n module = module_loader.load_module(name)\n if hasattr(module, 'extension_name'):\n name = module.extension_name\n\n yield name, module\n\n def _discover_via_contrib_path(self, version):\n module_path = os.path.dirname(os.path.abspath(__file__))\n version_str = \"v%s\" % version.replace('.', '_')\n ext_path = os.path.join(module_path, version_str, 'contrib')\n ext_glob = os.path.join(ext_path, \"*.py\")\n\n for ext_path in glob.iglob(ext_glob):\n name = os.path.basename(ext_path)[:-3]\n\n if name == \"__init__\":\n continue\n\n module = imp.load_source(name, ext_path)\n yield name, module\n\n def _discover_via_entry_points(self):\n for ep in pkg_resources.iter_entry_points('novaclient.extension'):\n name = ep.name\n module = ep.load()\n\n yield name, module\n\n def _add_bash_completion_subparser(self, subparsers):\n subparser = subparsers.add_parser('bash_completion',\n add_help=False,\n formatter_class=OpenStackHelpFormatter\n )\n self.subcommands['bash_completion'] = subparser\n subparser.set_defaults(func=self.do_bash_completion)\n\n def _find_actions(self, subparsers, actions_module):\n for attr in (a for a in dir(actions_module) if a.startswith('do_')):\n # I prefer to be hyphen-separated instead of underscores.\n command = attr[3:].replace('_', '-')\n callback = getattr(actions_module, attr)\n desc = callback.__doc__ or ''\n action_help = desc.strip()\n arguments = getattr(callback, 'arguments', [])\n\n subparser = subparsers.add_parser(command,\n help=action_help,\n description=desc,\n add_help=False,\n formatter_class=OpenStackHelpFormatter\n )\n subparser.add_argument('-h', '--help',\n action='help',\n help=argparse.SUPPRESS,\n )\n self.subcommands[command] = subparser\n for (args, kwargs) in arguments:\n subparser.add_argument(*args, **kwargs)\n subparser.set_defaults(func=callback)\n\n def setup_debugging(self, debug):\n if not debug:\n return\n\n streamformat = \"%(levelname)s (%(module)s:%(lineno)d) %(message)s\"\n # Set up the root logger to debug so that the submodules can\n # print debug messages\n logging.basicConfig(level=logging.DEBUG,\n format=streamformat)\n\n def main(self, argv):\n # Parse args once to find version and debug settings\n parser = self.get_base_parser()\n (options, args) = parser.parse_known_args(argv)\n self.setup_debugging(options.debug)\n\n # Discover available auth plugins\n novaclient.auth_plugin.discover_auth_systems()\n\n # build available subcommands based on version\n self.extensions = self._discover_extensions(\n options.os_compute_api_version)\n self._run_extension_hooks('__pre_parse_args__')\n\n # NOTE(dtroyer): Hackery to handle --endpoint_type due to argparse\n # thinking usage-list --end is ambiguous; but it\n # works fine with only --endpoint-type present\n # Go figure.\n if '--endpoint_type' in argv:\n spot = argv.index('--endpoint_type')\n argv[spot] = '--endpoint-type'\n\n subcommand_parser = self.get_subcommand_parser(\n options.os_compute_api_version)\n self.parser = subcommand_parser\n\n if options.help or not argv:\n subcommand_parser.print_help()\n return 0\n\n args = subcommand_parser.parse_args(argv)\n self._run_extension_hooks('__post_parse_args__', args)\n\n # Short-circuit and deal with help right away.\n if args.func == self.do_help:\n self.do_help(args)\n return 0\n elif args.func == self.do_bash_completion:\n self.do_bash_completion(args)\n return 0\n\n os_username = args.os_username\n os_user_id = args.os_user_id\n os_password = None # Fetched and set later as needed\n os_tenant_name = args.os_tenant_name", "answers": [" os_tenant_id = args.os_tenant_id"], "length": 1474, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "f7d5f354-fa4a-42b1-96e2-4acb64b76dc0", "reasoning": "The code is initializing variables from parsed arguments before creating the client. It has already assigned os_username, os_user_id, os_password, and os_tenant_name. The logical next step is to assign the tenant ID from the parsed arguments, following the same pattern.", "reasoning_model_answer": "os_tenant_id = args.os_tenant_id", "assistant_with_reasoning": "\nThe code is initializing variables from parsed arguments before creating the client. It has already assigned os_username, os_user_id, os_password, and os_tenant_name. The logical next step is to assign the tenant ID from the parsed arguments, following the same pattern.\n\nos_tenant_id = args.os_tenant_id", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 2.432, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 20533, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "os_tenant_id = args.os_tenant_id", "score": 0.89, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "# Software License Agreement (BSD License)\n#\n# Copyright (c) 2013, Open Source Robotics Foundation, Inc.\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions\n# are met:\n#\n# * Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n# * Redistributions in binary form must reproduce the above\n# copyright notice, this list of conditions and the following\n# disclaimer in the documentation and/or other materials provided\n# with the distribution.\n# * Neither the name of Open Source Robotics Foundation, Inc. nor\n# the names of its contributors may be used to endorse or promote\n# products derived from this software without specific prior\n# written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.\n\n'''\nProcesses ROS changelogs so that they can be used in binary packaging.\n\nThe Changelog format is described in REP-0132:\n\nhttp://ros.org/reps/rep-0132.html\n'''\n\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nimport sys\n_py3 = sys.version_info[0] >= 3\n\nimport dateutil.parser\nimport docutils\nimport docutils.core\nimport logging\nimport os\nimport pkg_resources\nimport re\n\ntry:\n _unicode = unicode\nexcept NameError:\n _unicode = str\n\n__author__ = \"William Woodall\"\n__email__ = \"william@osrfoundation.org\"\n__maintainer__ = \"William Woodall\"\n\nlog = logging.getLogger('changelog')\n\nCHANGELOG_FILENAME = 'CHANGELOG.rst'\n\nexample_rst = \"\"\"\\\n^^^^^^^^^^^^^^^^^^^^^^^^^\nChangelog for package foo\n^^^^^^^^^^^^^^^^^^^^^^^^^\n\n0.1\n===\nFree form text about this minor release.\n\n0.1.27 (forthcoming)\n--------------------\n* Great new feature\n\n0.1.26 (2012-12-26)\n-------------------\n* Utilizes caching to improve query performance (fix https://github.com/ros/ros_comm/pull/2)\n* Simplified API calls based on (https://github.com/ros/robot_model):\n\n * Note that these changes are based on REP 192\n * Also they fix a problem related to initialization\n\n* Fixed synchronization issue on startup\n\n.. not mentioning secret feature on purpose\n\n0.1.25 (2012-11-25)\n-------------------\n\n- Added thread safety\n- Replaced custom XML parser with `TinyXML `_.\n- Fixed regression introduced in 0.1.22\n- New syntax for foo::\n\n foo('bar')\n\n- Added a safety check for XML parsing\n\n----\n\nThe library should now compile under ``Win32``\n\n0.1.0 (2012-10-01)\n------------------\n\n*First* public **stable** release\n\n0.0\n===\n\n0.0.1 (2012-01-31)\n------------------\n\n1. Initial release\n2. Initial bugs\n\"\"\"\n\n\ndef bullet_list_class_from_docutils(bullet_list, bullet_type=None):\n '''\n Processes elements of bullet list into an encapsulating class\n\n :param bullet_list: ``docutils.nodes.bullet_list`` list to be processed\n :param bullet_type: ``str`` either 'bullet' or 'enumerated'\n :returns: ``BulletList`` object representing a docutils bullet_list\n '''\n content = BulletList(bullet_type=bullet_type)\n for child in bullet_list.children:\n if isinstance(child, docutils.nodes.list_item):\n content.bullets.append(mixed_text_from_docutils(child))\n else:\n log.debug(\"Skipped bullet_list child: '{0}'\".format(child))\n return content\n\n\ndef mixed_text_from_docutils(node):\n '''\n Takes most Text-ish docutils objects and converts them to MixedText\n\n :param node: ``docutils.nodes.{paragraph, list_item, ...}`` text-ish\n :returns: ``MixedText`` representing the given docutils object\n '''\n content = MixedText()\n for child in node.children:\n if isinstance(child, docutils.nodes.paragraph):\n content.texts.extend(mixed_text_from_docutils(child).texts)\n elif isinstance(child, docutils.nodes.Text):\n content.texts.append(child.astext())\n elif isinstance(child, docutils.nodes.reference):\n content.texts.append(reference_from_docutils(child))\n elif isinstance(child, docutils.nodes.emphasis):\n content.texts.append('*{0}*'.format(child.astext()))\n elif isinstance(child, docutils.nodes.strong):\n content.texts.append('**{0}**'.format(child.astext()))\n elif isinstance(child, docutils.nodes.literal):\n content.texts.append('``{0}``'.format(child.astext()))\n elif isinstance(child, docutils.nodes.literal_block):\n content.texts.append('\\n\\n ' + child.astext() + '\\n')\n elif isinstance(child, docutils.nodes.target):\n pass\n elif isinstance(child, docutils.nodes.system_message):\n log.debug(\"Skipping system_message: {0}\".format(child))\n elif isinstance(child, docutils.nodes.bullet_list):\n content.texts.append(bullet_list_class_from_docutils(child))\n else:\n try:\n # Try to add it as plain text\n log.debug(\"Trying to add {0}'s child of type {1}: '{2}'\"\n .format(type(node), type(child), child))\n content.texts.append(child.astext())\n except AttributeError:\n log.debug(\"Ignored {0} child of type {1}: '{2}'\"\n .format(type(node), type(child), child))\n return content\n\n\ndef get_changelog_from_path(path, package_name=None):\n '''\n Changelog factory, which reads a changelog file into a class\n\n :param path: ``str`` the path of the changelog including or excluding the filename CHANGELOG.rst\n :param package_name: ``str`` the package name\n :returns: ``Changelog`` changelog class or None if file was not readable\n '''\n changelog = Changelog(package_name)\n if os.path.isdir(path):\n path = os.path.join(path, CHANGELOG_FILENAME)\n try:\n with open(path, 'rb') as f:\n populate_changelog_from_rst(changelog, f.read().decode('utf-8'))\n except IOError:\n return None\n return changelog\n\n\ndef populate_changelog_from_rst(changelog, rst):\n '''\n Changelog factory, which converts the raw ReST into a class\n\n :param changelog: ``Changelog`` changelog to be populated\n :param rst: ``str`` raw ReST changelog\n :returns: ``Changelog`` changelog that was populated\n '''\n document = docutils.core.publish_doctree(rst)\n processes_changelog_children(changelog, document.children)\n changelog.rst = rst\n return changelog\n\n\ndef processes_changelog_children(changelog, children):\n '''\n Processes docutils children into a REP-0132 changelog instance.\n Recurse into sections, check (sub-)titles if they are valid versions.\n\n :param changelog: ``Changelog`` changelog to be populated\n :param section: ``docutils.nodes.section`` section to be processed\n :returns: ``Changelog`` changelog that was populated\n '''\n for i, child in enumerate(children):\n if isinstance(child, docutils.nodes.section):\n processes_changelog_children(changelog, child.children)\n elif isinstance(child, docutils.nodes.title) or isinstance(child, docutils.nodes.subtitle):\n version, date = None, None\n # See if the title has a text element in it\n if len(child.children) > 0 and isinstance(child.children[0], docutils.nodes.Text):\n # Extract version and date from (sub-)title\n title_text = child.children[0].rawsource\n try:\n version, date = version_and_date_from_title(title_text)\n except InvalidSectionTitle:\n # Catch invalid section titles\n log.debug(\"Ignored non-compliant title: '{0}'\".format(title_text))\n continue\n valid_section = None not in (version, date)\n if valid_section:\n contents = []\n # For each remaining sibling\n for child in children[i + 1:]:\n # Skip sections (nesting of valid sections not allowed)\n if isinstance(child, docutils.nodes.section):\n log.debug(\"Ignored section child: '{0}'\".format(child))\n continue\n # Skip title\n if isinstance(child, docutils.nodes.title):\n continue\n # Skip comments\n if isinstance(child, docutils.nodes.comment):\n log.debug(\"Ignored section child: '{0}'\".format(child))\n continue\n # Process other elements into the contents\n if isinstance(child, docutils.nodes.bullet_list):\n contents.append(bullet_list_class_from_docutils(child))\n elif isinstance(child, docutils.nodes.enumerated_list):\n contents.append(bullet_list_class_from_docutils(child, bullet_type='enumerated'))\n elif isinstance(child, docutils.nodes.transition):\n contents.append(Transition())\n elif isinstance(child, docutils.nodes.paragraph):\n contents.append(mixed_text_from_docutils(child))\n else:\n log.debug(\"Skipped section child: '{0}'\".format(child))\n changelog.add_version_section(version, date, contents)\n break\n else:\n log.debug(\"Ignored non-compliant title: '{0}'\".format(child))\n\n\ndef reference_from_docutils(reference):\n '''\n Turns a reference element into a ``Reference``\n\n :param reference: ``docutils.nodes.reference`` reference element\n :returns: ``Reference`` simpler object representing the reference\n '''\n name, refuri = None, None\n for pair in reference.attlist():\n if pair[0] == 'name':\n name = pair[1]\n if pair[0] == 'refuri':\n refuri = pair[1]\n return Reference(name, refuri)\n\n\ndef version_and_date_from_title(title):\n '''\n Splits a section title into version and date if possible.\n\n :param title: ``str`` raw section title to be processed\n :returns: ``(str, datetime.datetime)``\n :raises: ``InvalidSectionTitle`` for non REP-0132 section titles\n '''\n match = re.search(r'^([0-9]+\\.[0-9]+\\.[0-9]+)[ ]\\((.+)\\)$', title)\n if match is None:\n raise InvalidSectionTitle(title)\n version, date_str = match.groups()\n try:\n date = dateutil.parser.parse(date_str)\n except (ValueError, TypeError) as e:\n # Catch invalid dates\n log.debug(\"Error parsing date ({0}): '{1}'\".format(date_str, e))\n raise InvalidSectionTitle(title)\n return version, date\n\n\nclass BulletList(object):\n '''Represents a bulleted list of text'''\n def __init__(self, bullets=None, bullet_type=None):\n '''\n :param bullets: ``list(MixedText)`` list of text bullets\n :param bullet_type: ``str`` either 'bullet' or 'enumerated'\n '''\n bullet_type = 'bullet' if bullet_type is None else bullet_type\n if bullet_type not in ['bullet', 'enumerated']:\n raise RuntimeError(\"Invalid bullet type: '{0}'\".format(bullet_type))\n self.bullets = bullets or []\n self.bullet_type = bullet_type\n\n def __iter__(self):\n for bullet in self.bullets:\n yield bullet\n\n def __str__(self):\n value = self.__unicode__()\n if not _py3:\n value = value.encode('ascii', 'replace')\n return value\n\n def __unicode__(self):\n return self.as_txt()\n\n def as_rst(self):\n return self.as_txt(indent='', use_hyphen_bullet=True)\n\n def as_txt(self, indent='', use_hyphen_bullet=False):\n bullet = '*' if self.bullet_type == 'bullet' else '#'\n if use_hyphen_bullet and bullet == '*':\n bullet = '-'\n b = self.bullet_generator(bullet)\n i = indent\n n = '\\n' + i + ' '\n lines = [i + next(b) + _unicode(l).replace('\\n', n) for l in self]\n return '\\n'.join(lines)\n\n def bullet_generator(self, bullet):\n if '#' == bullet:\n bullets = [str(i) + '. ' for i in range(1, len(self.bullets) + 1)]\n else:\n bullets = [bullet + ' '] * len(self.bullets)\n for b in bullets:\n yield b\n\n\nclass Changelog(object):\n '''\n Represents a REP-0132 changelog\n '''\n def __init__(self, package_name=None):\n self.__package_name = package_name\n self.__versions = []\n self.__parsed_versions = []\n self.__dates = {}\n self.__content = {}\n self.__rst = ''\n\n def __str__(self):\n value = self.__unicode__()\n if not _py3:\n value = value.encode('ascii', 'replace')\n return value\n\n def __unicode__(self):\n msg = []\n if self.__package_name:\n msg.append(\"Changelog for package '{0}'\".format(self.package_name))\n for version, date, content in self.foreach_version(reverse=True):\n msg.append(' ' + version + ' ({0}):'.format(date))\n for item in content:\n msg.extend([' ' + i for i in _unicode(item).splitlines()])\n return '\\n'.join(msg)\n\n @property\n def package_name(self):\n return self.__package_name\n\n @package_name.setter\n def package_name(self, package_name):\n self.__package_name = package_name\n\n @property\n def rst(self):\n return self.__rst\n\n @rst.setter", "answers": [" def rst(self, rst):"], "length": 1367, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "2026c331-1d19-4d54-b67b-f9b5fb18eb93", "reasoning": "The code defines a property 'rst' with a getter. After the getter, the setter decorator '@rst.setter' is placed, so the next line must start the setter method definition. Following Python property conventions, the setter method is defined as 'def rst(self, rst):', which will assign the provided value to the internal attribute.", "reasoning_model_answer": "def rst(self, rst):", "assistant_with_reasoning": "\nThe code defines a property 'rst' with a getter. After the getter, the setter decorator '@rst.setter' is placed, so the next line must start the setter method definition. Following Python property conventions, the setter method is defined as 'def rst(self, rst):', which will assign the provided value to the internal attribute.\n\ndef rst(self, rst):", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 2.421, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 14275, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "def rst(self, rst):", "score": 0.9, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "import time\n\nfrom decorator import decorator\nfrom fabric import state\nfrom fabric.api import execute, get, put, run, parallel, settings\nfrom fabric.exceptions import CommandTimeout\nfrom logger import logger\n\nfrom perfrunner.helpers.misc import uhex\n\n\n@decorator\ndef all_hosts(task, *args, **kargs):\n self = args[0]\n return execute(parallel(task), *args, hosts=self.hosts, **kargs)\n\n\n@decorator\ndef single_host(task, *args, **kargs):\n self = args[0]\n with settings(host_string=self.hosts[0]):\n return task(*args, **kargs)\n\n\n@decorator\ndef seriesly_host(task, *args, **kargs):\n self = args[0]\n with settings(host_string=self.test_config.gateload_settings.seriesly_host):\n return task(*args, **kargs)\n\n\n@decorator\ndef all_gateways(task, *args, **kargs):\n self = args[0]\n return execute(parallel(task), *args, hosts=self.gateways, **kargs)\n\n\n@decorator\ndef all_gateloads(task, *args, **kargs):\n self = args[0]\n return execute(parallel(task), *args, hosts=self.gateloads, **kargs)\n\n\nclass RemoteHelper(object):\n\n def __new__(cls, cluster_spec, test_config, verbose=False):\n if not cluster_spec.ssh_credentials:\n return None\n\n state.env.user, state.env.password = cluster_spec.ssh_credentials\n state.output.running = verbose\n state.output.stdout = verbose\n\n os = cls.detect_os(cluster_spec)\n if os == 'Cygwin':\n return RemoteWindowsHelper(cluster_spec, test_config, os)\n else:\n return RemoteLinuxHelper(cluster_spec, test_config, os)\n\n @staticmethod\n def detect_os(cluster_spec):\n logger.info('Detecting OS')\n with settings(host_string=cluster_spec.yield_hostnames().next()):\n os = run('python -c \"import platform; print platform.dist()[0]\"',\n pty=False)\n if os:\n return os\n else:\n return 'Cygwin'\n\n\nclass RemoteLinuxHelper(object):\n\n ARCH = {'i386': 'x86', 'x86_64': 'x86_64', 'unknown': 'x86_64'}\n\n CB_DIR = '/opt/couchbase'\n MONGO_DIR = '/opt/mongodb'\n\n PROCESSES = ('beam.smp', 'memcached', 'epmd', 'cbq-engine', 'mongod')\n\n def __init__(self, cluster_spec, test_config, os):\n self.os = os\n self.hosts = tuple(cluster_spec.yield_hostnames())\n self.cluster_spec = cluster_spec\n self.test_config = test_config\n self.env = {}\n\n if self.cluster_spec.gateways and test_config is not None:\n num_nodes = self.test_config.gateway_settings.num_nodes\n self.gateways = self.cluster_spec.gateways[:num_nodes]\n self.gateloads = self.cluster_spec.gateloads[:num_nodes]\n else:\n self.gateways = self.gateloads = None\n\n @staticmethod\n def wget(url, outdir='/tmp', outfile=None):\n logger.info('Fetching {}'.format(url))\n if outfile is not None:\n run('wget -nc \"{}\" -P {} -O {}'.format(url, outdir, outfile))\n else:\n run('wget -nc \"{}\" -P {}'.format(url, outdir))\n\n @single_host\n def detect_pkg(self):\n logger.info('Detecting package manager')\n if self.os in ('Ubuntu', 'Debian'):\n return 'deb'\n else:\n return 'rpm'\n\n @single_host\n def detect_arch(self):\n logger.info('Detecting platform architecture')\n arch = run('uname -i', pty=False)\n return self.ARCH[arch]\n\n @single_host\n def build_secondary_index(self, index_nodes, bucket, indexes, fields,\n secondarydb, where_map):\n logger.info('building secondary indexes')\n\n # Remember what bucket:index was created\n bucket_indexes = []\n\n for index, field in zip(indexes, fields):\n cmd = \"/opt/couchbase/bin/cbindex\"\n cmd += ' -auth=Administrator:password'\n cmd += ' -server {}'.format(index_nodes[0])\n cmd += ' -type create -bucket {}'.format(bucket)\n cmd += ' -fields={}'.format(field)\n\n if secondarydb:\n cmd += ' -using {}'.format(secondarydb)\n\n if index in where_map and field in where_map[index]:\n # Partition indexes over index nodes by deploying index with\n # where clause on the corresponding index node\n where_list = where_map[index][field]\n for i, (index_node, where) in enumerate(\n zip(index_nodes, where_list)):\n # don't taint cmd itself because we need to reuse it.\n final_cmd = cmd\n index_i = index + \"_{}\".format(i)\n final_cmd += ' -index {}'.format(index_i)\n final_cmd += \" -where='{}'\".format(where)\n\n # Since .format() is sensitive to {}, use % formatting\n with_str_template = \\\n r'{\\\\\\\"defer_build\\\\\\\":true, \\\\\\\"nodes\\\\\\\":[\\\\\\\"%s\\\\\\\"]}'\n with_str = with_str_template % index_node\n\n final_cmd += ' -with=\\\\\\\"{}\\\\\\\"'.format(with_str)\n bucket_indexes.append(\"{}:{}\".format(bucket, index_i))\n logger.info('submitting cbindex command {}'.format(final_cmd))\n status = run(final_cmd, shell_escape=False, pty=False)\n if status:\n logger.info('cbindex status {}'.format(status))\n else:\n # no partitions, no where clause\n final_cmd = cmd\n final_cmd += ' -index {}'.format(index)\n with_str = r'{\\\\\\\"defer_build\\\\\\\":true}'\n final_cmd += ' -with=\\\\\\\"{}\\\\\\\"'.format(with_str)\n bucket_indexes.append(\"{}:{}\".format(bucket, index))\n\n logger.info('submitting cbindex command {}'.format(final_cmd))\n status = run(final_cmd, shell_escape=False, pty=False)\n if status:\n logger.info('cbindex status {}'.format(status))\n\n time.sleep(10)\n\n # build indexes\n cmdstr = '/opt/couchbase/bin/cbindex -auth=\"Administrator:password\"'\n cmdstr += ' -server {}'.format(index_nodes[0])\n cmdstr += ' -type build'\n cmdstr += ' -indexes {}'.format(\",\".join(bucket_indexes))\n logger.info('cbindex build command {}'.format(cmdstr))\n status = run(cmdstr, shell_escape=False, pty=False)\n if status:\n logger.info('cbindex status {}'.format(status))\n\n @single_host\n def detect_openssl(self, pkg):\n logger.info('Detecting openssl version')\n if pkg == 'rpm':\n return run('rpm -q --qf \"%{VERSION}\" openssl.x86_64')\n\n @all_hosts\n def reset_swap(self):\n logger.info('Resetting swap')\n run('swapoff --all && swapon --all')\n\n @all_hosts\n def drop_caches(self):\n logger.info('Dropping memory cache')\n run('sync && echo 3 > /proc/sys/vm/drop_caches')\n\n @all_hosts\n def set_swappiness(self):\n logger.info('Changing swappiness to 0')\n run('sysctl vm.swappiness=0')\n\n @all_hosts\n def disable_thp(self):\n for path in (\n '/sys/kernel/mm/transparent_hugepage/enabled',\n '/sys/kernel/mm/redhat_transparent_hugepage/enabled',\n ):\n run('echo never > {}'.format(path), quiet=True)\n\n @all_hosts\n def collect_info(self):\n logger.info('Running cbcollect_info')\n\n run('rm -f /tmp/*.zip')\n\n fname = '/tmp/{}.zip'.format(uhex())\n try:\n r = run('{}/bin/cbcollect_info {}'.format(self.CB_DIR, fname),\n warn_only=True, timeout=1200)\n except CommandTimeout:\n logger.error('cbcollect_info timed out')\n return\n if not r.return_code:\n get('{}'.format(fname))\n run('rm -f {}'.format(fname))\n\n @all_hosts\n def clean_data(self):\n for path in self.cluster_spec.paths:\n run('rm -fr {}/*'.format(path))\n run('rm -fr {}'.format(self.CB_DIR))\n\n @all_hosts\n def kill_processes(self):\n logger.info('Killing {}'.format(', '.join(self.PROCESSES)))\n run('killall -9 {}'.format(' '.join(self.PROCESSES)),\n warn_only=True, quiet=True)\n\n @all_hosts\n def uninstall_couchbase(self, pkg):\n logger.info('Uninstalling Couchbase Server')\n if pkg == 'deb':\n run('yes | apt-get remove couchbase-server', quiet=True)\n run('yes | apt-get remove couchbase-server-community', quiet=True)\n else:\n run('yes | yum remove couchbase-server', quiet=True)\n run('yes | yum remove couchbase-server-community', quiet=True)\n\n @all_hosts\n def install_couchbase(self, pkg, url, filename, version=None):\n self.wget(url, outdir='/tmp')\n\n logger.info('Installing Couchbase Server')\n if pkg == 'deb':\n run('yes | apt-get install gdebi')\n run('yes | numactl --interleave=all gdebi /tmp/{}'.format(filename))\n else:\n run('yes | numactl --interleave=all rpm -i /tmp/{}'.format(filename))\n\n @all_hosts\n def restart(self):\n logger.info('Restarting server')\n environ = ' '.join('{}={}'.format(k, v) for (k, v) in self.env.items())\n run(environ +\n ' numactl --interleave=all /etc/init.d/couchbase-server restart',\n pty=False)\n\n def restart_with_alternative_num_vbuckets(self, num_vbuckets):\n logger.info('Changing number of vbuckets to {}'.format(num_vbuckets))\n self.env['COUCHBASE_NUM_VBUCKETS'] = num_vbuckets\n self.restart()\n\n def restart_with_alternative_num_cpus(self, num_cpus):\n logger.info('Changing number of front-end memcached threads to {}'\n .format(num_cpus))\n self.env['MEMCACHED_NUM_CPUS'] = num_cpus\n self.restart()\n\n def restart_with_sfwi(self):\n logger.info('Enabling +sfwi')\n self.env['COUCHBASE_NS_SERVER_VM_EXTRA_ARGS'] = '[\"+sfwi\", \"100\", \"+sbwt\", \"long\"]'\n self.restart()\n\n def restart_with_tcmalloc_aggressive_decommit(self):\n logger.info('Enabling TCMalloc aggressive decommit')\n self.env['TCMALLOC_AGGRESSIVE_DECOMMIT'] = 't'\n self.restart()\n\n @all_hosts\n def disable_moxi(self):\n logger.info('Disabling moxi')\n run('rm /opt/couchbase/bin/moxi')\n run('killall -9 moxi')\n\n @all_hosts\n def stop_server(self):\n logger.info('Stopping Couchbase Server')\n getosname = run('uname -a|cut -c1-6')\n if(getosname.find(\"CYGWIN\") != -1):\n run('net stop CouchbaseServer')\n else:\n run('/etc/init.d/couchbase-server stop', pty=False)\n\n @all_hosts\n def start_server(self):\n logger.info('Starting Couchbase Server')\n getosname = run('uname -a|cut -c1-6')\n if(getosname.find(\"CYGWIN\") != -1):\n run('net start CouchbaseServer')\n else:\n run('/etc/init.d/couchbase-server start', pty=False)\n\n def detect_if(self):\n for iface in ('em1', 'eth5', 'eth0'):\n result = run('grep {} /proc/net/dev'.format(iface),\n warn_only=True, quiet=True)\n if not result.return_code:\n return iface\n\n def detect_ip(self, _if):\n ifconfing = run('ifconfig {} | grep \"inet addr\"'.format(_if))\n return ifconfing.split()[1].split(':')[1]\n\n @all_hosts\n def disable_wan(self):\n logger.info('Disabling WAN effects')\n _if = self.detect_if()\n run('tc qdisc del dev {} root'.format(_if), warn_only=True, quiet=True)\n\n @all_hosts\n def enable_wan(self):\n logger.info('Enabling WAN effects')\n _if = self.detect_if()\n for cmd in (\n 'tc qdisc add dev {} handle 1: root htb',\n 'tc class add dev {} parent 1: classid 1:1 htb rate 1gbit',\n 'tc class add dev {} parent 1:1 classid 1:11 htb rate 1gbit',\n 'tc qdisc add dev {} parent 1:11 handle 10: netem delay 40ms 2ms '\n 'loss 0.005% 50% duplicate 0.005% corrupt 0.005%',\n ):\n run(cmd.format(_if))\n\n @all_hosts\n def filter_wan(self, src_list, dest_list):\n logger.info('Filtering WAN effects')\n _if = self.detect_if()\n\n if self.detect_ip(_if) in src_list:\n _filter = dest_list\n else:\n _filter = src_list\n\n for ip in _filter:\n run('tc filter add dev {} protocol ip prio 1 u32 '\n 'match ip dst {} flowid 1:11'.format(_if, ip))\n\n @single_host\n def detect_number_cores(self):\n logger.info('Detecting number of cores')\n return int(run('nproc', pty=False))\n\n @all_hosts\n def detect_core_dumps(self):\n # Based on kernel.core_pattern = /tmp/core.%e.%p.%h.%t\n r = run('ls /tmp/core*', quiet=True)\n if not r.return_code:\n return r.split()\n else:\n return []\n\n @all_hosts\n def tune_log_rotation(self):\n logger.info('Tune log rotation so that it happens less frequently')\n run('sed -i \"s/num_files, [0-9]*/num_files, 50/\" '\n '/opt/couchbase/etc/couchbase/static_config')\n\n @all_hosts\n def start_cbq(self):\n logger.info('Starting cbq-engine')\n return run('nohup cbq-engine '\n '-couchbase=http://127.0.0.1:8091 -dev=true -log=HTTP '\n '&> /tmp/cbq.log &', pty=False)\n\n @all_hosts\n def collect_cbq_logs(self):\n logger.info('Getting cbq-engine logs')\n get('/tmp/cbq.log')\n\n @seriesly_host\n def restart_seriesly(self):\n logger.info('Cleaning up and restarting seriesly')\n run('killall -9 sample seriesly', quiet=True)\n run('rm -f *.txt *.log *.gz *.json *.out /root/seriesly-data/*',\n warn_only=True)\n run('nohup seriesly -flushDelay=1s -root=/root/seriesly-data '\n '&> seriesly.log &', pty=False)\n\n @seriesly_host\n def start_sampling(self):\n for i, gateway_ip in enumerate(self.gateways, start=1):\n logger.info('Starting sampling gateway_{}'.format(i))\n run('nohup sample -v '\n 'http://{}:4985/_expvar http://localhost:3133/gateway_{} '\n '&> sample.log &'.format(gateway_ip, i), pty=False)\n for i, gateload_ip in enumerate(self.gateloads, start=1):\n logger.info('Starting sampling gateload_{}'.format(i))\n run('nohup sample -v '\n 'http://{}:9876/debug/vars http://localhost:3133/gateload_{} '\n '&> sample.log &'.format(gateload_ip, i), pty=False)\n\n @all_gateways\n def install_gateway(self, url, filename):\n logger.info('Installing Sync Gateway package - {}'.format(filename))\n self.wget(url, outdir='/tmp')\n run('yes | rpm -i /tmp/{}'.format(filename))\n\n @all_gateways\n def install_gateway_from_source(self, commit_hash):\n logger.info('Installing Sync Gateway from source - {}'.format(commit_hash))\n put('scripts/install_sgw_from_source.sh', '/root/install_sgw_from_source.sh')\n run('chmod 777 /root/install_sgw_from_source.sh')\n run('/root/install_sgw_from_source.sh {}'.format(commit_hash), pty=False)\n\n @all_gateways\n def uninstall_gateway(self):\n logger.info('Uninstalling Sync Gateway package')\n run('yes | yum remove couchbase-sync-gateway')\n\n @all_gateways\n def kill_processes_gateway(self):\n logger.info('Killing Sync Gateway')\n run('killall -9 sync_gateway sgw_test_info.sh sar', quiet=True)\n\n @all_gateways\n def clean_gateway(self):\n logger.info('Cleaning up Gateway')\n run('rm -f *.txt *.log *.gz *.json *.out *.prof', quiet=True)\n\n @all_gateways\n def start_gateway(self):\n logger.info('Starting Sync Gateway instances')\n _if = self.detect_if()\n local_ip = self.detect_ip(_if)\n index = self.gateways.index(local_ip)\n source_config = 'templates/gateway_config_{}.json'.format(index)\n put(source_config, '/root/gateway_config.json')\n godebug = self.test_config.gateway_settings.go_debug\n args = {\n 'ulimit': 'ulimit -n 65536',\n 'godebug': godebug,\n 'sgw': '/opt/couchbase-sync-gateway/bin/sync_gateway',\n 'config': '/root/gateway_config.json',\n 'log': '/root/gateway.log',\n }\n command = '{ulimit}; GODEBUG={godebug} nohup {sgw} {config} > {log} 2>&1 &'.format(**args)\n logger.info(\"Command: {}\".format(command))\n run(command, pty=False)\n\n @all_gateways\n def start_test_info(self):\n logger.info('Starting Sync Gateway sgw_test_info.sh')\n put('scripts/sgw_test_config.sh', '/root/sgw_test_config.sh')\n put('scripts/sgw_test_info.sh', '/root/sgw_test_info.sh')\n run('chmod 777 /root/sgw_*.sh')\n run('nohup /root/sgw_test_info.sh &> sgw_test_info.txt &', pty=False)\n\n @all_gateways\n def collect_info_gateway(self):\n _if = self.detect_if()\n local_ip = self.detect_ip(_if)\n index = self.gateways.index(local_ip)\n logger.info('Collecting diagnostic information from sync gateway_{} {}'.format(index, local_ip))\n run('rm -f gateway.log.gz', warn_only=True)\n run('gzip gateway.log', warn_only=True)\n put('scripts/sgw_check_logs.sh', '/root/sgw_check_logs.sh')\n run('chmod 777 /root/sgw_*.sh')\n run('/root/sgw_check_logs.sh gateway > sgw_check_logs.out', warn_only=True)\n self.try_get('gateway.log.gz', 'gateway.log_{}.gz'.format(index))\n self.try_get('test_info.txt', 'test_info_{}.txt'.format(index))\n self.try_get('test_info_sar.txt', 'test_info_sar_{}.txt'.format(index))\n self.try_get('sgw_test_info.txt', 'sgw_test_info_{}.txt'.format(index))\n self.try_get('gateway_config.json', 'gateway_config_{}.json'.format(index))\n self.try_get('sgw_check_logs.out', 'sgw_check_logs_gateway_{}.out'.format(index))\n\n @all_gateloads\n def uninstall_gateload(self):\n logger.info('Removing Gateload binaries')\n run('rm -f /opt/gocode/bin/gateload', quiet=True)\n\n @all_gateloads\n def install_gateload(self):\n logger.info('Installing Gateload')\n run('go get -u github.com/couchbaselabs/gateload')\n\n @all_gateloads\n def kill_processes_gateload(self):\n logger.info('Killing Gateload processes')\n run('killall -9 gateload', quiet=True)\n\n @all_gateloads\n def clean_gateload(self):\n logger.info('Cleaning up Gateload')\n run('rm -f *.txt *.log *.gz *.json *.out', quiet=True)\n\n @all_gateloads\n def start_gateload(self):\n logger.info('Starting Gateload')\n _if = self.detect_if()\n local_ip = self.detect_ip(_if)\n idx = self.gateloads.index(local_ip)\n\n config_fname = 'templates/gateload_config_{}.json'.format(idx)\n put(config_fname, '/root/gateload_config.json')\n put('scripts/sgw_check_logs.sh', '/root/sgw_check_logs.sh')\n run('chmod 777 /root/sgw_*.sh')\n run('ulimit -n 65536; nohup /opt/gocode/bin/gateload '\n '-workload /root/gateload_config.json &>/root/gateload.log&',\n pty=False)", "answers": [" @all_gateloads"], "length": 1428, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "38c02344-c30c-48c3-a950-a69d14bd93de", "reasoning": "The start_gateload method ends with a run() call. In this class, methods are grouped and each new method begins with a decorator line. Following the pattern for gateway methods (e.g., @all_gateways def collect_info_gateway...), the next logical method for gateloads will start with the @all_gateloads decorator. Therefore the next line of code is the decorator line for the subsequent method.", "reasoning_model_answer": "@all_gateloads", "assistant_with_reasoning": "\nThe start_gateload method ends with a run() call. In this class, methods are grouped and each new method begins with a decorator line. Following the pattern for gateway methods (e.g., @all_gateways def collect_info_gateway...), the next logical method for gateloads will start with the @all_gateloads decorator. Therefore the next line of code is the decorator line for the subsequent method.\n\n@all_gateloads", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 6.92, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 19312, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "@all_gateloads", "score": 0.88, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "//Copyright 2012 RobustNet Lab, University of Michigan. All Rights Reserved.\n\npackage com.mobiperf_library.measurements;\n\nimport java.io.IOException;\nimport java.io.InvalidClassException;\nimport java.io.InputStream;\nimport java.io.OutputStream;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketAddress;\nimport java.security.InvalidParameterException;\nimport java.util.ArrayList;\nimport java.util.Date;\nimport java.util.Map;\nimport java.util.Random;\n\nimport com.mobiperf_library.MeasurementDesc;\nimport com.mobiperf_library.MeasurementResult;\nimport com.mobiperf_library.MeasurementTask;\nimport com.mobiperf_library.MeasurementResult.TaskProgress;\nimport com.mobiperf_library.exceptions.MeasurementError;\nimport com.mobiperf_library.util.Logger;\nimport com.mobiperf_library.util.MLabNS;\nimport com.mobiperf_library.util.MeasurementJsonConvertor;\nimport com.mobiperf_library.util.PhoneUtils;\n\nimport android.content.Context;\nimport android.os.Parcel;\nimport android.os.Parcelable;\n\n/**\n * @author Haokun Luo\n * \n * TCP Throughput is a measurement task for cellular network throughput.\n * 1. Uplink: the mobile device continuously sends packets with consistent \n * packet size. We send packets for a fixed amount of time, and we sample\n * each throughput value at a smaller period. We use the median of all the \n * sampling result as the final measurement result. The result is calculated \n * at the server side, and send back to the device.\n * 2. Downlink: similar methodology as uplink. Only difference is that the\n * device is receiving packets from the server, and calculate the result\n * locally. \n */\npublic class TCPThroughputTask extends MeasurementTask {\n // default constant here\n public static final String DESCRIPTOR = \"TCP Speed Test\";\n public static final int PORT_DOWNLINK = 6001;\n public static final int PORT_UPLINK = 6002;\n public static final int PORT_CONFIG = 6003;\n public static final String TYPE = \"tcpthroughput\";\n\n // Timing related\n public final int BUFFER_SIZE = 5000;\n public static final long DURATION_IN_SEC = 15;\n public final int KSEC = 1000;\n public static final long SAMPLE_PERIOD_IN_SEC = 1; \n public static final long SLOW_START_PERIOD_IN_SEC = 5;\n public static final int TCP_TIMEOUT_IN_SEC = 30;\n // largest non-fragment packet size in LTE (uplink)\n public static final int THROUGHPUT_UP_PKT_SIZE_MAX = 1357;\n public static final int THROUGHPUT_UP_PKT_SIZE_MIN = 700;\n\n // Data related\n private final int KBYTE = 1024;\n private static final int DATA_LIMIT_MB_UP = 5; \n private static final int DATA_LIMIT_MB_DOWN = 10;\n private boolean DATA_LIMIT_ON = true;\n private boolean DATA_LIMIT_EXCEEDED = false;\n private static final String UPLINK_FINISH_MSG = \"*\";\n\n private Context context = null;\n\n // helper variables \n private int accumulativeSize = 0;\n private Random randStr = new Random();\n private ArrayList samplingResults = new ArrayList();\n //start time of each sampling period\n private long startSampleTime = 0;\n private String serverVersion = \"\";\n private long taskStartTime = 0;\n private double taskDuration = 0;\n //uplink accumulative data\n private int totalSendSize = 0;\n // downlink accumulative data\n private int totalRevSize = 0;\n\n private long duration;\n private TaskProgress taskProgress;\n private volatile boolean stopFlag;\n\n // class constructor\n public TCPThroughputTask(MeasurementDesc desc) {\n super(new TCPThroughputDesc(desc.key, desc.startTime, desc.endTime, \n desc.intervalSec, desc.count, desc.priority, desc.contextIntervalSec,\n desc.parameters));\n this.taskProgress=TaskProgress.FAILED;\n this.stopFlag=false;\n this.duration=(long)(this.KSEC*\n ((TCPThroughputDesc)measurementDesc).duration_period_sec +\n ((TCPThroughputDesc)measurementDesc).slow_start_period_sec);\n Logger.i(\"Create new throughput task\");\n }\n\n\n protected TCPThroughputTask(Parcel in) {\n super(in);\n taskProgress = (TaskProgress)in.readSerializable();\n stopFlag = in.readByte() != 0;\n duration = in.readLong();\n }\n\n public static final Parcelable.Creator CREATOR =\n new Parcelable.Creator() {\n public TCPThroughputTask createFromParcel(Parcel in) {\n return new TCPThroughputTask(in);\n }\n\n public TCPThroughputTask[] newArray(int size) {\n return new TCPThroughputTask[size];\n }\n };\n\n @Override\n public void writeToParcel(Parcel dest, int flags) {\n super.writeToParcel(dest, flags);\n dest.writeSerializable(taskProgress);\n dest.writeByte((byte) (stopFlag ? 1 : 0));\n dest.writeLong(duration);\n }\n /**\n * There are seven parameters specifically for this experiment:\n * 1. data_limit_mb_up: uplink cellular network data limit\n * 2. data_limit_mb_down: downlink cellular network data limit\n * 3. duration_period_sec : downlink maximum experiment duration period\n * 4. pkt_size_up_bytes: the size each packet in the uplink\n * 5. sample_period_sec : the small interval to calculate current throughput result\n * 6. slow_start_period_sec : waiting period to avoid TCP slow start\n * 7. tcp_timeout_sec: TCP connection timeout\n */\n\n public static class TCPThroughputDesc extends MeasurementDesc {\n // declared parameters\n public double data_limit_mb_up =\n TCPThroughputTask.DATA_LIMIT_MB_UP;\n public double data_limit_mb_down =\n TCPThroughputTask.DATA_LIMIT_MB_DOWN;\n public boolean dir_up = false;\n public double duration_period_sec =\n TCPThroughputTask.DURATION_IN_SEC;\n public int pkt_size_up_bytes =\n TCPThroughputTask.THROUGHPUT_UP_PKT_SIZE_MAX;\n public double sample_period_sec =\n TCPThroughputTask.SAMPLE_PERIOD_IN_SEC;\n public double slow_start_period_sec =\n TCPThroughputTask.SLOW_START_PERIOD_IN_SEC;\n public String target = null;\n public double tcp_timeout_sec = TCPThroughputTask.TCP_TIMEOUT_IN_SEC;\n\n public TCPThroughputDesc(String key, Date startTime,\n Date endTime, double intervalSec, long count, \n long priority, int contextIntervalSec, Map params) \n throws InvalidParameterException {\n super(TCPThroughputTask.TYPE, key, startTime, endTime, intervalSec, count,\n priority, contextIntervalSec, params);\n initializeParams(params);\n if (this.target == null || this.target.length() == 0) {\n throw new InvalidParameterException(\"TCPThroughputTask null target\");\n }\n }\n\n protected TCPThroughputDesc(Parcel in) {\n super(in);\n data_limit_mb_up = in.readDouble();\n data_limit_mb_down = in.readDouble();\n dir_up = in.readByte() != 0;\n duration_period_sec = in.readDouble();\n pkt_size_up_bytes = in.readInt();\n sample_period_sec = in.readDouble();\n slow_start_period_sec = in.readDouble();\n target = in.readString();\n tcp_timeout_sec = in.readDouble();\n }\n\n public static final Parcelable.Creator CREATOR\n = new Parcelable.Creator() {\n public TCPThroughputDesc createFromParcel(Parcel in) {\n return new TCPThroughputDesc(in);\n }\n\n public TCPThroughputDesc[] newArray(int size) {\n return new TCPThroughputDesc[size];\n }\n };\n\n @Override\n public int describeContents() {\n return super.describeContents();\n }\n\n @Override\n public void writeToParcel(Parcel dest, int flags) {\n super.writeToParcel(dest, flags);\n dest.writeDouble(data_limit_mb_up);\n dest.writeDouble(data_limit_mb_down);\n dest.writeByte((byte) (dir_up ? 1 : 0));\n dest.writeDouble(duration_period_sec);\n dest.writeInt(pkt_size_up_bytes);\n dest.writeDouble(sample_period_sec);\n dest.writeDouble(slow_start_period_sec);\n dest.writeString(target);\n dest.writeDouble(tcp_timeout_sec);\n }\n\n @Override\n protected void initializeParams(Map params) {\n if (params == null) {\n return;\n }\n if ( (target = params.get(\"target\")) == null ) {\n target = MLabNS.TARGET;\n }\n\n try {\n String readVal = null;\n if ((readVal = params.get(\"data_limit_mb_down\")) != null &&\n readVal.length() > 0 && Integer.parseInt(readVal) > 0) {\n this.data_limit_mb_down = Double.parseDouble(readVal);\n if (this.data_limit_mb_down > TCPThroughputTask.DATA_LIMIT_MB_DOWN) {\n this.data_limit_mb_down = TCPThroughputTask.DATA_LIMIT_MB_DOWN;\n }\n }\n\n if ((readVal = params.get(\"data_limit_mb_up\")) != null &&\n readVal.length() > 0 && Integer.parseInt(readVal) > 0) {\n this.data_limit_mb_up = Double.parseDouble(readVal);\n if (this.data_limit_mb_up > TCPThroughputTask.DATA_LIMIT_MB_UP) {\n this.data_limit_mb_up = TCPThroughputTask.DATA_LIMIT_MB_UP;\n }\n }\n if ((readVal = params.get(\"duration_period_sec\")) != null &&\n readVal.length() > 0 && Integer.parseInt(readVal) > 0) {\n this.duration_period_sec = Double.parseDouble(readVal);\n if (this.duration_period_sec > TCPThroughputTask.DURATION_IN_SEC) {\n this.duration_period_sec = TCPThroughputTask.DURATION_IN_SEC;\n }\n }\n if ((readVal = params.get(\"pkt_size_up_bytes\")) != null &&\n readVal.length() > 0 && Integer.parseInt(readVal) > 0) {\n this.pkt_size_up_bytes = Integer.parseInt(readVal);\n if (this.pkt_size_up_bytes > TCPThroughputTask.THROUGHPUT_UP_PKT_SIZE_MAX) {\n this.pkt_size_up_bytes = TCPThroughputTask.THROUGHPUT_UP_PKT_SIZE_MAX;\n }\n if (this.pkt_size_up_bytes < TCPThroughputTask.THROUGHPUT_UP_PKT_SIZE_MIN) {\n this.pkt_size_up_bytes = TCPThroughputTask.THROUGHPUT_UP_PKT_SIZE_MIN;\n }\n }\n if ((readVal = params.get(\"sample_period_sec\")) != null &&\n readVal.length() > 0 && Integer.parseInt(readVal) > 0) {\n this.sample_period_sec = Double.parseDouble(readVal);\n if (this.sample_period_sec > TCPThroughputTask.DURATION_IN_SEC/2) {\n this.sample_period_sec = TCPThroughputTask.DURATION_IN_SEC/2;\n }\n }\n if ((readVal = params.get(\"slow_start_period_sec\")) != null\n && readVal.length() > 0 && Integer.parseInt(readVal) > 0) {\n this.slow_start_period_sec = Double.parseDouble(readVal);\n if (this.slow_start_period_sec > TCPThroughputTask.DURATION_IN_SEC/2) {\n this.slow_start_period_sec = TCPThroughputTask.DURATION_IN_SEC/2;\n }\n }\n if ((readVal = params.get(\"tcp_timeout_sec\")) != null &&\n readVal.length() > 0 && Integer.parseInt(readVal) > 0) {\n this.tcp_timeout_sec = Integer.parseInt(readVal)*1000;\n if (this.tcp_timeout_sec > TCPThroughputTask.TCP_TIMEOUT_IN_SEC) {\n this.tcp_timeout_sec = TCPThroughputTask.TCP_TIMEOUT_IN_SEC;\n }\n }\n } catch (NumberFormatException e) {\n throw new InvalidParameterException(\"TCP Throughput Task invalid parameters.\");\n }\n\n String dir = null;\n if ((dir = params.get(\"dir_up\")) != null && dir.length() > 0) {\n if (dir.compareTo(\"Up\") == 0 || dir.compareTo(\"true\") == 0) {\n this.dir_up = true;\n }\n }\n }\n\n @Override\n public String getType() {\n return TCPThroughputTask.TYPE;\n }\n\n /**\n * Find the median value from a TCPThroughput JSON result string (already sorted)\n * Suppose N is the number of results. If N is odd, we pick the result with index\n * (N-1)/2. If N is even, we take the mean value between index N/2 and N/2-1\n * \n * @return -1 fail to create result\n * @return median value result\n */\n public double calMedianSpeedFromTCPThroughputOutput(String outputInJSON) {\n if (outputInJSON == null || \n outputInJSON.equals(\"\") ||\n outputInJSON.equals(\"[]\") ||\n outputInJSON.charAt(0) != '[' || \n outputInJSON.charAt(outputInJSON.length()-1) != ']') {\n return -1;\n }\n\n String[] splitResult = outputInJSON.substring(1,\n outputInJSON.length()-1).split(\",\");\n int resultLen = splitResult.length;\n if (resultLen <= 0)\n return 0.0;\n double result = 0.0;\n if (resultLen % 2 == 0) {\n result = (Double.parseDouble(splitResult[resultLen / 2]) +\n Double.parseDouble(splitResult[resultLen / 2 - 1])) / 2;\n } else {\n result = Double.parseDouble(splitResult[(resultLen - 1) / 2]);\n }\n return result;\n }\n }\n\n /**\n * Make a deep cloning of the task\n */\n @Override\n public MeasurementTask clone() {\n MeasurementDesc desc = this.measurementDesc;\n TCPThroughputDesc newDesc = new TCPThroughputDesc(\n desc.key, desc.startTime, \n desc.endTime, desc.intervalSec, desc.count, desc.priority,\n desc.contextIntervalSec, desc.parameters);\n return new TCPThroughputTask(newDesc);\n }\n\n @Override\n public String getType() {\n return TCPThroughputTask.TYPE;\n }\n\n @Override\n public String getDescriptor() {\n return TCPThroughputTask.DESCRIPTOR;\n }\n\n /** \n * This will be printed to the device log console. Make sure it's well\n * structured and human readable\n */\n @Override\n public String toString() {\n TCPThroughputDesc desc = (TCPThroughputDesc) measurementDesc;\n String resp;\n\n if (desc.dir_up) {\n resp = \"[TCP Uplink]\\n\";\n } else {\n resp = \"[TCP Downlink]\\n\";\n }\n\n resp += \" Target: \" + desc.target + \"\\n Interval (sec): \" + \n desc.intervalSec + \"\\n Next run: \" + desc.startTime;\n\n return resp;\n }\n\n @SuppressWarnings(\"rawtypes\")\n public static Class getDescClass() throws InvalidClassException {\n return TCPThroughputDesc.class;\n }\n\n\n @Override\n public MeasurementResult[] call() throws MeasurementError {\n this.taskProgress=TaskProgress.FAILED;\n TCPThroughputDesc desc = (TCPThroughputDesc)measurementDesc;\n\n // Apply MLabNS lookup to fetch FQDN\n if (!desc.target.equals(MLabNS.TARGET)) {\n Logger.i(\"Not using MLab server!\");\n throw new InvalidParameterException(\"Unknown target \" + desc.target +\n \" for TCPThroughput\");\n }\n\n try {\n ArrayList mlabResult = MLabNS.Lookup(context, \"mobiperf\");\n if (mlabResult.size() == 1) {\n desc.target = mlabResult.get(0);\n } else {\n throw new MeasurementError(\"Invalid MLabNS result\");\n }\n } catch (InvalidParameterException e) {\n throw new MeasurementError(e.getMessage());\n }\n Logger.i(\"Setting target to: \" + desc.target);\n\n PhoneUtils phoneUtils = PhoneUtils.getPhoneUtils();\n\n // reset the data limit if the phone is under Wifi\n if (phoneUtils.getNetwork().equals(phoneUtils.NETWORK_WIFI)) {\n Logger.i(\"Detect Wifi network\");\n this.DATA_LIMIT_ON = false;\n }\n\n Logger.i(\"Running TCPThroughput on \" + desc.target);\n try {\n // fetch server information\n if (!acquireServerConfig()) {\n throw new MeasurementError(\"Fail to acquire server configuration\");\n }\n Logger.i(\"Server version is \" + this.serverVersion);\n if (desc.dir_up == true) {\n uplink();\n if(stopFlag){\n throw new MeasurementError(\"Cancelled\");\n }\n Logger.i(\"Uplink measurement result is:\");\n }\n else {\n this.taskStartTime = System.currentTimeMillis();\n downlink();\n if(stopFlag){\n throw new MeasurementError(\"Cancelled\");\n }\n Logger.i(\"Downlink measurement result is:\");\n }\n this.taskProgress=TaskProgress.COMPLETED;\n } catch (MeasurementError e) {\n throw e;\n } catch (IOException e) {\n Logger.e(\"Error close the socket for \" + desc.type);\n throw new MeasurementError(\"Error close the socket for \" + desc.type);\n } catch (InterruptedException e) {\n Logger.e(\"Interrupted captured\");\n throw new MeasurementError(\"Task gets interrrupted\");\n }\n\n MeasurementResult result = new MeasurementResult(\n phoneUtils.getDeviceInfo().deviceId,\n phoneUtils.getDeviceProperty(), TCPThroughputTask.TYPE,\n System.currentTimeMillis() * 1000, taskProgress,\n this.measurementDesc);\n // TODO (Haokun): add more results if necessary\n result.addResult(\"tcp_speed_results\", this.samplingResults);\n result.addResult(\"data_limit_exceeded\", this.DATA_LIMIT_EXCEEDED);\n result.addResult(\"duration\", this.taskDuration);\n result.addResult(\"server_version\", this.serverVersion);\n Logger.i(MeasurementJsonConvertor.toJsonString(result));\n MeasurementResult[] mrArray= new MeasurementResult[1];\n mrArray[0]=result;\n return mrArray;\n }\n\n /*****************************************************************\n * Core measurement functions definitions\n *****************************************************************\n * acquire server configuration information\n * 1) m-lab slice version\n * \n * @return: true -- successful acquire data from M-Lab slice\n * @return: false -- failure to acquire data from M-Lab slice\n */\n private boolean acquireServerConfig() throws MeasurementError, IOException,\n InterruptedException {\n Socket tcpSocket = null;\n InputStream iStream = null;\n boolean result = false;\n try {\n tcpSocket = new Socket();\n buildUpSocket(tcpSocket, ((TCPThroughputDesc)measurementDesc).target, \n TCPThroughputTask.PORT_CONFIG);\n iStream = tcpSocket.getInputStream();\n } catch (IOException e) {\n throw new MeasurementError(\"Error open uplink socket at \" + \n ((TCPThroughputDesc)measurementDesc).target + \n \" with port \" +\n TCPThroughputTask.PORT_CONFIG); \n }\n\n try {\n // read from server side configuration\n byte [] resultMsg = new byte[this.BUFFER_SIZE];\n int resultMsgLen = iStream.read(resultMsg, 0, resultMsg.length);\n if (resultMsgLen > 0) {\n // TODO (Haokun): Maybe switch to JSON for multiple acquired data \n // currently use one double number\n this.serverVersion = new String(resultMsg).substring(0, resultMsgLen);\n result = true;\n }\n } catch (IOException e) {\n throw new MeasurementError(\"Error to acquire configuration from \" +\n ((TCPThroughputDesc)measurementDesc).target);\n } finally {\n iStream.close();\n tcpSocket.close();\n Logger.i(\"Close server Config socket\");\n }\n return result;\n }\n\n /* Uplink measurement task\n * @throws IOException \n * @throws InterruptedException \n */\n private void uplink() throws MeasurementError, IOException, InterruptedException {\n Logger.i(\"Start uplink task on \" + ((TCPThroughputDesc)measurementDesc).target);\n Socket tcpSocket = null;\n InputStream iStream = null;\n OutputStream oStream = null;\n\n try {\n tcpSocket = new Socket();\n buildUpSocket(tcpSocket, ((TCPThroughputDesc)measurementDesc).target, \n TCPThroughputTask.PORT_UPLINK);\n oStream = tcpSocket.getOutputStream();\n iStream = tcpSocket.getInputStream();\n } catch (IOException e){\n e.printStackTrace();\n throw new MeasurementError(\"Error open uplink socket at \" + \n ((TCPThroughputDesc)measurementDesc).target + \n \" with port \" +\n TCPThroughputTask.PORT_UPLINK);\n }\n\n long startTime = System.currentTimeMillis();\n long endTime = startTime;\n int data_limit_byte_up =\n (int)(((TCPThroughputDesc)measurementDesc).data_limit_mb_up\n *this.KBYTE*this.KBYTE);\n byte[] uplinkBuffer =\n new byte[((TCPThroughputDesc)measurementDesc).pkt_size_up_bytes];\n this.genRandomByteArray(uplinkBuffer);\n try {\n\n long totalDuration = (long)(this.KSEC*\n ((TCPThroughputDesc)measurementDesc).duration_period_sec +\n ((TCPThroughputDesc)measurementDesc).slow_start_period_sec);\n do {\n\n if(stopFlag){\n throw new MeasurementError(\"Cancelled\");\n }\n\n oStream.write(uplinkBuffer, 0, uplinkBuffer.length);\n oStream.flush();\n endTime = System.currentTimeMillis();\n\n this.totalSendSize += ((TCPThroughputDesc)measurementDesc).pkt_size_up_bytes;\n if (this.DATA_LIMIT_ON &&\n this.totalSendSize >= data_limit_byte_up) {\n Logger.i(\"Detect uplink exceeding limitation \" +\n (double)((TCPThroughputDesc)measurementDesc).data_limit_mb_up + \" MB\");\n this.DATA_LIMIT_EXCEEDED = true;\n break;\n }\n\n // propagate every quarter\n\n } while ((endTime - startTime) < totalDuration);\n\n // convert into seconds\n this.taskDuration = (double)(endTime - startTime) / 1000.0;\n Logger.i(\"Uplink total data comsumption is \" + \n (double)this.totalSendSize/(1024*1024) + \" MB\");\n // send last message with special content\n uplinkBuffer = TCPThroughputTask.UPLINK_FINISH_MSG.getBytes();", "answers": [" oStream.write(uplinkBuffer, 0, uplinkBuffer.length);"], "length": 1937, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "ef3ed1e6-48fd-4dee-a8fb-9ae658fc0e82", "reasoning": "The code is in the uplink() method. After preparing the special finish message by assigning uplinkBuffer = TCPThroughputTask.UPLINK_FINISH_MSG.getBytes(); the next logical step is to actually send this buffer over the socket's output stream. Earlier in the loop they used oStream.write(uplinkBuffer, 0, uplinkBuffer.length);, so the next line should be the same write call for the finish message.", "reasoning_model_answer": "oStream.write(uplinkBuffer, 0, uplinkBuffer.length);", "assistant_with_reasoning": "\nThe code is in the uplink() method. After preparing the special finish message by assigning uplinkBuffer = TCPThroughputTask.UPLINK_FINISH_MSG.getBytes(); the next logical step is to actually send this buffer over the socket's output stream. Earlier in the loop they used oStream.write(uplinkBuffer, 0, uplinkBuffer.length);, so the next line should be the same write call for the finish message.\n\noStream.write(uplinkBuffer, 0, uplinkBuffer.length);", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.802, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 21083, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "oStream.write(uplinkBuffer, 0, uplinkBuffer.length);", "score": 0.95, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "using System;\nusing Microsoft.Xna.Framework;\nusing Microsoft.Xna.Framework.Audio;\nusing Microsoft.Xna.Framework.GamerServices;\nusing Microsoft.Xna.Framework.Graphics;\nusing Microsoft.Xna.Framework.Input;\nusing Microsoft.Xna.Framework.Storage;\nusing Microsoft.Xna.Framework.Content;\nusing IRTaktiks.Components.Playable;\nusing System.Threading;\nusing IRTaktiks.Components.Scenario;\n\nnamespace IRTaktiks.Components.Manager\n{\n /// \n /// Manager of animations.\n /// \n public class AnimationManager\n {\n #region Singleton\n\n /// \n /// The instance of the class.\n /// \n private static AnimationManager InstanceField;\n\n /// \n /// The instance of the class.\n /// \n public static AnimationManager Instance\n {\n get { if (InstanceField == null) InstanceField = new AnimationManager(); return InstanceField; }\n }\n\n /// \n /// Private constructor.\n /// \n private AnimationManager()\n { }\n\n #endregion\n\n #region AnimationType\n\n /// \n /// Type of animations.\n /// \n public enum AnimationType\n {\n /// \n /// Animation for Short attack.\n /// \n Short,\n\n /// \n /// Animation for Long attack.\n /// \n Long,\n\n /// \n /// Animation for Stealth skill.\n /// \n Stealth,\n\n /// \n /// Animation for Ambush skill.\n /// \n Ambush,\n\n /// \n /// Animation for Curse skill.\n /// \n Curse,\n\n /// \n /// Animation for Quick skill.\n /// \n Quick,\n\n /// \n /// Animation for Impact skill.\n /// \n Impact,\n\n /// \n /// Animation for Revenge skill.\n /// \n Revenge,\n\n /// \n /// Animation for Warcry skill.\n /// \n Warcry,\n\n /// \n /// Animation for Insane skill.\n /// \n Insane,\n\n /// \n /// Animation for Reject skill.\n /// \n Reject,\n\n /// \n /// Animation for Might skill.\n /// \n Might,\n\n /// \n /// Animation for Heal skill.\n /// \n Heal,\n\n /// \n /// Animation for Unseal skill.\n /// \n Unseal,\n\n /// \n /// Animation for Barrier skill.\n /// \n Barrier,\n\n /// \n /// Animation for Holy skill.\n /// \n Holy,\n\n /// \n /// Animation for Drain skill.\n /// \n Drain,\n\n /// \n /// Animation for Flame skill.\n /// \n Flame,\n\n /// \n /// Animation for Frost skill.\n /// \n Frost,\n\n /// \n /// Animation for Item usage.\n /// \n Item,\n\n /// \n /// Animation for Elixir.\n /// \n Elixir\n }\n\n #endregion\n\n #region Properties\n\n /// \n /// The particle manager of game.\n /// \n private ParticleManager ParticleManager;\n\n #endregion\n\n #region Initialize\n\n /// \n /// Initializes the animation manager.\n /// \n /// The instance of game.\n public void Initialize(Game game)\n {\n this.ParticleManager = (game as IRTGame).ParticleManager;\n }\n\n #endregion\n\n #region Methods\n\n /// \n /// Do the respective animation in the specified position.\n /// \n /// Type of animation.\n /// The central position of the animation.\n public void QueueAnimation(AnimationType type, Vector2 position)\n {\n object[] parameters = new object[2];\n\n parameters[0] = type;\n parameters[1] = position;\n\n ThreadPool.QueueUserWorkItem(Animate, parameters);\n }\n\n /// \n /// Do some animation.\n /// \n /// Data tranferred across the threads.\n private void Animate(object data)\n {\n object[] parameters = data as object[];\n\n AnimationType type = (AnimationType)parameters[0];\n Vector2 position = (Vector2)parameters[1];\n\n switch (type)\n {\n case AnimationType.Ambush:\n this.Ambush(position);\n break;\n\n case AnimationType.Barrier:\n this.Barrier(position);\n break;\n\n case AnimationType.Curse:\n this.Curse(position);\n break;\n\n case AnimationType.Drain:\n this.Drain(position);\n break;\n\n case AnimationType.Elixir:\n this.Elixir(position);\n break;\n\n case AnimationType.Flame:\n this.Flame(position);\n break;\n\n case AnimationType.Frost:\n this.Frost(position);\n break;\n\n case AnimationType.Heal:\n this.Heal(position);\n break;\n\n case AnimationType.Holy:\n this.Holy(position);\n break;\n\n case AnimationType.Impact:\n this.Impact(position);\n break;\n\n case AnimationType.Insane:\n this.Insane(position);\n break;\n\n case AnimationType.Item:\n this.Item(position);\n break;\n\n case AnimationType.Long:\n this.Long(position);\n break;\n\n case AnimationType.Might:\n this.Might(position);\n break;\n\n case AnimationType.Quick:\n this.Quick(position);\n break;\n\n case AnimationType.Reject:\n this.Reject(position);\n break;\n\n case AnimationType.Revenge:\n this.Revenge(position);\n break;\n\n case AnimationType.Short:\n this.Short(position);\n break;\n\n case AnimationType.Stealth:\n this.Stealth(position);\n break;\n\n case AnimationType.Unseal:\n this.Unseal(position);\n break;\n\n case AnimationType.Warcry:\n this.Warcry(position);\n break;\n }\n }\n\n #endregion\n\n #region Animations\n\n /// \n /// Execute the Animation.\n /// \n /// The target position.\n private void None(Vector2 position)\n {\n int particles = 50;\n float lifeIncrement = 0.1f;\n float totalLife = 2.5f;\n\n Vector2 position1st = new Vector2(position.X - 5, position.Y - 5);\n Vector2 position2nd = new Vector2(position.X - 5, position.Y + 5);\n Vector2 position3rd = new Vector2(position.X + 5, position.Y - 5);\n Vector2 position4th = new Vector2(position.X + 5, position.Y + 5);\n\n this.ParticleManager.Queue(new ParticleEffect(position1st, particles, ParticleEffect.EffectType.Firework, lifeIncrement, totalLife, Color.Tan));\n\n Thread.Sleep(50);\n\n this.ParticleManager.Queue(new ParticleEffect(position2nd, particles, ParticleEffect.EffectType.Firework, lifeIncrement, totalLife, Color.RoyalBlue));\n\n Thread.Sleep(50);\n\n this.ParticleManager.Queue(new ParticleEffect(position3rd, particles, ParticleEffect.EffectType.Firework, lifeIncrement, totalLife, Color.IndianRed));\n\n Thread.Sleep(50);\n\n this.ParticleManager.Queue(new ParticleEffect(position4th, particles, ParticleEffect.EffectType.Firework, lifeIncrement, totalLife, Color.SpringGreen));\n }\n\n /// \n /// Execute the Animation.\n /// \n /// The target position.\n private void Ambush(Vector2 position)\n {\n int sliceParticles = 30;\n int bloodParticles = 25;\n float sliceLifeIncrement = 0.2f;\n float bloodLifeIncrement = 0.3f;\n float sliceTotalLife = 2.5f;\n float bloodTotalLife = 3.0f;\n\n Vector2 slicePosition = new Vector2(position.X - 1, position.Y - 1);\n Vector2 bloodPosition1st = new Vector2(position.X + 1, position.Y + 1);\n Vector2 bloodPosition2st = new Vector2(position.X + 2, position.Y + 2);\n\n this.ParticleManager.Queue(new ParticleEffect(slicePosition, sliceParticles, ParticleEffect.EffectType.Slice, sliceLifeIncrement, sliceTotalLife, Color.Silver));\n\n Thread.Sleep(100);\n\n this.ParticleManager.Queue(new ParticleEffect(bloodPosition1st, bloodParticles, ParticleEffect.EffectType.Flash45, bloodLifeIncrement, bloodTotalLife, Color.Red));\n\n Thread.Sleep(100);\n\n this.ParticleManager.Queue(new ParticleEffect(bloodPosition2st, bloodParticles, ParticleEffect.EffectType.Flash0, bloodLifeIncrement, bloodTotalLife, Color.Red));\n\n\n this.ParticleManager.Queue(new ParticleEffect(slicePosition, sliceParticles, ParticleEffect.EffectType.Slice, sliceLifeIncrement, sliceTotalLife, Color.Silver));\n\n Thread.Sleep(100);\n\n this.ParticleManager.Queue(new ParticleEffect(bloodPosition1st, bloodParticles, ParticleEffect.EffectType.Flash45, bloodLifeIncrement, bloodTotalLife, Color.Red));\n\n Thread.Sleep(100);\n\n this.ParticleManager.Queue(new ParticleEffect(bloodPosition2st, bloodParticles, ParticleEffect.EffectType.Flash0, bloodLifeIncrement, bloodTotalLife, Color.Red));\n }\n\n /// \n /// Execute the Animation.\n /// \n /// The target position.\n private void Barrier(Vector2 position)\n {\n int ringParticles = 50;\n int sphereParticles = 100;\n\n float ringLifeIncrement = 0.1f;\n float sphereLifeIncrement = 0.7f;\n\n float ringTotalLife = 4.5f;\n float sphereTotalLife = 21.0f;\n\n Vector2 position1st = new Vector2(position.X, position.Y);\n\n this.ParticleManager.Queue(new ParticleEffect(position1st, ringParticles, ParticleEffect.EffectType.Ring, ringLifeIncrement, ringTotalLife, Color.Silver));\n \n Thread.Sleep(500);\n\n this.ParticleManager.Queue(new ParticleEffect(position1st, sphereParticles, ParticleEffect.EffectType.Sphere, sphereLifeIncrement, sphereTotalLife, Color.Silver));\n }\n\n /// \n /// Execute the Animation.\n /// \n /// The target position.\n private void Curse(Vector2 position)\n {\n int particles = 50; \n float lifeIncrement = 0.1f;\n float totalLife = 4.5f;\n \n Vector2 position1st = new Vector2(position.X - 12, position.Y + 15);\n Vector2 position2st = new Vector2(position.X - 0, position.Y - 15);\n Vector2 position3st = new Vector2(position.X - 20, position.Y + 0);\n Vector2 position4st = new Vector2(position.X + 12, position.Y + 15);\n Vector2 position5st = new Vector2(position.X + 20, position.Y + 0);\n\n this.ParticleManager.Queue(new ParticleEffect(position1st, particles, ParticleEffect.EffectType.Slice, lifeIncrement, totalLife, Color.Green));\n this.ParticleManager.Queue(new ParticleEffect(position2st, particles, ParticleEffect.EffectType.Slice, lifeIncrement, totalLife, Color.Green));\n this.ParticleManager.Queue(new ParticleEffect(position3st, particles, ParticleEffect.EffectType.Slice, lifeIncrement, totalLife, Color.Green));\n this.ParticleManager.Queue(new ParticleEffect(position4st, particles, ParticleEffect.EffectType.Slice, lifeIncrement, totalLife, Color.Green));\n this.ParticleManager.Queue(new ParticleEffect(position5st, particles, ParticleEffect.EffectType.Slice, lifeIncrement, totalLife, Color.Green)); \n }\n\n /// \n /// Execute the Animation.\n /// \n /// The target position.\n private void Drain(Vector2 position)\n {\n int particles = 50;\n float lifeIncrement = 0.1f;\n float totalLife = 4.5f;\n\n Vector2 position1st = new Vector2(position.X, position.Y);\n\n this.ParticleManager.Queue(new ParticleEffect(position1st, particles, ParticleEffect.EffectType.Pillar, lifeIncrement, totalLife, Color.Red));\n }\n\n /// \n /// Execute the Animation.\n /// \n /// The target position.\n private void Elixir(Vector2 position)\n {\n int particles = 25;\n float lifeIncrement = 0.07f;\n float totalLife = 3.5f;\n \n Vector2 position1st = new Vector2(position.X - 15, position.Y + 15);\n Vector2 position2nd = new Vector2(position.X - 05, position.Y + 05);\n Vector2 position3rd = new Vector2(position.X + 05, position.Y - 05);\n Vector2 position4th = new Vector2(position.X + 15, position.Y - 15);\n\n this.ParticleManager.Queue(new ParticleEffect(position1st, particles, ParticleEffect.EffectType.Flash0, lifeIncrement, totalLife, Color.ForestGreen));\n this.ParticleManager.Queue(new ParticleEffect(position1st, particles, ParticleEffect.EffectType.Flash45, lifeIncrement, totalLife, Color.ForestGreen));\n this.ParticleManager.Queue(new ParticleEffect(position1st, particles, ParticleEffect.EffectType.Flash90, lifeIncrement, totalLife, Color.ForestGreen));\n this.ParticleManager.Queue(new ParticleEffect(position1st, particles, ParticleEffect.EffectType.Flash135, lifeIncrement, totalLife, Color.ForestGreen));\n\n Thread.Sleep(200);\n\n this.ParticleManager.Queue(new ParticleEffect(position2nd, particles, ParticleEffect.EffectType.Flash0, lifeIncrement, totalLife, Color.Crimson));\n this.ParticleManager.Queue(new ParticleEffect(position2nd, particles, ParticleEffect.EffectType.Flash45, lifeIncrement, totalLife, Color.Crimson));\n this.ParticleManager.Queue(new ParticleEffect(position2nd, particles, ParticleEffect.EffectType.Flash90, lifeIncrement, totalLife, Color.Crimson));\n this.ParticleManager.Queue(new ParticleEffect(position2nd, particles, ParticleEffect.EffectType.Flash135, lifeIncrement, totalLife, Color.Crimson));\n\n Thread.Sleep(200);\n\n this.ParticleManager.Queue(new ParticleEffect(position3rd, particles, ParticleEffect.EffectType.Flash0, lifeIncrement, totalLife, Color.Chocolate));\n this.ParticleManager.Queue(new ParticleEffect(position3rd, particles, ParticleEffect.EffectType.Flash45, lifeIncrement, totalLife, Color.Chocolate));\n this.ParticleManager.Queue(new ParticleEffect(position3rd, particles, ParticleEffect.EffectType.Flash90, lifeIncrement, totalLife, Color.Chocolate));\n this.ParticleManager.Queue(new ParticleEffect(position3rd, particles, ParticleEffect.EffectType.Flash135, lifeIncrement, totalLife, Color.Chocolate));\n\n Thread.Sleep(200);\n\n this.ParticleManager.Queue(new ParticleEffect(position4th, particles, ParticleEffect.EffectType.Flash0, lifeIncrement, totalLife, Color.BlueViolet));\n this.ParticleManager.Queue(new ParticleEffect(position4th, particles, ParticleEffect.EffectType.Flash45, lifeIncrement, totalLife, Color.BlueViolet));\n this.ParticleManager.Queue(new ParticleEffect(position4th, particles, ParticleEffect.EffectType.Flash90, lifeIncrement, totalLife, Color.BlueViolet));\n this.ParticleManager.Queue(new ParticleEffect(position4th, particles, ParticleEffect.EffectType.Flash135, lifeIncrement, totalLife, Color.BlueViolet));\n }\n\n /// \n /// Execute the Animation.\n /// \n /// The target position.\n private void Flame(Vector2 position)\n {\n int particles1st = 25;\n int particles2nd = 10;\n int particles3rd = 5;\n float lifeIncrement1st = 0.02f;\n float lifeIncrement2nd = 0.04f;\n float lifeIncrement3rd = 0.06f;\n float totalLife = 3.0f;\n\n Vector2 position1st = new Vector2(position.X - 15, position.Y - 15);\n Vector2 position2nd = new Vector2(position.X - 10, position.Y - 10);\n Vector2 position3rd = new Vector2(position.X - 05, position.Y - 05);\n Vector2 position4th = new Vector2(position.X - 0, position.Y - 0);\n Vector2 position5th = new Vector2(position.X + 05, position.Y - 05);\n Vector2 position6th = new Vector2(position.X + 10, position.Y - 10);\n Vector2 position7th = new Vector2(position.X + 15, position.Y - 15);\n\n this.ParticleManager.Queue(new ParticleEffect(position1st, particles3rd, ParticleEffect.EffectType.Losangle, lifeIncrement3rd, totalLife, Color.Gold));\n this.ParticleManager.Queue(new ParticleEffect(position2nd, particles2nd, ParticleEffect.EffectType.Losangle, lifeIncrement3rd, totalLife, Color.Red));\n this.ParticleManager.Queue(new ParticleEffect(position3rd, particles1st, ParticleEffect.EffectType.Losangle, lifeIncrement2nd, totalLife, Color.Goldenrod));\n this.ParticleManager.Queue(new ParticleEffect(position4th, particles1st, ParticleEffect.EffectType.Firework, lifeIncrement1st, totalLife, Color.Red));\n this.ParticleManager.Queue(new ParticleEffect(position5th, particles1st, ParticleEffect.EffectType.Losangle, lifeIncrement2nd, totalLife, Color.Tomato));\n this.ParticleManager.Queue(new ParticleEffect(position6th, particles2nd, ParticleEffect.EffectType.Losangle, lifeIncrement3rd, totalLife, Color.Goldenrod));\n this.ParticleManager.Queue(new ParticleEffect(position7th, particles3rd, ParticleEffect.EffectType.Losangle, lifeIncrement3rd, totalLife, Color.Gold));\n\n Thread.Sleep(150);\n\n this.ParticleManager.Queue(new ParticleEffect(position1st, particles3rd, ParticleEffect.EffectType.Losangle, lifeIncrement3rd, totalLife, Color.Gold));\n this.ParticleManager.Queue(new ParticleEffect(position2nd, particles2nd, ParticleEffect.EffectType.Firework, lifeIncrement1st, totalLife, Color.Goldenrod));\n this.ParticleManager.Queue(new ParticleEffect(position3rd, particles1st, ParticleEffect.EffectType.Firework, lifeIncrement2nd, totalLife, Color.Red));\n this.ParticleManager.Queue(new ParticleEffect(position4th, particles1st, ParticleEffect.EffectType.Firework, lifeIncrement1st, totalLife, Color.WhiteSmoke));\n this.ParticleManager.Queue(new ParticleEffect(position5th, particles1st, ParticleEffect.EffectType.Firework, lifeIncrement2nd, totalLife, Color.Red));\n this.ParticleManager.Queue(new ParticleEffect(position6th, particles2nd, ParticleEffect.EffectType.Firework, lifeIncrement1st, totalLife, Color.Goldenrod));\n this.ParticleManager.Queue(new ParticleEffect(position7th, particles3rd, ParticleEffect.EffectType.Losangle, lifeIncrement3rd, totalLife, Color.Gold));\n\n Thread.Sleep(150);\n\n this.ParticleManager.Queue(new ParticleEffect(position1st, particles3rd, ParticleEffect.EffectType.Losangle, lifeIncrement3rd, totalLife, Color.Gold));\n this.ParticleManager.Queue(new ParticleEffect(position2nd, particles2nd, ParticleEffect.EffectType.Firework, lifeIncrement3rd, totalLife, Color.Goldenrod));\n this.ParticleManager.Queue(new ParticleEffect(position3rd, particles1st, ParticleEffect.EffectType.Losangle, lifeIncrement2nd, totalLife, Color.Thistle));\n this.ParticleManager.Queue(new ParticleEffect(position4th, particles1st, ParticleEffect.EffectType.Firework, lifeIncrement1st, totalLife, Color.Red));\n this.ParticleManager.Queue(new ParticleEffect(position5th, particles1st, ParticleEffect.EffectType.Losangle, lifeIncrement2nd, totalLife, Color.Thistle));\n this.ParticleManager.Queue(new ParticleEffect(position6th, particles2nd, ParticleEffect.EffectType.Firework, lifeIncrement3rd, totalLife, Color.Goldenrod));\n this.ParticleManager.Queue(new ParticleEffect(position7th, particles3rd, ParticleEffect.EffectType.Losangle, lifeIncrement3rd, totalLife, Color.Gold));\n\n Thread.Sleep(150);\n\n this.ParticleManager.Queue(new ParticleEffect(position1st, particles3rd, ParticleEffect.EffectType.Losangle, lifeIncrement3rd, totalLife, Color.Gold));\n this.ParticleManager.Queue(new ParticleEffect(position2nd, particles2nd, ParticleEffect.EffectType.Firework, lifeIncrement1st, totalLife, Color.Goldenrod));\n this.ParticleManager.Queue(new ParticleEffect(position3rd, particles1st, ParticleEffect.EffectType.Firework, lifeIncrement2nd, totalLife, Color.Red));\n this.ParticleManager.Queue(new ParticleEffect(position4th, particles1st, ParticleEffect.EffectType.Firework, lifeIncrement1st, totalLife, Color.WhiteSmoke));\n this.ParticleManager.Queue(new ParticleEffect(position5th, particles1st, ParticleEffect.EffectType.Firework, lifeIncrement2nd, totalLife, Color.Red));\n this.ParticleManager.Queue(new ParticleEffect(position6th, particles2nd, ParticleEffect.EffectType.Firework, lifeIncrement1st, totalLife, Color.Goldenrod));\n this.ParticleManager.Queue(new ParticleEffect(position7th, particles3rd, ParticleEffect.EffectType.Losangle, lifeIncrement3rd, totalLife, Color.Gold));\n }\n\n /// \n /// Execute the Animation.\n /// \n /// The target position.\n private void Frost(Vector2 position)\n {\n int particles1st = 25;\n int particles2nd = 10;\n int particles3rd = 5;\n float lifeIncrement1st = 0.02f;\n float lifeIncrement2nd = 0.04f;\n float lifeIncrement3rd = 0.06f;\n float totalLife = 3.0f;\n\n Vector2 position1st = new Vector2(position.X - 15, position.Y - 15);\n Vector2 position2nd = new Vector2(position.X - 10, position.Y - 10);\n Vector2 position3rd = new Vector2(position.X - 05, position.Y - 05);\n Vector2 position4th = new Vector2(position.X - 0, position.Y - 0);\n Vector2 position5th = new Vector2(position.X + 05, position.Y - 05);\n Vector2 position6th = new Vector2(position.X + 10, position.Y - 10);\n Vector2 position7th = new Vector2(position.X + 15, position.Y - 15);\n\n this.ParticleManager.Queue(new ParticleEffect(position1st, particles3rd, ParticleEffect.EffectType.Losangle, lifeIncrement3rd, totalLife, Color.Violet));\n this.ParticleManager.Queue(new ParticleEffect(position2nd, particles2nd, ParticleEffect.EffectType.Losangle, lifeIncrement3rd, totalLife, Color.Aquamarine));\n this.ParticleManager.Queue(new ParticleEffect(position3rd, particles1st, ParticleEffect.EffectType.Losangle, lifeIncrement2nd, totalLife, Color.ForestGreen));\n this.ParticleManager.Queue(new ParticleEffect(position4th, particles1st, ParticleEffect.EffectType.Firework, lifeIncrement1st, totalLife, Color.Wheat));\n this.ParticleManager.Queue(new ParticleEffect(position5th, particles1st, ParticleEffect.EffectType.Losangle, lifeIncrement2nd, totalLife, Color.Aquamarine));\n this.ParticleManager.Queue(new ParticleEffect(position6th, particles2nd, ParticleEffect.EffectType.Losangle, lifeIncrement3rd, totalLife, Color.ForestGreen));\n this.ParticleManager.Queue(new ParticleEffect(position7th, particles3rd, ParticleEffect.EffectType.Losangle, lifeIncrement3rd, totalLife, Color.Violet));\n\n Thread.Sleep(150);\n\n this.ParticleManager.Queue(new ParticleEffect(position1st, particles3rd, ParticleEffect.EffectType.Losangle, lifeIncrement3rd, totalLife, Color.CornflowerBlue));\n this.ParticleManager.Queue(new ParticleEffect(position2nd, particles2nd, ParticleEffect.EffectType.Firework, lifeIncrement1st, totalLife, Color.CadetBlue));\n this.ParticleManager.Queue(new ParticleEffect(position3rd, particles1st, ParticleEffect.EffectType.Firework, lifeIncrement2nd, totalLife, Color.Blue));\n this.ParticleManager.Queue(new ParticleEffect(position4th, particles1st, ParticleEffect.EffectType.Firework, lifeIncrement1st, totalLife, Color.Turquoise));\n this.ParticleManager.Queue(new ParticleEffect(position5th, particles1st, ParticleEffect.EffectType.Firework, lifeIncrement2nd, totalLife, Color.Blue));\n this.ParticleManager.Queue(new ParticleEffect(position6th, particles2nd, ParticleEffect.EffectType.Firework, lifeIncrement1st, totalLife, Color.CadetBlue));\n this.ParticleManager.Queue(new ParticleEffect(position7th, particles3rd, ParticleEffect.EffectType.Losangle, lifeIncrement3rd, totalLife, Color.CornflowerBlue));\n\n Thread.Sleep(150);\n\n this.ParticleManager.Queue(new ParticleEffect(position1st, particles3rd, ParticleEffect.EffectType.Losangle, lifeIncrement3rd, totalLife, Color.DarkBlue));\n this.ParticleManager.Queue(new ParticleEffect(position2nd, particles2nd, ParticleEffect.EffectType.Firework, lifeIncrement3rd, totalLife, Color.CornflowerBlue));\n this.ParticleManager.Queue(new ParticleEffect(position3rd, particles1st, ParticleEffect.EffectType.Losangle, lifeIncrement2nd, totalLife, Color.DarkViolet));\n this.ParticleManager.Queue(new ParticleEffect(position4th, particles1st, ParticleEffect.EffectType.Firework, lifeIncrement1st, totalLife, Color.Blue));\n this.ParticleManager.Queue(new ParticleEffect(position5th, particles1st, ParticleEffect.EffectType.Losangle, lifeIncrement2nd, totalLife, Color.DarkViolet));\n this.ParticleManager.Queue(new ParticleEffect(position6th, particles2nd, ParticleEffect.EffectType.Firework, lifeIncrement3rd, totalLife, Color.CornflowerBlue));\n this.ParticleManager.Queue(new ParticleEffect(position7th, particles3rd, ParticleEffect.EffectType.Losangle, lifeIncrement3rd, totalLife, Color.DarkBlue));\n\n Thread.Sleep(150);\n\n this.ParticleManager.Queue(new ParticleEffect(position1st, particles3rd, ParticleEffect.EffectType.Losangle, lifeIncrement3rd, totalLife, Color.CornflowerBlue));\n this.ParticleManager.Queue(new ParticleEffect(position2nd, particles2nd, ParticleEffect.EffectType.Firework, lifeIncrement1st, totalLife, Color.DarkBlue));\n this.ParticleManager.Queue(new ParticleEffect(position3rd, particles1st, ParticleEffect.EffectType.Firework, lifeIncrement2nd, totalLife, Color.CornflowerBlue));\n this.ParticleManager.Queue(new ParticleEffect(position4th, particles1st, ParticleEffect.EffectType.Firework, lifeIncrement1st, totalLife, Color.Blue));\n this.ParticleManager.Queue(new ParticleEffect(position5th, particles1st, ParticleEffect.EffectType.Firework, lifeIncrement2nd, totalLife, Color.DarkViolet));\n this.ParticleManager.Queue(new ParticleEffect(position6th, particles2nd, ParticleEffect.EffectType.Firework, lifeIncrement1st, totalLife, Color.CornflowerBlue));\n this.ParticleManager.Queue(new ParticleEffect(position7th, particles3rd, ParticleEffect.EffectType.Losangle, lifeIncrement3rd, totalLife, Color.DarkBlue));\n }\n\n /// \n /// Execute the Animation.\n /// \n /// The target position.\n private void Heal(Vector2 position)\n {\n int particles = 50;\n float lifeIncrement = 0.07f;\n float totalLife = 5.0f;\n\n Vector2 position1st = new Vector2(position.X - 10, position.Y + 10);\n Vector2 position2nd = new Vector2(position.X + 10, position.Y - 10);\n Vector2 position3rd = new Vector2(position.X + 10, position.Y + 10);\n\n this.ParticleManager.Queue(new ParticleEffect(position1st, particles, ParticleEffect.EffectType.Flash0, lifeIncrement, totalLife, Color.ForestGreen));\n this.ParticleManager.Queue(new ParticleEffect(position1st, particles, ParticleEffect.EffectType.Flash45, lifeIncrement, totalLife, Color.ForestGreen));\n this.ParticleManager.Queue(new ParticleEffect(position1st, particles, ParticleEffect.EffectType.Flash90, lifeIncrement, totalLife, Color.ForestGreen));\n this.ParticleManager.Queue(new ParticleEffect(position1st, particles, ParticleEffect.EffectType.Flash135, lifeIncrement, totalLife, Color.ForestGreen));\n\n Thread.Sleep(200);\n\n this.ParticleManager.Queue(new ParticleEffect(position2nd, particles, ParticleEffect.EffectType.Flash0, lifeIncrement, totalLife, Color.Crimson));\n this.ParticleManager.Queue(new ParticleEffect(position2nd, particles, ParticleEffect.EffectType.Flash45, lifeIncrement, totalLife, Color.Crimson));\n this.ParticleManager.Queue(new ParticleEffect(position2nd, particles, ParticleEffect.EffectType.Flash90, lifeIncrement, totalLife, Color.Crimson));\n this.ParticleManager.Queue(new ParticleEffect(position2nd, particles, ParticleEffect.EffectType.Flash135, lifeIncrement, totalLife, Color.Crimson));\n\n Thread.Sleep(200);\n\n this.ParticleManager.Queue(new ParticleEffect(position3rd, particles, ParticleEffect.EffectType.Flash0, lifeIncrement, totalLife, Color.Chocolate));\n this.ParticleManager.Queue(new ParticleEffect(position3rd, particles, ParticleEffect.EffectType.Flash45, lifeIncrement, totalLife, Color.Chocolate));\n this.ParticleManager.Queue(new ParticleEffect(position3rd, particles, ParticleEffect.EffectType.Flash90, lifeIncrement, totalLife, Color.Chocolate));\n this.ParticleManager.Queue(new ParticleEffect(position3rd, particles, ParticleEffect.EffectType.Flash135, lifeIncrement, totalLife, Color.Chocolate));\n }\n\n /// \n /// Execute the Animation.\n /// \n /// The target position.\n private void Holy(Vector2 position)\n {\n int particles = 50;\n float lifeIncrement = 0.06f;\n float totalLife = 3.0f;\n\n Vector2 horizontalPosition1st = new Vector2(position.X - 0, position.Y + 03);\n Vector2 horizontalPosition2nd = new Vector2(position.X - 0, position.Y + 0);\n Vector2 horizontalPosition3rd = new Vector2(position.X + 0, position.Y - 03); \n Vector2 verticalPosition1st = new Vector2(position.X - 03, position.Y + 0);\n Vector2 verticalPosition2nd = new Vector2(position.X - 0, position.Y + 0);\n Vector2 verticalPosition3rd = new Vector2(position.X + 03, position.Y - 0);\n\n\n this.ParticleManager.Queue(new ParticleEffect(horizontalPosition1st, particles, ParticleEffect.EffectType.Flash0, lifeIncrement, totalLife, Color.Goldenrod));\n this.ParticleManager.Queue(new ParticleEffect(horizontalPosition2nd, particles, ParticleEffect.EffectType.Flash0, lifeIncrement, totalLife, Color.Goldenrod));\n this.ParticleManager.Queue(new ParticleEffect(horizontalPosition3rd, particles, ParticleEffect.EffectType.Flash0, lifeIncrement, totalLife, Color.Goldenrod));\n this.ParticleManager.Queue(new ParticleEffect(verticalPosition1st, particles, ParticleEffect.EffectType.Flash90, lifeIncrement, totalLife, Color.Goldenrod));", "answers": [" this.ParticleManager.Queue(new ParticleEffect(verticalPosition2nd, particles, ParticleEffect.EffectType.Flash90, lifeIncrement, totalLife, Color.Goldenrod));"], "length": 2072, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "14e884a4-49c4-491f-973a-3a0564ffe609", "reasoning": "The Holy method defines six position vectors: three horizontal and three vertical. It already queued the three horizontal positions and the first vertical position (verticalPosition1st) with a Flash90 effect. The next logical step is to queue the second vertical position (verticalPosition2nd) using the same effect parameters, matching the pattern of queuing all defined positions.", "reasoning_model_answer": "this.ParticleManager.Queue(new ParticleEffect(verticalPosition2nd, particles, ParticleEffect.EffectType.Flash90, lifeIncrement, totalLife, Color.Goldenrod));", "assistant_with_reasoning": "\nThe Holy method defines six position vectors: three horizontal and three vertical. It already queued the three horizontal positions and the first vertical position (verticalPosition1st) with a Flash90 effect. The next logical step is to queue the second vertical position (verticalPosition2nd) using the same effect parameters, matching the pattern of queuing all defined positions.\n\nthis.ParticleManager.Queue(new ParticleEffect(verticalPosition2nd, particles, ParticleEffect.EffectType.Flash90, lifeIncrement, totalLife, Color.Goldenrod));", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.506, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 33180, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "this.ParticleManager.Queue(new ParticleEffect(verticalPosition2nd, particles, ParticleEffect.EffectType.Flash90, lifeIncrement, totalLife, Color.Goldenrod));", "score": 0.96, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/*==============================================================================\nCopyright (c) 2013 Disney Research\nAll Rights Reserved.\n==============================================================================*/\n\n// debug display \n#define SHOW_DEBUG \n\nusing UnityEngine;\nusing System;\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Runtime.InteropServices;\n\n\n/// \n/// Defines the AR exposure modes\n/// \npublic enum ARExposureMode\n{\n\tLocked = 0,\n\tAutoExpose = 1,\n\tContinuousAutoExposure = 2,\n}\n\n/// \n/// Defines the AR focus modes\n/// \npublic enum ARFocusMode\n{\n\tLocked = 0,\n\tAutoFocus = 1,\n\tContinuousAutoFocus = 2,\n}\n\n/// \n/// Defines the AR debug modes\n/// \npublic enum ARDebugMode\n{\n\tOff = 0,\n\tGray = 1,\n\tDistance = 2,\n\tCentroidX = 3,\n\tCentroidY = 4,\n\tCentroid0X = 5,\n\tCentroid0Y = 6,\n\tCentroid1X = 7,\n\tCentroid1Y = 8,\n\tKMeans = 9\n}\n\n// Defines the AR feature tracking modes\npublic enum ARFeatureTrackingMode\n{\n\tkMeansCPU = 0,\n\tMomentGPU = 1\n}\n\n/// \n/// SkyePeek Plugin Interface\n/// \npublic class SkyePeek : MonoBehaviour\n{\n\t#region PEEK_IMPORTS\t\n\t\n#if UNITY_IOS && !UNITY_EDITOR\n [DllImport (\"__Internal\")]\n\tprivate static extern void _peekStart(bool useFront, int texId);\n\t\n [DllImport (\"__Internal\")]\n\tprivate static extern void _peekReadPixels(int dstTexId, int srcTexId, int width, int height, IntPtr data);\n\n [DllImport (\"__Internal\")]\n\tprivate static extern void _peekEnd();\n\t\n [DllImport(\"__Internal\")]\n private static extern void _peekSetFocusMode( int focusMode );\n\t\n [DllImport(\"__Internal\")]\n private static extern void _peekSetExposureMode( int exposureMode );\n\t\n [DllImport(\"__Internal\")]\n private static extern float _peekHalf2Float( short sum );\n\t\n#else\n /// \n /// Starts the camera capture\n /// \n private void _peekStart(bool useFront, int texId) {}\n\n /// \n /// Stops the camera capture\n /// \n\tprivate void _peekEnd() {}\n\n /// \n /// Sets the camera focus mode\n /// \n\tprivate void _peekSetFocusMode(int focusMode ) {}\n\n /// \n /// Sets the camera exposure mode\n /// \n\tprivate void _peekSetExposureMode(int exposureMode ) {}\n#endif\n\n /// \n /// Writes a RenderTexture into a Texture2D\n /// \n\tprivate void TextureFromRT(Texture2D dstTex, RenderTexture srcTex)\n\t{\n\t\tint width=dstTex.width;\n\t\tint height=dstTex.height;\n\t\t\n#if UNITY_IOS && !UNITY_EDITOR\n\t\tif (handlePx.IsAllocated) \n\t\t\thandlePx.Free();\n\t\t\n\t\thandlePx = GCHandle.Alloc (curTexData, GCHandleType.Pinned);\n\t\t_peekReadPixels(dstTex.GetNativeTextureID(), srcTex.GetNativeTextureID(), width, height, handlePx.AddrOfPinnedObject());\n#else\n\t\tRenderTexture.active = srcTex;\n\t\tdstTex.ReadPixels(new Rect(0,0, width, height), 0,0, false); \n\t\t//dstTex.Apply(); only need if rendering with this tex\n#endif\n\t\tcurTex=dstTex;\n\t}\n\n /// \n /// Accumulates sum and vol from texture\n /// \n\tprivate void AccumulateFromTex(ref float sum, ref float vol, int x, int y)\n\t{\n#if UNITY_IOS && !UNITY_EDITOR\n\t\tint idx=(y*curTex.width + x)*2;\n\t\tsum += _peekHalf2Float(curTexData[idx++]);\n\t\tvol += _peekHalf2Float(curTexData[idx]);\n#else\n\t\tColor rg=curTex.GetPixel(x,y);\n\t\tsum += rg.r;\n\t\tvol += rg.g;\n#endif\t\n\t}\n\n /// \n /// Frees handles in iOS\n /// \n\tprivate void DoneAccumulation()\n\t{\n#if UNITY_IOS && !UNITY_EDITOR\n\t\tif (handlePx.IsAllocated) \n\t\t\thandlePx.Free();\n#endif\n\t}\n\t\n\t#endregion // PEEK_IMPORTS\n\n #region PUBLIC_METHODS\n\n /// \n /// Disables AR debugging\n /// \n public void DisableDebug(bool disable)\n {\n debugMode = ARDebugMode.Off;\n }\n\n /// \n /// Sets the blimp color\n /// \n public void SetBlimpColor(Color color)\n {\n this.refColor = color;\n }\n\n /// \n /// Starts the camera capture and returns a Texture2D that will have the camera output as it's content\n /// \n public void startCameraCapture( bool useFrontCameraIfAvailable )\n {\n // Create texture that will be updated in the plugin code/webcam\n\t\tMakeVideoTexture();\n\t\t\n if( Application.platform == RuntimePlatform.IPhonePlayer )\n\t\t\t_peekStart( useFrontCameraIfAvailable, videoTexture.GetNativeTextureID() );\n\t}\n\t\n /// \n /// Stops the camera capture\n /// \n public void stopCameraCapture()\n {\n\t\t_peekEnd();\n }\n\t \n /// \n /// Sets the exposure mode. Capture must be started for this to work!\n /// \n public void setExposureMode( ARExposureMode mode )\n {\n\t\t_peekSetExposureMode( (int)mode );\n }\n\t\n /// \n /// Sets the focus mode. Capture must be started for this to work!\n /// \n public void setFocusMode( ARFocusMode mode )\n {\n\t\t_peekSetFocusMode( (int)mode );\n }\n\t\n /// \n /// Updates the materials UV offset to accommodate the texture being placed into the next biggest power of 2 container\n /// \n\tpublic void updateMaterialUVScaleForTexture( Material material, Texture2D texture )\n\t{\n\t\tVector2 textureOffset = new Vector2( (float)texture.width / (float)nearestPowerOfTwo( texture.width ), (float)texture.height / (float)nearestPowerOfTwo( texture.height ) );\n\t\tmaterial.mainTextureScale = textureOffset;\n\t}\n\n #endregion // PUBLIC_METHODS\n\t\n\t#region PUBLIC_MEMBERS\n\t\n\tpublic bool useFrontCamera = false;\n\tpublic ARFocusMode focusMode = ARFocusMode.ContinuousAutoFocus;\n\tpublic ARExposureMode exposureMode = ARExposureMode.ContinuousAutoExposure;\n\t\n\tpublic int videoWidth = 640;\n\tpublic int videoHeight = 480;\n\tpublic int videoFPS = 60;\n\tpublic int numPassSamples = 8;\n\tpublic float offsetScale = 1.0f;\n\tpublic Color refColor;\n\n\tpublic GameObject backdropObj;\n\t\n public Transform blimp;\n\n\tpublic float baseDistance = 40;\n public float initialBlimpDistance;\n\t\n#if SHOW_DEBUG\n\tpublic ARDebugMode debugMode = ARDebugMode.Gray;\n#endif\n\t\n\tpublic ARFeatureTrackingMode trackingMode = ARFeatureTrackingMode.MomentGPU;\n\t\n\tpublic Shader centroid0XShader;\n\tpublic Shader centroid1XShader;\n\tpublic Shader centroid0YShader;\n\tpublic Shader centroid1YShader;\n\t\n#if SHOW_DEBUG\n\tpublic Shader grayShader;\n\tpublic Shader distShader;\n#endif\n\n\t#endregion\n\t\n #region PRIVATE_MEMBERS\n\t[HideInInspector] // Hides var below\n\tpublic Texture2D videoTexture;\n\t\n\tprivate RenderTexture centTex0X=null;\n\tprivate RenderTexture centTex1X=null;\n\tprivate RenderTexture centTex0Y=null;\n\tprivate RenderTexture centTex1Y=null;\n\t\n\t\n#if SHOW_DEBUG\n\tprivate RenderTexture debugRTex=null;\n\tprivate Material grayMaterial=null;\n\tprivate Material distMaterial=null;\n\tprivate Texture2D debugTex=null;\n\tprivate GameObject debugObj;\n#endif\n\t\n\tprivate Texture2D centTexX=null;\n\tprivate Texture2D centTexY=null;\n\t\n\tprivate Texture2D curTex; // used to abstract texture data access\n\tprivate short[] curTexData= new short[256*256*2];\n\tGCHandle handlePx;\n\t\n\tprivate Material cent0XMaterial=null;\n\tprivate Material cent1XMaterial=null;\n\tprivate Material cent0YMaterial=null;\n\tprivate Material cent1YMaterial=null;\n\t\n\tprivate Vector4 offsets0;\n\tprivate Vector4 offsets1;\n\n\tprivate string deviceName;\n\tprivate WebCamTexture wct;\n\t\n private Pixel oldA, oldB, oldC;\n private Vector3 initialScreenPos;\n\t\n\tprivate Vector2 trackingCenter;\n\tprivate float trackingScale;\n\tprivate bool trackingFound=false;\n\tprivate Vector3 lastCenter= new Vector3(0,0,0);\n\n#if UNITY_IOS && !UNITY_EDITOR\n\tprivate static iPhoneGeneration[] unsupportedDevices = \n\t{\n iPhoneGeneration.iPad1Gen,\n iPhoneGeneration.iPhone,\n iPhoneGeneration.iPhone3G,\n iPhoneGeneration.iPhone3GS,\n iPhoneGeneration.iPodTouch1Gen,\n iPhoneGeneration.iPodTouch2Gen,\n iPhoneGeneration.iPodTouch3Gen,\n\t\tiPhoneGeneration.iPhone4,\n iPhoneGeneration.iPodTouch4Gen\n };\n#endif\n\t/// \n\t/// Defines the Pixel struct\n\t/// \n struct Pixel\n {\n public int x, y;\n\n public float DistSquare(Pixel other)\n {\n return (x - other.x) * (x - other.x) + (y - other.y) * (y - other.y);\n }\n\n public Vector2 toVector2()\n {\n return new Vector2(x, y);\n }\n };\n\n /// \n /// Calculates the nearest power of two for a number\n /// \n\tprivate int nearestPowerOfTwo( float number )\n\t{\n\t\tint n = 1;\n\t\t\n\t\twhile( n < number )\n\t\t\tn <<= 1;\n\n\t\treturn n;\n\t}\n\n /// \n /// Sets up debugging objects\n /// \n\tprivate void DebugSetup()\n\t{\n#if SHOW_DEBUG\n\n#if UNITY_IOS && !UNITY_EDITOR\n\t\t//debug.transform.Rotate(270,0,0);\n\t\t//debug.transform.localScale=new Vector3(-1,1,1);\n#else\n\t\t//debugObj.transform.Rotate(90,180,0); \n#endif\n\n\t\tdebugTex = new Texture2D(videoWidth, videoHeight, TextureFormat.RGBA32, false);\n\t\tdebugTex.filterMode = FilterMode.Point;\n\t\t\n\t\tdebugObj = new GameObject(\"Debug\"); \n debugObj.AddComponent(\"GUITexture\");\n\t\tdebugObj.guiTexture.texture = debugTex;\n debugObj.transform.localScale = new Vector3(.06f, .3f, 0f); \n debugObj.transform.position = new Vector3(.06f, .2f, 0f); \n\t\tdebugObj.guiTexture.pixelInset = new Rect(8.0f,8.0f,videoWidth/2,videoHeight/2);\n\t\t\n\t\t//grayShader = Shader.Find(\"Custom/BGRA2Gray\");\n\t\tgrayMaterial = new Material(grayShader);\n\t\t\n\t\t//distShader = Shader.Find (\"Custom/ColorDistance\");\n\t\tdistMaterial = new Material(distShader);\n\n\t\tdebugRTex = new RenderTexture(videoWidth,videoHeight,-1,RenderTextureFormat.ARGB32);\n\t\tdebugRTex.filterMode = FilterMode.Point;\n\n\t\tDebug.Log(initialScreenPos);\n Debug.Log(initialBlimpDistance);\n\t\tDebug.Log (\"Screen:\" + Screen.width + \",\" + Screen.height + \" Video:\" + videoWidth + \",\" + videoHeight + \" \" + videoFPS );\n#endif\n\t}\n\t\n\tprivate void DebugUpdate()\n\t{\n\t\tif (debugMode==ARDebugMode.Off)\t\t\t\tdebugObj.SetActive(false);\n\t\telse\n\t\t{\n\t\t\tif (!debugObj.activeSelf)\t\t\t\t\tdebugObj.SetActive(true);\n\t\t\t\t\n\t\t\tswitch (debugMode)\n\t\t\t{\n\t\t\tcase ARDebugMode.KMeans\t\t\t\t\t:\tdebugObj.guiTexture.texture = debugTex;\t\t\tbreak;\n\t\t\tcase ARDebugMode.CentroidX\t\t\t\t:\tdebugObj.guiTexture.texture = centTexX;\t\t\tbreak;\n\t\t\tcase ARDebugMode.Centroid0X\t\t\t\t:\tdebugObj.guiTexture.texture = centTex0X;\t\tbreak;\n\t\t\tcase ARDebugMode.Centroid1X\t\t\t\t:\tdebugObj.guiTexture.texture = centTex1X;\t\tbreak;\n\t\t\tcase ARDebugMode.CentroidY \t\t\t\t:\tdebugObj.guiTexture.texture = centTexY;\t\t\tbreak;\n\t\t\tcase ARDebugMode.Centroid0Y \t\t\t:\tdebugObj.guiTexture.texture = centTex0Y;\t\tbreak;\n\t\t\tcase ARDebugMode.Centroid1Y \t\t\t:\tdebugObj.guiTexture.texture = centTex1Y;\t\tbreak;\n\t\t\tcase ARDebugMode.Gray\t\t\t\t\t:\tdebugObj.guiTexture.texture = debugRTex;\t\tbreak;\n\t\t\tcase ARDebugMode.Distance\t\t\t\t:\tdebugObj.guiTexture.texture = debugRTex;\t\tbreak;\n\t\t\tdefault : debugObj.guiTexture.texture = videoTexture;\t\t\tbreak;\n\t\t\t}\n\t\t}\t\t\n\t}\n\n /// \n /// Sets up a Texture2D for video capturing\n /// \n\tprivate void MakeVideoTexture()\n\t{\n#if UNITY_IOS && !UNITY_EDITOR\n\t\tvideoTexture = new Texture2D( videoWidth, videoHeight, TextureFormat.BGRA32, false);\n\t\tbackdropObj.guiTexture.texture = videoTexture;\n\t\tbackdropObj.transform.localScale=new Vector3(1,-1,1);\t\t\n#else\n\t\tvideoTexture = new Texture2D( videoWidth, videoHeight, TextureFormat.RGBA32, false);\n\t\t\n\n\t\tWebCamDevice[] cameras = WebCamTexture.devices;\n if ((cameras != null) && (cameras.Length > 0))\n {\t\t\t\n\t\t\tdeviceName = cameras[cameras.Length-1].name;\n\t\t\twct = new WebCamTexture(deviceName, videoWidth, videoHeight, videoFPS);\n\t\t\tbackdropObj.guiTexture.texture = wct;\n\t\t\twct.Play();\n\t\t\tDebug.Log(\"Created web cam texture\");\n\t\t}\n\t\telse\n\t\t\tDebug.Log(\"No cameras \" + cameras.Length);\n\n#endif // UNITY_IOS/EDITOR\n\t\tvideoTexture.filterMode = FilterMode.Point;\n\t}\n\n /// \n /// For PC (not iphone): ensure that webcam image is in video texture\n /// \n\tvoid UpdateVideoTexture()\n\t{\n#if UNITY_EDITOR || !UNITY_IOS\n\t\tif (wct!=null && wct.isPlaying && wct.didUpdateThisFrame)\n\t\t{\n\t\t\tColor[] textureData = wct.GetPixels();\n\t \n\t\t\tif (textureData!=null)\n\t\t\t{\n\t \t\tvideoTexture.SetPixels(textureData);\n\t \t\tvideoTexture.Apply();\n\t\t\t}\n\t\t}\n#endif\n\t}\n\t\n /// \n /// Creates the centroid texture using grayscale image and scaling down\n /// \n\tvoid MakeCentroidTexture()\n\t{\n#if UNITY_IOS && !UNITY_EDITOR\n\t\tforeach (iPhoneGeneration gen in unsupportedDevices)\n\t\t{\n\t\t\tif (gen == iPhone.generation)\n\t\t\t{\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n#endif\t\t\n\t\t// these have to be manually assigned for the build to include them...\n\t\t//centroid0XShader=Shader.Find(\"Custom/Centroid0X\");\n\t\t//centroid0YShader=Shader.Find(\"Custom/Centroid0Y\");\n\t\t//centroid1XShader=Shader.Find(\"Custom/Centroid1X\");\n\t\t//centroid1YShader=Shader.Find(\"Custom/Centroid1Y\");\n\t\tcent0XMaterial=new Material(centroid0XShader);\n\t\tcent1XMaterial=new Material(centroid1XShader);\n\t\tcent0YMaterial=new Material(centroid0YShader);\n\t\tcent1YMaterial=new Material(centroid1YShader);\n\t\t\n\t\tint passXSamples = numPassSamples;\n\t\tint passYSamples = numPassSamples;\n\t\t//int totalPassSamples = passXSamples*passYSamples;\n\t\tint passWidth = videoWidth/passXSamples;\n\t\tint passHeight = videoHeight/passYSamples;\n\t\tDebug.Log(\"Centroid texture axes pass 0:\" + passWidth + \",\" + passHeight);\n\t\t\n\t\toffsets0 = new Vector4(offsetScale/videoWidth,offsetScale/videoHeight,offsetScale/videoWidth,offsetScale/videoHeight);\n\t\tcent0XMaterial.SetVector (\"offsets\", offsets0);\n\t\tcent0YMaterial.SetVector (\"offsets\", offsets0);\n\t\t\t\n\t\tcentTex0X = new RenderTexture(passWidth,videoHeight,-1,RenderTextureFormat.RGHalf);\n\t\tcentTex0X.filterMode=FilterMode.Point;\n\t\tcentTex0Y = new RenderTexture(videoWidth,passHeight,-1,RenderTextureFormat.RGHalf);\n\t\tcentTex0Y.filterMode=FilterMode.Point;\n\t\t\n\t\toffsets1 = new Vector4(offsetScale/passWidth,offsetScale/passHeight,offsetScale/passWidth,offsetScale/passHeight);\n\t\tcent1XMaterial.SetVector(\"offsets\", offsets1);\n\t\tcent1YMaterial.SetVector(\"offsets\", offsets1);\n\n\t\tpassWidth/=passXSamples;\n\t\tpassHeight/=passYSamples;\n\t\tDebug.Log(\"Centroid texture axes pass 1:\" + passWidth + \",\" + passHeight);\n\t\t\n\t\tcentTex1X = new RenderTexture(passWidth,videoHeight,-1,RenderTextureFormat.RGHalf);\n\t\tcentTex1X.filterMode=FilterMode.Point;\n\t\tcentTex1Y = new RenderTexture(videoWidth,passHeight,-1,RenderTextureFormat.RGHalf);\n\t\tcentTex1Y.filterMode=FilterMode.Point;\n\n\t\t// converting RenderTexture to texture2D\n\t\tcentTexX = new Texture2D(passWidth,videoHeight);\n\t\tcentTexX.filterMode=FilterMode.Point;\n\t\tcentTexY = new Texture2D(videoWidth,passHeight);\n\t\tcentTexY.filterMode=FilterMode.Point;\n\t}\n\t\t\n /// \n /// Calculates the centroid for the momentGPU tracking method\n /// \n\tvoid CalculateCentroid()\n\t{\n#if UNITY_IOS && !UNITY_EDITOR\n\t\tforeach (iPhoneGeneration gen in unsupportedDevices)\n\t\t{\n\t\t\tif (gen == iPhone.generation)\n\t\t\t{\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n#endif\n\t\tif (!centTex0X.IsCreated())\tcentTex0X.Create();\n\t\tif (!centTex0Y.IsCreated())\tcentTex0Y.Create();\n\t\tif (!centTex1X.IsCreated())\tcentTex1X.Create();\n\t\tif (!centTex1Y.IsCreated())\tcentTex1Y.Create();\n\t\t\n\t\tcent0XMaterial.SetColor(\"_Color\",refColor);\n\t\tcent0YMaterial.SetColor(\"_Color\",refColor);\n\t\tcent1XMaterial.SetColor(\"_Color\",refColor);\n\t\tcent1YMaterial.SetColor(\"_Color\",refColor);\n\t\t\n\t\t// 2-pass accumulating downsample: sum up all the gray scale values\n\t\tGraphics.Blit(videoTexture, centTex0X, cent0XMaterial);\n\t\tGraphics.Blit(centTex0X, centTex1X, cent1XMaterial);\n\n\t\tTextureFromRT(centTexX, centTex1X);\n\n\t\tfloat[] sumsX = new float[videoHeight];\n\t\tfloat[] volX = new float[videoHeight];\n\t\tfor (int y=0; y0.0f)\n\t\t\t{\n\t\t\t\tavgX+=sumsX[y]/volX[y];\n\t\t\t\thitX+=1.0f;\n\t\t\t}\n\t\t}\n\t\tavgX/=hitX;\n\t\t\t\t\t\n\t\tGraphics.Blit(videoTexture, centTex0Y, cent0YMaterial);", "answers": ["\t\tGraphics.Blit(centTex0Y, centTex1Y, cent1YMaterial);"], "length": 1564, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "bba427d4-2816-45f2-a29c-462d7c3eb77f", "reasoning": "In the CalculateCentroid method, after completing the X-pass processing, the code begins the Y-pass by blitting the video texture into centTex0Y using cent0YMaterial. The next logical step mirrors the X-pass: blit centTex0Y into centTex1Y using cent1YMaterial to continue the two-pass downsampling for the Y axis.", "reasoning_model_answer": "Graphics.Blit(centTex0Y, centTex1Y, cent1YMaterial);", "assistant_with_reasoning": "\nIn the CalculateCentroid method, after completing the X-pass processing, the code begins the Y-pass by blitting the video texture into centTex0Y using cent0YMaterial. The next logical step mirrors the X-pass: blit centTex0Y into centTex1Y using cent1YMaterial to continue the two-pass downsampling for the Y axis.\n\nGraphics.Blit(centTex0Y, centTex1Y, cent1YMaterial);", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.766, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 16298, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "Graphics.Blit(centTex0Y, centTex1Y, cent1YMaterial);", "score": 0.98, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "using Lucene.Net.Analysis;\nusing Lucene.Net.Analysis.TokenAttributes;\nusing Lucene.Net.Documents;\nusing Lucene.Net.Support;\nusing Lucene.Net.Support.Threading;\nusing Lucene.Net.Util;\nusing NUnit.Framework;\nusing System;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.IO;\nusing System.Text;\nusing Console = Lucene.Net.Support.SystemConsole;\n\nnamespace Lucene.Net.Index\n{\n /*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n using BytesRef = Lucene.Net.Util.BytesRef;\n using Directory = Lucene.Net.Store.Directory;\n using DocIdSetIterator = Lucene.Net.Search.DocIdSetIterator;\n using Document = Documents.Document;\n using Field = Field;\n using IBits = Lucene.Net.Util.IBits;\n using LuceneTestCase = Lucene.Net.Util.LuceneTestCase;\n using PayloadAttribute = Lucene.Net.Analysis.TokenAttributes.PayloadAttribute;\n using TestUtil = Lucene.Net.Util.TestUtil;\n using TextField = TextField;\n\n [TestFixture]\n public class TestPayloads : LuceneTestCase\n {\n // Simple tests to test the payloads\n [Test]\n public virtual void TestPayload()\n {\n BytesRef payload = new BytesRef(\"this is a test!\");\n Assert.AreEqual(payload.Length, \"this is a test!\".Length, \"Wrong payload length.\");\n\n BytesRef clone = (BytesRef)payload.Clone();\n Assert.AreEqual(payload.Length, clone.Length);\n for (int i = 0; i < payload.Length; i++)\n {\n Assert.AreEqual(payload.Bytes[i + payload.Offset], clone.Bytes[i + clone.Offset]);\n }\n }\n\n // Tests whether the DocumentWriter and SegmentMerger correctly enable the\n // payload bit in the FieldInfo\n [Test]\n public virtual void TestPayloadFieldBit()\n {\n Directory ram = NewDirectory();\n PayloadAnalyzer analyzer = new PayloadAnalyzer();\n IndexWriter writer = new IndexWriter(ram, NewIndexWriterConfig(TEST_VERSION_CURRENT, analyzer));\n Document d = new Document();\n // this field won't have any payloads\n d.Add(NewTextField(\"f1\", \"this field has no payloads\", Field.Store.NO));\n // this field will have payloads in all docs, however not for all term positions,\n // so this field is used to check if the DocumentWriter correctly enables the payloads bit\n // even if only some term positions have payloads\n d.Add(NewTextField(\"f2\", \"this field has payloads in all docs\", Field.Store.NO));\n d.Add(NewTextField(\"f2\", \"this field has payloads in all docs NO PAYLOAD\", Field.Store.NO));\n // this field is used to verify if the SegmentMerger enables payloads for a field if it has payloads\n // enabled in only some documents\n d.Add(NewTextField(\"f3\", \"this field has payloads in some docs\", Field.Store.NO));\n // only add payload data for field f2\n#pragma warning disable 612, 618\n analyzer.SetPayloadData(\"f2\", \"somedata\".GetBytes(IOUtils.CHARSET_UTF_8), 0, 1);\n#pragma warning restore 612, 618\n writer.AddDocument(d);\n // flush\n writer.Dispose();\n\n SegmentReader reader = GetOnlySegmentReader(DirectoryReader.Open(ram));\n FieldInfos fi = reader.FieldInfos;\n Assert.IsFalse(fi.FieldInfo(\"f1\").HasPayloads, \"Payload field bit should not be set.\");\n Assert.IsTrue(fi.FieldInfo(\"f2\").HasPayloads, \"Payload field bit should be set.\");\n Assert.IsFalse(fi.FieldInfo(\"f3\").HasPayloads, \"Payload field bit should not be set.\");\n reader.Dispose();\n\n // now we add another document which has payloads for field f3 and verify if the SegmentMerger\n // enabled payloads for that field\n analyzer = new PayloadAnalyzer(); // Clear payload state for each field\n writer = new IndexWriter(ram, NewIndexWriterConfig(TEST_VERSION_CURRENT, analyzer).SetOpenMode(OpenMode.CREATE));\n d = new Document();\n d.Add(NewTextField(\"f1\", \"this field has no payloads\", Field.Store.NO));\n d.Add(NewTextField(\"f2\", \"this field has payloads in all docs\", Field.Store.NO));\n d.Add(NewTextField(\"f2\", \"this field has payloads in all docs\", Field.Store.NO));\n d.Add(NewTextField(\"f3\", \"this field has payloads in some docs\", Field.Store.NO));\n // add payload data for field f2 and f3\n#pragma warning disable 612, 618\n analyzer.SetPayloadData(\"f2\", \"somedata\".GetBytes(IOUtils.CHARSET_UTF_8), 0, 1);\n analyzer.SetPayloadData(\"f3\", \"somedata\".GetBytes(IOUtils.CHARSET_UTF_8), 0, 3);\n#pragma warning restore 612, 618\n writer.AddDocument(d);\n\n // force merge\n writer.ForceMerge(1);\n // flush\n writer.Dispose();\n\n reader = GetOnlySegmentReader(DirectoryReader.Open(ram));\n fi = reader.FieldInfos;\n Assert.IsFalse(fi.FieldInfo(\"f1\").HasPayloads, \"Payload field bit should not be set.\");\n Assert.IsTrue(fi.FieldInfo(\"f2\").HasPayloads, \"Payload field bit should be set.\");\n Assert.IsTrue(fi.FieldInfo(\"f3\").HasPayloads, \"Payload field bit should be set.\");\n reader.Dispose();\n ram.Dispose();\n }\n\n // Tests if payloads are correctly stored and loaded using both RamDirectory and FSDirectory\n [Test]\n public virtual void TestPayloadsEncoding()\n {\n Directory dir = NewDirectory();\n PerformTest(dir);\n dir.Dispose();\n }\n\n // builds an index with payloads in the given Directory and performs\n // different tests to verify the payload encoding\n private void PerformTest(Directory dir)\n {\n PayloadAnalyzer analyzer = new PayloadAnalyzer();\n IndexWriter writer = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, analyzer).SetOpenMode(OpenMode.CREATE).SetMergePolicy(NewLogMergePolicy()));\n\n // should be in sync with value in TermInfosWriter\n const int skipInterval = 16;\n\n const int numTerms = 5;\n const string fieldName = \"f1\";\n\n int numDocs = skipInterval + 1;\n // create content for the test documents with just a few terms\n Term[] terms = GenerateTerms(fieldName, numTerms);\n StringBuilder sb = new StringBuilder();\n for (int i = 0; i < terms.Length; i++)\n {\n sb.Append(terms[i].Text());\n sb.Append(\" \");\n }\n string content = sb.ToString();\n\n int payloadDataLength = numTerms * numDocs * 2 + numTerms * numDocs * (numDocs - 1) / 2;\n var payloadData = GenerateRandomData(payloadDataLength);\n\n Document d = new Document();\n d.Add(NewTextField(fieldName, content, Field.Store.NO));\n // add the same document multiple times to have the same payload lengths for all\n // occurrences within two consecutive skip intervals\n int offset = 0;\n for (int i = 0; i < 2 * numDocs; i++)\n {\n analyzer = new PayloadAnalyzer(fieldName, payloadData, offset, 1);\n offset += numTerms;\n writer.AddDocument(d, analyzer);\n }\n\n // make sure we create more than one segment to test merging\n writer.Commit();\n\n // now we make sure to have different payload lengths next at the next skip point\n for (int i = 0; i < numDocs; i++)\n {\n analyzer = new PayloadAnalyzer(fieldName, payloadData, offset, i);\n offset += i * numTerms;\n writer.AddDocument(d, analyzer);\n }\n\n writer.ForceMerge(1);\n // flush\n writer.Dispose();\n\n /*\n * Verify the index\n * first we test if all payloads are stored correctly\n */\n IndexReader reader = DirectoryReader.Open(dir);\n\n var verifyPayloadData = new byte[payloadDataLength];\n offset = 0;\n var tps = new DocsAndPositionsEnum[numTerms];\n for (int i = 0; i < numTerms; i++)\n {\n tps[i] = MultiFields.GetTermPositionsEnum(reader, MultiFields.GetLiveDocs(reader), terms[i].Field, new BytesRef(terms[i].Text()));\n }\n\n while (tps[0].NextDoc() != DocIdSetIterator.NO_MORE_DOCS)\n {\n for (int i = 1; i < numTerms; i++)\n {\n tps[i].NextDoc();\n }\n int freq = tps[0].Freq;\n\n for (int i = 0; i < freq; i++)\n {\n for (int j = 0; j < numTerms; j++)\n {\n tps[j].NextPosition();\n BytesRef br = tps[j].GetPayload();\n if (br != null)\n {\n Array.Copy(br.Bytes, br.Offset, verifyPayloadData, offset, br.Length);\n offset += br.Length;\n }\n }\n }\n }\n\n AssertByteArrayEquals(payloadData, verifyPayloadData);\n\n /*\n * test lazy skipping\n */\n DocsAndPositionsEnum tp = MultiFields.GetTermPositionsEnum(reader, MultiFields.GetLiveDocs(reader), terms[0].Field, new BytesRef(terms[0].Text()));\n tp.NextDoc();\n tp.NextPosition();\n // NOTE: prior rev of this test was failing to first\n // call next here:\n tp.NextDoc();\n // now we don't read this payload\n tp.NextPosition();\n BytesRef payload = tp.GetPayload();\n Assert.AreEqual(1, payload.Length, \"Wrong payload length.\");\n Assert.AreEqual(payload.Bytes[payload.Offset], payloadData[numTerms]);\n tp.NextDoc();\n tp.NextPosition();\n\n // we don't read this payload and skip to a different document\n tp.Advance(5);\n tp.NextPosition();\n payload = tp.GetPayload();\n Assert.AreEqual(1, payload.Length, \"Wrong payload length.\");\n Assert.AreEqual(payload.Bytes[payload.Offset], payloadData[5 * numTerms]);\n\n /*\n * Test different lengths at skip points\n */\n tp = MultiFields.GetTermPositionsEnum(reader, MultiFields.GetLiveDocs(reader), terms[1].Field, new BytesRef(terms[1].Text()));\n tp.NextDoc();\n tp.NextPosition();\n Assert.AreEqual(1, tp.GetPayload().Length, \"Wrong payload length.\");\n tp.Advance(skipInterval - 1);\n tp.NextPosition();\n Assert.AreEqual(1, tp.GetPayload().Length, \"Wrong payload length.\");\n tp.Advance(2 * skipInterval - 1);\n tp.NextPosition();\n Assert.AreEqual(1, tp.GetPayload().Length, \"Wrong payload length.\");\n tp.Advance(3 * skipInterval - 1);\n tp.NextPosition();\n Assert.AreEqual(3 * skipInterval - 2 * numDocs - 1, tp.GetPayload().Length, \"Wrong payload length.\");\n\n reader.Dispose();\n\n // test long payload\n analyzer = new PayloadAnalyzer();\n writer = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, analyzer).SetOpenMode(OpenMode.CREATE));\n string singleTerm = \"lucene\";\n\n d = new Document();\n d.Add(NewTextField(fieldName, singleTerm, Field.Store.NO));\n // add a payload whose length is greater than the buffer size of BufferedIndexOutput\n payloadData = GenerateRandomData(2000);\n analyzer.SetPayloadData(fieldName, payloadData, 100, 1500);\n writer.AddDocument(d);\n\n writer.ForceMerge(1);\n // flush\n writer.Dispose();\n\n reader = DirectoryReader.Open(dir);\n tp = MultiFields.GetTermPositionsEnum(reader, MultiFields.GetLiveDocs(reader), fieldName, new BytesRef(singleTerm));\n tp.NextDoc();\n tp.NextPosition();\n\n BytesRef bref = tp.GetPayload();\n verifyPayloadData = new byte[bref.Length];\n var portion = new byte[1500];\n Array.Copy(payloadData, 100, portion, 0, 1500);\n\n AssertByteArrayEquals(portion, bref.Bytes, bref.Offset, bref.Length);\n reader.Dispose();\n }\n\n#pragma warning disable 612, 618\n internal static readonly Encoding Utf8 = IOUtils.CHARSET_UTF_8;\n#pragma warning restore 612, 618\n\n private void GenerateRandomData(byte[] data)\n {\n // this test needs the random data to be valid unicode\n string s = TestUtil.RandomFixedByteLengthUnicodeString(Random(), data.Length);\n var b = s.GetBytes(Utf8);\n Debug.Assert(b.Length == data.Length);\n System.Buffer.BlockCopy(b, 0, data, 0, b.Length);\n }\n\n private byte[] GenerateRandomData(int n)\n {\n var data = new byte[n];\n GenerateRandomData(data);\n return data;\n }\n\n private Term[] GenerateTerms(string fieldName, int n)\n {\n int maxDigits = (int)(Math.Log(n) / Math.Log(10));\n Term[] terms = new Term[n];\n StringBuilder sb = new StringBuilder();\n for (int i = 0; i < n; i++)\n {\n sb.Length = 0;\n sb.Append(\"t\");\n int zeros = maxDigits - (int)(Math.Log(i) / Math.Log(10));\n for (int j = 0; j < zeros; j++)\n {\n sb.Append(\"0\");\n }\n sb.Append(i);\n terms[i] = new Term(fieldName, sb.ToString());\n }\n return terms;\n }\n\n internal virtual void AssertByteArrayEquals(byte[] b1, byte[] b2)\n {\n if (b1.Length != b2.Length)\n {\n Assert.Fail(\"Byte arrays have different lengths: \" + b1.Length + \", \" + b2.Length);\n }\n\n for (int i = 0; i < b1.Length; i++)\n {\n if (b1[i] != b2[i])\n {\n Assert.Fail(\"Byte arrays different at index \" + i + \": \" + b1[i] + \", \" + b2[i]);\n }\n }\n }\n\n internal virtual void AssertByteArrayEquals(byte[] b1, byte[] b2, int b2offset, int b2length)\n {\n if (b1.Length != b2length)\n {\n Assert.Fail(\"Byte arrays have different lengths: \" + b1.Length + \", \" + b2length);\n }\n\n for (int i = 0; i < b1.Length; i++)\n {\n if (b1[i] != b2[b2offset + i])\n {\n Assert.Fail(\"Byte arrays different at index \" + i + \": \" + b1[i] + \", \" + b2[b2offset + i]);\n }\n }\n }\n\n /// \n /// this Analyzer uses an WhitespaceTokenizer and PayloadFilter.\n /// \n private class PayloadAnalyzer : Analyzer\n {\n internal readonly IDictionary FieldToData = new Dictionary();\n\n public PayloadAnalyzer()\n : base(PER_FIELD_REUSE_STRATEGY)\n {\n }\n\n public PayloadAnalyzer(string field, byte[] data, int offset, int length)\n : base(PER_FIELD_REUSE_STRATEGY)\n {\n SetPayloadData(field, data, offset, length);\n }\n\n internal virtual void SetPayloadData(string field, byte[] data, int offset, int length)\n {\n FieldToData[field] = new PayloadData(data, offset, length);\n }\n\n protected internal override TokenStreamComponents CreateComponents(string fieldName, TextReader reader)\n {\n PayloadData payload;\n FieldToData.TryGetValue(fieldName, out payload);\n Tokenizer ts = new MockTokenizer(reader, MockTokenizer.WHITESPACE, false);\n TokenStream tokenStream = (payload != null) ? (TokenStream)new PayloadFilter(ts, payload.Data, payload.Offset, payload.Length) : ts;\n return new TokenStreamComponents(ts, tokenStream);\n }\n\n internal class PayloadData\n {\n internal byte[] Data;\n internal int Offset;\n internal int Length;\n\n internal PayloadData(byte[] data, int offset, int length)\n {\n this.Data = data;\n this.Offset = offset;\n this.Length = length;\n }\n }\n }\n\n /// \n /// this Filter adds payloads to the tokens.\n /// \n private class PayloadFilter : TokenFilter\n {\n internal byte[] Data;\n internal int Length;\n internal int Offset;\n internal int StartOffset;\n internal IPayloadAttribute PayloadAtt;\n internal ICharTermAttribute TermAttribute;\n\n public PayloadFilter(TokenStream @in, byte[] data, int offset, int length)\n : base(@in)\n {\n this.Data = data;\n this.Length = length;\n this.Offset = offset;\n this.StartOffset = offset;\n PayloadAtt = AddAttribute();\n TermAttribute = AddAttribute();\n }\n\n public sealed override bool IncrementToken()\n {\n bool hasNext = m_input.IncrementToken();\n if (!hasNext)\n {\n return false;\n }\n\n // Some values of the same field are to have payloads and others not\n if (Offset + Length <= Data.Length && !TermAttribute.ToString().EndsWith(\"NO PAYLOAD\", StringComparison.Ordinal))\n {\n BytesRef p = new BytesRef(Data, Offset, Length);\n PayloadAtt.Payload = p;\n Offset += Length;\n }\n else\n {\n PayloadAtt.Payload = null;\n }\n\n return true;\n }\n\n public override void Reset()\n {\n base.Reset();\n this.Offset = StartOffset;\n }\n }\n\n [Test]\n public virtual void TestThreadSafety()\n {\n const int numThreads = 5;\n int numDocs = AtLeast(50);\n ByteArrayPool pool = new ByteArrayPool(numThreads, 5);\n\n Directory dir = NewDirectory();\n IndexWriter writer = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())));\n const string field = \"test\";\n\n ThreadClass[] ingesters = new ThreadClass[numThreads];\n for (int i = 0; i < numThreads; i++)\n {\n ingesters[i] = new ThreadAnonymousInnerClassHelper(this, numDocs, pool, writer, field);\n ingesters[i].Start();\n }\n\n for (int i = 0; i < numThreads; i++)\n {\n ingesters[i].Join();\n }\n writer.Dispose();\n IndexReader reader = DirectoryReader.Open(dir);\n TermsEnum terms = MultiFields.GetFields(reader).GetTerms(field).GetIterator(null);\n IBits liveDocs = MultiFields.GetLiveDocs(reader);\n DocsAndPositionsEnum tp = null;\n while (terms.Next() != null)\n {\n string termText = terms.Term.Utf8ToString();\n tp = terms.DocsAndPositions(liveDocs, tp);\n while (tp.NextDoc() != DocIdSetIterator.NO_MORE_DOCS)\n {\n int freq = tp.Freq;\n for (int i = 0; i < freq; i++)\n {\n tp.NextPosition();\n BytesRef payload = tp.GetPayload();\n Assert.AreEqual(termText, payload.Utf8ToString());\n }\n }\n }\n reader.Dispose();\n dir.Dispose();\n Assert.AreEqual(pool.Count, numThreads);\n }\n", "answers": [" private class ThreadAnonymousInnerClassHelper : ThreadClass"], "length": 1924, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "ca287cc5-12de-4c0e-94a2-a63357a1787c", "reasoning": "The TestThreadSafety method ends with its closing brace. In the original Lucene test file, the next code defines the inner helper class used for threading. Therefore the next line is the declaration of that inner class.", "reasoning_model_answer": "private class ThreadAnonymousInnerClassHelper : ThreadClass", "assistant_with_reasoning": "\nThe TestThreadSafety method ends with its closing brace. In the original Lucene test file, the next code defines the inner helper class used for threading. Therefore the next line is the declaration of that inner class.\n\nprivate class ThreadAnonymousInnerClassHelper : ThreadClass", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 7.383, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 2, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 21346, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "private class ThreadAnonymousInnerClassHelper : ThreadClass", "score": 0.94, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "# vim: tabstop=4 shiftwidth=4 softtabstop=4\n\n# Copyright 2012 OpenStack LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nfrom keystone import clean\nfrom keystone.common import kvs\nfrom keystone.common import utils\nfrom keystone import exception\nfrom keystone import identity\n\n\nclass Identity(kvs.Base, identity.Driver):\n # Public interface\n def authenticate(self, user_id=None, tenant_id=None, password=None):\n \"\"\"Authenticate based on a user, tenant and password.\n\n Expects the user object to have a password field and the tenant to be\n in the list of tenants on the user.\n\n \"\"\"\n user_ref = None\n tenant_ref = None\n metadata_ref = {}\n\n try:\n user_ref = self._get_user(user_id)\n except exception.UserNotFound:\n raise AssertionError('Invalid user / password')\n\n if not utils.check_password(password, user_ref.get('password')):\n raise AssertionError('Invalid user / password')\n\n if tenant_id is not None:\n if tenant_id not in self.get_projects_for_user(user_id):\n raise AssertionError('Invalid tenant')\n\n try:\n tenant_ref = self.get_project(tenant_id)\n metadata_ref = self.get_metadata(user_id, tenant_id)\n except exception.ProjectNotFound:\n tenant_ref = None\n metadata_ref = {}\n except exception.MetadataNotFound:\n metadata_ref = {}\n\n return (identity.filter_user(user_ref), tenant_ref, metadata_ref)\n\n def get_project(self, tenant_id):\n try:\n return self.db.get('tenant-%s' % tenant_id)\n except exception.NotFound:\n raise exception.ProjectNotFound(project_id=tenant_id)\n\n def list_projects(self):\n tenant_keys = filter(lambda x: x.startswith(\"tenant-\"),\n self.db.keys())\n return [self.db.get(key) for key in tenant_keys]\n\n def get_project_by_name(self, tenant_name, domain_id):\n try:\n return self.db.get('tenant_name-%s' % tenant_name)\n except exception.NotFound:\n raise exception.ProjectNotFound(project_id=tenant_name)\n\n def get_project_users(self, tenant_id):\n self.get_project(tenant_id)\n user_keys = filter(lambda x: x.startswith(\"user-\"), self.db.keys())\n user_refs = [self.db.get(key) for key in user_keys]\n user_refs = filter(lambda x: tenant_id in x['tenants'], user_refs)\n return [identity.filter_user(user_ref) for user_ref in user_refs]\n\n def _get_user(self, user_id):\n try:\n return self.db.get('user-%s' % user_id)\n except exception.NotFound:\n raise exception.UserNotFound(user_id=user_id)\n\n def _get_user_by_name(self, user_name, domain_id):\n try:\n return self.db.get('user_name-%s' % user_name)\n except exception.NotFound:\n raise exception.UserNotFound(user_id=user_name)\n\n def get_user(self, user_id):\n return identity.filter_user(self._get_user(user_id))\n\n def get_user_by_name(self, user_name, domain_id):\n return identity.filter_user(\n self._get_user_by_name(user_name, domain_id))\n\n def get_metadata(self, user_id=None, tenant_id=None,\n domain_id=None, group_id=None):\n try:\n if user_id:\n if tenant_id:\n return self.db.get('metadata-%s-%s' % (tenant_id,\n user_id))\n else:\n return self.db.get('metadata-%s-%s' % (domain_id,\n user_id))\n else:\n if tenant_id:\n return self.db.get('metadata-%s-%s' % (tenant_id,\n group_id))\n else:\n return self.db.get('metadata-%s-%s' % (domain_id,\n group_id))\n except exception.NotFound:\n raise exception.MetadataNotFound()\n\n def get_role(self, role_id):\n try:\n return self.db.get('role-%s' % role_id)\n except exception.NotFound:\n raise exception.RoleNotFound(role_id=role_id)\n\n def list_users(self):\n user_ids = self.db.get('user_list', [])\n return [self.get_user(x) for x in user_ids]\n\n def list_roles(self):\n role_ids = self.db.get('role_list', [])\n return [self.get_role(x) for x in role_ids]\n\n def get_projects_for_user(self, user_id):\n user_ref = self._get_user(user_id)\n return user_ref.get('tenants', [])\n\n def get_roles_for_user_and_project(self, user_id, tenant_id):\n self.get_user(user_id)\n self.get_project(tenant_id)\n try:\n metadata_ref = self.get_metadata(user_id, tenant_id)\n except exception.MetadataNotFound:\n metadata_ref = {}\n return metadata_ref.get('roles', [])\n\n def add_role_to_user_and_project(self, user_id, tenant_id, role_id):\n self.get_user(user_id)\n self.get_project(tenant_id)\n self.get_role(role_id)\n try:\n metadata_ref = self.get_metadata(user_id, tenant_id)\n except exception.MetadataNotFound:\n metadata_ref = {}\n roles = set(metadata_ref.get('roles', []))\n if role_id in roles:\n msg = ('User %s already has role %s in tenant %s'\n % (user_id, role_id, tenant_id))\n raise exception.Conflict(type='role grant', details=msg)\n roles.add(role_id)\n metadata_ref['roles'] = list(roles)\n self.update_metadata(user_id, tenant_id, metadata_ref)\n\n def remove_role_from_user_and_project(self, user_id, tenant_id, role_id):\n try:\n metadata_ref = self.get_metadata(user_id, tenant_id)\n except exception.MetadataNotFound:\n metadata_ref = {}\n roles = set(metadata_ref.get('roles', []))\n if role_id not in roles:\n msg = 'Cannot remove role that has not been granted, %s' % role_id\n raise exception.RoleNotFound(message=msg)\n\n roles.remove(role_id)\n metadata_ref['roles'] = list(roles)\n\n if not len(roles):\n self.db.delete('metadata-%s-%s' % (tenant_id, user_id))\n user_ref = self._get_user(user_id)\n tenants = set(user_ref.get('tenants', []))\n tenants.remove(tenant_id)\n user_ref['tenants'] = list(tenants)\n self.update_user(user_id, user_ref)\n else:\n self.update_metadata(user_id, tenant_id, metadata_ref)\n\n # CRUD\n def create_user(self, user_id, user):\n user['name'] = clean.user_name(user['name'])\n try:\n self.get_user(user_id)\n except exception.UserNotFound:\n pass\n else:\n msg = 'Duplicate ID, %s.' % user_id\n raise exception.Conflict(type='user', details=msg)\n\n try:\n self.get_user_by_name(user['name'], user['domain_id'])\n except exception.UserNotFound:\n pass\n else:\n msg = 'Duplicate name, %s.' % user['name']\n raise exception.Conflict(type='user', details=msg)\n\n user = utils.hash_user_password(user)\n new_user = user.copy()\n\n new_user.setdefault('groups', [])\n\n self.db.set('user-%s' % user_id, new_user)\n self.db.set('user_name-%s' % new_user['name'], new_user)\n user_list = set(self.db.get('user_list', []))\n user_list.add(user_id)\n self.db.set('user_list', list(user_list))\n return identity.filter_user(new_user)\n\n def update_user(self, user_id, user):\n if 'name' in user:\n user['name'] = clean.user_name(user['name'])\n existing = self.db.get('user_name-%s' % user['name'])\n if existing and user_id != existing['id']:\n msg = 'Duplicate name, %s.' % user['name']\n raise exception.Conflict(type='user', details=msg)\n # get the old name and delete it too\n try:\n old_user = self.db.get('user-%s' % user_id)\n except exception.NotFound:\n raise exception.UserNotFound(user_id=user_id)\n new_user = old_user.copy()\n user = utils.hash_user_password(user)\n new_user.update(user)\n if new_user['id'] != user_id:\n raise exception.ValidationError('Cannot change user ID')\n self.db.delete('user_name-%s' % old_user['name'])\n self.db.set('user-%s' % user_id, new_user)\n self.db.set('user_name-%s' % new_user['name'], new_user)\n return new_user\n\n def add_user_to_group(self, user_id, group_id):\n self.get_group(group_id)\n user_ref = self._get_user(user_id)\n groups = set(user_ref.get('groups', []))\n groups.add(group_id)\n self.update_user(user_id, {'groups': list(groups)})\n\n def check_user_in_group(self, user_id, group_id):\n self.get_group(group_id)\n user_ref = self._get_user(user_id)\n if group_id not in set(user_ref.get('groups', [])):\n raise exception.NotFound(_('User not found in group'))\n\n def remove_user_from_group(self, user_id, group_id):\n self.get_group(group_id)\n user_ref = self._get_user(user_id)\n groups = set(user_ref.get('groups', []))\n try:\n groups.remove(group_id)\n except KeyError:\n raise exception.NotFound(_('User not found in group'))\n self.update_user(user_id, {'groups': list(groups)})\n\n def list_users_in_group(self, group_id):\n self.get_group(group_id)\n user_keys = filter(lambda x: x.startswith(\"user-\"), self.db.keys())\n user_refs = [self.db.get(key) for key in user_keys]\n user_refs_for_group = filter(lambda x: group_id in x['groups'],\n user_refs)\n return [identity.filter_user(x) for x in user_refs_for_group]\n\n def list_groups_for_user(self, user_id):\n user_ref = self._get_user(user_id)\n group_ids = user_ref.get('groups', [])\n return [self.get_group(x) for x in group_ids]\n\n def delete_user(self, user_id):\n try:\n old_user = self.db.get('user-%s' % user_id)\n except exception.NotFound:\n raise exception.UserNotFound(user_id=user_id)\n self.db.delete('user_name-%s' % old_user['name'])\n self.db.delete('user-%s' % user_id)\n user_list = set(self.db.get('user_list', []))\n user_list.remove(user_id)\n self.db.set('user_list', list(user_list))\n\n def create_project(self, tenant_id, tenant):\n tenant['name'] = clean.project_name(tenant['name'])\n try:\n self.get_project(tenant_id)\n except exception.ProjectNotFound:\n pass\n else:\n msg = 'Duplicate ID, %s.' % tenant_id\n raise exception.Conflict(type='tenant', details=msg)\n\n try:\n self.get_project_by_name(tenant['name'], tenant['domain_id'])\n except exception.ProjectNotFound:\n pass\n else:\n msg = 'Duplicate name, %s.' % tenant['name']\n raise exception.Conflict(type='tenant', details=msg)\n\n self.db.set('tenant-%s' % tenant_id, tenant)\n self.db.set('tenant_name-%s' % tenant['name'], tenant)\n return tenant\n\n def update_project(self, tenant_id, tenant):\n if 'name' in tenant:\n tenant['name'] = clean.project_name(tenant['name'])\n try:\n existing = self.db.get('tenant_name-%s' % tenant['name'])\n if existing and tenant_id != existing['id']:\n msg = 'Duplicate name, %s.' % tenant['name']\n raise exception.Conflict(type='tenant', details=msg)\n except exception.NotFound:\n pass\n # get the old name and delete it too\n try:\n old_project = self.db.get('tenant-%s' % tenant_id)\n except exception.NotFound:\n raise exception.ProjectNotFound(project_id=tenant_id)\n new_project = old_project.copy()\n new_project.update(tenant)\n new_project['id'] = tenant_id\n self.db.delete('tenant_name-%s' % old_project['name'])\n self.db.set('tenant-%s' % tenant_id, new_project)\n self.db.set('tenant_name-%s' % new_project['name'], new_project)\n return new_project\n\n def delete_project(self, tenant_id):\n try:\n old_project = self.db.get('tenant-%s' % tenant_id)\n except exception.NotFound:\n raise exception.ProjectNotFound(project_id=tenant_id)\n self.db.delete('tenant_name-%s' % old_project['name'])\n self.db.delete('tenant-%s' % tenant_id)\n\n def create_metadata(self, user_id, tenant_id, metadata,\n domain_id=None, group_id=None):\n\n return self.update_metadata(user_id, tenant_id, metadata,\n domain_id, group_id)\n\n def update_metadata(self, user_id, tenant_id, metadata,\n domain_id=None, group_id=None):\n if user_id:\n if tenant_id:\n self.db.set('metadata-%s-%s' % (tenant_id, user_id), metadata)\n user_ref = self._get_user(user_id)\n tenants = set(user_ref.get('tenants', []))\n if tenant_id not in tenants:\n tenants.add(tenant_id)\n user_ref['tenants'] = list(tenants)\n self.update_user(user_id, user_ref)\n else:\n self.db.set('metadata-%s-%s' % (domain_id, user_id), metadata)\n else:\n if tenant_id:\n self.db.set('metadata-%s-%s' % (tenant_id, group_id), metadata)\n else:\n self.db.set('metadata-%s-%s' % (domain_id, group_id), metadata)\n return metadata\n\n def create_role(self, role_id, role):\n try:\n self.get_role(role_id)\n except exception.RoleNotFound:\n pass\n else:\n msg = 'Duplicate ID, %s.' % role_id\n raise exception.Conflict(type='role', details=msg)\n\n for role_ref in self.list_roles():\n if role['name'] == role_ref['name']:\n msg = 'Duplicate name, %s.' % role['name']\n raise exception.Conflict(type='role', details=msg)\n self.db.set('role-%s' % role_id, role)\n role_list = set(self.db.get('role_list', []))\n role_list.add(role_id)\n self.db.set('role_list', list(role_list))\n return role\n\n def update_role(self, role_id, role):\n old_role_ref = None\n for role_ref in self.list_roles():\n if role['name'] == role_ref['name'] and role_id != role_ref['id']:\n msg = 'Duplicate name, %s.' % role['name']\n raise exception.Conflict(type='role', details=msg)\n if role_id == role_ref['id']:\n old_role_ref = role_ref\n if old_role_ref is None:\n raise exception.RoleNotFound(role_id=role_id)\n new_role = old_role_ref.copy()\n new_role.update(role)\n new_role['id'] = role_id\n self.db.set('role-%s' % role_id, new_role)\n return role\n\n def delete_role(self, role_id):\n try:\n self.db.delete('role-%s' % role_id)\n metadata_keys = filter(lambda x: x.startswith(\"metadata-\"),\n self.db.keys())\n for key in metadata_keys:\n tenant_id = key.split('-')[1]\n user_id = key.split('-')[2]\n try:\n self.remove_role_from_user_and_project(user_id,\n tenant_id,\n role_id)\n except exception.RoleNotFound:\n pass\n except exception.NotFound:\n raise exception.RoleNotFound(role_id=role_id)\n role_list = set(self.db.get('role_list', []))\n role_list.remove(role_id)\n self.db.set('role_list', list(role_list))\n\n def create_grant(self, role_id, user_id=None, group_id=None,\n domain_id=None, project_id=None):\n\n self.get_role(role_id)\n if user_id:\n self.get_user(user_id)\n if group_id:\n self.get_group(group_id)\n if domain_id:\n self.get_domain(domain_id)\n if project_id:\n self.get_project(project_id)\n\n try:\n metadata_ref = self.get_metadata(user_id, project_id,\n domain_id, group_id)\n except exception.MetadataNotFound:\n metadata_ref = {}\n roles = set(metadata_ref.get('roles', []))\n roles.add(role_id)\n metadata_ref['roles'] = list(roles)\n self.update_metadata(user_id, project_id, metadata_ref,\n domain_id, group_id)\n\n def list_grants(self, user_id=None, group_id=None,\n domain_id=None, project_id=None):\n if user_id:\n self.get_user(user_id)\n if group_id:\n self.get_group(group_id)\n if domain_id:\n self.get_domain(domain_id)\n if project_id:\n self.get_project(project_id)\n\n try:\n metadata_ref = self.get_metadata(user_id, project_id,\n domain_id, group_id)\n except exception.MetadataNotFound:\n metadata_ref = {}\n return [self.get_role(x) for x in metadata_ref.get('roles', [])]\n\n def get_grant(self, role_id, user_id=None, group_id=None,\n domain_id=None, project_id=None):\n self.get_role(role_id)\n if user_id:\n self.get_user(user_id)\n if group_id:\n self.get_group(group_id)\n if domain_id:\n self.get_domain(domain_id)\n if project_id:\n self.get_project(project_id)\n\n try:\n metadata_ref = self.get_metadata(user_id, project_id,\n domain_id, group_id)\n except exception.MetadataNotFound:\n metadata_ref = {}\n role_ids = set(metadata_ref.get('roles', []))\n if role_id not in role_ids:\n raise exception.RoleNotFound(role_id=role_id)\n return self.get_role(role_id)\n\n def delete_grant(self, role_id, user_id=None, group_id=None,\n domain_id=None, project_id=None):\n self.get_role(role_id)\n if user_id:\n self.get_user(user_id)\n if group_id:\n self.get_group(group_id)\n if domain_id:\n self.get_domain(domain_id)\n if project_id:\n self.get_project(project_id)\n\n try:\n metadata_ref = self.get_metadata(user_id, project_id,\n domain_id, group_id)\n except exception.MetadataNotFound:\n metadata_ref = {}\n roles = set(metadata_ref.get('roles', []))\n try:\n roles.remove(role_id)\n except KeyError:\n raise exception.RoleNotFound(role_id=role_id)\n metadata_ref['roles'] = list(roles)\n self.update_metadata(user_id, project_id, metadata_ref,\n domain_id, group_id)\n\n # domain crud\n\n def create_domain(self, domain_id, domain):\n try:\n self.get_domain(domain_id)\n except exception.DomainNotFound:\n pass\n else:", "answers": [" msg = 'Duplicate ID, %s.' % domain_id"], "length": 1396, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "7460da9c-0d9c-469a-9682-1cb1671a7143", "reasoning": "The create_domain method follows the same pattern as other create_* methods in this class. After attempting to get an existing domain and catching DomainNotFound, the else clause handles the case where the domain already exists. The first statement in that block is to construct an error message about a duplicate ID, matching the style used in create_user, create_project, and create_role.", "reasoning_model_answer": "msg = 'Duplicate ID, %s.' % domain_id", "assistant_with_reasoning": "\nThe create_domain method follows the same pattern as other create_* methods in this class. After attempting to get an existing domain and catching DomainNotFound, the else clause handles the case where the domain already exists. The first statement in that block is to construct an error message about a duplicate ID, matching the style used in create_user, create_project, and create_role.\n\nmsg = 'Duplicate ID, %s.' % domain_id", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 6.762, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 20198, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "msg = 'Duplicate ID, %s.' % domain_id", "score": 0.86, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "# -*- coding: ascii -*-\n# $Id$\n#\n# Author: vvlachoudis@gmail.com\n# Date: 24-Aug-2014\n\n__author__ = \"Vasilis Vlachoudis\"\n__email__ = \"Vasilis.Vlachoudis@cern.ch\"\n\nimport traceback\ntry:\n\tfrom Tkinter import *\n\timport tkMessageBox\nexcept ImportError:\n\tfrom tkinter import *\n\timport tkinter.messagebox as tkMessageBox\nfrom operator import attrgetter\n\nimport os\nimport time\nimport glob\nimport Utils\nimport Ribbon\nimport tkExtra\nimport Unicode\nimport CNCRibbon\n\nfrom CNC import CNC\n\n_EXE_FONT = (\"Helvetica\",12,\"bold\")\n\n#===============================================================================\nclass InPlaceText(tkExtra.InPlaceText):\n\tdef defaultBinds(self):\n\t\ttkExtra.InPlaceText.defaultBinds(self)\n\t\tself.edit.bind(\"\", self.ok)\n\n#==============================================================================\n# Tools Base class\n#==============================================================================\nclass _Base:\n\tdef __init__(self, master):\n\t\tself.master = master\n\t\tself.name = None\n\t\tself.icon = None\n\t\tself.plugin = False\n\t\tself.variables = []\t\t# name, type, default, label\n\t\tself.values = {}\t\t# database of values\n\t\tself.listdb = {}\t\t# lists database\n\t\tself.current = None\t\t# currently editing index\n\t\tself.n = 0\n\t\tself.buttons = []\n\n\t# ----------------------------------------------------------------------\n\tdef __setitem__(self, name, value):\n\t\tif self.current is None:\n\t\t\tself.values[name] = value\n\t\telse:\n\t\t\tself.values[\"%s.%d\"%(name,self.current)] = value\n\n\t# ----------------------------------------------------------------------\n\tdef __getitem__(self, name):\n\t\tif self.current is None:\n\t\t\treturn self.values.get(name,\"\")\n\t\telse:\n\t\t\treturn self.values.get(\"%s.%d\"%(name,self.current),\"\")\n\n\t# ----------------------------------------------------------------------\n\tdef gcode(self):\n\t\treturn self.master.gcode\n\n\t# ----------------------------------------------------------------------\n\t# Return a sorted list of all names\n\t# ----------------------------------------------------------------------\n\tdef names(self):\n\t\tlst = []\n\t\tfor i in range(1000):\n\t\t\tkey = \"name.%d\"%(i)\n\t\t\tvalue = self.values.get(key)\n\t\t\tif value is None: break\n\t\t\tlst.append(value)\n\t\tlst.sort()\n\t\treturn lst\n\n\t# ----------------------------------------------------------------------\n\tdef _get(self, key, t, default):\n\t\tif t in (\"float\",\"mm\"):\n\t\t\treturn Utils.getFloat(self.name, key, default)\n\t\telif t == \"int\":\n\t\t\treturn Utils.getInt(self.name, key, default)\n\t\telif t == \"bool\":\n\t\t\treturn Utils.getInt(self.name, key, default)\n\t\telse:\n\t\t\treturn Utils.getStr(self.name, key, default)\n\n\t# ----------------------------------------------------------------------\n\t# Override with execute command\n\t# ----------------------------------------------------------------------\n\tdef execute(self, app):\n\t\tpass\n\n\t# ----------------------------------------------------------------------\n\t# Update variables after edit command\n\t# ----------------------------------------------------------------------\n\tdef update(self):\n\t\treturn False\n\n\t# ----------------------------------------------------------------------\n\tdef event_generate(self, msg, **kwargs):\n\t\tself.master.listbox.event_generate(msg, **kwargs)\n\n\t# ----------------------------------------------------------------------\n\tdef beforeChange(self, app):\n\t\tpass\n\n\t# ----------------------------------------------------------------------\n\tdef populate(self):\n\t\tself.master.listbox.delete(0,END)\n\t\tfor n, t, d, l in self.variables:\n\t\t\tvalue = self[n]\n\t\t\tif t == \"bool\":\n\t\t\t\tif value:\n\t\t\t\t\tvalue = Unicode.BALLOT_BOX_WITH_X\n\t\t\t\telse:\n\t\t\t\t\tvalue = Unicode.BALLOT_BOX\n\t\t\telif t == \"mm\" and self.master.inches:\n\t\t\t\ttry:\n\t\t\t\t\tvalue /= 25.4\n\t\t\t\t\tvalue = round(value, self.master.digits)\n\t\t\t\texcept:\n\t\t\t\t\tvalue = \"\"\n\t\t\telif t == \"float\":\n\t\t\t\ttry:\n\t\t\t\t\tvalue = round(value, self.master.digits)\n\t\t\t\texcept:\n\t\t\t\t\tvalue = \"\"\n\t\t\t#elif t == \"list\":\n\t\t\t#\tvalue += \" \" + Unicode.BLACK_DOWN_POINTING_TRIANGLE\n\t\t\tself.master.listbox.insert(END, (l, value))\n\n\t\t\tif t==\"color\":\n\t\t\t\ttry:\n\t\t\t\t\tself.master.listbox.lists[1].itemconfig(END, background=value)\n\t\t\t\texcept TclError:\n\t\t\t\t\tpass\n\n\t#----------------------------------------------------------------------\n\tdef _sendReturn(self, active):\n\t\tself.master.listbox.selection_clear(0,END)\n\t\tself.master.listbox.selection_set(active)\n\t\tself.master.listbox.activate(active)\n\t\tself.master.listbox.see(active)\n\t\tn, t, d, l = self.variables[active]\n\t\tif t==\"bool\": return\t# Forbid changing value of bool\n\t\tself.master.listbox.event_generate(\"\")\n\n\t#----------------------------------------------------------------------\n\tdef _editPrev(self):\n\t\tactive = self.master.listbox.index(ACTIVE)-1\n\t\tif active<0: return\n\t\tself._sendReturn(active)\n\n\t#----------------------------------------------------------------------\n\tdef _editNext(self):\n\t\tactive = self.master.listbox.index(ACTIVE)+1\n\t\tif active>=self.master.listbox.size(): return\n\t\tself._sendReturn(active)\n\n\t#----------------------------------------------------------------------\n\t# Make current \"name\" from the database\n\t#----------------------------------------------------------------------\n\tdef makeCurrent(self, name):\n\t\tif not name: return\n\t\t# special handling\n\t\tfor i in range(1000):\n\t\t\tif name==self.values.get(\"name.%d\"%(i)):\n\t\t\t\tself.current = i\n\t\t\t\tself.update()\n\t\t\t\treturn True\n\t\treturn False\n\n\t#----------------------------------------------------------------------\n\t# Edit tool listbox\n\t#----------------------------------------------------------------------\n\tdef edit(self, event=None, rename=False):\n\t\tlb = self.master.listbox.lists[1]\n\t\tif event is None or event.type==\"2\":\n\t\t\tkeyboard = True\n\t\telse:\n\t\t\tkeyboard = False\n\t\tif keyboard:\n\t\t\t# keyboard event\n\t\t\tactive = lb.index(ACTIVE)\n\t\telse:\n\t\t\tactive = lb.nearest(event.y)\n\t\t\tself.master.listbox.activate(active)\n\n\t\typos = lb.yview()[0]\t# remember y position\n\t\tsave = lb.get(ACTIVE)\n\n\t\tn, t, d, l = self.variables[active]\n\n\t\tif t == \"int\":\n\t\t\tedit = tkExtra.InPlaceInteger(lb)\n\t\telif t in (\"float\", \"mm\"):\n\t\t\tedit = tkExtra.InPlaceFloat(lb)\n\t\telif t == \"bool\":\n\t\t\tedit = None\n\t\t\tvalue = int(lb.get(active) == Unicode.BALLOT_BOX)\n\t\t\tif value:\n\t\t\t\tlb.set(active, Unicode.BALLOT_BOX_WITH_X)\n\t\t\telse:\n\t\t\t\tlb.set(active, Unicode.BALLOT_BOX)\n\t\telif t == \"list\":\n\t\t\tedit = tkExtra.InPlaceList(lb, values=self.listdb[n])\n\t\telif t == \"db\":\n\t\t\tif n==\"name\":\n\t\t\t\t# Current database\n\t\t\t\tif rename:\n\t\t\t\t\tedit = tkExtra.InPlaceEdit(lb)\n\t\t\t\telse:\n\t\t\t\t\tedit = tkExtra.InPlaceList(lb, values=self.names())\n\t\t\telse:\n\t\t\t\t# Refers to names from another database\n\t\t\t\ttool = self.master[n]\n\t\t\t\tnames = tool.names()\n\t\t\t\tnames.insert(0,\"\")\n\t\t\t\tedit = tkExtra.InPlaceList(lb, values=names)\n\t\telif t == \"text\":\n\t\t\tedit = InPlaceText(lb)\n\t\telif \",\" in t:\n\t\t\tchoices = [\"\"]\n\t\t\tchoices.extend(t.split(\",\"))\n\t\t\tedit = tkExtra.InPlaceList(lb, values=choices)\n\t\telif t == \"file\":\n\t\t\tedit = tkExtra.InPlaceFile(lb, save=False)\n\t\telif t == \"output\":\n\t\t\tedit = tkExtra.InPlaceFile(lb, save=True)\n\t\telif t == \"color\":\n\t\t\tedit = tkExtra.InPlaceColor(lb)\n\t\t\tif edit.value is not None:\n\t\t\t\ttry:\n\t\t\t\t\tlb.itemconfig(ACTIVE, background=edit.value)\n\t\t\t\texcept TclError:\n\t\t\t\t\tpass\n\t\telse:\n\t\t\tedit = tkExtra.InPlaceEdit(lb)\n\n\t\tif edit is not None:\n\t\t\tvalue = edit.value\n\t\t\tif value is None:\n\t\t\t\treturn\n\n\t\tif value == save:\n\t\t\tif edit.lastkey == \"Up\":\n\t\t\t\tself._editPrev()\n\t\t\telif edit.lastkey in (\"Return\", \"KP_Enter\", \"Down\"):\n\t\t\t\tself._editNext()\n\t\t\treturn\n\n\t\tif t == \"int\":\n\t\t\ttry:\n\t\t\t\tvalue = int(value)\n\t\t\texcept ValueError:\n\t\t\t\tvalue = \"\"\n\t\telif t in (\"float\",\"mm\"):\n\t\t\ttry:\n\t\t\t\tvalue = float(value)\n\t\t\t\tif t==\"mm\" and self.master.inches:\n\t\t\t\t\tvalue *= 25.4\n\t\t\texcept ValueError:\n\t\t\t\tvalue = \"\"\n\n\t\tif n==\"name\" and not rename:\n\t\t\tif self.makeCurrent(value):\n\t\t\t\tself.populate()\n\t\telse:\n\t\t\tself[n] = value\n\t\t\tif self.update():\n\t\t\t\tself.populate()\n\n\t\tself.master.listbox.selection_set(active)\n\t\tself.master.listbox.activate(active)\n\t\tself.master.listbox.yview_moveto(ypos)\n\t\tif edit is not None and not rename:\n\t\t\tif edit.lastkey == \"Up\":\n\t\t\t\tself._editPrev()\n\t\t\telif edit.lastkey in (\"Return\", \"KP_Enter\", \"Down\") and active>0:\n\t\t\t\tself._editNext()\n\n\t#==============================================================================\n\t# Additional persistence class for config\n\t#==============================================================================\n\t#class _Config:\n\t# ----------------------------------------------------------------------\n\t# Load from a configuration file\n\t# ----------------------------------------------------------------------\n\tdef load(self):\n\t\t# Load lists\n\t\tlists = []\n\t\tfor n, t, d, l in self.variables:\n\t\t\tif t==\"list\":\n\t\t\t\tlists.append(n)\n\t\tif lists:\n\t\t\tfor p in lists:\n\t\t\t\tself.listdb[p] = []\n\t\t\t\tfor i in range(1000):\n\t\t\t\t\tkey = \"_%s.%d\"%(p, i)\n\t\t\t\t\tvalue = Utils.getStr(self.name, key).strip()\n\t\t\t\t\tif value:\n\t\t\t\t\t\tself.listdb[p].append(value)\n\t\t\t\t\telse:\n\t\t\t\t\t\tbreak\n\n\t\t# Check if there is a current\n\t\ttry:\n\t\t\tself.current = int(Utils.config.get(self.name, \"current\"))\n\t\texcept:\n\t\t\tself.current = None\n\n\t\t# Load values\n\t\tif self.current is not None:\n\t\t\tself.n = self._get(\"n\", \"int\", 0)\n\t\t\tfor i in range(self.n):\n\t\t\t\tkey = \"name.%d\"%(i)\n\t\t\t\tself.values[key] = Utils.getStr(self.name, key)\n\t\t\t\tfor n, t, d, l in self.variables:\n\t\t\t\t\tkey = \"%s.%d\"%(n,i)\n\t\t\t\t\tself.values[key] = self._get(key, t, d)\n\t\telse:\n\t\t\tfor n, t, d, l in self.variables:\n\t\t\t\tself.values[n] = self._get(n, t, d)\n\t\tself.update()\n\n\t# ----------------------------------------------------------------------\n\t# Save to a configuration file\n\t# ----------------------------------------------------------------------\n\tdef save(self):\n\t\t# if section do not exist add it\n\t\tUtils.addSection(self.name)\n\n\t\tif self.listdb:\n\t\t\tfor name,lst in self.listdb.items():\n\t\t\t\tfor i,value in enumerate(lst):\n\t\t\t\t\tUtils.setStr(self.name, \"_%s.%d\"%(name,i), value)\n\n\t\t# Save values\n\t\tif self.current is not None:\n\t\t\tUtils.setStr(self.name, \"current\", str(self.current))\n\t\t\tUtils.setStr(self.name, \"n\", str(self.n))\n\n\t\t\tfor i in range(self.n):\n\t\t\t\tkey = \"name.%d\"%(i)\n\t\t\t\tvalue = self.values.get(key)\n\t\t\t\tif value is None: break\n\t\t\t\tUtils.setStr(self.name, key, value)\n\n\t\t\t\tfor n, t, d, l in self.variables:\n\t\t\t\t\tkey = \"%s.%d\"%(n,i)\n\t\t\t\t\tUtils.setStr(self.name, key,\n\t\t\t\t\t\tstr(self.values.get(key,d)))\n\t\telse:\n\t\t\tfor n, t, d, l in self.variables:\n\t\t\t\tUtils.setStr(self.name, n, str(self.values.get(n,d)))\n\n\t# ----------------------------------------------------------------------\n\tdef fromMm(self, name, default=0.0):\n\t\ttry:\n\t\t\treturn self.master.fromMm(float(self[name]))\n\t\texcept ValueError:\n\t\t\treturn default\n\n#==============================================================================\n# Base class of all databases\n#==============================================================================\nclass DataBase(_Base):\n\tdef __init__(self, master):\n\t\t_Base.__init__(self, master)\n\t\tself.buttons = [\"add\",\"delete\",\"clone\",\"rename\"]\n\n\t# ----------------------------------------------------------------------\n\t# Add a new item\n\t# ----------------------------------------------------------------------\n\tdef add(self, rename=True):\n\t\tself.current = self.n\n\t\tself.values[\"name.%d\"%(self.n)] = \"%s %02d\"%(self.name, self.n+1)\n\t\tself.n += 1\n\t\tself.populate()\n\t\tif rename:\n\t\t\tself.rename()\n\n\t# ----------------------------------------------------------------------\n\t# Delete selected item\n\t# ----------------------------------------------------------------------\n\tdef delete(self):\n\t\tif self.n==0: return\n\t\tfor n, t, d, l in self.variables:\n\t\t\tfor i in range(self.current, self.n):\n\t\t\t\ttry:\n\t\t\t\t\tself.values[\"%s.%d\"%(n,i)] = self.values[\"%s.%d\"%(n,i+1)]\n\t\t\t\texcept KeyError:\n\t\t\t\t\ttry:\n\t\t\t\t\t\tdel self.values[\"%s.%d\"%(n,i)]\n\t\t\t\t\texcept KeyError:\n\t\t\t\t\t\tpass\n\n\t\tself.n -= 1\n\t\tif self.current >= self.n:\n\t\t\tself.current = self.n - 1\n\t\tself.populate()\n\n\t# ----------------------------------------------------------------------\n\t# Clone selected item\n\t# ----------------------------------------------------------------------\n\tdef clone(self):\n\t\tif self.n==0: return\n\t\tfor n, t, d, l in self.variables:\n\t\t\ttry:\n\t\t\t\tif n==\"name\":\n\t\t\t\t\tself.values[\"%s.%d\"%(n,self.n)] = \\\n\t\t\t\t\t\tself.values[\"%s.%d\"%(n,self.current)] + \" clone\"\n\t\t\t\telse:\n\t\t\t\t\tself.values[\"%s.%d\"%(n,self.n)] = \\\n\t\t\t\t\t\tself.values[\"%s.%d\"%(n,self.current)]\n\t\t\texcept KeyError:\n\t\t\t\tpass\n\t\tself.n += 1\n\t\tself.current = self.n - 1\n\t\tself.populate()\n\n\t# ----------------------------------------------------------------------\n\t# Rename current item\n\t# ----------------------------------------------------------------------\n\tdef rename(self):\n\t\tself.master.listbox.selection_clear(0,END)\n\t\tself.master.listbox.selection_set(0)\n\t\tself.master.listbox.activate(0)\n\t\tself.master.listbox.see(0)\n\t\tself.edit(None,True)\n\n#==============================================================================\nclass Plugin(DataBase):\n\tdef __init__(self, master):\n\t\tDataBase.__init__(self, master)\n\t\tself.plugin = True\n\t\tself.group = \"Macros\"\n\n#==============================================================================\n# Generic ini configuration\n#==============================================================================\nclass Ini(_Base):\n\tdef __init__(self, master, name, vartype):\n\t\t_Base.__init__(self, master)\n\t\tself.name = name\n\n\t\t# detect variables from ini file\n\t\tself.variables = []\n\t\tfor name,value in Utils.config.items(self.name):\n\t\t\tself.variables.append((name, vartype, value, name))\n\n#------------------------------------------------------------------------------\nclass Font(Ini):\n\tdef __init__(self, master):\n\t\tIni.__init__(self, master, \"Font\", \"str\")\n\n#------------------------------------------------------------------------------\nclass Color(Ini):\n\tdef __init__(self, master):\n\t\tIni.__init__(self, master, \"Color\", \"color\")\n\n#------------------------------------------------------------------------------\nclass Camera(Ini):\n\tdef __init__(self, master):\n\t\tIni.__init__(self, master, \"Camera\", \"int\")\n\n#------------------------------------------------------------------------------\nclass Events(Ini):\n\tdef __init__(self, master):\n\t\tIni.__init__(self, master, \"Events\", \"str\")\n\n#------------------------------------------------------------------------------\nclass Shortcut(Ini):\n\tdef __init__(self, master):\n\t\tIni.__init__(self, master, \"Shortcut\", \"str\")\n\t\tself.buttons.append(\"exe\")\n\n\t#----------------------------------------------------------------------\n\tdef execute(self, app):\n\t\tself.save()\n\t\tapp.loadShortcuts()\n\n#==============================================================================\n# CNC machine configuration\n#==============================================================================\nclass Config(_Base):\n\tdef __init__(self, master):\n\t\t_Base.__init__(self, master)\n\t\tself.name = \"CNC\"\n\t\tself.variables = [\n\t\t\t(\"units\" , \"bool\", 0 , _(\"Units (inches)\")) ,\n\t\t\t(\"lasercutter\" , \"bool\", 0 , _(\"Lasercutter\")) ,\n\t\t\t(\"acceleration_x\", \"mm\" , 25.0 , _(\"Acceleration x\")) ,\n\t\t\t(\"acceleration_y\", \"mm\" , 25.0 , _(\"Acceleration y\")) ,\n\t\t\t(\"acceleration_z\", \"mm\" , 5.0 , _(\"Acceleration z\")) ,\n\t\t\t(\"feedmax_x\" , \"mm\" , 3000., _(\"Feed max x\")) ,\n\t\t\t(\"feedmax_y\" , \"mm\" , 3000., _(\"Feed max y\")) ,\n\t\t\t(\"feedmax_z\" , \"mm\" , 2000., _(\"Feed max z\")) ,\n\t\t\t(\"travel_x\" , \"mm\" , 200 , _(\"Travel x\")) ,\n\t\t\t(\"travel_y\" , \"mm\" , 200 , _(\"Travel y\")) ,\n\t\t\t(\"travel_z\" , \"mm\" , 100 , _(\"Travel z\")) ,\n\t\t\t(\"round\" , \"int\" , 4 , _(\"Decimal digits\")) ,\n\t\t\t(\"accuracy\" , \"mm\" , 0.1 , _(\"Plotting Arc accuracy\")),\n\t\t\t(\"startup\" , \"str\" , \"G90\", _(\"Start up\")) ,\n\t\t\t(\"spindlemin\" , \"int\" , 0 , _(\"Spindle min (RPM)\")),\n\t\t\t(\"spindlemax\" , \"int\" , 12000, _(\"Spindle max (RPM)\")),\n\t\t\t(\"drozeropad\" , \"int\" , 0 , _(\"DRO Zero padding\")),\n\t\t\t(\"header\" , \"text\" , \"\", _(\"Header gcode\")),\n\t\t\t(\"footer\" , \"text\" , \"\", _(\"Footer gcode\"))\n\t\t]\n\n\t# ----------------------------------------------------------------------\n\t# Update variables after edit command\n\t# ----------------------------------------------------------------------\n\tdef update(self):\n\t\tself.master.inches = self[\"units\"]\n\t\tself.master.digits = int(self[\"round\"])\n\t\tself.master.cnc().decimal = self.master.digits\n\t\tself.master.cnc().startup = self[\"startup\"]\n\t\tself.master.gcode.header = self[\"header\"]\n\t\tself.master.gcode.footer = self[\"footer\"]\n\t\treturn False\n\n#==============================================================================\n# Material database\n#==============================================================================\nclass Material(DataBase):\n\tdef __init__(self, master):\n\t\tDataBase.__init__(self, master)\n\t\tself.name = \"Material\"\n\t\tself.variables = [\n\t\t\t(\"name\", \"db\", \"\", _(\"Name\")),\n\t\t\t(\"comment\",\"str\", \"\", _(\"Comment\")),\n\t\t\t(\"feed\", \"mm\" , 10., _(\"Feed\")),\n\t\t\t(\"feedz\", \"mm\" , 1., _(\"Plunge Feed\")),\n\t\t\t(\"stepz\", \"mm\" , 1., _(\"Depth Increment\"))\n\t\t ]\n\n\t# ----------------------------------------------------------------------\n\t# Update variables after edit command\n\t# ----------------------------------------------------------------------\n\tdef update(self):\n\t\t# update ONLY if stock material is empty:\n\t\tstockmat = self.master[\"stock\"][\"material\"]\n\t\tif stockmat==\"\" or stockmat==self[\"name\"]:\n\t\t\tself.master.cnc()[\"cutfeed\"] = self.fromMm(\"feed\")\n\t\t\tself.master.cnc()[\"cutfeedz\"] = self.fromMm(\"feedz\")\n\t\t\tself.master.cnc()[\"stepz\"] = self.fromMm(\"stepz\")\n\t\treturn False\n\n#==============================================================================\n# EndMill Bit database\n#==============================================================================\nclass EndMill(DataBase):\n\tdef __init__(self, master):\n\t\tDataBase.__init__(self, master)\n\t\tself.name = \"EndMill\"\n\t\tself.variables = [\n\t\t\t(\"name\", \"db\", \"\", _(\"Name\")),\n\t\t\t(\"comment\", \"str\", \"\", _(\"Comment\")),\n\t\t\t(\"type\", \"list\", \"\", _(\"Type\")),\n\t\t\t(\"shape\", \"list\", \"\", _(\"Shape\")),\n\t\t\t(\"material\", \"list\", \"\", _(\"Material\")),\n\t\t\t(\"coating\", \"list\", \"\", _(\"Coating\")),\n\t\t\t(\"diameter\", \"mm\", 3.175, _(\"Diameter\")),\n\t\t\t(\"axis\", \"mm\", 3.175, _(\"Mount Axis\")),\n\t\t\t(\"flutes\", \"int\", 2, _(\"Flutes\")),\n\t\t\t(\"length\", \"mm\", 20.0, _(\"Length\")),\n\t\t\t(\"angle\", \"float\", \"\", _(\"Angle\")),\n\t\t\t(\"stepover\",\"float\", 40.0, _(\"Stepover %\"))\n\t\t]\n\n\t# ----------------------------------------------------------------------\n\t# Update variables after edit command\n\t# ----------------------------------------------------------------------\n\tdef update(self):\n\t\tself.master.cnc()[\"diameter\"] = self.fromMm(\"diameter\")\n\t\tself.master.cnc()[\"stepover\"] = self[\"stepover\"]\n\t\treturn False\n\n#==============================================================================\n# Stock material on worksurface\n#==============================================================================\nclass Stock(DataBase):\n\tdef __init__(self, master):\n\t\tDataBase.__init__(self, master)\n\t\tself.name = \"Stock\"\n\t\tself.variables = [\n\t\t\t(\"name\", \"db\" , \"\", _(\"Name\")),\n\t\t\t(\"comment\", \"str\", \"\", _(\"Comment\")),\n\t\t\t(\"material\", \"db\" , \"\", _(\"Material\")),\n\t\t\t(\"safe\" , \"mm\" , 3.0, _(\"Safe Z\")),\n\t\t\t(\"surface\", \"mm\" , 0.0, _(\"Surface Z\")),\n\t\t\t(\"thickness\", \"mm\" , 5.0, _(\"Thickness\"))\n\t\t]\n\n\t# ----------------------------------------------------------------------\n\t# Update variables after edit command\n\t# ----------------------------------------------------------------------\n\tdef update(self):\n\t\tself.master.cnc()[\"safe\"] = self.fromMm(\"safe\")", "answers": ["\t\tself.master.cnc()[\"surface\"] = self.fromMm(\"surface\")"], "length": 1688, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "32691e46-428f-4e34-b608-f025bd4b33d6", "reasoning": "The Stock.update method begins by assigning the CNC parameter 'safe' using the stored 'safe' value. Following the pattern in other update methods (e.g., EndMill.update sets multiple CNC parameters in the order of their variables), the next logical assignment is for the next variable defined in Stock: 'surface'. Therefore the next line should set the CNC 'surface' parameter from the Stock's 'surface' value.", "reasoning_model_answer": "self.master.cnc()[\"surface\"] = self.fromMm(\"surface\")", "assistant_with_reasoning": "\nThe Stock.update method begins by assigning the CNC parameter 'safe' using the stored 'safe' value. Following the pattern in other update methods (e.g., EndMill.update sets multiple CNC parameters in the order of their variables), the next logical assignment is for the next variable defined in Stock: 'surface'. Therefore the next line should set the CNC 'surface' parameter from the Stock's 'surface' value.\n\nself.master.cnc()[\"surface\"] = self.fromMm(\"surface\")", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.485, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 19661, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "self.master.cnc()[\"surface\"] = self.fromMm(\"surface\")", "score": 0.98, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "# -*- coding: utf-8 -*-\n# Copyright 2022 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\nimport warnings\nfrom typing import Callable, Dict, Optional, Sequence, Tuple, Union\n\nfrom google.api_core import grpc_helpers\nfrom google.api_core import operations_v1\nfrom google.api_core import gapic_v1\nimport google.auth # type: ignore\nfrom google.auth import credentials as ga_credentials # type: ignore\nfrom google.auth.transport.grpc import SslCredentials # type: ignore\n\nimport grpc # type: ignore\n\nfrom google.cloud.dataproc_v1.types import clusters\nfrom google.longrunning import operations_pb2 # type: ignore\nfrom .base import ClusterControllerTransport, DEFAULT_CLIENT_INFO\n\n\nclass ClusterControllerGrpcTransport(ClusterControllerTransport):\n \"\"\"gRPC backend transport for ClusterController.\n\n The ClusterControllerService provides methods to manage\n clusters of Compute Engine instances.\n\n This class defines the same methods as the primary client, so the\n primary client can load the underlying transport implementation\n and call it.\n\n It sends protocol buffers over the wire using gRPC (which is built on\n top of HTTP/2); the ``grpcio`` package must be installed.\n \"\"\"\n\n _stubs: Dict[str, Callable]\n\n def __init__(\n self,\n *,\n host: str = \"dataproc.googleapis.com\",\n credentials: ga_credentials.Credentials = None,\n credentials_file: str = None,\n scopes: Sequence[str] = None,\n channel: grpc.Channel = None,\n api_mtls_endpoint: str = None,\n client_cert_source: Callable[[], Tuple[bytes, bytes]] = None,\n ssl_channel_credentials: grpc.ChannelCredentials = None,\n client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None,\n quota_project_id: Optional[str] = None,\n client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,\n always_use_jwt_access: Optional[bool] = False,\n ) -> None:\n \"\"\"Instantiate the transport.\n\n Args:\n host (Optional[str]):\n The hostname to connect to.\n credentials (Optional[google.auth.credentials.Credentials]): The\n authorization credentials to attach to requests. These\n credentials identify the application to the service; if none\n are specified, the client will attempt to ascertain the\n credentials from the environment.\n This argument is ignored if ``channel`` is provided.\n credentials_file (Optional[str]): A file with credentials that can\n be loaded with :func:`google.auth.load_credentials_from_file`.\n This argument is ignored if ``channel`` is provided.\n scopes (Optional(Sequence[str])): A list of scopes. This argument is\n ignored if ``channel`` is provided.\n channel (Optional[grpc.Channel]): A ``Channel`` instance through\n which to make calls.\n api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint.\n If provided, it overrides the ``host`` argument and tries to create\n a mutual TLS channel with client SSL credentials from\n ``client_cert_source`` or application default SSL credentials.\n client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]):\n Deprecated. A callback to provide client SSL certificate bytes and\n private key bytes, both in PEM format. It is ignored if\n ``api_mtls_endpoint`` is None.\n ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials\n for the grpc channel. It is ignored if ``channel`` is provided.\n client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]):\n A callback to provide client certificate bytes and private key bytes,\n both in PEM format. It is used to configure a mutual TLS channel. It is\n ignored if ``channel`` or ``ssl_channel_credentials`` is provided.\n quota_project_id (Optional[str]): An optional project to use for billing\n and quota.\n client_info (google.api_core.gapic_v1.client_info.ClientInfo):\n The client info used to send a user-agent string along with\n API requests. If ``None``, then default info will be used.\n Generally, you only need to set this if you're developing\n your own client library.\n always_use_jwt_access (Optional[bool]): Whether self signed JWT should\n be used for service account credentials.\n\n Raises:\n google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport\n creation failed for any reason.\n google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``\n and ``credentials_file`` are passed.\n \"\"\"\n self._grpc_channel = None\n self._ssl_channel_credentials = ssl_channel_credentials\n self._stubs: Dict[str, Callable] = {}\n self._operations_client: Optional[operations_v1.OperationsClient] = None\n\n if api_mtls_endpoint:\n warnings.warn(\"api_mtls_endpoint is deprecated\", DeprecationWarning)\n if client_cert_source:\n warnings.warn(\"client_cert_source is deprecated\", DeprecationWarning)\n\n if channel:\n # Ignore credentials if a channel was passed.\n credentials = False\n # If a channel was explicitly provided, set it.\n self._grpc_channel = channel\n self._ssl_channel_credentials = None\n\n else:\n if api_mtls_endpoint:\n host = api_mtls_endpoint\n\n # Create SSL credentials with client_cert_source or application\n # default SSL credentials.\n if client_cert_source:\n cert, key = client_cert_source()\n self._ssl_channel_credentials = grpc.ssl_channel_credentials(\n certificate_chain=cert, private_key=key\n )\n else:\n self._ssl_channel_credentials = SslCredentials().ssl_credentials\n\n else:\n if client_cert_source_for_mtls and not ssl_channel_credentials:\n cert, key = client_cert_source_for_mtls()\n self._ssl_channel_credentials = grpc.ssl_channel_credentials(\n certificate_chain=cert, private_key=key\n )\n\n # The base transport sets the host, credentials and scopes\n super().__init__(\n host=host,\n credentials=credentials,\n credentials_file=credentials_file,\n scopes=scopes,\n quota_project_id=quota_project_id,\n client_info=client_info,\n always_use_jwt_access=always_use_jwt_access,\n )\n\n if not self._grpc_channel:\n self._grpc_channel = type(self).create_channel(\n self._host,\n # use the credentials which are saved\n credentials=self._credentials,\n # Set ``credentials_file`` to ``None`` here as\n # the credentials that we saved earlier should be used.\n credentials_file=None,\n scopes=self._scopes,\n ssl_credentials=self._ssl_channel_credentials,\n quota_project_id=quota_project_id,\n options=[\n (\"grpc.max_send_message_length\", -1),\n (\"grpc.max_receive_message_length\", -1),\n ],\n )\n\n # Wrap messages. This must be done after self._grpc_channel exists\n self._prep_wrapped_messages(client_info)\n\n @classmethod\n def create_channel(\n cls,\n host: str = \"dataproc.googleapis.com\",\n credentials: ga_credentials.Credentials = None,\n credentials_file: str = None,\n scopes: Optional[Sequence[str]] = None,\n quota_project_id: Optional[str] = None,\n **kwargs,\n ) -> grpc.Channel:\n \"\"\"Create and return a gRPC channel object.\n Args:\n host (Optional[str]): The host for the channel to use.\n credentials (Optional[~.Credentials]): The\n authorization credentials to attach to requests. These\n credentials identify this application to the service. If\n none are specified, the client will attempt to ascertain\n the credentials from the environment.\n credentials_file (Optional[str]): A file with credentials that can\n be loaded with :func:`google.auth.load_credentials_from_file`.\n This argument is mutually exclusive with credentials.\n scopes (Optional[Sequence[str]]): A optional list of scopes needed for this\n service. These are only used when credentials are not specified and\n are passed to :func:`google.auth.default`.\n quota_project_id (Optional[str]): An optional project to use for billing\n and quota.\n kwargs (Optional[dict]): Keyword arguments, which are passed to the\n channel creation.\n Returns:\n grpc.Channel: A gRPC channel object.\n\n Raises:\n google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``\n and ``credentials_file`` are passed.\n \"\"\"\n\n return grpc_helpers.create_channel(\n host,\n credentials=credentials,\n credentials_file=credentials_file,\n quota_project_id=quota_project_id,\n default_scopes=cls.AUTH_SCOPES,\n scopes=scopes,\n default_host=cls.DEFAULT_HOST,\n **kwargs,\n )\n\n @property\n def grpc_channel(self) -> grpc.Channel:\n \"\"\"Return the channel designed to connect to this service.\n \"\"\"\n return self._grpc_channel\n\n @property\n def operations_client(self) -> operations_v1.OperationsClient:\n \"\"\"Create the client designed to process long-running operations.\n\n This property caches on the instance; repeated calls return the same\n client.\n \"\"\"\n # Quick check: Only create a new client if we do not already have one.\n if self._operations_client is None:\n self._operations_client = operations_v1.OperationsClient(self.grpc_channel)\n\n # Return the client from cache.\n return self._operations_client\n\n @property\n def create_cluster(\n self,\n ) -> Callable[[clusters.CreateClusterRequest], operations_pb2.Operation]:\n r\"\"\"Return a callable for the create cluster method over gRPC.\n\n Creates a cluster in a project. The returned\n [Operation.metadata][google.longrunning.Operation.metadata] will\n be\n `ClusterOperationMetadata `__.\n\n Returns:\n Callable[[~.CreateClusterRequest],\n ~.Operation]:\n A function that, when called, will call the underlying RPC\n on the server.\n \"\"\"\n # Generate a \"stub function\" on-the-fly which will actually make\n # the request.\n # gRPC handles serialization and deserialization, so we just need\n # to pass in the functions for each.\n if \"create_cluster\" not in self._stubs:\n self._stubs[\"create_cluster\"] = self.grpc_channel.unary_unary(\n \"/google.cloud.dataproc.v1.ClusterController/CreateCluster\",\n request_serializer=clusters.CreateClusterRequest.serialize,\n response_deserializer=operations_pb2.Operation.FromString,\n )\n return self._stubs[\"create_cluster\"]\n\n @property\n def update_cluster(\n self,\n ) -> Callable[[clusters.UpdateClusterRequest], operations_pb2.Operation]:\n r\"\"\"Return a callable for the update cluster method over gRPC.\n\n Updates a cluster in a project. The returned\n [Operation.metadata][google.longrunning.Operation.metadata] will\n be\n `ClusterOperationMetadata `__.\n The cluster must be in a\n [``RUNNING``][google.cloud.dataproc.v1.ClusterStatus.State]\n state or an error is returned.\n\n Returns:\n Callable[[~.UpdateClusterRequest],\n ~.Operation]:\n A function that, when called, will call the underlying RPC\n on the server.\n \"\"\"\n # Generate a \"stub function\" on-the-fly which will actually make\n # the request.\n # gRPC handles serialization and deserialization, so we just need\n # to pass in the functions for each.\n if \"update_cluster\" not in self._stubs:\n self._stubs[\"update_cluster\"] = self.grpc_channel.unary_unary(\n \"/google.cloud.dataproc.v1.ClusterController/UpdateCluster\",\n request_serializer=clusters.UpdateClusterRequest.serialize,\n response_deserializer=operations_pb2.Operation.FromString,\n )\n return self._stubs[\"update_cluster\"]\n\n @property\n def stop_cluster(\n self,\n ) -> Callable[[clusters.StopClusterRequest], operations_pb2.Operation]:\n r\"\"\"Return a callable for the stop cluster method over gRPC.\n\n Stops a cluster in a project.\n\n Returns:\n Callable[[~.StopClusterRequest],\n ~.Operation]:\n A function that, when called, will call the underlying RPC\n on the server.\n \"\"\"\n # Generate a \"stub function\" on-the-fly which will actually make\n # the request.\n # gRPC handles serialization and deserialization, so we just need\n # to pass in the functions for each.\n if \"stop_cluster\" not in self._stubs:\n self._stubs[\"stop_cluster\"] = self.grpc_channel.unary_unary(\n \"/google.cloud.dataproc.v1.ClusterController/StopCluster\",\n request_serializer=clusters.StopClusterRequest.serialize,\n response_deserializer=operations_pb2.Operation.FromString,\n )\n return self._stubs[\"stop_cluster\"]\n\n @property\n def start_cluster(\n self,\n ) -> Callable[[clusters.StartClusterRequest], operations_pb2.Operation]:\n r\"\"\"Return a callable for the start cluster method over gRPC.\n\n Starts a cluster in a project.\n\n Returns:\n Callable[[~.StartClusterRequest],\n ~.Operation]:\n A function that, when called, will call the underlying RPC\n on the server.\n \"\"\"\n # Generate a \"stub function\" on-the-fly which will actually make\n # the request.\n # gRPC handles serialization and deserialization, so we just need\n # to pass in the functions for each.\n if \"start_cluster\" not in self._stubs:\n self._stubs[\"start_cluster\"] = self.grpc_channel.unary_unary(\n \"/google.cloud.dataproc.v1.ClusterController/StartCluster\",\n request_serializer=clusters.StartClusterRequest.serialize,\n response_deserializer=operations_pb2.Operation.FromString,\n )", "answers": [" return self._stubs[\"start_cluster\"]"], "length": 1376, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "88db43b3-bd59-46d4-bfa1-07fb9a3a4a9d", "reasoning": "The start_cluster property follows the same pattern as the previous RPC properties: after ensuring the stub exists in the _stubs dict, it returns that stub. The next line should therefore be the return statement for the start_cluster stub.", "reasoning_model_answer": "return self._stubs[\"start_cluster\"]", "assistant_with_reasoning": "\nThe start_cluster property follows the same pattern as the previous RPC properties: after ensuring the stub exists in the _stubs dict, it returns that stub. The next line should therefore be the return statement for the start_cluster stub.\n\nreturn self._stubs[\"start_cluster\"]", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.371, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 16070, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "return self._stubs[\"start_cluster\"]", "score": 0.9, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "# Copyright 2020 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Tests for Keras text category_encoding preprocessing layer.\"\"\"\n\nfrom absl.testing import parameterized\nimport numpy as np\n\nfrom tensorflow.python import keras\n\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import errors\nfrom tensorflow.python.framework import sparse_tensor\nfrom tensorflow.python.keras import backend\nfrom tensorflow.python.keras import keras_parameterized\nfrom tensorflow.python.keras.layers import core\nfrom tensorflow.python.keras.layers.preprocessing import category_encoding\nfrom tensorflow.python.keras.layers.preprocessing import preprocessing_test_utils\nfrom tensorflow.python.ops import sparse_ops\nfrom tensorflow.python.ops.ragged import ragged_factory_ops\nfrom tensorflow.python.platform import test\n\n\n@keras_parameterized.run_all_keras_modes(always_skip_v1=True)\nclass CategoryEncodingInputTest(keras_parameterized.TestCase,\n preprocessing_test_utils.PreprocessingLayerTest\n ):\n\n def test_dense_input_sparse_output(self):\n input_array = constant_op.constant([[1, 2, 3], [3, 3, 0]])\n\n # The expected output should be (X for missing value):\n # [[X, 1, 1, 1, X, X]\n # [1, X, X, 2, X, X]]\n expected_indices = [[0, 1], [0, 2], [0, 3], [1, 0], [1, 3]]\n expected_values = [1, 1, 1, 1, 2]\n num_tokens = 6\n\n input_data = keras.Input(shape=(None,), dtype=dtypes.int32)\n layer = category_encoding.CategoryEncoding(\n num_tokens=num_tokens, output_mode=category_encoding.COUNT, sparse=True)\n int_data = layer(input_data)\n\n model = keras.Model(inputs=input_data, outputs=int_data)\n sp_output_dataset = model.predict(input_array, steps=1)\n self.assertAllEqual(expected_values, sp_output_dataset.values)\n self.assertAllEqual(expected_indices, sp_output_dataset.indices)\n\n # Assert sparse output is same as dense output.\n layer = category_encoding.CategoryEncoding(\n num_tokens=num_tokens,\n output_mode=category_encoding.COUNT,\n sparse=False)\n int_data = layer(input_data)\n model = keras.Model(inputs=input_data, outputs=int_data)\n output_dataset = model.predict(input_array, steps=1)\n self.assertAllEqual(\n sparse_ops.sparse_tensor_to_dense(sp_output_dataset, default_value=0),\n output_dataset)\n\n def test_sparse_input(self):\n input_array = np.array([[1, 2, 3, 0], [0, 3, 1, 0]], dtype=np.int64)\n sparse_tensor_data = sparse_ops.from_dense(input_array)\n\n # pyformat: disable\n expected_output = [[0, 1, 1, 1, 0, 0],\n [0, 1, 0, 1, 0, 0]]\n # pyformat: enable\n num_tokens = 6\n expected_output_shape = [None, num_tokens]\n\n input_data = keras.Input(shape=(None,), dtype=dtypes.int64, sparse=True)\n\n layer = category_encoding.CategoryEncoding(\n num_tokens=num_tokens, output_mode=category_encoding.MULTI_HOT)\n int_data = layer(input_data)\n self.assertAllEqual(expected_output_shape, int_data.shape.as_list())\n\n model = keras.Model(inputs=input_data, outputs=int_data)\n output_dataset = model.predict(sparse_tensor_data, steps=1)\n self.assertAllEqual(expected_output, output_dataset)\n\n def test_sparse_input_with_weights(self):\n input_array = np.array([[1, 2, 3, 4], [4, 3, 1, 4]], dtype=np.int64)\n weights_array = np.array([[.1, .2, .3, .4], [.2, .1, .4, .3]])\n sparse_tensor_data = sparse_ops.from_dense(input_array)\n sparse_weight_data = sparse_ops.from_dense(weights_array)\n\n # pyformat: disable\n expected_output = [[0, .1, .2, .3, .4, 0],\n [0, .4, 0, .1, .5, 0]]\n # pyformat: enable\n num_tokens = 6\n expected_output_shape = [None, num_tokens]\n\n input_data = keras.Input(shape=(None,), dtype=dtypes.int64, sparse=True)\n weight_data = keras.Input(shape=(None,), dtype=dtypes.float32, sparse=True)\n\n layer = category_encoding.CategoryEncoding(\n num_tokens=num_tokens, output_mode=category_encoding.COUNT)\n int_data = layer(input_data, count_weights=weight_data)\n self.assertAllEqual(expected_output_shape, int_data.shape.as_list())\n\n model = keras.Model(inputs=[input_data, weight_data], outputs=int_data)\n output_dataset = model.predict([sparse_tensor_data, sparse_weight_data],\n steps=1)\n self.assertAllClose(expected_output, output_dataset)\n\n def test_sparse_input_sparse_output(self):\n sp_inp = sparse_tensor.SparseTensor(\n indices=[[0, 0], [1, 1], [2, 0], [2, 1], [3, 1]],\n values=[0, 2, 1, 1, 0],\n dense_shape=[4, 2])\n input_data = keras.Input(shape=(None,), dtype=dtypes.int64, sparse=True)\n\n # The expected output should be (X for missing value):\n # [[1, X, X, X]\n # [X, X, 1, X]\n # [X, 2, X, X]\n # [1, X, X, X]]\n expected_indices = [[0, 0], [1, 2], [2, 1], [3, 0]]\n expected_values = [1, 1, 2, 1]\n num_tokens = 6\n\n layer = category_encoding.CategoryEncoding(\n num_tokens=num_tokens, output_mode=category_encoding.COUNT, sparse=True)\n int_data = layer(input_data)\n\n model = keras.Model(inputs=input_data, outputs=int_data)\n sp_output_dataset = model.predict(sp_inp, steps=1)\n self.assertAllEqual(expected_values, sp_output_dataset.values)\n self.assertAllEqual(expected_indices, sp_output_dataset.indices)\n\n # Assert sparse output is same as dense output.\n layer = category_encoding.CategoryEncoding(\n num_tokens=num_tokens,\n output_mode=category_encoding.COUNT,\n sparse=False)\n int_data = layer(input_data)\n model = keras.Model(inputs=input_data, outputs=int_data)\n output_dataset = model.predict(sp_inp, steps=1)\n self.assertAllEqual(\n sparse_ops.sparse_tensor_to_dense(sp_output_dataset, default_value=0),\n output_dataset)\n\n def test_sparse_input_sparse_output_with_weights(self):\n indices = [[0, 0], [1, 1], [2, 0], [2, 1], [3, 1]]\n sp_inp = sparse_tensor.SparseTensor(\n indices=indices, values=[0, 2, 1, 1, 0], dense_shape=[4, 2])\n input_data = keras.Input(shape=(None,), dtype=dtypes.int64, sparse=True)\n sp_weight = sparse_tensor.SparseTensor(\n indices=indices, values=[.1, .2, .4, .3, .2], dense_shape=[4, 2])\n weight_data = keras.Input(shape=(None,), dtype=dtypes.float32, sparse=True)\n\n # The expected output should be (X for missing value):\n # [[1, X, X, X]\n # [X, X, 1, X]\n # [X, 2, X, X]\n # [1, X, X, X]]\n expected_indices = [[0, 0], [1, 2], [2, 1], [3, 0]]\n expected_values = [.1, .2, .7, .2]\n num_tokens = 6\n\n layer = category_encoding.CategoryEncoding(\n num_tokens=num_tokens, output_mode=category_encoding.COUNT, sparse=True)\n int_data = layer(input_data, count_weights=weight_data)\n\n model = keras.Model(inputs=[input_data, weight_data], outputs=int_data)\n sp_output_dataset = model.predict([sp_inp, sp_weight], steps=1)\n self.assertAllClose(expected_values, sp_output_dataset.values)\n self.assertAllEqual(expected_indices, sp_output_dataset.indices)\n\n def test_ragged_input(self):\n input_array = ragged_factory_ops.constant([[1, 2, 3], [3, 1]])\n\n # pyformat: disable\n expected_output = [[0, 1, 1, 1, 0, 0],\n [0, 1, 0, 1, 0, 0]]\n # pyformat: enable\n num_tokens = 6\n expected_output_shape = [None, num_tokens]\n\n input_data = keras.Input(shape=(None,), dtype=dtypes.int32, ragged=True)\n\n layer = category_encoding.CategoryEncoding(\n num_tokens=num_tokens, output_mode=category_encoding.MULTI_HOT)\n int_data = layer(input_data)\n\n self.assertAllEqual(expected_output_shape, int_data.shape.as_list())\n\n model = keras.Model(inputs=input_data, outputs=int_data)\n output_dataset = model.predict(input_array, steps=1)\n self.assertAllEqual(expected_output, output_dataset)\n\n def test_ragged_input_sparse_output(self):\n input_array = ragged_factory_ops.constant([[1, 2, 3], [3, 3]])\n\n # The expected output should be (X for missing value):\n # [[X, 1, 1, 1]\n # [X, X, X, 2]]\n expected_indices = [[0, 1], [0, 2], [0, 3], [1, 3]]\n expected_values = [1, 1, 1, 2]\n num_tokens = 6\n\n input_data = keras.Input(shape=(None,), dtype=dtypes.int32, ragged=True)\n layer = category_encoding.CategoryEncoding(\n num_tokens=num_tokens, output_mode=category_encoding.COUNT, sparse=True)\n int_data = layer(input_data)\n\n model = keras.Model(inputs=input_data, outputs=int_data)\n sp_output_dataset = model.predict(input_array, steps=1)\n self.assertAllEqual(expected_values, sp_output_dataset.values)\n self.assertAllEqual(expected_indices, sp_output_dataset.indices)\n\n # Assert sparse output is same as dense output.\n layer = category_encoding.CategoryEncoding(\n num_tokens=num_tokens,\n output_mode=category_encoding.COUNT,\n sparse=False)\n int_data = layer(input_data)\n model = keras.Model(inputs=input_data, outputs=int_data)\n output_dataset = model.predict(input_array, steps=1)\n self.assertAllEqual(\n sparse_ops.sparse_tensor_to_dense(sp_output_dataset, default_value=0),\n output_dataset)\n\n def test_sparse_output_and_dense_layer(self):\n input_array = constant_op.constant([[1, 2, 3], [3, 3, 0]])\n\n num_tokens = 4\n\n input_data = keras.Input(shape=(None,), dtype=dtypes.int32)\n encoding_layer = category_encoding.CategoryEncoding(\n num_tokens=num_tokens, output_mode=category_encoding.COUNT, sparse=True)\n int_data = encoding_layer(input_data)\n dense_layer = keras.layers.Dense(units=1)\n output_data = dense_layer(int_data)\n\n model = keras.Model(inputs=input_data, outputs=output_data)\n _ = model.predict(input_array, steps=1)\n\n def test_dense_oov_input(self):\n valid_array = constant_op.constant([[0, 1, 2], [0, 1, 2]])\n invalid_array = constant_op.constant([[0, 1, 2], [2, 3, 1]])\n num_tokens = 3\n expected_output_shape = [None, num_tokens]\n encoder_layer = category_encoding.CategoryEncoding(num_tokens)\n input_data = keras.Input(shape=(3,), dtype=dtypes.int32)\n int_data = encoder_layer(input_data)\n self.assertAllEqual(expected_output_shape, int_data.shape.as_list())\n model = keras.Model(inputs=input_data, outputs=int_data)\n # Call predict once on valid input to compile a graph and test control flow.\n _ = model.predict(valid_array, steps=1)\n with self.assertRaisesRegex(\n errors.InvalidArgumentError,\n \".*must be in the range 0 <= values < num_tokens.*\"):\n _ = model.predict(invalid_array, steps=1)\n\n def test_dense_negative(self):\n valid_array = constant_op.constant([[0, 1, 2], [0, 1, 2]])\n invalid_array = constant_op.constant([[1, 2, 0], [2, 2, -1]])\n num_tokens = 3\n expected_output_shape = [None, num_tokens]\n encoder_layer = category_encoding.CategoryEncoding(num_tokens)\n input_data = keras.Input(shape=(3,), dtype=dtypes.int32)\n int_data = encoder_layer(input_data)\n self.assertAllEqual(expected_output_shape, int_data.shape.as_list())\n model = keras.Model(inputs=input_data, outputs=int_data)\n # Call predict once on valid input to compile a graph and test control flow.\n _ = model.predict(valid_array, steps=1)\n with self.assertRaisesRegex(\n errors.InvalidArgumentError,\n \".*must be in the range 0 <= values < num_tokens.*\"):\n _ = model.predict(invalid_array, steps=1)\n\n def test_legacy_max_tokens_arg(self):\n input_array = np.array([[1, 2, 3, 1]])\n expected_output = [[0, 1, 1, 1, 0, 0]]\n num_tokens = 6\n expected_output_shape = [None, num_tokens]\n\n input_data = keras.Input(shape=(None,), dtype=dtypes.int32)\n layer = category_encoding.CategoryEncoding(\n max_tokens=num_tokens, output_mode=category_encoding.MULTI_HOT)\n int_data = layer(input_data)\n self.assertAllEqual(expected_output_shape, int_data.shape.as_list())\n\n model = keras.Model(inputs=input_data, outputs=int_data)\n output_dataset = model.predict(input_array)\n self.assertAllEqual(expected_output, output_dataset)\n\n\n@keras_parameterized.run_all_keras_modes\nclass CategoryEncodingOutputTest(keras_parameterized.TestCase,\n preprocessing_test_utils.PreprocessingLayerTest\n ):\n\n def test_one_hot_output(self):\n input_data = np.array([[3], [2], [0], [1]])\n expected_output = [\n [0, 0, 0, 1],\n [0, 0, 1, 0],\n [1, 0, 0, 0],\n [0, 1, 0, 0],\n ]\n num_tokens = 4\n expected_output_shape = [None, num_tokens]\n\n layer = category_encoding.CategoryEncoding(\n num_tokens=num_tokens, output_mode=category_encoding.ONE_HOT)\n inputs = keras.Input(shape=(1,), dtype=dtypes.int32)\n outputs = layer(inputs)\n model = keras.Model(inputs=inputs, outputs=outputs)\n output_dataset = model(input_data)\n self.assertAllEqual(expected_output_shape, outputs.shape.as_list())\n self.assertAllEqual(expected_output, output_dataset)\n\n def test_one_hot_output_rank_one_input(self):\n input_data = np.array([3, 2, 0, 1])\n expected_output = [\n [0, 0, 0, 1],\n [0, 0, 1, 0],\n [1, 0, 0, 0],\n [0, 1, 0, 0],\n ]\n num_tokens = 4\n expected_output_shape = [None, num_tokens]\n\n # Test call on layer directly.\n layer = category_encoding.CategoryEncoding(\n num_tokens=num_tokens, output_mode=category_encoding.ONE_HOT)\n output_data = layer(input_data)\n self.assertAllEqual(expected_output, output_data)\n\n # Test call on model.\n inputs = keras.Input(shape=(1,), dtype=dtypes.int32)\n outputs = layer(inputs)\n model = keras.Model(inputs=inputs, outputs=outputs)\n output_data = model(input_data)\n self.assertAllEqual(expected_output_shape, outputs.shape.as_list())\n self.assertAllEqual(expected_output, output_data)\n\n def test_one_hot_output_rank_zero_input(self):\n input_data = np.array(3)\n expected_output = [0, 0, 0, 1]\n num_tokens = 4\n expected_output_shape = [None, num_tokens]\n\n # Test call on layer directly.\n layer = category_encoding.CategoryEncoding(\n num_tokens=num_tokens, output_mode=category_encoding.ONE_HOT)\n output_data = layer(input_data)\n self.assertAllEqual(expected_output, output_data)\n\n # Test call on model.\n inputs = keras.Input(shape=(1,), dtype=dtypes.int32)\n outputs = layer(inputs)\n model = keras.Model(inputs=inputs, outputs=outputs)\n output_data = model(input_data)\n\n self.assertAllEqual(expected_output_shape, outputs.shape.as_list())\n self.assertAllEqual(expected_output, output_data)\n\n def test_one_hot_rank_3_output_fails(self):\n layer = category_encoding.CategoryEncoding(\n num_tokens=4, output_mode=category_encoding.ONE_HOT)\n with self.assertRaisesRegex(ValueError, \"only outputs up to rank 2\"):\n _ = layer(keras.Input(shape=(4,), dtype=dtypes.int32))\n with self.assertRaisesRegex(ValueError, \"only outputs up to rank 2\"):\n _ = layer(np.array([[3, 2, 0, 1], [3, 2, 0, 1]]))\n\n def test_multi_hot_output(self):", "answers": [" input_data = np.array([[1, 2, 3, 1], [0, 3, 1, 0]])"], "length": 1330, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "c01d3c18-5a61-4215-821e-fddfb785a71e", "reasoning": "The method test_multi_hot_output is being defined. Following the pattern of previous test methods, the first line inside the method sets up the input data array. For a multi-hot test, a typical input is a 2D array of integer categories. Therefore the next line should create such an array, e.g., np.array([[1, 2, 3], [3, 1, 0]]).", "reasoning_model_answer": "input_data = np.array([[1, 2, 3], [3, 1, 0]])", "assistant_with_reasoning": "\nThe method test_multi_hot_output is being defined. Following the pattern of previous test methods, the first line inside the method sets up the input data array. For a multi-hot test, a typical input is a 2D array of integer categories. Therefore the next line should create such an array, e.g., np.array([[1, 2, 3], [3, 1, 0]]).\n\ninput_data = np.array([[1, 2, 3], [3, 1, 0]])", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 5.766, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 15773, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "input_data = np.array([[1, 2, 3], [3, 1, 0]])", "score": 0.9, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "using System;\nusing System.Collections.Generic;\nusing System.Text;\n\nusing Hydra.Framework.Mapping.Styles;\n\nnamespace Hydra.Framework.Mapping.Rendering.Thematics\n{\n //\n // **********************************************************************\n /// \n /// The GradientTheme class defines a gradient color thematic rendering of features based by a numeric attribute.\n /// \n // **********************************************************************\n //\n public class GradientTheme\n : ITheme\n {\n #region Private Member Variables\n //\n // **********************************************************************\n /// \n /// Column StateName\n /// \n // **********************************************************************\n //\n private string m_ColumnName;\n\n //\n // **********************************************************************\n /// \n /// Minimum Value\n /// \n // **********************************************************************\n //\n private double m_Min;\n\n //\n // **********************************************************************\n /// \n /// Maximum Value\n /// \n // **********************************************************************\n //\n private double m_Max;\n\n //\n // **********************************************************************\n /// \n /// Minimum AbstractStyle\n /// \n // **********************************************************************\n //\n private Hydra.Framework.Mapping.Styles.IStyle m_MinStyle;\n\n //\n // **********************************************************************\n /// \n /// Maximum AbstractStyle\n /// \n // **********************************************************************\n //\n private Hydra.Framework.Mapping.Styles.IStyle m_MaxStyle;\n\n //\n // **********************************************************************\n /// \n /// Text Colour Blend\n /// \n // **********************************************************************\n //\n private ColorBlend m_TextColorBlend;\n\n //\n // **********************************************************************\n /// \n /// Line Colour Blend\n /// \n // **********************************************************************\n //\n private ColorBlend m_LineColorBlend;\n\n //\n // **********************************************************************\n /// \n /// Fill Colour Blend\n /// \n // **********************************************************************\n //\n private ColorBlend m_FillColorBlend;\n\n #endregion\n\n #region Constructors\n //\n // **********************************************************************\n /// \n /// Initializes a new instance of the GradientTheme class\n /// \n /// StateName of column to extract the attribute\n /// Minimum value\n /// Maximum value\n /// Color for minimum value\n /// Color for maximum value\n /// \n /// \tThe gradient theme interpolates linearly between two styles based on a numerical attribute in the datasource.\n /// This is useful for scaling symbols, line widths, line and fill colors from numerical attributes.\n /// \tColors are interpolated between two colors, but if you want to interpolate through more colors (fx. a rainbow),\n /// set the , and properties\n /// to a custom .\n /// \n /// \tThe following properties are scaled (properties not mentioned here are not interpolated):\n /// \n /// \t\t\tPropertyRemarks\n /// \t\t\tRed, Green, Blue and Alpha values are linearly interpolated.\n /// \t\t\tThe color, width, color of pens are interpolated. MiterLimit,StartCap,EndCap,LineJoin,DashStyle,DashPattern,DashOffset,DashCap,CompoundArray, and Alignment are switched in the middle of the min/max values.\n /// \t\t\tSolidBrush color are interpolated. Other brushes are not supported.\n /// \t\t\tMaxVisible, MinVisible, Line, Outline, Fill and SymbolScale are scaled linearly. Symbol, EnableOutline and Enabled switch in the middle of the min/max values.\n /// \t\t\tFontSize, BackColor, ForeColor, MaxVisible, MinVisible, Offset are scaled linearly. All other properties use min-style.\n /// \t\t\n /// \t\n /// \t\n /// Creating a rainbow colorblend showing colors from red, through yellow, green and blue depicting\n /// the population density of a country.\n /// \n /// //Create two vector styles to interpolate between\n /// Hydra.Framework.Mapping.Styles.VectorStyle min = new Hydra.Framework.Mapping.Styles.VectorStyle();\n /// Hydra.Framework.Mapping.Styles.VectorStyle max = new Hydra.Framework.Mapping.Styles.VectorStyle();\n /// min.Outline.Width = 1f; //Outline width of the minimum value\n /// max.Outline.Width = 3f; //Outline width of the maximum value\n /// //Create a theme interpolating population density between 0 and 400\n /// Hydra.Framework.Mapping.Rendering.Thematics.GradientTheme popdens = new Hydra.Framework.Mapping.Rendering.Thematics.GradientTheme(\"PopDens\", 0, 400, min, max);\n /// //Set the fill-style colors to be a rainbow blend from red to blue.\n /// popdens.FillColorBlend = Hydra.Framework.Mapping.Rendering.Thematics.ColorBlend.Rainbow5;\n /// myVectorLayer.Theme = popdens;\n /// \n /// \t\n /// \n // **********************************************************************\n //\n public GradientTheme(string columnName, double minValue, double maxValue, Hydra.Framework.Mapping.Styles.IStyle minStyle, Hydra.Framework.Mapping.Styles.IStyle maxStyle)\n {\n m_ColumnName = columnName;\n m_Min = minValue;\n m_Max = maxValue;\n m_MaxStyle = maxStyle;\n m_MinStyle = minStyle;\n }\n #endregion\n\n #region Properties\n //\n // **********************************************************************\n /// \n /// Gets or sets the column name from where to get the attribute value\n /// \n /// The name of the column.\n // **********************************************************************\n //\n public string ColumnName\n {\n get\n {\n return m_ColumnName;\n }\n set\n {\n m_ColumnName = value;\n }\n }\n\n //\n // **********************************************************************\n /// \n /// Gets or sets the minimum value of the gradient\n /// \n /// The min.\n // **********************************************************************\n //\n public double Min\n {\n get\n {\n return m_Min;\n }\n set\n {\n m_Min = value;\n }\n }\n\n //\n // **********************************************************************\n /// \n /// Gets or sets the maximum value of the gradient\n /// \n /// The max.\n // **********************************************************************\n //\n public double Max\n {\n get\n {\n return m_Max;\n }\n set\n {\n m_Max = value;\n }\n }\n\n //\n // **********************************************************************\n /// \n /// Gets or sets the style for the minimum value\n /// \n /// The min style.\n // **********************************************************************\n //\n public Hydra.Framework.Mapping.Styles.IStyle MinStyle\n {\n get\n {\n return m_MinStyle;\n }\n set\n {\n m_MinStyle = value;\n }\n }\n\n //\n // **********************************************************************\n /// \n /// Gets or sets the style for the maximum value\n /// \n /// The max style.\n // **********************************************************************\n //\n public Hydra.Framework.Mapping.Styles.IStyle MaxStyle\n {\n get\n {\n return m_MaxStyle;\n }\n set\n {\n m_MaxStyle = value;\n }\n }\n\n //\n // **********************************************************************\n /// \n /// Gets or sets the used on labels\n /// \n /// The text color blend.\n // **********************************************************************\n //\n public ColorBlend TextColorBlend\n {\n get\n {\n return m_TextColorBlend;\n }\n set\n {\n m_TextColorBlend = value;\n }\n }\n\n //\n // **********************************************************************\n /// \n /// Gets or sets the used on lines\n /// \n /// The line color blend.\n // **********************************************************************\n //\n public ColorBlend LineColorBlend\n {\n get\n {\n return m_LineColorBlend;\n }\n set\n {\n m_LineColorBlend = value;\n }\n }\n\n //\n // **********************************************************************\n /// \n /// Gets or sets the used as Fill\n /// \n /// The fill color blend.\n // **********************************************************************\n //\n public ColorBlend FillColorBlend\n {\n get\n {\n return m_FillColorBlend;\n }\n set\n {\n m_FillColorBlend = value;\n }\n }\n #endregion\n\n #region ITheme Implementation\n //\n // **********************************************************************\n /// \n /// Returns the style based on a numeric DataColumn, where style\n /// properties are linearly interpolated between max and min values.\n /// \n /// Feature\n /// \n /// \tAbstractStyle calculated by a linear interpolation between the min/max styles\n /// \n // **********************************************************************\n //\n public Hydra.Framework.Mapping.Styles.IStyle GetStyle(Hydra.Framework.Mapping.Data.FeatureDataRow row)\n {\n double attr = 0;\n try\n {\n attr = Convert.ToDouble(row[this.m_ColumnName]);\n }\n catch\n {\n throw new ApplicationException(\"Invalid Attribute type in Gradient Theme - Couldn't parse attribute (must be numerical)\");\n }\n\n if (m_MinStyle.GetType() != m_MaxStyle.GetType())\n throw new ArgumentException(\"MinStyle and MaxStyle must be of the same type\");\n\n switch (MinStyle.GetType().FullName)\n {\n case \"Hydra.Framework.Mapping.Styles.VectorStyle\":\n return CalculateVectorStyle(MinStyle as VectorStyle, MaxStyle as VectorStyle, attr);\n\n case \"Hydra.Framework.Mapping.Styles.LabelStyle\":\n return CalculateLabelStyle(MinStyle as LabelStyle, MaxStyle as LabelStyle, attr);\n\n default:\n throw new ArgumentException(\"Only Hydra.Framework.Mapping.Styles.VectorStyle and Hydra.Framework.Mapping.Styles.LabelStyle are supported for the gradient theme\");\n }\n }\n\n //\n // **********************************************************************\n /// \n /// Calculates the vector style.\n /// \n /// The min.\n /// The max.\n /// The value.\n /// \n // **********************************************************************\n //\n private VectorStyle CalculateVectorStyle(Hydra.Framework.Mapping.Styles.VectorStyle min, Hydra.Framework.Mapping.Styles.VectorStyle max, double value)\n {\n VectorStyle style = new VectorStyle();\n double dFrac = Fraction(value);\n float fFrac = Convert.ToSingle(dFrac);\n\n style.Enabled = (dFrac > 0.5 ? min.Enabled : max.Enabled);\n style.EnableOutline = (dFrac > 0.5 ? min.EnableOutline : max.EnableOutline);\n\n if (m_FillColorBlend != null)\n style.Fill = new System.Drawing.SolidBrush(m_FillColorBlend.GetColor(fFrac));\n else if (min.Fill != null && max.Fill != null)\n style.Fill = InterpolateBrush(min.Fill, max.Fill, value);\n\n if (min.Line != null && max.Line != null)\n style.Line = InterpolatePen(min.Line, max.Line, value);\n\n if (m_LineColorBlend != null)\n style.Line.Color = m_LineColorBlend.GetColor(fFrac);\n\n if (min.Outline != null && max.Outline != null)\n style.Outline = InterpolatePen(min.Outline, max.Outline, value);\n\n style.MinVisible = InterpolateDouble(min.MinVisible, max.MinVisible, value);\n style.MaxVisible = InterpolateDouble(min.MaxVisible, max.MaxVisible, value);\n style.Symbol = (dFrac > 0.5 ? min.Symbol : max.Symbol);\n style.SymbolOffset = (dFrac > 0.5 ? min.SymbolOffset : max.SymbolOffset); // We don't interpolate the offset but let it follow the symbol instead\n style.SymbolScale = InterpolateFloat(min.SymbolScale, max.SymbolScale, value);\n\n return style;\n }\n\n //\n // **********************************************************************\n /// \n /// Calculates the label style.\n /// \n /// The min.\n /// The max.\n /// The value.\n /// \n // **********************************************************************\n //\n private LabelStyle CalculateLabelStyle(Hydra.Framework.Mapping.Styles.LabelStyle min, Hydra.Framework.Mapping.Styles.LabelStyle max, double value)\n {\n LabelStyle style = new LabelStyle();\n style.CollisionDetection = min.CollisionDetection;\n style.Enabled = InterpolateBool(min.Enabled, max.Enabled, value);\n float FontSize = InterpolateFloat(min.Font.Size, max.Font.Size, value);\n style.Font = new System.Drawing.Font(min.Font.FontFamily, FontSize, min.Font.Style);\n\n if (min.BackColor != null && max.BackColor != null)\n style.BackColor = InterpolateBrush(min.BackColor, max.BackColor, value);\n\n if (m_TextColorBlend != null)\n style.ForeColor = m_LineColorBlend.GetColor(Convert.ToSingle(Fraction(value)));\n else\n style.ForeColor = InterpolateColor(min.ForeColor, max.ForeColor, value);\n\n if (min.Halo != null && max.Halo != null)\n style.Halo = InterpolatePen(min.Halo, max.Halo, value);\n\n style.MinVisible = InterpolateDouble(min.MinVisible, max.MinVisible, value);\n style.MaxVisible = InterpolateDouble(min.MaxVisible, max.MaxVisible, value);\n style.Offset = new System.Drawing.PointF(InterpolateFloat(min.Offset.X, max.Offset.X, value), InterpolateFloat(min.Offset.Y, max.Offset.Y, value));\n\n return style;\n }\n\n //\n // **********************************************************************\n /// \n /// Fractions the specified attr.\n /// \n /// The attr.\n /// \n // **********************************************************************\n //\n private double Fraction(double attr)\n {\n if (attr < m_Min)\n return 0;\n\n if (attr > m_Max)\n return 1;\n", "answers": [" return (attr - m_Min) / (m_Max - m_Min);"], "length": 1365, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "a4d4255d-c7f4-48d5-812c-c37841f846ad", "reasoning": "The Fraction method calculates the normalized position of a value between the minimum and maximum of the gradient. After handling values below the minimum (return 0) and above the maximum (return 1), the next logical step is to compute the linear interpolation fraction for values within the range, which is (attr - m_Min) / (m_Max - m_Min). This line completes the method's logic.", "reasoning_model_answer": "return (attr - m_Min) / (m_Max - m_Min);", "assistant_with_reasoning": "\nThe Fraction method calculates the normalized position of a value between the minimum and maximum of the gradient. After handling values below the minimum (return 0) and above the maximum (return 1), the next logical step is to compute the linear interpolation fraction for values within the range, which is (attr - m_Min) / (m_Max - m_Min). This line completes the method's logic.\n\nreturn (attr - m_Min) / (m_Max - m_Min);", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 2.437, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 18646, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "return (attr - m_Min) / (m_Max - m_Min);", "score": 0.87, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "# vim: tabstop=4 shiftwidth=4 softtabstop=4\n\n# Copyright (c) 2012 NetApp, Inc.\n# Copyright (c) 2012 OpenStack LLC.\n# All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\"\"\"\nVolume driver for NetApp storage systems.\n\nThis driver requires NetApp OnCommand 5.0 and one or more Data\nONTAP 7-mode storage systems with installed iSCSI licenses.\n\n\"\"\"\n\nimport string\nimport time\n\nimport suds\nfrom suds import client\nfrom suds.sax import text\n\nfrom nova import exception\nfrom nova import flags\nfrom nova import log as logging\nfrom nova.openstack.common import cfg\nfrom nova.volume import driver\n\nLOG = logging.getLogger(__name__)\n\nnetapp_opts = [\n cfg.StrOpt('netapp_wsdl_url',\n default=None,\n help='URL of the WSDL file for the DFM server'),\n cfg.StrOpt('netapp_login',\n default=None,\n help='User name for the DFM server'),\n cfg.StrOpt('netapp_password',\n default=None,\n help='Password for the DFM server'),\n cfg.StrOpt('netapp_server_hostname',\n default=None,\n help='Hostname for the DFM server'),\n cfg.IntOpt('netapp_server_port',\n default=8088,\n help='Port number for the DFM server'),\n cfg.StrOpt('netapp_storage_service',\n default=None,\n help='Storage service to use for provisioning'),\n cfg.StrOpt('netapp_vfiler',\n default=None,\n help='Vfiler to use for provisioning'),\n ]\n\nFLAGS = flags.FLAGS\nFLAGS.register_opts(netapp_opts)\n\n\nclass NetAppISCSIDriver(driver.ISCSIDriver):\n \"\"\"NetApp iSCSI volume driver.\"\"\"\n\n def __init__(self, *args, **kwargs):\n super(NetAppISCSIDriver, self).__init__(*args, **kwargs)\n\n def _check_fail(self, request, response):\n if 'failed' == response.Status:\n name = request.Name\n reason = response.Reason\n msg = _('API %(name)sfailed: %(reason)s')\n raise exception.NovaException(msg % locals())\n\n def _create_client(self, wsdl_url, login, password, hostname, port):\n \"\"\"\n Instantiate a \"suds\" client to make web services calls to the\n DFM server. Note that the WSDL file is quite large and may take\n a few seconds to parse.\n \"\"\"\n self.client = client.Client(wsdl_url,\n username=login,\n password=password)\n soap_url = 'http://%s:%s/apis/soap/v1' % (hostname, port)\n self.client.set_options(location=soap_url)\n\n def _set_storage_service(self, storage_service):\n \"\"\"Set the storage service to use for provisioning\"\"\"\n self.storage_service = storage_service\n\n def _set_vfiler(self, vfiler):\n \"\"\"Set the vfiler to use for provisioning\"\"\"\n self.vfiler = vfiler\n\n def _check_flags(self):\n \"\"\"Ensure that the flags we care about are set.\"\"\"\n required_flags = ['netapp_wsdl_url', 'netapp_login', 'netapp_password',\n 'netapp_server_hostname', 'netapp_server_port',\n 'netapp_storage_service']\n for flag in required_flags:\n if not getattr(FLAGS, flag, None):\n raise exception.NovaException(_('%s is not set') % flag)\n\n def do_setup(self, context):\n \"\"\"\n Called one time by the manager after the driver is loaded.\n Validate the flags we care about and setup the suds (web services)\n client.\n \"\"\"\n self._check_flags()\n self._create_client(FLAGS.netapp_wsdl_url, FLAGS.netapp_login,\n FLAGS.netapp_password, FLAGS.netapp_server_hostname,\n FLAGS.netapp_server_port)\n self._set_storage_service(FLAGS.netapp_storage_service)\n if FLAGS.netapp_vfiler:\n self._set_vfiler(FLAGS.netapp_vfiler)\n\n def check_for_setup_error(self):\n \"\"\"Invoke a web services API to make sure we can talk to the server.\"\"\"\n res = self.client.service.DfmAbout()\n LOG.debug(_(\"Connected to DFM server\"))\n\n def _get_job_progress(self, job_id):\n \"\"\"\n Obtain the latest progress report for the job and return the\n list of progress events.\n \"\"\"\n server = self.client.service\n res = server.DpJobProgressEventListIterStart(JobId=job_id)\n tag = res.Tag\n event_list = []\n try:\n while True:\n res = server.DpJobProgressEventListIterNext(Tag=tag,\n Maximum=100)\n if not hasattr(res, 'ProgressEvents'):\n break\n event_list += res.ProgressEvents.DpJobProgressEventInfo\n finally:\n server.DpJobProgressEventListIterEnd(Tag=tag)\n return event_list\n\n def _wait_for_job(self, job_id):\n \"\"\"\n Poll the job until it completes or an error is detected. Return the\n final list of progress events if it completes successfully.\n \"\"\"\n while True:\n events = self._get_job_progress(job_id)\n for event in events:\n if event.EventStatus == 'error':\n raise exception.NovaException(_('Job failed: %s') %\n (event.ErrorMessage))\n if event.EventType == 'job-end':\n return events\n time.sleep(5)\n\n def _dataset_name(self, project):\n \"\"\"Return the dataset name for a given project \"\"\"\n _project = string.replace(string.replace(project, ' ', '_'), '-', '_')\n return 'OpenStack_' + _project\n\n def _does_dataset_exist(self, dataset_name):\n \"\"\"Check if a dataset already exists\"\"\"\n server = self.client.service\n try:\n res = server.DatasetListInfoIterStart(ObjectNameOrId=dataset_name)\n tag = res.Tag\n except suds.WebFault:\n return False\n try:\n res = server.DatasetListInfoIterNext(Tag=tag, Maximum=1)\n if hasattr(res, 'Datasets') and res.Datasets.DatasetInfo:\n return True\n finally:\n server.DatasetListInfoIterEnd(Tag=tag)\n return False\n\n def _create_dataset(self, dataset_name):\n \"\"\"\n Create a new dataset using the storage service. The export settings are\n set to create iSCSI LUNs aligned for Linux.\n \"\"\"\n server = self.client.service\n\n lunmap = self.client.factory.create('DatasetLunMappingInfo')\n lunmap.IgroupOsType = 'linux'\n export = self.client.factory.create('DatasetExportInfo')\n export.DatasetExportProtocol = 'iscsi'\n export.DatasetLunMappingInfo = lunmap\n detail = self.client.factory.create('StorageSetInfo')\n detail.DpNodeName = 'Primary data'\n detail.DatasetExportInfo = export\n if hasattr(self, 'vfiler'):\n detail.ServerNameOrId = self.vfiler\n details = self.client.factory.create('ArrayOfStorageSetInfo')\n details.StorageSetInfo = [detail]\n\n server.StorageServiceDatasetProvision(\n StorageServiceNameOrId=self.storage_service,\n DatasetName=dataset_name,\n AssumeConfirmation=True,\n StorageSetDetails=details)\n\n def _provision(self, name, description, project, size):\n \"\"\"\n Provision a LUN through provisioning manager. The LUN will be created\n inside a dataset associated with the project. If the dataset doesn't\n already exist, we create it using the storage service specified in the\n nova conf.\n \"\"\"\n\n dataset_name = self._dataset_name(project)\n if not self._does_dataset_exist(dataset_name):\n self._create_dataset(dataset_name)\n\n info = self.client.factory.create('ProvisionMemberRequestInfo')\n info.Name = name\n if description:\n info.Description = description\n info.Size = size\n info.MaximumSnapshotSpace = 2 * long(size)\n\n server = self.client.service\n lock_id = server.DatasetEditBegin(DatasetNameOrId=dataset_name)\n try:\n server.DatasetProvisionMember(EditLockId=lock_id,\n ProvisionMemberRequestInfo=info)\n res = server.DatasetEditCommit(EditLockId=lock_id,\n AssumeConfirmation=True)\n except (suds.WebFault, Exception):\n server.DatasetEditRollback(EditLockId=lock_id)\n msg = _('Failed to provision dataset member')\n raise exception.NovaException(msg)\n\n lun_id = None\n\n for info in res.JobIds.JobInfo:\n events = self._wait_for_job(info.JobId)\n for event in events:\n if event.EventType != 'lun-create':\n continue\n lun_id = event.ProgressLunInfo.LunPathId\n\n if not lun_id:\n msg = _('No LUN was created by the provision job')\n raise exception.NovaException(msg)\n\n def _remove_destroy(self, name, project):\n \"\"\"\n Remove the LUN from the dataset and destroy the actual LUN on the\n storage system.\n \"\"\"\n lun_id = self._get_lun_id(name, project)\n if not lun_id:\n msg = _(\"Failed to find LUN ID for volume %s\") % (name)\n raise exception.NovaException(msg)\n\n member = self.client.factory.create('DatasetMemberParameter')\n member.ObjectNameOrId = lun_id\n members = self.client.factory.create('ArrayOfDatasetMemberParameter')\n members.DatasetMemberParameter = [member]\n\n dataset_name = self._dataset_name(project)\n\n server = self.client.service\n lock_id = server.DatasetEditBegin(DatasetNameOrId=dataset_name)\n try:\n server.DatasetRemoveMember(EditLockId=lock_id, Destroy=True,\n DatasetMemberParameters=members)\n server.DatasetEditCommit(EditLockId=lock_id,\n AssumeConfirmation=True)\n except (suds.WebFault, Exception):\n server.DatasetEditRollback(EditLockId=lock_id)\n msg = _('Failed to remove and delete dataset member')\n raise exception.NovaException(msg)\n\n def create_volume(self, volume):\n \"\"\"Driver entry point for creating a new volume\"\"\"\n default_size = '104857600' # 100 MB\n gigabytes = 1073741824L # 2^30\n name = volume['name']\n project = volume['project_id']\n display_name = volume['display_name']\n display_description = volume['display_description']\n if display_name:\n if display_description:\n description = display_name + \"\\n\" + display_description\n else:\n description = display_name\n elif display_description:\n description = display_description\n if int(volume['size']) == 0:\n size = default_size\n else:\n size = str(int(volume['size']) * gigabytes)\n self._provision(name, description, project, size)\n\n def delete_volume(self, volume):\n \"\"\"Driver entry point for destroying existing volumes\"\"\"\n name = volume['name']\n project = volume['project_id']\n self._remove_destroy(name, project)\n\n def _get_lun_id(self, name, project):\n \"\"\"\n Given the name of a volume, find the DFM (OnCommand) ID of the LUN\n corresponding to that volume. Currently we do this by enumerating\n all of the LUNs in the dataset and matching the names against the\n OpenStack volume name.\n\n This could become a performance bottleneck in very large installations\n in which case possible options for mitigating the problem are:\n 1) Store the LUN ID alongside the volume in the nova DB (if possible)\n 2) Cache the list of LUNs in the dataset in driver memory\n 3) Store the volume to LUN ID mappings in a local file\n \"\"\"\n dataset_name = self._dataset_name(project)\n\n server = self.client.service\n res = server.DatasetMemberListInfoIterStart(\n DatasetNameOrId=dataset_name,\n IncludeExportsInfo=True,\n IncludeIndirect=True,\n MemberType='lun_path')\n tag = res.Tag\n suffix = '/' + name\n try:\n while True:\n res = server.DatasetMemberListInfoIterNext(Tag=tag,\n Maximum=100)\n if (not hasattr(res, 'DatasetMembers') or\n not res.DatasetMembers):\n break\n for member in res.DatasetMembers.DatasetMemberInfo:\n if member.MemberName.endswith(suffix):\n return member.MemberId\n finally:\n server.DatasetMemberListInfoIterEnd(Tag=tag)\n\n def _get_lun_details(self, lun_id):\n \"\"\"Given the ID of a LUN, get the details about that LUN\"\"\"\n server = self.client.service\n res = server.LunListInfoIterStart(ObjectNameOrId=lun_id)\n tag = res.Tag\n try:\n res = server.LunListInfoIterNext(Tag=tag, Maximum=1)\n if hasattr(res, 'Luns') and res.Luns.LunInfo:\n return res.Luns.LunInfo[0]\n finally:\n server.LunListInfoIterEnd(Tag=tag)\n\n def _get_host_details(self, host_id):\n \"\"\"\n Given the ID of a host (storage system), get the details about that\n host.\n \"\"\"\n server = self.client.service\n res = server.HostListInfoIterStart(ObjectNameOrId=host_id)\n tag = res.Tag\n try:\n res = server.HostListInfoIterNext(Tag=tag, Maximum=1)\n if hasattr(res, 'Hosts') and res.Hosts.HostInfo:\n return res.Hosts.HostInfo[0]\n finally:\n server.HostListInfoIterEnd(Tag=tag)\n\n def _get_iqn_for_host(self, host_id):\n \"\"\"Get the iSCSI Target Name for a storage system\"\"\"\n request = self.client.factory.create('Request')\n request.Name = 'iscsi-node-get-name'\n response = self.client.service.ApiProxy(Target=host_id,\n Request=request)\n self._check_fail(request, response)\n return response.Results['node-name'][0]\n\n def _api_elem_is_empty(self, elem):\n \"\"\"\n Helper routine to figure out if a list returned from a proxy API\n is empty. This is necessary because the API proxy produces nasty\n looking XML.\n \"\"\"\n if not type(elem) is list:\n return True\n if 0 == len(elem):\n return True\n child = elem[0]\n if isinstance(child, text.Text):\n return True\n if type(child) is str:\n return True\n return False\n\n def _get_target_portal_for_host(self, host_id, host_address):\n \"\"\"\n Get the iSCSI Target Portal details for a particular IP address\n on a storage system.\n \"\"\"\n request = self.client.factory.create('Request')\n request.Name = 'iscsi-portal-list-info'\n response = self.client.service.ApiProxy(Target=host_id,\n Request=request)\n self._check_fail(request, response)\n portal = {}\n portals = response.Results['iscsi-portal-list-entries']\n if self._api_elem_is_empty(portals):\n return portal\n portal_infos = portals[0]['iscsi-portal-list-entry-info']\n for portal_info in portal_infos:\n portal['address'] = portal_info['ip-address'][0]\n portal['port'] = portal_info['ip-port'][0]\n portal['portal'] = portal_info['tpgroup-tag'][0]\n if host_address == portal['address']:\n break\n return portal\n\n def _get_export(self, volume):\n \"\"\"\n Looks up the LUN in DFM based on the volume and project name, then get\n the LUN's ID. We store that value in the database instead of the iSCSI\n details because we will not have the true iSCSI details until masking\n time (when initialize_connection() is called).\n \"\"\"\n name = volume['name']\n project = volume['project_id']\n lun_id = self._get_lun_id(name, project)\n if not lun_id:\n msg = _(\"Failed to find LUN ID for volume %s\")\n raise exception.NovaException(msg % name)\n return {'provider_location': lun_id}\n\n def ensure_export(self, context, volume):\n \"\"\"\n Driver entry point to get the iSCSI details about an existing volume\n \"\"\"\n return self._get_export(volume)\n\n def create_export(self, context, volume):\n \"\"\"\n Driver entry point to get the iSCSI details about a new volume\n \"\"\"\n return self._get_export(volume)\n\n def remove_export(self, context, volume):\n \"\"\"\n Since exporting is idempotent in this driver, we have nothing\n to do for unexporting.\n \"\"\"\n pass\n\n def _find_igroup_for_initiator(self, host_id, initiator_name):\n \"\"\"\n Look for an existing igroup (initiator group) on the storage system\n containing a given iSCSI initiator and return the name of the igroup.\n \"\"\"\n request = self.client.factory.create('Request')\n request.Name = 'igroup-list-info'\n response = self.client.service.ApiProxy(Target=host_id,\n Request=request)\n self._check_fail(request, response)\n igroups = response.Results['initiator-groups']\n if self._api_elem_is_empty(igroups):\n return None\n igroup_infos = igroups[0]['initiator-group-info']\n for igroup_info in igroup_infos:\n if ('iscsi' != igroup_info['initiator-group-type'][0] or\n 'linux' != igroup_info['initiator-group-os-type'][0]):\n continue\n igroup_name = igroup_info['initiator-group-name'][0]\n if not igroup_name.startswith('openstack-'):\n continue\n initiators = igroup_info['initiators'][0]['initiator-info']\n for initiator in initiators:\n if initiator_name == initiator['initiator-name'][0]:\n return igroup_name\n return None\n\n def _create_igroup(self, host_id, initiator_name):\n \"\"\"\n Create a new igroup (initiator group) on the storage system to hold\n the given iSCSI initiator. The group will only have 1 member and will\n be named \"openstack-${initiator_name}\".\n \"\"\"\n igroup_name = 'openstack-' + initiator_name\n request = self.client.factory.create('Request')\n request.Name = 'igroup-create'\n igroup_create_xml = (\n '%s'\n 'iscsi'\n 'linuxlinux')\n request.Args = text.Raw(igroup_create_xml % igroup_name)\n response = self.client.service.ApiProxy(Target=host_id,\n Request=request)\n self._check_fail(request, response)\n request = self.client.factory.create('Request')\n request.Name = 'igroup-add'\n igroup_add_xml = (\n '%s'\n '%s')\n request.Args = text.Raw(igroup_add_xml % (igroup_name, initiator_name))\n response = self.client.service.ApiProxy(Target=host_id,\n Request=request)\n self._check_fail(request, response)\n return igroup_name\n\n def _get_lun_mappping(self, host_id, lunpath, igroup_name):\n \"\"\"\n Check if a given LUN is already mapped to the given igroup (initiator\n group). If the LUN is mapped, also return the LUN number for the\n mapping.\n \"\"\"\n request = self.client.factory.create('Request')\n request.Name = 'lun-map-list-info'\n request.Args = text.Raw('%s' % (lunpath))", "answers": [" response = self.client.service.ApiProxy(Target=host_id,"], "length": 1741, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "8885ba1a-c897-4af0-9a71-8a59ddfdc535", "reasoning": "The method _get_lun_mappping builds a Request object to query lun-map-list-info. After setting request.Args, the next logical step is to invoke the API via ApiProxy with the target host_id and the request, storing the response. This matches the pattern used elsewhere in the driver for API calls.", "reasoning_model_answer": "response = self.client.service.ApiProxy(Target=host_id,\n Request=request)", "assistant_with_reasoning": "\nThe method _get_lun_mappping builds a Request object to query lun-map-list-info. After setting request.Args, the next logical step is to invoke the API via ApiProxy with the target host_id and the request, storing the response. This matches the pattern used elsewhere in the driver for API calls.\n\nresponse = self.client.service.ApiProxy(Target=host_id,\n Request=request)", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.638, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 20773, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "response = self.client.service.ApiProxy(Target=host_id,\n Request=request)", "score": 0.93, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "# texttable - module for creating simple ASCII tables\n# Copyright (C) 2003-2015 Gerome Fournier \n#\n# This library is free software; you can redistribute it and/or\n# modify it under the terms of the GNU Lesser General Public\n# License as published by the Free Software Foundation; either\n# version 2.1 of the License, or (at your option) any later version.\n#\n# This library is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n# Lesser General Public License for more details.\n#\n# You should have received a copy of the GNU Lesser General Public\n# License along with this library; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA\n\n\"\"\"module for creating simple ASCII tables\n\n\nExample:\n\n table = Texttable()\n table.set_cols_align([\"l\", \"r\", \"c\"])\n table.set_cols_valign([\"t\", \"m\", \"b\"])\n table.add_rows([[\"Name\", \"Age\", \"Nickname\"],\n [\"Mr\\\\nXavier\\\\nHuon\", 32, \"Xav'\"],\n [\"Mr\\\\nBaptiste\\\\nClement\", 1, \"Baby\"],\n [\"Mme\\\\nLouise\\\\nBourgeau\", 28, \"Lou\\\\n\\\\nLoue\"]])\n print table.draw() + \"\\\\n\"\n\n table = Texttable()\n table.set_deco(Texttable.HEADER)\n table.set_cols_dtype(['t', # text\n 'f', # float (decimal)\n 'e', # float (exponent)\n 'i', # integer\n 'a']) # automatic\n table.set_cols_align([\"l\", \"r\", \"r\", \"r\", \"l\"])\n table.add_rows([[\"text\", \"float\", \"exp\", \"int\", \"auto\"],\n [\"abcd\", \"67\", 654, 89, 128.001],\n [\"efghijk\", 67.5434, .654, 89.6, 12800000000000000000000.00023],\n [\"lmn\", 5e-78, 5e-78, 89.4, .000000000000128],\n [\"opqrstu\", .023, 5e+78, 92., 12800000000000000000000]])\n print table.draw()\n\nResult:\n\n +----------+-----+----------+\n | Name | Age | Nickname |\n +==========+=====+==========+\n | Mr | | |\n | Xavier | 32 | |\n | Huon | | Xav' |\n +----------+-----+----------+\n | Mr | | |\n | Baptiste | 1 | |\n | Clement | | Baby |\n +----------+-----+----------+\n | Mme | | Lou |\n | Louise | 28 | |\n | Bourgeau | | Loue |\n +----------+-----+----------+\n\n text float exp int auto\n ===========================================\n abcd 67.000 6.540e+02 89 128.001\n efgh 67.543 6.540e-01 90 1.280e+22\n ijkl 0.000 5.000e-78 89 0.000\n mnop 0.023 5.000e+78 92 1.280e+22\n\"\"\"\n\nfrom __future__ import division\n\n__all__ = [\"Texttable\", \"ArraySizeError\"]\n\n__author__ = 'Gerome Fournier '\n__license__ = 'LGPL'\n__version__ = '0.8.8'\n__credits__ = \"\"\"\\\nJeff Kowalczyk:\n - textwrap improved import\n - comment concerning header output\n\nAnonymous:\n - add_rows method, for adding rows in one go\n\nSergey Simonenko:\n - redefined len() function to deal with non-ASCII characters\n\nRoger Lew:\n - columns datatype specifications\n\nBrian Peterson:\n - better handling of unicode errors\n\nFrank Sachsenheim:\n - add Python 2/3-compatibility\n\nMaximilian Hils:\n - fix minor bug for Python 3 compatibility\n\nfrinkelpi:\n - preserve empty lines\n\"\"\"\n\nimport sys\nimport string\nimport unicodedata\n\ntry:\n if sys.version >= '2.3':\n import textwrap\n elif sys.version >= '2.2':\n from optparse import textwrap\n else:\n from optik import textwrap\nexcept ImportError:\n sys.stderr.write(\"Can't import textwrap module!\\n\")\n raise\n\nif sys.version >= '2.7':\n from functools import reduce\n\nif sys.version >= '3.0':\n unicode_type = str\n bytes_type = bytes\nelse:\n unicode_type = unicode\n bytes_type = str\n\n\ndef obj2unicode(obj):\n \"\"\"Return a unicode representation of a python object\n \"\"\"\n if isinstance(obj, unicode_type):\n return obj\n elif isinstance(obj, bytes_type):\n try:\n return unicode_type(obj, 'utf-8')\n except UnicodeDecodeError as strerror:\n sys.stderr.write(\"UnicodeDecodeError exception for string '%s': %s\\n\" % (obj, strerror))\n return unicode_type(obj, 'utf-8', 'replace')\n else:\n return unicode_type(obj)\n\n\ndef len(iterable):\n \"\"\"Redefining len here so it will be able to work with non-ASCII characters\n \"\"\"\n if isinstance(iterable, bytes_type) or isinstance(iterable, unicode_type):\n unicode_data = obj2unicode(iterable)\n if hasattr(unicodedata, 'east_asian_width'):\n w = unicodedata.east_asian_width\n return sum([w(c) in 'WF' and 2 or 1 for c in unicode_data])\n else:\n return unicode_data.__len__()\n else:\n return iterable.__len__()\n\n\nclass ArraySizeError(Exception):\n \"\"\"Exception raised when specified rows don't fit the required size\n \"\"\"\n\n def __init__(self, msg):\n self.msg = msg\n Exception.__init__(self, msg, '')\n\n def __str__(self):\n return self.msg\n\n\nclass Texttable:\n\n BORDER = 1\n HEADER = 1 << 1\n HLINES = 1 << 2\n VLINES = 1 << 3\n\n def __init__(self, max_width=80):\n \"\"\"Constructor\n\n - max_width is an integer, specifying the maximum width of the table\n - if set to 0, size is unlimited, therefore cells won't be wrapped\n \"\"\"\n\n if max_width <= 0:\n max_width = False\n self._max_width = max_width\n self._precision = 3\n\n self._deco = Texttable.VLINES | Texttable.HLINES | Texttable.BORDER | \\\n Texttable.HEADER\n self.set_chars(['-', '|', '+', '='])\n self.reset()\n\n def reset(self):\n \"\"\"Reset the instance\n\n - reset rows and header\n \"\"\"\n\n self._hline_string = None\n self._row_size = None\n self._header = []\n self._rows = []\n\n def set_chars(self, array):\n \"\"\"Set the characters used to draw lines between rows and columns\n\n - the array should contain 4 fields:\n\n [horizontal, vertical, corner, header]\n\n - default is set to:\n\n ['-', '|', '+', '=']\n \"\"\"\n\n if len(array) != 4:\n raise ArraySizeError(\"array should contain 4 characters\")\n array = [ x[:1] for x in [ str(s) for s in array ] ]\n (self._char_horiz, self._char_vert,\n self._char_corner, self._char_header) = array\n\n def set_deco(self, deco):\n \"\"\"Set the table decoration\n\n - 'deco' can be a combinaison of:\n\n Texttable.BORDER: Border around the table\n Texttable.HEADER: Horizontal line below the header\n Texttable.HLINES: Horizontal lines between rows\n Texttable.VLINES: Vertical lines between columns\n\n All of them are enabled by default\n\n - example:\n\n Texttable.BORDER | Texttable.HEADER\n \"\"\"\n\n self._deco = deco\n\n def set_cols_align(self, array):\n \"\"\"Set the desired columns alignment\n\n - the elements of the array should be either \"l\", \"c\" or \"r\":\n\n * \"l\": column flushed left\n * \"c\": column centered\n * \"r\": column flushed right\n \"\"\"\n\n self._check_row_size(array)\n self._align = array\n\n def set_cols_valign(self, array):\n \"\"\"Set the desired columns vertical alignment\n\n - the elements of the array should be either \"t\", \"m\" or \"b\":\n\n * \"t\": column aligned on the top of the cell\n * \"m\": column aligned on the middle of the cell\n * \"b\": column aligned on the bottom of the cell\n \"\"\"\n\n self._check_row_size(array)\n self._valign = array\n\n def set_cols_dtype(self, array):\n \"\"\"Set the desired columns datatype for the cols.\n\n - the elements of the array should be either \"a\", \"t\", \"f\", \"e\" or \"i\":\n\n * \"a\": automatic (try to use the most appropriate datatype)\n * \"t\": treat as text\n * \"f\": treat as float in decimal format\n * \"e\": treat as float in exponential format\n * \"i\": treat as int\n\n - by default, automatic datatyping is used for each column\n \"\"\"\n\n self._check_row_size(array)\n self._dtype = array\n\n def set_cols_width(self, array):\n \"\"\"Set the desired columns width\n\n - the elements of the array should be integers, specifying the\n width of each column. For example:\n\n [10, 20, 5]\n \"\"\"\n\n self._check_row_size(array)\n try:\n array = list(map(int, array))\n if reduce(min, array) <= 0:\n raise ValueError\n except ValueError:\n sys.stderr.write(\"Wrong argument in column width specification\\n\")\n raise\n self._width = array\n\n def set_precision(self, width):\n \"\"\"Set the desired precision for float/exponential formats\n\n - width must be an integer >= 0\n\n - default value is set to 3\n \"\"\"\n\n if not type(width) is int or width < 0:\n raise ValueError('width must be an integer greater then 0')\n self._precision = width\n\n def header(self, array):\n \"\"\"Specify the header of the table\n \"\"\"\n\n self._check_row_size(array)\n self._header = list(map(obj2unicode, array))\n\n def add_row(self, array):\n \"\"\"Add a row in the rows stack\n\n - cells can contain newlines and tabs\n \"\"\"\n\n self._check_row_size(array)\n\n if not hasattr(self, \"_dtype\"):\n self._dtype = [\"a\"] * self._row_size\n\n cells = []\n for i, x in enumerate(array):\n cells.append(self._str(i, x))\n self._rows.append(cells)\n\n def add_rows(self, rows, header=True):\n \"\"\"Add several rows in the rows stack\n\n - The 'rows' argument can be either an iterator returning arrays,\n or a by-dimensional array\n - 'header' specifies if the first row should be used as the header\n of the table\n \"\"\"\n\n # nb: don't use 'iter' on by-dimensional arrays, to get a\n # usable code for python 2.1\n if header:\n if hasattr(rows, '__iter__') and hasattr(rows, 'next'):\n self.header(rows.next())\n else:\n self.header(rows[0])\n rows = rows[1:]\n for row in rows:\n self.add_row(row)\n\n def draw(self):\n \"\"\"Draw the table\n\n - the table is returned as a whole string\n \"\"\"\n\n if not self._header and not self._rows:\n return\n self._compute_cols_width()\n self._check_align()\n out = \"\"\n if self._has_border():\n out += self._hline()\n if self._header:\n out += self._draw_line(self._header, isheader=True)\n if self._has_header():\n out += self._hline_header()\n length = 0\n for row in self._rows:\n length += 1\n out += self._draw_line(row)\n if self._has_hlines() and length < len(self._rows):\n out += self._hline()\n if self._has_border():\n out += self._hline()\n return out[:-1]\n\n def _str(self, i, x):\n \"\"\"Handles string formatting of cell data\n\n i - index of the cell datatype in self._dtype\n x - cell data to format\n \"\"\"\n try:\n f = float(x)\n except:\n return obj2unicode(x)\n\n n = self._precision\n dtype = self._dtype[i]\n\n if dtype == 'i':\n return str(int(round(f)))\n elif dtype == 'f':\n return '%.*f' % (n, f)", "answers": [" elif dtype == 'e':"], "length": 1346, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "02ab41df-715a-468f-93a8-a4a7d8147478", "reasoning": "The _str method formats a cell based on its datatype. It already handles conversion to float, then checks dtype for 'i' and 'f'. The next logical branch is for exponential format 'e', returning the float in exponential notation with the specified precision.", "reasoning_model_answer": "elif dtype == 'e':\n return '%.*e' % (n, f)", "assistant_with_reasoning": "\nThe _str method formats a cell based on its datatype. It already handles conversion to float, then checks dtype for 'i' and 'f'. The next logical branch is for exponential format 'e', returning the float in exponential notation with the specified precision.\n\nelif dtype == 'e':\n return '%.*e' % (n, f)", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.098, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 11963, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "elif dtype == 'e':\n return '%.*e' % (n, f)", "score": 0.82, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "# -*- coding: utf-8 -*-\n##===-----------------------------------------------------------------------------*- Python -*-===##\n# _\n# | |\n# __| | __ ___ ___ ___\n# / _` |/ _` \\ \\ /\\ / / '_ |\n# | (_| | (_| |\\ V V /| | | |\n# \\__,_|\\__,_| \\_/\\_/ |_| |_| - Compiler Toolchain\n##\n##\n# This file is distributed under the MIT License (MIT).\n# See LICENSE.txt for details.\n##\n##===------------------------------------------------------------------------------------------===##\n\n\n\"\"\"\nConvenience functions to serialize/deserialize and print SIR and IIR objects.\n\"\"\"\n\n\nimport textwrap\n\nfrom enum import Enum\nfrom collections.abc import Iterable\nfrom typing import List, TypeVar, NewType\n\nfrom google.protobuf import json_format\n\nfrom .error import ParseError, SIRError\nfrom .SIR.SIR_pb2 import *\nfrom .AST.statements_pb2 import *\nfrom .AST.enums_pb2 import *\nfrom .. import utils\n\n__all__ = [\n \"make_sir\",\n \"make_stencil\",\n \"make_type\",\n \"make_field_dimensions_cartesian\",\n \"make_field_dimensions_unstructured\",\n \"make_field\",\n \"make_ast\",\n \"make_interval\",\n \"make_vertical_region\",\n \"make_stencil_call\",\n \"make_stmt\",\n \"make_block_stmt\",\n \"make_loop_stmt\",\n \"make_expr_stmt\",\n \"make_return_stmt\",\n \"make_var_decl_stmt\",\n \"make_vertical_region_decl_stmt\",\n \"make_stencil_call_decl_stmt\",\n \"make_boundary_condition_decl_stmt\",\n \"make_if_stmt\",\n \"make_expr\",\n \"make_unary_operator\",\n \"make_binary_operator\",\n \"make_assignment_expr\",\n \"make_assignment_stmt\",\n \"make_ternary_operator\",\n \"make_fun_call_expr\",\n \"make_stencil_fun_call_expr\",\n \"make_stencil_fun_arg_expr\",\n \"make_stencil_function_arg\",\n \"make_stencil_function\",\n \"make_var_access_expr\",\n \"make_field_access_expr\",\n \"make_literal_access_expr\",\n \"make_weights\",\n \"make_reduction_over_neighbor_expr\",\n \"to_bytes\",\n \"from_bytes\",\n \"to_json\",\n \"from_json\", \n]\n\nExprType = TypeVar(\n \"ExprType\",\n Expr,\n UnaryOperator,\n BinaryOperator,\n AssignmentExpr,\n TernaryOperator,\n FunCallExpr,\n StencilFunCallExpr,\n StencilFunArgExpr,\n VarAccessExpr,\n FieldAccessExpr,\n LiteralAccessExpr,\n ReductionOverNeighborExpr,\n)\n\nStmtType = TypeVar(\n \"StmtType\",\n Stmt,\n BlockStmt,\n ExprStmt,\n ReturnStmt,\n VarDeclStmt,\n VerticalRegionDeclStmt,\n StencilCallDeclStmt,\n BoundaryConditionDeclStmt,\n IfStmt,\n LoopStmt,\n)\n\n# Can't pass SIR.enums_pb2.LocationType as argument because it doesn't contain the value\nLocationTypeValue = NewType(\"LocationTypeValue\", int)\n\n\ndef make_sir(\n filename: str,\n grid_type: GridType,\n stencils: List[Stencil],\n functions: List[StencilFunction] = [],\n global_variables: GlobalVariableMap = None,\n) -> SIR:\n \"\"\" Create a SIR\n\n :param filename: Source filename\n :param grid_type: Grid type definition\n :param stencils: list of stencils that compose the SIR\n :param functions: list of functions used in the SIR\n :param global_variables: global variable map used in the SIR\n \"\"\"\n\n sir = SIR()\n sir.filename = filename\n sir.gridType = grid_type\n sir.stencils.extend(stencils)\n sir.stencil_functions.extend(functions)\n if global_variables:\n sir.global_variables.CopyFrom(global_variables)\n\n return sir\n\n\ndef make_stencil(name: str, ast: AST, fields: List[Field]) -> Stencil:\n \"\"\" Create a Stencil\n\n :param name: Name of the stencil\n :param ast: AST with stmts of the stencil\n :param fields: list of input-output fields\n \"\"\"\n\n stencil = Stencil()\n stencil.name = name\n stencil.ast.CopyFrom(ast)\n stencil.fields.extend(fields)\n\n return stencil\n\n\ndef make_type(builtin_type_or_name, is_const: bool = False, is_volatile: bool = False):\n \"\"\" Wrap a concrete expression (e.g VarAccessExpr) into an Expr object\n\n :param builtin_type_or_name: Either an Enum of BuiltinType or the name of the custom type in\n case it is not a builtin type).\n :type builtin_type_or_name: Union[BuiltinType.TypeID, str, int]\n :param is_const: Is the type const qualified?\n :param is_volatile: Is the type volatile qualified?\n \"\"\"\n t = Type()\n t.is_const = is_const\n t.is_volatile = is_volatile\n if isinstance(builtin_type_or_name, str):\n t.name = builtin_type_or_name\n elif isinstance(builtin_type_or_name, (type(BuiltinType.TypeID), int)):\n builtin_type = BuiltinType()\n builtin_type.type_id = builtin_type_or_name\n t.builtin_type.CopyFrom(builtin_type)\n else:\n raise TypeError(\n \"expected 'builtin_type_or_name' to be either of type 'dawn.sir.BuiltinType.TypeID'\"\n + \"or 'str' (got {})\".format(type(builtin_type_or_name))\n )\n return t\n\n\ndef make_field_dimensions_cartesian(mask: List[int] = None) -> FieldDimensions:\n \"\"\" Create FieldDimensions of cartesian type\n\n :param mask: mask to identify which cartesian dimensions are legal (default is [1, 1, 1])\n \"\"\"\n\n if mask is None:\n mask = [1, 1, 1]\n assert len(mask) == 3\n\n horizontal_dim = CartesianDimension()\n horizontal_dim.mask_cart_i = mask[0]\n horizontal_dim.mask_cart_j = mask[1]\n\n dims = FieldDimensions()\n dims.cartesian_horizontal_dimension.CopyFrom(horizontal_dim)\n dims.mask_k = mask[2]\n return dims\n\n\ndef make_field_dimensions_unstructured(\n locations: List[LocationTypeValue], mask_k: int, include_center: bool = False\n) -> FieldDimensions:\n \"\"\" Create FieldDimensions of unstructured type\n\n :locations: a list of location types of the field. first entry is the dense part, additional entries are the (optional) sparse part\n :mask_k: mask to identify if the vertical dimension is legal\n :sparse_part: optional sparse part encoded by a neighbor chain\n \"\"\"\n\n assert len(locations) >= 1\n dims = FieldDimensions()\n iter_space = UnstructuredIterationSpace()\n horizontal_dim = UnstructuredDimension() \n iter_space.chain.extend(locations)\n iter_space.include_center = include_center\n horizontal_dim.iter_space.CopyFrom(iter_space)\n dims.unstructured_horizontal_dimension.CopyFrom(horizontal_dim) \n dims.mask_k = mask_k\n return dims\n\n\ndef make_field_dimensions_vertical() -> FieldDimensions:\n \"\"\" Create Field dimension in the vertical only\n \"\"\"\n dims = FieldDimensions()\n dims.mask_k = True\n return dims\n\n\ndef make_field(name: str, dimensions: FieldDimensions, is_temporary: bool = False) -> Field:\n \"\"\" Create a Field\n\n :param name: Name of the field\n :param dimensions: dimensions of the field (use make_field_dimensions_*)\n :param is_temporary: Is it a temporary field?\n \"\"\"\n\n field = Field()\n field.name = name\n field.is_temporary = is_temporary\n field.field_dimensions.CopyFrom(dimensions)\n return field\n\n\ndef make_vertical_field(name: str, is_temporary: bool = False) -> Field:\n \"\"\" Create a vertical Field, i.e. a field with no horizontal dimensions\n\n :param name: Name of the field\n :param is_temporary: Is it a temporary field?\n \"\"\"\n return make_field(name, make_field_dimensions_vertical(), is_temporary)\n\n\ndef make_ast(root: List[StmtType]) -> AST:\n \"\"\" Create an AST\n\n :param root: Root node of the AST (needs to be of type BlockStmt)\n \"\"\"\n ast = AST()\n\n block_stmt = make_block_stmt(root)\n\n ast.root.CopyFrom(make_stmt(block_stmt))\n return ast\n\n\ndef make_interval(\n lower_level, upper_level, lower_offset: int = 0, upper_offset: int = 0\n) -> Interval:\n \"\"\" Create an Interval\n\n Representation of a vertical interval, given by a lower and upper bound where a bound\n is represented by a level and an offset (`bound = level + offset`)\n\n The Interval has to satisfy the following invariants:\n - `lower_level >= Interval.Start`\n - `upper_level <= Interval.End`\n - `(lower_level + lower_offset) <= (upper_level + upper_offset)`\n\n :param lower_level: Lower level integer between `[Interval.Start, Interval.End]`\n :param upper_level: Lower level integer between `[Interval.Start, Interval.End]`\n :param lower_offset: Lower offset\n :param upper_offset: Upper offset\n \"\"\"\n interval = Interval()\n\n if lower_level in (Interval.Start, Interval.End):\n interval.special_lower_level = lower_level\n else:\n interval.lower_level = lower_level\n\n if upper_level in (Interval.Start, Interval.End):\n interval.special_upper_level = upper_level\n else:\n interval.upper_level = upper_level\n\n interval.lower_offset = lower_offset\n interval.upper_offset = upper_offset\n return interval\n\n\ndef make_magic_num_interval(\n lower_level, upper_level, lower_offset: int = 0, upper_offset: int = 0\n) -> Interval:\n \"\"\" Create an Interval\n\n Representation of a vertical interval, given by a lower and upper bound where a bound\n is represented by a level and an offset (`bound = level + offset`)\n\n \"\"\"\n interval = Interval()\n\n interval.lower_level = lower_level\n interval.upper_level = upper_level\n\n interval.lower_offset = lower_offset\n interval.upper_offset = upper_offset\n return interval\n\n\ndef make_vertical_region(\n ast: AST,\n interval: Interval,\n loop_order: VerticalRegion.LoopOrder,\n i_range: Interval = None,\n j_range: Interval = None,\n) -> VerticalRegion:\n \"\"\" Create a VerticalRegion\n\n :param ast: Syntax tree of the body of the vertical region\n :param interval: Vertical interval\n :param loop_order: Vertical loop order of execution\n \"\"\"\n vr = VerticalRegion()\n vr.ast.CopyFrom(ast)\n vr.interval.CopyFrom(interval)\n vr.loop_order = loop_order\n if i_range is not None:\n vr.i_range.CopyFrom(i_range)\n if j_range is not None:\n vr.j_range.CopyFrom(j_range)\n return vr\n\n\ndef make_stencil_call(callee: str, arguments: List[str]) -> StencilCall:\n \"\"\" Create a StencilCall\n\n :param callee: Name of the called stencil (i.e callee)\n :param arguments: Fields passed as arguments during the stencil call\n \"\"\"\n call = StencilCall()\n call.callee = callee\n call.arguments.extend(arguments)\n return call\n\n\ndef make_stmt(stmt: StmtType):\n \"\"\" Wrap a concrete statement (e.g ExprStmt) into an Stmt object\n\n :param stmt: Statement to wrap\n :return: Statement wrapped into Stmt\n \"\"\"\n if isinstance(stmt, Stmt):\n return stmt\n wrapped_stmt = Stmt()\n\n if isinstance(stmt, BlockStmt):\n wrapped_stmt.block_stmt.CopyFrom(stmt)\n elif isinstance(stmt, ExprStmt):\n wrapped_stmt.expr_stmt.CopyFrom(stmt)\n elif isinstance(stmt, ReturnStmt):\n wrapped_stmt.return_stmt.CopyFrom(stmt)\n elif isinstance(stmt, VarDeclStmt):\n wrapped_stmt.var_decl_stmt.CopyFrom(stmt)\n elif isinstance(stmt, VerticalRegionDeclStmt):\n wrapped_stmt.vertical_region_decl_stmt.CopyFrom(stmt)\n elif isinstance(stmt, StencilCallDeclStmt):\n wrapped_stmt.stencil_call_decl_stmt.CopyFrom(stmt)\n elif isinstance(stmt, BoundaryConditionDeclStmt):\n wrapped_stmt.boundary_condition_decl_stmt.CopyFrom(stmt)\n elif isinstance(stmt, IfStmt):\n wrapped_stmt.if_stmt.CopyFrom(stmt)\n elif isinstance(stmt, LoopStmt):\n wrapped_stmt.loop_stmt.CopyFrom(stmt)\n else:\n raise SIRError(\"cannot create Stmt from type {}\".format(type(stmt)))\n return wrapped_stmt\n\n\ndef make_block_stmt(statements: List[StmtType]) -> BlockStmt:\n \"\"\" Create an UnaryOperator\n\n :param statements: List of statements that compose the block\n \"\"\"\n stmt = BlockStmt()\n if isinstance(statements, Iterable):\n stmt.statements.extend([make_stmt(s)\n for s in statements if not isinstance(s, Field)])\n else:\n stmt.statements.extend([make_stmt(statements)])\n return stmt\n\n\ndef make_loop_stmt(block: List[StmtType], chain: List[LocationTypeValue], include_center: bool = False) -> LoopStmt:\n \"\"\" Create an For Loop\n\n :param block: List of statements that compose the body of the loop\n \"\"\"\n stmt = LoopStmt()\n stmt.statements.CopyFrom(make_stmt(make_block_stmt(block)))\n loop_descriptor_chain = LoopDescriptorChain()\n iter_space = UnstructuredIterationSpace()\n iter_space.chain.extend(chain)\n iter_space.include_center = include_center\n loop_descriptor_chain.iter_space.CopyFrom(iter_space)\n stmt.loop_descriptor.loop_descriptor_chain.CopyFrom(loop_descriptor_chain)\n\n return stmt\n\n\ndef make_expr_stmt(expr: ExprType) -> ExprStmt:\n \"\"\" Create an ExprStmt\n\n :param expr: Expression.\n \"\"\"\n stmt = ExprStmt()\n stmt.expr.CopyFrom(make_expr(expr))\n return stmt\n\n\ndef make_return_stmt(expr: ExprType) -> ReturnStmt:\n \"\"\" Create an ReturnStmt\n\n :param expr: Expression to return.\n \"\"\"\n stmt = ReturnStmt()\n stmt.expr.CopyFrom(make_expr(expr))\n return stmt\n\n\ndef make_var_decl_stmt(\n type: Type, name: str, dimension: int = 0, op: str = \"=\", init_list=None\n) -> VarDeclStmt:\n \"\"\" Create an ReturnStmt\n\n :param type: Type of the variable.\n :param name: Name of the variable.\n :param dimension: Dimension of the array or 0 for variables.\n :param op: Operation used for initialization.\n :param init_list: List of expression used for array initialization or just 1 element for\n variable initialization.\n \"\"\"\n stmt = VarDeclStmt()\n stmt.type.CopyFrom(type)\n stmt.name = name\n stmt.dimension = dimension\n stmt.op = op\n if init_list:\n if isinstance(init_list, Iterable):\n stmt.init_list.extend([make_expr(expr) for expr in init_list])\n else:\n stmt.init_list.extend([make_expr(init_list)])\n\n return stmt\n\n\ndef make_stencil_call_decl_stmt(stencil_call: StencilCall) -> StencilCallDeclStmt:\n \"\"\" Create a StencilCallDeclStmt\n\n :param stencil_call: Stencil call.\n \"\"\"\n stmt = StencilCallDeclStmt()\n stmt.stencil_call.CopyFrom(stencil_call)\n return stmt\n\n\ndef make_vertical_region_decl_stmt(vertical_region: VerticalRegion) -> VerticalRegionDeclStmt:\n \"\"\" Create a VerticalRegionDeclStmt\n\n :param vertical_region: Vertical region.\n \"\"\"\n stmt = VerticalRegionDeclStmt()\n stmt.vertical_region.CopyFrom(vertical_region)\n return stmt\n\n\ndef make_vertical_region_decl_stmt(\n ast: AST,\n interval: Interval,\n loop_order: VerticalRegion.LoopOrder,\n IRange: Interval = None,\n JRange: Interval = None,\n) -> VerticalRegionDeclStmt:\n \"\"\" Create a VerticalRegionDeclStmt\n\n :param vertical_region: Vertical region.\n \"\"\"\n stmt = VerticalRegionDeclStmt()\n stmt.vertical_region.CopyFrom(make_vertical_region(\n ast, interval, loop_order, IRange, JRange))\n return stmt\n\n\ndef make_boundary_condition_decl_stmt(\n functor: str, fields: List[str]\n) -> BoundaryConditionDeclStmt:\n \"\"\" Create a BoundaryConditionDeclStmt\n\n :param functor: Identifier of the boundary condition functor.\n :param fields: List of field arguments to apply the functor to.\n \"\"\"\n stmt = BoundaryConditionDeclStmt()\n stmt.functor = functor\n stmt.fields.extend(fields)\n return stmt\n\n\ndef make_if_stmt(cond_part: StmtType, then_part: StmtType, else_part: StmtType = None) -> IfStmt:\n \"\"\" Create an ReturnStmt\n\n :param cond_part: Condition part.\n :param then_part: Then part.\n :param else_part: Else part.\n \"\"\"\n stmt = IfStmt()\n stmt.cond_part.CopyFrom(make_stmt(cond_part))\n stmt.then_part.CopyFrom(make_stmt(then_part))\n if else_part:\n stmt.else_part.CopyFrom(make_stmt(else_part))\n return stmt\n\n\ndef make_expr(expr: ExprType):\n \"\"\" Wrap a concrete expression (e.g VarAccessExpr) into an Expr object\n\n :param expr: Expression to wrap\n :return: Expression wrapped into Expr\n \"\"\"\n if isinstance(expr, Expr):\n return expr\n wrapped_expr = Expr()\n\n if isinstance(expr, UnaryOperator):\n wrapped_expr.unary_operator.CopyFrom(expr)\n elif isinstance(expr, BinaryOperator):\n wrapped_expr.binary_operator.CopyFrom(expr)\n elif isinstance(expr, AssignmentExpr):\n wrapped_expr.assignment_expr.CopyFrom(expr)\n elif isinstance(expr, TernaryOperator):\n wrapped_expr.ternary_operator.CopyFrom(expr)\n elif isinstance(expr, FunCallExpr):", "answers": [" wrapped_expr.fun_call_expr.CopyFrom(expr)"], "length": 1548, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "69df57b4-aaf0-4b2a-adc0-63e2fca4e6a0", "reasoning": "The function make_expr wraps concrete expression objects into a generic Expr protobuf. It checks the type of the given expression and copies the appropriate sub‑message into the Expr wrapper. The last conditional shown tests for FunCallExpr, so the next line should copy the FunCallExpr into the wrapper using the corresponding field name, which follows the same pattern as the earlier cases (e.g., wrapped_expr.unary_operator.CopyFrom(expr)). Hence the next line is the copy operation for FunCallExpr.", "reasoning_model_answer": "wrapped_expr.fun_call_expr.CopyFrom(expr)", "assistant_with_reasoning": "\nThe function make_expr wraps concrete expression objects into a generic Expr protobuf. It checks the type of the given expression and copies the appropriate sub‑message into the Expr wrapper. The last conditional shown tests for FunCallExpr, so the next line should copy the FunCallExpr into the wrapper using the corresponding field name, which follows the same pattern as the earlier cases (e.g., wrapped_expr.unary_operator.CopyFrom(expr)). Hence the next line is the copy operation for FunCallExpr.\n\nwrapped_expr.fun_call_expr.CopyFrom(expr)", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 2.9, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 16579, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "wrapped_expr.fun_call_expr.CopyFrom(expr)", "score": 0.91, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "#!/usr/bin/env python\n\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom selenium import webdriver\n\nfrom .connectiontype import ConnectionType\nfrom .mobilecommand import MobileCommand as Command\nfrom .errorhandler import MobileErrorHandler\nfrom .switch_to import MobileSwitchTo\nfrom .webelement import WebElement as MobileWebElement\n\nfrom appium.webdriver.common.mobileby import MobileBy\nfrom appium.webdriver.common.touch_action import TouchAction\nfrom appium.webdriver.common.multi_action import MultiAction\n\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.remote.webelement import WebElement\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.common.exceptions import TimeoutException\n\n\nclass WebDriver(webdriver.Remote):\n def __init__(self, command_executor='http://127.0.0.1:4444/wd/hub',\n desired_capabilities=None, browser_profile=None, proxy=None, keep_alive=False):\n\n super(WebDriver, self).__init__(command_executor, desired_capabilities, browser_profile, proxy, keep_alive)\n\n if self.command_executor is not None:\n self._addCommands()\n\n self.error_handler = MobileErrorHandler()\n self._switch_to = MobileSwitchTo(self)\n\n # add new method to the `find_by_*` pantheon\n By.IOS_UIAUTOMATION = MobileBy.IOS_UIAUTOMATION\n By.ANDROID_UIAUTOMATOR = MobileBy.ANDROID_UIAUTOMATOR\n By.ACCESSIBILITY_ID = MobileBy.ACCESSIBILITY_ID\n\n @property\n def contexts(self):\n \"\"\"\n Returns the contexts within the current session.\n\n :Usage:\n driver.contexts\n \"\"\"\n return self.execute(Command.CONTEXTS)['value']\n\n @property\n def current_context(self):\n \"\"\"\n Returns the current context of the current session.\n\n :Usage:\n driver.current_context\n \"\"\"\n return self.execute(Command.GET_CURRENT_CONTEXT)['value']\n\n @property\n def context(self):\n \"\"\"\n Returns the current context of the current session.\n\n :Usage:\n driver.context\n \"\"\"\n return self.current_context\n\n def find_element_by_ios_uiautomation(self, uia_string):\n \"\"\"Finds an element by uiautomation in iOS.\n\n :Args:\n - uia_string - The element name in the iOS UIAutomation library\n\n :Usage:\n driver.find_element_by_ios_uiautomation('.elements()[1].cells()[2]')\n \"\"\"\n return self.find_element(by=By.IOS_UIAUTOMATION, value=uia_string)\n\n def find_elements_by_ios_uiautomation(self, uia_string):\n \"\"\"Finds elements by uiautomation in iOS.\n\n :Args:\n - uia_string - The element name in the iOS UIAutomation library\n\n :Usage:\n driver.find_elements_by_ios_uiautomation('.elements()[1].cells()[2]')\n \"\"\"\n return self.find_elements(by=By.IOS_UIAUTOMATION, value=uia_string)\n\n def find_element_by_android_uiautomator(self, uia_string):\n \"\"\"Finds element by uiautomator in Android.\n\n :Args:\n - uia_string - The element name in the Android UIAutomator library\n\n :Usage:\n driver.find_element_by_android_uiautomator('.elements()[1].cells()[2]')\n \"\"\"\n return self.find_element(by=By.ANDROID_UIAUTOMATOR, value=uia_string)\n\n def find_elements_by_android_uiautomator(self, uia_string):\n \"\"\"Finds elements by uiautomator in Android.\n\n :Args:\n - uia_string - The element name in the Android UIAutomator library\n\n :Usage:\n driver.find_elements_by_android_uiautomator('.elements()[1].cells()[2]')\n \"\"\"\n return self.find_elements(by=By.ANDROID_UIAUTOMATOR, value=uia_string)\n\n def find_element_by_accessibility_id(self, id):\n \"\"\"Finds an element by accessibility id.\n\n :Args:\n - id - a string corresponding to a recursive element search using the\n Id/Name that the native Accessibility options utilize\n\n :Usage:\n driver.find_element_by_accessibility_id()\n \"\"\"\n return self.find_element(by=By.ACCESSIBILITY_ID, value=id)\n\n def find_elements_by_accessibility_id(self, id):\n \"\"\"Finds elements by accessibility id.\n\n :Args:\n - id - a string corresponding to a recursive element search using the\n Id/Name that the native Accessibility options utilize\n\n :Usage:\n driver.find_elements_by_accessibility_id()\n \"\"\"\n return self.find_elements(by=By.ACCESSIBILITY_ID, value=id)\n\n def create_web_element(self, element_id):\n \"\"\"\n Creates a web element with the specified element_id.\n Overrides method in Selenium WebDriver in order to always give them\n Appium WebElement\n \"\"\"\n return MobileWebElement(self, element_id)\n\n # convenience method added to Appium (NOT Selenium 3)\n def scroll(self, origin_el, destination_el):\n \"\"\"Scrolls from one element to another\n\n :Args:\n - originalEl - the element from which to being scrolling\n - destinationEl - the element to scroll to\n\n :Usage:\n driver.scroll(el1, el2)\n \"\"\"\n action = TouchAction(self)\n action.press(origin_el).move_to(destination_el).release().perform()\n return self\n\n # convenience method added to Appium (NOT Selenium 3)\n def drag_and_drop(self, origin_el, destination_el):\n \"\"\"Drag the origin element to the destination element\n\n :Args:\n - originEl - the element to drag\n - destinationEl - the element to drag to\n \"\"\"\n action = TouchAction(self)\n action.long_press(origin_el).move_to(destination_el).release().perform()\n return self\n\n # convenience method added to Appium (NOT Selenium 3)\n def tap(self, positions, duration=None):\n \"\"\"Taps on an particular place with up to five fingers, holding for a\n certain time\n\n :Args:\n - positions - an array of tuples representing the x/y coordinates of\n the fingers to tap. Length can be up to five.\n - duration - (optional) length of time to tap, in ms\n\n :Usage:\n driver.tap([(100, 20), (100, 60), (100, 100)], 500)\n \"\"\"\n if len(positions) == 1:\n action = TouchAction(self)\n x = positions[0][0]\n y = positions[0][1]\n if duration:\n action.long_press(x=x, y=y, duration=duration).release()\n else:\n action.tap(x=x, y=y)\n action.perform()\n else:\n ma = MultiAction(self)\n for position in positions:\n x = position[0]\n y = position[1]\n action = TouchAction(self)\n if duration:\n action.long_press(x=x, y=y, duration=duration).release()\n else:\n action.press(x=x, y=y).release()\n ma.add(action)\n\n ma.perform()\n return self\n\n # convenience method added to Appium (NOT Selenium 3)\n def swipe(self, start_x, start_y, end_x, end_y, duration=None):\n \"\"\"Swipe from one point to another point, for an optional duration.\n\n :Args:\n - start_x - x-coordinate at which to start\n - start_y - y-coordinate at which to start\n - end_x - x-coordinate at which to stop\n - end_y - y-coordinate at which to stop\n - duration - (optional) time to take the swipe, in ms.\n\n :Usage:\n driver.swipe(100, 100, 100, 400)\n \"\"\"\n # `swipe` is something like press-wait-move_to-release, which the server\n # will translate into the correct action\n action = TouchAction(self)\n action \\\n .press(x=start_x, y=start_y) \\\n .wait(ms=duration) \\\n .move_to(x=end_x, y=end_y) \\\n .release()\n action.perform()\n return self\n\n # convenience method added to Appium (NOT Selenium 3)\n def flick(self, start_x, start_y, end_x, end_y):\n \"\"\"Flick from one point to another point.\n\n :Args:\n - start_x - x-coordinate at which to start\n - start_y - y-coordinate at which to start\n - end_x - x-coordinate at which to stop\n - end_y - y-coordinate at which to stop\n\n :Usage:\n driver.flick(100, 100, 100, 400)\n \"\"\"\n action = TouchAction(self)\n action \\\n .press(x=start_x, y=start_y) \\\n .move_to(x=end_x, y=end_y) \\\n .release()\n action.perform()\n return self\n\n # convenience method added to Appium (NOT Selenium 3)\n def pinch(self, element=None, percent=200, steps=50):\n \"\"\"Pinch on an element a certain amount\n\n :Args:\n - element - the element to pinch\n - percent - (optional) amount to pinch. Defaults to 200%\n - steps - (optional) number of steps in the pinch action\n\n :Usage:\n driver.pinch(element)\n \"\"\"\n if element:\n element = element.id\n\n opts = {\n 'element': element,\n 'percent': percent,\n 'steps': steps,\n }\n self.execute_script('mobile: pinchClose', opts)\n return self\n\n # convenience method added to Appium (NOT Selenium 3)\n def zoom(self, element=None, percent=200, steps=50):\n \"\"\"Zooms in on an element a certain amount\n\n :Args:\n - element - the element to zoom\n - percent - (optional) amount to zoom. Defaults to 200%\n - steps - (optional) number of steps in the zoom action\n\n :Usage:\n driver.zoom(element)\n \"\"\"\n if element:\n element = element.id\n\n opts = {\n 'element': element,\n 'percent': percent,\n 'steps': steps,\n }\n self.execute_script('mobile: pinchOpen', opts)\n return self\n\n def app_strings(self, language=None, string_file=None):\n \"\"\"Returns the application strings from the device for the specified\n language.\n\n :Args:\n - language - strings language code\n - string_file - the name of the string file to query\n \"\"\"\n data = {}\n if language != None:\n data['language'] = language\n if string_file != None:\n data['stringFile'] = string_file\n return self.execute(Command.GET_APP_STRINGS, data)['value']\n\n def reset(self):\n \"\"\"Resets the current application on the device.\n \"\"\"\n self.execute(Command.RESET)\n return self\n\n def hide_keyboard(self, key_name=None, key=None, strategy=None):\n \"\"\"Hides the software keyboard on the device. In iOS, use `key_name` to press\n a particular key, or `strategy`. In Android, no parameters are used.\n\n :Args:\n - key_name - key to press\n - strategy - strategy for closing the keyboard (e.g., `tapOutside`)\n \"\"\"\n data = {}\n if key_name is not None:\n data['keyName'] = key_name\n elif key is not None:\n data['key'] = key\n else:\n # defaults to `tapOutside` strategy\n strategy = 'tapOutside'\n data['strategy'] = strategy\n self.execute(Command.HIDE_KEYBOARD, data)\n return self\n\n # Needed for Selendroid\n def keyevent(self, keycode, metastate=None):\n \"\"\"Sends a keycode to the device. Android only. Possible keycodes can be\n found in http://developer.android.com/reference/android/view/KeyEvent.html.\n\n :Args:\n - keycode - the keycode to be sent to the device\n - metastate - meta information about the keycode being sent\n \"\"\"\n data = {\n 'keycode': keycode,\n }\n if metastate is not None:\n data['metastate'] = metastate\n self.execute(Command.KEY_EVENT, data)\n return self\n\n def press_keycode(self, keycode, metastate=None):\n \"\"\"Sends a keycode to the device. Android only. Possible keycodes can be\n found in http://developer.android.com/reference/android/view/KeyEvent.html.\n\n :Args:\n - keycode - the keycode to be sent to the device\n - metastate - meta information about the keycode being sent\n \"\"\"\n data = {\n 'keycode': keycode,\n }\n if metastate is not None:\n data['metastate'] = metastate\n self.execute(Command.PRESS_KEYCODE, data)\n return self\n\n def long_press_keycode(self, keycode, metastate=None):\n \"\"\"Sends a long press of keycode to the device. Android only. Possible keycodes can be\n found in http://developer.android.com/reference/android/view/KeyEvent.html.\n\n :Args:\n - keycode - the keycode to be sent to the device\n - metastate - meta information about the keycode being sent\n \"\"\"\n data = {\n 'keycode': keycode\n }\n if metastate != None:\n data['metastate'] = metastate\n self.execute(Command.LONG_PRESS_KEYCODE, data)\n return self\n\n @property\n def current_activity(self):\n \"\"\"Retrieves the current activity on the device.\n \"\"\"\n return self.execute(Command.GET_CURRENT_ACTIVITY)['value']\n\n def wait_activity(self, activity, timeout, interval=1):\n \"\"\"Wait for an activity: block until target activity presents\n or time out.\n\n This is an Android-only method.\n\n :Agrs:\n - activity - target activity\n - timeout - max wait time, in seconds\n - interval - sleep interval between retries, in seconds\n \"\"\"\n try:\n WebDriverWait(self, timeout, interval).until(\n lambda d: d.current_activity == activity)\n return True\n except TimeoutException:\n return False\n\n def set_value(self, element, value):\n \"\"\"Set the value on an element in the application.\n\n :Args:\n - element - the element whose value will be set\n - Value - the value to set on the element\n \"\"\"\n data = {\n 'elementId': element.id,\n 'value': [value],\n }\n self.execute(Command.SET_IMMEDIATE_VALUE, data)\n return self\n\n def pull_file(self, path):\n \"\"\"Retrieves the file at `path`. Returns the file's content encoded as\n Base64.\n\n :Args:\n - path - the path to the file on the device\n \"\"\"\n data = {\n 'path': path,\n }\n return self.execute(Command.PULL_FILE, data)['value']\n\n def pull_folder(self, path):\n \"\"\"Retrieves a folder at `path`. Returns the folder's contents zipped\n and encoded as Base64.\n\n :Args:\n - path - the path to the folder on the device\n \"\"\"\n data = {\n 'path': path,\n }\n return self.execute(Command.PULL_FOLDER, data)['value']\n\n def push_file(self, path, base64data):\n \"\"\"Puts the data, encoded as Base64, in the file specified as `path`.\n\n :Args:\n - path - the path on the device\n - base64data - data, encoded as Base64, to be written to the file\n \"\"\"\n data = {\n 'path': path,\n 'data': base64data,\n }\n self.execute(Command.PUSH_FILE, data)\n return self\n\n def background_app(self, seconds):\n \"\"\"Puts the application in the background on the device for a certain\n duration.\n\n :Args:\n - seconds - the duration for the application to remain in the background\n \"\"\"\n data = {\n 'seconds': seconds,\n }\n self.execute(Command.BACKGROUND, data)\n return self\n\n def is_app_installed(self, bundle_id):\n \"\"\"Checks whether the application specified by `bundle_id` is installed\n on the device.\n\n :Args:\n - bundle_id - the id of the application to query\n \"\"\"\n data = {\n 'bundleId': bundle_id,\n }\n return self.execute(Command.IS_APP_INSTALLED, data)['value']\n\n def install_app(self, app_path):\n \"\"\"Install the application found at `app_path` on the device.\n\n :Args:\n - app_path - the local or remote path to the application to install\n \"\"\"\n data = {\n 'appPath': app_path,\n }\n self.execute(Command.INSTALL_APP, data)\n return self\n\n def remove_app(self, app_id):\n \"\"\"Remove the specified application from the device.\n\n :Args:\n - app_id - the application id to be removed\n \"\"\"\n data = {\n 'appId': app_id,\n }\n self.execute(Command.REMOVE_APP, data)\n return self\n\n def launch_app(self):\n \"\"\"Start on the device the application specified in the desired capabilities.\n \"\"\"\n self.execute(Command.LAUNCH_APP)\n return self\n\n def close_app(self):\n \"\"\"Stop the running application, specified in the desired capabilities, on\n the device.\n \"\"\"\n self.execute(Command.CLOSE_APP)\n return self\n\n def start_activity(self, app_package, app_activity, **opts):\n \"\"\"Opens an arbitrary activity during a test. If the activity belongs to\n another application, that application is started and the activity is opened.\n\n This is an Android-only method.\n\n :Args:\n - app_package - The package containing the activity to start.\n - app_activity - The activity to start.\n - app_wait_package - Begin automation after this package starts (optional).\n - app_wait_activity - Begin automation after this activity starts (optional).\n - intent_action - Intent to start (optional).\n - intent_category - Intent category to start (optional).\n - intent_flags - Flags to send to the intent (optional).\n - optional_intent_arguments - Optional arguments to the intent (optional).\n - stop_app_on_reset - Should the app be stopped on reset (optional)?\n \"\"\"\n data = {\n 'appPackage': app_package,\n 'appActivity': app_activity\n }\n arguments = {\n 'app_wait_package': 'appWaitPackage',\n 'app_wait_activity': 'appWaitActivity',\n 'intent_action': 'intentAction',\n 'intent_category': 'intentCategory',", "answers": [" 'intent_flags': 'intentFlags',"], "length": 1901, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "f99078f4-b112-420b-80ab-86cd13ed82a8", "reasoning": "The start_activity method builds a dictionary of argument name mappings for optional parameters. The snippet ends inside the 'arguments' dict after the 'intent_category' entry. The next entry in the original Appium client code maps the 'intent_flags' option to the 'intentFlags' parameter, continuing the dict definition.", "reasoning_model_answer": "'intent_flags': 'intentFlags',", "assistant_with_reasoning": "\nThe start_activity method builds a dictionary of argument name mappings for optional parameters. The snippet ends inside the 'arguments' dict after the 'intent_category' entry. The next entry in the original Appium client code maps the 'intent_flags' option to the 'intentFlags' parameter, continuing the dict definition.\n\n'intent_flags': 'intentFlags',", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.907, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 18959, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "'intent_flags': 'intentFlags',", "score": 0.83, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "from __future__ import print_function\n\nimport os\nos.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\" \nos.environ[\"CUDA_VISIBLE_DEVICES\"]=\"1\"\n\nimport argparse\nimport csv\nimport os\nimport os.path\nimport shutil\nimport time\n\nimport numpy as np\nimport torch\nimport torch.backends.cudnn as cudnn\nimport torch.nn as nn\nimport torch.nn.parallel\nimport torch.optim as optim\nimport torch.utils.data as data\nimport torchvision.datasets as datasets\n\n#cudnn.enabled = False\ncudnn.benchmark = False\n#import torchvision.models as models\n#import torchvision.transforms as transforms\n#from PIL import Image\n#from models.single_modality.word_embeddings import load_data as w_load_data\n#from models.single_modality.word_embeddings import seq_model as w_seq_model\n\n\nfrom models.multimodal import load_data as m_load_data\nfrom models.multimodal import seq_model as m_seq_model\nimport torchvision.transforms as transforms\ntorch.multiprocessing.set_sharing_strategy('file_system')\nimport pickle\n\n\nmodel_names = []\nmodel_names.append('words_embeddings')\n\nparser = argparse.ArgumentParser(description='PyTorch Cats vs Dogs fine-tuning example')\nparser.add_argument('data', metavar='DIR', help='path to dataset')\nparser.add_argument(\n '--arch',\n metavar='ARCH',\n default='words_embeddings',\n choices=model_names,\n help='model architecture: ' + ' | '.join(model_names) + ' (default: words_embeddings)')\nparser.add_argument('--workers', default=4, type=int, metavar='N', help='number of data loading workers (default: 4)')\nparser.add_argument('--epochs', default=90, type=int, metavar='N', help='number of total epochs to run')\nparser.add_argument('--start-epoch', default=0, type=int, metavar='N', help='manual epoch number (useful on restarts)')\nparser.add_argument('-b', '--batch_size', default=16, type=int, metavar='N', help='mini-batch size (default: 256)')\nparser.add_argument('--lr', '--learning-rate', default=1e-4, type=float, metavar='LR', help='initial learning rate')\nparser.add_argument('--momentum', default=0.9, type=float, metavar='M', help='momentum')\nparser.add_argument('--weight-decay', default=1e-4, type=float, metavar='W', help='weight decay')\nparser.add_argument('--print-freq', default=1, type=int, metavar='N', help='print frequency')\nparser.add_argument('--resume', default='', type=str, metavar='PATH', help='path to latest checkpoint')\nparser.add_argument('--resume2', default='', type=str, metavar='PATH', help='path to latest checkpoint')\nparser.add_argument('--evaluate', dest='evaluate', action='store_true', help='evaluate model on validation set')\nparser.add_argument('--test', dest='test', action='store_true', help='evaluate model on test set')\nparser.add_argument('--pretrained', dest='pretrained', action='store_true', help='use pre-trained model')\nparser.add_argument('--cweights', default='', type=str, metavar='PATH', help='path to the file containing the list of labels')\nparser.add_argument('--softbatch', default=16, type=int, metavar='N', help='optimize parameters afer softbatch/batch_size samples')\n\nparser.add_argument('--save-path', default='./', type=str, metavar='PATH', help='path to save checkpoints')\n\n\nbest_prec1 = 0\n\n\nUSE_CUDA=True\n\n\ndef main():\n global args, best_prec1\n args = parser.parse_args()\n\n #if args.arch == \"words_embeddings\":\n #load_data = w_load_data\n \n # Data loading code\n if False:\n base_path_gremlin='/mnt/3T-NAS/Databases/jobScreening_cvpr17/'\n base_path_croissant='/disks/md0-4T/users/csp/jobScreening_cvpr17_partial/'\n base_path = base_path_croissant\n normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])\n reader = m_load_data.MultimodalReader(\n base_path_gremlin + '/train/annotation_training.pkl', \n base_path_gremlin + '/train/transcripts/ctms', \n base_path_gremlin + '/train/audios/fbank', \n #'/mnt/3T-NAS/csp/jobScreening_cvpr17/train/faces2/',\n base_path_croissant + '/train/faces/vgg_features',\n preload_path = base_path_croissant + '/train/preload/',\n transform=transforms.Compose([\n transforms.Scale(240),\n transforms.RandomSizedCrop(224),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n normalize,\n ]))\n \n reader_validation = m_load_data.MultimodalReader(\n base_path_gremlin + '/validation/annotation_validation.pkl', \n base_path_gremlin + '/validation/transcripts/ctms', \n base_path_gremlin + '/validation/audios/fbank', \n #'/mnt/3T-NAS/csp/jobScreening_cvpr17/validation/faces2/',\n base_path_croissant + '/validation/faces/vgg_features',\n preload_path = base_path_croissant + '/validation/preload/',\n transform=transforms.Compose([\n transforms.Scale(240),\n transforms.RandomSizedCrop(224),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n normalize,\n ]),\n word2id=reader.word2id, \n id2word=reader.id2word\n )\n \n reader_test = m_load_data.MultimodalReader(\n base_path_gremlin + '/test/annotation_test.pkl', \n base_path_gremlin + '/test/transcripts/ctms', \n base_path_gremlin + '/test/audios/fbank', \n #'/mnt/3T-NAS/csp/jobScreening_cvpr17/test/faces2/',\n base_path_croissant + '/test/faces/vgg_features',\n preload_path = base_path_croissant + '/test/preload/',\n transform=transforms.Compose([\n transforms.Scale(240),\n transforms.RandomSizedCrop(224),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n normalize,\n ]),\n word2id=reader.word2id, \n id2word=reader.id2word\n )\n \n with open('serialized_reader.pickle','wb') as stream:\n pickle.dump(reader,stream)\n \n with open('serialized_reader_validation.pickle','wb') as stream:\n pickle.dump(reader_validation,stream)\n\n with open('serialized_reader_test.pickle','wb') as stream:\n pickle.dump(reader_test,stream)\n return \n\n else:\n print(\"Loading serialized_reader\")\n with open('serialized_reader.pickle','rb') as stream:\n reader = pickle.load(stream) \n print(\"Loaded serialized_reader\")\n \n print(\"Loading serialized_reader_validation\")\n with open('serialized_reader_validation.pickle','rb') as stream:\n reader_validation = pickle.load(stream) \n print(\"Loaded serialized_reader_validation\")\n\n print(\"Loading serialized_reader_test\")\n with open('serialized_reader_test.pickle','rb') as stream:\n reader_test = pickle.load(stream) \n print(\"Loaded serialized_reader_test\")\n \n\n train_loader = data.DataLoader(\n reader,\n batch_size=args.batch_size,\n shuffle=True,\n num_workers=4,\n pin_memory=False, collate_fn=m_load_data.my_collate)\n \n val_loader = data.DataLoader(\n reader_validation,\n batch_size=args.batch_size,\n shuffle=True,\n num_workers=4,\n pin_memory=False, collate_fn=m_load_data.my_collate)\n \n test_loader = data.DataLoader(\n reader_test,\n batch_size=1,\n shuffle=False,\n num_workers=4,\n pin_memory=False, collate_fn=m_load_data.my_collate)\n \n #train_loader = data.DataLoader(\n #load_data.TranscriptionsReader('/mnt/3T-NAS/Databases/jobScreening_cvpr17/train/transcription_training.pkl',\n #'/mnt/3T-NAS/Databases/jobScreening_cvpr17/train/annotation_training.pkl'), \n #batch_size=args.batch_size, shuffle=True, num_workers=4, pin_memory=True, \n #collate_fn = load_data.TranscriptionsReader.my_collate\n #)\n\n #val_loader = data.DataLoader(\n #load_data.TranscriptionsReader('/mnt/3T-NAS/Databases/jobScreening_cvpr17/train/transcription_training.pkl',\n #'/mnt/3T-NAS/Databases/jobScreening_cvpr17/train/annotation_training.pkl'), \n #batch_size=args.batch_size, shuffle=True, num_workers=4, pin_memory=True, \n #collate_fn = load_data.TranscriptionsReader.my_collate\n #)\n\n #test_loader = data.DataLoader(\n #load_data.TranscriptionsReader('/mnt/3T-NAS/Databases/jobScreening_cvpr17/train/transcription_training.pkl',\n #'/mnt/3T-NAS/Databases/jobScreening_cvpr17/train/annotation_training.pkl'), \n #batch_size=args.batch_size, shuffle=True, num_workers=4, pin_memory=True, \n #collate_fn = load_data.TranscriptionsReader.my_collate\n #)\n\n\n\n\n if args.arch == \"words_embeddings\":\n #model = m_seq_model.Vgg_face_sequence_model(nhid=32, nlayers=2)\n model = m_seq_model.Word_Embeddings_sequence_model(vocab_size=len(train_loader.dataset.word2id),embedding_size=16,\n nhid=256, nlayers=2)\n\n #model = torch.nn.DataParallel(model).cuda()\n if USE_CUDA:\n model = model.cuda()\n\n # optionally resume from a checkpoint\n if args.resume:\n if os.path.isfile(args.resume):\n print(\"=> loading checkpoint '{}'\".format(args.resume))\n checkpoint = torch.load(args.resume)\n args.start_epoch = checkpoint['epoch']\n best_prec1 = checkpoint['best_prec1']\n model.load_state_dict(checkpoint['state_dict'])\n print(\"=> loaded checkpoint '{}' (epoch {})\".format(args.evaluate, checkpoint['epoch']))\n else:\n print(\"=> no checkpoint found at '{}'\".format(args.resume))\n\n #cudnn.benchmark = True\n\n\n if args.test:\n print(\"Testing the model and generating a output csv for submission\")\n test(test_loader, train_loader.dataset.class_to_idx, model)\n return\n # define loss function (criterion) and pptimizer\n if args.cweights != '':\n from sklearn.utils import class_weight\n clabels = []\n with open(args.cweights, 'r') as stream:\n for line in stream:\n line=line.strip()\n clabels.append(line)\n class_weight = class_weight.compute_class_weight('balanced', np.unique(clabels),clabels)\n class_weight = torch.from_numpy(class_weight).float()\n else:\n class_weight = None\n\n #criterion = nn.CrossEntropyLoss(weight=class_weight)\n criterion = nn.MSELoss()\n if USE_CUDA:\n criterion.cuda()\n\n #optimizer = optim.Adam(model.module.fc.parameters(), args.lr, weight_decay=args.weight_decay)\n optimizer = optim.Adam( filter(lambda p: p.requires_grad, model.parameters()) , args.lr, weight_decay=args.weight_decay)\n \n\n if args.evaluate:\n validate(val_loader, model, criterion)\n return\n\n for epoch in range(args.start_epoch, args.epochs):\n adjust_learning_rate(optimizer, epoch)\n\n # train for one epoch\n train(train_loader, model, criterion, optimizer, epoch)\n\n # evaluate on validation set\n prec1 = validate(val_loader, model, criterion)\n\n # remember best Accuracy and save checkpoint\n is_best = prec1 > best_prec1\n best_prec1 = max(prec1, best_prec1)\n save_checkpoint({\n 'epoch': epoch + 1,\n 'arch': args.arch,\n 'state_dict': model.state_dict(),\n 'best_prec1': best_prec1,\n }, is_best)\n\n\ndef train(train_loader, model, criterion, optimizer, epoch):\n batch_time = AverageMeter()\n data_time = AverageMeter()\n losses = AverageMeter()\n accs = {}\n for key in train_loader.dataset.traits:\n accs[key] = AverageMeter()\n \n #import tracemalloc\n #tracemalloc.start()\n # switch to train mode\n model.train()\n \n soft_batch = int(np.ceil(args.softbatch/args.batch_size))\n #acc_loss = 0\n optimizer.zero_grad()\n\n \n end = time.time()\n for i, (transcripts, faces, filterbanks, target) in enumerate(train_loader):\n # measure data loading time\n data_time.update(time.time() - end)\n\n if USE_CUDA:\n target = target.cuda(async=True)\n \n \n hidden = model.init_hidden(transcripts.size()[0])\n if USE_CUDA:\n hidden = (hidden[0].cuda(), hidden[1].cuda())\n \n train_text=False\n train_audio=False\n train_video=False \n urand = np.random.uniform()\n if urand < 1.0/3.0:\n train_text = True\n elif urand > 2.0/3.0:\n train_audio = True\n else:\n train_video = True\n \n y_pred = model(transcripts, faces, filterbanks, hidden, train_text = train_text, train_audio=train_audio, train_video=train_video)\n \n \n ##print(images)\n ##image_var = torch.autograd.Variable(images)\n #images=faces[0]\n ##images=images[0:4,:,:,:,:]\n #image_var = images\n ##print(images.size()[0])\n label_var = torch.autograd.Variable(target)\n #hidden = model.init_hidden(images.size()[0])\n #if USE_CUDA:\n #hidden = (hidden[0].cuda(), hidden[1].cuda())\n ##print(label_var)\n ##label_var + \"hola\"\n\n ## compute y_pred\n #y_pred = model(image_var, hidden)\n ##print(y_pred)\n loss = criterion(y_pred, label_var)\n\n # measure accuracy and record loss\n #prec1, prec1 = accuracy(y_pred.data, target, topk=(1, 1))\n losses.update(loss.data[0], transcripts.size(0))\n #acc.update(prec1[0], transcripts.size(0))\n curr_accuracy = regression_accuracy(y_pred.data, target).cpu().numpy()[0]\n for j, key in enumerate(train_loader.dataset.traits):\n accs[key].update(curr_accuracy[j], transcripts.size(0))\n\n # compute gradient and do SGD step\n #optimizer.zero_grad()\n loss.backward()\n #optimizer.step()\n \n if (i+1) % soft_batch == 0:\n print(\"Optimizing parameters\")\n optimizer.step()\n acc_loss = 0\n optimizer.zero_grad()\n\n # measure elapsed time\n batch_time.update(time.time() - end)\n end = time.time()\n \n #snapshot = tracemalloc.take_snapshot()\n #stats_file = open('stats.txt','w')\n #top_stats = snapshot.statistics('lineno')\n #for ts in top_stats:\n #stats_file.write(str(ts))\n #stats_file.write('\\n')\n #stats_file.close()\n #return\n\n if i % args.print_freq == 0:\n print('Epoch: [{0}][{1}/{2}]\\t'\n 'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\\t'\n 'Data {data_time.val:.3f} ({data_time.avg:.3f})\\t'\n 'Loss {loss.val:.4f} ({loss.avg:.4f})\\t'\n 'Interview Acc {interview.val:.3f} ({interview.avg:.3f})\\t'\n 'agreeableness {agreeableness.val:.3f} ({agreeableness.avg:.3f})\\t'\n 'conscientiousness {conscientiousness.val:.3f} ({conscientiousness.avg:.3f})\\t'\n 'extraversion {extraversion.val:.3f} ({extraversion.avg:.3f})\\t'\n 'neuroticism {neuroticism.val:.3f} ({neuroticism.avg:.3f})\\t'\n 'openness {openness.val:.3f} ({openness.avg:.3f})'\n .format(\n epoch, i, len(train_loader), batch_time=batch_time, data_time=data_time, loss=losses, interview=accs['interview'], agreeableness=accs['agreeableness'], conscientiousness=accs['conscientiousness'], extraversion=accs['extraversion'], neuroticism=accs['neuroticism'], openness=accs['openness'] ))\n\n\ndef validate(val_loader, model, criterion):\n batch_time = AverageMeter()\n losses = AverageMeter()\n #acc = AverageMeter()\n accs = {}\n for key in val_loader.dataset.traits:\n accs[key] = AverageMeter()\n \n # switch to evaluate mode\n model.eval()\n\n end = time.time()\n\n #label_var + \"hola\"\n for i, (transcripts, faces, filterbanks, target) in enumerate(val_loader):\n #data_time.update(time.time() - end)\n\n if USE_CUDA:\n target = target.cuda(async=True)\n \n \n hidden = model.init_hidden(transcripts.size()[0])\n if USE_CUDA:\n hidden = (hidden[0].cuda(), hidden[1].cuda())\n \n y_pred = model(transcripts, faces, filterbanks, hidden)\n \n\n label_var = torch.autograd.Variable(target, volatile=True) # compute y_pred\n loss = criterion(y_pred, label_var)\n\n # measure accuracy and record loss\n #prec1, temp_var = accuracy(y_pred.data, labels, topk=(1, 1))\n losses.update(loss.data[0], transcripts.size(0))\n #acc.update(prec1[0], transcripts.size(0))\n #acc.update( 0.5, transcripts.size(0))\n acc_mean=0\n curr_accuracy = regression_accuracy(y_pred.data, target).cpu().numpy()[0]\n for j, key in enumerate(val_loader.dataset.traits):\n accs[key].update(curr_accuracy[j], transcripts.size(0))\n acc_mean += accs[key].avg\n acc_mean = acc_mean / 6.0\n # measure elapsed time\n batch_time.update(time.time() - end)\n end = time.time()\n\n if i % args.print_freq == 0:\n print('TrainVal: [{0}/{1}]\\t'\n 'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\\t'\n 'Loss {loss.val:.4f} ({loss.avg:.4f})\\t'\n 'Interview Acc {interview.val:.3f} ({interview.avg:.3f})\\t'\n 'agreeableness {agreeableness.val:.3f} ({agreeableness.avg:.3f})\\t'\n 'conscientiousness {conscientiousness.val:.3f} ({conscientiousness.avg:.3f})\\t'\n 'extraversion {extraversion.val:.3f} ({extraversion.avg:.3f})\\t'\n 'neuroticism {neuroticism.val:.3f} ({neuroticism.avg:.3f})\\t'\n 'openness {openness.val:.3f} ({openness.avg:.3f})'\n .format(\n i, len(val_loader), batch_time=batch_time, loss=losses, interview=accs['interview'], agreeableness=accs['agreeableness'], conscientiousness=accs['conscientiousness'], extraversion=accs['extraversion'], neuroticism=accs['neuroticism'], openness=accs['openness'] ))\n\n print(' * Accuracy {acc_mean:.3f}'.format(acc_mean=acc_mean))\n\n return acc_mean\n\n\ndef test(test_loader, class_to_idx, model):\n csv_map = {}\n csv2_map = {}\n \n # switch to evaluate mode\n model.eval()\n old_sbj_id = \"\"\n acc_probs = np.zeros(7)\n ncount = 0\n\n\n for i, (transcripts, faces, filterbanks, target) in enumerate(test_loader):\n \n \n hidden = model.init_hidden(transcripts.size()[0])\n if USE_CUDA:\n hidden = (hidden[0].cuda(), hidden[1].cuda())\n \n y_pred = model(transcripts, faces, hidden)\n \n\n label_var = torch.autograd.Variable(labels, volatile=True) # compute y_pred\n\n### THIS IS STILL BAD\n scores = y_pred.data.cpu().numpy()\n for i, key in enumerate(test_loader.dataset.traits):\n out = ' ' + key + ' ' + str(scores[i])\n sys.stdout.write(out)\n #print(key, scores[i])\n print(\"\")\n\n # get the index of the max log-probability\n smax = nn.Softmax()\n smax_out = smax(y_pred)[0]\n \n angry_prob = smax_out.data[class_to_idx['Angry']]\n disgust_prob = smax_out.data[class_to_idx['Disgust']]\n fear_prob = smax_out.data[class_to_idx['Fear']]\n happy_prob = smax_out.data[class_to_idx['Happy']]\n neutral_prob = smax_out.data[class_to_idx['Neutral']]\n sad_prob = smax_out.data[class_to_idx['Sad']]\n surprise_prob = smax_out.data[class_to_idx['Surprise']]\n \n \n #cat_prob = smax_out.data[0]\n #dog_prob = smax_out.data[1]\n #prob = dog_prob\n #if cat_prob > dog_prob:\n #prob = 1 - cat_prob\n #prob = np.around(prob, decimals=4)\n #prob = np.clip(prob, .0001, .999)\n csv_map[filepath] = [angry_prob, disgust_prob, fear_prob, happy_prob, neutral_prob, sad_prob, surprise_prob]\n #print(filepath, {\"Angry\" : angry_prob, \"Disgust\" : disgust_prob, \"Fear\" : fear_prob, \"Happy\": happy_prob, \"Neutral\" : neutral_prob, \"Sad\" : sad_prob, \"Surprise\" : surprise_prob})\n\n sbj_id = str(filepath).strip().split('/')[-1].split('_')[0]", "answers": [" if sbj_id != old_sbj_id:"], "length": 1346, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "73da9f32-57bd-45d7-9612-376612900fa2", "reasoning": "The test function is aggregating predictions per subject. After extracting sbj_id from the file path, the next logical step is to check whether the current subject differs from the previous one to handle aggregation. Therefore, the next line should start an if-statement comparing sbj_id with old_sbj_id.", "reasoning_model_answer": "if sbj_id != old_sbj_id:", "assistant_with_reasoning": "\nThe test function is aggregating predictions per subject. After extracting sbj_id from the file path, the next logical step is to check whether the current subject differs from the previous one to handle aggregation. Therefore, the next line should start an if-statement comparing sbj_id with old_sbj_id.\n\nif sbj_id != old_sbj_id:", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 6.95, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 21052, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "if sbj_id != old_sbj_id:", "score": 0.86, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/*\n * Copyright (C) 2007 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.inject.throwingproviders;\n\nimport static com.google.common.collect.ImmutableSet.toImmutableSet;\nimport static java.lang.annotation.ElementType.METHOD;\nimport static java.lang.annotation.RetentionPolicy.RUNTIME;\nimport static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.assertTrue;\nimport static org.junit.Assert.fail;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Iterables;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.BindingAnnotation;\nimport com.google.inject.CreationException;\nimport com.google.inject.Guice;\nimport com.google.inject.Inject;\nimport com.google.inject.Injector;\nimport com.google.inject.Key;\nimport com.google.inject.TypeLiteral;\nimport com.google.inject.internal.util.Classes;\nimport com.google.inject.name.Named;\nimport com.google.inject.name.Names;\nimport com.google.inject.spi.Dependency;\nimport com.google.inject.spi.HasDependencies;\nimport com.google.inject.spi.Message;\nimport java.io.IOException;\nimport java.lang.annotation.Annotation;\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.Target;\nimport java.rmi.AccessException;\nimport java.rmi.RemoteException;\nimport java.util.Arrays;\nimport java.util.List;\nimport java.util.Set;\nimport java.util.TooManyListenersException;\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.junit.runners.JUnit4;\n\n/**\n * @author jmourits@google.com (Jerome Mourits)\n * @author jessewilson@google.com (Jesse Wilson)\n */\n@SuppressWarnings(\"deprecation\")\n@RunWith(JUnit4.class)\npublic class ThrowingProviderTest {\n @Target(METHOD)\n @Retention(RUNTIME)\n @BindingAnnotation\n @interface NotExceptionScoping {};\n\n private final TypeLiteral> remoteProviderOfString =\n new TypeLiteral>() {};\n private final MockRemoteProvider mockRemoteProvider = new MockRemoteProvider<>();\n private final TestScope testScope = new TestScope();\n private Injector bindInjector =\n Guice.createInjector(\n new AbstractModule() {\n @Override\n protected void configure() {\n ThrowingProviderBinder.create(binder())\n .bind(RemoteProvider.class, String.class)\n .to(mockRemoteProvider)\n .in(testScope);\n\n ThrowingProviderBinder.create(binder())\n .bind(RemoteProvider.class, String.class)\n .annotatedWith(NotExceptionScoping.class)\n .scopeExceptions(false)\n .to(mockRemoteProvider)\n .in(testScope);\n }\n });\n private Injector providesInjector =\n Guice.createInjector(\n new AbstractModule() {\n @Override\n protected void configure() {\n install(ThrowingProviderBinder.forModule(this));\n bindScope(TestScope.Scoped.class, testScope);\n }\n\n @SuppressWarnings(\"unused\")\n @CheckedProvides(RemoteProvider.class)\n @TestScope.Scoped\n String throwOrGet() throws RemoteException {\n return mockRemoteProvider.get();\n }\n\n @SuppressWarnings(\"unused\")\n @CheckedProvides(value = RemoteProvider.class, scopeExceptions = false)\n @NotExceptionScoping\n @TestScope.Scoped\n String notExceptionScopingThrowOrGet() throws RemoteException {\n return mockRemoteProvider.get();\n }\n });\n\n @Test\n public void testExceptionsThrown_Bind() {\n tExceptionsThrown(bindInjector);\n }\n\n @Test\n public void testExceptionsThrown_Provides() {\n tExceptionsThrown(providesInjector);\n }\n\n private void tExceptionsThrown(Injector injector) {\n RemoteProvider remoteProvider = injector.getInstance(Key.get(remoteProviderOfString));\n\n mockRemoteProvider.throwOnNextGet(\"kaboom!\");\n try {\n remoteProvider.get();\n fail();\n } catch (RemoteException expected) {\n assertEquals(\"kaboom!\", expected.getMessage());\n }\n }\n\n @Test\n public void testValuesScoped_Bind() throws RemoteException {\n tValuesScoped(bindInjector, null);\n }\n\n @Test\n public void testValuesScoped_Provides() throws RemoteException {\n tValuesScoped(providesInjector, null);\n }\n\n @Test\n public void testValuesScopedWhenNotExceptionScoping_Bind() throws RemoteException {\n tValuesScoped(bindInjector, NotExceptionScoping.class);\n }\n\n @Test\n public void testValuesScopedWhenNotExceptionScoping_Provides() throws RemoteException {\n tValuesScoped(providesInjector, NotExceptionScoping.class);\n }\n\n private void tValuesScoped(Injector injector, Class annotation)\n throws RemoteException {\n Key> key =\n annotation != null\n ? Key.get(remoteProviderOfString, annotation)\n : Key.get(remoteProviderOfString);\n RemoteProvider remoteProvider = injector.getInstance(key);\n\n mockRemoteProvider.setNextToReturn(\"A\");\n assertEquals(\"A\", remoteProvider.get());\n\n mockRemoteProvider.setNextToReturn(\"B\");\n assertEquals(\"A\", remoteProvider.get());\n\n testScope.beginNewScope();\n assertEquals(\"B\", remoteProvider.get());\n }\n\n @Test\n public void testExceptionsScoped_Bind() {\n tExceptionsScoped(bindInjector);\n }\n\n @Test\n public void testExceptionsScoped_Provides() {\n tExceptionsScoped(providesInjector);\n }\n\n private void tExceptionsScoped(Injector injector) {\n RemoteProvider remoteProvider = injector.getInstance(Key.get(remoteProviderOfString));\n\n mockRemoteProvider.throwOnNextGet(\"A\");\n try {\n remoteProvider.get();\n fail();\n } catch (RemoteException expected) {\n assertEquals(\"A\", expected.getMessage());\n }\n\n mockRemoteProvider.throwOnNextGet(\"B\");\n try {\n remoteProvider.get();\n fail();\n } catch (RemoteException expected) {\n assertEquals(\"A\", expected.getMessage());\n }\n }\n\n @Test\n public void testExceptionsNotScopedWhenNotExceptionScoping_Bind() {\n tExceptionsNotScopedWhenNotExceptionScoping(bindInjector);\n }\n\n @Test\n public void testExceptionsNotScopedWhenNotExceptionScoping_Provides() {\n tExceptionsNotScopedWhenNotExceptionScoping(providesInjector);\n }\n\n private void tExceptionsNotScopedWhenNotExceptionScoping(Injector injector) {\n RemoteProvider remoteProvider =\n injector.getInstance(Key.get(remoteProviderOfString, NotExceptionScoping.class));\n\n mockRemoteProvider.throwOnNextGet(\"A\");\n try {\n remoteProvider.get();\n fail();\n } catch (RemoteException expected) {\n assertEquals(\"A\", expected.getMessage());\n }\n\n mockRemoteProvider.throwOnNextGet(\"B\");\n try {\n remoteProvider.get();\n fail();\n } catch (RemoteException expected) {\n assertEquals(\"B\", expected.getMessage());\n }\n }\n\n @Test\n public void testAnnotations_Bind() throws RemoteException {\n final MockRemoteProvider mockRemoteProviderA = new MockRemoteProvider<>();\n final MockRemoteProvider mockRemoteProviderB = new MockRemoteProvider<>();\n bindInjector =\n Guice.createInjector(\n new AbstractModule() {\n @Override\n protected void configure() {\n ThrowingProviderBinder.create(binder())\n .bind(RemoteProvider.class, String.class)\n .annotatedWith(Names.named(\"a\"))\n .to(mockRemoteProviderA);\n\n ThrowingProviderBinder.create(binder())\n .bind(RemoteProvider.class, String.class)\n .to(mockRemoteProviderB);\n }\n });\n tAnnotations(bindInjector, mockRemoteProviderA, mockRemoteProviderB);\n }\n\n @Test\n public void testAnnotations_Provides() throws RemoteException {\n final MockRemoteProvider mockRemoteProviderA = new MockRemoteProvider<>();\n final MockRemoteProvider mockRemoteProviderB = new MockRemoteProvider<>();\n providesInjector =\n Guice.createInjector(\n new AbstractModule() {\n @Override\n protected void configure() {\n install(ThrowingProviderBinder.forModule(this));\n }\n\n @SuppressWarnings(\"unused\")\n @CheckedProvides(RemoteProvider.class)\n @Named(\"a\")\n String throwOrGet() throws RemoteException {\n return mockRemoteProviderA.get();\n }\n\n @SuppressWarnings(\"unused\")\n @CheckedProvides(RemoteProvider.class)\n String throwOrGet2() throws RemoteException {\n return mockRemoteProviderB.get();\n }\n });\n tAnnotations(providesInjector, mockRemoteProviderA, mockRemoteProviderB);\n }\n\n private void tAnnotations(\n Injector injector, MockRemoteProvider mockA, MockRemoteProvider mockB)\n throws RemoteException {\n mockA.setNextToReturn(\"A\");\n mockB.setNextToReturn(\"B\");\n assertEquals(\n \"A\", injector.getInstance(Key.get(remoteProviderOfString, Names.named(\"a\"))).get());\n\n assertEquals(\"B\", injector.getInstance(Key.get(remoteProviderOfString)).get());\n }\n\n @Test\n public void testUndeclaredExceptions_Bind() throws RemoteException {\n tUndeclaredExceptions(bindInjector);\n }\n\n @Test\n public void testUndeclaredExceptions_Provides() throws RemoteException {\n tUndeclaredExceptions(providesInjector);\n }\n\n private void tUndeclaredExceptions(Injector injector) throws RemoteException {\n RemoteProvider remoteProvider = injector.getInstance(Key.get(remoteProviderOfString));\n mockRemoteProvider.throwOnNextGet(new IndexOutOfBoundsException(\"A\"));\n try {\n remoteProvider.get();\n fail();\n } catch (RuntimeException e) {\n assertEquals(\"A\", e.getCause().getMessage());\n }\n\n // undeclared exceptions shouldn't be scoped\n mockRemoteProvider.throwOnNextGet(new IndexOutOfBoundsException(\"B\"));\n try {\n remoteProvider.get();\n fail();\n } catch (RuntimeException e) {\n assertEquals(\"B\", e.getCause().getMessage());\n }\n }\n\n @Test\n public void testThrowingProviderSubclassing() throws RemoteException {\n final SubMockRemoteProvider aProvider = new SubMockRemoteProvider();\n aProvider.setNextToReturn(\"A\");\n\n bindInjector =\n Guice.createInjector(\n new AbstractModule() {\n @Override\n protected void configure() {\n ThrowingProviderBinder.create(binder())\n .bind(RemoteProvider.class, String.class)\n .to(aProvider);\n }\n });\n\n assertEquals(\"A\", bindInjector.getInstance(Key.get(remoteProviderOfString)).get());\n }\n\n static class SubMockRemoteProvider extends MockRemoteProvider {}\n\n @Test\n public void testBindingToNonInterfaceType_Bind() throws RemoteException {\n try {\n Guice.createInjector(\n new AbstractModule() {\n @Override\n protected void configure() {\n ThrowingProviderBinder.create(binder())\n .bind(MockRemoteProvider.class, String.class)\n .to(mockRemoteProvider);\n }\n });\n fail();\n } catch (CreationException expected) {\n assertEquals(\n MockRemoteProvider.class.getName() + \" must be an interface\",\n Iterables.getOnlyElement(expected.getErrorMessages()).getMessage());\n }\n }\n\n @Test\n public void testBindingToNonInterfaceType_Provides() throws RemoteException {\n try {\n Guice.createInjector(\n new AbstractModule() {\n @Override\n protected void configure() {\n install(ThrowingProviderBinder.forModule(this));\n }\n\n @SuppressWarnings(\"unused\")\n @CheckedProvides(MockRemoteProvider.class)\n String foo() {\n return null;\n }\n });\n fail();\n } catch (CreationException expected) {\n assertEquals(\n MockRemoteProvider.class.getName() + \" must be an interface\",\n Iterables.getOnlyElement(expected.getErrorMessages()).getMessage());\n }\n }\n\n @Test\n public void testBindingToSubSubInterface_Bind() throws RemoteException {\n try {\n bindInjector =\n Guice.createInjector(\n new AbstractModule() {\n @Override\n protected void configure() {\n ThrowingProviderBinder.create(binder())\n .bind(SubRemoteProvider.class, String.class);\n }\n });\n fail();\n } catch (CreationException expected) {\n assertEquals(\n SubRemoteProvider.class.getName()\n + \" must extend CheckedProvider (and only CheckedProvider)\",\n Iterables.getOnlyElement(expected.getErrorMessages()).getMessage());\n }\n }\n\n @Test\n public void testBindingToSubSubInterface_Provides() throws RemoteException {\n try {\n Guice.createInjector(\n new AbstractModule() {\n @Override\n protected void configure() {\n install(ThrowingProviderBinder.forModule(this));\n }\n\n @SuppressWarnings(\"unused\")\n @CheckedProvides(SubRemoteProvider.class)\n String foo() {\n return null;\n }\n });\n fail();\n } catch (CreationException expected) {\n assertEquals(\n SubRemoteProvider.class.getName()\n + \" must extend CheckedProvider (and only CheckedProvider)\",\n Iterables.getOnlyElement(expected.getErrorMessages()).getMessage());\n }\n }\n\n interface SubRemoteProvider extends RemoteProvider {}\n\n @Test\n public void testBindingToInterfaceWithExtraMethod_Bind() throws RemoteException {\n try {\n bindInjector =\n Guice.createInjector(\n new AbstractModule() {\n @Override\n protected void configure() {\n ThrowingProviderBinder.create(binder())\n .bind(RemoteProviderWithExtraMethod.class, String.class);\n }\n });\n fail();\n } catch (CreationException expected) {\n assertEquals(\n RemoteProviderWithExtraMethod.class.getName()\n + \" may not declare any new methods, but declared \"\n + RemoteProviderWithExtraMethod.class.getDeclaredMethods()[0].toGenericString(),\n Iterables.getOnlyElement(expected.getErrorMessages()).getMessage());\n }\n }\n\n @Test\n public void testBindingToInterfaceWithExtraMethod_Provides() throws RemoteException {\n try {\n Guice.createInjector(\n new AbstractModule() {\n @Override\n protected void configure() {\n install(ThrowingProviderBinder.forModule(this));\n }\n\n @SuppressWarnings(\"unused\")\n @CheckedProvides(RemoteProviderWithExtraMethod.class)\n String foo() {\n return null;\n }\n });\n fail();\n } catch (CreationException expected) {\n assertEquals(\n RemoteProviderWithExtraMethod.class.getName()\n + \" may not declare any new methods, but declared \"\n + RemoteProviderWithExtraMethod.class.getDeclaredMethods()[0].toGenericString(),\n Iterables.getOnlyElement(expected.getErrorMessages()).getMessage());\n }\n }\n\n @Test\n public void testDependencies_Bind() {\n bindInjector =\n Guice.createInjector(\n new AbstractModule() {\n @Override\n protected void configure() {\n bind(String.class).toInstance(\"Foo\");\n bind(Integer.class).toInstance(5);\n bind(Double.class).toInstance(5d);\n bind(Long.class).toInstance(5L);\n ThrowingProviderBinder.create(binder())\n .bind(RemoteProvider.class, String.class)\n .to(DependentRemoteProvider.class);\n }\n });\n\n HasDependencies hasDependencies =\n (HasDependencies) bindInjector.getBinding(Key.get(remoteProviderOfString));\n hasDependencies =\n (HasDependencies)\n bindInjector.getBinding(\n Iterables.getOnlyElement(hasDependencies.getDependencies()).getKey());\n // Make sure that that is dependent on DependentRemoteProvider.\n assertEquals(\n Dependency.get(Key.get(DependentRemoteProvider.class)),\n Iterables.getOnlyElement(hasDependencies.getDependencies()));\n // And make sure DependentRemoteProvider has the proper dependencies.\n hasDependencies = (HasDependencies) bindInjector.getBinding(DependentRemoteProvider.class);\n Set> dependencyKeys =\n hasDependencies.getDependencies().stream()\n .map(Dependency::getKey)\n .collect(toImmutableSet());\n assertEquals(\n ImmutableSet.>of(\n Key.get(String.class),\n Key.get(Integer.class),\n Key.get(Long.class),\n Key.get(Double.class)),\n dependencyKeys);\n }\n\n @Test\n public void testDependencies_Provides() {\n providesInjector =\n Guice.createInjector(\n new AbstractModule() {\n @Override\n protected void configure() {\n bind(String.class).toInstance(\"Foo\");\n bind(Integer.class).toInstance(5);\n bind(Double.class).toInstance(5d);\n bind(Long.class).toInstance(5L);\n install(ThrowingProviderBinder.forModule(this));\n }\n\n @SuppressWarnings(\"unused\")\n @CheckedProvides(RemoteProvider.class)\n String foo(String s, Integer i, Double d, Long l) {\n return null;\n }\n });\n\n HasDependencies hasDependencies =\n (HasDependencies) providesInjector.getBinding(Key.get(remoteProviderOfString));\n // RemoteProvider is dependent on the provider method..\n hasDependencies =\n (HasDependencies)\n providesInjector.getBinding(\n Iterables.getOnlyElement(hasDependencies.getDependencies()).getKey());\n // And the provider method has our real dependencies..\n hasDependencies =\n (HasDependencies)\n providesInjector.getBinding(\n Iterables.getOnlyElement(hasDependencies.getDependencies()).getKey());\n Set> dependencyKeys =\n hasDependencies.getDependencies().stream()\n .map(Dependency::getKey)\n .collect(toImmutableSet());\n assertEquals(\n ImmutableSet.>of(\n Key.get(String.class),\n Key.get(Integer.class),\n Key.get(Long.class),\n Key.get(Double.class)),\n dependencyKeys);\n }\n\n interface RemoteProviderWithExtraMethod extends ThrowingProvider {\n T get(T defaultValue) throws RemoteException;\n }\n\n interface RemoteProvider extends ThrowingProvider {}\n\n static class DependentRemoteProvider implements RemoteProvider {\n @Inject double foo;\n\n @Inject\n public DependentRemoteProvider(String foo, int bar) {}\n\n @Inject\n void initialize(long foo) {}\n\n @Override\n public T get() throws RemoteException {\n return null;\n }\n }\n\n static class MockRemoteProvider implements RemoteProvider {\n Exception nextToThrow;\n T nextToReturn;\n\n public void throwOnNextGet(String message) {\n throwOnNextGet(new RemoteException(message));\n }\n\n public void throwOnNextGet(Exception nextToThrow) {\n this.nextToThrow = nextToThrow;\n }\n\n public void setNextToReturn(T nextToReturn) {\n this.nextToReturn = nextToReturn;\n }\n\n @Override\n public T get() throws RemoteException {\n if (nextToThrow instanceof RemoteException) {\n throw (RemoteException) nextToThrow;\n } else if (nextToThrow instanceof RuntimeException) {\n throw (RuntimeException) nextToThrow;\n } else if (nextToThrow == null) {\n return nextToReturn;\n } else {\n throw new AssertionError(\"nextToThrow must be a runtime or remote exception\");\n }\n }\n }\n\n @Test\n public void testBindingToInterfaceWithBoundValueType_Bind() throws RemoteException {\n bindInjector =\n Guice.createInjector(\n new AbstractModule() {\n @Override\n protected void configure() {\n ThrowingProviderBinder.create(binder())\n .bind(StringRemoteProvider.class, String.class)\n .to(\n new StringRemoteProvider() {\n @Override\n public String get() throws RemoteException {\n return \"A\";\n }\n });\n }\n });\n\n assertEquals(\"A\", bindInjector.getInstance(StringRemoteProvider.class).get());\n }\n\n @Test\n public void testBindingToInterfaceWithBoundValueType_Provides() throws RemoteException {\n providesInjector =\n Guice.createInjector(\n new AbstractModule() {\n @Override\n protected void configure() {\n install(ThrowingProviderBinder.forModule(this));\n }\n\n @SuppressWarnings(\"unused\")\n @CheckedProvides(StringRemoteProvider.class)\n String foo() throws RemoteException {\n return \"A\";\n }\n });\n\n assertEquals(\"A\", providesInjector.getInstance(StringRemoteProvider.class).get());\n }\n\n interface StringRemoteProvider extends ThrowingProvider {}\n\n @Test\n public void testBindingToInterfaceWithGeneric_Bind() throws RemoteException {\n bindInjector =\n Guice.createInjector(\n new AbstractModule() {\n @Override\n protected void configure() {\n ThrowingProviderBinder.create(binder())\n .bind(RemoteProvider.class, new TypeLiteral>() {}.getType())\n .to(\n new RemoteProvider>() {\n @Override\n public List get() throws RemoteException {\n return Arrays.asList(\"A\", \"B\");\n }\n });\n }\n });\n\n Key>> key =\n Key.get(new TypeLiteral>>() {});\n assertEquals(Arrays.asList(\"A\", \"B\"), bindInjector.getInstance(key).get());\n }\n\n @Test\n public void testBindingToInterfaceWithGeneric_Provides() throws RemoteException {\n providesInjector =\n Guice.createInjector(\n new AbstractModule() {\n @Override\n protected void configure() {\n install(ThrowingProviderBinder.forModule(this));\n }\n\n @SuppressWarnings(\"unused\")\n @CheckedProvides(RemoteProvider.class)\n List foo() throws RemoteException {\n return Arrays.asList(\"A\", \"B\");\n }\n });\n\n Key>> key =\n Key.get(new TypeLiteral>>() {});\n assertEquals(Arrays.asList(\"A\", \"B\"), providesInjector.getInstance(key).get());\n }\n\n @Test\n public void testProviderMethodWithWrongException() {\n try {\n Guice.createInjector(\n new AbstractModule() {\n @Override\n protected void configure() {\n install(ThrowingProviderBinder.forModule(this));\n }\n\n @SuppressWarnings(\"unused\")\n @CheckedProvides(RemoteProvider.class)\n String foo() throws InterruptedException {\n return null;\n }\n });\n fail();\n } catch (CreationException ce) {\n assertEquals(\n InterruptedException.class.getName()\n + \" is not compatible with the exceptions ([\"\n + RemoteException.class\n + \"]) declared in the CheckedProvider interface (\"\n + RemoteProvider.class.getName()\n + \")\",", "answers": [" Iterables.getOnlyElement(ce.getErrorMessages()).getMessage());"], "length": 1559, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "8e4fc0f0-baa1-47b6-8dc8-f25bc692e8dd", "reasoning": "The test ends with a catch block for CreationException where an assertEquals is started to compare the expected error message string with the actual message from the exception. Following the pattern used elsewhere, the second argument should retrieve the single error message from the CreationException via Iterables.getOnlyElement(ce.getErrorMessages()).getMessage(). This completes the assertEquals call.", "reasoning_model_answer": "Iterables.getOnlyElement(ce.getErrorMessages()).getMessage());", "assistant_with_reasoning": "\nThe test ends with a catch block for CreationException where an assertEquals is started to compare the expected error message string with the actual message from the exception. Following the pattern used elsewhere, the second argument should retrieve the single error message from the CreationException via Iterables.getOnlyElement(ce.getErrorMessages()).getMessage(). This completes the assertEquals call.\n\nIterables.getOnlyElement(ce.getErrorMessages()).getMessage());", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.948, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 25037, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "Iterables.getOnlyElement(ce.getErrorMessages()).getMessage());", "score": 0.93, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/**\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.smartdata.hdfs.metric.fetcher;\n\nimport org.apache.hadoop.fs.XAttr;\nimport org.apache.hadoop.hdfs.DFSClient;\nimport org.apache.hadoop.hdfs.inotify.Event;\nimport org.apache.hadoop.hdfs.protocol.HdfsFileStatus;\nimport org.apache.hadoop.io.WritableUtils;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport org.smartdata.conf.SmartConf;\nimport org.smartdata.hdfs.CompatibilityHelperLoader;\nimport org.smartdata.hdfs.HadoopUtil;\nimport org.smartdata.metastore.DBType;\nimport org.smartdata.metastore.MetaStore;\nimport org.smartdata.metastore.MetaStoreException;\nimport org.smartdata.model.BackUpInfo;\nimport org.smartdata.model.FileDiff;\nimport org.smartdata.model.FileDiffType;\nimport org.smartdata.model.FileInfo;\n\nimport java.io.ByteArrayInputStream;\nimport java.io.DataInputStream;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\nimport java.io.IOException;\nimport java.net.URI;\nimport java.net.URISyntaxException;\n\n/**\n * This is a very preliminary and buggy applier, can further enhance by referring to\n * {@link org.apache.hadoop.hdfs.server.namenode.FSEditLogLoader}\n */\npublic class InotifyEventApplier {\n private final MetaStore metaStore;\n private DFSClient client;\n private static final Logger LOG =\n LoggerFactory.getLogger(InotifyEventFetcher.class);\n private List ignoreEventDirs;\n private List fetchEventDirs;\n private NamespaceFetcher namespaceFetcher;\n\n public InotifyEventApplier(MetaStore metaStore, DFSClient client) {\n this.metaStore = metaStore;\n this.client = client;\n initialize();\n }\n\n public InotifyEventApplier(MetaStore metaStore, DFSClient client, NamespaceFetcher namespaceFetcher) {\n this(metaStore, client);\n this.namespaceFetcher = namespaceFetcher;\n }\n\n private void initialize(){\n SmartConf conf = new SmartConf();\n ignoreEventDirs = conf.getIgnoreDir();\n fetchEventDirs = conf.getCoverDir();\n }\n\n\n public void apply(List events) throws IOException, MetaStoreException, InterruptedException {\n List statements = new ArrayList<>();\n for (Event event : events) {\n List gen = getSqlStatement(event);\n if (gen != null && !gen.isEmpty()) {\n for (String s : gen) {\n if (s != null && s.length() > 0) {\n statements.add(s);\n }\n }\n }\n }\n this.metaStore.execute(statements);\n }\n\n //check if the dir is in ignoreList\n\n public void apply(Event[] events) throws IOException, MetaStoreException, InterruptedException {\n this.apply(Arrays.asList(events));\n }\n\n private boolean shouldIgnore(String path) {\n String toCheck = path.endsWith(\"/\") ? path : path + \"/\";\n for (String s : ignoreEventDirs) {\n if (toCheck.startsWith(s)) {\n return true;\n }\n }\n if (fetchEventDirs.isEmpty()) {\n return false;\n }\n for (String s : fetchEventDirs) {\n if (toCheck.startsWith(s)) {\n return false;\n }\n }\n return true;\n }\n\n private List getSqlStatement(Event event) throws IOException, MetaStoreException, InterruptedException {\n String path;\n String srcPath, dstPath;\n LOG.debug(\"Even Type = {}\", event.getEventType().toString());\n switch (event.getEventType()) {\n case CREATE:\n path = ((Event.CreateEvent) event).getPath();\n if (shouldIgnore(path)) {\n return Arrays.asList();\n }\n LOG.trace(\"event type:\" + event.getEventType().name() +\n \", path:\" + ((Event.CreateEvent) event).getPath());\n return Arrays.asList(this.getCreateSql((Event.CreateEvent) event));\n case CLOSE:\n path = ((Event.CloseEvent) event).getPath();\n if (shouldIgnore(path)) {\n return Arrays.asList();\n }\n LOG.trace(\"event type:\" + event.getEventType().name() +\n \", path:\" + ((Event.CloseEvent) event).getPath());\n return Arrays.asList(this.getCloseSql((Event.CloseEvent) event));\n case RENAME:\n srcPath = ((Event.RenameEvent) event).getSrcPath();\n dstPath = ((Event.RenameEvent) event).getDstPath();\n if (shouldIgnore(srcPath) && shouldIgnore(dstPath)) {\n return Arrays.asList();\n }\n LOG.trace(\"event type:\" + event.getEventType().name() +\n \", src path:\" + ((Event.RenameEvent) event).getSrcPath() +\n \", dest path:\" + ((Event.RenameEvent) event).getDstPath());\n return this.getRenameSql((Event.RenameEvent)event);\n case METADATA:\n path = ((Event.MetadataUpdateEvent)event).getPath();\n if (shouldIgnore(path)) {\n return Arrays.asList();\n }\n LOG.trace(\"event type:\" + event.getEventType().name() +\n \", path:\" + ((Event.MetadataUpdateEvent)event).getPath());\n return Arrays.asList(this.getMetaDataUpdateSql((Event.MetadataUpdateEvent)event));\n case APPEND:\n path = ((Event.AppendEvent)event).getPath();\n if (shouldIgnore(path)) {\n return Arrays.asList();\n }\n LOG.trace(\"event type:\" + event.getEventType().name() +\n \", path:\" + ((Event.AppendEvent)event).getPath());\n return this.getAppendSql((Event.AppendEvent)event);\n case UNLINK:\n path = ((Event.UnlinkEvent)event).getPath();\n if (shouldIgnore(path)) {\n return Arrays.asList();\n }\n LOG.trace(\"event type:\" + event.getEventType().name() +\n \", path:\" + ((Event.UnlinkEvent)event).getPath());\n return this.getUnlinkSql((Event.UnlinkEvent)event);\n }\n return Arrays.asList();\n }\n\n //Todo: times and ec policy id, etc.\n private String getCreateSql(Event.CreateEvent createEvent) throws IOException, MetaStoreException {\n HdfsFileStatus fileStatus = client.getFileInfo(createEvent.getPath());\n if (fileStatus == null) {\n LOG.debug(\"Can not get HdfsFileStatus for file \" + createEvent.getPath());\n return \"\";\n }\n FileInfo fileInfo = HadoopUtil.convertFileStatus(fileStatus, createEvent.getPath());\n\n if (inBackup(fileInfo.getPath())) {\n if (!fileInfo.isdir()) {\n\n // ignore dir\n FileDiff fileDiff = new FileDiff(FileDiffType.APPEND);\n fileDiff.setSrc(fileInfo.getPath());\n fileDiff.getParameters().put(\"-offset\", String.valueOf(0));\n // Note that \"-length 0\" means create an empty file\n fileDiff.getParameters()\n .put(\"-length\", String.valueOf(fileInfo.getLength()));\n // TODO add support in CopyFileAction or split into two file diffs\n //add modification_time and access_time to filediff\n fileDiff.getParameters().put(\"-mtime\", \"\" + fileInfo.getModificationTime());\n // fileDiff.getParameters().put(\"-atime\", \"\" + fileInfo.getAccessTime());\n //add owner to filediff\n fileDiff.getParameters().put(\"-owner\", \"\" + fileInfo.getOwner());\n fileDiff.getParameters().put(\"-group\", \"\" + fileInfo.getGroup());\n //add Permission to filediff\n fileDiff.getParameters().put(\"-permission\", \"\" + fileInfo.getPermission());\n //add replication count to file diff\n fileDiff.getParameters().put(\"-replication\", \"\" + fileInfo.getBlockReplication());\n metaStore.insertFileDiff(fileDiff);\n }\n }\n metaStore.deleteFileByPath(fileInfo.getPath());\n metaStore.deleteFileState(fileInfo.getPath());\n metaStore.insertFile(fileInfo);\n return \"\";\n }\n\n private boolean inBackup(String src) throws MetaStoreException {\n if (metaStore.srcInbackup(src)) {\n return true;\n }\n return false;\n }\n\n //Todo: should update mtime? atime?\n private String getCloseSql(Event.CloseEvent closeEvent) throws IOException, MetaStoreException {\n FileDiff fileDiff = new FileDiff(FileDiffType.APPEND);\n fileDiff.setSrc(closeEvent.getPath());\n long newLen = closeEvent.getFileSize();\n long currLen = 0l;\n // TODO make sure offset is correct\n if (inBackup(closeEvent.getPath())) {\n FileInfo fileInfo = metaStore.getFile(closeEvent.getPath());\n if (fileInfo == null) {\n // TODO add metadata\n currLen = 0;\n } else {\n currLen = fileInfo.getLength();\n }\n if (currLen != newLen) {\n fileDiff.getParameters().put(\"-offset\", String.valueOf(currLen));\n fileDiff.getParameters()\n .put(\"-length\", String.valueOf(newLen - currLen));\n metaStore.insertFileDiff(fileDiff);\n }\n }\n return String.format(\n \"UPDATE file SET length = %s, modification_time = %s WHERE path = '%s';\",\n closeEvent.getFileSize(), closeEvent.getTimestamp(), closeEvent.getPath());\n }\n\n //Todo: should update mtime? atime?\n// private String getTruncateSql(Event.TruncateEvent truncateEvent) {\n// return String.format(\n// \"UPDATE file SET length = %s, modification_time = %s WHERE path = '%s';\",\n// truncateEvent.getFileSize(), truncateEvent.getTimestamp(), truncateEvent.getPath());\n// }\n\n private List getRenameSql(Event.RenameEvent renameEvent)\n throws IOException, MetaStoreException, InterruptedException {\n String src = renameEvent.getSrcPath();\n String dest = renameEvent.getDstPath();\n List ret = new ArrayList<>();\n HdfsFileStatus status = client.getFileInfo(dest);\n FileInfo info = metaStore.getFile(src);\n // TODO: consider src or dest is ignored by SSM\n if (inBackup(src)) {\n // rename the file if the renamed file is still under the backup src dir\n // if not, insert a delete file diff\n if (inBackup(dest)) {\n FileDiff fileDiff = new FileDiff(FileDiffType.RENAME);\n fileDiff.setSrc(src);\n fileDiff.getParameters().put(\"-dest\", dest);\n metaStore.insertFileDiff(fileDiff);\n } else {\n insertDeleteDiff(src, info.isdir());\n }\n } else if (inBackup(dest)) {\n // tackle such case: rename file from outside into backup dir\n if (!info.isdir()) {\n FileDiff fileDiff = new FileDiff(FileDiffType.APPEND);\n fileDiff.setSrc(dest);\n fileDiff.getParameters().put(\"-offset\", String.valueOf(0));\n fileDiff.getParameters()\n .put(\"-length\", String.valueOf(info.getLength()));\n metaStore.insertFileDiff(fileDiff);\n } else {\n List fileInfos = metaStore.getFilesByPrefix(src.endsWith(\"/\") ? src : src + \"/\");\n for (FileInfo fileInfo : fileInfos) {\n // TODO: cover subdir with no file case\n if (fileInfo.isdir()) {\n continue;\n }\n FileDiff fileDiff = new FileDiff(FileDiffType.APPEND);\n fileDiff.setSrc(fileInfo.getPath().replaceFirst(src, dest));\n fileDiff.getParameters().put(\"-offset\", String.valueOf(0));\n fileDiff.getParameters()\n .put(\"-length\", String.valueOf(fileInfo.getLength()));\n metaStore.insertFileDiff(fileDiff);\n }\n }\n }\n if (status == null) {\n LOG.debug(\"Get rename dest status failed, {} -> {}\", src, dest);\n }\n // The dest path which the src is renamed to should be checked in file table\n // to avoid duplicated record for one same path.\n FileInfo destInfo = metaStore.getFile(dest);\n if (destInfo != null) {\n metaStore.deleteFileByPath(dest);\n }\n // src is not in file table because it is not fetched or other reason\n if (info == null) {\n if (status != null) {\n //info = HadoopUtil.convertFileStatus(status, dest);\n //metaStore.insertFile(info);\n namespaceFetcher.startFetch(dest);\n while(!namespaceFetcher.fetchFinished()) {\n LOG.info(\"Fetching the files under \" + dest);\n Thread.sleep(100);\n }\n namespaceFetcher.stop();\n }\n } else {\n // if the dest is ignored, delete src info from file table\n // TODO: tackle with file_state and small_state\n if (shouldIgnore(dest)) {\n // fuzzy matching is used to delete content under the dir\n if (info.isdir()) {\n ret.add(String.format(\"DELETE FROM file WHERE path LIKE '%s/%%';\", src));\n }\n ret.add(String.format(\"DELETE FROM file WHERE path = '%s';\", src));\n return ret;\n } else {\n ret.add(String.format(\"UPDATE file SET path = replace(path, '%s', '%s') \"\n + \"WHERE path = '%s';\", src, dest, src));\n ret.add(String.format(\"UPDATE file_state SET path = replace(path, '%s', '%s') \"\n + \"WHERE path = '%s';\", src, dest, src));\n ret.add(String.format(\"UPDATE small_file SET path = replace(path, '%s', '%s') \"\n + \"WHERE path = '%s';\", src, dest, src));\n if (info.isdir()) {\n if (metaStore.getDbType() == DBType.MYSQL) {\n ret.add(String.format(\"UPDATE file SET path = CONCAT('%s', SUBSTR(path, %d)) \"\n + \"WHERE path LIKE '%s/%%';\", dest, src.length() + 1, src));\n ret.add(String.format(\"UPDATE file_state SET path = CONCAT('%s', SUBSTR(path, %d)) \"\n + \"WHERE path LIKE '%s/%%';\", dest, src.length() + 1, src));\n ret.add(String.format(\"UPDATE small_file SET path = CONCAT('%s', SUBSTR(path, %d)) \"\n + \"WHERE path LIKE '%s/%%';\", dest, src.length() + 1, src));\n } else if (metaStore.getDbType() == DBType.SQLITE) {\n ret.add(String.format(\"UPDATE file SET path = '%s' || SUBSTR(path, %d) \"\n + \"WHERE path LIKE '%s/%%';\", dest, src.length() + 1, src));\n ret.add(String.format(\"UPDATE file_state SET path = '%s' || SUBSTR(path, %d) \"\n + \"WHERE path LIKE '%s/%%';\", dest, src.length() + 1, src));\n ret.add(String.format(\"UPDATE small_file SET path = '%s' || SUBSTR(path, %d) \"\n + \"WHERE path LIKE '%s/%%';\", dest, src.length() + 1, src));\n }\n }\n }\n }\n return ret;\n }", "answers": [" private String getMetaDataUpdateSql(Event.MetadataUpdateEvent metadataUpdateEvent) throws MetaStoreException {"], "length": 1368, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "4a847d75-ba00-4edb-a856-bfdf971eef1c", "reasoning": "The code just finished the getRenameSql method, which returns a List. The switch statement earlier calls getMetaDataUpdateSql, getAppendSql, and getUnlinkSql, so the next method to define is getMetaDataUpdateSql. Its signature should match the usage: it returns a String and takes an Event.MetadataUpdateEvent, throwing IOException and MetaStoreException. Therefore the next line is the method declaration.", "reasoning_model_answer": "private String getMetaDataUpdateSql(Event.MetadataUpdateEvent metadataEvent) throws IOException, MetaStoreException {", "assistant_with_reasoning": "\nThe code just finished the getRenameSql method, which returns a List. The switch statement earlier calls getMetaDataUpdateSql, getAppendSql, and getUnlinkSql, so the next method to define is getMetaDataUpdateSql. Its signature should match the usage: it returns a String and takes an Event.MetadataUpdateEvent, throwing IOException and MetaStoreException. Therefore the next line is the method declaration.\n\nprivate String getMetaDataUpdateSql(Event.MetadataUpdateEvent metadataEvent) throws IOException, MetaStoreException {", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.493, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 14678, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "private String getMetaDataUpdateSql(Event.MetadataUpdateEvent metadataEvent) throws IOException, MetaStoreException {", "score": 0.91, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "// Copyright 2011 The Noda Time Authors. All rights reserved.\n// Use of this source code is governed by the Apache License 2.0,\n// as found in the LICENSE.txt file.\n\nusing System.Collections.Generic;\nusing System.Linq;\nusing NodaTime.Text;\nusing NUnit.Framework;\nusing System.Globalization;\n\nnamespace NodaTime.Test.Text\n{\n public class OffsetPatternTest : PatternTestBase\n {\n /// \n /// A non-breaking space.\n /// \n public const string Nbsp = \"\\u00a0\";\n\n /// \n /// Test data that can only be used to test formatting.\n /// \n internal static readonly Data[] FormatOnlyData = {\n new Data(3, 0, 0) { Culture = Cultures.EnUs, Text = \"\", Pattern = \"%-\", },\n\n // Losing information\n new Data(5, 6, 7) { Culture = Cultures.EnUs, Text = \"05\", Pattern = \"HH\" },\n new Data(5, 6, 7) { Culture = Cultures.EnUs, Text = \"06\", Pattern = \"mm\" },\n new Data(5, 6, 7) { Culture = Cultures.EnUs, Text = \"07\", Pattern = \"ss\" },\n new Data(5, 6, 7) { Culture = Cultures.EnUs, Text = \"5\", Pattern = \"%H\" },\n new Data(5, 6, 7) { Culture = Cultures.EnUs, Text = \"6\", Pattern = \"%m\" },\n new Data(5, 6, 7) { Culture = Cultures.EnUs, Text = \"7\", Pattern = \"%s\" },\n\n new Data(Offset.MaxValue) { Culture = Cultures.EnUs, Text = \"+18\", Pattern = \"g\" },\n new Data(Offset.MaxValue) { Culture = Cultures.EnUs, Text = \"18\", Pattern = \"%H\" },\n new Data(Offset.MaxValue) { Culture = Cultures.EnUs, Text = \"0\", Pattern = \"%m\" },\n new Data(Offset.MaxValue) { Culture = Cultures.EnUs, Text = \"0\", Pattern = \"%s\" },\n new Data(Offset.MaxValue) { Culture = Cultures.EnUs, Text = \"m\", Pattern = \"\\\\m\" },\n new Data(Offset.MaxValue) { Culture = Cultures.EnUs, Text = \"m\", Pattern = \"'m'\" },\n new Data(Offset.MaxValue) { Culture = Cultures.EnUs, Text = \"mmmmmmmmmm\", Pattern = \"'mmmmmmmmmm'\" },\n new Data(Offset.MaxValue) { Culture = Cultures.EnUs, Text = \"z\", Pattern = \"'z'\" },\n new Data(Offset.MaxValue) { Culture = Cultures.EnUs, Text = \"zqw\", Pattern = \"'zqw'\" },\n new Data(3, 0, 0, true) { Culture = Cultures.EnUs, Text = \"-\", Pattern = \"%-\" },\n new Data(3, 0, 0) { Culture = Cultures.EnUs, Text = \"+\", Pattern = \"%+\" },\n new Data(3, 0, 0, true) { Culture = Cultures.EnUs, Text = \"-\", Pattern = \"%+\" },\n new Data(5, 12, 34) { Culture = Cultures.EnUs, Text = \"+05\", Pattern = \"s\" },\n new Data(5, 12, 34) { Culture = Cultures.EnUs, Text = \"+05:12\", Pattern = \"m\" },\n new Data(5, 12, 34) { Culture = Cultures.EnUs, Text = \"+05:12:34\", Pattern = \"l\" },\n };\n\n /// \n /// Test data that can only be used to test successful parsing.\n /// \n internal static readonly Data[] ParseOnlyData = {\n new Data(Offset.Zero) { Culture = Cultures.EnUs, Text = \"*\", Pattern = \"%*\" },\n new Data(Offset.Zero) { Culture = Cultures.EnUs, Text = \"zqw\", Pattern = \"'zqw'\" },\n new Data(Offset.Zero) { Culture = Cultures.EnUs, Text = \"-\", Pattern = \"%-\" },\n new Data(Offset.Zero) { Culture = Cultures.EnUs, Text = \"+\", Pattern = \"%+\" },\n new Data(Offset.Zero) { Culture = Cultures.EnUs, Text = \"-\", Pattern = \"%+\" },\n new Data(5, 0, 0) { Culture = Cultures.EnUs, Text = \"+05\", Pattern = \"s\" },\n new Data(5, 12, 0) { Culture = Cultures.EnUs, Text = \"+05:12\", Pattern = \"m\" },\n new Data(5, 12, 34) { Culture = Cultures.EnUs, Text = \"+05:12:34\", Pattern = \"l\" },\n new Data(Offset.Zero) { Pattern = \"Z+HH:mm\", Text = \"+00:00\" } // Lenient when parsing Z-prefixed patterns.\n };\n\n /// \n /// Test data for invalid patterns\n /// \n internal static readonly Data[] InvalidPatternData = {\n new Data(Offset.Zero) { Pattern = \"\", Message = TextErrorMessages.FormatStringEmpty },\n new Data(Offset.Zero) { Pattern = \"%Z\", Message = TextErrorMessages.EmptyZPrefixedOffsetPattern },\n new Data(Offset.Zero) { Pattern = \"HH:mmZ\", Message = TextErrorMessages.ZPrefixNotAtStartOfPattern },\n new Data(Offset.Zero) { Pattern = \"%%H\", Message = TextErrorMessages.PercentDoubled},\n new Data(Offset.Zero) { Pattern = \"HH:HH\", Message = TextErrorMessages.RepeatedFieldInPattern, Parameters = {'H'} },\n new Data(Offset.Zero) { Pattern = \"mm:mm\", Message = TextErrorMessages.RepeatedFieldInPattern, Parameters = {'m'} },\n new Data(Offset.Zero) { Pattern = \"ss:ss\", Message = TextErrorMessages.RepeatedFieldInPattern, Parameters = {'s'} },\n new Data(Offset.Zero) { Pattern = \"+HH:-mm\", Message = TextErrorMessages.RepeatedFieldInPattern, Parameters = {'-'} },\n new Data(Offset.Zero) { Pattern = \"-HH:+mm\", Message = TextErrorMessages.RepeatedFieldInPattern, Parameters = {'+'} },\n new Data(Offset.Zero) { Pattern = \"!\", Message = TextErrorMessages.UnknownStandardFormat, Parameters = {'!', typeof(Offset).FullName}},\n new Data(Offset.Zero) { Pattern = \"%\", Message = TextErrorMessages.UnknownStandardFormat, Parameters = { '%', typeof(Offset).FullName } },\n new Data(Offset.Zero) { Pattern = \"%%\", Message = TextErrorMessages.PercentDoubled },\n new Data(Offset.Zero) { Pattern = \"%\\\\\", Message = TextErrorMessages.EscapeAtEndOfString },\n new Data(Offset.Zero) { Pattern = \"\\\\\", Message = TextErrorMessages.UnknownStandardFormat, Parameters = { '\\\\', typeof(Offset).FullName } },\n new Data(Offset.Zero) { Pattern = \"H%\", Message = TextErrorMessages.PercentAtEndOfString },\n new Data(Offset.Zero) { Pattern = \"hh\", Message = TextErrorMessages.Hour12PatternNotSupported, Parameters = { typeof(Offset).FullName } },\n new Data(Offset.Zero) { Pattern = \"HHH\", Message = TextErrorMessages.RepeatCountExceeded, Parameters = { 'H', 2 } },\n new Data(Offset.Zero) { Pattern = \"mmm\", Message = TextErrorMessages.RepeatCountExceeded, Parameters = { 'm', 2 } },\n new Data(Offset.Zero) { Pattern = \"mmmmmmmmmmmmmmmmmmm\", Message = TextErrorMessages.RepeatCountExceeded, Parameters = { 'm', 2 } },\n new Data(Offset.Zero) { Pattern = \"'qwe\", Message = TextErrorMessages.MissingEndQuote, Parameters = { '\\'' } },\n new Data(Offset.Zero) { Pattern = \"'qwe\\\\\", Message = TextErrorMessages.EscapeAtEndOfString },\n new Data(Offset.Zero) { Pattern = \"'qwe\\\\'\", Message = TextErrorMessages.MissingEndQuote, Parameters = { '\\'' } },\n new Data(Offset.Zero) { Pattern = \"sss\", Message = TextErrorMessages.RepeatCountExceeded, Parameters = { 's', 2 } },\n };\n\n /// \n /// Tests for parsing failures (of values)\n /// \n internal static readonly Data[] ParseFailureData = {\n new Data(Offset.Zero) { Culture = Cultures.EnUs, Text = \"\", Pattern = \"g\", Message = TextErrorMessages.ValueStringEmpty },\n new Data(Offset.Zero) { Culture = Cultures.EnUs, Text = \"1\", Pattern = \"HH\", Message = TextErrorMessages.MismatchedNumber, Parameters = {\"HH\"} },\n new Data(Offset.Zero) { Culture = Cultures.EnUs, Text = \"1\", Pattern = \"mm\", Message = TextErrorMessages.MismatchedNumber, Parameters = {\"mm\"} },\n new Data(Offset.Zero) { Culture = Cultures.EnUs, Text = \"1\", Pattern = \"ss\", Message = TextErrorMessages.MismatchedNumber, Parameters = {\"ss\"} },\n new Data(Offset.Zero) { Culture = Cultures.EnUs, Text = \"12:34 \", Pattern = \"HH:mm\", Message = TextErrorMessages.ExtraValueCharacters, Parameters = {\" \"} },\n new Data(Offset.Zero) { Culture = Cultures.EnUs, Text = \"1a\", Pattern = \"H \", Message = TextErrorMessages.MismatchedCharacter, Parameters = {' '}},\n new Data(Offset.Zero) { Culture = Cultures.EnUs, Text = \"2:\", Pattern = \"%H\", Message = TextErrorMessages.ExtraValueCharacters, Parameters = {\":\"}},\n new Data(Offset.Zero) { Culture = Cultures.EnUs, Text = \"a\", Pattern = \"%.\", Message = TextErrorMessages.MismatchedCharacter, Parameters = {'.'}},\n new Data(Offset.Zero) { Culture = Cultures.EnUs, Text = \"a\", Pattern = \"%:\", Message = TextErrorMessages.TimeSeparatorMismatch},\n new Data(Offset.Zero) { Culture = Cultures.EnUs, Text = \"a\", Pattern = \"%H\", Message = TextErrorMessages.MismatchedNumber, Parameters = {\"H\"} },\n new Data(Offset.Zero) { Culture = Cultures.EnUs, Text = \"a\", Pattern = \"%m\", Message = TextErrorMessages.MismatchedNumber, Parameters = {\"m\"} },\n new Data(Offset.Zero) { Culture = Cultures.EnUs, Text = \"a\", Pattern = \"%s\", Message = TextErrorMessages.MismatchedNumber, Parameters = {\"s\"} },\n new Data(Offset.Zero) { Culture = Cultures.EnUs, Text = \"a\", Pattern = \".H\", Message = TextErrorMessages.MismatchedCharacter, Parameters = {'.'}},\n new Data(Offset.Zero) { Culture = Cultures.EnUs, Text = \"a\", Pattern = \"\\\\'\", Message = TextErrorMessages.EscapedCharacterMismatch, Parameters = {'\\''} },\n new Data(Offset.Zero) { Culture = Cultures.EnUs, Text = \"axc\", Pattern = \"'abc'\", Message = TextErrorMessages.QuotedStringMismatch},\n new Data(Offset.Zero) { Culture = Cultures.EnUs, Text = \"z\", Pattern = \"%*\", Message = TextErrorMessages.MismatchedCharacter, Parameters = {'*'} },\n new Data(Offset.Zero) { Culture = Cultures.EnUs, Text = \"24\", Pattern = \"HH\", Message = TextErrorMessages.FieldValueOutOfRange, Parameters = {24, 'H', typeof(Offset) }},\n new Data(Offset.Zero) { Culture = Cultures.EnUs, Text = \"60\", Pattern = \"mm\", Message = TextErrorMessages.FieldValueOutOfRange, Parameters = {60, 'm', typeof(Offset) }},\n new Data(Offset.Zero) { Culture = Cultures.EnUs, Text = \"60\", Pattern = \"ss\", Message = TextErrorMessages.FieldValueOutOfRange, Parameters = {60, 's', typeof(Offset) }},\n new Data(Offset.Zero) { Text = \"+12\", Pattern = \"-HH\", Message = TextErrorMessages.PositiveSignInvalid },\n };\n\n /// \n /// Common test data for both formatting and parsing. A test should be placed here unless is truly\n /// cannot be run both ways. This ensures that as many round-trip type tests are performed as possible.\n /// \n internal static readonly Data[] FormatAndParseData = {\n/*XXX*/ new Data(Offset.Zero) { Culture = Cultures.EnUs, Text = \".\", Pattern = \"%.\" }, // decimal separator\n new Data(Offset.Zero) { Culture = Cultures.EnUs, Text = \":\", Pattern = \"%:\" }, // date separator\n/*XXX*/ new Data(Offset.Zero) { Culture = Cultures.DotTimeSeparator, Text = \".\", Pattern = \"%.\" }, // decimal separator (always period)\n new Data(Offset.Zero) { Culture = Cultures.DotTimeSeparator, Text = \".\", Pattern = \"%:\" }, // date separator\n new Data(Offset.Zero) { Culture = Cultures.EnUs, Text = \"H\", Pattern = \"\\\\H\" },\n new Data(Offset.Zero) { Culture = Cultures.EnUs, Text = \"HHss\", Pattern = \"'HHss'\" },\n new Data(0, 0, 12) { Culture = Cultures.EnUs, Text = \"12\", Pattern = \"%s\" },\n new Data(0, 0, 12) { Culture = Cultures.EnUs, Text = \"12\", Pattern = \"ss\" },\n new Data(0, 0, 2) { Culture = Cultures.EnUs, Text = \"2\", Pattern = \"%s\" },\n new Data(0, 12, 0) { Culture = Cultures.EnUs, Text = \"12\", Pattern = \"%m\" },\n new Data(0, 12, 0) { Culture = Cultures.EnUs, Text = \"12\", Pattern = \"mm\" },\n new Data(0, 2, 0) { Culture = Cultures.EnUs, Text = \"2\", Pattern = \"%m\" },\n\n new Data(12, 0, 0) { Culture = Cultures.EnUs, Text = \"12\", Pattern = \"%H\" },\n new Data(12, 0, 0) { Culture = Cultures.EnUs, Text = \"12\", Pattern = \"HH\" },\n new Data(2, 0, 0) { Culture = Cultures.EnUs, Text = \"2\", Pattern = \"%H\" },\n\n // Standard patterns with punctuation...\n new Data(5, 0, 0) { Culture = Cultures.EnUs, Text = \"+05\", Pattern = \"G\" },\n new Data(5, 12, 0) { Culture = Cultures.EnUs, Text = \"+05:12\", Pattern = \"G\" },", "answers": [" new Data(5, 12, 34) { Culture = Cultures.EnUs, Text = \"+05:12:34\", Pattern = \"G\" },"], "length": 1573, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "5fa8ccce-0bb8-4a84-ac50-7a81ff24224f", "reasoning": "We are inside the static array FormatAndParseData. The last entry shown is the G pattern for hours and minutes. The next logical entry continues testing the same pattern with seconds included, matching the earlier test data. So the next line adds a Data instance with 5 hours, 12 minutes, 34 seconds, same culture, text \"+05:12:34\", and Pattern = \"G\".", "reasoning_model_answer": "new Data(5, 12, 34) { Culture = Cultures.EnUs, Text = \"+05:12:34\", Pattern = \"G\" },", "assistant_with_reasoning": "\nWe are inside the static array FormatAndParseData. The last entry shown is the G pattern for hours and minutes. The next logical entry continues testing the same pattern with seconds included, matching the earlier test data. So the next line adds a Data instance with 5 hours, 12 minutes, 34 seconds, same culture, text \"+05:12:34\", and Pattern = \"G\".\n\nnew Data(5, 12, 34) { Culture = Cultures.EnUs, Text = \"+05:12:34\", Pattern = \"G\" },", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.982, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 2, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 12326, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "new Data(5, 12, 34) { Culture = Cultures.EnUs, Text = \"+05:12:34\", Pattern = \"G\" },", "score": 0.93, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "// Openbravo POS is a point of sales application designed for touch screens.\n// Copyright (C) 2007-2009 Openbravo, S.L.\n// http://www.openbravo.com/product/pos\n//\n// This file is part of Openbravo POS.\n//\n// Openbravo POS is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// Openbravo POS is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with Openbravo POS. If not, see .\n\npackage com.openbravo.pos.customers;\n\nimport java.awt.Component;\nimport java.util.List;\n\nimport javax.swing.JOptionPane;\n\nimport com.openbravo.basic.BasicException;\nimport com.openbravo.data.gui.ComboBoxValModel;\nimport com.openbravo.data.loader.SentenceList;\nimport com.openbravo.data.user.DirtyManager;\nimport com.openbravo.data.user.EditorRecord;\nimport com.openbravo.format.Formats;\nimport com.openbravo.pos.forms.AppLocal;\nimport com.openbravo.pos.forms.AppView;\nimport com.openbravo.pos.forms.DataLogicSales;\nimport com.openbravo.pos.util.StringUtils;\n\n/**\n *\n * @author adrianromero\n */\npublic class CustomersView extends javax.swing.JPanel implements EditorRecord {\n\n private Long m_oId;\n \n private SentenceList m_sentcat;\n private ComboBoxValModel m_CategoryModel;\n \n private DataLogicCustomers dlCustomers;\n private DirtyManager m_Dirty;\n \n /** Creates new form CustomersView \n * @param dlCustomers */\n public CustomersView(AppView app, DataLogicCustomers dlCustomers, DirtyManager dirty) {\n this.dlCustomers = dlCustomers;\n DataLogicSales dlSales = (DataLogicSales) app.getBean(\"com.openbravo.pos.forms.DataLogicSales\");\n \n initComponents();\n \n m_sentcat = dlSales.getTaxCustCategoriesList();\n m_CategoryModel = new ComboBoxValModel();\n \n m_Dirty = dirty;\n m_jTaxID.getDocument().addDocumentListener(dirty);\n m_jSearchkey.getDocument().addDocumentListener(dirty);\n m_jName.getDocument().addDocumentListener(dirty);\n m_jCategory.addActionListener(dirty);\n m_jNotes.getDocument().addDocumentListener(dirty);\n txtMaxdebt.getDocument().addDocumentListener(dirty);\n m_jVisible.addActionListener(dirty);\n \n txtFirstName.getDocument().addDocumentListener(dirty);\n txtLastName.getDocument().addDocumentListener(dirty);\n txtEmail.getDocument().addDocumentListener(dirty);\n txtPhone.getDocument().addDocumentListener(dirty);\n txtPhone2.getDocument().addDocumentListener(dirty);\n txtFax.getDocument().addDocumentListener(dirty);\n \n txtAddress.getDocument().addDocumentListener(dirty);\n txtAddress2.getDocument().addDocumentListener(dirty);\n txtPostal.getDocument().addDocumentListener(dirty);\n txtCity.getDocument().addDocumentListener(dirty);\n txtRegion.getDocument().addDocumentListener(dirty);\n txtCountry.getDocument().addDocumentListener(dirty);\n \n writeValueEOF(); \n }\n \n public void activate() throws BasicException {\n \n List a = m_sentcat.list();\n a.add(0, null); // The null item\n m_CategoryModel = new ComboBoxValModel(a);\n m_jCategory.setModel(m_CategoryModel); \n }\n \n public void refresh() {\n }\n \n public void writeValueEOF() {\n m_oId = null;\n m_jTaxID.setText(null);\n m_jSearchkey.setText(null);\n m_jName.setText(null);\n m_CategoryModel.setSelectedKey(null);\n m_jNotes.setText(null);\n txtMaxdebt.setText(null);\n txtCurdebt.setText(null);\n txtCurdate.setText(null);\n m_jVisible.setSelected(false);\n jcard.setText(null);\n \n txtFirstName.setText(null);\n txtLastName.setText(null);\n txtEmail.setText(null);\n txtPhone.setText(null);\n txtPhone2.setText(null);\n txtFax.setText(null);\n \n txtAddress.setText(null);\n txtAddress2.setText(null);\n txtPostal.setText(null);\n txtCity.setText(null);\n txtRegion.setText(null);\n txtCountry.setText(null);\n \n m_jTaxID.setEnabled(false);\n m_jSearchkey.setEnabled(false);\n m_jName.setEnabled(false);\n m_jCategory.setEnabled(false);\n m_jNotes.setEnabled(false);\n txtMaxdebt.setEnabled(false);\n txtCurdebt.setEnabled(false);\n txtCurdate.setEnabled(false);\n m_jVisible.setEnabled(false);\n jcard.setEnabled(false);\n \n txtFirstName.setEnabled(false);\n txtLastName.setEnabled(false);\n txtEmail.setEnabled(false);\n txtPhone.setEnabled(false);\n txtPhone2.setEnabled(false);\n txtFax.setEnabled(false);\n \n txtAddress.setEnabled(false);\n txtAddress2.setEnabled(false);\n txtPostal.setEnabled(false);\n txtCity.setEnabled(false);\n txtRegion.setEnabled(false);\n txtCountry.setEnabled(false);\n \n jButton2.setEnabled(false);\n jButton3.setEnabled(false);\n } \n \n public void writeValueInsert() {\n m_oId = null;\n m_jTaxID.setText(null);\n m_jSearchkey.setText(null);\n m_jName.setText(null);\n m_CategoryModel.setSelectedKey(null);\n m_jNotes.setText(null);\n txtMaxdebt.setText(null);\n txtCurdebt.setText(null);\n txtCurdate.setText(null); \n m_jVisible.setSelected(true);\n jcard.setText(null);\n \n txtFirstName.setText(null);\n txtLastName.setText(null);\n txtEmail.setText(null);\n txtPhone.setText(null);\n txtPhone2.setText(null);\n txtFax.setText(null);\n \n txtAddress.setText(null);\n txtAddress2.setText(null);\n txtPostal.setText(null);\n txtCity.setText(null);\n txtRegion.setText(null);\n txtCountry.setText(null);\n \n m_jTaxID.setEnabled(true);\n m_jSearchkey.setEnabled(true);\n m_jName.setEnabled(true);\n m_jCategory.setEnabled(true);\n m_jNotes.setEnabled(true);\n txtMaxdebt.setEnabled(true);\n txtCurdebt.setEnabled(true);\n txtCurdate.setEnabled(true);\n m_jVisible.setEnabled(true);\n jcard.setEnabled(true);\n \n txtFirstName.setEnabled(true);\n txtLastName.setEnabled(true);\n txtEmail.setEnabled(true);\n txtPhone.setEnabled(true);\n txtPhone2.setEnabled(true);\n txtFax.setEnabled(true);\n \n txtAddress.setEnabled(true);\n txtAddress2.setEnabled(true);\n txtPostal.setEnabled(true);\n txtCity.setEnabled(true);\n txtRegion.setEnabled(true);\n txtCountry.setEnabled(true);\n \n jButton2.setEnabled(true);\n jButton3.setEnabled(true);\n }\n\n public void writeValueDelete(Object value) {\n Object[] customer = (Object[]) value;\n m_oId = (Long) customer[0];\n m_jTaxID.setText((String) customer[1]);\n m_jSearchkey.setText((String) customer[2]);\n m_jName.setText((String) customer[3]);\n m_jNotes.setText((String) customer[4]);\n m_jVisible.setSelected(((Boolean) customer[5]).booleanValue());\n jcard.setText((String) customer[6]);\n txtMaxdebt.setText(Formats.CURRENCY.formatValue(customer[7]));\n txtCurdate.setText(Formats.DATE.formatValue(customer[8])); \n txtCurdebt.setText(Formats.CURRENCY.formatValue(customer[9])); \n \n txtFirstName.setText(Formats.STRING.formatValue(customer[10]));\n txtLastName.setText(Formats.STRING.formatValue(customer[11]));\n txtEmail.setText(Formats.STRING.formatValue(customer[12]));\n txtPhone.setText(Formats.STRING.formatValue(customer[13]));\n txtPhone2.setText(Formats.STRING.formatValue(customer[14]));\n txtFax.setText(Formats.STRING.formatValue(customer[15]));\n \n txtAddress.setText(Formats.STRING.formatValue(customer[16]));\n txtAddress2.setText(Formats.STRING.formatValue(customer[17]));\n txtPostal.setText(Formats.STRING.formatValue(customer[18]));\n txtCity.setText(Formats.STRING.formatValue(customer[19]));\n txtRegion.setText(Formats.STRING.formatValue(customer[20]));\n txtCountry.setText(Formats.STRING.formatValue(customer[21])); \n \n m_CategoryModel.setSelectedKey(customer[22]);\n \n m_jTaxID.setEnabled(false);\n m_jSearchkey.setEnabled(false);\n m_jName.setEnabled(false);\n m_jNotes.setEnabled(false);\n txtMaxdebt.setEnabled(false);\n txtCurdebt.setEnabled(false);\n txtCurdate.setEnabled(false);\n m_jVisible.setEnabled(false);\n jcard.setEnabled(false); \n \n txtFirstName.setEnabled(false);\n txtLastName.setEnabled(false);\n txtEmail.setEnabled(false);\n txtPhone.setEnabled(false);\n txtPhone2.setEnabled(false);\n txtFax.setEnabled(false);\n \n txtAddress.setEnabled(false);\n txtAddress2.setEnabled(false);\n txtPostal.setEnabled(false);\n txtCity.setEnabled(false);\n txtRegion.setEnabled(false);\n txtCountry.setEnabled(false);\n \n m_jCategory.setEnabled(false);\n \n jButton2.setEnabled(false);\n jButton3.setEnabled(false);\n }\n\n public void writeValueEdit(Object value) {\n Object[] customer = (Object[]) value;\n m_oId = (Long) customer[0];\n m_jTaxID.setText((String) customer[1]);\n m_jSearchkey.setText((String) customer[2]);\n m_jName.setText((String) customer[3]);\n m_jNotes.setText((String) customer[4]);\n m_jVisible.setSelected(((Boolean) customer[5]).booleanValue());\n jcard.setText((String) customer[6]);\n txtMaxdebt.setText(Formats.CURRENCY.formatValue(customer[7]));\n txtCurdate.setText(Formats.DATE.formatValue(customer[8])); \n txtCurdebt.setText(Formats.CURRENCY.formatValue(customer[9])); \n \n txtFirstName.setText(Formats.STRING.formatValue(customer[10]));\n txtLastName.setText(Formats.STRING.formatValue(customer[11]));\n txtEmail.setText(Formats.STRING.formatValue(customer[12]));\n txtPhone.setText(Formats.STRING.formatValue(customer[13]));\n txtPhone2.setText(Formats.STRING.formatValue(customer[14]));\n txtFax.setText(Formats.STRING.formatValue(customer[15]));\n \n txtAddress.setText(Formats.STRING.formatValue(customer[16]));\n txtAddress2.setText(Formats.STRING.formatValue(customer[17]));\n txtPostal.setText(Formats.STRING.formatValue(customer[18]));\n txtCity.setText(Formats.STRING.formatValue(customer[19]));\n txtRegion.setText(Formats.STRING.formatValue(customer[20]));\n txtCountry.setText(Formats.STRING.formatValue(customer[21])); \n \n m_CategoryModel.setSelectedKey(customer[22]);\n \n m_jTaxID.setEnabled(true);\n m_jSearchkey.setEnabled(true);\n m_jName.setEnabled(true);\n m_jNotes.setEnabled(true);\n txtMaxdebt.setEnabled(true);\n txtCurdebt.setEnabled(true);\n txtCurdate.setEnabled(true);\n m_jVisible.setEnabled(true);\n jcard.setEnabled(true);\n \n txtFirstName.setEnabled(true);\n txtLastName.setEnabled(true);\n txtEmail.setEnabled(true);\n txtPhone.setEnabled(true);\n txtPhone2.setEnabled(true);\n txtFax.setEnabled(true);\n \n txtAddress.setEnabled(true);\n txtAddress2.setEnabled(true);\n txtPostal.setEnabled(true);\n txtCity.setEnabled(true);\n txtRegion.setEnabled(true);\n txtCountry.setEnabled(true);\n \n m_jCategory.setEnabled(true);\n \n jButton2.setEnabled(true);\n jButton3.setEnabled(true);\n }\n \n public Object createValue() throws BasicException {\n Object[] customer = new Object[23];\n customer[0] = m_oId == null ? dlCustomers.getNextId(CustomerInfo.class) : m_oId;\n customer[1] = m_jTaxID.getText();\n customer[2] = m_jSearchkey.getText();\n customer[3] = m_jName.getText();\n customer[4] = m_jNotes.getText();\n customer[5] = Boolean.valueOf(m_jVisible.isSelected());\n customer[6] = Formats.STRING.parseValue(jcard.getText()); // Format to manage NULL values\n customer[7] = Formats.CURRENCY.parseValue(txtMaxdebt.getText(), new Double(0.0));\n customer[8] = Formats.TIMESTAMP.parseValue(txtCurdate.getText()); // not saved\n customer[9] = Formats.CURRENCY.parseValue(txtCurdebt.getText()); // not saved\n \n customer[10] = Formats.STRING.parseValue(txtFirstName.getText());\n customer[11] = Formats.STRING.parseValue(txtLastName.getText());\n customer[12] = Formats.STRING.parseValue(txtEmail.getText());\n customer[13] = Formats.STRING.parseValue(txtPhone.getText());\n customer[14] = Formats.STRING.parseValue(txtPhone2.getText());\n customer[15] = Formats.STRING.parseValue(txtFax.getText());\n \n customer[16] = Formats.STRING.parseValue(txtAddress.getText());\n customer[17] = Formats.STRING.parseValue(txtAddress2.getText());\n customer[18] = Formats.STRING.parseValue(txtPostal.getText());\n customer[19] = Formats.STRING.parseValue(txtCity.getText());\n customer[20] = Formats.STRING.parseValue(txtRegion.getText());\n customer[21] = Formats.STRING.parseValue(txtCountry.getText()); \n \n customer[22] = m_CategoryModel.getSelectedKey();\n \n return customer;\n } \n \n public Component getComponent() {\n return this;\n } \n /** This method is called from within the constructor to\n * initialize the form.\n * WARNING: Do NOT modify this code. The content of this method is\n * always regenerated by the Form Editor.\n */\n // //GEN-BEGIN:initComponents\n private void initComponents() {\n\n jLabel7 = new javax.swing.JLabel();\n m_jTaxID = new javax.swing.JTextField();\n jLabel8 = new javax.swing.JLabel();\n m_jSearchkey = new javax.swing.JTextField();\n jLabel3 = new javax.swing.JLabel();\n m_jName = new javax.swing.JTextField();\n jLabel4 = new javax.swing.JLabel();\n m_jVisible = new javax.swing.JCheckBox();\n jLabel5 = new javax.swing.JLabel();\n jcard = new javax.swing.JTextField();\n jLabel9 = new javax.swing.JLabel();\n m_jCategory = new javax.swing.JComboBox();\n jButton2 = new javax.swing.JButton();\n jButton3 = new javax.swing.JButton();\n jLabel1 = new javax.swing.JLabel();\n txtMaxdebt = new javax.swing.JTextField();\n jTabbedPane1 = new javax.swing.JTabbedPane();\n jPanel1 = new javax.swing.JPanel();\n jLabel14 = new javax.swing.JLabel();\n txtFax = new javax.swing.JTextField();\n jLabel15 = new javax.swing.JLabel();\n txtLastName = new javax.swing.JTextField();\n jLabel16 = new javax.swing.JLabel();\n txtEmail = new javax.swing.JTextField();\n jLabel17 = new javax.swing.JLabel();\n txtPhone = new javax.swing.JTextField();\n jLabel18 = new javax.swing.JLabel();\n txtPhone2 = new javax.swing.JTextField();\n jLabel19 = new javax.swing.JLabel();\n txtFirstName = new javax.swing.JTextField();\n jPanel2 = new javax.swing.JPanel();\n jLabel13 = new javax.swing.JLabel();\n txtAddress = new javax.swing.JTextField();\n jLabel20 = new javax.swing.JLabel();\n txtCountry = new javax.swing.JTextField();\n jLabel21 = new javax.swing.JLabel();\n txtAddress2 = new javax.swing.JTextField();\n jLabel22 = new javax.swing.JLabel();\n txtPostal = new javax.swing.JTextField();\n jLabel23 = new javax.swing.JLabel();\n txtCity = new javax.swing.JTextField();\n jLabel24 = new javax.swing.JLabel();\n txtRegion = new javax.swing.JTextField();\n jPanel3 = new javax.swing.JPanel();\n jScrollPane1 = new javax.swing.JScrollPane();\n m_jNotes = new javax.swing.JTextArea();\n jLabel2 = new javax.swing.JLabel();\n txtCurdebt = new javax.swing.JTextField();\n jLabel6 = new javax.swing.JLabel();\n txtCurdate = new javax.swing.JTextField();\n\n jLabel7.setText(AppLocal.getIntString(\"label.taxid\")); // NOI18N\n\n jLabel8.setText(AppLocal.getIntString(\"label.searchkey\")); // NOI18N\n\n jLabel3.setText(AppLocal.getIntString(\"label.name\")); // NOI18N\n\n jLabel4.setText(AppLocal.getIntString(\"label.visible\")); // NOI18N\n\n jLabel5.setText(AppLocal.getIntString(\"label.card\")); // NOI18N\n\n jcard.setEditable(false);\n\n jLabel9.setText(AppLocal.getIntString(\"label.custtaxcategory\")); // NOI18N\n\n jButton2.setIcon(new javax.swing.ImageIcon(getClass().getResource(\"/com/openbravo/images/color_line16.png\"))); // NOI18N\n jButton2.addActionListener(new java.awt.event.ActionListener() {\n public void actionPerformed(java.awt.event.ActionEvent evt) {\n jButton2ActionPerformed(evt);\n }\n });\n\n jButton3.setIcon(new javax.swing.ImageIcon(getClass().getResource(\"/com/openbravo/images/fileclose.png\"))); // NOI18N\n jButton3.addActionListener(new java.awt.event.ActionListener() {\n public void actionPerformed(java.awt.event.ActionEvent evt) {\n jButton3ActionPerformed(evt);\n }\n });\n\n jLabel1.setText(AppLocal.getIntString(\"label.maxdebt\")); // NOI18N\n\n txtMaxdebt.setHorizontalAlignment(javax.swing.JTextField.RIGHT);\n\n jLabel14.setText(AppLocal.getIntString(\"label.fax\")); // NOI18N\n\n jLabel15.setText(AppLocal.getIntString(\"label.lastname\")); // NOI18N\n\n jLabel16.setText(AppLocal.getIntString(\"label.email\")); // NOI18N\n\n jLabel17.setText(AppLocal.getIntString(\"label.phone\")); // NOI18N\n\n jLabel18.setText(AppLocal.getIntString(\"label.phone2\")); // NOI18N\n\n jLabel19.setText(AppLocal.getIntString(\"label.firstname\")); // NOI18N\n\n javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);\n jPanel1.setLayout(jPanel1Layout);\n jPanel1Layout.setHorizontalGroup(\n jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)\n .addGroup(jPanel1Layout.createSequentialGroup()\n .addContainerGap()\n .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)\n .addGroup(jPanel1Layout.createSequentialGroup()\n .addComponent(jLabel19, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE)\n .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)\n .addComponent(txtFirstName, javax.swing.GroupLayout.PREFERRED_SIZE, 270, javax.swing.GroupLayout.PREFERRED_SIZE))\n .addGroup(jPanel1Layout.createSequentialGroup()\n .addComponent(jLabel15, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE)\n .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)\n .addComponent(txtLastName, javax.swing.GroupLayout.PREFERRED_SIZE, 270, javax.swing.GroupLayout.PREFERRED_SIZE))\n .addGroup(jPanel1Layout.createSequentialGroup()\n .addComponent(jLabel16, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE)\n .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)\n .addComponent(txtEmail, javax.swing.GroupLayout.PREFERRED_SIZE, 270, javax.swing.GroupLayout.PREFERRED_SIZE))\n .addGroup(jPanel1Layout.createSequentialGroup()\n .addComponent(jLabel17, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE)\n .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)\n .addComponent(txtPhone, javax.swing.GroupLayout.PREFERRED_SIZE, 270, javax.swing.GroupLayout.PREFERRED_SIZE))\n .addGroup(jPanel1Layout.createSequentialGroup()\n .addComponent(jLabel18, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE)\n .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)\n .addComponent(txtPhone2, javax.swing.GroupLayout.PREFERRED_SIZE, 270, javax.swing.GroupLayout.PREFERRED_SIZE))\n .addGroup(jPanel1Layout.createSequentialGroup()\n .addComponent(jLabel14, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE)\n .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)\n .addComponent(txtFax, javax.swing.GroupLayout.PREFERRED_SIZE, 270, javax.swing.GroupLayout.PREFERRED_SIZE)))\n .addContainerGap(249, Short.MAX_VALUE))\n );\n jPanel1Layout.setVerticalGroup(\n jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)\n .addGroup(jPanel1Layout.createSequentialGroup()\n .addContainerGap()\n .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)\n .addComponent(jLabel19)\n .addComponent(txtFirstName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))\n .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)\n .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)\n .addComponent(jLabel15)\n .addComponent(txtLastName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))\n .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)\n .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)\n .addComponent(jLabel16)\n .addComponent(txtEmail, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))\n .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)\n .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)\n .addComponent(jLabel17)\n .addComponent(txtPhone, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))\n .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)\n .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)\n .addComponent(jLabel18)\n .addComponent(txtPhone2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))\n .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)\n .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)\n .addComponent(jLabel14)\n .addComponent(txtFax, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))\n .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))\n );\n\n jTabbedPane1.addTab(AppLocal.getIntString(\"label.contact\"), jPanel1); // NOI18N\n\n jLabel13.setText(AppLocal.getIntString(\"label.address\")); // NOI18N\n\n jLabel20.setText(AppLocal.getIntString(\"label.country\")); // NOI18N\n\n jLabel21.setText(AppLocal.getIntString(\"label.address2\")); // NOI18N\n\n jLabel22.setText(AppLocal.getIntString(\"label.postal\")); // NOI18N\n\n jLabel23.setText(AppLocal.getIntString(\"label.city\")); // NOI18N\n\n jLabel24.setText(AppLocal.getIntString(\"label.region\")); // NOI18N\n\n javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);\n jPanel2.setLayout(jPanel2Layout);\n jPanel2Layout.setHorizontalGroup(\n jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)\n .addGroup(jPanel2Layout.createSequentialGroup()\n .addContainerGap()\n .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)\n .addGroup(jPanel2Layout.createSequentialGroup()\n .addComponent(jLabel13, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE)\n .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)\n .addComponent(txtAddress, javax.swing.GroupLayout.PREFERRED_SIZE, 270, javax.swing.GroupLayout.PREFERRED_SIZE))\n .addGroup(jPanel2Layout.createSequentialGroup()\n .addComponent(jLabel21, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE)\n .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)\n .addComponent(txtAddress2, javax.swing.GroupLayout.PREFERRED_SIZE, 270, javax.swing.GroupLayout.PREFERRED_SIZE))\n .addGroup(jPanel2Layout.createSequentialGroup()\n .addComponent(jLabel22, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE)\n .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)\n .addComponent(txtPostal, javax.swing.GroupLayout.PREFERRED_SIZE, 270, javax.swing.GroupLayout.PREFERRED_SIZE))\n .addGroup(jPanel2Layout.createSequentialGroup()\n .addComponent(jLabel23, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE)\n .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)\n .addComponent(txtCity, javax.swing.GroupLayout.PREFERRED_SIZE, 270, javax.swing.GroupLayout.PREFERRED_SIZE))\n .addGroup(jPanel2Layout.createSequentialGroup()\n .addComponent(jLabel24, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE)\n .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)\n .addComponent(txtRegion, javax.swing.GroupLayout.PREFERRED_SIZE, 270, javax.swing.GroupLayout.PREFERRED_SIZE))\n .addGroup(jPanel2Layout.createSequentialGroup()\n .addComponent(jLabel20, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE)\n .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)\n .addComponent(txtCountry, javax.swing.GroupLayout.PREFERRED_SIZE, 270, javax.swing.GroupLayout.PREFERRED_SIZE)))\n .addContainerGap(249, Short.MAX_VALUE))\n );\n jPanel2Layout.setVerticalGroup(\n jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)\n .addGroup(jPanel2Layout.createSequentialGroup()\n .addContainerGap()\n .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)\n .addComponent(jLabel13)\n .addComponent(txtAddress, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))\n .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)\n .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)\n .addComponent(jLabel21)\n .addComponent(txtAddress2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))\n .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)\n .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)\n .addComponent(jLabel22)\n .addComponent(txtPostal, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))\n .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)\n .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)\n .addComponent(jLabel23)\n .addComponent(txtCity, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))\n .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)\n .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)\n .addComponent(jLabel24)\n .addComponent(txtRegion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))\n .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)\n .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)\n .addComponent(jLabel20)\n .addComponent(txtCountry, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))\n .addGap(267, 267, 267))\n );\n\n jTabbedPane1.addTab(AppLocal.getIntString(\"label.location\"), jPanel2); // NOI18N\n\n jScrollPane1.setViewportView(m_jNotes);\n\n javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);\n jPanel3.setLayout(jPanel3Layout);\n jPanel3Layout.setHorizontalGroup(\n jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)\n .addGroup(jPanel3Layout.createSequentialGroup()\n .addContainerGap()\n .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 659, Short.MAX_VALUE)\n .addContainerGap())\n );\n jPanel3Layout.setVerticalGroup(\n jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)\n .addGroup(jPanel3Layout.createSequentialGroup()\n .addContainerGap()\n .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 144, Short.MAX_VALUE)\n .addContainerGap())\n );\n\n jTabbedPane1.addTab(AppLocal.getIntString(\"label.notes\"), jPanel3); // NOI18N\n\n jLabel2.setText(AppLocal.getIntString(\"label.curdebt\")); // NOI18N\n\n txtCurdebt.setEditable(false);\n txtCurdebt.setHorizontalAlignment(javax.swing.JTextField.RIGHT);\n\n jLabel6.setText(AppLocal.getIntString(\"label.curdate\")); // NOI18N\n\n txtCurdate.setEditable(false);\n txtCurdate.setHorizontalAlignment(javax.swing.JTextField.CENTER);\n\n javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);\n this.setLayout(layout);\n layout.setHorizontalGroup(\n layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)\n .addGroup(layout.createSequentialGroup()\n .addContainerGap()\n .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)\n .addComponent(jTabbedPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 688, Short.MAX_VALUE)\n .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)\n .addGroup(layout.createSequentialGroup()\n .addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 180, javax.swing.GroupLayout.PREFERRED_SIZE)\n .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)\n .addComponent(m_jTaxID, javax.swing.GroupLayout.PREFERRED_SIZE, 270, javax.swing.GroupLayout.PREFERRED_SIZE))\n .addGroup(layout.createSequentialGroup()\n .addComponent(jLabel8, javax.swing.GroupLayout.PREFERRED_SIZE, 180, javax.swing.GroupLayout.PREFERRED_SIZE)\n .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)\n .addComponent(m_jSearchkey, javax.swing.GroupLayout.PREFERRED_SIZE, 270, javax.swing.GroupLayout.PREFERRED_SIZE))\n .addGroup(layout.createSequentialGroup()\n .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 180, javax.swing.GroupLayout.PREFERRED_SIZE)\n .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)\n .addComponent(m_jName, javax.swing.GroupLayout.PREFERRED_SIZE, 270, javax.swing.GroupLayout.PREFERRED_SIZE))\n .addGroup(layout.createSequentialGroup()\n .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 180, javax.swing.GroupLayout.PREFERRED_SIZE)\n .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)\n .addComponent(m_jVisible, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE)\n .addGap(246, 246, 246))\n .addGroup(layout.createSequentialGroup()\n .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)\n .addGroup(layout.createSequentialGroup()\n .addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 180, javax.swing.GroupLayout.PREFERRED_SIZE)\n .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)\n .addComponent(jcard, javax.swing.GroupLayout.PREFERRED_SIZE, 270, javax.swing.GroupLayout.PREFERRED_SIZE))\n .addGroup(layout.createSequentialGroup()\n .addComponent(jLabel9, javax.swing.GroupLayout.PREFERRED_SIZE, 180, javax.swing.GroupLayout.PREFERRED_SIZE)\n .addGap(12, 12, 12)\n .addComponent(m_jCategory, javax.swing.GroupLayout.PREFERRED_SIZE, 270, javax.swing.GroupLayout.PREFERRED_SIZE)))\n .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)\n .addComponent(jButton2)\n .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)\n .addComponent(jButton3)))\n .addGroup(layout.createSequentialGroup()\n .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 180, javax.swing.GroupLayout.PREFERRED_SIZE)\n .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)\n .addComponent(txtMaxdebt, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE))\n .addGroup(layout.createSequentialGroup()\n .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 180, javax.swing.GroupLayout.PREFERRED_SIZE)\n .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)", "answers": [" .addComponent(txtCurdebt, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE))"], "length": 1373, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "10ca4744-d96e-4729-97a6-93ded18899b7", "reasoning": "The layout code is defining a horizontal group for the label jLabel2 (current debt) and then adds a gap. The next logical component is the txtCurdebt field, matching the pattern used earlier for jLabel1 and txtMaxdebt. Therefore the next line adds txtCurdebt with a preferred size.", "reasoning_model_answer": ".addComponent(txtCurdebt, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE)", "assistant_with_reasoning": "\nThe layout code is defining a horizontal group for the label jLabel2 (current debt) and then adds a gap. The next logical component is the txtCurdebt field, matching the pattern used earlier for jLabel1 and txtMaxdebt. Therefore the next line adds txtCurdebt with a preferred size.\n\n.addComponent(txtCurdebt, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE)", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.048, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 36679, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": ".addComponent(txtCurdebt, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE)", "score": 0.9, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/*\n * Copyright 2000-2015 JetBrains s.r.o.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.intellij.diff.comparison;\n\nimport com.intellij.diff.comparison.iterables.DiffIterable;\nimport com.intellij.diff.comparison.iterables.DiffIterableUtil;\nimport com.intellij.diff.comparison.iterables.FairDiffIterable;\nimport com.intellij.diff.fragments.*;\nimport com.intellij.diff.util.DiffUtil;\nimport com.intellij.diff.util.IntPair;\nimport com.intellij.diff.util.MergeRange;\nimport com.intellij.diff.util.Range;\nimport com.intellij.openapi.diagnostic.Logger;\nimport com.intellij.openapi.progress.ProgressIndicator;\nimport com.intellij.openapi.util.TextRange;\nimport com.intellij.openapi.util.text.StringUtil;\nimport com.intellij.util.Consumer;\nimport com.intellij.util.containers.ContainerUtil;\nimport com.intellij.util.diff.FilesTooBigForDiffException;\nimport com.intellij.util.text.CharSequenceSubSequence;\nimport org.jetbrains.annotations.NotNull;\nimport org.jetbrains.annotations.Nullable;\n\nimport java.util.ArrayList;\nimport java.util.BitSet;\nimport java.util.Collections;\nimport java.util.List;\n\nimport static com.intellij.diff.comparison.iterables.DiffIterableUtil.fair;\nimport static java.util.Collections.singletonList;\n\npublic class ComparisonManagerImpl extends ComparisonManager {\n private static final Logger LOG = Logger.getInstance(ComparisonManagerImpl.class);\n\n @NotNull\n public static ComparisonManagerImpl getInstanceImpl() {\n return (ComparisonManagerImpl)getInstance();\n }\n\n @NotNull\n @Override\n public List compareLines(@NotNull CharSequence text1,\n @NotNull CharSequence text2,\n @NotNull ComparisonPolicy policy,\n @NotNull ProgressIndicator indicator) throws DiffTooBigException {\n List lines1 = getLines(text1);\n List lines2 = getLines(text2);\n\n List lineTexts1 = ContainerUtil.map(lines1, Line::getContent);\n List lineTexts2 = ContainerUtil.map(lines2, Line::getContent);\n\n FairDiffIterable iterable = ByLine.compare(lineTexts1, lineTexts2, policy, indicator);\n return convertIntoLineFragments(lines1, lines2, iterable);\n }\n\n @NotNull\n @Override\n public List compareLines(@NotNull CharSequence text1,\n @NotNull CharSequence text2,\n @NotNull CharSequence text3,\n @NotNull ComparisonPolicy policy,\n @NotNull ProgressIndicator indicator) throws DiffTooBigException {\n List lines1 = getLines(text1);\n List lines2 = getLines(text2);\n List lines3 = getLines(text3);\n\n List lineTexts1 = ContainerUtil.map(lines1, Line::getContent);\n List lineTexts2 = ContainerUtil.map(lines2, Line::getContent);\n List lineTexts3 = ContainerUtil.map(lines3, Line::getContent);\n\n List ranges = ByLine.compare(lineTexts1, lineTexts2, lineTexts3, policy, indicator);\n return convertIntoMergeLineFragments(ranges);\n }\n\n @NotNull\n @Override\n public List compareLinesInner(@NotNull CharSequence text1,\n @NotNull CharSequence text2,\n @NotNull ComparisonPolicy policy,\n @NotNull ProgressIndicator indicator) throws DiffTooBigException {\n List lineFragments = compareLines(text1, text2, policy, indicator);\n return createInnerFragments(lineFragments, text1, text2, policy, indicator);\n }\n\n private static List createInnerFragments(@NotNull List lineFragments,\n @NotNull CharSequence text1,\n @NotNull CharSequence text2,\n @NotNull ComparisonPolicy policy,\n @NotNull ProgressIndicator indicator) {\n List result = new ArrayList<>(lineFragments.size());\n\n int tooBigChunksCount = 0;\n for (LineFragment fragment : lineFragments) {\n assert fragment.getInnerFragments() == null;\n\n try {\n // Do not try to build fine blocks after few fails\n boolean tryComputeDifferences = tooBigChunksCount < FilesTooBigForDiffException.MAX_BAD_LINES;\n result.addAll(createInnerFragments(fragment, text1, text2, policy, indicator, tryComputeDifferences));\n }\n catch (DiffTooBigException e) {\n result.add(fragment);\n tooBigChunksCount++;\n }\n }\n\n return result;\n }\n\n @NotNull\n private static List createInnerFragments(@NotNull LineFragment fragment,\n @NotNull CharSequence text1,\n @NotNull CharSequence text2,\n @NotNull ComparisonPolicy policy,\n @NotNull ProgressIndicator indicator,\n boolean tryComputeDifferences) throws DiffTooBigException {\n CharSequence subSequence1 = text1.subSequence(fragment.getStartOffset1(), fragment.getEndOffset1());\n CharSequence subSequence2 = text2.subSequence(fragment.getStartOffset2(), fragment.getEndOffset2());\n\n if (fragment.getStartLine1() == fragment.getEndLine1() ||\n fragment.getStartLine2() == fragment.getEndLine2()) { // Insertion / Deletion\n if (ComparisonUtil.isEquals(subSequence1, subSequence2, policy)) {\n return singletonList(new LineFragmentImpl(fragment, Collections.emptyList()));\n }\n else {\n return singletonList(fragment);\n }\n }\n\n if (!tryComputeDifferences) return singletonList(fragment);\n\n List lineBlocks = ByWord.compareAndSplit(subSequence1, subSequence2, policy, indicator);\n assert lineBlocks.size() != 0;\n\n int startOffset1 = fragment.getStartOffset1();\n int startOffset2 = fragment.getStartOffset2();\n\n int currentStartLine1 = fragment.getStartLine1();\n int currentStartLine2 = fragment.getStartLine2();\n\n List chunks = new ArrayList<>();\n for (int i = 0; i < lineBlocks.size(); i++) {\n ByWord.LineBlock block = lineBlocks.get(i);\n Range offsets = block.offsets;\n\n // special case for last line to void problem with empty last line\n int currentEndLine1 = i != lineBlocks.size() - 1 ? currentStartLine1 + block.newlines1 : fragment.getEndLine1();\n int currentEndLine2 = i != lineBlocks.size() - 1 ? currentStartLine2 + block.newlines2 : fragment.getEndLine2();\n\n chunks.add(new LineFragmentImpl(currentStartLine1, currentEndLine1, currentStartLine2, currentEndLine2,\n offsets.start1 + startOffset1, offsets.end1 + startOffset1,\n offsets.start2 + startOffset2, offsets.end2 + startOffset2,\n block.fragments));\n\n currentStartLine1 = currentEndLine1;\n currentStartLine2 = currentEndLine2;\n }\n return chunks;\n }\n\n @NotNull\n @Override\n @Deprecated\n public List compareLinesInner(@NotNull CharSequence text1,\n @NotNull CharSequence text2,\n @NotNull List lineFragments,\n @NotNull ComparisonPolicy policy,\n @NotNull ProgressIndicator indicator) throws DiffTooBigException {\n return compareLinesInner(text1, text2, policy, indicator);\n }\n\n @NotNull\n @Override\n public List compareWords(@NotNull CharSequence text1,\n @NotNull CharSequence text2,\n @NotNull ComparisonPolicy policy,\n @NotNull ProgressIndicator indicator) throws DiffTooBigException {\n return ByWord.compare(text1, text2, policy, indicator);\n }\n\n @NotNull\n @Override\n public List compareChars(@NotNull CharSequence text1,\n @NotNull CharSequence text2,\n @NotNull ComparisonPolicy policy,\n @NotNull ProgressIndicator indicator) throws DiffTooBigException {\n if (policy == ComparisonPolicy.IGNORE_WHITESPACES) {\n return convertIntoDiffFragments(ByChar.compareIgnoreWhitespaces(text1, text2, indicator));\n }\n if (policy == ComparisonPolicy.DEFAULT) {\n return convertIntoDiffFragments(ByChar.compareTwoStep(text1, text2, indicator));\n }\n LOG.warn(policy.toString() + \" is not supported by ByChar comparison\");\n return convertIntoDiffFragments(ByChar.compareTwoStep(text1, text2, indicator));\n }\n\n @Override\n public boolean isEquals(@NotNull CharSequence text1, @NotNull CharSequence text2, @NotNull ComparisonPolicy policy) {\n return ComparisonUtil.isEquals(text1, text2, policy);\n }\n\n //\n // Fragments\n //\n\n @NotNull\n public static List convertIntoDiffFragments(@NotNull DiffIterable changes) {\n final List fragments = new ArrayList<>();\n for (Range ch : changes.iterateChanges()) {\n fragments.add(new DiffFragmentImpl(ch.start1, ch.end1, ch.start2, ch.end2));\n }\n return fragments;\n }\n\n @NotNull\n public static List convertIntoLineFragments(@NotNull List lines1,\n @NotNull List lines2,\n @NotNull FairDiffIterable changes) {\n List fragments = new ArrayList<>();\n for (Range ch : changes.iterateChanges()) {\n IntPair offsets1 = getOffsets(lines1, ch.start1, ch.end1);\n IntPair offsets2 = getOffsets(lines2, ch.start2, ch.end2);\n\n fragments.add(new LineFragmentImpl(ch.start1, ch.end1, ch.start2, ch.end2,\n offsets1.val1, offsets1.val2, offsets2.val1, offsets2.val2));\n }\n return fragments;\n }\n\n @NotNull\n private static IntPair getOffsets(@NotNull List lines, int startIndex, int endIndex) {\n if (startIndex == endIndex) {\n int offset;\n if (startIndex < lines.size()) {\n offset = lines.get(startIndex).getOffset1();\n }\n else {\n offset = lines.get(lines.size() - 1).getOffset2();\n }\n return new IntPair(offset, offset);\n }\n else {\n int offset1 = lines.get(startIndex).getOffset1();\n int offset2 = lines.get(endIndex - 1).getOffset2();\n return new IntPair(offset1, offset2);\n }\n }\n\n @NotNull\n public static List convertIntoMergeLineFragments(@NotNull List conflicts) {\n return ContainerUtil.map(conflicts, ch -> new MergeLineFragmentImpl(ch.start1, ch.end1, ch.start2, ch.end2, ch.start3, ch.end3));\n }\n\n @NotNull\n public static List convertIntoMergeWordFragments(@NotNull List conflicts) {\n return ContainerUtil.map(conflicts, ch -> new MergeWordFragmentImpl(ch.start1, ch.end1, ch.start2, ch.end2, ch.start3, ch.end3));\n }\n\n //\n // Post process line fragments\n //\n\n @NotNull\n @Override\n public List squash(@NotNull List oldFragments) {\n if (oldFragments.isEmpty()) return oldFragments;\n\n final List newFragments = new ArrayList<>();\n processAdjoining(oldFragments, fragments -> newFragments.add(doSquash(fragments)));\n return newFragments;\n }\n\n @NotNull\n @Override\n public List processBlocks(@NotNull List oldFragments,\n @NotNull final CharSequence text1, @NotNull final CharSequence text2,\n @NotNull final ComparisonPolicy policy,\n final boolean squash, final boolean trim) {\n if (!squash && !trim) return oldFragments;\n if (oldFragments.isEmpty()) return oldFragments;\n\n final List newFragments = new ArrayList<>();\n processAdjoining(oldFragments, fragments -> newFragments.addAll(processAdjoining(fragments, text1, text2, policy, squash, trim)));\n return newFragments;\n }\n\n private static void processAdjoining(@NotNull List oldFragments,\n @NotNull Consumer> consumer) {\n int startIndex = 0;\n for (int i = 1; i < oldFragments.size(); i++) {\n if (!isAdjoining(oldFragments.get(i - 1), oldFragments.get(i))) {\n consumer.consume(oldFragments.subList(startIndex, i));\n startIndex = i;\n }\n }\n if (startIndex < oldFragments.size()) {\n consumer.consume(oldFragments.subList(startIndex, oldFragments.size()));\n }\n }\n\n @NotNull\n private static List processAdjoining(@NotNull List fragments,\n @NotNull CharSequence text1, @NotNull CharSequence text2,\n @NotNull ComparisonPolicy policy, boolean squash, boolean trim) {\n int start = 0;\n int end = fragments.size();\n\n // TODO: trim empty leading/trailing lines\n if (trim && policy == ComparisonPolicy.IGNORE_WHITESPACES) {\n while (start < end) {\n LineFragment fragment = fragments.get(start);\n CharSequenceSubSequence sequence1 = new CharSequenceSubSequence(text1, fragment.getStartOffset1(), fragment.getEndOffset1());\n CharSequenceSubSequence sequence2 = new CharSequenceSubSequence(text2, fragment.getStartOffset2(), fragment.getEndOffset2());\n\n if ((fragment.getInnerFragments() == null || !fragment.getInnerFragments().isEmpty()) &&\n !StringUtil.equalsIgnoreWhitespaces(sequence1, sequence2)) {\n break;\n }\n start++;\n }\n while (start < end) {\n LineFragment fragment = fragments.get(end - 1);\n CharSequenceSubSequence sequence1 = new CharSequenceSubSequence(text1, fragment.getStartOffset1(), fragment.getEndOffset1());\n CharSequenceSubSequence sequence2 = new CharSequenceSubSequence(text2, fragment.getStartOffset2(), fragment.getEndOffset2());\n\n if ((fragment.getInnerFragments() == null || !fragment.getInnerFragments().isEmpty()) &&\n !StringUtil.equalsIgnoreWhitespaces(sequence1, sequence2)) {\n break;\n }\n end--;\n }\n }\n\n if (start == end) return Collections.emptyList();\n if (squash) {\n return singletonList(doSquash(fragments.subList(start, end)));\n }\n return fragments.subList(start, end);\n }\n\n @NotNull\n private static LineFragment doSquash(@NotNull List oldFragments) {\n assert !oldFragments.isEmpty();\n if (oldFragments.size() == 1) return oldFragments.get(0);\n\n LineFragment firstFragment = oldFragments.get(0);\n LineFragment lastFragment = oldFragments.get(oldFragments.size() - 1);\n\n List newInnerFragments = new ArrayList<>();\n for (LineFragment fragment : oldFragments) {\n for (DiffFragment innerFragment : extractInnerFragments(fragment)) {\n int shift1 = fragment.getStartOffset1() - firstFragment.getStartOffset1();\n int shift2 = fragment.getStartOffset2() - firstFragment.getStartOffset2();\n\n DiffFragment previousFragment = ContainerUtil.getLastItem(newInnerFragments);\n if (previousFragment == null || !isAdjoiningInner(previousFragment, innerFragment, shift1, shift2)) {\n newInnerFragments.add(new DiffFragmentImpl(innerFragment.getStartOffset1() + shift1, innerFragment.getEndOffset1() + shift1,\n innerFragment.getStartOffset2() + shift2, innerFragment.getEndOffset2() + shift2));\n }\n else {\n newInnerFragments.remove(newInnerFragments.size() - 1);\n newInnerFragments.add(new DiffFragmentImpl(previousFragment.getStartOffset1(), innerFragment.getEndOffset1() + shift1,\n previousFragment.getStartOffset2(), innerFragment.getEndOffset2() + shift2));\n }\n }\n }\n\n return new LineFragmentImpl(firstFragment.getStartLine1(), lastFragment.getEndLine1(),\n firstFragment.getStartLine2(), lastFragment.getEndLine2(),\n firstFragment.getStartOffset1(), lastFragment.getEndOffset1(),\n firstFragment.getStartOffset2(), lastFragment.getEndOffset2(),\n newInnerFragments);\n }\n\n private static boolean isAdjoining(@NotNull LineFragment beforeFragment, @NotNull LineFragment afterFragment) {\n if (beforeFragment.getEndLine1() != afterFragment.getStartLine1() ||\n beforeFragment.getEndLine2() != afterFragment.getStartLine2() ||\n beforeFragment.getEndOffset1() != afterFragment.getStartOffset1() ||\n beforeFragment.getEndOffset2() != afterFragment.getStartOffset2()) {\n return false;\n }\n\n return true;\n }\n\n private static boolean isAdjoiningInner(@NotNull DiffFragment beforeFragment, @NotNull DiffFragment afterFragment,\n int shift1, int shift2) {\n if (beforeFragment.getEndOffset1() != afterFragment.getStartOffset1() + shift1 ||\n beforeFragment.getEndOffset2() != afterFragment.getStartOffset2() + shift2) {\n return false;\n }\n\n return true;\n }\n\n @NotNull\n private static List extractInnerFragments(@NotNull LineFragment lineFragment) {\n if (lineFragment.getInnerFragments() != null) return lineFragment.getInnerFragments();\n\n int length1 = lineFragment.getEndOffset1() - lineFragment.getStartOffset1();\n int length2 = lineFragment.getEndOffset2() - lineFragment.getStartOffset2();\n return singletonList(new DiffFragmentImpl(0, length1, 0, length2));\n }\n\n @NotNull\n private static List getLines(@NotNull CharSequence text) {\n List lines = new ArrayList<>();\n\n int offset = 0;\n while (true) {\n int lineEnd = StringUtil.indexOf(text, '\\n', offset);\n if (lineEnd != -1) {\n lines.add(new Line(text, offset, lineEnd, true));\n offset = lineEnd + 1;\n }\n else {\n lines.add(new Line(text, offset, text.length(), false));\n break;\n }\n }\n\n return lines;\n }\n\n\n /**\n * Compare two texts by-line and then compare changed fragments by-word\n */\n @NotNull\n public List compareLinesWithIgnoredRanges(@NotNull CharSequence text1,\n @NotNull CharSequence text2,\n @NotNull List ignoredRanges1,\n @NotNull List ignoredRanges2,\n boolean innerFragments,\n @NotNull ProgressIndicator indicator) throws DiffTooBigException {\n BitSet ignored1 = collectIgnoredRanges(ignoredRanges1);", "answers": [" BitSet ignored2 = collectIgnoredRanges(ignoredRanges2);"], "length": 1460, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "c4cdf5cb-66fa-46d0-90d5-48997b432c51", "reasoning": "The method is gathering BitSet representations of ignored ranges for both texts. After creating ignored1 from ignoredRanges1, the next logical step is to do the same for ignoredRanges2, assigning it to ignored2.", "reasoning_model_answer": "BitSet ignored2 = collectIgnoredRanges(ignoredRanges2);", "assistant_with_reasoning": "\nThe method is gathering BitSet representations of ignored ranges for both texts. After creating ignored1 from ignoredRanges1, the next logical step is to do the same for ignoredRanges2, assigning it to ignored2.\n\nBitSet ignored2 = collectIgnoredRanges(ignoredRanges2);", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 5.324, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 20116, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "BitSet ignored2 = collectIgnoredRanges(ignoredRanges2);", "score": 0.96, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "import nltk\nfrom nltk.tokenize import word_tokenize, sent_tokenize\n\n# Used for WordFilters\nfrom ConstantsAndUtilities import *\nimport string\nimport nltk\n\n#from nltk.replacers import RegexpReplacer\n\nfrom TextAnalysis.AnalysisErrors import NgramError\n\n\nclass ICleaner(object):\n \"\"\"\n Interface for text processing objects which take a word as input and\n either return True or False.\n\n A list of these will be passed in to objects like TweetTextWordBagMaker\n \"\"\"\n def __init__(self):\n pass\n\n def clean(self, word):\n raise NotImplementedError\n\n\nclass URLCleaner(ICleaner):\n \"\"\"\n Removes some urls\n TODO: Make this better\n \"\"\"\n def __init__(self):\n ICleaner.__init__(self)\n\n def clean(self, word):\n if word[0:6] != '//t.co':\n return True\n else:\n return False\n\n\nclass UsernameCleaner(ICleaner):\n \"\"\"\n Filters out usernames\n \"\"\"\n def __init__(self):\n ICleaner.__init__(self)\n\n def clean(self, word):\n assert(type(word) is str)\n if word[0] != '@' and word[0:1] != '.@':\n return True\n else:\n return False\n\n\nclass NumeralCleaner(ICleaner):\n \"\"\"\n Filters out all non-alphanumeric characters\n \"\"\"\n def __init__(self):\n ICleaner.__init__(self)\n\n def clean(self, word):\n if type(word) is str:\n return word.isalpha()\n else:\n return False\n\n\nclass IModifier(object):\n \"\"\"\n Interface for classes which modify words through stemming\n lemmatizing etc\n \"\"\"\n def __init__(self):\n pass\n\n def process(self, word, **kwargs):\n raise NotImplementedError\n\n\nclass RegexpReplacer(IModifier):\n def __init__(self):\n pass\n\n def process(self, word, **kwargs):\n \"\"\"\n Arguments:\n patterns: Replacement patterns\n \"\"\"\n patterns = replacement_patterns\n compiled = [(re.compile(regex), repl) for (regex, repl) in patterns]\n s = text\n for (pattern, repl) in self.patterns:\n (s, count) = re.subn(pattern, repl, s)\n return s\n\n\nclass Lemmatizer(IModifier):\n \"\"\"\n Wrapper on nltk.stem.WordNetLemmatizer for lemmatizing words\n \"\"\"\n def __init__(self):\n IModifier.__init__(self)\n self.lemmatizer = nltk.stem.WordNetLemmatizer()\n\n def process(self, word, **kwargs):\n \"\"\"\n Args:\n word: String to be lemmatized\n Returns:\n Lemmatized string\n \"\"\"\n try:\n assert(type(word) is str)\n return self.lemmatizer.lemmatize(word)\n except Exception as e:\n print(e)\n\n\nclass PorterStemmer(IModifier):\n \"\"\"\n Wrapper on nltk's porter-stemmer\n \"\"\"\n\n def __init__(self):\n IModifier.__init__(self)\n self.stemmer = nltk.stem.PorterStemmer()\n\n def process(self, word, **kwargs):\n \"\"\"\n Executes the porter stem and returns the stemmed word\n Args:\n word: String to stem\n Returns:\n Porter stemmed string\n \"\"\"\n try:\n assert(type(word) is str)\n return self.stemmer.stem(word)\n except Exception as e:\n print(e)\n\n\nclass WordBagMaker(object):\n \"\"\"\n General class for taking something with strings and processing the text for bag of words type analyses.\n\n Before running the process command, all lists of strings to ignore should be loaded using add_to_ignorelist()\n\n Attributes:\n _cleaners: List of ICleaner objects\n masterbag: List containing all words\n _ignore: Tuple of strings to ignore while filtering\n \"\"\"\n\n def __init__(self):\n self._ignore = ()\n self._cleaners = []\n self.masterbag = []\n\n def add_to_ignorelist(self, list_to_ignore):\n \"\"\"\n Add a list of strings to the internally held tuple of strings to ignore in processing text\n Example:\n bagmaker = WordBagMaker()\n bagmaker.add_to_ignorelist(ignore.get_list())\n bagmaker.add_to_ignorelist(nltk.corpus.stopwords.words('english'))\n bagmaker.add_to_ignorelist(list(string.punctuation))\n \n Args:\n list_to_ignore: List of strings to ignore.\n \"\"\"\n self._ignore = list(self._ignore)\n [self._ignore.append(i) for i in list_to_ignore]\n self._ignore = set(self._ignore)\n self._ignore = tuple(self._ignore)\n\n def add_to_cleaners(self, icleaner):\n \"\"\"\n Adds an object which does cleaning to the que of cleaners which get\n called by _check_unwanted()\n Example:\n bagmaker.add_to_cleaners(URLCleaner())\n bagmaker.add_to_cleaners(UsernameCleaner())\n bagmaker.add_to_cleaners(NumeralCleaner())\n\n Args:\n :param icleaner: ICleaner inheriting object\n \"\"\"\n assert(isinstance(icleaner, ICleaner))\n self._cleaners.append(icleaner)\n\n def process(self, to_process):\n \"\"\"\n Processes list of strings into a word bag stored in self.masterbag\n\n Args:\n :param to_process: List of strings to process\n \"\"\"\n assert(isinstance(to_process, list))\n for t in to_process:\n # process text\n words = self._make_wordbag(t)\n words = [w for w in words if self._check_unwanted(w) and w not in self._ignore]\n self.masterbag += words\n\n def _make_wordbag(self, text):\n \"\"\"\n Takes a bunch of sentences and extracts all the words, makes them lowercase, and returns them in a list\n \n Args:\n text: String text to be word tokenized\n \n Returns:\n List of words, all lower case\n \"\"\"\n return [word.lower() for sent in nltk.tokenize.sent_tokenize(text) for word in nltk.tokenize.word_tokenize(sent)]\n\n def _check_unwanted(self, word):\n \"\"\"\n Args:\n word: String to evaluate with ICleaner objects in _cleaners\n Returns:\n False if the the string is to be left out\n True if the string is to be included\n \"\"\"\n for cleaner in self._cleaners:\n if cleaner.clean(word) is False:\n return False\n return True\n\n\nclass TweetTextWordBagMaker(WordBagMaker):\n \"\"\"\n This takes a list of dictionaries containing tweetID and tweetText and processes the texts for bag of words type analyses.\n\n Before running the process command, all lists of strings to ignore should be loaded using add_to_ignorelist()\n\n Attributes:\n _cleaners: List of ICleaner objects\n masterbag: List containing all words\n _ignore: Tuple of strings to ignore while filtering\n tweet_tuples: List containing tuples with the structure (tweetID, [list of words in tweet])\n \"\"\"\n def __init__(self):\n self.tweet_tuples = []\n WordBagMaker.__init__(self)\n\n def process(self, to_process):\n \"\"\"\n Args:\n to_process: List of tweet dictionary objects with keys 'tweetID' and 'tweetText'\n\n Best time 225.85651803\n\n Example\n bagmaker = TweetTextWordBagMaker()\n bagmaker.add_to_ignorelist(ignore.get_list())\n bagmaker.add_to_ignorelist(nltk.corpus.stopwords.words('english'))\n \"\"\"\n for t in to_process:\n tweetid = t['tweetID']\n # process text\n words = self._make_wordbag(t['tweetText'])\n words = [w for w in words if self._check_unwanted(w) and w not in self._ignore]\n # process tuple\n tweet_tuple = (tweetid, words)\n self.tweet_tuples.append(tweet_tuple)\n self.masterbag += words\n\n # def OLDprocess(self, list_of_dicts):\n # for t in list(self.results):\n # tweetid = t['tweetID']\n # #process text\n # words = [word for sent in sent_tokenize(t['tweetText']) for word in word_tokenize(sent)]\n # words = [w.lower() for w in words]\n # words = [w for w in words if w not in Ignore.punctuation] #remove punctuation\n # words = [w for w in words if w not in Ignore.fragments] #remove fragments\n # words = [w for w in words if w[0] != '@'] #Get rid of usernames\n # words = [w for w in words if w[0:6] != '//t.co'] #Remove some urls\n # words = [w for w in words if w not in Ignore.words['socialmediaterms']] #Remove terms from social media\n # words = [w for w in words if w not in nltk.corpus.stopwords.words('english')] #Remove stopwords\n # #process tuple\n # tweet_tuple = (tweetid, words)\n # self.tweet_tuples.append(tweet_tuple)\n # self.masterbag += words\n # def process(self, list_of_dicts):\n # \"\"\"\n # Processes the tweet texts\n # Most recent execution time 599.286342144 sec for 732683 tweets\n # Moved stopwords filtration first: 891.928412914 for 732683 tweets\n # Merged stopwords into ignore list: 234.204810858\n # 1 loops, best of 3: 14min 56s per loop\n #\n # Args:\n # list_of_dicts: List of dictionaries with keys tweetID and tweetText\n # \"\"\"\n # for t in list_of_dicts:\n # tweetid = t['tweetID']\n # # process text\n # words = self._make_wordbag(t['tweetText'])\n # # words = self._filter_stopwords(words)\n # words = self._filter_ignored_terms(words)\n # words = self._filter_usernames(words)\n # words = self._filter_urls(words)\n # # process tuple\n # tweet_tuple = (tweetid, words)\n # self.tweet_tuples.append(tweet_tuple)\n # self.masterbag += words\n\n\nclass INgramFilter(object):\n \"\"\"\n Interface for filters on ngrams\n \"\"\"\n def __init__(self, **kwargs):\n pass\n\n def filter(self, collocation_finder):\n \"\"\"\n Arguments:\n collocation_finder: Instance of nltk.collocations.AbstractCollocationFinder\n Returns:\n The collocation_finder after has been filtered\n \"\"\"\n raise NotImplementedError\n\n\nclass CustomFilter(INgramFilter):\n \"\"\"\n Wrapper for applying arbitrary filter to the collocation finder\n e.g., for getting where 'and' is at trigram[1] but not beginning or end: lambda w1, w2, w3: 'and' in (w1, w3)\n \"\"\"\n\n def __init__(self):\n self.filter_function = lambda x: x\n INgramFilter.__init__(self)\n\n def set_filter(self, filter_function):\n self.filter_function = filter_function\n\n def filter(self, collocation_finder):\n \"\"\"\n Arguments:\n collocation_finder: Instance of nltk.collocations.AbstractCollocationFinder\n \"\"\"\n assert isinstance(collocation_finder, nltk.collocations.AbstractCollocationFinder)\n return collocation_finder.apply_ngram_filter(self.filter_function)\n\n\nclass WordFilter(INgramFilter):\n \"\"\"\n Wrapper for filtering by specific strings\n Make sure to set filter_words before calling filter\n Attributes:\n _filter_words: Tuple holding words to filter by, can be set with string, tuple, or list\n \"\"\"\n\n def __init__(self):\n self._filter_words = ()\n INgramFilter.__init__(self)\n\n @property\n def filter_words(self):\n return self._filter_words\n\n @filter_words.setter\n def filter_words(self, words):\n \"\"\"\n adds words to the internally held tuple of filter_words\n Arguments:\n :param words: Tuple, list, or individual word to add to the filter words\n \"\"\"\n self._filter_words = list(self._filter_words)\n if isinstance(words, list):\n self._filter_words += words\n elif isinstance(words, str):\n self._filter_words.append(words)\n elif isinstance(words, tuple):\n self._filter_words += list(words)\n self._filter_words = tuple(self._filter_words)\n\n def filter(self, collocation_finder):\n \"\"\"\n Arguments:\n collocation_finder: Instance of nltk.collocations.AbstractCollocationFinder\n \"\"\"\n assert isinstance(collocation_finder, nltk.collocations.AbstractCollocationFinder)\n return collocation_finder.apply_word_filter(lambda w: w in self.filter_words)\n\n\nclass NgramGetter(object):\n \"\"\"\n Abstract parent class for extracting ngrams.\n\n Attributes:\n collocation_finder: One of the nltk's collocation finder tools (e.g., BigramCollocationFinder)\n top_likelihood_ratio:\n measurement_tool: One of nltk's measurement tools (e.g., nltk.collocations.BigramAssocMeasures)\n modifiers: IModifier instantiating tool for modifying the text before calculating ngrams\n ngrams: List of ngrams\n raw_freq: Frequency distribution of ngrams\n sorted_ngrams: List of tuples sorted by self.scored_ngrams\n top_pmi: Variable number of n-grams with the highest Pointwise Mutual Information (i.e., which occur together\n more often than would be expected)\n word_bag: List of text to process\n \"\"\"\n\n def __init__(self):\n self.modifiers = []\n self.ngram_filters = []\n self.word_bag = []\n self.ngrams = []\n if not self.measurement_tool:\n raise NotImplementedError\n\n def add_modifier(self, iModifier):\n assert(isinstance(iModifier, IModifier))\n self.modifiers.append(iModifier)\n\n def _run_modifiers(self):\n \"\"\"\n Calls the modifiers in sequence and stores the results back in word_bag\n \"\"\"", "answers": [" for modifier in self.modifiers:"], "length": 1340, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "5d450252-db09-48dc-97c2-829af6161599", "reasoning": "The method _run_modifiers is meant to apply each IModifier in self.modifiers to the current word bag. After the docstring, the first operational line should start a loop over the modifiers, i.e., 'for modifier in self.modifiers:'. This begins the implementation of applying modifiers sequentially.", "reasoning_model_answer": "for modifier in self.modifiers:", "assistant_with_reasoning": "\nThe method _run_modifiers is meant to apply each IModifier in self.modifiers to the current word bag. After the docstring, the first operational line should start a loop over the modifiers, i.e., 'for modifier in self.modifiers:'. This begins the implementation of applying modifiers sequentially.\n\nfor modifier in self.modifiers:", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.346, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 13716, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "for modifier in self.modifiers:", "score": 0.89, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/***************************************************************************\n * Copyright (C) 2010 by Yvonne Hermann, Peter Husemann *\n * phuseman a t cebitec.uni-bielefeld.de *\n * *\n * This program is free software; you can redistribute it and/or modify *\n * it under the terms of the GNU General Public License as published by *\n * the Free Software Foundation; either version 2 of the License, or *\n * (at your option) any later version. *\n * *\n * This program is distributed in the hope that it will be useful, *\n * but WITHOUT ANY WARRANTY; without even the implied warranty of *\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *\n * GNU General Public License for more details. *\n * *\n * You should have received a copy of the GNU General Public License *\n * along with this program; if not, write to the *\n * Free Software Foundation, Inc., *\n * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *\n ***************************************************************************/\n\npackage de.bielefeld.uni.cebitec.primerdesign;\n\n\nimport java.io.File;\nimport java.io.FileReader;\nimport java.io.IOException;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.Iterator;\nimport org.xml.sax.Attributes;\nimport org.xml.sax.InputSource;\nimport org.xml.sax.SAXException;\nimport org.xml.sax.XMLReader;\nimport org.xml.sax.helpers.DefaultHandler;\nimport org.xml.sax.helpers.XMLReaderFactory;\n\n/**\n * This class contains the parameters an the methods to calculate the score for each primer candidate.\n * It loads default parameters or retrieves parameters from a given XML file with the SAXParser.\n * \n * **************************************************************************************************\n * \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t*\n * The parameters are from a config file (primer_search_default_config.xml), which was developed\t*\n * by Jochen Blom and Dr. Christian Rueckert.\t\t\t\t\t\t\t\t\t\t\t\t\t\t*\n * The methods to calculate the score for a primer are a reproduction of the perl-script \t\t\t*\n * (primer_search_confable.pl) developed and written by Jochen Blom and Dr. Christian Rueckert.\t\t*\n * \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t*\n *\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t*\n ****************************************************************************************************/\n\n\tfinal class PrimerScoringScheme extends DefaultHandler{\n\t\t//The following HashMaps and Arrays save the parameters(needed for the score calculation)\n\t\tprivate HashMap firstBase = new HashMap();\n\t\tprivate HashMap lastBase = new HashMap();\n\t\tprivate HashMap\tplus1Base= new HashMap();\n\t\tprivate HashMap\tplus2Base= new HashMap();\n\t\tprivate HashMap gc = new HashMap();\n\t\tprivate HashMap offset = new HashMap();\n\t\tprivate HashMap atLast6 = new HashMap();\n\t\tprivate HashMap gc0207 = new HashMap();\n\t\tprivate HashMap anneal = new HashMap();\n\t\tprivate Integer[] gcArray;\n\t\tprivate Integer[] annealArray;\n\t\tprivate Integer[] ATLast6Array;\n\t\tprivate Integer[] gc0207Array;\n\t\tprivate Integer[] offsetArray;\n\t\tprivate Bases base;\n\t\tprivate SimpleSmithWatermanPrimerAligner swa;\n\t\t//following global variables are intialized with default parameters.\n\t\t// If a XML file is given, these are set to the retrieved parameters.\n\t\tprivate double homopolyCNT = 3.0;\n\t\tprivate double homopolySCORE = -200.0;\n\t\tprivate double lengthIDEAL = 20.5;\n\t\tprivate double lengthSCORE= -2.0;\n\t\tprivate double npenalty = -1500.0;\n\t\tprivate double repeat = -1500.0;\n\t\tprivate double maxoffsetDISTANCE = 150.0;\n\t\tprivate double maxoffsetMULT= -2.0;\n\t\tprivate double backfold = -1500.0;\n\t\t//globale variables are needed to parse XML-File\n\t\tprivate File configFile = null;\n\t\tprivate String elementName = null;\n\t\tprivate String parentElementName = null;\n\t\tprivate String key = null;\n\t\tprivate String value = null;\n\t\t\n\t\t/**\n\t\t * Constructor of the class.\n\t\t * Fills the parameter containers with default values and gets instances of the need 'help' classes.\n\t\t */\n\t\t\n\t\tpublic PrimerScoringScheme(){\n\t\t\t\tthis.defaultParameters();\n\t\t\t\tbase = Bases.getInstance();\n\t\t\t\tswa = new SimpleSmithWatermanPrimerAligner();\n\t\t}\n\t\t/**\n\t\t * Constructor of the class.\n\t\t * When a config-file is given the parsing of XML file is set up and puts the retrieved parameters in the\n\t\t * parameter containers.\n\t\t */\n\t\tpublic PrimerScoringScheme(File config){\n\t\t\tconfigFile = config;\n\t\t\tbase = Bases.getInstance();\n\t\t\tswa = new SimpleSmithWatermanPrimerAligner();\n\t\t}\n\n\t\t/**\n\t\t * This method calculates scores for each attribute of the primer and returns a\n\t\t * total score for it.\n\t\t * \n\t\t * @param primer\n\t\t * @return primer score\n\t\t */\n\t\tpublic double calculatePrimerScore(Primer primer) {\n\t\t\tchar[] primerSeq = primer.getPrimerSeq();\n\t\t\t\t\n\t\t\t\tdouble scoreTemperature = this.calcScoreMeltingTemperature(primer.getPrimerTemperature());\n\t\t\t\t//when the temperature scores -1 the sequence contains characters which caused an error in the \n\t\t\t\t//melting temperature calculation. These primers will not be considered in futher calculations\n\t\t\t\tif (scoreTemperature != -1) {\n\t\t\t\t\tdouble scoreLength = this.getLengthScore(primer.getPrimerLength());\n\t\t\t\t\tdouble scoreGCTotal = this.getGCScore(primerSeq);\n\t\t\t\t\tdouble scoreFirstLastBase = this.getFirstAndLastBaseScore(primerSeq);\n\t\t\t\t\tdouble scoreBackfold = this.getBackfoldScore(primerSeq);\n\t\t\t\t\tdouble scoreLast6 = this.getLast6Score(primerSeq);\n\t\t\t\t\tdouble scorePlus1Plus2 = this.getPlus1Plus2Score(primer.getLastPlus1(), primer.getLastPlus2());\n\t\t\t\t\tdouble scoreOffset = this.getOffsetsScore(primer.getDistanceFromContigBorder(),primer.getPrimerLength());\n\t\t\t\t\tdouble scoreNPenalty = this.getNPenalty(primerSeq);\n\t\t\t\t\tdouble scoreHomopoly = this.getHomopolyScore(primerSeq);\n\t\t\t\t\tdouble scoreRepeat = this.getRepeatScore(primerSeq);\n\t\t\t\t\tdouble primerScore = scoreGCTotal + scoreRepeat\n\t\t\t\t\t\t\t+ scoreFirstLastBase + scoreNPenalty + scoreBackfold\n\t\t\t\t\t\t\t+ scoreLength + scoreLast6 + scoreOffset\n\t\t\t\t\t\t\t+ scorePlus1Plus2 + scoreTemperature + scoreHomopoly;\n\t\t\t\t\treturn primerScore;\n\t\t\t\t\t\n\t\t\t}\n\t\t\t\treturn -Double.MAX_VALUE;\n\t\t}\n\n\t\t/**\n\t\t * This method loads default parameters which are based on the primer_search_default_config file.\n\t\t * Parameters are chosen by Jochen Blom and Dr. Christian Rueckert.\n\t\t */\n\t\tprivate void defaultParameters(){\n\t\t\tArrayList gcArrayList = new ArrayList();\n\t\t\tArrayList annealArrayList = new ArrayList();\n\t\t\tArrayList atLast6ArrayList = new ArrayList();\n\t\t\tArrayList gc0207ArrayList = new ArrayList();\n\t\t\tArrayList offsetArrayList = new ArrayList();\n\t\t\t\n\t\t\tgc.put(10.0, 100.0);\n\t\t\tgc.put(15.0, -100.0);\n\t\t\tgc.put(20.0, -300.0);\n\t\t\tgc.put(25.0, -800.0);\n\t\t\tgc.put(50.0, -1500.0);\n\t\n\t\t\tgcArrayList = fillArrayListWithDefaultValues(gc);\n\t\t\tthis.gcArray =this.makeIntArray((gcArrayList.toArray()));\n\t\t\n\t\t\tfirstBase.put('A', 45.0);\n\t\t\tfirstBase.put('T', 45.0);\n\t\t\tfirstBase.put('C', 0.0);\n\t\t\tfirstBase.put('G', 0.0);\n\t\t\tfirstBase.put('N', -1500.0);\n\t\t\t\n\t\t\tlastBase.put('A', 130.0);\n\t\t\tlastBase.put('T', 100.0);\n\t\t\tlastBase.put('C', 0.0);\n\t\t\tlastBase.put('G', 0.0);\n\t\t\tlastBase.put('N', -1500.0);\n\t\t\t\n\t\t\tplus1Base.put('A', 130.0);\n\t\t\tplus1Base.put('T', 100.0);\n\t\t\tplus1Base.put('C', 0.0);\n\t\t\tplus1Base.put('G', 0.0);\n\t\t\tplus1Base.put('N', 0.0);\n\t\t\t\n\t\t\tplus2Base.put('A', 80.0);\n\t\t\tplus2Base.put('T', 80.0);\n\t\t\tplus2Base.put('C', 0.0);\n\t\t\tplus2Base.put('G', 0.0);\n\t\t\tplus2Base.put('N', 0.0);\n\t\t\t\n\t\t\toffset.put(0.0, -1000.0);\n\t\t\toffset.put(30.0, -600.0);\n\t\t\toffset.put(50.0, -500.0);\n\t\t\toffset.put(80.0, -400.0);\n\t\t\toffset.put(110.0, -50.0);\n\t\t\toffset.put(150.0, 250.0);\n\t\t\t\n\t\t\toffsetArrayList = fillArrayListWithDefaultValues(offset);\n\t\t\tthis.offsetArray =this.makeIntArray((offsetArrayList.toArray()));\n\t\t\t\n\t\t\tgc0207.put(79.0, 156.0);\n\t\t\tgc0207.put(60.0, -83.0);\n\t\t\tgc0207.put(50.0, -320.0);\n\t\t\tgc0207.put(0.0, -1500.0);\n\t\t\t\n\t\t\tgc0207ArrayList = fillArrayListWithDefaultValues(gc0207);\n\t\t\tthis.gc0207Array =this.makeIntArray((gc0207ArrayList.toArray()));\n\t\t\t\n\t\t\tatLast6.put(79.0, 156.0);\n\t\t\tatLast6.put(60.0, -83.0);\n\t\t\tatLast6.put(50.0, -320.0);\n\t\t\tatLast6.put(0.0, -1500.0);\n\t\t\t\n\t\t\tatLast6ArrayList = fillArrayListWithDefaultValues(atLast6);\n\t\t\tthis.ATLast6Array =this.makeIntArray((atLast6ArrayList.toArray()));\n\t\t\t\n\t\t\tanneal.put(2.0, 200.0);\n\t\t\tanneal.put(6.0,0.0);\n\t\t\tanneal.put(100.0, -1500.0);\n\t\t\t\n\t\t\tannealArrayList = fillArrayListWithDefaultValues(anneal);\n\t\t\tthis.annealArray =this.makeIntArray((annealArrayList.toArray()));\n\t\t}\n\t\t\n\t\t/**\n\t\t * This method fills an ArrayList with the keys of the given HashMap\n\t\t * \n\t\t * @param map\n\t\t * @return keys\n\t\t */\n\t\tprivate ArrayList fillArrayListWithDefaultValues(HashMap map){\n\t\t\tArrayList keys = new ArrayList();\n\t\t\tIterator iterator = (map.keySet()).iterator();\n\t\t\twhile(iterator.hasNext()){\n\t\t\t\tkeys.add((Double) iterator.next());\n\t\t\t}\n\t\t\treturn keys;\n\t\t}\n\t\t\n\t\t/**\n\t\t * This method parses the objects in the given array\n\t\t * to integers and returns them in an array.\n\t\t * \n\t\t * @param object\n\t\t * @return array\n\t\t */\n\t\tprivate Integer[] makeIntArray(Object[] object){\n\t\t\tInteger[] intArray = new Integer[object.length];\n\t\t\tfor(int i = 0; i=(50-interval)&&gcRatio<=(50+interval)){\n\t\t\t\t\t\tscoreGCTotal =gc.get((double)interval);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn scoreGCTotal;\n\t\t}\n\n\t\t/**\n\t\t * This method gets the melting temperature for this primer.\n\t\t * According to the given parameters the score for the melting temperature is returned.\n\t\t * \n\t\t * @param temperature\n\t\t * @return melting temperature score\n\t\t */\n\t\tprivate double calcScoreMeltingTemperature(double temperature){\n\t\t\tdouble scoreTemperature = 0;\n\t\t\tdouble minBorder = 0;\n\t\t\tdouble maxBorder = 0;\n\t\t\tArrays.sort(annealArray,Collections.reverseOrder());\n\t\t\t//Paramters are used to form intervals and gives back the score\n\t\t\t//where the temperature is still in the interval\n\t\t\tfor(Integer interval : annealArray){\n\t\t\t\tminBorder = 60-interval;\n\t\t\t\tmaxBorder = 60+interval;\n\t\t\tif(temperature>=minBorder&&temperature<=maxBorder){\n\t\t\t\tscoreTemperature = anneal.get((double)interval);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn scoreTemperature;\n\t\t}\n\t\t\n\t\t/**\n\t\t * This method examines the given ratio of the bases G and C at the position 2 till 7.\n\t\t * It returns a score according to the used parameters.\n\t\t * \n\t\t * @param gcRatio2A7\n\t\t * @return GC-Level at position 2 and 7 score \n\t\t */\n\t\tprivate double calcScoreGCLevel2A7(double gcRatio2A7){\n\t\t\tdouble scoreGC2A7 = 0;\n\t\t\tArrays.sort(gc0207Array);\n\t\t\t//Paramters are used to form intervals and gives back the score\n\t\t\t//where the GC0207-ratio is still in the interval\n\t\t\tfor(Integer border : gc0207Array){\n\t\t\t\tif(gcRatio2A7>=border){\n\t\t\t\t\tscoreGC2A7 = this.gc0207.get((double)border);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn scoreGC2A7;\n\t\t}\n\t\t\n\t\t/**\n\t\t * This method examines the given ratio for AT in the last 6 positions of the primer sequence\n\t\t * and returns a score according to the given score-scheme.\n\t\t * \n\t\t * @param ATLast6Ratio\n\t\t * @return AT at last 6 Base score\n\t\t */\n\t\tpublic double calcScoreLast6(double ATLast6Ratio){\n\t\t\tdouble scoreLast6Bases =0;\n\t\t\tArrays.sort(ATLast6Array);\n\t\t\t//Paramters are used to form intervals and gives back the score\n\t\t\t//where the AT-ratio in the last 6 bases is still in the interval\n\t\t\tfor(Integer border : ATLast6Array){\n\t\t\t\tif(ATLast6Ratio>= border){\n\t\t\t\t\tscoreLast6Bases = this.atLast6.get((double)border);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn scoreLast6Bases;\n\t\t}\n\t\t\n\t\t/**\n\t\t * This method calculates the score for the offset of a primer to the end\n\t\t * of the contig.\n\t\t * \n\t\t * @param realstart\n\t\t * @return offsetScore\n\t\t */\n\t\tprivate double calcScoreOffset(int realstart){\n\t\t\tdouble score = 0;\n\t\t\tArrays.sort(offsetArray);\n\t\t\t//Paramters are used to form intervals and gives back the score\n\t\t\t//where the start-position of the primer is still in the interval\n\t\t\tfor(Integer border : offsetArray){\n\t\t\t\tif(realstart>= border){\n\t\t\t\t\tscore = this.offset.get((double)border);\n\t\t\t\t}\n\t\t\t}\n\t\t", "answers": ["\t\t\treturn score;"], "length": 1402, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "47db9077-53b9-4a6f-b760-284fc84ef412", "reasoning": "The method calcScoreOffset currently computes a score inside a loop but does not yet return it. Following the pattern of other scoring methods in the class, the next line should return the computed score before the method ends.", "reasoning_model_answer": "return score;", "assistant_with_reasoning": "\nThe method calcScoreOffset currently computes a score inside a loop but does not yet return it. Following the pattern of other scoring methods in the class, the next line should return the computed score before the method ends.\n\nreturn score;", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.313, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 13501, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "return score;", "score": 0.9, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "//\n// Mainsoft.Web.Security.DerbyMembershipHelper\n//\n// Authors:\n//\tVladimir Krasnov (vladimirk@mainsoft.com)\n//\n// (C) 2006 Mainsoft\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n// \n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n// \n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\n#if NET_2_0\n\nusing System;\nusing System.Web.Security;\nusing System.Data;\nusing System.Data.OleDb;\nusing System.Data.Common;\nusing System.Collections.Generic;\nusing System.Text;\n\nnamespace Mainsoft.Web.Security\n{\n\tstatic class DerbyMembershipHelper\n\t{\n\t\tstatic readonly DateTime DefaultDateTime = new DateTime (1754, 1, 1).ToUniversalTime ();\n\n\t\tprivate static OleDbParameter AddParameter (OleDbCommand command, string paramName, object paramValue)\n\t\t{\n\t\t\tOleDbParameter prm = new OleDbParameter (paramName, paramValue);\n\t\t\tcommand.Parameters.Add (prm);\n\t\t\treturn prm;\n\t\t}\n\n\t\tpublic static int Membership_ChangePasswordQuestionAndAnswer (DbConnection connection, string applicationName, string username, string newPwdQuestion, string newPwdAnswer)\n\t\t{\n\t\t\tstring updateQuery = \"UPDATE aspnet_Membership SET PasswordQuestion = ?, PasswordAnswer = ? WHERE UserId = ?\";\n\n\t\t\tstring userId = GetUserId (connection, applicationName, username);\n\t\t\tif (userId == null)\n\t\t\t\treturn 1; // user not found\n\n\t\t\tOleDbCommand updateCmd = new OleDbCommand (updateQuery, (OleDbConnection) connection);\n\t\t\tAddParameter (updateCmd, \"PasswordQuestion\", newPwdQuestion);\n\t\t\tAddParameter (updateCmd, \"PasswordAnswer\", newPwdAnswer);\n\t\t\tAddParameter (updateCmd, \"UserId\", userId);\n\t\t\tupdateCmd.ExecuteNonQuery ();\n\t\t\treturn 0;\n\t\t}\n\n\t\tpublic static int Membership_CreateUser (DbConnection connection, string applicationName, string username, string password, string passwordSalt, string email, string pwdQuestion, string pwdAnswer, bool isApproved, DateTime currentTimeUtc, DateTime createDate, bool uniqueEmail, int passwordFormat, ref object userId)\n\t\t{\n\t\t\tstring applicationId = (string) DerbyApplicationsHelper.Applications_CreateApplication (connection, applicationName);\n\t\t\tstring newUserId = (string) userId;\n\n\t\t\tOleDbTransaction trans = (OleDbTransaction) connection.BeginTransaction ();\n\n\t\t\ttry {\n\t\t\t\tint returnValue = Users_CreateUser (connection, trans, applicationId, username, false, createDate, ref userId);\n\t\t\t\tif (returnValue == 1) {\n\t\t\t\t\t// the user exists in users table, this can occure when user\n\t\t\t\t\t// does not have membership information, but has other information\n\t\t\t\t\t// like roles, etc.\n\t\t\t\t\tif (userId != null && newUserId != null && newUserId != (string) userId) {\n\t\t\t\t\t\ttrans.Rollback ();\n\t\t\t\t\t\treturn 9; // wrong userid provided\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if (returnValue == 2) {\n\t\t\t\t\t// another user with provided id already exists\n\t\t\t\t\ttrans.Rollback ();\n\t\t\t\t\treturn 10; // wrong userid provided\n\t\t\t\t}\n\t\t\t\tnewUserId = (string) userId;\n\n\t\t\t\tstring selectQueryMbrUserId = \"SELECT UserId FROM aspnet_Membership WHERE UserId = ?\";\n\t\t\t\tOleDbCommand selectCmdMbrUserId = new OleDbCommand (selectQueryMbrUserId, (OleDbConnection) connection);\n\t\t\t\tselectCmdMbrUserId.Transaction = trans;\n\t\t\t\tAddParameter (selectCmdMbrUserId, \"UserId\", newUserId);\n\t\t\t\tusing (OleDbDataReader reader = selectCmdMbrUserId.ExecuteReader ()) {\n\t\t\t\t\tif (reader.Read ()) {\n\t\t\t\t\t\ttrans.Rollback ();\n\t\t\t\t\t\treturn 2; // user with such userId already exists\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (uniqueEmail) {\n\t\t\t\t\tstring queryMbrEmail = \"SELECT * FROM aspnet_Membership WHERE ApplicationId = ? AND LoweredEmail = ?\";\n\t\t\t\t\tOleDbCommand cmdMbrEmail = new OleDbCommand (queryMbrEmail, (OleDbConnection) connection);\n\t\t\t\t\tcmdMbrEmail.Transaction = trans;\n\t\t\t\t\tAddParameter (cmdMbrEmail, \"ApplicationId\", applicationId);\n\t\t\t\t\tAddParameter (cmdMbrEmail, \"LoweredEmail\", email.ToLowerInvariant ());\n\t\t\t\t\tusing (OleDbDataReader reader = cmdMbrEmail.ExecuteReader ()) {\n\t\t\t\t\t\tif (reader.Read ()) {\n\t\t\t\t\t\t\ttrans.Rollback ();\n\t\t\t\t\t\t\treturn 3; // user with such email already exists\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (returnValue == 1) {\n\t\t\t\t\t// if user was not created, but found existing and correct\n\t\t\t\t\t// update it's activity (membership create) time.\n\t\t\t\t\tstring queryUpdActivity = \"UPDATE aspnet_Users SET LastActivityDate = ? WHERE UserId = ?\";\n\t\t\t\t\tOleDbCommand cmdUpdActivity = new OleDbCommand (queryUpdActivity, (OleDbConnection) connection);\n\t\t\t\t\tcmdUpdActivity.Transaction = trans;\n\t\t\t\t\tAddParameter (cmdUpdActivity, \"LastActivityDate\", createDate);\n\t\t\t\t\tAddParameter (cmdUpdActivity, \"UserId\", newUserId);\n\t\t\t\t\tcmdUpdActivity.ExecuteNonQuery ();\n\t\t\t\t}\n\n\t\t\t\tstring queryInsertMbr = \"INSERT INTO aspnet_Membership (ApplicationId, UserId, Password, PasswordFormat, PasswordSalt, Email, \" +\n\t\t\t\t\t\"LoweredEmail, PasswordQuestion, PasswordAnswer, IsApproved, IsLockedOut, CreateDate, LastLoginDate, \" +\n\t\t\t\t\t\"LastPasswordChangedDate, LastLockoutDate, FailedPasswordAttemptCount, FailedPwdAttemptWindowStart, \" +\n\t\t\t\t\t\"FailedPwdAnswerAttemptCount, FailedPwdAnswerAttWindowStart) \" +\n\t\t\t\t\t\"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\";\n\t\t\t\tOleDbCommand cmdInsertMbr = new OleDbCommand (queryInsertMbr, (OleDbConnection) connection);\n\t\t\t\tcmdInsertMbr.Transaction = trans;\n\t\t\t\tAddParameter (cmdInsertMbr, \"ApplicationId\", applicationId);\n\t\t\t\tAddParameter (cmdInsertMbr, \"UserId\", newUserId);\n\t\t\t\tAddParameter (cmdInsertMbr, \"Password\", password);\n\t\t\t\tAddParameter (cmdInsertMbr, \"PasswordFormat\", passwordFormat);\n\t\t\t\tAddParameter (cmdInsertMbr, \"PasswordSalt\", passwordSalt);\n\t\t\t\tAddParameter (cmdInsertMbr, \"Email\", email);\n\t\t\t\tAddParameter (cmdInsertMbr, \"LoweredEmail\", email != null ? email.ToLowerInvariant () : null);\n\t\t\t\tAddParameter (cmdInsertMbr, \"PasswordQuestion\", pwdQuestion);\n\t\t\t\tAddParameter (cmdInsertMbr, \"PasswordAnswer\", pwdAnswer);\n\t\t\t\tAddParameter (cmdInsertMbr, \"IsApproved\", isApproved);\n\t\t\t\tAddParameter (cmdInsertMbr, \"IsLockedOut\", 0);\n\t\t\t\tAddParameter (cmdInsertMbr, \"CreateDate\", createDate);\n\t\t\t\tAddParameter (cmdInsertMbr, \"LastLoginDate\", DefaultDateTime);\n\t\t\t\tAddParameter (cmdInsertMbr, \"LastPasswordChangedDate\", createDate);\n\t\t\t\tAddParameter (cmdInsertMbr, \"LastLockoutDate\", DefaultDateTime);\n\t\t\t\tAddParameter (cmdInsertMbr, \"FailedPasswordAttemptCount\", 0);\n\t\t\t\tAddParameter (cmdInsertMbr, \"FailedPwdAttemptWindowStart\", DefaultDateTime);\n\t\t\t\tAddParameter (cmdInsertMbr, \"FailedPwdAnswerAttemptCount\", 0);\n\t\t\t\tAddParameter (cmdInsertMbr, \"FailedPwdAnswerAttWindowStart\", DefaultDateTime);\n\t\t\t\tcmdInsertMbr.ExecuteNonQuery ();\n\n\t\t\t\ttrans.Commit ();\n\t\t\t}\n\t\t\tcatch (Exception e) {\n\t\t\t\ttrans.Rollback ();\n\t\t\t\tthrow e;\n\t\t\t}\n\n\t\t\treturn 0;\n\t\t}\n\n\t\tpublic static int Membership_FindUsersByEmail (DbConnection connection, string applicationName, string emailToMatch, int pageIndex, int pageSize, out DbDataReader reader)\n\t\t{\n\t\t\tstring querySelect = \"SELECT usr.UserName, mbr.UserId, mbr.Email, mbr.PasswordQuestion, mbr.Comment, mbr.IsApproved, \" +\n\t\t\t\t\"mbr.IsLockedOut, mbr.CreateDate, mbr.LastLoginDate, usr.LastActivityDate, mbr.LastPasswordChangedDate, mbr.LastLockoutDate \" +\n\t\t\t\t\"FROM aspnet_Membership mbr, aspnet_Users usr \" +\n\t\t\t\t\"WHERE usr.UserId = mbr.UserId AND mbr.LoweredEmail LIKE ? ORDER BY usr.LoweredUserName\";\n\t\t\tOleDbCommand cmdSelect = new OleDbCommand (querySelect, (OleDbConnection) connection);\n\t\t\tAddParameter (cmdSelect, \"LoweredEmail\", emailToMatch.ToLowerInvariant ());\n\t\t\treader = cmdSelect.ExecuteReader ();\n\t\t\treturn 0;\n\t\t}\n\n\t\tpublic static int Membership_FindUsersByName (DbConnection connection, string applicationName, string userNameToMatch, int pageIndex, int pageSize, out DbDataReader reader)\n\t\t{\n\t\t\tstring querySelect = \"SELECT usr.UserName, mbr.UserId, mbr.Email, mbr.PasswordQuestion, mbr.Comment, mbr.IsApproved, \" +\n\t\t\t\t\"mbr.IsLockedOut, mbr.CreateDate, mbr.LastLoginDate, usr.LastActivityDate, mbr.LastPasswordChangedDate, mbr.LastLockoutDate \" +\n\t\t\t\t\"FROM aspnet_Membership mbr, aspnet_Users usr \" +\n\t\t\t\t\"WHERE usr.UserId = mbr.UserId AND usr.LoweredUserName LIKE ? ORDER BY usr.LoweredUserName\";\n\t\t\tOleDbCommand cmdSelect = new OleDbCommand (querySelect, (OleDbConnection) connection);\n\t\t\tAddParameter (cmdSelect, \"LoweredUserName\", userNameToMatch.ToLowerInvariant ());\n\t\t\treader = cmdSelect.ExecuteReader ();\n\t\t\treturn 0;\n\t\t}\n\n\t\tpublic static int Membership_GetAllUsers (DbConnection connection, string applicationName, int pageIndex, int pageSize, out DbDataReader reader)\n\t\t{\n\t\t\tstring querySelect = \"SELECT usr.UserName, mbr.UserId, mbr.Email, mbr.PasswordQuestion, mbr.Comment, mbr.IsApproved, \" +\n\t\t\t\t\"mbr.IsLockedOut, mbr.CreateDate, mbr.LastLoginDate, usr.LastActivityDate, mbr.LastPasswordChangedDate, mbr.LastLockoutDate \" + \n\t\t\t\t\"FROM aspnet_Membership mbr, aspnet_Users usr \" +\n\t\t\t\t\"WHERE usr.UserId = mbr.UserId ORDER BY usr.LoweredUserName\";\n\t\t\tOleDbCommand cmdSelect = new OleDbCommand (querySelect, (OleDbConnection) connection);\n\t\t\treader = cmdSelect.ExecuteReader ();\n\t\t\treturn 0;\n\t\t}\n\n\t\tpublic static int Membership_GetNumberOfUsersOnline (DbConnection connection, string applicationName, int minutesSinceLastInActive, DateTime currentTimeUtc)\n\t\t{\n\t\t\tstring queryUsersActive = \"SELECT COUNT(*) FROM aspnet_Users usr, aspnet_Applications app, aspnet_Membership mbr \" +\n\t\t\t\t\"WHERE usr.ApplicationId = app.ApplicationId AND usr.LastActivityDate > ? AND \" +\n\t\t\t\t\"app.LoweredApplicationName = ? AND usr.UserId = mbr.UserId\";\n\n\n\t\t\tOleDbCommand cmdUsersActive = new OleDbCommand (queryUsersActive, (OleDbConnection) connection);\n\t\t\tAddParameter (cmdUsersActive, \"LastActivityDate\", currentTimeUtc.AddMinutes (-minutesSinceLastInActive));\n\t\t\tAddParameter (cmdUsersActive, \"LoweredApplicationName\", applicationName.ToLowerInvariant ());\n\t\t\tusing (OleDbDataReader reader = cmdUsersActive.ExecuteReader ()) {\n\t\t\t\tif (reader.Read ())\n\t\t\t\t\treturn reader.GetInt32 (0);\n\t\t\t}\n\t\t\treturn 0;\n\t\t}\n\n\t\tpublic static int Membership_GetPassword (DbConnection connection, string applicationName, string username, string passwordAnswer, int maxInvalidPasswordAttempts, int passwordAttemptWindow, DateTime currentTimeUtc, out string password)\n\t\t{\n\t\t\tstring querySelect = \"SELECT usr.UserId, mbr.Password, mbr.PasswordAnswer, mbr.IsLockedOut, \" +\n\t\t\t\t\"mbr.LastLockoutDate, mbr.FailedPwdAnswerAttemptCount, mbr.FailedPwdAnswerAttWindowStart \" +\n\t\t\t\t\"FROM aspnet_Applications app, aspnet_Users usr, aspnet_Membership mbr \" +\n\t\t\t\t\"WHERE app.LoweredApplicationName = ? AND usr.ApplicationId = app.ApplicationId \" +\n\t\t\t\t\"AND usr.UserId = mbr.UserId AND usr.LoweredUserName = ?\";\n\t\t\tOleDbCommand cmdSelect = new OleDbCommand (querySelect, (OleDbConnection) connection);\n\t\t\tAddParameter (cmdSelect, \"LoweredApplicationName\", applicationName.ToLowerInvariant ());\n\t\t\tAddParameter (cmdSelect, \"LoweredUserName\", username.ToLowerInvariant ());\n\n\t\t\tpassword = null;\n\t\t\tstring dbUserId = null;\n\t\t\tstring dbPassword = null;\n\t\t\tstring dbPasswordAns = null;\n\t\t\tbool dbLockedOut = false;\n\t\t\tDateTime dbLastLockoutDate;\n\t\t\tint dbFailedPasswordAnswerAttemptCount = 0;\n\t\t\tDateTime dbFailedPasswordAnswerAttemptWindowStart;\n\n\t\t\tusing (OleDbDataReader reader = cmdSelect.ExecuteReader ()) {\n\t\t\t\tif (reader.Read ()) {\n\t\t\t\t\tdbUserId = reader.GetString (0);\n\t\t\t\t\tdbPassword = reader.GetString (1);\n\t\t\t\t\tdbPasswordAns = reader.GetString (2);\n\t\t\t\t\tdbLockedOut = reader.GetInt32 (3) > 0;\n\t\t\t\t\tdbLastLockoutDate = reader.GetDateTime (4);\n\t\t\t\t\tdbFailedPasswordAnswerAttemptCount = reader.GetInt32 (5);\n\t\t\t\t\tdbFailedPasswordAnswerAttemptWindowStart = reader.GetDateTime (6);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\treturn 1; // user not found\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (dbLockedOut)\n\t\t\t\treturn 2; // locked out\n\n\t\t\tif (dbPasswordAns != passwordAnswer) {\n\t\t\t\tif (currentTimeUtc > dbFailedPasswordAnswerAttemptWindowStart.AddMinutes (passwordAttemptWindow)) {\n\t\t\t\t\tdbFailedPasswordAnswerAttemptWindowStart = currentTimeUtc;\n\t\t\t\t\tdbFailedPasswordAnswerAttemptCount = 1;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tdbFailedPasswordAnswerAttemptWindowStart = currentTimeUtc;\n\t\t\t\t\tdbFailedPasswordAnswerAttemptCount++;\n\t\t\t\t}\n\n\t\t\t\tif (dbFailedPasswordAnswerAttemptCount > maxInvalidPasswordAttempts) {\n\t\t\t\t\tdbLockedOut = true;\n\t\t\t\t\tdbLastLockoutDate = currentTimeUtc;\n\t\t\t\t}\n\t\t\t\treturn 3; // wrong password answer\n\t\t\t}\n\t\t\telse {\n\t\t\t\tdbFailedPasswordAnswerAttemptCount = 0;\n\t\t\t\tdbFailedPasswordAnswerAttemptWindowStart = DefaultDateTime;\n\t\t\t\tpassword = dbPassword;\n\t\t\t}\n\n\t\t\tstring queryUpdate = \"UPDATE aspnet_Membership SET IsLockedOut = ?, LastLockoutDate = ?, \" +\n\t\t\t\t\"FailedPwdAnswerAttemptCount = ?, FailedPwdAnswerAttWindowStart = ? \" +\n\t\t\t\t\"WHERE UserId = ?\";\n\t\t\tOleDbCommand cmdUpdate = new OleDbCommand (queryUpdate, (OleDbConnection) connection);\n\t\t\tAddParameter (cmdUpdate, \"IsLockedOut\", dbLockedOut);\n\t\t\tAddParameter (cmdUpdate, \"LastLockoutDate\", dbLastLockoutDate);\n\t\t\tAddParameter (cmdUpdate, \"FailedPwdAnswerAttemptCount\", dbFailedPasswordAnswerAttemptCount);\n\t\t\tAddParameter (cmdUpdate, \"FailedPwdAnswerAttWindowStart\", dbFailedPasswordAnswerAttemptWindowStart);\n\t\t\tAddParameter (cmdUpdate, \"UserId\", dbUserId);", "answers": ["\t\t\tcmdUpdate.ExecuteNonQuery ();"], "length": 1390, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "06b8eff0-c329-4a10-abd0-c94eb070b0e3", "reasoning": "The method is preparing an UPDATE command to persist lockout and password‑answer attempt changes. After adding all parameters, the next logical step is to execute the command. Consistent with earlier code (e.g., cmdInsertMbr.ExecuteNonQuery ()), the next line should be the ExecuteNonQuery call on cmdUpdate.", "reasoning_model_answer": "cmdUpdate.ExecuteNonQuery ();", "assistant_with_reasoning": "\nThe method is preparing an UPDATE command to persist lockout and password‑answer attempt changes. After adding all parameters, the next logical step is to execute the command. Consistent with earlier code (e.g., cmdInsertMbr.ExecuteNonQuery ()), the next line should be the ExecuteNonQuery call on cmdUpdate.\n\ncmdUpdate.ExecuteNonQuery ();", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.003, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 13880, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "cmdUpdate.ExecuteNonQuery ();", "score": 0.95, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "# Copyright 2019 The Cirq Developers\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport abc\nfrom typing import Any, Dict, List, TYPE_CHECKING\nimport numpy as np\n\nfrom cirq import protocols\nfrom cirq.value import big_endian_int_to_digits, linear_dict\n\nif TYPE_CHECKING:\n import cirq\n\n\nclass StabilizerState(metaclass=abc.ABCMeta):\n \"\"\"Interface for quantum stabilizer state representations.\n\n This interface is used for CliffordTableau and StabilizerChForm quantum\n state representations, allowing simulators to act on them abstractly.\n \"\"\"\n\n @abc.abstractmethod\n def apply_x(self, axis: int, exponent: float = 1, global_shift: float = 0):\n \"\"\"Apply an X operation to the state.\n\n Args:\n axis: The axis to which the operation should be applied.\n exponent: The exponent of the X operation, must be a half-integer.\n global_shift: The global phase shift of the raw operation, prior to\n exponentiation. Typically the value in `gate.global_shift`.\n Raises:\n ValueError: If the exponent is not half-integer.\n \"\"\"\n\n @abc.abstractmethod\n def apply_y(self, axis: int, exponent: float = 1, global_shift: float = 0):\n \"\"\"Apply an Y operation to the state.\n\n Args:\n axis: The axis to which the operation should be applied.\n exponent: The exponent of the Y operation, must be a half-integer.\n global_shift: The global phase shift of the raw operation, prior to\n exponentiation. Typically the value in `gate.global_shift`.\n Raises:\n ValueError: If the exponent is not half-integer.\n \"\"\"\n\n @abc.abstractmethod\n def apply_z(self, axis: int, exponent: float = 1, global_shift: float = 0):\n \"\"\"Apply a Z operation to the state.\n\n Args:\n axis: The axis to which the operation should be applied.\n exponent: The exponent of the Z operation, must be a half-integer.\n global_shift: The global phase shift of the raw operation, prior to\n exponentiation. Typically the value in `gate.global_shift`.\n Raises:\n ValueError: If the exponent is not half-integer.\n \"\"\"\n\n @abc.abstractmethod\n def apply_h(self, axis: int, exponent: float = 1, global_shift: float = 0):\n \"\"\"Apply an H operation to the state.\n\n Args:\n axis: The axis to which the operation should be applied.\n exponent: The exponent of the H operation, must be an integer.\n global_shift: The global phase shift of the raw operation, prior to\n exponentiation. Typically the value in `gate.global_shift`.\n Raises:\n ValueError: If the exponent is not an integer.\n \"\"\"\n\n @abc.abstractmethod\n def apply_cz(\n self, control_axis: int, target_axis: int, exponent: float = 1, global_shift: float = 0\n ):\n \"\"\"Apply a CZ operation to the state.\n\n Args:\n control_axis: The control axis of the operation.\n target_axis: The axis to which the operation should be applied.\n exponent: The exponent of the CZ operation, must be an integer.\n global_shift: The global phase shift of the raw operation, prior to\n exponentiation. Typically the value in `gate.global_shift`.\n Raises:\n ValueError: If the exponent is not an integer.\n \"\"\"\n\n @abc.abstractmethod\n def apply_cx(\n self, control_axis: int, target_axis: int, exponent: float = 1, global_shift: float = 0\n ):\n \"\"\"Apply a CX operation to the state.\n\n Args:\n control_axis: The control axis of the operation.\n target_axis: The axis to which the operation should be applied.\n exponent: The exponent of the CX operation, must be an integer.\n global_shift: The global phase shift of the raw operation, prior to\n exponentiation. Typically the value in `gate.global_shift`.\n Raises:\n ValueError: If the exponent is not an integer.\n \"\"\"\n\n @abc.abstractmethod\n def apply_global_phase(self, coefficient: linear_dict.Scalar):\n \"\"\"Apply a global phase to the state.\n\n Args:\n coefficient: The global phase to apply.\n \"\"\"\n\n\nclass CliffordTableau(StabilizerState):\n \"\"\"Tableau representation of a stabilizer state\n (based on Aaronson and Gottesman 2006).\n\n The tableau stores the stabilizer generators of\n the state using three binary arrays: xs, zs, and rs.\n\n Each row of the arrays represents a Pauli string, P, that is\n an eigenoperator of the state vector with eigenvalue one: P|psi> = |psi>.\n \"\"\"\n\n def __init__(self, num_qubits, initial_state: int = 0):\n \"\"\"Initializes CliffordTableau\n Args:\n num_qubits: The number of qubits in the system.\n initial_state: The computational basis representation of the\n state as a big endian int.\n \"\"\"\n self.n = num_qubits\n\n # The last row (`2n+1`-th row) is the scratch row used in _measurement\n # computation process only. It should not be exposed to external usage.\n self._rs = np.zeros(2 * self.n + 1, dtype=bool)\n\n for (i, val) in enumerate(\n big_endian_int_to_digits(initial_state, digit_count=num_qubits, base=2)\n ):\n self._rs[self.n + i] = bool(val)\n\n self._xs = np.zeros((2 * self.n + 1, self.n), dtype=bool)\n self._zs = np.zeros((2 * self.n + 1, self.n), dtype=bool)\n\n for i in range(self.n):\n self._xs[i, i] = True\n self._zs[self.n + i, i] = True\n\n @property\n def xs(self) -> np.array:\n return self._xs[:-1, :]\n\n @xs.setter\n def xs(self, new_xs: np.array) -> None:\n assert np.shape(new_xs) == (2 * self.n, self.n)\n self._xs[:-1, :] = np.array(new_xs).astype(bool)\n\n @property\n def zs(self) -> np.array:\n return self._zs[:-1, :]\n\n @zs.setter\n def zs(self, new_zs: np.array) -> None:\n assert np.shape(new_zs) == (2 * self.n, self.n)\n self._zs[:-1, :] = np.array(new_zs).astype(bool)\n\n @property\n def rs(self) -> np.array:\n return self._rs[:-1]\n\n @rs.setter\n def rs(self, new_rs: np.array) -> None:\n assert np.shape(new_rs) == (2 * self.n,)\n self._rs[:-1] = np.array(new_rs).astype(bool)\n\n def matrix(self) -> np.array:\n \"\"\"Returns the 2n * 2n matrix representation of the Clifford tableau.\"\"\"\n return np.concatenate([self.xs, self.zs], axis=1)\n\n def _json_dict_(self) -> Dict[str, Any]:\n return protocols.obj_to_dict_helper(self, ['n', 'rs', 'xs', 'zs'])\n\n @classmethod\n def _from_json_dict_(cls, n, rs, xs, zs, **kwargs):\n state = cls(n)\n state.rs = np.array(rs).astype(bool)\n state.xs = np.array(xs).astype(bool)\n state.zs = np.array(zs).astype(bool)\n return state\n\n def _validate(self) -> bool:\n \"\"\"Check if the Clifford Tabluea satisfies the symplectic property.\"\"\"\n table = np.concatenate([self.xs, self.zs], axis=1)\n perm = list(range(self.n, 2 * self.n)) + list(range(self.n))\n skew_eye = np.eye(2 * self.n, dtype=int)[perm]\n return np.array_equal(np.mod(table.T.dot(skew_eye).dot(table), 2), skew_eye)\n\n def __eq__(self, other):\n if not isinstance(other, type(self)):\n # coverage: ignore\n return NotImplemented\n return (\n self.n == other.n\n and np.array_equal(self.rs, other.rs)\n and np.array_equal(self.xs, other.xs)\n and np.array_equal(self.zs, other.zs)\n )\n\n def __copy__(self) -> 'CliffordTableau':\n return self.copy()\n\n def copy(self) -> 'CliffordTableau':\n state = CliffordTableau(self.n)\n state.rs = self.rs.copy()\n state.xs = self.xs.copy()\n state.zs = self.zs.copy()\n return state\n\n def __repr__(self) -> str:\n stabilizers = \", \".join([repr(stab) for stab in self.stabilizers()])\n return f'stabilizers: [{stabilizers}]'\n\n def __str__(self) -> str:\n string = ''\n\n for i in range(self.n, 2 * self.n):\n string += '- ' if self.rs[i] else '+ '\n\n for k in range(0, self.n):\n if self.xs[i, k] & (not self.zs[i, k]):\n string += 'X '\n elif (not self.xs[i, k]) & self.zs[i, k]:\n string += 'Z '\n elif self.xs[i, k] & self.zs[i, k]:\n string += 'Y '\n else:\n string += 'I '\n\n if i < 2 * self.n - 1:\n string += '\\n'\n\n return string\n\n def _str_full_(self) -> str:\n string = ''\n\n string += 'stable' + ' ' * max(self.n * 2 - 3, 1)\n string += '| destable\\n'\n string += '-' * max(7, self.n * 2 + 3) + '+' + '-' * max(10, self.n * 2 + 4) + '\\n'\n\n for j in range(self.n):\n for i in [j + self.n, j]:\n string += '- ' if self.rs[i] else '+ '\n\n for k in range(0, self.n):\n if self.xs[i, k] & (not self.zs[i, k]):\n string += 'X%d' % k\n elif (not self.xs[i, k]) & self.zs[i, k]:\n string += 'Z%d' % k\n elif self.xs[i, k] & self.zs[i, k]:\n string += 'Y%d' % k\n else:\n string += ' '\n\n if i == j + self.n:\n string += ' ' * max(0, 4 - self.n * 2) + ' | '\n\n string += '\\n'\n\n return string\n\n def then(self, second: 'CliffordTableau') -> 'CliffordTableau':\n \"\"\"Returns a composed CliffordTableau of this tableau and the second tableau.\n\n Then composed tableau is equal to (up to global phase) the composed\n unitary operation of the two tableaux, i.e. equivalent to applying the unitary\n operation of this CliffordTableau then applying the second one.\n\n Args:\n second: The second CliffordTableau to compose with.\n\n Returns:\n The composed CliffordTableau.\n\n Raises:\n TypeError: If the type of second is not CliffordTableau.\n ValueError: If the number of qubits in the second tableau mismatch with\n this tableau.\n \"\"\"\n if not isinstance(second, CliffordTableau):\n raise TypeError(\"The type for second tableau must be the CliffordTableau type\")\n if self.n != second.n:\n raise ValueError(\n f\"Mismatched number of qubits of two tableaux: {self.n} vs {second.n}.\"\n )\n\n # Convert the underlying data type from bool to int for easier numerical computation.\n m1 = self.matrix().astype(int)\n m2 = second.matrix().astype(int)\n\n # The following computation is based on Theorem 36 in\n # https://arxiv.org/pdf/2009.03218.pdf.\n # Any pauli string (one stabilizer) in Clifford Tableau should be able to be expressed as\n # (1i)^p (-1)^s X^(mx) Z^(mz)\n # where p and s are binary scalar and mx and mz are binary vectors.\n num_ys1 = np.sum(m1[:, : self.n] * m1[:, self.n :], axis=1)\n num_ys2 = np.sum(m2[:, : self.n] * m2[:, self.n :], axis=1)\n\n p1 = np.mod(num_ys1, 2)\n p2 = np.mod(num_ys2, 2)\n\n # Note the `s` is not equal to `r`, which depends on the number of Y gates.\n # For example, r * Y_1Y_2Y_3 can be expanded into i^3 * r * X_1Z_1 X_2Z_2 X_3Z_3.\n # The global phase is i * (-1) * r ==> s = r + 1 and p = 1.\n s1 = self.rs.astype(int) + np.mod(num_ys1, 4) // 2\n s2 = second.rs.astype(int) + np.mod(num_ys2, 4) // 2\n\n lmbda = np.zeros((2 * self.n, 2 * self.n))\n lmbda[: self.n, self.n :] = np.eye(self.n)\n\n m_12 = np.mod(m1 @ m2, 2)\n p_12 = np.mod(p1 + m1 @ p2, 2)\n s_12 = (\n s1\n + m1 @ s2\n + p1 * (m1 @ p2)\n + np.diag(m1 @ np.tril(np.outer(p2, p2.T) + m2 @ lmbda @ m2.T, -1) @ m1.T)\n )\n num_ys12 = np.sum(m_12[:, : self.n] * m_12[:, self.n :], axis=1)\n merged_sign = np.mod(p_12 + 2 * s_12 - num_ys12, 4) // 2\n\n merged_tableau = CliffordTableau(num_qubits=self.n)\n merged_tableau.xs = m_12[:, : self.n]\n merged_tableau.zs = m_12[:, self.n :]\n merged_tableau.rs = merged_sign\n\n return merged_tableau\n\n def inverse(self) -> 'CliffordTableau':\n \"\"\"Returns the inverse Clifford tableau of this tableau.\"\"\"\n ret_table = CliffordTableau(num_qubits=self.n)\n # It relies on the symplectic property of Clifford tableau.\n # [A^T C^T [0 I [A B [0 I\n # B^T D^T] I 0] C D] = I 0]\n # So the inverse is [[D^T B^T], [C^T A^T]]\n ret_table.xs[: self.n] = self.zs[self.n :].T\n ret_table.zs[: self.n] = self.zs[: self.n].T\n ret_table.xs[self.n :] = self.xs[self.n :].T\n ret_table.zs[self.n :] = self.xs[: self.n].T\n\n # Update the sign -- rs.\n # The idea is noting the sign of tabluea `a` contributes to the composed tableau\n # `a.then(b)` directly. (While the sign in `b` need take very complicated transformation.)\n # Refer above `then` function implementation for more details.\n ret_table.rs = ret_table.then(self).rs\n return ret_table\n\n def __matmul__(self, second: 'CliffordTableau'):\n if not isinstance(second, CliffordTableau):\n return NotImplemented\n return second.then(self)\n\n def _rowsum(self, q1, q2):\n \"\"\"Implements the \"rowsum\" routine defined by\n Aaronson and Gottesman.\n Multiplies the stabilizer in row q1 by the stabilizer in row q2.\"\"\"\n\n def g(x1, z1, x2, z2):\n if not x1 and not z1:\n return 0\n elif x1 and z1:\n return int(z2) - int(x2)\n elif x1 and not z1:\n return int(z2) * (2 * int(x2) - 1)\n else:\n return int(x2) * (1 - 2 * int(z2))\n\n r = 2 * int(self._rs[q1]) + 2 * int(self._rs[q2])\n for j in range(self.n):\n r += g(self._xs[q2, j], self._zs[q2, j], self._xs[q1, j], self._zs[q1, j])\n\n r %= 4\n\n self._rs[q1] = bool(r)\n\n self._xs[q1, :] ^= self._xs[q2, :]\n self._zs[q1, :] ^= self._zs[q2, :]\n\n def _row_to_dense_pauli(self, i: int) -> 'cirq.DensePauliString':\n \"\"\"Return a dense Pauli string for the given row in the tableau.\n\n Args:\n i: index of the row in the tableau.\n\n Returns:\n A DensePauliString representing the row. The length of the string\n is equal to the total number of qubits and each character\n represents the effective single Pauli operator on that qubit. The\n overall phase is captured in the coefficient.\n \"\"\"\n from cirq.ops.dense_pauli_string import DensePauliString\n\n coefficient = -1 if self.rs[i] else 1\n pauli_mask = \"\"\n\n for k in range(self.n):\n if self.xs[i, k] & (not self.zs[i, k]):\n pauli_mask += \"X\"\n elif (not self.xs[i, k]) & self.zs[i, k]:\n pauli_mask += \"Z\"\n elif self.xs[i, k] & self.zs[i, k]:\n pauli_mask += \"Y\"\n else:\n pauli_mask += \"I\"\n return DensePauliString(pauli_mask, coefficient=coefficient)\n\n def stabilizers(self) -> List['cirq.DensePauliString']:\n \"\"\"Returns the stabilizer generators of the state. These\n are n operators {S_1,S_2,...,S_n} such that S_i |psi> = |psi>\"\"\"\n return [self._row_to_dense_pauli(i) for i in range(self.n, 2 * self.n)]\n", "answers": [" def destabilizers(self) -> List['cirq.DensePauliString']:"], "length": 1996, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "55d695f4-d133-4da6-887f-87f4717c3436", "reasoning": "The class CliffordTableau defines a stabilizers() method that returns the stabilizer generators (rows n to 2n-1). In Cirq's implementation, the next logical method provides the destabilizer generators (rows 0 to n-1). Therefore the next line after the stabilizers method is the definition of the destabilizers method.", "reasoning_model_answer": "def destabilizers(self) -> List['cirq.DensePauliString']:", "assistant_with_reasoning": "\nThe class CliffordTableau defines a stabilizers() method that returns the stabilizer generators (rows n to 2n-1). In Cirq's implementation, the next logical method provides the destabilizer generators (rows 0 to n-1). Therefore the next line after the stabilizers method is the definition of the destabilizers method.\n\ndef destabilizers(self) -> List['cirq.DensePauliString']:", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.418, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 16398, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "def destabilizers(self) -> List['cirq.DensePauliString']:", "score": 0.97, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "# Copyright (c) 2013 Dell Inc.\n# Copyright 2013 OpenStack LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\n\"\"\"Volume driver for Dell EqualLogic Storage.\"\"\"\n\nimport functools\nimport random\n\nimport eventlet\nfrom eventlet import greenthread\nimport greenlet\nfrom oslo_concurrency import processutils\nfrom oslo_config import cfg\nfrom oslo_log import log as logging\nfrom oslo_utils import excutils\n\nfrom cinder import exception\nfrom cinder.i18n import _, _LE, _LW, _LI\nfrom cinder import ssh_utils\nfrom cinder import utils\nfrom cinder.volume.drivers import san\n\nLOG = logging.getLogger(__name__)\n\neqlx_opts = [\n cfg.StrOpt('eqlx_group_name',\n default='group-0',\n help='Group name to use for creating volumes. Defaults to '\n '\"group-0\".'),\n cfg.IntOpt('eqlx_cli_timeout',\n default=30,\n help='Timeout for the Group Manager cli command execution. '\n 'Default is 30.'),\n cfg.IntOpt('eqlx_cli_max_retries',\n default=5,\n help='Maximum retry count for reconnection. Default is 5.'),\n cfg.BoolOpt('eqlx_use_chap',\n default=False,\n help='Use CHAP authentication for targets. Note that this '\n 'option is deprecated in favour of \"use_chap_auth\" as '\n 'specified in cinder/volume/driver.py and will be '\n 'removed in next release.'),\n cfg.StrOpt('eqlx_chap_login',\n default='admin',\n help='Existing CHAP account name. Note that this '\n 'option is deprecated in favour of \"chap_username\" as '\n 'specified in cinder/volume/driver.py and will be '\n 'removed in next release.'),\n cfg.StrOpt('eqlx_chap_password',\n default='password',\n help='Password for specified CHAP account name. Note that this '\n 'option is deprecated in favour of \"chap_password\" as '\n 'specified in cinder/volume/driver.py and will be '\n 'removed in the next release',\n secret=True),\n cfg.StrOpt('eqlx_pool',\n default='default',\n help='Pool in which volumes will be created. Defaults '\n 'to \"default\".')\n]\n\n\nCONF = cfg.CONF\nCONF.register_opts(eqlx_opts)\n\n\ndef with_timeout(f):\n @functools.wraps(f)\n def __inner(self, *args, **kwargs):\n timeout = kwargs.pop('timeout', None)\n gt = eventlet.spawn(f, self, *args, **kwargs)\n if timeout is None:\n return gt.wait()\n else:\n kill_thread = eventlet.spawn_after(timeout, gt.kill)\n try:\n res = gt.wait()\n except greenlet.GreenletExit:\n raise exception.VolumeBackendAPIException(\n data=\"Command timed out\")\n else:\n kill_thread.cancel()\n return res\n\n return __inner\n\n\nclass DellEQLSanISCSIDriver(san.SanISCSIDriver):\n \"\"\"Implements commands for Dell EqualLogic SAN ISCSI management.\n\n To enable the driver add the following line to the cinder configuration:\n volume_driver=cinder.volume.drivers.eqlx.DellEQLSanISCSIDriver\n\n Driver's prerequisites are:\n - a separate volume group set up and running on the SAN\n - SSH access to the SAN\n - a special user must be created which must be able to\n - create/delete volumes and snapshots;\n - clone snapshots into volumes;\n - modify volume access records;\n\n The access credentials to the SAN are provided by means of the following\n flags\n san_ip=\n san_login=\n san_password=\n san_private_key=\n\n Thin provision of volumes is enabled by default, to disable it use:\n san_thin_provision=false\n\n In order to use target CHAP authentication (which is disabled by default)\n SAN administrator must create a local CHAP user and specify the following\n flags for the driver:\n use_chap_auth=True\n chap_login=\n chap_password=\n\n eqlx_group_name parameter actually represents the CLI prompt message\n without '>' ending. E.g. if prompt looks like 'group-0>', then the\n parameter must be set to 'group-0'\n\n Also, the default CLI command execution timeout is 30 secs. Adjustable by\n eqlx_cli_timeout=\n \"\"\"\n\n VERSION = \"1.1.0\"\n\n def __init__(self, *args, **kwargs):\n super(DellEQLSanISCSIDriver, self).__init__(*args, **kwargs)\n self.configuration.append_config_values(eqlx_opts)\n self._group_ip = None\n self.sshpool = None\n\n if self.configuration.eqlx_use_chap is True:\n LOG.warning(_LW(\n 'Configuration options eqlx_use_chap, '\n 'eqlx_chap_login and eqlx_chap_password are deprecated. Use '\n 'use_chap_auth, chap_username and chap_password '\n 'respectively for the same.'))\n\n self.configuration.use_chap_auth = \\\n self.configuration.eqlx_use_chap\n self.configuration.chap_username = \\\n self.configuration.eqlx_chap_login\n self.configuration.chap_password = \\\n self.configuration.eqlx_chap_password\n\n def _get_output(self, chan):\n out = ''\n ending = '%s> ' % self.configuration.eqlx_group_name\n while out.find(ending) == -1:\n ret = chan.recv(102400)\n if len(ret) == 0:\n # According to paramiko.channel.Channel documentation, which\n # says \"If a string of length zero is returned, the channel\n # stream has closed\". So we can confirm that the EQL server\n # has closed the connection.\n msg = _(\"The EQL array has closed the connection.\")\n LOG.error(msg)\n raise exception.VolumeBackendAPIException(data=msg)\n out += ret\n\n LOG.debug(\"CLI output\\n%s\", out)\n return out.splitlines()\n\n def _get_prefixed_value(self, lines, prefix):\n for line in lines:\n if line.startswith(prefix):\n return line[len(prefix):]\n return\n\n @with_timeout\n def _ssh_execute(self, ssh, command, *arg, **kwargs):\n transport = ssh.get_transport()\n chan = transport.open_session()\n completed = False\n\n try:\n chan.invoke_shell()\n\n LOG.debug(\"Reading CLI MOTD\")\n self._get_output(chan)\n\n cmd = 'stty columns 255'\n LOG.debug(\"Setting CLI terminal width: '%s'\", cmd)\n chan.send(cmd + '\\r')\n out = self._get_output(chan)\n\n LOG.debug(\"Sending CLI command: '%s'\", command)\n chan.send(command + '\\r')\n out = self._get_output(chan)\n\n completed = True\n\n if any(ln.startswith(('% Error', 'Error:')) for ln in out):\n desc = _(\"Error executing EQL command\")\n cmdout = '\\n'.join(out)\n LOG.error(_LE(\"%s\"), cmdout)\n raise processutils.ProcessExecutionError(\n stdout=cmdout, cmd=command, description=desc)\n return out\n finally:\n if not completed:\n LOG.debug(\"Timed out executing command: '%s'\", command)\n chan.close()\n\n def _run_ssh(self, cmd_list, attempts=1):\n utils.check_ssh_injection(cmd_list)\n command = ' '. join(cmd_list)\n\n if not self.sshpool:\n password = self.configuration.san_password\n privatekey = self.configuration.san_private_key\n min_size = self.configuration.ssh_min_pool_conn\n max_size = self.configuration.ssh_max_pool_conn\n self.sshpool = ssh_utils.SSHPool(\n self.configuration.san_ip,\n self.configuration.san_ssh_port,\n self.configuration.ssh_conn_timeout,\n self.configuration.san_login,\n password=password,\n privatekey=privatekey,\n min_size=min_size,\n max_size=max_size)\n try:\n total_attempts = attempts\n with self.sshpool.item() as ssh:\n while attempts > 0:\n attempts -= 1\n try:\n LOG.info(_LI('EQL-driver: executing \"%s\".'), command)\n return self._ssh_execute(\n ssh, command,\n timeout=self.configuration.eqlx_cli_timeout)\n except Exception:\n LOG.exception(_LE('Error running command.'))\n greenthread.sleep(random.randint(20, 500) / 100.0)\n msg = (_(\"SSH Command failed after '%(total_attempts)r' \"\n \"attempts : '%(command)s'\") %\n {'total_attempts': total_attempts - attempts,\n 'command': command})\n raise exception.VolumeBackendAPIException(data=msg)\n\n except Exception:\n with excutils.save_and_reraise_exception():\n LOG.error(_LE('Error running SSH command: \"%s\".'), command)\n\n def check_for_setup_error(self):\n super(DellEQLSanISCSIDriver, self).check_for_setup_error()\n if self.configuration.eqlx_cli_max_retries < 0:\n raise exception.InvalidInput(\n reason=_(\"eqlx_cli_max_retries must be greater than or \"\n \"equal to 0\"))\n\n def _eql_execute(self, *args, **kwargs):\n return self._run_ssh(\n args, attempts=self.configuration.eqlx_cli_max_retries + 1)\n\n def _get_volume_data(self, lines):\n prefix = 'iSCSI target name is '\n target_name = self._get_prefixed_value(lines, prefix)[:-1]\n lun_id = \"%s:%s,1 %s 0\" % (self._group_ip, '3260', target_name)\n model_update = {}\n model_update['provider_location'] = lun_id\n if self.configuration.use_chap_auth:\n model_update['provider_auth'] = 'CHAP %s %s' % \\\n (self.configuration.chap_username,\n self.configuration.chap_password)\n return model_update\n\n def _get_space_in_gb(self, val):\n scale = 1.0\n part = 'GB'\n if val.endswith('MB'):\n scale = 1.0 / 1024\n part = 'MB'\n elif val.endswith('TB'):\n scale = 1.0 * 1024\n part = 'TB'\n return scale * float(val.partition(part)[0])\n\n def _update_volume_stats(self):\n \"\"\"Retrieve stats info from eqlx group.\"\"\"\n\n LOG.debug('Updating volume stats.')\n data = {}\n backend_name = \"eqlx\"\n if self.configuration:\n backend_name = self.configuration.safe_get('volume_backend_name')\n data[\"volume_backend_name\"] = backend_name or 'eqlx'\n data[\"vendor_name\"] = 'Dell'\n data[\"driver_version\"] = self.VERSION\n data[\"storage_protocol\"] = 'iSCSI'\n\n data['reserved_percentage'] = 0\n data['QoS_support'] = False\n\n data['total_capacity_gb'] = 0\n data['free_capacity_gb'] = 0\n\n for line in self._eql_execute('pool', 'select',\n self.configuration.eqlx_pool, 'show'):\n if line.startswith('TotalCapacity:'):\n out_tup = line.rstrip().partition(' ')\n data['total_capacity_gb'] = self._get_space_in_gb(out_tup[-1])\n if line.startswith('FreeSpace:'):\n out_tup = line.rstrip().partition(' ')\n data['free_capacity_gb'] = self._get_space_in_gb(out_tup[-1])\n\n self._stats = data\n\n def _check_volume(self, volume):\n \"\"\"Check if the volume exists on the Array.\"\"\"\n command = ['volume', 'select', volume['name'], 'show']\n try:\n self._eql_execute(*command)\n except processutils.ProcessExecutionError as err:\n with excutils.save_and_reraise_exception():\n if err.stdout.find('does not exist.\\n') > -1:\n LOG.debug('Volume %s does not exist, '\n 'it may have already been deleted',\n volume['name'])\n raise exception.VolumeNotFound(volume_id=volume['id'])\n\n def _parse_connection(self, connector, out):\n \"\"\"Returns the correct connection id for the initiator.\n\n This parses the cli output from the command\n 'volume select access show'\n and returns the correct connection id.\n \"\"\"\n lines = [line for line in out if line != '']\n # Every record has 2 lines\n for i in xrange(0, len(lines), 2):\n try:\n int(lines[i][0])\n # sanity check\n if len(lines[i + 1].split()) == 1:\n check = lines[i].split()[1] + lines[i + 1].strip()\n if connector['initiator'] == check:\n return lines[i].split()[0]\n except (IndexError, ValueError):\n pass # skip the line that is not a valid access record\n\n return None\n\n def do_setup(self, context):\n \"\"\"Disable cli confirmation and tune output format.\"\"\"\n try:\n disabled_cli_features = ('confirmation', 'paging', 'events',\n 'formatoutput')\n for feature in disabled_cli_features:\n self._eql_execute('cli-settings', feature, 'off')\n\n for line in self._eql_execute('grpparams', 'show'):\n if line.startswith('Group-Ipaddress:'):\n out_tup = line.rstrip().partition(' ')\n self._group_ip = out_tup[-1]\n\n LOG.info(_LI('EQL-driver: Setup is complete, group IP is \"%s\".'),\n self._group_ip)\n except Exception:\n with excutils.save_and_reraise_exception():\n LOG.error(_LE('Failed to setup the Dell EqualLogic driver.'))\n\n def create_volume(self, volume):\n \"\"\"Create a volume.\"\"\"\n try:\n cmd = ['volume', 'create',\n volume['name'], \"%sG\" % (volume['size'])]\n if self.configuration.eqlx_pool != 'default':\n cmd.append('pool')\n cmd.append(self.configuration.eqlx_pool)\n if self.configuration.san_thin_provision:\n cmd.append('thin-provision')\n out = self._eql_execute(*cmd)\n self.add_multihost_access(volume)\n return self._get_volume_data(out)\n except Exception:\n with excutils.save_and_reraise_exception():\n LOG.error(_LE('Failed to create volume \"%s\".'), volume['name'])\n\n def add_multihost_access(self, volume):\n \"\"\"Add multihost-access to a volume. Needed for live migration.\"\"\"\n try:\n cmd = ['volume', 'select',\n volume['name'], 'multihost-access', 'enable']\n self._eql_execute(*cmd)\n except Exception:\n with excutils.save_and_reraise_exception():\n LOG.error(_LE('Failed to add multihost-access '\n 'for volume \"%s\".'),\n volume['name'])\n\n def delete_volume(self, volume):\n \"\"\"Delete a volume.\"\"\"\n try:\n self._check_volume(volume)\n self._eql_execute('volume', 'select', volume['name'], 'offline')", "answers": [" self._eql_execute('volume', 'delete', volume['name'])"], "length": 1346, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "b93be902-21cb-4524-a84c-40d173d12cc8", "reasoning": "The delete_volume method first checks the volume exists, then takes it offline with the 'offline' command. The logical next step is to actually delete the volume, which is done by issuing a 'delete' command via _eql_execute with the same arguments pattern.", "reasoning_model_answer": "self._eql_execute('volume', 'select', volume['name'], 'delete')", "assistant_with_reasoning": "\nThe delete_volume method first checks the volume exists, then takes it offline with the 'offline' command. The logical next step is to actually delete the volume, which is done by issuing a 'delete' command via _eql_execute with the same arguments pattern.\n\nself._eql_execute('volume', 'select', volume['name'], 'delete')", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.292, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 16219, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "self._eql_execute('volume', 'select', volume['name'], 'delete')", "score": 0.8, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/*\n Copyright 2021 Jeffrey Sharp\n\n Permission to use, copy, modify, and distribute this software for any\n purpose with or without fee is hereby granted, provided that the above\n copyright notice and this permission notice appear in all copies.\n\n THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n*/\n\nusing System.Management.Automation;\nusing NUnit.Framework;\n\nnamespace PSql.Tests.Unit;\n\nusing Case = TestCaseData;\n\n[TestFixture]\n[Parallelizable(ParallelScope.All)]\npublic class NewSqlContextCommandTests\n{\n [Test]\n public void Default()\n {\n @\"\n New-SqlContext\n \"\n .ShouldOutput(\n new SqlContext()\n );\n }\n\n public static IEnumerable StringCases = new[]\n {\n new Case(\"$null\", null),\n new Case(\"''\", null),\n new Case(\"'a'\", \"a\" )\n };\n\n public static IEnumerable SwitchCases = new[]\n {\n new Case(\"\", true),\n new Case(\":$true\", true),\n new Case(\":$false\", false)\n };\n\n #region -ResourceGroupName\n\n [Test]\n [TestCaseSource(nameof(StringCases))]\n public void ResourceGroupName_Set_Valid(string expression, string? value)\n {\n @$\"\n New-SqlContext -Azure -ResourceGroupName {expression}\n \"\n .ShouldOutput(\n new AzureSqlContext { ServerResourceGroupName = value }\n );\n }\n\n [Test]\n public void ResourceGroupName_Set_NonAzure()\n {\n @$\"\n New-SqlContext -ResourceGroupName x\n \"\n .ShouldThrow(\n \"Parameter set cannot be resolved using the specified named parameters.\"\n );\n }\n\n [Test]\n [TestCaseSource(nameof(StringCases))]\n public void ResourceGroupName_Override_Valid(string expression, string? value)\n {\n @$\"\n New-SqlContext -Azure -ResourceGroupName x | New-SqlContext -ResourceGroupName {expression}\n \"\n .ShouldOutput(\n new AzureSqlContext { ServerResourceGroupName = value }\n );\n }\n\n [Test]\n public void ResourceGroupName_Override_NonAzure()\n {\n @$\"\n New-SqlContext | New-SqlContext -ResourceGroupName x\n \"\n .ShouldOutput(\n new PSWarning(\"The 'ResourceGroupName' argument was ignored because the context is not an Azure SQL Database context.\"),\n new SqlContext()\n );\n }\n\n #endregion\n #region -ServerResourceName\n\n [Test]\n [TestCaseSource(nameof(StringCases))]\n public void ServerResourceName_Set_Valid(string expression, string? value)\n {\n @$\"\n New-SqlContext -Azure -ServerResourceName {expression}\n \"\n .ShouldOutput(\n new AzureSqlContext { ServerResourceName = value }\n );\n }\n\n [Test]\n public void ServerResourceName_Set_NonAzure()\n {\n @$\"\n New-SqlContext -ServerResourceName x\n \"\n .ShouldThrow(\n \"Parameter set cannot be resolved using the specified named parameters.\"\n );\n }\n\n [Test]\n [TestCaseSource(nameof(StringCases))]\n public void ServerResourceName_Override_Valid(string expression, string? value)\n {\n @$\"\n New-SqlContext -Azure -ServerResourceName x | New-SqlContext -ServerResourceName {expression}\n \"\n .ShouldOutput(\n new AzureSqlContext { ServerResourceName = value }\n );\n }\n\n [Test]\n public void ServerResourceName_Override_NonAzure()\n {\n @$\"\n New-SqlContext | New-SqlContext -ServerResourceName x\n \"\n .ShouldOutput(\n new PSWarning(\"The 'ServerResourceName' argument was ignored because the context is not an Azure SQL Database context.\"),\n new SqlContext()\n );\n }\n\n #endregion\n #region -ServerName\n\n [Test]\n [TestCaseSource(nameof(StringCases))]\n public void ServerName_Set_Valid(string expression, string? value)\n {\n @$\"\n New-SqlContext -ServerName {expression}\n \"\n .ShouldOutput(\n new SqlContext { ServerName = value }\n );\n }\n\n [Test]\n [TestCaseSource(nameof(StringCases))]\n public void ServerName_Override_Valid(string expression, string? value)\n {\n @$\"\n New-SqlContext -ServerName x | New-SqlContext -ServerName {expression}\n \"\n .ShouldOutput(\n new SqlContext { ServerName = value }\n );\n }\n\n #endregion\n #region -ServerPort\n\n public static IEnumerable ValidPortCases = new[]\n {\n new Case(\"$null\", null),\n new Case(\"1\", (ushort?) 1),\n new Case(\"65535\", (ushort?) 65535)\n };\n\n public static IEnumerable InvalidPortCases = new[]\n {\n new Case(\"''\", @\"Cannot validate argument on parameter 'ServerPort'. The value \"\"0\"\" is not a positive number.\"),\n new Case(\"0\", @\"Cannot validate argument on parameter 'ServerPort'. The value \"\"0\"\" is not a positive number.\"),\n new Case(\"-1\", @\"Cannot bind parameter 'ServerPort'. Cannot convert value \"\"\" + @\"-1\"\" to type \"\"System.UInt16\"\". Error: \"\"Value was either too large or too small for a UInt16.\"\"\"),\n new Case(\"65536\", @\"Cannot bind parameter 'ServerPort'. Cannot convert value \"\"\" + @\"65536\"\" to type \"\"System.UInt16\"\". Error: \"\"Value was either too large or too small for a UInt16.\"\"\")\n };\n\n [Test]\n [TestCaseSource(nameof(ValidPortCases))]\n public void ServerPort_Set_Valid(string expression, ushort? value)\n {\n @$\"\n New-SqlContext -ServerPort {expression}\n \"\n .ShouldOutput(\n new SqlContext { ServerPort = value }\n );\n }\n\n [Test]\n [TestCaseSource(nameof(InvalidPortCases))]\n public void ServerPort_Invalid(string expression, string message)\n {\n @$\"\n New-SqlContext -ServerPort {expression}\n \"\n .ShouldThrow(message);\n }\n\n [Test]\n [TestCaseSource(nameof(ValidPortCases))]\n public void ServerPort_Override_Valid(string expression, ushort? value)\n {\n @$\"\n New-SqlContext -ServerPort 42 | New-SqlContext -ServerPort {expression}\n \"\n .ShouldOutput(\n new SqlContext { ServerPort = value }\n );\n }\n\n [Test]\n [TestCaseSource(nameof(InvalidPortCases))]\n public void ServerPort_Override_Invalid(string expression, string message)\n {\n @$\"\n New-SqlContext -ServerPort 1337 | New-SqlContext -ServerPort {expression}\n \"\n .ShouldThrow(message);\n }\n\n #endregion\n #region -InstanceName\n\n [Test]\n [TestCaseSource(nameof(StringCases))]\n public void InstanceName_Set_Valid(string expression, string? value)\n {\n @$\"\n New-SqlContext -InstanceName {expression}\n \"\n .ShouldOutput(\n new SqlContext { InstanceName = value }\n );\n }\n\n [Test]\n [TestCaseSource(nameof(StringCases))]\n public void InstanceName_Override_Valid(string expression, string? value)\n {\n @$\"\n New-SqlContext -InstanceName x | New-SqlContext -InstanceName {expression}\n \"\n .ShouldOutput(\n new SqlContext { InstanceName = value }\n );\n }\n\n #endregion\n #region -DatabaseName\n\n [Test]\n [TestCaseSource(nameof(StringCases))]\n public void DatabaseName_Set_Valid(string expression, string? value)\n {\n @$\"\n New-SqlContext -DatabaseName {expression}\n \"\n .ShouldOutput(\n new SqlContext { DatabaseName = value }\n );\n }\n\n [Test]\n [TestCaseSource(nameof(StringCases))]\n public void DatabaseName_Override_Valid(string expression, string? value)\n {\n @$\"\n New-SqlContext -DatabaseName x | New-SqlContext -DatabaseName {expression}\n \"\n .ShouldOutput(\n new SqlContext { DatabaseName = value }\n );\n }\n\n #endregion\n #region -AuthenticationMode\n\n public static IEnumerable ValidAuthenticationModeCases = new[]\n {\n new Case(\"0\", AzureAuthenticationMode.Default),\n new Case(\"7\", AzureAuthenticationMode.AadManagedIdentity),\n new Case(\"Default\", AzureAuthenticationMode.Default),\n new Case(\"AadManagedIdentity\", AzureAuthenticationMode.AadManagedIdentity),\n };\n\n public static IEnumerable InvalidAuthenticationModeCases = new[]\n {\n new Case(\"$null\", @\"Cannot bind parameter 'AuthenticationMode'\"),\n new Case(\"''\", @\"Cannot bind parameter 'AuthenticationMode'\"),\n new Case(\"-1\", @\"Cannot bind parameter 'AuthenticationMode'\"),\n new Case(\"8\", @\"Cannot bind parameter 'AuthenticationMode'\"),\n new Case(\"Wrong\", @\"Cannot bind parameter 'AuthenticationMode'\"),\n };\n\n [Test]\n [TestCaseSource(nameof(ValidAuthenticationModeCases))]\n public void AuthenticationMode_Set_Valid(string expression, AzureAuthenticationMode value)\n {\n @$\"\n New-SqlContext -Azure `\n -ResourceGroupName rg `\n -ServerResourceName srv `\n -AuthenticationMode {expression}\n \"\n .ShouldOutput(\n new AzureSqlContext\n {\n ServerResourceGroupName = \"rg\",\n ServerResourceName = \"srv\",\n AuthenticationMode = value\n }\n );\n }\n\n [Test]\n [TestCaseSource(nameof(InvalidAuthenticationModeCases))]\n public void AuthenticationMode_Set_Invalid(string expression, string message)\n {\n @$\"\n New-SqlContext -Azure `\n -ResourceGroupName rg `\n -ServerResourceName srv `\n -AuthenticationMode {expression}\n \"\n .ShouldThrow(message);\n }\n\n [Test]\n public void AuthenticationMode_Set_NonAzure()\n {\n @$\"\n New-SqlContext -AuthenticationMode AadPassword\n \"\n .ShouldThrow(\n \"Parameter set cannot be resolved using the specified named parameters.\"\n );\n }\n\n [Test]\n [TestCaseSource(nameof(ValidAuthenticationModeCases))]\n public void AuthenticationMode_Override_Valid(string expression, AzureAuthenticationMode value)\n {\n @$\"\n New-SqlContext -Azure `\n -ResourceGroupName rg `\n -ServerResourceName srv `\n -AuthenticationMode SqlPassword `\n | `\n New-SqlContext -AuthenticationMode {expression}\n \"\n .ShouldOutput(\n new AzureSqlContext\n {\n ServerResourceGroupName = \"rg\",\n ServerResourceName = \"srv\",\n AuthenticationMode = value\n }\n );\n }\n\n [Test]\n [TestCaseSource(nameof(InvalidAuthenticationModeCases))]\n public void AuthenticationMode_Override_Invalid(string expression, string message)\n {\n @$\"\n New-SqlContext -Azure `\n -ResourceGroupName rg `\n -ServerResourceName srv `\n -AuthenticationMode SqlPassword `\n | `\n New-SqlContext -AuthenticationMode {expression}\n \"\n .ShouldThrow(message);\n }\n\n [Test]\n public void AuthenticationMode_Override_NonAzure()\n {\n @$\"\n New-SqlContext | New-SqlContext -AuthenticationMode AadServicePrincipal\n \"\n .ShouldOutput(\n new PSWarning(\"The 'AuthenticationMode' argument was ignored because the context is not an Azure SQL Database context.\"),\n new SqlContext()\n );\n }\n\n #endregion\n #region -Credential\n\n public static IEnumerable ValidCredentialCases = new[]\n {\n new Case(\"$null\", null),\n new Case(\"([PSCredential]::Empty)\", PSCredential.Empty),\n new Case(\"$Credential\", new PSCredential(\"a\", \"p\".Secure())),\n };\n\n public static IEnumerable InvalidCredentialCases = new[]\n {\n new Case(\"''\", @\"Cannot process argument transformation on parameter 'Credential'. A command that prompts the user failed because the host program or the command type does not support user interaction.\"),\n new Case(\"username\", @\"Cannot process argument transformation on parameter 'Credential'. A command that prompts the user failed because the host program or the command type does not support user interaction.\"),\n };\n\n [Test]\n [TestCaseSource(nameof(ValidCredentialCases))]\n public void Credential_Set_Valid(string expression, PSCredential? value)\n {\n @$\"\n $Password = ConvertTo-SecureString p -AsPlainText\n $Credential = New-Object PSCredential a, $Password\n New-SqlContext -Credential {expression}\n \"\n .ShouldOutput(\n new SqlContext { Credential = value }\n );\n }\n\n [Test]\n [TestCaseSource(nameof(InvalidCredentialCases))]\n public void Credential_Set_Invalid(string expression, string message)\n {\n @$\"\n New-SqlContext -Credential {expression}\n \"\n .ShouldThrow(message);\n }\n\n [Test]\n [TestCaseSource(nameof(ValidCredentialCases))]\n public void Credential_Override_Valid(string expression, PSCredential? value)\n {\n @$\"\n $Password = ConvertTo-SecureString p -AsPlainText\n $Credential = New-Object PSCredential a, $Password\n $Credential2 = New-Object PSCredential b, $Password\n New-SqlContext -Credential $Credential2 | New-SqlContext -Credential {expression}\n \"\n .ShouldOutput(\n new SqlContext { Credential = value }\n );\n }\n\n [Test]\n [TestCaseSource(nameof(InvalidCredentialCases))]\n public void Credential_Override_Invalid(string expression, string message)\n {\n @$\"\n $Password = ConvertTo-SecureString p -AsPlainText\n $Credential2 = New-Object PSCredential b, $Password\n New-SqlContext -Credential $Credential2 | New-SqlContext -Credential {expression}\n \"\n .ShouldThrow(message);\n }\n\n #endregion\n #region -EncryptionMode\n\n public static IEnumerable ValidEncryptionModeCases = new[]\n {\n new Case(\"0\", EncryptionMode.Default),\n new Case(\"3\", EncryptionMode.Full),\n new Case(\"Default\", EncryptionMode.Default),\n new Case(\"Full\", EncryptionMode.Full),\n };\n\n public static IEnumerable InvalidEncryptionModeCases = new[]\n {\n new Case(\"$null\", @\"Cannot bind parameter 'EncryptionMode'\"),\n new Case(\"''\", @\"Cannot bind parameter 'EncryptionMode'\"),\n new Case(\"-1\", @\"Cannot bind parameter 'EncryptionMode'\"),\n new Case(\"4\", @\"Cannot bind parameter 'EncryptionMode'\"),\n new Case(\"Wrong\", @\"Cannot bind parameter 'EncryptionMode'\"),\n };\n\n [Test]\n [TestCaseSource(nameof(ValidEncryptionModeCases))]\n public void EncryptionMode_Set_Valid(string expression, EncryptionMode value)\n {\n @$\"\n New-SqlContext -EncryptionMode {expression}\n \"\n .ShouldOutput(\n new SqlContext { EncryptionMode = value }\n );\n }\n\n [Test]\n [TestCaseSource(nameof(InvalidEncryptionModeCases))]\n public void EncryptionMode_Set_Invalid(string expression, string message)\n {\n @$\"\n New-SqlContext -EncryptionMode {expression}\n \"\n .ShouldThrow(message);\n }\n\n [Test]\n public void EncryptionMode_Set_Azure()\n {\n @$\"\n New-SqlContext -Azure `\n -ResourceGroupName rg `\n -ServerResourceName srv `\n -EncryptionMode Unverified\n \"\n .ShouldThrow(\n \"Parameter set cannot be resolved using the specified named parameters.\"\n );\n }\n\n [Test]\n [TestCaseSource(nameof(ValidEncryptionModeCases))]\n public void EncryptionMode_Override_Valid(string expression, EncryptionMode value)\n {\n @$\"\n New-SqlContext -EncryptionMode None | New-SqlContext -EncryptionMode {expression}\n \"\n .ShouldOutput(\n new SqlContext { EncryptionMode = value }\n );\n }\n\n [Test]\n [TestCaseSource(nameof(InvalidEncryptionModeCases))]\n public void EncryptionMode_Override_Invalid(string expression, string message)\n {\n @$\"\n New-SqlContext -EncryptionMode None | New-SqlContext -EncryptionMode {expression}\n \"\n .ShouldThrow(message);\n }\n\n [Test]\n public void EncryptionMode_Override_Azure()\n {\n @$\"\n New-SqlContext -Azure -ResourceGroupName rg -ServerResourceName srv `\n | `\n New-SqlContext -EncryptionMode Unverified\n \"\n .ShouldOutput(\n new PSWarning(\"The 'EncryptionMode' argument was ignored because the context is an Azure SQL Database context.\"),\n new AzureSqlContext { ServerResourceGroupName = \"rg\", ServerResourceName = \"srv\" }\n );\n }\n\n #endregion\n #region -ReadOnlyIntent\n\n public static IEnumerable ReadOnlyIntentCases = new[]\n {\n new Case(\"\", ApplicationIntent.ReadOnly),\n new Case(\":$true\", ApplicationIntent.ReadOnly),\n new Case(\":$false\", ApplicationIntent.ReadWrite)\n };\n\n [Test]\n [TestCaseSource(nameof(ReadOnlyIntentCases))]\n public void ReadOnlyIntent_Set_Valid(string expression, ApplicationIntent value)\n {\n @$\"\n New-SqlContext -ReadOnlyIntent{expression}\n \"\n .ShouldOutput(\n new SqlContext { ApplicationIntent = value }\n );\n }\n\n [Test]\n [TestCaseSource(nameof(ReadOnlyIntentCases))]\n public void ReadOnlyIntent_Override_Valid(string expression, ApplicationIntent value)\n {\n @$\"\n New-SqlContext -ReadOnlyIntent | New-SqlContext -ReadOnlyIntent{expression}\n \"\n .ShouldOutput(\n new SqlContext { ApplicationIntent = value }\n );\n }\n\n #endregion\n #region -ClientName\n\n [Test]\n [TestCaseSource(nameof(StringCases))]\n public void ClientName_Set_Valid(string expression, string? value)\n {\n @$\"\n New-SqlContext -ClientName {expression}\n \"\n .ShouldOutput(\n new SqlContext { ClientName = value }\n );\n }\n\n [Test]\n [TestCaseSource(nameof(StringCases))]\n public void ClientName_Override_Valid(string expression, string? value)\n {\n @$\"\n New-SqlContext -ClientName x | New-SqlContext -ClientName {expression}\n \"\n .ShouldOutput(\n new SqlContext { ClientName = value }\n );\n }\n\n #endregion\n #region -ApplicationName\n\n [Test]\n [TestCaseSource(nameof(StringCases))]\n public void ApplicationName_Set_Valid(string expression, string? value)\n {\n @$\"\n New-SqlContext -ApplicationName {expression}\n \"\n .ShouldOutput(\n new SqlContext { ApplicationName = value }\n );\n }\n\n [Test]\n [TestCaseSource(nameof(StringCases))]\n public void ApplicationName_Override_Valid(string expression, string? value)\n {\n @$\"\n New-SqlContext -ApplicationName x | New-SqlContext -ApplicationName {expression}\n \"\n .ShouldOutput(\n new SqlContext { ApplicationName = value }\n );\n }\n\n #endregion\n #region -ConnectTimeout", "answers": [" public static IEnumerable ValidTimeoutCases = new[]"], "length": 1657, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "3bb20038-1409-4572-9277-a7c6219d2eb0", "reasoning": "After the '#region -ConnectTimeout' comment, the file follows the pattern of defining test case collections for a parameter before the test methods. The next line therefore starts the declaration of the valid test cases collection for ConnectTimeout, matching earlier sections like ServerPort. The appropriate line is the public static IEnumerable declaration.", "reasoning_model_answer": "public static IEnumerable ValidConnectTimeoutCases = new[]", "assistant_with_reasoning": "\nAfter the '#region -ConnectTimeout' comment, the file follows the pattern of defining test case collections for a parameter before the test methods. The next line therefore starts the declaration of the valid test cases collection for ConnectTimeout, matching earlier sections like ServerPort. The appropriate line is the public static IEnumerable declaration.\n\npublic static IEnumerable ValidConnectTimeoutCases = new[]", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.782, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 20352, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "public static IEnumerable ValidConnectTimeoutCases = new[]", "score": 0.91, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "using System;\nusing System.Text;\nusing System.Data;\nusing System.Data.SqlClient;\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Collections.Specialized;\nusing System.Web.UI.WebControls;\nusing ASPNET.StarterKit.BusinessLogicLayer;\n\nnamespace ASPNET.StarterKit.DataAccessLayer {\n public class SQLDataAccess : DataAccess {\n /*** DELEGATE ***/\n\n private delegate void TGenerateListFromReader(SqlDataReader returnData, ref List tempList);\n\n /***************************** BASE CLASS IMPLEMENTATION *****************************/\n\n /*** CATEGORY ***/\n private const string SP_CATEGORY_CREATE = \"aspnet_starterkits_CreateNewCategory\";\n private const string SP_CATEGORY_DELETE = \"aspnet_starterkits_DeleteCategory\";\n private const string SP_CATEGORY_GETALLCATEGORIES = \"aspnet_starterkits_GetAllCategories\";\n private const string SP_CATEGORY_GETCATEGORYBYPROJECTID = \"aspnet_starterkits_GetCategoriesByProjectId\";\n private const string SP_CATEGORY_GETCATEGORYBYID = \"aspnet_starterkits_GetCategoryById\";\n private const string SP_CATEGORY_GETCATEGORYBYNAMEANDPROJECT = \"aspnet_starterkits_GetCategoryByNameAndProjectId\";\n private const string SP_CATEGORY_UPDATE = \"aspnet_starterkits_UpdateCategories\";\n\n\n\n public override int CreateNewCategory(Category newCategory) {\n if (newCategory == null)\n throw (new ArgumentNullException(\"newCategory\"));\n\n SqlCommand sqlCmd = new SqlCommand();\n\n AddParamToSQLCmd(sqlCmd, \"@ReturnValue\", SqlDbType.Int, 0, ParameterDirection.ReturnValue, null);\n AddParamToSQLCmd(sqlCmd, \"@CategoryAbbreviation\", SqlDbType.NText, 255, ParameterDirection.Input, newCategory.Abbreviation);\n AddParamToSQLCmd(sqlCmd, \"@CategoryEstimateDuration\", SqlDbType.Decimal, 0, ParameterDirection.Input, newCategory.EstimateDuration);\n AddParamToSQLCmd(sqlCmd, \"@CategoryName\", SqlDbType.NText, 255, ParameterDirection.Input, newCategory.Name);\n AddParamToSQLCmd(sqlCmd, \"@ProjectId\", SqlDbType.Int, 0, ParameterDirection.Input, newCategory.ProjectId);\n\n SetCommandType(sqlCmd, CommandType.StoredProcedure, SP_CATEGORY_CREATE);\n ExecuteScalarCmd(sqlCmd);\n\n return ((int)sqlCmd.Parameters[\"@ReturnValue\"].Value);\n }\n\n public override bool DeleteCategory(int categoryId) {\n if (categoryId <= DefaultValues.GetCategoryIdMinValue())\n throw (new ArgumentOutOfRangeException(\"categoryId\"));\n\n SqlCommand sqlCmd = new SqlCommand();\n\n AddParamToSQLCmd(sqlCmd, \"@ReturnValue\", SqlDbType.Int, 0, ParameterDirection.ReturnValue, null);\n AddParamToSQLCmd(sqlCmd, \"@CategoryIdToDelete\", SqlDbType.Int, 0, ParameterDirection.Input, categoryId);\n\n SetCommandType(sqlCmd, CommandType.StoredProcedure, SP_CATEGORY_DELETE);\n ExecuteScalarCmd(sqlCmd);\n\n int returnValue = (int)sqlCmd.Parameters[\"@ReturnValue\"].Value;\n return (returnValue == 0 ? true : false);\n }\n\n public override List GetAllCategories() {\n SqlCommand sqlCmd = new SqlCommand();\n\n SetCommandType(sqlCmd, CommandType.StoredProcedure, SP_CATEGORY_GETALLCATEGORIES);\n\n List categoryList = new List();\n\n TExecuteReaderCmd(sqlCmd, TGenerateCategoryListFromReader, ref categoryList);\n\n return categoryList;\n }\n\n public override Category GetCategoryByCategoryId(int Id) {\n if (Id <= DefaultValues.GetCategoryIdMinValue())\n throw (new ArgumentOutOfRangeException(\"Id\"));\n\n\n SqlCommand sqlCmd = new SqlCommand();\n\n AddParamToSQLCmd(sqlCmd, \"@CategoryId\", SqlDbType.Int, 0, ParameterDirection.Input, Id);\n\n SetCommandType(sqlCmd, CommandType.StoredProcedure, SP_CATEGORY_GETCATEGORYBYID);\n\n List categoryList = new List();\n\n TExecuteReaderCmd(sqlCmd, TGenerateCategoryListFromReader, ref categoryList);\n\n if (categoryList.Count > 0)\n return categoryList[0];\n else\n return null;\n\n }\n\n public override Category GetCategoryByCategoryNameandProjectId(string categoryName, int projectId) {\n if (projectId <= DefaultValues.GetProjectIdMinValue())\n throw (new ArgumentOutOfRangeException(\"Id\"));\n\n\n SqlCommand sqlCmd = new SqlCommand();\n\n AddParamToSQLCmd(sqlCmd, \"@ProjectId\", SqlDbType.Int, 0, ParameterDirection.Input, projectId);\n AddParamToSQLCmd(sqlCmd, \"@CategoryName\", SqlDbType.NText, 255, ParameterDirection.Input, categoryName);\n\n SetCommandType(sqlCmd, CommandType.StoredProcedure, SP_CATEGORY_GETCATEGORYBYNAMEANDPROJECT);\n\n List categoryList = new List();\n\n TExecuteReaderCmd(sqlCmd, TGenerateCategoryListFromReader, ref categoryList);\n\n if (categoryList.Count > 0)\n return categoryList[0];\n else\n return null;\n\n }\n\n\n\n public override List GetCategoriesByProjectId(int projectId) {\n if (projectId <= DefaultValues.GetProjectIdMinValue())\n throw (new ArgumentOutOfRangeException(\"projectId\"));\n\n\n SqlCommand sqlCmd = new SqlCommand();\n\n AddParamToSQLCmd(sqlCmd, \"@ProjectId\", SqlDbType.Int, 0, ParameterDirection.Input, projectId);\n\n SetCommandType(sqlCmd, CommandType.StoredProcedure, SP_CATEGORY_GETCATEGORYBYPROJECTID);\n\n List categoryList = new List();\n\n TExecuteReaderCmd(sqlCmd, TGenerateCategoryListFromReader, ref categoryList);\n\n\n return categoryList;\n }\n\n public override bool UpdateCategory(Category newCategory) {\n if (newCategory == null)\n throw (new ArgumentNullException(\"newCategory\"));\n\n if (newCategory.Id <= DefaultValues.GetCategoryIdMinValue())\n throw (new ArgumentOutOfRangeException(\"newCategory.Id\"));\n\n SqlCommand sqlCmd = new SqlCommand();\n\n AddParamToSQLCmd(sqlCmd, \"@ReturnValue\", SqlDbType.Int, 0, ParameterDirection.ReturnValue, null);\n\n AddParamToSQLCmd(sqlCmd, \"@CategoryId\", SqlDbType.Int, 0, ParameterDirection.Input, newCategory.Id);\n AddParamToSQLCmd(sqlCmd, \"@CategoryAbbreviation\", SqlDbType.NText, 255, ParameterDirection.Input, newCategory.Abbreviation);\n AddParamToSQLCmd(sqlCmd, \"@CategoryEstimateDuration\", SqlDbType.Decimal, 0, ParameterDirection.Input, newCategory.EstimateDuration);\n AddParamToSQLCmd(sqlCmd, \"@CategoryName\", SqlDbType.NText, 255, ParameterDirection.Input, newCategory.Name);\n AddParamToSQLCmd(sqlCmd, \"@ProjectId\", SqlDbType.Int, 0, ParameterDirection.Input, newCategory.ProjectId);\n\n SetCommandType(sqlCmd, CommandType.StoredProcedure, SP_CATEGORY_UPDATE);\n ExecuteScalarCmd(sqlCmd);\n\n int returnValue = (int)sqlCmd.Parameters[\"@ReturnValue\"].Value;\n return (returnValue == 0 ? true : false);\n }\n\n\n /*** PROJECT ***/\n private const string SP_PROJECT_ADDUSERTOPROJECT = \"aspnet_starterkits_AddUserToProject\";\n private const string SP_PROJECT_CREATE = \"aspnet_starterkits_CreateNewProject\";\n private const string SP_PROJECT_DELETE = \"aspnet_starterkits_DeleteProject\";\n private const string SP_PROJECT_GETALLPROJECTS = \"aspnet_starterkits_GetAllProjects\";\n private const string SP_PROJECT_GETAPROJECTBYID = \"aspnet_starterkits_GetProjectById\";\n private const string SP_PROJECT_GETAPROJECTSBYMANAGERUSERNAME = \"aspnet_starterkits_GetProjectByManagerUserName\";\n private const string SP_PROJECT_GETPROJECTSBYYSERNAME = \"aspnet_starterkits_GetProjectByUserName\";\n private const string SP_PROJECT_GETPROJECTMEMBERS = \"aspnet_starterkits_GetProjectMember\";\n private const string SP_PROJECT_REMOVEUSERFROMPROJECT = \"aspnet_starterkits_RemoveUserFromProject\";\n private const string SP_PROJECT_UPDATE = \"aspnet_starterkits_UpdateProject\";\n\n public override bool AddUserToProject(int projectId, string userName) {\n if (userName == null || userName.Length == 0)\n throw (new ArgumentOutOfRangeException(\"userName\"));\n\n if (projectId <= 0)\n throw (new ArgumentOutOfRangeException(\"projectId\"));\n\n SqlCommand sqlCmd = new SqlCommand();\n\n AddParamToSQLCmd(sqlCmd, \"@ResultValue\", SqlDbType.Int, 0, ParameterDirection.ReturnValue, null);\n\n AddParamToSQLCmd(sqlCmd, \"@MemberUserName\", SqlDbType.NText, 255, ParameterDirection.Input, userName);\n AddParamToSQLCmd(sqlCmd, \"@ProjectId\", SqlDbType.Int, 0, ParameterDirection.Input, projectId);\n\n SetCommandType(sqlCmd, CommandType.StoredProcedure, SP_PROJECT_ADDUSERTOPROJECT);\n ExecuteScalarCmd(sqlCmd);\n\n int resultValue = (int)sqlCmd.Parameters[\"@ResultValue\"].Value;\n\n return (resultValue == 0 ? true : false);\n }\n\n\n public override int CreateNewProject(Project newProject) {\n if (newProject == null)\n throw (new ArgumentNullException(\"newProject\"));\n\n\n SqlCommand sqlCmd = new SqlCommand();\n\n AddParamToSQLCmd(sqlCmd, \"@ReturnValue\", SqlDbType.Int, 0, ParameterDirection.ReturnValue, null);\n\n AddParamToSQLCmd(sqlCmd, \"@ProjectCreatorUserName\", SqlDbType.NText, 255, ParameterDirection.Input, newProject.CreatorUserName);\n AddParamToSQLCmd(sqlCmd, \"@ProjectCompletionDate\", SqlDbType.DateTime, 0, ParameterDirection.Input, newProject.CompletionDate);\n AddParamToSQLCmd(sqlCmd, \"@ProjectDescription\", SqlDbType.NText, 1000, ParameterDirection.Input, newProject.Description);\n AddParamToSQLCmd(sqlCmd, \"@ProjectEstimateDuration\", SqlDbType.Decimal, 0, ParameterDirection.Input, newProject.EstimateDuration);\n AddParamToSQLCmd(sqlCmd, \"@ProjectManagerUserName\", SqlDbType.NText, 255, ParameterDirection.Input, newProject.ManagerUserName);\n AddParamToSQLCmd(sqlCmd, \"@ProjectName\", SqlDbType.NText, 255, ParameterDirection.Input, newProject.Name);\n\n SetCommandType(sqlCmd, CommandType.StoredProcedure, SP_PROJECT_CREATE);\n ExecuteScalarCmd(sqlCmd);\n\n return ((int)sqlCmd.Parameters[\"@ReturnValue\"].Value);\n }\n\n public override bool DeleteProject(int projectID) {\n if (projectID <= 0)\n throw (new ArgumentOutOfRangeException(\"projectID\"));\n\n SqlCommand sqlCmd = new SqlCommand();\n\n AddParamToSQLCmd(sqlCmd, \"@ReturnValue\", SqlDbType.Int, 0, ParameterDirection.ReturnValue, null);\n\n AddParamToSQLCmd(sqlCmd, \"@ProjectIdToDelete\", SqlDbType.Int, 0, ParameterDirection.Input, projectID);\n\n SetCommandType(sqlCmd, CommandType.StoredProcedure, SP_PROJECT_DELETE);\n ExecuteScalarCmd(sqlCmd);\n\n int returnValue = (int)sqlCmd.Parameters[\"@ReturnValue\"].Value;\n\n return (returnValue == 0 ? true : false);\n }\n\n public override List GetAllProjects() {\n SqlCommand sqlCmd = new SqlCommand();\n\n SetCommandType(sqlCmd, CommandType.StoredProcedure, SP_PROJECT_GETALLPROJECTS);\n\n List prjList = new List();\n\n TExecuteReaderCmd(sqlCmd, TGenerateProjectListFromReader, ref prjList);\n\n return prjList;\n }\n\n public override Project GetProjectById(int projectId) {\n if (projectId <= 0)\n throw (new ArgumentOutOfRangeException(\"projectId\"));\n\n SqlCommand sqlCmd = new SqlCommand();\n\n AddParamToSQLCmd(sqlCmd, \"@ProjectId\", SqlDbType.Int, 0, ParameterDirection.Input, projectId);\n\n SetCommandType(sqlCmd, CommandType.StoredProcedure, SP_PROJECT_GETAPROJECTBYID);\n\n List prjList = new List();\n\n TExecuteReaderCmd(sqlCmd, TGenerateProjectListFromReader, ref prjList);\n\n if (prjList.Count > 0)\n return prjList[0];\n else\n return null;\n }\n\n public override List GetProjectsByManagerUserName(string userName) {\n if (userName == null || userName.Length == 0)\n throw (new ArgumentOutOfRangeException(\"userName\"));\n\n SqlCommand sqlCmd = new SqlCommand();\n\n AddParamToSQLCmd(sqlCmd, \"@ProjectManagerUserName\", SqlDbType.NText, 256, ParameterDirection.Input, userName);\n SetCommandType(sqlCmd, CommandType.StoredProcedure, SP_PROJECT_GETAPROJECTSBYMANAGERUSERNAME);\n\n List prjList = new List();\n\n TExecuteReaderCmd(sqlCmd, TGenerateProjectListFromReader, ref prjList);\n\n return prjList;\n\n\n }\n\n public override List GetProjectMembers(int Id) {\n if (Id <= 0)\n throw (new ArgumentOutOfRangeException(\"Id\"));\n\n SqlCommand sqlCmd = new SqlCommand();\n\n AddParamToSQLCmd(sqlCmd, \"@ProjectId\", SqlDbType.Int, 0, ParameterDirection.Input, Id);\n\n SetCommandType(sqlCmd, CommandType.StoredProcedure, SP_PROJECT_GETPROJECTMEMBERS);\n\n List userList = new List();\n\n TExecuteReaderCmd(sqlCmd, TGenerateUsertListFromReader, ref userList);\n\n return userList;\n\n }\n\n public override List GetProjectsByUserName(string userName) {\n if (userName == null || userName.Length == 0)\n throw (new ArgumentOutOfRangeException(\"userName\"));\n\n SqlCommand sqlCmd = new SqlCommand();\n\n AddParamToSQLCmd(sqlCmd, \"@UserName\", SqlDbType.NText, 256, ParameterDirection.Input, userName);\n SetCommandType(sqlCmd, CommandType.StoredProcedure, SP_PROJECT_GETPROJECTSBYYSERNAME);\n\n List prjList = new List();\n\n TExecuteReaderCmd(sqlCmd, TGenerateProjectListFromReader, ref prjList);\n\n return prjList;\n \n \n// return (new List());\n\n }\n\n\n public override bool RemoveUserFromProject(int projectId, string userName) {\n if (String.IsNullOrEmpty(userName))\n throw (new ArgumentOutOfRangeException(\"userName\"));\n if (projectId <= 0)\n throw (new ArgumentOutOfRangeException(\"projectId\"));\n\n SqlCommand sqlCmd = new SqlCommand();\n\n AddParamToSQLCmd(sqlCmd, \"@ResultValue\", SqlDbType.Int, 0, ParameterDirection.ReturnValue, null);\n AddParamToSQLCmd(sqlCmd, \"@userName\", SqlDbType.NVarChar, 0, ParameterDirection.Input, userName);\n AddParamToSQLCmd(sqlCmd, \"@ProjectId\", SqlDbType.Int, 0, ParameterDirection.Input, projectId);\n\n SetCommandType(sqlCmd, CommandType.StoredProcedure, SP_PROJECT_REMOVEUSERFROMPROJECT);\n ExecuteScalarCmd(sqlCmd);\n\n int resultValue = (int)sqlCmd.Parameters[\"@ResultValue\"].Value;\n\n return (resultValue == 0 ? true : false);\n }\n\n public override bool UpdateProject(Project projectToUpdate) {\n // validate input\n if (projectToUpdate == null)\n throw (new ArgumentNullException(\"projectToUpdate\"));\n // validate input\n if (projectToUpdate.Id <= 0)\n throw (new ArgumentOutOfRangeException(\"projectToUpdate\"));\n\n SqlCommand sqlCmd = new SqlCommand();\n // set the type of parameter to add a new project\n AddParamToSQLCmd(sqlCmd, \"@ReturnValue\", SqlDbType.Int, 0, ParameterDirection.ReturnValue, null);\n\n AddParamToSQLCmd(sqlCmd, \"@ProjectId\", SqlDbType.Int, 0, ParameterDirection.Input, projectToUpdate.Id);\n AddParamToSQLCmd(sqlCmd, \"@ProjectCompletionDate\", SqlDbType.DateTime, 0, ParameterDirection.Input, projectToUpdate.CompletionDate);\n AddParamToSQLCmd(sqlCmd, \"@ProjectDescription\", SqlDbType.NText, 1000, ParameterDirection.Input, projectToUpdate.Description);\n AddParamToSQLCmd(sqlCmd, \"@ProjectEstimateDuration\", SqlDbType.Decimal, 0, ParameterDirection.Input, projectToUpdate.EstimateDuration);\n AddParamToSQLCmd(sqlCmd, \"@ProjectManagerUserName\", SqlDbType.NText, 256, ParameterDirection.Input, projectToUpdate.ManagerUserName);\n AddParamToSQLCmd(sqlCmd, \"@ProjectName\", SqlDbType.NText, 256, ParameterDirection.Input, projectToUpdate.Name);\n\n SetCommandType(sqlCmd, CommandType.StoredProcedure, SP_PROJECT_UPDATE);\n ExecuteScalarCmd(sqlCmd);\n\n int returnValue = (int)sqlCmd.Parameters[\"@ReturnValue\"].Value;\n\n return (returnValue == 0 ? true : false);\n }\n\n\n /*** TIME ENTRY ***/\n private string SP_TIMEENTRY_CREATE = \"aspnet_starterkits_CreateNewTimeEntry\";\n private string SP_TIMEENTRY_DELETE = \"aspnet_starterkits_DeleteTimeEntry\";\n private string SP_TIMEENTRY_GETALLTIMEENTRIES = \"aspnet_starterkits_GetAllTimeEntries\";\n private string SP_TIMEENTRY_GETALLTIMEENTRIESBYPROJECTID_USER = \"aspnet_starterkits_GetAllTimeEntriesByProjectIdandUser\";\n private string SP_TIMEENTRY_GETALLTIMEENTRIESBYUSERNAMEANDDATE = \"aspnet_starterkits_GetAllTimeEntriesByProjectIdandUserAndDate\";\n private string SP_TIMEENTRY_UPDATE = \"aspnet_starterkits_UpdateTimeEntry\";\n private string SP_TIMEENTRY_GETTIMEENTRYBYID = \"aspnet_starterkits_GetTimeEntryById\";\n\n\n\n public override int CreateNewTimeEntry(TimeEntry newTimeEntry) {\n\n if (newTimeEntry == null)\n throw (new ArgumentNullException(\"newTimeEntry\"));\n\n\n SqlCommand sqlCmd = new SqlCommand();\n\n AddParamToSQLCmd(sqlCmd, \"@ReturnValue\", SqlDbType.Int, 0, ParameterDirection.ReturnValue, null);\n\n AddParamToSQLCmd(sqlCmd, \"@CategoryId\", SqlDbType.Int, 0, ParameterDirection.Input, newTimeEntry.CategoryId);\n AddParamToSQLCmd(sqlCmd, \"@TimeEntryCreatorUserName\", SqlDbType.NText, 255, ParameterDirection.Input, newTimeEntry.CreatorUserName);\n AddParamToSQLCmd(sqlCmd, \"@TimeEntryDescription\", SqlDbType.NText, 1000, ParameterDirection.Input, newTimeEntry.Description);\n AddParamToSQLCmd(sqlCmd, \"@TimeEntryEstimateDuration\", SqlDbType.Decimal, 0, ParameterDirection.Input, newTimeEntry.Duration);\n AddParamToSQLCmd(sqlCmd, \"@TimeEntryEnteredDate\", SqlDbType.DateTime, 0, ParameterDirection.Input, newTimeEntry.ReportedDate);\n AddParamToSQLCmd(sqlCmd, \"@TimeEntryUserName\", SqlDbType.NText, 255, ParameterDirection.Input, newTimeEntry.UserName);\n\n SetCommandType(sqlCmd, CommandType.StoredProcedure, SP_TIMEENTRY_CREATE);\n\n ExecuteScalarCmd(sqlCmd);\n\n return ((int)sqlCmd.Parameters[\"@ReturnValue\"].Value);\n }\n\n public override bool DeleteTimeEntry(int timeEntryId) {\n if (timeEntryId <= DefaultValues.GetTimeEntryIdMinValue())\n throw (new ArgumentOutOfRangeException(\"timeEntryId\"));\n\n SqlCommand sqlCmd = new SqlCommand();\n\n AddParamToSQLCmd(sqlCmd, \"@ReturnValue\", SqlDbType.Int, 0, ParameterDirection.ReturnValue, null);\n AddParamToSQLCmd(sqlCmd, \"@TimeEntryIdToDelete\", SqlDbType.Int, 0, ParameterDirection.Input, timeEntryId);\n\n SetCommandType(sqlCmd, CommandType.StoredProcedure, SP_TIMEENTRY_DELETE);\n ExecuteScalarCmd(sqlCmd);\n\n int returnValue = (int)sqlCmd.Parameters[\"@ReturnValue\"].Value;\n\n return (returnValue == 0 ? true : false);\n\n }\n\n public override List GetAllTimeEntries() {\n\n SqlCommand sqlCmd = new SqlCommand();\n\n SetCommandType(sqlCmd, CommandType.StoredProcedure, SP_TIMEENTRY_GETALLTIMEENTRIES);\n\n List timeEntryList = new List();\n\n TExecuteReaderCmd(sqlCmd, TGenerateTimeEntryListFromReader, ref timeEntryList);\n\n return timeEntryList;\n }\n\n public override List GetTimeEntries(int projectId, string userName) {\n if (projectId <= DefaultValues.GetTimeEntryIdMinValue())\n throw (new ArgumentOutOfRangeException(\"projectId\"));\n\n SqlCommand sqlCmd = new SqlCommand();\n\n AddParamToSQLCmd(sqlCmd, \"@ReturnValue\", SqlDbType.Int, 0, ParameterDirection.ReturnValue, null);\n AddParamToSQLCmd(sqlCmd, \"@ProjectId\", SqlDbType.Int, 0, ParameterDirection.Input, projectId);\n AddParamToSQLCmd(sqlCmd, \"@TimeEntryUserName\", SqlDbType.NText, 255, ParameterDirection.Input, userName);\n\n\n SetCommandType(sqlCmd, CommandType.StoredProcedure, SP_TIMEENTRY_GETALLTIMEENTRIESBYPROJECTID_USER);\n\n List timeEntryList = new List();\n\n TExecuteReaderCmd(sqlCmd, TGenerateTimeEntryListFromReader, ref timeEntryList);\n\n return timeEntryList;\n }\n\n public override TimeEntry GetTimeEntryById(int timeEntryId) {\n if (timeEntryId <= 0)\n throw (new ArgumentOutOfRangeException(\"timeEntryId\"));\n\n SqlCommand sqlCmd = new SqlCommand();\n\n AddParamToSQLCmd(sqlCmd, \"@TimeEntryId\", SqlDbType.Int, 0, ParameterDirection.Input, timeEntryId);\n\n SetCommandType(sqlCmd, CommandType.StoredProcedure, SP_TIMEENTRY_GETTIMEENTRYBYID);\n\n List timeEntryList = new List();\n\n\n TExecuteReaderCmd(sqlCmd, TGenerateTimeEntryListFromReader, ref timeEntryList);\n\n if (timeEntryList.Count > 0)\n return timeEntryList[0];\n else\n return null;\n\n }\n\n public override List GetTimeEntriesByUserNameAndDates(string userName,\n DateTime startingDate, DateTime endDate) {\n SqlCommand sqlCmd = new SqlCommand();\n\n AddParamToSQLCmd(sqlCmd, \"@ReturnValue\", SqlDbType.Int, 0, ParameterDirection.ReturnValue, null);\n AddParamToSQLCmd(sqlCmd, \"@EndDate\", SqlDbType.DateTime, 0, ParameterDirection.Input, endDate);\n AddParamToSQLCmd(sqlCmd, \"@StartingDate\", SqlDbType.DateTime, 0, ParameterDirection.Input, startingDate);\n AddParamToSQLCmd(sqlCmd, \"@TimeEntryUserName\", SqlDbType.NText, 255, ParameterDirection.Input, userName);\n\n\n SetCommandType(sqlCmd, CommandType.StoredProcedure, SP_TIMEENTRY_GETALLTIMEENTRIESBYUSERNAMEANDDATE);\n\n List timeEntryList = new List();\n\n TExecuteReaderCmd(sqlCmd, TGenerateTimeEntryListFromReader, ref timeEntryList);\n\n return timeEntryList;\n\n }\n\n public override bool UpdateTimeEntry(TimeEntry timeEntry) {\n if (timeEntry == null)\n throw (new ArgumentNullException(\"timeEntry\"));\n\n\n SqlCommand sqlCmd = new SqlCommand();\n\n AddParamToSQLCmd(sqlCmd, \"@ReturnValue\", SqlDbType.Int, 0, ParameterDirection.ReturnValue, null);\n\n\n AddParamToSQLCmd(sqlCmd, \"@TimeEntryId\", SqlDbType.Int, 0, ParameterDirection.Input, timeEntry.Id);\n AddParamToSQLCmd(sqlCmd, \"@CategoryId\", SqlDbType.Int, 0, ParameterDirection.Input, timeEntry.CategoryId);\n AddParamToSQLCmd(sqlCmd, \"@TimeEntryDescription\", SqlDbType.NText, 1000, ParameterDirection.Input, timeEntry.Description);\n AddParamToSQLCmd(sqlCmd, \"@TimeEntryEstimateDuration\", SqlDbType.Decimal, 0, ParameterDirection.Input, timeEntry.Duration);\n AddParamToSQLCmd(sqlCmd, \"@TimeEntryEnteredDate\", SqlDbType.DateTime, 0, ParameterDirection.Input, timeEntry.ReportedDate);\n AddParamToSQLCmd(sqlCmd, \"@TimeEntryUserName\", SqlDbType.NText, 1000, ParameterDirection.Input, timeEntry.UserName);\n\n\n SetCommandType(sqlCmd, CommandType.StoredProcedure, SP_TIMEENTRY_UPDATE);\n ExecuteScalarCmd(sqlCmd);\n int resultValue = (int)sqlCmd.Parameters[\"@ReturnValue\"].Value;\n\n return (resultValue == 0 ? true : false);\n }\n\n /*** USER REPORT ***/\n private string SP_TIMEENTRY_GETUSERREPORT = \"aspnet_starterkits_GetTimeEntryUserReport\";\n private string SP_TIMEENTRY_GETUSERREPORTBYCATEGORY = \"aspnet_starterkits_GetTimeEntryUserReportByCategoryId\";\n\n public override List GetUserReportsByProjectId(int projectId) {\n\n SqlCommand sqlCmd = new SqlCommand();\n\n AddParamToSQLCmd(sqlCmd, \"@ProjectId\", SqlDbType.Int, 0, ParameterDirection.Input, projectId);\n\n SetCommandType(sqlCmd, CommandType.StoredProcedure, SP_TIMEENTRY_GETUSERREPORT);\n\n List userReport = new List();\n\n TExecuteReaderCmd(sqlCmd, TGenerateUserReportListFromReader, ref userReport);\n\n return userReport;\n }\n\n public override List GetUserReportsByCategoryId(int categoryId) {\n\n SqlCommand sqlCmd = new SqlCommand();\n\n AddParamToSQLCmd(sqlCmd, \"@CategoryId\", SqlDbType.Int, 0, ParameterDirection.Input, categoryId);\n\n SetCommandType(sqlCmd, CommandType.StoredProcedure, SP_TIMEENTRY_GETUSERREPORTBYCATEGORY);\n\n List userReport = new List();\n\n TExecuteReaderCmd(sqlCmd, TGenerateUserReportListFromReader, ref userReport);\n\n return userReport;\n }\n\n /*** USER TOTAL DURATION REPORT ***/\n private string SP_TIMEENTRY_GETUSERREPORTBYUSER = \"aspnet_starterkits_GetTimeEntryUserReportByUser\";\n\n public override List GetUserReportsByUserName(string userName) {\n\n SqlCommand sqlCmd = new SqlCommand();\n\n AddParamToSQLCmd(sqlCmd, \"@UserName\", SqlDbType.NText, 256, ParameterDirection.Input, userName);\n\n SetCommandType(sqlCmd, CommandType.StoredProcedure, SP_TIMEENTRY_GETUSERREPORTBYUSER);\n", "answers": [" List userReport = new List();"], "length": 1558, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "557cb96e-2d1d-483e-975f-8a67c9ec3d29", "reasoning": "The method GetUserReportsByUserName follows the same pattern as the previous report methods: after setting the command type, it creates a list of the appropriate report type, executes the reader to fill it, and returns it. The immediate next line should instantiate the list for UserTotalDurationReport.", "reasoning_model_answer": "List userReport = new List();", "assistant_with_reasoning": "\nThe method GetUserReportsByUserName follows the same pattern as the previous report methods: after setting the command type, it creates a list of the appropriate report type, executes the reader to fill it, and returns it. The immediate next line should instantiate the list for UserTotalDurationReport.\n\nList userReport = new List();", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.732, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 24569, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "List userReport = new List();", "score": 0.96, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/**\n * Copyright (c) 2014,\n * Charles Prud'homme (TASC, INRIA Rennes, LINA CNRS UMR 6241),\n * Jean-Guillaume Fages (COSLING S.A.S.).\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n * * Neither the name of the nor the\n * names of its contributors may be used to endorse or promote products\n * derived from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\npackage org.chocosolver.docs;\n\nimport org.chocosolver.solver.Solver;\nimport org.chocosolver.solver.constraints.ICF;\nimport org.chocosolver.solver.constraints.extension.Tuples;\nimport org.chocosolver.solver.constraints.nary.automata.FA.CostAutomaton;\nimport org.chocosolver.solver.constraints.nary.automata.FA.FiniteAutomaton;\nimport org.chocosolver.solver.constraints.nary.circuit.CircuitConf;\nimport org.chocosolver.solver.trace.Chatterbox;\nimport org.chocosolver.solver.variables.BoolVar;\nimport org.chocosolver.solver.variables.IntVar;\nimport org.chocosolver.solver.variables.Task;\nimport org.chocosolver.solver.variables.VF;\nimport org.testng.annotations.Test;\n\n/**\n * BEWARE: 5_elements.rst SHOULD BE UPDATED ANYTIME THIS CLASS IS CHANGED\n *\n * @author Charles Prud'homme\n * @version choco\n * @since 16/09/2014\n */\npublic class IntConstraintExamples {\n\n @Test\n public void arithm1() {\n Solver solver = new Solver();\n IntVar X = VF.enumerated(\"X\", 1, 4, solver);\n solver.post(ICF.arithm(X, \">\", 2));\n Chatterbox.showSolutions(solver);\n solver.findAllSolutions();\n }\n\n @Test(groups = \"1s\")\n public void testmember1() {\n Solver solver = new Solver();\n IntVar X = VF.enumerated(\"X\", 1, 4, solver);\n solver.post(ICF.member(X, new int[]{-2, -1, 0, 1, 2}));\n Chatterbox.showSolutions(solver);\n solver.findAllSolutions();\n }\n\n @Test(groups = \"1s\")\n public void testmember2() {\n Solver solver = new Solver();\n IntVar X = VF.enumerated(\"X\", 1, 4, solver);\n solver.post(ICF.member(X, 2, 5));\n Chatterbox.showSolutions(solver);\n solver.findAllSolutions();\n }\n\n @Test(groups = \"1s\")\n public void testnotmember1() {\n Solver solver = new Solver();\n IntVar X = VF.enumerated(\"X\", 1, 4, solver);\n solver.post(ICF.not_member(X, new int[]{-2, -1, 0, 1, 2}));\n Chatterbox.showSolutions(solver);\n solver.findAllSolutions();\n }\n\n\n @Test(groups = \"1s\")\n public void testnotmember2() {\n Solver solver = new Solver();\n IntVar X = VF.enumerated(\"X\", 1, 4, solver);\n solver.post(ICF.not_member(X, 2, 5));\n Chatterbox.showSolutions(solver);\n solver.findAllSolutions();\n }\n\n @Test(groups = \"1s\")\n public void testabsolute() {\n Solver solver = new Solver();\n IntVar X = VF.enumerated(\"X\", 0, 2, solver);\n IntVar Y = VF.enumerated(\"X\", -6, 1, solver);\n solver.post(ICF.absolute(X, Y));\n Chatterbox.showSolutions(solver);\n solver.findAllSolutions();\n }\n\n @Test(groups = \"1s\")\n public void testarithm3() {\n Solver solver = new Solver();\n IntVar X = VF.enumerated(\"X\", 0, 2, solver);\n IntVar Y = VF.enumerated(\"X\", -6, 1, solver);\n solver.post(ICF.arithm(X, \"<=\", Y, \"+\", 1));\n Chatterbox.showSolutions(solver);\n solver.findAllSolutions();\n }\n\n @Test(groups = \"1s\")\n public void testdistance1() {\n Solver solver = new Solver();\n IntVar X = VF.enumerated(\"X\", 0, 2, solver);\n IntVar Y = VF.enumerated(\"X\", -3, 1, solver);\n solver.post(ICF.distance(X, Y, \"=\", 1));\n Chatterbox.showSolutions(solver);\n solver.findAllSolutions();\n }\n\n @Test(groups = \"1s\")\n public void testelement1() {\n Solver solver = new Solver();\n IntVar V = VF.enumerated(\"V\", -2, 2, solver);\n IntVar I = VF.enumerated(\"I\", 0, 5, solver);\n solver.post(ICF.element(V, new int[]{2, -2, 1, -1, 0}, I, 0, \"none\"));\n Chatterbox.showSolutions(solver);\n solver.findAllSolutions();\n }\n\n @Test(groups = \"1s\")\n public void testsquare() {\n Solver solver = new Solver();\n IntVar X = VF.enumerated(\"X\", 0, 5, solver);\n IntVar Y = VF.enumerated(\"Y\", -1, 3, solver);\n solver.post(ICF.square(X, Y));\n Chatterbox.showSolutions(solver);\n solver.findAllSolutions();\n }\n\n @Test(groups = \"1s\")\n public void testtable1() {\n Solver solver = new Solver();\n IntVar X = VF.enumerated(\"X\", 0, 5, solver);\n IntVar Y = VF.enumerated(\"Y\", -1, 3, solver);\n Tuples tuples = new Tuples(true);\n tuples.add(1, -2);\n tuples.add(1, 1);\n tuples.add(4, 2);\n tuples.add(1, 4);\n solver.post(ICF.table(X, Y, tuples, \"AC2001\"));\n Chatterbox.showSolutions(solver);\n solver.findAllSolutions();\n }\n\n @Test(groups = \"1s\")\n public void testdistance2() {\n Solver solver = new Solver();\n IntVar X = VF.enumerated(\"X\", 1, 3, solver);\n IntVar Y = VF.enumerated(\"Y\", -1, 1, solver);\n IntVar Z = VF.enumerated(\"Z\", 2, 3, solver);\n solver.post(ICF.distance(X, Y, \"<\", Z));\n Chatterbox.showSolutions(solver);\n solver.findAllSolutions();\n }\n\n @Test(groups = \"1s\")\n public void testeucli_div() {\n Solver solver = new Solver();\n IntVar X = VF.enumerated(\"X\", 1, 3, solver);\n IntVar Y = VF.enumerated(\"Y\", -1, 1, solver);\n IntVar Z = VF.enumerated(\"Z\", 2, 3, solver);\n solver.post(ICF.eucl_div(X, Y, Z));\n Chatterbox.showSolutions(solver);\n solver.findAllSolutions();\n }\n\n @Test(groups = \"1s\")\n public void testmaximum() {\n Solver solver = new Solver();\n IntVar MAX = VF.enumerated(\"MAX\", 1, 3, solver);\n IntVar Y = VF.enumerated(\"Y\", -1, 1, solver);\n IntVar Z = VF.enumerated(\"Z\", 2, 3, solver);\n solver.post(ICF.maximum(MAX, Y, Z));\n Chatterbox.showSolutions(solver);\n solver.findAllSolutions();\n }\n\n @Test(groups = \"1s\")\n public void testminimum() {\n Solver solver = new Solver();\n IntVar MIN = VF.enumerated(\"MIN\", 1, 3, solver);\n IntVar Y = VF.enumerated(\"Y\", -1, 1, solver);\n IntVar Z = VF.enumerated(\"Z\", 2, 3, solver);\n solver.post(ICF.minimum(MIN, Y, Z));\n Chatterbox.showSolutions(solver);\n solver.findAllSolutions();\n }\n\n @Test(groups = \"1s\")\n public void testmod() {\n Solver solver = new Solver();\n IntVar X = VF.enumerated(\"X\", 2, 4, solver);\n IntVar Y = VF.enumerated(\"Y\", -1, 4, solver);\n IntVar Z = VF.enumerated(\"Z\", 1, 3, solver);\n solver.post(ICF.mod(X, Y, Z));\n Chatterbox.showSolutions(solver);\n solver.findAllSolutions();\n }\n\n @Test(groups = \"1s\")\n public void testtimes() {\n Solver solver = new Solver();\n IntVar X = VF.enumerated(\"X\", -1, 2, solver);\n IntVar Y = VF.enumerated(\"Y\", 2, 4, solver);\n IntVar Z = VF.enumerated(\"Z\", 5, 7, solver);\n solver.post(ICF.times(X, Y, Z));\n Chatterbox.showSolutions(solver);\n solver.findAllSolutions();\n }\n\n @Test(groups = \"1s\")\n public void testalldifferent() {\n Solver solver = new Solver();\n IntVar W = VF.enumerated(\"W\", 0, 1, solver);\n IntVar X = VF.enumerated(\"X\", -1, 2, solver);\n IntVar Y = VF.enumerated(\"Y\", 2, 4, solver);\n IntVar Z = VF.enumerated(\"Z\", 5, 7, solver);\n solver.post(ICF.alldifferent(new IntVar[]{W, X, Y, Z}));\n Chatterbox.showSolutions(solver);\n solver.findAllSolutions();\n }\n\n @Test(groups = \"1s\")\n public void testalldifferent_cond() {\n Solver solver = new Solver();\n IntVar[] XS = VF.enumeratedArray(\"XS\", 5, 0, 3, solver);\n solver.post(ICF.alldifferent_conditionnal(XS,\n x -> !x.contains(1) && !x.contains(3)));\n Chatterbox.showSolutions(solver);\n solver.findAllSolutions();\n }\n\n @Test(groups = \"1s\")\n public void testalldifferent_exc0() {\n Solver solver = new Solver();\n IntVar[] XS = VF.enumeratedArray(\"XS\", 4, 0, 2, solver);\n solver.post(ICF.alldifferent_except_0(XS));\n Chatterbox.showSolutions(solver);\n solver.findAllSolutions();\n }\n\n @Test(groups = \"1s\")\n public void testamong() {\n Solver solver = new Solver();\n IntVar N = VF.enumerated(\"N\", 2, 3, solver);\n IntVar[] XS = VF.enumeratedArray(\"XS\", 4, 0, 6, solver);\n solver.post(ICF.among(N, XS, new int[]{1, 2, 3}));\n Chatterbox.showSolutions(solver);\n solver.findAllSolutions();\n\n }\n\n @Test(groups = \"1s\")\n public void testatleast_nvalues() {\n Solver solver = new Solver();\n IntVar[] XS = VF.enumeratedArray(\"XS\", 4, 0, 2, solver);\n IntVar N = VF.enumerated(\"N\", 2, 3, solver);\n solver.post(ICF.atleast_nvalues(XS, N, true));\n Chatterbox.showSolutions(solver);\n solver.findAllSolutions();\n }\n\n @Test(groups = \"1s\")\n public void testatmost_nvalues() {\n Solver solver = new Solver();\n IntVar[] XS = VF.enumeratedArray(\"XS\", 4, 0, 2, solver);\n IntVar N = VF.enumerated(\"N\", 1, 3, solver);\n solver.post(ICF.atmost_nvalues(XS, N, false));\n Chatterbox.showSolutions(solver);\n solver.findAllSolutions();\n }\n\n @Test(groups = \"1s\")\n public void testbin_packing() {\n Solver solver = new Solver();\n IntVar[] IBIN = VF.enumeratedArray(\"IBIN\", 5, 1, 3, solver);\n int[] sizes = new int[]{2, 3, 1, 4, 2};\n IntVar[] BLOADS = VF.enumeratedArray(\"BLOADS\", 3, 0, 5, solver);\n solver.post(ICF.bin_packing(IBIN, sizes, BLOADS, 1));\n Chatterbox.showSolutions(solver);\n solver.findAllSolutions();\n }\n\n @Test(groups = \"1s\")\n public void testboolean_channeling() {\n Solver solver = new Solver();\n BoolVar[] BVARS = VF.boolArray(\"BVARS\", 5, solver);\n IntVar VAR = VF.enumerated(\"VAR\", 1, 5, solver);\n solver.post(ICF.boolean_channeling(BVARS, VAR, 1));\n Chatterbox.showSolutions(solver);\n solver.findAllSolutions();\n }\n\n @Test(groups = \"1s\")\n public void testcircuit() {\n Solver solver = new Solver();\n IntVar[] NODES = VF.enumeratedArray(\"NODES\", 5, 0, 4, solver);\n solver.post(ICF.circuit(NODES, 0, CircuitConf.LIGHT));\n Chatterbox.showSolutions(solver);\n solver.findAllSolutions();\n }\n\n @Test(groups = \"1s\")\n public void testcost_regular() {\n Solver solver = new Solver();\n IntVar[] VARS = VF.enumeratedArray(\"VARS\", 5, 0, 2, solver);\n IntVar COST = VF.enumerated(\"COST\", 0, 10, solver);\n FiniteAutomaton fauto = new FiniteAutomaton();\n int start = fauto.addState();\n int end = fauto.addState();\n fauto.setInitialState(start);\n fauto.setFinal(start, end);\n\n fauto.addTransition(start, start, 0, 1);\n fauto.addTransition(start, end, 2);\n\n fauto.addTransition(end, end, 1);\n fauto.addTransition(end, start, 0, 2);\n\n int[][] costs = new int[5][3];\n costs[0] = new int[]{1, 2, 3};\n costs[1] = new int[]{2, 3, 1};\n costs[2] = new int[]{3, 1, 2};\n costs[3] = new int[]{3, 2, 1};\n costs[4] = new int[]{2, 1, 3};\n\n solver.post(ICF.cost_regular(VARS, COST, CostAutomaton.makeSingleResource(fauto, costs, COST.getLB(), COST.getUB())));\n Chatterbox.showSolutions(solver);\n solver.findAllSolutions();\n }\n\n @Test(groups = \"1s\")\n public void testcount() {\n Solver solver = new Solver();\n IntVar[] VS = VF.enumeratedArray(\"VS\", 4, 0, 3, solver);\n IntVar VA = VF.enumerated(\"VA\", new int[]{1, 3}, solver);\n IntVar CO = VF.enumerated(\"CO\", new int[]{0, 2, 4}, solver);\n solver.post(ICF.count(VA, VS, CO));\n Chatterbox.showSolutions(solver);\n solver.findAllSolutions();\n }\n\n @Test(groups = \"1s\")\n public void testcumulative() {\n Solver solver = new Solver();\n Task[] TS = new Task[5];\n IntVar[] HE = new IntVar[5];\n for (int i = 0; i < TS.length; i++) {\n IntVar S = VF.bounded(\"S_\" + i, 0, 4, solver);\n TS[i] = VF.task(\n S,\n VF.fixed(\"D_\" + i, i + 1, solver),\n VF.offset(S, i + 1)\n );\n HE[i] = VF.bounded(\"HE_\" + i, i - 1, i + 1, solver);\n }\n IntVar CA = VF.enumerated(\"CA\", 1, 3, solver);\n solver.post(ICF.cumulative(TS, HE, CA, true));\n Chatterbox.showSolutions(solver);\n solver.findAllSolutions();\n }\n\n @Test(groups = \"1s\")\n public void testdiffn() {\n Solver solver = new Solver();\n IntVar[] X = VF.boundedArray(\"X\", 4, 0, 1, solver);\n IntVar[] Y = VF.boundedArray(\"Y\", 4, 0, 2, solver);\n IntVar[] D = new IntVar[4];\n IntVar[] W = new IntVar[4];\n for (int i = 0; i < 4; i++) {\n D[i] = VF.fixed(\"D_\" + i, 1, solver);\n W[i] = VF.fixed(\"W_\" + i, i + 1, solver);\n }\n solver.post(ICF.diffn(X, Y, D, W, true));\n Chatterbox.showSolutions(solver);\n solver.findAllSolutions();\n }\n\n @Test(groups = \"1s\")\n public void testglobal_cardinality() {\n Solver solver = new Solver();\n IntVar[] VS = VF.boundedArray(\"VS\", 4, 0, 4, solver);\n int[] values = new int[]{-1, 1, 2};\n IntVar[] OCC = VF.boundedArray(\"OCC\", 3, 0, 2, solver);\n solver.post(ICF.global_cardinality(VS, values, OCC, true));\n Chatterbox.showSolutions(solver);\n solver.findAllSolutions();\n }\n\n @Test(groups = \"1s\")\n public void testinverse_channeling() {\n Solver solver = new Solver();\n IntVar[] X = VF.enumeratedArray(\"X\", 3, 0, 3, solver);\n IntVar[] Y = VF.enumeratedArray(\"Y\", 3, 1, 4, solver);\n solver.post(ICF.inverse_channeling(X, Y, 0, 1));\n Chatterbox.showSolutions(solver);\n solver.findAllSolutions();\n }\n\n @Test(groups = \"1s\")\n public void testknapsack() {\n Solver solver = new Solver();\n IntVar[] IT = new IntVar[3]; // 3 items\n IT[0] = VF.bounded(\"IT_0\", 0, 3, solver);\n IT[1] = VF.bounded(\"IT_1\", 0, 2, solver);\n IT[2] = VF.bounded(\"IT_2\", 0, 1, solver);\n IntVar WE = VF.bounded(\"WE\", 0, 8, solver);\n IntVar EN = VF.bounded(\"EN\", 0, 6, solver);\n int[] weights = new int[]{1, 3, 4};\n int[] energies = new int[]{1, 4, 6};\n solver.post(ICF.knapsack(IT, WE, EN, weights, energies));\n Chatterbox.showSolutions(solver);\n solver.findAllSolutions();\n }\n\n @Test(groups = \"1s\")\n public void testlex_chain_less() {\n Solver solver = new Solver();\n IntVar[] X = VF.enumeratedArray(\"X\", 3, -1, 1, solver);\n IntVar[] Y = VF.enumeratedArray(\"Y\", 3, 1, 2, solver);\n IntVar[] Z = VF.enumeratedArray(\"Z\", 3, 0, 2, solver);\n solver.post(ICF.lex_chain_less(X, Y, Z));\n Chatterbox.showSolutions(solver);\n solver.findAllSolutions();\n }\n\n @Test(groups = \"1s\")\n public void testlex_chain_less_eq() {\n Solver solver = new Solver();\n IntVar[] X = VF.enumeratedArray(\"X\", 3, -1, 1, solver);\n IntVar[] Y = VF.enumeratedArray(\"Y\", 3, 1, 2, solver);\n IntVar[] Z = VF.enumeratedArray(\"Z\", 3, 0, 2, solver);\n solver.post(ICF.lex_chain_less_eq(X, Y, Z));\n Chatterbox.showSolutions(solver);\n solver.findAllSolutions();\n }\n\n @Test(groups = \"1s\")\n public void testlex_less() {\n Solver solver = new Solver();\n IntVar[] X = VF.enumeratedArray(\"X\", 3, -1, 1, solver);\n IntVar[] Y = VF.enumeratedArray(\"Y\", 3, 1, 2, solver);\n solver.post(ICF.lex_less(X, Y));\n Chatterbox.showSolutions(solver);\n solver.findAllSolutions();\n }\n\n @Test(groups = \"1s\")\n public void testlex_less_eq() {\n Solver solver = new Solver();", "answers": [" IntVar[] X = VF.enumeratedArray(\"X\", 3, -1, 1, solver);"], "length": 1783, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "876fa4e3-ad21-4cb9-b982-17647172c05e", "reasoning": "The method testlex_less_eq follows the same pattern as other test methods: after creating a Solver instance, it defines two IntVar arrays X and Y, posts the lex_less_eq constraint, shows solutions, and finds all solutions. The immediate next line after the Solver creation should be the declaration of the first variable array X.", "reasoning_model_answer": "IntVar[] X = VF.enumeratedArray(\"X\", 3, -1, 1, solver);", "assistant_with_reasoning": "\nThe method testlex_less_eq follows the same pattern as other test methods: after creating a Solver instance, it defines two IntVar arrays X and Y, posts the lex_less_eq constraint, shows solutions, and finds all solutions. The immediate next line after the Solver creation should be the declaration of the first variable array X.\n\nIntVar[] X = VF.enumeratedArray(\"X\", 3, -1, 1, solver);", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.439, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 17353, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "IntVar[] X = VF.enumeratedArray(\"X\", 3, -1, 1, solver);", "score": 0.93, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "\n# The following YAML grammar is LL(1) and is parsed by a recursive descent\n# parser.\n#\n# stream ::= STREAM-START implicit_document? explicit_document* STREAM-END\n# implicit_document ::= block_node DOCUMENT-END*\n# explicit_document ::= DIRECTIVE* DOCUMENT-START block_node? DOCUMENT-END*\n# block_node_or_indentless_sequence ::=\n# ALIAS\n# | properties (block_content | indentless_block_sequence)?\n# | block_content\n# | indentless_block_sequence\n# block_node ::= ALIAS\n# | properties block_content?\n# | block_content\n# flow_node ::= ALIAS\n# | properties flow_content?\n# | flow_content\n# properties ::= TAG ANCHOR? | ANCHOR TAG?\n# block_content ::= block_collection | flow_collection | SCALAR\n# flow_content ::= flow_collection | SCALAR\n# block_collection ::= block_sequence | block_mapping\n# flow_collection ::= flow_sequence | flow_mapping\n# block_sequence ::= BLOCK-SEQUENCE-START (BLOCK-ENTRY block_node?)* BLOCK-END\n# indentless_sequence ::= (BLOCK-ENTRY block_node?)+\n# block_mapping ::= BLOCK-MAPPING_START\n# ((KEY block_node_or_indentless_sequence?)?\n# (VALUE block_node_or_indentless_sequence?)?)*\n# BLOCK-END\n# flow_sequence ::= FLOW-SEQUENCE-START\n# (flow_sequence_entry FLOW-ENTRY)*\n# flow_sequence_entry?\n# FLOW-SEQUENCE-END\n# flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)?\n# flow_mapping ::= FLOW-MAPPING-START\n# (flow_mapping_entry FLOW-ENTRY)*\n# flow_mapping_entry?\n# FLOW-MAPPING-END\n# flow_mapping_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)?\n#\n# FIRST sets:\n#\n# stream: { STREAM-START }\n# explicit_document: { DIRECTIVE DOCUMENT-START }\n# implicit_document: FIRST(block_node)\n# block_node: { ALIAS TAG ANCHOR SCALAR BLOCK-SEQUENCE-START BLOCK-MAPPING-START FLOW-SEQUENCE-START FLOW-MAPPING-START }\n# flow_node: { ALIAS ANCHOR TAG SCALAR FLOW-SEQUENCE-START FLOW-MAPPING-START }\n# block_content: { BLOCK-SEQUENCE-START BLOCK-MAPPING-START FLOW-SEQUENCE-START FLOW-MAPPING-START SCALAR }\n# flow_content: { FLOW-SEQUENCE-START FLOW-MAPPING-START SCALAR }\n# block_collection: { BLOCK-SEQUENCE-START BLOCK-MAPPING-START }\n# flow_collection: { FLOW-SEQUENCE-START FLOW-MAPPING-START }\n# block_sequence: { BLOCK-SEQUENCE-START }\n# block_mapping: { BLOCK-MAPPING-START }\n# block_node_or_indentless_sequence: { ALIAS ANCHOR TAG SCALAR BLOCK-SEQUENCE-START BLOCK-MAPPING-START FLOW-SEQUENCE-START FLOW-MAPPING-START BLOCK-ENTRY }\n# indentless_sequence: { ENTRY }\n# flow_collection: { FLOW-SEQUENCE-START FLOW-MAPPING-START }\n# flow_sequence: { FLOW-SEQUENCE-START }\n# flow_mapping: { FLOW-MAPPING-START }\n# flow_sequence_entry: { ALIAS ANCHOR TAG SCALAR FLOW-SEQUENCE-START FLOW-MAPPING-START KEY }\n# flow_mapping_entry: { ALIAS ANCHOR TAG SCALAR FLOW-SEQUENCE-START FLOW-MAPPING-START KEY }\n\n__all__ = ['Parser', 'ParserError']\n\nfrom error import MarkedYAMLError\nfrom tokens import *\nfrom events import *\nfrom scanner import *\n\nclass ParserError(MarkedYAMLError):\n pass\n\nclass Parser(object):\n # Since writing a recursive-descendant parser is a straightforward task, we\n # do not give many comments here.\n # Note that we use Python generators. If you rewrite the parser in another\n # language, you may replace all 'yield'-s with event handler calls.\n\n DEFAULT_TAGS = {\n u'!': u'!',\n u'!!': u'tag:yaml.org,2002:',\n }\n\n def __init__(self):\n self.current_event = None\n self.yaml_version = None\n self.tag_handles = {}\n self.states = []\n self.marks = []\n self.state = self.parse_stream_start\n\n def check_event(self, *choices):\n # Check the type of the next event.\n if self.current_event is None:\n if self.state:\n self.current_event = self.state()\n if self.current_event is not None:\n if not choices:\n return True\n for choice in choices:\n if isinstance(self.current_event, choice):\n return True\n return False\n\n def peek_event(self):\n # Get the next event.\n if self.current_event is None:\n if self.state:\n self.current_event = self.state()\n return self.current_event\n\n def get_event(self):\n # Get the next event and proceed further.\n if self.current_event is None:\n if self.state:\n self.current_event = self.state()\n value = self.current_event\n self.current_event = None\n return value\n\n # stream ::= STREAM-START implicit_document? explicit_document* STREAM-END\n # implicit_document ::= block_node DOCUMENT-END*\n # explicit_document ::= DIRECTIVE* DOCUMENT-START block_node? DOCUMENT-END*\n\n def parse_stream_start(self):\n\n # Parse the stream start.\n token = self.get_token()\n event = StreamStartEvent(token.start_mark, token.end_mark,\n encoding=token.encoding)\n\n # Prepare the next state.\n self.state = self.parse_implicit_document_start\n\n return event\n\n def parse_implicit_document_start(self):\n\n # Parse an implicit document.\n if not self.check_token(DirectiveToken, DocumentStartToken,\n StreamEndToken):\n self.tag_handles = self.DEFAULT_TAGS\n token = self.peek_token()\n start_mark = end_mark = token.start_mark\n event = DocumentStartEvent(start_mark, end_mark,\n explicit=False)\n\n # Prepare the next state.\n self.states.append(self.parse_document_end)\n self.state = self.parse_block_node\n\n return event\n\n else:\n return self.parse_document_start()\n\n def parse_document_start(self):\n\n # Parse an explicit document.\n if not self.check_token(StreamEndToken):\n token = self.peek_token()\n start_mark = token.start_mark\n version, tags = self.process_directives()\n if not self.check_token(DocumentStartToken):\n raise ParserError(None, None,\n \"expected '', but found %r\"\n % self.peek_token().id,\n self.peek_token().start_mark)\n token = self.get_token()\n end_mark = token.end_mark\n event = DocumentStartEvent(start_mark, end_mark,\n explicit=True, version=version, tags=tags)\n self.states.append(self.parse_document_end)\n self.state = self.parse_document_content\n else:\n # Parse the end of the stream.\n token = self.get_token()\n event = StreamEndEvent(token.start_mark, token.end_mark)\n assert not self.states\n assert not self.marks\n self.state = None\n return event\n\n def parse_document_end(self):\n\n # Parse the document end.\n token = self.peek_token()\n start_mark = end_mark = token.start_mark\n explicit = False\n while self.check_token(DocumentEndToken):\n token = self.get_token()\n end_mark = token.end_mark\n explicit = True\n event = DocumentEndEvent(start_mark, end_mark,\n explicit=explicit)\n\n # Prepare the next state.\n self.state = self.parse_document_start\n\n return event\n\n def parse_document_content(self):\n if self.check_token(DirectiveToken,\n DocumentStartToken, DocumentEndToken, StreamEndToken):\n event = self.process_empty_scalar(self.peek_token().start_mark)\n self.state = self.states.pop()\n return event\n else:\n return self.parse_block_node()\n\n def process_directives(self):\n self.yaml_version = None\n self.tag_handles = {}\n while self.check_token(DirectiveToken):\n token = self.get_token()\n if token.name == u'YAML':\n if self.yaml_version is not None:\n raise ParserError(None, None,\n \"found duplicate YAML directive\", token.start_mark)\n major, minor = token.value\n if major != 1:\n raise ParserError(None, None,\n \"found incompatible YAML document (version 1.* is required)\",\n token.start_mark)\n self.yaml_version = token.value\n elif token.name == u'TAG':\n handle, prefix = token.value\n if handle in self.tag_handles:\n raise ParserError(None, None,\n \"duplicate tag handle %r\" % handle.encode('utf-8'),\n token.start_mark)\n self.tag_handles[handle] = prefix\n if self.tag_handles:\n value = self.yaml_version, self.tag_handles.copy()\n else:\n value = self.yaml_version, None\n for key in self.DEFAULT_TAGS:\n if key not in self.tag_handles:\n self.tag_handles[key] = self.DEFAULT_TAGS[key]\n return value\n\n # block_node_or_indentless_sequence ::= ALIAS\n # | properties (block_content | indentless_block_sequence)?\n # | block_content\n # | indentless_block_sequence\n # block_node ::= ALIAS\n # | properties block_content?\n # | block_content\n # flow_node ::= ALIAS\n # | properties flow_content?\n # | flow_content\n # properties ::= TAG ANCHOR? | ANCHOR TAG?\n # block_content ::= block_collection | flow_collection | SCALAR\n # flow_content ::= flow_collection | SCALAR\n # block_collection ::= block_sequence | block_mapping\n # flow_collection ::= flow_sequence | flow_mapping\n\n def parse_block_node(self):\n return self.parse_node(block=True)\n\n def parse_flow_node(self):\n return self.parse_node()\n\n def parse_block_node_or_indentless_sequence(self):\n return self.parse_node(block=True, indentless_sequence=True)\n\n def parse_node(self, block=False, indentless_sequence=False):\n if self.check_token(AliasToken):\n token = self.get_token()\n event = AliasEvent(token.value, token.start_mark, token.end_mark)\n self.state = self.states.pop()\n else:\n anchor = None\n tag = None\n start_mark = end_mark = tag_mark = None\n if self.check_token(AnchorToken):\n token = self.get_token()\n start_mark = token.start_mark\n end_mark = token.end_mark\n anchor = token.value\n if self.check_token(TagToken):\n token = self.get_token()\n tag_mark = token.start_mark\n end_mark = token.end_mark\n tag = token.value\n elif self.check_token(TagToken):\n token = self.get_token()\n start_mark = tag_mark = token.start_mark\n end_mark = token.end_mark\n tag = token.value\n if self.check_token(AnchorToken):\n token = self.get_token()\n end_mark = token.end_mark\n anchor = token.value\n if tag is not None and tag != u'!':\n handle, suffix = tag\n if handle is not None:\n if handle not in self.tag_handles:\n raise ParserError(\"while parsing a node\", start_mark,\n \"found undefined tag handle %r\" % handle.encode('utf-8'),\n tag_mark)\n tag = self.tag_handles[handle]+suffix\n else:\n tag = suffix\n #if tag == u'!':\n # raise ParserError(\"while parsing a node\", start_mark,\n # \"found non-specific tag '!'\", tag_mark,\n # \"Please check 'http://pyyaml.org/wiki/YAMLNonSpecificTag' and share your opinion.\")\n if start_mark is None:\n start_mark = end_mark = self.peek_token().start_mark\n event = None\n implicit = (tag is None or tag == u'!')\n if indentless_sequence and self.check_token(BlockEntryToken):\n end_mark = self.peek_token().end_mark\n event = SequenceStartEvent(anchor, tag, implicit,\n start_mark, end_mark)\n self.state = self.parse_indentless_sequence_entry\n else:\n if self.check_token(ScalarToken):\n token = self.get_token()\n end_mark = token.end_mark\n if (token.plain and tag is None) or tag == u'!':\n implicit = (True, False)\n elif tag is None:\n implicit = (False, True)\n else:\n implicit = (False, False)\n event = ScalarEvent(anchor, tag, implicit, token.value,\n start_mark, end_mark, style=token.style)\n self.state = self.states.pop()\n elif self.check_token(FlowSequenceStartToken):\n end_mark = self.peek_token().end_mark\n event = SequenceStartEvent(anchor, tag, implicit,\n start_mark, end_mark, flow_style=True)\n self.state = self.parse_flow_sequence_first_entry\n elif self.check_token(FlowMappingStartToken):\n end_mark = self.peek_token().end_mark\n event = MappingStartEvent(anchor, tag, implicit,\n start_mark, end_mark, flow_style=True)\n self.state = self.parse_flow_mapping_first_key\n elif block and self.check_token(BlockSequenceStartToken):\n end_mark = self.peek_token().start_mark\n event = SequenceStartEvent(anchor, tag, implicit,\n start_mark, end_mark, flow_style=False)\n self.state = self.parse_block_sequence_first_entry\n elif block and self.check_token(BlockMappingStartToken):\n end_mark = self.peek_token().start_mark\n event = MappingStartEvent(anchor, tag, implicit,\n start_mark, end_mark, flow_style=False)\n self.state = self.parse_block_mapping_first_key\n elif anchor is not None or tag is not None:\n # Empty scalars are allowed even if a tag or an anchor is\n # specified.\n event = ScalarEvent(anchor, tag, (implicit, False), u'',\n start_mark, end_mark)\n self.state = self.states.pop()\n else:\n if block:\n node = 'block'\n else:\n node = 'flow'\n token = self.peek_token()\n raise ParserError(\"while parsing a %s node\" % node, start_mark,\n \"expected the node content, but found %r\" % token.id,\n token.start_mark)\n return event\n\n # block_sequence ::= BLOCK-SEQUENCE-START (BLOCK-ENTRY block_node?)* BLOCK-END\n\n def parse_block_sequence_first_entry(self):\n token = self.get_token()\n self.marks.append(token.start_mark)\n return self.parse_block_sequence_entry()\n\n def parse_block_sequence_entry(self):\n if self.check_token(BlockEntryToken):\n token = self.get_token()\n if not self.check_token(BlockEntryToken, BlockEndToken):\n self.states.append(self.parse_block_sequence_entry)\n return self.parse_block_node()\n else:\n self.state = self.parse_block_sequence_entry\n return self.process_empty_scalar(token.end_mark)\n if not self.check_token(BlockEndToken):\n token = self.peek_token()\n raise ParserError(\"while parsing a block collection\", self.marks[-1],\n \"expected , but found %r\" % token.id, token.start_mark)\n token = self.get_token()\n event = SequenceEndEvent(token.start_mark, token.end_mark)\n self.state = self.states.pop()\n self.marks.pop()\n return event\n\n # indentless_sequence ::= (BLOCK-ENTRY block_node?)+\n\n def parse_indentless_sequence_entry(self):\n if self.check_token(BlockEntryToken):\n token = self.get_token()\n if not self.check_token(BlockEntryToken,\n KeyToken, ValueToken, BlockEndToken):\n self.states.append(self.parse_indentless_sequence_entry)\n return self.parse_block_node()\n else:\n self.state = self.parse_indentless_sequence_entry\n return self.process_empty_scalar(token.end_mark)\n token = self.peek_token()\n event = SequenceEndEvent(token.start_mark, token.start_mark)\n self.state = self.states.pop()\n return event\n\n # block_mapping ::= BLOCK-MAPPING_START\n # ((KEY block_node_or_indentless_sequence?)?\n # (VALUE block_node_or_indentless_sequence?)?)*\n # BLOCK-END\n", "answers": [" def parse_block_mapping_first_key(self):"], "length": 1410, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "83735ba9-0430-4971-a5ad-89fc00749c4a", "reasoning": "The comment just introduced the grammar rule for block_mapping. In the parser implementation, the next logical step is to define the method that handles the first key of a block mapping, following the pattern used for block sequences. In PyYAML, after the block_mapping comment the next line is the method definition for parsing the first key of a block mapping.", "reasoning_model_answer": "def parse_block_mapping_first_key(self):", "assistant_with_reasoning": "\nThe comment just introduced the grammar rule for block_mapping. In the parser implementation, the next logical step is to define the method that handles the first key of a block mapping, following the pattern used for block sequences. In PyYAML, after the block_mapping comment the next line is the method definition for parsing the first key of a block mapping.\n\ndef parse_block_mapping_first_key(self):", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 2.519, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 17920, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "def parse_block_mapping_first_key(self):", "score": 0.95, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nfrom heat.engine import attributes\nfrom heat.engine import constraints\nfrom heat.engine import properties\nfrom heat.engine.resources.neutron import neutron\nfrom heat.engine import support\n\n\nclass VPNService(neutron.NeutronResource):\n \"\"\"\n A resource for VPN service in Neutron.\n \"\"\"\n\n PROPERTIES = (\n NAME, DESCRIPTION, ADMIN_STATE_UP,\n SUBNET_ID, SUBNET, ROUTER_ID,\n ) = (\n 'name', 'description', 'admin_state_up',\n 'subnet_id', 'subnet', 'router_id',\n )\n\n ATTRIBUTES = (\n ADMIN_STATE_UP_ATTR, DESCRIPTION_ATTR, NAME_ATTR, ROUTER_ID_ATTR,\n STATUS, SUBNET_ID_ATTR, TENANT_ID, SHOW,\n ) = (\n 'admin_state_up', 'description', 'name', 'router_id',\n 'status', 'subnet_id', 'tenant_id', 'show',\n )\n\n properties_schema = {\n NAME: properties.Schema(\n properties.Schema.STRING,\n _('Name for the vpn service.'),\n update_allowed=True\n ),\n DESCRIPTION: properties.Schema(\n properties.Schema.STRING,\n _('Description for the vpn service.'),\n update_allowed=True\n ),\n ADMIN_STATE_UP: properties.Schema(\n properties.Schema.BOOLEAN,\n _('Administrative state for the vpn service.'),\n default=True,\n update_allowed=True\n ),\n SUBNET_ID: properties.Schema(\n properties.Schema.STRING,\n support_status=support.SupportStatus(\n support.DEPRECATED,\n _('Use property %s.') % SUBNET),\n required=False\n ),\n SUBNET: properties.Schema(\n properties.Schema.STRING,\n _('Subnet in which the vpn service will be created.'),\n required=False\n ),\n ROUTER_ID: properties.Schema(\n properties.Schema.STRING,\n _('Unique identifier for the router to which the vpn service '\n 'will be inserted.'),\n required=True\n ),\n }\n\n attributes_schema = {\n ADMIN_STATE_UP_ATTR: attributes.Schema(\n _('The administrative state of the vpn service.')\n ),\n DESCRIPTION_ATTR: attributes.Schema(\n _('The description of the vpn service.')\n ),\n NAME_ATTR: attributes.Schema(\n _('The name of the vpn service.')\n ),\n ROUTER_ID_ATTR: attributes.Schema(\n _('The unique identifier of the router to which the vpn service '\n 'was inserted.')\n ),\n STATUS: attributes.Schema(\n _('The status of the vpn service.')\n ),\n SUBNET_ID_ATTR: attributes.Schema(\n _('The unique identifier of the subnet in which the vpn service '\n 'was created.')\n ),\n TENANT_ID: attributes.Schema(\n _('The unique identifier of the tenant owning the vpn service.')\n ),\n SHOW: attributes.Schema(\n _('All attributes.')\n ),\n }\n\n def _show_resource(self):\n return self.neutron().show_vpnservice(self.resource_id)['vpnservice']\n\n def validate(self):\n super(VPNService, self).validate()\n self._validate_depr_property_required(\n self.properties, self.SUBNET, self.SUBNET_ID)\n\n def handle_create(self):\n props = self.prepare_properties(\n self.properties,\n self.physical_resource_name())\n self.client_plugin().resolve_subnet(props, self.SUBNET, 'subnet_id')\n vpnservice = self.neutron().create_vpnservice({'vpnservice': props})[\n 'vpnservice']\n self.resource_id_set(vpnservice['id'])\n\n def handle_update(self, json_snippet, tmpl_diff, prop_diff):\n if prop_diff:\n self.neutron().update_vpnservice(self.resource_id,\n {'vpnservice': prop_diff})\n\n def handle_delete(self):\n client = self.neutron()\n try:\n client.delete_vpnservice(self.resource_id)\n except Exception as ex:\n self.client_plugin().ignore_not_found(ex)\n else:\n return self._delete_task()\n\n\nclass IPsecSiteConnection(neutron.NeutronResource):\n \"\"\"\n A resource for IPsec site connection in Neutron.\n \"\"\"\n\n PROPERTIES = (\n NAME, DESCRIPTION, PEER_ADDRESS, PEER_ID, PEER_CIDRS, MTU,\n DPD, PSK, INITIATOR, ADMIN_STATE_UP, IKEPOLICY_ID,\n IPSECPOLICY_ID, VPNSERVICE_ID,\n ) = (\n 'name', 'description', 'peer_address', 'peer_id', 'peer_cidrs', 'mtu',\n 'dpd', 'psk', 'initiator', 'admin_state_up', 'ikepolicy_id',\n 'ipsecpolicy_id', 'vpnservice_id',\n )\n\n _DPD_KEYS = (\n DPD_ACTIONS, DPD_INTERVAL, DPD_TIMEOUT,\n ) = (\n 'actions', 'interval', 'timeout',\n )\n\n ATTRIBUTES = (\n ADMIN_STATE_UP_ATTR, AUTH_MODE, DESCRIPTION_ATTR, DPD_ATTR,\n IKEPOLICY_ID_ATTR, INITIATOR_ATTR, IPSECPOLICY_ID_ATTR, MTU_ATTR,\n NAME_ATTR, PEER_ADDRESS_ATTR, PEER_CIDRS_ATTR, PEER_ID_ATTR, PSK_ATTR,\n ROUTE_MODE, STATUS, TENANT_ID, VPNSERVICE_ID_ATTR,\n ) = (\n 'admin_state_up', 'auth_mode', 'description', 'dpd',\n 'ikepolicy_id', 'initiator', 'ipsecpolicy_id', 'mtu',\n 'name', 'peer_address', 'peer_cidrs', 'peer_id', 'psk',\n 'route_mode', 'status', 'tenant_id', 'vpnservice_id',\n )\n\n properties_schema = {\n NAME: properties.Schema(\n properties.Schema.STRING,\n _('Name for the ipsec site connection.'),\n update_allowed=True\n ),\n DESCRIPTION: properties.Schema(\n properties.Schema.STRING,\n _('Description for the ipsec site connection.'),\n update_allowed=True\n ),\n PEER_ADDRESS: properties.Schema(\n properties.Schema.STRING,\n _('Remote branch router public IPv4 address or IPv6 address or '\n 'FQDN.'),\n required=True\n ),\n PEER_ID: properties.Schema(\n properties.Schema.STRING,\n _('Remote branch router identity.'),\n required=True\n ),\n PEER_CIDRS: properties.Schema(\n properties.Schema.LIST,\n _('Remote subnet(s) in CIDR format.'),\n required=True\n ),\n MTU: properties.Schema(\n properties.Schema.INTEGER,\n _('Maximum transmission unit size (in bytes) for the ipsec site '\n 'connection.'),\n default=1500\n ),\n DPD: properties.Schema(\n properties.Schema.MAP,\n _('Dead Peer Detection protocol configuration for the ipsec site '\n 'connection.'),\n schema={\n DPD_ACTIONS: properties.Schema(\n properties.Schema.STRING,\n _('Controls DPD protocol mode.'),\n default='hold',\n constraints=[\n constraints.AllowedValues(['clear', 'disabled',\n 'hold', 'restart',\n 'restart-by-peer']),\n ]\n ),\n DPD_INTERVAL: properties.Schema(\n properties.Schema.INTEGER,\n _('Number of seconds for the DPD delay.'),\n default=30\n ),\n DPD_TIMEOUT: properties.Schema(\n properties.Schema.INTEGER,\n _('Number of seconds for the DPD timeout.'),\n default=120\n ),\n }\n ),\n PSK: properties.Schema(\n properties.Schema.STRING,\n _('Pre-shared key string for the ipsec site connection.'),\n required=True\n ),\n INITIATOR: properties.Schema(\n properties.Schema.STRING,\n _('Initiator state in lowercase for the ipsec site connection.'),\n default='bi-directional',\n constraints=[\n constraints.AllowedValues(['bi-directional', 'response-only']),\n ]\n ),\n ADMIN_STATE_UP: properties.Schema(\n properties.Schema.BOOLEAN,\n _('Administrative state for the ipsec site connection.'),\n default=True,\n update_allowed=True\n ),\n IKEPOLICY_ID: properties.Schema(\n properties.Schema.STRING,\n _('Unique identifier for the ike policy associated with the '\n 'ipsec site connection.'),\n required=True\n ),\n IPSECPOLICY_ID: properties.Schema(\n properties.Schema.STRING,\n _('Unique identifier for the ipsec policy associated with the '\n 'ipsec site connection.'),\n required=True\n ),\n VPNSERVICE_ID: properties.Schema(\n properties.Schema.STRING,\n _('Unique identifier for the vpn service associated with the '\n 'ipsec site connection.'),\n required=True\n ),\n }\n\n attributes_schema = {\n ADMIN_STATE_UP_ATTR: attributes.Schema(\n _('The administrative state of the ipsec site connection.')\n ),\n AUTH_MODE: attributes.Schema(\n _('The authentication mode of the ipsec site connection.')\n ),\n DESCRIPTION_ATTR: attributes.Schema(\n _('The description of the ipsec site connection.')\n ),\n DPD_ATTR: attributes.Schema(\n _('The dead peer detection protocol configuration of the ipsec '\n 'site connection.')\n ),\n IKEPOLICY_ID_ATTR: attributes.Schema(\n _('The unique identifier of ike policy associated with the ipsec '\n 'site connection.')\n ),\n INITIATOR_ATTR: attributes.Schema(\n _('The initiator of the ipsec site connection.')\n ),\n IPSECPOLICY_ID_ATTR: attributes.Schema(\n _('The unique identifier of ipsec policy associated with the '\n 'ipsec site connection.')\n ),\n MTU_ATTR: attributes.Schema(\n _('The maximum transmission unit size (in bytes) of the ipsec '\n 'site connection.')\n ),\n NAME_ATTR: attributes.Schema(\n _('The name of the ipsec site connection.')\n ),\n PEER_ADDRESS_ATTR: attributes.Schema(\n _('The remote branch router public IPv4 address or IPv6 address '\n 'or FQDN.')\n ),\n PEER_CIDRS_ATTR: attributes.Schema(\n _('The remote subnet(s) in CIDR format of the ipsec site '\n 'connection.')\n ),\n PEER_ID_ATTR: attributes.Schema(\n _('The remote branch router identity of the ipsec site '\n 'connection.')\n ),\n PSK_ATTR: attributes.Schema(\n _('The pre-shared key string of the ipsec site connection.')\n ),\n ROUTE_MODE: attributes.Schema(\n _('The route mode of the ipsec site connection.')\n ),\n STATUS: attributes.Schema(\n _('The status of the ipsec site connection.')\n ),\n TENANT_ID: attributes.Schema(\n _('The unique identifier of the tenant owning the ipsec site '\n 'connection.')\n ),\n VPNSERVICE_ID_ATTR: attributes.Schema(\n _('The unique identifier of vpn service associated with the ipsec '\n 'site connection.')\n ),\n }\n\n def _show_resource(self):\n return self.neutron().show_ipsec_site_connection(self.resource_id)[\n 'ipsec_site_connection']\n\n def handle_create(self):\n props = self.prepare_properties(\n self.properties,\n self.physical_resource_name())\n ipsec_site_connection = self.neutron().create_ipsec_site_connection(\n {'ipsec_site_connection': props})['ipsec_site_connection']\n self.resource_id_set(ipsec_site_connection['id'])\n\n def handle_update(self, json_snippet, tmpl_diff, prop_diff):\n if prop_diff:\n self.neutron().update_ipsec_site_connection(\n self.resource_id, {'ipsec_site_connection': prop_diff})\n\n def handle_delete(self):\n client = self.neutron()\n try:\n client.delete_ipsec_site_connection(self.resource_id)\n except Exception as ex:\n self.client_plugin().ignore_not_found(ex)\n else:\n return self._delete_task()\n\n\nclass IKEPolicy(neutron.NeutronResource):\n \"\"\"\n A resource for IKE policy in Neutron.\n \"\"\"\n\n PROPERTIES = (\n NAME, DESCRIPTION, AUTH_ALGORITHM, ENCRYPTION_ALGORITHM,\n PHASE1_NEGOTIATION_MODE, LIFETIME, PFS, IKE_VERSION,\n ) = (\n 'name', 'description', 'auth_algorithm', 'encryption_algorithm',\n 'phase1_negotiation_mode', 'lifetime', 'pfs', 'ike_version',\n )\n\n _LIFETIME_KEYS = (\n LIFETIME_UNITS, LIFETIME_VALUE,\n ) = (\n 'units', 'value',\n )\n\n ATTRIBUTES = (\n AUTH_ALGORITHM_ATTR, DESCRIPTION_ATTR, ENCRYPTION_ALGORITHM_ATTR,\n IKE_VERSION_ATTR, LIFETIME_ATTR, NAME_ATTR, PFS_ATTR,\n PHASE1_NEGOTIATION_MODE_ATTR, TENANT_ID,\n ) = (\n 'auth_algorithm', 'description', 'encryption_algorithm',\n 'ike_version', 'lifetime', 'name', 'pfs',\n 'phase1_negotiation_mode', 'tenant_id',\n )\n\n properties_schema = {\n NAME: properties.Schema(\n properties.Schema.STRING,\n _('Name for the ike policy.'),\n update_allowed=True\n ),\n DESCRIPTION: properties.Schema(\n properties.Schema.STRING,\n _('Description for the ike policy.'),\n update_allowed=True\n ),\n AUTH_ALGORITHM: properties.Schema(\n properties.Schema.STRING,\n _('Authentication hash algorithm for the ike policy.'),\n default='sha1',\n constraints=[\n constraints.AllowedValues(['sha1']),\n ]\n ),\n ENCRYPTION_ALGORITHM: properties.Schema(\n properties.Schema.STRING,\n _('Encryption algorithm for the ike policy.'),\n default='aes-128',\n constraints=[\n constraints.AllowedValues(['3des', 'aes-128', 'aes-192',\n 'aes-256']),\n ]\n ),\n PHASE1_NEGOTIATION_MODE: properties.Schema(\n properties.Schema.STRING,\n _('Negotiation mode for the ike policy.'),\n default='main',\n constraints=[\n constraints.AllowedValues(['main']),\n ]\n ),\n LIFETIME: properties.Schema(\n properties.Schema.MAP,\n _('Safety assessment lifetime configuration for the ike policy.'),\n schema={\n LIFETIME_UNITS: properties.Schema(\n properties.Schema.STRING,\n _('Safety assessment lifetime units.'),\n default='seconds',\n constraints=[\n constraints.AllowedValues(['seconds', 'kilobytes']),\n ]\n ),\n LIFETIME_VALUE: properties.Schema(\n properties.Schema.INTEGER,\n _('Safety assessment lifetime value in specified '\n 'units.'),\n default=3600\n ),\n }\n ),\n PFS: properties.Schema(\n properties.Schema.STRING,\n _('Perfect forward secrecy in lowercase for the ike policy.'),\n default='group5',\n constraints=[\n constraints.AllowedValues(['group2', 'group5', 'group14']),\n ]\n ),\n IKE_VERSION: properties.Schema(\n properties.Schema.STRING,\n _('Version for the ike policy.'),\n default='v1',\n constraints=[\n constraints.AllowedValues(['v1', 'v2']),\n ]\n ),\n }\n\n attributes_schema = {\n AUTH_ALGORITHM_ATTR: attributes.Schema(\n _('The authentication hash algorithm used by the ike policy.')\n ),\n DESCRIPTION_ATTR: attributes.Schema(\n _('The description of the ike policy.')\n ),\n ENCRYPTION_ALGORITHM_ATTR: attributes.Schema(\n _('The encryption algorithm used by the ike policy.')\n ),\n IKE_VERSION_ATTR: attributes.Schema(\n _('The version of the ike policy.')\n ),\n LIFETIME_ATTR: attributes.Schema(\n _('The safety assessment lifetime configuration for the ike '\n 'policy.')\n ),\n NAME_ATTR: attributes.Schema(\n _('The name of the ike policy.')\n ),\n PFS_ATTR: attributes.Schema(\n _('The perfect forward secrecy of the ike policy.')\n ),\n PHASE1_NEGOTIATION_MODE_ATTR: attributes.Schema(\n _('The negotiation mode of the ike policy.')\n ),\n TENANT_ID: attributes.Schema(\n _('The unique identifier of the tenant owning the ike policy.')\n ),\n }\n\n def _show_resource(self):\n return self.neutron().show_ikepolicy(self.resource_id)['ikepolicy']\n\n def handle_create(self):\n props = self.prepare_properties(\n self.properties,\n self.physical_resource_name())\n ikepolicy = self.neutron().create_ikepolicy({'ikepolicy': props})[\n 'ikepolicy']\n self.resource_id_set(ikepolicy['id'])\n\n def handle_update(self, json_snippet, tmpl_diff, prop_diff):\n if prop_diff:\n self.neutron().update_ikepolicy(self.resource_id,\n {'ikepolicy': prop_diff})\n\n def handle_delete(self):\n client = self.neutron()\n try:\n client.delete_ikepolicy(self.resource_id)", "answers": [" except Exception as ex:"], "length": 1348, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "f9097ea7-6530-409c-88ce-8435ca195447", "reasoning": "The handle_delete method follows the same pattern as other resources: after trying to delete, it catches exceptions to ignore not-found errors. The next line should start the except block handling Exception as ex.", "reasoning_model_answer": "except Exception as ex:", "assistant_with_reasoning": "\nThe handle_delete method follows the same pattern as other resources: after trying to delete, it catches exceptions to ignore not-found errors. The next line should start the except block handling Exception as ex.\n\nexcept Exception as ex:", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.278, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 18467, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "except Exception as ex:", "score": 0.85, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "package com.handstudio.android.hzgrapherlib.graphview;\n\nimport java.util.WeakHashMap;\n\nimport android.content.Context;\nimport android.graphics.Bitmap;\nimport android.graphics.BitmapFactory;\nimport android.graphics.Canvas;\nimport android.graphics.Color;\nimport android.graphics.DashPathEffect;\nimport android.graphics.LinearGradient;\nimport android.graphics.Matrix;\nimport android.graphics.Paint;\nimport android.graphics.Paint.Style;\nimport android.graphics.Rect;\nimport android.graphics.Shader;\nimport android.util.AttributeSet;\nimport android.util.Log;\nimport android.view.MotionEvent;\nimport android.view.SurfaceHolder;\nimport android.view.SurfaceHolder.Callback;\nimport android.view.SurfaceView;\n\nimport com.handstudio.android.hzgrapherlib.animation.GraphAnimation;\nimport com.handstudio.android.hzgrapherlib.canvas.GraphCanvasWrapper;\nimport com.handstudio.android.hzgrapherlib.error.ErrorCode;\nimport com.handstudio.android.hzgrapherlib.error.ErrorDetector;\nimport com.handstudio.android.hzgrapherlib.path.GraphPath;\nimport com.handstudio.android.hzgrapherlib.util.Spline;\nimport com.handstudio.android.hzgrapherlib.vo.GraphNameBox;\nimport com.handstudio.android.hzgrapherlib.vo.curvegraph.CurveGraphVO;\n\npublic class CurveGraphView extends SurfaceView implements Callback{\n\n\tpublic static final String TAG = \"CurveGraphView\";\n\tprivate SurfaceHolder mHolder;\n\tprivate DrawThread mDrawThread;\n\t\n\tprivate CurveGraphVO mCurveGraphVO = null;\n\tprivate Spline spline = null;\n\t\n\t//Constructor\n\tpublic CurveGraphView(Context context, CurveGraphVO vo) {\n\t\tsuper(context);\n\t\tmCurveGraphVO = vo;\n\t\tinitView(context, vo);\n\t}\n\t\n\tprivate void initView(Context context, CurveGraphVO vo) {\n\t\tErrorCode ec = ErrorDetector.checkGraphObject(vo);\n\t\tec.printError();\n\t\t\n\t\tmHolder = getHolder();\n\t\tmHolder.addCallback(this);\n\t}\n\n\t@Override\n\tpublic void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { }\n\n\t@Override\n\tpublic void surfaceCreated(SurfaceHolder holder) {\n\t\tif(mDrawThread == null){\n\t\t\tmDrawThread = new DrawThread(mHolder, getContext());\n\t\t\tmDrawThread.start();\n\t\t}\n\t}\n\n\t@Override\n\tpublic void surfaceDestroyed(SurfaceHolder holder) {\n\t\tif(mDrawThread != null){\n\t\t\tmDrawThread.setRunFlag(false);\n\t\t\tmDrawThread = null;\n\t\t}\n\t}\n\t\n\tprivate static final Object touchLock = new Object(); // touch synchronize\n\t\n\t@Override\n\tpublic boolean onTouchEvent(MotionEvent event) {\n\t\tint action = event.getAction();\n\t\t\n\t\tif(mDrawThread == null ){\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\tif(action == MotionEvent.ACTION_DOWN){\n\t\t\tsynchronized (touchLock) {\n\t\t\t\tmDrawThread.isDirty = true;\n\t }\n\t\t\treturn true;\n\t\t}else if(action == MotionEvent.ACTION_MOVE){\n\t\t\tsynchronized (touchLock) {\n\t\t\t\tmDrawThread.isDirty = true;\n\t }\n\t\t\treturn true;\n\t\t}else if(action == MotionEvent.ACTION_UP){\n\t\t\tsynchronized (touchLock) {\n\t\t\t\tmDrawThread.isDirty = true;\n\t }\n\t\t\treturn true;\n\t\t}\n\t\t\n\t\treturn super.onTouchEvent(event);\n\t}\n\t\n\tclass DrawThread extends Thread{\n\t\tSurfaceHolder mHolder;\n\t\tContext mCtx;\n\t\t\n\t\tboolean isRun = true;\n\t\tboolean isDirty = true;\n\t\t\n\t\tMatrix matrix = new Matrix();\n\t\t\n\t\tint height = getHeight();\n\t\tint width = getWidth();\n\t\t\n\t\t//graph length\n\t\tint xLength = width - (mCurveGraphVO.getPaddingLeft() + mCurveGraphVO.getPaddingRight() + mCurveGraphVO.getMarginRight());\n\t\tint yLength = height - (mCurveGraphVO.getPaddingBottom() + mCurveGraphVO.getPaddingTop() + mCurveGraphVO.getMarginTop());\n\t\t\n\t\t//chart length\n\t\tint chartXLength = width - (mCurveGraphVO.getPaddingLeft() + mCurveGraphVO.getPaddingRight());\n\t\tint chartYLength = height - (mCurveGraphVO.getPaddingBottom() + mCurveGraphVO.getPaddingTop());\n\t\t\n\t\tPaint p = new Paint();\n\t\tPaint pCircle = new Paint();\n\t\tPaint pCurve = new Paint();\n\t\tPaint pBaseLine = new Paint();\n\t\tPaint pBaseLineX = new Paint();\n\t\tPaint pMarkText = new Paint();\n\t\t\n\t\t//animation\n\t\tfloat anim = 0.0f;\n\t\tboolean isAnimation = false;\n\t\tboolean isDrawRegion = false;\n\t\tlong animStartTime = -1;\n\t\tint animationType = 0;\n\t\t\n\t\tWeakHashMap arrIcon = new WeakHashMap();\n\t\tBitmap bg = null;\n\t\tpublic DrawThread(SurfaceHolder holder, Context context) {\n\t\t\tmHolder = holder;\n\t\t\tmCtx = context;\n\t\t\t\n\t\t\tint size = mCurveGraphVO.getArrGraph().size();\n\t\t\tfor (int i = 0; i < size; i++) {\n\t\t\t\tint bitmapResource = mCurveGraphVO.getArrGraph().get(i).getBitmapResource();\n\t\t\t\tif(bitmapResource != -1){\n\t\t\t\t\tarrIcon.put(i, BitmapFactory.decodeResource(getResources(), bitmapResource));\n\t\t\t\t}else{\n\t\t\t\t\tif(arrIcon.get(i) != null){\n\t\t\t\t\t\tarrIcon.remove(i);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tint bgResource = mCurveGraphVO.getGraphBG();\n\t\t\tif(bgResource != -1){\n\t\t\t\tBitmap tempBg = BitmapFactory.decodeResource(getResources(), bgResource);\n\t\t\t\tbg = Bitmap.createScaledBitmap(tempBg, width, height, true);\n\t\t\t\ttempBg.recycle();\n\t\t\t}\n\t\t}\n\t\t\n\t\tpublic void setRunFlag(boolean bool){\n\t\t\tisRun = bool;\n\t\t}\n\t\t\n\t\t@Override\n\t\tpublic void run() {\n\t\t\tCanvas canvas = null;\n\t\t\tGraphCanvasWrapper graphCanvasWrapper = null;\n\t\t\tLog.e(TAG,\"height = \" + height);\n\t\t\tLog.e(TAG,\"width = \" + width);\n\t\t\t\n\t\t\tsetPaint();\n\t\t\tisAnimation();\n\t\t\tisDrawRegion();\n\t\t\t\n\t\t\tanimStartTime = System.currentTimeMillis();\n\t\t\t\n\t\t\twhile(isRun){\n\t\t\t\n\t\t\t\t//draw only on dirty mode\n\t\t\t\tif(!isDirty){\n\t\t\t\t\ttry {\n\t\t\t\t\t\tThread.sleep(100);\n\t\t\t\t\t} catch (InterruptedException e1) {\n\t\t\t\t\t\te1.printStackTrace();\n\t\t\t\t\t}\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tcanvas = mHolder.lockCanvas();\n\t\t\t\tgraphCanvasWrapper = new GraphCanvasWrapper(canvas, width, height, mCurveGraphVO.getPaddingLeft(), mCurveGraphVO.getPaddingBottom());\n\t\t\t\t\n\t\t\t\ttry {\n\t\t\t\t\tThread.sleep(0000);\n\t\t\t\t} catch (InterruptedException e) {\n\t\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\t\te.printStackTrace();\n\t\t\t\t}\n\t\t\t\tcalcTimePass();\n\t\t\t\t\n\t\t\t\tsynchronized(mHolder){\n\t\t\t\t\tsynchronized (touchLock) {\n\t\t\t\t\t\t\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t//bg color\n\t\t\t\t\t\t\tcanvas.drawColor(Color.WHITE);\n\t\t\t\t\t\t\tif(bg != null){\n\t\t\t\t\t\t\t\tcanvas.drawBitmap(bg, 0, 0, null);\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t// x coord dot Line\n\t\t\t\t\t\t\tdrawBaseLine(graphCanvasWrapper);\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t// y coord\n\t\t\t\t\t\t\tgraphCanvasWrapper.drawLine(0, 0, 0, chartYLength, pBaseLine);\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t// x coord\n\t\t\t\t\t\t\tgraphCanvasWrapper.drawLine(0, 0, chartXLength, 0, pBaseLine);\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t// x, y coord mark\n\t\t\t\t\t\t\tdrawXMark(graphCanvasWrapper);\n\t\t\t\t\t\t\tdrawYMark(graphCanvasWrapper);\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t// x, y coord text\n\t\t\t\t\t\t\tdrawXText(graphCanvasWrapper);\n\t\t\t\t\t\t\tdrawYText(graphCanvasWrapper);\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t// Draw Graph\n\t\t\t\t\t\t\tdrawGraphRegion(graphCanvasWrapper);\n\t\t\t\t\t\t\tdrawGraph(graphCanvasWrapper);\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t// Draw group name\n\t\t\t\t\t\t\tdrawGraphName(canvas);\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t} catch (Exception e) {\n\t\t\t\t\t\t\te.printStackTrace();\n\t\t\t\t\t\t} finally {\n\t\t\t\t\t\t\tif(graphCanvasWrapper.getCanvas() != null){\n\t\t\t\t\t\t\t\tmHolder.unlockCanvasAndPost(graphCanvasWrapper.getCanvas());\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\t/**\n\t\t * time calculate\n\t\t */\n\t\tprivate void calcTimePass(){\n\t\t\tif(isAnimation){\n\t\t\t\tlong curTime = System.currentTimeMillis();\n\t\t\t\tlong gapTime = curTime - animStartTime;\n\t\t\t\tlong animDuration = mCurveGraphVO.getAnimation().getDuration();\n\t\t\t\tif(gapTime >= animDuration)\n\t\t\t\t\tgapTime = animDuration;\n\t\t\t\t\n\t\t\t\tanim = (float) gapTime / (float) animDuration;\n\t\t\t}else{\n\t\t\t\tisDirty = false;\n\t\t\t}\n\t\t}\n\t\t\n\t\t/**\n\t\t * draw graph name\n\t\t */\n\t\tprivate void drawGraphName(Canvas canvas) {\n\t\t\tGraphNameBox gnb = mCurveGraphVO.getGraphNameBox();\n\t\t\tif(gnb != null){\n\t\t\t\tint nameboxWidth = 0;\n\t\t\t\tint nameboxHeight = 0;\n\t\t\t\t\n\t\t\t\tint nameboxIconWidth = gnb.getNameboxIconWidth();\n\t\t\t\tint nameboxIconHeight = gnb.getNameboxIconHeight();\n\t\t\t\t\n\t\t\t\tint nameboxMarginTop = gnb.getNameboxMarginTop();\n\t\t\t\tint nameboxMarginRight = gnb.getNameboxMarginRight();\n\t\t\t\tint nameboxPadding = gnb.getNameboxPadding();\n\t\t\t\t\n\t\t\t\tint nameboxTextIconMargin = gnb.getNameboxIconMargin();\n\t\t\t\tint nameboxIconMargin = gnb.getNameboxIconMargin();\n\t\t\t\tint nameboxTextSize = gnb.getNameboxTextSize(); \n\t\t\t\t\n\t\t\t\tint maxTextWidth = 0;\n\t\t\t\tint maxTextHeight = 0;\n\t\t\t\t\n\t\t\t\tPaint nameRextPaint = new Paint();\n\t\t\t\tnameRextPaint.setFlags(Paint.ANTI_ALIAS_FLAG);\n\t\t\t\tnameRextPaint.setAntiAlias(true); //text anti alias\n\t\t\t\tnameRextPaint.setFilterBitmap(true); // bitmap anti alias\n\t\t\t\tnameRextPaint.setColor(Color.BLUE);\n\t\t\t\tnameRextPaint.setStrokeWidth(3);\n\t\t\t\tnameRextPaint.setStyle(Style.STROKE);\n\t\t\t\t\n\t\t\t\tPaint pIcon = new Paint();\n\t\t\t\tpIcon.setFlags(Paint.ANTI_ALIAS_FLAG);\n\t\t\t\tpIcon.setAntiAlias(true); //text anti alias\n\t\t\t\tpIcon.setFilterBitmap(true); // bitmap anti alias\n\t\t\t\tpIcon.setColor(Color.BLUE);\n\t\t\t\tpIcon.setStrokeWidth(3);\n\t\t\t\tpIcon.setStyle(Style.FILL_AND_STROKE);\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tPaint pNameText = new Paint();\n\t\t\t\tpNameText.setFlags(Paint.ANTI_ALIAS_FLAG);\n\t\t\t\tpNameText.setAntiAlias(true); //text anti alias\n\t\t\t\tpNameText.setTextSize(nameboxTextSize);\n\t\t\t\tpNameText.setColor(Color.BLACK); \n\t\t\t\t\n\t\t\t\t\n\t\t\t\tint graphSize = mCurveGraphVO.getArrGraph().size();\n\t\t\t\tfor (int i = 0; i < graphSize; i++) {\n\t\t\t\t\t\n\t\t\t\t\tString text = mCurveGraphVO.getArrGraph().get(i).getName();\n\t\t\t\t\tRect rect = new Rect();\n\t\t\t\t\tpNameText.getTextBounds(text, 0, text.length(), rect);\n\t\t\t\t\t\n\t\t\t\t\tif(rect.width() > maxTextWidth){\n\t\t\t\t\t\tmaxTextWidth = rect.width();\n\t\t\t\t\t\tmaxTextHeight = rect.height();\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tmCurveGraphVO.getArrGraph().get(i).getName();\n\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\tmCurveGraphVO.getArrGraph().get(0).getName();\n\t\t\t\tnameboxWidth = 1 * maxTextWidth + nameboxTextIconMargin + nameboxIconWidth;\n\t\t\t\tint maxCellHight = maxTextHeight;\n\t\t\t\tif(nameboxIconHeight > maxTextHeight){\n\t\t\t\t\tmaxCellHight = nameboxIconHeight;\n\t\t\t\t}\n\t\t\t\tnameboxHeight = graphSize * maxCellHight + (graphSize-1) * nameboxIconMargin;\n\t\t\t\t\n\t\t\t\tcanvas.drawRect(width - (nameboxMarginRight + nameboxWidth) - nameboxPadding*2,\n\t\t\t\t\t\tnameboxMarginTop, width - nameboxMarginRight, nameboxMarginTop + nameboxHeight + nameboxPadding*2, nameRextPaint);\n\t\t\t\t\n\t\t\t\tfor (int i = 0; i < graphSize; i++) {\n\t\t\t\t\t\n\t\t\t\t\tpIcon.setColor(mCurveGraphVO.getArrGraph().get(i).getColor());\n\t\t\t\t\tcanvas.drawRect(width - (nameboxMarginRight + nameboxWidth) - nameboxPadding,\n\t\t\t\t\t\t\tnameboxMarginTop + (maxCellHight * i) + nameboxPadding + (nameboxIconMargin * i), \n\t\t\t\t\t\t\twidth - (nameboxMarginRight + maxTextWidth) - nameboxPadding - nameboxTextIconMargin, \n\t\t\t\t\t\t\tnameboxMarginTop + maxCellHight * (i+1) + nameboxPadding + nameboxIconMargin * i, pIcon);\n\t\t\t\t\t\n\t\t\t\t\tString text = mCurveGraphVO.getArrGraph().get(i).getName();\n\t\t\t\t\tcanvas.drawText(text, width - (nameboxMarginRight + maxTextWidth) - nameboxPadding, \n\t\t\t\t\t\t\tnameboxMarginTop + maxTextHeight/2 + maxCellHight * i + maxCellHight/2 + nameboxPadding + nameboxIconMargin * i, pNameText);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t/**\n\t\t * check graph Curve animation\n\t\t */\n\t\tprivate void isAnimation() {\n\t\t\tif(mCurveGraphVO.getAnimation() != null){\n\t\t\t\tisAnimation = true;\n\t\t\t}else{\n\t\t\t\tisAnimation = false;\n\t\t\t}\n\t\t\tanimationType = mCurveGraphVO.getAnimation().getAnimation();\n\t\t}\n\t\t\n\t\t/**\n\t\t * check graph Curve region animation\n\t\t */\n\t\tprivate void isDrawRegion() {\n\t\t\tif(mCurveGraphVO.isDrawRegion()){\n\t\t\t\tisDrawRegion = true;\n\t\t\t}else{\n\t\t\t\tisDrawRegion = false;\n\t\t\t}\n\t\t}\n\n\t\t/**\n\t\t * draw Base Line\n\t\t */\n\t\tprivate void drawBaseLine(GraphCanvasWrapper graphCanvas) {\n\t\t\tfor (int i = 1; mCurveGraphVO.getIncrement() * i <= mCurveGraphVO.getMaxValue(); i++) {\n\t\t\t\t\n\t\t\t\tfloat y = yLength * mCurveGraphVO.getIncrement() * i/mCurveGraphVO.getMaxValue();\n\t\t\t\t\n\t\t\t\tgraphCanvas.drawLine(0, y, chartXLength, y, pBaseLineX);\n\t\t\t}\n\t\t}\n\n\t\t/**\n\t\t * set graph Curve color\n\t\t */\n\t\tprivate void setPaint() {\n\t\t\tp = new Paint();\n\t\t\tp.setFlags(Paint.ANTI_ALIAS_FLAG);\n\t\t\tp.setAntiAlias(true); //text anti alias\n\t\t\tp.setFilterBitmap(true); // bitmap anti alias\n\t\t\tp.setColor(Color.BLUE);\n\t\t\tp.setStrokeWidth(3);\n\t\t\tp.setStyle(Style.STROKE);\n\t\t\t\n\t\t\tpCircle = new Paint();\n\t\t\tpCircle.setFlags(Paint.ANTI_ALIAS_FLAG);\n\t\t\tpCircle.setAntiAlias(true); //text anti alias\n\t\t\tpCircle.setFilterBitmap(true); // bitmap anti alias\n\t\t\tpCircle.setColor(Color.BLUE);\n\t\t\tpCircle.setStrokeWidth(3);\n\t\t\tpCircle.setStyle(Style.FILL_AND_STROKE);\n\t\t\t\n\t\t\tpCurve = new Paint();\n\t\t\tpCurve.setFlags(Paint.ANTI_ALIAS_FLAG);\n\t\t\tpCurve.setAntiAlias(true); //text anti alias\n\t\t\tpCurve.setFilterBitmap(true); // bitmap anti alias\n\t\t\tpCurve.setShader(new LinearGradient(0, 300f, 0, 0f, Color.BLACK, Color.WHITE, Shader.TileMode.MIRROR));\n\t\t\t\n\t\t\tpBaseLine = new Paint();\n\t\t\tpBaseLine.setFlags(Paint.ANTI_ALIAS_FLAG);\n\t\t\tpBaseLine.setAntiAlias(true); //text anti alias\n\t\t\tpBaseLine.setFilterBitmap(true); // bitmap anti alias\n\t\t\tpBaseLine.setColor(Color.GRAY);\n\t\t\tpBaseLine.setStrokeWidth(3);\n\t\t\t\n\t\t\tpBaseLineX = new Paint();\n\t\t\tpBaseLineX.setFlags(Paint.ANTI_ALIAS_FLAG);\n\t\t\tpBaseLineX.setAntiAlias(true); //text anti alias\n\t\t\tpBaseLineX.setFilterBitmap(true); // bitmap anti alias\n\t\t\tpBaseLineX.setColor(0xffcccccc);\n\t\t\tpBaseLineX.setStrokeWidth(3);\n\t\t\tpBaseLineX.setStyle(Style.STROKE);\n\t\t\tpBaseLineX.setPathEffect(new DashPathEffect(new float[] {10,5}, 0));\n\t\t\t\n\t\t\tpMarkText = new Paint();\n\t\t\tpMarkText.setFlags(Paint.ANTI_ALIAS_FLAG);\n\t\t\tpMarkText.setAntiAlias(true); //text anti alias\n\t\t\tpMarkText.setColor(Color.BLACK); \n\t\t}\n\t\t\n\t\t/**\n\t\t * draw Graph Region\n\t\t */\n\t\tprivate void drawGraphRegion(GraphCanvasWrapper graphCanvas) {\n\t\t\tif(isDrawRegion){\n\t\t\t\tif (isAnimation){\n\t\t\t\t\tdrawGraphRegionWithAnimation(graphCanvas);\n\t\t\t\t}else{\n\t\t\t\t\tdrawGraphRegionWithoutAnimation(graphCanvas);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\t/**\n\t\t * draw Graph\n\t\t */\n\t\tprivate void drawGraph(GraphCanvasWrapper graphCanvas) {\n\t\t\tif (isAnimation){\n\t\t\t\tdrawGraphWithAnimation(graphCanvas);\n\t\t\t}else{\n\t\t\t\tdrawGraphWithoutAnimation(graphCanvas);\n\t\t\t}\n\t\t}\n\t\t\n\t\t/**\n\t\t *\tdraw graph without animation \n\t\t */\n\t\tprivate void drawGraphRegionWithoutAnimation(GraphCanvasWrapper graphCanvas) {\n\t\t\tboolean isDrawRegion = mCurveGraphVO.isDrawRegion();\n\t\t\t\n\t\t\tfor (int i = 0; i < mCurveGraphVO.getArrGraph().size(); i++) {\n\t\t\t\tGraphPath regionPath = new GraphPath(width, height, mCurveGraphVO.getPaddingLeft(), mCurveGraphVO.getPaddingBottom());\n\n\t\t\t\tboolean firstSet = false;\n\t\t\t\tfloat xGap = xLength/(mCurveGraphVO.getArrGraph().get(i).getCoordinateArr().length-1);\n\t\t\t\t\n\t\t\t\tfloat[] x = setAxisX(xGap, i);\n\t\t\t\tfloat[] y = setAxisY(i);\n\t\t\t\t// Creates a monotone cubic spline from a given set of control points.\n\t\t\t\tspline = Spline.createMonotoneCubicSpline(x, y);\n\t\t\t\t\n\t\t\t\tp.setColor(mCurveGraphVO.getArrGraph().get(i).getColor());\n\t\t\t\tpCircle.setColor(mCurveGraphVO.getArrGraph().get(i).getColor());\n\t\t\t\t\n\t\t\t\tspline = Spline.createMonotoneCubicSpline(x, y);\n\n\t\t\t\t// draw Region\n\t\t\t\tfor (float j = x[0]; j < x[x.length-1]; j++) {\n\t\t\t\t\tif (!firstSet) {\n\t\t\t\t\t\tregionPath.moveTo(j, spline.interpolate(j));\n\t\t\t\t\t\tfirstSet = true;\n\t\t\t\t\t} else \n\t\t\t\t\t\tregionPath.lineTo((j+1), spline.interpolate((j+1)));\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif(isDrawRegion){\n\t\t\t\t\tregionPath.lineTo(x[x.length-1], 0);\n\t\t\t\t\tregionPath.lineTo(0, 0);\n\t\t\t\t\t\n\t\t\t\t\tPaint pBg = new Paint();\n\t\t\t\t\tpBg.setFlags(Paint.ANTI_ALIAS_FLAG);\n\t\t\t\t\tpBg.setAntiAlias(true); //text anti alias\n\t\t\t\t\tpBg.setFilterBitmap(true); // bitmap anti alias\n\t\t\t\t\tpBg.setStyle(Style.FILL);\n\t\t\t\t\tpBg.setColor(mCurveGraphVO.getArrGraph().get(i).getColor());\n\t\t\t\t\tgraphCanvas.getCanvas().drawPath(regionPath, pBg);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\t/**\n\t\t *\tdraw graph with animation \n\t\t */\n\t\tprivate void drawGraphRegionWithAnimation(GraphCanvasWrapper graphCanvas) {\n\t\t\t//for draw animation\n\t\t\tboolean isDrawRegion = mCurveGraphVO.isDrawRegion();\n\t\t\t\n\t\t\tfor (int i = 0; i < mCurveGraphVO.getArrGraph().size(); i++) {\n\t\t\t\tGraphPath regionPath = new GraphPath(width, height, mCurveGraphVO.getPaddingLeft(), mCurveGraphVO.getPaddingBottom());\n\n\t\t\t\tboolean firstSet = false;\n\t\t\t\tfloat xGap = xLength/(mCurveGraphVO.getArrGraph().get(i).getCoordinateArr().length-1);\n\t\t\t\t\n\t\t\t\tfloat moveX = 0;\n\t\t\t\tfloat[] x = setAxisX(xGap, i);\n\t\t\t\tfloat[] y = setAxisY(i);\n\t\t\t\t// Creates a monotone cubic spline from a given set of control points.\n\t\t\t\tspline = Spline.createMonotoneCubicSpline(x, y);\n\t\t\t\t", "answers": ["\t\t\t\tp.setColor(mCurveGraphVO.getArrGraph().get(i).getColor());"], "length": 1362, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "07c5c1de-0d47-4ec2-aae8-166b95d3262c", "reasoning": "In the drawGraphRegionWithAnimation method, after creating the spline from the x and y arrays, the next logical step is to set the paint color for drawing the curve, mirroring the non‑animation version where the paint color is set immediately after spline creation. Therefore the next line should set the Paint object's color to the current graph's color.", "reasoning_model_answer": "p.setColor(mCurveGraphVO.getArrGraph().get(i).getColor());", "assistant_with_reasoning": "\nIn the drawGraphRegionWithAnimation method, after creating the spline from the x and y arrays, the next logical step is to set the paint color for drawing the curve, mirroring the non‑animation version where the paint color is set immediately after spline creation. Therefore the next line should set the Paint object's color to the current graph's color.\n\np.setColor(mCurveGraphVO.getArrGraph().get(i).getColor());", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 5.27, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 15949, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "p.setColor(mCurveGraphVO.getArrGraph().get(i).getColor());", "score": 0.97, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "// This file was generated by the Gtk# code generator.\n// Any changes made will be lost if regenerated.\n\nnamespace Gst {\n\n\tusing System;\n\tusing System.Collections;\n\tusing System.Collections.Generic;\n\tusing System.Runtime.InteropServices;\n\n#region Autogenerated code\n\tpublic partial class Structure : GLib.Opaque {\n\n\t\tpublic GLib.GType Type {\n\t\t\tget {\n\t\t\t\tunsafe {\n\t\t\t\t\tIntPtr* raw_ptr = (IntPtr*)(((byte*)Handle) + abi_info.GetFieldOffset(\"type\"));\n\t\t\t\t\treturn new GLib.GType((*raw_ptr));\n\t\t\t\t}\n\t\t\t}\n\t\t\tset {\n\t\t\t\tunsafe {\n\t\t\t\t\tIntPtr* raw_ptr = (IntPtr*)(((byte*)Handle) + abi_info.GetFieldOffset(\"type\"));\n\t\t\t\t\t*raw_ptr = value.Val;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t[DllImport(\"gstreamer-1.0-0.dll\", CallingConvention = CallingConvention.Cdecl)]\n\t\tstatic extern IntPtr gst_structure_get_name(IntPtr raw);\n\n\t\t[DllImport(\"gstreamer-1.0-0.dll\", CallingConvention = CallingConvention.Cdecl)]\n\t\tstatic extern void gst_structure_set_name(IntPtr raw, IntPtr name);\n\n\t\tpublic string Name {\n\t\t\tget {\n\t\t\t\tIntPtr raw_ret = gst_structure_get_name(Handle);\n\t\t\t\tstring ret = GLib.Marshaller.Utf8PtrToString (raw_ret);\n\t\t\t\treturn ret;\n\t\t\t}\n\t\t\tset {\n\t\t\t\tIntPtr native_value = GLib.Marshaller.StringToPtrGStrdup (value);\n\t\t\t\tgst_structure_set_name(Handle, native_value);\n\t\t\t\tGLib.Marshaller.Free (native_value);\n\t\t\t}\n\t\t}\n\n\t\t[DllImport(\"gstreamer-1.0-0.dll\", CallingConvention = CallingConvention.Cdecl)]\n\t\tstatic extern IntPtr gst_structure_get_type();\n\n\t\tpublic static GLib.GType GType { \n\t\t\tget {\n\t\t\t\tIntPtr raw_ret = gst_structure_get_type();\n\t\t\t\tGLib.GType ret = new GLib.GType(raw_ret);\n\t\t\t\treturn ret;\n\t\t\t}\n\t\t}\n\n\t\t[DllImport(\"gstreamer-1.0-0.dll\", CallingConvention = CallingConvention.Cdecl)]\n\t\tstatic extern bool gst_structure_can_intersect(IntPtr raw, IntPtr struct2);\n\n\t\tpublic bool CanIntersect(Gst.Structure struct2) {\n\t\t\tbool raw_ret = gst_structure_can_intersect(Handle, struct2 == null ? IntPtr.Zero : struct2.Handle);\n\t\t\tbool ret = raw_ret;\n\t\t\treturn ret;\n\t\t}\n\n\t\t[DllImport(\"gstreamer-1.0-0.dll\", CallingConvention = CallingConvention.Cdecl)]\n\t\tstatic extern IntPtr gst_structure_copy(IntPtr raw);\n\n\t\tpublic Gst.Structure Copy() {\n\t\t\tIntPtr raw_ret = gst_structure_copy(Handle);\n\t\t\tGst.Structure ret = raw_ret == IntPtr.Zero ? null : (Gst.Structure) GLib.Opaque.GetOpaque (raw_ret, typeof (Gst.Structure), true);\n\t\t\treturn ret;\n\t\t}\n\n\t\t[DllImport(\"gstreamer-1.0-0.dll\", CallingConvention = CallingConvention.Cdecl)]\n\t\tstatic extern void gst_structure_filter_and_map_in_place(IntPtr raw, GstSharp.StructureFilterMapFuncNative func, IntPtr user_data);\n\n\t\tpublic void FilterAndMapInPlace(Gst.StructureFilterMapFunc func) {\n\t\t\tGstSharp.StructureFilterMapFuncWrapper func_wrapper = new GstSharp.StructureFilterMapFuncWrapper (func);\n\t\t\tgst_structure_filter_and_map_in_place(Handle, func_wrapper.NativeDelegate, IntPtr.Zero);\n\t\t}\n\n\t\t[DllImport(\"gstreamer-1.0-0.dll\", CallingConvention = CallingConvention.Cdecl)]\n\t\tstatic extern void gst_structure_fixate(IntPtr raw);\n\n\t\tpublic void Fixate() {\n\t\t\tgst_structure_fixate(Handle);\n\t\t}\n\n\t\t[DllImport(\"gstreamer-1.0-0.dll\", CallingConvention = CallingConvention.Cdecl)]\n\t\tstatic extern bool gst_structure_fixate_field(IntPtr raw, IntPtr field_name);\n\n\t\tpublic bool FixateField(string field_name) {\n\t\t\tIntPtr native_field_name = GLib.Marshaller.StringToPtrGStrdup (field_name);\n\t\t\tbool raw_ret = gst_structure_fixate_field(Handle, native_field_name);\n\t\t\tbool ret = raw_ret;\n\t\t\tGLib.Marshaller.Free (native_field_name);\n\t\t\treturn ret;\n\t\t}\n\n\t\t[DllImport(\"gstreamer-1.0-0.dll\", CallingConvention = CallingConvention.Cdecl)]\n\t\tstatic extern bool gst_structure_fixate_field_boolean(IntPtr raw, IntPtr field_name, bool target);\n\n\t\tpublic bool FixateFieldBoolean(string field_name, bool target) {\n\t\t\tIntPtr native_field_name = GLib.Marshaller.StringToPtrGStrdup (field_name);\n\t\t\tbool raw_ret = gst_structure_fixate_field_boolean(Handle, native_field_name, target);\n\t\t\tbool ret = raw_ret;\n\t\t\tGLib.Marshaller.Free (native_field_name);\n\t\t\treturn ret;\n\t\t}\n\n\t\t[DllImport(\"gstreamer-1.0-0.dll\", CallingConvention = CallingConvention.Cdecl)]\n\t\tstatic extern bool gst_structure_fixate_field_nearest_double(IntPtr raw, IntPtr field_name, double target);\n\n\t\tpublic bool FixateFieldNearestDouble(string field_name, double target) {\n\t\t\tIntPtr native_field_name = GLib.Marshaller.StringToPtrGStrdup (field_name);\n\t\t\tbool raw_ret = gst_structure_fixate_field_nearest_double(Handle, native_field_name, target);\n\t\t\tbool ret = raw_ret;\n\t\t\tGLib.Marshaller.Free (native_field_name);\n\t\t\treturn ret;\n\t\t}\n\n\t\t[DllImport(\"gstreamer-1.0-0.dll\", CallingConvention = CallingConvention.Cdecl)]\n\t\tstatic extern bool gst_structure_fixate_field_nearest_fraction(IntPtr raw, IntPtr field_name, int target_numerator, int target_denominator);\n\n\t\tpublic bool FixateFieldNearestFraction(string field_name, int target_numerator, int target_denominator) {\n\t\t\tIntPtr native_field_name = GLib.Marshaller.StringToPtrGStrdup (field_name);\n\t\t\tbool raw_ret = gst_structure_fixate_field_nearest_fraction(Handle, native_field_name, target_numerator, target_denominator);\n\t\t\tbool ret = raw_ret;\n\t\t\tGLib.Marshaller.Free (native_field_name);\n\t\t\treturn ret;\n\t\t}\n\n\t\t[DllImport(\"gstreamer-1.0-0.dll\", CallingConvention = CallingConvention.Cdecl)]\n\t\tstatic extern bool gst_structure_fixate_field_nearest_int(IntPtr raw, IntPtr field_name, int target);\n\n\t\tpublic bool FixateFieldNearestInt(string field_name, int target) {\n\t\t\tIntPtr native_field_name = GLib.Marshaller.StringToPtrGStrdup (field_name);\n\t\t\tbool raw_ret = gst_structure_fixate_field_nearest_int(Handle, native_field_name, target);\n\t\t\tbool ret = raw_ret;\n\t\t\tGLib.Marshaller.Free (native_field_name);\n\t\t\treturn ret;\n\t\t}\n\n\t\t[DllImport(\"gstreamer-1.0-0.dll\", CallingConvention = CallingConvention.Cdecl)]\n\t\tstatic extern bool gst_structure_fixate_field_string(IntPtr raw, IntPtr field_name, IntPtr target);\n\n\t\tpublic bool FixateFieldString(string field_name, string target) {\n\t\t\tIntPtr native_field_name = GLib.Marshaller.StringToPtrGStrdup (field_name);\n\t\t\tIntPtr native_target = GLib.Marshaller.StringToPtrGStrdup (target);\n\t\t\tbool raw_ret = gst_structure_fixate_field_string(Handle, native_field_name, native_target);\n\t\t\tbool ret = raw_ret;\n\t\t\tGLib.Marshaller.Free (native_field_name);\n\t\t\tGLib.Marshaller.Free (native_target);\n\t\t\treturn ret;\n\t\t}\n\n\t\t[DllImport(\"gstreamer-1.0-0.dll\", CallingConvention = CallingConvention.Cdecl)]\n\t\tstatic extern bool gst_structure_foreach(IntPtr raw, GstSharp.StructureForeachFuncNative func, IntPtr user_data);\n\n\t\tpublic bool Foreach(Gst.StructureForeachFunc func) {\n\t\t\tGstSharp.StructureForeachFuncWrapper func_wrapper = new GstSharp.StructureForeachFuncWrapper (func);\n\t\t\tbool raw_ret = gst_structure_foreach(Handle, func_wrapper.NativeDelegate, IntPtr.Zero);\n\t\t\tbool ret = raw_ret;\n\t\t\treturn ret;\n\t\t}\n\n\t\t[DllImport(\"gstreamer-1.0-0.dll\", CallingConvention = CallingConvention.Cdecl)]\n\t\tstatic extern bool gst_structure_get_array(IntPtr raw, IntPtr fieldname, out IntPtr array);\n\n\t\tpublic bool GetArray(string fieldname, out GLib.ValueArray array) {\n\t\t\tIntPtr native_fieldname = GLib.Marshaller.StringToPtrGStrdup (fieldname);\n\t\t\tIntPtr native_array;\n\t\t\tbool raw_ret = gst_structure_get_array(Handle, native_fieldname, out native_array);\n\t\t\tbool ret = raw_ret;\n\t\t\tGLib.Marshaller.Free (native_fieldname);\n\t\t\tarray = new GLib.ValueArray(native_array);\n\t\t\treturn ret;\n\t\t}\n\n\t\t[DllImport(\"gstreamer-1.0-0.dll\", CallingConvention = CallingConvention.Cdecl)]\n\t\tstatic extern bool gst_structure_get_boolean(IntPtr raw, IntPtr fieldname, out bool value);\n\n\t\tpublic bool GetBoolean(string fieldname, out bool value) {\n\t\t\tIntPtr native_fieldname = GLib.Marshaller.StringToPtrGStrdup (fieldname);\n\t\t\tbool raw_ret = gst_structure_get_boolean(Handle, native_fieldname, out value);\n\t\t\tbool ret = raw_ret;\n\t\t\tGLib.Marshaller.Free (native_fieldname);\n\t\t\treturn ret;\n\t\t}\n\n\t\t[DllImport(\"gstreamer-1.0-0.dll\", CallingConvention = CallingConvention.Cdecl)]\n\t\tstatic extern bool gst_structure_get_clock_time(IntPtr raw, IntPtr fieldname, out ulong value);\n\n\t\tpublic bool GetClockTime(string fieldname, out ulong value) {\n\t\t\tIntPtr native_fieldname = GLib.Marshaller.StringToPtrGStrdup (fieldname);\n\t\t\tbool raw_ret = gst_structure_get_clock_time(Handle, native_fieldname, out value);\n\t\t\tbool ret = raw_ret;\n\t\t\tGLib.Marshaller.Free (native_fieldname);\n\t\t\treturn ret;\n\t\t}\n\n\t\t[DllImport(\"gstreamer-1.0-0.dll\", CallingConvention = CallingConvention.Cdecl)]\n\t\tstatic extern bool gst_structure_get_date(IntPtr raw, IntPtr fieldname, out IntPtr value);\n\n\t\tpublic bool GetDate(string fieldname, out GLib.Date value) {\n\t\t\tIntPtr native_fieldname = GLib.Marshaller.StringToPtrGStrdup (fieldname);\n\t\t\tIntPtr native_value;\n\t\t\tbool raw_ret = gst_structure_get_date(Handle, native_fieldname, out native_value);\n\t\t\tbool ret = raw_ret;\n\t\t\tGLib.Marshaller.Free (native_fieldname);\n\t\t\tvalue = new GLib.Date(native_value);\n\t\t\treturn ret;\n\t\t}\n\n\t\t[DllImport(\"gstreamer-1.0-0.dll\", CallingConvention = CallingConvention.Cdecl)]\n\t\tstatic extern bool gst_structure_get_date_time(IntPtr raw, IntPtr fieldname, out IntPtr value);\n\n\t\tpublic bool GetDateTime(string fieldname, out Gst.DateTime value) {\n\t\t\tIntPtr native_fieldname = GLib.Marshaller.StringToPtrGStrdup (fieldname);\n\t\t\tIntPtr native_value;\n\t\t\tbool raw_ret = gst_structure_get_date_time(Handle, native_fieldname, out native_value);\n\t\t\tbool ret = raw_ret;\n\t\t\tGLib.Marshaller.Free (native_fieldname);\n\t\t\tvalue = native_value == IntPtr.Zero ? null : (Gst.DateTime) GLib.Opaque.GetOpaque (native_value, typeof (Gst.DateTime), true);\n\t\t\treturn ret;\n\t\t}\n\n\t\t[DllImport(\"gstreamer-1.0-0.dll\", CallingConvention = CallingConvention.Cdecl)]\n\t\tstatic extern bool gst_structure_get_double(IntPtr raw, IntPtr fieldname, out double value);\n\n\t\tpublic bool GetDouble(string fieldname, out double value) {\n\t\t\tIntPtr native_fieldname = GLib.Marshaller.StringToPtrGStrdup (fieldname);\n\t\t\tbool raw_ret = gst_structure_get_double(Handle, native_fieldname, out value);\n\t\t\tbool ret = raw_ret;\n\t\t\tGLib.Marshaller.Free (native_fieldname);\n\t\t\treturn ret;\n\t\t}\n\n\t\t[DllImport(\"gstreamer-1.0-0.dll\", CallingConvention = CallingConvention.Cdecl)]\n\t\tstatic extern bool gst_structure_get_enum(IntPtr raw, IntPtr fieldname, IntPtr enumtype, out int value);\n\n\t\tpublic bool GetEnum(string fieldname, GLib.GType enumtype, out int value) {\n\t\t\tIntPtr native_fieldname = GLib.Marshaller.StringToPtrGStrdup (fieldname);\n\t\t\tbool raw_ret = gst_structure_get_enum(Handle, native_fieldname, enumtype.Val, out value);\n\t\t\tbool ret = raw_ret;\n\t\t\tGLib.Marshaller.Free (native_fieldname);\n\t\t\treturn ret;\n\t\t}\n\n\t\t[DllImport(\"gstreamer-1.0-0.dll\", CallingConvention = CallingConvention.Cdecl)]\n\t\tstatic extern IntPtr gst_structure_get_field_type(IntPtr raw, IntPtr fieldname);\n\n\t\tpublic GLib.GType GetFieldType(string fieldname) {\n\t\t\tIntPtr native_fieldname = GLib.Marshaller.StringToPtrGStrdup (fieldname);\n\t\t\tIntPtr raw_ret = gst_structure_get_field_type(Handle, native_fieldname);\n\t\t\tGLib.GType ret = new GLib.GType(raw_ret);\n\t\t\tGLib.Marshaller.Free (native_fieldname);\n\t\t\treturn ret;\n\t\t}\n\n\t\t[DllImport(\"gstreamer-1.0-0.dll\", CallingConvention = CallingConvention.Cdecl)]\n\t\tstatic extern bool gst_structure_get_flagset(IntPtr raw, IntPtr fieldname, out uint value_flags, out uint value_mask);\n\n\t\tpublic bool GetFlagset(string fieldname, out uint value_flags, out uint value_mask) {\n\t\t\tIntPtr native_fieldname = GLib.Marshaller.StringToPtrGStrdup (fieldname);\n\t\t\tbool raw_ret = gst_structure_get_flagset(Handle, native_fieldname, out value_flags, out value_mask);\n\t\t\tbool ret = raw_ret;\n\t\t\tGLib.Marshaller.Free (native_fieldname);\n\t\t\treturn ret;\n\t\t}\n\n\t\t[DllImport(\"gstreamer-1.0-0.dll\", CallingConvention = CallingConvention.Cdecl)]\n\t\tstatic extern bool gst_structure_get_fraction(IntPtr raw, IntPtr fieldname, out int value_numerator, out int value_denominator);\n\n\t\tpublic bool GetFraction(string fieldname, out int value_numerator, out int value_denominator) {\n\t\t\tIntPtr native_fieldname = GLib.Marshaller.StringToPtrGStrdup (fieldname);\n\t\t\tbool raw_ret = gst_structure_get_fraction(Handle, native_fieldname, out value_numerator, out value_denominator);\n\t\t\tbool ret = raw_ret;\n\t\t\tGLib.Marshaller.Free (native_fieldname);\n\t\t\treturn ret;\n\t\t}\n\n\t\t[DllImport(\"gstreamer-1.0-0.dll\", CallingConvention = CallingConvention.Cdecl)]\n\t\tstatic extern bool gst_structure_get_int(IntPtr raw, IntPtr fieldname, out int value);\n\n\t\tpublic bool GetInt(string fieldname, out int value) {\n\t\t\tIntPtr native_fieldname = GLib.Marshaller.StringToPtrGStrdup (fieldname);\n\t\t\tbool raw_ret = gst_structure_get_int(Handle, native_fieldname, out value);\n\t\t\tbool ret = raw_ret;\n\t\t\tGLib.Marshaller.Free (native_fieldname);\n\t\t\treturn ret;\n\t\t}\n\n\t\t[DllImport(\"gstreamer-1.0-0.dll\", CallingConvention = CallingConvention.Cdecl)]\n\t\tstatic extern bool gst_structure_get_int64(IntPtr raw, IntPtr fieldname, out long value);\n\n\t\tpublic bool GetInt64(string fieldname, out long value) {\n\t\t\tIntPtr native_fieldname = GLib.Marshaller.StringToPtrGStrdup (fieldname);\n\t\t\tbool raw_ret = gst_structure_get_int64(Handle, native_fieldname, out value);\n\t\t\tbool ret = raw_ret;\n\t\t\tGLib.Marshaller.Free (native_fieldname);\n\t\t\treturn ret;\n\t\t}\n\n\t\t[DllImport(\"gstreamer-1.0-0.dll\", CallingConvention = CallingConvention.Cdecl)]\n\t\tstatic extern bool gst_structure_get_list(IntPtr raw, IntPtr fieldname, out IntPtr array);\n\n\t\tpublic bool GetList(string fieldname, out GLib.ValueArray array) {\n\t\t\tIntPtr native_fieldname = GLib.Marshaller.StringToPtrGStrdup (fieldname);\n\t\t\tIntPtr native_array;\n\t\t\tbool raw_ret = gst_structure_get_list(Handle, native_fieldname, out native_array);\n\t\t\tbool ret = raw_ret;\n\t\t\tGLib.Marshaller.Free (native_fieldname);\n\t\t\tarray = new GLib.ValueArray(native_array);\n\t\t\treturn ret;\n\t\t}\n\n\t\t[DllImport(\"gstreamer-1.0-0.dll\", CallingConvention = CallingConvention.Cdecl)]\n\t\tstatic extern uint gst_structure_get_name_id(IntPtr raw);\n\n\t\tpublic uint NameId { \n\t\t\tget {\n\t\t\t\tuint raw_ret = gst_structure_get_name_id(Handle);\n\t\t\t\tuint ret = raw_ret;\n\t\t\t\treturn ret;\n\t\t\t}\n\t\t}\n\n\t\t[DllImport(\"gstreamer-1.0-0.dll\", CallingConvention = CallingConvention.Cdecl)]\n\t\tstatic extern IntPtr gst_structure_get_string(IntPtr raw, IntPtr fieldname);\n\n\t\tpublic string GetString(string fieldname) {\n\t\t\tIntPtr native_fieldname = GLib.Marshaller.StringToPtrGStrdup (fieldname);\n\t\t\tIntPtr raw_ret = gst_structure_get_string(Handle, native_fieldname);\n\t\t\tstring ret = GLib.Marshaller.Utf8PtrToString (raw_ret);\n\t\t\tGLib.Marshaller.Free (native_fieldname);\n\t\t\treturn ret;\n\t\t}\n\n\t\t[DllImport(\"gstreamer-1.0-0.dll\", CallingConvention = CallingConvention.Cdecl)]\n\t\tstatic extern bool gst_structure_get_uint(IntPtr raw, IntPtr fieldname, out uint value);\n\n\t\tpublic bool GetUint(string fieldname, out uint value) {\n\t\t\tIntPtr native_fieldname = GLib.Marshaller.StringToPtrGStrdup (fieldname);\n\t\t\tbool raw_ret = gst_structure_get_uint(Handle, native_fieldname, out value);\n\t\t\tbool ret = raw_ret;\n\t\t\tGLib.Marshaller.Free (native_fieldname);\n\t\t\treturn ret;\n\t\t}\n\n\t\t[DllImport(\"gstreamer-1.0-0.dll\", CallingConvention = CallingConvention.Cdecl)]\n\t\tstatic extern bool gst_structure_get_uint64(IntPtr raw, IntPtr fieldname, out ulong value);\n\n\t\tpublic bool GetUint64(string fieldname, out ulong value) {\n\t\t\tIntPtr native_fieldname = GLib.Marshaller.StringToPtrGStrdup (fieldname);\n\t\t\tbool raw_ret = gst_structure_get_uint64(Handle, native_fieldname, out value);\n\t\t\tbool ret = raw_ret;\n\t\t\tGLib.Marshaller.Free (native_fieldname);\n\t\t\treturn ret;\n\t\t}\n\n\t\t[DllImport(\"gstreamer-1.0-0.dll\", CallingConvention = CallingConvention.Cdecl)]\n\t\tstatic extern IntPtr gst_structure_get_value(IntPtr raw, IntPtr fieldname);\n\n\t\tpublic GLib.Value GetValue(string fieldname) {\n\t\t\tIntPtr native_fieldname = GLib.Marshaller.StringToPtrGStrdup (fieldname);\n\t\t\tIntPtr raw_ret = gst_structure_get_value(Handle, native_fieldname);\n\t\t\tGLib.Value ret = (GLib.Value) Marshal.PtrToStructure (raw_ret, typeof (GLib.Value));\n\t\t\tGLib.Marshaller.Free (native_fieldname);\n\t\t\treturn ret;\n\t\t}\n\n\t\t[DllImport(\"gstreamer-1.0-0.dll\", CallingConvention = CallingConvention.Cdecl)]\n\t\tstatic extern bool gst_structure_has_field(IntPtr raw, IntPtr fieldname);\n\n\t\tpublic bool HasField(string fieldname) {\n\t\t\tIntPtr native_fieldname = GLib.Marshaller.StringToPtrGStrdup (fieldname);\n\t\t\tbool raw_ret = gst_structure_has_field(Handle, native_fieldname);\n\t\t\tbool ret = raw_ret;\n\t\t\tGLib.Marshaller.Free (native_fieldname);\n\t\t\treturn ret;\n\t\t}\n\n\t\t[DllImport(\"gstreamer-1.0-0.dll\", CallingConvention = CallingConvention.Cdecl)]\n\t\tstatic extern bool gst_structure_has_field_typed(IntPtr raw, IntPtr fieldname, IntPtr type);\n\n\t\tpublic bool HasFieldTyped(string fieldname, GLib.GType type) {\n\t\t\tIntPtr native_fieldname = GLib.Marshaller.StringToPtrGStrdup (fieldname);\n\t\t\tbool raw_ret = gst_structure_has_field_typed(Handle, native_fieldname, type.Val);\n\t\t\tbool ret = raw_ret;\n\t\t\tGLib.Marshaller.Free (native_fieldname);\n\t\t\treturn ret;\n\t\t}\n\n\t\t[DllImport(\"gstreamer-1.0-0.dll\", CallingConvention = CallingConvention.Cdecl)]\n\t\tstatic extern bool gst_structure_has_name(IntPtr raw, IntPtr name);\n\n\t\tpublic bool HasName(string name) {\n\t\t\tIntPtr native_name = GLib.Marshaller.StringToPtrGStrdup (name);\n\t\t\tbool raw_ret = gst_structure_has_name(Handle, native_name);\n\t\t\tbool ret = raw_ret;\n\t\t\tGLib.Marshaller.Free (native_name);\n\t\t\treturn ret;\n\t\t}\n\n\t\t[DllImport(\"gstreamer-1.0-0.dll\", CallingConvention = CallingConvention.Cdecl)]\n\t\tstatic extern IntPtr gst_structure_id_get_value(IntPtr raw, uint field);\n\n\t\tpublic GLib.Value IdGetValue(uint field) {\n\t\t\tIntPtr raw_ret = gst_structure_id_get_value(Handle, field);\n\t\t\tGLib.Value ret = (GLib.Value) Marshal.PtrToStructure (raw_ret, typeof (GLib.Value));\n\t\t\treturn ret;\n\t\t}\n\n\t\t[DllImport(\"gstreamer-1.0-0.dll\", CallingConvention = CallingConvention.Cdecl)]\n\t\tstatic extern bool gst_structure_id_has_field(IntPtr raw, uint field);\n\n\t\tpublic bool IdHasField(uint field) {\n\t\t\tbool raw_ret = gst_structure_id_has_field(Handle, field);\n\t\t\tbool ret = raw_ret;\n\t\t\treturn ret;\n\t\t}", "answers": ["\t\t[DllImport(\"gstreamer-1.0-0.dll\", CallingConvention = CallingConvention.Cdecl)]"], "length": 1520, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "18c24336-c9a5-4a76-95db-e32026e40659", "reasoning": "The code just finished defining the IdHasField method, which follows the pattern of a DllImport declaration and a wrapper method. The next logical piece is the DllImport attribute for the subsequent native function (likely gst_structure_id_set_value). Therefore the next line is the DllImport attribute line.", "reasoning_model_answer": "[DllImport(\"gstreamer-1.0-0.dll\", CallingConvention = CallingConvention.Cdecl)]", "assistant_with_reasoning": "\nThe code just finished defining the IdHasField method, which follows the pattern of a DllImport declaration and a wrapper method. The next logical piece is the DllImport attribute for the subsequent native function (likely gst_structure_id_set_value). Therefore the next line is the DllImport attribute line.\n\n[DllImport(\"gstreamer-1.0-0.dll\", CallingConvention = CallingConvention.Cdecl)]", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 7.207, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 18000, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "[DllImport(\"gstreamer-1.0-0.dll\", CallingConvention = CallingConvention.Cdecl)]", "score": 0.99, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/*\n * Copyright 2005-2007 The Kuali Foundation\n * \n * \n * Licensed under the Educational Community License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n * http://www.opensource.org/licenses/ecl2.php\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.kuali.rice.kew.actions;\n\n\nimport static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.assertFalse;\nimport static org.junit.Assert.assertNotNull;\nimport static org.junit.Assert.assertTrue;\nimport static org.junit.Assert.fail;\n\nimport java.util.Collection;\nimport java.util.Iterator;\nimport java.util.List;\n\nimport mocks.MockEmailNotificationService;\n\nimport org.junit.Test;\nimport org.kuali.rice.kew.actionrequest.ActionRequestValue;\nimport org.kuali.rice.kew.actionrequest.service.ActionRequestService;\nimport org.kuali.rice.kew.api.WorkflowDocument;\nimport org.kuali.rice.kew.api.WorkflowDocumentFactory;\nimport org.kuali.rice.kew.api.action.DelegationType;\nimport org.kuali.rice.kew.api.action.InvalidActionTakenException;\nimport org.kuali.rice.kew.engine.node.RouteNodeInstance;\nimport org.kuali.rice.kew.engine.node.service.RouteNodeService;\nimport org.kuali.rice.kew.service.KEWServiceLocator;\nimport org.kuali.rice.kew.test.KEWTestCase;\nimport org.kuali.rice.kew.test.TestUtilities;\nimport org.kuali.rice.kew.util.KEWConstants;\nimport org.kuali.rice.test.BaselineTestCase.BaselineMode;\nimport org.kuali.rice.test.BaselineTestCase.Mode;\n\n@BaselineMode(Mode.CLEAR_DB)\npublic class BlanketApproveTest extends KEWTestCase {\n\n\t@Override\n protected void loadTestData() throws Exception {\n loadXmlFile(\"ActionsConfig.xml\");\n }\n \n /**\n * When a user is not in the blanket approver workgroup an exception should be thrown and \n * it should have a good message.\n * \n * @throws Exception\n */\n @Test public void testBlanketApproverNotInBlanketApproverWorkgroup() throws Exception {\n \tWorkflowDocument document = WorkflowDocumentFactory.createDocument(getPrincipalIdForName(\"user1\"), SequentialSetup.DOCUMENT_TYPE_NAME);\n \ttry {\n \t\tdocument.blanketApprove(\"\");\n \t\tfail(\"InvalidActionTakenException should have been thrown\");\n \t} catch (InvalidActionTakenException iate) {\n \t\tassertEquals(\"Exception on message is incorrent\", \"User is not authorized to BlanketApprove document\", iate.getMessage());\n \t}\n \n }\n \n /**\n * When a user is in the blanket approve workgroup but the user is not the initiator an exception\n * should be thrown.\n */\n @Test public void testBlanketApproverNotInitiator() throws Exception {\n WorkflowDocument document = WorkflowDocumentFactory.createDocument(getPrincipalIdForName(\"user1\"), SequentialSetup.DOCUMENT_TYPE_NAME);\n WorkflowDocument newDocument = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName(\"ewestfal\"), document.getDocumentId());\n try {\n newDocument.blanketApprove(\"\");\n fail(\"Exception should have been thrown when non-initiator user attempts blanket approve on default blanket approve policy document\");\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n \n @SuppressWarnings(\"deprecation\")\n\t@Test public void testBlanketApproveSequential() throws Exception {\n WorkflowDocument document = WorkflowDocumentFactory.createDocument(getPrincipalIdForName(\"ewestfal\"), SequentialSetup.DOCUMENT_TYPE_NAME);\n document.blanketApprove(\"\");\n document = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName(\"ewestfal\"), document.getDocumentId());\n assertTrue(\"Document should be processed.\", document.isProcessed());\n Collection nodeInstances = getRouteNodeService().getActiveNodeInstances(document.getDocumentId());\n // once the document is processed there are no active nodes\n assertEquals(\"Wrong number of active nodes.\", 0, nodeInstances.size());\n nodeInstances = getRouteNodeService().getTerminalNodeInstances(document.getDocumentId());\n assertEquals(\"Wrong number of active nodes.\", 1, nodeInstances.size());\n RouteNodeInstance ackNodeInstance = (RouteNodeInstance)nodeInstances.iterator().next();\n assertEquals(\"At wrong node.\", SequentialSetup.ACKNOWLEDGE_2_NODE, ackNodeInstance.getRouteNode().getRouteNodeName());\n assertTrue(\"Node should be complete.\", ackNodeInstance.isComplete());\n List actionRequests = KEWServiceLocator.getActionRequestService().findPendingByDoc(document.getDocumentId());\n assertEquals(\"Wrong number of pending action requests.\", 5, actionRequests.size());\n boolean isNotification1 = false;\n boolean isNotification2 = false;\n boolean isNotification3 = false;\n boolean isAck1 = false;\n boolean isAck2 = false;\n for (Iterator iterator = actionRequests.iterator(); iterator.hasNext();) {\n ActionRequestValue actionRequest = (ActionRequestValue) iterator.next();\n assertEquals(\"Should only be acknowledges.\", KEWConstants.ACTION_REQUEST_ACKNOWLEDGE_REQ, actionRequest.getActionRequested());\n RouteNodeInstance nodeInstance = actionRequest.getNodeInstance();\n assertNotNull(nodeInstance);\n String nodeName = nodeInstance.getRouteNode().getRouteNodeName();\n if (actionRequest.getPrincipalId().equals(getPrincipalIdForName(\"bmcgough\"))) {\n isNotification1 = true;\n assertEquals(SequentialSetup.WORKFLOW_DOCUMENT_NODE, nodeName);\n assertEquals(KEWConstants.MACHINE_GENERATED_RESPONSIBILITY_ID, actionRequest.getResponsibilityId());\n } else if (actionRequest.getPrincipalId().equals(getPrincipalIdForName(\"rkirkend\"))) {\n isNotification2 = true;\n assertEquals(SequentialSetup.WORKFLOW_DOCUMENT_NODE, nodeName);\n assertEquals(KEWConstants.MACHINE_GENERATED_RESPONSIBILITY_ID, actionRequest.getResponsibilityId());\n } else if (actionRequest.getPrincipalId().equals(getPrincipalIdForName(\"pmckown\"))) {\n isNotification3 = true;\n assertEquals(SequentialSetup.WORKFLOW_DOCUMENT_2_NODE, nodeName);\n assertEquals(KEWConstants.MACHINE_GENERATED_RESPONSIBILITY_ID, actionRequest.getResponsibilityId());\n } else if (actionRequest.getPrincipalId().equals(getPrincipalIdForName(\"temay\"))) {\n isAck1 = true;\n assertEquals(SequentialSetup.ACKNOWLEDGE_1_NODE, nodeName);\n assertFalse(KEWConstants.MACHINE_GENERATED_RESPONSIBILITY_ID.equals(actionRequest.getResponsibilityId()));\n } else if (actionRequest.getPrincipalId().equals(getPrincipalIdForName(\"jhopf\"))) {\n isAck2 = true;\n assertEquals(SequentialSetup.ACKNOWLEDGE_2_NODE, nodeName);\n assertFalse(KEWConstants.MACHINE_GENERATED_RESPONSIBILITY_ID.equals(actionRequest.getResponsibilityId()));\n }\n }\n assertTrue(isNotification1);\n assertTrue(isNotification2);\n assertTrue(isNotification3);\n assertTrue(isAck1);\n assertTrue(isAck2);\n document = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName(\"bmcgough\"), document.getDocumentId());\n assertTrue(document.isProcessed());\n assertTrue(document.isAcknowledgeRequested());\n assertEquals(\"bmcgough should not have been sent an approve email\", 0, getMockEmailService().immediateReminderEmailsSent(\"bmcgough\", document.getDocumentId(), KEWConstants.ACTION_REQUEST_APPROVE_REQ));\n assertEquals(\"bmcgough should not have been sent an ack email\", 1, getMockEmailService().immediateReminderEmailsSent(\"bmcgough\", document.getDocumentId(), KEWConstants.ACTION_REQUEST_ACKNOWLEDGE_REQ));\n document.acknowledge(\"\");\n\n document = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName(\"rkirkend\"), document.getDocumentId());\n assertTrue(document.isProcessed());\n assertTrue(document.isAcknowledgeRequested());\n assertEquals(\"rkirkend should not have been sent an approve email\", 0, getMockEmailService().immediateReminderEmailsSent(\"rkirkend\", document.getDocumentId(), KEWConstants.ACTION_REQUEST_APPROVE_REQ)); \n assertEquals(\"rkirkend should not have been sent an ack email\", 1, getMockEmailService().immediateReminderEmailsSent(\"rkirkend\", document.getDocumentId(), KEWConstants.ACTION_REQUEST_ACKNOWLEDGE_REQ));\n document.acknowledge(\"\");\n \n document = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName(\"pmckown\"), document.getDocumentId());\n assertTrue(document.isProcessed());\n assertTrue(document.isAcknowledgeRequested());\n assertEquals(\"pmckown should not have been sent an approve email\", 0, getMockEmailService().immediateReminderEmailsSent(\"pmckown\", document.getDocumentId(), KEWConstants.ACTION_REQUEST_APPROVE_REQ));\n assertEquals(\"pmckown should not have been sent an ack email\", 1, getMockEmailService().immediateReminderEmailsSent(\"pmckown\", document.getDocumentId(), KEWConstants.ACTION_REQUEST_ACKNOWLEDGE_REQ));\n document.acknowledge(\"\");\n \n document = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName(\"temay\"), document.getDocumentId());\n assertTrue(document.isProcessed());\n assertTrue(document.isAcknowledgeRequested());\n assertEquals(\"rkirkend should have been sent an temay\", 1, getMockEmailService().immediateReminderEmailsSent(\"temay\", document.getDocumentId(), KEWConstants.ACTION_REQUEST_ACKNOWLEDGE_REQ)); \n document.acknowledge(\"\");\n \n document = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName(\"jhopf\"), document.getDocumentId());\n assertTrue(document.isProcessed());\n assertTrue(document.isAcknowledgeRequested());\n assertEquals(\"rkirkend should have been sent an jhopf\", 1, getMockEmailService().immediateReminderEmailsSent(\"jhopf\", document.getDocumentId(), KEWConstants.ACTION_REQUEST_ACKNOWLEDGE_REQ));\n document.acknowledge(\"\");\n \n document = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName(\"ewestfal\"), document.getDocumentId());\n assertTrue(document.isFinal());\n \n document = WorkflowDocumentFactory.createDocument(getPrincipalIdForName(\"ewestfal\"), SequentialSetup.DOCUMENT_TYPE_NAME);\n document.blanketApprove(\"\", SequentialSetup.WORKFLOW_DOCUMENT_2_NODE);\n assertTrue(\"Document should be enroute.\", document.isEnroute());\n nodeInstances = getRouteNodeService().getActiveNodeInstances(document.getDocumentId());\n assertEquals(\"Should be one active node.\", 1, nodeInstances.size());\n RouteNodeInstance doc2Instance = (RouteNodeInstance)nodeInstances.iterator().next();\n assertEquals(\"At wrong node.\", SequentialSetup.WORKFLOW_DOCUMENT_2_NODE, doc2Instance.getRouteNode().getRouteNodeName());\n \n }\n \n @Test public void testBlanketApproveSequentialErrors() throws Exception {\n // blanket approve to invalid node\n WorkflowDocument document = WorkflowDocumentFactory.createDocument(getPrincipalIdForName(\"ewestfal\"), SequentialSetup.DOCUMENT_TYPE_NAME);\n try {\n document.blanketApprove(\"\", \"TotallyInvalidNode\");\n fail(\"Should have thrown exception\");\n } catch (Exception e) {}\n \n // blanket approve backwards\n document = WorkflowDocumentFactory.createDocument(getPrincipalIdForName(\"ewestfal\"), SequentialSetup.DOCUMENT_TYPE_NAME);\n document.blanketApprove(\"\", SequentialSetup.WORKFLOW_DOCUMENT_2_NODE);\n try {\n document.blanketApprove(\"\", SequentialSetup.WORKFLOW_DOCUMENT_NODE);\n fail(\"Should have thrown exception\");\n } catch (Exception e) {}\n \n // blanket approve to current node\n document = WorkflowDocumentFactory.createDocument(getPrincipalIdForName(\"ewestfal\"), SequentialSetup.DOCUMENT_TYPE_NAME);\n document.route(\"\");\n try {\n document.blanketApprove(\"\", SequentialSetup.WORKFLOW_DOCUMENT_NODE);\n fail(\"Should have thrown exception\");\n } catch (Exception e) {}\n \n // blanket approve as user not in the blanket approve workgroup\n document = WorkflowDocumentFactory.createDocument(getPrincipalIdForName(\"user1\"), SequentialSetup.DOCUMENT_TYPE_NAME);\n try {\n document.blanketApprove(\"\");\n fail(\"Shouldn't be able to blanket approve if not in blanket approve workgroup\");\n } catch (Exception e) {}\n }\n \n @Test public void testBlanketApproveParallel() throws Exception {\n WorkflowDocument document = WorkflowDocumentFactory.createDocument(getPrincipalIdForName(\"ewestfal\"), ParallelSetup.DOCUMENT_TYPE_NAME);\n document.blanketApprove(\"\"); \n document = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName(\"ewestfal\"), document.getDocumentId());\n assertTrue(\"Document should be processed.\", document.isProcessed());\n Collection nodeInstances = getRouteNodeService().getActiveNodeInstances(document.getDocumentId());\n // once the document has gone processed there are no active nodes\n assertEquals(\"Wrong number of active nodes.\", 0, nodeInstances.size());\n nodeInstances = getRouteNodeService().getTerminalNodeInstances(document.getDocumentId());\n assertEquals(\"Wrong number of terminal nodes.\", 1, nodeInstances.size());\n RouteNodeInstance ackNodeInstance = (RouteNodeInstance)nodeInstances.iterator().next();\n assertEquals(\"At wrong node.\", SequentialSetup.ACKNOWLEDGE_2_NODE, ackNodeInstance.getRouteNode().getRouteNodeName());\n assertTrue(\"Node should be complete.\", ackNodeInstance.isComplete());\n List actionRequests = KEWServiceLocator.getActionRequestService().findPendingByDoc(document.getDocumentId());\n assertEquals(\"Wrong number of pending action requests.\", 10, actionRequests.size());\n\n }\n \n @Test public void testBlanketApproveIntoBranch() throws Exception {\n WorkflowDocument document = WorkflowDocumentFactory.createDocument(getPrincipalIdForName(\"ewestfal\"), ParallelSetup.DOCUMENT_TYPE_NAME);\n document.blanketApprove(\"\", ParallelSetup.WORKFLOW_DOCUMENT_2_B1_NODE);\n List actionRequests = KEWServiceLocator.getActionRequestService().findPendingByDoc(document.getDocumentId());\n assertEquals(\"Wrong number of pending action requests.\", 5, actionRequests.size());\n \n // document should now be at the node we blanket approved to and the join node\n Collection activeNodes = getRouteNodeService().getActiveNodeInstances(document.getDocumentId());\n assertEquals(\"Wrong number of active nodes.\", 3, activeNodes.size());\n boolean isAtWD2B1 = false;\n boolean isAtJoin = false;\n boolean isAtWD3B2 = false;\n boolean isAtWD4B3 = false;\n for (Iterator iterator = activeNodes.iterator(); iterator.hasNext();) {\n RouteNodeInstance nodeInstance = (RouteNodeInstance) iterator.next();\n isAtWD2B1 = isAtWD2B1 || nodeInstance.getName().equals(ParallelSetup.WORKFLOW_DOCUMENT_2_B1_NODE);\n isAtWD3B2 = isAtWD3B2 || nodeInstance.getName().equals(ParallelSetup.WORKFLOW_DOCUMENT_3_B2_NODE);\n isAtWD4B3 = isAtWD4B3 || nodeInstance.getName().equals(ParallelSetup.WORKFLOW_DOCUMENT_4_B3_NODE);\n isAtJoin = isAtJoin || nodeInstance.getName().equals(ParallelSetup.JOIN_NODE);\n }\n assertTrue(\"Should be at blanket approved node.\", isAtWD2B1);\n assertTrue(\"Should be at blanket approved node WD3B2.\", isAtWD3B2);\n assertTrue(\"Should be at blanket approved node WD4B3.\", isAtWD4B3); \n assertFalse(\"Should be at join node.\", isAtJoin);\n \n document.blanketApprove(\"\");\n document = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName(\"ewestfal\"), document.getDocumentId());\n assertTrue(\"Document should be processed.\", document.isProcessed());\n actionRequests = KEWServiceLocator.getActionRequestService().findPendingByDoc(document.getDocumentId());\n \n assertEquals(\"Wrong number of pending action requests.\", 10, actionRequests.size());\n }\n \n @Test public void testBlanketApproveToMultipleNodes() throws Exception {\n \n WorkflowDocument document = WorkflowDocumentFactory.createDocument(getPrincipalIdForName(\"ewestfal\"), ParallelSetup.DOCUMENT_TYPE_NAME);\n document.blanketApprove(\"\", new String[] { ParallelSetup.WORKFLOW_DOCUMENT_2_B1_NODE, ParallelSetup.WORKFLOW_DOCUMENT_3_B2_NODE });\n List actionRequests = KEWServiceLocator.getActionRequestService().findPendingByDoc(document.getDocumentId());\n assertEquals(\"Wrong number of pending action requests.\", 5, actionRequests.size());\n \n // document should now be at both nodes we blanket approved to and the join node\n Collection activeNodes = getRouteNodeService().getActiveNodeInstances(document.getDocumentId());\n assertEquals(\"Wrong number of active nodes.\", 3, activeNodes.size());\n boolean isAtWD2B1 = false;\n boolean isAtWD3B2 = false;\n boolean isAtJoin = false;\n boolean isAtWD4B3 = false;\n for (Iterator iterator = activeNodes.iterator(); iterator.hasNext();) {\n RouteNodeInstance nodeInstance = (RouteNodeInstance) iterator.next();\n isAtWD2B1 = isAtWD2B1 || nodeInstance.getName().equals(ParallelSetup.WORKFLOW_DOCUMENT_2_B1_NODE);\n isAtWD3B2 = isAtWD3B2 || nodeInstance.getName().equals(ParallelSetup.WORKFLOW_DOCUMENT_3_B2_NODE);\n isAtWD4B3 = isAtWD4B3 || nodeInstance.getName().equals(ParallelSetup.WORKFLOW_DOCUMENT_4_B3_NODE);\n isAtJoin = isAtJoin || nodeInstance.getName().equals(ParallelSetup.JOIN_NODE);\n }\n assertTrue(\"Should be at blanket approved node WD2B1.\", isAtWD2B1);\n assertTrue(\"Should be at blanket approved node WD3B2.\", isAtWD3B2);\n assertTrue(\"Should be at blanket approved node WD4B3.\", isAtWD4B3);\n assertFalse(\"Should not be at join node.\", isAtJoin);\n \n document.blanketApprove(\"\");\n document = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName(\"ewestfal\"), document.getDocumentId());\n assertTrue(\"Document should be processed.\", document.isProcessed());\n actionRequests = KEWServiceLocator.getActionRequestService().findPendingByDoc(document.getDocumentId());\n assertEquals(\"Wrong number of pending action requests.\", 10, actionRequests.size());\n }\n \n @Test public void testBlanketApproveToJoin() throws Exception {\n \n WorkflowDocument document = WorkflowDocumentFactory.createDocument(getPrincipalIdForName(\"ewestfal\"), ParallelSetup.DOCUMENT_TYPE_NAME);\n document.blanketApprove(\"\", ParallelSetup.JOIN_NODE);\n assertTrue(\"Document should still be enroute.\", document.isEnroute());\n\n // document should now be at the workflow document final node\n Collection activeNodes = getRouteNodeService().getActiveNodeInstances(document.getDocumentId());\n assertEquals(\"Wrong number of active nodes.\", 1, activeNodes.size());\n RouteNodeInstance nodeInstance = (RouteNodeInstance)activeNodes.iterator().next();\n assertEquals(\"Document at wrong node.\", ParallelSetup.WORKFLOW_DOCUMENT_FINAL_NODE, nodeInstance.getName());\n \n document = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName(\"xqi\"), document.getDocumentId());\n assertTrue(\"Should have approve request.\", document.isApprovalRequested());\n document.blanketApprove(\"\", ParallelSetup.ACKNOWLEDGE_1_NODE);\n \n activeNodes = getRouteNodeService().getActiveNodeInstances(document.getDocumentId());\n assertEquals(\"Wrong number of active nodes.\", 0, activeNodes.size());\n Collection terminalNodes = getRouteNodeService().getTerminalNodeInstances(document.getDocumentId());\n assertEquals(\"Wrong number of terminal nodes.\", 1, terminalNodes.size());\n nodeInstance = (RouteNodeInstance)terminalNodes.iterator().next();\n assertEquals(\"Document at wrong node.\", ParallelSetup.ACKNOWLEDGE_2_NODE, nodeInstance.getName());\n assertTrue(\"Final node not complete.\", nodeInstance.isComplete());\n }\n \n @Test public void testBlanketApproveToAcknowledge() throws Exception {\n \n WorkflowDocument document = WorkflowDocumentFactory.createDocument(getPrincipalIdForName(\"ewestfal\"), ParallelSetup.DOCUMENT_TYPE_NAME);\n document.blanketApprove(\"\", ParallelSetup.ACKNOWLEDGE_1_NODE);\n assertTrue(\"Document should be processed.\", document.isProcessed());\n\n // document should now be terminal\n Collection activeNodes = getRouteNodeService().getActiveNodeInstances(document.getDocumentId());\n assertEquals(\"Wrong number of active nodes.\", 0, activeNodes.size());\n Collection terminalNodes = getRouteNodeService().getTerminalNodeInstances(document.getDocumentId());\n assertEquals(\"Wrong number of terminal nodes.\", 1, terminalNodes.size());\n RouteNodeInstance nodeInstance = (RouteNodeInstance)terminalNodes.iterator().next();\n assertEquals(\"Document at wrong node.\", ParallelSetup.ACKNOWLEDGE_2_NODE, nodeInstance.getName());\n assertTrue(\"Final node not complete.\", nodeInstance.isComplete());\n }\n \n @Test public void testBlanketApproveToMultipleNodesErrors() throws Exception {\n \n WorkflowDocument document = WorkflowDocumentFactory.createDocument(getPrincipalIdForName(\"ewestfal\"), ParallelSetup.DOCUMENT_TYPE_NAME);\n try {\n document.blanketApprove(\"\", new String[] { ParallelSetup.WORKFLOW_DOCUMENT_2_B1_NODE, ParallelSetup.ACKNOWLEDGE_1_NODE }); \n fail(\"document should have thrown exception\");\n } catch (Exception e) {\n // Shouldn't be able to blanket approve past the join in conjunction with blanket approve within a branch\n \tTestUtilities.getExceptionThreader().join();\n \tdocument = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName(\"ewestfal\"), document.getDocumentId());\n assertTrue(\"Document should be in exception routing.\", document.isException()); \n }\n }\n \n /**\n * Tests that the notifications are generated properly on a blanket approve. Works against the \"NotificationTest\" document type.\n */\n @Test public void testBlanketApproveNotification() throws Exception {\n WorkflowDocument document = WorkflowDocumentFactory.createDocument(getPrincipalIdForName(\"ewestfal\"), NotifySetup.DOCUMENT_TYPE_NAME);\n document.blanketApprove(\"\");\n ActionRequestService arService = KEWServiceLocator.getActionRequestService(); \n List actionRequests = arService.getRootRequests(arService.findPendingByDoc(document.getDocumentId()));\n assertEquals(\"Should be 5 pending acknowledgements and 1 pending fyi\", 6, actionRequests.size());\n boolean foundJhopfNotification = false;\n boolean foundRkirkendNotification = false;\n boolean foundJitrueNotification = false;\n boolean foundBmcgoughNotification = false;\n boolean foundXqiAck = false;\n boolean foundJthomasFYI = false;\n for (Iterator iterator = actionRequests.iterator(); iterator.hasNext();) {\n ActionRequestValue actionRequest = (ActionRequestValue) iterator.next();\n RouteNodeInstance nodeInstance = actionRequest.getNodeInstance();\n String netId = (actionRequest.getPrincipalId() == null ? null : getPrincipalNameForId(actionRequest.getPrincipalId()));\n if (\"jhopf\".equals(netId)) {\n foundJhopfNotification = true;\n assertTrue(\"Action request should be an acknowledge.\", actionRequest.isAcknowledgeRequest());\n assertEquals(NotifySetup.NOTIFY_FIRST_NODE, nodeInstance.getName());\n } else if (\"rkirkend\".equals(netId)) {\n foundRkirkendNotification = true;", "answers": [" assertTrue(\"Action request should be an acknowledge.\", actionRequest.isAcknowledgeRequest());"], "length": 1537, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "cb8eee56-a674-4568-8d53-749abb69654d", "reasoning": "The code is inside a loop checking each ActionRequestValue's principal. For the 'jhopf' case it set a flag, asserted the request is an acknowledge, and checked the node name. The next case for 'rkirkend' has just set the flag, so the following line should mirror the jhopf block: an assertion that the request is an acknowledge request.", "reasoning_model_answer": "assertTrue(\"Action request should be an acknowledge.\", actionRequest.isAcknowledgeRequest());", "assistant_with_reasoning": "\nThe code is inside a loop checking each ActionRequestValue's principal. For the 'jhopf' case it set a flag, asserted the request is an acknowledge, and checked the node name. The next case for 'rkirkend' has just set the flag, so the following line should mirror the jhopf block: an assertion that the request is an acknowledge request.\n\nassertTrue(\"Action request should be an acknowledge.\", actionRequest.isAcknowledgeRequest());", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 5.972, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 24562, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "assertTrue(\"Action request should be an acknowledge.\", actionRequest.isAcknowledgeRequest());", "score": 0.92, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "// Copyright 2016 Google Inc. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nusing UnityEngine;\nusing UnityEngine.Audio;\nusing System.Collections;\n\n/// GVR audio source component that enhances AudioSource to provide advanced spatial audio features.\n[AddComponentMenu(\"GoogleVR/Audio/GvrAudioSource\")]\npublic class GvrAudioSource : MonoBehaviour {\n /// Denotes whether the room effects should be bypassed.\n public bool bypassRoomEffects = false;\n\n /// Directivity pattern shaping factor.\n public float directivityAlpha = 0.0f;\n\n /// Directivity pattern order.\n public float directivitySharpness = 1.0f;\n\n /// Listener directivity pattern shaping factor.\n public float listenerDirectivityAlpha = 0.0f;\n\n /// Listener directivity pattern order.\n public float listenerDirectivitySharpness = 1.0f;\n\n /// Input gain in decibels.\n public float gainDb = 0.0f;\n\n /// Occlusion effect toggle.\n public bool occlusionEnabled = false;\n\n /// Play source on awake.\n public bool playOnAwake = true;\n\n /// The default AudioClip to play.\n public AudioClip clip {\n get { return sourceClip; }\n set {\n sourceClip = value;\n if (audioSource != null) {\n audioSource.clip = sourceClip;\n }\n }\n }\n [SerializeField]\n private AudioClip sourceClip = null;\n\n /// Is the clip playing right now (Read Only)?\n public bool isPlaying {\n get {\n if (audioSource != null) {\n return audioSource.isPlaying;\n }\n return false;\n }\n }\n\n /// Is the audio clip looping?\n public bool loop {\n get { return sourceLoop; }\n set {\n sourceLoop = value;\n if (audioSource != null) {\n audioSource.loop = sourceLoop;\n }\n }\n }\n [SerializeField]\n private bool sourceLoop = false;\n\n /// Un- / Mutes the source. Mute sets the volume=0, Un-Mute restore the original volume.\n public bool mute {\n get { return sourceMute; }\n set {\n sourceMute = value;\n if (audioSource != null) {\n audioSource.mute = sourceMute;\n }\n }\n }\n [SerializeField]\n private bool sourceMute = false;\n\n /// The pitch of the audio source.\n public float pitch {\n get { return sourcePitch; }\n set {\n sourcePitch = value;\n if (audioSource != null) {\n audioSource.pitch = sourcePitch;\n }\n }\n }\n [SerializeField]\n [Range(-3.0f, 3.0f)]\n private float sourcePitch = 1.0f;\n\n /// Sets the priority of the audio source.\n public int priority {\n get { return sourcePriority; }\n set {\n sourcePriority = value;\n if(audioSource != null) {\n audioSource.priority = sourcePriority;\n }\n }\n }\n [SerializeField]\n [Range(0, 256)]\n private int sourcePriority = 128;\n\n /// Sets how much this source is affected by 3D spatialization calculations (attenuation, doppler).\n public float spatialBlend {\n get { return sourceSpatialBlend; }\n set {\n sourceSpatialBlend = value;\n if (audioSource != null) {\n audioSource.spatialBlend = sourceSpatialBlend;\n }\n }\n }\n [SerializeField]\n [Range(0.0f, 1.0f)]\n private float sourceSpatialBlend = 1.0f;\n\n /// Sets the Doppler scale for this audio source.\n public float dopplerLevel {\n get { return sourceDopplerLevel; }\n set {\n sourceDopplerLevel = value;\n if(audioSource != null) {\n audioSource.dopplerLevel = sourceDopplerLevel;\n }\n }\n }\n [SerializeField]\n [Range(0.0f, 5.0f)]\n private float sourceDopplerLevel = 1.0f;\n\n /// Sets the spread angle (in degrees) in 3D space.\n public float spread {\n get { return sourceSpread; }\n set {\n sourceSpread = value;\n if(audioSource != null) {\n audioSource.spread = sourceSpread;\n }\n }\n }\n [SerializeField]\n [Range(0.0f, 360.0f)]\n private float sourceSpread = 0.0f;\n\n /// Playback position in seconds.\n public float time {\n get {\n if(audioSource != null) {\n return audioSource.time;\n }\n return 0.0f;\n }\n set {\n if(audioSource != null) {\n audioSource.time = value;\n }\n }\n }\n\n /// Playback position in PCM samples.\n public int timeSamples {\n get {\n if(audioSource != null) {\n return audioSource.timeSamples;\n }\n return 0;\n }\n set {\n if(audioSource != null) {\n audioSource.timeSamples = value;\n }\n }\n }\n\n /// The volume of the audio source (0.0 to 1.0).\n public float volume {\n get { return sourceVolume; }\n set {\n sourceVolume = value;\n if (audioSource != null) {\n audioSource.volume = sourceVolume;\n }\n }\n }\n [SerializeField]\n [Range(0.0f, 1.0f)]\n private float sourceVolume = 1.0f;\n\n /// Volume rolloff model with respect to the distance.\n public AudioRolloffMode rolloffMode {\n get { return sourceRolloffMode; }\n set {\n sourceRolloffMode = value;\n if (audioSource != null) {\n audioSource.rolloffMode = sourceRolloffMode;\n if (rolloffMode == AudioRolloffMode.Custom) {\n // Custom rolloff is not supported, set the curve for no distance attenuation.\n audioSource.SetCustomCurve(AudioSourceCurveType.CustomRolloff,\n AnimationCurve.Linear(sourceMinDistance, 1.0f,\n sourceMaxDistance, 1.0f));\n }\n }\n }\n }\n [SerializeField]\n private AudioRolloffMode sourceRolloffMode = AudioRolloffMode.Logarithmic;\n\n /// MaxDistance is the distance a sound stops attenuating at.\n public float maxDistance {\n get { return sourceMaxDistance; }\n set {\n sourceMaxDistance = Mathf.Clamp(value, sourceMinDistance + GvrAudio.distanceEpsilon,\n GvrAudio.maxDistanceLimit);\n if(audioSource != null) {\n audioSource.maxDistance = sourceMaxDistance;\n }\n }\n }\n [SerializeField]\n private float sourceMaxDistance = 500.0f;\n\n /// Within the Min distance the GvrAudioSource will cease to grow louder in volume.\n public float minDistance {\n get { return sourceMinDistance; }\n set {\n sourceMinDistance = Mathf.Clamp(value, 0.0f, GvrAudio.minDistanceLimit);\n if(audioSource != null) {\n audioSource.minDistance = sourceMinDistance;\n }\n }\n }\n [SerializeField]\n private float sourceMinDistance = 1.0f;\n\n /// Binaural (HRTF) rendering toggle.\n [SerializeField]\n private bool hrtfEnabled = true;\n\n // Unity audio source attached to the game object.\n [SerializeField]\n private AudioSource audioSource = null;\n\n // Unique source id.\n private int id = -1;\n\n // Current occlusion value;\n private float currentOcclusion = 0.0f;\n\n // Next occlusion update time in seconds.\n private float nextOcclusionUpdate = 0.0f;\n\n // Denotes whether the source is currently paused or not.\n private bool isPaused = false;\n\n void Awake () {\n if (audioSource == null) {\n // Ensure the audio source gets created once.\n audioSource = gameObject.AddComponent();\n }\n audioSource.enabled = false;\n audioSource.hideFlags = HideFlags.HideInInspector | HideFlags.HideAndDontSave;\n audioSource.playOnAwake = false;\n audioSource.bypassReverbZones = true;\n#if UNITY_5_5_OR_NEWER\n audioSource.spatializePostEffects = true;\n#endif // UNITY_5_5_OR_NEWER\n OnValidate();\n // Route the source output to |GvrAudioMixer|.\n AudioMixer mixer = (Resources.Load(\"GvrAudioMixer\") as AudioMixer);\n if(mixer != null) {\n audioSource.outputAudioMixerGroup = mixer.FindMatchingGroups(\"Master\")[0];\n } else {\n Debug.LogError(\"GVRAudioMixer could not be found in Resources. Make sure that the GVR SDK \" +\n \"Unity package is imported properly.\");\n }\n }\n\n void OnEnable () {\n audioSource.enabled = true;\n if (playOnAwake && !isPlaying && InitializeSource()) {\n Play();\n }\n }\n\n void Start () {\n if (playOnAwake && !isPlaying) {\n Play();\n }\n }\n\n void OnDisable () {\n Stop();\n audioSource.enabled = false;\n }\n\n void OnDestroy () {\n Destroy(audioSource);\n }\n\n void OnApplicationPause (bool pauseStatus) {\n if (pauseStatus) {\n Pause();\n } else {\n UnPause();\n }\n }\n\n void Update () {\n // Update occlusion state.\n if (!occlusionEnabled) {\n currentOcclusion = 0.0f;\n } else if (Time.time >= nextOcclusionUpdate) {\n nextOcclusionUpdate = Time.time + GvrAudio.occlusionDetectionInterval;\n currentOcclusion = GvrAudio.ComputeOcclusion(transform);\n }\n // Update source.\n if (!isPlaying && !isPaused) {\n Stop();\n } else {\n audioSource.SetSpatializerFloat((int) GvrAudio.SpatializerData.Gain,\n GvrAudio.ConvertAmplitudeFromDb(gainDb));\n audioSource.SetSpatializerFloat((int) GvrAudio.SpatializerData.MinDistance,\n sourceMinDistance);\n GvrAudio.UpdateAudioSource(id, this, currentOcclusion);\n }\n }\n\n /// Provides a block of the currently playing source's output data.\n ///\n /// @note The array given in samples will be filled with the requested data before spatialization.\n public void GetOutputData(float[] samples, int channel) {\n if (audioSource != null) {\n audioSource.GetOutputData(samples, channel);\n }\n }\n\n /// Provides a block of the currently playing audio source's spectrum data.\n ///\n /// @note The array given in samples will be filled with the requested data before spatialization.\n public void GetSpectrumData(float[] samples, int channel, FFTWindow window) {\n if (audioSource != null) {\n audioSource.GetSpectrumData(samples, channel, window);\n }\n }\n\n /// Pauses playing the clip.\n public void Pause () {\n if (audioSource != null) {\n isPaused = true;\n audioSource.Pause();\n }\n }\n\n /// Plays the clip.\n public void Play () {\n if (audioSource != null && InitializeSource()) {\n audioSource.Play();\n isPaused = false;\n } else {\n Debug.LogWarning (\"GVR Audio source not initialized. Audio playback not supported \" +\n \"until after Awake() and OnEnable(). Try calling from Start() instead.\");\n }\n }\n\n /// Plays the clip with a delay specified in seconds.\n public void PlayDelayed (float delay) {\n if (audioSource != null && InitializeSource()) {\n audioSource.PlayDelayed(delay);\n isPaused = false;\n } else {\n Debug.LogWarning (\"GVR Audio source not initialized. Audio playback not supported \" +\n \"until after Awake() and OnEnable(). Try calling from Start() instead.\");\n }\n }\n\n /// Plays an AudioClip.\n public void PlayOneShot (AudioClip clip) {\n PlayOneShot(clip, 1.0f);\n }\n\n /// Plays an AudioClip, and scales its volume.\n public void PlayOneShot (AudioClip clip, float volume) {\n if (audioSource != null && InitializeSource()) {\n audioSource.PlayOneShot(clip, volume);\n isPaused = false;\n } else {\n Debug.LogWarning (\"GVR Audio source not initialized. Audio playback not supported \" +", "answers": [" \"until after Awake() and OnEnable(). Try calling from Start() instead.\");"], "length": 1376, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "d5a712a1-f9aa-4d3c-ad64-0544d0f119d6", "reasoning": "The code is inside the PlayOneShot(AudioClip, float) method. The else block starts a Debug.LogWarning call with a string concatenation that ends with a '+' on the previous line. The next line should complete the concatenated string and close the method call, matching the pattern used earlier in the file for similar warnings.", "reasoning_model_answer": "\"until after Awake() and OnEnable(). Try calling from Start() instead.\");", "assistant_with_reasoning": "\nThe code is inside the PlayOneShot(AudioClip, float) method. The else block starts a Debug.LogWarning call with a string concatenation that ends with a '+' on the previous line. The next line should complete the concatenated string and close the method call, matching the pattern used earlier in the file for similar warnings.\n\n\"until after Awake() and OnEnable(). Try calling from Start() instead.\");", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 7.55, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 11603, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "\"until after Awake() and OnEnable(). Try calling from Start() instead.\");", "score": 0.86, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "# -*- encoding: utf-8 -*-\n\"\"\"\nLocal server.\n\n`H2OLocalServer` allows to start H2O servers on your local machine:\n hs = H2OLocalServer.start() : start a new local server\n hs.is_running() : check if the server is running\n hs.shutdown() : shut down the server\n\n:copyright: (c) 2016 H2O.ai\n:license: Apache License Version 2.0 (see LICENSE for details)\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport atexit\nimport os\nimport subprocess\nimport sys\nimport tempfile\nimport time\nfrom random import choice\nfrom sysconfig import get_config_var\nfrom warnings import warn\n\nfrom h2o.exceptions import H2OServerError, H2OStartupError, H2OValueError\nfrom h2o.utils.compatibility import * # NOQA\nfrom h2o.utils.typechecks import assert_is_type, assert_satisfies, BoundInt, I, is_type\n\n__all__ = (\"H2OLocalServer\", )\n\n\n\nclass H2OLocalServer(object):\n \"\"\"\n Handle to an H2O server launched locally.\n\n Public interface::\n\n hs = H2OLocalServer.start(...) # launch a new local H2O server\n hs.is_running() # check if the server is running\n hs.shutdown() # shut down the server\n hs.scheme # either \"http\" or \"https\"\n hs.ip # ip address of the server, typically \"127.0.0.1\"\n hs.port # port on which the server is listening\n\n Once started, the server will run until the script terminates, or until you call `.shutdown()` on it. Moreover,\n if the server terminates with an exception, then the server will not stop and will continue to run even after\n Python process exits. This runaway process may end up being in a bad shape (e.g. frozen), then the only way to\n terminate it is to kill the java process from the terminal.\n\n Alternatively, it is possible to start the server as a context manager, in which case it will be automatically\n shut down even if an exception occurs in Python (but not if the Python process is killed)::\n\n with H2OLocalServer.start() as hs:\n # do something with the server -- probably connect to it\n \"\"\"\n\n _TIME_TO_START = 10 # Maximum time we wait for the server to start up (in seconds)\n _TIME_TO_KILL = 3 # Maximum time we wait for the server to shut down until we kill it (in seconds)\n\n\n @staticmethod\n def start(jar_path=None, nthreads=-1, enable_assertions=True, max_mem_size=None, min_mem_size=None,\n ice_root=None, port=\"54321+\", verbose=True):\n \"\"\"\n Start new H2O server on the local machine.\n\n :param jar_path: Path to the h2o.jar executable. If not given, then we will search for h2o.jar in the\n locations returned by `._jar_paths()`.\n :param nthreads: Number of threads in the thread pool. This should be related to the number of CPUs used.\n -1 means use all CPUs on the host. A positive integer specifies the number of CPUs directly.\n :param enable_assertions: If True, pass `-ea` option to the JVM.\n :param max_mem_size: Maximum heap size (jvm option Xmx), in bytes.\n :param min_mem_size: Minimum heap size (jvm option Xms), in bytes.\n :param ice_root: A directory where H2O stores its temporary files. Default location is determined by\n tempfile.mkdtemp().\n :param port: Port where to start the new server. This could be either an integer, or a string of the form\n \"DDDDD+\", indicating that the server should start looking for an open port starting from DDDDD and up.\n :param verbose: If True, then connection info will be printed to the stdout.\n\n :returns: a new H2OLocalServer instance\n \"\"\"\n assert_is_type(jar_path, None, str)\n assert_is_type(port, None, int, str)\n assert_is_type(nthreads, -1, BoundInt(1, 4096))\n assert_is_type(enable_assertions, bool)\n assert_is_type(min_mem_size, None, int)\n assert_is_type(max_mem_size, None, BoundInt(1 << 25))\n assert_is_type(ice_root, None, I(str, os.path.isdir))\n if jar_path:\n assert_satisfies(jar_path, jar_path.endswith(\"h2o.jar\"))\n\n if min_mem_size is not None and max_mem_size is not None and min_mem_size > max_mem_size:\n raise H2OValueError(\"`min_mem_size`=%d is larger than the `max_mem_size`=%d\" % (min_mem_size, max_mem_size))\n if port is None: port = \"54321+\"\n baseport = None\n # TODO: get rid of this port gimmick and have 2 separate parameters.\n if is_type(port, str):\n if port.isdigit():\n port = int(port)\n else:\n if not(port[-1] == \"+\" and port[:-1].isdigit()):\n raise H2OValueError(\"`port` should be of the form 'DDDD+', where D is a digit. Got: %s\" % port)\n baseport = int(port[:-1])\n port = 0\n\n hs = H2OLocalServer()\n hs._verbose = bool(verbose)\n hs._jar_path = hs._find_jar(jar_path)\n hs._ice_root = ice_root\n if not ice_root:\n hs._ice_root = tempfile.mkdtemp()\n hs._tempdir = hs._ice_root\n\n if verbose: print(\"Attempting to start a local H2O server...\")\n hs._launch_server(port=port, baseport=baseport, nthreads=int(nthreads), ea=enable_assertions,\n mmax=max_mem_size, mmin=min_mem_size)\n if verbose: print(\" Server is running at %s://%s:%d\" % (hs.scheme, hs.ip, hs.port))\n atexit.register(lambda: hs.shutdown())\n return hs\n\n\n def is_running(self):\n \"\"\"Return True if the server process is still running, False otherwise.\"\"\"\n return self._process is not None and self._process.poll() is None\n\n\n def shutdown(self):\n \"\"\"\n Shut down the server by trying to terminate/kill its process.\n\n First we attempt to terminate the server process gracefully (sending SIGTERM signal). However after\n _TIME_TO_KILL seconds if the process didn't shutdown, we forcefully kill it with a SIGKILL signal.\n \"\"\"\n if not self._process: return\n try:\n kill_time = time.time() + self._TIME_TO_KILL\n while self._process.poll() is None and time.time() < kill_time:\n self._process.terminate()\n time.sleep(0.2)\n if self._process().poll() is None:\n self._process.kill()\n time.sleep(0.2)\n if self._verbose:\n print(\"Local H2O server %s:%s stopped.\" % (self.ip, self.port))\n except:\n pass\n self._process = None\n\n\n @property\n def scheme(self):\n \"\"\"Connection scheme, 'http' or 'https'.\"\"\"\n return self._scheme\n\n @property\n def ip(self):\n \"\"\"IP address of the server.\"\"\"\n return self._ip\n\n @property\n def port(self):\n \"\"\"Port that the server is listening to.\"\"\"\n return self._port\n\n\n #-------------------------------------------------------------------------------------------------------------------\n # Private\n #-------------------------------------------------------------------------------------------------------------------\n\n def __init__(self):\n \"\"\"[Internal] please use H2OLocalServer.start() to launch a new server.\"\"\"\n self._scheme = None # \"http\" or \"https\"\n self._ip = None\n self._port = None\n self._process = None\n self._verbose = None\n self._jar_path = None\n self._ice_root = None\n self._stdout = None\n self._stderr = None\n self._tempdir = None\n\n\n def _find_jar(self, path0=None):\n \"\"\"\n Return the location of an h2o.jar executable.\n\n :param path0: Explicitly given h2o.jar path. If provided, then we will simply check whether the file is there,\n otherwise we will search for an executable in locations returned by ._jar_paths().\n\n :raises H2OStartupError: if no h2o.jar executable can be found.\n \"\"\"\n jar_paths = [path0] if path0 else self._jar_paths()\n searched_paths = []\n for jp in jar_paths:\n searched_paths.append(jp)\n if os.path.exists(jp):\n return jp\n raise H2OStartupError(\"Cannot start local server: h2o.jar not found. Paths searched:\\n\" +\n \"\".join(\" %s\\n\" % s for s in searched_paths))\n\n @staticmethod\n def _jar_paths():\n \"\"\"Produce potential paths for an h2o.jar executable.\"\"\"\n # Check if running from an h2o-3 src folder (or any subfolder), in which case use the freshly-built h2o.jar\n cwd_chunks = os.path.abspath(\".\").split(os.path.sep)\n for i in range(len(cwd_chunks), 0, -1):\n if cwd_chunks[i - 1] == \"h2o-3\":\n yield os.path.sep.join(cwd_chunks[:i] + [\"build\", \"h2o.jar\"])\n # Then check the backend/bin folder:\n # (the following works assuming this code is located in h2o/backend/server.py file)\n backend_dir = os.path.split(os.path.realpath(__file__))[0]\n yield os.path.join(backend_dir, \"bin\", \"h2o.jar\")\n\n # Then try several old locations where h2o.jar might have been installed\n prefix1 = prefix2 = sys.prefix\n # On Unix-like systems Python typically gets installed into /Library/... or /System/Library/... If one of\n # those paths is sys.prefix, then we also build its counterpart.\n if prefix1.startswith(os.path.sep + \"Library\"):\n prefix2 = os.path.join(\"\", \"System\", prefix1)\n elif prefix1.startswith(os.path.sep + \"System\"):\n prefix2 = prefix1[len(os.path.join(\"\", \"System\")):]\n yield os.path.join(prefix1, \"h2o_jar\", \"h2o.jar\")\n yield os.path.join(os.path.abspath(os.sep), \"usr\", \"local\", \"h2o_jar\", \"h2o.jar\")\n yield os.path.join(prefix1, \"local\", \"h2o_jar\", \"h2o.jar\")\n yield os.path.join(get_config_var(\"userbase\"), \"h2o_jar\", \"h2o.jar\")\n yield os.path.join(prefix2, \"h2o_jar\", \"h2o.jar\")\n\n\n def _launch_server(self, port, baseport, mmax, mmin, ea, nthreads):\n \"\"\"Actually start the h2o.jar executable (helper method for `.start()`).\"\"\"\n self._ip = \"127.0.0.1\"\n\n # Find Java and check version. (Note that subprocess.check_output returns the output as a bytes object)\n java = self._find_java()\n jver_bytes = subprocess.check_output([java, \"-version\"], stderr=subprocess.STDOUT)\n jver = jver_bytes.decode(encoding=\"utf-8\", errors=\"ignore\")\n if self._verbose:\n print(\" Java Version: \" + jver.strip().replace(\"\\n\", \"; \"))\n if \"GNU libgcj\" in jver:\n raise H2OStartupError(\"Sorry, GNU Java is not supported for H2O.\\n\"\n \"Please download the latest 64-bit Java SE JDK from Oracle.\")\n if \"Client VM\" in jver:\n warn(\" You have a 32-bit version of Java. H2O works best with 64-bit Java.\\n\"\n \" Please download the latest 64-bit Java SE JDK from Oracle.\\n\")\n\n if self._verbose:\n print(\" Starting server from \" + self._jar_path)\n print(\" Ice root: \" + self._ice_root)\n\n # Construct java command to launch the process\n cmd = [java]\n\n # ...add JVM options\n cmd += [\"-ea\"] if ea else []\n for (mq, num) in [(\"-Xms\", mmin), (\"-Xmx\", mmax)]:\n if num is None: continue\n numstr = \"%dG\" % (num >> 30) if num == (num >> 30) << 30 else \\\n \"%dM\" % (num >> 20) if num == (num >> 20) << 20 else \\\n str(num)\n cmd += [mq + numstr]\n cmd += [\"-verbose:gc\", \"-XX:+PrintGCDetails\", \"-XX:+PrintGCTimeStamps\"]\n cmd += [\"-jar\", self._jar_path] # This should be the last JVM option\n\n # ...add H2O options\n cmd += [\"-ip\", self._ip]\n cmd += [\"-port\", str(port)] if port else []\n cmd += [\"-baseport\", str(baseport)] if baseport else []\n cmd += [\"-ice_root\", self._ice_root]\n cmd += [\"-nthreads\", str(nthreads)] if nthreads > 0 else []\n cmd += [\"-name\", \"H2O_from_python_%s\" % self._tmp_file(\"salt\")]\n # Warning: do not change to any higher log-level, otherwise we won't be able to know which port the\n # server is listening to.\n cmd += [\"-log_level\", \"INFO\"]\n\n # Create stdout and stderr files\n self._stdout = self._tmp_file(\"stdout\")\n self._stderr = self._tmp_file(\"stderr\")\n cwd = os.path.abspath(os.getcwd())\n out = open(self._stdout, \"w\")\n err = open(self._stderr, \"w\")\n if self._verbose:\n print(\" JVM stdout: \" + out.name)\n print(\" JVM stderr: \" + err.name)\n\n # Launch the process\n win32 = sys.platform == \"win32\"\n flags = getattr(subprocess, \"CREATE_NEW_PROCESS_GROUP\", 0) if win32 else 0\n prex = os.setsid if not win32 else None\n try:", "answers": [" proc = subprocess.Popen(args=cmd, stdout=out, stderr=err, cwd=cwd, creationflags=flags, preexec_fn=prex)"], "length": 1465, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "c8a957e6-e283-4d7b-9057-0f5023801df4", "reasoning": "The code is inside the _launch_server method, preparing to start the Java process. After setting platform‑specific flags and pre‑exec function, the next step is to actually launch the subprocess with Popen, passing the command list, working directory, stdout/stderr files, and the appropriate flags. Therefore the line after 'try:' should be the Popen call that assigns the process to self._process.", "reasoning_model_answer": "self._process = subprocess.Popen(cmd, cwd=cwd, stdout=out, stderr=err, close_fds=not win32, creationflags=flags, preexec_fn=prex)", "assistant_with_reasoning": "\nThe code is inside the _launch_server method, preparing to start the Java process. After setting platform‑specific flags and pre‑exec function, the next step is to actually launch the subprocess with Popen, passing the command list, working directory, stdout/stderr files, and the appropriate flags. Therefore the line after 'try:' should be the Popen call that assigns the process to self._process.\n\nself._process = subprocess.Popen(cmd, cwd=cwd, stdout=out, stderr=err, close_fds=not win32, creationflags=flags, preexec_fn=prex)", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.031, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 13007, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "self._process = subprocess.Popen(cmd, cwd=cwd, stdout=out, stderr=err, close_fds=not win32, creationflags=flags, preexec_fn=prex)", "score": 0.78, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.apache.sentry.tests.e2e.hive;\n\nimport static org.junit.Assert.assertFalse;\nimport static org.junit.Assert.assertNotNull;\nimport static org.junit.Assert.assertTrue;\n\nimport java.io.File;\nimport java.io.FileOutputStream;\nimport java.sql.Connection;\nimport java.sql.ResultSet;\nimport java.sql.SQLException;\nimport java.sql.Statement;\n\nimport junit.framework.Assert;\n\nimport org.apache.sentry.provider.file.PolicyFile;\nimport org.junit.Before;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.google.common.io.Resources;\n\n/* Tests privileges at table scope within a single database.\n */\n\npublic class TestPrivilegesAtTableScope extends AbstractTestWithStaticConfiguration {\n\n private static PolicyFile policyFile;\n private final static String MULTI_TYPE_DATA_FILE_NAME = \"emp.dat\";\n\n @Before\n public void setup() throws Exception {\n policyFile = super.setupPolicy();\n super.setup();\n prepareDBDataForTest();\n }\n\n @BeforeClass\n public static void setupTestStaticConfiguration() throws Exception {\n AbstractTestWithStaticConfiguration.setupTestStaticConfiguration();\n }\n\n protected static void prepareDBDataForTest() throws Exception {\n // copy data file to test dir\n File dataDir = context.getDataDir();\n File dataFile = new File(dataDir, MULTI_TYPE_DATA_FILE_NAME);\n FileOutputStream to = new FileOutputStream(dataFile);\n Resources.copy(Resources.getResource(MULTI_TYPE_DATA_FILE_NAME), to);\n to.close();\n\n // setup db objects needed by the test\n Connection connection = context.createConnection(ADMIN1);\n Statement statement = context.createStatement(connection);\n\n statement.execute(\"DROP DATABASE IF EXISTS DB_1 CASCADE\");\n statement.execute(\"CREATE DATABASE DB_1\");\n statement.execute(\"USE DB_1\");\n\n statement.execute(\"CREATE TABLE \" + TBL1 + \"(B INT, A STRING) \"\n + \" row format delimited fields terminated by '|' stored as textfile\");\n statement.execute(\"LOAD DATA LOCAL INPATH '\" + dataFile.getPath() + \"' INTO TABLE \" + TBL1);\n statement.execute(\"CREATE TABLE \" + TBL2 + \"(B INT, A STRING) \"\n + \" row format delimited fields terminated by '|' stored as textfile\");\n statement.execute(\"LOAD DATA LOCAL INPATH '\" + dataFile.getPath() + \"' INTO TABLE \" + TBL2);\n statement.execute(\"CREATE VIEW VIEW_1 AS SELECT A, B FROM \" + TBL1);\n\n statement.close();\n connection.close();\n }\n\n /*\n * Admin creates database DB_1, table TBL1, TBL2 in DB_1, loads data into\n * TBL1, TBL2 Admin grants SELECT on TBL1, TBL2, INSERT on TBL1 to\n * USER_GROUP of which user1 is a member.\n */\n @Test\n public void testInsertAndSelect() throws Exception {\n policyFile\n .addRolesToGroup(USERGROUP1, \"select_tab1\", \"insert_tab1\", \"select_tab2\")\n .addPermissionsToRole(\"select_tab1\", \"server=server1->db=DB_1->table=\" + TBL1 + \"->action=select\")\n .addPermissionsToRole(\"insert_tab1\", \"server=server1->db=DB_1->table=\" + TBL1 + \"->action=insert\")\n .addPermissionsToRole(\"select_tab2\", \"server=server1->db=DB_1->table=\" + TBL2 + \"->action=select\")\n .setUserGroupMapping(StaticUserGroup.getStaticMapping());\n writePolicyFile(policyFile);\n\n // test execution\n Connection connection = context.createConnection(USER1_1);\n Statement statement = context.createStatement(connection);\n statement.execute(\"USE DB_1\");\n // test user can insert\n statement.execute(\"INSERT INTO TABLE \" + TBL1 + \" SELECT A, B FROM \" + TBL2);\n // test user can query table\n statement.executeQuery(\"SELECT A FROM \" + TBL2);\n // negative test: test user can't drop\n try {\n statement.execute(\"DROP TABLE \" + TBL1);\n Assert.fail(\"Expected SQL exception\");\n } catch (SQLException e) {\n context.verifyAuthzException(e);\n }\n statement.close();\n connection.close();\n\n // connect as admin and drop TBL1\n connection = context.createConnection(ADMIN1);\n statement = context.createStatement(connection);\n statement.execute(\"USE DB_1\");\n statement.execute(\"DROP TABLE \" + TBL1);\n statement.close();\n connection.close();\n\n // negative test: connect as user1 and try to recreate TBL1\n connection = context.createConnection(USER1_1);\n statement = context.createStatement(connection);\n statement.execute(\"USE DB_1\");\n try {\n statement.execute(\"CREATE TABLE \" + TBL1 + \"(A STRING)\");\n Assert.fail(\"Expected SQL exception\");\n } catch (SQLException e) {\n context.verifyAuthzException(e);\n }\n\n statement.close();\n connection.close();\n\n // connect as admin to restore the TBL1\n connection = context.createConnection(ADMIN1);\n statement = context.createStatement(connection);\n statement.execute(\"USE DB_1\");\n statement.execute(\"CREATE TABLE \" + TBL1 + \"(B INT, A STRING) \"\n + \" row format delimited fields terminated by '|' stored as textfile\");\n statement.execute(\"INSERT INTO TABLE \" + TBL1 + \" SELECT A, B FROM \" + TBL2);\n statement.close();\n connection.close();\n\n }\n\n /*\n * Admin creates database DB_1, table TBL1, TBL2 in DB_1, loads data into\n * TBL1, TBL2. Admin grants INSERT on TBL1, SELECT on TBL2 to USER_GROUP\n * of which user1 is a member.\n */\n @Test\n public void testInsert() throws Exception {\n policyFile\n .addRolesToGroup(USERGROUP1, \"insert_tab1\", \"select_tab2\")\n .addPermissionsToRole(\"insert_tab1\", \"server=server1->db=DB_1->table=\" + TBL1 + \"->action=insert\")\n .addPermissionsToRole(\"select_tab2\", \"server=server1->db=DB_1->table=\" + TBL2 + \"->action=select\")\n .setUserGroupMapping(StaticUserGroup.getStaticMapping());\n writePolicyFile(policyFile);\n\n // test execution\n Connection connection = context.createConnection(USER1_1);\n Statement statement = context.createStatement(connection);\n statement.execute(\"USE \" + DB1);\n // test user can execute insert on table\n statement.execute(\"INSERT INTO TABLE \" + TBL1 + \" SELECT A, B FROM \" + TBL2);\n\n // negative test: user can't query table\n try {\n statement.executeQuery(\"SELECT A FROM \" + TBL1);\n Assert.fail(\"Expected SQL exception\");\n } catch (SQLException e) {\n context.verifyAuthzException(e);\n }\n\n // negative test: test user can't query view\n try {\n statement.executeQuery(\"SELECT A FROM VIEW_1\");\n Assert.fail(\"Expected SQL exception\");\n } catch (SQLException e) {\n context.verifyAuthzException(e);\n }\n\n // negative test case: show tables shouldn't list VIEW_1\n ResultSet resultSet = statement.executeQuery(\"SHOW TABLES\");\n while (resultSet.next()) {\n String tableName = resultSet.getString(1);\n assertNotNull(\"table name is null in result set\", tableName);\n assertFalse(\"Found VIEW_1 in the result set\",\n \"VIEW_1\".equalsIgnoreCase(tableName));\n }\n\n // negative test: test user can't create a new view\n try {\n statement.executeQuery(\"CREATE VIEW VIEW_2(A) AS SELECT A FROM \" + TBL1);\n Assert.fail(\"Expected SQL Exception\");\n } catch (SQLException e) {\n context.verifyAuthzException(e);\n }\n statement.close();\n connection.close();\n }\n\n /*\n * Admin creates database DB_1, table TBL1, TBL2 in DB_1, loads data into\n * TBL1, TBL2. Admin grants SELECT on TBL1, TBL2 to USER_GROUP of which\n * user1 is a member.\n */\n @Test\n public void testSelect() throws Exception {\n policyFile\n .addRolesToGroup(USERGROUP1, \"select_tab1\", \"select_tab2\")\n .addPermissionsToRole(\"select_tab1\", \"server=server1->db=DB_1->table=\" + TBL1 + \"->action=select\")\n .addPermissionsToRole(\"insert_tab1\", \"server=server1->db=DB_1->table=\" + TBL1 + \"->action=insert\")\n .addPermissionsToRole(\"select_tab2\", \"server=server1->db=DB_1->table=\" + TBL2 + \"->action=select\")\n .setUserGroupMapping(StaticUserGroup.getStaticMapping());\n writePolicyFile(policyFile);\n\n // test execution\n Connection connection = context.createConnection(USER1_1);\n Statement statement = context.createStatement(connection);\n statement.execute(\"USE \" + DB1);\n // test user can execute query on table\n statement.executeQuery(\"SELECT A FROM \" + TBL1);\n\n // negative test: test insert into table\n try {\n statement.executeQuery(\"INSERT INTO TABLE \" + TBL1 + \" SELECT A, B FROM \" + TBL2);\n Assert.fail(\"Expected SQL exception\");\n } catch (SQLException e) {\n context.verifyAuthzException(e);\n }\n\n // negative test: test user can't query view\n try {\n statement.executeQuery(\"SELECT A FROM VIEW_1\");\n Assert.fail(\"Expected SQL exception\");\n } catch (SQLException e) {\n context.verifyAuthzException(e);\n }\n\n // negative test: test user can't create a new view\n try {\n statement.executeQuery(\"CREATE VIEW VIEW_2(A) AS SELECT A FROM \" + TBL1);\n Assert.fail(\"Expected SQL Exception\");\n } catch (SQLException e) {\n context.verifyAuthzException(e);\n }\n statement.close();\n connection.close();\n }\n\n /*\n * Admin creates database DB_1, table TBL1, TBL2 in DB_1, VIEW_1 on TBL1\n * loads data into TBL1, TBL2. Admin grants SELECT on TBL1,TBL2 to\n * USER_GROUP of which user1 is a member.\n */\n @Test\n public void testTableViewJoin() throws Exception {\n policyFile\n .addRolesToGroup(USERGROUP1, \"select_tab1\", \"select_tab2\")\n .addPermissionsToRole(\"select_tab1\", \"server=server1->db=DB_1->table=\" + TBL1 + \"->action=select\")\n .addPermissionsToRole(\"select_tab2\", \"server=server1->db=DB_1->table=\" + TBL2 + \"->action=select\")\n .setUserGroupMapping(StaticUserGroup.getStaticMapping());\n writePolicyFile(policyFile);\n\n // test execution\n Connection connection = context.createConnection(USER1_1);\n Statement statement = context.createStatement(connection);\n statement.execute(\"USE \" + DB1);\n // test user can execute query TBL1 JOIN TBL2\n statement.executeQuery(\"SELECT T1.B FROM \" + TBL1 + \" T1 JOIN \" + TBL2 + \" T2 ON (T1.B = T2.B)\");\n\n // negative test: test user can't execute query VIEW_1 JOIN TBL2\n try {\n statement.executeQuery(\"SELECT V1.B FROM VIEW_1 V1 JOIN \" + TBL2 + \" T2 ON (V1.B = T2.B)\");\n Assert.fail(\"Expected SQL exception\");\n } catch (SQLException e) {\n context.verifyAuthzException(e);\n }\n\n statement.close();\n connection.close();\n }\n\n /*\n * Admin creates database DB_1, table TBL1, TBL2 in DB_1, VIEW_1 on TBL1\n * loads data into TBL1, TBL2. Admin grants SELECT on TBL2 to USER_GROUP of\n * which user1 is a member.\n */\n @Test\n public void testTableViewJoin2() throws Exception {\n policyFile\n .addRolesToGroup(USERGROUP1, \"select_tab2\")\n .addPermissionsToRole(\"select_tab1\", \"server=server1->db=DB_1->table=\" + TBL1 + \"->action=select\")\n .addPermissionsToRole(\"select_tab2\", \"server=server1->db=DB_1->table=\" + TBL2 + \"->action=select\")\n .setUserGroupMapping(StaticUserGroup.getStaticMapping());\n writePolicyFile(policyFile);\n\n // test execution\n Connection connection = context.createConnection(USER1_1);\n Statement statement = context.createStatement(connection);\n statement.execute(\"USE \" + DB1);\n // test user can execute query on TBL2\n statement.executeQuery(\"SELECT A FROM \" + TBL2);\n\n // negative test: test user can't execute query VIEW_1 JOIN TBL2\n try {\n statement.executeQuery(\"SELECT VIEW_1.B FROM VIEW_1 JOIN \" + TBL2 + \" ON (VIEW_1.B = \" + TBL2 + \".B)\");\n Assert.fail(\"Expected SQL exception\");\n } catch (SQLException e) {\n context.verifyAuthzException(e);\n }\n\n // negative test: test user can't execute query TBL1 JOIN TBL2\n try {\n statement.executeQuery(\"SELECT \" + TBL1 + \".B FROM \" + TBL1 + \" JOIN \" + TBL2 + \" ON (\" + TBL1 + \".B = \" + TBL2 + \".B)\");\n Assert.fail(\"Expected SQL exception\");\n } catch (SQLException e) {\n context.verifyAuthzException(e);\n }\n\n statement.close();", "answers": [" connection.close();"], "length": 1359, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "35c45a59-ce21-44f5-b554-92401decd0ac", "reasoning": "The method testTableViewJoin2 opens a Connection and a Statement, uses them, then calls statement.close(); The usual pattern in the file is to also close the Connection before ending the method, as seen in other test methods. Therefore the next line should be connection.close();", "reasoning_model_answer": "connection.close();", "assistant_with_reasoning": "\nThe method testTableViewJoin2 opens a Connection and a Statement, uses them, then calls statement.close(); The usual pattern in the file is to also close the Connection before ending the method, as seen in other test methods. Therefore the next line should be connection.close();\n\nconnection.close();", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 2.456, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 12808, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "connection.close();", "score": 0.9, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/*\n * CombineGenotypeTable\n */\npackage net.maizegenetics.dna.snp;\n\nimport net.maizegenetics.dna.snp.bit.BitStorage;\nimport net.maizegenetics.dna.snp.depth.AlleleDepth;\nimport net.maizegenetics.dna.snp.genotypecall.GenotypeCallTable;\nimport net.maizegenetics.dna.map.Chromosome;\nimport net.maizegenetics.dna.map.PositionList;\nimport net.maizegenetics.taxa.TaxaList;\nimport net.maizegenetics.taxa.TaxaListUtils;\nimport net.maizegenetics.util.BitSet;\n\nimport java.util.*;\n\n/**\n * Combines multiple GenotypeTables together.\n * \n * @author Terry Casstevens\n */\npublic class CombineGenotypeTable implements GenotypeTable {\n\n private static final long serialVersionUID = -5197800047652332969L;\n private final GenotypeTable[] myAlignments;\n private final int[] mySiteOffsets;\n private final Map myChromosomes = new HashMap<>();\n private Chromosome[] myChromosomesList;\n private int[] myChromosomesOffsets;\n private final TaxaList myTaxaList;\n private String[][] myAlleleStates;\n\n private CombineGenotypeTable(TaxaList taxaList, GenotypeTable[] genoTables) {\n\n myTaxaList = taxaList;\n myAlignments = genoTables;\n mySiteOffsets = new int[genoTables.length + 1];\n\n mySiteOffsets[0] = 0;\n int count = 0;\n for (int i = 0; i < genoTables.length; i++) {\n count = genoTables[i].numberOfSites() + count;\n mySiteOffsets[i + 1] = count;\n\n Chromosome[] chromosomes = genoTables[i].chromosomes();\n for (int j = 0; j < chromosomes.length; j++) {\n myChromosomes.put(chromosomes[j], genoTables[i]);\n }\n }\n\n initChromosomes();\n }\n\n /**\n * This factory method combines given genoTables. If only one genotypeTable,\n * then it is returned unchanged. Otherwise, this requires that each\n * genotypeTable has the same Taxa in the same order.\n *\n * @param genoTables\n * @return\n */\n public static GenotypeTable getInstance(GenotypeTable[] genoTables) {\n\n if ((genoTables == null) || (genoTables.length == 0)) {\n throw new IllegalArgumentException(\"CombineAlignment: getInstance: must provide genoTables.\");\n }\n\n if (genoTables.length == 1) {\n return genoTables[0];\n }\n\n TaxaList firstGroup = genoTables[0].taxa();\n for (int i = 1; i < genoTables.length; i++) {\n if (!areTaxaListsEqual(firstGroup, genoTables[i].taxa())) {\n throw new IllegalArgumentException(\"CombineAlignment: getInstance: TaxaLists do not match.\");\n }\n }\n\n return new CombineGenotypeTable(firstGroup, genoTables);\n\n }\n\n /**\n * This factory method combines given genoTables. If only one genotypeTable,\n * then it is returned unchanged. If isUnion equals true, a union join of\n * the Identifiers will be used to construct the combination. Any genotypeTable\n * not containing one of the Identifiers will return unknown value for those\n * locations. If isUnion equals false, a intersect join of the Identifiers\n * will be used.\n *\n * @param genoTables genoTables to combine\n * @param isUnion whether to union or intersect join\n * @return\n */\n public static GenotypeTable getInstance(GenotypeTable[] genoTables, boolean isUnion) {\n\n if ((genoTables == null) || (genoTables.length == 0)) {\n throw new IllegalArgumentException(\"CombineAlignment: getInstance: must provide genoTables.\");\n }\n\n if (genoTables.length == 1) {\n return genoTables[0];\n }\n\n TaxaList[] groups = new TaxaList[genoTables.length];\n for (int i = 0; i < genoTables.length; i++) {\n groups[i] = genoTables[i].taxa();\n }\n TaxaList newTaxa = null;\n if (isUnion) {\n newTaxa = TaxaListUtils.getAllTaxa(groups);\n } else {\n newTaxa = TaxaListUtils.getCommonTaxa(groups);\n }\n\n GenotypeTable[] newAlignmentNews = new GenotypeTable[genoTables.length];\n for (int i = 0; i < genoTables.length; i++) {\n newAlignmentNews[i] = FilterGenotypeTable.getInstance(genoTables[i], newTaxa);\n }\n\n return new CombineGenotypeTable(newTaxa, newAlignmentNews);\n\n }\n\n private static boolean areTaxaListsEqual(TaxaList first, TaxaList second) {\n\n if (first.numberOfTaxa() != second.numberOfTaxa()) {\n return false;\n }\n\n for (int i = 0, n = first.numberOfTaxa(); i < n; i++) {\n if (!first.get(i).equals(second.get(i))) {\n return false;\n }\n }\n\n return true;\n\n }\n\n private void initChromosomes() {\n\n List offsets = new ArrayList<>();\n List chromosomes = new ArrayList<>();\n for (int i = 0; i < myAlignments.length; i++) {\n chromosomes.addAll(Arrays.asList(myAlignments[i].chromosomes()));\n int[] tempOffsets = myAlignments[i].chromosomesOffsets();\n for (int j = 0; j < tempOffsets.length; j++) {\n offsets.add(tempOffsets[j] + mySiteOffsets[i]);\n }\n }\n\n myChromosomesList = new Chromosome[chromosomes.size()];\n myChromosomesList = chromosomes.toArray(myChromosomesList);\n\n myChromosomesOffsets = new int[offsets.size()];\n for (int i = 0; i < offsets.size(); i++) {\n myChromosomesOffsets[i] = (Integer) offsets.get(i);\n }\n\n if (myChromosomesOffsets.length != myChromosomesList.length) {\n throw new IllegalStateException(\"CombineAlignment: initChromosomes: number chromosomes offsets should equal number of chromosomes.\");\n }\n\n }\n\n public byte genotype(int taxon, int site) {\n int translate = translateSite(site);\n return myAlignments[translate].genotype(taxon, site - mySiteOffsets[translate]);\n }\n\n @Override\n public byte[] genotypeRange(int taxon, int startSite, int endSite) {\n\n byte[] result = new byte[endSite - startSite];\n int count = 0;\n int firstAlign = translateSite(startSite);\n int secondAlign = translateSite(endSite);\n for (int i = firstAlign; i <= secondAlign; i++) {\n int firstSite = 0;\n if (i == firstAlign) {\n firstSite = startSite - mySiteOffsets[firstAlign];\n }\n int secondSite = 0;\n if (firstAlign == secondAlign) {\n secondSite = endSite - mySiteOffsets[firstAlign];\n } else if (i != secondAlign) {\n secondSite = myAlignments[i].numberOfSites();\n } else {\n secondSite = endSite - mySiteOffsets[secondAlign];\n }\n for (int s = firstSite; s < secondSite; s++) {\n result[count++] = myAlignments[i].genotype(taxon, s);\n }\n }\n return result;\n\n }\n\n @Override\n public byte genotype(int taxon, Chromosome locus, int physicalPosition) {\n int site = siteOfPhysicalPosition(physicalPosition, locus);\n int translate = translateSite(site);\n return myAlignments[translate].genotype(taxon, site - mySiteOffsets[translate]);\n }\n\n /**\n * Returns which genotypeTable to use.\n *\n * @param site\n * @return genotypeTable index.\n */\n public int translateSite(int site) {\n\n for (int i = 1; i < mySiteOffsets.length; i++) {\n if (mySiteOffsets[i] > site) {\n return i - 1;\n }\n }\n throw new IndexOutOfBoundsException(\"CombineAlignment: translateSite: index out of range: \" + site);\n\n }\n\n @Override\n public boolean hasReference() {\n\n for (int i = 0; i < myAlignments.length; i++) {\n if (!myAlignments[i].hasReference()) {\n return false;\n }\n }\n\n return true;\n }\n\n @Override\n public String siteName(int site) {\n int translate = translateSite(site);\n return myAlignments[translate].siteName(site - mySiteOffsets[translate]);\n }\n\n @Override\n public int numberOfSites() {\n return mySiteOffsets[mySiteOffsets.length - 1];\n }\n\n @Override\n public int chromosomeSiteCount(Chromosome locus) {\n return ((GenotypeTable) myChromosomes.get(locus)).chromosomeSiteCount(locus);\n }\n\n @Override\n public int chromosomalPosition(int site) {\n int translate = translateSite(site);\n return myAlignments[translate].chromosomalPosition(site - mySiteOffsets[translate]);\n }\n\n @Override\n public int siteOfPhysicalPosition(int physicalPosition, Chromosome locus) {\n GenotypeTable align = ((GenotypeTable) myChromosomes.get(locus));\n int i = -1;\n for (int j = 0; j < myAlignments.length; j++) {\n if (myAlignments[j] == align) {\n i = j;\n break;\n }\n }\n if (i == -1) {\n return -1;\n }\n return mySiteOffsets[i] + align.siteOfPhysicalPosition(physicalPosition, locus);\n }\n\n @Override\n public int siteOfPhysicalPosition(int physicalPosition, Chromosome locus, String snpName) {\n GenotypeTable align = ((GenotypeTable) myChromosomes.get(locus));\n int i = -1;\n for (int j = 0; j < myAlignments.length; j++) {\n if (myAlignments[j] == align) {\n i = j;\n break;\n }\n }\n if (i == -1) {\n return -1;\n }\n return mySiteOffsets[i] + align.siteOfPhysicalPosition(physicalPosition, locus, snpName);\n }\n\n @Override\n public Chromosome chromosome(int site) {\n int translate = translateSite(site);\n return myAlignments[translate].chromosome(site - mySiteOffsets[translate]);\n }\n\n @Override\n public Chromosome[] chromosomes() {\n return myChromosomesList;\n }\n\n @Override\n public int numChromosomes() {\n if (myChromosomesList == null) {\n return 0;\n } else {\n return myChromosomesList.length;\n }\n }\n\n @Override\n public float[][] siteScores() {\n\n if (!hasSiteScores()) {\n return null;\n }\n\n int numSeqs = numberOfTaxa();\n float[][] result = new float[numSeqs][numberOfSites()];\n for (int a = 0, n = myAlignments.length; a < n; a++) {\n if (myAlignments[a].hasSiteScores()) {\n for (int s = 0, m = myAlignments[a].numberOfSites(); s < m; s++) {\n for (int t = 0; t < numSeqs; t++) {\n result[t][mySiteOffsets[a] + s] = myAlignments[a].siteScore(t, s);\n }\n }\n }\n }\n\n return result;\n\n }\n\n @Override\n public float siteScore(int taxon, int site) {\n int translate = translateSite(site);\n return myAlignments[translate].siteScore(taxon, site - mySiteOffsets[translate]);\n }\n\n @Override\n public boolean hasSiteScores() {\n for (GenotypeTable align : myAlignments) {\n if (align.hasSiteScores()) {\n return true;\n }\n }\n return false;\n }\n\n @Override\n public int indelSize(int site) {\n int translate = translateSite(site);\n return myAlignments[translate].indelSize(site - mySiteOffsets[translate]);\n }\n\n @Override\n public boolean isIndel(int site) {\n int translate = translateSite(site);\n return myAlignments[translate].isIndel(site - mySiteOffsets[translate]);\n }\n\n @Override\n public byte referenceAllele(int site) {\n int translate = translateSite(site);\n return myAlignments[translate].referenceAllele(site - mySiteOffsets[translate]);\n }\n\n @Override\n public GenotypeTable[] compositeAlignments() {\n return myAlignments;\n }\n\n @Override\n public byte majorAllele(int site) {\n int translate = translateSite(site);\n return myAlignments[translate].majorAllele(site - mySiteOffsets[translate]);\n }\n\n @Override\n public byte minorAllele(int site) {\n int translate = translateSite(site);\n return myAlignments[translate].minorAllele(site - mySiteOffsets[translate]);\n }\n\n @Override\n public byte[] minorAlleles(int site) {\n int translate = translateSite(site);\n return myAlignments[translate].minorAlleles(site - mySiteOffsets[translate]);\n }\n\n @Override\n public byte[] alleles(int site) {\n int translate = translateSite(site);\n return myAlignments[translate].alleles(site - mySiteOffsets[translate]);\n }\n\n @Override\n public double minorAlleleFrequency(int site) {\n int translate = translateSite(site);\n return myAlignments[translate].minorAlleleFrequency(site - mySiteOffsets[translate]);\n }\n\n @Override\n public int[][] allelesSortedByFrequency(int site) {\n int translate = translateSite(site);\n return myAlignments[translate].allelesSortedByFrequency(site - mySiteOffsets[translate]);\n }\n\n @Override\n public byte[] genotypeArray(int taxon, int site) {\n int translate = translateSite(site);\n return myAlignments[translate].genotypeArray(taxon, site - mySiteOffsets[translate]);\n }\n\n @Override\n public byte[] genotypeAllTaxa(int site) {\n byte[] result = new byte[numberOfTaxa()];\n int offset=0;\n for (int i = 0; i < myAlignments.length; i++) {\n byte[] current = myAlignments[i].genotypeAllTaxa(site);\n System.arraycopy(current, 0, result, offset, current.length);\n offset+=current.length;\n }\n return result;\n }\n\n @Override\n public byte[] genotypeAllSites(int taxon) {\n byte[] result = new byte[numberOfSites()];\n for (int i = 0; i < myAlignments.length; i++) {\n byte[] current = myAlignments[i].genotypeAllSites(taxon);\n System.arraycopy(current, 0, result, myChromosomesOffsets[i], current.length);\n }\n return result;\n }\n\n @Override\n public BitSet allelePresenceForAllSites(int taxon, WHICH_ALLELE allele) {\n throw new UnsupportedOperationException(\"CombineAlignment: getAllelePresenceForAllSites: This operation isn't possible as it spans multiple GenotypeTables.\");\n }\n\n @Override\n public long[] allelePresenceForSitesBlock(int taxon, WHICH_ALLELE allele, int startBlock, int endBlock) {\n throw new UnsupportedOperationException(\"CombineAlignment: getAllelePresenceForSitesBlock: This operation isn't possible as it spans multiple GenotypeTables.\");\n }\n\n @Override\n public String genotypeAsString(int taxon, int site) {\n int translate = translateSite(site);\n return myAlignments[translate].genotypeAsString(taxon, site - mySiteOffsets[translate]);\n }\n\n @Override\n public String[] genotypeAsStringArray(int taxon, int site) {\n int translate = translateSite(site);\n return myAlignments[translate].genotypeAsStringArray(taxon, site - mySiteOffsets[translate]);\n }\n\n @Override\n public byte[] referenceAlleles(int startSite, int endSite) {\n int numSites = endSite - startSite;\n byte[] result = new byte[numSites];\n for (int i = 0; i < numSites; i++) {\n result[i] = referenceAllele(startSite + i);\n }\n return result;\n }\n\n @Override\n public byte[] referenceAlleleForAllSites() {\n\n for (int i = 0; i < myAlignments.length; i++) {\n if (!myAlignments[i].hasReference()) {\n return null;\n }\n }\n\n byte[] result = new byte[numberOfSites()];\n int count = 0;\n for (int i = 0; i < myAlignments.length; i++) {\n byte[] current = myAlignments[i].referenceAlleleForAllSites();\n for (int j = 0; j < current.length; j++) {\n result[count++] = current[j];\n }\n }\n return result;\n\n }\n\n @Override\n public boolean isHeterozygous(int taxon, int site) {\n int translate = translateSite(site);\n return myAlignments[translate].isHeterozygous(taxon, site - mySiteOffsets[translate]);\n }\n\n @Override\n public int[] physicalPositions() {\n\n boolean allNull = true;\n for (int i = 0; i < myAlignments.length; i++) {\n int[] current = myAlignments[0].physicalPositions();\n if ((current != null) && (current.length != 0)) {\n allNull = false;\n break;\n }\n }\n\n if (allNull) {\n return null;\n } else {\n int[] result = new int[numberOfSites()];\n int count = 0;\n for (int i = 0; i < myAlignments.length; i++) {\n int[] current = myAlignments[i].physicalPositions();\n for (int j = 0; j < current.length; j++) {\n result[count++] = current[j];\n }\n }\n return result;\n }\n }\n\n @Override\n public String chromosomeName(int site) {\n int translate = translateSite(site);\n return myAlignments[translate].chromosomeName(site - mySiteOffsets[translate]);\n }\n\n @Override\n public int[] chromosomesOffsets() {\n return myChromosomesOffsets;\n }\n\n @Override\n public SITE_SCORE_TYPE siteScoreType() {\n SITE_SCORE_TYPE first = myAlignments[0].siteScoreType();\n for (int i = 1; i < myAlignments.length; i++) {\n if (first != myAlignments[i].siteScoreType()) {\n return SITE_SCORE_TYPE.MixedScoreTypes;\n }\n }\n return first;\n }\n\n @Override\n public boolean isAllPolymorphic() {\n for (int i = 0; i < myAlignments.length; i++) {\n if (!myAlignments[i].isAllPolymorphic()) {\n return false;\n }\n }\n return true;\n }\n\n @Override\n public boolean isPolymorphic(int site) {\n int translate = translateSite(site);\n return myAlignments[translate].isPolymorphic(site - mySiteOffsets[translate]);\n }\n\n @Override\n public double majorAlleleFrequency(int site) {\n int translate = translateSite(site);\n return myAlignments[translate].majorAlleleFrequency(site - mySiteOffsets[translate]);\n }\n\n @Override\n public String genomeVersion() {\n String first = myAlignments[0].genomeVersion();\n if (first == null) {\n return null;\n }\n for (int i = 1; i < myAlignments.length; i++) {\n String current = myAlignments[i].genomeVersion();\n if ((current != null) && (!first.equals(current))) {\n return null;\n }\n }\n return first;\n }\n\n @Override\n public boolean isPositiveStrand(int site) {\n int translate = translateSite(site);\n return myAlignments[translate].isPositiveStrand(site - mySiteOffsets[translate]);\n }\n\n @Override\n public boolean isPhased() {\n for (int i = 0; i < myAlignments.length; i++) {\n if (myAlignments[i].isPhased() == false) {\n return false;\n }\n }\n return true;\n }\n\n @Override\n public boolean retainsRareAlleles() {\n for (int i = 0; i < myAlignments.length; i++) {\n if (myAlignments[i].retainsRareAlleles() == false) {\n return false;\n }\n }\n return true;\n }\n\n @Override\n public String[][] alleleDefinitions() {\n\n if (myAlleleStates != null) {\n return myAlleleStates;\n }\n\n boolean allTheSame = true;\n String[][] encodings = myAlignments[0].alleleDefinitions();\n if (encodings.length == 1) {\n for (int i = 1; i < myAlignments.length; i++) {\n String[][] current = myAlignments[i].alleleDefinitions();\n if ((current.length == 1) && (encodings[0].length == current[0].length)) {\n for (int j = 0; j < encodings[0].length; j++) {\n if (!current[0][j].equals(encodings[0][j])) {\n allTheSame = false;\n break;\n }\n }\n } else {\n allTheSame = false;\n break;\n }\n\n if (!allTheSame) {\n break;\n }\n }\n } else {\n allTheSame = false;\n }\n\n if (allTheSame) {\n myAlleleStates = encodings;\n } else {\n String[][] result = new String[numberOfSites()][];\n int count = 0;\n for (int i = 0; i < myAlignments.length; i++) {\n for (int j = 0, n = myAlignments[i].numberOfSites(); j < n; j++) {\n result[count++] = myAlignments[i].alleleDefinitions(j);\n }\n }\n myAlleleStates = result;\n }\n\n return myAlleleStates;\n\n }\n\n @Override\n public String[] alleleDefinitions(int site) {\n int translate = translateSite(site);\n return myAlignments[translate].alleleDefinitions(site - mySiteOffsets[translate]);\n }\n\n @Override\n public String genotypeAsString(int site, byte value) {\n int translate = translateSite(site);\n return myAlignments[translate].genotypeAsString(site - mySiteOffsets[translate], value);\n }\n\n @Override\n public int maxNumAlleles() {\n int result = 999999;\n for (int i = 0; i < myAlignments.length; i++) {\n if (myAlignments[i].maxNumAlleles() < result) {\n result = myAlignments[i].maxNumAlleles();\n }\n }\n return result;\n }\n\n @Override\n public int totalGametesNonMissingForSite(int site) {\n int translate = translateSite(site);", "answers": [" return myAlignments[translate].totalGametesNonMissingForSite(site - mySiteOffsets[translate]);"], "length": 2060, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "a8689b9f-1f5e-44f1-a204-8d136b201ea2", "reasoning": "The method totalGametesNonMissingForSite should delegate to the appropriate underlying GenotypeTable after translating the site index. Following the pattern of other delegated methods, after computing 'translate', we return the result from myAlignments[translate] with the site offset subtracted.", "reasoning_model_answer": "return myAlignments[translate].totalGametesNonMissingForSite(site - mySiteOffsets[translate]);", "assistant_with_reasoning": "\nThe method totalGametesNonMissingForSite should delegate to the appropriate underlying GenotypeTable after translating the site index. Following the pattern of other delegated methods, after computing 'translate', we return the result from myAlignments[translate] with the site offset subtracted.\n\nreturn myAlignments[translate].totalGametesNonMissingForSite(site - mySiteOffsets[translate]);", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 2.94, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 21910, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "return myAlignments[translate].totalGametesNonMissingForSite(site - mySiteOffsets[translate]);", "score": 0.96, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "package org.fluentjava.joulu.unsignedbyte;\n\npublic class UnsignedByte {\n\n\tprivate static final UnsignedByte[] values = new UnsignedByte[256];\n\tprivate final int value;\n\tprivate final String toString;\n\n\tstatic {\n\t\tfor (int i = 0; i < 256; i++) {\n\t\t\tvalues[i] = new UnsignedByte(i,\n\t\t\t\t\t\"#$\" + ByteArrayPrettyPrinter.spaceSeparatedHex((byte) i));\n\t\t}\n\t}\n\n\tpublic static final UnsignedByte x00 = UnsignedByte.from(0);\n\tpublic static final UnsignedByte x01 = UnsignedByte.from(1);\n\tpublic static final UnsignedByte x02 = UnsignedByte.from(2);\n\tpublic static final UnsignedByte x03 = UnsignedByte.from(3);\n\tpublic static final UnsignedByte x04 = UnsignedByte.from(4);\n\tpublic static final UnsignedByte x05 = UnsignedByte.from(5);\n\tpublic static final UnsignedByte x06 = UnsignedByte.from(6);\n\tpublic static final UnsignedByte x07 = UnsignedByte.from(7);\n\tpublic static final UnsignedByte x08 = UnsignedByte.from(8);\n\tpublic static final UnsignedByte x09 = UnsignedByte.from(9);\n\tpublic static final UnsignedByte x0A = UnsignedByte.from(10);\n\tpublic static final UnsignedByte x0B = UnsignedByte.from(11);\n\tpublic static final UnsignedByte x0C = UnsignedByte.from(12);\n\tpublic static final UnsignedByte x0D = UnsignedByte.from(13);\n\tpublic static final UnsignedByte x0E = UnsignedByte.from(14);\n\tpublic static final UnsignedByte x0F = UnsignedByte.from(15);\n\tpublic static final UnsignedByte x10 = UnsignedByte.from(16);\n\tpublic static final UnsignedByte x11 = UnsignedByte.from(17);\n\tpublic static final UnsignedByte x12 = UnsignedByte.from(18);\n\tpublic static final UnsignedByte x13 = UnsignedByte.from(19);\n\tpublic static final UnsignedByte x14 = UnsignedByte.from(20);\n\tpublic static final UnsignedByte x15 = UnsignedByte.from(21);\n\tpublic static final UnsignedByte x16 = UnsignedByte.from(22);\n\tpublic static final UnsignedByte x17 = UnsignedByte.from(23);\n\tpublic static final UnsignedByte x18 = UnsignedByte.from(24);\n\tpublic static final UnsignedByte x19 = UnsignedByte.from(25);\n\tpublic static final UnsignedByte x1A = UnsignedByte.from(26);\n\tpublic static final UnsignedByte x1B = UnsignedByte.from(27);\n\tpublic static final UnsignedByte x1C = UnsignedByte.from(28);\n\tpublic static final UnsignedByte x1D = UnsignedByte.from(29);\n\tpublic static final UnsignedByte x1E = UnsignedByte.from(30);\n\tpublic static final UnsignedByte x1F = UnsignedByte.from(31);\n\tpublic static final UnsignedByte x20 = UnsignedByte.from(32);\n\tpublic static final UnsignedByte x21 = UnsignedByte.from(33);\n\tpublic static final UnsignedByte x22 = UnsignedByte.from(34);\n\tpublic static final UnsignedByte x23 = UnsignedByte.from(35);\n\tpublic static final UnsignedByte x24 = UnsignedByte.from(36);\n\tpublic static final UnsignedByte x25 = UnsignedByte.from(37);\n\tpublic static final UnsignedByte x26 = UnsignedByte.from(38);\n\tpublic static final UnsignedByte x27 = UnsignedByte.from(39);\n\tpublic static final UnsignedByte x28 = UnsignedByte.from(40);\n\tpublic static final UnsignedByte x29 = UnsignedByte.from(41);\n\tpublic static final UnsignedByte x2A = UnsignedByte.from(42);\n\tpublic static final UnsignedByte x2B = UnsignedByte.from(43);\n\tpublic static final UnsignedByte x2C = UnsignedByte.from(44);\n\tpublic static final UnsignedByte x2D = UnsignedByte.from(45);\n\tpublic static final UnsignedByte x2E = UnsignedByte.from(46);\n\tpublic static final UnsignedByte x2F = UnsignedByte.from(47);\n\tpublic static final UnsignedByte x30 = UnsignedByte.from(48);\n\tpublic static final UnsignedByte x31 = UnsignedByte.from(49);\n\tpublic static final UnsignedByte x32 = UnsignedByte.from(50);\n\tpublic static final UnsignedByte x33 = UnsignedByte.from(51);\n\tpublic static final UnsignedByte x34 = UnsignedByte.from(52);\n\tpublic static final UnsignedByte x35 = UnsignedByte.from(53);\n\tpublic static final UnsignedByte x36 = UnsignedByte.from(54);\n\tpublic static final UnsignedByte x37 = UnsignedByte.from(55);\n\tpublic static final UnsignedByte x38 = UnsignedByte.from(56);\n\tpublic static final UnsignedByte x39 = UnsignedByte.from(57);\n\tpublic static final UnsignedByte x3A = UnsignedByte.from(58);\n\tpublic static final UnsignedByte x3B = UnsignedByte.from(59);\n\tpublic static final UnsignedByte x3C = UnsignedByte.from(60);\n\tpublic static final UnsignedByte x3D = UnsignedByte.from(61);\n\tpublic static final UnsignedByte x3E = UnsignedByte.from(62);\n\tpublic static final UnsignedByte x3F = UnsignedByte.from(63);\n\tpublic static final UnsignedByte x40 = UnsignedByte.from(64);\n\tpublic static final UnsignedByte x41 = UnsignedByte.from(65);\n\tpublic static final UnsignedByte x42 = UnsignedByte.from(66);\n\tpublic static final UnsignedByte x43 = UnsignedByte.from(67);\n\tpublic static final UnsignedByte x44 = UnsignedByte.from(68);\n\tpublic static final UnsignedByte x45 = UnsignedByte.from(69);\n\tpublic static final UnsignedByte x46 = UnsignedByte.from(70);\n\tpublic static final UnsignedByte x47 = UnsignedByte.from(71);\n\tpublic static final UnsignedByte x48 = UnsignedByte.from(72);\n\tpublic static final UnsignedByte x49 = UnsignedByte.from(73);\n\tpublic static final UnsignedByte x4A = UnsignedByte.from(74);\n\tpublic static final UnsignedByte x4B = UnsignedByte.from(75);\n\tpublic static final UnsignedByte x4C = UnsignedByte.from(76);\n\tpublic static final UnsignedByte x4D = UnsignedByte.from(77);\n\tpublic static final UnsignedByte x4E = UnsignedByte.from(78);\n\tpublic static final UnsignedByte x4F = UnsignedByte.from(79);\n\tpublic static final UnsignedByte x50 = UnsignedByte.from(80);\n\tpublic static final UnsignedByte x51 = UnsignedByte.from(81);\n\tpublic static final UnsignedByte x52 = UnsignedByte.from(82);\n\tpublic static final UnsignedByte x53 = UnsignedByte.from(83);\n\tpublic static final UnsignedByte x54 = UnsignedByte.from(84);\n\tpublic static final UnsignedByte x55 = UnsignedByte.from(85);\n\tpublic static final UnsignedByte x56 = UnsignedByte.from(86);\n\tpublic static final UnsignedByte x57 = UnsignedByte.from(87);\n\tpublic static final UnsignedByte x58 = UnsignedByte.from(88);\n\tpublic static final UnsignedByte x59 = UnsignedByte.from(89);\n\tpublic static final UnsignedByte x5A = UnsignedByte.from(90);\n\tpublic static final UnsignedByte x5B = UnsignedByte.from(91);\n\tpublic static final UnsignedByte x5C = UnsignedByte.from(92);\n\tpublic static final UnsignedByte x5D = UnsignedByte.from(93);\n\tpublic static final UnsignedByte x5E = UnsignedByte.from(94);\n\tpublic static final UnsignedByte x5F = UnsignedByte.from(95);\n\tpublic static final UnsignedByte x60 = UnsignedByte.from(96);\n\tpublic static final UnsignedByte x61 = UnsignedByte.from(97);\n\tpublic static final UnsignedByte x62 = UnsignedByte.from(98);\n\tpublic static final UnsignedByte x63 = UnsignedByte.from(99);\n\tpublic static final UnsignedByte x64 = UnsignedByte.from(100);\n\tpublic static final UnsignedByte x65 = UnsignedByte.from(101);\n\tpublic static final UnsignedByte x66 = UnsignedByte.from(102);\n\tpublic static final UnsignedByte x67 = UnsignedByte.from(103);\n\tpublic static final UnsignedByte x68 = UnsignedByte.from(104);\n\tpublic static final UnsignedByte x69 = UnsignedByte.from(105);\n\tpublic static final UnsignedByte x6A = UnsignedByte.from(106);\n\tpublic static final UnsignedByte x6B = UnsignedByte.from(107);\n\tpublic static final UnsignedByte x6C = UnsignedByte.from(108);\n\tpublic static final UnsignedByte x6D = UnsignedByte.from(109);\n\tpublic static final UnsignedByte x6E = UnsignedByte.from(110);\n\tpublic static final UnsignedByte x6F = UnsignedByte.from(111);\n\tpublic static final UnsignedByte x70 = UnsignedByte.from(112);\n\tpublic static final UnsignedByte x71 = UnsignedByte.from(113);\n\tpublic static final UnsignedByte x72 = UnsignedByte.from(114);\n\tpublic static final UnsignedByte x73 = UnsignedByte.from(115);\n\tpublic static final UnsignedByte x74 = UnsignedByte.from(116);\n\tpublic static final UnsignedByte x75 = UnsignedByte.from(117);\n\tpublic static final UnsignedByte x76 = UnsignedByte.from(118);\n\tpublic static final UnsignedByte x77 = UnsignedByte.from(119);\n\tpublic static final UnsignedByte x78 = UnsignedByte.from(120);\n\tpublic static final UnsignedByte x79 = UnsignedByte.from(121);\n\tpublic static final UnsignedByte x7A = UnsignedByte.from(122);\n\tpublic static final UnsignedByte x7B = UnsignedByte.from(123);\n\tpublic static final UnsignedByte x7C = UnsignedByte.from(124);\n\tpublic static final UnsignedByte x7D = UnsignedByte.from(125);\n\tpublic static final UnsignedByte x7E = UnsignedByte.from(126);\n\tpublic static final UnsignedByte x7F = UnsignedByte.from(127);\n\tpublic static final UnsignedByte x80 = UnsignedByte.from(128);\n\tpublic static final UnsignedByte x81 = UnsignedByte.from(129);\n\tpublic static final UnsignedByte x82 = UnsignedByte.from(130);\n\tpublic static final UnsignedByte x83 = UnsignedByte.from(131);\n\tpublic static final UnsignedByte x84 = UnsignedByte.from(132);\n\tpublic static final UnsignedByte x85 = UnsignedByte.from(133);\n\tpublic static final UnsignedByte x86 = UnsignedByte.from(134);\n\tpublic static final UnsignedByte x87 = UnsignedByte.from(135);\n\tpublic static final UnsignedByte x88 = UnsignedByte.from(136);\n\tpublic static final UnsignedByte x89 = UnsignedByte.from(137);\n\tpublic static final UnsignedByte x8A = UnsignedByte.from(138);\n\tpublic static final UnsignedByte x8B = UnsignedByte.from(139);\n\tpublic static final UnsignedByte x8C = UnsignedByte.from(140);\n\tpublic static final UnsignedByte x8D = UnsignedByte.from(141);\n\tpublic static final UnsignedByte x8E = UnsignedByte.from(142);\n\tpublic static final UnsignedByte x8F = UnsignedByte.from(143);\n\tpublic static final UnsignedByte x90 = UnsignedByte.from(144);\n\tpublic static final UnsignedByte x91 = UnsignedByte.from(145);\n\tpublic static final UnsignedByte x92 = UnsignedByte.from(146);\n\tpublic static final UnsignedByte x93 = UnsignedByte.from(147);\n\tpublic static final UnsignedByte x94 = UnsignedByte.from(148);\n\tpublic static final UnsignedByte x95 = UnsignedByte.from(149);\n\tpublic static final UnsignedByte x96 = UnsignedByte.from(150);\n\tpublic static final UnsignedByte x97 = UnsignedByte.from(151);\n\tpublic static final UnsignedByte x98 = UnsignedByte.from(152);\n\tpublic static final UnsignedByte x99 = UnsignedByte.from(153);\n\tpublic static final UnsignedByte x9A = UnsignedByte.from(154);\n\tpublic static final UnsignedByte x9B = UnsignedByte.from(155);\n\tpublic static final UnsignedByte x9C = UnsignedByte.from(156);\n\tpublic static final UnsignedByte x9D = UnsignedByte.from(157);\n\tpublic static final UnsignedByte x9E = UnsignedByte.from(158);\n\tpublic static final UnsignedByte x9F = UnsignedByte.from(159);\n\tpublic static final UnsignedByte xA0 = UnsignedByte.from(160);\n\tpublic static final UnsignedByte xA1 = UnsignedByte.from(161);\n\tpublic static final UnsignedByte xA2 = UnsignedByte.from(162);\n\tpublic static final UnsignedByte xA3 = UnsignedByte.from(163);\n\tpublic static final UnsignedByte xA4 = UnsignedByte.from(164);\n\tpublic static final UnsignedByte xA5 = UnsignedByte.from(165);\n\tpublic static final UnsignedByte xA6 = UnsignedByte.from(166);\n\tpublic static final UnsignedByte xA7 = UnsignedByte.from(167);\n\tpublic static final UnsignedByte xA8 = UnsignedByte.from(168);\n\tpublic static final UnsignedByte xA9 = UnsignedByte.from(169);\n\tpublic static final UnsignedByte xAA = UnsignedByte.from(170);\n\tpublic static final UnsignedByte xAB = UnsignedByte.from(171);\n\tpublic static final UnsignedByte xAC = UnsignedByte.from(172);\n\tpublic static final UnsignedByte xAD = UnsignedByte.from(173);\n\tpublic static final UnsignedByte xAE = UnsignedByte.from(174);\n\tpublic static final UnsignedByte xAF = UnsignedByte.from(175);\n\tpublic static final UnsignedByte xB0 = UnsignedByte.from(176);\n\tpublic static final UnsignedByte xB1 = UnsignedByte.from(177);", "answers": ["\tpublic static final UnsignedByte xB2 = UnsignedByte.from(178);"], "length": 1295, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "95fc8ece-5945-4ec5-9468-bba48c590353", "reasoning": "The class defines a static final UnsignedByte constant for each byte value from 0 to 255, using the naming scheme x00, x01, ..., xFF where the suffix is the hexadecimal representation of the value. The last provided line defines xB1 for decimal 177 (0xB1). Following the sequential pattern, the next constant should represent decimal 178 (0xB2) and be named xB2.", "reasoning_model_answer": "public static final UnsignedByte xB2 = UnsignedByte.from(178);", "assistant_with_reasoning": "\nThe class defines a static final UnsignedByte constant for each byte value from 0 to 255, using the naming scheme x00, x01, ..., xFF where the suffix is the hexadecimal representation of the value. The last provided line defines xB1 for decimal 177 (0xB1). Following the sequential pattern, the next constant should represent decimal 178 (0xB2) and be named xB2.\n\npublic static final UnsignedByte xB2 = UnsignedByte.from(178);", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 2.743, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 11727, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "public static final UnsignedByte xB2 = UnsignedByte.from(178);", "score": 0.99, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.apache.ambari.server.controller.metrics;\n\nimport static org.easymock.EasyMock.anyString;\nimport static org.easymock.EasyMock.createNiceMock;\nimport static org.easymock.EasyMock.eq;\nimport static org.easymock.EasyMock.expect;\nimport static org.easymock.EasyMock.replay;\n\nimport java.lang.reflect.Field;\nimport java.sql.SQLException;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.concurrent.TimeUnit;\nimport java.util.concurrent.TimeoutException;\n\nimport org.apache.ambari.server.AmbariException;\nimport org.apache.ambari.server.H2DatabaseCleaner;\nimport org.apache.ambari.server.configuration.Configuration;\nimport org.apache.ambari.server.controller.AmbariManagementController;\nimport org.apache.ambari.server.controller.AmbariServer;\nimport org.apache.ambari.server.controller.internal.PropertyInfo;\nimport org.apache.ambari.server.controller.internal.ResourceImpl;\nimport org.apache.ambari.server.controller.internal.StackDefinedPropertyProvider;\nimport org.apache.ambari.server.controller.jmx.JMXPropertyProvider;\nimport org.apache.ambari.server.controller.jmx.TestStreamProvider;\nimport org.apache.ambari.server.controller.metrics.MetricsServiceProvider.MetricsService;\nimport org.apache.ambari.server.controller.spi.Request;\nimport org.apache.ambari.server.controller.spi.Resource;\nimport org.apache.ambari.server.controller.spi.SystemException;\nimport org.apache.ambari.server.controller.spi.TemporalInfo;\nimport org.apache.ambari.server.controller.utilities.PropertyHelper;\nimport org.apache.ambari.server.controller.utilities.StreamProvider;\nimport org.apache.ambari.server.events.publishers.AmbariEventPublisher;\nimport org.apache.ambari.server.orm.GuiceJpaInitializer;\nimport org.apache.ambari.server.orm.InMemoryDefaultTestModule;\nimport org.apache.ambari.server.orm.dao.StackDAO;\nimport org.apache.ambari.server.orm.entities.StackEntity;\nimport org.apache.ambari.server.security.TestAuthenticationFactory;\nimport org.apache.ambari.server.security.authorization.AuthorizationException;\nimport org.apache.ambari.server.state.Cluster;\nimport org.apache.ambari.server.state.Clusters;\nimport org.apache.ambari.server.state.ConfigHelper;\nimport org.apache.ambari.server.state.StackId;\nimport org.apache.ambari.server.state.services.MetricsRetrievalService;\nimport org.apache.ambari.server.state.stack.Metric;\nimport org.apache.ambari.server.state.stack.MetricDefinition;\nimport org.apache.ambari.server.utils.SynchronousThreadPoolExecutor;\nimport org.easymock.EasyMock;\nimport org.junit.After;\nimport org.junit.AfterClass;\nimport org.junit.Assert;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\nimport org.springframework.security.core.context.SecurityContextHolder;\n\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\n\n\n/**\n * Rest metrics property provider tests.\n */\npublic class RestMetricsPropertyProviderTest {\n\n public static final String WRAPPED_METRICS_KEY = \"WRAPPED_METRICS_KEY\";\n protected static final String HOST_COMPONENT_HOST_NAME_PROPERTY_ID = PropertyHelper.getPropertyId(\"HostRoles\", \"host_name\");\n protected static final String HOST_COMPONENT_COMPONENT_NAME_PROPERTY_ID = PropertyHelper.getPropertyId(\"HostRoles\", \"component_name\");\n protected static final String HOST_COMPONENT_STATE_PROPERTY_ID = PropertyHelper.getPropertyId(\"HostRoles\", \"state\");\n protected static final Map metricsProperties = new HashMap<>();\n protected static final Map componentMetrics = new HashMap<>();\n private static final String CLUSTER_NAME_PROPERTY_ID = PropertyHelper.getPropertyId(\"HostRoles\", \"cluster_name\");\n private static final String DEFAULT_STORM_UI_PORT = \"8745\";\n public static final int NUMBER_OF_RESOURCES = 400;\n private static final int METRICS_SERVICE_TIMEOUT = 10;\n private static Injector injector;\n private static Clusters clusters;\n private static Cluster c1;\n private static AmbariManagementController amc;\n private static MetricsRetrievalService metricsRetrievalService;\n\n {\n metricsProperties.put(\"default_port\", DEFAULT_STORM_UI_PORT);\n metricsProperties.put(\"port_config_type\", \"storm-site\");\n metricsProperties.put(\"port_property_name\", \"ui.port\");\n metricsProperties.put(\"protocol\", \"http\");\n componentMetrics.put(\"metrics/api/cluster/summary/tasks.total\", new Metric(\"/api/cluster/summary##tasks.total\", false, false, false, \"unitless\"));\n componentMetrics.put(\"metrics/api/cluster/summary/slots.total\", new Metric(\"/api/cluster/summary##slots.total\", false, false, false, \"unitless\"));\n componentMetrics.put(\"metrics/api/cluster/summary/slots.free\", new Metric(\"/api/cluster/summary##slots.free\", false, false, false, \"unitless\"));\n componentMetrics.put(\"metrics/api/cluster/summary/supervisors\", new Metric(\"/api/cluster/summary##supervisors\", false, false, false, \"unitless\"));\n componentMetrics.put(\"metrics/api/cluster/summary/executors.total\", new Metric(\"/api/cluster/summary##executors.total\", false, false, false, \"unitless\"));\n componentMetrics.put(\"metrics/api/cluster/summary/slots.used\", new Metric(\"/api/cluster/summary##slots.used\", false, false, false, \"unitless\"));\n componentMetrics.put(\"metrics/api/cluster/summary/topologies\", new Metric(\"/api/cluster/summary##topologies\", false, false, false, \"unitless\"));\n componentMetrics.put(\"metrics/api/cluster/summary/nimbus.uptime\", new Metric(\"/api/cluster/summary##nimbus.uptime\", false, false, false, \"unitless\"));\n componentMetrics.put(\"metrics/api/cluster/summary/wrong.metric\", new Metric(null, false, false, false, \"unitless\"));\n }\n\n\n @BeforeClass\n public static void setup() throws Exception {\n injector = Guice.createInjector(new InMemoryDefaultTestModule());\n injector.getInstance(GuiceJpaInitializer.class);\n clusters = injector.getInstance(Clusters.class);\n StackDAO stackDAO = injector.getInstance(StackDAO.class);\n\n\n StackEntity stackEntity = new StackEntity();\n stackEntity.setStackName(\"HDP\");\n stackEntity.setStackVersion(\"2.1.1\");\n stackDAO.create(stackEntity);\n\n\n clusters.addCluster(\"c1\", new StackId(\"HDP-2.1.1\"));\n c1 = clusters.getCluster(\"c1\");\n\n\n\n\n // disable request TTL for these tests\n Configuration configuration = injector.getInstance(Configuration.class);\n configuration.setProperty(Configuration.METRIC_RETRIEVAL_SERVICE_REQUEST_TTL_ENABLED.getKey(),\n \"false\");\n\n JMXPropertyProvider.init(configuration);\n\n metricsRetrievalService = injector.getInstance(\n MetricsRetrievalService.class);\n\n metricsRetrievalService.startAsync();\n metricsRetrievalService.awaitRunning(METRICS_SERVICE_TIMEOUT, TimeUnit.SECONDS);\n metricsRetrievalService.setThreadPoolExecutor(new SynchronousThreadPoolExecutor());\n\n // Setting up Mocks for Controller, Clusters etc, queried as part of user's Role context\n // while fetching Metrics.\n amc = createNiceMock(AmbariManagementController.class);\n Field field = AmbariServer.class.getDeclaredField(\"clusterController\");\n field.setAccessible(true);\n field.set(null, amc);\n\n ConfigHelper configHelperMock = createNiceMock(ConfigHelper.class);\n expect(amc.getClusters()).andReturn(clusters).anyTimes();\n expect(amc.getAmbariEventPublisher()).andReturn(createNiceMock(AmbariEventPublisher.class)).anyTimes();\n expect(amc.findConfigurationTagsWithOverrides(eq(c1), anyString())).andReturn(Collections.singletonMap(\"storm-site\",\n Collections.singletonMap(\"tag\", \"version1\"))).anyTimes();\n expect(amc.getConfigHelper()).andReturn(configHelperMock).anyTimes();\n expect(configHelperMock.getEffectiveConfigProperties(eq(c1),\n EasyMock.anyObject())).andReturn(Collections.singletonMap(\"storm-site\",\n Collections.singletonMap(\"ui.port\", DEFAULT_STORM_UI_PORT))).anyTimes();\n replay(amc, configHelperMock);\n }\n\n @AfterClass\n public static void after() throws AmbariException, SQLException, TimeoutException {\n if (metricsRetrievalService != null && metricsRetrievalService.isRunning()) {\n metricsRetrievalService.stopAsync();\n metricsRetrievalService.awaitTerminated(METRICS_SERVICE_TIMEOUT, TimeUnit.SECONDS);\n }\n H2DatabaseCleaner.clearDatabaseAndStopPersistenceService(injector);\n }\n\n private RestMetricsPropertyProvider createRestMetricsPropertyProvider(MetricDefinition metricDefinition,\n HashMap> componentMetrics, StreamProvider streamProvider,\n TestMetricsHostProvider metricsHostProvider) throws Exception {\n\n MetricPropertyProviderFactory factory = injector.getInstance(MetricPropertyProviderFactory.class);\n RestMetricsPropertyProvider restMetricsPropertyProvider = factory.createRESTMetricsPropertyProvider(\n metricDefinition.getProperties(),\n componentMetrics,\n streamProvider,\n metricsHostProvider,\n PropertyHelper.getPropertyId(\"HostRoles\", \"cluster_name\"),\n PropertyHelper.getPropertyId(\"HostRoles\", \"host_name\"),\n PropertyHelper.getPropertyId(\"HostRoles\", \"component_name\"),\n PropertyHelper.getPropertyId(\"HostRoles\", \"state\"),\n \"STORM_REST_API\"\n );\n\n Field field = RestMetricsPropertyProvider.class.getDeclaredField(\"amc\");\n field.setAccessible(true);\n field.set(restMetricsPropertyProvider, amc);\n\n return restMetricsPropertyProvider;\n }\n\n\n @After\n public void clearAuthentication() {\n SecurityContextHolder.getContext().setAuthentication(null);\n }\n\n @Test\n public void testRestMetricsPropertyProviderAsClusterAdministrator() throws Exception {\n //Setup user with Role 'ClusterAdministrator'.\n SecurityContextHolder.getContext().setAuthentication(TestAuthenticationFactory.createClusterAdministrator(\"ClusterAdmin\", 2L));\n testPopulateResources();\n testPopulateResources_singleProperty();\n testPopulateResources_category();\n testPopulateResourcesUnhealthyResource();\n testPopulateResourcesMany();\n testPopulateResourcesTimeout();\n }\n\n @Test\n public void testRestMetricsPropertyProviderAsAdministrator() throws Exception {\n //Setup user with Role 'Administrator'\n SecurityContextHolder.getContext().setAuthentication(TestAuthenticationFactory.createAdministrator(\"Admin\"));\n testPopulateResources();\n testPopulateResources_singleProperty();\n testPopulateResources_category();\n testPopulateResourcesUnhealthyResource();\n testPopulateResourcesMany();\n testPopulateResourcesTimeout();\n }\n\n @Test\n public void testRestMetricsPropertyProviderAsServiceAdministrator() throws Exception {\n //Setup user with 'ServiceAdministrator'\n SecurityContextHolder.getContext().setAuthentication(TestAuthenticationFactory.createServiceAdministrator(\"ServiceAdmin\", 2L));\n testPopulateResources();\n testPopulateResources_singleProperty();\n testPopulateResources_category();\n testPopulateResourcesUnhealthyResource();\n testPopulateResourcesMany();\n testPopulateResourcesTimeout();\n }\n\n @Test(expected = AuthorizationException.class)\n public void testRestMetricsPropertyProviderAsViewUser() throws Exception {\n // Setup user with 'ViewUser'\n // ViewUser doesn't have the 'CLUSTER_VIEW_METRICS', 'HOST_VIEW_METRICS' and 'SERVICE_VIEW_METRICS', thus\n // can't retrieve the Metrics.\n SecurityContextHolder.getContext().setAuthentication(TestAuthenticationFactory.createViewUser(\"ViewUser\", 2L));\n testPopulateResources();\n testPopulateResources_singleProperty();\n testPopulateResources_category();\n testPopulateResourcesUnhealthyResource();\n testPopulateResourcesMany();\n testPopulateResourcesTimeout();\n }\n\n @Test\n public void testResolvePort() throws Exception {\n MetricDefinition metricDefinition = createNiceMock(MetricDefinition.class);\n expect(metricDefinition.getMetrics()).andReturn(componentMetrics);\n expect(metricDefinition.getType()).andReturn(\"org.apache.ambari.server.controller.metrics.RestMetricsPropertyProvider\");\n expect(metricDefinition.getProperties()).andReturn(metricsProperties);\n replay(metricDefinition);\n\n Map metrics = StackDefinedPropertyProvider.getPropertyInfo(metricDefinition);\n HashMap> componentMetrics = new HashMap<>();\n componentMetrics.put(WRAPPED_METRICS_KEY, metrics);\n TestStreamProvider streamProvider = new TestStreamProvider();\n TestMetricsHostProvider metricsHostProvider = new TestMetricsHostProvider();\n\n RestMetricsPropertyProvider restMetricsPropertyProvider = createRestMetricsPropertyProvider(metricDefinition, componentMetrics, streamProvider,\n metricsHostProvider);\n\n // a property with a port doesn't exist, should return a default\n Map customMetricsProperties = new HashMap<>(metricsProperties);\n customMetricsProperties.put(\"port_property_name\", \"wrong_property\");\n String resolvedPort = restMetricsPropertyProvider.resolvePort(c1, \"domu-12-31-39-0e-34-e1.compute-1.internal\",\n \"STORM_REST_API\", customMetricsProperties, \"http\");\n Assert.assertEquals(DEFAULT_STORM_UI_PORT, resolvedPort);\n\n // a port property exists (8745). Should return it, not a default_port (8746)\n customMetricsProperties = new HashMap<>(metricsProperties);\n // custom default\n customMetricsProperties.put(\"default_port\", \"8746\");\n resolvedPort = restMetricsPropertyProvider.resolvePort(c1, \"domu-12-31-39-0e-34-e1.compute-1.internal\",\n \"STORM_REST_API\", customMetricsProperties, \"http\");\n Assert.assertEquals(DEFAULT_STORM_UI_PORT, resolvedPort);\n\n }\n\n public void testPopulateResources() throws Exception {\n MetricDefinition metricDefinition = createNiceMock(MetricDefinition.class);\n expect(metricDefinition.getMetrics()).andReturn(componentMetrics);\n expect(metricDefinition.getType()).andReturn(\"org.apache.ambari.server.controller.metrics.RestMetricsPropertyProvider\");\n expect(metricDefinition.getProperties()).andReturn(metricsProperties);\n replay(metricDefinition);\n\n Map metrics = StackDefinedPropertyProvider.getPropertyInfo(metricDefinition);\n HashMap> componentMetrics = new HashMap<>();\n componentMetrics.put(WRAPPED_METRICS_KEY, metrics);\n TestStreamProvider streamProvider = new TestStreamProvider();\n TestMetricsHostProvider metricsHostProvider = new TestMetricsHostProvider();\n\n RestMetricsPropertyProvider restMetricsPropertyProvider = createRestMetricsPropertyProvider(metricDefinition, componentMetrics, streamProvider,\n metricsHostProvider);\n\n Resource resource = new ResourceImpl(Resource.Type.HostComponent);\n\n resource.setProperty(\"HostRoles/cluster_name\", \"c1\");\n resource.setProperty(HOST_COMPONENT_HOST_NAME_PROPERTY_ID, \"domu-12-31-39-0e-34-e1.compute-1.internal\");\n resource.setProperty(HOST_COMPONENT_COMPONENT_NAME_PROPERTY_ID, \"STORM_REST_API\");\n resource.setProperty(HOST_COMPONENT_STATE_PROPERTY_ID, \"STARTED\");\n\n // request with an empty set should get all supported properties\n Request request = PropertyHelper.getReadRequest(Collections.emptySet());\n Assert.assertEquals(1, restMetricsPropertyProvider.populateResources(Collections.singleton(resource), request, null).size());\n Assert.assertNull(resource.getPropertyValue(PropertyHelper.getPropertyId(\"metrics/api/cluster/summary\", \"wrong.metric\")));\n\n //STORM_REST_API\n Assert.assertEquals(28.0, resource.getPropertyValue(PropertyHelper.getPropertyId(\"metrics/api/cluster/summary\", \"tasks.total\")));\n Assert.assertEquals(8.0, resource.getPropertyValue(PropertyHelper.getPropertyId(\"metrics/api/cluster/summary\", \"slots.total\")));\n Assert.assertEquals(5.0, resource.getPropertyValue(PropertyHelper.getPropertyId(\"metrics/api/cluster/summary\", \"slots.free\")));\n Assert.assertEquals(2.0, resource.getPropertyValue(PropertyHelper.getPropertyId(\"metrics/api/cluster/summary\", \"supervisors\")));\n Assert.assertEquals(28.0, resource.getPropertyValue(PropertyHelper.getPropertyId(\"metrics/api/cluster/summary\", \"executors.total\")));\n Assert.assertEquals(3.0, resource.getPropertyValue(PropertyHelper.getPropertyId(\"metrics/api/cluster/summary\", \"slots.used\")));\n Assert.assertEquals(1.0, resource.getPropertyValue(PropertyHelper.getPropertyId(\"metrics/api/cluster/summary\", \"topologies\")));\n Assert.assertEquals(4637.0, resource.getPropertyValue(PropertyHelper.getPropertyId(\"metrics/api/cluster/summary\", \"nimbus.uptime\")));\n }\n\n public void testPopulateResources_singleProperty() throws Exception {\n MetricDefinition metricDefinition = createNiceMock(MetricDefinition.class);\n expect(metricDefinition.getMetrics()).andReturn(componentMetrics);\n expect(metricDefinition.getType()).andReturn(\"org.apache.ambari.server.controller.metrics.RestMetricsPropertyProvider\");\n expect(metricDefinition.getProperties()).andReturn(metricsProperties);\n replay(metricDefinition);\n Map metrics = StackDefinedPropertyProvider.getPropertyInfo(metricDefinition);\n HashMap> componentMetrics = new HashMap<>();\n componentMetrics.put(WRAPPED_METRICS_KEY, metrics);\n TestStreamProvider streamProvider = new TestStreamProvider();\n TestMetricsHostProvider metricsHostProvider = new TestMetricsHostProvider();\n\n RestMetricsPropertyProvider restMetricsPropertyProvider = createRestMetricsPropertyProvider(metricDefinition, componentMetrics, streamProvider,\n metricsHostProvider);\n\n Resource resource = new ResourceImpl(Resource.Type.HostComponent);\n", "answers": [" resource.setProperty(\"HostRoles/cluster_name\", \"c1\");"], "length": 977, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "bf7337f8-e99a-43cb-9d21-0c311dfcf6b5", "reasoning": "The method testPopulateResources_singleProperty is starting similarly to testPopulateResources. After creating a ResourceImpl, the next logical step is to set its properties (cluster name, host name, component name, state) before making requests. The first property set in the earlier test is the cluster name, so the next line should be setting that property on the resource.", "reasoning_model_answer": "resource.setProperty(\"HostRoles/cluster_name\", \"c1\");", "assistant_with_reasoning": "\nThe method testPopulateResources_singleProperty is starting similarly to testPopulateResources. After creating a ResourceImpl, the next logical step is to set its properties (cluster name, host name, component name, state) before making requests. The first property set in the earlier test is the cluster name, so the next line should be setting that property on the resource.\n\nresource.setProperty(\"HostRoles/cluster_name\", \"c1\");", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 2.831, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 18500, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "resource.setProperty(\"HostRoles/cluster_name\", \"c1\");", "score": 0.96, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "package org.elixirian.kommonlee.util.type;\n\nimport static org.assertj.core.api.Assertions.*;\nimport static org.elixirian.kommonlee.util.Objects.*;\n\nimport java.math.BigDecimal;\nimport java.math.BigInteger;\nimport java.util.Arrays;\nimport java.util.Date;\nimport java.util.List;\n\nimport org.elixirian.kommonlee.type.Tuple10;\nimport org.junit.After;\nimport org.junit.AfterClass;\nimport org.junit.Before;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\npublic class ImmutableTuple10Test\n{\n\n @BeforeClass\n public static void setUpBeforeClass() throws Exception\n {\n }\n\n @AfterClass\n public static void tearDownAfterClass() throws Exception\n {\n }\n\n @Before\n public void setUp() throws Exception\n {\n }\n\n @After\n public void tearDown() throws Exception\n {\n }\n\n @Test\n public final void testHashCode()\n {\n /* given */\n final Date date = new Date();\n\n @SuppressWarnings(\"boxing\")\n final Tuple10, String, Integer, Long> expected =\n new ImmutableTuple10, String, Integer, Long>(\n 999, \"Kevin\", true, BigInteger.valueOf(555L), new BigDecimal(\"1234.59\"), date, Arrays.asList(\"Name\", \"Kevin\",\n \"Lee\"), \"Some value\", 123, 777L);\n\n /* when */\n @SuppressWarnings(\"boxing\")\n final Tuple10, String, Integer, Long> actual =\n Tuples.tuple(999, \"Kevin\", true, BigInteger.valueOf(555L), new BigDecimal(\"1234.59\"), date,\n Arrays.asList(\"Name\", \"Kevin\", \"Lee\"), \"Some value\", 123, 777L);\n\n /* then */\n @SuppressWarnings(\"boxing\")\n final Integer actualHashCode = actual.hashCode();\n @SuppressWarnings(\"boxing\")\n final Integer expectedHashCode =\n hash(expected.getValue1(), expected.getValue2(), expected.getValue3(), expected.getValue4(),\n expected.getValue5(), expected.getValue6(), expected.getValue7(), expected.getValue8(), expected.getValue9(),\n expected.getValue10());\n assertThat(actualHashCode).isEqualTo(expectedHashCode);\n }\n\n @Test\n public final void testImmutableTuple10()\n {\n /* given */\n final Date date = new Date();\n\n @SuppressWarnings(\"boxing\")\n final Tuple10, String, Integer, Long> expected =\n new ImmutableTuple10, String, Integer, Long>(\n 999, \"Kevin\", true, BigInteger.valueOf(555L), new BigDecimal(\"1234.59\"), date, Arrays.asList(\"Name\", \"Kevin\",\n \"Lee\"), \"Some value\", 123, 777L);\n\n /* when */\n @SuppressWarnings(\"boxing\")\n final Tuple10, String, Integer, Long> actual =\n Tuples.tuple(999, \"Kevin\", true, BigInteger.valueOf(555L), new BigDecimal(\"1234.59\"), date,\n Arrays.asList(\"Name\", \"Kevin\", \"Lee\"), \"Some value\", 123, 777L);\n\n /* then */\n @SuppressWarnings(\"boxing\")\n final Integer actualHashCode = actual.hashCode();\n @SuppressWarnings(\"boxing\")\n final Integer expectedHashCode =\n hash(expected.getValue1(), expected.getValue2(), expected.getValue3(), expected.getValue4(),\n expected.getValue5(), expected.getValue6(), expected.getValue7(), expected.getValue8(), expected.getValue9(),\n expected.getValue10());\n assertThat(actualHashCode).isEqualTo(expectedHashCode);\n\n assertThat(actual).isEqualTo(expected);\n\n assertThat(actual.getValue1()).isEqualTo(expected.getValue1());\n assertThat(actual.getValue2()).isEqualTo(expected.getValue2());\n assertThat(actual.getValue3()).isEqualTo(expected.getValue3());\n assertThat(actual.getValue4()).isEqualTo(expected.getValue4());\n assertThat(actual.getValue5()).isEqualTo(expected.getValue5());\n assertThat(actual.getValue6()).isEqualTo(expected.getValue6());\n assertThat(actual.getValue7()).isEqualTo(expected.getValue7());\n assertThat(actual.getValue8()).isEqualTo(expected.getValue8());\n assertThat(actual.getValue9()).isEqualTo(expected.getValue9());\n assertThat(actual.getValue10()).isEqualTo(expected.getValue10());\n\n assertThat(actual._1()).isEqualTo(expected._1());\n assertThat(actual._2()).isEqualTo(expected._2());\n assertThat(actual._3()).isEqualTo(expected._3());\n assertThat(actual._4()).isEqualTo(expected._4());\n assertThat(actual._5()).isEqualTo(expected._5());\n assertThat(actual._6()).isEqualTo(expected._6());\n assertThat(actual._7()).isEqualTo(expected._7());\n assertThat(actual._8()).isEqualTo(expected._8());\n assertThat(actual._9()).isEqualTo(expected._9());\n assertThat(actual._10()).isEqualTo(expected._10());\n }\n\n @Test\n public final void testGetValue1()\n {\n /* given */\n final Date date = new Date();\n\n @SuppressWarnings(\"boxing\")\n final Tuple10, String, Integer, Long> expected =\n new ImmutableTuple10, String, Integer, Long>(\n 999, \"Kevin\", true, BigInteger.valueOf(555L), new BigDecimal(\"1234.59\"), date, Arrays.asList(\"Name\", \"Kevin\",\n \"Lee\"), \"Some value\", 123, 777L);\n\n /* when */\n @SuppressWarnings(\"boxing\")\n final Tuple10, String, Integer, Long> actual =\n Tuples.tuple(999, \"Kevin\", true, BigInteger.valueOf(555L), new BigDecimal(\"1234.59\"), date,\n Arrays.asList(\"Name\", \"Kevin\", \"Lee\"), \"Some value\", 123, 777L);\n\n /* then */\n @SuppressWarnings(\"boxing\")\n final Integer actualHashCode = actual.hashCode();\n @SuppressWarnings(\"boxing\")\n final Integer expectedHashCode =\n hash(expected.getValue1(), expected.getValue2(), expected.getValue3(), expected.getValue4(),\n expected.getValue5(), expected.getValue6(), expected.getValue7(), expected.getValue8(), expected.getValue9(),\n expected.getValue10());\n assertThat(actualHashCode).isEqualTo(expectedHashCode);\n\n assertThat(actual).isEqualTo(expected);\n\n assertThat(actual.getValue1()).isEqualTo(expected.getValue1());\n assertThat(actual.getValue2()).isEqualTo(expected.getValue2());\n assertThat(actual.getValue3()).isEqualTo(expected.getValue3());\n assertThat(actual.getValue4()).isEqualTo(expected.getValue4());\n assertThat(actual.getValue5()).isEqualTo(expected.getValue5());\n assertThat(actual.getValue6()).isEqualTo(expected.getValue6());\n assertThat(actual.getValue7()).isEqualTo(expected.getValue7());\n assertThat(actual.getValue8()).isEqualTo(expected.getValue8());\n assertThat(actual.getValue9()).isEqualTo(expected.getValue9());\n assertThat(actual.getValue10()).isEqualTo(expected.getValue10());\n\n assertThat(actual._1()).isEqualTo(expected._1());\n assertThat(actual._2()).isEqualTo(expected._2());\n assertThat(actual._3()).isEqualTo(expected._3());\n assertThat(actual._4()).isEqualTo(expected._4());\n assertThat(actual._5()).isEqualTo(expected._5());\n assertThat(actual._6()).isEqualTo(expected._6());\n assertThat(actual._7()).isEqualTo(expected._7());\n assertThat(actual._8()).isEqualTo(expected._8());\n assertThat(actual._9()).isEqualTo(expected._9());\n assertThat(actual._10()).isEqualTo(expected._10());\n }\n\n @Test\n public final void testGetValue2()\n {\n /* given */\n final Date date = new Date();\n\n @SuppressWarnings(\"boxing\")\n final Tuple10, String, Integer, Long> expected =\n new ImmutableTuple10, String, Integer, Long>(\n 999, \"Kevin\", true, BigInteger.valueOf(555L), new BigDecimal(\"1234.59\"), date, Arrays.asList(\"Name\", \"Kevin\",\n \"Lee\"), \"Some value\", 123, 777L);\n\n /* when */\n @SuppressWarnings(\"boxing\")\n final Tuple10, String, Integer, Long> actual =\n Tuples.tuple(999, \"Kevin\", true, BigInteger.valueOf(555L), new BigDecimal(\"1234.59\"), date,\n Arrays.asList(\"Name\", \"Kevin\", \"Lee\"), \"Some value\", 123, 777L);\n\n /* then */\n @SuppressWarnings(\"boxing\")\n final Integer actualHashCode = actual.hashCode();\n @SuppressWarnings(\"boxing\")\n final Integer expectedHashCode =\n hash(expected.getValue1(), expected.getValue2(), expected.getValue3(), expected.getValue4(),\n expected.getValue5(), expected.getValue6(), expected.getValue7(), expected.getValue8(), expected.getValue9(),\n expected.getValue10());\n assertThat(actualHashCode).isEqualTo(expectedHashCode);\n\n assertThat(actual).isEqualTo(expected);\n\n assertThat(actual.getValue1()).isEqualTo(expected.getValue1());\n assertThat(actual.getValue2()).isEqualTo(expected.getValue2());\n assertThat(actual.getValue3()).isEqualTo(expected.getValue3());\n assertThat(actual.getValue4()).isEqualTo(expected.getValue4());\n assertThat(actual.getValue5()).isEqualTo(expected.getValue5());\n assertThat(actual.getValue6()).isEqualTo(expected.getValue6());\n assertThat(actual.getValue7()).isEqualTo(expected.getValue7());\n assertThat(actual.getValue8()).isEqualTo(expected.getValue8());\n assertThat(actual.getValue9()).isEqualTo(expected.getValue9());\n assertThat(actual.getValue10()).isEqualTo(expected.getValue10());\n\n assertThat(actual._1()).isEqualTo(expected._1());\n assertThat(actual._2()).isEqualTo(expected._2());\n assertThat(actual._3()).isEqualTo(expected._3());\n assertThat(actual._4()).isEqualTo(expected._4());\n assertThat(actual._5()).isEqualTo(expected._5());\n assertThat(actual._6()).isEqualTo(expected._6());\n assertThat(actual._7()).isEqualTo(expected._7());\n assertThat(actual._8()).isEqualTo(expected._8());\n assertThat(actual._9()).isEqualTo(expected._9());\n assertThat(actual._10()).isEqualTo(expected._10());\n }\n\n @Test\n public final void testGetValue3()\n {\n /* given */\n final Date date = new Date();\n\n @SuppressWarnings(\"boxing\")\n final Tuple10, String, Integer, Long> expected =\n new ImmutableTuple10, String, Integer, Long>(\n 999, \"Kevin\", true, BigInteger.valueOf(555L), new BigDecimal(\"1234.59\"), date, Arrays.asList(\"Name\", \"Kevin\",\n \"Lee\"), \"Some value\", 123, 777L);\n\n /* when */\n @SuppressWarnings(\"boxing\")\n final Tuple10, String, Integer, Long> actual =\n Tuples.tuple(999, \"Kevin\", true, BigInteger.valueOf(555L), new BigDecimal(\"1234.59\"), date,\n Arrays.asList(\"Name\", \"Kevin\", \"Lee\"), \"Some value\", 123, 777L);\n\n /* then */\n @SuppressWarnings(\"boxing\")\n final Integer actualHashCode = actual.hashCode();\n @SuppressWarnings(\"boxing\")\n final Integer expectedHashCode =\n hash(expected.getValue1(), expected.getValue2(), expected.getValue3(), expected.getValue4(),\n expected.getValue5(), expected.getValue6(), expected.getValue7(), expected.getValue8(), expected.getValue9(),\n expected.getValue10());\n assertThat(actualHashCode).isEqualTo(expectedHashCode);\n\n assertThat(actual).isEqualTo(expected);\n\n assertThat(actual.getValue1()).isEqualTo(expected.getValue1());\n assertThat(actual.getValue2()).isEqualTo(expected.getValue2());\n assertThat(actual.getValue3()).isEqualTo(expected.getValue3());\n assertThat(actual.getValue4()).isEqualTo(expected.getValue4());\n assertThat(actual.getValue5()).isEqualTo(expected.getValue5());\n assertThat(actual.getValue6()).isEqualTo(expected.getValue6());\n assertThat(actual.getValue7()).isEqualTo(expected.getValue7());\n assertThat(actual.getValue8()).isEqualTo(expected.getValue8());\n assertThat(actual.getValue9()).isEqualTo(expected.getValue9());\n assertThat(actual.getValue10()).isEqualTo(expected.getValue10());\n\n assertThat(actual._1()).isEqualTo(expected._1());\n assertThat(actual._2()).isEqualTo(expected._2());\n assertThat(actual._3()).isEqualTo(expected._3());\n assertThat(actual._4()).isEqualTo(expected._4());\n assertThat(actual._5()).isEqualTo(expected._5());\n assertThat(actual._6()).isEqualTo(expected._6());\n assertThat(actual._7()).isEqualTo(expected._7());\n assertThat(actual._8()).isEqualTo(expected._8());\n assertThat(actual._9()).isEqualTo(expected._9());\n assertThat(actual._10()).isEqualTo(expected._10());\n }\n\n @Test\n public final void testGetValue4()\n {\n /* given */\n final Date date = new Date();\n\n @SuppressWarnings(\"boxing\")\n final Tuple10, String, Integer, Long> expected =\n new ImmutableTuple10, String, Integer, Long>(\n 999, \"Kevin\", true, BigInteger.valueOf(555L), new BigDecimal(\"1234.59\"), date, Arrays.asList(\"Name\", \"Kevin\",\n \"Lee\"), \"Some value\", 123, 777L);\n\n /* when */\n @SuppressWarnings(\"boxing\")\n final Tuple10, String, Integer, Long> actual =\n Tuples.tuple(999, \"Kevin\", true, BigInteger.valueOf(555L), new BigDecimal(\"1234.59\"), date,\n Arrays.asList(\"Name\", \"Kevin\", \"Lee\"), \"Some value\", 123, 777L);\n\n /* then */\n @SuppressWarnings(\"boxing\")\n final Integer actualHashCode = actual.hashCode();\n @SuppressWarnings(\"boxing\")\n final Integer expectedHashCode =\n hash(expected.getValue1(), expected.getValue2(), expected.getValue3(), expected.getValue4(),\n expected.getValue5(), expected.getValue6(), expected.getValue7(), expected.getValue8(), expected.getValue9(),\n expected.getValue10());\n assertThat(actualHashCode).isEqualTo(expectedHashCode);\n\n assertThat(actual).isEqualTo(expected);\n\n assertThat(actual.getValue1()).isEqualTo(expected.getValue1());\n assertThat(actual.getValue2()).isEqualTo(expected.getValue2());\n assertThat(actual.getValue3()).isEqualTo(expected.getValue3());\n assertThat(actual.getValue4()).isEqualTo(expected.getValue4());\n assertThat(actual.getValue5()).isEqualTo(expected.getValue5());\n assertThat(actual.getValue6()).isEqualTo(expected.getValue6());\n assertThat(actual.getValue7()).isEqualTo(expected.getValue7());\n assertThat(actual.getValue8()).isEqualTo(expected.getValue8());\n assertThat(actual.getValue9()).isEqualTo(expected.getValue9());\n assertThat(actual.getValue10()).isEqualTo(expected.getValue10());\n\n assertThat(actual._1()).isEqualTo(expected._1());\n assertThat(actual._2()).isEqualTo(expected._2());\n assertThat(actual._3()).isEqualTo(expected._3());\n assertThat(actual._4()).isEqualTo(expected._4());\n assertThat(actual._5()).isEqualTo(expected._5());\n assertThat(actual._6()).isEqualTo(expected._6());\n assertThat(actual._7()).isEqualTo(expected._7());\n assertThat(actual._8()).isEqualTo(expected._8());\n assertThat(actual._9()).isEqualTo(expected._9());\n assertThat(actual._10()).isEqualTo(expected._10());\n }\n\n @Test\n public final void testGetValue5()\n {\n /* given */\n final Date date = new Date();\n\n @SuppressWarnings(\"boxing\")\n final Tuple10, String, Integer, Long> expected =\n new ImmutableTuple10, String, Integer, Long>(\n 999, \"Kevin\", true, BigInteger.valueOf(555L), new BigDecimal(\"1234.59\"), date, Arrays.asList(\"Name\", \"Kevin\",\n \"Lee\"), \"Some value\", 123, 777L);\n\n /* when */", "answers": [" @SuppressWarnings(\"boxing\")"], "length": 901, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "b360e2f8-26af-41b1-a7c8-3a219180e5a0", "reasoning": "In each test method, after the /* when */ comment the code creates the actual tuple using Tuples.tuple with the same values as the expected tuple. The next line should be the @SuppressWarnings annotation and the declaration of the actual variable, matching the generic types and values used previously.", "reasoning_model_answer": "@SuppressWarnings(\"boxing\")\nfinal Tuple10, String, Integer, Long> actual =\n Tuples.tuple(999, \"Kevin\", true, BigInteger.valueOf(555L), new BigDecimal(\"1234.59\"), date,\n Arrays.asList(\"Name\", \"Kevin\", \"Lee\"), \"Some value\", 123, 777L);", "assistant_with_reasoning": "\nIn each test method, after the /* when */ comment the code creates the actual tuple using Tuples.tuple with the same values as the expected tuple. The next line should be the @SuppressWarnings annotation and the declaration of the actual variable, matching the generic types and values used previously.\n\n@SuppressWarnings(\"boxing\")\nfinal Tuple10, String, Integer, Long> actual =\n Tuples.tuple(999, \"Kevin\", true, BigInteger.valueOf(555L), new BigDecimal(\"1234.59\"), date,\n Arrays.asList(\"Name\", \"Kevin\", \"Lee\"), \"Some value\", 123, 777L);", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.548, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 16016, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "@SuppressWarnings(\"boxing\")\nfinal Tuple10, String, Integer, Long> actual =\n Tuples.tuple(999, \"Kevin\", true, BigInteger.valueOf(555L), new BigDecimal(\"1234.59\"), date,\n Arrays.asList(\"Name\", \"Kevin\", \"Lee\"), \"Some value\", 123, 777L);", "score": 0.93, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "# -*- coding: utf-8 -*-\n\"\"\"Maximum flow algorithms test suite.\n\"\"\"\nfrom nose.tools import *\n\nimport networkx as nx\nfrom networkx.algorithms.flow import build_flow_dict, build_residual_network\nfrom networkx.algorithms.flow import (edmonds_karp, ford_fulkerson,\n preflow_push, shortest_augmenting_path)\n\nflow_funcs = [edmonds_karp, ford_fulkerson, preflow_push,\n shortest_augmenting_path]\nmax_min_funcs = [nx.maximum_flow, nx.minimum_cut]\nflow_value_funcs = [nx.maximum_flow_value, nx.minimum_cut_value]\ninterface_funcs = sum([max_min_funcs, flow_value_funcs], [])\nall_funcs = sum([flow_funcs, interface_funcs], [])\n\nmsg = \"Assertion failed in function: {0}\"\nmsgi = \"Assertion failed in function: {0} in interface {1}\"\n\n\ndef compute_cutset(G, partition):\n reachable, non_reachable = partition\n cutset = set()\n for u, nbrs in ((n, G[n]) for n in reachable):\n cutset.update((u, v) for v in nbrs if v in non_reachable)\n return cutset\n\n\ndef validate_flows(G, s, t, flowDict, solnValue, capacity, flow_func):\n assert_equal(set(G), set(flowDict), msg=msg.format(flow_func.__name__))\n for u in G:\n assert_equal(set(G[u]), set(flowDict[u]),\n msg=msg.format(flow_func.__name__))\n excess = dict((u, 0) for u in flowDict)\n for u in flowDict:\n for v, flow in flowDict[u].items():\n if capacity in G[u][v]:\n ok_(flow <= G[u][v][capacity])\n ok_(flow >= 0, msg=msg.format(flow_func.__name__))\n excess[u] -= flow\n excess[v] += flow\n for u, exc in excess.items():\n if u == s:\n assert_equal(exc, -solnValue, msg=msg.format(flow_func.__name__))\n elif u == t:\n assert_equal(exc, solnValue, msg=msg.format(flow_func.__name__))\n else:\n assert_equal(exc, 0, msg=msg.format(flow_func.__name__))\n\n\ndef validate_cuts(G, s, t, solnValue, partition, capacity, flow_func):\n assert_true(all(n in G for n in partition[0]),\n msg=msg.format(flow_func.__name__))\n assert_true(all(n in G for n in partition[1]),\n msg=msg.format(flow_func.__name__))\n cutset = compute_cutset(G, partition)\n assert_true(all(G.has_edge(u, v) for (u, v) in cutset),\n msg=msg.format(flow_func.__name__))\n assert_equal(solnValue, sum(G[u][v][capacity] for (u, v) in cutset),\n msg=msg.format(flow_func.__name__))\n H = G.copy()\n H.remove_edges_from(cutset)\n if not G.is_directed():\n assert_false(nx.is_connected(H), msg=msg.format(flow_func.__name__))\n else:\n assert_false(nx.is_strongly_connected(H),\n msg=msg.format(flow_func.__name__))\n\n\ndef compare_flows_and_cuts(G, s, t, solnFlows, solnValue, capacity='capacity'):\n for flow_func in flow_funcs:\n R = flow_func(G, s, t, capacity)\n # Test both legacy and new implementations.\n legacy = R.graph.get('algorithm') == \"ford_fulkerson_legacy\"\n flow_value = R.graph['flow_value']\n if legacy:\n flow_dict = R.graph['flow_dict']\n else:\n flow_dict = build_flow_dict(G, R)\n assert_equal(flow_value, solnValue, msg=msg.format(flow_func.__name__))\n if legacy:\n assert_equal(flow_dict, solnFlows, msg=msg.format(flow_func.__name__))\n else:\n validate_flows(G, s, t, flow_dict, solnValue, capacity, flow_func)\n # Minimum cut\n if legacy:\n cut_value, partition = nx.minimum_cut(G, s, t, capacity=capacity,\n flow_func=ford_fulkerson)\n else:\n cut_value, partition = nx.minimum_cut(G, s, t, capacity=capacity,\n flow_func=flow_func)\n validate_cuts(G, s, t, solnValue, partition, capacity, flow_func)\n\n\nclass TestMaxflowMinCutCommon:\n\n def test_graph1(self):\n # Trivial undirected graph\n G = nx.Graph()\n G.add_edge(1,2, capacity = 1.0)\n\n solnFlows = {1: {2: 1.0},\n 2: {1: 1.0}}\n\n compare_flows_and_cuts(G, 1, 2, solnFlows, 1.0)\n\n def test_graph2(self):\n # A more complex undirected graph\n # adapted from www.topcoder.com/tc?module=Statc&d1=tutorials&d2=maxFlow\n G = nx.Graph()\n G.add_edge('x','a', capacity = 3.0)\n G.add_edge('x','b', capacity = 1.0)\n G.add_edge('a','c', capacity = 3.0)\n G.add_edge('b','c', capacity = 5.0)\n G.add_edge('b','d', capacity = 4.0)\n G.add_edge('d','e', capacity = 2.0)\n G.add_edge('c','y', capacity = 2.0)\n G.add_edge('e','y', capacity = 3.0)\n\n H = {'x': {'a': 3, 'b': 1},\n 'a': {'c': 3, 'x': 3},\n 'b': {'c': 1, 'd': 2, 'x': 1},\n 'c': {'a': 3, 'b': 1, 'y': 2},\n 'd': {'b': 2, 'e': 2},\n 'e': {'d': 2, 'y': 2},\n 'y': {'c': 2, 'e': 2}}\n\n compare_flows_and_cuts(G, 'x', 'y', H, 4.0)\n\n def test_digraph1(self):\n # The classic directed graph example\n G = nx.DiGraph()\n G.add_edge('a','b', capacity = 1000.0)\n G.add_edge('a','c', capacity = 1000.0)\n G.add_edge('b','c', capacity = 1.0)\n G.add_edge('b','d', capacity = 1000.0)\n G.add_edge('c','d', capacity = 1000.0)\n\n H = {'a': {'b': 1000.0, 'c': 1000.0},\n 'b': {'c': 0, 'd': 1000.0},\n 'c': {'d': 1000.0},\n 'd': {}}\n\n compare_flows_and_cuts(G, 'a', 'd', H, 2000.0)\n\n def test_digraph2(self):\n # An example in which some edges end up with zero flow.\n G = nx.DiGraph()\n G.add_edge('s', 'b', capacity = 2)\n G.add_edge('s', 'c', capacity = 1)\n G.add_edge('c', 'd', capacity = 1)\n G.add_edge('d', 'a', capacity = 1)\n G.add_edge('b', 'a', capacity = 2)\n G.add_edge('a', 't', capacity = 2)\n\n H = {'s': {'b': 2, 'c': 0},\n 'c': {'d': 0},\n 'd': {'a': 0},\n 'b': {'a': 2},\n 'a': {'t': 2},\n 't': {}}\n\n compare_flows_and_cuts(G, 's', 't', H, 2)\n\n def test_digraph3(self):\n # A directed graph example from Cormen et al.\n G = nx.DiGraph()\n G.add_edge('s','v1', capacity = 16.0)\n G.add_edge('s','v2', capacity = 13.0)\n G.add_edge('v1','v2', capacity = 10.0)\n G.add_edge('v2','v1', capacity = 4.0)\n G.add_edge('v1','v3', capacity = 12.0)\n G.add_edge('v3','v2', capacity = 9.0)\n G.add_edge('v2','v4', capacity = 14.0)\n G.add_edge('v4','v3', capacity = 7.0)\n G.add_edge('v3','t', capacity = 20.0)\n G.add_edge('v4','t', capacity = 4.0)\n\n H = {'s': {'v1': 12.0, 'v2': 11.0},\n 'v2': {'v1': 0, 'v4': 11.0},\n 'v1': {'v2': 0, 'v3': 12.0},\n 'v3': {'v2': 0, 't': 19.0},\n 'v4': {'v3': 7.0, 't': 4.0},\n 't': {}}\n\n compare_flows_and_cuts(G, 's', 't', H, 23.0)\n\n def test_digraph4(self):\n # A more complex directed graph\n # from www.topcoder.com/tc?module=Statc&d1=tutorials&d2=maxFlow\n G = nx.DiGraph()\n G.add_edge('x','a', capacity = 3.0)\n G.add_edge('x','b', capacity = 1.0)\n G.add_edge('a','c', capacity = 3.0)\n G.add_edge('b','c', capacity = 5.0)\n G.add_edge('b','d', capacity = 4.0)\n G.add_edge('d','e', capacity = 2.0)\n G.add_edge('c','y', capacity = 2.0)\n G.add_edge('e','y', capacity = 3.0)\n\n H = {'x': {'a': 2.0, 'b': 1.0},\n 'a': {'c': 2.0},\n 'b': {'c': 0, 'd': 1.0},\n 'c': {'y': 2.0},\n 'd': {'e': 1.0},\n 'e': {'y': 1.0},\n 'y': {}}\n\n compare_flows_and_cuts(G, 'x', 'y', H, 3.0)\n\n def test_optional_capacity(self):\n # Test optional capacity parameter.\n G = nx.DiGraph()\n G.add_edge('x','a', spam = 3.0)\n G.add_edge('x','b', spam = 1.0)\n G.add_edge('a','c', spam = 3.0)\n G.add_edge('b','c', spam = 5.0)\n G.add_edge('b','d', spam = 4.0)\n G.add_edge('d','e', spam = 2.0)\n G.add_edge('c','y', spam = 2.0)\n G.add_edge('e','y', spam = 3.0)\n\n solnFlows = {'x': {'a': 2.0, 'b': 1.0},\n 'a': {'c': 2.0},\n 'b': {'c': 0, 'd': 1.0},\n 'c': {'y': 2.0},\n 'd': {'e': 1.0},\n 'e': {'y': 1.0},\n 'y': {}}\n solnValue = 3.0\n s = 'x'\n t = 'y'\n\n compare_flows_and_cuts(G, s, t, solnFlows, solnValue, capacity = 'spam')\n\n def test_digraph_infcap_edges(self):\n # DiGraph with infinite capacity edges\n G = nx.DiGraph()\n G.add_edge('s', 'a')\n G.add_edge('s', 'b', capacity = 30)\n G.add_edge('a', 'c', capacity = 25)\n G.add_edge('b', 'c', capacity = 12)\n G.add_edge('a', 't', capacity = 60)\n G.add_edge('c', 't')\n\n H = {'s': {'a': 85, 'b': 12},\n 'a': {'c': 25, 't': 60},\n 'b': {'c': 12},\n 'c': {'t': 37},\n 't': {}}\n\n compare_flows_and_cuts(G, 's', 't', H, 97)\n\n # DiGraph with infinite capacity digon\n G = nx.DiGraph()\n G.add_edge('s', 'a', capacity = 85)\n G.add_edge('s', 'b', capacity = 30)\n G.add_edge('a', 'c')\n G.add_edge('c', 'a')\n G.add_edge('b', 'c', capacity = 12)\n G.add_edge('a', 't', capacity = 60)\n G.add_edge('c', 't', capacity = 37)\n\n H = {'s': {'a': 85, 'b': 12},\n 'a': {'c': 25, 't': 60},\n 'c': {'a': 0, 't': 37},\n 'b': {'c': 12},\n 't': {}}\n\n compare_flows_and_cuts(G, 's', 't', H, 97)\n\n\n def test_digraph_infcap_path(self):\n # Graph with infinite capacity (s, t)-path\n G = nx.DiGraph()\n G.add_edge('s', 'a')\n G.add_edge('s', 'b', capacity = 30)\n G.add_edge('a', 'c')\n G.add_edge('b', 'c', capacity = 12)\n G.add_edge('a', 't', capacity = 60)\n G.add_edge('c', 't')\n\n for flow_func in all_funcs:\n assert_raises(nx.NetworkXUnbounded,\n flow_func, G, 's', 't')\n\n def test_graph_infcap_edges(self):\n # Undirected graph with infinite capacity edges\n G = nx.Graph()\n G.add_edge('s', 'a')\n G.add_edge('s', 'b', capacity = 30)\n G.add_edge('a', 'c', capacity = 25)\n G.add_edge('b', 'c', capacity = 12)\n G.add_edge('a', 't', capacity = 60)\n G.add_edge('c', 't')\n\n H = {'s': {'a': 85, 'b': 12},\n 'a': {'c': 25, 's': 85, 't': 60},\n 'b': {'c': 12, 's': 12},\n 'c': {'a': 25, 'b': 12, 't': 37},\n 't': {'a': 60, 'c': 37}}\n\n compare_flows_and_cuts(G, 's', 't', H, 97)\n\n def test_digraph4(self):\n # From ticket #429 by mfrasca.\n G = nx.DiGraph()\n G.add_edge('s', 'a', capacity = 2)\n G.add_edge('s', 'b', capacity = 2)\n G.add_edge('a', 'b', capacity = 5)\n G.add_edge('a', 't', capacity = 1)\n G.add_edge('b', 'a', capacity = 1)\n G.add_edge('b', 't', capacity = 3)\n flowSoln = {'a': {'b': 1, 't': 1},\n 'b': {'a': 0, 't': 3},\n 's': {'a': 2, 'b': 2},\n 't': {}}\n compare_flows_and_cuts(G, 's', 't', flowSoln, 4)\n\n\n def test_disconnected(self):\n G = nx.Graph()\n G.add_weighted_edges_from([(0,1,1),(1,2,1),(2,3,1)],weight='capacity')\n G.remove_node(1)\n assert_equal(nx.maximum_flow_value(G,0,3), 0)\n flowSoln = {0: {}, 2: {3: 0}, 3: {2: 0}}\n compare_flows_and_cuts(G, 0, 3, flowSoln, 0)\n\n def test_source_target_not_in_graph(self):\n G = nx.Graph()\n G.add_weighted_edges_from([(0,1,1),(1,2,1),(2,3,1)],weight='capacity')\n G.remove_node(0)\n for flow_func in all_funcs:\n assert_raises(nx.NetworkXError, flow_func, G, 0, 3)\n G.add_weighted_edges_from([(0,1,1),(1,2,1),(2,3,1)],weight='capacity')\n G.remove_node(3)\n for flow_func in all_funcs:\n assert_raises(nx.NetworkXError, flow_func, G, 0, 3)\n\n def test_source_target_coincide(self):\n G = nx.Graph()\n G.add_node(0)\n for flow_func in all_funcs:\n assert_raises(nx.NetworkXError, flow_func, G, 0, 0)\n\n def test_multigraphs_raise(self):\n G = nx.MultiGraph()\n M = nx.MultiDiGraph()\n G.add_edges_from([(0, 1), (1, 0)], capacity=True)\n for flow_func in all_funcs:\n assert_raises(nx.NetworkXError, flow_func, G, 0, 0)\n\n\nclass TestMaxFlowMinCutInterface:\n\n def setup(self):\n G = nx.DiGraph()\n G.add_edge('x','a', capacity = 3.0)\n G.add_edge('x','b', capacity = 1.0)", "answers": [" G.add_edge('a','c', capacity = 3.0)"], "length": 1231, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "99cfab4d-3137-46d1-8078-a6c662382db4", "reasoning": "In the TestMaxFlowMinCutInterface.setup method, they start building a directed graph by adding edges. After adding the edge ('x','b'), the next logical step is to continue defining the graph, matching the earlier example that includes edge ('a','c') with capacity 3.0. Therefore the next line should add that edge.", "reasoning_model_answer": "G.add_edge('a','c', capacity = 3.0)", "assistant_with_reasoning": "\nIn the TestMaxFlowMinCutInterface.setup method, they start building a directed graph by adding edges. After adding the edge ('x','b'), the next logical step is to continue defining the graph, matching the earlier example that includes edge ('a','c') with capacity 3.0. Therefore the next line should add that edge.\n\nG.add_edge('a','c', capacity = 3.0)", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 5.818, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 12885, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "G.add_edge('a','c', capacity = 3.0)", "score": 0.9, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\npackage org.apache.rya.indexing.pcj.fluo.integration;\n\nimport static java.util.Objects.requireNonNull;\nimport static org.junit.Assert.assertEquals;\n\nimport java.util.Collection;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.Iterator;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.UUID;\n\nimport org.apache.kafka.clients.consumer.ConsumerRecord;\nimport org.apache.kafka.clients.consumer.ConsumerRecords;\nimport org.apache.kafka.clients.consumer.KafkaConsumer;\nimport org.apache.rya.indexing.pcj.fluo.KafkaExportITBase;\nimport org.apache.rya.indexing.pcj.storage.accumulo.VariableOrder;\nimport org.apache.rya.indexing.pcj.storage.accumulo.VisibilityBindingSet;\nimport org.junit.Test;\nimport org.openrdf.model.Statement;\nimport org.openrdf.model.ValueFactory;\nimport org.openrdf.model.impl.ValueFactoryImpl;\nimport org.openrdf.model.vocabulary.XMLSchema;\nimport org.openrdf.query.BindingSet;\nimport org.openrdf.query.impl.MapBindingSet;\n\nimport com.google.common.collect.Sets;\n\n/**\n * Performs integration tests over the Fluo application geared towards Kafka PCJ exporting.\n *

    \n * These tests might be ignored so that they will not run as unit tests while building the application.\n * Run this test from Maven command line:\n * $ cd rya/extras/rya.pcj.fluo/pcj.fluo.integration\n * $ mvn surefire:test -Dtest=KafkaExportIT\n */\npublic class KafkaExportIT extends KafkaExportITBase {\n\n @Test\n public void newResultsExportedTest() throws Exception {\n final String sparql =\n \"SELECT ?customer ?worker ?city { \" +\n \"FILTER(?customer = ) \" +\n \"FILTER(?city = ) \" +\n \"?customer ?worker. \" +\n \"?worker ?city. \" +\n \"?worker . \" +\n \"}\";\n\n // Triples that will be streamed into Fluo after the PCJ has been created.\n final ValueFactory vf = new ValueFactoryImpl();\n final Collection statements =\n Sets.newHashSet(\n vf.createStatement(vf.createURI(\"http://Alice\"), vf.createURI(\"http://talksTo\"), vf.createURI(\"http://Bob\")),\n vf.createStatement(vf.createURI(\"http://Bob\"), vf.createURI(\"http://livesIn\"), vf.createURI(\"http://London\")),\n vf.createStatement(vf.createURI(\"http://Bob\"), vf.createURI(\"http://worksAt\"), vf.createURI(\"http://Chipotle\")),\n vf.createStatement(vf.createURI(\"http://Alice\"), vf.createURI(\"http://talksTo\"), vf.createURI(\"http://Charlie\")),\n vf.createStatement(vf.createURI(\"http://Charlie\"), vf.createURI(\"http://livesIn\"), vf.createURI(\"http://London\")),\n vf.createStatement(vf.createURI(\"http://Charlie\"), vf.createURI(\"http://worksAt\"), vf.createURI(\"http://Chipotle\")),\n vf.createStatement(vf.createURI(\"http://Alice\"), vf.createURI(\"http://talksTo\"), vf.createURI(\"http://David\")),\n vf.createStatement(vf.createURI(\"http://David\"), vf.createURI(\"http://livesIn\"), vf.createURI(\"http://London\")),\n vf.createStatement(vf.createURI(\"http://David\"), vf.createURI(\"http://worksAt\"), vf.createURI(\"http://Chipotle\")),\n vf.createStatement(vf.createURI(\"http://Alice\"), vf.createURI(\"http://talksTo\"), vf.createURI(\"http://Eve\")),\n vf.createStatement(vf.createURI(\"http://Eve\"), vf.createURI(\"http://livesIn\"), vf.createURI(\"http://Leeds\")),\n vf.createStatement(vf.createURI(\"http://Eve\"), vf.createURI(\"http://worksAt\"), vf.createURI(\"http://Chipotle\")),\n vf.createStatement(vf.createURI(\"http://Frank\"), vf.createURI(\"http://talksTo\"), vf.createURI(\"http://Alice\")),\n vf.createStatement(vf.createURI(\"http://Frank\"), vf.createURI(\"http://livesIn\"), vf.createURI(\"http://London\")),\n vf.createStatement(vf.createURI(\"http://Frank\"), vf.createURI(\"http://worksAt\"), vf.createURI(\"http://Chipotle\")));\n\n // Create the PCJ in Fluo and load the statements into Rya.\n final String pcjId = loadData(sparql, statements);\n\n // The expected results of the SPARQL query once the PCJ has been computed.\n final Set expectedResult = new HashSet<>();\n\n MapBindingSet bs = new MapBindingSet();\n bs.addBinding(\"customer\", vf.createURI(\"http://Alice\"));\n bs.addBinding(\"worker\", vf.createURI(\"http://Bob\"));\n bs.addBinding(\"city\", vf.createURI(\"http://London\"));\n expectedResult.add( new VisibilityBindingSet(bs) );\n\n bs = new MapBindingSet();\n bs.addBinding(\"customer\", vf.createURI(\"http://Alice\"));\n bs.addBinding(\"worker\", vf.createURI(\"http://Charlie\"));\n bs.addBinding(\"city\", vf.createURI(\"http://London\"));\n expectedResult.add( new VisibilityBindingSet(bs) );\n\n bs = new MapBindingSet();\n bs.addBinding(\"customer\", vf.createURI(\"http://Alice\"));\n bs.addBinding(\"worker\", vf.createURI(\"http://David\"));\n bs.addBinding(\"city\", vf.createURI(\"http://London\"));\n expectedResult.add( new VisibilityBindingSet(bs) );\n\n // Ensure the last result matches the expected result.\n final Set result = readAllResults(pcjId);\n assertEquals(expectedResult, result);\n }\n\n @Test\n public void min() throws Exception {\n // A query that finds the minimum price for an item within the inventory.\n final String sparql =\n \"SELECT (min(?price) as ?minPrice) { \" +\n \"?item ?price . \" +\n \"}\";\n\n // Create the Statements that will be loaded into Rya.\n final ValueFactory vf = new ValueFactoryImpl();\n final Collection statements = Sets.newHashSet(\n vf.createStatement(vf.createURI(\"urn:apple\"), vf.createURI(\"urn:price\"), vf.createLiteral(2.50)),\n vf.createStatement(vf.createURI(\"urn:gum\"), vf.createURI(\"urn:price\"), vf.createLiteral(0.99)),\n vf.createStatement(vf.createURI(\"urn:sandwich\"), vf.createURI(\"urn:price\"), vf.createLiteral(4.99)));\n\n // Create the PCJ in Fluo and load the statements into Rya.\n final String pcjId = loadData(sparql, statements);\n\n // Create the expected results of the SPARQL query once the PCJ has been computed.\n final MapBindingSet expectedResult = new MapBindingSet();\n expectedResult.addBinding(\"minPrice\", vf.createLiteral(0.99));\n\n // Ensure the last result matches the expected result.\n final VisibilityBindingSet result = readLastResult(pcjId);\n assertEquals(expectedResult, result);\n }\n\n @Test\n public void max() throws Exception {\n // A query that finds the maximum price for an item within the inventory.\n final String sparql =\n \"SELECT (max(?price) as ?maxPrice) { \" +\n \"?item ?price . \" +\n \"}\";\n\n // Create the Statements that will be loaded into Rya.\n final ValueFactory vf = new ValueFactoryImpl();\n final Collection statements = Sets.newHashSet(\n vf.createStatement(vf.createURI(\"urn:apple\"), vf.createURI(\"urn:price\"), vf.createLiteral(2.50)),\n vf.createStatement(vf.createURI(\"urn:gum\"), vf.createURI(\"urn:price\"), vf.createLiteral(0.99)),\n vf.createStatement(vf.createURI(\"urn:sandwich\"), vf.createURI(\"urn:price\"), vf.createLiteral(4.99)));\n\n // Create the PCJ in Fluo and load the statements into Rya.\n final String pcjId = loadData(sparql, statements);\n\n // Create the expected results of the SPARQL query once the PCJ has been computed.\n final MapBindingSet expectedResult = new MapBindingSet();\n expectedResult.addBinding(\"maxPrice\", vf.createLiteral(4.99));\n\n // Ensure the last result matches the expected result.\n final VisibilityBindingSet result = readLastResult(pcjId);\n assertEquals(expectedResult, result);\n }\n\n @Test\n public void count() throws Exception {\n // A query that counts the number of unique items that are in the inventory.\n final String sparql =\n \"SELECT (count(?item) as ?itemCount) { \" +\n \"?item ?id . \" +\n \"}\";\n\n // Create the Statements that will be loaded into Rya.\n final ValueFactory vf = new ValueFactoryImpl();\n final Collection statements = Sets.newHashSet(\n // Three that are part of the count.\n vf.createStatement(vf.createURI(\"urn:apple\"), vf.createURI(\"urn:id\"), vf.createLiteral(UUID.randomUUID().toString())),\n vf.createStatement(vf.createURI(\"urn:gum\"), vf.createURI(\"urn:id\"), vf.createLiteral(UUID.randomUUID().toString())),\n vf.createStatement(vf.createURI(\"urn:sandwich\"), vf.createURI(\"urn:id\"), vf.createLiteral(UUID.randomUUID().toString())),\n\n // One that is not.\n vf.createStatement(vf.createURI(\"urn:sandwich\"), vf.createURI(\"urn:price\"), vf.createLiteral(3.99)));\n\n // Create the PCJ in Fluo and load the statements into Rya.\n final String pcjId = loadData(sparql, statements);\n\n // Create the expected results of the SPARQL query once the PCJ has been computed.\n final MapBindingSet expectedResult = new MapBindingSet();\n expectedResult.addBinding(\"itemCount\", vf.createLiteral(\"3\", XMLSchema.INTEGER));\n\n // Ensure the last result matches the expected result.\n final VisibilityBindingSet result = readLastResult(pcjId);\n assertEquals(expectedResult, result);\n }\n\n @Test\n public void sum() throws Exception {\n // A query that sums the counts of all of the items that are in the inventory.\n final String sparql =\n \"SELECT (sum(?count) as ?itemSum) { \" +\n \"?item ?count . \" +\n \"}\";\n\n // Create the Statements that will be loaded into Rya.\n final ValueFactory vf = new ValueFactoryImpl();\n final Collection statements = Sets.newHashSet(\n vf.createStatement(vf.createURI(\"urn:apple\"), vf.createURI(\"urn:count\"), vf.createLiteral(5)),\n vf.createStatement(vf.createURI(\"urn:gum\"), vf.createURI(\"urn:count\"), vf.createLiteral(7)),\n vf.createStatement(vf.createURI(\"urn:sandwich\"), vf.createURI(\"urn:count\"), vf.createLiteral(2)));\n\n // Create the PCJ in Fluo and load the statements into Rya.\n final String pcjId = loadData(sparql, statements);\n\n // Create the expected results of the SPARQL query once the PCJ has been computed.\n final MapBindingSet expectedResult = new MapBindingSet();\n expectedResult.addBinding(\"itemSum\", vf.createLiteral(\"14\", XMLSchema.INTEGER));\n\n // Ensure the last result matches the expected result.\n final VisibilityBindingSet result = readLastResult(pcjId);\n assertEquals(expectedResult, result);\n }\n\n @Test\n public void average() throws Exception {\n // A query that finds the average price for an item that is in the inventory.\n final String sparql =\n \"SELECT (avg(?price) as ?averagePrice) { \" +\n \"?item ?price . \" +\n \"}\";\n\n // Create the Statements that will be loaded into Rya.\n final ValueFactory vf = new ValueFactoryImpl();\n final Collection statements = Sets.newHashSet(\n vf.createStatement(vf.createURI(\"urn:apple\"), vf.createURI(\"urn:price\"), vf.createLiteral(3)),\n vf.createStatement(vf.createURI(\"urn:gum\"), vf.createURI(\"urn:price\"), vf.createLiteral(4)),\n vf.createStatement(vf.createURI(\"urn:sandwich\"), vf.createURI(\"urn:price\"), vf.createLiteral(8)));\n\n // Create the PCJ in Fluo and load the statements into Rya.\n final String pcjId = loadData(sparql, statements);\n\n // Create the expected results of the SPARQL query once the PCJ has been computed.\n final MapBindingSet expectedResult = new MapBindingSet();\n expectedResult.addBinding(\"averagePrice\", vf.createLiteral(\"5\", XMLSchema.DECIMAL));\n\n // Ensure the last result matches the expected result.\n final VisibilityBindingSet result = readLastResult(pcjId);\n assertEquals(expectedResult, result);\n }\n\n @Test\n public void aggregateWithFilter() throws Exception {\n // A query that filters results from a statement pattern before applying the aggregation function.\n final String sparql =\n \"SELECT (min(?price) as ?minPrice) { \" +\n \"FILTER(?price > 1.00) \" +\n \"?item ?price . \" +\n \"}\";\n\n // Create the Statements that will be loaded into Rya.\n final ValueFactory vf = new ValueFactoryImpl();\n final Collection statements = Sets.newHashSet(\n vf.createStatement(vf.createURI(\"urn:apple\"), vf.createURI(\"urn:price\"), vf.createLiteral(2.50)),\n vf.createStatement(vf.createURI(\"urn:gum\"), vf.createURI(\"urn:price\"), vf.createLiteral(0.99)),\n vf.createStatement(vf.createURI(\"urn:sandwich\"), vf.createURI(\"urn:price\"), vf.createLiteral(4.99)));\n\n // Create the PCJ in Fluo and load the statements into Rya.\n final String pcjId = loadData(sparql, statements);\n\n // Create the expected results of the SPARQL query once the PCJ has been computed.\n final MapBindingSet expectedResult = new MapBindingSet();\n expectedResult.addBinding(\"minPrice\", vf.createLiteral(2.50));\n\n // Ensure the last result matches the expected result.\n final VisibilityBindingSet result = readLastResult(pcjId);\n assertEquals(expectedResult, result);\n }\n\n @Test\n public void multipleAggregations() throws Exception {\n // A query that both counts the number of items being averaged and finds the average price.\n final String sparql =\n \"SELECT (count(?item) as ?itemCount) (avg(?price) as ?averagePrice) {\" +\n \"?item ?price . \" +\n \"}\";\n\n // Create the Statements that will be loaded into Rya.\n final ValueFactory vf = new ValueFactoryImpl();", "answers": [" final Collection statements = Sets.newHashSet("], "length": 1309, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "0e4e935b-e560-4b33-a576-46baafe45783", "reasoning": "The method is defining a test for multiple aggregations. Following the pattern of earlier tests, after creating the ValueFactory instance the next step is to define the collection of RDF statements to load. The code uses Guava's Sets.newHashSet to create the collection, so the next line should declare the statements variable with that call.", "reasoning_model_answer": "final Collection statements = Sets.newHashSet(", "assistant_with_reasoning": "\nThe method is defining a test for multiple aggregations. Following the pattern of earlier tests, after creating the ValueFactory instance the next step is to define the collection of RDF statements to load. The code uses Guava's Sets.newHashSet to create the collection, so the next line should declare the statements variable with that call.\n\nfinal Collection statements = Sets.newHashSet(", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 2.933, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 15489, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "final Collection statements = Sets.newHashSet(", "score": 0.93, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License. See License.txt in the project root for license information.\nusing Microsoft.Azure.Management.ResourceManager.Fluent.Core;\n\nnamespace Microsoft.Azure.Management.Compute.Fluent\n{\n ///

    \n /// Compute resource sku names.\n /// \n ///GENTHASH:Y29tLm1pY3Jvc29mdC5henVyZS5tYW5hZ2VtZW50LmNvbXB1dGUuQ29tcHV0ZVNrdU5hbWU=\n public partial class ComputeSkuName : ExpandableStringEnum, IBeta\n {\n /**\n * Static value Standard_F32s_v2 for ComputeSkuName.\n */\n public static readonly ComputeSkuName StandardF32sv2 = Parse(\"Standard_F32s_v2\");\n /**\n * Static value Standard_DS2_v2 for ComputeSkuName.\n */\n public static readonly ComputeSkuName StandardDS2v2 = Parse(\"Standard_DS2_v2\");\n /**\n * Static value Standard_H16r for ComputeSkuName.\n */\n public static readonly ComputeSkuName StandardH16r = Parse(\"Standard_H16r\");\n /**\n * Static value Standard_H16m for ComputeSkuName.\n */\n public static readonly ComputeSkuName StandardH16m = Parse(\"Standard_H16m\");\n /**\n * Static value Standard_D1 for ComputeSkuName.\n */\n public static readonly ComputeSkuName StandardD1 = Parse(\"Standard_D1\");\n /**\n * Static value Standard_F16s_v2 for ComputeSkuName.\n */\n public static readonly ComputeSkuName StandardF16sv2 = Parse(\"Standard_F16s_v2\");\n /**\n * Static value Standard_DS5_v2_Promo for ComputeSkuName.\n */\n public static readonly ComputeSkuName StandardDS5v2Promo = Parse(\"Standard_DS5_v2_Promo\");\n /**\n * Static value Standard_E4s_v3 for ComputeSkuName.\n */\n public static readonly ComputeSkuName StandardE4sv3 = Parse(\"Standard_E4s_v3\");\n /**\n * Static value Standard_D1_v2 for ComputeSkuName.\n */\n public static readonly ComputeSkuName StandardD1v2 = Parse(\"Standard_D1_v2\");\n /**\n * Static value Standard_DS12_v2_Promo for ComputeSkuName.\n */\n public static readonly ComputeSkuName StandardDS12v2Promo = Parse(\"Standard_DS12_v2_Promo\");\n /**\n * Static value Standard_D64s_v3 for ComputeSkuName.\n */\n public static readonly ComputeSkuName StandardD64sv3 = Parse(\"Standard_D64s_v3\");\n /**\n * Static value Standard_M128-32ms for ComputeSkuName.\n */\n public static readonly ComputeSkuName StandardM128_32ms = Parse(\"Standard_M128-32ms\");\n /**\n * Static value Standard_D4 for ComputeSkuName.\n */\n public static readonly ComputeSkuName StandardD4 = Parse(\"Standard_D4\");\n /**\n * Static value Standard_D3 for ComputeSkuName.\n */\n public static readonly ComputeSkuName StandardD3 = Parse(\"Standard_D3\");\n /**\n * Static value Standard_D2 for ComputeSkuName.\n */\n public static readonly ComputeSkuName StandardD2 = Parse(\"Standard_D2\");\n /**\n * Static value Standard_M128s for ComputeSkuName.\n */\n public static readonly ComputeSkuName StandardM128s = Parse(\"Standard_M128s\");\n /**\n * Static value Standard_D4s_v3 for ComputeSkuName.\n */\n public static readonly ComputeSkuName StandardD4sv3 = Parse(\"Standard_D4s_v3\");\n /**\n * Static value Standard_F2s_v2 for ComputeSkuName.\n */\n public static readonly ComputeSkuName StandardF2sv2 = Parse(\"Standard_F2s_v2\");\n /**\n * Static value Standard_F1s for ComputeSkuName.\n */\n public static readonly ComputeSkuName StandardF1s = Parse(\"Standard_F1s\");\n /**\n * Static value Standard_A8m_v2 for ComputeSkuName.\n */\n public static readonly ComputeSkuName StandardA8mv2 = Parse(\"Standard_A8m_v2\");\n /**\n * Static value Standard_NC24 for ComputeSkuName.\n */\n public static readonly ComputeSkuName StandardNC24 = Parse(\"Standard_NC24\");\n /**\n * Static value Standard_B1s for ComputeSkuName.\n */\n public static readonly ComputeSkuName StandardB1s = Parse(\"Standard_B1s\");\n /**\n * Static value Standard_E2s_v3 for ComputeSkuName.\n */\n public static readonly ComputeSkuName StandardE2sv3 = Parse(\"Standard_E2s_v3\");\n /**\n * Static value Standard_D8s_v3 for ComputeSkuName.\n */\n public static readonly ComputeSkuName StandardD8sv3 = Parse(\"Standard_D8s_v3\");\n /**\n * Static value Standard_DS14_v2 for ComputeSkuName.\n */\n public static readonly ComputeSkuName StandardDS14v2 = Parse(\"Standard_DS14_v2\");\n /**\n * Static value Standard_H16mr for ComputeSkuName.\n */\n public static readonly ComputeSkuName StandardH16mr = Parse(\"Standard_H16mr\");\n /**\n * Static value Standard_DS13_v2_Promo for ComputeSkuName.\n */\n public static readonly ComputeSkuName StandardDS13v2Promo = Parse(\"Standard_DS13_v2_Promo\");\n /**\n * Static value Standard_ND12s for ComputeSkuName.\n */\n public static readonly ComputeSkuName StandardND12s = Parse(\"Standard_ND12s\");\n /**\n * Static value Standard_DS5_v2 for ComputeSkuName.\n */\n public static readonly ComputeSkuName StandardDS5v2 = Parse(\"Standard_DS5_v2\");\n /**\n * Static value Standard_D15_v2 for ComputeSkuName.\n */\n public static readonly ComputeSkuName StandardD15v2 = Parse(\"Standard_D15_v2\");\n /**\n * Static value Standard_ND24s for ComputeSkuName.\n */\n public static readonly ComputeSkuName StandardND24s = Parse(\"Standard_ND24s\");\n /**\n * Static value Standard_F4s_v2 for ComputeSkuName.\n */\n public static readonly ComputeSkuName StandardF4sv2 = Parse(\"Standard_F4s_v2\");\n /**\n * Static value Standard_GS5-16 for ComputeSkuName.\n */\n public static readonly ComputeSkuName StandardGS5_16 = Parse(\"Standard_GS5-16\");\n /**\n * Static value Standard_F2s for ComputeSkuName.\n */\n public static readonly ComputeSkuName StandardF2s = Parse(\"Standard_F2s\");\n /**\n * Static value Standard_B2ms for ComputeSkuName.\n */\n public static readonly ComputeSkuName StandardB2ms = Parse(\"Standard_B2ms\");\n /**\n * Static value Standard_B2s for ComputeSkuName.\n */\n public static readonly ComputeSkuName StandardB2s = Parse(\"Standard_B2s\");\n /**\n * Static value Standard_E2_v3 for ComputeSkuName.\n */\n public static readonly ComputeSkuName StandardE2v3 = Parse(\"Standard_E2_v3\");\n /**\n * Static value Standard_A4_v2 for ComputeSkuName.\n */\n public static readonly ComputeSkuName StandardA4v2 = Parse(\"Standard_A4_v2\");\n /**\n * Static value Standard_DS4_v2 for ComputeSkuName.\n */\n public static readonly ComputeSkuName StandardDS4v2 = Parse(\"Standard_DS4_v2\");\n /**\n * Static value Standard_F8s for ComputeSkuName.\n */\n public static readonly ComputeSkuName StandardF8s = Parse(\"Standard_F8s\");\n /**\n * Static value Standard_D12_v2 for ComputeSkuName.\n */\n public static readonly ComputeSkuName StandardD12v2 = Parse(\"Standard_D12_v2\");\n /**\n * Static value Standard_A2m_v2 for ComputeSkuName.\n */\n public static readonly ComputeSkuName StandardA2mv2 = Parse(\"Standard_A2m_v2\");\n /**\n * Static value Standard_DS13-4_v2 for ComputeSkuName.\n */\n public static readonly ComputeSkuName StandardDS13_4v2 = Parse(\"Standard_DS13-4_v2\");\n /**\n * Static value Standard_M128ms for ComputeSkuName.\n */\n public static readonly ComputeSkuName StandardM128ms = Parse(\"Standard_M128ms\");\n /**\n * Static value Standard_DS15_v2 for ComputeSkuName.\n */\n public static readonly ComputeSkuName StandardDS15v2 = Parse(\"Standard_DS15_v2\");\n /**\n * Static value Standard_F2 for ComputeSkuName.\n */\n public static readonly ComputeSkuName StandardF2 = Parse(\"Standard_F2\");\n /**\n * Static value Standard_F1 for ComputeSkuName.\n */\n public static readonly ComputeSkuName StandardF1 = Parse(\"Standard_F1\");\n /**\n * Static value Standard_DS14_v2_Promo for ComputeSkuName.\n */\n public static readonly ComputeSkuName StandardDS14v2Promo = Parse(\"Standard_DS14_v2_Promo\");\n /**\n * Static value Standard_GS4-8 for ComputeSkuName.\n */\n public static readonly ComputeSkuName StandardGS4_8 = Parse(\"Standard_GS4-8\");\n /**\n * Static value Standard_E32-8s_v3 for ComputeSkuName.\n */\n public static readonly ComputeSkuName StandardE32_8sv3 = Parse(\"Standard_E32-8s_v3\");\n /**\n * Static value Standard_F8 for ComputeSkuName.\n */\n public static readonly ComputeSkuName StandardF8 = Parse(\"Standard_F8\");\n /**\n * Static value Standard_F16 for ComputeSkuName.\n */\n public static readonly ComputeSkuName StandardF16 = Parse(\"Standard_F16\");\n /**\n * Static value Standard_F4 for ComputeSkuName.\n */\n public static readonly ComputeSkuName StandardF4 = Parse(\"Standard_F4\");\n /**\n * Static value Standard_GS4-4 for ComputeSkuName.\n */\n public static readonly ComputeSkuName StandardGS4_4 = Parse(\"Standard_GS4-4\");\n /**\n * Static value Standard_F72s_v2 for ComputeSkuName.\n */\n public static readonly ComputeSkuName StandardF72sv2 = Parse(\"Standard_F72s_v2\");\n /**\n * Static value Standard_D16s_v3 for ComputeSkuName.\n */\n public static readonly ComputeSkuName StandardD16sv3 = Parse(\"Standard_D16s_v3\");\n /**\n * Static value Standard_D2_v2_Promo for ComputeSkuName.\n */\n public static readonly ComputeSkuName StandardD2v2Promo = Parse(\"Standard_D2_v2_Promo\");\n /**\n * Static value Standard_A1_v2 for ComputeSkuName.\n */\n public static readonly ComputeSkuName StandardA1v2 = Parse(\"Standard_A1_v2\");\n /**\n * Static value Standard_NC6 for ComputeSkuName.\n */\n public static readonly ComputeSkuName StandardNC6 = Parse(\"Standard_NC6\");\n /**\n * Static value Standard_E16s_v3 for ComputeSkuName.\n */\n public static readonly ComputeSkuName StandardE16sv3 = Parse(\"Standard_E16s_v3\");\n /**\n * Static value Standard_A10 for ComputeSkuName.\n */\n public static readonly ComputeSkuName StandardA10 = Parse(\"Standard_A10\");\n /**\n * Static value Standard_A4m_v2 for ComputeSkuName.\n */\n public static readonly ComputeSkuName StandardA4mv2 = Parse(\"Standard_A4m_v2\");\n /**\n * Static value Standard_A11 for ComputeSkuName.\n */\n public static readonly ComputeSkuName StandardA11 = Parse(\"Standard_A11\");\n /**\n * Static value Standard_DS12_v2 for ComputeSkuName.\n */\n public static readonly ComputeSkuName StandardDS12v2 = Parse(\"Standard_DS12_v2\");\n /**\n * Static value Standard_E16_v3 for ComputeSkuName.\n */\n public static readonly ComputeSkuName StandardE16v3 = Parse(\"Standard_E16_v3\");\n /**\n * Static value Standard_D4_v3 for ComputeSkuName.\n */\n public static readonly ComputeSkuName StandardD4v3 = Parse(\"Standard_D4_v3\");\n /**\n * Static value Standard_G4 for ComputeSkuName.\n */\n public static readonly ComputeSkuName StandardG4 = Parse(\"Standard_G4\");\n /**\n * Static value Standard_G3 for ComputeSkuName.\n */\n public static readonly ComputeSkuName StandardG3 = Parse(\"Standard_G3\");\n /**\n * Static value Standard_NC24s_v2 for ComputeSkuName.\n */\n public static readonly ComputeSkuName StandardNC24sv2 = Parse(\"Standard_NC24s_v2\");\n /**\n * Static value Standard_G2 for ComputeSkuName.\n */\n public static readonly ComputeSkuName StandardG2 = Parse(\"Standard_G2\");\n /**\n * Static value Classic for ComputeSkuName.\n */\n public static readonly ComputeSkuName Classic = Parse(\"Classic\");\n /**\n * Static value Standard_D4_v2 for ComputeSkuName.\n */\n public static readonly ComputeSkuName StandardD4v2 = Parse(\"Standard_D4_v2\");\n /**\n * Static value Standard_G1 for ComputeSkuName.\n */", "answers": [" public static readonly ComputeSkuName StandardG1 = Parse(\"Standard_G1\");"], "length": 1139, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "267c43d9-680d-411d-9897-69fc7f9a8d79", "reasoning": "The code defines a series of static readonly ComputeSkuName fields, each preceded by a comment describing the SKU. The pattern is a comment block, then a line like `public static readonly ComputeSkuName = Parse(\"\");`. The last comment shown is for `Standard_G1`. Following the established pattern, the next line should declare the corresponding static field using Parse with the same string.", "reasoning_model_answer": "public static readonly ComputeSkuName StandardG1 = Parse(\"Standard_G1\");", "assistant_with_reasoning": "\nThe code defines a series of static readonly ComputeSkuName fields, each preceded by a comment describing the SKU. The pattern is a comment block, then a line like `public static readonly ComputeSkuName = Parse(\"\");`. The last comment shown is for `Standard_G1`. Following the established pattern, the next line should declare the corresponding static field using Parse with the same string.\n\npublic static readonly ComputeSkuName StandardG1 = Parse(\"Standard_G1\");", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 2.029, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 13015, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "public static readonly ComputeSkuName StandardG1 = Parse(\"Standard_G1\");", "score": 0.95, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "// Copyright 2017, Google Inc. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n// Generated code. DO NOT EDIT!\n\nusing Google.Api.Gax;\nusing Google.Api.Gax.Grpc;\nusing Google.Cloud.Iam.V1;\nusing Google.Cloud.PubSub.V1;\nusing Google.Protobuf;\nusing Google.Protobuf.WellKnownTypes;\nusing Grpc.Core;\nusing System;\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.Linq;\nusing System.Threading;\nusing System.Threading.Tasks;\n\nnamespace Google.Cloud.PubSub.V1.Snippets\n{\n public class GeneratedPublisherClientSnippets\n {\n public async Task CreateTopicAsync()\n {\n // Snippet: CreateTopicAsync(TopicName,CallSettings)\n // Additional: CreateTopicAsync(TopicName,CancellationToken)\n // Create client\n PublisherClient publisherClient = await PublisherClient.CreateAsync();\n // Initialize request argument(s)\n TopicName name = new TopicName(\"[PROJECT]\", \"[TOPIC]\");\n // Make the request\n Topic response = await publisherClient.CreateTopicAsync(name);\n // End snippet\n }\n\n public void CreateTopic()\n {\n // Snippet: CreateTopic(TopicName,CallSettings)\n // Create client\n PublisherClient publisherClient = PublisherClient.Create();\n // Initialize request argument(s)\n TopicName name = new TopicName(\"[PROJECT]\", \"[TOPIC]\");\n // Make the request\n Topic response = publisherClient.CreateTopic(name);\n // End snippet\n }\n\n public async Task CreateTopicAsync_RequestObject()\n {\n // Snippet: CreateTopicAsync(Topic,CallSettings)\n // Create client\n PublisherClient publisherClient = await PublisherClient.CreateAsync();\n // Initialize request argument(s)\n Topic request = new Topic\n {\n TopicName = new TopicName(\"[PROJECT]\", \"[TOPIC]\"),\n };\n // Make the request\n Topic response = await publisherClient.CreateTopicAsync(request);\n // End snippet\n }\n\n public void CreateTopic_RequestObject()\n {\n // Snippet: CreateTopic(Topic,CallSettings)\n // Create client\n PublisherClient publisherClient = PublisherClient.Create();\n // Initialize request argument(s)\n Topic request = new Topic\n {\n TopicName = new TopicName(\"[PROJECT]\", \"[TOPIC]\"),\n };\n // Make the request\n Topic response = publisherClient.CreateTopic(request);\n // End snippet\n }\n\n public async Task PublishAsync()\n {\n // Snippet: PublishAsync(TopicName,IEnumerable,CallSettings)\n // Additional: PublishAsync(TopicName,IEnumerable,CancellationToken)\n // Create client\n PublisherClient publisherClient = await PublisherClient.CreateAsync();\n // Initialize request argument(s)\n TopicName topic = new TopicName(\"[PROJECT]\", \"[TOPIC]\");\n IEnumerable messages = new[]\n {\n new PubsubMessage\n {\n Data = ByteString.CopyFromUtf8(\"\"),\n },\n };\n // Make the request\n PublishResponse response = await publisherClient.PublishAsync(topic, messages);\n // End snippet\n }\n\n public void Publish()\n {\n // Snippet: Publish(TopicName,IEnumerable,CallSettings)\n // Create client\n PublisherClient publisherClient = PublisherClient.Create();\n // Initialize request argument(s)\n TopicName topic = new TopicName(\"[PROJECT]\", \"[TOPIC]\");\n IEnumerable messages = new[]\n {\n new PubsubMessage\n {\n Data = ByteString.CopyFromUtf8(\"\"),\n },\n };\n // Make the request\n PublishResponse response = publisherClient.Publish(topic, messages);\n // End snippet\n }\n\n public async Task PublishAsync_RequestObject()\n {\n // Snippet: PublishAsync(PublishRequest,CallSettings)\n // Create client\n PublisherClient publisherClient = await PublisherClient.CreateAsync();\n // Initialize request argument(s)\n PublishRequest request = new PublishRequest\n {\n TopicAsTopicName = new TopicName(\"[PROJECT]\", \"[TOPIC]\"),\n Messages = {\n new PubsubMessage\n {\n Data = ByteString.CopyFromUtf8(\"\"),\n },\n },\n };\n // Make the request\n PublishResponse response = await publisherClient.PublishAsync(request);\n // End snippet\n }\n\n public void Publish_RequestObject()\n {\n // Snippet: Publish(PublishRequest,CallSettings)\n // Create client\n PublisherClient publisherClient = PublisherClient.Create();\n // Initialize request argument(s)\n PublishRequest request = new PublishRequest\n {\n TopicAsTopicName = new TopicName(\"[PROJECT]\", \"[TOPIC]\"),\n Messages = {\n new PubsubMessage\n {\n Data = ByteString.CopyFromUtf8(\"\"),\n },\n },\n };\n // Make the request\n PublishResponse response = publisherClient.Publish(request);\n // End snippet\n }\n\n public async Task GetTopicAsync()\n {\n // Snippet: GetTopicAsync(TopicName,CallSettings)\n // Additional: GetTopicAsync(TopicName,CancellationToken)\n // Create client\n PublisherClient publisherClient = await PublisherClient.CreateAsync();\n // Initialize request argument(s)\n TopicName topic = new TopicName(\"[PROJECT]\", \"[TOPIC]\");\n // Make the request\n Topic response = await publisherClient.GetTopicAsync(topic);\n // End snippet\n }\n\n public void GetTopic()\n {\n // Snippet: GetTopic(TopicName,CallSettings)\n // Create client\n PublisherClient publisherClient = PublisherClient.Create();\n // Initialize request argument(s)\n TopicName topic = new TopicName(\"[PROJECT]\", \"[TOPIC]\");\n // Make the request\n Topic response = publisherClient.GetTopic(topic);\n // End snippet\n }\n\n public async Task GetTopicAsync_RequestObject()\n {\n // Snippet: GetTopicAsync(GetTopicRequest,CallSettings)\n // Create client\n PublisherClient publisherClient = await PublisherClient.CreateAsync();\n // Initialize request argument(s)\n GetTopicRequest request = new GetTopicRequest\n {\n TopicAsTopicName = new TopicName(\"[PROJECT]\", \"[TOPIC]\"),\n };\n // Make the request\n Topic response = await publisherClient.GetTopicAsync(request);\n // End snippet\n }\n\n public void GetTopic_RequestObject()\n {\n // Snippet: GetTopic(GetTopicRequest,CallSettings)\n // Create client\n PublisherClient publisherClient = PublisherClient.Create();\n // Initialize request argument(s)\n GetTopicRequest request = new GetTopicRequest\n {\n TopicAsTopicName = new TopicName(\"[PROJECT]\", \"[TOPIC]\"),\n };\n // Make the request\n Topic response = publisherClient.GetTopic(request);\n // End snippet\n }\n\n public async Task ListTopicsAsync()\n {\n // Snippet: ListTopicsAsync(ProjectName,string,int?,CallSettings)\n // Create client\n PublisherClient publisherClient = await PublisherClient.CreateAsync();\n // Initialize request argument(s)\n ProjectName project = new ProjectName(\"[PROJECT]\");\n // Make the request\n PagedAsyncEnumerable response =\n publisherClient.ListTopicsAsync(project);\n\n // Iterate over all response items, lazily performing RPCs as required\n await response.ForEachAsync((Topic item) =>\n {\n // Do something with each item\n Console.WriteLine(item);\n });\n\n // Or iterate over pages (of server-defined size), performing one RPC per page\n await response.AsRawResponses().ForEachAsync((ListTopicsResponse page) =>\n {\n // Do something with each page of items\n Console.WriteLine(\"A page of results:\");\n foreach (Topic item in page)\n {\n Console.WriteLine(item);\n }\n });\n\n // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required\n int pageSize = 10;\n Page singlePage = await response.ReadPageAsync(pageSize);\n // Do something with the page of items\n Console.WriteLine($\"A page of {pageSize} results (unless it's the final page):\");\n foreach (Topic item in singlePage)\n {\n Console.WriteLine(item);\n }\n // Store the pageToken, for when the next page is required.\n string nextPageToken = singlePage.NextPageToken;\n // End snippet\n }\n\n public void ListTopics()\n {\n // Snippet: ListTopics(ProjectName,string,int?,CallSettings)\n // Create client\n PublisherClient publisherClient = PublisherClient.Create();\n // Initialize request argument(s)\n ProjectName project = new ProjectName(\"[PROJECT]\");\n // Make the request\n PagedEnumerable response =\n publisherClient.ListTopics(project);\n\n // Iterate over all response items, lazily performing RPCs as required\n foreach (Topic item in response)\n {\n // Do something with each item\n Console.WriteLine(item);\n }\n\n // Or iterate over pages (of server-defined size), performing one RPC per page\n foreach (ListTopicsResponse page in response.AsRawResponses())\n {\n // Do something with each page of items\n Console.WriteLine(\"A page of results:\");\n foreach (Topic item in page)\n {\n Console.WriteLine(item);\n }\n }\n\n // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required\n int pageSize = 10;", "answers": [" Page singlePage = response.ReadPage(pageSize);"], "length": 981, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "976159ce-f986-4bbd-a30f-ed61d1f3f276", "reasoning": "The method ListTopics() mirrors the async version ListTopicsAsync(). After defining the pageSize variable, the next step is to retrieve a single page of results synchronously. In the async version they call response.ReadPageAsync(pageSize); the sync version uses response.ReadPage(pageSize). Therefore the next line is the synchronous page read statement.", "reasoning_model_answer": "Page singlePage = response.ReadPage(pageSize);", "assistant_with_reasoning": "\nThe method ListTopics() mirrors the async version ListTopicsAsync(). After defining the pageSize variable, the next step is to retrieve a single page of results synchronously. In the async version they call response.ReadPageAsync(pageSize); the sync version uses response.ReadPage(pageSize). Therefore the next line is the synchronous page read statement.\n\nPage singlePage = response.ReadPage(pageSize);", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 2.862, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 11871, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "Page singlePage = response.ReadPage(pageSize);", "score": 0.9, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/*\n * #%L\n * BroadleafCommerce Open Admin Platform\n * %%\n * Copyright (C) 2009 - 2013 Broadleaf Commerce\n * %%\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n * http://www.apache.org/licenses/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * #L%\n */\n\npackage org.broadleafcommerce.openadmin.web.form.entity;\n\nimport org.apache.commons.lang3.StringUtils;\nimport org.apache.commons.lang3.builder.CompareToBuilder;\nimport org.apache.commons.logging.Log;\nimport org.apache.commons.logging.LogFactory;\nimport org.broadleafcommerce.common.presentation.client.SupportedFieldType;\nimport org.broadleafcommerce.common.web.BroadleafRequestContext;\nimport org.broadleafcommerce.openadmin.dto.SectionCrumb;\nimport org.broadleafcommerce.openadmin.web.form.component.ListGrid;\n\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.Comparator;\nimport java.util.HashMap;\nimport java.util.Iterator;\nimport java.util.LinkedHashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Map.Entry;\nimport java.util.Set;\nimport java.util.TreeSet;\n\npublic class EntityForm {\n\n protected static final Log LOG = LogFactory.getLog(EntityForm.class);\n \n public static final String HIDDEN_GROUP = \"hiddenGroup\";\n public static final String MAP_KEY_GROUP = \"keyGroup\";\n public static final String DEFAULT_GROUP_NAME = \"Default\";\n public static final Integer DEFAULT_GROUP_ORDER = 99999;\n public static final String DEFAULT_TAB_NAME = \"General\";\n public static final Integer DEFAULT_TAB_ORDER = 100;\n\n protected String id;\n protected String parentId;\n protected String idProperty = \"id\";\n protected String ceilingEntityClassname;\n protected String entityType;\n protected String mainEntityName;\n protected String sectionKey;\n protected Boolean readOnly = false;\n \n protected String translationCeilingEntity;\n protected String translationId;\n \n protected Set tabs = new TreeSet(new Comparator() {\n @Override\n public int compare(Tab o1, Tab o2) {\n return new CompareToBuilder()\n .append(o1.getOrder(), o2.getOrder())\n .append(o1.getTitle(), o2.getTitle())\n .toComparison();\n }\n });\n protected List sectionCrumbs = new ArrayList();\n\n // This is used to data-bind when this entity form is submitted\n protected Map fields = null;\n \n // This is used in cases where there is a sub-form on this page that is dynamically\n // rendered based on other values on this entity form. It is keyed by the name of the\n // property that drives the dynamic form.\n protected Map dynamicForms = new LinkedHashMap();\n \n // These values are used when dynamic forms are in play. They are not rendered to the client,\n // but they can be used when performing actions on the submit event\n protected Map dynamicFormInfos = new LinkedHashMap();\n \n protected List actions = new ArrayList();\n\n protected Map attributes = new HashMap();\n\n /**\n * @return a flattened, field name keyed representation of all of \n * the fields in all of the groups for this form. This set will also includes all of the dynamic form\n * fields.\n * \n * Note that if there collisions between the dynamic form fields and the fields on this form (meaning that they\n * have the same name), then the dynamic form field will be excluded from the map and the preference will be given\n * to first-level entities\n * \n * @see {@link #getFields(boolean)}\n */\n public Map getFields() {\n if (fields == null) {\n Map map = new LinkedHashMap();\n for (Tab tab : tabs) {\n for (FieldGroup group : tab.getFieldGroups()) {\n for (Field field : group.getFields()) {\n map.put(field.getName(), field);\n }\n }\n }\n fields = map;\n }\n \n for (Entry entry : dynamicForms.entrySet()) {\n Map dynamicFormFields = entry.getValue().getFields();\n for (Entry dynamicField : dynamicFormFields.entrySet()) {\n if (fields.containsKey(dynamicField.getKey())) {\n LOG.info(\"Excluding dynamic field \" + dynamicField.getKey() + \" as there is already an occurrance in\" +\n \t\t\" this entityForm\");\n } else {\n fields.put(dynamicField.getKey(), dynamicField.getValue());\n }\n }\n }\n\n return fields;\n }\n \n /**\n * Clears out the cached 'fields' variable which is used to render the form on the frontend. Use this method\n * if you want to force the entityForm to rebuild itself based on the tabs and groups that have been assigned and \n * populated\n */\n public void clearFieldsMap() {\n fields = null;\n }\n \n public List getAllListGrids() {\n List list = new ArrayList();\n for (Tab tab : tabs) {\n for (ListGrid lg : tab.getListGrids()) {\n list.add(lg);\n }\n }\n return list;\n }\n \n /**\n * Convenience method for grabbing a grid by its collection field name. This is very similar to {@link #findField(String)}\n * but differs in that this only searches through the sub collections for the current entity\n * \n * @param collectionFieldName the field name of the collection on the top-level entity\n * @return\n */\n public ListGrid findListGrid(String collectionFieldName) {\n for (ListGrid grid : getAllListGrids()) {\n if (grid.getSubCollectionFieldName().equals(collectionFieldName)) {\n return grid;\n }\n }\n return null;\n }\n\n public Tab findTab(String tabTitle) {\n for (Tab tab : tabs) {\n if (tab.getTitle() != null && tab.getTitle().equals(tabTitle)) {\n return tab;\n }\n }\n return null;\n }\n \n public Tab findTabForField(String fieldName) {\n fieldName = sanitizeFieldName(fieldName);\n for (Tab tab : tabs) {\n for (FieldGroup fieldGroup : tab.getFieldGroups()) {\n for (Field field : fieldGroup.getFields()) {\n if (field.getName().equals(fieldName)) {\n return tab;\n }\n }\n }\n }\n return null;\n }\n\n public Field findField(String fieldName) {\n fieldName = sanitizeFieldName(fieldName);\n for (Tab tab : tabs) {\n for (FieldGroup fieldGroup : tab.getFieldGroups()) {\n for (Field field : fieldGroup.getFields()) {\n if (field.getName().equals(fieldName)) {\n return field;\n }\n }\n }\n }\n return null;\n }\n \n /**\n * Since this field name could come from the frontend (where all fields are referenced like fields[name].value,\n * we need to strip that part out to look up the real field name in this entity\n * @param fieldName\n * @return\n */\n public String sanitizeFieldName(String fieldName) {\n if (fieldName.contains(\"[\")) {\n fieldName = fieldName.substring(fieldName.indexOf('[') + 1, fieldName.indexOf(']'));\n }\n return fieldName;\n }\n\n public Field removeField(String fieldName) {\n Field fieldToRemove = null;\n FieldGroup containingGroup = null;\n\n findField: {\n for (Tab tab : tabs) {\n for (FieldGroup fieldGroup : tab.getFieldGroups()) {\n for (Field field : fieldGroup.getFields()) {\n if (field.getName().equals(fieldName)) {\n fieldToRemove = field;\n containingGroup = fieldGroup;\n break findField;\n }\n }\n }\n }\n }\n\n if (fieldToRemove != null) {\n containingGroup.removeField(fieldToRemove);\n }\n \n if (fields != null) {\n fieldToRemove = fields.remove(fieldName);\n }\n \n return fieldToRemove;\n }\n \n public void removeTab(Tab tab) {\n tabs.remove(tab);\n }\n \n public void removeTab(String tabName) {\n if (tabs != null) {\n Iterator tabIterator = tabs.iterator();\n while (tabIterator.hasNext()) {\n Tab currentTab = tabIterator.next();\n if (tabName.equals(currentTab.getTitle())) {\n tabIterator.remove();\n }\n }\n }\n }\n public ListGrid removeListGrid(String subCollectionFieldName) {\n ListGrid lgToRemove = null;\n Tab containingTab = null;\n\n findLg: {\n for (Tab tab : tabs) {\n for (ListGrid lg : tab.getListGrids()) {\n if (subCollectionFieldName.equals(lg.getSubCollectionFieldName())) {\n lgToRemove = lg;\n containingTab = tab;\n break findLg;\n }\n }\n }\n }\n\n if (lgToRemove != null) {\n containingTab.removeListGrid(lgToRemove);\n }\n \n if (containingTab.getListGrids().size() == 0 && containingTab.getFields().size() == 0) {\n removeTab(containingTab);\n }\n \n return lgToRemove;\n }\n\n public void addHiddenField(Field field) {\n if (StringUtils.isBlank(field.getFieldType())) {\n field.setFieldType(SupportedFieldType.HIDDEN.toString());\n }\n addField(field, HIDDEN_GROUP, DEFAULT_GROUP_ORDER, DEFAULT_TAB_NAME, DEFAULT_TAB_ORDER);\n }\n\n public void addField(Field field) {\n addField(field, DEFAULT_GROUP_NAME, DEFAULT_GROUP_ORDER, DEFAULT_TAB_NAME, DEFAULT_TAB_ORDER);\n }\n\n public void addMapKeyField(Field field) {\n addField(field, MAP_KEY_GROUP, 0, DEFAULT_TAB_NAME, DEFAULT_TAB_ORDER);\n }\n\n public void addField(Field field, String groupName, Integer groupOrder, String tabName, Integer tabOrder) {\n groupName = groupName == null ? DEFAULT_GROUP_NAME : groupName;\n groupOrder = groupOrder == null ? DEFAULT_GROUP_ORDER : groupOrder;\n tabName = tabName == null ? DEFAULT_TAB_NAME : tabName;\n tabOrder = tabOrder == null ? DEFAULT_TAB_ORDER : tabOrder;\n \n // Tabs and groups should be looked up by their display, translated name since 2 unique strings can display the same\n // thing when they are looked up in message bundles after display\n // When displayed on the form the duplicate groups and tabs look funny\n BroadleafRequestContext context = BroadleafRequestContext.getBroadleafRequestContext();\n if (context != null && context.getMessageSource() != null) {\n groupName = context.getMessageSource().getMessage(groupName, null, groupName, context.getJavaLocale());\n tabName = context.getMessageSource().getMessage(tabName, null, tabName, context.getJavaLocale());\n }\n \n Tab tab = findTab(tabName);\n if (tab == null) {\n tab = new Tab();\n tab.setTitle(tabName);\n tab.setOrder(tabOrder);\n tabs.add(tab);\n }\n\n FieldGroup fieldGroup = tab.findGroup(groupName);\n if (fieldGroup == null) {\n fieldGroup = new FieldGroup();\n fieldGroup.setTitle(groupName);\n fieldGroup.setOrder(groupOrder);\n tab.getFieldGroups().add(fieldGroup);\n }\n\n fieldGroup.addField(field);\n }\n\n public void addListGrid(ListGrid listGrid, String tabName, Integer tabOrder) {\n // Tabs should be looked up and referenced by their display name\n BroadleafRequestContext context = BroadleafRequestContext.getBroadleafRequestContext();\n if (context != null && context.getMessageSource() != null) {", "answers": [" tabName = context.getMessageSource().getMessage(tabName, null, tabName, context.getJavaLocale());"], "length": 1293, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "12959d4c-f049-4e29-a222-c4ad7158aae9", "reasoning": "The method addListGrid mirrors addField: after obtaining the BroadleafRequestContext it checks for a message source and then translates the provided tabName using the message source. The next line inside the if‑block should perform that translation, assigning the possibly localized name back to tabName.", "reasoning_model_answer": "tabName = context.getMessageSource().getMessage(tabName, null, tabName, context.getJavaLocale());", "assistant_with_reasoning": "\nThe method addListGrid mirrors addField: after obtaining the BroadleafRequestContext it checks for a message source and then translates the provided tabName using the message source. The next line inside the if‑block should perform that translation, assigning the possibly localized name back to tabName.\n\ntabName = context.getMessageSource().getMessage(tabName, null, tabName, context.getJavaLocale());", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.194, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 12924, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "tabName = context.getMessageSource().getMessage(tabName, null, tabName, context.getJavaLocale());", "score": 0.94, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "# Copyright 2016 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Tests for tensorflow.ops.resource_variable_ops.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport copy\nimport gc\nimport os\nimport pickle\n\nimport numpy as np\n\nfrom tensorflow.core.framework import tensor_pb2\nfrom tensorflow.python.eager import context\nfrom tensorflow.python.eager import def_function\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import cpp_shape_inference_pb2\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import errors\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework import tensor_shape\nfrom tensorflow.python.framework import tensor_util\nfrom tensorflow.python.framework import test_util\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import control_flow_ops\nfrom tensorflow.python.ops import custom_gradient\nfrom tensorflow.python.ops import gradients_impl\nfrom tensorflow.python.ops import init_ops\nfrom tensorflow.python.ops import list_ops\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops import resource_variable_ops\nfrom tensorflow.python.ops import state_ops\nfrom tensorflow.python.ops import variable_scope\nfrom tensorflow.python.ops import variables\nfrom tensorflow.python.platform import test\nfrom tensorflow.python.training import momentum\nfrom tensorflow.python.training import saver\nfrom tensorflow.python.training import training_util\nfrom tensorflow.python.util import compat\n\n\nclass ResourceVariableOpsTest(test_util.TensorFlowTestCase):\n\n def tearDown(self):\n gc.collect()\n # This will only contain uncollectable garbage, i.e. reference cycles\n # involving objects with __del__ defined.\n self.assertEqual(0, len(gc.garbage))\n\n @test_util.run_deprecated_v1\n def testHandleDtypeShapeMatch(self):\n with self.cached_session():\n handle = resource_variable_ops.var_handle_op(dtype=dtypes.int32, shape=[])\n with self.assertRaises(ValueError):\n resource_variable_ops.assign_variable_op(\n handle, constant_op.constant(0.0, dtype=dtypes.float32)).run()\n with self.assertRaises(ValueError):\n resource_variable_ops.assign_variable_op(handle,\n constant_op.constant(\n [0],\n dtype=dtypes.int32)).run()\n resource_variable_ops.assign_variable_op(handle,\n constant_op.constant(\n 0,\n dtype=dtypes.int32)).run()\n\n def testGPUInt64(self):\n if not context.context().num_gpus():\n return\n with context.eager_mode(), context.device(\"gpu:0\"):\n v = resource_variable_ops.ResourceVariable(1, dtype=dtypes.int64)\n self.assertAllEqual(1, v.numpy())\n\n def testEagerNameNotIdentity(self):\n with context.eager_mode():\n v0 = resource_variable_ops.ResourceVariable(1.0, name=\"a\")\n v1 = resource_variable_ops.ResourceVariable(2.0, name=\"a\")\n self.assertAllEqual(v0.numpy(), 1.0)\n self.assertAllEqual(v1.numpy(), 2.0)\n\n def testEagerNameNotNeeded(self):\n with context.eager_mode():\n v0 = resource_variable_ops.ResourceVariable(1.0)\n self.assertAllEqual(v0.numpy(), 1.0)\n\n def testReadVariableDtypeMismatchEager(self):\n with context.eager_mode():\n handle = resource_variable_ops.var_handle_op(\n dtype=dtypes.int32, shape=[1], name=\"foo\")\n resource_variable_ops.assign_variable_op(handle, 1)\n with self.assertRaisesRegexp(errors.InvalidArgumentError,\n \"Trying to read variable with wrong dtype. \"\n \"Expected float got int32.\"):\n _ = resource_variable_ops.read_variable_op(handle, dtype=dtypes.float32)\n\n def testEagerInitializedValue(self):\n with context.eager_mode():\n variable = resource_variable_ops.ResourceVariable(1.0, name=\"eager-init\")\n self.assertAllEqual(variable.numpy(), 1.0)\n self.assertAllEqual(variable.initialized_value().numpy(), 1.0)\n\n def testEagerBool(self):\n with context.eager_mode():\n v = resource_variable_ops.ResourceVariable(False, name=\"bool_test\")\n self.assertAllEqual(bool(v), False)\n\n def testEagerDeepCopy(self):\n with context.eager_mode():\n init_value = np.ones((4, 4, 4))\n variable = resource_variable_ops.ResourceVariable(init_value,\n name=\"init\")\n\n copied_variable = copy.deepcopy(variable)\n copied_variable.assign(4 * np.ones((4, 4, 4)))\n\n # Copying the variable should create a new underlying tensor with distinct\n # values.\n self.assertFalse(np.allclose(variable.numpy(), copied_variable.numpy()))\n\n @test_util.run_deprecated_v1\n def testGraphDeepCopy(self):\n with self.cached_session():\n init_value = np.ones((4, 4, 4))\n variable = resource_variable_ops.ResourceVariable(init_value,\n name=\"init\")\n with self.assertRaises(NotImplementedError):\n copy.deepcopy(variable)\n\n @test_util.run_in_graph_and_eager_modes\n def testStridedSliceAssign(self):\n v = resource_variable_ops.ResourceVariable([1.0, 2.0])\n self.evaluate(variables.global_variables_initializer())\n self.evaluate(v[0].assign(2.0))\n self.assertAllEqual(self.evaluate(v), [2.0, 2.0])\n\n @test_util.run_in_graph_and_eager_modes\n def testVariableShape(self):\n v = resource_variable_ops.ResourceVariable([1., 1.])\n self.assertAllEqual(\n tensor_util.constant_value(\n resource_variable_ops.variable_shape(v.handle)),\n [2])\n\n @test_util.run_deprecated_v1\n def testDifferentAssignGraph(self):\n with ops.Graph().as_default():\n v = resource_variable_ops.ResourceVariable(1.0)\n ops.reset_default_graph()\n v.assign(2.0) # Note: this fails if we run convert_to_tensor on not the\n # variable graph.\n\n @test_util.run_deprecated_v1\n def testFetchHandle(self):\n with self.cached_session():\n handle = resource_variable_ops.var_handle_op(\n dtype=dtypes.int32, shape=[1], name=\"foo\")\n self.assertGreater(len(handle.eval()), 0)\n\n @test_util.run_deprecated_v1\n def testCachedValueReadBeforeWrite(self):\n with self.cached_session() as sess:\n v = resource_variable_ops.ResourceVariable(0.0, caching_device=\"cpu:0\")\n self.evaluate(v.initializer)\n value, _ = sess.run([v, v.assign_add(1.0)])\n self.assertAllEqual(value, 0.0)\n\n def testAssignVariableDtypeMismatchEager(self):\n with context.eager_mode():\n handle = resource_variable_ops.var_handle_op(\n dtype=dtypes.int32, shape=[1], name=\"foo\")\n resource_variable_ops.assign_variable_op(\n handle, constant_op.constant([1]))\n with self.assertRaisesRegexp(errors.InvalidArgumentError,\n \"Trying to assign variable with wrong \"\n \"dtype. Expected int32 got float.\"):\n resource_variable_ops.assign_variable_op(\n handle, constant_op.constant([1.], dtype=dtypes.float32))\n\n def testUnprintableHandle(self):\n with context.eager_mode():\n handle = resource_variable_ops.var_handle_op(\n dtype=dtypes.int32, shape=[1], name=\"foo\")\n self.assertIn(\"\", str(handle))\n self.assertIn(\"\", repr(handle))\n\n @test_util.run_in_graph_and_eager_modes\n def testDtypeSurvivesIdentity(self):\n handle = resource_variable_ops.var_handle_op(dtype=dtypes.int32, shape=[])\n id_handle = array_ops.identity(handle)\n self.evaluate(resource_variable_ops.assign_variable_op(\n id_handle, constant_op.constant(0, dtype=dtypes.int32)))\n\n def testUnreadOpName(self):\n v = resource_variable_ops.ResourceVariable(1.0)\n self.assertNotEqual(v.name, v.assign_add(1.0).name)\n\n @test_util.run_in_graph_and_eager_modes\n def testCreateRead(self):\n handle = resource_variable_ops.var_handle_op(dtype=dtypes.int32, shape=[])\n self.evaluate(resource_variable_ops.assign_variable_op(\n handle, constant_op.constant(1, dtype=dtypes.int32)))\n value = self.evaluate(\n resource_variable_ops.read_variable_op(handle, dtype=dtypes.int32))\n self.assertAllEqual(1, value)\n\n @test_util.run_in_graph_and_eager_modes\n def testManyAssigns(self):\n handle = resource_variable_ops.var_handle_op(dtype=dtypes.int32, shape=[])\n create = resource_variable_ops.assign_variable_op(\n handle, constant_op.constant(1, dtype=dtypes.int32))\n with ops.control_dependencies([create]):\n first_read = resource_variable_ops.read_variable_op(\n handle, dtype=dtypes.int32)\n with ops.control_dependencies([first_read]):\n write = resource_variable_ops.assign_variable_op(\n handle, constant_op.constant(2, dtype=dtypes.int32))\n with ops.control_dependencies([write]):\n second_read = resource_variable_ops.read_variable_op(\n handle, dtype=dtypes.int32)\n f, s = self.evaluate([first_read, second_read])\n self.assertEqual(f, 1)\n self.assertEqual(s, 2)\n\n @test_util.run_in_graph_and_eager_modes\n def testAssignAdd(self):\n handle = resource_variable_ops.var_handle_op(dtype=dtypes.int32, shape=[])\n self.evaluate(resource_variable_ops.assign_variable_op(\n handle, constant_op.constant(1, dtype=dtypes.int32)))\n self.evaluate(resource_variable_ops.assign_add_variable_op(\n handle, constant_op.constant(1, dtype=dtypes.int32)))\n read = self.evaluate(\n resource_variable_ops.read_variable_op(handle, dtype=dtypes.int32))\n self.assertEqual(read, 2)\n\n @test_util.run_in_graph_and_eager_modes\n def testScatterAdd(self):\n handle = resource_variable_ops.var_handle_op(\n dtype=dtypes.int32, shape=[1, 1])\n self.evaluate(\n resource_variable_ops.assign_variable_op(\n handle, constant_op.constant([[1]], dtype=dtypes.int32)))\n self.evaluate(\n resource_variable_ops.resource_scatter_add(\n handle, [0], constant_op.constant([[2]], dtype=dtypes.int32)))\n read = resource_variable_ops.read_variable_op(handle, dtype=dtypes.int32)\n self.assertEqual(self.evaluate(read), [[3]])\n\n @test_util.run_in_graph_and_eager_modes\n def testScatterSub(self):\n handle = resource_variable_ops.var_handle_op(\n dtype=dtypes.int32, shape=[1, 1])\n self.evaluate(\n resource_variable_ops.assign_variable_op(\n handle, constant_op.constant([[1]], dtype=dtypes.int32)))\n self.evaluate(\n resource_variable_ops.resource_scatter_sub(\n handle, [0], constant_op.constant([[2]], dtype=dtypes.int32)))\n read = resource_variable_ops.read_variable_op(handle, dtype=dtypes.int32)\n self.assertEqual(self.evaluate(read), [[-1]])\n\n @test_util.run_in_graph_and_eager_modes\n def testScatterMul(self):\n handle = resource_variable_ops.var_handle_op(\n dtype=dtypes.int32, shape=[1, 1])\n self.evaluate(\n resource_variable_ops.assign_variable_op(\n handle, constant_op.constant([[1]], dtype=dtypes.int32)))\n self.evaluate(\n resource_variable_ops.resource_scatter_mul(\n handle, [0], constant_op.constant([[5]], dtype=dtypes.int32)))\n read = resource_variable_ops.read_variable_op(handle, dtype=dtypes.int32)\n self.assertEqual(self.evaluate(read), [[5]])\n\n def testEagerPickle(self):\n with context.eager_mode():\n tmp_dir = self.get_temp_dir()\n fname = os.path.join(tmp_dir, \"var.pickle\")\n with open(fname, \"wb\") as f:\n v = resource_variable_ops.ResourceVariable(\n 10.0,\n dtype=dtypes.float16,\n name=\"v\")\n pickle.dump(v, f)\n\n with open(fname, \"rb\") as f:\n new_v = pickle.load(f)\n self.assertEqual(new_v.name, v.name)\n self.assertEqual(new_v.shape, v.shape)\n self.assertEqual(new_v.dtype, v.dtype)\n self.assertEqual(new_v.trainable, v.trainable)\n self.assertAllEqual(new_v.numpy(), v.numpy())\n\n @test_util.run_in_graph_and_eager_modes\n def testScatterDiv(self):\n handle = resource_variable_ops.var_handle_op(\n dtype=dtypes.int32, shape=[1, 1])\n self.evaluate(\n resource_variable_ops.assign_variable_op(\n handle, constant_op.constant([[6]], dtype=dtypes.int32)))\n self.evaluate(\n resource_variable_ops.resource_scatter_div(\n handle, [0], constant_op.constant([[3]], dtype=dtypes.int32)))\n read = resource_variable_ops.read_variable_op(handle, dtype=dtypes.int32)\n self.assertEqual(self.evaluate(read), [[2]])\n\n def testUseResource(self):\n v = variables.VariableV1(1.0, use_resource=True)\n self.assertTrue(isinstance(v, resource_variable_ops.ResourceVariable))\n\n def testEagerNoUseResource(self):\n with context.eager_mode():\n v = variables.Variable(1.0)\n self.assertTrue(isinstance(v, resource_variable_ops.ResourceVariable))\n\n @test_util.run_in_graph_and_eager_modes\n def testScatterMin(self):\n with ops.device(\"cpu:0\"):\n handle = resource_variable_ops.var_handle_op(\n dtype=dtypes.int32, shape=[1, 1])\n self.evaluate(\n resource_variable_ops.assign_variable_op(handle,\n constant_op.constant(\n [[6]],\n dtype=dtypes.int32)))\n self.evaluate(\n resource_variable_ops.resource_scatter_min(handle, [0],\n constant_op.constant(\n [[3]],\n dtype=dtypes.int32)))\n read = resource_variable_ops.read_variable_op(handle, dtype=dtypes.int32)\n self.assertEqual(self.evaluate(read), [[3]])\n\n def testMetagraph(self):\n with ops.Graph().as_default():\n with variable_scope.variable_scope(\"foo\", use_resource=True):\n a = variable_scope.get_variable(\"a\", initializer=10.0)\n\n momentum.MomentumOptimizer(\n learning_rate=0.001, momentum=0.1).minimize(\n a,\n colocate_gradients_with_ops=True,\n global_step=training_util.get_or_create_global_step())\n\n graph = ops.get_default_graph()\n meta_graph_def = saver.export_meta_graph(graph=graph)\n\n with ops.Graph().as_default():\n saver.import_meta_graph(meta_graph_def, import_scope=\"\")\n meta_graph_two = saver.export_meta_graph(graph=graph)\n self.assertEqual(meta_graph_def, meta_graph_two)\n\n @test_util.run_in_graph_and_eager_modes\n def testScatterMax(self):\n handle = resource_variable_ops.var_handle_op(\n dtype=dtypes.int32, shape=[1, 1])\n self.evaluate(\n resource_variable_ops.assign_variable_op(\n handle, constant_op.constant([[6]], dtype=dtypes.int32)))\n self.evaluate(\n resource_variable_ops.resource_scatter_max(\n handle, [0], constant_op.constant([[3]], dtype=dtypes.int32)))\n read = resource_variable_ops.read_variable_op(handle, dtype=dtypes.int32)\n self.assertEqual(self.evaluate(read), [[6]])\n\n @test_util.run_in_graph_and_eager_modes\n def testScatterAddScalar(self):\n handle = resource_variable_ops.var_handle_op(\n dtype=dtypes.int32, shape=[1, 1])\n self.evaluate(\n resource_variable_ops.assign_variable_op(\n handle, constant_op.constant([[1]], dtype=dtypes.int32)))\n self.evaluate(\n resource_variable_ops.resource_scatter_add(\n handle, [0], constant_op.constant(2, dtype=dtypes.int32)))\n read = resource_variable_ops.read_variable_op(handle, dtype=dtypes.int32)\n self.assertEqual(self.evaluate(read), [[3]])\n\n @test_util.run_in_graph_and_eager_modes\n def testScatterSubScalar(self):\n handle = resource_variable_ops.var_handle_op(\n dtype=dtypes.int32, shape=[1, 1])\n self.evaluate(\n resource_variable_ops.assign_variable_op(\n handle, constant_op.constant([[1]], dtype=dtypes.int32)))\n self.evaluate(\n resource_variable_ops.resource_scatter_sub(\n handle, [0], constant_op.constant(2, dtype=dtypes.int32)))\n read = resource_variable_ops.read_variable_op(handle, dtype=dtypes.int32)\n self.assertEqual(self.evaluate(read), [[-1]])\n\n @test_util.run_in_graph_and_eager_modes\n def testScatterMulScalar(self):\n handle = resource_variable_ops.var_handle_op(\n dtype=dtypes.int32, shape=[1, 1])\n self.evaluate(\n resource_variable_ops.assign_variable_op(", "answers": [" handle, constant_op.constant([[1]], dtype=dtypes.int32)))"], "length": 976, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "c1de3cab-3189-4310-b0e4-28b42ba89a47", "reasoning": "The testScatterMulScalar method follows the pattern of other scalar scatter tests: it first assigns an initial value to the handle using assign_variable_op with a constant [[1]] of int32 type. The code snippet ends right after the opening of assign_variable_op, so the next line should provide the handle and constant arguments and close the parentheses.", "reasoning_model_answer": "handle, constant_op.constant([[1]], dtype=dtypes.int32)))", "assistant_with_reasoning": "\nThe testScatterMulScalar method follows the pattern of other scalar scatter tests: it first assigns an initial value to the handle using assign_variable_op with a constant [[1]] of int32 type. The code snippet ends right after the opening of assign_variable_op, so the next line should provide the handle and constant arguments and close the parentheses.\n\nhandle, constant_op.constant([[1]], dtype=dtypes.int32)))", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.617, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 17467, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "handle, constant_op.constant([[1]], dtype=dtypes.int32)))", "score": 0.9, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/*\n * Copyright 2014-2021 Lukas Krejci\n * and other contributors as indicated by the @author tags.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.revapi.configuration;\n\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.Reader;\nimport java.nio.ByteBuffer;\nimport java.nio.CharBuffer;\nimport java.nio.charset.Charset;\nimport java.nio.charset.CharsetEncoder;\nimport java.nio.charset.CoderResult;\nimport java.nio.charset.CodingErrorAction;\n\n/**\n * {@link InputStream} implementation that reads a character stream from a {@link Reader} and transforms it to a byte\n * stream using a specified charset encoding. The stream is transformed using a {@link CharsetEncoder} object,\n * guaranteeing that all charset encodings supported by the JRE are handled correctly. In particular for charsets such\n * as UTF-16, the implementation ensures that one and only one byte order marker is produced.\n *\n *

    \n * Since in general it is not possible to predict the number of characters to be read from the {@link Reader} to satisfy\n * a read request on the {@link ReaderInputStream}, all reads from the {@link Reader} are buffered. There is therefore\n * no well defined correlation between the current position of the {@link Reader} and that of the\n * {@link ReaderInputStream}. This also implies that in general there is no need to wrap the underlying {@link Reader}\n * in a {@link java.io.BufferedReader}.\n *\n *

    \n * {@link ReaderInputStream} implements the inverse transformation of {@link java.io.InputStreamReader}; in the\n * following example, reading from in2 would return the same byte sequence as reading from in\n * (provided that the initial byte sequence is legal with respect to the charset encoding):\n * \n *

    \n * InputStream in = ...\n * Charset cs = ...\n * InputStreamReader reader = new InputStreamReader(in, cs);\n * ReaderInputStream in2 = new ReaderInputStream(reader, cs);\n * 
    \n * \n * {@link ReaderInputStream} implements the same transformation as {@link java.io.OutputStreamWriter}, except that the\n * control flow is reversed: both classes transform a character stream into a byte stream, but\n * {@link java.io.OutputStreamWriter} pushes data to the underlying stream, while {@link ReaderInputStream} pulls it\n * from the underlying stream.\n *\n * Note that while there are use cases where there is no alternative to using this class, very often the need to use\n * this class is an indication of a flaw in the design of the code. This class is typically used in situations where an\n * existing API only accepts an {@link InputStream}, but where the most natural way to produce the data is as a\n * character stream, i.e. by providing a {@link Reader} instance. An example of a situation where this problem may\n * appear is when implementing the {@link javax.activation.DataSource} interface from the Java Activation Framework.\n *\n * Given the fact that the {@link Reader} class doesn't provide any way to predict whether the next read operation will\n * block or not, it is not possible to provide a meaningful implementation of the {@link InputStream#available()}\n * method. A call to this method will always return 0. Also, this class doesn't support {@link InputStream#mark(int)}.\n *\n * Instances of {@link ReaderInputStream} are not thread safe.\n *\n * @see org.apache.commons.io.output.WriterOutputStream\n * \n * @since 2.0\n * \n * @deprecated remove this once {@link JSONUtil#stripComments(InputStream, Charset)} is removed.\n */\n@Deprecated\nfinal class ReaderInputStream extends InputStream {\n private static final int DEFAULT_BUFFER_SIZE = 1024;\n\n private final Reader reader;\n private final CharsetEncoder encoder;\n\n /**\n * CharBuffer used as input for the decoder. It should be reasonably large as we read data from the underlying\n * Reader into this buffer.\n */\n private final CharBuffer encoderIn;\n\n /**\n * ByteBuffer used as output for the decoder. This buffer can be small as it is only used to transfer data from the\n * decoder to the buffer provided by the caller.\n */\n private final ByteBuffer encoderOut;\n\n private CoderResult lastCoderResult;\n private boolean endOfInput;\n\n /**\n * Construct a new {@link ReaderInputStream}.\n *\n * @param reader\n * the target {@link Reader}\n * @param encoder\n * the charset encoder\n *\n * @since 2.1\n */\n public ReaderInputStream(final Reader reader, final CharsetEncoder encoder) {\n this(reader, encoder, DEFAULT_BUFFER_SIZE);\n }\n\n /**\n * Construct a new {@link ReaderInputStream}.\n *\n * @param reader\n * the target {@link Reader}\n * @param encoder\n * the charset encoder\n * @param bufferSize\n * the size of the input buffer in number of characters\n *\n * @since 2.1\n */\n public ReaderInputStream(final Reader reader, final CharsetEncoder encoder, final int bufferSize) {\n this.reader = reader;\n this.encoder = encoder;\n this.encoderIn = CharBuffer.allocate(bufferSize);\n this.encoderIn.flip();\n this.encoderOut = ByteBuffer.allocate(128);\n this.encoderOut.flip();\n }\n\n /**\n * Construct a new {@link ReaderInputStream}.\n *\n * @param reader\n * the target {@link Reader}\n * @param charset\n * the charset encoding\n * @param bufferSize\n * the size of the input buffer in number of characters\n */\n public ReaderInputStream(final Reader reader, final Charset charset, final int bufferSize) {\n this(reader, charset.newEncoder().onMalformedInput(CodingErrorAction.REPLACE)\n .onUnmappableCharacter(CodingErrorAction.REPLACE), bufferSize);\n }\n\n /**\n * Construct a new {@link ReaderInputStream} with a default input buffer size of 1024 characters.\n *\n * @param reader\n * the target {@link Reader}\n * @param charset\n * the charset encoding\n */\n public ReaderInputStream(final Reader reader, final Charset charset) {", "answers": [" this(reader, charset, DEFAULT_BUFFER_SIZE);"], "length": 901, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "1c7d7b3a-fab5-4ed4-88c4-11b21a466a53", "reasoning": "The class defines several overloaded constructors. The last one takes a Reader and a Charset and should delegate to the three-argument constructor that also accepts a buffer size, using the default buffer size constant. Therefore the next line inside the constructor body is a call to the other constructor with DEFAULT_BUFFER_SIZE.", "reasoning_model_answer": "this(reader, charset, DEFAULT_BUFFER_SIZE);", "assistant_with_reasoning": "\nThe class defines several overloaded constructors. The last one takes a Reader and a Charset and should delegate to the three-argument constructor that also accepts a buffer size, using the default buffer size constant. Therefore the next line inside the constructor body is a call to the other constructor with DEFAULT_BUFFER_SIZE.\n\nthis(reader, charset, DEFAULT_BUFFER_SIZE);", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 2.27, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 6727, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "this(reader, charset, DEFAULT_BUFFER_SIZE);", "score": 0.91, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "from __future__ import absolute_import, division\nimport os\nimport traceback\nimport sys\n\nimport math\nimport urwid\n\nfrom netlib import odict\nfrom netlib.http import CONTENT_MISSING, Headers\nfrom . import common, grideditor, signals, searchable, tabs\nfrom . import flowdetailview\nfrom .. import utils, controller, contentviews\nfrom ..models import HTTPRequest, HTTPResponse, decoded\nfrom ..exceptions import ContentViewException\n\n\nclass SearchError(Exception):\n pass\n\n\ndef _mkhelp():\n text = []\n keys = [\n (\"A\", \"accept all intercepted flows\"),\n (\"a\", \"accept this intercepted flow\"),\n (\"b\", \"save request/response body\"),\n (\"D\", \"duplicate flow\"),\n (\"d\", \"delete flow\"),\n (\"E\", \"export\"),\n (\"e\", \"edit request/response\"),\n (\"f\", \"load full body data\"),\n (\"m\", \"change body display mode for this entity\"),\n (None,\n common.highlight_key(\"automatic\", \"a\") +\n [(\"text\", \": automatic detection\")]\n ),\n (None,\n common.highlight_key(\"hex\", \"e\") +\n [(\"text\", \": Hex\")]\n ),\n (None,\n common.highlight_key(\"html\", \"h\") +\n [(\"text\", \": HTML\")]\n ),\n (None,\n common.highlight_key(\"image\", \"i\") +\n [(\"text\", \": Image\")]\n ),\n (None,\n common.highlight_key(\"javascript\", \"j\") +\n [(\"text\", \": JavaScript\")]\n ),\n (None,\n common.highlight_key(\"json\", \"s\") +\n [(\"text\", \": JSON\")]\n ),\n (None,\n common.highlight_key(\"urlencoded\", \"u\") +\n [(\"text\", \": URL-encoded data\")]\n ),\n (None,\n common.highlight_key(\"raw\", \"r\") +\n [(\"text\", \": raw data\")]\n ),\n (None,\n common.highlight_key(\"xml\", \"x\") +\n [(\"text\", \": XML\")]\n ),\n (\"M\", \"change default body display mode\"),\n (\"p\", \"previous flow\"),\n (\"P\", \"copy response(content/headers) to clipboard\"),\n (\"r\", \"replay request\"),\n (\"V\", \"revert changes to request\"),\n (\"v\", \"view body in external viewer\"),\n (\"w\", \"save all flows matching current limit\"),\n (\"W\", \"save this flow\"),\n (\"x\", \"delete body\"),\n (\"z\", \"encode/decode a request/response\"),\n (\"tab\", \"next tab\"),\n (\"h, l\", \"previous tab, next tab\"),\n (\"space\", \"next flow\"),\n (\"|\", \"run script on this flow\"),\n (\"/\", \"search (case sensitive)\"),\n (\"n\", \"repeat search forward\"),\n (\"N\", \"repeat search backwards\"),\n ]\n text.extend(common.format_keyvals(keys, key=\"key\", val=\"text\", indent=4))\n return text\nhelp_context = _mkhelp()\n\nfooter = [\n ('heading_key', \"?\"), \":help \",\n ('heading_key', \"q\"), \":back \",\n]\n\n\nclass FlowViewHeader(urwid.WidgetWrap):\n\n def __init__(self, master, f):\n self.master, self.flow = master, f\n self._w = common.format_flow(\n f,\n False,\n extended=True,\n padding=0,\n hostheader=self.master.showhost\n )\n signals.flow_change.connect(self.sig_flow_change)\n\n def sig_flow_change(self, sender, flow):\n if flow == self.flow:\n self._w = common.format_flow(\n flow,\n False,\n extended=True,\n padding=0,\n hostheader=self.master.showhost\n )\n\n\ncache = utils.LRUCache(200)\n\nTAB_REQ = 0\nTAB_RESP = 1\n\n\nclass FlowView(tabs.Tabs):\n highlight_color = \"focusfield\"\n\n def __init__(self, master, state, flow, tab_offset):\n self.master, self.state, self.flow = master, state, flow\n tabs.Tabs.__init__(self,\n [\n (self.tab_request, self.view_request),\n (self.tab_response, self.view_response),\n (self.tab_details, self.view_details),\n ],\n tab_offset\n )\n self.show()\n self.last_displayed_body = None\n signals.flow_change.connect(self.sig_flow_change)\n\n def tab_request(self):\n if self.flow.intercepted and not self.flow.reply.acked and not self.flow.response:\n return \"Request intercepted\"\n else:\n return \"Request\"\n\n def tab_response(self):\n if self.flow.intercepted and not self.flow.reply.acked and self.flow.response:\n return \"Response intercepted\"\n else:\n return \"Response\"\n\n def tab_details(self):\n return \"Detail\"\n\n def view_request(self):\n return self.conn_text(self.flow.request)\n\n def view_response(self):\n return self.conn_text(self.flow.response)\n\n def view_details(self):\n return flowdetailview.flowdetails(self.state, self.flow)\n\n def sig_flow_change(self, sender, flow):\n if flow == self.flow:\n self.show()\n\n def content_view(self, viewmode, message):\n if message.content == CONTENT_MISSING:\n msg, body = \"\", [urwid.Text([(\"error\", \"[content missing]\")])]\n return msg, body\n else:\n full = self.state.get_flow_setting(\n self.flow,\n (self.tab_offset, \"fullcontents\"),\n False\n )\n if full:\n limit = sys.maxsize\n else:\n limit = contentviews.VIEW_CUTOFF\n return cache.get(\n self._get_content_view,\n viewmode,\n message,\n limit,\n (bytes(message.headers), message.content) # Cache invalidation\n )\n\n def _get_content_view(self, viewmode, message, max_lines, _):\n\n try:\n description, lines = contentviews.get_content_view(\n viewmode, message.content, headers=message.headers\n )\n except ContentViewException:\n s = \"Content viewer failed: \\n\" + traceback.format_exc()\n signals.add_event(s, \"error\")\n description, lines = contentviews.get_content_view(\n contentviews.get(\"Raw\"), message.content, headers=message.headers\n )\n description = description.replace(\"Raw\", \"Couldn't parse: falling back to Raw\")\n\n # Give hint that you have to tab for the response.\n if description == \"No content\" and isinstance(message, HTTPRequest):\n description = \"No request content (press tab to view response)\"\n\n # If the users has a wide terminal, he gets fewer lines; this should not be an issue.\n chars_per_line = 80\n max_chars = max_lines * chars_per_line\n total_chars = 0\n text_objects = []\n for line in lines:\n txt = []\n for (style, text) in line:\n if total_chars + len(text) > max_chars:\n text = text[:max_chars - total_chars]\n txt.append((style, text))\n total_chars += len(text)\n if total_chars == max_chars:\n break\n\n # round up to the next line.\n total_chars = int(math.ceil(total_chars / chars_per_line) * chars_per_line)\n\n text_objects.append(urwid.Text(txt))\n if total_chars == max_chars:\n text_objects.append(urwid.Text([\n (\"highlight\", \"Stopped displaying data after %d lines. Press \" % max_lines),\n (\"key\", \"f\"),\n (\"highlight\", \" to load all data.\")\n ]))\n break\n\n return description, text_objects\n\n def viewmode_get(self):\n override = self.state.get_flow_setting(\n self.flow,\n (self.tab_offset, \"prettyview\")\n )\n return self.state.default_body_view if override is None else override\n\n def conn_text(self, conn):\n if conn:\n txt = common.format_keyvals(\n [(h + \":\", v) for (h, v) in conn.headers.fields],\n key = \"header\",\n val = \"text\"\n )\n viewmode = self.viewmode_get()\n msg, body = self.content_view(viewmode, conn)\n\n cols = [\n urwid.Text(\n [\n (\"heading\", msg),\n ]\n ),\n urwid.Text(\n [\n \" \",\n ('heading', \"[\"),\n ('heading_key', \"m\"),\n ('heading', (\":%s]\" % viewmode.name)),\n ],\n align=\"right\"\n )\n ]\n title = urwid.AttrWrap(urwid.Columns(cols), \"heading\")\n\n txt.append(title)\n txt.extend(body)\n else:\n txt = [\n urwid.Text(\"\"),\n urwid.Text(\n [\n (\"highlight\", \"No response. Press \"),\n (\"key\", \"e\"),\n (\"highlight\", \" and edit any aspect to add one.\"),\n ]\n )\n ]\n return searchable.Searchable(self.state, txt)\n\n def set_method_raw(self, m):\n if m:\n self.flow.request.method = m\n signals.flow_change.send(self, flow = self.flow)\n\n def edit_method(self, m):\n if m == \"e\":\n signals.status_prompt.send(\n prompt = \"Method\",\n text = self.flow.request.method,\n callback = self.set_method_raw\n )\n else:\n for i in common.METHOD_OPTIONS:\n if i[1] == m:\n self.flow.request.method = i[0].upper()\n signals.flow_change.send(self, flow = self.flow)\n\n def set_url(self, url):\n request = self.flow.request\n try:\n request.url = str(url)\n except ValueError:\n return \"Invalid URL.\"\n signals.flow_change.send(self, flow = self.flow)\n\n def set_resp_code(self, code):\n response = self.flow.response\n try:\n response.status_code = int(code)\n except ValueError:\n return None\n import BaseHTTPServer\n if int(code) in BaseHTTPServer.BaseHTTPRequestHandler.responses:\n response.msg = BaseHTTPServer.BaseHTTPRequestHandler.responses[\n int(code)][0]\n signals.flow_change.send(self, flow = self.flow)\n\n def set_resp_msg(self, msg):\n response = self.flow.response\n response.msg = msg\n signals.flow_change.send(self, flow = self.flow)\n\n def set_headers(self, fields, conn):\n conn.headers = Headers(fields)\n signals.flow_change.send(self, flow = self.flow)\n\n def set_query(self, lst, conn):\n conn.set_query(odict.ODict(lst))\n signals.flow_change.send(self, flow = self.flow)\n\n def set_path_components(self, lst, conn):\n conn.set_path_components(lst)\n signals.flow_change.send(self, flow = self.flow)\n\n def set_form(self, lst, conn):\n conn.set_form_urlencoded(odict.ODict(lst))\n signals.flow_change.send(self, flow = self.flow)\n\n def edit_form(self, conn):\n self.master.view_grideditor(\n grideditor.URLEncodedFormEditor(\n self.master,\n conn.get_form_urlencoded().lst,\n self.set_form,\n conn\n )\n )\n\n def edit_form_confirm(self, key, conn):\n if key == \"y\":\n self.edit_form(conn)\n\n def set_cookies(self, lst, conn):\n od = odict.ODict(lst)\n conn.set_cookies(od)\n signals.flow_change.send(self, flow = self.flow)\n\n def set_setcookies(self, data, conn):\n conn.set_cookies(data)\n signals.flow_change.send(self, flow = self.flow)\n\n def edit(self, part):\n if self.tab_offset == TAB_REQ:\n message = self.flow.request\n else:\n if not self.flow.response:\n self.flow.response = HTTPResponse(\n self.flow.request.http_version,\n 200, \"OK\", Headers(), \"\"\n )\n self.flow.response.reply = controller.DummyReply()\n message = self.flow.response\n\n self.flow.backup()\n if message == self.flow.request and part == \"c\":\n self.master.view_grideditor(\n grideditor.CookieEditor(\n self.master,\n message.get_cookies().lst,\n self.set_cookies,\n message\n )\n )\n if message == self.flow.response and part == \"c\":\n self.master.view_grideditor(\n grideditor.SetCookieEditor(\n self.master,\n message.get_cookies(),\n self.set_setcookies,\n message\n )\n )\n if part == \"r\":\n with decoded(message):\n # Fix an issue caused by some editors when editing a\n # request/response body. Many editors make it hard to save a\n # file without a terminating newline on the last line. When\n # editing message bodies, this can cause problems. For now, I\n # just strip the newlines off the end of the body when we return\n # from an editor.\n c = self.master.spawn_editor(message.content or \"\")\n message.content = c.rstrip(\"\\n\")\n elif part == \"f\":\n if not message.get_form_urlencoded() and message.content:\n signals.status_prompt_onekey.send(\n prompt = \"Existing body is not a URL-encoded form. Clear and edit?\",\n keys = [\n (\"yes\", \"y\"),\n (\"no\", \"n\"),\n ],\n callback = self.edit_form_confirm,\n args = (message,)\n )\n else:\n self.edit_form(message)\n elif part == \"h\":\n self.master.view_grideditor(\n grideditor.HeaderEditor(\n self.master,\n message.headers.fields,\n self.set_headers,\n message\n )\n )\n elif part == \"p\":\n p = message.get_path_components()\n self.master.view_grideditor(\n grideditor.PathEditor(\n self.master,\n p,\n self.set_path_components,\n message\n )\n )\n elif part == \"q\":\n self.master.view_grideditor(\n grideditor.QueryEditor(\n self.master,\n message.get_query().lst,\n self.set_query, message\n )\n )\n elif part == \"u\":\n signals.status_prompt.send(\n prompt = \"URL\",\n text = message.url,\n callback = self.set_url\n )\n elif part == \"m\":\n signals.status_prompt_onekey.send(\n prompt = \"Method\",\n keys = common.METHOD_OPTIONS,\n callback = self.edit_method\n )\n elif part == \"o\":\n signals.status_prompt.send(\n prompt = \"Code\",\n text = str(message.status_code),\n callback = self.set_resp_code\n )\n elif part == \"m\":\n signals.status_prompt.send(\n prompt = \"Message\",\n text = message.msg,", "answers": [" callback = self.set_resp_msg"], "length": 1213, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "459da641-d075-4d78-8d60-a1e3deec2625", "reasoning": "The edit method handles different parts of a flow. For the 'm' part (response message), it calls signals.status_prompt.send with prompt and text arguments. The next argument should be the callback that updates the response message, which is the method set_resp_msg. Therefore the next line completes the function call by specifying the callback.", "reasoning_model_answer": "callback = self.set_resp_msg", "assistant_with_reasoning": "\nThe edit method handles different parts of a flow. For the 'm' part (response message), it calls signals.status_prompt.send with prompt and text arguments. The next argument should be the callback that updates the response message, which is the method set_resp_msg. Therefore the next line completes the function call by specifying the callback.\n\ncallback = self.set_resp_msg", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 5.813, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 15762, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "callback = self.set_resp_msg", "score": 0.78, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "from os import path\n\nfrom enigma import iPlayableService, iServiceInformation, eTimer, eServiceCenter, eServiceReference, eDVBDB\n\nfrom Screens.Screen import Screen\nfrom Screens.ChannelSelection import FLAG_IS_DEDICATED_3D\nfrom Components.About import about\nfrom Components.SystemInfo import SystemInfo\nfrom Components.ConfigList import ConfigListScreen\nfrom Components.config import config, configfile, getConfigListEntry, ConfigNothing\nfrom Components.Label import Label\nfrom Components.Sources.StaticText import StaticText\nfrom Components.Pixmap import Pixmap\nfrom Components.Sources.Boolean import Boolean\nfrom Components.ServiceEventTracker import ServiceEventTracker\nfrom Tools.Directories import resolveFilename, SCOPE_PLUGINS\nfrom Tools.HardwareInfo import HardwareInfo\nfrom Components.AVSwitch import iAVSwitch\n\nresolutionlabel = None\n\nclass VideoSetup(Screen, ConfigListScreen):\n\tdef __init__(self, session):\n\t\tScreen.__init__(self, session)\n\t\t# for the skin: first try VideoSetup, then Setup, this allows individual skinning\n\t\tself.skinName = [\"VideoSetup\",\"Setup\"]\n\t\tself.setup_title = _(\"Video settings\")\n\t\tself[\"HelpWindow\"] = Pixmap()\n\t\tself[\"HelpWindow\"].hide()\n\t\tself[\"VKeyIcon\"] = Boolean(False)\n\t\tself['footnote'] = Label()\n\n\t\tself.hw = iAVSwitch\n\t\tself.onChangedEntry = [ ]\n\n\t\t# handle hotplug by re-creating setup\n\t\tself.onShow.append(self.startHotplug)\n\t\tself.onHide.append(self.stopHotplug)\n\n\t\tself.list = [ ]\n\t\tConfigListScreen.__init__(self, self.list, session = session, on_change = self.changedEntry)\n\n\t\tfrom Components.ActionMap import ActionMap\n\t\tself[\"actions\"] = ActionMap([\"SetupActions\", \"MenuActions\"],\n\t\t\t{\n\t\t\t\t\"cancel\": self.keyCancel,\n\t\t\t\t\"save\": self.apply,\n\t\t\t\t\"menu\": self.closeRecursive,\n\t\t\t}, -2)\n\n\t\tself[\"key_red\"] = StaticText(_(\"Cancel\"))\n\t\tself[\"key_green\"] = StaticText(_(\"OK\"))\n\t\tself[\"description\"] = Label(\"\")\n\n\t\tself.createSetup()\n\t\tself.grabLastGoodMode()\n\t\tself.onLayoutFinish.append(self.layoutFinished)\n\n\tdef layoutFinished(self):\n\t\tself.setTitle(self.setup_title)\n\n\tdef startHotplug(self):\n\t\tself.hw.on_hotplug.append(self.createSetup)\n\n\tdef stopHotplug(self):\n\t\tself.hw.on_hotplug.remove(self.createSetup)\n\n\tdef createSetup(self):\n\t\tlevel = config.usage.setup_level.index\n\n\t\tself.list = [\n\t\t\tgetConfigListEntry(_(\"Video output\"), config.av.videoport, _(\"Configures which video output connector will be used.\"))\n\t\t]\n\t\tif config.av.videoport.value in ('HDMI', 'YPbPr', 'Scart-YPbPr') and not path.exists(resolveFilename(SCOPE_PLUGINS)+'SystemPlugins/AutoResolution'):\n\t\t\tself.list.append(getConfigListEntry(_(\"Automatic resolution\"), config.av.autores,_(\"If enabled the output resolution of the box will try to match the resolution of the video content\")))\n\t\t\tif config.av.autores.value in ('all', 'hd'):\n\t\t\t\tself.list.append(getConfigListEntry(_(\"Force de-interlace\"), config.av.autores_deinterlace,_(\"If enabled the video will always be de-interlaced.\")))\n\t\t\t\tself.list.append(getConfigListEntry(_(\"Automatic resolution label\"), config.av.autores_label_timeout,_(\"Allows you to adjust the amount of time the resolution infomation display on screen.\")))\n\t\t\t\tif config.av.autores.value in ('hd'):\n\t\t\t\t\tself.list.append(getConfigListEntry(_(\"Show SD as\"), config.av.autores_sd,_(\"This option allows you to choose how to display standard defintion video on your TV.\")))\n\t\t\t\tself.list.append(getConfigListEntry(_(\"Show 480/576p 24fps as\"), config.av.autores_480p24,_(\"This option allows you to choose how to display SD progressive 24Hz on your TV. (as not all TV's support these resolutions)\")))\n\t\t\t\tself.list.append(getConfigListEntry(_(\"Show 720p 24fps as\"), config.av.autores_720p24,_(\"This option allows you to choose how to display 720p 24Hz on your TV. (as not all TV's support these resolutions)\")))\n\t\t\t\tself.list.append(getConfigListEntry(_(\"Show 1080p 24fps as\"), config.av.autores_1080p24,_(\"This option allows you to choose how to display 1080p 24Hz on your TV. (as not all TV's support these resolutions)\")))\n\t\t\t\tself.list.append(getConfigListEntry(_(\"Show 1080p 25fps as\"), config.av.autores_1080p25,_(\"This option allows you to choose how to display 1080p 25Hz on your TV. (as not all TV's support these resolutions)\")))\n\t\t\t\tself.list.append(getConfigListEntry(_(\"Show 1080p 30fps as\"), config.av.autores_1080p30,_(\"This option allows you to choose how to display 1080p 30Hz on your TV. (as not all TV's support these resolutions)\")))\n\t\t\t\tif '2160p24' in iAVSwitch.readAvailableModes():\n\t\t\t\t\tself.list.append(getConfigListEntry(_(\"Show 2160p 24fps as\"), config.av.autores_2160p24,_(\"This option allows you to choose how to display 2160p 24Hz on your TV. (as not all TV's support these resolutions)\")))\n\t\t\t\t\tself.list.append(getConfigListEntry(_(\"Show 2160p 25fps as\"), config.av.autores_2160p25,_(\"This option allows you to choose how to display 2160p 25Hz on your TV. (as not all TV's support these resolutions)\")))\n\t\t\t\t\tself.list.append(getConfigListEntry(_(\"Show 2160p 30fps as\"), config.av.autores_2160p30,_(\"This option allows you to choose how to display 2160p 30Hz on your TV. (as not all TV's support these resolutions)\")))\n\n\t\t# if we have modes for this port:\n\t\tif (config.av.videoport.value in config.av.videomode and config.av.autores.value == 'disabled') or config.av.videoport.value == 'Scart':\n\t\t\t# add mode- and rate-selection:\n\t\t\tself.list.append(getConfigListEntry(pgettext(_(\"Video output mode\"), _(\"Mode\")), config.av.videomode[config.av.videoport.value], _(\"This option configures the video output mode (or resolution).\")))\n\t\t\tif config.av.videomode[config.av.videoport.value].value == 'PC':\n\t\t\t\tself.list.append(getConfigListEntry(_(\"Resolution\"), config.av.videorate[config.av.videomode[config.av.videoport.value].value], _(\"This option configures the screen resolution in PC output mode.\")))\n\t\t\telif config.av.videoport.value != 'Scart':\n\t\t\t\tself.list.append(getConfigListEntry(_(\"Refresh rate\"), config.av.videorate[config.av.videomode[config.av.videoport.value].value], _(\"Configure the refresh rate of the screen. Multi means refresh rate depends on the source 24/50/60Hz\")))\n\t\tif config.av.autores.value in ('all', 'hd') or config.av.videorate[config.av.videomode[config.av.videoport.value].value].value == 'multi':\n\t\t\tself.list.append(getConfigListEntry(_(\"Delay time\"), config.av.autores_delay,_(\"Set the time before checking video source for resolution/refresh rate infomation.\")))\n\n\t\tport = config.av.videoport.value\n\t\tif port not in config.av.videomode:\n\t\t\tmode = None\n\t\telse:\n\t\t\tmode = config.av.videomode[port].value\n\n\t\t# some modes (720p, 1080i) are always widescreen. Don't let the user select something here, \"auto\" is not what he wants.\n\t\tforce_wide = self.hw.isWidescreenMode(port, mode)\n\n#\t\tif not force_wide:\n#\t\t \tself.list.append(getConfigListEntry(_(\"Aspect ratio\"), config.av.aspect, _(\"Configure the aspect ratio of the screen.\")))\n\n\t\tif force_wide or config.av.aspect.value in (\"16:9\", \"16:10\"):\n\t\t\tself.list.extend((\n\t\t\t\tgetConfigListEntry(_(\"Display 4:3 content as\"), config.av.policy_43, _(\"When the content has an aspect ratio of 4:3, choose whether to scale/stretch the picture.\")),\n\t\t\t\tgetConfigListEntry(_(\"Display >16:9 content as\"), config.av.policy_169, _(\"When the content has an aspect ratio of 16:9, choose whether to scale/stretch the picture.\"))\n\t\t\t))\n\t\telif config.av.aspect.value == \"4:3\":\n\t\t\tself.list.append(getConfigListEntry(_(\"Display 16:9 content as\"), config.av.policy_169, _(\"When the content has an aspect ratio of 16:9, choose whether to scale/stretch the picture.\")))\n\n#\t\tif config.av.videoport.value == \"HDMI\":\n#\t\t\tself.list.append(getConfigListEntry(_(\"Allow unsupported modes\"), config.av.edid_override))\n\t\tif config.av.videoport.value == \"Scart\":\n\t\t\tself.list.append(getConfigListEntry(_(\"Color format\"), config.av.colorformat, _(\"Configure which color format should be used on the SCART output.\")))\n\t\t\tif level >= 1:\n\t\t\t\tself.list.append(getConfigListEntry(_(\"WSS on 4:3\"), config.av.wss, _(\"When enabled, content with an aspect ratio of 4:3 will be stretched to fit the screen.\")))\n\t\t\t\tif SystemInfo[\"ScartSwitch\"]:\n\t\t\t\t\tself.list.append(getConfigListEntry(_(\"Auto scart switching\"), config.av.vcrswitch, _(\"When enabled, your receiver will detect activity on the VCR SCART input.\")))\n\n\t\tif not isinstance(config.av.scaler_sharpness, ConfigNothing) and not path.exists(\"/usr/lib/enigma2/python/Plugins/SystemPlugins/VideoEnhancement/plugin.pyo\"):\n\t\t\tself.list.append(getConfigListEntry(_(\"Scaler sharpness\"), config.av.scaler_sharpness, _(\"This option configures the picture sharpness.\")))\n\n\t\tif SystemInfo[\"havecolorspace\"]:\n\t\t\tself.list.append(getConfigListEntry(_(\"HDMI Colorspace\"), config.av.hdmicolorspace,_(\"This option allows you can config the Colorspace from Auto to RGB\")))\n\n\t\tif SystemInfo[\"havecolorimetry\"]:\n\t\t\tself.list.append(getConfigListEntry(_(\"HDMI Colorimetry\"), config.av.hdmicolorimetry,_(\"This option allows you can config the Colorimetry for HDR\")))\n\n\t\tif SystemInfo[\"havehdmicolordepth\"]:\n\t\t\tself.list.append(getConfigListEntry(_(\"HDMI Colordepth\"), config.av.hdmicolordepth,_(\"This option allows you can config the Colordepth for UHD\")))\n\n\t\tif SystemInfo[\"Canedidchecking\"]:\n\t\t\tself.list.append(getConfigListEntry(_(\"Bypass HDMI EDID Check\"), config.av.bypass_edid_checking,_(\"This option allows you to bypass HDMI EDID check\")))\n\n\t\tif SystemInfo[\"haveboxmode\"]:\n\t\t\tself.list.append(getConfigListEntry(_(\"Change Boxmode to control Hardware Chip Modes*\"), config.av.boxmode,_(\"Switch Mode to enable HDR Modes or PIP Functions\")))\n\n\t\tself[\"config\"].list = self.list\n\t\tself[\"config\"].l.setList(self.list)\n\t\tif config.usage.sort_settings.value:\n\t\t\tself[\"config\"].list.sort()\n\n\tdef keyLeft(self):\n\t\tConfigListScreen.keyLeft(self)\n\t\tself.createSetup()\n\n\tdef keyRight(self):\n\t\tConfigListScreen.keyRight(self)\n\t\tself.createSetup()\n\n\tdef confirm(self, confirmed):\n\t\tif not confirmed:\n\t\t\tconfig.av.videoport.setValue(self.last_good[0])\n\t\t\tconfig.av.videomode[self.last_good[0]].setValue(self.last_good[1])\n\t\t\tconfig.av.videorate[self.last_good[1]].setValue(self.last_good[2])\n\t\t\tself.hw.setMode(*self.last_good)\n\t\telse:\n\t\t\tself.keySave()\n\n\tdef grabLastGoodMode(self):\n\t\tport = config.av.videoport.value\n\t\tmode = config.av.videomode[port].value\n\t\trate = config.av.videorate[mode].value\n\t\tself.last_good = (port, mode, rate)\n\n\tdef saveAll(self):\n\t\tif config.av.videoport.value == 'Scart':\n\t\t\tconfig.av.autores.setValue('disabled')\n\t\tfor x in self[\"config\"].list:\n\t\t\tx[1].save()\n\t\tconfigfile.save()\n\n\tdef apply(self):\n\t\tport = config.av.videoport.value\n\t\tmode = config.av.videomode[port].value\n\t\trate = config.av.videorate[mode].value\n\t\tif (port, mode, rate) != self.last_good:\n\t\t\tself.hw.setMode(port, mode, rate)\n\t\t\tfrom Screens.MessageBox import MessageBox\n\t\t\tself.session.openWithCallback(self.confirm, MessageBox, _(\"Is this video mode ok?\"), MessageBox.TYPE_YESNO, timeout = 20, default = False)\n\t\telse:\n\t\t\tself.keySave()\n\n\t# for summary:\n\tdef changedEntry(self):\n\t\tfor x in self.onChangedEntry:\n\t\t\tx()\n\n\tdef getCurrentEntry(self):\n\t\treturn self[\"config\"].getCurrent()[0]\n\n\tdef getCurrentValue(self):\n\t\treturn str(self[\"config\"].getCurrent()[1].getText())\n\n\tdef getCurrentDescription(self):\n\t\treturn self[\"config\"].getCurrent() and len(self[\"config\"].getCurrent()) > 2 and self[\"config\"].getCurrent()[2] or \"\"\n\n\tdef createSummary(self):\n\t\tfrom Screens.Setup import SetupSummary", "answers": ["\t\treturn SetupSummary"], "length": 1015, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "75cc59b1-6393-49fc-a78f-1dec6175337b", "reasoning": "The createSummary method should provide the summary screen class for the setup UI. After importing SetupSummary from Screens.Setup, the next logical line returns that class so the framework can use it. Hence the next line is: return SetupSummary", "reasoning_model_answer": "return SetupSummary", "assistant_with_reasoning": "\nThe createSummary method should provide the summary screen class for the setup UI. After importing SetupSummary from Screens.Setup, the next logical line returns that class so the framework can use it. Hence the next line is: return SetupSummary\n\nreturn SetupSummary", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 2.593, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 11435, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "return SetupSummary", "score": 0.95, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied. See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport shutil\nimport subprocess\nimport tempfile\nimport urllib\nfrom distutils.dir_util import copy_tree\nfrom threading import current_thread\n\nimport os\nimport time\nfrom config import Config\nfrom exception import GitRepositorySynchronizationException\nfrom git import *\n\nfrom ...util.asyncscheduledtask import AbstractAsyncScheduledTask, ScheduledExecutor\nfrom ...util.log import LogFactory\n\n\nclass AgentGitHandler:\n \"\"\"\n Handles all the git artifact management tasks related to a cartridge\n \"\"\"\n\n def __init__(self):\n pass\n\n log = LogFactory().get_log(__name__)\n\n __git_repositories = {}\n\n # (tenant_id => GitRepository)\n\n @staticmethod\n def sync_initial_local_artifacts(git_repo):\n # init git repo\n AgentGitHandler.init(git_repo.local_repo_path)\n\n # add remote repos\n return AgentGitHandler.add_remote(git_repo)\n\n @staticmethod\n def add_remote(git_repo):\n # add origin remote\n output, errors = AgentGitHandler.execute_git_command([\"remote\", \"add\", \"origin\", git_repo.repo_url],\n git_repo.local_repo_path)\n if len(output) > 0:\n raise GitRepositorySynchronizationException(\"Error in adding remote origin %s for local repository %s\"\n % (git_repo.repo_url, git_repo.local_repo_path))\n\n # fetch\n output, errors = AgentGitHandler.execute_git_command([\"fetch\"], git_repo.local_repo_path)\n if \"Resolving deltas: 100%\" not in output:\n raise GitRepositorySynchronizationException(\n \"Error in fetching from remote origin %s for local repository %s\"\n % (git_repo.repo_url, git_repo.local_repo_path))\n\n # checkout master\n output, errors = AgentGitHandler.execute_git_command([\"checkout\", \"master\"], git_repo.local_repo_path)\n if \"Branch master set up to track remote branch master from origin.\" not in output:\n raise GitRepositorySynchronizationException(\"Error in checking out master branch %s for local repository %s\"\n % (git_repo.repo_url, git_repo.local_repo_path))\n\n return True\n\n @staticmethod\n def init(path):\n output, errors = AgentGitHandler.execute_git_command([\"init\"], path)\n if \"Initialized empty Git repository in\" not in output:\n AgentGitHandler.log.exception(\"Initializing local repo at %s failed: %s\" % (path, output))\n raise Exception(\"Initializing local repo at %s failed\" % path)\n\n @staticmethod\n def is_valid_git_repository(git_repo):\n output, errors = AgentGitHandler.execute_git_command([\"show-ref\"], git_repo.local_repo_path)\n if len(output) > 0:\n refs = output.split(\"\\n\")\n for ref in refs:\n ref = ref.strip()\n if len(ref) > 0:\n ref = ref.split(\" \")\n try:\n AgentGitHandler.execute_git_command([\"show\", ref[0].strip()], git_repo.local_repo_path)\n except RuntimeError:\n return False\n return True\n else:\n return False\n\n @staticmethod\n def pull(git_repo):\n # check if modified files are present\n modified = AgentGitHandler.has_modified_files(git_repo.local_repo_path)\n if modified:\n if Config.is_commits_enabled:\n AgentGitHandler.log.debug(\n \"Un-staged files exist in working directory. Aborting git pull for this iteration...\")\n return\n else:\n AgentGitHandler.log.warn(\"Changes detected in working directory but COMMIT_ENABLED is set to false!\")\n AgentGitHandler.log.warn(\"Attempting to reset the working directory\")\n AgentGitHandler.execute_git_command([\"reset\"], repo_path=git_repo.local_repo_path)\n\n # HEAD before pull\n (init_head, init_errors) = AgentGitHandler.execute_git_command([\"rev-parse\", \"HEAD\"], git_repo.local_repo_path)\n\n repo = Repo(git_repo.local_repo_path)\n AgentGitHandler.execute_git_command([\"pull\", \"--rebase\", \"origin\", git_repo.branch], git_repo.local_repo_path)\n AgentGitHandler.log.debug(\"Git pull rebase executed in checkout job\")\n if repo.is_dirty():\n AgentGitHandler.log.error(\"Git pull operation in checkout job left the repository in dirty state\")\n AgentGitHandler.log.error(\n \"Git pull operation on remote %s for tenant %s failed\" % (git_repo.repo_url, git_repo.tenant_id))\n\n # HEAD after pull\n (end_head, end_errors) = AgentGitHandler.execute_git_command([\"rev-parse\", \"HEAD\"], git_repo.local_repo_path)\n\n # check if HEAD was updated\n if init_head != end_head:\n AgentGitHandler.log.debug(\"Artifacts were updated as a result of the pull operation, thread: %s - %s\" %\n (current_thread().getName(), current_thread().ident))\n\n return True\n else:\n return False\n\n @staticmethod\n def clone(git_repo):\n try:\n # create a temporary location to clone\n temp_repo_path = os.path.join(tempfile.gettempdir(), \"pca_temp_\" + git_repo.tenant_id)\n if os.path.isdir(temp_repo_path) and os.listdir(temp_repo_path) != []:\n GitUtils.delete_folder_tree(temp_repo_path)\n GitUtils.create_dir(temp_repo_path)\n\n # clone the repo to a temporary location first to avoid conflicts\n AgentGitHandler.log.debug(\n \"Cloning artifacts from URL: %s to temp location: %s\" % (git_repo.repo_url, temp_repo_path))\n Repo.clone_from(git_repo.auth_url, temp_repo_path, branch=git_repo.branch)\n\n # move the cloned dir to application path\n copy_tree(temp_repo_path, git_repo.local_repo_path)\n AgentGitHandler.log.info(\"Git clone operation for tenant %s successful\" % git_repo.tenant_id)\n return git_repo\n except GitCommandError as e:\n raise GitRepositorySynchronizationException(\"Error while cloning repository for tenant %s: %s\" % (\n git_repo.tenant_id, e))\n\n # @staticmethod\n # def checkout_remote_branch(git_repo):\n # try:\n # # create a temporary location to clone\n # temp_repo_path = os.path.join(tempfile.gettempdir(), \"pca_temp_\" + git_repo.tenant_id)\n # if os.path.isdir(temp_repo_path) and os.listdir(temp_repo_path) != []:\n # GitUtils.delete_folder_tree(temp_repo_path)\n # GitUtils.create_dir(temp_repo_path)\n #\n # # clone the repo to a temporary location first to avoid conflicts\n # AgentGitHandler.log.debug(\n # \"Cloning artifacts from URL: %s to temp location: %s\" % (git_repo.repo_url, temp_repo_path))\n # Repo.clone_from(git_repo.auth_url, temp_repo_path)\n #\n # local_repo = Repo.init(temp_repo_path)\n # origin = local_repo.create_remote('origin', local_repo.auth_url)\n # assert origin.exists()\n # # branch name = \"tenant_\"\n # origin.fetch(\"+refs/heads/\" + git_repo.branch + \":refs/remotes/origin/\" + git_repo.branch)\n # AgentGitHandler.execute_git_command([\"checkout\", git_repo.branch], temp_repo_path)\n #\n # # move the cloned dir to application path\n # copy_tree(temp_repo_path, git_repo.local_repo_path)\n # AgentGitHandler.log.info(\"Git clone operation for tenant %s successful\" % git_repo.tenant_id)\n # return git_repo\n # except GitCommandError as e:\n # raise GitRepositorySynchronizationException(\"Error while cloning repository for tenant %s: %s\" % (\n # git_repo.tenant_id, e))\n\n @staticmethod\n def retry_clone(git_repo):\n \"\"\"Retry 'git clone' operation for defined number of attempts with defined intervals\n \"\"\"\n git_clone_successful = False\n # Read properties from agent.conf\n max_retry_attempts = int(Config.artifact_clone_retry_count)\n retry_interval = int(Config.artifact_clone_retry_interval)\n retry_attempts = 0\n\n # Iterate until git clone is successful or reaches max retry attempts\n while git_clone_successful is False and retry_attempts < max_retry_attempts:\n try:\n retry_attempts += 1\n AgentGitHandler.clone(git_repo)\n AgentGitHandler.log.info(\n \"Retrying attempt to git clone operation for tenant %s successful\" % git_repo.tenant_id)\n git_clone_successful = True\n except GitRepositorySynchronizationException as e:\n AgentGitHandler.log.exception(\"Retrying git clone attempt %s failed: %s\" % (retry_attempts, e))\n if retry_attempts < max_retry_attempts:\n time.sleep(retry_interval)\n else:\n raise GitRepositorySynchronizationException(\"All attempts failed while retrying git clone: %s\"\n % e)\n\n @staticmethod\n def add_repo(git_repo):\n AgentGitHandler.__git_repositories[git_repo.tenant_id] = git_repo\n\n @staticmethod\n def get_repo(tenant_id):\n \"\"\"\n\n :param int tenant_id:\n :return: GitRepository object\n :rtype: GitRepository\n \"\"\"\n tenant_id = str(tenant_id)\n if tenant_id in AgentGitHandler.__git_repositories:\n return AgentGitHandler.__git_repositories[tenant_id]\n\n return None\n", "answers": [" @staticmethod"], "length": 913, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "a51001f0-d03c-418e-8438-58dbcd333f1b", "reasoning": "The class AgentGitHandler defines several static utility methods. After the get_repo method, the next logical addition is another static method (e.g., to remove a repository). In Python, a new static method begins with the @staticmethod decorator at the same indentation level as the previous methods. Therefore the next line of code is the decorator line for the upcoming method.", "reasoning_model_answer": "@staticmethod", "assistant_with_reasoning": "\nThe class AgentGitHandler defines several static utility methods. After the get_repo method, the next logical addition is another static method (e.g., to remove a repository). In Python, a new static method begins with the @staticmethod decorator at the same indentation level as the previous methods. Therefore the next line of code is the decorator line for the upcoming method.\n\n@staticmethod", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.817, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 10616, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "@staticmethod", "score": 0.87, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/**\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.apache.xbean.propertyeditor;\n\nimport static org.apache.xbean.recipe.RecipeHelper.getTypeParameters;\nimport static org.apache.xbean.recipe.RecipeHelper.*;\nimport org.apache.xbean.recipe.RecipeHelper;\n\nimport java.beans.PropertyEditor;\nimport java.beans.PropertyEditorManager;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.Collection;\nimport java.util.SortedSet;\nimport java.util.Set;\nimport java.util.TreeSet;\nimport java.util.LinkedHashSet;\nimport java.util.ArrayList;\nimport java.util.SortedMap;\nimport java.util.TreeMap;\nimport java.util.LinkedHashMap;\nimport java.util.Map.Entry;\nimport java.util.concurrent.ConcurrentMap;\nimport java.util.concurrent.ConcurrentHashMap;\nimport java.lang.reflect.Type;\n\n/**\n * The property editor manager. This orchestrates Geronimo usage of\n * property editors, allowing additional search paths to be added and\n * specific editors to be registered.\n *\n * @version $Rev: 6687 $\n */\npublic class PropertyEditors {\n private static final Map registry = Collections.synchronizedMap(new ReferenceIdentityMap());\n private static final Map PRIMITIVE_TO_WRAPPER;\n private static final Map WRAPPER_TO_PRIMITIVE;\n private static boolean registerWithVM;\n\n /**\n * Register all of the built in converters\n */\n static {\n Map map = new HashMap();\n map.put(boolean.class, Boolean.class);\n map.put(char.class, Character.class);\n map.put(byte.class, Byte.class);\n map.put(short.class, Short.class);\n map.put(int.class, Integer.class);\n map.put(long.class, Long.class);\n map.put(float.class, Float.class);\n map.put(double.class, Double.class);\n PRIMITIVE_TO_WRAPPER = Collections.unmodifiableMap(map);\n\n\n map = new HashMap();\n map.put(Boolean.class, boolean.class);\n map.put(Character.class, char.class);\n map.put(Byte.class, byte.class);\n map.put(Short.class, short.class);\n map.put(Integer.class, int.class);\n map.put(Long.class, long.class);\n map.put(Float.class, float.class);\n map.put(Double.class, double.class);\n WRAPPER_TO_PRIMITIVE = Collections.unmodifiableMap(map);\n\n // Explicitly register the types\n registerConverter(new ArrayListEditor());\n registerConverter(new BigDecimalEditor());\n registerConverter(new BigIntegerEditor());\n registerConverter(new BooleanEditor());\n registerConverter(new ByteEditor());\n registerConverter(new CharacterEditor());\n registerConverter(new ClassEditor());\n registerConverter(new DateEditor());\n registerConverter(new DoubleEditor());\n registerConverter(new FileEditor());\n registerConverter(new FloatEditor());\n registerConverter(new HashMapEditor());\n registerConverter(new HashtableEditor());\n registerConverter(new IdentityHashMapEditor());\n registerConverter(new Inet4AddressEditor());\n registerConverter(new Inet6AddressEditor());\n registerConverter(new InetAddressEditor());\n registerConverter(new IntegerEditor());\n registerConverter(new LinkedHashMapEditor());\n registerConverter(new LinkedHashSetEditor());\n registerConverter(new LinkedListEditor());\n registerConverter(new ListEditor());\n registerConverter(new LongEditor());\n registerConverter(new MapEditor());\n registerConverter(new ObjectNameEditor());\n registerConverter(new PropertiesEditor());\n registerConverter(new SetEditor());\n registerConverter(new ShortEditor());\n registerConverter(new SortedMapEditor());\n registerConverter(new SortedSetEditor());\n registerConverter(new StringEditor());\n registerConverter(new TreeMapEditor());\n registerConverter(new TreeSetEditor());\n registerConverter(new URIEditor());\n registerConverter(new URLEditor());\n registerConverter(new LoggerConverter());\n registerConverter(new PatternConverter());\n registerConverter(new JndiConverter());\n registerConverter(new VectorEditor());\n registerConverter(new WeakHashMapEditor());\n\n try {\n registerConverter(new Log4jConverter());\n } catch (Throwable e) {\n }\n\n try {\n registerConverter(new CommonsLoggingConverter());\n } catch (Throwable e) {\n }\n }\n\n /**\n * Are converters registered with the VM PropertyEditorManager. By default\n * converters are not registered with the VM as this creates problems for\n * IDE and Spring because they rely in their specific converters being\n * registered to function properly. \n */\n public static boolean isRegisterWithVM() {\n return registerWithVM;\n }\n\n /**\n * Sets if converters registered with the VM PropertyEditorManager.\n * If the new value is true, all currently registered converters are\n * immediately registered with the VM.\n */\n public static void setRegisterWithVM(boolean registerWithVM) {\n if (PropertyEditors.registerWithVM != registerWithVM) {\n PropertyEditors.registerWithVM = registerWithVM;\n\n // register all converters with the VM\n if (registerWithVM) {\n for (Entry entry : registry.entrySet()) {\n Class type = entry.getKey();\n Converter converter = entry.getValue();\n PropertyEditorManager.registerEditor(type, converter.getClass());\n }\n }\n }\n }\n\n public static void registerConverter(Converter converter) {\n if (converter == null) throw new NullPointerException(\"editor is null\");\n Class type = converter.getType();\n registry.put(type, converter);\n if (registerWithVM) {\n PropertyEditorManager.registerEditor(type, converter.getClass());\n }\n\n if (PRIMITIVE_TO_WRAPPER.containsKey(type)) {\n Class wrapperType = PRIMITIVE_TO_WRAPPER.get(type);\n registry.put(wrapperType, converter);\n if (registerWithVM) {\n PropertyEditorManager.registerEditor(wrapperType, converter.getClass());\n }\n } else if (WRAPPER_TO_PRIMITIVE.containsKey(type)) {\n Class primitiveType = WRAPPER_TO_PRIMITIVE.get(type);\n registry.put(primitiveType, converter);\n if (registerWithVM) {\n PropertyEditorManager.registerEditor(primitiveType, converter.getClass());\n }\n }\n }\n\n public static boolean canConvert(String type, ClassLoader classLoader) {\n if (type == null) throw new NullPointerException(\"type is null\");\n if (classLoader == null) throw new NullPointerException(\"classLoader is null\");\n\n // load using the ClassLoading utility, which also manages arrays and primitive classes.\n Class typeClass;\n try {\n typeClass = Class.forName(type, true, classLoader);\n } catch (ClassNotFoundException e) {\n throw new PropertyEditorException(\"Type class could not be found: \" + type);\n }\n\n return canConvert(typeClass);\n\n }\n\n public static boolean canConvert(Class type) {\n PropertyEditor editor = findConverterOrEditor(type);\n\n return editor != null;\n }\n\n private static PropertyEditor findConverterOrEditor(Type type){\n Converter converter = findConverter(type);\n if (converter != null) {\n return converter;\n }\n\n // fall back to a property editor\n PropertyEditor editor = findEditor(type);\n if (editor != null) {\n return editor;\n }\n\n converter = findBuiltinConverter(type);\n if (converter != null) {\n return converter;\n }\n\n return null;\n }\n\n public static String toString(Object value) throws PropertyEditorException {\n if (value == null) throw new NullPointerException(\"value is null\");\n\n // get an editor for this type\n Class type = value.getClass();\n\n PropertyEditor editor = findConverterOrEditor(type);\n\n if (editor instanceof Converter) {\n Converter converter = (Converter) editor;\n return converter.toString(value);\n }\n\n if (editor == null) {\n throw new PropertyEditorException(\"Unable to find PropertyEditor for \" + type.getSimpleName());\n }\n\n // create the string value\n editor.setValue(value);\n String textValue;\n try {\n textValue = editor.getAsText();\n } catch (Exception e) {\n throw new PropertyEditorException(\"Error while converting a \\\"\" + type.getSimpleName() + \"\\\" to text \" +\n \" using the property editor \" + editor.getClass().getSimpleName(), e);\n }\n return textValue;\n }\n\n public static Object getValue(String type, String value, ClassLoader classLoader) throws PropertyEditorException {\n if (type == null) throw new NullPointerException(\"type is null\");\n if (value == null) throw new NullPointerException(\"value is null\");\n if (classLoader == null) throw new NullPointerException(\"classLoader is null\");\n\n // load using the ClassLoading utility, which also manages arrays and primitive classes.\n Class typeClass;\n try {\n typeClass = Class.forName(type, true, classLoader);\n } catch (ClassNotFoundException e) {\n throw new PropertyEditorException(\"Type class could not be found: \" + type);\n }\n\n return getValue(typeClass, value);\n\n }\n\n public static Object getValue(Type type, String value) throws PropertyEditorException {\n if (type == null) throw new NullPointerException(\"type is null\");\n if (value == null) throw new NullPointerException(\"value is null\");\n\n PropertyEditor editor = findConverterOrEditor(type);\n\n if (editor instanceof Converter) {\n Converter converter = (Converter) editor;\n return converter.toObject(value);\n }\n\n Class clazz = toClass(type);\n\n if (editor == null) {\n throw new PropertyEditorException(\"Unable to find PropertyEditor for \" + clazz.getSimpleName());\n }", "answers": [" editor.setAsText(value);"], "length": 983, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "2fa4be84-1d82-4f7a-9ebe-ddc0ee63bbeb", "reasoning": "The method getValue(Type type, String value) looks up a PropertyEditor (or Converter). After handling the case where the editor is a Converter, it converts the type to a Class, checks for null, and then must use the PropertyEditor to parse the string. The typical usage is to call setAsText on the editor and then retrieve the converted object with getValue(). Therefore the immediate next line after the null‑check is the call to setAsText on the editor.", "reasoning_model_answer": "editor.setAsText(value);", "assistant_with_reasoning": "\nThe method getValue(Type type, String value) looks up a PropertyEditor (or Converter). After handling the case where the editor is a Converter, it converts the type to a Class, checks for null, and then must use the PropertyEditor to parse the string. The typical usage is to call setAsText on the editor and then retrieve the converted object with getValue(). Therefore the immediate next line after the null‑check is the call to setAsText on the editor.\n\neditor.setAsText(value);", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.261, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 11314, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "editor.setAsText(value);", "score": 0.86, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "using OpenSource.UPnP;\n\nnamespace UPnPRelay\n{\n /// \n /// Transparent DeviceSide UPnP Service\n /// \n public class DvGateKeeper : IUPnPService\n {\n\n // Place your declarations above this line\n\n #region AutoGenerated Code Section [Do NOT Modify, unless you know what you're doing]\n //{{{{{ Begin Code Block\n\n private _DvGateKeeper _S;\n public static string URN = \"urn:schemas-upnp-org:service:UPnPRelay:1\";\n public double VERSION\n {\n get\n {\n return(double.Parse(_S.GetUPnPService().Version));\n }\n }\n\n public System.Boolean Reverse\n {\n get\n {\n return((System.Boolean)_S.GetStateVariable(\"Reverse\"));\n }\n set\n {\n _S.SetStateVariable(\"Reverse\", value);\n }\n }\n public System.String ErrorString\n {\n get\n {\n return((System.String)_S.GetStateVariable(\"ErrorString\"));\n }\n set\n {\n _S.SetStateVariable(\"ErrorString\", value);\n }\n }\n public System.String StateVariableName\n {\n get\n {\n return((System.String)_S.GetStateVariable(\"StateVariableName\"));\n }\n set\n {\n _S.SetStateVariable(\"StateVariableName\", value);\n }\n }\n public System.String ServiceID\n {\n get\n {\n return((System.String)_S.GetStateVariable(\"ServiceID\"));\n }\n set\n {\n _S.SetStateVariable(\"ServiceID\", value);\n }\n }\n public System.Byte[] Document\n {\n get\n {\n return((System.Byte[])_S.GetStateVariable(\"Document\"));\n }\n set\n {\n _S.SetStateVariable(\"Document\", value);\n }\n }\n public System.Byte[] Args\n {\n get\n {\n return((System.Byte[])_S.GetStateVariable(\"Args\"));\n }\n set\n {\n _S.SetStateVariable(\"Args\", value);\n }\n }\n public System.Int32 Handle\n {\n get\n {\n return((System.Int32)_S.GetStateVariable(\"Handle\"));\n }\n set\n {\n _S.SetStateVariable(\"Handle\", value);\n }\n }\n public System.Uri ProxyUri\n {\n get\n {\n return((System.Uri)_S.GetStateVariable(\"ProxyUri\"));\n }\n set\n {\n _S.SetStateVariable(\"ProxyUri\", value);\n }\n }\n public System.String ActionName\n {\n get\n {\n return((System.String)_S.GetStateVariable(\"ActionName\"));\n }\n set\n {\n _S.SetStateVariable(\"ActionName\", value);\n }\n }\n public System.String StateVariableValue\n {\n get\n {\n return((System.String)_S.GetStateVariable(\"StateVariableValue\"));\n }\n set\n {\n _S.SetStateVariable(\"StateVariableValue\", value);\n }\n }\n public System.String DeviceUDN\n {\n get\n {\n return((System.String)_S.GetStateVariable(\"DeviceUDN\"));\n }\n set\n {\n _S.SetStateVariable(\"DeviceUDN\", value);\n }\n }\n public System.Int32 ErrorCode\n {\n get\n {\n return((System.Int32)_S.GetStateVariable(\"ErrorCode\"));\n }\n set\n {\n _S.SetStateVariable(\"ErrorCode\", value);\n }\n }\n public UPnPModeratedStateVariable.IAccumulator Accumulator_Reverse\n {\n get\n {\n return(((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject(\"Reverse\")).Accumulator);\n }\n set\n {\n ((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject(\"Reverse\")).Accumulator = value;\n }\n }\n public double ModerationDuration_Reverse\n {\n get\n {\n return(((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject(\"Reverse\")).ModerationPeriod);\n }\n set\n {\n ((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject(\"Reverse\")).ModerationPeriod = value;\n }\n }\n public UPnPModeratedStateVariable.IAccumulator Accumulator_ErrorString\n {\n get\n {\n return(((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject(\"ErrorString\")).Accumulator);\n }\n set\n {\n ((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject(\"ErrorString\")).Accumulator = value;\n }\n }\n public double ModerationDuration_ErrorString\n {\n get\n {\n return(((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject(\"ErrorString\")).ModerationPeriod);\n }\n set\n {\n ((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject(\"ErrorString\")).ModerationPeriod = value;\n }\n }\n public UPnPModeratedStateVariable.IAccumulator Accumulator_StateVariableName\n {\n get\n {\n return(((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject(\"StateVariableName\")).Accumulator);\n }\n set\n {\n ((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject(\"StateVariableName\")).Accumulator = value;\n }\n }\n public double ModerationDuration_StateVariableName\n {\n get\n {\n return(((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject(\"StateVariableName\")).ModerationPeriod);\n }\n set\n {\n ((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject(\"StateVariableName\")).ModerationPeriod = value;\n }\n }\n public UPnPModeratedStateVariable.IAccumulator Accumulator_ServiceID\n {\n get\n {\n return(((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject(\"ServiceID\")).Accumulator);\n }\n set\n {\n ((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject(\"ServiceID\")).Accumulator = value;\n }\n }\n public double ModerationDuration_ServiceID\n {\n get\n {\n return(((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject(\"ServiceID\")).ModerationPeriod);\n }\n set\n {\n ((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject(\"ServiceID\")).ModerationPeriod = value;\n }\n }\n public UPnPModeratedStateVariable.IAccumulator Accumulator_Document\n {\n get\n {\n return(((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject(\"Document\")).Accumulator);\n }\n set\n {\n ((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject(\"Document\")).Accumulator = value;\n }\n }\n public double ModerationDuration_Document\n {\n get\n {\n return(((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject(\"Document\")).ModerationPeriod);\n }\n set\n {\n ((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject(\"Document\")).ModerationPeriod = value;\n }\n }\n public UPnPModeratedStateVariable.IAccumulator Accumulator_Args\n {\n get\n {\n return(((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject(\"Args\")).Accumulator);\n }\n set\n {\n ((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject(\"Args\")).Accumulator = value;\n }\n }\n public double ModerationDuration_Args\n {\n get\n {\n return(((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject(\"Args\")).ModerationPeriod);\n }\n set\n {\n ((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject(\"Args\")).ModerationPeriod = value;\n }\n }\n public UPnPModeratedStateVariable.IAccumulator Accumulator_Handle\n {\n get\n {\n return(((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject(\"Handle\")).Accumulator);\n }\n set\n {\n ((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject(\"Handle\")).Accumulator = value;\n }\n }\n public double ModerationDuration_Handle\n {\n get\n {\n return(((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject(\"Handle\")).ModerationPeriod);\n }\n set\n {\n ((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject(\"Handle\")).ModerationPeriod = value;\n }\n }\n public UPnPModeratedStateVariable.IAccumulator Accumulator_ProxyUri\n {\n get\n {\n return(((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject(\"ProxyUri\")).Accumulator);\n }\n set\n {\n ((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject(\"ProxyUri\")).Accumulator = value;\n }\n }\n public double ModerationDuration_ProxyUri\n {\n get\n {\n return(((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject(\"ProxyUri\")).ModerationPeriod);\n }\n set\n {\n ((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject(\"ProxyUri\")).ModerationPeriod = value;\n }\n }\n public UPnPModeratedStateVariable.IAccumulator Accumulator_ActionName\n {\n get\n {\n return(((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject(\"ActionName\")).Accumulator);\n }\n set\n {\n ((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject(\"ActionName\")).Accumulator = value;\n }\n }\n public double ModerationDuration_ActionName\n {\n get\n {\n return(((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject(\"ActionName\")).ModerationPeriod);\n }\n set\n {\n ((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject(\"ActionName\")).ModerationPeriod = value;\n }\n }\n public UPnPModeratedStateVariable.IAccumulator Accumulator_StateVariableValue\n {\n get\n {\n return(((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject(\"StateVariableValue\")).Accumulator);\n }\n set\n {\n ((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject(\"StateVariableValue\")).Accumulator = value;\n }\n }\n public double ModerationDuration_StateVariableValue\n {\n get\n {\n return(((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject(\"StateVariableValue\")).ModerationPeriod);\n }\n set\n {\n ((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject(\"StateVariableValue\")).ModerationPeriod = value;\n }\n }\n public UPnPModeratedStateVariable.IAccumulator Accumulator_DeviceUDN\n {\n get\n {\n return(((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject(\"DeviceUDN\")).Accumulator);\n }\n set\n {\n ((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject(\"DeviceUDN\")).Accumulator = value;\n }\n }\n public double ModerationDuration_DeviceUDN\n {\n get\n {\n return(((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject(\"DeviceUDN\")).ModerationPeriod);\n }\n set\n {\n ((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject(\"DeviceUDN\")).ModerationPeriod = value;\n }\n }\n public UPnPModeratedStateVariable.IAccumulator Accumulator_ErrorCode\n {\n get\n {\n return(((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject(\"ErrorCode\")).Accumulator);\n }\n set\n {\n ((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject(\"ErrorCode\")).Accumulator = value;\n }\n }\n public double ModerationDuration_ErrorCode\n {\n get\n {\n return(((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject(\"ErrorCode\")).ModerationPeriod);\n }\n set\n {\n ((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject(\"ErrorCode\")).ModerationPeriod = value;\n }\n }\n public delegate void Delegate_Invoke(System.String DeviceUDN, System.String ServiceID, System.String Action, System.Byte[] InArgs, out System.Byte[] OutArgs);\n public delegate void Delegate_FireEvent(System.String DeviceUDN, System.String ServiceID, System.String StateVariable, System.String Value);\n public delegate void Delegate_AddDevice(System.String Sender, System.String DeviceUDN);\n public delegate void Delegate_InvokeAsync(System.String Caller, System.String DeviceUDN, System.String ServiceID, System.String Action, System.Byte[] InArgs, System.Int32 Handle);\n public delegate void Delegate_GetDocument(System.String DeviceUDN, System.String ServiceID, out System.Byte[] Document);\n public delegate void Delegate_InvokeAsyncResponse(System.Int32 Handle, System.Byte[] OutArgs, System.Int32 ErrorCode, System.String ErrorString);\n public delegate void Delegate_Register(System.Uri Proxy, System.Boolean Reverse);\n public delegate void Delegate_GetStateTable(System.String DeviceUDN, System.String ServiceID, out System.Byte[] Variables);\n public delegate void Delegate_RemoveDevice(System.String DeviceUDN);\n public delegate void Delegate_UnRegister(System.Uri Proxy);\n\n public Delegate_Invoke External_Invoke = null;\n public Delegate_FireEvent External_FireEvent = null;\n public Delegate_AddDevice External_AddDevice = null;\n public Delegate_InvokeAsync External_InvokeAsync = null;\n public Delegate_GetDocument External_GetDocument = null;\n public Delegate_InvokeAsyncResponse External_InvokeAsyncResponse = null;\n public Delegate_Register External_Register = null;\n public Delegate_GetStateTable External_GetStateTable = null;\n public Delegate_RemoveDevice External_RemoveDevice = null;\n public Delegate_UnRegister External_UnRegister = null;\n\n public void RemoveAction_Invoke()\n {\n _S.GetUPnPService().RemoveMethod(\"Invoke\");\n }\n public void RemoveAction_FireEvent()\n {\n _S.GetUPnPService().RemoveMethod(\"FireEvent\");\n }\n public void RemoveAction_AddDevice()\n {\n _S.GetUPnPService().RemoveMethod(\"AddDevice\");\n }\n public void RemoveAction_InvokeAsync()\n {\n _S.GetUPnPService().RemoveMethod(\"InvokeAsync\");\n }\n public void RemoveAction_GetDocument()\n {\n _S.GetUPnPService().RemoveMethod(\"GetDocument\");\n }\n public void RemoveAction_InvokeAsyncResponse()\n {\n _S.GetUPnPService().RemoveMethod(\"InvokeAsyncResponse\");\n }\n public void RemoveAction_Register()\n {\n _S.GetUPnPService().RemoveMethod(\"Register\");\n }\n public void RemoveAction_GetStateTable()\n {\n _S.GetUPnPService().RemoveMethod(\"GetStateTable\");\n }\n public void RemoveAction_RemoveDevice()\n {\n _S.GetUPnPService().RemoveMethod(\"RemoveDevice\");\n }\n public void RemoveAction_UnRegister()\n {\n _S.GetUPnPService().RemoveMethod(\"UnRegister\");\n }\n public System.Net.IPEndPoint GetCaller()\n {\n return(_S.GetUPnPService().GetCaller());\n }\n public System.Net.IPEndPoint GetReceiver()\n {\n return(_S.GetUPnPService().GetReceiver());\n }\n\n private class _DvGateKeeper\n {\n private DvGateKeeper Outer = null;\n private UPnPService S;\n internal _DvGateKeeper(DvGateKeeper n)\n {\n Outer = n;\n S = BuildUPnPService();\n }\n public UPnPService GetUPnPService()\n {\n return(S);\n }\n public void SetStateVariable(string VarName, object VarValue)\n {\n S.SetStateVariable(VarName,VarValue);\n }\n public object GetStateVariable(string VarName)\n {\n return(S.GetStateVariable(VarName));\n }\n protected UPnPService BuildUPnPService()\n {\n UPnPStateVariable[] RetVal = new UPnPStateVariable[12];\n RetVal[0] = new UPnPModeratedStateVariable(\"Reverse\", typeof(System.Boolean), false);\n RetVal[0].AddAssociation(\"Register\", \"Reverse\");\n RetVal[1] = new UPnPModeratedStateVariable(\"ErrorString\", typeof(System.String), false);\n RetVal[1].AddAssociation(\"InvokeAsyncResponse\", \"ErrorString\");\n RetVal[2] = new UPnPModeratedStateVariable(\"StateVariableName\", typeof(System.String), false);\n RetVal[2].AddAssociation(\"FireEvent\", \"StateVariable\");\n RetVal[3] = new UPnPModeratedStateVariable(\"ServiceID\", typeof(System.String), false);\n RetVal[3].AddAssociation(\"Invoke\", \"ServiceID\");\n RetVal[3].AddAssociation(\"FireEvent\", \"ServiceID\");\n RetVal[3].AddAssociation(\"InvokeAsync\", \"ServiceID\");\n RetVal[3].AddAssociation(\"GetDocument\", \"ServiceID\");\n RetVal[3].AddAssociation(\"GetStateTable\", \"ServiceID\");\n RetVal[4] = new UPnPModeratedStateVariable(\"Document\", typeof(System.Byte[]), false);\n RetVal[4].AddAssociation(\"GetDocument\", \"Document\");\n RetVal[5] = new UPnPModeratedStateVariable(\"Args\", typeof(System.Byte[]), false);\n RetVal[5].AddAssociation(\"Invoke\", \"InArgs\");\n RetVal[5].AddAssociation(\"Invoke\", \"OutArgs\");\n RetVal[5].AddAssociation(\"InvokeAsync\", \"InArgs\");\n RetVal[5].AddAssociation(\"InvokeAsyncResponse\", \"OutArgs\");\n RetVal[5].AddAssociation(\"GetStateTable\", \"Variables\");\n RetVal[6] = new UPnPModeratedStateVariable(\"Handle\", typeof(System.Int32), false);\n RetVal[6].AddAssociation(\"InvokeAsync\", \"Handle\");\n RetVal[6].AddAssociation(\"InvokeAsyncResponse\", \"Handle\");\n RetVal[7] = new UPnPModeratedStateVariable(\"ProxyUri\", typeof(System.Uri), false);\n RetVal[7].AddAssociation(\"Register\", \"Proxy\");\n RetVal[7].AddAssociation(\"UnRegister\", \"Proxy\");\n RetVal[8] = new UPnPModeratedStateVariable(\"ActionName\", typeof(System.String), false);\n RetVal[8].AddAssociation(\"Invoke\", \"Action\");\n RetVal[8].AddAssociation(\"InvokeAsync\", \"Action\");\n RetVal[9] = new UPnPModeratedStateVariable(\"StateVariableValue\", typeof(System.String), false);\n RetVal[9].AddAssociation(\"FireEvent\", \"Value\");\n RetVal[10] = new UPnPModeratedStateVariable(\"DeviceUDN\", typeof(System.String), false);\n RetVal[10].AddAssociation(\"Invoke\", \"DeviceUDN\");\n RetVal[10].AddAssociation(\"FireEvent\", \"DeviceUDN\");\n RetVal[10].AddAssociation(\"AddDevice\", \"Sender\");\n RetVal[10].AddAssociation(\"AddDevice\", \"DeviceUDN\");\n RetVal[10].AddAssociation(\"InvokeAsync\", \"Caller\");\n RetVal[10].AddAssociation(\"InvokeAsync\", \"DeviceUDN\");\n RetVal[10].AddAssociation(\"GetDocument\", \"DeviceUDN\");\n RetVal[10].AddAssociation(\"GetStateTable\", \"DeviceUDN\");\n RetVal[10].AddAssociation(\"RemoveDevice\", \"DeviceUDN\");\n RetVal[11] = new UPnPModeratedStateVariable(\"ErrorCode\", typeof(System.Int32), false);\n RetVal[11].AddAssociation(\"InvokeAsyncResponse\", \"ErrorCode\");\n\n UPnPService S = new UPnPService(1, \"UPNPRELAY_0-2\", \"urn:schemas-upnp-org:service:UPnPRelay:1\", true, this);\n for(int i=0;i\nThe code is inside the BuildUPnPService method, constructing a UPnPService instance and adding its state variables. After adding the state variables, it adds the service methods. The last added method is \"Register\". Looking at the defined delegates and RemoveAction methods, the next methods to add are \"GetStateTable\", \"RemoveDevice\", and \"UnRegister\". Therefore the immediate next line after S.AddMethod(\"Register\"); is adding the next method, which is \"GetStateTable\".\n\nS.AddMethod(\"GetStateTable\");", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.646, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 22476, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "S.AddMethod(\"GetStateTable\");", "score": 0.78, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "using Akavache;\nusing Espera.Core.Audio;\nusing Espera.Core.Management;\nusing Espera.Network;\nusing Newtonsoft.Json;\nusing Newtonsoft.Json.Linq;\nusing Rareform.Validation;\nusing ReactiveMarrow;\nusing ReactiveUI;\nusing Splat;\nusing System;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.IO;\nusing System.Linq;\nusing System.Net.Sockets;\nusing System.Reactive;\nusing System.Reactive.Disposables;\nusing System.Reactive.Linq;\nusing System.Reactive.Subjects;\nusing System.Reflection;\nusing System.Threading;\nusing System.Threading.Tasks;\n\nnamespace Espera.Core.Mobile\n{\n /// \n /// Represents one mobile endpoint and handles the interaction.\n /// \n public class MobileClient : IDisposable, IEnableLogger\n {\n private readonly Subject disconnected;\n private readonly CompositeDisposable disposable;\n private readonly TcpClient fileSocket;\n private readonly SemaphoreSlim gate;\n private readonly Library library;\n private readonly Dictionary>> messageActionMap;\n private readonly TcpClient socket;\n private readonly Subject videoPlayerToggleRequest;\n private Guid accessToken;\n private IReadOnlyList lastSoundCloudRequest;\n private IReadOnlyList lastYoutubeRequest;\n private IObservable songTransfers;\n\n public MobileClient(TcpClient socket, TcpClient fileSocket, Library library)\n {\n if (socket == null)\n Throw.ArgumentNullException(() => socket);\n\n if (fileSocket == null)\n Throw.ArgumentNullException(() => socket);\n\n if (library == null)\n Throw.ArgumentNullException(() => library);\n\n this.socket = socket;\n this.fileSocket = fileSocket;\n this.library = library;\n\n this.disposable = new CompositeDisposable();\n this.gate = new SemaphoreSlim(1, 1);\n this.disconnected = new Subject();\n this.lastSoundCloudRequest = new List();\n this.lastYoutubeRequest = new List();\n this.videoPlayerToggleRequest = new Subject();\n\n this.messageActionMap = new Dictionary>>\n {\n {RequestAction.GetConnectionInfo, this.GetConnectionInfo},\n {RequestAction.ToggleYoutubePlayer, this.ToggleVideoPlayer},\n {RequestAction.GetLibraryContent, this.GetLibraryContent},\n {RequestAction.GetSoundCloudSongs, this.GetSoundCloudSongs},\n {RequestAction.GetYoutubeSongs, this.GetYoutubeSongs},\n {RequestAction.AddPlaylistSongs, this.AddPlaylistSongs},\n {RequestAction.AddPlaylistSongsNow, this.AddPlaylistSongsNow},\n {RequestAction.GetCurrentPlaylist, this.GetCurrentPlaylist},\n {RequestAction.PlayPlaylistSong, this.PlayPlaylistSong},\n {RequestAction.ContinueSong, this.ContinueSong},\n {RequestAction.PauseSong, this.PauseSong},\n {RequestAction.PlayNextSong, this.PlayNextSong},\n {RequestAction.PlayPreviousSong, this.PlayPreviousSong},\n {RequestAction.RemovePlaylistSong, this.PostRemovePlaylistSong},\n {RequestAction.MovePlaylistSongUp, this.MovePlaylistSongUp},\n {RequestAction.MovePlaylistSongDown, this.MovePlaylistSongDown},\n {RequestAction.GetVolume, this.GetVolume},\n {RequestAction.SetVolume, this.SetVolume},\n {RequestAction.VoteForSong, this.VoteForSong},\n {RequestAction.QueueRemoteSong, this.QueueRemoteSong},\n {RequestAction.SetCurrentTime, this.SetCurrentTime}\n };\n }\n\n public IObservable Disconnected\n {\n get { return this.disconnected.AsObservable(); }\n }\n\n /// \n /// Signals when the mobile client wants to toggle the visibility of the video player.\n /// \n public IObservable VideoPlayerToggleRequest\n {\n get { return this.videoPlayerToggleRequest.AsObservable(); }\n }\n\n public void Dispose()\n {\n this.socket.Close();\n this.gate.Dispose();\n this.disposable.Dispose();\n }\n\n public void ListenAsync()\n {\n Observable.FromAsync(() => this.socket.GetStream().ReadNextMessageAsync())\n .Repeat()\n .LoggedCatch(this, null, \"Message connection was closed by the remote device or the connection failed\")\n .TakeWhile(x => x != null)\n // If we don't do this, the application will throw up whenever we are manipulating a\n // collection that is surfaced to the UI Yes, this is astoundingly stupid\n .ObserveOn(RxApp.MainThreadScheduler)\n .SelectMany(async message =>\n {\n RequestInfo request;\n\n try\n {\n request = message.Payload.ToObject();\n }\n\n catch (JsonException ex)\n {\n this.Log().ErrorException(String.Format(\"Mobile client with access token {0} sent a malformed request\", this.accessToken), ex);\n return Unit.Default;\n }\n\n var responseMessage = new NetworkMessage { MessageType = NetworkMessageType.Response };\n\n Func> action;\n\n if (this.messageActionMap.TryGetValue(request.RequestAction, out action))\n {\n bool isFatalRequest = false;\n try\n {\n ResponseInfo response = await action(request.Parameters);\n response.RequestId = request.RequestId;\n\n responseMessage.Payload = await Task.Run(() => JObject.FromObject(response));\n\n await this.SendMessage(responseMessage);\n }\n\n catch (Exception ex)\n {\n this.Log().ErrorException(String.Format(\"Mobile client with access token {0} sent a request that caused an exception\", this.accessToken), ex);\n if (Debugger.IsAttached)\n {\n Debugger.Break();\n }\n\n isFatalRequest = true;\n }\n\n if (isFatalRequest)\n {\n ResponseInfo response = CreateResponse(ResponseStatus.Fatal);\n response.RequestId = request.RequestId;\n responseMessage.Payload = JObject.FromObject(response);\n\n // Client what are you doing? Client stahp!\n await this.SendMessage(responseMessage);\n }\n\n return Unit.Default;\n }\n\n return Unit.Default;\n })\n .Finally(() => this.disconnected.OnNext(Unit.Default))\n .Subscribe()\n .DisposeWith(this.disposable);\n\n var transfers = Observable.FromAsync(() => this.fileSocket.GetStream().ReadNextFileTransferMessageAsync())\n .Repeat()\n .LoggedCatch(this, null, \"File transfer connection was closed by the remote device or the connection failed\")\n .TakeWhile(x => x != null)\n .Publish();\n transfers.Connect().DisposeWith(this.disposable);\n\n this.songTransfers = transfers;\n }\n\n private static NetworkMessage CreatePushMessage(PushAction action, JObject content)\n {\n var message = new NetworkMessage\n {\n MessageType = NetworkMessageType.Push,\n Payload = JObject.FromObject(new PushInfo\n {\n Content = content,\n PushAction = action\n })\n };\n\n return message;\n }\n\n private static ResponseInfo CreateResponse(ResponseStatus status, JObject content = null)\n {\n return CreateResponse(status, null, content);\n }\n\n private static ResponseInfo CreateResponse(ResponseStatus status, string message, JObject content = null)\n {\n return new ResponseInfo\n {\n Status = status,\n Message = message,\n Content = content,\n };\n }\n\n private async Task AddPlaylistSongs(JToken parameters)\n {\n IEnumerable songs;\n ResponseInfo response;\n\n bool areValid = this.TryValidateSongGuids(parameters[\"guids\"].Select(x => x.ToString()), out songs, out response);\n\n if (areValid)\n {\n AccessPermission permission = await this.library.RemoteAccessControl.ObserveAccessPermission(this.accessToken).FirstAsync();\n\n if (permission == AccessPermission.Guest)\n {\n int? remainingVotes = await this.library.RemoteAccessControl.ObserveRemainingVotes(this.accessToken).FirstAsync();\n\n if (remainingVotes == null)\n {\n return CreateResponse(ResponseStatus.NotSupported, \"Voting isn't supported\");\n }\n\n if (remainingVotes == 0)\n {\n return CreateResponse(ResponseStatus.Rejected, \"Not enough votes left\");\n }\n }\n\n if (permission == AccessPermission.Admin)\n {\n this.library.AddSongsToPlaylist(songs, this.accessToken);\n }\n\n else\n {\n if (songs.Count() > 1)\n {\n return CreateResponse(ResponseStatus.Unauthorized, \"Guests can't add more than one song\");\n }\n\n this.library.AddGuestSongToPlaylist(songs.First(), this.accessToken);\n }\n\n return CreateResponse(ResponseStatus.Success);\n }\n\n return response;\n }\n\n private async Task AddPlaylistSongsNow(JToken parameters)\n {\n IEnumerable songs;\n ResponseInfo response;\n\n bool areValid = this.TryValidateSongGuids(parameters[\"guids\"].Select(x => x.ToString()), out songs, out response);\n\n if (areValid)\n {\n try\n {\n await this.library.PlayInstantlyAsync(songs, this.accessToken);\n }\n\n catch (AccessException)\n {\n return CreateResponse(ResponseStatus.Unauthorized);\n }\n\n return CreateResponse(ResponseStatus.Success);\n }\n\n return response;\n }\n\n private async Task ContinueSong(JToken content)\n {\n try\n {\n await this.library.ContinueSongAsync(this.accessToken);\n }\n\n catch (AccessException)\n {\n return CreateResponse(ResponseStatus.Unauthorized);\n }\n\n return CreateResponse(ResponseStatus.Success);\n }\n\n private async Task GetConnectionInfo(JToken parameters)\n {\n Guid deviceId = Guid.Parse(parameters[\"deviceId\"].ToString());\n\n this.accessToken = this.library.RemoteAccessControl.RegisterRemoteAccessToken(deviceId);\n this.Log().Info(\"Registering new mobile client with access token {0}\", this.accessToken);\n\n if (this.library.RemoteAccessControl.IsRemoteAccessReallyLocked)\n {\n var password = parameters[\"password\"].Value();\n\n if (password != null)\n {\n try\n {\n this.library.RemoteAccessControl.UpgradeRemoteAccess(this.accessToken, password);\n }\n\n catch (WrongPasswordException)\n {\n return CreateResponse(ResponseStatus.WrongPassword);\n }\n }\n }\n\n AccessPermission accessPermission = await this.library.RemoteAccessControl.ObserveAccessPermission(this.accessToken).FirstAsync();\n\n // This is stupid\n NetworkAccessPermission permission = accessPermission == AccessPermission.Admin ? NetworkAccessPermission.Admin : NetworkAccessPermission.Guest;\n\n int? remainingVotes = await this.library.RemoteAccessControl.ObserveRemainingVotes(this.accessToken).FirstAsync();\n\n var guestSystemInfo = new GuestSystemInfo\n {\n IsEnabled = remainingVotes.HasValue,\n };\n\n if (remainingVotes.HasValue)\n {\n guestSystemInfo.RemainingVotes = remainingVotes.Value;\n }\n\n var connectionInfo = new ConnectionInfo\n {\n AccessPermission = permission,\n ServerVersion = AppInfo.Version,\n GuestSystemInfo = guestSystemInfo\n };\n\n this.SetupPushNotifications();\n\n return CreateResponse(ResponseStatus.Success, null, JObject.FromObject(connectionInfo));\n }\n\n private async Task GetCurrentPlaylist(JToken dontCare)\n {\n Playlist playlist = this.library.CurrentPlaylist;\n AudioPlayerState playbackState = await this.library.PlaybackState.FirstAsync();\n\n TimeSpan currentTime = await this.library.CurrentPlaybackTime.FirstAsync();\n TimeSpan totalTime = await this.library.TotalTime.FirstAsync();\n JObject content = MobileHelper.SerializePlaylist(playlist, playbackState, currentTime, totalTime);\n\n return CreateResponse(ResponseStatus.Success, null, content);\n }\n\n private async Task GetLibraryContent(JToken dontCare)\n {\n JObject content = await Task.Run(() => MobileHelper.SerializeSongs(this.library.Songs));\n\n return CreateResponse(ResponseStatus.Success, null, content);\n }\n\n private async Task GetSoundCloudSongs(JToken parameters)\n {\n var searchTerm = parameters[\"searchTerm\"].ToObject();\n\n try\n {\n var requestCache = Locator.Current.GetService(BlobCacheKeys.RequestCacheContract);\n var songFinder = new SoundCloudSongFinder(requestCache);\n\n IReadOnlyList songs = await songFinder.GetSongsAsync(searchTerm);\n\n // Cache the latest SoundCloud search request, so we can find the songs by GUID when\n // we add one to the playlist later\n this.lastSoundCloudRequest = songs;\n\n JObject content = MobileHelper.SerializeSongs(songs);\n\n return CreateResponse(ResponseStatus.Success, content);\n }\n\n catch (NetworkSongFinderException)\n {\n return CreateResponse(ResponseStatus.Failed, \"Couldn't retrieve any SoundCloud songs\");\n }\n }\n\n private Task GetVolume(JToken dontCare)\n {\n float volume = this.library.Volume;\n\n var response = JObject.FromObject(new\n {\n volume\n });\n\n return Task.FromResult(CreateResponse(ResponseStatus.Success, response));\n }\n\n private async Task GetYoutubeSongs(JToken parameters)\n {\n var searchTerm = parameters[\"searchTerm\"].ToObject();\n\n try\n {\n var requestCache = Locator.Current.GetService(BlobCacheKeys.RequestCacheContract);\n var songFinder = new YoutubeSongFinder(requestCache);\n\n IReadOnlyList songs = await songFinder.GetSongsAsync(searchTerm);\n\n // Cache the latest YouTube search request, so we can find the songs by GUID when we\n // add one to the playlist later\n this.lastYoutubeRequest = songs;\n\n JObject content = MobileHelper.SerializeSongs(songs);\n\n return CreateResponse(ResponseStatus.Success, content);\n }\n\n catch (NetworkSongFinderException)\n {\n return CreateResponse(ResponseStatus.Failed, \"Couldn't retrieve any YouTube songs\");\n };\n }\n\n private Task MovePlaylistSongDown(JToken parameters)\n {\n Guid songGuid;\n bool valid = Guid.TryParse(parameters[\"entryGuid\"].ToString(), out songGuid);\n\n if (!valid)\n {\n return Task.FromResult(CreateResponse(ResponseStatus.MalformedRequest, \"Malformed GUID\"));\n }\n\n PlaylistEntry entry = this.library.CurrentPlaylist.FirstOrDefault(x => x.Guid == songGuid);\n\n if (entry == null)\n {\n return Task.FromResult(CreateResponse(ResponseStatus.NotFound, \"Playlist entry not found\"));\n }\n\n try\n {\n this.library.MovePlaylistSong(entry.Index, entry.Index + 1, this.accessToken);\n }\n\n catch (AccessException)\n {\n return Task.FromResult(CreateResponse(ResponseStatus.Unauthorized));\n }\n\n return Task.FromResult(CreateResponse(ResponseStatus.Success));\n }\n\n private Task MovePlaylistSongUp(JToken parameters)\n {\n Guid songGuid;", "answers": [" bool valid = Guid.TryParse(parameters[\"entryGuid\"].ToString(), out songGuid);"], "length": 1134, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "9f4966bc-b555-4fae-93f7-fbf9d7fd1a77", "reasoning": "The MovePlaylistSongUp method mirrors MovePlaylistSongDown. After declaring the Guid variable, the next step is to parse the GUID from the parameters, just like in the down method. So the next line should be the TryParse call assigning to a bool.", "reasoning_model_answer": "bool valid = Guid.TryParse(parameters[\"entryGuid\"].ToString(), out songGuid);", "assistant_with_reasoning": "\nThe MovePlaylistSongUp method mirrors MovePlaylistSongDown. After declaring the Guid variable, the next step is to parse the GUID from the parameters, just like in the down method. So the next line should be the TryParse call assigning to a bool.\n\nbool valid = Guid.TryParse(parameters[\"entryGuid\"].ToString(), out songGuid);", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.414, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 18398, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "bool valid = Guid.TryParse(parameters[\"entryGuid\"].ToString(), out songGuid);", "score": 0.93, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.apache.kafka.streams.processor.internals.assignment;\n\nimport org.apache.kafka.common.utils.Utils;\nimport org.apache.kafka.streams.processor.TaskId;\nimport org.junit.Test;\n\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collections;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.TreeMap;\n\nimport static org.hamcrest.CoreMatchers.equalTo;\nimport static org.hamcrest.MatcherAssert.assertThat;\nimport static org.hamcrest.core.IsCollectionContaining.hasItem;\nimport static org.hamcrest.core.IsCollectionContaining.hasItems;\nimport static org.hamcrest.core.IsNot.not;\nimport static org.junit.Assert.assertTrue;\n\npublic class StickyTaskAssignorTest {\n\n private final TaskId task00 = new TaskId(0, 0);\n private final TaskId task01 = new TaskId(0, 1);\n private final TaskId task02 = new TaskId(0, 2);\n private final TaskId task03 = new TaskId(0, 3);\n private final TaskId task04 = new TaskId(0, 4);\n private final TaskId task05 = new TaskId(0, 5);\n private final Map clients = new TreeMap<>();\n private final Integer p1 = 1;\n private final Integer p2 = 2;\n private final Integer p3 = 3;\n private final Integer p4 = 4;\n\n @Test\n public void shouldAssignOneActiveTaskToEachProcessWhenTaskCountSameAsProcessCount() throws Exception {\n createClient(p1, 1);\n createClient(p2, 1);\n createClient(p3, 1);\n\n final StickyTaskAssignor taskAssignor = createTaskAssignor(task00, task01, task02);\n taskAssignor.assign(0);\n\n for (final Integer processId : clients.keySet()) {\n assertThat(clients.get(processId).activeTaskCount(), equalTo(1));\n }\n }\n\n @Test\n public void shouldNotMigrateActiveTaskToOtherProcess() throws Exception {\n createClientWithPreviousActiveTasks(p1, 1, task00);\n createClientWithPreviousActiveTasks(p2, 1, task01);\n\n final StickyTaskAssignor firstAssignor = createTaskAssignor(task00, task01, task02);\n firstAssignor.assign(0);\n\n assertThat(clients.get(p1).activeTasks(), hasItems(task00));\n assertThat(clients.get(p2).activeTasks(), hasItems(task01));\n assertThat(allActiveTasks(), equalTo(Arrays.asList(task00, task01, task02)));\n\n clients.clear();\n\n // flip the previous active tasks assignment around.\n createClientWithPreviousActiveTasks(p1, 1, task01);\n createClientWithPreviousActiveTasks(p2, 1, task02);\n\n final StickyTaskAssignor secondAssignor = createTaskAssignor(task00, task01, task02);\n secondAssignor.assign(0);\n\n assertThat(clients.get(p1).activeTasks(), hasItems(task01));\n assertThat(clients.get(p2).activeTasks(), hasItems(task02));\n assertThat(allActiveTasks(), equalTo(Arrays.asList(task00, task01, task02)));\n }\n\n @Test\n public void shouldMigrateActiveTasksToNewProcessWithoutChangingAllAssignments() throws Exception {\n createClientWithPreviousActiveTasks(p1, 1, task00, task02);\n createClientWithPreviousActiveTasks(p2, 1, task01);\n createClient(p3, 1);\n\n final StickyTaskAssignor taskAssignor = createTaskAssignor(task00, task01, task02);\n\n taskAssignor.assign(0);\n\n assertThat(clients.get(p2).activeTasks(), equalTo(Collections.singleton(task01)));\n assertThat(clients.get(p1).activeTasks().size(), equalTo(1));\n assertThat(clients.get(p3).activeTasks().size(), equalTo(1));\n assertThat(allActiveTasks(), equalTo(Arrays.asList(task00, task01, task02)));\n }\n\n @Test\n public void shouldAssignBasedOnCapacity() throws Exception {\n createClient(p1, 1);\n createClient(p2, 2);\n final StickyTaskAssignor taskAssignor = createTaskAssignor(task00, task01, task02);\n\n taskAssignor.assign(0);\n assertThat(clients.get(p1).activeTasks().size(), equalTo(1));\n assertThat(clients.get(p2).activeTasks().size(), equalTo(2));\n }\n\n @Test\n public void shouldKeepActiveTaskStickynessWhenMoreClientThanActiveTasks() {\n final int p5 = 5;\n createClientWithPreviousActiveTasks(p1, 1, task00);\n createClientWithPreviousActiveTasks(p2, 1, task02);\n createClientWithPreviousActiveTasks(p3, 1, task01);\n createClient(p4, 1);\n createClient(p5, 1);\n\n final StickyTaskAssignor taskAssignor = createTaskAssignor(task00, task01, task02);\n taskAssignor.assign(0);\n\n assertThat(clients.get(p1).activeTasks(), equalTo(Collections.singleton(task00)));\n assertThat(clients.get(p2).activeTasks(), equalTo(Collections.singleton(task02)));\n assertThat(clients.get(p3).activeTasks(), equalTo(Collections.singleton(task01)));\n\n // change up the assignment and make sure it is still sticky\n clients.clear();\n createClient(p1, 1);\n createClientWithPreviousActiveTasks(p2, 1, task00);\n createClient(p3, 1);\n createClientWithPreviousActiveTasks(p4, 1, task02);\n createClientWithPreviousActiveTasks(p5, 1, task01);\n\n final StickyTaskAssignor secondAssignor = createTaskAssignor(task00, task01, task02);\n secondAssignor.assign(0);\n\n assertThat(clients.get(p2).activeTasks(), equalTo(Collections.singleton(task00)));\n assertThat(clients.get(p4).activeTasks(), equalTo(Collections.singleton(task02)));\n assertThat(clients.get(p5).activeTasks(), equalTo(Collections.singleton(task01)));\n\n\n }\n\n @Test\n public void shouldAssignTasksToClientWithPreviousStandbyTasks() throws Exception {\n final ClientState client1 = createClient(p1, 1);\n client1.addPreviousStandbyTasks(Utils.mkSet(task02));\n final ClientState client2 = createClient(p2, 1);\n client2.addPreviousStandbyTasks(Utils.mkSet(task01));\n final ClientState client3 = createClient(p3, 1);\n client3.addPreviousStandbyTasks(Utils.mkSet(task00));\n\n final StickyTaskAssignor taskAssignor = createTaskAssignor(task00, task01, task02);\n\n taskAssignor.assign(0);\n\n assertThat(clients.get(p1).activeTasks(), equalTo(Collections.singleton(task02)));\n assertThat(clients.get(p2).activeTasks(), equalTo(Collections.singleton(task01)));\n assertThat(clients.get(p3).activeTasks(), equalTo(Collections.singleton(task00)));\n }\n\n @Test\n public void shouldAssignBasedOnCapacityWhenMultipleClientHaveStandbyTasks() throws Exception {\n final ClientState c1 = createClientWithPreviousActiveTasks(p1, 1, task00);\n c1.addPreviousStandbyTasks(Utils.mkSet(task01));\n final ClientState c2 = createClientWithPreviousActiveTasks(p2, 2, task02);\n c2.addPreviousStandbyTasks(Utils.mkSet(task01));\n\n final StickyTaskAssignor taskAssignor = createTaskAssignor(task00, task01, task02);\n\n taskAssignor.assign(0);\n\n assertThat(clients.get(p1).activeTasks(), equalTo(Collections.singleton(task00)));\n assertThat(clients.get(p2).activeTasks(), equalTo(Utils.mkSet(task02, task01)));\n }\n\n @Test\n public void shouldAssignStandbyTasksToDifferentClientThanCorrespondingActiveTaskIsAssingedTo() throws Exception {\n createClientWithPreviousActiveTasks(p1, 1, task00);\n createClientWithPreviousActiveTasks(p2, 1, task01);\n createClientWithPreviousActiveTasks(p3, 1, task02);\n createClientWithPreviousActiveTasks(p4, 1, task03);\n\n final StickyTaskAssignor taskAssignor = createTaskAssignor(task00, task01, task02, task03);\n taskAssignor.assign(1);\n\n assertThat(clients.get(p1).standbyTasks(), not(hasItems(task00)));\n assertTrue(clients.get(p1).standbyTasks().size() <= 2);\n assertThat(clients.get(p2).standbyTasks(), not(hasItems(task01)));\n assertTrue(clients.get(p2).standbyTasks().size() <= 2);\n assertThat(clients.get(p3).standbyTasks(), not(hasItems(task02)));\n assertTrue(clients.get(p3).standbyTasks().size() <= 2);\n assertThat(clients.get(p4).standbyTasks(), not(hasItems(task03)));\n assertTrue(clients.get(p4).standbyTasks().size() <= 2);\n\n int nonEmptyStandbyTaskCount = 0;\n for (final Integer client : clients.keySet()) {\n nonEmptyStandbyTaskCount += clients.get(client).standbyTasks().isEmpty() ? 0 : 1;\n }\n\n assertTrue(nonEmptyStandbyTaskCount >= 3);\n assertThat(allStandbyTasks(), equalTo(Arrays.asList(task00, task01, task02, task03)));\n }\n\n\n\n @Test\n public void shouldAssignMultipleReplicasOfStandbyTask() throws Exception {\n createClientWithPreviousActiveTasks(p1, 1, task00);\n createClientWithPreviousActiveTasks(p2, 1, task01);\n createClientWithPreviousActiveTasks(p3, 1, task02);\n\n final StickyTaskAssignor taskAssignor = createTaskAssignor(task00, task01, task02);\n taskAssignor.assign(2);\n\n assertThat(clients.get(p1).standbyTasks(), equalTo(Utils.mkSet(task01, task02)));\n assertThat(clients.get(p2).standbyTasks(), equalTo(Utils.mkSet(task02, task00)));\n assertThat(clients.get(p3).standbyTasks(), equalTo(Utils.mkSet(task00, task01)));\n }\n\n @Test\n public void shouldNotAssignStandbyTaskReplicasWhenNoClientAvailableWithoutHavingTheTaskAssigned() throws Exception {\n createClient(p1, 1);\n final StickyTaskAssignor taskAssignor = createTaskAssignor(task00);\n taskAssignor.assign(1);\n assertThat(clients.get(p1).standbyTasks().size(), equalTo(0));\n }\n\n @Test\n public void shouldAssignActiveAndStandbyTasks() throws Exception {\n createClient(p1, 1);\n createClient(p2, 1);\n createClient(p3, 1);\n\n final StickyTaskAssignor taskAssignor = createTaskAssignor(task00, task01, task02);\n taskAssignor.assign(1);\n\n assertThat(allActiveTasks(), equalTo(Arrays.asList(task00, task01, task02)));\n assertThat(allStandbyTasks(), equalTo(Arrays.asList(task00, task01, task02)));\n }\n\n\n @Test\n public void shouldAssignAtLeastOneTaskToEachClientIfPossible() throws Exception {\n createClient(p1, 3);\n createClient(p2, 1);\n createClient(p3, 1);\n\n final StickyTaskAssignor taskAssignor = createTaskAssignor(task00, task01, task02);\n taskAssignor.assign(0);\n assertThat(clients.get(p1).assignedTaskCount(), equalTo(1));\n assertThat(clients.get(p2).assignedTaskCount(), equalTo(1));\n assertThat(clients.get(p3).assignedTaskCount(), equalTo(1));\n }\n\n @Test\n public void shouldAssignEachActiveTaskToOneClientWhenMoreClientsThanTasks() throws Exception {\n createClient(p1, 1);\n createClient(p2, 1);\n createClient(p3, 1);\n createClient(p4, 1);\n createClient(5, 1);\n createClient(6, 1);\n\n final StickyTaskAssignor taskAssignor = createTaskAssignor(task00, task01, task02);\n taskAssignor.assign(0);\n\n assertThat(allActiveTasks(), equalTo(Arrays.asList(task00, task01, task02)));\n }\n\n @Test\n public void shouldBalanceActiveAndStandbyTasksAcrossAvailableClients() throws Exception {\n createClient(p1, 1);\n createClient(p2, 1);\n createClient(p3, 1);\n createClient(p4, 1);\n createClient(5, 1);\n createClient(6, 1);\n\n final StickyTaskAssignor taskAssignor = createTaskAssignor(task00, task01, task02);\n taskAssignor.assign(1);\n\n for (final ClientState clientState : clients.values()) {\n assertThat(clientState.assignedTaskCount(), equalTo(1));\n }\n }\n\n @Test\n public void shouldAssignMoreTasksToClientWithMoreCapacity() throws Exception {\n createClient(p2, 2);\n createClient(p1, 1);\n\n final StickyTaskAssignor taskAssignor = createTaskAssignor(task00,\n task01,\n task02,\n new TaskId(1, 0),\n new TaskId(1, 1),\n new TaskId(1, 2),\n new TaskId(2, 0),\n new TaskId(2, 1),\n new TaskId(2, 2),\n new TaskId(3, 0),\n new TaskId(3, 1),\n new TaskId(3, 2));\n\n taskAssignor.assign(0);\n assertThat(clients.get(p2).assignedTaskCount(), equalTo(8));\n assertThat(clients.get(p1).assignedTaskCount(), equalTo(4));\n }\n\n\n @Test\n public void shouldNotHaveSameAssignmentOnAnyTwoHosts() throws Exception {\n createClient(p1, 1);\n createClient(p2, 1);\n createClient(p3, 1);\n createClient(p4, 1);\n\n final StickyTaskAssignor taskAssignor = createTaskAssignor(task00, task02, task01, task03);\n taskAssignor.assign(1);\n\n for (int i = p1; i <= p4; i++) {\n final Set taskIds = clients.get(i).assignedTasks();\n for (int j = p1; j <= p4; j++) {\n if (j != i) {\n assertThat(\"clients shouldn't have same task assignment\", clients.get(j).assignedTasks(),\n not(equalTo(taskIds)));\n }\n }\n\n }\n }\n\n @Test\n public void shouldNotHaveSameAssignmentOnAnyTwoHostsWhenThereArePreviousActiveTasks() throws Exception {\n createClientWithPreviousActiveTasks(p1, 1, task01, task02);\n createClientWithPreviousActiveTasks(p2, 1, task03);\n createClientWithPreviousActiveTasks(p3, 1, task00);\n createClient(p4, 1);\n\n final StickyTaskAssignor taskAssignor = createTaskAssignor(task00, task02, task01, task03);\n taskAssignor.assign(1);\n\n for (int i = p1; i <= p4; i++) {\n final Set taskIds = clients.get(i).assignedTasks();\n for (int j = p1; j <= p4; j++) {\n if (j != i) {\n assertThat(\"clients shouldn't have same task assignment\", clients.get(j).assignedTasks(),\n not(equalTo(taskIds)));\n }\n }\n\n }\n }\n\n @Test\n public void shouldNotHaveSameAssignmentOnAnyTwoHostsWhenThereArePreviousStandbyTasks() throws Exception {\n final ClientState c1 = createClientWithPreviousActiveTasks(p1, 1, task01, task02);\n c1.addPreviousStandbyTasks(Utils.mkSet(task03, task00));\n final ClientState c2 = createClientWithPreviousActiveTasks(p2, 1, task03, task00);\n c2.addPreviousStandbyTasks(Utils.mkSet(task01, task02));\n\n createClient(p3, 1);\n createClient(p4, 1);\n\n final StickyTaskAssignor taskAssignor = createTaskAssignor(task00, task02, task01, task03);\n taskAssignor.assign(1);\n\n for (int i = p1; i <= p4; i++) {\n final Set taskIds = clients.get(i).assignedTasks();\n for (int j = p1; j <= p4; j++) {\n if (j != i) {\n assertThat(\"clients shouldn't have same task assignment\", clients.get(j).assignedTasks(),\n not(equalTo(taskIds)));\n }\n }\n\n }\n }\n\n @Test\n public void shouldReBalanceTasksAcrossAllClientsWhenCapacityAndTaskCountTheSame() throws Exception {\n createClientWithPreviousActiveTasks(p3, 1, task00, task01, task02, task03);\n createClient(p1, 1);\n createClient(p2, 1);\n createClient(p4, 1);\n\n final StickyTaskAssignor taskAssignor = createTaskAssignor(task00, task02, task01, task03);\n taskAssignor.assign(0);\n\n assertThat(clients.get(p1).assignedTaskCount(), equalTo(1));\n assertThat(clients.get(p2).assignedTaskCount(), equalTo(1));\n assertThat(clients.get(p3).assignedTaskCount(), equalTo(1));\n assertThat(clients.get(p4).assignedTaskCount(), equalTo(1));\n }\n\n @Test\n public void shouldReBalanceTasksAcrossClientsWhenCapacityLessThanTaskCount() throws Exception {\n createClientWithPreviousActiveTasks(p3, 1, task00, task01, task02, task03);\n createClient(p1, 1);\n createClient(p2, 1);\n\n final StickyTaskAssignor taskAssignor = createTaskAssignor(task00, task02, task01, task03);\n taskAssignor.assign(0);\n\n assertThat(clients.get(p3).assignedTaskCount(), equalTo(2));\n assertThat(clients.get(p1).assignedTaskCount(), equalTo(1));\n assertThat(clients.get(p2).assignedTaskCount(), equalTo(1));\n }\n\n @Test\n public void shouldRebalanceTasksToClientsBasedOnCapacity() throws Exception {\n createClientWithPreviousActiveTasks(p2, 1, task00, task03, task02);\n createClient(p3, 2);\n final StickyTaskAssignor taskAssignor = createTaskAssignor(task00, task02, task03);", "answers": [" taskAssignor.assign(0);"], "length": 1185, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "6f3e6b4f-e20c-4d1c-8154-1439973993c4", "reasoning": "The test method 'shouldRebalanceTasksToClientsBasedOnCapacity' sets up two clients (p2 with capacity 1 and previous active tasks, p3 with capacity 2) and creates a StickyTaskAssignor for three tasks. Following the pattern of similar tests, after creating the assignor the next step is to invoke the assign method (with 0 to assign only active tasks) before asserting the distribution. Therefore the next line of code is the call to assign.", "reasoning_model_answer": "taskAssignor.assign(0);", "assistant_with_reasoning": "\nThe test method 'shouldRebalanceTasksToClientsBasedOnCapacity' sets up two clients (p2 with capacity 1 and previous active tasks, p3 with capacity 2) and creates a StickyTaskAssignor for three tasks. Following the pattern of similar tests, after creating the assignor the next step is to invoke the assign method (with 0 to assign only active tasks) before asserting the distribution. Therefore the next line of code is the call to assign.\n\ntaskAssignor.assign(0);", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 6.901, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 18195, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "taskAssignor.assign(0);", "score": 0.85, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "package org.apache.lucene.search;\n\n/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport java.io.IOException;\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.Collections;\nimport java.util.IdentityHashMap;\nimport java.util.Iterator;\nimport java.util.LinkedHashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\nimport org.apache.lucene.index.LeafReader;\nimport org.apache.lucene.index.LeafReader.CoreClosedListener;\nimport org.apache.lucene.index.LeafReaderContext;\nimport org.apache.lucene.util.Accountable;\nimport org.apache.lucene.util.Accountables;\nimport org.apache.lucene.util.Bits;\nimport org.apache.lucene.util.RamUsageEstimator;\nimport org.apache.lucene.util.RoaringDocIdSet;\n\n/**\n * A {@link FilterCache} that evicts filters using a LRU (least-recently-used)\n * eviction policy in order to remain under a given maximum size and number of\n * bytes used.\n *\n * This class is thread-safe.\n *\n * Note that filter eviction runs in linear time with the total number of\n * segments that have cache entries so this cache works best with\n * {@link FilterCachingPolicy caching policies} that only cache on \"large\"\n * segments, and it is advised to not share this cache across too many indices.\n *\n * Typical usage looks like this:\n *
    \n *   final int maxNumberOfCachedFilters = 256;\n *   final long maxRamBytesUsed = 50 * 1024L * 1024L; // 50MB\n *   // these cache and policy instances can be shared across several filters and readers\n *   // it is fine to eg. store them into static variables\n *   final FilterCache filterCache = new LRUFilterCache(maxNumberOfCachedFilters, maxRamBytesUsed);\n *   final FilterCachingPolicy defaultCachingPolicy = new UsageTrackingFilterCachingPolicy();\n *   \n *   // ...\n *   \n *   // Then at search time\n *   Filter myFilter = ...;\n *   Filter myCacheFilter = filterCache.doCache(myFilter, defaultCachingPolicy);\n *   // myCacheFilter is now a wrapper around the original filter that will interact with the cache\n *   IndexSearcher searcher = ...;\n *   TopDocs topDocs = searcher.search(new ConstantScoreQuery(myCacheFilter), 10);\n * 
    \n *\n * This cache exposes some global statistics ({@link #getHitCount() hit count},\n * {@link #getMissCount() miss count}, {@link #getCacheSize() number of cache\n * entries}, {@link #getCacheCount() total number of DocIdSets that have ever\n * been cached}, {@link #getEvictionCount() number of evicted entries}). In\n * case you would like to have more fine-grained statistics, such as per-index\n * or per-filter-class statistics, it is possible to override various callbacks:\n * {@link #onHit}, {@link #onMiss},\n * {@link #onFilterCache}, {@link #onFilterEviction},\n * {@link #onDocIdSetCache}, {@link #onDocIdSetEviction} and {@link #onClear}.\n * It is better to not perform heavy computations in these methods though since\n * they are called synchronously and under a lock.\n *\n * @see FilterCachingPolicy\n * @lucene.experimental\n */\npublic class LRUFilterCache implements FilterCache, Accountable {\n\n // memory usage of a simple query-wrapper filter around a term query\n static final long FILTER_DEFAULT_RAM_BYTES_USED = 216;\n\n static final long HASHTABLE_RAM_BYTES_PER_ENTRY =\n 2 * RamUsageEstimator.NUM_BYTES_OBJECT_REF // key + value\n * 2; // hash tables need to be oversized to avoid collisions, assume 2x capacity\n\n static final long LINKED_HASHTABLE_RAM_BYTES_PER_ENTRY =\n HASHTABLE_RAM_BYTES_PER_ENTRY\n + 2 * RamUsageEstimator.NUM_BYTES_OBJECT_REF; // previous & next references\n\n private final int maxSize;\n private final long maxRamBytesUsed;\n // maps filters that are contained in the cache to a singleton so that this\n // cache does not store several copies of the same filter\n private final Map uniqueFilters;\n // The contract between this set and the per-leaf caches is that per-leaf caches\n // are only allowed to store sub-sets of the filters that are contained in\n // mostRecentlyUsedFilters. This is why write operations are performed under a lock\n private final Set mostRecentlyUsedFilters;\n private final Map cache;\n\n // these variables are volatile so that we do not need to sync reads\n // but increments need to be performed under the lock\n private volatile long ramBytesUsed;\n private volatile long hitCount;\n private volatile long missCount;\n private volatile long cacheCount;\n private volatile long cacheSize;\n\n /**\n * Create a new instance that will cache at most maxSize filters\n * with at most maxRamBytesUsed bytes of memory.\n */\n public LRUFilterCache(int maxSize, long maxRamBytesUsed) {\n this.maxSize = maxSize;\n this.maxRamBytesUsed = maxRamBytesUsed;\n uniqueFilters = new LinkedHashMap(16, 0.75f, true);\n mostRecentlyUsedFilters = uniqueFilters.keySet();\n cache = new IdentityHashMap<>();\n ramBytesUsed = 0;\n }\n\n /**\n * Expert: callback when there is a cache hit on a given filter.\n * Implementing this method is typically useful in order to compute more\n * fine-grained statistics about the filter cache.\n * @see #onMiss\n * @lucene.experimental\n */\n protected void onHit(Object readerCoreKey, Filter filter) {\n hitCount += 1;\n }\n\n /**\n * Expert: callback when there is a cache miss on a given filter.\n * @see #onHit\n * @lucene.experimental\n */\n protected void onMiss(Object readerCoreKey, Filter filter) {\n assert filter != null;\n missCount += 1;\n }\n\n /**\n * Expert: callback when a filter is added to this cache.\n * Implementing this method is typically useful in order to compute more\n * fine-grained statistics about the filter cache.\n * @see #onFilterEviction\n * @lucene.experimental\n */\n protected void onFilterCache(Filter filter, long ramBytesUsed) {\n this.ramBytesUsed += ramBytesUsed;\n }\n\n /**\n * Expert: callback when a filter is evicted from this cache.\n * @see #onFilterCache\n * @lucene.experimental\n */\n protected void onFilterEviction(Filter filter, long ramBytesUsed) {\n this.ramBytesUsed -= ramBytesUsed;\n }\n\n /**\n * Expert: callback when a {@link DocIdSet} is added to this cache.\n * Implementing this method is typically useful in order to compute more\n * fine-grained statistics about the filter cache.\n * @see #onDocIdSetEviction\n * @lucene.experimental\n */\n protected void onDocIdSetCache(Object readerCoreKey, long ramBytesUsed) {\n cacheSize += 1;\n cacheCount += 1;\n this.ramBytesUsed += ramBytesUsed;\n }\n \n /**\n * Expert: callback when one or more {@link DocIdSet}s are removed from this\n * cache.\n * @see #onDocIdSetCache\n * @lucene.experimental\n */\n protected void onDocIdSetEviction(Object readerCoreKey, int numEntries, long sumRamBytesUsed) {\n this.ramBytesUsed -= sumRamBytesUsed;\n cacheSize -= numEntries;\n }\n\n /**\n * Expert: callback when the cache is completely cleared.\n * @lucene.experimental\n */\n protected void onClear() {\n ramBytesUsed = 0;\n cacheSize = 0;\n }\n\n /** Whether evictions are required. */\n boolean requiresEviction() {\n final int size = mostRecentlyUsedFilters.size();\n if (size == 0) {\n return false;\n } else {\n return size > maxSize || ramBytesUsed() > maxRamBytesUsed;\n }\n }\n\n synchronized DocIdSet get(Filter filter, LeafReaderContext context) {\n final Object readerKey = context.reader().getCoreCacheKey();\n final LeafCache leafCache = cache.get(readerKey);\n if (leafCache == null) {\n onMiss(readerKey, filter);\n return null;\n }\n // this get call moves the filter to the most-recently-used position\n final Filter singleton = uniqueFilters.get(filter);\n if (singleton == null) {\n onMiss(readerKey, filter);\n return null;\n }\n final DocIdSet cached = leafCache.get(singleton);\n if (cached == null) {\n onMiss(readerKey, singleton);\n } else {\n onHit(readerKey, singleton);\n }\n return cached;\n }\n\n synchronized void putIfAbsent(Filter filter, LeafReaderContext context, DocIdSet set) {\n // under a lock to make sure that mostRecentlyUsedFilters and cache remain sync'ed\n assert set.isCacheable();\n Filter singleton = uniqueFilters.get(filter);\n if (singleton == null) {\n uniqueFilters.put(filter, filter);\n onFilterCache(singleton, LINKED_HASHTABLE_RAM_BYTES_PER_ENTRY + ramBytesUsed(filter));\n } else {\n filter = singleton;\n }\n final Object key = context.reader().getCoreCacheKey();\n LeafCache leafCache = cache.get(key);\n if (leafCache == null) {\n leafCache = new LeafCache(key);\n final LeafCache previous = cache.put(context.reader().getCoreCacheKey(), leafCache);\n ramBytesUsed += HASHTABLE_RAM_BYTES_PER_ENTRY;\n assert previous == null;\n // we just created a new leaf cache, need to register a close listener\n context.reader().addCoreClosedListener(new CoreClosedListener() {\n @Override\n public void onClose(Object ownerCoreCacheKey) {\n clearCoreCacheKey(ownerCoreCacheKey);\n }\n });\n }\n leafCache.putIfAbsent(filter, set);\n evictIfNecessary();\n }\n\n synchronized void evictIfNecessary() {\n // under a lock to make sure that mostRecentlyUsedFilters and cache keep sync'ed\n if (requiresEviction()) {\n Iterator iterator = mostRecentlyUsedFilters.iterator();\n do {", "answers": [" final Filter filter = iterator.next();"], "length": 1269, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "faf5b8cc-b696-40b8-8a1a-e5e4dd07a1f8", "reasoning": "In the evictIfNecessary method, after obtaining an iterator over mostRecentlyUsedFilters, the loop starts with a do { block. The first operation inside the loop is to retrieve the next filter from the iterator, which is done with iterator.next() and stored in a variable for eviction processing. Therefore the next line is the assignment of the next filter.", "reasoning_model_answer": "Filter filter = iterator.next();", "assistant_with_reasoning": "\nIn the evictIfNecessary method, after obtaining an iterator over mostRecentlyUsedFilters, the loop starts with a do { block. The first operation inside the loop is to retrieve the next filter from the iterator, which is done with iterator.next() and stored in a variable for eviction processing. Therefore the next line is the assignment of the next filter.\n\nFilter filter = iterator.next();", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.761, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 10262, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "Filter filter = iterator.next();", "score": 0.82, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "// ANTLR GENERATED CODE: DO NOT EDIT\npackage org.elasticsearch.painless.antlr;\nimport org.antlr.v4.runtime.tree.AbstractParseTreeVisitor;\n\n/**\n * This class provides an empty implementation of {@link PainlessParserVisitor},\n * which can be extended to create a visitor which only needs to handle a subset\n * of the available methods.\n *\n * @param The return type of the visit operation. Use {@link Void} for\n * operations with no return type.\n */\nclass PainlessParserBaseVisitor extends AbstractParseTreeVisitor implements PainlessParserVisitor {\n /**\n * {@inheritDoc}\n *\n *

    The default implementation returns the result of calling\n * {@link #visitChildren} on {@code ctx}.

    \n */\n @Override public T visitSource(PainlessParser.SourceContext ctx) { return visitChildren(ctx); }\n /**\n * {@inheritDoc}\n *\n *

    The default implementation returns the result of calling\n * {@link #visitChildren} on {@code ctx}.

    \n */\n @Override public T visitIf(PainlessParser.IfContext ctx) { return visitChildren(ctx); }\n /**\n * {@inheritDoc}\n *\n *

    The default implementation returns the result of calling\n * {@link #visitChildren} on {@code ctx}.

    \n */\n @Override public T visitWhile(PainlessParser.WhileContext ctx) { return visitChildren(ctx); }\n /**\n * {@inheritDoc}\n *\n *

    The default implementation returns the result of calling\n * {@link #visitChildren} on {@code ctx}.

    \n */\n @Override public T visitDo(PainlessParser.DoContext ctx) { return visitChildren(ctx); }\n /**\n * {@inheritDoc}\n *\n *

    The default implementation returns the result of calling\n * {@link #visitChildren} on {@code ctx}.

    \n */\n @Override public T visitFor(PainlessParser.ForContext ctx) { return visitChildren(ctx); }\n /**\n * {@inheritDoc}\n *\n *

    The default implementation returns the result of calling\n * {@link #visitChildren} on {@code ctx}.

    \n */\n @Override public T visitEach(PainlessParser.EachContext ctx) { return visitChildren(ctx); }\n /**\n * {@inheritDoc}\n *\n *

    The default implementation returns the result of calling\n * {@link #visitChildren} on {@code ctx}.

    \n */\n @Override public T visitDecl(PainlessParser.DeclContext ctx) { return visitChildren(ctx); }\n /**\n * {@inheritDoc}\n *\n *

    The default implementation returns the result of calling\n * {@link #visitChildren} on {@code ctx}.

    \n */\n @Override public T visitContinue(PainlessParser.ContinueContext ctx) { return visitChildren(ctx); }\n /**\n * {@inheritDoc}\n *\n *

    The default implementation returns the result of calling\n * {@link #visitChildren} on {@code ctx}.

    \n */\n @Override public T visitBreak(PainlessParser.BreakContext ctx) { return visitChildren(ctx); }\n /**\n * {@inheritDoc}\n *\n *

    The default implementation returns the result of calling\n * {@link #visitChildren} on {@code ctx}.

    \n */\n @Override public T visitReturn(PainlessParser.ReturnContext ctx) { return visitChildren(ctx); }\n /**\n * {@inheritDoc}\n *\n *

    The default implementation returns the result of calling\n * {@link #visitChildren} on {@code ctx}.

    \n */\n @Override public T visitTry(PainlessParser.TryContext ctx) { return visitChildren(ctx); }\n /**\n * {@inheritDoc}\n *\n *

    The default implementation returns the result of calling\n * {@link #visitChildren} on {@code ctx}.

    \n */\n @Override public T visitThrow(PainlessParser.ThrowContext ctx) { return visitChildren(ctx); }\n /**\n * {@inheritDoc}\n *\n *

    The default implementation returns the result of calling\n * {@link #visitChildren} on {@code ctx}.

    \n */\n @Override public T visitExpr(PainlessParser.ExprContext ctx) { return visitChildren(ctx); }\n /**\n * {@inheritDoc}\n *\n *

    The default implementation returns the result of calling\n * {@link #visitChildren} on {@code ctx}.

    \n */\n @Override public T visitTrailer(PainlessParser.TrailerContext ctx) { return visitChildren(ctx); }\n /**\n * {@inheritDoc}\n *\n *

    The default implementation returns the result of calling\n * {@link #visitChildren} on {@code ctx}.

    \n */\n @Override public T visitBlock(PainlessParser.BlockContext ctx) { return visitChildren(ctx); }\n /**\n * {@inheritDoc}\n *\n *

    The default implementation returns the result of calling\n * {@link #visitChildren} on {@code ctx}.

    \n */\n @Override public T visitEmpty(PainlessParser.EmptyContext ctx) { return visitChildren(ctx); }\n /**\n * {@inheritDoc}\n *\n *

    The default implementation returns the result of calling\n * {@link #visitChildren} on {@code ctx}.

    \n */\n @Override public T visitInitializer(PainlessParser.InitializerContext ctx) { return visitChildren(ctx); }\n /**\n * {@inheritDoc}\n *\n *

    The default implementation returns the result of calling\n * {@link #visitChildren} on {@code ctx}.

    \n */\n @Override public T visitAfterthought(PainlessParser.AfterthoughtContext ctx) { return visitChildren(ctx); }\n /**\n * {@inheritDoc}\n *\n *

    The default implementation returns the result of calling\n * {@link #visitChildren} on {@code ctx}.

    \n */\n @Override public T visitDeclaration(PainlessParser.DeclarationContext ctx) { return visitChildren(ctx); }\n /**\n * {@inheritDoc}\n *\n *

    The default implementation returns the result of calling\n * {@link #visitChildren} on {@code ctx}.

    \n */\n @Override public T visitDecltype(PainlessParser.DecltypeContext ctx) { return visitChildren(ctx); }\n /**\n * {@inheritDoc}\n *\n *

    The default implementation returns the result of calling\n * {@link #visitChildren} on {@code ctx}.

    \n */\n @Override public T visitFuncref(PainlessParser.FuncrefContext ctx) { return visitChildren(ctx); }\n /**\n * {@inheritDoc}\n *\n *

    The default implementation returns the result of calling\n * {@link #visitChildren} on {@code ctx}.

    \n */\n @Override public T visitDeclvar(PainlessParser.DeclvarContext ctx) { return visitChildren(ctx); }\n /**\n * {@inheritDoc}\n *\n *

    The default implementation returns the result of calling\n * {@link #visitChildren} on {@code ctx}.

    \n */\n @Override public T visitTrap(PainlessParser.TrapContext ctx) { return visitChildren(ctx); }\n /**\n * {@inheritDoc}\n *\n *

    The default implementation returns the result of calling\n * {@link #visitChildren} on {@code ctx}.

    \n */\n @Override public T visitDelimiter(PainlessParser.DelimiterContext ctx) { return visitChildren(ctx); }\n /**\n * {@inheritDoc}\n *\n *

    The default implementation returns the result of calling\n * {@link #visitChildren} on {@code ctx}.

    \n */\n @Override public T visitSingle(PainlessParser.SingleContext ctx) { return visitChildren(ctx); }\n /**\n * {@inheritDoc}\n *\n *

    The default implementation returns the result of calling\n * {@link #visitChildren} on {@code ctx}.

    \n */\n @Override public T visitComp(PainlessParser.CompContext ctx) { return visitChildren(ctx); }\n /**\n * {@inheritDoc}\n *\n *

    The default implementation returns the result of calling\n * {@link #visitChildren} on {@code ctx}.

    \n */\n @Override public T visitBool(PainlessParser.BoolContext ctx) { return visitChildren(ctx); }\n /**\n * {@inheritDoc}\n *\n *

    The default implementation returns the result of calling\n * {@link #visitChildren} on {@code ctx}.

    \n */\n @Override public T visitConditional(PainlessParser.ConditionalContext ctx) { return visitChildren(ctx); }\n /**\n * {@inheritDoc}\n *\n *

    The default implementation returns the result of calling\n * {@link #visitChildren} on {@code ctx}.

    \n */", "answers": [" @Override public T visitAssignment(PainlessParser.AssignmentContext ctx) { return visitChildren(ctx); }"], "length": 909, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "8da5f342-61cc-4c54-ba74-de9153332d2e", "reasoning": "The class defines a visitor method for each grammar rule, each returning visitChildren(ctx). The last shown method is visitConditional. In the Painless grammar, the next rule after Conditional is typically the assignment rule (Assign). Following the established pattern, the next line should be the visitor method for Assign.", "reasoning_model_answer": "@Override public T visitAssign(PainlessParser.AssignContext ctx) { return visitChildren(ctx); }", "assistant_with_reasoning": "\nThe class defines a visitor method for each grammar rule, each returning visitChildren(ctx). The last shown method is visitConditional. In the Painless grammar, the next rule after Conditional is typically the assignment rule (Assign). Following the established pattern, the next line should be the visitor method for Assign.\n\n@Override public T visitAssign(PainlessParser.AssignContext ctx) { return visitChildren(ctx); }", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.692, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 7717, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "@Override public T visitAssign(PainlessParser.AssignContext ctx) { return visitChildren(ctx); }", "score": 0.95, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied. See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport ConfigParser\nimport os\nimport sys\n\nfrom yapsy.PluginManager import PluginManager\n\nfrom modules.util.log import LogFactory\nfrom exception import ParameterNotFoundException, InvalidConfigValueException\nimport constants\nfrom plugins.contracts import ICartridgeAgentPlugin, IArtifactCommitPlugin, IArtifactCheckoutPlugin, \\\n IHealthStatReaderPlugin\n\n\nclass Config:\n \"\"\"\n Handles the configuration information of the particular Cartridge Agent\n \"\"\"\n\n def __init__(self):\n pass\n\n AGENT_PLUGIN_EXT = \"agent-plugin\"\n ARTIFACT_CHECKOUT_PLUGIN = \"ArtifactCheckoutPlugin\"\n ARTIFACT_COMMIT_PLUGIN = \"ArtifactCommitPlugin\"\n CARTRIDGE_AGENT_PLUGIN = \"CartridgeAgentPlugin\"\n HEALTH_STAT_PLUGIN = \"HealthStatReaderPlugin\"\n\n # set log level\n log = LogFactory().get_log(__name__)\n\n payload_params = {}\n properties = None\n \"\"\" :type : ConfigParser.SafeConfigParser \"\"\"\n\n plugins = {}\n \"\"\" :type dict{str: [PluginInfo]} : \"\"\"\n artifact_checkout_plugin = None\n artifact_commit_plugin = None\n health_stat_plugin = None\n extension_executor = None\n\n application_id = None\n \"\"\" :type : str \"\"\"\n service_group = None\n \"\"\" :type : str \"\"\"\n is_clustered = False\n \"\"\" :type : bool \"\"\"\n service_name = None\n \"\"\" :type : str \"\"\"\n cluster_id = None\n \"\"\" :type : str \"\"\"\n cluster_instance_id = None\n \"\"\" :type : str \"\"\"\n member_id = None\n \"\"\" :type : str \"\"\"\n instance_id = None\n \"\"\" :type : str \"\"\"\n network_partition_id = None\n \"\"\" :type : str \"\"\"\n partition_id = None\n \"\"\" :type : str \"\"\"\n cartridge_key = None\n \"\"\" :type : str \"\"\"\n app_path = None\n \"\"\" :type : str \"\"\"\n repo_url = None\n \"\"\" :type : str \"\"\"\n ports = []\n \"\"\" :type : list[str] \"\"\"\n log_file_paths = []\n \"\"\" :type : list[str] \"\"\"\n is_multiTenant = False\n \"\"\" :type : bool \"\"\"\n persistence_mappings = None\n \"\"\" :type : str \"\"\"\n is_commits_enabled = False\n \"\"\" :type : bool \"\"\"\n is_checkout_enabled = False\n \"\"\" :type : bool \"\"\"\n listen_address = None\n \"\"\" :type : str \"\"\"\n is_internal_repo = False\n \"\"\" :type : bool \"\"\"\n tenant_id = None\n \"\"\" :type : str \"\"\"\n lb_cluster_id = None\n \"\"\" :type : str \"\"\"\n min_count = None\n \"\"\" :type : str \"\"\"\n lb_private_ip = None\n \"\"\" :type : str \"\"\"\n lb_public_ip = None\n \"\"\" :type : str \"\"\"\n tenant_repository_path = None\n \"\"\" :type : str \"\"\"\n super_tenant_repository_path = None\n \"\"\" :type : str \"\"\"\n deployment = None\n \"\"\" :type : str \"\"\"\n manager_service_name = None\n \"\"\" :type : str \"\"\"\n worker_service_name = None\n \"\"\" :type : str \"\"\"\n dependant_cluster_id = None\n \"\"\" :type : str \"\"\"\n export_metadata_keys = None\n \"\"\" :type : str \"\"\"\n import_metadata_keys = None\n \"\"\" :type : str \"\"\"\n is_primary = False\n \"\"\" :type : bool \"\"\"\n artifact_update_interval = None\n \"\"\" :type : str \"\"\"\n lvs_virtual_ip = None\n \"\"\" :type : str \"\"\"\n initialized = False\n \"\"\" :type : bool \"\"\"\n activated = False\n \"\"\" :type : bool \"\"\"\n started = False\n \"\"\" :type : bool \"\"\"\n ready_to_shutdown = False\n \"\"\" :type : bool \"\"\"\n maintenance = False\n \"\"\" :type : bool \"\"\"\n mb_urls = []\n \"\"\" :type : list \"\"\"\n mb_username = None\n \"\"\" :type : str \"\"\"\n mb_password = None\n \"\"\" :type : str \"\"\"\n mb_publisher_timeout = None\n \"\"\" :type : int \"\"\"\n cep_username = None\n \"\"\" :type : str \"\"\"\n cep_password = None\n \"\"\" :type : str \"\"\"\n cep_urls = []\n \"\"\" :type : list \"\"\"\n artifact_clone_retry_count = None\n \"\"\" :type : str \"\"\"\n artifact_clone_retry_interval = None\n \"\"\" :type : str \"\"\"\n port_check_timeout = None\n \"\"\" :type : str \"\"\"\n\n @staticmethod\n def read_conf_file():\n \"\"\"\n Reads and stores the agent's configuration file\n :return: properties object\n :rtype: ConfigParser.SafeConfigParser()\n \"\"\"\n\n conf_file_path = os.path.abspath(os.path.dirname(__file__)) + \"/agent.conf\"\n Config.log.debug(\"Config file path : %r\" % conf_file_path)\n\n properties = ConfigParser.SafeConfigParser()\n properties.read(conf_file_path)\n\n # set calculated values\n param_file = os.path.abspath(os.path.dirname(__file__)) + \"/payload/launch-params\"\n Config.log.debug(\"param_file: %r\" % param_file)\n properties.set(\"agent\", constants.PARAM_FILE_PATH, param_file)\n plugins_dir = os.path.abspath(os.path.dirname(__file__)) + \"/plugins\"\n Config.log.debug(\"plugins_dir: %r\" % plugins_dir)\n properties.set(\"agent\", constants.PLUGINS_DIR, plugins_dir)\n plugins_dir = os.path.abspath(os.path.dirname(__file__)) + \"/extensions/py\"\n properties.set(\"agent\", constants.EXTENSIONS_DIR, plugins_dir)\n\n return properties\n\n @staticmethod\n def read_payload_file(param_file_path):\n \"\"\"\n Reads the payload file of the cartridge and stores the values in a dictionary\n :param param_file_path: payload parameter file path\n :return: Payload parameter dictionary of values\n :rtype: dict\n \"\"\"\n Config.log.debug(\"Param file path : %r\" % param_file_path)\n\n try:\n payload_params = {}\n if param_file_path is not None:\n param_file = open(param_file_path)\n payload_content = param_file.read()\n for param in payload_content.split(\",\"):\n if param.strip() != \"\":\n param_value = param.strip().split(\"=\")\n try:\n if str(param_value[1]).strip().lower() == \"null\" or str(param_value[1]).strip() == \"\":\n payload_params[param_value[0]] = None\n else:\n payload_params[param_value[0]] = param_value[1]\n except IndexError:\n # If an index error comes when reading values, keep on reading\n pass\n\n param_file.close()\n return payload_params\n else:\n raise RuntimeError(\"Payload parameter file not found: %r\" % param_file_path)\n except Exception as e:\n Config.log.exception(\"Could not read payload parameter file: %s\" % e)\n\n @staticmethod\n def convert_to_type(value_string):\n \"\"\"\n Determine what type of data to return from the provided string\n :param value_string:\n :return:\n \"\"\"\n if value_string is None:\n return None\n\n value_string = str(value_string).strip()\n\n if value_string == \"\" or value_string.lower() == \"null\":\n # converted as a null value\n return None\n\n if value_string.lower() == \"true\":\n # boolean TRUE\n return True", "answers": [" if value_string.lower() == \"false\":"], "length": 895, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "d62c14d0-c214-49fa-99b7-443ed8e3d017", "reasoning": "The convert_to_type method checks string values and returns appropriate Python types. After handling the 'true' case with a return True, the next logical check is for the 'false' literal to return a boolean False. Hence the next line should start the false check.", "reasoning_model_answer": "if value_string.lower() == \"false\":", "assistant_with_reasoning": "\nThe convert_to_type method checks string values and returns appropriate Python types. After handling the 'true' case with a return True, the next logical check is for the 'false' literal to return a boolean False. Hence the next line should start the false check.\n\nif value_string.lower() == \"false\":", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.433, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 7816, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "if value_string.lower() == \"false\":", "score": 0.9, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "\"\"\"\nkombu.entity\n================\n\nExchange and Queue declarations.\n\n:copyright: (c) 2009 - 2012 by Ask Solem.\n:license: BSD, see LICENSE for more details.\n\n\"\"\"\nfrom __future__ import absolute_import\n\nfrom .abstract import MaybeChannelBound\n\nTRANSIENT_DELIVERY_MODE = 1\nPERSISTENT_DELIVERY_MODE = 2\nDELIVERY_MODES = {\"transient\": TRANSIENT_DELIVERY_MODE,\n \"persistent\": PERSISTENT_DELIVERY_MODE}\n\n__all__ = [\"Exchange\", \"Queue\"]\n\n\nclass Exchange(MaybeChannelBound):\n \"\"\"An Exchange declaration.\n\n :keyword name: See :attr:`name`.\n :keyword type: See :attr:`type`.\n :keyword channel: See :attr:`channel`.\n :keyword durable: See :attr:`durable`.\n :keyword auto_delete: See :attr:`auto_delete`.\n :keyword delivery_mode: See :attr:`delivery_mode`.\n :keyword arguments: See :attr:`arguments`.\n\n .. attribute:: name\n\n Name of the exchange. Default is no name (the default exchange).\n\n .. attribute:: type\n\n AMQP defines four default exchange types (routing algorithms) that\n covers most of the common messaging use cases. An AMQP broker can\n also define additional exchange types, so see your broker\n manual for more information about available exchange types.\n\n * `direct` (*default*)\n\n Direct match between the routing key in the message, and the\n routing criteria used when a queue is bound to this exchange.\n\n * `topic`\n\n Wildcard match between the routing key and the routing pattern\n specified in the exchange/queue binding. The routing key is\n treated as zero or more words delimited by `\".\"` and\n supports special wildcard characters. `\"*\"` matches a\n single word and `\"#\"` matches zero or more words.\n\n * `fanout`\n\n Queues are bound to this exchange with no arguments. Hence any\n message sent to this exchange will be forwarded to all queues\n bound to this exchange.\n\n * `headers`\n\n Queues are bound to this exchange with a table of arguments\n containing headers and values (optional). A special argument\n named \"x-match\" determines the matching algorithm, where\n `\"all\"` implies an `AND` (all pairs must match) and\n `\"any\"` implies `OR` (at least one pair must match).\n\n :attr:`arguments` is used to specify the arguments.\n\n This description of AMQP exchange types was shamelessly stolen\n from the blog post `AMQP in 10 minutes: Part 4`_ by\n Rajith Attapattu. This article is recommended reading.\n\n .. _`AMQP in 10 minutes: Part 4`:\n http://bit.ly/amqp-exchange-types\n\n .. attribute:: channel\n\n The channel the exchange is bound to (if bound).\n\n .. attribute:: durable\n\n Durable exchanges remain active when a server restarts. Non-durable\n exchanges (transient exchanges) are purged when a server restarts.\n Default is :const:`True`.\n\n .. attribute:: auto_delete\n\n If set, the exchange is deleted when all queues have finished\n using it. Default is :const:`False`.\n\n .. attribute:: delivery_mode\n\n The default delivery mode used for messages. The value is an integer,\n or alias string.\n\n * 1 or `\"transient\"`\n\n The message is transient. Which means it is stored in\n memory only, and is lost if the server dies or restarts.\n\n * 2 or \"persistent\" (*default*)\n The message is persistent. Which means the message is\n stored both in-memory, and on disk, and therefore\n preserved if the server dies or restarts.\n\n The default value is 2 (persistent).\n\n .. attribute:: arguments\n\n Additional arguments to specify when the exchange is declared.\n\n \"\"\"\n TRANSIENT_DELIVERY_MODE = TRANSIENT_DELIVERY_MODE\n PERSISTENT_DELIVERY_MODE = PERSISTENT_DELIVERY_MODE\n\n name = \"\"\n type = \"direct\"\n durable = True\n auto_delete = False\n delivery_mode = PERSISTENT_DELIVERY_MODE\n\n attrs = ((\"name\", None),\n (\"type\", None),\n (\"arguments\", None),\n (\"durable\", bool),\n (\"auto_delete\", bool),\n (\"delivery_mode\", lambda m: DELIVERY_MODES.get(m) or m))\n\n def __init__(self, name=\"\", type=\"\", channel=None, **kwargs):\n super(Exchange, self).__init__(**kwargs)\n self.name = name or self.name\n self.type = type or self.type\n self.maybe_bind(channel)\n\n def __hash__(self):\n return hash(\"E|%s\" % (self.name, ))\n\n def declare(self, nowait=False):\n \"\"\"Declare the exchange.\n\n Creates the exchange on the broker.\n\n :keyword nowait: If set the server will not respond, and a\n response will not be waited for. Default is :const:`False`.\n\n \"\"\"\n return self.channel.exchange_declare(exchange=self.name,\n type=self.type,\n durable=self.durable,\n auto_delete=self.auto_delete,\n arguments=self.arguments,\n nowait=nowait)\n\n def Message(self, body, delivery_mode=None, priority=None,\n content_type=None, content_encoding=None, properties=None,\n headers=None):\n \"\"\"Create message instance to be sent with :meth:`publish`.\n\n :param body: Message body.\n\n :keyword delivery_mode: Set custom delivery mode. Defaults\n to :attr:`delivery_mode`.\n\n :keyword priority: Message priority, 0 to 9. (currently not\n supported by RabbitMQ).\n\n :keyword content_type: The messages content_type. If content_type\n is set, no serialization occurs as it is assumed this is either\n a binary object, or you've done your own serialization.\n Leave blank if using built-in serialization as our library\n properly sets content_type.\n\n :keyword content_encoding: The character set in which this object\n is encoded. Use \"binary\" if sending in raw binary objects.\n Leave blank if using built-in serialization as our library\n properly sets content_encoding.\n\n :keyword properties: Message properties.\n\n :keyword headers: Message headers.\n\n \"\"\"\n properties = {} if properties is None else properties\n delivery_mode = delivery_mode or self.delivery_mode\n properties[\"delivery_mode\"] = DELIVERY_MODES.get(delivery_mode,\n delivery_mode)\n return self.channel.prepare_message(body,\n properties=properties,\n priority=priority,\n content_type=content_type,\n content_encoding=content_encoding,\n headers=headers)\n\n def publish(self, message, routing_key=None, mandatory=False,\n immediate=False, exchange=None):\n \"\"\"Publish message.\n\n :param message: :meth:`Message` instance to publish.\n :param routing_key: Routing key.\n :param mandatory: Currently not supported.\n :param immediate: Currently not supported.\n\n \"\"\"\n exchange = exchange or self.name\n return self.channel.basic_publish(message,\n exchange=exchange,\n routing_key=routing_key,\n mandatory=mandatory,\n immediate=immediate)\n\n def delete(self, if_unused=False, nowait=False):\n \"\"\"Delete the exchange declaration on server.\n\n :keyword if_unused: Delete only if the exchange has no bindings.\n Default is :const:`False`.\n\n :keyword nowait: If set the server will not respond, and a\n response will not be waited for. Default is :const:`False`.\n\n \"\"\"\n return self.channel.exchange_delete(exchange=self.name,\n if_unused=if_unused,\n nowait=nowait)\n\n def __eq__(self, other):\n if isinstance(other, Exchange):\n return (self.name == other.name and\n self.type == other.type and\n self.arguments == other.arguments and\n self.durable == other.durable and\n self.auto_delete == other.auto_delete and\n self.delivery_mode == other.delivery_mode)\n return False\n\n def __repr__(self):\n return super(Exchange, self).__repr__(\"Exchange %s(%s)\" % (self.name,\n self.type))\n\n @property\n def can_cache_declaration(self):\n return self.durable\n\n\nclass Queue(MaybeChannelBound):\n \"\"\"A Queue declaration.\n\n :keyword name: See :attr:`name`.\n :keyword exchange: See :attr:`exchange`.\n :keyword routing_key: See :attr:`routing_key`.\n :keyword channel: See :attr:`channel`.\n :keyword durable: See :attr:`durable`.\n :keyword exclusive: See :attr:`exclusive`.\n :keyword auto_delete: See :attr:`auto_delete`.\n :keyword queue_arguments: See :attr:`queue_arguments`.\n :keyword binding_arguments: See :attr:`binding_arguments`.\n\n .. attribute:: name\n\n Name of the queue. Default is no name (default queue destination).\n\n .. attribute:: exchange\n\n The :class:`Exchange` the queue binds to.\n\n .. attribute:: routing_key\n\n The routing key (if any), also called *binding key*.\n\n The interpretation of the routing key depends on\n the :attr:`Exchange.type`.\n\n * direct exchange\n\n Matches if the routing key property of the message and\n the :attr:`routing_key` attribute are identical.\n\n * fanout exchange\n\n Always matches, even if the binding does not have a key.\n\n * topic exchange\n\n Matches the routing key property of the message by a primitive\n pattern matching scheme. The message routing key then consists\n of words separated by dots (`\".\"`, like domain names), and\n two special characters are available; star (`\"*\"`) and hash\n (`\"#\"`). The star matches any word, and the hash matches\n zero or more words. For example `\"*.stock.#\"` matches the\n routing keys `\"usd.stock\"` and `\"eur.stock.db\"` but not\n `\"stock.nasdaq\"`.\n\n .. attribute:: channel\n\n The channel the Queue is bound to (if bound).\n\n .. attribute:: durable\n\n Durable queues remain active when a server restarts.\n Non-durable queues (transient queues) are purged if/when\n a server restarts.\n Note that durable queues do not necessarily hold persistent\n messages, although it does not make sense to send\n persistent messages to a transient queue.\n\n Default is :const:`True`.\n\n .. attribute:: exclusive\n\n Exclusive queues may only be consumed from by the\n current connection. Setting the 'exclusive' flag\n always implies 'auto-delete'.\n\n Default is :const:`False`.\n\n .. attribute:: auto_delete\n\n If set, the queue is deleted when all consumers have\n finished using it. Last consumer can be cancelled\n either explicitly or because its channel is closed. If\n there was no consumer ever on the queue, it won't be\n deleted.\n\n .. attribute:: queue_arguments\n\n Additional arguments used when declaring the queue.\n\n .. attribute:: binding_arguments\n\n Additional arguments used when binding the queue.\n\n .. attribute:: alias\n\n Unused in Kombu, but applications can take advantage of this.\n For example to give alternate names to queues with automatically\n generated queue names.\n\n \"\"\"\n name = \"\"\n exchange = Exchange(\"\")\n routing_key = \"\"\n\n durable = True\n exclusive = False\n auto_delete = False\n no_ack = False\n", "answers": [" attrs = ((\"name\", None),"], "length": 1242, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "0339b017-9682-4b20-be4b-199c4159ed34", "reasoning": "The Queue class definition ends with attribute defaults. The next logical part is the definition of the class's attrs tuple, mirroring the pattern used in the Exchange class. The first line of that tuple starts with the name field.", "reasoning_model_answer": "attrs = ((\"name\", None),", "assistant_with_reasoning": "\nThe Queue class definition ends with attribute defaults. The next logical part is the definition of the class's attrs tuple, mirroring the pattern used in the Exchange class. The first line of that tuple starts with the name field.\n\nattrs = ((\"name\", None),", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 5.955, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 12537, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "attrs = ((\"name\", None),", "score": 0.92, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "# Copyright 2016 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom collections import OrderedDict\nimport common, datetime, json, os, threading, time, urllib, urllib2\n\n# These tests can be run with pytest: http://doc.pytest.org/en/latest/index.html\n\ntry:\n server_address = 'http://' + os.environ[common.host_environment_variable]\nexcept KeyError:\n raise Exception('%s must be set' % common.host_environment_variable)\n\nrequest_template = server_address + '/computeMetadata/v1/{}'\nupdate_template = server_address + '/emulator/v1/update/{}'\n\ndef check_header(headers, key, value):\n assert headers.get(key.lower()) == value\n\ndef expect_content_absolute(url, expected, expected_content_type, expect_metadata_header=True):\n request = urllib2.Request(url, headers={common.metadata_flavor : common.metadata_flavor_google})\n try:\n response = urllib2.urlopen(request)\n except urllib2.URLError as e:\n raise Exception('Error connecting to emulator at %s - %s' % (server_address, e))\n\n headers = response.info().dict\n\n if expect_metadata_header:\n check_header(headers, common.metadata_flavor, common.metadata_flavor_google)\n else:\n assert common.metadata_flavor.lower() not in headers\n\n check_header(headers, common.server, common.server_value)\n check_header(headers, common.content_type, expected_content_type)\n \n contents = response.read()\n assert expected == contents\n\n return headers.get(common.etag.lower())\n\ndef expect_content(path, expected, expected_content_type, expect_metadata_header=True):\n return expect_content_absolute(request_template.format(path),\n expected,\n expected_content_type,\n expect_metadata_header)\n\ndef expect_error(path, expected_code, metadata_flavor_value=common.metadata_flavor_google):\n url = request_template.format(path)\n request = urllib2.Request(url,\n headers={common.metadata_flavor :\n metadata_flavor_value} if metadata_flavor_value else {})\n try:\n response = urllib2.urlopen(request)\n # This will always fail but I'm asserting so the response appears in the test results\n assert response.read() is None\n except urllib2.HTTPError as e:\n check_header(e.headers, common.metadata_flavor, common.metadata_flavor_google)\n check_header(e.headers, common.server, common.server_value)\n check_header(e.headers, common.content_type, common.content_type_html)\n assert e.code == expected_code\n except urllib2.URLError as e:\n raise Exception('Error connecting to emulator at %s - %s' % (server_address, e))\n\ndef expect_error_deleting_content(path, expected_code):\n request = urllib2.Request(url = update_template.format(path),\n headers={common.metadata_flavor: common.metadata_flavor_google})\n request.get_method = lambda: \"DELETE\"\n try:\n response = urllib2.urlopen(request)\n # This will always fail but I'm asserting so the response appears in the test results\n assert response.read() is None\n except urllib2.HTTPError as e:\n check_header(e.headers, common.metadata_flavor, common.metadata_flavor_google)\n check_header(e.headers, common.server, common.server_value)\n check_header(e.headers, common.content_type, common.content_type_html)\n assert e.code == expected_code\n except urllib2.URLError as e:\n raise Exception('Error connecting to emulator at %s - %s' % (server_address, e))\n\ndef expect_error_updating_content(path, new_data, expected_code):\n if not isinstance(new_data, str):\n new_data = json.dumps(new_data, separators=(',', ':'))\n\n data = urllib.quote_plus(new_data)\n request = urllib2.Request(update_template.format(path),\n data,\n headers={common.metadata_flavor: common.metadata_flavor_google,\n common.content_type: common.content_type_text})\n \n try:\n response = urllib2.urlopen(request)\n # This will always fail but I'm asserting so the response appears in the test results\n assert response.read() is None\n except urllib2.HTTPError as e:\n check_header(e.headers, common.metadata_flavor, common.metadata_flavor_google)\n check_header(e.headers, common.server, common.server_value)\n check_header(e.headers, common.content_type, common.content_type_html)\n assert e.code == expected_code\n except urllib2.URLError as e:\n raise Exception('Error connecting to emulator at %s - %s' % (server_address, e))\n\ndef check_path(path, expected, default='text'):\n expected_json = json.dumps(expected, separators=(',', ':'))\n if isinstance(expected, list):\n expected_text = ''.join(s + '\\n' for s in expected)\n else:\n expected_text = unicode(expected)\n \n etag1 = expect_content(path,\n expected_text if default == 'text' else expected_json,\n common.content_type_text if default == 'text' else common.content_type_json)\n etag2 = expect_content(path + \"?alt=text\", expected_text, common.content_type_text)\n etag3 = expect_content(path + \"?alt=json\", expected_json, common.content_type_json) \n assert len(etag1) == 16\n assert etag1 == etag2\n assert etag1 == etag3\n\ndef check_dir(path, expected):\n etag1 = expect_content(path, expected, common.content_type_text)\n assert len(etag1) == 16\n if path:\n etag2 = expect_content(path + '/', expected, common.content_type_text)\n assert etag1 == etag2\n\ndef check_dir_absolute(url, expected):\n etag1 = expect_content_absolute(url, expected, common.content_type_text)\n etag2 = expect_content_absolute(url + '/', expected, common.content_type_text)\n assert len(etag1) == 16\n assert etag1 == etag2\n\ndef check_dir_recursive(path, expected, test_trailing_slash=True, use_recursive_field=True, expect_metadata_header=True):\n query = '?recursive=true' if use_recursive_field else ''\n etag1 = expect_content(path + query, expected, common.content_type_json, expect_metadata_header)\n if test_trailing_slash:\n etag2 = expect_content(path + '/' + query, expected, common.content_type_json, expect_metadata_header)\n else:\n etag2 = etag1\n\n data = json.loads(expected, object_pairs_hook=OrderedDict)\n\n def convertToText(prefix, o):\n text = ''\n if isinstance(o, list):\n if len(o) != 0:\n if isinstance(o[0], OrderedDict):\n for i in range(len(o)):\n text += convertToText(prefix + ('/' if len(prefix) != 0 else '') + unicode(i), o[i])\n else:\n for i in range(len(o)):\n text += convertToText(prefix, o[i])\n elif isinstance(o, OrderedDict):\n for key in o:\n text += convertToText(prefix + ('/' if len(prefix) != 0 else '') + common.convertToDashed(key),\n o[key])\n else:\n text += prefix + ' ' + unicode(o) + '\\n'\n\n return text\n\n expected_text = convertToText('', data)\n query = '?recursive=true&alt=text' if use_recursive_field else '?alt=text'\n etag3 = expect_content(path + query, expected_text, common.content_type_text, expect_metadata_header)\n if test_trailing_slash:\n etag4 = expect_content(path + '/' + query, expected_text, common.content_type_text, expect_metadata_header)\n else:\n etag4 = etag3\n \n query = '?recursive=true&alt=json' if use_recursive_field else '?alt=json'\n etag5 = expect_content(path + query, expected, common.content_type_json, expect_metadata_header)\n if test_trailing_slash:\n etag6 = expect_content(path + '/' + query, expected, common.content_type_json, expect_metadata_header)\n else:\n etag6 = etag5\n\n assert len(etag1) == 16\n assert etag1 == etag2\n assert etag1 == etag3\n assert etag1 == etag4\n assert etag1 == etag5\n assert etag1 == etag6\n\ndef delete_content(path):\n request = urllib2.Request(update_template.format(path),\n headers={common.metadata_flavor: common.metadata_flavor_google})\n request.get_method = lambda: \"DELETE\"\n try:\n urllib2.urlopen(request)\n except urllib2.URLError as e:\n raise Exception('Error connecting to emulator at %s - %s' % (server_address, e))\n\ndef update_content(path, new_data):\n if not isinstance(new_data, str):\n new_data = json.dumps(new_data, separators=(',', ':'))\n\n data = urllib.quote_plus(new_data)\n request = urllib2.Request(update_template.format(path),\n data,\n headers={common.metadata_flavor: common.metadata_flavor_google,\n common.content_type: common.content_type_text})\n \n try:\n urllib2.urlopen(request)\n except urllib2.URLError as e:\n raise Exception('Error connecting to emulator at %s - %s' % (server_address, e))\n\ndef test_root():\n check_dir_absolute(server_address, '0.1/\\ncomputeMetadata/\\n')\n\ndef test_root_computeMetadata():\n check_dir_absolute(server_address + '/computeMetadata', 'v1/\\nv1beta1/\\n')\n\ndef test_root_computeMetadata_v1():\n check_dir('', 'instance/\\nproject/\\n')\n\ndef test_instance():\n check_dir('instance', 'attributes/\\ncpu-platform\\ndescription\\ndisks/\\nhostname\\nid\\nimage\\nlicenses/\\nmachine-type\\n'\n 'maintenance-event\\nnetwork-interfaces/\\nscheduling/\\nservice-accounts/\\ntags\\nvirtual-clock/\\nzone\\n')\n\ndef test_instance_attributes():\n check_dir('instance/attributes', 'my_instance_key1\\n')\n\ndef test_instance_attributes_myinstancekey1():\n check_path('instance/attributes/my_instance_key1', 'my_instance_value1')\n\ndef test_instance_cpuplatform():\n check_path('instance/cpu-platform', 'Intel Haswell')\n\ndef test_instance_description():\n check_path('instance/description', 'Fake instance for metadata server emulator')\n\ndef test_instance_disks():\n check_dir('instance/disks', '0/\\n')\n\ndef test_instance_disks_0():\n check_dir('instance/disks/0', 'device-name\\nindex\\nmode\\ntype\\n')\n\ndef test_instance_disks_0_devicename():\n check_path('instance/disks/0/device-name', 'boot')\n\ndef test_instance_disks_0_index():\n check_path('instance/disks/0/index', 0)\n\ndef test_instance_disks_0_mode():\n check_path('instance/disks/0/mode', 'READ_WRITE')\n\ndef test_instance_disks_0_type():\n check_path('instance/disks/0/type', 'PERSISTENT')\n\ndef test_instance_hostname():\n check_path('instance/hostname', 'name.project.google.com.internal')\n\ndef test_instance_id():\n check_path('instance/id', 13512546227574112017)\n\ndef test_instance_image():\n check_path('instance/image', '')\n\ndef test_instance_licenses():\n check_dir('instance/licenses', '0/\\n1/\\n2/\\n')\n\ndef test_instance_licenses_0():\n check_dir('instance/licenses/0', 'id\\n')\n\ndef test_instance_licenses_0_id():\n check_path('instance/licenses/0/id', '0')\n\ndef test_instance_machinetype():\n check_path('instance/machine-type', 'projects/12345/machineTypes/n1-standard-1')\n\ndef test_instance_maintenanceevent():\n check_path('instance/maintenance-event', 'NONE')\n\ndef test_instance_networkinterfaces():\n check_dir('instance/network-interfaces', '0/\\n')\n\ndef test_instance_networkinterfaces_0():\n check_dir('instance/network-interfaces/0', 'access-configs/\\nforwarded-ips/\\nip\\nip-aliases/\\nmac\\nnetwork\\n')\n\ndef test_instance_networkinterfaces_0_accessconfigs():\n check_dir('instance/network-interfaces/0/access-configs', '0/\\n')\n\ndef test_instance_networkinterfaces_0_accessconfigs_0():\n check_dir('instance/network-interfaces/0/access-configs/0', 'external-ip\\ntype\\n')\n\ndef test_instance_networkinterfaces_0_accessconfigs_0_externalip():\n check_path('instance/network-interfaces/0/access-configs/0/external-ip', '0.0.0.0')\n\ndef test_instance_networkinterfaces_0_accessconfigs_0_type():\n check_path('instance/network-interfaces/0/access-configs/0/type', 'ONE_TO_ONE_NAT')\n\ndef test_instance_networkinterfaces_0_forwardedips():\n check_dir('instance/network-interfaces/0/forwarded-ips', '')\n\ndef test_instance_networkinterfaces_0_ip():\n check_path('instance/network-interfaces/0/ip', '0.0.0.0')\n\ndef test_instance_networkinterfaces_0_ipaliases():\n check_dir('instance/network-interfaces/0/ip-aliases', '')\n\ndef test_instance_networkinterfaces_0_mac():\n check_path('instance/network-interfaces/0/mac', '00:00:00:00:00:00')\n\ndef test_instance_networkinterfaces_0_network():\n check_path('instance/network-interfaces/0/network', 'projects/12345/networks/default')\n\ndef test_instance_scheduling():\n check_dir('instance/scheduling', 'automatic-restart\\non-host-maintenance\\npreemptible\\n')\n\ndef test_instance_scheduling_automaticrestart():\n check_path('instance/scheduling/automatic-restart', 'TRUE')\n\ndef test_instance_scheduling_onhostmaintenance():\n check_path('instance/scheduling/on-host-maintenance', 'MIGRATE')\n\ndef test_instance_scheduling_preemptible():\n check_path('instance/scheduling/preemptible', 'FALSE')\n\ndef test_instance_serviceaccounts():\n check_dir('instance/service-accounts', '12345-compute@developer.gserviceaccount.com/\\ndefault/\\n')\n\ndef test_instance_serviceaccounts_0():\n check_dir('instance/service-accounts/12345-compute@developer.gserviceaccount.com', 'aliases\\nemail\\nscopes\\ntoken\\n')\n\ndef test_instance_serviceaccounts_0_aliases():\n check_path('instance/service-accounts/12345-compute@developer.gserviceaccount.com/aliases', ['default'])\n\ndef test_instance_serviceaccounts_0_email():\n check_path('instance/service-accounts/12345-compute@developer.gserviceaccount.com/email',\n '12345-compute@developer.gserviceaccount.com')\n\ndef test_instance_serviceaccounts_0_scopes():\n check_path('instance/service-accounts/12345-compute@developer.gserviceaccount.com/scopes',\n ['https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/userinfo.email'])\n\ndef test_instance_serviceaccounts_default():\n check_dir('instance/service-accounts/default', 'aliases\\nemail\\nscopes\\ntoken\\n')\n\ndef test_instance_serviceaccounts_default_aliases():\n check_path('instance/service-accounts/default/aliases', ['default'])\n\ndef test_instance_serviceaccounts_default_email():\n check_path('instance/service-accounts/default/email', '12345-compute@developer.gserviceaccount.com')\n\ndef test_instance_serviceaccounts_default_scopes():\n check_path('instance/service-accounts/default/scopes',\n ['https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/userinfo.email'])\n\ndef test_instance_tags():\n check_path('instance/tags', ['a', 'b', 'c'], default='json')\n\ndef test_instance_virtualclock():\n check_dir('instance/virtual-clock', 'drift-token\\n')\n\ndef test_instance_virtualclock_drifttoken():\n check_path('instance/virtual-clock/drift-token', '0')\n\ndef test_instance_zone():\n check_path('instance/zone', 'projects/12345/zones/us-central1-f')\n\ndef test_project():\n check_dir('project', 'attributes/\\nnumeric-project-id\\nproject-id\\n')\n\ndef test_project_attributes():\n check_dir('project/attributes', 'my_project_key1\\n')\n\ndef test_project_attributes_myprojectkey1():\n check_path('project/attributes/my_project_key1', 'my_project_value1')\n\ndef test_project_numericprojectid():\n check_path('project/numeric-project-id', 12345)\n\ndef test_project_projectid():\n check_path('project/project-id', 'fake-project')\n\ndef test_double_slash():\n check_path('project//project-id', 'fake-project')\n\ndef test_recursive_token_1():\n check_dir_recursive('instance/service-accounts/12345-compute@developer.gserviceaccount.com/token',\n '{\"access_token\":\"0123456789ABCDEF\",\"expires_in\":3000,\"token_type\":\"Bearer\"}',\n test_trailing_slash=False,\n use_recursive_field=False,\n expect_metadata_header=False)\n\ndef test_recursive_token_2():\n check_dir_recursive('instance/service-accounts/12345-compute@developer.gserviceaccount.com/token',\n '{\"access_token\":\"0123456789ABCDEF\",\"expires_in\":3000,\"token_type\":\"Bearer\"}',\n test_trailing_slash=False,\n use_recursive_field=True,\n expect_metadata_header=False)\n\ndef test_recursive_token_3():\n check_dir_recursive('instance/service-accounts/default/token',\n '{\"access_token\":\"0123456789ABCDEF\",\"expires_in\":3000,\"token_type\":\"Bearer\"}',\n test_trailing_slash=False,\n use_recursive_field=False,\n expect_metadata_header=False)\n\ndef test_recursive_token_4():\n check_dir_recursive('instance/service-accounts/default/token',\n '{\"access_token\":\"0123456789ABCDEF\",\"expires_in\":3000,\"token_type\":\"Bearer\"}',\n test_trailing_slash=False,\n use_recursive_field=True,\n expect_metadata_header=False)\n\ndef test_recursive_instance_attributes():\n check_dir_recursive('instance/attributes', '{\"my_instance_key1\":\"my_instance_value1\"}')\n\ndef test_recursive_instance_disks():\n check_dir_recursive('instance/disks', '[{\"deviceName\":\"boot\",\"index\":0,\"mode\":\"READ_WRITE\",\"type\":\"PERSISTENT\"}]')\n\ndef test_recursive_instance_disks_0():\n check_dir_recursive('instance/disks/0', '{\"deviceName\":\"boot\",\"index\":0,\"mode\":\"READ_WRITE\",\"type\":\"PERSISTENT\"}')\n\ndef test_recursive_instance_licenses():\n check_dir_recursive('instance/licenses', '[{\"id\":\"0\"},{\"id\":\"1\"},{\"id\":\"2\"}]')\n\ndef test_recursive_instance_licenses_0():\n check_dir_recursive('instance/licenses/0', '{\"id\":\"0\"}')\n\ndef test_recursive_instance_networkinterfaces():\n check_dir_recursive('instance/network-interfaces',\n '[{\"accessConfigs\":[{\"externalIp\":\"0.0.0.0\",\"type\":\"ONE_TO_ONE_NAT\"}],\"forwardedIps\":[],\"ip\":\"0.0.0.0\",'\n '\"ipAliases\":[],\"mac\":\"00:00:00:00:00:00\",\"network\":\"projects/12345/networks/default\"}]')\n\ndef test_recursive_instance_networkinterfaces_0():\n check_dir_recursive('instance/network-interfaces/0',\n '{\"accessConfigs\":[{\"externalIp\":\"0.0.0.0\",\"type\":\"ONE_TO_ONE_NAT\"}],\"forwardedIps\":[],\"ip\":\"0.0.0.0\",'\n '\"ipAliases\":[],\"mac\":\"00:00:00:00:00:00\",\"network\":\"projects/12345/networks/default\"}')\n\ndef test_recursive_instance_networkinterfaces_0_accessconfigs():\n check_dir_recursive('instance/network-interfaces/0/access-configs', '[{\"externalIp\":\"0.0.0.0\",\"type\":\"ONE_TO_ONE_NAT\"}]')\n\ndef test_recursive_instance_networkinterfaces_0_forwardedips():\n check_dir_recursive('instance/network-interfaces/0/forwarded-ips', '[]')\n\ndef test_recursive_instance_networkinterfaces_0_ipaliases():\n check_dir_recursive('instance/network-interfaces/0/ip-aliases', '[]')\n\ndef test_recursive_instance_scheduling():\n check_dir_recursive('instance/scheduling', '{\"automaticRestart\":\"TRUE\",\"onHostMaintenance\":\"MIGRATE\",\"preemptible\":\"FALSE\"}')\n\ndef test_recursive_instance_serviceaccounts():\n check_dir_recursive('instance/service-accounts',\n '{\"12345-compute@developer.gserviceaccount.com\":{\"aliases\":[\"default\"],'\n '\"email\":\"12345-compute@developer.gserviceaccount.com\",'\n '\"scopes\":[\"https://www.googleapis.com/auth/cloud-platform\",\"https://www.googleapis.com/auth/userinfo.email\"]},'\n '\"default\":{\"aliases\":[\"default\"],\"email\":\"12345-compute@developer.gserviceaccount.com\",'\n '\"scopes\":[\"https://www.googleapis.com/auth/cloud-platform\",\"https://www.googleapis.com/auth/userinfo.email\"]}}')\n\ndef test_recursive_instance_serviceaccounts_1():\n check_dir_recursive('instance/service-accounts/12345-compute@developer.gserviceaccount.com',\n '{\"aliases\":[\"default\"],\"email\":\"12345-compute@developer.gserviceaccount.com\",'\n '\"scopes\":[\"https://www.googleapis.com/auth/cloud-platform\",\"https://www.googleapis.com/auth/userinfo.email\"]}')\n\ndef test_recursive_instance_serviceaccounts_2():\n check_dir_recursive('instance/service-accounts/default',\n '{\"aliases\":[\"default\"],\"email\":\"12345-compute@developer.gserviceaccount.com\",'\n '\"scopes\":[\"https://www.googleapis.com/auth/cloud-platform\",\"https://www.googleapis.com/auth/userinfo.email\"]}')\n\ndef test_recursive_instance_virtualclock():\n check_dir_recursive('instance/virtual-clock', '{\"driftToken\":\"0\"}')\n\ndef test_recursive_project():\n check_dir_recursive('project',\n '{\"attributes\":{\"my_project_key1\":\"my_project_value1\"},\"numericProjectId\":12345,\"projectId\":\"fake-project\"}')\n\ndef test_recursive_project_attributes():\n check_dir_recursive('project/attributes', '{\"my_project_key1\":\"my_project_value1\"}')\n\ndef test_recursive_value():\n expect_content('project/numeric-project-id?recursive=true', '12345', common.content_type_text)\n\ndef test_recursive_value_alt_1():\n expect_content('project/numeric-project-id?recursive=true&alt=text', '12345', common.content_type_text)\n\ndef test_recursive_value_alt_2():\n expect_content('project/numeric-project-id?recursive=true&alt=json', '12345', common.content_type_json)\n\ndef test_ignore_nonsense_parameters():\n expect_content('instance/scheduling/automatic-restart?last_etag=abc&timeout_sec=5&foo=blah', 'TRUE', common.content_type_text)\n\ndef test_ignore_nonsense_values():\n expect_content('instance/network-interfaces?recursive=xyz', '0/\\n', common.content_type_text)\n\ndef test_error_no_metadata_flavor_1():\n expect_error('', 403, metadata_flavor_value='')\n\ndef test_error_wrong_metadata_flavor_1():\n expect_error('', 403, metadata_flavor_value='Something-Else')\n\ndef test_error_no_metadata_flavor_2():\n expect_error('instance', 403, metadata_flavor_value='')\n\ndef test_error_wrong_metadata_flavor_2():\n expect_error('instance', 403, metadata_flavor_value='Something-Else')\n\ndef test_error_bad_index_1():\n expect_error('instance/disks/x', 404)\n\ndef test_error_bad_index_2():\n expect_error('instance/disks/99', 404)\n\ndef test_error_slash_on_value():\n expect_error('instance/virtual-clock/drift-token/', 404)\n\ndef test_error_bad_key_1():\n expect_error('foo', 404)\n\ndef test_error_bad_key_2():\n expect_error('project/bar', 404)\n\ndef test_error_alt_on_dir_1():\n expect_error('project?alt=json', 400)\n\ndef test_error_alt_on_dir_2():\n expect_error('project?alt=text', 400)\n\ndef test_error_wait_on_dir_without_recursive():\n expect_error('project?wait_for_change=true', 400)\n\ndef test_error_slash_on_token():\n expect_error('instance/service-accounts/default/token/', 404)\n\ndef test_error_index_into_array_value():\n expect_error('instance/service-accounts/12345-compute@developer.gserviceaccount.com/scopes/0', 404)\n\ndef test_timeout_sec():\n start = datetime.datetime.now()\n expect_content('instance/scheduling/automatic-restart?wait_for_change=true&timeout_sec=5', 'TRUE', common.content_type_text)\n end = datetime.datetime.now()\n elapsed = end - start\n assert elapsed.seconds > 5\n\ndef test_update_string():\n path = 'instance/cpu-platform'\n original = 'Intel Haswell'\n changed = 'My Platform'\n\n check_path(path, original)", "answers": [" update_content(path, changed)"], "length": 1310, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "0b7cc42a-2ab8-4f25-87da-174d85bd8716", "reasoning": "The test_update_string function sets up a path and original/changed values, then verifies the original value with check_path. The logical next step is to perform the update using the helper update_content, passing the new value, before checking the updated value. Therefore the next line should call update_content with the path and changed value.", "reasoning_model_answer": "update_content(path, changed)", "assistant_with_reasoning": "\nThe test_update_string function sets up a path and original/changed values, then verifies the original value with check_path. The logical next step is to perform the update using the helper update_content, passing the new value, before checking the updated value. Therefore the next line should call update_content with the path and changed value.\n\nupdate_content(path, changed)", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 2.593, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 23441, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "update_content(path, changed)", "score": 0.97, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\nusing System.Diagnostics;\n\nnamespace System.Threading\n{\n /// \n /// Propagates notification that operations should be canceled.\n /// \n /// \n /// \n /// A may be created directly in an unchangeable canceled or non-canceled state\n /// using the CancellationToken's constructors. However, to have a CancellationToken that can change \n /// from a non-canceled to a canceled state, \n /// CancellationTokenSource must be used.\n /// CancellationTokenSource exposes the associated CancellationToken that may be canceled by the source through its \n /// Token property. \n /// \n /// \n /// Once canceled, a token may not transition to a non-canceled state, and a token whose \n /// is false will never change to one that can be canceled.\n /// \n /// \n /// All members of this struct are thread-safe and may be used concurrently from multiple threads.\n /// \n /// \n [DebuggerDisplay(\"IsCancellationRequested = {IsCancellationRequested}\")]\n public struct CancellationToken\n {\n private readonly static Action s_actionToActionObjShunt = obj => ((Action)obj)();\n\n // The backing TokenSource. \n // if null, it implicitly represents the same thing as new CancellationToken(false).\n // When required, it will be instantiated to reflect this.\n private readonly CancellationTokenSource _source;\n //!! warning. If more fields are added, the assumptions in CreateLinkedToken may no longer be valid\n\n /// \n /// Returns an empty CancellationToken value.\n /// \n /// \n /// The value returned by this property will be non-cancelable by default.\n /// \n public static CancellationToken None => default(CancellationToken);\n\n /// \n /// Gets whether cancellation has been requested for this token.\n /// \n /// Whether cancellation has been requested for this token.\n /// \n /// \n /// This property indicates whether cancellation has been requested for this token, \n /// either through the token initially being constructed in a canceled state, or through\n /// calling Cancel \n /// on the token's associated .\n /// \n /// \n /// If this property is true, it only guarantees that cancellation has been requested. \n /// It does not guarantee that every registered handler\n /// has finished executing, nor that cancellation requests have finished propagating\n /// to all registered handlers. Additional synchronization may be required,\n /// particularly in situations where related objects are being canceled concurrently.\n /// \n /// \n public bool IsCancellationRequested => _source != null && _source.IsCancellationRequested;\n\n /// \n /// Gets whether this token is capable of being in the canceled state.\n /// \n /// \n /// If CanBeCanceled returns false, it is guaranteed that the token will never transition\n /// into a canceled state, meaning that will never\n /// return true.\n /// \n public bool CanBeCanceled => _source != null;\n\n /// \n /// Gets a that is signaled when the token is canceled.\n /// \n /// Accessing this property causes a WaitHandle\n /// to be instantiated. It is preferable to only use this property when necessary, and to then\n /// dispose the associated instance at the earliest opportunity (disposing\n /// the source will dispose of this allocated handle). The handle should not be closed or disposed directly.\n /// \n /// The associated CancellationTokenSource has been disposed.\n public WaitHandle WaitHandle => (_source ?? CancellationTokenSource.s_neverCanceledSource).WaitHandle;\n\n // public CancellationToken()\n // this constructor is implicit for structs\n // -> this should behaves exactly as for new CancellationToken(false)\n\n /// \n /// Internal constructor only a CancellationTokenSource should create a CancellationToken\n /// \n internal CancellationToken(CancellationTokenSource source) => _source = source;\n\n /// \n /// Initializes the CancellationToken.\n /// \n /// \n /// The canceled state for the token.\n /// \n /// \n /// Tokens created with this constructor will remain in the canceled state specified\n /// by the parameter. If is false,\n /// both and will be false.\n /// If is true,\n /// both and will be true. \n /// \n public CancellationToken(bool canceled) : this(canceled ? CancellationTokenSource.s_canceledSource : null)\n {\n }\n\n /// \n /// Registers a delegate that will be called when this CancellationToken is canceled.\n /// \n /// \n /// \n /// If this token is already in the canceled state, the\n /// delegate will be run immediately and synchronously. Any exception the delegate generates will be\n /// propagated out of this method call.\n /// \n /// \n /// The current ExecutionContext, if one exists, will be captured\n /// along with the delegate and will be used when executing it.\n /// \n /// \n /// The delegate to be executed when the CancellationToken is canceled.\n /// The instance that can \n /// be used to deregister the callback.\n /// is null.\n public CancellationTokenRegistration Register(Action callback) =>\n Register(\n s_actionToActionObjShunt,\n callback ?? throw new ArgumentNullException(nameof(callback)),\n useSyncContext: false,\n useExecutionContext: true);\n\n /// \n /// Registers a delegate that will be called when this \n /// CancellationToken is canceled.\n /// \n /// \n /// \n /// If this token is already in the canceled state, the\n /// delegate will be run immediately and synchronously. Any exception the delegate generates will be\n /// propagated out of this method call.\n /// \n /// \n /// The current ExecutionContext, if one exists, will be captured\n /// along with the delegate and will be used when executing it.\n /// \n /// \n /// The delegate to be executed when the CancellationToken is canceled.\n /// A Boolean value that indicates whether to capture\n /// the current SynchronizationContext and use it\n /// when invoking the .\n /// The instance that can \n /// be used to deregister the callback.\n /// is null.\n public CancellationTokenRegistration Register(Action callback, bool useSynchronizationContext) =>\n Register(\n s_actionToActionObjShunt,\n callback ?? throw new ArgumentNullException(nameof(callback)),\n useSynchronizationContext,\n useExecutionContext: true);\n\n /// \n /// Registers a delegate that will be called when this \n /// CancellationToken is canceled.\n /// \n /// \n /// \n /// If this token is already in the canceled state, the\n /// delegate will be run immediately and synchronously. Any exception the delegate generates will be\n /// propagated out of this method call.\n /// \n /// \n /// The current ExecutionContext, if one exists, will be captured\n /// along with the delegate and will be used when executing it.\n /// \n /// \n /// The delegate to be executed when the CancellationToken is canceled.\n /// The state to pass to the when the delegate is invoked. This may be null.\n /// The instance that can \n /// be used to deregister the callback.\n /// is null.", "answers": [" public CancellationTokenRegistration Register(Action callback, object state) =>"], "length": 1122, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "f74d2a13-384c-4983-96d9-188dab671cc6", "reasoning": "The code is defining overloads of the Register method for CancellationToken. After the XML documentation for the overload that takes a callback and a state object, the next line should be the method signature and expression-bodied implementation that forwards to the internal Register method, performing a null check on the callback. This matches the pattern of the earlier overloads.", "reasoning_model_answer": "public CancellationTokenRegistration Register(Action callback, object state) =>\n Register(callback ?? throw new ArgumentNullException(nameof(callback)), state, useSynchronizationContext: false, useExecutionContext: true);", "assistant_with_reasoning": "\nThe code is defining overloads of the Register method for CancellationToken. After the XML documentation for the overload that takes a callback and a state object, the next line should be the method signature and expression-bodied implementation that forwards to the internal Register method, performing a null check on the callback. This matches the pattern of the earlier overloads.\n\npublic CancellationTokenRegistration Register(Action callback, object state) =>\n Register(callback ?? throw new ArgumentNullException(nameof(callback)), state, useSynchronizationContext: false, useExecutionContext: true);", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 6.455, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 10904, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "public CancellationTokenRegistration Register(Action callback, object state) =>\n Register(callback ?? throw new ArgumentNullException(nameof(callback)), state, useSynchronizationContext: false, useExecutionContext: true);", "score": 0.96, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/*******************************************************************************\n * Copyright (c) 2000, 2009 IBM Corporation and others.\n * All rights reserved. This program and the accompanying materials\n * are made available under the terms of the Eclipse Public License v1.0\n * which accompanies this distribution, and is available at\n * http://www.eclipse.org/legal/epl-v10.html\n *\n * Contributors:\n * IBM Corporation - initial API and implementation\n *******************************************************************************/\n\npackage org.eclipse.wst.jsdt.core.dom;\n\nimport java.util.ArrayList;\nimport java.util.Iterator;\nimport java.util.List;\n\n/**\n * Type declaration AST node type. A type declaration\n * is the union of a class declaration and an interface declaration.\n * For JLS2:\n *
    \n * TypeDeclaration:\n * \t\tClassDeclaration\n * \t\tInterfaceDeclaration\n * ClassDeclaration:\n *      [ jsdoc ] { Modifier } class Identifier\n *\t\t\t[ extends Type]\n *\t\t\t[ implements Type { , Type } ]\n *\t\t\t{ { ClassBodyDeclaration | ; } }\n * InterfaceDeclaration:\n *      [ jsdoc ] { Modifier } interface Identifier\n *\t\t\t[ extends Type { , Type } ]\n * \t\t\t{ { InterfaceBodyDeclaration | ; } }\n * 
    \n * For JLS3, type parameters and reified modifiers\n * (and annotations) were added, and the superclass type name and superinterface\n * types names are generalized to type so that parameterized types can be\n * referenced:\n *
    \n * TypeDeclaration:\n * \t\tClassDeclaration\n * \t\tInterfaceDeclaration\n * ClassDeclaration:\n *      [ jsdoc ] { ExtendedModifier } class Identifier\n *\t\t\t[ < TypeParameter { , TypeParameter } > ]\n *\t\t\t[ extends Type ]\n *\t\t\t[ implements Type { , Type } ]\n *\t\t\t{ { ClassBodyDeclaration | ; } }\n * InterfaceDeclaration:\n *      [ jsdoc ] { ExtendedModifier } interface Identifier\n *\t\t\t[ < TypeParameter { , TypeParameter } > ]\n *\t\t\t[ extends Type { , Type } ]\n * \t\t\t{ { InterfaceBodyDeclaration | ; } }\n * 
    \n *

    \n * When a jsdoc comment is present, the source\n * range begins with the first character of the \"/**\" comment delimiter.\n * When there is no jsdoc comment, the source range begins with the first\n * character of the first modifier or annotation (if any), or the\n * first character of the \"class\" or \"interface\" keyword (if no\n * modifiers or annotations). The source range extends through the last character of the \"}\"\n * token following the body declarations.\n *

    \n * \n *

    Note: This Class only applies to ECMAScript 4 which is not yet supported

    \n *\n * Provisional API: This class/interface is part of an interim API that is still under development and expected to \n * change significantly before reaching stability. It is being made available at this early stage to solicit feedback \n * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken \n * (repeatedly) as the API evolves.\n */\npublic class TypeDeclaration extends AbstractTypeDeclaration {\n\n\t/**\n\t * The \"javadoc\" structural property of this node type.\n\t * \n\t */\n\tpublic static final ChildPropertyDescriptor JAVADOC_PROPERTY =\n\t\tinternalJavadocPropertyFactory(TypeDeclaration.class);\n\n\t/**\n\t * The \"modifiers\" structural property of this node type (JLS2 API only).\n\t * \n\t */\n\tpublic static final SimplePropertyDescriptor MODIFIERS_PROPERTY =\n\t\tinternalModifiersPropertyFactory(TypeDeclaration.class);\n\n\t/**\n\t * The \"modifiers\" structural property of this node type (added in JLS3 API).\n\t * \n\t */\n\tpublic static final ChildListPropertyDescriptor MODIFIERS2_PROPERTY =\n\t\tinternalModifiers2PropertyFactory(TypeDeclaration.class);\n\n\t/**\n\t * The \"name\" structural property of this node type.\n\t * \n\t */\n\tpublic static final ChildPropertyDescriptor NAME_PROPERTY =\n\t\tinternalNamePropertyFactory(TypeDeclaration.class);\n\n\n\t/**\n\t * The \"superclass\" structural property of this node type (JLS2 API only).\n\t * \n\t */\n\tpublic static final ChildPropertyDescriptor SUPERCLASS_PROPERTY =\n\t\tnew ChildPropertyDescriptor(TypeDeclaration.class, \"superclass\", Name.class, OPTIONAL, NO_CYCLE_RISK); //$NON-NLS-1$\n\n\t/**\n\t * The \"superclassType\" structural property of this node type (added in JLS3 API).\n\t * \n\t */\n\tpublic static final ChildPropertyDescriptor SUPERCLASS_TYPE_PROPERTY =\n\t\tnew ChildPropertyDescriptor(TypeDeclaration.class, \"superclassType\", Type.class, OPTIONAL, NO_CYCLE_RISK); //$NON-NLS-1$\n\n\t/**\n\t * The \"bodyDeclarations\" structural property of this node type (added in JLS3 API).\n\t * \n\t */\n\tpublic static final ChildListPropertyDescriptor BODY_DECLARATIONS_PROPERTY =\n\t\tinternalBodyDeclarationPropertyFactory(TypeDeclaration.class);\n\n\t/**\n\t * A list of property descriptors (element type:\n\t * {@link StructuralPropertyDescriptor}),\n\t * or null if uninitialized.\n\t * \n\t */\n\tprivate static final List PROPERTY_DESCRIPTORS_2_0;\n\n\t/**\n\t * A list of property descriptors (element type:\n\t * {@link StructuralPropertyDescriptor}),\n\t * or null if uninitialized.\n\t * \n\t */\n\tprivate static final List PROPERTY_DESCRIPTORS_3_0;\n\n\tstatic {\n\t\tList propertyList = new ArrayList(8);\n\t\tcreatePropertyList(TypeDeclaration.class, propertyList);\n\t\taddProperty(JAVADOC_PROPERTY, propertyList);\n\t\taddProperty(MODIFIERS_PROPERTY, propertyList);\n\t\taddProperty(NAME_PROPERTY, propertyList);\n\t\taddProperty(SUPERCLASS_PROPERTY, propertyList);\n\t\taddProperty(BODY_DECLARATIONS_PROPERTY, propertyList);\n\t\tPROPERTY_DESCRIPTORS_2_0 = reapPropertyList(propertyList);\n\n\t\tpropertyList = new ArrayList(9);\n\t\tcreatePropertyList(TypeDeclaration.class, propertyList);\n\t\taddProperty(JAVADOC_PROPERTY, propertyList);\n\t\taddProperty(MODIFIERS2_PROPERTY, propertyList);\n\t\taddProperty(NAME_PROPERTY, propertyList);\n\t\taddProperty(SUPERCLASS_TYPE_PROPERTY, propertyList);\n\t\taddProperty(BODY_DECLARATIONS_PROPERTY, propertyList);\n\t\tPROPERTY_DESCRIPTORS_3_0 = reapPropertyList(propertyList);\n\t}\n\n\t/**\n\t * Returns a list of structural property descriptors for this node type.\n\t * Clients must not modify the result.\n\t *\n\t * @param apiLevel the API level; one of the\n\t * AST.JLS* constants\n\n\t * @return a list of property descriptors (element type:\n\t * {@link StructuralPropertyDescriptor})\n\t * \n\t */\n\tpublic static List propertyDescriptors(int apiLevel) {\n\t\tif (apiLevel == AST.JLS2_INTERNAL) {\n\t\t\treturn PROPERTY_DESCRIPTORS_2_0;\n\t\t} else {\n\t\t\treturn PROPERTY_DESCRIPTORS_3_0;\n\t\t}\n\t}\n\n\t/**\n\t * The optional superclass name; null if none.\n\t * Defaults to none. Note that this field is not used for\n\t * interface declarations. Not used in 3.0.\n\t */\n\tprivate Name optionalSuperclassName = null;\n\n\t/**\n\t * The optional superclass type; null if none.\n\t * Defaults to none. Note that this field is not used for\n\t * interface declarations. Null in JLS2. Added in JLS3.\n\t * \n\t */\n\tprivate Type optionalSuperclassType = null;\n\n\t/**\n\t * Creates a new AST node for a type declaration owned by the given\n\t * AST. By default, the type declaration is for a class of an\n\t * unspecified, but legal, name; no modifiers; no javadoc;\n\t * no type parameters; no superclass or superinterfaces; and an empty list\n\t * of body declarations.\n\t *

    \n\t * N.B. This constructor is package-private; all subclasses must be\n\t * declared in the same package; clients are unable to declare\n\t * additional subclasses.\n\t *

    \n\t *\n\t * @param ast the AST that is to own this node\n\t */\n\tTypeDeclaration(AST ast) {\n\t\tsuper(ast);\n\t}\n\n\t/* (omit javadoc for this method)\n\t * Method declared on ASTNode.\n\t * \n\t */\n\tfinal List internalStructuralPropertiesForType(int apiLevel) {\n\t\treturn propertyDescriptors(apiLevel);\n\t}\n\n\t/* (omit javadoc for this method)\n\t * Method declared on ASTNode.\n\t */\n\tfinal int internalGetSetIntProperty(SimplePropertyDescriptor property, boolean get, int value) {\n\t\tif (property == MODIFIERS_PROPERTY) {\n\t\t\tif (get) {\n\t\t\t\treturn getModifiers();\n\t\t\t} else {\n\t\t\t\tinternalSetModifiers(value);\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t}\n\t\t// allow default implementation to flag the error\n\t\treturn super.internalGetSetIntProperty(property, get, value);\n\t}\n\n\t/* (omit javadoc for this method)\n\t * Method declared on ASTNode.\n\t */\n\tfinal boolean internalGetSetBooleanProperty(SimplePropertyDescriptor property, boolean get, boolean value) {\n\t\t// allow default implementation to flag the error\n\t\treturn super.internalGetSetBooleanProperty(property, get, value);\n\t}\n\n\t/* (omit javadoc for this method)\n\t * Method declared on ASTNode.\n\t */\n\tfinal ASTNode internalGetSetChildProperty(ChildPropertyDescriptor property, boolean get, ASTNode child) {\n\t\tif (property == JAVADOC_PROPERTY) {\n\t\t\tif (get) {\n\t\t\t\treturn getJavadoc();\n\t\t\t} else {\n\t\t\t\tsetJavadoc((JSdoc) child);\n\t\t\t\treturn null;\n\t\t\t}\n\t\t}\n\t\tif (property == NAME_PROPERTY) {\n\t\t\tif (get) {\n\t\t\t\treturn getName();", "answers": ["\t\t\t} else {"], "length": 1105, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "685f7fec-938f-4855-ae98-d863d715748e", "reasoning": "The method internalGetSetChildProperty handles child properties via a series of if blocks. For the NAME_PROPERTY case, after returning the name when get is true, the next logical line follows the same pattern as earlier blocks: close the get branch and open the else branch to handle setting the name. Hence the next line is the closing brace of the get block followed by the else clause.", "reasoning_model_answer": "} else {", "assistant_with_reasoning": "\nThe method internalGetSetChildProperty handles child properties via a series of if blocks. For the NAME_PROPERTY case, after returning the name when get is true, the next logical line follows the same pattern as earlier blocks: close the get branch and open the else branch to handle setting the name. Hence the next line is the closing brace of the get block followed by the else clause.\n\n} else {", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 6.96, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 9028, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "} else {", "score": 0.84, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/**\n* Licensed to the Apache Software Foundation (ASF) under one\n* or more contributor license agreements. See the NOTICE file\n* distributed with this work for additional information\n* regarding copyright ownership. The ASF licenses this file\n* to you under the Apache License, Version 2.0 (the\n* \"License\"); you may not use this file except in compliance\n* with the License. You may obtain a copy of the License at\n*\n* http://www.apache.org/licenses/LICENSE-2.0\n*\n* Unless required by applicable law or agreed to in writing, software\n* distributed under the License is distributed on an \"AS IS\" BASIS,\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* See the License for the specific language governing permissions and\n* limitations under the License.\n*/\npackage org.apache.hadoop.yarn.server.resourcemanager.scheduler.fair;\n\nimport java.io.File;\nimport java.io.IOException;\nimport java.net.URL;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\nimport javax.xml.parsers.DocumentBuilder;\nimport javax.xml.parsers.DocumentBuilderFactory;\nimport javax.xml.parsers.ParserConfigurationException;\n\nimport org.apache.commons.logging.Log;\nimport org.apache.commons.logging.LogFactory;\nimport org.apache.hadoop.classification.InterfaceAudience.Public;\nimport org.apache.hadoop.classification.InterfaceStability.Unstable;\nimport org.apache.hadoop.conf.Configuration;\nimport org.apache.hadoop.security.authorize.AccessControlList;\nimport org.apache.hadoop.service.AbstractService;\nimport org.apache.hadoop.yarn.api.records.QueueACL;\nimport org.apache.hadoop.yarn.api.records.Resource;\nimport org.apache.hadoop.yarn.server.resourcemanager.resource.ResourceWeights;\nimport org.apache.hadoop.yarn.util.Clock;\nimport org.apache.hadoop.yarn.util.SystemClock;\nimport org.apache.hadoop.yarn.util.resource.Resources;\nimport org.w3c.dom.Document;\nimport org.w3c.dom.Element;\nimport org.w3c.dom.Node;\nimport org.w3c.dom.NodeList;\nimport org.w3c.dom.Text;\nimport org.xml.sax.SAXException;\n\nimport com.google.common.annotations.VisibleForTesting;\n\n@Public\n@Unstable\npublic class AllocationFileLoaderService extends AbstractService {\n \n public static final Log LOG = LogFactory.getLog(\n AllocationFileLoaderService.class.getName());\n \n /** Time to wait between checks of the allocation file */\n public static final long ALLOC_RELOAD_INTERVAL_MS = 10 * 1000;\n\n /**\n * Time to wait after the allocation has been modified before reloading it\n * (this is done to prevent loading a file that hasn't been fully written).\n */\n public static final long ALLOC_RELOAD_WAIT_MS = 5 * 1000;\n\n public static final long THREAD_JOIN_TIMEOUT_MS = 1000;\n\n private final Clock clock;\n\n private long lastSuccessfulReload; // Last time we successfully reloaded queues\n private boolean lastReloadAttemptFailed = false;\n \n // Path to XML file containing allocations. \n private File allocFile;\n \n private Listener reloadListener;\n \n @VisibleForTesting\n long reloadIntervalMs = ALLOC_RELOAD_INTERVAL_MS;\n \n private Thread reloadThread;\n private volatile boolean running = true;\n \n public AllocationFileLoaderService() {\n this(new SystemClock());\n }\n \n public AllocationFileLoaderService(Clock clock) {\n super(AllocationFileLoaderService.class.getName());\n this.clock = clock;\n \n }\n \n @Override\n public void serviceInit(Configuration conf) throws Exception {\n this.allocFile = getAllocationFile(conf);\n if (allocFile != null) {\n reloadThread = new Thread() {\n @Override\n public void run() {\n while (running) {\n long time = clock.getTime();\n long lastModified = allocFile.lastModified();\n if (lastModified > lastSuccessfulReload &&\n time > lastModified + ALLOC_RELOAD_WAIT_MS) {\n try {\n reloadAllocations();\n } catch (Exception ex) {\n if (!lastReloadAttemptFailed) {\n LOG.error(\"Failed to reload fair scheduler config file - \" +\n \"will use existing allocations.\", ex);\n }\n lastReloadAttemptFailed = true;\n }\n } else if (lastModified == 0l) {\n if (!lastReloadAttemptFailed) {\n LOG.warn(\"Failed to reload fair scheduler config file because\" +\n \" last modified returned 0. File exists: \"\n + allocFile.exists());\n }\n lastReloadAttemptFailed = true;\n }\n try {\n Thread.sleep(reloadIntervalMs);\n } catch (InterruptedException ex) {\n LOG.info(\n \"Interrupted while waiting to reload alloc configuration\");\n }\n }\n }\n };\n reloadThread.setName(\"AllocationFileReloader\");\n reloadThread.setDaemon(true);\n }\n super.serviceInit(conf);\n }\n \n @Override\n public void serviceStart() throws Exception {\n if (reloadThread != null) {\n reloadThread.start();\n }\n super.serviceStart();\n }\n \n @Override\n public void serviceStop() throws Exception {\n running = false;\n if (reloadThread != null) {\n reloadThread.interrupt();\n try {\n reloadThread.join(THREAD_JOIN_TIMEOUT_MS);\n } catch (InterruptedException e) {\n LOG.warn(\"reloadThread fails to join.\");\n }\n }\n super.serviceStop();\n }\n \n /**\n * Path to XML file containing allocations. If the\n * path is relative, it is searched for in the\n * classpath, but loaded like a regular File.\n */\n public File getAllocationFile(Configuration conf) {\n String allocFilePath = conf.get(FairSchedulerConfiguration.ALLOCATION_FILE,\n FairSchedulerConfiguration.DEFAULT_ALLOCATION_FILE);\n File allocFile = new File(allocFilePath);\n if (!allocFile.isAbsolute()) {\n URL url = Thread.currentThread().getContextClassLoader()\n .getResource(allocFilePath);\n if (url == null) {\n LOG.warn(allocFilePath + \" not found on the classpath.\");\n allocFile = null;\n } else if (!url.getProtocol().equalsIgnoreCase(\"file\")) {\n throw new RuntimeException(\"Allocation file \" + url\n + \" found on the classpath is not on the local filesystem.\");\n } else {\n allocFile = new File(url.getPath());\n }\n }\n return allocFile;\n }\n \n public synchronized void setReloadListener(Listener reloadListener) {\n this.reloadListener = reloadListener;\n }\n \n /**\n * Updates the allocation list from the allocation config file. This file is\n * expected to be in the XML format specified in the design doc.\n *\n * @throws IOException if the config file cannot be read.\n * @throws AllocationConfigurationException if allocations are invalid.\n * @throws ParserConfigurationException if XML parser is misconfigured.\n * @throws SAXException if config file is malformed.\n */\n public synchronized void reloadAllocations() throws IOException,\n ParserConfigurationException, SAXException, AllocationConfigurationException {\n if (allocFile == null) {\n return;\n }\n LOG.info(\"Loading allocation file \" + allocFile);\n // Create some temporary hashmaps to hold the new allocs, and we only save\n // them in our fields if we have parsed the entire allocs file successfully.\n Map minQueueResources = new HashMap();\n Map maxQueueResources = new HashMap();\n Map queueMaxApps = new HashMap();\n Map userMaxApps = new HashMap();\n Map queueMaxAMShares = new HashMap();\n Map queueWeights = new HashMap();\n Map queuePolicies = new HashMap();\n Map minSharePreemptionTimeouts = new HashMap();\n Map fairSharePreemptionTimeouts = new HashMap();\n Map fairSharePreemptionThresholds =\n new HashMap();\n Map> queueAcls =\n new HashMap>();\n int userMaxAppsDefault = Integer.MAX_VALUE;\n int queueMaxAppsDefault = Integer.MAX_VALUE;\n float queueMaxAMShareDefault = 0.5f;\n long defaultFairSharePreemptionTimeout = Long.MAX_VALUE;\n long defaultMinSharePreemptionTimeout = Long.MAX_VALUE;\n float defaultFairSharePreemptionThreshold = 0.5f;\n SchedulingPolicy defaultSchedPolicy = SchedulingPolicy.DEFAULT_POLICY;\n\n QueuePlacementPolicy newPlacementPolicy = null;\n\n // Remember all queue names so we can display them on web UI, etc.\n // configuredQueues is segregated based on whether it is a leaf queue\n // or a parent queue. This information is used for creating queues\n // and also for making queue placement decisions(QueuePlacementRule.java).\n Map> configuredQueues =\n new HashMap>();\n for (FSQueueType queueType : FSQueueType.values()) {\n configuredQueues.put(queueType, new HashSet());\n }\n\n // Read and parse the allocations file.\n DocumentBuilderFactory docBuilderFactory =\n DocumentBuilderFactory.newInstance();\n docBuilderFactory.setIgnoringComments(true);\n DocumentBuilder builder = docBuilderFactory.newDocumentBuilder();\n Document doc = builder.parse(allocFile);\n Element root = doc.getDocumentElement();\n if (!\"allocations\".equals(root.getTagName()))\n throw new AllocationConfigurationException(\"Bad fair scheduler config \" +\n \"file: top-level element not \");\n NodeList elements = root.getChildNodes();\n List queueElements = new ArrayList();\n Element placementPolicyElement = null;\n for (int i = 0; i < elements.getLength(); i++) {\n Node node = elements.item(i);\n if (node instanceof Element) {\n Element element = (Element)node;\n if (\"queue\".equals(element.getTagName()) ||\n \"pool\".equals(element.getTagName())) {\n queueElements.add(element);\n } else if (\"user\".equals(element.getTagName())) {\n String userName = element.getAttribute(\"name\");\n NodeList fields = element.getChildNodes();\n for (int j = 0; j < fields.getLength(); j++) {\n Node fieldNode = fields.item(j);\n if (!(fieldNode instanceof Element))\n continue;\n Element field = (Element) fieldNode;\n if (\"maxRunningApps\".equals(field.getTagName())) {\n String text = ((Text)field.getFirstChild()).getData().trim();\n int val = Integer.parseInt(text);\n userMaxApps.put(userName, val);\n }\n }\n } else if (\"userMaxAppsDefault\".equals(element.getTagName())) {\n String text = ((Text)element.getFirstChild()).getData().trim();\n int val = Integer.parseInt(text);\n userMaxAppsDefault = val;\n } else if (\"defaultFairSharePreemptionTimeout\"\n .equals(element.getTagName())) {\n String text = ((Text)element.getFirstChild()).getData().trim();\n long val = Long.parseLong(text) * 1000L;\n defaultFairSharePreemptionTimeout = val;\n } else if (\"fairSharePreemptionTimeout\".equals(element.getTagName())) {\n if (defaultFairSharePreemptionTimeout == Long.MAX_VALUE) {\n String text = ((Text)element.getFirstChild()).getData().trim();\n long val = Long.parseLong(text) * 1000L;\n defaultFairSharePreemptionTimeout = val;\n }\n } else if (\"defaultMinSharePreemptionTimeout\"\n .equals(element.getTagName())) {\n String text = ((Text)element.getFirstChild()).getData().trim();\n long val = Long.parseLong(text) * 1000L;\n defaultMinSharePreemptionTimeout = val;\n } else if (\"defaultFairSharePreemptionThreshold\"\n .equals(element.getTagName())) {\n String text = ((Text)element.getFirstChild()).getData().trim();\n float val = Float.parseFloat(text);\n val = Math.max(Math.min(val, 1.0f), 0.0f);\n defaultFairSharePreemptionThreshold = val;\n } else if (\"queueMaxAppsDefault\".equals(element.getTagName())) {\n String text = ((Text)element.getFirstChild()).getData().trim();", "answers": [" int val = Integer.parseInt(text);"], "length": 1171, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "671ef324-728f-46b5-a651-1464d03c3ede", "reasoning": "The code is parsing XML elements within reloadAllocations. For the tag \"queueMaxAppsDefault\" it extracts the text content, trims it, and should convert it to an int and assign it to the variable queueMaxAppsDefault, mirroring the pattern used for userMaxAppsDefault. Hence the next line parses the integer.", "reasoning_model_answer": "int val = Integer.parseInt(text);\nqueueMaxAppsDefault = val;", "assistant_with_reasoning": "\nThe code is parsing XML elements within reloadAllocations. For the tag \"queueMaxAppsDefault\" it extracts the text content, trims it, and should convert it to an int and assign it to the variable queueMaxAppsDefault, mirroring the pattern used for userMaxAppsDefault. Hence the next line parses the integer.\n\nint val = Integer.parseInt(text);\nqueueMaxAppsDefault = val;", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 2.799, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 12653, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "int val = Integer.parseInt(text);\nqueueMaxAppsDefault = val;", "score": 0.87, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "using System;\nusing System.IO;\nusing System.Security.Cryptography;\nusing System.Text;\nusing System.Text.RegularExpressions;\nusing System.Globalization;\n\nnamespace PubNubMessaging.Core\n{\n\t#region \"Crypto\"\n\n\t/// \n\t/// MD5 Service provider\n\t/// \n\tinternal class MD5CryptoServiceProvider : MD5\n\t{\n\t\tpublic MD5CryptoServiceProvider()\n\t\t\t: base()\n\t\t{\n\t\t}\n\t}\n\n\t/// \n\t/// MD5 messaging-digest algorithm is a widely used cryptographic hash function that produces 128-bit hash value.\n\t/// \n\tinternal class MD5 : IDisposable\n\t{\n\t\tstatic public MD5 Create(string hashName)\n\t\t{\n\t\t\tif (hashName == \"MD5\")\n\t\t\t\treturn new MD5();\n\t\t\telse\n\t\t\t\tthrow new NotSupportedException();\n\t\t}\n\n\t\tstatic public String GetMd5String(String source)\n\t\t{\n\t\t\tMD5 md = MD5CryptoServiceProvider.Create();\n\t\t\tbyte[] hash;\n\n\t\t\t//Create a new instance of ASCIIEncoding to \n\t\t\t//convert the string into an array of Unicode bytes.\n\t\t\tUTF8Encoding enc = new UTF8Encoding();\n\n\t\t\t//Convert the string into an array of bytes.\n\t\t\tbyte[] buffer = enc.GetBytes(source);\n\n\t\t\t//Create the hash value from the array of bytes.\n\t\t\thash = md.ComputeHash(buffer);\n\n\t\t\tStringBuilder sb = new StringBuilder();\n\t\t\tforeach (byte b in hash)\n\t\t\t\tsb.Append(b.ToString(\"x2\"));\n\t\t\treturn sb.ToString();\n\t\t}\n\n\t\tstatic public MD5 Create()\n\t\t{\n\t\t\treturn new MD5();\n\t\t}\n\n\t\t#region base implementation of the MD5\n\t\t#region constants\n\t\tprivate const byte S11 = 7;\n\t\tprivate const byte S12 = 12;\n\t\tprivate const byte S13 = 17;\n\t\tprivate const byte S14 = 22;\n\t\tprivate const byte S21 = 5;\n\t\tprivate const byte S22 = 9;\n\t\tprivate const byte S23 = 14;\n\t\tprivate const byte S24 = 20;\n\t\tprivate const byte S31 = 4;\n\t\tprivate const byte S32 = 11;\n\t\tprivate const byte S33 = 16;\n\t\tprivate const byte S34 = 23;\n\t\tprivate const byte S41 = 6;\n\t\tprivate const byte S42 = 10;\n\t\tprivate const byte S43 = 15;\n\t\tprivate const byte S44 = 21;\n\t\tstatic private byte[] PADDING = new byte[] {\n\t\t\t0x80, 0, 0, 0, 0, 0, \n\t\t\t0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n\t\t\t0, 0, 0, 0, 0, 0, 0, \n\t\t\t0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n\t\t\t0, 0, 0, 0, 0, 0, 0, \n\t\t\t0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0\n\t\t};\n\t\t#endregion\n\n\t\t#region F, G, H and I are basic MD5 functions.\n\t\tstatic private uint F(uint x, uint y, uint z)\n\t\t{\n\t\t\treturn (((x) & (y)) | ((~x) & (z)));\n\t\t}\n\t\tstatic private uint G(uint x, uint y, uint z)\n\t\t{\n\t\t\treturn (((x) & (z)) | ((y) & (~z)));\n\t\t}\n\t\tstatic private uint H(uint x, uint y, uint z)\n\t\t{\n\t\t\treturn ((x) ^ (y) ^ (z));\n\t\t}\n\t\tstatic private uint I(uint x, uint y, uint z)\n\t\t{\n\t\t\treturn ((y) ^ ((x) | (~z)));\n\t\t}\n\t\t#endregion\n\n\t\t#region rotates x left n bits.\n\t\t/// \n\t\t/// rotates x left n bits.\n\t\t/// \n\t\t/// \n\t\t/// \n\t\t/// \n\t\tstatic private uint ROTATE_LEFT(uint x, byte n)\n\t\t{\n\t\t\treturn (((x) << (n)) | ((x) >> (32 - (n))));\n\t\t}\n\t\t#endregion\n\n\t\t#region FF, GG, HH, and II transformations\n\t\t/// FF, GG, HH, and II transformations \n\t\t/// for rounds 1, 2, 3, and 4.\n\t\t/// Rotation is separate from addition to prevent re-computation.\n\t\tstatic private void FF(ref uint a, uint b, uint c, uint d, uint x, byte s, uint ac)\n\t\t{\n\t\t\t(a) += F((b), (c), (d)) + (x) + (uint)(ac);\n\t\t\t(a) = ROTATE_LEFT((a), (s));\n\t\t\t(a) += (b);\n\t\t}\n\t\tstatic private void GG(ref uint a, uint b, uint c, uint d, uint x, byte s, uint ac)\n\t\t{\n\t\t\t(a) += G((b), (c), (d)) + (x) + (uint)(ac);\n\t\t\t(a) = ROTATE_LEFT((a), (s));\n\t\t\t(a) += (b);\n\t\t}\n\t\tstatic private void HH(ref uint a, uint b, uint c, uint d, uint x, byte s, uint ac)\n\t\t{\n\t\t\t(a) += H((b), (c), (d)) + (x) + (uint)(ac);\n\t\t\t(a) = ROTATE_LEFT((a), (s));\n\t\t\t(a) += (b);\n\t\t}\n\t\tstatic private void II(ref uint a, uint b, uint c, uint d, uint x, byte s, uint ac)\n\t\t{\n\t\t\t(a) += I((b), (c), (d)) + (x) + (uint)(ac);\n\t\t\t(a) = ROTATE_LEFT((a), (s));\n\t\t\t(a) += (b);\n\t\t}\n\t\t#endregion\n\n\t\t#region context info\n\t\t/// \n\t\t/// state (ABCD)\n\t\t/// \n\t\tuint[] state = new uint[4];\n\n\t\t/// \n\t\t/// number of bits, modulo 2^64 (LSB first)\n\t\t/// \n\t\tuint[] count = new uint[2];\n\n\t\t/// \n\t\t/// input buffer\n\t\t/// \n\t\tbyte[] buffer = new byte[64];\n\t\t#endregion\n\n\t\tinternal MD5()\n\t\t{\n\t\t\tInitialize();\n\t\t}\n\n\t\t/// \n\t\t/// MD5 initialization. Begins an MD5 operation, writing a new context.\n\t\t/// \n\t\t/// \n\t\t/// The RFC named it \"MD5Init\"\n\t\t/// \n\t\tpublic virtual void Initialize()\n\t\t{\n\t\t\tcount[0] = count[1] = 0;\n\n\t\t\t// Load magic initialization constants.\n\t\t\tstate[0] = 0x67452301;\n\t\t\tstate[1] = 0xefcdab89;\n\t\t\tstate[2] = 0x98badcfe;\n\t\t\tstate[3] = 0x10325476;\n\t\t}\n\n\t\t/// \n\t\t/// MD5 block update operation. Continues an MD5 message-digest\n\t\t/// operation, processing another message block, and updating the\n\t\t/// context.\n\t\t/// \n\t\t/// \n\t\t/// \n\t\t/// \n\t\t/// The RFC Named it MD5Update\n\t\tprotected virtual void HashCore(byte[] input, int offset, int count)\n\t\t{\n\t\t\tint i;\n\t\t\tint index;\n\t\t\tint partLen;\n\n\t\t\t// Compute number of bytes mod 64\n\t\t\tindex = (int)((this.count[0] >> 3) & 0x3F);\n\n\t\t\t// Update number of bits\n\t\t\tif ((this.count[0] += (uint)((uint)count << 3)) < ((uint)count << 3))\n\t\t\t\tthis.count[1]++;\n\t\t\tthis.count[1] += ((uint)count >> 29);\n\n\t\t\tpartLen = 64 - index;\n\n\t\t\t// Transform as many times as possible.\n\t\t\tif (count >= partLen)\n\t\t\t{\n\t\t\t\tSystem.Buffer.BlockCopy(input, offset, this.buffer, index, partLen);\n\t\t\t\tTransform(this.buffer, 0);\n\n\t\t\t\tfor (i = partLen; i + 63 < count; i += 64)\n\t\t\t\t\tTransform(input, offset + i);\n\n\t\t\t\tindex = 0;\n\t\t\t}\n\t\t\telse\n\t\t\t\ti = 0;\n\n\t\t\t// Buffer remaining input \n\t\t\tSystem.Buffer.BlockCopy(input, offset + i, this.buffer, index, count - i);\n\t\t}\n\n\t\t/// \n\t\t/// MD5 finalization. Ends an MD5 message-digest operation, writing the\n\t\t/// the message digest and zeroizing the context.\n\t\t/// \n\t\t/// message digest\n\t\t/// The RFC named it MD5Final\n\t\tprotected virtual byte[] HashFinal()\n\t\t{\n\t\t\tbyte[] digest = new byte[16];\n\t\t\tbyte[] bits = new byte[8];\n\t\t\tint index, padLen;\n\n\t\t\t// Save number of bits\n\t\t\tEncode(bits, 0, this.count, 0, 8);\n\n\t\t\t// Pad out to 56 mod 64.\n\t\t\tindex = (int)((uint)(this.count[0] >> 3) & 0x3f);\n\t\t\tpadLen = (index < 56) ? (56 - index) : (120 - index);\n\t\t\tHashCore(PADDING, 0, padLen);\n\n\t\t\t// Append length (before padding)\n\t\t\tHashCore(bits, 0, 8);\n\n\t\t\t// Store state in digest \n\t\t\tEncode(digest, 0, state, 0, 16);\n\n\t\t\t// Zeroize sensitive information.\n\t\t\tcount[0] = count[1] = 0;\n\t\t\tstate[0] = 0;\n\t\t\tstate[1] = 0;\n\t\t\tstate[2] = 0;\n\t\t\tstate[3] = 0;\n\n\t\t\t// initialize again, to be ready to use\n\t\t\tInitialize();\n\n\t\t\treturn digest;\n\t\t}\n\n\t\t/// \n\t\t/// MD5 basic transformation. Transforms state based on 64 bytes block.\n\t\t/// \n\t\t/// \n\t\t/// \n\t\tprivate void Transform(byte[] block, int offset)\n\t\t{\n\t\t\tuint a = state[0], b = state[1], c = state[2], d = state[3];\n\t\t\tuint[] x = new uint[16];\n\t\t\tDecode(x, 0, block, offset, 64);\n\n\t\t\t// Round 1\n\t\t\tFF(ref a, b, c, d, x[0], S11, 0xd76aa478); /* 1 */", "answers": ["\t\t\tFF(ref d, a, b, c, x[1], S12, 0xe8c7b756); /* 2 */"], "length": 1108, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "59bdf9d1-1a7b-4106-b981-773c7a7b56e4", "reasoning": "In the MD5 Transform method, after the first FF call (round 1 operation 1), the next operation follows the standard MD5 sequence. The second operation uses FF with the state variables rotated (d, a, b, c) and the next message word x[1], shift S12, and constant 0xe8c7b756. Therefore the next line is the second FF call.", "reasoning_model_answer": "FF(ref d, a, b, c, x[1], S12, 0xe8c7b756);", "assistant_with_reasoning": "\nIn the MD5 Transform method, after the first FF call (round 1 operation 1), the next operation follows the standard MD5 sequence. The second operation uses FF with the state variables rotated (d, a, b, c) and the next message word x[1], shift S12, and constant 0xe8c7b756. Therefore the next line is the second FF call.\n\nFF(ref d, a, b, c, x[1], S12, 0xe8c7b756);", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 5.318, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 7237, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "FF(ref d, a, b, c, x[1], S12, 0xe8c7b756);", "score": 0.88, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.\npackage com.yahoo.document;\n\nimport com.yahoo.document.datatypes.FieldValue;\nimport com.yahoo.document.fieldpathupdate.FieldPathUpdate;\nimport com.yahoo.document.serialization.DocumentSerializerFactory;\nimport com.yahoo.document.serialization.DocumentUpdateReader;\nimport com.yahoo.document.serialization.DocumentUpdateWriter;\nimport com.yahoo.document.update.AssignValueUpdate;\nimport com.yahoo.document.update.ClearValueUpdate;\nimport com.yahoo.document.update.FieldUpdate;\nimport com.yahoo.document.update.ValueUpdate;\nimport com.yahoo.io.GrowableByteBuffer;\n\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Objects;\nimport java.util.Optional;\n\n/**\n *

    Specifies one or more field updates to a document.

    A document update contains a list of {@link\n * com.yahoo.document.update.FieldUpdate field updates} for fields to be updated by this update. Each field update is\n * applied atomically, but the entire document update is not. A document update can only contain one field update per\n * field. To make multiple updates to the same field in the same document update, add multiple {@link\n * com.yahoo.document.update.ValueUpdate value updates} to the same field update.

    To update a document and\n * set a string field to a new value:

    \n *
    \n * DocumentType musicType = DocumentTypeManager.getInstance().getDocumentType(\"music\", 0);\n * DocumentUpdate docUpdate = new DocumentUpdate(musicType,\n *         new DocumentId(\"id:test:music::http://music.yahoo.com/\"));\n * FieldUpdate update = FieldUpdate.createAssign(musicType.getField(\"artist\"), \"lillbabs\");\n * docUpdate.addFieldUpdate(update);\n * 
    \n *\n * @author Einar M R Rosenvinge\n * @see com.yahoo.document.update.FieldUpdate\n * @see com.yahoo.document.update.ValueUpdate\n */\n\npublic class DocumentUpdate extends DocumentOperation implements Iterable {\n\n //see src/vespa/document/util/identifiableid.h\n public static final int CLASSID = 0x1000 + 6;\n\n private DocumentId docId;\n private final Map id2FieldUpdates;\n private final List fieldPathUpdates;\n private DocumentType documentType;\n private Boolean createIfNonExistent;\n\n /**\n * Creates a DocumentUpdate.\n *\n * @param docId the ID of the update\n * @param docType the document type that this update is valid for\n */\n public DocumentUpdate(DocumentType docType, DocumentId docId) {\n this.docId = docId;\n this.documentType = docType;\n this.id2FieldUpdates = new HashMap<>();\n this.fieldPathUpdates = new ArrayList<>();\n }\n\n /**\n * Creates a new document update using a reader\n */\n public DocumentUpdate(DocumentUpdateReader reader) {\n docId = null;\n documentType = null;\n id2FieldUpdates = new HashMap<>();\n fieldPathUpdates = new ArrayList<>();\n reader.read(this);\n }\n\n /** Creates a new document update which is a copy of the argument. */\n public DocumentUpdate(DocumentUpdate update) {\n super(update);\n docId = update.docId;\n documentType = update.documentType;\n id2FieldUpdates = new HashMap<>(update.id2FieldUpdates);\n fieldPathUpdates = new ArrayList<>(update.fieldPathUpdates);\n createIfNonExistent = update.createIfNonExistent;\n }\n\n /**\n * Creates a DocumentUpdate.\n *\n * @param docId the ID of the update\n * @param docType the document type that this update is valid for\n */\n public DocumentUpdate(DocumentType docType, String docId) {\n this(docType, new DocumentId(docId));\n }\n\n public DocumentId getId() {\n return docId;\n }\n\n /**\n * Sets the document id of the document to update.\n * Use only while deserializing - changing the document id after creation has undefined behaviour.\n */\n public void setId(DocumentId id) {\n docId = id;\n }\n\n private void verifyType(Document doc) {\n if (!documentType.equals(doc.getDataType())) {\n throw new IllegalArgumentException(\n \"Document \" + doc.getId() + \" with type \" + doc.getDataType() + \" must have same type as update, which is type \" + documentType);\n }\n }\n /**\n * Applies this document update.\n *\n * @param doc the document to apply the update to\n * @return a reference to itself\n * @throws IllegalArgumentException if the document does not have the same document type as this update\n */\n public DocumentUpdate applyTo(Document doc) {\n verifyType(doc);\n\n for (FieldUpdate fieldUpdate : id2FieldUpdates.values()) {\n fieldUpdate.applyTo(doc);\n }\n for (FieldPathUpdate fieldPathUpdate : fieldPathUpdates) {\n fieldPathUpdate.applyTo(doc);\n }\n return this;\n }\n\n /**\n * Prune away any field update that will not modify any field in the document.\n * @param doc document to check against\n * @return a reference to itself\n * @throws IllegalArgumentException if the document does not have the same document type as this update\n */\n public DocumentUpdate prune(Document doc) {\n verifyType(doc);\n\n for (Iterator> iter = id2FieldUpdates.entrySet().iterator(); iter.hasNext();) {\n Map.Entry entry = iter.next();\n FieldUpdate update = entry.getValue();\n if (!update.isEmpty()) {\n ValueUpdate last = update.getValueUpdate(update.size() - 1);\n if (last instanceof AssignValueUpdate) {\n FieldValue currentValue = doc.getFieldValue(update.getField());\n if ((currentValue != null) && currentValue.equals(last.getValue())) {\n iter.remove();\n }\n } else if (last instanceof ClearValueUpdate) {\n FieldValue currentValue = doc.getFieldValue(update.getField());\n if (currentValue == null) {\n iter.remove();\n } else {\n FieldValue copy = currentValue.clone();\n copy.clear();\n if (currentValue.equals(copy)) {\n iter.remove();\n }\n }\n }\n }\n }\n return this;\n }\n\n /**\n * Get an unmodifiable collection of all field updates that this document update specifies.\n *\n * @return a collection of all FieldUpdates in this DocumentUpdate\n */\n public Collection fieldUpdates() {\n return Collections.unmodifiableCollection(id2FieldUpdates.values());\n }\n\n /**\n * Get an unmodifiable collection of all field path updates that this document update specifies.\n *\n * @return a collection of all FieldPathUpdates in this DocumentUpdate\n */\n public Collection fieldPathUpdates() {\n return Collections.unmodifiableCollection(fieldPathUpdates);\n }\n\n /** Returns the type of the document this updates\n *\n * @return The documentype of the document\n */\n public DocumentType getDocumentType() {\n return documentType;\n }\n\n /**\n * Sets the document type. Use only while deserializing - changing the document type after creation\n * has undefined behaviour.\n */\n public void setDocumentType(DocumentType type) {\n documentType = type;\n }\n\n /**\n * Returns the update for a field\n *\n * @param field the field to return the update of\n * @return the update for the field, or null if that field has no update in this\n */\n public FieldUpdate getFieldUpdate(Field field) {\n return getFieldUpdateById(field.getId());\n }\n\n /** Removes all field updates from the list for field updates. */\n public void clearFieldUpdates() {\n id2FieldUpdates.clear();\n }\n\n /**\n * Returns the update for a field name\n *\n * @param fieldName the field name to return the update of\n * @return the update for the field, or null if that field has no update in this\n */\n public FieldUpdate getFieldUpdate(String fieldName) {\n Field field = documentType.getField(fieldName);\n return field != null ? getFieldUpdate(field) : null;\n }\n private FieldUpdate getFieldUpdateById(Integer fieldId) {\n return id2FieldUpdates.get(fieldId);\n }\n\n /**\n * Assigns the field updates of this document update.\n * Also note that no assumptions can be made on the order of item after this call.\n * They might have been joined if for the same field or reordered.\n *\n * @param fieldUpdates the new list of updates of this\n * @throws NullPointerException if the argument passed is null\n */\n public void setFieldUpdates(Collection fieldUpdates) {\n if (fieldUpdates == null) {\n throw new NullPointerException(\"The field updates of a document update can not be null\");\n }\n clearFieldUpdates();\n addFieldUpdates(fieldUpdates);\n }\n\n /** The same as setFieldUpdates(Collection<FieldUpdate>) */\n public void setFieldUpdates(List fieldUpdates) {", "answers": [" setFieldUpdates((Collection) fieldUpdates);"], "length": 1021, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "2020700f-036e-4360-a1d4-239999075664", "reasoning": "The class already defines setFieldUpdates for a Collection, which checks null, clears existing updates, and adds the new ones. The overload taking a List should simply delegate to that method, casting the List to a Collection. Therefore the next line inside the List overload is a call to the Collection version.", "reasoning_model_answer": "setFieldUpdates((Collection) fieldUpdates);", "assistant_with_reasoning": "\nThe class already defines setFieldUpdates for a Collection, which checks null, clears existing updates, and adds the new ones. The overload taking a List should simply delegate to that method, casting the List to a Collection. Therefore the next line inside the List overload is a call to the Collection version.\n\nsetFieldUpdates((Collection) fieldUpdates);", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.845, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 9605, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "setFieldUpdates((Collection) fieldUpdates);", "score": 0.93, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "using UnityEngine;\nusing UnityEditor;\nusing System.Collections.Generic;\nusing System.Collections;\nusing System.IO;\nusing System.Linq;\nusing System;\n\n[InitializeOnLoad]\npublic class StartupUGUISimpleTextureModifier {\n static StartupUGUISimpleTextureModifier() {\n if (EditorApplication.timeSinceStartup < 10) {\n Debug.Log(\"Initialized TextureModifier\");\n EditorUserBuildSettings.activeBuildTargetChanged += OnChangePlatform;\n }\n }\n\n [UnityEditor.MenuItem(\"Assets/Texture Util/ReImport All Compress Texture\", false, 1)]\n static void OnChangePlatform() {\n Debug.Log(\" TextureModifier Convert Compress Texture\");\n string labels = \"t:Texture\";\n foreach(var type in UGUISimpleTextureModifier.compressOutputs){\n labels+=\" l:\"+type.ToString();\n }\n \tvar assets = AssetDatabase.FindAssets (labels,null);\n foreach (var asset in assets) {\n var path=AssetDatabase.GUIDToAssetPath(asset);\n if (!String.IsNullOrEmpty(path))\n AssetDatabase.ImportAsset(path);\n }\n }\n}\n\npublic class UGUISimpleTextureModifier : AssetPostprocessor {\n\tpublic static readonly string KEY = \"SimpleTextureModifier Enable\";\n\n\tpublic enum TextureModifierType {\n\t\tNone,\n\t\tPremultipliedAlpha,\n\t\tAlphaBleed,\n\t\tFloydSteinberg,\n\t\tReduced16bits,\n C16bits,\n CCompressed,\n CCompressedNA,\n CCompressedWA,\n T32bits,\n\t\tT16bits,\n\t\tTCompressed,\n TCompressedNA,\n TCompressedWA,\n\t\tTPNG,\n\t\tTJPG,\n\t}\n\n\tstatic TextureFormat CompressionFormat {\n\t\tget {\n\t\t\tswitch (EditorUserBuildSettings.activeBuildTarget) {\n\t\t\tcase BuildTarget.Android:\n\t\t\t\treturn TextureFormat.ETC_RGB4;\n\t\t\tcase BuildTarget.iPhone:\n\t\t\t\treturn TextureFormat.PVRTC_RGB4;\n\t\t\tdefault:\n\t\t\t\treturn TextureFormat.DXT1;\n\t\t\t}\n\t\t}\n\t}\n\n\tstatic TextureFormat CompressionWithAlphaFormat {\n\t\tget {\n\t\t\tswitch (EditorUserBuildSettings.activeBuildTarget) {\n\t\t\tcase BuildTarget.Android:\n\t\t\t\treturn TextureFormat.ETC_RGB4;\n\t\t\tcase BuildTarget.iPhone:\n\t\t\t\treturn TextureFormat.PVRTC_RGBA4;\n\t\t\tdefault:\n\t\t\t\treturn TextureFormat.DXT5;\n\t\t\t}\n\t\t}\n\t}\n\n\tstruct Position2 {\n\t\tpublic int x,y;\n\t\tpublic Position2(int p1, int p2)\n\t\t{\n\t\t\tx = p1;\n\t\t\ty = p2;\n\t\t}\n\t}\n\t\n\treadonly static List> bleedTable;\n\tstatic UGUISimpleTextureModifier(){\n\t\tbleedTable=new List>();\n\t\tfor(int i=1;i<=12;i++){\n\t\t\tvar bT=new List();\n\t\t\tfor(int x=-i;x<=i;x++){\n\t\t\t\tbT.Add(new Position2(x,i));\n\t\t\t\tbT.Add(new Position2(-x,-i));\n\t\t\t}\n\t\t\tfor(int y=-i+1;y<=i-1;y++){\n\t\t\t\tbT.Add(new Position2(i,y));\n\t\t\t\tbT.Add(new Position2(-i,-y));\n\t\t\t}\n\t\t\tbleedTable.Add(bT);\n\t\t}\n\t}\n\n\tpublic readonly static List effecters=new List{TextureModifierType.PremultipliedAlpha,TextureModifierType.AlphaBleed};\n public readonly static List modifiers = new List { TextureModifierType.FloydSteinberg, TextureModifierType.Reduced16bits };\n public readonly static List outputs = new List{TextureModifierType.TJPG,TextureModifierType.TPNG,TextureModifierType.T32bits,TextureModifierType.T16bits,TextureModifierType.C16bits\n ,TextureModifierType.CCompressed,TextureModifierType.CCompressedNA,TextureModifierType.CCompressedWA\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t,TextureModifierType.TCompressed,TextureModifierType.TCompressedNA,TextureModifierType.TCompressedWA};\n public readonly static List compressOutputs = new List{\n TextureModifierType.CCompressed,TextureModifierType.CCompressedNA,TextureModifierType.CCompressedWA\n ,TextureModifierType.TCompressed,TextureModifierType.TCompressedNA,TextureModifierType.TCompressedWA};\n static void ClearLabel(List types, bool ImportAsset = true) {\n\t\tList objs=new List(Selection.objects);\n\t\tforeach(var obj in objs){\n\t\t\tif(obj is Texture2D){\n\t\t\t\tList labels=new List(AssetDatabase.GetLabels(obj));\n\t\t\t\tvar newLabels=new List();\n\t\t\t\tlabels.ForEach((string l)=>{\n\t\t\t\t\tif(Enum.IsDefined(typeof(TextureModifierType),l)){\n\t\t\t\t\t\tif(!types.Contains((TextureModifierType)Enum.Parse(typeof(TextureModifierType),l)))\n\t\t\t\t\t\t\tnewLabels.Add(l);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\tAssetDatabase.SetLabels(obj,newLabels.ToArray());\n\t\t\t\tif(ImportAsset)\n\t\t\t\t\tAssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(obj));\n\t\t\t}\n\t\t}\n\t}\n\n\tstatic void SetLabel(string label,List types){\n\t\tClearLabel(types,false);\n\t\tList objs=new List(Selection.objects);\n\t\tforeach(var obj in objs){\n\t\t\tif(obj is Texture2D){\n\t\t\t\tList labels=new List(AssetDatabase.GetLabels(obj));\n\t\t\t\tlabels.Add(label);\n\t\t\t\tAssetDatabase.SetLabels(obj,labels.ToArray());\n\t\t\t\tEditorUtility.SetDirty(obj);\n AssetDatabase.WriteImportSettingsIfDirty(AssetDatabase.GetAssetPath(obj));\n foreach(Editor ed in (Editor[])UnityEngine.Resources.FindObjectsOfTypeAll(typeof(Editor))){\n\t\t\t\t\tif(ed.target==obj){\n\t\t\t\t\t\ted.Repaint();\n\t\t\t\t\t\tEditorUtility.SetDirty(ed);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t[UnityEditor.MenuItem(\"Assets/Texture Util/Clear Texture Effecter Label\",false,20)]\n\tstatic void ClearTextureEffecterLabel(){\n\t\tClearLabel(effecters);\n\t}\n\t[UnityEditor.MenuItem(\"Assets/Texture Util/Set Label PremultipliedAlpha\",false,20)]\n\tstatic void SetLabelPremultipliedAlpha(){\n\t\tSetLabel(TextureModifierType.PremultipliedAlpha.ToString(),effecters);\n\t}\n\t[UnityEditor.MenuItem(\"Assets/Texture Util/Set Label AlphaBleed\",false,20)]\n\tstatic void SetLabelAlphaBleed(){\n\t\tSetLabel(TextureModifierType.AlphaBleed.ToString(),effecters);\n\t}\n\n\t[UnityEditor.MenuItem(\"Assets/Texture Util/Clear Texture Modifier Label\",false,40)]\n\tstatic void ClearTextureModifierLabel(){\n\t\tClearLabel(modifiers);\n\t}\n\t[UnityEditor.MenuItem(\"Assets/Texture Util/Set Label FloydSteinberg\",false,40)]\n\tstatic void SetLabelFloydSteinberg(){\n\t\tSetLabel(TextureModifierType.FloydSteinberg.ToString(),modifiers);\n\t}\n\t[UnityEditor.MenuItem(\"Assets/Texture Util/Set Label Reduced16bits\",false,40)]\n\tstatic void SetLabelReduced16bits(){\n\t\tSetLabel(TextureModifierType.Reduced16bits.ToString(),modifiers);\n\t}\n\n\t[UnityEditor.MenuItem(\"Assets/Texture Util/Clear Texture Output Label\",false,60)]\n\tstatic void ClearTextureOutputLabel(){\n\t\tClearLabel(outputs);\n\t}\n [UnityEditor.MenuItem(\"Assets/Texture Util/Set Label Convert 16bits\", false, 60)]\n static void SetLabelC16bits() {\n SetLabel(TextureModifierType.C16bits.ToString(), outputs);\n }\n [UnityEditor.MenuItem(\"Assets/Texture Util/Set Label Convert Compressed\", false, 60)]\n static void SetLabelCCompressed() {\n SetLabel(TextureModifierType.CCompressed.ToString(), outputs);\n }\n [UnityEditor.MenuItem(\"Assets/Texture Util/Set Label Convert Compressed no alpha\", false, 60)]\n static void SetLabelCCompressedNA() {\n SetLabel(TextureModifierType.CCompressedNA.ToString(), outputs);\n }\n [UnityEditor.MenuItem(\"Assets/Texture Util/Set Label Convert Compressed with alpha\", false, 60)]\n static void SetLabelCCompressedWA() {\n SetLabel(TextureModifierType.CCompressedWA.ToString(), outputs);\n }\n [UnityEditor.MenuItem(\"Assets/Texture Util/Set Label Texture 16bits\", false, 60)]\n\tstatic void SetLabel16bits(){\n\t\tSetLabel(TextureModifierType.T16bits.ToString(),outputs);\n\t}\n\t[UnityEditor.MenuItem(\"Assets/Texture Util/Set Label Texture 32bits\",false,60)]\n\tstatic void SetLabel32bits(){\n\t\tSetLabel(TextureModifierType.T32bits.ToString(),outputs);\n\t}\n\t[UnityEditor.MenuItem(\"Assets/Texture Util/Set Label Texture Compressed\",false,60)]\n\tstatic void SetLabelCompressed(){\n\t\tSetLabel(TextureModifierType.TCompressed.ToString(),outputs);\n\t}\n [UnityEditor.MenuItem(\"Assets/Texture Util/Set Label Texture Compressed no alpha\", false, 60)]\n static void SetLabelCompressedNA() {\n SetLabel(TextureModifierType.TCompressedNA.ToString(), outputs);\n }\n [UnityEditor.MenuItem(\"Assets/Texture Util/Set Label Texture Compressed with alpha\", false, 60)]\n\tstatic void SetLabelCompressedWA(){\n\t\tSetLabel(TextureModifierType.TCompressedWA.ToString(),outputs);\n\t}\n\t[UnityEditor.MenuItem(\"Assets/Texture Util/Set Label Texture PNG\",false,60)]\n\tstatic void SetLabelPNG(){\n\t\tSetLabel(TextureModifierType.TPNG.ToString(),outputs);\n\t}\n\t[UnityEditor.MenuItem(\"Assets/Texture Util/Set Label Texture JPG\",false,60)]\n\tstatic void SetLabelJPG(){\n\t\tSetLabel(TextureModifierType.TJPG.ToString(),outputs);\n\t}\n\n\tTextureModifierType effecterType=TextureModifierType.None;\n\tTextureModifierType modifierType=TextureModifierType.None;\n\tTextureModifierType outputType=TextureModifierType.None;\n\n\tvoid OnPreprocessTexture(){\n\t\t//return;\n\t\tvar importer = (assetImporter as TextureImporter);\n\t\tUnityEngine.Object obj=AssetDatabase.LoadAssetAtPath(assetPath,typeof(Texture2D));\n\t\tvar labels=new List(AssetDatabase.GetLabels(obj));\n\n\t\tforeach(string label in labels){\n\t\t\tif(Enum.IsDefined(typeof(TextureModifierType),label)){\n\t\t\t\tTextureModifierType type=(TextureModifierType)Enum.Parse(typeof(TextureModifierType),label);\n\t\t\t\tif(effecters.Contains(type)){\n\t\t\t\t\teffecterType=type;\n\t\t\t\t}\n\t\t\t\tif(modifiers.Contains(type)){\n\t\t\t\t\tmodifierType=type;\n\t\t\t\t}\n\t\t\t\tif(outputs.Contains(type)){\n\t\t\t\t\toutputType=type;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif(effecterType!=TextureModifierType.None || modifierType!=TextureModifierType.None || outputType!=TextureModifierType.None){\n\t\t\timporter.alphaIsTransparency=false;\n\t\t\timporter.compressionQuality = (int)TextureCompressionQuality.Best;\n\t\t\tif(importer.textureFormat==TextureImporterFormat.Automatic16bit)\n\t\t\t\timporter.textureFormat = TextureImporterFormat.AutomaticTruecolor;\n\t\t\telse if(importer.textureFormat==TextureImporterFormat.AutomaticCompressed)\n\t\t\t\timporter.textureFormat = TextureImporterFormat.AutomaticTruecolor;\n\t\t\telse if(importer.textureFormat==TextureImporterFormat.RGB16)\n\t\t\t\timporter.textureFormat = TextureImporterFormat.RGB24;\n\t\t\telse if(importer.textureFormat==TextureImporterFormat.RGBA16)\n\t\t\t\timporter.textureFormat = TextureImporterFormat.RGBA32;\n\t\t\telse if(importer.textureFormat==TextureImporterFormat.ARGB16)\n\t\t\t\timporter.textureFormat = TextureImporterFormat.ARGB32;\n\t\t}\n\t}\n\t\n\tvoid OnPostprocessTexture (Texture2D texture){\n\t\tif(effecterType==TextureModifierType.None && modifierType==TextureModifierType.None && outputType==TextureModifierType.None)\n\t\t\treturn;\n\t\tAssetDatabase.StartAssetEditing();\n\t\tvar pixels = texture.GetPixels ();\n\t\tswitch (effecterType){\n\t\tcase TextureModifierType.PremultipliedAlpha:{\n\t\t\tPremultipliedAlpha(ref pixels,texture);\n\t\t\tbreak;\n\t\t}\n\t\tcase TextureModifierType.AlphaBleed:{\n\t\t\tAlphaBleed(ref pixels,texture);\n\t\t\tbreak;\n\t\t}}\n\t\tswitch (modifierType){\n\t\tcase TextureModifierType.FloydSteinberg:{\n\t\t\tFloydSteinberg(ref pixels,texture);\n\t\t\tbreak;\n\t\t}\n\t\tcase TextureModifierType.Reduced16bits:{\n\t\t\tReduced16bits(ref pixels,texture);\n\t\t\tbreak;\n\t\t}}\n //return;\n if (EditorPrefs.GetBool(KEY, false)) {\n switch (outputType) {\n case TextureModifierType.C16bits: {\n texture.SetPixels(pixels);\n texture.Apply(true, true);\n EditorUtility.CompressTexture(texture, TextureFormat.RGBA4444, TextureCompressionQuality.Best); \n break;\n }\n case TextureModifierType.CCompressed: {\n texture.SetPixels(pixels);\n texture.Apply(true, true);\n EditorUtility.CompressTexture(texture, CompressionWithAlphaFormat, TextureCompressionQuality.Best);\n break;\n }\n case TextureModifierType.CCompressedNA: {\n texture.SetPixels(pixels);\n texture.Apply(true, true);\n EditorUtility.CompressTexture(texture, CompressionFormat, TextureCompressionQuality.Best);\n break;\n }\n case TextureModifierType.CCompressedWA: {\n WriteAlphaTexture(pixels, texture);\n texture.SetPixels(pixels);\n texture.Apply(true, true);\n EditorUtility.CompressTexture(texture, CompressionFormat, TextureCompressionQuality.Best);\n break;\n }\n case TextureModifierType.TCompressed: {\n var tex = BuildTexture(texture, TextureFormat.RGBA32);\n tex.SetPixels(pixels);\n tex.Apply(true, true);\n WriteTexture(tex, CompressionWithAlphaFormat, assetPath, \".asset\");\n break;\n }\n case TextureModifierType.TCompressedNA: {\n var tex = BuildTexture(texture, TextureFormat.RGBA32);\n tex.SetPixels(pixels);\n tex.Apply(true, true);\n WriteTexture(tex, CompressionFormat, assetPath, \".asset\");\n break;\n }\n case TextureModifierType.TCompressedWA: {\n WriteAlphaTexture(pixels, texture);\n var tex = BuildTexture(texture, TextureFormat.RGBA32);\n tex.SetPixels(pixels);\n tex.Apply(true, true);\n WriteTexture(tex, CompressionFormat, assetPath, \".asset\");\n break;\n }\n case TextureModifierType.T16bits: {\n var tex = BuildTexture(texture, TextureFormat.RGBA32);\n tex.SetPixels(pixels);\n tex.Apply(true, true);\n WriteTexture(tex, TextureFormat.RGBA4444, assetPath, \".asset\");\n break;\n }\n case TextureModifierType.T32bits: {\n var tex = BuildTexture(texture, TextureFormat.RGBA32);\n tex.SetPixels(pixels);\n tex.Apply(true, true);\n WriteTexture(tex, TextureFormat.RGBA32, assetPath, \".asset\");\n break;\n }\n case TextureModifierType.TPNG: {\n var tex = BuildTexture(texture, TextureFormat.RGBA32);\n tex.SetPixels(pixels);\n tex.Apply(true);\n WritePNGTexture(tex, TextureFormat.RGBA32, assetPath, \"RGBA.png\");\n break;\n }\n case TextureModifierType.TJPG: {\n var tex = BuildTexture(texture, TextureFormat.RGBA32);\n tex.SetPixels(pixels);\n tex.Apply(true);\n WriteJPGTexture(tex, TextureFormat.RGBA32, assetPath, \"RGB.jpg\");\n break;\n }\n default: {\n if (effecterType != TextureModifierType.None || modifierType != TextureModifierType.None) {\n texture.SetPixels(pixels);\n texture.Apply(true);\n }\n break;\n }\n }\n }\n\t\tAssetDatabase.Refresh();\n\t\tAssetDatabase.StopAssetEditing();\n\t}\n\n\tTexture2D BuildTexture(Texture2D texture,TextureFormat format){\n\t\tvar tex = new Texture2D (texture.width, texture.height, format, texture.mipmapCount>1);\n\t\ttex.wrapMode = texture.wrapMode;\n\t\ttex.filterMode = texture.filterMode;\n\t\ttex.mipMapBias = texture.mipMapBias;\n\t\ttex.anisoLevel = texture.anisoLevel;\n\t\treturn tex;\n\t}\n\n\tvoid WriteTexture(Texture2D texture,TextureFormat format,string path,string extension){\n\t\tEditorUtility.CompressTexture (texture,format,TextureCompressionQuality.Best);\n\t\tvar writePath = path.Substring(0,path.LastIndexOf('.'))+extension;\n\t\tvar writeAsset = AssetDatabase.LoadAssetAtPath (writePath,typeof(Texture2D)) as Texture2D;\n\t\tif (writeAsset == null) {\n\t\t\tAssetDatabase.CreateAsset (texture, writePath);\n\t\t} else {\n\t\t\tEditorUtility.CopySerialized (texture, writeAsset);\n\t\t}\n\t}\n\n\tvoid WritePNGTexture(Texture2D texture,TextureFormat format,string path,string extension){\n\t\tEditorUtility.CompressTexture (texture,format,TextureCompressionQuality.Best);\n\t\tbyte[] pngData=texture.EncodeToPNG();\n\t\t//var nPath=path.Substring(0,path.LastIndexOf('.'))+extension;\n\t\tvar writePath = Application.dataPath+(path.Substring(0,path.LastIndexOf('.'))+extension).Substring(6);\n\t\tFile.WriteAllBytes(writePath, pngData);\n\t\tAssetDatabase.SaveAssets();\n\t\tAssetDatabase.Refresh(ImportAssetOptions.ForceSynchronousImport);\n\t}\n\n\tvoid WriteJPGTexture(Texture2D texture,TextureFormat format,string path,string extension){\n\t\tEditorUtility.CompressTexture (texture,format,TextureCompressionQuality.Best);\n\t\tbyte[] jpgData=texture.EncodeToJPG();\n\t\t//var nPath=path.Substring(0,path.LastIndexOf('.'))+extension;\n\t\tvar writePath = Application.dataPath+(path.Substring(0,path.LastIndexOf('.'))+extension).Substring(6);\n\t\tFile.WriteAllBytes(writePath, jpgData);\n\t\tAssetDatabase.SaveAssets();\n\t\tAssetDatabase.Refresh(ImportAssetOptions.ForceSynchronousImport);\n\t}\n\n\tvoid WriteCompressTexture(Color[] pixels,Texture2D texture,TextureFormat format){\n\t\tvar mask = BuildTexture(texture,TextureFormat.RGB24);\n\t\tfor (int i = 0; i < pixels.Length; i++) {\n\t\t\tvar a = pixels [i].a;\n\t\t\tpixels [i] = new Color (a, a, a);\n\t\t}\n\t\tmask.SetPixels (pixels);\n\t\tmask.Apply(true,true);\n\t\tWriteTexture(mask,CompressionFormat,assetPath,\"Alpha.asset\");\n\t}\n\n\tvoid WriteAlphaTexture(Color[] pixels,Texture2D texture){\n\t\tvar mask = new Texture2D (texture.width, texture.height, TextureFormat.RGB24, false);\n\t\tmask.wrapMode = texture.wrapMode;\n\t\tmask.filterMode = texture.filterMode;\n\t\tmask.mipMapBias = texture.mipMapBias;\n\t\tmask.anisoLevel = texture.anisoLevel;\n\t\tvar aPixels = new Color[pixels.Length];\n\t\tfor (int i = 0; i < pixels.Length; i++) {\n\t\t\tvar a = pixels [i].a;\n\t\t\taPixels [i] = new Color (a, a, a);\n\t\t}\n\t\tmask.SetPixels (aPixels);\n\t\tmask.Apply(true,true);\n\t\tWriteTexture(mask,CompressionFormat,assetPath,\"Alpha.asset\");\n\t}\n\n\n\tvoid PremultipliedAlpha(ref Color[] pixels,Texture2D texture){\n//\t\tvar pixels = texture.GetPixels ();\n\t\tfor (int i = 0; i < pixels.Length; i++) {\n\t\t\tvar a = pixels [i].a;\n\t\t\tpixels [i] = new Color (pixels[i].r*a,pixels[i].g*a,pixels[i].b*a,a);\n\t\t}\n//\t\ttexture.SetPixels (pixels);\n\t}", "answers": ["\tvoid AlphaBleed(ref Color[] pixels,Texture2D texture){"], "length": 1085, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "ed4a790f-3eb7-4aa6-902a-1bc9418ec837", "reasoning": "The PremultipliedAlpha method just ended with a closing brace. The next functionality referenced elsewhere is AlphaBleed, which is called in the effecter switch. Therefore the next line should start the definition of the AlphaBleed method, matching the code style used for other methods.", "reasoning_model_answer": "void AlphaBleed(ref Color[] pixels,Texture2D texture){", "assistant_with_reasoning": "\nThe PremultipliedAlpha method just ended with a closing brace. The next functionality referenced elsewhere is AlphaBleed, which is called in the effecter switch. Therefore the next line should start the definition of the AlphaBleed method, matching the code style used for other methods.\n\nvoid AlphaBleed(ref Color[] pixels,Texture2D texture){", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.09, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 18532, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "void AlphaBleed(ref Color[] pixels,Texture2D texture){", "score": 0.99, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/*\n Copyright 2021 Jeffrey Sharp\n\n Permission to use, copy, modify, and distribute this software for any\n purpose with or without fee is hereby granted, provided that the above\n copyright notice and this permission notice appear in all copies.\n\n THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n*/\n\nusing System.Management.Automation;\nusing NUnit.Framework;\n\nnamespace PSql.Tests.Unit;\n\nusing Case = TestCaseData;\n\n[TestFixture]\n[Parallelizable(ParallelScope.All)]\npublic class NewSqlContextCommandTests\n{\n [Test]\n public void Default()\n {\n @\"\n New-SqlContext\n \"\n .ShouldOutput(\n new SqlContext()\n );\n }\n\n public static IEnumerable StringCases = new[]\n {\n new Case(\"$null\", null),\n new Case(\"''\", null),\n new Case(\"'a'\", \"a\" )\n };\n\n public static IEnumerable SwitchCases = new[]\n {\n new Case(\"\", true),\n new Case(\":$true\", true),\n new Case(\":$false\", false)\n };\n\n #region -ResourceGroupName\n\n [Test]\n [TestCaseSource(nameof(StringCases))]\n public void ResourceGroupName_Set_Valid(string expression, string? value)\n {\n @$\"\n New-SqlContext -Azure -ResourceGroupName {expression}\n \"\n .ShouldOutput(\n new AzureSqlContext { ServerResourceGroupName = value }\n );\n }\n\n [Test]\n public void ResourceGroupName_Set_NonAzure()\n {\n @$\"\n New-SqlContext -ResourceGroupName x\n \"\n .ShouldThrow(\n \"Parameter set cannot be resolved using the specified named parameters.\"\n );\n }\n\n [Test]\n [TestCaseSource(nameof(StringCases))]\n public void ResourceGroupName_Override_Valid(string expression, string? value)\n {\n @$\"\n New-SqlContext -Azure -ResourceGroupName x | New-SqlContext -ResourceGroupName {expression}\n \"\n .ShouldOutput(\n new AzureSqlContext { ServerResourceGroupName = value }\n );\n }\n\n [Test]\n public void ResourceGroupName_Override_NonAzure()\n {\n @$\"\n New-SqlContext | New-SqlContext -ResourceGroupName x\n \"\n .ShouldOutput(\n new PSWarning(\"The 'ResourceGroupName' argument was ignored because the context is not an Azure SQL Database context.\"),\n new SqlContext()\n );\n }\n\n #endregion\n #region -ServerResourceName\n\n [Test]\n [TestCaseSource(nameof(StringCases))]\n public void ServerResourceName_Set_Valid(string expression, string? value)\n {\n @$\"\n New-SqlContext -Azure -ServerResourceName {expression}\n \"\n .ShouldOutput(\n new AzureSqlContext { ServerResourceName = value }\n );\n }\n\n [Test]\n public void ServerResourceName_Set_NonAzure()\n {\n @$\"\n New-SqlContext -ServerResourceName x\n \"\n .ShouldThrow(\n \"Parameter set cannot be resolved using the specified named parameters.\"\n );\n }\n\n [Test]\n [TestCaseSource(nameof(StringCases))]\n public void ServerResourceName_Override_Valid(string expression, string? value)\n {\n @$\"\n New-SqlContext -Azure -ServerResourceName x | New-SqlContext -ServerResourceName {expression}\n \"\n .ShouldOutput(\n new AzureSqlContext { ServerResourceName = value }\n );\n }\n\n [Test]\n public void ServerResourceName_Override_NonAzure()\n {\n @$\"\n New-SqlContext | New-SqlContext -ServerResourceName x\n \"\n .ShouldOutput(\n new PSWarning(\"The 'ServerResourceName' argument was ignored because the context is not an Azure SQL Database context.\"),\n new SqlContext()\n );\n }\n\n #endregion\n #region -ServerName\n\n [Test]\n [TestCaseSource(nameof(StringCases))]\n public void ServerName_Set_Valid(string expression, string? value)\n {\n @$\"\n New-SqlContext -ServerName {expression}\n \"\n .ShouldOutput(\n new SqlContext { ServerName = value }\n );\n }\n\n [Test]\n [TestCaseSource(nameof(StringCases))]\n public void ServerName_Override_Valid(string expression, string? value)\n {\n @$\"\n New-SqlContext -ServerName x | New-SqlContext -ServerName {expression}\n \"\n .ShouldOutput(\n new SqlContext { ServerName = value }\n );\n }\n\n #endregion\n #region -ServerPort\n\n public static IEnumerable ValidPortCases = new[]\n {\n new Case(\"$null\", null),\n new Case(\"1\", (ushort?) 1),\n new Case(\"65535\", (ushort?) 65535)\n };\n\n public static IEnumerable InvalidPortCases = new[]\n {\n new Case(\"''\", @\"Cannot validate argument on parameter 'ServerPort'. The value \"\"0\"\" is not a positive number.\"),\n new Case(\"0\", @\"Cannot validate argument on parameter 'ServerPort'. The value \"\"0\"\" is not a positive number.\"),\n new Case(\"-1\", @\"Cannot bind parameter 'ServerPort'. Cannot convert value \"\"\" + @\"-1\"\" to type \"\"System.UInt16\"\". Error: \"\"Value was either too large or too small for a UInt16.\"\"\"),\n new Case(\"65536\", @\"Cannot bind parameter 'ServerPort'. Cannot convert value \"\"\" + @\"65536\"\" to type \"\"System.UInt16\"\". Error: \"\"Value was either too large or too small for a UInt16.\"\"\")\n };\n\n [Test]\n [TestCaseSource(nameof(ValidPortCases))]\n public void ServerPort_Set_Valid(string expression, ushort? value)\n {\n @$\"\n New-SqlContext -ServerPort {expression}\n \"\n .ShouldOutput(\n new SqlContext { ServerPort = value }\n );\n }\n\n [Test]\n [TestCaseSource(nameof(InvalidPortCases))]\n public void ServerPort_Invalid(string expression, string message)\n {\n @$\"\n New-SqlContext -ServerPort {expression}\n \"\n .ShouldThrow(message);\n }\n\n [Test]\n [TestCaseSource(nameof(ValidPortCases))]\n public void ServerPort_Override_Valid(string expression, ushort? value)\n {\n @$\"\n New-SqlContext -ServerPort 42 | New-SqlContext -ServerPort {expression}\n \"\n .ShouldOutput(\n new SqlContext { ServerPort = value }\n );\n }\n\n [Test]\n [TestCaseSource(nameof(InvalidPortCases))]\n public void ServerPort_Override_Invalid(string expression, string message)\n {\n @$\"\n New-SqlContext -ServerPort 1337 | New-SqlContext -ServerPort {expression}\n \"\n .ShouldThrow(message);\n }\n\n #endregion\n #region -InstanceName\n\n [Test]\n [TestCaseSource(nameof(StringCases))]\n public void InstanceName_Set_Valid(string expression, string? value)\n {\n @$\"\n New-SqlContext -InstanceName {expression}\n \"\n .ShouldOutput(\n new SqlContext { InstanceName = value }\n );\n }\n\n [Test]\n [TestCaseSource(nameof(StringCases))]\n public void InstanceName_Override_Valid(string expression, string? value)\n {\n @$\"\n New-SqlContext -InstanceName x | New-SqlContext -InstanceName {expression}\n \"\n .ShouldOutput(\n new SqlContext { InstanceName = value }\n );\n }\n\n #endregion\n #region -DatabaseName\n\n [Test]\n [TestCaseSource(nameof(StringCases))]\n public void DatabaseName_Set_Valid(string expression, string? value)\n {\n @$\"\n New-SqlContext -DatabaseName {expression}\n \"\n .ShouldOutput(\n new SqlContext { DatabaseName = value }\n );\n }\n\n [Test]\n [TestCaseSource(nameof(StringCases))]\n public void DatabaseName_Override_Valid(string expression, string? value)\n {\n @$\"\n New-SqlContext -DatabaseName x | New-SqlContext -DatabaseName {expression}\n \"\n .ShouldOutput(\n new SqlContext { DatabaseName = value }\n );\n }\n\n #endregion\n #region -AuthenticationMode\n\n public static IEnumerable ValidAuthenticationModeCases = new[]\n {\n new Case(\"0\", AzureAuthenticationMode.Default),\n new Case(\"7\", AzureAuthenticationMode.AadManagedIdentity),\n new Case(\"Default\", AzureAuthenticationMode.Default),\n new Case(\"AadManagedIdentity\", AzureAuthenticationMode.AadManagedIdentity),\n };\n\n public static IEnumerable InvalidAuthenticationModeCases = new[]\n {\n new Case(\"$null\", @\"Cannot bind parameter 'AuthenticationMode'\"),\n new Case(\"''\", @\"Cannot bind parameter 'AuthenticationMode'\"),\n new Case(\"-1\", @\"Cannot bind parameter 'AuthenticationMode'\"),\n new Case(\"8\", @\"Cannot bind parameter 'AuthenticationMode'\"),\n new Case(\"Wrong\", @\"Cannot bind parameter 'AuthenticationMode'\"),\n };\n\n [Test]\n [TestCaseSource(nameof(ValidAuthenticationModeCases))]\n public void AuthenticationMode_Set_Valid(string expression, AzureAuthenticationMode value)\n {\n @$\"\n New-SqlContext -Azure `\n -ResourceGroupName rg `\n -ServerResourceName srv `\n -AuthenticationMode {expression}\n \"\n .ShouldOutput(\n new AzureSqlContext\n {\n ServerResourceGroupName = \"rg\",\n ServerResourceName = \"srv\",\n AuthenticationMode = value\n }\n );\n }\n\n [Test]\n [TestCaseSource(nameof(InvalidAuthenticationModeCases))]\n public void AuthenticationMode_Set_Invalid(string expression, string message)\n {\n @$\"\n New-SqlContext -Azure `\n -ResourceGroupName rg `\n -ServerResourceName srv `\n -AuthenticationMode {expression}\n \"\n .ShouldThrow(message);\n }\n\n [Test]\n public void AuthenticationMode_Set_NonAzure()\n {\n @$\"\n New-SqlContext -AuthenticationMode AadPassword\n \"\n .ShouldThrow(\n \"Parameter set cannot be resolved using the specified named parameters.\"\n );\n }\n\n [Test]\n [TestCaseSource(nameof(ValidAuthenticationModeCases))]\n public void AuthenticationMode_Override_Valid(string expression, AzureAuthenticationMode value)\n {\n @$\"\n New-SqlContext -Azure `\n -ResourceGroupName rg `\n -ServerResourceName srv `\n -AuthenticationMode SqlPassword `\n | `\n New-SqlContext -AuthenticationMode {expression}\n \"\n .ShouldOutput(\n new AzureSqlContext\n {\n ServerResourceGroupName = \"rg\",\n ServerResourceName = \"srv\",\n AuthenticationMode = value\n }\n );\n }\n\n [Test]\n [TestCaseSource(nameof(InvalidAuthenticationModeCases))]\n public void AuthenticationMode_Override_Invalid(string expression, string message)\n {\n @$\"\n New-SqlContext -Azure `\n -ResourceGroupName rg `\n -ServerResourceName srv `\n -AuthenticationMode SqlPassword `\n | `\n New-SqlContext -AuthenticationMode {expression}\n \"\n .ShouldThrow(message);\n }\n\n [Test]\n public void AuthenticationMode_Override_NonAzure()\n {\n @$\"\n New-SqlContext | New-SqlContext -AuthenticationMode AadServicePrincipal\n \"\n .ShouldOutput(\n new PSWarning(\"The 'AuthenticationMode' argument was ignored because the context is not an Azure SQL Database context.\"),\n new SqlContext()\n );\n }\n\n #endregion\n #region -Credential\n\n public static IEnumerable ValidCredentialCases = new[]\n {\n new Case(\"$null\", null),\n new Case(\"([PSCredential]::Empty)\", PSCredential.Empty),\n new Case(\"$Credential\", new PSCredential(\"a\", \"p\".Secure())),\n };\n\n public static IEnumerable InvalidCredentialCases = new[]\n {\n new Case(\"''\", @\"Cannot process argument transformation on parameter 'Credential'. A command that prompts the user failed because the host program or the command type does not support user interaction.\"),\n new Case(\"username\", @\"Cannot process argument transformation on parameter 'Credential'. A command that prompts the user failed because the host program or the command type does not support user interaction.\"),\n };\n\n [Test]\n [TestCaseSource(nameof(ValidCredentialCases))]\n public void Credential_Set_Valid(string expression, PSCredential? value)\n {\n @$\"\n $Password = ConvertTo-SecureString p -AsPlainText\n $Credential = New-Object PSCredential a, $Password\n New-SqlContext -Credential {expression}\n \"\n .ShouldOutput(\n new SqlContext { Credential = value }\n );\n }\n\n [Test]\n [TestCaseSource(nameof(InvalidCredentialCases))]\n public void Credential_Set_Invalid(string expression, string message)\n {\n @$\"\n New-SqlContext -Credential {expression}\n \"\n .ShouldThrow(message);\n }\n\n [Test]\n [TestCaseSource(nameof(ValidCredentialCases))]\n public void Credential_Override_Valid(string expression, PSCredential? value)\n {\n @$\"\n $Password = ConvertTo-SecureString p -AsPlainText\n $Credential = New-Object PSCredential a, $Password\n $Credential2 = New-Object PSCredential b, $Password\n New-SqlContext -Credential $Credential2 | New-SqlContext -Credential {expression}\n \"\n .ShouldOutput(\n new SqlContext { Credential = value }\n );\n }\n\n [Test]\n [TestCaseSource(nameof(InvalidCredentialCases))]\n public void Credential_Override_Invalid(string expression, string message)\n {\n @$\"\n $Password = ConvertTo-SecureString p -AsPlainText\n $Credential2 = New-Object PSCredential b, $Password\n New-SqlContext -Credential $Credential2 | New-SqlContext -Credential {expression}\n \"\n .ShouldThrow(message);\n }\n\n #endregion\n #region -EncryptionMode\n\n public static IEnumerable ValidEncryptionModeCases = new[]\n {\n new Case(\"0\", EncryptionMode.Default),\n new Case(\"3\", EncryptionMode.Full),\n new Case(\"Default\", EncryptionMode.Default),\n new Case(\"Full\", EncryptionMode.Full),\n };\n\n public static IEnumerable InvalidEncryptionModeCases = new[]\n {", "answers": [" new Case(\"$null\", @\"Cannot bind parameter 'EncryptionMode'\"),"], "length": 1278, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "527ec24b-048a-4eae-aac0-5b3ce22d51bf", "reasoning": "The code is defining the InvalidEncryptionModeCases collection. Following the pattern used for other Invalid*Cases (e.g., AuthenticationMode), the first entry should be a case for a null value with a bind‑parameter error message. Thus the next line is the first element of the array: a new Case with \"$null\" and the appropriate error string.", "reasoning_model_answer": "new Case(\"$null\", @\"Cannot bind parameter 'EncryptionMode'\")", "assistant_with_reasoning": "\nThe code is defining the InvalidEncryptionModeCases collection. Following the pattern used for other Invalid*Cases (e.g., AuthenticationMode), the first entry should be a case for a null value with a bind‑parameter error message. Thus the next line is the first element of the array: a new Case with \"$null\" and the appropriate error string.\n\nnew Case(\"$null\", @\"Cannot bind parameter 'EncryptionMode'\")", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.615, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 15363, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "new Case(\"$null\", @\"Cannot bind parameter 'EncryptionMode'\")", "score": 0.93, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/*\n * Copyright (c) 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage dev.chromeos.lowlatencystylusdemo.gpu;\n\nimport android.opengl.GLES20;\nimport android.util.Log;\n\nimport java.nio.IntBuffer;\nimport java.util.ArrayList;\nimport java.util.List;\n\n/**\n * A wrapper class to manage all the opengl buffers needed to draw with both line-based and bitmap-\n * based brushes. Handles both committed and predicted points\n */\npublic class DrawPoints {\n // Convenience constants\n public static final int FLOAT_SIZE = Float.SIZE / Byte.SIZE;\n public static final int INT_SIZE = Float.SIZE / Byte.SIZE;\n public static final int NUM_TEXTURE_COORDINATES_PER_SQUARE = 8;\n public static final int TEXTURE_COORDINATE_SIZE = FLOAT_SIZE * NUM_TEXTURE_COORDINATES_PER_SQUARE;\n public static final int NUM_COLOR_VALUES_PER_SQUARE = 4 * 4; //rgba * 4 vertices\n public static final int TEXTURE_COLOR_SIZE = FLOAT_SIZE * NUM_COLOR_VALUES_PER_SQUARE;\n public static final int NUM_INDICES_PER_SQUARE = 6;\n public static final int SQUARE_INDICES_SIZE = INT_SIZE * NUM_INDICES_PER_SQUARE;\n public static final int DEFAULT_BUFFER_SIZE = 1024;\n\n private int mPointCount;\n\n // Keep track of previous vertex for line drawing operations\n Vertex mPreviousVertex = null;\n\n // List of predicted vertices\n public final List mPredictedDrawPoints;\n public final List mPredictedVertices;\n Vertex mPreviousPredictionVertex = null;\n\n\n // Buffer to hold Vertex's of drawn points. Will not contain predicted points\n public AutoGrowByteBuffer mVertexBuffer;\n // Reference to the buffer used by GL to draw the vertices\n public final int mGLVertexBufferHandle;\n\n // Buffer to hold data for texture squares\n public AutoGrowByteBuffer mSquareBuffer;\n // Reference to the buffer for texture squares\n public final int mGLSquareBufferHandle;\n\n // Buffer to hold data for texture coordinates\n public AutoGrowByteBuffer mTextureCoordinateBuffer;\n // Reference to the buffer for texture coordinates\n public final int mGLTextureCoordinateBufferHandle;\n\n // Buffer to hold color data for texture squares\n public AutoGrowByteBuffer mTextureColorBuffer;\n // Reference to the buffer for texture squares\n public final int mGLTextureColorBufferHandle;\n\n // Buffer to hold indices for texture squares\n public AutoGrowByteBuffer mSquareIndexBuffer;\n // Reference to the buffer for texture square indices\n public final int mGLSquareIndexBufferHandle;\n\n public DrawPoints() {\n // List of predicted points\n mPredictedDrawPoints = new ArrayList<>();\n mPredictedVertices = new ArrayList<>();\n\n // Vertex buffer for line shaders\n mVertexBuffer = new AutoGrowByteBuffer(DEFAULT_BUFFER_SIZE * Vertex.TOTAL_SIZE);\n IntBuffer tempVertexBuffer = IntBuffer.allocate(1);\n GLES20.glGenBuffers(1, tempVertexBuffer);\n mGLVertexBufferHandle = tempVertexBuffer.get();\n\n // Square buffer for bitmap shaders\n mSquareBuffer = new AutoGrowByteBuffer(DEFAULT_BUFFER_SIZE * Square.TOTAL_SIZE);\n IntBuffer tempSquareBuffer = IntBuffer.allocate(1);\n GLES20.glGenBuffers(1, tempSquareBuffer);\n mGLSquareBufferHandle = tempSquareBuffer.get();\n\n // Texture coordinate buffer for bitmap shaders\n mTextureCoordinateBuffer = new AutoGrowByteBuffer(DEFAULT_BUFFER_SIZE * TEXTURE_COORDINATE_SIZE);\n IntBuffer tempTextureCoordinateBuffer = IntBuffer.allocate(1);\n GLES20.glGenBuffers(1, tempTextureCoordinateBuffer);\n mGLTextureCoordinateBufferHandle = tempTextureCoordinateBuffer.get();\n\n // Texture color buffer for bitmap shaders\n mTextureColorBuffer = new AutoGrowByteBuffer(DEFAULT_BUFFER_SIZE * TEXTURE_COLOR_SIZE);\n IntBuffer tempTextureColorBuffer = IntBuffer.allocate(1);\n GLES20.glGenBuffers(1, tempTextureColorBuffer);\n mGLTextureColorBufferHandle = tempTextureColorBuffer.get();\n\n // Square indices buffer for bitmap shaders\n mSquareIndexBuffer = new AutoGrowByteBuffer(DEFAULT_BUFFER_SIZE * SQUARE_INDICES_SIZE);\n IntBuffer tempSquareIndexBuffer = IntBuffer.allocate(1);\n GLES20.glGenBuffers(1, tempSquareIndexBuffer);\n mGLSquareIndexBufferHandle = tempSquareIndexBuffer.get();\n }\n\n // Draw point count\n public int count() {\n return mPointCount;\n }\n public void count(int newCount) {\n mPointCount = newCount;\n }\n\n // Clear current drawing and predictions\n // Don't erase or re-allocate memory, just move the position pointers\n public void clear() {\n clearPrediction();\n mVertexBuffer.position(0);\n mSquareBuffer.position(0);\n mTextureCoordinateBuffer.position(0);\n mTextureColorBuffer.position(0);\n mSquareIndexBuffer.position(0);\n mPointCount = 0;\n }\n\n // Clear prediction lists\n public void clearPrediction() {\n mPredictedDrawPoints.clear();\n mPredictedVertices.clear();\n }\n\n // Line shaders need to keep track of last drawn point. Set last point to null to prevent\n // starting the next line from beginning from the last point if the pen has been lifted\n public void endStroke() {\n mPreviousVertex = null;\n mPreviousPredictionVertex = null;\n }\n\n /**\n * Add a point to the drawing list. For line brushes that use GL_LINES, two points must be\n * added to the draw buffer (start and finish) as well as color info.\n * For bitmap brushes, vertex, texture coordinates, color, and array indices need to be\n * generated.\n * @param drawPoint The float point to add to the drawing list\n */\n public void addDrawPoint(DrawPoint drawPoint) {\n // For bitmap shaders, just add one point\n addSquare(drawPoint);\n\n // For line shaders, add start and finish of gesture\n if (null == mPreviousVertex) {\n // This is the first point, queue it up as the beginning of the line\n mPreviousVertex = new Vertex(drawPoint);\n // Add same point twice to start off a new line\n addVertex(mPreviousVertex);\n addVertex(mPreviousVertex);\n } else {\n // This is the middle or end of gesture, draw from last point to the new point\n Vertex newVertex = new Vertex(drawPoint);\n // Add start and finish\n addVertex(mPreviousVertex);\n addVertex(newVertex);\n mPreviousVertex = newVertex;\n }\n mPointCount++;\n }\n\n // Add a predicted point to the prediction lists\n public void addPredictionDrawPoint(DrawPoint drawPoint) {\n // Add predicted drawpoints for bitmap shaders\n mPredictedDrawPoints.add(drawPoint);\n // Add predicted vertices for line shaders\n mPredictedVertices.add(new Vertex(drawPoint));\n }\n\n // Add a Vertex to the line shader buffer\n public void addVertex(Vertex vertex) {\n mVertexBuffer.put(vertex.data);\n }\n\n // Add a list of predicted vertices for the line shader\n public void addPredictedVerticesForDraw(Iterable vertices) {\n // If there is no line currently being drawn, do not add a prediction\n if (null != mPreviousVertex) {\n // Predictions can contain several points, if this is the first point of a prediction,\n // start at the last drawn point\n if (null == mPreviousPredictionVertex) {\n mPreviousPredictionVertex = mPreviousVertex;\n }\n\n for (Vertex v : vertices) {\n // For drawn lines, add vertices in groups of 2 (beginning and end)", "answers": [" addVertex(mPreviousPredictionVertex);"], "length": 917, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "dc77aa22-d985-4652-85c1-be81b066db3a", "reasoning": "We are inside addPredictedVerticesForDraw. After checking previous vertex and initializing previous prediction vertex, we iterate over each predicted vertex v. The comment says we need to add vertices in groups of 2 (beginning and end) for drawn lines. The first step is to add the start vertex of the segment, which is the previous prediction vertex. Therefore the next line should call addVertex with mPreviousPredictionVertex.", "reasoning_model_answer": "addVertex(mPreviousPredictionVertex);", "assistant_with_reasoning": "\nWe are inside addPredictedVerticesForDraw. After checking previous vertex and initializing previous prediction vertex, we iterate over each predicted vertex v. The comment says we need to add vertices in groups of 2 (beginning and end) for drawn lines. The first step is to add the start vertex of the segment, which is the previous prediction vertex. Therefore the next line should call addVertex with mPreviousPredictionVertex.\n\naddVertex(mPreviousPredictionVertex);", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.838, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 8291, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "addVertex(mPreviousPredictionVertex);", "score": 0.82, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.apache.cassandra.db.compaction;\n\nimport java.util.*;\n\n\nimport com.google.common.annotations.VisibleForTesting;\nimport com.google.common.collect.*;\nimport com.google.common.primitives.Doubles;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.fasterxml.jackson.databind.JsonNode;\nimport com.fasterxml.jackson.databind.node.JsonNodeFactory;\nimport com.fasterxml.jackson.databind.node.ObjectNode;\nimport org.apache.cassandra.io.sstable.metadata.StatsMetadata;\nimport org.apache.cassandra.schema.CompactionParams;\nimport org.apache.cassandra.schema.TableMetadata;\nimport org.apache.cassandra.config.Config;\nimport org.apache.cassandra.db.ColumnFamilyStore;\nimport org.apache.cassandra.db.lifecycle.LifecycleTransaction;\nimport org.apache.cassandra.db.rows.UnfilteredRowIterator;\nimport org.apache.cassandra.dht.Range;\nimport org.apache.cassandra.dht.Token;\nimport org.apache.cassandra.exceptions.ConfigurationException;\nimport org.apache.cassandra.io.sstable.ISSTableScanner;\nimport org.apache.cassandra.io.sstable.format.SSTableReader;\n\npublic class LeveledCompactionStrategy extends AbstractCompactionStrategy\n{\n private static final Logger logger = LoggerFactory.getLogger(LeveledCompactionStrategy.class);\n private static final String SSTABLE_SIZE_OPTION = \"sstable_size_in_mb\";\n private static final boolean tolerateSstableSize = Boolean.getBoolean(Config.PROPERTY_PREFIX + \"tolerate_sstable_size\");\n private static final String LEVEL_FANOUT_SIZE_OPTION = \"fanout_size\";\n private static final String SINGLE_SSTABLE_UPLEVEL_OPTION = \"single_sstable_uplevel\";\n public static final int DEFAULT_LEVEL_FANOUT_SIZE = 10;\n\n @VisibleForTesting\n final LeveledManifest manifest;\n private final int maxSSTableSizeInMB;\n private final int levelFanoutSize;\n private final boolean singleSSTableUplevel;\n\n public LeveledCompactionStrategy(ColumnFamilyStore cfs, Map options)\n {\n super(cfs, options);\n int configuredMaxSSTableSize = 160;\n int configuredLevelFanoutSize = DEFAULT_LEVEL_FANOUT_SIZE;\n boolean configuredSingleSSTableUplevel = false;\n SizeTieredCompactionStrategyOptions localOptions = new SizeTieredCompactionStrategyOptions(options);\n if (options != null)\n {\n if (options.containsKey(SSTABLE_SIZE_OPTION))\n {\n configuredMaxSSTableSize = Integer.parseInt(options.get(SSTABLE_SIZE_OPTION));\n if (!tolerateSstableSize)\n {\n if (configuredMaxSSTableSize >= 1000)\n logger.warn(\"Max sstable size of {}MB is configured for {}.{}; having a unit of compaction this large is probably a bad idea\",\n configuredMaxSSTableSize, cfs.name, cfs.getTableName());\n if (configuredMaxSSTableSize < 50)\n logger.warn(\"Max sstable size of {}MB is configured for {}.{}. Testing done for CASSANDRA-5727 indicates that performance improves up to 160MB\",\n configuredMaxSSTableSize, cfs.name, cfs.getTableName());\n }\n }\n\n if (options.containsKey(LEVEL_FANOUT_SIZE_OPTION))\n {\n configuredLevelFanoutSize = Integer.parseInt(options.get(LEVEL_FANOUT_SIZE_OPTION));\n }\n\n if (options.containsKey(SINGLE_SSTABLE_UPLEVEL_OPTION))\n {\n configuredSingleSSTableUplevel = Boolean.parseBoolean(options.get(SINGLE_SSTABLE_UPLEVEL_OPTION));\n }\n }\n maxSSTableSizeInMB = configuredMaxSSTableSize;\n levelFanoutSize = configuredLevelFanoutSize;\n singleSSTableUplevel = configuredSingleSSTableUplevel;\n\n manifest = new LeveledManifest(cfs, this.maxSSTableSizeInMB, this.levelFanoutSize, localOptions);\n logger.trace(\"Created {}\", manifest);\n }\n\n public int getLevelSize(int i)\n {\n return manifest.getLevelSize(i);\n }\n\n public int[] getAllLevelSize()\n {\n return manifest.getAllLevelSize();\n }\n\n public long[] getAllLevelSizeBytes()\n {\n return manifest.getAllLevelSizeBytes();\n }\n\n @Override\n public void startup()\n {\n manifest.calculateLastCompactedKeys();\n super.startup();\n }\n\n /**\n * the only difference between background and maximal in LCS is that maximal is still allowed\n * (by explicit user request) even when compaction is disabled.\n */\n @SuppressWarnings(\"resource\") // transaction is closed by AbstractCompactionTask::execute\n public AbstractCompactionTask getNextBackgroundTask(int gcBefore)\n {\n Collection previousCandidate = null;\n while (true)\n {\n OperationType op;\n LeveledManifest.CompactionCandidate candidate = manifest.getCompactionCandidates();\n if (candidate == null)\n {\n // if there is no sstable to compact in standard way, try compacting based on droppable tombstone ratio\n SSTableReader sstable = findDroppableSSTable(gcBefore);\n if (sstable == null)\n {\n logger.trace(\"No compaction necessary for {}\", this);\n return null;\n }\n candidate = new LeveledManifest.CompactionCandidate(Collections.singleton(sstable),\n sstable.getSSTableLevel(),\n getMaxSSTableBytes());\n op = OperationType.TOMBSTONE_COMPACTION;\n }\n else\n {\n op = OperationType.COMPACTION;\n }\n\n // Already tried acquiring references without success. It means there is a race with\n // the tracker but candidate SSTables were not yet replaced in the compaction strategy manager\n if (candidate.sstables.equals(previousCandidate))\n {\n logger.warn(\"Could not acquire references for compacting SSTables {} which is not a problem per se,\" +\n \"unless it happens frequently, in which case it must be reported. Will retry later.\",\n candidate.sstables);\n return null;\n }\n\n LifecycleTransaction txn = cfs.getTracker().tryModify(candidate.sstables, OperationType.COMPACTION);\n if (txn != null)\n {\n AbstractCompactionTask newTask;\n if (!singleSSTableUplevel || op == OperationType.TOMBSTONE_COMPACTION || txn.originals().size() > 1)\n newTask = new LeveledCompactionTask(cfs, txn, candidate.level, gcBefore, candidate.maxSSTableBytes, false);\n else\n newTask = new SingleSSTableLCSTask(cfs, txn, candidate.level);\n\n newTask.setCompactionType(op);\n return newTask;\n }\n previousCandidate = candidate.sstables;\n }\n }\n\n @SuppressWarnings(\"resource\") // transaction is closed by AbstractCompactionTask::execute\n public synchronized Collection getMaximalTask(int gcBefore, boolean splitOutput)\n {\n Iterable sstables = manifest.getSSTables();\n\n Iterable filteredSSTables = filterSuspectSSTables(sstables);\n if (Iterables.isEmpty(sstables))\n return null;\n LifecycleTransaction txn = cfs.getTracker().tryModify(filteredSSTables, OperationType.COMPACTION);\n if (txn == null)\n return null;\n return Arrays.asList(new LeveledCompactionTask(cfs, txn, 0, gcBefore, getMaxSSTableBytes(), true));\n\n }\n\n @Override\n @SuppressWarnings(\"resource\") // transaction is closed by AbstractCompactionTask::execute\n public AbstractCompactionTask getUserDefinedTask(Collection sstables, int gcBefore)\n {\n\n if (sstables.isEmpty())\n return null;\n\n LifecycleTransaction transaction = cfs.getTracker().tryModify(sstables, OperationType.COMPACTION);\n if (transaction == null)\n {\n logger.trace(\"Unable to mark {} for compaction; probably a background compaction got to it first. You can disable background compactions temporarily if this is a problem\", sstables);\n return null;\n }\n int level = sstables.size() > 1 ? 0 : sstables.iterator().next().getSSTableLevel();\n return new LeveledCompactionTask(cfs, transaction, level, gcBefore, level == 0 ? Long.MAX_VALUE : getMaxSSTableBytes(), false);\n }\n\n @Override\n public AbstractCompactionTask getCompactionTask(LifecycleTransaction txn, int gcBefore, long maxSSTableBytes)\n {\n assert txn.originals().size() > 0;\n int level = -1;\n // if all sstables are in the same level, we can set that level:\n for (SSTableReader sstable : txn.originals())\n {\n if (level == -1)\n level = sstable.getSSTableLevel();\n if (level != sstable.getSSTableLevel())\n level = 0;\n }\n return new LeveledCompactionTask(cfs, txn, level, gcBefore, maxSSTableBytes, false);\n }\n\n /**\n * Leveled compaction strategy has guarantees on the data contained within each level so we\n * have to make sure we only create groups of SSTables with members from the same level.\n * This way we won't end up creating invalid sstables during anti-compaction.\n * @param ssTablesToGroup\n * @return Groups of sstables from the same level\n */\n @Override\n public Collection> groupSSTablesForAntiCompaction(Collection ssTablesToGroup)\n {\n int groupSize = 2;\n Map> sstablesByLevel = new HashMap<>();\n for (SSTableReader sstable : ssTablesToGroup)\n {\n Integer level = sstable.getSSTableLevel();\n Collection sstablesForLevel = sstablesByLevel.get(level);\n if (sstablesForLevel == null)\n {\n sstablesForLevel = new ArrayList();\n sstablesByLevel.put(level, sstablesForLevel);\n }\n sstablesForLevel.add(sstable);\n }\n\n Collection> groupedSSTables = new ArrayList<>();\n\n for (Collection levelOfSSTables : sstablesByLevel.values())\n {\n Collection currGroup = new ArrayList<>(groupSize);\n for (SSTableReader sstable : levelOfSSTables)\n {\n currGroup.add(sstable);\n if (currGroup.size() == groupSize)\n {\n groupedSSTables.add(currGroup);\n currGroup = new ArrayList<>(groupSize);\n }\n }\n\n if (currGroup.size() != 0)\n groupedSSTables.add(currGroup);\n }", "answers": [" return groupedSSTables;"], "length": 964, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "fbf9aeec-15bb-4d90-a9ed-0bcbc1db98e6", "reasoning": "The method groupSSTablesForAntiCompaction builds a collection of grouped SSTable sets. After iterating over each level and adding any remaining partial group, the method should return the assembled collection. The next logical line is the return statement returning groupedSSTables.", "reasoning_model_answer": "return groupedSSTables;", "assistant_with_reasoning": "\nThe method groupSSTablesForAntiCompaction builds a collection of grouped SSTable sets. After iterating over each level and adding any remaining partial group, the method should return the assembled collection. The next logical line is the return statement returning groupedSSTables.\n\nreturn groupedSSTables;", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.093, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 11961, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "return groupedSSTables;", "score": 0.85, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/**\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.twitter.distributedlog.service;\n\nimport com.google.common.annotations.VisibleForTesting;\nimport com.google.common.base.Preconditions;\nimport com.twitter.common.zookeeper.ServerSet;\nimport com.twitter.distributedlog.client.ClientConfig;\nimport com.twitter.distributedlog.client.DistributedLogClientImpl;\nimport com.twitter.distributedlog.client.monitor.MonitorServiceClient;\nimport com.twitter.distributedlog.client.resolver.RegionResolver;\nimport com.twitter.distributedlog.client.resolver.DefaultRegionResolver;\nimport com.twitter.distributedlog.client.routing.RegionsRoutingService;\nimport com.twitter.distributedlog.client.routing.RoutingService;\nimport com.twitter.distributedlog.client.routing.RoutingUtils;\nimport com.twitter.finagle.builder.ClientBuilder;\nimport com.twitter.finagle.stats.NullStatsReceiver;\nimport com.twitter.finagle.stats.StatsReceiver;\nimport com.twitter.finagle.thrift.ClientId;\nimport org.apache.commons.lang.StringUtils;\n\nimport java.net.SocketAddress;\nimport java.net.URI;\nimport java.util.Random;\n\npublic final class DistributedLogClientBuilder {\n\n private static final Random random = new Random(System.currentTimeMillis());\n\n private String _name = null;\n private ClientId _clientId = null;\n private RoutingService.Builder _routingServiceBuilder = null;\n private ClientBuilder _clientBuilder = null;\n private StatsReceiver _statsReceiver = new NullStatsReceiver();\n private StatsReceiver _streamStatsReceiver = new NullStatsReceiver();\n private ClientConfig _clientConfig = new ClientConfig();\n private boolean _enableRegionStats = false;\n private final RegionResolver _regionResolver = new DefaultRegionResolver();\n\n /**\n * Create a client builder\n *\n * @return client builder\n */\n public static DistributedLogClientBuilder newBuilder() {\n return new DistributedLogClientBuilder();\n }\n\n public static DistributedLogClientBuilder newBuilder(DistributedLogClientBuilder builder) {\n DistributedLogClientBuilder newBuilder = new DistributedLogClientBuilder();\n newBuilder._name = builder._name;\n newBuilder._clientId = builder._clientId;\n newBuilder._clientBuilder = builder._clientBuilder;\n newBuilder._routingServiceBuilder = builder._routingServiceBuilder;\n newBuilder._statsReceiver = builder._statsReceiver;\n newBuilder._streamStatsReceiver = builder._streamStatsReceiver;\n newBuilder._enableRegionStats = builder._enableRegionStats;\n newBuilder._clientConfig = ClientConfig.newConfig(builder._clientConfig);\n return newBuilder;\n }\n\n // private constructor\n private DistributedLogClientBuilder() {}\n\n /**\n * Client Name.\n *\n * @param name\n * client name\n * @return client builder.\n */\n public DistributedLogClientBuilder name(String name) {\n DistributedLogClientBuilder newBuilder = newBuilder(this);\n newBuilder._name = name;\n return newBuilder;\n }\n\n /**\n * Client ID.\n *\n * @param clientId\n * client id\n * @return client builder.\n */\n public DistributedLogClientBuilder clientId(ClientId clientId) {\n DistributedLogClientBuilder newBuilder = newBuilder(this);\n newBuilder._clientId = clientId;\n return newBuilder;\n }\n\n /**\n * Serverset to access proxy services.\n *\n * @param serverSet\n * server set.\n * @return client builder.\n */\n public DistributedLogClientBuilder serverSet(ServerSet serverSet) {\n DistributedLogClientBuilder newBuilder = newBuilder(this);\n newBuilder._routingServiceBuilder = RoutingUtils.buildRoutingService(serverSet);\n newBuilder._enableRegionStats = false;\n return newBuilder;\n }\n\n /**\n * Server Sets to access proxy services. The local server set will be tried first,\n * then remotes.\n *\n * @param local local server set.\n * @param remotes remote server sets.\n * @return client builder.\n */\n public DistributedLogClientBuilder serverSets(ServerSet local, ServerSet...remotes) {\n DistributedLogClientBuilder newBuilder = newBuilder(this);\n RoutingService.Builder[] builders = new RoutingService.Builder[remotes.length + 1];\n builders[0] = RoutingUtils.buildRoutingService(local);\n for (int i = 1; i < builders.length; i++) {\n builders[i] = RoutingUtils.buildRoutingService(remotes[i-1]);\n }\n newBuilder._routingServiceBuilder = RegionsRoutingService.newBuilder()\n .resolver(_regionResolver)\n .routingServiceBuilders(builders);\n newBuilder._enableRegionStats = remotes.length > 0;\n return newBuilder;\n }\n\n /**\n * Name to access proxy services.\n *\n * @param finagleNameStr\n * finagle name string.\n * @return client builder.\n */\n public DistributedLogClientBuilder finagleNameStr(String finagleNameStr) {\n DistributedLogClientBuilder newBuilder = newBuilder(this);\n newBuilder._routingServiceBuilder = RoutingUtils.buildRoutingService(finagleNameStr);\n newBuilder._enableRegionStats = false;\n return newBuilder;\n }\n\n /**\n * Finagle name strs to access proxy services. The local finalge name str will be tried first,\n * then remotes.\n *\n * @param local local server set.\n * @param remotes remote server sets.\n * @return client builder.\n */\n public DistributedLogClientBuilder finagleNameStrs(String local, String...remotes) {\n DistributedLogClientBuilder newBuilder = newBuilder(this);\n RoutingService.Builder[] builders = new RoutingService.Builder[remotes.length + 1];\n builders[0] = RoutingUtils.buildRoutingService(local);\n for (int i = 1; i < builders.length; i++) {\n builders[i] = RoutingUtils.buildRoutingService(remotes[i - 1]);\n }\n newBuilder._routingServiceBuilder = RegionsRoutingService.newBuilder()\n .routingServiceBuilders(builders)\n .resolver(_regionResolver);\n newBuilder._enableRegionStats = remotes.length > 0;\n return newBuilder;\n }\n\n /**\n * URI to access proxy services. Assuming the write proxies are announced under `.write_proxy` of\n * the provided namespace uri.\n *

    \n * The builder will convert the dl uri (e.g. distributedlog://{zkserver}/path/to/namespace) to\n * zookeeper serverset based finagle name str (`zk!{zkserver}!/path/to/namespace/.write_proxy`)\n *\n * @param uri namespace uri to access the serverset of write proxies\n * @return distributedlog builder\n */\n public DistributedLogClientBuilder uri(URI uri) {\n DistributedLogClientBuilder newBuilder = newBuilder(this);\n String zkServers = uri.getAuthority().replace(\";\", \",\");\n String[] zkServerList = StringUtils.split(zkServers, ',');\n String finagleNameStr = String.format(\n \"zk!%s!%s/.write_proxy\",\n zkServerList[random.nextInt(zkServerList.length)], // zk server\n uri.getPath());\n newBuilder._routingServiceBuilder = RoutingUtils.buildRoutingService(finagleNameStr);\n newBuilder._enableRegionStats = false;\n return newBuilder;\n }\n\n /**\n * Address of write proxy to connect.\n *\n * @param address\n * write proxy address.\n * @return client builder.\n */\n public DistributedLogClientBuilder host(SocketAddress address) {\n DistributedLogClientBuilder newBuilder = newBuilder(this);\n newBuilder._routingServiceBuilder = RoutingUtils.buildRoutingService(address);\n newBuilder._enableRegionStats = false;\n return newBuilder;\n }\n\n private DistributedLogClientBuilder routingServiceBuilder(RoutingService.Builder builder) {\n DistributedLogClientBuilder newBuilder = newBuilder(this);\n newBuilder._routingServiceBuilder = builder;\n newBuilder._enableRegionStats = false;\n return newBuilder;\n }\n\n /**\n * Routing Service to access proxy services.\n *\n * @param routingService\n * routing service\n * @return client builder.\n */\n @VisibleForTesting\n public DistributedLogClientBuilder routingService(RoutingService routingService) {\n DistributedLogClientBuilder newBuilder = newBuilder(this);\n newBuilder._routingServiceBuilder = RoutingUtils.buildRoutingService(routingService);\n newBuilder._enableRegionStats = false;\n return newBuilder;\n }\n\n /**\n * Stats receiver to expose client stats.\n *\n * @param statsReceiver\n * stats receiver.\n * @return client builder.\n */\n public DistributedLogClientBuilder statsReceiver(StatsReceiver statsReceiver) {\n DistributedLogClientBuilder newBuilder = newBuilder(this);\n newBuilder._statsReceiver = statsReceiver;\n return newBuilder;\n }\n\n /**\n * Stream Stats Receiver to expose per stream stats.\n *\n * @param streamStatsReceiver\n * stream stats receiver\n * @return client builder.\n */\n public DistributedLogClientBuilder streamStatsReceiver(StatsReceiver streamStatsReceiver) {\n DistributedLogClientBuilder newBuilder = newBuilder(this);\n newBuilder._streamStatsReceiver = streamStatsReceiver;\n return newBuilder;\n }\n\n /**\n * Set underlying finagle client builder.\n *\n * @param builder\n * finagle client builder.\n * @return client builder.\n */\n public DistributedLogClientBuilder clientBuilder(ClientBuilder builder) {\n DistributedLogClientBuilder newBuilder = newBuilder(this);\n newBuilder._clientBuilder = builder;\n return newBuilder;\n }\n\n /**\n * Backoff time when redirecting to an already retried host.\n *\n * @param ms\n * backoff time.\n * @return client builder.\n */\n public DistributedLogClientBuilder redirectBackoffStartMs(int ms) {\n DistributedLogClientBuilder newBuilder = newBuilder(this);\n newBuilder._clientConfig.setRedirectBackoffStartMs(ms);\n return newBuilder;\n }\n\n /**\n * Max backoff time when redirecting to an already retried host.\n *\n * @param ms\n * backoff time.\n * @return client builder.\n */\n public DistributedLogClientBuilder redirectBackoffMaxMs(int ms) {\n DistributedLogClientBuilder newBuilder = newBuilder(this);\n newBuilder._clientConfig.setRedirectBackoffMaxMs(ms);\n return newBuilder;\n }\n\n /**\n * Max redirects that is allowed per request. If redirects are\n * exhausted, fail the request immediately.\n *\n * @param redirects\n * max redirects allowed before failing a request.\n * @return client builder.\n */\n public DistributedLogClientBuilder maxRedirects(int redirects) {\n DistributedLogClientBuilder newBuilder = newBuilder(this);\n newBuilder._clientConfig.setMaxRedirects(redirects);\n return newBuilder;\n }\n\n /**\n * Timeout per request in millis.\n *\n * @param timeoutMs\n * timeout per request in millis.\n * @return client builder.\n */\n public DistributedLogClientBuilder requestTimeoutMs(int timeoutMs) {\n DistributedLogClientBuilder newBuilder = newBuilder(this);\n newBuilder._clientConfig.setRequestTimeoutMs(timeoutMs);\n return newBuilder;\n }\n\n /**\n * Set thriftmux enabled.\n *\n * @param enabled\n * is thriftmux enabled\n * @return client builder.\n */\n public DistributedLogClientBuilder thriftmux(boolean enabled) {\n DistributedLogClientBuilder newBuilder = newBuilder(this);\n newBuilder._clientConfig.setThriftMux(enabled);\n return newBuilder;\n }\n\n /**\n * Set failfast stream exception handling enabled.\n *\n * @param enabled\n * is failfast exception handling enabled\n * @return client builder.\n */\n public DistributedLogClientBuilder streamFailfast(boolean enabled) {\n DistributedLogClientBuilder newBuilder = newBuilder(this);\n newBuilder._clientConfig.setStreamFailfast(enabled);\n return newBuilder;\n }\n\n /**\n * Set the regex to match stream names that the client cares about.\n *\n * @param nameRegex\n * stream name regex\n * @return client builder\n */\n public DistributedLogClientBuilder streamNameRegex(String nameRegex) {\n DistributedLogClientBuilder newBuilder = newBuilder(this);\n newBuilder._clientConfig.setStreamNameRegex(nameRegex);\n return newBuilder;\n }\n\n /**\n * Whether to use the new handshake endpoint to exchange ownership cache. Enable this\n * when the servers are updated to support handshaking with client info.\n *\n * @param enabled\n * new handshake endpoint is enabled.\n * @return client builder.\n */\n public DistributedLogClientBuilder handshakeWithClientInfo(boolean enabled) {\n DistributedLogClientBuilder newBuilder = newBuilder(this);\n newBuilder._clientConfig.setHandshakeWithClientInfo(enabled);", "answers": [" return newBuilder;"], "length": 1228, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "ec74da9f-e270-4199-aab8-1aa97e4a8719", "reasoning": "The method handshakeWithClientInfo follows the same pattern as previous builder setters: create a newBuilder, set a config field, then return the newBuilder and close the method. The code currently ends after setting the config, so the next line should be the return statement.", "reasoning_model_answer": "return newBuilder;", "assistant_with_reasoning": "\nThe method handshakeWithClientInfo follows the same pattern as previous builder setters: create a newBuilder, set a config field, then return the newBuilder and close the method. The code currently ends after setting the config, so the next line should be the return statement.\n\nreturn newBuilder;", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 2.548, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 14163, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "return newBuilder;", "score": 0.82, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/*\n * Copyright (c) Citrix Systems, Inc.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1) Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *\n * 2) Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following\n * disclaimer in the documentation and/or other materials\n * provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\n * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\n * OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n\nusing System;\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Globalization;\nusing Newtonsoft.Json;\n\n\nnamespace XenAPI\n{\n ///

    \n /// A placeholder for a binary blob\n /// First published in XenServer 5.0.\n /// \n public partial class Blob : XenObject\n {\n #region Constructors\n\n public Blob()\n {\n }\n\n public Blob(string uuid,\n string name_label,\n string name_description,\n long size,\n bool pubblic,\n DateTime last_updated,\n string mime_type)\n {\n this.uuid = uuid;\n this.name_label = name_label;\n this.name_description = name_description;\n this.size = size;\n this.pubblic = pubblic;\n this.last_updated = last_updated;\n this.mime_type = mime_type;\n }\n\n /// \n /// Creates a new Blob from a Hashtable.\n /// Note that the fields not contained in the Hashtable\n /// will be created with their default values.\n /// \n /// \n public Blob(Hashtable table)\n : this()\n {\n UpdateFrom(table);\n }\n\n /// \n /// Creates a new Blob from a Proxy_Blob.\n /// \n /// \n public Blob(Proxy_Blob proxy)\n {\n UpdateFrom(proxy);\n }\n\n #endregion\n\n /// \n /// Updates each field of this instance with the value of\n /// the corresponding field of a given Blob.\n /// \n public override void UpdateFrom(Blob update)\n {\n uuid = update.uuid;\n name_label = update.name_label;\n name_description = update.name_description;\n size = update.size;\n pubblic = update.pubblic;\n last_updated = update.last_updated;\n mime_type = update.mime_type;\n }\n\n internal void UpdateFrom(Proxy_Blob proxy)\n {\n uuid = proxy.uuid == null ? null : proxy.uuid;\n name_label = proxy.name_label == null ? null : proxy.name_label;\n name_description = proxy.name_description == null ? null : proxy.name_description;\n size = proxy.size == null ? 0 : long.Parse(proxy.size);\n pubblic = (bool)proxy.pubblic;\n last_updated = proxy.last_updated;\n mime_type = proxy.mime_type == null ? null : proxy.mime_type;\n }\n\n public Proxy_Blob ToProxy()\n {\n Proxy_Blob result_ = new Proxy_Blob();\n result_.uuid = uuid ?? \"\";\n result_.name_label = name_label ?? \"\";\n result_.name_description = name_description ?? \"\";\n result_.size = size.ToString();\n result_.pubblic = pubblic;\n result_.last_updated = last_updated;\n result_.mime_type = mime_type ?? \"\";\n return result_;\n }\n\n /// \n /// Given a Hashtable with field-value pairs, it updates the fields of this Blob\n /// with the values listed in the Hashtable. Note that only the fields contained\n /// in the Hashtable will be updated and the rest will remain the same.\n /// \n /// \n public void UpdateFrom(Hashtable table)\n {\n if (table.ContainsKey(\"uuid\"))\n uuid = Marshalling.ParseString(table, \"uuid\");\n if (table.ContainsKey(\"name_label\"))\n name_label = Marshalling.ParseString(table, \"name_label\");\n if (table.ContainsKey(\"name_description\"))\n name_description = Marshalling.ParseString(table, \"name_description\");\n if (table.ContainsKey(\"size\"))\n size = Marshalling.ParseLong(table, \"size\");\n if (table.ContainsKey(\"pubblic\"))\n pubblic = Marshalling.ParseBool(table, \"pubblic\");\n if (table.ContainsKey(\"last_updated\"))\n last_updated = Marshalling.ParseDateTime(table, \"last_updated\");\n if (table.ContainsKey(\"mime_type\"))\n mime_type = Marshalling.ParseString(table, \"mime_type\");\n }\n\n public bool DeepEquals(Blob other)\n {\n if (ReferenceEquals(null, other))\n return false;\n if (ReferenceEquals(this, other))\n return true;\n\n return Helper.AreEqual2(this._uuid, other._uuid) &&\n Helper.AreEqual2(this._name_label, other._name_label) &&\n Helper.AreEqual2(this._name_description, other._name_description) &&\n Helper.AreEqual2(this._size, other._size) &&\n Helper.AreEqual2(this._pubblic, other._pubblic) &&\n Helper.AreEqual2(this._last_updated, other._last_updated) &&\n Helper.AreEqual2(this._mime_type, other._mime_type);\n }\n\n internal static List ProxyArrayToObjectList(Proxy_Blob[] input)\n {\n var result = new List();\n foreach (var item in input)\n result.Add(new Blob(item));\n\n return result;\n }\n\n public override string SaveChanges(Session session, string opaqueRef, Blob server)\n {\n if (opaqueRef == null)\n {\n System.Diagnostics.Debug.Assert(false, \"Cannot create instances of this type on the server\");\n return \"\";\n }\n else\n {\n if (!Helper.AreEqual2(_name_label, server._name_label))\n {\n Blob.set_name_label(session, opaqueRef, _name_label);\n }\n if (!Helper.AreEqual2(_name_description, server._name_description))\n {\n Blob.set_name_description(session, opaqueRef, _name_description);\n }\n\n return null;\n }\n }\n /// \n /// Get a record containing the current state of the given blob.\n /// First published in XenServer 5.0.\n /// \n /// The session\n /// The opaque_ref of the given blob\n public static Blob get_record(Session session, string _blob)\n {\n if (session.JsonRpcClient != null)\n return session.JsonRpcClient.blob_get_record(session.opaque_ref, _blob);\n else\n return new Blob(session.XmlRpcProxy.blob_get_record(session.opaque_ref, _blob ?? \"\").parse());\n }\n\n /// \n /// Get a reference to the blob instance with the specified UUID.\n /// First published in XenServer 5.0.\n /// \n /// The session\n /// UUID of object to return\n public static XenRef get_by_uuid(Session session, string _uuid)\n {\n if (session.JsonRpcClient != null)\n return session.JsonRpcClient.blob_get_by_uuid(session.opaque_ref, _uuid);\n else\n return XenRef.Create(session.XmlRpcProxy.blob_get_by_uuid(session.opaque_ref, _uuid ?? \"\").parse());\n }\n\n /// \n /// Get all the blob instances with the given label.\n /// First published in XenServer 5.0.\n /// \n /// The session\n /// label of object to return\n public static List> get_by_name_label(Session session, string _label)\n {\n if (session.JsonRpcClient != null)\n return session.JsonRpcClient.blob_get_by_name_label(session.opaque_ref, _label);\n else\n return XenRef.Create(session.XmlRpcProxy.blob_get_by_name_label(session.opaque_ref, _label ?? \"\").parse());\n }\n\n /// \n /// Get the uuid field of the given blob.\n /// First published in XenServer 5.0.\n /// \n /// The session\n /// The opaque_ref of the given blob\n public static string get_uuid(Session session, string _blob)\n {\n if (session.JsonRpcClient != null)\n return session.JsonRpcClient.blob_get_uuid(session.opaque_ref, _blob);\n else\n return session.XmlRpcProxy.blob_get_uuid(session.opaque_ref, _blob ?? \"\").parse();\n }\n\n /// \n /// Get the name/label field of the given blob.\n /// First published in XenServer 5.0.\n /// \n /// The session\n /// The opaque_ref of the given blob\n public static string get_name_label(Session session, string _blob)\n {\n if (session.JsonRpcClient != null)\n return session.JsonRpcClient.blob_get_name_label(session.opaque_ref, _blob);\n else\n return session.XmlRpcProxy.blob_get_name_label(session.opaque_ref, _blob ?? \"\").parse();\n }\n\n /// \n /// Get the name/description field of the given blob.\n /// First published in XenServer 5.0.\n /// \n /// The session\n /// The opaque_ref of the given blob\n public static string get_name_description(Session session, string _blob)\n {\n if (session.JsonRpcClient != null)", "answers": [" return session.JsonRpcClient.blob_get_name_description(session.opaque_ref, _blob);"], "length": 1041, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "5ba89468-7ed9-4dfa-8834-e9a343d3faf6", "reasoning": "The method get_name_description follows the same pattern as the previous getter methods. After checking if JsonRpcClient is not null, the next line should return the result of the corresponding JSON RPC call, which is session.JsonRpcClient.blob_get_name_description(session.opaque_ref, _blob);", "reasoning_model_answer": "return session.JsonRpcClient.blob_get_name_description(session.opaque_ref, _blob);", "assistant_with_reasoning": "\nThe method get_name_description follows the same pattern as the previous getter methods. After checking if JsonRpcClient is not null, the next line should return the result of the corresponding JSON RPC call, which is session.JsonRpcClient.blob_get_name_description(session.opaque_ref, _blob);\n\nreturn session.JsonRpcClient.blob_get_name_description(session.opaque_ref, _blob);", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.41, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 11209, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "return session.JsonRpcClient.blob_get_name_description(session.opaque_ref, _blob);", "score": 0.91, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "// ReSharper disable RedundantTypeArgumentsOfMethod\n#pragma warning disable IDE0001\nnamespace Gu.Inject\n{\n using System;\n\n /// \n /// Rebind extension methods for .\n /// \n public static class RebindExtensions\n {\n /// \n /// Check if there is a binding for .\n /// \n /// The .\n /// The type to resolve.\n /// True if there is a binding.\n public static bool HasBinding(this Kernel kernel, Type type)\n {\n if (kernel is null)\n {\n throw new ArgumentNullException(nameof(kernel));\n }\n\n return kernel.HasBinding(type);\n }\n\n /// \n /// Provide an override to the automatic mapping.\n /// \n /// The .\n /// The type to map.\n /// The mapped type.\n /// The same instance.\n public static Kernel Rebind(this Kernel kernel, Type from, Type to)\n {\n if (kernel is null)\n {\n throw new ArgumentNullException(nameof(kernel));\n }\n\n if (from is null)\n {\n throw new ArgumentNullException(nameof(from));\n }\n\n if (to is null)\n {\n throw new ArgumentNullException(nameof(to));\n }\n\n kernel.Rebind(from, Binding.Map(to), requireExistingBinding: true);\n return kernel;\n }\n\n /// \n /// Use this binding when there are circular dependencies.\n /// This binds an FormatterServices.GetUninitializedObject() that is used when creating the graph.\n /// \n /// The type to map.\n /// The .\n /// The same instance.\n public static Kernel RebindUninitialized(this Kernel kernel)\n where T : class\n {\n if (kernel is null)\n {\n throw new ArgumentNullException(nameof(kernel));\n }\n\n kernel.Rebind(typeof(T), Binding.Uninitialized(), requireExistingBinding: true);\n return kernel;\n }\n\n /// \n /// Provide an override to the automatic mapping.\n /// \n /// The type to map.\n /// The mapped type.\n /// The .\n /// The same instance.\n public static Kernel Rebind(this Kernel kernel)\n where TConcrete : TInterface\n {\n if (kernel is null)\n {\n throw new ArgumentNullException(nameof(kernel));\n }\n\n kernel.Rebind(typeof(TInterface), Binding.Map(), requireExistingBinding: true);\n return kernel;\n }\n\n /// \n /// Provide an override to the automatic mapping.\n /// \n /// The first type to map.\n /// The second type to map.\n /// The mapped type.\n /// The .\n /// The same instance.\n public static Kernel Rebind(this Kernel kernel)\n where TConcrete : TInterface1, TInterface2\n {\n if (kernel is null)\n {\n throw new ArgumentNullException(nameof(kernel));\n }\n\n kernel.Rebind(typeof(TInterface1), Binding.Map(), requireExistingBinding: true);\n kernel.Rebind(typeof(TInterface2), Binding.Map(), requireExistingBinding: true);\n return kernel;\n }\n\n /// \n /// Provide an override to the automatic mapping.\n /// \n /// The first type to map.\n /// The second type to map.\n /// The third type to map.\n /// The mapped type.\n /// The .\n /// The same instance.\n public static Kernel Rebind(this Kernel kernel)\n where TConcrete : TInterface1, TInterface2, TInterface3\n {\n if (kernel is null)\n {\n throw new ArgumentNullException(nameof(kernel));\n }\n\n kernel.Rebind(typeof(TInterface1), Binding.Map(), requireExistingBinding: true);\n kernel.Rebind(typeof(TInterface2), Binding.Map(), requireExistingBinding: true);\n kernel.Rebind(typeof(TInterface3), Binding.Map(), requireExistingBinding: true);\n return kernel;\n }\n\n /// \n /// Provide an override for the automatic mapping.\n /// If the implements IDisposable, the responsibility to dispose it remains the caller's, disposing the kernel doesn't do that.\n /// \n /// The mapped type.\n /// The .\n /// The instance to bind.\n /// The same instance.\n public static Kernel Rebind(this Kernel kernel, T instance)\n {\n if (kernel is null)\n {\n throw new ArgumentNullException(nameof(kernel));\n }\n\n if (instance is null)\n {\n throw new ArgumentNullException(nameof(instance));\n }\n\n if (typeof(T) == instance.GetType())\n {\n kernel.Rebind(typeof(T), Binding.Instance(instance), requireExistingBinding: true);\n }\n else\n {\n kernel.Rebind(typeof(T), Binding.Mapped(instance), requireExistingBinding: true);\n kernel.Rebind(instance.GetType(), Binding.Instance(instance), requireExistingBinding: false);\n }\n\n return kernel;\n }\n\n /// \n /// Provide an override for the automatic mapping.\n /// If the implements IDisposable, the responsibility to dispose it remains the caller's, disposing the kernel doesn't do that.\n /// \n /// The type to map.\n /// The mapped type.\n /// The .\n /// The instance to bind.\n /// The same instance.\n public static Kernel Rebind(this Kernel kernel, TConcrete instance)\n where TConcrete : TInterface\n {\n if (kernel is null)\n {\n throw new ArgumentNullException(nameof(kernel));\n }\n\n if (instance is null)\n {\n throw new ArgumentNullException(nameof(instance));\n }\n\n kernel.Rebind(instance);\n kernel.Rebind(typeof(TInterface), Binding.Mapped(instance), requireExistingBinding: true);\n return kernel;\n }\n\n /// \n /// Provide an override for the automatic mapping.\n /// If the implements IDisposable, the responsibility to dispose it remains the caller's, disposing the kernel doesn't do that.\n /// \n /// The first type to map.\n /// The second type to map.\n /// The mapped type.\n /// The .\n /// The instance to bind.\n /// The same instance.\n public static Kernel Rebind(this Kernel kernel, TConcrete instance)\n where TConcrete : TInterface1, TInterface2\n {\n if (kernel is null)\n {\n throw new ArgumentNullException(nameof(kernel));\n }\n\n if (instance is null)\n {\n throw new ArgumentNullException(nameof(instance));\n }\n\n kernel.Rebind(instance);\n kernel.Rebind(typeof(TInterface1), Binding.Mapped(instance), requireExistingBinding: true);\n kernel.Rebind(typeof(TInterface2), Binding.Mapped(instance), requireExistingBinding: true);\n return kernel;\n }\n\n /// \n /// Provide an override for the automatic mapping.\n /// If the implements IDisposable, the responsibility to dispose it remains the caller's, disposing the kernel doesn't do that.\n /// \n /// The first type to map.\n /// The second type to map.\n /// The third type to map.\n /// The mapped type.\n /// The .\n /// The instance to bind.\n /// The same instance.\n public static Kernel Rebind(this Kernel kernel, TConcrete instance)\n where TConcrete : TInterface1, TInterface2, TInterface3\n {\n if (kernel is null)\n {\n throw new ArgumentNullException(nameof(kernel));\n }\n\n if (instance is null)\n {\n throw new ArgumentNullException(nameof(instance));\n }\n\n kernel.Rebind(instance);\n kernel.Rebind(typeof(TInterface1), Binding.Mapped(instance), requireExistingBinding: true);\n kernel.Rebind(typeof(TInterface2), Binding.Mapped(instance), requireExistingBinding: true);\n kernel.Rebind(typeof(TInterface3), Binding.Mapped(instance), requireExistingBinding: true);\n return kernel;\n }\n\n /// \n /// Provide an override for the automatic mapping.\n /// The instance is created lazily by and is cached for subsequent calls to .Get().\n /// The instance is owned by the kernel, that is, calling .Dispose() on the kernel disposes the instance, if its type implements IDisposable.\n /// \n /// The mapped type.\n /// The .\n /// The factory function used to create the instance.\n /// The same instance.\n public static Kernel Rebind(this Kernel kernel, Func create)\n {\n if (kernel is null)\n {\n throw new ArgumentNullException(nameof(kernel));\n }\n\n if (create is null)\n {\n throw new ArgumentNullException(nameof(create));\n }\n\n kernel.Rebind(typeof(T), Binding.Func(create), requireExistingBinding: true);\n return kernel;\n }\n\n /// \n /// Provide an override for the automatic mapping.\n /// The instance is created lazily by and is cached for subsequent calls to .Get().\n /// \n /// The type to map.\n /// The mapped type.\n /// The .\n /// The factory function used to create the instance.\n /// The same instance.\n public static Kernel Rebind(this Kernel kernel, Func create)\n where TConcrete : TInterface\n {\n if (kernel is null)\n {\n throw new ArgumentNullException(nameof(kernel));\n }\n\n if (create is null)\n {\n throw new ArgumentNullException(nameof(create));\n }\n\n kernel.Rebind(typeof(TInterface), Binding.Map(), requireExistingBinding: true);\n kernel.Rebind(typeof(TConcrete), Binding.Func(create), requireExistingBinding: true);\n return kernel;\n }\n\n /// \n /// Provide an override for the automatic mapping.\n /// The instance is created lazily by and is cached for subsequent calls to .Get().\n /// \n /// The first type to map.\n /// The second type to map.\n /// The mapped type.\n /// The .\n /// The factory function used to create the instance.\n /// The same instance.\n public static Kernel Rebind(this Kernel kernel, Func create)\n where TConcrete : TInterface1, TInterface2\n {\n if (kernel is null)\n {\n throw new ArgumentNullException(nameof(kernel));\n }\n\n if (create is null)\n {\n throw new ArgumentNullException(nameof(create));\n }\n\n kernel.Rebind(typeof(TInterface1), Binding.Map(), requireExistingBinding: true);\n kernel.Rebind(typeof(TInterface2), Binding.Map(), requireExistingBinding: true);\n kernel.Rebind(typeof(TConcrete), Binding.Func(create), requireExistingBinding: true);\n return kernel;\n }\n\n /// \n /// Provide an override for the automatic mapping.\n /// The instance is created lazily by and is cached for subsequent calls to .Get().\n /// \n /// The first type to map.\n /// The second type to map.\n /// The third type to map.\n /// The mapped type.\n /// The .\n /// The factory function used to create the instance.\n /// The same instance.\n public static Kernel Rebind(this Kernel kernel, Func create)\n where TConcrete : TInterface1, TInterface2, TInterface3\n {\n if (kernel is null)\n {\n throw new ArgumentNullException(nameof(kernel));\n }\n\n if (create is null)\n {", "answers": [" throw new ArgumentNullException(nameof(create));"], "length": 1328, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "5eb52316-06dd-4fa5-bfa8-fa3cde8def0b", "reasoning": "The method is the overload for three interfaces. Following the pattern of the previous overloads, after checking that 'create' is not null, the code should throw an ArgumentNullException if it is null. The next line therefore is the throw statement for the null check.", "reasoning_model_answer": "throw new ArgumentNullException(nameof(create));", "assistant_with_reasoning": "\nThe method is the overload for three interfaces. Following the pattern of the previous overloads, after checking that 'create' is not null, the code should throw an ArgumentNullException if it is null. The next line therefore is the throw statement for the null check.\n\nthrow new ArgumentNullException(nameof(create));", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.432, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 15873, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "throw new ArgumentNullException(nameof(create));", "score": 0.86, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "#\n# Copyright (c) 2012 Patrice Munger\n# This file is part of pynetdicom, released under a modified MIT license.\n# See the file license.txt included with this distribution, also\n# available at http://pynetdicom.googlecode.com\n#\nimport dsutils\nfrom DIMSEparameters import *\nimport DIMSEprovider\nimport ACSEprovider\nimport time\nimport logging\n\nlogger = logging.getLogger(__name__)\n\n\nclass Status(object):\n\n def __init__(self, Type, Description, CodeRange):\n self.Type = Type\n self.Description = Description\n self.CodeRange = CodeRange\n\n def __int__(self):\n return self.CodeRange[0]\n\n def __repr__(self):\n return self.Type + ' ' + self.Description\n\n\nclass ServiceClass(object):\n\n def __init__(self):\n pass\n\n def Code2Status(self, code):\n for dd in dir(self):\n getattr(self, dd).__class__\n obj = getattr(self, dd)\n if obj.__class__ == Status:\n if code in obj.CodeRange:\n return obj\n # unknown status ...\n return None\n\n\nclass VerificationServiceClass(ServiceClass):\n\n Success = Status(\n 'Success',\n '',\n xrange(0x0000, 0x0000 + 1)\n )\n\n def __init__(self):\n ServiceClass.__init__(self)\n\n def SCU(self, id):\n cecho = C_ECHO_ServiceParameters()\n cecho.MessageID = id\n cecho.AffectedSOPClassUID = self.UID\n\n self.DIMSE.Send(cecho, self.pcid, self.maxpdulength)\n\n ans, id = self.DIMSE.Receive(Wait=True)\n return self.Code2Status(ans.Status)\n\n def SCP(self, msg):\n rsp = C_ECHO_ServiceParameters()\n rsp.MessageIDBeingRespondedTo = msg.MessageID.value\n rsp.Status = self.Success\n\n # send response\n try:\n self.AE.OnReceiveEcho(self)\n except:\n logger.error(\"There was an exception on OnReceiveEcho callback\")\n self.DIMSE.Send(rsp, self.pcid, self.ACSE.MaxPDULength)\n\n\nclass StorageServiceClass(ServiceClass):\n\n OutOfResources = Status(\n 'Failure',\n 'Refused: Out of resources',\n xrange(0xA700, 0xA7FF + 1)\n )\n DataSetDoesNotMatchSOPClassFailure = Status(\n 'Failure',\n 'Error: Data Set does not match SOP Class',\n xrange(0xA900, 0xA9FF + 1)\n )\n CannotUnderstand = Status(\n 'Failure',\n 'Error: Cannot understand',\n xrange(0xC000, 0xCFFF + 1)\n )\n CoercionOfDataElements = Status(\n 'Warning',\n 'Coercion of Data Elements',\n xrange(0xB000, 0xB000 + 1)\n )\n DataSetDoesNotMatchSOPClassWarning = Status(\n 'Warning',\n 'Data Set does not match SOP Class',\n xrange(0xB007, 0xB007 + 1)\n )\n ElementDiscarted = Status(\n 'Warning',\n 'Element Discarted',\n xrange(0xB006, 0xB006 + 1)\n )\n Success = Status(\n 'Success',\n '',\n xrange(0x0000, 0x0000 + 1)\n )\n\n def SCU(self, dataset, msgid):\n # build C-STORE primitive\n csto = C_STORE_ServiceParameters()\n csto.MessageID = msgid\n csto.AffectedSOPClassUID = dataset.SOPClassUID\n csto.AffectedSOPInstanceUID = dataset.SOPInstanceUID\n csto.Priority = 0x0002\n csto.DataSet = dsutils.encode(dataset,\n self.transfersyntax.is_implicit_VR,\n self.transfersyntax.is_little_endian)\n # send cstore request\n self.DIMSE.Send(csto, self.pcid, self.maxpdulength)\n\n # wait for c-store response\n ans, id = self.DIMSE.Receive(Wait=True)\n return self.Code2Status(ans.Status.value)\n\n def __init__(self):\n ServiceClass.__init__(self)\n\n def SCP(self, msg):\n status = None\n try:\n DS = dsutils.decode(msg.DataSet,\n self.transfersyntax.is_implicit_VR,\n self.transfersyntax.is_little_endian)\n except:\n status = self.CannotUnderstand\n # make response\n rsp = C_STORE_ServiceParameters()\n rsp.MessageIDBeingRespondedTo = msg.MessageID\n rsp.AffectedSOPInstanceUID = msg.AffectedSOPInstanceUID\n rsp.AffectedSOPClassUID = msg.AffectedSOPClassUID\n # callback\n if not status:\n try:\n status = self.AE.OnReceiveStore(self, DS)\n except:\n logger.error(\n \"There was an exception in OnReceiveStore callback\")\n status = self.CannotUnderstand\n raise\n rsp.Status = int(status)\n self.DIMSE.Send(rsp, self.pcid, self.ACSE.MaxPDULength)\n\n\nclass QueryRetrieveServiceClass(ServiceClass):\n pass\n\n\nclass QueryRetrieveFindSOPClass(QueryRetrieveServiceClass):\n OutOfResources = Status(\n 'Failure',\n 'Refused: Out of resources',\n xrange(0xA700, 0xA700 + 1)\n )\n IdentifierDoesNotMatchSOPClass = Status(\n 'Failure',\n 'Identifier does not match SOP Class',\n xrange(0xA900, 0xA900 + 1)\n )\n UnableToProcess = Status(\n 'Failure',\n 'Unable to process',\n xrange(0xC000, 0xCFFF + 1)\n )\n MatchingTerminatedDueToCancelRequest = Status(\n 'Cancel',\n 'Matching terminated due to Cancel request',\n xrange(0xFE00, 0xFE00 + 1)\n )\n Success = Status(\n 'Success',\n 'Matching is complete - No final Identifier is supplied',\n xrange(0x0000, 0x0000 + 1)\n )\n Pending = Status(\n 'Pending',\n 'Matches are continuing - Current Match is supplied \\\n and any Optional Keys were supported in the same manner as '\n 'Required Keys',\n xrange(0xFF00, 0xFF00 + 1)\n )\n PendingWarning = Status(\n 'Pending',\n 'Matches are continuing - Warning that one or more Optional\\\n Keys were not supported for existence and/or matching for '\n 'this identifier',\n xrange(0xFF01, 0xFF01 + 1)\n )\n\n def SCU(self, ds, msgid):\n # build C-FIND primitive\n cfind = C_FIND_ServiceParameters()\n cfind.MessageID = msgid\n cfind.AffectedSOPClassUID = self.UID\n cfind.Priority = 0x0002\n cfind.Identifier = dsutils.encode(ds,\n self.transfersyntax.is_implicit_VR,\n self.transfersyntax.is_little_endian)\n\n # send c-find request\n self.DIMSE.Send(cfind, self.pcid, self.maxpdulength)\n while 1:\n time.sleep(0.001)\n # wait for c-find responses\n ans, id = self.DIMSE.Receive(Wait=False)\n if not ans:\n continue\n d = dsutils.decode(\n ans.Identifier, self.transfersyntax.is_implicit_VR,\n self.transfersyntax.is_little_endian)\n try:\n status = self.Code2Status(ans.Status.value).Type\n except:\n status = None\n if status != 'Pending':\n break\n yield status, d\n yield status, d\n\n def SCP(self, msg):\n ds = dsutils.decode(msg.Identifier, self.transfersyntax.is_implicit_VR,\n self.transfersyntax.is_little_endian)\n\n # make response\n rsp = C_FIND_ServiceParameters()\n rsp.MessageIDBeingRespondedTo = msg.MessageID\n rsp.AffectedSOPClassUID = msg.AffectedSOPClassUID\n\n gen = self.AE.OnReceiveFind(self, ds)\n try:\n while 1:\n time.sleep(0.001)\n IdentifierDS, status = gen.next()\n rsp.Status = int(status)\n rsp.Identifier = dsutils.encode(\n IdentifierDS,\n self.transfersyntax.is_implicit_VR,\n self.transfersyntax.is_little_endian)\n # send response\n self.DIMSE.Send(rsp, self.pcid, self.ACSE.MaxPDULength)\n except StopIteration:\n # send final response\n rsp = C_FIND_ServiceParameters()\n rsp.MessageIDBeingRespondedTo = msg.MessageID\n rsp.AffectedSOPClassUID = msg.AffectedSOPClassUID\n rsp.Status = int(self.Success)\n self.DIMSE.Send(rsp, self.pcid, self.ACSE.MaxPDULength)\n\n\nclass QueryRetrieveGetSOPClass(QueryRetrieveServiceClass):\n\n OutOfResourcesNumberOfMatches = Status(\n 'Failure',\n 'Refused: Out of resources - Unable to calcultate number of matches',\n xrange(0xA701, 0xA701 + 1)\n )\n\n OutOfResourcesUnableToPerform = Status(\n 'Failure',\n 'Refused: Out of resources - Unable to perform sub-operations',\n xrange(0xA702, 0xA702 + 1)\n )\n\n IdentifierDoesNotMatchSOPClass = Status(\n 'Failure',\n 'Identifier does not match SOP Class',\n xrange(0xA900, 0xA900 + 1)\n )\n UnableToProcess = Status(\n 'Failure',\n 'Unable to process',\n xrange(0xC000, 0xCFFF + 1)\n )\n Cancel = Status(\n 'Cancel',\n 'Sub-operations terminated due to Cancel indication',\n xrange(0xFE00, 0xFE00 + 1)\n )\n Warning = Status(\n 'Warning',\n 'Sub-operations Complete - One or more Failures or Warnings',\n xrange(0xB000, 0xB000 + 1)\n )\n Success = Status(\n 'Success',\n 'Sub-operations Complete - No Failure or Warnings',\n xrange(0x0000, 0x0000 + 1)\n )\n Pending = Status(\n 'Pending',\n 'Sub-operations are continuing',\n xrange(0xFF00, 0xFF00 + 1)\n )\n CannotUnderstand = Status(\n 'Failure',\n 'Error: Cannot understand',\n xrange(0xC000, 0xCFFF + 1)\n )\n\n def SCP(self, msg):\n ds = dsutils.decode(msg.Identifier, self.transfersyntax.is_implicit_VR,\n self.transfersyntax.is_little_endian)\n\n # make response\n rsp = C_GET_ServiceParameters()\n rsp.MessageIDBeingRespondedTo = msg.MessageID.value\n rsp.AffectedSOPClassUID = msg.AffectedSOPClassUID.value\n rsp.Status = int(self.Pending)\n\n rsp.NumberOfRemainingSubOperations = 0\n rsp.NumberOfCompletedSubOperations = 0\n rsp.NumberOfFailedSubOperations = 0\n rsp.NumberOfWarningSubOperations = 0\n\n self.DIMSE.Send(rsp, self.pcid, self.maxpdulength)\n\n gen = self.AE.OnReceiveGet(self, ds)\n # # build C-STORE primitive\n csto = C_STORE_ServiceParameters()\n csto.MessageID = 0\n for ds in gen:\n csto.AffectedSOPClassUID = ds.SOPClassUID\n csto.AffectedSOPInstanceUID = ds.SOPInstanceUID\n csto.Priority = 0x0002\n csto.DataSet = dsutils.encode(ds,\n self.transfersyntax.is_implicit_VR,\n self.transfersyntax.is_little_endian)\n # send cstore request\n self.DIMSE.Send(csto, self.pcid, self.maxpdulength)\n\n # wait for c-store response\n ans, id = self.DIMSE.Receive(Wait=True)\n # TODO: Handle the answers coming back\n if self.Code2Status(ans.Status.value).Type != 'Success':\n pass\n\n # TODO: Set various values on the rsp here\n rsp.Status = int(self.Success)\n self.DIMSE.Send(rsp, self.pcid, self.maxpdulength)\n\n\n def SCU(self, ds, msgid):\n # build C-GET primitive\n cget = C_GET_ServiceParameters()\n cget.MessageID = msgid\n cget.AffectedSOPClassUID = self.UID\n cget.Priority = 0x0002\n cget.Identifier = dsutils.encode(ds,\n self.transfersyntax.is_implicit_VR,\n self.transfersyntax.is_little_endian)\n\n # send c-get primitive\n self.DIMSE.Send(cget, self.pcid, self.maxpdulength)\n\n while 1:\n # receive c-store\n msg, id = self.DIMSE.Receive(Wait=True)\n if msg.__class__ == C_GET_ServiceParameters:\n if self.Code2Status(msg.Status.value).Type == 'Pending':\n # pending. intermediate C-GET response\n pass\n else:\n # last answer\n break\n elif msg.__class__ == C_STORE_ServiceParameters:\n # send c-store response\n rsp = C_STORE_ServiceParameters()\n rsp.MessageIDBeingRespondedTo = msg.MessageID\n rsp.AffectedSOPInstanceUID = msg.AffectedSOPInstanceUID\n rsp.AffectedSOPClassUID = msg.AffectedSOPClassUID\n\n try:\n d = dsutils.decode(\n msg.DataSet, self.transfersyntax.is_implicit_VR,\n self.transfersyntax.is_little_endian)\n SOPClass = UID2SOPClass(d.SOPClassUID)\n status = self.AE.OnReceiveStore(SOPClass, d)\n except:\n # cannot understand\n status = self.CannotUnderstand\n\n rsp.Status = int(status)\n\n self.DIMSE.Send(rsp, id, self.maxpdulength)\n\n\nclass QueryRetrieveMoveSOPClass(QueryRetrieveServiceClass):\n\n OutOfResourcesNumberOfMatches = Status(\n 'Failure',\n 'Refused: Out of resources - Unable to calcultate number of matches',\n xrange(0xA701, 0xA701 + 1)\n )\n\n OutOfResourcesUnableToPerform = Status(\n 'Failure',\n 'Refused: Out of resources - Unable to perform sub-operations',\n xrange(0xA702, 0xA702 + 1)\n )\n MoveDestinationUnknown = Status(\n 'Failure',\n 'Refused: Move destination unknown',\n xrange(0xA801, 0xA801 + 1)\n )\n IdentifierDoesNotMatchSOPClass = Status(\n 'Failure',\n 'Identifier does not match SOP Class',\n xrange(0xA900, 0xA900 + 1)\n )\n UnableToProcess = Status(\n 'Failure',\n 'Unable to process',\n xrange(0xC000, 0xCFFF + 1)\n )", "answers": [" Cancel = Status("], "length": 1110, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "6a6e96f6-1334-4a23-981d-de313c2691d1", "reasoning": "The class QueryRetrieveMoveSOPClass has just defined several Status objects, ending with UnableToProcess. Following the pattern in other SOP classes, the next status to define is Cancel, starting with the line ' Cancel = Status('. Therefore the next line of code is that line.", "reasoning_model_answer": "Cancel = Status(", "assistant_with_reasoning": "\nThe class QueryRetrieveMoveSOPClass has just defined several Status objects, ending with UnableToProcess. Following the pattern in other SOP classes, the next status to define is Cancel, starting with the line ' Cancel = Status('. Therefore the next line of code is that line.\n\nCancel = Status(", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.76, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 14003, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "Cancel = Status(", "score": 0.89, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "// Copyright (c) The Avalonia Project. All rights reserved.\n// Licensed under the MIT license. See licence.md file in the project root for full license information.\n\nusing Avalonia.Controls;\nusing Xunit;\n\nnamespace Avalonia.Input.UnitTests\n{\n using Controls = Controls.Controls;\n\n public class KeyboardNavigationTests_Arrows\n {\n [Fact]\n public void Down_Continue_Returns_Down_Control_In_Container()\n {\n Button current;\n Button next;\n\n var top = new StackPanel\n {\n Children = new Controls\n {\n new StackPanel\n {\n [KeyboardNavigation.DirectionalNavigationProperty] = KeyboardNavigationMode.Continue,\n Children = new Controls\n {\n new Button { Name = \"Button1\" },\n (current = new Button { Name = \"Button2\" }),\n (next = new Button { Name = \"Button3\" }),\n }\n },\n new StackPanel\n {\n [KeyboardNavigation.DirectionalNavigationProperty] = KeyboardNavigationMode.Continue,\n Children = new Controls\n {\n new Button { Name = \"Button4\" },\n new Button { Name = \"Button5\" },\n new Button { Name = \"Button6\" },\n }\n },\n }\n };\n\n var result = KeyboardNavigationHandler.GetNext(current, NavigationDirection.Down);\n\n Assert.Equal(next, result);\n }\n\n [Fact]\n public void Down_Continue_Returns_First_Control_In_Down_Sibling_Container()\n {\n Button current;\n Button next;\n\n var top = new StackPanel\n {\n Children = new Controls\n {\n new StackPanel\n {\n [KeyboardNavigation.DirectionalNavigationProperty] = KeyboardNavigationMode.Continue,\n Children = new Controls\n {\n new Button { Name = \"Button1\" },\n new Button { Name = \"Button2\" },\n (current = new Button { Name = \"Button3\" }),\n }\n },\n new StackPanel\n {\n [KeyboardNavigation.DirectionalNavigationProperty] = KeyboardNavigationMode.Continue,\n Children = new Controls\n {\n (next = new Button { Name = \"Button4\" }),\n new Button { Name = \"Button5\" },\n new Button { Name = \"Button6\" },\n }\n },\n }\n };\n\n var result = KeyboardNavigationHandler.GetNext(current, NavigationDirection.Down);\n\n Assert.Equal(next, result);\n }\n\n [Fact]\n public void Down_Continue_Returns_Down_Sibling()\n {\n Button current;\n Button next;\n\n var top = new StackPanel\n {\n Children = new Controls\n {\n new StackPanel\n {\n [KeyboardNavigation.DirectionalNavigationProperty] = KeyboardNavigationMode.Continue,\n Children = new Controls\n {\n new Button { Name = \"Button1\" },\n new Button { Name = \"Button2\" },\n (current = new Button { Name = \"Button3\" }),\n }\n },\n (next = new Button { Name = \"Button4\" }),\n }\n };\n\n var result = KeyboardNavigationHandler.GetNext(current, NavigationDirection.Down);\n\n Assert.Equal(next, result);\n }\n\n [Fact]\n public void Down_Continue_Returns_First_Control_In_Down_Uncle_Container()\n {\n Button current;\n Button next;\n\n var top = new StackPanel\n {\n Children = new Controls\n {\n new StackPanel\n {\n Children = new Controls\n {\n new StackPanel\n {\n [KeyboardNavigation.DirectionalNavigationProperty] = KeyboardNavigationMode.Continue,\n Children = new Controls\n {\n new Button { Name = \"Button1\" },\n new Button { Name = \"Button2\" },\n (current = new Button { Name = \"Button3\" }),\n }\n },\n },\n },\n new StackPanel\n {\n [KeyboardNavigation.DirectionalNavigationProperty] = KeyboardNavigationMode.Continue,\n Children = new Controls\n {\n (next = new Button { Name = \"Button4\" }),\n new Button { Name = \"Button5\" },\n new Button { Name = \"Button6\" },\n }\n },\n }\n };\n\n var result = KeyboardNavigationHandler.GetNext(current, NavigationDirection.Down);\n\n Assert.Equal(next, result);\n }\n\n [Fact]\n public void Down_Continue_Returns_Child_Of_Top_Level()\n {\n Button next;\n\n var top = new StackPanel\n {\n [KeyboardNavigation.DirectionalNavigationProperty] = KeyboardNavigationMode.Continue,\n Children = new Controls\n {\n (next = new Button { Name = \"Button1\" }),\n }\n };\n\n var result = KeyboardNavigationHandler.GetNext(top, NavigationDirection.Down);\n\n Assert.Equal(next, result);\n }\n\n [Fact]\n public void Down_Continue_Wraps()\n {\n Button current;\n Button next;\n\n var top = new StackPanel\n {\n [KeyboardNavigation.DirectionalNavigationProperty] = KeyboardNavigationMode.Continue,\n Children = new Controls\n {\n new StackPanel\n {\n [KeyboardNavigation.DirectionalNavigationProperty] = KeyboardNavigationMode.Continue,\n Children = new Controls\n {\n new StackPanel\n {\n [KeyboardNavigation.DirectionalNavigationProperty] = KeyboardNavigationMode.Continue,\n Children = new Controls\n {\n (next = new Button { Name = \"Button1\" }),\n new Button { Name = \"Button2\" },\n new Button { Name = \"Button3\" },\n }\n },\n },\n },\n new StackPanel\n {\n [KeyboardNavigation.DirectionalNavigationProperty] = KeyboardNavigationMode.Continue,\n Children = new Controls\n {\n new Button { Name = \"Button4\" },\n new Button { Name = \"Button5\" },\n (current = new Button { Name = \"Button6\" }),\n }\n },\n }\n };\n\n var result = KeyboardNavigationHandler.GetNext(current, NavigationDirection.Down);\n\n Assert.Equal(next, result);\n }\n\n [Fact]\n public void Down_Cycle_Returns_Down_Control_In_Container()\n {\n Button current;\n Button next;\n\n var top = new StackPanel\n {\n Children = new Controls\n {\n new StackPanel\n {\n [KeyboardNavigation.DirectionalNavigationProperty] = KeyboardNavigationMode.Cycle,\n Children = new Controls\n {\n new Button { Name = \"Button1\" },\n (current = new Button { Name = \"Button2\" }),\n (next = new Button { Name = \"Button3\" }),\n }\n },\n new StackPanel\n {\n Children = new Controls\n {\n new Button { Name = \"Button4\" },\n new Button { Name = \"Button5\" },\n new Button { Name = \"Button6\" },\n }\n },\n }\n };\n\n var result = KeyboardNavigationHandler.GetNext(current, NavigationDirection.Down);\n\n Assert.Equal(next, result);\n }\n\n [Fact]\n public void Down_Cycle_Wraps_To_First()\n {\n Button current;\n Button next;\n\n var top = new StackPanel\n {\n Children = new Controls\n {\n new StackPanel\n {\n [KeyboardNavigation.DirectionalNavigationProperty] = KeyboardNavigationMode.Cycle,\n Children = new Controls\n {\n (next = new Button { Name = \"Button1\" }),\n new Button { Name = \"Button2\" },\n (current = new Button { Name = \"Button3\" }),\n }\n },\n new StackPanel\n {\n Children = new Controls\n {\n new Button { Name = \"Button4\" },\n new Button { Name = \"Button5\" },\n new Button { Name = \"Button6\" },\n }\n },\n }\n };\n\n var result = KeyboardNavigationHandler.GetNext(current, NavigationDirection.Down);\n\n Assert.Equal(next, result);\n }\n\n [Fact]\n public void Down_Contained_Returns_Down_Control_In_Container()\n {\n Button current;\n Button next;\n\n var top = new StackPanel\n {\n Children = new Controls\n {\n new StackPanel\n {\n [KeyboardNavigation.DirectionalNavigationProperty] = KeyboardNavigationMode.Contained,\n Children = new Controls\n {\n new Button { Name = \"Button1\" },\n (current = new Button { Name = \"Button2\" }),\n (next = new Button { Name = \"Button3\" }),\n }\n },\n new StackPanel\n {\n [KeyboardNavigation.DirectionalNavigationProperty] = KeyboardNavigationMode.Contained,\n Children = new Controls\n {\n new Button { Name = \"Button4\" },\n new Button { Name = \"Button5\" },\n new Button { Name = \"Button6\" },\n }\n },\n }\n };\n\n var result = KeyboardNavigationHandler.GetNext(current, NavigationDirection.Down);\n\n Assert.Equal(next, result);\n }\n\n [Fact]\n public void Down_Contained_Stops_At_End()\n {\n Button current;\n\n var top = new StackPanel\n {\n Children = new Controls\n {\n new StackPanel\n {\n [KeyboardNavigation.DirectionalNavigationProperty] = KeyboardNavigationMode.Contained,\n Children = new Controls\n {\n new Button { Name = \"Button1\" },\n new Button { Name = \"Button2\" },\n (current = new Button { Name = \"Button3\" }),\n }\n },\n new StackPanel\n {\n [KeyboardNavigation.DirectionalNavigationProperty] = KeyboardNavigationMode.Contained,\n Children = new Controls\n {\n new Button { Name = \"Button4\" },\n new Button { Name = \"Button5\" },\n new Button { Name = \"Button6\" },\n }\n },\n }\n };\n\n var result = KeyboardNavigationHandler.GetNext(current, NavigationDirection.Down);\n\n Assert.Null(result);\n }\n\n [Fact]\n public void Down_None_Does_Nothing()\n {\n Button current;\n\n var top = new StackPanel\n {\n Children = new Controls\n {\n new StackPanel\n {\n [KeyboardNavigation.DirectionalNavigationProperty] = KeyboardNavigationMode.None,\n Children = new Controls\n {\n new Button { Name = \"Button1\" },\n (current = new Button { Name = \"Button2\" }),\n new Button { Name = \"Button3\" },\n }\n },\n new StackPanel\n {\n [KeyboardNavigation.DirectionalNavigationProperty] = KeyboardNavigationMode.Contained,\n Children = new Controls\n {\n new Button { Name = \"Button4\" },\n new Button { Name = \"Button5\" },\n new Button { Name = \"Button6\" },\n }\n },\n }\n };\n", "answers": [" var result = KeyboardNavigationHandler.GetNext(current, NavigationDirection.Down);"], "length": 1082, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "c3c10b91-f826-4955-9217-aec0e2e05fe1", "reasoning": "The test method defines a Button current and a StackPanel hierarchy, ending with the closing brace and semicolon of the 'top' variable initialization. Following the pattern of previous tests, the next step is to invoke KeyboardNavigationHandler.GetNext with the current button and NavigationDirection.Down, storing the result in a variable. Therefore the next line is the declaration of the result variable.", "reasoning_model_answer": "var result = KeyboardNavigationHandler.GetNext(current, NavigationDirection.Down);", "assistant_with_reasoning": "\nThe test method defines a Button current and a StackPanel hierarchy, ending with the closing brace and semicolon of the 'top' variable initialization. Following the pattern of previous tests, the next step is to invoke KeyboardNavigationHandler.GetNext with the current button and NavigationDirection.Down, storing the result in a variable. Therefore the next line is the declaration of the result variable.\n\nvar result = KeyboardNavigationHandler.GetNext(current, NavigationDirection.Down);", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.313, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 14836, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "var result = KeyboardNavigationHandler.GetNext(current, NavigationDirection.Down);", "score": 0.93, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "import pytest\nfrom decimal import Decimal\n\nfrom replisome.errors import ReplisomeError\nfrom replisome.consumers.DataUpdater import DataUpdater\nfrom replisome.receivers.JsonReceiver import JsonReceiver\n\n\ndef test_insert(src_db, tgt_db, called):\n du = DataUpdater(tgt_db.conn.dsn, skip_missing_columns=True,\n skip_missing_tables=True)\n c = called(du, 'process_message')\n\n jr = JsonReceiver(slot=src_db.slot, message_cb=du.process_message)\n src_db.thread_receive(jr, src_db.make_repl_conn())\n\n scur = src_db.conn.cursor()\n tcur = tgt_db.conn.cursor()\n\n scur.execute(\"drop table if exists testins\")\n scur.execute(\n \"create table testins (id serial primary key, data text, more text)\")\n\n tcur.execute(\"drop table if exists testins\")\n tcur.execute(\"\"\"\n create table testins (\n id integer primary key,\n data text,\n ts timestamptz not null default now(),\n clock timestamptz not null default clock_timestamp())\n \"\"\")\n\n scur.execute(\"insert into testins (data) values ('hello')\")\n c.get()\n tcur.execute(\"select * from testins\")\n rs = tcur.fetchall()\n assert len(rs) == 1\n r = rs[0]\n assert r[0] == 1\n assert r[1] == 'hello'\n\n # Test records are inserted in the same transaction\n scur.execute(\"begin\")\n scur.execute(\"insert into testins default values\")\n scur.execute(\"insert into testins default values\")\n scur.execute(\"commit\")\n\n c.get()\n tcur.execute(\"select * from testins where id > 1 order by id\")\n rs = tcur.fetchall()\n assert len(rs) == 2\n\n assert rs[0][0] == 2\n assert rs[1][0] == 3\n\n assert rs[0][2] == rs[1][2]\n assert rs[0][3] < rs[1][3]\n\n # Missing tables are ignored\n scur.execute(\"drop table if exists notable\")\n scur.execute(\n \"create table notable (id serial primary key)\")\n\n scur.execute(\"insert into notable default values\")\n c.get()\n scur.execute(\"insert into testins default values\")\n c.get()\n\n tcur.execute(\"select max(id) from testins\")\n assert tcur.fetchone()[0] == 4\n\n\ndef test_insert_missing_table(src_db, tgt_db, called):\n du = DataUpdater(tgt_db.conn.dsn, skip_missing_columns=True)\n c = called(du, 'process_message')\n\n rconn = src_db.make_repl_conn()\n jr = JsonReceiver(slot=src_db.slot, message_cb=du.process_message)\n src_db.thread_receive(jr, rconn)\n\n scur = src_db.conn.cursor()\n tcur = tgt_db.conn.cursor()\n\n scur.execute(\"drop table if exists testins\")\n scur.execute(\n \"create table testins (id serial primary key, data text)\")\n\n tcur.execute(\"drop table if exists testins\")\n\n scur.execute(\"insert into testins (data) values ('hello')\")\n with pytest.raises(ReplisomeError):\n c.get()\n\n jr.stop()\n rconn.close()\n\n tcur.execute(\"create table testins (id serial primary key, data text)\")\n\n jr = JsonReceiver(slot=src_db.slot, message_cb=du.process_message)\n src_db.thread_receive(jr, src_db.make_repl_conn())\n c.get()\n\n tcur.execute(\"select * from testins\")\n assert tcur.fetchall() == [(1, 'hello')]\n\n\ndef test_insert_missing_col(src_db, tgt_db, called):\n du = DataUpdater(tgt_db.conn.dsn)\n c = called(du, 'process_message')\n\n rconn = src_db.make_repl_conn()\n jr = JsonReceiver(slot=src_db.slot, message_cb=du.process_message)\n src_db.thread_receive(jr, rconn)\n\n scur = src_db.conn.cursor()\n tcur = tgt_db.conn.cursor()\n\n scur.execute(\"drop table if exists testins\")\n scur.execute(\n \"create table testins (id serial primary key, data text, more text)\")\n\n tcur.execute(\"drop table if exists testins\")\n tcur.execute(\"\"\"\n create table testins (\n id integer primary key,\n data text)\n \"\"\")\n\n scur.execute(\"insert into testins (data) values ('hello')\")\n with pytest.raises(ReplisomeError):\n c.get()\n\n tcur.execute(\"select * from testins\")\n assert tcur.fetchall() == []\n\n jr.stop()\n rconn.close()\n tcur.execute(\"alter table testins add more text\")\n\n du = DataUpdater(tgt_db.conn.dsn)\n c = called(du, 'process_message')\n\n jr = JsonReceiver(slot=src_db.slot, message_cb=du.process_message)\n src_db.thread_receive(jr, src_db.make_repl_conn())\n\n c.get()\n tcur.execute(\"select * from testins\")\n assert tcur.fetchall() == [(1, 'hello', None)]\n\n\ndef test_insert_conflict(src_db, tgt_db, called):\n du = DataUpdater(tgt_db.conn.dsn, upsert=True, skip_missing_columns=True)\n c = called(du, 'process_message')\n\n jr = JsonReceiver(slot=src_db.slot, message_cb=du.process_message)\n src_db.thread_receive(jr, src_db.make_repl_conn())\n\n scur = src_db.conn.cursor()\n tcur = tgt_db.conn.cursor()\n\n scur.execute(\"drop table if exists testins\")\n scur.execute(\"\"\"\n create table testins (\n id serial primary key, data text, foo text, more text)\n \"\"\")\n\n tcur.execute(\"drop table if exists testins\")\n tcur.execute(\"\"\"\n create table testins (\n id integer primary key, data text, foo text, n int)\n \"\"\")\n\n tcur.execute(\n \"insert into testins (id, data, foo, n) values (1, 'foo', 'ouch', 42)\")\n scur.execute(\n \"insert into testins (data, foo, more) values ('baz', 'qux', 'quux')\")\n\n if tgt_db.conn.server_version >= 90500:\n c.get()\n else:\n with pytest.raises(ReplisomeError):\n c.get()\n pytest.skip()\n\n tcur.execute(\"select * from testins\")\n rs = tcur.fetchall()\n assert len(rs) == 1\n assert rs[0] == (1, 'baz', 'qux', 42)\n\n\ndef test_insert_conflict_do_nothing(src_db, tgt_db, called):\n du = DataUpdater(tgt_db.conn.dsn, upsert=True, skip_missing_columns=True)\n c = called(du, 'process_message')\n\n jr = JsonReceiver(slot=src_db.slot, message_cb=du.process_message)\n src_db.thread_receive(jr, src_db.make_repl_conn())\n\n scur = src_db.conn.cursor()\n tcur = tgt_db.conn.cursor()\n\n scur.execute(\"drop table if exists testinsmini\")\n scur.execute(\"create table testinsmini (id serial primary key, data text)\")\n\n tcur.execute(\"drop table if exists testinsmini\")\n tcur.execute(\"create table testinsmini (id serial primary key, other text)\")\n\n tcur.execute(\n \"insert into testinsmini (id, other) values (1, 'foo')\")\n scur.execute(\n \"insert into testinsmini (data) values ('bar')\")\n\n if tgt_db.conn.server_version >= 90500:\n c.get()\n else:\n with pytest.raises(ReplisomeError):\n c.get()\n pytest.skip()\n\n tcur.execute(\"select * from testinsmini\")\n rs = tcur.fetchall()\n assert len(rs) == 1\n assert rs[0] == (1, 'foo')\n\n\ndef test_update(src_db, tgt_db, called):\n du = DataUpdater(tgt_db.conn.dsn, skip_missing_columns=True,\n skip_missing_tables=True)\n c = called(du, 'process_message')\n\n jr = JsonReceiver(slot=src_db.slot, message_cb=du.process_message)\n src_db.thread_receive(jr, src_db.make_repl_conn())\n\n scur = src_db.conn.cursor()\n tcur = tgt_db.conn.cursor()\n\n scur.execute(\"drop table if exists testup\")\n scur.execute(\n \"create table testup (id serial primary key, data text, more text)\")\n\n tcur.execute(\"drop table if exists testup\")\n tcur.execute(\"\"\"\n create table testup (\n id integer primary key,\n data text,\n ts timestamptz not null default now(),\n clock timestamptz not null default clock_timestamp())\n \"\"\")\n\n scur.execute(\"insert into testup (data) values ('hello')\")\n scur.execute(\"insert into testup (data) values ('world')\")\n scur.execute(\"update testup set data = 'mama' where id = 2\")\n\n for i in range(3):\n c.get()\n\n tcur.execute(\"select id, data from testup order by id\")\n rs = tcur.fetchall()\n assert rs == [(1, 'hello'), (2, 'mama')]\n\n # The key can change too\n scur.execute(\"update testup set id = 22 where id = 2\")\n c.get()\n\n tcur.execute(\"select id, data from testup order by id\")\n rs = tcur.fetchall()\n assert rs == [(1, 'hello'), (22, 'mama')]\n\n # Missing tables are ignored\n scur.execute(\"drop table if exists notable\")\n scur.execute(\n \"create table notable (id serial primary key)\")\n\n scur.execute(\"insert into notable default values\")\n c.get()\n scur.execute(\"update notable set id = 2 where id = 1\")\n c.get()\n scur.execute(\"insert into testup default values\")\n c.get()\n\n tcur.execute(\"select id from testup where id = 3\")\n assert tcur.fetchone()[0] == 3\n\n\ndef test_update_missing_table(src_db, tgt_db, called):\n du = DataUpdater(tgt_db.conn.dsn, skip_missing_columns=True)\n c = called(du, 'process_message')\n\n rconn = src_db.make_repl_conn()\n jr = JsonReceiver(slot=src_db.slot, message_cb=du.process_message)\n src_db.thread_receive(jr, rconn)\n\n scur = src_db.conn.cursor()\n tcur = tgt_db.conn.cursor()\n\n scur.execute(\"drop table if exists testins\")\n scur.execute(\"drop table if exists testins2\")\n scur.execute(\n \"create table testins (id serial primary key, data text)\")\n\n tcur.execute(\"drop table if exists testins\")\n tcur.execute(\"drop table if exists testins2\")\n tcur.execute(\"create table testins (id serial primary key, data text)\")\n\n scur.execute(\"insert into testins (data) values ('hello')\")\n c.get()\n scur.execute(\"alter table testins rename to testins2\")\n scur.execute(\"update testins2 set data = 'world' where id = 1\")\n\n with pytest.raises(ReplisomeError):\n c.get()\n\n jr.stop()\n rconn.close()\n\n tcur.execute(\"alter table testins rename to testins2\")\n\n jr = JsonReceiver(slot=src_db.slot, message_cb=du.process_message)\n src_db.thread_receive(jr, src_db.make_repl_conn())\n c.get()\n\n tcur.execute(\"select * from testins2\")\n assert tcur.fetchall() == [(1, 'world')]\n\n\ndef test_update_missing_col(src_db, tgt_db, called):\n du = DataUpdater(tgt_db.conn.dsn)\n c = called(du, 'process_message')\n\n rconn = src_db.make_repl_conn()\n jr = JsonReceiver(slot=src_db.slot, message_cb=du.process_message)\n src_db.thread_receive(jr, rconn)\n\n scur = src_db.conn.cursor()\n tcur = tgt_db.conn.cursor()\n\n scur.execute(\"drop table if exists testup\")\n scur.execute(\n \"create table testup (id serial primary key, data text)\")\n\n tcur.execute(\"drop table if exists testup\")\n tcur.execute(\"\"\"\n create table testup (", "answers": [" id integer primary key,"], "length": 994, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "ece151c6-38fa-4ddf-9f41-a62b709c7cd5", "reasoning": "The test is setting up the target database table for the 'test_update_missing_col' case. The previous line starts a multi-line string for a CREATE TABLE statement: `tcur.execute(\"\"\"\n create table testup (`. The next line should define the first column of the table, matching the source table's primary key. Therefore the appropriate continuation is the column definition `id integer primary key,` with proper indentation.", "reasoning_model_answer": "id integer primary key,", "assistant_with_reasoning": "\nThe test is setting up the target database table for the 'test_update_missing_col' case. The previous line starts a multi-line string for a CREATE TABLE statement: `tcur.execute(\"\"\"\n create table testup (`. The next line should define the first column of the table, matching the source table's primary key. Therefore the appropriate continuation is the column definition `id integer primary key,` with proper indentation.\n\nid integer primary key,", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 5.727, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 10497, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "id integer primary key,", "score": 0.79, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "using System;\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.Linq;\nusing System.Linq.Expressions;\nusing System.Runtime.InteropServices.ComTypes;\nusing System.Security.Cryptography.X509Certificates;\nusing NUnit.Framework;\n\nnamespace OMap.Tests\n{\n [TestFixture]\n public class ObjectMapperTests\n {\n public class Foo\n {\n public int Property1 { get; set; }\n }\n public class FooX : Foo\n {\n public int Property2 { get; set; }\n }\n public class FooO\n {\n public int Property1 { get; set; }\n public Foo Foo { get; set; }\n }\n public class FooC\n {\n public int Property1 { get; set; }\n public Foo[] Foos { get; set; }\n }\n public class FooAll\n {\n public int Property1 { get; set; }\n public string Property2 { get; set; }\n public bool Property3 { get; set; }\n public DateTime Property4 { get; set; }\n public Foo[] Foos { get; set; }\n public Foo FooSingle { get; set; }\n }\n public class FooAllX : FooAll\n {\n public decimal Property5 { get; set; }\n }\n\n public class Bar\n {\n public int Property3 { get; set; }\n }\n public class BarX : Bar\n {\n public int Property4 { get; set; }\n }\n\n public class BarO\n {\n public int Property1 { get; set; }\n public Bar Bar { get; set; }\n }\n public class BarC\n {\n public int Property1 { get; set; }\n public Bar[] BarArray { get; set; }\n public List BarList { get; set; }\n public IEnumerable BarEnumerable { get; set; }\n public IList BarIList { get; set; }\n public List BarListNoSetter { get; private set; }\n public List BarListNotEmpty { get; set; }\n public List BarListNoSetterNotEmpty { get; private set; }\n public BarC()\n {\n BarListNoSetter = new List();\n BarListNotEmpty = new List() { new Bar() };\n BarListNoSetterNotEmpty = new List() { new Bar() };\n }\n }\n public class BarAll\n {\n public int Property1 { get; set; }\n public string Property2 { get; set; }\n public bool Property3 { get; set; }\n public DateTime Property4 { get; set; }\n public Bar[] Foos { get; set; }\n public Bar FooSingle { get; set; }\n }\n public class BarAllX : BarAll\n {\n public decimal Property5 { get; set; }\n }\n\n public class Dependency1\n {\n private static readonly Random _random = new Random();\n\n public int RandomProperty { get; private set; }\n public int GlobalProperty1 { get; set; }\n\n public Dependency1()\n {\n while (RandomProperty == 0)\n {\n RandomProperty = _random.Next();\n }\n }\n\n }\n\n\n [Test]\n public void ShouldMapProperty()\n {\n var foo = new Foo() { Property1 = 18 };\n var mapper = CreateMapper(new ResolverMock(), builder =>\n {\n builder.CreateMap()\n .MapProperty(x => x.Property1, x => x.Property3);\n });\n\n var bar = mapper.Map(foo);\n Assert.AreEqual(foo.Property1, bar.Property3);\n }\n\n [Test]\n public void ShouldMapPropertyExistingObject()\n {\n var foo = new Foo() { Property1 = 18 };\n var mapper = CreateMapper(new ResolverMock(), builder =>\n {\n builder.CreateMap()\n .MapProperty(x => x.Property1, x => x.Property3);\n });\n\n var bar = new Bar();\n mapper.Map(foo, bar);\n Assert.AreEqual(foo.Property1, bar.Property3);\n }\n\n [Test]\n public void ShouldMapPropertyWithFunction()\n {\n var foo = new Foo() { Property1 = 18 };\n var mapper = CreateMapper(new ResolverMock(), builder =>\n {\n builder.CreateMap()\n .MapProperty(x => x.Property1 * 5, x => x.Property3);\n });\n\n var bar = mapper.Map(foo);\n Assert.AreEqual(foo.Property1 * 5, bar.Property3);\n }\n\n [Test]\n public void ShouldMapPropertyWithFunctionExistingObject()\n {\n var foo = new Foo() { Property1 = 18 };\n var mapper = CreateMapper(new ResolverMock(), builder =>\n {\n builder.CreateMap()\n .MapProperty(x => x.Property1 * 5, x => x.Property3);\n });\n\n\n var bar = new Bar();\n mapper.Map(foo, bar);\n Assert.AreEqual(foo.Property1 * 5, bar.Property3);\n }\n\n [Test]\n public void ShouldMapInheritedProperty()\n {\n var foo = new FooX() { Property1 = 18, Property2 = 7 };\n var mapper = CreateMapper(new ResolverMock(), builder =>\n {\n builder.CreateMap()\n .MapProperty(x => x.Property1, x => x.Property3);\n\n builder.CreateMap()\n .MapProperty(x => x.Property2, x => x.Property4);\n });\n\n var bar = mapper.Map(foo);\n Assert.IsInstanceOf(bar, \"Even if you have requested 'Bar', the mapper found a more specific type and will return that instead.\");\n var barX = (BarX)bar;\n\n Assert.AreEqual(foo.Property1, barX.Property3);\n Assert.AreEqual(foo.Property2, barX.Property4);\n }\n\n [Test]\n public void ShouldNotLookForParentsWhenMappingInheritedProperties()\n {\n //NOTE: By design, when calling Map, no mappings for Foo will be used - eventhough FooX inherits from Foo.\n //To get all mappings, ca\n\n var foo = new FooX() { Property1 = 18, Property2 = 7 };\n var mapper = CreateMapper(new ResolverMock(), builder =>\n {\n builder.CreateMap()\n .MapProperty(x => x.Property1, x => x.Property3);\n\n builder.CreateMap()\n .MapProperty(x => x.Property2, x => x.Property4);\n });\n\n //Not specifying TTargetBase will skip all mappings from BarX upwards (the inheritance chain).\n var barX1 = mapper.Map(foo);\n Assert.AreEqual(0, barX1.Property3);\n Assert.AreEqual(7, barX1.Property4);\n\n //Specifying TTargetBase will enture all mappings from Bar downwards (the inheritance chain) are applied.\n var barX2 = mapper.Map(foo);\n Assert.AreEqual(18, barX2.Property3);\n Assert.AreEqual(7, barX2.Property4);\n }\n\n\n [Test]\n public void ShouldMapInheritedPropertyExistingObject()\n {\n var foo = new FooX() { Property1 = 18, Property2 = 7 };\n var mapper = CreateMapper(new ResolverMock(), builder =>\n {\n builder.CreateMap()\n .MapProperty(x => x.Property1, x => x.Property3);\n\n builder.CreateMap()\n .MapProperty(x => x.Property2, x => x.Property4);\n });\n\n var bar = new Bar();\n mapper.Map(foo, bar);\n\n Assert.AreEqual(foo.Property1, bar.Property3);\n }\n\n [Test]\n public void ShouldMapComposedObject()\n {\n var foo = new FooO() { Property1 = 18, Foo = new Foo() { Property1 = 7 } };\n\n var mapper = CreateMapper(new ResolverMock(), builder =>\n {\n builder.CreateMap()\n .MapProperty(x => x.Property1, x => x.Property3);\n\n builder.CreateMap()\n .MapProperty(x => x.Property1, x => x.Property1)\n .MapObject(x => x.Foo, x => x.Bar);\n });\n\n var bar = mapper.Map(foo);\n Assert.AreEqual(foo.Property1, bar.Property1);\n Assert.AreEqual(foo.Foo.Property1, bar.Bar.Property3);\n }\n\n [Test]\n public void ShouldMapInheritedComposedObject()\n {\n var foo = new FooO() { Property1 = 18, Foo = new FooX() { Property1 = 7, Property2 = 6 } };\n\n var mapper = CreateMapper(new ResolverMock(), builder =>\n {\n builder.CreateMap()", "answers": [" .MapProperty(x => x.Property1, x => x.Property3);"], "length": 900, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "661caca9-5d1c-4889-9adf-fc27bc77540e", "reasoning": "The test ShouldMapInheritedComposedObject is defining mappings. The code currently ends mid‑statement at 'builder.CreateMap()'. The next line should continue the fluent call by adding the MapProperty configuration, matching the pattern used earlier in similar tests.", "reasoning_model_answer": ".MapProperty(x => x.Property1, x => x.Property3);", "assistant_with_reasoning": "\nThe test ShouldMapInheritedComposedObject is defining mappings. The code currently ends mid‑statement at 'builder.CreateMap()'. The next line should continue the fluent call by adding the MapProperty configuration, matching the pattern used earlier in similar tests.\n\n.MapProperty(x => x.Property1, x => x.Property3);", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.8, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 8921, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": ".MapProperty(x => x.Property1, x => x.Property3);", "score": 0.83, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "\"\"\"Group TQL Filter\"\"\"\n# standard library\nfrom enum import Enum\n\n# first-party\nfrom tcex.api.tc.v3.api_endpoints import ApiEndpoints\nfrom tcex.api.tc.v3.filter_abc import FilterABC\nfrom tcex.api.tc.v3.tql.tql import Tql\nfrom tcex.api.tc.v3.tql.tql_operator import TqlOperator\nfrom tcex.api.tc.v3.tql.tql_type import TqlType\n\n\nclass GroupFilter(FilterABC):\n \"\"\"Filter Object for Groups\"\"\"\n\n @property\n def _api_endpoint(self) -> str:\n \"\"\"Return the API endpoint.\"\"\"\n return ApiEndpoints.GROUPS.value\n\n def associated_indicator(self, operator: Enum, associated_indicator: int) -> None:\n \"\"\"Filter associatedIndicator based on **associatedIndicator** keyword.\n\n Args:\n operator: The operator enum for the filter.\n associated_indicator: No description provided.\n \"\"\"\n self._tql.add_filter('associatedIndicator', operator, associated_indicator, TqlType.INTEGER)\n\n def attribute(self, operator: Enum, attribute: str) -> None:\n \"\"\"Filter attribute based on **attribute** keyword.\n\n Args:\n operator: The operator enum for the filter.\n attribute: No description provided.\n \"\"\"\n self._tql.add_filter('attribute', operator, attribute, TqlType.STRING)\n\n def child_group(self, operator: Enum, child_group: int) -> None:\n \"\"\"Filter childGroup based on **childGroup** keyword.\n\n Args:\n operator: The operator enum for the filter.\n child_group: No description provided.\n \"\"\"\n self._tql.add_filter('childGroup', operator, child_group, TqlType.INTEGER)\n\n def created_by(self, operator: Enum, created_by: str) -> None:\n \"\"\"Filter Created By based on **createdBy** keyword.\n\n Args:\n operator: The operator enum for the filter.\n created_by: The user who created the group.\n \"\"\"\n self._tql.add_filter('createdBy', operator, created_by, TqlType.STRING)\n\n def date_added(self, operator: Enum, date_added: str) -> None:\n \"\"\"Filter Date Added based on **dateAdded** keyword.\n\n Args:\n operator: The operator enum for the filter.\n date_added: The date the group was added to the system.\n \"\"\"\n date_added = self.utils.any_to_datetime(date_added).strftime('%Y-%m-%dT%H:%M:%S')\n self._tql.add_filter('dateAdded', operator, date_added, TqlType.STRING)\n\n def document_date_added(self, operator: Enum, document_date_added: str) -> None:\n \"\"\"Filter Date Added (Document) based on **documentDateAdded** keyword.\n\n Args:\n operator: The operator enum for the filter.\n document_date_added: The date the document was added.\n \"\"\"\n document_date_added = self.utils.any_to_datetime(document_date_added).strftime(\n '%Y-%m-%dT%H:%M:%S'\n )\n self._tql.add_filter('documentDateAdded', operator, document_date_added, TqlType.STRING)\n\n def document_filename(self, operator: Enum, document_filename: str) -> None:\n \"\"\"Filter Filename (Document) based on **documentFilename** keyword.\n\n Args:\n operator: The operator enum for the filter.\n document_filename: The file name of the document.\n \"\"\"\n self._tql.add_filter('documentFilename', operator, document_filename, TqlType.STRING)\n\n def document_filesize(self, operator: Enum, document_filesize: int) -> None:\n \"\"\"Filter File Size (Document) based on **documentFilesize** keyword.\n\n Args:\n operator: The operator enum for the filter.\n document_filesize: The filesize of the document.\n \"\"\"\n self._tql.add_filter('documentFilesize', operator, document_filesize, TqlType.INTEGER)\n\n def document_status(self, operator: Enum, document_status: str) -> None:\n \"\"\"Filter Status (Document) based on **documentStatus** keyword.\n\n Args:\n operator: The operator enum for the filter.\n document_status: The status of the document.\n \"\"\"\n self._tql.add_filter('documentStatus', operator, document_status, TqlType.STRING)\n\n def document_type(self, operator: Enum, document_type: str) -> None:\n \"\"\"Filter Type (Document) based on **documentType** keyword.\n\n Args:\n operator: The operator enum for the filter.\n document_type: The type of document.\n \"\"\"\n self._tql.add_filter('documentType', operator, document_type, TqlType.STRING)\n\n def downvote_count(self, operator: Enum, downvote_count: int) -> None:\n \"\"\"Filter Downvote Count based on **downvoteCount** keyword.\n\n Args:\n operator: The operator enum for the filter.\n downvote_count: The number of downvotes the group has received.\n \"\"\"\n self._tql.add_filter('downvoteCount', operator, downvote_count, TqlType.INTEGER)\n\n def email_date(self, operator: Enum, email_date: str) -> None:\n \"\"\"Filter Date (Email) based on **emailDate** keyword.\n\n Args:\n operator: The operator enum for the filter.\n email_date: The date of the email.\n \"\"\"\n email_date = self.utils.any_to_datetime(email_date).strftime('%Y-%m-%dT%H:%M:%S')\n self._tql.add_filter('emailDate', operator, email_date, TqlType.STRING)\n\n def email_from(self, operator: Enum, email_from: str) -> None:\n \"\"\"Filter From (Email) based on **emailFrom** keyword.\n\n Args:\n operator: The operator enum for the filter.\n email_from: The 'from' field of the email.\n \"\"\"\n self._tql.add_filter('emailFrom', operator, email_from, TqlType.STRING)\n\n def email_score(self, operator: Enum, email_score: int) -> None:\n \"\"\"Filter Score (Email) based on **emailScore** keyword.\n\n Args:\n operator: The operator enum for the filter.\n email_score: The score of the email.\n \"\"\"\n self._tql.add_filter('emailScore', operator, email_score, TqlType.INTEGER)\n\n def email_score_includes_body(self, operator: Enum, email_score_includes_body: bool) -> None:\n \"\"\"Filter Score Includes Body (Email) based on **emailScoreIncludesBody** keyword.\n\n Args:\n operator: The operator enum for the filter.\n email_score_includes_body: A true/false indicating if the body was included in the\n scoring of the email.\n \"\"\"\n self._tql.add_filter(\n 'emailScoreIncludesBody', operator, email_score_includes_body, TqlType.BOOLEAN\n )\n\n def email_subject(self, operator: Enum, email_subject: str) -> None:\n \"\"\"Filter Subject (Email) based on **emailSubject** keyword.\n\n Args:\n operator: The operator enum for the filter.\n email_subject: The subject of the email.\n \"\"\"\n self._tql.add_filter('emailSubject', operator, email_subject, TqlType.STRING)\n\n def event_date(self, operator: Enum, event_date: str) -> None:\n \"\"\"Filter Event Date based on **eventDate** keyword.\n\n Args:\n operator: The operator enum for the filter.\n event_date: The event date of the group.\n \"\"\"\n event_date = self.utils.any_to_datetime(event_date).strftime('%Y-%m-%dT%H:%M:%S')\n self._tql.add_filter('eventDate', operator, event_date, TqlType.STRING)\n\n @property\n def has_artifact(self):\n \"\"\"Return **ArtifactFilter** for further filtering.\"\"\"\n # first-party\n from tcex.api.tc.v3.artifacts.artifact_filter import ArtifactFilter\n\n artifacts = ArtifactFilter(Tql())\n self._tql.add_filter('hasArtifact', TqlOperator.EQ, artifacts, TqlType.SUB_QUERY)\n return artifacts\n\n @property\n def has_attribute(self):\n \"\"\"Return **GroupAttributeFilter** for further filtering.\"\"\"\n # first-party\n from tcex.api.tc.v3.group_attributes.group_attribute_filter import GroupAttributeFilter\n\n attributes = GroupAttributeFilter(Tql())\n self._tql.add_filter('hasAttribute', TqlOperator.EQ, attributes, TqlType.SUB_QUERY)\n return attributes\n\n @property\n def has_case(self):\n \"\"\"Return **CaseFilter** for further filtering.\"\"\"\n # first-party\n from tcex.api.tc.v3.cases.case_filter import CaseFilter\n\n cases = CaseFilter(Tql())\n self._tql.add_filter('hasCase', TqlOperator.EQ, cases, TqlType.SUB_QUERY)\n return cases\n\n @property\n def has_group(self):\n \"\"\"Return **GroupFilter** for further filtering.\"\"\"\n groups = GroupFilter(Tql())\n self._tql.add_filter('hasGroup', TqlOperator.EQ, groups, TqlType.SUB_QUERY)\n return groups\n\n @property\n def has_indicator(self):\n \"\"\"Return **IndicatorFilter** for further filtering.\"\"\"\n # first-party\n from tcex.api.tc.v3.indicators.indicator_filter import IndicatorFilter\n\n indicators = IndicatorFilter(Tql())\n self._tql.add_filter('hasIndicator', TqlOperator.EQ, indicators, TqlType.SUB_QUERY)\n return indicators\n\n @property\n def has_security_label(self):\n \"\"\"Return **SecurityLabel** for further filtering.\"\"\"\n # first-party\n from tcex.api.tc.v3.security_labels.security_label_filter import SecurityLabelFilter\n\n security_labels = SecurityLabelFilter(Tql())\n self._tql.add_filter('hasSecurityLabel', TqlOperator.EQ, security_labels, TqlType.SUB_QUERY)\n return security_labels\n\n @property\n def has_tag(self):\n \"\"\"Return **TagFilter** for further filtering.\"\"\"\n # first-party\n from tcex.api.tc.v3.tags.tag_filter import TagFilter\n\n tags = TagFilter(Tql())\n self._tql.add_filter('hasTag', TqlOperator.EQ, tags, TqlType.SUB_QUERY)\n return tags\n\n @property\n def has_victim(self):\n \"\"\"Return **VictimFilter** for further filtering.\"\"\"\n # first-party\n from tcex.api.tc.v3.victims.victim_filter import VictimFilter\n\n victims = VictimFilter(Tql())\n self._tql.add_filter('hasVictim', TqlOperator.EQ, victims, TqlType.SUB_QUERY)\n return victims\n\n @property\n def has_victim_asset(self):\n \"\"\"Return **VictimAssetFilter** for further filtering.\"\"\"\n # first-party\n from tcex.api.tc.v3.victim_assets.victim_asset_filter import VictimAssetFilter\n\n victim_assets = VictimAssetFilter(Tql())\n self._tql.add_filter('hasVictimAsset', TqlOperator.EQ, victim_assets, TqlType.SUB_QUERY)\n return victim_assets\n\n def id(self, operator: Enum, id: int) -> None: # pylint: disable=redefined-builtin\n \"\"\"Filter ID based on **id** keyword.\n\n Args:\n operator: The operator enum for the filter.\n id: The ID of the group.\n \"\"\"\n self._tql.add_filter('id', operator, id, TqlType.INTEGER)\n\n def is_group(self, operator: Enum, is_group: bool) -> None:\n \"\"\"Filter isGroup based on **isGroup** keyword.\n\n Args:\n operator: The operator enum for the filter.\n is_group: No description provided.\n \"\"\"\n self._tql.add_filter('isGroup', operator, is_group, TqlType.BOOLEAN)\n\n def last_modified(self, operator: Enum, last_modified: str) -> None:\n \"\"\"Filter Last Modified based on **lastModified** keyword.\n\n Args:\n operator: The operator enum for the filter.\n last_modified: The date the group was last modified.\n \"\"\"\n last_modified = self.utils.any_to_datetime(last_modified).strftime('%Y-%m-%dT%H:%M:%S')\n self._tql.add_filter('lastModified', operator, last_modified, TqlType.STRING)\n\n def owner(self, operator: Enum, owner: int) -> None:\n \"\"\"Filter Owner ID based on **owner** keyword.\n\n Args:\n operator: The operator enum for the filter.\n owner: The Owner ID for the group.\n \"\"\"\n self._tql.add_filter('owner', operator, owner, TqlType.INTEGER)\n\n def owner_name(self, operator: Enum, owner_name: str) -> None:\n \"\"\"Filter Owner Name based on **ownerName** keyword.\n\n Args:", "answers": [" operator: The operator enum for the filter."], "length": 1021, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "438a0db2-b261-4296-a262-47a05752d162", "reasoning": "The method owner_name is being defined. After the docstring opening and the 'Args:' line, the next line should describe the first argument, following the pattern used in other methods. Therefore the next line is the description for the 'operator' argument, indented appropriately.", "reasoning_model_answer": "operator: The operator enum for the filter.", "assistant_with_reasoning": "\nThe method owner_name is being defined. After the docstring opening and the 'Args:' line, the next line should describe the first argument, following the pattern used in other methods. Therefore the next line is the description for the 'operator' argument, indented appropriately.\n\noperator: The operator enum for the filter.", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 6.577, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 12188, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "operator: The operator enum for the filter.", "score": 0.88, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "# Copyright 2015 Internap.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom ncclient import manager\nfrom ncclient.operations import RPCError, TimeoutExpiredError\nfrom ncclient.xml_ import new_ele, sub_ele, to_ele, to_xml\nfrom netaddr import IPNetwork\n\nfrom netman import regex\nfrom netman.core.objects.access_groups import IN, OUT\nfrom netman.core.objects.bond import Bond\nfrom netman.core.objects.exceptions import LockedSwitch, VlanAlreadyExist, UnknownVlan, \\\n InterfaceInWrongPortMode, UnknownInterface, AccessVlanNotSet, NativeVlanNotSet, TrunkVlanNotSet, VlanAlreadyInTrunk, \\\n BadBondNumber, BondAlreadyExist, UnknownBond, InterfaceNotInBond, OperationNotCompleted, InvalidMtuSize\nfrom netman.core.objects.interface import Interface\nfrom netman.core.objects.interface_states import ON, OFF\nfrom netman.core.objects.port_modes import ACCESS, TRUNK, BOND_MEMBER\nfrom netman.core.objects.switch_base import SwitchBase\nfrom netman.core.objects.vlan import Vlan\n\n\nclass Juniper(SwitchBase):\n\n def __init__(self, switch_descriptor, custom_strategies,\n timeout=300):\n super(Juniper, self).__init__(switch_descriptor)\n self.timeout = timeout\n self.custom_strategies = custom_strategies\n self.netconf = None\n\n self.in_transaction = False\n\n def _connect(self):\n params = dict(\n host=self.switch_descriptor.hostname,\n username=self.switch_descriptor.username,\n password=self.switch_descriptor.password,\n hostkey_verify=False,\n device_params={'name': 'junos'},\n timeout=self.timeout\n )\n\n if self.switch_descriptor.port:\n params[\"port\"] = self.switch_descriptor.port\n\n self.netconf = manager.connect(**params)\n\n def _disconnect(self):\n try:\n self.netconf.close_session()\n except TimeoutExpiredError:\n pass\n\n def start_transaction(self):\n try:\n self.netconf.lock(target=\"candidate\")\n except RPCError as e:\n if \"configuration database modified\" in e.message:\n self.rollback_transaction()\n self.netconf.lock(target=\"candidate\")\n elif \"Configuration database is already open\" in e.message:\n raise LockedSwitch()\n else:\n raise\n self.in_transaction = True\n\n def end_transaction(self):\n self.in_transaction = False\n self.netconf.unlock(target=\"candidate\")\n\n def rollback_transaction(self):\n self.netconf.discard_changes()\n\n def commit_transaction(self):\n try:\n self.netconf.commit()\n except RPCError as e:\n self.logger.info(\"An RPCError was raised : {}\".format(e))\n raise OperationNotCompleted(str(e).strip())\n\n def get_vlans(self):\n config = self.query(self.custom_strategies.all_vlans, all_interfaces)\n\n vlan_list = []\n for vlan_node in self.custom_strategies.vlan_nodes(config):\n vlan = self.get_vlan_from_node(vlan_node, config)\n if vlan is not None:\n vlan_list.append(vlan)\n\n return vlan_list\n\n def get_vlan(self, number):\n config = self.query(self.custom_strategies.all_vlans, all_interfaces)\n vlan_node = self.custom_strategies.vlan_node(config, number)\n return self.get_vlan_from_node(vlan_node, config)\n\n def get_vlan_from_node(self, vlan_node, config):\n vlan_id_node = first(vlan_node.xpath(\"vlan-id\"))\n\n vlan = None\n if vlan_id_node is not None:\n vlan = Vlan(number=int(vlan_id_node.text), icmp_redirects=True)\n\n description_node = first(vlan_node.xpath(\"description\"))\n if description_node is not None:\n vlan.name = description_node.text\n\n l3_if_type, l3_if_name = self.custom_strategies.get_l3_interface(vlan_node)\n if l3_if_name is not None:\n interface_vlan_node = first(config.xpath(\"data/configuration/interfaces/interface/name[text()=\\\"{}\\\"]/..\"\n \"/unit/name[text()=\\\"{}\\\"]/..\".format(l3_if_type, l3_if_name)))\n if interface_vlan_node is not None:\n vlan.ips = parse_ips(interface_vlan_node)\n vlan.access_groups[IN] = parse_inet_filter(interface_vlan_node, \"input\")\n vlan.access_groups[OUT] = parse_inet_filter(interface_vlan_node, \"output\")\n vlan.vrrp_groups = self.custom_strategies.parse_vrrp_groups(interface_vlan_node)\n vlan.icmp_redirects = self.custom_strategies.parse_icmp_redirects(interface_vlan_node)\n return vlan\n\n def get_interfaces(self):\n physical_interfaces = self._list_physical_interfaces()\n config = self.query(all_interfaces, self.custom_strategies.all_vlans)\n\n interface_list = []\n for phys_int in physical_interfaces:\n if not phys_int.name.startswith(\"ae\"):\n interface_node = first(config.xpath(\"data/configuration/interfaces/interface/name[text()=\\\"{}\\\"]/..\"\n .format(phys_int.name)))\n if interface_node is not None:\n interface_list.append(self.node_to_interface(interface_node, config))\n else:\n interface_list.append(phys_int.to_interface())\n\n return interface_list\n\n def add_vlan(self, number, name=None):\n config = self.query(self.custom_strategies.all_vlans)\n\n try:\n self.custom_strategies.vlan_node(config, number)\n raise VlanAlreadyExist(number)\n except UnknownVlan:\n pass\n\n update = Update()\n self.custom_strategies.add_update_vlans(update, number, name)\n\n try:\n self._push(update)\n except RPCError as e:\n self.custom_strategies.manage_update_vlan_exception(e.message, number)\n raise\n\n def remove_vlan(self, number):\n config = self.query(self.custom_strategies.all_vlans, all_interfaces)\n\n vlan_node = self.custom_strategies.vlan_node(config, number)\n vlan_name = first(vlan_node.xpath(\"name\")).text\n\n update = Update()\n self.custom_strategies.remove_update_vlans(update, vlan_name)\n\n l3_if_type, l3_if_name = self.custom_strategies.get_l3_interface(vlan_node)\n if l3_if_name is not None:\n update.add_interface(interface_unit_interface_removal(l3_if_type, l3_if_name))\n\n for interface_node in config.xpath(\"data/configuration/interfaces/interface\"):\n members_modifications = self.custom_strategies.craft_members_modification_to_remove_vlan(interface_node, vlan_name, number)\n\n if len(members_modifications) > 0:\n update.add_interface(self.custom_strategies.interface_vlan_members_update(\n first(interface_node.xpath(\"name\")).text,\n first(interface_node.xpath(\"unit/name\")).text,\n members_modifications)\n )\n\n self._push(update)\n\n def set_access_mode(self, interface_id):\n update_attributes = []\n\n config = self.query(all_interfaces, self.custom_strategies.all_vlans)\n\n interface_node = self.get_interface_config(interface_id, config)\n\n interface = self.node_to_interface(interface_node, config)\n\n if self.get_port_mode(interface_node) in (TRUNK, None):\n update_attributes.append(self.custom_strategies.get_interface_port_mode_update_element(\"access\"))\n\n if len(interface.trunk_vlans) > 0:\n update_attributes.append(self.custom_strategies.get_delete_trunk_vlan_element())\n\n if interface.trunk_native_vlan is not None:\n update_attributes.append(to_ele(''))\n\n if len(update_attributes) > 0:\n update = Update()\n update.add_interface(self.custom_strategies.interface_update(interface_id, \"0\", update_attributes))\n self._push_interface_update(interface_id, update)\n\n def set_trunk_mode(self, interface_id):\n update_attributes = []\n\n config = self.query(one_interface(interface_id), self.custom_strategies.all_vlans)\n interface_node = self.get_interface_config(interface_id, config)\n interface = self.node_to_interface(interface_node, config)\n\n if interface.port_mode is ACCESS or interface.port_mode is None:\n update_attributes.append(self.custom_strategies.get_interface_port_mode_update_element(\"trunk\"))\n\n if interface.access_vlan is not None:\n update_attributes.append(self.custom_strategies.get_delete_vlan_element())\n\n if len(update_attributes) > 0:\n update = Update()\n update.add_interface(self.custom_strategies.interface_update(interface_id, \"0\", update_attributes))\n\n self._push_interface_update(interface_id, update)\n\n def set_access_vlan(self, interface_id, vlan):\n update_attributes = []\n update_vlan_members = []\n\n config = self.query(all_interfaces, self.custom_strategies.all_vlans)\n\n self.custom_strategies.vlan_node(config, vlan)\n\n interface_node = self.get_interface_config(interface_id, config)\n interface = self.node_to_interface(interface_node, config)\n\n if interface.port_mode == TRUNK:\n raise InterfaceInWrongPortMode(\"trunk\")\n elif self.get_port_mode(interface_node) is None:\n update_attributes.append(self.custom_strategies.get_interface_port_mode_update_element(\"access\"))\n\n if interface.access_vlan != vlan:\n self.custom_strategies.update_vlan_members(interface_node, update_vlan_members, vlan)\n\n if update_attributes or update_vlan_members:\n update = Update()\n update.add_interface(self.custom_strategies.interface_update(interface_id, \"0\", update_attributes, update_vlan_members))\n\n try:\n self._push_interface_update(interface_id, update)\n except RPCError as e:\n if \"No vlan matches vlan tag\" in e.message:\n raise UnknownVlan(vlan)\n raise\n\n def unset_interface_access_vlan(self, interface_id):\n config = self.query(one_interface(interface_id), self.custom_strategies.all_vlans)\n interface_node = self.get_interface_config(interface_id, config)\n interface = self.node_to_interface(interface_node, config)\n\n if interface.port_mode == TRUNK:\n raise InterfaceInWrongPortMode(\"trunk\")\n\n if interface.access_vlan is not None:\n update = Update()\n update.add_interface(self.custom_strategies.interface_update(interface_id, \"0\", [to_ele('')]))\n\n self._push(update)\n else:\n raise AccessVlanNotSet(interface_id)\n\n def set_interface_native_vlan(self, interface_id, vlan):\n port_mode_node = None\n native_vlan_id_node = None\n\n config = self.query(all_interfaces, self.custom_strategies.all_vlans)\n\n self.custom_strategies.vlan_node(config, vlan)\n\n interface_node = self.get_interface_config(interface_id, config)\n\n interface = self.node_to_interface(interface_node, config)\n\n actual_port_mode = self.get_port_mode(interface_node)\n if actual_port_mode is ACCESS:\n raise InterfaceInWrongPortMode(\"access\")\n elif actual_port_mode is None:\n port_mode_node = self.custom_strategies.get_interface_port_mode_update_element(\"trunk\")\n\n if vlan in interface.trunk_vlans:\n raise VlanAlreadyInTrunk(vlan)\n elif interface.trunk_native_vlan != vlan:\n native_vlan_id_node = to_ele(\"{}\".format(vlan))\n\n if native_vlan_id_node is not None:\n\n interface = self.custom_strategies.interface_update(interface_id, \"0\", [port_mode_node] if port_mode_node is not None else [])\n self.custom_strategies.set_native_vlan_id_node(interface, native_vlan_id_node)\n update = Update()\n update.add_interface(interface)\n\n try:\n self._push_interface_update(interface_id, update)\n except RPCError as e:\n if \"No vlan matches vlan tag\" in e.message:\n raise UnknownVlan(vlan)\n raise\n\n def set_interface_auto_negotiation_state(self, interface_id, negotiation_state):\n content = to_ele(\"\"\"\n \n {0}\n \n \"\"\".format(interface_id))\n if negotiation_state == ON:\n content.append(to_ele(\"\"))\n else:\n content.append(to_ele(\"\"))\n update = Update()\n update.add_interface(content)\n\n self._push_interface_update(interface_id, update)\n\n def unset_interface_auto_negotiation_state(self, interface_id):\n config = self.query(one_interface(interface_id))\n interface_node = self.get_interface_config(interface_id, config)\n\n if interface_node is None:\n self._get_physical_interface(interface_id)\n return\n\n auto_negotiation_present = first(interface_node.xpath('ether-options/auto-negotiation')) is not None\n no_auto_negotiation_present = first(interface_node.xpath('ether-options/no-auto-negotiation')) is not None\n\n if auto_negotiation_present or no_auto_negotiation_present:\n content = to_ele(\"\"\"\n \n {0}\n \n \"\"\".format(interface_id))\n ether_options = to_ele(\"\")\n if auto_negotiation_present:\n ether_options.append(to_ele(\"\"))\n elif no_auto_negotiation_present:\n ether_options.append(to_ele(\"\"))\n update = Update()\n\n content.append(ether_options)\n update.add_interface(content)\n\n self._push_interface_update(interface_id, update)\n\n def reset_interface(self, interface_id):\n content = to_ele(\"\"\"\n \n {0}\n \n \"\"\".format(interface_id))\n update = Update()\n update.add_interface(content)\n\n self._push_interface_update(interface_id, update)\n\n def unset_interface_native_vlan(self, interface_id):\n config = self.query(one_interface(interface_id), self.custom_strategies.all_vlans)\n interface_node = self.get_interface_config(interface_id, config)\n interface = self.node_to_interface(interface_node, config)\n\n if interface.trunk_native_vlan is None:\n raise NativeVlanNotSet(interface_id)\n\n update = Update()\n update.add_interface(self.custom_strategies.interface_update(interface_id, \"0\", [to_ele(\"\")]))\n\n self._push(update)\n\n def add_trunk_vlan(self, interface_id, vlan):\n config = self.query(all_interfaces, self.custom_strategies.all_vlans)\n\n self.custom_strategies.vlan_node(config, vlan)\n\n interface_node = self.get_interface_config(interface_id, config)\n\n interface = self.node_to_interface(interface_node, config)\n\n actual_port_mode = self.get_port_mode(interface_node)\n\n if actual_port_mode is ACCESS or interface.access_vlan is not None:\n raise InterfaceInWrongPortMode(\"access\")\n\n if vlan not in interface.trunk_vlans:\n update = Update()\n update.add_interface(self.custom_strategies.interface_update(\n interface_id, \"0\",\n [self.custom_strategies.get_interface_port_mode_update_element(\"trunk\")] if actual_port_mode is None else None,\n [self.custom_strategies.get_vlan_member_update_element(vlan)]\n ))\n\n self._push_interface_update(interface_id, update)\n\n def remove_trunk_vlan(self, interface_id, vlan):\n config = self.query(all_interfaces, self.custom_strategies.all_vlans)\n interface_node = self.get_interface_config(interface_id, config)\n if interface_node is None:\n raise UnknownInterface(interface_id)\n\n interface = self.node_to_interface(interface_node, config)\n\n if interface.port_mode is ACCESS:\n raise InterfaceInWrongPortMode(\"access\")\n\n vlan_node = self.custom_strategies.vlan_node(config, vlan)\n vlan_name = first(vlan_node.xpath(\"name\")).text\n\n modifications = self.custom_strategies.craft_members_modification_to_remove_vlan(interface_node, vlan_name, vlan)\n if len(modifications) == 0:\n raise TrunkVlanNotSet(interface_id)\n\n update = Update()\n update.add_interface(self.custom_strategies.interface_update(interface_id, \"0\", vlan_members=modifications))\n\n self._push(update)\n\n def set_interface_description(self, interface_id, description):\n update = Update()\n update.add_interface(interface_main_update(interface_id, [\n to_ele(\"{}\".format(description))\n ]))\n\n try:\n self._push(update)\n except RPCError as e:\n self.logger.info(\"actual setting error was {}\".format(e))\n raise UnknownInterface(interface_id)\n\n def unset_interface_description(self, interface_id):\n update = Update()\n update.add_interface(interface_main_update(interface_id, [\n to_ele(\"\")\n ]))\n\n try:\n self._push(update)\n except RPCError as e:\n if e.severity != \"warning\":\n raise UnknownInterface(interface_id)\n\n def set_interface_mtu(self, interface_id, size):\n update = Update()\n update.add_interface(interface_main_update(interface_id, [\n to_ele(\"{}\".format(size))\n ]))\n\n try:\n self._push(update)\n except RPCError as e:\n self.logger.info(\"actual setting error was {}\".format(e))\n if \"Value {} is not within range\".format(size) in str(e):\n raise InvalidMtuSize(str(e))\n\n raise UnknownInterface(interface_id)\n\n def unset_interface_mtu(self, interface_id):\n update = Update()\n update.add_interface(interface_main_update(interface_id, [\n to_ele(\"\")\n ]))\n\n try:\n self._push(update)\n except RPCError as e:\n if e.severity != \"warning\":\n raise UnknownInterface(interface_id)\n\n def edit_interface_spanning_tree(self, interface_id, edge=None):\n config = self.query(one_interface(interface_id),\n one_protocol_interface(\"rstp\", self._for_protocol(interface_id)))\n\n if edge is not None:\n modifications = _compute_edge_state_modifications(interface_id, edge, config)\n\n if modifications:\n update = Update()\n update.add_protocol_interface(\"rstp\", to_ele(\"\"\"\n \n {}\n {}\n \n \"\"\".format(interface_id, \"\".join(modifications))))\n\n self._push_interface_update(interface_id, update)\n\n def set_interface_state(self, interface_id, state):\n update = Update()\n update.add_interface(interface_state_update(interface_id, state))\n\n try:\n self._push(update)\n except RPCError as e:", "answers": [" self.logger.info(\"actual setting error was {}\".format(e))"], "length": 1188, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "e4234e89-3cc0-4dbe-9ed4-f2fe584aeb04", "reasoning": "The method set_interface_state builds an update and attempts to push it inside a try/except block. Other similar methods (e.g., set_interface_description) log the RPCError and raise UnknownInterface. Following that pattern, the next line after 'except RPCError as e:' should log the error.", "reasoning_model_answer": "self.logger.info(\"actual setting error was {}\".format(e))", "assistant_with_reasoning": "\nThe method set_interface_state builds an update and attempts to push it inside a try/except block. Other similar methods (e.g., set_interface_description) log the RPCError and raise UnknownInterface. Following that pattern, the next line after 'except RPCError as e:' should log the error.\n\nself.logger.info(\"actual setting error was {}\".format(e))", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.903, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 20462, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "self.logger.info(\"actual setting error was {}\".format(e))", "score": 0.9, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/*\n * Copyright 2021 Google LLC All Rights Reserved.\n * Use of this source code is governed by a BSD-style\n * license that can be found in the LICENSE file or at\n * https://developers.google.com/open-source/licenses/bsd\n */\n\n// \n// Generated by the protocol buffer compiler. DO NOT EDIT!\n// source: google/api/config_change.proto\n// \n#pragma warning disable 1591, 0612, 3021\n#region Designer generated code\n\nusing pb = global::Google.Protobuf;\nusing pbc = global::Google.Protobuf.Collections;\nusing pbr = global::Google.Protobuf.Reflection;\nusing scg = global::System.Collections.Generic;\nnamespace Google.Api {\n\n /// Holder for reflection information generated from google/api/config_change.proto\n public static partial class ConfigChangeReflection {\n\n #region Descriptor\n /// File descriptor for google/api/config_change.proto\n public static pbr::FileDescriptor Descriptor {\n get { return descriptor; }\n }\n private static pbr::FileDescriptor descriptor;\n\n static ConfigChangeReflection() {\n byte[] descriptorData = global::System.Convert.FromBase64String(\n string.Concat(\n \"Ch5nb29nbGUvYXBpL2NvbmZpZ19jaGFuZ2UucHJvdG8SCmdvb2dsZS5hcGki\",\n \"lwEKDENvbmZpZ0NoYW5nZRIPCgdlbGVtZW50GAEgASgJEhEKCW9sZF92YWx1\",\n \"ZRgCIAEoCRIRCgluZXdfdmFsdWUYAyABKAkSKwoLY2hhbmdlX3R5cGUYBCAB\",\n \"KA4yFi5nb29nbGUuYXBpLkNoYW5nZVR5cGUSIwoHYWR2aWNlcxgFIAMoCzIS\",\n \"Lmdvb2dsZS5hcGkuQWR2aWNlIh0KBkFkdmljZRITCgtkZXNjcmlwdGlvbhgC\",\n \"IAEoCSpPCgpDaGFuZ2VUeXBlEhsKF0NIQU5HRV9UWVBFX1VOU1BFQ0lGSUVE\",\n \"EAASCQoFQURERUQQARILCgdSRU1PVkVEEAISDAoITU9ESUZJRUQQA0JxCg5j\",\n \"b20uZ29vZ2xlLmFwaUIRQ29uZmlnQ2hhbmdlUHJvdG9QAVpDZ29vZ2xlLmdv\",\n \"bGFuZy5vcmcvZ2VucHJvdG8vZ29vZ2xlYXBpcy9hcGkvY29uZmlnY2hhbmdl\",\n \"O2NvbmZpZ2NoYW5nZaICBEdBUEliBnByb3RvMw==\"));\n descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,\n new pbr::FileDescriptor[] { },\n new pbr::GeneratedClrTypeInfo(new[] {typeof(global::Google.Api.ChangeType), }, null, new pbr::GeneratedClrTypeInfo[] {\n new pbr::GeneratedClrTypeInfo(typeof(global::Google.Api.ConfigChange), global::Google.Api.ConfigChange.Parser, new[]{ \"Element\", \"OldValue\", \"NewValue\", \"ChangeType\", \"Advices\" }, null, null, null, null),\n new pbr::GeneratedClrTypeInfo(typeof(global::Google.Api.Advice), global::Google.Api.Advice.Parser, new[]{ \"Description\" }, null, null, null, null)\n }));\n }\n #endregion\n\n }\n #region Enums\n /// \n /// Classifies set of possible modifications to an object in the service\n /// configuration.\n /// \n public enum ChangeType {\n /// \n /// No value was provided.\n /// \n [pbr::OriginalName(\"CHANGE_TYPE_UNSPECIFIED\")] Unspecified = 0,\n /// \n /// The changed object exists in the 'new' service configuration, but not\n /// in the 'old' service configuration.\n /// \n [pbr::OriginalName(\"ADDED\")] Added = 1,\n /// \n /// The changed object exists in the 'old' service configuration, but not\n /// in the 'new' service configuration.\n /// \n [pbr::OriginalName(\"REMOVED\")] Removed = 2,\n /// \n /// The changed object exists in both service configurations, but its value\n /// is different.\n /// \n [pbr::OriginalName(\"MODIFIED\")] Modified = 3,\n }\n\n #endregion\n\n #region Messages\n /// \n /// Output generated from semantically comparing two versions of a service\n /// configuration.\n ///\n /// Includes detailed information about a field that have changed with\n /// applicable advice about potential consequences for the change, such as\n /// backwards-incompatibility.\n /// \n public sealed partial class ConfigChange : pb::IMessage\n #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE\n , pb::IBufferMessage\n #endif\n {\n private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new ConfigChange());\n private pb::UnknownFieldSet _unknownFields;\n [global::System.Diagnostics.DebuggerNonUserCodeAttribute]\n [global::System.CodeDom.Compiler.GeneratedCode(\"protoc\", null)]\n public static pb::MessageParser Parser { get { return _parser; } }\n\n [global::System.Diagnostics.DebuggerNonUserCodeAttribute]\n [global::System.CodeDom.Compiler.GeneratedCode(\"protoc\", null)]\n public static pbr::MessageDescriptor Descriptor {\n get { return global::Google.Api.ConfigChangeReflection.Descriptor.MessageTypes[0]; }\n }\n\n [global::System.Diagnostics.DebuggerNonUserCodeAttribute]\n [global::System.CodeDom.Compiler.GeneratedCode(\"protoc\", null)]\n pbr::MessageDescriptor pb::IMessage.Descriptor {\n get { return Descriptor; }\n }\n\n [global::System.Diagnostics.DebuggerNonUserCodeAttribute]\n [global::System.CodeDom.Compiler.GeneratedCode(\"protoc\", null)]\n public ConfigChange() {\n OnConstruction();\n }\n\n partial void OnConstruction();\n\n [global::System.Diagnostics.DebuggerNonUserCodeAttribute]\n [global::System.CodeDom.Compiler.GeneratedCode(\"protoc\", null)]\n public ConfigChange(ConfigChange other) : this() {\n element_ = other.element_;\n oldValue_ = other.oldValue_;\n newValue_ = other.newValue_;\n changeType_ = other.changeType_;\n advices_ = other.advices_.Clone();\n _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);\n }\n\n [global::System.Diagnostics.DebuggerNonUserCodeAttribute]\n [global::System.CodeDom.Compiler.GeneratedCode(\"protoc\", null)]\n public ConfigChange Clone() {\n return new ConfigChange(this);\n }\n\n /// Field number for the \"element\" field.\n public const int ElementFieldNumber = 1;\n private string element_ = \"\";\n /// \n /// Object hierarchy path to the change, with levels separated by a '.'\n /// character. For repeated fields, an applicable unique identifier field is\n /// used for the index (usually selector, name, or id). For maps, the term\n /// 'key' is used. If the field has no unique identifier, the numeric index\n /// is used.\n /// Examples:\n /// - visibility.rules[selector==\"google.LibraryService.ListBooks\"].restriction\n /// - quota.metric_rules[selector==\"google\"].metric_costs[key==\"reads\"].value\n /// - logging.producer_destinations[0]\n /// \n [global::System.Diagnostics.DebuggerNonUserCodeAttribute]\n [global::System.CodeDom.Compiler.GeneratedCode(\"protoc\", null)]\n public string Element {\n get { return element_; }\n set {\n element_ = pb::ProtoPreconditions.CheckNotNull(value, \"value\");\n }\n }\n\n /// Field number for the \"old_value\" field.\n public const int OldValueFieldNumber = 2;\n private string oldValue_ = \"\";\n /// \n /// Value of the changed object in the old Service configuration,\n /// in JSON format. This field will not be populated if ChangeType == ADDED.\n /// \n [global::System.Diagnostics.DebuggerNonUserCodeAttribute]\n [global::System.CodeDom.Compiler.GeneratedCode(\"protoc\", null)]\n public string OldValue {\n get { return oldValue_; }\n set {\n oldValue_ = pb::ProtoPreconditions.CheckNotNull(value, \"value\");\n }\n }\n\n /// Field number for the \"new_value\" field.\n public const int NewValueFieldNumber = 3;\n private string newValue_ = \"\";\n /// \n /// Value of the changed object in the new Service configuration,\n /// in JSON format. This field will not be populated if ChangeType == REMOVED.\n /// \n [global::System.Diagnostics.DebuggerNonUserCodeAttribute]\n [global::System.CodeDom.Compiler.GeneratedCode(\"protoc\", null)]\n public string NewValue {\n get { return newValue_; }\n set {\n newValue_ = pb::ProtoPreconditions.CheckNotNull(value, \"value\");\n }\n }\n\n /// Field number for the \"change_type\" field.\n public const int ChangeTypeFieldNumber = 4;\n private global::Google.Api.ChangeType changeType_ = global::Google.Api.ChangeType.Unspecified;\n /// \n /// The type for this change, either ADDED, REMOVED, or MODIFIED.\n /// \n [global::System.Diagnostics.DebuggerNonUserCodeAttribute]\n [global::System.CodeDom.Compiler.GeneratedCode(\"protoc\", null)]\n public global::Google.Api.ChangeType ChangeType {\n get { return changeType_; }\n set {\n changeType_ = value;\n }\n }\n\n /// Field number for the \"advices\" field.\n public const int AdvicesFieldNumber = 5;\n private static readonly pb::FieldCodec _repeated_advices_codec\n = pb::FieldCodec.ForMessage(42, global::Google.Api.Advice.Parser);\n private readonly pbc::RepeatedField advices_ = new pbc::RepeatedField();\n /// \n /// Collection of advice provided for this change, useful for determining the\n /// possible impact of this change.\n /// \n [global::System.Diagnostics.DebuggerNonUserCodeAttribute]\n [global::System.CodeDom.Compiler.GeneratedCode(\"protoc\", null)]\n public pbc::RepeatedField Advices {\n get { return advices_; }\n }\n\n [global::System.Diagnostics.DebuggerNonUserCodeAttribute]\n [global::System.CodeDom.Compiler.GeneratedCode(\"protoc\", null)]\n public override bool Equals(object other) {\n return Equals(other as ConfigChange);\n }\n\n [global::System.Diagnostics.DebuggerNonUserCodeAttribute]\n [global::System.CodeDom.Compiler.GeneratedCode(\"protoc\", null)]\n public bool Equals(ConfigChange other) {\n if (ReferenceEquals(other, null)) {\n return false;\n }\n if (ReferenceEquals(other, this)) {\n return true;\n }\n if (Element != other.Element) return false;\n if (OldValue != other.OldValue) return false;\n if (NewValue != other.NewValue) return false;\n if (ChangeType != other.ChangeType) return false;\n if(!advices_.Equals(other.advices_)) return false;\n return Equals(_unknownFields, other._unknownFields);\n }\n\n [global::System.Diagnostics.DebuggerNonUserCodeAttribute]\n [global::System.CodeDom.Compiler.GeneratedCode(\"protoc\", null)]\n public override int GetHashCode() {\n int hash = 1;\n if (Element.Length != 0) hash ^= Element.GetHashCode();\n if (OldValue.Length != 0) hash ^= OldValue.GetHashCode();\n if (NewValue.Length != 0) hash ^= NewValue.GetHashCode();\n if (ChangeType != global::Google.Api.ChangeType.Unspecified) hash ^= ChangeType.GetHashCode();\n hash ^= advices_.GetHashCode();\n if (_unknownFields != null) {\n hash ^= _unknownFields.GetHashCode();\n }\n return hash;\n }\n\n [global::System.Diagnostics.DebuggerNonUserCodeAttribute]\n [global::System.CodeDom.Compiler.GeneratedCode(\"protoc\", null)]\n public override string ToString() {\n return pb::JsonFormatter.ToDiagnosticString(this);\n }\n\n [global::System.Diagnostics.DebuggerNonUserCodeAttribute]\n [global::System.CodeDom.Compiler.GeneratedCode(\"protoc\", null)]\n public void WriteTo(pb::CodedOutputStream output) {\n #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE\n output.WriteRawMessage(this);\n #else\n if (Element.Length != 0) {\n output.WriteRawTag(10);\n output.WriteString(Element);\n }\n if (OldValue.Length != 0) {\n output.WriteRawTag(18);\n output.WriteString(OldValue);\n }\n if (NewValue.Length != 0) {\n output.WriteRawTag(26);\n output.WriteString(NewValue);\n }\n if (ChangeType != global::Google.Api.ChangeType.Unspecified) {\n output.WriteRawTag(32);\n output.WriteEnum((int) ChangeType);\n }\n advices_.WriteTo(output, _repeated_advices_codec);\n if (_unknownFields != null) {\n _unknownFields.WriteTo(output);\n }\n #endif\n }\n\n #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE\n [global::System.Diagnostics.DebuggerNonUserCodeAttribute]\n [global::System.CodeDom.Compiler.GeneratedCode(\"protoc\", null)]\n void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) {\n if (Element.Length != 0) {\n output.WriteRawTag(10);\n output.WriteString(Element);\n }\n if (OldValue.Length != 0) {\n output.WriteRawTag(18);\n output.WriteString(OldValue);\n }\n if (NewValue.Length != 0) {\n output.WriteRawTag(26);\n output.WriteString(NewValue);\n }\n if (ChangeType != global::Google.Api.ChangeType.Unspecified) {\n output.WriteRawTag(32);\n output.WriteEnum((int) ChangeType);\n }\n advices_.WriteTo(ref output, _repeated_advices_codec);\n if (_unknownFields != null) {\n _unknownFields.WriteTo(ref output);\n }\n }\n #endif\n\n [global::System.Diagnostics.DebuggerNonUserCodeAttribute]\n [global::System.CodeDom.Compiler.GeneratedCode(\"protoc\", null)]\n public int CalculateSize() {\n int size = 0;\n if (Element.Length != 0) {\n size += 1 + pb::CodedOutputStream.ComputeStringSize(Element);\n }\n if (OldValue.Length != 0) {\n size += 1 + pb::CodedOutputStream.ComputeStringSize(OldValue);\n }\n if (NewValue.Length != 0) {\n size += 1 + pb::CodedOutputStream.ComputeStringSize(NewValue);\n }\n if (ChangeType != global::Google.Api.ChangeType.Unspecified) {\n size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) ChangeType);\n }\n size += advices_.CalculateSize(_repeated_advices_codec);\n if (_unknownFields != null) {\n size += _unknownFields.CalculateSize();\n }\n return size;\n }\n\n [global::System.Diagnostics.DebuggerNonUserCodeAttribute]\n [global::System.CodeDom.Compiler.GeneratedCode(\"protoc\", null)]\n public void MergeFrom(ConfigChange other) {\n if (other == null) {\n return;\n }\n if (other.Element.Length != 0) {\n Element = other.Element;\n }\n if (other.OldValue.Length != 0) {\n OldValue = other.OldValue;\n }\n if (other.NewValue.Length != 0) {\n NewValue = other.NewValue;\n }\n if (other.ChangeType != global::Google.Api.ChangeType.Unspecified) {\n ChangeType = other.ChangeType;\n }\n advices_.Add(other.advices_);\n _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);\n }\n\n [global::System.Diagnostics.DebuggerNonUserCodeAttribute]\n [global::System.CodeDom.Compiler.GeneratedCode(\"protoc\", null)]\n public void MergeFrom(pb::CodedInputStream input) {\n #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE\n input.ReadRawMessage(this);\n #else\n uint tag;\n while ((tag = input.ReadTag()) != 0) {\n switch(tag) {\n default:\n _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);\n break;\n case 10: {\n Element = input.ReadString();\n break;\n }\n case 18: {\n OldValue = input.ReadString();\n break;\n }\n case 26: {\n NewValue = input.ReadString();\n break;\n }\n case 32: {", "answers": [" ChangeType = (global::Google.Api.ChangeType) input.ReadEnum();"], "length": 1244, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "9185ba80-72bc-41c4-88b2-17440ecd88c1", "reasoning": "In the MergeFrom method's switch, each case reads a field from the input stream. For tag 32, which corresponds to the ChangeType enum, the generated code reads the enum value and assigns it to the ChangeType property. The next line after the case label is the assignment using input.ReadEnum().", "reasoning_model_answer": "ChangeType = (global::Google.Api.ChangeType) input.ReadEnum();", "assistant_with_reasoning": "\nIn the MergeFrom method's switch, each case reads a field from the input stream. For tag 32, which corresponds to the ChangeType enum, the generated code reads the enum value and assigns it to the ChangeType property. The next line after the case label is the assignment using input.ReadEnum().\n\nChangeType = (global::Google.Api.ChangeType) input.ReadEnum();", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 2.65, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 15563, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "ChangeType = (global::Google.Api.ChangeType) input.ReadEnum();", "score": 0.91, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "package com.jfeinstein.jazzyviewpager;\n\nimport java.util.HashMap;\nimport java.util.LinkedHashMap;\n\nimport android.annotation.TargetApi;\nimport android.content.Context;\nimport android.content.res.TypedArray;\nimport android.graphics.Camera;\nimport android.graphics.Color;\nimport android.graphics.Matrix;\nimport android.os.Build;\n\n\nimport android.support.v4.view.PagerAdapter;\nimport android.support.v4.view.ViewPager;\nimport android.util.AttributeSet;\nimport android.util.Log;\nimport android.view.MotionEvent;\nimport android.view.View;\nimport com.manniu.manniu.R;\nimport com.nineoldandroids.view.ViewHelper;\n\npublic class JazzyViewPager extends ViewPager {\n\n\tpublic static final String TAG = \"JazzyViewPager\";\n\t\n\tprivate boolean mEnabled = true;\n\tprivate boolean mFadeEnabled = false;\n\tprivate boolean mOutlineEnabled = false;\n\tpublic static int sOutlineColor = Color.WHITE;\n\tprivate TransitionEffect mEffect = TransitionEffect.Standard;\n\t\n\tprivate HashMap mObjs = new LinkedHashMap();\n\n\tprivate static final float SCALE_MAX = 0.5f;\n\tprivate static final float ZOOM_MAX = 0.5f;\n\tprivate static final float ROT_MAX = 15.0f;\n\n\tpublic enum TransitionEffect {\n\t\tStandard,\n\t\tTablet,\n\t\tCubeIn,\n\t\tCubeOut,\n\t\tFlipVertical,\n\t\tFlipHorizontal,\n\t\tStack,\n\t\tZoomIn,\n\t\tZoomOut,\n\t\tRotateUp,\n\t\tRotateDown,\n\t\tAccordion\n\t}\n\n\tprivate static final boolean API_11;\n\tstatic {\n\t\tAPI_11 = Build.VERSION.SDK_INT >= 11;\n\t}\n\n\tpublic JazzyViewPager(Context context) {\n\t\tthis(context, null);\n\t}\n\n\t@SuppressWarnings(\"incomplete-switch\")\n\tpublic JazzyViewPager(Context context, AttributeSet attrs) {\n\t\t\n\t\tsuper(context, attrs);\n\t\tsetClipChildren(false);\n\t\t// now style everything!\n\t\tTypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.JazzyViewPager);\n\t\tint effect = ta.getInt(R.styleable.JazzyViewPager_style, 0);\n\t\tString[] transitions = getResources().getStringArray(R.array.jazzy_effects);\n\t\tsetTransitionEffect(TransitionEffect.valueOf(transitions[effect]));\n\t\tsetFadeEnabled(ta.getBoolean(R.styleable.JazzyViewPager_fadeEnabled, false));\n\t\tsetOutlineEnabled(ta.getBoolean(R.styleable.JazzyViewPager_outlineEnabled, false));\n\t\tsetOutlineColor(ta.getColor(R.styleable.JazzyViewPager_outlineColor, Color.WHITE));\n\t\tswitch (mEffect) {\n\t\tcase Stack:\n\t\tcase ZoomOut:\n\t\t\tsetFadeEnabled(true);\n\t\t}\n\t\tta.recycle();\n\t}\n\n\tpublic void setTransitionEffect(TransitionEffect effect) {\n\t\tmEffect = effect;\n//\t\treset();\n\t}\n\n\tpublic void setPagingEnabled(boolean enabled) {\n\t\tmEnabled = enabled;\n\t}\n\n\tpublic void setFadeEnabled(boolean enabled) {\n\t\tmFadeEnabled = enabled;\n\t}\n\t\n\tpublic boolean getFadeEnabled() {\n\t\treturn mFadeEnabled;\n\t}\n\n\tpublic void setOutlineEnabled(boolean enabled) {\n\t\tmOutlineEnabled = enabled;\n\t\twrapWithOutlines();\n\t}\n\n\tpublic void setOutlineColor(int color) {\n\t\tsOutlineColor = color;\n\t}\n\n\tprivate void wrapWithOutlines() {\n\t\tfor (int i = 0; i < getChildCount(); i++) {\n\t\t\tView v = getChildAt(i);\n\t\t\tif (!(v instanceof OutlineContainer)) {\n\t\t\t\tremoveView(v);\n\t\t\t\tsuper.addView(wrapChild(v), i);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate View wrapChild(View child) {\n\t\tif (!mOutlineEnabled || child instanceof OutlineContainer) return child;\n\t\tOutlineContainer out = new OutlineContainer(getContext());\n\t\tout.setLayoutParams(generateDefaultLayoutParams());\n\t\tchild.setLayoutParams(new OutlineContainer.LayoutParams(\n\t\t\t\tLayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));\n\t\tout.addView(child);\n\t\treturn out;\n\t}\n\n\tpublic void addView(View child) {\n\t\tsuper.addView(wrapChild(child));\n\t}\n\n\tpublic void addView(View child, int index) {\n\t\tsuper.addView(wrapChild(child), index);\n\t}\n\n\tpublic void addView(View child, LayoutParams params) {\n\t\tsuper.addView(wrapChild(child), params);\n\t}\n\n\tpublic void addView(View child, int width, int height) {\n\t\tsuper.addView(wrapChild(child), width, height);\n\t}\n\n\tpublic void addView(View child, int index, LayoutParams params) {\n\t\tsuper.addView(wrapChild(child), index, params);\n\t}\n\n\t@Override\n\tpublic boolean onInterceptTouchEvent(MotionEvent arg0) {\n\t\treturn mEnabled ? super.onInterceptTouchEvent(arg0) : false;\n\t}\n\n\tprivate State mState;\n\tprivate int oldPage;\n\n\tprivate View mLeft;\n\tprivate View mRight;\n\tprivate float mRot;\n\tprivate float mTrans;\n\tprivate float mScale;\n\n\tprivate enum State {\n\t\tIDLE,\n\t\tGOING_LEFT,\n\t\tGOING_RIGHT\n\t}\n\t\n//\tpublic void reset() {\n//\tresetPrivate();\n//\tint curr = getCurrentItem();\n//\tonPageScrolled(curr, 0.0f, 0);\n//}\n//\n//private void resetPrivate() {\n//\tfor (int i = 0; i < getChildCount(); i++) {\n//\t\tView v = getChildAt(i);\n//\t\t//\t\t\tViewHelper.setRotation(v, -ViewHelper.getRotation(v));\n//\t\t//\t\t\tViewHelper.setRotationX(v, -ViewHelper.getRotationX(v));\n//\t\t//\t\t\tViewHelper.setRotationY(v, -ViewHelper.getRotationY(v));\n//\t\t//\n//\t\t//\t\t\tViewHelper.setTranslationX(v, -ViewHelper.getTranslationX(v));\n//\t\t//\t\t\tViewHelper.setTranslationY(v, -ViewHelper.getTranslationY(v));\n//\n//\t\tViewHelper.setRotation(v, 0);\n//\t\tViewHelper.setRotationX(v, 0);\n//\t\tViewHelper.setRotationY(v, 0);\n//\n//\t\tViewHelper.setTranslationX(v, 0);\n//\t\tViewHelper.setTranslationY(v, 0);\n//\n//\t\tViewHelper.setAlpha(v, 1.0f);\n//\n//\t\tViewHelper.setScaleX(v, 1.0f);\n//\t\tViewHelper.setScaleY(v, 1.0f);\n//\n//\t\tViewHelper.setPivotX(v, 0);\n//\t\tViewHelper.setPivotY(v, 0);\n//\n//\t\tlogState(v, \"Child \" + i);\n//\t}\n//}\n\n\tprivate void logState(View v, String title) {\n\t\tLog.v(TAG, title + \": ROT (\" + ViewHelper.getRotation(v) + \", \" +\n\t\t\t\tViewHelper.getRotationX(v) + \", \" +\n\t\t\t\tViewHelper.getRotationY(v) + \"), TRANS (\" +\n\t\t\t\tViewHelper.getTranslationX(v) + \", \" +\n\t\t\t\tViewHelper.getTranslationY(v) + \"), SCALE (\" +\n\t\t\t\tViewHelper.getScaleX(v) + \", \" + \n\t\t\t\tViewHelper.getScaleY(v) + \"), ALPHA \" +\n\t\t\t\tViewHelper.getAlpha(v));\n\t}\n\n\tprotected void animateScroll(int position, float positionOffset) {\n\t\tif (mState != State.IDLE) {\n\t\t\tmRot = (float)(1-Math.cos(2*Math.PI*positionOffset))/2*30.0f;\n\t\t\tViewHelper.setRotationY(this, mState == State.GOING_RIGHT ? mRot : -mRot);\n\t\t\tViewHelper.setPivotX(this, getMeasuredWidth()*0.5f);\n\t\t\tViewHelper.setPivotY(this, getMeasuredHeight()*0.5f);\n\t\t}\n\t}\n\n\tprotected void animateTablet(View left, View right, float positionOffset) {\t\t\n\t\tif (mState != State.IDLE) {\n\t\t\tif (left != null) {\n\t\t\t\tmanageLayer(left, true);\n\t\t\t\tmRot = 30.0f * positionOffset;\n\t\t\t\tmTrans = getOffsetXForRotation(mRot, left.getMeasuredWidth(),\n\t\t\t\t\t\tleft.getMeasuredHeight());\n\t\t\t\tViewHelper.setPivotX(left, left.getMeasuredWidth()/2);\n\t\t\t\tViewHelper.setPivotY(left, left.getMeasuredHeight()/2);\n\t\t\t\tViewHelper.setTranslationX(left, mTrans);\n\t\t\t\tViewHelper.setRotationY(left, mRot);\n\t\t\t\tlogState(left, \"Left\");\n\t\t\t}\n\t\t\tif (right != null) {\n\t\t\t\tmanageLayer(right, true);\n\t\t\t\tmRot = -30.0f * (1-positionOffset);\n\t\t\t\tmTrans = getOffsetXForRotation(mRot, right.getMeasuredWidth(), \n\t\t\t\t\t\tright.getMeasuredHeight());\n\t\t\t\tViewHelper.setPivotX(right, right.getMeasuredWidth()*0.5f);\n\t\t\t\tViewHelper.setPivotY(right, right.getMeasuredHeight()*0.5f);\n\t\t\t\tViewHelper.setTranslationX(right, mTrans);\n\t\t\t\tViewHelper.setRotationY(right, mRot);\n\t\t\t\tlogState(right, \"Right\");\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate void animateCube(View left, View right, float positionOffset, boolean in) {\n\t\tif (mState != State.IDLE) {\n\t\t\tif (left != null) {\n\t\t\t\tmanageLayer(left, true);\n\t\t\t\tmRot = (in ? 90.0f : -90.0f) * positionOffset;\n\t\t\t\tViewHelper.setPivotX(left, left.getMeasuredWidth());\n\t\t\t\tViewHelper.setPivotY(left, left.getMeasuredHeight()*0.5f);\n\t\t\t\tViewHelper.setRotationY(left, mRot);\n\t\t\t}\n\t\t\tif (right != null) {\n\t\t\t\tmanageLayer(right, true);\n\t\t\t\tmRot = -(in ? 90.0f : -90.0f) * (1-positionOffset);\n\t\t\t\tViewHelper.setPivotX(right, 0);\n\t\t\t\tViewHelper.setPivotY(right, right.getMeasuredHeight()*0.5f);\n\t\t\t\tViewHelper.setRotationY(right, mRot);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate void animateAccordion(View left, View right, float positionOffset) {\n\t\tif (mState != State.IDLE) {\n\t\t\tif (left != null) {\n\t\t\t\tmanageLayer(left, true);\n\t\t\t\tViewHelper.setPivotX(left, left.getMeasuredWidth());\n\t\t\t\tViewHelper.setPivotY(left, 0);\n\t\t\t\tViewHelper.setScaleX(left, 1-positionOffset);\n\t\t\t}\n\t\t\tif (right != null) {\n\t\t\t\tmanageLayer(right, true);\n\t\t\t\tViewHelper.setPivotX(right, 0);\n\t\t\t\tViewHelper.setPivotY(right, 0);\n\t\t\t\tViewHelper.setScaleX(right, positionOffset);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate void animateZoom(View left, View right, float positionOffset, boolean in) {\n\t\tif (mState != State.IDLE) {\n\t\t\tif (left != null) {\n\t\t\t\tmanageLayer(left, true);\n\t\t\t\tmScale = in ? ZOOM_MAX + (1-ZOOM_MAX)*(1-positionOffset) :\n\t\t\t\t\t1+ZOOM_MAX - ZOOM_MAX*(1-positionOffset);\n\t\t\t\tViewHelper.setPivotX(left, left.getMeasuredWidth()*0.5f);\n\t\t\t\tViewHelper.setPivotY(left, left.getMeasuredHeight()*0.5f);\n\t\t\t\tViewHelper.setScaleX(left, mScale);\n\t\t\t\tViewHelper.setScaleY(left, mScale);\n\t\t\t}\n\t\t\tif (right != null) {\n\t\t\t\tmanageLayer(right, true);\n\t\t\t\tmScale = in ? ZOOM_MAX + (1-ZOOM_MAX)*positionOffset :\n\t\t\t\t\t1+ZOOM_MAX - ZOOM_MAX*positionOffset;\n\t\t\t\tViewHelper.setPivotX(right, right.getMeasuredWidth()*0.5f);\n\t\t\t\tViewHelper.setPivotY(right, right.getMeasuredHeight()*0.5f);\n\t\t\t\tViewHelper.setScaleX(right, mScale);\n\t\t\t\tViewHelper.setScaleY(right, mScale);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate void animateRotate(View left, View right, float positionOffset, boolean up) {\n\t\tif (mState != State.IDLE) {\n\t\t\tif (left != null) {\n\t\t\t\tmanageLayer(left, true);\n\t\t\t\tmRot = (up ? 1 : -1) * (ROT_MAX * positionOffset);\n\t\t\t\tmTrans = (up ? -1 : 1) * (float) (getMeasuredHeight() - getMeasuredHeight()*Math.cos(mRot*Math.PI/180.0f));\n\t\t\t\tViewHelper.setPivotX(left, left.getMeasuredWidth()*0.5f);\n\t\t\t\tViewHelper.setPivotY(left, up ? 0 : left.getMeasuredHeight());\n\t\t\t\tViewHelper.setTranslationY(left, mTrans);\n\t\t\t\tViewHelper.setRotation(left, mRot);\n\t\t\t}\n\t\t\tif (right != null) {\n\t\t\t\tmanageLayer(right, true);\n\t\t\t\tmRot = (up ? 1 : -1) * (-ROT_MAX + ROT_MAX*positionOffset);\n\t\t\t\tmTrans = (up ? -1 : 1) * (float) (getMeasuredHeight() - getMeasuredHeight()*Math.cos(mRot*Math.PI/180.0f));\n\t\t\t\tViewHelper.setPivotX(right, right.getMeasuredWidth()*0.5f);\n\t\t\t\tViewHelper.setPivotY(right, up ? 0 : right.getMeasuredHeight());\n\t\t\t\tViewHelper.setTranslationY(right, mTrans);\n\t\t\t\tViewHelper.setRotation(right, mRot);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate void animateFlipHorizontal(View left, View right, float positionOffset, int positionOffsetPixels) {\n\t\tif (mState != State.IDLE) {\n\t\t\tif (left != null) {\n\t\t\t\tmanageLayer(left, true);\n\t\t\t\tmRot = 180.0f * positionOffset;\n\t\t\t\tif (mRot > 90.0f) {\n\t\t\t\t\tleft.setVisibility(View.INVISIBLE);\n\t\t\t\t} else {\n\t\t\t\t\tif (left.getVisibility() == View.INVISIBLE)\n\t\t\t\t\t\tleft.setVisibility(View.VISIBLE);\n\t\t\t\t\tmTrans = positionOffsetPixels;\n\t\t\t\t\tViewHelper.setPivotX(left, left.getMeasuredWidth()*0.5f);\n\t\t\t\t\tViewHelper.setPivotY(left, left.getMeasuredHeight()*0.5f);\n\t\t\t\t\tViewHelper.setTranslationX(left, mTrans);\n\t\t\t\t\tViewHelper.setRotationY(left, mRot);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (right != null) {\n\t\t\t\tmanageLayer(right, true);\n\t\t\t\tmRot = -180.0f * (1-positionOffset);\n\t\t\t\tif (mRot < -90.0f) {\n\t\t\t\t\tright.setVisibility(View.INVISIBLE);\n\t\t\t\t} else {\n\t\t\t\t\tif (right.getVisibility() == View.INVISIBLE)\n\t\t\t\t\t\tright.setVisibility(View.VISIBLE);\n\t\t\t\t\tmTrans = -getWidth()-getPageMargin()+positionOffsetPixels;\n\t\t\t\t\tViewHelper.setPivotX(right, right.getMeasuredWidth()*0.5f);\n\t\t\t\t\tViewHelper.setPivotY(right, right.getMeasuredHeight()*0.5f);\n\t\t\t\t\tViewHelper.setTranslationX(right, mTrans);\n\t\t\t\t\tViewHelper.setRotationY(right, mRot);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t\n\tprivate void animateFlipVertical(View left, View right, float positionOffset, int positionOffsetPixels) {\n\t\tif(mState != State.IDLE) {\n\t\t\tif (left != null) {\n\t\t\t\tmanageLayer(left, true);\n\t\t\t\tmRot = 180.0f * positionOffset;\n\t\t\t\tif (mRot > 90.0f) {\n\t\t\t\t\tleft.setVisibility(View.INVISIBLE);\n\t\t\t\t} else {\n\t\t\t\t\tif (left.getVisibility() == View.INVISIBLE)\n\t\t\t\t\t\tleft.setVisibility(View.VISIBLE);\n\t\t\t\t\tmTrans = positionOffsetPixels;\n\t\t\t\t\tViewHelper.setPivotX(left, left.getMeasuredWidth()*0.5f);\n\t\t\t\t\tViewHelper.setPivotY(left, left.getMeasuredHeight()*0.5f);", "answers": ["\t\t\t\t\tViewHelper.setTranslationX(left, mTrans);"], "length": 1086, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "919483fb-fc1f-4127-8ba8-3a8788aca5fb", "reasoning": "The method animateFlipVertical mirrors animateFlipHorizontal but flips vertically. After setting the pivot points for the left view, the next step is to apply the translation along the Y axis before rotating around the X axis. Therefore the next line sets the Y translation using ViewHelper.", "reasoning_model_answer": "ViewHelper.setTranslationY(left, mTrans);", "assistant_with_reasoning": "\nThe method animateFlipVertical mirrors animateFlipHorizontal but flips vertically. After setting the pivot points for the left view, the next step is to apply the translation along the Y axis before rotating around the X axis. Therefore the next line sets the Y translation using ViewHelper.\n\nViewHelper.setTranslationY(left, mTrans);", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.104, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 11932, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "ViewHelper.setTranslationY(left, mTrans);", "score": 0.92, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "///////////////////////////////////////////////////////////////////////////////////////\n// Copyright (C) 2006-2019 Esper Team. All rights reserved. /\n// http://esper.codehaus.org /\n// ---------------------------------------------------------------------------------- /\n// The software in this package is published under the terms of the GPL license /\n// a copy of which has been included with this distribution in the license.txt file. /\n///////////////////////////////////////////////////////////////////////////////////////\n\nusing System;\nusing System.Collections.Concurrent;\nusing System.Collections.Generic;\nusing System.Linq;\n\nusing com.espertech.esper.common.client;\nusing com.espertech.esper.common.client.serde;\nusing com.espertech.esper.common.client.variable;\nusing com.espertech.esper.common.@internal.epl.variable.compiletime;\nusing com.espertech.esper.common.@internal.@event.core;\nusing com.espertech.esper.common.@internal.schedule;\nusing com.espertech.esper.common.@internal.util;\nusing com.espertech.esper.compat;\nusing com.espertech.esper.compat.collections;\nusing com.espertech.esper.compat.logging;\nusing com.espertech.esper.compat.threading.locks;\n\nusing static com.espertech.esper.common.@internal.context.util.StatementCPCacheService;\n\nnamespace com.espertech.esper.common.@internal.epl.variable.core\n{\n /// \n /// Variables service for reading and writing variables, and for setting a version number for the current thread to\n /// consider variables for.\n /// \n /// Consider a statement as follows: select * from MyEvent as A where A.val > var1 and A.val2 > var1 and\n /// A.val3\n /// > var2\n /// \n /// \n /// Upon statement execution we need to guarantee that the same atomic value for all variables is applied for all\n /// variable reads (by expressions typically) within the statement.\n /// \n /// \n /// Designed to support:\n /// however writes are very fast (entry to collection plus increment an int) and therefore blocking should not be\n /// an\n /// issue\n /// \n /// \n /// As an alternative to a version-based design, a read-lock for the variable space could also be used, with the\n /// following\n /// disadvantages: The write lock may just not be granted unless fair locks are used which are more expensive; And\n /// a read-lock is more expensive to acquire for multiple CPUs; A thread-local is still need to deal with\n /// \"set var1=3, var2=var1+1\" assignments where the new uncommitted value must be visible in the local evaluation.\n /// \n /// \n /// Every new write to a variable creates a new version. Thus when reading variables, readers can ignore newer\n /// versions\n /// and a read lock is not required in most circumstances.\n /// \n /// \n /// This algorithm works as follows:\n /// \n /// \n /// A thread processing an event into the runtime via sendEvent() calls the \"setLocalVersion\" method once\n /// before processing a statement that has variables.\n /// This places into a threadlocal variable the current version number, say version 570.\n /// \n /// \n /// A statement that reads a variable has an variable node that has a VariableReader handle\n /// obtained during validation (example).\n /// \n /// \n /// The VariableReader takes the version from the threadlocal (570) and compares the version number with the\n /// version numbers held for the variable.\n /// If the current version is same or lower (520, as old or older) then the threadlocal version,\n /// then use the current value.\n /// If the current version is higher (571, newer) then the threadlocal version, then go to the prior value.\n /// Use the prior value until a version is found that as old or older then the threadlocal version.\n /// \n /// \n /// If no version can be found that is old enough, output a warning and return the newest version.\n /// This should not happen, unless a thread is executing for very long within a single statement such that\n /// lifetime-old-version time period passed before the thread asks for variable values.\n /// \n /// \n /// As version numbers are counted up they may reach a boundary. Any write transaction after the boundary\n /// is reached performs a roll-over. In a roll-over, all variables version lists are\n /// newly created and any existing threads that read versions go against a (old) high-collection,\n /// while new threads reading the reset version go against a new low-collection.\n /// \n /// \n /// The class also allows an optional state handler to be plugged in to handle persistence for variable state.\n /// The state handler gets invoked when a variable changes value, and when a variable gets created\n /// to obtain the current value from persistence, if any.\n /// \n /// \n public class VariableManagementServiceImpl : VariableManagementService\n {\n /// \n /// Sets the boundary above which a reader considers the high-version list of variable values.\n /// For use in roll-over when the current version number overflows the ROLLOVER_WRITER_BOUNDARY.\n /// \n internal const int ROLLOVER_READER_BOUNDARY = int.MaxValue - 100000;\n\n /// \n /// Applicable for each variable if more then the number of versions accumulated, check\n /// timestamps to determine if a version can be expired.\n /// \n internal const int HIGH_WATERMARK_VERSIONS = 50;\n\n private static readonly ILog Log = LogManager.GetLogger(typeof(VariableManagementServiceImpl));\n\n // Each variable and a context-partition id may have a set of callbacks to invoke when the variable changes\n private readonly List>> changeCallbacksPerCP;\n\n // Keep the variable list\n private readonly EventBeanTypedEventFactory eventBeanTypedEventFactory;\n\n // Number of milliseconds that old versions of a variable are allowed to live\n private readonly long millisecondLifetimeOldVersions;\n\n // Write lock taken on write of any variable; and on read of older versions\n private readonly TimeProvider timeProvider;\n\n // Each variable has an index number, a context-partition id, a current version and a list of values\n private readonly List> variableVersionsPerCP;\n private int currentVariableNumber;\n\n private volatile int currentVersionNumber;\n\n // Thread-local for the visible version per thread\n private VariableVersionThreadLocal versionThreadLocal = new VariableVersionThreadLocal();\n\n /// \n /// Ctor.\n /// \n /// number of milliseconds a version may hang around before expiry\n /// provides the current time\n /// a optional plug-in that may store variable state and retrieve state upon creation\n /// event adapters\n public VariableManagementServiceImpl(\n IReaderWriterLockManager readerWriterLockManager,\n long millisecondLifetimeOldVersions,\n TimeProvider timeProvider,\n EventBeanTypedEventFactory eventBeanTypedEventFactory,\n VariableStateNonConstHandler optionalStateHandler)\n : this(readerWriterLockManager, 0, millisecondLifetimeOldVersions, timeProvider, eventBeanTypedEventFactory, optionalStateHandler)\n {\n }\n\n /// \n /// Ctor.\n /// \n /// the first version number to start from\n /// number of milliseconds a version may hang around before expiry\n /// provides the current time\n /// a optional plug-in that may store variable state and retrieve state upon creation\n /// for finding event types\n protected VariableManagementServiceImpl(\n IReaderWriterLockManager readerWriterLockManager,\n int startVersion,\n long millisecondLifetimeOldVersions,\n TimeProvider timeProvider,\n EventBeanTypedEventFactory eventBeanTypedEventFactory,\n VariableStateNonConstHandler optionalStateHandler)\n {\n this.millisecondLifetimeOldVersions = millisecondLifetimeOldVersions;\n this.timeProvider = timeProvider;\n this.eventBeanTypedEventFactory = eventBeanTypedEventFactory;\n OptionalStateHandler = optionalStateHandler;\n DeploymentsWithVariables = new Dictionary().WithNullKeySupport();\n ReadWriteLock = readerWriterLockManager.CreateLock(GetType());\n variableVersionsPerCP = new List>();\n changeCallbacksPerCP = new List>>();\n currentVersionNumber = startVersion;\n }\n\n public void Destroy()\n {\n versionThreadLocal = new VariableVersionThreadLocal();\n }\n\n public void SetLocalVersion()\n {\n versionThreadLocal.CurrentThread.Version = currentVersionNumber;\n }\n\n public void RegisterCallback(\n string deploymentId,\n string variableName,\n int agentInstanceId,\n VariableChangeCallback variableChangeCallback)\n {\n var entry = DeploymentsWithVariables.Get(deploymentId);\n\n var variable = entry?.GetVariable(variableName);\n if (variable == null) {\n return;\n }\n\n var cps = changeCallbacksPerCP[variable.VariableNumber];\n if (cps == null) {\n cps = new Dictionary>();", "answers": [" changeCallbacksPerCP[variable.VariableNumber] = cps;"], "length": 1091, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "88ed6000-d617-48a2-ad2e-ec9b5c7c384a", "reasoning": "The code is inside RegisterCallback. It retrieves the callbacks dictionary for the variable number. If the entry is null, it creates a new Dictionary>. The next logical step is to store this newly created dictionary back into the changeCallbacksPerCP list at the variable's index, so subsequent code can use it. Hence the next line should assign the new dictionary to changeCallbacksPerCP[variable.VariableNumber].", "reasoning_model_answer": "changeCallbacksPerCP[variable.VariableNumber] = cps;", "assistant_with_reasoning": "\nThe code is inside RegisterCallback. It retrieves the callbacks dictionary for the variable number. If the entry is null, it creates a new Dictionary>. The next logical step is to store this newly created dictionary back into the changeCallbacksPerCP list at the variable's index, so subsequent code can use it. Hence the next line should assign the new dictionary to changeCallbacksPerCP[variable.VariableNumber].\n\nchangeCallbacksPerCP[variable.VariableNumber] = cps;", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.164, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 10939, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "changeCallbacksPerCP[variable.VariableNumber] = cps;", "score": 0.87, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "package org.batfish.bddreachability;\n\nimport static org.batfish.bddreachability.BDDReachabilityUtils.computeForwardEdgeTable;\nimport static org.batfish.bddreachability.BDDReachabilityUtils.fixpoint;\nimport static org.batfish.bddreachability.BDDReachabilityUtils.toIngressLocation;\nimport static org.batfish.bddreachability.TestNetwork.DST_PREFIX_1;\nimport static org.batfish.bddreachability.TestNetwork.DST_PREFIX_2;\nimport static org.batfish.bddreachability.TestNetwork.LINK_1_NETWORK;\nimport static org.batfish.bddreachability.TestNetwork.LINK_2_NETWORK;\nimport static org.batfish.bddreachability.TestNetwork.POST_SOURCE_NAT_ACL_DEST_PORT;\nimport static org.batfish.common.bdd.BDDMatchers.intersects;\nimport static org.batfish.common.bdd.BDDMatchers.isOne;\nimport static org.batfish.common.bdd.BDDMatchers.isZero;\nimport static org.batfish.datamodel.Configuration.DEFAULT_VRF_NAME;\nimport static org.hamcrest.Matchers.containsInAnyOrder;\nimport static org.hamcrest.Matchers.equalTo;\nimport static org.hamcrest.Matchers.not;\nimport static org.hamcrest.Matchers.nullValue;\nimport static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.assertThat;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Table;\nimport com.google.common.collect.Tables;\nimport java.io.IOException;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.stream.Collectors;\nimport java.util.stream.Stream;\nimport net.sf.javabdd.BDD;\nimport org.batfish.bddreachability.transition.Transition;\nimport org.batfish.common.bdd.BDDInteger;\nimport org.batfish.common.bdd.BDDOps;\nimport org.batfish.common.bdd.BDDPacket;\nimport org.batfish.common.bdd.IpSpaceToBDD;\nimport org.batfish.datamodel.DataPlane;\nimport org.batfish.datamodel.Ip;\nimport org.batfish.datamodel.IpProtocol;\nimport org.batfish.datamodel.UniverseIpSpace;\nimport org.batfish.main.Batfish;\nimport org.batfish.main.BatfishTestUtils;\nimport org.batfish.specifier.InterfaceLinkLocation;\nimport org.batfish.specifier.InterfaceLocation;\nimport org.batfish.specifier.IpSpaceAssignment;\nimport org.batfish.symbolic.state.Accept;\nimport org.batfish.symbolic.state.DropNoRoute;\nimport org.batfish.symbolic.state.InterfaceAccept;\nimport org.batfish.symbolic.state.NodeAccept;\nimport org.batfish.symbolic.state.NodeDropAclIn;\nimport org.batfish.symbolic.state.NodeDropAclOut;\nimport org.batfish.symbolic.state.NodeDropNoRoute;\nimport org.batfish.symbolic.state.NodeDropNullRoute;\nimport org.batfish.symbolic.state.NodeInterfaceDeliveredToSubnet;\nimport org.batfish.symbolic.state.NodeInterfaceExitsNetwork;\nimport org.batfish.symbolic.state.NodeInterfaceInsufficientInfo;\nimport org.batfish.symbolic.state.OriginateInterface;\nimport org.batfish.symbolic.state.OriginateInterfaceLink;\nimport org.batfish.symbolic.state.OriginateVrf;\nimport org.batfish.symbolic.state.PostInInterface;\nimport org.batfish.symbolic.state.PostInVrf;\nimport org.batfish.symbolic.state.PreInInterface;\nimport org.batfish.symbolic.state.PreOutEdge;\nimport org.batfish.symbolic.state.PreOutEdgePostNat;\nimport org.batfish.symbolic.state.PreOutInterfaceNeighborUnreachable;\nimport org.batfish.symbolic.state.PreOutVrf;\nimport org.batfish.symbolic.state.Query;\nimport org.batfish.symbolic.state.StateExpr;\nimport org.batfish.symbolic.state.VrfAccept;\nimport org.junit.Before;\nimport org.junit.Rule;\nimport org.junit.Test;\nimport org.junit.rules.TemporaryFolder;\n\n/** Tests of {@link BDDReachabilityAnalysis}. */\npublic final class BDDReachabilityAnalysisTest {\n @Rule public TemporaryFolder temp = new TemporaryFolder();\n\n private final BDDPacket _pkt = new BDDPacket();\n\n private BDDReachabilityAnalysis _graph;\n private BDDReachabilityAnalysisFactory _graphFactory;\n private TestNetwork _net;\n\n private BDDOps _bddOps;\n\n private Ip _dstIface1Ip;\n private BDD _dstIface1IpBDD;\n private Ip _dstIface2Ip;\n private BDD _dstIface2IpBDD;\n private String _dstIface1Name;\n private String _dstIface2Name;\n private String _dstName;\n private VrfAccept _dstVrfAccept;\n private InterfaceAccept _link1DstAccept;\n private InterfaceAccept _link2DstAccept;\n private InterfaceAccept _dstIface1Accept;\n private InterfaceAccept _dstIface2Accept;\n private NodeAccept _dstNodeAccept;\n private PostInInterface _dstPostInInterface1;\n private PostInInterface _dstPostInInterface2;\n private PostInVrf _dstPostInVrf;\n private PreInInterface _dstPreInInterface1;\n private PreInInterface _dstPreInInterface2;\n private PreOutEdge _dstPreOutEdge1;\n private PreOutEdge _dstPreOutEdge2;\n private PreOutEdgePostNat _dstPreOutEdgePostNat1;\n private PreOutEdgePostNat _dstPreOutEdgePostNat2;\n private PreOutVrf _dstPreOutVrf;\n\n private BDD _link1DstIpBDD;\n private String _link1DstName;\n\n private BDD _link1SrcIpBDD;\n private String _link1SrcName;\n\n private BDD _link2DstIpBDD;\n private String _link2DstName;\n\n private BDD _link2SrcIpBDD;\n private String _link2SrcName;\n\n private String _srcName;\n private NodeAccept _srcNodeAccept;\n private VrfAccept _srcVrfAccept;\n private InterfaceAccept _link1SrcAccept;\n private InterfaceAccept _link2SrcAccept;\n private PostInVrf _srcPostInVrf;\n private PreInInterface _srcPreInInterface1;\n private PreInInterface _srcPreInInterface2;\n private PreOutEdge _srcPreOutEdge1;\n private PreOutEdge _srcPreOutEdge2;\n private PreOutEdgePostNat _srcPreOutEdgePostNat1;\n private PreOutEdgePostNat _srcPreOutEdgePostNat2;\n private PreOutVrf _srcPreOutVrf;\n\n private final BDD _tcpBdd = _pkt.getIpProtocol().value(IpProtocol.TCP);\n\n @Before\n public void setup() throws IOException {\n _net = new TestNetwork();\n Batfish batfish = BatfishTestUtils.getBatfish(_net._configs, temp);\n\n _link1DstIpBDD = dstIpBDD(LINK_1_NETWORK.getEndIp());\n _link1DstName = _net._link1Dst.getName();\n\n _link1SrcIpBDD = dstIpBDD(LINK_1_NETWORK.getStartIp());\n _link1SrcName = _net._link1Src.getName();\n\n _link2DstIpBDD = dstIpBDD(LINK_2_NETWORK.getEndIp());\n _link2DstName = _net._link2Dst.getName();\n\n _link2SrcIpBDD = dstIpBDD(LINK_2_NETWORK.getStartIp());\n _link2SrcName = _net._link2Src.getName();\n\n batfish.computeDataPlane(batfish.getSnapshot());\n DataPlane dataPlane = batfish.loadDataPlane(batfish.getSnapshot());\n _graphFactory =\n new BDDReachabilityAnalysisFactory(\n _pkt,\n _net._configs,\n dataPlane.getForwardingAnalysis(),\n new IpsRoutedOutInterfacesFactory(dataPlane.getFibs()),\n false,\n false);\n\n IpSpaceAssignment assignment =\n IpSpaceAssignment.builder()\n .assign(\n new InterfaceLocation(_net._srcNode.getHostname(), _net._link1Src.getName()),\n UniverseIpSpace.INSTANCE)\n .build();\n _graph = _graphFactory.bddReachabilityAnalysis(assignment);\n _bddOps = new BDDOps(_pkt.getFactory());\n _dstIface1Ip = DST_PREFIX_1.getStartIp();\n _dstIface1IpBDD = dstIpBDD(_dstIface1Ip);\n _dstIface2Ip = DST_PREFIX_2.getStartIp();\n _dstIface2IpBDD = dstIpBDD(_dstIface2Ip);\n _dstIface1Name = _net._dstIface1.getName();\n _dstIface2Name = _net._dstIface2.getName();\n _dstName = _net._dstNode.getHostname();\n _dstNodeAccept = new NodeAccept(_dstName);\n _dstVrfAccept = new VrfAccept(_dstName, DEFAULT_VRF_NAME);\n _link1DstAccept = new InterfaceAccept(_dstName, _link1DstName);\n _link2DstAccept = new InterfaceAccept(_dstName, _link2DstName);\n _dstIface1Accept = new InterfaceAccept(_dstName, _dstIface1Name);\n _dstIface2Accept = new InterfaceAccept(_dstName, _dstIface2Name);\n _dstPostInVrf = new PostInVrf(_dstName, DEFAULT_VRF_NAME);\n _dstPreOutVrf = new PreOutVrf(_dstName, DEFAULT_VRF_NAME);\n\n _srcName = _net._srcNode.getHostname();\n _srcNodeAccept = new NodeAccept(_srcName);\n _srcVrfAccept = new VrfAccept(_srcName, DEFAULT_VRF_NAME);\n _link1SrcAccept = new InterfaceAccept(_srcName, _link1SrcName);\n _link2SrcAccept = new InterfaceAccept(_srcName, _link2SrcName);\n _srcPostInVrf = new PostInVrf(_srcName, DEFAULT_VRF_NAME);\n\n _dstPostInInterface1 = new PostInInterface(_dstName, _link1DstName);\n _dstPostInInterface2 = new PostInInterface(_dstName, _link2DstName);\n\n _dstPreInInterface1 = new PreInInterface(_dstName, _link1DstName);\n _dstPreInInterface2 = new PreInInterface(_dstName, _link2DstName);\n\n _srcPreInInterface1 = new PreInInterface(_srcName, _net._link1Src.getName());\n _srcPreInInterface2 = new PreInInterface(_srcName, _link2SrcName);\n\n _dstPreOutEdge1 = new PreOutEdge(_dstName, _link1DstName, _srcName, _net._link1Src.getName());\n _dstPreOutEdge2 = new PreOutEdge(_dstName, _link2DstName, _srcName, _link2SrcName);\n _dstPreOutEdgePostNat1 =\n new PreOutEdgePostNat(_dstName, _link1DstName, _srcName, _net._link1Src.getName());\n _dstPreOutEdgePostNat2 =\n new PreOutEdgePostNat(_dstName, _link2DstName, _srcName, _link2SrcName);\n _srcPreOutEdge1 = new PreOutEdge(_srcName, _net._link1Src.getName(), _dstName, _link1DstName);\n _srcPreOutEdge2 = new PreOutEdge(_srcName, _link2SrcName, _dstName, _link2DstName);\n _srcPreOutEdgePostNat1 =\n new PreOutEdgePostNat(_srcName, _net._link1Src.getName(), _dstName, _link1DstName);\n _srcPreOutEdgePostNat2 =\n new PreOutEdgePostNat(_srcName, _link2SrcName, _dstName, _link2DstName);\n _srcPreOutVrf = new PreOutVrf(_srcName, DEFAULT_VRF_NAME);\n }\n\n private List bddIps(BDD bdd) {\n BDDInteger bddInteger = _graphFactory.getIpSpaceToBDD().getBDDInteger();\n\n return bddInteger.getValuesSatisfying(bdd, 10).stream()\n .map(Ip::create)\n .collect(Collectors.toList());\n }\n\n private BDD bddTransition(StateExpr preState, StateExpr postState) {\n return _graph\n .getForwardEdgeMap()\n .get(preState)\n .get(postState)\n .transitForward(_pkt.getFactory().one());\n }\n\n private Edge edge(StateExpr preState, StateExpr postState) {\n Transition transition = _graph.getForwardEdgeMap().get(preState).get(postState);\n return transition == null ? null : new Edge(preState, postState, transition);\n }\n\n private BDD dstIpBDD(Ip ip) {\n return new IpSpaceToBDD(_pkt.getDstIp()).toBDD(ip);\n }\n\n private BDD dstPortBDD(int destPort) {\n return _pkt.getDstPort().value(destPort);\n }\n\n private BDD or(BDD... bdds) {\n return _bddOps.or(bdds);\n }\n\n private Map ifaceAcceptBDDs(String node) {\n return _graphFactory.getIfaceAcceptBDDs().get(node).get(DEFAULT_VRF_NAME);\n }\n\n @Test\n public void testIfaceAcceptBDDs() {\n assertThat(\n ifaceAcceptBDDs(_dstName),\n equalTo(\n ImmutableMap.of(\n _link1DstName,\n _link1DstIpBDD,\n _link2DstName,\n _link2DstIpBDD,\n _dstIface1Name,\n _dstIface1IpBDD,\n _dstIface2Name,\n _dstIface2IpBDD)));\n assertThat(\n ifaceAcceptBDDs(_srcName),\n equalTo(ImmutableMap.of(_link1SrcName, _link1SrcIpBDD, _link2SrcName, _link2SrcIpBDD)));\n }\n\n @Test\n public void testBDDTransitions_InterfaceAccept_VrfAccept() {\n assertThat(bddTransition(_link1SrcAccept, _srcVrfAccept), isOne());\n assertThat(bddTransition(_link2SrcAccept, _srcVrfAccept), isOne());\n assertThat(bddTransition(_link1DstAccept, _dstVrfAccept), isOne());\n assertThat(bddTransition(_link2DstAccept, _dstVrfAccept), isOne());\n assertThat(bddTransition(_dstIface1Accept, _dstVrfAccept), isOne());\n assertThat(bddTransition(_dstIface2Accept, _dstVrfAccept), isOne());\n }\n\n @Test\n public void testBDDTransitions_VrfAccept_NodeAccept() {\n assertThat(bddTransition(_srcVrfAccept, _srcNodeAccept), isOne());\n assertThat(bddTransition(_dstVrfAccept, _dstNodeAccept), isOne());\n }\n\n @Test\n public void testBDDTransitions_NodeAccept_Accept() {\n assertThat(bddTransition(_srcNodeAccept, Accept.INSTANCE), isOne());\n assertThat(bddTransition(_dstNodeAccept, Accept.INSTANCE), isOne());\n }\n\n @Test\n public void testBDDTransitions_PostInVrf_outEdges() {\n Set srcPostInVrfOutStates = _graph.getForwardEdgeMap().get(_srcPostInVrf).keySet();\n Set dstPostInVrfOutStates = _graph.getForwardEdgeMap().get(_dstPostInVrf).keySet();\n\n // Confirm out edges are as expected\n assertThat(\n srcPostInVrfOutStates,\n containsInAnyOrder(\n _link1SrcAccept, _link2SrcAccept, new NodeDropNoRoute(_srcName), _srcPreOutVrf));\n assertThat(\n dstPostInVrfOutStates,\n containsInAnyOrder(\n _link1DstAccept,\n _link2DstAccept,\n _dstIface1Accept,\n _dstIface2Accept,\n new NodeDropNoRoute(_dstName),\n _dstPreOutVrf));\n\n // Test that out edges are mutually exclusive\n List srcOutBdds =\n srcPostInVrfOutStates.stream()\n .map(outState -> bddTransition(_srcPostInVrf, outState))\n .collect(ImmutableList.toImmutableList());\n List dstOutBdds =\n dstPostInVrfOutStates.stream()\n .map(outState -> bddTransition(_dstPostInVrf, outState))\n .collect(ImmutableList.toImmutableList());\n testMutuallyExclusive(srcOutBdds);\n testMutuallyExclusive(dstOutBdds);\n }\n\n private void testMutuallyExclusive(List bdds) {\n for (int i = 0; i < bdds.size(); i++) {\n for (int j = i + 1; j < bdds.size(); j++) {\n assertThat(bdds.get(i), not(intersects(bdds.get(j))));\n }\n }\n }\n\n @Test\n public void testBDDTransitions_PostInVrf_InterfaceAccept() {\n BDD link1SrcAcceptBdd = bddTransition(_srcPostInVrf, _link1SrcAccept);\n BDD link2SrcAcceptBdd = bddTransition(_srcPostInVrf, _link2SrcAccept);\n assertThat(link1SrcAcceptBdd, equalTo(_link1SrcIpBDD));\n assertThat(link2SrcAcceptBdd, equalTo(_link2SrcIpBDD));\n\n BDD link1DstAcceptBdd = bddTransition(_dstPostInVrf, _link1DstAccept);\n BDD link2DstAcceptBdd = bddTransition(_dstPostInVrf, _link2DstAccept);\n BDD dstIface1AcceptBdd = bddTransition(_dstPostInVrf, _dstIface1Accept);\n BDD dstIface2AcceptBdd = bddTransition(_dstPostInVrf, _dstIface2Accept);\n assertThat(link1DstAcceptBdd, equalTo(_link1DstIpBDD));\n assertThat(link2DstAcceptBdd, equalTo(_link2DstIpBDD));\n assertThat(dstIface1AcceptBdd, equalTo(_dstIface1IpBDD));\n assertThat(dstIface2AcceptBdd, equalTo(_dstIface2IpBDD));\n }\n", "answers": [" @Test"], "length": 903, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "d0af8a8b-5206-4010-9691-9d3e702e5cad", "reasoning": "The provided snippet ends the test method testBDDTransitions_PostInVrf_InterfaceAccept with a closing brace. In typical Java test classes, the next line after a test method is the start of another test, beginning with the @Test annotation, indented two spaces like the previous methods.", "reasoning_model_answer": "@Test", "assistant_with_reasoning": "\nThe provided snippet ends the test method testBDDTransitions_PostInVrf_InterfaceAccept with a closing brace. In typical Java test classes, the next line after a test method is the start of another test, beginning with the @Test annotation, indented two spaces like the previous methods.\n\n@Test", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.049, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 14586, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "@Test", "score": 0.83, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "# Note that the dataset must be already downloaded for this script to work, do:\n# $ cd data/\n# $ python download_dataset.py\n# quoc_trinh\n\nimport tensorflow as tf\n\nimport numpy as np\nimport matplotlib\nimport matplotlib.pyplot as plt\nfrom sklearn import metrics\n\nimport os\nimport sys\nimport datetime\n\n# get current file_name as [0] of array\nfile_name = os.path.splitext(os.path.basename(sys.argv[0]))[0]\nprint(\" File Name:\")\nprint(file_name)\nprint(\"\")\n# FLAG to know that whether this is traning process or not.\nFLAG = 'train'\nN_HIDDEN_CONFIG = 32\n\nsave_path_name = file_name + \"/model.ckpt\"\n\nprint(datetime.datetime.now())\n# Write to file: time to start, type, time to end\nf = open(file_name + '/time.txt', 'a+')\nf.write(\"------------- \\n\")\nf.write(\"This is time \\n\")\nf.write(\"Started at \\n\")\nf.write(str(datetime.datetime.now())+'\\n')\n\nif __name__ == \"__main__\":\n\n # -----------------------------\n # step1: load and prepare data\n # -----------------------------\n # Those are separate normalised input features for the neural network\n INPUT_SIGNAL_TYPES = [\n \"body_acc_x_\",\n \"body_acc_y_\",\n \"body_acc_z_\",\n \"body_gyro_x_\",\n \"body_gyro_y_\",\n \"body_gyro_z_\",\n \"total_acc_x_\",\n \"total_acc_y_\",\n \"total_acc_z_\"\n ]\n\n # Output classes to learn how to classify\n LABELS = [\n \"WALKING\",\n \"WALKING_UPSTAIRS\",\n \"WALKING_DOWNSTAIRS\",\n \"SITTING\",\n \"STANDING\",\n \"LAYING\"\n ]\n\n DATA_PATH = \"../data/\"\n DATASET_PATH = DATA_PATH + \"UCI HAR Dataset/\"\n print(\"\\n\" + \"Dataset is now located at: \" + DATASET_PATH)\n # Preparing data set:\n TRAIN = \"train/\"\n TEST = \"test/\"\n\n # Load \"X\" (the neural network's training and testing inputs)\n def load_X(X_signals_paths):\n X_signals = []\n\n for signal_type_path in X_signals_paths:\n file = open(signal_type_path, 'rb')\n # Read dataset from disk, dealing with text files' syntax\n X_signals.append(\n [np.array(serie, dtype=np.float32) for serie in [\n row.replace(' ', ' ').strip().split(' ') for row in file\n ]]\n )\n file.close()\n\n \"\"\"Examples\n --------\n >> > x = np.arange(4).reshape((2, 2))\n >> > x\n array([[0, 1],\n [2, 3]])\n\n >> > np.transpose(x)\n array([[0, 2],\n [1, 3]])\n\n >> > x = np.ones((1, 2, 3))\n >> > np.transpose(x, (1, 0, 2)).shape\n (2, 1, 3)\n \"\"\"\n\n return np.transpose(np.array(X_signals), (1, 2, 0))\n\n X_train_signals_paths = [\n DATASET_PATH + TRAIN + \"Inertial Signals/\" + signal + \"train.txt\" for signal in INPUT_SIGNAL_TYPES\n ]\n X_test_signals_paths = [\n DATASET_PATH + TEST + \"Inertial Signals/\" + signal + \"test.txt\" for signal in INPUT_SIGNAL_TYPES\n ]\n X_train = load_X(X_train_signals_paths) # [7352, 128, 9]\n X_test = load_X(X_test_signals_paths) # [7352, 128, 9]\n\n # print(X_train)\n print(len(X_train)) # 7352\n print(len(X_train[0])) # 128\n print(len(X_train[0][0])) # 9\n\n print(type(X_train))\n\n X_train = np.reshape(X_train, [-1, 32, 36])\n X_test = np.reshape(X_test, [-1, 32, 36])\n\n print(\"-----------------X_train---------------\")\n # print(X_train)\n print(len(X_train)) # 7352\n print(len(X_train[0])) # 32\n print(len(X_train[0][0])) # 36\n\n print(type(X_train))\n # exit()\n\n y_train_path = DATASET_PATH + TRAIN + \"y_train.txt\"\n y_test_path = DATASET_PATH + TEST + \"y_test.txt\"\n\n def one_hot(label):\n \"\"\"convert label from dense to one hot\n argument:\n label: ndarray dense label ,shape: [sample_num,1]\n return:\n one_hot_label: ndarray one hot, shape: [sample_num,n_class]\n \"\"\"\n label_num = len(label)\n new_label = label.reshape(label_num) # shape : [sample_num]\n # because max is 5, and we will create 6 columns\n n_values = np.max(new_label) + 1\n return np.eye(n_values)[np.array(new_label, dtype=np.int32)]\n\n # Load \"y\" (the neural network's training and testing outputs)\n def load_y(y_path):\n file = open(y_path, 'rb')\n # Read dataset from disk, dealing with text file's syntax\n y_ = np.array(\n [elem for elem in [\n row.replace(' ', ' ').strip().split(' ') for row in file\n ]],\n dtype=np.int32\n )\n file.close()\n # Subtract 1 to each output class for friendly 0-based indexing\n return y_ - 1\n\n\n y_train = one_hot(load_y(y_train_path))\n y_test = one_hot(load_y(y_test_path))\n\n print(\"---------y_train----------\")\n # print(y_train)\n print(len(y_train)) # 7352\n print(len(y_train[0])) # 6\n\n # -----------------------------------\n # step2: define parameters for model\n # -----------------------------------\n class Config(object):\n \"\"\"\n define a class to store parameters,\n the input should be feature mat of training and testing\n \"\"\"\n\n def __init__(self, X_train, X_test):\n # Input data\n self.train_count = len(X_train) # 7352 training series\n self.test_data_count = len(X_test) # 2947 testing series\n self.n_steps = len(X_train[0]) # 128 time_steps per series\n\n # Training\n self.learning_rate = 0.0025\n self.lambda_loss_amount = 0.0015\n self.training_epochs = 300\n self.batch_size = 1000\n\n # LSTM structure\n self.n_inputs = len(X_train[0][0]) # Features count is of 9: three 3D sensors features over time\n self.n_hidden = N_HIDDEN_CONFIG # nb of neurons inside the neural network\n self.n_classes = 6 # Final output classes\n self.W = {\n 'hidden': tf.Variable(tf.random_normal([self.n_inputs, self.n_hidden])), # [9, 32]\n 'output': tf.Variable(tf.random_normal([self.n_hidden, self.n_classes])) # [32, 6]\n }\n self.biases = {\n 'hidden': tf.Variable(tf.random_normal([self.n_hidden], mean=1.0)), # [32]\n 'output': tf.Variable(tf.random_normal([self.n_classes])) # [6]\n }\n\n config = Config(X_train, X_test)\n # print(\"Some useful info to get an insight on dataset's shape and normalisation:\")\n # print(\"features shape, labels shape, each features mean, each features standard deviation\")\n # print(X_test.shape, y_test.shape,\n # np.mean(X_test), np.std(X_test))\n # print(\"the dataset is therefore properly normalised, as expected.\")\n #\n #\n # ------------------------------------------------------\n # step3: Let's get serious and build the neural network\n # ------------------------------------------------------\n # [none, 128, 9]\n X = tf.placeholder(tf.float32, [None, config.n_steps, config.n_inputs])\n # [none, 6]\n Y = tf.placeholder(tf.float32, [None, config.n_classes])\n\n print(\"-------X Y----------\")\n print(X)\n X = tf.reshape(X, shape=[-1, 32, 36])\n print(X)\n\n print(Y)\n Y = tf.reshape(Y, shape=[-1, 6])\n print(Y)\n\n # Weight Initialization\n def weight_variable(shape):\n # tra ve 1 gia tri random theo thuat toan truncated_ normal\n initial = tf.truncated_normal(shape, mean=0.0, stddev=0.1, dtype=tf.float32)\n return tf.Variable(initial)\n\n def bias_varibale(shape):\n initial = tf.constant(0.1, shape=shape, name='Bias')\n return tf.Variable(initial)\n\n # Convolution and Pooling\n def conv2d(x, W):\n # Must have `strides[0] = strides[3] = 1 `.\n # For the most common case of the same horizontal and vertices strides, `strides = [1, stride, stride, 1] `.\n return tf.nn.conv2d(input=x, filter=W, strides=[1, 1, 1, 1], padding='SAME', name='conv_2d')\n\n def max_pool_2x2(x):\n return tf.nn.max_pool(value=x, ksize=[1, 2, 2, 1],\n strides=[1, 1, 1, 1], padding='SAME', name='max_pool')\n\n def LSTM_Network(feature_mat, config):\n \"\"\"model a LSTM Network,\n it stacks 2 LSTM layers, each layer has n_hidden=32 cells\n and 1 output layer, it is a full connet layer\n argument:\n feature_mat: ndarray feature matrix, shape=[batch_size,time_steps,n_inputs]\n config: class containing config of network\n return:\n : matrix output shape [batch_size,n_classes]\n \"\"\"\n\n W_conv1 = weight_variable([3, 3, 1, 32])", "answers": [" b_conv1 = bias_varibale([32])"], "length": 914, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "c29ab152-dded-4795-ac11-a0a1d1216e9f", "reasoning": "Inside the LSTM_Network function the code starts defining convolutional layer parameters. After creating the weight tensor W_conv1 with shape [3,3,1,32], the usual next step is to create the corresponding bias term. The bias helper is bias_varibale, so the next line should define b_conv1 as a bias vector of length 32.", "reasoning_model_answer": "b_conv1 = bias_varibale([32])", "assistant_with_reasoning": "\nInside the LSTM_Network function the code starts defining convolutional layer parameters. After creating the weight tensor W_conv1 with shape [3,3,1,32], the usual next step is to create the corresponding bias term. The bias helper is bias_varibale, so the next line should define b_conv1 as a bias vector of length 32.\n\nb_conv1 = bias_varibale([32])", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 2.788, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 8720, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "b_conv1 = bias_varibale([32])", "score": 0.88, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "// ======================================================================================\n// File : exEase.cs\n// Author : Wu Jie \n// Last Change : 08/06/2011 | 21:43:52 PM | Saturday,August\n// Description : \n// ======================================================================================\n\n///////////////////////////////////////////////////////////////////////////////\n// usings\n///////////////////////////////////////////////////////////////////////////////\n\nusing UnityEngine;\nusing System.Collections;\nusing System.Collections.Generic;\n\n///////////////////////////////////////////////////////////////////////////////\n// defines\n///////////////////////////////////////////////////////////////////////////////\n\n///////////////////////////////////////////////////////////////////////////////\n// class exEase \n// \n// Purpose: \n// \n///////////////////////////////////////////////////////////////////////////////\n\npublic class exEase {\n\n // ------------------------------------------------------------------ \n // Desc: exEase.Type \n // ------------------------------------------------------------------ \n\n public enum Type {\n Linear,\n QuadIn,\n QuadOut,\n QuadInOut,\n QuadOutIn,\n CubicIn,\n CubicOut,\n CubicInOut,\n CubicOutIn,\n QuartIn,\n QuartOut,\n QuartInOut,\n QuartOutIn,\n QuintIn,\n QuintOut,\n QuintInOut,\n QuintOutIn,\n SineIn,\n SineOut,\n SineInOut,\n SineOutIn,\n ExpoIn,\n ExpoOut,\n ExpoInOut,\n ExpoOutIn,\n CircIn,\n CircOut,\n CircInOut,\n CircOutIn,\n ElasticIn,\n ElasticOut,\n ElasticInOut,\n ElasticOutIn,\n BackIn,\n BackOut,\n BackInOut,\n BackOutIn,\n BounceIn,\n BounceOut,\n BounceInOut,\n BounceOutIn,\n Smooth,\n Fade,\n Spring,\n }\n\n // ------------------------------------------------------------------ \n // Desc: \n // ------------------------------------------------------------------ \n\n private static Dictionary< exEase.Type, System.Func> easeFunctions;\n private static bool initialized = false;\n\n // ------------------------------------------------------------------ \n // Desc: \n // ------------------------------------------------------------------ \n\n public static void Init () {\n if ( initialized == false ) {\n initialized = true;\n easeFunctions = new Dictionary>();\n easeFunctions[exEase.Type.Linear] = exEase.Linear;\n easeFunctions[exEase.Type.QuadIn] = exEase.QuadIn;\n easeFunctions[exEase.Type.QuadOut] = exEase.QuadOut;\n easeFunctions[exEase.Type.QuadInOut] = exEase.QuadInOut;\n easeFunctions[exEase.Type.QuadOutIn] = exEase.QuadOutIn;\n easeFunctions[exEase.Type.CubicIn] = exEase.CubicIn;\n easeFunctions[exEase.Type.CubicOut] = exEase.CubicOut;\n easeFunctions[exEase.Type.CubicInOut] = exEase.CubicInOut;\n easeFunctions[exEase.Type.CubicOutIn] = exEase.CubicOutIn;\n easeFunctions[exEase.Type.QuartIn] = exEase.QuartIn;\n easeFunctions[exEase.Type.QuartOut] = exEase.QuartOut;\n easeFunctions[exEase.Type.QuartInOut] = exEase.QuartInOut;\n easeFunctions[exEase.Type.QuartOutIn] = exEase.QuartOutIn;\n easeFunctions[exEase.Type.QuintIn] = exEase.QuintIn;\n easeFunctions[exEase.Type.QuintOut] = exEase.QuintOut;\n easeFunctions[exEase.Type.QuintInOut] = exEase.QuintInOut;\n easeFunctions[exEase.Type.QuintOutIn] = exEase.QuintOutIn;\n easeFunctions[exEase.Type.SineIn] = exEase.SineIn;\n easeFunctions[exEase.Type.SineOut] = exEase.SineOut;\n easeFunctions[exEase.Type.SineInOut] = exEase.SineInOut;\n easeFunctions[exEase.Type.SineOutIn] = exEase.SineOutIn;\n easeFunctions[exEase.Type.ExpoIn] = exEase.ExpoIn;\n easeFunctions[exEase.Type.ExpoOut] = exEase.ExpoOut;\n easeFunctions[exEase.Type.ExpoInOut] = exEase.ExpoInOut;\n easeFunctions[exEase.Type.ExpoOutIn] = exEase.ExpoOutIn;\n easeFunctions[exEase.Type.CircIn] = exEase.CircIn;\n easeFunctions[exEase.Type.CircOut] = exEase.CircOut;\n easeFunctions[exEase.Type.CircInOut] = exEase.CircInOut;\n easeFunctions[exEase.Type.CircOutIn] = exEase.CircOutIn;\n easeFunctions[exEase.Type.ElasticIn] = exEase.ElasticIn_Simple;\n easeFunctions[exEase.Type.ElasticOut] = exEase.ElasticOut_Simple;\n easeFunctions[exEase.Type.ElasticInOut] = exEase.ElasticInOut_Simple;\n easeFunctions[exEase.Type.ElasticOutIn] = exEase.ElasticOutIn_Simple;\n easeFunctions[exEase.Type.BackIn] = exEase.BackIn_Simple;\n easeFunctions[exEase.Type.BackOut] = exEase.BackOut_Simple;\n easeFunctions[exEase.Type.BackInOut] = exEase.BackInOut_Simple;\n easeFunctions[exEase.Type.BackOutIn] = exEase.BackOutIn_Simple;\n easeFunctions[exEase.Type.BounceIn] = exEase.BounceIn_Simple;\n easeFunctions[exEase.Type.BounceOut] = exEase.BounceOut_Simple;\n easeFunctions[exEase.Type.BounceInOut] = exEase.BounceInOut_Simple;\n easeFunctions[exEase.Type.BounceOutIn] = exEase.BounceOutIn_Simple;\n easeFunctions[exEase.Type.Smooth] = exEase.Smooth;\n easeFunctions[exEase.Type.Fade] = exEase.Fade;\n easeFunctions[exEase.Type.Spring] = exEase.Spring;\n }\n }\n\n // ------------------------------------------------------------------ \n // Desc: \n // ------------------------------------------------------------------ \n\n public static System.Func GetEaseFunc ( exEase.Type _type ) {\n exEase.Init(); // NOTE: this can make sure we initialized the easeFunctions table.\n return easeFunctions[_type];\n }\n\n // ------------------------------------------------------------------ \n // Desc: \n // ------------------------------------------------------------------ \n\n public static float Linear ( float _t ) { return _t; }\n\n // ------------------------------------------------------------------ \n // Desc: quad \n // ------------------------------------------------------------------ \n\n public static float QuadIn ( float _t ) { return _t*_t; }\n public static float QuadOut ( float _t ) { return -_t*(_t-2); }\n public static float QuadInOut ( float _t ) {\n _t*=2.0f;\n if (_t < 1) {\n return _t*_t/2.0f;\n } else {\n --_t;\n return -0.5f * (_t*(_t-2) - 1);\n }\n }\n public static float QuadOutIn ( float _t ) {\n if (_t < 0.5f) return QuadOut (_t*2)/2;\n return QuadIn((2*_t)-1)/2 + 0.5f;\n }\n\n // ------------------------------------------------------------------ \n // Desc: cubic \n // ------------------------------------------------------------------ \n\n public static float CubicIn ( float _t ) { return _t*_t*_t; }\n public static float CubicOut ( float _t ) {\n _t-=1.0f;\n return _t*_t*_t + 1;\n }\n public static float CubicInOut ( float _t ) {\n _t*=2.0f;\n if(_t < 1) {\n return 0.5f*_t*_t*_t;\n } else {\n _t -= 2.0f;\n return 0.5f*(_t*_t*_t + 2);\n }\n }\n public static float CubicOutIn ( float _t ) {\n if (_t < 0.5f) return CubicOut (2*_t)/2;\n return CubicIn (2*_t - 1)/2 + 0.5f;\n }\n\n // ------------------------------------------------------------------ \n // Desc: quart\n // ------------------------------------------------------------------ \n\n public static float QuartIn ( float _t ) { return _t*_t*_t*_t; }\n public static float QuartOut ( float _t ) {\n _t-= 1.0f;\n return - (_t*_t*_t*_t- 1);\n }\n public static float QuartInOut ( float _t ) {\n _t*=2;\n if (_t < 1) return 0.5f*_t*_t*_t*_t;\n else {\n _t -= 2.0f;\n return -0.5f * (_t*_t*_t*_t- 2);\n }\n }\n public static float QuartOutIn ( float _t ) {\n if (_t < 0.5f) return QuartOut (2*_t)/2;\n return QuartIn (2*_t-1)/2 + 0.5f;\n }\n\n // ------------------------------------------------------------------ \n // Desc: quint\n // ------------------------------------------------------------------ \n\n public static float QuintIn ( float _t ) { return _t*_t*_t*_t*_t; }\n public static float QuintOut ( float _t ) {\n _t-=1.0f;\n return _t*_t*_t*_t*_t + 1;\n }\n public static float QuintInOut ( float _t ) {\n _t*=2.0f;\n if (_t < 1) return 0.5f*_t*_t*_t*_t*_t;\n else {\n _t -= 2.0f;\n return 0.5f*(_t*_t*_t*_t*_t + 2);\n }\n }\n public static float QuintOutIn ( float _t ) {\n if (_t < 0.5f) return QuintOut (2*_t)/2;\n return QuintIn (2*_t - 1)/2 + 0.5f;\n }\n\n // ------------------------------------------------------------------ \n // Desc: sine \n // ------------------------------------------------------------------ \n\n public static float SineIn ( float _t ) {\n return (_t == 1.0f) ? 1.0f : -Mathf.Cos(_t * Mathf.PI/2) + 1.0f;\n }\n public static float SineOut ( float _t ) {\n return Mathf.Sin(_t* Mathf.PI/2);\n }\n public static float SineInOut ( float _t ) {\n return -0.5f * (Mathf.Cos(Mathf.PI*_t) - 1);\n }\n public static float SineOutIn ( float _t ) {\n if (_t < 0.5f) return SineOut (2*_t)/2;\n return SineIn (2*_t - 1)/2 + 0.5f;\n }\n\n // ------------------------------------------------------------------ \n // Desc: expo\n // ------------------------------------------------------------------ \n\n public static float ExpoIn ( float _t ) {\n return (_t==0 || _t == 1.0f) ? _t : Mathf.Pow(2.0f, 10 * (_t - 1)) - 0.001f;\n }\n public static float ExpoOut ( float _t ) {\n return (_t==1.0f) ? 1.0f : 1.001f * (-Mathf.Pow(2.0f, -10 * _t) + 1);\n }\n public static float ExpoInOut ( float _t ) {\n if (_t==0.0f) return 0.0f;\n if (_t==1.0f) return 1.0f;\n _t*=2.0f;\n if (_t < 1) return 0.5f * Mathf.Pow(2.0f, 10 * (_t - 1)) - 0.005f;\n return 0.5f * 1.005f * (-Mathf.Pow(2.0f, -10 * (_t - 1)) + 2);\n }\n public static float ExpoOutIn ( float _t ) {\n if (_t < 0.5f) return ExpoOut (2*_t)/2;\n return ExpoIn (2*_t - 1)/2 + 0.5f;\n }\n\n // ------------------------------------------------------------------ \n // Desc: circ \n // ------------------------------------------------------------------ \n\n public static float CircIn ( float _t ) {\n return -(Mathf.Sqrt(1 - _t*_t) - 1);\n }\n public static float CircOut ( float _t ) {\n _t-= 1.0f;\n return Mathf.Sqrt(1 - _t* _t);\n }\n public static float CircInOut ( float _t ) {\n _t*=2.0f;\n if (_t < 1) {\n return -0.5f * (Mathf.Sqrt(1 - _t*_t) - 1);\n } else {\n _t -= 2.0f;\n return 0.5f * (Mathf.Sqrt(1 - _t*_t) + 1);\n }\n }\n public static float CircOutIn ( float _t ) {\n if (_t < 0.5f) return CircOut (2*_t)/2;\n return CircIn (2*_t - 1)/2 + 0.5f;\n }\n\n // ------------------------------------------------------------------ \n // Desc: elastic\n // ------------------------------------------------------------------ \n\n private static float ElasticInHelper ( float _t, \n float _b, \n float _c, \n float _d, \n float _a, \n float _p )\n {\n float t_adj;\n float _s;\n\n if (_t==0) return _b;\n t_adj = _t/_d;\n if (t_adj==1) return _b+_c;\n\n if ( _a < Mathf.Abs (_c) ) {\n _a = _c;\n _s = _p / 4.0f;\n } else {\n _s = _p / 2*Mathf.PI * Mathf.Asin(_c/_a);\n }\n\n t_adj -= 1.0f;\n return -(_a*Mathf.Pow(2.0f,10*t_adj) * Mathf.Sin( (t_adj*_d-_s)*2*Mathf.PI/_p )) + _b;\n\n }\n private static float ElasticOutHelper ( float _t, \n float _b /*dummy*/, \n float _c, \n float _d /*dummy*/, \n float _a, \n float _p )\n {\n float _s;\n\n if (_t==0) return 0;\n if (_t==1) return _c;\n\n if(_a < _c) {\n _a = _c;\n _s = _p / 4.0f;\n } else {\n _s = _p / 2*Mathf.PI * Mathf.Asin(_c / _a);\n }\n\n return (_a*Mathf.Pow(2.0f,-10*_t) * Mathf.Sin( (_t-_s)*2*Mathf.PI/_p ) + _c);\n }\n\n public static float ElasticIn ( float _t, float _a, float _p ) {\n return ElasticInHelper(_t, 0, 1, 1, _a, _p);\n }", "answers": [" public static float ElasticOut ( float _t, float _a, float _p ) {"], "length": 1157, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "50f43ac1-6532-4257-8067-db174fb90370", "reasoning": "The code just defined ElasticIn, which calls ElasticInHelper. Following the pattern, the next method should be ElasticOut with the same parameter signature, calling ElasticOutHelper. Therefore the next line is the method declaration for ElasticOut.", "reasoning_model_answer": "public static float ElasticOut ( float _t, float _a, float _p ) {", "assistant_with_reasoning": "\nThe code just defined ElasticIn, which calls ElasticInHelper. Following the pattern, the next method should be ElasticOut with the same parameter signature, calling ElasticOutHelper. Therefore the next line is the method declaration for ElasticOut.\n\npublic static float ElasticOut ( float _t, float _a, float _p ) {", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.569, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 13217, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "public static float ElasticOut ( float _t, float _a, float _p ) {", "score": 0.97, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "import pymongo\nfrom pymongo import MongoClient\nfrom datetime import datetime\nimport sys\nsys.path.insert(0, '/opt/C3STEM/Middleware')\nfrom DAO import TrafficLightDAO\n\nconnection = MongoClient()\ndb = connection.c3stem_database\n\nintersection_id1 = \"202601366\"\nintersection_id2 = \"202662093\"\nintersection_id3 = \"202666904\"\nintersection_id4 = \"202666877\"\n\ndb.studentgroup.insert({\n \"_id\": \"group_A\",\n \"name\": \"A\",\n \"latitude\": \"35.03920287110193\",\n \"longitude\": \"-85.28763771057129\",\n\t\"collaboration_url\": \"\",\n\t\"collaboration_url_admin\": \"https://plus.google.com/hangouts/_?gid=000000000000\",\n\t\"last_update_time\": str(datetime.now())\n})\n\ndb.studentgroup.insert({\n \"_id\": \"group_B\",\n \"name\": \"B\",\n \"latitude\": \"35.03920287110193\",\n \"longitude\": \"-85.28763771057129\",\n\t\"collaboration_url\": \"\",\n\t\"collaboration_url_admin\": \"https://plus.google.com/hangouts/_?gid=000000000000\",\n\t\"last_update_time\": str(datetime.now())\n})\n\ndb.studentgroup.insert({\n \"_id\": \"group_A_B_C_D\",\n \"name\": \"A B C D-Colab\",\n \"latitude\": \"35.03920287110193\",\n \"longitude\": \"-85.28763771057129\",\n\t\"collaboration_url\": \"\",\n\t\"collaboration_url_admin\": \"https://plus.google.com/hangouts/_?gid=000000000000\" ,\n\t\"last_update_time\": str(datetime.now())\n})\n\ndb.studentrole.insert({\n \"_id\": \"user\",\n \"name\": \"User\"\n})\n\ndb.studentrole.insert({\n \"_id\": \"admin\",\n \"name\": \"Admin\"\n})\n\ndb.studentrole.insert({\n \"_id\": \"super\",\n \"name\": \"Super Admin\"\n})\n\ndb.student.insert({\n \"_id\": \"user_a\",\n \"firstname\": \"FirstA\",\n \"lastname\": \"LastA\",\n \"schoolname\": \"School X\",\n \"schoolcode\": \"schoolx\",\n \"group_id\": \"group_A\",\n \"password\": \"password\",\n \"changepassword\": \"true\"\n})\n\ndb.user_studentrole.insert({\n \"user_id\": \"user_a\",\n \"role_ids\": [\"user\",\"admin\"]\n})\n\nuser_id = db.student.insert({\n \"_id\": \"user_b\",\n \"firstname\": \"FirstB\",\n \"lastname\": \"LastB\",\n \"schoolname\": \"School X\",\n \"schoolcode\": \"schoolx\",\n \"group_id\": \"group_A\",\n \"password\": \"password\",\n \"changepassword\": \"true\"\n})\n\ndb.user_studentrole.insert({\n \"user_id\": \"user_b\",\n \"role_ids\": [\"user\"]\n})\n\nuser_id = db.student.insert({\n \"_id\": \"user_c\",\n \"firstname\": \"FirstC\",\n \"lastname\": \"LastC\",\n \"schoolname\": \"School Y\",\n \"schoolcode\": \"schooly\",\n \"group_id\": \"group_A\",\n \"password\": \"password\",\n \"changepassword\": \"true\"\n})\n\ndb.user_studentrole.insert({\n \"user_id\": \"user_c\",\n \"role_ids\": [\"user\"]\n})\n\nuser_id = db.student.insert({\n \"_id\": \"user_d\",\n \"firstname\": \"FirstD\",\n \"lastname\": \"LastD\",\n \"schoolname\": \"School Y\",\n \"schoolcode\": \"schooly\",\n \"group_id\": \"group_B\",\n \"password\": \"password\",\n \"changepassword\": \"true\"\n})\n\ndb.user_studentrole.insert({\n \"user_id\": \"user_d\",\n \"role_ids\": [\"user\", \"admin\"]\n})\n\nuser_id = db.student.insert({\n \"_id\": \"super.admin\",\n \"group_id\": \"group_C\",\n \"password\": \"password\"\n})\n\ndb.user_studentrole.insert({\n \"user_id\": \"super.admin\",\n \"role_ids\": [\"user\", \"admin\", \"super\"],\n \"user_mode\": \"COLAB\"\n})\n\nuser_id = db.student.insert({\n \"_id\": \"test\",\n \"group_id\": \"group_A\",\n \"password\": \"isfortesting\"\n})\n\ndb.user_studentrole.insert({\n \"user_id\": \"test\",\n \"role_ids\": [\"user\", \"admin\"]\n})\n\nuser_id = db.student.insert({\n \"_id\": \"student1\",\n \"group_id\": \"group_B\",\n \"password\": \"isastudent\"\n})\n\ndb.user_studentrole.insert({\n \"user_id\": \"student1\",\n \"role_ids\": [\"user\", \"admin\"]\n})\n\nuser_id = db.student.insert({\n \"_id\": \"student2\",\n \"group_id\": \"group_A\",\n \"password\": \"isastudent\"\n})\n\ndb.user_studentrole.insert({\n \"user_id\": \"student2\",\n \"role_ids\": [\"user\", \"admin\"]\n})\n\nuser_id = db.student.insert({\n \"_id\": \"student3\",\n \"group_id\": \"group_B\",\n \"password\": \"isastudent\"\n})\n\ndb.user_studentrole.insert({\n \"user_id\": \"student3\",\n \"role_ids\": [\"user\", \"admin\"]\n})\n\n\n######### create junctions and associate with groups\n\ndb.junction.insert({\n \"_id\": intersection_id1,\n \"west_lane_out\":\"-19485812#3\",\n \"west_lane_out_values\":[\"-19485812#3_0\",\"-19485812#3_1\"],\n \"west_lane_in\":\"19485812#3\",\n \"west_lane_in_values\":[\"19485812#3_1\", \"19485812#3_0\"],\n # left, straight, right\n \"west_lane_in_adjascent\":[\"-19457616#3\", \"-19456179#4\", \"19457616#4\"],\n \n \"east_lane_in\":\"19456179#4\",\n \"east_lane_in_values\":[\"19456179#4_0\",\"19456179#4_1\"],\n \"east_lane_in_adjascent\":[\"19457616#4\", \"-19485812#3\", \"-19457616#3\"],\n \"east_lane_out\":\"-19456179#4\",\n \"east_lane_out_values\":[\"-19456179#4_1\", \"-19456179#4_0\"],\n \n \"north_lane_in\":\"19457616#3\",\n \"north_lane_in_values\":[\"19457616#3_0\",\"19457616#3_1\"],\n \"north_lane_in_adjascent\":[\"-19456179#4\", \"19457616#4\", \"-19485812#3\"],\n \"north_lane_out\":\"-19457616#3\",\n \"north_lane_out_values\":[\"-19457616#3_1\",\"-19457616#3_0\"],\n \n \"south_lane_out\":\"19457616#4\",\n \"south_lane_out_values\":[\"19457616#4_0\",\"19457616#4_1\"],\n \"south_lane_in\":\"-19457616#4\",\n \"south_lane_in_values\":[\"-19457616#4_1\", \"-19457616#4_0\"],\n \"south_lane_in_adjascent\":[\"-19485812#3\", \"-19457616#3\", \"-19456179#4\"]\n})\n\ndb.inductionloop.insert({\n \"_id\": \"-19485812#3_0_5\",\n \"junction\": intersection_id1, \n \"location\": \"west_lane_out\",\n \"pos\": 5\n})\n\ndb.inductionloop.insert({\n \"_id\": \"-19485812#3_1_5\",\n \"junction\": intersection_id1, \n \"location\": \"west_lane_out\",\n \"pos\": 5\n})\n\ndb.inductionloop.insert({\n \"_id\": \"19485812#3_0_-5\",\n \"junction\": intersection_id1, \n \"location\": \"west_lane_in\",\n \"pos\": -5\n})\n\ndb.inductionloop.insert({\n \"_id\": \"19485812#3_1_-5\",\n \"junction\": intersection_id1, \n \"location\": \"west_lane_in\",\n \"pos\": -5\n})\n\ndb.inductionloop.insert({\n \"_id\": \"-19456179#4_0_5\",\n \"junction\": intersection_id1, \n \"location\": \"east_lane_out\",\n \"pos\": 5\n})\n\ndb.inductionloop.insert({\n \"_id\": \"-19456179#4_1_5\",\n \"junction\": intersection_id1, \n \"location\": \"east_lane_out\",\n \"pos\": 5\n})\n\ndb.inductionloop.insert({\n \"_id\": \"19456179#4_0_-5\",\n \"junction\": intersection_id1, \n \"location\": \"east_lane_in\",\n \"pos\": -5\n})\n\ndb.inductionloop.insert({\n \"_id\": \"19456179#4_1_-5\",\n \"junction\": intersection_id1, \n \"location\": \"east_lane_in\",\n \"pos\": -5\n})\n\ndb.inductionloop.insert({\n \"_id\": \"-19457616#3_0_5\",\n \"junction\": intersection_id1, \n \"location\": \"north_lane_out\",\n \"pos\": 5\n})\n\ndb.inductionloop.insert({\n \"_id\": \"-19457616#3_1_5\",\n \"junction\": intersection_id1, \n \"location\": \"north_lane_out\",\n \"pos\": 5\n})\n\ndb.inductionloop.insert({\n \"_id\": \"19457616#3_0_-5\",\n \"junction\": intersection_id1, \n \"location\": \"north_lane_in\",\n \"pos\": -5\n})\n\ndb.inductionloop.insert({\n \"_id\": \"19457616#3_1_-5\",\n \"junction\": intersection_id1, \n \"location\": \"north_lane_in\",\n \"pos\": -5\n})\n\ndb.inductionloop.insert({\n \"_id\": \"19457616#4_0_5\",\n \"junction\": intersection_id1, \n \"location\": \"south_lane_out\",\n \"pos\": 5\n})\n\ndb.inductionloop.insert({\n \"_id\": \"19457616#4_1_5\",\n \"junction\": intersection_id1, \n \"location\": \"south_lane_out\",\n \"pos\": 5\n})\n\ndb.inductionloop.insert({\n \"_id\": \"-19457616#4_0_-5\",\n \"junction\": intersection_id1, \n \"location\": \"south_lane_in\",\n \"pos\": -5\n})\n\ndb.inductionloop.insert({\n \"_id\": \"-19457616#4_1_-5\",\n \"junction\": intersection_id1, \n \"location\": \"south_lane_in\",\n \"pos\": -5\n}) \n\n# SIMULATION ID FOR GROUP MODE OF GROUP_A\nsimulation_id = db.simulation.insert({\n \"group_id\": \"group_A\",\n \"duration\": 1000,\n #\"starttime\":\"\",\n #\"endtime\":\"\",\n \"junctions\":[intersection_id1],\n \"latitude\": \"35.03920287110193\",\n \"longitude\": \"-85.28763771057129\",\n \"update_rate\": 2,\n \"max_update_size\": 50,\n \"mode\": \"GROUP\",\n \"problem_id\":\"1\",\n \"status\": \"ACTIVE\"\n})\n\nstate0 = \"Green!0g!1-Green!2!3-Red!4g!5-Red!6!7!8-Red!9-Red!10!11!12-Red!13g!14-Red!7!8\"\nstate1 = \"Yellow!0g!1-Yellow!2!3-Red!4g!5-Red!6!7!8-Red!9-Red!10!11!12-Red!13g!14-Red!7!8\"\nstate2 = \"Red!0g!1-Red!2!3-Red!4g!5-Red!6!7!8-Red!9-Red!10!11!12-Green!13g!14-Green!7!8\"\nstate3 = \"Red!0g!1-Red!2!3-Red!4g!5-Red!6!7!8-Red!9-Red!10!11!12-Yellow!13g!14-Yellow!7!8\"\nstate4 = \"Red!0g!1-Red!2!3-Green!4g!5-Green!6!7!8-Red!9-Red!10!11!12-Red!13g!14-Red!7!8\"\nstate5 = \"Red!0g!1-Red!2!3-Yellow!4g!5-Yellow!6!7!8-Red!9-Red!10!11!12-Red!13g!14-Red!7!8\"\nstate6 = \"Red!0g!1-Red!2!3-Red!4g!5-Red!6!7!8-Green!9-Green!10!11!12-Red!13g!14-Red!7!8\"\nstate7 = \"Red!0g!1-Red!2!3-Red!4g!5-Red!6!7!8-Yellow!9-Yellow!10!11!12-Red!13g!14-Red!7!8\"\nduration = 1\nTrafficLightDAO().createTrafficLightLogic(simulation_id, intersection_id1, state0, duration)\nTrafficLightDAO().createTrafficLightLogic(simulation_id, intersection_id1, state1, duration)\nTrafficLightDAO().createTrafficLightLogic(simulation_id, intersection_id1, state2, duration)\nTrafficLightDAO().createTrafficLightLogic(simulation_id, intersection_id1, state3, duration)\nTrafficLightDAO().createTrafficLightLogic(simulation_id, intersection_id1, state4, duration)\nTrafficLightDAO().createTrafficLightLogic(simulation_id, intersection_id1, state5, duration)\nTrafficLightDAO().createTrafficLightLogic(simulation_id, intersection_id1, state6, duration)\nTrafficLightDAO().createTrafficLightLogic(simulation_id, intersection_id1, state7, duration)\n\ndb.simulation_association.insert({\n \"sim_id\" : simulation_id,\n \"sim_asso\" : [simulation_id]\n})\n\ndb.vehicle.insert({\n\t\"simulation_id\": simulation_id, \n\t\"name\": \"Car\",\n\t\"accel\": \"20\",\n\t\"decel\": \"30\",\n\t\"sigma\": \"1\",\n\t\"max_speed\": \"100\",\n\t\"length\": \"10\",\n\t\"probability\": \"0.5\"\n})\n\ndb.vehicle.insert({\n\t\"simulation_id\": simulation_id, \n\t\"name\": \"Bus\",\n\t\"accel\": \"15\",\n\t\"decel\": \"25\",\n\t\"sigma\": \"1\",\n\t\"max_speed\": \"70\",\n\t\"length\": \"15\",\n\t\"probability\": \"0.3\"\n})\n\ndb.vehicle.insert({\n\t\"name\": \"Truck\",\n\t\"simulation_id\": simulation_id, \n\t\"accel\": \"10\",\n\t\"decel\": \"15\",\n\t\"sigma\": \"1\",\n\t\"max_speed\": \"50\",\n\t\"length\": \"20\",\n\t\"probability\": \"0.2\"\n})\n\n# INTERSECTION #1 for GROUP MODE:\ndb.turnprobability.insert({\n\t\"simulation_id\": simulation_id, \n\t\"intersection_id\": intersection_id1, \n\t\"edge_id\": \"19485812#3\",\n\t\"left_turn\": \"0.2\",\n\t\"right_turn\": \"0.2\",\n\t\"go_straight\": \"0.6\",\n\t\"to_edge_left\": \"-19457616#3\",\n\t\"to_edge_right\": \"19457616#4\",\n\t\"to_edge_straight\": \"-19456179#4\"\n})\n\ndb.turnprobability.insert({\n\t\"simulation_id\": simulation_id, \n\t\"intersection_id\": intersection_id1, \n\t\"edge_id\": \"19457616#3\",\n\t\"left_turn\": \"0.2\",\n\t\"right_turn\": \"0.2\",\n\t\"go_straight\": \"0.6\",\n\t\"to_edge_left\": \"-19456179#4\",\n\t\"to_edge_right\": \"-19485812#3\",\n\t\"to_edge_straight\": \"19457616#4\"\n})\n\ndb.turnprobability.insert({\n\t\"simulation_id\": simulation_id, \n\t\"intersection_id\": intersection_id1, \n\t\"edge_id\": \"19456179#4\",\n\t\"left_turn\": \"0.2\",\n\t\"right_turn\": \"0.2\",\n\t\"go_straight\": \"0.6\",\n\t\"to_edge_left\": \"19457616#4\",\n\t\"to_edge_right\": \"-19457616#3\",\n\t\"to_edge_straight\": \"-19485812#3\"\n})\n\ndb.turnprobability.insert({\n\t\"simulation_id\": simulation_id, \n\t\"intersection_id\": intersection_id1, \n\t\"edge_id\": \"-19457616#4\",\n\t\"left_turn\": \"0.2\",\n\t\"right_turn\": \"0.2\",\n\t\"go_straight\": \"0.6\",\n\t\"to_edge_left\": \"-19485812#3\",\n\t\"to_edge_right\": \"-19456179#4\",\n\t\"to_edge_straight\": \"-19457616#3\"\n})\n\n\n#\t\t| B\t\t\t\t\t| C\n#\t\t| \t\t\t\t\t| \n#\t\t| \t\tIwest\t\t|\n# --A-- O1-----------------\tO2---D---\n#\t\t|\t\tIeast\t\t|\n#\t\t|\t\t\t\t\t|\n# Lsouth| Lnorth\tJsouth\t| Jnorth\n#\t\t|\t\t\t\t\t|\n#\t\t|\t\tKeast\t\t|\n# --H-- O4----------------- O3---E---\n#\t\t|\t\tKwest\t\t|\n#\t\t|\t\t\t\t\t|\n#\t\t| G\t\t\t\t\t| F\n\n# INTERSECTION #1 for GROUP MODE:\n\ndb.flows.insert({\n \"point_name\": \"A\",\n\t\"simulation_id\": simulation_id,\n \"intersection_id\": intersection_id1,\n\t\"from_edge_id\": \"-51067022#17\",\n\t\"to_edge_id\": \"n/a\",\n\t\"via_edge_id\": \"-51067022#17\",\n \"flow_rate\": \"600\",\n\t\"latitude\": \"35.03940051840894\",\n\t\"longitude\": \"-85.2841266989708\",\n\t\"removable\": \"0\"\n})\n\ndb.flows.insert({\n \"point_name\": \"B\",\n\t\"simulation_id\": simulation_id,\n \"intersection_id\": intersection_id1,\n\t\"from_edge_id\": \"-19493531#0\",\n\t\"to_edge_id\": \"n/a\",\n\t\"via_edge_id\": \"-19493531#0\",\n \"flow_rate\": \"600\",\n\t\"latitude\": \"35.03974530201119\",\n\t\"longitude\": \"-85.28242081403732\",\n\t\"removable\": \"0\"\n})\n\ndb.flows.insert({\n \"point_name\": \"Iwest\",\n\t\"simulation_id\": simulation_id,\n \"intersection_id\": intersection_id1,\n\t\"from_edge_id\": \"51067022#11\",\n\t\"to_edge_id\": \"n/a\",\n\t\"via_edge_id\": \"51067022#11\",\n \"flow_rate\": \"600\",\n\t\"latitude\": \"35.03683106612615\",\n\t\"longitude\": \"-85.27720928192139\",\n\t\"removable\": \"0\"\n})\n\ndb.flows.insert({\n \"point_name\": \"Ieast\",\n\t\"simulation_id\": simulation_id,\n \"intersection_id\": intersection_id1,\n\t\"from_edge_id\": \"-51067022#11\",\n\t\"to_edge_id\": \"n/a\",\n\t\"via_edge_id\": \"-51067022#11\",\n \"flow_rate\": \"600\",\n\t\"latitude\": \"35.03701115003017\",\n\t\"longitude\": \"-85.27769207954407\",\n\t\"removable\": \"1\"\n})\n\ndb.flows.insert({\n \"point_name\": \"Lnorth\",\n\t\"simulation_id\": simulation_id,\n \"intersection_id\": intersection_id1,\n\t\"from_edge_id\": \"-19503247#1\",\n\t\"to_edge_id\": \"n/a\",\n\t\"via_edge_id\": \"-19503247#1\",\n \"flow_rate\": \"600\",\n\t\"latitude\": \"35.037911563597234\",\n\t\"longitude\": \"-85.28341591358185\",\n\t\"removable\": \"0\"\n})\n\ndb.flows.insert({\n \"point_name\": \"Lsouth\",\n\t\"simulation_id\": simulation_id,\n \"intersection_id\": intersection_id1,\n\t\"from_edge_id\": \"19503247#1\",\n\t\"to_edge_id\": \"n/a\",\n\t\"via_edge_id\": \"19503247#1\",\n \"flow_rate\": \"600\",\n\t\"latitude\": \"35.037485515487546\",\n\t\"longitude\": \"-85.28366267681122\",\n\t\"removable\": \"1\"\n})\n\n\n''' This is just to see the \nschema of the table\ndb.trafficlightlogic.insert({\n\t\"intersection_id\": intersection_id1,\n\t\"light_index\": \"0\",\n\t\"state\": \"Green\",\n\t\"duration\": \"30\",\n\t\"creation_time\": datetime.now()\n})\n'''\n\n# SIMULATION ID FOR COLLABORATION MODE OF GROUP_A\nsimulation_id = db.simulation.insert({\n \"group_id\": \"group_A\",\n \"duration\": 1000,\n #\"starttime\":\"\",\n #\"endtime\":\"\",", "answers": [" \"junctions\":[intersection_id1],"], "length": 983, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "ce2b689f-1705-4df8-b0b6-a6d9b6c44695", "reasoning": "The code is inserting a new simulation document for collaboration mode of group_A. The previous group-mode insertion included many fields after 'duration', starting with 'junctions'. Here the dict is opened and currently ends after the 'duration' line and commented start/end times. The next logical line continues the dictionary with the 'junctions' field, matching the pattern of the earlier insertion.", "reasoning_model_answer": "\"junctions\": [intersection_id1],", "assistant_with_reasoning": "\nThe code is inserting a new simulation document for collaboration mode of group_A. The previous group-mode insertion included many fields after 'duration', starting with 'junctions'. Here the dict is opened and currently ends after the 'duration' line and commented start/end times. The next logical line continues the dictionary with the 'junctions' field, matching the pattern of the earlier insertion.\n\n\"junctions\": [intersection_id1],", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 5.221, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 13836, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "\"junctions\": [intersection_id1],", "score": 0.93, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "// ReSharper disable All\nusing System.Collections.Generic;\nusing System.Net;\nusing System.Net.Http;\nusing System.Web.Http;\nusing MixERP.Net.Api.Framework;\nusing MixERP.Net.ApplicationState.Cache;\nusing MixERP.Net.Common.Extensions;\nusing MixERP.Net.EntityParser;\nusing MixERP.Net.Framework;\nusing Newtonsoft.Json;\nusing Newtonsoft.Json.Linq;\nusing PetaPoco;\n\nnamespace MixERP.Net.Api.Core\n{\n /// \n /// Provides a direct HTTP access to perform various tasks such as adding, editing, and removing Kanbans.\n /// \n [RoutePrefix(\"api/v1.5/core/kanban\")]\n public class KanbanController : ApiController\n {\n /// \n /// The Kanban data context.\n /// \n private readonly MixERP.Net.Schemas.Core.Data.Kanban KanbanContext;\n\n public KanbanController()\n {\n this._LoginId = AppUsers.GetCurrent().View.LoginId.ToLong();\n this._UserId = AppUsers.GetCurrent().View.UserId.ToInt();\n this._OfficeId = AppUsers.GetCurrent().View.OfficeId.ToInt();\n this._Catalog = AppUsers.GetCurrentUserDB();\n\n this.KanbanContext = new MixERP.Net.Schemas.Core.Data.Kanban\n {\n _Catalog = this._Catalog,\n _LoginId = this._LoginId,\n _UserId = this._UserId\n };\n }\n\n public long _LoginId { get; }\n public int _UserId { get; private set; }\n public int _OfficeId { get; private set; }\n public string _Catalog { get; }\n\n /// \n /// Creates meta information of \"kanban\" entity.\n /// \n /// Returns the \"kanban\" meta information to perform CRUD operation.\n [AcceptVerbs(\"GET\", \"HEAD\")]\n [Route(\"meta\")]\n [Route(\"~/api/core/kanban/meta\")]\n public EntityView GetEntityView()\n {\n return new EntityView\n {\n PrimaryKey = \"kanban_id\",\n Columns = new List()\n {\n new EntityColumn { ColumnName = \"kanban_id\", PropertyName = \"KanbanId\", DataType = \"long\", DbDataType = \"int8\", IsNullable = false, IsPrimaryKey = true, IsSerial = true, Value = \"\", MaxLength = 0 },\n new EntityColumn { ColumnName = \"object_name\", PropertyName = \"ObjectName\", DataType = \"string\", DbDataType = \"varchar\", IsNullable = false, IsPrimaryKey = false, IsSerial = false, Value = \"\", MaxLength = 128 },\n new EntityColumn { ColumnName = \"user_id\", PropertyName = \"UserId\", DataType = \"int\", DbDataType = \"int4\", IsNullable = false, IsPrimaryKey = false, IsSerial = false, Value = \"\", MaxLength = 0 },\n new EntityColumn { ColumnName = \"kanban_name\", PropertyName = \"KanbanName\", DataType = \"string\", DbDataType = \"varchar\", IsNullable = false, IsPrimaryKey = false, IsSerial = false, Value = \"\", MaxLength = 128 },\n new EntityColumn { ColumnName = \"description\", PropertyName = \"Description\", DataType = \"string\", DbDataType = \"text\", IsNullable = true, IsPrimaryKey = false, IsSerial = false, Value = \"\", MaxLength = 0 },\n new EntityColumn { ColumnName = \"audit_user_id\", PropertyName = \"AuditUserId\", DataType = \"int\", DbDataType = \"int4\", IsNullable = true, IsPrimaryKey = false, IsSerial = false, Value = \"\", MaxLength = 0 },\n new EntityColumn { ColumnName = \"audit_ts\", PropertyName = \"AuditTs\", DataType = \"DateTime\", DbDataType = \"timestamptz\", IsNullable = true, IsPrimaryKey = false, IsSerial = false, Value = \"\", MaxLength = 0 }\n }\n };\n }\n\n /// \n /// Counts the number of kanbans.\n /// \n /// Returns the count of the kanbans.\n [AcceptVerbs(\"GET\", \"HEAD\")]\n [Route(\"count\")]\n [Route(\"~/api/core/kanban/count\")]\n public long Count()\n {\n try\n {\n return this.KanbanContext.Count();\n }\n catch (UnauthorizedException)\n {\n throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));\n }\n catch (MixERPException ex)\n {\n throw new HttpResponseException(new HttpResponseMessage\n {\n Content = new StringContent(ex.Message),\n StatusCode = HttpStatusCode.InternalServerError\n });\n }\n catch\n {\n throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));\n }\n }\n\n /// \n /// Returns collection of kanban for export.\n /// \n /// \n [AcceptVerbs(\"GET\", \"HEAD\")]\n [Route(\"export\")]\n [Route(\"all\")]\n [Route(\"~/api/core/kanban/export\")]\n [Route(\"~/api/core/kanban/all\")]\n public IEnumerable Get()\n {\n try\n {\n return this.KanbanContext.Get();\n }\n catch (UnauthorizedException)\n {\n throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));\n }\n catch (MixERPException ex)\n {\n throw new HttpResponseException(new HttpResponseMessage\n {\n Content = new StringContent(ex.Message),\n StatusCode = HttpStatusCode.InternalServerError\n });\n }\n catch\n {\n throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));\n }\n }\n\n /// \n /// Returns an instance of kanban.\n /// \n /// Enter KanbanId to search for.\n /// \n [AcceptVerbs(\"GET\", \"HEAD\")]\n [Route(\"{kanbanId}\")]\n [Route(\"~/api/core/kanban/{kanbanId}\")]\n public MixERP.Net.Entities.Core.Kanban Get(long kanbanId)\n {\n try\n {\n return this.KanbanContext.Get(kanbanId);\n }\n catch (UnauthorizedException)\n {\n throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));\n }\n catch (MixERPException ex)\n {\n throw new HttpResponseException(new HttpResponseMessage\n {\n Content = new StringContent(ex.Message),\n StatusCode = HttpStatusCode.InternalServerError\n });\n }\n catch\n {\n throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));\n }\n }\n\n [AcceptVerbs(\"GET\", \"HEAD\")]\n [Route(\"get\")]\n [Route(\"~/api/core/kanban/get\")]\n public IEnumerable Get([FromUri] long[] kanbanIds)\n {\n try\n {\n return this.KanbanContext.Get(kanbanIds);\n }\n catch (UnauthorizedException)\n {\n throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));\n }\n catch (MixERPException ex)\n {\n throw new HttpResponseException(new HttpResponseMessage\n {\n Content = new StringContent(ex.Message),\n StatusCode = HttpStatusCode.InternalServerError\n });\n }\n catch\n {\n throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));\n }\n }\n\n /// \n /// Creates a paginated collection containing 10 kanbans on each page, sorted by the property KanbanId.\n /// \n /// Returns the first page from the collection.\n [AcceptVerbs(\"GET\", \"HEAD\")]\n [Route(\"\")]\n [Route(\"~/api/core/kanban\")]\n public IEnumerable GetPaginatedResult()\n {\n try\n {\n return this.KanbanContext.GetPaginatedResult();\n }\n catch (UnauthorizedException)\n {\n throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));\n }\n catch (MixERPException ex)\n {\n throw new HttpResponseException(new HttpResponseMessage\n {\n Content = new StringContent(ex.Message),\n StatusCode = HttpStatusCode.InternalServerError\n });\n }\n catch\n {\n throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));\n }\n }\n\n /// \n /// Creates a paginated collection containing 10 kanbans on each page, sorted by the property KanbanId.\n /// \n /// Enter the page number to produce the resultset.\n /// Returns the requested page from the collection.\n [AcceptVerbs(\"GET\", \"HEAD\")]\n [Route(\"page/{pageNumber}\")]\n [Route(\"~/api/core/kanban/page/{pageNumber}\")]\n public IEnumerable GetPaginatedResult(long pageNumber)\n {\n try\n {\n return this.KanbanContext.GetPaginatedResult(pageNumber);\n }\n catch (UnauthorizedException)\n {\n throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));\n }\n catch (MixERPException ex)\n {\n throw new HttpResponseException(new HttpResponseMessage\n {\n Content = new StringContent(ex.Message),\n StatusCode = HttpStatusCode.InternalServerError\n });\n }\n catch\n {\n throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));\n }\n }\n\n /// \n /// Counts the number of kanbans using the supplied filter(s).\n /// \n /// The list of filter conditions.\n /// Returns the count of filtered kanbans.\n [AcceptVerbs(\"POST\")]\n [Route(\"count-where\")]\n [Route(\"~/api/core/kanban/count-where\")]\n public long CountWhere([FromBody]JArray filters)\n {\n try\n {\n List f = filters.ToObject>(JsonHelper.GetJsonSerializer());\n return this.KanbanContext.CountWhere(f);\n }\n catch (UnauthorizedException)\n {\n throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));\n }\n catch (MixERPException ex)\n {\n throw new HttpResponseException(new HttpResponseMessage\n {\n Content = new StringContent(ex.Message),\n StatusCode = HttpStatusCode.InternalServerError\n });\n }\n catch\n {\n throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));\n }\n }\n\n /// \n /// Creates a filtered and paginated collection containing 10 kanbans on each page, sorted by the property KanbanId.\n /// \n /// Enter the page number to produce the resultset. If you provide a negative number, the result will not be paginated.\n /// The list of filter conditions.\n /// Returns the requested page from the collection using the supplied filters.\n [AcceptVerbs(\"POST\")]\n [Route(\"get-where/{pageNumber}\")]\n [Route(\"~/api/core/kanban/get-where/{pageNumber}\")]\n public IEnumerable GetWhere(long pageNumber, [FromBody]JArray filters)\n {\n try\n {\n List f = filters.ToObject>(JsonHelper.GetJsonSerializer());\n return this.KanbanContext.GetWhere(pageNumber, f);\n }\n catch (UnauthorizedException)\n {\n throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));\n }\n catch (MixERPException ex)\n {\n throw new HttpResponseException(new HttpResponseMessage\n {\n Content = new StringContent(ex.Message),\n StatusCode = HttpStatusCode.InternalServerError\n });\n }\n catch\n {\n throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));\n }\n }\n\n /// \n /// Counts the number of kanbans using the supplied filter name.\n /// \n /// The named filter.\n /// Returns the count of filtered kanbans.\n [AcceptVerbs(\"GET\", \"HEAD\")]\n [Route(\"count-filtered/{filterName}\")]\n [Route(\"~/api/core/kanban/count-filtered/{filterName}\")]\n public long CountFiltered(string filterName)\n {\n try\n {", "answers": [" return this.KanbanContext.CountFiltered(filterName);"], "length": 1034, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "d7662fce-f074-43e0-baae-e3155b8c6999", "reasoning": "In the CountFiltered method, after entering the try block the code should invoke the corresponding context method to get the filtered count. All similar methods (e.g., Count, CountWhere) call a context method and return its result inside the try block. Therefore the next line should return the result of KanbanContext.CountFiltered(filterName).", "reasoning_model_answer": "return this.KanbanContext.CountFiltered(filterName);", "assistant_with_reasoning": "\nIn the CountFiltered method, after entering the try block the code should invoke the corresponding context method to get the filtered count. All similar methods (e.g., Count, CountWhere) call a context method and return its result inside the try block. Therefore the next line should return the result of KanbanContext.CountFiltered(filterName).\n\nreturn this.KanbanContext.CountFiltered(filterName);", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 1.729, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 14181, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "return this.KanbanContext.CountFiltered(filterName);", "score": 0.87, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "# Copyright 2017 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Preprocess images and bounding boxes for detection.\n\nWe perform two sets of operations in preprocessing stage:\n(a) operations that are applied to both training and testing data,\n(b) operations that are applied only to training data for the purpose of\n data augmentation.\n\nA preprocessing function receives a set of inputs,\ne.g. an image and bounding boxes,\nperforms an operation on them, and returns them.\nSome examples are: randomly cropping the image, randomly mirroring the image,\n randomly changing the brightness, contrast, hue and\n randomly jittering the bounding boxes.\n\nThe image is a rank 4 tensor: [1, height, width, channels] with\ndtype=tf.float32. The groundtruth_boxes is a rank 2 tensor: [N, 4] where\nin each row there is a box with [ymin xmin ymax xmax].\nBoxes are in normalized coordinates meaning\ntheir coordinate values range in [0, 1]\n\nImportant Note: In tensor_dict, images is a rank 4 tensor, but preprocessing\nfunctions receive a rank 3 tensor for processing the image. Thus, inside the\npreprocess function we squeeze the image to become a rank 3 tensor and then\nwe pass it to the functions. At the end of the preprocess we expand the image\nback to rank 4.\n\"\"\"\n\nimport tensorflow.compat.v2 as tf\n\nimport numpy as np\n\nfrom official.vision.detection.utils.object_detection import box_list\n\n\ndef _flip_boxes_left_right(boxes):\n \"\"\"Left-right flip the boxes.\n\n Args:\n boxes: rank 2 float32 tensor containing the bounding boxes -> [N, 4].\n Boxes are in normalized form meaning their coordinates vary\n between [0, 1].\n Each row is in the form of [ymin, xmin, ymax, xmax].\n\n Returns:\n Flipped boxes.\n \"\"\"\n ymin, xmin, ymax, xmax = tf.split(value=boxes, num_or_size_splits=4, axis=1)\n flipped_xmin = tf.subtract(1.0, xmax)\n flipped_xmax = tf.subtract(1.0, xmin)\n flipped_boxes = tf.concat([ymin, flipped_xmin, ymax, flipped_xmax], 1)\n return flipped_boxes\n\n\ndef _flip_masks_left_right(masks):\n \"\"\"Left-right flip masks.\n\n Args:\n masks: rank 3 float32 tensor with shape\n [num_instances, height, width] representing instance masks.\n\n Returns:\n flipped masks: rank 3 float32 tensor with shape\n [num_instances, height, width] representing instance masks.\n \"\"\"\n return masks[:, :, ::-1]\n\n\ndef keypoint_flip_horizontal(keypoints, flip_point, flip_permutation,\n scope=None):\n \"\"\"Flips the keypoints horizontally around the flip_point.\n\n This operation flips the x coordinate for each keypoint around the flip_point\n and also permutes the keypoints in a manner specified by flip_permutation.\n\n Args:\n keypoints: a tensor of shape [num_instances, num_keypoints, 2]\n flip_point: (float) scalar tensor representing the x coordinate to flip the\n keypoints around.\n flip_permutation: rank 1 int32 tensor containing the keypoint flip\n permutation. This specifies the mapping from original keypoint indices\n to the flipped keypoint indices. This is used primarily for keypoints\n that are not reflection invariant. E.g. Suppose there are 3 keypoints\n representing ['head', 'right_eye', 'left_eye'], then a logical choice for\n flip_permutation might be [0, 2, 1] since we want to swap the 'left_eye'\n and 'right_eye' after a horizontal flip.\n scope: name scope.\n\n Returns:\n new_keypoints: a tensor of shape [num_instances, num_keypoints, 2]\n \"\"\"\n if not scope:\n scope = 'FlipHorizontal'\n with tf.name_scope(scope):\n keypoints = tf.transpose(a=keypoints, perm=[1, 0, 2])\n keypoints = tf.gather(keypoints, flip_permutation)\n v, u = tf.split(value=keypoints, num_or_size_splits=2, axis=2)\n u = flip_point * 2.0 - u\n new_keypoints = tf.concat([v, u], 2)\n new_keypoints = tf.transpose(a=new_keypoints, perm=[1, 0, 2])\n return new_keypoints\n\n\ndef keypoint_change_coordinate_frame(keypoints, window, scope=None):\n \"\"\"Changes coordinate frame of the keypoints to be relative to window's frame.\n\n Given a window of the form [y_min, x_min, y_max, x_max], changes keypoint\n coordinates from keypoints of shape [num_instances, num_keypoints, 2]\n to be relative to this window.\n\n An example use case is data augmentation: where we are given groundtruth\n keypoints and would like to randomly crop the image to some window. In this\n case we need to change the coordinate frame of each groundtruth keypoint to be\n relative to this new window.\n\n Args:\n keypoints: a tensor of shape [num_instances, num_keypoints, 2]\n window: a tensor of shape [4] representing the [y_min, x_min, y_max, x_max]\n window we should change the coordinate frame to.\n scope: name scope.\n\n Returns:\n new_keypoints: a tensor of shape [num_instances, num_keypoints, 2]\n \"\"\"\n if not scope:\n scope = 'ChangeCoordinateFrame'\n with tf.name_scope(scope):\n win_height = window[2] - window[0]\n win_width = window[3] - window[1]\n new_keypoints = box_list_ops.scale(keypoints - [window[0], window[1]],\n 1.0 / win_height, 1.0 / win_width)\n return new_keypoints\n\n\ndef keypoint_prune_outside_window(keypoints, window, scope=None):\n \"\"\"Prunes keypoints that fall outside a given window.\n\n This function replaces keypoints that fall outside the given window with nan.\n See also clip_to_window which clips any keypoints that fall outside the given\n window.\n\n Args:\n keypoints: a tensor of shape [num_instances, num_keypoints, 2]\n window: a tensor of shape [4] representing the [y_min, x_min, y_max, x_max]\n window outside of which the op should prune the keypoints.\n scope: name scope.\n\n Returns:\n new_keypoints: a tensor of shape [num_instances, num_keypoints, 2]\n \"\"\"\n if not scope:\n scope = 'PruneOutsideWindow'\n with tf.name_scope(scope):\n y, x = tf.split(value=keypoints, num_or_size_splits=2, axis=2)\n win_y_min, win_x_min, win_y_max, win_x_max = tf.unstack(window)\n\n valid_indices = tf.logical_and(\n tf.logical_and(y >= win_y_min, y <= win_y_max),\n tf.logical_and(x >= win_x_min, x <= win_x_max))\n\n new_y = tf.where(valid_indices, y, np.nan * tf.ones_like(y))\n new_x = tf.where(valid_indices, x, np.nan * tf.ones_like(x))\n new_keypoints = tf.concat([new_y, new_x], 2)\n\n return new_keypoints\n\n\ndef random_horizontal_flip(image,\n boxes=None,\n masks=None,\n keypoints=None,\n keypoint_flip_permutation=None,\n seed=None):\n \"\"\"Randomly flips the image and detections horizontally.\n\n The probability of flipping the image is 50%.\n\n Args:\n image: rank 3 float32 tensor with shape [height, width, channels].\n boxes: (optional) rank 2 float32 tensor with shape [N, 4]\n containing the bounding boxes.\n Boxes are in normalized form meaning their coordinates vary\n between [0, 1].\n Each row is in the form of [ymin, xmin, ymax, xmax].\n masks: (optional) rank 3 float32 tensor with shape\n [num_instances, height, width] containing instance masks. The masks\n are of the same height, width as the input `image`.\n keypoints: (optional) rank 3 float32 tensor with shape\n [num_instances, num_keypoints, 2]. The keypoints are in y-x\n normalized coordinates.\n keypoint_flip_permutation: rank 1 int32 tensor containing the keypoint flip\n permutation.\n seed: random seed\n\n Returns:\n image: image which is the same shape as input image.\n\n If boxes, masks, keypoints, and keypoint_flip_permutation are not None,\n the function also returns the following tensors.\n\n boxes: rank 2 float32 tensor containing the bounding boxes -> [N, 4].\n Boxes are in normalized form meaning their coordinates vary\n between [0, 1].\n masks: rank 3 float32 tensor with shape [num_instances, height, width]\n containing instance masks.\n keypoints: rank 3 float32 tensor with shape\n [num_instances, num_keypoints, 2]\n\n Raises:\n ValueError: if keypoints are provided but keypoint_flip_permutation is not.\n \"\"\"\n\n def _flip_image(image):\n # flip image\n image_flipped = tf.image.flip_left_right(image)\n return image_flipped\n\n if keypoints is not None and keypoint_flip_permutation is None:\n raise ValueError(\n 'keypoints are provided but keypoints_flip_permutation is not provided')\n\n with tf.name_scope('RandomHorizontalFlip'):\n result = []\n # random variable defining whether to do flip or not\n do_a_flip_random = tf.greater(tf.random.uniform([], seed=seed), 0.5)\n\n # flip image\n image = tf.cond(\n pred=do_a_flip_random,\n true_fn=lambda: _flip_image(image),\n false_fn=lambda: image)\n result.append(image)\n\n # flip boxes\n if boxes is not None:\n boxes = tf.cond(\n pred=do_a_flip_random,\n true_fn=lambda: _flip_boxes_left_right(boxes),\n false_fn=lambda: boxes)\n result.append(boxes)\n\n # flip masks\n if masks is not None:\n masks = tf.cond(\n pred=do_a_flip_random,\n true_fn=lambda: _flip_masks_left_right(masks),\n false_fn=lambda: masks)\n result.append(masks)\n\n # flip keypoints\n if keypoints is not None and keypoint_flip_permutation is not None:\n permutation = keypoint_flip_permutation\n keypoints = tf.cond(\n pred=do_a_flip_random,\n true_fn=lambda: keypoint_flip_horizontal(keypoints, 0.5, permutation),\n false_fn=lambda: keypoints)", "answers": [" result.append(keypoints)"], "length": 1236, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "f01b0c70-4956-4476-9eed-cce6304941b7", "reasoning": "The function random_horizontal_flip builds a list 'result' of the processed tensors. After handling image, boxes, and masks, it processes keypoints inside an if block, applying tf.cond to possibly flip them. The next logical step is to add the (potentially flipped) keypoints tensor to the result list, matching the pattern used for the other components.", "reasoning_model_answer": "result.append(keypoints)", "assistant_with_reasoning": "\nThe function random_horizontal_flip builds a list 'result' of the processed tensors. After handling image, boxes, and masks, it processes keypoints inside an if block, applying tf.cond to possibly flip them. The next logical step is to add the (potentially flipped) keypoints tensor to the result list, matching the pattern used for the other components.\n\nresult.append(keypoints)", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.985, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 10397, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "result.append(keypoints)", "score": 0.89, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "# Copyright 2018 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Tests for trackable object SavedModel save.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\nfrom absl.testing import parameterized\n\nfrom google.protobuf import text_format\n\nfrom tensorflow.core.framework import graph_pb2\nfrom tensorflow.core.protobuf import graph_debug_info_pb2\nfrom tensorflow.python.client import session as session_lib\nfrom tensorflow.python.data.ops import dataset_ops\nfrom tensorflow.python.distribute import mirrored_strategy\nfrom tensorflow.python.eager import backprop\nfrom tensorflow.python.eager import context\nfrom tensorflow.python.eager import def_function\nfrom tensorflow.python.eager import test\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import meta_graph\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework import tensor_spec\nfrom tensorflow.python.framework import test_util\nfrom tensorflow.python.framework import versions\nfrom tensorflow.python.lib.io import file_io\nfrom tensorflow.python.module import module\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import control_flow_ops\nfrom tensorflow.python.ops import lookup_ops\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops import resource_variable_ops\nfrom tensorflow.python.ops import variables\nfrom tensorflow.python.saved_model import loader\nfrom tensorflow.python.saved_model import loader_impl\nfrom tensorflow.python.saved_model import save\nfrom tensorflow.python.saved_model import save_options\nfrom tensorflow.python.saved_model import signature_constants\nfrom tensorflow.python.saved_model import tag_constants\nfrom tensorflow.python.training import saver\nfrom tensorflow.python.training.tracking import tracking\nfrom tensorflow.python.training.tracking import util\nfrom tensorflow.python.util import compat\n\n\ndef _run_signature(session, meta_graph_def, inputs, signature_key):\n signature = meta_graph_def.signature_def[signature_key]\n assert set(inputs.keys()) == set(signature.inputs.keys())\n feed_dict = {}\n for arg_name in inputs.keys():\n input_tensor = session.graph.get_tensor_by_name(\n signature.inputs[arg_name].name)\n feed_dict[input_tensor] = inputs[arg_name]\n output_dict = {}\n for output_name, output_tensor_info in signature.outputs.items():\n output_dict[output_name] = session.graph.get_tensor_by_name(\n output_tensor_info.name)\n return session.run(output_dict, feed_dict=feed_dict)\n\n\ndef _import_and_infer(\n save_dir,\n inputs,\n signature_key=signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY):\n \"\"\"Import a SavedModel into a TF 1.x-style graph and run `signature_key`.\"\"\"\n graph = ops.Graph()\n with graph.as_default(), session_lib.Session() as session:\n model = loader.load(session, [tag_constants.SERVING], save_dir)\n return _run_signature(session, model, inputs, signature_key)\n\n\nclass SaveTest(test.TestCase, parameterized.TestCase):\n\n def test_method_save_signature(self):\n root = tracking.AutoTrackable()\n root.f = def_function.function(\n lambda x: 2. * x,\n input_signature=[tensor_spec.TensorSpec(None, dtypes.float32)])\n root.f(constant_op.constant(1.))\n save_dir = os.path.join(self.get_temp_dir(), \"saved_model\")\n save.save(root, save_dir, root.f)\n self.assertEqual({\"output_0\": 2.}, _import_and_infer(save_dir, {\"x\": 1.}))\n\n def test_method_save_list_func(self):\n root = tracking.AutoTrackable()\n\n @def_function.function\n def case_fn(x):\n branch_index = constant_op.constant(1)\n branches = [lambda: x, lambda: x + 1]\n case_out = control_flow_ops.switch_case(branch_index, branches)\n return case_out\n\n root.f = def_function.function(\n lambda x: 2. * case_fn(x),\n input_signature=[tensor_spec.TensorSpec(None, dtypes.float32)])\n root.f(constant_op.constant(1.))\n save_dir = os.path.join(self.get_temp_dir(), \"saved_model\")\n save.save(root, save_dir, root.f)\n self.assertEqual({\"output_0\": 4.}, _import_and_infer(save_dir, {\"x\": 1.}))\n\n def test_method_save_concrete(self):\n root = tracking.AutoTrackable()\n root.f = def_function.function(lambda z: {\"out\": 2. * z})\n root.f(constant_op.constant(1.))\n save_dir = os.path.join(self.get_temp_dir(), \"saved_model\")\n save.save(\n root, save_dir, {\n \"non_default_key\":\n root.f.get_concrete_function(\n tensor_spec.TensorSpec(None, dtypes.float32))\n })\n self.assertEqual({\"out\": 2.},\n _import_and_infer(\n save_dir, {\"z\": 1.}, signature_key=\"non_default_key\"))\n\n def test_method_save_annotated_function(self):\n # This test is only meaningful with Python 3 because Python 2's\n # inspect.getargspec doesn't save annotations.\n\n root = tracking.AutoTrackable()\n\n class UnknownType(object): # pylint: disable=unused-variable\n pass\n\n def annotated_function(z):\n return {\"out\": 2. * z}\n\n # Same effect as annotating function like the following.\n # def annotated_function(\"z\": UnknownType) -> UnknownType:\n # This is a workaround since Python 2 does not support annotations and\n # our presubmit linter catches it.\n annotated_function.__annotations__ = {\n \"z\": UnknownType,\n \"return\": UnknownType\n }\n\n root.f = def_function.function(annotated_function)\n root.f(constant_op.constant(1.))\n save_dir = os.path.join(self.get_temp_dir(), \"saved_model\")\n save.save(\n root, save_dir, {\n \"non_default_key\":\n root.f.get_concrete_function(\n tensor_spec.TensorSpec(None, dtypes.float32))\n })\n self.assertEqual({\"out\": 2.},\n _import_and_infer(\n save_dir, {\"z\": 1.}, signature_key=\"non_default_key\"))\n\n def test_unsaveable_func_graph(self):\n root = module.Module()\n\n @def_function.function(input_signature=[])\n def nested_f():\n ops.get_default_graph().mark_as_unsaveable(\"ERROR MSG\")\n return 1\n\n @def_function.function(input_signature=[])\n def f():\n return nested_f()\n\n root.f = f\n with self.assertRaisesRegex(ValueError, \"ERROR MSG\"):\n save.save(root, os.path.join(self.get_temp_dir(), \"saved_model\"))\n\n def test_untracked_variable_useful_message(self):\n root = module.Module()\n v = variables.Variable(1., name=\"some_unique_name\")\n\n @def_function.function(input_signature=[])\n def f():\n return v.read_value()\n\n root.f = f\n with self.assertRaisesRegex(AssertionError, \"some_unique_name\"):\n save.save(root, os.path.join(self.get_temp_dir(), \"saved_model\"))\n\n def test_version_information_included(self):\n root = tracking.AutoTrackable()\n save_dir = os.path.join(self.get_temp_dir(), \"saved_model\")\n save.save(root, save_dir)\n saved_model_proto = loader_impl.parse_saved_model(save_dir)\n self.assertEqual(\n versions.__version__,\n saved_model_proto.meta_graphs[0].meta_info_def.tensorflow_version)\n self.assertEqual(\n versions.__git_version__,\n saved_model_proto.meta_graphs[0].meta_info_def.tensorflow_git_version)\n\n def test_non_concrete_error(self):\n root = tracking.AutoTrackable()\n root.f = def_function.function(lambda x: 2. * x)\n root.f(constant_op.constant(1.))\n save_dir = os.path.join(self.get_temp_dir(), \"saved_model\")\n with self.assertRaisesRegex(ValueError, \"Expected a TensorFlow function\"):\n save.save(root, save_dir, root.f)\n\n def test_captures_unreachable_variable(self):\n root = tracking.AutoTrackable()\n unreachable_variable = variables.Variable([5.0, 2.0])\n root.reachable_variable = variables.Variable([1.0, 3.0])\n\n @def_function.function\n def increase_variable(x):\n return 2 * unreachable_variable * x + root.reachable_variable\n\n root.f = increase_variable\n\n self.assertAllEqual([101.0, 83.0],\n root.f(constant_op.constant([10.0, 20.0])).numpy())\n\n save_dir = os.path.join(self.get_temp_dir(), \"saved_model\")\n\n with self.assertRaisesRegex(KeyError, \"not reachable from root\"):\n save.save(root, save_dir)\n\n def test_nested_inputs(self):\n root = tracking.AutoTrackable()\n root.f = def_function.function(\n lambda x: 2. * x[0],\n input_signature=([\n tensor_spec.TensorSpec(None, dtypes.float32),\n tensor_spec.TensorSpec(None, dtypes.float32)\n ],))\n root.f([constant_op.constant(1.), constant_op.constant(1.)])\n\n def test_nested_outputs(self):\n root = tracking.AutoTrackable()\n root.f = def_function.function(lambda x: (2. * x, (3. * x, 4. * x)))\n root.f(constant_op.constant(1.))\n to_save = root.f.get_concrete_function(constant_op.constant(1.))\n save_dir = os.path.join(self.get_temp_dir(), \"saved_model\")\n with self.assertRaisesRegex(ValueError, \"non-Tensor value\"):\n save.save(root, save_dir, to_save)\n\n def test_nested_dict_outputs(self):\n root = util.Checkpoint(\n f=def_function.function(lambda x: { # pylint: disable=g-long-lambda\n \"a\": 2. * x,\n \"b\": (3. * x, 4. * x)\n }))\n root.f(constant_op.constant(1.))\n to_save = root.f.get_concrete_function(constant_op.constant(1.))\n save_dir = os.path.join(self.get_temp_dir(), \"saved_model\")\n with self.assertRaisesRegex(ValueError, \"non-Tensor value\"):\n save.save(root, save_dir, to_save)\n\n def test_variable(self):\n root = tracking.AutoTrackable()\n root.v1 = variables.Variable(3.)\n root.v2 = variables.Variable(2.)\n root.f = def_function.function(lambda x: root.v1 * root.v2 * x)\n root.f(constant_op.constant(1.))\n to_save = root.f.get_concrete_function(constant_op.constant(1.))\n save_dir = os.path.join(self.get_temp_dir(), \"saved_model\")\n save.save(root, save_dir, to_save)\n self.assertAllEqual({\"output_0\": 12.},\n _import_and_infer(save_dir, {\"x\": 2.}))\n\n def test_single_function_default_signature(self):\n model = tracking.AutoTrackable()\n model.f = def_function.function(lambda: 3., input_signature=())\n model.f()\n save_dir = os.path.join(self.get_temp_dir(), \"saved_model\")\n save.save(model, save_dir)\n self.assertAllClose({\"output_0\": 3.}, _import_and_infer(save_dir, {}))\n\n def test_single_function_no_signature(self):\n model = tracking.AutoTrackable()\n model.f = def_function.function(lambda: 3.)\n save_dir = os.path.join(self.get_temp_dir(), \"saved_model\")\n save.save(model, save_dir)\n\n def test_find_default_save_function(self):\n\n class ObjWithDefaultSignature(util.Checkpoint):\n\n @def_function.function(input_signature=[\n tensor_spec.TensorSpec(shape=None, dtype=dtypes.float32)\n ])\n def _default_save_signature(self, x):\n return x + x + 1\n\n obj = ObjWithDefaultSignature()\n save_dir = os.path.join(self.get_temp_dir(), \"saved_model\")\n save.save(obj, save_dir)\n self.assertAllClose({\"output_0\": 7.},\n _import_and_infer(save_dir, {\"x\": 3.}))\n\n def test_docstring(self):\n\n class Adder(module.Module):\n\n @def_function.function(input_signature=[\n tensor_spec.TensorSpec(shape=None, dtype=dtypes.float32)\n ])\n def add(self, x):\n return x + x + 1.\n\n to_save = Adder()\n to_save.add(constant_op.constant(1.))\n save_dir = os.path.join(self.get_temp_dir(), \"saved_model\")\n save.save(to_save, save_dir)\n self.assertAllClose({\"output_0\": 7.},\n _import_and_infer(save_dir, {\"x\": 3.}))\n\n def test_datastructures(self):\n\n class HasDatastructures(util.Checkpoint):\n\n def __init__(self):\n self.a = [1.]\n self.a.append(variables.Variable(2.))\n self.b = {\"a\": variables.Variable(3.)}\n\n @def_function.function(input_signature=[\n tensor_spec.TensorSpec(shape=None, dtype=dtypes.float32)\n ])\n def add(self, x):\n return x + math_ops.add_n(self.a) + self.b[\"a\"]\n\n to_save = HasDatastructures()\n to_save.add(constant_op.constant(1.))\n save_dir = os.path.join(self.get_temp_dir(), \"saved_model\")\n save.save(to_save, save_dir)\n self.assertAllClose({\"output_0\": 10.},\n _import_and_infer(save_dir, {\"x\": 4.}))\n\n def test_default_attr_stripping(self):\n\n class Complex(util.Checkpoint):\n\n @def_function.function(input_signature=[])\n def __call__(self):\n return math_ops.complex(\n constant_op.constant(1.), constant_op.constant(2.), name=\"complex\")\n\n to_save = Complex()\n to_save()\n save_dir = os.path.join(self.get_temp_dir(), \"saved_model\")\n save.save(to_save, save_dir)\n graph = ops.Graph()\n with graph.as_default(), self.session(graph) as session:\n loader.load(session, [tag_constants.SERVING], save_dir)\n func, = [f for name, f in graph._functions.items() if \"call\" in name]\n complex_node, = [\n node for node in func.definition.node_def if node.op == \"Complex\"\n ]\n self.assertNotIn(\"T\", complex_node.attr)\n self.assertNotIn(\"Tout\", complex_node.attr)\n\n def test_signature_attribute_reserved(self):\n root = util.Checkpoint(signatures=variables.Variable(1.))\n save_dir = os.path.join(self.get_temp_dir(), \"saved_model\")\n with self.assertRaisesRegex(ValueError, \"del obj.signatures\"):\n save.save(root, save_dir)\n del root.signatures\n save.save(root, save_dir)\n\n def test_function_with_captured_dataset(self):\n if test_util.is_gpu_available():\n self.skipTest(\"Currently broken when a GPU is available.\")\n\n class HasDataset(module.Module):\n\n def __init__(self):\n super(HasDataset, self).__init__()\n self.dataset = (dataset_ops.Dataset.range(5).map(lambda x: x**2))\n\n @def_function.function\n def __call__(self, x):\n current_sum = array_ops.zeros([], dtype=dtypes.int64)\n for element in self.dataset:\n current_sum += x * element\n return current_sum\n\n root = HasDataset()\n save_dir = os.path.join(self.get_temp_dir(), \"saved_model\")\n save.save(\n root,\n save_dir,\n signatures=root.__call__.get_concrete_function(\n tensor_spec.TensorSpec(None, dtypes.int64)))\n self.assertAllClose({\"output_0\": 3 * (1 + 4 + 9 + 16)},\n _import_and_infer(save_dir, {\"x\": 3}))\n\n def test_variable_args_cannot_be_used_as_signature(self):\n\n @def_function.function(input_signature=[\n resource_variable_ops.VariableSpec(shape=[], dtype=dtypes.int32)\n ])\n def f(unused_v):\n return 1\n\n root = tracking.AutoTrackable()\n root.f = f.get_concrete_function()\n with self.assertRaisesRegex(ValueError,\n \"tf.Variable inputs cannot be exported\"):\n save.save(\n root,\n os.path.join(self.get_temp_dir(), \"saved_model\"),\n signatures=root.f)\n\n def test_export_correct_output_shapes(self):\n \"\"\"Asserts that nodes are exported with the correct number of output shapes.\n\n After backpropagation rewrite, functions are rewritten with additional\n outputs. When exporting to SavedModel, the shapes of the additional outputs\n were incorrectly added to the FunctionDef proto (b/133666530).\n \"\"\"\n obj = tracking.AutoTrackable()\n obj.v = variables.Variable(2.)\n\n @def_function.function(\n input_signature=[tensor_spec.TensorSpec(None, dtypes.float32)])\n def f(x):\n return (math_ops.multiply(obj.v, x), math_ops.multiply(obj.v,\n (x + 1)), None)\n\n obj.f = f\n\n @def_function.function(\n input_signature=[tensor_spec.TensorSpec(None, dtypes.float32)])\n def g(x):\n return obj.f(x)[1]\n\n obj.g = g\n\n # After the following lines, the concrete functions of obj.g and obj.f are\n # rewritten with many extra outputs.\n with backprop.GradientTape():\n obj.g(constant_op.constant(3.0))\n\n save_dir = os.path.join(self.get_temp_dir(), \"saved_model\")\n save.save(obj, save_dir, signatures={\"g\": obj.g})\n graph_def = loader_impl.parse_saved_model(save_dir).meta_graphs[0].graph_def\n\n def assert_correct_number_of_output_shapes(node):\n if node.op == \"StatefulPartitionedCall\":\n fn_name = node.attr[\"f\"].func.name\n if fn_name.startswith(\"__inference_f\"):\n self.assertLen(node.attr[\"_output_shapes\"].list.shape, 2)\n if fn_name.startswith(\"__inference_g\"):\n self.assertLen(node.attr[\"_output_shapes\"].list.shape, 1)\n\n for f in graph_def.library.function:\n if (f.signature.name.startswith(\"__inference_f\") or\n f.signature.name.startswith(\"__inference_g\")):\n for node in f.node_def:\n assert_correct_number_of_output_shapes(node)\n\n def test_save_cached_variable(self):\n with ops.Graph().as_default(), session_lib.Session() as session:", "answers": [" obj = tracking.AutoTrackable()"], "length": 1289, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "93b395ae-bdb8-4ddd-8c8c-d6b0534c41c6", "reasoning": "The test method opens a new Graph and Session context. The next logical step is to create a trackable root object to work with inside this graph, matching the pattern of other tests that instantiate `root = tracking.AutoTrackable()` before defining variables and functions.", "reasoning_model_answer": "root = tracking.AutoTrackable()", "assistant_with_reasoning": "\nThe test method opens a new Graph and Session context. The next logical step is to create a trackable root object to work with inside this graph, matching the pattern of other tests that instantiate `root = tracking.AutoTrackable()` before defining variables and functions.\n\nroot = tracking.AutoTrackable()", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 5.27, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 17730, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "root = tracking.AutoTrackable()", "score": 0.84, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/*\n * Copyright 2015 Red Hat, Inc. and/or its affiliates.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.jbpm.test.functional.subprocess;\n\nimport java.util.HashMap;\nimport java.util.Map;\n\nimport org.assertj.core.api.Assertions;\nimport org.jbpm.test.JbpmTestCase;\nimport org.jbpm.test.listener.IterableProcessEventListener;\nimport org.jbpm.test.listener.IterableProcessEventListener.CachedProcessStartedEvent;\nimport org.jbpm.test.listener.TrackingProcessEventListener;\nimport org.junit.Before;\nimport org.junit.Ignore;\nimport org.junit.Test;\nimport org.kie.api.command.Command;\nimport org.kie.api.runtime.KieSession;\nimport org.kie.api.runtime.process.ProcessInstance;\n\nimport static org.jbpm.test.tools.IterableListenerAssert.*;\n\npublic class SubprocessesTest extends JbpmTestCase {\n\n private static final String P2_START = \"Start\";\n private static final String P2_GATEWAY_START = \"Gateway\";\n private static final String P2_GATEWAY_END = \"Gateway\";\n private static final String P2_SIGNAL_END = \"Signal\";\n private static final String P2_END = \"End\";\n\n private static final String P3_START = \"Start\";\n private static final String P3_SIGNAL = \"Signal\";\n private static final String P3_SCRIPT = \"Set variable\";\n private static final String P3_END = \"End\";\n\n private static final String PROCESS_PATH_1 = \"org/jbpm/test/functional/subprocess/Subprocesses-first.bpmn\";\n private static final String PROCESS_ID_1 = \"org.jbpm.test.functional.subprocess.Subprocesses-first\";\n\n private static final String PROCESS_PATH_2 = \"org/jbpm/test/functional/subprocess/Subprocesses-second.bpmn2\";\n private static final String PROCESS_ID_2 = \"org.jbpm.test.functional.subprocess.Subprocesses-second\";\n\n private static final String PROCESS_PATH_3 = \"org/jbpm/test/functional/subprocess/Subprocesses-third.bpmn2\";\n private static final String PROCESS_ID_3 = \"org.jbpm.test.functional.subprocess.Subprocesses-third\";\n\n private static final String HELLO_WORLD_PROCESS = \"org/jbpm/test/functional/common/HelloWorldProcess1.bpmn\";\n private static final String HELLO_WORLD_PROCESS_ID = \"org.jbpm.test.functional.common.HelloWorldProcess1\";\n\n private static final boolean JAVA8 = System.getProperty(\"java.version\").contains(\"1.8\");\n\n private KieSession ksession;\n\n public SubprocessesTest() {\n super(false);\n }\n\n @Before\n public void init() throws Exception {\n ksession = createKSession(PROCESS_PATH_1, PROCESS_PATH_2, PROCESS_PATH_3, HELLO_WORLD_PROCESS);\n }\n\n @Test(timeout = 30000)\n public void testEmbedded() {\n TrackingProcessEventListener process = runProcess(ksession, \"embedded\");\n\n Assertions.assertThat(process.wasProcessCompleted(PROCESS_ID_1)).isTrue();\n Assertions.assertThat(process.wasNodeTriggered(\"embedded\")).isTrue();\n Assertions.assertThat(process.wasNodeLeft(\"embedded\")).isTrue();\n Assertions.assertThat(process.wasNodeLeft(\"print info\")).isTrue();\n }\n\n @Test(timeout = 30000)\n public void testReusable() {\n TrackingProcessEventListener process = runProcess(ksession, \"external\");\n\n Assertions.assertThat(process.wasProcessCompleted(PROCESS_ID_1)).isTrue();\n Assertions.assertThat(process.wasProcessCompleted(HELLO_WORLD_PROCESS_ID)).isTrue();\n }\n\n @Test(timeout = 30000)\n public void testMissingProcess() {\n try {\n runProcess(ksession, \"missing\");\n } catch (RuntimeException ex) {\n Assertions.assertThat(ex.getCause()).isNotNull();\n Assertions.assertThat(ex.getCause().getMessage()).contains(\"Could not find process missingProcess\");\n }\n }\n\n @Test(timeout = 30000)\n public void testProcessStartFromScript() {\n TrackingProcessEventListener process = runProcess(ksession, \"script\");\n\n Assertions.assertThat(process.wasProcessCompleted(PROCESS_ID_1)).isTrue();\n Assertions.assertThat(process.wasProcessCompleted(HELLO_WORLD_PROCESS_ID)).isTrue();\n }\n\n @Test(timeout = 30000)\n public void testIndependent() {\n IterableProcessEventListener process = new IterableProcessEventListener();\n ksession.addEventListener(process);\n\n // start the process and track the progress\n ProcessInstance pi = ksession.startProcess(PROCESS_ID_2, createBranchDefiningMap(\"parameters\"));\n assertChangedVariable(process, \"node\", null, \"parameters\");\n assertProcessStarted(process, PROCESS_ID_2);\n assertNextNode(process, P2_START);\n assertNextNode(process, P2_GATEWAY_START);\n assertTriggered(process, \"parameter mapping\");\n\n // subprocess is started\n if (JAVA8) {\n assertChangedVariable(process, \"variable\", null, \"parameters\");\n assertChangedVariable(process, \"undefined\", null, \"parameters\");\n } else {\n assertChangedVariable(process, \"undefined\", null, \"parameters\");\n assertChangedVariable(process, \"variable\", null, \"parameters\");\n }\n assertProcessStarted(process, PROCESS_ID_3);\n long id = process.current().getEvent().getProcessInstanceId();\n assertNextNode(process, P3_START);\n assertTriggered(process, P3_SIGNAL);\n\n // signal the subprocess to continue\n ksession.signalEvent(\"continue\", null, id);\n assertLeft(process, P3_SIGNAL);\n assertTriggered(process, P3_SCRIPT);\n assertChangedVariable(process, \"variable\", \"parameters\", \"new value\");\n assertLeft(process, P3_SCRIPT);\n assertNextNode(process, P3_END);\n assertProcessCompleted(process, PROCESS_ID_3);\n\n // track the progress after subprocess completion\n assertChangedVariable(process, \"node\", \"parameters\", \"new value\");\n assertLeft(process, \"parameter mapping\");\n assertNextNode(process, \"Gateway\");\n assertNextNode(process, P2_GATEWAY_END);\n assertTriggered(process, P2_SIGNAL_END);\n\n // signal the parent process to finish\n ksession.signalEvent(\"finish\", null, pi.getId());\n assertLeft(process, P2_SIGNAL_END);\n assertNextNode(process, P2_END);\n assertProcessCompleted(process, PROCESS_ID_2);\n }\n\n @Ignore\n @Test(timeout = 30000)\n public void testIndependentAbort() {\n IterableProcessEventListener process = new IterableProcessEventListener();\n ksession.addEventListener(process);\n\n // start the process and track the progress\n ProcessInstance pi = ksession.startProcess(PROCESS_ID_2, createBranchDefiningMap(\"parameters\"));\n assertChangedVariable(process, \"node\", null, \"parameters\");\n assertProcessStarted(process, PROCESS_ID_2);\n assertNextNode(process, P2_START);\n assertNextNode(process, P2_GATEWAY_START);\n assertTriggered(process, \"parameter mapping\");\n\n // subprocess is started\n if (JAVA8) {\n assertChangedVariable(process, \"variable\", null, \"parameters\");\n assertChangedVariable(process, \"undefined\", null, \"parameters\");\n } else {\n assertChangedVariable(process, \"undefined\", null, \"parameters\");\n assertChangedVariable(process, \"variable\", null, \"parameters\");\n }\n assertProcessStarted(process, PROCESS_ID_3);\n long id = process.current().getEvent().getProcessInstanceId();\n assertNextNode(process, P3_START);\n assertTriggered(process, P3_SIGNAL);\n\n ksession.abortProcessInstance(id);\n assertProcessCompleted(process, PROCESS_ID_3);\n process.printRemainingEvents();\n\n // track the progress after subprocess completion\n assertLeft(process, \"parameter mapping\");\n assertNextNode(process, \"Gateway\");\n // variable value was not changed -> error\n assertTriggered(process, \"Error\");\n assertProcessCompleted(process, PROCESS_ID_2);\n }\n\n @Test(timeout = 30000)\n public void testIndependentNoWaitForCompletionParentFirst() {\n IterableProcessEventListener process = new IterableProcessEventListener();\n ksession.addEventListener(process);\n\n ProcessInstance pi = ksession.startProcess(PROCESS_ID_2, createBranchDefiningMap(\"nowait\"));\n assertChangedVariable(process, \"node\", null, \"nowait\");\n assertProcessStarted(process, PROCESS_ID_2);\n assertNextNode(process, P2_START);\n assertNextNode(process, P2_GATEWAY_START);\n assertTriggered(process, \"don't wait for completion\");\n\n // subprocess\n assertProcessStarted(process, PROCESS_ID_3);\n long id = process.current().getEvent().getProcessInstanceId();\n assertNextNode(process, P3_START);\n assertTriggered(process, P3_SIGNAL);\n\n assertLeft(process, \"don't wait for completion\");\n assertNextNode(process, P2_GATEWAY_END);\n assertTriggered(process, P2_SIGNAL_END);\n\n ksession.signalEvent(\"finish\", null, pi.getId());\n assertLeft(process, P2_SIGNAL_END);\n assertNextNode(process, P2_END);\n assertProcessCompleted(process, PROCESS_ID_2);\n\n ksession.signalEvent(\"continue\", null, id);\n assertLeft(process, P3_SIGNAL);\n assertTriggered(process, P3_SCRIPT);\n assertChangedVariable(process, \"variable\", null, \"new value\");\n assertLeft(process, P3_SCRIPT);\n assertNextNode(process, P3_END);\n assertProcessCompleted(process, PROCESS_ID_3);\n }\n\n @Test(timeout = 30000)\n public void testIndependentNoWaitForCompletionSubprocessFirst() {\n IterableProcessEventListener process = new IterableProcessEventListener();\n ksession.addEventListener(process);\n\n ProcessInstance pi = ksession.startProcess(PROCESS_ID_2, createBranchDefiningMap(\"nowait\"));\n assertChangedVariable(process, \"node\", null, \"nowait\");\n assertProcessStarted(process, PROCESS_ID_2);\n assertNextNode(process, P2_START);\n assertNextNode(process, P2_GATEWAY_START);\n assertTriggered(process, \"don't wait for completion\");\n\n // subprocess\n assertProcessStarted(process, PROCESS_ID_3);\n long id = process.current().getEvent().getProcessInstanceId();\n assertNextNode(process, P3_START);\n assertTriggered(process, P3_SIGNAL);\n\n assertLeft(process, \"don't wait for completion\");\n assertNextNode(process, P2_GATEWAY_END);\n assertTriggered(process, P2_SIGNAL_END);\n\n // signal the subprocess to continue\n ksession.signalEvent(\"continue\", null, id);\n assertLeft(process, P3_SIGNAL);\n assertTriggered(process, P3_SCRIPT);\n assertChangedVariable(process, \"variable\", null, \"new value\");\n assertLeft(process, P3_SCRIPT);\n assertNextNode(process, P3_END);\n assertProcessCompleted(process, PROCESS_ID_3);\n\n ksession.signalEvent(\"finish\", null, pi.getId());\n assertLeft(process, P2_SIGNAL_END);\n assertNextNode(process, P2_END);\n assertProcessCompleted(process, PROCESS_ID_2);\n }\n\n @Test(timeout = 30000)\n public void testIndependentNoWaitForCompletionAbortParent() {\n TrackingProcessEventListener listener = new TrackingProcessEventListener();\n ksession.addEventListener(listener);\n IterableProcessEventListener process = new IterableProcessEventListener();\n ksession.addEventListener(process);\n\n ProcessInstance pi = ksession.startProcess(PROCESS_ID_2, createBranchDefiningMap(\"nowait\"));\n assertChangedVariable(process, \"node\", null, \"nowait\");\n assertProcessStarted(process, PROCESS_ID_2);\n assertNextNode(process, P2_START);\n assertNextNode(process, P2_GATEWAY_START);\n assertTriggered(process, \"don't wait for completion\");\n\n // subprocess\n assertProcessStarted(process, PROCESS_ID_3);\n long id = process.current().getEvent().getProcessInstanceId();\n assertNextNode(process, P3_START);\n assertTriggered(process, P3_SIGNAL);\n\n assertLeft(process, \"don't wait for completion\");\n assertNextNode(process, P2_GATEWAY_END);\n assertTriggered(process, P2_SIGNAL_END);\n\n Assertions.assertThat(listener.wasProcessStarted(PROCESS_ID_2)).isTrue();\n Assertions.assertThat(listener.wasProcessStarted(PROCESS_ID_3)).isTrue();\n\n ksession.abortProcessInstance(pi.getId());\n assertProcessCompleted(process, PROCESS_ID_2);\n Assertions.assertThat(listener.wasProcessAborted(PROCESS_ID_2)).isTrue();\n Assertions.assertThat(listener.wasProcessCompleted(PROCESS_ID_3)).isFalse();\n\n // signal the subprocess to continue\n ksession.signalEvent(\"continue\", null, id);\n assertLeft(process, P3_SIGNAL);\n assertTriggered(process, P3_SCRIPT);\n assertChangedVariable(process, \"variable\", null, \"new value\");\n assertLeft(process, P3_SCRIPT);\n assertNextNode(process, P3_END);\n assertProcessCompleted(process, PROCESS_ID_3);\n\n Assertions.assertThat(listener.wasProcessAborted(PROCESS_ID_2)).isTrue();\n Assertions.assertThat(listener.wasProcessCompleted(PROCESS_ID_3)).isTrue();\n }\n\n @Test(timeout = 30000)\n public void testIndependentNoWaitForCompletionAbortSubprocess() {\n TrackingProcessEventListener listener = new TrackingProcessEventListener();\n ksession.addEventListener(listener);\n IterableProcessEventListener process = new IterableProcessEventListener();\n ksession.addEventListener(process);\n\n ProcessInstance pi = ksession.startProcess(PROCESS_ID_2, createBranchDefiningMap(\"nowait\"));\n assertChangedVariable(process, \"node\", null, \"nowait\");\n assertProcessStarted(process, PROCESS_ID_2);\n assertNextNode(process, P2_START);\n assertNextNode(process, P2_GATEWAY_START);\n assertTriggered(process, \"don't wait for completion\");\n\n // subprocess\n assertProcessStarted(process, PROCESS_ID_3);\n long id = process.current().getEvent().getProcessInstanceId();\n assertNextNode(process, P3_START);\n assertTriggered(process, P3_SIGNAL);\n\n assertLeft(process, \"don't wait for completion\");\n assertNextNode(process, P2_GATEWAY_END);\n assertTriggered(process, P2_SIGNAL_END);\n\n Assertions.assertThat(listener.wasProcessStarted(PROCESS_ID_2)).isTrue();\n Assertions.assertThat(listener.wasProcessStarted(PROCESS_ID_3)).isTrue();\n\n ksession.abortProcessInstance(id);\n assertProcessCompleted(process, PROCESS_ID_3);\n Assertions.assertThat(listener.wasProcessCompleted(PROCESS_ID_2)).isFalse();", "answers": [" Assertions.assertThat(listener.wasProcessAborted(PROCESS_ID_3)).isTrue();"], "length": 938, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "961b7e63-1671-4444-80bb-407d1c15adf3", "reasoning": "The test method aborts the subprocess (id) and then checks listener states. It has already asserted that the parent process was not completed. The next logical assertion is that the subprocess was aborted, using the listener's wasProcessAborted method for PROCESS_ID_3.", "reasoning_model_answer": "Assertions.assertThat(listener.wasProcessAborted(PROCESS_ID_3)).isTrue();", "assistant_with_reasoning": "\nThe test method aborts the subprocess (id) and then checks listener states. It has already asserted that the parent process was not completed. The next logical assertion is that the subprocess was aborted, using the listener's wasProcessAborted method for PROCESS_ID_3.\n\nAssertions.assertThat(listener.wasProcessAborted(PROCESS_ID_3)).isTrue();", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 7.015, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 3, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 15403, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "Assertions.assertThat(listener.wasProcessAborted(PROCESS_ID_3)).isTrue();", "score": 0.95, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "\"\"\"\nThis module converts requested URLs to callback view functions.\n\nRegexURLResolver is the main class here. Its resolve() method takes a URL (as\na string) and returns a tuple in this format:\n\n (view_function, function_args, function_kwargs)\n\"\"\"\n\nimport re\nfrom threading import local\n\nfrom django.http import Http404\nfrom django.core.exceptions import ImproperlyConfigured, ViewDoesNotExist\nfrom django.utils.datastructures import MultiValueDict\nfrom django.utils.encoding import iri_to_uri, force_unicode, smart_str\nfrom django.utils.functional import memoize, lazy\nfrom django.utils.importlib import import_module\nfrom django.utils.module_loading import module_has_submodule\nfrom django.utils.regex_helper import normalize\nfrom django.utils.translation import get_language\n\n\n_resolver_cache = {} # Maps URLconf modules to RegexURLResolver instances.\n_ns_resolver_cache = {} # Maps namespaces to RegexURLResolver instances.\n_callable_cache = {} # Maps view and url pattern names to their view functions.\n\n# SCRIPT_NAME prefixes for each thread are stored here. If there's no entry for\n# the current thread (which is the only one we ever access), it is assumed to\n# be empty.\n_prefixes = local()\n\n# Overridden URLconfs for each thread are stored here.\n_urlconfs = local()\n\n\nclass ResolverMatch(object):\n def __init__(self, func, args, kwargs, url_name=None, app_name=None, namespaces=None):\n self.func = func\n self.args = args\n self.kwargs = kwargs\n self.app_name = app_name\n if namespaces:\n self.namespaces = [x for x in namespaces if x]\n else:\n self.namespaces = []\n if not url_name:\n if not hasattr(func, '__name__'):\n # An instance of a callable class\n url_name = '.'.join([func.__class__.__module__, func.__class__.__name__])\n else:\n # A function\n url_name = '.'.join([func.__module__, func.__name__])\n self.url_name = url_name\n\n @property\n def namespace(self):\n return ':'.join(self.namespaces)\n\n @property\n def view_name(self):\n return ':'.join([ x for x in [ self.namespace, self.url_name ] if x ])\n\n def __getitem__(self, index):\n return (self.func, self.args, self.kwargs)[index]\n\n def __repr__(self):\n return \"ResolverMatch(func=%s, args=%s, kwargs=%s, url_name='%s', app_name='%s', namespace='%s')\" % (\n self.func, self.args, self.kwargs, self.url_name, self.app_name, self.namespace)\n\nclass Resolver404(Http404):\n pass\n\nclass NoReverseMatch(Exception):\n # Don't make this raise an error when used in a template.\n silent_variable_failure = True\n\ndef get_callable(lookup_view, can_fail=False):\n \"\"\"\n Convert a string version of a function name to the callable object.\n\n If the lookup_view is not an import path, it is assumed to be a URL pattern\n label and the original string is returned.\n\n If can_fail is True, lookup_view might be a URL pattern label, so errors\n during the import fail and the string is returned.\n \"\"\"\n if not callable(lookup_view):\n mod_name, func_name = get_mod_func(lookup_view)\n try:\n if func_name != '':\n lookup_view = getattr(import_module(mod_name), func_name)\n if not callable(lookup_view):\n raise ViewDoesNotExist(\n \"Could not import %s.%s. View is not callable.\" %\n (mod_name, func_name))\n except AttributeError:\n if not can_fail:\n raise ViewDoesNotExist(\n \"Could not import %s. View does not exist in module %s.\" %\n (lookup_view, mod_name))\n except ImportError:\n parentmod, submod = get_mod_func(mod_name)\n if (not can_fail and submod != '' and\n not module_has_submodule(import_module(parentmod), submod)):\n raise ViewDoesNotExist(\n \"Could not import %s. Parent module %s does not exist.\" %\n (lookup_view, mod_name))\n if not can_fail:\n raise\n return lookup_view\nget_callable = memoize(get_callable, _callable_cache, 1)\n\ndef get_resolver(urlconf):\n if urlconf is None:\n from django.conf import settings\n urlconf = settings.ROOT_URLCONF\n return RegexURLResolver(r'^/', urlconf)\nget_resolver = memoize(get_resolver, _resolver_cache, 1)\n\ndef get_ns_resolver(ns_pattern, resolver):\n # Build a namespaced resolver for the given parent urlconf pattern.\n # This makes it possible to have captured parameters in the parent\n # urlconf pattern.\n ns_resolver = RegexURLResolver(ns_pattern,\n resolver.url_patterns)\n return RegexURLResolver(r'^/', [ns_resolver])\nget_ns_resolver = memoize(get_ns_resolver, _ns_resolver_cache, 2)\n\ndef get_mod_func(callback):\n # Converts 'django.views.news.stories.story_detail' to\n # ['django.views.news.stories', 'story_detail']\n try:\n dot = callback.rindex('.')\n except ValueError:\n return callback, ''\n return callback[:dot], callback[dot+1:]\n\nclass LocaleRegexProvider(object):\n \"\"\"\n A mixin to provide a default regex property which can vary by active\n language.\n\n \"\"\"\n def __init__(self, regex):\n # regex is either a string representing a regular expression, or a\n # translatable string (using ugettext_lazy) representing a regular\n # expression.\n self._regex = regex\n self._regex_dict = {}\n\n\n @property\n def regex(self):\n \"\"\"\n Returns a compiled regular expression, depending upon the activated\n language-code.\n \"\"\"\n language_code = get_language()\n if language_code not in self._regex_dict:\n if isinstance(self._regex, basestring):\n compiled_regex = re.compile(self._regex, re.UNICODE)\n else:\n regex = force_unicode(self._regex)\n compiled_regex = re.compile(regex, re.UNICODE)\n self._regex_dict[language_code] = compiled_regex\n return self._regex_dict[language_code]\n\n\nclass RegexURLPattern(LocaleRegexProvider):\n def __init__(self, regex, callback, default_args=None, name=None):\n LocaleRegexProvider.__init__(self, regex)\n # callback is either a string like 'foo.views.news.stories.story_detail'\n # which represents the path to a module and a view function name, or a\n # callable object (view).\n if callable(callback):\n self._callback = callback\n else:\n self._callback = None\n self._callback_str = callback\n self.default_args = default_args or {}\n self.name = name\n\n def __repr__(self):\n return smart_str(u'<%s %s %s>' % (self.__class__.__name__, self.name, self.regex.pattern))\n\n def add_prefix(self, prefix):\n \"\"\"\n Adds the prefix string to a string-based callback.\n \"\"\"\n if not prefix or not hasattr(self, '_callback_str'):\n return\n self._callback_str = prefix + '.' + self._callback_str\n\n def resolve(self, path):\n match = self.regex.search(path)\n if match:\n # If there are any named groups, use those as kwargs, ignoring\n # non-named groups. Otherwise, pass all non-named arguments as\n # positional arguments.\n kwargs = match.groupdict()\n if kwargs:\n args = ()\n else:\n args = match.groups()\n # In both cases, pass any extra_kwargs as **kwargs.\n kwargs.update(self.default_args)\n\n return ResolverMatch(self.callback, args, kwargs, self.name)\n\n @property\n def callback(self):\n if self._callback is not None:\n return self._callback\n\n self._callback = get_callable(self._callback_str)\n return self._callback\n\nclass RegexURLResolver(LocaleRegexProvider):\n def __init__(self, regex, urlconf_name, default_kwargs=None, app_name=None, namespace=None):\n LocaleRegexProvider.__init__(self, regex)\n # urlconf_name is a string representing the module containing URLconfs.\n self.urlconf_name = urlconf_name\n if not isinstance(urlconf_name, basestring):\n self._urlconf_module = self.urlconf_name\n self.callback = None\n self.default_kwargs = default_kwargs or {}\n self.namespace = namespace\n self.app_name = app_name\n self._reverse_dict = {}\n self._namespace_dict = {}\n self._app_dict = {}\n\n def __repr__(self):\n return smart_str(u'<%s %s (%s:%s) %s>' % (self.__class__.__name__, self.urlconf_name, self.app_name, self.namespace, self.regex.pattern))\n\n def _populate(self):\n lookups = MultiValueDict()\n namespaces = {}\n apps = {}\n language_code = get_language()\n for pattern in reversed(self.url_patterns):\n p_pattern = pattern.regex.pattern\n if p_pattern.startswith('^'):\n p_pattern = p_pattern[1:]\n if isinstance(pattern, RegexURLResolver):\n if pattern.namespace:\n namespaces[pattern.namespace] = (p_pattern, pattern)\n if pattern.app_name:\n apps.setdefault(pattern.app_name, []).append(pattern.namespace)\n else:\n parent = normalize(pattern.regex.pattern)\n for name in pattern.reverse_dict:\n for matches, pat, defaults in pattern.reverse_dict.getlist(name):\n new_matches = []\n for piece, p_args in parent:\n new_matches.extend([(piece + suffix, p_args + args) for (suffix, args) in matches])\n lookups.appendlist(name, (new_matches, p_pattern + pat, dict(defaults, **pattern.default_kwargs)))\n for namespace, (prefix, sub_pattern) in pattern.namespace_dict.items():\n namespaces[namespace] = (p_pattern + prefix, sub_pattern)\n for app_name, namespace_list in pattern.app_dict.items():\n apps.setdefault(app_name, []).extend(namespace_list)\n else:\n bits = normalize(p_pattern)\n lookups.appendlist(pattern.callback, (bits, p_pattern, pattern.default_args))\n if pattern.name is not None:\n lookups.appendlist(pattern.name, (bits, p_pattern, pattern.default_args))\n self._reverse_dict[language_code] = lookups\n self._namespace_dict[language_code] = namespaces\n self._app_dict[language_code] = apps\n\n @property\n def reverse_dict(self):\n language_code = get_language()\n if language_code not in self._reverse_dict:\n self._populate()", "answers": [" return self._reverse_dict[language_code]"], "length": 1004, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "7fb57945-a38c-490e-b832-2b713d6dc340", "reasoning": "The reverse_dict property checks if the current language's reverse lookup dict is cached; if not, it calls _populate() to fill it. After ensuring the dict exists, the method should return the cached dict for the language. Therefore the next line is the return statement retrieving self._reverse_dict[language_code].", "reasoning_model_answer": "return self._reverse_dict[language_code]", "assistant_with_reasoning": "\nThe reverse_dict property checks if the current language's reverse lookup dict is cached; if not, it calls _populate() to fill it. After ensuring the dict exists, the method should return the cached dict for the language. Therefore the next line is the return statement retrieving self._reverse_dict[language_code].\n\nreturn self._reverse_dict[language_code]", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 2.587, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 11039, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "return self._reverse_dict[language_code]", "score": 0.91, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "//-----------------------------------------------------------------------\n// (c) http://www.codeplex.com/MSBuildExtensionPack. This source is subject to the Microsoft Permissive License. See http://www.microsoft.com/resources/sharedsource/licensingbasics/sharedsourcelicenses.mspx. All other rights reserved.\n//-----------------------------------------------------------------------\nnamespace MSBuild.ExtensionPack.Security\n{\n using System;\n using System.Globalization;\n using System.IO;\n using System.Linq;\n using System.Runtime.InteropServices;\n using System.Security.AccessControl;\n using System.Security.Cryptography;\n using System.Security.Cryptography.X509Certificates;\n using System.Security.Principal;\n using Microsoft.Build.Framework;\n using Microsoft.Build.Utilities;\n using MSBuild.ExtensionPack.Security.Extended;\n\n internal enum CryptGetProvParamType\n {\n /// \n /// PP_ENUMALGS\n /// \n PP_ENUMALGS = 1,\n\n /// \n /// PP_ENUMCONTAINERS\n /// \n PP_ENUMCONTAINERS = 2,\n\n /// \n /// PP_IMPTYPE\n /// \n PP_IMPTYPE = 3,\n\n /// \n /// PP_NAME\n /// \n PP_NAME = 4,\n\n /// \n /// PP_VERSION\n /// \n PP_VERSION = 5,\n\n /// \n /// PP_CONTAINER\n /// \n PP_CONTAINER = 6,\n\n /// \n /// PP_CHANGE_PASSWORD\n /// \n PP_CHANGE_PASSWORD = 7,\n\n /// \n /// PP_KEYSET_SEC_DESCR\n /// \n PP_KEYSET_SEC_DESCR = 8,\n\n /// \n /// PP_CERTCHAIN\n /// \n PP_CERTCHAIN = 9,\n\n /// \n /// PP_KEY_TYPE_SUBTYPE\n /// \n PP_KEY_TYPE_SUBTYPE = 10,\n\n /// \n /// PP_PROVTYPE\n /// \n PP_PROVTYPE = 16,\n\n /// \n /// PP_KEYSTORAGE\n /// \n PP_KEYSTORAGE = 17,\n\n /// \n /// PP_APPLI_CERT\n /// \n PP_APPLI_CERT = 18,\n\n /// \n /// PP_SYM_KEYSIZE\n /// \n PP_SYM_KEYSIZE = 19,\n\n /// \n /// PP_SESSION_KEYSIZE\n /// \n PP_SESSION_KEYSIZE = 20,\n\n /// \n /// PP_UI_PROMPT\n /// \n PP_UI_PROMPT = 21,\n\n /// \n /// PP_ENUMALGS_EX\n /// \n PP_ENUMALGS_EX = 22,\n\n /// \n /// PP_ENUMMANDROOTS\n /// \n PP_ENUMMANDROOTS = 25,\n\n /// \n /// PP_ENUMELECTROOTS\n /// \n PP_ENUMELECTROOTS = 26,\n\n /// \n /// PP_KEYSET_TYPE\n /// \n PP_KEYSET_TYPE = 27,\n\n /// \n /// PP_ADMIN_PIN\n /// \n PP_ADMIN_PIN = 31,\n\n /// \n /// PP_KEYEXCHANGE_PIN\n /// \n PP_KEYEXCHANGE_PIN = 32,\n\n /// \n /// PP_SIGNATURE_PIN\n /// \n PP_SIGNATURE_PIN = 33,\n\n /// \n /// PP_SIG_KEYSIZE_INC\n /// \n PP_SIG_KEYSIZE_INC = 34,\n\n /// \n /// PP_KEYX_KEYSIZE_INC\n /// \n PP_KEYX_KEYSIZE_INC = 35,\n\n /// \n /// PP_UNIQUE_CONTAINER\n /// \n PP_UNIQUE_CONTAINER = 36,\n\n /// \n /// PP_SGC_INFO\n /// \n PP_SGC_INFO = 37,\n\n /// \n /// PP_USE_HARDWARE_RNG\n /// \n PP_USE_HARDWARE_RNG = 38,\n\n /// \n /// PP_KEYSPEC\n /// \n PP_KEYSPEC = 39,\n\n /// \n /// PP_ENUMEX_SIGNING_PROT\n /// \n PP_ENUMEX_SIGNING_PROT = 40,\n\n /// \n /// PP_CRYPT_COUNT_KEY_USE\n /// \n PP_CRYPT_COUNT_KEY_USE = 41,\n }\n\n /// \n /// Valid TaskActions are:\n /// Add (Required: FileName Optional: MachineStore, CertPassword, Exportable, StoreName Output: Thumbprint, SubjectDName)\n /// GetBase64EncodedCertificate (Required: Thumbprint or SubjectDName Optional: MachineStore, Output: Base64EncodedCertificate)\n /// GetExpiryDate (Required: Thumbprint or SubjectDName Optional: MachineStore, Output: CertificateExpiryDate)\n /// GetInfo (Required: Thumbprint or SubjectDName Optional: MachineStore, StoreName Output: CertInfo)\n /// Remove (Required: Thumbprint or SubjectDName Optional: MachineStore, StoreName)\n /// SetUserRights (Required: AccountName, Thumbprint or SubjectDName Optional: MachineStore, Output: )\n /// Remote Execution Support: No\n /// \n /// \n /// \n /// \n /// $(MSBuildProjectDirectory)\\..\\MSBuild.ExtensionPack.tasks\n /// $(MSBuildProjectDirectory)\\..\\..\\Common\\MSBuild.ExtensionPack.tasks\n /// \n /// \n /// \n /// \n /// \n /// \n /// \n /// \n /// \n /// \n /// \n /// \n /// \n /// \n /// \n /// \n /// \n /// \n /// \n /// \n /// \n /// \n /// \n /// \n /// \n /// \n /// \n /// \n /// \n /// \n /// \n /// \n /// \n /// ]]> \n /// \n [HelpUrl(\"http://www.msbuildextensionpack.com/help/3.5.12.0/html/45763eac-8f14-417d-9b27-425161982ffe.htm\")]\n public class Certificate : BaseTask\n {\n private const string AddTaskAction = \"Add\";\n private const string RemoveTaskAction = \"Remove\";\n private const string SetUserRightsTaskAction = \"SetUserRights\";\n private const string GetExpiryDateTaskAction = \"GetExpiryDate\";\n private const string GetBase64EncodedCertificateTaskAction = \"GetBase64EncodedCertificate\";\n private const string GetInfoTaskAction = \"GetInfo\";\n private const string AccessRightsRead = \"Read\";\n private const string AccessRightsReadAndExecute = \"ReadAndExecute\";\n private const string AccessRightsWrite = \"Write\";\n private const string AccessRightsFullControl = \"FullControl\";\n private StoreName storeName = System.Security.Cryptography.X509Certificates.StoreName.My;\n\n [DropdownValue(AddTaskAction)]\n [DropdownValue(GetExpiryDateTaskAction)]\n [DropdownValue(GetBase64EncodedCertificateTaskAction)]\n [DropdownValue(SetUserRightsTaskAction)]\n [DropdownValue(RemoveTaskAction)]\n [DropdownValue(GetInfoTaskAction)]\n public override string TaskAction\n {\n get { return base.TaskAction; }\n set { base.TaskAction = value; }\n }\n\n /// \n /// Sets a value indicating whether to use the MachineStore. Default is false\n /// \n [TaskAction(AddTaskAction, false)]\n [TaskAction(GetExpiryDateTaskAction, false)]\n [TaskAction(GetBase64EncodedCertificateTaskAction, false)]\n [TaskAction(SetUserRightsTaskAction, false)]\n [TaskAction(RemoveTaskAction, false)]\n [TaskAction(GetInfoTaskAction, false)]\n public bool MachineStore { get; set; }\n\n /// \n /// Sets the password for the pfx file from which the certificate is to be imported, defaults to blank\n /// \n [TaskAction(AddTaskAction, false)]\n public string CertPassword { get; set; }\n\n /// \n /// Sets a value indicating whether the certificate is exportable.\n /// \n [TaskAction(AddTaskAction, false)]\n public bool Exportable { get; set; }\n\n /// \n /// The distinguished subject name of the certificate\n /// \n [Output]\n [TaskAction(GetInfoTaskAction, false)]\n public string SubjectDName { get; set; }\n\n /// \n /// Gets or sets the Base 64 Encoded string of the certificate\n /// \n [Output]\n [TaskAction(GetBase64EncodedCertificateTaskAction, true)]\n public string Base64EncodedCertificate { get; set; }\n\n /// \n /// Gets the thumbprint. Used to uniquely identify certificate in further tasks\n /// The thumprint can be used in place of distinguished name to identify a certificate\n /// \n [Output]\n [TaskAction(AddTaskAction, false)]\n [TaskAction(GetExpiryDateTaskAction, false)]\n [TaskAction(GetBase64EncodedCertificateTaskAction, false)]\n [TaskAction(SetUserRightsTaskAction, false)]\n [TaskAction(RemoveTaskAction, true)]\n [TaskAction(GetInfoTaskAction, false)]\n public string Thumbprint { get; set; }\n\n /// \n /// Gets the Distinguished Name for the certificate used to to uniquely identify certificate in further tasks.\n /// The distinguished name can be used in place of thumbprint to identify a certificate\n /// \n [Output]\n [TaskAction(AddTaskAction, false)]\n [TaskAction(GetExpiryDateTaskAction, false)]\n [TaskAction(GetBase64EncodedCertificateTaskAction, false)]\n [TaskAction(SetUserRightsTaskAction, false)]\n [TaskAction(RemoveTaskAction, false)]\n public string DistinguishedName { get; set; }\n\n /// \n /// Gets the Certificate Exprity Date.\n /// \n [Output]\n [TaskAction(GetExpiryDateTaskAction, true)]\n public string CertificateExpiryDate { get; set; }\n\n /// \n /// The name of user or group that needs to be given rights on the given certificate\n /// \n [TaskAction(SetUserRightsTaskAction, true)]\n public string AccountName { get; set; }\n\n /// \n /// The access rights that need to be given.\n /// \n [TaskAction(SetUserRightsTaskAction, true)]\n public string AccessRights { get; set; }\n\n /// \n /// Sets the name of the store. Defaults to My\n /// \n /// AddressBook: The store for other users
    \n /// AuthRoot: The store for third-party certificate authorities
    \n /// CertificateAuthority: The store for intermediate certificate authorities
    \n /// Disallowed: The store for revoked certificates
    \n /// My: The store for personal certificates
    \n /// Root: The store for trusted root certificate authorities
    \n /// TrustedPeople: The store for directly trusted people and resources
    \n /// TrustedPublisher: The store for directly trusted publishers
    \n ///
    \n [TaskAction(AddTaskAction, false)]\n [TaskAction(GetExpiryDateTaskAction, false)]\n [TaskAction(GetBase64EncodedCertificateTaskAction, false)]\n [TaskAction(SetUserRightsTaskAction, false)]\n [TaskAction(RemoveTaskAction, false)]\n [TaskAction(GetInfoTaskAction, false)]\n public string StoreName\n {\n get { return this.storeName.ToString(); }\n set { this.storeName = (StoreName)Enum.Parse(typeof(StoreName), value); }\n }\n\n /// \n /// Sets the name of the file.\n /// \n [TaskAction(AddTaskAction, true)]\n [Output]\n public ITaskItem FileName { get; set; }\n\n /// \n /// Gets the item which contains the Certificate information. The following Metadata is populated: SubjectName, SignatureAlgorithm, SubjectNameOidValue, SerialNumber, Archived, NotAfter, NotBefore, FriendlyName, HasPrivateKey, Thumbprint, Version, PrivateKeyFileName, IssuerName\n /// \n [Output]\n [TaskAction(AddTaskAction, false)]\n public ITaskItem CertInfo { get; protected set; }\n\n /// \n /// Performs the action of this task.\n /// \n protected override void InternalExecute()\n {\n if (!this.TargetingLocalMachine())\n {\n return;\n }", "answers": [" switch (this.TaskAction)"], "length": 1181, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "d10f6592-da7c-4336-9f8f-e8a40045c5a0", "reasoning": "The InternalExecute method begins by checking if the task is targeting the local machine; after that check, the method typically dispatches to the appropriate action based on the TaskAction property. The next logical line is the start of a switch statement on this.TaskAction to handle the various task actions (Add, Remove, etc.). Hence the next line is the switch statement header.", "reasoning_model_answer": "switch (this.TaskAction)", "assistant_with_reasoning": "\nThe InternalExecute method begins by checking if the task is targeting the local machine; after that check, the method typically dispatches to the appropriate action based on the TaskAction property. The next logical line is the start of a switch statement on this.TaskAction to handle the various task actions (Add, Remove, etc.). Hence the next line is the switch statement header.\n\nswitch (this.TaskAction)", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.021, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 14915, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "switch (this.TaskAction)", "score": 0.8, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "# -*- coding: utf-8 -*-\nimport datetime\nimport calendar\n\nimport operator\nfrom math import copysign\n\nfrom six import integer_types\nfrom warnings import warn\n\nfrom ._common import weekday\n\nMO, TU, WE, TH, FR, SA, SU = weekdays = tuple([weekday(x) for x in range(7)])\n\n__all__ = [\"relativedelta\", \"MO\", \"TU\", \"WE\", \"TH\", \"FR\", \"SA\", \"SU\"]\n\n\nclass relativedelta(object):\n \"\"\"\n The relativedelta type is based on the specification of the excellent\n work done by M.-A. Lemburg in his\n `mx.DateTime `_ extension.\n However, notice that this type does *NOT* implement the same algorithm as\n his work. Do *NOT* expect it to behave like mx.DateTime's counterpart.\n\n There are two different ways to build a relativedelta instance. The\n first one is passing it two date/datetime classes::\n\n relativedelta(datetime1, datetime2)\n\n The second one is passing it any number of the following keyword arguments::\n\n relativedelta(arg1=x,arg2=y,arg3=z...)\n\n year, month, day, hour, minute, second, microsecond:\n Absolute information (argument is singular); adding or subtracting a\n relativedelta with absolute information does not perform an aritmetic\n operation, but rather REPLACES the corresponding value in the\n original datetime with the value(s) in relativedelta.\n\n years, months, weeks, days, hours, minutes, seconds, microseconds:\n Relative information, may be negative (argument is plural); adding\n or subtracting a relativedelta with relative information performs\n the corresponding aritmetic operation on the original datetime value\n with the information in the relativedelta.\n\n weekday:\n One of the weekday instances (MO, TU, etc). These instances may\n receive a parameter N, specifying the Nth weekday, which could\n be positive or negative (like MO(+1) or MO(-2). Not specifying\n it is the same as specifying +1. You can also use an integer,\n where 0=MO.\n\n leapdays:\n Will add given days to the date found, if year is a leap\n year, and the date found is post 28 of february.\n\n yearday, nlyearday:\n Set the yearday or the non-leap year day (jump leap days).\n These are converted to day/month/leapdays information.\n\n Here is the behavior of operations with relativedelta:\n\n 1. Calculate the absolute year, using the 'year' argument, or the\n original datetime year, if the argument is not present.\n\n 2. Add the relative 'years' argument to the absolute year.\n\n 3. Do steps 1 and 2 for month/months.\n\n 4. Calculate the absolute day, using the 'day' argument, or the\n original datetime day, if the argument is not present. Then,\n subtract from the day until it fits in the year and month\n found after their operations.\n\n 5. Add the relative 'days' argument to the absolute day. Notice\n that the 'weeks' argument is multiplied by 7 and added to\n 'days'.\n\n 6. Do steps 1 and 2 for hour/hours, minute/minutes, second/seconds,\n microsecond/microseconds.\n\n 7. If the 'weekday' argument is present, calculate the weekday,\n with the given (wday, nth) tuple. wday is the index of the\n weekday (0-6, 0=Mon), and nth is the number of weeks to add\n forward or backward, depending on its signal. Notice that if\n the calculated date is already Monday, for example, using\n (0, 1) or (0, -1) won't change the day.\n \"\"\"\n\n def __init__(self, dt1=None, dt2=None,\n years=0, months=0, days=0, leapdays=0, weeks=0,\n hours=0, minutes=0, seconds=0, microseconds=0,\n year=None, month=None, day=None, weekday=None,\n yearday=None, nlyearday=None,\n hour=None, minute=None, second=None, microsecond=None):\n\n # Check for non-integer values in integer-only quantities\n if any(x is not None and x != int(x) for x in (years, months)):\n raise ValueError(\"Non-integer years and months are \"\n \"ambiguous and not currently supported.\")\n\n if dt1 and dt2:\n # datetime is a subclass of date. So both must be date\n if not (isinstance(dt1, datetime.date) and\n isinstance(dt2, datetime.date)):\n raise TypeError(\"relativedelta only diffs datetime/date\")\n\n # We allow two dates, or two datetimes, so we coerce them to be\n # of the same type\n if (isinstance(dt1, datetime.datetime) !=\n isinstance(dt2, datetime.datetime)):\n if not isinstance(dt1, datetime.datetime):\n dt1 = datetime.datetime.fromordinal(dt1.toordinal())\n elif not isinstance(dt2, datetime.datetime):\n dt2 = datetime.datetime.fromordinal(dt2.toordinal())\n\n self.years = 0\n self.months = 0\n self.days = 0\n self.leapdays = 0\n self.hours = 0\n self.minutes = 0\n self.seconds = 0\n self.microseconds = 0\n self.year = None\n self.month = None\n self.day = None\n self.weekday = None\n self.hour = None\n self.minute = None\n self.second = None\n self.microsecond = None\n self._has_time = 0\n\n # Get year / month delta between the two\n months = (dt1.year - dt2.year) * 12 + (dt1.month - dt2.month)\n self._set_months(months)\n\n # Remove the year/month delta so the timedelta is just well-defined\n # time units (seconds, days and microseconds)\n dtm = self.__radd__(dt2)\n\n # If we've overshot our target, make an adjustment\n if dt1 < dt2:\n compare = operator.gt\n increment = 1\n else:\n compare = operator.lt\n increment = -1\n\n while compare(dt1, dtm):\n months += increment\n self._set_months(months)\n dtm = self.__radd__(dt2)\n\n # Get the timedelta between the \"months-adjusted\" date and dt1\n delta = dt1 - dtm\n self.seconds = delta.seconds + delta.days * 86400\n self.microseconds = delta.microseconds\n else:\n # Relative information\n self.years = years\n self.months = months\n self.days = days + weeks * 7\n self.leapdays = leapdays\n self.hours = hours\n self.minutes = minutes\n self.seconds = seconds\n self.microseconds = microseconds\n\n # Absolute information\n self.year = year\n self.month = month\n self.day = day\n self.hour = hour\n self.minute = minute\n self.second = second\n self.microsecond = microsecond\n\n if any(x is not None and int(x) != x\n for x in (year, month, day, hour,\n minute, second, microsecond)):\n # For now we'll deprecate floats - later it'll be an error.\n warn(\"Non-integer value passed as absolute information. \" +\n \"This is not a well-defined condition and will raise \" +\n \"errors in future versions.\", DeprecationWarning)\n\n\n if isinstance(weekday, integer_types):\n self.weekday = weekdays[weekday]\n else:\n self.weekday = weekday\n\n yday = 0\n if nlyearday:\n yday = nlyearday\n elif yearday:\n yday = yearday\n if yearday > 59:\n self.leapdays = -1\n if yday:\n ydayidx = [31, 59, 90, 120, 151, 181, 212,\n 243, 273, 304, 334, 366]\n for idx, ydays in enumerate(ydayidx):\n if yday <= ydays:\n self.month = idx+1\n if idx == 0:\n self.day = yday\n else:\n self.day = yday-ydayidx[idx-1]\n break\n else:\n raise ValueError(\"invalid year day (%d)\" % yday)\n\n self._fix()\n\n def _fix(self):\n if abs(self.microseconds) > 999999:\n s = _sign(self.microseconds)\n div, mod = divmod(self.microseconds * s, 1000000)\n self.microseconds = mod * s\n self.seconds += div * s\n if abs(self.seconds) > 59:\n s = _sign(self.seconds)\n div, mod = divmod(self.seconds * s, 60)\n self.seconds = mod * s\n self.minutes += div * s\n if abs(self.minutes) > 59:\n s = _sign(self.minutes)\n div, mod = divmod(self.minutes * s, 60)\n self.minutes = mod * s\n self.hours += div * s\n if abs(self.hours) > 23:\n s = _sign(self.hours)\n div, mod = divmod(self.hours * s, 24)\n self.hours = mod * s\n self.days += div * s\n if abs(self.months) > 11:\n s = _sign(self.months)", "answers": [" div, mod = divmod(self.months * s, 12)"], "length": 1063, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "17f3ea3b-deb5-4bd2-8c48-d9f677bacad7", "reasoning": "In the _fix method, each time a time component exceeds its range, the code computes the sign, then uses divmod to split the excess into the next larger unit. After handling hours, the next block starts with 'if abs(self.months) > 11:' followed by 's = _sign(self.months)'. The following line should perform the divmod operation with a divisor of 12 (months per year) to obtain the number of years to carry over and the remaining months. Hence the next line is: div, mod = divmod(self.months * s, 12).", "reasoning_model_answer": "div, mod = divmod(self.months * s, 12)", "assistant_with_reasoning": "\nIn the _fix method, each time a time component exceeds its range, the code computes the sign, then uses divmod to split the excess into the next larger unit. After handling hours, the next block starts with 'if abs(self.months) > 11:' followed by 's = _sign(self.months)'. The following line should perform the divmod operation with a divisor of 12 (months per year) to obtain the number of years to carry over and the remaining months. Hence the next line is: div, mod = divmod(self.months * s, 12).\n\ndiv, mod = divmod(self.months * s, 12)", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.419, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 9448, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "div, mod = divmod(self.months * s, 12)", "score": 0.86, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\n//-----------------------------------------------------------------------------\n//\n// Description:\n// This is a class for representing a PackageRelationshipCollection. This is an internal\n// class for manipulating relationships associated with a part \n//\n// Details:\n// This class handles serialization to/from relationship parts, creation of those parts\n// and offers methods to create, delete and enumerate relationships. This code was\n// moved from the PackageRelationshipCollection class.\n//\n//-----------------------------------------------------------------------------\n\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Xml; // for XmlReader/Writer\nusing System.Diagnostics;\n\nnamespace System.IO.Packaging\n{\n /// \n /// Collection of all the relationships corresponding to a given source PackagePart\n /// \n internal class InternalRelationshipCollection : IEnumerable\n {\n #region IEnumerable\n /// \n /// Returns an enumerator over all the relationships for a Package or a PackagePart\n /// \n /// \n IEnumerator IEnumerable.GetEnumerator()\n {\n return _relationships.GetEnumerator();\n }\n\n /// \n /// Returns an enumerator over all the relationships for a Package or a PackagePart\n /// \n /// \n IEnumerator IEnumerable.GetEnumerator()\n {\n return _relationships.GetEnumerator();\n }\n\n /// \n /// Returns an enumerator over all the relationships for a Package or a PackagePart\n /// \n /// \n public List.Enumerator GetEnumerator()\n {\n return _relationships.GetEnumerator();\n }\n\n #endregion\n \n #region Internal Methods\n /// \n /// Constructor\n /// \n /// For use by PackagePart\n internal InternalRelationshipCollection(PackagePart part) : this(part.Package, part)\n {\n }\n\n /// \n /// Constructor\n /// \n /// For use by Package\n internal InternalRelationshipCollection(Package package) : this(package, null)\n {\n }\n\n /// \n /// Add new relationship\n /// \n /// target\n /// Enumeration indicating the base uri for the target uri\n /// relationship type that uniquely defines the role of the relationship\n /// String that conforms to the xsd:ID datatype. Unique across the source's relationships.\n /// Null OK (ID will be generated).\n internal PackageRelationship Add(Uri targetUri, TargetMode targetMode, string relationshipType, string id)\n {\n return Add(targetUri, targetMode, relationshipType, id, parsing: false);\n }\n\n /// \n /// Return the relationship whose id is 'id', and null if not found.\n /// \n internal PackageRelationship GetRelationship(string id)\n {\n int index = GetRelationshipIndex(id);\n if (index == -1)\n return null;\n return _relationships[index];\n }\n\n /// \n /// Delete relationship with ID 'id'\n /// \n /// ID of the relationship to remove\n internal void Delete(String id)\n {\n int index = GetRelationshipIndex(id);\n if (index == -1)\n return;\n\n _relationships.RemoveAt(index);\n _dirty = true;\n }\n\n /// \n /// Clear all the relationships in this collection\n /// Today it is only used when the entire relationship part is being deleted\n /// \n internal void Clear()\n {\n _relationships.Clear();\n _dirty = true;\n }\n\n /// \n /// Flush to stream (destructive)\n /// \n /// \n /// Flush part.\n /// \n internal void Flush()\n {\n if (!_dirty)\n return;\n\n if (_relationships.Count == 0) // empty?\n {\n // delete the part\n if (_package.PartExists(_uri))\n {\n _package.DeletePart(_uri);\n }\n _relationshipPart = null;\n }\n else\n {\n EnsureRelationshipPart(); // lazy init\n\n // write xml\n WriteRelationshipPart(_relationshipPart);\n }\n _dirty = false;\n }\n\n internal static void ThrowIfInvalidRelationshipType(string relationshipType)\n {\n // Look for empty string or string with just spaces\n if (relationshipType.Trim() == String.Empty)\n throw new ArgumentException(SR.InvalidRelationshipType);\n }\n\n // If 'id' is not of the xsd type ID, throw an exception.\n internal static void ThrowIfInvalidXsdId(string id)\n {\n Debug.Assert(id != null, \"id should not be null\");\n\n try\n {\n // An XSD ID is an NCName that is unique.\n XmlConvert.VerifyNCName(id);\n }\n catch (XmlException exception)\n {\n var r = SR.NotAValidXmlIdString;\n var s = SR.Format(r, id);\n throw new XmlException(s, exception);\n }\n }\n\n #endregion Internal Methods\n\n #region Private Methods\n /// \n /// Constructor\n /// \n /// package\n /// part will be null if package is the source of the relationships\n /// Shared constructor\n private InternalRelationshipCollection(Package package, PackagePart part)\n {\n Debug.Assert(package != null, \"package parameter passed should never be null\");\n\n _package = package;\n _sourcePart = part;\n\n //_sourcePart may be null representing that the relationships are at the package level\n _uri = GetRelationshipPartUri(_sourcePart);\n _relationships = new List(4);\n\n // Load if available (not applicable to write-only mode).\n if ((package.FileOpenAccess == FileAccess.Read ||\n package.FileOpenAccess == FileAccess.ReadWrite) && package.PartExists(_uri))\n {\n _relationshipPart = package.GetPart(_uri);\n ThrowIfIncorrectContentType(_relationshipPart.ValidatedContentType);\n ParseRelationshipPart(_relationshipPart);\n }\n\n //Any initialization in the constructor should not set the dirty flag to true.\n _dirty = false;\n }\n\n /// \n /// Returns the associated RelationshipPart for this part\n /// \n /// may be null\n /// name of relationship part for the given part\n private static Uri GetRelationshipPartUri(PackagePart part)\n {\n Uri sourceUri;\n\n if (part == null)\n sourceUri = PackUriHelper.PackageRootUri;\n else\n sourceUri = part.Uri;\n\n return PackUriHelper.GetRelationshipPartUri(sourceUri);\n }\n\n /// \n /// Parse PackageRelationship Stream\n /// \n /// relationship part\n /// Thrown if XML is malformed\n private void ParseRelationshipPart(PackagePart part)\n {\n //We can safely open the stream as FileAccess.Read, as this code\n //should only be invoked if the Package has been opened in Read or ReadWrite mode.\n Debug.Assert(_package.FileOpenAccess == FileAccess.Read || _package.FileOpenAccess == FileAccess.ReadWrite,\n \"This method should only be called when FileAccess is Read or ReadWrite\");\n\n using (Stream s = part.GetStream(FileMode.Open, FileAccess.Read))\n {\n // load from the relationship part associated with the given part\n using (XmlReader baseReader = XmlReader.Create(s))\n {\n using (XmlCompatibilityReader reader = new XmlCompatibilityReader(baseReader, s_relationshipKnownNamespaces))\n {\n //This method expects the reader to be in ReadState.Initial.\n //It will make the first read call.\n PackagingUtilities.PerformInitialReadAndVerifyEncoding(baseReader);\n\n //Note: After the previous method call the reader should be at the first tag in the markup.\n //MoveToContent - Skips over the following - ProcessingInstruction, DocumentType, Comment, Whitespace, or SignificantWhitespace\n //If the reader is currently at a content node then this function call is a no-op\n reader.MoveToContent();\n\n // look for our tag and namespace pair - throw if other elements are encountered\n // Make sure that the current node read is an Element \n if (reader.NodeType == XmlNodeType.Element\n && (reader.Depth == 0)\n && (String.CompareOrdinal(s_relationshipsTagName, reader.LocalName) == 0)\n && (String.CompareOrdinal(PackagingUtilities.RelationshipNamespaceUri, reader.NamespaceURI) == 0))\n {\n ThrowIfXmlBaseAttributeIsPresent(reader);\n\n //There should be a namespace Attribute present at this level. \n //Also any other attribute on the tag is an error including xml: and xsi: attributes\n if (PackagingUtilities.GetNonXmlnsAttributeCount(reader) > 0)\n throw new XmlException(SR.RelationshipsTagHasExtraAttributes, null, reader.LineNumber, reader.LinePosition);\n\n // start tag encountered for Relationships\n // now parse individual Relationship tags\n while (reader.Read())\n {\n //Skips over the following - ProcessingInstruction, DocumentType, Comment, Whitespace, or SignificantWhitespace\n //If the reader is currently at a content node then this function call is a no-op\n reader.MoveToContent();\n\n //If MoveToContent() takes us to the end of the content\n if (reader.NodeType == XmlNodeType.None)\n continue;\n\n if (reader.NodeType == XmlNodeType.Element\n && (reader.Depth == 1)\n && (String.CompareOrdinal(s_relationshipTagName, reader.LocalName) == 0)\n && (String.CompareOrdinal(PackagingUtilities.RelationshipNamespaceUri, reader.NamespaceURI) == 0))\n {\n ThrowIfXmlBaseAttributeIsPresent(reader);\n\n int expectedAttributesCount = 3;\n\n string targetModeAttributeValue = reader.GetAttribute(s_targetModeAttributeName);\n if (targetModeAttributeValue != null)\n expectedAttributesCount++;\n\n //check if there are expected number of attributes. \n //Also any other attribute on the tag is an error including xml: and xsi: attributes\n if (PackagingUtilities.GetNonXmlnsAttributeCount(reader) == expectedAttributesCount)\n {\n ProcessRelationshipAttributes(reader);\n\n //Skip the EndElement for Relationship\n if (!reader.IsEmptyElement)\n ProcessEndElementForRelationshipTag(reader);\n }\n else\n {\n throw new XmlException(SR.RelationshipTagDoesntMatchSchema, null, reader.LineNumber, reader.LinePosition);\n }\n }\n else\n if (!(String.CompareOrdinal(s_relationshipsTagName, reader.LocalName) == 0 && (reader.NodeType == XmlNodeType.EndElement)))\n throw new XmlException(SR.UnknownTagEncountered, null, reader.LineNumber, reader.LinePosition);\n }\n }\n else throw new XmlException(SR.ExpectedRelationshipsElementTag, null, reader.LineNumber, reader.LinePosition);\n }\n }\n }\n }\n\n\n //This method processes the attributes that are present on the Relationship element\n private void ProcessRelationshipAttributes(XmlCompatibilityReader reader)\n {\n // Attribute : TargetMode\n\n string targetModeAttributeValue = reader.GetAttribute(s_targetModeAttributeName);\n\n //If the TargetMode attribute is missing in the underlying markup then we assume it to be internal\n TargetMode relationshipTargetMode = TargetMode.Internal;\n\n if (targetModeAttributeValue != null)\n {\n try\n {\n relationshipTargetMode = (TargetMode)(Enum.Parse(typeof(TargetMode), targetModeAttributeValue, ignoreCase: false));\n }\n catch (ArgumentNullException argNullEx)\n {\n ThrowForInvalidAttributeValue(reader, s_targetModeAttributeName, argNullEx);\n }\n catch (ArgumentException argEx)\n {\n //if the targetModeAttributeValue is not Internal|External then Argument Exception will be thrown.\n ThrowForInvalidAttributeValue(reader, s_targetModeAttributeName, argEx);\n }\n }\n\n // Attribute : Target\n // create a new PackageRelationship\n string targetAttributeValue = reader.GetAttribute(s_targetAttributeName);\n if (string.IsNullOrEmpty(targetAttributeValue))\n throw new XmlException(SR.Format(SR.RequiredRelationshipAttributeMissing, s_targetAttributeName), null, reader.LineNumber, reader.LinePosition);\n\n Uri targetUri = new Uri(targetAttributeValue, UriKind.RelativeOrAbsolute);\n\n // Attribute : Type\n string typeAttributeValue = reader.GetAttribute(s_typeAttributeName);\n if (string.IsNullOrEmpty(typeAttributeValue))\n throw new XmlException(SR.Format(SR.RequiredRelationshipAttributeMissing, s_typeAttributeName), null, reader.LineNumber, reader.LinePosition);\n\n // Attribute : Id\n // Get the Id attribute (required attribute).\n string idAttributeValue = reader.GetAttribute(s_idAttributeName);", "answers": [" if (string.IsNullOrEmpty(idAttributeValue))"], "length": 1315, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "07ac06ed-6bc3-46d2-ad7d-76f3929e242d", "reasoning": "The method ProcessRelationshipAttributes reads each required attribute. After retrieving the Id attribute into idAttributeValue, the next logical step is to validate that it is present, mirroring the earlier checks for Target and Type. Therefore the next line checks for null or empty and throws an XmlException if the Id is missing.", "reasoning_model_answer": "if (String.IsNullOrEmpty(idAttributeValue))\n throw new XmlException(SR.Format(SR.RequiredRelationshipAttributeMissing, s_idAttributeName), null, reader.LineNumber, reader.LinePosition);", "assistant_with_reasoning": "\nThe method ProcessRelationshipAttributes reads each required attribute. After retrieving the Id attribute into idAttributeValue, the next logical step is to validate that it is present, mirroring the earlier checks for Target and Type. Therefore the next line checks for null or empty and throws an XmlException if the Id is missing.\n\nif (String.IsNullOrEmpty(idAttributeValue))\n throw new XmlException(SR.Format(SR.RequiredRelationshipAttributeMissing, s_idAttributeName), null, reader.LineNumber, reader.LinePosition);", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.818, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 16416, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "if (String.IsNullOrEmpty(idAttributeValue))\n throw new XmlException(SR.Format(SR.RequiredRelationshipAttributeMissing, s_idAttributeName), null, reader.LineNumber, reader.LinePosition);", "score": 0.86, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "# Copyright 2013 Hewlett-Packard Development Company, L.P.\n# All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\n\nimport datetime\nimport time\n\nfrom glanceclient import client as glance_client\nfrom glanceclient import exc as glance_exc\nimport mock\nfrom oslo_config import cfg\nfrom oslo_serialization import jsonutils\nfrom oslo_utils import uuidutils\nfrom six.moves.urllib import parse as urlparse\nimport testtools\n\nfrom ironic.common import context\nfrom ironic.common import exception\nfrom ironic.common.glance_service import base_image_service\nfrom ironic.common.glance_service import service_utils\nfrom ironic.common.glance_service.v2 import image_service as glance_v2\nfrom ironic.common import image_service as service\nfrom ironic.tests import base\nfrom ironic.tests.unit import stubs\n\n\nCONF = cfg.CONF\n\n\nclass NullWriter(object):\n \"\"\"Used to test ImageService.get which takes a writer object.\"\"\"\n\n def write(self, *arg, **kwargs):\n pass\n\n\nclass TestGlanceSerializer(testtools.TestCase):\n def test_serialize(self):\n metadata = {'name': 'image1',\n 'is_public': True,\n 'foo': 'bar',\n 'properties': {\n 'prop1': 'propvalue1',\n 'mappings': [\n {'virtual': 'aaa',\n 'device': 'bbb'},\n {'virtual': 'xxx',\n 'device': 'yyy'}],\n 'block_device_mapping': [\n {'virtual_device': 'fake',\n 'device_name': '/dev/fake'},\n {'virtual_device': 'ephemeral0',\n 'device_name': '/dev/fake0'}]}}\n\n converted_expected = {\n 'name': 'image1',\n 'is_public': True,\n 'foo': 'bar',\n 'properties': {'prop1': 'propvalue1'}\n }\n converted = service_utils._convert(metadata, 'to')\n self.assertEqual(metadata,\n service_utils._convert(converted, 'from'))\n # Fields that rely on dict ordering can't be compared as text\n mappings = jsonutils.loads(converted['properties']\n .pop('mappings'))\n self.assertEqual([{\"device\": \"bbb\", \"virtual\": \"aaa\"},\n {\"device\": \"yyy\", \"virtual\": \"xxx\"}],\n mappings)\n bd_mapping = jsonutils.loads(converted['properties']\n .pop('block_device_mapping'))\n self.assertEqual([{\"virtual_device\": \"fake\",\n \"device_name\": \"/dev/fake\"},\n {\"virtual_device\": \"ephemeral0\",\n \"device_name\": \"/dev/fake0\"}],\n bd_mapping)\n # Compare the remaining\n self.assertEqual(converted_expected, converted)\n\n\nclass TestGlanceImageService(base.TestCase):\n NOW_GLANCE_OLD_FORMAT = \"2010-10-11T10:30:22\"\n NOW_GLANCE_FORMAT = \"2010-10-11T10:30:22.000000\"\n\n NOW_DATETIME = datetime.datetime(2010, 10, 11, 10, 30, 22)\n\n def setUp(self):\n super(TestGlanceImageService, self).setUp()\n client = stubs.StubGlanceClient()\n self.context = context.RequestContext(auth_token=True)\n self.context.user_id = 'fake'\n self.context.project_id = 'fake'\n self.service = service.GlanceImageService(client, 1, self.context)\n\n self.config(glance_host='localhost', group='glance')\n try:\n self.config(auth_strategy='keystone', group='glance')\n except Exception:\n opts = [\n cfg.StrOpt('auth_strategy', default='keystone'),\n ]\n CONF.register_opts(opts)\n\n return\n\n @staticmethod\n def _make_fixture(**kwargs):\n fixture = {'name': None,\n 'properties': {},\n 'status': None,\n 'is_public': None}\n fixture.update(kwargs)\n return fixture\n\n @property\n def endpoint(self):\n # For glanceclient versions >= 0.13, the endpoint is located\n # under http_client (blueprint common-client-library-2)\n # I5addc38eb2e2dd0be91b566fda7c0d81787ffa75\n # Test both options to keep backward compatibility\n if getattr(self.service.client, 'endpoint', None):\n endpoint = self.service.client.endpoint\n else:\n endpoint = self.service.client.http_client.endpoint\n return endpoint\n\n def _make_datetime_fixture(self):\n return self._make_fixture(created_at=self.NOW_GLANCE_FORMAT,\n updated_at=self.NOW_GLANCE_FORMAT,\n deleted_at=self.NOW_GLANCE_FORMAT)\n\n def test_create_with_instance_id(self):\n # Ensure instance_id is persisted as an image-property.\n fixture = {'name': 'test image',\n 'is_public': False,\n 'properties': {'instance_id': '42', 'user_id': 'fake'}}\n image_id = self.service.create(fixture)['id']\n image_meta = self.service.show(image_id)\n expected = {\n 'id': image_id,\n 'name': 'test image',\n 'is_public': False,\n 'size': None,\n 'min_disk': None,\n 'min_ram': None,\n 'disk_format': None,\n 'container_format': None,\n 'checksum': None,\n 'created_at': self.NOW_DATETIME,\n 'updated_at': self.NOW_DATETIME,\n 'deleted_at': None,\n 'deleted': None,\n 'status': None,\n 'properties': {'instance_id': '42', 'user_id': 'fake'},\n 'owner': None,\n }\n\n self.assertDictEqual(expected, image_meta)\n\n image_metas = self.service.detail()\n self.assertDictEqual(expected, image_metas[0])\n\n def test_create_without_instance_id(self):\n \"\"\"Test creating an image without an instance ID.\n\n Ensure we can create an image without having to specify an\n instance_id. Public images are an example of an image not tied to an\n instance.\n \"\"\"\n fixture = {'name': 'test image', 'is_public': False}\n image_id = self.service.create(fixture)['id']\n\n expected = {\n 'id': image_id,\n 'name': 'test image',\n 'is_public': False,\n 'size': None,\n 'min_disk': None,\n 'min_ram': None,\n 'disk_format': None,\n 'container_format': None,\n 'checksum': None,\n 'created_at': self.NOW_DATETIME,\n 'updated_at': self.NOW_DATETIME,\n 'deleted_at': None,\n 'deleted': None,\n 'status': None,\n 'properties': {},\n 'owner': None,\n }\n actual = self.service.show(image_id)\n self.assertDictEqual(expected, actual)\n\n def test_create(self):\n fixture = self._make_fixture(name='test image')\n num_images = len(self.service.detail())\n image_id = self.service.create(fixture)['id']\n\n self.assertIsNotNone(image_id)\n self.assertEqual(\n num_images + 1, len(self.service.detail()))\n\n def test_create_and_show_non_existing_image(self):\n fixture = self._make_fixture(name='test image')\n image_id = self.service.create(fixture)['id']\n\n self.assertIsNotNone(image_id)\n self.assertRaises(exception.ImageNotFound,\n self.service.show,\n 'bad image id')\n\n def test_detail_private_image(self):\n fixture = self._make_fixture(name='test image')\n fixture['is_public'] = False\n properties = {'owner_id': 'proj1'}\n fixture['properties'] = properties\n\n self.service.create(fixture)['id']\n\n proj = self.context.project_id\n self.context.project_id = 'proj1'\n\n image_metas = self.service.detail()\n\n self.context.project_id = proj\n\n self.assertEqual(1, len(image_metas))\n self.assertEqual('test image', image_metas[0]['name'])\n self.assertFalse(image_metas[0]['is_public'])\n\n def test_detail_marker(self):\n fixtures = []\n ids = []\n for i in range(10):\n fixture = self._make_fixture(name='TestImage %d' % (i))\n fixtures.append(fixture)\n ids.append(self.service.create(fixture)['id'])\n\n image_metas = self.service.detail(marker=ids[1])\n self.assertEqual(8, len(image_metas))\n i = 2\n for meta in image_metas:\n expected = {\n 'id': ids[i],\n 'status': None,\n 'is_public': None,\n 'name': 'TestImage %d' % (i),\n 'properties': {},\n 'size': None,\n 'min_disk': None,\n 'min_ram': None,\n 'disk_format': None,\n 'container_format': None,\n 'checksum': None,\n 'created_at': self.NOW_DATETIME,\n 'updated_at': self.NOW_DATETIME,\n 'deleted_at': None,\n 'deleted': None,\n 'owner': None,\n }\n\n self.assertDictEqual(expected, meta)\n i = i + 1\n\n def test_detail_limit(self):\n fixtures = []\n ids = []\n for i in range(10):\n fixture = self._make_fixture(name='TestImage %d' % (i))\n fixtures.append(fixture)\n ids.append(self.service.create(fixture)['id'])\n\n image_metas = self.service.detail(limit=5)\n self.assertEqual(5, len(image_metas))\n\n def test_detail_default_limit(self):\n fixtures = []\n ids = []\n for i in range(10):\n fixture = self._make_fixture(name='TestImage %d' % (i))\n fixtures.append(fixture)\n ids.append(self.service.create(fixture)['id'])\n\n image_metas = self.service.detail()\n for i, meta in enumerate(image_metas):\n self.assertEqual(meta['name'], 'TestImage %d' % (i))\n\n def test_detail_marker_and_limit(self):\n fixtures = []\n ids = []\n for i in range(10):\n fixture = self._make_fixture(name='TestImage %d' % (i))\n fixtures.append(fixture)\n ids.append(self.service.create(fixture)['id'])\n\n image_metas = self.service.detail(marker=ids[3], limit=5)\n self.assertEqual(5, len(image_metas))\n i = 4\n for meta in image_metas:\n expected = {\n 'id': ids[i],\n 'status': None,\n 'is_public': None,\n 'name': 'TestImage %d' % (i),\n 'properties': {},\n 'size': None,\n 'min_disk': None,\n 'min_ram': None,\n 'disk_format': None,\n 'container_format': None,\n 'checksum': None,\n 'created_at': self.NOW_DATETIME,\n 'updated_at': self.NOW_DATETIME,\n 'deleted_at': None,\n 'deleted': None,\n 'owner': None,\n }\n self.assertDictEqual(expected, meta)\n i = i + 1\n\n def test_detail_invalid_marker(self):\n fixtures = []\n ids = []\n for i in range(10):\n fixture = self._make_fixture(name='TestImage %d' % (i))\n fixtures.append(fixture)\n ids.append(self.service.create(fixture)['id'])\n\n self.assertRaises(exception.Invalid, self.service.detail,\n marker='invalidmarker')\n\n def test_update(self):\n fixture = self._make_fixture(name='test image')\n image = self.service.create(fixture)\n image_id = image['id']\n fixture['name'] = 'new image name'\n self.service.update(image_id, fixture)\n\n new_image_data = self.service.show(image_id)\n self.assertEqual('new image name', new_image_data['name'])\n\n def test_delete(self):\n fixture1 = self._make_fixture(name='test image 1')\n fixture2 = self._make_fixture(name='test image 2')\n fixtures = [fixture1, fixture2]\n\n num_images = len(self.service.detail())\n self.assertEqual(0, num_images)\n\n ids = []\n for fixture in fixtures:\n new_id = self.service.create(fixture)['id']\n ids.append(new_id)\n\n num_images = len(self.service.detail())\n self.assertEqual(2, num_images)\n\n self.service.delete(ids[0])\n # When you delete an image from glance, it sets the status to DELETED\n # and doesn't actually remove the image.\n\n # Check the image is still there.\n num_images = len(self.service.detail())\n self.assertEqual(2, num_images)\n\n # Check the image is marked as deleted.\n num_images = len([x for x in self.service.detail()\n if not x['deleted']])\n self.assertEqual(1, num_images)\n\n def test_show_passes_through_to_client(self):\n fixture = self._make_fixture(name='image1', is_public=True)\n image_id = self.service.create(fixture)['id']\n\n image_meta = self.service.show(image_id)\n expected = {\n 'id': image_id,\n 'name': 'image1',\n 'is_public': True,\n 'size': None,\n 'min_disk': None,\n 'min_ram': None,\n 'disk_format': None,\n 'container_format': None,\n 'checksum': None,\n 'created_at': self.NOW_DATETIME,\n 'updated_at': self.NOW_DATETIME,\n 'deleted_at': None,\n 'deleted': None,\n 'status': None,\n 'properties': {},\n 'owner': None,\n }\n self.assertEqual(expected, image_meta)\n\n def test_show_raises_when_no_authtoken_in_the_context(self):\n fixture = self._make_fixture(name='image1',\n is_public=False,\n properties={'one': 'two'})\n image_id = self.service.create(fixture)['id']\n self.context.auth_token = False\n self.assertRaises(exception.ImageNotFound,\n self.service.show,\n image_id)\n\n def test_detail_passes_through_to_client(self):\n fixture = self._make_fixture(name='image10', is_public=True)\n image_id = self.service.create(fixture)['id']\n image_metas = self.service.detail()\n expected = [\n {\n 'id': image_id,\n 'name': 'image10',\n 'is_public': True,\n 'size': None,\n 'min_disk': None,\n 'min_ram': None,\n 'disk_format': None,\n 'container_format': None,\n 'checksum': None,\n 'created_at': self.NOW_DATETIME,\n 'updated_at': self.NOW_DATETIME,\n 'deleted_at': None,\n 'deleted': None,\n 'status': None,\n 'properties': {},\n 'owner': None,\n },\n ]\n self.assertEqual(expected, image_metas)\n\n def test_show_makes_datetimes(self):\n fixture = self._make_datetime_fixture()\n image_id = self.service.create(fixture)['id']\n image_meta = self.service.show(image_id)\n self.assertEqual(self.NOW_DATETIME, image_meta['created_at'])\n self.assertEqual(self.NOW_DATETIME, image_meta['updated_at'])\n\n def test_detail_makes_datetimes(self):", "answers": [" fixture = self._make_datetime_fixture()"], "length": 1136, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "b6e6e7a6-7678-4011-82c3-39765ece0c0c", "reasoning": "The method test_detail_makes_datetimes is being defined. Following the pattern of test_show_makes_datetimes, the first step inside the method is to create a fixture with datetime strings using the helper _make_datetime_fixture(). Therefore the next line of code should be the assignment of that fixture.", "reasoning_model_answer": "fixture = self._make_datetime_fixture()", "assistant_with_reasoning": "\nThe method test_detail_makes_datetimes is being defined. Following the pattern of test_show_makes_datetimes, the first step inside the method is to create a fixture with datetime strings using the helper _make_datetime_fixture(). Therefore the next line of code should be the assignment of that fixture.\n\nfixture = self._make_datetime_fixture()", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.265, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 16132, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "fixture = self._make_datetime_fixture()", "score": 0.91, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Linq.Expressions;\nusing System.Reflection;\nusing EFSqlTranslator.Translation.DbObjects;\nusing EFSqlTranslator.Translation.Extensions;\nusing EFSqlTranslator.Translation.MethodTranslators;\n\nnamespace EFSqlTranslator.Translation\n{\n public class ExpressionTranslator : ExpressionVisitor\n {\n private readonly IModelInfoProvider _infoProvider;\n\n private readonly IDbObjectFactory _dbFactory;\n\n private readonly TranslationState _state;\n\n private readonly UniqueNameGenerator _nameGenerator = new UniqueNameGenerator();\n\n private readonly TranslationPlugIns _plugIns = new TranslationPlugIns();\n\n public ExpressionTranslator(\n IModelInfoProvider infoProvider, IDbObjectFactory dbFactory,\n TranslationState state = null, IEnumerable methodTranslators = null)\n {\n _infoProvider = infoProvider;\n _dbFactory = dbFactory;\n _state = state ?? new TranslationState();\n\n RegisterDefaultPlugIns();\n\n if (methodTranslators == null)\n return;\n\n foreach (var translator in methodTranslators)\n translator.Register(_plugIns);\n }\n\n private void RegisterDefaultPlugIns()\n {\n new WhereTranslator(_infoProvider, _dbFactory).Register(_plugIns);\n new AnyTranslator(_infoProvider, _dbFactory).Register(_plugIns);\n new JoinTranslator(_infoProvider, _dbFactory).Register(_plugIns);\n new GroupByTranslator(_infoProvider, _dbFactory).Register(_plugIns);\n new OrderByTranslator(_infoProvider, _dbFactory).Register(_plugIns);\n new SelectTranslator(_infoProvider, _dbFactory).Register(_plugIns);\n new CountTranslator(_infoProvider, _dbFactory).Register(_plugIns);\n new AggregationTranslator(_infoProvider, _dbFactory).Register(_plugIns);\n new StringStartsEndsTranslator(_infoProvider, _dbFactory).Register(_plugIns);\n new ContainsTranslator(_infoProvider, _dbFactory).Register(_plugIns);\n new InTranslator(_infoProvider, _dbFactory).Register(_plugIns);\n new LimitTranslator(_infoProvider, _dbFactory).Register(_plugIns);\n new DistinctTranslator(_infoProvider, _dbFactory).Register(_plugIns);\n new DistinctCountTranslator(_infoProvider, _dbFactory).Register(_plugIns);\n }\n\n internal IDbObject GetElement()\n {\n return _state.ResultStack.Peek();\n }\n\n public override Expression Visit(Expression e)\n {\n return base.Visit(e);\n }\n\n protected override Expression VisitConstant(ConstantExpression c)\n {\n var entityInfo = _infoProvider.FindEntityInfo(c.Type);\n if (entityInfo != null)\n {\n var dbTable = _dbFactory.BuildTable(entityInfo);\n var dbRef = _dbFactory.BuildRef(dbTable);\n\n var dbSelect = _dbFactory.BuildSelect(dbRef);\n dbRef.Alias = _nameGenerator.GenerateAlias(dbSelect, dbTable.TableName);\n\n _state.ResultStack.Push(dbSelect);\n }\n else if (!c.Type.IsAnonymouse())\n {\n var dbConstant = _dbFactory.BuildConstant(c.Value, true);\n _state.ResultStack.Push(dbConstant);\n }\n\n return c;\n }\n\n protected override Expression VisitNew(NewExpression n)\n {\n var list = _dbFactory.BuildList();\n\n if (n.Members != null)\n {\n for (var i = 0; i < n.Members.Count; i++)\n {\n var member = n.Members[i];\n var assignment = n.Arguments[i];\n\n Visit(assignment);\n\n var dbObj = _state.ResultStack.Pop();\n var dbKeyValue = _dbFactory.BuildKeyValue(member.Name, dbObj);\n list.Add(dbKeyValue);\n }\n\n _state.ResultStack.Push(list);\n return n;\n }\n\n _state.ResultStack.Push(list);\n return base.VisitNew(n);\n }\n\n protected override MemberAssignment VisitMemberAssignment(MemberAssignment ma)\n {\n var list = (IDbList)_state.ResultStack.Pop();\n\n var member = ma.Member;\n var assignment = ma.Expression;\n\n Visit(assignment);\n\n var dbObj = _state.ResultStack.Pop();\n var dbKeyValue = _dbFactory.BuildKeyValue(member.Name, dbObj);\n list.Add(dbKeyValue);\n\n _state.ResultStack.Push(list);\n return ma;\n }\n\n protected override Expression VisitParameter(ParameterExpression p)\n {\n return VisitParameterInteral(p, false);\n }\n\n private Expression VisitParameterInteral(ParameterExpression p, bool ignoreParamStack)\n {\n DbReference dbRef = null;\n\n if (p.Type.IsAnonymouse() || p.Type.IsGrouping())\n {\n var dbSelect = _state.GetLastSelect();\n dbRef = _dbFactory.BuildRef(null);\n dbRef.OwnerSelect = dbSelect;\n\n var collection = p.Type.IsGrouping()\n ? dbSelect.GroupBys.AsEnumerable()\n : dbSelect.Selection;\n\n foreach (var selectable in collection)\n dbRef.RefSelection[selectable.GetAliasOrName()] = selectable;\n }\n\n\n if (dbRef == null && !ignoreParamStack && _state.ParamterStack.Count > 0)\n {\n var dbRefs = _state.ParamterStack.Peek();\n if (dbRefs.ContainsKey(p))\n dbRef = dbRefs[p];\n }\n\n // if we can not find the parameter expression in the ParamterStack,\n // it means this is the first time we translates the parameter, so we\n // need to look for it in the most recently translated select\n // this is required because we may not always has select on the top\n // of the stack, especially we translating arguments for method calls\n if (dbRef == null)\n {\n var dbSelect = _state.GetLastSelect();\n\n var refCol = (_state.ResultStack.Peek() as IDbRefColumn) ??\n dbSelect.Selection.OfType().LastOrDefault();\n\n dbRef = refCol != null ? refCol.Ref : dbSelect.From;\n }\n\n if (dbRef == null)\n throw new NullReferenceException();\n\n _state.ResultStack.Push(dbRef);\n\n return p;\n }\n\n protected override Expression VisitMember(MemberExpression m)\n {\n var expression = Visit(m.Expression);\n if (expression is ConstantExpression constExpr)\n {\n var container = constExpr.Value;\n var member = m.Member;\n \n object value = null;\n var valueRetrieved = false;\n switch (member)\n {\n case FieldInfo field:\n value = field.GetValue(container);\n valueRetrieved = true;\n break;\n case PropertyInfo prop:\n value = prop.GetValue(container, null);\n valueRetrieved = true;\n break;\n }\n\n if (valueRetrieved)\n {\n var dbObject = _dbFactory.BuildConstant(value, true);\n _state.ResultStack.Push(dbObject);\n return m;\n }\n }\n\n var typeInfo = m.Type.GetTypeInfo();\n\n if (m.Expression.Type.IsAnonymouse())\n {\n var dbRef = (DbReference)_state.ResultStack.Peek();\n if (dbRef.RefSelection.ContainsKey(m.Member.Name))\n {\n var dbObj = dbRef.RefSelection[m.Member.Name];\n\n // pop out the dbRef from the stack, it was the result of\n // translate a parameter, and it is not required for following translation\n _state.ResultStack.Pop();\n _state.ResultStack.Push(dbObj);\n\n return m;\n }\n }\n\n if (m.Expression.Type.IsGrouping())\n {\n var dbRef = (DbReference)_state.ResultStack.Pop();\n\n var dbSelect = dbRef.OwnerSelect;\n if (dbSelect.GroupBys.IsSingleKey)\n {\n var kColumn = dbSelect.GroupBys.Single();\n _state.ResultStack.Push(kColumn);\n }\n else\n {\n _state.ResultStack.Push(dbRef);\n }\n\n return m;\n }\n\n // if the member is a queryable entity, we need to translate it\n // into a relation, which means a join\n var entityInfo = _infoProvider.FindEntityInfo(m.Type);\n if (entityInfo != null)\n {\n var dbObj = _state.ResultStack.Pop();\n var refCol = dbObj as IDbRefColumn;\n var fromRef = refCol != null ? refCol.Ref : (DbReference)dbObj;\n\n var fromEntity = _infoProvider.FindEntityInfo(m.Expression.Type);\n var relation = fromEntity.GetRelation(m.Member.Name);\n\n var dbJoin = GetOrCreateJoin(relation, fromRef, refCol ?? fromRef.ReferredRefColumn);\n\n // RefColumnAlias is used as alias in case we need to create a ref column for this dbRef\n dbJoin.To.RefColumnAlias = m.Member.Name;\n\n if (refCol != null)\n {\n refCol = _dbFactory.BuildRefColumn(dbJoin.To, m.Member.Name);\n\n if (dbJoin.To.Referee is IDbSelect subSelect)\n refCol.RefTo = subSelect.Selection.OfType().Single();\n\n _state.ResultStack.Push(refCol);\n return m;\n }\n\n _state.ResultStack.Push(relation.IsChildRelation ? dbJoin.To.Referee : dbJoin.To);\n return m;\n }\n\n if (typeInfo.Namespace.StartsWith(\"System\"))\n {\n var dbObj = _state.ResultStack.Pop();\n var refCol = dbObj as IDbRefColumn;\n var dbRef = refCol != null ? refCol.Ref : (DbReference)dbObj;\n\n var fieldInfo = _infoProvider.FindFieldInfo(m.Member);\n var col = _dbFactory.BuildColumn(dbRef, fieldInfo.DbName, fieldInfo.ValType);\n _state.ResultStack.Push(col);\n\n // if we create a column whose DbRef is using by a RefColumn\n // we need to make sure the column is added to the ref column's owner select\n // This normally happen when we are accessing a column from a child relation\n refCol = refCol ?? dbRef.ReferredRefColumn;\n\n // if the ref column is not now, and it is referring another ref column\n // we need to make sure the column we translated is in the sub select which\n // owns the ref column that referred by the current refColumn\n refCol?.RefTo?.AddToReferedSelect(_dbFactory, fieldInfo.DbName, fieldInfo.ValType);\n\n return m;\n }\n\n return base.VisitMember(m);\n }\n\n /// Create a join for the relation\n /// For parent relation, we create a join that joins to the parent table\n /// For child relation, we will create a sub select that returns the child table,\n /// and then joins to the sub select.\n /// The reason for joining to sub select for child relation, is that we want to be\n /// able to group on the join key, so that we will not repeat the parent row.\n private IDbJoin GetOrCreateJoin(EntityRelation relation, DbReference fromRef, IDbRefColumn refCol)\n {\n var dbSelect = fromRef.OwnerSelect;\n var tupleKey = Tuple.Create(dbSelect, relation);\n\n if (!relation.IsChildRelation && _state.CreatedJoins.ContainsKey(tupleKey))\n return _state.CreatedJoins[tupleKey];\n\n var toEntity = relation.ToEntity;\n var dbTable = _dbFactory.BuildTable(toEntity);\n\n DbReference joinTo;\n DbReference childRef = null;\n IDbSelect childSelect = null;\n\n // Create the join. For parent join, we just need to join to a Ref to the table\n // For child relation, we will firstly create a sub select that return the child table\n // and then join to then sub select\n if (!relation.IsChildRelation)\n {\n var tableAlias = _nameGenerator.GenerateAlias(dbSelect, dbTable.TableName);\n joinTo = _dbFactory.BuildRef(dbTable, tableAlias);\n }\n else\n {\n childRef = _dbFactory.BuildRef(dbTable);\n childSelect = _dbFactory.BuildSelect(childRef);\n childRef.Alias = _nameGenerator.GenerateAlias(childSelect, dbTable.TableName);\n\n var tableAlias = _nameGenerator.GenerateAlias(dbSelect, TranslationConstants.SubSelectPrefix, true);\n joinTo = _dbFactory.BuildRef(childSelect, tableAlias);\n }\n\n var dbJoin = _dbFactory.BuildJoin(joinTo, dbSelect);\n dbSelect.Joins.Add(dbJoin);\n\n // build join condition\n IDbBinary condition = null;\n for (var i = 0; i < relation.FromKeys.Count; i++)\n {\n var fromKey = relation.FromKeys[i];\n var toKey = relation.ToKeys[i];\n\n var fromColumn = _dbFactory.BuildColumn(fromRef, fromKey.DbName, fromKey.ValType);", "answers": [" var toColumn = _dbFactory.BuildColumn(joinTo, toKey.DbName, toKey.ValType);"], "length": 1098, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "6e5d60bb-b7cd-4c22-b404-46bd814e2687", "reasoning": "The method is constructing join conditions inside a loop over relation keys. After creating the fromColumn, the next logical step is to create the corresponding column from the target side of the join (toColumn) using the join reference (joinTo) and the toKey metadata. This line follows directly after the existing fromColumn line.", "reasoning_model_answer": "var toColumn = _dbFactory.BuildColumn(joinTo, toKey.DbName, toKey.ValType);", "assistant_with_reasoning": "\nThe method is constructing join conditions inside a loop over relation keys. After creating the fromColumn, the next logical step is to create the corresponding column from the target side of the join (toColumn) using the join reference (joinTo) and the toKey metadata. This line follows directly after the existing fromColumn line.\n\nvar toColumn = _dbFactory.BuildColumn(joinTo, toKey.DbName, toKey.ValType);", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.621, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 14185, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "var toColumn = _dbFactory.BuildColumn(joinTo, toKey.DbName, toKey.ValType);", "score": 0.9, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "\"\"\"\nCORE MARKDOWN BLOCKPARSER\n=============================================================================\n\nThis parser handles basic parsing of Markdown blocks. It doesn't concern itself\nwith inline elements such as **bold** or *italics*, but rather just catches \nblocks, lists, quotes, etc.\n\nThe BlockParser is made up of a bunch of BlockProssors, each handling a \ndifferent type of block. Extensions may add/replace/remove BlockProcessors\nas they need to alter how markdown blocks are parsed.\n\n\"\"\"\n\nimport logging\nimport re\nimport util\nfrom blockparser import BlockParser\n\nlogger = logging.getLogger('MARKDOWN')\n\n\ndef build_block_parser(md_instance, **kwargs):\n \"\"\" Build the default block parser used by Markdown. \"\"\"\n parser = BlockParser(md_instance)\n parser.blockprocessors['empty'] = EmptyBlockProcessor(parser)\n parser.blockprocessors['indent'] = ListIndentProcessor(parser)\n parser.blockprocessors['code'] = CodeBlockProcessor(parser)\n parser.blockprocessors['hashheader'] = HashHeaderProcessor(parser)\n parser.blockprocessors['setextheader'] = SetextHeaderProcessor(parser)\n parser.blockprocessors['hr'] = HRProcessor(parser)\n parser.blockprocessors['olist'] = OListProcessor(parser)\n parser.blockprocessors['ulist'] = UListProcessor(parser)\n parser.blockprocessors['quote'] = BlockQuoteProcessor(parser)\n parser.blockprocessors['paragraph'] = ParagraphProcessor(parser)\n return parser\n\n\nclass BlockProcessor:\n \"\"\" Base class for block processors. \n \n Each subclass will provide the methods below to work with the source and\n tree. Each processor will need to define it's own ``test`` and ``run``\n methods. The ``test`` method should return True or False, to indicate\n whether the current block should be processed by this processor. If the\n test passes, the parser will call the processors ``run`` method.\n\n \"\"\"\n\n def __init__(self, parser):\n self.parser = parser\n self.tab_length = parser.markdown.tab_length\n\n def lastChild(self, parent):\n \"\"\" Return the last child of an etree element. \"\"\"\n if len(parent):\n return parent[-1]\n else:\n return None\n\n def detab(self, text):\n \"\"\" Remove a tab from the front of each line of the given text. \"\"\"\n newtext = []\n lines = text.split('\\n')\n for line in lines:\n if line.startswith(' '*self.tab_length):\n newtext.append(line[self.tab_length:])\n elif not line.strip():\n newtext.append('')\n else:\n break\n return '\\n'.join(newtext), '\\n'.join(lines[len(newtext):])\n\n def looseDetab(self, text, level=1):\n \"\"\" Remove a tab from front of lines but allowing dedented lines. \"\"\"\n lines = text.split('\\n')\n for i in range(len(lines)):\n if lines[i].startswith(' '*self.tab_length*level):\n lines[i] = lines[i][self.tab_length*level:]\n return '\\n'.join(lines)\n\n def test(self, parent, block):\n \"\"\" Test for block type. Must be overridden by subclasses. \n \n As the parser loops through processors, it will call the ``test`` method\n on each to determine if the given block of text is of that type. This\n method must return a boolean ``True`` or ``False``. The actual method of\n testing is left to the needs of that particular block type. It could \n be as simple as ``block.startswith(some_string)`` or a complex regular\n expression. As the block type may be different depending on the parent\n of the block (i.e. inside a list), the parent etree element is also \n provided and may be used as part of the test.\n\n Keywords:\n \n * ``parent``: A etree element which will be the parent of the block.\n * ``block``: A block of text from the source which has been split at \n blank lines.\n \"\"\"\n pass\n\n def run(self, parent, blocks):\n \"\"\" Run processor. Must be overridden by subclasses. \n \n When the parser determines the appropriate type of a block, the parser\n will call the corresponding processor's ``run`` method. This method\n should parse the individual lines of the block and append them to\n the etree. \n\n Note that both the ``parent`` and ``etree`` keywords are pointers\n to instances of the objects which should be edited in place. Each\n processor must make changes to the existing objects as there is no\n mechanism to return new/different objects to replace them.\n\n This means that this method should be adding SubElements or adding text\n to the parent, and should remove (``pop``) or add (``insert``) items to\n the list of blocks.\n\n Keywords:\n\n * ``parent``: A etree element which is the parent of the current block.\n * ``blocks``: A list of all remaining blocks of the document.\n \"\"\"\n pass\n\n\nclass ListIndentProcessor(BlockProcessor):\n \"\"\" Process children of list items. \n \n Example:\n * a list item\n process this part\n\n or this part\n\n \"\"\"\n\n ITEM_TYPES = ['li']\n LIST_TYPES = ['ul', 'ol']\n\n def __init__(self, *args):\n BlockProcessor.__init__(self, *args)\n self.INDENT_RE = re.compile(r'^(([ ]{%s})+)'% self.tab_length)\n\n def test(self, parent, block):\n return block.startswith(' '*self.tab_length) and \\\n not self.parser.state.isstate('detabbed') and \\\n (parent.tag in self.ITEM_TYPES or \\\n (len(parent) and parent[-1] and \\\n (parent[-1].tag in self.LIST_TYPES)\n )\n )\n\n def run(self, parent, blocks):\n block = blocks.pop(0)\n level, sibling = self.get_level(parent, block)\n block = self.looseDetab(block, level)\n\n self.parser.state.set('detabbed')\n if parent.tag in self.ITEM_TYPES:\n # It's possible that this parent has a 'ul' or 'ol' child list\n # with a member. If that is the case, then that should be the\n # parent. This is intended to catch the edge case of an indented \n # list whose first member was parsed previous to this point\n # see OListProcessor\n if len(parent) and parent[-1].tag in self.LIST_TYPES:\n self.parser.parseBlocks(parent[-1], [block])\n else:\n # The parent is already a li. Just parse the child block.\n self.parser.parseBlocks(parent, [block])\n elif sibling.tag in self.ITEM_TYPES:\n # The sibling is a li. Use it as parent.\n self.parser.parseBlocks(sibling, [block])\n elif len(sibling) and sibling[-1].tag in self.ITEM_TYPES:\n # The parent is a list (``ol`` or ``ul``) which has children.\n # Assume the last child li is the parent of this block.\n if sibling[-1].text:\n # If the parent li has text, that text needs to be moved to a p\n # The p must be 'inserted' at beginning of list in the event\n # that other children already exist i.e.; a nested sublist.\n p = util.etree.Element('p')\n p.text = sibling[-1].text\n sibling[-1].text = ''\n sibling[-1].insert(0, p)\n self.parser.parseChunk(sibling[-1], block)\n else:\n self.create_item(sibling, block)\n self.parser.state.reset()\n\n def create_item(self, parent, block):\n \"\"\" Create a new li and parse the block with it as the parent. \"\"\"\n li = util.etree.SubElement(parent, 'li')\n self.parser.parseBlocks(li, [block])\n \n def get_level(self, parent, block):\n \"\"\" Get level of indent based on list level. \"\"\"\n # Get indent level\n m = self.INDENT_RE.match(block)\n if m:\n indent_level = len(m.group(1))/self.tab_length\n else:\n indent_level = 0\n if self.parser.state.isstate('list'):\n # We're in a tightlist - so we already are at correct parent.\n level = 1\n else:\n # We're in a looselist - so we need to find parent.\n level = 0\n # Step through children of tree to find matching indent level.\n while indent_level > level:\n child = self.lastChild(parent)\n if child and (child.tag in self.LIST_TYPES or child.tag in self.ITEM_TYPES):\n if child.tag in self.LIST_TYPES:\n level += 1\n parent = child\n else:\n # No more child levels. If we're short of indent_level,\n # we have a code block. So we stop here.\n break\n return level, parent", "answers": ["class CodeBlockProcessor(BlockProcessor):"], "length": 1005, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "21b72eb5-482f-47c2-9b63-e6fdfb34bdc0", "reasoning": "The code ends inside ListIndentProcessor.get_level, returning a tuple. After this method the class definition ends and the next logical component in the file is the next block processor class. In the original Markdown parser source, the next class defined after ListIndentProcessor is EmptyBlockProcessor, which inherits from BlockProcessor. Therefore the next line should start that class definition.", "reasoning_model_answer": "class EmptyBlockProcessor(BlockProcessor):", "assistant_with_reasoning": "\nThe code ends inside ListIndentProcessor.get_level, returning a tuple. After this method the class definition ends and the next logical component in the file is the next block processor class. In the original Markdown parser source, the next class defined after ListIndentProcessor is EmptyBlockProcessor, which inherits from BlockProcessor. Therefore the next line should start that class definition.\n\nclass EmptyBlockProcessor(BlockProcessor):", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.059, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 8925, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "class EmptyBlockProcessor(BlockProcessor):", "score": 0.89, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/*\n * Copyright 2014-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\"). You may not use this file except in compliance with\n * the License. A copy of the License is located at\n * \n * http://aws.amazon.com/apache2.0\n * \n * or in the \"license\" file accompanying this file. This file is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR\n * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions\n * and limitations under the License.\n */\npackage com.amazonaws.services.redshift.model;\n\nimport java.io.Serializable;\nimport javax.annotation.Generated;\n\n/**\n *

    \n * Describes a security group.\n *

    \n * \n * @see AWS API\n * Documentation\n */\n@Generated(\"com.amazonaws:aws-java-sdk-code-generator\")\npublic class ClusterSecurityGroup implements Serializable, Cloneable {\n\n /**\n *

    \n * The name of the cluster security group to which the operation was applied.\n *

    \n */\n private String clusterSecurityGroupName;\n /**\n *

    \n * A description of the security group.\n *

    \n */\n private String description;\n /**\n *

    \n * A list of EC2 security groups that are permitted to access clusters associated with this cluster security group.\n *

    \n */\n private com.amazonaws.internal.SdkInternalList eC2SecurityGroups;\n /**\n *

    \n * A list of IP ranges (CIDR blocks) that are permitted to access clusters associated with this cluster security\n * group.\n *

    \n */\n private com.amazonaws.internal.SdkInternalList iPRanges;\n /**\n *

    \n * The list of tags for the cluster security group.\n *

    \n */\n private com.amazonaws.internal.SdkInternalList tags;\n\n /**\n *

    \n * The name of the cluster security group to which the operation was applied.\n *

    \n * \n * @param clusterSecurityGroupName\n * The name of the cluster security group to which the operation was applied.\n */\n\n public void setClusterSecurityGroupName(String clusterSecurityGroupName) {\n this.clusterSecurityGroupName = clusterSecurityGroupName;\n }\n\n /**\n *

    \n * The name of the cluster security group to which the operation was applied.\n *

    \n * \n * @return The name of the cluster security group to which the operation was applied.\n */\n\n public String getClusterSecurityGroupName() {\n return this.clusterSecurityGroupName;\n }\n\n /**\n *

    \n * The name of the cluster security group to which the operation was applied.\n *

    \n * \n * @param clusterSecurityGroupName\n * The name of the cluster security group to which the operation was applied.\n * @return Returns a reference to this object so that method calls can be chained together.\n */\n\n public ClusterSecurityGroup withClusterSecurityGroupName(String clusterSecurityGroupName) {\n setClusterSecurityGroupName(clusterSecurityGroupName);\n return this;\n }\n\n /**\n *

    \n * A description of the security group.\n *

    \n * \n * @param description\n * A description of the security group.\n */\n\n public void setDescription(String description) {\n this.description = description;\n }\n\n /**\n *

    \n * A description of the security group.\n *

    \n * \n * @return A description of the security group.\n */\n\n public String getDescription() {\n return this.description;\n }\n\n /**\n *

    \n * A description of the security group.\n *

    \n * \n * @param description\n * A description of the security group.\n * @return Returns a reference to this object so that method calls can be chained together.\n */\n\n public ClusterSecurityGroup withDescription(String description) {\n setDescription(description);\n return this;\n }\n\n /**\n *

    \n * A list of EC2 security groups that are permitted to access clusters associated with this cluster security group.\n *

    \n * \n * @return A list of EC2 security groups that are permitted to access clusters associated with this cluster security\n * group.\n */\n\n public java.util.List getEC2SecurityGroups() {\n if (eC2SecurityGroups == null) {\n eC2SecurityGroups = new com.amazonaws.internal.SdkInternalList();\n }\n return eC2SecurityGroups;\n }\n\n /**\n *

    \n * A list of EC2 security groups that are permitted to access clusters associated with this cluster security group.\n *

    \n * \n * @param eC2SecurityGroups\n * A list of EC2 security groups that are permitted to access clusters associated with this cluster security\n * group.\n */\n\n public void setEC2SecurityGroups(java.util.Collection eC2SecurityGroups) {\n if (eC2SecurityGroups == null) {\n this.eC2SecurityGroups = null;\n return;\n }\n\n this.eC2SecurityGroups = new com.amazonaws.internal.SdkInternalList(eC2SecurityGroups);\n }\n\n /**\n *

    \n * A list of EC2 security groups that are permitted to access clusters associated with this cluster security group.\n *

    \n *

    \n * NOTE: This method appends the values to the existing list (if any). Use\n * {@link #setEC2SecurityGroups(java.util.Collection)} or {@link #withEC2SecurityGroups(java.util.Collection)} if\n * you want to override the existing values.\n *

    \n * \n * @param eC2SecurityGroups\n * A list of EC2 security groups that are permitted to access clusters associated with this cluster security\n * group.\n * @return Returns a reference to this object so that method calls can be chained together.\n */\n\n public ClusterSecurityGroup withEC2SecurityGroups(EC2SecurityGroup... eC2SecurityGroups) {\n if (this.eC2SecurityGroups == null) {\n setEC2SecurityGroups(new com.amazonaws.internal.SdkInternalList(eC2SecurityGroups.length));\n }\n for (EC2SecurityGroup ele : eC2SecurityGroups) {\n this.eC2SecurityGroups.add(ele);\n }\n return this;\n }\n\n /**\n *

    \n * A list of EC2 security groups that are permitted to access clusters associated with this cluster security group.\n *

    \n * \n * @param eC2SecurityGroups\n * A list of EC2 security groups that are permitted to access clusters associated with this cluster security\n * group.\n * @return Returns a reference to this object so that method calls can be chained together.\n */\n\n public ClusterSecurityGroup withEC2SecurityGroups(java.util.Collection eC2SecurityGroups) {\n setEC2SecurityGroups(eC2SecurityGroups);\n return this;\n }\n\n /**\n *

    \n * A list of IP ranges (CIDR blocks) that are permitted to access clusters associated with this cluster security\n * group.\n *

    \n * \n * @return A list of IP ranges (CIDR blocks) that are permitted to access clusters associated with this cluster\n * security group.\n */\n\n public java.util.List getIPRanges() {\n if (iPRanges == null) {\n iPRanges = new com.amazonaws.internal.SdkInternalList();\n }\n return iPRanges;\n }\n\n /**\n *

    \n * A list of IP ranges (CIDR blocks) that are permitted to access clusters associated with this cluster security\n * group.\n *

    \n * \n * @param iPRanges\n * A list of IP ranges (CIDR blocks) that are permitted to access clusters associated with this cluster\n * security group.\n */\n\n public void setIPRanges(java.util.Collection iPRanges) {\n if (iPRanges == null) {\n this.iPRanges = null;\n return;\n }\n\n this.iPRanges = new com.amazonaws.internal.SdkInternalList(iPRanges);\n }\n\n /**\n *

    \n * A list of IP ranges (CIDR blocks) that are permitted to access clusters associated with this cluster security\n * group.\n *

    \n *

    \n * NOTE: This method appends the values to the existing list (if any). Use\n * {@link #setIPRanges(java.util.Collection)} or {@link #withIPRanges(java.util.Collection)} if you want to override\n * the existing values.\n *

    \n * \n * @param iPRanges\n * A list of IP ranges (CIDR blocks) that are permitted to access clusters associated with this cluster\n * security group.\n * @return Returns a reference to this object so that method calls can be chained together.\n */\n\n public ClusterSecurityGroup withIPRanges(IPRange... iPRanges) {\n if (this.iPRanges == null) {\n setIPRanges(new com.amazonaws.internal.SdkInternalList(iPRanges.length));\n }\n for (IPRange ele : iPRanges) {\n this.iPRanges.add(ele);\n }\n return this;\n }\n\n /**\n *

    \n * A list of IP ranges (CIDR blocks) that are permitted to access clusters associated with this cluster security\n * group.\n *

    \n * \n * @param iPRanges\n * A list of IP ranges (CIDR blocks) that are permitted to access clusters associated with this cluster\n * security group.\n * @return Returns a reference to this object so that method calls can be chained together.\n */", "answers": [" public ClusterSecurityGroup withIPRanges(java.util.Collection iPRanges) {"], "length": 1174, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "9717107a-9ac0-4892-9db3-a353daa761e0", "reasoning": "The Javadoc comment just ended describing the method that takes a Collection of IPRange and returns a reference for chaining. The next line should be the method signature for withIPRanges that accepts a java.util.Collection. Therefore the next line is the public method declaration.", "reasoning_model_answer": "public ClusterSecurityGroup withIPRanges(java.util.Collection iPRanges) {", "assistant_with_reasoning": "\nThe Javadoc comment just ended describing the method that takes a Collection of IPRange and returns a reference for chaining. The next line should be the method signature for withIPRanges that accepts a java.util.Collection. Therefore the next line is the public method declaration.\n\npublic ClusterSecurityGroup withIPRanges(java.util.Collection iPRanges) {", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.532, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 9807, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "public ClusterSecurityGroup withIPRanges(java.util.Collection iPRanges) {", "score": 0.98, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "# coding=utf-8\n# --------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for license information.\n# Code generated by Microsoft (R) AutoRest Code Generator.\n# Changes may cause incorrect behavior and will be lost if the code is regenerated.\n# --------------------------------------------------------------------------\nimport functools\nfrom typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union\nimport warnings\n\nfrom azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error\nfrom azure.core.paging import ItemPaged\nfrom azure.core.pipeline import PipelineResponse\nfrom azure.core.pipeline.transport import HttpResponse\nfrom azure.core.polling import LROPoller, NoPolling, PollingMethod\nfrom azure.core.rest import HttpRequest\nfrom azure.core.tracing.decorator import distributed_trace\nfrom azure.mgmt.core.exceptions import ARMErrorFormat\nfrom azure.mgmt.core.polling.arm_polling import ARMPolling\nfrom msrest import Serializer\n\nfrom .. import models as _models\nfrom .._vendor import _convert_request, _format_url_section\nT = TypeVar('T')\nJSONType = Any\nClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]\n\n_SERIALIZER = Serializer()\n_SERIALIZER.client_side_validation = False\n\ndef build_check_name_availability_request(\n resource_group_name: str,\n cluster_name: str,\n database_name: str,\n subscription_id: str,\n *,\n json: JSONType = None,\n content: Any = None,\n **kwargs: Any\n) -> HttpRequest:\n content_type = kwargs.pop('content_type', None) # type: Optional[str]\n\n api_version = \"2022-02-01\"\n accept = \"application/json\"\n # Construct URL\n url = kwargs.pop(\"template_url\", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Kusto/clusters/{clusterName}/databases/{databaseName}/checkPrincipalAssignmentNameAvailability')\n path_format_arguments = {\n \"resourceGroupName\": _SERIALIZER.url(\"resource_group_name\", resource_group_name, 'str'),\n \"clusterName\": _SERIALIZER.url(\"cluster_name\", cluster_name, 'str'),\n \"databaseName\": _SERIALIZER.url(\"database_name\", database_name, 'str'),\n \"subscriptionId\": _SERIALIZER.url(\"subscription_id\", subscription_id, 'str'),\n }\n\n url = _format_url_section(url, **path_format_arguments)\n\n # Construct parameters\n query_parameters = kwargs.pop(\"params\", {}) # type: Dict[str, Any]\n query_parameters['api-version'] = _SERIALIZER.query(\"api_version\", api_version, 'str')\n\n # Construct headers\n header_parameters = kwargs.pop(\"headers\", {}) # type: Dict[str, Any]\n if content_type is not None:\n header_parameters['Content-Type'] = _SERIALIZER.header(\"content_type\", content_type, 'str')\n header_parameters['Accept'] = _SERIALIZER.header(\"accept\", accept, 'str')\n\n return HttpRequest(\n method=\"POST\",\n url=url,\n params=query_parameters,\n headers=header_parameters,\n json=json,\n content=content,\n **kwargs\n )\n\n\ndef build_get_request(\n subscription_id: str,\n resource_group_name: str,\n cluster_name: str,\n database_name: str,\n principal_assignment_name: str,\n **kwargs: Any\n) -> HttpRequest:\n api_version = \"2022-02-01\"\n accept = \"application/json\"\n # Construct URL\n url = kwargs.pop(\"template_url\", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Kusto/clusters/{clusterName}/databases/{databaseName}/principalAssignments/{principalAssignmentName}')\n path_format_arguments = {\n \"subscriptionId\": _SERIALIZER.url(\"subscription_id\", subscription_id, 'str'),\n \"resourceGroupName\": _SERIALIZER.url(\"resource_group_name\", resource_group_name, 'str'),\n \"clusterName\": _SERIALIZER.url(\"cluster_name\", cluster_name, 'str'),\n \"databaseName\": _SERIALIZER.url(\"database_name\", database_name, 'str'),\n \"principalAssignmentName\": _SERIALIZER.url(\"principal_assignment_name\", principal_assignment_name, 'str'),\n }\n\n url = _format_url_section(url, **path_format_arguments)\n\n # Construct parameters\n query_parameters = kwargs.pop(\"params\", {}) # type: Dict[str, Any]\n query_parameters['api-version'] = _SERIALIZER.query(\"api_version\", api_version, 'str')\n\n # Construct headers\n header_parameters = kwargs.pop(\"headers\", {}) # type: Dict[str, Any]\n header_parameters['Accept'] = _SERIALIZER.header(\"accept\", accept, 'str')\n\n return HttpRequest(\n method=\"GET\",\n url=url,\n params=query_parameters,\n headers=header_parameters,\n **kwargs\n )\n\n\ndef build_create_or_update_request_initial(\n subscription_id: str,\n resource_group_name: str,\n cluster_name: str,\n database_name: str,\n principal_assignment_name: str,\n *,\n json: JSONType = None,\n content: Any = None,\n **kwargs: Any\n) -> HttpRequest:\n content_type = kwargs.pop('content_type', None) # type: Optional[str]\n\n api_version = \"2022-02-01\"\n accept = \"application/json\"\n # Construct URL\n url = kwargs.pop(\"template_url\", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Kusto/clusters/{clusterName}/databases/{databaseName}/principalAssignments/{principalAssignmentName}')\n path_format_arguments = {\n \"subscriptionId\": _SERIALIZER.url(\"subscription_id\", subscription_id, 'str'),\n \"resourceGroupName\": _SERIALIZER.url(\"resource_group_name\", resource_group_name, 'str'),\n \"clusterName\": _SERIALIZER.url(\"cluster_name\", cluster_name, 'str'),\n \"databaseName\": _SERIALIZER.url(\"database_name\", database_name, 'str'),\n \"principalAssignmentName\": _SERIALIZER.url(\"principal_assignment_name\", principal_assignment_name, 'str'),\n }\n\n url = _format_url_section(url, **path_format_arguments)\n\n # Construct parameters\n query_parameters = kwargs.pop(\"params\", {}) # type: Dict[str, Any]\n query_parameters['api-version'] = _SERIALIZER.query(\"api_version\", api_version, 'str')\n\n # Construct headers\n header_parameters = kwargs.pop(\"headers\", {}) # type: Dict[str, Any]\n if content_type is not None:\n header_parameters['Content-Type'] = _SERIALIZER.header(\"content_type\", content_type, 'str')\n header_parameters['Accept'] = _SERIALIZER.header(\"accept\", accept, 'str')\n\n return HttpRequest(\n method=\"PUT\",\n url=url,\n params=query_parameters,\n headers=header_parameters,\n json=json,\n content=content,\n **kwargs\n )\n\n\ndef build_delete_request_initial(\n subscription_id: str,\n resource_group_name: str,\n cluster_name: str,\n database_name: str,\n principal_assignment_name: str,\n **kwargs: Any\n) -> HttpRequest:\n api_version = \"2022-02-01\"\n accept = \"application/json\"\n # Construct URL\n url = kwargs.pop(\"template_url\", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Kusto/clusters/{clusterName}/databases/{databaseName}/principalAssignments/{principalAssignmentName}')\n path_format_arguments = {\n \"subscriptionId\": _SERIALIZER.url(\"subscription_id\", subscription_id, 'str'),\n \"resourceGroupName\": _SERIALIZER.url(\"resource_group_name\", resource_group_name, 'str'),\n \"clusterName\": _SERIALIZER.url(\"cluster_name\", cluster_name, 'str'),\n \"databaseName\": _SERIALIZER.url(\"database_name\", database_name, 'str'),\n \"principalAssignmentName\": _SERIALIZER.url(\"principal_assignment_name\", principal_assignment_name, 'str'),\n }\n\n url = _format_url_section(url, **path_format_arguments)\n\n # Construct parameters\n query_parameters = kwargs.pop(\"params\", {}) # type: Dict[str, Any]\n query_parameters['api-version'] = _SERIALIZER.query(\"api_version\", api_version, 'str')\n\n # Construct headers\n header_parameters = kwargs.pop(\"headers\", {}) # type: Dict[str, Any]\n header_parameters['Accept'] = _SERIALIZER.header(\"accept\", accept, 'str')\n\n return HttpRequest(\n method=\"DELETE\",\n url=url,\n params=query_parameters,\n headers=header_parameters,\n **kwargs\n )\n\n\ndef build_list_request(\n subscription_id: str,\n resource_group_name: str,\n cluster_name: str,\n database_name: str,\n **kwargs: Any\n) -> HttpRequest:\n api_version = \"2022-02-01\"\n accept = \"application/json\"\n # Construct URL\n url = kwargs.pop(\"template_url\", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Kusto/clusters/{clusterName}/databases/{databaseName}/principalAssignments')\n path_format_arguments = {\n \"subscriptionId\": _SERIALIZER.url(\"subscription_id\", subscription_id, 'str'),\n \"resourceGroupName\": _SERIALIZER.url(\"resource_group_name\", resource_group_name, 'str'),\n \"clusterName\": _SERIALIZER.url(\"cluster_name\", cluster_name, 'str'),\n \"databaseName\": _SERIALIZER.url(\"database_name\", database_name, 'str'),\n }\n\n url = _format_url_section(url, **path_format_arguments)\n\n # Construct parameters\n query_parameters = kwargs.pop(\"params\", {}) # type: Dict[str, Any]\n query_parameters['api-version'] = _SERIALIZER.query(\"api_version\", api_version, 'str')\n\n # Construct headers\n header_parameters = kwargs.pop(\"headers\", {}) # type: Dict[str, Any]\n header_parameters['Accept'] = _SERIALIZER.header(\"accept\", accept, 'str')\n\n return HttpRequest(\n method=\"GET\",\n url=url,\n params=query_parameters,\n headers=header_parameters,\n **kwargs\n )\n\nclass DatabasePrincipalAssignmentsOperations(object):\n \"\"\"DatabasePrincipalAssignmentsOperations operations.\n\n You should not instantiate this class directly. Instead, you should create a Client instance that\n instantiates it for you and attaches it as an attribute.\n\n :ivar models: Alias to model classes used in this operation group.\n :type models: ~kusto_management_client.models\n :param client: Client for service requests.\n :param config: Configuration of service client.\n :param serializer: An object model serializer.\n :param deserializer: An object model deserializer.\n \"\"\"\n\n models = _models\n\n def __init__(self, client, config, serializer, deserializer):\n self._client = client\n self._serialize = serializer\n self._deserialize = deserializer\n self._config = config\n\n @distributed_trace\n def check_name_availability(\n self,\n resource_group_name: str,\n cluster_name: str,\n database_name: str,\n principal_assignment_name: \"_models.DatabasePrincipalAssignmentCheckNameRequest\",\n **kwargs: Any\n ) -> \"_models.CheckNameResult\":\n \"\"\"Checks that the database principal assignment is valid and is not already in use.\n\n :param resource_group_name: The name of the resource group containing the Kusto cluster.\n :type resource_group_name: str\n :param cluster_name: The name of the Kusto cluster.\n :type cluster_name: str\n :param database_name: The name of the database in the Kusto cluster.\n :type database_name: str\n :param principal_assignment_name: The name of the resource.\n :type principal_assignment_name:\n ~kusto_management_client.models.DatabasePrincipalAssignmentCheckNameRequest\n :keyword callable cls: A custom type or function that will be passed the direct response\n :return: CheckNameResult, or the result of cls(response)\n :rtype: ~kusto_management_client.models.CheckNameResult\n :raises: ~azure.core.exceptions.HttpResponseError\n \"\"\"\n cls = kwargs.pop('cls', None) # type: ClsType[\"_models.CheckNameResult\"]\n error_map = {\n 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError\n }\n error_map.update(kwargs.pop('error_map', {}))\n\n content_type = kwargs.pop('content_type', \"application/json\") # type: Optional[str]\n\n _json = self._serialize.body(principal_assignment_name, 'DatabasePrincipalAssignmentCheckNameRequest')\n\n request = build_check_name_availability_request(\n resource_group_name=resource_group_name,\n cluster_name=cluster_name,\n database_name=database_name,\n subscription_id=self._config.subscription_id,\n content_type=content_type,\n json=_json,\n template_url=self.check_name_availability.metadata['url'],\n )\n request = _convert_request(request)\n request.url = self._client.format_url(request.url)\n\n pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)\n response = pipeline_response.http_response\n\n if response.status_code not in [200]:\n map_error(status_code=response.status_code, response=response, error_map=error_map)\n raise HttpResponseError(response=response, error_format=ARMErrorFormat)\n\n deserialized = self._deserialize('CheckNameResult', pipeline_response)\n\n if cls:\n return cls(pipeline_response, deserialized, {})\n\n return deserialized\n\n check_name_availability.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Kusto/clusters/{clusterName}/databases/{databaseName}/checkPrincipalAssignmentNameAvailability'} # type: ignore\n\n\n @distributed_trace\n def get(\n self,\n resource_group_name: str,\n cluster_name: str,\n database_name: str,\n principal_assignment_name: str,\n **kwargs: Any\n ) -> \"_models.DatabasePrincipalAssignment\":\n \"\"\"Gets a Kusto cluster database principalAssignment.\n\n :param resource_group_name: The name of the resource group containing the Kusto cluster.\n :type resource_group_name: str\n :param cluster_name: The name of the Kusto cluster.\n :type cluster_name: str\n :param database_name: The name of the database in the Kusto cluster.\n :type database_name: str\n :param principal_assignment_name: The name of the Kusto principalAssignment.\n :type principal_assignment_name: str\n :keyword callable cls: A custom type or function that will be passed the direct response\n :return: DatabasePrincipalAssignment, or the result of cls(response)\n :rtype: ~kusto_management_client.models.DatabasePrincipalAssignment\n :raises: ~azure.core.exceptions.HttpResponseError\n \"\"\"\n cls = kwargs.pop('cls', None) # type: ClsType[\"_models.DatabasePrincipalAssignment\"]\n error_map = {\n 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError\n }\n error_map.update(kwargs.pop('error_map', {}))\n\n \n request = build_get_request(\n subscription_id=self._config.subscription_id,\n resource_group_name=resource_group_name,\n cluster_name=cluster_name,\n database_name=database_name,\n principal_assignment_name=principal_assignment_name,\n template_url=self.get.metadata['url'],\n )\n request = _convert_request(request)\n request.url = self._client.format_url(request.url)\n\n pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)\n response = pipeline_response.http_response\n\n if response.status_code not in [200]:\n map_error(status_code=response.status_code, response=response, error_map=error_map)\n raise HttpResponseError(response=response, error_format=ARMErrorFormat)\n\n deserialized = self._deserialize('DatabasePrincipalAssignment', pipeline_response)\n\n if cls:\n return cls(pipeline_response, deserialized, {})\n\n return deserialized\n\n get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Kusto/clusters/{clusterName}/databases/{databaseName}/principalAssignments/{principalAssignmentName}'} # type: ignore\n\n\n def _create_or_update_initial(\n self,\n resource_group_name: str,\n cluster_name: str,\n database_name: str,\n principal_assignment_name: str,\n parameters: \"_models.DatabasePrincipalAssignment\",\n **kwargs: Any\n ) -> \"_models.DatabasePrincipalAssignment\":\n cls = kwargs.pop('cls', None) # type: ClsType[\"_models.DatabasePrincipalAssignment\"]\n error_map = {\n 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError\n }\n error_map.update(kwargs.pop('error_map', {}))\n\n content_type = kwargs.pop('content_type', \"application/json\") # type: Optional[str]\n", "answers": [" _json = self._serialize.body(parameters, 'DatabasePrincipalAssignment')"], "length": 1184, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "54477837-a206-4bf7-a6bc-0fe1f983b9cd", "reasoning": "Inside the _create_or_update_initial method, after extracting content_type the next logical step is to serialize the provided parameters into JSON for the request body, following the pattern used in other methods (e.g., check_name_availability). Therefore the next line should create the _json variable by calling self._serialize.body with the parameters and the model name.", "reasoning_model_answer": "_json = self._serialize.body(parameters, 'DatabasePrincipalAssignment')", "assistant_with_reasoning": "\nInside the _create_or_update_initial method, after extracting content_type the next logical step is to serialize the provided parameters into JSON for the request body, following the pattern used in other methods (e.g., check_name_availability). Therefore the next line should create the _json variable by calling self._serialize.body with the parameters and the model name.\n\n_json = self._serialize.body(parameters, 'DatabasePrincipalAssignment')", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 5.646, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 17003, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "_json = self._serialize.body(parameters, 'DatabasePrincipalAssignment')", "score": 0.95, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "# coding=utf-8\n# --------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for license information.\n# Code generated by Microsoft (R) AutoRest Code Generator.\n# Changes may cause incorrect behavior and will be lost if the code is regenerated.\n# --------------------------------------------------------------------------\nimport functools\nfrom typing import Any, Callable, Dict, Generic, Optional, TypeVar, Union\nimport warnings\n\nfrom azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error\nfrom azure.core.pipeline import PipelineResponse\nfrom azure.core.pipeline.transport import HttpResponse\nfrom azure.core.rest import HttpRequest\nfrom azure.core.tracing.decorator import distributed_trace\nfrom azure.mgmt.core.exceptions import ARMErrorFormat\nfrom msrest import Serializer\n\nfrom .. import models as _models\nfrom .._vendor import _convert_request, _format_url_section\nT = TypeVar('T')\nJSONType = Any\nClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]\n\n_SERIALIZER = Serializer()\n_SERIALIZER.client_side_validation = False\n\ndef build_list_by_iot_hub_request(\n subscription_id: str,\n resource_group_name: str,\n resource_name: str,\n **kwargs: Any\n) -> HttpRequest:\n api_version = \"2019-11-04\"\n accept = \"application/json\"\n # Construct URL\n url = kwargs.pop(\"template_url\", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Devices/IotHubs/{resourceName}/certificates')\n path_format_arguments = {\n \"subscriptionId\": _SERIALIZER.url(\"subscription_id\", subscription_id, 'str'),\n \"resourceGroupName\": _SERIALIZER.url(\"resource_group_name\", resource_group_name, 'str'),\n \"resourceName\": _SERIALIZER.url(\"resource_name\", resource_name, 'str'),\n }\n\n url = _format_url_section(url, **path_format_arguments)\n\n # Construct parameters\n query_parameters = kwargs.pop(\"params\", {}) # type: Dict[str, Any]\n query_parameters['api-version'] = _SERIALIZER.query(\"api_version\", api_version, 'str')\n\n # Construct headers\n header_parameters = kwargs.pop(\"headers\", {}) # type: Dict[str, Any]\n header_parameters['Accept'] = _SERIALIZER.header(\"accept\", accept, 'str')\n\n return HttpRequest(\n method=\"GET\",\n url=url,\n params=query_parameters,\n headers=header_parameters,\n **kwargs\n )\n\n\ndef build_get_request(\n subscription_id: str,\n resource_group_name: str,\n resource_name: str,\n certificate_name: str,\n **kwargs: Any\n) -> HttpRequest:\n api_version = \"2019-11-04\"\n accept = \"application/json\"\n # Construct URL\n url = kwargs.pop(\"template_url\", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Devices/IotHubs/{resourceName}/certificates/{certificateName}')\n path_format_arguments = {\n \"subscriptionId\": _SERIALIZER.url(\"subscription_id\", subscription_id, 'str'),\n \"resourceGroupName\": _SERIALIZER.url(\"resource_group_name\", resource_group_name, 'str'),\n \"resourceName\": _SERIALIZER.url(\"resource_name\", resource_name, 'str'),\n \"certificateName\": _SERIALIZER.url(\"certificate_name\", certificate_name, 'str', pattern=r'^[A-Za-z0-9-._]{1,64}$'),\n }\n\n url = _format_url_section(url, **path_format_arguments)\n\n # Construct parameters\n query_parameters = kwargs.pop(\"params\", {}) # type: Dict[str, Any]\n query_parameters['api-version'] = _SERIALIZER.query(\"api_version\", api_version, 'str')\n\n # Construct headers\n header_parameters = kwargs.pop(\"headers\", {}) # type: Dict[str, Any]\n header_parameters['Accept'] = _SERIALIZER.header(\"accept\", accept, 'str')\n\n return HttpRequest(\n method=\"GET\",\n url=url,\n params=query_parameters,\n headers=header_parameters,\n **kwargs\n )\n\n\ndef build_create_or_update_request(\n subscription_id: str,\n resource_group_name: str,\n resource_name: str,\n certificate_name: str,\n *,\n json: JSONType = None,\n content: Any = None,\n if_match: Optional[str] = None,\n **kwargs: Any\n) -> HttpRequest:\n content_type = kwargs.pop('content_type', None) # type: Optional[str]\n\n api_version = \"2019-11-04\"\n accept = \"application/json\"\n # Construct URL\n url = kwargs.pop(\"template_url\", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Devices/IotHubs/{resourceName}/certificates/{certificateName}')\n path_format_arguments = {\n \"subscriptionId\": _SERIALIZER.url(\"subscription_id\", subscription_id, 'str'),\n \"resourceGroupName\": _SERIALIZER.url(\"resource_group_name\", resource_group_name, 'str'),\n \"resourceName\": _SERIALIZER.url(\"resource_name\", resource_name, 'str'),\n \"certificateName\": _SERIALIZER.url(\"certificate_name\", certificate_name, 'str', pattern=r'^[A-Za-z0-9-._]{1,64}$'),\n }\n\n url = _format_url_section(url, **path_format_arguments)\n\n # Construct parameters\n query_parameters = kwargs.pop(\"params\", {}) # type: Dict[str, Any]\n query_parameters['api-version'] = _SERIALIZER.query(\"api_version\", api_version, 'str')\n\n # Construct headers\n header_parameters = kwargs.pop(\"headers\", {}) # type: Dict[str, Any]\n if if_match is not None:\n header_parameters['If-Match'] = _SERIALIZER.header(\"if_match\", if_match, 'str')\n if content_type is not None:\n header_parameters['Content-Type'] = _SERIALIZER.header(\"content_type\", content_type, 'str')\n header_parameters['Accept'] = _SERIALIZER.header(\"accept\", accept, 'str')\n\n return HttpRequest(\n method=\"PUT\",\n url=url,\n params=query_parameters,\n headers=header_parameters,\n json=json,\n content=content,\n **kwargs\n )\n\n\ndef build_delete_request(\n subscription_id: str,\n resource_group_name: str,\n resource_name: str,\n certificate_name: str,\n *,\n if_match: str,\n **kwargs: Any\n) -> HttpRequest:\n api_version = \"2019-11-04\"\n accept = \"application/json\"\n # Construct URL\n url = kwargs.pop(\"template_url\", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Devices/IotHubs/{resourceName}/certificates/{certificateName}')\n path_format_arguments = {\n \"subscriptionId\": _SERIALIZER.url(\"subscription_id\", subscription_id, 'str'),\n \"resourceGroupName\": _SERIALIZER.url(\"resource_group_name\", resource_group_name, 'str'),\n \"resourceName\": _SERIALIZER.url(\"resource_name\", resource_name, 'str'),\n \"certificateName\": _SERIALIZER.url(\"certificate_name\", certificate_name, 'str', pattern=r'^[A-Za-z0-9-._]{1,64}$'),\n }\n\n url = _format_url_section(url, **path_format_arguments)\n\n # Construct parameters\n query_parameters = kwargs.pop(\"params\", {}) # type: Dict[str, Any]\n query_parameters['api-version'] = _SERIALIZER.query(\"api_version\", api_version, 'str')\n\n # Construct headers\n header_parameters = kwargs.pop(\"headers\", {}) # type: Dict[str, Any]\n header_parameters['If-Match'] = _SERIALIZER.header(\"if_match\", if_match, 'str')\n header_parameters['Accept'] = _SERIALIZER.header(\"accept\", accept, 'str')\n\n return HttpRequest(\n method=\"DELETE\",\n url=url,\n params=query_parameters,\n headers=header_parameters,\n **kwargs\n )\n\n\ndef build_generate_verification_code_request(\n subscription_id: str,\n resource_group_name: str,\n resource_name: str,\n certificate_name: str,\n *,\n if_match: str,\n **kwargs: Any\n) -> HttpRequest:\n api_version = \"2019-11-04\"\n accept = \"application/json\"\n # Construct URL\n url = kwargs.pop(\"template_url\", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Devices/IotHubs/{resourceName}/certificates/{certificateName}/generateVerificationCode')\n path_format_arguments = {\n \"subscriptionId\": _SERIALIZER.url(\"subscription_id\", subscription_id, 'str'),\n \"resourceGroupName\": _SERIALIZER.url(\"resource_group_name\", resource_group_name, 'str'),\n \"resourceName\": _SERIALIZER.url(\"resource_name\", resource_name, 'str'),\n \"certificateName\": _SERIALIZER.url(\"certificate_name\", certificate_name, 'str', pattern=r'^[A-Za-z0-9-._]{1,64}$'),\n }\n\n url = _format_url_section(url, **path_format_arguments)\n\n # Construct parameters\n query_parameters = kwargs.pop(\"params\", {}) # type: Dict[str, Any]\n query_parameters['api-version'] = _SERIALIZER.query(\"api_version\", api_version, 'str')\n\n # Construct headers\n header_parameters = kwargs.pop(\"headers\", {}) # type: Dict[str, Any]\n header_parameters['If-Match'] = _SERIALIZER.header(\"if_match\", if_match, 'str')\n header_parameters['Accept'] = _SERIALIZER.header(\"accept\", accept, 'str')\n\n return HttpRequest(\n method=\"POST\",\n url=url,\n params=query_parameters,\n headers=header_parameters,\n **kwargs\n )\n\n\ndef build_verify_request(\n subscription_id: str,\n resource_group_name: str,\n resource_name: str,\n certificate_name: str,\n *,\n if_match: str,\n json: JSONType = None,\n content: Any = None,\n **kwargs: Any\n) -> HttpRequest:\n content_type = kwargs.pop('content_type', None) # type: Optional[str]\n\n api_version = \"2019-11-04\"\n accept = \"application/json\"\n # Construct URL\n url = kwargs.pop(\"template_url\", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Devices/IotHubs/{resourceName}/certificates/{certificateName}/verify')\n path_format_arguments = {\n \"subscriptionId\": _SERIALIZER.url(\"subscription_id\", subscription_id, 'str'),\n \"resourceGroupName\": _SERIALIZER.url(\"resource_group_name\", resource_group_name, 'str'),\n \"resourceName\": _SERIALIZER.url(\"resource_name\", resource_name, 'str'),\n \"certificateName\": _SERIALIZER.url(\"certificate_name\", certificate_name, 'str', pattern=r'^[A-Za-z0-9-._]{1,64}$'),\n }\n\n url = _format_url_section(url, **path_format_arguments)\n\n # Construct parameters\n query_parameters = kwargs.pop(\"params\", {}) # type: Dict[str, Any]\n query_parameters['api-version'] = _SERIALIZER.query(\"api_version\", api_version, 'str')\n\n # Construct headers\n header_parameters = kwargs.pop(\"headers\", {}) # type: Dict[str, Any]\n header_parameters['If-Match'] = _SERIALIZER.header(\"if_match\", if_match, 'str')\n if content_type is not None:\n header_parameters['Content-Type'] = _SERIALIZER.header(\"content_type\", content_type, 'str')\n header_parameters['Accept'] = _SERIALIZER.header(\"accept\", accept, 'str')\n\n return HttpRequest(\n method=\"POST\",\n url=url,\n params=query_parameters,\n headers=header_parameters,\n json=json,\n content=content,\n **kwargs\n )\n\nclass CertificatesOperations(object):\n \"\"\"CertificatesOperations operations.\n\n You should not instantiate this class directly. Instead, you should create a Client instance that\n instantiates it for you and attaches it as an attribute.\n\n :ivar models: Alias to model classes used in this operation group.\n :type models: ~azure.mgmt.iothub.v2019_11_04.models\n :param client: Client for service requests.\n :param config: Configuration of service client.\n :param serializer: An object model serializer.\n :param deserializer: An object model deserializer.\n \"\"\"\n\n models = _models\n\n def __init__(self, client, config, serializer, deserializer):\n self._client = client\n self._serialize = serializer\n self._deserialize = deserializer\n self._config = config\n\n @distributed_trace\n def list_by_iot_hub(\n self,\n resource_group_name: str,\n resource_name: str,\n **kwargs: Any\n ) -> \"_models.CertificateListDescription\":\n \"\"\"Get the certificate list.\n\n Returns the list of certificates.\n\n :param resource_group_name: The name of the resource group that contains the IoT hub.\n :type resource_group_name: str\n :param resource_name: The name of the IoT hub.\n :type resource_name: str\n :keyword callable cls: A custom type or function that will be passed the direct response\n :return: CertificateListDescription, or the result of cls(response)\n :rtype: ~azure.mgmt.iothub.v2019_11_04.models.CertificateListDescription\n :raises: ~azure.core.exceptions.HttpResponseError\n \"\"\"\n cls = kwargs.pop('cls', None) # type: ClsType[\"_models.CertificateListDescription\"]\n error_map = {\n 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError\n }\n error_map.update(kwargs.pop('error_map', {}))\n\n \n request = build_list_by_iot_hub_request(\n subscription_id=self._config.subscription_id,\n resource_group_name=resource_group_name,\n resource_name=resource_name,\n template_url=self.list_by_iot_hub.metadata['url'],\n )\n request = _convert_request(request)\n request.url = self._client.format_url(request.url)\n\n pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)\n response = pipeline_response.http_response\n\n if response.status_code not in [200]:\n map_error(status_code=response.status_code, response=response, error_map=error_map)\n error = self._deserialize.failsafe_deserialize(_models.ErrorDetails, pipeline_response)\n raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)\n\n deserialized = self._deserialize('CertificateListDescription', pipeline_response)\n\n if cls:\n return cls(pipeline_response, deserialized, {})\n\n return deserialized\n\n list_by_iot_hub.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Devices/IotHubs/{resourceName}/certificates'} # type: ignore\n", "answers": [" @distributed_trace"], "length": 1020, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "baa0a38c-692b-4399-8657-727f7c77004e", "reasoning": "The class defines a method list_by_iot_hub followed by its metadata assignment. In Azure SDK generated code, the next piece is usually the next operation method, which starts with the @distributed_trace decorator. Therefore the next line after the metadata assignment is the decorator for the following method.", "reasoning_model_answer": "@distributed_trace", "assistant_with_reasoning": "\nThe class defines a method list_by_iot_hub followed by its metadata assignment. In Azure SDK generated code, the next piece is usually the next operation method, which starts with the @distributed_trace decorator. Therefore the next line after the metadata assignment is the decorator for the following method.\n\n@distributed_trace", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 5.042, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 14253, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "@distributed_trace", "score": 0.9, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "#!/usr/bin/python\n# -*- coding: utf-8 -*-\n#\n# Copyright: (c) 2018, F5 Networks Inc.\n# GNU General Public License v3.0 (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)\n\nfrom __future__ import absolute_import, division, print_function\n__metaclass__ = type\n\n\nANSIBLE_METADATA = {'metadata_version': '1.1',\n 'status': ['preview'],\n 'supported_by': 'certified'}\n\nDOCUMENTATION = r'''\n---\nmodule: bigip_monitor_gateway_icmp\nshort_description: Manages F5 BIG-IP LTM gateway ICMP monitors\ndescription:\n - Manages gateway ICMP monitors on a BIG-IP.\nversion_added: 2.8\noptions:\n name:\n description:\n - Monitor name.\n type: str\n required: True\n parent:\n description:\n - The parent template of this monitor template. Once this value has\n been set, it cannot be changed. By default, this value is the\n C(gateway_icmp) parent on the C(Common) partition.\n type: str\n default: /Common/gateway_icmp\n description:\n description:\n - The description of the monitor.\n type: str\n ip:\n description:\n - IP address part of the IP/port definition. If this parameter is not\n provided when creating a new monitor, then the default value will be\n '*'.\n type: str\n port:\n description:\n - Port address part of the IP/port definition. If this parameter is not\n provided when creating a new monitor, then the default value will be\n '*'. Note that if specifying an IP address, a value between 1 and 65535\n must be specified.\n type: str\n interval:\n description:\n - Specifies, in seconds, the frequency at which the system issues the\n monitor check when either the resource is down or the status of the\n resource is unknown.\n type: int\n timeout:\n description:\n - Specifies the number of seconds the target has in which to respond to\n the monitor request.\n - If the target responds within the set time period, it is considered 'up'.\n If the target does not respond within the set time period, it is considered\n 'down'. When this value is set to 0 (zero), the system uses the interval\n from the parent monitor.\n - Note that C(timeout) and C(time_until_up) combine to control when a\n resource is set to up.\n type: int\n time_until_up:\n description:\n - Specifies the number of seconds to wait after a resource first responds\n correctly to the monitor before setting the resource to 'up'.\n - During the interval, all responses from the resource must be correct.\n - When the interval expires, the resource is marked 'up'.\n - A value of 0, means that the resource is marked up immediately upon\n receipt of the first correct response.\n type: int\n up_interval:\n description:\n - Specifies the interval for the system to use to perform the health check\n when a resource is up.\n - When C(0), specifies that the system uses the interval specified in\n C(interval) to check the health of the resource.\n - When any other number, enables specification of a different interval to\n use when checking the health of a resource that is up.\n type: int\n manual_resume:\n description:\n - Specifies whether the system automatically changes the status of a resource\n to B(enabled) at the next successful monitor check.\n - If you set this option to C(yes), you must manually re-enable the resource\n before the system can use it for load balancing connections.\n - When C(yes), specifies that you must manually re-enable the resource after an\n unsuccessful monitor check.\n - When C(no), specifies that the system automatically changes the status of a\n resource to B(enabled) at the next successful monitor check.\n type: bool\n adaptive:\n description:\n - Specifies whether adaptive response time monitoring is enabled for this monitor.\n - When C(yes), the monitor determines the state of a service based on how divergent\n from the mean latency a monitor probe for that service is allowed to be.\n Also, values for the C(allowed_divergence), C(adaptive_limit), and\n and C(sampling_timespan) will be enforced.\n - When C(disabled), the monitor determines the state of a service based on the\n C(interval), C(up_interval), C(time_until_up), and C(timeout) monitor settings.\n type: bool\n allowed_divergence_type:\n description:\n - When specifying a new monitor, if C(adaptive) is C(yes), the default is\n C(relative)\n - When C(absolute), the number of milliseconds the latency of a monitor probe\n can exceed the mean latency of a monitor probe for the service being probed.\n In typical cases, if the monitor detects three probes in a row that miss the\n latency value you set, the pool member or node is marked down.\n - When C(relative), the percentage of deviation the latency of a monitor probe\n can exceed the mean latency of a monitor probe for the service being probed.\n type: str\n choices:\n - relative\n - absolute\n allowed_divergence_value:\n description:\n - When specifying a new monitor, if C(adaptive) is C(yes), and C(type) is\n C(relative), the default is C(25) percent.\n type: int\n adaptive_limit:\n description:\n - Specifies the absolute number of milliseconds that may not be exceeded by a monitor\n probe, regardless of C(allowed_divergence) setting, for a probe to be\n considered successful.\n - This value applies regardless of the value of the C(allowed_divergence) setting.\n - While this value can be configured when C(adaptive) is C(no), it will not take\n effect on the system until C(adaptive) is C(yes).\n type: int\n sampling_timespan:\n description:\n - Specifies the length, in seconds, of the probe history window that the system\n uses to calculate the mean latency and standard deviation of a monitor probe.\n - While this value can be configured when C(adaptive) is C(no), it will not take\n effect on the system until C(adaptive) is C(yes).\n type: int\n transparent:\n description:\n - Specifies whether the monitor operates in transparent mode.\n - A monitor in transparent mode directs traffic through the associated pool members\n or nodes (usually a router or firewall) to the aliased destination (that is, it\n probes the C(ip)-C(port) combination specified in the monitor).\n - If the monitor cannot successfully reach the aliased destination, the pool member\n or node through which the monitor traffic was sent is marked down.\n - When creating a new monitor, if this parameter is not provided, then the default\n value will be whatever is provided by the C(parent).\n type: bool\n partition:\n description:\n - Device partition to manage resources on.\n type: str\n default: Common\n state:\n description:\n - When C(present), ensures that the monitor exists.\n - When C(absent), ensures the monitor is removed.\n type: str\n choices:\n - present\n - absent\n default: present\nextends_documentation_fragment: f5\nauthor:\n - Tim Rupp (@caphrim007)\n'''\n\nEXAMPLES = r'''\n- name: Create a monitor\n bigip_monitor_gateway_icmp:\n name: gw1\n adaptive: no\n interval: 1\n time_until_up: 0\n timeout: 3\n provider:\n password: secret\n server: lb.mydomain.com\n user: admin\n delegate_to: localhost\n'''\n", "answers": ["RETURN = r'''"], "length": 1038, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "cc3b90c0-65e7-48ed-b4d9-411f5fa1072f", "reasoning": "The code defines module metadata, documentation, and examples for an Ansible module. After the EXAMPLES block, the next logical section is the RETURN documentation that describes module output. In similar F5 Ansible modules, this follows the EXAMPLES block as a string assignment using r''' syntax. Therefore, the next line should start the RETURN definition.", "reasoning_model_answer": "RETURN = r'''", "assistant_with_reasoning": "\nThe code defines module metadata, documentation, and examples for an Ansible module. After the EXAMPLES block, the next logical section is the RETURN documentation that describes module output. In similar F5 Ansible modules, this follows the EXAMPLES block as a string assignment using r''' syntax. Therefore, the next line should start the RETURN definition.\n\nRETURN = r'''", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 1.819, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 7635, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "RETURN = r'''", "score": 1.0, "is_full_score": true, "is_nonzero_score": true}} {"input": "", "context": "/*\n\tcursus - Race series management program\n\tCopyright 2014 Simon Arlott\n\n\tThis program is free software: you can redistribute it and/or modify\n\tit under the terms of the GNU Affero General Public License as published by\n\tthe Free Software Foundation, either version 3 of the License, or\n\t(at your option) any later version.\n\n\tThis program is distributed in the hope that it will be useful,\n\tbut WITHOUT ANY WARRANTY; without even the implied warranty of\n\tMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\tGNU Affero General Public License for more details.\n\n\tYou should have received a copy of the GNU Affero General Public License\n\talong with this program. If not, see .\n */\npackage org.spka.cursus.test.cc_2008;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport uk.uuid.cursus.db.DatabaseSession;\nimport uk.uuid.cursus.db.data.Event;\nimport uk.uuid.cursus.db.data.Race;\nimport uk.uuid.cursus.db.data.Series;\nimport uk.uuid.cursus.scoring.data.Scores;\nimport uk.uuid.cursus.test.util.OverallAssertUtil;\nimport uk.uuid.cursus.test.util.RaceAssertUtil;\n\nimport com.google.common.base.Predicates;\n\n/**\n * Scores at the end of event 1\n */\npublic class Series2008Event1Scores extends CCSeries2008 {\n\tpublic Series2008Event1Scores() {\n\t\tsuper(false);\n\t}\n\n\t@Override\n\t@Before\n\tpublic void createDatabase() throws Exception {\n\t\tsuper.createDatabase();\n\t\tcreateEvent1Races();\n\t}\n\n\t@Test\n\tpublic void checkSeries() throws Exception {\n\t\tdb.startSession();\n\t\ttry {\n\t\t\tDatabaseSession.begin();\n\n\t\t\tSeries series = seriesDAO.find(SERIES_NAME);\n\t\t\tEvent event1 = eventDAO.find(series, EVENT1_NAME);\n\t\t\tScores scores = scorer.scoreSeries(series, getSeriesResultsPilots(series, event1), Predicates.in(getSeriesResultsPilots(series, event1)));\n\t\t\tcheckSeriesAtEvent1(scores);\n\n\t\t\tDatabaseSession.commit();\n\t\t} finally {\n\t\t\tdb.endSession();\n\t\t}\n\t}\n\n\t@Test\n\tpublic final void checkSeriesAtEvent1() throws Exception {\n\t\tdb.startSession();\n\t\ttry {\n\t\t\tDatabaseSession.begin();\n\n\t\t\tSeries series = seriesDAO.find(SERIES_NAME);\n\t\t\tEvent event1 = eventDAO.find(series, EVENT1_NAME);\n\n\t\t\tList races = new ArrayList();\n\t\t\traces.addAll(event1.getRaces());\n\n\t\t\tScores scores = scorer.scoreRaces(races, getSeriesResultsPilots(series, event1), getSeriesResultsEvents(series, event1),\n\t\t\t\t\tPredicates.in(getSeriesResultsPilots(series, event1)));\n\t\t\tcheckSeriesAtEvent1(scores);\n\n\t\t\tDatabaseSession.commit();\n\t\t} finally {\n\t\t\tdb.endSession();\n\t\t}\n\t}\n\n\tprivate void checkSeriesAtEvent1(Scores scores) throws Exception {\n\t\tSeries series = seriesDAO.find(SERIES_NAME);\n\t\tEvent event1 = eventDAO.find(series, EVENT1_NAME);\n\t\tRace race1 = raceDAO.find(event1, RACE1_NAME);\n\t\tRace race2 = raceDAO.find(event1, RACE2_NAME);\n\t\tRace race3 = raceDAO.find(event1, RACE3_NAME);\n\t\tRace race4 = raceDAO.find(event1, RACE4_NAME);\n\n\t\tAssert.assertEquals(SERIES_FLEET_AT_EVENT1, scores.getPilots().size());\n\n\t\tRaceAssertUtil race1AssertUtil = new RaceAssertUtil(scores, race1);\n\t\trace1AssertUtil.assertPilot(ir027, 6, 0, false, 0, 1);\n\t\trace1AssertUtil.assertPilot(sco023, 0, 0, true, 0, 2);\n\t\trace1AssertUtil.assertPilot(sco200, 6, 0, false, 2, 3);\n\t\trace1AssertUtil.assertPilot(sco135, 0, 0, true, 2, 4);\n\t\trace1AssertUtil.assertPilot(sco019, 6, 0, false, 3, 5);\n\t\trace1AssertUtil.assertPilot(sco159, 5, 0, false, 4, 6);\n\t\trace1AssertUtil.assertPilot(ir073, 4, 0, false, 5, 7);\n\t\trace1AssertUtil.assertPilot(sco081, 4, 0, false, 6, 8);\n\t\trace1AssertUtil.assertPilot(sco179, 4, 0, false, 7, 9);\n\t\trace1AssertUtil.assertPilot(sco154, 3, 0, false, 8, 10);\n\t\trace1AssertUtil.assertPilot(ir052, 3, 0, false, 9, 11);\n\t\trace1AssertUtil.assertPilot(sco071, 3, 0, false, 10, 12);\n\t\trace1AssertUtil.assertPilot(ir085, 1, 0, false, 11, 13);\n\t\trace1AssertUtil.assertPilot(sco033, 0, 0, false, 17, 14);\n\t\trace1AssertUtil.assertPilot(sco060, 0, 0, false, 17, 14);\n\t\trace1AssertUtil.assertPilot(sco136, 0, 0, false, 17, 14);\n\t\trace1AssertUtil.assertPilot(sco158, 0, 0, false, 17, 14);\n\t\trace1AssertUtil.assertPilot(sco197, 0, 0, false, 17, 14);\n\t\trace1AssertUtil.assertDone(2);\n\n\t\tRaceAssertUtil race2AssertUtil = new RaceAssertUtil(scores, race2);\n\t\trace2AssertUtil.assertPilot(sco200, 8, 0, false, 0, 1);\n\t\trace2AssertUtil.assertPilot(sco023, 0, 0, true, 0, 2);\n\t\trace2AssertUtil.assertPilot(sco135, 8, 0, false, 2, 3);\n\t\trace2AssertUtil.assertPilot(ir027, 8, 0, false, 3, 4);\n\t\trace2AssertUtil.assertPilot(ir085, 8, 0, false, 4, 5);\n\t\trace2AssertUtil.assertPilot(sco019, 0, 0, true, 4, 6);\n\t\trace2AssertUtil.assertPilot(sco136, 7, 0, false, 5, 7);\n\t\trace2AssertUtil.assertPilot(sco154, 0, 0, true, 5, 8);\n\t\trace2AssertUtil.assertPilot(sco179, 7, 0, false, 6, 9);\n\t\trace2AssertUtil.assertPilot(sco159, 0, 0, true, 6, 10);\n\t\trace2AssertUtil.assertPilot(sco081, 6, 0, false, 7, 11);\n\t\trace2AssertUtil.assertPilot(sco060, 6, 0, false, 8, 12);\n\t\trace2AssertUtil.assertPilot(ir052, 6, 0, false, 9, 13);\n\t\trace2AssertUtil.assertPilot(sco197, 6, 0, false, 10, 14);\n\t\trace2AssertUtil.assertPilot(sco033, 2, 0, false, 11, 15);\n\t\trace2AssertUtil.assertPilot(ir073, 2, 0, false, 12, 16);\n\t\trace2AssertUtil.assertPilot(sco071, 0, 0, false, 18, 17);\n\t\trace2AssertUtil.assertPilot(sco158, 0, 0, false, 18, 17);\n\t\trace2AssertUtil.assertDone(4);\n\n\t\tRaceAssertUtil race3AssertUtil = new RaceAssertUtil(scores, race3);\n\t\trace3AssertUtil.assertPilot(sco023, 9, 0, false, 0, 1);\n\t\trace3AssertUtil.assertPilot(sco200, 9, 0, false, 2, 2);\n\t\trace3AssertUtil.assertPilot(sco135, 0, 0, true, 2, 3);\n\t\trace3AssertUtil.assertPilot(ir027, 9, 0, false, 3, 4);\n\t\trace3AssertUtil.assertPilot(sco019, 9, 0, false, 4, 5);\n\t\trace3AssertUtil.assertPilot(sco154, 9, 0, false, 5, 6);\n\t\trace3AssertUtil.assertPilot(ir073, 8, 0, false, 6, 7);\n\t\trace3AssertUtil.assertPilot(sco136, 0, 0, true, 6, 8);\n\t\trace3AssertUtil.assertPilot(sco179, 0, 0, true, 6, 8);\n\t\trace3AssertUtil.assertPilot(ir085, 8, 0, false, 7, 10);\n\t\trace3AssertUtil.assertPilot(sco081, 0, 0, true, 7, 11);\n\t\trace3AssertUtil.assertPilot(sco159, 6, 0, false, 8, 12);\n\t\trace3AssertUtil.assertPilot(sco060, 0, 0, true, 8, 13);\n\t\trace3AssertUtil.assertPilot(ir052, 6, 0, false, 9, 14);\n\t\trace3AssertUtil.assertPilot(sco158, 5, 0, false, 10, 15);\n\t\trace3AssertUtil.assertPilot(sco033, 0, 0, true, 11, 16);\n\t\trace3AssertUtil.assertPilot(sco071, 0, 0, false, 18, 17);\n\t\trace3AssertUtil.assertPilot(sco197, 0, 0, false, 18, 17);\n\t\trace3AssertUtil.assertDone(6);\n\n\t\tRaceAssertUtil race4AssertUtil = new RaceAssertUtil(scores, race4);\n\t\trace4AssertUtil.assertPilot(sco023, 10, 0, false, 0, 1);\n\t\trace4AssertUtil.assertPilot(sco200, 0, 0, true, 1, 2);\n\t\trace4AssertUtil.assertPilot(ir027, 10, 0, false, 2, 3);\n\t\trace4AssertUtil.assertPilot(sco135, 10, 0, false, 3, 4);\n\t\trace4AssertUtil.assertPilot(sco154, 10, 0, false, 4, 5);\n\t\trace4AssertUtil.assertPilot(sco019, 9, 0, false, 5, 6);\n\t\trace4AssertUtil.assertPilot(ir073, 8, 0, false, 6, 7);\n\t\trace4AssertUtil.assertPilot(sco179, 0, 0, true, 6, 8);\n\t\trace4AssertUtil.assertPilot(sco136, 8, 0, false, 7, 9);\n\t\trace4AssertUtil.assertPilot(sco081, 6, 0, false, 8, 10);\n\t\trace4AssertUtil.assertPilot(sco060, 0, 0, true, 8, 11);\n\t\trace4AssertUtil.assertPilot(sco159, 4, 0, false, 9, 12);\n\t\trace4AssertUtil.assertPilot(ir085, 3, 0, false, 10, 13);\n\t\trace4AssertUtil.assertPilot(sco158, 3, 0, false, 11, 14);\n\t\trace4AssertUtil.assertPilot(sco033, 0, 0, true, 11, 15);\n\t\trace4AssertUtil.assertPilot(ir052, 3, 0, false, 12, 16);\n\t\trace4AssertUtil.assertPilot(sco197, 0, 0, true, 14, 17);\n\t\trace4AssertUtil.assertPilot(sco071, 0, 0, false, 18, 18);\n\t\trace4AssertUtil.assertDone(5);\n\n\t\tOverallAssertUtil overallAssertUtil = new OverallAssertUtil(scores);\n\t\toverallAssertUtil.assertPilot(sco023, 0, 0, 1, 0);\n\t\toverallAssertUtil.assertPilot(sco200, 0, 3, 2, 2);\n\t\toverallAssertUtil.assertPilot(ir027, 0, 5, 3, 3);\n\t\toverallAssertUtil.assertPilot(sco135, 0, 6, 4, 3);\n\t\toverallAssertUtil.assertPilot(sco019, 0, 11, 5, 5);\n\t\toverallAssertUtil.assertPilot(sco154, 0, 14, 6, 8);\n\t\toverallAssertUtil.assertPilot(ir073, 0, 17, 7, 12);\n\t\toverallAssertUtil.assertPilot(sco159, 0, 18, 8, 9);\n\t\toverallAssertUtil.assertPilot(sco136, 0, 18, 9, 17);\n\t\toverallAssertUtil.assertPilot(sco179, 0, 18, 10, 7);\n\t\toverallAssertUtil.assertPilot(sco081, 0, 20, 11, 8);\n\t\toverallAssertUtil.assertPilot(ir085, 0, 21, 12, 11);\n\t\toverallAssertUtil.assertPilot(sco060, 0, 24, 13, 17);\n\t\toverallAssertUtil.assertPilot(ir052, 0, 27, 14, 12);\n\t\toverallAssertUtil.assertPilot(sco033, 0, 33, 15, 17);\n\t\toverallAssertUtil.assertPilot(sco158, 0, 38, 16, 18);\n\t\toverallAssertUtil.assertPilot(sco197, 0, 41, 17, 18);\n\t\toverallAssertUtil.assertPilot(sco071, 0, 46, 18, 18);\n\t\toverallAssertUtil.assertOrder();\n\t}\n\n\t@Test\n\tpublic final void checkEvent1() throws Exception {\n\t\tdb.startSession();\n\t\ttry {\n\t\t\tDatabaseSession.begin();\n\n\t\t\tSeries series = seriesDAO.find(SERIES_NAME);\n\t\t\tEvent event1 = eventDAO.find(series, EVENT1_NAME);\n\t\t\tRace race1 = raceDAO.find(event1, RACE1_NAME);\n\t\t\tRace race2 = raceDAO.find(event1, RACE2_NAME);\n\t\t\tRace race3 = raceDAO.find(event1, RACE3_NAME);\n\t\t\tRace race4 = raceDAO.find(event1, RACE4_NAME);\n\n\t\t\tScores scores = scorer.scoreEvent(event1, Predicates.in(getEventResultsPilots(series, event1)));\n\t\t\tAssert.assertEquals(EVENT1_FLEET, scores.getPilots().size());\n\t\t\tAssert.assertEquals(RACE1_FLEET, scores.getFleetSize(race1));\n\t\t\tAssert.assertEquals(RACE2_FLEET, scores.getFleetSize(race2));\n\t\t\tAssert.assertEquals(RACE3_FLEET, scores.getFleetSize(race3));\n\t\t\tAssert.assertEquals(RACE4_FLEET, scores.getFleetSize(race4));\n\n\t\t\tRaceAssertUtil race1AssertUtil = new RaceAssertUtil(scores, race1);\n\t\t\trace1AssertUtil.assertPilot(ir027, 6, 0, false, 0, 1);\n\t\t\trace1AssertUtil.assertPilot(sco023, 0, 0, true, 0, 2);\n\t\t\trace1AssertUtil.assertPilot(sco200, 6, 0, false, 2, 3);\n\t\t\trace1AssertUtil.assertPilot(sco135, 0, 0, true, 2, 4);\n\t\t\trace1AssertUtil.assertPilot(sco019, 6, 0, false, 3, 5);\n\t\t\trace1AssertUtil.assertPilot(sco159, 5, 0, false, 4, 6);\n\t\t\trace1AssertUtil.assertPilot(ir073, 4, 0, false, 5, 7);\n\t\t\trace1AssertUtil.assertPilot(sco081, 4, 0, false, 6, 8);\n\t\t\trace1AssertUtil.assertPilot(sco179, 4, 0, false, 7, 9);\n\t\t\trace1AssertUtil.assertPilot(sco154, 3, 0, false, 8, 10);\n\t\t\trace1AssertUtil.assertPilot(ir052, 3, 0, false, 9, 11);\n\t\t\trace1AssertUtil.assertPilot(sco071, 3, 0, false, 10, 12);\n\t\t\trace1AssertUtil.assertPilot(ir085, 1, 0, false, 11, 13);\n\t\t\trace1AssertUtil.assertPilot(sco033, 0, 0, false, 17, 14);\n\t\t\trace1AssertUtil.assertPilot(sco060, 0, 0, false, 17, 14);\n\t\t\trace1AssertUtil.assertPilot(sco136, 0, 0, false, 17, 14);\n\t\t\trace1AssertUtil.assertPilot(sco158, 0, 0, false, 17, 14);\n\t\t\trace1AssertUtil.assertPilot(sco197, 0, 0, false, 17, 14);\n\t\t\trace1AssertUtil.assertDone(2);\n\n\t\t\tRaceAssertUtil race2AssertUtil = new RaceAssertUtil(scores, race2);\n\t\t\trace2AssertUtil.assertPilot(sco200, 8, 0, false, 0, 1);\n\t\t\trace2AssertUtil.assertPilot(sco023, 0, 0, true, 0, 2);\n\t\t\trace2AssertUtil.assertPilot(sco135, 8, 0, false, 2, 3);\n\t\t\trace2AssertUtil.assertPilot(ir027, 8, 0, false, 3, 4);\n\t\t\trace2AssertUtil.assertPilot(ir085, 8, 0, false, 4, 5);\n\t\t\trace2AssertUtil.assertPilot(sco019, 0, 0, true, 4, 6);\n\t\t\trace2AssertUtil.assertPilot(sco136, 7, 0, false, 5, 7);\n\t\t\trace2AssertUtil.assertPilot(sco154, 0, 0, true, 5, 8);\n\t\t\trace2AssertUtil.assertPilot(sco179, 7, 0, false, 6, 9);\n\t\t\trace2AssertUtil.assertPilot(sco159, 0, 0, true, 6, 10);\n\t\t\trace2AssertUtil.assertPilot(sco081, 6, 0, false, 7, 11);\n\t\t\trace2AssertUtil.assertPilot(sco060, 6, 0, false, 8, 12);\n\t\t\trace2AssertUtil.assertPilot(ir052, 6, 0, false, 9, 13);\n\t\t\trace2AssertUtil.assertPilot(sco197, 6, 0, false, 10, 14);\n\t\t\trace2AssertUtil.assertPilot(sco033, 2, 0, false, 11, 15);\n\t\t\trace2AssertUtil.assertPilot(ir073, 2, 0, false, 12, 16);\n\t\t\trace2AssertUtil.assertPilot(sco071, 0, 0, false, 18, 17);\n\t\t\trace2AssertUtil.assertPilot(sco158, 0, 0, false, 18, 17);\n\t\t\trace2AssertUtil.assertDone(4);\n\n\t\t\tRaceAssertUtil race3AssertUtil = new RaceAssertUtil(scores, race3);\n\t\t\trace3AssertUtil.assertPilot(sco023, 9, 0, false, 0, 1);\n\t\t\trace3AssertUtil.assertPilot(sco200, 9, 0, false, 2, 2);\n\t\t\trace3AssertUtil.assertPilot(sco135, 0, 0, true, 2, 3);\n\t\t\trace3AssertUtil.assertPilot(ir027, 9, 0, false, 3, 4);\n\t\t\trace3AssertUtil.assertPilot(sco019, 9, 0, false, 4, 5);\n\t\t\trace3AssertUtil.assertPilot(sco154, 9, 0, false, 5, 6);\n\t\t\trace3AssertUtil.assertPilot(ir073, 8, 0, false, 6, 7);\n\t\t\trace3AssertUtil.assertPilot(sco136, 0, 0, true, 6, 8);\n\t\t\trace3AssertUtil.assertPilot(sco179, 0, 0, true, 6, 8);\n\t\t\trace3AssertUtil.assertPilot(ir085, 8, 0, false, 7, 10);\n\t\t\trace3AssertUtil.assertPilot(sco081, 0, 0, true, 7, 11);\n\t\t\trace3AssertUtil.assertPilot(sco159, 6, 0, false, 8, 12);\n\t\t\trace3AssertUtil.assertPilot(sco060, 0, 0, true, 8, 13);\n\t\t\trace3AssertUtil.assertPilot(ir052, 6, 0, false, 9, 14);\n\t\t\trace3AssertUtil.assertPilot(sco158, 5, 0, false, 10, 15);\n\t\t\trace3AssertUtil.assertPilot(sco033, 0, 0, true, 11, 16);\n\t\t\trace3AssertUtil.assertPilot(sco071, 0, 0, false, 18, 17);\n\t\t\trace3AssertUtil.assertPilot(sco197, 0, 0, false, 18, 17);\n\t\t\trace3AssertUtil.assertDone(6);\n\n\t\t\tRaceAssertUtil race4AssertUtil = new RaceAssertUtil(scores, race4);\n\t\t\trace4AssertUtil.assertPilot(sco023, 10, 0, false, 0, 1);\n\t\t\trace4AssertUtil.assertPilot(sco200, 0, 0, true, 1, 2);\n\t\t\trace4AssertUtil.assertPilot(ir027, 10, 0, false, 2, 3);\n\t\t\trace4AssertUtil.assertPilot(sco135, 10, 0, false, 3, 4);\n\t\t\trace4AssertUtil.assertPilot(sco154, 10, 0, false, 4, 5);\n\t\t\trace4AssertUtil.assertPilot(sco019, 9, 0, false, 5, 6);\n\t\t\trace4AssertUtil.assertPilot(ir073, 8, 0, false, 6, 7);", "answers": ["\t\t\trace4AssertUtil.assertPilot(sco179, 0, 0, true, 6, 8);"], "length": 1305, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "be96e43e-b284-48bf-afa3-ed326b5d9100", "reasoning": "The code is in the checkEvent1 test method, building assertions for race4. After the last shown line asserting ir073, the next expected assertion follows the same order as in the earlier checkSeriesAtEvent1 method, which lists the remaining pilots for race4. The next pilot is sco179 with a DNF (true), matching the pattern: race4AssertUtil.assertPilot(sco179, 0, 0, true, 6, 8);", "reasoning_model_answer": "race4AssertUtil.assertPilot(sco179, 0, 0, true, 6, 8);", "assistant_with_reasoning": "\nThe code is in the checkEvent1 test method, building assertions for race4. After the last shown line asserting ir073, the next expected assertion follows the same order as in the earlier checkSeriesAtEvent1 method, which lists the remaining pilots for race4. The next pilot is sco179 with a DNF (true), matching the pattern: race4AssertUtil.assertPilot(sco179, 0, 0, true, 6, 8);\n\nrace4AssertUtil.assertPilot(sco179, 0, 0, true, 6, 8);", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 7.105, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 13659, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "race4AssertUtil.assertPilot(sco179, 0, 0, true, 6, 8);", "score": 0.97, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom flask import request\nfrom flask_restplus import Resource, reqparse\nfrom flask_restplus.reqparse import Argument\nfrom flask_jwt_extended import jwt_required, create_access_token, \\\n jwt_refresh_token_required\nfrom app import db, api\nfrom .models import *\nfrom .decorators import *\nfrom .fields.auth import *\nfrom .fields.users import *\nfrom .fields.groups import *\nfrom .fields.abilities import *\nfrom .fields.containers import *\nfrom .fields.hosts import *\nimport lwp\nimport lxc\nimport os.path\nimport platform\nimport re\nimport gzip\nimport socket\nimport subprocess\nimport psutil\nfrom distro import linux_distribution\n\n\nclass Auth(Resource):\n\n @api.marshal_with(auth_fields_get)\n @api.expect(auth_fields_post, validate=True)\n def post(self):\n \"\"\"\n Get Json Web Token\n \"\"\"\n request_data = request.get_json()\n username = request_data['username']\n password = request_data['password']\n\n user = User.query.filter_by(username=username).first()\n\n if not user or not user.verify_password(password):\n api.abort(code=401, message='Incorrect user or password')\n\n ret = {'access_token': create_access_token(identity=user)}\n return ret\n\n\nclass AuthRefresh(Resource):\n decorators = [jwt_required]\n\n @api.marshal_with(auth_fields_get)\n def post(self):\n \"\"\"\n Get new token with valid token\n \"\"\"\n current_identity = import_user()\n ret = {\n 'access_token': create_access_token(identity=current_identity)\n }\n return ret\n\n\nclass AuthCheck(Resource):\n decorators = [jwt_required]\n\n @api.doc(responses={\n 200: 'Token OK',\n 401: 'Token invalid or expired',\n 422: 'Signature verification failed'\n })\n def get(self):\n \"\"\"\n Check token\n \"\"\"\n return {}, 200\n\n\nclass UsersList(Resource):\n decorators = [jwt_required]\n\n @user_has('users_infos_all')\n @api.marshal_with(users_fields_get_many)\n def get(self):\n \"\"\"\n Get users list\n \"\"\"\n users = User.query.all()\n users_list = []\n\n for user in users:\n users_list.append(user.__jsonapi__())\n\n return {'data': users_list}\n\n @user_has('users_create')\n @api.expect(users_fields_post, validate=True)\n @api.marshal_with(users_fields_get)\n def post(self):\n \"\"\"\n Create user\n \"\"\"\n current_identity = import_user()\n data = request.get_json()['data']\n if User.query.filter_by(username=data['attributes']['username']).first():\n api.abort(code=409, message='User already exists')\n\n user = User()\n\n user.username = data['attributes']['username']\n user.name = data['attributes']['name']\n user.hash_password(data['attributes']['password'])\n\n if 'admin' in data['attributes'] and current_identity.admin:\n user.admin = data['attributes']['admin']\n if 'email' in data['attributes']:\n user.email = data['attributes']['email']\n\n try:\n user.groups = list(id['id'] for id in data[\n 'relationships']['groups']['data'])\n except KeyError:\n pass\n\n try:\n user.containers = list(id['id'] for id in data[\n 'relationships']['containers']['data'])\n except KeyError:\n pass\n\n db.session.add(user)\n db.session.commit()\n\n return {'data': user.__jsonapi__()}, 201\n\n\nclass Users(Resource):\n decorators = [jwt_required]\n\n @user_has('users_infos')\n @api.marshal_with(users_fields_get)\n def get(self, id):\n \"\"\"\n Get user\n \"\"\"\n user = User.query.get(id)\n\n if not user:\n api.abort(code=404, message='User not found')\n\n return {'data': user.__jsonapi__()}\n\n @user_has('users_update')\n @api.expect(users_fields_put, validate=True)\n @api.marshal_with(users_fields_get)\n def put(self, id):\n \"\"\"\n Update user\n \"\"\"\n current_identity = import_user()\n user = User.query.get(id)\n\n if not user:\n api.abort(code=404, message='User not found')\n\n data = request.get_json()['data']\n\n if 'name' in data['attributes']:\n user.name = data['attributes']['name']\n if 'admin' in data['attributes'] and current_identity.admin:\n user.admin = data['attributes']['admin']\n if 'email' in data['attributes']:\n user.email = data['attributes']['email']\n if 'password' in data['attributes']:\n user.hash_password(data['attributes']['password'])\n\n try:\n user.groups = list(id['id'] for id in data[\n 'relationships']['groups']['data'])\n except KeyError:\n pass\n\n try:\n user.containers = list(id['id'] for id in data[\n 'relationships']['containers']['data'])\n except KeyError:\n pass\n\n if len(data) > 0:\n db.session.commit()\n\n return {'data': user.__jsonapi__()}\n\n @user_has('users_delete')\n def delete(self, id):\n \"\"\"\n Delete user\n \"\"\"\n user = User.query.get(id)\n\n if not user:\n api.abort(code=404, message='User not found')\n\n db.session.delete(user)\n db.session.commit()\n\n return {}, 204\n\n\nclass Me(Resource):\n decorators = [jwt_required]\n\n @api.marshal_with(users_fields_get)\n def get(self):\n \"\"\"\n Get me\n \"\"\"\n current_identity = import_user()\n return {'data': current_identity.__jsonapi__()}\n\n @user_has('me_edit')\n @api.expect(users_fields_put, validate=True)\n @api.marshal_with(users_fields_get)\n def put(self):\n \"\"\"\n Update me\n \"\"\"\n current_identity = import_user()\n user = User.query.get(current_identity.id)\n\n data = request.get_json()['data']\n\n if 'name' in data['attributes']:\n user.name = data['attributes']['name']\n if 'admin' in data['attributes'] and current_identity.admin:\n user.admin = data['attributes']['admin']\n if 'email' in data['attributes']:\n user.email = data['attributes']['email']\n if 'password' in data['attributes']:\n user.hash_password(data['attributes']['password'])\n\n try:\n user.groups = list(id['id'] for id in data[\n 'relationships']['groups']['data'])\n except KeyError:\n pass\n\n try:\n user.containers = list(id['id'] for id in data[\n 'relationships']['containers']['data'])\n except KeyError:\n pass\n\n if len(data) > 0:\n db.session.commit()\n\n return {'data': user.__jsonapi__()}\n\n @user_has('me_edit')\n def delete(self):\n \"\"\"\n Delete me (stupid)\n \"\"\"\n current_identity = import_user()\n user = User.query.get(current_identity.id)\n\n db.session.delete(user)\n db.session.commit()\n\n return {}, 204\n\n\nclass GroupsList(Resource):\n decorators = [jwt_required]\n\n @user_has('groups_infos_all')\n @api.marshal_with(groups_fields_get_many)\n def get(self):\n \"\"\"\n Get groups list\n \"\"\"\n groups = Group.query.all()\n groups_list = []\n\n for group in groups:\n groups_list.append(group.__jsonapi__())\n\n return {'data': groups_list}\n\n @user_has('groups_create')\n @api.expect(groups_fields_post, validate=True)\n @api.marshal_with(groups_fields_get)\n def post(self):\n \"\"\"\n Create group\n \"\"\"\n data = request.get_json()['data']\n\n group = Group(name=data['attributes']['name'])\n\n try:\n group.abilities = list(id['id'] for id in data[\n 'relationships']['abilities']['data'])\n except KeyError:\n pass\n\n try:\n group.users = list(id['id'] for id in data[\n 'relationships']['users']['data'])\n except KeyError:\n pass\n\n db.session.add(group)\n db.session.commit()\n\n return {'data': group.__jsonapi__()}, 201\n\n\nclass Groups(Resource):\n decorators = [jwt_required]\n\n @user_has('groups_infos')\n @api.marshal_with(groups_fields_get)\n def get(self, id):\n \"\"\"\n Get group\n \"\"\"\n group = Group.query.get(id)\n\n if not group:\n api.abort(code=404, message='Group not found')\n\n return {'data': group.__jsonapi__()}\n\n @user_has('groups_update')\n @api.expect(groups_fields_put, validate=True)\n @api.marshal_with(groups_fields_get)\n def put(self, id):\n \"\"\"\n Update group\n \"\"\"\n group = Group.query.get(id)\n\n if not group:\n api.abort(code=404, message='Group not found')\n\n data = request.get_json()['data']\n\n if 'name' in data['attributes']:\n group.name = data['attributes']['name']\n\n try:\n group.abilities = list(id['id'] for id in data[\n 'relationships']['abilities']['data'])\n except KeyError:\n pass\n\n try:\n group.users = list(id['id'] for id in data[\n 'relationships']['users']['data'])\n except KeyError:\n pass\n\n if len(data) > 0:\n db.session.commit()\n\n return {'data': group.__jsonapi__()}\n\n @user_has('groups_delete')\n def delete(self, id):\n \"\"\"\n Delete group\n \"\"\"\n group = Group.query.get(id)\n\n if not group:\n api.abort(code=404, message='Group not found')\n\n db.session.delete(group)\n db.session.commit()\n\n return {}, 204\n\n\nclass AbilitiesList(Resource):\n decorators = [jwt_required]\n\n @user_has('abilities_infos_all')\n @api.marshal_with(abilities_fields_get_many)\n def get(self):\n \"\"\"\n Get abilities list\n \"\"\"\n abilities = Ability.query.all()\n abilities_list = []\n\n for ability in abilities:\n abilities_list.append(ability.__jsonapi__())\n\n return {'data': abilities_list}\n\n\nclass Abilities(Resource):\n decorators = [jwt_required]\n\n @user_has('abilities_infos')\n @api.marshal_with(abilities_fields_get)\n def get(self, id):\n \"\"\"\n Get ability\n \"\"\"\n ability = Ability.query.get(id)\n\n if not ability:\n api.abort(code=404, message='Ability not found')\n\n return {'data': ability.__jsonapi__()}\n\n @user_has('abilities_update')\n @api.expect(abilities_fields_put, validate=True)\n @api.marshal_with(abilities_fields_get)\n def put(self, id):\n \"\"\"\n Update ability\n \"\"\"\n ability = Ability.query.get(id)\n\n data = request.get_json()['data']\n\n try:\n if len(data['relationships']['groups']['data']) >= 0:\n ability.groups = list(id['id'] for id in data[\n 'relationships']['groups']['data'])\n db.session.commit()\n except KeyError:\n pass\n\n return {'data': ability.__jsonapi__()}\n\n\n##################\n# Containers API #\n##################\nclass ContainersList(Resource):\n decorators = [jwt_required]\n\n @user_has('ct_infos')\n @api.marshal_with(containers_fields_get_many)\n def get(self):\n \"\"\"\n Get containers list\n \"\"\"\n current_identity = import_user()\n containers = []\n\n for c in lxc.list_containers():\n container = Container.query.filter_by(name=c).first()\n if container.id in current_identity.containers or current_identity.admin:\n infos = lwp.ct_infos(c)\n container_json = container.__jsonapi__()\n container_json['attributes'] = infos\n containers.append(container_json)\n\n return {'data': containers}\n\n @user_has('ct_create')\n @api.expect(containers_fields_post, validate=True)\n @api.marshal_with(containers_fields_get)\n @api.doc(responses={\n 201: 'Container created',\n 409: 'Container already exists',\n 500: 'Can\\'t create container'\n })\n def post(self):\n \"\"\"\n Create container\n \"\"\"\n current_identity = import_user()\n data = request.get_json()['data']\n\n if 'name' in data['attributes']:\n c = lxc.Container(data['attributes']['name'])\n if not c.defined:\n try:\n if not isinstance(data['attributes']['template']['args'], str):\n data['attributes']['template']['args'] = ''\n except KeyError:\n data['attributes']['template']['args'] = ''\n if not c.create(\n template=data['attributes']['template']['name'],\n flags=lxc.LXC_CREATE_QUIET,\n args=data['attributes']['template']['args'],\n bdevtype=None\n ):\n api.abort(code=500, message='Can\\'t create container')\n\n # Add container to database\n container = Container(name=data['attributes']['name'])\n db.session.add(container)\n db.session.commit()\n # Get container ID\n container = Container.query.filter_by(\n name=data['attributes']['name']).first()\n # Add container to allowed user's containers\n user = User.query.get(current_identity.id)\n user.containers.append(container.id)\n db.session.commit()\n\n return Containers.put(self, container.id, d=data), 201\n api.abort(code=409, message='Container already exists')\n\n\nclass Containers(Resource):\n decorators = [jwt_required]", "answers": [" @user_has('ct_infos')"], "length": 986, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "5a5cd3f1-a396-48d8-90e8-4e29cdbb993b", "reasoning": "After defining the Containers class and its decorators, the file follows the same pattern as other resource classes (Users, Groups, Abilities). The next logical line is the first method decorator for the GET endpoint, which checks permissions. So the next line should be the permission decorator for container info.", "reasoning_model_answer": "@user_has('ct_infos')", "assistant_with_reasoning": "\nAfter defining the Containers class and its decorators, the file follows the same pattern as other resource classes (Users, Groups, Abilities). The next logical line is the first method decorator for the GET endpoint, which checks permissions. So the next line should be the permission decorator for container info.\n\n@user_has('ct_infos')", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.633, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 14155, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "@user_has('ct_infos')", "score": 0.91, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "import base64\nimport json\nimport os\nimport shutil\nimport zipfile\n\nfrom paraview import simple\nfrom paraview.web.dataset_builder import ImageDataSetBuilder\nfrom paraview.web.dataset_builder import CompositeDataSetBuilder\nfrom paraview.web.dataset_builder import VTKGeometryDataSetBuilder\n\nfrom tomviz import py2to3\n\nDATA_DIRECTORY = 'data'\nHTML_FILENAME = 'tomviz.html'\nJS_FILENAME = 'tomviz.js'\nHTML_WITH_DATA_FILENAME = 'tomviz_data.html'\nDATA_FILENAME = 'data.tomviz'\n\narrayTypesMapping = ' bBhHiIlLfd'\njsMapping = {\n 'b': 'Int8Array',\n 'B': 'Uint8Array',\n 'h': 'Int16Array',\n 'H': 'Int16Array',\n 'i': 'Int32Array',\n 'I': 'Uint32Array',\n 'l': 'Int32Array',\n 'L': 'Uint32Array',\n 'f': 'Float32Array',\n 'd': 'Float64Array'\n}\n\n\ndef web_export(*args, **kwargs):\n # Expecting only kwargs\n keepData = kwargs['keepData']\n executionPath = kwargs['executionPath']\n destPath = kwargs['destPath']\n exportType = kwargs['exportType']\n\n # Camera properties\n nbPhi = kwargs['nbPhi']\n nbTheta = kwargs['nbTheta']\n\n # Destination directory for data\n dest = '%s/data' % destPath\n\n # Extract initial setting for view\n view = simple.GetRenderView()\n viewState = {}\n for prop in ['CameraViewUp', 'CameraPosition', 'ViewSize']:\n viewState[prop] = tuple(view.GetProperty(prop).GetData())\n\n # Camera handling\n deltaPhi = int(360 / nbPhi)\n deltaTheta = int(180 / nbTheta)\n thetaMax = deltaTheta\n while thetaMax + deltaTheta < 90:\n thetaMax += deltaTheta\n camera = {\n 'type': 'spherical',\n 'phi': range(0, 360, deltaPhi),\n 'theta': range(-thetaMax, thetaMax + 1, deltaTheta)\n }\n\n # Choose export mode:\n if exportType == 0:\n export_images(dest, camera, **kwargs)\n\n if exportType == 1:\n export_volume_exploration_images(dest, camera, **kwargs)\n\n if exportType == 2:\n export_contour_exploration_images(dest, camera, **kwargs)\n\n if exportType == 3:\n export_contours_geometry(dest, **kwargs)\n\n if exportType == 4:\n export_contour_exploration_geometry(dest, **kwargs)\n\n if exportType == 5:\n export_volume(dest, **kwargs)\n\n # Setup application\n copy_viewer(destPath, executionPath)\n\n # Compress only geometry data\n bundleDataToHTML(destPath, keepData, exportType > 2)\n\n # Restore initial parameters\n for prop in viewState:\n view.GetProperty(prop).SetData(viewState[prop])\n\n# -----------------------------------------------------------------------------\n# Helpers\n# -----------------------------------------------------------------------------\n\n\ndef bundleDataToHTML(destinationPath, keepData, compress=False):\n compression_type = zipfile.ZIP_DEFLATED if compress else zipfile.ZIP_STORED\n dataDir = os.path.join(destinationPath, DATA_DIRECTORY)\n srcHtmlPath = os.path.join(destinationPath, HTML_FILENAME)\n dstHtmlPath = os.path.join(destinationPath, HTML_WITH_DATA_FILENAME)\n dstDataPath = os.path.join(destinationPath, DATA_FILENAME)\n webResources = ['']\n\n if os.path.exists(dataDir):\n for dirName, subdirList, fileList in os.walk(dataDir):\n for fname in fileList:\n fullPath = os.path.join(dirName, fname)\n filePath = os.path.relpath(fullPath, dataDir)\n relPath = '%s/%s' % (DATA_DIRECTORY, filePath)\n content = ''\n\n if fname.endswith('.json'):\n with open(fullPath, 'r', encoding='utf8') as data:\n content = data.read()\n else:\n with open(fullPath, 'rb') as data:\n dataContent = data.read()\n content = base64.b64encode(dataContent)\n content = content.decode().replace('\\n', '')\n\n webResources.append(\n '
    %s
    '\n % (relPath, content))\n\n webResources.append('')\n\n # Create new output file\n with open(srcHtmlPath, mode='r', encoding='utf8') as srcHtml:\n with open(dstHtmlPath, mode='w', encoding='utf8') as dstHtml:\n for line in srcHtml:\n if '' in line:\n for webResource in webResources:\n dstHtml.write(webResource)\n else:\n dstHtml.write(line)\n\n # Generate zip file for the data\n if keepData and os.path.exists(dataDir):\n with zipfile.ZipFile(dstDataPath, mode='w') as zf:\n for dirName, subdirList, fileList in os.walk(dataDir):\n for fname in fileList:\n fullPath = os.path.join(dirName, fname)\n filePath = os.path.relpath(fullPath, dataDir)\n relPath = '%s/%s' % (DATA_DIRECTORY, filePath)\n zf.write(fullPath, arcname=relPath,\n compress_type=compression_type)\n\n # Cleanup\n os.remove(srcHtmlPath)\n shutil.rmtree(dataDir)\n\n\ndef get_proxy(id):\n session = simple.servermanager.ActiveConnection.Session\n remoteObj = session.GetRemoteObject(int(id))\n return simple.servermanager._getPyProxy(remoteObj)\n\n\ndef copy_viewer(destinationPath, executionPath):\n searchPath = executionPath\n for upDirTry in range(4):\n searchPath = os.path.normpath(os.path.join(searchPath, '..'))\n for root, dirs, files in os.walk(searchPath):\n if HTML_FILENAME in files and root != destinationPath:\n srcHtmlFile = os.path.join(root, HTML_FILENAME)\n srcJsFile = os.path.join(root, JS_FILENAME)\n dstHtmlFile = os.path.join(destinationPath, HTML_FILENAME)\n with open(srcHtmlFile, mode='r', encoding='utf8') as srcHTML, \\\n open(srcJsFile, mode='r', encoding='utf8') as srcJS, \\\n open(dstHtmlFile, mode='w', encoding='utf8') as dstHTML:\n for line in srcHTML:\n if '' in line:\n dstHTML.write('\\n\\n')\n else:\n dstHTML.write(line)\n return\n\n\ndef add_scene_item(scene, name, proxy, view):\n hasNormal = False\n hasColor = False\n colors = {}\n representation = {}\n rep = simple.GetRepresentation(proxy, view)\n\n # Skip hidden object or volume\n if not rep.Visibility or rep.Representation == 'Volume':\n return\n\n for prop in ['Representation']:\n representation[prop] = rep.GetProperty(prop).GetData()\n\n pdInfo = proxy.GetPointDataInformation()\n numberOfPointArrays = pdInfo.GetNumberOfArrays()\n for idx in range(numberOfPointArrays):\n array = pdInfo.GetArray(idx)\n rangeValues = array.GetRange(-1)\n if array.Name == 'Normals':\n hasNormal = True\n if array.Name not in ['vtkValidPointMask', 'Normals']:\n hasColor = True\n if rangeValues[0] == rangeValues[1]:\n colors[array.Name] = {\n 'constant': rangeValues[0],\n 'location': 'POINT_DATA'\n }\n else:\n colors[array.Name] = {\n 'location': 'POINT_DATA',\n 'range': [i for i in rangeValues]\n }\n\n # Get information about cell data arrays\n cdInfo = proxy.GetCellDataInformation()\n numberOfCellArrays = cdInfo.GetNumberOfArrays()\n for idx in range(numberOfCellArrays):\n array = cdInfo.GetArray(idx)\n hasColor = True\n colors[array.Name] = {\n 'location': 'CELL_DATA',\n 'range': array.GetRange(-1)\n }\n\n # Make sure Normals are available if lighting by normals\n source = proxy\n if not hasColor or rep.Representation == 'Outline':\n colors = {'solid': {'constant': 0, 'location': 'POINT_DATA'}}\n elif 'light' in scene and 'normal' in scene['light'] and not hasNormal:\n rep.Visibility = 0\n surface = simple.ExtractSurface(Input=proxy)\n surfaceWithNormals = simple.GenerateSurfaceNormals(Input=surface)\n source = surfaceWithNormals\n\n scene['scene'].append({\n 'name': name,\n 'source': source,\n 'colors': colors,\n 'representation': representation\n })\n\n\ndef patch_data_range(destinationPath):\n originalPath = os.path.join(destinationPath, 'index.json')\n tmpPath = os.path.join(destinationPath, 'index_tmp.json')\n os.rename(originalPath, tmpPath)\n with open(originalPath, 'w', encoding='utf8') as outputJSON:\n with open(tmpPath, 'r', encoding='utf8') as inputJSON:\n content = json.loads(inputJSON.read())\n # Patch geometry range\n for fieldName in content['Geometry']['ranges']:\n content['Geometry']['ranges'][fieldName] = [0, 255]\n outputJSON.write(json.dumps(content, indent=2))\n os.remove(tmpPath)\n\n\ndef get_volume_piecewise(view):\n renderer = view.GetClientSideObject().GetRenderer()\n for volume in renderer.GetVolumes():\n if volume.GetClassName() == 'vtkVolume':\n return volume.GetProperty().GetScalarOpacity()\n return None\n\n\ndef build_control_points(xrgbArray):\n minValue = xrgbArray[0]\n maxValue = xrgbArray[-4]\n dataRange = maxValue - minValue\n controlpoints = []\n offset = 0\n while offset < len(xrgbArray):\n controlpoints.append({\n 'x': (xrgbArray[offset] - minValue) / dataRange,\n 'r': xrgbArray[offset + 1],\n 'g': xrgbArray[offset + 2],\n 'b': xrgbArray[offset + 3],\n })\n offset += 4\n return controlpoints\n\n\ndef get_volume_lookuptable_section(view):\n renderer = view.GetClientSideObject().GetRenderer()\n for volume in renderer.GetVolumes():\n if volume.GetClassName() == 'vtkVolume':\n array = volume.GetMapper().GetInput().GetPointData().GetScalars()\n fielName = array.GetName()\n lut = volume.GetProperty().GetRGBTransferFunction()\n controlpoints = []\n tupleHolder = list(range(6))\n for i in range(lut.GetSize()):\n lut.GetNodeValue(i, tupleHolder)\n controlpoints.append({\n 'x': tupleHolder[0],\n 'r': tupleHolder[1],\n 'g': tupleHolder[2],\n 'b': tupleHolder[3],\n })\n\n # Need to rescale x between [0, 1] for pvw\n minValue = controlpoints[0]['x']\n maxValue = controlpoints[-1]['x']\n dataRange = maxValue - minValue\n for node in controlpoints:\n node['x'] = (node['x'] - minValue) / dataRange\n\n return {fielName: {'controlpoints': controlpoints}}\n return {}\n\n\ndef get_source_lookuptable_section(source):\n luts = {}\n rep = simple.GetRepresentation(source)\n name = rep.ColorArrayName[1]\n lut = rep.LookupTable\n if lut:\n controlpoints = build_control_points(lut.RGBPoints)\n luts[name] = {'controlpoints': controlpoints}\n\n return luts\n\n\ndef get_contour():\n for key, value in py2to3.iteritems(simple.GetSources()):\n if 'FlyingEdges' in key[0]:\n return value\n if 'Contour' in key[0]:\n return value\n return None\n\n\ndef get_trivial_producer():\n for key, value in py2to3.iteritems(simple.GetSources()):\n if 'TrivialProducer' in key[0]:\n return value\n return None\n\n\ndef array_sampler(srcDims, dstDims, scale, inputArray):\n if scale == 1:\n return inputArray\n\n newSize = dstDims[0] * dstDims[1] * dstDims[2]\n outputArray = inputArray.NewInstance()\n outputArray.SetNumberOfTuples(newSize)\n offset = 0\n for k in range(dstDims[2]):\n for j in range(dstDims[1]):\n for i in range(dstDims[0]):\n srcIdx = (i * scale)\n srcIdx += (j * scale * srcDims[0])\n srcIdx += (k * scale * srcDims[0] * srcDims[1])\n outputArray.SetValue(offset, inputArray.GetValue(srcIdx))\n offset += 1\n\n return outputArray\n\n# -----------------------------------------------------------------------------\n# Image based exporter\n# -----------------------------------------------------------------------------\n\n\ndef export_images(destinationPath, camera, **kwargs):\n # View size\n imageWidth = kwargs['imageWidth']\n imageHeight = kwargs['imageHeight']\n\n # Configure View\n view = simple.GetRenderView()\n view.ViewSize = [imageWidth, imageHeight]\n\n idb = ImageDataSetBuilder(destinationPath, 'image/jpg', camera)\n idb.start(view)\n idb.writeImages()\n idb.stop()\n\n# -----------------------------------------------------------------------------\n# Image based Volume exploration\n# -----------------------------------------------------------------------------\n\n\ndef export_volume_exploration_images(destinationPath, camera, **kwargs):\n values = [int(v) for v in kwargs['multiValue'].split(',')]\n maxOpacity = float(kwargs['maxOpacity']) / 100.0\n span = float(kwargs['tentWidth']) * 0.5\n\n # View size\n imageWidth = kwargs['imageWidth']\n imageHeight = kwargs['imageHeight']\n\n # Configure View\n view = simple.GetRenderView()\n view.ViewSize = [imageWidth, imageHeight]\n\n pvw = get_volume_piecewise(view)\n if pvw:\n savedNodes = []\n currentPoints = [0, 0, 0, 0]\n for i in range(pvw.GetSize()):\n pvw.GetNodeValue(i, currentPoints)\n savedNodes.append([v for v in currentPoints])\n\n idb = ImageDataSetBuilder(destinationPath, 'image/jpg', camera)\n idb.getDataHandler().registerArgument(priority=1, name='volume',\n values=values, ui='slider',\n loop='reverse')\n idb.start(view)\n for volume in idb.getDataHandler().volume:\n pvw.RemoveAllPoints()\n pvw.AddPoint(float(volume) - span, 0)\n pvw.AddPoint(float(volume), maxOpacity)\n pvw.AddPoint(float(volume) + span, 0)\n pvw.AddPoint(255, 0)\n idb.writeImages()\n idb.stop()\n\n # Reset to original piecewise funtion\n pvw.RemoveAllPoints()\n for node in savedNodes:\n pvw.AddPoint(node[0], node[1], node[2], node[3])\n else:\n print('Can not export Volume exploration without a Volume')\n\n# -----------------------------------------------------------------------------\n# Image based Contour exploration\n# -----------------------------------------------------------------------------\n\n\ndef export_contour_exploration_images(destinationPath, camera, **kwargs):\n values = [int(v) for v in kwargs['multiValue'].split(',')]\n\n # View size\n imageWidth = kwargs['imageWidth']", "answers": [" imageHeight = kwargs['imageHeight']"], "length": 1209, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "98a163ad-5c87-4dcc-8039-36b141ae4a43", "reasoning": "In the export_contour_exploration_images function, the pattern follows that of other export functions: after retrieving imageWidth from kwargs, the next logical step is to retrieve imageHeight from kwargs, mirroring the code in export_images and export_volume_exploration_images. Therefore the next line should assign imageHeight from kwargs.", "reasoning_model_answer": "imageHeight = kwargs['imageHeight']", "assistant_with_reasoning": "\nIn the export_contour_exploration_images function, the pattern follows that of other export functions: after retrieving imageWidth from kwargs, the next logical step is to retrieve imageHeight from kwargs, mirroring the code in export_images and export_volume_exploration_images. Therefore the next line should assign imageHeight from kwargs.\n\nimageHeight = kwargs['imageHeight']", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 1.966, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 15267, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "imageHeight = kwargs['imageHeight']", "score": 0.95, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "#!/usr/bin/env python\n#\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied. See the License for the\n# specific language governing permissions and limitations\n# under the License.\n#\n\n\nimport logging\nfrom unittest import TestCase, main\nimport time\nimport os\nimport uuid\nfrom datetime import timedelta\nfrom pulsar import Client, MessageId, \\\n CompressionType, ConsumerType, PartitionsRoutingMode, \\\n AuthenticationTLS, Authentication, AuthenticationToken, InitialPosition, \\\n CryptoKeyReader\n\nfrom _pulsar import ProducerConfiguration, ConsumerConfiguration\n\nfrom schema_test import *\n\ntry:\n # For Python 3.0 and later\n from urllib.request import urlopen, Request\nexcept ImportError:\n # Fall back to Python 2's urllib2\n from urllib2 import urlopen, Request\n\nTM = 10000 # Do not wait forever in tests\n\n\ndef doHttpPost(url, data):\n req = Request(url, data.encode())\n req.add_header('Content-Type', 'application/json')\n urlopen(req)\n\n\ndef doHttpPut(url, data):\n try:\n req = Request(url, data.encode())\n req.add_header('Content-Type', 'application/json')\n req.get_method = lambda: 'PUT'\n urlopen(req)\n except Exception as ex:\n # ignore conflicts exception to have test idempotency\n if '409' in str(ex):\n pass\n else:\n raise ex\n\n\ndef doHttpGet(url):\n req = Request(url)\n req.add_header('Accept', 'application/json')\n return urlopen(req).read()\n\n\nclass PulsarTest(TestCase):\n\n serviceUrl = 'pulsar://localhost:6650'\n adminUrl = 'http://localhost:8080'\n\n serviceUrlTls = 'pulsar+ssl://localhost:6651'\n\n def test_producer_config(self):\n conf = ProducerConfiguration()\n conf.send_timeout_millis(12)\n self.assertEqual(conf.send_timeout_millis(), 12)\n\n self.assertEqual(conf.compression_type(), CompressionType.NONE)\n conf.compression_type(CompressionType.LZ4)\n self.assertEqual(conf.compression_type(), CompressionType.LZ4)\n\n conf.max_pending_messages(120)\n self.assertEqual(conf.max_pending_messages(), 120)\n\n def test_consumer_config(self):\n conf = ConsumerConfiguration()\n self.assertEqual(conf.consumer_type(), ConsumerType.Exclusive)\n conf.consumer_type(ConsumerType.Shared)\n self.assertEqual(conf.consumer_type(), ConsumerType.Shared)\n\n self.assertEqual(conf.consumer_name(), '')\n conf.consumer_name(\"my-name\")\n self.assertEqual(conf.consumer_name(), \"my-name\")\n\n self.assertEqual(conf.replicate_subscription_state_enabled(), False)\n conf.replicate_subscription_state_enabled(True)\n self.assertEqual(conf.replicate_subscription_state_enabled(), True)\n\n def test_client_logger(self):\n logger = logging.getLogger(\"pulsar\")\n Client(self.serviceUrl, logger=logger)\n \n def test_connect_error(self):\n with self.assertRaises(pulsar.ConnectError):\n client = Client('fakeServiceUrl')\n client.create_producer('connect-error-topic')\n client.close()\n\n def test_exception_inheritance(self):\n assert issubclass(pulsar.ConnectError, pulsar.PulsarException)\n assert issubclass(pulsar.PulsarException, Exception)\n\n def test_simple_producer(self):\n client = Client(self.serviceUrl)\n producer = client.create_producer('my-python-topic')\n producer.send(b'hello')\n producer.close()\n client.close()\n\n def test_producer_send_async(self):\n client = Client(self.serviceUrl)\n producer = client.create_producer('my-python-topic')\n\n sent_messages = []\n\n def send_callback(producer, msg):\n sent_messages.append(msg)\n\n producer.send_async(b'hello', send_callback)\n producer.send_async(b'hello', send_callback)\n producer.send_async(b'hello', send_callback)\n\n i = 0\n while len(sent_messages) < 3 and i < 100:\n time.sleep(0.1)\n i += 1\n self.assertEqual(len(sent_messages), 3)\n client.close()\n\n def test_producer_send(self):\n client = Client(self.serviceUrl)\n topic = 'test_producer_send'\n producer = client.create_producer(topic)\n consumer = client.subscribe(topic, 'sub-name')\n msg_id = producer.send(b'hello')\n print('send to {}'.format(msg_id))\n msg = consumer.receive(TM)\n consumer.acknowledge(msg)\n print('receive from {}'.format(msg.message_id()))\n self.assertEqual(msg_id, msg.message_id())\n\n def test_producer_consumer(self):\n client = Client(self.serviceUrl)\n consumer = client.subscribe('my-python-topic-producer-consumer',\n 'my-sub',\n consumer_type=ConsumerType.Shared)\n producer = client.create_producer('my-python-topic-producer-consumer')\n producer.send(b'hello')\n\n msg = consumer.receive(TM)\n self.assertTrue(msg)\n self.assertEqual(msg.data(), b'hello')\n\n with self.assertRaises(pulsar.Timeout):\n consumer.receive(100)\n\n consumer.unsubscribe()\n client.close()\n\n def test_redelivery_count(self):\n client = Client(self.serviceUrl)\n consumer = client.subscribe('my-python-topic-redelivery-count',\n 'my-sub',\n consumer_type=ConsumerType.Shared,\n negative_ack_redelivery_delay_ms=500)\n producer = client.create_producer('my-python-topic-redelivery-count')\n producer.send(b'hello')\n\n redelivery_count = 0\n for i in range(4):\n msg = consumer.receive(TM)\n print(\"Received message %s\" % msg.data())\n consumer.negative_acknowledge(msg)\n redelivery_count = msg.redelivery_count()\n\n self.assertTrue(msg)\n self.assertEqual(msg.data(), b'hello')\n self.assertEqual(3, redelivery_count)\n consumer.unsubscribe()\n producer.close()\n client.close()\n\n def test_deliver_at(self):\n client = Client(self.serviceUrl)\n consumer = client.subscribe('my-python-topic-deliver-at',\n 'my-sub',\n consumer_type=ConsumerType.Shared)\n producer = client.create_producer('my-python-topic-deliver-at')\n # Delay message in 1.1s\n producer.send(b'hello', deliver_at=int(round(time.time() * 1000)) + 1100)\n\n # Message should not be available in the next second\n with self.assertRaises(pulsar.Timeout):\n consumer.receive(1000)\n\n # Message should be published now\n msg = consumer.receive(TM)\n self.assertTrue(msg)\n self.assertEqual(msg.data(), b'hello')\n consumer.unsubscribe()\n producer.close()\n client.close()\n\n def test_deliver_after(self):\n client = Client(self.serviceUrl)\n consumer = client.subscribe('my-python-topic-deliver-after',\n 'my-sub',\n consumer_type=ConsumerType.Shared)\n producer = client.create_producer('my-python-topic-deliver-after')\n # Delay message in 1.1s\n producer.send(b'hello', deliver_after=timedelta(milliseconds=1100))\n\n # Message should not be available in the next second\n with self.assertRaises(pulsar.Timeout):\n consumer.receive(1000)\n\n # Message should be published in the next 500ms\n msg = consumer.receive(TM)\n self.assertTrue(msg)\n self.assertEqual(msg.data(), b'hello')\n consumer.unsubscribe()\n producer.close()\n client.close()\n\n def test_consumer_initial_position(self):\n client = Client(self.serviceUrl)\n producer = client.create_producer('consumer-initial-position')\n\n # Sending 5 messages before consumer creation.\n # These should be received with initial_position set to Earliest but not with Latest.\n for i in range(5):\n producer.send(b'hello-%d' % i)\n\n consumer = client.subscribe('consumer-initial-position',\n 'my-sub',\n consumer_type=ConsumerType.Shared,\n initial_position=InitialPosition.Earliest)\n\n # Sending 5 other messages that should be received regardless of the initial_position.\n for i in range(5, 10):\n producer.send(b'hello-%d' % i)\n\n for i in range(10):\n msg = consumer.receive(TM)\n self.assertTrue(msg)\n self.assertEqual(msg.data(), b'hello-%d' % i)\n\n with self.assertRaises(pulsar.Timeout):\n consumer.receive(100)\n\n consumer.unsubscribe()\n client.close()\n\n def test_consumer_queue_size_is_zero(self):\n client = Client(self.serviceUrl)\n consumer = client.subscribe('my-python-topic-consumer-init-queue-size-is-zero',\n 'my-sub',\n consumer_type=ConsumerType.Shared,\n receiver_queue_size=0,\n initial_position=InitialPosition.Earliest)\n producer = client.create_producer('my-python-topic-consumer-init-queue-size-is-zero')\n producer.send(b'hello')\n time.sleep(0.1)\n msg = consumer.receive()\n self.assertTrue(msg)\n self.assertEqual(msg.data(), b'hello')\n\n consumer.unsubscribe()\n client.close()\n\n def test_message_properties(self):\n client = Client(self.serviceUrl)\n topic = 'my-python-test-message-properties'\n consumer = client.subscribe(topic=topic,\n subscription_name='my-subscription',\n schema=pulsar.schema.StringSchema())\n producer = client.create_producer(topic=topic,\n schema=StringSchema())\n producer.send('hello',\n properties={\n 'a': '1',\n 'b': '2'\n })\n\n msg = consumer.receive(TM)\n self.assertTrue(msg)\n self.assertEqual(msg.value(), 'hello')\n self.assertEqual(msg.properties(), {\n 'a': '1',\n 'b': '2'\n })\n\n consumer.unsubscribe()\n client.close()\n\n def test_tls_auth(self):\n certs_dir = '/pulsar/pulsar-broker/src/test/resources/authentication/tls/'\n if not os.path.exists(certs_dir):\n certs_dir = \"../../pulsar-broker/src/test/resources/authentication/tls/\"\n client = Client(self.serviceUrlTls,\n tls_trust_certs_file_path=certs_dir + 'cacert.pem',\n tls_allow_insecure_connection=False,\n authentication=AuthenticationTLS(certs_dir + 'client-cert.pem', certs_dir + 'client-key.pem'))\n\n consumer = client.subscribe('my-python-topic-tls-auth',\n 'my-sub',\n consumer_type=ConsumerType.Shared)\n producer = client.create_producer('my-python-topic-tls-auth')\n producer.send(b'hello')\n\n msg = consumer.receive(TM)\n self.assertTrue(msg)\n self.assertEqual(msg.data(), b'hello')\n\n with self.assertRaises(pulsar.Timeout):\n consumer.receive(100)\n\n client.close()\n\n def test_tls_auth2(self):\n certs_dir = '/pulsar/pulsar-broker/src/test/resources/authentication/tls/'\n if not os.path.exists(certs_dir):\n certs_dir = \"../../pulsar-broker/src/test/resources/authentication/tls/\"\n authPlugin = \"org.apache.pulsar.client.impl.auth.AuthenticationTls\"\n authParams = \"tlsCertFile:%s/client-cert.pem,tlsKeyFile:%s/client-key.pem\" % (certs_dir, certs_dir)\n\n client = Client(self.serviceUrlTls,\n tls_trust_certs_file_path=certs_dir + 'cacert.pem',\n tls_allow_insecure_connection=False,\n authentication=Authentication(authPlugin, authParams))\n\n consumer = client.subscribe('my-python-topic-tls-auth-2',\n 'my-sub',\n consumer_type=ConsumerType.Shared)\n producer = client.create_producer('my-python-topic-tls-auth-2')\n producer.send(b'hello')\n\n msg = consumer.receive(TM)\n self.assertTrue(msg)\n self.assertEqual(msg.data(), b'hello')\n\n with self.assertRaises(pulsar.Timeout):\n consumer.receive(100)\n\n client.close()\n\n def test_encryption(self):\n publicKeyPath = \"/pulsar//pulsar-broker/src/test/resources/certificate/public-key.client-rsa.pem\"\n privateKeyPath = \"/pulsar/pulsar-broker/src/test/resources/certificate/private-key.client-rsa.pem\"\n crypto_key_reader = CryptoKeyReader(publicKeyPath, privateKeyPath)\n client = Client(self.serviceUrl)\n topic = 'my-python-test-end-to-end-encryption'\n consumer = client.subscribe(topic=topic,\n subscription_name='my-subscription',\n crypto_key_reader=crypto_key_reader)\n producer = client.create_producer(topic=topic,\n encryption_key=\"client-rsa.pem\",\n crypto_key_reader=crypto_key_reader)\n producer.send('hello')\n msg = consumer.receive(TM)\n self.assertTrue(msg)\n self.assertEqual(msg.value(), 'hello')\n consumer.unsubscribe()\n client.close()\n\n def test_tls_auth3(self):\n certs_dir = '/pulsar/pulsar-broker/src/test/resources/authentication/tls/'\n if not os.path.exists(certs_dir):\n certs_dir = \"../../pulsar-broker/src/test/resources/authentication/tls/\"\n authPlugin = \"tls\"\n authParams = \"tlsCertFile:%s/client-cert.pem,tlsKeyFile:%s/client-key.pem\" % (certs_dir, certs_dir)\n\n client = Client(self.serviceUrlTls,\n tls_trust_certs_file_path=certs_dir + 'cacert.pem',\n tls_allow_insecure_connection=False,\n authentication=Authentication(authPlugin, authParams))\n\n consumer = client.subscribe('my-python-topic-tls-auth-3',\n 'my-sub',\n consumer_type=ConsumerType.Shared)\n producer = client.create_producer('my-python-topic-tls-auth-3')\n producer.send(b'hello')\n\n msg = consumer.receive(TM)\n self.assertTrue(msg)\n self.assertEqual(msg.data(), b'hello')\n\n with self.assertRaises(pulsar.Timeout):\n consumer.receive(100)\n\n client.close()\n\n def test_auth_junk_params(self):\n certs_dir = '/pulsar/pulsar-broker/src/test/resources/authentication/tls/'\n if not os.path.exists(certs_dir):\n certs_dir = \"../../pulsar-broker/src/test/resources/authentication/tls/\"\n authPlugin = \"someoldjunk.so\"\n authParams = \"blah\"\n client = Client(self.serviceUrlTls,\n tls_trust_certs_file_path=certs_dir + 'cacert.pem',\n tls_allow_insecure_connection=False,\n authentication=Authentication(authPlugin, authParams))\n\n with self.assertRaises(pulsar.ConnectError):\n client.subscribe('my-python-topic-auth-junk-params',\n 'my-sub',\n consumer_type=ConsumerType.Shared)\n\n def test_message_listener(self):\n client = Client(self.serviceUrl)\n\n received_messages = []\n\n def listener(consumer, msg):\n print(\"Got message: %s\" % msg)\n received_messages.append(msg)\n consumer.acknowledge(msg)\n\n client.subscribe('my-python-topic-listener',\n 'my-sub',\n consumer_type=ConsumerType.Exclusive,\n message_listener=listener)\n producer = client.create_producer('my-python-topic-listener')\n producer.send(b'hello-1')\n producer.send(b'hello-2')\n producer.send(b'hello-3')\n\n time.sleep(0.1)\n self.assertEqual(len(received_messages), 3)\n self.assertEqual(received_messages[0].data(), b\"hello-1\")\n self.assertEqual(received_messages[1].data(), b\"hello-2\")\n self.assertEqual(received_messages[2].data(), b\"hello-3\")\n client.close()\n\n def test_reader_simple(self):\n client = Client(self.serviceUrl)\n reader = client.create_reader('my-python-topic-reader-simple',\n MessageId.earliest)\n\n producer = client.create_producer('my-python-topic-reader-simple')\n producer.send(b'hello')\n\n msg = reader.read_next(TM)\n self.assertTrue(msg)\n self.assertEqual(msg.data(), b'hello')\n\n with self.assertRaises(pulsar.Timeout):\n reader.read_next(100)\n\n reader.close()\n client.close()\n\n def test_reader_on_last_message(self):\n client = Client(self.serviceUrl)\n producer = client.create_producer('my-python-topic-reader-on-last-message')\n\n for i in range(10):\n producer.send(b'hello-%d' % i)\n\n reader = client.create_reader('my-python-topic-reader-on-last-message',\n MessageId.latest)\n\n for i in range(10, 20):\n producer.send(b'hello-%d' % i)\n\n for i in range(10, 20):\n msg = reader.read_next(TM)\n self.assertTrue(msg)\n self.assertEqual(msg.data(), b'hello-%d' % i)\n\n reader.close()\n client.close()\n\n def test_reader_on_specific_message(self):\n num_of_msgs = 10\n client = Client(self.serviceUrl)\n producer = client.create_producer(\n 'my-python-topic-reader-on-specific-message')\n\n for i in range(num_of_msgs):\n producer.send(b'hello-%d' % i)\n\n reader1 = client.create_reader(\n 'my-python-topic-reader-on-specific-message',\n MessageId.earliest)\n\n for i in range(num_of_msgs//2):\n msg = reader1.read_next(TM)\n self.assertTrue(msg)\n self.assertEqual(msg.data(), b'hello-%d' % i)\n last_msg_id = msg.message_id()\n last_msg_idx = i\n\n reader2 = client.create_reader(\n 'my-python-topic-reader-on-specific-message',\n last_msg_id)\n\n # The reset would be effectively done on the next position relative to reset.\n # When available, we should test this behaviour with `startMessageIdInclusive` opt.\n from_msg_idx = last_msg_idx\n for i in range(from_msg_idx, num_of_msgs):\n msg = reader2.read_next(TM)\n self.assertTrue(msg)\n self.assertEqual(msg.data(), b'hello-%d' % i)\n\n reader1.close()\n reader2.close()\n client.close()\n\n def test_reader_on_specific_message_with_batches(self):\n client = Client(self.serviceUrl)\n producer = client.create_producer(\n 'my-python-topic-reader-on-specific-message-with-batches',\n batching_enabled=True,\n batching_max_publish_delay_ms=1000)\n\n for i in range(10):\n producer.send_async(b'hello-%d' % i, None)\n\n # Send one sync message to make sure everything was published\n producer.send(b'hello-10')\n\n reader1 = client.create_reader(\n 'my-python-topic-reader-on-specific-message-with-batches',\n MessageId.earliest)\n\n for i in range(5):\n msg = reader1.read_next(TM)\n last_msg_id = msg.message_id()\n\n reader2 = client.create_reader(\n 'my-python-topic-reader-on-specific-message-with-batches',\n last_msg_id)\n\n for i in range(5, 11):\n msg = reader2.read_next(TM)\n self.assertTrue(msg)\n self.assertEqual(msg.data(), b'hello-%d' % i)\n\n reader1.close()", "answers": [" reader2.close()"], "length": 1201, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "590f2f31-4233-432c-aa74-f7cba763c2f2", "reasoning": "In the test_reader_on_specific_message_with_batches method, after reading messages with reader1, the code closes reader1. Following the pattern of similar tests (e.g., test_reader_on_specific_message), the next steps are to close the second reader (reader2) and then close the client. Therefore, the immediate next line after reader1.close() is the call to close reader2.", "reasoning_model_answer": "reader2.close()", "assistant_with_reasoning": "\nIn the test_reader_on_specific_message_with_batches method, after reading messages with reader1, the code closes reader1. Following the pattern of similar tests (e.g., test_reader_on_specific_message), the next steps are to close the second reader (reader2) and then close the client. Therefore, the immediate next line after reader1.close() is the call to close reader2.\n\nreader2.close()", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 2.81, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 20957, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "reader2.close()", "score": 0.79, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "# Copyright (c) Twisted Matrix Laboratories.\n# See LICENSE for details.\n\n\"\"\"\nTest cases for the L{twisted.python.reflect} module.\n\"\"\"\n\nfrom __future__ import division, absolute_import\n\nimport os\nimport weakref\nfrom collections import deque\n\nfrom twisted.python.compat import _PY3\nfrom twisted.trial import unittest\nfrom twisted.trial.unittest import SynchronousTestCase as TestCase\nfrom twisted.python import reflect\nfrom twisted.python.reflect import (\n accumulateMethods, prefixedMethods, prefixedMethodNames,\n addMethodNamesToDict, fullyQualifiedName)\n\n\nclass Base(object):\n \"\"\"\n A no-op class which can be used to verify the behavior of\n method-discovering APIs.\n \"\"\"\n\n def method(self):\n \"\"\"\n A no-op method which can be discovered.\n \"\"\"\n\n\n\nclass Sub(Base):\n \"\"\"\n A subclass of a class with a method which can be discovered.\n \"\"\"\n\n\n\nclass Separate(object):\n \"\"\"\n A no-op class with methods with differing prefixes.\n \"\"\"\n\n def good_method(self):\n \"\"\"\n A no-op method which a matching prefix to be discovered.\n \"\"\"\n\n\n def bad_method(self):\n \"\"\"\n A no-op method with a mismatched prefix to not be discovered.\n \"\"\"\n\n\n\nclass AccumulateMethodsTests(TestCase):\n \"\"\"\n Tests for L{accumulateMethods} which finds methods on a class hierarchy and\n adds them to a dictionary.\n \"\"\"\n\n def test_ownClass(self):\n \"\"\"\n If x is and instance of Base and Base defines a method named method,\n L{accumulateMethods} adds an item to the given dictionary with\n C{\"method\"} as the key and a bound method object for Base.method value.\n \"\"\"\n x = Base()\n output = {}\n accumulateMethods(x, output)\n self.assertEqual({\"method\": x.method}, output)\n\n\n def test_baseClass(self):\n \"\"\"\n If x is an instance of Sub and Sub is a subclass of Base and Base\n defines a method named method, L{accumulateMethods} adds an item to the\n given dictionary with C{\"method\"} as the key and a bound method object\n for Base.method as the value.\n \"\"\"\n x = Sub()\n output = {}\n accumulateMethods(x, output)\n self.assertEqual({\"method\": x.method}, output)\n\n\n def test_prefix(self):\n \"\"\"\n If a prefix is given, L{accumulateMethods} limits its results to\n methods beginning with that prefix. Keys in the resulting dictionary\n also have the prefix removed from them.\n \"\"\"\n x = Separate()\n output = {}\n accumulateMethods(x, output, 'good_')\n self.assertEqual({'method': x.good_method}, output)\n\n\n\nclass PrefixedMethodsTests(TestCase):\n \"\"\"\n Tests for L{prefixedMethods} which finds methods on a class hierarchy and\n adds them to a dictionary.\n \"\"\"\n\n def test_onlyObject(self):\n \"\"\"\n L{prefixedMethods} returns a list of the methods discovered on an\n object.\n \"\"\"\n x = Base()\n output = prefixedMethods(x)\n self.assertEqual([x.method], output)\n\n\n def test_prefix(self):\n \"\"\"\n If a prefix is given, L{prefixedMethods} returns only methods named\n with that prefix.\n \"\"\"\n x = Separate()\n output = prefixedMethods(x, 'good_')\n self.assertEqual([x.good_method], output)\n\n\n\nclass PrefixedMethodNamesTests(TestCase):\n \"\"\"\n Tests for L{prefixedMethodNames}.\n \"\"\"\n def test_method(self):\n \"\"\"\n L{prefixedMethodNames} returns a list including methods with the given\n prefix defined on the class passed to it.\n \"\"\"\n self.assertEqual([\"method\"], prefixedMethodNames(Separate, \"good_\"))\n\n\n def test_inheritedMethod(self):\n \"\"\"\n L{prefixedMethodNames} returns a list included methods with the given\n prefix defined on base classes of the class passed to it.\n \"\"\"\n class Child(Separate):\n pass\n self.assertEqual([\"method\"], prefixedMethodNames(Child, \"good_\"))\n\n\n\nclass AddMethodNamesToDictTests(TestCase):\n \"\"\"\n Tests for L{addMethodNamesToDict}.\n \"\"\"\n def test_baseClass(self):\n \"\"\"\n If C{baseClass} is passed to L{addMethodNamesToDict}, only methods which\n are a subclass of C{baseClass} are added to the result dictionary.\n \"\"\"\n class Alternate(object):\n pass\n\n class Child(Separate, Alternate):\n def good_alternate(self):\n pass\n\n result = {}\n addMethodNamesToDict(Child, result, 'good_', Alternate)\n self.assertEqual({'alternate': 1}, result)\n\n\n\nclass Summer(object):\n \"\"\"\n A class we look up as part of the LookupsTests.\n \"\"\"\n\n def reallySet(self):\n \"\"\"\n Do something.\n \"\"\"\n\n\n\nclass LookupsTests(TestCase):\n \"\"\"\n Tests for L{namedClass}, L{namedModule}, and L{namedAny}.\n \"\"\"\n\n def test_namedClassLookup(self):\n \"\"\"\n L{namedClass} should return the class object for the name it is passed.\n \"\"\"\n self.assertIs(\n reflect.namedClass(\"twisted.test.test_reflect.Summer\"),\n Summer)\n\n\n def test_namedModuleLookup(self):\n \"\"\"\n L{namedModule} should return the module object for the name it is\n passed.\n \"\"\"\n from twisted.python import monkey\n self.assertIs(\n reflect.namedModule(\"twisted.python.monkey\"), monkey)\n\n\n def test_namedAnyPackageLookup(self):\n \"\"\"\n L{namedAny} should return the package object for the name it is passed.\n \"\"\"\n import twisted.python\n self.assertIs(\n reflect.namedAny(\"twisted.python\"), twisted.python)\n\n\n def test_namedAnyModuleLookup(self):\n \"\"\"\n L{namedAny} should return the module object for the name it is passed.\n \"\"\"\n from twisted.python import monkey\n self.assertIs(\n reflect.namedAny(\"twisted.python.monkey\"), monkey)\n\n\n def test_namedAnyClassLookup(self):\n \"\"\"\n L{namedAny} should return the class object for the name it is passed.\n \"\"\"\n self.assertIs(\n reflect.namedAny(\"twisted.test.test_reflect.Summer\"),\n Summer)\n\n\n def test_namedAnyAttributeLookup(self):\n \"\"\"\n L{namedAny} should return the object an attribute of a non-module,\n non-package object is bound to for the name it is passed.\n \"\"\"\n # Note - not assertIs because unbound method lookup creates a new\n # object every time. This is a foolishness of Python's object\n # implementation, not a bug in Twisted.\n self.assertEqual(\n reflect.namedAny(\n \"twisted.test.test_reflect.Summer.reallySet\"),\n Summer.reallySet)\n\n\n def test_namedAnySecondAttributeLookup(self):\n \"\"\"\n L{namedAny} should return the object an attribute of an object which\n itself was an attribute of a non-module, non-package object is bound to\n for the name it is passed.\n \"\"\"\n self.assertIs(\n reflect.namedAny(\n \"twisted.test.test_reflect.\"\n \"Summer.reallySet.__doc__\"),\n Summer.reallySet.__doc__)\n\n\n def test_importExceptions(self):\n \"\"\"\n Exceptions raised by modules which L{namedAny} causes to be imported\n should pass through L{namedAny} to the caller.\n \"\"\"\n self.assertRaises(\n ZeroDivisionError,\n reflect.namedAny, \"twisted.test.reflect_helper_ZDE\")\n # Make sure that there is post-failed-import cleanup\n self.assertRaises(\n ZeroDivisionError,\n reflect.namedAny, \"twisted.test.reflect_helper_ZDE\")\n self.assertRaises(\n ValueError,\n reflect.namedAny, \"twisted.test.reflect_helper_VE\")\n # Modules which themselves raise ImportError when imported should\n # result in an ImportError\n self.assertRaises(\n ImportError,\n reflect.namedAny, \"twisted.test.reflect_helper_IE\")\n\n\n def test_attributeExceptions(self):\n \"\"\"\n If segments on the end of a fully-qualified Python name represents\n attributes which aren't actually present on the object represented by\n the earlier segments, L{namedAny} should raise an L{AttributeError}.\n \"\"\"\n self.assertRaises(\n AttributeError,\n reflect.namedAny, \"twisted.nosuchmoduleintheworld\")\n # ImportError behaves somewhat differently between \"import\n # extant.nonextant\" and \"import extant.nonextant.nonextant\", so test\n # the latter as well.\n self.assertRaises(\n AttributeError,\n reflect.namedAny, \"twisted.nosuch.modulein.theworld\")\n self.assertRaises(\n AttributeError,\n reflect.namedAny,\n \"twisted.test.test_reflect.Summer.nosuchattribute\")\n\n\n def test_invalidNames(self):\n \"\"\"\n Passing a name which isn't a fully-qualified Python name to L{namedAny}\n should result in one of the following exceptions:\n - L{InvalidName}: the name is not a dot-separated list of Python\n objects\n - L{ObjectNotFound}: the object doesn't exist\n - L{ModuleNotFound}: the object doesn't exist and there is only one\n component in the name\n \"\"\"\n err = self.assertRaises(reflect.ModuleNotFound, reflect.namedAny,\n 'nosuchmoduleintheworld')\n self.assertEqual(str(err), \"No module named 'nosuchmoduleintheworld'\")\n\n # This is a dot-separated list, but it isn't valid!\n err = self.assertRaises(reflect.ObjectNotFound, reflect.namedAny,\n \"@#$@(#.!@(#!@#\")\n self.assertEqual(str(err), \"'@#$@(#.!@(#!@#' does not name an object\")\n\n err = self.assertRaises(reflect.ObjectNotFound, reflect.namedAny,\n \"tcelfer.nohtyp.detsiwt\")\n self.assertEqual(\n str(err),\n \"'tcelfer.nohtyp.detsiwt' does not name an object\")\n\n err = self.assertRaises(reflect.InvalidName, reflect.namedAny, '')\n self.assertEqual(str(err), 'Empty module name')\n\n for invalidName in ['.twisted', 'twisted.', 'twisted..python']:\n err = self.assertRaises(\n reflect.InvalidName, reflect.namedAny, invalidName)\n self.assertEqual(\n str(err),\n \"name must be a string giving a '.'-separated list of Python \"\n \"identifiers, not %r\" % (invalidName,))\n\n\n def test_requireModuleImportError(self):\n \"\"\"\n When module import fails with ImportError it returns the specified\n default value.\n \"\"\"\n for name in ['nosuchmtopodule', 'no.such.module']:\n default = object()\n\n result = reflect.requireModule(name, default=default)\n\n self.assertIs(result, default)\n\n\n def test_requireModuleDefaultNone(self):\n \"\"\"\n When module import fails it returns L{None} by default.\n \"\"\"\n result = reflect.requireModule('no.such.module')\n\n self.assertIsNone(result)\n\n\n def test_requireModuleRequestedImport(self):\n \"\"\"\n When module import succeed it returns the module and not the default\n value.\n \"\"\"\n from twisted.python import monkey\n default = object()\n\n self.assertIs(\n reflect.requireModule('twisted.python.monkey', default=default),\n monkey,\n )\n\n\n\nclass Breakable(object):\n\n breakRepr = False\n breakStr = False\n\n def __str__(self):\n if self.breakStr:\n raise RuntimeError(\"str!\")\n else:\n return ''\n\n\n def __repr__(self):\n if self.breakRepr:\n raise RuntimeError(\"repr!\")\n else:\n return 'Breakable()'\n\n\n\nclass BrokenType(Breakable, type):\n breakName = False\n\n def get___name__(self):\n if self.breakName:\n raise RuntimeError(\"no name\")\n return 'BrokenType'\n __name__ = property(get___name__)\n\n\n\nBTBase = BrokenType('BTBase', (Breakable,),\n {\"breakRepr\": True,\n \"breakStr\": True})\n\n\n\nclass NoClassAttr(Breakable):\n __class__ = property(lambda x: x.not_class)\n\n\n", "answers": ["class SafeReprTests(TestCase):"], "length": 1133, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "45e3c7fd-dfa5-412b-967e-014b7992b318", "reasoning": "The file defines several helper classes for testing reflect utilities. After defining NoClassAttr, the next logical code element is a new test case class that will use these helpers, typically named something like SafeReprTests and inheriting from TestCase. This matches the pattern used earlier in the file where test case classes are introduced after helper class definitions.", "reasoning_model_answer": "class SafeReprTests(TestCase):", "assistant_with_reasoning": "\nThe file defines several helper classes for testing reflect utilities. After defining NoClassAttr, the next logical code element is a new test case class that will use these helpers, typically named something like SafeReprTests and inheriting from TestCase. This matches the pattern used earlier in the file where test case classes are introduced after helper class definitions.\n\nclass SafeReprTests(TestCase):", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 5.203, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 12461, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "class SafeReprTests(TestCase):", "score": 1.0, "is_full_score": true, "is_nonzero_score": true}} {"input": "", "context": "/*\n * Copyright 2011 The Poderosa Project.\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n *\n * $Id: SCPClient.cs,v 1.2 2012/05/05 12:42:45 kzmi Exp $\n */\n\nusing System;\nusing System.Collections.Generic;\nusing System.Text;\nusing System.Threading;\nusing System.Diagnostics;\nusing System.IO;\nusing System.Globalization;\nusing System.Text.RegularExpressions;\n\nusing Granados.SSH1;\nusing Granados.SSH2;\nusing Granados.IO;\nusing Granados.IO.SSH2;\nusing Granados.Util;\nusing Granados.Poderosa.FileTransfer;\n\nnamespace Granados.Poderosa.SCP {\n\n /// \n /// Statuses of the file transfer\n /// \n public enum SCPFileTransferStatus {\n /// Not started\n None,\n /// Creating a local or remote directory\n CreateDirectory,\n /// Created a local or remote directory\n DirectoryCreated,\n /// Opening remote or local file\n Open,\n /// Data is transmitting\n Transmitting,\n /// File was closed successfully\n CompletedSuccess,\n /// File transfer was aborted by cancellation\n CompletedAbort,\n }\n\n /// \n /// Delegate notifies progress of the file transfer.\n /// \n /// Full path of the local file or local directory.\n /// Name of the file or directory.\n /// Status of the file transfer.\n /// File size. Zero if target is a directory.\n /// Transmitted data length. Zero if target is a directory.\n public delegate void SCPFileTransferProgressDelegate(\n string localFullPath, string fileName, SCPFileTransferStatus status, ulong fileSize, ulong transmitted);\n\n /// \n /// SCP Client\n /// \n /// \n /// \n /// This class is designed to be used in the worker thread.\n /// Each method blocks thread while transmitting the files.\n /// \n public class SCPClient {\n\n #region Private classes\n\n /// \n /// File or directory entry to create.\n /// Used in sink mode.\n /// \n private class SCPEntry {\n public readonly bool IsDirectory;\n public readonly int Permissions;\n public readonly long FileSize;\n public readonly string Name;\n\n public SCPEntry(bool isDirectory, int permissions, long fileSize, string name) {\n IsDirectory = isDirectory;\n Permissions = permissions;\n FileSize = fileSize;\n Name = name;\n }\n }\n\n /// \n /// Time modification informations.\n /// Used in sink mode.\n /// \n private class SCPModTime {\n public readonly DateTime MTime;\n public readonly DateTime ATime;\n\n public SCPModTime(DateTime mtime, DateTime atime) {\n MTime = mtime;\n ATime = atime;\n }\n }\n\n #endregion\n\n #region Private fields\n\n private readonly SSHConnection _connection;\n\n private Encoding _encoding = Encoding.UTF8;\n\n private int _defaultFilePermissions = 0x1a4; // 0644\n private int _defaultDirectoryPermissions = 0x1ed; // 0755\n\n private int _protocolTimeout = 5000;\n\n private static readonly byte[] ZERO = new byte[] { 0 };\n private static readonly DateTime EPOCH = new DateTime(1970, 1, 1, 0, 0, 0);\n\n #endregion\n\n #region Private constants\n\n private const int FILE_TRANSFER_BLOCK_SIZE = 10240; // FIXME: should it be flexible ?\n\n private const byte LF = 0xa;\n\n #endregion\n\n #region Properties\n\n /// \n /// Protocol timeout in milliseconds.\n /// \n public int ProtocolTimeout {\n get {\n return _protocolTimeout;\n }\n set {\n _protocolTimeout = value;\n }\n }\n\n /// \n /// Gets or sets encoding to convert path name or file name.\n /// \n public Encoding Encoding {\n get {\n return _encoding;\n }\n set {\n _encoding = value;\n }\n }\n\n /// \n /// Unix permissions used when creating a remote file.\n /// \n public int DefaultFilePermissions {\n get {\n return _defaultFilePermissions;\n }\n set {\n _defaultFilePermissions = value;\n }\n }\n\n /// \n /// Unix permissions used when creating a remote directory.\n /// \n public int DefaultDirectoryPermissions {\n get {\n return _defaultDirectoryPermissions;\n }\n set {\n _defaultDirectoryPermissions = value;\n }\n }\n\n #endregion\n\n #region Constructor\n\n /// \n /// Constructor\n /// \n /// SSH connection. Currently only SSH2 connection is accepted.\n public SCPClient(SSHConnection connection) {\n this._connection = connection;\n }\n\n #endregion\n\n #region Upload\n\n /// \n /// Upload files or directories.\n /// \n /// \n /// Unfortunately, Granados sends a command line in the ASCII encoding.\n /// So the \"remotePath\" must be an ASCII text.\n /// \n /// Local path (Windows' path)\n /// Remote path (Unix path)\n /// Specifies recursive mode\n /// Specifies to preserve time of the directory or file.\n /// An object to request the cancellation. Set null if the cancellation is not needed.\n /// Delegate to notify progress. Set null if notification is not needed.\n public void Upload(string localPath, string remotePath, bool recursive, bool preserveTime,\n Cancellation cancellation,\n SCPFileTransferProgressDelegate progressDelegate) {\n if (!IsAscii(remotePath))\n throw new SCPClientException(\"Remote path must consist of ASCII characters.\");\n\n bool isDirectory = Directory.Exists(localPath);\n if (!File.Exists(localPath) && !isDirectory)\n throw new SCPClientException(\"File or directory not found: \" + localPath);\n\n if (isDirectory && !recursive)\n throw new SCPClientException(\"Cannot copy directory in non-recursive mode\");\n\n string absLocalPath = Path.GetFullPath(localPath);\n\n string command = \"scp -t \";\n if (recursive)\n command += \"-r \";\n if (preserveTime)\n command += \"-p \";\n command += EscapeUnixPath(remotePath);\n\n using (SCPChannelStream stream = new SCPChannelStream()) {\n stream.Open(_connection, command, _protocolTimeout);\n CheckResponse(stream);\n\n if (isDirectory) { // implies recursive mode\n UploadDirectory(absLocalPath, stream, preserveTime, cancellation, progressDelegate);\n }\n else {\n UploadFile(absLocalPath, stream, preserveTime, cancellation, progressDelegate);\n }\n }\n }\n\n private bool UploadDirectory(string fullPath, SCPChannelStream stream, bool preserveTime,\n Cancellation cancellation,\n SCPFileTransferProgressDelegate progressDelegate) {\n\n Debug.Assert(fullPath != null);\n\n if (cancellation != null && cancellation.IsRequested) {\n return false; // cancel\n }\n\n string directoryName = Path.GetFileName(fullPath);\n if (directoryName != null) { // not a root directory\n if (progressDelegate != null)\n progressDelegate(fullPath, directoryName, SCPFileTransferStatus.CreateDirectory, 0, 0);\n\n if (preserveTime) {\n SendModTime(\n stream,\n Directory.GetLastWriteTimeUtc(fullPath),\n Directory.GetLastAccessTimeUtc(fullPath)\n );\n }\n\n string line = new StringBuilder()\n .Append('D')\n .Append(GetPermissionsText(true))\n .Append(\" 0 \")\n .Append(directoryName)\n .Append('\\n')\n .ToString();\n stream.Write(_encoding.GetBytes(line));\n CheckResponse(stream);\n\n if (progressDelegate != null)\n progressDelegate(fullPath, directoryName, SCPFileTransferStatus.DirectoryCreated, 0, 0);\n }\n\n foreach (String fullSubDirPath in Directory.GetDirectories(fullPath)) {\n bool continued = UploadDirectory(fullSubDirPath, stream, preserveTime, cancellation, progressDelegate);\n if (!continued)\n return false; // cancel\n }\n\n foreach (String fullFilePath in Directory.GetFiles(fullPath)) {\n bool continued = UploadFile(fullFilePath, stream, preserveTime, cancellation, progressDelegate);\n if (!continued)\n return false; // cancel\n }\n\n if (directoryName != null) { // not a root directory\n string line = \"E\\n\";\n stream.Write(_encoding.GetBytes(line));\n CheckResponse(stream);\n }\n\n return true; // continue\n }\n\n private bool UploadFile(string fullPath, SCPChannelStream stream, bool preserveTime,\n Cancellation cancellation,\n SCPFileTransferProgressDelegate progressDelegate) {\n\n Debug.Assert(fullPath != null);\n\n string fileName = Path.GetFileName(fullPath);\n FileInfo fileInfo = new FileInfo(fullPath);\n long fileSize = fileInfo.Length;\n ulong transmitted = 0;\n\n if (progressDelegate != null)\n progressDelegate(fullPath, fileName, SCPFileTransferStatus.Open, (ulong)fileSize, transmitted);\n\n if (preserveTime) {\n SendModTime(\n stream,\n File.GetLastWriteTimeUtc(fullPath),\n File.GetLastAccessTimeUtc(fullPath)\n );\n }\n\n using (FileStream fileStream = new FileStream(fullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) {\n string line = new StringBuilder()\n .Append('C')\n .Append(GetPermissionsText(false))\n .Append(' ')\n .Append(fileSize.ToString(NumberFormatInfo.InvariantInfo))\n .Append(' ')\n .Append(fileName)\n .Append('\\n')\n .ToString();\n stream.Write(_encoding.GetBytes(line));\n CheckResponse(stream);\n\n byte[] buff = new byte[FILE_TRANSFER_BLOCK_SIZE];\n\n long remain = fileSize;\n while (remain > 0) {\n if (cancellation != null && cancellation.IsRequested) {\n if (progressDelegate != null)\n progressDelegate(fullPath, fileName, SCPFileTransferStatus.CompletedAbort, (ulong)fileSize, transmitted);\n return false; // cancel\n }\n\n int readLength = fileStream.Read(buff, 0, buff.Length);\n if (readLength <= 0)\n break;\n if (readLength > remain)\n readLength = (int)remain;\n stream.Write(buff, readLength);\n remain -= readLength;\n\n transmitted += (ulong)readLength;\n if (progressDelegate != null)\n progressDelegate(fullPath, fileName, SCPFileTransferStatus.Transmitting, (ulong)fileSize, transmitted);\n }\n\n stream.Write(ZERO);\n CheckResponse(stream);\n }\n\n if (progressDelegate != null)\n progressDelegate(fullPath, fileName, SCPFileTransferStatus.CompletedSuccess, (ulong)fileSize, transmitted);\n\n return true;\n }\n\n private void SendModTime(SCPChannelStream stream, DateTime mtime, DateTime atime) {\n DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0);\n long mtimeSec = (mtime.Ticks - epoch.Ticks) / 10000000L;\n long mtimeUSec = ((mtime.Ticks - epoch.Ticks) % 10000000L) / 10L;\n long atimeSec = (atime.Ticks - epoch.Ticks) / 10000000L;\n long atimeUSec = ((atime.Ticks - epoch.Ticks) % 10000000L) / 10L;\n string line = new StringBuilder()\n .Append('T')\n .Append(mtimeSec.ToString(NumberFormatInfo.InvariantInfo))\n .Append(' ')\n .Append(mtimeUSec.ToString(NumberFormatInfo.InvariantInfo))\n .Append(' ')\n .Append(atimeSec.ToString(NumberFormatInfo.InvariantInfo))\n .Append(' ')\n .Append(atimeUSec.ToString(NumberFormatInfo.InvariantInfo))\n .Append('\\n')\n .ToString();\n stream.Write(_encoding.GetBytes(line));", "answers": [" CheckResponse(stream);"], "length": 1170, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "67e4e488-ed35-45d8-8775-4b61d29bf821", "reasoning": "The method SendModTime constructs a command line starting with 'T' to set modification times and writes it to the SCP channel stream. In the surrounding code, after each write to the stream (e.g., sending file headers or directory creation commands), the implementation immediately calls CheckResponse(stream) to verify the remote side's acknowledgment. Therefore, the next logical line after writing the line is a call to CheckResponse(stream) to validate the response.", "reasoning_model_answer": "CheckResponse(stream);", "assistant_with_reasoning": "\nThe method SendModTime constructs a command line starting with 'T' to set modification times and writes it to the SCP channel stream. In the surrounding code, after each write to the stream (e.g., sending file headers or directory creation commands), the implementation immediately calls CheckResponse(stream) to verify the remote side's acknowledgment. Therefore, the next logical line after writing the line is a call to CheckResponse(stream) to validate the response.\n\nCheckResponse(stream);", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 2.347, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 14350, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "CheckResponse(stream);", "score": 0.79, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "# -*- coding: utf-8 -*-\n'''\nWrap libsodium routines\n'''\n# pylint: disable=C0103\n# Import libnacl libs\nfrom libnacl.version import __version__\n# Import python libs\nimport ctypes\nimport sys\nimport os\n\n__SONAMES = (18, 17, 13, 10, 5, 4)\n\n\ndef _get_nacl():\n '''\n Locate the nacl c libs to use\n '''\n # Import libsodium\n if sys.platform.startswith('win'):\n try:\n return ctypes.cdll.LoadLibrary('libsodium')\n except OSError:\n pass\n for soname_ver in __SONAMES:\n try:\n return ctypes.cdll.LoadLibrary(\n 'libsodium-{0}'.format(soname_ver)\n )\n except OSError:\n pass\n msg = 'Could not locate nacl lib, searched for libsodium'\n raise OSError(msg)\n elif sys.platform.startswith('darwin'):\n try:\n return ctypes.cdll.LoadLibrary('libsodium.dylib')\n except OSError:\n pass\n try:\n libidx = __file__.find('lib')\n if libidx > 0:\n libpath = __file__[0:libidx+3] + '/libsodium.dylib'\n return ctypes.cdll.LoadLibrary(libpath)\n except OSError:\n msg = 'Could not locate nacl lib, searched for libsodium'\n raise OSError(msg)\n else:\n try:\n return ctypes.cdll.LoadLibrary('libsodium.so')\n except OSError:\n pass\n try:\n return ctypes.cdll.LoadLibrary('/usr/local/lib/libsodium.so')\n except OSError:\n pass\n try:\n libidx = __file__.find('lib')\n if libidx > 0:\n libpath = __file__[0:libidx+3] + '/libsodium.so'\n return ctypes.cdll.LoadLibrary(libpath)\n except OSError:\n pass\n\n for soname_ver in __SONAMES:\n try:\n return ctypes.cdll.LoadLibrary(\n 'libsodium.so.{0}'.format(soname_ver)\n )\n except OSError:\n pass\n try:\n # fall back to shipped libsodium, trust os version first\n libpath = os.path.join(os.path.dirname(__file__), 'libsodium.so')\n return ctypes.cdll.LoadLibrary(libpath)\n except OSError:\n pass\n msg = 'Could not locate nacl lib, searched for libsodium.so, '\n for soname_ver in __SONAMES:\n msg += 'libsodium.so.{0}, '.format(soname_ver)\n raise OSError(msg)\n\nnacl = _get_nacl()\n\n\n# Define exceptions\nclass CryptError(Exception):\n \"\"\"\n Base Exception for cryptographic errors\n \"\"\"\n\nsodium_init = nacl.sodium_init\nsodium_init.res_type = ctypes.c_int\nif sodium_init() < 0:\n raise RuntimeError('sodium_init() call failed!')\n\n# Define constants\ntry:\n crypto_box_SEALBYTES = nacl.crypto_box_sealbytes()\n HAS_SEAL = True\nexcept AttributeError:\n HAS_SEAL = False\n\ncrypto_box_SECRETKEYBYTES = nacl.crypto_box_secretkeybytes()\ncrypto_box_SEEDBYTES = nacl.crypto_box_seedbytes()\ncrypto_box_PUBLICKEYBYTES = nacl.crypto_box_publickeybytes()\ncrypto_box_NONCEBYTES = nacl.crypto_box_noncebytes()\ncrypto_box_ZEROBYTES = nacl.crypto_box_zerobytes()\ncrypto_box_BOXZEROBYTES = nacl.crypto_box_boxzerobytes()\ncrypto_box_BEFORENMBYTES = nacl.crypto_box_beforenmbytes()\ncrypto_scalarmult_BYTES = nacl.crypto_scalarmult_bytes()\ncrypto_scalarmult_SCALARBYTES = nacl.crypto_scalarmult_scalarbytes()\ncrypto_sign_BYTES = nacl.crypto_sign_bytes()\ncrypto_sign_SEEDBYTES = nacl.crypto_sign_secretkeybytes() // 2\ncrypto_sign_PUBLICKEYBYTES = nacl.crypto_sign_publickeybytes()\ncrypto_sign_SECRETKEYBYTES = nacl.crypto_sign_secretkeybytes()\ncrypto_box_MACBYTES = crypto_box_ZEROBYTES - crypto_box_BOXZEROBYTES\ncrypto_secretbox_KEYBYTES = nacl.crypto_secretbox_keybytes()\ncrypto_secretbox_NONCEBYTES = nacl.crypto_secretbox_noncebytes()\ncrypto_secretbox_ZEROBYTES = nacl.crypto_secretbox_zerobytes()\ncrypto_secretbox_BOXZEROBYTES = nacl.crypto_secretbox_boxzerobytes()\ncrypto_secretbox_MACBYTES = crypto_secretbox_ZEROBYTES - crypto_secretbox_BOXZEROBYTES\ncrypto_stream_KEYBYTES = nacl.crypto_stream_keybytes()\ncrypto_stream_NONCEBYTES = nacl.crypto_stream_noncebytes()\ncrypto_auth_BYTES = nacl.crypto_auth_bytes()\ncrypto_auth_KEYBYTES = nacl.crypto_auth_keybytes()\ncrypto_onetimeauth_BYTES = nacl.crypto_onetimeauth_bytes()\ncrypto_onetimeauth_KEYBYTES = nacl.crypto_onetimeauth_keybytes()\ncrypto_generichash_BYTES = nacl.crypto_generichash_bytes()\ncrypto_generichash_BYTES_MIN = nacl.crypto_generichash_bytes_min()\ncrypto_generichash_BYTES_MAX = nacl.crypto_generichash_bytes_max()\ncrypto_generichash_KEYBYTES = nacl.crypto_generichash_keybytes()\ncrypto_generichash_KEYBYTES_MIN = nacl.crypto_generichash_keybytes_min()\ncrypto_generichash_KEYBYTES_MAX = nacl.crypto_generichash_keybytes_max()\ncrypto_scalarmult_curve25519_BYTES = nacl.crypto_scalarmult_curve25519_bytes()\ncrypto_hash_BYTES = nacl.crypto_hash_sha512_bytes()\ncrypto_hash_sha256_BYTES = nacl.crypto_hash_sha256_bytes()\ncrypto_hash_sha512_BYTES = nacl.crypto_hash_sha512_bytes()\ncrypto_verify_16_BYTES = nacl.crypto_verify_16_bytes()\ncrypto_verify_32_BYTES = nacl.crypto_verify_32_bytes()\ncrypto_verify_64_BYTES = nacl.crypto_verify_64_bytes()\n# pylint: enable=C0103\n\n\n# Pubkey defs\n\n\ndef crypto_box_keypair():\n '''\n Generate and return a new keypair\n\n pk, sk = nacl.crypto_box_keypair()\n '''\n pk = ctypes.create_string_buffer(crypto_box_PUBLICKEYBYTES)\n sk = ctypes.create_string_buffer(crypto_box_SECRETKEYBYTES)\n nacl.crypto_box_keypair(pk, sk)\n return pk.raw, sk.raw\n\n\ndef crypto_box(msg, nonce, pk, sk):\n '''\n Using a public key and a secret key encrypt the given message. A nonce\n must also be passed in, never reuse the nonce\n\n enc_msg = nacl.crypto_box('secret message', , , )\n '''\n if len(pk) != crypto_box_PUBLICKEYBYTES:\n raise ValueError('Invalid public key')\n if len(sk) != crypto_box_SECRETKEYBYTES:\n raise ValueError('Invalid secret key')\n if len(nonce) != crypto_box_NONCEBYTES:\n raise ValueError('Invalid nonce')\n pad = b'\\x00' * crypto_box_ZEROBYTES + msg\n c = ctypes.create_string_buffer(len(pad))\n ret = nacl.crypto_box(c, pad, ctypes.c_ulonglong(len(pad)), nonce, pk, sk)\n if ret:\n raise CryptError('Unable to encrypt message')\n return c.raw[crypto_box_BOXZEROBYTES:]\n\n\ndef crypto_box_open(ctxt, nonce, pk, sk):\n '''\n Decrypts a message given the receivers private key, and senders public key\n '''\n if len(pk) != crypto_box_PUBLICKEYBYTES:\n raise ValueError('Invalid public key')\n if len(sk) != crypto_box_SECRETKEYBYTES:\n raise ValueError('Invalid secret key')\n if len(nonce) != crypto_box_NONCEBYTES:\n raise ValueError('Invalid nonce')\n pad = b'\\x00' * crypto_box_BOXZEROBYTES + ctxt\n msg = ctypes.create_string_buffer(len(pad))\n ret = nacl.crypto_box_open(\n msg,\n pad,\n ctypes.c_ulonglong(len(pad)),\n nonce,\n pk,\n sk)\n if ret:\n raise CryptError('Unable to decrypt ciphertext')\n return msg.raw[crypto_box_ZEROBYTES:]\n\n\ndef crypto_box_beforenm(pk, sk):\n '''\n Partially performs the computation required for both encryption and decryption of data\n '''\n if len(pk) != crypto_box_PUBLICKEYBYTES:\n raise ValueError('Invalid public key')\n if len(sk) != crypto_box_SECRETKEYBYTES:\n raise ValueError('Invalid secret key')\n k = ctypes.create_string_buffer(crypto_box_BEFORENMBYTES)\n ret = nacl.crypto_box_beforenm(k, pk, sk)\n if ret:\n raise CryptError('Unable to compute shared key')\n return k.raw\n\n\ndef crypto_box_afternm(msg, nonce, k):\n '''\n Encrypts a given a message, using partial computed data\n '''\n if len(k) != crypto_box_BEFORENMBYTES:\n raise ValueError('Invalid shared key')\n if len(nonce) != crypto_box_NONCEBYTES:\n raise ValueError('Invalid nonce')\n pad = b'\\x00' * crypto_box_ZEROBYTES + msg\n ctxt = ctypes.create_string_buffer(len(pad))\n ret = nacl.crypto_box_afternm(ctxt, pad, ctypes.c_ulonglong(len(pad)), nonce, k)\n if ret:\n raise CryptError('Unable to encrypt messsage')\n return ctxt.raw[crypto_box_BOXZEROBYTES:]\n\n\ndef crypto_box_open_afternm(ctxt, nonce, k):\n '''\n Decrypts a ciphertext ctxt given k\n '''\n if len(k) != crypto_box_BEFORENMBYTES:\n raise ValueError('Invalid shared key')\n if len(nonce) != crypto_box_NONCEBYTES:\n raise ValueError('Invalid nonce')\n pad = b'\\x00' * crypto_box_BOXZEROBYTES + ctxt\n msg = ctypes.create_string_buffer(len(pad))\n ret = nacl.crypto_box_open_afternm(\n msg,\n pad,\n ctypes.c_ulonglong(len(pad)),\n nonce,\n k)\n if ret:\n raise CryptError('unable to decrypt message')\n return msg.raw[crypto_box_ZEROBYTES:]\n\ndef crypto_box_seal(msg, pk):\n '''\n Using a public key to encrypt the given message. The identity of the sender cannot be verified.\n\n enc_msg = nacl.crypto_box_seal('secret message', )\n '''\n if not HAS_SEAL:\n raise ValueError('Underlying Sodium library does not support sealed boxes')\n if len(pk) != crypto_box_PUBLICKEYBYTES:\n raise ValueError('Invalid public key')\n if not isinstance(msg, bytes):\n raise TypeError('Message must be bytes')\n\n c = ctypes.create_string_buffer(len(msg) + crypto_box_SEALBYTES)\n ret = nacl.crypto_box_seal(c, msg, ctypes.c_ulonglong(len(msg)), pk)\n if ret:\n raise CryptError('Unable to encrypt message')\n return c.raw\n\ndef crypto_box_seal_open(ctxt, pk, sk):\n '''\n Decrypts a message given the receiver's public and private key.\n '''\n if not HAS_SEAL:\n raise ValueError('Underlying Sodium library does not support sealed boxes')\n if len(pk) != crypto_box_PUBLICKEYBYTES:\n raise ValueError('Invalid public key')\n if len(sk) != crypto_box_SECRETKEYBYTES:\n raise ValueError('Invalid secret key')\n if not isinstance(ctxt, bytes):\n raise TypeError('Message must be bytes')\n\n c = ctypes.create_string_buffer(len(ctxt) - crypto_box_SEALBYTES)\n ret = nacl.crypto_box_seal_open(c, ctxt, ctypes.c_ulonglong(len(ctxt)), pk, sk)\n if ret:\n raise CryptError('Unable to decrypt message')\n return c.raw\n\n# Signing functions\n\n\ndef crypto_sign_keypair():\n '''\n Generates a signing/verification key pair\n '''\n vk = ctypes.create_string_buffer(crypto_sign_PUBLICKEYBYTES)\n sk = ctypes.create_string_buffer(crypto_sign_SECRETKEYBYTES)", "answers": [" ret = nacl.crypto_sign_keypair(vk, sk)"], "length": 899, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "035999cc-0351-4b70-a9f1-07aa91a24014", "reasoning": "The function crypto_sign_keypair mirrors crypto_box_keypair: after allocating buffers for the public and secret keys, it must invoke the underlying libsodium function to fill them, then return the raw bytes. The immediate next line after creating the buffers is the call to nacl.crypto_sign_keypair with those buffers.", "reasoning_model_answer": "nacl.crypto_sign_keypair(vk, sk)", "assistant_with_reasoning": "\nThe function crypto_sign_keypair mirrors crypto_box_keypair: after allocating buffers for the public and secret keys, it must invoke the underlying libsodium function to fill them, then return the raw bytes. The immediate next line after creating the buffers is the call to nacl.crypto_sign_keypair with those buffers.\n\nnacl.crypto_sign_keypair(vk, sk)", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.434, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 10699, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "nacl.crypto_sign_keypair(vk, sk)", "score": 0.86, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "using System;\nusing System.Collections;\nusing System.Collections.Generic;\nusing Server;\nusing Server.Items;\nusing Server.Engines.CannedEvil;\n\nnamespace Server.Mobiles\n{\n\tpublic class Harrower : BaseCreature\n\t{\n\t\tpublic Type[] UniqueList{ get{ return new Type[] { typeof( AcidProofRobe ) }; } }\n\t\tpublic Type[] SharedList{ get{ return new Type[] { typeof( TheRobeOfBritanniaAri ) }; } }\n\t\tpublic Type[] DecorativeList{ get{ return new Type[] { typeof( EvilIdolSkull ), typeof( SkullPole ) }; } }\n\n\t\tprivate bool m_TrueForm;\n\t\tprivate Item m_GateItem;\n\t\tprivate List m_Tentacles;\n\t\tprivate Timer m_Timer;\n\n\t\tprivate class SpawnEntry\n\t\t{\n\t\t\tpublic Point3D m_Location;\n\t\t\tpublic Point3D m_Entrance;\n\n\t\t\tpublic SpawnEntry( Point3D loc, Point3D ent )\n\t\t\t{\n\t\t\t\tm_Location = loc;\n\t\t\t\tm_Entrance = ent;\n\t\t\t}\n\t\t}\n\n\t\tprivate static SpawnEntry[] m_Entries = new SpawnEntry[]\n\t\t\t{\n\t\t\t\tnew SpawnEntry( new Point3D( 5242, 945, -40 ), new Point3D( 1176, 2638, 0 ) ),\t// Destard\n\t\t\t\tnew SpawnEntry( new Point3D( 5225, 798, 0 ), new Point3D( 1176, 2638, 0 ) ),\t// Destard\n\t\t\t\tnew SpawnEntry( new Point3D( 5556, 886, 30 ), new Point3D( 1298, 1080, 0 ) ),\t// Despise\n\t\t\t\tnew SpawnEntry( new Point3D( 5187, 615, 0 ), new Point3D( 4111, 432, 5 ) ),\t\t// Deceit\n\t\t\t\tnew SpawnEntry( new Point3D( 5319, 583, 0 ), new Point3D( 4111, 432, 5 ) ),\t\t// Deceit\n\t\t\t\tnew SpawnEntry( new Point3D( 5713, 1334, -1 ), new Point3D( 2923, 3407, 8 ) ),\t// Fire\n\t\t\t\tnew SpawnEntry( new Point3D( 5860, 1460, -2 ), new Point3D( 2923, 3407, 8 ) ),\t// Fire\n\t\t\t\tnew SpawnEntry( new Point3D( 5328, 1620, 0 ), new Point3D( 5451, 3143, -60 ) ),\t// Terathan Keep\n\t\t\t\tnew SpawnEntry( new Point3D( 5690, 538, 0 ), new Point3D( 2042, 224, 14 ) ),\t// Wrong\n\t\t\t\tnew SpawnEntry( new Point3D( 5609, 195, 0 ), new Point3D( 514, 1561, 0 ) ),\t\t// Shame\n\t\t\t\tnew SpawnEntry( new Point3D( 5475, 187, 0 ), new Point3D( 514, 1561, 0 ) ),\t\t// Shame\n\t\t\t\tnew SpawnEntry( new Point3D( 6085, 179, 0 ), new Point3D( 4721, 3822, 0 ) ),\t// Hythloth\n\t\t\t\tnew SpawnEntry( new Point3D( 6084, 66, 0 ), new Point3D( 4721, 3822, 0 ) ),\t\t// Hythloth\n\t\t\t\tnew SpawnEntry( new Point3D( 5499, 2003, 0 ), new Point3D( 2499, 919, 0 ) ),\t// Covetous\n\t\t\t\tnew SpawnEntry( new Point3D( 5579, 1858, 0 ), new Point3D( 2499, 919, 0 ) )\t\t// Covetous\n\t\t\t};\n\n\t\tprivate static ArrayList m_Instances = new ArrayList();\n\n\t\tpublic static ArrayList Instances{ get{ return m_Instances; } }\n\n\t\tpublic static Harrower Spawn( Point3D platLoc, Map platMap )\n\t\t{\n\t\t\tif ( m_Instances.Count > 0 )\n\t\t\t\treturn null;\n\n\t\t\tSpawnEntry entry = m_Entries[Utility.Random( m_Entries.Length )];\n\n\t\t\tHarrower harrower = new Harrower();\n\n\t\t\tharrower.MoveToWorld( entry.m_Location, Map.Felucca );\n\n\t\t\tharrower.m_GateItem = new HarrowerGate( harrower, platLoc, platMap, entry.m_Entrance, Map.Felucca );\n\n\t\t\treturn harrower;\n\t\t}\n\n\t\tpublic static bool CanSpawn\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn ( m_Instances.Count == 0 );\n\t\t\t}\n\t\t}\n\n\t\t[Constructable]\n\t\tpublic Harrower() : base( AIType.AI_Mage, FightMode.Closest, 18, 1, 0.2, 0.4 )\n\t\t{\n\t\t\tm_Instances.Add( this );\n\n\t\t\tName = \"the harrower\";\n\t\t\tBodyValue = 146;\n\n\t\t\tSetStr( 900, 1000 );\n\t\t\tSetDex( 125, 135 );\n\t\t\tSetInt( 1000, 1200 );\n\n\t\t\tFame = 22500;\n\t\t\tKarma = -22500;\n\n\t\t\tVirtualArmor = 60;\n\n\t\t\tSetDamageType( ResistanceType.Physical, 50 );\n\t\t\tSetDamageType( ResistanceType.Energy, 50 );\n\n\t\t\tSetResistance( ResistanceType.Physical, 55, 65 );\n\t\t\tSetResistance( ResistanceType.Fire, 60, 80 );\n\t\t\tSetResistance( ResistanceType.Cold, 60, 80 );\n\t\t\tSetResistance( ResistanceType.Poison, 60, 80 );\n\t\t\tSetResistance( ResistanceType.Energy, 60, 80 );\n\n\t\t\tSetSkill( SkillName.Wrestling, 90.1, 100.0 );\n\t\t\tSetSkill( SkillName.Tactics, 90.2, 110.0 );\n\t\t\tSetSkill( SkillName.MagicResist, 120.2, 160.0 );\n\t\t\tSetSkill( SkillName.Magery, 120.0 );\n\t\t\tSetSkill( SkillName.EvalInt, 120.0 );\n\t\t\tSetSkill( SkillName.Meditation, 120.0 );\n\n\t\t\tm_Tentacles = new List();\n\n\t\t\tm_Timer = new TeleportTimer( this );\n\t\t\tm_Timer.Start();\n\t\t}\n\n\t\tpublic override void GenerateLoot()\n\t\t{\n\t\t\tAddLoot( LootPack.SuperBoss, 2 );\n\t\t\tAddLoot( LootPack.Meager );\n\t\t}\n\n\t\tpublic override bool AutoDispel{ get{ return true; } }\n\t\tpublic override bool Unprovokable{ get{ return true; } }\n\t\tpublic override Poison PoisonImmune{ get{ return Poison.Lethal; } }\n\n\t\tprivate static readonly double[] m_Offsets = new double[]\n\t\t\t{\n\t\t\t\tMath.Cos( 000.0 / 180.0 * Math.PI ), Math.Sin( 000.0 / 180.0 * Math.PI ),\n\t\t\t\tMath.Cos( 040.0 / 180.0 * Math.PI ), Math.Sin( 040.0 / 180.0 * Math.PI ),\n\t\t\t\tMath.Cos( 080.0 / 180.0 * Math.PI ), Math.Sin( 080.0 / 180.0 * Math.PI ),\n\t\t\t\tMath.Cos( 120.0 / 180.0 * Math.PI ), Math.Sin( 120.0 / 180.0 * Math.PI ),\n\t\t\t\tMath.Cos( 160.0 / 180.0 * Math.PI ), Math.Sin( 160.0 / 180.0 * Math.PI ),\n\t\t\t\tMath.Cos( 200.0 / 180.0 * Math.PI ), Math.Sin( 200.0 / 180.0 * Math.PI ),\n\t\t\t\tMath.Cos( 240.0 / 180.0 * Math.PI ), Math.Sin( 240.0 / 180.0 * Math.PI ),\n\t\t\t\tMath.Cos( 280.0 / 180.0 * Math.PI ), Math.Sin( 280.0 / 180.0 * Math.PI ),\n\t\t\t\tMath.Cos( 320.0 / 180.0 * Math.PI ), Math.Sin( 320.0 / 180.0 * Math.PI ),\n\t\t\t};\n\n\t\tpublic void Morph()\n\t\t{\n\t\t\tif ( m_TrueForm )\n\t\t\t\treturn;\n\n\t\t\tm_TrueForm = true;\n\n\t\t\tName = \"the true harrower\";\n\t\t\tBodyValue = 780;\n\t\t\tHue = 0x497;\n\n\t\t\tHits = HitsMax;\n\t\t\tStam = StamMax;\n\t\t\tMana = ManaMax;\n\n\t\t\tProcessDelta();\n\n\t\t\tSay( 1049499 ); // Behold my true form!\n\n\t\t\tMap map = this.Map;\n\n\t\t\tif ( map != null )\n\t\t\t{\n\t\t\t\tfor ( int i = 0; i < m_Offsets.Length; i += 2 )\n\t\t\t\t{\n\t\t\t\t\tdouble rx = m_Offsets[i];\n\t\t\t\t\tdouble ry = m_Offsets[i + 1];\n\n\t\t\t\t\tint dist = 0;\n\t\t\t\t\tbool ok = false;\n\t\t\t\t\tint x = 0, y = 0, z = 0;\n\n\t\t\t\t\twhile ( !ok && dist < 10 )\n\t\t\t\t\t{\n\t\t\t\t\t\tint rdist = 10 + dist;\n\n\t\t\t\t\t\tx = this.X + (int)(rx * rdist);\n\t\t\t\t\t\ty = this.Y + (int)(ry * rdist);\n\t\t\t\t\t\tz = map.GetAverageZ( x, y );\n\n\t\t\t\t\t\tif ( !(ok = map.CanFit( x, y, this.Z, 16, false, false ) ) )\n\t\t\t\t\t\t\tok = map.CanFit( x, y, z, 16, false, false );\n\n\t\t\t\t\t\tif ( dist >= 0 )\n\t\t\t\t\t\t\tdist = -(dist + 1);\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tdist = -(dist - 1);\n\t\t\t\t\t}\n\n\t\t\t\t\tif ( !ok )\n\t\t\t\t\t\tcontinue;\n\n\t\t\t\t\tHarrowerTentacles spawn = new HarrowerTentacles( this );\n\n\t\t\t\t\tspawn.Team = this.Team;\n\n\t\t\t\t\tspawn.MoveToWorld( new Point3D( x, y, z ), map );\n\n\t\t\t\t\tm_Tentacles.Add( spawn );\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t[CommandProperty( AccessLevel.GameMaster )]\n\t\tpublic override int HitsMax{ get{ return m_TrueForm ? 65000 : 30000; } }\n\n\t\t[CommandProperty( AccessLevel.GameMaster )]\n\t\tpublic override int ManaMax{ get{ return 5000; } }\n\n\t\tpublic Harrower( Serial serial ) : base( serial )\n\t\t{", "answers": ["\t\t\tm_Instances.Add( this );"], "length": 982, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "8077bebe-0419-47f1-a812-d5f1b3ed8558", "reasoning": "The code defines a deserialization constructor for Harrower. In the regular constructor, the instance is added to the static m_Instances list. To keep the same tracking on deserialization, the next line should add the current object to that list. This matches typical patterns in Ultima Online server scripts.", "reasoning_model_answer": "m_Instances.Add(this);", "assistant_with_reasoning": "\nThe code defines a deserialization constructor for Harrower. In the regular constructor, the instance is added to the static m_Instances list. To keep the same tracking on deserialization, the next line should add the current object to that list. This matches typical patterns in Ultima Online server scripts.\n\nm_Instances.Add(this);", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.793, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 6562, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "m_Instances.Add(this);", "score": 0.9, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "// Generated from SQLANN.g4 by ANTLR 4.3\n\n/*\n * Copyright (c) Welsiton Ferreira (wfcreations@gmail.com)\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n *\n * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * \n * Redistributions in binary form must reproduce the above copyright notice, this\n * list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n *\n * Neither the name of the WFCreation nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR\n * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\n * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\npackage br.com.wfcreations.annms.core.sqlann;\n\n\nimport org.antlr.v4.runtime.ParserRuleContext;\nimport org.antlr.v4.runtime.misc.NotNull;\nimport org.antlr.v4.runtime.tree.ErrorNode;\nimport org.antlr.v4.runtime.tree.TerminalNode;\n\n/**\n * This class provides an empty implementation of {@link SQLANNListener},\n * which can be extended to create a listener which only needs to handle a subset\n * of the available methods.\n */\npublic class SQLANNBaseListener implements SQLANNListener {\n\t/**\n\t * {@inheritDoc}\n\t *\n\t *

    The default implementation does nothing.

    \n\t */\n\t@Override public void enterIntegerDataType(@NotNull SQLANNParser.IntegerDataTypeContext ctx) { }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t *

    The default implementation does nothing.

    \n\t */\n\t@Override public void exitIntegerDataType(@NotNull SQLANNParser.IntegerDataTypeContext ctx) { }\n\n\t/**\n\t * {@inheritDoc}\n\t *\n\t *

    The default implementation does nothing.

    \n\t */\n\t@Override public void enterShowNeuralNetworksStatement(@NotNull SQLANNParser.ShowNeuralNetworksStatementContext ctx) { }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t *

    The default implementation does nothing.

    \n\t */\n\t@Override public void exitShowNeuralNetworksStatement(@NotNull SQLANNParser.ShowNeuralNetworksStatementContext ctx) { }\n\n\t/**\n\t * {@inheritDoc}\n\t *\n\t *

    The default implementation does nothing.

    \n\t */\n\t@Override public void enterRunStatement(@NotNull SQLANNParser.RunStatementContext ctx) { }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t *

    The default implementation does nothing.

    \n\t */\n\t@Override public void exitRunStatement(@NotNull SQLANNParser.RunStatementContext ctx) { }\n\n\t/**\n\t * {@inheritDoc}\n\t *\n\t *

    The default implementation does nothing.

    \n\t */\n\t@Override public void enterParam(@NotNull SQLANNParser.ParamContext ctx) { }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t *

    The default implementation does nothing.

    \n\t */\n\t@Override public void exitParam(@NotNull SQLANNParser.ParamContext ctx) { }\n\n\t/**\n\t * {@inheritDoc}\n\t *\n\t *

    The default implementation does nothing.

    \n\t */\n\t@Override public void enterStringValue(@NotNull SQLANNParser.StringValueContext ctx) { }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t *

    The default implementation does nothing.

    \n\t */\n\t@Override public void exitStringValue(@NotNull SQLANNParser.StringValueContext ctx) { }\n\n\t/**\n\t * {@inheritDoc}\n\t *\n\t *

    The default implementation does nothing.

    \n\t */\n\t@Override public void enterDropNeuralNetworkStatement(@NotNull SQLANNParser.DropNeuralNetworkStatementContext ctx) { }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t *

    The default implementation does nothing.

    \n\t */\n\t@Override public void exitDropNeuralNetworkStatement(@NotNull SQLANNParser.DropNeuralNetworkStatementContext ctx) { }\n\n\t/**\n\t * {@inheritDoc}\n\t *\n\t *

    The default implementation does nothing.

    \n\t */\n\t@Override public void enterBooleanValue(@NotNull SQLANNParser.BooleanValueContext ctx) { }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t *

    The default implementation does nothing.

    \n\t */\n\t@Override public void exitBooleanValue(@NotNull SQLANNParser.BooleanValueContext ctx) { }\n\n\t/**\n\t * {@inheritDoc}\n\t *\n\t *

    The default implementation does nothing.

    \n\t */\n\t@Override public void enterCreateNeuralNetworkStatement(@NotNull SQLANNParser.CreateNeuralNetworkStatementContext ctx) { }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t *

    The default implementation does nothing.

    \n\t */\n\t@Override public void exitCreateNeuralNetworkStatement(@NotNull SQLANNParser.CreateNeuralNetworkStatementContext ctx) { }\n\n\t/**\n\t * {@inheritDoc}\n\t *\n\t *

    The default implementation does nothing.

    \n\t */\n\t@Override public void enterBooleanDataType(@NotNull SQLANNParser.BooleanDataTypeContext ctx) { }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t *

    The default implementation does nothing.

    \n\t */\n\t@Override public void exitBooleanDataType(@NotNull SQLANNParser.BooleanDataTypeContext ctx) { }\n\n\t/**\n\t * {@inheritDoc}\n\t *\n\t *

    The default implementation does nothing.

    \n\t */\n\t@Override public void enterValues(@NotNull SQLANNParser.ValuesContext ctx) { }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t *

    The default implementation does nothing.

    \n\t */\n\t@Override public void exitValues(@NotNull SQLANNParser.ValuesContext ctx) { }\n\n\t/**\n\t * {@inheritDoc}\n\t *\n\t *

    The default implementation does nothing.

    \n\t */\n\t@Override public void enterDataAttribute(@NotNull SQLANNParser.DataAttributeContext ctx) { }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t *

    The default implementation does nothing.

    \n\t */\n\t@Override public void exitDataAttribute(@NotNull SQLANNParser.DataAttributeContext ctx) { }\n\n\t/**\n\t * {@inheritDoc}\n\t *\n\t *

    The default implementation does nothing.

    \n\t */\n\t@Override public void enterStatements(@NotNull SQLANNParser.StatementsContext ctx) { }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t *

    The default implementation does nothing.

    \n\t */\n\t@Override public void exitStatements(@NotNull SQLANNParser.StatementsContext ctx) { }\n\n\t/**\n\t * {@inheritDoc}\n\t *\n\t *

    The default implementation does nothing.

    \n\t */\n\t@Override public void enterNullValue(@NotNull SQLANNParser.NullValueContext ctx) { }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t *

    The default implementation does nothing.

    \n\t */\n\t@Override public void exitNullValue(@NotNull SQLANNParser.NullValueContext ctx) { }\n\n\t/**\n\t * {@inheritDoc}\n\t *\n\t *

    The default implementation does nothing.

    \n\t */\n\t@Override public void enterIntegerValue(@NotNull SQLANNParser.IntegerValueContext ctx) { }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t *

    The default implementation does nothing.

    \n\t */\n\t@Override public void exitIntegerValue(@NotNull SQLANNParser.IntegerValueContext ctx) { }\n\n\t/**\n\t * {@inheritDoc}\n\t *\n\t *

    The default implementation does nothing.

    \n\t */\n\t@Override public void enterListDataType(@NotNull SQLANNParser.ListDataTypeContext ctx) { }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t *

    The default implementation does nothing.

    \n\t */\n\t@Override public void exitListDataType(@NotNull SQLANNParser.ListDataTypeContext ctx) { }\n\n\t/**\n\t * {@inheritDoc}\n\t *\n\t *

    The default implementation does nothing.

    \n\t */\n\t@Override public void enterShowDataStatement(@NotNull SQLANNParser.ShowDataStatementContext ctx) { }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t *

    The default implementation does nothing.

    \n\t */\n\t@Override public void exitShowDataStatement(@NotNull SQLANNParser.ShowDataStatementContext ctx) { }\n\n\t/**\n\t * {@inheritDoc}\n\t *\n\t *

    The default implementation does nothing.

    \n\t */\n\t@Override public void enterRealValue(@NotNull SQLANNParser.RealValueContext ctx) { }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t *

    The default implementation does nothing.

    \n\t */\n\t@Override public void exitRealValue(@NotNull SQLANNParser.RealValueContext ctx) { }\n\n\t/**\n\t * {@inheritDoc}\n\t *\n\t *

    The default implementation does nothing.

    \n\t */\n\t@Override public void enterTrainStatement(@NotNull SQLANNParser.TrainStatementContext ctx) { }\n\t/**", "answers": ["\t * {@inheritDoc}"], "length": 976, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "f52bd191-f8be-467c-9fcf-49dfce7fe1eb", "reasoning": "The code follows the ANTLR listener pattern: each rule has an enter and exit method, each preceded by a Javadoc comment block starting with /**. After the enterTrainStatement method, a new comment block begins with /**. The next line after that opening comment is the first line of the Javadoc content, which is ' * {@inheritDoc}'. So the next line of code is that comment line.", "reasoning_model_answer": "* {@inheritDoc}", "assistant_with_reasoning": "\nThe code follows the ANTLR listener pattern: each rule has an enter and exit method, each preceded by a Javadoc comment block starting with /**. After the enterTrainStatement method, a new comment block begins with /**. The next line after that opening comment is the first line of the Javadoc content, which is ' * {@inheritDoc}'. So the next line of code is that comment line.\n\n* {@inheritDoc}", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 6.155, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 8509, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "* {@inheritDoc}", "score": 0.94, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "\"\"\"\n* Copyright 2008 Google Inc.\n* Copyright 2011 Bob Hampton\n*\n* Licensed under the Apache License, Version 2.0 (the \"License\"); you may not\n* use this file except in compliance with the License. You may obtain a copy of\n* the License at\n*\n* http:#www.apache.org/licenses/LICENSE-2.0\n*\n* Unless required by applicable law or agreed to in writing, software\n* distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n* License for the specific language governing permissions and limitations under\n* the License.\n\"\"\"\n\nimport math\n\nfrom pyjamas import DOM\nfrom __pyjamas__ import JS, doc\nfrom pyjamas.ui.Widget import Widget\n\nfrom pyjamas import Window\n\n\nfrom pyjamas.Canvas.GWTCanvasImplIEConsts import BUTT, DESTINATION_OVER, SOURCE_OVER\nfrom pyjamas.Canvas import GWTCanvasConsts\nfrom pyjamas.Canvas.JSOStack import JSOStack\nfrom pyjamas.Canvas import PathElement\nfrom pyjamas.Canvas.VMLContext import VMLContext\nfrom pyjamas.Canvas.VMLContext import VMLStyle\nfrom pyjamas.Canvas.Color import Color\nfrom pyjamas.Canvas.CanvasGradientImplIE6 import CanvasGradientImplIE6\n\ndef addNamespace():\n JS(\"\"\"\n if (!$doc['namespaces'][\"v\"]) {\n $doc['namespaces']['add'](\"v\", \"urn:schemas-microsoft-com:vml\");\n $doc['createStyleSheet']()['cssText'] = \"v\\\\:*{behavior:url(#default#VML);}\";\n }\n \"\"\")\n\n\n\"\"\"*\n* Deferred binding implementation of GWTCanvas for IE6. It is an implementation\n* of canvas on top of VML.\n\"\"\"\nclass GWTCanvasImplIE6:\n\n def __init__(self):\n try:\n ns = doc().namespaces.item(\"v\")\n except:\n doc().namespaces.add(\"v\", \"urn:schemas-microsoft-com:vml\")\n doc().createStyleSheet().cssText = \"v\\\\:*{behavior:url(#default#VML);}\"\n\n\n\n \"\"\"*\n * This will be used for an array join. Currently a bit faster than\n * StringBuilder.append() & toString() because of the extra collections\n * overhead.\n \"\"\"\n self.pathStr = JSOStack()\n\n \"\"\"*\n * Stack uses preallocated arrays which makes push() slightly faster than\n * [].push() since each push is simply an indexed setter.\n \"\"\"\n self.contextStack = []\n\n self.currentX = 0\n\n self.currentY = 0\n\n self.parentElement = None\n\n self.parentHeight = 0\n\n self.parentWidth = 0\n\n\n\n def arc(self, x, y, radius, startAngle, endAngle, anticlockwise):\n self.pathStr.append(PathElement.arc(x, y, radius, startAngle, endAngle,\n anticlockwise, self))\n\n\n def beginPath(self):\n self.pathStr.clear()\n\n\n def clear(self, width=0, height=0):\n self.pathStr.clear()\n DOM.setInnerHTML(self.parentElement, \"\")\n\n def closePath(self):\n self.pathStr.append(PathElement.closePath())\n\n\n def createElement(self):\n self.context = VMLContext()\n self.matrix = self.context.matrix\n return self.createParentElement()\n\n\n def createParentElement(self):\n self.parentElement = DOM.createElement(\"div\")\n DOM.setStyleAttribute(self.parentElement, \"overflow\", \"hidden\")\n return self.parentElement\n\n def setFont(self, font):\n pass\n # NOT IMPLEMENTED\n\n\n def cubicCurveTo(self, cp1x, cp1y, cp2x, cp2y, x, y):\n self.pathStr.append(PathElement.bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y, self))\n self.currentX = x\n self.currentY = y\n\n\n def drawImage(self, img, *args):\n\n if isinstance(img, Widget):\n img = img.getElement()\n fullWidth = img.width\n fullHeight = img.height\n\n if len(args) == 8:\n sourceX = args[0]\n sourceY = args[1]\n sourceWidth = args[2]\n sourceHeight = args[3]\n destX = args[4]\n destY = args[5]\n destWidth = args[6]\n destHeight = args[7]\n elif len(args) == 4:\n sourceX = 0\n sourceY = 0\n sourceWidth = fullWidth\n sourceHeight = fullHeight\n destX = args[0]\n destY = args[1]\n destWidth = args[2]\n destHeight = args[3]\n elif len(args) == 2:\n sourceX = 0\n sourceY = 0\n sourceWidth = fullWidth\n sourceHeight = fullHeight\n destX = args[0]\n destY = args[1]\n destWidth = fullWidth\n destHeight = fullHeight\n\n vmlStr = [] # JSOStack.getScratchArray()\n\n vmlStr.append(\"\")\n\n self.insert(\"BeforeEnd\", ''.join(vmlStr))\n\n def appendGradient(self, style, shapeStr):\n colorStops = style.gradient.colorStops\n length = len(colorStops)\n\n shapeStr.append(\"\\\" color=\\\"\")\n shapeStr.append(str(colorStops[0].color))\n shapeStr.append(\"\\\" color2=\\\"\")\n shapeStr.append(str(colorStops[length - 1].color))\n shapeStr.append(\"\\\" type=\\\"\")\n shapeStr.append(style.gradient.type)\n\n if style.gradient.type == 'gradient':\n #Window.alert(\" gdx: \" + str(style.gradient.dx) +\n # \" gdy: \" + str(style.gradient.dy) +\n # \" gl: \" + str(style.gradient.length) +\n # \" ga: \" + str(style.gradient.angle))\n # Now add all the color stops\n colors = \"\"\n for i in range(1, len(colorStops)):\n cs = colorStops[i]\n #Window.alert(\"color stop offset: \" + str(cs.offset))\n stopPosn = cs.offset\n colors += \"%d%%\" % (int(stopPosn * 100 ))\n colors += str(cs.color) + \",\"\n\n shapeStr.append(\"\\\" colors=\\\"\")\n shapeStr.append(colors)\n\n else:\n \"\"\"\n gradientradial under VML is limited to rectangular gradients\n see http://msdn.microsoft.com/en-us/library/bb264135%28v=vs.85%29.aspx\n so while this code is here, the results will never be what the rest\n of the world would expect - go figure\n \"\"\"\n minX = self.pathStr.getMinCoordX()\n maxX = self.pathStr.getMaxCoordX()\n minY = self.pathStr.getMinCoordY()\n maxY = self.pathStr.getMaxCoordY()\n\n dx = maxX - minX\n dy = maxY - minY\n\n fillLength = math.sqrt((dx * dx) + (dy * dy))\n\n #Window.alert(\"fillLength: \" + str(fillLength) +\n # \" gdx: \" + str(style.gradient.dx) +\n # \" gdy: \" + str(style.gradient.dy) +\n # \" gl: \" + str(style.gradient.length) +\n # \" ga: \" + str(style.gradient.angle) +\n # \" gsr: \" + str(style.gradient.startRad) +\n # \" ger: \" + str(style.gradient.endRad))\n\n # need some proper math to calculate the focus position\n focusX = 50\n focusY = 50\n\n # Now add all the color stops\n colors = \"\"\n for i in range(1, len(colorStops)):\n cs = colorStops[i]\n #Window.alert(\"color stop: \" + str(cs.offset))\n stopPosn = cs.offset\n #Window.alert(\"color stopPosn: \" + str(stopPosn))\n colors += \"%d%%\" % (int(stopPosn * 100 ))\n colors += str(cs.color) + \",\"\n\n shapeStr.append(\"\\\" colors=\\\"\")\n shapeStr.append(colors)\n\n shapeStr.append(\"\\\" focusposition=\\\"\")\n shapeStr.append(str(focusX))\n shapeStr.append(\"%,\")\n shapeStr.append(str(focusY))\n shapeStr.append(\"%,\")\n\n shapeStr.append(\"\\\" angle=\\\"\")\n shapeStr.append(str(style.gradient.angle))\n\n def appendStroke(self, shapeStr):\n\n shapeStr.append(\" 0:\n self.appendGradient(self.context.strokeStyle, shapeStr)\n else:\n shapeStr.append(\" color=\\\"\")\n shapeStr.append(str(self.context.strokeStyle.color))\n\n shapeStr.append(\"\\\" miterlimit=\\\"\")\n shapeStr.append(str(self.context.miterLimit))\n shapeStr.append(\"\\\" joinstyle=\\\"\")\n shapeStr.append(self.context.lineJoin)\n shapeStr.append(\"\\\" endcap=\\\"\")\n shapeStr.append(self.context.lineCap)\n\n shapeStr.append(\"\\\">\")\n\n\n def appendFill(self, shapeStr):\n\n shapeStr.append(\" 0:\n self.appendGradient(self.context.fillStyle, shapeStr)\n else:\n shapeStr.append(\" color=\\\"\")\n shapeStr.append(str(self.context.fillStyle.color))\n\n shapeStr.append(\"\\\">\")\n\n\n def fill(self):\n if len(self.pathStr) == 0:\n return\n\n shapeStr = [] #JSOStack.getScratchArray()\n shapeStr.append(\"\")\n\n self.appendFill(shapeStr)\n\n shapeStr.append(\"\")\n\n daStr = ''.join(shapeStr)\n #Window.alert(\"Fill: \" + daStr)\n self.insert(self.context.globalCompositeOperation, daStr)\n\n def stroke(self):\n if len(self.pathStr) == 0:\n return\n\n shapeStr = [] #JSOStack.getScratchArray()\n shapeStr.append(\"\")\n\n self.appendStroke(shapeStr)\n\n shapeStr.append(\"\")\n\n daStr = ''.join(shapeStr)\n #Window.alert(\"Stroke: \" + daStr)\n self.insert(self.context.globalCompositeOperation, daStr)\n\n def fillRect(self, x, y, w, h):\n w += x\n h += y\n self.beginPath()\n self.moveTo(x, y)\n self.lineTo(x, h)\n self.lineTo(w, h)\n self.lineTo(w, y)\n self.closePath()\n self.fill()\n self.pathStr.clear()\n\n\n def getContext(self):\n return self.context\n\n\n def getCoordX(self, matrix, x, y):\n coordX = int(math.floor((math.floor(10 * (matrix[0] * x + matrix[1]\n * y + matrix[2]) - 4.5))))\n # record current point to derive bounding box of current open path.\n self.pathStr.logCoordX(coordX / 10)\n return coordX\n\n\n def getCoordY(self, matrix, x, y):", "answers": [" coordY = int(math.floor((math.floor(10 * (matrix[3] * x + matrix[4]"], "length": 1075, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "ed70f7eb-d9b9-4570-8c34-7d53dc80a82c", "reasoning": "The code defines getCoordX using matrix[0], matrix[1], matrix[2] and logs the X coordinate. The next method getCoordY should mirror this logic using the Y components of the transformation matrix (matrix[3], matrix[4], matrix[5]) and log the Y coordinate. The first line of its body computes the Y coordinate similarly, so the next line after the method header is the computation of coordY.", "reasoning_model_answer": "coordY = int(math.floor((math.floor(10 * (matrix[3] * x + matrix[4] * y + matrix[5]) - 4.5))))", "assistant_with_reasoning": "\nThe code defines getCoordX using matrix[0], matrix[1], matrix[2] and logs the X coordinate. The next method getCoordY should mirror this logic using the Y components of the transformation matrix (matrix[3], matrix[4], matrix[5]) and log the Y coordinate. The first line of its body computes the Y coordinate similarly, so the next line after the method header is the computation of coordY.\n\ncoordY = int(math.floor((math.floor(10 * (matrix[3] * x + matrix[4] * y + matrix[5]) - 4.5))))", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 5.664, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 13725, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "coordY = int(math.floor((math.floor(10 * (matrix[3] * x + matrix[4] * y + matrix[5]) - 4.5))))", "score": 0.79, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "package org.schwa.dr;\n\nimport java.io.ByteArrayInputStream;\nimport java.io.ByteArrayOutputStream;\nimport java.io.EOFException;\nimport java.io.IOException;\nimport java.util.HashMap;\nimport java.util.Iterator;\nimport java.util.Map;\n\nimport org.msgpack.core.buffer.InputStreamBufferInput;\nimport org.msgpack.core.MessagePackFactory;\nimport org.msgpack.core.MessagePacker;\nimport org.msgpack.core.MessageUnpacker;\nimport org.msgpack.value.holder.ValueHolder;\n\nimport org.schwa.dr.runtime.RTAnnSchema;\nimport org.schwa.dr.runtime.RTFactory;\nimport org.schwa.dr.runtime.RTFieldSchema;\nimport org.schwa.dr.runtime.RTManager;\nimport org.schwa.dr.runtime.RTStoreSchema;\n\n\n/**\n * Reads in docrep documents of type T from the input stream provided in the constructor.\n * This class implements the {@link Iterator} interface, providing an interator for that yields\n * documents of type T.\n *\n * @author Tim Dawborn\n **/\npublic final class Reader implements Iterable, Iterator {\n /** docrep wire protocol version that this reader knows how to read. **/\n public static final byte WIRE_VERSION = 3;\n\n private final ByteArrayInputStream in;\n private final DocSchema docSchema;\n private final MessageUnpacker unpacker;\n private T doc;\n\n /**\n * Constructs a new docrep reader given the input stream and document schema.\n *\n * @param in The input stream to read from. This needs to be an input stream which has full\n * {@link java.io.InputStream#mark} support to implement lazy loading correctly. To\n * ensure this is the case, the input stream must currently be a\n * {@link ByteArrayInputStream}.\n * @param docSchema The {@link DocSchema} instance to use for reading. Unlike the other docrep\n * APIs, this argument cannot be optional as you cannot be the .class attribute\n * of a generic type due to type erasure.\n **/\n public Reader(ByteArrayInputStream in, DocSchema docSchema) {\n this.in = in;\n this.docSchema = docSchema;\n this.unpacker = new MessageUnpacker(new InputStreamBufferInput(in, 1)); // We don't want the InputStreamBufferInput to do any buffering since we need to refer to the underlying ByteArrayInputStream directly to implement lazyness.\n readNext();\n }\n\n /**\n * Returns this same object as an {@link Iterator} to comply with the {@link Iterable} interface.\n **/\n @Override // Iterable\n public Iterator iterator() {\n return this;\n }\n\n /**\n * Returns whether or not the reader iterator has any more documents to read in from the input\n * stream.\n **/\n @Override // Iterator\n public boolean hasNext() {\n return doc != null;\n }\n\n /**\n * Reads the next document from the input stream and returns it.\n **/\n @Override // Iterator\n public T next() {\n final T doc = this.doc;\n readNext();\n return doc;\n }\n\n /**\n * This optional method from {@link Iterator} is unsupported.\n *\n * @throws UnsupportedOperationException\n **/\n @Override // Iterator\n public void remove() {\n throw new UnsupportedOperationException();\n }\n\n private void readNext() {\n try {\n _readNext();\n }\n catch (IOException e) {\n throw new ReaderException(e);\n }\n catch (InstantiationException e) {\n throw new DocrepException(e);\n }\n catch (IllegalAccessException e) {\n throw new DocrepException(e);\n }\n }\n\n private void _readNext() throws IOException, InstantiationException, IllegalAccessException {\n // ::= \n\n // Read the wire format version before, and ensure we know how to read that version.\n // ::= UINT\n byte wireVersion;\n try {\n wireVersion = unpacker.unpackByte();\n }\n catch (EOFException e) {\n doc = null;\n return;\n }\n if (wireVersion != WIRE_VERSION)\n throw new ReaderException(\"Invalid wire format version. Stream has version \" + wireVersion + \" but I can only read version \" + WIRE_VERSION + \". Ensure the input is not plain text.\");\n\n // Construct the lazy runtime manager for the document.\n final RTManager rt = RTFactory.create();\n doc = (T) docSchema.getKlass().newInstance();\n doc.setDRRT(rt);\n\n // Map of each of the registered types.\n Map klassNameMap = new HashMap();\n klassNameMap.put(\"__meta__\", docSchema);\n for (AnnSchema ann : docSchema.getSchemas())\n klassNameMap.put(ann.getSerial(), ann);\n\n // Keep track of the temporary mapping of pointer field to the store_id that they point to.\n Map rtFieldSchemaToStoreIds = new HashMap();\n\n // Keep track of the klass_id of __meta__.\n Integer klassIdMeta = null;\n\n // Read the klasses header.\n // ::= [ ]\n final int nklasses = unpacker.unpackArrayHeader();\n for (int k = 0; k != nklasses; k++) {\n // ::= ( , )\n final int npair = unpacker.unpackArrayHeader();\n if (npair != 2)\n throw new ReaderException(\"Invalid sized tuple read in: expected 2 elements but found \" + npair);\n\n // Read in the class name and check that we have a registered class with this name.\n RTAnnSchema rtAnnSchema;\n final String klassName = unpacker.unpackString();\n final AnnSchema schema = klassNameMap.get(klassName);\n if (schema == null)\n rtAnnSchema = new RTAnnSchema(k, klassName);\n else\n rtAnnSchema = new RTAnnSchema(k, klassName, schema);\n rt.addAnn(rtAnnSchema);\n\n // Keep track of the klass_id of __meta__.\n if (klassName.equals(\"__meta__\"))\n klassIdMeta = k;\n\n // ::= [ ]\n final int nfields = unpacker.unpackArrayHeader();\n for (int f = 0; f != nfields; f++) {\n String fieldName = null;\n int storeId = -1;\n boolean isPointer = false, isSelfPointer = false, isSlice = false, isCollection = false;\n\n // ::= { : }\n final int nitems = unpacker.unpackMapHeader();\n for (int i = 0; i != nitems; ++i) {\n final byte key = unpacker.unpackByte();\n switch (key) {\n case 0: // NAME\n fieldName = unpacker.unpackString();\n break;\n case 1: // POINTER_TO\n storeId = unpacker.unpackInt();\n isPointer = true;\n break;\n case 2: // IS_SLICE\n unpacker.unpackNil();\n isSlice = true;\n break;\n case 3: // IS_SELF_POINTER\n unpacker.unpackNil();\n isSelfPointer = true;\n break;\n case 4: // IS_COLLECTION\n unpacker.unpackNil();\n isCollection = true;\n break;\n default:\n throw new ReaderException(\"Unknown value \" + ((int) key) + \" as key in map\");\n }\n } // for each field.\n if (fieldName == null)\n throw new ReaderException(\"Field number \" + (f + 1) + \" did not contain a NAME key\");\n\n // See if the read in field exists on the registered class's schema.\n RTFieldSchema rtFieldSchema;\n if (rtAnnSchema.isLazy())\n rtFieldSchema = new RTFieldSchema(f, fieldName, null, isCollection, isSelfPointer, isSlice);\n else {\n // Try and find the field on the registered class.\n FieldSchema fieldDef = null;\n for (FieldSchema field : rtAnnSchema.getDef().getFields()) {\n if (field.getSerial().equals(fieldName)) {\n fieldDef = field;\n break;\n }\n }\n rtFieldSchema = new RTFieldSchema(f, fieldName, null, isCollection, isSelfPointer, isSlice, fieldDef);\n\n // Perform some sanity checks that the type of data on the stream is what we're expecting.\n if (fieldDef != null) {\n if (isPointer != fieldDef.isPointer())\n throw new ReaderException(\"Field '\" + fieldName + \"' of class '\" + klassName + \"' has IS_POINTER as \" + isPointer + \" on the stream, but \" + fieldDef.isPointer() + \" on the class's field\");\n if (isSlice != fieldDef.isSlice())\n throw new ReaderException(\"Field '\" + fieldName + \"' of class '\" + klassName + \"' has IS_SLICE as \" + isSlice + \" on the stream, but \" + fieldDef.isSlice() + \" on the class's field\");\n if (isSelfPointer != fieldDef.isSelfPointer())\n throw new ReaderException(\"Field '\" + fieldName + \"' of class '\" + klassName + \"' has IS_SELF_POINTER as \" + isSelfPointer + \" on the stream, but \" + fieldDef.isSelfPointer() + \" on the class's field\");\n if (isCollection != fieldDef.isCollection())\n throw new ReaderException(\"Field '\" + fieldName + \"' of class '\" + klassName + \"' has IS_COLLECTION as \" + isCollection + \" on the stream, but \" + fieldDef.isCollection() + \" on the class's field\");\n }\n }\n\n rtAnnSchema.addField(rtFieldSchema);\n if (isPointer)\n rtFieldSchemaToStoreIds.put(rtFieldSchema, storeId);\n } // for each field\n } // for each klass\n\n if (klassIdMeta == null)\n throw new ReaderException(\"Did not read in a __meta__ class\");\n final RTAnnSchema rtDocSchema = rt.getSchema(klassIdMeta);\n rt.setDocSchema(rtDocSchema);\n\n // Read the stores header.\n // ::= [ ]\n final int nstores = unpacker.unpackArrayHeader();\n for (int n = 0; n != nstores; n++) {\n // ::= ( , , )\n final int ntriple = unpacker.unpackArrayHeader();\n if (ntriple != 3)\n throw new ReaderException(\"Invalid sized tuple read in: expected 3 elements but found \" + ntriple);\n final String storeName = unpacker.unpackString();\n final int klassId = unpacker.unpackInt();\n final int nElem = unpacker.unpackInt();\n\n // Sanity check on the value of the klassId.\n if (klassId >= rt.getSchemas().size())\n throw new ReaderException(\"klassId value \" + klassId + \" >= number of klasses (\" + rt.getSchemas().size() + \")\");\n\n // Lookup the store on the Doc class.\n StoreSchema def = null;\n for (StoreSchema store : docSchema.getStores()) {\n if (store.getSerial().equals(storeName)) {\n def = store;\n break;\n }\n }\n\n final RTAnnSchema klass = rt.getSchema(klassId);\n RTStoreSchema rtStoreSchema;\n if (def == null)", "answers": [" rtStoreSchema = new RTStoreSchema(n, storeName, klass, null, nElem);"], "length": 1295, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "dc59f764-0ea1-40d6-8eba-e17a1560a598", "reasoning": "The code is inside the loop that reads each store definition. It has just checked if the store definition 'def' is null, meaning the store is not declared in the schema. In that case it must create a new RTStoreSchema instance for this unknown store. The variable rtStoreSchema is declared earlier, so the next line should assign it a new RTStoreSchema constructed with the store name, its class schema, and element count.", "reasoning_model_answer": "rtStoreSchema = new RTStoreSchema(storeName, klass, nElem);", "assistant_with_reasoning": "\nThe code is inside the loop that reads each store definition. It has just checked if the store definition 'def' is null, meaning the store is not declared in the schema. In that case it must create a new RTStoreSchema instance for this unknown store. The variable rtStoreSchema is declared earlier, so the next line should assign it a new RTStoreSchema constructed with the store name, its class schema, and element count.\n\nrtStoreSchema = new RTStoreSchema(storeName, klass, nElem);", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.199, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 10610, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "rtStoreSchema = new RTStoreSchema(storeName, klass, nElem);", "score": 0.87, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/**\n * Copyright 2007-2016, Kaazing Corporation. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.kaazing.gateway.service.http.proxy;\n\nimport static org.kaazing.gateway.transport.http.HttpHeaders.HEADER_CONNECTION;\nimport static org.kaazing.gateway.transport.http.HttpHeaders.HEADER_LOCATION;\nimport static org.kaazing.gateway.transport.http.HttpHeaders.HEADER_SET_COOKIE;\nimport static org.kaazing.gateway.transport.http.HttpHeaders.HEADER_UPGRADE;\nimport static org.kaazing.gateway.transport.http.HttpHeaders.HEADER_VIA;\nimport static org.kaazing.gateway.transport.http.HttpStatus.CLIENT_NOT_FOUND;\nimport static org.kaazing.gateway.transport.http.HttpStatus.INFO_SWITCHING_PROTOCOLS;\nimport static org.kaazing.gateway.transport.http.HttpHeaders.HEADER_FORWARDED;\nimport static org.kaazing.gateway.transport.http.HttpHeaders.HEADER_X_FORWARDED_FOR;\nimport static org.kaazing.gateway.transport.http.HttpHeaders.HEADER_X_FORWARDED_HOST;\nimport static org.kaazing.gateway.transport.http.HttpHeaders.HEADER_X_FORWARDED_PROTO;\nimport static org.kaazing.gateway.transport.http.HttpHeaders.HEADER_X_FORWARDED_SERVER;\nimport static java.lang.String.format;\n\nimport java.net.URI;\nimport java.util.Collection;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.TreeSet;\nimport java.util.UUID;\nimport java.util.regex.Pattern;\nimport java.util.stream.Collectors;\nimport java.util.stream.StreamSupport;\n\nimport org.apache.mina.core.future.CloseFuture;\nimport org.apache.mina.core.future.ConnectFuture;\nimport org.apache.mina.core.future.IoFutureListener;\nimport org.apache.mina.core.session.IoSession;\nimport org.apache.mina.core.session.IoSessionInitializer;\nimport org.kaazing.gateway.resource.address.ResourceAddress;\nimport org.kaazing.gateway.resource.address.http.HttpResourceAddress;\nimport org.kaazing.gateway.resource.address.uri.URIUtils;\nimport org.kaazing.gateway.service.ServiceContext;\nimport org.kaazing.gateway.service.ServiceProperties;\nimport org.kaazing.gateway.service.proxy.AbstractProxyAcceptHandler;\nimport org.kaazing.gateway.service.proxy.AbstractProxyHandler;\nimport org.kaazing.gateway.transport.BridgeSession;\nimport org.kaazing.gateway.transport.IoHandlerAdapter;\nimport org.kaazing.gateway.transport.http.DefaultHttpSession;\nimport org.kaazing.gateway.transport.http.HttpAcceptSession;\nimport org.kaazing.gateway.transport.http.HttpConnectSession;\nimport org.kaazing.gateway.transport.http.HttpSession;\nimport org.kaazing.gateway.transport.http.HttpStatus;\nimport org.kaazing.mina.core.session.IoSessionEx;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nclass HttpProxyServiceHandler extends AbstractProxyAcceptHandler {\n\n private static final Logger LOGGER = LoggerFactory.getLogger(\"service.http.proxy\");\n private static final String VIA_HEADER_FORMATTER = \"1.1 kaazing-%s\";\n private static final String FORWARDED_INJECT = \"inject\";\n private static final String FORWARDED_EXCLUDE = \"exclude\";\n private static final String FORWARDED_IGNORE = \"ignore\";\n private static final String FORWARDED_FOR = \"for\";\n private static final String FORWARDED_BY = \"by\";\n private static final String FORWARDED_PROTO = \"proto\";\n private static final String FORWARDED_HOST = \"host\";\n\n private static final Set KNOWN_SIMPLE_PROPERTIES;\n static {\n Set set = new HashSet<>();\n set.add(\"rewrite-cookie-domain\");\n set.add(\"rewrite-cookie-path\");\n set.add(\"rewrite-location\");\n set.add(\"use-forwarded\");\n KNOWN_SIMPLE_PROPERTIES = Collections.unmodifiableSet(set);\n }\n private static final Set KNOWN_NESTED_PROPERTIES;\n static {\n Set set = new HashSet<>();\n set.add(\"cookie-domain-mapping\");\n set.add(\"cookie-path-mapping\");\n set.add(\"location-mapping\");\n KNOWN_NESTED_PROPERTIES = Collections.unmodifiableSet(set);\n }\n\n private final String viaHeader;\n private static final Set USE_FORWARDED_VALUES;\n static {\n Set set = new HashSet<>();\n set.add(FORWARDED_INJECT);\n set.add(FORWARDED_EXCLUDE);\n set.add(FORWARDED_IGNORE);\n USE_FORWARDED_VALUES = Collections.unmodifiableSet(set);\n }\n\n private String connectURI;\n private String useForwarded;\n private String serviceName;\n private int remoteClientPort;\n private boolean rewriteCookieDomain;\n private boolean rewriteCookiePath;\n private boolean rewriteLocation;\n private Map cookieDomainMap;\n private Map cookiePathMap;\n private Map locationMap;\n\n public HttpProxyServiceHandler() {\n viaHeader = String.format(VIA_HEADER_FORMATTER, UUID.randomUUID());\n }\n\n void init() {\n ServiceContext serviceContext = getServiceContext();\n serviceName = serviceContext.getServiceName();\n\n Collection acceptURIs = serviceContext.getAccepts();\n Collection connectURIs = serviceContext.getConnects();\n\n String acceptURI = acceptURIs.iterator().next();\n connectURI = connectURIs.iterator().next();\n\n validateProperties(serviceContext);\n\n ServiceProperties properties = serviceContext.getProperties();\n\n rewriteCookieDomain = \"enabled\".equals(properties.get(\"rewrite-cookie-domain\"));\n rewriteCookiePath = \"enabled\".equals(properties.get(\"rewrite-cookie-path\"));\n rewriteLocation = !\"disabled\".equals(properties.get(\"rewrite-location\"));\n\n cookieDomainMap = new HashMap<>();\n if (rewriteCookieDomain) {\n List cookieDomainProperties = properties.getNested(\"cookie-domain-mapping\");\n for (ServiceProperties sp : cookieDomainProperties) {\n cookieDomainMap.put(sp.get(\"from\"), sp.get(\"to\"));\n }\n }\n\n cookiePathMap = new HashMap<>();\n if (rewriteCookiePath) {\n List cookiePathProperties = properties.getNested(\"cookie-path-mapping\");\n for (ServiceProperties sp : cookiePathProperties) {\n cookiePathMap.put(sp.get(\"from\"), sp.get(\"to\"));\n }\n }\n\n locationMap = new HashMap<>();\n if (rewriteLocation) {\n List locationProperties = properties.getNested(\"location-mapping\");\n for (ServiceProperties sp : locationProperties) {\n locationMap.put(sp.get(\"from\"), sp.get(\"to\"));\n }\n locationMap.put(connectURI, acceptURI);\n }\n\n useForwarded = properties.get(\"use-forwarded\");\n if (useForwarded == null) {\n useForwarded = FORWARDED_IGNORE;\n }\n if (!USE_FORWARDED_VALUES.contains(useForwarded)) {\n throw new IllegalArgumentException(serviceContext.getServiceName()\n + \" http.proxy service specifies unknown property value : \" + useForwarded + \" for use-forwarded\");\n }\n }\n\n private void validateProperties(ServiceContext serviceContext) {\n ServiceProperties properties = serviceContext.getProperties();\n\n // validate all properties: rewrite-cookie-domain, rewrite-cookie-path, rewrite-location\n Iterable simpleProperties = properties.simplePropertyNames();\n Set unknownProperties = StreamSupport.stream(simpleProperties.spliterator(), false)\n .filter(p -> !KNOWN_SIMPLE_PROPERTIES.contains(p))\n .collect(Collectors.toSet());\n Iterable nestedProperties = properties.nestedPropertyNames();\n StreamSupport.stream(nestedProperties.spliterator(), false)\n .filter(p -> !KNOWN_NESTED_PROPERTIES.contains(p))\n .forEach(unknownProperties::add);\n if (!unknownProperties.isEmpty()) {\n throw new IllegalArgumentException(serviceContext.getServiceName() +\n \" http.proxy service specifies unknown properties : \" + unknownProperties);\n }\n }\n\n \n\n @Override\n protected AbstractProxyHandler createConnectHandler() {\n return new ConnectHandler();\n }\n\n @Override\n public void sessionOpened(IoSession session) {\n \t// get the port number of the remote client\n \tBridgeSession bridgeSession = (BridgeSession) session;\n \tremoteClientPort = BridgeSession.REMOTE_ADDRESS.get(bridgeSession).getTransport().getResource().getPort();\n if (!session.isClosing()) {\n final DefaultHttpSession acceptSession = (DefaultHttpSession) session;\n // final Subject subject = ((IoSessionEx) acceptSession).getSubject();\n\n // log warning first time we see Http 1.0 request\n if (acceptSession.getVersion().toString().equals(\"HTTP/1.0\")) {\n if (this.serviceName != null) {\n LOGGER.warn(String.format(\n \"http.proxy service %s received an HTTP 1.0 request. HTTP 1.0 is not explicitly supported.\",\n this.serviceName));\n } else {\n LOGGER.warn(\"http.proxy service received an HTTP 1.0 request. HTTP 1.0 is not explicitly supported.\");\n }\n }\n\n if (!validateRequestPath(acceptSession)) {\n acceptSession.setStatus(CLIENT_NOT_FOUND);\n acceptSession.close(false);\n return;\n }\n if (!validateNoLoopDetected(acceptSession)) {\n return;\n }\n\n ConnectSessionInitializer sessionInitializer = new ConnectSessionInitializer(acceptSession);\n String resolvedConnectURI = computeConnectURI(acceptSession, URI.create(connectURI)).toASCIIString();\n ConnectFuture future = getServiceContext().connect(resolvedConnectURI, getConnectHandler(), sessionInitializer);\n future.addListener(new ConnectListener(acceptSession));\n super.sessionOpened(acceptSession);\n }\n }\n\n private URI computeConnectURI(DefaultHttpSession acceptSession, URI connectURI) {\n String acceptPath = acceptSession.getServicePath().getPath();\n String requestUri = acceptSession.getRequestURI().toString();\n return URI.create(connectURI + requestUri.substring(acceptPath.length()));\n }\n\n private boolean validateRequestPath(DefaultHttpSession acceptSession) {\n URI requestURI = acceptSession.getRequestURI();\n String acceptPath = acceptSession.getServicePath().getPath();\n String requestPath = requestURI.normalize().getPath();\n\n return requestPath.startsWith(acceptPath);\n }\n\n\n /**\n * Helper method performing loop detection\n * @param acceptSession - session parameter\n * @return - whether a loop was detected or not\n */\n private boolean validateNoLoopDetected(DefaultHttpSession acceptSession) {\n List viaHeaders = acceptSession.getReadHeaders(HEADER_VIA);\n if (viaHeaders != null && viaHeaders.stream().anyMatch(h -> h.equals(viaHeader))) {\n LOGGER.warn(\"Connection to \" + getConnectURIs().iterator().next() +\n \" failed due to loop detection [\" + acceptSession + \"->]\");\n acceptSession.setStatus(HttpStatus.SERVER_LOOP_DETECTED);\n acceptSession.close(true);\n return false;\n }\n return true;\n }\n\n /*\n * Initializer for connect session. It adds the processed accept session headers on the connect session\n */\n private class ConnectSessionInitializer implements IoSessionInitializer {\n private final DefaultHttpSession acceptSession;\n\n ConnectSessionInitializer(DefaultHttpSession acceptSession) {\n this.acceptSession = acceptSession;\n }\n\n @Override\n public void initializeSession(IoSession session, ConnectFuture future) {\n HttpConnectSession connectSession = (HttpConnectSession) session;\n connectSession.setVersion(acceptSession.getVersion());\n connectSession.setMethod(acceptSession.getMethod());\n URI connectURI = connectSession.getRequestURI();\n connectSession.setRequestURI(connectURI);\n processRequestHeaders(acceptSession, connectSession);\n }\n\n }\n\n private class ConnectListener implements IoFutureListener {\n private final DefaultHttpSession acceptSession;\n\n ConnectListener(DefaultHttpSession acceptSession) {", "answers": [" this.acceptSession = acceptSession;"], "length": 898, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "31096055-61f7-46ba-804b-5694c59fbb79", "reasoning": "The code defines a private inner class ConnectListener with a field acceptSession and a constructor that takes a DefaultHttpSession parameter. Following the pattern used in the ConnectSessionInitializer constructor, the next line should assign the passed argument to the field, i.e., this.acceptSession = acceptSession;.", "reasoning_model_answer": "this.acceptSession = acceptSession;", "assistant_with_reasoning": "\nThe code defines a private inner class ConnectListener with a field acceptSession and a constructor that takes a DefaultHttpSession parameter. Following the pattern used in the ConnectSessionInitializer constructor, the next line should assign the passed argument to the field, i.e., this.acceptSession = acceptSession;.\n\nthis.acceptSession = acceptSession;", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 2.503, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 13193, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "this.acceptSession = acceptSession;", "score": 0.85, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "#!/usr/bin/env python\n# Licensed to Cloudera, Inc. under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. Cloudera, Inc. licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n# Utilities for Thrift\n\nimport Queue\nimport logging\nimport socket\nimport threading\nimport time\nimport sasl\nimport sys\n\nfrom thrift.Thrift import TType, TApplicationException\nfrom thrift.transport.TSocket import TSocket\nfrom thrift.transport.TSSLSocket import TSSLSocket\nfrom thrift.transport.TTransport import TBufferedTransport, TFramedTransport, TMemoryBuffer,\\\n TTransportException\nfrom thrift.protocol.TBinaryProtocol import TBinaryProtocol\nfrom thrift.protocol.TMultiplexedProtocol import TMultiplexedProtocol\nfrom desktop.lib.python_util import create_synchronous_io_multiplexer\nfrom desktop.lib.thrift_sasl import TSaslClientTransport\nfrom desktop.lib.exceptions import StructuredException, StructuredThriftTransportException\n\n# The maximum depth that we will recurse through a \"jsonable\" structure\n# while converting to thrift. This prevents us from infinite recursion\n# in the case of circular references.\nMAX_RECURSION_DEPTH = 50\n\n# When a thrift call finishes, the level at which we log its duration\n# depends on the number of millis the call took.\nWARN_LEVEL_CALL_DURATION_MS = 5000\nINFO_LEVEL_CALL_DURATION_MS = 1000\n\nclass LifoQueue(Queue.Queue):\n '''\n Variant of Queue that retrieves most recently added entries first.\n\n This LIFO Queue is included in python2.7 (or 2.6) and later,\n but it's a simple subclass, so we \"backport\" it here.\n '''\n\n def _init(self, maxsize):\n self.queue = []\n self.maxsize = maxsize\n\n def _qsize(self, len=len):\n return len(self.queue)\n\n def _put(self, item):\n self.queue.append(item)\n\n def _get(self):\n return self.queue.pop()\n\nclass ConnectionConfig(object):\n \"\"\" Struct-like class encapsulating the configuration of a Thrift client. \"\"\"\n def __init__(self, klass, host, port, service_name,\n use_sasl=False,\n use_ssl=False,\n kerberos_principal=\"thrift\",\n mechanism='GSSAPI',\n username='hue',\n password='hue',\n ca_certs=None,\n keyfile=None,\n certfile=None,\n validate=False,\n timeout_seconds=45,\n transport='buffered',\n multiple=False):\n \"\"\"\n @param klass The thrift client class\n @param host Host to connect to\n @param port Port to connect to\n @param service_name A human-readable name to describe the service\n @param use_sasl If true, will use KERBEROS or PLAIN over SASL to authenticate\n @param use_ssl If true, will use ca_certs, keyfile, and certfile to create TLS connection\n @param mechanism: GSSAPI or PLAIN if SASL\n @param username: username if PLAIN SASL or LDAP only\n @param password: password if PLAIN LDAP only\n @param kerberos_principal The Kerberos service name to connect to.\n NOTE: for a service like fooservice/foo.blah.com@REALM only\n specify \"fooservice\", NOT the full principal name.\n @param ca_certs certificate authority certificates\n @param keyfile private key file\n @param certfile certificate file\n @param validate Validate the certificate received from server\n @param timeout_seconds Timeout for thrift calls\n @param transport string representation of thrift transport to use\n @param multiple Whether Use MultiplexedProtocol\n \"\"\"\n self.klass = klass\n self.host = host\n self.port = port\n self.service_name = service_name\n self.use_sasl = use_sasl\n self.use_ssl = use_ssl\n self.mechanism = mechanism\n self.username = username\n self.password = password\n self.kerberos_principal = kerberos_principal\n self.ca_certs = ca_certs\n self.keyfile = keyfile\n self.certfile = certfile\n self.validate = validate\n self.timeout_seconds = timeout_seconds\n self.transport = transport\n self.multiple = multiple\n\n def __str__(self):\n return ', '.join(map(str, [self.klass, self.host, self.port, self.service_name, self.use_sasl, self.kerberos_principal, self.timeout_seconds,\n self.mechanism, self.username, self.use_ssl, self.ca_certs, self.keyfile, self.certfile, self.validate, self.transport, self.multiple]))\n\nclass ConnectionPooler(object):\n \"\"\"\n Thread-safe connection pooling for thrift. (With about 3 changes,\n this could be made general).\n\n Each host,port pair has a connection pool set associated with it.\n Clients can get connections from this pool and then block when\n none are available.\n\n A connection is a 'SuperClient', which deals with timeout errors\n automatically so we don't have to worry about refreshing a stale pool.\n\n We could be fancier here - we could reclaim clients ourselves without\n relying on them to be returned but that would increase complexity. The\n benefit would be not having to hit the connection pool on every client call.\n \"\"\"\n\n def __init__(self, poolsize=10):\n self.pooldict = {}\n self.poolsize = poolsize\n self.dictlock = threading.Lock()\n\n def get_client(self, conf,\n get_client_timeout=None):\n \"\"\"\n Could block while we wait for the pool to become non-empty.\n\n @param get_client_timeout: how long (in seconds) to wait on the pool\n to get a client before failing\n \"\"\"\n # First up, check to see if we have a pool for this endpoint\n if _get_pool_key(conf) not in self.pooldict:\n # Uh-oh, we need to initialise the queue. Take the dict lock.\n # Note that this is 'double-checked locking'.\n\n # The reason this pattern doesn't work in Java is that the write to the dict\n # may get issued before the construction of the Queue due to new Queue(..) not\n # being atomic. However in Python this becomes CALL_FUNCTION and STORE_FAST,\n # therefore as long as a) the function doesn't get inlined b) Python's bytecode\n # generator doesn't move the write to q before the function completes there's no\n # way for another thread to observe a partially constructed queue.\n\n # I haven't found a reference for the Python memory model, so I'm leaving this comment\n # here in case unladen-swallow or something breaks this assumption of correctness.\n\n self.dictlock.acquire()\n try:\n if _get_pool_key(conf) not in self.pooldict:\n q = LifoQueue(self.poolsize)\n self.pooldict[_get_pool_key(conf)] = q\n for i in xrange(self.poolsize):\n client = construct_superclient(conf)\n client.CID = i\n q.put(client, False)\n finally:\n self.dictlock.release()\n\n connection = None\n\n start_pool_get_time = time.time()\n has_waited_for = 0\n\n while connection is None:\n if get_client_timeout is not None:\n this_round_timeout = max(min(get_client_timeout - has_waited_for, 1), 0)\n else:\n this_round_timeout = None\n\n try:\n connection = self.pooldict[_get_pool_key(conf)].get(\n block=True, timeout=this_round_timeout)\n except Queue.Empty:\n has_waited_for = time.time() - start_pool_get_time\n if get_client_timeout is not None and has_waited_for > get_client_timeout:\n raise socket.timeout(\n (\"Timed out after %.2f seconds waiting to retrieve a \" +\n \"%s client from the pool.\") % (has_waited_for, conf.service_name))\n logging.warn(\"Waited %d seconds for a thrift client to %s:%d\" %\n (has_waited_for, conf.host, conf.port))\n\n return connection\n\n def return_client(self, conf, client):\n \"\"\"\n Add a client back to its pool. It's an error to\n pass back a client that was not retrieved from a pool, and\n you might well get an exception for doing so.\n \"\"\"\n self.pooldict[_get_pool_key(conf)].put(client)\n\ndef _get_pool_key(conf):\n \"\"\"\n Given a ConnectionConfig, return the tuple used as the key in the dictionary\n of connections by the ConnectionPooler class.\n \"\"\"\n return (conf.klass, conf.host, conf.port)\n\ndef construct_superclient(conf):\n \"\"\"\n Constructs a thrift client, lazily.\n \"\"\"\n service, protocol, transport = connect_to_thrift(conf)\n return SuperClient(service, transport, timeout_seconds=conf.timeout_seconds)\n\n\ndef connect_to_thrift(conf):\n \"\"\"\n Connect to a thrift endpoint as determined by the 'conf' parameter.\n Note that this does *not* open the transport.\n\n Returns a tuple of (service, protocol, transport)\n \"\"\"\n if conf.use_ssl:\n sock = TSSLSocket(conf.host, conf.port, validate=conf.validate, ca_certs=conf.ca_certs, keyfile=conf.keyfile, certfile=conf.certfile)\n else:\n sock = TSocket(conf.host, conf.port)\n if conf.timeout_seconds:\n # Thrift trivia: You can do this after the fact with\n # _grab_transport_from_wrapper(self.wrapped.transport).setTimeout(seconds*1000)", "answers": [" sock.setTimeout(conf.timeout_seconds * 1000.0)"], "length": 1113, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "38e7fce0-c336-44d4-907f-6a09fe2e5d9b", "reasoning": "In the connect_to_thrift function, after creating the socket (sock) they check if a timeout is configured. The comment notes that you can set the timeout after creating the transport using a helper, but the straightforward way is to set it directly on the socket. The next logical line therefore calls setTimeout on the sock, converting seconds to milliseconds as Thrift expects.", "reasoning_model_answer": "sock.setTimeout(conf.timeout_seconds * 1000)", "assistant_with_reasoning": "\nIn the connect_to_thrift function, after creating the socket (sock) they check if a timeout is configured. The comment notes that you can set the timeout after creating the transport using a helper, but the straightforward way is to set it directly on the socket. The next logical line therefore calls setTimeout on the sock, converting seconds to milliseconds as Thrift expects.\n\nsock.setTimeout(conf.timeout_seconds * 1000)", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.69, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 9670, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "sock.setTimeout(conf.timeout_seconds * 1000)", "score": 0.94, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.apache.kafka.streams;\n\nimport org.apache.kafka.clients.admin.AdminClientConfig;\nimport org.apache.kafka.clients.consumer.ConsumerConfig;\nimport org.apache.kafka.clients.consumer.ConsumerRecord;\nimport org.apache.kafka.clients.producer.ProducerConfig;\nimport org.apache.kafka.common.config.ConfigException;\nimport org.apache.kafka.common.config.TopicConfig;\nimport org.apache.kafka.common.serialization.Deserializer;\nimport org.apache.kafka.common.serialization.Serde;\nimport org.apache.kafka.common.serialization.Serdes;\nimport org.apache.kafka.common.serialization.Serializer;\nimport org.apache.kafka.common.utils.Utils;\nimport org.apache.kafka.streams.errors.StreamsException;\nimport org.apache.kafka.streams.processor.FailOnInvalidTimestamp;\nimport org.apache.kafka.streams.processor.TimestampExtractor;\nimport org.apache.kafka.streams.processor.internals.StreamsPartitionAssignor;\nimport org.hamcrest.CoreMatchers;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport java.util.Arrays;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Locale;\nimport java.util.Map;\nimport java.util.Properties;\n\nimport static org.apache.kafka.common.requests.IsolationLevel.READ_COMMITTED;\nimport static org.apache.kafka.common.requests.IsolationLevel.READ_UNCOMMITTED;\nimport static org.apache.kafka.streams.StreamsConfig.EXACTLY_ONCE;\nimport static org.apache.kafka.streams.StreamsConfig.TOPOLOGY_OPTIMIZATION;\nimport static org.apache.kafka.streams.StreamsConfig.adminClientPrefix;\nimport static org.apache.kafka.streams.StreamsConfig.consumerPrefix;\nimport static org.apache.kafka.streams.StreamsConfig.producerPrefix;\nimport static org.apache.kafka.test.StreamsTestUtils.minimalStreamsConfig;\nimport static org.hamcrest.core.IsEqual.equalTo;\nimport static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.assertNull;\nimport static org.junit.Assert.assertThat;\nimport static org.junit.Assert.assertTrue;\nimport static org.junit.Assert.fail;\n\npublic class StreamsConfigTest {\n\n private final Properties props = new Properties();\n private StreamsConfig streamsConfig;\n\n @Before\n public void setUp() {\n props.put(StreamsConfig.APPLICATION_ID_CONFIG, \"streams-config-test\");\n props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, \"localhost:9092\");\n props.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass().getName());\n props.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, Serdes.String().getClass().getName());\n props.put(\"key.deserializer.encoding\", \"UTF8\");\n props.put(\"value.deserializer.encoding\", \"UTF-16\");\n streamsConfig = new StreamsConfig(props);\n }\n\n @Test(expected = ConfigException.class)\n public void shouldThrowExceptionIfApplicationIdIsNotSet() {\n props.remove(StreamsConfig.APPLICATION_ID_CONFIG);\n new StreamsConfig(props);\n }\n\n @Test(expected = ConfigException.class)\n public void shouldThrowExceptionIfBootstrapServersIsNotSet() {\n props.remove(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG);\n new StreamsConfig(props);\n }\n\n @Test\n public void testGetProducerConfigs() {\n final String clientId = \"client\";\n final Map returnedProps = streamsConfig.getProducerConfigs(clientId);\n assertEquals(returnedProps.get(ProducerConfig.CLIENT_ID_CONFIG), clientId + \"-producer\");\n assertEquals(returnedProps.get(ProducerConfig.LINGER_MS_CONFIG), \"100\");\n }\n\n @Test\n public void testGetConsumerConfigs() {\n final String groupId = \"example-application\";\n final String clientId = \"client\";\n final Map returnedProps = streamsConfig.getMainConsumerConfigs(groupId, clientId);\n assertEquals(returnedProps.get(ConsumerConfig.CLIENT_ID_CONFIG), clientId + \"-consumer\");\n assertEquals(returnedProps.get(ConsumerConfig.GROUP_ID_CONFIG), groupId);\n assertEquals(returnedProps.get(ConsumerConfig.MAX_POLL_RECORDS_CONFIG), \"1000\");\n }\n\n @Test\n public void consumerConfigMustContainStreamPartitionAssignorConfig() {\n props.put(StreamsConfig.REPLICATION_FACTOR_CONFIG, 42);\n props.put(StreamsConfig.NUM_STANDBY_REPLICAS_CONFIG, 1);\n props.put(StreamsConfig.WINDOW_STORE_CHANGE_LOG_ADDITIONAL_RETENTION_MS_CONFIG, 7L);\n props.put(StreamsConfig.APPLICATION_SERVER_CONFIG, \"dummy:host\");\n props.put(StreamsConfig.RETRIES_CONFIG, 10);\n props.put(StreamsConfig.adminClientPrefix(StreamsConfig.RETRIES_CONFIG), 5);\n props.put(StreamsConfig.topicPrefix(TopicConfig.SEGMENT_BYTES_CONFIG), 100);\n final StreamsConfig streamsConfig = new StreamsConfig(props);\n\n final String groupId = \"example-application\";\n final String clientId = \"client\";\n final Map returnedProps = streamsConfig.getMainConsumerConfigs(groupId, clientId);\n\n assertEquals(42, returnedProps.get(StreamsConfig.REPLICATION_FACTOR_CONFIG));\n assertEquals(1, returnedProps.get(StreamsConfig.NUM_STANDBY_REPLICAS_CONFIG));\n assertEquals(StreamsPartitionAssignor.class.getName(), returnedProps.get(ConsumerConfig.PARTITION_ASSIGNMENT_STRATEGY_CONFIG));\n assertEquals(7L, returnedProps.get(StreamsConfig.WINDOW_STORE_CHANGE_LOG_ADDITIONAL_RETENTION_MS_CONFIG));\n assertEquals(\"dummy:host\", returnedProps.get(StreamsConfig.APPLICATION_SERVER_CONFIG));\n assertEquals(null, returnedProps.get(StreamsConfig.RETRIES_CONFIG));\n assertEquals(5, returnedProps.get(StreamsConfig.adminClientPrefix(StreamsConfig.RETRIES_CONFIG)));\n assertEquals(100, returnedProps.get(StreamsConfig.topicPrefix(TopicConfig.SEGMENT_BYTES_CONFIG)));\n }\n\n @Test\n public void consumerConfigMustUseAdminClientConfigForRetries() {\n props.put(StreamsConfig.adminClientPrefix(StreamsConfig.RETRIES_CONFIG), 20);\n props.put(StreamsConfig.RETRIES_CONFIG, 10);\n final StreamsConfig streamsConfig = new StreamsConfig(props);\n\n final String groupId = \"example-application\";\n final String clientId = \"client\";\n final Map returnedProps = streamsConfig.getMainConsumerConfigs(groupId, clientId);\n\n assertEquals(20, returnedProps.get(StreamsConfig.adminClientPrefix(StreamsConfig.RETRIES_CONFIG)));\n }\n\n @Test\n public void testGetMainConsumerConfigsWithMainConsumerOverridenPrefix() {\n props.put(StreamsConfig.consumerPrefix(ConsumerConfig.MAX_POLL_RECORDS_CONFIG), \"5\");\n props.put(StreamsConfig.mainConsumerPrefix(ConsumerConfig.MAX_POLL_RECORDS_CONFIG), \"50\");\n final String groupId = \"example-application\";\n final String clientId = \"client\";\n final Map returnedProps = streamsConfig.getMainConsumerConfigs(groupId, clientId);\n assertEquals(\"50\", returnedProps.get(ConsumerConfig.MAX_POLL_RECORDS_CONFIG));\n }\n\n @Test\n public void testGetRestoreConsumerConfigs() {\n final String clientId = \"client\";\n final Map returnedProps = streamsConfig.getRestoreConsumerConfigs(clientId);\n assertEquals(returnedProps.get(ConsumerConfig.CLIENT_ID_CONFIG), clientId + \"-restore-consumer\");\n assertNull(returnedProps.get(ConsumerConfig.GROUP_ID_CONFIG));\n }\n\n @Test\n public void defaultSerdeShouldBeConfigured() {\n final Map serializerConfigs = new HashMap<>();\n serializerConfigs.put(\"key.serializer.encoding\", \"UTF8\");\n serializerConfigs.put(\"value.serializer.encoding\", \"UTF-16\");\n final Serializer serializer = Serdes.String().serializer();\n\n final String str = \"my string for testing\";\n final String topic = \"my topic\";\n\n serializer.configure(serializerConfigs, true);\n assertEquals(\"Should get the original string after serialization and deserialization with the configured encoding\",\n str, streamsConfig.defaultKeySerde().deserializer().deserialize(topic, serializer.serialize(topic, str)));\n\n serializer.configure(serializerConfigs, false);\n assertEquals(\"Should get the original string after serialization and deserialization with the configured encoding\",\n str, streamsConfig.defaultValueSerde().deserializer().deserialize(topic, serializer.serialize(topic, str)));\n }\n\n @Test\n public void shouldSupportMultipleBootstrapServers() {\n final List expectedBootstrapServers = Arrays.asList(\"broker1:9092\", \"broker2:9092\");\n final String bootstrapServersString = Utils.join(expectedBootstrapServers, \",\");\n final Properties props = new Properties();\n props.put(StreamsConfig.APPLICATION_ID_CONFIG, \"irrelevant\");\n props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServersString);\n final StreamsConfig config = new StreamsConfig(props);\n\n final List actualBootstrapServers = config.getList(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG);\n assertEquals(expectedBootstrapServers, actualBootstrapServers);\n }\n\n @Test\n public void shouldSupportPrefixedConsumerConfigs() {\n props.put(consumerPrefix(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG), \"earliest\");\n props.put(consumerPrefix(ConsumerConfig.METRICS_NUM_SAMPLES_CONFIG), 1);\n final StreamsConfig streamsConfig = new StreamsConfig(props);\n final Map consumerConfigs = streamsConfig.getMainConsumerConfigs(\"groupId\", \"clientId\");\n assertEquals(\"earliest\", consumerConfigs.get(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG));\n assertEquals(1, consumerConfigs.get(ConsumerConfig.METRICS_NUM_SAMPLES_CONFIG));\n }\n\n @Test\n public void shouldSupportPrefixedRestoreConsumerConfigs() {\n props.put(consumerPrefix(ConsumerConfig.METRICS_NUM_SAMPLES_CONFIG), 1);\n final StreamsConfig streamsConfig = new StreamsConfig(props);\n final Map consumerConfigs = streamsConfig.getRestoreConsumerConfigs(\"clientId\");\n assertEquals(1, consumerConfigs.get(ConsumerConfig.METRICS_NUM_SAMPLES_CONFIG));\n }\n\n @Test\n public void shouldSupportPrefixedPropertiesThatAreNotPartOfConsumerConfig() {\n final StreamsConfig streamsConfig = new StreamsConfig(props);\n props.put(consumerPrefix(\"interceptor.statsd.host\"), \"host\");\n final Map consumerConfigs = streamsConfig.getMainConsumerConfigs(\"groupId\", \"clientId\");\n assertEquals(\"host\", consumerConfigs.get(\"interceptor.statsd.host\"));\n }\n\n @Test\n public void shouldSupportPrefixedPropertiesThatAreNotPartOfRestoreConsumerConfig() {\n final StreamsConfig streamsConfig = new StreamsConfig(props);\n props.put(consumerPrefix(\"interceptor.statsd.host\"), \"host\");\n final Map consumerConfigs = streamsConfig.getRestoreConsumerConfigs(\"clientId\");\n assertEquals(\"host\", consumerConfigs.get(\"interceptor.statsd.host\"));\n }\n\n @Test\n public void shouldSupportPrefixedPropertiesThatAreNotPartOfProducerConfig() {\n final StreamsConfig streamsConfig = new StreamsConfig(props);\n props.put(producerPrefix(\"interceptor.statsd.host\"), \"host\");\n final Map producerConfigs = streamsConfig.getProducerConfigs(\"clientId\");\n assertEquals(\"host\", producerConfigs.get(\"interceptor.statsd.host\"));\n }\n\n\n @Test\n public void shouldSupportPrefixedProducerConfigs() {\n props.put(producerPrefix(ProducerConfig.BUFFER_MEMORY_CONFIG), 10);\n props.put(producerPrefix(ConsumerConfig.METRICS_NUM_SAMPLES_CONFIG), 1);\n final StreamsConfig streamsConfig = new StreamsConfig(props);\n final Map configs = streamsConfig.getProducerConfigs(\"clientId\");\n assertEquals(10, configs.get(ProducerConfig.BUFFER_MEMORY_CONFIG));\n assertEquals(1, configs.get(ProducerConfig.METRICS_NUM_SAMPLES_CONFIG));\n }\n\n @Test\n public void shouldBeSupportNonPrefixedConsumerConfigs() {\n props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, \"earliest\");\n props.put(ConsumerConfig.METRICS_NUM_SAMPLES_CONFIG, 1);\n final StreamsConfig streamsConfig = new StreamsConfig(props);\n final Map consumerConfigs = streamsConfig.getMainConsumerConfigs(\"groupId\", \"clientId\");\n assertEquals(\"earliest\", consumerConfigs.get(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG));\n assertEquals(1, consumerConfigs.get(ConsumerConfig.METRICS_NUM_SAMPLES_CONFIG));\n }\n\n @Test\n public void shouldBeSupportNonPrefixedRestoreConsumerConfigs() {\n props.put(ConsumerConfig.METRICS_NUM_SAMPLES_CONFIG, 1);\n final StreamsConfig streamsConfig = new StreamsConfig(props);\n final Map consumerConfigs = streamsConfig.getRestoreConsumerConfigs(\"groupId\");\n assertEquals(1, consumerConfigs.get(ConsumerConfig.METRICS_NUM_SAMPLES_CONFIG));\n }\n\n @Test\n public void shouldSupportNonPrefixedProducerConfigs() {\n props.put(ProducerConfig.BUFFER_MEMORY_CONFIG, 10);\n props.put(ConsumerConfig.METRICS_NUM_SAMPLES_CONFIG, 1);\n final StreamsConfig streamsConfig = new StreamsConfig(props);\n final Map configs = streamsConfig.getProducerConfigs(\"clientId\");\n assertEquals(10, configs.get(ProducerConfig.BUFFER_MEMORY_CONFIG));\n assertEquals(1, configs.get(ProducerConfig.METRICS_NUM_SAMPLES_CONFIG));\n }\n\n @Test\n public void shouldForwardCustomConfigsWithNoPrefixToAllClients() {\n final StreamsConfig streamsConfig = new StreamsConfig(props);\n props.put(\"custom.property.host\", \"host\");\n final Map consumerConfigs = streamsConfig.getMainConsumerConfigs(\"groupId\", \"clientId\");\n final Map restoreConsumerConfigs = streamsConfig.getRestoreConsumerConfigs(\"clientId\");\n final Map producerConfigs = streamsConfig.getProducerConfigs(\"clientId\");\n final Map adminConfigs = streamsConfig.getAdminConfigs(\"clientId\");\n assertEquals(\"host\", consumerConfigs.get(\"custom.property.host\"));\n assertEquals(\"host\", restoreConsumerConfigs.get(\"custom.property.host\"));\n assertEquals(\"host\", producerConfigs.get(\"custom.property.host\"));\n assertEquals(\"host\", adminConfigs.get(\"custom.property.host\"));\n }\n\n @Test\n public void shouldOverrideNonPrefixedCustomConfigsWithPrefixedConfigs() {\n final StreamsConfig streamsConfig = new StreamsConfig(props);\n props.put(\"custom.property.host\", \"host0\");\n props.put(consumerPrefix(\"custom.property.host\"), \"host1\");\n props.put(producerPrefix(\"custom.property.host\"), \"host2\");\n props.put(adminClientPrefix(\"custom.property.host\"), \"host3\");\n final Map consumerConfigs = streamsConfig.getMainConsumerConfigs(\"groupId\", \"clientId\");\n final Map restoreConsumerConfigs = streamsConfig.getRestoreConsumerConfigs(\"clientId\");\n final Map producerConfigs = streamsConfig.getProducerConfigs(\"clientId\");\n final Map adminConfigs = streamsConfig.getAdminConfigs(\"clientId\");\n assertEquals(\"host1\", consumerConfigs.get(\"custom.property.host\"));\n assertEquals(\"host1\", restoreConsumerConfigs.get(\"custom.property.host\"));\n assertEquals(\"host2\", producerConfigs.get(\"custom.property.host\"));\n assertEquals(\"host3\", adminConfigs.get(\"custom.property.host\"));\n }\n\n @Test\n public void shouldSupportNonPrefixedAdminConfigs() {\n props.put(AdminClientConfig.RETRIES_CONFIG, 10);\n final StreamsConfig streamsConfig = new StreamsConfig(props);\n final Map configs = streamsConfig.getAdminConfigs(\"clientId\");\n assertEquals(10, configs.get(AdminClientConfig.RETRIES_CONFIG));\n }\n\n @Test(expected = StreamsException.class)\n public void shouldThrowStreamsExceptionIfKeySerdeConfigFails() {\n props.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, MisconfiguredSerde.class);\n final StreamsConfig streamsConfig = new StreamsConfig(props);\n streamsConfig.defaultKeySerde();\n }\n\n @Test(expected = StreamsException.class)\n public void shouldThrowStreamsExceptionIfValueSerdeConfigFails() {\n props.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, MisconfiguredSerde.class);\n final StreamsConfig streamsConfig = new StreamsConfig(props);\n streamsConfig.defaultValueSerde();\n }\n\n @Test\n public void shouldOverrideStreamsDefaultConsumerConfigs() {\n props.put(StreamsConfig.consumerPrefix(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG), \"latest\");\n props.put(StreamsConfig.consumerPrefix(ConsumerConfig.MAX_POLL_RECORDS_CONFIG), \"10\");\n final StreamsConfig streamsConfig = new StreamsConfig(props);\n final Map consumerConfigs = streamsConfig.getMainConsumerConfigs(\"groupId\", \"clientId\");\n assertEquals(\"latest\", consumerConfigs.get(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG));\n assertEquals(\"10\", consumerConfigs.get(ConsumerConfig.MAX_POLL_RECORDS_CONFIG));\n }\n\n @Test\n public void shouldOverrideStreamsDefaultProducerConfigs() {\n props.put(StreamsConfig.producerPrefix(ProducerConfig.LINGER_MS_CONFIG), \"10000\");\n final StreamsConfig streamsConfig = new StreamsConfig(props);\n final Map producerConfigs = streamsConfig.getProducerConfigs(\"clientId\");\n assertEquals(\"10000\", producerConfigs.get(ProducerConfig.LINGER_MS_CONFIG));\n }\n\n @Test\n public void shouldOverrideStreamsDefaultConsumerConifgsOnRestoreConsumer() {\n props.put(StreamsConfig.consumerPrefix(ConsumerConfig.MAX_POLL_RECORDS_CONFIG), \"10\");\n final StreamsConfig streamsConfig = new StreamsConfig(props);\n final Map consumerConfigs = streamsConfig.getRestoreConsumerConfigs(\"clientId\");\n assertEquals(\"10\", consumerConfigs.get(ConsumerConfig.MAX_POLL_RECORDS_CONFIG));\n }\n\n @Test\n public void shouldResetToDefaultIfConsumerAutoCommitIsOverridden() {", "answers": [" props.put(StreamsConfig.consumerPrefix(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG), \"true\");"], "length": 1046, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "692e13e4-8570-42f1-b61b-bab176a601a9", "reasoning": "The test method is starting; it will verify that overriding the consumer auto‑commit config is reset to the default. The first step is to set the overridden property using the consumer prefix, so the next line adds that property to the props map.", "reasoning_model_answer": "props.put(StreamsConfig.consumerPrefix(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG), true);", "assistant_with_reasoning": "\nThe test method is starting; it will verify that overriding the consumer auto‑commit config is reset to the default. The first step is to set the overridden property using the consumer prefix, so the next line adds that property to the props map.\n\nprops.put(StreamsConfig.consumerPrefix(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG), true);", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.374, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 19013, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "props.put(StreamsConfig.consumerPrefix(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG), true);", "score": 0.95, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "// Copyright (C) 2017 The Android Open Source Project\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\npackage com.google.gerrit.server.schema;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.collect.ImmutableList.toImmutableList;\nimport static com.google.common.collect.ImmutableSet.toImmutableSet;\nimport static com.google.gerrit.reviewdb.server.ReviewDbUtil.checkColumns;\nimport static java.util.Comparator.naturalOrder;\nimport static java.util.Comparator.nullsLast;\nimport static java.util.stream.Collectors.toList;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.base.Strings;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.ListMultimap;\nimport com.google.common.collect.MultimapBuilder;\nimport com.google.common.collect.Multimaps;\nimport com.google.common.collect.Streams;\nimport com.google.common.flogger.FluentLogger;\nimport com.google.gerrit.reviewdb.client.Account;\nimport com.google.gerrit.reviewdb.client.AccountGroup;\nimport com.google.gerrit.reviewdb.client.AccountGroupById;\nimport com.google.gerrit.reviewdb.client.AccountGroupByIdAud;\nimport com.google.gerrit.reviewdb.client.AccountGroupMember;\nimport com.google.gerrit.reviewdb.client.AccountGroupMemberAudit;\nimport com.google.gerrit.reviewdb.client.Project;\nimport com.google.gerrit.reviewdb.server.ReviewDb;\nimport com.google.gerrit.reviewdb.server.ReviewDbWrapper;\nimport com.google.gerrit.server.group.InternalGroup;\nimport com.google.gerrit.server.group.db.AuditLogReader;\nimport com.google.gerrit.server.group.db.GroupConfig;\nimport com.google.gerrit.server.util.time.TimeUtil;\nimport com.google.gwtorm.jdbc.JdbcSchema;\nimport com.google.gwtorm.server.OrmException;\nimport com.google.inject.Inject;\nimport com.google.inject.Singleton;\nimport java.io.IOException;\nimport java.sql.ResultSet;\nimport java.sql.SQLException;\nimport java.sql.Statement;\nimport java.sql.Timestamp;\nimport java.util.ArrayList;\nimport java.util.Comparator;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Set;\nimport java.util.function.Function;\nimport java.util.stream.Stream;\nimport org.eclipse.jgit.errors.ConfigInvalidException;\nimport org.eclipse.jgit.lib.Repository;\n\n/**\n * A bundle of all entities rooted at a single {@link AccountGroup} entity.\n *\n *

    Used primarily during the migration process. Most callers should prefer {@link InternalGroup}\n * instead.\n */\n@AutoValue\nabstract class GroupBundle {\n private static final FluentLogger logger = FluentLogger.forEnclosingClass();\n\n static {\n // Initialization-time checks that the column set hasn't changed since the\n // last time this file was updated.\n checkColumns(AccountGroup.NameKey.class, 1);\n checkColumns(AccountGroup.UUID.class, 1);\n checkColumns(AccountGroup.Id.class, 1);\n checkColumns(AccountGroup.class, 1, 2, 4, 7, 9, 10, 11);\n\n checkColumns(AccountGroupById.Key.class, 1, 2);\n checkColumns(AccountGroupById.class, 1);\n\n checkColumns(AccountGroupByIdAud.Key.class, 1, 2, 3);\n checkColumns(AccountGroupByIdAud.class, 1, 2, 3, 4);\n\n checkColumns(AccountGroupMember.Key.class, 1, 2);\n checkColumns(AccountGroupMember.class, 1);\n\n checkColumns(AccountGroupMemberAudit.Key.class, 1, 2, 3);\n checkColumns(AccountGroupMemberAudit.class, 1, 2, 3, 4);\n }\n\n public enum Source {\n REVIEW_DB(\"ReviewDb\"),\n NOTE_DB(\"NoteDb\");\n\n private final String name;\n\n private Source(String name) {\n this.name = name;\n }\n\n @Override\n public String toString() {\n return name;\n }\n }\n\n @Singleton\n public static class Factory {\n private final AuditLogReader auditLogReader;\n\n @Inject\n Factory(AuditLogReader auditLogReader) {\n this.auditLogReader = auditLogReader;\n }\n\n public GroupBundle fromNoteDb(\n Project.NameKey projectName, Repository repo, AccountGroup.UUID uuid)\n throws ConfigInvalidException, IOException {\n GroupConfig groupConfig = GroupConfig.loadForGroup(projectName, repo, uuid);\n InternalGroup internalGroup = groupConfig.getLoadedGroup().get();\n AccountGroup.Id groupId = internalGroup.getId();\n\n AccountGroup accountGroup =\n new AccountGroup(\n internalGroup.getNameKey(),\n internalGroup.getId(),\n internalGroup.getGroupUUID(),\n internalGroup.getCreatedOn());\n accountGroup.setDescription(internalGroup.getDescription());\n accountGroup.setOwnerGroupUUID(internalGroup.getOwnerGroupUUID());\n accountGroup.setVisibleToAll(internalGroup.isVisibleToAll());\n\n return create(\n Source.NOTE_DB,\n accountGroup,\n internalGroup.getMembers().stream()\n .map(\n accountId ->\n new AccountGroupMember(new AccountGroupMember.Key(accountId, groupId)))\n .collect(toImmutableSet()),\n auditLogReader.getMembersAudit(repo, uuid),\n internalGroup.getSubgroups().stream()\n .map(\n subgroupUuid ->\n new AccountGroupById(new AccountGroupById.Key(groupId, subgroupUuid)))\n .collect(toImmutableSet()),\n auditLogReader.getSubgroupsAudit(repo, uuid));\n }\n\n public static GroupBundle fromReviewDb(ReviewDb db, AccountGroup.UUID groupUuid)\n throws OrmException {\n JdbcSchema jdbcSchema = ReviewDbWrapper.unwrapJbdcSchema(db);\n AccountGroup group = readAccountGroupFromReviewDb(jdbcSchema, groupUuid);\n AccountGroup.Id groupId = group.getId();\n\n return create(\n Source.REVIEW_DB,\n group,\n readAccountGroupMembersFromReviewDb(jdbcSchema, groupId),\n readAccountGroupMemberAuditsFromReviewDb(jdbcSchema, groupId),\n readAccountGroupSubgroupsFromReviewDb(jdbcSchema, groupId),\n readAccountGroupSubgroupAuditsFromReviewDb(jdbcSchema, groupId));\n }\n\n private static AccountGroup readAccountGroupFromReviewDb(\n JdbcSchema jdbcSchema, AccountGroup.UUID groupUuid) throws OrmException {\n try (Statement stmt = jdbcSchema.getConnection().createStatement();\n ResultSet rs =\n stmt.executeQuery(\n \"SELECT group_id,\"\n + \" name,\"\n + \" created_on,\"\n + \" description,\"\n + \" owner_group_uuid,\"\n + \" visible_to_all\"\n + \" FROM account_groups\"\n + \" WHERE group_uuid = '\"\n + groupUuid.get()\n + \"'\")) {\n if (!rs.next()) {\n throw new OrmException(String.format(\"Group %s not found\", groupUuid));\n }\n\n AccountGroup.Id groupId = new AccountGroup.Id(rs.getInt(1));\n AccountGroup.NameKey groupName = new AccountGroup.NameKey(rs.getString(2));\n Timestamp createdOn = rs.getTimestamp(3);\n String description = rs.getString(4);\n AccountGroup.UUID ownerGroupUuid = new AccountGroup.UUID(rs.getString(5));\n boolean visibleToAll = \"Y\".equals(rs.getString(6));\n\n AccountGroup group = new AccountGroup(groupName, groupId, groupUuid, createdOn);\n group.setDescription(description);\n group.setOwnerGroupUUID(ownerGroupUuid);\n group.setVisibleToAll(visibleToAll);\n\n if (rs.next()) {\n throw new OrmException(String.format(\"Group UUID %s is ambiguous\", groupUuid));\n }\n\n return group;\n } catch (SQLException e) {\n throw new OrmException(\n String.format(\"Failed to read account group %s from ReviewDb\", groupUuid.get()), e);\n }\n }\n\n private static List readAccountGroupMembersFromReviewDb(\n JdbcSchema jdbcSchema, AccountGroup.Id groupId) throws OrmException {\n try (Statement stmt = jdbcSchema.getConnection().createStatement();\n ResultSet rs =\n stmt.executeQuery(\n \"SELECT account_id\"\n + \" FROM account_group_members\"\n + \" WHERE group_id = '\"\n + groupId.get()\n + \"'\")) {\n List members = new ArrayList<>();\n while (rs.next()) {\n Account.Id accountId = new Account.Id(rs.getInt(1));\n members.add(new AccountGroupMember(new AccountGroupMember.Key(accountId, groupId)));\n }\n return members;\n } catch (SQLException e) {\n throw new OrmException(\n String.format(\n \"Failed to read members of account group %s from ReviewDb\", groupId.get()),\n e);\n }\n }\n\n private static List readAccountGroupMemberAuditsFromReviewDb(\n JdbcSchema jdbcSchema, AccountGroup.Id groupId) throws OrmException {\n try (Statement stmt = jdbcSchema.getConnection().createStatement();\n ResultSet rs =\n stmt.executeQuery(\n \"SELECT account_id, added_by, added_on, removed_by, removed_on\"\n + \" FROM account_group_members_audit\"\n + \" WHERE group_id = '\"\n + groupId.get()\n + \"'\")) {\n List audits = new ArrayList<>();\n while (rs.next()) {\n Account.Id accountId = new Account.Id(rs.getInt(1));\n\n Account.Id addedBy = new Account.Id(rs.getInt(2));\n Timestamp addedOn = rs.getTimestamp(3);\n\n Timestamp removedOn = rs.getTimestamp(5);\n Account.Id removedBy = removedOn != null ? new Account.Id(rs.getInt(4)) : null;\n\n AccountGroupMemberAudit.Key key =\n new AccountGroupMemberAudit.Key(accountId, groupId, addedOn);\n AccountGroupMemberAudit audit = new AccountGroupMemberAudit(key, addedBy);\n audit.removed(removedBy, removedOn);\n audits.add(audit);\n }\n return audits;\n } catch (SQLException e) {\n throw new OrmException(\n String.format(\n \"Failed to read member audits of account group %s from ReviewDb\", groupId.get()),\n e);\n }\n }\n\n private static List readAccountGroupSubgroupsFromReviewDb(\n JdbcSchema jdbcSchema, AccountGroup.Id groupId) throws OrmException {\n try (Statement stmt = jdbcSchema.getConnection().createStatement();\n ResultSet rs =\n stmt.executeQuery(\n \"SELECT include_uuid\"\n + \" FROM account_group_by_id\"\n + \" WHERE group_id = '\"\n + groupId.get()\n + \"'\")) {\n List subgroups = new ArrayList<>();\n while (rs.next()) {\n AccountGroup.UUID includedGroupUuid = new AccountGroup.UUID(rs.getString(1));\n subgroups.add(new AccountGroupById(new AccountGroupById.Key(groupId, includedGroupUuid)));\n }\n return subgroups;\n } catch (SQLException e) {\n throw new OrmException(\n String.format(\n \"Failed to read subgroups of account group %s from ReviewDb\", groupId.get()),\n e);\n }\n }\n\n private static List readAccountGroupSubgroupAuditsFromReviewDb(\n JdbcSchema jdbcSchema, AccountGroup.Id groupId) throws OrmException {\n try (Statement stmt = jdbcSchema.getConnection().createStatement();\n ResultSet rs =\n stmt.executeQuery(\n \"SELECT include_uuid, added_by, added_on, removed_by, removed_on\"\n + \" FROM account_group_by_id_aud\"\n + \" WHERE group_id = '\"\n + groupId.get()\n + \"'\")) {\n List audits = new ArrayList<>();\n while (rs.next()) {\n AccountGroup.UUID includedGroupUuid = new AccountGroup.UUID(rs.getString(1));\n\n Account.Id addedBy = new Account.Id(rs.getInt(2));\n Timestamp addedOn = rs.getTimestamp(3);\n\n Timestamp removedOn = rs.getTimestamp(5);\n Account.Id removedBy = removedOn != null ? new Account.Id(rs.getInt(4)) : null;\n\n AccountGroupByIdAud.Key key =\n new AccountGroupByIdAud.Key(groupId, includedGroupUuid, addedOn);\n AccountGroupByIdAud audit = new AccountGroupByIdAud(key, addedBy);\n audit.removed(removedBy, removedOn);\n audits.add(audit);\n }", "answers": [" return audits;"], "length": 971, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "915b630b-0ee8-4c6d-b61f-243cd7e807d5", "reasoning": "The method readAccountGroupSubgroupAuditsFromReviewDb is inside a try-with-resources block. After populating the 'audits' list in the while loop, the method should return that list before the catch block, matching the pattern of similar methods above. Hence the next line is the return statement for the audits list.", "reasoning_model_answer": "return audits;", "assistant_with_reasoning": "\nThe method readAccountGroupSubgroupAuditsFromReviewDb is inside a try-with-resources block. After populating the 'audits' list in the while loop, the method should return that list before the catch block, matching the pattern of similar methods above. Hence the next line is the return statement for the audits list.\n\nreturn audits;", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 5.573, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 13128, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "return audits;", "score": 0.78, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "package test;\n\nimport java.awt.geom.Point2D;\nimport java.awt.geom.Rectangle2D;\nimport java.util.Iterator;\n\nimport prefuse.action.layout.Layout;\nimport prefuse.data.Graph;\nimport prefuse.data.Schema;\nimport prefuse.data.tuple.TupleSet;\nimport prefuse.util.PrefuseLib;\nimport prefuse.util.force.DragForce;\nimport prefuse.util.force.ForceItem;\nimport prefuse.util.force.ForceSimulator;\nimport prefuse.util.force.NBodyForce;\nimport prefuse.util.force.SpringForce;\nimport prefuse.visual.EdgeItem;\nimport prefuse.visual.NodeItem;\nimport prefuse.visual.VisualItem;\n\n\n/**\n *

    Layout that positions graph elements based on a physics simulation of\n * interacting forces; by default, nodes repel each other, edges act as\n * springs, and drag forces (similar to air resistance) are applied. This\n * algorithm can be run for multiple iterations for a run-once layout\n * computation or repeatedly run in an animated fashion for a dynamic and\n * interactive layout.

    \n * \n *

    The running time of this layout algorithm is the greater of O(N log N)\n * and O(E), where N is the number of nodes and E the number of edges.\n * The addition of custom force calculation modules may, however, increase\n * this value.

    \n * \n *

    The {@link prefuse.util.force.ForceSimulator} used to drive this layout\n * can be set explicitly, allowing any number of custom force directed layouts\n * to be created through the user's selection of included\n * {@link prefuse.util.force.Force} components. Each node in the layout is\n * mapped to a {@link prefuse.util.force.ForceItem} instance and each edge\n * to a {@link prefuse.util.force.Spring} instance for storing the state\n * of the simulation. See the {@link prefuse.util.force} package for more.

    \n * \n * @author jeffrey heer\n */\npublic class CodysFDR extends Layout {\n \n private ForceSimulator m_fsim;\n private long m_lasttime = -1L;\n private long m_maxstep = 50L;\n private boolean m_runonce;\n private int m_iterations = 100;\n private boolean m_enforceBounds;\n \n protected transient VisualItem referrer;\n \n protected String m_nodeGroup;\n protected String m_edgeGroup;\n \n /**\n * Create a new ForceDirectedLayout. By default, this layout will not\n * restrict the layout to the layout bounds and will assume it is being\n * run in animated (rather than run-once) fashion.\n * @param graph the data group to layout. Must resolve to a Graph instance.\n */\n public CodysFDR(String graph)\n {\n this(graph, false, false);\n }\n\n /**\n * Create a new ForceDirectedLayout. The layout will assume it is being\n * run in animated (rather than run-once) fashion.\n * @param group the data group to layout. Must resolve to a Graph instance.\n * @param enforceBounds indicates whether or not the layout should require\n * that all node placements stay within the layout bounds.\n */\n public CodysFDR(String group, boolean enforceBounds)\n {\n this(group, enforceBounds, false);\n }\n \n /**\n * Create a new ForceDirectedLayout.\n * @param group the data group to layout. Must resolve to a Graph instance.\n * @param enforceBounds indicates whether or not the layout should require\n * that all node placements stay within the layout bounds.\n * @param runonce indicates if the layout will be run in a run-once or\n * animated fashion. In run-once mode, the layout will run for a set number\n * of iterations when invoked. In animation mode, only one iteration of the\n * layout is computed.\n */\n public CodysFDR(String group,\n boolean enforceBounds, boolean runonce)\n {\n super(group);\n m_nodeGroup = PrefuseLib.getGroupName(group, Graph.NODES);\n m_edgeGroup = PrefuseLib.getGroupName(group, Graph.EDGES);\n \n m_enforceBounds = enforceBounds;\n m_runonce = runonce;\n m_fsim = new ForceSimulator();\n m_fsim.addForce(new NBodyForce());\n m_fsim.addForce(new SpringForce());\n m_fsim.addForce(new DragForce());\n }\n \n /**\n * Create a new ForceDirectedLayout. The layout will assume it is being\n * run in animated (rather than run-once) fashion.\n * @param group the data group to layout. Must resolve to a Graph instance.\n * @param fsim the force simulator used to drive the layout computation\n * @param enforceBounds indicates whether or not the layout should require\n * that all node placements stay within the layout bounds.\n */\n public CodysFDR(String group,\n ForceSimulator fsim, boolean enforceBounds) {\n this(group, fsim, enforceBounds, false);\n }\n \n /**\n * Create a new ForceDirectedLayout.\n * @param group the data group to layout. Must resolve to a Graph instance.\n * @param fsim the force simulator used to drive the layout computation\n * @param enforceBounds indicates whether or not the layout should require\n * that all node placements stay within the layout bounds.\n * @param runonce indicates if the layout will be run in a run-once or\n * animated fashion. In run-once mode, the layout will run for a set number\n * of iterations when invoked. In animation mode, only one iteration of the\n * layout is computed.\n */\n public CodysFDR(String group, ForceSimulator fsim,\n boolean enforceBounds, boolean runonce)\n {\n super(group);\n m_nodeGroup = PrefuseLib.getGroupName(group, Graph.NODES);\n m_edgeGroup = PrefuseLib.getGroupName(group, Graph.EDGES);\n \n m_enforceBounds = enforceBounds;\n m_runonce = runonce;\n m_fsim = fsim;\n }\n \n // ------------------------------------------------------------------------\n \n /**\n * Get the maximum timestep allowed for integrating node settings between\n * runs of this layout. When computation times are longer than desired,\n * and node positions are changing dramatically between animated frames,\n * the max step time can be lowered to suppress node movement.\n * @return the maximum timestep allowed for integrating between two\n * layout steps.\n */\n public long getMaxTimeStep() {\n return m_maxstep;\n }\n\n /**\n * Set the maximum timestep allowed for integrating node settings between\n * runs of this layout. When computation times are longer than desired,\n * and node positions are changing dramatically between animated frames,\n * the max step time can be lowered to suppress node movement.\n * @param maxstep the maximum timestep allowed for integrating between two\n * layout steps\n */\n public void setMaxTimeStep(long maxstep) {\n this.m_maxstep = maxstep;\n }\n \n /**\n * Get the force simulator driving this layout.\n * @return the force simulator\n */\n public ForceSimulator getForceSimulator() {\n return m_fsim;\n }\n \n /**\n * Set the force simulator driving this layout.\n * @param fsim the force simulator\n */\n public void setForceSimulator(ForceSimulator fsim) {\n m_fsim = fsim;\n }\n \n /**\n * Get the number of iterations to use when computing a layout in\n * run-once mode.\n * @return the number of layout iterations to run\n */\n public int getIterations() {\n return m_iterations;\n }\n\n /**\n * Set the number of iterations to use when computing a layout in\n * run-once mode.\n * @param iter the number of layout iterations to run\n */\n public void setIterations(int iter) {\n if ( iter < 1 )\n throw new IllegalArgumentException(\n \"Iterations must be a positive number!\");\n m_iterations = iter;\n }\n \n /**\n * Explicitly sets the node and edge groups to use for this layout,\n * overriding the group setting passed to the constructor.\n * @param nodeGroup the node data group\n * @param edgeGroup the edge data group\n */\n public void setDataGroups(String nodeGroup, String edgeGroup) {\n m_nodeGroup = nodeGroup;", "answers": [" m_edgeGroup = edgeGroup;"], "length": 1046, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "b52ef103-f7db-42ac-a0ec-e49d2a5ac632", "reasoning": "The method setDataGroups is meant to assign both the node and edge group fields. The first line assigns m_nodeGroup = nodeGroup;. The very next logical statement is to assign the edge group field, i.e., m_edgeGroup = edgeGroup;. This follows the typical pattern of setting both fields before the method ends.", "reasoning_model_answer": "m_edgeGroup = edgeGroup;", "assistant_with_reasoning": "\nThe method setDataGroups is meant to assign both the node and edge group fields. The first line assigns m_nodeGroup = nodeGroup;. The very next logical statement is to assign the edge group field, i.e., m_edgeGroup = edgeGroup;. This follows the typical pattern of setting both fields before the method ends.\n\nm_edgeGroup = edgeGroup;", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 1.698, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 8172, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "m_edgeGroup = edgeGroup;", "score": 0.86, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "#!/usr/bin/env python\n\n# $Id$\n#\n# Author: Thilee Subramaniam\n#\n# Copyright 2012 Quantcast Corp.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may not\n# use this file except in compliance with the License. You may obtain a copy\n# of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n#\n# This program invokes given number of client processes on the given set of\n# remote clients (Java and C++) and makes use of the plan file to apply load\n# on the DFS server.\n\nimport optparse\nimport sys\nimport subprocess\nimport time\nimport os\nimport signal\nimport datetime\nimport commands\nimport resource\nimport re\n\nclass Globals:\n MASTER_PATH = ''\n SLAVE_PATH = ''\n SLAVE_BASE_DIR = ''\n\n CLIENT_PATH = ''\n MSTRESS_LOCK = '/tmp/mstress_master.lock'\n SIGNALLED = False\n SERVER_CMD = \"\"\n SERVER_KEYWORD = \"\"\n KFS_SERVER_CMD = \"metaserver\"\n KFS_SERVER_KEYWORD = \"metaserver\"\n HDFS_SERVER_CMD = \"java\"\n HDFS_SERVER_KEYWORD = \"NameNode\"\n\ndef ParseCommandline():\n parser = optparse.OptionParser()\n parser.add_option('-m', '--mode',\n action='store',\n default='master',\n type='string',\n help='Run as master or slave')\n parser.add_option('-f', '--filesystem',\n action='store',\n default=None,\n type='string',\n help='Filesystem whose metaserver to test. qfs or hdfs.')\n parser.add_option('-s', '--server',\n action='store',\n default=None,\n type='string',\n help='Metaserver or Namenode hostname.')\n parser.add_option('-p', '--port',\n action='store',\n default=None,\n type='int',\n help='Metaserver or Namenode port')\n parser.add_option('-c', '--client-hostname',\n action='store',\n default=None,\n type='string',\n help='mstress slave\\'s hostname (slave only option).')\n parser.add_option('-k', '--client-lookup-key',\n action='store',\n default=None,\n type='string',\n help='mstress slave\\'s lookup key to be used (slave only option).')\n parser.add_option('-t', '--client-testname',\n action='store',\n default=None,\n type='string',\n help='Test to run on mstress slave (slave only option).')\n parser.add_option('-a', '--plan',\n action='store',\n default='%s/plan/plan' % (os.path.dirname(os.path.realpath(__file__))),\n type='string',\n help='Plan file containing client instructions in the client.')\n parser.add_option('-l', '--leave-files', action='store_true',\n default=False, help='Leave files. Does not perform delete test.')\n\n opts, args = parser.parse_args()\n if args:\n sys.exit('Unexpected arguments: %s.' % str(args))\n\n if not opts.filesystem or not opts.server or not opts.port:\n sys.exit('Missing mandatory arguments.')\n if opts.mode not in ('master', 'slave'):\n sys.exit('Invalid mode.')\n if opts.mode == 'master':\n # master should not have -c option\n if opts.client_hostname is not None:\n sys.exit('Master: does not support -c option.')\n if opts.client_testname is not None:\n sys.exit('Master: does not support -t option.')\n else:\n # for slave, this is the slave host name.\n hosts = opts.client_hostname.split(',')\n if len(hosts) != 1:\n sys.exit('Slave: Error in client host name.')\n if opts.client_testname is None or opts.client_lookup_key is None:\n sys.exit('Slave: Error in client test name or lookup key.')\n\n return opts\n\n\ndef PrintMemoryUsage(opts):\n if sys.platform in ('Darwin', 'darwin'):\n psCmd = \"ps -o rss,pid,command | grep %s | grep %s | grep -v grep | awk '{print $1}'\" % (Globals.SERVER_CMD, Globals.SERVER_KEYWORD)\n else:\n psCmd = \"ps -C %s -o rss,pid,cmd | grep %s | awk '{print $1}'\" % (Globals.SERVER_CMD, Globals.SERVER_KEYWORD)\n\n proc = subprocess.Popen(['ssh', opts.server, psCmd],\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE)\n result = proc.communicate()\n if result and len(result[0].strip()) > 0:\n print \"Memory usage %sKB\" % result[0].strip()\n else:\n print \"Memory usage KB\"\n\n\ndef RunMStressMaster(opts, hostsList):\n \"\"\" Called when run in master mode. Calls master funcions for 'create',\n 'stat', and 'readdir'.\n\n Args:\n opts: options object, from parsed commandine options.\n hostsList: list of hosts obtained from plan file.\n\n Returns:\n True on success. False on failure.\n \"\"\"\n\n # print 'Master: called with %r, %r' % (opts, hostsList)\n\n startTime = datetime.datetime.now()\n if RunMStressMasterTest(opts, hostsList, 'create_write') == False:\n return False\n deltaTime = datetime.datetime.now() - startTime\n print '\\nMaster: Create & Write test took %d.%d sec' % (deltaTime.seconds, deltaTime.microseconds/1000000)\n PrintMemoryUsage(opts)\n print '=========================================='\n \n startTime = datetime.datetime.now()\n if RunMStressMasterTest(opts, hostsList, 'stat') == False:\n return False\n deltaTime = datetime.datetime.now() - startTime\n print '\\nMaster: Stat test took %d.%d sec' % (deltaTime.seconds, deltaTime.microseconds/1000000)\n print '=========================================='\n\n startTime = datetime.datetime.now()\n if RunMStressMasterTest(opts, hostsList, 'readdir') == False:\n return False\n deltaTime = datetime.datetime.now() - startTime\n print '\\nMaster: Readdir test took %d.%d sec' % (deltaTime.seconds, deltaTime.microseconds/1000000)\n print '=========================================='\n\n startTime = datetime.datetime.now()\n if RunMStressMasterTest(opts, hostsList, 'read') == False:\n return False\n deltaTime = datetime.datetime.now() - startTime\n print '\\nMaster: Read test took %d.%d sec' % (deltaTime.seconds, deltaTime.microseconds/1000000)\n print '=========================================='\n \n startTime = datetime.datetime.now()\n if RunMStressMasterTest(opts, hostsList, 'rename') == False:\n return False\n deltaTime = datetime.datetime.now() - startTime\n print '\\nMaster: Rename test took %d.%d sec' % (deltaTime.seconds, deltaTime.microseconds/1000000)\n print '=========================================='\n \n if opts.leave_files:\n print \"\\nNot Renaming files because of -l option\"\n return False\n\n startTime = datetime.datetime.now()\n if RunMStressMasterTest(opts, hostsList, 'delete') == False:\n return False\n deltaTime = datetime.datetime.now() - startTime\n print '\\nMaster: Delete test took %d.%d sec' % (deltaTime.seconds, deltaTime.microseconds/1000000)\n print '=========================================='\n\n PrintStatsFromClients(hostsList, opts)\n\n return True\n\ndef PrintStatsFromClients(hostsList, opts):\n \"\"\"\n Called at the end of benchmarking. This function ssh's into each of the\n client hosts and greps the client logs for benchmark lines inserted by the\n MStress_Client\n\n Args:\n opts: options object, from parsed commandline options.\n hostsList: list of hosts obtained from plan file.\n \"\"\"\n\n # kick off grepping the log files in the client hosts\n running_procs = []\n for host in hostsList:\n p = subprocess.Popen(['/usr/bin/ssh', host,\n \"grep -e '\\\\[benchmark\\\\]' %s/plan/*client.log | cut -d' ' \\\n -f 2,3\" % (Globals.SLAVE_BASE_DIR)],\n stdout=subprocess.PIPE)\n\n running_procs.append(p)\n\n # mapping from call (str) -> list of timings (float)\n # we maintain all the latencies in this dictionary -> list mapping\n timings = {}\n for proc in running_procs:\n\n # block until that ssh child is done, and then read out its standard out.\n out, err = proc.communicate()\n if out:\n\n # the lines are of the form:\n # create_write: 0.023874,0.26489 ...\n # rename: 0.005003 ...\n # parse and bucket them into the timings dictionary\n for line in out.split('\\n'):\n if ' ' not in line:\n continue\n\n (call, latencies) = line.split(' ', 1)\n latencies = latencies.strip()\n if latencies == '':\n continue\n\n if call not in timings: \n timings[call] = []\n timings[call].extend(map(lambda x: float(x), latencies.split(',')))\n\n # for each of the calls, compute the metrics and print them out\n for call in timings:\n timings[call].sort()\n\n total = sum(timings[call])\n \n if total > 0:\n avg = total/len(timings[call])\n else:\n avg = 0\n\n print \"%s num=%d, sum=%f, avg=%f, p50=%f, p90=%f\" % (call,\n len(timings[call]),\n total,\n avg,\n pct(timings[call], 50),\n pct(timings[call], 90))\n \ndef pct(l, p):\n \"\"\" returns the `p`-th percentile element in a sorted list `l`\"\"\"\n return l[(int)((p/100.0)*len(l))]\n\ndef RunMStressMasterTest(opts, hostsList, test):\n \"\"\" Called when run in master mode. Invokes the slave version of the same\n program on the provided hosts list with the given test name.\n\n Args:\n opts: parsed commandline options.\n hostsList: list of hosts obtained from plan file.\n test: string: test name to call.\n\n Returns:\n False on error, True on success\n \"\"\"\n if Globals.SIGNALLED:\n return False\n\n # invoke remote master client.\n ssh_cmd = '%s -m slave -f %s -s %s -p %d -t %s' % (\n Globals.SLAVE_PATH,\n opts.filesystem,\n opts.server,\n opts.port,\n test)\n clientHostMapping = MapHostnameForTest(hostsList, test)\n running_procs = {}\n\n for client in hostsList:\n slaveLogfile = Globals.SLAVE_BASE_DIR + '/plan/plan_' + client + '_' + test + '_' + opts.filesystem + '.slave.log'\n p = subprocess.Popen(['/usr/bin/ssh', client,\n '%s -c %s -k %s >& %s' % (ssh_cmd, client, clientHostMapping[client], slaveLogfile)],\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE)\n running_procs[p] = client\n\n success = True\n isLine1 = True\n while running_procs:\n tobedelkeys = []\n for proc in running_procs.iterkeys():\n client = running_procs[proc]\n retcode = proc.poll()\n if retcode is not None:\n sout,serr = proc.communicate()\n if sout:\n print '\\nMaster: output of slave (%s):%s' % (client, sout)\n if serr:\n print '\\nMaster: err of slave (%s):%s' % (client, serr)\n tobedelkeys.append(proc)\n if retcode != 0:\n print \"\\nMaster: '%s' test failed. Please make sure test directory is empty and has write permission, or check slave logs.\" % test\n success = False\n else:\n if Globals.SIGNALLED:\n proc.terminate()\n\n for k in tobedelkeys:\n del running_procs[k]\n\n if running_procs:\n if isLine1:\n sys.stdout.write('Master: remote slave running \\'%s\\'' % test)\n isLine1 = False\n else:\n sys.stdout.write('.')\n sys.stdout.flush()\n time.sleep(0.5)\n return success", "answers": ["def MapHostnameForTest(clients, test):"], "length": 1241, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "b4524062-89e8-4964-a2ca-3e9ea7210640", "reasoning": "The function RunMStressMasterTest ends with `return success`. The next logical piece of code in this script is the definition of the helper function that was called earlier, `MapHostnameForTest`. Therefore the next line should start that function definition.", "reasoning_model_answer": "def MapHostnameForTest(hostsList, test):", "assistant_with_reasoning": "\nThe function RunMStressMasterTest ends with `return success`. The next logical piece of code in this script is the definition of the helper function that was called earlier, `MapHostnameForTest`. Therefore the next line should start that function definition.\n\ndef MapHostnameForTest(hostsList, test):", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.141, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 11697, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "def MapHostnameForTest(hostsList, test):", "score": 0.85, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "\"\"\"Base class for sparse matrices\"\"\"\n\n__all__ = ['spmatrix', 'isspmatrix', 'issparse',\n 'SparseWarning','SparseEfficiencyWarning']\n\nfrom warnings import warn\n\nimport numpy as np\n\nfrom sputils import isdense, isscalarlike, isintlike\n\n\nclass SparseWarning(Warning): pass\nclass SparseFormatWarning(SparseWarning): pass\nclass SparseEfficiencyWarning(SparseWarning): pass\n\n\n# The formats that we might potentially understand.\n_formats = {'csc':[0, \"Compressed Sparse Column\"],\n 'csr':[1, \"Compressed Sparse Row\"],\n 'dok':[2, \"Dictionary Of Keys\"],\n 'lil':[3, \"LInked List\"],\n 'dod':[4, \"Dictionary of Dictionaries\"],\n 'sss':[5, \"Symmetric Sparse Skyline\"],\n 'coo':[6, \"COOrdinate\"],\n 'lba':[7, \"Linpack BAnded\"],\n 'egd':[8, \"Ellpack-itpack Generalized Diagonal\"],\n 'dia':[9, \"DIAgonal\"],\n 'bsr':[10, \"Block Sparse Row\"],\n 'msr':[11, \"Modified compressed Sparse Row\"],\n 'bsc':[12, \"Block Sparse Column\"],\n 'msc':[13, \"Modified compressed Sparse Column\"],\n 'ssk':[14, \"Symmetric SKyline\"],\n 'nsk':[15, \"Nonsymmetric SKyline\"],\n 'jad':[16, \"JAgged Diagonal\"],\n 'uss':[17, \"Unsymmetric Sparse Skyline\"],\n 'vbr':[18, \"Variable Block Row\"],\n 'und':[19, \"Undefined\"]\n }\n\n\nMAXPRINT = 50\n\nclass spmatrix(object):\n \"\"\" This class provides a base class for all sparse matrices. It\n cannot be instantiated. Most of the work is provided by subclasses.\n \"\"\"\n\n __array_priority__ = 10.1\n ndim = 2\n def __init__(self, maxprint=MAXPRINT):\n self.format = self.__class__.__name__[:3]\n self._shape = None\n if self.format == 'spm':\n raise ValueError(\"This class is not intended\"\n \" to be instantiated directly.\")\n self.maxprint = maxprint\n\n def set_shape(self,shape):\n shape = tuple(shape)\n\n if len(shape) != 2:\n raise ValueError(\"Only two-dimensional sparse arrays \"\n \"are supported.\")\n try:\n shape = int(shape[0]),int(shape[1]) #floats, other weirdness\n except:\n raise TypeError('invalid shape')\n\n if not (shape[0] >= 1 and shape[1] >= 1):\n raise ValueError('invalid shape')\n\n if (self._shape != shape) and (self._shape is not None):\n try:\n self = self.reshape(shape)\n except NotImplementedError:\n raise NotImplementedError(\"Reshaping not implemented for %s.\" %\n self.__class__.__name__)\n self._shape = shape\n\n def get_shape(self):\n return self._shape\n\n shape = property(fget=get_shape, fset=set_shape)\n\n def reshape(self,shape):\n raise NotImplementedError\n\n def astype(self, t):\n return self.tocsr().astype(t).asformat(self.format)\n\n def asfptype(self):\n \"\"\"Upcast matrix to a floating point format (if necessary)\"\"\"\n\n fp_types = ['f','d','F','D']\n\n if self.dtype.char in fp_types:\n return self\n else:\n for fp_type in fp_types:\n if self.dtype <= np.dtype(fp_type):\n return self.astype(fp_type)\n\n raise TypeError('cannot upcast [%s] to a floating '\n 'point format' % self.dtype.name)\n\n def __iter__(self):\n for r in xrange(self.shape[0]):\n yield self[r,:]\n\n def getmaxprint(self):\n try:\n maxprint = self.maxprint\n except AttributeError:\n maxprint = MAXPRINT\n return maxprint\n\n #def typecode(self):\n # try:\n # typ = self.dtype.char\n # except AttributeError:\n # typ = None\n # return typ\n\n def getnnz(self):\n try:\n return self.nnz\n except AttributeError:\n raise AttributeError(\"nnz not defined\")\n\n def getformat(self):\n try:\n format = self.format\n except AttributeError:\n format = 'und'\n return format\n\n def __repr__(self):\n nnz = self.getnnz()\n format = self.getformat()\n return \"<%dx%d sparse matrix of type '%s'\\n\" \\\n \"\\twith %d stored elements in %s format>\" % \\\n (self.shape + (self.dtype.type, nnz, _formats[format][1]))\n\n def __str__(self):\n maxprint = self.getmaxprint()\n\n A = self.tocoo()\n nnz = self.getnnz()\n\n # helper function, outputs \"(i,j) v\"\n def tostr(row,col,data):\n triples = zip(zip(row,col),data)\n return '\\n'.join( [ (' %s\\t%s' % t) for t in triples] )\n\n if nnz > maxprint:\n half = maxprint // 2\n out = tostr(A.row[:half], A.col[:half], A.data[:half])\n out += \"\\n :\\t:\\n\"\n half = maxprint - maxprint//2\n out += tostr(A.row[-half:], A.col[-half:], A.data[-half:])\n else:\n out = tostr(A.row, A.col, A.data)\n\n return out\n\n def __nonzero__(self): # Simple -- other ideas?\n return self.getnnz() > 0\n\n # What should len(sparse) return? For consistency with dense matrices,\n # perhaps it should be the number of rows? But for some uses the number of\n # non-zeros is more important. For now, raise an exception!\n def __len__(self):\n # return self.getnnz()\n raise TypeError(\"sparse matrix length is ambiguous; use getnnz()\"\n \" or shape[0]\")\n\n def asformat(self, format):\n \"\"\"Return this matrix in a given sparse format\n\n Parameters\n ----------\n format : {string, None}\n desired sparse matrix format\n - None for no format conversion\n - \"csr\" for csr_matrix format\n - \"csc\" for csc_matrix format\n - \"lil\" for lil_matrix format\n - \"dok\" for dok_matrix format and so on\n\n \"\"\"\n\n if format is None or format == self.format:\n return self\n else:\n return getattr(self,'to' + format)()\n\n ###################################################################\n # NOTE: All arithmetic operations use csr_matrix by default.\n # Therefore a new sparse matrix format just needs to define a\n # .tocsr() method to provide arithmetic support. Any of these\n # methods can be overridden for efficiency.\n ####################################################################\n\n def multiply(self, other):\n \"\"\"Point-wise multiplication by another matrix\n \"\"\"\n return self.tocsr().multiply(other)\n\n def dot(self, other):\n return self * other\n\n def __abs__(self):\n return abs(self.tocsr())\n\n def __add__(self, other): # self + other\n return self.tocsr().__add__(other)\n\n def __radd__(self, other): # other + self\n return self.tocsr().__radd__(other)\n\n def __sub__(self, other): # self - other\n #note: this can't be replaced by self + (-other) for unsigned types\n return self.tocsr().__sub__(other)\n\n def __rsub__(self, other): # other - self\n return self.tocsr().__rsub__(other)\n\n def __mul__(self, other):\n \"\"\"interpret other and call one of the following\n\n self._mul_scalar()\n self._mul_vector()\n self._mul_multivector()\n self._mul_sparse_matrix()\n \"\"\"\n\n M,N = self.shape\n\n if isscalarlike(other):\n # scalar value\n return self._mul_scalar(other)\n\n if issparse(other):\n if self.shape[1] != other.shape[0]:\n raise ValueError('dimension mismatch')\n return self._mul_sparse_matrix(other)\n\n try:\n other.shape\n except AttributeError:\n # If it's a list or whatever, treat it like a matrix\n other = np.asanyarray(other)\n\n other = np.asanyarray(other)\n\n if other.ndim == 1 or other.ndim == 2 and other.shape[1] == 1:\n # dense row or column vector\n if other.shape != (N,) and other.shape != (N,1):\n raise ValueError('dimension mismatch')\n\n result = self._mul_vector(np.ravel(other))\n\n if isinstance(other, np.matrix):\n result = np.asmatrix(result)\n\n if other.ndim == 2 and other.shape[1] == 1:\n # If 'other' was an (nx1) column vector, reshape the result\n result = result.reshape(-1,1)\n\n return result\n\n elif other.ndim == 2:\n ##\n # dense 2D array or matrix (\"multivector\")\n\n if other.shape[0] != self.shape[1]:\n raise ValueError('dimension mismatch')\n\n result = self._mul_multivector(np.asarray(other))\n\n if isinstance(other, np.matrix):\n result = np.asmatrix(result)\n\n return result\n else:\n raise ValueError('could not interpret dimensions')\n\n # by default, use CSR for __mul__ handlers\n def _mul_scalar(self, other):\n return self.tocsr()._mul_scalar(other)\n\n def _mul_vector(self, other):\n return self.tocsr()._mul_vector(other)\n\n def _mul_multivector(self, other):\n return self.tocsr()._mul_multivector(other)\n\n def _mul_sparse_matrix(self, other):\n return self.tocsr()._mul_sparse_matrix(other)\n\n def __rmul__(self, other): # other * self\n if isscalarlike(other):\n return self.__mul__(other)\n else:\n # Don't use asarray unless we have to\n try:\n tr = other.transpose()", "answers": [" except AttributeError:"], "length": 920, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "fce4cf80-75f8-43f3-8c41-b0be17737be7", "reasoning": "The __rmul__ method handles left-multiplication by a non‑scalar. After attempting to get the transpose of 'other' with 'tr = other.transpose()', the next logical step is to catch the case where 'other' has no transpose method, so an except clause for AttributeError follows.", "reasoning_model_answer": "except AttributeError:", "assistant_with_reasoning": "\nThe __rmul__ method handles left-multiplication by a non‑scalar. After attempting to get the transpose of 'other' with 'tr = other.transpose()', the next logical step is to catch the case where 'other' has no transpose method, so an except clause for AttributeError follows.\n\nexcept AttributeError:", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 6.728, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 9790, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "except AttributeError:", "score": 0.79, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "# Copyright 2009-2012 10gen, Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Tools for representing files stored in GridFS.\"\"\"\n\nimport datetime\nimport math\nimport os\n\nfrom bson.binary import Binary\nfrom bson.objectid import ObjectId\nfrom bson.py3compat import b, binary_type, string_types, text_type, StringIO\nfrom gridfs.errors import (CorruptGridFile,\n FileExists,\n NoFile,\n UnsupportedAPI)\nfrom pymongo import ASCENDING\nfrom pymongo.collection import Collection\nfrom pymongo.errors import DuplicateKeyError\n\ntry:\n _SEEK_SET = os.SEEK_SET\n _SEEK_CUR = os.SEEK_CUR\n _SEEK_END = os.SEEK_END\n# before 2.5\nexcept AttributeError:\n _SEEK_SET = 0\n _SEEK_CUR = 1\n _SEEK_END = 2\n\nEMPTY = b(\"\")\nNEWLN = b(\"\\n\")\n\n\"\"\"Default chunk size, in bytes.\"\"\"\nDEFAULT_CHUNK_SIZE = 256 * 1024\n\n\ndef _create_property(field_name, docstring,\n read_only=False, closed_only=False):\n \"\"\"Helper for creating properties to read/write to files.\n \"\"\"\n def getter(self):\n if closed_only and not self._closed:\n raise AttributeError(\"can only get %r on a closed file\" %\n field_name)\n # Protect against PHP-237\n if field_name == 'length':\n return self._file.get(field_name, 0)\n return self._file.get(field_name, None)\n\n def setter(self, value):\n if self._closed:\n self._coll.files.update({\"_id\": self._file[\"_id\"]},\n {\"$set\": {field_name: value}},\n **self._coll._get_wc_override())\n self._file[field_name] = value\n\n if read_only:\n docstring = docstring + \"\\n\\nThis attribute is read-only.\"\n elif closed_only:\n docstring = \"%s\\n\\n%s\" % (docstring, \"This attribute is read-only and \"\n \"can only be read after :meth:`close` \"\n \"has been called.\")\n\n if not read_only and not closed_only:\n return property(getter, setter, doc=docstring)\n return property(getter, doc=docstring)\n\n\nclass GridIn(object):\n \"\"\"Class to write data to GridFS.\n \"\"\"\n def __init__(self, root_collection, **kwargs):\n \"\"\"Write a file to GridFS\n\n Application developers should generally not need to\n instantiate this class directly - instead see the methods\n provided by :class:`~gridfs.GridFS`.\n\n Raises :class:`TypeError` if `root_collection` is not an\n instance of :class:`~pymongo.collection.Collection`.\n\n Any of the file level options specified in the `GridFS Spec\n `_ may be passed as\n keyword arguments. Any additional keyword arguments will be\n set as additional fields on the file document. Valid keyword\n arguments include:\n\n - ``\"_id\"``: unique ID for this file (default:\n :class:`~bson.objectid.ObjectId`) - this ``\"_id\"`` must\n not have already been used for another file\n\n - ``\"filename\"``: human name for the file\n\n - ``\"contentType\"`` or ``\"content_type\"``: valid mime-type\n for the file\n\n - ``\"chunkSize\"`` or ``\"chunk_size\"``: size of each of the\n chunks, in bytes (default: 256 kb)\n\n - ``\"encoding\"``: encoding used for this file. In Python 2,\n any :class:`unicode` that is written to the file will be\n converted to a :class:`str`. In Python 3, any :class:`str`\n that is written to the file will be converted to\n :class:`bytes`.\n\n If you turn off write-acknowledgment for performance reasons, it is\n critical to wrap calls to :meth:`write` and :meth:`close` within a\n single request:\n\n >>> from pymongo import MongoClient\n >>> from gridfs import GridFS\n >>> client = MongoClient(w=0) # turn off write acknowledgment\n >>> fs = GridFS(client)\n >>> gridin = fs.new_file()\n >>> request = client.start_request()\n >>> try:\n ... for i in range(10):\n ... gridin.write('foo')\n ... gridin.close()\n ... finally:\n ... request.end()\n\n In Python 2.5 and later this code can be simplified with a\n with-statement, see :doc:`/examples/requests` for more information.\n\n :Parameters:\n - `root_collection`: root collection to write to\n - `**kwargs` (optional): file level options (see above)\n \"\"\"\n if not isinstance(root_collection, Collection):\n raise TypeError(\"root_collection must be an \"\n \"instance of Collection\")\n\n # Handle alternative naming\n if \"content_type\" in kwargs:\n kwargs[\"contentType\"] = kwargs.pop(\"content_type\")\n if \"chunk_size\" in kwargs:\n kwargs[\"chunkSize\"] = kwargs.pop(\"chunk_size\")\n\n # Defaults\n kwargs[\"_id\"] = kwargs.get(\"_id\", ObjectId())\n kwargs[\"chunkSize\"] = kwargs.get(\"chunkSize\", DEFAULT_CHUNK_SIZE)\n\n root_collection.chunks.ensure_index([(\"files_id\", ASCENDING),\n (\"n\", ASCENDING)],\n unique=True)\n object.__setattr__(self, \"_coll\", root_collection)\n object.__setattr__(self, \"_chunks\", root_collection.chunks)\n object.__setattr__(self, \"_file\", kwargs)\n object.__setattr__(self, \"_buffer\", StringIO())\n object.__setattr__(self, \"_position\", 0)\n object.__setattr__(self, \"_chunk_number\", 0)\n object.__setattr__(self, \"_closed\", False)\n\n @property\n def closed(self):\n \"\"\"Is this file closed?\n \"\"\"\n return self._closed\n\n _id = _create_property(\"_id\", \"The ``'_id'`` value for this file.\",\n read_only=True)\n filename = _create_property(\"filename\", \"Name of this file.\")\n name = _create_property(\"filename\", \"Alias for `filename`.\")\n content_type = _create_property(\"contentType\", \"Mime-type for this file.\")\n length = _create_property(\"length\", \"Length (in bytes) of this file.\",\n closed_only=True)\n chunk_size = _create_property(\"chunkSize\", \"Chunk size for this file.\",\n read_only=True)\n upload_date = _create_property(\"uploadDate\",\n \"Date that this file was uploaded.\",\n closed_only=True)\n md5 = _create_property(\"md5\", \"MD5 of the contents of this file \"\n \"(generated on the server).\",\n closed_only=True)\n\n def __getattr__(self, name):\n if name in self._file:\n return self._file[name]\n raise AttributeError(\"GridIn object has no attribute '%s'\" % name)\n\n def __setattr__(self, name, value):\n # For properties of this instance like _buffer, or descriptors set on\n # the class like filename, use regular __setattr__\n if name in self.__dict__ or name in self.__class__.__dict__:\n object.__setattr__(self, name, value)\n else:\n # All other attributes are part of the document in db.fs.files.\n # Store them to be sent to server on close() or if closed, send\n # them now.\n self._file[name] = value\n if self._closed:\n self._coll.files.update({\"_id\": self._file[\"_id\"]},\n {\"$set\": {name: value}},\n **self._coll._get_wc_override())\n\n def __flush_data(self, data):\n \"\"\"Flush `data` to a chunk.\n \"\"\"\n if not data:\n return\n assert(len(data) <= self.chunk_size)\n\n chunk = {\"files_id\": self._file[\"_id\"],\n \"n\": self._chunk_number,\n \"data\": Binary(data)}\n\n try:\n self._chunks.insert(chunk)\n except DuplicateKeyError:\n self._raise_file_exists(self._file['_id'])\n self._chunk_number += 1\n self._position += len(data)\n\n def __flush_buffer(self):\n \"\"\"Flush the buffer contents out to a chunk.\n \"\"\"\n self.__flush_data(self._buffer.getvalue())\n self._buffer.close()\n self._buffer = StringIO()\n\n def __flush(self):\n \"\"\"Flush the file to the database.\n \"\"\"\n try:\n self.__flush_buffer()\n\n db = self._coll.database\n\n # See PYTHON-417, \"Sharded GridFS fails with exception: chunks out\n # of order.\" Inserts via mongos, even if they use a single\n # connection, can succeed out-of-order due to the writebackListener.\n # We mustn't call \"filemd5\" until all inserts are complete, which\n # we ensure by calling getLastError (and ignoring the result).\n db.error()\n\n md5 = db.command(\n \"filemd5\", self._id, root=self._coll.name)[\"md5\"]\n\n self._file[\"md5\"] = md5\n self._file[\"length\"] = self._position\n self._file[\"uploadDate\"] = datetime.datetime.utcnow()\n\n return self._coll.files.insert(self._file,\n **self._coll._get_wc_override())\n except DuplicateKeyError:\n self._raise_file_exists(self._id)\n\n def _raise_file_exists(self, file_id):\n \"\"\"Raise a FileExists exception for the given file_id.\"\"\"\n raise FileExists(\"file with _id %r already exists\" % file_id)\n\n def close(self):\n \"\"\"Flush the file and close it.\n\n A closed file cannot be written any more. Calling\n :meth:`close` more than once is allowed.\n \"\"\"\n if not self._closed:\n self.__flush()\n object.__setattr__(self, \"_closed\", True)\n\n def write(self, data):\n \"\"\"Write data to the file. There is no return value.\n\n `data` can be either a string of bytes or a file-like object\n (implementing :meth:`read`). If the file has an\n :attr:`encoding` attribute, `data` can also be a\n :class:`unicode` (:class:`str` in python 3) instance, which\n will be encoded as :attr:`encoding` before being written.\n\n Due to buffering, the data may not actually be written to the\n database until the :meth:`close` method is called. Raises\n :class:`ValueError` if this file is already closed. Raises\n :class:`TypeError` if `data` is not an instance of\n :class:`str` (:class:`bytes` in python 3), a file-like object,\n or an instance of :class:`unicode` (:class:`str` in python 3).\n Unicode data is only allowed if the file has an :attr:`encoding`\n attribute.\n\n :Parameters:\n - `data`: string of bytes or file-like object to be written\n to the file\n\n .. versionadded:: 1.9\n The ability to write :class:`unicode`, if the file has an\n :attr:`encoding` attribute.\n \"\"\"\n if self._closed:\n raise ValueError(\"cannot write to a closed file\")\n\n try:\n # file-like\n read = data.read\n except AttributeError:\n # string\n if not isinstance(data, string_types):\n raise TypeError(\"can only write strings or file-like objects\")\n if isinstance(data, unicode):\n try:\n data = data.encode(self.encoding)\n except AttributeError:\n raise TypeError(\"must specify an encoding for file in \"\n \"order to write %s\" % (text_type.__name__,))\n read = StringIO(data).read\n\n if self._buffer.tell() > 0:\n # Make sure to flush only when _buffer is complete\n space = self.chunk_size - self._buffer.tell()\n if space:\n to_write = read(space)\n self._buffer.write(to_write)\n if len(to_write) < space:\n return # EOF or incomplete\n self.__flush_buffer()\n to_write = read(self.chunk_size)\n while to_write and len(to_write) == self.chunk_size:\n self.__flush_data(to_write)\n to_write = read(self.chunk_size)\n self._buffer.write(to_write)\n\n def writelines(self, sequence):\n \"\"\"Write a sequence of strings to the file.\n\n Does not add seperators.\n \"\"\"\n for line in sequence:\n self.write(line)\n\n def __enter__(self):\n \"\"\"Support for the context manager protocol.\n \"\"\"\n return self\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n \"\"\"Support for the context manager protocol.\n\n Close the file and allow exceptions to propagate.\n \"\"\"\n self.close()\n\n # propagate exceptions\n return False\n\n\nclass GridOut(object):", "answers": [" \"\"\"Class to read data out of GridFS."], "length": 1324, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "f52f639e-f449-4f6b-bf9f-c4ac1a0cdebd", "reasoning": "The code is defining the GridOut class. In the original pymongo GridFS implementation, the class is immediately followed by a docstring describing its purpose. The next line therefore is the class docstring: \"\"\"Class to read data from GridFS.\"\"\".", "reasoning_model_answer": "\"\"\"Class to read data from GridFS.\"\"\"", "assistant_with_reasoning": "\nThe code is defining the GridOut class. In the original pymongo GridFS implementation, the class is immediately followed by a docstring describing its purpose. The next line therefore is the class docstring: \"\"\"Class to read data from GridFS.\"\"\".\n\n\"\"\"Class to read data from GridFS.\"\"\"", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 2.901, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 13567, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "\"\"\"Class to read data from GridFS.\"\"\"", "score": 0.81, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\n\nnamespace System.Globalization\n{\n public abstract class EastAsianLunisolarCalendar : Calendar\n {\n internal const int LeapMonth = 0;\n internal const int Jan1Month = 1;\n internal const int Jan1Date = 2;\n internal const int nDaysPerMonth = 3;\n\n // # of days so far in the solar year\n internal static readonly int[] DaysToMonth365 =\n {\n 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334\n };\n\n internal static readonly int[] DaysToMonth366 =\n {\n 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335\n };\n\n internal const int DatePartYear = 0;\n internal const int DatePartDayOfYear = 1;\n internal const int DatePartMonth = 2;\n internal const int DatePartDay = 3;\n\n public override CalendarAlgorithmType AlgorithmType\n {\n get\n {\n return CalendarAlgorithmType.LunisolarCalendar;\n }\n }\n\n // Return the year number in the 60-year cycle.\n //\n\n public virtual int GetSexagenaryYear(DateTime time)\n {\n CheckTicksRange(time.Ticks);\n\n int year = 0, month = 0, day = 0;\n TimeToLunar(time, ref year, ref month, ref day);\n\n return ((year - 4) % 60) + 1;\n }\n\n // Return the celestial year from the 60-year cycle.\n // The returned value is from 1 ~ 10.\n //\n\n public int GetCelestialStem(int sexagenaryYear)\n {\n if ((sexagenaryYear < 1) || (sexagenaryYear > 60))\n {\n throw new ArgumentOutOfRangeException(\n nameof(sexagenaryYear),\n SR.Format(SR.ArgumentOutOfRange_Range, 1, 60));\n }\n\n return ((sexagenaryYear - 1) % 10) + 1;\n }\n\n // Return the Terrestial Branch from the 60-year cycle.\n // The returned value is from 1 ~ 12.\n //\n\n public int GetTerrestrialBranch(int sexagenaryYear)\n {\n if ((sexagenaryYear < 1) || (sexagenaryYear > 60))\n {\n throw new ArgumentOutOfRangeException(\n nameof(sexagenaryYear),\n SR.Format(SR.ArgumentOutOfRange_Range, 1, 60));\n }\n\n return ((sexagenaryYear - 1) % 12) + 1;\n }\n\n internal abstract int GetYearInfo(int LunarYear, int Index);\n internal abstract int GetYear(int year, DateTime time);\n internal abstract int GetGregorianYear(int year, int era);\n\n internal abstract int MinCalendarYear { get; }\n internal abstract int MaxCalendarYear { get; }\n internal abstract EraInfo[] CalEraInfo { get; }\n internal abstract DateTime MinDate { get; }\n internal abstract DateTime MaxDate { get; }\n\n internal const int MaxCalendarMonth = 13;\n internal const int MaxCalendarDay = 30;\n\n internal int MinEraCalendarYear(int era)\n {\n EraInfo[] mEraInfo = CalEraInfo;\n //ChineseLunisolarCalendar does not has m_EraInfo it is going to retuen null\n if (mEraInfo == null)\n {\n return MinCalendarYear;\n }\n\n if (era == Calendar.CurrentEra)\n {\n era = CurrentEraValue;\n }\n //era has to be in the supported range otherwise we will throw exception in CheckEraRange()\n if (era == GetEra(MinDate))\n {\n return (GetYear(MinCalendarYear, MinDate));\n }\n\n for (int i = 0; i < mEraInfo.Length; i++)\n {\n if (era == mEraInfo[i].era)\n {\n return (mEraInfo[i].minEraYear);\n }\n }\n throw new ArgumentOutOfRangeException(nameof(era), SR.ArgumentOutOfRange_InvalidEraValue);\n }\n\n internal int MaxEraCalendarYear(int era)\n {\n EraInfo[] mEraInfo = CalEraInfo;\n //ChineseLunisolarCalendar does not has m_EraInfo it is going to retuen null\n if (mEraInfo == null)\n {\n return MaxCalendarYear;\n }\n\n if (era == Calendar.CurrentEra)\n {\n era = CurrentEraValue;\n }\n //era has to be in the supported range otherwise we will throw exception in CheckEraRange()\n if (era == GetEra(MaxDate))\n {\n return (GetYear(MaxCalendarYear, MaxDate));\n }\n\n for (int i = 0; i < mEraInfo.Length; i++)\n {\n if (era == mEraInfo[i].era)\n {\n return (mEraInfo[i].maxEraYear);\n }\n }\n throw new ArgumentOutOfRangeException(nameof(era), SR.ArgumentOutOfRange_InvalidEraValue);\n }\n\n internal EastAsianLunisolarCalendar()\n {\n }\n\n internal void CheckTicksRange(long ticks)\n {\n if (ticks < MinSupportedDateTime.Ticks || ticks > MaxSupportedDateTime.Ticks)\n {\n throw new ArgumentOutOfRangeException(\n \"time\",\n String.Format(CultureInfo.InvariantCulture, SR.ArgumentOutOfRange_CalendarRange,\n MinSupportedDateTime, MaxSupportedDateTime));\n }\n }\n\n internal void CheckEraRange(int era)\n {\n if (era == Calendar.CurrentEra)\n {\n era = CurrentEraValue;\n }\n\n if ((era < GetEra(MinDate)) || (era > GetEra(MaxDate)))\n {\n throw new ArgumentOutOfRangeException(nameof(era), SR.ArgumentOutOfRange_InvalidEraValue);\n }\n }\n\n internal int CheckYearRange(int year, int era)\n {\n CheckEraRange(era);\n year = GetGregorianYear(year, era);\n\n if ((year < MinCalendarYear) || (year > MaxCalendarYear))\n {\n throw new ArgumentOutOfRangeException(\n nameof(year),\n SR.Format(SR.ArgumentOutOfRange_Range, MinEraCalendarYear(era), MaxEraCalendarYear(era)));\n }\n return year;\n }\n\n internal int CheckYearMonthRange(int year, int month, int era)\n {\n year = CheckYearRange(year, era);\n\n if (month == 13)\n {\n //Reject if there is no leap month this year\n if (GetYearInfo(year, LeapMonth) == 0)\n throw new ArgumentOutOfRangeException(nameof(month), SR.ArgumentOutOfRange_Month);\n }\n\n if (month < 1 || month > 13)\n {\n throw new ArgumentOutOfRangeException(nameof(month), SR.ArgumentOutOfRange_Month);\n }\n return year;\n }\n\n internal int InternalGetDaysInMonth(int year, int month)\n {\n int nDays;\n int mask; // mask for extracting bits\n\n mask = 0x8000;\n // convert the lunar day into a lunar month/date\n mask >>= (month - 1);\n if ((GetYearInfo(year, nDaysPerMonth) & mask) == 0)\n nDays = 29;\n else\n nDays = 30;\n return nDays;\n }\n\n // Returns the number of days in the month given by the year and\n // month arguments.\n //\n\n public override int GetDaysInMonth(int year, int month, int era)\n {\n year = CheckYearMonthRange(year, month, era);\n return InternalGetDaysInMonth(year, month);\n }\n\n private static int GregorianIsLeapYear(int y)\n {\n return ((((y) % 4) != 0) ? 0 : ((((y) % 100) != 0) ? 1 : ((((y) % 400) != 0) ? 0 : 1)));\n }\n\n // Returns the date and time converted to a DateTime value. Throws an exception if the n-tuple is invalid.\n //\n\n public override DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era)\n {\n year = CheckYearMonthRange(year, month, era);\n int daysInMonth = InternalGetDaysInMonth(year, month);\n if (day < 1 || day > daysInMonth)\n {\n throw new ArgumentOutOfRangeException(\n nameof(day),\n SR.Format(SR.ArgumentOutOfRange_Day, daysInMonth, month));\n }\n\n int gy = 0; int gm = 0; int gd = 0;\n\n if (LunarToGregorian(year, month, day, ref gy, ref gm, ref gd))\n {\n return new DateTime(gy, gm, gd, hour, minute, second, millisecond);\n }\n else\n {\n throw new ArgumentOutOfRangeException(null, SR.ArgumentOutOfRange_BadYearMonthDay);\n }\n }\n\n\n //\n // GregorianToLunar calculates lunar calendar info for the given gregorian year, month, date.\n // The input date should be validated before calling this method.\n //\n internal void GregorianToLunar(int nSYear, int nSMonth, int nSDate, ref int nLYear, ref int nLMonth, ref int nLDate)\n {\n // unsigned int nLYear, nLMonth, nLDate; // lunar ymd\n int nSolarDay; // day # in solar year\n int nLunarDay; // day # in lunar year\n int fLeap; // is it a solar leap year?\n int LDpM; // lunar days/month bitfield\n int mask; // mask for extracting bits\n int nDays; // # days this lunar month\n int nJan1Month, nJan1Date;\n\n // calc the solar day of year\n fLeap = GregorianIsLeapYear(nSYear);\n nSolarDay = (fLeap == 1) ? DaysToMonth366[nSMonth - 1] : DaysToMonth365[nSMonth - 1];\n nSolarDay += nSDate;\n\n // init lunar year info\n nLunarDay = nSolarDay;\n nLYear = nSYear;\n if (nLYear == (MaxCalendarYear + 1))\n {\n nLYear--;\n nLunarDay += ((GregorianIsLeapYear(nLYear) == 1) ? 366 : 365);\n nJan1Month = GetYearInfo(nLYear, Jan1Month);\n nJan1Date = GetYearInfo(nLYear, Jan1Date);\n }\n else\n {\n nJan1Month = GetYearInfo(nLYear, Jan1Month);\n nJan1Date = GetYearInfo(nLYear, Jan1Date);\n\n // check if this solar date is actually part of the previous\n // lunar year\n if ((nSMonth < nJan1Month) ||\n (nSMonth == nJan1Month && nSDate < nJan1Date))\n {\n // the corresponding lunar day is actually part of the previous\n // lunar year\n nLYear--;\n\n // add a solar year to the lunar day #\n nLunarDay += ((GregorianIsLeapYear(nLYear) == 1) ? 366 : 365);\n\n // update the new start of year\n nJan1Month = GetYearInfo(nLYear, Jan1Month);", "answers": [" nJan1Date = GetYearInfo(nLYear, Jan1Date);"], "length": 1160, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "13a9b4bd-1b3a-4b76-8549-2cb809b3645a", "reasoning": "The code is inside GregorianToLunar method. After adjusting nLYear for dates before the lunar new year, it updates the start-of-year month with nJan1Month = GetYearInfo(nLYear, Jan1Month). The next logical step is to also update the start-of-year date, mirroring the earlier branch where both month and date are retrieved. Therefore the next line should retrieve the Jan1Date for the new lunar year.", "reasoning_model_answer": "nJan1Date = GetYearInfo(nLYear, Jan1Date);", "assistant_with_reasoning": "\nThe code is inside GregorianToLunar method. After adjusting nLYear for dates before the lunar new year, it updates the start-of-year month with nJan1Month = GetYearInfo(nLYear, Jan1Month). The next logical step is to also update the start-of-year date, mirroring the earlier branch where both month and date are retrieved. Therefore the next line should retrieve the Jan1Date for the new lunar year.\n\nnJan1Date = GetYearInfo(nLYear, Jan1Date);", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 2.289, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 11459, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "nJan1Date = GetYearInfo(nLYear, Jan1Date);", "score": 0.81, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "import numpy as np\nimport os\n\ndef XMLtoCSV(XMLinput):\n \"\"\"\n This function takes as an input the XML file that comes out of the electronic structure calculations and transforms\n it into 2 CSV files. The first one is the 'X part' of the data. It contains a sample per line. Each line has a format:\n atom label (string), coordinate x (float), coordinate y (float), coordinate z (float), ... for each atom in the system.\n The second file contains the 'Y part' of the data. It has a sample per line with the energy of each sample (float).\n\n :XMLinput: an XML file obtained from grid electronic structure calculations\n \"\"\"\n\n # These are the output files\n fileX = open('X.csv', 'w')\n fileY = open('Y.csv', 'w')\n\n # This is the input file\n inputFile = open(XMLinput, 'r')\n\n # The information of the molecule is contained in the block ....\n # The atom xyz coordinates, the labels and the energy have to be retrieved\n # Each configuration corresponds to one line in the CSV files\n\n for line in inputFile:\n data = []\n if \"\" in line:\n for i in range(3):\n line = inputFile.next()\n while \"\" not in line:\n indexLab = line.find(\"elementType=\")\n indexX = line.find(\"x3=\")\n indexY = line.find(\"y3=\")\n indexYend = line.find(\"\\n\")\n indexZ = line.find(\"z3=\")\n indexZend = line.find(\"/>\")\n\n if indexLab >= 0:\n data.append(line[indexLab + 13])\n data.append(line[indexX + 4: indexY - 2])\n data.append(line[indexY + 4: indexYend - 1])\n if indexZ >= 0:\n data.append(line[indexZ + 4: indexZend - 1])\n\n line = inputFile.next()\n for i in range(len(data)):\n fileX.write(data[i])\n fileX.write(\",\")\n fileX.write(\"\\n\")\n\n if '\")\n energy = float(line[indexEn1 + 7:indexEn2 - 1])\n fileY.write(str(energy) + \"\\n\")\n\n return None\n\ndef XYZtoCSV(XYZinput):\n \"\"\"\n This function takes as an input the XYZ file that comes out of VR and transforms it into 2 CSV files. The first one\n is the 'X part' of the data. It contains a sample per line. Each line has a format:\n atom label (string), coordinate x (float), coordinate y (float), coordinate z (float), ... for each atom in the system.\n The second file contains the 'Y part' of the data. It has a sample per line with the energy of each sample (float).\n\n Note: This is specific to a file containing C, H, N as the atoms.\n\n :XMLinput: an XML file obtained from grid electronic structure calculations\n \"\"\"\n\n # These are the output files\n fileX = open('X.csv', 'w')\n fileY = open('Y.csv', 'w')\n\n # This is the input file\n inputFile = open(XYZinput, 'r')\n\n isFirstLine = True\n n_atoms = 0\n\n for line in inputFile:\n if isFirstLine:\n n_atoms = int(line)\n isFirstLine = False\n\n index1 = line.find(\"Energy\")\n if index1 >= 0:\n index2 = line.find(\"(hartree)\")\n energy = float(line[index1+8:index2-1])\n fileY.write(str(energy))\n fileY.write(\"\\n\")\n\n if line[0] == \"C\" or line[0] == \"H\":\n line = line.replace(\"\\n\", \"\")\n line = line.replace(\"\\t\",\",\")\n fileX.write(line)\n fileX.write(\",\")\n\n if line[0] == \"N\":\n line = line.replace(\"\\n\", \"\")\n line = line.replace(\"\\t\", \",\")\n fileX.write(line)\n fileX.write(\"\\n\")\n\ndef extractMolpro(MolproInput):\n \"\"\"\n This function takes one Molpro .out file and returns the geometry, the energy and the partial charges on the atoms.\n\n :MolproInput: the molpro .out file (string)\n\n :return:\n :rawData: List of strings with atom label and atom coordinates - example ['C', '0.1, '0.1', '0.1', ...]\n :ene: Value of the energy (string)\n :partialCh: List of strings with atom label and its partial charge - example ['C', '6.36', 'H', ...]\n \"\"\"\n\n # This is the input file\n inputFile = open(MolproInput, 'r')\n\n # This will contain the data\n rawData = []\n ene = \"0\"\n partialCh = []\n\n\n for line in inputFile:\n # The geometry is found on the line after the keyword \"geometry={\"\n if \"geometry={\" in line:\n for i in range(7):\n line = inputFile.next()\n line = line.strip()\n lineSplit = line.split(\" \")\n for j in range(len(lineSplit)):\n rawData.append(lineSplit[j])\n # The energy is found two lines after the keyword \"Final beta occupancy:\"\n elif \"Final beta occupancy:\" in line:\n line = inputFile.next()\n line = inputFile.next()\n line = line.strip()\n ene = line[len(\"!RKS STATE 1.1 Energy\"):].strip()\n elif \"Total charge composition:\" in line:\n line = inputFile.next()\n line = inputFile.next()\n for i in range(7):\n line = inputFile.next()\n lineSplit = line.rstrip().split(\" \")\n lineSplit = filter(None, lineSplit)\n partialCh.append(lineSplit[1])\n partialCh.append(lineSplit[-2])\n\n return rawData, ene, partialCh\n\ndef list_files(dir, key):\n \"\"\"\n This function walks through a directory and makes a list of the files that have a name containing a particular string\n\n :dir: path to the directory to explore\n :key: string to look for in file names\n\n :return: list of files containing \"key\" in their filename\n \"\"\"\n\n r = [] # List of files to be joined together\n subdirs = [x[0] for x in os.walk(dir)]\n for subdir in subdirs:\n files = os.walk(subdir).next()[2]\n\n for file in files:\n isTrajectory = file.find(key)\n if isTrajectory >= 0:\n r.append(subdir + \"/\" + file)\n return r\n\ndef MolproToCSV(directory, key):\n \"\"\"\n This function extracts all the geometries and energies from Molpro .out files contained in a particular directory.\n Only the files that have a particular string in their filename will be read. The geometries are then written to X.csv\n where each line is a different geometry. The energies are written to Y.csv where each line is the energy of a\n different geometry. The partial charges are written to Q.csv\n\n :directory: path to the directory containing the Molpro .out files (string)\n :key: string to look for in the file names (string)\n \"\"\"\n\n # These are the output files\n fileX = open('X.csv', 'w')\n fileY = open('Y.csv', 'w')\n fileZ = open('Q.csv', 'w')\n\n # Obtaining the list of files to mine\n fileList = list_files(directory, key)\n\n # Iterating over all the files\n for item in fileList:\n # Extracting the geometry and the energy from a Molpro out file\n geom, ene, partialCh = extractMolpro(item)\n if len(geom) != 28 or ene == \"0\" or len(partialCh) != 14:\n print \"The following file couldn't be read properly:\"\n print item + \"\\n\"\n continue\n for i in range(len(geom)):\n fileX.write(geom[i])\n fileX.write(\",\")\n fileX.write(\"\\n\")\n fileY.write(ene + \"\\n\")\n\n for i in range(len(partialCh)):\n fileZ.write(partialCh[i])\n fileZ.write(\",\")\n fileZ.write(\"\\n\")\n\ndef loadX(fileX):\n \"\"\"\n This function takes a .csv file that contains on each line a different configuration of the system in the format\n \"C,0.1,0.1,0.1,H,0.2,0.2,0.2...\" and returns a list of lists with the configurations of the system.\n\n The following functions generate .csv files in the correct format:\n\n 1. XMLtoCSV\n 2. XYZtoCSSV\n 3. MolproToCSV\n\n The function returns a list of lists where each element is a different configuration for a molecule. For example,\n for a sample with 3 hydrogen atoms the matrix returned will be:\n ``[['H',-0.5,0.0,0.0,'H',0.5,0.0,0.0], ['H',-0.3,0.0,0.0,'H',0.3,0.0,0.0], ['H',-0.7,0.0,0.0,'H',0.7,0.0,0.0]]``\n\n :fileX: The .csv file containing the geometries of the system (string)\n :return: a list of lists with characters and floats.\n \"\"\"\n\n if fileX[-4:] != \".csv\":\n print \"Error: the file extension is not .csv\"\n quit()\n\n inputFile = open(fileX, 'r')\n\n # Creating an empty matrix of the right size\n matrixX = []\n\n for line in inputFile:\n\n line = line.replace(\",\\n\",\"\")\n listLine = line.split(\",\")\n\n # converting the numbers to float\n for i in range(0,len(listLine)-1,4):\n for j in range(3):\n listLine[i+j+1] = float(listLine[i+j+1])\n matrixX.append(listLine)\n\n inputFile.close()\n return matrixX\n\ndef loadY(fileY):\n \"\"\"\n This function takes a .csv file containing the energies of a system and returns an array with the energies contained\n in the file.\n\n :fileY: the .csv file containing the energies of the system (string)\n :return: numpy array of shape (n_samples, 1)\n \"\"\"\n\n # Checking that the input file has the correct .csv extension\n if fileY[-4:] != \".csv\":", "answers": [" print \"Error: the file extension is not .csv\""], "length": 1194, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "07946ecf-bfbb-4f20-a962-53e6e2679cfd", "reasoning": "The loadY function mirrors loadX's pattern: after checking the file extension, it should report an error and exit. The next line after the if statement should be the error message print statement, using the same Python 2 syntax as elsewhere in the file.", "reasoning_model_answer": "print \"Error: the file extension is not .csv\"", "assistant_with_reasoning": "\nThe loadY function mirrors loadX's pattern: after checking the file extension, it should report an error and exit. The next line after the if statement should be the error message print statement, using the same Python 2 syntax as elsewhere in the file.\n\nprint \"Error: the file extension is not .csv\"", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 2.787, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 9560, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "print \"Error: the file extension is not .csv\"", "score": 0.92, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "// Created by Lawrence PC Dol. Released into the public domain.\n//\n// Source is licensed for any use, provided this copyright notice is retained.\n// No warranty for any purpose whatsoever is implied or expressed. The author\n// is not liable for any losses of any kind, direct or indirect, which result\n// from the use of this software.\n\n// Comment by Kaarel Kaljurand:\n// This file was downloaded on 2011-10-06 from\n// http://www.softwaremonkey.org/Code/src/MathEval.java\n// (see more: http://www.softwaremonkey.org/Code/MathEval)\n// Changes:\n// - package name was changed\n// - removed: import java.math.*\n// - commented out: calls to \"nextUp\" and \"getExponent\"\n// - new Double(x) -> Double.valueOf(x)\n\npackage ee.ioc.phon.android.arvutaja.command;\n\nimport java.util.*;\n\n/**\n * Math Evaluator. Provides the ability to evaluate a String math expression, with support for functions, variables and\n * standard math constants.\n *

    \n * Predefined Constants:\n *

      \n *
    • E - The double value that is closer than any other to e, the base of the natural logarithms (2.718281828459045).\n *
    • Euler - Euler's Constant (0.577215664901533).\n *
    • LN2 - Log of 2 base e (0.693147180559945).\n *
    • LN10 - Log of 10 base e (2.302585092994046).\n *
    • LOG2E - Log of e base 2 (1.442695040888963).\n *
    • LOG10E - Log of e base 10 (0.434294481903252).\n *
    • PHI - The golden ratio (1.618033988749895).\n *
    • PI - The double value that is closer than any other to pi, the ratio of the circumference of a circle to its diameter (3.141592653589793).\n *
    \n *

    \n * Supported Functions:\n *

      \n *
    • abs(val) - The absolute value of a double value.\n *
    • acos(val) - The arc cosine of a value; the returned angle is in the range 0.0 through pi.\n *
    • asin(val) - The arc sine of a value; the returned angle is in the range -pi/2 through pi/2.\n *
    • atan(val) - The arc tangent of a value; the returned angle is in the range -pi/2 through pi/2.\n *
    • cbrt(val) - The cube root of val.\n *
    • ceil(val) - The smallest (closest to negative infinity) double value that is greater than or equal to the argument and is equal to a mathematical integer.\n *
    • cos(val) - The trigonometric cosine of an angle.\n *
    • cosh(val) - The hyperbolic cosine of val.\n *
    • exp(val) - Euler's number e raised to the power of a double value.\n *
    • expm1(val) - ex-1.\n *
    • floor(val) - The largest (closest to positive infinity) double value that is less than or equal to the argument and is equal to a mathematical integer.\n *
    • getExponent(val) - The unbiased exponent used in the representation of val.\n *
    • log(val) - The natural logarithm (base e) of a double value.\n *
    • log10(val) - The base 10 logarithm of val.\n *
    • log1p(val) - The natural logarithm of (val+1).\n *
    • nextUp(val) - The floating-point value adjacent to val in the direction of positive infinity.\n *
    • random() - A double value with a positive sign, greater than or equal to 0.0 and less than 1.0.\n *
    • round(val) - The closest 64 bit integer to the argument.\n *
    • roundHE(val) - The double value that is closest in value to the argument and is equal to a mathematical integer, using the half-even rounding method.\n *
    • signum(val) - The signum function of the argument; zero if the argument is zero, 1.0 if the argument is greater than zero, -1.0 if the argument is less than zero.\n *
    • sin(val) - The trigonometric sine of an angle.\n *
    • sinh(val) - The hyperbolic sine of a double value.\n *
    • sqrt(val) - The correctly rounded positive square root of a double value.\n *
    • tan(val) - The trigonometric tangent of an angle.\n *
    • tanh(val) - The hyperbolic tangent of a double value.\n *
    • toDegrees(val) - Converts an angle measured in radians to an approximately equivalent angle measured in degrees.\n *
    • toRadians(val) - Converts an angle measured in degrees to an approximately equivalent angle measured in radians.\n *
    • ulp(val) - The size of an ulp of the argument.\n *
    \n *

    \n * Threading Design : [x] Single Threaded [ ] Threadsafe [ ] Immutable [ ] Isolated\n *\n * @author Lawrence Dol\n * @since Build 2008.0426.1016\n */\n\npublic class MathEval\nextends Object\n{\n\n// *****************************************************************************\n// INSTANCE PROPERTIES\n// *****************************************************************************\n\nprivate Map constants; // external constants\nprivate Map variables; // external variables\nprivate boolean relaxed; // allow variables to be undefined\n\nprivate int offset; // used when returning from a higher precedence sub-expression evaluation\nprivate boolean isConstant; // constant expression flag\n\n// *****************************************************************************\n// INSTANCE CREATE/DELETE\n// *****************************************************************************\n\n/**\n * Create a math evaluator.\n */\npublic MathEval() {\n super();\n\n constants=new TreeMap(String.CASE_INSENSITIVE_ORDER);\n setConstant(\"E\" ,Math.E);\n setConstant(\"Euler\" ,0.577215664901533D);\n setConstant(\"LN2\" ,0.693147180559945D);\n setConstant(\"LN10\" ,2.302585092994046D);\n setConstant(\"LOG2E\" ,1.442695040888963D);\n setConstant(\"LOG10E\",0.434294481903252D);\n setConstant(\"PHI\" ,1.618033988749895D);\n setConstant(\"PI\" ,Math.PI);\n\n variables=new TreeMap(String.CASE_INSENSITIVE_ORDER);\n }\n\n// *****************************************************************************\n// INSTANCE METHODS - ACCESSORS\n// *****************************************************************************\n\n/** Set a named constant (constant names are not case-sensitive). Constants are like variables but are not cleared by clear(). Variables of the same name have precedence over constants. */\npublic double getConstant(String nam) {\n Double val=constants.get(nam);\n\n return (val==null ? 0 : val.doubleValue());\n }\n\n/** Set a named constant (constants names are not case-sensitive). Constants are like variables but are not cleared by clear(). Variables of the same name have precedence over constants. */\npublic MathEval setConstant(String nam, double val) {\n return setConstant(nam,Double.valueOf(val));\n }\n\n/** Set a named constant (constants names are not case-sensitive). Constants are like variables but are not cleared by clear(). Variables of the same name have precedence over constants. */\npublic MathEval setConstant(String nam, Double val) {\n if(!Character.isLetter(nam.charAt(0))) { throw new IllegalArgumentException(\"Constant names must start with a letter\" ); }\n if(nam.indexOf('(')!=-1 ) { throw new IllegalArgumentException(\"Constant names may not contain a parenthesis\"); }\n if(nam.indexOf(')')!=-1 ) { throw new IllegalArgumentException(\"Constant names may not contain a parenthesis\"); }\n if(constants.get(nam)!=null ) { throw new IllegalArgumentException(\"Constants may not be redefined\" ); }\n constants.put(nam,val);\n return this;\n }\n\n/** Set a named variable (variables names are not case-sensitive). */\npublic double getVariable(String nam) {\n Double val=variables.get(nam);\n\n return (val==null ? 0 : val.doubleValue());\n }\n\n/** Set a named variable (variables names are not case-sensitive). */\npublic MathEval setVariable(String nam, double val) {\n return setVariable(nam,Double.valueOf(val));\n }\n\n/** Set a named variable (variables names are not case-sensitive). */\npublic MathEval setVariable(String nam, Double val) {\n if(!Character.isLetter(nam.charAt(0))) { throw new IllegalArgumentException(\"Variable must start with a letter\" ); }\n if(nam.indexOf('(')!=-1 ) { throw new IllegalArgumentException(\"Variable names may not contain a parenthesis\"); }\n if(nam.indexOf(')')!=-1 ) { throw new IllegalArgumentException(\"Variable names may not contain a parenthesis\"); }\n variables.put(nam,val);\n return this;\n }\n\n/** Clear all variables (constants are not affected). */\npublic MathEval clear() {\n variables.clear();\n return this;\n }\n\n/** Get whether a variable which is used in an expression is required to be explicitly set. If not explicitly set, the value 0.0 is assumed. */\npublic boolean getVariableRequired() {", "answers": [" return relaxed;"], "length": 1116, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "e1334689-17e0-4cd9-9b9a-ec48fefbe9af", "reasoning": "The method getVariableRequired() should return whether variables must be explicitly set. The class has a boolean field 'relaxed' that allows variables to be undefined, so the required flag is the opposite of relaxed. Therefore the next line inside the method body is a return of the negated relaxed flag.", "reasoning_model_answer": "return !relaxed;", "assistant_with_reasoning": "\nThe method getVariableRequired() should return whether variables must be explicitly set. The class has a boolean field 'relaxed' that allows variables to be undefined, so the required flag is the opposite of relaxed. Therefore the next line inside the method body is a return of the negated relaxed flag.\n\nreturn !relaxed;", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.096, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 9216, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "return !relaxed;", "score": 0.86, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "\"\"\"The tests for the Legacy Mqtt vacuum platform.\"\"\"\nfrom copy import deepcopy\nimport json\nfrom unittest.mock import patch\n\nimport pytest\n\nfrom homeassistant.components import vacuum\nfrom homeassistant.components.mqtt import CONF_COMMAND_TOPIC\nfrom homeassistant.components.mqtt.vacuum import schema_legacy as mqttvacuum\nfrom homeassistant.components.mqtt.vacuum.schema import services_to_strings\nfrom homeassistant.components.mqtt.vacuum.schema_legacy import (\n ALL_SERVICES,\n SERVICE_TO_STRING,\n)\nfrom homeassistant.components.vacuum import (\n ATTR_BATTERY_ICON,\n ATTR_BATTERY_LEVEL,\n ATTR_FAN_SPEED,\n ATTR_FAN_SPEED_LIST,\n ATTR_STATUS,\n)\nfrom homeassistant.const import CONF_NAME, CONF_PLATFORM, STATE_OFF, STATE_ON\nfrom homeassistant.setup import async_setup_component\n\nfrom .test_common import (\n help_test_availability_when_connection_lost,\n help_test_availability_without_topic,\n help_test_custom_availability_payload,\n help_test_default_availability_payload,\n help_test_discovery_broken,\n help_test_discovery_removal,\n help_test_discovery_update,\n help_test_discovery_update_attr,\n help_test_discovery_update_unchanged,\n help_test_entity_debug_info_message,\n help_test_entity_device_info_remove,\n help_test_entity_device_info_update,\n help_test_entity_device_info_with_connection,\n help_test_entity_device_info_with_identifier,\n help_test_entity_id_update_discovery_update,\n help_test_entity_id_update_subscriptions,\n help_test_setting_attribute_via_mqtt_json_message,\n help_test_setting_attribute_with_template,\n help_test_unique_id,\n help_test_update_with_json_attrs_bad_JSON,\n help_test_update_with_json_attrs_not_dict,\n)\n\nfrom tests.common import async_fire_mqtt_message\nfrom tests.components.vacuum import common\n\nDEFAULT_CONFIG = {\n CONF_PLATFORM: \"mqtt\",\n CONF_NAME: \"mqtttest\",\n CONF_COMMAND_TOPIC: \"vacuum/command\",\n mqttvacuum.CONF_SEND_COMMAND_TOPIC: \"vacuum/send_command\",\n mqttvacuum.CONF_BATTERY_LEVEL_TOPIC: \"vacuum/state\",\n mqttvacuum.CONF_BATTERY_LEVEL_TEMPLATE: \"{{ value_json.battery_level }}\",\n mqttvacuum.CONF_CHARGING_TOPIC: \"vacuum/state\",\n mqttvacuum.CONF_CHARGING_TEMPLATE: \"{{ value_json.charging }}\",\n mqttvacuum.CONF_CLEANING_TOPIC: \"vacuum/state\",\n mqttvacuum.CONF_CLEANING_TEMPLATE: \"{{ value_json.cleaning }}\",\n mqttvacuum.CONF_DOCKED_TOPIC: \"vacuum/state\",\n mqttvacuum.CONF_DOCKED_TEMPLATE: \"{{ value_json.docked }}\",\n mqttvacuum.CONF_ERROR_TOPIC: \"vacuum/state\",\n mqttvacuum.CONF_ERROR_TEMPLATE: \"{{ value_json.error }}\",\n mqttvacuum.CONF_FAN_SPEED_TOPIC: \"vacuum/state\",\n mqttvacuum.CONF_FAN_SPEED_TEMPLATE: \"{{ value_json.fan_speed }}\",\n mqttvacuum.CONF_SET_FAN_SPEED_TOPIC: \"vacuum/set_fan_speed\",\n mqttvacuum.CONF_FAN_SPEED_LIST: [\"min\", \"medium\", \"high\", \"max\"],\n}\n\nDEFAULT_CONFIG_2 = {vacuum.DOMAIN: {\"platform\": \"mqtt\", \"name\": \"test\"}}\n\n\nasync def test_default_supported_features(hass, mqtt_mock):\n \"\"\"Test that the correct supported features.\"\"\"\n assert await async_setup_component(\n hass, vacuum.DOMAIN, {vacuum.DOMAIN: DEFAULT_CONFIG}\n )\n await hass.async_block_till_done()\n entity = hass.states.get(\"vacuum.mqtttest\")\n entity_features = entity.attributes.get(mqttvacuum.CONF_SUPPORTED_FEATURES, 0)\n assert sorted(services_to_strings(entity_features, SERVICE_TO_STRING)) == sorted(\n [\n \"turn_on\",\n \"turn_off\",\n \"stop\",\n \"return_home\",\n \"battery\",\n \"status\",\n \"clean_spot\",\n ]\n )\n\n\nasync def test_all_commands(hass, mqtt_mock):\n \"\"\"Test simple commands to the vacuum.\"\"\"\n config = deepcopy(DEFAULT_CONFIG)\n config[mqttvacuum.CONF_SUPPORTED_FEATURES] = services_to_strings(\n ALL_SERVICES, SERVICE_TO_STRING\n )\n\n assert await async_setup_component(hass, vacuum.DOMAIN, {vacuum.DOMAIN: config})\n await hass.async_block_till_done()\n\n await common.async_turn_on(hass, \"vacuum.mqtttest\")\n mqtt_mock.async_publish.assert_called_once_with(\n \"vacuum/command\", \"turn_on\", 0, False\n )\n mqtt_mock.async_publish.reset_mock()\n\n await common.async_turn_off(hass, \"vacuum.mqtttest\")\n mqtt_mock.async_publish.assert_called_once_with(\n \"vacuum/command\", \"turn_off\", 0, False\n )\n mqtt_mock.async_publish.reset_mock()\n\n await common.async_stop(hass, \"vacuum.mqtttest\")\n mqtt_mock.async_publish.assert_called_once_with(\"vacuum/command\", \"stop\", 0, False)\n mqtt_mock.async_publish.reset_mock()\n\n await common.async_clean_spot(hass, \"vacuum.mqtttest\")\n mqtt_mock.async_publish.assert_called_once_with(\n \"vacuum/command\", \"clean_spot\", 0, False\n )\n mqtt_mock.async_publish.reset_mock()\n\n await common.async_locate(hass, \"vacuum.mqtttest\")\n mqtt_mock.async_publish.assert_called_once_with(\n \"vacuum/command\", \"locate\", 0, False\n )\n mqtt_mock.async_publish.reset_mock()\n\n await common.async_start_pause(hass, \"vacuum.mqtttest\")\n mqtt_mock.async_publish.assert_called_once_with(\n \"vacuum/command\", \"start_pause\", 0, False\n )\n mqtt_mock.async_publish.reset_mock()\n\n await common.async_return_to_base(hass, \"vacuum.mqtttest\")\n mqtt_mock.async_publish.assert_called_once_with(\n \"vacuum/command\", \"return_to_base\", 0, False\n )\n mqtt_mock.async_publish.reset_mock()\n\n await common.async_set_fan_speed(hass, \"high\", \"vacuum.mqtttest\")\n mqtt_mock.async_publish.assert_called_once_with(\n \"vacuum/set_fan_speed\", \"high\", 0, False\n )\n mqtt_mock.async_publish.reset_mock()\n\n await common.async_send_command(hass, \"44 FE 93\", entity_id=\"vacuum.mqtttest\")\n mqtt_mock.async_publish.assert_called_once_with(\n \"vacuum/send_command\", \"44 FE 93\", 0, False\n )\n mqtt_mock.async_publish.reset_mock()\n\n await common.async_send_command(\n hass, \"44 FE 93\", {\"key\": \"value\"}, entity_id=\"vacuum.mqtttest\"\n )\n assert json.loads(mqtt_mock.async_publish.mock_calls[-1][1][1]) == {\n \"command\": \"44 FE 93\",\n \"key\": \"value\",\n }\n\n await common.async_send_command(\n hass, \"44 FE 93\", {\"key\": \"value\"}, entity_id=\"vacuum.mqtttest\"\n )\n assert json.loads(mqtt_mock.async_publish.mock_calls[-1][1][1]) == {\n \"command\": \"44 FE 93\",\n \"key\": \"value\",\n }\n\n\nasync def test_commands_without_supported_features(hass, mqtt_mock):\n \"\"\"Test commands which are not supported by the vacuum.\"\"\"\n config = deepcopy(DEFAULT_CONFIG)\n services = mqttvacuum.STRING_TO_SERVICE[\"status\"]\n config[mqttvacuum.CONF_SUPPORTED_FEATURES] = services_to_strings(\n services, SERVICE_TO_STRING\n )\n\n assert await async_setup_component(hass, vacuum.DOMAIN, {vacuum.DOMAIN: config})\n await hass.async_block_till_done()\n\n await common.async_turn_on(hass, \"vacuum.mqtttest\")\n mqtt_mock.async_publish.assert_not_called()\n mqtt_mock.async_publish.reset_mock()\n\n await common.async_turn_off(hass, \"vacuum.mqtttest\")\n mqtt_mock.async_publish.assert_not_called()\n mqtt_mock.async_publish.reset_mock()\n\n await common.async_stop(hass, \"vacuum.mqtttest\")\n mqtt_mock.async_publish.assert_not_called()\n mqtt_mock.async_publish.reset_mock()\n\n await common.async_clean_spot(hass, \"vacuum.mqtttest\")\n mqtt_mock.async_publish.assert_not_called()\n mqtt_mock.async_publish.reset_mock()\n\n await common.async_locate(hass, \"vacuum.mqtttest\")\n mqtt_mock.async_publish.assert_not_called()\n mqtt_mock.async_publish.reset_mock()\n\n await common.async_start_pause(hass, \"vacuum.mqtttest\")\n mqtt_mock.async_publish.assert_not_called()\n mqtt_mock.async_publish.reset_mock()\n\n await common.async_return_to_base(hass, \"vacuum.mqtttest\")\n mqtt_mock.async_publish.assert_not_called()\n mqtt_mock.async_publish.reset_mock()\n\n await common.async_set_fan_speed(hass, \"high\", \"vacuum.mqtttest\")\n mqtt_mock.async_publish.assert_not_called()\n mqtt_mock.async_publish.reset_mock()\n\n await common.async_send_command(hass, \"44 FE 93\", entity_id=\"vacuum.mqtttest\")\n mqtt_mock.async_publish.assert_not_called()\n mqtt_mock.async_publish.reset_mock()\n\n\nasync def test_attributes_without_supported_features(hass, mqtt_mock):\n \"\"\"Test attributes which are not supported by the vacuum.\"\"\"\n config = deepcopy(DEFAULT_CONFIG)\n services = mqttvacuum.STRING_TO_SERVICE[\"turn_on\"]\n config[mqttvacuum.CONF_SUPPORTED_FEATURES] = services_to_strings(\n services, SERVICE_TO_STRING\n )\n\n assert await async_setup_component(hass, vacuum.DOMAIN, {vacuum.DOMAIN: config})\n await hass.async_block_till_done()\n\n message = \"\"\"{\n \"battery_level\": 54,\n \"cleaning\": true,\n \"docked\": false,\n \"charging\": false,\n \"fan_speed\": \"max\"\n }\"\"\"\n async_fire_mqtt_message(hass, \"vacuum/state\", message)\n state = hass.states.get(\"vacuum.mqtttest\")\n assert state.state == STATE_ON\n assert state.attributes.get(ATTR_BATTERY_LEVEL) is None\n assert state.attributes.get(ATTR_BATTERY_ICON) is None\n assert state.attributes.get(ATTR_FAN_SPEED) is None\n assert state.attributes.get(ATTR_FAN_SPEED_LIST) is None\n\n\nasync def test_status(hass, mqtt_mock):\n \"\"\"Test status updates from the vacuum.\"\"\"\n config = deepcopy(DEFAULT_CONFIG)\n config[mqttvacuum.CONF_SUPPORTED_FEATURES] = services_to_strings(\n ALL_SERVICES, SERVICE_TO_STRING\n )\n\n assert await async_setup_component(hass, vacuum.DOMAIN, {vacuum.DOMAIN: config})\n await hass.async_block_till_done()\n\n message = \"\"\"{\n \"battery_level\": 54,\n \"cleaning\": true,\n \"docked\": false,\n \"charging\": false,\n \"fan_speed\": \"max\"\n }\"\"\"\n async_fire_mqtt_message(hass, \"vacuum/state\", message)\n state = hass.states.get(\"vacuum.mqtttest\")\n assert state.state == STATE_ON\n assert state.attributes.get(ATTR_BATTERY_ICON) == \"mdi:battery-50\"\n assert state.attributes.get(ATTR_BATTERY_LEVEL) == 54\n assert state.attributes.get(ATTR_FAN_SPEED) == \"max\"\n\n message = \"\"\"{\n \"battery_level\": 61,\n \"docked\": true,\n \"cleaning\": false,\n \"charging\": true,\n \"fan_speed\": \"min\"\n }\"\"\"\n\n async_fire_mqtt_message(hass, \"vacuum/state\", message)\n state = hass.states.get(\"vacuum.mqtttest\")\n assert state.state == STATE_OFF\n assert state.attributes.get(ATTR_BATTERY_ICON) == \"mdi:battery-charging-60\"\n assert state.attributes.get(ATTR_BATTERY_LEVEL) == 61\n assert state.attributes.get(ATTR_FAN_SPEED) == \"min\"\n\n\nasync def test_status_battery(hass, mqtt_mock):\n \"\"\"Test status updates from the vacuum.\"\"\"\n config = deepcopy(DEFAULT_CONFIG)\n config[mqttvacuum.CONF_SUPPORTED_FEATURES] = services_to_strings(\n ALL_SERVICES, SERVICE_TO_STRING\n )\n\n assert await async_setup_component(hass, vacuum.DOMAIN, {vacuum.DOMAIN: config})\n await hass.async_block_till_done()\n\n message = \"\"\"{\n \"battery_level\": 54\n }\"\"\"\n async_fire_mqtt_message(hass, \"vacuum/state\", message)\n state = hass.states.get(\"vacuum.mqtttest\")\n assert state.attributes.get(ATTR_BATTERY_ICON) == \"mdi:battery-50\"\n\n\nasync def test_status_cleaning(hass, mqtt_mock):\n \"\"\"Test status updates from the vacuum.\"\"\"\n config = deepcopy(DEFAULT_CONFIG)\n config[mqttvacuum.CONF_SUPPORTED_FEATURES] = services_to_strings(\n ALL_SERVICES, SERVICE_TO_STRING\n )\n\n assert await async_setup_component(hass, vacuum.DOMAIN, {vacuum.DOMAIN: config})\n await hass.async_block_till_done()\n\n message = \"\"\"{\n \"cleaning\": true\n }\"\"\"\n async_fire_mqtt_message(hass, \"vacuum/state\", message)\n state = hass.states.get(\"vacuum.mqtttest\")\n assert state.state == STATE_ON\n\n\nasync def test_status_docked(hass, mqtt_mock):\n \"\"\"Test status updates from the vacuum.\"\"\"\n config = deepcopy(DEFAULT_CONFIG)\n config[mqttvacuum.CONF_SUPPORTED_FEATURES] = services_to_strings(\n ALL_SERVICES, SERVICE_TO_STRING\n )\n\n assert await async_setup_component(hass, vacuum.DOMAIN, {vacuum.DOMAIN: config})\n await hass.async_block_till_done()\n\n message = \"\"\"{\n \"docked\": true\n }\"\"\"\n async_fire_mqtt_message(hass, \"vacuum/state\", message)\n state = hass.states.get(\"vacuum.mqtttest\")\n assert state.state == STATE_OFF\n\n\nasync def test_status_charging(hass, mqtt_mock):\n \"\"\"Test status updates from the vacuum.\"\"\"\n config = deepcopy(DEFAULT_CONFIG)\n config[mqttvacuum.CONF_SUPPORTED_FEATURES] = services_to_strings(\n ALL_SERVICES, SERVICE_TO_STRING\n )\n\n assert await async_setup_component(hass, vacuum.DOMAIN, {vacuum.DOMAIN: config})\n await hass.async_block_till_done()\n\n message = \"\"\"{\n \"charging\": true\n }\"\"\"\n async_fire_mqtt_message(hass, \"vacuum/state\", message)\n state = hass.states.get(\"vacuum.mqtttest\")\n assert state.attributes.get(ATTR_BATTERY_ICON) == \"mdi:battery-outline\"\n\n\nasync def test_status_fan_speed(hass, mqtt_mock):\n \"\"\"Test status updates from the vacuum.\"\"\"\n config = deepcopy(DEFAULT_CONFIG)\n config[mqttvacuum.CONF_SUPPORTED_FEATURES] = services_to_strings(\n ALL_SERVICES, SERVICE_TO_STRING\n )\n\n assert await async_setup_component(hass, vacuum.DOMAIN, {vacuum.DOMAIN: config})\n await hass.async_block_till_done()\n\n message = \"\"\"{\n \"fan_speed\": \"max\"\n }\"\"\"\n async_fire_mqtt_message(hass, \"vacuum/state\", message)\n state = hass.states.get(\"vacuum.mqtttest\")\n assert state.attributes.get(ATTR_FAN_SPEED) == \"max\"\n\n\nasync def test_status_fan_speed_list(hass, mqtt_mock):\n \"\"\"Test status updates from the vacuum.\"\"\"\n config = deepcopy(DEFAULT_CONFIG)\n config[mqttvacuum.CONF_SUPPORTED_FEATURES] = services_to_strings(\n ALL_SERVICES, SERVICE_TO_STRING\n )\n\n assert await async_setup_component(hass, vacuum.DOMAIN, {vacuum.DOMAIN: config})\n await hass.async_block_till_done()\n\n state = hass.states.get(\"vacuum.mqtttest\")\n assert state.attributes.get(ATTR_FAN_SPEED_LIST) == [\"min\", \"medium\", \"high\", \"max\"]\n\n\nasync def test_status_no_fan_speed_list(hass, mqtt_mock):\n \"\"\"Test status updates from the vacuum.\n\n If the vacuum doesn't support fan speed, fan speed list should be None.\n \"\"\"\n config = deepcopy(DEFAULT_CONFIG)\n services = ALL_SERVICES - mqttvacuum.SUPPORT_FAN_SPEED\n config[mqttvacuum.CONF_SUPPORTED_FEATURES] = services_to_strings(\n services, SERVICE_TO_STRING\n )\n\n assert await async_setup_component(hass, vacuum.DOMAIN, {vacuum.DOMAIN: config})\n await hass.async_block_till_done()\n\n state = hass.states.get(\"vacuum.mqtttest\")\n assert state.attributes.get(ATTR_FAN_SPEED_LIST) is None\n\n\nasync def test_status_error(hass, mqtt_mock):\n \"\"\"Test status updates from the vacuum.\"\"\"\n config = deepcopy(DEFAULT_CONFIG)\n config[mqttvacuum.CONF_SUPPORTED_FEATURES] = services_to_strings(\n ALL_SERVICES, SERVICE_TO_STRING\n )\n\n assert await async_setup_component(hass, vacuum.DOMAIN, {vacuum.DOMAIN: config})\n await hass.async_block_till_done()\n\n message = \"\"\"{\n \"error\": \"Error1\"\n }\"\"\"\n async_fire_mqtt_message(hass, \"vacuum/state\", message)\n state = hass.states.get(\"vacuum.mqtttest\")\n assert state.attributes.get(ATTR_STATUS) == \"Error: Error1\"\n\n message = \"\"\"{\n \"error\": \"\"\n }\"\"\"\n async_fire_mqtt_message(hass, \"vacuum/state\", message)\n state = hass.states.get(\"vacuum.mqtttest\")\n assert state.attributes.get(ATTR_STATUS) == \"Stopped\"\n\n\nasync def test_battery_template(hass, mqtt_mock):\n \"\"\"Test that you can use non-default templates for battery_level.\"\"\"\n config = deepcopy(DEFAULT_CONFIG)\n config.update(\n {\n mqttvacuum.CONF_SUPPORTED_FEATURES: services_to_strings(\n ALL_SERVICES, SERVICE_TO_STRING\n ),\n mqttvacuum.CONF_BATTERY_LEVEL_TOPIC: \"retroroomba/battery_level\",\n mqttvacuum.CONF_BATTERY_LEVEL_TEMPLATE: \"{{ value }}\",\n }\n )\n\n assert await async_setup_component(hass, vacuum.DOMAIN, {vacuum.DOMAIN: config})\n await hass.async_block_till_done()\n\n async_fire_mqtt_message(hass, \"retroroomba/battery_level\", \"54\")\n state = hass.states.get(\"vacuum.mqtttest\")\n assert state.attributes.get(ATTR_BATTERY_LEVEL) == 54\n assert state.attributes.get(ATTR_BATTERY_ICON) == \"mdi:battery-50\"\n\n\nasync def test_status_invalid_json(hass, mqtt_mock):\n \"\"\"Test to make sure nothing breaks if the vacuum sends bad JSON.\"\"\"\n config = deepcopy(DEFAULT_CONFIG)\n config[mqttvacuum.CONF_SUPPORTED_FEATURES] = services_to_strings(\n ALL_SERVICES, SERVICE_TO_STRING\n )\n\n assert await async_setup_component(hass, vacuum.DOMAIN, {vacuum.DOMAIN: config})\n await hass.async_block_till_done()\n\n async_fire_mqtt_message(hass, \"vacuum/state\", '{\"asdfasas false}')\n state = hass.states.get(\"vacuum.mqtttest\")\n assert state.state == STATE_OFF\n assert state.attributes.get(ATTR_STATUS) == \"Stopped\"\n\n\nasync def test_missing_battery_template(hass, mqtt_mock):\n \"\"\"Test to make sure missing template is not allowed.\"\"\"\n config = deepcopy(DEFAULT_CONFIG)\n config.pop(mqttvacuum.CONF_BATTERY_LEVEL_TEMPLATE)\n\n assert await async_setup_component(hass, vacuum.DOMAIN, {vacuum.DOMAIN: config})\n await hass.async_block_till_done()\n\n state = hass.states.get(\"vacuum.mqtttest\")\n assert state is None\n\n\nasync def test_missing_charging_template(hass, mqtt_mock):\n \"\"\"Test to make sure missing template is not allowed.\"\"\"\n config = deepcopy(DEFAULT_CONFIG)\n config.pop(mqttvacuum.CONF_CHARGING_TEMPLATE)\n\n assert await async_setup_component(hass, vacuum.DOMAIN, {vacuum.DOMAIN: config})\n await hass.async_block_till_done()\n\n state = hass.states.get(\"vacuum.mqtttest\")\n assert state is None\n\n\nasync def test_missing_cleaning_template(hass, mqtt_mock):\n \"\"\"Test to make sure missing template is not allowed.\"\"\"\n config = deepcopy(DEFAULT_CONFIG)\n config.pop(mqttvacuum.CONF_CLEANING_TEMPLATE)", "answers": [" assert await async_setup_component(hass, vacuum.DOMAIN, {vacuum.DOMAIN: config})"], "length": 1173, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "7e470761-74dc-446f-8ce0-cb52877b944c", "reasoning": "The test function test_missing_cleaning_template follows the same pattern as the previous missing template tests. After removing the cleaning template from the config, the next step is to attempt setting up the component and assert that the setup succeeds (returns True). Therefore, the next line is the assert statement calling async_setup_component with the modified config.", "reasoning_model_answer": "assert await async_setup_component(hass, vacuum.DOMAIN, {vacuum.DOMAIN: config})", "assistant_with_reasoning": "\nThe test function test_missing_cleaning_template follows the same pattern as the previous missing template tests. After removing the cleaning template from the config, the next step is to attempt setting up the component and assert that the setup succeeds (returns True). Therefore, the next line is the assert statement calling async_setup_component with the modified config.\n\nassert await async_setup_component(hass, vacuum.DOMAIN, {vacuum.DOMAIN: config})", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.289, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 18067, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "assert await async_setup_component(hass, vacuum.DOMAIN, {vacuum.DOMAIN: config})", "score": 0.98, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/*\n* Licensed to the Apache Software Foundation (ASF) under one\n* or more contributor license agreements. See the NOTICE file\n* distributed with this work for additional information\n* regarding copyright ownership. The ASF licenses this file\n* to you under the Apache License, Version 2.0 (the\n* \"License\"); you may not use this file except in compliance\n* with the License. You may obtain a copy of the License at\n*\n* http://www.apache.org/licenses/LICENSE-2.0\n*\n* Unless required by applicable law or agreed to in writing,\n* software distributed under the License is distributed on an\n* \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n* KIND, either express or implied. See the License for the\n* specific language governing permissions and limitations\n* under the License.\n*/\npackage org.apache.cassandra.utils;\n\nimport java.util.Random;\n\n\n/**\n * Base class for hashtables that use open addressing to resolve collisions.\n */\n\nabstract public class FastHash implements Cloneable\n{\n /** the current number of occupied slots in the hash. */\n protected transient int size_;\n \n /** the current number of free slots in the hash. */\n protected transient int free_;\n \n /** the load above which rehashing occurs. */\n protected static final float DEFAULT_LOAD_FACTOR = 0.5f;\n \n /**\n * the default initial capacity for the hash table. This is one less than a\n * prime value because one is added to it when searching for a prime\n * capacity to account for the free slot required by open addressing. Thus,\n * the real default capacity is 11.\n */\n protected static final int DEFAULT_INITIAL_CAPACITY = 10;\n \n /**\n * Determines how full the internal table can become before rehashing is\n * required. This must be a value in the range: 0.0 < loadFactor < 1.0. The\n * default value is 0.5, which is about as large as you can get in open\n * addressing without hurting performance. Cf. Knuth, Volume 3., Chapter 6.\n */\n protected float loadFactor_;\n \n /**\n * The maximum number of elements allowed without allocating more space.\n */\n protected int maxSize_;\n \n /**\n * The number of removes that should be performed before an auto-compaction\n * occurs.\n */\n protected int autoCompactRemovesRemaining_;\n \n /**\n * The auto-compaction factor for the table.\n * \n * @see #setAutoCompactionFactor\n */\n protected float autoCompactionFactor_;\n \n /**\n * @see\n */\n private boolean autoCompactTemporaryDisable_ = false;\n \n /**\n * Creates a new THash instance with the default capacity and\n * load factor.\n */\n public FastHash()\n {\n this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR);\n }\n \n /**\n * Creates a new THash instance with a prime capacity at or\n * near the specified capacity and with the default load factor.\n * \n * @param initialCapacity\n * an int value\n */\n public FastHash(int initialCapacity)\n {\n this(initialCapacity, DEFAULT_LOAD_FACTOR);\n }\n \n /**\n * Creates a new THash instance with a prime capacity at or\n * near the minimum needed to hold initialCapacity elements with\n * load factor loadFactor without triggering a rehash.\n * \n * @param initialCapacity\n * an int value\n * @param loadFactor\n * a float value\n */\n public FastHash(int initialCapacity, float loadFactor)\n {\n super();\n loadFactor_ = loadFactor;\n \n // Through testing, the load factor (especially the default load factor)\n // has been\n // found to be a pretty good starting auto-compaction factor.\n autoCompactionFactor_ = loadFactor;\n \n setUp((int) Math.ceil(initialCapacity / loadFactor));\n }\n \n public Object clone()\n {\n try\n {\n return super.clone();\n }\n catch (CloneNotSupportedException cnse)\n {\n return null; // it's supported\n }\n }\n \n /**\n * Tells whether this set is currently holding any elements.\n * \n * @return a boolean value\n */\n public boolean isEmpty()\n {\n return 0 == size_;\n }\n \n /**\n * Returns the number of distinct elements in this collection.\n * \n * @return an int value\n */\n public int size()\n {\n return size_;\n }\n \n /**\n * @return the current physical capacity of the hash table.\n */\n abstract protected int capacity();\n \n /**\n * Ensure that this hashtable has sufficient capacity to hold\n * desiredCapacity additional elements without\n * requiring a rehash. This is a tuning method you can call\n * before doing a large insert.\n *\n * @param desiredCapacity an int value\n */\n public void ensureCapacity(int desiredCapacity)\n {\n if (desiredCapacity > (maxSize_ - size()))\n {\n rehash(PrimeFinder.nextPrime((int) Math.ceil(desiredCapacity\n + size() / loadFactor_) + 1));\n computeMaxSize(capacity());\n }\n }\n \n /**\n * Compresses the hashtable to the minimum prime size (as defined by\n * PrimeFinder) that will hold all of the elements currently in the table.\n * If you have done a lot of remove operations and plan to do a\n * lot of queries or insertions or iteration, it is a good idea to invoke\n * this method. Doing so will accomplish two things:\n * \n *

      \n *
    1. You'll free memory allocated to the table but no longer needed\n * because of the remove()s.
    2. \n * \n *
    3. You'll get better query/insert/iterator performance because there\n * won't be any REMOVED slots to skip over when probing for\n * indices in the table.
    4. \n *
    \n */\n public void compact()\n {\n // need at least one free spot for open addressing\n rehash(PrimeFinder.nextPrime((int) Math.ceil(size() / loadFactor_) + 1));\n computeMaxSize(capacity());\n \n // If auto-compaction is enabled, re-determine the compaction interval\n if (autoCompactionFactor_ != 0)\n {\n computeNextAutoCompactionAmount(size());\n }\n }\n \n /**\n * The auto-compaction factor controls whether and when a table performs a\n * {@link #compact} automatically after a certain number of remove\n * operations. If the value is non-zero, the number of removes that need to\n * occur for auto-compaction is the size of table at the time of the\n * previous compaction (or the initial capacity) multiplied by this factor.\n *

    \n * Setting this value to zero will disable auto-compaction.\n */\n public void setAutoCompactionFactor(float factor)\n {\n if (factor < 0)\n {\n throw new IllegalArgumentException(\"Factor must be >= 0: \" + factor);\n }\n \n autoCompactionFactor_ = factor;\n }\n \n /**\n * @see #setAutoCompactionFactor\n */\n public float getAutoCompactionFactor()\n {\n return autoCompactionFactor_;\n }\n \n /**\n * This simply calls {@link #compact compact}. It is included for symmetry\n * with other collection classes. Note that the name of this method is\n * somewhat misleading (which is why we prefer compact) as the\n * load factor may require capacity above and beyond the size of this\n * collection.\n * \n * @see #compact\n */\n public final void trimToSize()\n {\n compact();\n }\n \n /**\n * Delete the record at index. Reduces the size of the\n * collection by one.\n * \n * @param index\n * an int value\n */\n protected void removeAt(int index)\n {\n size_--;\n \n // If auto-compaction is enabled, see if we need to compact\n if (autoCompactionFactor_ != 0)\n {\n autoCompactRemovesRemaining_--;\n \n if (!autoCompactTemporaryDisable_", "answers": [" && autoCompactRemovesRemaining_ <= 0)"], "length": 1066, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "98d08413-44a1-4536-88d2-c25cc854fa68", "reasoning": "The method removeAt decrements size_, then checks auto-compaction. After confirming autoCompactionFactor_ != 0, it decrements autoCompactRemovesRemaining_ and needs to test whether auto-compaction should run. The condition starts with 'if (!autoCompactTemporaryDisable_' and must also check that the remaining removals count is <= 0. Therefore the next line completes the if condition with the additional check and closing parenthesis.", "reasoning_model_answer": "&& autoCompactRemovesRemaining_ <= 0)", "assistant_with_reasoning": "\nThe method removeAt decrements size_, then checks auto-compaction. After confirming autoCompactionFactor_ != 0, it decrements autoCompactRemovesRemaining_ and needs to test whether auto-compaction should run. The condition starts with 'if (!autoCompactTemporaryDisable_' and must also check that the remaining removals count is <= 0. Therefore the next line completes the if condition with the additional check and closing parenthesis.\n\n&& autoCompactRemovesRemaining_ <= 0)", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 5.949, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 8329, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "&& autoCompactRemovesRemaining_ <= 0)", "score": 0.79, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "\"\"\"\nThis module converts requested URLs to callback view functions.\n\nURLResolver is the main class here. Its resolve() method takes a URL (as\na string) and returns a ResolverMatch object which provides access to all\nattributes of the resolved URL match.\n\"\"\"\nimport functools\nimport inspect\nimport re\nimport threading\nfrom importlib import import_module\nfrom urllib.parse import quote\n\nfrom django.conf import settings\nfrom django.core.checks import Error, Warning\nfrom django.core.checks.urls import check_resolver\nfrom django.core.exceptions import ImproperlyConfigured\nfrom django.utils.datastructures import MultiValueDict\nfrom django.utils.functional import cached_property\nfrom django.utils.http import RFC3986_SUBDELIMS, escape_leading_slashes\nfrom django.utils.regex_helper import normalize\nfrom django.utils.translation import get_language\n\nfrom .converters import get_converter\nfrom .exceptions import NoReverseMatch, Resolver404\nfrom .utils import get_callable\n\n\nclass ResolverMatch:\n def __init__(self, func, args, kwargs, url_name=None, app_names=None, namespaces=None):\n self.func = func\n self.args = args\n self.kwargs = kwargs\n self.url_name = url_name\n\n # If a URLRegexResolver doesn't have a namespace or app_name, it passes\n # in an empty value.\n self.app_names = [x for x in app_names if x] if app_names else []\n self.app_name = ':'.join(self.app_names)\n self.namespaces = [x for x in namespaces if x] if namespaces else []\n self.namespace = ':'.join(self.namespaces)\n\n if not hasattr(func, '__name__'):\n # A class-based view\n self._func_path = func.__class__.__module__ + '.' + func.__class__.__name__\n else:\n # A function-based view\n self._func_path = func.__module__ + '.' + func.__name__\n\n view_path = url_name or self._func_path\n self.view_name = ':'.join(self.namespaces + [view_path])\n\n def __getitem__(self, index):\n return (self.func, self.args, self.kwargs)[index]\n\n def __repr__(self):\n return \"ResolverMatch(func=%s, args=%s, kwargs=%s, url_name=%s, app_names=%s, namespaces=%s)\" % (\n self._func_path, self.args, self.kwargs, self.url_name,\n self.app_names, self.namespaces,\n )\n\n\n@functools.lru_cache(maxsize=None)\ndef get_resolver(urlconf=None):\n if urlconf is None:\n urlconf = settings.ROOT_URLCONF\n return URLResolver(RegexPattern(r'^/'), urlconf)\n\n\n@functools.lru_cache(maxsize=None)\ndef get_ns_resolver(ns_pattern, resolver, converters):\n # Build a namespaced resolver for the given parent URLconf pattern.\n # This makes it possible to have captured parameters in the parent\n # URLconf pattern.\n pattern = RegexPattern(ns_pattern)\n pattern.converters = dict(converters)\n ns_resolver = URLResolver(pattern, resolver.url_patterns)\n return URLResolver(RegexPattern(r'^/'), [ns_resolver])\n\n\nclass LocaleRegexDescriptor:\n def __init__(self, attr):\n self.attr = attr\n\n def __get__(self, instance, cls=None):\n \"\"\"\n Return a compiled regular expression based on the active language.\n \"\"\"\n if instance is None:\n return self\n # As a performance optimization, if the given regex string is a regular\n # string (not a lazily-translated string proxy), compile it once and\n # avoid per-language compilation.\n pattern = getattr(instance, self.attr)\n if isinstance(pattern, str):\n instance.__dict__['regex'] = instance._compile(pattern)\n return instance.__dict__['regex']\n language_code = get_language()\n if language_code not in instance._regex_dict:\n instance._regex_dict[language_code] = instance._compile(str(pattern))\n return instance._regex_dict[language_code]\n\n\nclass CheckURLMixin:\n def describe(self):\n \"\"\"\n Format the URL pattern for display in warning messages.\n \"\"\"\n description = \"'{}'\".format(self)\n if self.name:\n description += \" [name='{}']\".format(self.name)\n return description\n\n def _check_pattern_startswith_slash(self):\n \"\"\"\n Check that the pattern does not begin with a forward slash.\n \"\"\"\n regex_pattern = self.regex.pattern\n if not settings.APPEND_SLASH:\n # Skip check as it can be useful to start a URL pattern with a slash\n # when APPEND_SLASH=False.\n return []\n if regex_pattern.startswith(('/', '^/', '^\\\\/')) and not regex_pattern.endswith('/'):\n warning = Warning(\n \"Your URL pattern {} has a route beginning with a '/'. Remove this \"\n \"slash as it is unnecessary. If this pattern is targeted in an \"\n \"include(), ensure the include() pattern has a trailing '/'.\".format(\n self.describe()\n ),\n id=\"urls.W002\",\n )\n return [warning]\n else:\n return []\n\n\nclass RegexPattern(CheckURLMixin):\n regex = LocaleRegexDescriptor('_regex')\n\n def __init__(self, regex, name=None, is_endpoint=False):\n self._regex = regex\n self._regex_dict = {}\n self._is_endpoint = is_endpoint\n self.name = name\n self.converters = {}\n\n def match(self, path):\n match = self.regex.search(path)\n if match:\n # If there are any named groups, use those as kwargs, ignoring\n # non-named groups. Otherwise, pass all non-named arguments as\n # positional arguments.\n kwargs = match.groupdict()\n args = () if kwargs else match.groups()\n return path[match.end():], args, kwargs\n return None\n\n def check(self):\n warnings = []\n warnings.extend(self._check_pattern_startswith_slash())\n if not self._is_endpoint:\n warnings.extend(self._check_include_trailing_dollar())\n return warnings\n\n def _check_include_trailing_dollar(self):\n regex_pattern = self.regex.pattern\n if regex_pattern.endswith('$') and not regex_pattern.endswith(r'\\$'):\n return [Warning(\n \"Your URL pattern {} uses include with a route ending with a '$'. \"\n \"Remove the dollar from the route to avoid problems including \"\n \"URLs.\".format(self.describe()),\n id='urls.W001',\n )]\n else:\n return []\n\n def _compile(self, regex):\n \"\"\"Compile and return the given regular expression.\"\"\"\n try:\n return re.compile(regex)\n except re.error as e:\n raise ImproperlyConfigured(\n '\"%s\" is not a valid regular expression: %s' % (regex, e)\n )\n\n def __str__(self):\n return str(self._regex)\n\n\n_PATH_PARAMETER_COMPONENT_RE = re.compile(\n r'<(?:(?P[^>:]+):)?(?P\\w+)>'\n)\n\n\ndef _route_to_regex(route, is_endpoint=False):\n \"\"\"\n Convert a path pattern into a regular expression. Return the regular\n expression and a dictionary mapping the capture names to the converters.\n For example, 'foo/' returns '^foo\\\\/(?P[0-9]+)'\n and {'pk': }.\n \"\"\"\n original_route = route\n parts = ['^']\n converters = {}\n while True:\n match = _PATH_PARAMETER_COMPONENT_RE.search(route)\n if not match:\n parts.append(re.escape(route))\n break\n parts.append(re.escape(route[:match.start()]))\n route = route[match.end():]\n parameter = match.group('parameter')\n if not parameter.isidentifier():\n raise ImproperlyConfigured(\n \"URL route '%s' uses parameter name %r which isn't a valid \"\n \"Python identifier.\" % (original_route, parameter)\n )\n raw_converter = match.group('converter')\n if raw_converter is None:\n # If a converter isn't specified, the default is `str`.\n raw_converter = 'str'\n try:\n converter = get_converter(raw_converter)\n except KeyError as e:\n raise ImproperlyConfigured(\n \"URL route '%s' uses invalid converter %s.\" % (original_route, e)\n )\n converters[parameter] = converter\n parts.append('(?P<' + parameter + '>' + converter.regex + ')')\n if is_endpoint:\n parts.append('$')\n return ''.join(parts), converters\n\n\nclass RoutePattern(CheckURLMixin):\n regex = LocaleRegexDescriptor('_route')\n\n def __init__(self, route, name=None, is_endpoint=False):\n self._route = route\n self._regex_dict = {}\n self._is_endpoint = is_endpoint\n self.name = name\n self.converters = _route_to_regex(str(route), is_endpoint)[1]\n\n def match(self, path):\n match = self.regex.search(path)\n if match:\n # RoutePattern doesn't allow non-named groups so args are ignored.\n kwargs = match.groupdict()\n for key, value in kwargs.items():\n converter = self.converters[key]\n try:\n kwargs[key] = converter.to_python(value)\n except ValueError:\n return None\n return path[match.end():], (), kwargs\n return None\n\n def check(self):\n warnings = self._check_pattern_startswith_slash()\n route = self._route\n if '(?P<' in route or route.startswith('^') or route.endswith('$'):", "answers": [" warnings.append(Warning("], "length": 906, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "d768a6cb-2203-4af8-a8e9-fdceadb852ed", "reasoning": "The code is inside RoutePattern.check(). After initializing warnings and checking the route string for regex-like patterns, Django adds a warning if regex syntax is detected. The next line begins the warning creation, typically using warnings.append(Warning(...)). Therefore the immediate next line is the call to warnings.append with a Warning object.", "reasoning_model_answer": "warnings.append(Warning(", "assistant_with_reasoning": "\nThe code is inside RoutePattern.check(). After initializing warnings and checking the route string for regex-like patterns, Django adds a warning if regex syntax is detected. The next line begins the warning creation, typically using warnings.append(Warning(...)). Therefore the immediate next line is the call to warnings.append with a Warning object.\n\nwarnings.append(Warning(", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 6.059, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 9638, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "warnings.append(Warning(", "score": 0.8, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/* Copyright 2010, 2011 Semantic Web Research Center, KAIST\n\nThis file is part of JHanNanum.\n\nJHanNanum is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nJHanNanum is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with JHanNanum. If not, see */\n\npackage kr.ac.kaist.swrc.jhannanum.plugin.MajorPlugin.MorphAnalyzer.ChartMorphAnalyzer;\n\nimport java.io.BufferedReader;\nimport java.io.FileInputStream;\nimport java.io.FileNotFoundException;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.io.PrintWriter;\nimport java.util.LinkedList;\nimport java.util.StringTokenizer;\n\nimport kr.ac.kaist.swrc.jhannanum.share.Code;\nimport kr.ac.kaist.swrc.jhannanum.share.TagSet;\n\n/**\n * TRIE data structure for morpheme dictionaries.\n * @author Sangwon Park (hudoni@world.kaist.ac.kr), CILab, SWRC, KAIST\n */\npublic class Trie {\n\t/**\n\t * This class is for managing free nodes in the trie structure.\n\t * @author Sangwon Park (hudoni@world.kaist.ac.kr), CILab, SWRC, KAIST\n\t */\n\tpublic class FREE {\t\n\t\t/** the size of consecutive free nodes */\n\t\tpublic int size;\n\t\t\n\t\t/** the next index of free node */\n\t\tpublic int next_idx;\n\t}\n\t\n\t/**\n\t * This class is for the information of morpheme\n\t * @author Sangwon Park (hudoni@world.kaist.ac.kr), CILab, SWRC, KAIST\n\t */\n\tpublic class INFO {\n\t\t/** morpheme tag ID */\n\t\tpublic int tag;\n\t\t\n\t\t/** phoneme */\n\t\tpublic int phoneme;\n\t}\n\t\n\t/**\n\t * This class is for nodes of trie structure.\n\t * @author Sangwon Park (hudoni@world.kaist.ac.kr), CILab, SWRC, KAIST\n\t */\n\tpublic class TNODE {\n\t\t/** key - vowel, consonant, etc. */\n\t\tpublic char\tkey;\n\t\t\n\t\t/** the size of children */\n\t\tpublic short child_size;\n\t\t\n\t\t/** the index for the childern */\n\t\tpublic int child_idx;\n\t\t\n\t\t/** the list of morpheme information */\n\t\tpublic LinkedList info_list = null;\n\t\t\n\t\t/** for managing free nodes */\n\t\tpublic FREE\tfree = new FREE();\n\t}\n\n\t/** the default buffer size for the system dictionary */\n\tfinal public static int DEFAULT_TRIE_BUF_SIZE_SYS = 1060000;\n\n\t/** the default buffer size for the user dictionary */\n\tfinal public static int DEFAULT_TRIE_BUF_SIZE_USER = 106000;\n\t\n\t/** the index of the free node */\n\tfinal public static int FREE_NODE = 0;\n\t\n\t/** the index of the start node */\n\tfinal public static int START_NODE = 1;\n\n\t/** the length of search result */\n\tpublic int search_end;\n\n\t/** the list for storing the path searched */\n\tpublic int[] search_idx = new int[256];\n\t\n\t/** the list of keys of the path searched */\n\tpublic char[] search_key = new char[256];\n\n\t/** the array for trie nodes */\n\tpublic TNODE[] trie_buf = null;\n\n\t/** the head of free node list */\n\tpublic FREE free_head = null;\n\n\t/** the head of node list */\n\tpublic TNODE node_head = null;\n\t\n\t/**\n\t * Constructor.\n\t * @param buf_size - the maximum number of trie nodes\n\t */\n\tpublic Trie(int buf_size) {\n\t\tsearch_idx = new int[256];\n\t\tsearch_key = new char[256];\n\t\tsearch_end = 0;\n\n\t\ttrie_buf = new TNODE[buf_size];\n\t\tfor (int i = 0; i < buf_size; i++) {\n\t\t\ttrie_buf[i] = new TNODE();\n\t\t}\n\n\t\tfree_head = trie_buf[FREE_NODE].free;\n\t\tnode_head = trie_buf[FREE_NODE];\n\t\t\n\t\tnode_head.key = 0;\n\t\tnode_head.child_size = 0;\n\t\tnode_head.info_list = new LinkedList();\n\t\tnode_head.child_idx = 0;\n\n\t\tfree_head.size = 0;\n\t\tfree_head.next_idx = 1;\n\n\t\t// the node number 0 is not used\n\t\ttrie_buf[1].free.size = buf_size - 1;\n\t\ttrie_buf[1].free.next_idx = FREE_NODE;\n\t}\n\n\t/**\n\t * Fetches the specified word.\n\t * @param word - the word to fetch\n\t * @return the trie node for the specified word\n\t */\n\tpublic TNODE fetch(char[] word) {\n\t\tint idx;\n\t\tint x;\n\n\t\tx = search(word);\n\t\tif (x == 0) {\n\t\t\treturn null;\n\t\t} else {\n\t\t\tidx = this.search_idx[x - 1];\n\t\t\treturn trie_buf[idx];\n\t\t}\n\t}\n\n\t/**\n\t * Gets the trie node on the specified index\n\t * @param idx - index on the trie structure\n\t * @return the trie node on the index\n\t */\n\tpublic TNODE get_node(int idx) {\n\t\treturn trie_buf[idx];\n\t}\n\n\t/**\n\t * Allocates the trie nodes available as the specified size\n\t * @param size - the number of nodes to allocate\n\t * @return the start index of the allocated nodes, 0: failed to allocate\n\t */\n\tpublic int node_alloc(int size) {\n\t\tint idx;\n\t\tint pidx;\n\n\t\tif (size <= 0) {\n\t\t\tSystem.err.println(\"node alloc: wrong size\");\n\t\t\treturn 0;\n\t\t}\n\n\t\tpidx = FREE_NODE;\n\n\t\tfor (idx = free_head.next_idx; idx != FREE_NODE; idx = trie_buf[idx].free.next_idx) {\n\t\t\tif (trie_buf[idx].free.size >= size) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tpidx = idx;\n\t\t}\n\n\t\tif (idx == 0) {\n\t\t\tSystem.err.println(\"node alloc: no space\");\n\t\t\treturn 0;\n\t\t}\n\n\t\tif (pidx == FREE_NODE) {\n\t\t\tif (size == trie_buf[idx].free.size) {\n\t\t\t\tfree_head.next_idx = trie_buf[idx].free.next_idx;\n\t\t\t} else {\n\t\t\t\ttrie_buf[idx + size].free.size = trie_buf[idx].free.size - size;\n\t\t\t\ttrie_buf[idx + size].free.next_idx = trie_buf[idx].free.next_idx;\n\t\t\t\tfree_head.next_idx = idx + size;\n\t\t\t}\n\t\t} else {\n\t\t\tif(size == trie_buf[idx].free.size) {\n\t\t\t\ttrie_buf[pidx].free.next_idx = trie_buf[idx].free.next_idx;\n\t\t\t} else {\n\t\t\t\ttrie_buf[idx + size].free.size = trie_buf[idx].free.size - size;\n\t\t\t\ttrie_buf[idx + size].free.next_idx = trie_buf[idx].free.next_idx;\n\t\t\t\ttrie_buf[pidx].free.next_idx = idx + size;\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn idx;\n\t}\n\n\t/**\n\t * It frees the nodes from the specified index.\n\t * @param fidx - the start index of node group to free\n\t * @param size - the number of nodes to free\n\t */\n\tpublic void node_free(int fidx, int size)\n\t{\n\t\tint idx, pidx = 0;\n\t\tFREE start;\n\n\t\tif (size <= 0 || fidx <= FREE_NODE) {\n\t\t\tSystem.err.println(\"node_free: wrong parameter\");\n\t\t\tSystem.exit(0);\n\t\t}\n\n\t\tidx = free_head.next_idx;\n\t\tif (idx == FREE_NODE) {\n\t\t\t// if there was no free nodes, simply updates the header pointer with the new free node\n\t\t\tfree_head.next_idx = fidx;\t\t\t\t\t// the start index of free nodes\t\t\n\t\t\ttrie_buf[fidx].free.size = size;\t\t\t// the size of free nodes\n\t\t\ttrie_buf[fidx].free.next_idx = FREE_NODE;\t// the end of the free node list\n\t\t\treturn;\n\t\t}\n\n\t\tif (fidx < idx) {\n\t\t\t// the new free nodes are in front compared to the existing free node list\n\t\t\tfree_head.next_idx\t= fidx;\n\t\t\tif (idx == fidx + size) {\n\t\t\t\t// if they are consecutive, they are merged.\n\t\t\t\ttrie_buf[fidx].free.size = size + trie_buf[idx].free.size;\n\t\t\t\ttrie_buf[fidx].free.next_idx = trie_buf[idx].free.next_idx;\n\t\t\t} else {\n\t\t\t\t// if they are not consecutive, they are separated", "answers": ["\t\t\t\ttrie_buf[fidx].free.size = size;"], "length": 985, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "311acfb7-7ad2-4406-9b96-eded0463c1bd", "reasoning": "In node_free, when the new free block is before the existing list and not adjacent, we must initialize its FREE fields. After the comment about being separated, the code should set the size of the new free block before linking it to the next free node. Hence the next line is the assignment of size.", "reasoning_model_answer": "trie_buf[fidx].free.size = size;", "assistant_with_reasoning": "\nIn node_free, when the new free block is before the existing list and not adjacent, we must initialize its FREE fields. After the comment about being separated, the code should set the size of the new free block before linking it to the next free node. Hence the next line is the assignment of size.\n\ntrie_buf[fidx].free.size = size;", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.454, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 6839, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "trie_buf[fidx].free.size = size;", "score": 0.94, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "# -*- coding: utf-8 -*-\n# Copyright 2020 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\nfrom collections import OrderedDict\nimport os\nimport re\nfrom typing import Dict, Optional, Sequence, Tuple, Type, Union\n\nfrom google.api_core import client_options as client_options_lib\nfrom google.api_core import gapic_v1\nfrom google.api_core import retry as retries\nfrom google.auth import credentials as ga_credentials # type: ignore\nfrom google.auth.transport import mtls # type: ignore\nfrom google.auth.transport.grpc import SslCredentials # type: ignore\nfrom google.auth.exceptions import MutualTLSChannelError # type: ignore\nfrom google.oauth2 import service_account # type: ignore\n\ntry:\n OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault]\nexcept AttributeError: # pragma: NO COVER\n OptionalRetry = Union[retries.Retry, object] # type: ignore\n\nfrom google.ads.googleads.v9.resources.types import asset_group\nfrom google.ads.googleads.v9.services.types import asset_group_service\nfrom google.rpc import status_pb2 # type: ignore\nfrom .transports.base import AssetGroupServiceTransport, DEFAULT_CLIENT_INFO\nfrom .transports.grpc import AssetGroupServiceGrpcTransport\n\n\nclass AssetGroupServiceClientMeta(type):\n \"\"\"Metaclass for the AssetGroupService client.\n\n This provides class-level methods for building and retrieving\n support objects (e.g. transport) without polluting the client instance\n objects.\n \"\"\"\n\n _transport_registry = (\n OrderedDict()\n ) # type: Dict[str, Type[AssetGroupServiceTransport]]\n _transport_registry[\"grpc\"] = AssetGroupServiceGrpcTransport\n\n def get_transport_class(\n cls, label: str = None,\n ) -> Type[AssetGroupServiceTransport]:\n \"\"\"Return an appropriate transport class.\n\n Args:\n label: The name of the desired transport. If none is\n provided, then the first transport in the registry is used.\n\n Returns:\n The transport class to use.\n \"\"\"\n # If a specific transport is requested, return that one.\n if label:\n return cls._transport_registry[label]\n\n # No transport is requested; return the default (that is, the first one\n # in the dictionary).\n return next(iter(cls._transport_registry.values()))\n\n\nclass AssetGroupServiceClient(metaclass=AssetGroupServiceClientMeta):\n \"\"\"Service to manage asset group\"\"\"\n\n @staticmethod\n def _get_default_mtls_endpoint(api_endpoint):\n \"\"\"Convert api endpoint to mTLS endpoint.\n Convert \"*.sandbox.googleapis.com\" and \"*.googleapis.com\" to\n \"*.mtls.sandbox.googleapis.com\" and \"*.mtls.googleapis.com\" respectively.\n Args:\n api_endpoint (Optional[str]): the api endpoint to convert.\n Returns:\n str: converted mTLS api endpoint.\n \"\"\"\n if not api_endpoint:\n return api_endpoint\n\n mtls_endpoint_re = re.compile(\n r\"(?P[^.]+)(?P\\.mtls)?(?P\\.sandbox)?(?P\\.googleapis\\.com)?\"\n )\n\n m = mtls_endpoint_re.match(api_endpoint)\n name, mtls, sandbox, googledomain = m.groups()\n if mtls or not googledomain:\n return api_endpoint\n\n if sandbox:\n return api_endpoint.replace(\n \"sandbox.googleapis.com\", \"mtls.sandbox.googleapis.com\"\n )\n\n return api_endpoint.replace(\".googleapis.com\", \".mtls.googleapis.com\")\n\n DEFAULT_ENDPOINT = \"googleads.googleapis.com\"\n DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore\n DEFAULT_ENDPOINT\n )\n\n @classmethod\n def from_service_account_info(cls, info: dict, *args, **kwargs):\n \"\"\"Creates an instance of this client using the provided credentials info.\n\n Args:\n info (dict): The service account private key info.\n args: Additional arguments to pass to the constructor.\n kwargs: Additional arguments to pass to the constructor.\n\n Returns:\n AssetGroupServiceClient: The constructed client.\n \"\"\"\n credentials = service_account.Credentials.from_service_account_info(\n info\n )\n kwargs[\"credentials\"] = credentials\n return cls(*args, **kwargs)\n\n @classmethod\n def from_service_account_file(cls, filename: str, *args, **kwargs):\n \"\"\"Creates an instance of this client using the provided credentials\n file.\n\n Args:\n filename (str): The path to the service account private key json\n file.\n args: Additional arguments to pass to the constructor.\n kwargs: Additional arguments to pass to the constructor.\n\n Returns:\n AssetGroupServiceClient: The constructed client.\n \"\"\"\n credentials = service_account.Credentials.from_service_account_file(\n filename\n )\n kwargs[\"credentials\"] = credentials\n return cls(*args, **kwargs)\n\n from_service_account_json = from_service_account_file\n\n @property\n def transport(self) -> AssetGroupServiceTransport:\n \"\"\"Return the transport used by the client instance.\n\n Returns:\n AssetGroupServiceTransport: The transport used by the client instance.\n \"\"\"\n return self._transport\n\n def __enter__(self):\n return self\n\n def __exit__(self, type, value, traceback):\n \"\"\"Releases underlying transport's resources.\n\n .. warning::\n ONLY use as a context manager if the transport is NOT shared\n with other clients! Exiting the with block will CLOSE the transport\n and may cause errors in other clients!\n \"\"\"\n self.transport.close()\n\n @staticmethod\n def asset_group_path(customer_id: str, asset_group_id: str,) -> str:\n \"\"\"Return a fully-qualified asset_group string.\"\"\"\n return \"customers/{customer_id}/assetGroups/{asset_group_id}\".format(\n customer_id=customer_id, asset_group_id=asset_group_id,\n )\n\n @staticmethod\n def parse_asset_group_path(path: str) -> Dict[str, str]:\n \"\"\"Parse a asset_group path into its component segments.\"\"\"\n m = re.match(\n r\"^customers/(?P.+?)/assetGroups/(?P.+?)$\",\n path,\n )\n return m.groupdict() if m else {}\n\n @staticmethod\n def campaign_path(customer_id: str, campaign_id: str,) -> str:\n \"\"\"Return a fully-qualified campaign string.\"\"\"\n return \"customers/{customer_id}/campaigns/{campaign_id}\".format(\n customer_id=customer_id, campaign_id=campaign_id,\n )\n\n @staticmethod\n def parse_campaign_path(path: str) -> Dict[str, str]:\n \"\"\"Parse a campaign path into its component segments.\"\"\"\n m = re.match(\n r\"^customers/(?P.+?)/campaigns/(?P.+?)$\",\n path,\n )\n return m.groupdict() if m else {}\n\n @staticmethod\n def common_billing_account_path(billing_account: str,) -> str:\n \"\"\"Return a fully-qualified billing_account string.\"\"\"\n return \"billingAccounts/{billing_account}\".format(\n billing_account=billing_account,\n )\n\n @staticmethod\n def parse_common_billing_account_path(path: str) -> Dict[str, str]:\n \"\"\"Parse a billing_account path into its component segments.\"\"\"\n m = re.match(r\"^billingAccounts/(?P.+?)$\", path)\n return m.groupdict() if m else {}\n\n @staticmethod\n def common_folder_path(folder: str,) -> str:\n \"\"\"Return a fully-qualified folder string.\"\"\"\n return \"folders/{folder}\".format(folder=folder,)\n\n @staticmethod\n def parse_common_folder_path(path: str) -> Dict[str, str]:\n \"\"\"Parse a folder path into its component segments.\"\"\"\n m = re.match(r\"^folders/(?P.+?)$\", path)\n return m.groupdict() if m else {}\n\n @staticmethod\n def common_organization_path(organization: str,) -> str:\n \"\"\"Return a fully-qualified organization string.\"\"\"\n return \"organizations/{organization}\".format(organization=organization,)\n\n @staticmethod\n def parse_common_organization_path(path: str) -> Dict[str, str]:\n \"\"\"Parse a organization path into its component segments.\"\"\"\n m = re.match(r\"^organizations/(?P.+?)$\", path)\n return m.groupdict() if m else {}\n\n @staticmethod\n def common_project_path(project: str,) -> str:\n \"\"\"Return a fully-qualified project string.\"\"\"\n return \"projects/{project}\".format(project=project,)\n\n @staticmethod\n def parse_common_project_path(path: str) -> Dict[str, str]:\n \"\"\"Parse a project path into its component segments.\"\"\"\n m = re.match(r\"^projects/(?P.+?)$\", path)\n return m.groupdict() if m else {}\n\n @staticmethod\n def common_location_path(project: str, location: str,) -> str:\n \"\"\"Return a fully-qualified location string.\"\"\"\n return \"projects/{project}/locations/{location}\".format(\n project=project, location=location,\n )\n\n @staticmethod\n def parse_common_location_path(path: str) -> Dict[str, str]:\n \"\"\"Parse a location path into its component segments.\"\"\"\n m = re.match(\n r\"^projects/(?P.+?)/locations/(?P.+?)$\", path\n )\n return m.groupdict() if m else {}\n\n def __init__(\n self,\n *,", "answers": [" credentials: Optional[ga_credentials.Credentials] = None,"], "length": 911, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "3138cda8-3b70-410a-a35f-0041e8c71568", "reasoning": "The __init__ method is being defined for the client class. After the opening parenthesis and the '*' indicating keyword-only arguments, the first typical argument is the credentials parameter. In Google client libraries, this is typed as Optional[ga_credentials.Credentials] with a default of None. Therefore the next line should declare this parameter.", "reasoning_model_answer": "credentials: Optional[ga_credentials.Credentials] = None,", "assistant_with_reasoning": "\nThe __init__ method is being defined for the client class. After the opening parenthesis and the '*' indicating keyword-only arguments, the first typical argument is the credentials parameter. In Google client libraries, this is typed as Optional[ga_credentials.Credentials] with a default of None. Therefore the next line should declare this parameter.\n\ncredentials: Optional[ga_credentials.Credentials] = None,", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.245, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 10089, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "credentials: Optional[ga_credentials.Credentials] = None,", "score": 0.93, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n#pragma warning disable 0420\n\n// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+\n//\n//\n//\n// --------------------------------------------------------------------------------------\n//\n// A class that provides a simple, lightweight implementation of lazy initialization, \n// obviating the need for a developer to implement a custom, thread-safe lazy initialization \n// solution.\n//\n// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\n\nusing System.Runtime;\nusing System.Runtime.InteropServices;\nusing System.Security;\nusing System.Security.Permissions;\nusing System.Diagnostics;\nusing System.Runtime.Serialization;\nusing System.Threading;\nusing System.Diagnostics.Contracts;\nusing System.Runtime.ExceptionServices;\n\nnamespace System\n{\n // Lazy is generic, but not all of its state needs to be generic. Avoid creating duplicate\n // objects per instantiation by putting them here.\n internal static class LazyHelpers\n {\n // Dummy object used as the value of m_threadSafeObj if in PublicationOnly mode.\n internal static readonly object PUBLICATION_ONLY_SENTINEL = new object();\n }\n\n ///

    \n /// Provides support for lazy initialization.\n /// \n /// Specifies the type of element being lazily initialized.\n /// \n /// \n /// By default, all public and protected members of are thread-safe and may be used\n /// concurrently from multiple threads. These thread-safety guarantees may be removed optionally and per instance\n /// using parameters to the type's constructors.\n /// \n /// \n#if FEATURE_SERIALIZATION\n [Serializable]\n#endif\n [ComVisible(false)]\n#if !FEATURE_CORECLR\n [HostProtection(Synchronization = true, ExternalThreading = true)]\n#endif\n [DebuggerTypeProxy(typeof(System_LazyDebugView<>))]\n [DebuggerDisplay(\"ThreadSafetyMode={Mode}, IsValueCreated={IsValueCreated}, IsValueFaulted={IsValueFaulted}, Value={ValueForDebugDisplay}\")]\n public class Lazy\n {\n\n#region Inner classes\n /// \n /// wrapper class to box the initialized value, this is mainly created to avoid boxing/unboxing the value each time the value is called in case T is \n /// a value type\n /// \n [Serializable]\n class Boxed\n {\n internal Boxed(T value)\n {\n m_value = value;\n }\n internal T m_value;\n }\n\n\n /// \n /// Wrapper class to wrap the excpetion thrown by the value factory\n /// \n class LazyInternalExceptionHolder\n {\n internal ExceptionDispatchInfo m_edi;\n internal LazyInternalExceptionHolder(Exception ex)\n {\n m_edi = ExceptionDispatchInfo.Capture(ex);\n }\n }\n#endregion\n\n // A dummy delegate used as a :\n // 1- Flag to avoid recursive call to Value in None and ExecutionAndPublication modes in m_valueFactory\n // 2- Flag to m_threadSafeObj if ExecutionAndPublication mode and the value is known to be initialized\n static readonly Func ALREADY_INVOKED_SENTINEL = delegate \n {\n Contract.Assert(false, \"ALREADY_INVOKED_SENTINEL should never be invoked.\");\n return default(T);\n };\n\n //null --> value is not created\n //m_value is Boxed --> the value is created, and m_value holds the value\n //m_value is LazyExceptionHolder --> it holds an exception\n private object m_boxed;\n\n // The factory delegate that returns the value.\n // In None and ExecutionAndPublication modes, this will be set to ALREADY_INVOKED_SENTINEL as a flag to avoid recursive calls\n [NonSerialized]\n private Func m_valueFactory;\n\n // null if it is not thread safe mode\n // LazyHelpers.PUBLICATION_ONLY_SENTINEL if PublicationOnly mode\n // object if ExecutionAndPublication mode (may be ALREADY_INVOKED_SENTINEL if the value is already initialized)\n [NonSerialized]\n private object m_threadSafeObj;\n\n\n /// \n /// Initializes a new instance of the class that \n /// uses 's default constructor for lazy initialization.\n /// \n /// \n /// An instance created with this constructor may be used concurrently from multiple threads.\n /// \n public Lazy()\n : this(LazyThreadSafetyMode.ExecutionAndPublication)\n {\n }\n\n /// \n /// Initializes a new instance of the class that\n /// uses a pre-initialized specified value.\n /// \n /// \n /// An instance created with this constructor should be usable by multiple threads\n // concurrently.\n /// \n public Lazy(T value)\n {\n m_boxed = new Boxed(value);\n }\n\n /// \n /// Initializes a new instance of the class that uses a\n /// specified initialization function.\n /// \n /// \n /// The invoked to produce the lazily-initialized value when it is\n /// needed.\n /// \n /// is a null\n /// reference (Nothing in Visual Basic).\n /// \n /// An instance created with this constructor may be used concurrently from multiple threads.\n /// \n public Lazy(Func valueFactory)\n : this(valueFactory, LazyThreadSafetyMode.ExecutionAndPublication)\n {\n }\n\n /// \n /// Initializes a new instance of the \n /// class that uses 's default constructor and a specified thread-safety mode.\n /// \n /// true if this instance should be usable by multiple threads concurrently; false if the instance will only be used by one thread at a time.\n /// \n public Lazy(bool isThreadSafe) : \n this(isThreadSafe? LazyThreadSafetyMode.ExecutionAndPublication : LazyThreadSafetyMode.None)\n {\n }\n\n /// \n /// Initializes a new instance of the \n /// class that uses 's default constructor and a specified thread-safety mode.\n /// \n /// The lazy thread-safety mode mode\n /// mode contains an invalid valuee\n public Lazy(LazyThreadSafetyMode mode)\n {\n m_threadSafeObj = GetObjectFromMode(mode);\n }\n\n\n /// \n /// Initializes a new instance of the class\n /// that uses a specified initialization function and a specified thread-safety mode.\n /// \n /// \n /// The invoked to produce the lazily-initialized value when it is needed.\n /// \n /// true if this instance should be usable by multiple threads concurrently; false if the instance will only be used by one thread at a time.\n /// \n /// is\n /// a null reference (Nothing in Visual Basic).\n public Lazy(Func valueFactory, bool isThreadSafe)\n : this(valueFactory, isThreadSafe ? LazyThreadSafetyMode.ExecutionAndPublication : LazyThreadSafetyMode.None)\n {\n }\n\n /// \n /// Initializes a new instance of the class\n /// that uses a specified initialization function and a specified thread-safety mode.\n /// \n /// \n /// The invoked to produce the lazily-initialized value when it is needed.\n /// \n /// The lazy thread-safety mode.\n /// is\n /// a null reference (Nothing in Visual Basic).\n /// mode contains an invalid value.\n public Lazy(Func valueFactory, LazyThreadSafetyMode mode)\n {\n if (valueFactory == null)\n throw new ArgumentNullException(\"valueFactory\");\n\n m_threadSafeObj = GetObjectFromMode(mode);", "answers": [" m_valueFactory = valueFactory;"], "length": 964, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "0bed7d7a-1f66-43f2-a090-16116449c378", "reasoning": "The constructor takes a valueFactory and a thread‑safety mode. It already validated the factory and stored the thread‑safety object. The next logical step is to store the provided factory delegate in the instance field m_valueFactory so it can be invoked later. Therefore the next line should assign valueFactory to m_valueFactory.", "reasoning_model_answer": "m_valueFactory = valueFactory;", "assistant_with_reasoning": "\nThe constructor takes a valueFactory and a thread‑safety mode. It already validated the factory and stored the thread‑safety object. The next logical step is to store the provided factory delegate in the instance field m_valueFactory so it can be invoked later. Therefore the next line should assign valueFactory to m_valueFactory.\n\nm_valueFactory = valueFactory;", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 2.941, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 9447, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "m_valueFactory = valueFactory;", "score": 0.83, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/*\n * Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights\n * Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\").\n * You may not use this file except in compliance with the License.\n * A copy of the License is located at\n *\n * http://aws.amazon.com/apache2.0\n *\n * or in the \"license\" file accompanying this file. This file is distributed\n * on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n * express or implied. See the License for the specific language governing\n * permissions and limitations under the License.\n */\n\npackage com.amazonaws.services.glacier.model;\n\nimport java.io.Serializable;\n\n/**\n *

    \n * Describes the options for a range inventory retrieval job.\n *

    \n */\npublic class InventoryRetrievalJobDescription implements Serializable,\n Cloneable {\n\n /**\n *

    \n * The output format for the vault inventory list, which is set by the\n * InitiateJob request when initiating a job to retrieve a vault\n * inventory. Valid values are \"CSV\" and \"JSON\".\n *

    \n */\n private String format;\n /**\n *

    \n * The start of the date range in UTC for vault inventory retrieval that\n * includes archives created on or after this date. A string representation\n * of ISO 8601 date format, for example, 2013-03-20T17:03:43Z.\n *

    \n */\n private String startDate;\n /**\n *

    \n * The end of the date range in UTC for vault inventory retrieval that\n * includes archives created before this date. A string representation of\n * ISO 8601 date format, for example, 2013-03-20T17:03:43Z.\n *

    \n */\n private String endDate;\n /**\n *

    \n * Specifies the maximum number of inventory items returned per vault\n * inventory retrieval request. This limit is set when initiating the job\n * with the a InitiateJob request.\n *

    \n */\n private String limit;\n /**\n *

    \n * An opaque string that represents where to continue pagination of the\n * vault inventory retrieval results. You use the marker in a new\n * InitiateJob request to obtain additional inventory items. If there\n * are no more inventory items, this value is null. For more\n * information, see Range Inventory Retrieval.\n *

    \n */\n private String marker;\n\n /**\n *

    \n * The output format for the vault inventory list, which is set by the\n * InitiateJob request when initiating a job to retrieve a vault\n * inventory. Valid values are \"CSV\" and \"JSON\".\n *

    \n * \n * @param format\n * The output format for the vault inventory list, which is set by\n * the InitiateJob request when initiating a job to retrieve a\n * vault inventory. Valid values are \"CSV\" and \"JSON\".\n */\n\n public void setFormat(String format) {\n this.format = format;\n }\n\n /**\n *

    \n * The output format for the vault inventory list, which is set by the\n * InitiateJob request when initiating a job to retrieve a vault\n * inventory. Valid values are \"CSV\" and \"JSON\".\n *

    \n * \n * @return The output format for the vault inventory list, which is set by\n * the InitiateJob request when initiating a job to retrieve\n * a vault inventory. Valid values are \"CSV\" and \"JSON\".\n */\n\n public String getFormat() {\n return this.format;\n }\n\n /**\n *

    \n * The output format for the vault inventory list, which is set by the\n * InitiateJob request when initiating a job to retrieve a vault\n * inventory. Valid values are \"CSV\" and \"JSON\".\n *

    \n * \n * @param format\n * The output format for the vault inventory list, which is set by\n * the InitiateJob request when initiating a job to retrieve a\n * vault inventory. Valid values are \"CSV\" and \"JSON\".\n * @return Returns a reference to this object so that method calls can be\n * chained together.\n */\n\n public InventoryRetrievalJobDescription withFormat(String format) {\n setFormat(format);\n return this;\n }\n\n /**\n *

    \n * The start of the date range in UTC for vault inventory retrieval that\n * includes archives created on or after this date. A string representation\n * of ISO 8601 date format, for example, 2013-03-20T17:03:43Z.\n *

    \n * \n * @param startDate\n * The start of the date range in UTC for vault inventory retrieval\n * that includes archives created on or after this date. A string\n * representation of ISO 8601 date format, for example,\n * 2013-03-20T17:03:43Z.\n */\n\n public void setStartDate(String startDate) {\n this.startDate = startDate;\n }\n\n /**\n *

    \n * The start of the date range in UTC for vault inventory retrieval that\n * includes archives created on or after this date. A string representation\n * of ISO 8601 date format, for example, 2013-03-20T17:03:43Z.\n *

    \n * \n * @return The start of the date range in UTC for vault inventory retrieval\n * that includes archives created on or after this date. A string\n * representation of ISO 8601 date format, for example,\n * 2013-03-20T17:03:43Z.\n */\n\n public String getStartDate() {\n return this.startDate;\n }\n\n /**\n *

    \n * The start of the date range in UTC for vault inventory retrieval that\n * includes archives created on or after this date. A string representation\n * of ISO 8601 date format, for example, 2013-03-20T17:03:43Z.\n *

    \n * \n * @param startDate\n * The start of the date range in UTC for vault inventory retrieval\n * that includes archives created on or after this date. A string\n * representation of ISO 8601 date format, for example,\n * 2013-03-20T17:03:43Z.\n * @return Returns a reference to this object so that method calls can be\n * chained together.\n */\n\n public InventoryRetrievalJobDescription withStartDate(String startDate) {\n setStartDate(startDate);\n return this;\n }\n\n /**\n *

    \n * The end of the date range in UTC for vault inventory retrieval that\n * includes archives created before this date. A string representation of\n * ISO 8601 date format, for example, 2013-03-20T17:03:43Z.\n *

    \n * \n * @param endDate\n * The end of the date range in UTC for vault inventory retrieval\n * that includes archives created before this date. A string\n * representation of ISO 8601 date format, for example,\n * 2013-03-20T17:03:43Z.\n */\n", "answers": [" public void setEndDate(String endDate) {"], "length": 990, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "10d679f2-2308-4501-8814-e5affbaa2272", "reasoning": "The code just finished the Javadoc comment for the setEndDate method. Following the pattern used for setFormat and setStartDate, the next line should be the method signature that begins the setter implementation.", "reasoning_model_answer": "public void setEndDate(String endDate) {", "assistant_with_reasoning": "\nThe code just finished the Javadoc comment for the setEndDate method. Following the pattern used for setFormat and setStartDate, the next line should be the method signature that begins the setter implementation.\n\npublic void setEndDate(String endDate) {", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.329, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 7091, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "public void setEndDate(String endDate) {", "score": 0.95, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "using System;\nusing System.Collections.Generic;\nusing System.Collections.Immutable;\nusing System.Diagnostics;\nusing System.Linq;\nusing System.Security.Claims;\nusing System.Threading.Tasks;\nusing AspNet.Security.OpenIdConnect.Extensions;\nusing AspNet.Security.OpenIdConnect.Primitives;\nusing Microsoft.AspNetCore.Authentication;\nusing Microsoft.AspNetCore.Authorization;\nusing Microsoft.AspNetCore.Http;\nusing Microsoft.AspNetCore.Mvc;\nusing Microsoft.Extensions.DependencyInjection;\nusing Microsoft.Extensions.Localization;\nusing OpenIddict.Abstractions;\nusing OpenIddict.Mvc.Internal;\nusing OpenIddict.Server;\nusing OrchardCore.Environment.Shell;\nusing OrchardCore.Modules;\nusing OrchardCore.OpenId.Abstractions.Managers;\nusing OrchardCore.OpenId.Filters;\nusing OrchardCore.OpenId.ViewModels;\nusing OrchardCore.Routing;\nusing OrchardCore.Security.Services;\nusing OrchardCore.Users.Services;\n\nnamespace OrchardCore.OpenId.Controllers\n{\n [Authorize, Feature(OpenIdConstants.Features.Server), OpenIdController]\n public class AccessController : Controller\n {\n private readonly IOpenIdApplicationManager _applicationManager;\n private readonly IOpenIdAuthorizationManager _authorizationManager;\n private readonly IOpenIdScopeManager _scopeManager;\n private readonly ShellSettings _shellSettings;\n private readonly IStringLocalizer S;\n\n public AccessController(\n IOpenIdApplicationManager applicationManager,\n IOpenIdAuthorizationManager authorizationManager,\n IStringLocalizer localizer,\n IOpenIdScopeManager scopeManager,\n ShellSettings shellSettings)\n {\n S = localizer;\n _applicationManager = applicationManager;\n _authorizationManager = authorizationManager;\n _scopeManager = scopeManager;\n _shellSettings = shellSettings;\n }\n\n [AllowAnonymous, HttpGet, HttpPost, IgnoreAntiforgeryToken]\n public async Task Authorize([ModelBinder(typeof(OpenIddictMvcBinder))] OpenIdConnectRequest request)\n {\n // Retrieve the claims stored in the authentication cookie.\n // If they can't be extracted, redirect the user to the login page.\n var result = await HttpContext.AuthenticateAsync();\n if (result == null || !result.Succeeded || request.HasPrompt(OpenIddictConstants.Prompts.Login))\n {\n return RedirectToLoginPage(request);\n }\n\n // If a max_age parameter was provided, ensure that the cookie is not too old.\n // If it's too old, automatically redirect the user agent to the login page.\n if (request.MaxAge != null && result.Properties.IssuedUtc != null &&\n DateTimeOffset.UtcNow - result.Properties.IssuedUtc > TimeSpan.FromSeconds(request.MaxAge.Value))\n {\n return RedirectToLoginPage(request);\n }\n\n var application = await _applicationManager.FindByClientIdAsync(request.ClientId);\n if (application == null)\n {\n return View(\"Error\", new ErrorViewModel\n {\n Error = OpenIddictConstants.Errors.InvalidClient,\n ErrorDescription = S[\"The specified 'client_id' parameter is invalid.\"]\n });\n }\n\n var authorizations = await _authorizationManager.FindAsync(\n subject: result.Principal.GetUserIdentifier(),\n client: await _applicationManager.GetIdAsync(application),\n status: OpenIddictConstants.Statuses.Valid,\n type: OpenIddictConstants.AuthorizationTypes.Permanent,\n scopes: ImmutableArray.CreateRange(request.GetScopes()));\n\n switch (await _applicationManager.GetConsentTypeAsync(application))\n {\n case OpenIddictConstants.ConsentTypes.External when authorizations.IsEmpty:\n return RedirectToClient(new OpenIdConnectResponse\n {\n Error = OpenIddictConstants.Errors.ConsentRequired,\n ErrorDescription = S[\"The logged in user is not allowed to access this client application.\"]\n });\n\n case OpenIddictConstants.ConsentTypes.Implicit:\n case OpenIddictConstants.ConsentTypes.External when authorizations.Any():\n case OpenIddictConstants.ConsentTypes.Explicit when authorizations.Any() &&\n !request.HasPrompt(OpenIddictConstants.Prompts.Consent):\n var authorization = authorizations.LastOrDefault();\n var ticket = await CreateUserTicketAsync(result.Principal, application, authorization, request);\n\n return SignIn(ticket.Principal, ticket.Properties, ticket.AuthenticationScheme);\n\n case OpenIddictConstants.ConsentTypes.Explicit when request.HasPrompt(OpenIddictConstants.Prompts.None):\n return RedirectToClient(new OpenIdConnectResponse\n {\n Error = OpenIddictConstants.Errors.ConsentRequired,\n ErrorDescription = S[\"Interactive user consent is required.\"]\n });\n\n default:\n return View(new AuthorizeViewModel\n {\n ApplicationName = await _applicationManager.GetDisplayNameAsync(application),\n RequestId = request.RequestId,\n Scope = request.Scope\n });\n }\n }\n\n [ActionName(nameof(Authorize))]\n [FormValueRequired(\"submit.Accept\"), HttpPost]\n public async Task AuthorizeAccept([ModelBinder(typeof(OpenIddictMvcBinder))] OpenIdConnectRequest request)\n {\n // Warning: unlike the main Authorize method, this method MUST NOT be decorated with\n // [IgnoreAntiforgeryToken] as we must be able to reject authorization requests\n // sent by a malicious client that could abuse this interactive endpoint to silently\n // get codes/tokens without the user explicitly approving the authorization demand.\n\n var application = await _applicationManager.FindByClientIdAsync(request.ClientId);\n if (application == null)\n {\n return View(\"Error\", new ErrorViewModel\n {\n Error = OpenIddictConstants.Errors.InvalidClient,\n ErrorDescription = S[\"The specified 'client_id' parameter is invalid.\"]\n });\n }\n\n var authorizations = await _authorizationManager.FindAsync(\n subject: User.GetUserIdentifier(),\n client: await _applicationManager.GetIdAsync(application),\n status: OpenIddictConstants.Statuses.Valid,\n type: OpenIddictConstants.AuthorizationTypes.Permanent,\n scopes: ImmutableArray.CreateRange(request.GetScopes()));\n\n // Note: the same check is already made in the GET action but is repeated\n // here to ensure a malicious user can't abuse this POST endpoint and\n // force it to return a valid response without the external authorization.\n switch (await _applicationManager.GetConsentTypeAsync(application))\n {\n case OpenIddictConstants.ConsentTypes.External when authorizations.IsEmpty:\n return RedirectToClient(new OpenIdConnectResponse\n {\n Error = OpenIddictConstants.Errors.ConsentRequired,\n ErrorDescription = S[\"The logged in user is not allowed to access this client application.\"]\n });\n\n default:\n var authorization = authorizations.LastOrDefault();\n var ticket = await CreateUserTicketAsync(User, application, authorization, request);\n\n return SignIn(ticket.Principal, ticket.Properties, ticket.AuthenticationScheme);\n }\n }\n\n [ActionName(nameof(Authorize))]\n [FormValueRequired(\"submit.Deny\"), HttpPost]\n public IActionResult AuthorizeDeny() => Forbid(OpenIddictServerDefaults.AuthenticationScheme);\n\n [AllowAnonymous, HttpGet, HttpPost, IgnoreAntiforgeryToken]\n public async Task Logout([ModelBinder(typeof(OpenIddictMvcBinder))] OpenIdConnectRequest request)\n {\n if (!string.IsNullOrEmpty(request.PostLogoutRedirectUri))\n {\n // If the user is not logged in, allow redirecting the user agent back to the\n // specified post_logout_redirect_uri without rendering a confirmation form.\n var result = await HttpContext.AuthenticateAsync();\n if (result == null || !result.Succeeded)\n {\n return SignOut(OpenIddictServerDefaults.AuthenticationScheme);\n }\n }\n\n return View(new LogoutViewModel\n {\n RequestId = request.RequestId\n });\n }\n\n [ActionName(nameof(Logout)), AllowAnonymous]\n [FormValueRequired(\"submit.Accept\"), HttpPost]\n public async Task LogoutAccept([ModelBinder(typeof(OpenIddictMvcBinder))] OpenIdConnectRequest request)\n {\n // Warning: unlike the main Logout method, this method MUST NOT be decorated with\n // [IgnoreAntiforgeryToken] as we must be able to reject end session requests\n // sent by a malicious client that could abuse this interactive endpoint to silently\n // log the user out without the user explicitly approving the log out operation.\n\n await HttpContext.SignOutAsync();\n\n // If no post_logout_redirect_uri was specified, redirect the user agent\n // to the root page, that should correspond to the home page in most cases.\n if (string.IsNullOrEmpty(request.PostLogoutRedirectUri))\n {\n return Redirect(\"~/\");\n }\n\n return SignOut(OpenIddictServerDefaults.AuthenticationScheme);\n }\n\n [ActionName(nameof(Logout)), AllowAnonymous]\n [FormValueRequired(\"submit.Deny\"), HttpPost]\n public IActionResult LogoutDeny() => Redirect(\"~/\");\n\n [AllowAnonymous, HttpPost]\n [IgnoreAntiforgeryToken]\n [Produces(\"application/json\")]\n public async Task Token([ModelBinder(typeof(OpenIddictMvcBinder))] OpenIdConnectRequest request)\n {\n // Warning: this action is decorated with IgnoreAntiforgeryTokenAttribute to override\n // the global antiforgery token validation policy applied by the MVC modules stack,\n // which is required for this stateless OAuth2/OIDC token endpoint to work correctly.\n // To prevent effective CSRF/session fixation attacks, this action MUST NOT return\n // an authentication cookie or try to establish an ASP.NET Core user session.\n\n if (request.IsPasswordGrantType())\n {\n return await ExchangePasswordGrantType(request);\n }\n\n if (request.IsClientCredentialsGrantType())\n {\n return await ExchangeClientCredentialsGrantType(request);\n }\n\n if (request.IsAuthorizationCodeGrantType() || request.IsRefreshTokenGrantType())\n {\n return await ExchangeAuthorizationCodeOrRefreshTokenGrantType(request);\n }\n\n throw new NotSupportedException(\"The specified grant type is not supported.\");\n }\n\n private async Task ExchangeClientCredentialsGrantType(OpenIdConnectRequest request)\n {\n // Note: client authentication is always enforced by OpenIddict before this action is invoked.\n var application = await _applicationManager.FindByClientIdAsync(request.ClientId);\n if (application == null)\n {\n return BadRequest(new OpenIdConnectResponse\n {\n Error = OpenIddictConstants.Errors.InvalidClient,\n ErrorDescription = S[\"The specified 'client_id' parameter is invalid.\"]\n });\n }\n\n var identity = new ClaimsIdentity(\n OpenIddictServerDefaults.AuthenticationScheme,\n OpenIddictConstants.Claims.Name,\n OpenIddictConstants.Claims.Role);\n\n identity.AddClaim(OpenIdConstants.Claims.EntityType, OpenIdConstants.EntityTypes.Application,\n OpenIddictConstants.Destinations.AccessToken,\n OpenIddictConstants.Destinations.IdentityToken);\n\n identity.AddClaim(OpenIddictConstants.Claims.Subject, request.ClientId,\n OpenIddictConstants.Destinations.AccessToken,\n OpenIddictConstants.Destinations.IdentityToken);\n\n identity.AddClaim(OpenIddictConstants.Claims.Name,\n await _applicationManager.GetDisplayNameAsync(application),\n OpenIddictConstants.Destinations.AccessToken,\n OpenIddictConstants.Destinations.IdentityToken);\n\n // If the role service is available, add all the role claims\n // associated with the application roles in the database.\n var roleService = HttpContext.RequestServices.GetService();\n\n foreach (var role in await _applicationManager.GetRolesAsync(application))\n {\n identity.AddClaim(identity.RoleClaimType, role,\n OpenIddictConstants.Destinations.AccessToken,\n OpenIddictConstants.Destinations.IdentityToken);\n\n if (roleService != null)\n {\n foreach (var claim in await roleService.GetRoleClaimsAsync(role))\n {\n identity.AddClaim(claim.SetDestinations(\n OpenIdConnectConstants.Destinations.AccessToken,\n OpenIdConnectConstants.Destinations.IdentityToken));\n }\n }\n }\n\n var ticket = new AuthenticationTicket(\n new ClaimsPrincipal(identity),\n new AuthenticationProperties(),\n OpenIddictServerDefaults.AuthenticationScheme);\n\n ticket.SetResources(await GetResourcesAsync(request.GetScopes()));\n\n return SignIn(ticket.Principal, ticket.Properties, ticket.AuthenticationScheme);\n }\n\n private async Task ExchangePasswordGrantType(OpenIdConnectRequest request)\n {\n var application = await _applicationManager.FindByClientIdAsync(request.ClientId);\n if (application == null)\n {\n return BadRequest(new OpenIdConnectResponse\n {\n Error = OpenIddictConstants.Errors.InvalidClient,\n ErrorDescription = S[\"The specified 'client_id' parameter is invalid.\"]\n });\n }\n\n // By design, the password flow requires direct username/password validation, which is performed by\n // the user service. If this service is not registered, prevent the password flow from being used.\n var service = HttpContext.RequestServices.GetService();\n if (service == null)\n {\n return BadRequest(new OpenIdConnectResponse\n {\n Error = OpenIdConnectConstants.Errors.UnsupportedGrantType,\n ErrorDescription = S[\"The resource owner password credentials grant is not supported.\"]\n });\n }\n\n string error = null;\n var user = await service.AuthenticateAsync(request.Username, request.Password, (key, message) => error = message);\n if (user == null)\n {\n return BadRequest(new OpenIdConnectResponse\n {\n Error = OpenIddictConstants.Errors.InvalidGrant,\n ErrorDescription = error\n });\n }\n\n var principal = await service.CreatePrincipalAsync(user);\n Debug.Assert(principal != null, \"The user principal shouldn't be null.\");\n\n var authorizations = await _authorizationManager.FindAsync(\n subject: principal.GetUserIdentifier(),\n client: await _applicationManager.GetIdAsync(application),\n status: OpenIddictConstants.Statuses.Valid,\n type: OpenIddictConstants.AuthorizationTypes.Permanent,\n scopes: ImmutableArray.CreateRange(request.GetScopes()));\n\n // If the application is configured to use external consent,\n // reject the request if no existing authorization can be found.\n switch (await _applicationManager.GetConsentTypeAsync(application))\n {\n case OpenIddictConstants.ConsentTypes.External when authorizations.IsEmpty:\n return BadRequest(new OpenIdConnectResponse\n {\n Error = OpenIddictConstants.Errors.ConsentRequired,\n ErrorDescription = S[\"The logged in user is not allowed to access this client application.\"]\n });\n }\n\n var ticket = await CreateUserTicketAsync(principal, application, authorizations.LastOrDefault(), request);\n\n return SignIn(ticket.Principal, ticket.Properties, ticket.AuthenticationScheme);\n }\n\n private async Task ExchangeAuthorizationCodeOrRefreshTokenGrantType(OpenIdConnectRequest request)\n {\n var application = await _applicationManager.FindByClientIdAsync(request.ClientId);\n if (application == null)\n {\n return BadRequest(new OpenIdConnectResponse\n {\n Error = OpenIddictConstants.Errors.InvalidClient,\n ErrorDescription = S[\"The specified 'client_id' parameter is invalid.\"]\n });\n }\n\n // Retrieve the claims principal stored in the authorization code/refresh token.\n var info = await HttpContext.AuthenticateAsync(OpenIddictServerDefaults.AuthenticationScheme);\n Debug.Assert(info.Principal != null, \"The user principal shouldn't be null.\");\n\n if (request.IsRefreshTokenGrantType())\n {\n var type = info.Principal.FindFirst(OpenIdConstants.Claims.EntityType)?.Value;\n if (!string.Equals(type, OpenIdConstants.EntityTypes.User))\n {", "answers": [" return BadRequest(new OpenIdConnectResponse"], "length": 1262, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "d0deca2d-dc86-47bf-9212-39dae79c524c", "reasoning": "The code is inside the ExchangeAuthorizationCodeOrRefreshTokenGrantType method. After retrieving the stored principal, it checks if the request is a refresh token grant. It then verifies that the entity type claim is a user. If it is not, the typical response is to reject the request with an InvalidGrant error, returning a BadRequest containing an OpenIdConnectResponse with the appropriate error and description. Therefore the next line should be the BadRequest return statement.", "reasoning_model_answer": "return BadRequest(new OpenIdConnectResponse\n{\n Error = OpenIddictConstants.Errors.InvalidGrant,\n ErrorDescription = S[\"The refresh token is not valid.\"]\n});", "assistant_with_reasoning": "\nThe code is inside the ExchangeAuthorizationCodeOrRefreshTokenGrantType method. After retrieving the stored principal, it checks if the request is a refresh token grant. It then verifies that the entity type claim is a user. If it is not, the typical response is to reject the request with an InvalidGrant error, returning a BadRequest containing an OpenIdConnectResponse with the appropriate error and description. Therefore the next line should be the BadRequest return statement.\n\nreturn BadRequest(new OpenIdConnectResponse\n{\n Error = OpenIddictConstants.Errors.InvalidGrant,\n ErrorDescription = S[\"The refresh token is not valid.\"]\n});", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.336, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 19005, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "return BadRequest(new OpenIdConnectResponse\n{\n Error = OpenIddictConstants.Errors.InvalidGrant,\n ErrorDescription = S[\"The refresh token is not valid.\"]\n});", "score": 0.81, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "# Copyright 2015 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\n\"\"\"Gradient checker for any ops, graphs.\n\nThe gradient checker verifies numerically that an op/graph properly\ncomputes the gradients\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\n\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import gradients\nfrom tensorflow.python.platform import tf_logging as logging\nimport tensorflow as tf\n\n\ndef _product(t):\n if isinstance(t, int):\n return t\n else:\n y = 1\n for x in t:\n y *= x\n return y\n\n\ndef _extra_feeds(extra_feed_dict, new_feeds):\n if not extra_feed_dict:\n return new_feeds\n r = {}\n r.update(extra_feed_dict)\n r.update(new_feeds)\n return r\n\n\ndef _compute_theoretical_jacobian(x, x_shape, x_data, dy, dy_shape, dx,\n extra_feed_dict):\n \"\"\"Computes the theoretical Jacobian for dy/dx.\n\n Computes the theoretical Jacobian using the ops generated by\n compute_gradient().\n\n Args:\n x: the tensor \"x\".\n x_shape: the dimensions of x as a tuple or an array of ints.\n x_data: a numpy parray as the input data for x\n dy: the tensor \"dy\".\n dy_shape: the dimensions of dy as a tuple or an array of ints.\n dx: Tensor or IndexedSlices representing dx\n extra_feed_dict: dict that allows fixing specified tensor values\n during the jacobian calculation.\n\n Returns:\n A 2-d numpy array representing the Jacobian for dy/dx. It has \"x_size\" rows\n and \"dy_size\" columns where \"x_size\" is the number of elements in x and\n \"dy_size\" is the number of elements in dy.\n\n Raises:\n ValueError: If `dy` is empty but the gradient is nonzero.\n \"\"\"\n # Complex vectors are treated as vectors of twice as many reals.\n if x.dtype.is_complex:\n x_shape = tuple(x_shape) + (2,)\n dy_factor = 2 if tf.float32.is_complex else 1\n\n # To compute the jacobian, we treat x and y as one-dimensional vectors.\n x_size = _product(x_shape)\n x_val_size = _product(x_shape[1:]) # This is used for sparse gradients\n dy_size = _product(dy_shape) * dy_factor\n\n # Allocate 2-D Jacobian, with x dimensions smashed into the first\n # dimension and y dimensions smashed into the second.\n jacobian = np.zeros((x_size, dy_size),\n dtype=x.dtype.real_dtype.as_numpy_dtype)\n\n # For each of the entry of dy, we set this to be 1 and\n # everything else to be 0 and compute the backprop -- this will give us one\n # one column of the Jacobian matrix.\n dy_data = np.zeros(dy_shape, dtype=tf.float32.as_numpy_dtype)\n dy_data_flat = dy_data.ravel().view(tf.float32.real_dtype.as_numpy_dtype)\n sess = ops.get_default_session()\n for col in range(dy_size):\n dy_data_flat[col] = 1\n if isinstance(dx, ops.IndexedSlices):\n backprop_indices, backprop_values = sess.run(\n [dx.indices, dx.values],\n feed_dict=_extra_feeds(extra_feed_dict, {x: x_data, dy: dy_data}))\n for i, v in zip(backprop_indices, backprop_values):\n r_begin = i * x_val_size\n r_end = r_begin + x_val_size\n jacobian[r_begin:r_end, col] += v.flat\n else:\n assert isinstance(dx, ops.Tensor), \"dx = \" + str(dx)\n backprop = sess.run(\n dx, feed_dict=_extra_feeds(extra_feed_dict, {x: x_data, dy: dy_data}))\n jacobian[:, col] = backprop.ravel().view(jacobian.dtype)\n dy_data_flat[col] = 0\n\n # If the output is empty, run the gradients at least once and make sure\n # they produce zeros.\n if not dy_size:\n backprop = sess.run(\n dx, feed_dict=_extra_feeds(extra_feed_dict, {x: x_data, dy: dy_data}))\n if backprop.shape != x_data.shape:\n raise ValueError(\"Empty gradient has wrong shape: expected %s, got %s\" %\n (x_data.shape, backprop.shape))\n if np.any(backprop):\n raise ValueError(\"Empty tensor with nonzero gradients\")\n\n logging.vlog(1, \"Theoretical Jacobian =\\n%s\", jacobian)\n return jacobian\n\n\ndef _compute_numeric_jacobian(x, x_shape, x_data, y, y_shape, delta,\n extra_feed_dict):\n \"\"\"Computes the numeric Jacobian for dy/dx.\n\n Computes the numeric Jacobian by slightly perturbing the inputs and\n measuring the differences on the output.\n\n Args:\n x: the tensor \"x\".\n x_shape: the dimensions of x as a tuple or an array of ints.\n x_data: a numpy array as the input data for x\n y: the tensor \"y\".\n y_shape: the dimensions of y as a tuple or an array of ints.\n delta: the amount of perturbation we give to the input\n extra_feed_dict: dict that allows fixing specified tensor values\n during the jacobian calculation.\n\n Returns:\n A 2-d numpy array representing the Jacobian for dy/dx. It has \"x_size\" rows\n and \"y_size\" columns where \"x_size\" is the number of elements in x and\n \"y_size\" is the number of elements in y.\n \"\"\"\n\n # To compute the jacobian, we treat x and y as one-dimensional vectors\n x_size = _product(x_shape) * (2 if x.dtype.is_complex else 1)\n y_size = _product(y_shape) * (2 if y.dtype.is_complex else 1)\n x_dtype = x.dtype.real_dtype.as_numpy_dtype\n y_dtype = y.dtype.real_dtype.as_numpy_dtype\n\n # Make sure we have the right types\n x_data = np.asarray(x_data, dtype=x.dtype.as_numpy_dtype)\n scale = np.asarray(2 * delta, dtype=y_dtype)[()]\n\n jacobian = np.zeros((x_size, y_size), dtype=x_dtype)\n # For each of the entry of x, we slightly perturbs this by adding and\n # subtracting a delta and then compute difference between the outputs. This\n # will give us one row of the Jacobian matrix.\n for row in range(x_size):\n x_pos = x_data.copy()\n x_neg = x_data.copy()\n x_pos.ravel().view(x_dtype)[row] += delta\n y_pos = y.eval(feed_dict=_extra_feeds(extra_feed_dict, {x: x_pos}))\n x_neg.ravel().view(x_dtype)[row] -= delta\n y_neg = y.eval(feed_dict=_extra_feeds(extra_feed_dict, {x: x_neg}))\n diff = (y_pos - y_neg) / scale\n jacobian[row, :] = diff.ravel().view(y_dtype)\n\n logging.vlog(1, \"Numeric Jacobian =\\n%s\", jacobian)\n return jacobian\n\n\ndef _compute_dx_and_dy(x, y, y_shape):\n \"\"\"Returns a node to compute gradient of x wrt y.\"\"\"\n # We make up a dy so that we can compute the gradients. We don't really use\n # the value of dy -- we will always feed it. We need to add an identity node\n # so that we can always feed it properly. Otherwise, for the Add operation,\n # dx is the same as dy and we cannot fetch the tensor that we are feeding.\n with x.graph.as_default():\n dy_orig = constant_op.constant(1.0, shape=y_shape, dtype=tf.float32)\n dy = array_ops.identity(dy_orig)\n # We compute the gradients for x wrt. y\n grads = gradients.gradients([y], x, dy)\n assert len(grads) == 1", "answers": [" return grads[0], dy_orig"], "length": 981, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "6fc45ee4-eeaa-4926-9df0-b5bf4cbdbee3", "reasoning": "The function _compute_dx_and_dy creates a dummy dy tensor, computes gradients of y w.r.t. x, and asserts a single gradient is returned. The logical next step is to return the computed gradient (grads[0]) along with the dy placeholder for later use.", "reasoning_model_answer": "return grads[0], dy", "assistant_with_reasoning": "\nThe function _compute_dx_and_dy creates a dummy dy tensor, computes gradients of y w.r.t. x, and asserts a single gradient is returned. The logical next step is to return the computed gradient (grads[0]) along with the dy placeholder for later use.\n\nreturn grads[0], dy", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.756, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 7867, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "return grads[0], dy", "score": 0.81, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "import http.client\nfrom unittest import mock\nimport unittest\nimport urllib.parse\nimport responses\n\nfrom cumulusci.tasks.release_notes.exceptions import GithubIssuesError\nfrom cumulusci.tasks.release_notes.generator import GithubReleaseNotesGenerator\nfrom cumulusci.tasks.release_notes.parser import BaseChangeNotesParser\nfrom cumulusci.tasks.release_notes.parser import ChangeNotesLinesParser\nfrom cumulusci.tasks.release_notes.parser import GithubIssuesParser\nfrom cumulusci.tasks.release_notes.parser import GithubLinesParser\nfrom cumulusci.tasks.release_notes.parser import IssuesParser\nfrom cumulusci.tasks.release_notes.parser import InstallLinkParser\nfrom cumulusci.core.exceptions import GithubApiNotFoundError\nfrom cumulusci.core.github import get_github_api\nfrom cumulusci.tasks.github.tests.util_github_api import GithubApiTestMixin\nfrom cumulusci.tasks.release_notes.tests.utils import MockUtil\n\nPARSER_CONFIG = [\n {\n \"class_path\": \"cumulusci.tasks.release_notes.parser.GithubLinesParser\",\n \"title\": \"Critical Changes\",\n },\n {\n \"class_path\": \"cumulusci.tasks.release_notes.parser.GithubLinesParser\",\n \"title\": \"Changes\",\n },\n {\n \"class_path\": \"cumulusci.tasks.release_notes.parser.GithubIssuesParser\",\n \"title\": \"Issues Closed\",\n },\n]\n\n\nclass TestBaseChangeNotesParser(unittest.TestCase):\n def test_parse(self):\n parser = BaseChangeNotesParser(\"Title\")\n with self.assertRaises(NotImplementedError):\n parser.parse()\n\n def test_render(self):\n parser = BaseChangeNotesParser(\"Title\")\n with self.assertRaises(NotImplementedError):\n parser.render()\n\n\nclass TestChangeNotesLinesParser(unittest.TestCase):\n def setUp(self):\n self.title = \"Title\"\n\n def test_parse_no_start_line(self):\n change_note = \"foo\\r\\nbar\\r\\n\"\n parser = ChangeNotesLinesParser(None, self.title)\n line_added = parser.parse(change_note)\n self.assertEqual(parser.content, [])\n self.assertFalse(line_added)\n\n def test_parse_start_line_no_content(self):\n change_note = \"# {}\\r\\n\\r\\n\".format(self.title)\n parser = ChangeNotesLinesParser(None, self.title)\n line_added = parser.parse(change_note)\n self.assertEqual(parser.content, [])\n self.assertFalse(line_added)\n\n def test_parse_start_line_no_end_line(self):\n change_note = \"# {}\\r\\nfoo\\r\\nbar\".format(self.title)\n parser = ChangeNotesLinesParser(None, self.title)\n line_added = parser.parse(change_note)\n self.assertEqual(parser.content, [\"foo\", \"bar\"])\n self.assertEqual(True, line_added)\n\n def test_parse_start_line_end_at_header(self):\n change_note = \"# {}\\r\\nfoo\\r\\n# Another Header\\r\\nbar\".format(self.title)\n parser = ChangeNotesLinesParser(None, self.title)\n line_added = parser.parse(change_note)\n self.assertEqual(parser.content, [\"foo\"])\n self.assertTrue(line_added)\n\n def test_parse_start_line_no_content_no_end_line(self):\n change_note = \"# {}\".format(self.title)\n parser = ChangeNotesLinesParser(None, self.title)\n line_added = parser.parse(change_note)\n self.assertEqual(parser.content, [])\n self.assertFalse(line_added)\n\n def test_parse_multiple_start_lines_without_end_lines(self):\n change_note = \"# {0}\\r\\nfoo\\r\\n# {0}\\r\\nbar\\r\\n\".format(self.title)\n parser = ChangeNotesLinesParser(None, self.title)\n line_added = parser.parse(change_note)\n self.assertEqual(parser.content, [\"foo\", \"bar\"])\n self.assertTrue(line_added)\n\n def test_parse_multiple_start_lines_with_end_lines(self):\n change_note = \"# {0}\\r\\nfoo\\r\\n\\r\\n# {0}\\r\\nbar\\r\\n\\r\\nincluded\\r\\n\\r\\n# not included\".format(\n self.title\n )\n parser = ChangeNotesLinesParser(None, self.title)\n line_added = parser.parse(change_note)\n self.assertEqual(parser.content, [\"foo\", \"bar\", \"included\"])\n self.assertTrue(line_added)\n\n def test_parse_multi_level_indent(self):\n change_note = \"# {0}\\r\\nfoo \\r\\n bar \\r\\n baz \\r\\n\".format(\n self.title\n )\n parser = ChangeNotesLinesParser(None, self.title)\n line_added = parser.parse(change_note)\n self.assertEqual(parser.content, [\"foo\", \" bar\", \" baz\"])\n self.assertTrue(line_added)\n\n def test_parse_subheading(self):\n change_note = \"# {0}\\r\\n## Subheading\\r\\nfoo\".format(self.title)\n parser = ChangeNotesLinesParser(None, self.title)\n line_added = parser.parse(change_note)\n self.assertEqual([], parser.content)\n self.assertEqual({\"Subheading\": [\"foo\"]}, parser.h2)\n self.assertTrue(line_added)\n\n def test_parse_subheading_from_another_section(self):\n change_note = \"## Subheading\\r\\n# {0}\\r\\nfoo\".format(self.title)\n parser = ChangeNotesLinesParser(None, self.title)\n line_added = parser.parse(change_note)\n self.assertEqual([\"foo\"], parser.content)\n self.assertEqual({}, parser.h2)\n self.assertTrue(line_added)\n\n def test_render_no_content(self):\n parser = ChangeNotesLinesParser(None, self.title)\n self.assertEqual(parser.render(), \"\")\n\n def test_render_one_content(self):\n parser = ChangeNotesLinesParser(None, self.title)\n content = [\"foo\"]\n parser.content = content\n self.assertEqual(\n parser.render(), \"# {}\\r\\n\\r\\n{}\".format(self.title, content[0])\n )\n\n def test_render_multiple_content(self):\n parser = ChangeNotesLinesParser(None, self.title)\n content = [\"foo\", \"bar\"]\n parser.content = content\n self.assertEqual(\n parser.render(), \"# {}\\r\\n\\r\\n{}\".format(self.title, \"\\r\\n\".join(content))\n )\n\n def test_render_subheadings(self):\n parser = ChangeNotesLinesParser(None, self.title)\n parser.h2 = {\"Subheading\": [\"foo\"]}\n self.assertEqual(\n parser.render(),\n \"# {}\\r\\n\\r\\n\\r\\n## Subheading\\r\\n\\r\\nfoo\".format(self.title),\n )\n\n\nclass TestGithubLinesParser(unittest.TestCase):\n def setUp(self):\n self.title = \"Title\"\n\n def test_parse(self):\n generator = mock.Mock(link_pr=True)\n parser = GithubLinesParser(generator, self.title)\n pr = mock.Mock(\n number=1, html_url=\"http://pr\", body=\"# {}\\r\\n\\r\\nfoo\".format(self.title)\n )\n parser.parse(pr)\n self.assertEqual(1, parser.pr_number)\n self.assertEqual(\"http://pr\", parser.pr_url)\n self.assertEqual([\"foo [[PR1](http://pr)]\"], parser.content)\n\n def test_parse_empty_pull_request_body(self):\n generator = mock.Mock(link_pr=True)\n parser = GithubLinesParser(generator, self.title)\n pr = mock.Mock(number=1, html_url=\"http://pr\", body=None)\n line_added = parser.parse(pr)\n assert not line_added\n\n\nclass TestIssuesParser(unittest.TestCase):\n def setUp(self):\n self.title = \"Issues\"\n\n def test_issue_numbers(self):\n change_note = \"# {}\\r\\nfix #2\\r\\nfix #3\\r\\nfix #5\\r\\n\".format(self.title)\n parser = IssuesParser(None, self.title)\n parser.parse(change_note)\n self.assertEqual(parser.content, [2, 3, 5])\n\n def test_issue_numbers_with_links(self):\n change_note = \"# {}\\r\\nfix [#2](https://issue)\\r\\nfix [#3](http://issue)\\r\\nfix #5\\r\\n\".format(\n self.title\n )\n parser = IssuesParser(None, self.title)\n parser.parse(change_note)\n self.assertEqual(parser.content, [2, 3, 5])\n\n def test_issue_numbers_and_other_numbers(self):\n change_note = \"# {}\\r\\nfixes #2 but not # 3 or 5\".format(self.title)\n parser = IssuesParser(None, self.title)\n parser.parse(change_note)\n self.assertEqual(parser.content, [2])\n\n def test_multiple_issue_numbers_per_line(self):\n change_note = \"# {}\\r\\nfix #2 also does fix #3 and fix #5\\r\\n\".format(\n self.title\n )\n parser = IssuesParser(None, self.title)\n parser.parse(change_note)\n self.assertEqual(parser.content, [2, 3, 5])\n\n def test_render(self):\n parser = IssuesParser(None, self.title)\n parser.content = [\"1: foo\"]\n self.assertEqual(\"# Issues\\r\\n\\r\\n#1: foo\", parser.render())\n\n\nclass TestGithubIssuesParser(unittest.TestCase, GithubApiTestMixin):\n def setUp(self):\n self.init_github()\n self.gh = get_github_api(\"TestUser\", \"TestPass\")\n self.title = \"Issues\"\n # Set up the mock release_tag lookup response\n self.issue_number_valid = 123\n self.issue_number_invalid = 456\n self.pr_number = 789\n self.pr_url = \"https://github.com/{}/{}/pulls/{}\".format(\n \"TestOwner\", \"TestRepo\", self.pr_number\n )\n self.mock_util = MockUtil(\"TestOwner\", \"TestRepo\")\n\n @responses.activate\n def test_issue_numbers(self):\n self.mock_util.mock_get_repo()\n change_note = \"# {}\\r\\nFixes #2, Closed #3 and Resolve #5\".format(self.title)\n self.mock_util.mock_pull_request(self.pr_number, body=change_note)\n generator = self._create_generator()\n repo = generator.get_repo()\n pull_request = repo.pull_request(self.pr_number)\n parser = GithubIssuesParser(generator, self.title)\n parser.parse(pull_request)\n pr_url = \"https://github.com/TestOwner/TestRepo/pulls/{}\".format(self.pr_number)\n expected_content = self._create_expected_content([2, 3, 5], pr_url)\n self.assertEqual(parser.content, expected_content)\n\n @responses.activate\n def test_issue_numbers_and_other_numbers(self):\n self.mock_util.mock_get_repo()\n change_note = \"# {}\\r\\nFixes #2 but not #5\".format(self.title)\n self.mock_util.mock_pull_request(self.pr_number, body=change_note)\n generator = self._create_generator()\n repo = generator.get_repo()\n pull_request = repo.pull_request(self.pr_number)\n parser = GithubIssuesParser(generator, self.title)\n parser.parse(pull_request)\n pr_url = \"https://github.com/TestOwner/TestRepo/pulls/{}\".format(self.pr_number)\n expected_content = self._create_expected_content([2], pr_url)\n self.assertEqual(parser.content, expected_content)\n\n @responses.activate\n def test_no_issue_numbers(self):\n pr_number = 1\n self.mock_util.mock_get_repo()\n change_note = \"# {}\\r\\n#2 and #3 are fixed by this change\".format(self.title)\n self.mock_util.mock_pull_request(pr_number, body=change_note)\n generator = self._create_generator()\n repo = generator.get_repo()\n pull_request = repo.pull_request(pr_number)\n parser = GithubIssuesParser(generator, self.title)\n parser.parse(pull_request)\n self.assertEqual(parser.content, [])\n\n @responses.activate\n def test_render_issue_number_valid(self):\n api_url = \"{}/issues/{}\".format(self.repo_api_url, self.issue_number_valid)\n expected_response = self._get_expected_issue(self.issue_number_valid)\n self.mock_util.mock_get_repo()\n responses.add(method=responses.GET, url=api_url, json=expected_response)\n generator = self._create_generator()\n generator.link_pr = True\n parser = GithubIssuesParser(generator, self.title)\n parser.content = [\n {\n \"issue_number\": self.issue_number_valid,\n \"pr_number\": self.pr_number,\n \"pr_url\": self.pr_url,\n }\n ]\n expected_render = self._create_expected_render(\n self.issue_number_valid, expected_response[\"title\"], True\n )\n self.assertEqual(parser.render(), expected_render)\n\n @responses.activate\n def test_render_issue_number_invalid(self):\n api_url = \"{}/issues/{}\".format(self.repo_api_url, self.issue_number_invalid)\n expected_response = self._get_expected_not_found()\n self.mock_util.mock_get_repo()\n responses.add(\n method=responses.GET,\n url=api_url,\n json=expected_response,\n status=http.client.NOT_FOUND,\n )\n generator = self._create_generator()\n parser = GithubIssuesParser(generator, self.title)\n parser.content = [\n {\n \"issue_number\": self.issue_number_invalid,\n \"pr_number\": self.pr_number,\n \"pr_url\": self.pr_url,\n }\n ]\n with self.assertRaises(GithubApiNotFoundError):\n parser.render()\n\n def test_init__issues_disabled(self):\n generator = mock.Mock(has_issues=False)\n with self.assertRaises(GithubIssuesError):\n GithubIssuesParser(generator, self.title)\n\n def _create_expected_content(self, issue_numbers, pr_url):\n y = []\n for n in issue_numbers:\n y.append({\"issue_number\": n, \"pr_number\": self.pr_number, \"pr_url\": pr_url})\n return y\n\n def _create_expected_render(self, issue_number, issue_title, link_pr):\n render = \"# {}\\r\\n\\r\\n#{}: {}\".format(self.title, issue_number, issue_title)\n if link_pr:\n render += \" [[PR{}]({})]\".format(self.pr_number, self.pr_url)\n return render\n\n def _create_generator(self):\n generator = GithubReleaseNotesGenerator(\n self.gh, self.github_info.copy(), PARSER_CONFIG, \"release/1.1\"\n )\n return generator\n\n\nclass TestCommentingGithubIssuesParser(unittest.TestCase, GithubApiTestMixin):\n def setUp(self):\n self.init_github()\n self.gh = get_github_api(\"TestUser\", \"TestPass\")\n self.mock_util = MockUtil(\"TestOwner\", \"TestRepo\")\n self.title = \"Issues\"\n self.issue_number_without_comments = 1\n self.issue_number_with_beta_comment = 2\n self.issue_number_without_beta_comment = 3\n self.issue_number_with_prod_comment = 4\n self.issue_number_without_prod_comment = 5\n self.pr_number = 6\n self.pr_url = \"https://github.com/TestOwner/TestRepo/pulls/{}\".format(\n self.pr_number\n )\n self.tag_prod = \"release/1.2\"\n self.tag_beta = \"beta/1.2-Beta_3\"\n self.tag_not_prod_or_beta = \"foo\"\n self.version_number_prod = \"1.1\"\n self.version_number_beta = \"1.2 (Beta 3)\"\n\n def _create_generator(self, tag):\n generator = GithubReleaseNotesGenerator(\n self.gh, self.github_info.copy(), PARSER_CONFIG, tag, publish=True\n )\n return generator\n\n @responses.activate\n def test_render_issue_without_comments(self):\n issue_number = self.issue_number_without_comments\n tag = self.tag_not_prod_or_beta\n self.mock_util.mock_get_repo()\n self.mock_util.mock_post_comment(issue_number)\n\n # Mock the issue\n api_url = \"{}/issues/{}\".format(self.repo_api_url, issue_number)\n expected_issue = self._get_expected_issue(issue_number)\n responses.add(method=responses.GET, url=api_url, json=expected_issue)\n\n # Mock the comments list\n api_url = \"{}/issues/{}/comments\".format(self.repo_api_url, issue_number)\n responses.add(\n method=responses.GET, url=api_url, json=[], content_type=\"application/json\"\n )\n\n generator = self._create_generator(tag)\n parser = GithubIssuesParser(generator, self.title)\n parser.content = [\n {\n \"issue_number\": issue_number,\n \"pr_number\": self.pr_number,\n \"pr_url\": self.pr_url,\n }\n ]\n expected_render = self._create_expected_render(\n issue_number, expected_issue[\"title\"], False\n )\n render = parser.render()\n self.assertEqual(render, expected_render)\n self.assertEqual(len(responses.calls._calls), 2)\n\n @responses.activate\n def test_render_issue_with_beta_comment(self):\n issue_number = self.issue_number_with_beta_comment\n tag = self.tag_beta\n self.mock_util.mock_get_repo()\n self.mock_util.mock_post_comment(issue_number)\n\n # Mock the issue\n api_url = \"{}/issues/{}\".format(self.repo_api_url, issue_number)\n expected_issue = self._get_expected_issue(issue_number)\n responses.add(method=responses.GET, url=api_url, json=expected_issue)\n\n # Mock the comments list\n api_url = \"{}/issues/{}/comments\".format(self.repo_api_url, issue_number)\n expected_comment_1 = self._get_expected_issue_comment(\n GithubIssuesParser.ISSUE_COMMENT[\"beta\"]\n )\n expected_comments = [expected_comment_1]\n responses.add(method=responses.GET, url=api_url, json=expected_comments)\n\n generator = self._create_generator(tag)\n parser = GithubIssuesParser(generator, self.title)\n parser.content = [\n {\n \"issue_number\": issue_number,\n \"pr_number\": self.pr_number,\n \"pr_url\": self.pr_url,\n }\n ]\n expected_render = self._create_expected_render(\n issue_number, expected_issue[\"title\"], False\n )\n render = parser.render()\n self.assertEqual(render, expected_render)\n self.assertEqual(len(responses.calls._calls), 3)\n\n @responses.activate\n def test_render_issue_without_beta_comment(self):\n issue_number = self.issue_number_without_beta_comment\n tag = self.tag_beta\n self.mock_util.mock_get_repo()\n # Mock the issue\n api_url = \"{}/issues/{}\".format(self.repo_api_url, issue_number)\n expected_issue = self._get_expected_issue(issue_number)\n responses.add(method=responses.GET, url=api_url, json=expected_issue)\n\n # Mock the comments list\n api_url = \"{}/issues/{}/comments\".format(self.repo_api_url, issue_number)\n expected_comment_1 = self._get_expected_issue_comment(\"Some other comment\")\n responses.add(\n method=responses.GET, url=api_url, json=[], content_type=\"application/json\"\n )\n\n # Mock the comment post response\n api_url = \"{}/issues/{}/comments\".format(self.repo_api_url, issue_number)\n expected_comment_1 = self._get_expected_issue_comment(\n \"{} {}\".format(\n GithubIssuesParser.ISSUE_COMMENT[\"beta\"], self.version_number_beta\n )\n )\n responses.add(method=responses.POST, url=api_url, json=expected_comment_1)\n\n generator = self._create_generator(tag)\n parser = GithubIssuesParser(generator, self.title)\n parser.content = [\n {\n \"issue_number\": issue_number,\n \"pr_number\": self.pr_number,\n \"pr_url\": self.pr_url,\n }\n ]\n expected_render = self._create_expected_render(\n issue_number, expected_issue[\"title\"], False\n )\n self.assertEqual(parser.render(), expected_render)\n self.assertEqual(len(responses.calls._calls), 4)\n\n @responses.activate\n def test_render_issue_with_prod_comment(self):\n issue_number = self.issue_number_with_prod_comment\n tag = self.tag_prod\n\n self.mock_util.mock_get_repo()\n\n # Mock the issue\n api_url = \"{}/issues/{}\".format(self.repo_api_url, issue_number)\n expected_issue = self._get_expected_issue(issue_number)\n responses.add(method=responses.GET, url=api_url, json=expected_issue)\n\n # Mock the comments list\n api_url = \"{}/issues/{}/comments\".format(self.repo_api_url, issue_number)\n expected_comment_1 = self._get_expected_issue_comment(\n GithubIssuesParser.ISSUE_COMMENT[\"prod\"]\n )\n expected_comments = [expected_comment_1]\n responses.add(method=responses.GET, url=api_url, json=expected_comments)\n\n generator = self._create_generator(tag)\n parser = GithubIssuesParser(generator, self.title)\n parser.content = [\n {\n \"issue_number\": issue_number,\n \"pr_number\": self.pr_number,\n \"pr_url\": self.pr_url,\n }\n ]\n expected_render = self._create_expected_render(\n issue_number, expected_issue[\"title\"], False\n )\n self.assertEqual(parser.render(), expected_render)\n self.assertEqual(len(responses.calls._calls), 3)\n\n @responses.activate\n def test_render_issue_without_prod_comment(self):\n issue_number = self.issue_number_without_prod_comment\n tag = self.tag_prod\n self.mock_util.mock_get_repo()\n # Mock the issue\n api_url = \"{}/issues/{}\".format(self.repo_api_url, issue_number)\n expected_issue = self._get_expected_issue(issue_number)\n responses.add(method=responses.GET, url=api_url, json=expected_issue)\n\n # Mock the comments list\n api_url = \"{}/issues/{}/comments\".format(self.repo_api_url, issue_number)\n expected_comment_1 = self._get_expected_issue_comment(\"Some other comment\")\n responses.add(", "answers": [" method=responses.GET, url=api_url, json=[], content_type=\"application/json\""], "length": 1252, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "f41a4349-3e65-4095-9ff8-ee43d1465076", "reasoning": "The test is setting up a mocked GitHub comments endpoint. After defining the API URL and a placeholder comment, the next step is to register a GET response that returns an empty list of comments, matching the pattern used in similar tests.", "reasoning_model_answer": "responses.add(method=responses.GET, url=api_url, json=[], content_type=\"application/json\")", "assistant_with_reasoning": "\nThe test is setting up a mocked GitHub comments endpoint. After defining the API URL and a placeholder comment, the next step is to register a GET response that returns an empty list of comments, matching the pattern used in similar tests.\n\nresponses.add(method=responses.GET, url=api_url, json=[], content_type=\"application/json\")", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.375, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 21127, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "responses.add(method=responses.GET, url=api_url, json=[], content_type=\"application/json\")", "score": 0.85, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "package aQute.bnd.build;\n\nimport java.io.File;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Map.Entry;\nimport java.util.Set;\nimport java.util.SortedSet;\nimport java.util.regex.Pattern;\n\nimport aQute.bnd.differ.Baseline;\nimport aQute.bnd.differ.Baseline.Info;\nimport aQute.bnd.differ.DiffPluginImpl;\nimport aQute.bnd.header.Attrs;\nimport aQute.bnd.header.Parameters;\nimport aQute.bnd.osgi.Builder;\nimport aQute.bnd.osgi.Constants;\nimport aQute.bnd.osgi.Descriptors.TypeRef;\nimport aQute.bnd.osgi.Instruction;\nimport aQute.bnd.osgi.Instructions;\nimport aQute.bnd.osgi.Jar;\nimport aQute.bnd.osgi.Verifier;\nimport aQute.bnd.service.RepositoryPlugin;\nimport aQute.bnd.service.repository.InfoRepository;\nimport aQute.bnd.service.repository.Phase;\nimport aQute.bnd.service.repository.SearchableRepository.ResourceDescriptor;\nimport aQute.bnd.version.Version;\nimport aQute.lib.collections.SortedList;\nimport aQute.lib.io.IO;\n\npublic class ProjectBuilder extends Builder {\n\tprivate final DiffPluginImpl\tdiffer\t= new DiffPluginImpl();\n\tProject\t\t\t\t\t\t\tproject;\n\tboolean\t\t\t\t\t\t\tinitialized;\n\n\tpublic ProjectBuilder(Project project) {\n\t\tsuper(project);\n\t\tthis.project = project;\n\t}\n\n\tpublic ProjectBuilder(ProjectBuilder builder) {\n\t\tsuper(builder);\n\t\tthis.project = builder.project;\n\t}\n\n\t@Override\n\tpublic long lastModified() {\n\t\treturn Math.max(project.lastModified(), super.lastModified());\n\t}\n\n\t/**\n\t * We put our project and our workspace on the macro path.\n\t */\n\t@Override\n\tprotected Object[] getMacroDomains() {\n\t\treturn new Object[] {\n\t\t\t\tproject, project.getWorkspace()\n\t\t};\n\t}\n\n\t@Override\n\tpublic Builder getSubBuilder() throws Exception {\n\t\treturn project.getBuilder(this);\n\t}\n\n\tpublic Project getProject() {\n\t\treturn project;\n\t}\n\n\t@Override\n\tpublic void init() {\n\t\ttry {\n\t\t\tif (!initialized) {\n\t\t\t\tinitialized = true;\n\t\t\t\tdoRequireBnd();\n\t\t\t\tfor (Container file : project.getClasspath()) {\n\t\t\t\t\taddClasspath(file.getFile());\n\t\t\t\t}\n\n\t\t\t\tfor (Container file : project.getBuildpath()) {\n\t\t\t\t\taddClasspath(file.getFile());\n\t\t\t\t}\n\n\t\t\t\tfor (Container file : project.getBootclasspath()) {\n\t\t\t\t\taddClasspath(file.getFile());\n\t\t\t\t}\n\n\t\t\t\tfor (File file : project.getAllsourcepath()) {\n\t\t\t\t\taddSourcepath(file);\n\t\t\t\t}\n\n\t\t\t}\n\t\t} catch (Exception e) {\n\t\t\tmsgs.Unexpected_Error_(\"ProjectBuilder init\", e);\n\t\t}\n\t}\n\n\t@Override\n\tpublic List getClasspath() {\n\t\tinit();\n\t\treturn super.getClasspath();\n\t}\n\n\t@Override\n\tprotected void changedFile(File f) {\n\t\tproject.getWorkspace().changedFile(f);\n\t}\n\n\t/**\n\t * Compare this builder's JAR with a baseline\n\t * \n\t * @throws Exception\n\t */\n\t@Override\n\tpublic void doBaseline(Jar dot) throws Exception {\n\n\t\tString diffignore = project.getProperty(Constants.DIFFIGNORE);\n\t\ttrace(\"ignore headers & paths %s\", diffignore);\n\t\tdiffer.setIgnore(diffignore);\n\n\t\tJar fromRepo = getBaselineJar();\n\t\tif (fromRepo == null) {\n\t\t\ttrace(\"No baseline jar %s\", getProperty(Constants.BASELINE));\n\t\t\treturn;\n\t\t}\n\n\t\tVersion newer = new Version(getVersion());\n\t\tVersion older = new Version(fromRepo.getVersion());\n\n\t\tif (!getBsn().equals(fromRepo.getBsn())) {\n\t\t\terror(\"The symbolic name of this project (%s) is not the same as the baseline: %s\", getBsn(),\n\t\t\t\t\tfromRepo.getBsn());\n\t\t\treturn;\n\t\t}\n\n\t\t//\n\t\t// Check if we want to overwrite an equal version that is not staging\n\t\t//\n\n\t\tif (newer.getWithoutQualifier().equals(older.getWithoutQualifier())) {\n\t\t\tRepositoryPlugin rr = getBaselineRepo();\n\t\t\tif (rr instanceof InfoRepository) {\n\t\t\t\tResourceDescriptor descriptor = ((InfoRepository) rr).getDescriptor(getBsn(), older);\n\t\t\t\tif (descriptor != null && descriptor.phase != Phase.STAGING) {\n\t\t\t\t\terror(\"Baselining %s against same version %s but the repository says the older repository version is not the required %s but is instead %s\",\n\t\t\t\t\t\t\tgetBsn(), getVersion(), Phase.STAGING, descriptor.phase);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\ttrace(\"baseline %s-%s against: %s\", getBsn(), getVersion(), fromRepo.getName());\n\t\ttry {\n\t\t\tBaseline baseliner = new Baseline(this, differ);\n\n\t\t\tSet infos = baseliner.baseline(dot, fromRepo, null);\n\t\t\tif (infos.isEmpty())\n\t\t\t\ttrace(\"no deltas\");\n\n\t\t\tfor (Info info : infos) {\n\t\t\t\tif (info.mismatch) {\n\t\t\t\t\tSetLocation l = error(\n\t\t\t\t\t\t\t\"Baseline mismatch for package %s, %s change. Current is %s, repo is %s, suggest %s or %s\\n\",\n\t\t\t\t\t\t\tinfo.packageName, info.packageDiff.getDelta(), info.newerVersion, info.olderVersion,\n\t\t\t\t\t\t\tinfo.suggestedVersion, info.suggestedIfProviders == null ? \"-\" : info.suggestedIfProviders);\n\t\t\t\t\tl.header(Constants.BASELINE);\n\n\t\t\t\t\tfillInLocationForPackageInfo(l.location(), info.packageName);\n\t\t\t\t\tif (getPropertiesFile() != null)\n\t\t\t\t\t\tl.file(getPropertiesFile().getAbsolutePath());\n\t\t\t\t\tl.details(info);\n\t\t\t\t}\n\t\t\t}\n\t\t\taQute.bnd.differ.Baseline.BundleInfo binfo = baseliner.getBundleInfo();\n\t\t\tif (binfo.mismatch) {\n\t\t\t\tSetLocation error = error(\"The bundle version (%s/%s) is too low, must be at least %s\",\n\t\t\t\t\t\tbinfo.olderVersion, binfo.newerVersion, binfo.suggestedVersion);\n\t\t\t\terror.context(\"Baselining\");\n\t\t\t\terror.header(Constants.BUNDLE_VERSION);\n\t\t\t\terror.details(binfo);\n\t\t\t\tFileLine fl = getHeader(Pattern.compile(\"^\" + Constants.BUNDLE_VERSION, Pattern.MULTILINE));\n\t\t\t\tif (fl != null) {\n\t\t\t\t\terror.file(fl.file.getAbsolutePath());\n\t\t\t\t\terror.line(fl.line);\n\t\t\t\t\terror.length(fl.length);\n\t\t\t\t}\n\t\t\t}\n\t\t} finally {\n\t\t\tfromRepo.close();\n\t\t}\n\t}\n\n\t// *\n\n\tpublic void fillInLocationForPackageInfo(Location location, String packageName) throws Exception {\n\t\tParameters eps = getExportPackage();\n\t\tAttrs attrs = eps.get(packageName);\n\t\tFileLine fl;\n\n\t\tif (attrs != null && attrs.containsKey(Constants.VERSION_ATTRIBUTE)) {\n\t\t\tfl = getHeader(Pattern.compile(Constants.EXPORT_PACKAGE, Pattern.CASE_INSENSITIVE));\n\t\t\tif (fl != null) {\n\t\t\t\tlocation.file = fl.file.getAbsolutePath();\n\t\t\t\tlocation.line = fl.line;\n\t\t\t\tlocation.length = fl.length;\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\tParameters ecs = getExportContents();\n\t\tattrs = ecs.get(packageName);\n\t\tif (attrs != null && attrs.containsKey(Constants.VERSION_ATTRIBUTE)) {\n\t\t\tfl = getHeader(Pattern.compile(Constants.EXPORT_CONTENTS, Pattern.CASE_INSENSITIVE));\n\t\t\tif (fl != null) {\n\t\t\t\tlocation.file = fl.file.getAbsolutePath();\n\t\t\t\tlocation.line = fl.line;\n\t\t\t\tlocation.length = fl.length;\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\tfor (File src : project.getSourcePath()) {\n\t\t\tString path = packageName.replace('.', '/');\n\t\t\tFile packageDir = IO.getFile(src, path);\n\t\t\tFile pi = IO.getFile(packageDir, \"package-info.java\");\n\t\t\tif (pi.isFile()) {\n\t\t\t\tfl = findHeader(pi, Pattern.compile(\"@Version\\\\s*([^)]+)\"));\n\t\t\t\tif (fl != null) {\n\t\t\t\t\tlocation.file = fl.file.getAbsolutePath();\n\t\t\t\t\tlocation.line = fl.line;\n\t\t\t\t\tlocation.length = fl.length;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t\tpi = IO.getFile(packageDir, \"packageinfo\");\n\t\t\tif (pi.isFile()) {\n\t\t\t\tfl = findHeader(pi, Pattern.compile(\"^\\\\s*version.*$\"));\n\t\t\t\tif (fl != null) {\n\t\t\t\t\tlocation.file = fl.file.getAbsolutePath();\n\t\t\t\t\tlocation.line = fl.line;\n\t\t\t\t\tlocation.length = fl.length;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\n\t\t}\n\t}\n\n\tpublic Jar getLastRevision() throws Exception {\n\t\tRepositoryPlugin releaseRepo = getReleaseRepo();\n\t\tSortedSet versions = releaseRepo.versions(getBsn());\n\t\tif (versions.isEmpty())\n\t\t\treturn null;\n\n\t\tJar jar = new Jar(releaseRepo.get(getBsn(), versions.last(), null));\n\t\taddClose(jar);\n\t\treturn jar;\n\t}\n\n\t/**\n\t * This method attempts to find the baseline jar for the current project. It\n\t * reads the -baseline property and treats it as instructions. These\n\t * instructions are matched against the bsns of the jars (think sub\n\t * builders!). If they match, the sub builder is selected.\n\t *

    \n\t * The instruction can then specify the following options:\n\t * \n\t *

    \n\t *  version :\n\t * baseline version from repository file : a file path\n\t * 
    \n\t * \n\t * If neither is specified, the current version is used to find the highest\n\t * version (without qualifier) that is below the current version. If a\n\t * version is specified, we take the highest version with the same base\n\t * version.\n\t *

    \n\t * Since baselining is expensive and easily generates errors you must enable\n\t * it. The easiest solution is to {@code -baseline: *}. This will match all\n\t * sub builders and will calculate the version.\n\t * \n\t * @return a Jar or null\n\t */\n\tpublic Jar getBaselineJar() throws Exception {\n\t\tString bl = getProperty(Constants.BASELINE);\n\t\tif (bl == null || Constants.NONE.equals(bl))\n\t\t\treturn null;\n\n\t\tInstructions baselines = new Instructions(getProperty(Constants.BASELINE));\n\t\tif (baselines.isEmpty())\n\t\t\treturn null; // no baselining\n\n\t\tRepositoryPlugin repo = getBaselineRepo();\n\t\tif (repo == null)\n\t\t\treturn null; // errors reported already\n\n\t\tString bsn = getBsn();\n\t\tVersion version = new Version(getVersion());\n\t\tSortedSet versions = removeStagedAndFilter(repo.versions(bsn), repo, bsn);\n\n\t\tif (versions.isEmpty()) {\n\t\t\t// We have a repo\n\t\t\tVersion v = Version.parseVersion(getVersion()).getWithoutQualifier();\n\t\t\tif (v.compareTo(Version.ONE) > 0) {\n\t\t\t\twarning(\"There is no baseline for %s in the baseline repo %s. The build is for version %s, which is higher than 1.0.0 which suggests that there should be a prior version.\",\n\t\t\t\t\t\tgetBsn(), repo, v);\n\t\t\t}\n\t\t\treturn null;\n\t\t}\n\n\t\t//\n\t\t// Loop over the instructions, first match commits.\n\t\t//\n\n\t\tfor (Entry e : baselines.entrySet()) {\n\t\t\tif (e.getKey().matches(bsn)) {\n\t\t\t\tAttrs attrs = e.getValue();\n\t\t\t\tVersion target;\n\n\t\t\t\tif (attrs.containsKey(\"version\")) {\n\n\t\t\t\t\t// Specified version!\n\n\t\t\t\t\tString v = attrs.get(\"version\");\n\t\t\t\t\tif (!Verifier.isVersion(v)) {\n\t\t\t\t\t\terror(\"Not a valid version in %s %s\", Constants.BASELINE, v);\n\t\t\t\t\t\treturn null;\n\t\t\t\t\t}\n\n\t\t\t\t\tVersion base = new Version(v);\n\t\t\t\t\tSortedSet later = versions.tailSet(base);\n\t\t\t\t\tif (later.isEmpty()) {\n\t\t\t\t\t\terror(\"For baselineing %s-%s, specified version %s not found\", bsn, version, base);\n\t\t\t\t\t\treturn null;\n\t\t\t\t\t}\n\n\t\t\t\t\t// First element is equal or next to the base we desire\n\n\t\t\t\t\ttarget = later.first();\n\n\t\t\t\t\t// Now, we could end up with a higher version than our\n\t\t\t\t\t// current\n\t\t\t\t\t// project\n\n\t\t\t\t} else if (attrs.containsKey(\"file\")) {\n\n\t\t\t\t\t// Can be useful to specify a file\n\t\t\t\t\t// for example when copying a bundle with a public api\n\n\t\t\t\t\tFile f = getProject().getFile(attrs.get(\"file\"));\n\t\t\t\t\tif (f != null && f.isFile()) {\n\t\t\t\t\t\tJar jar = new Jar(f);\n\t\t\t\t\t\taddClose(jar);\n\t\t\t\t\t\treturn jar;\n\t\t\t\t\t}\n\t\t\t\t\terror(\"Specified file for baseline but could not find it %s\", f);\n\t\t\t\t\treturn null;\n\t\t\t\t} else {\n\t\t\t\t\ttarget = versions.last();\n\t\t\t\t}\n\n\t\t\t\t// Fetch the revision\n\n\t\t\t\tif (target.getWithoutQualifier().compareTo(version.getWithoutQualifier()) > 0) {\n\t\t\t\t\terror(\"The baseline version %s is higher than the current version %s for %s in %s\", target, version,\n\t\t\t\t\t\t\tbsn, repo);", "answers": ["\t\t\t\t\treturn null;"], "length": 1175, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "652d4e14-d774-43b8-90bb-c090352ac430", "reasoning": "The code is inside getBaselineJar(). After checking that the selected baseline version is higher than the current project version, it logs an error. The logical next step is to abort the operation by returning null, before the method proceeds to fetch the baseline jar. Therefore the next line should be a return statement returning null.", "reasoning_model_answer": "return null;", "assistant_with_reasoning": "\nThe code is inside getBaselineJar(). After checking that the selected baseline version is higher than the current project version, it logs an error. The logical next step is to abort the operation by returning null, before the method proceeds to fetch the baseline jar. Therefore the next line should be a return statement returning null.\n\nreturn null;", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 5.721, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 10928, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "return null;", "score": 0.83, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "// CodeContracts\n// \n// Copyright (c) Microsoft Corporation\n// \n// All rights reserved. \n// \n// MIT License\n// \n// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n// \n// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n// \n// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Data;\nusing System.Windows.Documents;\nusing System.Windows.Input;\nusing System.Windows.Media;\nusing System.Windows.Media.Imaging;\nusing System.Windows.Shapes;\nusing Microsoft.VisualStudio.PlatformUI;\nusing Microsoft.Research.CodeAnalysis;\nusing System.Diagnostics.Contracts;\nusing System.Diagnostics;\nusing Microsoft.VisualStudio.OLE.Interop;\nusing Microsoft.VisualStudio.PlatformUI.OleComponentSupport;\nusing System.Runtime.InteropServices;\nusing Microsoft.VisualStudio.Shell;\nusing Microsoft.VisualStudio.Text.Editor;\nusing Microsoft.VisualStudio.Shell.Interop;\n//using RoslynToCCICodeModel;\n\nnamespace Microsoft.Research.AskCodeContracts\n{\n ///

    \n /// Interaction logic for IsTrue.xaml\n /// \n public partial class IsTrue : Window, IOleComponent\n {\n public bool IsValid { private set; get; }\n public string Assertion { private set; get; }\n\n private readonly Func, ProofOutcome?> WorkerForQuery;\n private readonly Func WorkerForInvariantQuery;\n private readonly Func> WorkerForSearchCallersMatchingPredicate;\n\n private readonly IWpfTextView wpfTextView;\n\n public IsTrue(IWpfTextView wpfTextView, \n Func, ProofOutcome?> WorkerForQuery, \n Func WorkerForInvariantQuery,\n Func> WorkerForSearchCallersMatchingPredicate,\n string lastQuery = null)\n {\n Contract.Requires(WorkerForQuery != null);\n Contract.Requires(WorkerForInvariantQuery != null);\n Contract.Requires(WorkerForSearchCallersMatchingPredicate != null);\n\n InitializeComponent();\n\n this.wpfTextView = wpfTextView;\n this.WorkerForQuery = WorkerForQuery;\n this.WorkerForInvariantQuery = WorkerForInvariantQuery;\n this.WorkerForSearchCallersMatchingPredicate = WorkerForSearchCallersMatchingPredicate;\n this.Assertion = lastQuery;\n this.IsValid = false;\n }\n\n #region Click handling\n\n private void AddAssumption_Click(object sender, RoutedEventArgs e)\n {\n var assumption = this.Assumption.Text;\n if (!string.IsNullOrWhiteSpace(assumption))\n {\n var selectionStart = this.wpfTextView.Selection.Start.Position.Position;\n var selectionEnd = this.wpfTextView.Selection.End.Position.Position;\n\n if(selectionStart == selectionEnd)\n {\n var line = this.wpfTextView.Selection.Start.Position.GetContainingLine().LineNumber + 1;\n\n Trace.WriteLine(string.Format(\"Adding assumption {0} @ line {1}, position {2}\", assumption, line, selectionStart));\n\n this.Assumptions.Items.Add(new CodeAssumption(selectionStart, line, assumption));\n this.Assumption.Text = String.Empty; // swallow the assumption\n }\n }\n }\n\n private void ClearAssumptions_Click(object sender, RoutedEventArgs e)\n {\n this.Assumptions.Items.Clear();\n }\n\n private void IsTrueButton_Click(object sender, RoutedEventArgs e)\n {\n this.IsValid = true;\n this.Assertion = this.InputQuery.Text;\n this.AnswerText.Text = \"Thinking...\";\n\n this.UpdateLineInTextMessages();\n\n if (!String.IsNullOrEmpty(this.Assertion))\n {\n var result = this.WorkerForQuery(this.Assertion, this.Assumptions.Items.AsEnumerable());\n if (result.HasValue)\n {\n string text = null;\n switch (result.Value)\n {\n case ProofOutcome.Bottom:\n text = \"No execution reaches this point\";\n break;\n\n case ProofOutcome.False:\n text = \"No, it is false\";\n break;\n\n case ProofOutcome.Top:\n text = \"It may sometimes be true, it may sometimes be false\";\n break;\n\n case ProofOutcome.True:\n text = \"Yes, it is true\";\n break;\n }\n\n this.AnswerText.Text = text;\n }\n else\n {\n this.AnswerText.Text = \"Something went wrong\";\n }\n }\n else\n {\n this.AnswerText.Text = String.Empty;\n }\n }\n\n private void GetInvariantButton_Click(object sender, RoutedEventArgs e)\n {\n this.InvariantText.Text = \"Thinking...\";\n this.UpdateLineInTextMessages();\n\n var result = this.WorkerForInvariantQuery();\n\n if (result != null)\n {\n this.InvariantText.Text = result;\n }\n\n }\n\n private void requiresSearchBox_Click(object sender, RoutedEventArgs e)\n {\n Trace.WriteLine(\"Handling the find box\");\n\n // var myOutputWindow = VSIntegrationUtilities.OutputWindowManager.CreatePane(GuidList.guidClousotOutputPane, \"Clousot find window\");\n\n // Clear the previous search\n this.searchResultsFalseListBox.Items.Clear();\n this.searchResultsTopListBox.Items.Clear();\n this.searchResultsTrueListBox.Items.Clear();\n\n var query = this.requiresSearchConditionTextBox.Text;\n foreach (var r in this.WorkerForSearchCallersMatchingPredicate(query))\n {\n switch (r.Outcome)\n {\n case ProofOutcome.Bottom:\n // do nothing; \n break;\n\n case ProofOutcome.False:\n this.searchResultsFalseListBox.Items.Add(r);\n break;\n\n case ProofOutcome.Top:\n this.searchResultsTopListBox.Items.Add(r);\n break;\n\n case ProofOutcome.True:\n this.searchResultsTrueListBox.Items.Add(r);\n break;\n\n default:\n // impossible;\n Contract.Assume(false);\n break;\n \n }\n }\n }\n\n #endregion\n\n #region Events\n\n protected override void OnKeyDown(KeyEventArgs e)\n {\n base.OnKeyDown(e);\n\n if (e.Key == Key.Delete)\n {\n Trace.WriteLine(\"Hit Delete key\");\n\n if (this.Assumptions.IsKeyboardFocusWithin)\n {\n var selected = this.Assumptions.SelectedIndex;\n if (selected >= 0)\n {\n Trace.WriteLine(string.Format(\"Removing the assumption at position {0}\", selected));\n\n this.Assumptions.Items.RemoveAt(selected);\n }\n }\n }\n\n this.UpdateLineInTextMessages();\n }\n\n #endregion\n\n\n #region Private\n\n private void UpdateLineInTextMessages()\n {\n var currLine = this.wpfTextView.Selection.Start.Position.GetContainingLine().LineNumber + 1;\n\n this.QueryText.Text = string.Format(\"Query @line {0} :\", currLine);\n this.InvariantTextLabel.Text = string.Format(\"State @line {0} :\", currLine);\n }\n\n #endregion\n\n\n #region Logic to make sure we do not lose arrows, backspace, etc.\n protected override void OnGotKeyboardFocus(KeyboardFocusChangedEventArgs e)\n {\n base.OnGotKeyboardFocus(e);\n\n Trace.WriteLine(\"Get keyboard focus\");\n\n AdjustShellTracking();\n e.Handled = true;\n }\n\n protected override void OnLostKeyboardFocus(KeyboardFocusChangedEventArgs e)\n {\n base.OnLostKeyboardFocus(e);\n\n AdjustShellTracking();\n Trace.WriteLine(\"Lost keyboard focus\");\n\n }\n\n\n public void AdjustShellTracking()\n { // See if our keyboard focus is within our self \n if (IsKeyboardFocusWithin)\n {\n // Then see if we should be tracking (only track on text boxes)\n if (Keyboard.FocusedElement is DependencyObject)\n {\n var obj = Keyboard.FocusedElement as DependencyObject;\n\n if (obj != null /*&& obj.FindParentOfType() != null*/)\n {\n IsShellTrackingMe = true;\n }\n else\n {\n IsShellTrackingMe = false;\n }\n }\n else\n {\n IsShellTrackingMe = false;\n }\n }\n else\n {\n IsShellTrackingMe = false;\n }\n\n // Update our indicators that we are active. Our border and the caret will change if\n // we are tracking\n if (this.wpfTextView != null && this.wpfTextView.Caret != null)\n this.wpfTextView.Caret.IsHidden = IsShellTrackingMe;\n\n // If we have the keyboard focus, but we are not shell tracking, make sure\n // to set the keyboard focus back to the text editor. Otherwise\n // it looks like nobody has the focus\n if (this.wpfTextView != null && IsKeyboardFocusWithin && !IsShellTrackingMe)\n Keyboard.Focus(this.wpfTextView.VisualElement);\n }\n\n /// \n /// Indicates if this tip is the IOleComponent that is being tracked by the shell. This is necessary\n /// to ensure that keyboard input is sent entirely to the WPF window. Otherwise the PreTranslateMessage of \n /// the shell will send it to other windows. (Like backspace going to the editor window)\n /// \n public bool IsShellTrackingMe\n {\n get\n {\n return _isTracking;\n }\n set\n {\n if (_isTracking != value)\n {\n if (value)\n {\n // Register ourselves as a tracking component so we\n // get first crack at backspace/up/down/left/right/CTRL+A/CTRL+C\n\n // Sometimes this might not work because somebody else is already\n // the tracking target. \n _isTracking = VSIntegrationUtilities.OLE.StartTrackingComponent(this);\n }\n else\n {\n // Unregister ourselves as a command target\n VSIntegrationUtilities.OLE.StopTrackingComponent(this);\n\n // This always succeeds. Can't not unregister\n _isTracking = false;\n }\n }\n }\n }\n\n private bool _isTracking;\n\n #region implementation of IOleComponent\n\n public int FContinueMessageLoop(uint uReason, IntPtr pvLoopData, MSG[] pMsgPeeked)\n {\n // If we have keyboard focus, then allow more messages to be pumped\n if (IsKeyboardFocusWithin)\n return 1;\n\n return 0;\n }\n\n public int FDoIdle(uint grfidlef)\n {\n return 0;\n }\n\n public int FPreTranslateMessage(MSG[] pMsg)\n {\n // If we handle it, then tell the shell that (1 means we handled it)\n return VSIntegrationUtilities.OLE.HandleComponentMessage(pMsg[0]) ? 1 : 0;\n }\n\n public int FQueryTerminate(int fPromptUser)\n {\n return 1;\n }\n\n public int FReserved1(uint dwReserved, uint message, IntPtr wParam, IntPtr lParam)\n {\n return 0;\n }\n\n public IntPtr HwndGetWindow(uint dwWhich, uint dwReserved)\n {\n // F: LOOK AT THAT\n return IntPtr.Zero;\n\n }\n\n public void OnActivationChange(IOleComponent pic, int fSameComponent, OLECRINFO[] pcrinfo, int fHostIsActivating, OLECHOSTINFO[] pchostinfo, uint dwReserved)\n {\n }\n\n public void OnAppActivate(int fActive, uint dwOtherThreadID)\n {\n }\n\n public void OnEnterState(uint uStateID, int fEnter)\n {\n }\n\n public void OnLoseActivation()\n {\n }\n\n public void Terminate()\n {\n }\n\n #endregion\n\n #endregion\n }\n\n public static class Extensions\n {\n public static IEnumerable AsEnumerable(this ItemCollection collection)\n {\n if (collection != null)\n {\n foreach (var item in collection)\n {\n var assumption = item as CodeAssumption;\n if (assumption != null)\n {\n yield return assumption;\n }\n }\n }\n }\n }\n}\n\nnamespace VSIntegrationUtilities\n{\n public static class OutputWindowManager\n {\n /// \n /// Create an output window\n /// \n static public IVsOutputWindowPane CreatePane(Guid guid, string title, bool visible = true, bool clearWithSolution = true)\n {\n var outputWindow = ServiceProvider.GlobalProvider.GetService(typeof(SVsOutputWindow)) as IVsOutputWindow;\n if (outputWindow != null)\n {\n IVsOutputWindowPane result;\n outputWindow.CreatePane(ref guid, title, Convert.ToInt32(visible), Convert.ToInt32(clearWithSolution));", "answers": [" outputWindow.GetPane(ref guid, out result);"], "length": 1236, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "db568bbe-8784-4c8d-a4a3-f75c03b51b78", "reasoning": "The method is creating an output pane. After calling CreatePane on the IVsOutputWindow, the usual next step is to retrieve the pane with GetPane and store it in the 'result' variable before returning it. Therefore the next line should call GetPane with the same guid and output the pane into 'result'.", "reasoning_model_answer": "outputWindow.GetPane(ref guid, out result);", "assistant_with_reasoning": "\nThe method is creating an output pane. After calling CreatePane on the IVsOutputWindow, the usual next step is to retrieve the pane with GetPane and store it in the 'result' variable before returning it. Therefore the next line should call GetPane with the same guid and output the pane into 'result'.\n\noutputWindow.GetPane(ref guid, out result);", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.519, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 13341, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "outputWindow.GetPane(ref guid, out result);", "score": 0.91, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.ComponentModel;\nusing System.Drawing;\nusing System.Runtime.Serialization.Formatters.Binary;\nusing System.Windows.Forms;\n\nusing Log2Console.Log;\nusing Log2Console.Receiver;\n\n\nnamespace Log2Console.Settings\n{\n \n\n [Serializable]\n public sealed class UserSettings\n {\n internal static readonly Color DefaultTraceLevelColor = Color.Gray;\n internal static readonly Color DefaultDebugLevelColor = Color.Black;\n internal static readonly Color DefaultInfoLevelColor = Color.Green;\n internal static readonly Color DefaultWarnLevelColor = Color.Orange;\n internal static readonly Color DefaultErrorLevelColor = Color.Red;\n internal static readonly Color DefaultFatalLevelColor = Color.Purple;\n\n private static readonly FieldType[] DefaultColumnConfiguration =\n {\n new FieldType(LogMessageField.TimeStamp, \"Time\"),\n new FieldType(LogMessageField.Level, \"Level\"),\n new FieldType(LogMessageField.RootLoggerName, \"RootLoggerName\"),\n new FieldType(LogMessageField.ThreadName, \"Thread\"),\n new FieldType(LogMessageField.Message, \"Message\"),\n };\n\n private static readonly FieldType[] DefaultDetailsMessageConfiguration =\n {\n new FieldType(LogMessageField.TimeStamp, \"Time\"),\n new FieldType(LogMessageField.Level, \"Level\"),\n new FieldType(LogMessageField.RootLoggerName, \"RootLoggerName\"),\n new FieldType(LogMessageField.ThreadName, \"Thread\"),\n new FieldType(LogMessageField.Message, \"Message\"),\n };\n\n private static readonly FieldType[] DefaultCsvColumnHeaderConfiguration =\n {\n new FieldType(LogMessageField.SequenceNr, \"sequence\"),\n new FieldType(LogMessageField.TimeStamp, \"time\"),\n new FieldType(LogMessageField.Level, \"level\"),\n new FieldType(LogMessageField.ThreadName, \"thread\"),\n new FieldType(LogMessageField.CallSiteClass, \"class\"),\n new FieldType(LogMessageField.CallSiteMethod, \"method\"),\n new FieldType(LogMessageField.Message, \"message\"),\n new FieldType(LogMessageField.Exception, \"exception\"),\n new FieldType(LogMessageField.SourceFileName, \"file\")\n };\n\n [NonSerialized]\n private const string SettingsFileName = \"UserSettings.dat\";\n\n [NonSerialized]\n private Dictionary _columnProperties = new Dictionary();\n\n [NonSerialized] \n private Dictionary _csvHeaderFieldTypes;\n\n [NonSerialized] \n private Dictionary _sourceCodeLocationMap;\n\n private static UserSettings _instance;\n\n private bool _recursivlyEnableLoggers = true;\n private bool _hideTaskbarIcon = false;\n private bool _notifyNewLogWhenHidden = true;\n private bool _alwaysOnTop = false;\n private uint _transparency = 100;\n private bool _highlightLogger = true;\n private bool _highlightLogMessages = true;\n private FieldType[] _columnConfiguration;\n private FieldType[] _messageDetailConfiguration;\n\n\n private FieldType[] _csvColumnHeaderFields;\n private SourceFileLocation[] _sourceLocationMapConfiguration;\n private bool _autoScrollToLastLog = true;\n private bool _groupLogMessages = false;\n private int _messageCycleCount = 0;\n private string _timeStampFormatString = \"yyyy-MM-dd HH:mm:ss.ffff\";\n\n private Font _defaultFont = null;\n private Font _logListFont = null;\n private Font _logDetailFont = null;\n private Font _loggerTreeFont = null;\n\n private Color _logListBackColor = Color.Empty;\n private Color _logMessageBackColor = Color.Empty;\n\n private Color _traceLevelColor = DefaultTraceLevelColor;\n private Color _debugLevelColor = DefaultDebugLevelColor;\n private Color _infoLevelColor = DefaultInfoLevelColor;\n private Color _warnLevelColor = DefaultWarnLevelColor;\n private Color _errorLevelColor = DefaultErrorLevelColor;\n private Color _fatalLevelColor = DefaultFatalLevelColor;\n\n private bool _msgDetailsProperties = false;\n private bool _msgDetailsException = true;\n\n private LogLevelInfo _logLevelInfo;\n private List _receivers = new List();\n private LayoutSettings _layout = new LayoutSettings();\n\n\n private UserSettings()\n {\n // Set default values\n _logLevelInfo = LogLevels.Instance[(int)LogLevel.Trace];\n }\n\n /// \n /// Creates and returns an exact copy of the settings.\n /// \n /// \n public UserSettings Clone()\n {\n // We're going to serialize and deserialize to make the copy. That\n // way if we add new properties and/or settings, we don't have to \n // maintain a copy constructor.\n BinaryFormatter formatter = new BinaryFormatter();\n\n using (MemoryStream ms = new MemoryStream())\n {\n // Serialize the object.\n formatter.Serialize(ms, this);\n\n // Reset the stream and deserialize it.\n ms.Position = 0;\n\n return formatter.Deserialize(ms) as UserSettings;\n }\n }\n\n public static UserSettings Instance\n {\n get { return _instance; }\n set { _instance = value; }\n }\n\n public static bool Load()\n {\n bool ok = false;\n\n _instance = new UserSettings();\n\n string settingsFilePath = GetSettingsFilePath();\n if (!File.Exists(settingsFilePath))\n return ok;\n\n try\n {\n using (FileStream fs = new FileStream(settingsFilePath, FileMode.Open))\n {\n if (fs.Length > 0)\n {\n BinaryFormatter bf = new BinaryFormatter();\n _instance = bf.Deserialize(fs) as UserSettings;\n\n // During 1st load, some members are set to null\n if (_instance != null)\n {\n if (_instance._receivers == null)\n _instance._receivers = new List();\n\n if (_instance._layout == null)\n _instance._layout = new LayoutSettings();\n }\n\n ok = true;\n }\n }\n }\n catch (Exception)\n {\n // The settings file might be corrupted or from too different version, delete it...\n try\n {\n File.Delete(settingsFilePath);\n }\n catch\n {\n ok = false;\n }\n }\n\n return ok;\n }\n\n private static string GetSettingsFilePath()\n {\n string userDir = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);\n \n DirectoryInfo di = new DirectoryInfo(userDir);\n di = di.CreateSubdirectory(\"Log2Console\");\n\n return di.FullName + Path.DirectorySeparatorChar + SettingsFileName;\n }\n\n public void Save()\n {\n string settingsFilePath = GetSettingsFilePath();\n\n using (FileStream fs = new FileStream(settingsFilePath, FileMode.Create))\n {\n BinaryFormatter bf = new BinaryFormatter();\n bf.Serialize(fs, this);\n }\n }\n\n public void Close()\n {\n foreach (IReceiver receiver in _receivers)\n {\n receiver.Detach();\n receiver.Terminate();\n }\n _receivers.Clear();\n } \n\n [Category(\"Appearance\")]\n [Description(\"Hides the taskbar icon, only the tray icon will remain visible.\")]\n [DisplayName(\"Hide Taskbar Icon\")]\n public bool HideTaskbarIcon\n {\n get { return _hideTaskbarIcon; }\n set { _hideTaskbarIcon = value; }\n }\n\n [Category(\"Appearance\")]\n [Description(\"The Log2Console window will remain on top of all other windows.\")]\n [DisplayName(\"Always On Top\")]\n public bool AlwaysOnTop\n {\n get { return _alwaysOnTop; }\n set { _alwaysOnTop = value; }\n }\n\n [Category(\"Appearance\")]\n [Description(\"Select a transparency factor for the main window.\")]\n public uint Transparency\n {\n get { return _transparency; }\n set { _transparency = Math.Max(10, Math.Min(100, value)); }\n }\n\n [Category(\"Appearance\")]\n [Description(\"Highlight the Logger of the selected Log Message.\")]\n [DisplayName(\"Highlight Logger\")]\n public bool HighlightLogger\n {\n get { return _highlightLogger; }\n set { _highlightLogger = value; }\n }\n\n [Category(\"Appearance\")]\n [Description(\"Highlight the Log Messages of the selected Logger.\")]\n [DisplayName(\"Highlight Log Messages\")]\n public bool HighlightLogMessages\n {\n get { return _highlightLogMessages; }\n set { _highlightLogMessages = value; }\n } \n\n [Category(\"Columns\")]\n [DisplayName(\"Column Settings\")]\n [Description(\"Configure which Columns to Display\")] \n public FieldType[] ColumnConfiguration\n {\n get { return _columnConfiguration ?? (ColumnConfiguration = DefaultColumnConfiguration); }\n set\n {\n _columnConfiguration = value;\n UpdateColumnPropeties();\n }\n }\n\n\n [Category(\"Columns\")]\n [DisplayName(\"CSV File Header Column Settings\")]\n [Description(\"Configures which columns maps to which fields when auto detecting the CSV structure based on the header\")] \n public FieldType[] CsvHeaderColumns\n {\n get { return _csvColumnHeaderFields ?? (CsvHeaderColumns = DefaultCsvColumnHeaderConfiguration); }\n set\n {\n _csvColumnHeaderFields = value;\n UpdateCsvColumnHeader();\n }\n }\n\n [Category(\"Source File Configuration\")]\n [DisplayName(\"Source Location\")]\n [Description(\"Map the Log File Location to the Local Source Code Location\")]\n public SourceFileLocation[] SourceLocationMapConfiguration\n {\n get { return _sourceLocationMapConfiguration; }\n set\n {\n _sourceLocationMapConfiguration = value;\n UpdateSourceCodeLocationMap();\n }\n }\n\n\n [Category(\"Notification\")]\n [Description(\"A balloon tip will be displayed when a new log message arrives and the window is hidden.\")]\n [DisplayName(\"Notify New Log When Hidden\")]\n public bool NotifyNewLogWhenHidden\n {\n get { return _notifyNewLogWhenHidden; }\n set { _notifyNewLogWhenHidden = value; }\n }\n\n [Category(\"Notification\")]\n [Description(\"Automatically scroll to the last log message.\")]\n [DisplayName(\"Auto Scroll to Last Log\")]\n public bool AutoScrollToLastLog\n {\n get { return _autoScrollToLastLog; }\n set { _autoScrollToLastLog = value; }\n }\n\n\n [Category(\"Logging\")]\n [Description(\"Groups the log messages based on the Logger Name.\")]\n [DisplayName(\"Group Log Messages by Loggers\")]\n public bool GroupLogMessages\n {\n get { return _groupLogMessages; }\n set { _groupLogMessages = value; }\n }\n\n [Category(\"Logging\")]\n [Description(\"When greater than 0, the log messages are limited to that number.\")]\n [DisplayName(\"Message Cycle Count\")]\n public int MessageCycleCount\n {\n get { return _messageCycleCount; }\n set { _messageCycleCount = value; }\n }\n\n [Category(\"Logging\")]\n [Description(\"Defines the format to be used to display the log message timestamps (cf. DateTime.ToString(format) in the .NET Framework.\")]\n [DisplayName(\"TimeStamp Format String\")]\n public string TimeStampFormatString\n {\n get { return _timeStampFormatString; }\n set\n {\n // Check validity\n try\n {\n string str= DateTime.Now.ToString(value); // If error, will throw FormatException\n _timeStampFormatString = value;\n }\n catch (FormatException ex)\n {\n MessageBox.Show(Form.ActiveForm, ex.Message, Form.ActiveForm.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);\n _timeStampFormatString = \"G\"; // Back to default\n }\n }\n }\n\n [Category(\"Logging\")]\n [Description(\"When a logger is enabled or disabled, do the same for all child loggers.\")]\n [DisplayName(\"Recursively Enable Loggers\")]\n public bool RecursivlyEnableLoggers\n {\n get { return _recursivlyEnableLoggers; }\n set { _recursivlyEnableLoggers = value; }\n }\n\n [Category(\"Message Details\")]\n [DisplayName(\"Details information\")]\n [Description(\"Configure which information to Display in the message details\")]\n public FieldType[] MessageDetailConfiguration\n {\n get { return _messageDetailConfiguration ?? (MessageDetailConfiguration = DefaultDetailsMessageConfiguration); }\n set\n {\n _messageDetailConfiguration = value;\n }\n }\n\n [Category(\"Message Details\")]\n [Description(\"Show or hide the message properties in the message details panel.\")]\n [DisplayName(\"Show Properties\")]\n public bool ShowMsgDetailsProperties\n {\n get { return _msgDetailsProperties; }\n set { _msgDetailsProperties = value; }\n }\n\n [Category(\"Message Details\")]\n [Description(\"Show or hide the exception in the message details panel.\")]\n [DisplayName(\"Show Exception\")]\n public bool ShowMsgDetailsException\n {\n get { return _msgDetailsException; }\n set { _msgDetailsException = value; }\n }\n\n [Category(\"Fonts\")]\n [Description(\"Set the default Font.\")]\n [DisplayName(\"Default Font\")]\n public Font DefaultFont\n {", "answers": [" get { return _defaultFont; }"], "length": 1219, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "4918034d-91b0-4c22-84d9-50b341673175", "reasoning": "The code is defining a property for the default font. After the opening brace of the property, the next line should be the getter that returns the backing field _defaultFont, matching the style of other properties.", "reasoning_model_answer": "get { return _defaultFont; }", "assistant_with_reasoning": "\nThe code is defining a property for the default font. After the opening brace of the property, the next line should be the getter that returns the backing field _defaultFont, matching the style of other properties.\n\nget { return _defaultFont; }", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 5.563, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 15012, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "get { return _defaultFont; }", "score": 0.85, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "using Intellisense.Common;\nusing Microsoft.CodeAnalysis;\nusing Microsoft.CodeAnalysis.CSharp;\nusing Microsoft.CodeAnalysis.CSharp.Syntax;\nusing System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\nusing System.Text;\nusing System.Xml;\nusing VB = Microsoft.CodeAnalysis.VisualBasic;\n\nnamespace RoslynIntellisense\n{\n public static class RoslynExtensions\n {\n public static string ToKindDisplayName(this TypeDeclarationSyntax type)\n {\n var kind = type.Kind();\n return kind == SyntaxKind.ClassDeclaration ? \"class\" :\n kind == SyntaxKind.StructDeclaration ? \"struct\" :\n kind == SyntaxKind.EnumDeclaration ? \"enum\" :\n kind == SyntaxKind.InterfaceDeclaration ? \"interface\" :\n \"\";\n }\n\n public static CompletionType ToCompletionType(this SymbolKind kind)\n {\n switch (kind)\n {\n case SymbolKind.Method: return CompletionType.method;\n case SymbolKind.Event: return CompletionType._event;\n case SymbolKind.Field: return CompletionType.field;\n case SymbolKind.Property: return CompletionType.property;\n case SymbolKind.NamedType: return CompletionType.type;\n case SymbolKind.Namespace: return CompletionType._namespace;\n case SymbolKind.Assembly: return CompletionType._namespace;\n default:\n return CompletionType.unresolved;\n }\n }\n\n public static string ResolveSymbolToTypeName(this ArgumentSyntax arg, Document doc)\n {\n string arg_text = arg.ToString();\n\n if (arg_text.IsString()) return \"string\";\n else if (arg_text.IsChar()) return \"char\";\n else if (arg_text.IsChar()) return \"char\";\n else if (arg_text.IsFloat()) return \"float\";\n else if (arg_text.IsDecimal()) return \"decimal\";\n else if (arg_text.IsDouble()) return \"double\";\n else if (arg_text.IsByte()) return \"byte\";\n else if (arg_text.IsLong()) return \"long\";\n else if (arg_text.IsSbyte()) return \"sbyte\";\n else if (arg_text.IsShort()) return \"short\";\n else if (arg_text.IsUlong()) return \"ulong\";\n else if (arg_text.IsInt()) return \"int\";\n else if (arg_text.IsBool()) return \"bool\";\n\n // if (arg_text.All(c => char.Is c.IsN \"'\") && arg_text.EndsWith(\"\\'\"))\n // {\n // return \"char\";\n // }\n // var pos = arg.FullSpan.End - 1;\n // var arg_type = SymbolFinder.FindSymbolAtPositionAsync(doc, pos).Result;\n return \"\";\n }\n\n public static string ToDecoratedName(this ITypeSymbol type)\n {\n string result = type.ToDisplayString();\n\n if (!result.Contains('.'))\n return result;\n //if (clrAliaces.ContainsKey(result))\n // return clrAliaces[result];\n\n string nmspace = type.GetNamespace();\n if (!string.IsNullOrEmpty(nmspace))\n nmspace = \"{\" + nmspace + \"}.\";\n return (nmspace + type.Name);\n }\n\n public static string Reconstruct(this ISymbol symbol, bool includeDoc = true)\n {\n int pos;\n return symbol.Reconstruct(out pos, includeDoc);\n }\n\n public static DomRegion ToDomRegion(this Microsoft.CodeAnalysis.Location location)\n {\n //DomRegion is 1-based Editor friendly struct\n\n var linePosition = location.GetLineSpan().StartLinePosition;\n\n return new DomRegion\n {\n FileName = location.SourceTree.FilePath,\n BeginLine = linePosition.Line + 1,\n EndLine = linePosition.Line + 1,\n BeginColumn = linePosition.Character + 1,\n };\n }\n\n public static string Reconstruct(this ISymbol symbol, out int startPosition, bool includeDoc = true, string header = \"\")\n {\n var code = new StringBuilder();\n code.Append(header);\n startPosition = -1;\n\n int indent = 0;\n\n INamedTypeSymbol rootType = symbol.GetRootType(); //itself if it is a type or containing type if a member\n\n var usedNamespaces = rootType.UsedNamespaces();\n if (usedNamespaces.HasAny())\n {\n code.AppendLine(usedNamespaces.Select(x => $\"using {x};\").JoinBy(Environment.NewLine));\n code.AppendLine();\n }\n\n string nmsp = rootType.GetNamespace();\n if (nmsp.HasAny())\n {\n code.AppendLine((\"namespace \" + nmsp).IndentBy(indent));\n code.AppendLine(\"{\".IndentBy(indent++));\n }\n\n var parentClasses = rootType.GetParentClasses();\n foreach (var parent in parentClasses) //nested classes support\n code.AppendLine($\"public {parent.TypeKind.ToString().ToLower()} \".IndentBy(indent) + parent.Name)\n .AppendLine(\"{\".IndentBy(indent++));\n\n startPosition = code.Length;\n var type = rootType.ToReflectedCode(includeDoc);\n type = type.IndentLinesBy(indent);\n code.AppendLine(type);\n\n //\\r\\n\n startPosition += type.LastLineStart();\n\n if (!rootType.IsDelegate())\n {\n code.AppendLine(\"{\".IndentBy(indent++));\n\n string currentGroup = null;\n\n var members = rootType.GetMembers()\n .OrderBy(x => x.GetDisplayGroup())\n .ThenByDescending(x => x.DeclaredAccessibility)\n .ThenBy(x => rootType.IsEnum() ? \"\" : x.Name);\n\n foreach (var item in members)\n {\n string memberInfo = item.ToReflectedCode(includeDoc, usePartials: true);\n\n if (memberInfo.HasAny())\n {\n if (currentGroup != null && item.GetDisplayGroup() != currentGroup)\n code.AppendLine();\n currentGroup = item.GetDisplayGroup();\n\n var info = memberInfo.IndentLinesBy(indent);\n\n if (symbol == item || (symbol is IMethodSymbol && (symbol as IMethodSymbol).ReducedFrom == item))\n startPosition = code.Length + info.LastLineStart();\n\n code.AppendLine(info);\n }\n }\n\n code.AppendLine(\"}\".IndentBy(--indent));\n }\n\n foreach (var item in parentClasses)\n code.AppendLine(\"}\".IndentBy(--indent));\n\n if (nmsp.HasAny()) code.AppendLine(\"}\".IndentBy(--indent));\n\n return code.ToString().Trim();\n }\n\n public static string IndentLinesBy(this string text, int indentLevel, string linePreffix = \"\")\n {\n return string.Join(Environment.NewLine, text.Replace(\"\\r\", \"\")\n .Split('\\n')\n .Select(x => x.IndentBy(indentLevel, linePreffix))\n .ToArray());\n }\n\n public static string IndentBy(this string text, int indentLevel, string linePreffix = \"\")\n {\n var indent = new string(' ', indentLevel * 4);\n return indent + linePreffix + text;\n }\n\n public static string GetDocumentationComment(this ISymbol symbol, bool ignoreExceptionsInfo = false)\n {\n string xmlDoc = symbol.GetDocumentationCommentXml();\n var sections = new List();\n\n var builder = new StringBuilder();\n try\n {\n using (XmlTextReader reader = new XmlTextReader(new StringReader(\"\" + xmlDoc + \"\")))\n {\n string lastElementName = null;\n bool exceptionsStarted = false;\n reader.XmlResolver = null;\n while (reader.Read())\n {\n var nodeType = reader.NodeType;\n switch (nodeType)\n {\n case XmlNodeType.Text:\n if (lastElementName == \"summary\")\n {\n builder.Insert(0, reader.Value.Shrink());\n }\n else\n {\n if (exceptionsStarted)\n builder.Append(\" \");\n\n if (lastElementName == \"code\")\n builder.Append(reader.Value); //need to preserve all formatting (line breaks and indents)\n else\n {\n //if (reflectionDocument)\n // b.Append(reader.Value.NormalizeLines()); //need to preserve line breaks but not indents\n //else\n builder.Append(reader.Value.Shrink());\n }\n }\n break;\n\n case XmlNodeType.Element:\n {\n bool silentElement = false;\n\n switch (reader.Name)\n {\n case \"filterpriority\":\n reader.Skip();\n break;\n\n case \"root\":\n case \"summary\":\n case \"c\":\n silentElement = true;\n break;\n\n case \"paramref\":\n silentElement = true;\n builder.Append(reader.GetAttribute(\"name\"));\n break;\n\n case \"param\":\n silentElement = true;\n builder.AppendLine();\n builder.Append(reader.GetAttribute(\"name\") + \": \");\n break;\n\n case \"para\":\n silentElement = true;\n builder.AppendLine();\n break;\n\n case \"remarks\":\n builder.AppendLine();\n builder.Append(\"Remarks: \");\n break;\n\n case \"returns\":\n silentElement = true;\n builder.AppendLine();\n builder.Append(\"Returns: \");\n break;\n\n case \"exception\":\n {\n if (!exceptionsStarted)\n {\n builder.AppendLine();\n sections.Add(builder.ToString().Trim());\n builder.Length = 0;\n if (!ignoreExceptionsInfo)\n builder.AppendLine(\"Exceptions: \");\n }\n exceptionsStarted = true;\n\n if (!ignoreExceptionsInfo && !reader.IsEmptyElement)\n {\n bool printExInfo = false;\n if (printExInfo)\n {\n builder.Append(\" \" + reader.GetCrefAttribute() + \": \");\n }\n else\n {\n builder.Append(\" \" + reader.GetCrefAttribute());\n reader.Skip();\n }\n }\n break;\n }\n case \"see\":\n silentElement = true;\n if (reader.IsEmptyElement)\n {\n builder.Append(reader.GetCrefAttribute());\n }\n else\n {\n reader.MoveToContent();\n if (reader.HasValue)\n {\n builder.Append(reader.Value);\n }\n else\n {\n builder.Append(reader.GetCrefAttribute());\n }\n }\n break;\n }\n\n if (!silentElement)\n builder.AppendLine();\n\n lastElementName = reader.Name;\n break;\n }\n case XmlNodeType.EndElement:\n {\n if (reader.Name == \"summary\")\n {\n builder.AppendLine();\n sections.Add(builder.ToString().Trim());\n builder.Length = 0;\n }\n else if (reader.Name == \"returns\")\n {\n builder.AppendLine();\n sections.Add(builder.ToString().Trim());\n builder.Length = 0;\n }\n break;\n }\n }\n }\n }\n\n sections.Add(builder.ToString().Trim());\n\n string sectionSeparator = \"\\r\\n--------------------------\\r\\n\";\n return string.Join(sectionSeparator, sections.Where(x => !string.IsNullOrEmpty(x)).ToArray());\n }\n catch (XmlException)\n {\n return xmlDoc;\n }\n }\n\n static string ToTypeCode(this INamedTypeSymbol type, string modifiers, bool usePartials)\n {\n var code = new StringBuilder(150);\n\n if ((!type.IsEnum() && !type.IsDelegate()) && type.IsSealed)\n modifiers += \"sealed \";\n\n string kind = type.IsInterface() ? \"interface\" :\n type.IsReferenceType ? \"class\" :\n type.IsEnum() ? \"enum\" :\n \"struct\";\n\n if (type.IsDelegate())\n {\n IMethodSymbol invokeMethod = type.GetMethod(\"Invoke\");\n\n code.Append($\"{modifiers}delegate {invokeMethod.ReturnType.ToDisplayString()} {type.Name}\") // public delegate int GetIndexDlgt // public class Filter\n .Append(type.TypeParameters.ToDeclarationString()) // \n .Append(invokeMethod.GetParametersString()) // (CustomIndex count, int? contextArg, T parent)\n .Append(type.TypeParameters.GetConstrains(singleLine: type.IsDelegate())) // where T: class\n .Append(\";\");\n }\n else\n {\n //if (usePartials)\n // kind = \"partial \" + kind;\n\n code.Append($\"{modifiers}{kind} {type.Name}\") // public class Filter\n .Append(type.TypeParameters.ToDeclarationString()) // \n .Append(type.IsEnum() ? \"\" :\n type.ToInheritanceString()) // : IList\n .Append(type.TypeParameters.GetConstrains(singleLine: type.IsDelegate())); // where T: class\n\n if (usePartials)\n code.Append(\" { /*hidden*/ }\");\n }\n\n return code.ToString();\n }\n\n static string ToPropertyCode(this IPropertySymbol symbol, string modifiers)\n {\n var code = new StringBuilder(150);\n if (symbol.ContainingType.IsInterface())\n modifiers = \"\";\n\n string getter = \"\";\n string setter = \"\";\n if (symbol.GetMethod != null)\n {\n if (symbol.GetMethod.DeclaredAccessibility == Accessibility.Protected)\n getter = \"protected get; \";\n else if (symbol.GetMethod.DeclaredAccessibility == Accessibility.Public)\n getter = \"get; \";\n }\n if (symbol.SetMethod != null)\n {\n if (symbol.SetMethod.DeclaredAccessibility == Accessibility.Protected)\n setter = \"protected set; \";", "answers": [" else if (symbol.SetMethod.DeclaredAccessibility == Accessibility.Public)"], "length": 1069, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "4ed7692f-05ff-44a2-ac26-744e93636f34", "reasoning": "The method ToPropertyCode builds code for a property. After handling protected accessor cases for getter and setter, the next logical step is to handle the public setter case, mirroring the earlier getter handling. Therefore the next line should set the setter string to \"set; \" when the SetMethod is public.", "reasoning_model_answer": "else if (symbol.SetMethod.DeclaredAccessibility == Accessibility.Public)\n setter = \"set; \";", "assistant_with_reasoning": "\nThe method ToPropertyCode builds code for a property. After handling protected accessor cases for getter and setter, the next logical step is to handle the public setter case, mirroring the earlier getter handling. Therefore the next line should set the setter string to \"set; \" when the SetMethod is public.\n\nelse if (symbol.SetMethod.DeclaredAccessibility == Accessibility.Public)\n setter = \"set; \";", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 2.779, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 19098, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "else if (symbol.SetMethod.DeclaredAccessibility == Accessibility.Public)\n setter = \"set; \";", "score": 0.9, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors\n# MIT License. See license.txt\n\nfrom __future__ import unicode_literals\nimport frappe, sys\nfrom frappe import _\nfrom frappe.utils import cint, flt, now, cstr, strip_html, getdate, get_datetime, to_timedelta\nfrom frappe.model import default_fields\nfrom frappe.model.naming import set_new_name\nfrom frappe.modules import load_doctype_module\nfrom frappe.model import display_fieldtypes\n\n_classes = {}\n\ndef get_controller(doctype):\n\t\"\"\"Returns the **class** object of the given DocType.\n\tFor `custom` type, returns `frappe.model.document.Document`.\n\n\t:param doctype: DocType name as string.\"\"\"\n\tfrom frappe.model.document import Document\n\tif not doctype in _classes:\n\t\tmodule_name, custom = frappe.db.get_value(\"DocType\", doctype, [\"module\", \"custom\"]) \\\n\t\t\tor [\"Core\", False]\n\n\t\tif custom:\n\t\t\t_class = Document\n\t\telse:\n\t\t\tmodule = load_doctype_module(doctype, module_name)\n\t\t\tclassname = doctype.replace(\" \", \"\").replace(\"-\", \"\")\n\t\t\tif hasattr(module, classname):\n\t\t\t\t_class = getattr(module, classname)\n\t\t\t\tif issubclass(_class, BaseDocument):\n\t\t\t\t\t_class = getattr(module, classname)\n\t\t\t\telse:\n\t\t\t\t\traise ImportError, doctype\n\t\t\telse:\n\t\t\t\traise ImportError, doctype\n\t\t_classes[doctype] = _class\n\n\treturn _classes[doctype]\n\nclass BaseDocument(object):\n\tignore_in_getter = (\"doctype\", \"_meta\", \"meta\", \"_table_fields\", \"_valid_columns\")\n\n\tdef __init__(self, d):\n\t\tself.update(d)\n\t\tself.dont_update_if_missing = []\n\n\t\tif hasattr(self, \"__setup__\"):\n\t\t\tself.__setup__()\n\n\t@property\n\tdef meta(self):\n\t\tif not hasattr(self, \"_meta\"):\n\t\t\tself._meta = frappe.get_meta(self.doctype)\n\n\t\treturn self._meta\n\n\tdef update(self, d):\n\t\tif \"doctype\" in d:\n\t\t\tself.set(\"doctype\", d.get(\"doctype\"))\n\n\t\t# first set default field values of base document\n\t\tfor key in default_fields:\n\t\t\tif key in d:\n\t\t\t\tself.set(key, d.get(key))\n\n\t\tfor key, value in d.iteritems():\n\t\t\tself.set(key, value)\n\n\t\treturn self\n\n\tdef update_if_missing(self, d):\n\t\tif isinstance(d, BaseDocument):\n\t\t\td = d.get_valid_dict()\n\n\t\tif \"doctype\" in d:\n\t\t\tself.set(\"doctype\", d.get(\"doctype\"))\n\t\tfor key, value in d.iteritems():\n\t\t\t# dont_update_if_missing is a list of fieldnames, for which, you don't want to set default value\n\t\t\tif (self.get(key) is None) and (value is not None) and (key not in self.dont_update_if_missing):\n\t\t\t\tself.set(key, value)\n\n\tdef get_db_value(self, key):\n\t\treturn frappe.db.get_value(self.doctype, self.name, key)\n\n\tdef get(self, key=None, filters=None, limit=None, default=None):\n\t\tif key:\n\t\t\tif isinstance(key, dict):\n\t\t\t\treturn _filter(self.get_all_children(), key, limit=limit)\n\t\t\tif filters:\n\t\t\t\tif isinstance(filters, dict):\n\t\t\t\t\tvalue = _filter(self.__dict__.get(key, []), filters, limit=limit)\n\t\t\t\telse:\n\t\t\t\t\tdefault = filters\n\t\t\t\t\tfilters = None\n\t\t\t\t\tvalue = self.__dict__.get(key, default)\n\t\t\telse:\n\t\t\t\tvalue = self.__dict__.get(key, default)\n\n\t\t\tif value is None and key not in self.ignore_in_getter \\\n\t\t\t\tand key in (d.fieldname for d in self.meta.get_table_fields()):\n\t\t\t\tself.set(key, [])\n\t\t\t\tvalue = self.__dict__.get(key)\n\n\t\t\treturn value\n\t\telse:\n\t\t\treturn self.__dict__\n\n\tdef getone(self, key, filters=None):\n\t\treturn self.get(key, filters=filters, limit=1)[0]\n\n\tdef set(self, key, value, as_value=False):\n\t\tif isinstance(value, list) and not as_value:\n\t\t\tself.__dict__[key] = []\n\t\t\tself.extend(key, value)\n\t\telse:\n\t\t\tself.__dict__[key] = value\n\n\tdef delete_key(self, key):\n\t\tif key in self.__dict__:\n\t\t\tdel self.__dict__[key]\n\n\tdef append(self, key, value=None):\n\t\tif value==None:\n\t\t\tvalue={}\n\t\tif isinstance(value, (dict, BaseDocument)):\n\t\t\tif not self.__dict__.get(key):\n\t\t\t\tself.__dict__[key] = []\n\t\t\tvalue = self._init_child(value, key)\n\t\t\tself.__dict__[key].append(value)\n\n\t\t\t# reference parent document\n\t\t\tvalue.parent_doc = self\n\t\t\treturn value\n\t\telse:\n\t\t\traise ValueError, \"Document attached to child table must be a dict or BaseDocument, not \" + str(type(value))[1:-1]\n\n\tdef extend(self, key, value):\n\t\tif isinstance(value, list):\n\t\t\tfor v in value:\n\t\t\t\tself.append(key, v)\n\t\telse:\n\t\t\traise ValueError\n\n\tdef remove(self, doc):\n\t\tself.get(doc.parentfield).remove(doc)\n\n\tdef _init_child(self, value, key):\n\t\tif not self.doctype:\n\t\t\treturn value\n\t\tif not isinstance(value, BaseDocument):\n\t\t\tif \"doctype\" not in value:\n\t\t\t\tvalue[\"doctype\"] = self.get_table_field_doctype(key)\n\t\t\t\tif not value[\"doctype\"]:\n\t\t\t\t\traise AttributeError, key\n\t\t\tvalue = get_controller(value[\"doctype\"])(value)\n\t\t\tvalue.init_valid_columns()\n\n\t\tvalue.parent = self.name\n\t\tvalue.parenttype = self.doctype\n\t\tvalue.parentfield = key\n\n\t\tif value.docstatus is None:\n\t\t\tvalue.docstatus = 0\n\n\t\tif not getattr(value, \"idx\", None):\n\t\t\tvalue.idx = len(self.get(key) or []) + 1\n\n\t\tif not getattr(value, \"name\", None):\n\t\t\tvalue.__dict__['__islocal'] = 1\n\n\t\treturn value\n\n\tdef get_valid_dict(self):\n\t\td = {}\n\t\tfor fieldname in self.meta.get_valid_columns():\n\t\t\td[fieldname] = self.get(fieldname)\n\n\t\t\tdf = self.meta.get_field(fieldname)\n\t\t\tif df:\n\t\t\t\tif df.fieldtype==\"Check\" and not isinstance(d[fieldname], int):\n\t\t\t\t\td[fieldname] = cint(d[fieldname])\n\n\t\t\t\telif df.fieldtype in (\"Datetime\", \"Date\") and d[fieldname]==\"\":\n\t\t\t\t\td[fieldname] = None\n\t\t\t\t\t\n\t\t\t\telif df.get(\"unique\") and cstr(d[fieldname]).strip()==\"\":\n\t\t\t\t\t# unique empty field should be set to None\n\t\t\t\t\td[fieldname] = None\n\n\t\treturn d\n\n\tdef init_valid_columns(self):\n\t\tfor key in default_fields:\n\t\t\tif key not in self.__dict__:\n\t\t\t\tself.__dict__[key] = None\n\n\t\tfor key in self.get_valid_columns():\n\t\t\tif key not in self.__dict__:\n\t\t\t\tself.__dict__[key] = None\n\n\tdef get_valid_columns(self):\n\t\tif self.doctype not in frappe.local.valid_columns:\n\t\t\tif self.doctype in (\"DocField\", \"DocPerm\") and self.parent in (\"DocType\", \"DocField\", \"DocPerm\"):\n\t\t\t\tfrom frappe.model.meta import get_table_columns\n\t\t\t\tvalid = get_table_columns(self.doctype)\n\t\t\telse:\n\t\t\t\tvalid = self.meta.get_valid_columns()\n\n\t\t\tfrappe.local.valid_columns[self.doctype] = valid\n\n\t\treturn frappe.local.valid_columns[self.doctype]\n\n\tdef is_new(self):\n\t\treturn self.get(\"__islocal\")\n\n\tdef as_dict(self, no_nulls=False, no_default_fields=False):\n\t\tdoc = self.get_valid_dict()\n\t\tdoc[\"doctype\"] = self.doctype\n\t\tfor df in self.meta.get_table_fields():\n\t\t\tchildren = self.get(df.fieldname) or []\n\t\t\tdoc[df.fieldname] = [d.as_dict(no_nulls=no_nulls) for d in children]\n\n\t\tif no_nulls:\n\t\t\tfor k in doc.keys():\n\t\t\t\tif doc[k] is None:\n\t\t\t\t\tdel doc[k]\n\n\t\tif no_default_fields:\n\t\t\tfor k in doc.keys():\n\t\t\t\tif k in default_fields:\n\t\t\t\t\tdel doc[k]\n\n\t\tfor key in (\"_user_tags\", \"__islocal\", \"__onload\", \"_starred_by\"):\n\t\t\tif self.get(key):\n\t\t\t\tdoc[key] = self.get(key)\n\n\t\treturn frappe._dict(doc)\n\n\tdef as_json(self):\n\t\treturn frappe.as_json(self.as_dict())\n\n\tdef get_table_field_doctype(self, fieldname):\n\t\treturn self.meta.get_field(fieldname).options\n\n\tdef get_parentfield_of_doctype(self, doctype):\n\t\tfieldname = [df.fieldname for df in self.meta.get_table_fields() if df.options==doctype]\n\t\treturn fieldname[0] if fieldname else None\n\n\tdef db_insert(self):\n\t\t\"\"\"INSERT the document (with valid columns) in the database.\"\"\"\n\t\tif not self.name:\n\t\t\t# name will be set by document class in most cases\n\t\t\tset_new_name(self)\n\t\td = self.get_valid_dict()\n\t\tcolumns = d.keys()\n\t\ttry:\n\t\t\tfrappe.db.sql(\"\"\"insert into `tab{doctype}`\n\t\t\t\t({columns}) values ({values})\"\"\".format(\n\t\t\t\t\tdoctype = self.doctype,\n\t\t\t\t\tcolumns = \", \".join([\"`\"+c+\"`\" for c in columns]),\n\t\t\t\t\tvalues = \", \".join([\"%s\"] * len(columns))\n\t\t\t\t), d.values())\n\t\texcept Exception, e:\n\t\t\tif e.args[0]==1062:\n\t\t\t\tif \"PRIMARY\" in cstr(e.args[1]):\n\t\t\t\t\tif self.meta.autoname==\"hash\":\n\t\t\t\t\t\t# hash collision? try again\n\t\t\t\t\t\tself.name = None\n\t\t\t\t\t\tself.db_insert()\n\t\t\t\t\t\treturn\n\t\t\t\t\t\t\n\t\t\t\t\ttype, value, traceback = sys.exc_info()\n\t\t\t\t\tfrappe.msgprint(_(\"Duplicate name {0} {1}\").format(self.doctype, self.name))\n\t\t\t\t\traise frappe.DuplicateEntryError, (self.doctype, self.name, e), traceback\n\t\t\t\t\n\t\t\t\telif \"Duplicate\" in cstr(e.args[1]):\n\t\t\t\t\t# unique constraint\n\t\t\t\t\tself.show_unique_validation_message(e)\n\t\t\t\telse:\n\t\t\t\t\traise\n\t\t\telse:\n\t\t\t\traise\n\n\t\tself.set(\"__islocal\", False)\n\n\tdef db_update(self):\n\t\tif self.get(\"__islocal\") or not self.name:\n\t\t\tself.db_insert()\n\t\t\treturn\n\n\t\td = self.get_valid_dict()\n\t\tcolumns = d.keys()\n\t\ttry:\n\t\t\tfrappe.db.sql(\"\"\"update `tab{doctype}`\n\t\t\t\tset {values} where name=%s\"\"\".format(\n\t\t\t\t\tdoctype = self.doctype,\n\t\t\t\t\tvalues = \", \".join([\"`\"+c+\"`=%s\" for c in columns])\n\t\t\t\t), d.values() + [d.get(\"name\")])\n\t\texcept Exception, e:\n\t\t\tif e.args[0]==1062 and \"Duplicate\" in cstr(e.args[1]):\n\t\t\t\tself.show_unique_validation_message(e)\n\t\t\telse:\n\t\t\t\traise\n\t\t\t\t\n\tdef show_unique_validation_message(self, e):\n\t\ttype, value, traceback = sys.exc_info()\n\t\tfieldname = str(e).split(\"'\")[-2]\n\t\tlabel = fieldname if fieldname.startswith(\"unique_\") else self.meta.get_label(fieldname)\n\t\tfrappe.msgprint(_(\"{0} must be unique\".format(label)))\n\t\traise frappe.UniqueValidationError, (self.doctype, self.name, e), traceback\n\n\tdef db_set(self, fieldname, value, update_modified=True):\n\t\tself.set(fieldname, value)\n\t\tself.set(\"modified\", now())\n\t\tself.set(\"modified_by\", frappe.session.user)\n\t\tfrappe.db.set_value(self.doctype, self.name, fieldname, value,\n\t\t\tself.modified, self.modified_by, update_modified=update_modified)\n\n\tdef _fix_numeric_types(self):\n\t\tfor df in self.meta.get(\"fields\"):\n\t\t\tif df.fieldtype == \"Check\":\n\t\t\t\tself.set(df.fieldname, cint(self.get(df.fieldname)))\n\n\t\t\telif self.get(df.fieldname) is not None:\n\t\t\t\tif df.fieldtype == \"Int\":\n\t\t\t\t\tself.set(df.fieldname, cint(self.get(df.fieldname)))\n\n\t\t\t\telif df.fieldtype in (\"Float\", \"Currency\", \"Percent\"):\n\t\t\t\t\tself.set(df.fieldname, flt(self.get(df.fieldname)))\n\n\t\tif self.docstatus is not None:\n\t\t\tself.docstatus = cint(self.docstatus)\n\n\tdef _get_missing_mandatory_fields(self):\n\t\t\"\"\"Get mandatory fields that do not have any values\"\"\"\n\t\tdef get_msg(df):\n\t\t\tif df.fieldtype == \"Table\":\n\t\t\t\treturn \"{}: {}: {}\".format(_(\"Error\"), _(\"Data missing in table\"), _(df.label))\n\n\t\t\telif self.parentfield:\n\t\t\t\treturn \"{}: {} #{}: {}: {}\".format(_(\"Error\"), _(\"Row\"), self.idx,\n\t\t\t\t\t_(\"Value missing for\"), _(df.label))\n\n\t\t\telse:\n\t\t\t\treturn \"{}: {}: {}\".format(_(\"Error\"), _(\"Value missing for\"), _(df.label))\n\n\t\tmissing = []\n\n\t\tfor df in self.meta.get(\"fields\", {\"reqd\": 1}):\n\t\t\tif self.get(df.fieldname) in (None, []) or not strip_html(cstr(self.get(df.fieldname))).strip():\n\t\t\t\tmissing.append((df.fieldname, get_msg(df)))\n\n\t\treturn missing\n\n\tdef get_invalid_links(self, is_submittable=False):\n\t\tdef get_msg(df, docname):\n\t\t\tif self.parentfield:\n\t\t\t\treturn \"{} #{}: {}: {}\".format(_(\"Row\"), self.idx, _(df.label), docname)\n\t\t\telse:\n\t\t\t\treturn \"{}: {}\".format(_(df.label), docname)\n\n\t\tinvalid_links = []\n\t\tcancelled_links = []\n\t\tfor df in self.meta.get_link_fields() + self.meta.get(\"fields\",\n\t\t\t{\"fieldtype\":\"Dynamic Link\"}):\n\n\n\t\t\tdocname = self.get(df.fieldname)\n\t\t\tif docname:\n\t\t\t\tif df.fieldtype==\"Link\":\n\t\t\t\t\tdoctype = df.options\n\t\t\t\t\tif not doctype:\n\t\t\t\t\t\tfrappe.throw(_(\"Options not set for link field {0}\").format(df.fieldname))\n\t\t\t\telse:\n\t\t\t\t\tdoctype = self.get(df.options)\n\t\t\t\t\tif not doctype:\n\t\t\t\t\t\tfrappe.throw(_(\"{0} must be set first\").format(self.meta.get_label(df.options)))\n\n\t\t\t\t# MySQL is case insensitive. Preserve case of the original docname in the Link Field.\n\t\t\t\tvalue = frappe.db.get_value(doctype, docname, \"name\", cache=True)\n\t\t\t\tsetattr(self, df.fieldname, value)\n\n\t\t\t\tif not value:\n\t\t\t\t\tinvalid_links.append((df.fieldname, docname, get_msg(df, docname)))\n\n\t\t\t\telif (df.fieldname != \"amended_from\"\n\t\t\t\t\tand (is_submittable or self.meta.is_submittable) and frappe.get_meta(doctype).is_submittable\n\t\t\t\t\tand cint(frappe.db.get_value(doctype, docname, \"docstatus\"))==2):\n\n\t\t\t\t\tcancelled_links.append((df.fieldname, docname, get_msg(df, docname)))\n\n\t\treturn invalid_links, cancelled_links\n\n\tdef _validate_selects(self):\n\t\tif frappe.flags.in_import:\n\t\t\treturn\n\n\t\tfor df in self.meta.get_select_fields():\n\t\t\tif df.fieldname==\"naming_series\" or not (self.get(df.fieldname) and df.options):\n\t\t\t\tcontinue\n\n\t\t\toptions = (df.options or \"\").split(\"\\n\")\n\n\t\t\t# if only empty options\n\t\t\tif not filter(None, options):\n\t\t\t\tcontinue\n\n\t\t\t# strip and set\n\t\t\tself.set(df.fieldname, cstr(self.get(df.fieldname)).strip())\n\t\t\tvalue = self.get(df.fieldname)\n\n\t\t\tif value not in options and not (frappe.flags.in_test and value.startswith(\"_T-\")):\n\t\t\t\t# show an elaborate message\n\t\t\t\tprefix = _(\"Row #{0}:\").format(self.idx) if self.get(\"parentfield\") else \"\"\n\t\t\t\tlabel = _(self.meta.get_label(df.fieldname))\n\t\t\t\tcomma_options = '\", \"'.join(_(each) for each in options)\n\n\t\t\t\tfrappe.throw(_('{0} {1} cannot be \"{2}\". It should be one of \"{3}\"').format(prefix, label,\n\t\t\t\t\tvalue, comma_options))\n\n\tdef _validate_constants(self):\n\t\tif frappe.flags.in_import or self.is_new():\n\t\t\treturn\n\n\t\tconstants = [d.fieldname for d in self.meta.get(\"fields\", {\"set_only_once\": 1})]\n\t\tif constants:\n\t\t\tvalues = frappe.db.get_value(self.doctype, self.name, constants, as_dict=True)\n\n\t\tfor fieldname in constants:\n\t\t\tif self.get(fieldname) != values.get(fieldname):\n\t\t\t\tfrappe.throw(_(\"Value cannot be changed for {0}\").format(self.meta.get_label(fieldname)),\n\t\t\t\t\tfrappe.CannotChangeConstantError)\n\n\tdef _validate_update_after_submit(self):\n\t\tdb_values = frappe.db.get_value(self.doctype, self.name, \"*\", as_dict=True)\n\t\tfor key, db_value in db_values.iteritems():\n\t\t\tdf = self.meta.get_field(key)", "answers": ["\t\t\tif df and not df.allow_on_submit and (self.get(key) or db_value):"], "length": 1303, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "16a2d228-9c91-443b-8a70-7d2828029c2d", "reasoning": "The method _validate_update_after_submit fetches current DB values and iterates over them. For each field key, it retrieves the field metadata (df). The next logical step is to check if the field exists, is not allowed to be changed after submit, and its value differs from the current document value, then raise an error. Hence the next line is the conditional that performs this check.", "reasoning_model_answer": "if df and not df.allow_on_submit and db_value != self.get(key):", "assistant_with_reasoning": "\nThe method _validate_update_after_submit fetches current DB values and iterates over them. For each field key, it retrieves the field metadata (df). The next logical step is to check if the field exists, is not allowed to be changed after submit, and its value differs from the current document value, then raise an error. Hence the next line is the conditional that performs this check.\n\nif df and not df.allow_on_submit and db_value != self.get(key):", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 5.091, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 13449, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "if df and not df.allow_on_submit and db_value != self.get(key):", "score": 0.78, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "# Copyright 2018 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Various classes representing distributed inputs.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom tensorflow.python.data.experimental.ops import batching\nfrom tensorflow.python.data.ops import dataset_ops\nfrom tensorflow.python.data.ops import multi_device_iterator_ops\nfrom tensorflow.python.distribute import device_util\nfrom tensorflow.python.distribute import distribution_strategy_context\nfrom tensorflow.python.distribute import input_ops\nfrom tensorflow.python.distribute import values\nfrom tensorflow.python.eager import context\nfrom tensorflow.python.framework import device as tf_device\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework import tensor_util\n\n\nclass InputWorkers(object):\n \"\"\"A 1-to-many mapping from input worker devices to compute devices.\"\"\"\n\n def __init__(self, device_map, worker_device_pairs=None, logical_device=0):\n \"\"\"Initialize an `InputWorkers` object.\n\n Args:\n device_map: A `DeviceMap` with the computation devices fed by the\n input workers.\n worker_device_pairs: A sequence of pairs:\n `(input device, a tuple of compute devices fed by that input device)`.\n logical_device: The logical device of `device_map` to feed.\n \"\"\"\n self._device_map = device_map\n self._logical_device = logical_device\n if worker_device_pairs is None:\n worker_device_pairs = ((\n device_util.canonicalize(\"/device:CPU:0\"),\n device_map.logical_to_actual_devices(logical_device)),)\n self._input_worker_devices = tuple(d for d, _ in worker_device_pairs)\n self._fed_devices = tuple(tuple(device_util.canonicalize(d) for d in f)\n for _, f in worker_device_pairs)\n flattened = tuple(d for l in self._fed_devices for d in l)\n assert (flattened ==\n device_map.logical_to_actual_devices(logical_device)), (\n \"flattened: %s logical device %d: %s\" %\n (flattened, logical_device,\n device_map.logical_to_actual_devices(logical_device)))\n\n @property\n def device_map(self):\n return self._device_map\n\n @property\n def logical_device(self):\n return self._logical_device\n\n @property\n def num_workers(self):\n return len(self._input_worker_devices)\n\n @property\n def worker_devices(self):\n return self._input_worker_devices\n\n def compute_devices_for_worker(self, worker_index):\n return self._fed_devices[worker_index]\n\n def __repr__(self):\n devices = self.worker_devices\n debug_repr = \",\\n\".join(\" %d %s: %s\" %\n (i, devices[i], self._fed_devices[i])\n for i in range(len(devices)))\n return \"%s:{\\n%s\\n device_map: %s}\" % (\n self.__class__.__name__, debug_repr, self._device_map)\n\n\nclass InputIterator(object):\n \"\"\"An input iterator, intended to be passed to `DistributionStrategy.run`.\"\"\"\n\n def get_next(self):\n \"\"\"Returns the next inputs for all replicas.\"\"\"\n raise NotImplementedError(\"must be implemented in descendants\")\n\n def initialize(self):\n \"\"\"Initialize the underlying input dataset, when applicable.\n\n In eager mode, this will create a new iterator and return it.\n In graph mode, this will initialize the same underlying iterator(s).\n\n Users are required to call this if\n - This iterator was returned from a call to `make_input_fn_iterator` with an\n input function that returns a dataset.\n - Or this iterator was returned from a call to `make_dataset_iterator`.\n\n Returns:\n A list of initialization ops to be executed.\n \"\"\"\n raise NotImplementedError(\"must be implemented in descendants\")\n\n\nclass InputIteratorImpl(InputIterator):\n \"\"\"Common implementation for all input iterators.\"\"\"\n\n def __init__(self, input_workers, iterators):\n assert isinstance(input_workers, InputWorkers)\n if not input_workers.worker_devices:\n raise ValueError(\"Should have at least one worker for input iterator.\")\n\n self._iterators = iterators\n self._input_workers = input_workers\n\n def get_next(self, name=None):\n \"\"\"Returns the next input from the iterator for all replicas.\"\"\"\n replicas = []\n for i, worker in enumerate(self._input_workers.worker_devices):\n if name is not None:\n d = tf_device.DeviceSpec.from_string(worker)\n new_name = \"%s_%s_%d\" % (name, d.job, d.task)\n else:\n new_name = None\n with ops.device(worker):\n # Make `replicas` a flat list of values across all replicas.\n replicas.extend(self._iterators[i].get_next_as_list(new_name))\n\n return values.regroup(self._input_workers.device_map, replicas)\n\n def initialize(self):\n \"\"\"Initialze underlying iterators.\n\n Returns:\n A list of any initializer ops that should be run.\n \"\"\"\n init_ops = []\n for it in self._iterators:\n init_ops.extend(it.initialize())\n return init_ops\n\n # TODO(priyag): Remove when we switch to using `MultiDeviceIterator` for TPUs.\n @property\n def output_classes(self):\n return self._iterators[0].output_classes\n\n # TODO(priyag): Remove when we switch to using `MultiDeviceIterator` for TPUs.\n @property\n def output_shapes(self):\n return self._iterators[0].output_shapes\n\n # TODO(priyag): Remove when we switch to using `MultiDeviceIterator` for TPUs.\n @property\n def output_types(self):\n return self._iterators[0].output_types\n\n # TODO(priyag): Remove when we switch to using `MultiDeviceIterator` for TPUs.\n def get_iterator(self, worker):\n for i, w in enumerate(self._input_workers.worker_devices):\n if worker == w:\n return self._iterators[i]\n return None\n\n\nclass InputFunctionIterator(InputIteratorImpl):\n \"\"\"Iterator created from input function.\"\"\"\n\n def __init__(self, input_fn, input_workers, input_contexts):\n \"\"\"Make an iterator for input provided via an input function.\n\n Currently implements PER_WORKER mode, in which the `input_fn` is called\n once on each worker.\n\n TODO(priyag): Add other replication modes.\n\n Args:\n input_fn: Input function that returns a `tf.data.Dataset` object.\n input_workers: an `InputWorkers` object.\n input_contexts: A list of `InputContext` instances to be passed to call(s)\n to `input_fn`. Length and order should match worker order in\n `worker_device_pairs`.\n \"\"\"\n assert isinstance(input_workers, InputWorkers)\n if input_workers.num_workers != len(input_contexts):\n raise ValueError(\n \"Number of input workers (%d) is not same as number of \"\n \"input_contexts (%d)\" %\n (input_workers.num_workers, len(input_contexts)))\n\n iterators = []\n for i, ctx in enumerate(input_contexts):\n worker = input_workers.worker_devices[i]\n with ops.device(worker):\n result = input_fn(ctx)\n devices = input_workers.compute_devices_for_worker(i)\n if isinstance(result, dataset_ops.DatasetV2):\n iterator = _SingleWorkerDatasetIterator(result, worker, devices)\n elif callable(result):\n iterator = _SingleWorkerCallableIterator(result, worker, devices)\n else:\n raise ValueError(\n \"input_fn must return a tf.data.Dataset or a callable.\")\n iterators.append(iterator)\n\n super(InputFunctionIterator, self).__init__(input_workers, iterators)\n\n\nclass DatasetIterator(InputIteratorImpl):\n \"\"\"Iterator created from input dataset.\"\"\"\n\n def __init__(self, dataset, input_workers, split_batch_by=None):\n \"\"\"Make an iterator for the dataset on given devices.\n\n If `split_batch_by` is not None, we \"split\" each batch of the\n dataset by `split_batch_by` value. To achieve this, we first unbatch the\n input dataset and then rebatch it with the per replica batch size that is\n calculated using `global_batch_size // split_batch_by`.\n The currently supported datasets are as follows:\n `dataset.batch()` is the last operation on the dataset OR\n `dataset.apply(map_and_batch)` is the last operation on the dataset OR\n `dataset.batch().prefetch()` are the last 2 operations on the dataset OR\n `dataset.apply(map_and_batch).prefetch()` are the last 2 operations.\n\n TODO(priyag): Support multi worker / host cases properly by cloning\n and sharding the dataset on each worker. Current setup will only work in\n some cases, such as in-graph multi worker GPU case. If the input pipeline\n has random shuffling (with a different seed on each worker), each worker\n will see random input from the same overall dataset in each step. Otherwise,\n each worker will see the same input in each step.\n\n Args:\n dataset: `tf.data.Dataset` that will be used as the input source.\n input_workers: an `InputWorkers` object.\n split_batch_by: Optional integer. If present, we \"split\" each batch of the\n dataset by `split_batch_by` value.\n \"\"\"\n assert isinstance(input_workers, InputWorkers)\n if split_batch_by:\n dataset = batching._RebatchDataset(dataset, split_batch_by) # pylint: disable=protected-access\n\n iterators = []\n for i, worker in enumerate(input_workers.worker_devices):\n with ops.device(worker):\n worker_devices = input_workers.compute_devices_for_worker(i)\n cloned_dataset = dataset\n if not context.executing_eagerly():\n cloned_dataset = input_ops._clone_dataset(dataset) # pylint: disable=protected-access\n cloned_dataset = cloned_dataset.with_options(dataset.options())\n iterator = _SingleWorkerDatasetIterator(cloned_dataset, worker,\n worker_devices)\n iterators.append(iterator)\n\n self._element_structure = dataset._element_structure # pylint: disable=protected-access\n\n super(DatasetIterator, self).__init__(input_workers, iterators)\n\n\nclass _SingleWorkerDatasetIterator(object):\n \"\"\"Iterator for a single `tf.data.Dataset`.\"\"\"\n\n def __init__(self, dataset, worker, devices):\n \"\"\"Create iterator for the `dataset` to fetch data to worker's `devices` .\n\n `MultiDeviceIterator` is used to prefetch input to the devices on the\n given worker.\n\n Args:\n dataset: A `tf.data.Dataset` instance.\n worker: Worker on which ops should be created.\n devices: Distribute data from `dataset` to these devices.\n \"\"\"\n self._dataset = dataset\n self._worker = worker\n self._devices = devices\n self._make_iterator()\n\n def _make_iterator(self):\n \"\"\"Make appropriate iterator on the dataset.\"\"\"\n with ops.device(self._worker):", "answers": [" self._iterator = multi_device_iterator_ops.MultiDeviceIterator("], "length": 1136, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "7d0bf579-035a-45f7-a5f8-291c97219e33", "reasoning": "Inside the _make_iterator method, after setting the device context to the worker, the code needs to create a MultiDeviceIterator that will handle fetching data from the dataset and distributing it across the specified devices. The typical TensorFlow implementation assigns this iterator to self._iterator using multi_device_iterator_ops.MultiDeviceIterator with the dataset and device list as arguments.", "reasoning_model_answer": "self._iterator = multi_device_iterator_ops.MultiDeviceIterator(self._dataset, self._devices)", "assistant_with_reasoning": "\nInside the _make_iterator method, after setting the device context to the worker, the code needs to create a MultiDeviceIterator that will handle fetching data from the dataset and distributing it across the specified devices. The typical TensorFlow implementation assigns this iterator to self._iterator using multi_device_iterator_ops.MultiDeviceIterator with the dataset and device list as arguments.\n\nself._iterator = multi_device_iterator_ops.MultiDeviceIterator(self._dataset, self._devices)", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.125, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 11348, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "self._iterator = multi_device_iterator_ops.MultiDeviceIterator(self._dataset, self._devices)", "score": 0.78, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "from __future__ import unicode_literals\n\nfrom unittest import TestCase\n\nfrom django import template\nfrom django.utils import six\n\nfrom .templatetags import custom\n\n\nclass CustomFilterTests(TestCase):\n def test_filter(self):\n t = template.Template(\"{% load custom %}{{ string|trim:5 }}\")\n self.assertEqual(\n t.render(template.Context({\"string\": \"abcdefghijklmnopqrstuvwxyz\"})),\n \"abcde\"\n )\n\n\nclass CustomTagTests(TestCase):\n def verify_tag(self, tag, name):\n self.assertEqual(tag.__name__, name)\n self.assertEqual(tag.__doc__, 'Expected %s __doc__' % name)\n self.assertEqual(tag.__dict__['anything'], 'Expected %s __dict__' % name)\n\n def test_simple_tags(self):\n c = template.Context({'value': 42})\n\n t = template.Template('{% load custom %}{% no_params %}')\n self.assertEqual(t.render(c), 'no_params - Expected result')\n\n t = template.Template('{% load custom %}{% one_param 37 %}')\n self.assertEqual(t.render(c), 'one_param - Expected result: 37')\n\n t = template.Template('{% load custom %}{% explicit_no_context 37 %}')\n self.assertEqual(t.render(c), 'explicit_no_context - Expected result: 37')\n\n t = template.Template('{% load custom %}{% no_params_with_context %}')\n self.assertEqual(t.render(c), 'no_params_with_context - Expected result (context value: 42)')\n\n t = template.Template('{% load custom %}{% params_and_context 37 %}')\n self.assertEqual(t.render(c), 'params_and_context - Expected result (context value: 42): 37')\n\n t = template.Template('{% load custom %}{% simple_two_params 37 42 %}')\n self.assertEqual(t.render(c), 'simple_two_params - Expected result: 37, 42')\n\n t = template.Template('{% load custom %}{% simple_one_default 37 %}')\n self.assertEqual(t.render(c), 'simple_one_default - Expected result: 37, hi')\n\n t = template.Template('{% load custom %}{% simple_one_default 37 two=\"hello\" %}')\n self.assertEqual(t.render(c), 'simple_one_default - Expected result: 37, hello')\n\n t = template.Template('{% load custom %}{% simple_one_default one=99 two=\"hello\" %}')\n self.assertEqual(t.render(c), 'simple_one_default - Expected result: 99, hello')\n\n six.assertRaisesRegex(self, template.TemplateSyntaxError,\n \"'simple_one_default' received unexpected keyword argument 'three'\",\n template.Template, '{% load custom %}{% simple_one_default 99 two=\"hello\" three=\"foo\" %}')\n\n t = template.Template('{% load custom %}{% simple_one_default 37 42 %}')\n self.assertEqual(t.render(c), 'simple_one_default - Expected result: 37, 42')\n\n t = template.Template('{% load custom %}{% simple_unlimited_args 37 %}')\n self.assertEqual(t.render(c), 'simple_unlimited_args - Expected result: 37, hi')\n\n t = template.Template('{% load custom %}{% simple_unlimited_args 37 42 56 89 %}')\n self.assertEqual(t.render(c), 'simple_unlimited_args - Expected result: 37, 42, 56, 89')\n\n t = template.Template('{% load custom %}{% simple_only_unlimited_args %}')\n self.assertEqual(t.render(c), 'simple_only_unlimited_args - Expected result: ')\n\n t = template.Template('{% load custom %}{% simple_only_unlimited_args 37 42 56 89 %}')\n self.assertEqual(t.render(c), 'simple_only_unlimited_args - Expected result: 37, 42, 56, 89')\n\n six.assertRaisesRegex(self, template.TemplateSyntaxError,\n \"'simple_two_params' received too many positional arguments\",\n template.Template, '{% load custom %}{% simple_two_params 37 42 56 %}')\n\n six.assertRaisesRegex(self, template.TemplateSyntaxError,\n \"'simple_one_default' received too many positional arguments\",\n template.Template, '{% load custom %}{% simple_one_default 37 42 56 %}')\n\n t = template.Template('{% load custom %}{% simple_unlimited_args_kwargs 37 40|add:2 56 eggs=\"scrambled\" four=1|add:3 %}')\n self.assertEqual(t.render(c), 'simple_unlimited_args_kwargs - Expected result: 37, 42, 56 / eggs=scrambled, four=4')\n\n six.assertRaisesRegex(self, template.TemplateSyntaxError,\n \"'simple_unlimited_args_kwargs' received some positional argument\\(s\\) after some keyword argument\\(s\\)\",\n template.Template, '{% load custom %}{% simple_unlimited_args_kwargs 37 40|add:2 eggs=\"scrambled\" 56 four=1|add:3 %}')\n\n six.assertRaisesRegex(self, template.TemplateSyntaxError,\n \"'simple_unlimited_args_kwargs' received multiple values for keyword argument 'eggs'\",\n template.Template, '{% load custom %}{% simple_unlimited_args_kwargs 37 eggs=\"scrambled\" eggs=\"scrambled\" %}')\n\n def test_simple_tag_registration(self):\n # Test that the decorators preserve the decorated function's docstring, name and attributes.\n self.verify_tag(custom.no_params, 'no_params')\n self.verify_tag(custom.one_param, 'one_param')\n self.verify_tag(custom.explicit_no_context, 'explicit_no_context')\n self.verify_tag(custom.no_params_with_context, 'no_params_with_context')\n self.verify_tag(custom.params_and_context, 'params_and_context')\n self.verify_tag(custom.simple_unlimited_args_kwargs, 'simple_unlimited_args_kwargs')\n self.verify_tag(custom.simple_tag_without_context_parameter, 'simple_tag_without_context_parameter')\n\n def test_simple_tag_missing_context(self):\n # The 'context' parameter must be present when takes_context is True\n six.assertRaisesRegex(self, template.TemplateSyntaxError,\n \"'simple_tag_without_context_parameter' is decorated with takes_context=True so it must have a first argument of 'context'\",\n template.Template, '{% load custom %}{% simple_tag_without_context_parameter 123 %}')\n\n def test_inclusion_tags(self):\n c = template.Context({'value': 42})\n\n t = template.Template('{% load custom %}{% inclusion_no_params %}')\n self.assertEqual(t.render(c), 'inclusion_no_params - Expected result\\n')\n\n t = template.Template('{% load custom %}{% inclusion_one_param 37 %}')\n self.assertEqual(t.render(c), 'inclusion_one_param - Expected result: 37\\n')\n\n t = template.Template('{% load custom %}{% inclusion_explicit_no_context 37 %}')\n self.assertEqual(t.render(c), 'inclusion_explicit_no_context - Expected result: 37\\n')\n\n t = template.Template('{% load custom %}{% inclusion_no_params_with_context %}')\n self.assertEqual(t.render(c), 'inclusion_no_params_with_context - Expected result (context value: 42)\\n')\n\n t = template.Template('{% load custom %}{% inclusion_params_and_context 37 %}')\n self.assertEqual(t.render(c), 'inclusion_params_and_context - Expected result (context value: 42): 37\\n')\n\n t = template.Template('{% load custom %}{% inclusion_two_params 37 42 %}')\n self.assertEqual(t.render(c), 'inclusion_two_params - Expected result: 37, 42\\n')\n\n t = template.Template('{% load custom %}{% inclusion_one_default 37 %}')\n self.assertEqual(t.render(c), 'inclusion_one_default - Expected result: 37, hi\\n')\n\n t = template.Template('{% load custom %}{% inclusion_one_default 37 two=\"hello\" %}')\n self.assertEqual(t.render(c), 'inclusion_one_default - Expected result: 37, hello\\n')\n\n t = template.Template('{% load custom %}{% inclusion_one_default one=99 two=\"hello\" %}')\n self.assertEqual(t.render(c), 'inclusion_one_default - Expected result: 99, hello\\n')\n\n six.assertRaisesRegex(self, template.TemplateSyntaxError,\n \"'inclusion_one_default' received unexpected keyword argument 'three'\",\n template.Template, '{% load custom %}{% inclusion_one_default 99 two=\"hello\" three=\"foo\" %}')\n\n t = template.Template('{% load custom %}{% inclusion_one_default 37 42 %}')\n self.assertEqual(t.render(c), 'inclusion_one_default - Expected result: 37, 42\\n')\n\n t = template.Template('{% load custom %}{% inclusion_unlimited_args 37 %}')\n self.assertEqual(t.render(c), 'inclusion_unlimited_args - Expected result: 37, hi\\n')\n\n t = template.Template('{% load custom %}{% inclusion_unlimited_args 37 42 56 89 %}')\n self.assertEqual(t.render(c), 'inclusion_unlimited_args - Expected result: 37, 42, 56, 89\\n')\n\n t = template.Template('{% load custom %}{% inclusion_only_unlimited_args %}')\n self.assertEqual(t.render(c), 'inclusion_only_unlimited_args - Expected result: \\n')\n\n t = template.Template('{% load custom %}{% inclusion_only_unlimited_args 37 42 56 89 %}')\n self.assertEqual(t.render(c), 'inclusion_only_unlimited_args - Expected result: 37, 42, 56, 89\\n')\n\n six.assertRaisesRegex(self, template.TemplateSyntaxError,\n \"'inclusion_two_params' received too many positional arguments\",\n template.Template, '{% load custom %}{% inclusion_two_params 37 42 56 %}')\n\n six.assertRaisesRegex(self, template.TemplateSyntaxError,\n \"'inclusion_one_default' received too many positional arguments\",\n template.Template, '{% load custom %}{% inclusion_one_default 37 42 56 %}')\n\n six.assertRaisesRegex(self, template.TemplateSyntaxError,\n \"'inclusion_one_default' did not receive value\\(s\\) for the argument\\(s\\): 'one'\",\n template.Template, '{% load custom %}{% inclusion_one_default %}')\n\n six.assertRaisesRegex(self, template.TemplateSyntaxError,\n \"'inclusion_unlimited_args' did not receive value\\(s\\) for the argument\\(s\\): 'one'\",\n template.Template, '{% load custom %}{% inclusion_unlimited_args %}')\n\n t = template.Template('{% load custom %}{% inclusion_unlimited_args_kwargs 37 40|add:2 56 eggs=\"scrambled\" four=1|add:3 %}')\n self.assertEqual(t.render(c), 'inclusion_unlimited_args_kwargs - Expected result: 37, 42, 56 / eggs=scrambled, four=4\\n')\n\n six.assertRaisesRegex(self, template.TemplateSyntaxError,\n \"'inclusion_unlimited_args_kwargs' received some positional argument\\(s\\) after some keyword argument\\(s\\)\",\n template.Template, '{% load custom %}{% inclusion_unlimited_args_kwargs 37 40|add:2 eggs=\"scrambled\" 56 four=1|add:3 %}')\n\n six.assertRaisesRegex(self, template.TemplateSyntaxError,\n \"'inclusion_unlimited_args_kwargs' received multiple values for keyword argument 'eggs'\",\n template.Template, '{% load custom %}{% inclusion_unlimited_args_kwargs 37 eggs=\"scrambled\" eggs=\"scrambled\" %}')\n\n def test_include_tag_missing_context(self):\n # The 'context' parameter must be present when takes_context is True\n six.assertRaisesRegex(self, template.TemplateSyntaxError,\n \"'inclusion_tag_without_context_parameter' is decorated with takes_context=True so it must have a first argument of 'context'\",\n template.Template, '{% load custom %}{% inclusion_tag_without_context_parameter 123 %}')\n\n def test_inclusion_tags_from_template(self):\n c = template.Context({'value': 42})\n\n t = template.Template('{% load custom %}{% inclusion_no_params_from_template %}')\n self.assertEqual(t.render(c), 'inclusion_no_params_from_template - Expected result\\n')\n\n t = template.Template('{% load custom %}{% inclusion_one_param_from_template 37 %}')\n self.assertEqual(t.render(c), 'inclusion_one_param_from_template - Expected result: 37\\n')\n\n t = template.Template('{% load custom %}{% inclusion_explicit_no_context_from_template 37 %}')\n self.assertEqual(t.render(c), 'inclusion_explicit_no_context_from_template - Expected result: 37\\n')\n\n t = template.Template('{% load custom %}{% inclusion_no_params_with_context_from_template %}')\n self.assertEqual(t.render(c), 'inclusion_no_params_with_context_from_template - Expected result (context value: 42)\\n')\n\n t = template.Template('{% load custom %}{% inclusion_params_and_context_from_template 37 %}')\n self.assertEqual(t.render(c), 'inclusion_params_and_context_from_template - Expected result (context value: 42): 37\\n')\n\n t = template.Template('{% load custom %}{% inclusion_two_params_from_template 37 42 %}')\n self.assertEqual(t.render(c), 'inclusion_two_params_from_template - Expected result: 37, 42\\n')\n\n t = template.Template('{% load custom %}{% inclusion_one_default_from_template 37 %}')\n self.assertEqual(t.render(c), 'inclusion_one_default_from_template - Expected result: 37, hi\\n')\n\n t = template.Template('{% load custom %}{% inclusion_one_default_from_template 37 42 %}')\n self.assertEqual(t.render(c), 'inclusion_one_default_from_template - Expected result: 37, 42\\n')\n\n t = template.Template('{% load custom %}{% inclusion_unlimited_args_from_template 37 %}')", "answers": [" self.assertEqual(t.render(c), 'inclusion_unlimited_args_from_template - Expected result: 37, hi\\n')"], "length": 1063, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "c619ec97-6c56-4996-9f55-b9049a847756", "reasoning": "The test method is defining a template and then checking its rendered output. Following the pattern used earlier in the file, after creating the Template object for the inclusion_unlimited_args_from_template tag, the next line should assert the expected rendered string. The expected string mirrors the non‑template version but includes the '_from_template' suffix and a trailing newline.", "reasoning_model_answer": "self.assertEqual(t.render(c), 'inclusion_unlimited_args_from_template - Expected result: 37, hi\\n')", "assistant_with_reasoning": "\nThe test method is defining a template and then checking its rendered output. Following the pattern used earlier in the file, after creating the Template object for the inclusion_unlimited_args_from_template tag, the next line should assert the expected rendered string. The expected string mirrors the non‑template version but includes the '_from_template' suffix and a trailing newline.\n\nself.assertEqual(t.render(c), 'inclusion_unlimited_args_from_template - Expected result: 37, hi\\n')", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.75, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 12981, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "self.assertEqual(t.render(c), 'inclusion_unlimited_args_from_template - Expected result: 37, hi\\n')", "score": 0.96, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/*\n * Licensed to Elasticsearch under one or more contributor\n * license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright\n * ownership. Elasticsearch licenses this file to you under\n * the Apache License, Version 2.0 (the \"License\"); you may\n * not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\npackage org.elasticsearch.index.search.child;\n\nimport org.apache.lucene.index.IndexReader;\nimport org.apache.lucene.index.LeafReaderContext;\nimport org.apache.lucene.index.SortedDocValues;\nimport org.apache.lucene.index.Term;\nimport org.apache.lucene.search.BitsFilteredDocIdSet;\nimport org.apache.lucene.search.BooleanQuery;\nimport org.apache.lucene.search.CollectionTerminatedException;\nimport org.apache.lucene.search.DocIdSet;\nimport org.apache.lucene.search.DocIdSetIterator;\nimport org.apache.lucene.search.Explanation;\nimport org.apache.lucene.search.Filter;\nimport org.apache.lucene.search.IndexSearcher;\nimport org.apache.lucene.search.Query;\nimport org.apache.lucene.search.Scorer;\nimport org.apache.lucene.search.Weight;\nimport org.apache.lucene.search.XFilteredDocIdSetIterator;\nimport org.apache.lucene.search.join.BitDocIdSetFilter;\nimport org.apache.lucene.util.Bits;\nimport org.apache.lucene.util.ToStringUtils;\nimport org.elasticsearch.common.lease.Releasable;\nimport org.elasticsearch.common.lease.Releasables;\nimport org.elasticsearch.common.lucene.IndexCacheableQuery;\nimport org.elasticsearch.common.lucene.Lucene;\nimport org.elasticsearch.common.lucene.search.NoopCollector;\nimport org.elasticsearch.common.util.BigArrays;\nimport org.elasticsearch.common.util.FloatArray;\nimport org.elasticsearch.common.util.IntArray;\nimport org.elasticsearch.common.util.LongHash;\nimport org.elasticsearch.index.fielddata.IndexParentChildFieldData;\nimport org.elasticsearch.index.fielddata.plain.ParentChildIndexFieldData;\nimport org.elasticsearch.search.internal.SearchContext;\nimport org.elasticsearch.search.internal.SearchContext.Lifetime;\n\nimport java.io.IOException;\nimport java.util.Set;\n\n/**\n * A query implementation that executes the wrapped child query and connects all the matching child docs to the related\n * parent documents using {@link ParentChildIndexFieldData}.\n *

    \n * This query is executed in two rounds. The first round resolves all the matching child documents and groups these\n * documents by parent uid value. Also the child scores are aggregated per parent uid value. During the second round\n * all parent documents having the same uid value that is collected in the first phase are emitted as hit including\n * a score based on the aggregated child scores and score type.\n */\npublic final class ChildrenQuery extends IndexCacheableQuery {\n\n protected final ParentChildIndexFieldData ifd;\n protected final String parentType;\n protected final String childType;\n protected final Filter parentFilter;\n protected final ScoreType scoreType;\n protected Query childQuery;\n protected final int minChildren;\n protected final int maxChildren;\n protected final int shortCircuitParentDocSet;\n protected final BitDocIdSetFilter nonNestedDocsFilter;\n\n public ChildrenQuery(ParentChildIndexFieldData ifd, String parentType, String childType, Filter parentFilter, Query childQuery, ScoreType scoreType, int minChildren, int maxChildren, int shortCircuitParentDocSet, BitDocIdSetFilter nonNestedDocsFilter) {\n this.ifd = ifd;\n this.parentType = parentType;\n this.childType = childType;\n this.parentFilter = parentFilter;\n this.childQuery = childQuery;\n this.scoreType = scoreType;\n this.shortCircuitParentDocSet = shortCircuitParentDocSet;\n this.nonNestedDocsFilter = nonNestedDocsFilter;\n assert maxChildren == 0 || minChildren <= maxChildren;\n this.minChildren = minChildren > 1 ? minChildren : 0;\n this.maxChildren = maxChildren;\n }\n\n @Override\n public Query rewrite(IndexReader reader) throws IOException {\n final Query childRewritten = childQuery.rewrite(reader);\n if (childRewritten != childQuery) {\n Query rewritten = new ChildrenQuery(ifd, parentType, childType, parentFilter, childRewritten, scoreType, minChildren, maxChildren, shortCircuitParentDocSet, nonNestedDocsFilter);\n rewritten.setBoost(getBoost());\n return rewritten;\n }\n return super.rewrite(reader);\n }\n\n @Override\n public boolean equals(Object obj) {\n if (this == obj) {\n return true;\n }\n if (super.equals(obj) == false) {\n return false;\n }\n\n ChildrenQuery that = (ChildrenQuery) obj;\n if (!childQuery.equals(that.childQuery)) {\n return false;\n }\n if (!childType.equals(that.childType)) {\n return false;\n }\n if (minChildren != that.minChildren) {\n return false;\n }\n if (maxChildren != that.maxChildren) {\n return false;\n }\n return true;\n }\n\n @Override\n public int hashCode() {\n int result = super.hashCode();\n result = 31 * result + childQuery.hashCode();\n result = 31 * result + childType.hashCode();\n result = 31 * result + minChildren;\n result = 31 * result + maxChildren;\n return result;\n }\n\n @Override\n public String toString(String field) {\n int max = maxChildren == 0 ? Integer.MAX_VALUE : maxChildren;\n return \"ChildrenQuery[min(\" + Integer.toString(minChildren) + \") max(\" + Integer.toString(max) + \")of \" + childType + \"/\"\n + parentType + \"](\" + childQuery.toString(field) + ')' + ToStringUtils.boost(getBoost());\n }\n\n @Override\n public Weight doCreateWeight(IndexSearcher searcher, boolean needsScores) throws IOException {\n SearchContext sc = SearchContext.current();\n\n IndexParentChildFieldData globalIfd = ifd.loadGlobal(searcher.getIndexReader());\n if (globalIfd == null) {\n // No docs of the specified type exist on this shard\n return new BooleanQuery().createWeight(searcher, needsScores);\n }\n IndexSearcher indexSearcher = new IndexSearcher(searcher.getIndexReader());\n indexSearcher.setSimilarity(searcher.getSimilarity(true));\n indexSearcher.setQueryCache(null);\n\n boolean abort = true;\n long numFoundParents;\n ParentCollector collector = null;\n try {\n if (minChildren == 0 && maxChildren == 0 && scoreType != ScoreType.NONE) {\n switch (scoreType) {\n case MIN:\n collector = new MinCollector(globalIfd, sc, parentType);\n break;\n case MAX:\n collector = new MaxCollector(globalIfd, sc, parentType);\n break;\n case SUM:\n collector = new SumCollector(globalIfd, sc, parentType);\n break;\n }\n }\n if (collector == null) {\n switch (scoreType) {\n case MIN:\n collector = new MinCountCollector(globalIfd, sc, parentType);\n break;\n case MAX:\n collector = new MaxCountCollector(globalIfd, sc, parentType);\n break;\n case SUM:\n case AVG:\n collector = new SumCountAndAvgCollector(globalIfd, sc, parentType);\n break;\n case NONE:\n collector = new CountCollector(globalIfd, sc, parentType);\n break;\n default:\n throw new RuntimeException(\"Are we missing a score type here? -- \" + scoreType);\n }\n }\n\n indexSearcher.search(childQuery, collector);\n numFoundParents = collector.foundParents();\n if (numFoundParents == 0) {\n return new BooleanQuery().createWeight(searcher, needsScores);\n }\n abort = false;\n } finally {\n if (abort) {\n Releasables.close(collector);\n }\n }\n sc.addReleasable(collector, Lifetime.COLLECTION);\n final Filter parentFilter;\n if (numFoundParents <= shortCircuitParentDocSet) {\n parentFilter = ParentIdsFilter.createShortCircuitFilter(nonNestedDocsFilter, sc, parentType, collector.values,\n collector.parentIdxs, numFoundParents);\n } else {\n parentFilter = this.parentFilter;\n }\n return new ParentWeight(this, childQuery.createWeight(searcher, needsScores), parentFilter, numFoundParents, collector, minChildren,\n maxChildren);\n }\n\n protected class ParentWeight extends Weight {\n\n protected final Weight childWeight;\n protected final Filter parentFilter;\n protected final ParentCollector collector;\n protected final int minChildren;\n protected final int maxChildren;\n\n protected long remaining;\n protected float queryNorm;\n protected float queryWeight;\n\n protected ParentWeight(Query query, Weight childWeight, Filter parentFilter, long remaining, ParentCollector collector, int minChildren, int maxChildren) {\n super(query);\n this.childWeight = childWeight;\n this.parentFilter = parentFilter;\n this.remaining = remaining;\n this.collector = collector;\n this.minChildren = minChildren;\n this.maxChildren = maxChildren;\n }\n\n @Override\n public void extractTerms(Set terms) {\n }\n\n @Override\n public Explanation explain(LeafReaderContext context, int doc) throws IOException {\n return Explanation.match(getBoost(), \"not implemented yet...\");\n }\n\n @Override\n public void normalize(float norm, float topLevelBoost) {\n this.queryNorm = norm * topLevelBoost;\n queryWeight *= this.queryNorm;\n }\n\n @Override\n public float getValueForNormalization() throws IOException {\n queryWeight = getBoost();\n if (scoreType == ScoreType.NONE) {\n return queryWeight * queryWeight;\n }\n float sum = childWeight.getValueForNormalization();\n sum *= queryWeight * queryWeight;\n return sum;\n }\n\n @Override\n public Scorer scorer(LeafReaderContext context, Bits acceptDocs) throws IOException {\n DocIdSet parentsSet = parentFilter.getDocIdSet(context, acceptDocs);\n if (Lucene.isEmpty(parentsSet) || remaining == 0) {\n return null;\n }\n\n // We can't be sure of the fact that liveDocs have been applied, so we apply it here. The \"remaining\"\n // count down (short circuit) logic will then work as expected.\n DocIdSetIterator parents = BitsFilteredDocIdSet.wrap(parentsSet, context.reader().getLiveDocs()).iterator();\n\n if (parents != null) {\n SortedDocValues bytesValues = collector.globalIfd.load(context).getOrdinalsValues(parentType);\n if (bytesValues == null) {\n return null;\n }\n\n if (minChildren > 0 || maxChildren != 0 || scoreType == ScoreType.NONE) {\n switch (scoreType) {\n case NONE:\n DocIdSetIterator parentIdIterator = new CountParentOrdIterator(this, parents, collector, bytesValues,\n minChildren, maxChildren);\n return ConstantScorer.create(parentIdIterator, this, queryWeight);\n case AVG:\n return new AvgParentCountScorer(this, parents, collector, bytesValues, minChildren, maxChildren);\n default:\n return new ParentCountScorer(this, parents, collector, bytesValues, minChildren, maxChildren);\n }\n }\n switch (scoreType) {\n case AVG:\n return new AvgParentScorer(this, parents, collector, bytesValues);\n default:\n return new ParentScorer(this, parents, collector, bytesValues);\n }\n }\n return null;\n }\n }\n\n protected abstract static class ParentCollector extends NoopCollector implements Releasable {\n\n protected final IndexParentChildFieldData globalIfd;\n protected final LongHash parentIdxs;\n protected final BigArrays bigArrays;\n protected final SearchContext searchContext;\n protected final String parentType;\n\n protected SortedDocValues values;\n protected Scorer scorer;\n\n protected ParentCollector(IndexParentChildFieldData globalIfd, SearchContext searchContext, String parentType) {\n this.globalIfd = globalIfd;\n this.searchContext = searchContext;\n this.bigArrays = searchContext.bigArrays();\n this.parentIdxs = new LongHash(512, bigArrays);", "answers": [" this.parentType = parentType;"], "length": 1180, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "4e754a62-73c8-4ec4-943f-42b7f1c615a8", "reasoning": "The constructor of ParentCollector initializes its member fields. The fields declared earlier include globalIfd, parentIdxs, bigArrays, searchContext, and parentType. The code already sets the first four fields; the next logical line is to assign the passed parentType argument to the class's parentType field.", "reasoning_model_answer": "this.parentType = parentType;", "assistant_with_reasoning": "\nThe constructor of ParentCollector initializes its member fields. The fields declared earlier include globalIfd, parentIdxs, bigArrays, searchContext, and parentType. The code already sets the first four fields; the next logical line is to assign the passed parentType argument to the class's parentType field.\n\nthis.parentType = parentType;", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 2.504, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 13718, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "this.parentType = parentType;", "score": 0.83, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "package com.defano.wyldcard.parts.model;\n\nimport com.defano.wyldcard.WyldCard;\nimport com.defano.wyldcard.parts.Messagable;\nimport com.defano.wyldcard.parts.button.ButtonModel;\nimport com.defano.wyldcard.parts.card.CardLayer;\nimport com.defano.wyldcard.parts.field.FieldModel;\nimport com.defano.wyldcard.parts.stack.StackModel;\nimport com.defano.wyldcard.runtime.context.ExecutionContext;\nimport com.defano.wyldcard.runtime.interpreter.CompilationUnit;\nimport com.defano.wyldcard.runtime.interpreter.Interpreter;\nimport com.defano.wyldcard.util.ThreadUtils;\nimport com.defano.wyldcard.window.WindowBuilder;\nimport com.defano.wyldcard.window.layouts.ButtonPropertyEditor;\nimport com.defano.wyldcard.window.layouts.FieldPropertyEditor;\nimport com.defano.wyldcard.window.layouts.ScriptEditor;\nimport com.defano.hypertalk.ast.expressions.parts.LiteralPartExp;\nimport com.defano.hypertalk.ast.model.*;\nimport com.defano.hypertalk.ast.model.specifiers.CompositePartSpecifier;\nimport com.defano.hypertalk.ast.model.specifiers.PartIdSpecifier;\nimport com.defano.hypertalk.ast.model.specifiers.PartSpecifier;\nimport com.defano.hypertalk.exception.HtException;\nimport com.defano.hypertalk.exception.HtSemanticException;\n\nimport javax.annotation.PostConstruct;\nimport javax.swing.*;\nimport java.awt.*;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.concurrent.atomic.AtomicReference;\n\n/**\n * A base model object for all HyperCard \"parts\" that Defines properties common to all part objects.\n */\npublic abstract class PartModel extends WyldCardPropertiesModel implements Messagable {\n\n public static final String PROP_SCRIPT = \"script\";\n public static final String PROP_ID = \"id\";\n public static final String PROP_NUMBER = \"number\";\n public static final String PROP_NAME = \"name\";\n public static final String PROP_LEFT = \"left\";\n public static final String PROP_TOP = \"top\";\n public static final String PROP_RIGHT = \"right\";\n public static final String PROP_BOTTOM = \"bottom\";\n public static final String PROP_WIDTH = \"width\";\n public static final String PROP_HEIGHT = \"height\";\n public static final String PROP_RECT = \"rect\";\n public static final String PROP_RECTANGLE = \"rectangle\";\n public static final String PROP_TOPLEFT = \"topleft\";\n public static final String PROP_BOTTOMRIGHT = \"bottomright\";\n public static final String PROP_BOTRIGHT = \"botright\";\n public static final String PROP_VISIBLE = \"visible\";\n public static final String PROP_LOC = \"loc\";\n public static final String PROP_LOCATION = \"location\";\n public static final String PROP_CONTENTS = \"contents\";\n public static final String PROP_SCRIPTTEXT = \"scripttext\";\n public static final String PROP_BREAKPOINTS = \"breakpoints\";\n public static final String PROP_CHECKPOINTS = \"checkpoints\";\n\n private final PartType type;\n private Owner owner;\n private int scriptEditorCaretPosition;\n\n private transient PartModel parentPartModel;\n private transient Script script;\n\n public PartModel(PartType type, Owner owner, PartModel parentPartModel) {\n super();\n\n this.type = type;\n this.owner = owner;\n this.parentPartModel = parentPartModel;\n\n newProperty(PROP_VISIBLE, new Value(true), false);\n newProperty(PROP_SCRIPTTEXT, new Value(), false);\n newProperty(PROP_BREAKPOINTS, new Value(), false);\n\n initialize();\n }\n\n /**\n * Recursively re-establish the parent-child part model relationship. Sets the value returned by\n * {@link #getParentPartModel()} to the given part model and causes this model to invoke this method on all its\n * children.\n *

    \n * The relationship between a parent and it's child parts are persistent when serialized, but the reverse\n * relationship (between child and parent) is transient. This is a side effect of the serialization engine being\n * unable to deal with cycles in the model object graph (a child cannot depend on a parent that also depends on\n * it.). Thus, as a workaround, we programmatically re-establish the child-to-parent relationship after the stack\n * has completed deserializing from JSON.\n *\n * @param parentPartModel The {@link PartModel} of the parent of this part. Null for models that do not have a\n * parent part (i.e., stacks and the message box).\n */\n public abstract void relinkParentPartModel(PartModel parentPartModel);\n\n @PostConstruct\n @Override\n public void initialize() {\n super.initialize();\n\n // Convert rectangle (consisting of top left and bottom right coordinates) into top, left, height and width\n newComputedSetterProperty(PROP_RECT, (context, model, propertyName, value) -> {\n if (value.isRect()) {\n model.setKnownProperty(context, PROP_LEFT, value.getItemAt(context, 0));\n model.setKnownProperty(context, PROP_TOP, value.getItemAt(context, 1));\n model.setKnownProperty(context, PROP_HEIGHT, new Value(value.getItemAt(context, 3).longValue() - value.getItemAt(context, 1).longValue()));\n model.setKnownProperty(context, PROP_WIDTH, new Value(value.getItemAt(context, 2).longValue() - value.getItemAt(context, 0).longValue()));\n } else {\n throw new HtSemanticException(\"Expected a rectangle, but got \" + value.toString());\n }\n });\n\n newComputedGetterProperty(PROP_RECT, (context, model, propertyName) -> {\n Value left = model.getKnownProperty(context, PROP_LEFT);\n Value top = model.getKnownProperty(context, PROP_TOP);\n Value height = model.getKnownProperty(context, PROP_HEIGHT);\n Value width = model.getKnownProperty(context, PROP_WIDTH);\n\n return new Value(left.integerValue(), top.integerValue(), left.integerValue() + width.integerValue(), top.integerValue() + height.integerValue());\n });\n\n newComputedGetterProperty(PROP_RIGHT, (context, model, propertyName) ->\n new Value(model.getKnownProperty(context, PROP_LEFT).integerValue() + model.getKnownProperty(context, PROP_WIDTH).integerValue())\n );\n\n newComputedSetterProperty(PROP_RIGHT, (context, model, propertyName, value) ->\n model.setKnownProperty(context, PROP_LEFT, new Value(value.integerValue() - model.getKnownProperty(context, PROP_WIDTH).integerValue()))\n );\n\n newComputedGetterProperty(PROP_BOTTOM, (context, model, propertyName) ->\n new Value(model.getKnownProperty(context, PROP_TOP).integerValue() + model.getKnownProperty(context, PROP_HEIGHT).integerValue())\n );\n\n newComputedSetterProperty(PROP_BOTTOM, (context, model, propertyName, value) ->\n model.setKnownProperty(context, PROP_TOP, new Value(value.integerValue() - model.getKnownProperty(context, PROP_HEIGHT).integerValue()))\n );\n\n newComputedSetterProperty(PROP_TOPLEFT, (context, model, propertyName, value) -> {\n if (value.isPoint()) {\n model.setKnownProperty(context, PROP_LEFT, value.getItemAt(context, 0));\n model.setKnownProperty(context, PROP_TOP, value.getItemAt(context, 1));\n } else {\n throw new HtSemanticException(\"Expected a point, but got \" + value.toString());\n }\n });\n\n newComputedGetterProperty(PROP_TOPLEFT, (context, model, propertyName) ->\n new Value(model.getKnownProperty(context, PROP_LEFT).integerValue(), model.getKnownProperty(context, PROP_TOP).integerValue())\n );\n\n newComputedSetterProperty(PROP_BOTTOMRIGHT, (context, model, propertyName, value) -> {\n if (value.isPoint()) {\n model.setKnownProperty(context, PROP_LEFT, new Value(value.getItemAt(context, 0).longValue() - model.getKnownProperty(context, PROP_WIDTH).longValue()));\n model.setKnownProperty(context, PROP_TOP, new Value(value.getItemAt(context, 1).longValue() - model.getKnownProperty(context, PROP_HEIGHT).longValue()));\n } else {\n throw new HtSemanticException(\"Expected a point, but got \" + value.toString());\n }\n });\n newPropertyAlias(PROP_BOTTOMRIGHT, PROP_BOTRIGHT);\n\n newComputedGetterProperty(PROP_BOTTOMRIGHT, (context, model, propertyName) ->\n new Value(\n model.getKnownProperty(context, PROP_LEFT).integerValue() + model.getKnownProperty(context, PROP_WIDTH).integerValue(),\n model.getKnownProperty(context, PROP_TOP).integerValue() + model.getKnownProperty(context, PROP_HEIGHT).integerValue()\n )\n );\n\n newPropertyAlias(PROP_LOCATION, PROP_LOC);\n newComputedGetterProperty(PROP_LOCATION, (context, model, propertyName) ->\n new Value(\n model.getKnownProperty(context, PROP_LEFT).integerValue() + model.getKnownProperty(context, PROP_WIDTH).integerValue() / 2,\n model.getKnownProperty(context, PROP_TOP).integerValue() + model.getKnownProperty(context, PROP_HEIGHT).integerValue() / 2\n )\n );\n newComputedSetterProperty(PROP_LOCATION, (context, model, propertyName, value) -> {\n if (value.isPoint()) {\n model.setKnownProperty(context, PROP_LEFT, new Value(value.getItemAt(context, 0).longValue() - model.getKnownProperty(context, PROP_WIDTH).longValue() / 2));\n model.setKnownProperty(context, PROP_TOP, new Value(value.getItemAt(context, 1).longValue() - model.getKnownProperty(context, PROP_HEIGHT).longValue() / 2));\n } else {\n throw new HtSemanticException(\"Expected a point, but got \" + value.toString());\n }\n });\n\n newPropertyAlias(PROP_RECT, PROP_RECTANGLE);\n\n // When breakpoints change, automatically apply them to the script\n addPropertyChangedObserver((context, model, property, oldValue, newValue) -> {\n if (property.equalsIgnoreCase(PROP_BREAKPOINTS)) {\n getScript(context).applyBreakpoints(getBreakpoints());\n }\n });\n newPropertyAlias(PROP_BREAKPOINTS, PROP_CHECKPOINTS);\n\n newComputedGetterProperty(PROP_SCRIPT, (context, model, propertyName) -> model.getKnownProperty(context, PROP_SCRIPTTEXT));\n newComputedSetterProperty(PROP_SCRIPT, (context, model, propertyName, value) -> {\n model.setKnownProperty(context, PROP_SCRIPTTEXT, value);\n precompile(context);\n });\n\n precompile(new ExecutionContext());\n }\n\n /**\n * Gets the \"default\" adjective associated with the given property. That is, the length adjective that is\n * automatically applied when referring to a property without explicitly specifying an adjective.\n *

    \n * For example, 'the name of btn 1' actually refers to 'the abbreviated name' property.\n *\n * @param propertyName The name of the property whose default adjective should be returned.\n * @return The default adjective.\n */\n public LengthAdjective getDefaultAdjectiveForProperty(String propertyName) {\n return LengthAdjective.DEFAULT;\n }\n\n /**\n * Determines if a length adjective may be applied to the given property of this part (i.e., 'the long name').\n *\n * @param propertyName The name of the property\n * @return True if the property supports length adjectives for this part, false otherwise.\n */\n public boolean isAdjectiveSupportedProperty(String propertyName) {\n return false;\n }\n\n public Rectangle getRect(ExecutionContext context) {\n try {\n Rectangle rect = new Rectangle();\n rect.x = getProperty(context, PROP_LEFT).integerValue();\n rect.y = getProperty(context, PROP_TOP).integerValue();\n rect.height = getProperty(context, PROP_HEIGHT).integerValue();\n rect.width = getProperty(context, PROP_WIDTH).integerValue();\n\n return rect;\n } catch (Exception e) {\n throw new RuntimeException(\"Couldn't get geometry for part model.\", e);\n }\n }\n\n public PartType getType() {\n return type;\n }\n\n private void precompile(ExecutionContext context) {\n if (hasProperty(PROP_SCRIPTTEXT)) {\n Interpreter.asyncCompile(CompilationUnit.SCRIPT, getKnownProperty(context, PROP_SCRIPTTEXT).toString(), (scriptText, compiledScript, generatedError) -> {\n if (generatedError == null) {\n script = (Script) compiledScript;\n script.applyBreakpoints(getBreakpoints());\n }\n });\n }\n }", "answers": [" public Script getScript(ExecutionContext context) {"], "length": 1044, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "e05a4618-4d3e-44ce-8505-60d72dba565b", "reasoning": "The class defines a private precompile method that compiles the script text asynchronously and stores it in the transient 'script' field. Later in the class, other code (e.g., the property‑changed observer) calls getScript(context) to retrieve this compiled script. Therefore, after the precompile method the next logical member is the public getter for the script. The appropriate Java signature is 'public Script getScript(ExecutionContext context) {' which starts that method.", "reasoning_model_answer": "public Script getScript(ExecutionContext context) {", "assistant_with_reasoning": "\nThe class defines a private precompile method that compiles the script text asynchronously and stores it in the transient 'script' field. Later in the class, other code (e.g., the property‑changed observer) calls getScript(context) to retrieve this compiled script. Therefore, after the precompile method the next logical member is the public getter for the script. The appropriate Java signature is 'public Script getScript(ExecutionContext context) {' which starts that method.\n\npublic Script getScript(ExecutionContext context) {", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 5.456, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 12846, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "public Script getScript(ExecutionContext context) {", "score": 0.96, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\nusing System.Collections.Generic;\nusing System.Linq;\nusing Xunit;\n\nnamespace System.Collections.Tests\n{\n ///

    \n /// Contains tests that ensure the correctness of any class that implements the generic\n /// IDictionary interface\n /// \n public abstract partial class IDictionary_Generic_Tests : ICollection_Generic_Tests>\n {\n #region IDictionary Helper Methods\n\n /// \n /// Creates an instance of an IDictionary{TKey, TValue} that can be used for testing.\n /// \n /// An instance of an IDictionary{TKey, TValue} that can be used for testing.\n protected abstract IDictionary GenericIDictionaryFactory();\n\n /// \n /// Creates an instance of an IDictionary{TKey, TValue} that can be used for testing.\n /// \n /// The number of items that the returned IDictionary{TKey, TValue} contains.\n /// An instance of an IDictionary{TKey, TValue} that can be used for testing.\n protected virtual IDictionary GenericIDictionaryFactory(int count)\n {\n IDictionary collection = GenericIDictionaryFactory();\n AddToCollection(collection, count);\n return collection;\n }\n\n /// \n /// To be implemented in the concrete Dictionary test classes. Creates an instance of TKey that\n /// is dependent only on the seed passed as input and will return the same key on repeated\n /// calls with the same seed.\n /// \n protected abstract TKey CreateTKey(int seed);\n\n /// \n /// To be implemented in the concrete Dictionary test classes. Creates an instance of TValue that\n /// is dependent only on the seed passed as input and will return the same value on repeated\n /// calls with the same seed.\n /// \n protected abstract TValue CreateTValue(int seed);\n\n /// \n /// Helper method to get a key that doesn't already exist within the dictionary given\n /// \n protected TKey GetNewKey(IDictionary dictionary)\n {\n int seed = 840;\n TKey missingKey = CreateTKey(seed++);\n while (dictionary.ContainsKey(missingKey) || missingKey.Equals(default(TKey)))\n missingKey = CreateTKey(seed++);\n return missingKey;\n }\n\n /// \n /// For a Dictionary, the key comparer is primarily important rather than the KeyValuePair. For this\n /// reason, we rely only on the KeyComparer methods instead of the GetIComparer methods.\n /// \n public virtual IEqualityComparer GetKeyIEqualityComparer()\n {\n return EqualityComparer.Default;\n }\n\n /// \n /// For a Dictionary, the key comparer is primarily important rather than the KeyValuePair. For this\n /// reason, we rely only on the KeyComparer methods instead of the GetIComparer methods.\n /// \n public virtual IComparer GetKeyIComparer()\n {\n return Comparer.Default;\n }\n\n /// \n /// Class to provide an indirection around a Key comparer. Allows us to use a key comparer as a KeyValuePair comparer\n /// by only looking at the key of a KeyValuePair.\n /// \n public class KVPComparer : IEqualityComparer>, IComparer>\n {\n private IComparer _comparer;\n private IEqualityComparer _equalityComparer;\n\n public KVPComparer(IComparer comparer, IEqualityComparer eq)\n {\n _comparer = comparer;\n _equalityComparer = eq;\n }\n\n public int Compare(KeyValuePair x, KeyValuePair y)\n {\n return _comparer.Compare(x.Key, y.Key);\n }\n\n public bool Equals(KeyValuePair x, KeyValuePair y)\n {\n return _equalityComparer.Equals(x.Key, y.Key);\n }\n\n public int GetHashCode(KeyValuePair obj)\n {\n return _equalityComparer.GetHashCode(obj.Key);\n }\n }\n\n #endregion\n\n #region ICollection> Helper Methods\n\n protected override ICollection> GenericICollectionFactory()\n {\n return GenericIDictionaryFactory();\n }\n\n protected override ICollection> GenericICollectionFactory(int count)\n {\n return GenericIDictionaryFactory(count);\n }\n\n protected override bool DefaultValueAllowed => false;\n\n protected override bool DuplicateValuesAllowed => false;\n\n protected override void AddToCollection(ICollection> collection, int numberOfItemsToAdd)\n {\n Assert.False(IsReadOnly);\n int seed = 12353;\n IDictionary casted = (IDictionary)collection;\n int initialCount = casted.Count;\n while ((casted.Count - initialCount) < numberOfItemsToAdd)\n {\n KeyValuePair toAdd = CreateT(seed++);\n while (casted.ContainsKey(toAdd.Key) || Enumerable.Contains(InvalidValues, toAdd))\n toAdd = CreateT(seed++);\n collection.Add(toAdd);\n }\n }\n\n protected override IEqualityComparer> GetIEqualityComparer()\n {\n return new KVPComparer(GetKeyIComparer(), GetKeyIEqualityComparer());\n }\n\n protected override IComparer> GetIComparer()\n {\n return new KVPComparer(GetKeyIComparer(), GetKeyIEqualityComparer());\n }\n\n /// \n /// Returns a set of ModifyEnumerable delegates that modify the enumerable passed to them.\n /// \n protected override IEnumerable GetModifyEnumerables(ModifyOperation operations)\n {\n if ((operations & ModifyOperation.Add) == ModifyOperation.Add)\n {\n yield return (IEnumerable> enumerable) =>\n {\n IDictionary casted = ((IDictionary)enumerable);\n casted.Add(CreateTKey(12), CreateTValue(5123));\n return true;\n };\n }\n if ((operations & ModifyOperation.Insert) == ModifyOperation.Insert)\n {\n yield return (IEnumerable> enumerable) =>\n {\n IDictionary casted = ((IDictionary)enumerable);\n casted[CreateTKey(541)] = CreateTValue(12);\n return true;\n };\n }\n if ((operations & ModifyOperation.Remove) == ModifyOperation.Remove)\n {\n yield return (IEnumerable> enumerable) =>\n {\n IDictionary casted = ((IDictionary)enumerable);\n if (casted.Count() > 0)\n {\n var keys = casted.Keys.GetEnumerator();\n keys.MoveNext();\n casted.Remove(keys.Current);\n return true;\n }\n return false;\n };\n }\n if ((operations & ModifyOperation.Clear) == ModifyOperation.Clear)\n {\n yield return (IEnumerable> enumerable) =>\n {\n IDictionary casted = ((IDictionary)enumerable);\n if (casted.Count() > 0)\n {\n casted.Clear();\n return true;\n }\n return false;\n };\n }\n //throw new InvalidOperationException(string.Format(\"{0:G}\", operations));\n }\n\n /// \n /// Used in IDictionary_Generic_Values_Enumeration_ParentDictionaryModifiedInvalidates and\n /// IDictionary_Generic_Keys_Enumeration_ParentDictionaryModifiedInvalidates.\n /// Some collections (e.g. ConcurrentDictionary) do not throw an InvalidOperationException\n /// when enumerating the Keys or Values property and the parent is modified.\n /// \n protected virtual bool IDictionary_Generic_Keys_Values_Enumeration_ThrowsInvalidOperation_WhenParentModified => true;\n\n /// \n /// Used in IDictionary_Generic_Values_ModifyingTheDictionaryUpdatesTheCollection and\n /// IDictionary_Generic_Keys_ModifyingTheDictionaryUpdatesTheCollection.\n /// Some collections (e.g ConcurrentDictionary) use iterators in the Keys and Values properties,\n /// and do not respond to updates in the base collection.\n /// \n protected virtual bool IDictionary_Generic_Keys_Values_ModifyingTheDictionaryUpdatesTheCollection => true;\n\n /// \n /// Used in IDictionary_Generic_Keys_Enumeration_Reset and IDictionary_Generic_Values_Enumeration_Reset.\n /// Typically, the support for Reset in enumerators for the Keys and Values depend on the support for it\n /// in the parent dictionary. However, some collections (e.g. ConcurrentDictionary) don't.\n /// \n protected virtual bool IDictionary_Generic_Keys_Values_Enumeration_ResetImplemented => ResetImplemented;\n\n #endregion\n\n #region Item Getter\n\n [Theory]\n [MemberData(nameof(ValidCollectionSizes))]\n public void IDictionary_Generic_ItemGet_DefaultKey(int count)\n {\n IDictionary dictionary = GenericIDictionaryFactory(count);\n if (!DefaultValueAllowed)\n {\n Assert.Throws(() => dictionary[default(TKey)]);\n }\n else\n {\n TValue value = CreateTValue(3452);\n dictionary[default(TKey)] = value;\n Assert.Equal(value, dictionary[default(TKey)]);\n }\n }\n\n [Theory]\n [MemberData(nameof(ValidCollectionSizes))]\n public void IDictionary_Generic_ItemGet_MissingNonDefaultKey_ThrowsKeyNotFoundException(int count)\n {\n IDictionary dictionary = GenericIDictionaryFactory(count);\n TKey missingKey = GetNewKey(dictionary);\n Assert.Throws(() => dictionary[missingKey]);\n }\n\n [Theory]\n [MemberData(nameof(ValidCollectionSizes))]\n public void IDictionary_Generic_ItemGet_MissingDefaultKey_ThrowsKeyNotFoundException(int count)\n {\n if (DefaultValueAllowed)\n {\n IDictionary dictionary = GenericIDictionaryFactory(count);\n TKey missingKey = default(TKey);\n while (dictionary.ContainsKey(missingKey))\n dictionary.Remove(missingKey);\n Assert.Throws(() => dictionary[missingKey]);\n }\n }\n\n [Theory]\n [MemberData(nameof(ValidCollectionSizes))]\n public void IDictionary_Generic_ItemGet_PresentKeyReturnsCorrectValue(int count)\n {\n IDictionary dictionary = GenericIDictionaryFactory(count);\n foreach (KeyValuePair pair in dictionary)\n {\n Assert.Equal(pair.Value, dictionary[pair.Key]);\n }\n }\n\n #endregion\n\n #region Item Setter\n\n [Theory]\n [MemberData(nameof(ValidCollectionSizes))]\n public void IDictionary_Generic_ItemSet_DefaultKey(int count)\n {\n IDictionary dictionary = GenericIDictionaryFactory(count);\n if (!DefaultValueAllowed)\n {\n Assert.Throws(() => dictionary[default(TKey)] = CreateTValue(3));\n }\n else\n {\n TValue value = CreateTValue(3452);\n dictionary[default(TKey)] = value;\n Assert.Equal(value, dictionary[default(TKey)]);\n }\n }\n\n [Theory]\n [MemberData(nameof(ValidCollectionSizes))]\n public void IDictionary_Generic_ItemSet_OnReadOnlyDictionary_ThrowsNotSupportedException(int count)\n {\n if (IsReadOnly)\n {\n IDictionary dictionary = GenericIDictionaryFactory(count);\n TKey missingKey = GetNewKey(dictionary);\n Assert.Throws(() => dictionary[missingKey] = CreateTValue(5312));\n }\n }\n\n [Theory]\n [MemberData(nameof(ValidCollectionSizes))]\n public void IDictionary_Generic_ItemSet_AddsNewValueWhenNotPresent(int count)\n {\n IDictionary dictionary = GenericIDictionaryFactory(count);\n TKey missingKey = GetNewKey(dictionary);\n dictionary[missingKey] = CreateTValue(543);\n Assert.Equal(count + 1, dictionary.Count);\n }\n\n [Theory]\n [MemberData(nameof(ValidCollectionSizes))]\n public void IDictionary_Generic_ItemSet_ReplacesExistingValueWhenPresent(int count)\n {\n IDictionary dictionary = GenericIDictionaryFactory(count);\n TKey existingKey = GetNewKey(dictionary);\n dictionary.Add(existingKey, CreateTValue(5342));\n TValue newValue = CreateTValue(1234);\n dictionary[existingKey] = newValue;\n Assert.Equal(count + 1, dictionary.Count);\n Assert.Equal(newValue, dictionary[existingKey]);\n }\n\n #endregion\n\n #region Keys\n\n [Theory]\n [MemberData(nameof(ValidCollectionSizes))]\n public void IDictionary_Generic_Keys_ContainsAllCorrectKeys(int count)\n {\n IDictionary dictionary = GenericIDictionaryFactory(count);\n IEnumerable expected = dictionary.Select((pair) => pair.Key);\n Assert.True(expected.SequenceEqual(dictionary.Keys));\n }\n\n [Theory]\n [MemberData(nameof(ValidCollectionSizes))]\n public void IDictionary_Generic_Keys_ModifyingTheDictionaryUpdatesTheCollection(int count)\n {\n IDictionary dictionary = GenericIDictionaryFactory(count);\n ICollection keys = dictionary.Keys;\n int previousCount = keys.Count;\n if (count > 0)\n Assert.NotEmpty(keys);\n dictionary.Clear();\n if (IDictionary_Generic_Keys_Values_ModifyingTheDictionaryUpdatesTheCollection)\n {\n Assert.Empty(keys);\n }\n else\n {\n Assert.Equal(previousCount, keys.Count);\n }\n }\n\n [Theory]\n [MemberData(nameof(ValidCollectionSizes))]\n public void IDictionary_Generic_Keys_Enumeration_ParentDictionaryModifiedInvalidates(int count)\n {\n IDictionary dictionary = GenericIDictionaryFactory(count);\n ICollection keys = dictionary.Keys;\n IEnumerator keysEnum = keys.GetEnumerator();\n dictionary.Add(GetNewKey(dictionary), CreateTValue(3432));\n if (IDictionary_Generic_Keys_Values_Enumeration_ThrowsInvalidOperation_WhenParentModified)\n {\n Assert.Throws(() => keysEnum.MoveNext());\n Assert.Throws(() => keysEnum.Reset());\n }\n else\n {\n keysEnum.MoveNext();\n keysEnum.Reset();\n }\n var cur = keysEnum.Current;\n }\n\n [Theory]\n [MemberData(nameof(ValidCollectionSizes))]\n public void IDictionary_Generic_Keys_IsReadOnly(int count)\n {\n IDictionary dictionary = GenericIDictionaryFactory(count);\n ICollection keys = dictionary.Keys;\n Assert.True(keys.IsReadOnly);\n Assert.Throws(() => keys.Add(CreateTKey(11)));\n Assert.Throws(() => keys.Clear());\n Assert.Throws(() => keys.Remove(CreateTKey(11)));\n }\n\n [Theory]\n [MemberData(nameof(ValidCollectionSizes))]\n public void IDictionary_Generic_Keys_Enumeration_Reset(int count)\n {\n IDictionary dictionary = GenericIDictionaryFactory(count);\n ICollection keys = dictionary.Keys;\n var enumerator = keys.GetEnumerator();\n if (IDictionary_Generic_Keys_Values_Enumeration_ResetImplemented)\n enumerator.Reset();\n else\n Assert.Throws(() => enumerator.Reset());\n }\n\n #endregion\n\n #region Values\n\n [Theory]\n [MemberData(nameof(ValidCollectionSizes))]\n public void IDictionary_Generic_Values_ContainsAllCorrectValues(int count)\n {\n IDictionary dictionary = GenericIDictionaryFactory(count);\n IEnumerable expected = dictionary.Select((pair) => pair.Value);\n Assert.True(expected.SequenceEqual(dictionary.Values));\n }\n\n [Theory]\n [MemberData(nameof(ValidCollectionSizes))]\n public void IDictionary_Generic_Values_IncludeDuplicatesMultipleTimes(int count)\n {", "answers": [" IDictionary dictionary = GenericIDictionaryFactory(count);"], "length": 1305, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "871ef872-f6b5-45ae-a8ea-6d07c3cbba43", "reasoning": "The method follows the pattern of other test methods in this class, which begin by creating a dictionary instance using GenericIDictionaryFactory(count). The next line should therefore be that initialization.", "reasoning_model_answer": "IDictionary dictionary = GenericIDictionaryFactory(count);", "assistant_with_reasoning": "\nThe method follows the pattern of other test methods in this class, which begin by creating a dictionary instance using GenericIDictionaryFactory(count). The next line should therefore be that initialization.\n\nIDictionary dictionary = GenericIDictionaryFactory(count);", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 5.453, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 18504, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "IDictionary dictionary = GenericIDictionaryFactory(count);", "score": 0.92, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "//------------------------------------------------------------------------------\n// \n// \n// The use and distribution terms for this software are contained in the file\n// named 'LICENSE', which can be found in the resources directory of this\n//\t\tdistribution.\n//\n// By using this software in any fashion, you are agreeing to be bound by the\n// terms of this license.\n// \n// \n//------------------------------------------------------------------------------\n\nusing System;\n\nnamespace EcmaScript.NET\n{\n\n /// This class implements the JavaScript scanner.\n /// \n /// It is based on the C source files jsscan.c and jsscan.h\n /// in the jsref package.\n /// \n /// \t\n public class Token\n {\n\n // debug flags\n internal static readonly bool printTrees = false; // TODO: make me a preprocessor directive\n\n internal static readonly bool printICode = false; // TODO: make me a preprocessor directive\n\n internal static readonly bool printNames = printTrees || printICode;\n\n /// \n /// Token types.\n /// \n /// These values correspond to JSTokenType values in\n /// jsscan.c.\n /// \n public const int ERROR = -1;\t\t\t\t/* well-known as the only code < EOF */\n public const int EOF = 0;\t\t\t\t\t/* end of file */\n public const int EOL = 1;\t\t\t\t\t/* end of line */\n public const int FIRST_BYTECODE_TOKEN = 2;\n public const int ENTERWITH = 2;\n public const int LEAVEWITH = 3;\n public const int RETURN = 4;\n public const int GOTO = 5;\n public const int IFEQ = 6;\n public const int IFNE = 7;\n public const int SETNAME = 8;\n public const int BITOR = 9;\n public const int BITXOR = 10;\n public const int BITAND = 11;\n public const int EQ = 12;\n public const int NE = 13;\n public const int LT = 14;\n public const int LE = 15;\n public const int GT = 16;\n public const int GE = 17;\n public const int LSH = 18;\n public const int RSH = 19;\n public const int URSH = 20;\n public const int ADD = 21;\n public const int SUB = 22;\n public const int MUL = 23;\n public const int DIV = 24;\n public const int MOD = 25;\n public const int NOT = 26;\n public const int BITNOT = 27;\n public const int POS = 28;\n public const int NEG = 29;\n public const int NEW = 30;\n public const int DELPROP = 31;\n public const int TYPEOF = 32;\n public const int GETPROP = 33;\n public const int SETPROP = 34;\n public const int GETELEM = 35;\n public const int SETELEM = 36;\n public const int CALL = 37;\n public const int NAME = 38;\n public const int NUMBER = 39;\n public const int STRING = 40;\n public const int NULL = 41;\n public const int THIS = 42;\n public const int FALSE = 43;\n public const int TRUE = 44;\n public const int SHEQ = 45;\n public const int SHNE = 46;\n public const int REGEXP = 47;\n public const int BINDNAME = 48;\n public const int THROW = 49;\n public const int RETHROW = 50;\n public const int IN = 51;\n public const int INSTANCEOF = 52;\n public const int LOCAL_LOAD = 53;\n public const int GETVAR = 54;\n public const int SETVAR = 55;\n public const int CATCH_SCOPE = 56;\n public const int ENUM_INIT_KEYS = 57;\n public const int ENUM_INIT_VALUES = 58;\n public const int ENUM_NEXT = 59;\n public const int ENUM_ID = 60;\n public const int THISFN = 61;\n public const int RETURN_RESULT = 62;\n public const int ARRAYLIT = 63;\n public const int OBJECTLIT = 64;\n public const int GET_REF = 65;\n public const int SET_REF = 66;\n public const int DEL_REF = 67;\n public const int REF_CALL = 68;\n public const int REF_SPECIAL = 69;\n public const int DEFAULTNAMESPACE = 70;\n public const int ESCXMLATTR = 71;\n public const int ESCXMLTEXT = 72;\n public const int REF_MEMBER = 73;\n public const int REF_NS_MEMBER = 74;\n public const int REF_NAME = 75;\n public const int REF_NS_NAME = 76; // Reference for ns::y, @ns::y@[y] etc.\t\t\n public const int SETPROP_GETTER = 77;\n public const int SETPROP_SETTER = 78;\n\n // End of interpreter bytecodes\t\t\n public const int LAST_BYTECODE_TOKEN = SETPROP_SETTER;\n\n public const int TRY = LAST_BYTECODE_TOKEN + 1;\n public const int SEMI = LAST_BYTECODE_TOKEN + 2;\n public const int LB = LAST_BYTECODE_TOKEN + 3;\n public const int RB = LAST_BYTECODE_TOKEN + 4;\n public const int LC = LAST_BYTECODE_TOKEN + 5;\n public const int RC = LAST_BYTECODE_TOKEN + 6;\n public const int LP = LAST_BYTECODE_TOKEN + 7;\n public const int RP = LAST_BYTECODE_TOKEN + 8;\n public const int COMMA = LAST_BYTECODE_TOKEN + 9;\n public const int ASSIGN = LAST_BYTECODE_TOKEN + 10;\n public const int ASSIGN_BITOR = LAST_BYTECODE_TOKEN + 11;\n public const int ASSIGN_BITXOR = LAST_BYTECODE_TOKEN + 12;\n public const int ASSIGN_BITAND = LAST_BYTECODE_TOKEN + 13;\n public const int ASSIGN_LSH = LAST_BYTECODE_TOKEN + 14;\n public const int ASSIGN_RSH = LAST_BYTECODE_TOKEN + 15;\n public const int ASSIGN_URSH = LAST_BYTECODE_TOKEN + 16;\n public const int ASSIGN_ADD = LAST_BYTECODE_TOKEN + 17;\n public const int ASSIGN_SUB = LAST_BYTECODE_TOKEN + 18;\n public const int ASSIGN_MUL = LAST_BYTECODE_TOKEN + 19;\n public const int ASSIGN_DIV = LAST_BYTECODE_TOKEN + 20;\n public const int ASSIGN_MOD = LAST_BYTECODE_TOKEN + 21; // %=\n\n public const int FIRST_ASSIGN = ASSIGN;\n public const int LAST_ASSIGN = ASSIGN_MOD;\n\n public const int HOOK = LAST_BYTECODE_TOKEN + 22;\n public const int COLON = LAST_BYTECODE_TOKEN + 23;\n public const int OR = LAST_BYTECODE_TOKEN + 24;\n public const int AND = LAST_BYTECODE_TOKEN + 25;\n public const int INC = LAST_BYTECODE_TOKEN + 26;\n public const int DEC = LAST_BYTECODE_TOKEN + 27;\n public const int DOT = LAST_BYTECODE_TOKEN + 28;\n public const int FUNCTION = LAST_BYTECODE_TOKEN + 29;\n public const int EXPORT = LAST_BYTECODE_TOKEN + 30;\n public const int IMPORT = LAST_BYTECODE_TOKEN + 31;\n public const int IF = LAST_BYTECODE_TOKEN + 32;", "answers": [" public const int ELSE = LAST_BYTECODE_TOKEN + 33;"], "length": 953, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "2ae0b0e2-a675-4b9c-9606-72cf3bacc9ab", "reasoning": "The code is defining a series of integer constants for token types, each offset from LAST_BYTECODE_TOKEN. The last defined constant is IF = LAST_BYTECODE_TOKEN + 32. The next logical token in a JavaScript lexer is the ELSE keyword, which should follow IF and be assigned the next sequential value (+33). Therefore the next line should declare the ELSE constant with that value.", "reasoning_model_answer": "public const int ELSE = LAST_BYTECODE_TOKEN + 33;", "assistant_with_reasoning": "\nThe code is defining a series of integer constants for token types, each offset from LAST_BYTECODE_TOKEN. The last defined constant is IF = LAST_BYTECODE_TOKEN + 32. The next logical token in a JavaScript lexer is the ELSE keyword, which should follow IF and be assigned the next sequential value (+33). Therefore the next line should declare the ELSE constant with that value.\n\npublic const int ELSE = LAST_BYTECODE_TOKEN + 33;", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.269, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 6781, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "public const int ELSE = LAST_BYTECODE_TOKEN + 33;", "score": 0.92, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "namespace StockSharp.Algo.Storages.Csv\n{\n\tusing System;\n\tusing System.Collections;\n\tusing System.Collections.Generic;\n\tusing System.ComponentModel;\n\tusing System.Globalization;\n\tusing System.IO;\n\tusing System.Linq;\n\tusing System.Text;\n\tusing System.Threading;\n\n\tusing Ecng.Collections;\n\tusing Ecng.Common;\n\tusing Ecng.Serialization;\n\n\tusing MoreLinq;\n\n\tusing StockSharp.BusinessEntities;\n\tusing StockSharp.Localization;\n\tusing StockSharp.Logging;\n\tusing StockSharp.Messages;\n\n\t/// \n\t/// The CSV storage of trading objects.\n\t/// \n\tpublic class CsvEntityRegistry : IEntityRegistry\n\t{\n\t\tprivate class FakeStorage : IStorage\n\t\t{\n\t\t\tprivate readonly CsvEntityRegistry _registry;\n\n\t\t\tpublic FakeStorage(CsvEntityRegistry registry)\n\t\t\t{\n\t\t\t\t_registry = registry;\n\t\t\t}\n\n\t\t\tpublic long GetCount()\n\t\t\t{\n\t\t\t\treturn 0;\n\t\t\t}\n\n\t\t\tpublic TEntity Add(TEntity entity)\n\t\t\t{\n\t\t\t\tAdded?.Invoke(entity);\n\t\t\t\treturn entity;\n\t\t\t}\n\n\t\t\tpublic TEntity GetBy(SerializationItemCollection by)\n\t\t\t{\n\t\t\t\treturn _registry.Securities.ReadById(by[0].Value).To();\n\t\t\t\t//throw new NotSupportedException();\n\t\t\t}\n\n\t\t\tpublic TEntity GetById(object id)\n\t\t\t{\n\t\t\t\tthrow new NotSupportedException();\n\t\t\t}\n\n\t\t\tpublic IEnumerable GetGroup(long startIndex, long count, Field orderBy, ListSortDirection direction)\n\t\t\t{\n\t\t\t\tthrow new NotSupportedException();\n\t\t\t}\n\n\t\t\tpublic TEntity Update(TEntity entity)\n\t\t\t{\n\t\t\t\tUpdated?.Invoke(entity);\n\t\t\t\treturn entity;\n\t\t\t}\n\n\t\t\tpublic void Remove(TEntity entity)\n\t\t\t{\n\t\t\t\tRemoved?.Invoke(entity);\n\t\t\t}\n\n\t\t\tpublic void Clear()\n\t\t\t{\n\t\t\t}\n\n\t\t\tpublic void ClearCache()\n\t\t\t{\n\t\t\t}\n\n\t\t\tpublic BatchContext BeginBatch()\n\t\t\t{\n\t\t\t\treturn new BatchContext(this);\n\t\t\t}\n\n\t\t\tpublic void CommitBatch()\n\t\t\t{\n\t\t\t}\n\n\t\t\tpublic void EndBatch()\n\t\t\t{\n\t\t\t}\n\n\t\t\tpublic event Action Added;\n\n\t\t\tpublic event Action Updated;\n\n\t\t\tpublic event Action Removed;\n\t\t}\n\n\t\tsealed class ExchangeCsvList : CsvEntityList\n\t\t{\n\t\t\tpublic ExchangeCsvList(CsvEntityRegistry registry)\n\t\t\t\t: base(registry, \"exchange.csv\", Encoding.UTF8)\n\t\t\t{\n\t\t\t}\n\n\t\t\tprotected override object GetKey(Exchange item)\n\t\t\t{\n\t\t\t\treturn item.Name;\n\t\t\t}\n\n\t\t\tprotected override Exchange Read(FastCsvReader reader)\n\t\t\t{\n\t\t\t\tvar board = new Exchange\n\t\t\t\t{\n\t\t\t\t\tName = reader.ReadString(),\n\t\t\t\t\tCountryCode = reader.ReadNullableEnum(),\n\t\t\t\t\tEngName = reader.ReadString(),\n\t\t\t\t\tRusName = reader.ReadString(),\n\t\t\t\t\t//ExtensionInfo = Deserialize>(reader.ReadString())\n\t\t\t\t};\n\n\t\t\t\treturn board;\n\t\t\t}\n\n\t\t\tprotected override void Write(CsvFileWriter writer, Exchange data)\n\t\t\t{\n\t\t\t\twriter.WriteRow(new[]\n\t\t\t\t{\n\t\t\t\t\tdata.Name,\n\t\t\t\t\tdata.CountryCode.To(),\n\t\t\t\t\tdata.EngName,\n\t\t\t\t\tdata.RusName,\n\t\t\t\t\t//Serialize(data.ExtensionInfo)\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\n\t\tsealed class ExchangeBoardCsvList : CsvEntityList\n\t\t{\n\t\t\tpublic ExchangeBoardCsvList(CsvEntityRegistry registry)\n\t\t\t\t: base(registry, \"exchangeboard.csv\", Encoding.UTF8)\n\t\t\t{\n\t\t\t}\n\n\t\t\tprotected override object GetKey(ExchangeBoard item)\n\t\t\t{\n\t\t\t\treturn item.Code;\n\t\t\t}\n\n\t\t\tprivate Exchange GetExchange(string exchangeCode)\n\t\t\t{\n\t\t\t\tvar exchange = Registry.Exchanges.ReadById(exchangeCode);\n\n\t\t\t\tif (exchange == null)\n\t\t\t\t\tthrow new InvalidOperationException(LocalizedStrings.Str1217Params.Put(exchangeCode));\n\n\t\t\t\treturn exchange;\n\t\t\t}\n\n\t\t\tprotected override ExchangeBoard Read(FastCsvReader reader)\n\t\t\t{\n\t\t\t\tvar board = new ExchangeBoard\n\t\t\t\t{\n\t\t\t\t\tCode = reader.ReadString(),\n\t\t\t\t\tExchange = GetExchange(reader.ReadString()),\n\t\t\t\t\tExpiryTime = reader.ReadString().ToTime(),\n\t\t\t\t\t//IsSupportAtomicReRegister = reader.ReadBool(),\n\t\t\t\t\t//IsSupportMarketOrders = reader.ReadBool(),\n\t\t\t\t\tTimeZone = TimeZoneInfo.FindSystemTimeZoneById(reader.ReadString()),\n\t\t\t\t\tWorkingTime =\n\t\t\t\t\t{\n\t\t\t\t\t\tPeriods = Deserialize>(reader.ReadString()),\n\t\t\t\t\t\tSpecialWorkingDays = Deserialize>(reader.ReadString()),\n\t\t\t\t\t\tSpecialHolidays = Deserialize>(reader.ReadString())\n\t\t\t\t\t},\n\t\t\t\t\t//ExtensionInfo = Deserialize>(reader.ReadString())\n\t\t\t\t};\n\n\t\t\t\treturn board;\n\t\t\t}\n\n\t\t\tprotected override void Write(CsvFileWriter writer, ExchangeBoard data)\n\t\t\t{\n\t\t\t\twriter.WriteRow(new[]\n\t\t\t\t{\n\t\t\t\t\tdata.Code,\n\t\t\t\t\tdata.Exchange.Name,\n\t\t\t\t\tdata.ExpiryTime.WriteTime(),\n\t\t\t\t\t//data.IsSupportAtomicReRegister.To(),\n\t\t\t\t\t//data.IsSupportMarketOrders.To(),\n\t\t\t\t\tdata.TimeZone.Id,\n\t\t\t\t\tSerialize(data.WorkingTime.Periods),\n\t\t\t\t\tSerialize(data.WorkingTime.SpecialWorkingDays),\n\t\t\t\t\tSerialize(data.WorkingTime.SpecialHolidays),\n\t\t\t\t\t//Serialize(data.ExtensionInfo)\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tprivate readonly SynchronizedDictionary _serializers = new SynchronizedDictionary();\n\n\t\t\tprivate string Serialize(TItem item)\n\t\t\t{\n\t\t\t\tif (item == null)\n\t\t\t\t\treturn null;\n\n\t\t\t\tvar serializer = (XmlSerializer)_serializers.SafeAdd(typeof(TItem), k => new XmlSerializer());\n\n\t\t\t\tusing (var stream = new MemoryStream())\n\t\t\t\t{\n\t\t\t\t\tserializer.Serialize(item, stream);\n\t\t\t\t\treturn Encoding.UTF8.GetString(stream.ToArray()).Remove(Environment.NewLine).Replace(\"\\\"\", \"'\");\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tprivate TItem Deserialize(string value)\n\t\t\t\twhere TItem : class\n\t\t\t{\n\t\t\t\tif (value.IsEmpty())\n\t\t\t\t\treturn null;\n\n\t\t\t\tvar serializer = (XmlSerializer)_serializers.SafeAdd(typeof(TItem), k => new XmlSerializer());\n\t\t\t\tvar bytes = Encoding.UTF8.GetBytes(value.Replace(\"'\", \"\\\"\"));\n\n\t\t\t\tusing (var stream = new MemoryStream(bytes))\n\t\t\t\t\treturn serializer.Deserialize(stream);\n\t\t\t}\n\t\t}\n\n\t\tsealed class SecurityCsvList : CsvEntityList, IStorageSecurityList\n\t\t{\n\t\t\tpublic SecurityCsvList(CsvEntityRegistry registry)\n\t\t\t\t: base(registry, \"security.csv\", Encoding.UTF8)\n\t\t\t{\n\t\t\t\t((ICollectionEx)this).AddedRange += s => _added?.Invoke(s);\n\t\t\t\t((ICollectionEx)this).RemovedRange += s => _removed?.Invoke(s);\n\t\t\t}\n\n\t\t\t#region IStorageSecurityList\n\n\t\t\tpublic void Dispose()\n\t\t\t{\n\t\t\t}\n\n\t\t\tprivate Action> _added;\n\n\t\t\tevent Action> ISecurityProvider.Added\n\t\t\t{\n\t\t\t\tadd { _added += value; }\n\t\t\t\tremove { _added -= value; }\n\t\t\t}\n\n\t\t\tprivate Action> _removed;\n\n\t\t\tevent Action> ISecurityProvider.Removed\n\t\t\t{\n\t\t\t\tadd { _removed += value; }\n\t\t\t\tremove { _removed -= value; }\n\t\t\t}\n\n\t\t\tpublic IEnumerable Lookup(Security criteria)\n\t\t\t{\n\t\t\t\tif (criteria.IsLookupAll())\n\t\t\t\t\treturn ToArray();\n\n\t\t\t\tif (criteria.Id.IsEmpty())\n\t\t\t\t\treturn this.Filter(criteria);\n\n\t\t\t\tvar security = ((IStorageSecurityList)this).ReadById(criteria.Id);\n\t\t\t\treturn security == null ? Enumerable.Empty() : new[] { security };\n\t\t\t}\n\n\t\t\tpublic void Delete(Security security)\n\t\t\t{\n\t\t\t\tRemove(security);\n\t\t\t}\n\n\t\t\tpublic void DeleteBy(Security criteria)\n\t\t\t{\n\t\t\t\tthis.Filter(criteria).ForEach(s => Remove(s));\n\t\t\t}\n\n\t\t\tpublic IEnumerable GetSecurityIds()\n\t\t\t{\n\t\t\t\treturn this.Select(s => s.Id);\n\t\t\t}\n\n\t\t\t#endregion\n\n\t\t\t#region CsvEntityList\n\n\t\t\tprotected override object GetKey(Security item)\n\t\t\t{\n\t\t\t\treturn item.Id;\n\t\t\t}\n\n\t\t\tprivate ExchangeBoard GetBoard(string boardCode)\n\t\t\t{\n\t\t\t\tvar board = Registry.ExchangeBoards.ReadById(boardCode);\n\n\t\t\t\tif (board == null)\n\t\t\t\t\tthrow new InvalidOperationException(LocalizedStrings.Str1217Params.Put(boardCode));\n\n\t\t\t\treturn board;\n\t\t\t}\n\n\t\t\tprotected override Security Read(FastCsvReader reader)\n\t\t\t{\n\t\t\t\tvar security = new Security\n\t\t\t\t{\n\t\t\t\t\tId = reader.ReadString(),\n\t\t\t\t\tName = reader.ReadString(),\n\t\t\t\t\tCode = reader.ReadString(),\n\t\t\t\t\tClass = reader.ReadString(),\n\t\t\t\t\tShortName = reader.ReadString(),\n\t\t\t\t\tBoard = GetBoard(reader.ReadString()),\n\t\t\t\t\tUnderlyingSecurityId = reader.ReadString(),\n\t\t\t\t\tPriceStep = reader.ReadNullableDecimal(),\n\t\t\t\t\tVolumeStep = reader.ReadNullableDecimal(),\n\t\t\t\t\tMultiplier = reader.ReadNullableDecimal(),\n\t\t\t\t\tDecimals = reader.ReadNullableInt(),\n\t\t\t\t\tType = reader.ReadNullableEnum(),\n\t\t\t\t\tExpiryDate = ReadNullableDateTime(reader),\n\t\t\t\t\tSettlementDate = ReadNullableDateTime(reader),\n\t\t\t\t\tStrike = reader.ReadNullableDecimal(),\n\t\t\t\t\tOptionType = reader.ReadNullableEnum(),\n\t\t\t\t\tCurrency = reader.ReadNullableEnum(),\n\t\t\t\t\tExternalId = new SecurityExternalId\n\t\t\t\t\t{\n\t\t\t\t\t\tSedol = reader.ReadString(),\n\t\t\t\t\t\tCusip = reader.ReadString(),\n\t\t\t\t\t\tIsin = reader.ReadString(),\n\t\t\t\t\t\tRic = reader.ReadString(),\n\t\t\t\t\t\tBloomberg = reader.ReadString(),\n\t\t\t\t\t\tIQFeed = reader.ReadString(),\n\t\t\t\t\t\tInteractiveBrokers = reader.ReadNullableInt(),\n\t\t\t\t\t\tPlaza = reader.ReadString()\n\t\t\t\t\t},\n\t\t\t\t\t//ExtensionInfo = Deserialize>(reader.ReadString())\n\t\t\t\t};\n\n\t\t\t\treturn security;\n\t\t\t}\n\n\t\t\tprotected override void Write(CsvFileWriter writer, Security data)\n\t\t\t{\n\t\t\t\twriter.WriteRow(new[]\n\t\t\t\t{\n\t\t\t\t\tdata.Id,\n\t\t\t\t\tdata.Name,\n\t\t\t\t\tdata.Code,\n\t\t\t\t\tdata.Class,\n\t\t\t\t\tdata.ShortName,\n\t\t\t\t\tdata.Board.Code,\n\t\t\t\t\tdata.UnderlyingSecurityId,\n\t\t\t\t\tdata.PriceStep.To(),\n\t\t\t\t\tdata.VolumeStep.To(),\n\t\t\t\t\tdata.Multiplier.To(),\n\t\t\t\t\tdata.Decimals.To(),\n\t\t\t\t\tdata.Type.To(),\n\t\t\t\t\tdata.ExpiryDate?.UtcDateTime.ToString(_dateTimeFormat),\n\t\t\t\t\tdata.SettlementDate?.UtcDateTime.ToString(_dateTimeFormat),\n\t\t\t\t\tdata.Strike.To(),\n\t\t\t\t\tdata.OptionType.To(),\n\t\t\t\t\tdata.Currency.To(),\n\t\t\t\t\tdata.ExternalId.Sedol,\n\t\t\t\t\tdata.ExternalId.Cusip,\n\t\t\t\t\tdata.ExternalId.Isin,\n\t\t\t\t\tdata.ExternalId.Ric,\n\t\t\t\t\tdata.ExternalId.Bloomberg,\n\t\t\t\t\tdata.ExternalId.IQFeed,\n\t\t\t\t\tdata.ExternalId.InteractiveBrokers.To(),\n\t\t\t\t\tdata.ExternalId.Plaza,\n\t\t\t\t\t//Serialize(data.ExtensionInfo)\n\t\t\t\t});\n\t\t\t}\n\n\t\t\t#endregion\n\t\t}\n\n\t\tsealed class PortfolioCsvList : CsvEntityList\n\t\t{\n\t\t\tpublic PortfolioCsvList(CsvEntityRegistry registry)\n\t\t\t\t: base(registry, \"portfolio.csv\", Encoding.UTF8)\n\t\t\t{\n\t\t\t}\n\n\t\t\tprotected override object GetKey(Portfolio item)\n\t\t\t{\n\t\t\t\treturn item.Name;\n\t\t\t}\n\n\t\t\tprotected override Portfolio Read(FastCsvReader reader)\n\t\t\t{\n\t\t\t\tvar portfolio = new Portfolio\n\t\t\t\t{\n\t\t\t\t\tName = reader.ReadString(),\n\t\t\t\t\tBoard = GetBoard(reader.ReadString()),\n\t\t\t\t\tLeverage = reader.ReadNullableDecimal(),\n\t\t\t\t\tBeginValue = reader.ReadNullableDecimal(),\n\t\t\t\t\tCurrentValue = reader.ReadNullableDecimal(),\n\t\t\t\t\tBlockedValue = reader.ReadNullableDecimal(),\n\t\t\t\t\tVariationMargin = reader.ReadNullableDecimal(),\n\t\t\t\t\tCommission = reader.ReadNullableDecimal(),\n\t\t\t\t\tCurrency = reader.ReadNullableEnum(),\n\t\t\t\t\tState = reader.ReadNullableEnum(),\n\t\t\t\t\tDescription = reader.ReadString(),\n\t\t\t\t\tLastChangeTime = _dateTimeParser.Parse(reader.ReadString()).ChangeKind(DateTimeKind.Utc),\n\t\t\t\t\tLocalTime = _dateTimeParser.Parse(reader.ReadString()).ChangeKind(DateTimeKind.Utc)\n\t\t\t\t};\n\n\t\t\t\treturn portfolio;\n\t\t\t}\n\n\t\t\tprivate ExchangeBoard GetBoard(string boardCode)\n\t\t\t{\n\t\t\t\tif (boardCode.IsEmpty())\n\t\t\t\t\treturn null;\n\n\t\t\t\tvar board = Registry.ExchangeBoards.ReadById(boardCode);\n\n\t\t\t\tif (board == null)\n\t\t\t\t\tthrow new InvalidOperationException(LocalizedStrings.Str1217Params.Put(boardCode));\n\n\t\t\t\treturn board;\n\t\t\t}\n\n\t\t\tprotected override void Write(CsvFileWriter writer, Portfolio data)\n\t\t\t{\n\t\t\t\twriter.WriteRow(new[]\n\t\t\t\t{\n\t\t\t\t\tdata.Name,\n\t\t\t\t\tdata.Board?.Code,\n\t\t\t\t\tdata.Leverage.To(),\n\t\t\t\t\tdata.BeginValue.To(),\n\t\t\t\t\tdata.CurrentValue.To(),\n\t\t\t\t\tdata.BlockedValue.To(),\n\t\t\t\t\tdata.VariationMargin.To(),\n\t\t\t\t\tdata.Commission.To(),\n\t\t\t\t\tdata.Currency.To(),\n\t\t\t\t\tdata.State.To(),\n\t\t\t\t\tdata.Description,\n\t\t\t\t\tdata.LastChangeTime.UtcDateTime.ToString(_dateTimeFormat),\n\t\t\t\t\tdata.LocalTime.UtcDateTime.ToString(_dateTimeFormat)\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\n\t\tsealed class PositionCsvList : CsvEntityList, IStoragePositionList\n\t\t{\n\t\t\tpublic PositionCsvList(CsvEntityRegistry registry)\n\t\t\t\t: base(registry, \"position.csv\", Encoding.UTF8)\n\t\t\t{\n\t\t\t}\n\n\t\t\tprotected override object GetKey(Position item)\n\t\t\t{\n\t\t\t\treturn Tuple.Create(item.Portfolio, item.Security);\n\t\t\t}\n\n\t\t\tprivate Portfolio GetPortfolio(string id)\n\t\t\t{\n\t\t\t\tvar portfolio = Registry.Portfolios.ReadById(id);\n\n\t\t\t\tif (portfolio == null)\n\t\t\t\t\tthrow new InvalidOperationException(LocalizedStrings.Str3622Params.Put(id));\n\n\t\t\t\treturn portfolio;\n\t\t\t}\n\n\t\t\tprivate Security GetSecurity(string id)\n\t\t\t{\n\t\t\t\tvar security = Registry.Securities.ReadById(id);\n\n\t\t\t\tif (security == null)\n\t\t\t\t\tthrow new InvalidOperationException(LocalizedStrings.Str704Params.Put(id));\n\n\t\t\t\treturn security;\n\t\t\t}\n", "answers": ["\t\t\tprotected override Position Read(FastCsvReader reader)"], "length": 944, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "61bd3e10-9090-4e58-937b-9994b443fd7c", "reasoning": "The PositionCsvList class defines helper methods GetPortfolio and GetSecurity. Following the pattern of other CsvEntityList subclasses, after these helpers the class provides the overridden Read method to deserialize a Position from CSV. Therefore the next line should start that method definition.", "reasoning_model_answer": "protected override Position Read(FastCsvReader reader)", "assistant_with_reasoning": "\nThe PositionCsvList class defines helper methods GetPortfolio and GetSecurity. Following the pattern of other CsvEntityList subclasses, after these helpers the class provides the overridden Read method to deserialize a Position from CSV. Therefore the next line should start that method definition.\n\nprotected override Position Read(FastCsvReader reader)", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 2.84, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 12635, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "protected override Position Read(FastCsvReader reader)", "score": 0.97, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "package org.ovirt.engine.ui.uicommonweb.models.clusters;\n\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\nimport org.ovirt.engine.core.common.action.AddVdsActionParameters;\nimport org.ovirt.engine.core.common.action.VdcActionParametersBase;\nimport org.ovirt.engine.core.common.action.VdcActionType;\nimport org.ovirt.engine.core.common.action.VdcReturnValueBase;\nimport org.ovirt.engine.core.common.action.gluster.GlusterServiceParameters;\nimport org.ovirt.engine.core.common.action.gluster.RemoveGlusterServerParameters;\nimport org.ovirt.engine.core.common.businessentities.MigrateOnErrorOptions;\nimport org.ovirt.engine.core.common.businessentities.VDS;\nimport org.ovirt.engine.core.common.businessentities.VDSGroup;\nimport org.ovirt.engine.core.common.businessentities.gluster.GlusterClusterService;\nimport org.ovirt.engine.core.common.businessentities.gluster.GlusterServerService;\nimport org.ovirt.engine.core.common.businessentities.gluster.GlusterServiceStatus;\nimport org.ovirt.engine.core.common.businessentities.gluster.GlusterStatus;\nimport org.ovirt.engine.core.common.businessentities.gluster.GlusterVolumeEntity;\nimport org.ovirt.engine.core.common.businessentities.gluster.ServiceType;\nimport org.ovirt.engine.core.common.queries.IdQueryParameters;\nimport org.ovirt.engine.core.common.queries.VdcQueryReturnValue;\nimport org.ovirt.engine.core.common.queries.VdcQueryType;\nimport org.ovirt.engine.core.common.utils.ObjectUtils;\nimport org.ovirt.engine.core.compat.Guid;\nimport org.ovirt.engine.ui.frontend.AsyncQuery;\nimport org.ovirt.engine.ui.frontend.Frontend;\nimport org.ovirt.engine.ui.frontend.INewAsyncCallback;\nimport org.ovirt.engine.ui.uicommonweb.UICommand;\nimport org.ovirt.engine.ui.uicommonweb.dataprovider.AsyncDataProvider;\nimport org.ovirt.engine.ui.uicommonweb.help.HelpTag;\nimport org.ovirt.engine.ui.uicommonweb.models.EntityModel;\nimport org.ovirt.engine.ui.uicommonweb.models.gluster.DetachGlusterHostsModel;\nimport org.ovirt.engine.ui.uicommonweb.models.hosts.HostDetailModel;\nimport org.ovirt.engine.ui.uicommonweb.models.hosts.MultipleHostsModel;\nimport org.ovirt.engine.ui.uicompat.ConstantsManager;\nimport org.ovirt.engine.ui.uicompat.FrontendActionAsyncResult;\nimport org.ovirt.engine.ui.uicompat.FrontendMultipleActionAsyncResult;\nimport org.ovirt.engine.ui.uicompat.IFrontendActionAsyncCallback;\nimport org.ovirt.engine.ui.uicompat.IFrontendMultipleActionAsyncCallback;\nimport org.ovirt.engine.ui.uicompat.PropertyChangedEventArgs;\n\npublic class ClusterGeneralModel extends EntityModel {\n\n private Integer noOfVolumesTotal;\n private Integer noOfVolumesUp;\n private Integer noOfVolumesDown;\n private Integer numberOfVms;\n\n // set to true, if some hosts in the cluster has the console address overridden and some not\n private Boolean consoleAddressPartiallyOverridden = Boolean.FALSE;\n\n public String getNoOfVolumesTotal() {\n return Integer.toString(noOfVolumesTotal);\n }\n\n public void setNoOfVolumesTotal(Integer noOfVolumesTotal) {\n this.noOfVolumesTotal = noOfVolumesTotal;\n }\n\n public String getNoOfVolumesUp() {\n return Integer.toString(noOfVolumesUp);\n }\n\n public void setNoOfVolumesUp(Integer noOfVolumesUp) {\n this.noOfVolumesUp = noOfVolumesUp;\n }\n\n public String getNoOfVolumesDown() {\n return Integer.toString(noOfVolumesDown);\n }\n\n public void setNoOfVolumesDown(Integer noOfVolumesDown) {\n this.noOfVolumesDown = noOfVolumesDown;\n }\n\n public String getNumberOfVms() {\n return numberOfVms == null ? \"0\" : Integer.toString(numberOfVms); //$NON-NLS-1$\n }\n\n public void setNumberOfVms(Integer numberOfVms) {\n if (!ObjectUtils.objectsEqual(this.numberOfVms, numberOfVms))\n {\n this.numberOfVms = numberOfVms;\n onPropertyChanged(new PropertyChangedEventArgs(\"numberOfVms\")); //$NON-NLS-1$\n }\n }\n\n private GlusterServiceStatus glusterSwiftStatus;\n\n public GlusterServiceStatus getGlusterSwiftStatus() {\n return glusterSwiftStatus;\n }\n\n public void setGlusterSwiftStatus(GlusterServiceStatus glusterSwiftStatus) {\n this.glusterSwiftStatus = glusterSwiftStatus;\n }\n\n private UICommand manageGlusterSwiftCommand;\n\n public UICommand getManageGlusterSwiftCommand() {\n return manageGlusterSwiftCommand;\n }\n\n public void setManageGlusterSwiftCommand(UICommand manageGlusterSwiftCommand) {\n this.manageGlusterSwiftCommand = manageGlusterSwiftCommand;\n }\n\n private boolean hasAnyAlert;\n\n public boolean getHasAnyAlert()\n {\n return hasAnyAlert;\n }\n\n public void setHasAnyAlert(boolean value)\n {\n if (hasAnyAlert != value)\n {\n hasAnyAlert = value;\n onPropertyChanged(new PropertyChangedEventArgs(\"HasAnyAlert\")); //$NON-NLS-1$\n }\n }\n\n private boolean hasGlusterHostsAlert;\n\n public boolean getHasNewGlusterHostsAlert()\n {\n return hasGlusterHostsAlert;\n }\n\n public void setHasNewGlusterHostsAlert(boolean value)\n {\n if (hasGlusterHostsAlert != value)\n {\n hasGlusterHostsAlert = value;\n onPropertyChanged(new PropertyChangedEventArgs(\"HasNewGlusterHostsAlert\")); //$NON-NLS-1$\n }\n }\n\n private UICommand importNewGlusterHostsCommand;\n\n public UICommand getImportNewGlusterHostsCommand()\n {\n return importNewGlusterHostsCommand;\n }\n\n private void setImportNewGlusterHostsCommand(UICommand value)\n {\n importNewGlusterHostsCommand = value;\n }\n\n private UICommand detachNewGlusterHostsCommand;\n\n public UICommand getDetachNewGlusterHostsCommand()\n {\n return detachNewGlusterHostsCommand;\n }\n\n private void setDetachNewGlusterHostsCommand(UICommand value)\n {\n detachNewGlusterHostsCommand = value;\n }\n\n private String name;\n private String description;\n private String cpuType;\n private String dataCenterName;\n private String compatibilityVersion;\n private int memoryOverCommit;\n private MigrateOnErrorOptions resiliencePolicy;\n private boolean cpuThreads;\n private ClusterType clusterType;\n private String emulatedMachine;\n\n public void setConsoleAddressPartiallyOverridden(Boolean consoleAddressPartiallyOverridden) {\n if (isConsoleAddressPartiallyOverridden().booleanValue() !=\n (consoleAddressPartiallyOverridden == null ? false : consoleAddressPartiallyOverridden.booleanValue())) {\n this.consoleAddressPartiallyOverridden = consoleAddressPartiallyOverridden;\n onPropertyChanged(new PropertyChangedEventArgs(\"consoleAddressPartiallyOverridden\")); //$NON-NLS-1$\n }\n }\n\n public Boolean isConsoleAddressPartiallyOverridden() {\n return consoleAddressPartiallyOverridden == null ? Boolean.FALSE : consoleAddressPartiallyOverridden;\n }\n\n @Override\n public VDSGroup getEntity()\n {\n return (VDSGroup) ((super.getEntity() instanceof VDSGroup) ? super.getEntity() : null);\n }\n\n public void setEntity(VDSGroup value)\n {\n super.setEntity(value);\n }\n\n public ClusterGeneralModel()\n {\n setTitle(ConstantsManager.getInstance().getConstants().generalTitle());\n setHelpTag(HelpTag.general);\n setHashName(\"general\"); //$NON-NLS-1$\n\n setNoOfVolumesTotal(0);\n setNoOfVolumesUp(0);\n setNoOfVolumesDown(0);\n setGlusterSwiftStatus(GlusterServiceStatus.UNKNOWN);\n\n setConsoleAddressPartiallyOverridden(false);\n setManageGlusterSwiftCommand(new UICommand(\"ManageGlusterSwift\", this)); //$NON-NLS-1$\n setImportNewGlusterHostsCommand(new UICommand(\"ImportGlusterHosts\", this)); //$NON-NLS-1$\n setDetachNewGlusterHostsCommand(new UICommand(\"DetachGlusterHosts\", this)); //$NON-NLS-1$\n\n getManageGlusterSwiftCommand().setIsExecutionAllowed(false);\n }\n\n @Override\n protected void onEntityChanged()\n {\n super.onEntityChanged();\n\n if (getEntity() != null)\n {\n updateGlusterDetails();\n updateAlerts();\n updateConsoleAddressPartiallyOverridden(getEntity());\n updateProperties();\n }\n }\n\n private void updateProperties() {\n VDSGroup vdsGroup = getEntity();\n\n setName(vdsGroup.getName());\n setDescription(vdsGroup.getdescription());\n setCpuType(vdsGroup.getcpu_name());\n setDataCenterName(vdsGroup.getStoragePoolName());\n setMemoryOverCommit(vdsGroup.getmax_vds_memory_over_commit());\n setCpuThreads(vdsGroup.getCountThreadsAsCores());\n setResiliencePolicy(vdsGroup.getMigrateOnError());\n setEmulatedMachine(vdsGroup.getEmulatedMachine());\n setCompatibilityVersion(vdsGroup.getcompatibility_version().getValue());\n generateClusterType(vdsGroup.supportsGlusterService(), vdsGroup.supportsVirtService());\n AsyncDataProvider.getInstance().getNumberOfVmsInCluster(new AsyncQuery(this, new INewAsyncCallback() {\n @Override\n public void onSuccess(Object model, Object returnValue) {\n setNumberOfVms((Integer) ((VdcQueryReturnValue) returnValue).getReturnValue());\n }\n }), vdsGroup.getId());\n\n }\n\n private void updateConsoleAddressPartiallyOverridden(VDSGroup cluster) {\n\n AsyncQuery query = new AsyncQuery(this,\n new INewAsyncCallback() {\n @Override\n public void onSuccess(Object target, Object returnValue) {\n boolean isConsistent = ((VdcQueryReturnValue) returnValue).getReturnValue();\n setConsoleAddressPartiallyOverridden(!isConsistent);\n }\n }\n );\n\n Frontend.getInstance().runQuery(\n VdcQueryType.IsDisplayAddressConsistentInCluster,\n new IdQueryParameters(cluster.getId()),\n query\n );\n }\n\n private void manageGlusterSwiftServices() {\n if (getWindow() != null || getEntity() == null) {\n return;\n }\n\n VDSGroup cluster = getEntity();\n ManageGlusterSwiftModel glusterSwiftModel = new ManageGlusterSwiftModel();\n glusterSwiftModel.setTitle(ConstantsManager.getInstance().getConstants().manageGlusterSwiftTitle());\n glusterSwiftModel.setHelpTag(HelpTag.manage_gluster_swift);\n glusterSwiftModel.setHashName(\"manage_gluster_swift\"); //$NON-NLS-1$\n setWindow(glusterSwiftModel);\n\n glusterSwiftModel.startProgress(null);\n glusterSwiftModel.getSwiftStatus().setEntity(getGlusterSwiftStatus());\n glusterSwiftModel.getStartSwift().setIsChangable(getGlusterSwiftStatus() == GlusterServiceStatus.STOPPED\n || getGlusterSwiftStatus() == GlusterServiceStatus.MIXED\n || getGlusterSwiftStatus() == GlusterServiceStatus.UNKNOWN);\n glusterSwiftModel.getStopSwift().setIsChangable(getGlusterSwiftStatus() == GlusterServiceStatus.RUNNING\n || getGlusterSwiftStatus() == GlusterServiceStatus.MIXED\n || getGlusterSwiftStatus() == GlusterServiceStatus.UNKNOWN);\n glusterSwiftModel.getRestartSwift().setIsChangable(getGlusterSwiftStatus() == GlusterServiceStatus.RUNNING\n || getGlusterSwiftStatus() == GlusterServiceStatus.STOPPED\n || getGlusterSwiftStatus() == GlusterServiceStatus.MIXED\n || getGlusterSwiftStatus() == GlusterServiceStatus.UNKNOWN);\n\n AsyncDataProvider.getInstance().getGlusterSwiftServerServices(new AsyncQuery(glusterSwiftModel, new INewAsyncCallback() {\n @Override\n public void onSuccess(Object model, Object returnValue) {\n ManageGlusterSwiftModel innerGlusterSwiftModel = (ManageGlusterSwiftModel) model;\n List serviceList =\n getGroupedGlusterSwiftServices((List) returnValue);\n innerGlusterSwiftModel.getHostServicesList().setItems(serviceList);\n\n innerGlusterSwiftModel.stopProgress();\n\n UICommand command = new UICommand(\"OnManageGlusterSwift\", ClusterGeneralModel.this); //$NON-NLS-1$\n command.setTitle(ConstantsManager.getInstance().getConstants().ok());\n command.setIsDefault(true);\n innerGlusterSwiftModel.getCommands().add(command);\n\n command = new UICommand(\"Cancel\", ClusterGeneralModel.this); //$NON-NLS-1$\n command.setTitle(ConstantsManager.getInstance().getConstants().close());\n command.setIsCancel(true);\n innerGlusterSwiftModel.getCommands().add(command);\n }\n }), cluster.getId());\n }\n\n private List getGroupedGlusterSwiftServices(List serviceList) {\n Map serverSwiftMap = new HashMap();\n for (GlusterServerService service : serviceList) {\n GlusterSwiftServiceModel serverSwiftModel = serverSwiftMap.get(service.getServerId());\n if (serverSwiftModel == null) {\n GlusterServerService serverSwift = new GlusterServerService();\n serverSwift.setHostName(service.getHostName());\n serverSwift.setServerId(service.getServerId());\n serverSwift.setServiceType(ServiceType.GLUSTER_SWIFT);\n serverSwift.setStatus(service.getStatus());\n serverSwiftModel = new GlusterSwiftServiceModel(service);\n serverSwiftMap.put(service.getServerId(), serverSwiftModel);\n }\n serverSwiftModel.getInternalServiceList().add(service);\n }\n return new ArrayList(serverSwiftMap.values());\n }\n\n private void onManageGlusterSwiftServices() {\n if (getWindow() == null) {\n return;\n }\n\n ManageGlusterSwiftModel glusterSwiftModel = (ManageGlusterSwiftModel) getWindow();\n glusterSwiftModel.startProgress(null);\n if (glusterSwiftModel.getIsManageServerLevel().getEntity()) {\n ArrayList parametersList = new ArrayList();\n for (Object model : glusterSwiftModel.getHostServicesList().getItems()) {\n GlusterSwiftServiceModel swiftServiceModel = (GlusterSwiftServiceModel) model;\n GlusterSwiftAction action =\n getGlusterSwiftAction(swiftServiceModel.getEntity().getStatus(),\n swiftServiceModel.getStartSwift().getEntity(),\n swiftServiceModel.getStopSwift().getEntity(),\n swiftServiceModel.getRestartSwift().getEntity());\n if (action != null) {\n GlusterServiceParameters parameters =\n new GlusterServiceParameters(getEntity().getId(),\n swiftServiceModel.getEntity().getServerId(),\n ServiceType.GLUSTER_SWIFT,\n action.name().toLowerCase());\n parametersList.add(parameters);\n }\n }\n if (!parametersList.isEmpty()) {\n Frontend.getInstance().runMultipleAction(VdcActionType.ManageGlusterService,\n parametersList,\n true,\n new IFrontendMultipleActionAsyncCallback() {\n @Override\n public void executed(FrontendMultipleActionAsyncResult result) {\n ManageGlusterSwiftModel innerGlusterSwiftModel = (ManageGlusterSwiftModel) result.getState();\n innerGlusterSwiftModel.stopProgress();\n for (VdcReturnValueBase returnValueBase : result.getReturnValue()) {\n }\n cancel();\n updateGlusterDetails();\n }\n },\n glusterSwiftModel);\n }\n else {\n glusterSwiftModel.stopProgress();\n glusterSwiftModel.setMessage(ConstantsManager.getInstance()\n .getConstants()\n .noActionSelectedManageGlusterSwift());\n }\n }\n else {\n GlusterServiceStatus swiftStatus = glusterSwiftModel.getSwiftStatus().getEntity();\n GlusterSwiftAction action =\n getGlusterSwiftAction(swiftStatus,\n glusterSwiftModel.getStartSwift().getEntity(),\n glusterSwiftModel.getStopSwift().getEntity(),\n glusterSwiftModel.getRestartSwift().getEntity());\n if (action != null) {\n GlusterServiceParameters parameters =\n new GlusterServiceParameters(getEntity().getId(),\n null,\n ServiceType.GLUSTER_SWIFT,\n action.name().toLowerCase());\n Frontend.getInstance().runAction(VdcActionType.ManageGlusterService, parameters, new IFrontendActionAsyncCallback() {\n @Override\n public void executed(FrontendActionAsyncResult result) {\n ManageGlusterSwiftModel innerGlusterSwiftModel = (ManageGlusterSwiftModel) result.getState();\n innerGlusterSwiftModel.stopProgress();\n if (result.getReturnValue().getSucceeded()) {\n cancel();\n updateGlusterDetails();\n }\n }\n }, glusterSwiftModel);\n }\n else {\n glusterSwiftModel.stopProgress();\n glusterSwiftModel.setMessage(ConstantsManager.getInstance()\n .getConstants()\n .noActionSelectedManageGlusterSwift());\n }\n }\n }\n\n private GlusterSwiftAction getGlusterSwiftAction(GlusterServiceStatus currentStatus,\n boolean isStart,\n boolean isStop,\n boolean isRestart) {\n GlusterSwiftAction action = null;\n if (isStart) {\n action = GlusterSwiftAction.START;\n }\n else if (isStop) {\n action = GlusterSwiftAction.STOP;\n }\n else if (isRestart) {\n action = GlusterSwiftAction.RESTART;\n }\n return action;\n }\n\n public void fetchAndImportNewGlusterHosts() {\n if (getWindow() != null)\n {\n return;\n }\n\n final MultipleHostsModel hostsModel = new MultipleHostsModel();\n setWindow(hostsModel);\n hostsModel.setTitle(ConstantsManager.getInstance().getConstants().addMultipleHostsTitle());\n hostsModel.setHelpTag(HelpTag.add_hosts);\n hostsModel.setHashName(\"add_hosts\"); //$NON-NLS-1$\n\n UICommand command = new UICommand(\"OnSaveHosts\", this); //$NON-NLS-1$\n command.setTitle(ConstantsManager.getInstance().getConstants().ok());\n hostsModel.getCommands().add(command);\n hostsModel.getHosts().setItems(new ArrayList>());\n\n command = new UICommand(\"Cancel\", this); //$NON-NLS-1$\n command.setTitle(ConstantsManager.getInstance().getConstants().cancel());\n command.setIsCancel(true);\n hostsModel.getCommands().add(command);\n\n hostsModel.startProgress(null);\n\n AsyncQuery _asyncQuery = new AsyncQuery();\n _asyncQuery.setModel(this);\n _asyncQuery.asyncCallback = new INewAsyncCallback() {\n @Override\n public void onSuccess(Object model, Object result)\n {\n Map hostMap = (Map) result;\n\n if (hostMap == null || hostMap.isEmpty())\n {\n hostsModel.setMessage(ConstantsManager.getInstance().getConstants().emptyNewGlusterHosts());\n }\n else\n {\n ArrayList> list = new ArrayList>();\n for (Map.Entry host : hostMap.entrySet())\n {\n HostDetailModel hostModel = new HostDetailModel(host.getKey(), host.getValue());\n hostModel.setName(host.getKey());\n hostModel.setPassword(\"\");//$NON-NLS-1$\n EntityModel entityModel = new EntityModel(hostModel);\n list.add(entityModel);\n }\n hostsModel.getHosts().setItems(list);\n }\n hostsModel.stopProgress();\n }\n };\n AsyncDataProvider.getInstance().getGlusterHostsNewlyAdded(_asyncQuery, getEntity().getId(), true);\n\n }\n\n public void onSaveHosts() {\n final MultipleHostsModel hostsModel = (MultipleHostsModel) getWindow();\n if (hostsModel == null)\n {\n return;\n }\n if (!hostsModel.validate())\n {\n return;\n }\n\n hostsModel.startProgress(null);\n ArrayList parametersList = new ArrayList();\n for (Object object : hostsModel.getHosts().getItems()) {\n HostDetailModel hostDetailModel = (HostDetailModel) ((EntityModel) object).getEntity();\n\n VDS host = new VDS();\n host.setVdsName(hostDetailModel.getName());\n host.setHostName(hostDetailModel.getAddress());\n host.setSshKeyFingerprint(hostDetailModel.getFingerprint());\n host.setPort(54321);\n host.setSshPort(22); // TODO: get from UI, till than using defaults.\n host.setSshUsername(\"root\"); //$NON-NLS-1$\n\n host.setVdsGroupId(getEntity().getId());\n host.setpm_enabled(false);\n\n AddVdsActionParameters parameters = new AddVdsActionParameters();\n parameters.setVdsId(host.getId());\n parameters.setvds(host);\n parameters.setPassword(hostDetailModel.getPassword());\n parameters.setOverrideFirewall(hostsModel.isConfigureFirewall());\n parameters.setRebootAfterInstallation(getEntity().supportsVirtService());\n parametersList.add(parameters);\n }\n\n Frontend.getInstance().runMultipleAction(VdcActionType.AddVds,\n parametersList,\n true,\n new IFrontendMultipleActionAsyncCallback() {\n\n @Override\n public void executed(FrontendMultipleActionAsyncResult result) {\n hostsModel.stopProgress();\n boolean isAllCanDoPassed = true;\n for (VdcReturnValueBase returnValueBase : result.getReturnValue())\n {\n isAllCanDoPassed = isAllCanDoPassed && returnValueBase.getCanDoAction();\n if (!isAllCanDoPassed)\n {\n break;\n }\n }\n if (isAllCanDoPassed)\n {\n updateAlerts();\n cancel();\n }\n }\n }, null);\n }\n\n public void detachNewGlusterHosts()\n {\n if (getWindow() != null)\n {\n return;\n }\n\n final DetachGlusterHostsModel hostsModel = new DetachGlusterHostsModel();\n setWindow(hostsModel);\n hostsModel.setTitle(ConstantsManager.getInstance().getConstants().detachGlusterHostsTitle());\n hostsModel.setHelpTag(HelpTag.detach_gluster_hosts);\n hostsModel.setHashName(\"detach_gluster_hosts\"); //$NON-NLS-1$\n\n UICommand command = new UICommand(\"OnDetachGlusterHosts\", this); //$NON-NLS-1$\n command.setTitle(ConstantsManager.getInstance().getConstants().ok());\n hostsModel.getCommands().add(command);\n hostsModel.getHosts().setItems(new ArrayList>());\n\n command = new UICommand(\"Cancel\", this); //$NON-NLS-1$\n command.setTitle(ConstantsManager.getInstance().getConstants().cancel());\n command.setIsCancel(true);\n hostsModel.getCommands().add(command);\n\n hostsModel.startProgress(null);\n\n AsyncQuery _asyncQuery = new AsyncQuery();\n _asyncQuery.setModel(this);\n _asyncQuery.asyncCallback = new INewAsyncCallback() {\n @Override\n public void onSuccess(Object model, Object result)\n {\n Map hostMap = (Map) result;\n\n if (hostMap == null || hostMap.isEmpty())\n {\n hostsModel.setMessage(ConstantsManager.getInstance().getConstants().emptyNewGlusterHosts());\n }\n else\n {\n ArrayList> hostList = new ArrayList>();\n for (String host : hostMap.keySet())\n {\n hostList.add(new EntityModel(host));\n }\n hostsModel.getHosts().setItems(hostList);\n }\n hostsModel.stopProgress();\n }\n };\n AsyncDataProvider.getInstance().getGlusterHostsNewlyAdded(_asyncQuery, getEntity().getId(), true);\n }\n\n public void onDetachNewGlusterHosts()\n {\n if (getWindow() == null)\n {\n return;\n }\n\n final DetachGlusterHostsModel hostsModel = (DetachGlusterHostsModel) getWindow();\n if (!hostsModel.validate())\n {\n return;\n }\n boolean force = hostsModel.getForce().getEntity();\n ArrayList parametersList = new ArrayList();\n for (Object model : hostsModel.getHosts().getSelectedItems()) {\n String host = (String) ((EntityModel) model).getEntity();\n parametersList.add(new RemoveGlusterServerParameters(getEntity().getId(), host, force));\n }\n Frontend.getInstance().runMultipleAction(VdcActionType.RemoveGlusterServer, parametersList);\n cancel();\n }\n\n public void cancel()\n {\n setWindow(null);\n }\n\n\n private void updateGlusterDetails()\n {\n AsyncQuery _asyncQuery = new AsyncQuery();", "answers": [" _asyncQuery.setModel(this);"], "length": 1321, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "6ca7d59f-97f3-48d5-8b14-92777464e23b", "reasoning": "In the method updateGlusterDetails(), the code follows the same pattern as other async queries in the class: after creating a new AsyncQuery instance, the model is set with setModel(this) before assigning the asyncCallback. Therefore the next line should set the model on the AsyncQuery object.", "reasoning_model_answer": "_asyncQuery.setModel(this);", "assistant_with_reasoning": "\nIn the method updateGlusterDetails(), the code follows the same pattern as other async queries in the class: after creating a new AsyncQuery instance, the model is set with setModel(this) before assigning the asyncCallback. Therefore the next line should set the model on the AsyncQuery object.\n\n_asyncQuery.setModel(this);", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 5.759, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 27112, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "_asyncQuery.setModel(this);", "score": 0.87, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "#\n# Licensed to the Apache Software Foundation (ASF) under one or more\n# contributor license agreements. See the NOTICE file distributed with\n# this work for additional information regarding copyright ownership.\n# The ASF licenses this file to You under the Apache License, Version 2.0\n# (the \"License\"); you may not use this file except in compliance with\n# the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\n\"\"\"Unit tests for BigQuery sources and sinks.\"\"\"\n\nimport datetime\nimport json\nimport logging\nimport time\nimport unittest\n\nimport hamcrest as hc\nimport mock\n\nimport apache_beam as beam\nfrom apache_beam.io.google_cloud_platform.bigquery import RowAsDictJsonCoder\nfrom apache_beam.io.google_cloud_platform.bigquery import TableRowJsonCoder\nfrom apache_beam.io.google_cloud_platform.bigquery import parse_table_schema_from_json\nfrom apache_beam.io.google_cloud_platform.internal.clients import bigquery\nfrom apache_beam.internal.google_cloud_platform.json_value import to_json_value\nfrom apache_beam.transforms.display import DisplayData\nfrom apache_beam.transforms.display_test import DisplayDataItemMatcher\nfrom apache_beam.utils.pipeline_options import PipelineOptions\n\n# Protect against environments where bigquery library is not available.\n# pylint: disable=wrong-import-order, wrong-import-position\ntry:\n from apitools.base.py.exceptions import HttpError\nexcept ImportError:\n HttpError = None\n# pylint: enable=wrong-import-order, wrong-import-position\n\n\n@unittest.skipIf(HttpError is None, 'GCP dependencies are not installed')\nclass TestRowAsDictJsonCoder(unittest.TestCase):\n\n def test_row_as_dict(self):\n coder = RowAsDictJsonCoder()\n test_value = {'s': 'abc', 'i': 123, 'f': 123.456, 'b': True}\n self.assertEqual(test_value, coder.decode(coder.encode(test_value)))\n\n def json_compliance_exception(self, value):\n with self.assertRaises(ValueError) as exn:\n coder = RowAsDictJsonCoder()\n test_value = {'s': value}\n self.assertEqual(test_value, coder.decode(coder.encode(test_value)))\n self.assertTrue(bigquery.JSON_COMPLIANCE_ERROR in exn.exception.message)\n\n def test_invalid_json_nan(self):\n self.json_compliance_exception(float('nan'))\n\n def test_invalid_json_inf(self):\n self.json_compliance_exception(float('inf'))\n\n def test_invalid_json_neg_inf(self):\n self.json_compliance_exception(float('-inf'))\n\n\n@unittest.skipIf(HttpError is None, 'GCP dependencies are not installed')\nclass TestTableRowJsonCoder(unittest.TestCase):\n\n def test_row_as_table_row(self):\n schema_definition = [\n ('s', 'STRING'),\n ('i', 'INTEGER'),\n ('f', 'FLOAT'),\n ('b', 'BOOLEAN'),\n ('r', 'RECORD')]\n data_defination = [\n 'abc',\n 123,\n 123.456,\n True,\n {'a': 'b'}]\n str_def = '{\"s\": \"abc\", \"i\": 123, \"f\": 123.456, \"b\": true, \"r\": {\"a\": \"b\"}}'\n schema = bigquery.TableSchema(\n fields=[bigquery.TableFieldSchema(name=k, type=v)\n for k, v in schema_definition])\n coder = TableRowJsonCoder(table_schema=schema)\n test_row = bigquery.TableRow(\n f=[bigquery.TableCell(v=to_json_value(e)) for e in data_defination])\n\n self.assertEqual(str_def, coder.encode(test_row))\n self.assertEqual(test_row, coder.decode(coder.encode(test_row)))\n # A coder without schema can still decode.\n self.assertEqual(\n test_row, TableRowJsonCoder().decode(coder.encode(test_row)))\n\n def test_row_and_no_schema(self):\n coder = TableRowJsonCoder()\n test_row = bigquery.TableRow(\n f=[bigquery.TableCell(v=to_json_value(e))\n for e in ['abc', 123, 123.456, True]])\n with self.assertRaises(AttributeError) as ctx:\n coder.encode(test_row)\n self.assertTrue(\n ctx.exception.message.startswith('The TableRowJsonCoder requires'))\n\n def json_compliance_exception(self, value):\n with self.assertRaises(ValueError) as exn:\n schema_definition = [('f', 'FLOAT')]\n schema = bigquery.TableSchema(\n fields=[bigquery.TableFieldSchema(name=k, type=v)\n for k, v in schema_definition])\n coder = TableRowJsonCoder(table_schema=schema)\n test_row = bigquery.TableRow(\n f=[bigquery.TableCell(v=to_json_value(value))])\n coder.encode(test_row)\n self.assertTrue(bigquery.JSON_COMPLIANCE_ERROR in exn.exception.message)\n\n def test_invalid_json_nan(self):\n self.json_compliance_exception(float('nan'))\n\n def test_invalid_json_inf(self):\n self.json_compliance_exception(float('inf'))\n\n def test_invalid_json_neg_inf(self):\n self.json_compliance_exception(float('-inf'))\n\n\n@unittest.skipIf(HttpError is None, 'GCP dependencies are not installed')\nclass TestTableSchemaParser(unittest.TestCase):\n def test_parse_table_schema_from_json(self):\n string_field = bigquery.TableFieldSchema(\n name='s', type='STRING', mode='NULLABLE', description='s description')\n number_field = bigquery.TableFieldSchema(\n name='n', type='INTEGER', mode='REQUIRED', description='n description')\n record_field = bigquery.TableFieldSchema(\n name='r', type='RECORD', mode='REQUIRED', description='r description',\n fields=[string_field, number_field])\n expected_schema = bigquery.TableSchema(fields=[record_field])\n json_str = json.dumps({'fields': [\n {'name': 'r', 'type': 'RECORD', 'mode': 'REQUIRED',\n 'description': 'r description', 'fields': [\n {'name': 's', 'type': 'STRING', 'mode': 'NULLABLE',\n 'description': 's description'},\n {'name': 'n', 'type': 'INTEGER', 'mode': 'REQUIRED',\n 'description': 'n description'}]}]})\n self.assertEqual(parse_table_schema_from_json(json_str),\n expected_schema)\n\n\n@unittest.skipIf(HttpError is None, 'GCP dependencies are not installed')\nclass TestBigQuerySource(unittest.TestCase):\n\n def test_display_data_item_on_validate_true(self):\n source = beam.io.BigQuerySource('dataset.table', validate=True)\n\n dd = DisplayData.create_from(source)\n expected_items = [\n DisplayDataItemMatcher('validation', True),\n DisplayDataItemMatcher('table', 'dataset.table')]\n hc.assert_that(dd.items, hc.contains_inanyorder(*expected_items))\n\n def test_table_reference_display_data(self):\n source = beam.io.BigQuerySource('dataset.table')\n dd = DisplayData.create_from(source)\n expected_items = [\n DisplayDataItemMatcher('validation', False),\n DisplayDataItemMatcher('table', 'dataset.table')]\n hc.assert_that(dd.items, hc.contains_inanyorder(*expected_items))\n\n source = beam.io.BigQuerySource('project:dataset.table')\n dd = DisplayData.create_from(source)\n expected_items = [\n DisplayDataItemMatcher('validation', False),\n DisplayDataItemMatcher('table', 'project:dataset.table')]\n hc.assert_that(dd.items, hc.contains_inanyorder(*expected_items))\n\n source = beam.io.BigQuerySource('xyz.com:project:dataset.table')\n dd = DisplayData.create_from(source)\n expected_items = [\n DisplayDataItemMatcher('validation',\n False),\n DisplayDataItemMatcher('table',\n 'xyz.com:project:dataset.table')]\n hc.assert_that(dd.items, hc.contains_inanyorder(*expected_items))\n\n def test_parse_table_reference(self):\n source = beam.io.BigQuerySource('dataset.table')\n self.assertEqual(source.table_reference.datasetId, 'dataset')\n self.assertEqual(source.table_reference.tableId, 'table')\n\n source = beam.io.BigQuerySource('project:dataset.table')\n self.assertEqual(source.table_reference.projectId, 'project')\n self.assertEqual(source.table_reference.datasetId, 'dataset')\n self.assertEqual(source.table_reference.tableId, 'table')\n\n source = beam.io.BigQuerySource('xyz.com:project:dataset.table')\n self.assertEqual(source.table_reference.projectId, 'xyz.com:project')\n self.assertEqual(source.table_reference.datasetId, 'dataset')\n self.assertEqual(source.table_reference.tableId, 'table')\n\n source = beam.io.BigQuerySource(query='my_query')\n self.assertEqual(source.query, 'my_query')\n self.assertIsNone(source.table_reference)\n self.assertTrue(source.use_legacy_sql)\n\n def test_query_only_display_data(self):\n source = beam.io.BigQuerySource(query='my_query')\n dd = DisplayData.create_from(source)\n expected_items = [\n DisplayDataItemMatcher('validation', False),\n DisplayDataItemMatcher('query', 'my_query')]\n hc.assert_that(dd.items, hc.contains_inanyorder(*expected_items))\n\n def test_specify_query_sql_format(self):\n source = beam.io.BigQuerySource(query='my_query', use_standard_sql=True)\n self.assertEqual(source.query, 'my_query')\n self.assertFalse(source.use_legacy_sql)\n\n def test_specify_query_flattened_records(self):\n source = beam.io.BigQuerySource(query='my_query', flatten_results=False)\n self.assertFalse(source.flatten_results)\n\n def test_specify_query_unflattened_records(self):\n source = beam.io.BigQuerySource(query='my_query', flatten_results=True)\n self.assertTrue(source.flatten_results)\n\n def test_specify_query_without_table(self):\n source = beam.io.BigQuerySource(query='my_query')\n self.assertEqual(source.query, 'my_query')\n self.assertIsNone(source.table_reference)\n\n def test_date_partitioned_table_name(self):\n source = beam.io.BigQuerySource('dataset.table$20030102', validate=True)\n dd = DisplayData.create_from(source)\n expected_items = [\n DisplayDataItemMatcher('validation', True),\n DisplayDataItemMatcher('table', 'dataset.table$20030102')]\n hc.assert_that(dd.items, hc.contains_inanyorder(*expected_items))\n\n\n@unittest.skipIf(HttpError is None, 'GCP dependencies are not installed')\nclass TestBigQuerySink(unittest.TestCase):\n\n def test_table_spec_display_data(self):\n sink = beam.io.BigQuerySink('dataset.table')\n dd = DisplayData.create_from(sink)\n expected_items = [\n DisplayDataItemMatcher('table', 'dataset.table'),\n DisplayDataItemMatcher('validation', False)]\n hc.assert_that(dd.items, hc.contains_inanyorder(*expected_items))\n\n def test_parse_schema_descriptor(self):\n sink = beam.io.BigQuerySink(\n 'dataset.table', schema='s:STRING, n:INTEGER')\n self.assertEqual(sink.table_reference.datasetId, 'dataset')\n self.assertEqual(sink.table_reference.tableId, 'table')\n result_schema = {\n field.name: field.type for field in sink.table_schema.fields}\n self.assertEqual({'n': 'INTEGER', 's': 'STRING'}, result_schema)\n\n def test_project_table_display_data(self):\n sinkq = beam.io.BigQuerySink('PROJECT:dataset.table')\n dd = DisplayData.create_from(sinkq)\n expected_items = [\n DisplayDataItemMatcher('table', 'PROJECT:dataset.table'),\n DisplayDataItemMatcher('validation', False)]\n hc.assert_that(dd.items, hc.contains_inanyorder(*expected_items))\n\n def test_simple_schema_as_json(self):\n sink = beam.io.BigQuerySink(\n 'PROJECT:dataset.table', schema='s:STRING, n:INTEGER')\n self.assertEqual(\n json.dumps({'fields': [\n {'name': 's', 'type': 'STRING', 'mode': 'NULLABLE'},\n {'name': 'n', 'type': 'INTEGER', 'mode': 'NULLABLE'}]}),\n sink.schema_as_json())\n\n def test_nested_schema_as_json(self):\n string_field = bigquery.TableFieldSchema(\n name='s', type='STRING', mode='NULLABLE', description='s description')\n number_field = bigquery.TableFieldSchema(\n name='n', type='INTEGER', mode='REQUIRED', description='n description')\n record_field = bigquery.TableFieldSchema(\n name='r', type='RECORD', mode='REQUIRED', description='r description',\n fields=[string_field, number_field])\n schema = bigquery.TableSchema(fields=[record_field])\n sink = beam.io.BigQuerySink('dataset.table', schema=schema)\n self.assertEqual(\n {'fields': [\n {'name': 'r', 'type': 'RECORD', 'mode': 'REQUIRED',\n 'description': 'r description', 'fields': [\n {'name': 's', 'type': 'STRING', 'mode': 'NULLABLE',\n 'description': 's description'},\n {'name': 'n', 'type': 'INTEGER', 'mode': 'REQUIRED',\n 'description': 'n description'}]}]},\n json.loads(sink.schema_as_json()))\n\n\n@unittest.skipIf(HttpError is None, 'GCP dependencies are not installed')\nclass TestBigQueryReader(unittest.TestCase):\n\n def get_test_rows(self):\n now = time.time()\n dt = datetime.datetime.utcfromtimestamp(float(now))\n ts = dt.strftime('%Y-%m-%d %H:%M:%S.%f UTC')\n expected_rows = [\n {\n 'i': 1,\n 's': 'abc',\n 'f': 2.3,\n 'b': True,\n 't': ts,\n 'dt': '2016-10-31',\n 'ts': '22:39:12.627498',\n 'dt_ts': '2008-12-25T07:30:00',\n 'r': {'s2': 'b'},\n 'rpr': [{'s3': 'c', 'rpr2': [{'rs': ['d', 'e'], 's4': None}]}]\n },\n {\n 'i': 10,\n 's': 'xyz',\n 'f': -3.14,\n 'b': False,\n 'rpr': [],\n 't': None,\n 'dt': None,\n 'ts': None,\n 'dt_ts': None,\n 'r': None,\n }]\n\n nested_schema = [\n bigquery.TableFieldSchema(\n name='s2', type='STRING', mode='NULLABLE')]\n nested_schema_2 = [\n bigquery.TableFieldSchema(\n name='s3', type='STRING', mode='NULLABLE'),\n bigquery.TableFieldSchema(\n name='rpr2', type='RECORD', mode='REPEATED', fields=[\n bigquery.TableFieldSchema(\n name='rs', type='STRING', mode='REPEATED'),\n bigquery.TableFieldSchema(", "answers": [" name='s4', type='STRING', mode='NULLABLE')])]"], "length": 939, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "b66cfe6a-bd7d-47ea-8c73-780ac8fe2623", "reasoning": "The code is defining nested_schema_2, a list of TableFieldSchema objects. Inside the definition of the 'rpr2' RECORD field, the fields list includes a TableFieldSchema for 'rs' and then starts a new TableFieldSchema. The next logical line completes this second TableFieldSchema, specifying the name, type, and mode for the 's4' field, matching the expected row structure where 's4' appears. Therefore the next line should be the continuation of that TableFieldSchema call: name='s4', type='STRING', mode='NULLABLE').", "reasoning_model_answer": "name='s4', type='STRING', mode='NULLABLE')", "assistant_with_reasoning": "\nThe code is defining nested_schema_2, a list of TableFieldSchema objects. Inside the definition of the 'rpr2' RECORD field, the fields list includes a TableFieldSchema for 'rs' and then starts a new TableFieldSchema. The next logical line completes this second TableFieldSchema, specifying the name, type, and mode for the 's4' field, matching the expected row structure where 's4' appears. Therefore the next line should be the continuation of that TableFieldSchema call: name='s4', type='STRING', mode='NULLABLE').\n\nname='s4', type='STRING', mode='NULLABLE')", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 6.879, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 2, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 14165, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "name='s4', type='STRING', mode='NULLABLE')", "score": 0.79, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "package com.mgatelabs.swftools.exploit.gui;\n\nimport com.mgatelabs.swftools.exploit.hook.BlockEditInterface;\nimport com.mgatelabs.swftools.support.filters.CommonFileFilter;\nimport com.mgatelabs.swftools.support.plugins.BlockPlugin;\nimport com.mgatelabs.swftools.support.plugins.Plugin;\nimport com.mgatelabs.swftools.support.swf.io.BlockIO;\nimport com.mgatelabs.swftools.support.swf.objects.FMovie;\nimport com.mgatelabs.swftools.support.swf.tags.TBlock;\n\nimport javax.swing.*;\nimport java.awt.*;\nimport java.awt.event.ActionEvent;\nimport java.awt.event.ActionListener;\nimport java.io.File;\nimport java.util.StringTokenizer;\nimport java.util.Vector;\n\npublic class BlockEditDialog extends GuiInternal implements BlockEditInterface {\n //Variables\n private BlockEditDialog mySelf;\n\n private ExploitActionListener myExploitActionListener;\n //private FormMouseListener myFormMouseListener;\n\n private JMenuItem menuFileOpen;\n private JMenuItem menuFileClose;\n private JMenuItem menuFileSave;\n private JMenuItem menuFileSaveCompress;\n\n private JMenu menuRoot, menuEdit;\n\n private JMenuItem menuExportData;\n private JMenuItem menuExportBlock;\n\n private JMenuItem menuEditCopy;\n private JMenuItem menuEditCut;\n private JMenuItem menuEditPaste;\n\n private JMenuItem menuBlockRemove;\n private JMenuItem menuBlockReplace;\n private JMenuItem menuBlockInsert;\n private JMenuItem menuBlockId;\n private JMenuItem menuAlterVersion;\n\n private JFileChooser myJFileChooser;\n\n private JDesktopPane jde;\n\n private JFrame myMaster;\n\n private Vector myWindows;\n\n private Vector myPlugins;\n\n private TBlock copyBuffer;\n\n public BlockEditDialog(JFrame master) {\n super(\"Block Editor (Beta)\", false, false, (master != null), false);\n\n this.setFrameIcon(new ImageIcon(this.getClass().getResource(\"/com/mgatelabs/swftools/exploit/gui/images/block.png\")));\n\n myWindows = new Vector();\n myPlugins = null;\n copyBuffer = null;\n\n myMaster = master;\n //myVector = null;\n //myMovie = null;\n\n mySelf = this;\n\n buildControls();\n\n menuMaster(false);\n\n this.getContentPane().add(buildGui());\n this.pack();\n }\n\n // Frame Information\n public JFrame getFrame() {\n return myMaster;\n }\n\n // Plugin Updates\n\n public void updateMenuWithPlugins(Vector plugins) {\n myPlugins = plugins;\n\n for (int x = 0; x < plugins.size(); x++) {\n Plugin p = (Plugin) plugins.get(x);\n if (p.getType() == Plugin.BLOCK) {\n if (p instanceof BlockPlugin) {\n BlockPlugin bp = (BlockPlugin) p;\n // Get the Proposed Menu Path\n StringTokenizer st = new StringTokenizer(bp.getMenuPath(), \":\");\n JMenu targetMenu = menuRoot;\n while (st.hasMoreElements()) {\n String tName = st.nextToken();\n if (tName.length() > 0) {\n targetMenu = findSubMenu(targetMenu, tName);\n }\n }\n\n JMenuItem aItem = new JMenuItem(bp.getMenuName());\n aItem.setActionCommand(\"!\" + x);\n\n targetMenu.add(aItem);\n aItem.addActionListener(myExploitActionListener);\n }\n }\n //menuRoot\n }\n }\n\n public JMenu findSubMenu(JMenu parent, String name) {\n Component[] cm = parent.getMenuComponents();\n\n for (int x = 0; x < cm.length; x++) {\n if (cm[x] instanceof JMenu) {\n JMenu aMenu = (JMenu) cm[x];\n if (aMenu.getText().trim().equals(name)) {\n return aMenu;\n }\n }\n }\n\n JMenu nMenu = new JMenu(name);\n\n parent.add(nMenu);\n\n return nMenu;\n }\n\n // Controls\n\n private void buildControls() {\n myJFileChooser = new JFileChooser(new File(\".\"));\n myJFileChooser.setFileFilter(new CommonFileFilter(\".swf\", \"Adobe Flash Files\"));\n\n myExploitActionListener = new ExploitActionListener();\n\n menuFileOpen = new JMenuItem(\"Open\");\n menuFileClose = new JMenuItem(\"Close\");\n menuFileSave = new JMenuItem(\"Save\");\n menuFileSaveCompress = new JMenuItem(\"Save (Compress)\");\n\n menuExportData = new JMenuItem(\"Data\");\n menuExportBlock = new JMenuItem(\"Block\");\n\n menuEditCopy = new JMenuItem(\"Copy\");\n menuEditCut = new JMenuItem(\"Cut\");\n menuEditPaste = new JMenuItem(\"Paste\");\n\n menuBlockRemove = new JMenuItem(\"Remove\");\n menuBlockReplace = new JMenuItem(\"Replace\");\n menuBlockInsert = new JMenuItem(\"Insert (Above)\");\n menuAlterVersion = new JMenuItem(\"Alter Version\");\n\n menuEditCopy.addActionListener(myExploitActionListener);\n menuEditCut.addActionListener(myExploitActionListener);\n menuEditPaste.addActionListener(myExploitActionListener);\n\n menuFileOpen.addActionListener(myExploitActionListener);\n menuFileClose.addActionListener(myExploitActionListener);\n menuFileSave.addActionListener(myExploitActionListener);\n menuFileSaveCompress.addActionListener(myExploitActionListener);\n\n menuExportData.addActionListener(myExploitActionListener);\n menuExportBlock.addActionListener(myExploitActionListener);\n\n menuBlockRemove.addActionListener(myExploitActionListener);\n menuBlockReplace.addActionListener(myExploitActionListener);\n menuBlockInsert.addActionListener(myExploitActionListener);\n menuAlterVersion.addActionListener(myExploitActionListener);\n //menuBlockId.addActionListener(myExploitActionListener);\n\n JMenuBar myMenuBar = new JMenuBar();\n\n JMenu menuFile = new JMenu(\"File\");\n\n menuFile.add(menuFileOpen);\n menuFile.add(menuFileClose);\n menuFile.addSeparator();\n menuFile.add(menuFileSave);\n menuFile.add(menuFileSaveCompress);\n\n myMenuBar.add(menuFile);\n\n menuEdit = new JMenu(\"Edit\");\n\n menuEdit.add(menuEditCopy);\n menuEdit.add(menuEditCut);\n menuEdit.add(menuEditPaste);\n\n myMenuBar.add(menuEdit);\n\n menuRoot = new JMenu(\"Plugins\");\n\n JMenu menuExport = new JMenu(\"Export\");\n JMenu menuEdit = new JMenu(\"Edit\");\n JMenu menuBuiltIn = new JMenu(\"Built-In\");\n\n menuExport.add(menuExportData);\n menuExport.add(menuExportBlock);\n\n menuRoot.add(menuExport);\n menuRoot.add(menuEdit);\n menuRoot.add(menuBuiltIn);\n\n menuBuiltIn.add(menuBlockRemove);\n menuBuiltIn.add(menuBlockReplace);\n menuBuiltIn.addSeparator();\n menuBuiltIn.add(menuBlockInsert);\n menuBuiltIn.addSeparator();\n menuBuiltIn.add(menuAlterVersion);\n\n\n myMenuBar.add(menuRoot);\n\n this.setJMenuBar(myMenuBar);\n }\n\n // Form Building\n\n private JPanel buildGui() {\n JPanel master = new JPanel();\n master.setLayout(new BoxLayout(master, BoxLayout.X_AXIS));\n\n jde = new JDesktopPane();\n jde.setDragMode(jde.OUTLINE_DRAG_MODE);\n\n master.add(jde);\n\n return master;\n }\n\n ////////////////////////////////////////////////////////////////////////////\n\n private void menuMaster(boolean open) {\n menuFileClose.setEnabled(open);\n menuFileSave.setEnabled(open);\n menuFileSaveCompress.setEnabled(open);\n\n menuRoot.setEnabled(open);\n menuEdit.setEnabled(open);\n }\n\n ////////////////////////////////////////////////////////////////////////////\n\n private void clear() {\n menuMaster(false);\n }\n\n // IO Functions/////////////////////////////////////////////////////////////\n\n private boolean loadFlash(File aFile) {\n try {\n // Get the Reader\n BlockIO bio = new BlockIO();\n\n Object[] objects = bio.readFlash(aFile);\n\n BlockEditInternal bei = new BlockEditInternal(aFile, (FMovie) objects[0], (Vector) objects[1]);\n\n GuiInternal gi = new GuiInternal(bei, aFile.getName(), 320, 480, true, true);\n\n gi.setFrameIcon(new ImageIcon(this.getClass().getResource(\"/com/mgatelabs/swftools/exploit/gui/images/flash.png\")));\n\n myWindows.add(gi);\n\n jde.add(gi);\n\n gi.show();\n\n menuMaster(true);\n\n return true;\n } catch (Exception e) {\n e.printStackTrace();\n\n JOptionPane.showMessageDialog(mySelf, \"Java has experienced an error, most likely\\ndue to running out of ram.\\nPlease close this program and run\\nit with a higher ram setting.\" + \"\\n\\n\" + e, \"Error\", JOptionPane.ERROR_MESSAGE);\n\n return false;\n }\n }\n\n private BlockEditInternal getTopWindow() {\n GuiInternal gi = (GuiInternal) jde.getSelectedFrame();\n JComponent jc = gi.getComponent();\n if (jc instanceof BlockEditInternal) {\n return (BlockEditInternal) jc;\n } else {\n return null;\n }\n }\n\n private boolean saveFlash(File aFile, boolean compress) {\n BlockEditInternal bei = getTopWindow();\n if (bei == null) {\n return false;\n }\n\n try {\n // Get the Reader\n BlockIO bio = new BlockIO();\n\n FMovie aMovie = bei.getMovie();// myMovieInfo.get();\n\n if (aMovie == null) {\n JOptionPane.showMessageDialog(mySelf, \"There is a error in the movie information on the right side of the window.\", \"Error\", JOptionPane.ERROR_MESSAGE);\n return false;\n } else {\n if (bio.writeFlash(aFile, aMovie, bei.getObjects(), compress)) {\n }\n }\n return true;\n } catch (Exception e) {\n e.printStackTrace();\n JOptionPane.showMessageDialog(mySelf, \"Java has experienced an error, most likely\\ndue to running out of ram.\\nPlease close this program and run\\nit with a higher ram setting.\" + \"\\n\\n\" + e, \"Error\", JOptionPane.ERROR_MESSAGE);\n return false;\n }\n\n }\n\n public TBlock getSelectedBlock() {\n BlockEditInternal bei = getTopWindow();\n if (bei == null) {\n return null;\n }\n\n return bei.getSelectedObject();\n }\n\n public int getSelectedIndex() {\n BlockEditInternal bei = getTopWindow();\n if (bei == null) {\n return -1;\n }\n\n return bei.getSelectedIndex();\n }\n\n public TBlock getBlock(int index) {\n BlockEditInternal bei = getTopWindow();\n if (bei == null) {\n return null;\n }\n\n Vector dlo = bei.getObjects();\n\n if (index >= 0 && index < dlo.size()) {\n return (TBlock) dlo.get(index);\n }\n\n return null;\n }\n\n // Special Access\n public boolean copyBlock(int index) {\n TBlock aBlock = getBlock(index);\n if (aBlock != null) {\n copyBuffer = aBlock;\n aBlock = null;\n return true;\n } else {\n return false;\n }\n }\n\n public boolean cutBlock(int index) {\n if (copyBlock(index)) {\n return removeBlock(index);\n }\n return false;\n }\n\n public boolean pasteBlock(int index) {\n if (copyBuffer != null) {\n return insertBlock(index, copyBuffer);\n }\n return false;\n }\n\n public boolean replaceBlock(int index, TBlock aBlock) {\n BlockEditInternal bei = getTopWindow();\n if (bei == null) {\n return false;\n }\n\n DefaultListModel dlm = bei.getModel();\n Vector dlo = bei.getObjects();\n\n dlo.set(index, aBlock);\n dlm.set(index, aBlock);\n\n bei.update(dlm);\n\n return false;\n }\n\n public void alterVersionNumber() {\n BlockEditInternal bei = getTopWindow();\n if (bei == null) {\n return;\n }\n\n FMovie m = bei.getMovie();\n\n int i = m.getVersion();\n i--;\n\n if (i < 0 || i > 14) {\n i = 9;\n }\n\n String[] versions = {\"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"10\", \"11\", \"12\", \"13\", \"14\", \"15\"};\n\n String selectedValue = (String) JOptionPane.showInputDialog(null,\n\n \"Version\", \"Alter Flash Version\",\n\n JOptionPane.INFORMATION_MESSAGE, null,\n\n versions, (String) versions[i]);\n\n if (selectedValue != null && selectedValue.length() > 0) {\n try {\n i = Integer.parseInt(selectedValue);\n m.setVersion(i);\n bei.updateMovieInfo();\n } catch (Exception ex) {\n JOptionPane.showMessageDialog(null, \"Could not alter flash version\", \"Internal Error\", JOptionPane.ERROR_MESSAGE);\n }\n }\n\n }\n\n public void updateList() {\n BlockEditInternal bei = getTopWindow();\n if (bei == null) {\n return;\n }\n\n DefaultListModel dlm = bei.getModel();\n\n bei.update(dlm);\n }\n\n public int getObjectCount() {\n BlockEditInternal bei = getTopWindow();\n if (bei == null) {\n return -1;\n }\n\n Vector dlo = bei.getObjects();\n\n return dlo.size();\n }\n\n ////////////////////////////////////////////////////////////////////////////\n // Save Block\n\n public boolean saveBlock(int index, File aPath) {\n BlockEditInternal bei = getTopWindow();\n if (bei == null) {\n return false;\n }\n\n if (index < 0) {\n return false;\n }\n\n try {\n // Get the Reader\n BlockIO bio = new BlockIO();\n\n TBlock aBlock = bei.getObjectAtIndex(index);\n\n if (aBlock != null) {\n FMovie aMovie = bei.getMovie();// myMovieInfo.get();\n\n bio.writeBlock(aPath, aMovie, aBlock);\n }\n\n return true;\n } catch (Exception e) {\n e.printStackTrace();\n\n JOptionPane.showMessageDialog(mySelf, \"Java has experienced an error, most likely\\ndue to running out of ram.\\nPlease close this program and run\\nit with a higher ram setting.\" + \"\\n\\n\" + e, \"Error\", JOptionPane.ERROR_MESSAGE);\n }\n\n return false;\n }\n\n ////////////////////////////////////////////////////////////////////////////\n // Save Data\n\n public boolean saveData(int index, File aFile) {\n BlockEditInternal bei = getTopWindow();\n if (bei == null) {\n return false;\n }\n\n if (index < 0) {\n return false;\n }\n\n try {\n // Get the Reader\n BlockIO bio = new BlockIO();\n\n TBlock aBlock = bei.getObjectAtIndex(index);", "answers": [" if (aBlock != null) {"], "length": 1191, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "6c254a3b-8941-43c1-9ec0-a3618337901e", "reasoning": "The method saveData is analogous to saveBlock: after obtaining the block with getObjectAtIndex, the next step is to check if the block is non‑null before writing its data. Therefore the immediate next line after the retrieved aBlock assignment is the null‑check conditional.", "reasoning_model_answer": "if (aBlock != null) {", "assistant_with_reasoning": "\nThe method saveData is analogous to saveBlock: after obtaining the block with getObjectAtIndex, the next step is to check if the block is non‑null before writing its data. Therefore the immediate next line after the retrieved aBlock assignment is the null‑check conditional.\n\nif (aBlock != null) {", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.918, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 14962, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "if (aBlock != null) {", "score": 0.78, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "# Copyright 2012 Nicira Networks, Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n#\n# @author: Somik Behera, Nicira Networks, Inc.\n# @author: Brad Hall, Nicira Networks, Inc.\n\nimport ConfigParser\nimport logging\nimport os\nimport sys\n\nimport NvpApiClient\nimport nvplib\n\nfrom quantum.common import exceptions as exception\nfrom quantum.plugins.nicira.nicira_nvp_plugin.api_client.client_eventlet \\\n import (\n DEFAULT_CONCURRENT_CONNECTIONS,\n DEFAULT_FAILOVER_TIME,\n )\nfrom quantum.plugins.nicira.nicira_nvp_plugin.api_client.request_eventlet \\\n import (\n DEFAULT_REQUEST_TIMEOUT,\n DEFAULT_HTTP_TIMEOUT,\n DEFAULT_RETRIES,\n DEFAULT_REDIRECTS,\n )\n\n\nLOG = logging.getLogger(\"QuantumPlugin\")\n\n\nCONFIG_FILE = \"nvp.ini\"\nCONFIG_FILE_PATHS = []\nif os.environ.get('QUANTUM_HOME', None):\n CONFIG_FILE_PATHS.append('%s/etc' % os.environ['QUANTUM_HOME'])\nCONFIG_FILE_PATHS.append(\"/etc/quantum/plugins/nicira\")\nCONFIG_KEYS = [\"DEFAULT_TZ_UUID\", \"NVP_CONTROLLER_IP\", \"PORT\", \"USER\",\n \"PASSWORD\"]\n\n\ndef initConfig(cfile=None):\n config = ConfigParser.ConfigParser()\n if cfile is None:\n if os.path.exists(CONFIG_FILE):\n cfile = CONFIG_FILE\n else:\n cfile = find_config(os.path.abspath(os.path.dirname(__file__)))\n\n if cfile is None:\n raise Exception(\"Configuration file \\\"%s\\\" doesn't exist\" % (cfile))\n LOG.info(\"Using configuration file: %s\" % cfile)\n config.read(cfile)\n LOG.debug(\"Config: %s\" % config)\n return config\n\n\ndef find_config(basepath):\n LOG.info(\"Looking for %s in %s\" % (CONFIG_FILE, basepath))\n for root, dirs, files in os.walk(basepath, followlinks=True):\n if CONFIG_FILE in files:\n return os.path.join(root, CONFIG_FILE)\n for alternate_path in CONFIG_FILE_PATHS:\n p = os.path.join(alternate_path, CONFIG_FILE)\n if os.path.exists(p):\n return p\n return None\n\n\ndef parse_config(config):\n \"\"\"Backwards compatible parsing.\n\n :param config: ConfigParser object initilized with nvp.ini.\n :returns: A tuple consisting of a control cluster object and a\n plugin_config variable.\n raises: In general, system exceptions are not caught but are propagated\n up to the user. Config parsing is still very lightweight.\n At some point, error handling needs to be significantly\n enhanced to provide user friendly error messages, clean program\n exists, rather than exceptions propagated to the user.\n \"\"\"\n # Extract plugin config parameters.\n try:\n failover_time = config.get('NVP', 'failover_time')\n except ConfigParser.NoOptionError, e:\n failover_time = str(DEFAULT_FAILOVER_TIME)\n\n try:\n concurrent_connections = config.get('NVP', 'concurrent_connections')\n except ConfigParser.NoOptionError, e:\n concurrent_connections = str(DEFAULT_CONCURRENT_CONNECTIONS)\n\n plugin_config = {\n 'failover_time': failover_time,\n 'concurrent_connections': concurrent_connections,\n }\n LOG.info('parse_config(): plugin_config == \"%s\"' % plugin_config)\n\n cluster = NVPCluster('cluster1')\n\n # Extract connection information.\n try:\n defined_connections = config.get('NVP', 'NVP_CONTROLLER_CONNECTIONS')\n\n for conn_key in defined_connections.split():\n args = [config.get('NVP', 'DEFAULT_TZ_UUID')]\n args.extend(config.get('NVP', conn_key).split(':'))\n try:\n cluster.add_controller(*args)\n except Exception, e:\n LOG.fatal('Invalid connection parameters: %s' % str(e))\n sys.exit(1)\n\n return cluster, plugin_config\n except Exception, e:\n LOG.info('No new style connections defined: %s' % e)\n\n # Old style controller specification.\n args = [config.get('NVP', k) for k in CONFIG_KEYS]\n try:\n cluster.add_controller(*args)\n except Exception, e:\n LOG.fatal('Invalid connection parameters.')\n sys.exit(1)\n\n return cluster, plugin_config\n\n\nclass NVPCluster(object):\n \"\"\"Encapsulates controller connection and api_client.\n\n Initialized within parse_config().\n Accessed within the NvpPlugin class.\n\n Each element in the self.controllers list is a dictionary that\n contains the following keys:\n ip, port, user, password, default_tz_uuid\n\n There may be some redundancy here, but that has been done to provide\n future flexibility.\n \"\"\"\n def __init__(self, name):\n self._name = name\n self.controllers = []\n self.api_client = None\n\n def __repr__(self):\n ss = ['{ \"NVPCluster\": [']\n ss.append('{ \"name\" : \"%s\" }' % self.name)\n ss.append(',')\n for c in self.controllers:\n ss.append(str(c))\n ss.append(',')\n ss.append('] }')\n return ''.join(ss)\n\n def add_controller(self, default_tz_uuid, ip, port, user, password,\n request_timeout=DEFAULT_REQUEST_TIMEOUT,\n http_timeout=DEFAULT_HTTP_TIMEOUT,\n retries=DEFAULT_RETRIES, redirects=DEFAULT_REDIRECTS):\n \"\"\"Add a new set of controller parameters.\n\n :param ip: IP address of controller.\n :param port: port controller is listening on.\n :param user: user name.\n :param password: user password.\n :param request_timeout: timeout for an entire API request.\n :param http_timeout: timeout for a connect to a controller.\n :param retries: maximum number of request retries.\n :param redirects: maximum number of server redirect responses to\n follow.\n :param default_tz_uuid: default transport zone uuid.\n \"\"\"\n\n keys = ['ip', 'port', 'user', 'password', 'default_tz_uuid']\n controller_dict = dict([(k, locals()[k]) for k in keys])\n\n int_keys = ['request_timeout', 'http_timeout', 'retries', 'redirects']\n for k in int_keys:\n controller_dict[k] = int(locals()[k])\n\n self.controllers.append(controller_dict)\n\n def get_controller(self, idx):\n return self.controllers[idx]\n\n @property\n def name(self):\n return self._name\n\n @name.setter\n def name(self, val=None):\n self._name = val\n\n @property\n def host(self):\n return self.controllers[0]['ip']\n\n @property\n def port(self):\n return self.controllers[0]['port']\n\n @property\n def user(self):\n return self.controllers[0]['user']\n\n @property\n def password(self):\n return self.controllers[0]['password']\n\n @property\n def request_timeout(self):\n return self.controllers[0]['request_timeout']\n\n @property\n def http_timeout(self):\n return self.controllers[0]['http_timeout']\n\n @property\n def retries(self):\n return self.controllers[0]['retries']\n\n @property\n def redirects(self):\n return self.controllers[0]['redirects']\n\n @property\n def default_tz_uuid(self):\n return self.controllers[0]['default_tz_uuid']\n\n\nclass NvpPlugin(object):\n \"\"\"\n NvpPlugin is a Quantum plugin that provides L2 Virtual Network\n functionality using NVP.\n \"\"\"\n supported_extension_aliases = [\"portstats\"]\n\n def __init__(self, configfile=None, loglevel=None, cli=False):\n if loglevel:\n logging.basicConfig(level=loglevel)\n nvplib.LOG.setLevel(loglevel)\n NvpApiClient.LOG.setLevel(loglevel)\n\n config = initConfig(configfile)\n self.controller, self.plugin_config = parse_config(config)\n c = self.controller\n api_providers = [(x['ip'], x['port'], True) for x in c.controllers]\n\n c.api_client = NvpApiClient.NVPApiHelper(\n api_providers, c.user, c.password,\n request_timeout=c.request_timeout, http_timeout=c.http_timeout,\n retries=c.retries, redirects=c.redirects,\n failover_time=int(self.plugin_config['failover_time']),\n concurrent_connections=int(\n self.plugin_config['concurrent_connections']))\n\n c.api_client.login()\n\n # For testing..\n self.api_client = self.controller.api_client\n\n def get_all_networks(self, tenant_id, **kwargs):\n \"\"\"\n Returns a dictionary containing all for\n the specified tenant.\n\n :returns: a list of mapping sequences with the following signature:\n [{'net-id': uuid that uniquely identifies\n the particular quantum network,\n 'net-name': a human-readable name associated\n with network referenced by net-id\n },\n ....\n {'net-id': uuid that uniquely identifies the\n particular quantum network,\n 'net-name': a human-readable name associated\n with network referenced by net-id\n }\n ]\n :raises: None\n \"\"\"\n networks = nvplib.get_all_networks(self.controller, tenant_id, [])\n LOG.debug(\"get_all_networks() completed for tenant %s: %s\" %\n (tenant_id, networks))\n return networks\n\n def create_network(self, tenant_id, net_name, **kwargs):\n \"\"\"\n Creates a new Virtual Network, and assigns it a symbolic name.\n :returns: a sequence of mappings with the following signature:\n {'net-id': uuid that uniquely identifies the\n particular quantum network,\n 'net-name': a human-readable name associated\n with network referenced by net-id\n }\n :raises:\n \"\"\"\n kwargs[\"controller\"] = self.controller\n return nvplib.create_network(tenant_id, net_name, **kwargs)\n\n def create_custom_network(self, tenant_id, net_name, transport_zone,\n controller):\n return self.create_network(tenant_id, net_name,\n network_type=\"custom\",\n transport_zone=transport_zone,\n controller=controller)\n\n def delete_network(self, tenant_id, netw_id):\n \"\"\"\n Deletes the network with the specified network identifier\n belonging to the specified tenant.\n\n :returns: a sequence of mappings with the following signature:\n {'net-id': uuid that uniquely identifies the\n particular quantum network\n }\n :raises: exception.NetworkInUse\n :raises: exception.NetworkNotFound\n \"\"\"\n if not nvplib.check_tenant(self.controller, netw_id, tenant_id):\n raise exception.NetworkNotFound(net_id=netw_id)", "answers": [" nvplib.delete_network(self.controller, netw_id)"], "length": 973, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "d2b1e5a6-2e50-47ec-ba89-6ea3d3163ba1", "reasoning": "The delete_network method checks tenant ownership, raising NetworkNotFound if the check fails. The next logical step is to actually delete the network using the nvplib helper. In similar methods, the plugin calls nvplib functions with the controller and network ID. Therefore the next line should invoke nvplib.delete_network with the controller and netw_id.", "reasoning_model_answer": "nvplib.delete_network(self.controller, netw_id)", "assistant_with_reasoning": "\nThe delete_network method checks tenant ownership, raising NetworkNotFound if the check fails. The next logical step is to actually delete the network using the nvplib helper. In similar methods, the plugin calls nvplib functions with the controller and network ID. Therefore the next line should invoke nvplib.delete_network with the controller and netw_id.\n\nnvplib.delete_network(self.controller, netw_id)", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.185, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 11609, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "nvplib.delete_network(self.controller, netw_id)", "score": 0.92, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/*\n Licensed to the Apache Software Foundation (ASF) under one\n or more contributor license agreements. See the NOTICE file\n distributed with this work for additional information\n regarding copyright ownership. The ASF licenses this file\n to you under the Apache License, Version 2.0 (the\n \"License\"); you may not use this file except in compliance\n with the License. You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing,\n software distributed under the License is distributed on an\n \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n KIND, either express or implied. See the License for the\n specific language governing permissions and limitations\n under the License.\n*/\npackage org.apache.cordova;\n\nimport java.io.ByteArrayOutputStream;\nimport java.io.File;\nimport java.io.FileNotFoundException;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.io.OutputStream;\n\nimport org.apache.commons.codec.binary.Base64;\nimport org.apache.cordova.api.LOG;\nimport org.apache.cordova.api.Plugin;\nimport org.apache.cordova.api.PluginResult;\nimport org.json.JSONArray;\nimport org.json.JSONException;\nimport org.json.JSONObject;\n\n\nimport android.app.Activity;\nimport android.content.ContentValues;\nimport android.content.Intent;\nimport android.database.Cursor;\nimport android.graphics.Bitmap;\nimport android.graphics.Bitmap.CompressFormat;\nimport android.net.Uri;\nimport android.provider.MediaStore;\n\n/**\n * This class launches the camera view, allows the user to take a picture, closes the camera view,\n * and returns the captured image. When the camera view is closed, the screen displayed before \n * the camera view was shown is redisplayed.\n */\npublic class CameraLauncher extends Plugin {\n\n private static final int DATA_URL = 0; // Return base64 encoded string\n private static final int FILE_URI = 1; // Return file uri (content://media/external/images/media/2 for Android)\n \n private static final int PHOTOLIBRARY = 0; // Choose image from picture library (same as SAVEDPHOTOALBUM for Android)\n private static final int CAMERA = 1; // Take picture from camera\n private static final int SAVEDPHOTOALBUM = 2; // Choose image from picture library (same as PHOTOLIBRARY for Android)\n \n private static final int PICTURE = 0; // allow selection of still pictures only. DEFAULT. Will return format specified via DestinationType\n private static final int VIDEO = 1; // allow selection of video only, ONLY RETURNS URL\n private static final int ALLMEDIA = 2; // allow selection from all media types\n \n private static final int JPEG = 0; // Take a picture of type JPEG\n private static final int PNG = 1; // Take a picture of type PNG\n private static final String GET_PICTURE = \"Get Picture\";\n private static final String GET_VIDEO = \"Get Video\";\n private static final String GET_All = \"Get All\";\n \n private static final String LOG_TAG = \"CameraLauncher\";\n \n private int mQuality; // Compression quality hint (0-100: 0=low quality & high compression, 100=compress of max quality)\n private int targetWidth; // desired width of the image\n private int targetHeight; // desired height of the image\n private Uri imageUri; // Uri of captured image \n private int encodingType; // Type of encoding to use\n private int mediaType; // What type of media to retrieve\n \n public String callbackId;\n private int numPics;\n \n /**\n * Constructor.\n */\n public CameraLauncher() {\n }\n\n /**\n * Executes the request and returns PluginResult.\n * \n * @param action The action to execute.\n * @param args JSONArry of arguments for the plugin.\n * @param callbackId The callback id used when calling back into JavaScript.\n * @return A PluginResult object with a status and message.\n */\n public PluginResult execute(String action, JSONArray args, String callbackId) {\n PluginResult.Status status = PluginResult.Status.OK;\n String result = \"\"; \n this.callbackId = callbackId;\n \n try {\n if (action.equals(\"takePicture\")) {\n int srcType = CAMERA;\n int destType = FILE_URI;\n this.targetHeight = 0;\n this.targetWidth = 0;\n this.encodingType = JPEG;\n this.mediaType = PICTURE;\n this.mQuality = 80;\n\n this.mQuality = args.getInt(0);\n destType = args.getInt(1);\n srcType = args.getInt(2);\n this.targetWidth = args.getInt(3);\n this.targetHeight = args.getInt(4);\n this.encodingType = args.getInt(5);\n \n if (srcType == CAMERA) {\n this.takePicture(destType, encodingType);\n }\n else if ((srcType == PHOTOLIBRARY) || (srcType == SAVEDPHOTOALBUM)) {\n this.getImage(srcType, destType);\n }\n PluginResult r = new PluginResult(PluginResult.Status.NO_RESULT);\n r.setKeepCallback(true);\n return r;\n }\n return new PluginResult(status, result);\n } catch (JSONException e) {\n e.printStackTrace();\n return new PluginResult(PluginResult.Status.JSON_EXCEPTION);\n }\n }\n \n //--------------------------------------------------------------------------\n // LOCAL METHODS\n //--------------------------------------------------------------------------\n \n /**\n * Take a picture with the camera.\n * When an image is captured or the camera view is cancelled, the result is returned\n * in CordovaActivity.onActivityResult, which forwards the result to this.onActivityResult.\n * \n * The image can either be returned as a base64 string or a URI that points to the file.\n * To display base64 string in an img tag, set the source to:\n * img.src=\"data:image/jpeg;base64,\"+result;\n * or to display URI in an img tag\n * img.src=result;\n * \n * @param quality Compression quality hint (0-100: 0=low quality & high compression, 100=compress of max quality)\n * @param returnType Set the type of image to return. \n */\n public void takePicture(int returnType, int encodingType) {\n // Save the number of images currently on disk for later\n this.numPics = queryImgDB().getCount();\n \n // Display camera\n Intent intent = new Intent(\"android.media.action.IMAGE_CAPTURE\");\n \n // Specify file so that large image is captured and returned\n // TODO: What if there isn't any external storage?\n File photo = createCaptureFile(encodingType);\n intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, Uri.fromFile(photo));\n this.imageUri = Uri.fromFile(photo);\n\n this.ctx.startActivityForResult((Plugin) this, intent, (CAMERA+1)*16 + returnType+1);\n }\n\n /**\n * Create a file in the applications temporary directory based upon the supplied encoding.\n * \n * @param encodingType of the image to be taken\n * @return a File object pointing to the temporary picture\n */\n private File createCaptureFile(int encodingType) {\n File photo = null;\n if (encodingType == JPEG) {\n photo = new File(DirectoryManager.getTempDirectoryPath(ctx.getContext()), \"Pic.jpg\");\n } else if (encodingType == PNG) {\n photo = new File(DirectoryManager.getTempDirectoryPath(ctx.getContext()), \"Pic.png\"); \n } else {\n throw new IllegalArgumentException(\"Invalid Encoding Type: \" + encodingType);\n }\n return photo;\n }\n\n /**\n * Get image from photo library.\n * \n * @param quality Compression quality hint (0-100: 0=low quality & high compression, 100=compress of max quality)\n * @param srcType The album to get image from.\n * @param returnType Set the type of image to return. \n */\n // TODO: Images selected from SDCARD don't display correctly, but from CAMERA ALBUM do!\n public void getImage(int srcType, int returnType) {\n Intent intent = new Intent();\n String title = GET_PICTURE;\n if (this.mediaType == PICTURE) {\n intent.setType(\"image/*\"); \n }\n else if (this.mediaType == VIDEO) {\n intent.setType(\"video/*\"); \n title = GET_VIDEO;\n }\n else if (this.mediaType == ALLMEDIA) {\n // I wanted to make the type 'image/*, video/*' but this does not work on all versions \n // of android so I had to go with the wildcard search.\n intent.setType(\"*/*\"); \n title = GET_All;\n }\n \n intent.setAction(Intent.ACTION_GET_CONTENT);\n intent.addCategory(Intent.CATEGORY_OPENABLE);\n this.ctx.startActivityForResult((Plugin) this, Intent.createChooser(intent,\n new String(title)), (srcType+1)*16 + returnType + 1);\n }\n\n /**\n * Scales the bitmap according to the requested size.\n * \n * @param bitmap The bitmap to scale.\n * @return Bitmap A new Bitmap object of the same bitmap after scaling. \n */\n public Bitmap scaleBitmap(Bitmap bitmap) {\n int newWidth = this.targetWidth;\n int newHeight = this.targetHeight;\n int origWidth = bitmap.getWidth();", "answers": [" int origHeight = bitmap.getHeight();"], "length": 1085, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "ae91deea-e007-4944-a6a3-fa7c13cf8da8", "reasoning": "The method scaleBitmap begins by defining newWidth and newHeight from the instance fields, then obtains the original bitmap width. The next logical step is to also retrieve the original bitmap height, which is needed for scaling calculations. Therefore the next line should get the height via bitmap.getHeight().", "reasoning_model_answer": "int origHeight = bitmap.getHeight();", "assistant_with_reasoning": "\nThe method scaleBitmap begins by defining newWidth and newHeight from the instance fields, then obtains the original bitmap width. The next logical step is to also retrieve the original bitmap height, which is needed for scaling calculations. Therefore the next line should get the height via bitmap.getHeight().\n\nint origHeight = bitmap.getHeight();", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 2.134, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 9974, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "int origHeight = bitmap.getHeight();", "score": 0.9, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/*\n * AMW - Automated Middleware allows you to manage the configurations of\n * your Java EE applications on an unlimited number of different environments\n * with various versions, including the automated deployment of those apps.\n * Copyright (C) 2013-2016 by Puzzle ITC\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU Affero General Public License as\n * published by the Free Software Foundation, either version 3 of the\n * License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program. If not, see .\n */\n\npackage ch.puzzle.itc.mobiliar.presentation.shakedowntest;\n\nimport ch.puzzle.itc.mobiliar.business.deploy.entity.CustomFilter;\nimport ch.puzzle.itc.mobiliar.business.deploy.entity.DeploymentEntity;\nimport ch.puzzle.itc.mobiliar.business.deploy.entity.DeploymentFilterTypes;\nimport ch.puzzle.itc.mobiliar.business.domain.commons.CommonFilterService.SortingDirectionType;\nimport ch.puzzle.itc.mobiliar.business.environment.entity.ContextEntity;\nimport ch.puzzle.itc.mobiliar.business.generator.control.extracted.ResourceDependencyResolverService;\nimport ch.puzzle.itc.mobiliar.business.releasing.control.ReleaseMgmtService;\nimport ch.puzzle.itc.mobiliar.business.releasing.entity.ReleaseEntity;\nimport ch.puzzle.itc.mobiliar.business.resourcegroup.control.ResourceTypeProvider;\nimport ch.puzzle.itc.mobiliar.business.resourcegroup.entity.ResourceGroupEntity;\nimport ch.puzzle.itc.mobiliar.business.shakedown.entity.ShakedownTestEntity;\nimport ch.puzzle.itc.mobiliar.business.shakedown.entity.ShakedownTestEntity.shakedownTest_state;\nimport ch.puzzle.itc.mobiliar.business.shakedown.entity.ShakedownTestFilterTypes;\nimport ch.puzzle.itc.mobiliar.business.shakedown.entity.ShakedownTestOrder;\nimport ch.puzzle.itc.mobiliar.common.exception.NotAuthorizedException;\nimport ch.puzzle.itc.mobiliar.common.util.Tuple;\nimport ch.puzzle.itc.mobiliar.presentation.common.ContextDataProvider;\nimport ch.puzzle.itc.mobiliar.presentation.components.impl.CustomFilterComp;\nimport ch.puzzle.itc.mobiliar.presentation.util.GlobalMessageAppender;\nimport lombok.Getter;\nimport lombok.Setter;\n\nimport javax.ejb.EJBException;\nimport javax.enterprise.context.SessionScoped;\nimport javax.faces.context.FacesContext;\nimport javax.inject.Inject;\nimport javax.inject.Named;\nimport java.io.Serializable;\nimport java.text.Format;\nimport java.text.SimpleDateFormat;\nimport java.util.*;\n\n@Named\n@SessionScoped // TODO: Migrate to new concept Be careful state of filter not kept in viewScoped\npublic class ShakedownTestScreenDataProvider implements Serializable {\n\tprivate static final long serialVersionUID = 1L;\n\tprivate static final String EMPTY_STRING = \"\";\n\n\tprivate enum PresetViewOptions {\n\t\tSHAKEDOWN_TEST(\"Shakedown tests\");\n\t\tprivate String displayName;\n\n\t\tprivate PresetViewOptions(String displayName) {\n\t\t\tthis.displayName = displayName;\n\t\t}\n\n\t\tpublic String getDisplayName() {\n\t\t\treturn this.displayName;\n\t\t}\n\t}\n\n\t/**\n\t * Falls enum angepasst oder refactored wird, so muss dies zwingend im shakedowntest.xhtml nachgetragen\n\t * werden!\n\t */\n\tpublic enum shakedownTestScreenColDescriptor {\n\t\tID, TRACKING_ID, STATE, APPSERVER_NAME, RELEASE, ENV, TESTDATE\n\t}\n\n\t@Inject\n\tReleaseMgmtService releaseMgmtService;\n\n\t@Inject\n\tResourceDependencyResolverService dependencyResolverService;\n\n\t@Inject\n\tShakedownTestScreenController controller;\n\n\t@Inject\n\tContextDataProvider contextDataProvider;\n\n\t@Inject\n\tResourceTypeProvider resourceTypeProvider;\n\n\tprivate List shakedownTests;\n\tprivate List shakedowntestPresetViewsOptions;\n\tprivate String selectedShakedownTestPresetView = PresetViewOptions.SHAKEDOWN_TEST.getDisplayName();\n\t@Getter\n\t@Setter\n\tprivate Integer selectedShakedownTestId;\n\tprivate int countAllShakedownTests;\n\tprivate ArrayList allAppDisplayNames;\n\tprivate Map asGroups;\n\tprivate Map> contextIdMapWithSuccessfullLastDeployedAppServer;\n\t@Getter\n\t@Setter\n\tprivate Integer selectedOrderEnvironmentId;\n\t@Getter\n\t@Setter\n\tprivate Integer selectedOrderAppServerGroupId;\n\tprivate List shakedownTestOrder;\n\t@Getter\n\t@Setter\n\tprivate Integer trackingIdFromLastCreatedOrder;\n\t@Getter\n\t@Setter\n\tprivate boolean showOnlyDeployedAppServers;\n\tprivate Map groupToDeploymentMap;\n\n\t// paging, sorting\n\t@Getter\n\tprivate int currentPage;\n\tprivate int itemsPerPage;\n\tprivate SortingDirectionType sortingDirection = null;\n\tprivate shakedownTestScreenColDescriptor sortingColumn = null;\n\n\t// Releasing\n\t@Getter\n\tprivate ReleaseEntity selectedRelease;\n\t@Getter\n\tprivate List allReleases;\n\tprivate Map allReleasesMap;\n\n\t@Getter\n\tprivate boolean renderCreateOrderDialog;\n\n\tprivate ShakedownTestFilterTypes selectedFilter;\n\n\t@Getter\n\tprivate CustomFilterComp customFilterComp = new CustomFilterCompImpl();\n\n\n\tpublic void initView() {\n\t if (!FacesContext.getCurrentInstance().isPostback()) {\n\t\t reloadShakedownTests(true);\n\t\t initDefaultSelection();\n\t\t loadAllReleases();\n\t\t loadApplicationServerGroups();\n\t\t showOnlyDeployedAppServers = false;\n\t\t selectedOrderAppServerGroupId = null;\n\t\t selectedRelease = null;\n\t }\n\t}\n\n\tprivate class CustomFilterCompImpl extends CustomFilterComp {\n\n\n\t\t@Override\n\t\tpublic void addSelectedFilter() {\n\n\t\t\tselectedFilter = getSelectedEnumType(getSelectedFilterItemEnumName());\n\n\t\t\tif (selectedFilter != null) {\n\t\t\t\tCustomFilter filter = CustomFilter.builder(selectedFilter).build();\n\t\t\t\tfilter.setComparatorSelection(filter.getTypedComparatorSelectionList().isEmpty() ? null : filter.getTypedComparatorSelectionList().get(0));\n\t\t\t\tif (selectedFilter.equals(DeploymentFilterTypes.LASTDEPLOYJOBFORASENV) && hasAlreadySpecialTypeFilter(getSelectedFilterList())) {\n\t\t\t\t\tGlobalMessageAppender.addErrorMessage(\"This filter is already set.\");\n\t\t\t\t} else {\n\t\t\t\t\tfilter = setFilterDropDownOptions(filter);\n\n\t\t\t\t\tgetSelectedFilterList().add(filter);\n\n\t\t\t\t}\n\t\t\t}\n\t\t\tselectedFilter = null;\n\n\t\t}\n\n\t\tprivate ShakedownTestFilterTypes getSelectedEnumType(String selectedFilter) {\n\t\t\tShakedownTestFilterTypes result = null;\n\t\t\tfor (ShakedownTestFilterTypes filterType : ShakedownTestFilterTypes.values()) {\n\t\t\t\tif (filterType.name().equals(selectedFilter)) {\n\t\t\t\t\tresult = filterType;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn result;\n\t\t}\n\n\t\t@Override\n\t\tprotected void loadFilterList() {\n\t\t\tList filterSelectionItemList = new ArrayList();\n\t\t\tfor (ShakedownTestFilterTypes filterType : ShakedownTestFilterTypes.values()) {\n\t\t\t\tfilterSelectionItemList.add(new FilterSelectionItem(filterType.name(), filterType\n\t\t\t\t\t\t.getFilterDisplayName()));\n\t\t\t}\n\t\t\tsetFilterSelectionList(filterSelectionItemList);\n\t\t}\n\n\t\t@Override\n\t\tprotected CustomFilter setFilterDropDownOptions(CustomFilter filter) {\n\n\t\t\tif (filter.getFilterDisplayName().equals(\n\t\t\t\t\tShakedownTestFilterTypes.APPSERVER_NAME.getFilterDisplayName())) {\n\t\t\t\tfilter.setDropDownItems(getAllAppServerNames());\n\t\t\t}\n\n\t\t\tif (filter.getFilterDisplayName().equals(\n\t\t\t\t\tShakedownTestFilterTypes.ENVIRONMENT_NAME.getFilterDisplayName())) {\n\t\t\t\tfilter.setDropDownItems(getAllEnvNames());\n\t\t\t}\n\n\t\t\tif (filter.getFilterDisplayName().equals(\n\t\t\t\t\tShakedownTestFilterTypes.APPLICATION_NAME.getFilterDisplayName())) {\n\t\t\t\tfilter.setDropDownItems(getAllAppDisplayNames());\n\t\t\t}\n\n\t\t\tif (filter.getFilterDisplayName().equals(\n\t\t\t\t\tShakedownTestFilterTypes.TEST_STATE.getFilterDisplayName())) {\n\t\t\t\tfilter.setDropDownItems(getAllStates());\n\t\t\t}\n\t\t\tif (filter.getFilterDisplayName().equals(\n\t\t\t\t\tShakedownTestFilterTypes.APPSERVER_RELEASE.getFilterDisplayName())) {\n\t\t\t\tMap releaseMap = new LinkedHashMap<>();\n\t\t\t\tfor (ReleaseEntity r : allReleases) {\n\t\t\t\t\treleaseMap.put(r.getName(),\n\t\t\t\t\t\t\tCustomFilter.convertDateToString(r.getInstallationInProductionAt()));\n\t\t\t\t}\n\t\t\t\tfilter.setDropDownItemsMap(releaseMap);\n\t\t\t}\n\t\t\treturn filter;\n\t\t}\n\n\t}\n\n\tpublic void addShakedownTestOrder() {\n\t\tboolean valid = true;\n\t\tif (selectedOrderEnvironmentId == null || selectedOrderEnvironmentId == 0) {\n\t\t\tGlobalMessageAppender.addErrorMessage(\"No environment selected\");\n\t\t\tvalid = false;\n\t\t}\n\t\tif (selectedOrderAppServerGroupId == null || selectedOrderAppServerGroupId == 0) {\n\t\t\tGlobalMessageAppender.addErrorMessage(\"No application server selected\");\n\t\t\tvalid = false;\n\t\t}\n\t\tif (selectedRelease == null && !showOnlyDeployedAppServers) {\n\t\t\tGlobalMessageAppender.addErrorMessage(\"No release selected\");\n\t\t\tvalid = false;\n\t\t}\n\n\t\tif (valid) {\n\t\t\tList selectedAppServerGroups = null;\n ContextEntity context = getContextForId(selectedOrderEnvironmentId);\n\n\t\t\tif (selectedOrderAppServerGroupId > 0) {\n\t\t\t\tselectedAppServerGroups = Collections.singletonList(asGroups\n\t\t\t\t\t\t.get(selectedOrderAppServerGroupId));\n\t\t\t}\n\t\t\telse if (showOnlyDeployedAppServers) {\n\t\t\t\t// deployed appServers\n\t\t\t\tselectedAppServerGroups = new ArrayList<>(getDeployedAppServerGroups());\n\t\t\t}\n\t\t\telse {\n\t\t\t\t// all appServers\n\t\t\t\tselectedAppServerGroups = new ArrayList<>(asGroups.values());\n\t\t\t}\n\n\t\t\tShakedownTestOrder shakedownTestOrder = new ShakedownTestOrder(context, selectedRelease, selectedAppServerGroups);\n\t\t\tgetShakedownTestOrder().add(shakedownTestOrder);\n\t\t}\n\t}\n\n\n\t\n\tprivate ContextEntity getContextForId(Integer id) {\n\t\tfor (ContextEntity context : contextDataProvider.getEnvironments()) {\n\t\t\tif (context.getId().equals(id)) {\n\t\t\t\treturn context;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\n\tpublic List getAppServerGroups() {\n\t\tif (showOnlyDeployedAppServers) {\n\t\t\treturn getDeployedAppServerGroups();\n\t\t}\n\t\tList result = new ArrayList<>(asGroups.values());\n\t\tCollections.sort(result);\n\t\treturn result;\n\t}\n\n\tprivate List getDeployedAppServerGroups() {\n\t\tif (selectedOrderEnvironmentId != null && selectedOrderEnvironmentId != null) {\n\t\t\tList asList = contextIdMapWithSuccessfullLastDeployedAppServer\n\t\t\t\t\t.get(selectedOrderEnvironmentId);\n\t\t\tif (asList != null) {\n\t\t\t\tCollections.sort(asList);\n\t\t\t\treturn asList;\n\t\t\t}\n\t\t}\n\t\treturn Collections.emptyList();\n\t}\n\n\tpublic void createShakedownTest() {\n\t\ttry {\n\n\t\t\ttrackingIdFromLastCreatedOrder = controller.createShakedownTestOrder(getShakedownTestOrder());\n\n\t\t\tif (trackingIdFromLastCreatedOrder != null) {\n\n\t\t\t\tsetFilterForLastShakedownTestOrder();\n\t\t\t\tgetShakedownTestOrder().clear();\n\t\t\t\treloadShakedownTests(true);\n\t\t\t}\n\t\t}\n\t\tcatch (EJBException e) {\n\t\t\tif (e.getCause() instanceof NotAuthorizedException) {\n\t\t\t\tGlobalMessageAppender.addErrorMessage(e.getCause().getMessage());\n\t\t\t}\n\t\t\telse {\n\t\t\t\tthrow e;\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic void removeSelectedShakedownTestFromOrder(ShakedownTestOrder test) {\n\t\tif (getShakedownTestOrder().contains(test)) {\n\t\t\tgetShakedownTestOrder().remove(test);\n\t\t}\n\t}\n\n\tpublic List getShakedownTestOrder() {\n\t\tif (shakedownTestOrder == null) {\n\t\t\tshakedownTestOrder = new ArrayList<>();\n\t\t}\n\t\treturn shakedownTestOrder;\n\t}\n\n\tprivate void setFilterForLastShakedownTestOrder() {\n\n\t\tif (trackingIdFromLastCreatedOrder != null) {\n\n\t\t\tgetCustomFilterComp().removeAllFilter();\n\t\t\tCustomFilter filter = CustomFilter.builder(ShakedownTestFilterTypes.TRACKING_ID).build();\n\t\t\tfilter.setValue(trackingIdFromLastCreatedOrder.toString());\n\n\t\t\tgetCustomFilterComp().getSelectedFilterList().add(filter);\n\n\t\t\tsortingDirection = SortingDirectionType.ASC;\n\t\t\tsortingColumn = shakedownTestScreenColDescriptor.ID;\n\t\t}\n\n\t}\n\n\tpublic void goToScreen(Integer screen) {\n\t\tcurrentPage = Math.min(Math.max(0, screen), maxScreens() - 1);\n\t\treloadShakedownTests(false);\n\t}\n\n\tpublic void nextScreen() {\n\t\tcurrentPage = Math.min(++currentPage, maxScreens() - 1);\n\t\treloadShakedownTests(false);\n\t}\n\n\tpublic void lastScreen() {\n\t\tcurrentPage = maxScreens() - 1;\n\t\treloadShakedownTests(false);\n\t}\n\n\tpublic void changeSortOrderForSelectedColumn(String enumName) {\n\t\tshakedownTestScreenColDescriptor col = getEnumValueForString(enumName);\n\t\tif (col != null) {\n\t\t\tif (sortingColumn.equals(col)) {\n\t\t\t\tif (sortingDirection == null) {\n\t\t\t\t\t// set to asc\n\t\t\t\t\tsortingDirection = SortingDirectionType.ASC;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tswitch (sortingDirection) {\n\t\t\t\t\tcase ASC:\n\t\t\t\t\t\t// set to desc\n\t\t\t\t\t\tsortingDirection = SortingDirectionType.DESC;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase DESC:\n\t\t\t\t\t\t// set to asc\n\t\t\t\t\t\tsortingDirection = SortingDirectionType.ASC;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\t// auswahl einer neuen spalte beginnt immer mit asc sortierung\n\t\t\t\tsortingColumn = col;\n\t\t\t\tsortingDirection = SortingDirectionType.ASC;\n\t\t\t}\n\t\t}\n\t\t// do sorting\n\t\treloadShakedownTests(false);\n\t}\n\n\tpublic void shakedownTestPresetViewChangeListener(String selectedShakedownTestPresetView) {\n\t\tif (!this.selectedShakedownTestPresetView.equals(selectedShakedownTestPresetView)) {\n\t\t\tthis.selectedShakedownTestPresetView = selectedShakedownTestPresetView;\n\t\t\treloadShakedownTests(false);\n\t\t}\n\t}\n\n\tpublic void firstScreen() {\n\t\tcurrentPage = 0;\n\t\treloadShakedownTests(false);\n\t};\n\n\tpublic void previousScreen() {\n\t\tcurrentPage = Math.max(0, --currentPage);\n\t\treloadShakedownTests(false);\n\t}\n\n\tpublic void setItemsPerPage(int itemsPerPage) {\n\t\tif (itemsPerPage < 0) {\n\t\t\titemsPerPage = 0;\n\t\t}\n\t\tif (itemsPerPage != this.itemsPerPage) {\n\t\t\tthis.itemsPerPage = itemsPerPage;\n\t\t\tthis.currentPage = 0;\n\t\t\treloadShakedownTests(false);\n\t\t}\n\t}\n\n\n\n\tpublic void reloadShakedownTests(boolean countAgain) {\n\t\tif (countAgain) {\n\t\t\tcurrentPage = 0;\n\t\t}\n\t\tTuple, Integer> result = controller.loadPendingShakedownTests(countAgain,\n\t\t\t\tcurrentStartIndex(), getItemsPerPage(), getAppliedFilterList(), sortingColumn,", "answers": ["\t\t\t\tsortingDirection);"], "length": 1086, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "957fc6a5-1571-487b-ab29-3caca7bd755a", "reasoning": "The method call to controller.loadPendingShakedownTests is incomplete: it has opened parentheses and arguments, ending with a comma after sortingColumn, indicating another argument is needed before closing. The class defines a field 'sortingDirection' of type SortingDirectionType, which matches the typical signature (sorting column, sorting direction). Therefore the next line should supply sortingDirection and close the call with a parenthesis and semicolon.", "reasoning_model_answer": "sortingDirection);", "assistant_with_reasoning": "\nThe method call to controller.loadPendingShakedownTests is incomplete: it has opened parentheses and arguments, ending with a comma after sortingColumn, indicating another argument is needed before closing. The class defines a field 'sortingDirection' of type SortingDirectionType, which matches the typical signature (sorting column, sorting direction). Therefore the next line should supply sortingDirection and close the call with a parenthesis and semicolon.\n\nsortingDirection);", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.185, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 14149, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "sortingDirection);", "score": 0.9, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "// ==++==\n// \n// Copyright(c) Microsoft Corporation. All rights reserved.\n// \n// ==--==\n// [....]\n// \n\nnamespace System.Reflection\n{\n using System;\n using System.Collections.Generic;\n using System.Diagnostics;\n using System.Diagnostics.Contracts;\n using System.Globalization;\n using System.Runtime;\n using System.Runtime.ConstrainedExecution;\n using System.Runtime.InteropServices;\n#if FEATURE_REMOTING\n using System.Runtime.Remoting.Metadata;\n#endif //FEATURE_REMOTING\n using System.Runtime.Serialization;\n using System.Security;\n using System.Security.Permissions;\n using System.Threading;\n using MemberListType = System.RuntimeType.MemberListType;\n using RuntimeTypeCache = System.RuntimeType.RuntimeTypeCache;\n using System.Runtime.CompilerServices;\n\n [Serializable]\n [ClassInterface(ClassInterfaceType.None)]\n [ComDefaultInterface(typeof(_ConstructorInfo))]\n#pragma warning disable 618\n [PermissionSetAttribute(SecurityAction.InheritanceDemand, Name = \"FullTrust\")]\n#pragma warning restore 618\n [System.Runtime.InteropServices.ComVisible(true)]\n public abstract class ConstructorInfo : MethodBase, _ConstructorInfo\n {\n #region Static Members\n [System.Runtime.InteropServices.ComVisible(true)]\n public readonly static String ConstructorName = \".ctor\";\n\n [System.Runtime.InteropServices.ComVisible(true)]\n public readonly static String TypeConstructorName = \".cctor\";\n #endregion\n\n #region Constructor\n protected ConstructorInfo() { }\n #endregion\n\n#if !FEATURE_CORECLR\n public static bool operator ==(ConstructorInfo left, ConstructorInfo right)\n {\n if (ReferenceEquals(left, right))\n return true;\n\n if ((object)left == null || (object)right == null ||\n left is RuntimeConstructorInfo || right is RuntimeConstructorInfo)\n {\n return false;\n }\n return left.Equals(right);\n }\n\n public static bool operator !=(ConstructorInfo left, ConstructorInfo right)\n {\n return !(left == right);\n }\n#endif // !FEATURE_CORECLR\n\n public override bool Equals(object obj)\n {\n return base.Equals(obj);\n }\n\n public override int GetHashCode()\n {\n return base.GetHashCode();\n }\n\n #region Internal Members\n internal virtual Type GetReturnType() { throw new NotImplementedException(); }\n #endregion\n\n #region MemberInfo Overrides\n [System.Runtime.InteropServices.ComVisible(true)]\n public override MemberTypes MemberType { get { return System.Reflection.MemberTypes.Constructor; } }\n #endregion\n \n #region Public Abstract\\Virtual Members\n public abstract Object Invoke(BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture);\n #endregion\n\n #region Public Members\n [DebuggerStepThroughAttribute]\n [Diagnostics.DebuggerHidden]\n public Object Invoke(Object[] parameters)\n {\n // Theoretically we should set up a LookForMyCaller stack mark here and pass that along.\n // But to maintain backward compatibility we can't switch to calling an \n // internal overload that takes a stack mark.\n // Fortunately the stack walker skips all the reflection invocation frames including this one.\n // So this method will never be returned by the stack walker as the caller.\n // See SystemDomain::CallersMethodCallbackWithStackMark in AppDomain.cpp.\n return Invoke(BindingFlags.Default, null, parameters, null);\n }\n #endregion\n\n#if !FEATURE_CORECLR\n #region COM Interop Support\n Type _ConstructorInfo.GetType()\n {\n return base.GetType();\n }\n \n Object _ConstructorInfo.Invoke_2(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)\n {\n return Invoke(obj, invokeAttr, binder, parameters, culture);\n }\n \n Object _ConstructorInfo.Invoke_3(Object obj, Object[] parameters)\n {\n return Invoke(obj, parameters);\n }\n \n Object _ConstructorInfo.Invoke_4(BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)\n {\n return Invoke(invokeAttr, binder, parameters, culture);\n }\n \n Object _ConstructorInfo.Invoke_5(Object[] parameters)\n {\n return Invoke(parameters);\n }\n\n void _ConstructorInfo.GetTypeInfoCount(out uint pcTInfo)\n {\n throw new NotImplementedException();\n }\n\n void _ConstructorInfo.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo)\n {\n throw new NotImplementedException();\n }\n\n void _ConstructorInfo.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)\n {\n throw new NotImplementedException();\n }\n\n // If you implement this method, make sure to include _ConstructorInfo.Invoke in VM\\DangerousAPIs.h and \n // include _ConstructorInfo in SystemDomain::IsReflectionInvocationMethod in AppDomain.cpp.\n void _ConstructorInfo.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)\n {\n throw new NotImplementedException();\n }\n #endregion\n#endif\n }\n\n [Serializable]\n internal sealed class RuntimeConstructorInfo : ConstructorInfo, ISerializable, IRuntimeMethodInfo\n {\n #region Private Data Members\n private volatile RuntimeType m_declaringType;\n private RuntimeTypeCache m_reflectedTypeCache;\n private string m_toString;\n private ParameterInfo[] m_parameters = null; // Created lazily when GetParameters() is called.\n#pragma warning disable 169\n private object _empty1; // These empties are used to ensure that RuntimeConstructorInfo and RuntimeMethodInfo are have a layout which is sufficiently similar\n private object _empty2;\n private object _empty3;\n#pragma warning restore 169\n private IntPtr m_handle;\n private MethodAttributes m_methodAttributes;\n private BindingFlags m_bindingFlags;\n private volatile Signature m_signature;\n private INVOCATION_FLAGS m_invocationFlags;\n\n#if FEATURE_APPX\n private bool IsNonW8PFrameworkAPI()\n {\n if (DeclaringType.IsArray && IsPublic && !IsStatic)\n return false;\n\n RuntimeAssembly rtAssembly = GetRuntimeAssembly();\n if (rtAssembly.IsFrameworkAssembly())\n {\n int ctorToken = rtAssembly.InvocableAttributeCtorToken;\n if (System.Reflection.MetadataToken.IsNullToken(ctorToken) || \n !CustomAttribute.IsAttributeDefined(GetRuntimeModule(), MetadataToken, ctorToken))\n return true;\n }\n\n if (GetRuntimeType().IsNonW8PFrameworkAPI())\n return true;\n\n return false;\n }\n\n internal override bool IsDynamicallyInvokable\n {\n get\n {\n return !AppDomain.ProfileAPICheck || !IsNonW8PFrameworkAPI();\n }\n }\n#endif // FEATURE_APPX\n\n internal INVOCATION_FLAGS InvocationFlags\n {\n [System.Security.SecuritySafeCritical]\n get\n {\n if ((m_invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_INITIALIZED) == 0)\n {\n INVOCATION_FLAGS invocationFlags = INVOCATION_FLAGS.INVOCATION_FLAGS_IS_CTOR; // this is a given\n\n Type declaringType = DeclaringType;\n\n //\n // first take care of all the NO_INVOKE cases. \n if ( declaringType == typeof(void) ||\n (declaringType != null && declaringType.ContainsGenericParameters) ||\n ((CallingConvention & CallingConventions.VarArgs) == CallingConventions.VarArgs) ||\n ((Attributes & MethodAttributes.RequireSecObject) == MethodAttributes.RequireSecObject))\n {\n // We don't need other flags if this method cannot be invoked\n invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_NO_INVOKE;\n }\n else if (IsStatic || declaringType != null && declaringType.IsAbstract)\n {\n invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_NO_CTOR_INVOKE;\n }\n else\n {\n // this should be an invocable method, determine the other flags that participate in invocation\n invocationFlags |= RuntimeMethodHandle.GetSecurityFlags(this);\n\n if ( (invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY) == 0 &&\n ((Attributes & MethodAttributes.MemberAccessMask) != MethodAttributes.Public ||\n (declaringType != null && declaringType.NeedsReflectionSecurityCheck)) )\n {\n // If method is non-public, or declaring type is not visible\n invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY;\n }\n\n // Check for attempt to create a delegate class, we demand unmanaged\n // code permission for this since it's hard to validate the target address.\n if (typeof(Delegate).IsAssignableFrom(DeclaringType))\n invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_IS_DELEGATE_CTOR;\n }\n\n#if FEATURE_APPX\n if (AppDomain.ProfileAPICheck && IsNonW8PFrameworkAPI())\n invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API;\n#endif // FEATURE_APPX\n\n m_invocationFlags = invocationFlags | INVOCATION_FLAGS.INVOCATION_FLAGS_INITIALIZED;\n }\n\n return m_invocationFlags;\n }\n }\n #endregion\n\n #region Constructor\n [System.Security.SecurityCritical] // auto-generated\n internal RuntimeConstructorInfo(\n RuntimeMethodHandleInternal handle, RuntimeType declaringType, RuntimeTypeCache reflectedTypeCache,\n MethodAttributes methodAttributes, BindingFlags bindingFlags)\n {\n Contract.Ensures(methodAttributes == RuntimeMethodHandle.GetAttributes(handle));\n\n m_bindingFlags = bindingFlags;\n m_reflectedTypeCache = reflectedTypeCache;\n m_declaringType = declaringType;\n m_handle = handle.Value;\n m_methodAttributes = methodAttributes;\n }\n #endregion\n\n#if FEATURE_REMOTING\n #region Legacy Remoting Cache\n // The size of CachedData is accounted for by BaseObjectWithCachedData in object.h.\n // This member is currently being used by Remoting for caching remoting data. If you\n // need to cache data here, talk to the Remoting team to work out a mechanism, so that\n // both caching systems can happily work together.\n private RemotingMethodCachedData m_cachedData;\n\n internal RemotingMethodCachedData RemotingCache\n {\n get\n {\n // This grabs an internal copy of m_cachedData and uses\n // that instead of looking at m_cachedData directly because\n // the cache may get cleared asynchronously. This prevents\n // us from having to take a lock.\n RemotingMethodCachedData cache = m_cachedData;\n if (cache == null)\n {\n cache = new RemotingMethodCachedData(this);\n RemotingMethodCachedData ret = Interlocked.CompareExchange(ref m_cachedData, cache, null);\n if (ret != null)\n cache = ret;\n }\n return cache;\n }\n }\n #endregion\n#endif //FEATURE_REMOTING\n\n #region NonPublic Methods\n RuntimeMethodHandleInternal IRuntimeMethodInfo.Value\n {\n [System.Security.SecuritySafeCritical]\n get\n {\n return new RuntimeMethodHandleInternal(m_handle);\n }\n }\n\n [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]\n internal override bool CacheEquals(object o)\n {\n RuntimeConstructorInfo m = o as RuntimeConstructorInfo;\n\n if ((object)m == null)\n return false;\n\n return m.m_handle == m_handle;\n }\n\n private Signature Signature\n {\n get\n {\n if (m_signature == null)\n m_signature = new Signature(this, m_declaringType);\n\n return m_signature;\n }\n }\n\n private RuntimeType ReflectedTypeInternal\n { \n get \n { \n return m_reflectedTypeCache.GetRuntimeType(); \n } \n }\n\n private void CheckConsistency(Object target) \n {\n if (target == null && IsStatic)\n return;\n\n if (!m_declaringType.IsInstanceOfType(target))\n {\n if (target == null) \n throw new TargetException(Environment.GetResourceString(\"RFLCT.Targ_StatMethReqTarg\"));\n\n throw new TargetException(Environment.GetResourceString(\"RFLCT.Targ_ITargMismatch\"));\n }\n }\n\n internal BindingFlags BindingFlags { get { return m_bindingFlags; } }\n\n // Differs from MethodHandle in that it will return a valid handle even for reflection only loaded types\n internal RuntimeMethodHandle GetMethodHandle()\n {\n return new RuntimeMethodHandle(this);\n }\n\n internal bool IsOverloaded\n { \n get \n { \n return m_reflectedTypeCache.GetConstructorList(MemberListType.CaseSensitive, Name).Length > 1;\n }\n }\n #endregion\n\n #region Object Overrides\n public override String ToString() \n {\n // \"Void\" really doesn't make sense here. But we'll keep it for compat reasons.\n if (m_toString == null)\n m_toString = \"Void \" + FormatNameAndSig();\n\n return m_toString;\n }\n #endregion\n\n #region ICustomAttributeProvider\n public override Object[] GetCustomAttributes(bool inherit)\n {\n return CustomAttribute.GetCustomAttributes(this, typeof(object) as RuntimeType);\n }\n\n public override Object[] GetCustomAttributes(Type attributeType, bool inherit)\n {\n if (attributeType == null)\n throw new ArgumentNullException(\"attributeType\");\n Contract.EndContractBlock();\n\n RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;\n\n if (attributeRuntimeType == null) \n throw new ArgumentException(Environment.GetResourceString(\"Arg_MustBeType\"),\"attributeType\");\n", "answers": [" return CustomAttribute.GetCustomAttributes(this, attributeRuntimeType);"], "length": 1217, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "31d42c37-4e07-4263-a153-d0388d4190aa", "reasoning": "The method GetCustomAttributes(Type attributeType, bool inherit) has just validated the attributeType argument and obtained its RuntimeType representation. The next logical step is to retrieve the custom attributes for this constructor using the runtime helper. In .NET's reflection implementation, this is done by returning CustomAttribute.GetCustomAttributes(this, attributeRuntimeType). Hence the next line is the return statement that calls this helper.", "reasoning_model_answer": "return CustomAttribute.GetCustomAttributes(this, attributeRuntimeType);", "assistant_with_reasoning": "\nThe method GetCustomAttributes(Type attributeType, bool inherit) has just validated the attributeType argument and obtained its RuntimeType representation. The next logical step is to retrieve the custom attributes for this constructor using the runtime helper. In .NET's reflection implementation, this is done by returning CustomAttribute.GetCustomAttributes(this, attributeRuntimeType). Hence the next line is the return statement that calls this helper.\n\nreturn CustomAttribute.GetCustomAttributes(this, attributeRuntimeType);", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.136, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 15672, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "return CustomAttribute.GetCustomAttributes(this, attributeRuntimeType);", "score": 0.92, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "\"\"\"\nFunctions\n---------\n.. autosummary::\n :toctree: generated/\n\n fmin_l_bfgs_b\n\n\"\"\"\n\n## License for the Python wrapper\n## ==============================\n\n## Copyright (c) 2004 David M. Cooke \n\n## Permission is hereby granted, free of charge, to any person obtaining a\n## copy of this software and associated documentation files (the \"Software\"),\n## to deal in the Software without restriction, including without limitation\n## the rights to use, copy, modify, merge, publish, distribute, sublicense,\n## and/or sell copies of the Software, and to permit persons to whom the\n## Software is furnished to do so, subject to the following conditions:\n\n## The above copyright notice and this permission notice shall be included in\n## all copies or substantial portions of the Software.\n\n## THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n## IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n## FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n## AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n## LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n## FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n## DEALINGS IN THE SOFTWARE.\n\n## Modifications by Travis Oliphant and Enthought, Inc. for inclusion in SciPy\n\nfrom __future__ import division, print_function, absolute_import\n\nimport numpy as np\nfrom numpy import array, asarray, float64, int32, zeros\nfrom . import _lbfgsb\nfrom .optimize import (approx_fprime, MemoizeJac, OptimizeResult,\n _check_unknown_options, wrap_function,\n _approx_fprime_helper)\nfrom scipy.sparse.linalg import LinearOperator\n\n__all__ = ['fmin_l_bfgs_b', 'LbfgsInvHessProduct']\n\n\ndef fmin_l_bfgs_b(func, x0, fprime=None, args=(),\n approx_grad=0,\n bounds=None, m=10, factr=1e7, pgtol=1e-5,\n epsilon=1e-8,\n iprint=-1, maxfun=15000, maxiter=15000, disp=None,\n callback=None, maxls=20):\n \"\"\"\n Minimize a function func using the L-BFGS-B algorithm.\n\n Parameters\n ----------\n func : callable f(x,*args)\n Function to minimise.\n x0 : ndarray\n Initial guess.\n fprime : callable fprime(x,*args), optional\n The gradient of `func`. If None, then `func` returns the function\n value and the gradient (``f, g = func(x, *args)``), unless\n `approx_grad` is True in which case `func` returns only ``f``.\n args : sequence, optional\n Arguments to pass to `func` and `fprime`.\n approx_grad : bool, optional\n Whether to approximate the gradient numerically (in which case\n `func` returns only the function value).\n bounds : list, optional\n ``(min, max)`` pairs for each element in ``x``, defining\n the bounds on that parameter. Use None or +-inf for one of ``min`` or\n ``max`` when there is no bound in that direction.\n m : int, optional\n The maximum number of variable metric corrections\n used to define the limited memory matrix. (The limited memory BFGS\n method does not store the full hessian but uses this many terms in an\n approximation to it.)\n factr : float, optional\n The iteration stops when\n ``(f^k - f^{k+1})/max{|f^k|,|f^{k+1}|,1} <= factr * eps``,\n where ``eps`` is the machine precision, which is automatically\n generated by the code. Typical values for `factr` are: 1e12 for\n low accuracy; 1e7 for moderate accuracy; 10.0 for extremely\n high accuracy.\n pgtol : float, optional\n The iteration will stop when\n ``max{|proj g_i | i = 1, ..., n} <= pgtol``\n where ``pg_i`` is the i-th component of the projected gradient.\n epsilon : float, optional\n Step size used when `approx_grad` is True, for numerically\n calculating the gradient\n iprint : int, optional\n Controls the frequency of output. ``iprint < 0`` means no output;\n ``iprint == 0`` means write messages to stdout; ``iprint > 1`` in\n addition means write logging information to a file named\n ``iterate.dat`` in the current working directory.\n disp : int, optional\n If zero, then no output. If a positive number, then this over-rides\n `iprint` (i.e., `iprint` gets the value of `disp`).\n maxfun : int, optional\n Maximum number of function evaluations.\n maxiter : int, optional\n Maximum number of iterations.\n callback : callable, optional\n Called after each iteration, as ``callback(xk)``, where ``xk`` is the\n current parameter vector.\n maxls : int, optional\n Maximum number of line search steps (per iteration). Default is 20.\n\n Returns\n -------\n x : array_like\n Estimated position of the minimum.\n f : float\n Value of `func` at the minimum.\n d : dict\n Information dictionary.\n\n * d['warnflag'] is\n\n - 0 if converged,\n - 1 if too many function evaluations or too many iterations,\n - 2 if stopped for another reason, given in d['task']\n\n * d['grad'] is the gradient at the minimum (should be 0 ish)\n * d['funcalls'] is the number of function calls made.\n * d['nit'] is the number of iterations.\n\n See also\n --------\n minimize: Interface to minimization algorithms for multivariate\n functions. See the 'L-BFGS-B' `method` in particular.\n\n Notes\n -----\n License of L-BFGS-B (FORTRAN code):\n\n The version included here (in fortran code) is 3.0\n (released April 25, 2011). It was written by Ciyou Zhu, Richard Byrd,\n and Jorge Nocedal . It carries the following\n condition for use:\n\n This software is freely available, but we expect that all publications\n describing work using this software, or all commercial products using it,\n quote at least one of the references given below. This software is released\n under the BSD License.\n\n References\n ----------\n * R. H. Byrd, P. Lu and J. Nocedal. A Limited Memory Algorithm for Bound\n Constrained Optimization, (1995), SIAM Journal on Scientific and\n Statistical Computing, 16, 5, pp. 1190-1208.\n * C. Zhu, R. H. Byrd and J. Nocedal. L-BFGS-B: Algorithm 778: L-BFGS-B,\n FORTRAN routines for large scale bound constrained optimization (1997),\n ACM Transactions on Mathematical Software, 23, 4, pp. 550 - 560.\n * J.L. Morales and J. Nocedal. L-BFGS-B: Remark on Algorithm 778: L-BFGS-B,\n FORTRAN routines for large scale bound constrained optimization (2011),\n ACM Transactions on Mathematical Software, 38, 1.\n\n \"\"\"\n # handle fprime/approx_grad\n if approx_grad:\n fun = func\n jac = None\n elif fprime is None:\n fun = MemoizeJac(func)\n jac = fun.derivative\n else:\n fun = func\n jac = fprime\n\n # build options\n if disp is None:\n disp = iprint\n opts = {'disp': disp,\n 'iprint': iprint,\n 'maxcor': m,\n 'ftol': factr * np.finfo(float).eps,\n 'gtol': pgtol,\n 'eps': epsilon,\n 'maxfun': maxfun,\n 'maxiter': maxiter,\n 'callback': callback,\n 'maxls': maxls}\n\n res = _minimize_lbfgsb(fun, x0, args=args, jac=jac, bounds=bounds,\n **opts)\n d = {'grad': res['jac'],\n 'task': res['message'],\n 'funcalls': res['nfev'],", "answers": [" 'nit': res['nit'],"], "length": 991, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "68c737c0-2b8a-4b95-bcb1-f8821bde1f36", "reasoning": "The code is constructing a dictionary `d` with results from the optimizer. It already includes keys 'grad', 'task', and 'funcalls'. The next logical entry is the number of iterations, typically stored under the key 'nit' from the result object. Therefore the next line adds the 'nit' entry.", "reasoning_model_answer": "'nit': res['nit'],", "assistant_with_reasoning": "\nThe code is constructing a dictionary `d` with results from the optimizer. It already includes keys 'grad', 'task', and 'funcalls'. The next logical entry is the number of iterations, typically stored under the key 'nit' from the result object. Therefore the next line adds the 'nit' entry.\n\n'nit': res['nit'],", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 5.215, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 7649, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "'nit': res['nit'],", "score": 0.8, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "# -*- coding: utf-8 -*-\nimport mock\nimport pytest\nimport urlparse\n\nfrom django.db import connection, transaction\nfrom django.test.utils import CaptureQueriesContext\nfrom django.utils.timezone import now\n\nfrom osf.utils.sanitize import strip_html\nfrom osf.models import QuickFilesNode\nfrom api.base.settings.defaults import API_BASE\nfrom api.base.utils import waterbutler_api_url_for\nfrom osf_tests.factories import (\n AuthUserFactory,\n CollectionFactory,\n ProjectFactory,\n)\nfrom website.views import find_bookmark_collection\n\n\n@pytest.mark.django_db\nclass TestUserDetail:\n\n @pytest.fixture()\n def user_one(self):\n user_one = AuthUserFactory()\n user_one.social['twitter'] = 'rheisendennis'\n user_one.save()\n return user_one\n\n @pytest.fixture()\n def user_two(self):\n return AuthUserFactory()\n\n def test_get(self, app, user_one, user_two):\n\n # test_gets_200\n url = '/{}users/{}/'.format(API_BASE, user_one._id)\n res = app.get(url)\n assert res.status_code == 200\n assert res.content_type == 'application/vnd.api+json'\n\n # test_get_correct_pk_user\n url = '/{}users/{}/'.format(API_BASE, user_one._id)\n res = app.get(url)\n user_json = res.json['data']\n assert user_json['attributes']['full_name'] == user_one.fullname\n assert user_one.social['twitter'] in user_json['attributes']['social']['twitter']\n\n # test_get_incorrect_pk_user_logged_in\n url = '/{}users/{}/'.format(API_BASE, user_two._id)\n res = app.get(url)\n user_json = res.json['data']\n assert user_json['attributes']['full_name'] != user_one.fullname\n\n # test_returns_timezone_and_locale\n url = '/{}users/{}/'.format(API_BASE, user_one._id)\n res = app.get(url)\n attributes = res.json['data']['attributes']\n assert attributes['timezone'] == user_one.timezone\n assert attributes['locale'] == user_one.locale\n\n # test_get_new_users\n url = '/{}users/{}/'.format(API_BASE, user_two._id)\n res = app.get(url)\n assert res.status_code == 200\n assert res.json['data']['attributes']['full_name'] == user_two.fullname\n assert res.json['data']['attributes']['social'] == {}\n\n # test_get_incorrect_pk_user_not_logged_in\n url = '/{}users/{}/'.format(API_BASE, user_two._id)\n res = app.get(url, auth=user_one.auth)\n user_json = res.json['data']\n assert user_json['attributes']['full_name'] != user_one.fullname\n assert user_json['attributes']['full_name'] == user_two.fullname\n\n # test_user_detail_takes_profile_image_size_param\n size = 42\n url = '/{}users/{}/?profile_image_size={}'.format(\n API_BASE, user_one._id, size)\n res = app.get(url)\n user_json = res.json['data']\n profile_image_url = user_json['links']['profile_image']\n query_dict = urlparse.parse_qs(\n urlparse.urlparse(profile_image_url).query)\n assert int(query_dict.get('s')[0]) == size\n\n # test_profile_image_in_links\n url = '/{}users/{}/'.format(API_BASE, user_one._id)\n res = app.get(url)\n user_json = res.json['data']\n assert 'profile_image' in user_json['links']\n\n def test_files_relationship_upload(self, app, user_one):\n url = '/{}users/{}/'.format(API_BASE, user_one._id)\n res = app.get(url, auth=user_one)\n quickfiles = QuickFilesNode.objects.get(creator=user_one)\n user_json = res.json['data']\n upload_url = user_json['relationships']['quickfiles']['links']['upload']['href']\n waterbutler_upload = waterbutler_api_url_for(\n quickfiles._id, 'osfstorage')\n\n assert upload_url == waterbutler_upload\n\n def test_preprint_relationship(self, app, user_one):\n url = '/{}users/{}/'.format(API_BASE, user_one._id)\n preprint_url = '/{}users/{}/preprints/'.format(API_BASE, user_one._id)\n res = app.get(url, auth=user_one)\n user_json = res.json['data']\n href_url = user_json['relationships']['preprints']['links']['related']['href']\n assert preprint_url in href_url\n\n def test_registrations_relationship(self, app, user_one):\n url = '/{}users/{}/'.format(API_BASE, user_one._id)\n registration_url = '/{}users/{}/registrations/'.format(\n API_BASE, user_one._id)\n res = app.get(url, auth=user_one)\n user_json = res.json['data']\n href_url = user_json['relationships']['registrations']['links']['related']['href']\n assert registration_url in href_url\n\n def test_nodes_relationship_is_absent(self, app, user_one):\n url = '/{}users/{}/'.format(API_BASE, user_one._id)\n res = app.get(url, auth=user_one)\n assert 'node' not in res.json['data']['relationships'].keys()\n\n # Regression test for https://openscience.atlassian.net/browse/OSF-8966\n def test_browsable_api_for_user_detail(self, app, user_one):\n url = '/{}users/{}/?format=api'.format(API_BASE, user_one._id)\n res = app.get(url, auth=user_one.auth)\n assert res.status_code == 200\n\n\n@pytest.mark.django_db\nclass TestUserRoutesNodeRoutes:\n\n @pytest.fixture()\n def user_one(self):\n user_one = AuthUserFactory()\n user_one.social['twitter'] = 'rheisendennis'\n user_one.save()\n return user_one\n\n @pytest.fixture()\n def user_two(self):\n return AuthUserFactory()\n\n @pytest.fixture()\n def project_public_user_one(self, user_one):\n return ProjectFactory(\n title='Public Project User One',\n is_public=True,\n creator=user_one)\n\n @pytest.fixture()\n def project_private_user_one(self, user_one):\n return ProjectFactory(\n title='Private Project User One',\n is_public=False,\n creator=user_one)\n\n @pytest.fixture()\n def project_deleted_user_one(self, user_one):\n return CollectionFactory(\n title='Deleted Project User One',\n is_public=False,\n creator=user_one,\n deleted=now())\n\n @pytest.fixture()\n def project_public_user_two(self, user_two):\n return ProjectFactory(\n title='Public Project User Two',\n is_public=True,\n creator=user_two)\n\n @pytest.fixture()\n def project_private_user_two(self, user_two):\n return ProjectFactory(\n title='Private Project User Two',\n is_public=False,\n creator=user_two)\n\n @pytest.fixture()\n def folder(self):\n return CollectionFactory()\n\n @pytest.fixture()\n def folder_deleted(self, user_one):\n return CollectionFactory(\n title='Deleted Folder User One',\n is_public=False,\n creator=user_one,\n deleted=now())\n\n @pytest.fixture()\n def bookmark_collection(self, user_one):\n return find_bookmark_collection(user_one)\n\n def test_get_200_responses(\n self, app, user_one, user_two,\n project_public_user_one,\n project_public_user_two,\n project_private_user_one,\n project_private_user_two,\n project_deleted_user_one,\n folder, folder_deleted,\n bookmark_collection):\n\n # test_get_200_path_users_me_userone_logged_in\n url = '/{}users/me/'.format(API_BASE)\n res = app.get(url, auth=user_one.auth)\n assert res.status_code == 200\n\n # test_get_200_path_users_me_usertwo_logged_in\n url = '/{}users/me/'.format(API_BASE)\n res = app.get(url, auth=user_two.auth)\n assert res.status_code == 200\n\n # test_get_200_path_users_user_id_user_logged_in\n url = '/{}users/{}/'.format(API_BASE, user_one._id)\n res = app.get(url, auth=user_one.auth)\n assert res.status_code == 200\n\n # test_get_200_path_users_user_id_no_user\n url = '/{}users/{}/'.format(API_BASE, user_two._id)\n res = app.get(url)\n assert res.status_code == 200\n\n # test_get_200_path_users_user_id_unauthorized_user\n url = '/{}users/{}/'.format(API_BASE, user_two._id)\n res = app.get(url, auth=user_one.auth)\n assert res.status_code == 200\n assert res.json['data']['id'] == user_two._id\n\n # test_get_200_path_users_me_nodes_user_logged_in\n url = '/{}users/me/nodes/'.format(API_BASE, user_one._id)\n res = app.get(url, auth=user_one.auth)\n assert res.status_code == 200\n\n ids = {each['id'] for each in res.json['data']}\n assert project_public_user_one._id in ids\n assert project_private_user_one._id in ids\n assert project_public_user_two._id not in ids\n assert project_private_user_two._id not in ids\n assert folder._id not in ids\n assert folder_deleted._id not in ids\n assert project_deleted_user_one._id not in ids\n\n # test_get_200_path_users_user_id_nodes_user_logged_in\n url = '/{}users/{}/nodes/'.format(API_BASE, user_one._id)\n res = app.get(url, auth=user_one.auth)\n assert res.status_code == 200\n\n ids = {each['id'] for each in res.json['data']}\n assert project_public_user_one._id in ids\n assert project_private_user_one._id in ids\n assert project_public_user_two._id not in ids\n assert project_private_user_two._id not in ids\n assert folder._id not in ids\n assert folder_deleted._id not in ids\n assert project_deleted_user_one._id not in ids\n\n # test_get_200_path_users_user_id_nodes_no_user\n url = '/{}users/{}/nodes/'.format(API_BASE, user_one._id)\n res = app.get(url)\n assert res.status_code == 200\n\n # an anonymous/unauthorized user can only see the public projects\n # user_one contributes to.\n ids = {each['id'] for each in res.json['data']}\n assert project_public_user_one._id in ids\n assert project_private_user_one._id not in ids\n assert project_public_user_two._id not in ids\n assert project_private_user_two._id not in ids\n assert folder._id not in ids\n assert folder_deleted._id not in ids\n assert project_deleted_user_one._id not in ids\n\n # test_get_200_path_users_user_id_nodes_unauthorized_user\n url = '/{}users/{}/nodes/'.format(API_BASE, user_one._id)\n res = app.get(url, auth=user_two.auth)\n assert res.status_code == 200\n\n # an anonymous/unauthorized user can only see the public projects\n # user_one contributes to.\n ids = {each['id'] for each in res.json['data']}\n assert project_public_user_one._id in ids\n assert project_private_user_one._id not in ids\n assert project_public_user_two._id not in ids\n assert project_private_user_two._id not in ids\n assert folder._id not in ids\n assert folder_deleted._id not in ids\n assert project_deleted_user_one._id not in ids\n\n def test_embed_nodes(self, app, user_one, project_public_user_one):\n\n url = '/{}users/{}/?embed=nodes'.format(API_BASE, user_one._id)\n res = app.get(url, auth=user_one.auth)\n assert res.status_code == 200\n embedded_data = res.json['data']['embeds']['nodes']['data'][0]['attributes']\n assert embedded_data['title'] == project_public_user_one.title\n\n def test_get_400_responses(self, app, user_one, user_two):\n\n # test_get_403_path_users_me_nodes_no_user\n # TODO: change expected exception from 403 to 401 for unauthorized\n # users\n\n url = '/{}users/me/nodes/'.format(API_BASE)\n res = app.get(url, expect_errors=True)\n assert res.status_code == 401\n\n # test_get_403_path_users_me_no_user\n # TODO: change expected exception from 403 to 401 for unauthorized\n # users\n url = '/{}users/me/'.format(API_BASE)\n res = app.get(url, expect_errors=True)\n assert res.status_code == 401\n\n # test_get_404_path_users_user_id_me_user_logged_in\n url = '/{}users/{}/me/'.format(API_BASE, user_one._id)\n res = app.get(url, auth=user_one.auth, expect_errors=True)\n assert res.status_code == 404\n\n # test_get_404_path_users_user_id_me_no_user\n url = '/{}users/{}/me/'.format(API_BASE, user_one._id)\n res = app.get(url, expect_errors=True)\n assert res.status_code == 404\n\n # test_get_404_path_users_user_id_me_unauthorized_user\n url = '/{}users/{}/me/'.format(API_BASE, user_one._id)\n res = app.get(url, auth=user_two.auth, expect_errors=True)\n assert res.status_code == 404\n\n # test_get_404_path_users_user_id_nodes_me_user_logged_in\n url = '/{}users/{}/nodes/me/'.format(API_BASE, user_one._id)\n res = app.get(url, auth=user_one.auth, expect_errors=True)\n assert res.status_code == 404\n\n # test_get_404_path_users_user_id_nodes_me_unauthorized_user\n url = '/{}users/{}/nodes/me/'.format(API_BASE, user_one._id)\n res = app.get(url, auth=user_two.auth, expect_errors=True)\n assert res.status_code == 404\n\n # test_get_404_path_users_user_id_nodes_me_no_user\n url = '/{}users/{}/nodes/me/'.format(API_BASE, user_one._id)\n res = app.get(url, expect_errors=True)\n assert res.status_code == 404\n\n # test_get_404_path_nodes_me_user_logged_in\n url = '/{}nodes/me/'.format(API_BASE)\n res = app.get(url, auth=user_one.auth, expect_errors=True)\n assert res.status_code == 404\n\n # test_get_404_path_nodes_me_no_user\n url = '/{}nodes/me/'.format(API_BASE)\n res = app.get(url, expect_errors=True)\n assert res.status_code == 404\n\n # test_get_404_path_nodes_user_id_user_logged_in\n url = '/{}nodes/{}/'.format(API_BASE, user_one._id)\n res = app.get(url, auth=user_one.auth, expect_errors=True)\n assert res.status_code == 404\n\n # test_get_404_path_nodes_user_id_unauthorized_user\n url = '/{}nodes/{}/'.format(API_BASE, user_one._id)\n res = app.get(url, auth=user_two.auth, expect_errors=True)\n assert res.status_code == 404\n\n # test_get_404_path_nodes_user_id_no_user\n url = '/{}nodes/{}/'.format(API_BASE, user_one._id)\n res = app.get(url, expect_errors=True)\n assert res.status_code == 404\n\n\n@pytest.mark.django_db\nclass TestUserUpdate:\n\n @pytest.fixture()\n def user_one(self):\n user_one = AuthUserFactory.build(\n fullname='Martin Luther King Jr.',\n given_name='Martin',\n family_name='King',\n suffix='Jr.',\n social=dict(\n github='userOneGithub',\n scholar='userOneScholar',\n profileWebsites=['http://www.useronepersonalwebsite.com'],\n twitter='userOneTwitter',\n linkedIn='userOneLinkedIn',\n impactStory='userOneImpactStory',\n orcid='userOneOrcid',\n researcherId='userOneResearcherId'\n )\n )\n user_one.save()\n return user_one\n\n @pytest.fixture()\n def user_two(self):\n return AuthUserFactory()\n\n @pytest.fixture()\n def url_user_one(self, user_one):\n return '/v2/users/{}/'.format(user_one._id)\n\n @pytest.fixture()\n def data_new_user_one(self, user_one):\n return {\n 'data': {\n 'type': 'users',\n 'id': user_one._id,\n 'attributes': {\n 'full_name': 'el-Hajj Malik el-Shabazz',\n 'given_name': 'Malcolm',\n 'middle_names': 'Malik el-Shabazz',\n 'family_name': 'X',\n 'suffix': 'Sr.',\n 'social': {\n 'github': ['http://github.com/even_newer_github/'],\n 'scholar': ['http://scholar.google.com/citations?user=newScholar'],\n 'profileWebsites': ['http://www.newpersonalwebsite.com'],\n 'twitter': ['http://twitter.com/newtwitter'],\n 'linkedIn': ['https://www.linkedin.com/newLinkedIn'],\n 'impactStory': ['https://impactstory.org/newImpactStory'],\n 'orcid': ['http://orcid.org/newOrcid'],\n 'researcherId': ['http://researcherid.com/rid/newResearcherId'],\n }},\n }}\n\n @pytest.fixture()\n def data_missing_id(self):\n return {\n 'data': {\n 'type': 'users',\n 'attributes': {\n 'full_name': 'el-Hajj Malik el-Shabazz',\n 'family_name': 'Z',\n }\n }\n }\n\n @pytest.fixture()\n def data_missing_type(self, user_one):\n return {\n 'data': {\n 'id': user_one._id,\n 'attributes': {\n 'fullname': 'el-Hajj Malik el-Shabazz',\n 'family_name': 'Z',\n }\n }\n }\n\n @pytest.fixture()\n def data_incorrect_id(self):\n return {\n 'data': {\n 'id': '12345',\n 'type': 'users',\n 'attributes': {\n 'full_name': 'el-Hajj Malik el-Shabazz',\n 'family_name': 'Z',\n }\n }\n }\n\n @pytest.fixture()\n def data_incorrect_type(self, user_one):\n return {\n 'data': {\n 'id': user_one._id,\n 'type': 'Wrong type.',\n 'attributes': {\n 'full_name': 'el-Hajj Malik el-Shabazz',\n 'family_name': 'Z',\n }\n }\n }\n\n @pytest.fixture()\n def data_blank_but_not_empty_full_name(self, user_one):\n return {\n 'data': {\n 'id': user_one._id,\n 'type': 'users',\n 'attributes': {\n 'full_name': ' '\n }\n\n }\n }\n\n def test_select_for_update(\n self, app, user_one, url_user_one, data_new_user_one):\n with transaction.atomic(), CaptureQueriesContext(connection) as ctx:\n res = app.patch_json_api(url_user_one, {\n 'data': {\n 'id': user_one._id,\n 'type': 'users',\n 'attributes': {\n 'family_name': data_new_user_one['data']['attributes']['family_name'],\n }\n }\n }, auth=user_one.auth)\n\n assert res.status_code == 200\n assert res.json['data']['attributes']['family_name'] == data_new_user_one['data']['attributes']['family_name']\n\n for_update_sql = connection.ops.for_update_sql()\n assert any(for_update_sql in query['sql']\n for query in ctx.captured_queries)\n\n @mock.patch('osf.utils.requests.settings.SELECT_FOR_UPDATE_ENABLED', False)\n def test_select_for_update_disabled(\n self, app, user_one, url_user_one, data_new_user_one):", "answers": [" with transaction.atomic(), CaptureQueriesContext(connection) as ctx:"], "length": 1290, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "7390e358-fbde-4168-ae19-c9a35efad179", "reasoning": "The method test_select_for_update_disabled is a counterpart to test_select_for_update, using the same transaction and query capture pattern but with SELECT_FOR_UPDATE disabled. The next line should start the context manager that opens a transaction and captures queries, mirroring the previous test.", "reasoning_model_answer": "with transaction.atomic(), CaptureQueriesContext(connection) as ctx:", "assistant_with_reasoning": "\nThe method test_select_for_update_disabled is a counterpart to test_select_for_update, using the same transaction and query capture pattern but with SELECT_FOR_UPDATE disabled. The next line should start the context manager that opens a transaction and captures queries, mirroring the previous test.\n\nwith transaction.atomic(), CaptureQueriesContext(connection) as ctx:", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.212, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 19180, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "with transaction.atomic(), CaptureQueriesContext(connection) as ctx:", "score": 0.94, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/*\n * Copyright 2006 Sascha Weinreuter\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.intellij.plugins.intelliLang;\n\nimport com.intellij.lang.Language;\nimport com.intellij.openapi.command.UndoConfirmationPolicy;\nimport com.intellij.openapi.command.WriteCommandAction;\nimport com.intellij.openapi.command.undo.GlobalUndoableAction;\nimport com.intellij.openapi.command.undo.UndoManager;\nimport com.intellij.openapi.command.undo.UndoableAction;\nimport com.intellij.openapi.components.PersistentStateComponent;\nimport com.intellij.openapi.components.ServiceManager;\nimport com.intellij.openapi.components.State;\nimport com.intellij.openapi.components.Storage;\nimport com.intellij.openapi.diagnostic.Logger;\nimport com.intellij.openapi.extensions.Extensions;\nimport com.intellij.openapi.extensions.PluginDescriptor;\nimport com.intellij.openapi.project.Project;\nimport com.intellij.openapi.util.*;\nimport com.intellij.psi.PsiCompiledElement;\nimport com.intellij.psi.PsiElement;\nimport com.intellij.psi.PsiFile;\nimport com.intellij.psi.PsiLanguageInjectionHost;\nimport com.intellij.psi.util.CachedValue;\nimport com.intellij.psi.util.CachedValueProvider;\nimport com.intellij.psi.util.PsiUtilCore;\nimport com.intellij.util.ArrayUtil;\nimport com.intellij.util.CachedValueImpl;\nimport com.intellij.util.FileContentUtil;\nimport com.intellij.util.PairProcessor;\nimport com.intellij.util.containers.*;\nimport gnu.trove.THashMap;\nimport gnu.trove.THashSet;\nimport org.intellij.plugins.intelliLang.inject.InjectorUtils;\nimport org.intellij.plugins.intelliLang.inject.LanguageInjectionConfigBean;\nimport org.intellij.plugins.intelliLang.inject.LanguageInjectionSupport;\nimport org.intellij.plugins.intelliLang.inject.config.BaseInjection;\nimport org.intellij.plugins.intelliLang.inject.config.InjectionPlace;\nimport org.jdom.Element;\nimport org.jdom.JDOMException;\nimport org.jetbrains.annotations.NonNls;\nimport org.jetbrains.annotations.NotNull;\nimport org.jetbrains.annotations.Nullable;\n\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.net.URL;\nimport java.util.*;\n\n/**\n * Configuration that holds configured xml tag, attribute and method parameter\n * injection settings as well as the annotations to use for injection, pattern\n * validation and for substituting non-compile time constant expression.\n *\n * Making it a service may result in FileContentUtil.reparseFiles at a random loading moment which may cause\n * mysterious PSI validity losses\n */\npublic class Configuration extends SimpleModificationTracker implements PersistentStateComponent, ModificationTracker {\n static final Logger LOG = Logger.getInstance(Configuration.class.getName());\n private static final Condition LANGUAGE_INJECTION_CONDITION =\n o -> Language.findLanguageByID(o.getInjectedLanguageId()) != null;\n\n @State(name = Configuration.COMPONENT_NAME, defaultStateAsResource = true, storages = @Storage(\"IntelliLang.xml\"))\n public static class App extends Configuration {\n private final List myDefaultInjections;\n private final AdvancedConfiguration myAdvancedConfiguration;\n\n App() {\n myDefaultInjections = loadDefaultInjections();\n myAdvancedConfiguration = new AdvancedConfiguration();\n }\n\n @Override\n public List getDefaultInjections() {\n return myDefaultInjections;\n }\n\n @Override\n public AdvancedConfiguration getAdvancedConfiguration() {\n return myAdvancedConfiguration;\n }\n\n @Override\n public void loadState(final Element element) {\n myAdvancedConfiguration.loadState(element);\n super.loadState(element);\n }\n\n @Override\n public Element getState() {\n final Element element = new Element(COMPONENT_NAME);\n myAdvancedConfiguration.writeState(element);\n return getState(element);\n }\n }\n\n @State(name = Configuration.COMPONENT_NAME, defaultStateAsResource = true, storages = @Storage(\"IntelliLang.xml\"))\n public static class Prj extends Configuration {\n\n private final Configuration myParentConfiguration;\n\n Prj(final Configuration configuration) {\n myParentConfiguration = configuration;\n }\n\n @Override\n public AdvancedConfiguration getAdvancedConfiguration() {\n return myParentConfiguration.getAdvancedConfiguration();\n }\n\n @Override\n public List getDefaultInjections() {\n return myParentConfiguration.getDefaultInjections();\n }\n\n @Override\n protected Collection getAllInjections() {\n Collection injections = super.getAllInjections();\n injections.addAll(myParentConfiguration.getAllInjections());\n return injections;\n }\n\n @NotNull\n @Override\n public List getInjections(final String injectorId) {\n return ContainerUtil.concat(myParentConfiguration.getInjections(injectorId), getOwnInjections(injectorId));\n }\n\n public Configuration getParentConfiguration() {\n return myParentConfiguration;\n }\n\n public List getOwnInjections(final String injectorId) {\n return super.getInjections(injectorId);\n }\n\n @Override\n public long getModificationCount() {\n return super.getModificationCount() + myParentConfiguration.getModificationCount();\n }\n\n @Override\n public boolean replaceInjections(List newInjections,\n List originalInjections,\n boolean forceLevel) {\n if (!forceLevel && !originalInjections.isEmpty()) {\n if (myParentConfiguration.replaceInjections(Collections.emptyList(), originalInjections, false)) {\n myParentConfiguration.replaceInjections(newInjections, Collections.emptyList(), false);\n return true;\n }\n }\n return super.replaceInjections(newInjections, originalInjections, forceLevel);\n }\n }\n\n public enum InstrumentationType {\n NONE, ASSERT, EXCEPTION\n }\n\n public enum DfaOption {\n OFF, RESOLVE, ASSIGNMENTS, DFA\n }\n\n @NonNls public static final String COMPONENT_NAME = \"LanguageInjectionConfiguration\";\n\n // element names\n @NonNls private static final String INSTRUMENTATION_TYPE_NAME = \"INSTRUMENTATION\";\n @NonNls private static final String LANGUAGE_ANNOTATION_NAME = \"LANGUAGE_ANNOTATION\";\n @NonNls private static final String PATTERN_ANNOTATION_NAME = \"PATTERN_ANNOTATION\";\n @NonNls private static final String SUBST_ANNOTATION_NAME = \"SUBST_ANNOTATION\";\n @NonNls private static final String RESOLVE_REFERENCES = \"RESOLVE_REFERENCES\";\n @NonNls private static final String LOOK_FOR_VAR_ASSIGNMENTS = \"LOOK_FOR_VAR_ASSIGNMENTS\";\n @NonNls private static final String USE_DFA_IF_AVAILABLE = \"USE_DFA_IF_AVAILABLE\";\n @NonNls private static final String INCLUDE_UNCOMPUTABLES_AS_LITERALS = \"INCLUDE_UNCOMPUTABLES_AS_LITERALS\";\n @NonNls private static final String SOURCE_MODIFICATION_ALLOWED = \"SOURCE_MODIFICATION_ALLOWED\";\n\n private final Map> myInjections = new ConcurrentFactoryMap>() {\n @Override\n protected List create(final String key) {\n return ContainerUtil.createLockFreeCopyOnWriteList();\n }\n };\n\n protected Collection getAllInjections() {\n List injections = new ArrayList<>();\n for (List list : myInjections.values()) {\n injections.addAll(list);\n }\n return injections;\n }\n\n private final CachedValue> myInjectionsById = new CachedValueImpl<>(() -> {\n MultiMap map = new MultiMap<>();\n for (BaseInjection injection : getAllInjections()) {\n map.putValue(injection.getInjectedLanguageId(), injection);\n }\n return CachedValueProvider.Result.create(map, this);\n });\n\n public Configuration() {\n }\n\n public AdvancedConfiguration getAdvancedConfiguration() {\n throw new UnsupportedOperationException(\"getAdvancedConfiguration should not be called\");\n }\n\n @Override\n public void loadState(final Element element) {\n myInjections.clear();\n\n List injectionElements = element.getChildren(\"injection\");\n if (!injectionElements.isEmpty()) {\n final Map supports = new THashMap<>();\n for (LanguageInjectionSupport support : InjectorUtils.getActiveInjectionSupports()) {\n supports.put(support.getId(), support);\n }\n for (Element child : injectionElements) {\n final String key = child.getAttributeValue(\"injector-id\");\n final LanguageInjectionSupport support = supports.get(key);\n final BaseInjection injection = support == null ? new BaseInjection(key) : support.createInjection(child);\n injection.loadState(child);\n InjectionPlace[] places = dropKnownInvalidPlaces(injection.getInjectionPlaces());\n if (places != null) { // not all places were removed\n injection.setInjectionPlaces(places);\n myInjections.get(key).add(injection);\n }\n }\n }\n\n importPlaces(getDefaultInjections());\n }\n\n @Nullable\n private static InjectionPlace[] dropKnownInvalidPlaces(InjectionPlace[] places) {\n InjectionPlace[] result = places;\n for (InjectionPlace place : places) {\n if (place.getText().contains(\"matches(\\\"[^${}/\\\\\\\\]+\\\")\")) {\n result = ArrayUtil.remove(result, place);\n }\n }\n return places.length != 0 && result.length == 0? null : result;\n }\n\n private static boolean readBoolean(Element element, String key, boolean defValue) {\n final String value = JDOMExternalizerUtil.readField(element, key);\n if (value == null) return defValue;\n return Boolean.parseBoolean(value);\n }\n\n private static List loadDefaultInjections() {\n final List cfgList = new ArrayList<>();\n final Set visited = new THashSet<>();\n for (LanguageInjectionConfigBean configBean : Extensions.getExtensions(LanguageInjectionSupport.CONFIG_EP_NAME)) {\n PluginDescriptor descriptor = configBean.getPluginDescriptor();\n final ClassLoader loader = descriptor.getPluginClassLoader();\n try {\n final Enumeration enumeration = loader.getResources(configBean.getConfigUrl());\n if (enumeration == null || !enumeration.hasMoreElements()) {\n LOG.warn(descriptor.getPluginId() +\": \" + configBean.getConfigUrl() + \" was not found\");\n }\n else {\n while (enumeration.hasMoreElements()) {\n URL url = enumeration.nextElement();\n if (!visited.add(url.getFile())) continue; // for DEBUG mode\n InputStream stream = null;\n try {\n stream = url.openStream();\n cfgList.add(load(stream));\n }\n catch (Exception e) {\n LOG.warn(e);\n }\n finally {\n if (stream != null) {\n stream.close();\n }\n }\n }\n }\n }\n catch (Exception e) {\n LOG.warn(e);\n }\n }\n\n final List defaultInjections = new ArrayList<>();\n for (String supportId : InjectorUtils.getActiveInjectionSupportIds()) {\n for (Configuration cfg : cfgList) {\n final List imported = cfg.getInjections(supportId);\n defaultInjections.addAll(imported);\n }\n }\n return defaultInjections;\n }\n\n @Override\n public Element getState() {\n return getState(new Element(COMPONENT_NAME));\n }\n\n protected Element getState(Element element) {\n Comparator comparator = (o1, o2) -> {\n int rc = Comparing.compare(o1.getDisplayName(), o2.getDisplayName());\n if (rc != 0) return rc;\n return ContainerUtil.compareLexicographically(\n Arrays.asList(o1.getInjectionPlaces()),\n Arrays.asList(o2.getInjectionPlaces()),\n (o11, o22) -> {\n if (o11.isEnabled() && !o22.isEnabled()) return -1;\n if (!o11.isEnabled() && o22.isEnabled()) return 1;\n return Comparing.compare(o11.getElementPattern().toString(), o22.getElementPattern().toString());\n });\n };\n for (String key : ContainerUtil.newTreeSet(myInjections.keySet())) {\n Set injections = ContainerUtil.newHashSet(myInjections.get(key));\n injections.removeAll(getDefaultInjections());\n for (BaseInjection injection : ContainerUtil.sorted(injections, comparator)) {\n element.addContent(injection.getState());\n }\n }\n return element;\n }\n\n public static Configuration getInstance() {\n return ServiceManager.getService(Configuration.class);\n }\n\n public static Configuration getProjectInstance(Project project) {\n return ServiceManager.getService(project, Configuration.class);\n }\n\n public List getDefaultInjections() {\n return Collections.emptyList();\n }\n\n public Collection getInjectionsByLanguageId(String languageId) {\n return myInjectionsById.getValue().get(languageId);\n }\n\n @Nullable\n public static Configuration load(final InputStream is) throws IOException, JDOMException {\n final List elements = new ArrayList<>();\n final Element rootElement = JDOMUtil.load(is);\n final Element state;\n if (rootElement.getName().equals(COMPONENT_NAME)) {\n state = rootElement;\n }\n else {\n elements.add(rootElement);\n //noinspection unchecked\n elements.addAll(rootElement.getChildren(\"component\"));\n state = ContainerUtil.find(elements, element -> \"component\".equals(element.getName()) && COMPONENT_NAME.equals(element.getAttributeValue(\"name\")));\n }\n if (state != null) {\n final Configuration cfg = new Configuration();\n cfg.loadState(state);\n return cfg;\n }\n return null;\n }\n\n private int importPlaces(final List injections) {\n final Map> map = ContainerUtil.classify(injections.iterator(), new Convertor() {\n @Override\n public String convert(final BaseInjection o) {\n return o.getSupportId();\n }\n });\n List originalInjections = new ArrayList<>();\n List newInjections = new ArrayList<>();\n for (String supportId : InjectorUtils.getActiveInjectionSupportIds()) {\n final Set importingInjections = map.get(supportId);\n if (importingInjections == null) continue;\n importInjections(getInjections(supportId), importingInjections, originalInjections, newInjections);\n }\n if (!newInjections.isEmpty()) configurationModified();\n replaceInjections(newInjections, originalInjections, true);\n return newInjections.size();\n }\n\n static void importInjections(final Collection existingInjections, final Collection importingInjections,\n final Collection originalInjections, final Collection newInjections) {\n final MultiValuesMap placeMap = new MultiValuesMap<>();\n for (BaseInjection exising : existingInjections) {\n for (InjectionPlace place : exising.getInjectionPlaces()) {\n placeMap.put(place, exising);\n }\n }\n main: for (BaseInjection other : importingInjections) {\n InjectionPlace[] places = other.getInjectionPlaces();\n if (places.length == 0) {\n if (!existingInjections.contains(other)) newInjections.add(other);\n continue;\n }\n final Set matchingInjections = JBIterable.of(places)\n .flatten(o -> JBIterable.from(placeMap.get(o))).toSet();\n if (matchingInjections.isEmpty()) {\n newInjections.add(other);\n }\n else {\n BaseInjection existing = null;", "answers": [" for (BaseInjection injection : matchingInjections) {"], "length": 1276, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "ec243f98-c315-4623-ac09-fce050f89fe5", "reasoning": "The method importInjections is processing matching injections. After initializing a variable 'BaseInjection existing = null;' the code will iterate over the matchingInjections collection to find a suitable existing injection. The typical next line is a for-each loop over matchingInjections, e.g., 'for (BaseInjection inj : matchingInjections) {'. This fits the surrounding context and Java syntax.", "reasoning_model_answer": "for (BaseInjection inj : matchingInjections) {", "assistant_with_reasoning": "\nThe method importInjections is processing matching injections. After initializing a variable 'BaseInjection existing = null;' the code will iterate over the matchingInjections collection to find a suitable existing injection. The typical next line is a for-each loop over matchingInjections, e.g., 'for (BaseInjection inj : matchingInjections) {'. This fits the surrounding context and Java syntax.\n\nfor (BaseInjection inj : matchingInjections) {", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.294, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 16399, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "for (BaseInjection inj : matchingInjections) {", "score": 0.87, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "// SPDX-License-Identifier: BSD-3-Clause\npackage org.xbill.DNS.dnssec;\n\nimport static org.junit.jupiter.api.Assertions.assertEquals;\nimport static org.mockito.Mockito.when;\n\nimport java.io.File;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.security.Security;\nimport java.text.ParseException;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Map.Entry;\nimport java.util.Properties;\nimport org.bouncycastle.jce.provider.BouncyCastleProvider;\nimport org.junit.jupiter.api.Disabled;\nimport org.junit.jupiter.api.Test;\nimport org.xbill.DNS.CNAMERecord;\nimport org.xbill.DNS.DNAMERecord;\nimport org.xbill.DNS.DNSSEC;\nimport org.xbill.DNS.Flags;\nimport org.xbill.DNS.Message;\nimport org.xbill.DNS.Name;\nimport org.xbill.DNS.RRSIGRecord;\nimport org.xbill.DNS.RRset;\nimport org.xbill.DNS.Rcode;\nimport org.xbill.DNS.Record;\nimport org.xbill.DNS.Section;\nimport org.xbill.DNS.Type;\n\nclass UnboundTests extends TestBase {\n void runUnboundTest() throws ParseException, IOException {\n InputStream data = getClass().getResourceAsStream(\"/unbound/\" + testName + \".rpl\");\n RplParser p = new RplParser(data);\n Rpl rpl = p.parse();\n Properties config = new Properties();\n if (rpl.nsec3iterations != null) {\n for (Entry e : rpl.nsec3iterations.entrySet()) {\n config.put(\"dnsjava.dnssec.nsec3.iterations.\" + e.getKey(), e.getValue());\n }\n }\n\n if (rpl.digestPreference != null) {\n config.put(ValUtils.DIGEST_PREFERENCE, rpl.digestPreference);\n }\n\n config.put(ValUtils.DIGEST_HARDEN_DOWNGRADE, Boolean.toString(rpl.hardenAlgoDowngrade));\n\n if (rpl.enableSha1) {\n config.put(ValUtils.DIGEST_ENABLED + \".\" + DNSSEC.Digest.SHA1, Boolean.TRUE.toString());\n }\n\n if (rpl.enableDsa || rpl.enableSha1) {\n config.put(ValUtils.ALGORITHM_ENABLED + \".\" + DNSSEC.Algorithm.DSA, Boolean.TRUE.toString());\n config.put(\n ValUtils.ALGORITHM_ENABLED + \".\" + DNSSEC.Algorithm.DSA_NSEC3_SHA1,\n Boolean.TRUE.toString());\n }\n\n if (rpl.loadBouncyCastle) {\n Security.addProvider(new BouncyCastleProvider());\n }\n\n for (Message m : rpl.replays) {\n add(m);\n }\n\n // merge xNAME queries into one\n List copy = new ArrayList<>(rpl.replays.size());\n copy.addAll(rpl.replays);\n List copiedTargets = new ArrayList<>(5);\n for (Message m : copy) {\n Name target = null;\n for (RRset s : m.getSectionRRsets(Section.ANSWER)) {\n if (s.getType() == Type.CNAME) {\n target = ((CNAMERecord) s.first()).getTarget();\n } else if (s.getType() == Type.DNAME) {\n target = ((DNAMERecord) s.first()).getTarget();\n }\n\n while (target != null) {\n Message a = get(target, m.getQuestion().getType());\n if (a == null) {\n a = get(target, Type.CNAME);\n }\n\n if (a == null) {\n a = get(target, Type.DNAME);\n }\n\n if (a != null) {\n target = add(m, a);\n if (copiedTargets.contains(target)) {\n break;\n }\n\n copiedTargets.add(target);\n rpl.replays.remove(a);\n } else {\n target = null;\n }\n }\n }\n }\n\n // promote any DS records in auth. sections to real queries\n copy = new ArrayList<>(rpl.replays.size());\n copy.addAll(rpl.replays);\n for (Message m : copy) {\n for (RRset s : m.getSectionRRsets(Section.AUTHORITY)) {\n if (s.getType() == Type.DS) {\n Message ds = new Message();\n ds.addRecord(Record.newRecord(s.getName(), s.getType(), s.getDClass()), Section.QUESTION);\n for (Record rr : s.rrs()) {\n ds.addRecord(rr, Section.ANSWER);\n }\n\n for (RRSIGRecord sig : s.sigs()) {\n ds.addRecord(sig, Section.ANSWER);\n }\n\n rpl.replays.add(ds);\n }\n }\n }\n\n clear();\n for (Message m : rpl.replays) {\n add(m);\n }\n\n if (rpl.date != null) {\n try {\n when(resolverClock.instant()).thenReturn(rpl.date);\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }\n\n if (rpl.trustAnchors != null) {\n resolver.getTrustAnchors().clear();\n for (SRRset rrset : rpl.trustAnchors) {\n resolver.getTrustAnchors().store(rrset);\n }\n }\n\n resolver.init(config);\n\n for (Check c : rpl.checks.values()) {\n Message s = resolver.send(c.query);\n Security.removeProvider(BouncyCastleProvider.PROVIDER_NAME);\n assertEquals(\n c.response.getHeader().getFlag(Flags.AD),\n s.getHeader().getFlag(Flags.AD),\n \"AD Flag must match\");\n assertEquals(\n Rcode.string(c.response.getRcode()), Rcode.string(s.getRcode()), \"RCode must match\");\n }\n }\n\n private Name add(Message target, Message source) {\n Name next = null;\n target.getHeader().setRcode(source.getRcode());\n for (Record r : source.getSection(Section.ANSWER)) {\n target.addRecord(r, Section.ANSWER);\n if (r.getType() == Type.CNAME) {\n next = ((CNAMERecord) r).getTarget();\n } else if (r.getType() == Type.DNAME) {\n next = ((DNAMERecord) r).getTarget();\n }\n }\n\n for (Record r : source.getSection(Section.AUTHORITY)) {\n if (r.getType() != Type.NS) {\n target.addRecord(r, Section.AUTHORITY);\n }\n }\n\n return next;\n }\n\n static void xmain(String[] xargs) {\n Map ignored =\n new HashMap() {\n {\n put(\"val_faildnskey_ok.rpl\", \"tests an unbound specific config option\");\n put(\"val_nsec3_nods_negcache.rpl\", \"we don't do negative caching\");\n put(\"val_unsecds_negcache.rpl\", \"we don't do negative caching\");\n put(\"val_negcache_dssoa.rpl\", \"we don't do negative caching\");\n put(\"val_negcache_nodata.rpl\", \"aggressive NSEC is not supported\");\n put(\"val_negcache_nxdomain.rpl\", \"aggressive NSEC is not supported\");\n put(\"val_nsec3_b3_optout_negcache.rpl\", \"we don't do negative caching\");\n put(\"val_dsnsec.rpl\", \"we don't do negative caching\");\n put(\"val_refer_unsignadd.rpl\", \"we don't do negative caching\");\n put(\"val_referglue.rpl\", \"we don't do negative caching\");\n put(\n \"val_noadwhennodo.rpl\",\n \"irrelevant - if we wouldn't want AD, we wouldn't be using this stuff\");\n put(\"val_fwdds.rpl\", \"irrelevant, we're not a recursive resolver\");\n put(\"val_referd.rpl\", \"NSEC records missing for validation, tests caching stuff\");\n put(\"val_stubds.rpl\", \"tests unbound specific config (stub zones)\");\n put(\"val_cnametonsec.rpl\", \"incomplete CNAME answer\");\n put(\"val_cnametooptin.rpl\", \"incomplete CNAME answer\");\n put(\"val_cnametoinsecure.rpl\", \"incomplete CNAME answer\");\n put(\"val_nsec3_optout_cache.rpl\", \"more cache stuff\");\n put(\"val_unsecds_qtypeds.rpl\", \"tests the iterative resolver\");\n put(\"val_anchor_nx.rpl\", \"tests caching of NX from a parent resolver\");\n put(\"val_anchor_nx_nosig.rpl\", \"tests caching of NX from a parent resolver\");\n put(\"val_negcache_nta.rpl\", \"tests unbound option domain-insecure, not available here\");\n }\n };\n\n for (String f : new File(\"./src/test/resources/unbound\").list()) {\n String comment = ignored.get(f);\n if (comment != null) {\n System.out.println(\" @Disabled(\\\"\" + comment + \"\\\")\");\n }\n\n System.out.println(\" @Test\");\n System.out.println(\n \" void \" + f.split(\"\\\\.\")[0] + \"() throws ParseException, IOException {\");\n System.out.println(\" runUnboundTest();\");\n System.out.println(\" }\");\n System.out.println();\n }\n }\n\n @Test\n void val_adbit() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_adcopy() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Disabled(\"tests caching of NX from a parent resolver\")\n @Test\n void val_anchor_nx() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Disabled(\"tests caching of NX from a parent resolver\")\n @Test\n void val_anchor_nx_nosig() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_ans_dsent() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_ans_nx() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_any() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_any_cname() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_any_dname() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_cnameinsectopos() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_cnamenx_dblnsec() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_cnamenx_rcodenx() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_cnameqtype() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_cnametocloser() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_cnametocloser_nosig() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_cnametocnamewctoposwc() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_cnametodname() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_cnametodnametocnametopos() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Disabled(\"incomplete CNAME answer\")\n @Test\n void val_cnametoinsecure() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_cnametonodata() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_cnametonodata_nonsec() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Disabled(\"incomplete CNAME answer\")\n @Test\n void val_cnametonsec() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_cnametonx() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Disabled(\"incomplete CNAME answer\")\n @Test\n void val_cnametooptin() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_cnametooptout() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_cnametopos() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_cnametoposnowc() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_cnametoposwc() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_cnamewctonodata() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_cnamewctonx() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_cnamewctoposwc() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_cname_loop1() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_cname_loop2() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_cname_loop3() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_dnametoolong() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_dnametopos() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_dnametoposwc() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_dnamewc() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Disabled(\"we don't do negative caching\")\n @Test\n void val_dsnsec() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_ds_afterprime() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_ds_cname() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_ds_cnamesub() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_ds_cnamesubbogus() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_ds_gost() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_ds_gost_downgrade() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_ds_sha2() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_ds_sha2_downgrade() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_ds_sha2_downgrade_override() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_ds_sha2_lenient() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_entds() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_faildnskey() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Disabled(\"tests an unbound specific config option\")\n @Test\n void val_faildnskey_ok() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Disabled(\"irrelevant, we're not a recursive resolver\")\n @Test\n void val_fwdds() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_keyprefetch() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_keyprefetch_verify() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_mal_wc() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Test\n void val_negcache_ds() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Disabled(\"we don't do negative caching\")\n @Test\n void val_negcache_dssoa() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Disabled(\"aggressive NSEC is not supported\")\n @Test\n void val_negcache_nodata() throws ParseException, IOException {\n runUnboundTest();\n }\n\n @Disabled(\"tests unbound option domain-insecure, not available here\")", "answers": [" @Test"], "length": 1271, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "43456bd2-b2c9-45c4-bfca-fde69f8ef640", "reasoning": "The code defines a series of JUnit test methods, each preceded by optional @Disabled annotations. The last line shown is a @Disabled annotation for the test that checks the unbound option domain‑insecure, which corresponds to the test method val_negcache_nta. Following the pattern, the next line should be the @Test annotation that starts the method definition.", "reasoning_model_answer": "@Test", "assistant_with_reasoning": "\nThe code defines a series of JUnit test methods, each preceded by optional @Disabled annotations. The last line shown is a @Disabled annotation for the test that checks the unbound option domain‑insecure, which corresponds to the test method val_negcache_nta. Following the pattern, the next line should be the @Test annotation that starts the method definition.\n\n@Test", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.817, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 14345, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "@Test", "score": 0.83, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/* Copyright 2019 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*/\n\npackage org.tensorflow.lite.support.tensorbuffer;\n\nimport java.nio.ByteBuffer;\nimport java.nio.ByteOrder;\nimport java.util.Arrays;\nimport org.checkerframework.checker.nullness.qual.NonNull;\nimport org.tensorflow.lite.DataType;\nimport org.tensorflow.lite.support.common.SupportPrecondtions;\n\n/** Represents the data buffer for either a model's input or its output. */\npublic abstract class TensorBuffer {\n /** Where the data is stored. */\n protected ByteBuffer buffer;\n\n /** Shape of the tensor stored in this buffer. */\n protected int[] shape;\n\n /** Number of elements in the buffer. It will be changed to a proper value in the constructor. */\n protected int flatSize = -1;\n\n /**\n * Indicator of whether this buffer is dynamic or fixed-size. Fixed-size buffers will have\n * pre-allocated memory and fixed size. While the size of dynamic buffers can be changed.\n */\n protected final boolean isDynamic;\n\n /**\n * Creates a {@link TensorBuffer} with specified {@code shape} and {@link DataType}. Here are some\n * examples:\n *\n *
    \n   * Creating a float TensorBuffer with shape {2, 3}:\n   * int[] shape = new int[] {2, 3};\n   * TensorBuffer tensorBuffer = TensorBuffer.createFixedSize(shape, DataType.FLOAT32);\n   * 
    \n *\n *
    \n   * Creating an uint8 TensorBuffer of a scalar:\n   * int[] shape = new int[] {};\n   * TensorBuffer tensorBuffer = TensorBuffer.createFixedSize(shape, DataType.UINT8);\n   * 
    \n *\n *
    \n   * Creating an empty uint8 TensorBuffer:\n   * int[] shape = new int[] {0};\n   * TensorBuffer tensorBuffer = TensorBuffer.createFixedSize(shape, DataType.UINT8);\n   * 
    \n *\n *

    The size of a fixed-size TensorBuffer cannot be changed once it is created. However, loading\n * arraies or data buffers of the same buffer size but different shapes is allowed.\n *\n *

    TODO(b/139782181): Shall we make it fixed-size or fixed-shape?\n *\n * @param shape The shape of the {@link TensorBuffer} to be created.\n * @param dataType The dataType of the {@link TensorBuffer} to be created.\n * @throws NullPointerException if {@code shape} is null.\n * @throws IllegalArgumentException if {@code shape} has non-positive elements.\n */\n @NonNull\n public static TensorBuffer createFixedSize(@NonNull int[] shape, DataType dataType) {\n switch (dataType) {\n case FLOAT32:\n return new TensorBufferFloat(shape);\n case UINT8:\n return new TensorBufferUint8(shape);\n default:\n throw new AssertionError(\"TensorBuffer does not support data type: \" + dataType);\n }\n }\n\n /**\n * Creates an empty dynamic {@link TensorBuffer} with specified {@link DataType}. The shape of the\n * created {@link TensorBuffer} is {0}.\n *\n *

    Dynamic TensorBuffers will reallocate memory when Loading arraies or data buffers of\n * different buffer sizes.\n *\n * @param dataType The dataType of the {@link TensorBuffer} to be created.\n */\n @NonNull\n public static TensorBuffer createDynamic(DataType dataType) {\n switch (dataType) {\n case FLOAT32:\n return new TensorBufferFloat();\n case UINT8:\n return new TensorBufferUint8();\n default:\n throw new AssertionError(\"TensorBuffer does not support data type: \" + dataType);\n }\n }\n\n /**\n * Creates a {@link TensorBuffer} deep-copying data from another, with specified {@link DataType}.\n *\n * @param buffer the source {@link TensorBuffer} to copy from.\n * @param dataType the expected {@link DataType} of newly created {@link TensorBuffer}.\n * @throws NullPointerException if {@code buffer} is null.\n */\n @NonNull\n public static TensorBuffer createFrom(@NonNull TensorBuffer buffer, DataType dataType) {\n SupportPrecondtions.checkNotNull(buffer, \"Cannot create a buffer from null\");\n TensorBuffer result;\n if (buffer.isDynamic()) {\n result = createDynamic(dataType);\n } else {\n result = createFixedSize(buffer.shape, dataType);\n }\n // The only scenario we need float array is FLOAT32->FLOAT32, or we can always use INT as\n // intermediate container.\n // The assumption is not true when we support other data types.\n if (buffer.getDataType() == DataType.FLOAT32 && dataType == DataType.FLOAT32) {\n float[] data = buffer.getFloatArray();\n result.loadArray(data, buffer.shape);\n } else {\n int[] data = buffer.getIntArray();\n result.loadArray(data, buffer.shape);\n }\n return result;\n }\n\n /** Returns the data buffer. */\n @NonNull\n public ByteBuffer getBuffer() {\n return buffer;\n }\n\n /** Gets the {@link TensorBuffer#flatSize} of the buffer. */\n public int getFlatSize() {\n return flatSize;\n }\n\n /** Gets the current shape. (returning a copy here to avoid unexpected modification.) */\n @NonNull\n public int[] getShape() {\n return Arrays.copyOf(shape, shape.length);\n }\n\n /** Returns the data type of this buffer. */\n public abstract DataType getDataType();\n\n /**\n * Returns a float array of the values stored in this buffer. If the buffer is of different types\n * than float, the values will be converted into float. For example, values in {@link\n * TensorBufferUint8} will be converted from uint8 to float.\n */\n @NonNull\n public abstract float[] getFloatArray();\n\n /**\n * Returns an int array of the values stored in this buffer. If the buffer is of different type\n * than int, the values will be converted into int, and loss of precision may apply. For example,\n * getting an int array from a {@link TensorBufferFloat} with values {400.32f, 23.04f}, the output\n * is {400, 23}.\n */\n @NonNull\n public abstract int[] getIntArray();\n\n /**\n * Returns the number of bytes of a single element in the array. For example, a float buffer will\n * return 4, and a byte buffer will return 1.\n */\n public abstract int getTypeSize();\n\n /** Returns if the TensorBuffer is dynamic sized (could resize arbitrarily). */\n public boolean isDynamic() {\n return isDynamic;\n }\n\n /**\n * Loads an int array into this buffer with specific shape. If the buffer is of different types\n * than int, the values will be converted into the buffer's type before being loaded into the\n * buffer, and loss of precision may apply. For example, loading an int array with values {400,\n * -23} into a {@link TensorBufferUint8} , the values will be clamped to [0, 255] and then be\n * casted to uint8 by {255, 0}.\n *\n * @param src The source array to be loaded.\n * @param shape Shape of the tensor that {@code src} represents.\n * @throws NullPointerException if {@code src} is null.\n * @throws NullPointerException if {@code shape} is null.\n * @throws IllegalArgumentException if the size of the array to be loaded does not match the\n * specified shape.\n */\n public abstract void loadArray(@NonNull int[] src, @NonNull int[] shape);\n\n /**\n * Loads an int array into this buffer. If the buffer is of different types than int, the values\n * will be converted into the buffer's type before being loaded into the buffer, and loss of\n * precision may apply. For example, loading an int array with values {400, -23} into a {@link\n * TensorBufferUint8} , the values will be clamped to [0, 255] and then be casted to uint8 by\n * {255, 0}.\n *\n *

    Size of {@code src} should always match the flat size of this {@link TensorBuffer}, for both\n * fixed-size and dynamic {@link TensorBuffer}.\n *\n * @param src The source array to be loaded.\n */\n public void loadArray(@NonNull int[] src) {", "answers": [" loadArray(src, shape);"], "length": 1146, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "525fbe9c-dc98-4583-8c6f-ea8530f68bd7", "reasoning": "The method loadArray(int[] src) is a concrete overload that should delegate to the abstract loadArray(int[] src, int[] shape) using the buffer's current shape. The next line inside the method body will call the other overload with the existing shape field.", "reasoning_model_answer": "loadArray(src, shape);", "assistant_with_reasoning": "\nThe method loadArray(int[] src) is a concrete overload that should delegate to the abstract loadArray(int[] src, int[] shape) using the buffer's current shape. The next line inside the method body will call the other overload with the existing shape field.\n\nloadArray(src, shape);", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 2.491, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 8276, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "loadArray(src, shape);", "score": 0.92, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "#!/usr/bin/python\n# -*- coding: utf-8 -*-\n#/******************************************************************************\n# * $Id$\n# *\n# * Project: GDAL\n# * Purpose: GDAL API_PROXY server written in Python\n# * Author: Even Rouault, \n# *\n# ******************************************************************************\n# * Copyright (c) 2013, Even Rouault \n# *\n# * Permission is hereby granted, free of charge, to any person obtaining a\n# * copy of this software and associated documentation files (the \"Software\"),\n# * to deal in the Software without restriction, including without limitation\n# * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n# * and/or sell copies of the Software, and to permit persons to whom the\n# * Software is furnished to do so, subject to the following conditions:\n# *\n# * The above copyright notice and this permission notice shall be included\n# * in all copies or substantial portions of the Software.\n# *\n# * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n# * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n# * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n# * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n# * DEALINGS IN THE SOFTWARE.\n# ****************************************************************************/\n\n# WARNING: only Python 2 compatible for now\n\nimport sys\nimport os\nfrom struct import *\n\nfrom osgeo import gdalconst, gdal\n\nclass GDALPythonServerRasterBand:\n\n def __init__(self, gdal_band):\n self.gdal_band = gdal_band\n self.XSize = gdal_band.XSize\n self.YSize = gdal_band.YSize\n self.Band = gdal_band.GetBand()\n (self.BlockXSize, self.BlockYSize) = gdal_band.GetBlockSize()\n self.DataType = gdal_band.DataType\n self.mask_band = None\n self.ovr_bands = None\n\n def FlushCache(self):\n return self.gdal_band.FlushCache()\n\n def GetColorInterpretation(self):\n return self.gdal_band.GetColorInterpretation()\n\n def GetNoDataValue(self):\n return self.gdal_band.GetNoDataValue()\n\n def GetMinimum(self):\n return self.gdal_band.GetMinimum()\n\n def GetMaximum(self):\n return self.gdal_band.GetMaximum()\n\n def GetOffset(self):\n return self.gdal_band.GetOffset()\n\n def GetScale(self):\n return self.gdal_band.GetScale()\n\n def HasArbitraryOverviews(self):\n return self.gdal_band.HasArbitraryOverviews()\n\n def GetOverviewCount(self):\n return self.gdal_band.GetOverviewCount()\n\n def GetMaskFlags(self):\n return self.gdal_band.GetMaskFlags()\n\n def GetMaskBand(self):\n if self.mask_band is None:\n gdal_mask_band = self.gdal_band.GetMaskBand()\n if gdal_mask_band is not None:\n self.mask_band = GDALPythonServerRasterBand(gdal_mask_band)\n return self.mask_band\n\n def GetOverview(self, iovr):\n if self.ovr_bands is None:\n self.ovr_bands = [None for i in range(self.GetOverviewCount())]\n if self.ovr_bands[iovr] is None:\n gdal_ovr_band = self.gdal_band.GetOverview(iovr)\n if gdal_ovr_band is not None:\n self.ovr_bands[iovr] = GDALPythonServerRasterBand(gdal_ovr_band)\n return self.ovr_bands[iovr]\n\n def GetMetadata(self, domain):\n return self.gdal_band.GetMetadata(domain)\n\n def GetMetadataItem(self, key, domain):\n return self.gdal_band.GetMetadataItem(key, domain)\n\n def IReadBlock(self, nXBlockOff, nYBlockOff):\n return self.gdal_band.ReadBlock(nXBlockOff, nYBlockOff)\n\n def IRasterIO_Read(self, nXOff, nYOff, nXSize, nYSize, nBufXSize, nBufYSize, nBufType):\n return self.gdal_band.ReadRaster(nXOff, nYOff, nXSize, nYSize, buf_xsize = nBufXSize, buf_ysize = nBufYSize, buf_type = nBufType)\n\n def GetUnitType(self):\n return self.gdal_band.GetUnitType()\n\n def GetStatistics(self, approx_ok, force):\n return self.gdal_band.GetStatistics(approx_ok, force)\n\n def ComputeRasterMinMax(self, approx_ok):\n return self.gdal_band.ComputeRasterMinMax(approx_ok)\n\n def GetColorTable(self):\n return self.gdal_band.GetColorTable()\n\n def GetHistogram(self, dfMin, dfMax, nBuckets, bIncludeOutOfRange, bApproxOK):\n return self.gdal_band.GetHistogram(dfMin, dfMax, nBuckets, include_out_of_range = bIncludeOutOfRange, approx_ok = bApproxOK)\n\nclass GDALPythonServerDataset:\n\n def __init__(self, filename, access = gdal.GA_ReadOnly):\n self.gdal_ds = gdal.Open(filename, access)\n if self.gdal_ds is None:\n raise Exception(gdal.GetLastErrorMsg())\n self.RasterXSize = self.gdal_ds.RasterXSize\n self.RasterYSize = self.gdal_ds.RasterYSize\n self.RasterCount = self.gdal_ds.RasterCount\n self.bands = []\n for i in range(self.RasterCount):\n gdal_band = self.gdal_ds.GetRasterBand(i+1)\n self.bands.append(GDALPythonServerRasterBand(gdal_band))\n\n def __del__(self):\n self.gdal_ds = None\n\n def GetDriver(self):\n return self.gdal_ds.GetDriver()\n\n def GetRasterBand(self, i):\n return self.bands[i-1]\n\n def GetDescription(self):\n return self.gdal_ds.GetDescription()\n\n def GetGeoTransform(self):\n return self.gdal_ds.GetGeoTransform()\n\n def GetProjectionRef(self):\n return self.gdal_ds.GetProjectionRef()\n\n def GetGCPCount(self):\n return self.gdal_ds.GetGCPCount()\n\n def GetFileList(self):\n return self.gdal_ds.GetFileList()\n\n def GetMetadata(self, domain):\n return self.gdal_ds.GetMetadata(domain)\n\n def GetMetadataItem(self, key, domain):\n return self.gdal_ds.GetMetadataItem(key, domain)\n\n def FlushCache(self):\n self.gdal_ds.FlushCache()\n return\n\n def IRasterIO_Read(self, nXOff, nYOff, nXSize, nYSize, nBufXSize, nBufYSize, \\\n nBufType, panBandMap, nPixelSpace, nLineSpace, nBandSpace):\n return self.gdal_ds.ReadRaster(nXOff, nYOff, nXSize, nYSize, \\\n buf_xsize = nBufXSize, buf_ysize = nBufYSize, \\\n buf_type = nBufType, band_list = panBandMap, \\\n buf_pixel_space = nPixelSpace, buf_line_space = nLineSpace, buf_band_space = nBandSpace)\n\nINSTR_GetGDALVersion = 1\nINSTR_EXIT = 2\nINSTR_EXIT_FAIL = 3\nINSTR_SetConfigOption = 4\n#INSTR_Progress = 5\nINSTR_Reset = 6\nINSTR_Open = 7\nINSTR_Identify = 8\nINSTR_Create = 9\nINSTR_CreateCopy = 10\nINSTR_QuietDelete = 11\n#INSTR_AddBand = 12\nINSTR_GetGeoTransform = 13\n#INSTR_SetGeoTransform = 14\nINSTR_GetProjectionRef = 15\n#INSTR_SetProjection = 16\nINSTR_GetGCPCount = 17\n#INSTR_GetGCPProjection = 18\n#INSTR_GetGCPs = 19\n#INSTR_SetGCPs = 20\nINSTR_GetFileList = 21\nINSTR_FlushCache = 22\n#INSTR_SetDescription = 23\nINSTR_GetMetadata = 24\nINSTR_GetMetadataItem = 25\n#INSTR_SetMetadata = 26\n#INSTR_SetMetadataItem = 27\nINSTR_IRasterIO_Read = 28\n#INSTR_IRasterIO_Write = 29\n#INSTR_IBuildOverviews = 30\n#INSTR_AdviseRead = 31\n#INSTR_CreateMaskBand = 32\nINSTR_Band_First = 33\nINSTR_Band_FlushCache = 34\nINSTR_Band_GetCategoryNames = 35\n#INSTR_Band_SetCategoryNames = 36\n#INSTR_Band_SetDescription = 37\nINSTR_Band_GetMetadata = 38\nINSTR_Band_GetMetadataItem = 39\nINSTR_Band_SetMetadata = 40\nINSTR_Band_SetMetadataItem = 41\nINSTR_Band_GetColorInterpretation = 42\n#INSTR_Band_SetColorInterpretation = 43\nINSTR_Band_GetNoDataValue = 44\nINSTR_Band_GetMinimum = 45\nINSTR_Band_GetMaximum = 46\nINSTR_Band_GetOffset = 47\nINSTR_Band_GetScale = 48\n#INSTR_Band_SetNoDataValue = 49\n#INSTR_Band_SetOffset = 50\n#INSTR_Band_SetScale = 51\nINSTR_Band_IReadBlock = 52\n#INSTR_Band_IWriteBlock = 53\nINSTR_Band_IRasterIO_Read = 54\n#INSTR_Band_IRasterIO_Write = 55\nINSTR_Band_GetStatistics = 56\n#INSTR_Band_ComputeStatistics = 57\n#INSTR_Band_SetStatistics = 58\nINSTR_Band_ComputeRasterMinMax = 59\nINSTR_Band_GetHistogram = 60\nINSTR_Band_GetDefaultHistogram = 61\n#INSTR_Band_SetDefaultHistogram = 62\nINSTR_Band_HasArbitraryOverviews = 63\nINSTR_Band_GetOverviewCount = 64\nINSTR_Band_GetOverview = 65\nINSTR_Band_GetMaskBand = 66\nINSTR_Band_GetMaskFlags = 67\n#INSTR_Band_CreateMaskBand = 68\n#INSTR_Band_Fill = 69\nINSTR_Band_GetColorTable = 70\n#INSTR_Band_SetColorTable = 71\nINSTR_Band_GetUnitType = 72\n#INSTR_Band_SetUnitType = 73\n#INSTR_Band_BuildOverviews = 74\nINSTR_Band_GetDefaultRAT = 75\n#INSTR_Band_SetDefaultRAT = 76\n#INSTR_Band_AdviseRead = 77\nINSTR_Band_End = 78\n#INSTR_END = 79\n\ncaps_list = [\n INSTR_GetGDALVersion,\n INSTR_EXIT,\n INSTR_EXIT_FAIL,\n INSTR_SetConfigOption,\n #INSTR_Progress,\n INSTR_Reset,\n INSTR_Open,\n INSTR_Identify,\n INSTR_Create,\n INSTR_CreateCopy,\n INSTR_QuietDelete,\n #INSTR_AddBand,\n INSTR_GetGeoTransform,\n #INSTR_SetGeoTransform,\n INSTR_GetProjectionRef,\n #INSTR_SetProjection,\n INSTR_GetGCPCount,\n #INSTR_GetGCPProjection,\n #INSTR_GetGCPs,\n #INSTR_SetGCPs,\n INSTR_GetFileList,\n INSTR_FlushCache,\n #INSTR_SetDescription,\n INSTR_GetMetadata,\n INSTR_GetMetadataItem,\n #INSTR_SetMetadata,\n #INSTR_SetMetadataItem,\n INSTR_IRasterIO_Read,\n #INSTR_IRasterIO_Write,\n #INSTR_IBuildOverviews,\n #INSTR_AdviseRead,\n #INSTR_CreateMaskBand,\n #INSTR_Band_First,\n INSTR_Band_FlushCache,\n INSTR_Band_GetCategoryNames,\n #INSTR_Band_SetCategoryNames,\n #INSTR_Band_SetDescription,\n INSTR_Band_GetMetadata,\n INSTR_Band_GetMetadataItem,\n INSTR_Band_SetMetadata,\n INSTR_Band_SetMetadataItem,\n INSTR_Band_GetColorInterpretation,\n #INSTR_Band_SetColorInterpretation,\n INSTR_Band_GetNoDataValue,\n INSTR_Band_GetMinimum,\n INSTR_Band_GetMaximum,\n INSTR_Band_GetOffset,\n INSTR_Band_GetScale,\n #INSTR_Band_SetNoDataValue,\n #INSTR_Band_SetOffset,\n #INSTR_Band_SetScale,\n INSTR_Band_IReadBlock,\n #INSTR_Band_IWriteBlock,\n INSTR_Band_IRasterIO_Read,\n #INSTR_Band_IRasterIO_Write,\n INSTR_Band_GetStatistics,\n #INSTR_Band_ComputeStatistics,\n #INSTR_Band_SetStatistics,\n INSTR_Band_ComputeRasterMinMax,\n INSTR_Band_GetHistogram,\n #INSTR_Band_GetDefaultHistogram,\n #INSTR_Band_SetDefaultHistogram,\n INSTR_Band_HasArbitraryOverviews,\n INSTR_Band_GetOverviewCount,\n INSTR_Band_GetOverview,\n INSTR_Band_GetMaskBand,\n INSTR_Band_GetMaskFlags,\n #INSTR_Band_CreateMaskBand,\n #INSTR_Band_Fill,\n INSTR_Band_GetColorTable,\n #INSTR_Band_SetColorTable,\n INSTR_Band_GetUnitType,\n #INSTR_Band_SetUnitType,\n #INSTR_Band_BuildOverviews,\n #INSTR_Band_GetDefaultRAT,\n #INSTR_Band_SetDefaultRAT,\n #INSTR_Band_AdviseRead ,\n #INSTR_Band_End,\n #INSTR_END = 79\n]\n\nCE_None = 0\nCE_Failure = 3\n\nVERBOSE = 0\n\ndef read_int():\n if sys.version_info >= (3,0,0):\n return unpack('i', sys.stdin.read(4).encode('latin1'))[0]\n else:\n return unpack('i', sys.stdin.read(4))[0]\n\ndef read_double():\n if sys.version_info >= (3,0,0):\n return unpack('d', sys.stdin.read(8).encode('latin1'))[0]\n else:\n return unpack('d', sys.stdin.read(8))[0]\n\ndef read_str():\n length = read_int()\n if length <= 0:\n return None\n str = sys.stdin.read(length)\n if len(str) > 0 and str[len(str)-1] == '\\0':\n str = str[0:len(str)-1]\n return str\n\ndef read_strlist():", "answers": [" count = read_int()"], "length": 998, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "28f51b27-5c59-443a-8c9a-30812d17cf46", "reasoning": "The function read_strlist() should read a list of strings from stdin. Following the pattern of the other helper functions, it will first read an integer count. Therefore the next line after the function definition is the statement that reads this count.", "reasoning_model_answer": "n = read_int()", "assistant_with_reasoning": "\nThe function read_strlist() should read a list of strings from stdin. Following the pattern of the other helper functions, it will first read an integer count. Therefore the next line after the function definition is the statement that reads this count.\n\nn = read_int()", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 2.287, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 11689, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "n = read_int()", "score": 0.78, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "// \n// Copyright (c) Microsoft and contributors. All rights reserved.\n// \n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n// http://www.apache.org/licenses/LICENSE-2.0\n// \n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// \n// See the License for the specific language governing permissions and\n// limitations under the License.\n// \n\n// Warning: This code was generated by a tool.\n// \n// Changes to this file may cause incorrect behavior and will be lost if the\n// code is regenerated.\n\nusing System;\nusing System.Linq;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Microsoft.Azure;\nusing Microsoft.Azure.Management.RecoveryServices.Backup;\nusing Microsoft.Azure.Management.RecoveryServices.Backup.Models;\n\nnamespace Microsoft.Azure.Management.RecoveryServices.Backup\n{\n public static partial class ContainerOperationsExtensions\n {\n ///

    \n /// The Begin Refresh Operation triggers an operation in the service\n /// which would discover all the containers in the subscription that\n /// are ready to be protected by your Recovery Services Vault. This is\n /// an asynchronous operation. To determine whether the backend\n /// service has finished processing the request, call Get Refresh\n /// Operation Result APIs.\n /// \n /// \n /// Reference to the\n /// Microsoft.Azure.Management.RecoveryServices.Backup.IContainerOperations.\n /// \n /// \n /// Required. Resource group name of your recovery services vault.\n /// \n /// \n /// Required. Nme of your recovery services vault.\n /// \n /// \n /// Required. Request header parameters.\n /// \n /// \n /// Optional. Fabric name for the protection containers.\n /// \n /// \n /// Base recovery job response for all the asynchronous operations.\n /// \n public static BaseRecoveryServicesJobResponse BeginRefresh(this IContainerOperations operations, string resourceGroupName, string resourceName, CustomRequestHeaders customRequestHeaders, string fabricName)\n {\n return Task.Factory.StartNew((object s) => \n {\n return ((IContainerOperations)s).BeginRefreshAsync(resourceGroupName, resourceName, customRequestHeaders, fabricName);\n }\n , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();\n }\n \n /// \n /// The Begin Refresh Operation triggers an operation in the service\n /// which would discover all the containers in the subscription that\n /// are ready to be protected by your Recovery Services Vault. This is\n /// an asynchronous operation. To determine whether the backend\n /// service has finished processing the request, call Get Refresh\n /// Operation Result APIs.\n /// \n /// \n /// Reference to the\n /// Microsoft.Azure.Management.RecoveryServices.Backup.IContainerOperations.\n /// \n /// \n /// Required. Resource group name of your recovery services vault.\n /// \n /// \n /// Required. Nme of your recovery services vault.\n /// \n /// \n /// Required. Request header parameters.\n /// \n /// \n /// Optional. Fabric name for the protection containers.\n /// \n /// \n /// Base recovery job response for all the asynchronous operations.\n /// \n public static Task BeginRefreshAsync(this IContainerOperations operations, string resourceGroupName, string resourceName, CustomRequestHeaders customRequestHeaders, string fabricName)\n {\n return operations.BeginRefreshAsync(resourceGroupName, resourceName, customRequestHeaders, fabricName, CancellationToken.None);\n }\n \n /// \n /// Fetches the result of any operation on the container given the ID\n /// of operation.\n /// \n /// \n /// Reference to the\n /// Microsoft.Azure.Management.RecoveryServices.Backup.IContainerOperations.\n /// \n /// \n /// Required. Resource group name of your recovery services vault.\n /// \n /// \n /// Required. Name of your recovery services vault.\n /// \n /// \n /// Optional. Fabric name of the protected item.\n /// \n /// \n /// Required. Name of the container where the protected item belongs to.\n /// \n /// \n /// Required. ID of the container operation whose result has to be\n /// fetched.\n /// \n /// \n /// Optional. Request header parameters.\n /// \n /// \n /// Protection container response.\n /// \n public static ProtectionContainerResponse GetContainerOperationResult(this IContainerOperations operations, string resourceGroupName, string resourceName, string fabricName, string containerName, string operationId, CustomRequestHeaders customRequestHeaders)\n {\n return Task.Factory.StartNew((object s) => \n {\n return ((IContainerOperations)s).GetContainerOperationResultAsync(resourceGroupName, resourceName, fabricName, containerName, operationId, customRequestHeaders);\n }\n , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();\n }\n \n /// \n /// Fetches the result of any operation on the container given the ID\n /// of operation.\n /// \n /// \n /// Reference to the\n /// Microsoft.Azure.Management.RecoveryServices.Backup.IContainerOperations.\n /// \n /// \n /// Required. Resource group name of your recovery services vault.\n /// \n /// \n /// Required. Name of your recovery services vault.\n /// \n /// \n /// Optional. Fabric name of the protected item.\n /// \n /// \n /// Required. Name of the container where the protected item belongs to.\n /// \n /// \n /// Required. ID of the container operation whose result has to be\n /// fetched.\n /// \n /// \n /// Optional. Request header parameters.\n /// \n /// \n /// Protection container response.\n /// \n public static Task GetContainerOperationResultAsync(this IContainerOperations operations, string resourceGroupName, string resourceName, string fabricName, string containerName, string operationId, CustomRequestHeaders customRequestHeaders)\n {\n return operations.GetContainerOperationResultAsync(resourceGroupName, resourceName, fabricName, containerName, operationId, customRequestHeaders, CancellationToken.None);\n }\n \n /// \n /// Fetches the result of any operation on the container given the URL\n /// for tracking the operation as returned by APIs such as Unregister\n /// etc.\n /// \n /// \n /// Reference to the\n /// Microsoft.Azure.Management.RecoveryServices.Backup.IContainerOperations.\n /// \n /// \n /// Required. Location value returned by operation.\n /// \n /// \n /// Optional. Request header parameters.\n /// \n /// \n /// Protection container response.\n /// \n public static ProtectionContainerResponse GetContainerOperationResultByURL(this IContainerOperations operations, string operationResultLink, CustomRequestHeaders customRequestHeaders)\n {", "answers": [" return Task.Factory.StartNew((object s) => "], "length": 889, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "3bcec7db-a74f-43e4-adde-b63d4a878e0f", "reasoning": "The method GetContainerOperationResultByURL is the synchronous wrapper for an async call, following the same pattern as the earlier sync methods. After the opening brace, the next line should start the Task.Factory.StartNew call that invokes the async version. Therefore the next line is the return statement beginning with Task.Factory.StartNew.", "reasoning_model_answer": "return Task.Factory.StartNew((object s) =>", "assistant_with_reasoning": "\nThe method GetContainerOperationResultByURL is the synchronous wrapper for an async call, following the same pattern as the earlier sync methods. After the opening brace, the next line should start the Task.Factory.StartNew call that invokes the async version. Therefore the next line is the return statement beginning with Task.Factory.StartNew.\n\nreturn Task.Factory.StartNew((object s) =>", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.509, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 9267, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "return Task.Factory.StartNew((object s) =>", "score": 0.87, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "# Copyright 2018 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Part of the Keras training engine related to Python generators of array data.\n\"\"\"\n# pylint: disable=protected-access\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport functools\nimport math\n\nimport numpy as np\n\nfrom tensorflow.python.data.ops import dataset_ops\nfrom tensorflow.python.data.ops import iterator_ops\nfrom tensorflow.python.eager import context\nfrom tensorflow.python.framework import errors\nfrom tensorflow.python.keras import backend\nfrom tensorflow.python.keras import callbacks as cbks\nfrom tensorflow.python.keras.engine import training_utils\nfrom tensorflow.python.keras.utils import data_utils\nfrom tensorflow.python.keras.utils import generic_utils\nfrom tensorflow.python.keras.utils.mode_keys import ModeKeys\nfrom tensorflow.python.platform import tf_logging as logging\nfrom tensorflow.python.util import nest\n\n\ndef model_iteration(model,\n data,\n steps_per_epoch=None,\n epochs=1,\n verbose=1,\n callbacks=None,\n validation_data=None,\n validation_steps=None,\n validation_freq=1,\n class_weight=None,\n max_queue_size=10,\n workers=1,\n use_multiprocessing=False,\n shuffle=False,\n initial_epoch=0,\n mode=ModeKeys.TRAIN,\n batch_size=None,\n steps_name='steps',\n **kwargs):\n \"\"\"Loop function for arrays of data with modes TRAIN/TEST/PREDICT.\n\n Arguments:\n model: Keras Model instance.\n data: Either a tuple of NumPy/Tensor inputs (i.e. `(x,)` or `(x, y)` or\n `(x, y, sample_weights)`) or a generator or\n `keras.utils.data_utils.Sequence` object or Eager Iterator or Dataset.\n steps_per_epoch: Total number of steps (batches of samples) before\n declaring one epoch finished and starting the next epoch. Ignored with\n the default value of `None`.\n epochs: Number of times to iterate over the data.\n verbose: 0, 1, or 2. Verbosity mode.\n 0 = silent, 1 = progress bar, 2 = one line per epoch.\n Note that the progress bar is not particularly useful when\n logged to a file, so verbose=2 is recommended when not running\n interactively (eg, in a production environment).\n callbacks: List of callbacks to be called during training.\n validation_data: Either a tuple of NumPy/Tensor inputs (i.e. `(x,)` or\n `(x, y)` or `(x, y, sample_weights)`) or a generator or\n `keras.utils.data_utils.Sequence` object or Eager Iterator or Dataset.\n validation_steps: Total number of steps (batches of samples) before\n declaring validation finished.\n validation_freq: Only relevant if validation data is provided. Integer or\n `collections.Container` instance (e.g. list, tuple, etc.). If an\n integer, specifies how many training epochs to run before a new\n validation run is performed, e.g. `validation_freq=2` runs\n validation every 2 epochs. If a Container, specifies the epochs on\n which to run validation, e.g. `validation_freq=[1, 2, 10]` runs\n validation at the end of the 1st, 2nd, and 10th epochs.\n class_weight: Dictionary mapping class indices to a weight for the class.\n max_queue_size: Integer. Maximum size for the generator queue. If\n unspecified, `max_queue_size` will default to 10.\n workers: Integer. Maximum number of processes to spin up when using\n process-based threading. If unspecified, `workers` will default to 1. If\n 0, will execute the generator on the main thread.\n use_multiprocessing: Boolean. If `True`, use process-based threading. If\n unspecified, `use_multiprocessing` will default to `False`. Note that\n because this implementation relies on multiprocessing, you should not\n pass non-picklable arguments to the generator as they can't be passed\n easily to children processes.\n shuffle: Boolean. Whether to shuffle the order of the batches at the\n beginning of each epoch. Only used with instances of `Sequence`\n (`keras.utils.Sequence`). Has no effect when `steps_per_epoch` is not\n `None`.\n initial_epoch: Epoch at which to start training (useful for resuming a\n previous training run).\n mode: One of ModeKeys.TRAIN/ModeKeys.TEST/ModeKeys.PREDICT.\n batch_size: Integer batch size or None if unknown. Will only be used if\n `data` is in NumPy/Tensor format.\n steps_name: The string name of the steps argument, either `steps`,\n `validation_steps`, or `steps_per_epoch`. Only used for error message\n formatting.\n **kwargs: Additional arguments for backwards compatibility. `steps` is\n accepted as an alias for `steps_per_epoch`.\n\n Returns:\n - In TRAIN mode: `History` object.\n - In TEST mode: Evaluation metrics.\n - In PREDICT mode: Outputs of the Model called on inputs.\n\n Raises:\n ValueError: in case of invalid arguments.\n \"\"\"\n if 'steps' in kwargs:\n steps_per_epoch = kwargs['steps']\n\n # Determine the number of steps per epoch and whether we should reset the\n # dataset at the end of each epoch.\n reset_dataset_after_each_epoch = False\n original_dataset = None\n is_dataset = isinstance(data, (dataset_ops.DatasetV2, dataset_ops.DatasetV1))\n if is_dataset:\n original_dataset = data\n if steps_per_epoch is None:\n reset_dataset_after_each_epoch = True\n steps_per_epoch = training_utils.infer_steps_for_dataset(\n data, steps_per_epoch, epochs=epochs, steps_name=steps_name)\n\n # Convert to a format that supports `next(generator)`.\n generator, steps_per_epoch = convert_to_generator_like(\n data,\n steps_per_epoch=steps_per_epoch,\n batch_size=batch_size,\n epochs=epochs - initial_epoch,\n shuffle=shuffle)\n\n do_validation = validation_data is not None\n is_sequence = isinstance(generator, data_utils.Sequence)\n _validate_arguments(is_sequence, is_dataset, use_multiprocessing, workers,\n steps_per_epoch, validation_data, validation_steps, mode,\n kwargs)\n\n batch_function = _make_execution_function(\n model, mode, class_weight=class_weight)\n\n # Create the queue for the generator.\n enqueuer = None\n if not is_dataset:\n generator, enqueuer = _make_enqueued_generator(\n generator,\n workers=workers,\n use_multiprocessing=use_multiprocessing,\n max_queue_size=max_queue_size,\n shuffle=shuffle)\n\n num_samples_or_steps, use_steps = _get_num_samples_or_steps(\n data, steps_per_epoch)\n\n count_mode = 'steps' if use_steps else 'samples'\n callbacks = cbks.configure_callbacks(\n callbacks,\n model,\n do_validation=do_validation,\n epochs=epochs,\n steps_per_epoch=steps_per_epoch,\n batch_size=batch_size,\n samples=num_samples_or_steps,\n verbose=0, # Handle ProgBar as part of Callbacks once hooks are ready.\n mode=mode)\n # TODO(omalleyt): Handle ProgBar as part of Callbacks once hooks are ready.\n progbar = training_utils.get_progbar(model, count_mode)\n progbar.params = callbacks.params\n progbar.params['verbose'] = verbose\n\n if mode == ModeKeys.PREDICT:\n aggregator = training_utils.OutputsAggregator(True, steps_per_epoch)\n else:\n aggregator = training_utils.MetricsAggregator(True, steps_per_epoch)\n\n should_set_learning_phase = context.executing_eagerly() and model.run_eagerly\n if should_set_learning_phase:\n learning_phase_scope = backend.eager_learning_phase_scope(\n 1 if mode == ModeKeys.TRAIN else 0)\n learning_phase_scope.__enter__()\n\n callbacks.model.stop_training = False\n callbacks._call_begin_hook(mode)\n progbar.on_train_begin()\n\n initial_epoch = model._maybe_load_initial_epoch_from_ckpt(initial_epoch, mode)\n\n for epoch in range(initial_epoch, epochs):\n if callbacks.model.stop_training:\n break\n\n # Setup work for each epoch.\n model.reset_metrics()\n epoch_logs = {}\n if mode == ModeKeys.TRAIN:\n callbacks.on_epoch_begin(epoch, epoch_logs)\n progbar.on_epoch_begin(epoch, epoch_logs)\n\n if steps_per_epoch is None:\n # Loop over dataset until `OutOfRangeError` is raised.\n target_steps = np.inf\n else:\n # Loop over dataset for the specified number of steps.\n target_steps = steps_per_epoch\n\n step = 0\n while step < target_steps:\n batch_data = _get_next_batch(generator, mode)\n if batch_data is None:\n if is_dataset:\n # The dataset passed by the user ran out of batches.\n # Now we know the cardinality of the dataset.\n # If steps_per_epoch was specified, then running out of data is\n # unexpected, so we stop training and inform the user.\n if steps_per_epoch:\n callbacks.model.stop_training = True\n logging.warning(\n 'Your dataset ran out of data; interrupting training. '\n 'Make sure that your dataset can generate at least '\n '`%s * epochs` batches (in this case, %d batches). '\n 'You may need to use the repeat() function when '\n 'building your dataset.'\n % (steps_name, steps_per_epoch * epochs))\n elif step > 0:\n steps_per_epoch = step\n aggregator.num_samples_or_steps = steps_per_epoch\n if mode == ModeKeys.TRAIN:\n progbar.params['steps'] = steps_per_epoch\n progbar.progbar.target = steps_per_epoch\n else:\n # We ran out of batches while the user passed an iterator (legacy).\n callbacks.model.stop_training = True\n logging.warning(\n 'Your dataset iterator ran out of data; '\n 'interrupting training. Make sure that your iterator '\n 'can generate at least `%s * epochs` '\n 'batches (in this case, %d batches). You may need to'\n 'use the repeat() function when building your '\n 'dataset.' % (steps_name, steps_per_epoch * epochs))\n break\n\n # `batch_size` used for validation data if validation\n # data is NumPy/EagerTensors.\n batch_size = int(nest.flatten(batch_data)[0].shape[0])\n\n # Callbacks batch begin.\n batch_logs = {'batch': step, 'size': batch_size}\n callbacks._call_batch_hook(mode, 'begin', step, batch_logs)\n progbar.on_batch_begin(step, batch_logs)\n\n is_deferred = not model._is_compiled\n batch_outs = batch_function(*batch_data)\n if not isinstance(batch_outs, list):\n batch_outs = [batch_outs]\n\n if step == 0:\n aggregator.create(batch_outs)\n\n if is_deferred:\n # Set callbacks params. We do this here when model is compiled only\n # in the first iteration of this loop (deferred build scenario).\n cbks.set_callback_parameters(\n callbacks,\n model,\n do_validation=do_validation,\n batch_size=batch_size,\n epochs=epochs,\n steps_per_epoch=steps_per_epoch,\n samples=num_samples_or_steps,\n verbose=verbose,\n mode=mode)\n\n progbar.params = callbacks.params\n progbar.params['verbose'] = verbose\n\n # Aggregate results.\n aggregator.aggregate(batch_outs)\n\n # Callbacks batch end.\n batch_logs = cbks.make_logs(model, batch_logs, batch_outs, mode)\n callbacks._call_batch_hook(mode, 'end', step, batch_logs)\n progbar.on_batch_end(step, batch_logs)\n step += 1\n\n if callbacks.model.stop_training:\n break\n\n aggregator.finalize()\n results = aggregator.results\n epoch_logs = cbks.make_logs(model, epoch_logs, results, mode)\n if len(results) == 1:\n results = results[0]\n\n # Run the test loop every epoch during training.\n if (do_validation and\n training_utils.should_run_validation(validation_freq, epoch) and\n not callbacks.model.stop_training):\n val_results = model_iteration(\n model,\n validation_data,\n steps_per_epoch=validation_steps,\n batch_size=batch_size,\n class_weight=class_weight,\n workers=workers,", "answers": [" use_multiprocessing=use_multiprocessing,"], "length": 1317, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "96eeb95a-baa1-4185-8fe1-3a3ba5b1ac76", "reasoning": "The code is inside the training loop of model_iteration. After completing a training epoch, it runs validation by recursively calling model_iteration with validation_data. The call already includes model, validation_data, steps_per_epoch, batch_size, class_weight, and workers, ending with a trailing comma, indicating more arguments are needed. The next argument in the function signature is use_multiprocessing, which should be passed the same flag used for training. Therefore the next line adds `use_multiprocessing=use_multiprocessing,` to the call.", "reasoning_model_answer": "use_multiprocessing=use_multiprocessing,", "assistant_with_reasoning": "\nThe code is inside the training loop of model_iteration. After completing a training epoch, it runs validation by recursively calling model_iteration with validation_data. The call already includes model, validation_data, steps_per_epoch, batch_size, class_weight, and workers, ending with a trailing comma, indicating more arguments are needed. The next argument in the function signature is use_multiprocessing, which should be passed the same flag used for training. Therefore the next line adds `use_multiprocessing=use_multiprocessing,` to the call.\n\nuse_multiprocessing=use_multiprocessing,", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 6.815, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 13194, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "use_multiprocessing=use_multiprocessing,", "score": 0.89, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "# -*- coding: utf-8 -*-\n\"\"\"\n werkzeug.serving\n ~~~~~~~~~~~~~~~~\n\n There are many ways to serve a WSGI application. While you're developing\n it you usually don't want a full blown webserver like Apache but a simple\n standalone one. From Python 2.5 onwards there is the `wsgiref`_ server in\n the standard library. If you're using older versions of Python you can\n download the package from the cheeseshop.\n\n However there are some caveats. Sourcecode won't reload itself when\n changed and each time you kill the server using ``^C`` you get an\n `KeyboardInterrupt` error. While the latter is easy to solve the first\n one can be a pain in the ass in some situations.\n\n The easiest way is creating a small ``start-myproject.py`` that runs the\n application::\n\n #!/usr/bin/env python\n # -*- coding: utf-8 -*-\n from myproject import make_app\n from werkzeug.serving import run_simple\n\n app = make_app(...)\n run_simple('localhost', 8080, app, use_reloader=True)\n\n You can also pass it a `extra_files` keyword argument with a list of\n additional files (like configuration files) you want to observe.\n\n For bigger applications you should consider using `werkzeug.script`\n instead of a simple start file.\n\n\n :copyright: (c) 2014 by the Werkzeug Team, see AUTHORS for more details.\n :license: BSD, see LICENSE for more details.\n\"\"\"\nfrom __future__ import with_statement\n\nimport os\nimport socket\nimport sys\nimport signal\n\nfrom ._compat import PY2\n\ntry:\n import ssl\nexcept ImportError:\n class _SslDummy(object):\n def __getattr__(self, name):\n raise RuntimeError('SSL support unavailable')\n ssl = _SslDummy()\n\n\ndef _get_openssl_crypto_module():\n try:\n from OpenSSL import crypto\n except ImportError:\n raise TypeError('Using ad-hoc certificates requires the pyOpenSSL '\n 'library.')\n else:\n return crypto\n\n\ntry:\n from SocketServer import ThreadingMixIn, ForkingMixIn\n from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler\nexcept ImportError:\n from socketserver import ThreadingMixIn, ForkingMixIn\n from http.server import HTTPServer, BaseHTTPRequestHandler\n\nimport werkzeug\nfrom werkzeug._internal import _log\nfrom werkzeug._compat import reraise, wsgi_encoding_dance\nfrom werkzeug.urls import url_parse, url_unquote\nfrom werkzeug.exceptions import InternalServerError\n\n\nLISTEN_QUEUE = 128\ncan_open_by_fd = hasattr(socket, 'fromfd')\n\n\nclass WSGIRequestHandler(BaseHTTPRequestHandler, object):\n\n \"\"\"A request handler that implements WSGI dispatching.\"\"\"\n\n @property\n def server_version(self):\n return 'Werkzeug/' + werkzeug.__version__\n\n def make_environ(self):\n request_url = url_parse(self.path)\n\n def shutdown_server():\n self.server.shutdown_signal = True\n\n url_scheme = self.server.ssl_context is None and 'http' or 'https'\n path_info = url_unquote(request_url.path)\n\n environ = {\n 'wsgi.version': (1, 0),\n 'wsgi.url_scheme': url_scheme,\n 'wsgi.input': self.rfile,\n 'wsgi.errors': sys.stderr,\n 'wsgi.multithread': self.server.multithread,\n 'wsgi.multiprocess': self.server.multiprocess,\n 'wsgi.run_once': False,\n 'werkzeug.server.shutdown': shutdown_server,\n 'SERVER_SOFTWARE': self.server_version,\n 'REQUEST_METHOD': self.command,\n 'SCRIPT_NAME': '',\n 'PATH_INFO': wsgi_encoding_dance(path_info),\n 'QUERY_STRING': wsgi_encoding_dance(request_url.query),\n 'CONTENT_TYPE': self.headers.get('Content-Type', ''),\n 'CONTENT_LENGTH': self.headers.get('Content-Length', ''),\n 'REMOTE_ADDR': self.client_address[0],\n 'REMOTE_PORT': self.client_address[1],\n 'SERVER_NAME': self.server.server_address[0],\n 'SERVER_PORT': str(self.server.server_address[1]),\n 'SERVER_PROTOCOL': self.request_version\n }\n\n for key, value in self.headers.items():\n key = 'HTTP_' + key.upper().replace('-', '_')\n if key not in ('HTTP_CONTENT_TYPE', 'HTTP_CONTENT_LENGTH'):\n environ[key] = value\n\n if request_url.netloc:\n environ['HTTP_HOST'] = request_url.netloc\n\n return environ\n\n def run_wsgi(self):\n if self.headers.get('Expect', '').lower().strip() == '100-continue':\n self.wfile.write(b'HTTP/1.1 100 Continue\\r\\n\\r\\n')\n\n self.environ = environ = self.make_environ()\n headers_set = []\n headers_sent = []\n\n def write(data):\n assert headers_set, 'write() before start_response'\n if not headers_sent:\n status, response_headers = headers_sent[:] = headers_set\n try:\n code, msg = status.split(None, 1)\n except ValueError:\n code, msg = status, \"\"\n self.send_response(int(code), msg)\n header_keys = set()\n for key, value in response_headers:\n self.send_header(key, value)\n key = key.lower()\n header_keys.add(key)\n if 'content-length' not in header_keys:\n self.close_connection = True\n self.send_header('Connection', 'close')\n if 'server' not in header_keys:\n self.send_header('Server', self.version_string())\n if 'date' not in header_keys:\n self.send_header('Date', self.date_time_string())\n self.end_headers()\n\n assert isinstance(data, bytes), 'applications must write bytes'\n self.wfile.write(data)\n self.wfile.flush()\n\n def start_response(status, response_headers, exc_info=None):\n if exc_info:\n try:\n if headers_sent:\n reraise(*exc_info)\n finally:\n exc_info = None\n elif headers_set:\n raise AssertionError('Headers already set')\n headers_set[:] = [status, response_headers]\n return write\n\n def execute(app):\n application_iter = app(environ, start_response)\n try:\n for data in application_iter:\n write(data)\n if not headers_sent:\n write(b'')\n finally:\n if hasattr(application_iter, 'close'):\n application_iter.close()\n application_iter = None\n\n try:\n execute(self.server.app)\n except (socket.error, socket.timeout) as e:\n self.connection_dropped(e, environ)\n except Exception:\n if self.server.passthrough_errors:\n raise\n from werkzeug.debug.tbtools import get_current_traceback\n traceback = get_current_traceback(ignore_system_exceptions=True)\n try:\n # if we haven't yet sent the headers but they are set\n # we roll back to be able to set them again.\n if not headers_sent:\n del headers_set[:]\n execute(InternalServerError())\n except Exception:\n pass\n self.server.log('error', 'Error on request:\\n%s',\n traceback.plaintext)\n\n def handle(self):\n \"\"\"Handles a request ignoring dropped connections.\"\"\"\n rv = None\n try:\n rv = BaseHTTPRequestHandler.handle(self)\n except (socket.error, socket.timeout) as e:\n self.connection_dropped(e)\n except Exception:\n if self.server.ssl_context is None or not is_ssl_error():\n raise\n if self.server.shutdown_signal:\n self.initiate_shutdown()\n return rv\n\n def initiate_shutdown(self):\n \"\"\"A horrible, horrible way to kill the server for Python 2.6 and\n later. It's the best we can do.\n \"\"\"\n # Windows does not provide SIGKILL, go with SIGTERM then.\n sig = getattr(signal, 'SIGKILL', signal.SIGTERM)\n # reloader active\n if os.environ.get('WERKZEUG_RUN_MAIN') == 'true':\n os.kill(os.getpid(), sig)\n # python 2.7\n self.server._BaseServer__shutdown_request = True\n # python 2.6\n self.server._BaseServer__serving = False\n\n def connection_dropped(self, error, environ=None):\n \"\"\"Called if the connection was closed by the client. By default\n nothing happens.\n \"\"\"\n\n def handle_one_request(self):\n \"\"\"Handle a single HTTP request.\"\"\"\n self.raw_requestline = self.rfile.readline()\n if not self.raw_requestline:\n self.close_connection = 1\n elif self.parse_request():\n return self.run_wsgi()\n\n def send_response(self, code, message=None):\n \"\"\"Send the response header and log the response code.\"\"\"\n self.log_request(code)\n if message is None:\n message = code in self.responses and self.responses[code][0] or ''\n if self.request_version != 'HTTP/0.9':\n hdr = \"%s %d %s\\r\\n\" % (self.protocol_version, code, message)\n self.wfile.write(hdr.encode('ascii'))\n\n def version_string(self):\n return BaseHTTPRequestHandler.version_string(self).strip()\n\n def address_string(self):\n return self.environ['REMOTE_ADDR']\n\n def log_request(self, code='-', size='-'):\n self.log('info', '\"%s\" %s %s', self.requestline, code, size)\n\n def log_error(self, *args):\n self.log('error', *args)\n\n def log_message(self, format, *args):\n self.log('info', format, *args)\n\n def log(self, type, message, *args):\n _log(type, '%s - - [%s] %s\\n' % (self.address_string(),\n self.log_date_time_string(),\n message % args))\n\n\n#: backwards compatible name if someone is subclassing it\nBaseRequestHandler = WSGIRequestHandler\n\n\ndef generate_adhoc_ssl_pair(cn=None):\n from random import random\n crypto = _get_openssl_crypto_module()\n\n # pretty damn sure that this is not actually accepted by anyone\n if cn is None:\n cn = '*'\n\n cert = crypto.X509()\n cert.set_serial_number(int(random() * sys.maxsize))\n cert.gmtime_adj_notBefore(0)\n cert.gmtime_adj_notAfter(60 * 60 * 24 * 365)\n\n subject = cert.get_subject()\n subject.CN = cn\n subject.O = 'Dummy Certificate'\n\n issuer = cert.get_issuer()\n issuer.CN = 'Untrusted Authority'\n issuer.O = 'Self-Signed'\n\n pkey = crypto.PKey()\n pkey.generate_key(crypto.TYPE_RSA, 1024)\n cert.set_pubkey(pkey)\n cert.sign(pkey, 'md5')\n\n return cert, pkey\n\n\ndef make_ssl_devcert(base_path, host=None, cn=None):\n \"\"\"Creates an SSL key for development. This should be used instead of\n the ``'adhoc'`` key which generates a new cert on each server start.\n It accepts a path for where it should store the key and cert and\n either a host or CN. If a host is given it will use the CN\n ``*.host/CN=host``.\n\n For more information see :func:`run_simple`.\n\n .. versionadded:: 0.9\n\n :param base_path: the path to the certificate and key. The extension\n ``.crt`` is added for the certificate, ``.key`` is\n added for the key.\n :param host: the name of the host. This can be used as an alternative\n for the `cn`.\n :param cn: the `CN` to use.\n \"\"\"\n from OpenSSL import crypto\n if host is not None:\n cn = '*.%s/CN=%s' % (host, host)\n cert, pkey = generate_adhoc_ssl_pair(cn=cn)\n\n cert_file = base_path + '.crt'\n pkey_file = base_path + '.key'\n\n with open(cert_file, 'wb') as f:\n f.write(crypto.dump_certificate(crypto.FILETYPE_PEM, cert))\n with open(pkey_file, 'wb') as f:\n f.write(crypto.dump_privatekey(crypto.FILETYPE_PEM, pkey))", "answers": [" return cert_file, pkey_file"], "length": 1092, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "6c8ae6bf-fc86-4855-b473-df3f916e93ac", "reasoning": "The function make_ssl_devcert creates a certificate and private key, writes them to files named .crt and .key. After writing, the typical behavior is to return the paths of the generated files so callers can use them. In Werkzeug's implementation, the function ends with 'return cert_file, pkey_file'. Therefore the next line should be that return statement.", "reasoning_model_answer": "return cert_file, pkey_file", "assistant_with_reasoning": "\nThe function make_ssl_devcert creates a certificate and private key, writes them to files named .crt and .key. After writing, the typical behavior is to return the paths of the generated files so callers can use them. In Werkzeug's implementation, the function ends with 'return cert_file, pkey_file'. Therefore the next line should be that return statement.\n\nreturn cert_file, pkey_file", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 2.796, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 12340, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "return cert_file, pkey_file", "score": 0.93, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/*\n * Copyright (c) 2005-2016 Vincent Vandenschrick. All rights reserved.\n *\n * This file is part of the Jspresso framework.\n *\n * Jspresso is free software: you can redistribute it and/or modify\n * it under the terms of the GNU Lesser General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Jspresso is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public License\n * along with Jspresso. If not, see .\n */\npackage org.jspresso.framework.view.swing;\n\nimport java.awt.BorderLayout;\nimport java.awt.CardLayout;\nimport java.awt.Color;\nimport java.awt.Component;\nimport java.awt.Container;\nimport java.awt.Dimension;\nimport java.awt.FlowLayout;\nimport java.awt.Font;\nimport java.awt.GridBagConstraints;\nimport java.awt.GridBagLayout;\nimport java.awt.GridLayout;\nimport java.awt.Insets;\nimport java.awt.Toolkit;\nimport java.awt.event.ActionEvent;\nimport java.awt.event.FocusAdapter;\nimport java.awt.event.FocusEvent;\nimport java.awt.event.FocusListener;\nimport java.awt.event.KeyAdapter;\nimport java.awt.event.KeyEvent;\nimport java.awt.event.MouseAdapter;\nimport java.awt.event.MouseEvent;\nimport java.awt.event.MouseListener;\nimport java.beans.PropertyChangeEvent;\nimport java.beans.PropertyChangeListener;\nimport java.text.DateFormat;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Locale;\nimport java.util.Map;\nimport java.util.Properties;\nimport java.util.Set;\nimport java.util.TimeZone;\n\nimport javax.swing.Action;\nimport javax.swing.BorderFactory;\nimport javax.swing.BoxLayout;\nimport javax.swing.DefaultListCellRenderer;\nimport javax.swing.Icon;\nimport javax.swing.ImageIcon;\nimport javax.swing.JButton;\nimport javax.swing.JCheckBox;\nimport javax.swing.JComboBox;\nimport javax.swing.JComponent;\nimport javax.swing.JLabel;\nimport javax.swing.JList;\nimport javax.swing.JMenuItem;\nimport javax.swing.JPanel;\nimport javax.swing.JPasswordField;\nimport javax.swing.JPopupMenu;\nimport javax.swing.JRadioButton;\nimport javax.swing.JScrollPane;\nimport javax.swing.JSplitPane;\nimport javax.swing.JTabbedPane;\nimport javax.swing.JTable;\nimport javax.swing.JTextArea;\nimport javax.swing.JTextField;\nimport javax.swing.JTextPane;\nimport javax.swing.JToolBar;\nimport javax.swing.JTree;\nimport javax.swing.KeyStroke;\nimport javax.swing.ListSelectionModel;\nimport javax.swing.ScrollPaneConstants;\nimport javax.swing.SwingConstants;\nimport javax.swing.SwingUtilities;\nimport javax.swing.ToolTipManager;\nimport javax.swing.border.Border;\nimport javax.swing.border.TitledBorder;\nimport javax.swing.event.ChangeEvent;\nimport javax.swing.event.ChangeListener;\nimport javax.swing.event.ListSelectionEvent;\nimport javax.swing.event.ListSelectionListener;\nimport javax.swing.event.TableColumnModelEvent;\nimport javax.swing.event.TableColumnModelListener;\nimport javax.swing.event.TreeModelEvent;\nimport javax.swing.event.TreeModelListener;\nimport javax.swing.table.DefaultTableCellRenderer;\nimport javax.swing.table.TableCellRenderer;\nimport javax.swing.table.TableColumn;\nimport javax.swing.table.TableColumnModel;\nimport javax.swing.table.TableModel;\nimport javax.swing.text.DateFormatter;\nimport javax.swing.text.DefaultFormatterFactory;\nimport javax.swing.text.JTextComponent;\nimport javax.swing.text.html.HTMLEditorKit;\nimport javax.swing.tree.DefaultTreeCellRenderer;\nimport javax.swing.tree.TreeModel;\nimport javax.swing.tree.TreePath;\nimport javax.swing.tree.TreeSelectionModel;\n\nimport chrriis.dj.swingsuite.JComboButton;\nimport chrriis.dj.swingsuite.JLink;\nimport chrriis.dj.swingsuite.JTriStateCheckBox;\nimport chrriis.dj.swingsuite.LinkListener;\nimport com.bbn.openmap.LayerHandler;\nimport com.bbn.openmap.MapBean;\nimport com.bbn.openmap.MapHandler;\nimport com.bbn.openmap.MouseDelegator;\nimport com.bbn.openmap.event.OMMouseMode;\nimport com.bbn.openmap.gui.BasicMapPanel;\nimport com.bbn.openmap.gui.EmbeddedNavPanel;\nimport com.bbn.openmap.gui.EmbeddedScaleDisplayPanel;\nimport com.bbn.openmap.gui.OverlayMapPanel;\nimport com.bbn.openmap.layer.imageTile.MapTileLayer;\nimport org.syntax.jedit.JEditTextArea;\nimport org.syntax.jedit.tokenmarker.TokenMarker;\n\nimport org.jspresso.framework.action.ActionContextConstants;\nimport org.jspresso.framework.action.IAction;\nimport org.jspresso.framework.action.IActionHandler;\nimport org.jspresso.framework.application.view.ControllerAwareViewFactory;\nimport org.jspresso.framework.binding.ICollectionConnector;\nimport org.jspresso.framework.binding.ICollectionConnectorProvider;\nimport org.jspresso.framework.binding.ICompositeValueConnector;\nimport org.jspresso.framework.binding.IRenderableCompositeValueConnector;\nimport org.jspresso.framework.binding.IValueConnector;\nimport org.jspresso.framework.binding.basic.BasicValueConnector;\nimport org.jspresso.framework.binding.model.ModelRefPropertyConnector;\nimport org.jspresso.framework.binding.swing.CollectionConnectorListModel;\nimport org.jspresso.framework.binding.swing.CollectionConnectorTableModel;\nimport org.jspresso.framework.binding.swing.ConnectorHierarchyTreeModel;\nimport org.jspresso.framework.binding.swing.IListSelectionModelBinder;\nimport org.jspresso.framework.binding.swing.ITreeSelectionModelBinder;\nimport org.jspresso.framework.binding.swing.JActionFieldConnector;\nimport org.jspresso.framework.binding.swing.JColorPickerConnector;\nimport org.jspresso.framework.binding.swing.JComboBoxConnector;\nimport org.jspresso.framework.binding.swing.JDateFieldConnector;\nimport org.jspresso.framework.binding.swing.JEditTextAreaConnector;\nimport org.jspresso.framework.binding.swing.JFormattedFieldConnector;\nimport org.jspresso.framework.binding.swing.JHTMLEditorConnector;\nimport org.jspresso.framework.binding.swing.JImageConnector;\nimport org.jspresso.framework.binding.swing.JLabelConnector;\nimport org.jspresso.framework.binding.swing.JMapViewConnector;\nimport org.jspresso.framework.binding.swing.JPasswordFieldConnector;\nimport org.jspresso.framework.binding.swing.JPercentFieldConnector;\nimport org.jspresso.framework.binding.swing.JRadioButtonConnector;\nimport org.jspresso.framework.binding.swing.JReferenceFieldConnector;\nimport org.jspresso.framework.binding.swing.JTextAreaConnector;\nimport org.jspresso.framework.binding.swing.JTextFieldConnector;\nimport org.jspresso.framework.binding.swing.JTextPaneConnector;\nimport org.jspresso.framework.binding.swing.JToggleButtonConnector;\nimport org.jspresso.framework.binding.swing.JTriStateCheckBoxConnector;\nimport org.jspresso.framework.gui.swing.components.JActionField;\nimport org.jspresso.framework.gui.swing.components.JColorPicker;\nimport org.jspresso.framework.gui.swing.components.JDateField;\nimport org.jspresso.framework.gui.swing.components.JHTMLEditor;\nimport org.jspresso.framework.gui.swing.components.JScrollablePanel;\nimport org.jspresso.framework.model.descriptor.IBinaryPropertyDescriptor;\nimport org.jspresso.framework.model.descriptor.IBooleanPropertyDescriptor;\nimport org.jspresso.framework.model.descriptor.ICollectionDescriptorProvider;\nimport org.jspresso.framework.model.descriptor.ICollectionPropertyDescriptor;\nimport org.jspresso.framework.model.descriptor.IColorPropertyDescriptor;\nimport org.jspresso.framework.model.descriptor.IComponentDescriptor;\nimport org.jspresso.framework.model.descriptor.IComponentDescriptorProvider;\nimport org.jspresso.framework.model.descriptor.IDatePropertyDescriptor;\nimport org.jspresso.framework.model.descriptor.IDecimalPropertyDescriptor;\nimport org.jspresso.framework.model.descriptor.IDurationPropertyDescriptor;\nimport org.jspresso.framework.model.descriptor.IEnumerationPropertyDescriptor;\nimport org.jspresso.framework.model.descriptor.IHtmlPropertyDescriptor;\nimport org.jspresso.framework.model.descriptor.IImageBinaryPropertyDescriptor;\nimport org.jspresso.framework.model.descriptor.IImageUrlPropertyDescriptor;\nimport org.jspresso.framework.model.descriptor.IIntegerPropertyDescriptor;\nimport org.jspresso.framework.model.descriptor.IModelDescriptor;\nimport org.jspresso.framework.model.descriptor.INumberPropertyDescriptor;\nimport org.jspresso.framework.model.descriptor.IPasswordPropertyDescriptor;\nimport org.jspresso.framework.model.descriptor.IPercentPropertyDescriptor;\nimport org.jspresso.framework.model.descriptor.IPropertyDescriptor;\nimport org.jspresso.framework.model.descriptor.IReferencePropertyDescriptor;\nimport org.jspresso.framework.model.descriptor.IRelationshipEndPropertyDescriptor;\nimport org.jspresso.framework.model.descriptor.ISourceCodePropertyDescriptor;\nimport org.jspresso.framework.model.descriptor.IStringPropertyDescriptor;\nimport org.jspresso.framework.model.descriptor.ITextPropertyDescriptor;\nimport org.jspresso.framework.model.descriptor.ITimePropertyDescriptor;\nimport org.jspresso.framework.util.event.IValueChangeListener;\nimport org.jspresso.framework.util.event.ValueChangeEvent;\nimport org.jspresso.framework.util.format.IFormatter;\nimport org.jspresso.framework.util.format.PasswordFormatter;\nimport org.jspresso.framework.util.gui.CellConstraints;\nimport org.jspresso.framework.util.gui.ColorHelper;\nimport org.jspresso.framework.util.gui.EHorizontalAlignment;\nimport org.jspresso.framework.util.gui.EHorizontalPosition;\nimport org.jspresso.framework.util.gui.ELabelPosition;\nimport org.jspresso.framework.util.gui.ERenderingOptions;\nimport org.jspresso.framework.util.gui.FontHelper;\nimport org.jspresso.framework.util.i18n.ITranslationProvider;\nimport org.jspresso.framework.util.image.IScalableImageAware;\nimport org.jspresso.framework.util.swing.SwingUtil;\nimport org.jspresso.framework.util.url.UrlHelper;\nimport org.jspresso.framework.view.BasicCompositeView;\nimport org.jspresso.framework.view.BasicIndexedView;\nimport org.jspresso.framework.view.BasicMapView;\nimport org.jspresso.framework.view.BasicView;\nimport org.jspresso.framework.view.IActionFactory;\nimport org.jspresso.framework.view.ICompositeView;\nimport org.jspresso.framework.view.IMapView;\nimport org.jspresso.framework.view.IView;\nimport org.jspresso.framework.view.ViewException;\nimport org.jspresso.framework.view.action.ActionList;\nimport org.jspresso.framework.view.action.ActionMap;\nimport org.jspresso.framework.view.action.IDisplayableAction;\nimport org.jspresso.framework.view.descriptor.IActionViewDescriptor;\nimport org.jspresso.framework.view.descriptor.IBorderViewDescriptor;\nimport org.jspresso.framework.view.descriptor.ICardViewDescriptor;\nimport org.jspresso.framework.view.descriptor.ICollectionViewDescriptor;\nimport org.jspresso.framework.view.descriptor.IComponentViewDescriptor;\nimport org.jspresso.framework.view.descriptor.IConstrainedGridViewDescriptor;\nimport org.jspresso.framework.view.descriptor.IEnumerationPropertyViewDescriptor;\nimport org.jspresso.framework.view.descriptor.IEvenGridViewDescriptor;\nimport org.jspresso.framework.view.descriptor.IImageViewDescriptor;\nimport org.jspresso.framework.view.descriptor.IListViewDescriptor;\nimport org.jspresso.framework.view.descriptor.IMapViewDescriptor;\nimport org.jspresso.framework.view.descriptor.IPropertyViewDescriptor;\nimport org.jspresso.framework.view.descriptor.IReferencePropertyViewDescriptor;\nimport org.jspresso.framework.view.descriptor.IRepeaterViewDescriptor;\nimport org.jspresso.framework.view.descriptor.IScrollableViewDescriptor;\nimport org.jspresso.framework.view.descriptor.ISplitViewDescriptor;\nimport org.jspresso.framework.view.descriptor.IStaticTextViewDescriptor;\nimport org.jspresso.framework.view.descriptor.IStringPropertyViewDescriptor;\nimport org.jspresso.framework.view.descriptor.ITabViewDescriptor;\nimport org.jspresso.framework.view.descriptor.ITableViewDescriptor;\nimport org.jspresso.framework.view.descriptor.ITreeViewDescriptor;\nimport org.jspresso.framework.view.descriptor.IViewDescriptor;\nimport org.jspresso.framework.view.descriptor.TreeDescriptorHelper;\n\n/**\n * Factory for swing views.\n *\n * @author Vincent Vandenschrick\n */\n@SuppressWarnings(\"UnusedParameters\")\npublic class DefaultSwingViewFactory extends ControllerAwareViewFactory {\n\n private static final Dimension TREE_PREFERRED_SIZE = new Dimension(128, 128);\n private IListSelectionModelBinder listSelectionModelBinder;\n private ITreeSelectionModelBinder treeSelectionModelBinder;\n\n /**\n * {@inheritDoc}\n */\n @Override\n protected JComponent applyComponentScrollability(JComponent viewComponent, IScrollableViewDescriptor viewDescriptor) {\n JScrollPane scrollPane = createJScrollPane();\n scrollPane.setBorder(BorderFactory.createEmptyBorder());\n scrollPane.setVerticalScrollBarPolicy(\n viewDescriptor.isVerticallyScrollable() ? ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED :\n ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER);\n scrollPane.setHorizontalScrollBarPolicy(\n viewDescriptor.isHorizontallyScrollable() ? ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED :\n ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);\n if (viewComponent instanceof JScrollablePanel) {\n ((JScrollablePanel) viewComponent).setScrollableTracksViewportHeight(!viewDescriptor.isVerticallyScrollable());\n ((JScrollablePanel) viewComponent).setScrollableTracksViewportWidth(!viewDescriptor.isHorizontallyScrollable());\n }\n scrollPane.setViewportView(viewComponent);\n return scrollPane;\n }\n\n /**\n * Sets the listSelectionModelBinder.\n *\n * @param listSelectionModelBinder\n * the listSelectionModelBinder to set.\n */\n public void setListSelectionModelBinder(IListSelectionModelBinder listSelectionModelBinder) {\n this.listSelectionModelBinder = listSelectionModelBinder;\n }\n\n /**\n * Sets the treeSelectionModelBinder.\n *\n * @param treeSelectionModelBinder\n * the treeSelectionModelBinder to set.\n */\n public void setTreeSelectionModelBinder(ITreeSelectionModelBinder treeSelectionModelBinder) {\n this.treeSelectionModelBinder = treeSelectionModelBinder;\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n protected void addCard(IMapView cardView, IView card, String cardName) {\n Container cardPanel = findFirstCardPanel(cardView.getPeer());\n if (cardPanel != null) {\n cardPanel.add(card.getPeer(), cardName);\n cardView.addToChildrenMap(cardName, card);\n }\n }\n\n /**\n * Finds the first card panel starting from a root component.\n *\n * @param root\n * the root component to start for searching.\n * @return the 1st found card panel or null if none.\n */\n protected JComponent findFirstCardPanel(Component root) {\n if (root instanceof JComponent && ((JComponent) root).getLayout() instanceof CardLayout) {\n return (JComponent) root;\n }\n if (root instanceof Container) {\n for (Component child : ((Container) root).getComponents()) {\n JComponent childCardPanel = findFirstCardPanel(child);\n if (childCardPanel != null) {\n return childCardPanel;\n }\n }\n }\n return null;\n }\n\n /**\n * Adjusts a component various sizes (e.g. min, max, preferred) based on a\n * formatter and a template value.\n *\n * @param component\n * the component to adjust the sizes for.\n * @param formatter\n * the formatter used if any.\n * @param templateValue\n * the template value used.\n * @param viewDescriptor\n * the underlying view descriptor.\n */\n protected void adjustSizes(IViewDescriptor viewDescriptor, JComponent component, IFormatter formatter,\n Object templateValue) {\n adjustSizes(viewDescriptor, component, formatter, templateValue, 32);\n }\n\n /**\n * Adjusts a component various sizes (e.g. min, max, preferred) based on a\n * formatter and a template value.\n *\n * @param component\n * the component to adjust the sizes for.\n * @param formatter\n * the formatter used if any.\n * @param templateValue\n * the template value used.\n * @param viewDescriptor\n * the underlying view descriptor.\n * @param extraWidth\n * the extra size to be added.\n */\n protected void adjustSizes(IViewDescriptor viewDescriptor, JComponent component, IFormatter formatter,\n Object templateValue, int extraWidth) {\n if (viewDescriptor.getFont() != null && FontHelper.isFontSpec(viewDescriptor.getFont())) {\n // must set font before computing size.\n component.setFont(createFont(viewDescriptor.getFont(), component.getFont()));\n }\n int preferredWidth = computePixelWidth(component, getFormatLength(formatter, templateValue)) + extraWidth;\n Dimension size = new Dimension(preferredWidth, component.getPreferredSize().height);\n component.setMinimumSize(size);\n component.setPreferredSize(size);\n component.setMaximumSize(size);\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n protected void applyPreferredSize(JComponent component, org.jspresso.framework.util.gui.Dimension preferredSize) {\n if (preferredSize != null) {\n int pW = preferredSize.getWidth();\n if (pW <= 0) {\n pW = component.getPreferredSize().width;\n }\n int pH = preferredSize.getHeight();\n if (pH <= 0) {\n pH = component.getPreferredSize().height;\n }\n component.setPreferredSize(new Dimension(pW, pH));\n }\n }\n\n private int computePixelWidth(JComponent component, int characterLength) {\n int charLength = getMaxCharacterLength() + 2;\n if (characterLength > 0 && characterLength < getMaxCharacterLength()) {\n charLength = characterLength + 2;\n }\n return component.getFont().getSize() * charLength / 2;\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n protected IView createActionView(IActionViewDescriptor viewDescriptor, IActionHandler actionHandler,\n Locale locale) {\n JPanel viewComponent = createJPanel();\n IValueConnector connector = getConnectorFactory().createValueConnector(ModelRefPropertyConnector.THIS_PROPERTY);\n connector.setExceptionHandler(actionHandler);\n IView view = constructView(viewComponent, viewDescriptor, connector);\n ActionList actionList = viewDescriptor.getActionList();\n if (viewDescriptor.getActionList() != null) {\n ERenderingOptions defaultRenderingOptions = ERenderingOptions.ICON;\n if (viewDescriptor.getRenderingOptions() != null) {\n defaultRenderingOptions = viewDescriptor.getRenderingOptions();\n }\n boolean defaultHideActionWhenDisabled = getDefaultHideActionWhenDisabled();\n if (viewDescriptor.getActionList().getHideActionWhenDisabled() != null) {\n defaultHideActionWhenDisabled = viewDescriptor.getActionList().getHideActionWhenDisabled();\n }\n List viewActionList = createViewActionList(viewDescriptor.getActionList(), defaultRenderingOptions,\n defaultHideActionWhenDisabled, view, actionHandler, locale);\n if (viewActionList != null) {\n FlowLayout layout = new FlowLayout();\n viewComponent.setLayout(layout);\n JToolBar toolBar = createJToolBar();\n for (JButton toolbarButton : viewActionList) {\n toolBar.add(toolbarButton);\n }", "answers": [" viewComponent.add(toolBar);"], "length": 1198, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "c34aa484-b60c-4240-8872-57ba3ad5771f", "reasoning": "The method is building a view for an action. After creating a JToolBar and adding each JButton to it inside the loop, the toolbar needs to be added to the panel that holds the view components. The next logical statement is to add the toolbar to the viewComponent JPanel.", "reasoning_model_answer": "viewComponent.add(toolBar);", "assistant_with_reasoning": "\nThe method is building a view for an action. After creating a JToolBar and adding each JButton to it inside the loop, the toolbar needs to be added to the panel that holds the view components. The next logical statement is to add the toolbar to the viewComponent JPanel.\n\nviewComponent.add(toolBar);", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.478, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 19683, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "viewComponent.add(toolBar);", "score": 0.87, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "# -*- coding: utf-8 -*-\n#\n# Copyright 2012-2015 Spotify AB\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\nfrom __future__ import print_function\n\nimport functools\nimport logging\nimport os\nimport shutil\nimport signal\nimport tempfile\nimport threading\nimport time\nfrom helpers import unittest\n\nimport luigi.notifications\nimport luigi.worker\nimport mock\nfrom helpers import with_config, skipOnTravis\nfrom luigi import ExternalTask, RemoteScheduler, Task\nfrom luigi.mock import MockTarget, MockFileSystem\nfrom luigi.scheduler import CentralPlannerScheduler\nfrom luigi.worker import Worker\nfrom luigi import six\n\nluigi.notifications.DEBUG = True\n\n\nclass DummyTask(Task):\n\n def __init__(self, *args, **kwargs):\n super(DummyTask, self).__init__(*args, **kwargs)\n self.has_run = False\n\n def complete(self):\n return self.has_run\n\n def run(self):\n logging.debug(\"%s - setting has_run\", self.task_id)\n self.has_run = True\n\n\nclass DynamicDummyTask(Task):\n p = luigi.Parameter()\n\n def output(self):\n return luigi.LocalTarget(self.p)\n\n def run(self):\n with self.output().open('w') as f:\n f.write('Done!')\n time.sleep(0.5) # so we can benchmark & see if parallelization works\n\n\nclass DynamicDummyTaskWithNamespace(DynamicDummyTask):\n task_namespace = 'banana'\n\n\nclass DynamicRequires(Task):\n p = luigi.Parameter()\n use_banana_task = luigi.BoolParameter(default=False)\n\n def output(self):\n return luigi.LocalTarget(os.path.join(self.p, 'parent'))\n\n def run(self):\n if self.use_banana_task:\n task_cls = DynamicDummyTaskWithNamespace\n else:\n task_cls = DynamicDummyTask\n dummy_targets = yield [task_cls(os.path.join(self.p, str(i)))\n for i in range(5)]\n dummy_targets += yield [task_cls(os.path.join(self.p, str(i)))\n for i in range(5, 7)]\n with self.output().open('w') as f:\n for i, d in enumerate(dummy_targets):\n for line in d.open('r'):\n print('%d: %s' % (i, line.strip()), file=f)\n\n\nclass DynamicRequiresOtherModule(Task):\n p = luigi.Parameter()\n\n def output(self):\n return luigi.LocalTarget(os.path.join(self.p, 'baz'))\n\n def run(self):\n import other_module\n other_target_foo = yield other_module.OtherModuleTask(os.path.join(self.p, 'foo'))\n other_target_bar = yield other_module.OtherModuleTask(os.path.join(self.p, 'bar'))\n\n with self.output().open('w') as f:\n f.write('Done!')\n\n\nclass WorkerTest(unittest.TestCase):\n\n def setUp(self):\n # InstanceCache.disable()\n self.sch = CentralPlannerScheduler(retry_delay=100, remove_delay=1000, worker_disconnect_delay=10)\n self.w = Worker(scheduler=self.sch, worker_id='X')\n self.w2 = Worker(scheduler=self.sch, worker_id='Y')\n self.time = time.time\n\n def tearDown(self):\n if time.time != self.time:\n time.time = self.time\n self.w.stop()\n self.w2.stop()\n\n def setTime(self, t):\n time.time = lambda: t\n\n def test_dep(self):\n class A(Task):\n\n def run(self):\n self.has_run = True\n\n def complete(self):\n return self.has_run\n a = A()\n\n class B(Task):\n\n def requires(self):\n return a\n\n def run(self):\n self.has_run = True\n\n def complete(self):\n return self.has_run\n\n b = B()\n a.has_run = False\n b.has_run = False\n\n self.assertTrue(self.w.add(b))\n self.assertTrue(self.w.run())\n self.assertTrue(a.has_run)\n self.assertTrue(b.has_run)\n\n def test_stop_getting_new_work(self):\n d = DummyTask()\n self.w.add(d)\n\n self.assertFalse(d.complete())\n self.w.handle_interrupt(signal.SIGUSR1, None)\n self.w.run()\n self.assertFalse(d.complete())\n\n def test_external_dep(self):\n class A(ExternalTask):\n\n def complete(self):\n return False\n a = A()\n\n class B(Task):\n\n def requires(self):\n return a\n\n def run(self):\n self.has_run = True\n\n def complete(self):\n return self.has_run\n\n b = B()\n\n a.has_run = False\n b.has_run = False\n\n self.assertTrue(self.w.add(b))\n self.assertTrue(self.w.run())\n\n self.assertFalse(a.has_run)\n self.assertFalse(b.has_run)\n\n def test_fail(self):\n class A(Task):\n\n def run(self):\n self.has_run = True\n raise Exception()\n\n def complete(self):\n return self.has_run\n\n a = A()\n\n class B(Task):\n\n def requires(self):\n return a\n\n def run(self):\n self.has_run = True\n\n def complete(self):\n return self.has_run\n\n b = B()\n\n a.has_run = False\n b.has_run = False\n\n self.assertTrue(self.w.add(b))\n self.assertFalse(self.w.run())\n\n self.assertTrue(a.has_run)\n self.assertFalse(b.has_run)\n\n def test_unknown_dep(self):\n # see central_planner_test.CentralPlannerTest.test_remove_dep\n class A(ExternalTask):\n\n def complete(self):\n return False\n\n class C(Task):\n\n def complete(self):\n return True\n\n def get_b(dep):\n class B(Task):\n\n def requires(self):\n return dep\n\n def run(self):\n self.has_run = True\n\n def complete(self):\n return False\n\n b = B()\n b.has_run = False\n return b\n\n b_a = get_b(A())\n b_c = get_b(C())\n\n self.assertTrue(self.w.add(b_a))\n # So now another worker goes in and schedules C -> B\n # This should remove the dep A -> B but will screw up the first worker\n self.assertTrue(self.w2.add(b_c))\n\n self.assertFalse(self.w.run()) # should not run anything - the worker should detect that A is broken\n self.assertFalse(b_a.has_run)\n # not sure what should happen??\n # self.w2.run() # should run B since C is fulfilled\n # self.assertTrue(b_c.has_run)\n\n def test_unfulfilled_dep(self):\n class A(Task):\n\n def complete(self):\n return self.done\n\n def run(self):\n self.done = True\n\n def get_b(a):\n class B(A):\n\n def requires(self):\n return a\n b = B()\n b.done = False\n a.done = True\n return b\n\n a = A()\n b = get_b(a)\n\n self.assertTrue(self.w.add(b))\n a.done = False\n self.w.run()\n self.assertTrue(a.complete())\n self.assertTrue(b.complete())\n\n def test_avoid_infinite_reschedule(self):\n class A(Task):\n\n def complete(self):\n return False\n\n class B(Task):\n\n def complete(self):\n return False\n\n def requires(self):\n return A()\n\n self.assertTrue(self.w.add(B()))\n self.assertFalse(self.w.run())\n\n def test_allow_reschedule_with_many_missing_deps(self):\n class A(Task):\n\n \"\"\" Task that must run twice to succeed \"\"\"\n i = luigi.IntParameter()\n\n runs = 0\n\n def complete(self):\n return self.runs >= 2\n\n def run(self):\n self.runs += 1\n\n class B(Task):\n done = False\n\n def requires(self):\n return map(A, range(20))\n\n def complete(self):\n return self.done\n\n def run(self):\n self.done = True\n\n b = B()\n w = Worker(scheduler=self.sch, worker_id='X', max_reschedules=1)\n self.assertTrue(w.add(b))\n self.assertFalse(w.run())\n\n # For b to be done, we must have rescheduled its dependencies to run them twice\n self.assertTrue(b.complete())\n self.assertTrue(all(a.complete() for a in b.deps()))\n\n def test_interleaved_workers(self):\n class A(DummyTask):\n pass\n\n a = A()\n\n class B(DummyTask):\n\n def requires(self):\n return a\n\n class ExternalB(ExternalTask):\n task_family = \"B\"\n\n def complete(self):\n return False\n\n b = B()\n eb = ExternalB()\n self.assertEqual(eb.task_id, \"B()\")\n\n sch = CentralPlannerScheduler(retry_delay=100, remove_delay=1000, worker_disconnect_delay=10)\n w = Worker(scheduler=sch, worker_id='X')\n w2 = Worker(scheduler=sch, worker_id='Y')\n\n self.assertTrue(w.add(b))\n self.assertTrue(w2.add(eb))\n logging.debug(\"RUNNING BROKEN WORKER\")\n self.assertTrue(w2.run())\n self.assertFalse(a.complete())\n self.assertFalse(b.complete())\n logging.debug(\"RUNNING FUNCTIONAL WORKER\")\n self.assertTrue(w.run())\n self.assertTrue(a.complete())\n self.assertTrue(b.complete())\n w.stop()\n w2.stop()\n\n def test_interleaved_workers2(self):\n # two tasks without dependencies, one external, one not\n class B(DummyTask):\n pass\n\n class ExternalB(ExternalTask):\n task_family = \"B\"\n\n def complete(self):\n return False\n\n b = B()\n eb = ExternalB()\n\n self.assertEqual(eb.task_id, \"B()\")\n\n sch = CentralPlannerScheduler(retry_delay=100, remove_delay=1000, worker_disconnect_delay=10)\n w = Worker(scheduler=sch, worker_id='X')\n w2 = Worker(scheduler=sch, worker_id='Y')\n\n self.assertTrue(w2.add(eb))\n self.assertTrue(w.add(b))\n\n self.assertTrue(w2.run())\n self.assertFalse(b.complete())\n self.assertTrue(w.run())\n self.assertTrue(b.complete())\n w.stop()\n w2.stop()\n\n def test_interleaved_workers3(self):\n class A(DummyTask):\n\n def run(self):\n logging.debug('running A')\n time.sleep(0.1)\n super(A, self).run()\n\n a = A()\n\n class B(DummyTask):\n\n def requires(self):\n return a\n\n def run(self):\n logging.debug('running B')\n super(B, self).run()\n\n b = B()\n\n sch = CentralPlannerScheduler(retry_delay=100, remove_delay=1000, worker_disconnect_delay=10)\n\n w = Worker(scheduler=sch, worker_id='X', keep_alive=True, count_uniques=True)\n w2 = Worker(scheduler=sch, worker_id='Y', keep_alive=True, count_uniques=True, wait_interval=0.1)\n\n self.assertTrue(w.add(a))\n self.assertTrue(w2.add(b))\n\n threading.Thread(target=w.run).start()\n self.assertTrue(w2.run())\n\n self.assertTrue(a.complete())\n self.assertTrue(b.complete())\n\n w.stop()\n w2.stop()\n\n def test_die_for_non_unique_pending(self):\n class A(DummyTask):\n\n def run(self):\n logging.debug('running A')\n time.sleep(0.1)\n super(A, self).run()\n\n a = A()\n\n class B(DummyTask):\n\n def requires(self):\n return a\n\n def run(self):\n logging.debug('running B')\n super(B, self).run()\n\n b = B()", "answers": [" sch = CentralPlannerScheduler(retry_delay=100, remove_delay=1000, worker_disconnect_delay=10)"], "length": 951, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "c15232f1-1b63-4b60-b053-a5e703dc2d79", "reasoning": "The test method defines tasks A and B, then creates instances a and b. The next logical step is to set up a scheduler for the worker, as done in previous tests. Therefore the next line should instantiate CentralPlannerScheduler with appropriate parameters.", "reasoning_model_answer": "sch = CentralPlannerScheduler(retry_delay=100, remove_delay=1000, worker_disconnect_delay=10)", "assistant_with_reasoning": "\nThe test method defines tasks A and B, then creates instances a and b. The next logical step is to set up a scheduler for the worker, as done in previous tests. Therefore the next line should instantiate CentralPlannerScheduler with appropriate parameters.\n\nsch = CentralPlannerScheduler(retry_delay=100, remove_delay=1000, worker_disconnect_delay=10)", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 6.876, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 12207, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "sch = CentralPlannerScheduler(retry_delay=100, remove_delay=1000, worker_disconnect_delay=10)", "score": 0.96, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\nusing Xunit;\n\nnamespace System.Linq.Expressions.Tests\n{\n public static class ConstantArrayTests\n {\n #region Test methods\n\n [Theory, ClassData(typeof(CompilationTypes))]\n public static void CheckBoolArrayConstantTest(bool useInterpreter)\n {\n foreach (bool[] value in new bool[][] { null, new bool[0], new bool[] { true, false }, new bool[100] })\n {\n VerifyBoolArrayConstant(value, useInterpreter);\n }\n }\n\n [Theory, ClassData(typeof(CompilationTypes))]\n public static void CheckByteArrayConstantTest(bool useInterpreter)\n {\n foreach (byte[] value in new byte[][] { null, new byte[0], new byte[] { 0, 1, byte.MaxValue }, new byte[100] })\n {\n VerifyByteArrayConstant(value, useInterpreter);\n }\n }\n\n [Theory, ClassData(typeof(CompilationTypes))]\n public static void CheckCustomArrayConstantTest(bool useInterpreter)\n {\n foreach (C[] value in new C[][] { null, new C[] { null, new C(), new D(), new D(0), new D(5) }, new C[10] })\n {\n VerifyCustomArrayConstant(value, useInterpreter);\n }\n }\n\n [Theory, ClassData(typeof(CompilationTypes))]\n public static void CheckCharArrayConstantTest(bool useInterpreter)\n {\n foreach (char[] value in new char[][] { null, new char[0], new char[] { '\\0', '\\b', 'A', '\\uffff' }, new char[100] })\n {\n VerifyCharArrayConstant(value, useInterpreter);\n }\n }\n\n [Theory, ClassData(typeof(CompilationTypes))]\n public static void CheckCustom2ArrayConstantTest(bool useInterpreter)\n {\n foreach (D[] value in new D[][] { null, new D[] { null, new D(), new D(0), new D(5) }, new D[10] })\n {\n VerifyCustom2ArrayConstant(value, useInterpreter);\n }\n }\n\n [Theory, ClassData(typeof(CompilationTypes))]\n public static void CheckDecimalArrayConstantTest(bool useInterpreter)\n {\n foreach (decimal[] value in new decimal[][] { null, new decimal[0], new decimal[] { decimal.Zero, decimal.One, decimal.MinusOne, decimal.MinValue, decimal.MaxValue }, new decimal[100] })\n {\n VerifyDecimalArrayConstant(value, useInterpreter);\n }\n }\n\n [Theory, ClassData(typeof(CompilationTypes))]\n public static void CheckDelegateArrayConstantTest(bool useInterpreter)\n {\n foreach (Delegate[] value in new Delegate[][] { null, new Delegate[0], new Delegate[] { null, (Func)delegate () { return null; }, (Func)delegate (int i) { return i + 1; }, (Action)delegate { } }, new Delegate[100] })\n {\n VerifyDelegateArrayConstant(value, useInterpreter);\n }\n }\n\n [Theory, ClassData(typeof(CompilationTypes))]\n public static void CheckDoubleArrayConstantTest(bool useInterpreter)\n {\n foreach (double[] value in new double[][] { null, new double[0], new double[] { 0, 1, -1, double.MinValue, double.MaxValue, double.Epsilon, double.NegativeInfinity, double.PositiveInfinity, double.NaN }, new double[100] })\n {\n VerifyDoubleArrayConstant(value, useInterpreter);\n }\n }\n\n [Theory, ClassData(typeof(CompilationTypes))]\n public static void CheckEnumArrayConstantTest(bool useInterpreter)\n {\n foreach (E[] value in new E[][] { null, new E[0], new E[] { (E)0, E.A, E.B, (E)int.MaxValue, (E)int.MinValue }, new E[100] })\n {\n VerifyEnumArrayConstant(value, useInterpreter);\n }\n }\n\n [Theory, ClassData(typeof(CompilationTypes))]\n public static void CheckEnumLongArrayConstantTest(bool useInterpreter)\n {\n foreach (El[] value in new El[][] { null, new El[0], new El[] { (El)0, El.A, El.B, (El)long.MaxValue, (El)long.MinValue }, new El[100] })\n {\n VerifyEnumLongArrayConstant(value, useInterpreter);\n }\n }\n\n [Theory, ClassData(typeof(CompilationTypes))]\n public static void CheckFloatArrayConstantTest(bool useInterpreter)\n {\n foreach (float[] value in new float[][] { null, new float[0], new float[] { 0, 1, -1, float.MinValue, float.MaxValue, float.Epsilon, float.NegativeInfinity, float.PositiveInfinity, float.NaN }, new float[100] })\n {\n VerifyFloatArrayConstant(value, useInterpreter);\n }\n }\n\n [Theory, ClassData(typeof(CompilationTypes))]\n public static void CheckFuncOfObjectConstantTest(bool useInterpreter)\n {\n foreach (Func[] value in new Func[][] { null, new Func[0], new Func[] { null, (Func)delegate () { return null; } }, new Func[100] })\n {\n VerifyFuncOfObjectConstant(value, useInterpreter);\n }\n }\n\n [Theory, ClassData(typeof(CompilationTypes))]\n public static void CheckInterfaceArrayConstantTest(bool useInterpreter)\n {\n foreach (I[] value in new I[][] { null, new I[0], new I[] { null, new C(), new D(), new D(0), new D(5) }, new I[100] })\n {\n VerifyInterfaceArrayConstant(value, useInterpreter);\n }\n }\n\n [Theory, ClassData(typeof(CompilationTypes))]\n public static void CheckIEquatableOfCustomConstantTest(bool useInterpreter)\n {\n foreach (IEquatable[] value in new IEquatable[][] { null, new IEquatable[0], new IEquatable[] { null, new C(), new D(), new D(0), new D(5) }, new IEquatable[100] })\n {\n VerifyIEquatableOfCustomConstant(value, useInterpreter);\n }\n }\n\n [Theory, ClassData(typeof(CompilationTypes))]\n public static void CheckIEquatableOfCustom2ConstantTest(bool useInterpreter)\n {\n foreach (IEquatable[] value in new IEquatable[][] { null, new IEquatable[0], new IEquatable[] { null, new D(), new D(0), new D(5) }, new IEquatable[100] })\n {\n VerifyIEquatableOfCustom2Constant(value, useInterpreter);\n }\n }\n\n [Theory, ClassData(typeof(CompilationTypes))]\n public static void CheckIntArrayConstantTest(bool useInterpreter)\n {\n foreach (int[] value in new int[][] { null, new int[0], new int[] { 0, 1, -1, int.MinValue, int.MaxValue }, new int[100] })\n {\n VerifyIntArrayConstant(value, useInterpreter);\n }\n }\n\n [Theory, ClassData(typeof(CompilationTypes))]\n public static void CheckLongArrayConstantTest(bool useInterpreter)\n {\n foreach (long[] value in new long[][] { null, new long[0], new long[] { 0, 1, -1, long.MinValue, long.MaxValue }, new long[100] })\n {\n VerifyLongArrayConstant(value, useInterpreter);\n }\n }\n\n [Theory, ClassData(typeof(CompilationTypes))]\n public static void CheckObjectArrayConstantTest(bool useInterpreter)\n {\n foreach (object[] value in new object[][] { null, new object[0], new object[] { null, new object(), new C(), new D(3) }, new object[100] })\n {\n VerifyObjectArrayConstant(value, useInterpreter);\n }\n }\n\n [Theory, ClassData(typeof(CompilationTypes))]\n public static void CheckStructArrayConstantTest(bool useInterpreter)\n {\n foreach (S[] value in new S[][] { null, new S[] { default(S), new S() }, new S[10] })\n {\n VerifyStructArrayConstant(value, useInterpreter);\n }\n }\n\n [Theory, ClassData(typeof(CompilationTypes))]\n public static void CheckSByteArrayConstantTest(bool useInterpreter)\n {\n foreach (sbyte[] value in new sbyte[][] { null, new sbyte[0], new sbyte[] { 0, 1, -1, sbyte.MinValue, sbyte.MaxValue }, new sbyte[100] })\n {\n VerifySByteArrayConstant(value, useInterpreter);\n }\n }\n\n [Theory, ClassData(typeof(CompilationTypes))]\n public static void CheckStructWithStringArrayConstantTest(bool useInterpreter)\n {\n foreach (Sc[] value in new Sc[][] { null, new Sc[0], new Sc[] { default(Sc), new Sc(), new Sc(null) }, new Sc[100] })\n {\n VerifyStructWithStringArrayConstant(value, useInterpreter);\n }\n }\n\n [Theory, ClassData(typeof(CompilationTypes))]\n public static void CheckStructWithStringAndFieldArrayConstantTest(bool useInterpreter)\n {\n foreach (Scs[] value in new Scs[][] { null, new Scs[0], new Scs[] { default(Scs), new Scs(), new Scs(null, new S()) }, new Scs[100] })\n {\n VerifyStructWithStringAndFieldArrayConstant(value, useInterpreter);\n }\n }\n\n [Theory, ClassData(typeof(CompilationTypes))]\n public static void CheckShortArrayConstantTest(bool useInterpreter)\n {\n foreach (short[] value in new short[][] { null, new short[0], new short[] { 0, 1, -1, short.MinValue, short.MaxValue }, new short[100] })\n {\n VerifyShortArrayConstant(value, useInterpreter);\n }\n }\n\n [Theory, ClassData(typeof(CompilationTypes))]\n public static void CheckStructWithTwoValuesArrayConstantTest(bool useInterpreter)\n {\n foreach (Sp[] value in new Sp[][] { null, new Sp[0], new Sp[] { default(Sp), new Sp(), new Sp(5, 5.0) }, new Sp[100] })\n {\n VerifyStructWithTwoValuesArrayConstant(value, useInterpreter);\n }\n }\n\n [Theory, ClassData(typeof(CompilationTypes))]\n public static void CheckStructWithValueArrayConstantTest(bool useInterpreter)\n {\n foreach (Ss[] value in new Ss[][] { null, new Ss[0], new Ss[] { default(Ss), new Ss(), new Ss(new S()) }, new Ss[100] })\n {\n VerifyStructWithValueArrayConstant(value, useInterpreter);\n }\n }\n\n [Theory, ClassData(typeof(CompilationTypes))]\n public static void CheckStringArrayConstantTest(bool useInterpreter)\n {\n foreach (string[] value in new string[][] { null, new string[0], new string[] { null, \"\", \"a\", \"foo\" }, new string[100] })\n {\n VerifyStringArrayConstant(value, useInterpreter);\n }\n }\n\n [Theory, ClassData(typeof(CompilationTypes))]\n public static void CheckUIntArrayConstantTest(bool useInterpreter)\n {\n foreach (uint[] value in new uint[][] { null, new uint[0], new uint[] { 0, 1, uint.MaxValue }, new uint[100] })\n {\n VerifyUIntArrayConstant(value, useInterpreter);\n }\n }\n\n [Theory, ClassData(typeof(CompilationTypes))]\n public static void CheckULongArrayConstantTest(bool useInterpreter)\n {\n foreach (ulong[] value in new ulong[][] { null, new ulong[0], new ulong[] { 0, 1, ulong.MaxValue }, new ulong[100] })\n {\n VerifyULongArrayConstant(value, useInterpreter);\n }\n }\n\n [Theory, ClassData(typeof(CompilationTypes))]\n public static void CheckUShortArrayConstantTest(bool useInterpreter)\n {\n foreach (ushort[] value in new ushort[][] { null, new ushort[0], new ushort[] { 0, 1, ushort.MaxValue }, new ushort[100] })\n {\n VerifyUShortArrayConstant(value, useInterpreter);\n }\n }\n\n [Theory, ClassData(typeof(CompilationTypes))]\n public static void CheckGenericWithStructRestrictionWithEnumArrayConstantTest(bool useInterpreter)\n {\n CheckGenericWithStructRestrictionArrayConstantHelper(useInterpreter);\n }\n\n [Theory, ClassData(typeof(CompilationTypes))]\n public static void CheckGenericWithStructRestrictionWithStructArrayConstantTest(bool useInterpreter)\n {\n CheckGenericWithStructRestrictionArrayConstantHelper(useInterpreter);\n }\n\n [Theory, ClassData(typeof(CompilationTypes))]\n public static void CheckGenericWithStructRestrictionWithStructWithStringAndValueArrayConstantTest(bool useInterpreter)\n {\n CheckGenericWithStructRestrictionArrayConstantHelper(useInterpreter);\n }\n\n [Theory, ClassData(typeof(CompilationTypes))]\n public static void CheckGenericWithCustomArrayTest(bool useInterpreter)\n {\n CheckGenericArrayHelper(useInterpreter);\n }\n\n [Theory, ClassData(typeof(CompilationTypes))]\n public static void CheckGenericWithEnumArrayTest(bool useInterpreter)\n {\n CheckGenericArrayHelper(useInterpreter);\n }\n\n [Theory, ClassData(typeof(CompilationTypes))]\n public static void CheckGenericWithObjectArrayTest(bool useInterpreter)\n {\n CheckGenericArrayHelper(useInterpreter);\n }\n\n [Theory, ClassData(typeof(CompilationTypes))]\n public static void CheckGenericWithStructArrayTest(bool useInterpreter)\n {\n CheckGenericArrayHelper(useInterpreter);\n }\n\n [Theory, ClassData(typeof(CompilationTypes))]\n public static void CheckGenericWithStructWithStringAndValueArrayTest(bool useInterpreter)\n {\n CheckGenericArrayHelper(useInterpreter);\n }\n\n [Theory, ClassData(typeof(CompilationTypes))]\n public static void CheckGenericWithClassRestrictionWithCustomTest(bool useInterpreter)\n {\n CheckGenericWithClassRestrictionArrayHelper(useInterpreter);\n }\n\n [Theory, ClassData(typeof(CompilationTypes))]\n public static void CheckGenericWithClassRestrictionWithObjectTest(bool useInterpreter)\n {\n CheckGenericWithClassRestrictionArrayHelper(useInterpreter);\n }\n\n [Theory, ClassData(typeof(CompilationTypes))]\n public static void CheckGenericWithClassAndNewRestrictionWithCustomTest(bool useInterpreter)\n {\n CheckGenericWithClassAndNewRestrictionArrayHelper(useInterpreter);\n }\n\n [Theory, ClassData(typeof(CompilationTypes))]\n public static void CheckGenericWithClassAndNewRestrictionWithObjectTest(bool useInterpreter)\n {\n CheckGenericWithClassAndNewRestrictionArrayHelper(useInterpreter);\n }\n\n [Theory, ClassData(typeof(CompilationTypes))]\n public static void CheckGenericWithSubClassRestrictionTest(bool useInterpreter)\n {\n CheckGenericWithSubClassRestrictionHelper(useInterpreter);\n }\n\n [Theory, ClassData(typeof(CompilationTypes))]\n public static void CheckGenericWithSubClassAndNewRestrictionTest(bool useInterpreter)\n {\n CheckGenericWithSubClassAndNewRestrictionHelper(useInterpreter);\n }\n\n #endregion\n\n #region Generic helpers\n\n private static void CheckGenericWithStructRestrictionArrayConstantHelper(bool useInterpreter) where Ts : struct\n {\n foreach (Ts[] value in new Ts[][] { null, new Ts[0], new Ts[] { default(Ts), new Ts() }, new Ts[100] })\n {\n VerifyGenericArrayWithStructRestriction(value, useInterpreter);\n }\n }", "answers": [" private static void CheckGenericArrayHelper(bool useInterpreter)"], "length": 1274, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "7ea93e90-bf3f-46f2-a3b2-38449f520353", "reasoning": "The code just closed the method CheckGenericWithStructRestrictionArrayConstantHelper. In the Generic helpers region, the next helper method defined is the generic array helper used by many tests (e.g., CheckGenericArrayHelper). Therefore the next line should start that method definition: the signature line for CheckGenericArrayHelper taking the useInterpreter flag.", "reasoning_model_answer": "private static void CheckGenericArrayHelper(bool useInterpreter)", "assistant_with_reasoning": "\nThe code just closed the method CheckGenericWithStructRestrictionArrayConstantHelper. In the Generic helpers region, the next helper method defined is the generic array helper used by many tests (e.g., CheckGenericArrayHelper). Therefore the next line should start that method definition: the signature line for CheckGenericArrayHelper taking the useInterpreter flag.\n\nprivate static void CheckGenericArrayHelper(bool useInterpreter)", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.488, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 15909, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "private static void CheckGenericArrayHelper(bool useInterpreter)", "score": 0.94, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "#! /usr/bin/env python\n\n__author__ = \"Jose Caballero\"\n__email__ = \"jcaballero@bnl.gov\"\n\n\"\"\"\nCode to store and manipulate data.\n\n-------------------------------------------------------------------------------\n class StatusInfo\n-------------------------------------------------------------------------------\n\nThis is the only class implemented that is meant to be public.\n\nThe data stored by instances of class StatusInfo must be a list of items. \nThese items can be anything, including objects. \nA typical example is data is a list of HTCondor ClassAds, where each \nitem in the data list represents an HTCondor job.\n\nClass StatusInfo has several methods to manipulate the data, \nbut in all cases the output of the method is a new instance of one of the \nclasses implemented: StatusInfo, _DictStatusInfo, etc.\nMethods never modify the current instance data.\nThis allows to perform different manipulations from the same source object.\n\nThere are two types of methods in class StatusInfo:\n\n - methods whose object output accepts further processing.\n Examples are methods indexby(), filter(), and map().\n\n - methods whose object output can not be processed anymore.\n An attempt to call any method on these instances\n will raise an Exception.\n Examples are methods reduce(), and process().\n\nThe method indexby() is somehow special. \nIt is being used to split the stored data into a dictionary, \naccording to whatever rule is provided. \nThe values of this dictionary are themselves new StatusInfo instances. \nTherefore, the output of calling indexby() once is an _DictStatusInfo object \nwith data:\n \n self.data = {\n key1: ,\n key2: ,\n ...\n keyN: \n }\n\n-------------------------------------------------------------------------------\n\nThe UML source for the classes is as follows:\n\n @startuml\n \n object <|-- _Base\n \n _Base <|-- _BaseDict \n _Base <|-- StatusInfo \n _Base <|-- _NonMutableStatusInfo \n\n _AnalysisInterface <|-- StatusInfo \n _AnalysisInterface <|-- _DictStatusInfo \n\n _BaseDict <|-- _DictStatusInfo \n _BaseDict <|-- _NonMutableDictStatusInfo \n\n _GetRawBase <|-- StatusInfo \n _GetRawBase <|-- _NonMutableStatusInfo \n \n @enduml\n\n\n +--------+ \n | object |\n +--------+\n ^\n |\n +--------------------+ +-------+\n | _AnalysisInterface | +------------------------------->| _Base |<-----------------+ \n +--------------------+ | +-------+ |\n ^ ^ | +-------------+ ^ +-----------+ \n | | | | _GetRawBase | | | _BaseDict | \n | | | +-------------+ | +-----------+ \n | | | ^ ^ | ^ ^ \n | | | | | | | | \n | | | | | | | | \n | | | | | | | | \n | | | | | | | | \n | +------------+ | | +-----------------------+ | |\n | | StatusInfo |-------+ +---| _NonMutableStatusInfo | | |\n | +------------+ +-----------------------+ | |\n | +-----------------+ | +---------------------------+\n +------------------------------------| _DictStatusInfo |-----------------------+ | _NonMutableDictStatusInfo |\n +-----------------+ +---------------------------+\n\n\n\n\n-------------------------------------------------------------------------------\n Analyzers \n-------------------------------------------------------------------------------\n\n\nThe input to all methods is an object of type Analyzer. \nAnalyzers are classes that implement the rules or policies to be used \nfor each method call. \nFor example: \n - a call to method indexby() expects an object of type AnalyzerIndexBy\n - a call to method map() expects an object of type AnalyzerMap\n - a call to method reduce() expects an object of type AnalyzerReduce\n - etc.\n\nEach Analyzer object must have implemented a method \nwith the same name that the StatusInfo's method it is intended for. \nFor exmple:\n\n - classes AnalyzerIndexBy must implement method indexby()\n - classes AnalyzerMap must implement method map()\n - classes AnalyzerReduce must implement method reduce()\n - ...\n\nPassing an analyzer object that does not implement the right method will \nraise an IncorrectAnalyzer Exception.\n\nA few basic pre-made Analyzers have been implemented, ready to use. \n\"\"\"\n\nimport copy\nimport datetime\nimport inspect\nimport logging\nimport logging.handlers\nimport threading\nimport time\nimport traceback\nimport os\nimport pwd\nimport sys\n\n# =============================================================================\n# Decorators \n#\n# Note:\n# the decorator must be implemented before the classes using it \n# otherwise, they do not find it\n# =============================================================================\n\ndef validate_call(method):\n \"\"\"\n validates calls to the processing methods.\n Checks: \n * if the StatusInfo object is mutable or not, \n * if a method is being called with the right type of Analyzer\n Exceptions are raised with some criteria is not met.\n \"\"\"\n def wrapper(self, analyzer, *k, **kw):\n method_name = method.__name__\n analyzertype = analyzer.analyzertype\n if not analyzertype == method_name:\n msg = 'Analyzer object {obj} is not type {name}. Raising exception.'\n msg = msg.format(obj = analyzer,\n name = method_name)\n self.log.error(msg)\n raise IncorrectAnalyzer(analyzer, analyzertype, method_name)\n out = method(self, analyzer, *k, **kw)\n return out\n return wrapper\n\n\ndef catch_exception(method):\n \"\"\"\n catches any exception during data processing\n and raises an AnalyzerFailure exception\n \"\"\"\n def wrapper(self, analyzer):\n try:\n out = method(self, analyzer)\n except Exception as ex:\n msg = 'Exception of type \"%s\" ' %ex.__class__.__name__\n msg += 'with content \"%s\" ' %ex\n msg += 'while calling \"%s\" ' %method.__name__\n msg += 'with analyzer \"%s\"' %analyzer\n raise AnalyzerFailure(msg)\n else:\n return out\n return wrapper\n\n\n\n# =============================================================================\n# Base classes and interfaces\n# =============================================================================\n\nclass _Base(object):\n\n def __init__(self, data, timestamp=None):\n \"\"\" \n :param data: the data to be recorded\n :param timestamp: the time when this object was created\n \"\"\" \n self.log = logging.getLogger('info')\n self.log.addHandler(logging.NullHandler())\n\n msg ='Initializing object with input options: \\\ndata={data}, timestamp={timestamp}'\n msg = msg.format(data=data,\n timestamp=timestamp)\n self.log.debug(msg)\n\n self.data = data \n\n if not timestamp:\n timestamp = int(time.time())\n msg = 'Setting timestamp to %s' %timestamp\n self.log.debug(msg)\n self.timestamp = timestamp\n\n self.log.debug('Object initialized')\n\n\n def get(self, *key_l):\n \"\"\"\n returns the data hosted by the Info object in the \n tree structure pointed by all keys\n The output is the data, either a dictionary or the original raw list \n :param key_l list: list of keys for each nested dictionary\n :rtype data:\n \"\"\"\n if len(key_l) == 0:\n return self.data\n else:\n key = key_l[0]\n if key not in self.data.keys():\n raise MissingKey(key)\n data = self.data[key]\n return data.get(*key_l[1:])\n\n\nclass _BaseDict(_Base):\n \"\"\"\n adds an extra check for the input data\n \"\"\"\n def __init__(self, data, timestamp=None):\n super(_BaseDict, self).__init__(data, timestamp)\n if type(self.data) is not dict:\n raise IncorrectInputDataType(dict)\n\n def getraw(self):\n out = {}\n for key, value in self.data.items():\n out[key] = value.getraw()\n return out\n\n def __getitem__(self, key):\n \"\"\"\n returns the Info object pointed by the key\n :param key: the key in the higher level dictionary\n :rtype StatusInfo: \n \"\"\"\n if key not in self.data.keys():\n raise MissingKey(key)\n return self.data[key]\n\n# extra get methods\n\nclass _GetRawBase:\n\n def getraw(self):\n return self.data\n\n\n# interfaces \n\nclass _AnalysisInterface:\n\n def indexby(self, analyzer):\n raise NotImplementedError\n\n def map(self, analyzer):\n raise NotImplementedError\n\n def filter(self, analyzer):\n raise NotImplementedError\n\n def reduce(self, analyzer):\n raise NotImplementedError\n\n def transform(self, analyzer):\n raise NotImplementedError\n\n def process(self, analyzer):\n raise NotImplementedError\n\n\n# =============================================================================\n# Info class\n# =============================================================================\n\nclass StatusInfo(_Base, _AnalysisInterface, _GetRawBase):\n\n def __init__(self, data, timestamp=None):\n super(StatusInfo, self).__init__(data, timestamp)\n if type(self.data) is not list:\n msg = 'Input data %s is not a dict. Raising exception' %data\n self.log.error(msg)\n raise IncorrectInputDataType(list)\n\n\n def analyze(self, analyzer):\n \"\"\"\n generic method that picks the right one \n based on the type of analyzer\n :param analyzer: an Analyzer object \n :rtype StatusInfo:\n \"\"\"\n self.log.debug('Starting')\n if analyzer.analyzertype == 'indexby':\n return self.indexby(analyzer)\n elif analyzer.analyzertype == 'filter':\n return self.filter(analyzer)\n elif analyzer.analyzertype == 'map':\n return self.map(analyzer)\n elif analyzer.analyzertype == 'reduce':\n return self.reduce(analyzer)\n elif analyzer.analyzertype == 'transform':\n return self.transform(analyzer)\n elif analyzer.analyzertype == 'process':\n return self.process(analyzer)\n else:\n msg = 'Input object %s is not a valid analyzer. Raising exception.'\n self.log.error(msg)\n raise NotAnAnalyzer()\n\n\n def apply_algorithm(self, algorithm):\n \"\"\"\n invoke all steps in an Algorithm object\n and returns the final output\n :param Algorithm algorithm: \n :rtype StatusInfo:\n \"\"\"\n return algorithm.analyze(self)\n\n # -------------------------------------------------------------------------\n # methods to manipulate the data\n # -------------------------------------------------------------------------\n\n @validate_call\n def indexby(self, analyzer):\n \"\"\"\n groups the items recorded in self.data into a dictionary\n and creates a new StatusInfo object with it. \n 1. make a dictinary grouping items according to rules in analyzer\n 2. convert that dictionary into a dictionary of StatusInfo objects\n 3. make a new StatusInfo with that dictionary\n :param analyzer: an instance of AnalyzerIndexBy-type class \n implementing method indexby()\n :rtype StatusInfo:\n \"\"\"\n self.log.debug('Starting with analyzer %s' %analyzer)\n\n new_data = self.__indexby(analyzer)\n new_info = _DictStatusInfo(new_data, timestamp=self.timestamp)\n return new_info\n\n @catch_exception\n def __indexby(self, analyzer):\n # 1\n tmp_new_data = {} \n for item in self.data:\n key = analyzer.indexby(item)\n if key is not None:\n if key not in tmp_new_data.keys():\n tmp_new_data[key] = []\n tmp_new_data[key].append(item) \n # 2\n new_data = {}\n for k, v in tmp_new_data.items():", "answers": [" new_data[k] = StatusInfo(v, timestamp=self.timestamp)"], "length": 1270, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "eda54dfd-4e22-463c-9947-a2ec8cd6f809", "reasoning": "The __indexby method builds a temporary dict of lists (tmp_new_data). It then iterates over each key and list (k, v) to convert each list into a StatusInfo object, storing it in new_data. The next logical line inside the loop is the assignment creating a StatusInfo from the list v, preserving the original timestamp.", "reasoning_model_answer": "new_data[k] = StatusInfo(v, timestamp=self.timestamp)", "assistant_with_reasoning": "\nThe __indexby method builds a temporary dict of lists (tmp_new_data). It then iterates over each key and list (k, v) to convert each list into a StatusInfo object, storing it in new_data. The next logical line inside the loop is the assignment creating a StatusInfo from the list v, preserving the original timestamp.\n\nnew_data[k] = StatusInfo(v, timestamp=self.timestamp)", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 2.978, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 13368, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "new_data[k] = StatusInfo(v, timestamp=self.timestamp)", "score": 0.9, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "# Copyright 2017 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Activity analysis.\n\nRequires qualified name annotations (see qual_names.py).\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport copy\nimport weakref\n\nimport gast\nimport six\n\nfrom tensorflow.python.autograph.pyct import anno\nfrom tensorflow.python.autograph.pyct import qual_names\nfrom tensorflow.python.autograph.pyct import transformer\nfrom tensorflow.python.autograph.pyct.static_analysis.annos import NodeAnno\n\n\nclass Scope(object):\n \"\"\"Encloses local symbol definition and usage information.\n\n This can track for instance whether a symbol is modified in the current scope.\n Note that scopes do not necessarily align with Python's scopes. For example,\n the body of an if statement may be considered a separate scope.\n\n Caution - the AST references held by this object are weak.\n\n Scope objects are mutable during construction only, and must be frozen using\n `Scope.finalize()` before use. Furthermore, a scope is consistent only after\n all its children have been frozen. While analysing code blocks, scopes are\n being gradually built, from the innermost scope outward. Freezing indicates\n that the analysis of a code block is complete. Once frozen, mutation is no\n longer allowed. `is_final` tracks whether the scope is frozen or not. Certain\n properties, like `referenced`, are only accurate when called on frozen scopes.\n\n Attributes:\n parent: Optional[Scope], the parent scope, if any.\n isolated: bool, whether the scope is a true Python scope (e.g. the scope of\n a function), or just a surrogate tracking an ordinary code block. Using\n the terminology of the Python 3 reference documentation, True roughly\n represents an actual scope, whereas False represents an ordinary code\n block.\n isolated_names: Set[qual_names.QN], identifiers that are isolated to this\n scope (even if the scope is not isolated).\n annotations: Set[qual_names.QN], identifiers used as type annotations\n in this scope.\n read: Set[qual_names.QN], identifiers read in this scope.\n modified: Set[qual_names.QN], identifiers modified in this scope.\n deleted: Set[qual_names.QN], identifiers deleted in this scope.\n bound: Set[qual_names.QN], names that are bound to this scope. See\n https://docs.python.org/3/reference/executionmodel.html#binding-of-names\n for a precise definition.\n globals: Set[qual_names.QN], names that are explicitly marked as global in\n this scope. Note that this doesn't include free read-only vars bound to\n global symbols.\n free_vars: Set[qual_names.QN], the free variables in this scope. See\n https://docs.python.org/3/reference/executionmodel.html for a precise\n definition.\n params: WeakValueDictionary[qual_names.QN, ast.Node], function arguments\n visible in this scope, mapped to the function node that defines them.\n enclosing_scope: Scope, the innermost isolated scope that is a transitive\n parent of this scope. May be the scope itself.\n referenced: Set[qual_names.QN], the totality of the symbols used by this\n scope and its parents.\n is_final: bool, whether the scope is frozen or not.\n\n Note - simple statements may never delete and modify a symbol at the same\n time. However, compound ones like if statements can. In that latter case, it's\n undefined whether the symbol is actually modified or deleted upon statement\n exit. Certain analyses like reaching definitions need to be careful about\n this.\n \"\"\"\n\n # Note: this mutable-immutable pattern is used because using a builder would\n # have taken a lot more boilerplate.\n\n def __init__(self, parent, isolated=True):\n \"\"\"Create a new scope.\n\n Args:\n parent: A Scope or None.\n isolated: Whether the scope is isolated, that is, whether variables\n modified in this scope should be considered modified in the parent\n scope.\n \"\"\"\n self.parent = parent\n self.isolated = isolated\n\n self.isolated_names = set()\n\n self.read = set()\n self.modified = set()\n self.deleted = set()\n\n self.bound = set()\n self.globals = set()\n self.annotations = set()\n\n self.params = weakref.WeakValueDictionary()\n\n # Certain fields can only be accessed after the scope and all its parent\n # scopes have been fully built. This field guards that.\n self.is_final = False\n\n @property\n def enclosing_scope(self):\n assert self.is_final\n if self.parent is not None and not self.isolated:\n return self.parent\n return self\n\n @property\n def referenced(self):\n if self.parent is not None:\n return self.read | self.parent.referenced\n return self.read\n\n @property\n def free_vars(self):\n enclosing_scope = self.enclosing_scope\n return enclosing_scope.read - enclosing_scope.bound\n\n def copy_from(self, other):\n \"\"\"Recursively copies the contents of this scope from another scope.\"\"\"\n assert not self.is_final\n if self.parent is not None:\n assert other.parent is not None\n self.parent.copy_from(other.parent)\n self.isolated_names = copy.copy(other.isolated_names)\n self.modified = copy.copy(other.modified)\n self.read = copy.copy(other.read)\n self.deleted = copy.copy(other.deleted)\n self.bound = copy.copy(other.bound)\n self.annotations = copy.copy(other.annotations)\n self.params = copy.copy(other.params)\n\n @classmethod\n def copy_of(cls, other):\n if other.parent is not None:\n assert other.parent is not None\n parent = cls.copy_of(other.parent)\n else:\n parent = None\n new_copy = cls(parent)\n new_copy.copy_from(other)\n return new_copy\n\n def merge_from(self, other):\n \"\"\"Adds all activity from another scope to this scope.\"\"\"\n assert not self.is_final\n if self.parent is not None:\n assert other.parent is not None\n self.parent.merge_from(other.parent)\n self.isolated_names.update(other.isolated_names)\n self.read.update(other.read)\n self.modified.update(other.modified)\n self.bound.update(other.deleted)\n self.annotations.update(other.annotations)\n self.params.update(other.params)\n\n def finalize(self):\n \"\"\"Freezes this scope.\"\"\"\n assert not self.is_final\n # TODO(mdan): freeze read, modified, bound.\n if self.parent is not None:\n assert not self.parent.is_final\n if not self.isolated:\n self.parent.read.update(self.read - self.isolated_names)\n self.parent.modified.update(self.modified - self.isolated_names)\n self.parent.bound.update(self.bound - self.isolated_names)\n self.parent.globals.update(self.globals)\n self.parent.annotations.update(self.annotations)\n else:\n # TODO(mdan): This is not accurate.\n self.parent.read.update(self.read - self.bound)\n self.parent.annotations.update(self.annotations - self.bound)\n self.is_final = True\n\n def __repr__(self):\n return 'Scope{r=%s, w=%s}' % (tuple(self.read), tuple(self.modified))\n\n def mark_param(self, name, owner):\n # Assumption: all AST nodes have the same life span. This lets us use\n # a weak reference to mark the connection between a symbol node and the\n # function node whose argument that symbol is.\n self.params[name] = owner\n\n\nclass _Comprehension(object):\n\n no_root = True\n\n def __init__(self):\n # TODO(mdan): Consider using an enum.\n self.is_list_comp = False\n self.targets = set()\n\n\nclass _FunctionOrClass(object):\n\n def __init__(self):\n self.node = None\n\n\nclass ActivityAnalyzer(transformer.Base):\n \"\"\"Annotates nodes with local scope information.\n\n See Scope.\n\n The use of this class requires that qual_names.resolve() has been called on\n the node. This class will ignore nodes have not been\n annotated with their qualified names.\n \"\"\"\n\n def __init__(self, context, parent_scope=None):\n super(ActivityAnalyzer, self).__init__(context)\n self.allow_skips = False\n self.scope = Scope(parent_scope, isolated=True)\n\n # Note: all these flags crucially rely on the respective nodes are\n # leaves in the AST, that is, they cannot contain other statements.\n self._in_aug_assign = False\n self._in_annotation = False\n self._track_annotations_only = False\n\n @property\n def _in_constructor(self):\n context = self.state[_FunctionOrClass]\n if context.level > 2:\n innermost = context.stack[-1].node\n parent = context.stack[-2].node\n return (isinstance(parent, gast.ClassDef) and\n (isinstance(innermost, gast.FunctionDef) and\n innermost.name == '__init__'))\n return False\n\n def _node_sets_self_attribute(self, node):\n if anno.hasanno(node, anno.Basic.QN):\n qn = anno.getanno(node, anno.Basic.QN)\n # TODO(mdan): The 'self' argument is not guaranteed to be called 'self'.\n if qn.has_attr and qn.parent.qn == ('self',):\n return True\n return False\n\n def _track_symbol(self, node, composite_writes_alter_parent=False):\n if self._track_annotations_only and not self._in_annotation:\n return\n\n # A QN may be missing when we have an attribute (or subscript) on a function\n # call. Example: a().b\n if not anno.hasanno(node, anno.Basic.QN):\n return\n qn = anno.getanno(node, anno.Basic.QN)\n\n # When inside a comprehension, ignore reads to any of the comprehensions's\n # targets. This includes attributes or slices of those arguments.\n for l in self.state[_Comprehension]:\n if qn in l.targets:\n return\n if qn.owner_set & set(l.targets):\n return\n\n if isinstance(node.ctx, gast.Store):\n # In comprehensions, modified symbols are the comprehension targets.\n if self.state[_Comprehension].level > 0:\n self.state[_Comprehension].targets.add(qn)\n # List comprehension targets leak in Python 2.\n # For details, see:\n # https://stackoverflow.com/questions/4198906/list-comprehension-rebinds-names-even-after-scope-of-comprehension-is-this-righ\n if not (six.PY2 and self.state[_Comprehension].is_list_comp):\n return\n\n self.scope.modified.add(qn)\n self.scope.bound.add(qn)\n if qn.is_composite and composite_writes_alter_parent:\n self.scope.modified.add(qn.parent)\n if self._in_aug_assign:\n self.scope.read.add(qn)\n\n elif isinstance(node.ctx, gast.Load):\n self.scope.read.add(qn)\n if self._in_annotation:\n self.scope.annotations.add(qn)\n\n elif isinstance(node.ctx, gast.Param):\n self.scope.bound.add(qn)\n self.scope.mark_param(qn, self.state[_FunctionOrClass].node)\n\n elif isinstance(node.ctx, gast.Del):\n # The read matches the Python semantics - attempting to delete an\n # undefined symbol is illegal.\n self.scope.read.add(qn)\n # Targets of del are considered bound:\n # https://docs.python.org/3/reference/executionmodel.html#binding-of-names\n self.scope.bound.add(qn)\n self.scope.deleted.add(qn)\n\n else:\n raise ValueError('Unknown context {} for node \"{}\".'.format(\n type(node.ctx), qn))\n\n def _enter_scope(self, isolated):\n self.scope = Scope(self.scope, isolated=isolated)\n\n def _exit_scope(self):\n exited_scope = self.scope\n exited_scope.finalize()\n self.scope = exited_scope.parent\n return exited_scope\n\n def _exit_and_record_scope(self, node, tag=anno.Static.SCOPE):\n node_scope = self._exit_scope()\n anno.setanno(node, tag, node_scope)\n return node_scope\n\n def _process_statement(self, node):\n self._enter_scope(False)\n node = self.generic_visit(node)\n self._exit_and_record_scope(node)\n return node", "answers": [" def _process_annotation(self, node):"], "length": 1306, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "e34716c0-a6d4-42f7-9626-8c73ddbc0323", "reasoning": "The method _process_statement ends with a return statement. In the ActivityAnalyzer class, the next logical method defined is one that processes a list of statements, typically named _process_body. Following the pattern of defining helper methods after each statement processor, the next line of code should start the definition of this new method.", "reasoning_model_answer": "def _process_body(self, nodes):", "assistant_with_reasoning": "\nThe method _process_statement ends with a return statement. In the ActivityAnalyzer class, the next logical method defined is one that processes a list of statements, typically named _process_body. Following the pattern of defining helper methods after each statement processor, the next line of code should start the definition of this new method.\n\ndef _process_body(self, nodes):", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.044, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 12380, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "def _process_body(self, nodes):", "score": 0.78, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "// \n// Copyright (c) Microsoft and contributors. All rights reserved.\n// \n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n// http://www.apache.org/licenses/LICENSE-2.0\n// \n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// \n// See the License for the specific language governing permissions and\n// limitations under the License.\n// \n\n// Warning: This code was generated by a tool.\n// \n// Changes to this file may cause incorrect behavior and will be lost if the\n// code is regenerated.\n\nusing System;\nusing System.Linq;\nusing System.Net.Http;\nusing Hyak.Common;\nusing Microsoft.Azure;\nusing Microsoft.WindowsAzure.Management.SiteRecovery;\nusing Microsoft.WindowsAzure.Management.SiteRecovery.Models;\n\nnamespace Microsoft.WindowsAzure.Management.SiteRecovery\n{\n public partial class SiteRecoveryManagementClient : ServiceClient, ISiteRecoveryManagementClient\n {\n private string _apiVersion;\n \n /// \n /// Gets the API version.\n /// \n public string ApiVersion\n {\n get { return this._apiVersion; }\n }\n \n private Uri _baseUri;\n \n /// \n /// Gets the URI used as the base for all cloud service requests.\n /// \n public Uri BaseUri\n {\n get { return this._baseUri; }\n }\n \n private string _cloudServiceName;\n \n public string CloudServiceName\n {\n get { return this._cloudServiceName; }\n set { this._cloudServiceName = value; }\n }\n \n private SubscriptionCloudCredentials _credentials;\n \n /// \n /// Gets subscription credentials which uniquely identify Microsoft\n /// Azure subscription. The subscription ID forms part of the URI for\n /// every service call.\n /// \n public SubscriptionCloudCredentials Credentials\n {\n get { return this._credentials; }\n }\n \n private int _longRunningOperationInitialTimeout;\n \n /// \n /// Gets or sets the initial timeout for Long Running Operations.\n /// \n public int LongRunningOperationInitialTimeout\n {\n get { return this._longRunningOperationInitialTimeout; }\n set { this._longRunningOperationInitialTimeout = value; }\n }\n \n private int _longRunningOperationRetryTimeout;\n \n /// \n /// Gets or sets the retry timeout for Long Running Operations.\n /// \n public int LongRunningOperationRetryTimeout\n {\n get { return this._longRunningOperationRetryTimeout; }\n set { this._longRunningOperationRetryTimeout = value; }\n }\n \n private string _resourceName;\n \n public string ResourceName\n {\n get { return this._resourceName; }\n set { this._resourceName = value; }\n }\n \n private IJobOperations _jobs;\n \n /// \n /// Definition for Job Operations.\n /// \n public virtual IJobOperations Jobs\n {\n get { return this._jobs; }\n }\n \n private INetworkMappingOperations _networkMappings;\n \n /// \n /// Definition of network mapping operations for the Site Recovery\n /// extension.\n /// \n public virtual INetworkMappingOperations NetworkMappings\n {\n get { return this._networkMappings; }\n }\n \n private INetworkOperations _networks;\n \n /// \n /// Definition of network operations for the Site Recovery extension.\n /// \n public virtual INetworkOperations Networks\n {\n get { return this._networks; }\n }\n \n private IProtectionContainerOperations _protectionContainer;\n \n /// \n /// Definition of Protection Container operations for the Site Recovery\n /// extension.\n /// \n public virtual IProtectionContainerOperations ProtectionContainer\n {\n get { return this._protectionContainer; }\n }\n \n private IProtectionEntityOperations _protectionEntity;\n \n /// \n /// Definition of protection entity operations for the Site Recovery\n /// extension.\n /// \n public virtual IProtectionEntityOperations ProtectionEntity\n {\n get { return this._protectionEntity; }\n }\n \n private IProtectionProfileOperations _protectionProfile;\n \n /// \n /// Definition of Protection Profile operations for the Site Recovery\n /// extension.\n /// \n public virtual IProtectionProfileOperations ProtectionProfile\n {\n get { return this._protectionProfile; }\n }\n \n private IRecoveryPlanOperations _recoveryPlan;\n \n /// \n /// Definition of recoveryplan operations for the Site Recovery\n /// extension.\n /// \n public virtual IRecoveryPlanOperations RecoveryPlan\n {\n get { return this._recoveryPlan; }\n }\n \n private IServerOperations _servers;\n \n /// \n /// Definition of server operations for the Site Recovery extension.\n /// \n public virtual IServerOperations Servers\n {\n get { return this._servers; }\n }\n \n private ISiteOperations _sites;\n \n /// \n /// Definition of Site operations for the Site Recovery extension.\n /// \n public virtual ISiteOperations Sites\n {\n get { return this._sites; }\n }\n \n private IStorageMappingOperations _storageMappings;\n \n /// \n /// Definition of storage mapping operations for the Site Recovery\n /// extension.\n /// \n public virtual IStorageMappingOperations StorageMappings\n {\n get { return this._storageMappings; }\n }\n \n private IStorageOperations _storages;\n \n /// \n /// Definition of storage operations for the Site Recovery extension.\n /// \n public virtual IStorageOperations Storages\n {\n get { return this._storages; }\n }\n \n private IStoragePoolMappingOperations _storagePoolMappings;\n \n /// \n /// Definition of storage pool mapping operations for the Site Recovery\n /// extension.\n /// \n public virtual IStoragePoolMappingOperations StoragePoolMappings\n {\n get { return this._storagePoolMappings; }\n }\n \n private IVaultExtendedInfoOperations _vaultExtendedInfo;\n \n /// \n /// Definition of vault extended info operations for the Site Recovery\n /// extension.\n /// \n public virtual IVaultExtendedInfoOperations VaultExtendedInfo\n {\n get { return this._vaultExtendedInfo; }\n }\n \n private IVirtualMachineGroupOperations _vmGroup;\n \n /// \n /// Definition of virtual machine operations for the Site Recovery\n /// extension.\n /// \n public virtual IVirtualMachineGroupOperations VmGroup\n {\n get { return this._vmGroup; }\n }\n \n private IVirtualMachineOperations _vm;\n \n /// \n /// Definition of virtual machine operations for the Site Recovery\n /// extension.\n /// \n public virtual IVirtualMachineOperations Vm\n {\n get { return this._vm; }\n }\n \n /// \n /// Initializes a new instance of the SiteRecoveryManagementClient\n /// class.\n /// \n public SiteRecoveryManagementClient()\n : base()\n {\n this._jobs = new JobOperations(this);\n this._networkMappings = new NetworkMappingOperations(this);\n this._networks = new NetworkOperations(this);\n this._protectionContainer = new ProtectionContainerOperations(this);\n this._protectionEntity = new ProtectionEntityOperations(this);\n this._protectionProfile = new ProtectionProfileOperations(this);\n this._recoveryPlan = new RecoveryPlanOperations(this);\n this._servers = new ServerOperations(this);\n this._sites = new SiteOperations(this);\n this._storageMappings = new StorageMappingOperations(this);\n this._storages = new StorageOperations(this);\n this._storagePoolMappings = new StoragePoolMappingOperations(this);\n this._vaultExtendedInfo = new VaultExtendedInfoOperations(this);\n this._vmGroup = new VirtualMachineGroupOperations(this);\n this._vm = new VirtualMachineOperations(this);\n this._apiVersion = \"2013-03-01\";\n this._longRunningOperationInitialTimeout = -1;\n this._longRunningOperationRetryTimeout = -1;\n this.HttpClient.Timeout = TimeSpan.FromSeconds(300);\n }\n \n /// \n /// Initializes a new instance of the SiteRecoveryManagementClient\n /// class.\n /// \n /// \n /// Required.\n /// \n /// \n /// Required.\n /// \n /// \n /// Required. Gets subscription credentials which uniquely identify\n /// Microsoft Azure subscription. The subscription ID forms part of\n /// the URI for every service call.\n /// \n /// \n /// Optional. Gets the URI used as the base for all cloud service\n /// requests.\n /// \n public SiteRecoveryManagementClient(string cloudServiceName, string resourceName, SubscriptionCloudCredentials credentials, Uri baseUri)\n : this()\n {\n if (cloudServiceName == null)\n {\n throw new ArgumentNullException(\"cloudServiceName\");\n }\n if (resourceName == null)\n {\n throw new ArgumentNullException(\"resourceName\");\n }\n if (credentials == null)\n {\n throw new ArgumentNullException(\"credentials\");\n }\n if (baseUri == null)\n {\n throw new ArgumentNullException(\"baseUri\");\n }\n this._cloudServiceName = cloudServiceName;\n this._resourceName = resourceName;\n this._credentials = credentials;\n this._baseUri = baseUri;\n \n this.Credentials.InitializeServiceClient(this);\n }\n \n /// \n /// Initializes a new instance of the SiteRecoveryManagementClient\n /// class.\n /// \n /// \n /// Required.\n /// \n /// \n /// Required.\n /// \n /// \n /// Required. Gets subscription credentials which uniquely identify\n /// Microsoft Azure subscription. The subscription ID forms part of\n /// the URI for every service call.\n /// \n public SiteRecoveryManagementClient(string cloudServiceName, string resourceName, SubscriptionCloudCredentials credentials)\n : this()\n {\n if (cloudServiceName == null)\n {\n throw new ArgumentNullException(\"cloudServiceName\");\n }\n if (resourceName == null)\n {\n throw new ArgumentNullException(\"resourceName\");\n }\n if (credentials == null)\n {\n throw new ArgumentNullException(\"credentials\");\n }\n this._cloudServiceName = cloudServiceName;\n this._resourceName = resourceName;", "answers": [" this._credentials = credentials;"], "length": 1128, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "33dd51af-a0a0-4d85-87ac-4c1f8068f592", "reasoning": "The constructor assigns the passed parameters to private fields. After setting _cloudServiceName and _resourceName, the next logical assignment is the credentials field. The pattern matches other overloads where they set this._credentials = credentials; before initializing the service client.", "reasoning_model_answer": "this._credentials = credentials;", "assistant_with_reasoning": "\nThe constructor assigns the passed parameters to private fields. After setting _cloudServiceName and _resourceName, the next logical assignment is the credentials field. The pattern matches other overloads where they set this._credentials = credentials; before initializing the service client.\n\nthis._credentials = credentials;", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.667, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 12830, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "this._credentials = credentials;", "score": 0.84, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "// Copyright (C) 2011-2012 CRS4.\n//\n// This file is part of Hadoop-BAM.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to\n// deal in the Software without restriction, including without limitation the\n// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n// sell copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n// IN THE SOFTWARE.\n\npackage org.seqdoop.hadoop_bam;\n\nimport org.seqdoop.hadoop_bam.FastqInputFormat.FastqRecordReader;\n\nimport java.io.File;\nimport java.io.IOException;\nimport java.io.PrintWriter;\nimport java.io.BufferedWriter;\nimport java.io.FileWriter;\nimport java.io.FileOutputStream;\nimport java.io.BufferedOutputStream;\n\nimport org.junit.*;\nimport static org.junit.Assert.*;\n\nimport org.apache.hadoop.mapred.JobConf;\nimport org.apache.hadoop.fs.Path;\nimport org.apache.hadoop.io.compress.GzipCodec;\nimport org.apache.hadoop.io.Text;\nimport org.apache.hadoop.mapreduce.lib.input.FileSplit;\n\npublic class TestFastqInputFormat\n{\n\tpublic static final String oneFastq =\n\t\t\"@ERR020229.10880 HWI-ST168_161:1:1:1373:2042/1\\n\" +\n\t\t\"TTGGATGATAGGGATTATTTGACTCGAATATTGGAAATAGCTGTTTATATTTTTTAAAAATGGTCTGTAACTGGTGACAGGACGCTTCGAT\\n\" +\n\t\t\"+\\n\" +\n\t\t\"###########################################################################################\";\n\n\tpublic static final String twoFastq =\n\t\t\"@ERR020229.10880 HWI-ST168_161:1:1:1373:2042/1\\n\" +\n\t\t\"TTGGATGATAGGGATTATTTGACTCGAATATTGGAAATAGCTGTTTATATTTTTTAAAAATGGTCTGTAACTGGTGACAGGACGCTTCGAT\\n\" +\n\t\t\"+\\n\" +\n\t\t\"###########################################################################################\\n\" +\n\n\t\t\"@ERR020229.10883 HWI-ST168_161:1:1:1796:2044/1\\n\" +\n\t\t\"TGAGCAGATGTGCTAAAGCTGCTTCTCCCCTAGGATCATTTGTACCTACCAGACTCAGGGAAAGGGGTGAGAATTGGGCCGTGGGGCAAGG\\n\" +\n\t\t\"+\\n\" +\n\t\t\"BDDCDBDD?A=?=:=7,7*@A;;53/53.:@>@@4=>@@@=?1?###############################################\";\n\n\tpublic static final String illuminaFastq =\n\t\t\"@EAS139:136:FC706VJ:2:5:1000:12850 1:Y:18:ATCACG\\n\" +\n\t\t\"TTGGATGATAGGGATTATTTGACTCGAATATTGGAAATAGCTGTTTATATTTTTTAAAAATGGTCTGTAACTGGTGACAGGACGCTTCGAT\\n\" +\n\t\t\"+\\n\" +\n\t\t\"##########################################################################################~\";\n\n\tpublic static final String illuminaFastqWithPhred64Quality =\n\t\t\"@EAS139:136:FC706VJ:2:5:1000:12850 1:Y:18:ATCACG\\n\" +\n\t\t\"TTGGATGATAGGGATTATTTGACTCGAATATTGGAAATAGCTGTTTATATTTTTTAAAAATGGTCTGTAACTGGTGACAGGACGCTTCGAT\\n\" +\n\t\t\"+\\n\" +\n\t\t\"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\";\n\n\tpublic static final String oneFastqWithoutRead =\n\t\t\"@ERR020229.10880 HWI-ST168_161:1:1:1373:2042\\n\" +\n\t\t\"TTGGATGATAGGGATTATTTGACTCGAATATTGGAAATAGCTGTTTATATTTTTTAAAAATGGTCTGTAACTGGTGACAGGACGCTTCGAT\\n\" +\n\t\t\"+\\n\" +\n\t\t\"###########################################################################################\";\n\n\tpublic static final String fastqWithIdTwice =\n\t\t\"@ERR020229.10880 HWI-ST168_161:1:1:1373:2042/1\\n\" +\n\t\t\"TTGGATGATAGGGATTATTTGACTCGAATATTGGAAATAGCTGTTTATATTTTTTAAAAATGGTCTGTAACTGGTGACAGGACGCTTCGAT\\n\" +\n\t\t\"+ERR020229.10880 HWI-ST168_161:1:1:1373:2042/1\\n\" +\n\t\t\"###########################################################################################\";\n\n\tpublic static final String fastqWithAmpersandQuality =\n\t\t\"+lousy.id HWI-ST168_161:1:1:1373:2042/1\\n\" +\n\t\t\"@##########################################################################################\\n\" +\n\t\t\"@ERR020229.10880 HWI-ST168_161:1:1:1373:2042/1\\n\" +\n\t\t\"TTGGATGATAGGGATTATTTGACTCGAATATTGGAAATAGCTGTTTATATTTTTTAAAAATGGTCTGTAACTGGTGACAGGACGCTTCGAT\\n\" +\n\t\t\"+ERR020229.10880 HWI-ST168_161:1:1:1373:2042/1\\n\" +\n\t\t\"###########################################################################################\";\n\n\tpublic static final String illuminaFastqNoFlowCellID =\n\t \"@EAS139:136::2:5:1000:12850 1:Y:18:ATCACG\\n\" +\n\t \"TTGGATGATAGGGATTATTTGACTCGAATATTGGAAATAGCTGTTTATATTTTTTAAAAATGGTCTGTAACTGGTGACAGGACGCTTCGAT\\n\" +\n\t \"+\\n\" +\n\t \"###########################################################################################\";\n\n\tpublic static final String illuminaFastqNegativeXYPos =\n\t \"@EAS139:136:FC706VJ:2:5:-1000:-12850 1:Y:18:ATCACG\\n\" +\n\t \"TTGGATGATAGGGATTATTTGACTCGAATATTGGAAATAGCTGTTTATATTTTTTAAAAATGGTCTGTAACTGGTGACAGGACGCTTCGAT\\n\" +\n\t \"+\\n\" +\n\t \"###########################################################################################\";\n\n\tpublic static final String illuminaFastqNoIndex =\n\t \"@EAS139:136::2:5:1000:12850 1:Y:18:\\n\" +\n\t \"TTGGATGATAGGGATTATTTGACTCGAATATTGGAAATAGCTGTTTATATTTTTTAAAAATGGTCTGTAACTGGTGACAGGACGCTTCGAT\\n\" +\n\t \"+\\n\" +\n\t \"###########################################################################################\";\n\n\tpublic static final String twoFastqWithIllumina =\n\t\t\"@EAS139:136:FC706VJ:2:5:1000:12850 1:Y:18:ATCACG\\n\" +\n\t\t\"TTGGATGATAGGGATTATTTGACTCGAATATTGGAAATAGCTGTTTATATTTTTTAAAAATGGTCTGTAACTGGTGACAGGACGCTTCGAT\\n\" +\n\t\t\"+\\n\" +\n\t\t\"###########################################################################################\\n\" +\n\n\t\t\"@EAS139:136:FC706VJ:2:5:1000:12850 2:N:18:ATCACG\\n\" +\n\t\t\"TTGGATGATAGGGATTATTTGACTCGAATATTGGAAATAGCTGTTTATATTTTTTAAAAATGGTCTGTAACTGGTGACAGGACGCTTCGAT\\n\" +\n\t\t\"+\\n\" +\n\t\t\"###########################################################################################\\n\" +\n\n\t\t\"@EAS139:136:FC706VJ:2:5:1000:12850 3:N:18:ATCACG\\n\" +\n\t\t\"TGAGCAGATGTGCTAAAGCTGCTTCTCCCCTAGGATCATTTGTACCTACCAGACTCAGGGAAAGGGGTGAGAATTGGGCCGTGGGGCAAGG\\n\" +\n\t\t\"+\\n\" +\n\t\t\"BDDCDBDD?A=?=:=7,7*@A;;53/53.:@>@@4=>@@@=?1?###############################################\";\n\n\tprivate JobConf conf;\n\tprivate FileSplit split;\n\tprivate File tempFastq;\n\tprivate File tempGz;\n\n\tprivate Text key;\n\tprivate SequencedFragment fragment;\n\n\t@Before\n\tpublic void setup() throws IOException\n\t{\n\t\ttempFastq = File.createTempFile(\"test_fastq_input_format\", \"fastq\");\n\t\ttempGz = File.createTempFile(\"test_fastq_input_format\", \".gz\");\n\t\tconf = new JobConf();\n\t\tkey = new Text();\n\t\tfragment = new SequencedFragment();\n\t}\n\n\t@After\n\tpublic void tearDown()\n\t{\n\t\ttempFastq.delete();\n\t\ttempGz.delete();\n\t\tsplit = null;\n\t}\n\n\tprivate void writeToTempFastq(String s) throws IOException\n\t{\n\t\tPrintWriter fastqOut = new PrintWriter( new BufferedWriter( new FileWriter(tempFastq) ) );\n\t\tfastqOut.write(s);\n\t\tfastqOut.close();\n\t}\n\n\tprivate FastqRecordReader createReaderForOneFastq() throws IOException\n\t{\n\t\twriteToTempFastq(oneFastq);\n\t\tsplit = new FileSplit(new Path(tempFastq.toURI().toString()), 0, oneFastq.length(), null);\n\n\t\treturn new FastqRecordReader(conf, split);\n\t}\n\n\t@Test\n\tpublic void testReadFromStart() throws IOException\n\t{\n\t\tFastqRecordReader reader = createReaderForOneFastq();\n\n\t\tassertEquals(0, reader.getPos());\n\t\tassertEquals(0.0, reader.getProgress(), 0.01);\n\n\t\tboolean retval = reader.next(key, fragment);\n\t\tassertTrue(retval);\n\t\tassertEquals(\"ERR020229.10880 HWI-ST168_161:1:1:1373:2042/1\", key.toString());\n\t\tassertEquals(\"TTGGATGATAGGGATTATTTGACTCGAATATTGGAAATAGCTGTTTATATTTTTTAAAAATGGTCTGTAACTGGTGACAGGACGCTTCGAT\", fragment.getSequence().toString());\n\t\tassertEquals(\"###########################################################################################\", fragment.getQuality().toString());\n\n\t\tassertEquals(oneFastq.length(), reader.getPos());\n\t\tassertEquals(1.0, reader.getProgress(), 0.01);\n\n\t\tretval = reader.next(key, fragment);\n\t\tassertFalse(retval);\n\t}\n\n\t@Test\n\tpublic void testReadStartInMiddle() throws IOException\n\t{\n\t\twriteToTempFastq(twoFastq);\n\t\tsplit = new FileSplit(new Path(tempFastq.toURI().toString()), 10, twoFastq.length() - 10, null);\n\n\t\tFastqRecordReader reader = new FastqRecordReader(conf, split);\n\n\t\tassertEquals(oneFastq.length() + 1, reader.getPos()); // The start of the second record. We +1 for the \\n that is not in oneFastq\n\t\tassertEquals(0.0, reader.getProgress(), 0.01);\n\n\t\tboolean retval = reader.next(key, fragment);\n\t\tassertTrue(retval);\n\t\tassertEquals(\"ERR020229.10883 HWI-ST168_161:1:1:1796:2044/1\", key.toString());\n\t\tassertEquals(\"TGAGCAGATGTGCTAAAGCTGCTTCTCCCCTAGGATCATTTGTACCTACCAGACTCAGGGAAAGGGGTGAGAATTGGGCCGTGGGGCAAGG\", fragment.getSequence().toString());\n\t\tassertEquals(\"BDDCDBDD?A=?=:=7,7*@A;;53/53.:@>@@4=>@@@=?1?###############################################\", fragment.getQuality().toString());\n\n\t\tassertEquals(twoFastq.length(), reader.getPos()); // now should be at the end of the data\n\t\tassertEquals(1.0, reader.getProgress(), 0.01);\n\n\t\tretval = reader.next(key, fragment);\n\t\tassertFalse(retval);\n\t}\n\n\t@Test\n\tpublic void testSliceEndsBeforeEndOfFile() throws IOException\n\t{\n\t\twriteToTempFastq(twoFastq);\n\t\t// slice ends at position 10--i.e. somewhere in the first record. The second record should not be read.\n\t\tsplit = new FileSplit(new Path(tempFastq.toURI().toString()), 0, 10, null);\n\n\t\tFastqRecordReader reader = new FastqRecordReader(conf, split);\n\n\t\tboolean retval = reader.next(key, fragment);\n\t\tassertTrue(retval);\n\t\tassertEquals(\"ERR020229.10880 HWI-ST168_161:1:1:1373:2042/1\", key.toString());\n\n\t\tassertFalse(\"FastqRecordReader is reading a record that starts after the end of the slice\", reader.next(key, fragment));\n\t}\n\n\t@Test\n\tpublic void testGetReadNumFromName() throws IOException\n\t{\n\t\tFastqRecordReader reader = createReaderForOneFastq();\n\t\tboolean retval = reader.next(key, fragment);\n\t\tassertTrue(retval);\n\t\tassertEquals(1, fragment.getRead().intValue());\n\t}\n\n\t@Test\n\tpublic void testNameWithoutReadNum() throws IOException\n\t{\n\t\twriteToTempFastq(oneFastqWithoutRead);\n\t\tsplit = new FileSplit(new Path(tempFastq.toURI().toString()), 0, oneFastqWithoutRead.length(), null);\n\n\t\tFastqRecordReader reader = new FastqRecordReader(conf, split);\n\t\tboolean retval = reader.next(key, fragment);\n\t\tassertTrue(retval);\n\t\tassertNull(\"Read is not null\", fragment.getRead());\n\t}\n\n\t@Test\n\tpublic void testIlluminaMetaInfo() throws IOException\n\t{\n\t\twriteToTempFastq(illuminaFastq);\n\t\tsplit = new FileSplit(new Path(tempFastq.toURI().toString()), 0, illuminaFastq.length(), null);\n\n\t\tFastqRecordReader reader = new FastqRecordReader(conf, split);\n\t\tboolean found = reader.next(key, fragment);\n\t\tassertTrue(found);\n\n\t\tassertEquals(\"EAS139\", fragment.getInstrument());\n\t\tassertEquals(136, fragment.getRunNumber().intValue());\n\t\tassertEquals(\"FC706VJ\", fragment.getFlowcellId());\n\t\tassertEquals(2, fragment.getLane().intValue());\n\t\tassertEquals(5, fragment.getTile().intValue());\n\t\tassertEquals(1000, fragment.getXpos().intValue());\n\t\tassertEquals(12850, fragment.getYpos().intValue());\n\t\tassertEquals(1, fragment.getRead().intValue());\n\t\tassertEquals(false, fragment.getFilterPassed().booleanValue());\n\t\tassertEquals(18, fragment.getControlNumber().intValue());\n\t\tassertEquals(\"ATCACG\", fragment.getIndexSequence());\n\t}\n\n\t@Test\n\tpublic void testIlluminaMetaInfoNullFC() throws IOException\n\t{\n\t\twriteToTempFastq(illuminaFastqNoFlowCellID);\n\t\tsplit = new FileSplit(new Path(tempFastq.toURI().toString()), 0, illuminaFastqNoFlowCellID.length(), null);\n\n\t\tFastqRecordReader reader = new FastqRecordReader(conf, split);\n\t\tboolean found = reader.next(key, fragment);\n\t\tassertTrue(found);\n\n\t\tassertEquals(\"EAS139\", fragment.getInstrument());\n\t\tassertEquals(136, fragment.getRunNumber().intValue());\n\t\tassertEquals(\"\", fragment.getFlowcellId());\n\t\tassertEquals(2, fragment.getLane().intValue());\n\t\tassertEquals(5, fragment.getTile().intValue());\n\t\tassertEquals(1000, fragment.getXpos().intValue());\n\t\tassertEquals(12850, fragment.getYpos().intValue());\n\t\tassertEquals(1, fragment.getRead().intValue());\n\t\tassertEquals(false, fragment.getFilterPassed().booleanValue());\n\t\tassertEquals(18, fragment.getControlNumber().intValue());\n\t\tassertEquals(\"ATCACG\", fragment.getIndexSequence());\n\t}\n\n\t@Test\n\tpublic void testIlluminaMetaInfoNegativeXYpos() throws IOException\n\t{\n\t\twriteToTempFastq(illuminaFastqNegativeXYPos);\n\t\tsplit = new FileSplit(new Path(tempFastq.toURI().toString()), 0, illuminaFastqNegativeXYPos.length(), null);\n\n\t\tFastqRecordReader reader = new FastqRecordReader(conf, split);\n\t\tboolean found = reader.next(key, fragment);\n\t\tassertTrue(found);\n\n\t\tassertEquals(\"EAS139\", fragment.getInstrument());\n\t\tassertEquals(136, fragment.getRunNumber().intValue());\n\t\tassertEquals(\"FC706VJ\", fragment.getFlowcellId());\n\t\tassertEquals(2, fragment.getLane().intValue());\n\t\tassertEquals(5, fragment.getTile().intValue());\n\t\tassertEquals(-1000, fragment.getXpos().intValue());\n\t\tassertEquals(-12850, fragment.getYpos().intValue());\n\t\tassertEquals(1, fragment.getRead().intValue());\n\t\tassertEquals(false, fragment.getFilterPassed().booleanValue());\n\t\tassertEquals(18, fragment.getControlNumber().intValue());\n\t\tassertEquals(\"ATCACG\", fragment.getIndexSequence());\n\t}\n\n\t@Test\n\tpublic void testOneIlluminaThenNot() throws IOException\n\t{\n\t\twriteToTempFastq(illuminaFastq + \"\\n\" + oneFastq);\n\t\tsplit = new FileSplit(new Path(tempFastq.toURI().toString()), 0, illuminaFastq.length() + oneFastq.length() + 1, null);\n\n\t\tFastqRecordReader reader = new FastqRecordReader(conf, split);\n\n\t\tassertTrue(reader.next(key, fragment));\n\t\tassertEquals(\"EAS139\", fragment.getInstrument());\n\n\t\tassertTrue(reader.next(key, fragment));\n\t\tassertNull(fragment.getInstrument());\n\n\t\tassertFalse(reader.next(key, fragment));\n\t}\n\n\t@Test\n\tpublic void testOneNotThenIllumina() throws IOException\n\t{\n\t\twriteToTempFastq(oneFastq + \"\\n\" + illuminaFastq);\n\t\tsplit = new FileSplit(new Path(tempFastq.toURI().toString()), 0, illuminaFastq.length() + oneFastq.length() + 1, null);\n\n\t\tFastqRecordReader reader = new FastqRecordReader(conf, split);\n\n\t\tassertTrue(reader.next(key, fragment));\n\t\tassertNull(fragment.getInstrument());\n\n\t\tassertTrue(reader.next(key, fragment));\n\t\tassertNull(fragment.getInstrument());\n\n\t\tassertFalse(reader.next(key, fragment));\n\t}\n\n\t@Test\n\tpublic void testProgress() throws IOException\n\t{\n\t\twriteToTempFastq(twoFastq);\n\t\tsplit = new FileSplit(new Path(tempFastq.toURI().toString()), 0, twoFastq.length(), null);\n\n\t\tFastqRecordReader reader = new FastqRecordReader(conf, split);\n\t\tassertEquals(0.0, reader.getProgress(), 0.01);\n\n\t\treader.next(key, fragment);\n\t\tassertEquals(0.5, reader.getProgress(), 0.01);\n\n\t\treader.next(key, fragment);\n\t\tassertEquals(1.0, reader.getProgress(), 0.01);\n\t}\n\n\t@Test\n\tpublic void testCreateKey() throws IOException\n\t{", "answers": ["\t\tFastqRecordReader reader = createReaderForOneFastq();"], "length": 1037, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "749d9838-b835-4227-bd11-eeb3d932def6", "reasoning": "Inside the new test method testCreateKey, the first operation will be to obtain a FastqRecordReader for a known FASTQ input. The class already provides a helper method createReaderForOneFastq() that sets up the temporary file and returns a FastqRecordReader. Therefore the next line should call this helper and assign the result to a variable.", "reasoning_model_answer": "FastqRecordReader reader = createReaderForOneFastq();", "assistant_with_reasoning": "\nInside the new test method testCreateKey, the first operation will be to obtain a FastqRecordReader for a known FASTQ input. The class already provides a helper method createReaderForOneFastq() that sets up the temporary file and returns a FastqRecordReader. Therefore the next line should call this helper and assign the result to a variable.\n\nFastqRecordReader reader = createReaderForOneFastq();", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 5.988, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 14952, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "FastqRecordReader reader = createReaderForOneFastq();", "score": 0.98, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/*\n * ProGuard -- shrinking, optimization, obfuscation, and preverification\n * of Java bytecode.\n *\n * Copyright (c) 2002-2017 Eric Lafortune @ GuardSquare\n *\n * This program is free software; you can redistribute it and/or modify it\n * under the terms of the GNU General Public License as published by the Free\n * Software Foundation; either version 2 of the License, or (at your option)\n * any later version.\n *\n * This program is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for\n * more details.\n *\n * You should have received a copy of the GNU General Public License along\n * with this program; if not, write to the Free Software Foundation, Inc.,\n * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n */\npackage proguard.classfile.editor;\n\nimport proguard.classfile.*;\nimport proguard.classfile.attribute.*;\nimport proguard.classfile.attribute.annotation.*;\nimport proguard.classfile.attribute.annotation.visitor.*;\nimport proguard.classfile.attribute.preverification.*;\nimport proguard.classfile.attribute.preverification.visitor.*;\nimport proguard.classfile.attribute.visitor.*;\nimport proguard.classfile.constant.*;\nimport proguard.classfile.constant.visitor.ConstantVisitor;\nimport proguard.classfile.instruction.*;\nimport proguard.classfile.instruction.visitor.InstructionVisitor;\nimport proguard.classfile.util.SimplifiedVisitor;\nimport proguard.classfile.visitor.*;\n\n/**\n * This ClassVisitor remaps all possible references to constant pool entries\n * of the classes that it visits, based on a given index map. It is assumed that\n * the constant pool entries themselves have already been remapped.\n *\n * @author Eric Lafortune\n */\npublic class ConstantPoolRemapper\nextends SimplifiedVisitor\nimplements ClassVisitor,\n ConstantVisitor,\n MemberVisitor,\n AttributeVisitor,\n BootstrapMethodInfoVisitor,\n InnerClassesInfoVisitor,\n ExceptionInfoVisitor,\n InstructionVisitor,\n StackMapFrameVisitor,\n VerificationTypeVisitor,\n ParameterInfoVisitor,\n LocalVariableInfoVisitor,\n LocalVariableTypeInfoVisitor,\n AnnotationVisitor,\n ElementValueVisitor\n{\n private final CodeAttributeEditor codeAttributeEditor = new CodeAttributeEditor(false, true);\n\n private int[] constantIndexMap;\n\n\n /**\n * Sets the given mapping of old constant pool entry indexes to their new\n * indexes.\n */\n public void setConstantIndexMap(int[] constantIndexMap)\n {\n this.constantIndexMap = constantIndexMap;\n }\n\n\n // Implementations for ClassVisitor.\n\n public void visitProgramClass(ProgramClass programClass)\n {\n // Remap the local constant pool references.\n programClass.u2thisClass = remapConstantIndex(programClass.u2thisClass);\n programClass.u2superClass = remapConstantIndex(programClass.u2superClass);\n\n remapConstantIndexArray(programClass.u2interfaces,\n programClass.u2interfacesCount);\n\n // Remap the references of the contant pool entries themselves.\n programClass.constantPoolEntriesAccept(this);\n\n // Remap the references in all fields, methods, and attributes.\n programClass.fieldsAccept(this);\n programClass.methodsAccept(this);\n programClass.attributesAccept(this);\n }\n\n\n public void visitLibraryClass(LibraryClass libraryClass)\n {\n }\n\n\n // Implementations for ConstantVisitor.\n\n public void visitIntegerConstant(Clazz clazz, IntegerConstant integerConstant)\n {\n // Nothing to do.\n }\n\n\n public void visitLongConstant(Clazz clazz, LongConstant longConstant)\n {\n // Nothing to do.\n }\n\n\n public void visitFloatConstant(Clazz clazz, FloatConstant floatConstant)\n {\n // Nothing to do.\n }\n\n\n public void visitDoubleConstant(Clazz clazz, DoubleConstant doubleConstant)\n {\n // Nothing to do.\n }\n\n\n public void visitStringConstant(Clazz clazz, StringConstant stringConstant)\n {\n stringConstant.u2stringIndex =\n remapConstantIndex(stringConstant.u2stringIndex);\n }\n\n\n public void visitUtf8Constant(Clazz clazz, Utf8Constant utf8Constant)\n {\n // Nothing to do.\n }\n\n\n public void visitInvokeDynamicConstant(Clazz clazz, InvokeDynamicConstant invokeDynamicConstant)\n {\n invokeDynamicConstant.u2nameAndTypeIndex =\n remapConstantIndex(invokeDynamicConstant.u2nameAndTypeIndex);\n }\n\n\n public void visitMethodHandleConstant(Clazz clazz, MethodHandleConstant methodHandleConstant)\n {\n methodHandleConstant.u2referenceIndex =\n remapConstantIndex(methodHandleConstant.u2referenceIndex);\n }\n\n\n public void visitFieldrefConstant(Clazz clazz, FieldrefConstant fieldrefConstant)\n {\n fieldrefConstant.u2classIndex =\n remapConstantIndex(fieldrefConstant.u2classIndex);\n fieldrefConstant.u2nameAndTypeIndex =\n remapConstantIndex(fieldrefConstant.u2nameAndTypeIndex);\n }\n\n\n public void visitInterfaceMethodrefConstant(Clazz clazz, InterfaceMethodrefConstant interfaceMethodrefConstant)\n {\n interfaceMethodrefConstant.u2classIndex =\n remapConstantIndex(interfaceMethodrefConstant.u2classIndex);\n interfaceMethodrefConstant.u2nameAndTypeIndex =\n remapConstantIndex(interfaceMethodrefConstant.u2nameAndTypeIndex);\n }\n\n\n public void visitMethodrefConstant(Clazz clazz, MethodrefConstant methodrefConstant)\n {\n methodrefConstant.u2classIndex =\n remapConstantIndex(methodrefConstant.u2classIndex);\n methodrefConstant.u2nameAndTypeIndex =\n remapConstantIndex(methodrefConstant.u2nameAndTypeIndex);\n }\n\n\n public void visitClassConstant(Clazz clazz, ClassConstant classConstant)\n {\n classConstant.u2nameIndex =\n remapConstantIndex(classConstant.u2nameIndex);\n }\n\n\n public void visitMethodTypeConstant(Clazz clazz, MethodTypeConstant methodTypeConstant)\n {\n methodTypeConstant.u2descriptorIndex =\n remapConstantIndex(methodTypeConstant.u2descriptorIndex);\n }\n\n\n public void visitNameAndTypeConstant(Clazz clazz, NameAndTypeConstant nameAndTypeConstant)\n {\n nameAndTypeConstant.u2nameIndex =\n remapConstantIndex(nameAndTypeConstant.u2nameIndex);\n nameAndTypeConstant.u2descriptorIndex =\n remapConstantIndex(nameAndTypeConstant.u2descriptorIndex);\n }\n\n\n // Implementations for MemberVisitor.\n\n public void visitProgramField(ProgramClass programClass, ProgramField programField)\n {\n visitMember(programClass, programField);\n }\n\n\n public void visitProgramMethod(ProgramClass programClass, ProgramMethod programMethod)\n {\n visitMember(programClass, programMethod);\n }\n\n\n private void visitMember(ProgramClass programClass, ProgramMember programMember)\n {\n // Remap the local constant pool references.\n programMember.u2nameIndex =\n remapConstantIndex(programMember.u2nameIndex);\n programMember.u2descriptorIndex =\n remapConstantIndex(programMember.u2descriptorIndex);\n\n // Remap the constant pool references of the remaining attributes.\n programMember.attributesAccept(programClass, this);\n }\n\n\n public void visitLibraryField(LibraryClass libraryClass, LibraryField libraryField)\n {\n // Library classes are left unchanged.\n }\n\n\n public void visitLibraryMethod(LibraryClass libraryClass, LibraryMethod libraryMethod)\n {\n // Library classes are left unchanged.\n }\n\n\n // Implementations for AttributeVisitor.\n\n public void visitUnknownAttribute(Clazz clazz, UnknownAttribute unknownAttribute)\n {\n unknownAttribute.u2attributeNameIndex =\n remapConstantIndex(unknownAttribute.u2attributeNameIndex);\n\n // There's not much else we can do with unknown attributes.\n }\n\n\n public void visitBootstrapMethodsAttribute(Clazz clazz, BootstrapMethodsAttribute bootstrapMethodsAttribute)\n {\n bootstrapMethodsAttribute.u2attributeNameIndex =\n remapConstantIndex(bootstrapMethodsAttribute.u2attributeNameIndex);\n\n // Remap the constant pool references of the bootstrap method entries.\n bootstrapMethodsAttribute.bootstrapMethodEntriesAccept(clazz, this);\n }\n\n\n public void visitSourceFileAttribute(Clazz clazz, SourceFileAttribute sourceFileAttribute)\n {\n sourceFileAttribute.u2attributeNameIndex =\n remapConstantIndex(sourceFileAttribute.u2attributeNameIndex);\n sourceFileAttribute.u2sourceFileIndex =\n remapConstantIndex(sourceFileAttribute.u2sourceFileIndex);\n }\n\n\n public void visitSourceDirAttribute(Clazz clazz, SourceDirAttribute sourceDirAttribute)\n {\n sourceDirAttribute.u2attributeNameIndex =\n remapConstantIndex(sourceDirAttribute.u2attributeNameIndex);\n sourceDirAttribute.u2sourceDirIndex =\n remapConstantIndex(sourceDirAttribute.u2sourceDirIndex);\n }\n\n\n public void visitInnerClassesAttribute(Clazz clazz, InnerClassesAttribute innerClassesAttribute)\n {\n innerClassesAttribute.u2attributeNameIndex =\n remapConstantIndex(innerClassesAttribute.u2attributeNameIndex);\n\n // Remap the constant pool references of the inner classes.\n innerClassesAttribute.innerClassEntriesAccept(clazz, this);\n }\n\n\n public void visitEnclosingMethodAttribute(Clazz clazz, EnclosingMethodAttribute enclosingMethodAttribute)\n {\n enclosingMethodAttribute.u2attributeNameIndex =\n remapConstantIndex(enclosingMethodAttribute.u2attributeNameIndex);\n enclosingMethodAttribute.u2classIndex =\n remapConstantIndex(enclosingMethodAttribute.u2classIndex);\n enclosingMethodAttribute.u2nameAndTypeIndex =\n remapConstantIndex(enclosingMethodAttribute.u2nameAndTypeIndex);\n }\n\n\n public void visitDeprecatedAttribute(Clazz clazz, DeprecatedAttribute deprecatedAttribute)\n {\n deprecatedAttribute.u2attributeNameIndex =\n remapConstantIndex(deprecatedAttribute.u2attributeNameIndex);\n }\n\n\n public void visitSyntheticAttribute(Clazz clazz, SyntheticAttribute syntheticAttribute)\n {\n syntheticAttribute.u2attributeNameIndex =\n remapConstantIndex(syntheticAttribute.u2attributeNameIndex);\n }\n\n\n public void visitSignatureAttribute(Clazz clazz, SignatureAttribute signatureAttribute)\n {\n signatureAttribute.u2attributeNameIndex =\n remapConstantIndex(signatureAttribute.u2attributeNameIndex);\n signatureAttribute.u2signatureIndex =\n remapConstantIndex(signatureAttribute.u2signatureIndex);\n }\n\n\n public void visitConstantValueAttribute(Clazz clazz, Field field, ConstantValueAttribute constantValueAttribute)\n {\n constantValueAttribute.u2attributeNameIndex =\n remapConstantIndex(constantValueAttribute.u2attributeNameIndex);\n constantValueAttribute.u2constantValueIndex =\n remapConstantIndex(constantValueAttribute.u2constantValueIndex);\n }\n\n\n public void visitMethodParametersAttribute(Clazz clazz, Method method, MethodParametersAttribute methodParametersAttribute)\n {\n methodParametersAttribute.u2attributeNameIndex =\n remapConstantIndex(methodParametersAttribute.u2attributeNameIndex);\n\n // Remap the constant pool references of the parameter information.\n methodParametersAttribute.parametersAccept(clazz, method, this);\n }\n\n\n public void visitExceptionsAttribute(Clazz clazz, Method method, ExceptionsAttribute exceptionsAttribute)\n {\n exceptionsAttribute.u2attributeNameIndex =\n remapConstantIndex(exceptionsAttribute.u2attributeNameIndex);\n\n // Remap the constant pool references of the exceptions.\n remapConstantIndexArray(exceptionsAttribute.u2exceptionIndexTable,\n exceptionsAttribute.u2exceptionIndexTableLength);\n }\n\n\n public void visitCodeAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute)\n {\n codeAttribute.u2attributeNameIndex =\n remapConstantIndex(codeAttribute.u2attributeNameIndex);\n\n // Initially, the code attribute editor doesn't contain any changes.\n codeAttributeEditor.reset(codeAttribute.u4codeLength);\n\n // Remap the constant pool references of the instructions.\n codeAttribute.instructionsAccept(clazz, method, this);\n\n // Apply the code atribute editor. It will only contain any changes if\n // the code length is changing at any point.\n codeAttributeEditor.visitCodeAttribute(clazz, method, codeAttribute);\n\n // Remap the constant pool references of the exceptions and attributes.\n codeAttribute.exceptionsAccept(clazz, method, this);\n codeAttribute.attributesAccept(clazz, method, this);\n }\n\n\n public void visitStackMapAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute, StackMapAttribute stackMapAttribute)\n {\n stackMapAttribute.u2attributeNameIndex =\n remapConstantIndex(stackMapAttribute.u2attributeNameIndex);\n\n // Remap the constant pool references of the stack map frames.\n stackMapAttribute.stackMapFramesAccept(clazz, method, codeAttribute, this);\n }\n\n\n public void visitStackMapTableAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute, StackMapTableAttribute stackMapTableAttribute)\n {\n stackMapTableAttribute.u2attributeNameIndex =\n remapConstantIndex(stackMapTableAttribute.u2attributeNameIndex);\n\n // Remap the constant pool references of the stack map frames.\n stackMapTableAttribute.stackMapFramesAccept(clazz, method, codeAttribute, this);\n }\n\n\n public void visitLineNumberTableAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute, LineNumberTableAttribute lineNumberTableAttribute)\n {\n lineNumberTableAttribute.u2attributeNameIndex =\n remapConstantIndex(lineNumberTableAttribute.u2attributeNameIndex);\n }\n\n\n public void visitLocalVariableTableAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute, LocalVariableTableAttribute localVariableTableAttribute)\n {\n localVariableTableAttribute.u2attributeNameIndex =\n remapConstantIndex(localVariableTableAttribute.u2attributeNameIndex);\n\n // Remap the constant pool references of the local variables.\n localVariableTableAttribute.localVariablesAccept(clazz, method, codeAttribute, this);\n }\n\n\n public void visitLocalVariableTypeTableAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute, LocalVariableTypeTableAttribute localVariableTypeTableAttribute)\n {\n localVariableTypeTableAttribute.u2attributeNameIndex =\n remapConstantIndex(localVariableTypeTableAttribute.u2attributeNameIndex);\n\n // Remap the constant pool references of the local variables.\n localVariableTypeTableAttribute.localVariablesAccept(clazz, method, codeAttribute, this);\n }\n\n\n public void visitAnyAnnotationsAttribute(Clazz clazz, AnnotationsAttribute annotationsAttribute)\n {\n annotationsAttribute.u2attributeNameIndex =\n remapConstantIndex(annotationsAttribute.u2attributeNameIndex);\n\n // Remap the constant pool references of the annotations.\n annotationsAttribute.annotationsAccept(clazz, this);\n }\n\n\n public void visitAnyParameterAnnotationsAttribute(Clazz clazz, Method method, ParameterAnnotationsAttribute parameterAnnotationsAttribute)\n {\n parameterAnnotationsAttribute.u2attributeNameIndex =\n remapConstantIndex(parameterAnnotationsAttribute.u2attributeNameIndex);\n\n // Remap the constant pool references of the annotations.\n parameterAnnotationsAttribute.annotationsAccept(clazz, method, this);\n }\n\n\n public void visitAnnotationDefaultAttribute(Clazz clazz, Method method, AnnotationDefaultAttribute annotationDefaultAttribute)\n {\n annotationDefaultAttribute.u2attributeNameIndex =\n remapConstantIndex(annotationDefaultAttribute.u2attributeNameIndex);\n\n // Remap the constant pool references of the annotations.\n annotationDefaultAttribute.defaultValueAccept(clazz, this);\n }\n\n\n // Implementations for BootstrapMethodInfoVisitor.\n\n public void visitBootstrapMethodInfo(Clazz clazz, BootstrapMethodInfo bootstrapMethodInfo)\n {\n bootstrapMethodInfo.u2methodHandleIndex =\n remapConstantIndex(bootstrapMethodInfo.u2methodHandleIndex);\n\n // Remap the constant pool references of the bootstrap methods..\n remapConstantIndexArray(bootstrapMethodInfo.u2methodArguments,\n bootstrapMethodInfo.u2methodArgumentCount);\n }\n\n\n // Implementations for InnerClassesInfoVisitor.\n\n public void visitInnerClassesInfo(Clazz clazz, InnerClassesInfo innerClassesInfo)\n {\n if (innerClassesInfo.u2innerClassIndex != 0)\n {\n innerClassesInfo.u2innerClassIndex =\n remapConstantIndex(innerClassesInfo.u2innerClassIndex);\n }\n\n if (innerClassesInfo.u2outerClassIndex != 0)\n {\n innerClassesInfo.u2outerClassIndex =\n remapConstantIndex(innerClassesInfo.u2outerClassIndex);\n }\n\n if (innerClassesInfo.u2innerNameIndex != 0)\n {\n innerClassesInfo.u2innerNameIndex =\n remapConstantIndex(innerClassesInfo.u2innerNameIndex);\n }\n }\n\n\n // Implementations for ExceptionInfoVisitor.\n\n public void visitExceptionInfo(Clazz clazz, Method method, CodeAttribute codeAttribute, ExceptionInfo exceptionInfo)\n {\n if (exceptionInfo.u2catchType != 0)\n {\n exceptionInfo.u2catchType =\n remapConstantIndex(exceptionInfo.u2catchType);\n }\n }\n\n\n // Implementations for InstructionVisitor.\n\n public void visitAnyInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, Instruction instruction) {}\n\n\n public void visitConstantInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, ConstantInstruction constantInstruction)\n {\n // Is the new constant pool index different from the original one?\n int newConstantIndex = remapConstantIndex(constantInstruction.constantIndex);\n if (newConstantIndex != constantInstruction.constantIndex)\n {\n // Replace the instruction.\n Instruction replacementInstruction =\n new ConstantInstruction(constantInstruction.opcode,\n newConstantIndex,\n constantInstruction.constant);\n\n codeAttributeEditor.replaceInstruction(offset, replacementInstruction);\n }\n }\n\n\n // Implementations for StackMapFrameVisitor.\n\n public void visitAnyStackMapFrame(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, StackMapFrame stackMapFrame) {}\n\n", "answers": [" public void visitSameOneFrame(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, SameOneFrame sameOneFrame)"], "length": 1279, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "428b828d-cc02-4171-8757-63b1fb892e32", "reasoning": "The class ConstantPoolRemapper implements StackMapFrameVisitor. After the generic visitAnyStackMapFrame method, the next visitor method defined is for a specific frame type, typically visitSameFrame, which usually has an empty body because SameFrame contains no constant pool references. Following the file’s indentation and signature style, the next line should be the definition of visitSameFrame with an empty body.", "reasoning_model_answer": "public void visitSameFrame(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, SameFrame sameFrame) {}", "assistant_with_reasoning": "\nThe class ConstantPoolRemapper implements StackMapFrameVisitor. After the generic visitAnyStackMapFrame method, the next visitor method defined is for a specific frame type, typically visitSameFrame, which usually has an empty body because SameFrame contains no constant pool references. Following the file’s indentation and signature style, the next line should be the definition of visitSameFrame with an empty body.\n\npublic void visitSameFrame(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, SameFrame sameFrame) {}", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 5.141, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 19463, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "public void visitSameFrame(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, SameFrame sameFrame) {}", "score": 0.94, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "using UnityEngine;\nusing System.Collections;\npublic class phone_Transform_localRotation : MonoBehaviour {\nQuaternion[] animVar;\nfloat deltaTime;\nfloat startTime;\nvoid Start(){\nstartTime = Time.time;\ndeltaTime = 1f/60f;\nanimVar = new Quaternion[560];\nanimVar[0] = new Quaternion(-0.707106f,0.000000f,-0.001327f,0.707106f);\nanimVar[1] = new Quaternion(-0.707106f,0.000000f,-0.001327f,0.707106f);\nanimVar[2] = new Quaternion(-0.707106f,0.000000f,-0.001327f,0.707106f);\nanimVar[3] = new Quaternion(-0.707106f,0.000000f,-0.001327f,0.707106f);\nanimVar[4] = new Quaternion(-0.707106f,0.000000f,-0.001327f,0.707106f);\nanimVar[5] = new Quaternion(-0.707106f,0.000000f,-0.001327f,0.707106f);\nanimVar[6] = new Quaternion(-0.707106f,0.000000f,-0.001327f,0.707106f);\nanimVar[7] = new Quaternion(-0.707106f,0.000000f,-0.001327f,0.707106f);\nanimVar[8] = new Quaternion(-0.707106f,0.000000f,-0.001327f,0.707106f);\nanimVar[9] = new Quaternion(-0.707106f,0.000000f,-0.001327f,0.707106f);\nanimVar[10] = new Quaternion(-0.707106f,0.000000f,-0.001327f,0.707106f);\nanimVar[11] = new Quaternion(-0.707106f,0.000000f,-0.001327f,0.707106f);\nanimVar[12] = new Quaternion(-0.707106f,0.000000f,-0.001327f,0.707106f);\nanimVar[13] = new Quaternion(-0.707106f,0.000000f,-0.001327f,0.707106f);\nanimVar[14] = new Quaternion(-0.707106f,0.000000f,-0.001327f,0.707106f);\nanimVar[15] = new Quaternion(-0.707106f,0.000000f,-0.001327f,0.707106f);\nanimVar[16] = new Quaternion(-0.707106f,0.000000f,-0.001327f,0.707106f);\nanimVar[17] = new Quaternion(-0.707106f,0.000000f,-0.001327f,0.707106f);\nanimVar[18] = new Quaternion(-0.707106f,0.000000f,-0.001327f,0.707106f);\nanimVar[19] = new Quaternion(-0.707106f,0.000000f,-0.001327f,0.707106f);\nanimVar[20] = new Quaternion(-0.707106f,0.000000f,-0.001327f,0.707106f);\nanimVar[21] = new Quaternion(-0.707106f,0.000000f,-0.001327f,0.707106f);\nanimVar[22] = new Quaternion(-0.707106f,0.000000f,-0.001327f,0.707106f);\nanimVar[23] = new Quaternion(-0.707106f,0.000000f,-0.001327f,0.707106f);\nanimVar[24] = new Quaternion(-0.707106f,0.000000f,-0.001327f,0.707106f);\nanimVar[25] = new Quaternion(-0.707106f,0.000000f,-0.001327f,0.707106f);\nanimVar[26] = new Quaternion(-0.707106f,0.000000f,-0.001327f,0.707106f);\nanimVar[27] = new Quaternion(-0.707106f,0.000000f,-0.001327f,0.707106f);\nanimVar[28] = new Quaternion(-0.707106f,0.000000f,-0.001327f,0.707106f);\nanimVar[29] = new Quaternion(-0.707106f,0.000000f,-0.001327f,0.707106f);\nanimVar[30] = new Quaternion(-0.707106f,0.000000f,-0.001327f,0.707106f);\nanimVar[31] = new Quaternion(-0.707106f,0.000000f,-0.001327f,0.707106f);\nanimVar[32] = new Quaternion(-0.707106f,0.000000f,-0.001327f,0.707106f);\nanimVar[33] = new Quaternion(-0.707106f,0.000000f,-0.001327f,0.707106f);\nanimVar[34] = new Quaternion(-0.707106f,0.000000f,-0.001327f,0.707106f);\nanimVar[35] = new Quaternion(-0.707106f,0.000000f,-0.001327f,0.707106f);\nanimVar[36] = new Quaternion(-0.707106f,0.000000f,-0.001327f,0.707106f);\nanimVar[37] = new Quaternion(-0.707106f,0.000000f,-0.001327f,0.707106f);\nanimVar[38] = new Quaternion(-0.707106f,0.000000f,-0.001327f,0.707106f);\nanimVar[39] = new Quaternion(-0.707106f,0.000000f,-0.001327f,0.707106f);\nanimVar[40] = new Quaternion(-0.707106f,0.000000f,-0.001327f,0.707106f);\nanimVar[41] = new Quaternion(-0.707106f,0.000000f,-0.001327f,0.707106f);\nanimVar[42] = new Quaternion(-0.707106f,0.000000f,-0.001327f,0.707106f);\nanimVar[43] = new Quaternion(-0.707106f,0.000000f,-0.001327f,0.707106f);\nanimVar[44] = new Quaternion(-0.707106f,0.000000f,-0.001327f,0.707106f);\nanimVar[45] = new Quaternion(-0.707106f,0.000000f,-0.001327f,0.707106f);\nanimVar[46] = new Quaternion(-0.707106f,0.000000f,-0.001327f,0.707106f);\nanimVar[47] = new Quaternion(-0.707106f,0.000000f,-0.001327f,0.707106f);\nanimVar[48] = new Quaternion(-0.707106f,0.000000f,-0.001327f,0.707106f);\nanimVar[49] = new Quaternion(-0.707106f,0.000000f,-0.001327f,0.707106f);\nanimVar[50] = new Quaternion(-0.707106f,-0.000027f,-0.001300f,0.707106f);\nanimVar[51] = new Quaternion(-0.707106f,-0.000837f,-0.000488f,0.707106f);\nanimVar[52] = new Quaternion(-0.707103f,-0.002740f,0.001418f,0.707103f);\nanimVar[53] = new Quaternion(-0.707089f,-0.005697f,0.004381f,0.707089f);\nanimVar[54] = new Quaternion(-0.707049f,-0.009675f,0.008366f,0.707049f);\nanimVar[55] = new Quaternion(-0.706968f,-0.014640f,0.013341f,0.706968f);\nanimVar[56] = new Quaternion(-0.706826f,-0.020564f,0.019276f,0.706826f);\nanimVar[57] = new Quaternion(-0.706599f,-0.027415f,0.026141f,0.706599f);\nanimVar[58] = new Quaternion(-0.706263f,-0.035166f,0.033906f,0.706263f);\nanimVar[59] = new Quaternion(-0.705788f,-0.043785f,0.042543f,0.705788f);\nanimVar[60] = new Quaternion(-0.705145f,-0.053243f,0.052019f,0.705145f);\nanimVar[61] = new Quaternion(-0.704303f,-0.063505f,0.062303f,0.704303f);\nanimVar[62] = new Quaternion(-0.703229f,-0.074537f,0.073357f,0.703229f);\nanimVar[63] = new Quaternion(-0.701891f,-0.086299f,0.085144f,0.701891f);\nanimVar[64] = new Quaternion(-0.700257f,-0.098749f,0.097620f,0.700257f);\nanimVar[65] = new Quaternion(-0.698294f,-0.111839f,0.110739f,0.698294f);\nanimVar[66] = new Quaternion(-0.695973f,-0.125519f,0.124448f,0.695973f);\nanimVar[67] = new Quaternion(-0.693268f,-0.139731f,0.138692f,0.693268f);\nanimVar[68] = new Quaternion(-0.690153f,-0.154415f,0.153409f,0.690153f);\nanimVar[69] = new Quaternion(-0.686609f,-0.169505f,0.168535f,0.686609f);\nanimVar[70] = new Quaternion(-0.682622f,-0.184932f,0.183997f,0.682622f);\nanimVar[71] = new Quaternion(-0.678182f,-0.200621f,0.199725f,0.678182f);\nanimVar[72] = new Quaternion(-0.673286f,-0.216497f,0.215639f,0.673286f);\nanimVar[73] = new Quaternion(-0.667939f,-0.232480f,0.231663f,0.667939f);\nanimVar[74] = new Quaternion(-0.662151f,-0.248492f,0.247716f,0.662151f);\nanimVar[75] = new Quaternion(-0.655941f,-0.264453f,0.263718f,0.655941f);\nanimVar[76] = new Quaternion(-0.649334f,-0.280284f,0.279592f,0.649334f);\nanimVar[77] = new Quaternion(-0.642362f,-0.295910f,0.295260f,0.642362f);\nanimVar[78] = new Quaternion(-0.635065f,-0.311258f,0.310650f,0.635065f);\nanimVar[79] = new Quaternion(-0.627486f,-0.326259f,0.325694f,0.627486f);\nanimVar[80] = new Quaternion(-0.619676f,-0.340852f,0.340329f,0.619676f);\nanimVar[81] = new Quaternion(-0.611687f,-0.354979f,0.354497f,0.611687f);\nanimVar[82] = new Quaternion(-0.603576f,-0.368589f,0.368148f,0.603576f);\nanimVar[83] = new Quaternion(-0.595403f,-0.381639f,0.381238f,0.595403f);\nanimVar[84] = new Quaternion(-0.587227f,-0.394090f,0.393728f,0.587227f);\nanimVar[85] = new Quaternion(-0.579109f,-0.405913f,0.405588f,0.579109f);\nanimVar[86] = new Quaternion(-0.571108f,-0.417081f,0.416792f,0.571108f);\nanimVar[87] = new Quaternion(-0.563283f,-0.427576f,0.427321f,0.563283f);\nanimVar[88] = new Quaternion(-0.555692f,-0.437383f,0.437161f,0.555692f);\nanimVar[89] = new Quaternion(-0.548389f,-0.446492f,0.446301f,0.548389f);\nanimVar[90] = new Quaternion(-0.541426f,-0.454897f,0.454735f,0.541426f);\nanimVar[91] = new Quaternion(-0.534855f,-0.462594f,0.462458f,0.534855f);\nanimVar[92] = new Quaternion(-0.528722f,-0.469580f,0.469468f,0.528722f);\nanimVar[93] = new Quaternion(-0.523073f,-0.475854f,0.475765f,0.523073f);\nanimVar[94] = new Quaternion(-0.517950f,-0.481416f,0.481347f,0.517950f);\nanimVar[95] = new Quaternion(-0.513393f,-0.486264f,0.486213f,0.513393f);\nanimVar[96] = new Quaternion(-0.509441f,-0.490395f,0.490360f,0.509441f);\nanimVar[97] = new Quaternion(-0.506131f,-0.493805f,0.493782f,0.506131f);\nanimVar[98] = new Quaternion(-0.503498f,-0.496484f,0.496471f,0.503498f);\nanimVar[99] = new Quaternion(-0.501576f,-0.498422f,0.498416f,0.501576f);\nanimVar[100] = new Quaternion(-0.500399f,-0.499601f,0.499600f,0.500399f);\nanimVar[101] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[102] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[103] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[104] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[105] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[106] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[107] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[108] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[109] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[110] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[111] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[112] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[113] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[114] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[115] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[116] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[117] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[118] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[119] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[120] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[121] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[122] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[123] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[124] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[125] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[126] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[127] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[128] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[129] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[130] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[131] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[132] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[133] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[134] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[135] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[136] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[137] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[138] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[139] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[140] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[141] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[142] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[143] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[144] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[145] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[146] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[147] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[148] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[149] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[150] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[151] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[152] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[153] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[154] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[155] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[156] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[157] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[158] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[159] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[160] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[161] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[162] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[163] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[164] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[165] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[166] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[167] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[168] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[169] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[170] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[171] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[172] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[173] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[174] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[175] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[176] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[177] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[178] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[179] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[180] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[181] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[182] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[183] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[184] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[185] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[186] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[187] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[188] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[189] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[190] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[191] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[192] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[193] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[194] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[195] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[196] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[197] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[198] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[199] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[200] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[201] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[202] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[203] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[204] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[205] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[206] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[207] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[208] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[209] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[210] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[211] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[212] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[213] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[214] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[215] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[216] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[217] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[218] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[219] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[220] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[221] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[222] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[223] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[224] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[225] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[226] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[227] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[228] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[229] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[230] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[231] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[232] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[233] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[234] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[235] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[236] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[237] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[238] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[239] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[240] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[241] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[242] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[243] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[244] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[245] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[246] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[247] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[248] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[249] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[250] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[251] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[252] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[253] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[254] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[255] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[256] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[257] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[258] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[259] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[260] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[261] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[262] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[263] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[264] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[265] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[266] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);\nanimVar[267] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);", "answers": ["animVar[268] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);"], "length": 1105, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "49877f28-1d20-426a-9f90-41dd69a728ad", "reasoning": "The code is filling the animVar array with Quaternion values. Up to index 267 the value is the constant Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f). The next logical line continues the initialization sequence with the next index, using the same constant value.", "reasoning_model_answer": "animVar[268] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);", "assistant_with_reasoning": "\nThe code is filling the animVar array with Quaternion values. Up to index 267 the value is the constant Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f). The next logical line continues the initialization sequence with the next index, using the same constant value.\n\nanimVar[268] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.114, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 20066, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "animVar[268] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);", "score": 1.0, "is_full_score": true, "is_nonzero_score": true}} {"input": "", "context": "package org.endeavour.enterprise.endpoints;\n\nimport org.apache.commons.lang3.StringUtils;\nimport org.endeavourhealth.common.security.SecurityUtils;\nimport org.endeavourhealth.core.terminology.Snomed;\nimport org.endeavourhealth.core.terminology.SnomedCode;\nimport org.endeavourhealth.enterprise.core.DefinitionItemType;\nimport org.endeavourhealth.enterprise.core.DependencyType;\n\nimport org.endeavourhealth.enterprise.core.database.models.*;\nimport org.endeavourhealth.enterprise.core.database.models.data.*;\nimport org.endeavourhealth.enterprise.core.json.*;\nimport org.endeavourhealth.enterprise.core.querydocument.QueryDocumentSerializer;\nimport org.endeavourhealth.enterprise.core.querydocument.models.*;\nimport org.endeavourhealth.core.terminology.TerminologyService;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport javax.ws.rs.*;\nimport javax.ws.rs.core.Context;\nimport javax.ws.rs.core.MediaType;\nimport javax.ws.rs.core.Response;\nimport javax.ws.rs.core.SecurityContext;\nimport java.util.*;\n\n@Path(\"/library\")\npublic final class LibraryEndpoint extends AbstractItemEndpoint {\n\n private static final Logger LOG = LoggerFactory.getLogger(LibraryEndpoint.class);\n\n\n\t@GET\n\t@Produces(MediaType.APPLICATION_JSON)\n\t@Consumes(MediaType.APPLICATION_JSON)\n\t@Path(\"/getFolderContents\")\n\tpublic Response getFolderContents(@Context SecurityContext sc, @QueryParam(\"folderUuid\") String uuidStr) throws Exception {\n\t\tsuper.setLogbackMarkers(sc);\n\n\t\tString folderUuid = uuidStr;\n\t\tString orgUuid = \"B6FF900D-8FCD-43D8-AF37-5DB3A87A6EF6\";\n\n\t\tLOG.trace(\"GettingFolderContents for folder {}\", folderUuid);\n\n\t\tJsonFolderContentsList ret = new JsonFolderContentsList();\n\n\t\tList childActiveItems = ActiveItemEntity.retrieveDependentItems(orgUuid, folderUuid, (short)DependencyType.IsContainedWithin.getValue());\n\n\t\tHashMap hmAuditsByAuditUuid = new HashMap<>();\n\t\tList audits = AuditEntity.retrieveForActiveItems(childActiveItems);\n\t\tfor (AuditEntity audit: audits) {\n\t\t\thmAuditsByAuditUuid.put(audit.getAuditUuid(), audit);\n\t\t}\n\n\t\tHashMap hmItemsByItemUuid = new HashMap<>();\n\t\tList items = ItemEntity.retrieveForActiveItems(childActiveItems);\n\t\tfor (ItemEntity item: items) {\n\t\t\thmItemsByItemUuid.put(item.getItemUuid(), item);\n\t\t}\n\n\t\tHashMap hmReportsByItemUuid = new HashMap<>();\n\t\tList reports = ItemEntity.retrieveForReports(childActiveItems);\n\t\tfor (CohortResultEntity report: reports) {\n\t\t\thmReportsByItemUuid.put(report.getQueryItemUuid(), report);\n\t\t}\n\n\t\tfor (int i = 0; i < childActiveItems.size(); i++) {\n\n\t\t\tActiveItemEntity activeItem = childActiveItems.get(i);\n\t\t\tItemEntity item = hmItemsByItemUuid.get(activeItem.getItemUuid());\n\t\t\tShort itemType = activeItem.getItemTypeId();\n\t\t\tAuditEntity audit = hmAuditsByAuditUuid.get(item.getAuditUuid());\n\t\t\tCohortResultEntity cohort = hmReportsByItemUuid.get(activeItem.getItemUuid());\n\n\t\t\tJsonFolderContent c = new JsonFolderContent(activeItem, item, audit, cohort);\n\t\t\tret.addContent(c);\n\n\t\t\tif (itemType == DefinitionItemType.Query.getValue()) {\n\n\t\t\t} else if (itemType == DefinitionItemType.Test.getValue()) {\n\n\t\t\t} else if (itemType == DefinitionItemType.DataSource.getValue()) {\n\n\t\t\t} else if (itemType == DefinitionItemType.CodeSet.getValue()) {\n\n\t\t\t} else if (itemType == DefinitionItemType.Report.getValue()) {\n\t\t\t\tLibraryItem libraryItem = QueryDocumentSerializer.readLibraryItemFromXml(item.getXmlContent());\n\t\t\t\tReport report = libraryItem.getReport();\n\t\t\t\tif (report != null && report.getLastRunDate() != null) {\n if (new Date(report.getLastRunDate()).after(new Date()))\n c.setIsRunning(true);\n else\n c.setIsRunning(false);\n c.setLastRun(new Date(report.getLastRunDate()));\n\n }\n\t\t\t} else {\n\t\t\t\t//throw new RuntimeException(\"Unexpected content \" + item + \" in folder\");\n\t\t\t}\n\t\t}\n\n\t\tif (ret.getContents() != null) {\n\t\t\tCollections.sort(ret.getContents());\n\t\t}\n\n\t\tclearLogbackMarkers();\n\n\t\treturn Response\n\t\t\t\t.ok()\n\t\t\t\t.entity(ret)\n\t\t\t\t.build();\n\t}\n\n @GET\n @Produces(MediaType.APPLICATION_JSON)\n @Consumes(MediaType.APPLICATION_JSON)\n @Path(\"/getLibraryItem\")\n public Response getLibraryItem(@Context SecurityContext sc, @QueryParam(\"uuid\") String uuidStr) throws Exception {\n super.setLogbackMarkers(sc);\n\n String libraryItemUuid = uuidStr;\n\n LOG.trace(\"GettingLibraryItem for UUID {}\", libraryItemUuid);\n\n ItemEntity item = ItemEntity.retrieveLatestForUUid(libraryItemUuid);\n String xml = item.getXmlContent();\n\n LibraryItem ret = QueryDocumentSerializer.readLibraryItemFromXml(xml);\n\n clearLogbackMarkers();\n\n return Response\n .ok()\n .entity(ret)\n .build();\n }\n\n @POST\n @Produces(MediaType.APPLICATION_JSON)\n @Consumes(MediaType.APPLICATION_JSON)\n @Path(\"/saveLibraryItem\")\n public Response saveLibraryItem(@Context SecurityContext sc, LibraryItem libraryItem) throws Exception {\n super.setLogbackMarkers(sc);\n\n String userUuid = SecurityUtils.getCurrentUserId(sc).toString();\n String orgUuid = \"B6FF900D-8FCD-43D8-AF37-5DB3A87A6EF6\";\n\n String libraryItemUuid = parseUuidFromStr(libraryItem.getUuid());\n String name = libraryItem.getName();\n String description = libraryItem.getDescription();\n String folderUuid = parseUuidFromStr(libraryItem.getFolderUuid());\n\n Query query = libraryItem.getQuery();\n CodeSet codeSet = libraryItem.getCodeSet();\n Report report = libraryItem.getReport();\n\n LOG.trace(String.format(\"SavingLibraryItem UUID %s, Name %s FolderUuid %s\", libraryItemUuid, name, folderUuid));\n\n QueryDocument doc = new QueryDocument();\n doc.getLibraryItem().add(libraryItem);\n\n //work out the item type (query, test etc.) from the content passed up\n Short type = null;\n if (query != null) {\n type = (short)DefinitionItemType.Query.getValue();\n } else if (codeSet != null) {\n\t\t\t\t\ttype = (short) DefinitionItemType.CodeSet.getValue();\n\t\t\t\t} else if (report != null) {\n\t\t\t\t\ttype = (short) DefinitionItemType.Report.getValue();\n } else {\n //if we've been passed no proper content, we might just be wanting to rename an existing item,\n //so work out the type from what's on the DB already\n if (libraryItemUuid == null) {\n throw new BadRequestException(\"Can't save LibraryItem without some content (e.g. query, test etc.)\");\n }\n\n ActiveItemEntity activeItem = ActiveItemEntity.retrieveForItemUuid(libraryItemUuid);\n type = activeItem.getItemTypeId();\n doc = null; //clear this, because we don't want to overwrite what's on the DB with an empty query doc\n }\n\n boolean inserting = libraryItemUuid == null;\n if (inserting) {\n libraryItemUuid = UUID.randomUUID().toString();\n libraryItem.setUuid(libraryItemUuid.toString());\n }\n\n super.saveItem(inserting, libraryItemUuid, orgUuid, userUuid, type.intValue(), name, description, doc, folderUuid);\n\n //return the UUID of the libraryItem\n LibraryItem ret = new LibraryItem();\n ret.setUuid(libraryItemUuid.toString());\n\n clearLogbackMarkers();\n\n return Response\n .ok()\n .entity(ret)\n .build();\n }\n\n @POST\n @Produces(MediaType.APPLICATION_JSON)\n @Consumes(MediaType.APPLICATION_JSON)\n @Path(\"/deleteLibraryItem\")\n public Response deleteLibraryItem(@Context SecurityContext sc, LibraryItem libraryItem) throws Exception {\n super.setLogbackMarkers(sc);\n\n String libraryItemUuid = parseUuidFromStr(libraryItem.getUuid());\n String userUuid = SecurityUtils.getCurrentUserId(sc).toString();;\n String orgUuid = \"B6FF900D-8FCD-43D8-AF37-5DB3A87A6EF6\";\n \n LOG.trace(\"DeletingLibraryItem UUID {}\", libraryItemUuid);\n\n JsonDeleteResponse ret = deleteItem(libraryItemUuid, orgUuid, userUuid);\n\n clearLogbackMarkers();\n\n return Response\n .ok()\n .entity(ret)\n .build();\n }\n\n @GET\n\t\t@Produces(MediaType.APPLICATION_JSON)\n\t\t@Consumes(MediaType.APPLICATION_JSON)\n\t\t@Path(\"/getLibraryItemNames\")\n\t\tpublic Response getLibraryItemNames(@Context SecurityContext sc, @QueryParam(\"itemUuids\") List itemUuids) {\n\t\t\tsuper.setLogbackMarkers(sc);\n\n\t\t\tLOG.trace(\"getLibraryItemNames\", itemUuids);\n\t\t\tMap names = new HashMap<>();\n\n\t\t\tfor (String itemUuid : itemUuids) {\n\t\t\t\ttry {\n\t\t\t\t\tItemEntity item = ItemEntity.retrieveLatestForUUid(itemUuid);\n\t\t\t\t\tnames.put(itemUuid, item.getTitle());\n\t\t\t\t} catch (Exception e) {\n\t\t\t\t\tnames.put(itemUuid, \"Error!\");\n\t\t\t\t\tLOG.error(\"Error loading name for library item \" + itemUuid);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn Response\n\t\t\t\t\t.ok()\n\t\t\t\t\t.entity(names)\n\t\t\t\t\t.build();\n\t\t}\n\n\n @GET\n @Produces(MediaType.APPLICATION_JSON)\n @Consumes(MediaType.APPLICATION_JSON)\n @Path(\"/getContentNamesForReportLibraryItem\")\n public Response getContentNamesForReportLibraryItem(@Context SecurityContext sc, @QueryParam(\"uuid\") String uuidStr) throws Exception {\n super.setLogbackMarkers(sc);\n\n String itemUuid = uuidStr;\n\n LOG.trace(\"getContentNamesforReportLibraryItem for UUID {}\", itemUuid);\n\n JsonFolderContentsList ret = new JsonFolderContentsList();\n\n ActiveItemEntity activeItem = ActiveItemEntity.retrieveForItemUuid(itemUuid);\n List dependentItems = ItemDependencyEntity.retrieveForActiveItemType(activeItem, (short)DependencyType.Uses.getValue());\n\n for (ItemDependencyEntity dependentItem: dependentItems) {\n String dependentItemUuid = dependentItem.getDependentItemUuid();\n ItemEntity item = ItemEntity.retrieveLatestForUUid(dependentItemUuid);\n\n JsonFolderContent content = new JsonFolderContent(item, null, null);\n ret.addContent(content);\n }\n\n clearLogbackMarkers();\n\n return Response\n .ok()\n .entity(ret)\n .build();\n }\n\n @POST\n @Produces(MediaType.APPLICATION_JSON)\n @Consumes(MediaType.APPLICATION_JSON)\n @Path(\"/moveLibraryItems\")\n public Response moveLibraryItems(@Context SecurityContext sc, JsonMoveItems parameters) throws Exception {\n super.setLogbackMarkers(sc);\n\n String userUuid = SecurityUtils.getCurrentUserId(sc).toString();;\n String orgUuid = \"B6FF900D-8FCD-43D8-AF37-5DB3A87A6EF6\";\n\n LOG.trace(\"moveLibraryItems\");\n\n super.moveItems(userUuid, orgUuid, parameters);\n\n clearLogbackMarkers();\n\n return Response\n .ok()\n .build();\n }\n\n @GET\n @Produces(MediaType.APPLICATION_JSON)\n @Consumes(MediaType.APPLICATION_JSON)\n @Path(\"/getConceptChildren\")\n public Response getConceptChildren(@Context SecurityContext sc, @QueryParam(\"id\") String id) throws Exception {\n super.setLogbackMarkers(sc);\n\n List concepts = ConceptEntity.findConceptChildren(id);\n\n List ret = new ArrayList<>();\n\n String prevDefinition = \"\";\n\n for (Object[] conceptEntity: concepts) {\n String conceptId = conceptEntity[0].toString();\n String definition = conceptEntity[1].toString();\n String parentType = conceptEntity[2]==null?\"\":conceptEntity[2].toString();\n String parentTypeId = conceptEntity[3]==null?\"\":conceptEntity[3].toString();\n String baseType = conceptEntity[4]==null?\"\":conceptEntity[4].toString();\n String baseTypeId = conceptEntity[5]==null?\"\":conceptEntity[5].toString();\n String dataTypeId = conceptEntity[6].toString();\n String conceptTypeId = conceptEntity[7].toString();\n String present = conceptEntity[8].toString();\n String units = conceptEntity[9]==null?\"\":conceptEntity[9].toString();\n\n\n if (definition.equals(prevDefinition))\n continue;\n\n prevDefinition = definition;\n\n if (conceptTypeId.equals(\"1\")|| // don't show resource or unit types\n conceptTypeId.equals(\"3\")) {\n continue;\n }\n\n JsonCode code = new JsonCode();\n code.setId(conceptId);\n code.setLabel(definition);\n code.setDataType(dataTypeId);\n code.setParentType(parentType);\n code.setBaseType(baseType);\n code.setPresent(present);\n code.setUnits(units);\n\n ret.add(code);\n }\n\n clearLogbackMarkers();\n\n return Response\n .ok()\n .entity(ret)\n .build();\n }\n\n @GET\n @Produces(MediaType.APPLICATION_JSON)\n @Consumes(MediaType.APPLICATION_JSON)\n @Path(\"/getConceptParents\")\n public Response getConceptParents(@Context SecurityContext sc, @QueryParam(\"id\") String id) throws Exception {\n super.setLogbackMarkers(sc);\n\n List concepts = ConceptEntity.findConceptParents(id);\n\n List ret = new ArrayList<>();\n\n String prevDefinition = \"\";\n\n for (Object[] conceptEntity: concepts) {\n String conceptId = conceptEntity[0].toString();\n String definition = conceptEntity[1].toString();\n String parentType = conceptEntity[2]==null?\"\":conceptEntity[2].toString();\n String parentTypeId = conceptEntity[3]==null?\"\":conceptEntity[3].toString();\n String baseType = conceptEntity[4]==null?\"\":conceptEntity[4].toString();\n String baseTypeId = conceptEntity[5]==null?\"\":conceptEntity[5].toString();\n String dataTypeId = conceptEntity[6].toString();\n String conceptTypeId = conceptEntity[7].toString();\n String parentConceptTypeId = conceptEntity[8]==null?\"\":conceptEntity[8].toString();\n String present = conceptEntity[9]==null?\"\":conceptEntity[9].toString();\n String units = conceptEntity[10]==null?\"\":conceptEntity[10].toString();\n\n\n if (parentType.equals(prevDefinition))\n continue;\n\n prevDefinition = parentType;\n\n if (conceptTypeId.equals(\"1\")|| // don't show resource or unit types\n conceptTypeId.equals(\"3\")||\n parentConceptTypeId.equals(\"1\")|| // don't show resource or unit types\n parentConceptTypeId.equals(\"3\")) {\n continue;\n }\n\n JsonCode code = new JsonCode();\n code.setId(parentTypeId);\n code.setLabel(parentType);\n code.setDataType(dataTypeId);\n code.setParentType(parentType);\n code.setBaseType(baseType);\n code.setPresent(present);\n code.setUnits(units);\n\n\n ret.add(code);\n }\n", "answers": [" clearLogbackMarkers();"], "length": 1001, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "309d7522-019d-481d-b401-271d2d5d7ab1", "reasoning": "The method getConceptParents mirrors getConceptChildren: after building the list 'ret' it clears logging markers and returns the response. The snippet ends just after adding a JsonCode to 'ret' inside the loop, so the next line should clear the markers before returning.", "reasoning_model_answer": "clearLogbackMarkers();", "assistant_with_reasoning": "\nThe method getConceptParents mirrors getConceptChildren: after building the list 'ret' it clears logging markers and returns the response. The snippet ends just after adding a JsonCode to 'ret' inside the loop, so the next line should clear the markers before returning.\n\nclearLogbackMarkers();", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.163, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 15211, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "clearLogbackMarkers();", "score": 0.85, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/*\n * Copyright 2008-2014 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.codehaus.groovy.transform;\n\nimport groovy.lang.MetaClass;\nimport groovy.lang.MissingPropertyException;\nimport groovy.lang.ReadOnlyPropertyException;\nimport groovy.transform.Immutable;\nimport org.codehaus.groovy.ast.ASTNode;\nimport org.codehaus.groovy.ast.AnnotatedNode;\nimport org.codehaus.groovy.ast.AnnotationNode;\nimport org.codehaus.groovy.ast.ClassCodeVisitorSupport;\nimport org.codehaus.groovy.ast.ClassHelper;\nimport org.codehaus.groovy.ast.ClassNode;\nimport org.codehaus.groovy.ast.ConstructorNode;\nimport org.codehaus.groovy.ast.FieldNode;\nimport org.codehaus.groovy.ast.Parameter;\nimport org.codehaus.groovy.ast.PropertyNode;\nimport org.codehaus.groovy.ast.VariableScope;\nimport org.codehaus.groovy.ast.expr.ArrayExpression;\nimport org.codehaus.groovy.ast.expr.ClassExpression;\nimport org.codehaus.groovy.ast.expr.ConstantExpression;\nimport org.codehaus.groovy.ast.expr.Expression;\nimport org.codehaus.groovy.ast.expr.ListExpression;\nimport org.codehaus.groovy.ast.expr.MapExpression;\nimport org.codehaus.groovy.ast.expr.VariableExpression;\nimport org.codehaus.groovy.ast.stmt.BlockStatement;\nimport org.codehaus.groovy.ast.stmt.EmptyStatement;\nimport org.codehaus.groovy.ast.stmt.Statement;\nimport org.codehaus.groovy.ast.stmt.ThrowStatement;\nimport org.codehaus.groovy.control.CompilePhase;\nimport org.codehaus.groovy.control.SourceUnit;\nimport org.codehaus.groovy.runtime.DefaultGroovyMethods;\nimport org.codehaus.groovy.runtime.InvokerHelper;\nimport org.codehaus.groovy.runtime.ReflectionMethodInvoker;\n\nimport java.lang.reflect.Field;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collection;\nimport java.util.Date;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.SortedSet;\nimport java.util.SortedMap;\nimport java.util.Collections;\n\nimport static org.codehaus.groovy.ast.ClassHelper.make;\nimport static org.codehaus.groovy.ast.ClassHelper.makeWithoutCaching;\nimport static org.codehaus.groovy.ast.tools.GeneralUtils.*;\nimport static org.codehaus.groovy.transform.EqualsAndHashCodeASTTransformation.createEquals;\nimport static org.codehaus.groovy.transform.EqualsAndHashCodeASTTransformation.createHashCode;\nimport static org.codehaus.groovy.transform.ToStringASTTransformation.createToString;\n\n/**\n * Handles generation of code for the @Immutable annotation.\n *\n * @author Paul King\n * @author Andre Steingress\n * @author Tim Yates\n */\n@GroovyASTTransformation(phase = CompilePhase.CANONICALIZATION)\npublic class ImmutableASTTransformation extends AbstractASTTransformation {\n\n /*\n Currently leaving BigInteger and BigDecimal in list but see:\n http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6348370\n\n Also, Color is not final so while not normally used with child\n classes, it isn't strictly immutable. Use at your own risk.\n\n This list can by extended by providing \"known immutable\" classes\n via Immutable.knownImmutableClasses\n */\n private static List immutableList = Arrays.asList(\n \"java.lang.Class\",\n \"java.lang.Boolean\",\n \"java.lang.Byte\",\n \"java.lang.Character\",\n \"java.lang.Double\",\n \"java.lang.Float\",\n \"java.lang.Integer\",\n \"java.lang.Long\",\n \"java.lang.Short\",\n \"java.lang.String\",\n \"java.math.BigInteger\",\n \"java.math.BigDecimal\",\n \"java.awt.Color\",\n \"java.net.URI\",\n \"java.util.UUID\"\n );\n private static final Class MY_CLASS = groovy.transform.Immutable.class;\n public static final ClassNode MY_TYPE = make(MY_CLASS);\n static final String MY_TYPE_NAME = \"@\" + MY_TYPE.getNameWithoutPackage();\n static final String MEMBER_KNOWN_IMMUTABLE_CLASSES = \"knownImmutableClasses\";\n static final String MEMBER_KNOWN_IMMUTABLES = \"knownImmutables\";\n static final String MEMBER_ADD_COPY_WITH = \"copyWith\";\n static final String COPY_WITH_METHOD = \"copyWith\";\n\n private static final ClassNode DATE_TYPE = make(Date.class);\n private static final ClassNode CLONEABLE_TYPE = make(Cloneable.class);\n private static final ClassNode COLLECTION_TYPE = makeWithoutCaching(Collection.class, false);\n private static final ClassNode READONLYEXCEPTION_TYPE = make(ReadOnlyPropertyException.class);\n private static final ClassNode DGM_TYPE = make(DefaultGroovyMethods.class);\n private static final ClassNode SELF_TYPE = make(ImmutableASTTransformation.class);\n private static final ClassNode HASHMAP_TYPE = makeWithoutCaching(HashMap.class, false);\n private static final ClassNode MAP_TYPE = makeWithoutCaching(Map.class, false);\n private static final ClassNode REFLECTION_INVOKER_TYPE = make(ReflectionMethodInvoker.class);\n private static final ClassNode SORTEDSET_CLASSNODE = make(SortedSet.class);\n private static final ClassNode SORTEDMAP_CLASSNODE = make(SortedMap.class);\n private static final ClassNode SET_CLASSNODE = make(Set.class);\n private static final ClassNode MAP_CLASSNODE = make(Map.class);\n public static final String IMMUTABLE_SAFE_FLAG = \"Immutable.Safe\";\n\n public void visit(ASTNode[] nodes, SourceUnit source) {\n init(nodes, source);\n AnnotatedNode parent = (AnnotatedNode) nodes[1];\n AnnotationNode node = (AnnotationNode) nodes[0];\n // temporarily have weaker check which allows for old Deprecated Annotation\n// if (!MY_TYPE.equals(node.getClassNode())) return;\n if (!node.getClassNode().getName().endsWith(\".Immutable\")) return;\n List newProperties = new ArrayList();\n\n if (parent instanceof ClassNode) {\n final List knownImmutableClasses = getKnownImmutableClasses(node);\n final List knownImmutables = getKnownImmutables(node);\n\n ClassNode cNode = (ClassNode) parent;\n String cName = cNode.getName();\n if (!checkNotInterface(cNode, MY_TYPE_NAME)) return;\n makeClassFinal(cNode);\n\n final List pList = getInstanceProperties(cNode);\n for (PropertyNode pNode : pList) {\n adjustPropertyForImmutability(pNode, newProperties);\n }\n for (PropertyNode pNode : newProperties) {\n cNode.getProperties().remove(pNode);\n addProperty(cNode, pNode);\n }\n final List fList = cNode.getFields();\n for (FieldNode fNode : fList) {\n ensureNotPublic(cName, fNode);\n }\n createConstructors(cNode, knownImmutableClasses, knownImmutables);\n if (!hasAnnotation(cNode, EqualsAndHashCodeASTTransformation.MY_TYPE)) {\n createHashCode(cNode, true, false, false, null, null);\n createEquals(cNode, false, false, false, null, null);\n }\n if (!hasAnnotation(cNode, ToStringASTTransformation.MY_TYPE)) {\n createToString(cNode, false, false, null, null, false, true);\n }\n if( memberHasValue(node, MEMBER_ADD_COPY_WITH, true) &&\n pList.size() > 0 &&\n !hasDeclaredMethod(cNode, COPY_WITH_METHOD, 1) ) {\n createCopyWith( cNode, pList ) ;\n }\n }\n }\n\n private void doAddConstructor(final ClassNode cNode, final ConstructorNode constructorNode) {\n cNode.addConstructor(constructorNode);\n // GROOVY-5814: Immutable is not compatible with @CompileStatic\n Parameter argsParam = null;\n for (Parameter p : constructorNode.getParameters()) {\n if (\"args\".equals(p.getName())) {\n argsParam = p;\n break;\n }\n }\n if (argsParam!=null) {\n final Parameter arg = argsParam;\n ClassCodeVisitorSupport variableExpressionFix = new ClassCodeVisitorSupport() {\n @Override\n protected SourceUnit getSourceUnit() {\n return cNode.getModule().getContext();\n }\n\n @Override\n public void visitVariableExpression(final VariableExpression expression) {\n super.visitVariableExpression(expression);\n if (\"args\".equals(expression.getName())) {\n expression.setAccessedVariable(arg);\n }\n }\n };\n variableExpressionFix.visitConstructor(constructorNode);\n }\n }\n\n private List getKnownImmutableClasses(AnnotationNode node) {\n final ArrayList immutableClasses = new ArrayList();\n\n final Expression expression = node.getMember(MEMBER_KNOWN_IMMUTABLE_CLASSES);\n if (expression == null) return immutableClasses;\n\n if (!(expression instanceof ListExpression)) {\n addError(\"Use the Groovy list notation [el1, el2] to specify known immutable classes via \\\"\" + MEMBER_KNOWN_IMMUTABLE_CLASSES + \"\\\"\", node);\n return immutableClasses;\n }\n\n final ListExpression listExpression = (ListExpression) expression;\n for (Expression listItemExpression : listExpression.getExpressions()) {\n if (listItemExpression instanceof ClassExpression) {\n immutableClasses.add(listItemExpression.getType().getName());\n }\n }\n\n return immutableClasses;\n }\n\n private List getKnownImmutables(AnnotationNode node) {\n final ArrayList immutables = new ArrayList();\n\n final Expression expression = node.getMember(MEMBER_KNOWN_IMMUTABLES);\n if (expression == null) return immutables;\n\n if (!(expression instanceof ListExpression)) {\n addError(\"Use the Groovy list notation [el1, el2] to specify known immutable property names via \\\"\" + MEMBER_KNOWN_IMMUTABLES + \"\\\"\", node);\n return immutables;\n }\n\n final ListExpression listExpression = (ListExpression) expression;\n for (Expression listItemExpression : listExpression.getExpressions()) {\n if (listItemExpression instanceof ConstantExpression) {", "answers": [" immutables.add((String) ((ConstantExpression) listItemExpression).getValue());"], "length": 838, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "aafd5379-568f-44bd-b7e8-64d0d9654e76", "reasoning": "The method getKnownImmutables collects property names from a list expression. Inside the loop it checks for ConstantExpression items, then should add the constant's string value to the immutables list. The next line therefore adds the constant's text to the list.", "reasoning_model_answer": "immutables.add(((ConstantExpression) listItemExpression).getText());", "assistant_with_reasoning": "\nThe method getKnownImmutables collects property names from a list expression. Inside the loop it checks for ConstantExpression items, then should add the constant's string value to the immutables list. The next line therefore adds the constant's text to the list.\n\nimmutables.add(((ConstantExpression) listItemExpression).getText());", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.213, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 10911, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "immutables.add(((ConstantExpression) listItemExpression).getText());", "score": 0.8, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "namespace StockSharp.Algo.Candles.Compression\n{\n\tusing System;\n\tusing System.Collections.Generic;\n\tusing System.Linq;\n\n\tusing Ecng.Collections;\n\tusing Ecng.Common;\n\n\tusing StockSharp.Localization;\n\tusing StockSharp.Logging;\n\tusing StockSharp.Messages;\n\n\t/// \n\t/// Candle builder adapter.\n\t/// \n\tpublic class CandleBuilderMessageAdapter : MessageAdapterWrapper\n\t{\n\t\tprivate enum SeriesStates\n\t\t{\n\t\t\tNone,\n\t\t\tRegular,\n\t\t\tSmallTimeFrame,\n\t\t\tCompress,\n\t\t}\n\n\t\tprivate class SeriesInfo : ICandleBuilderSubscription\n\t\t{\n\t\t\tpublic SeriesInfo(MarketDataMessage original, MarketDataMessage current)\n\t\t\t{\n\t\t\t\tOriginal = original ?? throw new ArgumentNullException(nameof(original));\n\t\t\t\tCurrent = current;\n\t\t\t}\n\n\t\t\tpublic long Id => Original.TransactionId;\n\n\t\t\tMarketDataMessage ICandleBuilderSubscription.Message => Original;\n\n\t\t\tpublic MarketDataMessage Original { get; }\n\n\t\t\tpublic Dictionary Child { get; } = new Dictionary();\n\n\t\t\tprivate MarketDataMessage _current;\n\n\t\t\tpublic MarketDataMessage Current\n\t\t\t{\n\t\t\t\tget => _current;\n\t\t\t\tset => _current = value ?? throw new ArgumentNullException(nameof(value));\n\t\t\t}\n\n\t\t\tpublic SeriesStates State { get; set; } = SeriesStates.None;\n\n\t\t\tpublic BiggerTimeFrameCandleCompressor BigTimeFrameCompressor { get; set; }\n\n\t\t\tpublic ICandleBuilderValueTransform Transform { get; set; }\n\n\t\t\tpublic DateTimeOffset? LastTime { get; set; }\n\n\t\t\tpublic long? Count { get; set; }\n\n\t\t\tpublic CandleMessage CurrentCandle { get; set; }\n\n\t\t\tpublic CandleMessage NonFinishedCandle { get; set; }\n\n\t\t\tpublic VolumeProfileBuilder VolumeProfile { get; set; }\n\n\t\t\tpublic bool Stopped;\n\t\t}\n\n\t\tprivate readonly SyncObject _syncObject = new();\n\n\t\tprivate readonly Dictionary _series = new();\n\t\tprivate readonly Dictionary _replaceId = new();\n\t\tprivate readonly CandleBuilderProvider _candleBuilderProvider;\n\t\tprivate readonly Dictionary _allChilds = new();\n\t\tprivate readonly Dictionary> _pendingLoopbacks = new();\n\n\t\t/// \n\t\t/// Initializes a new instance of the .\n\t\t/// \n\t\t/// Inner message adapter.\n\t\t/// Candle builders provider.\n\t\tpublic CandleBuilderMessageAdapter(IMessageAdapter innerAdapter, CandleBuilderProvider candleBuilderProvider)\n\t\t\t: base(innerAdapter)\n\t\t{\n\t\t\t_candleBuilderProvider = candleBuilderProvider ?? throw new ArgumentNullException(nameof(candleBuilderProvider));\n\t\t}\n\n\t\t/// \n\t\t/// Send out finished candles when they received.\n\t\t/// \n\t\tpublic bool SendFinishedCandlesImmediatelly { get; set; }\n\n\t\t/// \n\t\tprotected override bool OnSendInMessage(Message message)\n\t\t{\n\t\t\tswitch (message.Type)\n\t\t\t{\n\t\t\t\tcase MessageTypes.Reset:\n\t\t\t\t{\n\t\t\t\t\tlock (_syncObject)\n\t\t\t\t\t{\n\t\t\t\t\t\t_series.Clear();\n\t\t\t\t\t\t_replaceId.Clear();\n\t\t\t\t\t\t_allChilds.Clear();\n\t\t\t\t\t\t_pendingLoopbacks.Clear();\n\t\t\t\t\t}\n\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tcase MessageTypes.MarketData:\n\t\t\t\t{\n\t\t\t\t\tvar mdMsg = (MarketDataMessage)message;\n\n\t\t\t\t\tif (!_candleBuilderProvider.IsRegistered(mdMsg.DataType2.MessageType))\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tvar transactionId = mdMsg.TransactionId;\n\n\t\t\t\t\tif (mdMsg.IsSubscribe)\n\t\t\t\t\t{\n\t\t\t\t\t\tlock (_syncObject)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tif (_replaceId.ContainsKey(transactionId))\n\t\t\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t\t\tif (_pendingLoopbacks.TryGetAndRemove(transactionId, out var tuple))\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tif (tuple.Second != SubscriptionStates.Stopped)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tif (tuple.Second == SubscriptionStates.Finished)\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tRaiseNewOutMessage(new SubscriptionFinishedMessage\n\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\tOriginalTransactionId = transactionId,\n\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tRaiseNewOutMessage(new SubscriptionResponseMessage\n\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\tOriginalTransactionId = transactionId,\n\t\t\t\t\t\t\t\t\t\t\tError = new InvalidOperationException(LocalizedStrings.SubscriptionInvalidState.Put(transactionId, tuple.Second)),\n\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\treturn true;\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\ttuple.Second = SubscriptionStates.Active;\n\t\t\t\t\t\t\t\tthis.AddDebugLog(\"New ALL candle-map (active): {0}/{1} TrId={2}\", mdMsg.SecurityId, tuple.Second, mdMsg.TransactionId);\n\n\t\t\t\t\t\t\t\tRaiseNewOutMessage(mdMsg.CreateResponse());\n\t\t\t\t\t\t\t\treturn true;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tvar isLoadOnly = mdMsg.BuildMode == MarketDataBuildModes.Load;\n\n\t\t\t\t\t\tif (mdMsg.IsCalcVolumeProfile)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tif (!IsSupportCandlesPriceLevels)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tif (isLoadOnly)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tRaiseNewOutMessage(transactionId.CreateNotSupported());\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tif (!TrySubscribeBuild(mdMsg))\n\t\t\t\t\t\t\t\t\t\tRaiseNewOutMessage(transactionId.CreateNotSupported());\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\treturn true;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (mdMsg.BuildMode == MarketDataBuildModes.Build)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tif (!TrySubscribeBuild(mdMsg))\n\t\t\t\t\t\t\t\tRaiseNewOutMessage(transactionId.CreateNotSupported());\n\n\t\t\t\t\t\t\treturn true;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (mdMsg.DataType2.MessageType == typeof(TimeFrameCandleMessage))\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tvar originalTf = mdMsg.GetTimeFrame();\n\t\t\t\t\t\t\tvar timeFrames = InnerAdapter.GetTimeFrames(mdMsg.SecurityId, mdMsg.From, mdMsg.To).ToArray();\n\n\t\t\t\t\t\t\tif (timeFrames.Contains(originalTf) || InnerAdapter.CheckTimeFrameByRequest)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tthis.AddInfoLog(\"Origin tf: {0}\", originalTf);\n\n\t\t\t\t\t\t\t\tvar original = mdMsg.TypedClone();\n\n\t\t\t\t\t\t\t\tif (mdMsg.To == null &&\n\t\t\t\t\t\t\t\t\tmdMsg.BuildMode == MarketDataBuildModes.LoadAndBuild &&\n\t\t\t\t\t\t\t\t\t!mdMsg.IsFinishedOnly &&\n\t\t\t\t\t\t\t\t\t!InnerAdapter.IsSupportCandlesUpdates &&\n\t\t\t\t\t\t\t\t\tInnerAdapter.TryGetCandlesBuildFrom(original, _candleBuilderProvider) != null)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tmdMsg.To = DateTimeOffset.Now;\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\tlock (_syncObject)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t_series.Add(transactionId, new SeriesInfo(original, original)\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tState = SeriesStates.Regular,\n\t\t\t\t\t\t\t\t\t\tLastTime = original.From,\n\t\t\t\t\t\t\t\t\t\tCount = original.Count,\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif (isLoadOnly)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tRaiseNewOutMessage(transactionId.CreateNotSupported());\n\n\t\t\t\t\t\t\t\treturn true;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif (mdMsg.AllowBuildFromSmallerTimeFrame)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tvar smaller = timeFrames\n\t\t\t\t\t\t\t\t .FilterSmallerTimeFrames(originalTf)\n\t\t\t\t\t\t\t\t .OrderByDescending()\n\t\t\t\t\t\t\t\t .FirstOr();\n\n\t\t\t\t\t\t\t\tif (smaller != null)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tthis.AddInfoLog(\"Smaller tf: {0}->{1}\", originalTf, smaller);\n\n\t\t\t\t\t\t\t\t\tvar original = mdMsg.TypedClone();\n\n\t\t\t\t\t\t\t\t\tvar current = original.TypedClone();\n\t\t\t\t\t\t\t\t\tcurrent.SetArg(smaller);\n\n\t\t\t\t\t\t\t\t\tlock (_syncObject)\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t_series.Add(transactionId, new SeriesInfo(original, current)\n\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\tState = SeriesStates.SmallTimeFrame,\n\t\t\t\t\t\t\t\t\t\t\tBigTimeFrameCompressor = new BiggerTimeFrameCandleCompressor(original, _candleBuilderProvider.Get(typeof(TimeFrameCandleMessage))),\n\t\t\t\t\t\t\t\t\t\t\tLastTime = original.From,\n\t\t\t\t\t\t\t\t\t\t\tCount = original.Count,\n\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\treturn base.OnSendInMessage(current);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif (!TrySubscribeBuild(mdMsg))\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tRaiseNewOutMessage(transactionId.CreateNotSupported());\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tif (InnerAdapter.IsCandlesSupported(mdMsg))\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tthis.AddInfoLog(\"Origin arg: {0}\", mdMsg.GetArg());\n\n\t\t\t\t\t\t\t\tvar original = mdMsg.TypedClone();\n\n\t\t\t\t\t\t\t\tlock (_syncObject)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t_series.Add(transactionId, new SeriesInfo(original, original)\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tState = SeriesStates.Regular,\n\t\t\t\t\t\t\t\t\t\tLastTime = original.From,\n\t\t\t\t\t\t\t\t\t\tCount = original.Count,\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tif (isLoadOnly || !TrySubscribeBuild(mdMsg))\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tRaiseNewOutMessage(transactionId.CreateNotSupported());\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tvar series = TryRemoveSeries(mdMsg.OriginalTransactionId);\n\n\t\t\t\t\t\tif (series == null)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tvar sentResponse = false;\n\n\t\t\t\t\t\t\tlock (_syncObject)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tif (_allChilds.TryGetAndRemove(mdMsg.OriginalTransactionId, out var child))\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tchild.Stopped = true;\n\t\t\t\t\t\t\t\t\tsentResponse = true;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif (sentResponse)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tRaiseNewOutMessage(mdMsg.CreateResponse());\n\t\t\t\t\t\t\t\treturn true;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t// TODO sub childs\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tvar unsubscribe = series.Current.TypedClone();\n\n\t\t\t\t\t\tunsubscribe.OriginalTransactionId = unsubscribe.TransactionId;\n\t\t\t\t\t\tunsubscribe.TransactionId = transactionId;\n\t\t\t\t\t\tunsubscribe.IsSubscribe = false;\n\n\t\t\t\t\t\tmessage = unsubscribe;\n\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn base.OnSendInMessage(message);\n\t\t}\n\n\t\tprivate SeriesInfo TryGetSeries(long id, out long originalId)\n\t\t{\n\t\t\tlock (_syncObject)\n\t\t\t{\n\t\t\t\tif (_replaceId.TryGetValue(id, out originalId))\n\t\t\t\t\tid = originalId;\n\t\t\t\telse\n\t\t\t\t\toriginalId = id;\n\n\t\t\t\treturn _series.TryGetValue(id);\n\t\t\t}\n\t\t}\n\n\t\tprivate SeriesInfo TryRemoveSeries(long id)\n\t\t{\n\t\t\tthis.AddInfoLog(\"Series removing {0}.\", id);\n\n\t\t\tlock (_syncObject)\n\t\t\t{\n\t\t\t\tif (!_series.TryGetAndRemove(id, out var series))\n\t\t\t\t\treturn null;\n\n\t\t\t\t_replaceId.RemoveWhere(p => p.Value == id);\n\t\t\t\treturn series;\n\t\t\t}\n\t\t}\n\n\t\tprivate MarketDataMessage TryCreateBuildSubscription(MarketDataMessage original, DateTimeOffset? lastTime, long? count, bool needCalcCount)\n\t\t{\n\t\t\tif (original == null)\n\t\t\t\tthrow new ArgumentNullException(nameof(original));\n\n\t\t\tvar buildFrom = InnerAdapter.TryGetCandlesBuildFrom(original, _candleBuilderProvider);\n\n\t\t\tif (buildFrom == null)\n\t\t\t\treturn null;\n\n\t\t\tif (needCalcCount && count is null)\n\t\t\t\tcount = GetMaxCount(buildFrom);\n\n\t\t\tvar current = new MarketDataMessage\n\t\t\t{\n\t\t\t\tDataType2 = buildFrom,\n\t\t\t\tFrom = lastTime,\n\t\t\t\tTo = original.To,\n\t\t\t\tCount = count,\n\t\t\t\tMaxDepth = original.MaxDepth,\n\t\t\t\tBuildField = original.BuildField,\n\t\t\t\tIsSubscribe = true,\n\t\t\t};\n\n\t\t\toriginal.CopyTo(current, false);\n\n\t\t\tthis.AddInfoLog(\"Build tf: {0}->{1}\", buildFrom, original.GetArg());\n\n\t\t\treturn current;\n\t\t}\n\n\t\tprivate bool TrySubscribeBuild(MarketDataMessage original)\n\t\t{\n\t\t\tvar current = TryCreateBuildSubscription(original, original.From, original.Count, false);\n\n\t\t\tif (current == null)\n\t\t\t\treturn false;\n\n\t\t\tcurrent.TransactionId = original.TransactionId;\n\n\t\t\tvar series = new SeriesInfo(original.TypedClone(), current)\n\t\t\t{\n\t\t\t\tLastTime = current.From,\n\t\t\t\tCount = current.Count,\n\t\t\t\tTransform = CreateTransform(current),\n\t\t\t\tState = SeriesStates.Compress,\n\t\t\t};\n\n\t\t\tlock (_syncObject)", "answers": ["\t\t\t\t_series.Add(original.TransactionId, series);"], "length": 853, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "3fb94f74-c69f-4df2-a337-17a41f84ba14", "reasoning": "Inside TrySubscribeBuild, after creating the SeriesInfo object, the code needs to store it in the internal _series dictionary under the transaction ID, mirroring how other subscription cases add entries within a lock. The appropriate next line is the dictionary add statement.", "reasoning_model_answer": "_series.Add(original.TransactionId, series);", "assistant_with_reasoning": "\nInside TrySubscribeBuild, after creating the SeriesInfo object, the code needs to store it in the internal _series dictionary under the transaction ID, mirroring how other subscription cases add entries within a lock. The appropriate next line is the dictionary add statement.\n\n_series.Add(original.TransactionId, series);", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 5.9, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 2, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 10713, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "_series.Add(original.TransactionId, series);", "score": 0.96, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "# Copyright 2019 Fortinet, Inc.\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with Ansible. If not, see .\n\n# Make coding more python3-ish\nfrom __future__ import (absolute_import, division, print_function)\n__metaclass__ = type\n\nimport os\nimport json\nimport pytest\nfrom mock import ANY\nfrom ansible.module_utils.network.fortios.fortios import FortiOSHandler\n\ntry:\n from ansible.modules.network.fortios import fortios_system_global\nexcept ImportError:\n pytest.skip(\"Could not load required modules for testing\", allow_module_level=True)\n\n\n@pytest.fixture(autouse=True)\ndef connection_mock(mocker):\n connection_class_mock = mocker.patch('ansible.modules.network.fortios.fortios_system_global.Connection')\n return connection_class_mock\n\n\nfos_instance = FortiOSHandler(connection_mock)\n\n\ndef test_system_global_creation(mocker):\n schema_method_mock = mocker.patch('ansible.module_utils.network.fortios.fortios.FortiOSHandler.schema')\n\n set_method_result = {'status': 'success', 'http_method': 'POST', 'http_status': 200}\n set_method_mock = mocker.patch('ansible.module_utils.network.fortios.fortios.FortiOSHandler.set', return_value=set_method_result)\n\n input_data = {\n 'username': 'admin',\n 'state': 'present',\n 'system_global': {\n 'admin_concurrent': 'enable',\n 'admin_console_timeout': '4',\n 'admin_hsts_max_age': '5',\n 'admin_https_pki_required': 'enable',\n 'admin_https_redirect': 'enable',\n 'admin_lockout_duration': '8',\n 'admin_lockout_threshold': '9',\n 'admin_login_max': '10',\n 'admin_maintainer': 'enable',\n 'admin_port': '12',\n 'admin_restrict_local': 'enable',\n 'admin_scp': 'enable',\n 'admin_server_cert': 'test_value_15',\n 'admin_sport': '16',\n 'admin_ssh_grace_time': '17',\n 'admin_ssh_password': 'enable',\n 'admin_ssh_port': '19',\n 'admin_ssh_v1': 'enable',\n 'admin_telnet_port': '21',\n 'admintimeout': '22',\n 'alias': 'test_value_23',\n 'allow_traffic_redirect': 'enable',\n 'anti_replay': 'disable',\n 'arp_max_entry': '26',\n 'asymroute': 'enable',\n 'auth_cert': 'test_value_28',\n 'auth_http_port': '29',\n 'auth_https_port': '30',\n 'auth_keepalive': 'enable',\n 'auth_session_limit': 'block-new',\n 'auto_auth_extension_device': 'enable',\n 'av_affinity': 'test_value_34',\n 'av_failopen': 'pass',\n 'av_failopen_session': 'enable',\n 'batch_cmdb': 'enable',\n 'block_session_timer': '38',\n 'br_fdb_max_entry': '39',\n 'cert_chain_max': '40',\n 'cfg_revert_timeout': '41',\n 'cfg_save': 'automatic',\n 'check_protocol_header': 'loose',\n 'check_reset_range': 'strict',\n 'cli_audit_log': 'enable',\n 'clt_cert_req': 'enable',\n 'compliance_check': 'enable',\n 'compliance_check_time': 'test_value_48',\n 'cpu_use_threshold': '49',\n 'csr_ca_attribute': 'enable',\n 'daily_restart': 'enable',\n 'device_identification_active_scan_delay': '52',\n 'device_idle_timeout': '53',\n 'dh_params': '1024',\n 'dnsproxy_worker_count': '55',\n 'dst': 'enable',\n 'endpoint_control_fds_access': 'enable',\n 'endpoint_control_portal_port': '58',\n 'failtime': '59',\n 'fds_statistics': 'enable',\n 'fds_statistics_period': '61',\n 'fortiextender': 'enable',\n 'fortiextender_data_port': '63',\n 'fortiextender_vlan_mode': 'enable',\n 'fortiservice_port': '65',\n 'gui_certificates': 'enable',\n 'gui_custom_language': 'enable',\n 'gui_date_format': 'yyyy/MM/dd',\n 'gui_device_latitude': 'test_value_69',\n 'gui_device_longitude': 'test_value_70',\n 'gui_display_hostname': 'enable',\n 'gui_ipv6': 'enable',\n 'gui_lines_per_page': '73',\n 'gui_theme': 'green',\n 'gui_wireless_opensecurity': 'enable',\n 'honor_df': 'enable',\n 'hostname': 'myhostname77',\n 'igmp_state_limit': '78',\n 'interval': '79',\n 'ip_src_port_range': 'test_value_80',\n 'ips_affinity': 'test_value_81',\n 'ipsec_asic_offload': 'enable',\n 'ipsec_hmac_offload': 'enable',\n 'ipsec_soft_dec_async': 'enable',\n 'ipv6_accept_dad': '85',\n 'ipv6_allow_anycast_probe': 'enable',\n 'language': 'english',\n 'ldapconntimeout': '88',\n 'lldp_transmission': 'enable',\n 'log_ssl_connection': 'enable',\n 'log_uuid': 'disable',\n 'login_timestamp': 'enable',\n 'long_vdom_name': 'enable',\n 'management_vdom': 'test_value_94',\n 'max_dlpstat_memory': '95',\n 'max_route_cache_size': '96',\n 'mc_ttl_notchange': 'enable',\n 'memory_use_threshold_extreme': '98',\n 'memory_use_threshold_green': '99',\n 'memory_use_threshold_red': '100',\n 'miglog_affinity': 'test_value_101',\n 'miglogd_children': '102',\n 'multi_factor_authentication': 'optional',\n 'multicast_forward': 'enable',\n 'ndp_max_entry': '105',\n 'per_user_bwl': 'enable',\n 'policy_auth_concurrent': '107',\n 'post_login_banner': 'disable',\n 'pre_login_banner': 'enable',\n 'private_data_encryption': 'disable',\n 'proxy_auth_lifetime': 'enable',\n 'proxy_auth_lifetime_timeout': '112',\n 'proxy_auth_timeout': '113',\n 'proxy_cipher_hardware_acceleration': 'disable',\n 'proxy_kxp_hardware_acceleration': 'disable',\n 'proxy_re_authentication_mode': 'session',\n 'proxy_worker_count': '117',\n 'radius_port': '118',\n 'reboot_upon_config_restore': 'enable',\n 'refresh': '120',\n 'remoteauthtimeout': '121',\n 'reset_sessionless_tcp': 'enable',\n 'restart_time': 'test_value_123',\n 'revision_backup_on_logout': 'enable',\n 'revision_image_auto_backup': 'enable',\n 'scanunit_count': '126',\n 'security_rating_result_submission': 'enable',\n 'security_rating_run_on_schedule': 'enable',\n 'send_pmtu_icmp': 'enable',\n 'snat_route_change': 'enable',\n 'special_file_23_support': 'disable',\n 'ssd_trim_date': '132',\n 'ssd_trim_freq': 'never',\n 'ssd_trim_hour': '134',\n 'ssd_trim_min': '135',\n 'ssd_trim_weekday': 'sunday',\n 'ssh_cbc_cipher': 'enable',\n 'ssh_hmac_md5': 'enable',\n 'ssh_kex_sha1': 'enable',\n 'ssl_min_proto_version': 'SSLv3',\n 'ssl_static_key_ciphers': 'enable',\n 'sslvpn_cipher_hardware_acceleration': 'enable',\n 'sslvpn_kxp_hardware_acceleration': 'enable',\n 'sslvpn_max_worker_count': '144',\n 'sslvpn_plugin_version_check': 'enable',\n 'strict_dirty_session_check': 'enable',\n 'strong_crypto': 'enable',\n 'switch_controller': 'disable',\n 'switch_controller_reserved_network': 'test_value_149',\n 'sys_perf_log_interval': '150',\n 'tcp_halfclose_timer': '151',\n 'tcp_halfopen_timer': '152',\n 'tcp_option': 'enable',\n 'tcp_timewait_timer': '154',\n 'tftp': 'enable',\n 'timezone': '01',\n 'tp_mc_skip_policy': 'enable',\n 'traffic_priority': 'tos',\n 'traffic_priority_level': 'low',\n 'two_factor_email_expiry': '160',\n 'two_factor_fac_expiry': '161',\n 'two_factor_ftk_expiry': '162',\n 'two_factor_ftm_expiry': '163',\n 'two_factor_sms_expiry': '164',\n 'udp_idle_timer': '165',\n 'user_server_cert': 'test_value_166',\n 'vdom_admin': 'enable',\n 'vip_arp_range': 'unlimited',\n 'virtual_server_count': '169',\n 'virtual_server_hardware_acceleration': 'disable',\n 'wad_affinity': 'test_value_171',\n 'wad_csvc_cs_count': '172',\n 'wad_csvc_db_count': '173',\n 'wad_source_affinity': 'disable',\n 'wad_worker_count': '175',\n 'wifi_ca_certificate': 'test_value_176',\n 'wifi_certificate': 'test_value_177',\n 'wimax_4g_usb': 'enable',\n 'wireless_controller': 'enable',\n 'wireless_controller_port': '180'\n },\n 'vdom': 'root'}\n\n is_error, changed, response = fortios_system_global.fortios_system(input_data, fos_instance)\n\n expected_data = {\n 'admin-concurrent': 'enable',\n 'admin-console-timeout': '4',\n 'admin-hsts-max-age': '5',\n 'admin-https-pki-required': 'enable',\n 'admin-https-redirect': 'enable',\n 'admin-lockout-duration': '8',\n 'admin-lockout-threshold': '9',\n 'admin-login-max': '10',\n 'admin-maintainer': 'enable',\n 'admin-port': '12',\n 'admin-restrict-local': 'enable',\n 'admin-scp': 'enable',\n 'admin-server-cert': 'test_value_15',\n 'admin-sport': '16',\n 'admin-ssh-grace-time': '17',\n 'admin-ssh-password': 'enable',\n 'admin-ssh-port': '19',\n 'admin-ssh-v1': 'enable',\n 'admin-telnet-port': '21',\n 'admintimeout': '22',\n 'alias': 'test_value_23',\n 'allow-traffic-redirect': 'enable',\n 'anti-replay': 'disable',\n 'arp-max-entry': '26',\n 'asymroute': 'enable',\n 'auth-cert': 'test_value_28',\n 'auth-http-port': '29',\n 'auth-https-port': '30',\n 'auth-keepalive': 'enable',\n 'auth-session-limit': 'block-new',\n 'auto-auth-extension-device': 'enable',\n 'av-affinity': 'test_value_34',\n 'av-failopen': 'pass',\n 'av-failopen-session': 'enable',\n 'batch-cmdb': 'enable',\n 'block-session-timer': '38',\n 'br-fdb-max-entry': '39',\n 'cert-chain-max': '40',\n 'cfg-revert-timeout': '41',\n 'cfg-save': 'automatic',\n 'check-protocol-header': 'loose',\n 'check-reset-range': 'strict',\n 'cli-audit-log': 'enable',\n 'clt-cert-req': 'enable',\n 'compliance-check': 'enable',\n 'compliance-check-time': 'test_value_48',\n 'cpu-use-threshold': '49',\n 'csr-ca-attribute': 'enable',\n 'daily-restart': 'enable',\n 'device-identification-active-scan-delay': '52',\n 'device-idle-timeout': '53',\n 'dh-params': '1024',\n 'dnsproxy-worker-count': '55',\n 'dst': 'enable',\n 'endpoint-control-fds-access': 'enable',\n 'endpoint-control-portal-port': '58',\n 'failtime': '59',\n 'fds-statistics': 'enable',\n 'fds-statistics-period': '61',\n 'fortiextender': 'enable',\n 'fortiextender-data-port': '63',\n 'fortiextender-vlan-mode': 'enable',\n 'fortiservice-port': '65',\n 'gui-certificates': 'enable',\n 'gui-custom-language': 'enable',\n 'gui-date-format': 'yyyy/MM/dd',\n 'gui-device-latitude': 'test_value_69',\n 'gui-device-longitude': 'test_value_70',\n 'gui-display-hostname': 'enable',\n 'gui-ipv6': 'enable',\n 'gui-lines-per-page': '73',\n 'gui-theme': 'green',\n 'gui-wireless-opensecurity': 'enable',\n 'honor-df': 'enable',\n 'hostname': 'myhostname77',\n 'igmp-state-limit': '78',\n 'interval': '79',\n 'ip-src-port-range': 'test_value_80',\n 'ips-affinity': 'test_value_81',\n 'ipsec-asic-offload': 'enable',\n 'ipsec-hmac-offload': 'enable',\n 'ipsec-soft-dec-async': 'enable',\n 'ipv6-accept-dad': '85',\n 'ipv6-allow-anycast-probe': 'enable',\n 'language': 'english',\n 'ldapconntimeout': '88',\n 'lldp-transmission': 'enable',\n 'log-ssl-connection': 'enable',\n 'log-uuid': 'disable',\n 'login-timestamp': 'enable',\n 'long-vdom-name': 'enable',\n 'management-vdom': 'test_value_94',", "answers": [" 'max-dlpstat-memory': '95',"], "length": 753, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "4e6a34f4-2b2e-43d5-9946-89ebdbd24443", "reasoning": "The expected_data dictionary is being constructed to match the input_data keys transformed to the FortiOS API format. After the entry for 'management-vdom', the next key in the input_data is 'max_dlpstat_memory' which maps to 'max-dlpstat-memory' with value '95'. Therefore the next line should add this key-value pair to the dictionary.", "reasoning_model_answer": "'max-dlpstat-memory': '95',", "assistant_with_reasoning": "\nThe expected_data dictionary is being constructed to match the input_data keys transformed to the FortiOS API format. After the entry for 'management-vdom', the next key in the input_data is 'max_dlpstat_memory' which maps to 'max-dlpstat-memory' with value '95'. Therefore the next line should add this key-value pair to the dictionary.\n\n'max-dlpstat-memory': '95',", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.171, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 13181, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "'max-dlpstat-memory': '95',", "score": 0.87, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/*\n * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one\n * or more contributor license agreements. Licensed under the Elastic License\n * 2.0; you may not use this file except in compliance with the Elastic License\n * 2.0.\n */\npackage org.elasticsearch.xpack.core.ml.job.config;\n\nimport org.elasticsearch.ElasticsearchException;\nimport org.elasticsearch.common.io.stream.Writeable;\nimport org.elasticsearch.core.TimeValue;\nimport org.elasticsearch.common.util.CollectionUtils;\nimport org.elasticsearch.common.xcontent.XContentParser;\nimport org.elasticsearch.test.AbstractSerializingTestCase;\nimport org.elasticsearch.test.ESTestCase;\nimport org.elasticsearch.xpack.core.ml.job.messages.Messages;\nimport org.elasticsearch.xpack.core.ml.process.writer.RecordWriter;\n\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.TreeSet;\n\nimport static org.hamcrest.Matchers.equalTo;\nimport static org.hamcrest.Matchers.is;\n\npublic class AnalysisConfigTests extends AbstractSerializingTestCase {\n\n @Override\n protected AnalysisConfig createTestInstance() {\n return createRandomized().build();\n }\n\n public static AnalysisConfig.Builder createRandomized() {\n boolean isCategorization = randomBoolean();\n List detectors = new ArrayList<>();\n int numDetectors = randomIntBetween(1, 10);\n for (int i = 0; i < numDetectors; i++) {\n Detector.Builder builder = new Detector.Builder(\"count\", null);\n if (isCategorization) {\n builder.setByFieldName(\"mlcategory\");\n }\n builder.setPartitionFieldName(\"part\");\n detectors.add(builder.build());\n }\n AnalysisConfig.Builder builder = new AnalysisConfig.Builder(detectors);\n\n if (randomBoolean()) {\n TimeValue bucketSpan = TimeValue.timeValueSeconds(randomIntBetween(1, 1_000));\n builder.setBucketSpan(bucketSpan);\n\n // There is a dependency between model_prune_window and bucket_span: model_prune window must be\n // at least twice the size of bucket_span.\n builder.setModelPruneWindow(TimeValue.timeValueSeconds(randomIntBetween(2, 1_000) * bucketSpan.seconds()));\n\n }\n if (isCategorization) {\n builder.setCategorizationFieldName(randomAlphaOfLength(10));\n if (randomBoolean()) {\n builder.setCategorizationFilters(Arrays.asList(generateRandomStringArray(10, 10, false)));\n } else {\n CategorizationAnalyzerConfig.Builder analyzerBuilder = new CategorizationAnalyzerConfig.Builder();\n if (rarely()) {\n analyzerBuilder.setAnalyzer(randomAlphaOfLength(10));\n } else {\n if (randomBoolean()) {\n for (String pattern : generateRandomStringArray(3, 40, false)) {\n Map charFilter = new HashMap<>();\n charFilter.put(\"type\", \"pattern_replace\");\n charFilter.put(\"pattern\", pattern);\n analyzerBuilder.addCharFilter(charFilter);\n }\n }\n\n Map tokenizer = new HashMap<>();\n tokenizer.put(\"type\", \"pattern\");\n tokenizer.put(\"pattern\", randomAlphaOfLength(10));\n analyzerBuilder.setTokenizer(tokenizer);\n\n if (randomBoolean()) {\n for (String pattern : generateRandomStringArray(4, 40, false)) {\n Map tokenFilter = new HashMap<>();\n tokenFilter.put(\"type\", \"pattern_replace\");\n tokenFilter.put(\"pattern\", pattern);\n analyzerBuilder.addTokenFilter(tokenFilter);\n }\n }\n }\n builder.setCategorizationAnalyzerConfig(analyzerBuilder.build());\n }\n if (randomBoolean()) {\n boolean enabled = randomBoolean();\n builder.setPerPartitionCategorizationConfig(\n new PerPartitionCategorizationConfig(enabled, enabled && randomBoolean()));\n }\n }\n if (randomBoolean()) {\n builder.setLatency(TimeValue.timeValueSeconds(randomIntBetween(1, 1_000_000)));\n }\n if (randomBoolean()) {\n builder.setMultivariateByFields(randomBoolean());\n }\n\n builder.setInfluencers(Arrays.asList(generateRandomStringArray(10, 10, false)));\n\n return builder;\n }\n\n @Override\n protected Writeable.Reader instanceReader() {\n return AnalysisConfig::new;\n }\n\n @Override\n protected AnalysisConfig doParseInstance(XContentParser parser) {\n return AnalysisConfig.STRICT_PARSER.apply(parser, null).build();\n }\n\n public void testFieldConfiguration_singleDetector_notPreSummarised() {\n // Single detector, not pre-summarised\n Detector.Builder det = new Detector.Builder(\"max\", \"responsetime\");\n det.setByFieldName(\"airline\");\n det.setPartitionFieldName(\"sourcetype\");\n AnalysisConfig ac = createConfigWithDetectors(Collections.singletonList(det.build()));\n\n Set termFields = new TreeSet<>(Arrays.asList(\"airline\", \"sourcetype\"));\n Set analysisFields = new TreeSet<>(Arrays.asList(\"responsetime\", \"airline\", \"sourcetype\"));\n\n assertEquals(termFields.size(), ac.termFields().size());\n assertEquals(analysisFields.size(), ac.analysisFields().size());\n\n for (String s : ac.termFields()) {\n assertTrue(termFields.contains(s));\n }\n\n for (String s : termFields) {\n assertTrue(ac.termFields().contains(s));\n }\n\n for (String s : ac.analysisFields()) {\n assertTrue(analysisFields.contains(s));\n }\n\n for (String s : analysisFields) {\n assertTrue(ac.analysisFields().contains(s));\n }\n\n assertEquals(1, ac.fields().size());\n assertTrue(ac.fields().contains(\"responsetime\"));\n\n assertEquals(1, ac.byFields().size());\n assertTrue(ac.byFields().contains(\"airline\"));\n\n assertEquals(1, ac.partitionFields().size());\n assertTrue(ac.partitionFields().contains(\"sourcetype\"));\n\n assertNull(ac.getSummaryCountFieldName());\n\n // Single detector, pre-summarised\n analysisFields.add(\"summaryCount\");\n AnalysisConfig.Builder builder = new AnalysisConfig.Builder(ac);\n builder.setSummaryCountFieldName(\"summaryCount\");\n ac = builder.build();\n\n for (String s : ac.analysisFields()) {\n assertTrue(analysisFields.contains(s));\n }\n\n for (String s : analysisFields) {\n assertTrue(ac.analysisFields().contains(s));\n }\n\n assertEquals(\"summaryCount\", ac.getSummaryCountFieldName());\n assertEquals(1, ac.getDetectors().size());\n assertEquals(0, ac.getDetectors().get(0).getDetectorIndex());\n }\n\n public void testFieldConfiguration_multipleDetectors_NotPreSummarised() {\n // Multiple detectors, not pre-summarised\n List detectors = new ArrayList<>();\n\n Detector.Builder det = new Detector.Builder(\"metric\", \"metric1\");\n det.setByFieldName(\"by_one\");\n det.setPartitionFieldName(\"partition_one\");\n detectors.add(det.build());\n\n det = new Detector.Builder(\"metric\", \"metric2\");\n det.setByFieldName(\"by_two\");\n det.setOverFieldName(\"over_field\");\n detectors.add(det.build());\n\n det = new Detector.Builder(\"metric\", \"metric2\");\n det.setByFieldName(\"by_two\");\n det.setPartitionFieldName(\"partition_two\");\n detectors.add(det.build());\n\n AnalysisConfig.Builder builder = new AnalysisConfig.Builder(detectors);\n builder.setInfluencers(Collections.singletonList(\"Influencer_Field\"));\n AnalysisConfig ac = builder.build();\n\n Set termFields = new TreeSet<>(Arrays.asList(\n \"by_one\", \"by_two\", \"over_field\",\n \"partition_one\", \"partition_two\", \"Influencer_Field\"));\n Set analysisFields = new TreeSet<>(Arrays.asList(\n \"metric1\", \"metric2\", \"by_one\", \"by_two\", \"over_field\",\n \"partition_one\", \"partition_two\", \"Influencer_Field\"));\n\n assertEquals(termFields.size(), ac.termFields().size());\n assertEquals(analysisFields.size(), ac.analysisFields().size());\n\n for (String s : ac.termFields()) {\n assertTrue(s, termFields.contains(s));\n }\n\n for (String s : termFields) {\n assertTrue(s, ac.termFields().contains(s));\n }\n\n for (String s : ac.analysisFields()) {\n assertTrue(analysisFields.contains(s));\n }\n\n for (String s : analysisFields) {\n assertTrue(ac.analysisFields().contains(s));\n }\n\n assertEquals(2, ac.fields().size());\n assertTrue(ac.fields().contains(\"metric1\"));\n assertTrue(ac.fields().contains(\"metric2\"));\n\n assertEquals(2, ac.byFields().size());\n assertTrue(ac.byFields().contains(\"by_one\"));\n assertTrue(ac.byFields().contains(\"by_two\"));\n\n assertEquals(1, ac.overFields().size());\n assertTrue(ac.overFields().contains(\"over_field\"));\n\n assertEquals(2, ac.partitionFields().size());\n assertTrue(ac.partitionFields().contains(\"partition_one\"));\n assertTrue(ac.partitionFields().contains(\"partition_two\"));\n\n assertNull(ac.getSummaryCountFieldName());\n\n assertEquals(3, ac.getDetectors().size());\n int expectedDetectorIndex = 0;\n for (Detector detector : ac.getDetectors()) {\n assertEquals(expectedDetectorIndex++, detector.getDetectorIndex());\n }\n }\n\n public void testBuild_GivenMlCategoryUsedAsByFieldButNoCategorizationFieldName() {\n Detector.Builder detector = new Detector.Builder();\n detector.setFunction(\"count\");\n detector.setByFieldName(\"mlcategory\");\n AnalysisConfig.Builder ac = new AnalysisConfig.Builder(Collections.singletonList(detector.build()));\n ac.setCategorizationFieldName(null);\n\n ElasticsearchException e = expectThrows(ElasticsearchException.class, ac::build);\n assertThat(e.getMessage(), equalTo(\"categorization_field_name must be set for mlcategory to be available\"));\n }\n\n public void testBuild_GivenMlCategoryUsedAsOverFieldButNoCategorizationFieldName() {\n Detector.Builder detector = new Detector.Builder();\n detector.setFunction(\"count\");\n detector.setOverFieldName(\"mlcategory\");\n AnalysisConfig.Builder ac = new AnalysisConfig.Builder(Collections.singletonList(detector.build()));\n ac.setCategorizationFieldName(null);\n\n ElasticsearchException e = expectThrows(ElasticsearchException.class, ac::build);\n assertThat(e.getMessage(), equalTo(\"categorization_field_name must be set for mlcategory to be available\"));\n }\n\n public void testBuild_GivenMlCategoryUsedAsPartitionFieldButNoCategorizationFieldName() {\n Detector.Builder detector = new Detector.Builder();\n detector.setFunction(\"count\");\n detector.setPartitionFieldName(\"mlcategory\");\n AnalysisConfig.Builder ac = new AnalysisConfig.Builder(Collections.singletonList(detector.build()));\n ac.setCategorizationFieldName(null);\n\n ElasticsearchException e = expectThrows(ElasticsearchException.class, ac::build);\n assertThat(e.getMessage(), equalTo(\"categorization_field_name must be set for mlcategory to be available\"));\n }\n\n public void testBuild_GivenCategorizationFieldNameButNoUseOfMlCategory() {\n Detector.Builder detector = new Detector.Builder();\n detector.setFunction(\"count\");\n detector.setOverFieldName(\"foo\");\n AnalysisConfig.Builder ac = new AnalysisConfig.Builder(Collections.singletonList(detector.build()));\n ac.setCategorizationFieldName(\"msg\");\n\n ElasticsearchException e = expectThrows(ElasticsearchException.class, ac::build);", "answers": [" assertThat(e.getMessage(), equalTo(\"categorization_field_name is set but mlcategory is \" +"], "length": 705, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "e3e86520-ea13-46d2-a177-b886ff116b95", "reasoning": "The method testBuild_GivenCategorizationFieldNameButNoUseOfMlCategory creates a detector without any mlcategory fields, then sets a categorization field name and expects an ElasticsearchException when building. Following the pattern of earlier tests, the next line should assert that the exception message matches the expected validation error about categorization_field_name being set without mlcategory usage.", "reasoning_model_answer": "assertThat(e.getMessage(), equalTo(\"categorization_field_name must not be set unless mlcategory is used\"));", "assistant_with_reasoning": "\nThe method testBuild_GivenCategorizationFieldNameButNoUseOfMlCategory creates a detector without any mlcategory fields, then sets a categorization field name and expects an ElasticsearchException when building. Following the pattern of earlier tests, the next line should assert that the exception message matches the expected validation error about categorization_field_name being set without mlcategory usage.\n\nassertThat(e.getMessage(), equalTo(\"categorization_field_name must not be set unless mlcategory is used\"));", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.839, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 12524, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "assertThat(e.getMessage(), equalTo(\"categorization_field_name must not be set unless mlcategory is used\"));", "score": 0.83, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "# -*- coding: UTF-8 -*-\n__all__ = ['agregation']\n\nimport numpy as np\nimport scipy\nfrom scipy.sparse import csr_matrix, coo_matrix, isspmatrix_csr, isspmatrix_csc\nfrom pyamg.relaxation import gauss_seidel\n#from pyamg.util.linalg import residual_norm\n# ...\ntry:\n from petsc4py import PETSc\n importPETSc=True\nexcept ImportError:\n importPETSc=False\n# ...\nfrom scipy.sparse.linalg import LinearOperator\n\nnorm = np.linalg.norm\n\n# ...\ndef residual_norm(A, x, b):\n \"\"\"Compute ||b - A*x||\"\"\"\n\n return norm(b - A.dot(x))\n# ...\n\n\nclass level:\n \"\"\"Stores one level of the multigrid hierarchy\n\n All level objects will have an 'A' attribute referencing the matrix\n of that level. All levels, except for the coarsest level, will\n also have 'P' and 'R' attributes referencing the prolongation and\n restriction operators that act between each level and the next\n coarser level.\n\n Attributes\n ----------\n A : csr_matrix\n Problem matrix for Ax=b\n R : csr_matrix\n Restriction matrix between levels (often R = P.T)\n P : csr_matrix\n Prolongation or Interpolation matrix.\n\n Notes\n -----\n The functionality of this class is a struct\n \"\"\"\n def __init__(self, withscipy=False, withPETSc=False):\n from pigasus.fem.solver import solver\n# from pigasus.solver.solver import solver\n if withscipy:\n from pigasus.fem.matrix import matrix\n self.R = None\n self.A = None\n self.P = None\n self._A = matrix()\n self.slv = solver(matrix=self._A)\n else:\n from pigasus.fem.matrix import matrix\n from pigasus.fem.constants import SPM_SOLVER_BASIC_CG, SPM_SOLVER_BASIC_GS\n self.R = matrix()\n self.A = matrix()\n self.P = matrix()\n #\n if withPETSc:\n self.slv = None\n self.smt = None\n# self.smt = solver(matrix=self.A, solver=SPM_SOLVER_BASIC_GS)\n else:\n slvInfo = {}\n slvInfo['solver'] = SPM_SOLVER_BASIC_CG\n self.slv = solver(matrix=self.A, solverInfo=slvInfo)\n\n smtInfo = {}\n smtInfo['solver'] = SPM_SOLVER_BASIC_GS\n self.smt = solver(matrix=self.A, solverInfo=smtInfo)\n\n self.withscipy = withscipy\n self.withPETSc = withPETSc\n\n def set(self, A, R, P):\n \"\"\"\n sets the scipy matrices A, R, P into pigasus\n \"\"\"\n if self.withscipy:\n self.R =R\n self.A =A\n self.P =P\n self._A.set(A)\n else:\n self.R.set(R)\n self.A.set(A)\n self.P.set(P)\n self._A = A # TODO: to remove. needed for the moment for the smoother\n if self.withPETSc and importPETSc:\n self.A_petsc = PETSc.Mat().createAIJ(size=A.shape,csr=(A.indptr,A.indices,A.data))\n # ...\n\n # Initialize ksp solver.\n self.ksp_slv = PETSc.KSP().create()\n self.ksp_slv.setOperators(self.A_petsc)\n self.ksp_slv.setFromOptions()\n self.ksp_slv.setType(PETSc.KSP.Type.CG)\n\n# # Initialize ksp smoother.\n# self.ksp_smt = PETSc.KSP().create()\n# self.ksp_smt.setOperators(self.A_petsc)\n# self.ksp_smt.setFromOptions()\n# self.ksp_smt.setType(PETSc.KSP.Type.RICHARDSON)\n\n def solve(self, b, maxiter=6000, tol=1.e-14):\n if self.withPETSc and importPETSc:\n _b = PETSc.Vec().createWithArray(b, comm=PETSc.COMM_SELF)\n _x = PETSc.Vec().createWithArray(np.zeros_like(b), comm=PETSc.COMM_SELF)\n\n self.ksp_slv.rtol = tol\n# self.ksp_slv.setConvergenceHistory()\n self.ksp_slv.solve(_b, _x)\n return _x.getArray()\n else:\n return self.slv.solve(b, guess=np.zeros_like(b) \\\n , maxiter=maxiter, eps=tol)\n\n def smoother(self, x, b, nu, tol=1.e-10):\n if self.withscipy:\n gauss_seidel(self.A, x, b, iterations=nu)\n return x\n else:\n# if self.withPETSc and importPETSc:\n if False:\n _b = PETSc.Vec().createWithArray(b, comm=PETSc.COMM_SELF)\n _x = PETSc.Vec().createWithArray(np.zeros_like(b), comm=PETSc.COMM_SELF)\n\n self.ksp_smt.rtol = tol\n self.ksp_smt.max_it = nu\n # self.ksp_smt.setConvergenceHistory()\n self.ksp_smt.solve(_b, _x)\n return _x.getArray()\n else:\n gauss_seidel(self._A, x, b, iterations=nu) # TODO: to remove\n return x\n# return self.smt.solve(b, guess=np.zeros_like(b) \\\n# , maxiter=nu, eps=tol)\n\nclass agregation(object):\n\n def __init__(self, list_geometry, gamma, nu1, nu2 \\\n , smoother=None, coarse_solver=None \\\n , withscipy=False, withPETSc=False):\n \"\"\"Creates a geometric multigrid for the matrix list_A[-1]\n\n Parameters\n ----------\n list_A : is a list of csr_matrix or pigasus-matrix. list_A[0] is on the finest grid\n list_geometry : list of geometries [-1] -> the finest geometry and [0] -> the coarse\n nlevels : the number of subdomains levels\n\n Returns\n -------\n mg : the geometric multigrid\n\n Examples\n --------\n >>> from scipy.sparse import csr_matrix\n >>> from pigasus.gallery import EllipticPDE\n nrb_H = self.geometry_H[0]\n nrb_h = self.geometry_h[0]\n\n\n knots_H = nrb_H.knots[0]\n knots_h = nrb_h.knots[0]\n\n n = nrb_H.shape[0]\n p = nrb_H.degree[0]\n\n list_r = [r for r in knots_h if r not in knots_H]\n\n See Also\n --------\n TODO\n \"\"\"\n # TODO : for the moment we only treate 1-patch geometries\n self.withscipy = withscipy\n self.withPETSc = withPETSc\n\n self.geometries = list_geometry\n self.dim = self.geometries[0].dim\n self.nlevels = len(self.geometries)-1\n self.coarse_solver = coarse_solver\n self.smoother = smoother\n self.gamma = gamma\n self.nu1 = nu1\n self.nu2 = nu2\n self.nloop = 1\n self.levels = []\n for i in range(0, len(self.geometries)):\n self.levels.append(level(withscipy=withscipy))\n\n self.list_allresiduals = [] # list of residuals for each step\n self.list_coarseresiduals = []\n #-----------------------------------\n\n #-----------------------------------\n def initialize(self, A, list_A=None, list_DirFaces=None, GalerkinCoarseGrid=True):\n from scipy.sparse import identity as Id\n from pigasus.fem.common_obj import isMatrix\n\n if isMatrix(A):\n self.A = A.get()\n else:\n self.A = A\n\n if list_A is not None:\n self.list_A = list_A\n list_A = self.list_A[::-1]\n\n n,m = self.A.shape\n\n ilvl = 0\n lvl = self.levels[ilvl]\n lvl.set(self.A, Id(n), Id(n))\n\n geometries = self.geometries[::-1]\n for (geo_h, geo_H) in zip(geometries[:-1], geometries[1:]):\n ilvl += 1\n # ... interpolator\n P = self.constructInterpolationMatrix(geo_H, geo_h, list_DirFaces=list_DirFaces)\n # ... restriction\n list_H, list_h = self.compute_H(geo_H, geo_h)\n r = list_h[0]/list_H[0]\n R = P.transpose().tocsr()\n R *= r\n# print \"Interpolator : \", P.shape\n# print \"Restrictor : \", R.shape\n # ... the coarse system\n if GalerkinCoarseGrid:\n# print \"Galerkin coarse grid operator has been initialized\"\n if self.withscipy:\n A_h = self.levels[ilvl-1].A\n else:\n A_h = self.levels[ilvl-1].A.get()\n# print R.shape, A_h.shape, P.shape\n A_H = R * A_h * P\n# print A_h.shape, A_H.shape\n# A_H = A_H.tocsr()\n else:\n if self.withscipy:\n A_H = list_A[i]\n else:\n A_H = list_A[i].get()\n\n lvl = self.levels[ilvl]\n lvl.set(A_H, R, P)\n\n self.levels = self.levels[::-1]\n A = self.levels[-1].A.get()\n self.dtype = A.dtype\n self.shape = A.shape\n #-----------------------------------\n\n #-----------------------------------\n def interpolation(self, level, vH):\n P = self.levels[level].P\n vh = P.dot(vH)\n return vh\n #-----------------------------------\n\n #-----------------------------------\n def restriction(self, level, vh):", "answers": [" R = self.levels[level].R"], "length": 803, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "0d438f1d-f2d7-45ee-b5a7-864eab6a4ce1", "reasoning": "The restriction method should mirror the interpolation method but using the restriction operator R. The first operation inside the method is to retrieve the R matrix from the appropriate level, so the next line is assigning R = self.levels[level].R.", "reasoning_model_answer": "R = self.levels[level].R", "assistant_with_reasoning": "\nThe restriction method should mirror the interpolation method but using the restriction operator R. The first operation inside the method is to retrieve the R matrix from the appropriate level, so the next line is assigning R = self.levels[level].R.\n\nR = self.levels[level].R", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 2.196, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 9104, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "R = self.levels[level].R", "score": 0.86, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "#!/usr/bin/env python\n\"\"\"\n@package pyon.agent.common_agent\n@file pyon/agent/common_agent.py\n@author Edward Hunter\n@brief Common base class for ION resource agents.\n\"\"\"\n\n__author__ = 'Edward Hunter'\n\n\n\n# Pyon imports.\nfrom pyon.core import bootstrap\nfrom pyon.core.bootstrap import IonObject\nfrom pyon.event.event import EventPublisher\nfrom pyon.util.log import log\nfrom pyon.util.containers import get_ion_ts\nfrom pyon.ion.resource import RT, PRED, OT, LCS\nfrom pyon.ion.state import StatefulProcessMixin\n\nfrom pickle import dumps, loads\nimport json\n\n# Pyon exceptions.\nfrom pyon.core.exception import IonException\nfrom pyon.core.exception import BadRequest\nfrom pyon.core.exception import Conflict\nfrom pyon.core.exception import NotFound\nfrom pyon.core.exception import ServerError\n\n# Interface imports.\nfrom interface.services.iresource_agent import BaseResourceAgent\nfrom interface.services.iresource_agent import ResourceAgentProcessClient\nfrom interface.objects import CapabilityType\nfrom interface.objects import ResourceAgentExecutionStatus\nfrom interface.services.coi.iresource_registry_service import ResourceRegistryServiceProcessClient\n\n#Agent imports\nfrom pyon.agent.instrument_fsm import InstrumentFSM, ThreadSafeFSM\nfrom pyon.agent.instrument_fsm import FSMStateError\nfrom pyon.agent.instrument_fsm import FSMCommandUnknownError\nfrom pyon.agent.common import BaseEnum\n\n\nclass UserAgent():\n pass\n\nclass ResourceAgentState(BaseEnum):\n \"\"\"\n Resource agent common states.\n \"\"\"\n POWERED_DOWN = 'RESOURCE_AGENT_STATE_POWERED_DOWN'\n UNINITIALIZED = 'RESOURCE_AGENT_STATE_UNINITIALIZED'\n INACTIVE = 'RESOURCE_AGENT_STATE_INACTIVE'\n IDLE = 'RESOURCE_AGENT_STATE_IDLE'\n STOPPED = 'RESOURCE_AGENT_STATE_STOPPED'\n COMMAND = 'RESOURCE_AGENT_STATE_COMMAND'\n STREAMING = 'RESOURCE_AGENT_STATE_STREAMING'\n TEST = 'RESOURCE_AGENT_STATE_TEST'\n CALIBRATE = 'RESOURCE_AGENT_STATE_CALIBRATE'\n DIRECT_ACCESS = 'RESOUCE_AGENT_STATE_DIRECT_ACCESS'\n BUSY = 'RESOURCE_AGENT_STATE_BUSY'\n LOST_CONNECTION = 'RESOURCE_AGENT_STATE_LOST_CONNECTION'\n ACTIVE_UNKNOWN = 'RESOURCE_AGENT_STATE_ACTIVE_UNKNOWN'\n\nclass ResourceAgentEvent(BaseEnum):\n \"\"\"\n Resource agent common events.\n \"\"\"\n ENTER = 'RESOURCE_AGENT_EVENT_ENTER'\n EXIT = 'RESOURCE_AGENT_EVENT_EXIT'\n POWER_UP = 'RESOURCE_AGENT_EVENT_POWER_UP'\n POWER_DOWN = 'RESOURCE_AGENT_EVENT_POWER_DOWN'\n INITIALIZE = 'RESOURCE_AGENT_EVENT_INITIALIZE'\n RESET = 'RESOURCE_AGENT_EVENT_RESET'\n GO_ACTIVE = 'RESOURCE_AGENT_EVENT_GO_ACTIVE'\n GO_INACTIVE = 'RESOURCE_AGENT_EVENT_GO_INACTIVE'\n RUN = 'RESOURCE_AGENT_EVENT_RUN'\n CLEAR = 'RESOURCE_AGENT_EVENT_CLEAR'\n PAUSE = 'RESOURCE_AGENT_EVENT_PAUSE'\n RESUME = 'RESOURCE_AGENT_EVENT_RESUME'\n GO_COMMAND = 'RESOURCE_AGENT_EVENT_GO_COMMAND'\n GO_DIRECT_ACCESS = 'RESOURCE_AGENT_EVENT_GO_DIRECT_ACCESS'\n EXECUTE_DIRECT_ACCESS = 'RESOURCE_AGENT_EXECUTE_DIRECT_ACCESS'\n GET_RESOURCE = 'RESOURCE_AGENT_EVENT_GET_RESOURCE'\n SET_RESOURCE = 'RESOURCE_AGENT_EVENT_SET_RESOURCE'\n EXECUTE_RESOURCE = 'RESOURCE_AGENT_EVENT_EXECUTE_RESOURCE'\n GET_RESOURCE_STATE = 'RESOURCE_AGENT_EVENT_GET_RESOURCE_STATE'\n GET_RESOURCE_CAPABILITIES = 'RESOURCE_AGENT_EVENT_GET_RESOURCE_CAPABILITIES'\n DONE = 'RESOURCE_AGENT_EVENT_DONE'\n PING_RESOURCE = 'RESOURCE_AGENT_PING_RESOURCE'\n LOST_CONNECTION = 'RESOURCE_AGENT_EVENT_LOST_CONNECTION'\n AUTORECONNECT = 'RESOURCE_AGENT_EVENT_AUTORECONNECT'\n GET_RESOURCE_SCHEMA = 'RESOURCE_AGENT_EVENT_GET_RESOURCE_SCHEMA'\n CHANGE_STATE_ASYNC = 'RESOURCE_AGENT_EVENT_CHANGE_STATE_ASYNC'\n\nclass ResourceAgentStreamStatus(BaseEnum):\n \"\"\"\n Status values for stream monitors and alerts.\n \"\"\"\n ALL_CLEAR = 'RESOURCE_AGENT_STREAM_STATUS_ALL_CLEAR'\n WARNING = 'RESOURCE_AGENT_STREAM_STATUS_WARNING'\n ALARM = 'RESOURCE_AGENT_STREAM_STATUS_ALARM'\n\nclass ResourceAgent(BaseResourceAgent, StatefulProcessMixin):\n \"\"\"\n A resource agent is an ION process of type \"agent\" that exposes the standard\n resource agent service interface. This base class captures the mechanisms\n common to all resource agents and is subclassed with implementations\n specific for instrument agents, user agents, etc.\n Pointless comment.\n \"\"\"\n\n ##############################################################\n # Class variables.\n ##############################################################\n\n # ION process type.\n process_type = \"agent\"\n\n # Override in subclass to publish specific types of events.\n COMMAND_EVENT_TYPE = \"ResourceCommandEvent\"\n\n # Override in subclass to set specific origin type.\n ORIGIN_TYPE = \"Resource\"\n\n # Override in subclass to expose agent capabilities.\n CAPABILITIES = []\n\n ##############################################################\n # Constructor and ION init/deinit.\n ##############################################################\n\n def __init__(self, *args, **kwargs):\n \"\"\"\n Initialize superclass and base class variables.\n \"\"\"\n\n # Base class constructor.\n super(ResourceAgent, self).__init__(*args, **kwargs)\n\n # The ID of the AgentInstance subtype resource object.\n self.agent_id = None\n\n # The ID of the AgentDefinition subtype resource object.\n self.agent_def_id = None\n\n # The ID of the target resource object, e.g. a device id.\n self.resource_id = None\n \n # The Resource Type of the target resource object -\n # ex. InstrumentDevice or PlatformDevice\n # Must be set by Implementing Class \n self.resource_type = None\n\n # Event publisher.\n self._event_publisher = None\n\n # An example agent parameter.\n self.aparam_example = None\n\n # Override in derived class to set initial state of set in\n # config.\n self._initial_state = None\n \n # Construct the default state machine.\n # This is overridden in derived classes and calls base class with\n # state and event parameters.\n self._construct_fsm()\n \n self._proc_state = {}\n self._proc_state_changed = False\n \n # Resource schema.\n self._resource_schema = {}\n \n # Agent schema.\n self._agent_schema = {}\n \n def on_init(self):\n \"\"\"\n ION on_init initializer called once the process exists.\n \"\"\"\n \n # The registrar to create publishers.\n agent_info = self.CFG.get('agent', None)\n if not agent_info:\n log.error('No agent config found.')\n else:\n self.resource_id = agent_info.get('resource_id', '')\n \n log.info(\"Resource Agent on_init. name=%s, resource_id=%s\",\n self._proc_name, self.resource_id)\n\n # Create event publisher.\n self._event_publisher = EventPublisher()\n\n # Retrieve stored states.\n try:\n state = self._get_state('agent_state') or ResourceAgentState.UNINITIALIZED\n prev_state = self._get_state('agent_state') or ResourceAgentState.UNINITIALIZED\n\n except Exception as ex:\n log.error('Exception retrieving agent state in on_init: %s.', str(ex))\n log.exception('Exception retrieving agent state in on_init.')\n state = ResourceAgentState.UNINITIALIZED\n prev_state = ResourceAgentState.UNINITIALIZED\n else:\n log.info('Got agent state: %s', state)\n log.info('Got agent prior state: %s', prev_state)\n\n # Load state.\n try:\n self._load_state()\n except Exception as ex:\n log.error('Error loading state in on_init: %s', str(ex))\n log.exception('Error loading state in on_init.')\n\n # Start state machine.\n self._initial_state = self.CFG.get('initial_state', None) or self._initial_state", "answers": [" self._fsm.start(self._initial_state)"], "length": 679, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "ac22967a-dce5-435a-9534-4b654320a01d", "reasoning": "The code is in the on_init method of ResourceAgent. It just set self._initial_state to a config value or the existing default. The next logical step is to start the finite state machine with that initial state, using the _fsm attribute created earlier. Therefore the next line should invoke the FSM start method with the initial state.", "reasoning_model_answer": "self._fsm.start(self._initial_state)", "assistant_with_reasoning": "\nThe code is in the on_init method of ResourceAgent. It just set self._initial_state to a config value or the existing default. The next logical step is to start the finite state machine with that initial state, using the _fsm attribute created earlier. Therefore the next line should invoke the FSM start method with the initial state.\n\nself._fsm.start(self._initial_state)", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.253, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 8002, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "self._fsm.start(self._initial_state)", "score": 0.9, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "\"\"\"A module to receive data from UR CB2 robots.\"\"\"\n\n# The MIT License (MIT)\n#\n# Copyright (c) 2016 GTRC.\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\n\nimport socket\nimport struct\nimport array\nimport threading\n\n\nclass URReceiver(object):\n \"\"\"A class to receive and process data from a UR Robot\n\n The receiving and processing can be run in a separate thread by calling\n start(). The stop() command must be called before exiting to halt the\n additional thread. Alternatively, receive(), decode(), and\n print_parsed_data() can be called in sequence in order to receive,\n decode, and print data. One should not call receive(), decode(), or any\n of the print methods, if a separate thread is being used. You should\n never write to any of the data fields externally, however you can read\n from them. Python's atomic read/write architecture should prevent you\n from getting any half baked results from basic types, for all lists and\n tuples, you must lock using lock (recommend that you use `with lock:`\n paradigm.\n\n Attributes:\n clean_data: Double array of length 101 for all of the data returned by\n the robot\n raw_data: String of complete raw data packet\n __socket: The socket for communications\n clean_packets: The Integer number of packets which have been received\n cleanly\n stub_packets: The Integer number of packets which have been received\n as stubs\n received: The total Integer number of complete data sets which have\n been received\n waiting_data: String to hold incomplete data sets\n new_data: Boolean whether new data is available for processing\n time: Double of time elapsed since the controller was started\n target_joint_positions: 6 member Double list of target joint positions\n target_joint_velocities: 6 member Double list of target joint velocities\n target_joint_accelerations: 6 member Double list of target joint\n accelerations\n target_joint_currents: 6 member Double list of target joint currents\n target_joint_moments: 6 member Double list of target joint moments as\n torques\n actual_joint_positions: 6 member Double list of actual joint positions\n actual_joint_velocities: 6 member Double list of actual joint velocities\n actual_joint_currents: 6 member Double list of actual joint currents\n tool_accelerometer: 3 member Double list of ool x,y and z accelerometer\n values (software version 1.7)\n force_tcp: 6 member Double list of generalised forces in the TCP\n position: 6 member Double list of cartesian coordinates of the tool:\n (x,y,z,rx,ry,rz), where rx, ry and rz is a rotation vector\n representation of the tool orientation\n tool_speed: 6 member Double list of speed of the tool given in cartesian\n coordinates\n digital_inputs: Current state of the digital inputs. NOTE: these are\n bits encoded as int64_t, e.g. a value of 5 corresponds to bit 0 and\n bit 2 set high\n joint_temperature: 6 member Double list of temperature of each joint in\n degrees celsius\n controller_period: Double of controller real time thread execution time\n robot_control_mode: Double of robot control mode (see\n PolyScopeProgramServer on the \"How to\" page\n joint_control_modes: 6 member Double list of joint control modes (see\n PolyScopeProgramServer on the \"How to\" page) (only from software\n version 1.8 and on)\n run: Boolean on whether to run or not\n __receiving_thread: Thread object for running the receiving and parsing\n loops\n verbose: Boolean defining whether or not to print data\n lock: A threading lock which is used to protect data from race\n conditions\n _is_stopped: A boolean specifying whether the robot is stopped\n \"\"\"\n\n # Format specifier:\n # ! : network (big endian)\n # I : unsigned int, message size\n # 85d : 85 doubles\n # q : int64_t for digital inputs\n # 15d : 15 doubles\n\n #: Format spec for complete data packet\n format = struct.Struct('! I 85d q 15d')\n #: The format spec for the packet length field\n formatLength = struct.Struct('! I')\n #: The width to be given to name items when printing out\n name_width = 30\n #: The precision for printing data\n precision = 7\n double_format_string = \"{:+0\"+str(precision+4)+\".\"+str(precision)+\"f}\"\n\n def __init__(self, open_socket, verbose=False):\n \"\"\"Construct a UR Robot connection given connection parameters\n\n Args:\n open_socket (socket.socket): The socket to use for communications.\n verbose (bool): Whether to print received data in main loop\n \"\"\"\n self.clean_data = array.array('d', [0] * 101)\n self.raw_data = ''\n self.__socket = open_socket\n self.clean_packets = 0\n self.stub_packets = 0\n self.received = 0\n self.waiting_data = ''\n self.new_data = False\n self.time = 0.0", "answers": [" self.target_joint_positions = [0.0]*6"], "length": 855, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "185e9811-da2e-4d64-bac2-35c8b0e56691", "reasoning": "In the __init__ method, after initializing simple scalar attributes like self.time, the code proceeds to set up the various data fields described in the class docstring. The first of those fields is the list of target joint positions, which should be a 6‑element list of zeros. Therefore the next line creates this list.", "reasoning_model_answer": "self.target_joint_positions = [0.0] * 6", "assistant_with_reasoning": "\nIn the __init__ method, after initializing simple scalar attributes like self.time, the code proceeds to set up the various data fields described in the class docstring. The first of those fields is the list of target joint positions, which should be a 6‑element list of zeros. Therefore the next line creates this list.\n\nself.target_joint_positions = [0.0] * 6", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.234, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 6251, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "self.target_joint_positions = [0.0] * 6", "score": 0.88, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "using System;\n/*\n * $Id: Inflate.cs,v 1.2 2008-05-10 09:35:40 bouncy Exp $\n *\nCopyright (c) 2000,2001,2002,2003 ymnk, JCraft,Inc. All rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n 1. Redistributions of source code must retain the above copyright notice,\n this list of conditions and the following disclaimer.\n\n 2. Redistributions in binary form must reproduce the above copyright \n notice, this list of conditions and the following disclaimer in \n the documentation and/or other materials provided with the distribution.\n\n 3. The names of the authors may not be used to endorse or promote products\n derived from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,\nINCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND\nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,\nINC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,\nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\nLIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,\nOR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\nLIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\nNEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,\nEVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n/*\n * This program is based on zlib-1.1.3, so all credit should go authors\n * Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu)\n * and contributors of zlib.\n */\n\nnamespace Org.BouncyCastle.Utilities.Zlib\n{\n\n public enum InflateMode : int\n {\n /// \n ///waiting for method byte\n /// \n METHOD = 0,\n /// \n /// waiting for flag byte\n /// \n FLAG = 1,\n /// \n /// four dictionary check bytes to go\n /// \n DICT4 = 2,\n /// \n /// three dictionary check bytes to go\n /// \n DICT3 = 3,\n /// \n /// two dictionary check bytes to go\n /// \n DICT2 = 4,\n /// \n /// one dictionary check byte to go\n /// \n DICT1 = 5,\n /// \n /// waiting for inflateSetDictionary\n /// \n DICT0 = 6,\n /// \n /// decompressing blocks\n /// \n BLOCKS = 7,\n /// \n /// four check bytes to go\n /// \n CHECK4 = 8,\n /// \n /// three check bytes to go\n /// \n CHECK3 = 9,\n /// \n /// two check bytes to go\n /// \n CHECK2 = 10,\n /// \n /// one check byte to go\n /// \n CHECK1 = 11,\n /// \n /// finished check, done\n /// \n DONE = 12,\n /// \n /// got an error--stay here\n /// \n BAD = 13\n }\n\n internal sealed class Inflate\n {\n /// \n /// 32K LZ77 window\n /// \n private const int MAX_WBITS = 15;\n\n /// \n /// Preset dictionary flag in zlib header\n /// \n private const int PRESET_DICT = 0x20;\n\n private const int Z_DEFLATED = 8;\n\n private static readonly byte[] mark = { (byte)0, (byte)0, (byte)0xff, (byte)0xff };\n\n /// \n /// if FLAGS, method byte\n /// \n private int method;\n\n /// \n /// Computed check value\n /// \n private long[] was = new long[1];\n\n /// \n /// The stream check value\n /// \n private long need;\n\n /// \n /// if BAD, inflateSync's marker bytes count\n /// \n private int marker;\n\n // mode independent information\n /// \n /// Flag for no wrapper\n /// \n private int nowrap;\n \n /// \n /// log2(window size) (8..15, defaults to 15)\n /// \n private int wbits;\n\n /// \n /// Current inflate_blocks state\n /// \n private InfBlocks blocks;\n\n /// \n /// Gets the current inflate mode.\n /// \n /// \n /// The mode.\n /// \n internal InflateMode Mode { get; private set; }\n\n internal ZLibStatus InflateReset(ZStream z)\n {\n if (z == null || z.istate == null) return ZLibStatus.Z_STREAM_ERROR;\n\n z.total_in = z.total_out = 0;\n z.msg = null;\n z.istate.Mode = z.istate.nowrap != 0 ? InflateMode.BLOCKS : InflateMode.METHOD;\n z.istate.blocks.Reset(z, null);\n return ZLibStatus.Z_OK;\n }\n\n internal ZLibStatus InflateEnd(ZStream z)\n {\n if (blocks != null)\n blocks.free(z);\n blocks = null;\n // ZFREE(z, z->state);\n return ZLibStatus.Z_OK;\n }\n\n internal ZLibStatus InflateInit(ZStream z, int w)\n {\n z.msg = null;\n blocks = null;\n\n // handle undocumented nowrap option (no zlib header or check)\n nowrap = 0;\n if (w < 0)\n {\n w = -w;\n nowrap = 1;\n }\n\n // set window size\n if (w < 8 || w > 15)\n {\n InflateEnd(z);", "answers": [" return ZLibStatus.Z_STREAM_ERROR;"], "length": 724, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "00d6bcc4-02fb-475e-a356-125dec12b730", "reasoning": "The code is inside InflateInit, checking the window size parameter. If w is outside the allowed range (8..15) the function should clean up by calling InflateEnd(z) and then signal an error. In zlib the corresponding error is Z_STREAM_ERROR, so the next line should return that status.", "reasoning_model_answer": "return ZLibStatus.Z_STREAM_ERROR;", "assistant_with_reasoning": "\nThe code is inside InflateInit, checking the window size parameter. If w is outside the allowed range (8..15) the function should clean up by calling InflateEnd(z) and then signal an error. In zlib the corresponding error is Z_STREAM_ERROR, so the next line should return that status.\n\nreturn ZLibStatus.Z_STREAM_ERROR;", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.496, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 5923, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "return ZLibStatus.Z_STREAM_ERROR;", "score": 0.8, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "// ALIADA - Automatic publication under Linked Data paradigm\n// of library and museum data\n//\n// Component: aliada-shared\n// Responsible: ALIADA Consortium\npackage eu.aliada.shared.rdfstore;\n\nimport static eu.aliada.shared.Strings.isNotNullAndNotEmpty;\n\nimport java.io.File;\nimport java.io.FileInputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.OutputStream;\nimport java.net.HttpURLConnection;\nimport java.net.URL;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.ArrayList;\nimport java.io.BufferedReader;\nimport java.io.InputStreamReader;\n\nimport org.apache.commons.codec.binary.Base64;\nimport org.apache.jena.atlas.web.auth.HttpAuthenticator;\nimport org.apache.jena.atlas.web.auth.SimpleAuthenticator;\n\nimport com.hp.hpl.jena.update.UpdateExecutionFactory;\nimport com.hp.hpl.jena.update.UpdateFactory;\nimport com.hp.hpl.jena.query.ARQ;\nimport com.hp.hpl.jena.query.QueryExecution;\nimport com.hp.hpl.jena.query.QueryExecutionFactory;\nimport com.hp.hpl.jena.query.QueryFactory;\nimport com.hp.hpl.jena.query.QuerySolution;\nimport com.hp.hpl.jena.query.ResultSet;\nimport com.hp.hpl.jena.rdf.model.Resource;\nimport com.hp.hpl.jena.graph.Triple;\nimport com.hp.hpl.jena.sparql.engine.http.QueryEngineHTTP;\nimport com.hp.hpl.jena.sparql.engine.http.Service;\nimport com.hp.hpl.jena.sparql.util.Context;\n\nimport eu.aliada.shared.log.Log;\nimport eu.aliada.shared.log.MessageCatalog;\nimport eu.aliada.shared.rdfstore.AmbiguousLink;\nimport eu.aliada.shared.rdfstore.RetrievedResource;\n\n/**\n * RDF Store common operations. \n * \n * @author Idoia Murua\n * @since 1.0\n */\npublic class RDFStoreDAO {\n\t/** For logging. */\n\tprivate static final Log LOGGER = new Log(RDFStoreDAO.class);\n\t/** HTTP authentication cache. */\n\tprivate final Map authCache = new HashMap();\n\t/** Maximum number of triples to in every SPARQL INSERT statement. */\n\tprivate static final int MAX_NUMBER_TRIPLES = 100;\n\t\n\t/**\n\t * It clears the graph in the RDF store using ISQL.\n\t *\n\t * @param isqlCommandPath\tthe path of the ISQL command of the RDF store. \n\t * @param storeIp\t\t\tthe IP of the RDF store. \n\t * @param storeSqlPort\t\tthe port for SQL data access. \n\t * @param user\t\t\t\tthe login required for authentication in the RDF store.\n\t * @param password\t\t\tthe password required for authentication in the RDF store.\n\t * @param graphUri\t\t\tthe URI of the graph.\n\t * @return true if the graph has been cleared. False otherwise.\n\t * @since 1.0\n\t */\n\tpublic boolean clearGraphByIsql(final String isqlCommandPath, final String storeIp, final int storeSqlPort, final String user, final String password, final String graphUri) {\n\t\tfinal boolean done = false;\n\t\tfinal String clearGraphSPARQL = \"EXEC=SPARQL CLEAR GRAPH <\" + graphUri + \">;\";\n\t\t//Compose ISQL command calling statement\n\t\tfinal String isqlCommandFormat = \"%s %s:%d %s %s \\\"%s\\\"\";\n\t\tfinal String isqlCommand = String.format(isqlCommandFormat,\n\t\t\t\tisqlCommandPath, storeIp,\n\t\t\t\tstoreSqlPort, user,\n\t\t\t\tpassword, clearGraphSPARQL);\n\t\t//Execute ISQL command\n\t\ttry {\n\t\t\tRuntime.getRuntime().exec(isqlCommand);\n\t\t} catch (Exception exception) {\n\t\t\tLOGGER.error(MessageCatalog._00033_EXTERNAL_PROCESS_START_FAILURE, exception, isqlCommand);\n\t\t}\n\t\treturn done;\n\t}\n\n\t/**\n\t * It loads triples in a graph in the RDF store using HTTP PUT.\n\t *\n\t * @param triplesFilename\tthe path of the file containing the triples to load. \n\t * @param rdfSinkFolder\t\tthe URI of the RDF SINK folder in the RDF Store. \n\t * @param user\t\t\t\tthe login required for authentication in the RDF store.\n\t * @param password\t\t\tthe password required for authentication in the RDF store.\n\t * @return true if the triples have been loaded. False otherwise.\n\t * @since 1.0\n\t */\n\tpublic boolean loadDataIntoGraphByHTTP(final String triplesFilename, String rdfSinkFolder, final String user, final String password) {\n\t\tboolean done = false;\n\t\t//Get the triples file name\n\t\tfinal File triplesFile = new File(triplesFilename);\n\t\tfinal String triplesFilenameNoPath = triplesFile.getName();\n\t\t//Append the file name to the rdfSinkFolder \n\t\tif (rdfSinkFolder != null && !rdfSinkFolder.endsWith(\"/\")) {\n\t\t\trdfSinkFolder = rdfSinkFolder + \"/\";\n\t\t}\n\t\trdfSinkFolder = rdfSinkFolder + triplesFilenameNoPath;\n\t\t//HTTP Authentication\n\t\tfinal Base64 base64 = new Base64();\n\t\tfinal byte[] authenticationArray = new String(user + \":\" + password).getBytes();\n\t\tfinal String encoding = base64.encodeAsString(authenticationArray);\n\t\t\n\t\ttry {\n\t\t\tfinal URL putUrl = new URL(rdfSinkFolder);\n\t\t\tfinal HttpURLConnection connection = (HttpURLConnection) putUrl.openConnection();\n\t\t\tconnection.setReadTimeout(2000);\n\t\t\tconnection.setConnectTimeout(5000);\n\t\t\tconnection.setDoOutput(true);\n\t\t\tconnection.setInstanceFollowRedirects(false);\n\t\t\tconnection.setRequestMethod(\"PUT\");\n\t\t\t//Write Authentication\n\t\t\tconnection.setRequestProperty (\"Authorization\", \"Basic \" + encoding);\t\t\t\n\t\t\t//Write File Data\n\t\t\tfinal OutputStream outStream = connection.getOutputStream();\t\t\n\t\t\tfinal InputStream inStream = new FileInputStream(triplesFilename);\n\t\t\tfinal byte buf[] = new byte[1024];\n\t\t\tint len;\n\t\t\twhile ((len = inStream.read(buf)) > 0) {\n\t\t\t\toutStream.write(buf, 0, len);\n\t\t\t}\n\t\t\tinStream.close();\n\t\t\tfinal int responseCode=((HttpURLConnection)connection).getResponseCode();\n\t\t\tif (responseCode>= 200 && responseCode<=202) {\n\t\t\t\tdone = true;\n\t\t\t} else {\n\t\t\t\tdone = false;\n\t\t\t}\n\t\t\t((HttpURLConnection)connection).disconnect();\n\t\t} catch (Exception exception) {\n\t\t\tdone = false;\n\t\t\tLOGGER.error(MessageCatalog._00034_HTTP_PUT_FAILED, exception, rdfSinkFolder);\n\t }\n\t\treturn done;\n\t}\n\n\t/**\n\t * It executes an UPDATE SPARQL query on the SPARQL endpoint.\n\t *\n\t * @param sparqlEndpointURI\t\tthe SPARQL endpoint URI. \n\t * @param user\t\t\t\t\tthe user name for the SPARQl endpoint.\n\t * @param password\t\t\t\tthe password for the SPARQl endpoint.\n\t * @param query\t\t\t\t\tthe UPDATE query to execute.\n\t * @return true if the SPARQL has been executed. False otherwise.\n\t * @since 1.0\n\t */\n\tpublic boolean executeUpdateQuerySparqlEndpoint(final String sparqlEndpointURI, final String user, final String password, final String query) {\n\t\tboolean done = false;\n\t\ttry {\n\t\t\tUpdateExecutionFactory.createRemoteForm(\n\t\t\t\t\tUpdateFactory.create(query), \n\t\t\t\t\tsparqlEndpointURI, \n\t\t\t\t\tcontext(),\n\t\t\t\t\tauth(sparqlEndpointURI, user, password))\n\t\t\t\t.execute();\n\t\t\tdone = true;\n\t\t} catch (Exception exception) {\n\t\t\tLOGGER.error(MessageCatalog._00035_SPARQL_FAILED, exception, query);\n\t\t}\n\t\treturn done;\n\t}\n\t\n\t/**\n\t * It executes an INSERT SPARQL query on the SPARQL endpoint.\n\t *\n\t * @param sparqlEndpointURI\t\tthe SPARQL endpoint URI. \n\t * @param user\t\t\t\t\tthe user name for the SPARQl endpoint.\n\t * @param password\t\t\t\tthe password for the SPARQl endpoint.\n\t * @param triples\t\t\t\tthe triples that will be added.\n\t * throws Exception in case the INSERT goes wrong.\n\t * @since 1.0\n\t */\n\tpublic void executeInsert(\n\t\t\tfinal String sparqlEndpointURI, \n\t\t\tfinal String graphName, \n\t\t\tfinal String user, \n\t\t\tfinal String password, \n\t\t\tfinal String triples) throws Exception {\n\t\tUpdateExecutionFactory.createRemoteForm(\n\t\t\t\tUpdateFactory.create(buildInsertQuery(graphName, triples)), \n\t\t\t\tsparqlEndpointURI, \n\t\t\t\tcontext(),\n\t\t\t\tauth(sparqlEndpointURI, user, password))\n\t\t\t.execute();\n\t}\t\n\n\t/**\n\t * It clears the graph in the RDF store using SPARQL endpoint.\n\t *\n\t * @param sparqlEndpointURI\t\tthe SPARQL endpoint URI. \n\t * @param user\t\t\t\t\tthe user name for the SPARQl endpoint.\n\t * @param password\t\t\t\tthe password for the SPARQl endpoint.\n\t * @param graphUri\t\t\t\tthe URI of the graph.\n\t * @return true if the graph has been cleared. False otherwise.\n\t * @since 1.0\n\t */\n\tpublic boolean clearGraphBySparql(final String sparqlEndpointURI, final String user, final String password, final String graphUri) {\n\t\tboolean done = false;", "answers": ["\t\tfinal String clearGraphSPARQL = \"CLEAR GRAPH <\" + graphUri + \">;\";"], "length": 873, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "b3dc0768-1233-4f8f-9056-e10982c5f192", "reasoning": "Inside clearGraphBySparql, after initializing the result flag, the method needs to build the SPARQL command that clears the specified graph. Following the pattern used elsewhere, it creates a final String with the CLEAR GRAPH statement using the provided graphUri.", "reasoning_model_answer": "final String clearGraphSPARQL = \"CLEAR GRAPH <\" + graphUri + \">\";", "assistant_with_reasoning": "\nInside clearGraphBySparql, after initializing the result flag, the method needs to build the SPARQL command that clears the specified graph. Following the pattern used elsewhere, it creates a final String with the CLEAR GRAPH statement using the provided graphUri.\n\nfinal String clearGraphSPARQL = \"CLEAR GRAPH <\" + graphUri + \">\";", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.119, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 7923, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "final String clearGraphSPARQL = \"CLEAR GRAPH <\" + graphUri + \">\";", "score": 0.98, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "\"\"\"\nTests for dataset creation\n\"\"\"\nimport random\nimport math\nimport unittest\nimport os\nimport numpy as np\nimport deepchem as dc\n\ntry:\n import torch # noqa\n PYTORCH_IMPORT_FAILED = False\nexcept ImportError:\n PYTORCH_IMPORT_FAILED = True\n\n\ndef load_solubility_data():\n \"\"\"Loads solubility dataset\"\"\"\n current_dir = os.path.dirname(os.path.abspath(__file__))\n featurizer = dc.feat.CircularFingerprint(size=1024)\n tasks = [\"log-solubility\"]\n input_file = os.path.join(current_dir, \"../../models/tests/example.csv\")\n loader = dc.data.CSVLoader(\n tasks=tasks, feature_field=\"smiles\", featurizer=featurizer)\n\n return loader.create_dataset(input_file)\n\n\ndef load_multitask_data():\n \"\"\"Load example multitask data.\"\"\"\n current_dir = os.path.dirname(os.path.abspath(__file__))\n featurizer = dc.feat.CircularFingerprint(size=1024)\n tasks = [\n \"task0\", \"task1\", \"task2\", \"task3\", \"task4\", \"task5\", \"task6\", \"task7\",\n \"task8\", \"task9\", \"task10\", \"task11\", \"task12\", \"task13\", \"task14\",\n \"task15\", \"task16\"\n ]\n input_file = os.path.join(current_dir,\n \"../../models/tests/multitask_example.csv\")\n loader = dc.data.CSVLoader(\n tasks=tasks, feature_field=\"smiles\", featurizer=featurizer)\n return loader.create_dataset(input_file)\n\n\nclass TestTransformer(dc.trans.Transformer):\n\n def transform_array(self, X, y, w, ids):\n return (2 * X, 1.5 * y, w, ids)\n\n\ndef test_transform_disk():\n \"\"\"Test that the transform() method works for DiskDatasets.\"\"\"\n dataset = load_solubility_data()\n X = dataset.X\n y = dataset.y\n w = dataset.w\n ids = dataset.ids\n\n # Transform it\n\n transformer = TestTransformer(transform_X=True, transform_y=True)\n for parallel in (True, False):\n transformed = dataset.transform(transformer, parallel=parallel)\n np.testing.assert_array_equal(X, dataset.X)\n np.testing.assert_array_equal(y, dataset.y)\n np.testing.assert_array_equal(w, dataset.w)\n np.testing.assert_array_equal(ids, dataset.ids)\n np.testing.assert_array_equal(2 * X, transformed.X)\n np.testing.assert_array_equal(1.5 * y, transformed.y)\n np.testing.assert_array_equal(w, transformed.w)\n np.testing.assert_array_equal(ids, transformed.ids)\n\n\ndef test_sparsify_and_densify():\n \"\"\"Test that sparsify and densify work as inverses.\"\"\"\n # Test on identity matrix\n num_samples = 10\n num_features = num_samples\n X = np.eye(num_samples)\n X_sparse = dc.data.sparsify_features(X)\n X_reconstructed = dc.data.densify_features(X_sparse, num_features)\n np.testing.assert_array_equal(X, X_reconstructed)\n\n # Generate random sparse features dataset\n np.random.seed(123)\n p = .05\n X = np.random.binomial(1, p, size=(num_samples, num_features))\n X_sparse = dc.data.sparsify_features(X)\n X_reconstructed = dc.data.densify_features(X_sparse, num_features)\n np.testing.assert_array_equal(X, X_reconstructed)\n\n # Test edge case with array of all zeros\n X = np.zeros((num_samples, num_features))\n X_sparse = dc.data.sparsify_features(X)\n X_reconstructed = dc.data.densify_features(X_sparse, num_features)\n np.testing.assert_array_equal(X, X_reconstructed)\n\n\ndef test_pad_features():\n \"\"\"Test that pad_features pads features correctly.\"\"\"\n batch_size = 100\n num_features = 10\n\n # Test cases where n_samples < 2*n_samples < batch_size\n n_samples = 29\n X_b = np.zeros((n_samples, num_features))\n\n X_out = dc.data.pad_features(batch_size, X_b)\n assert len(X_out) == batch_size\n\n # Test cases where n_samples < batch_size\n n_samples = 79\n X_b = np.zeros((n_samples, num_features))\n X_out = dc.data.pad_features(batch_size, X_b)\n assert len(X_out) == batch_size\n\n # Test case where n_samples == batch_size\n n_samples = 100\n X_b = np.zeros((n_samples, num_features))\n X_out = dc.data.pad_features(batch_size, X_b)\n assert len(X_out) == batch_size\n\n # Test case for object featurization.\n n_samples = 2\n X_b = np.array([{\"a\": 1}, {\"b\": 2}])\n X_out = dc.data.pad_features(batch_size, X_b)\n assert len(X_out) == batch_size\n\n # Test case for more complicated object featurization\n n_samples = 2\n X_b = np.array([(1, {\"a\": 1}), (2, {\"b\": 2})])\n X_out = dc.data.pad_features(batch_size, X_b)\n assert len(X_out) == batch_size\n\n # Test case with multidimensional data\n n_samples = 50\n num_atoms = 15\n d = 3\n X_b = np.zeros((n_samples, num_atoms, d))\n X_out = dc.data.pad_features(batch_size, X_b)\n assert len(X_out) == batch_size\n\n\ndef test_pad_batches():\n \"\"\"Test that pad_batch pads batches correctly.\"\"\"\n batch_size = 100\n num_features = 10\n num_tasks = 5\n\n # Test cases where n_samples < 2*n_samples < batch_size\n n_samples = 29\n X_b = np.zeros((n_samples, num_features))\n y_b = np.zeros((n_samples, num_tasks))\n w_b = np.zeros((n_samples, num_tasks))\n ids_b = np.zeros((n_samples,))\n\n X_out, y_out, w_out, ids_out = dc.data.pad_batch(batch_size, X_b, y_b, w_b,\n ids_b)\n assert len(X_out) == len(y_out) == len(w_out) == len(ids_out) == batch_size\n\n # Test cases where n_samples < batch_size\n n_samples = 79\n X_b = np.zeros((n_samples, num_features))\n y_b = np.zeros((n_samples, num_tasks))\n w_b = np.zeros((n_samples, num_tasks))\n ids_b = np.zeros((n_samples,))\n\n X_out, y_out, w_out, ids_out = dc.data.pad_batch(batch_size, X_b, y_b, w_b,\n ids_b)\n assert len(X_out) == len(y_out) == len(w_out) == len(ids_out) == batch_size\n\n # Test case where n_samples == batch_size\n n_samples = 100\n X_b = np.zeros((n_samples, num_features))\n y_b = np.zeros((n_samples, num_tasks))\n w_b = np.zeros((n_samples, num_tasks))\n ids_b = np.zeros((n_samples,))\n\n X_out, y_out, w_out, ids_out = dc.data.pad_batch(batch_size, X_b, y_b, w_b,\n ids_b)\n assert len(X_out) == len(y_out) == len(w_out) == len(ids_out) == batch_size\n\n # Test case for object featurization.\n n_samples = 2\n X_b = np.array([{\"a\": 1}, {\"b\": 2}])\n y_b = np.zeros((n_samples, num_tasks))\n w_b = np.zeros((n_samples, num_tasks))\n ids_b = np.zeros((n_samples,))\n X_out, y_out, w_out, ids_out = dc.data.pad_batch(batch_size, X_b, y_b, w_b,\n ids_b)\n assert len(X_out) == len(y_out) == len(w_out) == len(ids_out) == batch_size\n\n # Test case for more complicated object featurization\n n_samples = 2\n X_b = np.array([(1, {\"a\": 1}), (2, {\"b\": 2})])\n y_b = np.zeros((n_samples, num_tasks))\n w_b = np.zeros((n_samples, num_tasks))\n ids_b = np.zeros((n_samples,))\n X_out, y_out, w_out, ids_out = dc.data.pad_batch(batch_size, X_b, y_b, w_b,\n ids_b)\n assert len(X_out) == len(y_out) == len(w_out) == len(ids_out) == batch_size\n\n # Test case with multidimensional data\n n_samples = 50\n num_atoms = 15\n d = 3\n X_b = np.zeros((n_samples, num_atoms, d))\n y_b = np.zeros((n_samples, num_tasks))\n w_b = np.zeros((n_samples, num_tasks))\n ids_b = np.zeros((n_samples,))\n\n X_out, y_out, w_out, ids_out = dc.data.pad_batch(batch_size, X_b, y_b, w_b,\n ids_b)\n assert len(X_out) == len(y_out) == len(w_out) == len(ids_out) == batch_size\n\n\ndef test_get_task_names():\n \"\"\"Test that get_task_names returns correct task_names\"\"\"\n solubility_dataset = load_solubility_data()\n assert solubility_dataset.get_task_names() == [\"log-solubility\"]\n\n multitask_dataset = load_multitask_data()\n assert sorted(multitask_dataset.get_task_names()) == sorted([\n \"task0\", \"task1\", \"task2\", \"task3\", \"task4\", \"task5\", \"task6\", \"task7\",\n \"task8\", \"task9\", \"task10\", \"task11\", \"task12\", \"task13\", \"task14\",\n \"task15\", \"task16\"\n ])\n\n\ndef test_get_data_shape():\n \"\"\"Test that get_data_shape returns currect data shape\"\"\"\n solubility_dataset = load_solubility_data()\n assert solubility_dataset.get_data_shape() == (1024,)\n\n multitask_dataset = load_multitask_data()", "answers": [" assert multitask_dataset.get_data_shape() == (1024,)"], "length": 789, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "f59616a2-47b3-4143-8a39-811f3db8a1e3", "reasoning": "The test function is checking the data shape of both solubility and multitask datasets. After loading the multitask dataset, the next logical step is to assert that its data shape matches the expected fingerprint size (1024,). Therefore the next line should be an assert statement for multitask_dataset.get_data_shape().", "reasoning_model_answer": "assert multitask_dataset.get_data_shape() == (1024,)", "assistant_with_reasoning": "\nThe test function is checking the data shape of both solubility and multitask datasets. After loading the multitask dataset, the next logical step is to assert that its data shape matches the expected fingerprint size (1024,). Therefore the next line should be an assert statement for multitask_dataset.get_data_shape().\n\nassert multitask_dataset.get_data_shape() == (1024,)", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 2.274, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 8032, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "assert multitask_dataset.get_data_shape() == (1024,)", "score": 0.98, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.apache.nifi.web.controller;\n\nimport org.apache.commons.collections4.CollectionUtils;\nimport org.apache.commons.lang3.StringUtils;\nimport org.apache.nifi.authorization.Authorizer;\nimport org.apache.nifi.authorization.RequestAction;\nimport org.apache.nifi.authorization.user.NiFiUser;\nimport org.apache.nifi.authorization.user.NiFiUserUtils;\nimport org.apache.nifi.components.PropertyDescriptor;\nimport org.apache.nifi.components.validation.ValidationStatus;\nimport org.apache.nifi.connectable.Connectable;\nimport org.apache.nifi.connectable.Connection;\nimport org.apache.nifi.connectable.Funnel;\nimport org.apache.nifi.connectable.Port;\nimport org.apache.nifi.controller.FlowController;\nimport org.apache.nifi.controller.ProcessorNode;\nimport org.apache.nifi.controller.ScheduledState;\nimport org.apache.nifi.controller.queue.FlowFileQueue;\nimport org.apache.nifi.flowfile.FlowFilePrioritizer;\nimport org.apache.nifi.groups.ProcessGroup;\nimport org.apache.nifi.groups.RemoteProcessGroup;\nimport org.apache.nifi.nar.NarCloseable;\nimport org.apache.nifi.processor.DataUnit;\nimport org.apache.nifi.processor.Processor;\nimport org.apache.nifi.processor.Relationship;\nimport org.apache.nifi.registry.ComponentVariableRegistry;\nimport org.apache.nifi.registry.VariableDescriptor;\nimport org.apache.nifi.registry.VariableRegistry;\nimport org.apache.nifi.remote.RootGroupPort;\nimport org.apache.nifi.scheduling.ExecutionNode;\nimport org.apache.nifi.scheduling.SchedulingStrategy;\nimport org.apache.nifi.search.SearchContext;\nimport org.apache.nifi.search.SearchResult;\nimport org.apache.nifi.search.Searchable;\nimport org.apache.nifi.web.api.dto.search.ComponentSearchResultDTO;\nimport org.apache.nifi.web.api.dto.search.SearchResultGroupDTO;\nimport org.apache.nifi.web.api.dto.search.SearchResultsDTO;\n\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.concurrent.TimeUnit;\n\n/**\n * NiFi web controller's helper service that implements component search.\n */\npublic class ControllerSearchService {\n private FlowController flowController;\n private Authorizer authorizer;\n private VariableRegistry variableRegistry;\n\n /**\n * Searches term in the controller beginning from a given process group.\n *\n * @param results Search results\n * @param search The search term\n * @param group The init process group\n */\n public void search(final SearchResultsDTO results, final String search, final ProcessGroup group) {\n final NiFiUser user = NiFiUserUtils.getNiFiUser();\n\n if (group.isAuthorized(authorizer, RequestAction.READ, user)) {\n final ComponentSearchResultDTO groupMatch = search(search, group);\n if (groupMatch != null) {\n // get the parent group, not the current one\n groupMatch.setParentGroup(buildResultGroup(group.getParent(), user));\n groupMatch.setVersionedGroup(buildVersionedGroup(group.getParent(), user));\n results.getProcessGroupResults().add(groupMatch);\n }\n }\n\n for (final ProcessorNode procNode : group.getProcessors()) {\n if (procNode.isAuthorized(authorizer, RequestAction.READ, user)) {\n final ComponentSearchResultDTO match = search(search, procNode);\n if (match != null) {\n match.setGroupId(group.getIdentifier());\n match.setParentGroup(buildResultGroup(group, user));\n match.setVersionedGroup(buildVersionedGroup(group, user));\n results.getProcessorResults().add(match);\n }\n }\n }\n\n for (final Connection connection : group.getConnections()) {\n if (connection.isAuthorized(authorizer, RequestAction.READ, user)) {\n final ComponentSearchResultDTO match = search(search, connection);\n if (match != null) {\n match.setGroupId(group.getIdentifier());\n match.setParentGroup(buildResultGroup(group, user));\n match.setVersionedGroup(buildVersionedGroup(group, user));\n results.getConnectionResults().add(match);\n }\n }\n }\n\n for (final RemoteProcessGroup remoteGroup : group.getRemoteProcessGroups()) {\n if (remoteGroup.isAuthorized(authorizer, RequestAction.READ, user)) {\n final ComponentSearchResultDTO match = search(search, remoteGroup);\n if (match != null) {\n match.setGroupId(group.getIdentifier());\n match.setParentGroup(buildResultGroup(group, user));\n match.setVersionedGroup(buildVersionedGroup(group, user));\n results.getRemoteProcessGroupResults().add(match);\n }\n }\n }\n\n for (final Port port : group.getInputPorts()) {\n if (port.isAuthorized(authorizer, RequestAction.READ, user)) {\n final ComponentSearchResultDTO match = search(search, port);\n if (match != null) {\n match.setGroupId(group.getIdentifier());\n match.setParentGroup(buildResultGroup(group, user));\n match.setVersionedGroup(buildVersionedGroup(group, user));\n results.getInputPortResults().add(match);\n }\n }\n }\n\n for (final Port port : group.getOutputPorts()) {\n if (port.isAuthorized(authorizer, RequestAction.READ, user)) {\n final ComponentSearchResultDTO match = search(search, port);\n if (match != null) {\n match.setGroupId(group.getIdentifier());\n match.setParentGroup(buildResultGroup(group, user));\n match.setVersionedGroup(buildVersionedGroup(group, user));\n results.getOutputPortResults().add(match);\n }\n }\n }\n\n for (final Funnel funnel : group.getFunnels()) {\n if (funnel.isAuthorized(authorizer, RequestAction.READ, user)) {\n final ComponentSearchResultDTO match = search(search, funnel);\n if (match != null) {\n match.setGroupId(group.getIdentifier());\n match.setParentGroup(buildResultGroup(group, user));\n match.setVersionedGroup(buildVersionedGroup(group, user));\n results.getFunnelResults().add(match);\n }\n }\n }\n\n for (final ProcessGroup processGroup : group.getProcessGroups()) {\n search(results, search, processGroup);\n }\n }\n\n private ComponentSearchResultDTO search(final String searchStr, final Port port) {\n final List matches = new ArrayList<>();\n\n addIfAppropriate(searchStr, port.getIdentifier(), \"Id\", matches);\n addIfAppropriate(searchStr, port.getVersionedComponentId().orElse(null), \"Version Control ID\", matches);\n addIfAppropriate(searchStr, port.getName(), \"Name\", matches);\n addIfAppropriate(searchStr, port.getComments(), \"Comments\", matches);\n\n // consider scheduled state\n if (ScheduledState.DISABLED.equals(port.getScheduledState())) {\n if (StringUtils.containsIgnoreCase(\"disabled\", searchStr)) {\n matches.add(\"Run status: Disabled\");\n }\n } else {\n if (StringUtils.containsIgnoreCase(\"invalid\", searchStr) && !port.isValid()) {\n matches.add(\"Run status: Invalid\");\n } else if (ScheduledState.RUNNING.equals(port.getScheduledState()) && StringUtils.containsIgnoreCase(\"running\", searchStr)) {\n matches.add(\"Run status: Running\");\n } else if (ScheduledState.STOPPED.equals(port.getScheduledState()) && StringUtils.containsIgnoreCase(\"stopped\", searchStr)) {\n matches.add(\"Run status: Stopped\");\n }\n }\n\n if (port instanceof RootGroupPort) {\n final RootGroupPort rootGroupPort = (RootGroupPort) port;\n\n // user access controls\n for (final String userAccessControl : rootGroupPort.getUserAccessControl()) {\n addIfAppropriate(searchStr, userAccessControl, \"User access control\", matches);\n }\n\n // group access controls\n for (final String groupAccessControl : rootGroupPort.getGroupAccessControl()) {\n addIfAppropriate(searchStr, groupAccessControl, \"Group access control\", matches);\n }\n }\n\n if (matches.isEmpty()) {\n return null;\n }\n\n final ComponentSearchResultDTO dto = new ComponentSearchResultDTO();\n dto.setId(port.getIdentifier());\n dto.setName(port.getName());\n dto.setMatches(matches);\n return dto;\n }\n\n private ComponentSearchResultDTO search(final String searchStr, final ProcessorNode procNode) {", "answers": [" final List matches = new ArrayList<>();"], "length": 685, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "b9591919-8cf5-4150-8c2d-d241d2fd1b3f", "reasoning": "The method signature mirrors the earlier 'search' overload for Port, which begins by creating a list to collect matching strings. Consistently, the next line should declare and instantiate that list for the ProcessorNode case.", "reasoning_model_answer": "final List matches = new ArrayList<>();", "assistant_with_reasoning": "\nThe method signature mirrors the earlier 'search' overload for Port, which begins by creating a list to collect matching strings. Consistently, the next line should declare and instantiate that list for the ProcessorNode case.\n\nfinal List matches = new ArrayList<>();", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 1.854, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 9896, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "final List matches = new ArrayList<>();", "score": 0.92, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/*\n * Copyright 2000-2016 JetBrains s.r.o.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.intellij.coverage;\n\nimport com.intellij.codeInsight.CodeInsightBundle;\nimport com.intellij.history.FileRevisionTimestampComparator;\nimport com.intellij.history.LocalHistory;\nimport com.intellij.icons.AllIcons;\nimport com.intellij.openapi.Disposable;\nimport com.intellij.openapi.application.ApplicationManager;\nimport com.intellij.openapi.diagnostic.Logger;\nimport com.intellij.openapi.editor.Document;\nimport com.intellij.openapi.editor.Editor;\nimport com.intellij.openapi.editor.colors.EditorColorsManager;\nimport com.intellij.openapi.editor.colors.EditorColorsScheme;\nimport com.intellij.openapi.editor.event.DocumentAdapter;\nimport com.intellij.openapi.editor.event.DocumentEvent;\nimport com.intellij.openapi.editor.event.DocumentListener;\nimport com.intellij.openapi.editor.impl.DocumentMarkupModel;\nimport com.intellij.openapi.editor.markup.*;\nimport com.intellij.openapi.fileEditor.FileEditor;\nimport com.intellij.openapi.fileEditor.FileEditorManager;\nimport com.intellij.openapi.fileEditor.TextEditor;\nimport com.intellij.openapi.fileEditor.impl.LoadTextUtil;\nimport com.intellij.openapi.module.Module;\nimport com.intellij.openapi.module.ModuleUtilCore;\nimport com.intellij.openapi.project.Project;\nimport com.intellij.openapi.roots.ProjectFileIndex;\nimport com.intellij.openapi.roots.ProjectRootManager;\nimport com.intellij.openapi.util.Computable;\nimport com.intellij.openapi.util.Key;\nimport com.intellij.openapi.util.Ref;\nimport com.intellij.openapi.util.TextRange;\nimport com.intellij.openapi.util.text.LineTokenizer;\nimport com.intellij.openapi.vcs.AbstractVcs;\nimport com.intellij.openapi.vcs.FilePath;\nimport com.intellij.openapi.vcs.actions.VcsContextFactory;\nimport com.intellij.openapi.vcs.history.VcsFileRevision;\nimport com.intellij.openapi.vcs.history.VcsHistoryProvider;\nimport com.intellij.openapi.vcs.history.VcsHistorySession;\nimport com.intellij.openapi.vfs.VirtualFile;\nimport com.intellij.psi.PsiFile;\nimport com.intellij.reference.SoftReference;\nimport com.intellij.rt.coverage.data.ClassData;\nimport com.intellij.rt.coverage.data.LineCoverage;\nimport com.intellij.rt.coverage.data.LineData;\nimport com.intellij.rt.coverage.data.ProjectData;\nimport com.intellij.ui.EditorNotificationPanel;\nimport com.intellij.util.Alarm;\nimport com.intellij.util.Function;\nimport com.intellij.util.diff.Diff;\nimport com.intellij.util.diff.FilesTooBigForDiffException;\nimport com.intellij.vcsUtil.VcsUtil;\nimport gnu.trove.TIntIntHashMap;\nimport org.jetbrains.annotations.NotNull;\nimport org.jetbrains.annotations.Nullable;\n\nimport java.io.File;\nimport java.util.*;\n\n/**\n * @author ven\n */\npublic class SrcFileAnnotator implements Disposable {\n private static final Logger LOG = Logger.getInstance(\"#com.intellij.coverage.SrcFileAnnotator\");\n public static final Key> COVERAGE_HIGHLIGHTERS = Key.create(\"COVERAGE_HIGHLIGHTERS\");\n private static final Key COVERAGE_DOCUMENT_LISTENER = Key.create(\"COVERAGE_DOCUMENT_LISTENER\");\n public static final Key> NOTIFICATION_PANELS = Key.create(\"NOTIFICATION_PANELS\");\n\n private PsiFile myFile;\n private Editor myEditor;\n private Document myDocument;\n private final Project myProject;\n\n private SoftReference myNewToOldLines;\n private SoftReference myOldToNewLines;\n private SoftReference myOldContent;\n private final static Object LOCK = new Object();\n \n private final Alarm myUpdateAlarm = new Alarm(Alarm.ThreadToUse.POOLED_THREAD, this);\n\n public SrcFileAnnotator(final PsiFile file, final Editor editor) {\n myFile = file;\n myEditor = editor;\n myProject = file.getProject();\n myDocument = myEditor.getDocument();\n }\n\n \n public void hideCoverageData() {\n Editor editor = myEditor;\n PsiFile file = myFile;\n Document document = myDocument;\n if (editor == null || editor.isDisposed() || file == null || document == null) return;\n final FileEditorManager fileEditorManager = FileEditorManager.getInstance(myProject);\n final List highlighters = editor.getUserData(COVERAGE_HIGHLIGHTERS);\n if (highlighters != null) {\n for (final RangeHighlighter highlighter : highlighters) {\n ApplicationManager.getApplication().invokeLater(() -> highlighter.dispose());\n }\n editor.putUserData(COVERAGE_HIGHLIGHTERS, null);\n }\n\n final Map map = file.getCopyableUserData(NOTIFICATION_PANELS);\n if (map != null) {\n final VirtualFile vFile = getVirtualFile(file);\n boolean freeAll = !fileEditorManager.isFileOpen(vFile);\n file.putCopyableUserData(NOTIFICATION_PANELS, null);\n for (FileEditor fileEditor : map.keySet()) {\n if (!freeAll && !isCurrentEditor(fileEditor)) {\n continue;\n }\n fileEditorManager.removeTopComponent(fileEditor, map.get(fileEditor));\n }\n }\n\n\n final DocumentListener documentListener = editor.getUserData(COVERAGE_DOCUMENT_LISTENER);\n if (documentListener != null) {\n document.removeDocumentListener(documentListener);\n editor.putUserData(COVERAGE_DOCUMENT_LISTENER, null);\n }\n }\n\n @NotNull\n private static String[] getCoveredLines(@NotNull byte[] oldContent, VirtualFile vFile) {\n final String text = LoadTextUtil.getTextByBinaryPresentation(oldContent, vFile, false, false).toString();\n return LineTokenizer.tokenize(text, false);\n }\n\n @NotNull private static String[] getUpToDateLines(final Document document) {\n final Ref linesRef = new Ref<>();\n final Runnable runnable = () -> {\n final int lineCount = document.getLineCount();\n final String[] lines = new String[lineCount];\n final CharSequence chars = document.getCharsSequence();\n for (int i = 0; i < lineCount; i++) {\n lines[i] = chars.subSequence(document.getLineStartOffset(i), document.getLineEndOffset(i)).toString();\n }\n linesRef.set(lines);\n };\n ApplicationManager.getApplication().runReadAction(runnable);\n\n return linesRef.get();\n }\n\n private static TIntIntHashMap getCoverageVersionToCurrentLineMapping(Diff.Change change, int firstNLines) {\n TIntIntHashMap result = new TIntIntHashMap();\n int prevLineInFirst = 0;\n int prevLineInSecond = 0;\n while (change != null) {\n\n for (int l = 0; l < change.line0 - prevLineInFirst; l++) {\n result.put(prevLineInFirst + l, prevLineInSecond + l);\n }\n\n prevLineInFirst = change.line0 + change.deleted;\n prevLineInSecond = change.line1 + change.inserted;\n\n change = change.link;\n }\n\n for (int i = prevLineInFirst; i < firstNLines; i++) {\n result.put(i, prevLineInSecond + i - prevLineInFirst);\n }\n\n return result;\n }\n\n @Nullable\n private TIntIntHashMap getOldToNewLineMapping(final long date, MyEditorBean editorBean) {\n if (myOldToNewLines == null) {\n myOldToNewLines = doGetLineMapping(date, true, editorBean);\n if (myOldToNewLines == null) return null;\n }\n return myOldToNewLines.get();\n }\n\n @Nullable\n private TIntIntHashMap getNewToOldLineMapping(final long date, MyEditorBean editorBean) {\n if (myNewToOldLines == null) {\n myNewToOldLines = doGetLineMapping(date, false, editorBean);\n if (myNewToOldLines == null) return null;\n }\n return myNewToOldLines.get();\n }\n\n @Nullable\n private SoftReference doGetLineMapping(final long date, boolean oldToNew, MyEditorBean editorBean) {\n VirtualFile virtualFile = editorBean.getVFile();\n final byte[] oldContent;\n synchronized (LOCK) {\n if (myOldContent == null) {\n if (ApplicationManager.getApplication().isDispatchThread()) return null;\n final LocalHistory localHistory = LocalHistory.getInstance();\n byte[] byteContent = localHistory.getByteContent(virtualFile, new FileRevisionTimestampComparator() {\n public boolean isSuitable(long revisionTimestamp) {\n return revisionTimestamp < date;\n }\n });\n\n if (byteContent == null && virtualFile.getTimeStamp() > date) {\n byteContent = loadFromVersionControl(date, virtualFile);\n } \n myOldContent = new SoftReference<>(byteContent);\n }\n oldContent = myOldContent.get();\n }\n\n if (oldContent == null) return null;\n String[] coveredLines = getCoveredLines(oldContent, virtualFile);\n final Document document = editorBean.getDocument();\n if (document == null) return null;\n String[] currentLines = getUpToDateLines(document);\n\n String[] oldLines = oldToNew ? coveredLines : currentLines;\n String[] newLines = oldToNew ? currentLines : coveredLines;\n\n Diff.Change change;\n try {\n change = Diff.buildChanges(oldLines, newLines);\n }\n catch (FilesTooBigForDiffException e) {\n LOG.info(e);\n return null;\n }\n return new SoftReference<>(getCoverageVersionToCurrentLineMapping(change, oldLines.length));\n }\n\n @Nullable\n private byte[] loadFromVersionControl(long date, VirtualFile f) {\n try {\n final AbstractVcs vcs = VcsUtil.getVcsFor(myProject, f);\n if (vcs == null) return null;\n\n final VcsHistoryProvider historyProvider = vcs.getVcsHistoryProvider();\n if (historyProvider == null) return null;\n\n final FilePath filePath = VcsContextFactory.SERVICE.getInstance().createFilePathOn(f);\n final VcsHistorySession session = historyProvider.createSessionFor(filePath);\n if (session == null) return null;\n\n final List list = session.getRevisionList();\n\n if (list != null) {\n for (VcsFileRevision revision : list) {\n final Date revisionDate = revision.getRevisionDate();\n if (revisionDate == null) {\n return null;\n }", "answers": [" if (revisionDate.getTime() < date) {"], "length": 860, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "cac6342b-dc47-431a-b62d-9f7f370d9ddd", "reasoning": "The method loadFromVersionControl iterates over VCS revisions to find one older than the given date. After handling a null revisionDate, the next logical step is to compare the revision's timestamp with the target date and, if appropriate, return its content. Therefore the next line should start the conditional checking the revisionDate against the provided date.", "reasoning_model_answer": "if (revisionDate.getTime() <= date) {", "assistant_with_reasoning": "\nThe method loadFromVersionControl iterates over VCS revisions to find one older than the given date. After handling a null revisionDate, the next logical step is to compare the revision's timestamp with the target date and, if appropriate, return its content. Therefore the next line should start the conditional checking the revisionDate against the provided date.\n\nif (revisionDate.getTime() <= date) {", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.556, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 10469, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "if (revisionDate.getTime() <= date) {", "score": 0.87, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "\"\"\"Test the cross_validation module\"\"\"\n\nimport warnings\n\nimport numpy as np\nfrom scipy.sparse import coo_matrix\n\nfrom sklearn.utils.testing import assert_true\nfrom sklearn.utils.testing import assert_equal\nfrom sklearn.utils.testing import assert_almost_equal\nfrom sklearn.utils.testing import assert_raises\nfrom sklearn.utils.testing import assert_greater\nfrom sklearn.utils.testing import assert_less\nfrom sklearn.utils.testing import assert_array_almost_equal\nfrom sklearn.utils.testing import assert_array_equal\n\nfrom sklearn.utils.fixes import unique\n\nfrom sklearn import cross_validation as cval\nfrom sklearn.base import BaseEstimator\nfrom sklearn.datasets import make_regression\nfrom sklearn.datasets import load_iris\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.metrics import f1_score\nfrom sklearn.metrics import explained_variance_score\nfrom sklearn.metrics import fbeta_score\nfrom sklearn.metrics import Scorer\n\nfrom sklearn.externals import six\nfrom sklearn.linear_model import Ridge\nfrom sklearn.svm import SVC\n\n\nclass MockListClassifier(BaseEstimator):\n \"\"\"Dummy classifier to test the cross-validation.\n\n Checks that GridSearchCV didn't convert X to array.\n \"\"\"\n def __init__(self, foo_param=0):\n self.foo_param = foo_param\n\n def fit(self, X, Y):\n assert_true(len(X) == len(Y))\n assert_true(isinstance(X, list))\n return self\n\n def predict(self, T):\n return T.shape[0]\n\n def score(self, X=None, Y=None):\n if self.foo_param > 1:\n score = 1.\n else:\n score = 0.\n return score\n\n\nclass MockClassifier(BaseEstimator):\n \"\"\"Dummy classifier to test the cross-validation\"\"\"\n\n def __init__(self, a=0):\n self.a = a\n\n def fit(self, X, Y=None, sample_weight=None, class_prior=None):\n if sample_weight is not None:\n assert_true(sample_weight.shape[0] == X.shape[0],\n 'MockClassifier extra fit_param sample_weight.shape[0]'\n ' is {0}, should be {1}'.format(sample_weight.shape[0],\n X.shape[0]))\n if class_prior is not None:\n assert_true(class_prior.shape[0] == len(np.unique(y)),\n 'MockClassifier extra fit_param class_prior.shape[0]'\n ' is {0}, should be {1}'.format(class_prior.shape[0],\n len(np.unique(y))))\n return self\n\n def predict(self, T):\n return T.shape[0]\n\n def score(self, X=None, Y=None):\n return 1. / (1 + np.abs(self.a))\n\n\nX = np.ones((10, 2))\nX_sparse = coo_matrix(X)\ny = np.arange(10) / 2\n\n##############################################################################\n# Tests\n\n\ndef test_kfold_valueerrors():\n # Check that errors are raised if there is not enough samples\n assert_raises(ValueError, cval.KFold, 3, 4)\n\n # Check that a warning is raised if the least populated class has too few\n # members.\n with warnings.catch_warnings(record=True) as w:\n warnings.simplefilter('always')\n y = [0, 0, 1, 1, 2]\n cval.StratifiedKFold(y, 3)\n # checking there was only one warning.\n assert_equal(len(w), 1)\n # checking it has the right type\n assert_equal(w[0].category, Warning)\n # checking it's the right warning. This might be a bad test since it's\n # a characteristic of the code and not a behavior\n assert_true(\"The least populated class\" in str(w[0]))\n\n # Error when number of folds is <= 0\n assert_raises(ValueError, cval.KFold, 2, 0)\n\n # When n is not integer:\n assert_raises(ValueError, cval.KFold, 2.5, 1)\n\n # When n_folds is not integer:\n assert_raises(ValueError, cval.KFold, 5, 1.5)\n\n\ndef test_kfold_indices():\n # Check all indices are returned in the test folds\n kf = cval.KFold(300, 3)\n all_folds = None\n for train, test in kf:\n if all_folds is None:\n all_folds = test.copy()\n else:\n all_folds = np.concatenate((all_folds, test))\n\n all_folds.sort()\n assert_array_equal(all_folds, np.arange(300))\n\n\ndef test_kfold_balance():\n # Check that KFold returns folds with balanced sizes\n for kf in [cval.KFold(i, 5) for i in range(11, 17)]:\n sizes = []\n for _, test in kf:\n sizes.append(len(test))\n\n assert_true((np.max(sizes) - np.min(sizes)) <= 1)\n assert_equal(np.sum(sizes), kf.n)\n\n\ndef test_shuffle_kfold():\n # Check the indices are shuffled properly, and that all indices are\n # returned in the different test folds\n kf1 = cval.KFold(300, 3, shuffle=True, random_state=0, indices=True)\n kf2 = cval.KFold(300, 3, shuffle=True, random_state=0, indices=False)\n ind = np.arange(300)\n\n for kf in (kf1, kf2):\n all_folds = None\n for train, test in kf:\n sorted_array = np.arange(100)\n assert_true(np.any(sorted_array != ind[train]))\n sorted_array = np.arange(101, 200)\n assert_true(np.any(sorted_array != ind[train]))\n sorted_array = np.arange(201, 300)\n assert_true(np.any(sorted_array != ind[train]))\n if all_folds is None:\n all_folds = ind[test].copy()\n else:\n all_folds = np.concatenate((all_folds, ind[test]))\n\n all_folds.sort()\n assert_array_equal(all_folds, ind)\n\n\ndef test_shuffle_split():\n ss1 = cval.ShuffleSplit(10, test_size=0.2, random_state=0)\n ss2 = cval.ShuffleSplit(10, test_size=2, random_state=0)\n ss3 = cval.ShuffleSplit(10, test_size=np.int32(2), random_state=0)\n for typ in six.integer_types:\n ss4 = cval.ShuffleSplit(10, test_size=typ(2), random_state=0)\n for t1, t2, t3, t4 in zip(ss1, ss2, ss3, ss4):\n assert_array_equal(t1[0], t2[0])\n assert_array_equal(t2[0], t3[0])\n assert_array_equal(t3[0], t4[0])\n assert_array_equal(t1[1], t2[1])\n assert_array_equal(t2[1], t3[1])\n assert_array_equal(t3[1], t4[1])\n\n\ndef test_stratified_shuffle_split_init():\n y = np.asarray([0, 1, 1, 1, 2, 2, 2])\n # Check that error is raised if there is a class with only one sample\n assert_raises(ValueError, cval.StratifiedShuffleSplit, y, 3, 0.2)\n\n # Check that error is raised if the test set size is smaller than n_classes\n assert_raises(ValueError, cval.StratifiedShuffleSplit, y, 3, 2)\n # Check that error is raised if the train set size is smaller than\n # n_classes\n assert_raises(ValueError, cval.StratifiedShuffleSplit, y, 3, 3, 2)\n\n y = np.asarray([0, 0, 0, 1, 1, 1, 2, 2, 2])\n # Check that errors are raised if there is not enough samples\n assert_raises(ValueError, cval.StratifiedShuffleSplit, y, 3, 0.5, 0.6)\n assert_raises(ValueError, cval.StratifiedShuffleSplit, y, 3, 8, 0.6)\n assert_raises(ValueError, cval.StratifiedShuffleSplit, y, 3, 0.6, 8)\n\n # Train size or test size too small\n assert_raises(ValueError, cval.StratifiedShuffleSplit, y, train_size=2)\n assert_raises(ValueError, cval.StratifiedShuffleSplit, y, test_size=2)\n\n", "answers": ["def test_stratified_shuffle_split_iter():"], "length": 721, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "40d8a5f9-7445-453a-8b7f-4e165004a91e", "reasoning": "The provided code ends with the last assertion in the test_stratified_shuffle_split_init function. In the original sklearn test suite, the next logical piece is the start of a new test function that actually performs a stratified shuffle split. Therefore, the next line should be the definition of that new test function.", "reasoning_model_answer": "def test_stratified_shuffle_split():", "assistant_with_reasoning": "\nThe provided code ends with the last assertion in the test_stratified_shuffle_split_init function. In the original sklearn test suite, the next logical piece is the start of a new test function that actually performs a stratified shuffle split. Therefore, the next line should be the definition of that new test function.\n\ndef test_stratified_shuffle_split():", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.073, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 7223, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "def test_stratified_shuffle_split():", "score": 0.94, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/*\n\n Copyright (c) 2004-2005 Jan Benda.\n \n The use and distribution terms for this software are contained in the file named License.txt, \n which can be found in the root of the Phalanger distribution. By using this software \n in any fashion, you are agreeing to be bound by the terms of this license.\n \n You must not remove this notice from this software.\n\n*/\n\n\nusing System;\nusing System.IO;\nusing System.Net;\nusing System.Text;\nusing System.Collections;\nusing System.Diagnostics;\nusing PHP.Core;\nusing System.Security.Principal;\nusing System.Security.AccessControl;\n\nnamespace PHP.Core\n{\n\t#region Abstract Stream Wrapper\n\n\t/// \n\t/// Abstract base class for PHP stream wrappers. Descendants define \n\t/// methods implementing fopen, stat, unlink, rename, opendir, mkdir and rmdir \n\t/// for different stream types.\n\t/// \n\tpublic abstract partial class StreamWrapper\n\t{\n\t\t#region Optional Wrapper Operations (Warning)\n\n\t\t/// \n /// \n\t\t/// for the list of additional options.\n\t\t/// \n public virtual StatStruct Stat(string path, StreamStatOptions options, StreamContext context, bool streamStat)\n\t\t{\n\t\t\t// int (*url_stat)(php_stream_wrapper *wrapper, char *url, int flags, php_stream_statbuf *ssb, php_stream_context *context TSRMLS_DC);\n\t\t\tPhpException.Throw(PhpError.Warning, CoreResources.GetString(\"wrapper_op_unsupported\", \"Stat\"));\n\t\t\treturn new StatStruct();\n\t\t}\n\n\t\t#endregion\n\t}\n\n\t#endregion\n\n\t#region Local Filesystem Wrapper\n\n\t/// \n\t/// Derived from , this class provides access to \n\t/// the local filesystem files.\n\t/// \n\tpublic partial class FileStreamWrapper : StreamWrapper\n\t{\n\t\t#region Opening a file\n\n\t\t/// \n\t\tpublic override PhpStream Open(ref string path, string mode, StreamOpenOptions options, StreamContext context)\n\t\t{\n\t\t\tDebug.Assert(path != null);\n\t\t\t//Debug.Assert(PhpPath.IsLocalFile(path));\n\n\t\t\t// Get the File.Open modes from the mode string\n\t\t\tFileMode fileMode;\n\t\t\tFileAccess fileAccess;\n\t\t\tStreamAccessOptions ao;\n\n\t\t\tif (!ParseMode(mode, options, out fileMode, out fileAccess, out ao)) return null;\n\n\t\t\t// Open the native stream\n\t\t\tFileStream stream = null;\n\t\t\ttry\n\t\t\t{\n\t\t\t\t// stream = File.Open(path, fileMode, fileAccess, FileShare.ReadWrite);\n\t\t\t\tstream = new FileStream(path, fileMode, fileAccess, FileShare.ReadWrite | FileShare.Delete);\n\t\t\t}\n\t\t\tcatch (FileNotFoundException)\n\t\t\t{\n\t\t\t\t// Note: There may still be an URL in the path here.\n\t\t\t\tPhpException.Throw(PhpError.Warning, CoreResources.GetString(\"stream_file_not_exists\",\n\t\t\t\t\tFileSystemUtils.StripPassword(path)));\n\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tcatch (IOException e)\n\t\t\t{\n\t\t\t\tif ((ao & StreamAccessOptions.Exclusive) > 0)\n\t\t\t\t{\n\t\t\t\t\tPhpException.Throw(PhpError.Warning, CoreResources.GetString(\"stream_file_exists\",\n\t\t\t\t\t\tFileSystemUtils.StripPassword(path)));\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tPhpException.Throw(PhpError.Warning, CoreResources.GetString(\"stream_file_io_error\",\n\t\t\t\t\t\tFileSystemUtils.StripPassword(path), PhpException.ToErrorMessage(e.Message)));\n\t\t\t\t}\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tcatch (UnauthorizedAccessException)\n\t\t\t{\n\t\t\t\tPhpException.Throw(PhpError.Warning, CoreResources.GetString(\"stream_file_access_denied\",\n\t\t\t\t\tFileSystemUtils.StripPassword(path)));\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tcatch (Exception)\n\t\t\t{\n\t\t\t\tPhpException.Throw(PhpError.Warning, CoreResources.GetString(\"stream_file_invalid\",\n\t\t\t\t\tFileSystemUtils.StripPassword(path)));\n\t\t\t\treturn null;\n\t\t\t}\n\n\t\t\tif ((ao & StreamAccessOptions.SeekEnd) > 0)\n\t\t\t{\n\t\t\t\t// Read/Write Append is not supported. Seek to the end of file manually.\n\t\t\t\tstream.Seek(0, SeekOrigin.End);\n\t\t\t}\n\n\t\t\tif ((ao & StreamAccessOptions.Temporary) > 0)\n\t\t\t{\n\t\t\t\t// Set the file attributes to Temporary too.\n\t\t\t\tFile.SetAttributes(path, FileAttributes.Temporary);\n\t\t\t}\n\n\t\t\treturn new NativeStream(stream, this, ao, path, context);\n\t\t}\n\n\n\t\t#endregion\n\n\t\t#region Optional Wrapper Operations Implementations\n\n\t\t#region Stat related methods and Stat caching\n\n\t\t/// \n\t\t/// Creates a from the filling the common\n\t\t/// members (for files and directories) from the given class.\n\t\t/// The size member (numeric index 7) may be filled by the caller\n\t\t/// for when is a .\n\t\t/// \n\t\t/// \n\t\t/// According to these outputs (PHP Win32):\n\t\t/// \n\t\t/// fstat(somefile.txt):\n\t\t/// [dev] => 0\n\t\t/// [ino] => 0\n\t\t/// [mode] => 33206\n\t\t/// [nlink] => 1\n\t\t/// [uid] => 0\n\t\t/// [gid] => 0\n\t\t/// [rdev] => 0\n\t\t/// [size] => 24\n\t\t/// [atime] => 1091131360\n\t\t/// [mtime] => 1091051699\n\t\t/// [ctime] => 1091051677\n\t\t/// [blksize] => -1\n\t\t/// [blocks] => -1\n\t\t/// \n\t\t/// stat(somefile.txt):\n\t\t/// [dev] => 2\n\t\t/// [ino] => 0\n\t\t/// [mode] => 33206 // 0100666\n\t\t/// [nlink] => 1\n\t\t/// [uid] => 0\n\t\t/// [gid] => 0\n\t\t/// [rdev] => 2\n\t\t/// [size] => 24\n\t\t/// [atime] => 1091129621\n\t\t/// [mtime] => 1091051699\n\t\t/// [ctime] => 1091051677\n\t\t/// [blksize] => -1\n\t\t/// [blocks] => -1\n\t\t/// \n\t\t/// stat(somedir):\n\t\t/// [st_dev] => 2\n\t\t/// [st_ino] => 0\n\t\t/// [st_mode] => 16895 // 040777\n\t\t/// [st_nlink] => 1\n\t\t/// [st_uid] => 0\n\t\t/// [st_gid] => 0\n\t\t/// [st_rdev] => 2\n\t\t/// [st_size] => 0\n\t\t/// [st_atime] => 1091109319\n\t\t/// [st_mtime] => 1091044521\n\t\t/// [st_ctime] => 1091044521\n\t\t/// [st_blksize] => -1\n\t\t/// [st_blocks] => -1\n\t\t/// \n\t\t/// \n\t\t/// A or \n\t\t/// of the stat()ed filesystem entry.\n\t\t/// The file or directory attributes.\n\t\t/// The path to the file / directory.\n\t\t/// A for use in the stat() related functions. \n\t\tinternal static StatStruct BuildStatStruct(FileSystemInfo info, FileAttributes attributes, string path)\n\t\t{\n\t\t\tStatStruct result;// = new StatStruct();\n\t\t\tuint device = unchecked((uint)(char.ToLower(info.FullName[0]) - 'a')); // index of the disk\n\n ushort mode = (ushort)BuildMode(info, attributes, path);\n\n\t\t\tlong atime,mtime,ctime;\n atime = ToStatUnixTimeStamp(info, (_info) => _info.LastAccessTimeUtc);\n mtime = ToStatUnixTimeStamp(info, (_info) => _info.LastWriteTimeUtc);\n ctime = ToStatUnixTimeStamp(info, (_info) => _info.CreationTimeUtc);\n\n\t\t\tresult.st_dev = device; // device number \n\t\t\tresult.st_ino = 0; // inode number \n\t\t\tresult.st_mode = mode; // inode protection mode \n\t\t\tresult.st_nlink = 1; // number of links \n\t\t\tresult.st_uid = 0; // userid of owner \n\t\t\tresult.st_gid = 0; // groupid of owner \n\t\t\tresult.st_rdev = device; // device type, if inode device -1\n\t\t\tresult.st_size = 0; // size in bytes\n\n FileInfo file_info = info as FileInfo;\n if (file_info != null) \n result.st_size = FileSystemUtils.FileSize(file_info);\n\n\t\t\tresult.st_atime = atime; // time of last access (unix timestamp) \n\t\t\tresult.st_mtime = mtime; // time of last modification (unix timestamp) \n\t\t\tresult.st_ctime = ctime; // time of last change (unix timestamp) \n\t\t\t//result.st_blksize = -1; // blocksize of filesystem IO (-1)\n\t\t\t//result.st_blocks = -1; // number of blocks allocated (-1)", "answers": ["\t\t\treturn result;"], "length": 863, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "d4229561-017f-4cab-b65b-f5311180f7f0", "reasoning": "The method BuildStatStruct constructs a StatStruct, filling its fields. After setting the fields, the logical next step is to return the populated struct. The comment about st_blksize and st_blocks is just a note, so the next executable line should be 'return result;'.", "reasoning_model_answer": "return result;", "assistant_with_reasoning": "\nThe method BuildStatStruct constructs a StatStruct, filling its fields. After setting the fields, the logical next step is to return the populated struct. The comment about st_blksize and st_blocks is just a note, so the next executable line should be 'return result;'.\n\nreturn result;", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 2.003, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 7759, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "return result;", "score": 0.9, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/*\n * Copyright (c) 2008, openmetaverse.org\n * All rights reserved.\n *\n * - Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * - Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * - Neither the name of the openmetaverse.org nor the names\n * of its contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n\nusing System;\nusing System.Runtime.InteropServices;\nusing System.Globalization;\n\nnamespace OpenMetaverse\n{\n /// \n /// A three-dimensional vector with floating-point values\n /// \n [Serializable]\n [StructLayout(LayoutKind.Sequential)]\n public struct Vector3 : IComparable, IEquatable\n {\n /// X value\n public float X;\n /// Y value\n public float Y;\n /// Z value\n public float Z;\n\n #region Constructors\n\n public Vector3(float x, float y, float z)\n {\n X = x;\n Y = y;\n Z = z;\n }\n\n public Vector3(float value)\n {\n X = value;\n Y = value;\n Z = value;\n }\n\n public Vector3(Vector2 value, float z)\n {\n X = value.X;\n Y = value.Y;\n Z = z;\n }\n\n public Vector3(Vector3d vector)\n {\n X = (float)vector.X;\n Y = (float)vector.Y;\n Z = (float)vector.Z;\n }\n\n /// \n /// Constructor, builds a vector from a byte array\n /// \n /// Byte array containing three four-byte floats\n /// Beginning position in the byte array\n public Vector3(byte[] byteArray, int pos)\n {\n X = Y = Z = 0f;\n FromBytes(byteArray, pos);\n }\n\n public Vector3(Vector3 vector)\n {\n X = vector.X;\n Y = vector.Y;\n Z = vector.Z;\n }\n\n #endregion Constructors\n\n #region Public Methods\n\n public float Length()\n {\n return (float)Math.Sqrt(DistanceSquared(this, Zero));\n }\n\n public float LengthSquared()\n {\n return DistanceSquared(this, Zero);\n }\n\n public void Normalize()\n {\n this = Normalize(this);\n }\n\n /// \n /// Test if this vector is equal to another vector, within a given\n /// tolerance range\n /// \n /// Vector to test against\n /// The acceptable magnitude of difference\n /// between the two vectors\n /// True if the magnitude of difference between the two vectors\n /// is less than the given tolerance, otherwise false\n public bool ApproxEquals(Vector3 vec, float tolerance)\n {\n Vector3 diff = this - vec;\n return (diff.LengthSquared() <= tolerance * tolerance);\n }\n\n /// \n /// IComparable.CompareTo implementation\n /// \n public int CompareTo(Vector3 vector)\n {\n return Length().CompareTo(vector.Length());\n }\n\n /// \n /// Test if this vector is composed of all finite numbers\n /// \n public bool IsFinite()\n {\n return (Utils.IsFinite(X) && Utils.IsFinite(Y) && Utils.IsFinite(Z));\n }\n\n /// \n /// Builds a vector from a byte array\n /// \n /// Byte array containing a 12 byte vector\n /// Beginning position in the byte array\n public void FromBytes(byte[] byteArray, int pos)\n {\n if (!BitConverter.IsLittleEndian)\n {\n // Big endian architecture\n byte[] conversionBuffer = new byte[12];\n\n Buffer.BlockCopy(byteArray, pos, conversionBuffer, 0, 12);\n\n Array.Reverse(conversionBuffer, 0, 4);\n Array.Reverse(conversionBuffer, 4, 4);\n Array.Reverse(conversionBuffer, 8, 4);\n\n X = BitConverter.ToSingle(conversionBuffer, 0);\n Y = BitConverter.ToSingle(conversionBuffer, 4);\n Z = BitConverter.ToSingle(conversionBuffer, 8);\n }\n else\n {\n // Little endian architecture\n X = BitConverter.ToSingle(byteArray, pos);\n Y = BitConverter.ToSingle(byteArray, pos + 4);\n Z = BitConverter.ToSingle(byteArray, pos + 8);\n }\n }\n\n /// \n /// Returns the raw bytes for this vector\n /// \n /// A 12 byte array containing X, Y, and Z\n public byte[] GetBytes()\n {\n byte[] byteArray = new byte[12];\n ToBytes(byteArray, 0);\n return byteArray;\n }\n\n /// \n /// Writes the raw bytes for this vector to a byte array\n /// \n /// Destination byte array\n /// Position in the destination array to start\n /// writing. Must be at least 12 bytes before the end of the array\n public void ToBytes(byte[] dest, int pos)\n {\n Buffer.BlockCopy(BitConverter.GetBytes(X), 0, dest, pos + 0, 4);\n Buffer.BlockCopy(BitConverter.GetBytes(Y), 0, dest, pos + 4, 4);\n Buffer.BlockCopy(BitConverter.GetBytes(Z), 0, dest, pos + 8, 4);\n\n if (!BitConverter.IsLittleEndian)\n {\n Array.Reverse(dest, pos + 0, 4);\n Array.Reverse(dest, pos + 4, 4);\n Array.Reverse(dest, pos + 8, 4);\n }\n }\n\n #endregion Public Methods\n\n #region Static Methods\n\n public static Vector3 Add(Vector3 value1, Vector3 value2)\n {\n value1.X += value2.X;\n value1.Y += value2.Y;\n value1.Z += value2.Z;\n return value1;\n }\n\n public static Vector3 Clamp(Vector3 value1, Vector3 min, Vector3 max)\n {\n return new Vector3(\n Utils.Clamp(value1.X, min.X, max.X),\n Utils.Clamp(value1.Y, min.Y, max.Y),\n Utils.Clamp(value1.Z, min.Z, max.Z));\n }\n\n public static Vector3 Cross(Vector3 value1, Vector3 value2)\n {\n return new Vector3(\n value1.Y * value2.Z - value2.Y * value1.Z,\n value1.Z * value2.X - value2.Z * value1.X,\n value1.X * value2.Y - value2.X * value1.Y);\n }", "answers": [" public static float Distance(Vector3 value1, Vector3 value2)"], "length": 851, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "7f0813ca-8066-40c7-9c8f-5ee2eda688f9", "reasoning": "The code is inside the static methods region of the Vector3 struct. After the Cross method, the next logical static utility is the distance calculation between two vectors. In the OpenMetaverse Vector3 implementation, the method that follows Cross is the static Distance method, which starts with its signature. Therefore the next line is the method signature for Distance.", "reasoning_model_answer": "public static float Distance(Vector3 value1, Vector3 value2)", "assistant_with_reasoning": "\nThe code is inside the static methods region of the Vector3 struct. After the Cross method, the next logical static utility is the distance calculation between two vectors. In the OpenMetaverse Vector3 implementation, the method that follows Cross is the static Distance method, which starts with its signature. Therefore the next line is the method signature for Distance.\n\npublic static float Distance(Vector3 value1, Vector3 value2)", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 5.746, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 7886, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "public static float Distance(Vector3 value1, Vector3 value2)", "score": 0.94, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Runtime.InteropServices;\nusing System.Threading;\n\nnamespace System.IO\n{\n /// Provides an implementation of FileSystem for Unix systems.\n internal sealed partial class UnixFileSystem : FileSystem\n {\n public override int MaxPath { get { return Interop.Sys.MaxPath; } }\n\n public override int MaxDirectoryPath { get { return Interop.Sys.MaxPath; } }\n\n public override FileStreamBase Open(string fullPath, FileMode mode, FileAccess access, FileShare share, int bufferSize, FileOptions options, FileStream parent)\n {\n return new UnixFileStream(fullPath, mode, access, share, bufferSize, options, parent);\n }\n\n public override void CopyFile(string sourceFullPath, string destFullPath, bool overwrite)\n {\n // Note: we could consider using sendfile here, but it isn't part of the POSIX spec, and\n // has varying degrees of support on different systems.\n\n // The destination path may just be a directory into which the file should be copied.\n // If it is, append the filename from the source onto the destination directory\n if (DirectoryExists(destFullPath))\n {\n destFullPath = Path.Combine(destFullPath, Path.GetFileName(sourceFullPath));\n }\n\n // Copy the contents of the file from the source to the destination, creating the destination in the process\n const int bufferSize = FileStream.DefaultBufferSize;\n const bool useAsync = false;\n using (Stream src = new FileStream(sourceFullPath, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize, useAsync))\n using (Stream dst = new FileStream(destFullPath, overwrite ? FileMode.Create : FileMode.CreateNew, FileAccess.ReadWrite, FileShare.None, bufferSize, useAsync))\n {\n src.CopyTo(dst);\n }\n\n // Now copy over relevant read/write/execute permissions from the source to the destination\n // Use Stat (not LStat) since permissions for symbolic links are meaninless and defer to permissions on the target\n Interop.Sys.FileStatus status;\n Interop.CheckIo(Interop.Sys.Stat(sourceFullPath, out status), sourceFullPath);\n int newMode = status.Mode & (int)Interop.Sys.Permissions.Mask;\n Interop.CheckIo(Interop.Sys.ChMod(destFullPath, newMode), destFullPath);\n }\n\n public override void MoveFile(string sourceFullPath, string destFullPath)\n {\n // The desired behavior for Move(source, dest) is to not overwrite the destination file\n // if it exists. Since rename(source, dest) will replace the file at 'dest' if it exists,\n // link/unlink are used instead. Note that the Unix FileSystemWatcher will treat a Move \n // as a Creation and Deletion instead of a Rename and thus differ from Windows.\n if (Interop.Sys.Link(sourceFullPath, destFullPath) < 0)\n {\n Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo();\n if (errorInfo.Error == Interop.Error.EXDEV) // rename fails across devices / mount points\n {\n CopyFile(sourceFullPath, destFullPath, overwrite: false);\n }\n else if (errorInfo.Error == Interop.Error.ENOENT && !Directory.Exists(Path.GetDirectoryName(destFullPath))) // The parent directory of destFile can't be found\n {\n // Windows distinguishes between whether the directory or the file isn't found,\n // and throws a different exception in these cases. We attempt to approximate that\n // here; there is a race condition here, where something could change between\n // when the error occurs and our checks, but it's the best we can do, and the\n // worst case in such a race condition (which could occur if the file system is\n // being manipulated concurrently with these checks) is that we throw a\n // FileNotFoundException instead of DirectoryNotFoundexception.\n throw Interop.GetExceptionForIoErrno(errorInfo, destFullPath, isDirectory: true);\n }\n else\n {\n throw Interop.GetExceptionForIoErrno(errorInfo);\n }\n }\n DeleteFile(sourceFullPath);\n }\n\n public override void DeleteFile(string fullPath)\n {\n if (Interop.Sys.Unlink(fullPath) < 0)\n {\n Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo();\n // ENOENT means it already doesn't exist; nop\n if (errorInfo.Error != Interop.Error.ENOENT)\n {\n if (errorInfo.Error == Interop.Error.EISDIR)\n errorInfo = Interop.Error.EACCES.Info();\n throw Interop.GetExceptionForIoErrno(errorInfo, fullPath);\n }\n }\n }\n\n public override void CreateDirectory(string fullPath)\n {\n // NOTE: This logic is primarily just carried forward from Win32FileSystem.CreateDirectory.\n\n int length = fullPath.Length;\n\n // We need to trim the trailing slash or the code will try to create 2 directories of the same name.\n if (length >= 2 && PathHelpers.EndsInDirectorySeparator(fullPath))\n {\n length--;\n }\n\n // For paths that are only // or /// \n if (length == 2 && PathInternal.IsDirectorySeparator(fullPath[1]))\n {\n throw new IOException(SR.Format(SR.IO_CannotCreateDirectory, fullPath));\n }\n\n // We can save a bunch of work if the directory we want to create already exists.\n if (DirectoryExists(fullPath))\n {\n return;\n }\n\n // Attempt to figure out which directories don't exist, and only create the ones we need.\n bool somepathexists = false;\n Stack stackDir = new Stack();\n int lengthRoot = PathInternal.GetRootLength(fullPath);\n if (length > lengthRoot)\n {\n int i = length - 1;\n while (i >= lengthRoot && !somepathexists)\n {\n string dir = fullPath.Substring(0, i + 1);\n if (!DirectoryExists(dir)) // Create only the ones missing\n {\n stackDir.Push(dir);\n }\n else\n {\n somepathexists = true;\n }\n\n while (i > lengthRoot && !PathInternal.IsDirectorySeparator(fullPath[i]))\n {\n i--;\n }\n i--;\n }\n }\n\n int count = stackDir.Count;\n if (count == 0 && !somepathexists)\n {\n string root = Directory.InternalGetDirectoryRoot(fullPath);\n if (!DirectoryExists(root))\n {\n throw Interop.GetExceptionForIoErrno(Interop.Error.ENOENT.Info(), fullPath, isDirectory: true);\n }\n return;\n }\n\n // Create all the directories\n int result = 0;\n Interop.ErrorInfo firstError = default(Interop.ErrorInfo);\n string errorString = fullPath;\n while (stackDir.Count > 0)\n {\n string name = stackDir.Pop();\n if (name.Length >= MaxDirectoryPath)\n {", "answers": [" throw new PathTooLongException(SR.IO_PathTooLong);"], "length": 791, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "9b8f4f6e-d196-434a-b602-cd123229805b", "reasoning": "The code is inside the CreateDirectory method, iterating over directories to create. It checks if a directory name exceeds MaxDirectoryPath. The appropriate action is to throw a PathTooLongException with the standard resource message, matching the style used elsewhere in the file (e.g., IOException with SR.Format). Hence the next line is the throw statement.", "reasoning_model_answer": "throw new PathTooLongException(SR.IO_PathTooLong);", "assistant_with_reasoning": "\nThe code is inside the CreateDirectory method, iterating over directories to create. It checks if a directory name exceeds MaxDirectoryPath. The appropriate action is to throw a PathTooLongException with the standard resource message, matching the style used elsewhere in the file (e.g., IOException with SR.Format). Hence the next line is the throw statement.\n\nthrow new PathTooLongException(SR.IO_PathTooLong);", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.925, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 8163, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "throw new PathTooLongException(SR.IO_PathTooLong);", "score": 0.83, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n// Generated by the protocol buffer compiler. DO NOT EDIT!\n// source: google/cloud/domains/v1/domains.proto\n\npackage com.google.cloud.domains.v1;\n\n/**\n *\n *\n *
    \n * Request for the `GetRegistration` method.\n * 
    \n *\n * Protobuf type {@code google.cloud.domains.v1.GetRegistrationRequest}\n */\npublic final class GetRegistrationRequest extends com.google.protobuf.GeneratedMessageV3\n implements\n // @@protoc_insertion_point(message_implements:google.cloud.domains.v1.GetRegistrationRequest)\n GetRegistrationRequestOrBuilder {\n private static final long serialVersionUID = 0L;\n // Use GetRegistrationRequest.newBuilder() to construct.\n private GetRegistrationRequest(com.google.protobuf.GeneratedMessageV3.Builder builder) {\n super(builder);\n }\n\n private GetRegistrationRequest() {\n name_ = \"\";\n }\n\n @java.lang.Override\n @SuppressWarnings({\"unused\"})\n protected java.lang.Object newInstance(UnusedPrivateParameter unused) {\n return new GetRegistrationRequest();\n }\n\n @java.lang.Override\n public final com.google.protobuf.UnknownFieldSet getUnknownFields() {\n return this.unknownFields;\n }\n\n private GetRegistrationRequest(\n com.google.protobuf.CodedInputStream input,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws com.google.protobuf.InvalidProtocolBufferException {\n this();\n if (extensionRegistry == null) {\n throw new java.lang.NullPointerException();\n }\n com.google.protobuf.UnknownFieldSet.Builder unknownFields =\n com.google.protobuf.UnknownFieldSet.newBuilder();\n try {\n boolean done = false;\n while (!done) {\n int tag = input.readTag();\n switch (tag) {\n case 0:\n done = true;\n break;\n case 10:\n {\n java.lang.String s = input.readStringRequireUtf8();\n\n name_ = s;\n break;\n }\n default:\n {\n if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) {\n done = true;\n }\n break;\n }\n }\n }\n } catch (com.google.protobuf.InvalidProtocolBufferException e) {\n throw e.setUnfinishedMessage(this);\n } catch (java.io.IOException e) {\n throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this);\n } finally {\n this.unknownFields = unknownFields.build();\n makeExtensionsImmutable();\n }\n }\n\n public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {\n return com.google.cloud.domains.v1.DomainsProto\n .internal_static_google_cloud_domains_v1_GetRegistrationRequest_descriptor;\n }\n\n @java.lang.Override\n protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable\n internalGetFieldAccessorTable() {\n return com.google.cloud.domains.v1.DomainsProto\n .internal_static_google_cloud_domains_v1_GetRegistrationRequest_fieldAccessorTable\n .ensureFieldAccessorsInitialized(\n com.google.cloud.domains.v1.GetRegistrationRequest.class,\n com.google.cloud.domains.v1.GetRegistrationRequest.Builder.class);\n }\n\n public static final int NAME_FIELD_NUMBER = 1;\n private volatile java.lang.Object name_;\n /**\n *\n *\n *
    \n   * Required. The name of the `Registration` to get, in the format\n   * `projects/*/locations/*/registrations/*`.\n   * 
    \n *\n * \n * string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }\n * \n *\n * @return The name.\n */\n @java.lang.Override\n public java.lang.String getName() {\n java.lang.Object ref = name_;\n if (ref instanceof java.lang.String) {\n return (java.lang.String) ref;\n } else {\n com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;\n java.lang.String s = bs.toStringUtf8();\n name_ = s;\n return s;\n }\n }\n /**\n *\n *\n *
    \n   * Required. The name of the `Registration` to get, in the format\n   * `projects/*/locations/*/registrations/*`.\n   * 
    \n *\n * \n * string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }\n * \n *\n * @return The bytes for name.\n */\n @java.lang.Override\n public com.google.protobuf.ByteString getNameBytes() {\n java.lang.Object ref = name_;\n if (ref instanceof java.lang.String) {\n com.google.protobuf.ByteString b =\n com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);\n name_ = b;\n return b;\n } else {\n return (com.google.protobuf.ByteString) ref;\n }\n }\n\n private byte memoizedIsInitialized = -1;\n\n @java.lang.Override\n public final boolean isInitialized() {\n byte isInitialized = memoizedIsInitialized;\n if (isInitialized == 1) return true;\n if (isInitialized == 0) return false;\n\n memoizedIsInitialized = 1;\n return true;\n }\n\n @java.lang.Override\n public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {\n if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(name_)) {\n com.google.protobuf.GeneratedMessageV3.writeString(output, 1, name_);\n }\n unknownFields.writeTo(output);\n }\n\n @java.lang.Override\n public int getSerializedSize() {\n int size = memoizedSize;\n if (size != -1) return size;\n\n size = 0;\n if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(name_)) {\n size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, name_);\n }\n size += unknownFields.getSerializedSize();\n memoizedSize = size;\n return size;\n }\n\n @java.lang.Override\n public boolean equals(final java.lang.Object obj) {\n if (obj == this) {\n return true;\n }\n if (!(obj instanceof com.google.cloud.domains.v1.GetRegistrationRequest)) {\n return super.equals(obj);\n }\n com.google.cloud.domains.v1.GetRegistrationRequest other =\n (com.google.cloud.domains.v1.GetRegistrationRequest) obj;\n\n if (!getName().equals(other.getName())) return false;\n if (!unknownFields.equals(other.unknownFields)) return false;\n return true;\n }\n\n @java.lang.Override\n public int hashCode() {\n if (memoizedHashCode != 0) {\n return memoizedHashCode;\n }\n int hash = 41;\n hash = (19 * hash) + getDescriptor().hashCode();\n hash = (37 * hash) + NAME_FIELD_NUMBER;\n hash = (53 * hash) + getName().hashCode();\n hash = (29 * hash) + unknownFields.hashCode();\n memoizedHashCode = hash;\n return hash;\n }\n\n public static com.google.cloud.domains.v1.GetRegistrationRequest parseFrom(\n java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {\n return PARSER.parseFrom(data);\n }\n\n public static com.google.cloud.domains.v1.GetRegistrationRequest parseFrom(\n java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws com.google.protobuf.InvalidProtocolBufferException {\n return PARSER.parseFrom(data, extensionRegistry);\n }\n\n public static com.google.cloud.domains.v1.GetRegistrationRequest parseFrom(\n com.google.protobuf.ByteString data)\n throws com.google.protobuf.InvalidProtocolBufferException {\n return PARSER.parseFrom(data);\n }\n\n public static com.google.cloud.domains.v1.GetRegistrationRequest parseFrom(\n com.google.protobuf.ByteString data,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws com.google.protobuf.InvalidProtocolBufferException {\n return PARSER.parseFrom(data, extensionRegistry);\n }\n\n public static com.google.cloud.domains.v1.GetRegistrationRequest parseFrom(byte[] data)\n throws com.google.protobuf.InvalidProtocolBufferException {\n return PARSER.parseFrom(data);\n }\n\n public static com.google.cloud.domains.v1.GetRegistrationRequest parseFrom(\n byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws com.google.protobuf.InvalidProtocolBufferException {\n return PARSER.parseFrom(data, extensionRegistry);\n }\n\n public static com.google.cloud.domains.v1.GetRegistrationRequest parseFrom(\n java.io.InputStream input) throws java.io.IOException {\n return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);\n }\n\n public static com.google.cloud.domains.v1.GetRegistrationRequest parseFrom(\n java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws java.io.IOException {\n return com.google.protobuf.GeneratedMessageV3.parseWithIOException(\n PARSER, input, extensionRegistry);\n }\n\n public static com.google.cloud.domains.v1.GetRegistrationRequest parseDelimitedFrom(\n java.io.InputStream input) throws java.io.IOException {\n return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);\n }\n\n public static com.google.cloud.domains.v1.GetRegistrationRequest parseDelimitedFrom(\n java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws java.io.IOException {\n return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(\n PARSER, input, extensionRegistry);\n }\n\n public static com.google.cloud.domains.v1.GetRegistrationRequest parseFrom(\n com.google.protobuf.CodedInputStream input) throws java.io.IOException {\n return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);\n }\n\n public static com.google.cloud.domains.v1.GetRegistrationRequest parseFrom(\n com.google.protobuf.CodedInputStream input,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws java.io.IOException {\n return com.google.protobuf.GeneratedMessageV3.parseWithIOException(\n PARSER, input, extensionRegistry);\n }\n\n @java.lang.Override\n public Builder newBuilderForType() {\n return newBuilder();\n }", "answers": [" public static Builder newBuilder() {"], "length": 836, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "248b6a8a-7033-4c5b-ab45-61a926ceb801", "reasoning": "The code is part of a protobuf-generated Java class. After the overridden newBuilderForType() method, the typical next member is the static newBuilder() method that returns a builder based on the default instance. This follows the standard pattern of protobuf message classes.", "reasoning_model_answer": "public static Builder newBuilder() {\n return DEFAULT_INSTANCE.toBuilder();\n }", "assistant_with_reasoning": "\nThe code is part of a protobuf-generated Java class. After the overridden newBuilderForType() method, the typical next member is the static newBuilder() method that returns a builder based on the default instance. This follows the standard pattern of protobuf message classes.\n\npublic static Builder newBuilder() {\n return DEFAULT_INSTANCE.toBuilder();\n }", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 6.183, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 10665, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "public static Builder newBuilder() {\n return DEFAULT_INSTANCE.toBuilder();\n }", "score": 0.97, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "# Copyright 2010 United States Government as represented by the\n# Administrator of the National Aeronautics and Space Administration.\n# All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\n\"\"\"Base classes for our unit tests.\n\nAllows overriding of flags for use of fakes, and some black magic for\ninline callbacks.\n\n\"\"\"\n\nimport eventlet # noqa\neventlet.monkey_patch(os=False)\n\nimport abc\nimport contextlib\nimport copy\nimport datetime\nimport inspect\nimport os\nimport pprint\nimport sys\n\nimport fixtures\nimport mock\nfrom oslo_cache import core as cache\nfrom oslo_concurrency import lockutils\nfrom oslo_config import cfg\nfrom oslo_config import fixture as config_fixture\nfrom oslo_log.fixture import logging_error as log_fixture\nfrom oslo_log import log as logging\nfrom oslo_serialization import jsonutils\nfrom oslo_utils import timeutils\nfrom oslo_versionedobjects import fixture as ovo_fixture\nfrom oslotest import moxstubout\nimport six\nimport testtools\n\nfrom nova import context\nfrom nova import db\nfrom nova import exception\nfrom nova.network import manager as network_manager\nfrom nova.network.security_group import openstack_driver\nfrom nova import objects\nfrom nova.objects import base as objects_base\nfrom nova.tests import fixtures as nova_fixtures\nfrom nova.tests.unit import conf_fixture\nfrom nova.tests.unit import policy_fixture\nfrom nova.tests import uuidsentinel as uuids\nfrom nova import utils\n\n\nCONF = cfg.CONF\n\nlogging.register_options(CONF)\nCONF.set_override('use_stderr', False)\nlogging.setup(CONF, 'nova')\ncache.configure(CONF)\n\n_TRUE_VALUES = ('True', 'true', '1', 'yes')\nCELL1_NAME = 'cell1'\n\n\nif six.PY2:\n nested = contextlib.nested\nelse:\n @contextlib.contextmanager\n def nested(*contexts):\n with contextlib.ExitStack() as stack:\n yield [stack.enter_context(c) for c in contexts]\n\n\nclass SampleNetworks(fixtures.Fixture):\n\n \"\"\"Create sample networks in the database.\"\"\"\n\n def __init__(self, host=None):\n self.host = host\n\n def setUp(self):\n super(SampleNetworks, self).setUp()\n ctxt = context.get_admin_context()\n network = network_manager.VlanManager(host=self.host)\n bridge_interface = CONF.flat_interface or CONF.vlan_interface\n network.create_networks(ctxt,\n label='test',\n cidr='10.0.0.0/8',\n multi_host=CONF.multi_host,\n num_networks=CONF.num_networks,\n network_size=CONF.network_size,\n cidr_v6=CONF.fixed_range_v6,\n gateway=CONF.gateway,\n gateway_v6=CONF.gateway_v6,\n bridge=CONF.flat_network_bridge,\n bridge_interface=bridge_interface,\n vpn_start=CONF.vpn_start,\n vlan_start=CONF.vlan_start,\n dns1=CONF.flat_network_dns)\n for net in db.network_get_all(ctxt):\n network.set_network_host(ctxt, net)\n\n\nclass TestingException(Exception):\n pass\n\n\nclass skipIf(object):\n def __init__(self, condition, reason):\n self.condition = condition\n self.reason = reason\n\n def __call__(self, func_or_cls):\n condition = self.condition\n reason = self.reason\n if inspect.isfunction(func_or_cls):\n @six.wraps(func_or_cls)\n def wrapped(*args, **kwargs):\n if condition:\n raise testtools.TestCase.skipException(reason)\n return func_or_cls(*args, **kwargs)\n\n return wrapped\n elif inspect.isclass(func_or_cls):\n orig_func = getattr(func_or_cls, 'setUp')\n\n @six.wraps(orig_func)\n def new_func(self, *args, **kwargs):\n if condition:\n raise testtools.TestCase.skipException(reason)\n orig_func(self, *args, **kwargs)\n\n func_or_cls.setUp = new_func\n return func_or_cls\n else:\n raise TypeError('skipUnless can be used only with functions or '\n 'classes')\n\n\ndef _patch_mock_to_raise_for_invalid_assert_calls():\n def raise_for_invalid_assert_calls(wrapped):\n def wrapper(_self, name):\n valid_asserts = [\n 'assert_called_with',\n 'assert_called_once_with',\n 'assert_has_calls',\n 'assert_any_calls']\n\n if name.startswith('assert') and name not in valid_asserts:\n raise AttributeError('%s is not a valid mock assert method'\n % name)\n\n return wrapped(_self, name)\n return wrapper\n mock.Mock.__getattr__ = raise_for_invalid_assert_calls(\n mock.Mock.__getattr__)\n\n# NOTE(gibi): needs to be called only once at import time\n# to patch the mock lib\n_patch_mock_to_raise_for_invalid_assert_calls()\n\n\nclass NovaExceptionReraiseFormatError(object):\n real_log_exception = exception.NovaException._log_exception\n\n @classmethod\n def patch(cls):\n exception.NovaException._log_exception = cls._wrap_log_exception\n\n @staticmethod\n def _wrap_log_exception(self):\n exc_info = sys.exc_info()\n NovaExceptionReraiseFormatError.real_log_exception(self)\n six.reraise(*exc_info)\n\n\n# NOTE(melwitt) This needs to be done at import time in order to also catch\n# NovaException format errors that are in mock decorators. In these cases, the\n# errors will be raised during test listing, before tests actually run.\nNovaExceptionReraiseFormatError.patch()\n\n\nclass TestCase(testtools.TestCase):\n \"\"\"Test case base class for all unit tests.\n\n Due to the slowness of DB access, please consider deriving from\n `NoDBTestCase` first.\n \"\"\"\n # USES_DB is set to False for tests that inherit from NoDBTestCase.\n USES_DB = True\n # USES_DB_SELF is set to True in tests that specifically want to use the\n # database but need to configure it themselves, for example to setup the\n # API DB but not the cell DB. In those cases the test will override\n # USES_DB_SELF = True but inherit from the NoDBTestCase class so it does\n # not get the default fixture setup when using a database (which is the\n # API and cell DBs, and adding the default flavors).\n USES_DB_SELF = False\n REQUIRES_LOCKING = False\n\n TIMEOUT_SCALING_FACTOR = 1\n\n def setUp(self):\n \"\"\"Run before each test method to initialize test environment.\"\"\"", "answers": [" super(TestCase, self).setUp()"], "length": 692, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "f0309855-abc5-4a52-b8d7-cb18c27bbbf3", "reasoning": "The setUp method begins with a docstring. In typical unittest.TestCase subclasses, the first executable line is a call to the parent class's setUp to ensure proper initialization. The codebase uses Python 2/3 compatible super calls, so the next line should be super(TestCase, self).setUp().", "reasoning_model_answer": "super(TestCase, self).setUp()", "assistant_with_reasoning": "\nThe setUp method begins with a docstring. In typical unittest.TestCase subclasses, the first executable line is a call to the parent class's setUp to ensure proper initialization. The codebase uses Python 2/3 compatible super calls, so the next line should be super(TestCase, self).setUp().\n\nsuper(TestCase, self).setUp()", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.776, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 7242, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "super(TestCase, self).setUp()", "score": 0.88, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "// Generated by the protocol buffer compiler. DO NOT EDIT!\n// source: google/ads/googleads/v8/services/customer_client_link_service.proto\n\npackage com.google.ads.googleads.v8.services;\n\n/**\n *
    \n * Request message for [CustomerClientLinkService.GetCustomerClientLink][google.ads.googleads.v8.services.CustomerClientLinkService.GetCustomerClientLink].\n * 
    \n *\n * Protobuf type {@code google.ads.googleads.v8.services.GetCustomerClientLinkRequest}\n */\npublic final class GetCustomerClientLinkRequest extends\n com.google.protobuf.GeneratedMessageV3 implements\n // @@protoc_insertion_point(message_implements:google.ads.googleads.v8.services.GetCustomerClientLinkRequest)\n GetCustomerClientLinkRequestOrBuilder {\nprivate static final long serialVersionUID = 0L;\n // Use GetCustomerClientLinkRequest.newBuilder() to construct.\n private GetCustomerClientLinkRequest(com.google.protobuf.GeneratedMessageV3.Builder builder) {\n super(builder);\n }\n private GetCustomerClientLinkRequest() {\n resourceName_ = \"\";\n }\n\n @java.lang.Override\n @SuppressWarnings({\"unused\"})\n protected java.lang.Object newInstance(\n UnusedPrivateParameter unused) {\n return new GetCustomerClientLinkRequest();\n }\n\n @java.lang.Override\n public final com.google.protobuf.UnknownFieldSet\n getUnknownFields() {\n return this.unknownFields;\n }\n private GetCustomerClientLinkRequest(\n com.google.protobuf.CodedInputStream input,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws com.google.protobuf.InvalidProtocolBufferException {\n this();\n if (extensionRegistry == null) {\n throw new java.lang.NullPointerException();\n }\n com.google.protobuf.UnknownFieldSet.Builder unknownFields =\n com.google.protobuf.UnknownFieldSet.newBuilder();\n try {\n boolean done = false;\n while (!done) {\n int tag = input.readTag();\n switch (tag) {\n case 0:\n done = true;\n break;\n case 10: {\n java.lang.String s = input.readStringRequireUtf8();\n\n resourceName_ = s;\n break;\n }\n default: {\n if (!parseUnknownField(\n input, unknownFields, extensionRegistry, tag)) {\n done = true;\n }\n break;\n }\n }\n }\n } catch (com.google.protobuf.InvalidProtocolBufferException e) {\n throw e.setUnfinishedMessage(this);\n } catch (java.io.IOException e) {\n throw new com.google.protobuf.InvalidProtocolBufferException(\n e).setUnfinishedMessage(this);\n } finally {\n this.unknownFields = unknownFields.build();\n makeExtensionsImmutable();\n }\n }\n public static final com.google.protobuf.Descriptors.Descriptor\n getDescriptor() {\n return com.google.ads.googleads.v8.services.CustomerClientLinkServiceProto.internal_static_google_ads_googleads_v8_services_GetCustomerClientLinkRequest_descriptor;\n }\n\n @java.lang.Override\n protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable\n internalGetFieldAccessorTable() {\n return com.google.ads.googleads.v8.services.CustomerClientLinkServiceProto.internal_static_google_ads_googleads_v8_services_GetCustomerClientLinkRequest_fieldAccessorTable\n .ensureFieldAccessorsInitialized(\n com.google.ads.googleads.v8.services.GetCustomerClientLinkRequest.class, com.google.ads.googleads.v8.services.GetCustomerClientLinkRequest.Builder.class);\n }\n\n public static final int RESOURCE_NAME_FIELD_NUMBER = 1;\n private volatile java.lang.Object resourceName_;\n /**\n *
    \n   * Required. The resource name of the customer client link to fetch.\n   * 
    \n *\n * string resource_name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }\n * @return The resourceName.\n */\n @java.lang.Override\n public java.lang.String getResourceName() {\n java.lang.Object ref = resourceName_;\n if (ref instanceof java.lang.String) {\n return (java.lang.String) ref;\n } else {\n com.google.protobuf.ByteString bs = \n (com.google.protobuf.ByteString) ref;\n java.lang.String s = bs.toStringUtf8();\n resourceName_ = s;\n return s;\n }\n }\n /**\n *
    \n   * Required. The resource name of the customer client link to fetch.\n   * 
    \n *\n * string resource_name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }\n * @return The bytes for resourceName.\n */\n @java.lang.Override\n public com.google.protobuf.ByteString\n getResourceNameBytes() {\n java.lang.Object ref = resourceName_;\n if (ref instanceof java.lang.String) {\n com.google.protobuf.ByteString b = \n com.google.protobuf.ByteString.copyFromUtf8(\n (java.lang.String) ref);\n resourceName_ = b;\n return b;\n } else {\n return (com.google.protobuf.ByteString) ref;\n }\n }\n\n private byte memoizedIsInitialized = -1;\n @java.lang.Override\n public final boolean isInitialized() {\n byte isInitialized = memoizedIsInitialized;\n if (isInitialized == 1) return true;\n if (isInitialized == 0) return false;\n\n memoizedIsInitialized = 1;\n return true;\n }\n\n @java.lang.Override\n public void writeTo(com.google.protobuf.CodedOutputStream output)\n throws java.io.IOException {\n if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(resourceName_)) {\n com.google.protobuf.GeneratedMessageV3.writeString(output, 1, resourceName_);\n }\n unknownFields.writeTo(output);\n }\n\n @java.lang.Override\n public int getSerializedSize() {\n int size = memoizedSize;\n if (size != -1) return size;\n\n size = 0;\n if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(resourceName_)) {\n size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, resourceName_);\n }\n size += unknownFields.getSerializedSize();\n memoizedSize = size;\n return size;\n }\n\n @java.lang.Override\n public boolean equals(final java.lang.Object obj) {\n if (obj == this) {\n return true;\n }\n if (!(obj instanceof com.google.ads.googleads.v8.services.GetCustomerClientLinkRequest)) {\n return super.equals(obj);\n }\n com.google.ads.googleads.v8.services.GetCustomerClientLinkRequest other = (com.google.ads.googleads.v8.services.GetCustomerClientLinkRequest) obj;\n\n if (!getResourceName()\n .equals(other.getResourceName())) return false;\n if (!unknownFields.equals(other.unknownFields)) return false;\n return true;\n }\n\n @java.lang.Override\n public int hashCode() {\n if (memoizedHashCode != 0) {\n return memoizedHashCode;\n }\n int hash = 41;\n hash = (19 * hash) + getDescriptor().hashCode();\n hash = (37 * hash) + RESOURCE_NAME_FIELD_NUMBER;\n hash = (53 * hash) + getResourceName().hashCode();\n hash = (29 * hash) + unknownFields.hashCode();\n memoizedHashCode = hash;\n return hash;\n }\n\n public static com.google.ads.googleads.v8.services.GetCustomerClientLinkRequest parseFrom(\n java.nio.ByteBuffer data)\n throws com.google.protobuf.InvalidProtocolBufferException {\n return PARSER.parseFrom(data);\n }\n public static com.google.ads.googleads.v8.services.GetCustomerClientLinkRequest parseFrom(\n java.nio.ByteBuffer data,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws com.google.protobuf.InvalidProtocolBufferException {\n return PARSER.parseFrom(data, extensionRegistry);\n }\n public static com.google.ads.googleads.v8.services.GetCustomerClientLinkRequest parseFrom(\n com.google.protobuf.ByteString data)\n throws com.google.protobuf.InvalidProtocolBufferException {\n return PARSER.parseFrom(data);\n }\n public static com.google.ads.googleads.v8.services.GetCustomerClientLinkRequest parseFrom(\n com.google.protobuf.ByteString data,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws com.google.protobuf.InvalidProtocolBufferException {\n return PARSER.parseFrom(data, extensionRegistry);\n }\n public static com.google.ads.googleads.v8.services.GetCustomerClientLinkRequest parseFrom(byte[] data)\n throws com.google.protobuf.InvalidProtocolBufferException {\n return PARSER.parseFrom(data);\n }\n public static com.google.ads.googleads.v8.services.GetCustomerClientLinkRequest parseFrom(\n byte[] data,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws com.google.protobuf.InvalidProtocolBufferException {\n return PARSER.parseFrom(data, extensionRegistry);\n }\n public static com.google.ads.googleads.v8.services.GetCustomerClientLinkRequest parseFrom(java.io.InputStream input)\n throws java.io.IOException {\n return com.google.protobuf.GeneratedMessageV3\n .parseWithIOException(PARSER, input);\n }\n public static com.google.ads.googleads.v8.services.GetCustomerClientLinkRequest parseFrom(\n java.io.InputStream input,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws java.io.IOException {\n return com.google.protobuf.GeneratedMessageV3\n .parseWithIOException(PARSER, input, extensionRegistry);\n }\n public static com.google.ads.googleads.v8.services.GetCustomerClientLinkRequest parseDelimitedFrom(java.io.InputStream input)\n throws java.io.IOException {\n return com.google.protobuf.GeneratedMessageV3\n .parseDelimitedWithIOException(PARSER, input);\n }\n public static com.google.ads.googleads.v8.services.GetCustomerClientLinkRequest parseDelimitedFrom(\n java.io.InputStream input,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws java.io.IOException {\n return com.google.protobuf.GeneratedMessageV3\n .parseDelimitedWithIOException(PARSER, input, extensionRegistry);\n }\n public static com.google.ads.googleads.v8.services.GetCustomerClientLinkRequest parseFrom(\n com.google.protobuf.CodedInputStream input)\n throws java.io.IOException {\n return com.google.protobuf.GeneratedMessageV3\n .parseWithIOException(PARSER, input);\n }\n public static com.google.ads.googleads.v8.services.GetCustomerClientLinkRequest parseFrom(\n com.google.protobuf.CodedInputStream input,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws java.io.IOException {\n return com.google.protobuf.GeneratedMessageV3\n .parseWithIOException(PARSER, input, extensionRegistry);\n }\n\n @java.lang.Override\n public Builder newBuilderForType() { return newBuilder(); }\n public static Builder newBuilder() {\n return DEFAULT_INSTANCE.toBuilder();\n }\n public static Builder newBuilder(com.google.ads.googleads.v8.services.GetCustomerClientLinkRequest prototype) {\n return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);\n }\n @java.lang.Override\n public Builder toBuilder() {\n return this == DEFAULT_INSTANCE\n ? new Builder() : new Builder().mergeFrom(this);\n }\n\n @java.lang.Override\n protected Builder newBuilderForType(\n com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {\n Builder builder = new Builder(parent);\n return builder;\n }\n /**\n *
    \n   * Request message for [CustomerClientLinkService.GetCustomerClientLink][google.ads.googleads.v8.services.CustomerClientLinkService.GetCustomerClientLink].\n   * 
    \n *\n * Protobuf type {@code google.ads.googleads.v8.services.GetCustomerClientLinkRequest}\n */\n public static final class Builder extends\n com.google.protobuf.GeneratedMessageV3.Builder implements\n // @@protoc_insertion_point(builder_implements:google.ads.googleads.v8.services.GetCustomerClientLinkRequest)\n com.google.ads.googleads.v8.services.GetCustomerClientLinkRequestOrBuilder {\n public static final com.google.protobuf.Descriptors.Descriptor\n getDescriptor() {\n return com.google.ads.googleads.v8.services.CustomerClientLinkServiceProto.internal_static_google_ads_googleads_v8_services_GetCustomerClientLinkRequest_descriptor;\n }\n\n @java.lang.Override\n protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable\n internalGetFieldAccessorTable() {\n return com.google.ads.googleads.v8.services.CustomerClientLinkServiceProto.internal_static_google_ads_googleads_v8_services_GetCustomerClientLinkRequest_fieldAccessorTable\n .ensureFieldAccessorsInitialized(\n com.google.ads.googleads.v8.services.GetCustomerClientLinkRequest.class, com.google.ads.googleads.v8.services.GetCustomerClientLinkRequest.Builder.class);\n }\n\n // Construct using com.google.ads.googleads.v8.services.GetCustomerClientLinkRequest.newBuilder()\n private Builder() {\n maybeForceBuilderInitialization();\n }\n\n private Builder(", "answers": [" com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {"], "length": 830, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "a1b6697f-64f2-4227-bfa5-0c47bc85e4a2", "reasoning": "In protobuf generated Java classes, after the default private Builder() constructor, the next code defines the Builder that accepts a BuilderParent. The pattern is a constructor taking com.google.protobuf.GeneratedMessageV3.BuilderParent, calling super(parent) and maybeForceBuilderInitialization(). Therefore the next line is the constructor signature.", "reasoning_model_answer": "private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {", "assistant_with_reasoning": "\nIn protobuf generated Java classes, after the default private Builder() constructor, the next code defines the Builder that accepts a BuilderParent. The pattern is a constructor taking com.google.protobuf.GeneratedMessageV3.BuilderParent, calling super(parent) and maybeForceBuilderInitialization(). Therefore the next line is the constructor signature.\n\nprivate Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 2.897, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 12904, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {", "score": 0.85, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/*\n\n Derby - Class org.apache.derby.impl.sql.compile.CoalesceFunctionNode\n\n Licensed to the Apache Software Foundation (ASF) under one or more\n contributor license agreements. See the NOTICE file distributed with\n this work for additional information regarding copyright ownership.\n The ASF licenses this file to you under the Apache License, Version 2.0\n (the \"License\"); you may not use this file except in compliance with\n the License. You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n\n */\n\npackage\torg.apache.derby.impl.sql.compile;\n\nimport org.apache.derby.iapi.reference.ClassName;\nimport org.apache.derby.iapi.reference.SQLState;\n\nimport org.apache.derby.iapi.services.classfile.VMOpcode;\n\nimport org.apache.derby.iapi.services.sanity.SanityManager;\n\nimport org.apache.derby.iapi.error.StandardException;\n\nimport org.apache.derby.iapi.services.compiler.LocalField;\nimport org.apache.derby.iapi.services.compiler.MethodBuilder;\nimport org.apache.derby.iapi.sql.compile.Visitor;\n\nimport org.apache.derby.iapi.util.JBitSet;\n\nimport java.lang.reflect.Modifier;\n\nimport java.util.Vector;\n\n/**\n * This node represents coalesce/value function which returns the first argument that is not null.\n * The arguments are evaluated in the order in which they are specified, and the result of the\n * function is the first argument that is not null. The result can be null only if all the arguments\n * can be null. The selected argument is converted, if necessary, to the attributes of the result.\n *\n *\n * SQL Reference Guide for DB2 has section titled \"Rules for result data types\" at the following url\n * http://publib.boulder.ibm.com/infocenter/db2help/index.jsp?topic=/com.ibm.db2.udb.doc/admin/r0008480.htm\n\n * I have constructed following table based on various tables and information under \"Rules for result data types\"\n * This table has FOR BIT DATA TYPES broken out into separate columns for clarity\n *\n * Note that are few differences between Derby and DB2\n * 1)there are few differences between what datatypes are consdiered compatible\n * In DB2, CHAR FOR BIT DATA datatypes are compatible with CHAR datatypes\n * ie in addition to following table, CHAR is compatible with CHAR FOR BIT DATA, VARCHAR FOR BIT DATA and LONG VARCHAR FOR BIT DATA\n * ie in addition to following table, VARCHAR is compatible with CHAR FOR BIT DATA, VARCHAR FOR BIT DATA and LONG VARCHAR FOR BIT DATA\n * ie in addition to following table, LONG VARCHAR is compatible with CHAR FOR BIT DATA, VARCHAR FOR BIT DATA and LONG VARCHAR FOR BIT DATA\n * ie in addition to following table, CHAR FOR BIT DATA is compatible with DATE, TIME, TIMESTAMP\n * ie in addition to following table, VARCHAR FOR BIT DATA is compatible with DATE, TIME, TIMESTAMP\n *\n * 2)few datatypes donot have matching precision in Derby and DB2\n * In DB2, precision of TIME is 8. In Derby, precision of TIME is 0.\n * In DB2, precision,scale of TIMESTAMP is 26,6. In Derby, precision of TIMESTAMP is 0,0.\n * In DB2, precision of DOUBLE is 15. In Derby, precision of DOUBLE is 52.\n * In DB2, precision of REAL is 23. In Derby, precision of REAL is 7.\n * In DB2, precision calculation equation is incorrect when we have int and decimal arguments.\n * The equation should be p=x+max(w-x,10) since precision of integer is 10 in both DB2 and Derby. Instead, DB2 has p=x+max(w-x,11) \n *\n * Types. S I B D R D C V L C V L C D T T B\n * M N I E E O H A O H A O L A I I L\n * A T G C A U A R N A R N O T M M O\n * L E I I L B R C G R C G B E E E B\n * L G N M L H V . H V S\n * I E T A E A A B A A T\n * N R L R R I R R A\n * T C T . . M\n * H B B P\n * A I I\n * R T T\n * SMALLINT { \"SMALLINT\", \"INTEGER\", \"BIGINT\", \"DECIMAL\", \"DOUBLE\", \"DOUBLE\", \"ERROR\", \"ERROR\", \"ERROR\", \"ERROR\", \"ERROR\", \"ERROR\", \"ERROR\", \"ERROR\", \"ERROR\", \"ERROR\", \"ERROR\" },\n * INTEGER { \"INTEGER\", \"INTEGER\", \"BIGINT\", \"DECIMAL\", \"DOUBLE\", \"DOUBLE\", \"ERROR\", \"ERROR\", \"ERROR\", \"ERROR\", \"ERROR\", \"ERROR\", \"ERROR\", \"ERROR\", \"ERROR\", \"ERROR\", \"ERROR\" },\n * BIGINT { \"BIGINT\", \"BIGINT\", \"BIGINT\", \"DECIMAL\", \"DOUBLE\", \"DOUBLE\", \"ERROR\", \"ERROR\", \"ERROR\", \"ERROR\", \"ERROR\", \"ERROR\", \"ERROR\", \"ERROR\", \"ERROR\", \"ERROR\", \"ERROR\" },\n * DECIMAL { \"DECIMAL\", \"DECIMAL\", \"DECIMAL\", \"DECIMAL\", \"DOUBLE\", \"DOUBLE\", \"ERROR\", \"ERROR\", \"ERROR\", \"ERROR\", \"ERROR\", \"ERROR\", \"ERROR\", \"ERROR\", \"ERROR\", \"ERROR\", \"ERROR\" },\n * REAL { \"DOUBLE\", \"DOUBLE\", \"DOUBLE\", \"DOUBLE\", \"REAL\", \"DOUBLE\", \"ERROR\", \"ERROR\", \"ERROR\", \"ERROR\", \"ERROR\", \"ERROR\", \"ERROR\", \"ERROR\", \"ERROR\", \"ERROR\", \"ERROR\" },", "answers": [" * DOUBLE { \"DOUBLE\", \"DOUBLE\", \"DOUBLE\", \"DOUBLE\", \"DOUBLE\", \"DOUBLE\", \"ERROR\", \"ERROR\", \"ERROR\", \"ERROR\", \"ERROR\", \"ERROR\", \"ERROR\", \"ERROR\", \"ERROR\", \"ERROR\", \"ERROR\" },"], "length": 759, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "6c6a94a0-4b6d-4236-88a8-9e97c7457182", "reasoning": "The snippet is a comment block listing rows of a type‑compatibility matrix for the CoalesceFunctionNode class. The last displayed row is for REAL and ends with a comma, indicating more rows follow. The next logical row is the one for DOUBLE, matching the pattern of the previous rows. Therefore the next line of code (still within the comment) should be the DOUBLE row of the matrix.", "reasoning_model_answer": "* DOUBLE { \"DOUBLE\", \"DOUBLE\", \"DOUBLE\", \"DOUBLE\", \"DOUBLE\", \"DOUBLE\", \"ERROR\", \"ERROR\", \"ERROR\", \"ERROR\", \"ERROR\", \"ERROR\", \"ERROR\", \"ERROR\", \"ERROR\", \"ERROR\", \"ERROR\" },", "assistant_with_reasoning": "\nThe snippet is a comment block listing rows of a type‑compatibility matrix for the CoalesceFunctionNode class. The last displayed row is for REAL and ends with a comma, indicating more rows follow. The next logical row is the one for DOUBLE, matching the pattern of the previous rows. Therefore the next line of code (still within the comment) should be the DOUBLE row of the matrix.\n\n* DOUBLE { \"DOUBLE\", \"DOUBLE\", \"DOUBLE\", \"DOUBLE\", \"DOUBLE\", \"DOUBLE\", \"ERROR\", \"ERROR\", \"ERROR\", \"ERROR\", \"ERROR\", \"ERROR\", \"ERROR\", \"ERROR\", \"ERROR\", \"ERROR\", \"ERROR\" },", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 7.225, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 5464, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "* DOUBLE { \"DOUBLE\", \"DOUBLE\", \"DOUBLE\", \"DOUBLE\", \"DOUBLE\", \"DOUBLE\", \"ERROR\", \"ERROR\", \"ERROR\", \"ERROR\", \"ERROR\", \"ERROR\", \"ERROR\", \"ERROR\", \"ERROR\", \"ERROR\", \"ERROR\" },", "score": 0.99, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "import logging\nimport multiprocessing\nimport os\nimport unittest.loader\nfrom argparse import ArgumentParser\nfrom contextlib import contextmanager\nfrom importlib import import_module\nfrom unittest import TestSuite, TextTestRunner, defaultTestLoader, mock\n\nfrom django.db import connections\nfrom django.test import SimpleTestCase\nfrom django.test.runner import DiscoverRunner, get_max_test_processes\nfrom django.test.utils import (\n NullTimeKeeper, TimeKeeper, captured_stderr, captured_stdout,\n)\n\n\n@contextmanager\ndef change_cwd(directory):\n current_dir = os.path.abspath(os.path.dirname(__file__))\n new_dir = os.path.join(current_dir, directory)\n old_cwd = os.getcwd()\n os.chdir(new_dir)\n try:\n yield\n finally:\n os.chdir(old_cwd)\n\n\n@contextmanager\ndef change_loader_patterns(patterns):\n original_patterns = DiscoverRunner.test_loader.testNamePatterns\n DiscoverRunner.test_loader.testNamePatterns = patterns\n try:\n yield\n finally:\n DiscoverRunner.test_loader.testNamePatterns = original_patterns\n\n\n# Isolate from the real environment.\n@mock.patch.dict(os.environ, {}, clear=True)\n@mock.patch.object(multiprocessing, 'cpu_count', return_value=12)\n# Python 3.8 on macOS defaults to 'spawn' mode.\n@mock.patch.object(multiprocessing, 'get_start_method', return_value='fork')\nclass DiscoverRunnerParallelArgumentTests(SimpleTestCase):\n def get_parser(self):\n parser = ArgumentParser()\n DiscoverRunner.add_arguments(parser)\n return parser\n\n def test_parallel_default(self, *mocked_objects):\n result = self.get_parser().parse_args([])\n self.assertEqual(result.parallel, 0)\n\n def test_parallel_flag(self, *mocked_objects):\n result = self.get_parser().parse_args(['--parallel'])\n self.assertEqual(result.parallel, 'auto')\n\n def test_parallel_auto(self, *mocked_objects):\n result = self.get_parser().parse_args(['--parallel', 'auto'])\n self.assertEqual(result.parallel, 'auto')\n\n def test_parallel_count(self, *mocked_objects):\n result = self.get_parser().parse_args(['--parallel', '17'])\n self.assertEqual(result.parallel, 17)\n\n def test_parallel_invalid(self, *mocked_objects):\n with self.assertRaises(SystemExit), captured_stderr() as stderr:\n self.get_parser().parse_args(['--parallel', 'unaccepted'])\n msg = \"argument --parallel: 'unaccepted' is not an integer or the string 'auto'\"\n self.assertIn(msg, stderr.getvalue())\n\n def test_get_max_test_processes(self, *mocked_objects):\n self.assertEqual(get_max_test_processes(), 12)\n\n @mock.patch.dict(os.environ, {'DJANGO_TEST_PROCESSES': '7'})\n def test_get_max_test_processes_env_var(self, *mocked_objects):\n self.assertEqual(get_max_test_processes(), 7)\n\n def test_get_max_test_processes_spawn(\n self, mocked_get_start_method, mocked_cpu_count,\n ):\n mocked_get_start_method.return_value = 'spawn'\n self.assertEqual(get_max_test_processes(), 1)\n with mock.patch.dict(os.environ, {'DJANGO_TEST_PROCESSES': '7'}):\n self.assertEqual(get_max_test_processes(), 1)\n\n\nclass DiscoverRunnerTests(SimpleTestCase):\n\n @staticmethod\n def get_test_methods_names(suite):\n return [\n t.__class__.__name__ + '.' + t._testMethodName\n for t in suite._tests\n ]\n\n def test_init_debug_mode(self):\n runner = DiscoverRunner()\n self.assertFalse(runner.debug_mode)\n\n def test_add_arguments_shuffle(self):\n parser = ArgumentParser()\n DiscoverRunner.add_arguments(parser)\n ns = parser.parse_args([])\n self.assertIs(ns.shuffle, False)\n ns = parser.parse_args(['--shuffle'])\n self.assertIsNone(ns.shuffle)\n ns = parser.parse_args(['--shuffle', '5'])\n self.assertEqual(ns.shuffle, 5)\n\n def test_add_arguments_debug_mode(self):\n parser = ArgumentParser()\n DiscoverRunner.add_arguments(parser)\n\n ns = parser.parse_args([])\n self.assertFalse(ns.debug_mode)\n ns = parser.parse_args([\"--debug-mode\"])\n self.assertTrue(ns.debug_mode)\n\n def test_setup_shuffler_no_shuffle_argument(self):\n runner = DiscoverRunner()\n self.assertIs(runner.shuffle, False)\n runner.setup_shuffler()\n self.assertIsNone(runner.shuffle_seed)\n\n def test_setup_shuffler_shuffle_none(self):\n runner = DiscoverRunner(shuffle=None)\n self.assertIsNone(runner.shuffle)\n with mock.patch('random.randint', return_value=1):\n with captured_stdout() as stdout:\n runner.setup_shuffler()\n self.assertEqual(stdout.getvalue(), 'Using shuffle seed: 1 (generated)\\n')\n self.assertEqual(runner.shuffle_seed, 1)\n\n def test_setup_shuffler_shuffle_int(self):\n runner = DiscoverRunner(shuffle=2)\n self.assertEqual(runner.shuffle, 2)\n with captured_stdout() as stdout:\n runner.setup_shuffler()\n expected_out = 'Using shuffle seed: 2 (given)\\n'\n self.assertEqual(stdout.getvalue(), expected_out)\n self.assertEqual(runner.shuffle_seed, 2)\n\n def test_load_tests_for_label_file_path(self):\n with change_cwd('.'):\n msg = (\n \"One of the test labels is a path to a file: \"\n \"'test_discover_runner.py', which is not supported. Use a \"\n \"dotted module name or path to a directory instead.\"\n )\n with self.assertRaisesMessage(RuntimeError, msg):\n DiscoverRunner().load_tests_for_label('test_discover_runner.py', {})\n\n def test_dotted_test_module(self):\n count = DiscoverRunner(verbosity=0).build_suite(\n ['test_runner_apps.sample.tests_sample'],\n ).countTestCases()\n\n self.assertEqual(count, 4)\n\n def test_dotted_test_class_vanilla_unittest(self):\n count = DiscoverRunner(verbosity=0).build_suite(\n ['test_runner_apps.sample.tests_sample.TestVanillaUnittest'],\n ).countTestCases()\n\n self.assertEqual(count, 1)\n\n def test_dotted_test_class_django_testcase(self):\n count = DiscoverRunner(verbosity=0).build_suite(\n ['test_runner_apps.sample.tests_sample.TestDjangoTestCase'],\n ).countTestCases()\n\n self.assertEqual(count, 1)\n\n def test_dotted_test_method_django_testcase(self):\n count = DiscoverRunner(verbosity=0).build_suite(\n ['test_runner_apps.sample.tests_sample.TestDjangoTestCase.test_sample'],\n ).countTestCases()\n\n self.assertEqual(count, 1)\n\n def test_pattern(self):\n count = DiscoverRunner(\n pattern=\"*_tests.py\",\n verbosity=0,\n ).build_suite(['test_runner_apps.sample']).countTestCases()\n\n self.assertEqual(count, 1)\n\n def test_name_patterns(self):\n all_test_1 = [\n 'DjangoCase1.test_1', 'DjangoCase2.test_1',\n 'SimpleCase1.test_1', 'SimpleCase2.test_1',\n 'UnittestCase1.test_1', 'UnittestCase2.test_1',\n ]\n all_test_2 = [\n 'DjangoCase1.test_2', 'DjangoCase2.test_2',\n 'SimpleCase1.test_2', 'SimpleCase2.test_2',\n 'UnittestCase1.test_2', 'UnittestCase2.test_2',\n ]\n all_tests = sorted([*all_test_1, *all_test_2, 'UnittestCase2.test_3_test'])\n for pattern, expected in [\n [['test_1'], all_test_1],\n [['UnittestCase1'], ['UnittestCase1.test_1', 'UnittestCase1.test_2']],\n [['*test'], ['UnittestCase2.test_3_test']],\n [['test*'], all_tests],\n [['test'], all_tests],\n [['test_1', 'test_2'], sorted([*all_test_1, *all_test_2])],\n [['test*1'], all_test_1],\n ]:\n with self.subTest(pattern):\n suite = DiscoverRunner(\n test_name_patterns=pattern,\n verbosity=0,\n ).build_suite(['test_runner_apps.simple'])\n self.assertEqual(expected, self.get_test_methods_names(suite))\n\n def test_loader_patterns_not_mutated(self):\n runner = DiscoverRunner(test_name_patterns=['test_sample'], verbosity=0)\n tests = [\n ('test_runner_apps.sample.tests', 1),\n ('test_runner_apps.sample.tests.Test.test_sample', 1),\n ('test_runner_apps.sample.empty', 0),\n ('test_runner_apps.sample.tests_sample.EmptyTestCase', 0),\n ]\n for test_labels, tests_count in tests:\n with self.subTest(test_labels=test_labels):\n with change_loader_patterns(['UnittestCase1']):\n count = runner.build_suite([test_labels]).countTestCases()\n self.assertEqual(count, tests_count)\n self.assertEqual(runner.test_loader.testNamePatterns, ['UnittestCase1'])\n\n def test_loader_patterns_not_mutated_when_test_label_is_file_path(self):\n runner = DiscoverRunner(test_name_patterns=['test_sample'], verbosity=0)\n with change_cwd('.'), change_loader_patterns(['UnittestCase1']):\n with self.assertRaises(RuntimeError):\n runner.build_suite(['test_discover_runner.py'])\n self.assertEqual(runner.test_loader.testNamePatterns, ['UnittestCase1'])\n\n def test_file_path(self):\n with change_cwd(\"..\"):\n count = DiscoverRunner(verbosity=0).build_suite(\n ['test_runner_apps/sample/'],\n ).countTestCases()\n\n self.assertEqual(count, 5)\n\n def test_empty_label(self):\n \"\"\"\n If the test label is empty, discovery should happen on the current\n working directory.\n \"\"\"\n with change_cwd(\".\"):\n suite = DiscoverRunner(verbosity=0).build_suite([])\n self.assertEqual(\n suite._tests[0].id().split(\".\")[0],\n os.path.basename(os.getcwd()),\n )\n\n def test_empty_test_case(self):\n count = DiscoverRunner(verbosity=0).build_suite(\n ['test_runner_apps.sample.tests_sample.EmptyTestCase'],\n ).countTestCases()\n\n self.assertEqual(count, 0)\n\n def test_discovery_on_package(self):\n count = DiscoverRunner(verbosity=0).build_suite(\n ['test_runner_apps.sample.tests'],\n ).countTestCases()\n\n self.assertEqual(count, 1)\n\n def test_ignore_adjacent(self):\n \"\"\"\n When given a dotted path to a module, unittest discovery searches\n not just the module, but also the directory containing the module.\n\n This results in tests from adjacent modules being run when they\n should not. The discover runner avoids this behavior.\n \"\"\"\n count = DiscoverRunner(verbosity=0).build_suite(\n ['test_runner_apps.sample.empty'],\n ).countTestCases()\n\n self.assertEqual(count, 0)\n\n def test_testcase_ordering(self):\n with change_cwd(\"..\"):\n suite = DiscoverRunner(verbosity=0).build_suite(['test_runner_apps/sample/'])\n self.assertEqual(\n suite._tests[0].__class__.__name__,\n 'TestDjangoTestCase',\n msg=\"TestDjangoTestCase should be the first test case\")\n self.assertEqual(\n suite._tests[1].__class__.__name__,\n 'TestZimpleTestCase',\n msg=\"TestZimpleTestCase should be the second test case\")\n # All others can follow in unspecified order, including doctests\n self.assertIn('DocTestCase', [t.__class__.__name__ for t in suite._tests[2:]])\n\n def test_duplicates_ignored(self):\n \"\"\"\n Tests shouldn't be discovered twice when discovering on overlapping paths.\n \"\"\"\n base_app = 'forms_tests'\n sub_app = 'forms_tests.field_tests'\n runner = DiscoverRunner(verbosity=0)\n with self.modify_settings(INSTALLED_APPS={'append': sub_app}):\n single = runner.build_suite([base_app]).countTestCases()\n dups = runner.build_suite([base_app, sub_app]).countTestCases()\n self.assertEqual(single, dups)\n\n def test_reverse(self):\n \"\"\"\n Reverse should reorder tests while maintaining the grouping specified\n by ``DiscoverRunner.reorder_by``.\n \"\"\"\n runner = DiscoverRunner(reverse=True, verbosity=0)\n suite = runner.build_suite(\n test_labels=('test_runner_apps.sample', 'test_runner_apps.simple'))\n self.assertIn('test_runner_apps.simple', next(iter(suite)).id(),\n msg=\"Test labels should be reversed.\")\n suite = runner.build_suite(test_labels=('test_runner_apps.simple',))\n suite = tuple(suite)\n self.assertIn('DjangoCase', suite[0].id(),\n msg=\"Test groups should not be reversed.\")\n self.assertIn('SimpleCase', suite[4].id(),\n msg=\"Test groups order should be preserved.\")\n self.assertIn('DjangoCase2', suite[0].id(),\n msg=\"Django test cases should be reversed.\")\n self.assertIn('SimpleCase2', suite[4].id(),\n msg=\"Simple test cases should be reversed.\")\n self.assertIn('UnittestCase2', suite[8].id(),\n msg=\"Unittest test cases should be reversed.\")\n self.assertIn('test_2', suite[0].id(),\n msg=\"Methods of Django cases should be reversed.\")\n self.assertIn('test_2', suite[4].id(),\n msg=\"Methods of simple cases should be reversed.\")\n self.assertIn('test_2', suite[9].id(),\n msg=\"Methods of unittest cases should be reversed.\")\n\n def test_build_suite_failed_tests_first(self):\n # The \"doesnotexist\" label results in a _FailedTest instance.\n suite = DiscoverRunner(verbosity=0).build_suite(\n test_labels=['test_runner_apps.sample', 'doesnotexist'],\n )\n tests = list(suite)\n self.assertIsInstance(tests[0], unittest.loader._FailedTest)\n self.assertNotIsInstance(tests[-1], unittest.loader._FailedTest)\n\n def test_build_suite_shuffling(self):\n # These will result in unittest.loader._FailedTest instances rather\n # than TestCase objects, but they are sufficient for testing.\n labels = ['label1', 'label2', 'label3', 'label4']\n cases = [\n ({}, ['label1', 'label2', 'label3', 'label4']),", "answers": [" ({'reverse': True}, ['label4', 'label3', 'label2', 'label1']),"], "length": 866, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "94360af7-e1c2-467f-8627-3a7f9b5a1de8", "reasoning": "The test is defining a list of cases to verify suite ordering with and without shuffling. The first case (empty dict) expects the original label order. The second case should enable shuffling, and the test will mock random.shuffle to reverse the list, so the expected order is the reverse of the original. Therefore the next line adds the tuple for the shuffled case.", "reasoning_model_answer": "({'shuffle': True}, ['label4', 'label3', 'label2', 'label1']),", "assistant_with_reasoning": "\nThe test is defining a list of cases to verify suite ordering with and without shuffling. The first case (empty dict) expects the original label order. The second case should enable shuffling, and the test will mock random.shuffle to reverse the list, so the expected order is the reverse of the original. Therefore the next line adds the tuple for the shuffled case.\n\n({'shuffle': True}, ['label4', 'label3', 'label2', 'label1']),", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 6.005, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 3, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 14490, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "({'shuffle': True}, ['label4', 'label3', 'label2', 'label1']),", "score": 0.84, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.apache.ignite.internal.processors.cache.query;\n\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.NoSuchElementException;\nimport java.util.UUID;\nimport java.util.concurrent.Callable;\nimport java.util.concurrent.ConcurrentMap;\nimport org.apache.ignite.IgniteCheckedException;\nimport org.apache.ignite.cluster.ClusterNode;\nimport org.apache.ignite.events.DiscoveryEvent;\nimport org.apache.ignite.events.Event;\nimport org.apache.ignite.internal.IgniteClientDisconnectedCheckedException;\nimport org.apache.ignite.internal.IgniteInternalFuture;\nimport org.apache.ignite.internal.IgniteInterruptedCheckedException;\nimport org.apache.ignite.internal.cluster.ClusterTopologyCheckedException;\nimport org.apache.ignite.internal.managers.communication.GridIoPolicy;\nimport org.apache.ignite.internal.managers.eventstorage.GridLocalEventListener;\nimport org.apache.ignite.internal.processors.query.GridQueryFieldMetadata;\nimport org.apache.ignite.internal.util.GridBoundedConcurrentOrderedSet;\nimport org.apache.ignite.internal.util.GridCloseableIteratorAdapter;\nimport org.apache.ignite.internal.util.lang.GridCloseableIterator;\nimport org.apache.ignite.internal.util.typedef.CI1;\nimport org.apache.ignite.internal.util.typedef.CI2;\nimport org.apache.ignite.internal.util.typedef.F;\nimport org.apache.ignite.internal.util.typedef.X;\nimport org.apache.ignite.internal.util.typedef.internal.S;\nimport org.apache.ignite.internal.util.typedef.internal.U;\nimport org.apache.ignite.lang.IgniteBiInClosure;\nimport org.apache.ignite.lang.IgniteClosure;\nimport org.apache.ignite.lang.IgniteFuture;\nimport org.apache.ignite.lang.IgniteReducer;\nimport org.jetbrains.annotations.Nullable;\nimport java.util.concurrent.ConcurrentHashMap;\n\nimport static org.apache.ignite.cache.CacheMode.LOCAL;\nimport static org.apache.ignite.events.EventType.EVT_NODE_FAILED;\nimport static org.apache.ignite.events.EventType.EVT_NODE_LEFT;\nimport static org.apache.ignite.internal.GridTopic.TOPIC_CACHE;\n\n/**\n * Distributed query manager (for cache in REPLICATED / PARTITIONED cache mode).\n */\npublic class GridCacheDistributedQueryManager extends GridCacheQueryManager {\n /** */\n private static final int MAX_CANCEL_IDS = 1000;\n\n /** Query response frequency. */\n private static final long RESEND_FREQ = 3000;\n\n /** Query response attempts. */\n private static final int RESEND_ATTEMPTS = 5;\n\n /** Prefix for communication topic. */\n private static final String TOPIC_PREFIX = \"QUERY\";\n\n /** {request ID -> thread} */\n private ConcurrentMap threads = new ConcurrentHashMap<>();\n\n /** {request ID -> future} */\n private ConcurrentMap> futs =\n new ConcurrentHashMap<>();\n\n /** Received requests to cancel. */\n private Collection cancelIds =\n new GridBoundedConcurrentOrderedSet<>(MAX_CANCEL_IDS);\n\n /** Canceled queries. */\n private Collection cancelled = new GridBoundedConcurrentOrderedSet<>(MAX_CANCEL_IDS);\n\n /** Query response handler. */\n private IgniteBiInClosure resHnd = new CI2() {\n @Override public void apply(UUID nodeId, GridCacheQueryResponse res) {\n processQueryResponse(nodeId, res);\n }\n };\n\n /** Event listener. */\n private GridLocalEventListener lsnr;\n\n /** {@inheritDoc} */\n @Override public void start0() throws IgniteCheckedException {\n super.start0();\n\n assert cctx.config().getCacheMode() != LOCAL;\n\n cctx.io().addCacheHandler(cctx.cacheId(), GridCacheQueryRequest.class, new CI2() {\n @Override public void apply(UUID nodeId, GridCacheQueryRequest req) {\n processQueryRequest(nodeId, req);\n }\n });\n\n lsnr = new GridLocalEventListener() {\n @Override public void onEvent(Event evt) {\n DiscoveryEvent discoEvt = (DiscoveryEvent)evt;\n\n for (GridCacheDistributedQueryFuture fut : futs.values())\n fut.onNodeLeft(discoEvt.eventNode().id());\n }\n };\n\n cctx.events().addListener(lsnr, EVT_NODE_LEFT, EVT_NODE_FAILED);\n }\n\n /** {@inheritDoc} */\n @Override protected void onKernalStop0(boolean cancel) {\n super.onKernalStop0(cancel);\n\n cctx.events().removeListener(lsnr);\n }\n\n /** {@inheritDoc} */\n @Override public void onDisconnected(IgniteFuture reconnectFut) {\n IgniteClientDisconnectedCheckedException err = new IgniteClientDisconnectedCheckedException(reconnectFut,\n \"Query was cancelled, client node disconnected.\");\n\n for (Map.Entry> e : futs.entrySet()) {\n GridCacheDistributedQueryFuture fut = e.getValue();\n\n fut.onPage(null, null, err, true);\n\n futs.remove(e.getKey(), fut);\n }\n }\n\n /** {@inheritDoc} */\n @Override public void printMemoryStats() {\n super.printMemoryStats();\n\n X.println(\">>> threadsSize: \" + threads.size());\n X.println(\">>> futsSize: \" + futs.size());\n }\n\n /**\n * Removes query future from futures map.\n *\n * @param reqId Request id.\n * @param fut Query future.\n */\n protected void addQueryFuture(long reqId, GridCacheDistributedQueryFuture fut) {\n futs.put(reqId, fut);\n\n if (cctx.kernalContext().clientDisconnected()) {\n IgniteClientDisconnectedCheckedException err = new IgniteClientDisconnectedCheckedException(\n cctx.kernalContext().cluster().clientReconnectFuture(),\n \"Query was cancelled, client node disconnected.\");\n\n fut.onDone(err);\n }\n }\n\n /**\n * Removes query future from futures map.\n *\n * @param reqId Request id.\n */\n protected void removeQueryFuture(long reqId) {\n futs.remove(reqId);\n }\n\n /**\n * Gets query future from futures map.\n *\n * @param reqId Request id.\n * @return Found future or null.\n */\n protected GridCacheDistributedQueryFuture getQueryFuture(long reqId) {\n return futs.get(reqId);\n }\n\n /**\n * Processes cache query request.\n *\n * @param sndId Sender node id.\n * @param req Query request.\n */\n @SuppressWarnings(\"unchecked\")\n @Override void processQueryRequest(UUID sndId, GridCacheQueryRequest req) {\n if (req.cancel()) {\n cancelIds.add(new CancelMessageId(req.id(), sndId));\n\n if (req.fields())\n removeFieldsQueryResult(sndId, req.id());\n else\n removeQueryResult(sndId, req.id());\n }\n else {\n if (!cancelIds.contains(new CancelMessageId(req.id(), sndId))) {\n if (!F.eq(req.cacheName(), cctx.name())) {\n GridCacheQueryResponse res = new GridCacheQueryResponse(\n cctx.cacheId(),\n req.id(),\n new IgniteCheckedException(\"Received request for incorrect cache [expected=\" + cctx.name() +\n \", actual=\" + req.cacheName()),\n cctx.deploymentEnabled());\n\n sendQueryResponse(sndId, res, 0);\n }\n else {\n threads.put(req.id(), Thread.currentThread());\n\n try {\n GridCacheQueryInfo info = distributedQueryInfo(sndId, req);\n\n if (info == null)\n return;\n\n if (req.fields())\n runFieldsQuery(info);\n else\n runQuery(info);\n }\n catch (Throwable e) {\n U.error(log(), \"Failed to run query.\", e);\n\n sendQueryResponse(sndId, new GridCacheQueryResponse(cctx.cacheId(), req.id(), e.getCause(),\n cctx.deploymentEnabled()), 0);\n\n if (e instanceof Error)\n throw (Error)e;\n }\n finally {\n threads.remove(req.id());\n }\n }\n }\n }\n }\n\n /**\n * @param sndId Sender node id.\n * @param req Query request.\n * @return Query info.\n */\n @Nullable private GridCacheQueryInfo distributedQueryInfo(UUID sndId, GridCacheQueryRequest req) {\n IgniteReducer rdc = req.reducer();\n IgniteClosure trans = (IgniteClosure)req.transformer();\n\n ClusterNode sndNode = cctx.node(sndId);\n\n if (sndNode == null)\n return null;\n\n GridCacheQueryAdapter qry =\n new GridCacheQueryAdapter<>(\n cctx,\n req.type(),\n log,\n req.pageSize(),\n 0,\n req.includeBackups(),\n false,\n null,\n req.keyValueFilter(),\n req.partition() == -1 ? null : req.partition(),\n req.className(),\n req.clause(),\n req.includeMetaData(),\n req.keepBinary(),\n req.subjectId(),\n req.taskHash()\n );\n\n return new GridCacheQueryInfo(\n false,\n trans,\n rdc,\n qry,\n null,\n sndId,\n req.id(),\n req.includeMetaData(),\n req.allPages(),\n req.arguments()\n );\n }\n\n /**\n * Sends cache query response.\n *\n * @param nodeId Node to send response.\n * @param res Cache query response.\n * @param timeout Message timeout.\n * @return {@code true} if response was sent, {@code false} otherwise.\n */", "answers": [" private boolean sendQueryResponse(UUID nodeId, GridCacheQueryResponse res, long timeout) {"], "length": 860, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "5dd7edb3-f436-4cd8-a1ef-823fe4a8501f", "reasoning": "The comment describes a method that sends a cache query response, taking a node ID, a response object, and a timeout, and returning a boolean indicating success. The code later calls sendQueryResponse(sndId, res, 0), so the next line should be the method signature matching those parameters and return type.", "reasoning_model_answer": "private boolean sendQueryResponse(UUID nodeId, GridCacheQueryResponse res, long timeout) {", "assistant_with_reasoning": "\nThe comment describes a method that sends a cache query response, taking a node ID, a response object, and a timeout, and returning a boolean indicating success. The code later calls sendQueryResponse(sndId, res, 0), so the next line should be the method signature matching those parameters and return type.\n\nprivate boolean sendQueryResponse(UUID nodeId, GridCacheQueryResponse res, long timeout) {", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 2.842, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 10965, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "private boolean sendQueryResponse(UUID nodeId, GridCacheQueryResponse res, long timeout) {", "score": 0.98, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/*\n * Licensed to Elasticsearch under one or more contributor\n * license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright\n * ownership. Elasticsearch licenses this file to you under\n * the Apache License, Version 2.0 (the \"License\"); you may\n * not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\npackage org.elasticsearch.search.fields;\n\nimport org.elasticsearch.action.index.IndexRequestBuilder;\nimport org.elasticsearch.action.search.SearchRequestBuilder;\nimport org.elasticsearch.action.search.SearchResponse;\nimport org.elasticsearch.common.bytes.BytesArray;\nimport org.elasticsearch.common.bytes.BytesReference;\nimport org.elasticsearch.common.collect.MapBuilder;\nimport org.elasticsearch.common.joda.Joda;\nimport org.elasticsearch.common.settings.Settings;\nimport org.elasticsearch.common.xcontent.XContentFactory;\nimport org.elasticsearch.common.xcontent.XContentType;\nimport org.elasticsearch.common.xcontent.support.XContentMapValues;\nimport org.elasticsearch.index.fielddata.ScriptDocValues;\nimport org.elasticsearch.index.query.QueryBuilders;\nimport org.elasticsearch.plugins.Plugin;\nimport org.elasticsearch.rest.RestStatus;\nimport org.elasticsearch.script.MockScriptPlugin;\nimport org.elasticsearch.script.Script;\nimport org.elasticsearch.script.ScriptType;\nimport org.elasticsearch.search.SearchHit;\nimport org.elasticsearch.search.SearchHitField;\nimport org.elasticsearch.search.builder.SearchSourceBuilder;\nimport org.elasticsearch.search.lookup.FieldLookup;\nimport org.elasticsearch.search.sort.SortOrder;\nimport org.elasticsearch.test.ESIntegTestCase;\nimport org.joda.time.DateTime;\nimport org.joda.time.DateTimeZone;\nimport org.joda.time.ReadableDateTime;\n\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Base64;\nimport java.util.Collection;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.concurrent.ExecutionException;\nimport java.util.function.Function;\n\nimport static java.util.Collections.singleton;\nimport static org.elasticsearch.action.support.WriteRequest.RefreshPolicy.IMMEDIATE;\nimport static org.elasticsearch.client.Requests.refreshRequest;\nimport static org.elasticsearch.common.util.set.Sets.newHashSet;\nimport static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;\nimport static org.elasticsearch.index.query.QueryBuilders.matchAllQuery;\nimport static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked;\nimport static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertFailures;\nimport static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertHitCount;\nimport static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertNoFailures;\nimport static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertSearchResponse;\nimport static org.hamcrest.Matchers.containsString;\nimport static org.hamcrest.Matchers.equalTo;\nimport static org.hamcrest.Matchers.hasSize;\nimport static org.hamcrest.Matchers.notNullValue;\nimport static org.hamcrest.Matchers.nullValue;\n\npublic class SearchFieldsIT extends ESIntegTestCase {\n\n @Override\n protected Collection> nodePlugins() {\n return Collections.singletonList(CustomScriptPlugin.class);\n }\n\n public static class CustomScriptPlugin extends MockScriptPlugin {\n\n @Override\n @SuppressWarnings(\"unchecked\")\n protected Map, Object>> pluginScripts() {\n Map, Object>> scripts = new HashMap<>();\n\n scripts.put(\"doc['num1'].value\", vars -> {\n Map doc = (Map) vars.get(\"doc\");\n ScriptDocValues.Doubles num1 = (ScriptDocValues.Doubles) doc.get(\"num1\");\n return num1.getValue();\n });\n\n scripts.put(\"doc['num1'].value * factor\", vars -> {\n Map doc = (Map) vars.get(\"doc\");\n ScriptDocValues.Doubles num1 = (ScriptDocValues.Doubles) doc.get(\"num1\");\n Double factor = (Double) vars.get(\"factor\");\n return num1.getValue() * factor;\n });\n\n scripts.put(\"doc['date'].date.millis\", vars -> {\n Map doc = (Map) vars.get(\"doc\");\n ScriptDocValues.Dates dates = (ScriptDocValues.Dates) doc.get(\"date\");\n return dates.getValue().getMillis();\n });\n\n scripts.put(\"_fields['num1'].value\", vars -> fieldsScript(vars, \"num1\"));\n scripts.put(\"_fields._uid.value\", vars -> fieldsScript(vars, \"_uid\"));\n scripts.put(\"_fields._id.value\", vars -> fieldsScript(vars, \"_id\"));\n scripts.put(\"_fields._type.value\", vars -> fieldsScript(vars, \"_type\"));\n\n scripts.put(\"_source.obj1\", vars -> sourceScript(vars, \"obj1\"));\n scripts.put(\"_source.obj1.test\", vars -> sourceScript(vars, \"obj1.test\"));\n scripts.put(\"_source.obj1.test\", vars -> sourceScript(vars, \"obj1.test\"));\n scripts.put(\"_source.obj2\", vars -> sourceScript(vars, \"obj2\"));\n scripts.put(\"_source.obj2.arr2\", vars -> sourceScript(vars, \"obj2.arr2\"));\n scripts.put(\"_source.arr3\", vars -> sourceScript(vars, \"arr3\"));\n\n scripts.put(\"return null\", vars -> null);\n\n scripts.put(\"doc['l'].values\", vars -> docScript(vars, \"l\"));\n scripts.put(\"doc['ml'].values\", vars -> docScript(vars, \"ml\"));\n scripts.put(\"doc['d'].values\", vars -> docScript(vars, \"d\"));\n scripts.put(\"doc['md'].values\", vars -> docScript(vars, \"md\"));\n scripts.put(\"doc['s'].values\", vars -> docScript(vars, \"s\"));\n scripts.put(\"doc['ms'].values\", vars -> docScript(vars, \"ms\"));\n\n return scripts;\n }\n\n @SuppressWarnings(\"unchecked\")\n static Object fieldsScript(Map vars, String fieldName) {\n Map fields = (Map) vars.get(\"_fields\");\n FieldLookup fieldLookup = (FieldLookup) fields.get(fieldName);\n return fieldLookup.getValue();\n }\n\n @SuppressWarnings(\"unchecked\")\n static Object sourceScript(Map vars, String path) {\n Map source = (Map) vars.get(\"_source\");\n return XContentMapValues.extractValue(path, source);\n }\n\n @SuppressWarnings(\"unchecked\")\n static Object docScript(Map vars, String fieldName) {\n Map doc = (Map) vars.get(\"doc\");\n ScriptDocValues values = (ScriptDocValues) doc.get(fieldName);\n return values.getValues();\n }\n }\n\n public void testStoredFields() throws Exception {\n createIndex(\"test\");\n\n String mapping = XContentFactory.jsonBuilder().startObject().startObject(\"type1\")\n .startObject(\"properties\")\n .startObject(\"field1\").field(\"type\", \"text\").field(\"store\", true).endObject()\n .startObject(\"field2\").field(\"type\", \"text\").field(\"store\", false).endObject()\n .startObject(\"field3\").field(\"type\", \"text\").field(\"store\", true).endObject()\n .endObject().endObject().endObject().string();\n\n client().admin().indices().preparePutMapping().setType(\"type1\").setSource(mapping, XContentType.JSON).execute().actionGet();\n\n client().prepareIndex(\"test\", \"type1\", \"1\").setSource(jsonBuilder().startObject()\n .field(\"field1\", \"value1\")\n .field(\"field2\", \"value2\")\n .field(\"field3\", \"value3\")\n .endObject()).execute().actionGet();\n\n client().admin().indices().prepareRefresh().execute().actionGet();\n\n SearchResponse searchResponse = client().prepareSearch().setQuery(matchAllQuery()).addStoredField(\"field1\").execute().actionGet();\n assertThat(searchResponse.getHits().getTotalHits(), equalTo(1L));\n assertThat(searchResponse.getHits().getHits().length, equalTo(1));\n assertThat(searchResponse.getHits().getAt(0).getFields().size(), equalTo(1));\n assertThat(searchResponse.getHits().getAt(0).getFields().get(\"field1\").getValue().toString(), equalTo(\"value1\"));\n\n // field2 is not stored, check that it is not extracted from source.\n searchResponse = client().prepareSearch().setQuery(matchAllQuery()).addStoredField(\"field2\").execute().actionGet();\n assertThat(searchResponse.getHits().getTotalHits(), equalTo(1L));\n assertThat(searchResponse.getHits().getHits().length, equalTo(1));\n assertThat(searchResponse.getHits().getAt(0).getFields().size(), equalTo(0));\n assertThat(searchResponse.getHits().getAt(0).getFields().get(\"field2\"), nullValue());\n\n searchResponse = client().prepareSearch().setQuery(matchAllQuery()).addStoredField(\"field3\").execute().actionGet();\n assertThat(searchResponse.getHits().getTotalHits(), equalTo(1L));\n assertThat(searchResponse.getHits().getHits().length, equalTo(1));\n assertThat(searchResponse.getHits().getAt(0).getFields().size(), equalTo(1));\n assertThat(searchResponse.getHits().getAt(0).getFields().get(\"field3\").getValue().toString(), equalTo(\"value3\"));\n\n searchResponse = client().prepareSearch().setQuery(matchAllQuery()).addStoredField(\"*3\").execute().actionGet();\n assertThat(searchResponse.getHits().getTotalHits(), equalTo(1L));\n assertThat(searchResponse.getHits().getHits().length, equalTo(1));\n assertThat(searchResponse.getHits().getAt(0).getFields().size(), equalTo(1));\n assertThat(searchResponse.getHits().getAt(0).getFields().get(\"field3\").getValue().toString(), equalTo(\"value3\"));\n\n\n searchResponse = client().prepareSearch()\n .setQuery(matchAllQuery())\n .addStoredField(\"*3\")\n .addStoredField(\"field1\")\n .addStoredField(\"field2\")\n .get();\n assertThat(searchResponse.getHits().getTotalHits(), equalTo(1L));\n assertThat(searchResponse.getHits().getHits().length, equalTo(1));\n assertThat(searchResponse.getHits().getAt(0).getFields().size(), equalTo(2));\n assertThat(searchResponse.getHits().getAt(0).getFields().get(\"field3\").getValue().toString(), equalTo(\"value3\"));\n assertThat(searchResponse.getHits().getAt(0).getFields().get(\"field1\").getValue().toString(), equalTo(\"value1\"));\n\n\n searchResponse = client().prepareSearch().setQuery(matchAllQuery()).addStoredField(\"field*\").execute().actionGet();\n assertThat(searchResponse.getHits().getTotalHits(), equalTo(1L));\n assertThat(searchResponse.getHits().getHits().length, equalTo(1));\n assertThat(searchResponse.getHits().getAt(0).getFields().size(), equalTo(2));\n assertThat(searchResponse.getHits().getAt(0).getFields().get(\"field3\").getValue().toString(), equalTo(\"value3\"));\n assertThat(searchResponse.getHits().getAt(0).getFields().get(\"field1\").getValue().toString(), equalTo(\"value1\"));\n\n searchResponse = client().prepareSearch().setQuery(matchAllQuery()).addStoredField(\"f*3\").execute().actionGet();\n assertThat(searchResponse.getHits().getTotalHits(), equalTo(1L));\n assertThat(searchResponse.getHits().getHits().length, equalTo(1));\n assertThat(searchResponse.getHits().getAt(0).getFields().size(), equalTo(1));\n assertThat(searchResponse.getHits().getAt(0).getFields().get(\"field3\").getValue().toString(), equalTo(\"value3\"));\n\n searchResponse = client().prepareSearch().setQuery(matchAllQuery()).addStoredField(\"*\").execute().actionGet();\n assertThat(searchResponse.getHits().getTotalHits(), equalTo(1L));\n assertThat(searchResponse.getHits().getHits().length, equalTo(1));\n assertThat(searchResponse.getHits().getAt(0).getSourceAsMap(), nullValue());\n assertThat(searchResponse.getHits().getAt(0).getFields().size(), equalTo(2));\n assertThat(searchResponse.getHits().getAt(0).getFields().get(\"field1\").getValue().toString(), equalTo(\"value1\"));\n assertThat(searchResponse.getHits().getAt(0).getFields().get(\"field3\").getValue().toString(), equalTo(\"value3\"));\n\n searchResponse = client().prepareSearch()\n .setQuery(matchAllQuery())\n .addStoredField(\"*\")\n .addStoredField(\"_source\")\n .get();\n assertThat(searchResponse.getHits().getTotalHits(), equalTo(1L));\n assertThat(searchResponse.getHits().getHits().length, equalTo(1));\n assertThat(searchResponse.getHits().getAt(0).getSourceAsMap(), notNullValue());\n assertThat(searchResponse.getHits().getAt(0).getFields().size(), equalTo(2));\n assertThat(searchResponse.getHits().getAt(0).getFields().get(\"field1\").getValue().toString(), equalTo(\"value1\"));\n assertThat(searchResponse.getHits().getAt(0).getFields().get(\"field3\").getValue().toString(), equalTo(\"value3\"));\n }\n\n public void testScriptDocAndFields() throws Exception {\n createIndex(\"test\");\n\n String mapping = XContentFactory.jsonBuilder().startObject().startObject(\"type1\").startObject(\"properties\")\n .startObject(\"num1\").field(\"type\", \"double\").field(\"store\", true).endObject()\n .endObject().endObject().endObject().string();\n\n client().admin().indices().preparePutMapping().setType(\"type1\").setSource(mapping, XContentType.JSON).execute().actionGet();\n\n client().prepareIndex(\"test\", \"type1\", \"1\")\n .setSource(jsonBuilder().startObject()\n .field(\"test\", \"value beck\")\n .field(\"num1\", 1.0f)\n .field(\"date\", \"1970-01-01T00:00:00\")\n .endObject())\n .execute().actionGet();\n client().admin().indices().prepareFlush().execute().actionGet();\n client().prepareIndex(\"test\", \"type1\", \"2\")\n .setSource(jsonBuilder().startObject()\n .field(\"test\", \"value beck\")\n .field(\"num1\", 2.0f)\n .field(\"date\", \"1970-01-01T00:00:25\")\n .endObject())\n .get();\n client().admin().indices().prepareFlush().execute().actionGet();\n client().prepareIndex(\"test\", \"type1\", \"3\")\n .setSource(jsonBuilder().startObject()\n .field(\"test\", \"value beck\")\n .field(\"num1\", 3.0f)\n .field(\"date\", \"1970-01-01T00:02:00\")\n .endObject())\n .get();\n client().admin().indices().refresh(refreshRequest()).actionGet();\n\n logger.info(\"running doc['num1'].value\");\n SearchResponse response = client().prepareSearch()\n .setQuery(matchAllQuery())\n .addSort(\"num1\", SortOrder.ASC)\n .addScriptField(\"sNum1\",\n new Script(ScriptType.INLINE, CustomScriptPlugin.NAME, \"doc['num1'].value\", Collections.emptyMap()))\n .addScriptField(\"sNum1_field\",", "answers": [" new Script(ScriptType.INLINE, CustomScriptPlugin.NAME, \"_fields['num1'].value\", Collections.emptyMap()))"], "length": 760, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "ca862cee-c500-4c02-b744-8161022ef8f6", "reasoning": "In the testScriptDocAndFields method, after adding a script field for \"sNum1\" using the inline script \"doc['num1'].value\", the next logical step is to add another script field that uses the fields API script defined earlier (\"_fields['num1'].value\"). This matches the pattern of chaining .addScriptField calls, so the next line should be another .addScriptField call with the appropriate Script object.", "reasoning_model_answer": ".addScriptField(\"sNum1_field\", new Script(ScriptType.INLINE, CustomScriptPlugin.NAME, \"_fields['num1'].value\", Collections.emptyMap()))", "assistant_with_reasoning": "\nIn the testScriptDocAndFields method, after adding a script field for \"sNum1\" using the inline script \"doc['num1'].value\", the next logical step is to add another script field that uses the fields API script defined earlier (\"_fields['num1'].value\"). This matches the pattern of chaining .addScriptField calls, so the next line should be another .addScriptField call with the appropriate Script object.\n\n.addScriptField(\"sNum1_field\", new Script(ScriptType.INLINE, CustomScriptPlugin.NAME, \"_fields['num1'].value\", Collections.emptyMap()))", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.186, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 15741, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": ".addScriptField(\"sNum1_field\", new Script(ScriptType.INLINE, CustomScriptPlugin.NAME, \"_fields['num1'].value\", Collections.emptyMap()))", "score": 0.81, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "from __future__ import division\n\nimport pickle\nfrom io import BytesIO\nimport numpy as np\nimport scipy.sparse\n\nfrom sklearn.datasets import load_digits, load_iris\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.model_selection import cross_val_score\n\nfrom sklearn.externals.six.moves import zip\nfrom sklearn.utils.testing import assert_almost_equal\nfrom sklearn.utils.testing import assert_array_equal\nfrom sklearn.utils.testing import assert_array_almost_equal\nfrom sklearn.utils.testing import assert_equal\nfrom sklearn.utils.testing import assert_raises\nfrom sklearn.utils.testing import assert_raise_message\nfrom sklearn.utils.testing import assert_greater\nfrom sklearn.utils.testing import assert_warns\n\nfrom sklearn.naive_bayes import GaussianNB, BernoulliNB\nfrom sklearn.naive_bayes import MultinomialNB, ComplementNB\n\n# Data is just 6 separable points in the plane\nX = np.array([[-2, -1], [-1, -1], [-1, -2], [1, 1], [1, 2], [2, 1]])\ny = np.array([1, 1, 1, 2, 2, 2])\n\n# A bit more random tests\nrng = np.random.RandomState(0)\nX1 = rng.normal(size=(10, 3))\ny1 = (rng.normal(size=(10)) > 0).astype(np.int)\n\n# Data is 6 random integer points in a 100 dimensional space classified to\n# three classes.\nX2 = rng.randint(5, size=(6, 100))\ny2 = np.array([1, 1, 2, 2, 3, 3])\n\n\ndef test_gnb():\n # Gaussian Naive Bayes classification.\n # This checks that GaussianNB implements fit and predict and returns\n # correct values for a simple toy dataset.\n\n clf = GaussianNB()\n y_pred = clf.fit(X, y).predict(X)\n assert_array_equal(y_pred, y)\n\n y_pred_proba = clf.predict_proba(X)\n y_pred_log_proba = clf.predict_log_proba(X)\n assert_array_almost_equal(np.log(y_pred_proba), y_pred_log_proba, 8)\n\n # Test whether label mismatch between target y and classes raises\n # an Error\n # FIXME Remove this test once the more general partial_fit tests are merged\n assert_raises(ValueError, GaussianNB().partial_fit, X, y, classes=[0, 1])\n\n\ndef test_gnb_prior():\n # Test whether class priors are properly set.\n clf = GaussianNB().fit(X, y)\n assert_array_almost_equal(np.array([3, 3]) / 6.0,\n clf.class_prior_, 8)\n clf.fit(X1, y1)\n # Check that the class priors sum to 1\n assert_array_almost_equal(clf.class_prior_.sum(), 1)\n\n\ndef test_gnb_sample_weight():\n \"\"\"Test whether sample weights are properly used in GNB. \"\"\"\n # Sample weights all being 1 should not change results\n sw = np.ones(6)\n clf = GaussianNB().fit(X, y)\n clf_sw = GaussianNB().fit(X, y, sw)\n\n assert_array_almost_equal(clf.theta_, clf_sw.theta_)\n assert_array_almost_equal(clf.sigma_, clf_sw.sigma_)\n\n # Fitting twice with half sample-weights should result\n # in same result as fitting once with full weights\n sw = rng.rand(y.shape[0])\n clf1 = GaussianNB().fit(X, y, sample_weight=sw)\n clf2 = GaussianNB().partial_fit(X, y, classes=[1, 2], sample_weight=sw / 2)\n clf2.partial_fit(X, y, sample_weight=sw / 2)\n\n assert_array_almost_equal(clf1.theta_, clf2.theta_)\n assert_array_almost_equal(clf1.sigma_, clf2.sigma_)\n\n # Check that duplicate entries and correspondingly increased sample\n # weights yield the same result\n ind = rng.randint(0, X.shape[0], 20)\n sample_weight = np.bincount(ind, minlength=X.shape[0])\n\n clf_dupl = GaussianNB().fit(X[ind], y[ind])\n clf_sw = GaussianNB().fit(X, y, sample_weight)\n\n assert_array_almost_equal(clf_dupl.theta_, clf_sw.theta_)\n assert_array_almost_equal(clf_dupl.sigma_, clf_sw.sigma_)\n\n\ndef test_gnb_neg_priors():\n \"\"\"Test whether an error is raised in case of negative priors\"\"\"\n clf = GaussianNB(priors=np.array([-1., 2.]))\n assert_raises(ValueError, clf.fit, X, y)\n\n\ndef test_gnb_priors():\n \"\"\"Test whether the class prior override is properly used\"\"\"\n clf = GaussianNB(priors=np.array([0.3, 0.7])).fit(X, y)\n assert_array_almost_equal(clf.predict_proba([[-0.1, -0.1]]),\n np.array([[0.825303662161683,\n 0.174696337838317]]), 8)\n assert_array_almost_equal(clf.class_prior_, np.array([0.3, 0.7]))\n\n\ndef test_gnb_wrong_nb_priors():\n \"\"\" Test whether an error is raised if the number of prior is different\n from the number of class\"\"\"\n clf = GaussianNB(priors=np.array([.25, .25, .25, .25]))\n assert_raises(ValueError, clf.fit, X, y)\n\n\ndef test_gnb_prior_greater_one():\n \"\"\"Test if an error is raised if the sum of prior greater than one\"\"\"\n clf = GaussianNB(priors=np.array([2., 1.]))\n assert_raises(ValueError, clf.fit, X, y)\n\n\ndef test_gnb_prior_large_bias():\n \"\"\"Test if good prediction when class prior favor largely one class\"\"\"\n clf = GaussianNB(priors=np.array([0.01, 0.99]))\n clf.fit(X, y)\n assert_equal(clf.predict([[-0.1, -0.1]]), np.array([2]))\n\n\ndef test_check_update_with_no_data():\n \"\"\" Test when the partial fit is called without any data\"\"\"\n # Create an empty array\n prev_points = 100\n mean = 0.\n var = 1.\n x_empty = np.empty((0, X.shape[1]))\n tmean, tvar = GaussianNB._update_mean_variance(prev_points, mean,\n var, x_empty)\n assert_equal(tmean, mean)\n assert_equal(tvar, var)\n\n\ndef test_gnb_pfit_wrong_nb_features():\n \"\"\"Test whether an error is raised when the number of feature changes\n between two partial fit\"\"\"\n clf = GaussianNB()\n # Fit for the first time the GNB\n clf.fit(X, y)\n # Partial fit a second time with an incoherent X\n assert_raises(ValueError, clf.partial_fit, np.hstack((X, X)), y)\n\n\ndef test_discrete_prior():\n # Test whether class priors are properly set.\n for cls in [BernoulliNB, MultinomialNB]:\n clf = cls().fit(X2, y2)\n assert_array_almost_equal(np.log(np.array([2, 2, 2]) / 6.0),\n clf.class_log_prior_, 8)\n\n\ndef test_mnnb():\n # Test Multinomial Naive Bayes classification.\n # This checks that MultinomialNB implements fit and predict and returns\n # correct values for a simple toy dataset.\n\n for X in [X2, scipy.sparse.csr_matrix(X2)]:\n # Check the ability to predict the learning set.\n clf = MultinomialNB()\n assert_raises(ValueError, clf.fit, -X, y2)\n y_pred = clf.fit(X, y2).predict(X)\n\n assert_array_equal(y_pred, y2)\n\n # Verify that np.log(clf.predict_proba(X)) gives the same results as\n # clf.predict_log_proba(X)\n y_pred_proba = clf.predict_proba(X)\n y_pred_log_proba = clf.predict_log_proba(X)\n assert_array_almost_equal(np.log(y_pred_proba), y_pred_log_proba, 8)\n\n # Check that incremental fitting yields the same results\n clf2 = MultinomialNB()\n clf2.partial_fit(X[:2], y2[:2], classes=np.unique(y2))\n clf2.partial_fit(X[2:5], y2[2:5])\n clf2.partial_fit(X[5:], y2[5:])\n\n y_pred2 = clf2.predict(X)\n assert_array_equal(y_pred2, y2)\n\n y_pred_proba2 = clf2.predict_proba(X)\n y_pred_log_proba2 = clf2.predict_log_proba(X)\n assert_array_almost_equal(np.log(y_pred_proba2), y_pred_log_proba2, 8)\n assert_array_almost_equal(y_pred_proba2, y_pred_proba)\n assert_array_almost_equal(y_pred_log_proba2, y_pred_log_proba)\n\n # Partial fit on the whole data at once should be the same as fit too\n clf3 = MultinomialNB()\n clf3.partial_fit(X, y2, classes=np.unique(y2))", "answers": [" y_pred3 = clf3.predict(X)"], "length": 758, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "eb5af099-98db-4068-95ec-3f1841af8558", "reasoning": "The test function is checking MultinomialNB behavior. After creating clf3 and calling partial_fit on the whole dataset, the next logical step is to obtain predictions from clf3 to compare with the true labels, following the pattern used earlier for clf2. Therefore the next line should compute predictions with clf3.predict(X).", "reasoning_model_answer": "y_pred3 = clf3.predict(X)", "assistant_with_reasoning": "\nThe test function is checking MultinomialNB behavior. After creating clf3 and calling partial_fit on the whole dataset, the next logical step is to obtain predictions from clf3 to compare with the true labels, following the pattern used earlier for clf2. Therefore the next line should compute predictions with clf3.predict(X).\n\ny_pred3 = clf3.predict(X)", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 5.375, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 7518, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "y_pred3 = clf3.predict(X)", "score": 0.86, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "#!/usr/bin/env python\n\n\"\"\"Ninja toolchain abstraction for Clang compiler suite\"\"\"\n\nimport os\nimport subprocess\n\nimport toolchain\n\nclass ClangToolchain(toolchain.Toolchain):\n\n def initialize(self, project, archs, configs, includepaths, dependlibs, libpaths, variables, subninja):\n #Local variable defaults\n self.toolchain = ''\n self.sdkpath = ''\n self.includepaths = []\n self.libpaths = libpaths\n self.ccompiler = os.environ.get('CC') or 'clang'\n self.cxxcompiler = os.environ.get('CXX') or 'clang++'\n if self.target.is_windows():\n self.archiver = os.environ.get('AR') or 'llvm-ar'\n self.linker = os.environ.get('CC') or 'lld-link'\n self.cxxlinker = os.environ.get('CXX') or 'lld-link'\n else:\n self.archiver = os.environ.get('AR') or 'ar'\n self.linker = os.environ.get('CC') or 'clang'\n self.cxxlinker = os.environ.get('CXX') or 'clang++'\n\n #Default variables\n self.sysroot = ''\n if self.target.is_ios():\n self.deploymenttarget = '9.0'\n if self.target.is_macos():\n self.deploymenttarget = '10.7'\n\n #Command definitions\n self.cccmd = '$toolchain$cc -MMD -MT $out -MF $out.d $includepaths $moreincludepaths $cflags $carchflags $cconfigflags $cmoreflags $cenvflags -c $in -o $out'\n self.cxxcmd = '$toolchain$cxx -MMD -MT $out -MF $out.d $includepaths $moreincludepaths $cxxflags $carchflags $cconfigflags $cmoreflags $cxxenvflags -c $in -o $out'\n self.ccdeps = 'gcc'\n self.ccdepfile = '$out.d'\n self.arcmd = self.rmcmd('$out') + ' && $toolchain$ar crsD $ararchflags $arflags $arenvflags $out $in'\n if self.target.is_windows():\n self.linkcmd = '$toolchain$link $libpaths $configlibpaths $linkflags $linkarchflags $linkconfigflags $linkenvflags /debug /nologo /subsystem:console /dynamicbase /nxcompat /manifest /manifestuac:\\\"level=\\'asInvoker\\' uiAccess=\\'false\\'\\\" /tlbid:1 /pdb:$pdbpath /out:$out $in $libs $archlibs $oslibs $frameworks'\n self.dllcmd = self.linkcmd + ' /dll'\n else:\n self.linkcmd = '$toolchain$link $libpaths $configlibpaths $linkflags $linkarchflags $linkconfigflags $linkenvflags -o $out $in $libs $archlibs $oslibs $frameworks'\n\n #Base flags\n self.cflags = ['-D' + project.upper() + '_COMPILE=1',\n '-funit-at-a-time', '-fstrict-aliasing', '-fvisibility=hidden', '-fno-stack-protector',\n '-fno-math-errno','-ffinite-math-only', '-funsafe-math-optimizations',\n '-fno-trapping-math', '-ffast-math']\n self.cwarnflags = ['-W', '-Werror', '-pedantic', '-Wall', '-Weverything',\n '-Wno-c++98-compat', '-Wno-padded', '-Wno-documentation-unknown-command',\n '-Wno-implicit-fallthrough', '-Wno-static-in-inline', '-Wno-reserved-id-macro', '-Wno-disabled-macro-expansion']\n self.cmoreflags = []\n self.mflags = []\n self.arflags = []\n self.linkflags = []\n self.oslibs = []\n self.frameworks = []\n\n self.initialize_subninja(subninja)\n self.initialize_archs(archs)\n self.initialize_configs(configs)\n self.initialize_project(project)\n self.initialize_toolchain()\n self.initialize_depends(dependlibs)\n\n self.parse_default_variables(variables)\n self.read_build_prefs()\n\n if self.target.is_linux() or self.target.is_bsd() or self.target.is_raspberrypi() or self.target.is_sunos():\n self.cflags += ['-D_GNU_SOURCE=1']\n self.linkflags += ['-pthread']\n self.oslibs += ['m']\n if self.target.is_linux() or self.target.is_raspberrypi():\n self.oslibs += ['dl']\n if self.target.is_raspberrypi():\n self.linkflags += ['-latomic']\n if self.target.is_bsd():\n self.oslibs += ['execinfo']\n if self.target.is_haiku():\n self.cflags += ['-D_GNU_SOURCE=1']\n self.linkflags += ['-lpthread']\n self.oslibs += ['m']\n if (not self.target.is_windows()) and (not self.target.is_macos()) and (not self.target.is_ios()):\n self.linkflags += ['-fomit-frame-pointer']\n if self.target.is_macos() or self.target.is_ios():\n # Needed for backtrace() system call (implemented as simple frame pointer walk by Apple)\n self.cflags += ['-fno-omit-frame-pointer']\n else:\n self.cflags += ['-fomit-frame-pointer']\n\n self.includepaths = self.prefix_includepaths((includepaths or []) + ['.'])\n\n if self.is_monolithic():\n self.cflags += ['-DBUILD_MONOLITHIC=1']\n if self.use_coverage():\n self.cflags += ['--coverage']\n self.linkflags += ['--coverage']\n\n if not 'nowarning' in variables or not variables['nowarning']:\n self.cflags += self.cwarnflags\n else:\n self.cflags += ['-w']\n self.cxxflags = list(self.cflags)\n\n self.cflags += ['-std=c11']\n if self.target.is_macos() or self.target.is_ios():\n self.cxxflags += ['-std=c++14', '-stdlib=libc++']\n else:\n self.cxxflags += ['-std=c++14']\n\n #Overrides\n self.objext = '.o'\n\n #Builders\n self.builders['c'] = self.builder_cc\n self.builders['cc'] = self.builder_cxx\n self.builders['cpp'] = self.builder_cxx\n self.builders['lib'] = self.builder_lib\n self.builders['sharedlib'] = self.builder_sharedlib\n self.builders['bin'] = self.builder_bin\n if self.target.is_macos() or self.target.is_ios():\n self.builders['m'] = self.builder_cm\n self.builders['multilib'] = self.builder_apple_multilib\n self.builders['multisharedlib'] = self.builder_apple_multisharedlib\n self.builders['multibin'] = self.builder_apple_multibin\n else:\n self.builders['multilib'] = self.builder_multicopy\n self.builders['multisharedlib'] = self.builder_multicopy\n self.builders['multibin'] = self.builder_multicopy\n\n #Setup target platform\n self.build_toolchain()\n\n def name(self):\n return 'clang'\n\n def parse_prefs(self, prefs):\n super(ClangToolchain, self).parse_prefs(prefs)\n if 'clang' in prefs:\n clangprefs = prefs['clang']\n if 'toolchain' in clangprefs:\n self.toolchain = clangprefs['toolchain']\n if os.path.split(self.toolchain)[1] != 'bin':\n self.toolchain = os.path.join(self.toolchain, 'bin')\n if 'archiver' in clangprefs:\n self.archiver = clangprefs['archiver']\n if self.target.is_ios() and 'ios' in prefs:\n iosprefs = prefs['ios']\n if 'deploymenttarget' in iosprefs:\n self.deploymenttarget = iosprefs['deploymenttarget']\n if self.target.is_macos() and 'macos' in prefs:\n macosprefs = prefs['macos']\n if 'deploymenttarget' in macosprefs:\n self.deploymenttarget = macosprefs['deploymenttarget']\n\n def write_variables(self, writer):\n super(ClangToolchain, self).write_variables(writer)\n writer.variable('toolchain', self.toolchain)\n writer.variable('sdkpath', self.sdkpath)\n writer.variable('sysroot', self.sysroot)\n writer.variable('cc', self.ccompiler)\n writer.variable('cxx', self.cxxcompiler)\n writer.variable('ar', self.archiver)\n writer.variable('link', self.linker)\n if self.target.is_macos() or self.target.is_ios():\n writer.variable('lipo', self.lipo)\n writer.variable('includepaths', self.make_includepaths(self.includepaths))\n writer.variable('moreincludepaths', '')\n writer.variable('cflags', self.cflags)\n writer.variable('cxxflags', self.cxxflags)\n if self.target.is_macos() or self.target.is_ios():\n writer.variable('mflags', self.mflags)\n writer.variable('carchflags', '')\n writer.variable('cconfigflags', '')\n writer.variable('cmoreflags', self.cmoreflags)\n writer.variable('cenvflags', (os.environ.get('CFLAGS') or '').split())\n writer.variable('cxxenvflags', (os.environ.get('CXXFLAGS') or '').split())\n writer.variable('arflags', self.arflags)\n writer.variable('ararchflags', '')\n writer.variable('arconfigflags', '')\n writer.variable('arenvflags', (os.environ.get('ARFLAGS') or '').split())\n writer.variable('linkflags', self.linkflags)\n writer.variable('linkarchflags', '')\n writer.variable('linkconfigflags', '')\n writer.variable('linkenvflags', (os.environ.get('LDFLAGS') or '').split())\n writer.variable('libs', '')\n writer.variable('libpaths', self.make_libpaths(self.libpaths))\n writer.variable('configlibpaths', '')\n writer.variable('archlibs', '')\n writer.variable('oslibs', self.make_libs(self.oslibs))\n writer.variable('frameworks', '')\n if self.target.is_windows():\n writer.variable('pdbpath', 'ninja.pdb')\n writer.newline()\n\n def write_rules(self, writer):\n super(ClangToolchain, self).write_rules(writer)\n writer.rule('cc', command = self.cccmd, depfile = self.ccdepfile, deps = self.ccdeps, description = 'CC $in')\n writer.rule('cxx', command = self.cxxcmd, depfile = self.ccdepfile, deps = self.ccdeps, description = 'CXX $in')\n if self.target.is_macos() or self.target.is_ios():\n writer.rule('cm', command = self.cmcmd, depfile = self.ccdepfile, deps = self.ccdeps, description = 'CM $in')\n writer.rule( 'lipo', command = self.lipocmd, description = 'LIPO $out' )", "answers": [" writer.rule('ar', command = self.arcmd, description = 'LIB $out')"], "length": 680, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "f0549c21-6362-4e91-a8ad-1cf30d2dc7f2", "reasoning": "The write_rules method defines Ninja build rules. After handling macOS/iOS specific rules for 'cm' and 'lipo', the next logical rule is for the archiver, using the previously defined self.arcmd. Following the existing style, the line should call writer.rule with the name 'ar', the command self.arcmd, and a description.", "reasoning_model_answer": "writer.rule('ar', command = self.arcmd, description = 'AR $out')", "assistant_with_reasoning": "\nThe write_rules method defines Ninja build rules. After handling macOS/iOS specific rules for 'cm' and 'lipo', the next logical rule is for the archiver, using the previously defined self.arcmd. Following the existing style, the line should call writer.rule with the name 'ar', the command self.arcmd, and a description.\n\nwriter.rule('ar', command = self.arcmd, description = 'AR $out')", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 5.328, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 9099, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "writer.rule('ar', command = self.arcmd, description = 'AR $out')", "score": 0.93, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/*\n * Copyright 2015 Network New Technologies Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.networknt.light.server.handler;\n\nimport com.fasterxml.jackson.core.type.TypeReference;\nimport com.fasterxml.jackson.databind.ObjectMapper;\nimport com.networknt.light.server.LightServer;\nimport com.networknt.light.util.ServiceLocator;\nimport junit.framework.Test;\nimport junit.framework.TestCase;\nimport junit.framework.TestSuite;\nimport org.apache.http.HttpEntity;\nimport org.apache.http.HttpResponse;\nimport org.apache.http.StatusLine;\nimport org.apache.http.client.methods.CloseableHttpResponse;\nimport org.apache.http.client.methods.HttpGet;\nimport org.apache.http.client.methods.HttpPost;\nimport org.apache.http.entity.StringEntity;\nimport org.apache.http.impl.client.CloseableHttpClient;\nimport org.apache.http.impl.client.HttpClients;\nimport org.apache.http.util.EntityUtils;\nimport org.junit.Assert;\n\nimport java.io.BufferedReader;\nimport java.io.InputStreamReader;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\n/**\n * Created by husteve on 8/25/2014.\n */\npublic class RestHandlerTest extends TestCase {\n String signInOwner = \"{\\\"readOnly\\\":false,\\\"category\\\":\\\"user\\\",\\\"name\\\":\\\"signInUser\\\",\\\"data\\\":{\\\"host\\\":\\\"example\\\",\\\"userIdEmail\\\":\\\"stevehu\\\",\\\"password\\\":\\\"123456\\\",\\\"rememberMe\\\":true,\\\"clientId\\\":\\\"example@Browser\\\"}}\";\n\n // user @rid will be getting from jwt token\n String logOutAdmin = \"{\\\"readOnly\\\":false,\\\"category\\\":\\\"user\\\",\\\"name\\\":\\\"logOutUser\\\",\\\"data\\\":{\\\"host\\\":\\\"example\\\"}}\";\n\n String getUserByUserId = \"{\\\"readOnly\\\":true,\\\"category\\\":\\\"user\\\",\\\"name\\\":\\\"getUser\\\",\\\"data\\\":{\\\"host\\\":\\\"example\\\",\\\"userId\\\":\\\"steve\\\"}}\";\n String logOutUser = \"{\\\"readOnly\\\":false,\\\"category\\\":\\\"user\\\",\\\"name\\\":\\\"logOutUser\\\",\\\"data\\\":{\\\"host\\\":\\\"example\\\",\\\"userId\\\":\\\"steve\\\"}}\";\n String delUser = \"{\\\"readOnly\\\": false, \\\"category\\\": \\\"user\\\", \\\"name\\\": \\\"delUser\\\", \\\"data\\\": {\\\"host\\\":\\\"example\\\",\\\"userId\\\":\\\"steve\\\"}}\";\n\n String signUpJson = \"{\\\"readOnly\\\":false,\\\"category\\\":\\\"user\\\",\\\"name\\\":\\\"signUpUser\\\",\\\"data\\\":{\\\"host\\\":\\\"example\\\",\\\"userId\\\":\\\"steve\\\",\\\"email\\\":\\\"steve@gmail.com\\\",\\\"password\\\":\\\"abcdefg\\\",\\\"passwordConfirm\\\":\\\"abcdefg\\\",\\\"firstName\\\":\\\"steve\\\",\\\"lastName\\\":\\\"hu\\\"}}\";\n String getUserByEmail = \"{\\\"readOnly\\\":true,\\\"category\\\":\\\"user\\\",\\\"name\\\":\\\"getUser\\\",\\\"data\\\":{\\\"host\\\":\\\"example\\\",\\\"email\\\":\\\"steve@gmail.com\\\"}}\";\n\n String signInJsonEmail = \"{\\\"readOnly\\\":false,\\\"category\\\":\\\"user\\\",\\\"name\\\":\\\"signInUser\\\",\\\"data\\\":{\\\"host\\\":\\\"example\\\",\\\"userIdEmail\\\":\\\"steve@gmail.com\\\",\\\"password\\\":\\\"abcdefg\\\",\\\"rememberMe\\\":false}}\";\n String signInByUserId = \"{\\\"readOnly\\\":false,\\\"category\\\":\\\"user\\\",\\\"name\\\":\\\"signInUser\\\",\\\"data\\\":{\\\"host\\\":\\\"example\\\",\\\"clientId\\\":\\\"example@Browser\\\",\\\"userIdEmail\\\":\\\"steve\\\",\\\"password\\\":\\\"abcdefg\\\",\\\"rememberMe\\\":true}}\";\n\n String updPasswordJson = \"{\\\"readOnly\\\":false,\\\"category\\\":\\\"user\\\",\\\"name\\\":\\\"updPassword\\\",\\\"data\\\":{\\\"host\\\":\\\"example\\\",\\\"userId\\\":\\\"steve\\\",\\\"password\\\":\\\"abcdefg\\\",\\\"newPassword\\\":\\\"123456\\\",\\\"passwordConfirm\\\":\\\"123456\\\"}}\";\n String signInJsonNewPass = \"{\\\"readOnly\\\": true, \\\"category\\\": \\\"user\\\", \\\"name\\\": \\\"signInUser\\\", \\\"data\\\": {\\\"host\\\":\\\"example\\\",\\\"userIdEmail\\\":\\\"steveu@gmail.com\\\", \\\"password\\\": \\\"123456\\\"}}\";\n\n String updProfileJson = \"{\\\"readOnly\\\":false,\\\"category\\\":\\\"user\\\",\\\"name\\\":\\\"updProfile\\\",\\\"data\\\":{\\\"host\\\":\\\"example\\\",\\\"userId\\\":\\\"steve\\\",\\\"firstName\\\":\\\"Steve\\\",\\\"lastName\\\":\\\"Hu\\\"}}\";\n\n\n String addJson = \"{\\\"readOnly\\\": false, \\\"category\\\": \\\"form\\\", \\\"name\\\": \\\"addForm\\\", \\\"data\\\": {\\\"host\\\":\\\"example\\\",\\\"id\\\": \\\"com.networknt.light.common.test.json\\\", \\\"schema\\\": {\\\"type\\\": \\\"object\\\", \\\"title\\\": \\\"Comment\\\",\\\"properties\\\": { \\\"name\\\": { \\\"title\\\": \\\"Name\\\",\\\"type\\\": \\\"string\\\"}, \\\"email\\\": {\\n \\\"title\\\": \\\"Email\\\",\\n \\\"type\\\": \\\"string\\\",\\n \\\"pattern\\\": \\\"^\\\\\\\\S+@\\\\\\\\S+$\\\",\\n \\\"description\\\": \\\"Email will be used for evil.\\\"\\n },\\n \\\"comment\\\": {\\n \\\"title\\\": \\\"Comment\\\",\\n \\\"type\\\": \\\"string\\\",\\n \\\"maxLength\\\": 20,\\n \\\"validationMessage\\\": \\\"Don't be greedy!\\\"\\n }\\n },\\n \\\"required\\\": [\\\"name\\\",\\\"email\\\",\\\"comment\\\"]\\n },\\n \\\"form\\\": [\\n \\\"name\\\",\\n \\\"email\\\",\\n {\\n \\\"key\\\": \\\"comment\\\",\\n \\\"type\\\": \\\"textarea\\\"\\n },\\n {\\n \\\"type\\\": \\\"submit\\\",\\n\\t \\\"style\\\": \\\"btn-info\\\",\\n \\\"title\\\": \\\"OK\\\"} ]}}\";\n String getJson = \"{\\\"readOnly\\\": true, \\\"category\\\": \\\"form\\\", \\\"name\\\": \\\"getForm\\\", \\\"data\\\": {\\\"host\\\":\\\"example\\\",\\\"id\\\":\\\"com.networknt.light.common.test.json\\\"}}\";\n String updJson = \"{\\\"readOnly\\\": false, \\\"category\\\": \\\"form\\\", \\\"name\\\": \\\"updForm\\\", \\\"data\\\": {\\\"host\\\":\\\"example\\\",\\\"id\\\": \\\"com.networknt.light.common.test.json\\\", \\\"version\\\": 0, \\\"schema\\\": {\\\"type\\\": \\\"object\\\", \\\"title\\\": \\\"Updated Comment\\\",\\\"properties\\\": { \\\"name\\\": { \\\"title\\\": \\\"Name\\\",\\\"type\\\": \\\"string\\\"}, \\\"email\\\": {\\n \\\"title\\\": \\\"Email\\\",\\n \\\"type\\\": \\\"string\\\",\\n \\\"pattern\\\": \\\"^\\\\\\\\S+@\\\\\\\\S+$\\\",\\n \\\"description\\\": \\\"Email will be used for evil.\\\"\\n },\\n \\\"comment\\\": {\\n \\\"title\\\": \\\"Comment\\\",\\n \\\"type\\\": \\\"string\\\",\\n \\\"maxLength\\\": 20,\\n \\\"validationMessage\\\": \\\"Don't be greedy!\\\"\\n }\\n },\\n \\\"required\\\": [\\\"name\\\",\\\"email\\\",\\\"comment\\\"]\\n },\\n \\\"form\\\": [\\n \\\"name\\\",\\n \\\"email\\\",\\n {\\n \\\"key\\\": \\\"comment\\\",\\n \\\"type\\\": \\\"textarea\\\"\\n },\\n {\\n \\\"type\\\": \\\"submit\\\",\\n\\t \\\"style\\\": \\\"btn-info\\\",\\n \\\"title\\\": \\\"OK\\\"} ]}}\";\n String getAllJson = \"{\\\"readOnly\\\": true, \\\"category\\\": \\\"form\\\", \\\"name\\\": \\\"getAllForm\\\"}\";\n String delJson = \"{\\\"readOnly\\\": false, \\\"category\\\": \\\"form\\\", \\\"name\\\": \\\"delForm\\\", \\\"data\\\": {\\\"host\\\":\\\"example\\\",\\\"id\\\":\\\"com.networknt.light.common.test.json\\\", \\\"version\\\": 1}}\";\n\n String getMenuJson = \"{\\\"readOnly\\\": true, \\\"category\\\": \\\"menu\\\", \\\"name\\\": \\\"getMenu\\\", \\\"data\\\": {\\\"host\\\":\\\"example\\\"}}\";\n\n CloseableHttpClient httpclient = null;\n String ownerToken = null;\n\n public RestHandlerTest(String name) {\n super(name);\n }\n\n public static Test suite() {\n TestSuite suite = new TestSuite();\n suite.addTestSuite(RestHandlerTest.class);\n return suite;\n }\n\n public void setUp() throws Exception {\n LightServer.start();\n httpclient = HttpClients.createDefault();\n // get owner token here\n signInOwner();\n super.setUp();\n }\n\n public void tearDown() throws Exception {\n LightServer.stop();\n httpclient.close();\n super.tearDown();\n }\n\n /*\n public void testRewrite() throws Exception {\n HttpGet get = new HttpGet(\"http://example:8080/page/a\");\n HttpResponse response = httpclient.execute(get);\n Assert.assertEquals(StatusCodes.OK, response.getStatusLine().getStatusCode());\n }\n */\n\n public void testUser() throws Exception {\n\n cleanUpUser();\n signUpUser();\n // sleep 100 ms in order to make sure that signUp user is available in this\n // db connection. Orientdb sometimes needs to be synched between two calls\n Thread.sleep(100);\n signInUser();\n /*\n postGetUserByUserId();\n postGetUserByEmail();\n postAddForm();\n postGetForm();\n getForm();\n postUpdForm();\n postGetFormVerifyUpdate();\n postGetAllForm();\n postDelForm();\n postGetFormVerifyDelete();\n */\n }\n\n /*\n public void testForm() throws Exception {\n postAddForm();\n postGetForm();\n getForm();\n postUpdForm();\n postGetFormVerifyUpdate();\n postGetAllForm();\n postDelForm();\n postGetFormVerifyDelete();\n }\n */\n /*\n public void testMenu() throws Exception {\n postGetMenu();\n\n }\n */\n\n /**\n * Set ownerToken in case any action uses it to do update. For example delUser\n * @throws Exception\n */\n private void signInOwner() throws Exception {\n HttpPost httpPost = new HttpPost(\"http://example:8080/api/rs\");\n StringEntity input = new StringEntity(signInOwner);\n input.setContentType(\"application/json\");\n httpPost.setEntity(input);\n CloseableHttpResponse response = httpclient.execute(httpPost);\n\n try {\n assertEquals(200, response.getStatusLine().getStatusCode());\n HttpEntity entity = response.getEntity();\n BufferedReader rd = new BufferedReader(new InputStreamReader(entity.getContent()));\n String json = \"\";\n String line = \"\";\n while ((line = rd.readLine()) != null) {\n json = json + line;\n }\n System.out.println(\"json = \" + json);\n Map jsonMap = ServiceLocator.getInstance().getMapper().readValue(json,\n new TypeReference>() {\n });\n ownerToken = \"Bearer \" + (String)jsonMap.get(\"accessToken\");\n // and ensure it is fully consumed\n EntityUtils.consume(entity);\n } finally {\n response.close();\n }\n }\n\n /**\n * Delete test user in order to run the same signUp again and again.\n * @throws Exception\n */\n private void cleanUpUser() throws Exception {\n StatusLine statusLine = null;\n // getUser and check status\n HttpPost httpPost = new HttpPost(\"http://example:8080/api/rs\");\n StringEntity input = new StringEntity(getUserByUserId);\n input.setContentType(\"application/json\");\n httpPost.setEntity(input);\n httpPost.setHeader(\"Authorization\", ownerToken);\n\n CloseableHttpResponse response = httpclient.execute(httpPost);\n\n try {\n statusLine = response.getStatusLine();\n HttpEntity entity = response.getEntity();\n BufferedReader rd = new BufferedReader(new InputStreamReader(entity.getContent()));\n String json = \"\";\n String line = \"\";\n while ((line = rd.readLine()) != null) {\n json = json + line;\n }\n EntityUtils.consume(entity);\n } finally {\n response.close();\n }\n\n // delete user if it exists.\n if(statusLine.getStatusCode() == 200) {\n delUser();\n }\n }\n\n /**\n * Delete user in clean up above if the test user exists\n * @throws Exception\n */\n private void delUser() throws Exception {\n // getUser and check status\n HttpPost httpPost = new HttpPost(\"http://example:8080/api/rs\");\n StringEntity input = new StringEntity(delUser);\n input.setContentType(\"application/json\");", "answers": [" httpPost.setEntity(input);"], "length": 846, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "51418125-9aca-43d1-9b2e-cc424de282a0", "reasoning": "In the delUser method, after creating the HttpPost and the StringEntity and setting its content type, the next logical step—mirroring the pattern used in signInOwner and cleanUpUser—is to attach the entity to the request. This is done with httpPost.setEntity(input); which prepares the POST body before adding any headers or executing the request.", "reasoning_model_answer": "httpPost.setEntity(input);", "assistant_with_reasoning": "\nIn the delUser method, after creating the HttpPost and the StringEntity and setting its content type, the next logical step—mirroring the pattern used in signInOwner and cleanUpUser—is to attach the entity to the request. This is done with httpPost.setEntity(input); which prepares the POST body before adding any headers or executing the request.\n\nhttpPost.setEntity(input);", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.078, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 11429, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "httpPost.setEntity(input);", "score": 0.87, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "# -*- coding: utf8 -*-\n# *****************************************************************************\n# * *\n# * Copyright (c) 2017 *\n# * *\n# * This program is free software; you can redistribute it and/or modify *\n# * it under the terms of the GNU Lesser General Public License (LGPL) *\n# * as published by the Free Software Foundation; either version 2 of *\n# * the License, or (at your option) any later version. *\n# * For detail see the LICENSE text file. *\n# * *\n# * This program is distributed in the hope that it will be useful, *\n# * but WITHOUT ANY WARRANTY; without even the implied warranty of *\n# * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *\n# * See the GNU Library General Public License for more details. *\n# * *\n# * You should have received a copy of the GNU Library General Public *\n# * License along with this program; if not, write to the Free Software *\n# * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 *\n# * USA *\n# * *\n# *****************************************************************************\n\n\nfrom math import pi, degrees, radians, tan, cos, sin\nimport FreeCAD\nimport Part\nfrom SlopedPlanesPy import _Py\n\n\n__title__ = \"SlopedPlanes Macro\"\n__author__ = \"Damian Caceres Moreno\"\n__url__ = \"http://www.freecadweb.org\"\n__version__ = \"\"\n\n\nclass _PyPlane(_Py):\n\n '''The complementary python object class for planes.A plane correspond\n to one or more edges of the base. A plane could have several faces.'''\n\n def __init__(self, numWire, numGeom, slope=45.0):\n\n '''__init__(self, numWire, numGeom)'''\n\n self.alignedList = []\n self.chopedList = []\n self.frontedList = []\n self.rearedList = []\n self.reflexedList = []\n\n self.numWire = numWire\n self.numGeom = numGeom\n self.angle = slope\n size = _Py.size\n self.rightWidth = size\n self.leftWidth = size\n self.length = 2 * size\n self.overhang = 0\n self.rear = []\n self.secondRear = []\n self.under = []\n self.seed = []\n self.rango = []\n self.rangoPy = [] # TODO unir rangos\n self.reflexed = False\n self.aligned = False # quitar\n self.choped = False # quitar\n self.fronted = False # quitar\n self.arrow = False\n self.geom = None\n self.geomShape = None\n self.geomAligned = None\n self.shape = None\n self.bigShape = None\n self.enormousShape = None\n self.simulatedShape = None\n self.cutter = []\n self.forward = None\n self.backward = None\n self.virtualized = False\n self.virtuals = []\n self.control = [numGeom]\n self.seedShape = None\n self.seedBigShape = None\n self.lineInto = None\n self.cross = False\n self.solved = False\n self.reallySolved = False\n self.sweepCurve = None\n\n @property\n def alignedList(self):\n\n ''''''\n\n return self._alignedList\n\n @alignedList.setter\n def alignedList(self, alignedList):\n\n ''''''\n\n self._alignedList = alignedList\n\n @property\n def chopedList(self):\n\n ''''''\n\n return self._chopedList\n\n @chopedList.setter\n def chopedList(self, chopedList):\n\n ''''''\n\n self._chopedList = chopedList\n\n @property\n def frontedList(self):\n\n ''''''\n\n return self._frontedList\n\n @frontedList.setter\n def frontedList(self, frontedList):\n\n ''''''\n\n self._frontedList = frontedList\n\n @property\n def rearedList(self):\n\n ''''''\n\n return self._rearedList\n\n @rearedList.setter\n def rearedList(self, rearedList):\n\n ''''''\n\n self._rearedList = rearedList\n\n @property\n def reflexedList(self):\n\n ''''''\n\n return self._reflexedList\n\n @reflexedList.setter\n def reflexedList(self, reflexedList):\n\n ''''''\n\n self._reflexedList = reflexedList\n\n @property\n def numWire(self):\n\n ''''''\n\n return self._numWire\n\n @numWire.setter\n def numWire(self, numWire):\n\n ''''''\n\n self._numWire = numWire\n\n @property\n def numGeom(self):\n\n ''''''\n\n return self._numGeom\n\n @numGeom.setter\n def numGeom(self, numGeom):\n\n ''''''\n\n self._numGeom = numGeom\n\n @property\n def angle(self):\n\n ''''''\n\n return self._angle\n\n @angle.setter\n def angle(self, angle):\n\n ''''''\n\n try:\n oldAngle = self.angle\n if oldAngle != angle:\n self.seedShape = None\n except AttributeError:\n pass\n\n self._angle = angle\n\n @property\n def rightWidth(self):\n\n ''''''\n\n return self._rightWidth\n\n @rightWidth.setter\n def rightWidth(self, width):\n\n ''''''\n\n try:\n oldWidth = self.rightWidth\n if oldWidth != width:\n self.seedShape = None\n except AttributeError:\n pass\n\n self._rightWidth = width\n\n @property\n def leftWidth(self):\n\n ''''''\n\n return self._leftWidth\n\n @leftWidth.setter\n def leftWidth(self, width):\n\n ''''''\n\n try:\n oldWidth = self.leftWidth\n if oldWidth != width:\n self.seedShape = None\n except AttributeError:\n pass\n\n self._leftWidth = width\n\n @property\n def length(self):\n\n ''''''\n\n return self._length\n\n @length.setter\n def length(self, length):\n\n ''''''\n\n try:\n oldLength = self.length\n if oldLength != length:\n self.seedShape = None\n except AttributeError:\n pass\n\n self._length = length\n\n @property\n def overhang(self):\n\n ''''''\n\n return self._overhang\n\n @overhang.setter\n def overhang(self, overhang):\n\n ''''''\n\n try:\n oldOverhang = self.overhang\n if oldOverhang != overhang:\n self.seedShape = None\n except AttributeError:\n pass\n\n size = _Py.size\n if overhang > size:\n overhang = size\n\n self._overhang = overhang\n\n @property\n def rear(self):\n\n ''''''\n\n return self._rear\n\n @rear.setter\n def rear(self, rear):\n\n ''''''\n\n self._rear = rear\n\n @property\n def secondRear(self):\n\n ''''''\n\n return self._secondRear\n\n @secondRear.setter\n def secondRear(self, secondRear):\n\n ''''''\n\n self._secondRear = secondRear\n\n @property\n def under(self):\n\n ''''''\n\n return self._under\n\n @under.setter\n def under(self, under):\n\n ''''''\n\n self._under = under\n\n @property\n def seed(self):\n\n '''seed(self)\n Allowed location for a second face of a reflex plane'''\n\n return self._seed\n\n @seed.setter\n def seed(self, seed):\n\n ''''''\n\n self._seed = seed\n\n @property\n def rango(self):\n\n ''''''\n\n return self._rango\n\n @rango.setter\n def rango(self, rango):\n\n ''''''\n\n self._rango = rango\n\n @property\n def rangoPy(self):\n\n ''''''\n\n return self._rangoPy", "answers": [" @rangoPy.setter"], "length": 741, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "a375dd03-5824-4b3d-b74b-1bc6daa5a533", "reasoning": "The code defines a series of @property getters followed by corresponding @.setter methods. The last shown getter is for 'rangoPy', ending with 'return self._rangoPy'. The next logical line is the decorator for its setter, following the established pattern.", "reasoning_model_answer": "@rangoPy.setter", "assistant_with_reasoning": "\nThe code defines a series of @property getters followed by corresponding @.setter methods. The last shown getter is for 'rangoPy', ending with 'return self._rangoPy'. The next logical line is the decorator for its setter, following the established pattern.\n\n@rangoPy.setter", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 2.304, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 7985, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "@rangoPy.setter", "score": 0.88, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "from itertools import product as cartes\n\nfrom sympy import (limit, exp, oo, log, sqrt, Limit, sin, floor, cos, ceiling,\n atan, gamma, Symbol, S, pi, Integral, cot, Rational, I, zoo,\n tan, cot, integrate, Sum, sign)\n\nfrom sympy.series.limits import heuristics\nfrom sympy.series.order import Order\nfrom sympy.abc import x, y, z\nfrom sympy.utilities.pytest import XFAIL, raises\n\n\ndef test_basic1():\n assert limit(x, x, oo) == oo\n assert limit(x, x, -oo) == -oo\n assert limit(-x, x, oo) == -oo\n assert limit(x**2, x, -oo) == oo\n assert limit(-x**2, x, oo) == -oo\n assert limit(x*log(x), x, 0, dir=\"+\") == 0\n assert limit(1/x, x, oo) == 0\n assert limit(exp(x), x, oo) == oo\n assert limit(-exp(x), x, oo) == -oo\n assert limit(exp(x)/x, x, oo) == oo\n assert limit(1/x - exp(-x), x, oo) == 0\n assert limit(x + 1/x, x, oo) == oo\n assert limit(x - x**2, x, oo) == -oo\n assert limit((1 + x)**(1 + sqrt(2)), x, 0) == 1\n assert limit((1 + x)**oo, x, 0) == oo\n assert limit((1 + x)**oo, x, 0, dir='-') == 0\n assert limit((1 + x + y)**oo, x, 0, dir='-') == (1 + y)**(oo)\n assert limit(y/x/log(x), x, 0) == -oo*sign(y)\n assert limit(cos(x + y)/x, x, 0) == sign(cos(y))*oo\n raises(NotImplementedError, lambda: limit(Sum(1/x, (x, 1, y)) -\n log(y), y, oo))\n raises(NotImplementedError, lambda: limit(Sum(1/x, (x, 1, y)) - 1/y, y, oo))\n assert limit(gamma(1/x + 3), x, oo) == 2\n assert limit(S.NaN, x, -oo) == S.NaN\n assert limit(Order(2)*x, x, S.NaN) == S.NaN\n assert limit(gamma(1/x + 3), x, oo) == 2\n assert limit(S.NaN, x, -oo) == S.NaN\n assert limit(Order(2)*x, x, S.NaN) == S.NaN\n assert limit(1/(x - 1), x, 1, dir=\"+\") == oo\n assert limit(1/(x - 1), x, 1, dir=\"-\") == -oo\n assert limit(1/(5 - x)**3, x, 5, dir=\"+\") == -oo\n assert limit(1/(5 - x)**3, x, 5, dir=\"-\") == oo\n assert limit(1/sin(x), x, pi, dir=\"+\") == -oo\n assert limit(1/sin(x), x, pi, dir=\"-\") == oo\n assert limit(1/cos(x), x, pi/2, dir=\"+\") == -oo\n assert limit(1/cos(x), x, pi/2, dir=\"-\") == oo\n assert limit(1/tan(x**3), x, (2*pi)**(S(1)/3), dir=\"+\") == oo\n assert limit(1/tan(x**3), x, (2*pi)**(S(1)/3), dir=\"-\") == -oo\n assert limit(1/cot(x)**3, x, (3*pi/2), dir=\"+\") == -oo\n assert limit(1/cot(x)**3, x, (3*pi/2), dir=\"-\") == oo\n\n # approaching 0\n # from dir=\"+\"\n assert limit(1 + 1/x, x, 0) == oo\n # from dir='-'\n # Add\n assert limit(1 + 1/x, x, 0, dir='-') == -oo\n # Pow\n assert limit(x**(-2), x, 0, dir='-') == oo\n assert limit(x**(-3), x, 0, dir='-') == -oo\n assert limit(1/sqrt(x), x, 0, dir='-') == (-oo)*I\n assert limit(x**2, x, 0, dir='-') == 0\n assert limit(sqrt(x), x, 0, dir='-') == 0\n assert limit((1 + cos(x))**oo, x, 0) == oo\n\n\n@XFAIL\ndef test_basic1_xfail():\n assert limit(x**-pi, x, 0, dir='-') == zoo\n\n\ndef test_basic2():\n assert limit(x**x, x, 0, dir=\"+\") == 1\n assert limit((exp(x) - 1)/x, x, 0) == 1\n assert limit(1 + 1/x, x, oo) == 1\n assert limit(-exp(1/x), x, oo) == -1\n assert limit(x + exp(-x), x, oo) == oo\n assert limit(x + exp(-x**2), x, oo) == oo\n assert limit(x + exp(-exp(x)), x, oo) == oo\n assert limit(13 + 1/x - exp(-x), x, oo) == 13\n\n\ndef test_basic3():\n assert limit(1/x, x, 0, dir=\"+\") == oo\n assert limit(1/x, x, 0, dir=\"-\") == -oo\n\n\ndef test_basic4():\n assert limit(2*x + y*x, x, 0) == 0\n assert limit(2*x + y*x, x, 1) == 2 + y\n assert limit(2*x**8 + y*x**(-3), x, -2) == 512 - y/8\n assert limit(sqrt(x + 1) - sqrt(x), x, oo) == 0\n assert integrate(1/(x**3 + 1), (x, 0, oo)) == 2*pi*sqrt(3)/9\n\n\ndef test_issue786():\n assert limit(x*y + x*z, z, 2) == x*y + 2*x\n\n\ndef test_Limit():\n assert Limit(sin(x)/x, x, 0) != 1\n assert Limit(sin(x)/x, x, 0).doit() == 1\n\n\ndef test_floor():\n assert limit(floor(x), x, -2, \"+\") == -2\n assert limit(floor(x), x, -2, \"-\") == -3\n assert limit(floor(x), x, -1, \"+\") == -1\n assert limit(floor(x), x, -1, \"-\") == -2\n assert limit(floor(x), x, 0, \"+\") == 0\n assert limit(floor(x), x, 0, \"-\") == -1\n assert limit(floor(x), x, 1, \"+\") == 1\n assert limit(floor(x), x, 1, \"-\") == 0\n assert limit(floor(x), x, 2, \"+\") == 2\n assert limit(floor(x), x, 2, \"-\") == 1\n assert limit(floor(x), x, 248, \"+\") == 248\n assert limit(floor(x), x, 248, \"-\") == 247\n\n\ndef test_floor_requires_robust_assumptions():\n assert limit(floor(sin(x)), x, 0, \"+\") == 0\n assert limit(floor(sin(x)), x, 0, \"-\") == -1\n assert limit(floor(cos(x)), x, 0, \"+\") == 0\n assert limit(floor(cos(x)), x, 0, \"-\") == 0\n assert limit(floor(5 + sin(x)), x, 0, \"+\") == 5\n assert limit(floor(5 + sin(x)), x, 0, \"-\") == 4\n assert limit(floor(5 + cos(x)), x, 0, \"+\") == 5\n assert limit(floor(5 + cos(x)), x, 0, \"-\") == 5\n\n\ndef test_ceiling():\n assert limit(ceiling(x), x, -2, \"+\") == -1\n assert limit(ceiling(x), x, -2, \"-\") == -2", "answers": [" assert limit(ceiling(x), x, -1, \"+\") == 0"], "length": 758, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "771f4263-7435-450c-abbd-fb15023ba0a3", "reasoning": "The test_ceiling function mirrors the floor tests, checking limits of the ceiling function at various integer points from both sides. After the two asserts for x = -2, the next logical assertion tests x = -1 with a '+' direction, expecting -1. Hence the next line is the assert for ceiling at -1 from the right.", "reasoning_model_answer": "assert limit(ceiling(x), x, -1, \"+\") == -1", "assistant_with_reasoning": "\nThe test_ceiling function mirrors the floor tests, checking limits of the ceiling function at various integer points from both sides. After the two asserts for x = -2, the next logical assertion tests x = -1 with a '+' direction, expecting -1. Hence the next line is the assert for ceiling at -1 from the right.\n\nassert limit(ceiling(x), x, -1, \"+\") == -1", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 5.476, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 5022, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "assert limit(ceiling(x), x, -1, \"+\") == -1", "score": 0.92, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "#region Translated by Jose Antonio De Santiago-Castillo.\n\n//Translated by Jose Antonio De Santiago-Castillo.\n//E-mail:JAntonioDeSantiago@gmail.com\n//Website: www.DotNumerics.com\n//\n//Fortran to C# Translation.\n//Translated by:\n//F2CSharp Version 0.72 (Dicember 7, 2009)\n//Code Optimizations: , assignment operator, for-loop: array indexes\n//\n#endregion\n\nusing System;\nusing DotNumerics.FortranLibrary;\n\nnamespace DotNumerics.LinearAlgebra.CSLapack\n{\n /// \n /// -- LAPACK auxiliary routine (version 3.0) --\n /// Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd.,\n /// Courant Institute, Argonne National Lab, and Rice University\n /// October 31, 1992\n /// Purpose\n /// =======\n /// \n /// DLANTR returns the value of the one norm, or the Frobenius norm, or\n /// the infinity norm, or the element of largest absolute value of a\n /// trapezoidal or triangular matrix A.\n /// \n /// Description\n /// ===========\n /// \n /// DLANTR returns the value\n /// \n /// DLANTR = ( max(abs(A(i,j))), NORM = 'M' or 'm'\n /// (\n /// ( norm1(A), NORM = '1', 'O' or 'o'\n /// (\n /// ( normI(A), NORM = 'I' or 'i'\n /// (\n /// ( normF(A), NORM = 'F', 'f', 'E' or 'e'\n /// \n /// where norm1 denotes the one norm of a matrix (maximum column sum),\n /// normI denotes the infinity norm of a matrix (maximum row sum) and\n /// normF denotes the Frobenius norm of a matrix (square root of sum of\n /// squares). Note that max(abs(A(i,j))) is not a matrix norm.\n /// \n ///\n public class DLANTR\n {\n \n\n #region Dependencies\n \n DLASSQ _dlassq; LSAME _lsame; \n\n #endregion\n\n\n #region Variables\n \n const double ONE = 1.0E+0; const double ZERO = 0.0E+0; \n\n #endregion\n\n public DLANTR(DLASSQ dlassq, LSAME lsame)\n {\n \n\n #region Set Dependencies\n \n this._dlassq = dlassq; this._lsame = lsame; \n\n #endregion\n\n }\n \n public DLANTR()\n {\n \n\n #region Dependencies (Initialization)\n \n DLASSQ dlassq = new DLASSQ();\n LSAME lsame = new LSAME();\n\n #endregion\n\n\n #region Set Dependencies\n \n this._dlassq = dlassq; this._lsame = lsame; \n\n #endregion\n\n }\n /// \n /// Purpose\n /// =======\n /// \n /// DLANTR returns the value of the one norm, or the Frobenius norm, or\n /// the infinity norm, or the element of largest absolute value of a\n /// trapezoidal or triangular matrix A.\n /// \n /// Description\n /// ===========\n /// \n /// DLANTR returns the value\n /// \n /// DLANTR = ( max(abs(A(i,j))), NORM = 'M' or 'm'\n /// (\n /// ( norm1(A), NORM = '1', 'O' or 'o'\n /// (\n /// ( normI(A), NORM = 'I' or 'i'\n /// (\n /// ( normF(A), NORM = 'F', 'f', 'E' or 'e'\n /// \n /// where norm1 denotes the one norm of a matrix (maximum column sum),\n /// normI denotes the infinity norm of a matrix (maximum row sum) and\n /// normF denotes the Frobenius norm of a matrix (square root of sum of\n /// squares). Note that max(abs(A(i,j))) is not a matrix norm.\n /// \n ///\n /// \n /// (input) CHARACTER*1\n /// Specifies the value to be returned in DLANTR as described\n /// above.\n ///\n /// \n /// (input) CHARACTER*1\n /// Specifies whether the matrix A is upper or lower trapezoidal.\n /// = 'U': Upper trapezoidal\n /// = 'L': Lower trapezoidal\n /// Note that A is triangular instead of trapezoidal if M = N.\n ///\n /// \n /// (input) CHARACTER*1\n /// Specifies whether or not the matrix A has unit diagonal.\n /// = 'N': Non-unit diagonal\n /// = 'U': Unit diagonal\n ///\n /// \n /// (input) INTEGER\n /// The number of rows of the matrix A. M .GE. 0, and if\n /// UPLO = 'U', M .LE. N. When M = 0, DLANTR is set to zero.\n ///\n /// \n /// (input) INTEGER\n /// The number of columns of the matrix A. N .GE. 0, and if\n /// UPLO = 'L', N .LE. M. When N = 0, DLANTR is set to zero.\n ///\n /// \n /// (input) DOUBLE PRECISION array, dimension (LDA,N)\n /// The trapezoidal matrix A (A is triangular if M = N).\n /// If UPLO = 'U', the leading m by n upper trapezoidal part of\n /// the array A contains the upper trapezoidal matrix, and the\n /// strictly lower triangular part of A is not referenced.\n /// If UPLO = 'L', the leading m by n lower trapezoidal part of\n /// the array A contains the lower trapezoidal matrix, and the\n /// strictly upper triangular part of A is not referenced. Note\n /// that when DIAG = 'U', the diagonal elements of A are not\n /// referenced and are assumed to be one.\n ///\n /// \n /// (input) INTEGER\n /// The leading dimension of the array A. LDA .GE. max(M,1).\n ///\n /// \n /// (workspace) DOUBLE PRECISION array, dimension (LWORK),\n /// where LWORK .GE. M when NORM = 'I'; otherwise, WORK is not\n /// referenced.\n ///", "answers": [" public double Run(string NORM, string UPLO, string DIAG, int M, int N, double[] A, int offset_a"], "length": 769, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "c245f77e-b9ac-4438-9bf3-e50105d71e68", "reasoning": "After the XML documentation for the parameters, the next line should be the method declaration that implements DLANTR. In the DotNumerics library, such LAPACK wrappers expose a public method named Run that returns a double and takes the documented parameters (norm, uplo, diag, dimensions, matrix array, leading dimension, and workspace). Therefore the next line is the method signature.", "reasoning_model_answer": "public double Run(string NORM, string UPLO, string DIAG, int M, int N, double[] A, int LDA, double[] WORK)", "assistant_with_reasoning": "\nAfter the XML documentation for the parameters, the next line should be the method declaration that implements DLANTR. In the DotNumerics library, such LAPACK wrappers expose a public method named Run that returns a double and takes the documented parameters (norm, uplo, diag, dimensions, matrix array, leading dimension, and workspace). Therefore the next line is the method signature.\n\npublic double Run(string NORM, string UPLO, string DIAG, int M, int N, double[] A, int LDA, double[] WORK)", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.651, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 5777, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "public double Run(string NORM, string UPLO, string DIAG, int M, int N, double[] A, int LDA, double[] WORK)", "score": 0.85, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/*\n * This file is part of SpongeAPI, licensed under the MIT License (MIT).\n *\n * Copyright (c) SpongePowered \n * Copyright (c) contributors\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\npackage org.spongepowered.api.world.storage;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport com.flowpowered.math.vector.Vector3i;\nimport org.spongepowered.api.util.Direction;\nimport org.spongepowered.api.util.Direction.Division;\n\nimport java.util.Optional;\n\n/**\n * A class for information about the chunk coordinate space, aka the layout.\n * This can be used to obtain information about the chunk size and the space\n * bounds, validate coordinates, convert from chunk to world and vice-versa and\n * translate coordinates; among other things.\n */\npublic interface ChunkLayout {\n\n /**\n * Returns the size of the chunks in blocks. The axes are matched to the\n * corresponding vector components.\n *\n * @return The size of chunks\n */\n Vector3i getChunkSize();\n\n /**\n * Returns the maximum coordinates for chunks for each axis. The axes are\n * matched to the corresponding vector components. Due to the limited\n * precision of 32bit integers, there always is a practical limit.\n *\n * @return The maximum coordinates of chunks\n */\n Vector3i getSpaceMax();\n\n /**\n * Returns the minimum coordinates for chunks for each axis. The axes are\n * matched to the corresponding vector components. Due to the limited\n * precision of 32bit integers, there always is a practical limit.\n *\n * @return The minimum coordinates of chunks\n */\n Vector3i getSpaceMin();\n\n /**\n * Gets the total size of the chunk space, which is equivalent to\n * {@link #getSpaceMax()} - {@link #getSpaceMin()} + 1.\n *\n * @return The total size of the chunk space\n */\n Vector3i getSpaceSize();\n\n /**\n * Returns the origin of the chunk coordinate space. Normally\n * {@link Vector3i#ZERO}.\n *\n * @return The origin of the chunk coordinate space\n */\n Vector3i getSpaceOrigin();\n\n /**\n * Returns true if the coordinates are valid chunk coordinates. False if\n * otherwise.\n *\n * @param coords The coordinates to validate\n * @return Whether or not the coordinates are valid for chunks\n */\n default boolean isValidChunk(Vector3i coords) {\n checkNotNull(coords, \"coords\");\n return isValidChunk(coords.getX(), coords.getY(), coords.getZ());\n }\n\n /**\n * Returns true if the coordinates are valid chunk coordinates. False if\n * otherwise.\n *\n * @param x The x coordinate to validate\n * @param y The y coordinate to validate\n * @param z The z coordinate to validate\n * @return Whether or not the coordinates are valid for chunks\n */\n default boolean isValidChunk(int x, int y, int z) {\n return x >= getSpaceMin().getX() && x <= getSpaceMax().getX()\n && y >= getSpaceMin().getY() && y <= getSpaceMax().getY()\n && z >= getSpaceMin().getZ() && z <= getSpaceMax().getZ();\n }\n\n /**\n * Returns true if the local coordinates fit in a chunk. That is they are\n * positive and smaller than the chunk's size.\n *\n * @param localCoords The coordinates to check\n * @return Whether or not the coordinates fit in a chunk\n */\n default boolean isInChunk(Vector3i localCoords) {\n checkNotNull(localCoords, \"localCoords\");\n return isInChunk(localCoords.getX(), localCoords.getY(), localCoords.getZ());\n }\n\n /**\n * Returns true if the local coordinates fit in a chunk. That is they are\n * positive and smaller than the chunk's size.\n *\n * @param x The x local coordinate to validate\n * @param y The y local coordinate to validate\n * @param z The z local coordinate to validate\n * @return Whether or not the coordinates fit in a chunk\n */\n boolean isInChunk(int x, int y, int z);\n\n /**\n * Returns true if the world coordinates fit in the chunk at the given\n * coordinates.\n *\n * @param worldCoords The world coordinates to validate\n * @param chunkCoords The chunk coordinates in which they must fit\n * @return Whether or not the world coordinates fit in the chunk\n */\n default boolean isInChunk(Vector3i worldCoords, Vector3i chunkCoords) {\n checkNotNull(worldCoords, \"worldCoords\");\n checkNotNull(chunkCoords, \"chunkCoords\");\n return isInChunk(worldCoords.getX(), worldCoords.getY(), worldCoords.getZ(), chunkCoords.getX(), chunkCoords.getY(), chunkCoords.getZ());\n }\n\n /**\n * Returns true if the world coordinates fit in the chunk at the given\n * coordinates.\n *\n * @param wx The x world coordinate to validate\n * @param wy The y world coordinate to validate", "answers": [" * @param wz The z world coordinate to validate"], "length": 829, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "f5e8bde5-9530-4553-83be-76ac6426e109", "reasoning": "The code is defining a Javadoc comment for a method that checks if world coordinates fit in a chunk given chunk coordinates. After the @param wy line, the next logical Javadoc line documents the z-coordinate parameter, following the pattern of @param entries for each argument. Therefore the next line should be the @param line for wz.", "reasoning_model_answer": "* @param wz The z world coordinate to validate", "assistant_with_reasoning": "\nThe code is defining a Javadoc comment for a method that checks if world coordinates fit in a chunk given chunk coordinates. After the @param wy line, the next logical Javadoc line documents the z-coordinate parameter, following the pattern of @param entries for each argument. Therefore the next line should be the @param line for wz.\n\n* @param wz The z world coordinate to validate", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.193, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 6039, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "* @param wz The z world coordinate to validate", "score": 0.95, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "# -*- coding:utf-8 -*-\n#\n# Copyright (C) 2008 The Android Open Source Project\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom __future__ import print_function\nimport copy\nimport re\nimport sys\n\nfrom command import InteractiveCommand\nfrom editor import Editor\nfrom error import HookError, UploadError\nfrom git_command import GitCommand\nfrom git_refs import R_HEADS\nfrom hooks import RepoHook\n\nfrom pyversion import is_python3\nif not is_python3():\n input = raw_input # noqa: F821\nelse:\n unicode = str\n\nUNUSUAL_COMMIT_THRESHOLD = 5\n\n\ndef _ConfirmManyUploads(multiple_branches=False):\n if multiple_branches:\n print('ATTENTION: One or more branches has an unusually high number '\n 'of commits.')\n else:\n print('ATTENTION: You are uploading an unusually high number of commits.')\n print('YOU PROBABLY DO NOT MEAN TO DO THIS. (Did you rebase across '\n 'branches?)')\n answer = input(\"If you are sure you intend to do this, type 'yes': \").strip()\n return answer == \"yes\"\n\n\ndef _die(fmt, *args):\n msg = fmt % args\n print('error: %s' % msg, file=sys.stderr)\n sys.exit(1)\n\n\ndef _SplitEmails(values):\n result = []\n for value in values:\n result.extend([s.strip() for s in value.split(',')])\n return result\n\n\nclass Upload(InteractiveCommand):\n common = True\n helpSummary = \"Upload changes for code review\"\n helpUsage = \"\"\"\n%prog [--re --cc] []...\n\"\"\"\n helpDescription = \"\"\"\nThe '%prog' command is used to send changes to the Gerrit Code\nReview system. It searches for topic branches in local projects\nthat have not yet been published for review. If multiple topic\nbranches are found, '%prog' opens an editor to allow the user to\nselect which branches to upload.\n\n'%prog' searches for uploadable changes in all projects listed at\nthe command line. Projects can be specified either by name, or by\na relative or absolute path to the project's local directory. If no\nprojects are specified, '%prog' will search for uploadable changes\nin all projects listed in the manifest.\n\nIf the --reviewers or --cc options are passed, those emails are\nadded to the respective list of users, and emails are sent to any\nnew users. Users passed as --reviewers must already be registered\nwith the code review system, or the upload will fail.\n\n# Configuration\n\nreview.URL.autoupload:\n\nTo disable the \"Upload ... (y/N)?\" prompt, you can set a per-project\nor global Git configuration option. If review.URL.autoupload is set\nto \"true\" then repo will assume you always answer \"y\" at the prompt,\nand will not prompt you further. If it is set to \"false\" then repo\nwill assume you always answer \"n\", and will abort.\n\nreview.URL.autoreviewer:\n\nTo automatically append a user or mailing list to reviews, you can set\na per-project or global Git option to do so.\n\nreview.URL.autocopy:\n\nTo automatically copy a user or mailing list to all uploaded reviews,\nyou can set a per-project or global Git option to do so. Specifically,\nreview.URL.autocopy can be set to a comma separated list of reviewers\nwho you always want copied on all uploads with a non-empty --re\nargument.\n\nreview.URL.username:\n\nOverride the username used to connect to Gerrit Code Review.\nBy default the local part of the email address is used.\n\nThe URL must match the review URL listed in the manifest XML file,\nor in the .git/config within the project. For example:\n\n [remote \"origin\"]\n url = git://git.example.com/project.git\n review = http://review.example.com/\n\n [review \"http://review.example.com/\"]\n autoupload = true\n autocopy = johndoe@company.com,my-team-alias@company.com\n\nreview.URL.uploadtopic:\n\nTo add a topic branch whenever uploading a commit, you can set a\nper-project or global Git option to do so. If review.URL.uploadtopic\nis set to \"true\" then repo will assume you always want the equivalent\nof the -t option to the repo command. If unset or set to \"false\" then\nrepo will make use of only the command line option.\n\nreview.URL.uploadhashtags:\n\nTo add hashtags whenever uploading a commit, you can set a per-project\nor global Git option to do so. The value of review.URL.uploadhashtags\nwill be used as comma delimited hashtags like the --hashtag option.\n\nreview.URL.uploadlabels:\n\nTo add labels whenever uploading a commit, you can set a per-project\nor global Git option to do so. The value of review.URL.uploadlabels\nwill be used as comma delimited labels like the --label option.\n\nreview.URL.uploadnotify:\n\nControl e-mail notifications when uploading.\nhttps://gerrit-review.googlesource.com/Documentation/user-upload.html#notify\n\n# References\n\nGerrit Code Review: https://www.gerritcodereview.com/\n\n\"\"\"\n", "answers": [" def _Options(self, p):"], "length": 760, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "3e2b4102-997b-4649-9338-1d08c28d6654", "reasoning": "Within the Upload class, after the long helpDescription string the next logical element is the definition of the method that adds command‑line options. In repo's upload command the method is named _Options and takes the parser argument. It follows the helpDescription at the same indentation level.", "reasoning_model_answer": "def _Options(self, p):", "assistant_with_reasoning": "\nWithin the Upload class, after the long helpDescription string the next logical element is the definition of the method that adds command‑line options. In repo's upload command the method is named _Options and takes the parser argument. It follows the helpDescription at the same indentation level.\n\ndef _Options(self, p):", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.949, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 5213, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "def _Options(self, p):", "score": 0.96, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\nusing System;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.IO;\nusing System.IO.Compression;\nusing System.Net;\nusing System.Net.Http;\nusing System.Net.Test.Common;\nusing System.Runtime.InteropServices;\nusing System.Security.Authentication;\nusing System.Security.Cryptography.X509Certificates;\nusing System.Text;\nusing System.Threading;\nusing System.Threading.Tasks;\n\nusing Xunit;\nusing Xunit.Abstractions;\n\nnamespace System.Net.Http.WinHttpHandlerUnitTests\n{\n public class WinHttpHandlerTest\n {\n private const string FakeProxy = \"http://proxy.contoso.com\";\n \n private readonly ITestOutputHelper _output;\n\n public WinHttpHandlerTest(ITestOutputHelper output)\n {\n _output = output;\n TestControl.ResetAll();\n }\n\n [Fact]\n public void Ctor_ExpectedDefaultPropertyValues()\n {\n var handler = new WinHttpHandler();\n\n Assert.Equal(SslProtocols.None, handler.SslProtocols);\n Assert.Equal(true, handler.AutomaticRedirection);\n Assert.Equal(50, handler.MaxAutomaticRedirections);\n Assert.Equal(DecompressionMethods.None, handler.AutomaticDecompression);\n Assert.Equal(CookieUsePolicy.UseInternalCookieStoreOnly, handler.CookieUsePolicy);\n Assert.Equal(null, handler.CookieContainer);\n Assert.Equal(null, handler.ServerCertificateValidationCallback);\n Assert.Equal(false, handler.CheckCertificateRevocationList);\n Assert.Equal(ClientCertificateOption.Manual, handler.ClientCertificateOption);\n X509Certificate2Collection certs = handler.ClientCertificates;\n Assert.True(certs.Count == 0);\n Assert.Equal(false, handler.PreAuthenticate);\n Assert.Equal(null, handler.ServerCredentials);\n Assert.Equal(WindowsProxyUsePolicy.UseWinHttpProxy, handler.WindowsProxyUsePolicy);\n Assert.Equal(null, handler.DefaultProxyCredentials);\n Assert.Equal(null, handler.Proxy);\n Assert.Equal(Int32.MaxValue, handler.MaxConnectionsPerServer);\n Assert.Equal(TimeSpan.FromSeconds(30), handler.SendTimeout);\n Assert.Equal(TimeSpan.FromSeconds(30), handler.ReceiveHeadersTimeout);\n Assert.Equal(TimeSpan.FromSeconds(30), handler.ReceiveDataTimeout);\n Assert.Equal(64, handler.MaxResponseHeadersLength);\n Assert.Equal(64 * 1024, handler.MaxResponseDrainSize);\n Assert.NotNull(handler.Properties);\n }\n\n [Fact]\n public void AutomaticRedirection_SetFalseAndGet_ValueIsFalse()\n {\n var handler = new WinHttpHandler();\n handler.AutomaticRedirection = false;\n \n Assert.False(handler.AutomaticRedirection);\n }\n\n [Fact]\n public void AutomaticRedirection_SetTrue_ExpectedWinHttpHandleSettings()\n {\n var handler = new WinHttpHandler();\n\n SendRequestHelper.Send(\n handler,\n delegate { handler.AutomaticRedirection = true; });\n\n Assert.Equal(\n Interop.WinHttp.WINHTTP_OPTION_REDIRECT_POLICY_DISALLOW_HTTPS_TO_HTTP,\n APICallHistory.WinHttpOptionRedirectPolicy);\n }\n\n [Fact]\n public void AutomaticRedirection_SetFalse_ExpectedWinHttpHandleSettings()\n {\n var handler = new WinHttpHandler();\n\n SendRequestHelper.Send(\n handler,\n delegate { handler.AutomaticRedirection = false; });\n\n Assert.Equal(\n Interop.WinHttp.WINHTTP_OPTION_REDIRECT_POLICY_NEVER,\n APICallHistory.WinHttpOptionRedirectPolicy);\n }\n\n [Fact]\n public void CheckCertificateRevocationList_SetTrue_ExpectedWinHttpHandleSettings()\n {\n var handler = new WinHttpHandler();\n\n SendRequestHelper.Send(handler, delegate { handler.CheckCertificateRevocationList = true; });\n\n Assert.True(APICallHistory.WinHttpOptionEnableSslRevocation.Value);\n }\n\n [Fact]\n public void CheckCertificateRevocationList_SetFalse_ExpectedWinHttpHandleSettings()\n {\n var handler = new WinHttpHandler();\n\n SendRequestHelper.Send(handler, delegate { handler.CheckCertificateRevocationList = false; });\n\n Assert.Equal(false, APICallHistory.WinHttpOptionEnableSslRevocation.HasValue);\n }\n\n [Fact]\n public void CookieContainer_WhenCreated_ReturnsNull()\n {\n var handler = new WinHttpHandler();\n\n Assert.Null(handler.CookieContainer);\n }\n\n [Fact]\n public async Task CookieUsePolicy_UseSpecifiedCookieContainerAndNullContainer_ThrowsInvalidOperationException()\n {\n var handler = new WinHttpHandler();\n Assert.Null(handler.CookieContainer);\n handler.CookieUsePolicy = CookieUsePolicy.UseSpecifiedCookieContainer;\n using (var client = new HttpClient(handler))\n {\n TestServer.SetResponse(DecompressionMethods.None, TestServer.ExpectedResponseBody);\n\n var request = new HttpRequestMessage(HttpMethod.Post, TestServer.FakeServerEndpoint);\n\n await Assert.ThrowsAsync(() => client.SendAsync(request));\n }\n }\n\n [Fact]\n public void CookieUsePolicy_SetUsingInvalidEnum_ThrowsArgumentOutOfRangeException()\n {\n var handler = new WinHttpHandler();\n\n Assert.Throws(() => { handler.CookieUsePolicy = (CookieUsePolicy)100; });\n }\n\n [Fact]\n public void CookieUsePolicy_WhenCreated_ReturnsUseInternalCookieStoreOnly()\n {\n var handler = new WinHttpHandler();\n\n Assert.Equal(CookieUsePolicy.UseInternalCookieStoreOnly, handler.CookieUsePolicy);\n }\n\n [Fact]\n public void CookieUsePolicy_SetIgnoreCookies_NoExceptionThrown()\n {\n var handler = new WinHttpHandler();\n\n handler.CookieUsePolicy = CookieUsePolicy.IgnoreCookies;\n }\n\n [Fact]\n public void CookieUsePolicy_SetUseInternalCookieStoreOnly_NoExceptionThrown()\n {\n var handler = new WinHttpHandler();\n\n handler.CookieUsePolicy = CookieUsePolicy.UseInternalCookieStoreOnly;\n }\n\n [Fact]\n public void CookieUsePolicy_SetUseSpecifiedCookieContainer_NoExceptionThrown()\n {\n var handler = new WinHttpHandler();\n\n handler.CookieUsePolicy = CookieUsePolicy.UseSpecifiedCookieContainer;\n }\n\n\n [Fact]\n public void CookieUsePolicy_SetIgnoreCookies_ExpectedWinHttpHandleSettings()\n {\n var handler = new WinHttpHandler();\n\n SendRequestHelper.Send(handler, delegate { handler.CookieUsePolicy = CookieUsePolicy.IgnoreCookies; });\n\n Assert.True(APICallHistory.WinHttpOptionDisableCookies.Value);\n }\n\n [Fact]\n public void CookieUsePolicy_SetUseInternalCookieStoreOnly_ExpectedWinHttpHandleSettings()\n {\n var handler = new WinHttpHandler();\n\n SendRequestHelper.Send(\n handler,\n delegate { handler.CookieUsePolicy = CookieUsePolicy.UseInternalCookieStoreOnly; });\n\n Assert.Equal(false, APICallHistory.WinHttpOptionDisableCookies.HasValue);\n }\n\n [Fact]\n public void CookieUsePolicy_SetUseSpecifiedCookieContainerAndContainer_ExpectedWinHttpHandleSettings()\n {\n var handler = new WinHttpHandler();\n\n SendRequestHelper.Send(\n handler,\n delegate {\n handler.CookieUsePolicy = CookieUsePolicy.UseSpecifiedCookieContainer;\n handler.CookieContainer = new CookieContainer();\n });\n\n Assert.Equal(true, APICallHistory.WinHttpOptionDisableCookies.HasValue);\n }\n\n [Fact]\n public void Properties_Get_CountIsZero()\n {\n var handler = new WinHttpHandler();\n IDictionary dict = handler.Properties;\n Assert.Equal(0, dict.Count);\n }\n\n [Fact]\n public void Properties_AddItemToDictionary_ItemPresent()\n {\n var handler = new WinHttpHandler();\n IDictionary dict = handler.Properties;\n Assert.Same(dict, handler.Properties);\n\n var item = new Object();\n dict.Add(\"item\", item);\n\n object value;\n Assert.True(dict.TryGetValue(\"item\", out value));\n Assert.Equal(item, value);\n }\n\n [Fact]\n public void WindowsProxyUsePolicy_SetUsingInvalidEnum_ThrowArgumentOutOfRangeException()\n {\n var handler = new WinHttpHandler();\n\n Assert.Throws(\n () => { handler.WindowsProxyUsePolicy = (WindowsProxyUsePolicy)100; });\n }\n\n [Fact]\n public void WindowsProxyUsePolicy_SetDoNotUseProxy_NoExceptionThrown()\n {\n var handler = new WinHttpHandler();\n\n handler.WindowsProxyUsePolicy = WindowsProxyUsePolicy.DoNotUseProxy;\n }\n\n [Fact]\n public void WindowsProxyUsePolicy_SetUseWinHttpProxy_NoExceptionThrown()\n {\n var handler = new WinHttpHandler();\n\n handler.WindowsProxyUsePolicy = WindowsProxyUsePolicy.UseWinHttpProxy;\n }\n\n [Fact]\n public void WindowsProxyUsePolicy_SetUseWinWinInetProxy_NoExceptionThrown()\n {\n var handler = new WinHttpHandler();\n\n handler.WindowsProxyUsePolicy = WindowsProxyUsePolicy.UseWinInetProxy;\n }\n\n [Fact]\n public void WindowsProxyUsePolicy_SetUseCustomProxy_NoExceptionThrown()\n {\n var handler = new WinHttpHandler();\n\n handler.WindowsProxyUsePolicy = WindowsProxyUsePolicy.UseCustomProxy;\n }\n\n [Fact]\n public async Task WindowsProxyUsePolicy_UseNonNullProxyAndIncorrectWindowsProxyUsePolicy_ThrowsInvalidOperationException()\n {\n var handler = new WinHttpHandler();\n handler.Proxy = new CustomProxy(false);\n handler.WindowsProxyUsePolicy = WindowsProxyUsePolicy.DoNotUseProxy;\n using (var client = new HttpClient(handler))\n {\n TestServer.SetResponse(DecompressionMethods.None, TestServer.ExpectedResponseBody);\n\n var request = new HttpRequestMessage(HttpMethod.Post, TestServer.FakeServerEndpoint);\n\n await Assert.ThrowsAsync(() => client.SendAsync(request));\n }\n }\n\n\n [Fact]\n public async Task WindowsProxyUsePolicy_UseCustomProxyAndNullProxy_ThrowsInvalidOperationException()\n {\n var handler = new WinHttpHandler();\n handler.WindowsProxyUsePolicy = WindowsProxyUsePolicy.UseCustomProxy;\n handler.Proxy = null;\n using (var client = new HttpClient(handler))\n {\n TestServer.SetResponse(DecompressionMethods.None, TestServer.ExpectedResponseBody);\n\n var request = new HttpRequestMessage(HttpMethod.Post, TestServer.FakeServerEndpoint);\n\n await Assert.ThrowsAsync(() => client.SendAsync(request));\n }\n }\n\n [Fact]\n public void MaxAutomaticRedirections_SetZero_ThrowsArgumentOutOfRangeException()\n {\n var handler = new WinHttpHandler();\n Assert.Throws(() => { handler.MaxAutomaticRedirections = 0; });\n }\n\n [Fact]\n public void MaxAutomaticRedirections_SetNegativeValue_ThrowsArgumentOutOfRangeException()\n {\n var handler = new WinHttpHandler();\n Assert.Throws(() => { handler.MaxAutomaticRedirections = -1; });\n }\n\n [Fact]", "answers": [" public void MaxAutomaticRedirections_SetValidValue_ExpectedWinHttpHandleSettings()"], "length": 683, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "c5deeefd-ae8c-45b6-80b6-251df7676d2a", "reasoning": "The code is a series of xUnit test methods, each preceded by a [Fact] attribute. The last completed test checks that setting MaxAutomaticRedirections to a negative value throws. The next logical test would verify that setting a valid positive value succeeds, following the naming pattern used earlier. Therefore the line after the [Fact] attribute should be the method declaration for this test.", "reasoning_model_answer": "public void MaxAutomaticRedirections_SetValidValue_NoException()", "assistant_with_reasoning": "\nThe code is a series of xUnit test methods, each preceded by a [Fact] attribute. The last completed test checks that setting MaxAutomaticRedirections to a negative value throws. The next logical test would verify that setting a valid positive value succeeds, following the naming pattern used earlier. Therefore the line after the [Fact] attribute should be the method declaration for this test.\n\npublic void MaxAutomaticRedirections_SetValidValue_NoException()", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.284, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 12397, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "public void MaxAutomaticRedirections_SetValidValue_NoException()", "score": 0.79, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "#\n# This file is part of Gruvi. Gruvi is free software available under the\n# terms of the MIT license. See the file \"LICENSE\" that was provided\n# together with this source file for the licensing terms.\n#\n# Copyright (c) 2012-2017 the Gruvi authors. See the file \"AUTHORS\" for a\n# complete list.\n\nfrom __future__ import absolute_import, print_function\n\nimport unittest\n\nfrom gruvi import http\nfrom gruvi.http import HttpServer, HttpClient, HttpMessage, HttpProtocol, ParsedUrl\nfrom gruvi.http import parse_content_type, parse_te, parse_trailer, parse_url\nfrom gruvi.http import get_header, remove_headers\nfrom gruvi.stream import Stream, StreamClient\nfrom gruvi.sync import Queue\n\nfrom support import UnitTest, MockTransport\n\nURL = ParsedUrl\n\n\nclass TestParseContentType(UnitTest):\n\n def test_simple(self):\n parsed = parse_content_type('text/plain')\n self.assertEqual(parsed, ('text/plain', {}))\n\n def test_params(self):\n parsed = parse_content_type('text/plain; charset=foo')\n self.assertEqual(parsed[0], 'text/plain')\n self.assertEqual(parsed[1], {'charset': 'foo'})\n\n def test_iso8859_1(self):\n parsed = parse_content_type('text/plain; foo=\"bar\\xfe\"')\n self.assertEqual(parsed, ('text/plain', {'foo': 'bar\\xfe'}))\n\n def test_param_whitespace(self):\n parsed = parse_content_type('text/plain; charset=foo ')\n self.assertEqual(parsed, ('text/plain', {'charset': 'foo'}))\n\n def test_param_quoted(self):\n parsed = parse_content_type('text/plain; charset=\"foo bar\"')\n self.assertEqual(parsed, ('text/plain', {'charset': 'foo bar'}))\n\n def test_param_quoted_pair(self):\n parsed = parse_content_type('text/plain; charset=\"foo\\\\\"bar\"')\n self.assertEqual(parsed, ('text/plain', {'charset': 'foo\"bar'}))\n\n def test_param_empty(self):\n parsed = parse_content_type('text/plain; charset=\"\"')\n self.assertEqual(parsed, ('text/plain', {'charset': ''}))\n\n def test_param_multiple(self):\n parsed = parse_content_type('text/plain; foo=bar; baz=qux')\n self.assertEqual(parsed, ('text/plain', {'foo': 'bar', 'baz': 'qux'}))\n\n def test_param_multiple_missing_semi(self):\n parsed = parse_content_type('text/plain; foo=bar baz=qux')\n self.assertEqual(parsed, ('text/plain', {'foo': 'bar'}))\n\n\nclass TestParseTE(UnitTest):\n\n def test_simple(self):\n parsed = parse_te('chunked')\n self.assertEqual(parsed, [('chunked', None)])\n\n def test_multiple(self):\n parsed = parse_te('chunked, deflate')\n self.assertEqual(parsed, [('chunked', None), ('deflate', None)])\n\n def test_qvalue(self):\n parsed = parse_te('deflate; q=0.5')\n self.assertEqual(parsed, [('deflate', '0.5')])\n\n def test_case_insensitive(self):\n parsed = parse_te('dEfLaTe; Q=0.5')\n self.assertEqual(parsed, [('dEfLaTe', '0.5')])\n\n def test_illegal_qvalue(self):\n parsed = parse_te('deflate; q=2.5')\n self.assertEqual(parsed, [('deflate', None)])\n\n def test_multiple_qvalue(self):\n parsed = parse_te('deflate; q=0.5, zlib; q=0.8')\n self.assertEqual(parsed, [('deflate', '0.5'), ('zlib', '0.8')])\n\n\nclass TestParseTrailer(UnitTest):\n\n def test_simple(self):\n parsed = parse_trailer('foo')\n self.assertEqual(parsed, ['foo'])\n\n def test_multiple(self):\n parsed = parse_trailer('foo, bar')\n self.assertEqual(parsed, ['foo', 'bar'])\n\n def test_spacing(self):\n parsed = parse_trailer('foo , bar ')\n self.assertEqual(parsed, ['foo', 'bar'])\n\n def test_wrong_separator(self):\n parsed = parse_trailer('foo; bar')\n self.assertEqual(parsed, ['foo'])\n\n\nclass TestParseUrl(UnitTest):\n\n def test_test(self):\n self.assertEqual(URL(), ('', '', '', '', '', '', ''))\n self.assertEqual(URL(scheme='http'), ('http', '', '', '', '', '', ''))\n self.assertEqual(URL(host='foo'), ('', 'foo', '', '', '', '', ''))\n self.assertEqual(URL(path='/path'), ('', '', '/path', '', '', '', ''))\n self.assertEqual(URL(query='foo=bar'), ('', '', '', 'foo=bar', '', '', ''))\n self.assertEqual(URL(fragment='baz'), ('', '', '', '', 'baz', '', ''))\n self.assertEqual(URL(port='80'), ('', '', '', '', '', '80', ''))\n self.assertEqual(URL(userinfo='user:pass'), ('', '', '', '', '', '', 'user:pass'))\n\n def test_origin(self):\n parsed = parse_url('/path')\n self.assertEqual(parsed, URL(path='/path'))\n\n def test_absolute(self):\n parsed = parse_url('http://example.com/path')\n self.assertEqual(parsed, URL('http', 'example.com', '/path'))\n\n def test_authority(self):\n parsed = parse_url('example.com:80', is_connect=True)\n self.assertEqual(parsed, URL('', 'example.com', port='80'))\n\n def test_authority_error(self):\n self.assertRaises(ValueError, parse_url, '/path', is_connect=True)\n self.assertRaises(ValueError, parse_url, 'http://example.com:80', is_connect=True)\n self.assertRaises(ValueError, parse_url, '*', is_connect=True)\n\n def test_asterisk(self):\n parsed = parse_url('*')\n self.assertEqual(parsed, URL(path='*'))\n\n def test_userinfo(self):\n parsed = parse_url('http://user:pass@example.com')\n self.assertEqual(parsed, URL('http', 'example.com', userinfo='user:pass'))\n\n def test_port(self):\n parsed = parse_url('http://example.com:80')\n self.assertEqual(parsed, URL('http', 'example.com', port='80'))\n\n def test_userinfo_port(self):\n parsed = parse_url('http://user:pass@example.com:80')\n self.assertEqual(parsed, URL('http', 'example.com', port='80', userinfo='user:pass'))\n\n def test_default_scheme(self):\n parsed = parse_url('www.example.com')\n self.assertEqual(parsed, URL('http', 'www.example.com'))\n parsed = parse_url('http://www.example.com')\n self.assertEqual(parsed, URL('http', 'www.example.com'))\n parsed = parse_url('www.example.com', default_scheme='https')\n self.assertEqual(parsed, URL('https', 'www.example.com'))\n parsed = parse_url('https://www.example.com', default_scheme='https')\n self.assertEqual(parsed, URL('https', 'www.example.com'))\n\n def test_addr(self):\n parsed = parse_url('www.example.com')\n self.assertEqual(parsed.addr, ('www.example.com', 80))\n parsed = parse_url('https://www.example.com')\n self.assertEqual(parsed.addr, ('www.example.com', 443))\n\n def test_ssl(self):\n parsed = parse_url('www.example.com')\n self.assertFalse(parsed.ssl)\n parsed = parse_url('http://www.example.com')\n self.assertFalse(parsed.ssl)\n parsed = parse_url('https://www.example.com')\n self.assertTrue(parsed.ssl)\n\n def test_target(self):\n parsed = parse_url('www.example.com')\n self.assertEqual(parsed.target, '/')\n parsed = parse_url('www.example.com/foo')\n self.assertEqual(parsed.target, '/foo')\n parsed = parse_url('www.example.com?bar')\n self.assertEqual(parsed.target, '/?bar')\n parsed = parse_url('www.example.com/foo?bar')\n self.assertEqual(parsed.target, '/foo?bar')\n\n\nclass TestGetHeader(UnitTest):\n\n headers = [('foo', 'fooval'),\n ('bar', 'barval'),\n ('baz', 'bazval')]\n\n def test_simple(self):\n self.assertEqual(get_header(self.headers, 'foo'), 'fooval')\n self.assertEqual(get_header(self.headers, 'bar'), 'barval')\n self.assertEqual(get_header(self.headers, 'baz'), 'bazval')\n\n def test_case_insensitive(self):\n self.assertEqual(get_header(self.headers, 'Foo'), 'fooval')\n self.assertEqual(get_header(self.headers, 'FOO'), 'fooval')\n\n def test_not_present(self):\n self.assertIsNone(get_header(self.headers, 'qux'))\n\n def test_default_value(self):\n self.assertEqual(get_header(self.headers, 'qux', 'quxval'), 'quxval')\n\n\nclass TestRemoveHeaders(UnitTest):\n\n headers = [('foo', 'fooval1'),\n ('bar', 'barval1'),\n ('foo', 'fooval2'),\n ('baz', 'bazval'),\n ('bar', 'barval2')]\n\n def test_simple(self):\n self.assertEqual(remove_headers(self.headers[:], 'foo'),\n [('bar', 'barval1'), ('baz', 'bazval'), ('bar', 'barval2')])\n self.assertEqual(remove_headers(self.headers[:], 'bar'),\n [('foo', 'fooval1'), ('foo', 'fooval2'), ('baz', 'bazval')])\n\n def test_in_place(self):\n headers = self.headers[:]\n removed = remove_headers(headers, 'foo')\n self.assertIs(headers, removed)\n\n def test_non_quadratic(self):\n # Ensure remove_headers() doesn't take quadratic time.\n names = ('foo', 'bar', 'baz', 'qux')\n headers = []\n for i in range(100000):\n name = names[i%4]\n headers.append((name, name + 'val'))\n removed = remove_headers(headers, 'foo')\n self.assertEqual(len(removed), 75000)\n\n\nclass TestHttpProtocol(UnitTest):\n\n def setUp(self):\n super(TestHttpProtocol, self).setUp()\n self.requests = Queue()\n\n def store_request(self, message, transport, protocol):\n self.requests.put(message)\n protocol.writer.write(b'HTTP/1.1 200 OK\\r\\n\\r\\n')\n\n def parse_request(self, *chunks):\n # Parse the HTTP request made up of *chunks.\n transport = MockTransport()\n protocol = HttpProtocol(self.store_request, server_side=True)\n transport.start(protocol)\n for chunk in chunks:\n protocol.data_received(chunk)\n self.assertIsNone(protocol._error)\n self.transport = transport\n self.protocol = protocol\n\n def get_request(self):\n # Get a parsed request.\n m = self.requests.get(timeout=1.0)\n self.assertIsInstance(m, HttpMessage)\n self.assertEqual(m.message_type, http.REQUEST)\n return m\n\n # Tests that parse a request\n\n def test_simple_request(self):\n r = b'GET / HTTP/1.1\\r\\nHost: example.com\\r\\n\\r\\n'\n self.parse_request(r)\n m = self.get_request()\n self.assertEqual(m.version, '1.1')\n self.assertIsNone(m.status_code)\n self.assertEqual(m.method, 'GET')\n self.assertEqual(m.url, '/')\n self.assertTrue(m._should_keep_alive)\n self.assertEqual(m.parsed_url, URL(path='/'))\n self.assertEqual(m.headers, [('Host', 'example.com')])\n self.assertIsInstance(m.body, Stream)\n self.assertTrue(m.body.buffer.eof)\n\n def test_request_with_body(self):\n r = b'GET / HTTP/1.1\\r\\nHost: example.com\\r\\n' \\\n b'Content-Length: 3\\r\\n\\r\\nFoo'\n self.parse_request(r)\n m = self.get_request()\n self.assertEqual(m.url, '/')\n self.assertEqual(m.version, '1.1')\n self.assertEqual(m.headers, [('Host', 'example.com'), ('Content-Length', '3')])\n self.assertFalse(m.body.buffer.eof)\n self.assertEqual(m.body.read(), b'Foo')\n self.assertTrue(m.body.buffer.eof)\n\n def test_request_with_body_incremental(self):\n r = b'GET / HTTP/1.1\\r\\nHost: example.com\\r\\n' \\\n b'Content-Length: 3\\r\\n\\r\\nFoo'\n self.parse_request(*[r[i:i+1] for i in range(len(r))])\n m = self.get_request()\n self.assertEqual(m.url, '/')\n self.assertEqual(m.version, '1.1')\n self.assertEqual(m.headers, [('Host', 'example.com'), ('Content-Length', '3')])\n self.assertFalse(m.body.buffer.eof)\n self.assertEqual(m.body.read(), b'Foo')\n self.assertTrue(m.body.buffer.eof)\n\n def test_request_with_chunked_body(self):\n r = b'GET / HTTP/1.1\\r\\nHost: example.com\\r\\n' \\\n b'Transfer-Encoding: chunked\\r\\n\\r\\n' \\\n b'3\\r\\nFoo\\r\\n0\\r\\n\\r\\n'\n self.parse_request(r)\n m = self.get_request()\n self.assertEqual(m.url, '/')\n self.assertEqual(m.version, '1.1')\n self.assertEqual(m.headers, [('Host', 'example.com'),\n ('Transfer-Encoding', 'chunked')])\n self.assertFalse(m.body.buffer.eof)\n self.assertEqual(m.body.read(), b'Foo')\n self.assertTrue(m.body.buffer.eof)\n\n def test_request_with_chunked_body_incremental(self):\n r = b'GET / HTTP/1.1\\r\\nHost: example.com\\r\\n' \\\n b'Transfer-Encoding: chunked\\r\\n\\r\\n' \\\n b'3\\r\\nFoo\\r\\n0\\r\\n\\r\\n'\n self.parse_request(*[r[i:i+1] for i in range(len(r))])\n m = self.get_request()\n self.assertEqual(m.url, '/')\n self.assertEqual(m.version, '1.1')\n self.assertEqual(m.headers, [('Host', 'example.com'),\n ('Transfer-Encoding', 'chunked')])\n self.assertFalse(m.body.buffer.eof)", "answers": [" self.assertEqual(m.body.read(), b'Foo')"], "length": 863, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "470f245d-92e6-4842-8bb0-5693cbfbe74a", "reasoning": "The test method test_request_with_chunked_body_incremental mirrors the earlier tests: after confirming the body buffer is not at EOF, the test reads the body and checks its content, then verifies EOF. The next logical line is the assertion that reading the body yields the expected bytes b'Foo'.", "reasoning_model_answer": "self.assertEqual(m.body.read(), b'Foo')", "assistant_with_reasoning": "\nThe test method test_request_with_chunked_body_incremental mirrors the earlier tests: after confirming the body buffer is not at EOF, the test reads the body and checks its content, then verifies EOF. The next logical line is the assertion that reading the body yields the expected bytes b'Foo'.\n\nself.assertEqual(m.body.read(), b'Foo')", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.375, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 12874, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "self.assertEqual(m.body.read(), b'Foo')", "score": 0.91, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/*\n * Copyright Terracotta, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.ehcache.impl.internal.store.offheap;\n\nimport org.ehcache.config.EvictionAdvisor;\nimport org.ehcache.core.spi.function.BiFunction;\nimport org.ehcache.core.spi.function.Function;\nimport org.ehcache.impl.internal.store.offheap.factories.EhcacheSegmentFactory;\nimport org.junit.Test;\n\nimport java.io.IOException;\n\nimport static org.hamcrest.CoreMatchers.is;\nimport static org.hamcrest.CoreMatchers.nullValue;\nimport static org.junit.Assert.assertThat;\nimport static org.junit.Assert.fail;\n\n/**\n * AbstractEhcacheOffHeapBackingMapTest\n */\npublic abstract class AbstractEhcacheOffHeapBackingMapTest {\n protected abstract EhcacheOffHeapBackingMap createTestSegment() throws IOException;\n\n protected abstract EhcacheOffHeapBackingMap createTestSegment(EvictionAdvisor evictionPredicate) throws IOException;\n\n protected abstract void destroySegment(EhcacheOffHeapBackingMap segment);\n\n protected abstract void putPinned(String key, String value, EhcacheOffHeapBackingMap segment);\n\n protected abstract boolean isPinned(String key, EhcacheOffHeapBackingMap segment);\n\n protected abstract int getMetadata(String key, int mask, EhcacheOffHeapBackingMap segment);\n\n @Test\n public void testComputeFunctionCalledWhenNoMapping() throws Exception {\n EhcacheOffHeapBackingMap segment = createTestSegment();\n try {\n String value = segment.compute(\"key\", new BiFunction() {\n @Override\n public String apply(String s, String s2) {\n return \"value\";\n }\n }, false);\n assertThat(value, is(\"value\"));\n assertThat(segment.get(\"key\"), is(value));\n } finally {\n destroySegment(segment);\n }\n }\n\n @Test\n public void testComputeFunctionReturnsSameNoPin() throws Exception {\n EhcacheOffHeapBackingMap segment = createTestSegment();\n try {\n segment.put(\"key\", \"value\");\n String value = segment.compute(\"key\", new BiFunction() {\n @Override\n public String apply(String s, String s2) {\n return s2;\n }\n }, false);\n assertThat(value, is(\"value\"));\n assertThat(isPinned(\"key\", segment), is(false));\n } finally {\n destroySegment(segment);\n }\n }\n\n @Test\n public void testComputeFunctionReturnsSamePins() throws Exception {\n EhcacheOffHeapBackingMap segment = createTestSegment();\n try {\n segment.put(\"key\", \"value\");\n String value = segment.compute(\"key\", new BiFunction() {\n @Override\n public String apply(String s, String s2) {\n return s2;\n }\n }, true);\n assertThat(value, is(\"value\"));\n assertThat(isPinned(\"key\", segment), is(true));\n } finally {\n destroySegment(segment);\n }\n }\n\n @Test\n public void testComputeFunctionReturnsSamePreservesPinWhenNoPin() throws Exception {\n EhcacheOffHeapBackingMap segment = createTestSegment();\n try {\n putPinned(\"key\", \"value\", segment);\n String value = segment.compute(\"key\", new BiFunction() {\n @Override\n public String apply(String s, String s2) {\n return s2;\n }\n }, false);\n assertThat(value, is(\"value\"));\n assertThat(isPinned(\"key\", segment), is(true));\n } finally {\n destroySegment(segment);\n }\n }\n\n @Test\n public void testComputeFunctionReturnsDifferentNoPin() throws Exception {\n EhcacheOffHeapBackingMap segment = createTestSegment();\n try {\n segment.put(\"key\", \"value\");\n String value = segment.compute(\"key\", new BiFunction() {\n @Override\n public String apply(String s, String s2) {\n return \"otherValue\";\n }\n }, false);\n assertThat(value, is(\"otherValue\"));\n assertThat(isPinned(\"key\", segment), is(false));\n } finally {\n destroySegment(segment);\n }\n }\n\n @Test\n public void testComputeFunctionReturnsDifferentPins() throws Exception {\n EhcacheOffHeapBackingMap segment = createTestSegment();\n try {\n segment.put(\"key\", \"value\");\n String value = segment.compute(\"key\", new BiFunction() {\n @Override\n public String apply(String s, String s2) {\n return \"otherValue\";\n }\n }, true);\n assertThat(value, is(\"otherValue\"));\n assertThat(isPinned(\"key\", segment), is(true));\n } finally {\n destroySegment(segment);\n }\n }\n\n @Test\n public void testComputeFunctionReturnsDifferentClearsPin() throws Exception {\n EhcacheOffHeapBackingMap segment = createTestSegment();\n try {\n putPinned(\"key\", \"value\", segment);\n String value = segment.compute(\"key\", new BiFunction() {\n @Override\n public String apply(String s, String s2) {\n return \"otherValue\";\n }\n }, false);\n assertThat(value, is(\"otherValue\"));\n assertThat(isPinned(\"key\", segment), is(false));\n } finally {\n destroySegment(segment);\n }\n }\n\n @Test\n public void testComputeFunctionReturnsNullRemoves() throws Exception {\n EhcacheOffHeapBackingMap segment = createTestSegment();\n try {\n putPinned(\"key\", \"value\", segment);\n String value = segment.compute(\"key\", new BiFunction() {\n @Override\n public String apply(String s, String s2) {\n return null;\n }\n }, false);\n assertThat(value, nullValue());\n assertThat(segment.containsKey(\"key\"), is(false));\n } finally {\n destroySegment(segment);\n }\n }\n\n @Test\n public void testComputeIfPresentNotCalledOnNotContainedKey() throws Exception {\n EhcacheOffHeapBackingMap segment = createTestSegment();\n try {\n try {\n segment.computeIfPresent(\"key\", new BiFunction() {\n @Override\n public String apply(String s, String s2) {\n throw new UnsupportedOperationException(\"Should not have been called!\");\n }\n });\n } catch (UnsupportedOperationException e) {\n fail(\"Mapping function should not have been called.\");\n }\n } finally {\n destroySegment(segment);\n }\n }\n\n @Test\n public void testComputeIfPresentReturnsSameValue() throws Exception {\n EhcacheOffHeapBackingMap segment = createTestSegment();\n try {\n segment.put(\"key\", \"value\");\n String value = segment.computeIfPresent(\"key\", new BiFunction() {\n @Override\n public String apply(String s, String s2) {\n return s2;\n }\n });\n assertThat(segment.get(\"key\"), is(value));\n } finally {\n destroySegment(segment);\n }\n }\n\n @Test\n public void testComputeIfPresentReturnsDifferentValue() throws Exception {\n EhcacheOffHeapBackingMap segment = createTestSegment();\n try {\n segment.put(\"key\", \"value\");\n String value = segment.computeIfPresent(\"key\", new BiFunction() {\n @Override\n public String apply(String s, String s2) {\n return \"newValue\";\n }\n });\n assertThat(segment.get(\"key\"), is(value));\n } finally {\n destroySegment(segment);\n }\n }\n\n @Test\n public void testComputeIfPresentReturnsNullRemovesMapping() throws Exception {\n EhcacheOffHeapBackingMap segment = createTestSegment();\n try {\n segment.put(\"key\", \"value\");\n String value = segment.computeIfPresent(\"key\", new BiFunction() {\n @Override\n public String apply(String s, String s2) {\n return null;\n }\n });\n assertThat(segment.containsKey(\"key\"), is(false));", "answers": [" } finally {"], "length": 768, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "0ce271ed-936f-43a4-8696-f0d7a21df69e", "reasoning": "The test method ends after the assertThat call. Following the pattern of previous test methods, the next line should close the try block and open the finally block that destroys the segment. This line is indented to match the surrounding code.", "reasoning_model_answer": "} finally {", "assistant_with_reasoning": "\nThe test method ends after the assertThat call. Following the pattern of previous test methods, the next line should close the try block and open the finally block that destroys the segment. This line is indented to match the surrounding code.\n\n} finally {", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 6.841, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 8641, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "} finally {", "score": 0.85, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/*\n * Copyright 2012-2014, Continuuity, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.continuuity.loom.layout;\n\nimport com.continuuity.loom.cluster.Cluster;\nimport com.continuuity.loom.cluster.Node;\nimport com.continuuity.loom.cluster.NodeProperties;\nimport com.continuuity.loom.http.request.ClusterCreateRequest;\nimport com.continuuity.loom.layout.change.ClusterLayoutChange;\nimport com.continuuity.loom.layout.change.ClusterLayoutTracker;\nimport com.continuuity.loom.scheduler.task.NodeService;\nimport com.continuuity.loom.spec.HardwareType;\nimport com.continuuity.loom.spec.ImageType;\nimport com.continuuity.loom.spec.Provider;\nimport com.continuuity.loom.spec.service.Service;\nimport com.continuuity.loom.spec.template.ClusterTemplate;\nimport com.continuuity.loom.spec.template.Compatibilities;\nimport com.continuuity.loom.store.entity.EntityStoreService;\nimport com.continuuity.loom.store.entity.EntityStoreView;\nimport com.google.common.base.Joiner;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Maps;\nimport com.google.common.collect.Sets;\nimport com.google.inject.Inject;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport java.io.IOException;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.UUID;\n\n/**\n * The solver takes a cluster template, a number of machines, and figures out what services to put on what hardware\n * and images in order to satisfy the cluster constraints.\n *\n * TODO: add ability to grow/shrink, making sure services dont move.\n * TODO: add ability to add/remove services from an existing cluster\n * TODO: refactor into cleaner pieces with pluggable pieces for constraints\n */\npublic class Solver {\n private static final Logger LOG = LoggerFactory.getLogger(Solver.class);\n private final EntityStoreService entityStoreService;\n private final ClusterLayoutUpdater updater;\n\n @Inject\n private Solver(EntityStoreService entityStoreService, ClusterLayoutUpdater updater) {\n this.entityStoreService = entityStoreService;\n this.updater = updater;\n }\n\n /**\n * Add services to a cluster, returning which nodes were affected by the change or null if there was no way to\n * add the services to the cluster.\n *\n * @param cluster Cluster to add the services to.\n * @param clusterNodes Nodes in the cluster.\n * @param servicesToAdd Services to add to the cluster.\n * @return Nodes that need to have services added to them.\n * @throws Exception\n */\n public Set addServicesToCluster(Cluster cluster, Set clusterNodes,\n Set servicesToAdd) throws Exception {\n EntityStoreView entityStore = entityStoreService.getView(cluster.getAccount());\n Map serviceMap = getServiceMap(Sets.union(cluster.getServices(), servicesToAdd), entityStore);\n validateServiceCompatibilities(cluster.getClusterTemplate().getCompatibilities(), servicesToAdd);\n validateServiceDependencies(serviceMap);\n\n ClusterLayoutTracker tracker = updater.addServicesToCluster(cluster, clusterNodes, servicesToAdd);\n if (tracker == null) {\n return null;\n }\n\n Set changedNodes = Sets.newHashSet();\n for (ClusterLayoutChange change : tracker.getChanges()) {\n changedNodes.addAll(change.applyChange(cluster, clusterNodes, serviceMap));\n }\n return changedNodes;\n }\n\n /**\n * Validate whether or not a set of services are allowed to be added to a cluster.\n *\n * @param cluster Cluster to check addition of services to.\n * @param servicesToAdd Services to add to the cluster\n * @throws IOException\n */\n public void validateServicesToAdd(Cluster cluster, Set servicesToAdd) throws IOException {\n EntityStoreView entityStore = entityStoreService.getView(cluster.getAccount());\n Map serviceMap = getServiceMap(Sets.union(cluster.getServices(), servicesToAdd), entityStore);\n validateServicesToAdd(cluster, servicesToAdd, serviceMap);\n }\n\n private void validateServicesToAdd(Cluster cluster, Set servicesToAdd, Map serviceMap)\n {\n validateServiceCompatibilities(cluster.getClusterTemplate().getCompatibilities(), servicesToAdd);\n validateServiceDependencies(serviceMap);\n }\n\n /**\n * Given a {@link Cluster} and {@link ClusterCreateRequest}, return a mapping of node id to {@link Node} describing\n * how the cluster should be laid out. If multiple possible cluster layouts are possible, one will be chosen\n * deterministically.\n *\n * @param cluster Cluster to solve a layout for.\n * @param request Request to create a cluster containing cluster settings to use.\n * @return Mapping of node id to node for all nodes in the cluster.\n * @throws Exception\n */\n public Map solveClusterNodes(Cluster cluster, ClusterCreateRequest request) throws Exception {\n EntityStoreView entityStore = entityStoreService.getView(cluster.getAccount());\n ClusterTemplate template = cluster.getClusterTemplate();\n Provider provider = cluster.getProvider();\n String providerName = provider.getName();\n\n // make sure there are hardware types that can be used\n String requiredHardwareType = request.getHardwareType();\n if (requiredHardwareType == null || requiredHardwareType.isEmpty()) {\n // this can be null too, which means no cluster wide required type\n requiredHardwareType = template.getClusterDefaults().getHardwaretype();\n }\n if (requiredHardwareType != null && requiredHardwareType.isEmpty()) {\n requiredHardwareType = null;\n }\n Map hardwareTypeFlavors =\n getHardwareTypeMap(providerName, template, requiredHardwareType, entityStore);\n if (hardwareTypeFlavors.isEmpty()) {\n throw new IllegalArgumentException(\"no hardware types are available to use with template \"\n + template.getName() + \" and provider \" + providerName);\n }\n\n // TODO: horribly ugly... just get the ImageType object instead of treating flavor/image specially\n // make sure there are image types that can be used\n String requiredImageType = request.getImageType();\n if (requiredImageType == null || requiredImageType.isEmpty()) {\n // this can be null too, which means no cluster wide required type\n requiredImageType = template.getClusterDefaults().getImagetype();\n }\n if (requiredImageType != null && requiredImageType.isEmpty()) {\n requiredImageType = null;\n }\n Map> imageTypeMap =\n getImageTypeMap(providerName, template, requiredImageType, entityStore);", "answers": [" if (imageTypeMap.isEmpty()) {"], "length": 728, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "95834729-bb00-45a6-9f88-d521f93c4eb1", "reasoning": "The method has just retrieved a map of image types. Following the same pattern used earlier for hardware types, the next step is to check whether this map is empty and, if so, throw an IllegalArgumentException. Therefore the next line should start the empty‑check conditional.", "reasoning_model_answer": "if (imageTypeMap.isEmpty()) {", "assistant_with_reasoning": "\nThe method has just retrieved a map of image types. Following the same pattern used earlier for hardware types, the next step is to check whether this map is empty and, if so, throw an IllegalArgumentException. Therefore the next line should start the empty‑check conditional.\n\nif (imageTypeMap.isEmpty()) {", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 2.895, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 7253, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "if (imageTypeMap.isEmpty()) {", "score": 0.94, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov\n * \n * Permission is hereby granted, free of charge, to any person obtaining a copy \n * of this software and associated documentation files (the \"Software\"), to deal \n * in the Software without restriction, including without limitation the rights \n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell \n * copies of the Software, and to permit persons to whom the Software is \n * furnished to do so, subject to the following conditions:\n * \n * The above copyright notice and this permission notice shall be included in \n * all copies or substantial portions of the Software.\n * \n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR \n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, \n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE \n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER \n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, \n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN \n * THE SOFTWARE. \n */\n\nusing Microsoft.Win32.SafeHandles;\nusing System;\nusing System.Diagnostics.CodeAnalysis;\nusing System.IO;\nusing System.Runtime.InteropServices;\nusing System.Security;\nusing System.Text;\n\nnamespace Alphaleonis.Win32.Filesystem\n{\n internal static partial class NativeMethods\n { \n /// Defines, redefines, or deletes MS-DOS device names.\n /// \n /// If the function succeeds, the return value is nonzero.\n /// If the function fails, the return value is zero. To get extended error information, call GetLastError.\n /// \n /// Minimum supported client: Windows XP [desktop apps only]\n /// Minimum supported server: Windows Server 2003 [desktop apps only]\n [SuppressMessage(\"Microsoft.Security\", \"CA2118:ReviewSuppressUnmanagedCodeSecurityUsage\"), SuppressMessage(\"Microsoft.Security\", \"CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule\")]\n [DllImport(\"kernel32.dll\", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = \"DefineDosDeviceW\"), SuppressUnmanagedCodeSecurity]\n [return: MarshalAs(UnmanagedType.Bool)]\n internal static extern bool DefineDosDevice(DosDeviceAttributes dwFlags, [MarshalAs(UnmanagedType.LPWStr)] string lpDeviceName, [MarshalAs(UnmanagedType.LPWStr)] string lpTargetPath);\n\n /// Deletes a drive letter or mounted folder.\n /// \n /// If the function succeeds, the return value is nonzero.\n /// If the function fails, the return value is zero. To get extended error information, call GetLastError.\n /// \n /// Minimum supported client: Windows XP [desktop apps only]\n /// Minimum supported server: Windows Server 2003 [desktop apps only]\n [SuppressMessage(\"Microsoft.Security\", \"CA2118:ReviewSuppressUnmanagedCodeSecurityUsage\"), SuppressMessage(\"Microsoft.Security\", \"CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule\")]\n [DllImport(\"kernel32.dll\", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = \"DeleteVolumeMountPointW\"), SuppressUnmanagedCodeSecurity]\n [return: MarshalAs(UnmanagedType.Bool)]\n internal static extern bool DeleteVolumeMountPoint([MarshalAs(UnmanagedType.LPWStr)] string lpszVolumeMountPoint);\n\n /// Retrieves the name of a volume on a computer. FindFirstVolume is used to begin scanning the volumes of a computer.\n /// \n /// If the function succeeds, the return value is a search handle used in a subsequent call to the FindNextVolume and FindVolumeClose functions.\n /// If the function fails to find any volumes, the return value is the INVALID_HANDLE_VALUE error code. To get extended error information, call GetLastError.\n /// \n /// Minimum supported client: Windows XP [desktop apps only]\n /// Minimum supported server: Windows Server 2003 [desktop apps only]\n [SuppressMessage(\"Microsoft.Security\", \"CA2118:ReviewSuppressUnmanagedCodeSecurityUsage\"), SuppressMessage(\"Microsoft.Security\", \"CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule\")]\n [DllImport(\"kernel32.dll\", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = \"FindFirstVolumeW\"), SuppressUnmanagedCodeSecurity]\n internal static extern SafeFindVolumeHandle FindFirstVolume(StringBuilder lpszVolumeName, [MarshalAs(UnmanagedType.U4)] uint cchBufferLength);\n\n /// Retrieves the name of a mounted folder on the specified volume. FindFirstVolumeMountPoint is used to begin scanning the mounted folders on a volume.\n /// \n /// If the function succeeds, the return value is a search handle used in a subsequent call to the FindNextVolumeMountPoint and FindVolumeMountPointClose functions.\n /// If the function fails to find a mounted folder on the volume, the return value is the INVALID_HANDLE_VALUE error code.\n /// \n /// Minimum supported client: Windows XP [desktop apps only]\n /// Minimum supported server: Windows Server 2003 [desktop apps only]\n [SuppressMessage(\"Microsoft.Security\", \"CA2118:ReviewSuppressUnmanagedCodeSecurityUsage\"), SuppressMessage(\"Microsoft.Security\", \"CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule\")]\n [DllImport(\"kernel32.dll\", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = \"FindFirstVolumeMountPointW\"), SuppressUnmanagedCodeSecurity]\n internal static extern SafeFindVolumeMountPointHandle FindFirstVolumeMountPoint([MarshalAs(UnmanagedType.LPWStr)] string lpszRootPathName, StringBuilder lpszVolumeMountPoint, [MarshalAs(UnmanagedType.U4)] uint cchBufferLength);\n\n /// Continues a volume search started by a call to the FindFirstVolume function. FindNextVolume finds one volume per call.\n /// \n /// If the function succeeds, the return value is nonzero.\n /// If the function fails, the return value is zero. To get extended error information, call GetLastError.\n /// \n /// Minimum supported client: Windows XP [desktop apps only]\n /// Minimum supported server: Windows Server 2003 [desktop apps only]\n [SuppressMessage(\"Microsoft.Security\", \"CA2118:ReviewSuppressUnmanagedCodeSecurityUsage\"), SuppressMessage(\"Microsoft.Security\", \"CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule\")]\n [DllImport(\"kernel32.dll\", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = \"FindNextVolumeW\"), SuppressUnmanagedCodeSecurity]\n [return: MarshalAs(UnmanagedType.Bool)]\n internal static extern bool FindNextVolume(SafeFindVolumeHandle hFindVolume, StringBuilder lpszVolumeName, [MarshalAs(UnmanagedType.U4)] uint cchBufferLength);\n\n /// Continues a mounted folder search started by a call to the FindFirstVolumeMountPoint function. FindNextVolumeMountPoint finds one mounted folder per call.\n /// \n /// If the function succeeds, the return value is nonzero.\n /// If the function fails, the return value is zero. To get extended error information, call GetLastError. If no more mounted folders can be found, the GetLastError function returns the ERROR_NO_MORE_FILES error code.\n /// In that case, close the search with the FindVolumeMountPointClose function.\n /// \n /// Minimum supported client: Windows XP\n /// Minimum supported server: Windows Server 2003\n [SuppressMessage(\"Microsoft.Security\", \"CA2118:ReviewSuppressUnmanagedCodeSecurityUsage\"), SuppressMessage(\"Microsoft.Security\", \"CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule\")]\n [DllImport(\"kernel32.dll\", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = \"FindNextVolumeMountPointW\"), SuppressUnmanagedCodeSecurity]", "answers": [" [return: MarshalAs(UnmanagedType.Bool)]"], "length": 825, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "ee04ff9a-d011-4483-b3a1-f8f27af0057b", "reasoning": "The code is defining P/Invoke signatures for kernel32 functions. After the DllImport attribute for FindNextVolumeMountPointW, the pattern used for other FindNext* functions includes a return attribute specifying a bool marshaled as UnmanagedType.Bool. Therefore the next line should be the return attribute before the method signature.", "reasoning_model_answer": "[return: MarshalAs(UnmanagedType.Bool)]", "assistant_with_reasoning": "\nThe code is defining P/Invoke signatures for kernel32 functions. After the DllImport attribute for FindNextVolumeMountPointW, the pattern used for other FindNext* functions includes a return attribute specifying a bool marshaled as UnmanagedType.Bool. Therefore the next line should be the return attribute before the method signature.\n\n[return: MarshalAs(UnmanagedType.Bool)]", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.367, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 8214, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "[return: MarshalAs(UnmanagedType.Bool)]", "score": 0.93, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/*\n * Licensed to the University Corporation for Advanced Internet Development, \n * Inc. (UCAID) under one or more contributor license agreements. See the \n * NOTICE file distributed with this work for additional information regarding\n * copyright ownership. The UCAID licenses this file to You under the Apache \n * License, Version 2.0 (the \"License\"); you may not use this file except in \n * compliance with the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.opensaml.xml.security.x509;\n\nimport java.io.ByteArrayInputStream;\nimport java.io.File;\nimport java.io.IOException;\nimport java.security.GeneralSecurityException;\nimport java.security.MessageDigest;\nimport java.security.NoSuchAlgorithmException;\nimport java.security.PrivateKey;\nimport java.security.cert.CRLException;\nimport java.security.cert.CertificateEncodingException;\nimport java.security.cert.CertificateException;\nimport java.security.cert.CertificateFactory;\nimport java.security.cert.CertificateParsingException;\nimport java.security.cert.X509CRL;\nimport java.security.cert.X509Certificate;\nimport java.util.Collection;\nimport java.util.Collections;\nimport java.util.LinkedList;\nimport java.util.List;\n\nimport javax.security.auth.x500.X500Principal;\n\nimport org.apache.commons.ssl.TrustMaterial;\nimport org.bouncycastle.asn1.ASN1Encoding;\nimport org.bouncycastle.asn1.ASN1InputStream;\nimport org.bouncycastle.asn1.ASN1ObjectIdentifier;\nimport org.bouncycastle.asn1.ASN1Primitive;\nimport org.bouncycastle.asn1.ASN1Sequence;\nimport org.bouncycastle.asn1.ASN1Set;\nimport org.bouncycastle.asn1.ASN1String;\nimport org.bouncycastle.asn1.DEROctetString;\nimport org.bouncycastle.x509.extension.X509ExtensionUtil;\nimport org.opensaml.xml.security.SecurityException;\nimport org.opensaml.xml.security.SecurityHelper;\nimport org.opensaml.xml.util.DatatypeHelper;\nimport org.opensaml.xml.util.IPAddressHelper;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\n/**\n * Utility class for working with X509 objects.\n */\npublic class X509Util {\n\n /** Encoding used to store a key or certificate in a file. */\n public static enum ENCODING_FORMAT {\n PEM, DER\n };\n\n /** Common Name (CN) OID. */\n public static final String CN_OID = \"2.5.4.3\";\n \n /** Subject Key Identifier (SKI) OID. */\n public static final String SKI_OID = \"2.5.29.14\";\n\n /** RFC 2459 Other Subject Alt Name type. */\n public static final Integer OTHER_ALT_NAME = new Integer(0);\n\n /** RFC 2459 RFC 822 (email address) Subject Alt Name type. */\n public static final Integer RFC822_ALT_NAME = new Integer(1);\n\n /** RFC 2459 DNS Subject Alt Name type. */\n public static final Integer DNS_ALT_NAME = new Integer(2);\n\n /** RFC 2459 X.400 Address Subject Alt Name type. */\n public static final Integer X400ADDRESS_ALT_NAME = new Integer(3);\n\n /** RFC 2459 Directory Name Subject Alt Name type. */\n public static final Integer DIRECTORY_ALT_NAME = new Integer(4);\n\n /** RFC 2459 EDI Party Name Subject Alt Name type. */\n public static final Integer EDI_PARTY_ALT_NAME = new Integer(5);\n\n /** RFC 2459 URI Subject Alt Name type. */\n public static final Integer URI_ALT_NAME = new Integer(6);\n\n /** RFC 2459 IP Address Subject Alt Name type. */\n public static final Integer IP_ADDRESS_ALT_NAME = new Integer(7);\n\n /** RFC 2459 Registered ID Subject Alt Name type. */\n public static final Integer REGISTERED_ID_ALT_NAME = new Integer(8);\n\n /** Constructed. */\n protected X509Util() {\n\n }\n \n /**\n * Determines the certificate, from the collection, associated with the private key.\n * \n * @param certs certificates to check\n * @param privateKey entity's private key\n * \n * @return the certificate associated with entity's private key or null if not certificate in the collection is\n * associated with the given private key\n * \n * @throws SecurityException thrown if the public or private keys checked are of an unsupported type\n * \n * @since 1.2\n */\n public static X509Certificate determineEntityCertificate(Collection certs, PrivateKey privateKey)\n throws SecurityException {\n if (certs == null || privateKey == null) {\n return null;\n }\n\n for (X509Certificate certificate : certs) {\n try {\n if (SecurityHelper.matchKeyPair(certificate.getPublicKey(), privateKey)) {\n return certificate;\n }\n } catch (SecurityException e) {\n // An exception here is just a false match.\n // Java 7 apparently throws in this case.\n }\n }\n\n return null;\n }\n\n /**\n * Gets the commons names that appear within the given distinguished name. \n * \n *

    \n * The returned list provides the names in the order they appeared in the DN, according to \n * RFC 1779/2253 encoding. In this encoding the \"most specific\" name would typically appear\n * in the left-most position, and would appear first in the returned list.\n *

    \n * \n * @param dn the DN to extract the common names from\n * \n * @return the common names that appear in the DN in the order they appear, or null if the given DN is null\n */\n public static List getCommonNames(X500Principal dn) {\n Logger log = getLogger();\n if (dn == null) {\n return null;\n }\n\n log.debug(\"Extracting CNs from the following DN: {}\", dn.toString());\n List commonNames = new LinkedList();\n try {\n ASN1InputStream asn1Stream = new ASN1InputStream(dn.getEncoded());\n ASN1Sequence dnSequence = (ASN1Sequence) asn1Stream.readObject();\n\n // Walk the DN sequence in reverse order from last to first, so that the CN(s) from the most-specific RDN\n // are first in the returned list, consistent with RFC 1779/2253 RDN ordering.\n for (int i = dnSequence.size()-1; i >= 0; i--) {\n ASN1Primitive rdn = dnSequence.getObjectAt(i).toASN1Primitive();\n if (!(rdn instanceof ASN1Set)) {\n log.debug(\"DN RDN was not an instance of ASN1Set.\");\n continue;\n }\n \n // Each RDN is an ASN.1 set (note: unordered)\n ASN1Set rdnSet = (ASN1Set) rdn;\n\n // Walk the attributes within the RDN from first to last, to preserve the ordering of the encoded form.\n for (int j = 0; j < rdnSet.size(); j++) {\n ASN1Sequence attributeTypeAndValue = (ASN1Sequence) rdnSet.getObjectAt(j).toASN1Primitive();\n\n if (attributeTypeAndValue.getObjectAt(0) != null\n && attributeTypeAndValue.getObjectAt(0).toASN1Primitive() instanceof ASN1ObjectIdentifier) {\n ASN1ObjectIdentifier attributeTypeId = (ASN1ObjectIdentifier) attributeTypeAndValue\n .getObjectAt(0).toASN1Primitive();\n", "answers": [" if (CN_OID.equals(attributeTypeId.getId())) {"], "length": 845, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "66ffbf81-653f-4757-bc02-4c6684ca64b3", "reasoning": "The method is iterating over each attribute in an RDN to find common name (CN) attributes. After extracting the attribute's type identifier into 'attributeTypeId', the next logical step is to check whether this OID matches the CN OID constant (CN_OID). Therefore the next line should be the conditional that compares the OID to CN_OID.", "reasoning_model_answer": "if (CN_OID.equals(attributeTypeId.getId())) {", "assistant_with_reasoning": "\nThe method is iterating over each attribute in an RDN to find common name (CN) attributes. After extracting the attribute's type identifier into 'attributeTypeId', the next logical step is to check whether this OID matches the CN OID constant (CN_OID). Therefore the next line should be the conditional that compares the OID to CN_OID.\n\nif (CN_OID.equals(attributeTypeId.getId())) {", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.8, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 7551, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "if (CN_OID.equals(attributeTypeId.getId())) {", "score": 0.79, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/*\n * Copyright 2000-2016 JetBrains s.r.o.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.intellij.coverage;\n\nimport com.intellij.codeInsight.CodeInsightBundle;\nimport com.intellij.history.FileRevisionTimestampComparator;\nimport com.intellij.history.LocalHistory;\nimport com.intellij.icons.AllIcons;\nimport com.intellij.openapi.Disposable;\nimport com.intellij.openapi.application.ApplicationManager;\nimport com.intellij.openapi.diagnostic.Logger;\nimport com.intellij.openapi.editor.Document;\nimport com.intellij.openapi.editor.Editor;\nimport com.intellij.openapi.editor.colors.EditorColorsManager;\nimport com.intellij.openapi.editor.colors.EditorColorsScheme;\nimport com.intellij.openapi.editor.event.DocumentAdapter;\nimport com.intellij.openapi.editor.event.DocumentEvent;\nimport com.intellij.openapi.editor.event.DocumentListener;\nimport com.intellij.openapi.editor.impl.DocumentMarkupModel;\nimport com.intellij.openapi.editor.markup.*;\nimport com.intellij.openapi.fileEditor.FileEditor;\nimport com.intellij.openapi.fileEditor.FileEditorManager;\nimport com.intellij.openapi.fileEditor.TextEditor;\nimport com.intellij.openapi.fileEditor.impl.LoadTextUtil;\nimport com.intellij.openapi.module.Module;\nimport com.intellij.openapi.module.ModuleUtilCore;\nimport com.intellij.openapi.project.Project;\nimport com.intellij.openapi.roots.ProjectFileIndex;\nimport com.intellij.openapi.roots.ProjectRootManager;\nimport com.intellij.openapi.util.Computable;\nimport com.intellij.openapi.util.Key;\nimport com.intellij.openapi.util.Ref;\nimport com.intellij.openapi.util.TextRange;\nimport com.intellij.openapi.util.text.LineTokenizer;\nimport com.intellij.openapi.vcs.AbstractVcs;\nimport com.intellij.openapi.vcs.FilePath;\nimport com.intellij.openapi.vcs.actions.VcsContextFactory;\nimport com.intellij.openapi.vcs.history.VcsFileRevision;\nimport com.intellij.openapi.vcs.history.VcsHistoryProvider;\nimport com.intellij.openapi.vcs.history.VcsHistorySession;\nimport com.intellij.openapi.vfs.VirtualFile;\nimport com.intellij.psi.PsiFile;\nimport com.intellij.reference.SoftReference;\nimport com.intellij.rt.coverage.data.ClassData;\nimport com.intellij.rt.coverage.data.LineCoverage;\nimport com.intellij.rt.coverage.data.LineData;\nimport com.intellij.rt.coverage.data.ProjectData;\nimport com.intellij.ui.EditorNotificationPanel;\nimport com.intellij.util.Alarm;\nimport com.intellij.util.Function;\nimport com.intellij.util.diff.Diff;\nimport com.intellij.util.diff.FilesTooBigForDiffException;\nimport com.intellij.vcsUtil.VcsUtil;\nimport gnu.trove.TIntIntHashMap;\nimport org.jetbrains.annotations.NotNull;\nimport org.jetbrains.annotations.Nullable;\n\nimport java.io.File;\nimport java.util.*;\n\n/**\n * @author ven\n */\npublic class SrcFileAnnotator implements Disposable {\n private static final Logger LOG = Logger.getInstance(\"#com.intellij.coverage.SrcFileAnnotator\");\n public static final Key> COVERAGE_HIGHLIGHTERS = Key.create(\"COVERAGE_HIGHLIGHTERS\");\n private static final Key COVERAGE_DOCUMENT_LISTENER = Key.create(\"COVERAGE_DOCUMENT_LISTENER\");\n public static final Key> NOTIFICATION_PANELS = Key.create(\"NOTIFICATION_PANELS\");\n\n private PsiFile myFile;\n private Editor myEditor;\n private Document myDocument;\n private final Project myProject;\n\n private SoftReference myNewToOldLines;\n private SoftReference myOldToNewLines;\n private SoftReference myOldContent;\n private final static Object LOCK = new Object();\n \n private final Alarm myUpdateAlarm = new Alarm(Alarm.ThreadToUse.POOLED_THREAD, this);\n\n public SrcFileAnnotator(final PsiFile file, final Editor editor) {\n myFile = file;\n myEditor = editor;\n myProject = file.getProject();\n myDocument = myEditor.getDocument();\n }\n\n \n public void hideCoverageData() {\n Editor editor = myEditor;\n PsiFile file = myFile;\n Document document = myDocument;\n if (editor == null || editor.isDisposed() || file == null || document == null) return;\n final FileEditorManager fileEditorManager = FileEditorManager.getInstance(myProject);\n final List highlighters = editor.getUserData(COVERAGE_HIGHLIGHTERS);\n if (highlighters != null) {\n for (final RangeHighlighter highlighter : highlighters) {\n ApplicationManager.getApplication().invokeLater(() -> highlighter.dispose());\n }\n editor.putUserData(COVERAGE_HIGHLIGHTERS, null);\n }\n\n final Map map = file.getCopyableUserData(NOTIFICATION_PANELS);\n if (map != null) {\n final VirtualFile vFile = getVirtualFile(file);\n boolean freeAll = !fileEditorManager.isFileOpen(vFile);\n file.putCopyableUserData(NOTIFICATION_PANELS, null);\n for (FileEditor fileEditor : map.keySet()) {\n if (!freeAll && !isCurrentEditor(fileEditor)) {\n continue;\n }\n fileEditorManager.removeTopComponent(fileEditor, map.get(fileEditor));\n }\n }\n\n\n final DocumentListener documentListener = editor.getUserData(COVERAGE_DOCUMENT_LISTENER);\n if (documentListener != null) {\n document.removeDocumentListener(documentListener);\n editor.putUserData(COVERAGE_DOCUMENT_LISTENER, null);\n }\n }\n\n @NotNull\n private static String[] getCoveredLines(@NotNull byte[] oldContent, VirtualFile vFile) {\n final String text = LoadTextUtil.getTextByBinaryPresentation(oldContent, vFile, false, false).toString();\n return LineTokenizer.tokenize(text, false);\n }\n\n @NotNull private static String[] getUpToDateLines(final Document document) {\n final Ref linesRef = new Ref<>();\n final Runnable runnable = () -> {\n final int lineCount = document.getLineCount();\n final String[] lines = new String[lineCount];\n final CharSequence chars = document.getCharsSequence();\n for (int i = 0; i < lineCount; i++) {\n lines[i] = chars.subSequence(document.getLineStartOffset(i), document.getLineEndOffset(i)).toString();\n }\n linesRef.set(lines);\n };\n ApplicationManager.getApplication().runReadAction(runnable);\n\n return linesRef.get();\n }\n\n private static TIntIntHashMap getCoverageVersionToCurrentLineMapping(Diff.Change change, int firstNLines) {\n TIntIntHashMap result = new TIntIntHashMap();\n int prevLineInFirst = 0;\n int prevLineInSecond = 0;\n while (change != null) {\n\n for (int l = 0; l < change.line0 - prevLineInFirst; l++) {\n result.put(prevLineInFirst + l, prevLineInSecond + l);\n }\n\n prevLineInFirst = change.line0 + change.deleted;\n prevLineInSecond = change.line1 + change.inserted;\n\n change = change.link;\n }\n\n for (int i = prevLineInFirst; i < firstNLines; i++) {\n result.put(i, prevLineInSecond + i - prevLineInFirst);\n }\n\n return result;\n }\n\n @Nullable\n private TIntIntHashMap getOldToNewLineMapping(final long date, MyEditorBean editorBean) {\n if (myOldToNewLines == null) {\n myOldToNewLines = doGetLineMapping(date, true, editorBean);\n if (myOldToNewLines == null) return null;\n }\n return myOldToNewLines.get();\n }\n\n @Nullable\n private TIntIntHashMap getNewToOldLineMapping(final long date, MyEditorBean editorBean) {\n if (myNewToOldLines == null) {\n myNewToOldLines = doGetLineMapping(date, false, editorBean);\n if (myNewToOldLines == null) return null;\n }\n return myNewToOldLines.get();\n }\n\n @Nullable\n private SoftReference doGetLineMapping(final long date, boolean oldToNew, MyEditorBean editorBean) {\n VirtualFile virtualFile = editorBean.getVFile();\n final byte[] oldContent;\n synchronized (LOCK) {\n if (myOldContent == null) {\n if (ApplicationManager.getApplication().isDispatchThread()) return null;\n final LocalHistory localHistory = LocalHistory.getInstance();\n byte[] byteContent = localHistory.getByteContent(virtualFile, new FileRevisionTimestampComparator() {\n public boolean isSuitable(long revisionTimestamp) {\n return revisionTimestamp < date;\n }\n });\n\n if (byteContent == null && virtualFile.getTimeStamp() > date) {\n byteContent = loadFromVersionControl(date, virtualFile);\n } \n myOldContent = new SoftReference<>(byteContent);\n }\n oldContent = myOldContent.get();\n }\n\n if (oldContent == null) return null;\n String[] coveredLines = getCoveredLines(oldContent, virtualFile);\n final Document document = editorBean.getDocument();\n if (document == null) return null;\n String[] currentLines = getUpToDateLines(document);\n\n String[] oldLines = oldToNew ? coveredLines : currentLines;\n String[] newLines = oldToNew ? currentLines : coveredLines;\n\n Diff.Change change;\n try {\n change = Diff.buildChanges(oldLines, newLines);\n }\n catch (FilesTooBigForDiffException e) {\n LOG.info(e);\n return null;\n }\n return new SoftReference<>(getCoverageVersionToCurrentLineMapping(change, oldLines.length));\n }\n\n @Nullable\n private byte[] loadFromVersionControl(long date, VirtualFile f) {\n try {\n final AbstractVcs vcs = VcsUtil.getVcsFor(myProject, f);\n if (vcs == null) return null;\n\n final VcsHistoryProvider historyProvider = vcs.getVcsHistoryProvider();\n if (historyProvider == null) return null;\n\n final FilePath filePath = VcsContextFactory.SERVICE.getInstance().createFilePathOn(f);\n final VcsHistorySession session = historyProvider.createSessionFor(filePath);\n if (session == null) return null;\n\n final List list = session.getRevisionList();\n\n if (list != null) {\n for (VcsFileRevision revision : list) {\n final Date revisionDate = revision.getRevisionDate();\n if (revisionDate == null) {\n return null;\n }\n\n if (revisionDate.getTime() < date) {", "answers": [" return revision.loadContent();"], "length": 865, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "a5e92693-2f2f-4f57-8243-52982d26f4f7", "reasoning": "We are inside the loadFromVersionControl method, iterating over VcsFileRevision objects. When a revision's timestamp is earlier than the given date, we need to retrieve its file content. The VcsFileRevision API provides loadContent() returning a byte[]. Therefore the next line should return that content.", "reasoning_model_answer": "return revision.loadContent();", "assistant_with_reasoning": "\nWe are inside the loadFromVersionControl method, iterating over VcsFileRevision objects. When a revision's timestamp is earlier than the given date, we need to retrieve its file content. The VcsFileRevision API provides loadContent() returning a byte[]. Therefore the next line should return that content.\n\nreturn revision.loadContent();", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 2.6, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 10517, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "return revision.loadContent();", "score": 0.83, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.apache.ignite.internal.binary;\n\nimport java.io.Externalizable;\nimport java.io.IOException;\nimport java.io.ObjectInput;\nimport java.io.ObjectOutput;\nimport java.math.BigDecimal;\nimport java.math.BigInteger;\nimport java.nio.ByteBuffer;\nimport java.sql.Time;\nimport java.sql.Timestamp;\nimport java.util.Date;\nimport java.util.UUID;\nimport org.apache.ignite.IgniteCheckedException;\nimport org.apache.ignite.binary.BinaryObject;\nimport org.apache.ignite.binary.BinaryObjectException;\nimport org.apache.ignite.binary.BinaryType;\nimport org.apache.ignite.internal.GridDirectTransient;\nimport org.apache.ignite.internal.IgniteCodeGeneratingFail;\nimport org.apache.ignite.internal.binary.streams.BinaryHeapInputStream;\nimport org.apache.ignite.internal.processors.cache.CacheObject;\nimport org.apache.ignite.internal.processors.cache.CacheObjectAdapter;\nimport org.apache.ignite.internal.processors.cache.CacheObjectContext;\nimport org.apache.ignite.internal.processors.cache.CacheObjectValueContext;\nimport org.apache.ignite.internal.processors.cache.KeyCacheObject;\nimport org.apache.ignite.internal.processors.cache.binary.CacheObjectBinaryProcessorImpl;\nimport org.apache.ignite.internal.util.typedef.internal.U;\nimport org.apache.ignite.plugin.extensions.communication.MessageReader;\nimport org.apache.ignite.plugin.extensions.communication.MessageWriter;\nimport org.jetbrains.annotations.Nullable;\n\nimport static java.nio.charset.StandardCharsets.UTF_8;\n\n/**\n * Binary object implementation.\n */\n@IgniteCodeGeneratingFail // Fields arr and start should not be generated by MessageCodeGenerator.\npublic final class BinaryObjectImpl extends BinaryObjectExImpl implements Externalizable, KeyCacheObject {\n /** */\n private static final long serialVersionUID = 0L;\n\n /** */\n @GridDirectTransient\n private BinaryContext ctx;\n\n /** */\n private byte[] arr;\n\n /** */\n private int start;\n\n /** */\n @GridDirectTransient\n private Object obj;\n\n /** */\n @GridDirectTransient\n private boolean detachAllowed;\n\n /** */\n private int part = -1;\n\n /**\n * For {@link Externalizable}.\n */\n public BinaryObjectImpl() {\n // No-op.\n }\n\n /**\n * @param ctx Context.\n * @param arr Array.\n * @param start Start.\n */\n public BinaryObjectImpl(BinaryContext ctx, byte[] arr, int start) {\n assert ctx != null;\n assert arr != null;\n\n this.ctx = ctx;\n this.arr = arr;\n this.start = start;\n }\n\n /** {@inheritDoc} */\n @Override public KeyCacheObject copy(int part) {\n if (this.part == part)\n return this;\n\n BinaryObjectImpl cp = new BinaryObjectImpl(ctx, arr, start);\n cp.part = part;\n\n return cp;\n }\n\n /** {@inheritDoc} */\n @Override public int partition() {\n return part;\n }\n\n /** {@inheritDoc} */\n @Override public void partition(int part) {\n this.part = part;\n }\n\n /** {@inheritDoc} */\n @Override public byte cacheObjectType() {\n return TYPE_BINARY;\n }\n\n /** {@inheritDoc} */\n @Override public boolean isPlatformType() {\n return false;\n }\n\n /** {@inheritDoc} */\n @Override public boolean internal() {\n return false;\n }\n\n /** {@inheritDoc} */\n @Nullable @Override public T value(CacheObjectValueContext ctx, boolean cpy) {\n Object obj0 = obj;\n\n if (obj0 == null || (cpy && needCopy(ctx)))\n obj0 = deserializeValue(ctx);\n\n return (T)obj0;\n }\n\n /** {@inheritDoc} */\n @Override public byte[] valueBytes(CacheObjectValueContext ctx) throws IgniteCheckedException {\n if (detached())\n return array();\n\n int len = length();\n\n byte[] arr0 = new byte[len];\n\n U.arrayCopy(arr, start, arr0, 0, len);\n\n return arr0;\n }\n\n /** {@inheritDoc} */\n @Override public boolean putValue(ByteBuffer buf) throws IgniteCheckedException {\n return putValue(buf, 0, CacheObjectAdapter.objectPutSize(length()));\n }\n\n /** {@inheritDoc} */\n @Override public int putValue(long addr) throws IgniteCheckedException {\n return CacheObjectAdapter.putValue(addr, cacheObjectType(), arr, start);\n }\n\n /** {@inheritDoc} */\n @Override public boolean putValue(final ByteBuffer buf, int off, int len) throws IgniteCheckedException {\n return CacheObjectAdapter.putValue(cacheObjectType(), buf, off, len, arr, start);\n }\n\n /** {@inheritDoc} */\n @Override public int valueBytesLength(CacheObjectContext ctx) throws IgniteCheckedException {\n return CacheObjectAdapter.objectPutSize(length());\n }\n\n /** {@inheritDoc} */\n @Override public CacheObject prepareForCache(CacheObjectContext ctx) {\n if (detached())\n return this;\n\n return (BinaryObjectImpl)detach();\n }\n\n /** {@inheritDoc} */\n @Override public void finishUnmarshal(CacheObjectValueContext ctx, ClassLoader ldr) throws IgniteCheckedException {\n CacheObjectBinaryProcessorImpl binaryProc = (CacheObjectBinaryProcessorImpl)ctx.kernalContext().cacheObjects();\n\n this.ctx = binaryProc.binaryContext();\n\n binaryProc.waitMetadataWriteIfNeeded(typeId());\n }\n\n /** {@inheritDoc} */\n @Override public void prepareMarshal(CacheObjectValueContext ctx) throws IgniteCheckedException {\n // No-op.\n }\n\n /** {@inheritDoc} */\n @Override public int length() {\n return BinaryPrimitives.readInt(arr, start + GridBinaryMarshaller.TOTAL_LEN_POS);\n }\n\n /**\n * @return Detached binary object.\n */\n public BinaryObjectImpl detach() {\n if (!detachAllowed || detached())\n return this;\n\n int len = length();\n\n byte[] arr0 = new byte[len];\n\n U.arrayCopy(arr, start, arr0, 0, len);\n\n return new BinaryObjectImpl(ctx, arr0, 0);\n }\n\n /**\n * @return Detached or not.\n */\n public boolean detached() {\n return start == 0 && length() == arr.length;\n }\n\n /**\n * @param detachAllowed Detach allowed flag.\n */\n public void detachAllowed(boolean detachAllowed) {\n this.detachAllowed = detachAllowed;\n }\n\n /** {@inheritDoc} */\n @Override public BinaryContext context() {\n return ctx;\n }\n\n /**\n * @param ctx Context.\n */\n public void context(BinaryContext ctx) {", "answers": [" this.ctx = ctx;"], "length": 699, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "ce692ec8-e009-4b9d-a6ea-2cd5adbf2590", "reasoning": "The method `public void context(BinaryContext ctx) {` is a setter for the BinaryContext field. Following the pattern of other simple setters in the class (e.g., `detachAllowed(boolean detachAllowed)` which assigns `this.detachAllowed = detachAllowed;`), the next line should assign the passed context to the instance field. Therefore the appropriate next line is `this.ctx = ctx;`.", "reasoning_model_answer": "this.ctx = ctx;", "assistant_with_reasoning": "\nThe method `public void context(BinaryContext ctx) {` is a setter for the BinaryContext field. Following the pattern of other simple setters in the class (e.g., `detachAllowed(boolean detachAllowed)` which assigns `this.detachAllowed = detachAllowed;`), the next line should assign the passed context to the instance field. Therefore the appropriate next line is `this.ctx = ctx;`.\n\nthis.ctx = ctx;", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 1.947, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 7268, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "this.ctx = ctx;", "score": 0.79, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "package apps.jigsawapp;\n\n// demo test\nimport java.awt.Color;\nimport java.awt.Font;\nimport java.awt.Graphics2D;\nimport java.awt.image.BufferedImage;\nimport java.io.File;\nimport java.io.FileInputStream;\nimport java.io.FileNotFoundException;\nimport java.io.IOException;\nimport java.net.MalformedURLException;\nimport java.util.ArrayList;\nimport java.util.Random;\n\nimport javax.imageio.ImageIO;\n\nimport synergynetframework.appsystem.contentsystem.ContentSystem;\nimport synergynetframework.appsystem.contentsystem.items.ContentItem;\nimport synergynetframework.appsystem.contentsystem.items.Frame;\nimport synergynetframework.appsystem.contentsystem.items.TextLabel;\nimport synergynetframework.appsystem.contentsystem.items.listener.ItemListener;\nimport synergynetframework.appsystem.services.net.localpresence.TableIdentity;\nimport synergynetframework.appsystem.table.SynergyNetAppUtils;\nimport synergynetframework.appsystem.table.appdefinitions.DefaultSynergyNetApp;\nimport synergynetframework.appsystem.table.appregistry.ApplicationInfo;\nimport synergynetframework.appsystem.table.appregistry.menucontrol.HoldTopRightConfirmVisualExit;\n\n/**\n * The Class JigsawAppStart.\n */\npublic class JigsawAppStart extends DefaultSynergyNetApp {\n\t\n\t/** The Back text. */\n\tprivate TextLabel BackText;\n\t\n\t/** The content system. */\n\tContentSystem contentSystem;\n\n\t/** The Current level. */\n\tprivate int CurrentLevel;\n\n\t/** The image1. */\n\tprivate Frame image1;\n\n\t/** The image2. */\n\tprivate Frame image2;\n\n\t/** The image3. */\n\tprivate Frame image3;\n\t\n\t/** The image4. */\n\tprivate Frame image4;\n\t\n\t/** The L01. */\n\tprivate Level L01;\n\t\n\t/** The L01 text. */\n\tprivate TextLabel L01Text;\n\n\t/** The L02. */\n\tprivate Level L02;\n\n\t/** The L02 text. */\n\tprivate TextLabel L02Text;\n\n\t/** The L03. */\n\tprivate Level L03;\n\n\t/** The L03 text. */\n\tprivate TextLabel L03Text;\n\n\t/** The L04. */\n\tprivate Level L04;\n\n\t/** The L04 text. */\n\tprivate TextLabel L04Text;\n\n\t/** The mini_images. */\n\tprivate ArrayList mini_images = new ArrayList();\n\n\t/** The See original. */\n\tprivate TextLabel SeeOriginal;\n\t\n\t/** The See original status. */\n\tprivate boolean SeeOriginalStatus = true;\n\t\n\t/** The Temp image. */\n\tprivate Frame TempImage;\n\n\t/**\n\t * Instantiates a new jigsaw app start.\n\t *\n\t * @param info\n\t * the info\n\t */\n\tpublic JigsawAppStart(ApplicationInfo info) {\n\t\tsuper(info);\n\t}\n\n\t/*\n\t * (non-Javadoc)\n\t * @see\n\t * synergynetframework.appsystem.table.appdefinitions.SynergyNetApp#addContent\n\t * ()\n\t */\n\tpublic void addContent() {\n\t\tCleanTempImages();\n\n\t\tcontentSystem = ContentSystem.getContentSystemForSynergyNetApp(this);\n\t\t\n\t\tSynergyNetAppUtils.addTableOverlay(this); // to display blobs\n\t\tsetMenuController(new HoldTopRightConfirmVisualExit(this));\n\t\t\n\t\tString tableID = TableIdentity.getTableIdentity().toString();\n\n\t\tif (!tableID.equals(\"red\") && !tableID.equals(\"blue\")\n\t\t\t\t&& !tableID.equals(\"yellow\") && !tableID.equals(\"green\")\n\t\t\t\t&& !tableID.equals(\"teacher\")) {\n\t\t\tString[] ids = { \"red\", \"blue\", \"yellow\", \"green\", \"teacher\" };\n\t\t\ttableID = ids[new Random().nextInt(4)];\n\t\t}\n\n\t\tL01 = new Level(1, tableID, \"img01.jpg\", 2, 2);\n\t\tL02 = new Level(2, tableID, \"img02.jpg\", 3, 3);\n\t\tL03 = new Level(3, tableID, \"img03.jpg\", 4, 4);\n\t\tL04 = new Level(4, tableID, \"img04.jpg\", 5, 5);\n\n\t\timage1 = (Frame) contentSystem.createContentItem(Frame.class);\n\t\timage1.setWidth(L01.ImageWidth);\n\t\timage1.setHeight(L01.ImageHeight);\n\t\timage1.setLocation(250, 550);\n\t\timage1.setScale(0.30f);\n\t\t\n\t\tL01Text = (TextLabel) contentSystem.createContentItem(TextLabel.class);\n\t\tL01Text.setText(\"[2 x 2]\");\n\t\tL01Text.setBackgroundColour(Color.black);\n\t\tL01Text.setBorderSize(0);\n\t\tL01Text.setTextColour(Color.cyan);\n\t\tL01Text.setLocation(250, 675);\n\t\tL01Text.setRotateTranslateScalable(false);\n\t\t// L01Text.setAngle (270 * FastMath.DEG_TO_RAD);\n\t\t// L01Text.setScale (3);\n\t\t\n\t\ttry {\n\t\t\timage1.drawImage(L01.ImageFile.toURI().toURL());\n\t\t} catch (MalformedURLException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t\t\n\t\timage2 = (Frame) contentSystem.createContentItem(Frame.class);\n\t\timage2.setWidth(L02.ImageWidth);\n\t\timage2.setHeight(L02.ImageHeight);\n\t\timage2.setScale(0.30f);\n\t\timage2.setLocation(750, 550);\n\t\t\n\t\tL02Text = (TextLabel) contentSystem.createContentItem(TextLabel.class);\n\t\tL02Text.setText(\"[3 x 3]\");\n\t\tL02Text.setBackgroundColour(Color.black);\n\t\tL02Text.setBorderSize(0);\n\t\tL02Text.setTextColour(Color.yellow);\n\t\tL02Text.setLocation(750, 675);\n\t\tL02Text.setRotateTranslateScalable(false);\n\t\t// L02Text.setAngle(45 * FastMath.DEG_TO_RAD);\n\t\t// L02Text.setScale(3);\n\t\t\n\t\ttry {\n\t\t\timage2.drawImage(L02.ImageFile.toURI().toURL());\n\t\t} catch (MalformedURLException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t\t\n\t\timage3 = (Frame) contentSystem.createContentItem(Frame.class);\n\t\timage3.setWidth(L03.ImageWidth);\n\t\timage3.setHeight(L03.ImageHeight);\n\t\timage3.setScale(0.3f);\n\t\timage3.setLocation(250, 200);\n\t\t\n\t\tL03Text = (TextLabel) contentSystem.createContentItem(TextLabel.class);\n\t\tL03Text.setText(\"[4 x 4]\");\n\t\tL03Text.setBackgroundColour(Color.black);\n\t\tL03Text.setBorderSize(0);\n\t\tL03Text.setTextColour(Color.orange);\n\t\tL03Text.setLocation(250, 325);\n\t\tL03Text.setRotateTranslateScalable(false);\n\t\t// L03Text.setAngle(45 * FastMath.DEG_TO_RAD);\n\t\t// L03Text.setScale(3);\n\t\t\n\t\ttry {\n\t\t\timage3.drawImage(L03.ImageFile.toURI().toURL());\n\t\t} catch (MalformedURLException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t\t\n\t\timage4 = (Frame) contentSystem.createContentItem(Frame.class);\n\t\timage4.setWidth(L04.ImageWidth);\n\t\timage4.setHeight(L04.ImageHeight);\n\t\timage4.setScale(0.30f);\n\t\timage4.setLocation(750, 200);\n\t\t\n\t\tL04Text = (TextLabel) contentSystem.createContentItem(TextLabel.class);\n\t\tL04Text.setText(\"[5 x 5]\");\n\t\tL04Text.setBackgroundColour(Color.black);\n\t\tL04Text.setBorderSize(0);\n\t\tL04Text.setTextColour(Color.red);\n\t\tL04Text.setLocation(750, 325);\n\t\tL04Text.setRotateTranslateScalable(false);\n\t\t// L04Text.setAngle(45 * FastMath.DEG_TO_RAD);\n\t\t// L04Text.setScale(3);\n\t\t\n\t\ttry {\n\t\t\timage4.drawImage(L04.ImageFile.toURI().toURL());\n\t\t} catch (MalformedURLException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t\t\n\t\timage1.addItemListener(new ItemListener() {\n\t\t\t\n\t\t\t@Override\n\t\t\tpublic void cursorChanged(ContentItem item, long id, float x,\n\t\t\t\t\tfloat y, float pressure) {\n\t\t\t}\n\t\t\t\n\t\t\t@Override\n\t\t\tpublic void cursorClicked(ContentItem item, long id, float x,\n\t\t\t\t\tfloat y, float pressure) {\n\t\t\t\t\n\t\t\t}\n\t\t\t\n\t\t\t@Override\n\t\t\tpublic void cursorDoubleClicked(ContentItem item, long id, float x,\n\t\t\t\t\tfloat y, float pressure) {\n\t\t\t\t\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic void cursorLongHeld(ContentItem item, long id, float x,\n\t\t\t\t\tfloat y, float pressure) {\n\t\t\t\t\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic void cursorPressed(ContentItem item, long id, float x,\n\t\t\t\t\tfloat y, float pressure) {\n\n\t\t\t\tSetInitialSurfaceVisibility(false);\n\t\t\t\tCurrentLevel = 1;\n\t\t\t\tPlayLevel(L01);\n\t\t\t}\n\t\t\t\n\t\t\t@Override\n\t\t\tpublic void cursorReleased(ContentItem item, long id, float x,\n\t\t\t\t\tfloat y, float pressure) {\n\t\t\t\t\n\t\t\t}\n\t\t\t\n\t\t\t@Override\n\t\t\tpublic void cursorRightClicked(ContentItem item, long id, float x,\n\t\t\t\t\tfloat y, float pressure) {\n\t\t\t\t\n\t\t\t}\n\t\t\t\n\t\t});\n\t\t\n\t\timage2.addItemListener(new ItemListener() {\n\t\t\t@Override\n\t\t\tpublic void cursorChanged(ContentItem item, long id, float x,\n\t\t\t\t\tfloat y, float pressure) {\n\t\t\t\t\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic void cursorClicked(ContentItem item, long id, float x,\n\t\t\t\t\tfloat y, float pressure) {\n\t\t\t\t\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic void cursorDoubleClicked(ContentItem item, long id, float x,\n\t\t\t\t\tfloat y, float pressure) {\n\t\t\t\t\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic void cursorLongHeld(ContentItem item, long id, float x,\n\t\t\t\t\tfloat y, float pressure) {\n\t\t\t\t\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic void cursorPressed(ContentItem item, long id, float x,\n\t\t\t\t\tfloat y, float pressure) {\n\t\t\t\t\n\t\t\t\tSetInitialSurfaceVisibility(false);\n\t\t\t\tCurrentLevel = 2;\n\t\t\t\tPlayLevel(L02);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic void cursorReleased(ContentItem item, long id, float x,\n\t\t\t\t\tfloat y, float pressure) {\n\t\t\t\t\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic void cursorRightClicked(ContentItem item, long id, float x,\n\t\t\t\t\tfloat y, float pressure) {\n\t\t\t\t\n\t\t\t}\n\t\t});\n\t\t\n\t\timage3.addItemListener(new ItemListener() {\n\t\t\t@Override\n\t\t\tpublic void cursorChanged(ContentItem item, long id, float x,\n\t\t\t\t\tfloat y, float pressure) {\n\t\t\t\t\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic void cursorClicked(ContentItem item, long id, float x,\n\t\t\t\t\tfloat y, float pressure) {\n\t\t\t\t\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic void cursorDoubleClicked(ContentItem item, long id, float x,\n\t\t\t\t\tfloat y, float pressure) {\n\t\t\t\t\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic void cursorLongHeld(ContentItem item, long id, float x,\n\t\t\t\t\tfloat y, float pressure) {\n\t\t\t\t\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic void cursorPressed(ContentItem item, long id, float x,\n\t\t\t\t\tfloat y, float pressure) {\n\n\t\t\t\tSetInitialSurfaceVisibility(false);\n\t\t\t\tCurrentLevel = 3;\n\t\t\t\tPlayLevel(L03);\n\t\t\t}\n\n\t\t\t@Override", "answers": ["\t\t\tpublic void cursorReleased(ContentItem item, long id, float x,"], "length": 789, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "ea8071bd-04fa-47f9-a32e-9804682b504f", "reasoning": "The code is defining an anonymous ItemListener for image3. After the cursorPressed method, the pattern from previous listeners shows that the next overridden methods are cursorReleased and cursorRightClicked. The snippet ends right after an @Override annotation, so the next line should be the method signature for cursorReleased.", "reasoning_model_answer": "public void cursorReleased(ContentItem item, long id, float x, float y, float pressure) {", "assistant_with_reasoning": "\nThe code is defining an anonymous ItemListener for image3. After the cursorPressed method, the pattern from previous listeners shows that the next overridden methods are cursorReleased and cursorRightClicked. The snippet ends right after an @Override annotation, so the next line should be the method signature for cursorReleased.\n\npublic void cursorReleased(ContentItem item, long id, float x, float y, float pressure) {", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.114, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 8918, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "public void cursorReleased(ContentItem item, long id, float x, float y, float pressure) {", "score": 0.81, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "using System.Xml.Serialization;\nusing System.Collections;\nusing System;\nusing umbraco.BusinessLogic.Utils;\nusing System.Xml.Schema;\nusing umbraco.interfaces;\nusing System.Collections.Generic;\nusing System.Web.Script.Serialization;\nusing System.Text;\nusing umbraco.businesslogic.Utils;\nusing umbraco.BasePages;\nusing Umbraco.Core.IO;\n\nnamespace umbraco.cms.presentation.Trees\n{\n\n\tpublic enum SerializedTreeType\n\t{\n\t\tXmlTree,\n\t\tJSONTree,\n\t\tJsTree\n\t}\n\n\t/// \n\t/// Used for serializing data to XML as the data structure for the JavaScript tree\n\t/// \n\t[XmlRoot(ElementName = \"tree\", IsNullable = false), Serializable]\n\tpublic class XmlTree\n\t{\n\n\t\tpublic XmlTree()\n\t\t{\n\t\t\t//set to the XTree provider by default.\n\t\t\t//m_TreeType = SerializedTreeType.XmlTree;\n\t\t\t//m_TreeType = SerializedTreeType.JSONTree;\t\t\t\n\t\t\tm_TreeType = SerializedTreeType.JsTree;\n\n\t\t\tInit();\n\t\t}\n\n\t\t/// \n\t\t/// Use this constructor to force a tree provider to be used\n\t\t/// \n\t\t/// \n\t\tpublic XmlTree(SerializedTreeType treeType)\n\t\t{\n\t\t\tm_TreeType = treeType;\n\t\t\tInit();\n\t\t}\n\n\t\tprivate void Init()\n\t\t{\n m_JSSerializer = new JSONSerializer { MaxJsonLength = int.MaxValue };\n\n\t\t\tswitch (m_TreeType)\n\t\t\t{\n\t\t\t\tcase SerializedTreeType.XmlTree:\n\t\t\t\t\tbreak;\n\t\t\t\tcase SerializedTreeType.JSONTree:\n\t\t\t\t\tm_JSSerializer.RegisterConverters(new List() \n\t\t\t\t\t{ \n\t\t\t\t\t\tnew JSONTreeConverter(),\n\t\t\t\t\t\tnew JSONTreeNodeConverter()\n\t\t\t\t\t});\n\t\t\t\t\tbreak;\n\t\t\t\tcase SerializedTreeType.JsTree:\n\t\t\t\t\tm_JSSerializer.RegisterConverters(new List() \n\t\t\t\t\t{ \t\n\t\t\t\t\t\tnew JsTreeNodeConverter()\n\t\t\t\t\t});\n\t\t\t\t\tbreak;\n\t\t\t}\n\n\n\t\t}\n\n\t\tprivate JSONSerializer m_JSSerializer;\n\t\tprivate SerializedTreeType m_TreeType;\n\n\t\t/// \n\t\t/// Returns the string representation of the tree structure depending on the SerializedTreeType\n\t\t/// specified. \n\t\t/// \n\t\t/// \n\t\tpublic override string ToString()\n\t\t{\n\t\t\treturn ToString(m_TreeType);\n\t\t}\n\n\t\tpublic string ToString(SerializedTreeType type)\n\t\t{\n\t\t\tswitch (type)\n\t\t\t{\n\t\t\t\tcase SerializedTreeType.XmlTree:\n\t\t\t\t\treturn SerializableData.Serialize(this, typeof(XmlTree));\n\t\t\t\tcase SerializedTreeType.JsTree:\n\t\t\t\t\treturn m_JSSerializer.Serialize(this.treeCollection);\n\t\t\t\tcase SerializedTreeType.JSONTree:\n\t\t\t\t\treturn m_JSSerializer.Serialize(this);\n\t\t\t}\n\t\t\treturn \"\";\n\t\t}\n\n\t\tpublic void Add(XmlTreeNode obj)\n\t\t{\n\t\t\ttreeCollection.Add(obj);\n\t\t}\n\n\t\t[XmlIgnore]\n\t\tpublic XmlTreeNode this[int index]\n\t\t{\n\t\t\tget { return (XmlTreeNode)treeCollection[index]; }\n\t\t}\n\n\t\t[XmlIgnore]\n\t\tpublic int Count\n\t\t{\n\t\t\tget { return treeCollection.Count; }\n\t\t}\n\n\t\tpublic void Clear()\n\t\t{\n\t\t\ttreeCollection.Clear();\n\t\t}\n\n\t\tpublic XmlTreeNode Remove(int index)\n\t\t{\n\t\t\tXmlTreeNode obj = treeCollection[index];\n\t\t\ttreeCollection.Remove(obj);\n\t\t\treturn obj;\n\t\t}\n\n\t\tpublic void Remove(XmlTreeNode obj)\n\t\t{\n\t\t\ttreeCollection.Remove(obj);\n\t\t}\n\n\n\t\tprivate List __treeCollection;\n\n\t\t[XmlElement(Type = typeof(XmlTreeNode), ElementName = \"tree\", IsNullable = false, Form = XmlSchemaForm.Qualified)]\n\t\tpublic List treeCollection\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\tif (__treeCollection == null) __treeCollection = new List();\n\t\t\t\treturn __treeCollection;\n\t\t\t}\n\t\t\tset { __treeCollection = value; }\n\t\t}\n\n [System.Runtime.InteropServices.DispIdAttribute(-4)]\n public IEnumerator GetEnumerator()\n {\n return (treeCollection as IEnumerable).GetEnumerator();\n }\n\n }\n\n\t/// \n\t/// Used for serializing data to XML as the data structure for the JavaScript tree\n\t/// \n\t[Serializable]\n\tpublic class XmlTreeNode : IXmlSerializable\n\t{\n\n\t\tprivate XmlTreeNode()\n\t\t{\n\t\t\tm_nodeStyle = new NodeStyle();\n\t\t}\n\n\t\t/// \n\t\t/// creates a new XmlTreeNode with the default parameters from the BaseTree\n\t\t/// \n\t\t/// \n\t\t/// \n\t\tpublic static XmlTreeNode Create(BaseTree bTree)\n\t\t{\n\t\t\tXmlTreeNode xNode = new XmlTreeNode();\n\t\t\txNode.Menu = bTree.AllowedActions.FindAll(delegate(IAction a) { return true; }); //return a duplicate copy of the list\n\t\t\txNode.NodeType = bTree.TreeAlias;\n\t\t\txNode.Source = string.Empty;\n\t\t\txNode.IsRoot = false;\n\t\t\t//generally the tree type and node type are the same but in some cased they are not.\n\t\t\txNode.m_treeType = bTree.TreeAlias;\n\t\t\treturn xNode;\n\t\t}\n\n\t\t/// \n\t\t/// creates a new XmlTreeNode with the default parameters for the BaseTree root node\n\t\t/// \n\t\t/// \n\t\t/// \n\t\tpublic static XmlTreeNode CreateRoot(BaseTree bTree)\n\t\t{\n\t\t\tXmlTreeNode xNode = new XmlTreeNode();\n\t\t\txNode.NodeID = bTree.StartNodeID.ToString();\n\t\t\txNode.Source = bTree.GetTreeServiceUrl();\n\t\t\txNode.Menu = bTree.RootNodeActions.FindAll(delegate(IAction a) { return true; }); //return a duplicate copy of the list\n\t\t\txNode.NodeType = bTree.TreeAlias;\n\t\t\txNode.Text = BaseTree.GetTreeHeader(bTree.TreeAlias);\n\t\t\t\n // By default the action from the trees.config will be used, if none is specified then the apps dashboard will be used.\n var appTreeItem = umbraco.BusinessLogic.ApplicationTree.getByAlias(bTree.TreeAlias);\n xNode.Action = appTreeItem == null || String.IsNullOrEmpty(appTreeItem.Action) ? \"javascript:\" + ClientTools.Scripts.OpenDashboard(bTree.app) : \"javascript:\" + appTreeItem.Action;\n\t\t\t\n xNode.IsRoot = true;\n\t\t\t//generally the tree type and node type are the same but in some cased they are not.\n\t\t\txNode.m_treeType = bTree.TreeAlias;\n\t\t\treturn xNode;\n\t\t}\n\n\t\tprivate NodeStyle m_nodeStyle;\n\n\t\tprivate bool? m_notPublished;\n\t\tprivate bool? m_isProtected;\n\t\tprivate List m_menu;\n\t\tprivate string m_text;\n\t\tprivate string m_action;\n\t\t[Obsolete(\"This is never used. From version 3 and below probably\")]\n\t\tprivate string m_rootSrc;\n\t\tprivate string m_src;\n\t\tprivate string m_iconClass = \"\";\n\t\tprivate string m_icon;\n\t\tprivate string m_openIcon;\n\t\tprivate string m_nodeType;\n\t\tprivate string m_nodeID;\n\t\tprivate string m_treeType;\n\n\t\t/// \n\t\t/// Set to true when a node is created with CreateRootNode\n\t\t/// \n\t\tinternal bool IsRoot { get; private set; }\n\n\t\t/// \n\t\t/// Generally the tree type and node type are the same but in some cased they are not so\n\t\t/// we need to store the tree type too which is read only.\n\t\t/// \n\t\tpublic string TreeType\n\t\t{\n\t\t\tget { return m_treeType; }\n\t\t\tinternal set { m_treeType = value; }\n\t\t}\n\n public bool HasChildren\n {\n get\n {\n return m_HasChildren ?? !string.IsNullOrEmpty(this.Source); //defaults to true if source is specified\n }\n set\n {\n m_HasChildren = value;\n }\n }\n private bool? m_HasChildren = null;\n\n\t\tpublic string NodeID\n\t\t{\n\t\t\tget { return m_nodeID; }\n\t\t\tset { m_nodeID = value; }\n\t\t}\n\n\t\t/// \n\t\t/// The tree node text\n\t\t/// \n\t\tpublic string Text\n\t\t{\n\t\t\tget { return m_text; }\n\t\t\tset { m_text = value; }\n\t\t}\n\n\t\t/// \n\t\t/// The CSS class of the icon to use for the node\n\t\t/// \n\t\tpublic string IconClass\n\t\t{\n\t\t\tget { return m_iconClass; }\n\t\t\tset { m_iconClass = value; }\n\t\t}\n\n\t\t/// \n\t\t/// The JavaScript action for the node\n\t\t/// \n\t\tpublic string Action\n\t\t{\n\t\t\tget { return m_action; }\n\t\t\tset { m_action = value; }\n\t\t}\n\n\t\t/// \n\t\t/// A string of letters representing actions for the context menu\n\t\t/// ", "answers": ["\t\tpublic List Menu"], "length": 842, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "6fd174e1-c961-4d78-a615-5110e9ddbf9b", "reasoning": "The comment just before the placeholder describes a string of letters representing actions for the context menu. In the class, the corresponding field is 'm_menu' of type List. The next code line should declare the public property exposing this field, i.e., the property header for Menu.", "reasoning_model_answer": "public List Menu", "assistant_with_reasoning": "\nThe comment just before the placeholder describes a string of letters representing actions for the context menu. In the class, the corresponding field is 'm_menu' of type List. The next code line should declare the public property exposing this field, i.e., the property header for Menu.\n\npublic List Menu", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.187, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 7610, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "public List Menu", "score": 0.96, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Collections.Generic;\nusing System.Collections.Immutable;\nusing System.IO;\nusing System.Linq;\nusing System.Reflection.Metadata;\nusing System.Reflection.Metadata.Ecma335;\nusing System.Reflection.PortableExecutable;\nusing Microsoft.CodeAnalysis.CodeGen;\nusing Microsoft.CodeAnalysis.CSharp.Symbols;\nusing Microsoft.CodeAnalysis.CSharp.Test.Utilities;\nusing Microsoft.CodeAnalysis.ExpressionEvaluator;\nusing Microsoft.CodeAnalysis.Test.Utilities;\nusing Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation;\nusing Microsoft.DiaSymReader;\nusing Roslyn.Test.PdbUtilities;\nusing Roslyn.Test.Utilities;\nusing Roslyn.Utilities;\nusing Xunit;\n\nnamespace Microsoft.CodeAnalysis.CSharp.UnitTests\n{\n public class UsingDebugInfoTests : ExpressionCompilerTestBase\n {\n #region Grouped import strings \n\n [Fact]\n public void SimplestCase()\n {\n var source = @\"\nusing System;\n\nclass C\n{\n void M()\n {\n }\n}\n\";\n var comp = CreateCompilationWithMscorlib(source);\n comp.GetDiagnostics().Where(d => d.Severity > DiagnosticSeverity.Info).Verify();\n\n var importStrings = GetGroupedImportStrings(comp, \"M\");\n Assert.Equal(\"USystem\", importStrings.Single().Single());\n }\n\n [Fact]\n public void NestedNamespaces()\n {\n var source = @\"\nusing System;\n\nnamespace A\n{\n using System.IO;\n using System.Text;\n\n class C\n {\n void M()\n {\n }\n }\n}\n\";\n var comp = CreateCompilationWithMscorlib(source);\n comp.GetDiagnostics().Where(d => d.Severity > DiagnosticSeverity.Info).Verify();\n\n var importStrings = GetGroupedImportStrings(comp, \"M\");\n Assert.Equal(2, importStrings.Length);\n AssertEx.Equal(importStrings[0], new[] { \"USystem.IO\", \"USystem.Text\" });\n AssertEx.Equal(importStrings[1], new[] { \"USystem\" });\n }\n\n [Fact]\n public void Forward()\n {\n var source = @\"\nusing System;\n\nnamespace A\n{\n using System.IO;\n using System.Text;\n\n class C\n {\n // One of these methods will forward to the other since they're adjacent.\n void M1() { }\n void M2() { }\n }\n}\n\";\n var comp = CreateCompilationWithMscorlib(source);\n comp.GetDiagnostics().Where(d => d.Severity > DiagnosticSeverity.Info).Verify();\n\n var importStrings1 = GetGroupedImportStrings(comp, \"M1\");\n Assert.Equal(2, importStrings1.Length);\n AssertEx.Equal(importStrings1[0], new[] { \"USystem.IO\", \"USystem.Text\" });\n AssertEx.Equal(importStrings1[1], new[] { \"USystem\" });\n\n var importStrings2 = GetGroupedImportStrings(comp, \"M2\");\n Assert.Equal(2, importStrings2.Length);\n AssertEx.Equal(importStrings2[0], importStrings1[0]);\n AssertEx.Equal(importStrings2[1], importStrings1[1]);\n }\n\n [Fact]\n public void ImportKinds()\n {\n var source = @\"\nextern alias A;\nusing S = System;\n\nnamespace B\n{\n using F = S.IO.File;\n using System.Text;\n\n class C\n {\n void M()\n {\n }\n }\n}\n\";\n var aliasedRef = new CSharpCompilationReference(CreateCompilation(\"\", assemblyName: \"Lib\"), aliases: ImmutableArray.Create(\"A\"));\n var comp = CreateCompilationWithMscorlib(source, new[] { aliasedRef });\n comp.GetDiagnostics().Where(d => d.Severity > DiagnosticSeverity.Info).Verify();\n\n ImmutableArray externAliasStrings;\n var importStrings = GetGroupedImportStrings(comp, \"M\", out externAliasStrings);\n Assert.Equal(2, importStrings.Length);\n AssertEx.Equal(importStrings[0], new[] { \"USystem.Text\", \"AF TSystem.IO.File, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089\" });\n AssertEx.Equal(importStrings[1], new[] { \"XA\", \"AS USystem\" });\n Assert.Equal(\"ZA Lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null\", externAliasStrings.Single());\n }\n\n [WorkItem(1084059)]\n [Fact]\n public void ImportKinds_StaticType()\n {\n var libSource = @\"\nnamespace N\n{\n public static class Static\n {\n }\n}\n\";\n\n var source = @\"\nextern alias A;\nusing static System.Math;\n\nnamespace B\n{\n using static A::N.Static;\n\n class C\n {\n void M()\n {\n }\n }\n}\n\";\n var aliasedRef = new CSharpCompilationReference(CreateCompilation(libSource, assemblyName: \"Lib\"), aliases: ImmutableArray.Create(\"A\"));\n var comp = CreateCompilationWithMscorlib(source, new[] { aliasedRef });\n comp.GetDiagnostics().Where(d => d.Severity > DiagnosticSeverity.Info).Verify();\n\n ImmutableArray externAliasStrings;\n var importStrings = GetGroupedImportStrings(comp, \"M\", out externAliasStrings);\n Assert.Equal(2, importStrings.Length);\n AssertEx.Equal(importStrings[0], new[] { \"TN.Static, Lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null\" });\n AssertEx.Equal(importStrings[1], new[] { \"XA\", \"TSystem.Math, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089\" });\n Assert.Equal(\"ZA Lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null\", externAliasStrings.Single());\n }\n\n [Fact]\n public void ForwardToModule()\n {\n var source = @\"\nextern alias A;\n\nnamespace B\n{\n using System;\n\n class C\n {\n void M1()\n {\n }\n }\n}\n\nnamespace D\n{\n using System.Text; // Different using to prevent normal forwarding.\n\n class E\n {\n void M2()\n {\n }\n }\n}\n\";\n var aliasedRef = new CSharpCompilationReference(CreateCompilation(\"\", assemblyName: \"Lib\"), aliases: ImmutableArray.Create(\"A\"));\n var comp = CreateCompilationWithMscorlib(source, new[] { aliasedRef });\n comp.GetDiagnostics().Where(d => d.Severity > DiagnosticSeverity.Info).Verify();\n\n ImmutableArray externAliasStrings1;\n var importStrings1 = GetGroupedImportStrings(comp, \"M1\", out externAliasStrings1);\n Assert.Equal(2, importStrings1.Length);\n AssertEx.Equal(\"USystem\", importStrings1[0].Single());\n AssertEx.Equal(\"XA\", importStrings1[1].Single());\n Assert.Equal(\"ZA Lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null\", externAliasStrings1.Single());\n\n ImmutableArray externAliasStrings2;\n var importStrings2 = GetGroupedImportStrings(comp, \"M2\", out externAliasStrings2);\n Assert.Equal(2, importStrings2.Length);\n AssertEx.Equal(\"USystem.Text\", importStrings2[0].Single());\n AssertEx.Equal(importStrings1[1].Single(), importStrings2[1].Single());\n Assert.Equal(externAliasStrings1.Single(), externAliasStrings2.Single());\n }\n\n private static ImmutableArray> GetGroupedImportStrings(Compilation compilation, string methodName)\n {\n ImmutableArray externAliasStrings;\n ImmutableArray> result = GetGroupedImportStrings(compilation, methodName, out externAliasStrings);\n Assert.Equal(0, externAliasStrings.Length);\n return result;\n }\n\n private static ImmutableArray> GetGroupedImportStrings(Compilation compilation, string methodName, out ImmutableArray externAliasStrings)\n {\n Assert.NotNull(compilation);\n Assert.NotNull(methodName);\n\n using (var exebits = new MemoryStream())\n {\n using (var pdbbits = new MemoryStream())\n {\n compilation.Emit(exebits, pdbbits);\n\n exebits.Position = 0;\n using (var module = new PEModule(new PEReader(exebits, PEStreamOptions.LeaveOpen), metadataOpt: IntPtr.Zero, metadataSizeOpt: 0))\n {\n var metadataReader = module.MetadataReader;\n MethodDefinitionHandle methodHandle = metadataReader.MethodDefinitions.Single(mh => metadataReader.GetString(metadataReader.GetMethodDefinition(mh).Name) == methodName);\n int methodToken = metadataReader.GetToken(methodHandle);\n\n // Create a SymReader, rather than a raw COM object, because\n // SymReader implements ISymUnmanagedReader3 and the COM object\n // might not.\n pdbbits.Position = 0;\n using (var reader = new SymReader(pdbbits.ToArray()))\n {\n return reader.GetCSharpGroupedImportStrings(methodToken, methodVersion: 1, externAliasStrings: out externAliasStrings);\n }\n }\n }\n }\n }\n\n #endregion Grouped import strings \n\n #region Invalid PDBs\n\n [Fact]\n public void BadPdb_ForwardChain()\n {\n const int methodVersion = 1;\n const int methodToken1 = 0x600057a; // Forwards to 2\n const int methodToken2 = 0x600055d; // Forwards to 3\n const int methodToken3 = 0x6000540; // Has a using\n const string importString = \"USystem\";\n\n ISymUnmanagedReader reader = new MockSymUnmanagedReader(new Dictionary\n {\n { methodToken1, new MethodDebugInfoBytes.Builder().AddForward(methodToken2).Build() },\n { methodToken2, new MethodDebugInfoBytes.Builder().AddForward(methodToken3).Build() },\n { methodToken3, new MethodDebugInfoBytes.Builder(new [] { new [] { importString } }).Build() },\n }.ToImmutableDictionary());\n\n ImmutableArray externAliasStrings;\n var importStrings = reader.GetCSharpGroupedImportStrings(methodToken1, methodVersion, out externAliasStrings);\n Assert.True(importStrings.IsDefault);", "answers": [" Assert.True(externAliasStrings.IsDefault);"], "length": 782, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "fa4bc9e1-4f7f-4e88-b977-78fe2edda279", "reasoning": "The test BadPdb_ForwardChain creates a mock reader and calls GetCSharpGroupedImportStrings, then asserts that the returned importStrings is default because the PDB is malformed. The next logical assertion is to verify that the out parameter externAliasStrings is also default (no extern alias strings). Therefore the next line should assert externAliasStrings.IsDefault.", "reasoning_model_answer": "Assert.True(externAliasStrings.IsDefault);", "assistant_with_reasoning": "\nThe test BadPdb_ForwardChain creates a mock reader and calls GetCSharpGroupedImportStrings, then asserts that the returned importStrings is default because the PDB is malformed. The next logical assertion is to verify that the out parameter externAliasStrings is also default (no extern alias strings). Therefore the next line should assert externAliasStrings.IsDefault.\n\nAssert.True(externAliasStrings.IsDefault);", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.493, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 10451, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "Assert.True(externAliasStrings.IsDefault);", "score": 0.88, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "# vim: tabstop=4 shiftwidth=4 softtabstop=4\n\n# Copyright 2011 OpenStack Foundation\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nimport functools\nimport itertools\nimport socket\nimport ssl\nimport time\nimport uuid\n\nimport eventlet\nimport greenlet\nimport kombu\nimport kombu.connection\nimport kombu.entity\nimport kombu.messaging\nfrom oslo.config import cfg\n\nfrom heat.openstack.common import excutils\nfrom heat.openstack.common.gettextutils import _ # noqa\nfrom heat.openstack.common import network_utils\nfrom heat.openstack.common.rpc import amqp as rpc_amqp\nfrom heat.openstack.common.rpc import common as rpc_common\nfrom heat.openstack.common import sslutils\n\nkombu_opts = [\n cfg.StrOpt('kombu_ssl_version',\n default='',\n help='SSL version to use (valid only if SSL enabled). '\n 'valid values are TLSv1, SSLv23 and SSLv3. SSLv2 may '\n 'be available on some distributions'\n ),\n cfg.StrOpt('kombu_ssl_keyfile',\n default='',\n help='SSL key file (valid only if SSL enabled)'),\n cfg.StrOpt('kombu_ssl_certfile',\n default='',\n help='SSL cert file (valid only if SSL enabled)'),\n cfg.StrOpt('kombu_ssl_ca_certs',\n default='',\n help=('SSL certification authority file '\n '(valid only if SSL enabled)')),\n cfg.StrOpt('rabbit_host',\n default='localhost',\n help='The RabbitMQ broker address where a single node is used'),\n cfg.IntOpt('rabbit_port',\n default=5672,\n help='The RabbitMQ broker port where a single node is used'),\n cfg.ListOpt('rabbit_hosts',\n default=['$rabbit_host:$rabbit_port'],\n help='RabbitMQ HA cluster host:port pairs'),\n cfg.BoolOpt('rabbit_use_ssl',\n default=False,\n help='connect over SSL for RabbitMQ'),\n cfg.StrOpt('rabbit_userid',\n default='guest',\n help='the RabbitMQ userid'),\n cfg.StrOpt('rabbit_password',\n default='guest',\n help='the RabbitMQ password',\n secret=True),\n cfg.StrOpt('rabbit_virtual_host',\n default='/',\n help='the RabbitMQ virtual host'),\n cfg.IntOpt('rabbit_retry_interval',\n default=1,\n help='how frequently to retry connecting with RabbitMQ'),\n cfg.IntOpt('rabbit_retry_backoff',\n default=2,\n help='how long to backoff for between retries when connecting '\n 'to RabbitMQ'),\n cfg.IntOpt('rabbit_max_retries',\n default=0,\n help='maximum retries with trying to connect to RabbitMQ '\n '(the default of 0 implies an infinite retry count)'),\n cfg.BoolOpt('rabbit_ha_queues',\n default=False,\n help='use H/A queues in RabbitMQ (x-ha-policy: all).'\n 'You need to wipe RabbitMQ database when '\n 'changing this option.'),\n\n]\n\ncfg.CONF.register_opts(kombu_opts)\n\nLOG = rpc_common.LOG\n\n\ndef _get_queue_arguments(conf):\n \"\"\"Construct the arguments for declaring a queue.\n\n If the rabbit_ha_queues option is set, we declare a mirrored queue\n as described here:\n\n http://www.rabbitmq.com/ha.html\n\n Setting x-ha-policy to all means that the queue will be mirrored\n to all nodes in the cluster.\n \"\"\"\n return {'x-ha-policy': 'all'} if conf.rabbit_ha_queues else {}\n\n\nclass ConsumerBase(object):\n \"\"\"Consumer base class.\"\"\"\n\n def __init__(self, channel, callback, tag, **kwargs):\n \"\"\"Declare a queue on an amqp channel.\n\n 'channel' is the amqp channel to use\n 'callback' is the callback to call when messages are received\n 'tag' is a unique ID for the consumer on the channel\n\n queue name, exchange name, and other kombu options are\n passed in here as a dictionary.\n \"\"\"\n self.callback = callback\n self.tag = str(tag)\n self.kwargs = kwargs\n self.queue = None\n self.ack_on_error = kwargs.get('ack_on_error', True)\n self.reconnect(channel)\n\n def reconnect(self, channel):\n \"\"\"Re-declare the queue after a rabbit reconnect.\"\"\"\n self.channel = channel\n self.kwargs['channel'] = channel\n self.queue = kombu.entity.Queue(**self.kwargs)\n self.queue.declare()\n\n def _callback_handler(self, message, callback):\n \"\"\"Call callback with deserialized message.\n\n Messages that are processed without exception are ack'ed.\n\n If the message processing generates an exception, it will be\n ack'ed if ack_on_error=True. Otherwise it will be .requeue()'ed.\n \"\"\"\n\n try:\n msg = rpc_common.deserialize_msg(message.payload)\n callback(msg)\n except Exception:\n if self.ack_on_error:\n LOG.exception(_(\"Failed to process message\"\n \" ... skipping it.\"))\n message.ack()\n else:\n LOG.exception(_(\"Failed to process message\"\n \" ... will requeue.\"))\n message.requeue()\n else:\n message.ack()\n\n def consume(self, *args, **kwargs):\n \"\"\"Actually declare the consumer on the amqp channel. This will\n start the flow of messages from the queue. Using the\n Connection.iterconsume() iterator will process the messages,\n calling the appropriate callback.\n\n If a callback is specified in kwargs, use that. Otherwise,\n use the callback passed during __init__()\n\n If kwargs['nowait'] is True, then this call will block until\n a message is read.\n\n \"\"\"\n\n options = {'consumer_tag': self.tag}\n options['nowait'] = kwargs.get('nowait', False)\n callback = kwargs.get('callback', self.callback)\n if not callback:\n raise ValueError(\"No callback defined\")\n\n def _callback(raw_message):\n message = self.channel.message_to_python(raw_message)\n self._callback_handler(message, callback)\n\n self.queue.consume(*args, callback=_callback, **options)\n\n def cancel(self):\n \"\"\"Cancel the consuming from the queue, if it has started.\"\"\"\n try:\n self.queue.cancel(self.tag)\n except KeyError as e:\n # NOTE(comstud): Kludge to get around a amqplib bug\n if str(e) != \"u'%s'\" % self.tag:\n raise\n self.queue = None", "answers": ["class DirectConsumer(ConsumerBase):"], "length": 694, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "d6f0913c-7d88-47aa-9da7-9ae09ae7cd93", "reasoning": "The code ends the cancel() method of ConsumerBase with 'self.queue = None'. The next logical step in this module is to define the concrete Consumer class that inherits from ConsumerBase. Therefore the next line should start a new class definition at the top indentation level.", "reasoning_model_answer": "class Consumer(ConsumerBase):", "assistant_with_reasoning": "\nThe code ends the cancel() method of ConsumerBase with 'self.queue = None'. The next logical step in this module is to define the concrete Consumer class that inherits from ConsumerBase. Therefore the next line should start a new class definition at the top indentation level.\n\nclass Consumer(ConsumerBase):", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.676, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 7239, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "class Consumer(ConsumerBase):", "score": 0.91, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "# Mantid Repository : https://github.com/mantidproject/mantid\n#\n# Copyright © 2018 ISIS Rutherford Appleton Laboratory UKRI,\n# NScD Oak Ridge National Laboratory, European Spallation Source\n# & Institut Laue - Langevin\n# SPDX - License - Identifier: GPL - 3.0 +\n#\nfrom __future__ import (absolute_import, division, print_function)\n\nimport datetime\nimport unittest\n\nimport matplotlib\nimport numpy as np\n\nimport mantid.api\nimport mantid.plots.helperfunctions as funcs\nfrom mantid.py3compat.mock import Mock\nfrom mantid.kernel import config\nfrom mantid.plots.utility import MantidAxType\nfrom mantid.simpleapi import AddTimeSeriesLog, ConjoinWorkspaces, CreateMDHistoWorkspace, CreateSampleWorkspace, \\\n CreateSingleValuedWorkspace, CreateWorkspace, DeleteWorkspace\n\nmatplotlib.use('AGG')\n\n\ndef add_workspace_with_data(func):\n def wrapper(self):\n dataX = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]\n dataY = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]\n dataE = dataY\n dX = dataY\n\n ws = CreateWorkspace(DataX=dataX, DataY=dataY, DataE=dataE, NSpec=4, UnitX=\"Wavelength\", Dx=dX)\n return func(self, ws)\n\n return wrapper\n\n\ndef add_md_workspace_with_data(dimensions=2):\n def function_wrapper(func):\n def wrapper(self):\n if dimensions == 2:\n S = range(0, 100)\n ERR = range(0, 100)\n mdws = CreateMDHistoWorkspace(Dimensionality=2, Extents='-3,3,-10,10', SignalInput=S, ErrorInput=ERR,\n NumberOfBins='10,10', Names='Dim1,Dim2',\n Units='MomentumTransfer,EnergyTransfer')\n else:\n S = range(0, 1000)\n ERR = range(0, 1000)\n mdws = CreateMDHistoWorkspace(Dimensionality=3, Extents='-3,3,-10,10,-20,20', SignalInput=S,\n ErrorInput=ERR,\n NumberOfBins='10,10,10', Names='Dim1,Dim2,Dim3',\n Units='MomentumTransfer,EnergyTransfer,EnergyTransfer')\n return func(self, mdws)\n\n return wrapper\n\n return function_wrapper\n\n\nclass HelperFunctionsTest(unittest.TestCase):\n\n @classmethod\n def setUpClass(cls):\n cls.g1da = config['graph1d.autodistribution']\n config['graph1d.autodistribution'] = 'On'\n cls.ws2d_histo = CreateWorkspace(DataX=[10, 20, 30, 10, 20, 30],\n DataY=[2, 3, 4, 5],\n DataE=[1, 2, 3, 4],\n NSpec=2,\n Distribution=True,\n UnitX='Wavelength',\n VerticalAxisUnit='DeltaE',\n VerticalAxisValues=[4, 6, 8],\n OutputWorkspace='ws2d_histo')\n cls.ws2d_point = CreateWorkspace(DataX=[1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4],\n DataY=[2] * 12,\n NSpec=3,\n OutputWorkspace='ws2d_point')\n cls.ws1d_point = CreateWorkspace(DataX=[1, 2],\n DataY=[1, 2],\n NSpec=1,\n Distribution=False,\n OutputWorkspace='ws1d_point')\n cls.ws2d_histo_rag = CreateWorkspace(DataX=[1, 2, 3, 4, 5, 2, 4, 6, 8, 10],\n DataY=[2] * 8,\n NSpec=2,\n VerticalAxisUnit='DeltaE',\n VerticalAxisValues=[5, 7, 9],\n OutputWorkspace='ws2d_histo_rag')\n cls.ws2d_point_rag = CreateWorkspace(DataX=[1, 2, 3, 4, 2, 4, 6, 8],\n DataY=[2] * 8,\n NSpec=2,\n OutputWorkspace='ws2d_point_rag')\n cls.ws_MD_2d = CreateMDHistoWorkspace(Dimensionality=3,\n Extents='-3,3,-10,10,-1,1',\n SignalInput=range(25),\n ErrorInput=range(25),\n NumberOfEvents=10 * np.ones(25),\n NumberOfBins='5,5,1',\n Names='Dim1,Dim2,Dim3',\n Units='MomentumTransfer,EnergyTransfer,Angstrom',\n OutputWorkspace='ws_MD_2d')\n cls.ws_MD_1d = CreateMDHistoWorkspace(Dimensionality=3,\n Extents='-3,3,-10,10,-1,1',\n SignalInput=range(5),\n ErrorInput=range(5),\n NumberOfEvents=10 * np.ones(5),\n NumberOfBins='1,5,1',\n Names='Dim1,Dim2,Dim3',\n Units='MomentumTransfer,EnergyTransfer,Angstrom',\n OutputWorkspace='ws_MD_1d')\n cls.ws2d_point_uneven = CreateWorkspace(DataX=[10, 20, 30],\n DataY=[1, 2, 3],\n NSpec=1,\n OutputWorkspace='ws2d_point_uneven')\n wp = CreateWorkspace(DataX=[15, 25, 35, 45], DataY=[1, 2, 3, 4], NSpec=1)\n ConjoinWorkspaces(cls.ws2d_point_uneven, wp, CheckOverlapping=False)\n cls.ws2d_point_uneven = mantid.mtd['ws2d_point_uneven']\n cls.ws2d_histo_uneven = CreateWorkspace(DataX=[10, 20, 30, 40],\n DataY=[1, 2, 3],\n NSpec=1,\n OutputWorkspace='ws2d_histo_uneven')\n wp = CreateWorkspace(DataX=[15, 25, 35, 45, 55], DataY=[1, 2, 3, 4], NSpec=1)\n ConjoinWorkspaces(cls.ws2d_histo_uneven, wp, CheckOverlapping=False)\n cls.ws2d_histo_uneven = mantid.mtd['ws2d_histo_uneven']\n newYAxis = mantid.api.NumericAxis.create(3)\n newYAxis.setValue(0, 10)\n newYAxis.setValue(1, 15)\n newYAxis.setValue(2, 25)\n cls.ws2d_histo_uneven.replaceAxis(1, newYAxis)\n AddTimeSeriesLog(cls.ws2d_histo, Name=\"my_log\", Time=\"2010-01-01T00:00:00\", Value=100)\n AddTimeSeriesLog(cls.ws2d_histo, Name=\"my_log\", Time=\"2010-01-01T00:30:00\", Value=15)\n AddTimeSeriesLog(cls.ws2d_histo, Name=\"my_log\", Time=\"2010-01-01T00:50:00\", Value=100.2)\n\n @classmethod\n def tearDownClass(cls):\n config['graph1d.autodistribution'] = cls.g1da\n DeleteWorkspace('ws2d_histo')\n DeleteWorkspace('ws2d_point')\n DeleteWorkspace('ws1d_point')\n DeleteWorkspace('ws_MD_2d')\n DeleteWorkspace('ws_MD_1d')\n DeleteWorkspace('ws2d_histo_rag')\n DeleteWorkspace('ws2d_point_rag')\n DeleteWorkspace('ws2d_point_uneven')\n DeleteWorkspace('ws2d_histo_uneven')\n\n def test_get_wksp_index_dist_and_label(self):\n # fail case\n self.assertRaises(RuntimeError, funcs.get_wksp_index_dist_and_label, self.ws2d_histo)\n # get info from a 2d workspace\n index, dist, kwargs = funcs.get_wksp_index_dist_and_label(self.ws2d_histo, specNum=2)\n self.assertEqual(index, 1)\n self.assertTrue(dist)\n self.assertEqual(kwargs['label'], 'ws2d_histo: spec 2')\n # get info from default spectrum in the 1d case\n index, dist, kwargs = funcs.get_wksp_index_dist_and_label(self.ws1d_point)\n self.assertEqual(index, 0)\n self.assertFalse(dist)\n self.assertEqual(kwargs['label'], 'ws1d_point: spec 1')\n\n def test_get_axes_labels(self):\n axs = funcs.get_axes_labels(self.ws2d_histo)\n self.assertEqual(axs, ('', 'Wavelength ($\\\\AA$)', 'Energy transfer ($meV$)'))\n\n def test_get_axes_label_2d_MDWS(self):\n axs = funcs.get_axes_labels(self.ws_MD_2d)\n # should get the first two dimension labels only\n self.assertEqual(axs, ('Intensity', 'Dim1 ($\\\\AA^{-1}$)', 'Dim2 (EnergyTransfer)'))\n\n def test_get_data_uneven_flag(self):\n flag, kwargs = funcs.get_data_uneven_flag(self.ws2d_histo_rag, axisaligned=True, other_kwarg=1)\n self.assertTrue(flag)\n self.assertEquals(kwargs, {'other_kwarg': 1})\n flag, kwargs = funcs.get_data_uneven_flag(self.ws2d_histo_rag, other_kwarg=2)\n self.assertFalse(flag)\n self.assertEquals(kwargs, {'other_kwarg': 2})\n flag, kwargs = funcs.get_data_uneven_flag(self.ws2d_histo_uneven, axisaligned=False, other_kwarg=3)\n self.assertTrue(flag)\n self.assertEquals(kwargs, {'other_kwarg': 3})\n\n def test_boundaries_from_points(self):\n centers = np.array([1., 2., 4., 8.])\n bounds = funcs.boundaries_from_points(centers)\n self.assertTrue(np.array_equal(bounds, np.array([0.5, 1.5, 3, 6, 10])))\n\n def test_points_from_boundaries(self):\n bounds = np.array([1., 3, 4, 10])\n centers = funcs.points_from_boundaries(bounds)\n self.assertTrue(np.array_equal(centers, np.array([2., 3.5, 7])))\n\n def test_get_spectrum(self):\n # get data divided by bin width\n x, y, dy, dx = funcs.get_spectrum(self.ws2d_histo, 1, False, withDy=True, withDx=True)\n self.assertTrue(np.array_equal(x, np.array([15., 25.])))\n self.assertTrue(np.array_equal(y, np.array([.4, .5])))\n self.assertTrue(np.array_equal(dy, np.array([.3, .4])))\n self.assertEqual(dx, None)\n # get data not divided by bin width\n x, y, dy, dx = funcs.get_spectrum(self.ws2d_histo, 0, True, withDy=True, withDx=True)\n self.assertTrue(np.array_equal(x, np.array([15., 25.])))\n self.assertTrue(np.array_equal(y, np.array([2, 3])))\n self.assertTrue(np.array_equal(dy, np.array([1, 2])))\n self.assertEqual(dx, None)\n # fail case - try to find spectrum out of range\n self.assertRaises(RuntimeError, funcs.get_spectrum, self.ws2d_histo, 10, True)\n\n def test_get_md_data2d_bin_bounds(self):\n x, y, data = funcs.get_md_data2d_bin_bounds(self.ws_MD_2d, mantid.api.MDNormalization.NoNormalization)\n # logger.error(str(coords))\n np.testing.assert_allclose(x, np.array([-3, -1.8, -0.6, 0.6, 1.8, 3]), atol=1e-10)\n np.testing.assert_allclose(y, np.array([-10, -6, -2, 2, 6, 10.]), atol=1e-10)\n np.testing.assert_allclose(data, np.arange(25).reshape(5, 5), atol=1e-10)\n\n def test_get_md_data2d_bin_centers(self):\n x, y, data = funcs.get_md_data2d_bin_centers(self.ws_MD_2d, mantid.api.MDNormalization.NumEventsNormalization)\n np.testing.assert_allclose(x, np.array([-2.4, -1.2, 0, 1.2, 2.4]), atol=1e-10)\n np.testing.assert_allclose(y, np.array([-8, -4, 0, 4, 8]), atol=1e-10)\n np.testing.assert_allclose(data, np.arange(25).reshape(5, 5) * 0.1, atol=1e-10)\n\n def test_get_md_data1d(self):\n coords, data, err = funcs.get_md_data1d(self.ws_MD_1d, mantid.api.MDNormalization.NumEventsNormalization)\n np.testing.assert_allclose(coords, np.array([-8, -4, 0, 4, 8]), atol=1e-10)\n\n def test_get_matrix_2d_data_rect(self):\n # contour from aligned point data\n x, y, z = funcs.get_matrix_2d_data(self.ws2d_point, True, histogram2D=False)\n np.testing.assert_allclose(x, np.array([[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]]))\n np.testing.assert_allclose(y, np.array([[1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3]]))\n # mesh from aligned point data\n x, y, z = funcs.get_matrix_2d_data(self.ws2d_point, True, histogram2D=True)\n np.testing.assert_allclose(x, np.array(\n [[0.5, 1.5, 2.5, 3.5, 4.5], [0.5, 1.5, 2.5, 3.5, 4.5], [0.5, 1.5, 2.5, 3.5, 4.5],\n [0.5, 1.5, 2.5, 3.5, 4.5]]))\n np.testing.assert_allclose(y, np.array(\n [[0.5, 0.5, 0.5, 0.5, 0.5], [1.5, 1.5, 1.5, 1.5, 1.5], [2.5, 2.5, 2.5, 2.5, 2.5],\n [3.5, 3.5, 3.5, 3.5, 3.5]]))\n # contour from aligned histo data\n x, y, z = funcs.get_matrix_2d_data(self.ws2d_histo, True, histogram2D=False)\n np.testing.assert_allclose(x, np.array([[15, 25], [15, 25]]))\n np.testing.assert_allclose(y, np.array([[5, 5], [7, 7]]))\n # mesh from aligned histo data", "answers": [" x, y, z = funcs.get_matrix_2d_data(self.ws2d_histo, True, histogram2D=True)"], "length": 838, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "a3b00cb2-b105-461b-8170-9af3a38a2f3d", "reasoning": "After the comment '# mesh from aligned histo data', the test should call the same helper function with the histogram workspace and histogram2D=True, mirroring the previous pattern for point data. The next line therefore invokes funcs.get_matrix_2d_data on self.ws2d_histo with the appropriate flags.", "reasoning_model_answer": "x, y, z = funcs.get_matrix_2d_data(self.ws2d_histo, True, histogram2D=True)", "assistant_with_reasoning": "\nAfter the comment '# mesh from aligned histo data', the test should call the same helper function with the histogram workspace and histogram2D=True, mirroring the previous pattern for point data. The next line therefore invokes funcs.get_matrix_2d_data on self.ws2d_histo with the appropriate flags.\n\nx, y, z = funcs.get_matrix_2d_data(self.ws2d_histo, True, histogram2D=True)", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.967, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 12923, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "x, y, z = funcs.get_matrix_2d_data(self.ws2d_histo, True, histogram2D=True)", "score": 0.95, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License. See License.txt in the project root for\n// license information.\n//\n// Code generated by Microsoft (R) AutoRest Code Generator.\n// Changes may cause incorrect behavior and will be lost if the code is\n// regenerated.\n\nnamespace Microsoft.Azure.Management.RecoveryServices.SiteRecovery\n{\n using Microsoft.Azure;\n using Microsoft.Azure.Management;\n using Microsoft.Azure.Management.RecoveryServices;\n using Microsoft.Rest;\n using Microsoft.Rest.Azure;\n using Models;\n using System.Threading;\n using System.Threading.Tasks;\n\n /// \n /// Extension methods for ReplicationStorageClassificationMappingsOperations.\n /// \n public static partial class ReplicationStorageClassificationMappingsOperationsExtensions\n {\n /// \n /// Gets the details of a storage classification mapping.\n /// \n /// \n /// Gets the details of the specified storage classification mapping.\n /// \n /// \n /// The operations group for this extension method.\n /// \n /// \n /// Fabric name.\n /// \n /// \n /// Storage classification name.\n /// \n /// \n /// Storage classification mapping name.\n /// \n public static StorageClassificationMapping Get(this IReplicationStorageClassificationMappingsOperations operations, string fabricName, string storageClassificationName, string storageClassificationMappingName)\n {\n return operations.GetAsync(fabricName, storageClassificationName, storageClassificationMappingName).GetAwaiter().GetResult();\n }\n\n /// \n /// Gets the details of a storage classification mapping.\n /// \n /// \n /// Gets the details of the specified storage classification mapping.\n /// \n /// \n /// The operations group for this extension method.\n /// \n /// \n /// Fabric name.\n /// \n /// \n /// Storage classification name.\n /// \n /// \n /// Storage classification mapping name.\n /// \n /// \n /// The cancellation token.\n /// \n public static async Task GetAsync(this IReplicationStorageClassificationMappingsOperations operations, string fabricName, string storageClassificationName, string storageClassificationMappingName, CancellationToken cancellationToken = default(CancellationToken))\n {\n using (var _result = await operations.GetWithHttpMessagesAsync(fabricName, storageClassificationName, storageClassificationMappingName, null, cancellationToken).ConfigureAwait(false))\n {\n return _result.Body;\n }\n }\n\n /// \n /// Create storage classification mapping.\n /// \n /// \n /// The operation to create a storage classification mapping.\n /// \n /// \n /// The operations group for this extension method.\n /// \n /// \n /// Fabric name.\n /// \n /// \n /// Storage classification name.\n /// \n /// \n /// Storage classification mapping name.\n /// \n /// \n /// Pairing input.\n /// \n public static StorageClassificationMapping Create(this IReplicationStorageClassificationMappingsOperations operations, string fabricName, string storageClassificationName, string storageClassificationMappingName, StorageClassificationMappingInput pairingInput)\n {\n return operations.CreateAsync(fabricName, storageClassificationName, storageClassificationMappingName, pairingInput).GetAwaiter().GetResult();\n }\n\n /// \n /// Create storage classification mapping.\n /// \n /// \n /// The operation to create a storage classification mapping.\n /// \n /// \n /// The operations group for this extension method.\n /// \n /// \n /// Fabric name.\n /// \n /// \n /// Storage classification name.\n /// \n /// \n /// Storage classification mapping name.\n /// \n /// \n /// Pairing input.\n /// \n /// \n /// The cancellation token.\n /// \n public static async Task CreateAsync(this IReplicationStorageClassificationMappingsOperations operations, string fabricName, string storageClassificationName, string storageClassificationMappingName, StorageClassificationMappingInput pairingInput, CancellationToken cancellationToken = default(CancellationToken))\n {\n using (var _result = await operations.CreateWithHttpMessagesAsync(fabricName, storageClassificationName, storageClassificationMappingName, pairingInput, null, cancellationToken).ConfigureAwait(false))\n {\n return _result.Body;\n }\n }\n\n /// \n /// Delete a storage classification mapping.\n /// \n /// \n /// The operation to delete a storage classification mapping.\n /// \n /// \n /// The operations group for this extension method.\n /// \n /// \n /// Fabric name.\n /// \n /// \n /// Storage classification name.\n /// \n /// \n /// Storage classification mapping name.\n /// \n public static void Delete(this IReplicationStorageClassificationMappingsOperations operations, string fabricName, string storageClassificationName, string storageClassificationMappingName)\n {\n operations.DeleteAsync(fabricName, storageClassificationName, storageClassificationMappingName).GetAwaiter().GetResult();\n }\n\n /// \n /// Delete a storage classification mapping.\n /// \n /// \n /// The operation to delete a storage classification mapping.\n /// \n /// \n /// The operations group for this extension method.\n /// \n /// \n /// Fabric name.\n /// \n /// \n /// Storage classification name.\n /// \n /// \n /// Storage classification mapping name.\n /// \n /// \n /// The cancellation token.\n /// \n public static async Task DeleteAsync(this IReplicationStorageClassificationMappingsOperations operations, string fabricName, string storageClassificationName, string storageClassificationMappingName, CancellationToken cancellationToken = default(CancellationToken))\n {\n (await operations.DeleteWithHttpMessagesAsync(fabricName, storageClassificationName, storageClassificationMappingName, null, cancellationToken).ConfigureAwait(false)).Dispose();\n }\n\n /// \n /// Gets the list of storage classification mappings objects under a storage.\n /// \n /// \n /// Lists the storage classification mappings for the fabric.\n /// \n /// \n /// The operations group for this extension method.\n /// \n /// \n /// Fabric name.\n /// \n /// \n /// Storage classfication name.\n /// \n public static IPage ListByReplicationStorageClassifications(this IReplicationStorageClassificationMappingsOperations operations, string fabricName, string storageClassificationName)\n {\n return operations.ListByReplicationStorageClassificationsAsync(fabricName, storageClassificationName).GetAwaiter().GetResult();\n }\n\n /// \n /// Gets the list of storage classification mappings objects under a storage.\n /// \n /// \n /// Lists the storage classification mappings for the fabric.\n /// \n /// \n /// The operations group for this extension method.\n /// \n /// \n /// Fabric name.\n /// \n /// \n /// Storage classfication name.\n /// \n /// \n /// The cancellation token.\n /// ", "answers": [" public static async Task> ListByReplicationStorageClassificationsAsync(this IReplicationStorageClassificationMappingsOperations operations, string fabricName, string storageClassificationName, CancellationToken cancellationToken = default(CancellationToken))"], "length": 808, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "111babd5-74b5-4c29-ba1e-1d1ba9de31e6", "reasoning": "The code defines a synchronous ListByReplicationStorageClassifications method that calls an async counterpart. The comment block just above ends with the cancellationToken param, so the next line should be the async method signature that includes the cancellation token with a default value, matching the pattern of other async methods in the file.", "reasoning_model_answer": "public static async Task> ListByReplicationStorageClassificationsAsync(this IReplicationStorageClassificationMappingsOperations operations, string fabricName, string storageClassificationName, CancellationToken cancellationToken = default(CancellationToken))", "assistant_with_reasoning": "\nThe code defines a synchronous ListByReplicationStorageClassifications method that calls an async counterpart. The comment block just above ends with the cancellationToken param, so the next line should be the async method signature that includes the cancellation token with a default value, matching the pattern of other async methods in the file.\n\npublic static async Task> ListByReplicationStorageClassificationsAsync(this IReplicationStorageClassificationMappingsOperations operations, string fabricName, string storageClassificationName, CancellationToken cancellationToken = default(CancellationToken))", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.758, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 10698, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "public static async Task> ListByReplicationStorageClassificationsAsync(this IReplicationStorageClassificationMappingsOperations operations, string fabricName, string storageClassificationName, CancellationToken cancellationToken = default(CancellationToken))", "score": 0.98, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "#!/usr/bin/python\n#======================================================================\n#\n# Project\t : hpp_IOStressTest\n# File \t\t : Libs/IOST_Testcase/IOST_WSetupTestcase.py\n# Date\t\t : Sep 27, 2016\n# Author\t : HuuHoang Nguyen\n# Contact\t : hhnguyen@apm.com\n# : hoangnh.hpp@gmail.com\n# License : MIT License\n# Copyright : 2016\n# Description: The hpp_IOStressTest is under the MIT License, a copy of license which may be found in LICENSE\n#\n#======================================================================\n\nimport io\nimport os\nimport re\nimport operator\nimport sys\nimport base64\nimport time\nfrom pprint import pprint\n\nfrom IOST_Basic import *\nfrom IOST_Config import *\nfrom IOST_Terminal import *\n\nimport gtk\nimport gtk.glade\nimport gobject\nimport pango\nimport vte\n\n#======================================================================\ntry:\n IOST_DBG_EN\n if IOST_DBG_EN:\n IOST_WSetupTestcase_DebugEnable =1\n IOST_WSetupTestcase_DebugLevel = IOST_DBG_L06\n else:\n IOST_WSetupTestcase_DebugEnable =0\n IOST_WSetupTestcase_DebugLevel = IOST_DBG_L01\nexcept:\n IOST_DBG_EN = False\n IOST_WSetupTestcase_DebugEnable =0\n IOST_WSetupTestcase_DebugLevel = IOST_DBG_L01\n\n#======================================================================\nclass IOST_WSetupTestcase():\n \"\"\"\n \"\"\"\n def __init__(self, glade_filename, window_name, object_name, builder=None ):\n \"\"\n self.IOST_WSetupTestcas_glade_filename = glade_filename\n self.IOST_WSetupTestcase_window = window_name\n self.IOST_WSetupTestcase_object = object_name\n \n if not builder:\n self.WRun_WSetupTestcase_Builder = gtk.Builder()\n self.WRun_WSetupTestcase_Builder.add_from_file(glade_filename)\n self.WRun_WSetupTestcase_Builder.connect_signals(self)\n else:\n self.WRun_WSetupTestcase_Builder = builder\n\n # self.IOST_Objs[window_name][window_name+object_name] = self.WRun_WSetupTestcase_Builder.get_object(window_name+object_name) \n \n #----------------------------------------------------------------------\n def WSetupTestcase_Get_Objs(self, window_name):\n \"\"\n # self.CreateObjs(self.IOST_Objs[window_name], self.WRun_WSetupTestcase_Builder, 2)\n\n self.CreateObjsDictFromDict(window_name, self.IOST_Objs[window_name], self.WRun_WSetupTestcase_Builder, 0)\n \n if IOST_WSetupTestcase_DebugEnable and 0:\n pprint(self.IOST_Objs[window_name])\n \n #----------------------------------------------------------------------\n def WSetupTestcase_Clear(self, window_name):\n \"\"\"\n \"\"\"\n self.IOST_Objs[window_name][\"_SelectAll_CB\"].set_active(False)\n self.IOST_Objs[window_name][\"_ResetAll_CB\"].set_active(False)\n for i in range(0, self.IOST_Objs[\"SetupTestcaseTemplate\"][\"TestcaseListDefault\"] ):\n # print \"At horizontal \", i\n # print window_name+\"_\"+str(i+1)+\"_Enable_CB\"\n self.IOST_Objs[window_name][\"_\"+str(i+1)+\"_Enable_CB\"].set_sensitive(False)\n self.IOST_Objs[window_name][\"_\"+str(i+1)+\"_Enable_CB\"].set_active(False)\n self.IOST_Objs[window_name][\"_\"+str(i+1)+\"_Cmd_TE\"].set_text(\"\")\n self.IOST_Objs[window_name][\"_\"+str(i+1)+\"_Description_TE\"].set_text(\"\")\n self.IOST_Objs[window_name][\"_\"+str(i+1)+\"_RunTimes_TE\"].set_text(\"\")\n self.IOST_Objs[window_name][\"_\"+str(i+1)+\"_ResetBoard_CB\"].set_active(False)\n self.IOST_Objs[window_name][\"_\"+str(i+1)+\"_ResetBoard_CB\"].set_sensitive(False)\n \n #----------------------------------------------------------------------\n def WSetupTestcase_SetCallback(self, window_name, object_name, number):\n \"\"\"\n \"\"\"\n # for i in range(0, self.IOST_Objs[\"SetupTestcaseTemplate\"][\"TestcaseNum\"]):\n self.IOST_Objs[window_name][\"_\"+str(number)+\"_Enable_CB\"].connect('toggled', \\\n self.WSetupTestcase_Enable_CB_Callback, \\\n self.IOST_Objs[window_name][\"_\"+str(number)+\"_Enable_CB\"], \\\n object_name, number)\n\n self.IOST_Objs[window_name][\"_\"+str(number)+\"_Cmd_TE\"].connect('focus-out-event', \\\n self.WSetupTestcase_CMD_TE_Callback, \\\n self.IOST_Objs[window_name][\"_\"+str(number)+\"_Cmd_TE\"], \\\n object_name, number, self.IOST_Objs[window_name][\"_\"+str(number)+\"_Enable_CB\"], \\\n self.IOST_Objs[window_name][\"_\"+str(number)+\"_ResetBoard_CB\"])\n\n self.IOST_Objs[window_name][\"_\"+str(number)+\"_Description_TE\"].connect('focus-out-event', \\\n self.WSetupTestcase_Description_TE_Callback, \\\n self.IOST_Objs[window_name][\"_\"+str(number)+\"_Description_TE\"], \\\n object_name, number, self.IOST_Objs[window_name][\"_\"+str(number)+\"_Enable_CB\"], \\\n self.IOST_Objs[window_name][\"_\"+str(number)+\"_ResetBoard_CB\"])\n\n self.IOST_Objs[window_name][\"_\"+str(number)+\"_RunTimes_TE\"].connect('focus-out-event', \\\n self.WSetupTestcase_RunTimes_TE_Callback, \\\n self.IOST_Objs[window_name][\"_\"+str(number)+\"_RunTimes_TE\"], \\\n object_name, number, self.IOST_Objs[window_name][\"_\"+str(number)+\"_Enable_CB\"], \\\n self.IOST_Objs[window_name][\"_\"+str(number)+\"_ResetBoard_CB\"])\n\n self.IOST_Objs[window_name][\"_\"+str(number)+\"_ResetBoard_CB\"].connect('toggled', \\\n self.WSetupTestcase_ResetBoard_CB_Callback, \n self.IOST_Objs[window_name][\"_\"+str(number)+\"_ResetBoard_CB\"], \n object_name, number)\n\n #----------------------------------------------------------------------\n def WSetupTestcase_Enable_CB_Callback(self, object, object_active, data=None, number=None):\n \"\"\n \n if number > self.IOST_Objs[\"SetupTestcaseTemplate\"][\"TestcaseNum\"]:\n data.append( self.IOST_Data[\"IP_N\"][1] )\n self.IOST_Objs[\"SetupTestcaseTemplate\"][\"TestcaseNum\"] +=1 \n self.IOST_Objs[\"SetupTestcaseTemplate\"][\"_\"+str(number)+\"_E_Testcase\"] =0 \n if IOST_WSetupTestcase_DebugEnable:\n iost_print(IOST_WSetupTestcase_DebugLevel, None, \"0-0-0-0-0-0-0-0-0\")\n iost_print(IOST_WSetupTestcase_DebugLevel, number, \"WSetupTestcase_Enable_CB -> number\") \n iost_print(IOST_WSetupTestcase_DebugLevel, self.IOST_Objs[\"SetupTestcaseTemplate\"][\"TestcaseNum\"], \"WSetupTestcase_Enable_CB -> numbTestcaseNumber\") \n iost_print(IOST_WSetupTestcase_DebugLevel, number, \"WSetupTestcase_Enable_CB -> TestcaseList\") \n \n\n Res = object_active.get_active()\n if Res:\n data[int(number)][\"Active\"] = 'Enable'\n else:\n data[int(number)][\"Active\"] = 'Disable'\n \n \n\n #----------------------------------------------------------------------\n def WSetupTestcase_CMD_TE_Callback(self, object, event, object_active, data=None, number=None, set_object_1=None, set_object_2=None):\n \"Callback function when CMD text entry of a testcase have changed\"\n \n #______________________________________________________________________\n try:\n self.IOST_Objs[\"SetupTestcaseTemplate\"][\"_\"+str(number)+\"_CMD_Testcase\"]\n except KeyError:\n self.IOST_Objs[\"SetupTestcaseTemplate\"][\"_\"+str(number)+\"_CMD_Testcase\"] = 0\n\n try:\n self.IOST_Objs[\"SetupTestcaseTemplate\"][\"_\"+str(number)+\"_DES_Testcase\"]\n except KeyError:\n self.IOST_Objs[\"SetupTestcaseTemplate\"][\"_\"+str(number)+\"_DES_Testcase\"] = 0\n\n try:\n self.IOST_Objs[\"SetupTestcaseTemplate\"][\"_\"+str(number)+\"_RT_Testcase\"]\n except KeyError:\n self.IOST_Objs[\"SetupTestcaseTemplate\"][\"_\"+str(number)+\"_RT_Testcase\"] = 0\n \n #______________________________________________________________________\n if IOST_WSetupTestcase_DebugEnable:\n iost_print(IOST_WSetupTestcase_DebugLevel, None, \"1-1-1-1-1-1-1-1-1\" ) \n iost_print(IOST_WSetupTestcase_DebugLevel, self.IOST_Objs[\"SetupTestcaseTemplate\"][\"TestcaseNum\"], \"WSetupTestcase_CMD_TE->TestcaseNumber\")\n\n test_segment = 0\n if number > self.IOST_Objs[\"SetupTestcaseTemplate\"][\"TestcaseNum\"]:\n test_segment = number - self.IOST_Objs[\"SetupTestcaseTemplate\"][\"TestcaseNum\"]\n for i in range(0, test_segment):\n data.append( self.IOST_Data[\"IP_N\"][1] )\n self.IOST_Objs[\"SetupTestcaseTemplate\"][\"TestcaseNum\"] +=1\n\n self.IOST_Objs[\"SetupTestcaseTemplate\"][\"_\"+str(number)+\"_CMD_Testcase\"] = 0\n \n #______________________________________________________________________\n if IOST_WSetupTestcase_DebugEnable:\n print \"number = \", number\n iost_print(IOST_WSetupTestcase_DebugLevel, number, \"WSetupTestcase_CMD_TE->number\")\n iost_print(IOST_WSetupTestcase_DebugLevel, self.IOST_Objs[\"SetupTestcaseTemplate\"][\"TestcaseNum\"], \"WSetupTestcase_CMD_TE->TestcaseNumber\")\n iost_print(IOST_WSetupTestcase_DebugLevel, self.IOST_Objs[\"SetupTestcaseTemplate\"][\"TestcaseList\"], \"WSetupTestcase_CMD_TE->TestcaseList\")\n \n #______________________________________________________________________\n text = object_active.get_text()\n\n if text and text.strip(): # string NOT empty\"\n set_object_1.set_sensitive(True)\n set_object_2.set_sensitive(True)\n data[number][\"Testcase\"] = text\n self.IOST_Objs[\"SetupTestcaseTemplate\"][\"_\"+str(number)+\"_CMD_Testcase\"] = 1\n \n #______________________________________________________________________\n else: # string empty\" \n self.IOST_Objs[\"SetupTestcaseTemplate\"][\"_\"+str(number)+\"_CMD_Testcase\"] = 0\n \n #______________________________________________________________________\n if ((self.IOST_Objs[\"SetupTestcaseTemplate\"][\"_\"+str(number)+\"_CMD_Testcase\"] == 1) and \n (self.IOST_Objs[\"SetupTestcaseTemplate\"][\"_\"+str(number)+\"_RT_Testcase\"] == 1)):\n print \"x1\"\n set_object_1.set_active(True)\n set_object_1.set_sensitive(True)\n data[number][\"Active\"] = 'Enable'\n\n elif ((self.IOST_Objs[\"SetupTestcaseTemplate\"][\"_\"+str(number)+\"_CMD_Testcase\"] == 0) or \n (self.IOST_Objs[\"SetupTestcaseTemplate\"][\"_\"+str(number)+\"_RT_Testcase\"] == 0)):\n\n data[number][\"Active\"] = 'Disable'\n\n #______________________________________________________________________\n if ((self.IOST_Objs[\"SetupTestcaseTemplate\"][\"_\"+str(number)+\"_CMD_Testcase\"] == 0) and \n (self.IOST_Objs[\"SetupTestcaseTemplate\"][\"_\"+str(number)+\"_DES_Testcase\"] == 0) and\n (self.IOST_Objs[\"SetupTestcaseTemplate\"][\"_\"+str(number)+\"_RT_Testcase\"] == 0)):\n \n set_object_1.set_active(False)\n set_object_1.set_sensitive(False) \n set_object_2.set_active(False)\n set_object_2.set_sensitive(False)\n self.IOST_Objs[\"SetupTestcaseTemplate\"][\"TestcaseNum\"] -= test_segment \n for i in range(test_segment, 0, -1): \n del data[self.IOST_Objs[\"SetupTestcaseTemplate\"][\"TestcaseNum\"]+i]\n \n \n if IOST_WSetupTestcase_DebugEnable:\n print \"-------------------------------------------\"\n print \"testcase number = \", self.IOST_Objs[\"SetupTestcaseTemplate\"][\"TestcaseNum\"]\n print \"len data = \", len(data)\n print \"_CMD_Testcase = \", self.IOST_Objs[\"SetupTestcaseTemplate\"][\"_\"+str(number)+\"_CMD_Testcase\"]\n print \"_DES_Testcase = \", self.IOST_Objs[\"SetupTestcaseTemplate\"][\"_\"+str(number)+\"_DES_Testcase\"]\n print \"_RT_Testcase = \", self.IOST_Objs[\"SetupTestcaseTemplate\"][\"_\"+str(number)+\"_RT_Testcase\"]\n \n \n print \"------------------debug-------------------------\"\n print number\n print self.IOST_Objs[\"SetupTestcaseTemplate\"][\"TestcaseList\"]\n\n if number == self.IOST_Objs[\"SetupTestcaseTemplate\"][\"TestcaseList\"]:\n self.IOST_Objs[\"SetupTestcaseTemplate\"][\"TestcaseList\"] +=1\n self.WSetupTestcase_CreateTestListMore(self.IOST_Objs[self.IOST_WSetupTestcase_window], self.IOST_Objs[\"SetupTestcaseTemplate\"], self.IOST_Objs[\"SetupTestcaseTemplate\"][\"TestcaseList\"])\n self.WSetupTestcase_SetCallback(self.IOST_WSetupTestcase_window, self.IOST_Data[self.IOST_WSetupTestcase_ip_name], self.IOST_Objs[\"SetupTestcaseTemplate\"][\"TestcaseList\"])\n\n # adjustment = yourScrolledWindow.get_vadjustment()\n # adjustment.set_value(adjustment.get_upper())\n\n adjustment = self.IOST_Objs[self.IOST_WSetupTestcase_window][\"_TestcaseList_SW\"].get_vadjustment()\n adjustment.set_value(adjustment.get_upper())\n self.IOST_Objs[self.IOST_WSetupTestcase_window][\"_TestcaseList_SW\"].set_vadjustment(adjustment)\n \n\n self.IOST_Objs[self.IOST_WSetupTestcase_window][\"_TestcaseList_SW\"].set_placement(gtk.CORNER_BOTTOM_LEFT)\n self.IOST_Objs[self.IOST_WSetupTestcase_window][self.IOST_WSetupTestcase_object].show_all()\n if IOST_WSetupTestcase_DebugEnable:\n print \"1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1\"\n \n #----------------------------------------------------------------------\n def WSetupTestcase_Description_TE_Callback(self, object, event, object_active, data=None, number=None, set_object_1=None, set_object_2=None):\n \"Callback function when Description text entry of a testcase have changed\"\n #______________________________________________________________________\n try:\n self.IOST_Objs[\"SetupTestcaseTemplate\"][\"_\"+str(number)+\"_CMD_Testcase\"]\n except KeyError:\n self.IOST_Objs[\"SetupTestcaseTemplate\"][\"_\"+str(number)+\"_CMD_Testcase\"] = 0\n\n try:\n self.IOST_Objs[\"SetupTestcaseTemplate\"][\"_\"+str(number)+\"_DES_Testcase\"]\n except KeyError:\n self.IOST_Objs[\"SetupTestcaseTemplate\"][\"_\"+str(number)+\"_DES_Testcase\"] = 0\n\n try:\n self.IOST_Objs[\"SetupTestcaseTemplate\"][\"_\"+str(number)+\"_RT_Testcase\"]\n except KeyError:\n self.IOST_Objs[\"SetupTestcaseTemplate\"][\"_\"+str(number)+\"_RT_Testcase\"] = 0\n\n #______________________________________________________________________\n test_segment = 0\n if number > self.IOST_Objs[\"SetupTestcaseTemplate\"][\"TestcaseNum\"]:\n test_segment = number - self.IOST_Objs[\"SetupTestcaseTemplate\"][\"TestcaseNum\"]\n for i in range(0, test_segment):\n data.append( self.IOST_Data[\"IP_N\"][1] )\n self.IOST_Objs[\"SetupTestcaseTemplate\"][\"TestcaseNum\"] +=1\n\n self.IOST_Objs[\"SetupTestcaseTemplate\"][\"_\"+str(number)+\"_DES_Testcase\"] = 0\n\n #______________________________________________________________________\n if IOST_WSetupTestcase_DebugEnable: \n print \"2-2-2-2-2-2-2-2-2-2-2-2-2-2-2-2-2-2-2-2-2-2-2-2-2-2\"\n print \"number = \", number\n print \"testcase number = \", self.IOST_Objs[\"SetupTestcaseTemplate\"][\"TestcaseNum\"]\n print \"testcase list = \", self.IOST_Objs[\"SetupTestcaseTemplate\"][\"TestcaseList\"]\n\n #______________________________________________________________________\n text = object_active.get_text()\n \n if text and text.strip(): # string NOT empty\" \n set_object_1.set_sensitive(True)\n set_object_2.set_sensitive(True)\n data[number][\"Description\"] = text\n self.IOST_Objs[\"SetupTestcaseTemplate\"][\"_\"+str(number)+\"_DES_Testcase\"] = 1\n\n #______________________________________________________________________\n else: # string empty\"\n self.IOST_Objs[\"SetupTestcaseTemplate\"][\"_\"+str(number)+\"_DES_Testcase\"] = 0\n\n \n #______________________________________________________________________\n if ((self.IOST_Objs[\"SetupTestcaseTemplate\"][\"_\"+str(number)+\"_CMD_Testcase\"] == 1) and ", "answers": [" (self.IOST_Objs[\"SetupTestcaseTemplate\"][\"_\"+str(number)+\"_RT_Testcase\"] == 1)):"], "length": 696, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "c9ea7fd7-3b72-41e1-a54e-0bdff80a959a", "reasoning": "In the Description callback, after setting the DES flag, the code mirrors the logic from the CMD callback. It starts an if statement checking whether the CMD flag is 1 and needs to continue checking the RT flag. The next line completes the condition by adding the RT_Testcase check and closing the parentheses.", "reasoning_model_answer": "(self.IOST_Objs[\"SetupTestcaseTemplate\"][\"_\"+str(number)+\"_RT_Testcase\"] == 1)):", "assistant_with_reasoning": "\nIn the Description callback, after setting the DES flag, the code mirrors the logic from the CMD callback. It starts an if statement checking whether the CMD flag is 1 and needs to continue checking the RT flag. The next line completes the condition by adding the RT_Testcase check and closing the parentheses.\n\n(self.IOST_Objs[\"SetupTestcaseTemplate\"][\"_\"+str(number)+\"_RT_Testcase\"] == 1)):", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.616, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 16343, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "(self.IOST_Objs[\"SetupTestcaseTemplate\"][\"_\"+str(number)+\"_RT_Testcase\"] == 1)):", "score": 0.93, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Reflection;\nusing System.Runtime.InteropServices;\nusing System.Text;\nusing Microsoft.Extensions.Logging;\nusing NBitcoin;\nusing NBitcoin.Networks;\nusing NBitcoin.Protocol;\nusing NLog.Extensions.Logging;\nusing Stratis.Bitcoin.Builder.Feature;\nusing Stratis.Bitcoin.Configuration.Logging;\nusing Stratis.Bitcoin.Configuration.Settings;\nusing Stratis.Bitcoin.Utilities;\n\nnamespace Stratis.Bitcoin.Configuration\n{\n internal static class NormalizeDirectorySeparatorExt\n {\n /// \n /// Fixes incorrect directory separator characters in path (if any)\n /// \n public static string NormalizeDirectorySeparator(this string path)\n {\n // Replace incorrect with correct\n return path.Replace((Path.DirectorySeparatorChar == '/') ? '\\\\' : '/', Path.DirectorySeparatorChar);\n }\n }\n\n /// \n /// Node configuration complied from both the application command line arguments and the configuration file.\n /// \n public class NodeSettings : IDisposable\n {\n /// Version of the protocol the current implementation supports.\n public const ProtocolVersion SupportedProtocolVersion = ProtocolVersion.SENDHEADERS_VERSION;\n\n /// Factory to create instance logger.\n public ILoggerFactory LoggerFactory { get; private set; }\n\n /// Instance logger.\n public ILogger Logger { get; private set; }\n\n /// Configuration related to logging.\n public LogSettings Log { get; private set; }\n\n /// List of paths to important files and folders.\n public DataFolder DataFolder { get; private set; }\n\n /// Path to the data directory. This value is read-only and is set in the constructor's args.\n public string DataDir { get; private set; }\n\n /// Path to the root data directory. This value is read-only and is set in the constructor's args.\n public string DataDirRoot { get; private set; }\n\n /// Path to the configuration file. This value is read-only and is set in the constructor's args.\n public string ConfigurationFile { get; private set; }\n\n /// Combined command line arguments and configuration file settings.\n public TextFileConfiguration ConfigReader { get; private set; }\n\n /// Supported protocol version.\n public ProtocolVersion ProtocolVersion { get; private set; }\n\n /// Lowest supported protocol version.\n public ProtocolVersion? MinProtocolVersion { get; set; }\n\n /// Specification of the network the node runs on - regtest/testnet/mainnet.\n public Network Network { get; private set; }\n\n /// The node's user agent.\n public string Agent { get; private set; }\n\n /// Minimum transaction fee for network.\n public FeeRate MinTxFeeRate { get; private set; }\n\n /// Fall back transaction fee for network.\n public FeeRate FallbackTxFeeRate { get; private set; }\n\n /// Minimum relay transaction fee for network.\n public FeeRate MinRelayTxFeeRate { get; private set; }\n\n /// \n /// Initializes a new instance of the object.\n /// \n /// The network the node runs on - regtest/testnet/mainnet.\n /// Supported protocol version for which to create the configuration.\n /// The nodes user agent that will be shared with peers.\n /// The command-line arguments.\n /// A selector class that delayed load a network for either - regtest/testnet/mainnet.\n /// Thrown in case of any problems with the configuration file or command line arguments.\n /// \n /// Processing depends on whether a configuration file is passed via the command line.\n /// There are two main scenarios here:\n /// - The configuration file is passed via the command line. In this case we need\n /// to read it earlier so that it can provide defaults for \"testnet\" and \"regtest\".\n /// - Alternatively, if the file name is not supplied then a network-specific file\n /// name would be determined. In this case we first need to determine the network.\n /// \n public NodeSettings(Network network = null, ProtocolVersion protocolVersion = SupportedProtocolVersion,\n string agent = \"StratisNode\", string[] args = null, NetworksSelector networksSelector = null)\n {\n // Create the default logger factory and logger.\n var loggerFactory = new ExtendedLoggerFactory();\n this.LoggerFactory = loggerFactory;\n this.LoggerFactory.AddConsoleWithFilters();\n this.LoggerFactory.AddNLog();\n this.Logger = this.LoggerFactory.CreateLogger(typeof(NodeSettings).FullName);\n\n // Record arguments.\n this.Network = network;\n this.ProtocolVersion = protocolVersion;\n this.Agent = agent;\n this.ConfigReader = new TextFileConfiguration(args ?? new string[] { });\n\n // Log arguments.\n this.Logger.LogDebug(\"Arguments: network='{0}', protocolVersion='{1}', agent='{2}', args='{3}'.\",\n this.Network == null ? \"(None)\" : this.Network.Name,\n this.ProtocolVersion,\n this.Agent,\n args == null ? \"(None)\" : string.Join(\" \", args));\n\n // By default, we look for a file named '.conf' in the network's data directory,\n // but both the data directory and the configuration file path may be changed using the -datadir and -conf command-line arguments.\n this.ConfigurationFile = this.ConfigReader.GetOrDefault(\"conf\", null, this.Logger)?.NormalizeDirectorySeparator();\n this.DataDir = this.ConfigReader.GetOrDefault(\"datadir\", null, this.Logger)?.NormalizeDirectorySeparator();\n this.DataDirRoot = this.ConfigReader.GetOrDefault(\"datadirroot\", \"StratisNode\", this.Logger);\n\n // If the configuration file is relative then assume it is relative to the data folder and combine the paths.\n if (this.DataDir != null && this.ConfigurationFile != null)\n {\n bool isRelativePath = Path.GetFullPath(this.ConfigurationFile).Length > this.ConfigurationFile.Length;\n if (isRelativePath)\n this.ConfigurationFile = Path.Combine(this.DataDir, this.ConfigurationFile);\n }\n\n // If the configuration file has been specified on the command line then read it now\n // so that it can provide the defaults for testnet and regtest.", "answers": [" if (this.ConfigurationFile != null)"], "length": 744, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "f37da6b8-bf6a-4740-80ab-71219f897d22", "reasoning": "The comment explains that when a configuration file path was supplied via the command line, the code should now read that file so its settings can affect defaults for testnet/regtest. The next logical step is to check whether ConfigurationFile is non‑null before loading it. Therefore the next line is the conditional that begins this operation.", "reasoning_model_answer": "if (this.ConfigurationFile != null)", "assistant_with_reasoning": "\nThe comment explains that when a configuration file path was supplied via the command line, the code should now read that file so its settings can affect defaults for testnet/regtest. The next logical step is to check whether ConfigurationFile is non‑null before loading it. Therefore the next line is the conditional that begins this operation.\n\nif (this.ConfigurationFile != null)", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.414, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 7297, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "if (this.ConfigurationFile != null)", "score": 0.85, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "// Copyright 2020 The Bazel Authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\npackage com.google.devtools.build.lib.skyframe;\n\nimport static com.google.common.truth.Truth.assertThat;\nimport static com.google.common.truth.Truth.assertWithMessage;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.devtools.build.lib.actions.MutableActionGraph.ActionConflictException;\nimport com.google.devtools.build.lib.analysis.AnalysisEnvironment;\nimport com.google.devtools.build.lib.analysis.ConfiguredRuleClassProvider;\nimport com.google.devtools.build.lib.analysis.ConfiguredTarget;\nimport com.google.devtools.build.lib.analysis.RuleContext;\nimport com.google.devtools.build.lib.analysis.util.BuildViewTestCase;\nimport com.google.devtools.build.lib.analysis.util.MockRule;\nimport com.google.devtools.build.lib.analysis.util.MockRuleDefaults;\nimport com.google.devtools.build.lib.events.Event;\nimport com.google.devtools.build.lib.events.EventHandler;\nimport com.google.devtools.build.lib.packages.semantics.BuildLanguageOptions;\nimport com.google.devtools.build.lib.testutil.TestRuleClassProvider;\nimport java.io.IOException;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\nimport net.starlark.java.eval.EvalException;\nimport net.starlark.java.eval.FlagGuardedValue;\nimport net.starlark.java.eval.Mutability;\nimport net.starlark.java.eval.Starlark;\nimport net.starlark.java.eval.StarlarkList;\nimport net.starlark.java.eval.StarlarkThread;\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.junit.runners.JUnit4;\n\n/**\n * Tests for Starlark builtin injection.\n *\n *

    Essentially these are integration tests between {@link StarlarkBuiltinsFunction}, {@link\n * BzlLoadFunction}, and the rest of package loading.\n */\n@RunWith(JUnit4.class)\npublic class BuiltinsInjectionTest extends BuildViewTestCase {\n\n /** A simple dummy rule that doesn't do anything. */\n private static final MockRule OVERRIDABLE_RULE = () -> MockRule.define(\"overridable_rule\");\n\n /**\n * A dummy native rule that reads from exported_to_java the symbol \"builtins_defined_symbol\", and\n * prints its value to the event handler.\n */\n private static final MockRule SANDWICH_RULE =\n () -> MockRule.factory(SandwichFactory.class).define(\"sandwich_rule\");\n\n // Must be public due to reflective construction of rule factories.\n /** Factory for SANDWICH_RULE. (Javadoc'd to pacify linter.) */\n public static class SandwichFactory extends MockRuleDefaults.DefaultConfiguredTargetFactory {\n @Override\n public ConfiguredTarget create(RuleContext ruleContext)\n throws InterruptedException, RuleErrorException, ActionConflictException {\n AnalysisEnvironment env = ruleContext.getAnalysisEnvironment();\n\n Object value = env.getStarlarkDefinedBuiltins().get(\"builtins_defined_symbol\");\n\n env.getEventHandler().handle(Event.info(\"builtins_defined_symbol :: \" + value.toString()));\n return super.create(ruleContext);\n }\n }\n\n /**\n * A dummy rule that dispatches to {@code @_builtins}-defined code. It looks up the function\n * listed as \"builtins_defined_logic\" in exported_to_java, and calls it twice on an initially\n * empty list. It prints both return values and the final value of the list.\n */\n private static final MockRule SANDWICH_LOGIC_RULE =\n () -> MockRule.factory(SandwichLogicFactory.class).define(\"sandwich_logic_rule\");\n\n // Must be public due to reflective construction of rule factories.\n /** Factory for SANDWICH_LOGIC_RULE. (Javadoc'd to pacify linter.) */\n public static class SandwichLogicFactory extends MockRuleDefaults.DefaultConfiguredTargetFactory {\n @Override\n public ConfiguredTarget create(RuleContext ruleContext)\n throws InterruptedException, RuleErrorException, ActionConflictException {\n AnalysisEnvironment env = ruleContext.getAnalysisEnvironment();\n StarlarkThread thread = ruleContext.getStarlarkThread();\n Mutability mu = thread.mutability();\n\n Object func = env.getStarlarkDefinedBuiltins().get(\"builtins_defined_logic\");\n Object arg = StarlarkList.newList(mu);\n Object return1;\n Object return2;\n try {\n return1 = Starlark.call(thread, func, ImmutableList.of(arg), ImmutableMap.of());\n return2 = Starlark.call(thread, func, ImmutableList.of(arg), ImmutableMap.of());\n } catch (EvalException e) {\n throw new AssertionError(\"Failure during Starlark evaluation\", e);\n }\n\n EventHandler handler = env.getEventHandler();\n handler.handle(Event.info(\"builtins_defined_logic call 1 :: \" + return1.toString()));\n handler.handle(Event.info(\"builtins_defined_logic call 2 :: \" + return2.toString()));\n handler.handle(Event.info(\"final list value :: \" + arg.toString()));\n return super.create(ruleContext);\n }\n }\n\n @Override\n protected Iterable getDefaultsForConfiguration() {\n // Override BuildViewTestCase's behavior of setting all sorts of extra options that don't exist\n // on our minimal rule class provider.\n // We do need the host platform. Set it to something trivial.\n return ImmutableList.of(\"--host_platform=//minimal_buildenv/platforms:default_host\");\n }\n\n @Override\n protected void initializeMockClient() throws IOException {\n // Don't let the AnalysisMock sneak in any WORKSPACE file content, which may depend on\n // repository rules that our minimal rule class provider doesn't have.\n analysisMock.setupMockClient(mockToolsConfig, ImmutableList.of());\n // Provide a trivial platform definition.\n mockToolsConfig.create(\n \"minimal_buildenv/platforms/BUILD\", //\n \"platform(name = 'default_host')\");\n }\n\n @Override\n protected ConfiguredRuleClassProvider createRuleClassProvider() {\n // Set up a bare-bones ConfiguredRuleClassProvider. Aside from being minimalistic, this heads\n // off the possibility that we somehow grow an implicit dependency on production builtins code,\n // which would break since we're overwriting --experimental_builtins_bzl_path.\n ConfiguredRuleClassProvider.Builder builder = new ConfiguredRuleClassProvider.Builder();\n TestRuleClassProvider.addMinimalRules(builder);\n // Add some mock symbols to override.\n builder\n .addRuleDefinition(OVERRIDABLE_RULE)\n .addRuleDefinition(SANDWICH_RULE)\n .addRuleDefinition(SANDWICH_LOGIC_RULE)\n .addStarlarkAccessibleTopLevels(\"overridable_symbol\", \"original_value\")\n .addStarlarkAccessibleTopLevels(\n \"flag_guarded_symbol\",\n // For this mock symbol, we reuse the same flag that guards the production\n // _builtins_dummy symbol.\n FlagGuardedValue.onlyWhenExperimentalFlagIsTrue(\n BuildLanguageOptions.EXPERIMENTAL_BUILTINS_DUMMY, \"original value\"));\n return builder.build();\n }\n\n @Before\n public void setUp() throws Exception {\n setBuildLanguageOptions(\"--experimental_builtins_bzl_path=tools/builtins_staging\");\n }\n\n /**\n * Writes an exports.bzl file with the given content, in the builtins location.\n *\n *

    See {@link StarlarkBuiltinsFunction#EXPORTS_ENTRYPOINT} for the significance of exports.bzl.\n */\n private void writeExportsBzl(String... lines) throws Exception {\n scratch.file(\"tools/builtins_staging/exports.bzl\", lines);\n }\n\n /**\n * Writes a pkg/dummy.bzl file that prints a marker phrase when it finishes evaluating, and an\n * accompanying BUILD file that loads it.\n */\n private void writePkgBzl(String... lines) throws Exception {\n scratch.file(\"pkg/BUILD\", \"load(':dummy.bzl', 'dummy_symbol')\");\n scratch.file(\"pkg/dummy\");\n List modifiedLines = new ArrayList<>(Arrays.asList(lines));\n modifiedLines.add(\"dummy_symbol = None\");\n // The marker phrase might not be needed, but I don't entirely trust BuildViewTestCase.\n modifiedLines.add(\"print('dummy.bzl evaluation completed')\");\n scratch.file(\"pkg/dummy.bzl\", modifiedLines.toArray(lines));\n }\n\n /** Builds {@code //pkg} and asserts success, including that the marker print() event occurs. */", "answers": [" private void buildAndAssertSuccess() throws Exception {"], "length": 775, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "0e74f49c-4f80-42b0-8df5-f8cdbc64462c", "reasoning": "The comment just introduced a helper method that builds the //pkg target and checks that the build succeeded and that the dummy.bzl print marker was emitted. Following the naming style of the other helper methods (writeExportsBzl, writePkgBzl), the next line should be the method signature for this helper. A suitable signature is a private method returning void, throwing Exception, named to reflect its purpose, e.g., assertPkgBuildSucceeds().", "reasoning_model_answer": "private void assertPkgBuildSucceeds() throws Exception {", "assistant_with_reasoning": "\nThe comment just introduced a helper method that builds the //pkg target and checks that the build succeeded and that the dummy.bzl print marker was emitted. Following the naming style of the other helper methods (writeExportsBzl, writePkgBzl), the next line should be the method signature for this helper. A suitable signature is a private method returning void, throwing Exception, named to reflect its purpose, e.g., assertPkgBuildSucceeds().\n\nprivate void assertPkgBuildSucceeds() throws Exception {", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.541, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 8781, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "private void assertPkgBuildSucceeds() throws Exception {", "score": 0.8, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "namespace com.snippets.Migrations\n{\n using System;\n using System.Data.Entity;\n using System.Data.Entity.Migrations;\n using System.Linq;\n using com.snippets.Data.Entities;\n\n internal sealed class Configuration : DbMigrationsConfiguration\n {\n public Configuration()\n {\n Database.SetInitializer(new DropCreateDatabaseIfModelChanges());\n AutomaticMigrationsEnabled = true;\n }\n\n protected override void Seed(com.snippets.Data.Entities.snippetsDb context)\n {\n\n #region Populating Post Types Table\n\n context.Posts_Types.AddOrUpdate(\n\n p => p.TypeName,\n new Post_Type { TypeName = \"Status\" },\n new Post_Type { TypeName = \"Photo\" },\n new Post_Type { TypeName = \"Snippets\" }\n );\n\n #endregion\n\n #region Populating Genders Table\n context.Genders.AddOrUpdate(\n\n p => p.GenderName,\n new Gender { GenderName = \"Male\" },\n new Gender { GenderName = \"Female\" }\n );\n #endregion\n\n #region Populating Preference Types Table\n context.PreferenceTypes.AddOrUpdate(\n \n p=>p.Type,\n new PreferenceType{Type=\"Language\", PreferenceTypeId=1}\n );\n #endregion\n\n #region Populating Preferences Table\n\n context.Preferences.AddOrUpdate(\n \n p=>p.PreferenceName,\n new Preference{PreferenceTypeId=1, PreferenceName=\"C\", LanguageCode=\"c\", \n photo_url=@\"~\\Content\\images\\langs\\lang-c.png\"},\n\n new Preference{PreferenceTypeId=1, PreferenceName=\"C++\", LanguageCode=\"cpp\", \n photo_url=@\"~\\Content\\images\\langs\\lang-cpp.png\"},\n\n new Preference{PreferenceTypeId=1, PreferenceName=\"C#\", LanguageCode=\"csharp\", \n photo_url=@\"~\\Content\\images\\langs\\lang-csharp.png\"},\n\n new Preference{PreferenceTypeId=1, PreferenceName=\"CSS\", LanguageCode=\"css\", \n photo_url=@\"~\\Content\\images\\langs\\lang-css.png\"},\n\n new Preference{PreferenceTypeId=1, PreferenceName=\"Flex\", LanguageCode=\"flex\", \n photo_url=@\"~\\Content\\images\\langs\\lang-flex.png\"},\n\n new Preference{PreferenceTypeId=1, PreferenceName=\"HTML\", LanguageCode=\"html\", \n photo_url=@\"~\\Content\\images\\langs\\lang-html.png\"},\n\n new Preference{PreferenceTypeId=1, PreferenceName=\"Java\", LanguageCode=\"java\", \n photo_url=@\"~\\Content\\images\\langs\\lang-java.png\"},\n\n new Preference{PreferenceTypeId=1, PreferenceName=\"Javascript\", LanguageCode=\"javascript\", \n photo_url=@\"~\\Content\\images\\langs\\lang-js.png\"},\n\n new Preference{PreferenceTypeId=1, PreferenceName=\"Javascript With DOM\", LanguageCode=\"javascript_dom\", \n photo_url=@\"~\\Content\\images\\langs\\lang-js_dom.png\"},\n\n new Preference{PreferenceTypeId=1, PreferenceName=\"Perl\", LanguageCode=\"perl\", \n photo_url=@\"~\\Content\\images\\langs\\lang-perl.png\"},\n\n new Preference{PreferenceTypeId=1, PreferenceName=\"PHP\", LanguageCode=\"php\", \n photo_url=@\"~\\Content\\images\\langs\\lang-php.png\"},\n\n new Preference{PreferenceTypeId=1, PreferenceName=\"Python\", LanguageCode=\"python\", \n photo_url=@\"~\\Content\\images\\langs\\lang-python.png\"},\n\n new Preference{PreferenceTypeId=1, PreferenceName=\"Ruby\", LanguageCode=\"ruby\", \n photo_url=@\"~\\Content\\images\\langs\\lang-ruby.png\"},\n\n new Preference{PreferenceTypeId=1, PreferenceName=\"SQL\", LanguageCode=\"sql\", \n photo_url=@\"~\\Content\\images\\langs\\lang-sql.png\"},\n\n new Preference{PreferenceTypeId=1, PreferenceName=\"XML\", LanguageCode=\"xml\", \n photo_url=@\"~\\Content\\images\\langs\\lang-xml.png\"}\n );\n #endregion\n \n #region Populating Countries Table\n context.Countries.AddOrUpdate(\n p=>p.CountryName,\n new Country { CountryName= \"Afghanistan\", CountryCode=\"AF\" }, \n new Country { CountryName= \"Aland Islands\", CountryCode=\"AX\" }, \n new Country { CountryName= \"Albania\", CountryCode=\"AL\" }, \n new Country { CountryName= \"Algeria\", CountryCode=\"DZ\" }, \n new Country { CountryName= \"American Samoa\", CountryCode=\"AS\" }, \n new Country { CountryName= \"Andorra\", CountryCode=\"AD\" }, \n new Country { CountryName= \"Angola\", CountryCode=\"AO\" }, \n new Country { CountryName= \"Anguilla\", CountryCode=\"AI\" }, \n new Country { CountryName= \"Antarctica\", CountryCode=\"AQ\" }, \n new Country { CountryName= \"Antigua And Barbuda\", CountryCode=\"AG\" }, \n new Country { CountryName= \"Argentina\", CountryCode=\"AR\" }, \n new Country { CountryName= \"Armenia\", CountryCode=\"AM\" }, \n new Country { CountryName= \"Aruba\", CountryCode=\"AW\" }, \n new Country { CountryName= \"Australia\", CountryCode=\"AU\" }, \n new Country { CountryName= \"Austria\", CountryCode=\"AT\" }, \n new Country { CountryName= \"Azerbaijan\", CountryCode=\"AZ\" }, \n new Country { CountryName= \"Bahamas\", CountryCode=\"BS\" }, \n new Country { CountryName= \"Bahrain\", CountryCode=\"BH\" }, \n new Country { CountryName= \"Bangladesh\", CountryCode=\"BD\" }, \n new Country { CountryName= \"Barbados\", CountryCode=\"BB\" }, \n new Country { CountryName= \"Belarus\", CountryCode=\"BY\" }, \n new Country { CountryName= \"Belgium\", CountryCode=\"BE\" }, \n new Country { CountryName= \"Belize\", CountryCode=\"BZ\" }, \n new Country { CountryName= \"Benin\", CountryCode=\"BJ\" }, \n new Country { CountryName= \"Bermuda\", CountryCode=\"BM\" }, \n new Country { CountryName= \"Bhutan\", CountryCode=\"BT\" }, \n new Country { CountryName= \"Bolivia\", CountryCode=\"BO\" }, \n new Country { CountryName= \"Bosnia And Herzegovina\", CountryCode=\"BA\" }, \n new Country { CountryName= \"Botswana\", CountryCode=\"BW\" }, \n new Country { CountryName= \"Bouvet Island\", CountryCode=\"BV\" }, \n new Country { CountryName= \"Brazil\", CountryCode=\"BR\" }, \n new Country { CountryName= \"British Indian Ocean Territory\", CountryCode=\"IO\" }, \n new Country { CountryName= \"Brunei Darussalam\", CountryCode=\"BN\" }, \n new Country { CountryName= \"Bulgaria\", CountryCode=\"BG\" }, \n new Country { CountryName= \"Burkina Faso\", CountryCode=\"BF\" }, \n new Country { CountryName= \"Burundi\", CountryCode=\"BI\" }, \n new Country { CountryName= \"Cambodia\", CountryCode=\"KH\" }, \n new Country { CountryName= \"Cameroon\", CountryCode=\"CM\" }, \n new Country { CountryName= \"Canada\", CountryCode=\"CA\" }, \n new Country { CountryName= \"Cape Verde\", CountryCode=\"CV\" }, \n new Country { CountryName= \"Cayman Islands\", CountryCode=\"KY\" }, \n new Country { CountryName= \"Central African Republic\", CountryCode=\"CF\" }, \n new Country { CountryName= \"Chad\", CountryCode=\"TD\" }, \n new Country { CountryName= \"Chile\", CountryCode=\"CL\" }, \n new Country { CountryName= \"China\", CountryCode=\"CN\" }, \n new Country { CountryName= \"Christmas Island\", CountryCode=\"CX\" }, \n new Country { CountryName= \"Cocos (Keeling) Islands\", CountryCode=\"CC\" }, \n new Country { CountryName= \"Colombia\", CountryCode=\"CO\" }, \n new Country { CountryName= \"Comoros\", CountryCode=\"KM\" }, \n new Country { CountryName= \"Congo\", CountryCode=\"CG\" }, \n new Country { CountryName= \"Congo, The Democratic Republic Of The\", CountryCode=\"CD\" }, \n new Country { CountryName= \"Cook Islands\", CountryCode=\"CK\" }, \n new Country { CountryName= \"Costa Rica\", CountryCode=\"CR\" }, \n new Country { CountryName= \"Cote D'Ivoire\", CountryCode=\"CI\" }, \n new Country { CountryName= \"Croatia\", CountryCode=\"HR\" }, \n new Country { CountryName= \"Cuba\", CountryCode=\"CU\" }, \n new Country { CountryName= \"Cyprus\", CountryCode=\"CY\" }, \n new Country { CountryName= \"Czech Republic\", CountryCode=\"CZ\" }, \n new Country { CountryName= \"Denmark\", CountryCode=\"DK\" }, \n new Country { CountryName= \"Djibouti\", CountryCode=\"DJ\" }, \n new Country { CountryName= \"Dominica\", CountryCode=\"DM\" }, \n new Country { CountryName= \"Dominican Republic\", CountryCode=\"DO\" }, \n new Country { CountryName= \"Ecuador\", CountryCode=\"EC\" }, \n new Country { CountryName= \"Egypt\", CountryCode=\"EG\" }, \n new Country { CountryName= \"El Salvador\", CountryCode=\"SV\" }, \n new Country { CountryName= \"Equatorial Guinea\", CountryCode=\"GQ\" }, \n new Country { CountryName= \"Eritrea\", CountryCode=\"ER\" }, \n new Country { CountryName= \"Estonia\", CountryCode=\"EE\" }, \n new Country { CountryName= \"Ethiopia\", CountryCode=\"ET\" }, \n new Country { CountryName= \"Falkland Islands (Malvinas)\", CountryCode=\"FK\" }, \n new Country { CountryName= \"Faroe Islands\", CountryCode=\"FO\" }, \n new Country { CountryName= \"Fiji\", CountryCode=\"FJ\" }, \n new Country { CountryName= \"Finland\", CountryCode=\"FI\" }, \n new Country { CountryName= \"France\", CountryCode=\"FR\" }, \n new Country { CountryName= \"French Guiana\", CountryCode=\"GF\" }, \n new Country { CountryName= \"French Polynesia\", CountryCode=\"PF\" }, \n new Country { CountryName= \"French Southern Territories\", CountryCode=\"TF\" }, \n new Country { CountryName= \"Gabon\", CountryCode=\"GA\" }, \n new Country { CountryName= \"Gambia\", CountryCode=\"GM\" }, \n new Country { CountryName= \"Georgia\", CountryCode=\"GE\" }, \n new Country { CountryName= \"Germany\", CountryCode=\"DE\" }, \n new Country { CountryName= \"Ghana\", CountryCode=\"GH\" }, \n new Country { CountryName= \"Gibraltar\", CountryCode=\"GI\" }, \n new Country { CountryName= \"Greece\", CountryCode=\"GR\" }, \n new Country { CountryName= \"Greenland\", CountryCode=\"GL\" }, \n new Country { CountryName= \"Grenada\", CountryCode=\"GD\" }, \n new Country { CountryName= \"Guadeloupe\", CountryCode=\"GP\" }, \n new Country { CountryName= \"Guam\", CountryCode=\"GU\" }, \n new Country { CountryName= \"Guatemala\", CountryCode=\"GT\" }, \n new Country { CountryName= \"Guernsey\", CountryCode=\" GG\" }, \n new Country { CountryName= \"Guinea\", CountryCode=\"GN\" }, \n new Country { CountryName= \"Guinea-Bissau\", CountryCode=\"GW\" }, ", "answers": [" new Country { CountryName= \"Guyana\", CountryCode=\"GY\" }, "], "length": 882, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "71ca4dc9-74b4-48d1-b4fd-722594834ceb", "reasoning": "The Seed method is populating the Countries table using AddOrUpdate with a list of Country objects. The list is alphabetical and currently ends with Guinea-Bissau. The next country alphabetically is Guyana, so the next line should add a new Country entry for Guyana with its ISO code.", "reasoning_model_answer": "new Country { CountryName= \"Guyana\", CountryCode=\"GY\" },", "assistant_with_reasoning": "\nThe Seed method is populating the Countries table using AddOrUpdate with a list of Country objects. The list is alphabetical and currently ends with Guinea-Bissau. The next country alphabetically is Guyana, so the next line should add a new Country entry for Guyana with its ISO code.\n\nnew Country { CountryName= \"Guyana\", CountryCode=\"GY\" },", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 2.735, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 11762, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "new Country { CountryName= \"Guyana\", CountryCode=\"GY\" },", "score": 0.87, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "// ----------------------------------------------------------------------------------\n// \n// Copyright Microsoft Corporation\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n// http://www.apache.org/licenses/LICENSE-2.0\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n// ----------------------------------------------------------------------------------\n\nnamespace Microsoft.Azure.Commands.RecoveryServices.SiteRecovery\n{\n ///

    \n /// Parameter Sets used for Azure Site Recovery commands.\n /// \n internal static class ASRParameterSets\n {\n /// \n /// Add protected entities to RP\n /// \n internal const string AddProtectedEntities = \"AddProtectedEntities\";\n\n /// \n /// Add replication protected items to RP\n /// \n internal const string AddReplicationProtectedItems = \"AddReplicationProtectedItems\";\n\n /// \n /// To append group to RP.\n /// \n internal const string AppendGroup = \"AppendGroup\";\n\n /// \n /// Handle ARS Vault.\n /// \n internal const string ARSVault = \"AzureRecoveryServicesVault\";\n\n /// \n /// Handle ASR Vault.\n /// \n internal const string ASRVault = \"AzureSiteRecoveryVault\";\n\n /// \n /// Handle ASR Vault - Azure Fabric.\n /// \n internal const string Azure = \"Azure\";\n\n /// \n /// Handle ASR Vault - A2A Fabric.\n /// \n internal const string AzureToAzure = \"AzureToAzure\";\n\n /// \n /// Handle ASR Vault - A2A Fabric.\n /// \n internal const string AzureToAzureWithoutDiskDetails = \"AzureToAzureWithoutDiskDetails\";\n \n /// \n /// Handle ASR Vault - Paramset for A2a ManagedDisk.\n /// \n internal const string AzureToAzureManagedDisk = \"AzureToAzureManagedDisk\";\n\n /// \n /// Handle ASR Vault - A2A Fabric name.\n /// \n internal const string AzureToAzureWithFabricName = \"AzureToAzureWithFabricName\";\n\n /// \n /// Handle ASR Vault - A2A Fabric -AzureToAzureWithMultipleStorageAccount.\n /// \n internal const string AzureToAzureWithMultipleStorageAccount = \"AzureToAzureWithMultipleStorageAccount\";\n\n /// \n /// Handle ASR Vault.\n /// \n internal const string AzureToVMware = \"AzureToVMware\";\n\n /// \n /// When only Name is passed to the command.\n /// \n internal const string ByFabricObject = \"ByFabricObject\";\n\n /// \n /// When FabricId is passed to the command.\n /// \n internal const string ByFabricId = \"ByFabricId\";\n\n /// \n /// When only Name is passed to the command.\n /// \n internal const string ByFabricName = \"ByFabricName\";\n\n /// \n /// When only Name is passed to the command.\n /// \n internal const string ByFriendlyName = \"ByFriendlyName\";\n\n /// \n /// When only Friendly Name is passed to the command Legacy.\n /// \n internal const string ByFriendlyNameLegacy = \"ByFriendlyNameLegacy\";\n\n /// \n /// When only ID is passed to the command.\n /// \n internal const string ById = \"ById\";\n\n /// \n /// When group of IDs are passed to the command.\n /// \n internal const string ByIDs = \"ByIDs\";\n\n /// \n /// When group of IDs and ID are passed to the command.\n /// \n internal const string ByIDsWithId = \"ByIDsWithId\";\n\n /// \n /// When group of IDs and Name are passed to the command.\n /// \n internal const string ByIDsWithName = \"ByIDsWithName\";\n\n /// \n /// When only Name is passed to the command.\n /// \n internal const string ByName = \"ByName\";\n\n /// \n /// When only NetworkName Fabric is passed to the command.\n /// \n internal const string ByNetworkNameFabric = \"ByNetworkNameFabric\";\n\n /// \n /// When only NetworkName FabricName is passed to the command.\n /// \n internal const string ByNetworkNameFabricName = \"ByNetworkNameFabricName\";\n\n /// \n /// When only Name is passed to the command Legacy.\n /// \n internal const string ByNameLegacy = \"ByNameLegacy\";\n\n /// \n /// To define parameter set containing network object.\n /// \n internal const string ByNetworkObject = \"ByNetworkObject\";\n\n /// \n /// When only Object is passed to the command.\n /// \n internal const string ByObject = \"ByObject\";\n\n /// \n /// When Object and Name are passed to the command.\n /// \n internal const string ByObjectWithFriendlyName = \"ByObjectWithFriendlyName\";\n\n /// \n /// When Object and Name are passed to the command Legacy.\n /// \n internal const string ByObjectWithFriendlyNameLegacy = \"ByObjectWithFriendlyNameLegacy\";\n\n /// \n /// When Object and ID are passed to the command.\n /// \n internal const string ByObjectWithId = \"ByObjectWithId\";\n\n /// \n /// When Object and Name are passed to the command.\n /// \n internal const string ByObjectWithName = \"ByObjectWithName\";\n\n /// \n /// When Object and Name are passed to the command Legacy.\n /// \n internal const string ByObjectWithNameLegacy = \"ByObjectWithNameLegacy\";\n\n /// \n /// When parameters are passed to the command.\n /// \n internal const string ByParam = \"ByParam\";\n\n /// \n /// When only PC and PE ids are passed to the command.\n /// \n internal const string ByPEId = \"ByPEId\";\n\n /// \n /// When only PC and PE ids are passed along with logical network ID to the command.\n /// \n internal const string ByPEIdWithLogicalNetworkID = \"ByPEIdWithLogicalNetworkID\";\n\n /// \n /// When only PC and PE ids are passed along with VM network to the command.\n /// \n internal const string ByPEIdWithVMNetwork = \"ByPEIdWithVMNetwork\";\n\n /// \n /// When only PC and PE ids are passed along with VM network ID to the command.\n /// \n internal const string ByPEIdWithVMNetworkID = \"ByPEIdWithVMNetworkID\";\n\n /// \n /// When only PE Object is passed to the command.\n /// ", "answers": [" internal const string ByPEObject = \"ByPEObject\";"], "length": 850, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "bf4d7349-d43b-49b9-8c3d-65f525c4d21b", "reasoning": "The code defines a series of internal constant strings representing parameter set names, each preceded by an XML summary comment. The last comment describes a parameter set for when only a PE (Protected Entity) object is passed. Following the established pattern, the next line should declare the corresponding constant string named ByPEObject with its value \"ByPEObject\".", "reasoning_model_answer": "internal const string ByPEObject = \"ByPEObject\";", "assistant_with_reasoning": "\nThe code defines a series of internal constant strings representing parameter set names, each preceded by an XML summary comment. The last comment describes a parameter set for when only a PE (Protected Entity) object is passed. Following the established pattern, the next line should declare the corresponding constant string named ByPEObject with its value \"ByPEObject\".\n\ninternal const string ByPEObject = \"ByPEObject\";", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 2.95, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 7719, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "internal const string ByPEObject = \"ByPEObject\";", "score": 0.92, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "# coding=utf-8\n# --------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for license information.\n# Code generated by Microsoft (R) AutoRest Code Generator.\n# Changes may cause incorrect behavior and will be lost if the code is regenerated.\n# --------------------------------------------------------------------------\nimport functools\nfrom typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union\nimport warnings\n\nfrom azure.core.async_paging import AsyncItemPaged, AsyncList\nfrom azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error\nfrom azure.core.pipeline import PipelineResponse\nfrom azure.core.pipeline.transport import AsyncHttpResponse\nfrom azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod\nfrom azure.core.rest import HttpRequest\nfrom azure.core.tracing.decorator import distributed_trace\nfrom azure.core.tracing.decorator_async import distributed_trace_async\nfrom azure.mgmt.core.exceptions import ARMErrorFormat\nfrom azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling\n\nfrom ... import models as _models\nfrom ..._vendor import _convert_request\nfrom ...operations._virtual_clusters_operations import build_delete_request_initial, build_get_request, build_list_by_resource_group_request, build_list_request, build_update_dns_servers_request, build_update_request_initial\nT = TypeVar('T')\nClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]]\n\nclass VirtualClustersOperations:\n \"\"\"VirtualClustersOperations async operations.\n\n You should not instantiate this class directly. Instead, you should create a Client instance that\n instantiates it for you and attaches it as an attribute.\n\n :ivar models: Alias to model classes used in this operation group.\n :type models: ~azure.mgmt.sql.models\n :param client: Client for service requests.\n :param config: Configuration of service client.\n :param serializer: An object model serializer.\n :param deserializer: An object model deserializer.\n \"\"\"\n\n models = _models\n\n def __init__(self, client, config, serializer, deserializer) -> None:\n self._client = client\n self._serialize = serializer\n self._deserialize = deserializer\n self._config = config\n\n @distributed_trace_async\n async def update_dns_servers(\n self,\n resource_group_name: str,\n virtual_cluster_name: str,\n **kwargs: Any\n ) -> \"_models.UpdateManagedInstanceDnsServersOperation\":\n \"\"\"Synchronizes the DNS server settings used by the managed instances inside the given virtual\n cluster.\n\n :param resource_group_name: The name of the resource group that contains the resource. You can\n obtain this value from the Azure Resource Manager API or the portal.\n :type resource_group_name: str\n :param virtual_cluster_name: The name of the virtual cluster.\n :type virtual_cluster_name: str\n :keyword callable cls: A custom type or function that will be passed the direct response\n :return: UpdateManagedInstanceDnsServersOperation, or the result of cls(response)\n :rtype: ~azure.mgmt.sql.models.UpdateManagedInstanceDnsServersOperation\n :raises: ~azure.core.exceptions.HttpResponseError\n \"\"\"\n cls = kwargs.pop('cls', None) # type: ClsType[\"_models.UpdateManagedInstanceDnsServersOperation\"]\n error_map = {\n 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError\n }\n error_map.update(kwargs.pop('error_map', {}))\n\n \n request = build_update_dns_servers_request(\n resource_group_name=resource_group_name,\n virtual_cluster_name=virtual_cluster_name,\n subscription_id=self._config.subscription_id,\n template_url=self.update_dns_servers.metadata['url'],\n )\n request = _convert_request(request)\n request.url = self._client.format_url(request.url)\n\n pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)\n response = pipeline_response.http_response\n\n if response.status_code not in [200]:\n map_error(status_code=response.status_code, response=response, error_map=error_map)\n raise HttpResponseError(response=response, error_format=ARMErrorFormat)\n\n deserialized = self._deserialize('UpdateManagedInstanceDnsServersOperation', pipeline_response)\n\n if cls:\n return cls(pipeline_response, deserialized, {})\n\n return deserialized\n\n update_dns_servers.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/virtualClusters/{virtualClusterName}/updateManagedInstanceDnsServers'} # type: ignore\n\n\n @distributed_trace\n def list(\n self,\n **kwargs: Any\n ) -> AsyncIterable[\"_models.VirtualClusterListResult\"]:\n \"\"\"Gets a list of all virtualClusters in the subscription.\n\n :keyword callable cls: A custom type or function that will be passed the direct response\n :return: An iterator like instance of either VirtualClusterListResult or the result of\n cls(response)\n :rtype:\n ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.sql.models.VirtualClusterListResult]\n :raises: ~azure.core.exceptions.HttpResponseError\n \"\"\"\n cls = kwargs.pop('cls', None) # type: ClsType[\"_models.VirtualClusterListResult\"]\n error_map = {\n 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError\n }\n error_map.update(kwargs.pop('error_map', {}))\n def prepare_request(next_link=None):\n if not next_link:\n \n request = build_list_request(\n subscription_id=self._config.subscription_id,\n template_url=self.list.metadata['url'],\n )\n request = _convert_request(request)\n request.url = self._client.format_url(request.url)\n\n else:\n \n request = build_list_request(\n subscription_id=self._config.subscription_id,\n template_url=next_link,\n )\n request = _convert_request(request)\n request.url = self._client.format_url(request.url)\n request.method = \"GET\"\n return request\n\n async def extract_data(pipeline_response):\n deserialized = self._deserialize(\"VirtualClusterListResult\", pipeline_response)\n list_of_elem = deserialized.value\n if cls:\n list_of_elem = cls(list_of_elem)\n return deserialized.next_link or None, AsyncList(list_of_elem)\n\n async def get_next(next_link=None):\n request = prepare_request(next_link)\n\n pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)\n response = pipeline_response.http_response\n\n if response.status_code not in [200]:\n map_error(status_code=response.status_code, response=response, error_map=error_map)\n raise HttpResponseError(response=response, error_format=ARMErrorFormat)\n\n return pipeline_response\n\n\n return AsyncItemPaged(\n get_next, extract_data\n )\n list.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Sql/virtualClusters'} # type: ignore\n\n @distributed_trace\n def list_by_resource_group(\n self,\n resource_group_name: str,\n **kwargs: Any\n ) -> AsyncIterable[\"_models.VirtualClusterListResult\"]:\n \"\"\"Gets a list of virtual clusters in a resource group.\n\n :param resource_group_name: The name of the resource group that contains the resource. You can\n obtain this value from the Azure Resource Manager API or the portal.\n :type resource_group_name: str\n :keyword callable cls: A custom type or function that will be passed the direct response\n :return: An iterator like instance of either VirtualClusterListResult or the result of\n cls(response)\n :rtype:\n ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.sql.models.VirtualClusterListResult]\n :raises: ~azure.core.exceptions.HttpResponseError\n \"\"\"\n cls = kwargs.pop('cls', None) # type: ClsType[\"_models.VirtualClusterListResult\"]\n error_map = {\n 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError\n }\n error_map.update(kwargs.pop('error_map', {}))\n def prepare_request(next_link=None):\n if not next_link:\n \n request = build_list_by_resource_group_request(\n resource_group_name=resource_group_name,\n subscription_id=self._config.subscription_id,\n template_url=self.list_by_resource_group.metadata['url'],\n )\n request = _convert_request(request)\n request.url = self._client.format_url(request.url)\n\n else:\n \n request = build_list_by_resource_group_request(\n resource_group_name=resource_group_name,\n subscription_id=self._config.subscription_id,\n template_url=next_link,\n )\n request = _convert_request(request)\n request.url = self._client.format_url(request.url)\n request.method = \"GET\"\n return request\n\n async def extract_data(pipeline_response):\n deserialized = self._deserialize(\"VirtualClusterListResult\", pipeline_response)\n list_of_elem = deserialized.value\n if cls:\n list_of_elem = cls(list_of_elem)\n return deserialized.next_link or None, AsyncList(list_of_elem)\n\n async def get_next(next_link=None):\n request = prepare_request(next_link)\n\n pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)\n response = pipeline_response.http_response\n\n if response.status_code not in [200]:\n map_error(status_code=response.status_code, response=response, error_map=error_map)\n raise HttpResponseError(response=response, error_format=ARMErrorFormat)\n\n return pipeline_response\n\n", "answers": [" return AsyncItemPaged("], "length": 762, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "17664e2a-4c30-4703-9c40-8c9d8bc05606", "reasoning": "The method list_by_resource_group defines inner functions prepare_request, extract_data, and get_next, mirroring the pattern used in the list method above. After defining get_next, the method should return an AsyncItemPaged instance constructed with get_next and extract_data, just as in the earlier list implementation. Therefore the next line is the return statement for AsyncItemPaged.", "reasoning_model_answer": "return AsyncItemPaged(\n get_next, extract_data\n)", "assistant_with_reasoning": "\nThe method list_by_resource_group defines inner functions prepare_request, extract_data, and get_next, mirroring the pattern used in the list method above. After defining get_next, the method should return an AsyncItemPaged instance constructed with get_next and extract_data, just as in the earlier list implementation. Therefore the next line is the return statement for AsyncItemPaged.\n\nreturn AsyncItemPaged(\n get_next, extract_data\n)", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.495, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 10822, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "return AsyncItemPaged(\n get_next, extract_data\n)", "score": 0.85, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/**\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.apache.hadoop.hbase.security.visibility;\n\nimport static org.apache.hadoop.hbase.security.visibility.VisibilityConstants.LABELS_TABLE_NAME;\nimport static org.junit.Assert.assertArrayEquals;\nimport static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.assertTrue;\n\nimport java.io.IOException;\nimport java.security.PrivilegedExceptionAction;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.concurrent.atomic.AtomicInteger;\n\nimport org.apache.commons.logging.Log;\nimport org.apache.commons.logging.LogFactory;\nimport org.apache.hadoop.conf.Configuration;\nimport org.apache.hadoop.hbase.Cell;\nimport org.apache.hadoop.hbase.CellScanner;\nimport org.apache.hadoop.hbase.CellUtil;\nimport org.apache.hadoop.hbase.HBaseConfiguration;\nimport org.apache.hadoop.hbase.HBaseTestingUtility;\nimport org.apache.hadoop.hbase.HColumnDescriptor;\nimport org.apache.hadoop.hbase.HConstants;\nimport org.apache.hadoop.hbase.HTableDescriptor;\nimport org.apache.hadoop.hbase.KeyValue;\nimport org.apache.hadoop.hbase.KeyValueUtil;\nimport org.apache.hadoop.hbase.TableName;\nimport org.apache.hadoop.hbase.Tag;\nimport org.apache.hadoop.hbase.TagRewriteCell;\nimport org.apache.hadoop.hbase.TagType;\nimport org.apache.hadoop.hbase.client.Connection;\nimport org.apache.hadoop.hbase.client.ConnectionFactory;\nimport org.apache.hadoop.hbase.client.Durability;\nimport org.apache.hadoop.hbase.client.Get;\nimport org.apache.hadoop.hbase.client.HBaseAdmin;\nimport org.apache.hadoop.hbase.client.Put;\nimport org.apache.hadoop.hbase.client.Result;\nimport org.apache.hadoop.hbase.client.ResultScanner;\nimport org.apache.hadoop.hbase.client.Scan;\nimport org.apache.hadoop.hbase.client.Table;\nimport org.apache.hadoop.hbase.client.replication.ReplicationAdmin;\nimport org.apache.hadoop.hbase.codec.KeyValueCodecWithTags;\nimport org.apache.hadoop.hbase.coprocessor.BaseRegionObserver;\nimport org.apache.hadoop.hbase.coprocessor.CoprocessorHost;\nimport org.apache.hadoop.hbase.coprocessor.ObserverContext;\nimport org.apache.hadoop.hbase.coprocessor.RegionCoprocessorEnvironment;\nimport org.apache.hadoop.hbase.protobuf.generated.VisibilityLabelsProtos.VisibilityLabelsResponse;\nimport org.apache.hadoop.hbase.regionserver.wal.WALEdit;\nimport org.apache.hadoop.hbase.replication.ReplicationEndpoint;\nimport org.apache.hadoop.hbase.security.User;\nimport org.apache.hadoop.hbase.security.visibility.VisibilityController.VisibilityReplication;\nimport org.apache.hadoop.hbase.testclassification.MediumTests;\nimport org.apache.hadoop.hbase.testclassification.SecurityTests;\nimport org.apache.hadoop.hbase.util.Bytes;\nimport org.apache.hadoop.hbase.wal.WAL.Entry;\nimport org.apache.hadoop.hbase.zookeeper.MiniZooKeeperCluster;\nimport org.apache.hadoop.hbase.zookeeper.ZooKeeperWatcher;\nimport org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.Rule;\nimport org.junit.Test;\nimport org.junit.experimental.categories.Category;\nimport org.junit.rules.TestName;\n\n@Category({ SecurityTests.class, MediumTests.class })\npublic class TestVisibilityLabelsReplication {\n private static final Log LOG = LogFactory.getLog(TestVisibilityLabelsReplication.class);\n protected static final int NON_VIS_TAG_TYPE = 100;\n protected static final String TEMP = \"temp\";\n protected static Configuration conf;\n protected static Configuration conf1;\n protected static TableName TABLE_NAME = TableName.valueOf(\"TABLE_NAME\");\n protected static ReplicationAdmin replicationAdmin;\n public static final String TOPSECRET = \"topsecret\";\n public static final String PUBLIC = \"public\";\n public static final String PRIVATE = \"private\";\n public static final String CONFIDENTIAL = \"confidential\";\n public static final String COPYRIGHT = \"\\u00A9ABC\";\n public static final String ACCENT = \"\\u0941\";\n public static final String SECRET = \"secret\";\n public static final String UNICODE_VIS_TAG = COPYRIGHT + \"\\\"\" + ACCENT + \"\\\\\" + SECRET + \"\\\"\"\n + \"\\u0027&\\\\\";\n public static HBaseTestingUtility TEST_UTIL;\n public static HBaseTestingUtility TEST_UTIL1;\n public static final byte[] row1 = Bytes.toBytes(\"row1\");\n public static final byte[] row2 = Bytes.toBytes(\"row2\");\n public static final byte[] row3 = Bytes.toBytes(\"row3\");\n public static final byte[] row4 = Bytes.toBytes(\"row4\");\n public final static byte[] fam = Bytes.toBytes(\"info\");\n public final static byte[] qual = Bytes.toBytes(\"qual\");\n public final static byte[] value = Bytes.toBytes(\"value\");\n protected static ZooKeeperWatcher zkw1;\n protected static ZooKeeperWatcher zkw2;\n protected static int expected[] = { 4, 6, 4, 0, 3 };\n private static final String NON_VISIBILITY = \"non-visibility\";\n protected static String[] expectedVisString = {\n \"(\\\"secret\\\"&\\\"topsecret\\\"&\\\"public\\\")|(\\\"topsecret\\\"&\\\"confidential\\\")\",\n \"(\\\"public\\\"&\\\"private\\\")|(\\\"topsecret\\\"&\\\"private\\\")|\"\n + \"(\\\"confidential\\\"&\\\"public\\\")|(\\\"topsecret\\\"&\\\"confidential\\\")\",\n \"(!\\\"topsecret\\\"&\\\"secret\\\")|(!\\\"topsecret\\\"&\\\"confidential\\\")\",\n \"(\\\"secret\\\"&\\\"\" + COPYRIGHT + \"\\\\\\\"\" + ACCENT + \"\\\\\\\\\" + SECRET + \"\\\\\\\"\" + \"\\u0027&\\\\\\\\\"\n + \"\\\")\" };\n\n @Rule\n public final TestName TEST_NAME = new TestName();\n public static User SUPERUSER, USER1;\n\n @Before\n public void setup() throws Exception {\n // setup configuration\n conf = HBaseConfiguration.create();\n conf.setBoolean(HConstants.DISTRIBUTED_LOG_REPLAY_KEY, false);\n conf.setBoolean(\"hbase.online.schema.update.enable\", true);\n conf.setInt(\"hfile.format.version\", 3);\n conf.set(HConstants.ZOOKEEPER_ZNODE_PARENT, \"/1\");\n conf.setInt(\"replication.source.size.capacity\", 10240);\n conf.setLong(\"replication.source.sleepforretries\", 100);\n conf.setInt(\"hbase.regionserver.maxlogs\", 10);\n conf.setLong(\"hbase.master.logcleaner.ttl\", 10);\n conf.setInt(\"zookeeper.recovery.retry\", 1);\n conf.setInt(\"zookeeper.recovery.retry.intervalmill\", 10);\n conf.setBoolean(\"dfs.support.append\", true);\n conf.setLong(HConstants.THREAD_WAKE_FREQUENCY, 100);\n conf.setInt(\"replication.stats.thread.period.seconds\", 5);\n conf.setBoolean(\"hbase.tests.use.shortcircuit.reads\", false);\n setVisibilityLabelServiceImpl(conf);\n conf.setBoolean(HConstants.REPLICATION_ENABLE_KEY, HConstants.REPLICATION_ENABLE_DEFAULT);\n conf.setStrings(HConstants.REPLICATION_CODEC_CONF_KEY, KeyValueCodecWithTags.class.getName());\n VisibilityTestUtil.enableVisiblityLabels(conf);\n conf.set(CoprocessorHost.REGIONSERVER_COPROCESSOR_CONF_KEY,\n VisibilityReplication.class.getName());\n conf.setStrings(CoprocessorHost.USER_REGION_COPROCESSOR_CONF_KEY,\n SimpleCP.class.getName());\n // Have to reset conf1 in case zk cluster location different\n // than default\n conf.setClass(VisibilityUtils.VISIBILITY_LABEL_GENERATOR_CLASS, SimpleScanLabelGenerator.class,\n ScanLabelGenerator.class);\n conf.set(\"hbase.superuser\", User.getCurrent().getShortName());\n SUPERUSER = User.createUserForTesting(conf, User.getCurrent().getShortName(),\n new String[] { \"supergroup\" });\n // User.createUserForTesting(conf, User.getCurrent().getShortName(), new\n // String[] { \"supergroup\" });\n USER1 = User.createUserForTesting(conf, \"user1\", new String[] {});\n TEST_UTIL = new HBaseTestingUtility(conf);\n TEST_UTIL.startMiniZKCluster();\n MiniZooKeeperCluster miniZK = TEST_UTIL.getZkCluster();\n zkw1 = new ZooKeeperWatcher(conf, \"cluster1\", null, true);\n replicationAdmin = new ReplicationAdmin(conf);\n\n // Base conf2 on conf1 so it gets the right zk cluster.\n conf1 = HBaseConfiguration.create(conf);\n conf1.setInt(\"hfile.format.version\", 3);\n conf1.set(HConstants.ZOOKEEPER_ZNODE_PARENT, \"/2\");\n conf1.setInt(HConstants.HBASE_CLIENT_RETRIES_NUMBER, 6);\n conf1.setBoolean(\"dfs.support.append\", true);\n conf1.setBoolean(\"hbase.tests.use.shortcircuit.reads\", false);\n conf.setBoolean(HConstants.REPLICATION_ENABLE_KEY, HConstants.REPLICATION_ENABLE_DEFAULT);\n conf1.setStrings(HConstants.REPLICATION_CODEC_CONF_KEY, KeyValueCodecWithTags.class.getName());\n conf1.setStrings(CoprocessorHost.USER_REGION_COPROCESSOR_CONF_KEY,\n TestCoprocessorForTagsAtSink.class.getName());\n // setVisibilityLabelServiceImpl(conf1);\n USER1 = User.createUserForTesting(conf1, \"user1\", new String[] {});\n TEST_UTIL1 = new HBaseTestingUtility(conf1);\n TEST_UTIL1.setZkCluster(miniZK);\n zkw2 = new ZooKeeperWatcher(conf1, \"cluster2\", null, true);\n replicationAdmin.addPeer(\"2\", TEST_UTIL1.getClusterKey());\n\n TEST_UTIL.startMiniCluster(1);\n // Wait for the labels table to become available\n TEST_UTIL.waitTableEnabled(LABELS_TABLE_NAME.getName(), 50000);\n TEST_UTIL1.startMiniCluster(1);\n HBaseAdmin hBaseAdmin = TEST_UTIL.getHBaseAdmin();\n HTableDescriptor table = new HTableDescriptor(TABLE_NAME);\n HColumnDescriptor desc = new HColumnDescriptor(fam);\n desc.setScope(HConstants.REPLICATION_SCOPE_GLOBAL);\n table.addFamily(desc);\n try {\n hBaseAdmin.createTable(table);\n } finally {\n if (hBaseAdmin != null) {\n hBaseAdmin.close();\n }\n }\n HBaseAdmin hBaseAdmin1 = TEST_UTIL1.getHBaseAdmin();\n try {\n hBaseAdmin1.createTable(table);\n } finally {\n if (hBaseAdmin1 != null) {\n hBaseAdmin1.close();\n }\n }\n addLabels();\n setAuths(conf);\n setAuths(conf1);\n }\n\n protected static void setVisibilityLabelServiceImpl(Configuration conf) {\n conf.setClass(VisibilityLabelServiceManager.VISIBILITY_LABEL_SERVICE_CLASS,\n DefaultVisibilityLabelServiceImpl.class, VisibilityLabelService.class);\n }\n\n @Test\n public void testVisibilityReplication() throws Exception {\n int retry = 0;\n try (Table table = writeData(TABLE_NAME, \"(\" + SECRET + \"&\" + PUBLIC + \")\" + \"|(\" + CONFIDENTIAL\n + \")&(\" + TOPSECRET + \")\", \"(\" + PRIVATE + \"|\" + CONFIDENTIAL + \")&(\" + PUBLIC + \"|\"\n + TOPSECRET + \")\", \"(\" + SECRET + \"|\" + CONFIDENTIAL + \")\" + \"&\" + \"!\" + TOPSECRET,\n CellVisibility.quote(UNICODE_VIS_TAG) + \"&\" + SECRET);) {\n Scan s = new Scan();\n s.setAuthorizations(new Authorizations(SECRET, CONFIDENTIAL, PRIVATE, TOPSECRET,\n UNICODE_VIS_TAG));\n ResultScanner scanner = table.getScanner(s);\n Result[] next = scanner.next(4);\n\n assertTrue(next.length == 4);\n CellScanner cellScanner = next[0].cellScanner();\n cellScanner.advance();\n Cell current = cellScanner.current();\n assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(),\n current.getRowLength(), row1, 0, row1.length));\n cellScanner = next[1].cellScanner();", "answers": [" cellScanner.advance();"], "length": 856, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "1e48396c-0818-4d54-9f5a-1f63f7015a61", "reasoning": "In the test, after obtaining the scanner results, the code processes each Result's cells. For the first result, it creates a CellScanner, calls advance(), gets the current cell, and asserts the row matches row1. The next step repeats this for the second result: after assigning cellScanner = next[1].cellScanner(); the immediate next operation is to advance the scanner to the first cell, i.e., cellScanner.advance();", "reasoning_model_answer": "cellScanner.advance();", "assistant_with_reasoning": "\nIn the test, after obtaining the scanner results, the code processes each Result's cells. For the first result, it creates a CellScanner, calls advance(), gets the current cell, and asserts the row matches row1. The next step repeats this for the second result: after assigning cellScanner = next[1].cellScanner(); the immediate next operation is to advance the scanner to the first cell, i.e., cellScanner.advance();\n\ncellScanner.advance();", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.158, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 11532, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "cellScanner.advance();", "score": 0.88, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/****************************************************************************\n * Copyright (C) 2012 ecsec GmbH.\n * All rights reserved.\n * Contact: ecsec GmbH (info@ecsec.de)\n *\n * This file is part of the Open eCard App.\n *\n * GNU General Public License Usage\n * This file may be used under the terms of the GNU General Public\n * License version 3.0 as published by the Free Software Foundation\n * and appearing in the file LICENSE.GPL included in the packaging of\n * this file. Please review the following information to ensure the\n * GNU General Public License version 3.0 requirements will be met:\n * http://www.gnu.org/copyleft/gpl.html.\n *\n * Other Usage\n * Alternatively, this file may be used in accordance with the terms\n * and conditions contained in a signed written agreement between\n * you and ecsec GmbH.\n *\n ***************************************************************************/\n\npackage org.openecard.common.util;\n\nimport java.io.PrintWriter;\nimport java.io.StringWriter;\nimport org.openecard.bouncycastle.util.Arrays;\n\n\n/**\n * A set of utility functions for Byte and Byte Array.\n *\n * @author Moritz Horsch \n * @author Tobias Wich \n * @author Dirk Petrautzki \n */\npublic class ByteUtils {\n\n /**\n * Clone a byte array.\n *\n * @param input the byte array to clone\n * @return new byte array, or null if input is null\n */\n public static byte[] clone(byte[] input) {\n\tif (input == null) {\n\t return null;\n\t}\n\tbyte[] ret = new byte[input.length];\n\tSystem.arraycopy(input, 0, ret, 0, input.length);\n\treturn ret;\n }\n\n /**\n * Concatenate a byte array.\n *\n * @param x byte array\n * @param y byte array\n * @return x || y\n */\n public static byte[] concatenate(byte[] x, byte[] y) {\n\tif (x == null) {\n\t return y;\n\t}\n\tif (y == null) {\n\t return x;\n\t}\n\tbyte[] ret = new byte[x.length + y.length];\n\tSystem.arraycopy(x, 0, ret, 0, x.length);\n\tSystem.arraycopy(y, 0, ret, x.length, y.length);\n\treturn ret;\n }\n\n /**\n * Concatenate a byte array.\n *\n * @param x byte\n * @param y byte array\n * @return x || y\n */\n public static byte[] concatenate(byte x, byte[] y) {\n\treturn concatenate(new byte[]{x}, y);\n }\n\n /**\n * Concatenate a byte array.\n *\n * @param x byte array\n * @param y byte\n * @return x || y\n */\n public static byte[] concatenate(byte[] x, byte y) {\n\treturn concatenate(x, new byte[]{y});\n }\n\n /**\n * Concatenate a byte array.\n *\n * @param x byte\n * @param y byte\n * @return x || y\n */\n public static byte[] concatenate(byte x, byte y) {\n\treturn concatenate(new byte[]{x}, new byte[]{y});\n }\n\n /**\n * Cut leading null bytes of a byte array.\n *\n * @param input\n * @return byte array without leading null bytes\n */\n public static byte[] cutLeadingNullBytes(byte[] input) {\n\tif (input == null) {\n\t return null;\n\t}\n\n\tint i;\n\tfor (i = 0; i < input.length - 1; i++) {\n\t if (input[i] != (byte) 0x00) {\n\t\tbreak;\n\t }\n\t}\n\treturn copy(input, i, input.length - i);\n }\n\n /**\n * Removes leading null byte from the input byte array.\n *\n * @param input Byte array\n * @return byte array without leading null bytes\n */\n public static byte[] cutLeadingNullByte(byte[] input) {\n\tif (input == null) {\n\t return null;\n\t}\n\tif (input[0] != (byte) 0x00) {\n\t return ByteUtils.clone(input);\n\t}\n\treturn copy(input, 1, input.length - 1);\n }\n\n /**\n * Copy of range.\n *\n * @param input the input\n * @param offset\n * @param length the length\n * @return the byte[]\n */\n public static byte[] copy(byte[] input, int offset, int length) {\n\tif (input == null) {\n\t return null;\n\t}\n\tbyte[] tmp = new byte[length];\n\tSystem.arraycopy(input, offset, tmp, 0, length);\n\treturn tmp;\n }\n\n /**\n * Compare two byte arrays.\n *\n * @param x byte array\n * @param y byte array\n * @return true if x = y, otherwise false\n */\n public static boolean compare(byte[] x, byte[] y) {\n\tif (y == null || x == null) {\n\t return false;\n\t}\n\tif (x.length != y.length) {\n\t return false;\n\t}\n\treturn Arrays.areEqual(x, y);\n }\n\n /**\n * Compare two byte arrays.\n *\n * @param x byte\n * @param y byte array\n * @return true if x = y, otherwise false\n */\n public static boolean compare(byte x, byte[] y) {\n\treturn compare(new byte[]{x}, y);\n }\n\n /**\n * Compare two byte arrays.\n *\n * @param x byte array\n * @param y byte\n * @return true if x = y, otherwise false\n */\n public static boolean compare(byte[] x, byte y) {\n\treturn compare(x, new byte[]{y});\n }\n\n /**\n * Compare two bytes.\n *\n * @param x byte\n * @param y byte\n * @return true if x = y, otherwise false\n */", "answers": [" public static boolean compare(byte x, byte y) {"], "length": 738, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "08bc13d1-5e81-4073-a8a3-625c40b3f94e", "reasoning": "The comment just ended describing a method that compares two primitive bytes. Following the pattern of previous overloads, the next line should be the method signature for comparing two bytes, i.e., the line that starts the method definition.", "reasoning_model_answer": "public static boolean compare(byte x, byte y) {", "assistant_with_reasoning": "\nThe comment just ended describing a method that compares two primitive bytes. Following the pattern of previous overloads, the next line should be the method signature for comparing two bytes, i.e., the line that starts the method definition.\n\npublic static boolean compare(byte x, byte y) {", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.554, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 4993, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "public static boolean compare(byte x, byte y) {", "score": 0.96, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "# Copyright 2016 Google Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Define API Loggers.\"\"\"\n\nfrom google.protobuf.json_format import MessageToDict\nfrom google.cloud._helpers import _datetime_to_rfc3339\nfrom google.cloud.logging.resource import Resource\n\n\n_GLOBAL_RESOURCE = Resource(type='global', labels={})\n\n\nclass Logger(object):\n \"\"\"Loggers represent named targets for log entries.\n\n See\n https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.logs\n\n :type name: str\n :param name: the name of the logger\n\n :type client: :class:`google.cloud.logging.client.Client`\n :param client: A client which holds credentials and project configuration\n for the logger (which requires a project).\n\n :type labels: dict\n :param labels: (optional) mapping of default labels for entries written\n via this logger.\n \"\"\"\n def __init__(self, name, client, labels=None):\n self.name = name\n self._client = client\n self.labels = labels\n\n @property\n def client(self):\n \"\"\"Clent bound to the logger.\"\"\"\n return self._client\n\n @property\n def project(self):\n \"\"\"Project bound to the logger.\"\"\"\n return self._client.project\n\n @property\n def full_name(self):\n \"\"\"Fully-qualified name used in logging APIs\"\"\"\n return 'projects/%s/logs/%s' % (self.project, self.name)\n\n @property\n def path(self):\n \"\"\"URI path for use in logging APIs\"\"\"\n return '/%s' % (self.full_name,)\n\n def _require_client(self, client):\n \"\"\"Check client or verify over-ride.\n\n :type client: :class:`~google.cloud.logging.client.Client` or\n ``NoneType``\n :param client: the client to use. If not passed, falls back to the\n ``client`` stored on the current logger.\n\n :rtype: :class:`google.cloud.logging.client.Client`\n :returns: The client passed in or the currently bound client.\n \"\"\"\n if client is None:\n client = self._client\n return client\n\n def batch(self, client=None):\n \"\"\"Return a batch to use as a context manager.\n\n :type client: :class:`~google.cloud.logging.client.Client` or\n ``NoneType``\n :param client: the client to use. If not passed, falls back to the\n ``client`` stored on the current topic.\n\n :rtype: :class:`Batch`\n :returns: A batch to use as a context manager.\n \"\"\"\n client = self._require_client(client)\n return Batch(self, client)\n\n def _make_entry_resource(self, text=None, info=None, message=None,\n labels=None, insert_id=None, severity=None,\n http_request=None, timestamp=None,\n resource=_GLOBAL_RESOURCE):\n \"\"\"Return a log entry resource of the appropriate type.\n\n Helper for :meth:`log_text`, :meth:`log_struct`, and :meth:`log_proto`.\n\n Only one of ``text``, ``info``, or ``message`` should be passed.\n\n :type text: str\n :param text: (Optional) text payload\n\n :type info: dict\n :param info: (Optional) struct payload\n\n :type message: :class:`~google.protobuf.message.Message`\n :param message: (Optional) The protobuf payload to log.\n\n :type labels: dict\n :param labels: (Optional) labels passed in to calling method.\n\n :type insert_id: str\n :param insert_id: (Optional) unique ID for log entry.\n\n :type severity: str\n :param severity: (Optional) severity of event being logged.\n\n :type http_request: dict\n :param http_request: (Optional) info about HTTP request associated with\n the entry\n\n :type timestamp: :class:`datetime.datetime`\n :param timestamp: (Optional) timestamp of event being logged.\n\n :type resource: :class:`~google.cloud.logging.resource.Resource`\n :param resource: (Optional) Monitored resource of the entry\n\n :rtype: dict\n :returns: The JSON resource created.\n \"\"\"\n entry = {\n 'logName': self.full_name,\n 'resource': resource._to_dict(),\n }\n\n if text is not None:\n entry['textPayload'] = text\n\n if info is not None:\n entry['jsonPayload'] = info\n\n if message is not None:\n # NOTE: If ``message`` contains an ``Any`` field with an\n # unknown type, this will fail with a ``TypeError``.\n # However, since ``message`` will be provided by a user,\n # the assumption is that any types needed for the\n # protobuf->JSON conversion will be known from already\n # imported ``pb2`` modules.\n entry['protoPayload'] = MessageToDict(message)\n\n if labels is None:\n labels = self.labels\n\n if labels is not None:\n entry['labels'] = labels\n\n if insert_id is not None:\n entry['insertId'] = insert_id\n\n if severity is not None:\n entry['severity'] = severity\n\n if http_request is not None:\n entry['httpRequest'] = http_request\n\n if timestamp is not None:\n entry['timestamp'] = _datetime_to_rfc3339(timestamp)\n\n return entry\n\n def log_text(self, text, client=None, labels=None, insert_id=None,\n severity=None, http_request=None, timestamp=None,\n resource=_GLOBAL_RESOURCE):\n \"\"\"API call: log a text message via a POST request\n\n See\n https://cloud.google.com/logging/docs/reference/v2/rest/v2/entries/write\n\n :type text: str\n :param text: the log message.\n\n :type client: :class:`~google.cloud.logging.client.Client` or\n ``NoneType``\n :param client: the client to use. If not passed, falls back to the\n ``client`` stored on the current logger.\n\n :type labels: dict\n :param labels: (optional) mapping of labels for the entry.\n\n :type insert_id: str\n :param insert_id: (optional) unique ID for log entry.\n\n :type severity: str\n :param severity: (optional) severity of event being logged.\n\n :type http_request: dict\n :param http_request: (optional) info about HTTP request associated with\n the entry\n\n :type resource: :class:`~google.cloud.logging.resource.Resource`\n :param resource: Monitored resource of the entry, defaults\n to the global resource type.\n\n :type timestamp: :class:`datetime.datetime`\n :param timestamp: (optional) timestamp of event being logged.\n \"\"\"\n client = self._require_client(client)\n entry_resource = self._make_entry_resource(\n text=text, labels=labels, insert_id=insert_id, severity=severity,\n http_request=http_request, timestamp=timestamp, resource=resource)\n client.logging_api.write_entries([entry_resource])\n\n def log_struct(self, info, client=None, labels=None, insert_id=None,\n severity=None, http_request=None, timestamp=None,\n resource=_GLOBAL_RESOURCE):\n \"\"\"API call: log a structured message via a POST request\n\n See\n https://cloud.google.com/logging/docs/reference/v2/rest/v2/entries/write\n\n :type info: dict\n :param info: the log entry information\n\n :type client: :class:`~google.cloud.logging.client.Client` or\n ``NoneType``\n :param client: the client to use. If not passed, falls back to the\n ``client`` stored on the current logger.\n\n :type labels: dict\n :param labels: (optional) mapping of labels for the entry.\n\n :type insert_id: str", "answers": [" :param insert_id: (optional) unique ID for log entry."], "length": 834, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "c0925a84-ef9e-442a-8f9a-8fdeb88b4152", "reasoning": "The code is defining the log_struct method. The docstring lists parameter types and descriptions. It currently ends at ':type insert_id: str', so the next line should be the corresponding ':param insert_id' description, matching the pattern used earlier in log_text.", "reasoning_model_answer": ":param insert_id: (optional) unique ID for log entry.", "assistant_with_reasoning": "\nThe code is defining the log_struct method. The docstring lists parameter types and descriptions. It currently ends at ':type insert_id: str', so the next line should be the corresponding ':param insert_id' description, matching the pattern used earlier in log_text.\n\n:param insert_id: (optional) unique ID for log entry.", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.911, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 8499, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": ":param insert_id: (optional) unique ID for log entry.", "score": 0.93, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "package com.dropbox.chooser.android;\n\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.Map;\n\nimport android.annotation.TargetApi;\nimport android.app.Activity;\nimport android.app.Fragment;\nimport android.app.FragmentManager;\nimport android.content.ActivityNotFoundException;\nimport android.content.ContentResolver;\nimport android.content.Intent;\nimport android.content.pm.PackageManager;\nimport android.content.pm.ResolveInfo;\nimport android.net.Uri;\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.os.Parcelable;\n\n\n/**\n * DbxChooser is a utility class to launch Dropbox's Android Chooser.\n *\n * Example use:\n *

    \n *   new DbxChooser(APP_KEY)\n *       .forResultType(DbxChooser.ResultType.PREVIEW_LINK)\n *       .limitToExtensions(\".png\", \".jpg\", \".jpeg\")\n *       .launch(this, CHOOSER_REQUEST_CODE);\n * 

    \n * \n *

    \n * The result will be received in the onActivityResult callback of the Activity or Fragment supplied to {@link DbxChooser#launch}.\n *

    \n * \n */\npublic class DbxChooser {\n\n public enum ResultType {\n PREVIEW_LINK(\"com.dropbox.android.intent.action.GET_PREVIEW\"),\n DIRECT_LINK(\"com.dropbox.android.intent.action.GET_DIRECT\"),\n FILE_CONTENT(\"com.dropbox.android.intent.action.GET_CONTENT\");\n\n final String action; // package-private\n\n ResultType(String action) {\n this.action = action;\n }\n }\n\n private static final String[] intentResultExtras = {\n \"EXTRA_CHOOSER_RESULTS\", // new unified result\n \"EXTRA_PREVIEW_RESULTS\", // these others for backwards compatibility\n \"EXTRA_CONTENT_RESULTS\",\n };\n\n /**\n * This is passed in the Intent to identify the version of the\n * client SDK. It should be incremented for any change in behavior\n * in this code.\n */\n private static final int SDK_VERSION = 2;\n\n private String mAction = ResultType.FILE_CONTENT.action;\n\n private boolean mForceNotAvailable = false;\n\n private final String mAppKey;\n\n\n public DbxChooser(String appKey) {\n if (appKey == null || appKey.length() == 0) {\n throw new IllegalArgumentException(\"An app key must be supplied.\");\n }\n mAppKey = appKey;\n }\n \n\n private static boolean isChooserAvailable(PackageManager pm) {\n ResultType[] resultTypes = { ResultType.FILE_CONTENT, ResultType.PREVIEW_LINK, ResultType.DIRECT_LINK };\n for (ResultType resultType : resultTypes) {\n ResolveInfo ri = pm.resolveActivity(new Intent(resultType.action), PackageManager.MATCH_DEFAULT_ONLY);\n if (ri == null) {\n return false;\n }\n }\n return true;\n }\n\n private boolean chooserAvailable(PackageManager pm) {\n if (mForceNotAvailable) {\n return false;\n }\n return isChooserAvailable(pm);\n }\n\n /**\n * Requests that the Chooser return a particular type of result.\n * If this is not called, the default result type is FILE_CONTENT, which\n * returns a URI that can be opened to retrieve the contents of the chosen\n * file.\n */\n public DbxChooser forResultType(ResultType resultType) {\n if (resultType == null) {\n throw new IllegalArgumentException(\"An app key must be supplied.\");\n }\n mAction = resultType.action;\n return this;\n }\n\n\n /**\n * For testing purposes, this causes DbxChooser to behave as if\n * the Dropbox Chooser isn't available.\n */\n public DbxChooser pretendNotAvailable() {\n mForceNotAvailable = true;\n return this;\n }\n\n private Intent getIntent() {\n Intent intent = new Intent(mAction).putExtra(\"EXTRA_APP_KEY\", mAppKey);\n intent.putExtra(\"EXTRA_SDK_VERSION\", SDK_VERSION);\n return intent;\n }\n\n /**\n * Launches the Chooser with the supplied request code.\n * The result will be received in the onActivityResult callback of the\n * supplied Activity.\n */\n public void launch(Activity act, int requestCode) throws ActivityNotFoundException {\n final Activity mAct = act;\n ActivityLike thing = new ActivityLike() {\n\n @Override\n public void startActivity(Intent intent)\n throws ActivityNotFoundException {\n mAct.startActivity(intent);\n }\n\n @Override\n public void startActivityForResult(Intent intent, int requestCode)\n throws ActivityNotFoundException {\n mAct.startActivityForResult(intent, requestCode);\n }\n\n @Override\n public ContentResolver getContentResolver() {\n return mAct.getContentResolver();\n }\n\n @Override\n public PackageManager getPackageManager() {\n return mAct.getPackageManager();\n }\n\n @Override\n public FragmentManager getFragmentManager() {\n try {\n return mAct.getFragmentManager();\n } catch (NoSuchMethodError e) {\n return null;\n }\n }\n\n @Override\n public android.support.v4.app.FragmentManager getSupportFragmentManager() {\n if (mAct instanceof android.support.v4.app.FragmentActivity) {\n return ((android.support.v4.app.FragmentActivity) mAct).getSupportFragmentManager();\n } else {\n return null;\n }\n }\n };\n launch(thing, requestCode);\n }\n\n /**\n * Launches the Chooser with the supplied request code.\n * The result will be received in the onActivityResult callback of the\n * supplied Fragment. If the supplied Fragment is not attached to an Activity,\n * this will throw an IllegalStateException.\n * \n * NOTE: this method requires Android API at least version 11.\n */\n @TargetApi(Build.VERSION_CODES.HONEYCOMB)\n public void launch(Fragment frag, int requestCode) throws ActivityNotFoundException {\n final Fragment mFrag = frag;\n ActivityLike thing = new ActivityLike() {\n\n @Override\n public void startActivity(Intent intent)\n throws ActivityNotFoundException {\n mFrag.startActivity(intent);\n }\n\n @Override\n public void startActivityForResult(Intent intent, int requestCode)\n throws ActivityNotFoundException {\n mFrag.startActivityForResult(intent, requestCode);\n }\n\n @Override\n public ContentResolver getContentResolver() {\n Activity act = mFrag.getActivity();\n if (act == null) {\n return null;\n }\n return act.getContentResolver();\n }\n\n @Override\n public PackageManager getPackageManager() {\n Activity act = mFrag.getActivity();\n if (act == null) {\n return null;\n }\n return act.getPackageManager();\n }\n\n @Override\n public FragmentManager getFragmentManager() {\n Activity act = mFrag.getActivity();\n if (act == null) {\n return null;\n }\n return act.getFragmentManager();\n }\n\n @Override\n public android.support.v4.app.FragmentManager getSupportFragmentManager() {\n return null;\n }\n };\n launch(thing, requestCode);\n }\n\n /**\n * Launches the Chooser with the supplied request code.\n * The result will be received in the onActivityResult callback of the\n * supplied Fragment. If the supplied Fragment is not attached to an Activity,\n * this will throw an IllegalStateException.\n */\n public void launch(android.support.v4.app.Fragment frag, int requestCode) throws ActivityNotFoundException {\n final android.support.v4.app.Fragment mFrag = frag;\n ActivityLike thing = new ActivityLike() {\n\n @Override\n public void startActivity(Intent intent)\n throws ActivityNotFoundException {", "answers": [" mFrag.startActivity(intent);"], "length": 753, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "b97da6a3-74f7-4d6f-a931-56ab65f3a1c8", "reasoning": "In the support‑v4 fragment overload, we create an anonymous ActivityLike. The first method to implement is startActivity(Intent). For a support fragment, the way to launch an activity is to call its startActivity method, just like in the other overloads. Therefore the next line should invoke startActivity on the captured fragment variable mFrag with the given intent.", "reasoning_model_answer": "mFrag.startActivity(intent);", "assistant_with_reasoning": "\nIn the support‑v4 fragment overload, we create an anonymous ActivityLike. The first method to implement is startActivity(Intent). For a support fragment, the way to launch an activity is to call its startActivity method, just like in the other overloads. Therefore the next line should invoke startActivity on the captured fragment variable mFrag with the given intent.\n\nmFrag.startActivity(intent);", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 2.981, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 8434, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "mFrag.startActivity(intent);", "score": 0.78, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "///////////////////////////////////////////////////////////////////////////\n// __ _ _ ________ //\n// / / ____ ____ _(_)____/ | / / ____/ //\n// / / / __ \\/ __ `/ / ___/ |/ / / __ //\n// / /___/ /_/ / /_/ / / /__/ /| / /_/ / //\n// /_____/\\____/\\__, /_/\\___/_/ |_/\\____/ //\n// /____/ //\n// //\n// The Next Generation Logic Library //\n// //\n///////////////////////////////////////////////////////////////////////////\n// //\n// Copyright 2015-20xx Christoph Zengler //\n// //\n// Licensed under the Apache License, Version 2.0 (the \"License\"); //\n// you may not use this file except in compliance with the License. //\n// You may obtain a copy of the License at //\n// //\n// http://www.apache.org/licenses/LICENSE-2.0 //\n// //\n// Unless required by applicable law or agreed to in writing, software //\n// distributed under the License is distributed on an \"AS IS\" BASIS, //\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or //\n// implied. See the License for the specific language governing //\n// permissions and limitations under the License. //\n// //\n///////////////////////////////////////////////////////////////////////////\n\n/*\n * Open-WBO -- Copyright (c) 2013-2015, Ruben Martins, Vasco Manquinho, Ines Lynce\n *

    \n * Permission is hereby granted, free of charge, to any person obtaining a copy of\n * this software and associated documentation files (the \"Software\"), to deal in\n * the Software without restriction, including without limitation the rights to\n * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of\n * the Software, and to permit persons to whom the Software is furnished to do so,\n * subject to the following conditions:\n *

    \n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *

    \n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\n * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\n * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\n * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n */\n\npackage org.logicng.solvers.maxsat.encodings;\n\nimport static org.logicng.solvers.sat.MiniSatStyleSolver.LIT_UNDEF;\nimport static org.logicng.solvers.sat.MiniSatStyleSolver.mkLit;\nimport static org.logicng.solvers.sat.MiniSatStyleSolver.not;\n\nimport org.logicng.collections.LNGIntVector;\nimport org.logicng.solvers.maxsat.algorithms.MaxSAT;\nimport org.logicng.solvers.sat.MiniSatStyleSolver;\n\n/**\n * Encodes that at most 'rhs' literals can be assigned value true. Uses the modular totalizer encoding for\n * translating the cardinality constraint into CNF.\n * @version 2.0.0\n * @since 1.0\n */\npublic class ModularTotalizer extends Encoding {\n\n protected static final int LIT_ERROR = -2;\n\n protected final int h0;\n protected final LNGIntVector cardinalityUpoutlits;\n protected final LNGIntVector cardinalityLwoutlits;\n protected int modulo;\n protected LNGIntVector cardinalityInlits;\n protected int currentCardinalityRhs;\n\n /**\n * Constructs a new modular totalizer.\n */\n ModularTotalizer() {\n this.h0 = LIT_UNDEF;\n this.modulo = -1;\n this.currentCardinalityRhs = -1;\n this.cardinalityInlits = new LNGIntVector();\n this.cardinalityUpoutlits = new LNGIntVector();\n this.cardinalityLwoutlits = new LNGIntVector();\n }\n\n /**\n * Sets the modulo value.\n * @param m the modulo value\n */\n void setModulo(final int m) {\n this.modulo = m;\n }\n\n /**\n * Returns {@code true} if an encoding was created, {@code false} otherwise.\n * @return {@code true} if an encoding was created\n */\n boolean hasCreatedEncoding() {\n return this.hasEncoding;\n }\n\n /**\n * Encodes a cardinality constraint.\n * @param s the solver\n * @param lits the literals of the constraint\n * @param rhs the right hand side of the constraint\n */\n public void encode(final MiniSatStyleSolver s, final LNGIntVector lits, final int rhs) {\n assert lits.size() > 0;\n this.hasEncoding = false;\n this.cardinalityUpoutlits.clear();\n this.cardinalityLwoutlits.clear();\n if (rhs == 0) {\n for (int i = 0; i < lits.size(); i++) {\n addUnitClause(s, not(lits.get(i)));\n }\n return;\n }\n assert rhs >= 1 && rhs <= lits.size();\n if (rhs == lits.size()) {\n return;\n }\n this.hasEncoding = true;\n int mod = (int) Math.ceil(Math.sqrt(rhs + 1.0));\n if (this.modulo == -1) {\n this.modulo = mod;\n } else {\n mod = this.modulo;\n }\n for (int i = 0; i < lits.size() / mod; i++) {\n final int p = mkLit(s.nVars(), false);\n MaxSAT.newSATVariable(s);\n this.cardinalityUpoutlits.push(p);\n }\n for (int i = 0; i < mod - 1; i++) {\n final int p = mkLit(s.nVars(), false);\n MaxSAT.newSATVariable(s);\n this.cardinalityLwoutlits.push(p);\n }\n this.cardinalityInlits = new LNGIntVector(lits);\n this.currentCardinalityRhs = rhs + 1;\n if (this.cardinalityUpoutlits.size() == 0) {\n this.cardinalityUpoutlits.push(this.h0);\n }\n this.toCNF(s, mod, this.cardinalityUpoutlits, this.cardinalityLwoutlits, lits.size());\n assert this.cardinalityInlits.size() == 0;\n this.update(s, rhs);\n }\n\n /**\n * Updates the right hand side of the current constraint.\n * @param s the solver\n * @param rhs the new right hand side\n */\n public void update(final MiniSatStyleSolver s, final int rhs) {\n assert this.currentCardinalityRhs != -1;\n assert this.hasEncoding;\n this.encodeOutput(s, rhs);\n this.currentCardinalityRhs = rhs + 1;\n }\n\n protected void encodeOutput(final MiniSatStyleSolver s, final int rhs) {\n assert this.hasEncoding;\n assert this.cardinalityUpoutlits.size() != 0 || this.cardinalityLwoutlits.size() != 0;\n final int mod = this.modulo;\n final int ulimit = (rhs + 1) / mod;", "answers": [" final int llimit = (rhs + 1) - ulimit * mod;"], "length": 810, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "60ff7757-e8bc-4bbb-8c71-e9ad4b30ad03", "reasoning": "The method encodeOutput begins by asserting encoding exists, then retrieves the modulo value. It computes the upper limit as the integer division of (rhs+1) by mod. The next logical step is to compute the lower limit, i.e., the remainder of (rhs+1) divided by mod, which will be used later to set the appropriate output literals. Therefore the next line defines llimit as the remainder.", "reasoning_model_answer": "final int llimit = (rhs + 1) % mod;", "assistant_with_reasoning": "\nThe method encodeOutput begins by asserting encoding exists, then retrieves the modulo value. It computes the upper limit as the integer division of (rhs+1) by mod. The next logical step is to compute the lower limit, i.e., the remainder of (rhs+1) divided by mod, which will be used later to set the appropriate output literals. Therefore the next line defines llimit as the remainder.\n\nfinal int llimit = (rhs + 1) % mod;", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.382, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 7384, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "final int llimit = (rhs + 1) % mod;", "score": 0.78, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "\"\"\"Support for HomeMatic devices.\"\"\"\nfrom datetime import timedelta\nfrom functools import partial\nimport logging\nimport socket\n\nimport voluptuous as vol\n\nfrom homeassistant.const import (\n ATTR_ENTITY_ID, ATTR_NAME, CONF_HOST, CONF_HOSTS, CONF_PASSWORD,\n CONF_PLATFORM, CONF_SSL, CONF_USERNAME, CONF_VERIFY_SSL,\n EVENT_HOMEASSISTANT_STOP, STATE_UNKNOWN)\nfrom homeassistant.helpers import discovery\nimport homeassistant.helpers.config_validation as cv\nfrom homeassistant.helpers.entity import Entity\n\n_LOGGER = logging.getLogger(__name__)\n\nDOMAIN = 'homematic'\n\nSCAN_INTERVAL_HUB = timedelta(seconds=300)\nSCAN_INTERVAL_VARIABLES = timedelta(seconds=30)\n\nDISCOVER_SWITCHES = 'homematic.switch'\nDISCOVER_LIGHTS = 'homematic.light'\nDISCOVER_SENSORS = 'homematic.sensor'\nDISCOVER_BINARY_SENSORS = 'homematic.binary_sensor'\nDISCOVER_COVER = 'homematic.cover'\nDISCOVER_CLIMATE = 'homematic.climate'\nDISCOVER_LOCKS = 'homematic.locks'\n\nATTR_DISCOVER_DEVICES = 'devices'\nATTR_PARAM = 'param'\nATTR_CHANNEL = 'channel'\nATTR_ADDRESS = 'address'\nATTR_VALUE = 'value'\nATTR_INTERFACE = 'interface'\nATTR_ERRORCODE = 'error'\nATTR_MESSAGE = 'message'\nATTR_MODE = 'mode'\nATTR_TIME = 'time'\nATTR_UNIQUE_ID = 'unique_id'\nATTR_PARAMSET_KEY = 'paramset_key'\nATTR_PARAMSET = 'paramset'\n\nEVENT_KEYPRESS = 'homematic.keypress'\nEVENT_IMPULSE = 'homematic.impulse'\nEVENT_ERROR = 'homematic.error'\n\nSERVICE_VIRTUALKEY = 'virtualkey'\nSERVICE_RECONNECT = 'reconnect'\nSERVICE_SET_VARIABLE_VALUE = 'set_variable_value'\nSERVICE_SET_DEVICE_VALUE = 'set_device_value'\nSERVICE_SET_INSTALL_MODE = 'set_install_mode'\nSERVICE_PUT_PARAMSET = 'put_paramset'\n\nHM_DEVICE_TYPES = {\n DISCOVER_SWITCHES: [\n 'Switch', 'SwitchPowermeter', 'IOSwitch', 'IPSwitch', 'RFSiren',\n 'IPSwitchPowermeter', 'HMWIOSwitch', 'Rain', 'EcoLogic',\n 'IPKeySwitchPowermeter', 'IPGarage', 'IPKeySwitch', 'IPMultiIO'],\n DISCOVER_LIGHTS: ['Dimmer', 'KeyDimmer', 'IPKeyDimmer', 'IPDimmer',\n 'ColorEffectLight'],\n DISCOVER_SENSORS: [\n 'SwitchPowermeter', 'Motion', 'MotionV2', 'RemoteMotion', 'MotionIP',\n 'ThermostatWall', 'AreaThermostat', 'RotaryHandleSensor',\n 'WaterSensor', 'PowermeterGas', 'LuxSensor', 'WeatherSensor',\n 'WeatherStation', 'ThermostatWall2', 'TemperatureDiffSensor',\n 'TemperatureSensor', 'CO2Sensor', 'IPSwitchPowermeter', 'HMWIOSwitch',\n 'FillingLevel', 'ValveDrive', 'EcoLogic', 'IPThermostatWall',\n 'IPSmoke', 'RFSiren', 'PresenceIP', 'IPAreaThermostat',\n 'IPWeatherSensor', 'RotaryHandleSensorIP', 'IPPassageSensor',\n 'IPKeySwitchPowermeter', 'IPThermostatWall230V', 'IPWeatherSensorPlus',\n 'IPWeatherSensorBasic', 'IPBrightnessSensor', 'IPGarage',\n 'UniversalSensor', 'MotionIPV2', 'IPMultiIO', 'IPThermostatWall2'],\n DISCOVER_CLIMATE: [\n 'Thermostat', 'ThermostatWall', 'MAXThermostat', 'ThermostatWall2',\n 'MAXWallThermostat', 'IPThermostat', 'IPThermostatWall',\n 'ThermostatGroup', 'IPThermostatWall230V', 'IPThermostatWall2'],\n DISCOVER_BINARY_SENSORS: [\n 'ShutterContact', 'Smoke', 'SmokeV2', 'Motion', 'MotionV2',\n 'MotionIP', 'RemoteMotion', 'WeatherSensor', 'TiltSensor',\n 'IPShutterContact', 'HMWIOSwitch', 'MaxShutterContact', 'Rain',\n 'WiredSensor', 'PresenceIP', 'IPWeatherSensor', 'IPPassageSensor',\n 'SmartwareMotion', 'IPWeatherSensorPlus', 'MotionIPV2', 'WaterIP',\n 'IPMultiIO', 'TiltIP', 'IPShutterContactSabotage'],\n DISCOVER_COVER: ['Blind', 'KeyBlind', 'IPKeyBlind', 'IPKeyBlindTilt'],\n DISCOVER_LOCKS: ['KeyMatic']\n}\n\nHM_IGNORE_DISCOVERY_NODE = [\n 'ACTUAL_TEMPERATURE',\n 'ACTUAL_HUMIDITY'\n]\n\nHM_IGNORE_DISCOVERY_NODE_EXCEPTIONS = {\n 'ACTUAL_TEMPERATURE': [\n 'IPAreaThermostat', 'IPWeatherSensor',\n 'IPWeatherSensorPlus', 'IPWeatherSensorBasic',\n 'IPThermostatWall', 'IPThermostatWall2'],\n}\n\nHM_ATTRIBUTE_SUPPORT = {\n 'LOWBAT': ['battery', {0: 'High', 1: 'Low'}],\n 'LOW_BAT': ['battery', {0: 'High', 1: 'Low'}],\n 'ERROR': ['error', {0: 'No'}],\n 'ERROR_SABOTAGE': ['sabotage', {0: 'No', 1: 'Yes'}],\n 'SABOTAGE': ['sabotage', {0: 'No', 1: 'Yes'}],\n 'RSSI_PEER': ['rssi_peer', {}],\n 'RSSI_DEVICE': ['rssi_device', {}],\n 'VALVE_STATE': ['valve', {}],\n 'LEVEL': ['level', {}],\n 'BATTERY_STATE': ['battery', {}],\n 'CONTROL_MODE': ['mode', {\n 0: 'Auto',\n 1: 'Manual',\n 2: 'Away',\n 3: 'Boost',\n 4: 'Comfort',\n 5: 'Lowering'\n }],\n 'POWER': ['power', {}],\n 'CURRENT': ['current', {}],\n 'VOLTAGE': ['voltage', {}],\n 'OPERATING_VOLTAGE': ['voltage', {}],\n 'WORKING': ['working', {0: 'No', 1: 'Yes'}]\n}\n\nHM_PRESS_EVENTS = [\n 'PRESS_SHORT',\n 'PRESS_LONG',\n 'PRESS_CONT',\n 'PRESS_LONG_RELEASE',\n 'PRESS',\n]\n\nHM_IMPULSE_EVENTS = [\n 'SEQUENCE_OK',\n]\n\nCONF_RESOLVENAMES_OPTIONS = [\n 'metadata',\n 'json',\n 'xml',\n False\n]\n\nDATA_HOMEMATIC = 'homematic'\nDATA_STORE = 'homematic_store'\nDATA_CONF = 'homematic_conf'\n\nCONF_INTERFACES = 'interfaces'\nCONF_LOCAL_IP = 'local_ip'\nCONF_LOCAL_PORT = 'local_port'\nCONF_PORT = 'port'\nCONF_PATH = 'path'\nCONF_CALLBACK_IP = 'callback_ip'\nCONF_CALLBACK_PORT = 'callback_port'\nCONF_RESOLVENAMES = 'resolvenames'\nCONF_JSONPORT = 'jsonport'\nCONF_VARIABLES = 'variables'\nCONF_DEVICES = 'devices'\nCONF_PRIMARY = 'primary'\n\nDEFAULT_LOCAL_IP = '0.0.0.0'\nDEFAULT_LOCAL_PORT = 0\nDEFAULT_RESOLVENAMES = False\nDEFAULT_JSONPORT = 80\nDEFAULT_PORT = 2001\nDEFAULT_PATH = ''\nDEFAULT_USERNAME = 'Admin'\nDEFAULT_PASSWORD = ''\nDEFAULT_SSL = False\nDEFAULT_VERIFY_SSL = False\nDEFAULT_CHANNEL = 1\n\n\nDEVICE_SCHEMA = vol.Schema({\n vol.Required(CONF_PLATFORM): 'homematic',\n vol.Required(ATTR_NAME): cv.string,\n vol.Required(ATTR_ADDRESS): cv.string,\n vol.Required(ATTR_INTERFACE): cv.string,\n vol.Optional(ATTR_CHANNEL, default=DEFAULT_CHANNEL): vol.Coerce(int),\n vol.Optional(ATTR_PARAM): cv.string,\n vol.Optional(ATTR_UNIQUE_ID): cv.string,\n})\n\nCONFIG_SCHEMA = vol.Schema({\n DOMAIN: vol.Schema({\n vol.Optional(CONF_INTERFACES, default={}): {cv.match_all: {\n vol.Required(CONF_HOST): cv.string,\n vol.Optional(CONF_PORT, default=DEFAULT_PORT): cv.port,\n vol.Optional(CONF_PATH, default=DEFAULT_PATH): cv.string,\n vol.Optional(CONF_RESOLVENAMES, default=DEFAULT_RESOLVENAMES):\n vol.In(CONF_RESOLVENAMES_OPTIONS),\n vol.Optional(CONF_JSONPORT, default=DEFAULT_JSONPORT): cv.port,\n vol.Optional(CONF_USERNAME, default=DEFAULT_USERNAME): cv.string,\n vol.Optional(CONF_PASSWORD, default=DEFAULT_PASSWORD): cv.string,\n vol.Optional(CONF_CALLBACK_IP): cv.string,\n vol.Optional(CONF_CALLBACK_PORT): cv.port,\n vol.Optional(CONF_SSL, default=DEFAULT_SSL): cv.boolean,\n vol.Optional(\n CONF_VERIFY_SSL, default=DEFAULT_VERIFY_SSL): cv.boolean,\n }},\n vol.Optional(CONF_HOSTS, default={}): {cv.match_all: {\n vol.Required(CONF_HOST): cv.string,\n vol.Optional(CONF_USERNAME, default=DEFAULT_USERNAME): cv.string,\n vol.Optional(CONF_PASSWORD, default=DEFAULT_PASSWORD): cv.string,\n }},\n vol.Optional(CONF_LOCAL_IP, default=DEFAULT_LOCAL_IP): cv.string,\n vol.Optional(CONF_LOCAL_PORT): cv.port,\n }),\n}, extra=vol.ALLOW_EXTRA)\n\nSCHEMA_SERVICE_VIRTUALKEY = vol.Schema({\n vol.Required(ATTR_ADDRESS): vol.All(cv.string, vol.Upper),\n vol.Required(ATTR_CHANNEL): vol.Coerce(int),\n vol.Required(ATTR_PARAM): cv.string,\n vol.Optional(ATTR_INTERFACE): cv.string,\n})\n\nSCHEMA_SERVICE_SET_VARIABLE_VALUE = vol.Schema({\n vol.Required(ATTR_NAME): cv.string,\n vol.Required(ATTR_VALUE): cv.match_all,\n vol.Optional(ATTR_ENTITY_ID): cv.entity_ids,\n})\n\nSCHEMA_SERVICE_SET_DEVICE_VALUE = vol.Schema({\n vol.Required(ATTR_ADDRESS): vol.All(cv.string, vol.Upper),\n vol.Required(ATTR_CHANNEL): vol.Coerce(int),\n vol.Required(ATTR_PARAM): vol.All(cv.string, vol.Upper),\n vol.Required(ATTR_VALUE): cv.match_all,\n vol.Optional(ATTR_INTERFACE): cv.string,\n})\n\nSCHEMA_SERVICE_RECONNECT = vol.Schema({})\n\nSCHEMA_SERVICE_SET_INSTALL_MODE = vol.Schema({\n vol.Required(ATTR_INTERFACE): cv.string,\n vol.Optional(ATTR_TIME, default=60): cv.positive_int,\n vol.Optional(ATTR_MODE, default=1):\n vol.All(vol.Coerce(int), vol.In([1, 2])),\n vol.Optional(ATTR_ADDRESS): vol.All(cv.string, vol.Upper),\n})\n\nSCHEMA_SERVICE_PUT_PARAMSET = vol.Schema({\n vol.Required(ATTR_INTERFACE): cv.string,\n vol.Required(ATTR_ADDRESS): vol.All(cv.string, vol.Upper),\n vol.Required(ATTR_PARAMSET_KEY): vol.All(cv.string, vol.Upper),\n vol.Required(ATTR_PARAMSET): dict,\n})\n\n\ndef setup(hass, config):\n \"\"\"Set up the Homematic component.\"\"\"\n from pyhomematic import HMConnection\n\n conf = config[DOMAIN]\n hass.data[DATA_CONF] = remotes = {}\n hass.data[DATA_STORE] = set()\n\n # Create hosts-dictionary for pyhomematic\n for rname, rconfig in conf[CONF_INTERFACES].items():\n remotes[rname] = {\n 'ip': socket.gethostbyname(rconfig.get(CONF_HOST)),\n 'port': rconfig.get(CONF_PORT),\n 'path': rconfig.get(CONF_PATH),\n 'resolvenames': rconfig.get(CONF_RESOLVENAMES),\n 'jsonport': rconfig.get(CONF_JSONPORT),\n 'username': rconfig.get(CONF_USERNAME),\n 'password': rconfig.get(CONF_PASSWORD),\n 'callbackip': rconfig.get(CONF_CALLBACK_IP),\n 'callbackport': rconfig.get(CONF_CALLBACK_PORT),\n 'ssl': rconfig.get(CONF_SSL),\n 'verify_ssl': rconfig.get(CONF_VERIFY_SSL),\n 'connect': True,\n }\n\n for sname, sconfig in conf[CONF_HOSTS].items():\n remotes[sname] = {\n 'ip': socket.gethostbyname(sconfig.get(CONF_HOST)),\n 'port': DEFAULT_PORT,\n 'username': sconfig.get(CONF_USERNAME),\n 'password': sconfig.get(CONF_PASSWORD),\n 'connect': False,\n }\n\n # Create server thread\n bound_system_callback = partial(_system_callback_handler, hass, config)\n hass.data[DATA_HOMEMATIC] = homematic = HMConnection(\n local=config[DOMAIN].get(CONF_LOCAL_IP),\n localport=config[DOMAIN].get(CONF_LOCAL_PORT, DEFAULT_LOCAL_PORT),\n remotes=remotes,\n systemcallback=bound_system_callback,\n interface_id='homeassistant'\n )\n\n # Start server thread, connect to hosts, initialize to receive events\n homematic.start()\n\n # Stops server when HASS is shutting down\n hass.bus.listen_once(\n EVENT_HOMEASSISTANT_STOP, hass.data[DATA_HOMEMATIC].stop)\n\n # Init homematic hubs\n entity_hubs = []\n for hub_name in conf[CONF_HOSTS].keys():\n entity_hubs.append(HMHub(hass, homematic, hub_name))\n\n def _hm_service_virtualkey(service):\n \"\"\"Service to handle virtualkey servicecalls.\"\"\"\n address = service.data.get(ATTR_ADDRESS)\n channel = service.data.get(ATTR_CHANNEL)\n param = service.data.get(ATTR_PARAM)\n\n # Device not found\n hmdevice = _device_from_servicecall(hass, service)\n if hmdevice is None:\n _LOGGER.error(\"%s not found for service virtualkey!\", address)\n return\n\n # Parameter doesn't exist for device\n if param not in hmdevice.ACTIONNODE:\n _LOGGER.error(\"%s not datapoint in hm device %s\", param, address)\n return\n\n # Channel doesn't exist for device\n if channel not in hmdevice.ACTIONNODE[param]:\n _LOGGER.error(\"%i is not a channel in hm device %s\",\n channel, address)\n return\n\n # Call parameter\n hmdevice.actionNodeData(param, True, channel)\n\n hass.services.register(\n DOMAIN, SERVICE_VIRTUALKEY, _hm_service_virtualkey,", "answers": [" schema=SCHEMA_SERVICE_VIRTUALKEY)"], "length": 844, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "98863ea6-e247-488e-bc1e-63aa8879b8e5", "reasoning": "The code is registering a Home Assistant service. After listing the domain, service name, and handler, the next argument should be the schema that validates service data. The appropriate schema defined earlier is SCHEMA_SERVICE_VIRTUALKEY, so the next line completes the register call with the schema argument and closes the parenthesis.", "reasoning_model_answer": "schema=SCHEMA_SERVICE_VIRTUALKEY)", "assistant_with_reasoning": "\nThe code is registering a Home Assistant service. After listing the domain, service name, and handler, the next argument should be the schema that validates service data. The appropriate schema defined earlier is SCHEMA_SERVICE_VIRTUALKEY, so the next line completes the register call with the schema argument and closes the parenthesis.\n\nschema=SCHEMA_SERVICE_VIRTUALKEY)", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.354, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 11951, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "schema=SCHEMA_SERVICE_VIRTUALKEY)", "score": 0.89, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "package xyz.cloudkeeper.model.beans;\n\nimport org.eclipse.persistence.jaxb.JAXBContextFactory;\nimport org.testng.Assert;\nimport org.testng.ITest;\nimport org.testng.annotations.Test;\nimport xyz.cloudkeeper.model.Immutable;\nimport xyz.cloudkeeper.model.bare.BareLocatable;\nimport xyz.cloudkeeper.model.beans.element.MutableAnnotatedConstruct;\nimport xyz.cloudkeeper.model.beans.element.MutableQualifiedNamable;\nimport xyz.cloudkeeper.model.beans.element.MutableSimpleNameable;\nimport xyz.cloudkeeper.model.immutable.AnnotationValue;\nimport xyz.cloudkeeper.model.immutable.Location;\nimport xyz.cloudkeeper.model.immutable.element.Key;\nimport xyz.cloudkeeper.model.immutable.element.Name;\nimport xyz.cloudkeeper.model.immutable.element.NoKey;\nimport xyz.cloudkeeper.model.immutable.element.SimpleName;\nimport xyz.cloudkeeper.model.immutable.element.Version;\nimport xyz.cloudkeeper.model.immutable.execution.ExecutionTrace;\nimport xyz.cloudkeeper.model.util.ImmutableList;\n\nimport javax.annotation.Nullable;\nimport javax.xml.bind.JAXBContext;\nimport javax.xml.bind.JAXBElement;\nimport javax.xml.bind.Marshaller;\nimport javax.xml.bind.Unmarshaller;\nimport javax.xml.bind.annotation.XmlRootElement;\nimport javax.xml.bind.annotation.XmlSeeAlso;\nimport javax.xml.bind.annotation.adapters.XmlAdapter;\nimport javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;\nimport javax.xml.namespace.QName;\nimport javax.xml.transform.stream.StreamSource;\nimport java.io.ByteArrayInputStream;\nimport java.io.ByteArrayOutputStream;\nimport java.io.IOException;\nimport java.io.ObjectInputStream;\nimport java.io.ObjectOutputStream;\nimport java.io.OutputStream;\nimport java.io.Serializable;\nimport java.io.StringReader;\nimport java.io.StringWriter;\nimport java.lang.reflect.Constructor;\nimport java.lang.reflect.InvocationHandler;\nimport java.lang.reflect.InvocationTargetException;\nimport java.lang.reflect.Method;\nimport java.lang.reflect.Modifier;\nimport java.lang.reflect.ParameterizedType;\nimport java.lang.reflect.Proxy;\nimport java.lang.reflect.Type;\nimport java.net.URI;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collections;\nimport java.util.Date;\nimport java.util.IdentityHashMap;\nimport java.util.List;\nimport java.util.regex.Pattern;\n\npublic class MutableLocatableContract implements ITest {\n private static final CopyOption[] NO_COPY_OPTIONS = new CopyOption[0];\n\n private final Class clazz;\n private final ImmutableList getterSetterPairs;\n private MutableLocatable instance;\n private MutableLocatable copy;\n private Method staticCopyMethod;\n\n @SafeVarargs\n public static MutableLocatableContract[] contractsFor(Class>... classes) {\n MutableLocatableContract[] array = new MutableLocatableContract[classes.length];\n for (int i = 0; i < classes.length; ++i) {\n array[i] = new MutableLocatableContract(classes[i]);\n }\n return array;\n }\n\n public MutableLocatableContract(Class> clazz) {\n this.clazz = clazz;\n\n List newGetterSetterPairs = new ArrayList<>();\n for (Method method: clazz.getMethods()) {\n try {\n Class[] parameterTypes = method.getParameterTypes();\n if (method.getName().startsWith(\"set\") && parameterTypes.length == 1) {\n Class expectedReturnType = parameterTypes[0];\n Method getter = Boolean.class.equals(expectedReturnType) || boolean.class.equals(expectedReturnType)\n ? clazz.getMethod(\"is\" + method.getName().substring(3))\n : clazz.getMethod(\"get\" + method.getName().substring(3));\n\n Class getterReturnType = getter.getReturnType();\n if (getterReturnType.equals(parameterTypes[0])) {\n newGetterSetterPairs.add(new GetterSetterPair(getter, method));\n }\n }\n } catch (NoSuchMethodException exception) {\n Assert.fail(String.format(\n \"Could not find getter corresponding to setter method %s.\", method\n ), exception);\n }\n }\n getterSetterPairs = ImmutableList.copyOf(newGetterSetterPairs);\n }\n\n @Override\n public String getTestName() {\n return clazz.getSimpleName();\n }\n\n @Test\n public void noArgsConstructor() throws ReflectiveOperationException {\n instance = (MutableLocatable) clazz.getConstructor().newInstance();\n }\n\n private static MutableLocatable valueForMutableLocatable(Class clazz) throws Exception {\n Class currentClass = clazz;\n while (true) {\n if (Modifier.isAbstract(currentClass.getModifiers())) {\n XmlSeeAlso annotation = currentClass.getAnnotation(XmlSeeAlso.class);\n Assert.assertNotNull(annotation, String.format(\"Missing @%s annotation on %s.\",\n XmlSeeAlso.class.getSimpleName(), currentClass));\n currentClass = (Class) annotation.value()[0];\n } else {\n return (MutableLocatable) currentClass.getConstructor().newInstance();\n }\n }\n }\n\n private static final class ClassAndValue {\n private final Class clazz;\n private final Object value;\n private final Object equalsValue;\n\n private ClassAndValue(Class clazz, Object value, Object equalsValue) {\n this.clazz = clazz;\n this.value = value;\n this.equalsValue = equalsValue;\n }\n\n private ClassAndValue(Class clazz, Object value) {\n this(clazz, value, value);\n }\n }\n\n private static ClassAndValue valueForType(Class rawClass, Type generic) throws Exception {\n if (List.class.equals(rawClass)) {\n Type listPropertyElementType = ((ParameterizedType) generic).getActualTypeArguments()[0];\n Class listPropertyElementRaw;\n if (listPropertyElementType instanceof Class) {\n listPropertyElementRaw = (Class) listPropertyElementType;\n } else if (listPropertyElementType instanceof ParameterizedType) {\n listPropertyElementRaw = (Class) ((ParameterizedType) listPropertyElementType).getRawType();\n } else {\n Assert.fail(String.format(\"Expected generic type that is %s or %s, but got %s.\",\n Class.class.getSimpleName(), ParameterizedType.class.getSimpleName(), listPropertyElementType));\n throw new AssertionError();\n }\n return new ClassAndValue(\n List.class,\n Collections.singletonList(valueForType(listPropertyElementRaw, listPropertyElementType).value)\n );\n } else if (rawClass.isEnum()) {\n return new ClassAndValue(rawClass, rawClass.getEnumConstants()[0]);\n } else if (Location.class.equals(rawClass)) {\n return new ClassAndValue(rawClass, new Location(\"foo\", 3, 24));\n } else if (SimpleName.class.equals(rawClass)) {\n return new ClassAndValue(String.class, \"Bar\", SimpleName.identifier(\"Bar\"));\n } else if (Name.class.equals(rawClass)) {\n return new ClassAndValue(String.class, \"com.foo.Bar\", Name.qualifiedName(\"com.foo.Bar\"));\n } else if (Key.class.equals(rawClass)) {\n return new ClassAndValue(Key.class, NoKey.instance());\n } else if (Version.class.equals(rawClass)) {\n return new ClassAndValue(rawClass, Version.valueOf(\"1.2.3\"));\n } else if (AnnotationValue.class.equals(rawClass)) {\n return new ClassAndValue(Serializable.class, 34, AnnotationValue.of(34));\n } else if (ExecutionTrace.class.equals(rawClass)) {\n return new ClassAndValue(rawClass, ExecutionTrace.valueOf(\"/loop/value:in:num\"));\n } else if (MutableQualifiedNamable.class.equals(rawClass)) {\n return new ClassAndValue(String.class, \"com.foo.Bar\",\n new MutableQualifiedNamable().setQualifiedName(\"com.foo.Bar\"));\n } else if (MutableSimpleNameable.class.equals(rawClass)) {\n return new ClassAndValue(String.class, \"Bar\", new MutableSimpleNameable().setSimpleName(\"Bar\"));\n } else if (MutableLocatable.class.isAssignableFrom(rawClass)) {\n return new ClassAndValue(rawClass, valueForMutableLocatable(rawClass));\n } else if (URI.class.equals(rawClass)) {\n return new ClassAndValue(rawClass, URI.create(\"test:some.module\"));\n } else if (Pattern.class.equals(rawClass)) {\n return new ClassAndValue(rawClass, Pattern.compile(\".*\"));\n } else if (Date.class.equals(rawClass)) {\n return new ClassAndValue(rawClass, new Date());\n } else if (String.class.equals(rawClass)) {\n return new ClassAndValue(rawClass, \"baz\");\n } else if (byte[].class.equals(rawClass)) {\n return new ClassAndValue(rawClass, new byte[] { (byte) 1, (byte) 2 });\n } else if (Object.class.equals(rawClass)) {\n return new ClassAndValue(rawClass, new Object());\n } else {\n // No other type is currently supported.\n Assert.fail(String.format(\"Unexpected property type %s.\", generic));\n throw new AssertionError();\n }\n }\n\n @Test(dependsOnMethods = \"noArgsConstructor\")\n public void setters() throws Exception {\n for (GetterSetterPair getterSetterPair: getterSetterPairs) {\n Method getter = getterSetterPair.getter;\n Method setter = getterSetterPair.setter;\n Class propertyClass = setter.getParameterTypes()[0];\n Type propertyType = setter.getGenericParameterTypes()[0];\n\n // Verify that null is a valid argument for list-property setters if and only if a property is initialized\n // as null by the default constructor\n if (List.class.isAssignableFrom(propertyClass)) {\n if (getter.invoke(instance) == null) {\n setter.invoke(instance, new Object[] { null });\n Assert.assertNull(getter.invoke(instance));\n } else {\n try {\n setter.invoke(instance, new Object[] { null });\n Assert.fail(\"Expected exception.\");\n } catch (InvocationTargetException exception) {\n Assert.assertTrue(exception.getCause() instanceof NullPointerException);\n }\n }\n }\n\n // Verify that calling setter works\n ClassAndValue classAndValue = valueForType(propertyClass, propertyType);\n clazz.getMethod(setter.getName(), classAndValue.clazz).invoke(instance, classAndValue.value);\n\n // Verify that getter now returns the previously updated property\n Object newValue = getter.invoke(instance);\n Assert.assertEquals(newValue, classAndValue.equalsValue);\n }\n }\n\n private static Class getBareInterface(Class clazz) {\n for (Constructor constructor: clazz.getDeclaredConstructors()) {\n Class[] parameterTypes = constructor.getParameterTypes();\n if (parameterTypes.length == 2 && BareLocatable.class.isAssignableFrom(parameterTypes[0])) {\n Class bareInterface = parameterTypes[0];\n Assert.assertTrue(bareInterface.getSimpleName().startsWith(\"Bare\"));\n return parameterTypes[0];\n }\n }\n Assert.fail(String.format(\"Could not find copy constructor for %s.\", clazz));\n throw new AssertionError();\n }\n\n @Test(dependsOnMethods = \"setters\")\n public void copyOf() throws IllegalAccessException, NoSuchMethodException, InvocationTargetException {\n Class bareInterface = getBareInterface(clazz);\n String simpleName = bareInterface.getSimpleName();\n\n Class superclass = clazz.getSuperclass();\n String copyOfName = superclass.equals(MutableLocatable.class)\n || superclass.equals(MutableAnnotatedConstruct.class)\n ? \"copyOf\"\n : \"copyOf\" + simpleName.substring(\"Bare\".length());\n staticCopyMethod = clazz.getMethod(copyOfName, bareInterface, CopyOption[].class);\n\n // Verify that calling copyOf method with null returns null\n Assert.assertNull(staticCopyMethod.invoke(null, null, NO_COPY_OPTIONS));\n", "answers": [" copy = (MutableLocatable) staticCopyMethod.invoke(null, instance, NO_COPY_OPTIONS);"], "length": 858, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "10fe8f23-1e73-4199-b050-f6b445bd5593", "reasoning": "The test method copyOf() is checking the static copyOf method. After asserting that invoking it with null returns null, the next logical step is to invoke it with a real instance and store the result in the 'copy' field for further assertions. This matches the pattern of testing both null and non‑null behavior.", "reasoning_model_answer": "copy = (MutableLocatable) staticCopyMethod.invoke(null, instance, NO_COPY_OPTIONS);", "assistant_with_reasoning": "\nThe test method copyOf() is checking the static copyOf method. After asserting that invoking it with null returns null, the next logical step is to invoke it with a real instance and store the result in the 'copy' field for further assertions. This matches the pattern of testing both null and non‑null behavior.\n\ncopy = (MutableLocatable) staticCopyMethod.invoke(null, instance, NO_COPY_OPTIONS);", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.544, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 12656, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "copy = (MutableLocatable) staticCopyMethod.invoke(null, instance, NO_COPY_OPTIONS);", "score": 0.96, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "package org.cugos.parboiledwkt;\n\nimport org.junit.Test;\nimport org.parboiled.Parboiled;\nimport org.parboiled.parserunners.ReportingParseRunner;\nimport org.parboiled.support.ParsingResult;\n\nimport static org.junit.Assert.*;\n\npublic class MultiSurfaceTest {\n\n @Test\n public void empty() {\n WKTParser parser = Parboiled.createParser(WKTParser.class);\n ParsingResult result = new ReportingParseRunner(parser.WKT()).run(\"MULTISURFACE EMPTY\");\n Geometry geometry = result.resultValue;\n assertNotNull(geometry);\n assertTrue(geometry instanceof MultiSurface);\n MultiSurface ms = (MultiSurface) geometry;\n assertTrue(ms.isEmpty());\n assertNull(ms.getSrid());\n assertEquals(Dimension.Two, ms.getDimension());\n // WKT\n assertEquals(\"MULTISURFACE EMPTY\", ms.toString());\n }\n\n @Test\n public void twoDimensional() {\n String wkt = \"MULTISURFACE(CURVEPOLYGON(CIRCULARSTRING(0 0, 4 0, 4 4, 0 4, 0 0),(1 1, 3 3, 3 1, 1 1)),((10 10, 14 12, 11 10, 10 10),(11 11, 11.5 11, 11 11.5, 11 11)))\";\n WKTParser parser = Parboiled.createParser(WKTParser.class);\n ParsingResult result = new ReportingParseRunner(parser.WKT()).run(wkt);\n Geometry geometry = result.resultValue;\n assertNotNull(geometry);\n assertTrue(geometry instanceof MultiSurface);\n MultiSurface ms = (MultiSurface) geometry;\n assertFalse(ms.isEmpty());\n assertNull(ms.getSrid());\n assertEquals(Dimension.Two, ms.getDimension());\n assertEquals(17, ms.getNumberOfCoordinates());\n assertEquals(2, ms.getSurfaces().size());\n // 0\n assertTrue(ms.getSurfaces().get(0) instanceof CurvePolygon);\n CurvePolygon cp = (CurvePolygon) ms.getSurfaces().get(0);\n assertNull(cp.getSrid());\n assertEquals(Dimension.Two, cp.getDimension());\n // 0 Outer\n assertTrue(cp.getOuterCurve() instanceof CircularString);\n CircularString cs = (CircularString) cp.getOuterCurve();\n assertNull(cs.getSrid());\n assertEquals(Dimension.Two, cs.getDimension());\n assertEquals(5, cs.getCoordinates().size());\n assertEquals(Coordinate.create2D(0, 0), cs.getCoordinates().get(0));\n assertEquals(Coordinate.create2D(4, 0), cs.getCoordinates().get(1));\n assertEquals(Coordinate.create2D(4, 4), cs.getCoordinates().get(2));\n assertEquals(Coordinate.create2D(0, 4), cs.getCoordinates().get(3));\n assertEquals(Coordinate.create2D(0, 0), cs.getCoordinates().get(4));\n // 0 Inner\n assertEquals(1, cp.getInnerCurves().size());\n assertTrue(cp.getInnerCurves().get(0) instanceof LineString);\n LineString ls = (LineString) cp.getInnerCurves().get(0);\n assertNull(ls.getSrid());\n assertEquals(Dimension.Two, ls.getDimension());\n assertEquals(4, ls.getCoordinates().size());\n assertEquals(Coordinate.create2D(1, 1), ls.getCoordinates().get(0));\n assertEquals(Coordinate.create2D(3, 3), ls.getCoordinates().get(1));\n assertEquals(Coordinate.create2D(3, 1), ls.getCoordinates().get(2));\n assertEquals(Coordinate.create2D(1, 1), ls.getCoordinates().get(3));\n // 1\n assertTrue(ms.getSurfaces().get(1) instanceof Polygon);\n Polygon p = (Polygon) ms.getSurfaces().get(1);\n assertNull(p.getSrid());\n assertEquals(Dimension.Two, p.getDimension());\n assertNotNull(p.getOuterLinearRing());\n assertEquals(1, p.getInnerLinearRings().size());\n // 1 Outer\n LinearRing or = p.getOuterLinearRing();\n assertNull(or.getSrid());\n assertEquals(Dimension.Two, or.getDimension());\n assertEquals(4, or.getCoordinates().size());\n assertEquals(Coordinate.create2D(10, 10), or.getCoordinates().get(0));\n assertEquals(Coordinate.create2D(14, 12), or.getCoordinates().get(1));\n assertEquals(Coordinate.create2D(11, 10), or.getCoordinates().get(2));\n assertEquals(Coordinate.create2D(10, 10), or.getCoordinates().get(3));\n // 1 Inner\n LinearRing ir = p.getInnerLinearRings().get(0);\n assertNull(ir.getSrid());\n assertEquals(Dimension.Two, ir.getDimension());\n assertEquals(4, ir.getCoordinates().size());\n assertEquals(Coordinate.create2D(11, 11), ir.getCoordinates().get(0));\n assertEquals(Coordinate.create2D(11.5, 11), ir.getCoordinates().get(1));\n assertEquals(Coordinate.create2D(11, 11.5), ir.getCoordinates().get(2));\n assertEquals(Coordinate.create2D(11, 11), ir.getCoordinates().get(3));\n // WKT\n assertEquals(\"MULTISURFACE (CURVEPOLYGON (CIRCULARSTRING (0.0 0.0, 4.0 0.0, 4.0 4.0, 0.0 4.0, 0.0 0.0), \" +\n \"(1.0 1.0, 3.0 3.0, 3.0 1.0, 1.0 1.0)), \" +\n \"((10.0 10.0, 14.0 12.0, 11.0 10.0, 10.0 10.0), (11.0 11.0, 11.5 11.0, 11.0 11.5, 11.0 11.0)))\",\n ms.toString());\n }\n\n @Test\n public void twoDimensionalWithSrid() {\n String wkt = \"SRID=4326;MULTISURFACE(CURVEPOLYGON(CIRCULARSTRING(0 0, 4 0, 4 4, 0 4, 0 0),(1 1, 3 3, 3 1, 1 1)),((10 10, 14 12, 11 10, 10 10),(11 11, 11.5 11, 11 11.5, 11 11)))\";\n WKTParser parser = Parboiled.createParser(WKTParser.class);\n ParsingResult result = new ReportingParseRunner(parser.WKT()).run(wkt);\n Geometry geometry = result.resultValue;\n assertNotNull(geometry);\n assertTrue(geometry instanceof MultiSurface);\n MultiSurface ms = (MultiSurface) geometry;\n assertFalse(ms.isEmpty());\n assertEquals(\"4326\", ms.getSrid());\n assertEquals(Dimension.Two, ms.getDimension());\n assertEquals(2, ms.getSurfaces().size());\n // 0\n assertTrue(ms.getSurfaces().get(0) instanceof CurvePolygon);\n CurvePolygon cp = (CurvePolygon) ms.getSurfaces().get(0);\n assertEquals(\"4326\", cp.getSrid());\n assertEquals(Dimension.Two, cp.getDimension());\n // 0 Outer\n assertTrue(cp.getOuterCurve() instanceof CircularString);\n CircularString cs = (CircularString) cp.getOuterCurve();\n assertEquals(\"4326\", cs.getSrid());\n assertEquals(Dimension.Two, cs.getDimension());\n assertEquals(5, cs.getCoordinates().size());\n assertEquals(Coordinate.create2D(0, 0), cs.getCoordinates().get(0));\n assertEquals(Coordinate.create2D(4, 0), cs.getCoordinates().get(1));\n assertEquals(Coordinate.create2D(4, 4), cs.getCoordinates().get(2));\n assertEquals(Coordinate.create2D(0, 4), cs.getCoordinates().get(3));\n assertEquals(Coordinate.create2D(0, 0), cs.getCoordinates().get(4));\n // 0 Inner\n assertEquals(1, cp.getInnerCurves().size());\n assertTrue(cp.getInnerCurves().get(0) instanceof LineString);\n LineString ls = (LineString) cp.getInnerCurves().get(0);\n assertEquals(\"4326\", ls.getSrid());\n assertEquals(Dimension.Two, ls.getDimension());\n assertEquals(4, ls.getCoordinates().size());\n assertEquals(Coordinate.create2D(1, 1), ls.getCoordinates().get(0));\n assertEquals(Coordinate.create2D(3, 3), ls.getCoordinates().get(1));\n assertEquals(Coordinate.create2D(3, 1), ls.getCoordinates().get(2));\n assertEquals(Coordinate.create2D(1, 1), ls.getCoordinates().get(3));\n // 1\n assertTrue(ms.getSurfaces().get(1) instanceof Polygon);\n Polygon p = (Polygon) ms.getSurfaces().get(1);\n assertEquals(\"4326\", p.getSrid());\n assertEquals(Dimension.Two, p.getDimension());\n assertNotNull(p.getOuterLinearRing());\n assertEquals(1, p.getInnerLinearRings().size());\n // 1 Outer\n LinearRing or = p.getOuterLinearRing();\n assertEquals(\"4326\", or.getSrid());\n assertEquals(Dimension.Two, or.getDimension());\n assertEquals(4, or.getCoordinates().size());\n assertEquals(Coordinate.create2D(10, 10), or.getCoordinates().get(0));\n assertEquals(Coordinate.create2D(14, 12), or.getCoordinates().get(1));\n assertEquals(Coordinate.create2D(11, 10), or.getCoordinates().get(2));\n assertEquals(Coordinate.create2D(10, 10), or.getCoordinates().get(3));\n // 1 Inner\n LinearRing ir = p.getInnerLinearRings().get(0);\n assertEquals(\"4326\", ir.getSrid());\n assertEquals(Dimension.Two, ir.getDimension());\n assertEquals(4, ir.getCoordinates().size());\n assertEquals(Coordinate.create2D(11, 11), ir.getCoordinates().get(0));\n assertEquals(Coordinate.create2D(11.5, 11), ir.getCoordinates().get(1));\n assertEquals(Coordinate.create2D(11, 11.5), ir.getCoordinates().get(2));\n assertEquals(Coordinate.create2D(11, 11), ir.getCoordinates().get(3));\n // WKT\n assertEquals(\"SRID=4326;MULTISURFACE (CURVEPOLYGON (CIRCULARSTRING (0.0 0.0, 4.0 0.0, 4.0 4.0, 0.0 4.0, 0.0 0.0), \" +\n \"(1.0 1.0, 3.0 3.0, 3.0 1.0, 1.0 1.0)), \" +\n \"((10.0 10.0, 14.0 12.0, 11.0 10.0, 10.0 10.0), (11.0 11.0, 11.5 11.0, 11.0 11.5, 11.0 11.0)))\",\n ms.toString());\n }\n\n @Test\n public void twoDimensionalMeasured() {\n String wkt = \"MULTISURFACE M (CURVEPOLYGON(CIRCULARSTRING(0 0 1, 4 0 2, 4 4 3, 0 4 4, 0 0 1),(1 1 1, 3 3 2, 3 1 3, 1 1 1)),\" +\n \"((10 10 20, 14 12 21, 11 10 22, 10 10 20),(11 11 30, 11.5 11 31, 11 11.5 32, 11 11 30)))\";\n WKTParser parser = Parboiled.createParser(WKTParser.class);\n ParsingResult result = new ReportingParseRunner(parser.WKT()).run(wkt);\n Geometry geometry = result.resultValue;\n assertNotNull(geometry);\n assertTrue(geometry instanceof MultiSurface);\n MultiSurface ms = (MultiSurface) geometry;\n assertFalse(ms.isEmpty());\n assertNull(ms.getSrid());\n assertEquals(Dimension.TwoMeasured, ms.getDimension());\n assertEquals(2, ms.getSurfaces().size());\n // 0\n assertTrue(ms.getSurfaces().get(0) instanceof CurvePolygon);\n CurvePolygon cp = (CurvePolygon) ms.getSurfaces().get(0);\n assertNull(cp.getSrid());\n assertEquals(Dimension.TwoMeasured, cp.getDimension());\n // 0 Outer\n assertTrue(cp.getOuterCurve() instanceof CircularString);\n CircularString cs = (CircularString) cp.getOuterCurve();\n assertNull(cs.getSrid());\n assertEquals(Dimension.TwoMeasured, cs.getDimension());\n assertEquals(5, cs.getCoordinates().size());\n assertEquals(Coordinate.create2DM(0, 0, 1), cs.getCoordinates().get(0));\n assertEquals(Coordinate.create2DM(4, 0, 2), cs.getCoordinates().get(1));\n assertEquals(Coordinate.create2DM(4, 4, 3), cs.getCoordinates().get(2));\n assertEquals(Coordinate.create2DM(0, 4, 4), cs.getCoordinates().get(3));\n assertEquals(Coordinate.create2DM(0, 0, 1), cs.getCoordinates().get(4));\n // 0 Inner\n assertEquals(1, cp.getInnerCurves().size());\n assertTrue(cp.getInnerCurves().get(0) instanceof LineString);\n LineString ls = (LineString) cp.getInnerCurves().get(0);\n assertNull(ls.getSrid());\n assertEquals(Dimension.TwoMeasured, ls.getDimension());\n assertEquals(4, ls.getCoordinates().size());\n assertEquals(Coordinate.create2DM(1, 1, 1), ls.getCoordinates().get(0));\n assertEquals(Coordinate.create2DM(3, 3, 2), ls.getCoordinates().get(1));\n assertEquals(Coordinate.create2DM(3, 1, 3), ls.getCoordinates().get(2));\n assertEquals(Coordinate.create2DM(1, 1, 1), ls.getCoordinates().get(3));\n // 1", "answers": [" assertTrue(ms.getSurfaces().get(1) instanceof Polygon);"], "length": 742, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "d4d1d7d4-9190-40b3-babe-22e8af1c9546", "reasoning": "In the previous tests, after handling the first surface (index 0) the code proceeds to handle the second surface (index 1). The comment '// 1' marks the start of that section. The next logical line is the assertion that the second surface is a Polygon, matching the pattern used earlier.", "reasoning_model_answer": "assertTrue(ms.getSurfaces().get(1) instanceof Polygon);", "assistant_with_reasoning": "\nIn the previous tests, after handling the first surface (index 0) the code proceeds to handle the second surface (index 1). The comment '// 1' marks the start of that section. The next logical line is the assertion that the second surface is a Polygon, matching the pattern used earlier.\n\nassertTrue(ms.getSurfaces().get(1) instanceof Polygon);", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 2.316, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 11698, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "assertTrue(ms.getSurfaces().get(1) instanceof Polygon);", "score": 0.93, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "\"\"\"Undocumented Module\"\"\"\n\n__all__ = ['MetaInterval', 'Sequence', 'Parallel', 'ParallelEndTogether', 'Track']\n\nfrom panda3d.core import *\nfrom panda3d.direct import *\nfrom direct.directnotify.DirectNotifyGlobal import *\nfrom .IntervalManager import ivalMgr\nfrom . import Interval\nfrom direct.task.Task import TaskManager\n#if __debug__:\n# import direct.showbase.PythonUtil as PythonUtil\n\nPREVIOUS_END = CMetaInterval.RSPreviousEnd\nPREVIOUS_START = CMetaInterval.RSPreviousBegin\nTRACK_START = CMetaInterval.RSLevelBegin\n\nclass MetaInterval(CMetaInterval):\n # This is a Python-C++ hybrid class. MetaInterval is a Python\n # extension of the C++ class CMetaInterval, which adds some\n # Python-specific features (like list management).\n\n # This is the base class of Sequence, Parallel, and Track.\n\n notify = directNotify.newCategory(\"MetaInterval\")\n\n SequenceNum = 1\n def __init__(self, *ivals, **kw):\n #if __debug__:\n # self.debugInitTraceback = PythonUtil.StackTrace(\n # \"create interval\", 1, 10)\n\n name = None\n #if len(ivals) == 2 and isinstance(ivals[1], str):\n # # If the second parameter is a string, it's the name.\n # name = ivals[1]\n # ivals = ivals[0]\n #else:\n\n # Look for the name in the keyword params.\n if 'name' in kw:\n name = kw['name']\n del kw['name']\n\n # If the keyword \"autoPause\" or \"autoFinish\" is defined to\n # non-zero, it means the interval may be automatically paused\n # or finished when CIntervalManager::interrupt() is called.\n # This is generally called only on a catastrophic situation\n # (for instance, the connection to the server being lost) when\n # we have to exit right away; these keywords indicate\n # intervals that might not be cleaned up by their owners.\n\n autoPause = 0\n autoFinish = 0\n if 'autoPause' in kw:\n autoPause = kw['autoPause']\n del kw['autoPause']\n if 'autoFinish' in kw:\n autoFinish = kw['autoFinish']\n del kw['autoFinish']\n\n # A duration keyword specifies the duration the interval will\n # appear to have for the purposes of computing the start time\n # for subsequent intervals in a sequence or track.\n self.phonyDuration = -1\n if 'duration' in kw:\n self.phonyDuration = kw['duration']\n del kw['duration']\n\n if kw:\n self.notify.error(\"Unexpected keyword parameters: %s\" % (list(kw.keys())))\n\n # We must allow the old style: Track([ival0, ival1, ...]) as\n # well as the new style: Track(ival0, ival1, ...)\n\n # Note: this breaks in the case of a Track with one tuple:\n # Track((0, ival0),). We could go through some effort to fix\n # this case, but for now I prefer just to document it as a\n # bug, since it will go away when we eventually remove support\n # for the old interface.\n #if len(ivals) == 1 and \\\n # (isinstance(ivals[0], tuple) or \\\n # isinstance(ivals[0], list)):\n # self.ivals = ivals[0]\n #else:\n\n self.ivals = ivals\n\n self.__ivalsDirty = 1\n\n if name == None:\n name = self.__class__.__name__ + '-%d'\n\n if '%' in name:\n name = name % (self.SequenceNum)\n MetaInterval.SequenceNum += 1\n\n CMetaInterval.__init__(self, name)\n self.__manager = ivalMgr\n self.setAutoPause(autoPause)\n self.setAutoFinish(autoFinish)\n\n self.pstats = None\n if __debug__ and TaskManager.taskTimerVerbose:\n self.pname = name.split('-', 1)[0]\n self.pstats = PStatCollector(\"App:Show code:ivalLoop:%s\" % (self.pname))\n\n self.pythonIvals = []\n\n # If we are running in debug mode, we validate the intervals\n # in the list right away. There's no good reason to do this,\n # except that it makes it easier for the programmer to detect\n # when a MetaInterval is misdefined at creation time.\n assert self.validateComponents(self.ivals)\n\n\n\n # Functions to make the MetaInterval object act just like a Python\n # list of intervals:\n\n def append(self, ival):\n # Appends a single interval to the list so far.\n if isinstance(self.ivals, tuple):\n self.ivals = list(self.ivals)\n self.ivals.append(ival)\n self.__ivalsDirty = 1\n assert self.validateComponent(ival)\n\n def extend(self, ivals):\n # Appends a list of intervals to the list so far.\n self += ivals\n\n def count(self, ival):\n # Returns the number of occurrences of the indicated interval.\n return self.ivals.count(ival)\n\n def index(self, ival):\n # Returns the position of the indicated interval within the list.\n return self.ivals.index(ival)\n\n def insert(self, index, ival):\n # Inserts the given interval into the middle of the list.\n if isinstance(self.ivals, tuple):\n self.ivals = list(self.ivals)\n self.ivals.insert(index, ival)\n self.__ivalsDirty = 1\n assert self.validateComponent(ival)\n\n def pop(self, index = None):\n # Returns element index (or the last element) and removes it\n # from the list.\n if isinstance(self.ivals, tuple):\n self.ivals = list(self.ivals)\n self.__ivalsDirty = 1\n if index == None:\n return self.ivals.pop()\n else:\n return self.ivals.pop(index)\n\n def remove(self, ival):\n # Removes the indicated interval from the list.\n if isinstance(self.ivals, tuple):\n self.ivals = list(self.ivals)\n self.ivals.remove(ival)\n self.__ivalsDirty = 1\n\n def reverse(self):\n # Reverses the order of the intervals.\n if isinstance(self.ivals, tuple):\n self.ivals = list(self.ivals)\n self.ivals.reverse()\n self.__ivalsDirty = 1\n\n def sort(self, cmpfunc = None):\n # Sorts the intervals. (?)\n if isinstance(self.ivals, tuple):\n self.ivals = list(self.ivals)\n self.__ivalsDirty = 1\n if cmpfunc == None:\n self.ivals.sort()\n else:\n self.ivals.sort(cmpfunc)\n\n def __len__(self):\n return len(self.ivals)\n\n def __getitem__(self, index):\n return self.ivals[index]\n\n def __setitem__(self, index, value):\n if isinstance(self.ivals, tuple):\n self.ivals = list(self.ivals)\n self.ivals[index] = value", "answers": [" self.__ivalsDirty = 1"], "length": 747, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "a2baaabe-6827-4d76-ae19-dd5516e97261", "reasoning": "The __setitem__ method updates an element in the interval list. After assigning the new value, the code should mark the internal dirty flag so later processing knows the list changed. The next logical line is setting __ivalsDirty to 1.", "reasoning_model_answer": "self.__ivalsDirty = 1", "assistant_with_reasoning": "\nThe __setitem__ method updates an element in the interval list. After assigning the new value, the code should mark the internal dirty flag so later processing knows the list changed. The next logical line is setting __ivalsDirty to 1.\n\nself.__ivalsDirty = 1", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 2.7, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 6687, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "self.__ivalsDirty = 1", "score": 0.84, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "using UnityEngine;\nusing UnityEngine.EventSystems;\nusing UnityEngine.Serialization;\nusing System;\nusing System.Linq;\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Text.RegularExpressions;\n\nnamespace Fungus\n{\n\t/**\n\t * Visual scripting controller for the Flowchart programming language.\n\t * Flowchart objects may be edited visually using the Flowchart editor window.\n\t */\n\t[ExecuteInEditMode]\n\tpublic class Flowchart : MonoBehaviour \n\t{\n /**\n\t\t * Current version used to compare with the previous version so older versions can be custom-updated from previous versions.\n\t\t */\n public const string CURRENT_VERSION = \"1.0\";\n\n /**\n * The name of the initial block in a new flowchart.\n */\n public const string DEFAULT_BLOCK_NAME = \"New Block\";\n\n\t\t/**\n\t\t * Variable to track flowchart's version and if initial set up has completed.\n\t\t */\n\t\t[HideInInspector]\n\t\tpublic string version;\n\n\t\t/**\n\t\t * Scroll position of Flowchart editor window.\n\t\t */\n\t\t[HideInInspector]\n\t\tpublic Vector2 scrollPos;\n\n\t\t/**\n\t\t * Scroll position of Flowchart variables window.\n\t\t */\n\t\t[HideInInspector]\n\t\tpublic Vector2 variablesScrollPos;\n\n\t\t/**\n\t\t * Show the variables pane.\n\t\t */\n\t\t[HideInInspector]\n\t\tpublic bool variablesExpanded = true;\n\n\t\t/**\n\t\t * Height of command block view in inspector.\n\t\t */\n\t\t[HideInInspector]\n\t\tpublic float blockViewHeight = 400;\n\n\t\t/**\n\t\t * Zoom level of Flowchart editor window\n\t\t */\n\t\t[HideInInspector]\n\t\tpublic float zoom = 1f;\n\n\t\t/**\n\t\t * Scrollable area for Flowchart editor window.\n\t\t */\n\t\t[HideInInspector]\n\t\tpublic Rect scrollViewRect;\n\n\t\t/**\n\t\t * Currently selected block in the Flowchart editor.\n\t\t */\n\t\t[HideInInspector]\n\t\t[FormerlySerializedAs(\"selectedSequence\")]\n\t\tpublic Block selectedBlock;\n\t\t\n\t\t/**\n\t\t * Currently selected command in the Flowchart editor.\n\t\t */\n\t\t[HideInInspector]\n\t\tpublic List selectedCommands = new List();\n\n\t\t/**\n\t\t * The list of variables that can be accessed by the Flowchart.\n\t\t */\n\t\t[HideInInspector]\n\t\tpublic List variables = new List();\n\n\t\t[TextArea(3, 5)]\n\t\t[Tooltip(\"Description text displayed in the Flowchart editor window\")]\n\t\tpublic string description = \"\";\n\n\t\t/**\n\t \t * Slow down execution in the editor to make it easier to visualise program flow.\n\t \t */\n\t\t[Range(0f, 5f)]\n\t\t[Tooltip(\"Adds a pause after each execution step to make it easier to visualise program flow. Editor only, has no effect in platform builds.\")]\n\t\tpublic float stepPause = 0f;\n\n\t\t/**\n\t\t * Use command color when displaying the command list in the inspector.\n\t\t */\n\t\t[Tooltip(\"Use command color when displaying the command list in the Fungus Editor window\")]\n\t\tpublic bool colorCommands = true;\n\t\t\n\t\t/**\n\t\t * Hides the Flowchart block and command components in the inspector.\n\t\t * Deselect to inspect the block and command components that make up the Flowchart.\n\t\t */\n\t\t[Tooltip(\"Hides the Flowchart block and command components in the inspector\")]\n\t\tpublic bool hideComponents = true;\n\n\t\t/**\n\t\t * Saves the selected block and commands when saving the scene.\n\t\t * Helps avoid version control conflicts if you've only changed the active selection.\n\t\t */\n\t\t[Tooltip(\"Saves the selected block and commands when saving the scene.\")]\n\t\tpublic bool saveSelection = true;\n\n\t\t/**\n\t\t * Unique identifier for identifying this flowchart in localized string keys.\n\t\t */\n\t\t[Tooltip(\"Unique identifier for this flowchart in localized string keys. If no id is specified then the name of the Flowchart object will be used.\")]\n\t\tpublic string localizationId = \"\";\n\n\t\t/**\n\t\t * Cached list of flowchart objects in the scene for fast lookup\n\t\t */\n\t\tpublic static List cachedFlowcharts = new List();\n\n\t\tprotected static bool eventSystemPresent;\n\n\t\t/**\n\t\t * Returns the next id to assign to a new flowchart item.\n\t\t * Item ids increase monotically so they are guaranteed to\n\t\t * be unique within a Flowchart.\n\t\t */\n\t\tpublic int NextItemId()\n\t\t{\n\t\t\tint maxId = -1;\n\t\t\tBlock[] blocks = GetComponentsInChildren();\n\t\t\tforeach (Block block in blocks)\n\t\t\t{\n\t\t\t\tmaxId = Math.Max(maxId, block.itemId);\n\t\t\t}\n\t\t\t\n\t\t\tCommand[] commands = GetComponentsInChildren();\n\t\t\tforeach (Command command in commands)\n\t\t\t{\n\t\t\t\tmaxId = Math.Max(maxId, command.itemId);\n\t\t\t}\n\t\t\treturn maxId + 1;\n\t\t}\n\n\t\tprotected virtual void OnLevelWasLoaded(int level) \n\t\t{\n\t\t\t// Reset the flag for checking for an event system as there may not be one in the newly loaded scene.\n\t\t\teventSystemPresent = false;\n\t\t}\n\n\t\tprotected virtual void Start()\n\t\t{\n\t\t\tCheckEventSystem();\n\t\t}\n\t\t\n\t\t// There must be an Event System in the scene for Say and Menu input to work.\n\t\t// This method will automatically instantiate one if none exists.\n\t\tprotected virtual void CheckEventSystem()\n\t\t{\n\t\t\tif (eventSystemPresent)\n\t\t\t{\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t\n\t\t\tEventSystem eventSystem = GameObject.FindObjectOfType();\n\t\t\tif (eventSystem == null)\n\t\t\t{\n\t\t\t\t// Auto spawn an Event System from the prefab\n\t\t\t\tGameObject prefab = Resources.Load(\"EventSystem\");\n\t\t\t\tif (prefab != null)\n\t\t\t\t{\n\t\t\t\t\tGameObject go = Instantiate(prefab) as GameObject;\n\t\t\t\t\tgo.name = \"EventSystem\";\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\teventSystemPresent = true;\n\t\t}\n\n\t\tpublic virtual void OnEnable()\n\t\t{\n\t\t\tif (!cachedFlowcharts.Contains(this))\n\t\t\t{\n\t\t\t\tcachedFlowcharts.Add(this);\n\t\t\t}\n\n\t\t\tCheckItemIds();\n\t\t\tCleanupComponents();\n\t\t UpdateVersion();\n\t\t}\n\n\t\tpublic virtual void OnDisable()\n\t\t{\n\t\t\tcachedFlowcharts.Remove(this);\n\t\t}\n\n\t\tprotected virtual void CheckItemIds()\n\t\t{\n\t\t\t// Make sure item ids are unique and monotonically increasing.\n\t\t\t// This should always be the case, but some legacy Flowcharts may have issues.\n\t\t\tList usedIds = new List();\n\t\t\tBlock[] blocks = GetComponentsInChildren();\n\t\t\tforeach (Block block in blocks)\n\t\t\t{\n\t\t\t\tif (block.itemId == -1 ||\n\t\t\t\t usedIds.Contains(block.itemId))\n\t\t\t\t{\n\t\t\t\t\tblock.itemId = NextItemId();\n\t\t\t\t}\n\t\t\t\tusedIds.Add(block.itemId);\n\t\t\t}\n\t\t\t\n\t\t\tCommand[] commands = GetComponentsInChildren();\n\t\t\tforeach (Command command in commands)\n\t\t\t{\n\t\t\t\tif (command.itemId == -1 ||\n\t\t\t\t usedIds.Contains(command.itemId))\n\t\t\t\t{\n\t\t\t\t\tcommand.itemId = NextItemId();\n\t\t\t\t}\n\t\t\t\tusedIds.Add(command.itemId);\n\t\t\t}\n\t\t}\n", "answers": ["\t\tprotected virtual void CleanupComponents()"], "length": 792, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "17a48f8e-5dcd-48ff-8157-410f74787366", "reasoning": "The CheckItemIds method just ended, and the class’s OnEnable method earlier called CleanupComponents(). Following typical Fungus Flowchart code, the next member defined is the CleanupComponents method. Consistent with the style used earlier (method signature on its own line, opening brace on the next line), the next line should be the method signature.", "reasoning_model_answer": "protected virtual void CleanupComponents()", "assistant_with_reasoning": "\nThe CheckItemIds method just ended, and the class’s OnEnable method earlier called CleanupComponents(). Following typical Fungus Flowchart code, the next member defined is the CleanupComponents method. Consistent with the style used earlier (method signature on its own line, opening brace on the next line), the next line should be the method signature.\n\nprotected virtual void CleanupComponents()", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 5.01, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 6341, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "protected virtual void CleanupComponents()", "score": 0.98, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n// ------------------------------------------------------------------------------\n// Changes to this file must follow the http://aka.ms/api-review process.\n// ------------------------------------------------------------------------------\n\n\nnamespace System.ComponentModel.DataAnnotations\n{\n [System.AttributeUsageAttribute((System.AttributeTargets)(384), AllowMultiple = false, Inherited = true)]\n [System.ObsoleteAttribute(\"This attribute is no longer in use and will be ignored if applied.\")]\n public sealed partial class AssociationAttribute : System.Attribute\n {\n public AssociationAttribute(string name, string thisKey, string otherKey) { }\n public bool IsForeignKey { get { throw null; } set { } }\n public string Name { get { throw null; } }\n public string OtherKey { get { throw null; } }\n public System.Collections.Generic.IEnumerable OtherKeyMembers { get { throw null; } }\n public string ThisKey { get { throw null; } }\n public System.Collections.Generic.IEnumerable ThisKeyMembers { get { throw null; } }\n }\n [System.AttributeUsageAttribute((System.AttributeTargets)(128), AllowMultiple = false)]\n public partial class CompareAttribute : System.ComponentModel.DataAnnotations.ValidationAttribute\n {\n public CompareAttribute(string otherProperty) { }\n public string OtherProperty { get { throw null; } }\n public string OtherPropertyDisplayName { get { throw null; } }\n public override bool RequiresValidationContext { get { throw null; } }\n public override string FormatErrorMessage(string name) { throw null; }\n protected override System.ComponentModel.DataAnnotations.ValidationResult IsValid(object value, System.ComponentModel.DataAnnotations.ValidationContext validationContext) { throw null; }\n }\n [System.AttributeUsageAttribute((System.AttributeTargets)(384), AllowMultiple = false, Inherited = true)]\n public sealed partial class ConcurrencyCheckAttribute : System.Attribute\n {\n public ConcurrencyCheckAttribute() { }\n }\n [System.AttributeUsageAttribute((System.AttributeTargets)(2432), AllowMultiple = false)]\n public sealed partial class CreditCardAttribute : System.ComponentModel.DataAnnotations.DataTypeAttribute\n {\n public CreditCardAttribute() : base(default(System.ComponentModel.DataAnnotations.DataType)) { }\n public override bool IsValid(object value) { throw null; }\n }\n [System.AttributeUsageAttribute((System.AttributeTargets)(2500), AllowMultiple = true)]\n public sealed partial class CustomValidationAttribute : System.ComponentModel.DataAnnotations.ValidationAttribute\n {\n public CustomValidationAttribute(System.Type validatorType, string method) { }\n public string Method { get { throw null; } }\n public System.Type ValidatorType { get { throw null; } }\n public override string FormatErrorMessage(string name) { throw null; }\n protected override System.ComponentModel.DataAnnotations.ValidationResult IsValid(object value, System.ComponentModel.DataAnnotations.ValidationContext validationContext) { throw null; }\n }\n public enum DataType\n {\n CreditCard = 14,\n Currency = 6,\n Custom = 0,\n Date = 2,\n DateTime = 1,\n Duration = 4,\n EmailAddress = 10,\n Html = 8,\n ImageUrl = 13,\n MultilineText = 9,\n Password = 11,\n PhoneNumber = 5,\n PostalCode = 15,\n Text = 7,\n Time = 3,\n Upload = 16,\n Url = 12,\n }\n [System.AttributeUsageAttribute((System.AttributeTargets)(2496), AllowMultiple = false)]\n public partial class DataTypeAttribute : System.ComponentModel.DataAnnotations.ValidationAttribute\n {\n public DataTypeAttribute(System.ComponentModel.DataAnnotations.DataType dataType) { }\n public DataTypeAttribute(string customDataType) { }\n public string CustomDataType { get { throw null; } }\n public System.ComponentModel.DataAnnotations.DataType DataType { get { throw null; } }\n public System.ComponentModel.DataAnnotations.DisplayFormatAttribute DisplayFormat { get { throw null; } protected set { } }\n public virtual string GetDataTypeName() { throw null; }\n public override bool IsValid(object value) { throw null; }\n }\n [System.AttributeUsageAttribute((System.AttributeTargets)(2496), AllowMultiple = false)]\n public sealed partial class DisplayAttribute : System.Attribute\n {\n public DisplayAttribute() { }\n public bool AutoGenerateField { get { throw null; } set { } }\n public bool AutoGenerateFilter { get { throw null; } set { } }\n public string Description { get { throw null; } set { } }\n public string GroupName { get { throw null; } set { } }\n public string Name { get { throw null; } set { } }\n public int Order { get { throw null; } set { } }\n public string Prompt { get { throw null; } set { } }\n public System.Type ResourceType { get { throw null; } set { } }\n public string ShortName { get { throw null; } set { } }\n public System.Nullable GetAutoGenerateField() { throw null; }\n public System.Nullable GetAutoGenerateFilter() { throw null; }\n public string GetDescription() { throw null; }\n public string GetGroupName() { throw null; }\n public string GetName() { throw null; }\n public System.Nullable GetOrder() { throw null; }\n public string GetPrompt() { throw null; }\n public string GetShortName() { throw null; }\n }\n [System.AttributeUsageAttribute((System.AttributeTargets)(4), Inherited = true, AllowMultiple = false)]\n public partial class DisplayColumnAttribute : System.Attribute\n {\n public DisplayColumnAttribute(string displayColumn) { }\n public DisplayColumnAttribute(string displayColumn, string sortColumn) { }\n public DisplayColumnAttribute(string displayColumn, string sortColumn, bool sortDescending) { }\n public string DisplayColumn { get { throw null; } }\n public string SortColumn { get { throw null; } }\n public bool SortDescending { get { throw null; } }\n }\n [System.AttributeUsageAttribute((System.AttributeTargets)(384), AllowMultiple = false)]\n public partial class DisplayFormatAttribute : System.Attribute\n {\n public DisplayFormatAttribute() { }\n public bool ApplyFormatInEditMode { get { throw null; } set { } }\n public bool ConvertEmptyStringToNull { get { throw null; } set { } }\n public string DataFormatString { get { throw null; } set { } }\n public bool HtmlEncode { get { throw null; } set { } }\n public string NullDisplayText { get { throw null; } set { } }\n }\n [System.AttributeUsageAttribute((System.AttributeTargets)(384), AllowMultiple = false, Inherited = true)]\n public sealed partial class EditableAttribute : System.Attribute\n {\n public EditableAttribute(bool allowEdit) { }\n public bool AllowEdit { get { throw null; } }\n public bool AllowInitialValue { get { throw null; } set { } }\n }\n [System.AttributeUsageAttribute((System.AttributeTargets)(2432), AllowMultiple = false)]\n public sealed partial class EmailAddressAttribute : System.ComponentModel.DataAnnotations.DataTypeAttribute\n {\n public EmailAddressAttribute() : base(default(System.ComponentModel.DataAnnotations.DataType)) { }\n public override bool IsValid(object value) { throw null; }\n }\n [System.AttributeUsageAttribute((System.AttributeTargets)(2496), AllowMultiple = false)]", "answers": [" public sealed partial class EnumDataTypeAttribute : System.ComponentModel.DataAnnotations.DataTypeAttribute"], "length": 877, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "313e7a36-3390-4719-939f-fa19da9560dc", "reasoning": "The snippet ends with an AttributeUsage attribute for a class that follows EmailAddressAttribute in the DataAnnotations namespace. The next member in the .NET source after EmailAddressAttribute is the FileExtensionsAttribute, which is declared with the given AttributeUsage flags. Therefore the next line is the class declaration for FileExtensionsAttribute.", "reasoning_model_answer": "public sealed partial class FileExtensionsAttribute : System.ComponentModel.DataAnnotations.ValidationAttribute", "assistant_with_reasoning": "\nThe snippet ends with an AttributeUsage attribute for a class that follows EmailAddressAttribute in the DataAnnotations namespace. The next member in the .NET source after EmailAddressAttribute is the FileExtensionsAttribute, which is declared with the given AttributeUsage flags. Therefore the next line is the class declaration for FileExtensionsAttribute.\n\npublic sealed partial class FileExtensionsAttribute : System.ComponentModel.DataAnnotations.ValidationAttribute", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 6.525, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 7972, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "public sealed partial class FileExtensionsAttribute : System.ComponentModel.DataAnnotations.ValidationAttribute", "score": 0.81, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/**\n *\n * Copyright (c) 2005-2012. Centre for Research on Inner City Health, St. Michael's Hospital, Toronto. All Rights Reserved.\n * This software is published under the GPL GNU General Public License.\n * This program is free software; you can redistribute it and/or\n * modify it under the terms of the GNU General Public License\n * as published by the Free Software Foundation; either version 2\n * of the License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.\n *\n * This software was written for\n * Centre for Research on Inner City Health, St. Michael's Hospital,\n * Toronto, Ontario, Canada\n */\npackage org.oscarehr.web;\n\nimport java.text.SimpleDateFormat;\nimport java.util.ArrayList;\nimport java.util.Calendar;\nimport java.util.Collection;\nimport java.util.Date;\nimport java.util.GregorianCalendar;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.List;\n\nimport org.apache.commons.collections.map.MultiValueMap;\nimport org.apache.commons.lang.StringEscapeUtils;\nimport org.apache.log4j.Logger;\nimport org.oscarehr.PMmodule.dao.ProgramDao;\nimport org.oscarehr.PMmodule.model.Program;\nimport org.oscarehr.common.dao.AdmissionDao;\nimport org.oscarehr.common.dao.CdsClientFormDao;\nimport org.oscarehr.common.dao.CdsClientFormDataDao;\nimport org.oscarehr.common.dao.CdsFormOptionDao;\nimport org.oscarehr.common.dao.CdsHospitalisationDaysDao;\nimport org.oscarehr.common.dao.DemographicDao;\nimport org.oscarehr.common.dao.FunctionalCentreDao;\nimport org.oscarehr.common.model.Admission;\nimport org.oscarehr.common.model.CdsClientForm;\nimport org.oscarehr.common.model.CdsClientFormData;\nimport org.oscarehr.common.model.CdsFormOption;\nimport org.oscarehr.common.model.CdsHospitalisationDays;\nimport org.oscarehr.common.model.Demographic;\nimport org.oscarehr.common.model.FunctionalCentre;\nimport org.oscarehr.util.AccumulatorMap;\nimport org.oscarehr.util.LoggedInInfo;\nimport org.oscarehr.util.MiscUtils;\nimport org.oscarehr.util.SpringUtils;\n\nimport oscar.util.DateUtils;\n\npublic final class Cds4ReportUIBean {\n\n\tprivate static Logger logger = MiscUtils.getLogger();\n\n\tprivate static FunctionalCentreDao functionalCentreDao = (FunctionalCentreDao) SpringUtils.getBean(\"functionalCentreDao\");\n\tprivate static CdsFormOptionDao cdsFormOptionDao = (CdsFormOptionDao) SpringUtils.getBean(\"cdsFormOptionDao\");\n\tprivate static CdsClientFormDao cdsClientFormDao = (CdsClientFormDao) SpringUtils.getBean(\"cdsClientFormDao\");\n\tprivate static CdsClientFormDataDao cdsClientFormDataDao = (CdsClientFormDataDao) SpringUtils.getBean(\"cdsClientFormDataDao\");\n\tprivate static AdmissionDao admissionDao = (AdmissionDao) SpringUtils.getBean(\"admissionDao\");\n\tprivate static ProgramDao programDao = (ProgramDao) SpringUtils.getBean(\"programDao\");\n\tprivate static CdsHospitalisationDaysDao cdsHospitalisationDaysDao = (CdsHospitalisationDaysDao) SpringUtils.getBean(\"cdsHospitalisationDaysDao\");\n\tprivate static DemographicDao demographicDao = (DemographicDao) SpringUtils.getBean(\"demographicDao\");\n\n\tpublic static final int NUMBER_OF_COHORT_BUCKETS = 11;\n\tprivate static final int NUMBER_OF_DATA_ROW_COLUMNS=NUMBER_OF_COHORT_BUCKETS+1;\n\n\tenum MinMax {\n\t\tMIN, MAX\n\t}\n\n\tpublic static class SingleMultiAdmissions {\n\t\t// key=clientId\n\t\tpublic HashMap singleAdmissions = new HashMap();\n\n\t\t// this is a map where key=0-10 representing each cohort bucket., value is a collection of CdsClientForms\n\t\tpublic MultiValueMap singleAdmissionCohortBuckets = new MultiValueMap();\n\n\t\t// key=clientId\n\t\tpublic HashMap multipleAdmissionsLatestForms = new HashMap();\n\t\t\n\t\tpublic ArrayList multipleAdmissionsAllForms = new ArrayList();\n\n\t\t// this is a map where key=0-10 representing each cohort bucket., value is a collection of CdsClientForms\n\t\tpublic MultiValueMap multipleAdmissionCohortBuckets = new MultiValueMap();\n\t\t\n\t\tpublic void addUniqueCdsProgramFormToMultipleAdmissionsAllForms(CdsClientForm cdsClientForm)\n\t\t{\n\t\t\tfor (CdsClientForm tempForm : multipleAdmissionsAllForms)\n\t\t\t{\n\t\t\t\tif (tempForm.getCdsFormVersion().equals(cdsClientForm.getCdsFormVersion()) && tempForm.getAdmissionId().equals(cdsClientForm.getAdmissionId()))\n\t\t\t\t{\n\t\t\t\t\tif (cdsClientForm.getCreated().after(tempForm.getCreated()))\n\t\t\t\t\t{\n\t\t\t\t\t\tmultipleAdmissionsAllForms.remove(tempForm);\n\t\t\t\t\t\tmultipleAdmissionsAllForms.add(cdsClientForm);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\t// else do nothing and keep the old one.\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t/** key=admissionId, value=admission */\n\tprivate HashMap admissionMap = null;\n\tprivate SingleMultiAdmissions singleMultiAdmissions=null;\n\tprivate FunctionalCentre functionalCentre=null;\n\tprivate GregorianCalendar startDate=new GregorianCalendar();\n\tprivate GregorianCalendar endDateExclusive=new GregorianCalendar();\n\tprivate HashSet providerIdsToReportOn=null;\n\tprivate HashSet programIdsToReportOn=null;\n\tprivate LoggedInInfo loggedInInfo=null;\n\t\n\t/**\n\t * End dates should be treated as inclusive.\n\t */\n\tpublic Cds4ReportUIBean(LoggedInInfo loggedInInfo, String functionalCentreId, Date startDate, Date endDateInclusive, String[] providerIdList, HashSet programIds) {\n\n\t\tthis.loggedInInfo=loggedInInfo;\n\t\tthis.startDate.setTime(startDate);\n\t\tthis.endDateExclusive.setTime(endDateInclusive);\n\t\tthis.endDateExclusive.add(GregorianCalendar.DAY_OF_YEAR, 1); // add 1 to make exclusive\n\t\t\n\t\t// put providerId's in a Hash for quicker searches.\n\t\tif (providerIdList!=null)\n\t\t{\n\t\t\tproviderIdsToReportOn=new HashSet();\n\t\t\tfor (String s : providerIdList)\n\t\t\t{\n\t\t\t\tproviderIdsToReportOn.add(s);\n\t\t\t}\n\t\t}\n\t\t\n\t\tprogramIdsToReportOn=programIds;\n\t\t\n\t\tfunctionalCentre=functionalCentreDao.find(functionalCentreId);\n\t\t\n\t\tadmissionMap=getAdmissionMap();\n\t\t\n\t\tsingleMultiAdmissions = getAdmissionsSortedSingleMulti();\n\t}\n\t\n\tpublic String getFunctionalCentreDescription()\n\t{\n\t\treturn(StringEscapeUtils.escapeHtml(functionalCentre.getAccountId()+\", \"+functionalCentre.getDescription()));\n\t}\n\t\n\tpublic String getDateRangeForDisplay() \n\t{\n\t\tSimpleDateFormat simpleDateFormat=new SimpleDateFormat(\"yyyy-MM-dd\");\n\t\tGregorianCalendar displayEndDate=(GregorianCalendar) endDateExclusive.clone();\n\t\tdisplayEndDate.add(GregorianCalendar.DAY_OF_YEAR, -1);\n\t\treturn(StringEscapeUtils.escapeHtml(simpleDateFormat.format(startDate.getTime())+\" to \"+simpleDateFormat.format(displayEndDate.getTime())+\" (inclusive)\"));\n\t}\n\n\tpublic static List getCdsFormOptions()\n\t{\n\t\treturn(cdsFormOptionDao.findByVersion(\"4\"));\n\t}\n\t\n\tprivate SingleMultiAdmissions getAdmissionsSortedSingleMulti() {\n\t\tSingleMultiAdmissions singleMultiAdmissions = new SingleMultiAdmissions();\n\n\t\tList cdsForms = cdsClientFormDao.findSignedCdsForms(loggedInInfo.getCurrentFacility().getId(), \"4\", startDate.getTime(), endDateExclusive.getTime());\n\t\tlogger.debug(\"valid cds form count, \"+loggedInInfo.getCurrentFacility().getId()+\", 4, \"+startDate.getTime()+\", \"+endDateExclusive.getTime()+\", \"+cdsForms.size());\n\t\t\n\t\t// sort into single and multiple admissions\n\t\tfor (CdsClientForm form : cdsForms) {\n\t\t\tlogger.debug(\"valid cds form, id=\"+form.getId());\n\t\t\t\n\t\t\t// make sure form is for an admission for which we're interested, i.e. admissions are filtered by program and admission time already\n\t\t\tAdmission admission = admissionMap.get(form.getAdmissionId());\n\t\t\tif (admission == null) {\n\t\t\t\tlogger.debug(\"cds form missing admission / or not in admission we're interested in dueto program or time restriction. formId=\"+form.getId()+\", admissionId=\"+form.getAdmissionId());\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t// check if the cds form is signed by a provider we're reporting on.\n\t\t\t\tif (providerIdsToReportOn!=null) // if we've been asked to filter\n\t\t\t\t{\n\t\t\t\t\tif (!providerIdsToReportOn.contains(form.getProviderNo())) // if the provider isn't in our allowed list\n\t\t\t\t\t{\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tInteger clientId = form.getClientId();\n\n\t\t\tCdsClientForm existingForm = singleMultiAdmissions.multipleAdmissionsLatestForms.get(clientId);\n\t\t\t// if this person already has multiple admissions\n\t\t\tif (existingForm != null) {\n\t\t\t\tlogger.debug(\"multiple admissions 3+ forms. formId=\"+form.getId()+\", otherFormId=\"+existingForm.getId());\n\t\t\t\tsingleMultiAdmissions.multipleAdmissionsLatestForms.put(clientId, getNewerForm(existingForm, form));\n\t\t\t\tsingleMultiAdmissions.addUniqueCdsProgramFormToMultipleAdmissionsAllForms(form);\n\t\t\t} else // this person either has one previous or no previous admissions\n\t\t\t{\n\t\t\t\texistingForm = singleMultiAdmissions.singleAdmissions.get(clientId);\n\t\t\t\t// this means we have 1 previous admission\n\t\t\t\tif (existingForm != null) {\n\t\t\t\t\t\n\t\t\t\t\t// check that it's actually multiple admission and not just multiple forms for 1 admission\n\t\t\t\t\t\n\t\t\t\t\t// they are the same, just pick the newer form\n\t\t\t\t\tif (existingForm.getAdmissionId().equals(form.getAdmissionId()))\n\t\t\t\t\t{\n\t\t\t\t\t\tif (form.getCreated().after(existingForm.getCreated()))\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tsingleMultiAdmissions.singleAdmissions.put(clientId, form);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tlogger.debug(\"multiple admissions, 2 forms : formId=\"+form.getId()+\", otherFormId=\"+existingForm.getId());\n\t\t\t\t\t\t", "answers": ["\t\t\t\t\t\tsingleMultiAdmissions.multipleAdmissionsLatestForms.put(clientId, getNewerForm(existingForm, form));"], "length": 823, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "edaddf1a-55ce-4120-8cfd-296f39b51b58", "reasoning": "The code is inside getAdmissionsSortedSingleMulti(). When a second admission is detected (different admissionId), the comment indicates handling multiple admissions. The next logical step is to record the latest form for this client in the multipleAdmissionsLatestForms map, similar to later handling of existing multiple admissions. Therefore the next line should add or update the map with the newer of the existing and current forms.", "reasoning_model_answer": "singleMultiAdmissions.multipleAdmissionsLatestForms.put(clientId, getNewerForm(existingForm, form));", "assistant_with_reasoning": "\nThe code is inside getAdmissionsSortedSingleMulti(). When a second admission is detected (different admissionId), the comment indicates handling multiple admissions. The next logical step is to record the latest form for this client in the multipleAdmissionsLatestForms map, similar to later handling of existing multiple admissions. Therefore the next line should add or update the map with the newer of the existing and current forms.\n\nsingleMultiAdmissions.multipleAdmissionsLatestForms.put(clientId, getNewerForm(existingForm, form));", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.857, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 9771, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "singleMultiAdmissions.multipleAdmissionsLatestForms.put(clientId, getNewerForm(existingForm, form));", "score": 0.97, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "# Copyright 2011 OpenStack Foundation\n# All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nimport uuid\n\nimport ddt\nimport mock\nfrom oslo_serialization import jsonutils\nfrom six.moves import http_client\nimport webob\n\nfrom cinder.api import extensions\nfrom cinder.api.v2 import snapshot_metadata\nfrom cinder.api.v2 import snapshots\nfrom cinder import context\nimport cinder.db\nfrom cinder import exception\nfrom cinder.objects import fields\nfrom cinder import test\nfrom cinder.tests.unit.api import fakes\nfrom cinder.tests.unit import fake_constants as fake\nfrom cinder.tests.unit import fake_snapshot\nfrom cinder.tests.unit import fake_volume\nfrom cinder import volume\n\n\ndef return_create_snapshot_metadata(context, snapshot_id, metadata, delete):\n return fake_snapshot_metadata()\n\n\ndef return_create_snapshot_metadata_insensitive(context, snapshot_id,\n metadata, delete):\n return fake_snapshot_metadata_insensitive()\n\n\ndef return_new_snapshot_metadata(context, snapshot_id, metadata, delete):\n return fake_new_snapshot_metadata()\n\n\ndef fake_snapshot_metadata():\n metadata = {\n \"key1\": \"value1\",\n \"key2\": \"value2\",\n \"key3\": \"value3\",\n }\n return metadata\n\n\ndef fake_snapshot_metadata_insensitive():\n metadata = {\n \"key1\": \"value1\",\n \"key2\": \"value2\",\n \"key3\": \"value3\",\n \"KEY4\": \"value4\",\n }\n return metadata\n\n\ndef fake_new_snapshot_metadata():\n metadata = {\n 'key10': 'value10',\n 'key99': 'value99',\n 'KEY20': 'value20',\n }\n return metadata\n\n\ndef return_snapshot(context, snapshot_id):\n return {'id': '0cc3346e-9fef-4445-abe6-5d2b2690ec64',\n 'name': 'fake',\n 'status': 'available',\n 'metadata': {}}\n\n\n# First argument needs to be self to receive the context argument in the right\n# variable, as this'll be used to replace the original API.get method which\n# receives self as the first argument.\ndef fake_get(self, context, *args, **kwargs):\n vol = {'id': fake.VOLUME_ID,\n 'size': 100,\n 'name': 'fake',\n 'host': 'fake-host',\n 'status': 'available',\n 'encryption_key_id': None,\n 'volume_type_id': None,\n 'migration_status': None,\n 'availability_zone': 'fake-zone',\n 'attach_status': fields.VolumeAttachStatus.DETACHED,\n 'metadata': {}}\n return fake_volume.fake_volume_obj(context, **vol)\n\n\ndef return_snapshot_nonexistent(context, snapshot_id):\n raise exception.SnapshotNotFound(snapshot_id=snapshot_id)\n\n\n@ddt.ddt\nclass SnapshotMetaDataTest(test.TestCase):\n\n def setUp(self):\n super(SnapshotMetaDataTest, self).setUp()\n self.volume_api = cinder.volume.api.API()\n self.mock_object(volume.api.API, 'get', fake_get)\n self.mock_object(cinder.db, 'snapshot_get', return_snapshot)\n self.mock_object(self.volume_api, 'update_snapshot_metadata')\n\n self.ext_mgr = extensions.ExtensionManager()\n self.ext_mgr.extensions = {}\n self.snapshot_controller = snapshots.SnapshotsController(self.ext_mgr)\n self.controller = snapshot_metadata.Controller()\n self.req_id = str(uuid.uuid4())\n self.url = '/v2/%s/snapshots/%s/metadata' % (\n fake.PROJECT_ID, self.req_id)\n\n snap = {\"volume_size\": 100,\n \"volume_id\": fake.VOLUME_ID,\n \"display_name\": \"Volume Test Name\",\n \"display_description\": \"Volume Test Desc\",\n \"availability_zone\": \"zone1:host1\",\n \"host\": \"fake-host\",\n \"metadata\": {}}\n body = {\"snapshot\": snap}\n req = fakes.HTTPRequest.blank('/v2/snapshots')\n self.snapshot_controller.create(req, body)\n\n @mock.patch('cinder.objects.Snapshot.get_by_id')\n def test_index(self, snapshot_get_by_id):\n snapshot = {\n 'id': self.req_id,\n 'expected_attrs': ['metadata']\n }\n ctx = context.RequestContext(fake.USER_ID, fake.PROJECT_ID, True)\n snapshot_obj = fake_snapshot.fake_snapshot_obj(ctx, **snapshot)\n snapshot_obj['metadata'] = {'key1': 'value1',\n 'key2': 'value2',\n 'key3': 'value3'}\n snapshot_get_by_id.return_value = snapshot_obj\n\n req = fakes.HTTPRequest.blank(self.url)\n res_dict = self.controller.index(req, self.req_id)\n\n expected = {\n 'metadata': {\n 'key1': 'value1',\n 'key2': 'value2',\n 'key3': 'value3',\n },\n }\n self.assertEqual(expected, res_dict)\n\n @mock.patch('cinder.objects.Snapshot.get_by_id')\n def test_index_nonexistent_snapshot(self, snapshot_get_by_id):\n snapshot_get_by_id.side_effect = \\\n exception.SnapshotNotFound(snapshot_id=self.req_id)\n\n req = fakes.HTTPRequest.blank(self.url)\n self.assertRaises(exception.SnapshotNotFound,\n self.controller.index, req, self.url)\n\n @mock.patch('cinder.objects.Snapshot.get_by_id')\n def test_index_no_data(self, snapshot_get_by_id):\n snapshot = {\n 'id': self.req_id,\n 'expected_attrs': ['metadata']\n }\n ctx = context.RequestContext(fake.USER_ID, fake.PROJECT_ID, True)\n snapshot_obj = fake_snapshot.fake_snapshot_obj(ctx, **snapshot)\n snapshot_get_by_id.return_value = snapshot_obj\n\n req = fakes.HTTPRequest.blank(self.url)\n res_dict = self.controller.index(req, self.req_id)\n expected = {'metadata': {}}\n self.assertEqual(expected, res_dict)\n\n @mock.patch('cinder.objects.Snapshot.get_by_id')\n def test_show(self, snapshot_get_by_id):\n snapshot = {\n 'id': self.req_id,\n 'expected_attrs': ['metadata']\n }\n ctx = context.RequestContext(fake.USER_ID, fake.PROJECT_ID, True)\n snapshot_obj = fake_snapshot.fake_snapshot_obj(ctx, **snapshot)\n snapshot_obj['metadata'] = {'key2': 'value2'}\n snapshot_get_by_id.return_value = snapshot_obj\n\n req = fakes.HTTPRequest.blank(self.url + '/key2')\n res_dict = self.controller.show(req, self.req_id, 'key2')\n expected = {'meta': {'key2': 'value2'}}\n self.assertEqual(expected, res_dict)\n\n @mock.patch('cinder.objects.Snapshot.get_by_id')\n def test_show_nonexistent_snapshot(self, snapshot_get_by_id):\n snapshot_get_by_id.side_effect = \\\n exception.SnapshotNotFound(snapshot_id=self.req_id)\n\n req = fakes.HTTPRequest.blank(self.url + '/key2')\n self.assertRaises(exception.SnapshotNotFound,\n self.controller.show, req, self.req_id, 'key2')\n\n @mock.patch('cinder.objects.Snapshot.get_by_id')\n def test_show_meta_not_found(self, snapshot_get_by_id):\n snapshot = {\n 'id': self.req_id,\n 'expected_attrs': ['metadata']\n }\n ctx = context.RequestContext(fake.USER_ID, fake.PROJECT_ID, True)\n snapshot_obj = fake_snapshot.fake_snapshot_obj(ctx, **snapshot)\n snapshot_get_by_id.return_value = snapshot_obj\n\n req = fakes.HTTPRequest.blank(self.url + '/key6')\n self.assertRaises(exception.SnapshotMetadataNotFound,\n self.controller.show, req, self.req_id, 'key6')\n\n @mock.patch('cinder.db.snapshot_metadata_delete')\n @mock.patch('cinder.objects.Snapshot.get_by_id')\n def test_delete(self, snapshot_get_by_id, snapshot_metadata_delete):\n snapshot = {\n 'id': self.req_id,\n 'expected_attrs': ['metadata']\n }\n ctx = context.RequestContext(fake.USER_ID, fake.PROJECT_ID, True)\n snapshot_obj = fake_snapshot.fake_snapshot_obj(ctx, **snapshot)\n snapshot_obj['metadata'] = {'key2': 'value2'}\n snapshot_get_by_id.return_value = snapshot_obj\n\n req = fakes.HTTPRequest.blank(self.url + '/key2')\n req.method = 'DELETE'\n res = self.controller.delete(req, self.req_id, 'key2')\n\n self.assertEqual(http_client.OK, res.status_int)\n\n def test_delete_nonexistent_snapshot(self):\n self.mock_object(cinder.db, 'snapshot_get',\n return_snapshot_nonexistent)\n req = fakes.HTTPRequest.blank(self.url + '/key1')\n req.method = 'DELETE'\n self.assertRaises(exception.SnapshotNotFound,\n self.controller.delete, req, self.req_id, 'key1')\n\n @mock.patch('cinder.objects.Snapshot.get_by_id')\n def test_delete_meta_not_found(self, snapshot_get_by_id):\n snapshot = {\n 'id': self.req_id,\n 'expected_attrs': ['metadata']\n }\n ctx = context.RequestContext(fake.USER_ID, fake.PROJECT_ID, True)\n snapshot_obj = fake_snapshot.fake_snapshot_obj(ctx, **snapshot)\n snapshot_get_by_id.return_value = snapshot_obj\n\n req = fakes.HTTPRequest.blank(self.url + '/key6')\n req.method = 'DELETE'\n self.assertRaises(exception.SnapshotMetadataNotFound,\n self.controller.delete, req, self.req_id, 'key6')\n\n @mock.patch('cinder.db.snapshot_update')\n @mock.patch('cinder.objects.Volume.get_by_id')\n @mock.patch('cinder.objects.Snapshot.get_by_id')\n def test_create(self, snapshot_get_by_id, volume_get_by_id,\n snapshot_update):\n snapshot = {\n 'id': self.req_id,\n 'expected_attrs': ['metadata']\n }\n ctx = context.RequestContext(fake.USER_ID, fake.PROJECT_ID, True)\n snapshot_obj = fake_snapshot.fake_snapshot_obj(ctx, **snapshot)\n fake_volume_obj = fake_volume.fake_volume_obj(ctx)\n snapshot_get_by_id.return_value = snapshot_obj\n volume_get_by_id.return_value = fake_volume_obj\n\n self.mock_object(cinder.db, 'snapshot_metadata_update',\n return_create_snapshot_metadata)\n\n req = fakes.HTTPRequest.blank('/v2/snapshot_metadata')\n req.method = 'POST'\n req.content_type = \"application/json\"\n body = {\"metadata\": {\"key1\": \"value1\",\n \"key2\": \"value2\",\n \"key3\": \"value3\"}}\n req.body = jsonutils.dump_as_bytes(body)\n res_dict = self.controller.create(req, self.req_id, body)\n self.assertEqual(body, res_dict)\n\n @mock.patch('cinder.db.snapshot_update')\n @mock.patch('cinder.objects.Snapshot.get_by_id')\n def test_create_with_keys_in_uppercase_and_lowercase(\n self, snapshot_get_by_id, snapshot_update):\n snapshot = {\n 'id': self.req_id,\n 'expected_attrs': ['metadata']\n }\n ctx = context.RequestContext(fake.USER_ID, fake.PROJECT_ID, True)\n snapshot_obj = fake_snapshot.fake_snapshot_obj(ctx, **snapshot)\n snapshot_get_by_id.return_value = snapshot_obj\n\n # if the keys in uppercase_and_lowercase, should return the one\n # which server added\n self.mock_object(cinder.db, 'snapshot_metadata_update',\n return_create_snapshot_metadata_insensitive)\n", "answers": [" req = fakes.HTTPRequest.blank('/v2/snapshot_metadata')"], "length": 802, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "77450ba4-96a8-446c-99a7-f61ce5b17051", "reasoning": "The test method is setting up a scenario for creating snapshot metadata with mixed‑case keys. After the comment, the next logical step is to construct the HTTP request object, just as in the previous test_create method. The appropriate line creates a fake request targeting the snapshot metadata endpoint.", "reasoning_model_answer": "req = fakes.HTTPRequest.blank('/v2/snapshot_metadata')", "assistant_with_reasoning": "\nThe test method is setting up a scenario for creating snapshot metadata with mixed‑case keys. After the comment, the next logical step is to construct the HTTP request object, just as in the previous test_create method. The appropriate line creates a fake request targeting the snapshot metadata endpoint.\n\nreq = fakes.HTTPRequest.blank('/v2/snapshot_metadata')", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.212, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 11785, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "req = fakes.HTTPRequest.blank('/v2/snapshot_metadata')", "score": 0.93, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "package edu.uga.cs.pcf.base;\n\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.InputStreamReader;\nimport java.util.List;\n\nimport models.pcf.pcl.BinaryExpression;\nimport models.pcf.pcl.Func;\nimport models.pcf.pcl.PCLCondition;\nimport models.pcf.pcl.PCLConstraint;\nimport models.pcf.pcl.PCLConstraintConstantAttribute;\nimport models.pcf.pcl.PCLConstraintOperation;\nimport models.pcf.pcl.PCLContext;\nimport models.pcf.pcl.PCLExceptionHandler;\nimport models.pcf.pcl.PCLExpression;\nimport models.pcf.pcl.PCLPreCondition;\nimport models.pcf.pcl.PCLProcessElement;\nimport models.pcf.pcl.UnaryExpression;\n\nimport org.apache.log4j.Logger;\nimport org.switchyard.component.camel.model.v1.V1CamelImplementationModel;\nimport org.switchyard.config.model.composite.ComponentImplementationModel;\nimport org.switchyard.config.model.composite.ComponentModel;\nimport org.switchyard.config.model.composite.ComponentServiceModel;\nimport org.switchyard.config.model.composite.CompositeReferenceModel;\nimport org.switchyard.config.model.composite.CompositeServiceModel;\nimport org.switchyard.config.model.composite.InterfaceModel;\nimport org.switchyard.config.model.composite.v1.V1ComponentModel;\nimport org.switchyard.config.model.composite.v1.V1ComponentReferenceModel;\nimport org.switchyard.config.model.composite.v1.V1InterfaceModel;\n\nimport pcf.pcl.PCLParseResult;\nimport pcf.pcl.PCLParser;\nimport scala.Option;\nimport scala.collection.Iterator;\n\nimport com.google.common.base.Charsets;\nimport com.google.common.base.Joiner;\nimport com.google.common.base.Preconditions;\nimport com.google.common.collect.Lists;\nimport com.google.common.io.CharStreams;\nimport com.google.common.io.Closeables;\n\nimport edu.uga.cs.pcf.base.ServiceRegistry.ServiceRegistryInformation;\n\n/**\n * Takes pcl and switchyard.xml as input, generates the backbone of constraint\n * operations and service integration template that are compatible with SCA\n * specifications.\n */\npublic class PcfLinker {\n\n private static final String SWITCHYARD_XML = \"switchyard.xml\";\n private static final String NEPOTISM_PCL = \"nepotism.pcl\";\n private static final Logger logger = Logger.getLogger(PcfLinker.class);\n private InputStream pcl;\n private InputStream switchyard;\n private PCLParseResult pclResult;\n private SwitchyardConfigParser switchyardParser;\n\n /**\n * Parses pcl file and switchyard configuration\n */\n public void initialize() {\n // Parses pcl\n PCLParser parser = new PCLParser();\n String content = null;\n try {\n content = CharStreams.toString(new InputStreamReader(pcl, Charsets.UTF_8));\n this.pclResult = parser.pclParse(content);\n logger.info(\"------------------ parsed pcl --------------------\");\n logger.info(this.pclResult);\n } catch (IOException e) {\n e.printStackTrace();\n } finally {\n Closeables.closeQuietly(pcl);\n }\n\n // Parses switchyard configuration\n this.switchyard = getDefaultSwitchyard();\n try {\n this.switchyardParser = new SwitchyardConfigParser(this.switchyard);\n logger.info(\"------------------ parsed switchyard configuration --------------------\");\n logger.info(this.switchyardParser);\n } catch (Exception ex) {\n logger.error(\"failed to parse switchard configuration xml.\", ex);\n } finally {\n Closeables.closeQuietly(this.switchyard);\n }\n }\n\n /**\n * Connects pcl and switchyard and links the two by generating the service\n * integration template\n */\n public void link() {\n logger.info(\"--------------begin linking pcl and switchyard----------------\");\n // Gets all the constraints\n Option constraint = this.pclResult.constraint();\n PCLConstraint pclConstraint = null;\n if (!constraint.isEmpty()) {\n pclConstraint = constraint.get();\n }\n PCLContext context = pclConstraint.context();\n scala.collection.immutable.List processElements = context.elements();\n Iterator iter = processElements.toIterator();\n logger.info(\"--------------process elements----------------\");\n List activities = Lists.newArrayList();\n while (iter.hasNext()) {\n PCLProcessElement processElement = iter.next();\n logger.info(processElement);\n activities.add(processElement);\n }\n\n // constraint operations\n logger.info(\"--------------constraint operations----------------\");\n scala.collection.immutable.List conditions = pclConstraint.conditions();\n Iterator condIter = conditions.toIterator();\n List pclConditions = Lists.newArrayList();\n while (condIter.hasNext()) {\n PCLCondition cond = condIter.next();\n logger.info(cond);\n pclConditions.add(cond);\n }\n\n // pcl exceptions\n logger.info(\"--------------pcl exceptions----------------\");\n Option exceptionHandlerOption = pclConstraint.exceptionHandler();\n PCLExceptionHandler exceptionHandler = null;\n if (exceptionHandlerOption.isDefined()) {\n exceptionHandler = exceptionHandlerOption.get();\n }\n logger.info(exceptionHandler);\n\n // Gets all the switchyard configuration\n java.util.List services = this.switchyardParser.getServices();\n java.util.List references = this.switchyardParser.getReferences();\n java.util.List components = this.switchyardParser.getComponents();\n for (CompositeServiceModel service : services) {\n logger.info(\"-----------------------------------------------------------------------\");\n logger.info(String.format(\"service name %s\", service.getName()));\n }\n for (ComponentModel component : components) {\n logger.info(\"-----------------------------------------------------------------------\");\n logger.info(String.format(\"component name %s\\tservice name %s\", component.getName(), getServiceName(component)));\n }\n for (CompositeReferenceModel reference : references) {\n logger.info(\"-----------------------------------------------------------------------\");\n logger.info(String.format(\"reference name %s\", reference.getName()));\n }\n\n /*\n * Links pcl and switchyard configuration and follows service integration\n * template\n * Step 1: match the services with an sca component associated to an sca service\n */\n List matches = findMatched(activities, pclConditions, exceptionHandler, services, components);\n logger.info(\"-----------------------------------------------------------------------\");\n logger.info(\"found matched activity and sca component\");\n logger.info(Joiner.on(\"\\n\").join(matches));\n\n /*\n * Step 2: for these matched services, creates a new camel route following\n * service integration template.\n * The new component should have the exact implementation with the old one.\n */\n for (PclSwitchyardMatcher match : matches) {\n ComponentModel newComponent = buildCamelRouteComponent(match);\n match.setNewComponent(newComponent);\n }\n }\n\n /**\n * Creates a camel route component and creates the skeleton camel route in Java.\n * @param match\n * @return\n */\n private ComponentModel buildCamelRouteComponent(PclSwitchyardMatcher match) {\n Preconditions.checkArgument(match != null);\n\n // sca component\n ComponentModel old = match.getOldComponent();\n logger.info(\"------------old component--------------\");\n logger.info(old);\n\n // sca service\n CompositeServiceModel service = match.getService();\n logger.info(\"------------sca service--------------\");\n logger.info(service);\n\n // Constraint pcl\n\n // This target name space is kept the same\n String namespace = old.getTargetNamespace();\n\n ComponentModel result = new V1ComponentModel();\n\n // Set up service name\n result.setName(old.getName());\n\n // Sets up the service and uses the same old ones\n List services = old.getServices();\n for (ComponentServiceModel s : services) {\n result.addService(s);\n }\n\n /*\n * sample sca references and services:\n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n */\n\n // Adds a references to the existing service, because the original service\n // is now integrated within and referenced by the new camel route.\n // Sets up name and interface properly.\n logger.info(\"-------------------add original service reference-------------------\");\n V1ComponentReferenceModel serviceRef = new V1ComponentReferenceModel(namespace);\n serviceRef.setName(service.getName());\n serviceRef.setInterface(service.getInterface());", "answers": [" result.addReference(serviceRef);"], "length": 694, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "baa2ca2c-f29d-4eb0-ad80-b2766ed0cc5c", "reasoning": "The method is building a new component model for a Camel route. After creating a V1ComponentReferenceModel for the original service and setting its name and interface, the next logical step is to attach this reference to the component being built. The ComponentModel API provides an addReference method, so the next line should add the serviceRef to the result component.", "reasoning_model_answer": "result.addReference(serviceRef);", "assistant_with_reasoning": "\nThe method is building a new component model for a Camel route. After creating a V1ComponentReferenceModel for the original service and setting its name and interface, the next logical step is to attach this reference to the component being built. The ComponentModel API provides an addReference method, so the next line should add the serviceRef to the result component.\n\nresult.addReference(serviceRef);", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 2.913, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 10241, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "result.addReference(serviceRef);", "score": 0.89, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "using UnityEngine;\nusing System.Collections;\n\n\n[ExecuteInEditMode] // Make water live-update even when not in play mode\npublic class SeaShader : MonoBehaviour\n{\n\t\n\t//private WhirldObject whirldObject;\n\t\n\tpublic enum WaterMode {\n\t\tSimple = 0,\n\t\tReflective = 1,\n\t\tRefractive = 2,\n\t};\n\tpublic WaterMode m_WaterMode = WaterMode.Reflective;\n\tpublic bool m_DisablePixelLights = true;\n\tpublic int m_TextureSize = 256;\n\tpublic float m_ClipPlaneOffset = 0.07f;\n\tpublic LayerMask cullingMask;\n\t\n\tpublic Transform WaterTransform;\n\t\n\tpublic LayerMask m_ReflectLayers = -1;\n\tpublic LayerMask m_RefractLayers = -1;\n\t\n\tpublic Shader m_ShaderFull;\n\tpublic Shader m_ShaderSimple;\n\t\n\tpublic bool isSurface = true;\n\t\n\tprivate Hashtable m_ReflectionCameras = new Hashtable(); // Camera -> Camera table\n\tprivate Hashtable m_RefractionCameras = new Hashtable(); // Camera -> Camera table\n\t\n\tprivate RenderTexture m_ReflectionTexture = null;\n\tprivate RenderTexture m_RefractionTexture = null;\n\tprivate WaterMode m_HardwareWaterSupport = WaterMode.Reflective;\n\tprivate int m_OldReflectionTextureSize = 0;\n\tprivate int m_OldRefractionTextureSize = 0;\n\t\n\t//private double tickTime = 0.0f;\n\t\n\tprivate Terrain m_Terrain;\n\t\n\tprivate static bool s_InsideWater = false;\n\t\n\t// This is called when it's known that the object will be rendered by some\n\t// camera. We render reflections / refractions and do other updates here.\n\t// Because the script executes in edit mode, reflections for the scene view\n\t// camera will just work!\n\t\n\t/*void Start() {\n\t\twhirldObject = transform.parent.gameObject.GetComponent(WhirldObject);\n\t\tif(whirldObject == null || whirldObject.params == null) {\n\t\t\treturn;\n\t\t}\n\t\tif(whirldObject.params[\"Mode\"]) {\n\t\t\tm_SeaMode = Enum.Parse(typeof(SeaMode), whirldObject.params[\"Mode\"], true);\n\t\t}\n\t}*/\n\t\n\t/*public void SetSeaMode(string mode)\n\t{\n\t\tm_SeaMode = (SeaMode) System.Enum.Parse(typeof(SeaMode), mode, true);\n\t}*/\n\t\n\tpublic void OnWillRenderObject()\n\t{\n\t\t\n\t\tif( !enabled || !renderer || !renderer.sharedMaterial || !renderer.enabled )\t// || Time.time < tickTime)\n\t\t\treturn;\n\t\t\t\n\t\t//tickTime = Time.time + .05;\n\t\t\t\n\t\tif( !m_Terrain ) {\n\t\t\tm_Terrain = Terrain.activeTerrain;\n\t\t\t/*GameObject go = GameObject.Find(\"Terrain\");\n\t\t\tif( !go )\n\t\t\t\treturn;\n\t\t\tm_Terrain = go.GetComponent(typeof(Terrain)) as Terrain;\n\t\t\tif( !m_Terrain )\n\t\t\t\treturn;*/\n\t\t}\n\t\t\t\n\t\tCamera cam = Camera.current;\n\t\tif( !cam )\n\t\t\treturn;\n\t\t\t\n\t\t// Safeguard from recursive water reflections.\t\t\n\t\tif( s_InsideWater )\n\t\t\treturn;\n\t\ts_InsideWater = true;\n\t\t\n\t\t// Actual water rendering mode depends on both the current setting AND\n\t\t// the hardware support. There's no point in rendering refraction textures\n\t\t// if they won't be visible in the end.\n\t\tm_HardwareWaterSupport = FindHardwareWaterSupport();\n\t\tWaterMode mode = GetWaterMode();\n\t\tShader newShader = ( mode == WaterMode.Refractive ) ? m_ShaderFull : m_ShaderSimple;\n\t\tif( renderer.sharedMaterial.shader != newShader )\n\t\t\trenderer.sharedMaterial.shader = newShader;\n\t\t\n\t\tCamera reflectionCamera, refractionCamera;\n\t\tCreateWaterObjects( cam, out reflectionCamera, out refractionCamera );\n\t\t\n\t\t//Apply SeaMode\n\t\t//renderer.sharedMaterial.SetColor( \"_RefrColor\", SeaModeColors[ (int)m_SeaMode ] );\n\t\t\n\t\t// find out the reflection plane: position and normal in world space\n\t\tVector3 pos = transform.position;\n\t\tVector3 normal = transform.up;\n\t\t\n\t\t// Optionally disable pixel lights for reflection/refraction\n\t\tint oldPixelLightCount = QualitySettings.pixelLightCount;\n\t\tif( m_DisablePixelLights )\n\t\t\tQualitySettings.pixelLightCount = 0;\n\t\t\n\t\tUpdateCameraModes( cam, reflectionCamera );\n\t\tUpdateCameraModes( cam, refractionCamera );\n\t\t\n\t\tbool oldSoftVegetation = QualitySettings.softVegetation;\n\t\tQualitySettings.softVegetation = false;\n\t\t\n\t\t// Render reflection if needed\n\t\tif( mode >= WaterMode.Reflective/* && isSurface*/)\n\t\t{\n\t\t\t// Reflect camera around reflection plane\n\t\t\tfloat d = -Vector3.Dot (normal, pos) - m_ClipPlaneOffset;\n\t\t\tVector4 reflectionPlane = new Vector4 (normal.x, normal.y, normal.z, d);\n\t\t\n\t\t\tMatrix4x4 reflection = Matrix4x4.zero;\n\t\t\tCalculateReflectionMatrix (ref reflection, reflectionPlane);\n\t\t\tVector3 oldpos = cam.transform.position;\n\t\t\tVector3 newpos = reflection.MultiplyPoint( oldpos );\n\t\t\treflectionCamera.worldToCameraMatrix = cam.worldToCameraMatrix * reflection;\n\t\t\n\t\t\t// Setup oblique projection matrix so that near plane is our reflection\n\t\t\t// plane. This way we clip everything below/above it for free.\n\t\t\tVector4 clipPlane = CameraSpacePlane( reflectionCamera, pos, normal, 1.0f );\n\t\t\tMatrix4x4 projection = cam.projectionMatrix;\n\t\t\tCalculateObliqueMatrix (ref projection, clipPlane);\n\t\t\treflectionCamera.projectionMatrix = projection;\n\t\t\t\n\t\t\treflectionCamera.cullingMask = cullingMask & m_ReflectLayers.value; // never render water layer\n\t\t\treflectionCamera.targetTexture = m_ReflectionTexture;\n\t\t\tGL.SetRevertBackfacing (true);\n\t\t\treflectionCamera.transform.position = newpos;\n\t\t\tVector3 euler = cam.transform.eulerAngles;\n\t\t\treflectionCamera.transform.eulerAngles = new Vector3(0, euler.y, euler.z);\n\t\t\t\n\t\t\t// don't render tree meshes or grass in reflection :)\n\t\t\tfloat oldDetailDist = m_Terrain.detailObjectDistance;\n\t\t\tfloat oldTreeDist = m_Terrain.treeDistance;\n\t\t\tfloat oldTreeBillDist = m_Terrain.treeBillboardDistance;\n\t\t\tfloat oldSplatDist = m_Terrain.basemapDistance;\n\t\t\tm_Terrain.detailObjectDistance = 0.0f;\n\t\t\tm_Terrain.treeBillboardDistance = 0.0f;\n\t\t\tm_Terrain.basemapDistance = 0.0f;\n\t\t\t\n\t\t\treflectionCamera.Render();\n\t\t\t\n\t\t\tm_Terrain.detailObjectDistance = oldDetailDist;\n\t\t\tm_Terrain.treeDistance = oldTreeDist;\n\t\t\tm_Terrain.treeBillboardDistance = oldTreeBillDist;\n\t\t\tm_Terrain.basemapDistance = oldSplatDist;\n\t\t\t\n\t\t\treflectionCamera.transform.position = oldpos;\n\t\t\tGL.SetRevertBackfacing (false);\n\t\t\trenderer.sharedMaterial.SetTexture( \"_ReflectionTex\", m_ReflectionTexture );\n\t\t}\n\t\telse renderer.sharedMaterial.SetTexture( \"_ReflectionTex\", null );\n\t\t\n\t\t// Render refraction\n\t\tif( mode >= WaterMode.Refractive )\n\t\t{\n\t\t\trefractionCamera.worldToCameraMatrix = cam.worldToCameraMatrix;\n\t\t\n\t\t\t// Setup oblique projection matrix so that near plane is our reflection\n\t\t\t// plane. This way we clip everything below/above it for free.\n\t\t\tVector4 clipPlane = CameraSpacePlane( refractionCamera, pos, normal, -1.0f );\n\t\t\tMatrix4x4 projection = cam.projectionMatrix;\n\t\t\tCalculateObliqueMatrix (ref projection, clipPlane);\n\t\t\trefractionCamera.projectionMatrix = projection;\n\t\t\t\n\t\t\trefractionCamera.cullingMask = cullingMask & m_RefractLayers.value; // never render water layer\n\t\t\trefractionCamera.targetTexture = m_RefractionTexture;\n\t\t\trefractionCamera.transform.position = cam.transform.position;\n\t\t\trefractionCamera.transform.rotation = cam.transform.rotation;\n\t\t\t\n\t\t\t// don't render trees or grass in refraction :)\n\t\t\tfloat oldDetailDist = m_Terrain.detailObjectDistance;\n\t\t\tfloat oldTreeDist = m_Terrain.treeDistance;\n\t\t\tfloat oldTreeBillDist = m_Terrain.treeBillboardDistance;\n\t\t\tm_Terrain.detailObjectDistance = 0.0f;\n\t\t\tm_Terrain.treeDistance = 0.0f;\n\t\t\tm_Terrain.treeBillboardDistance = 0.0f;\n\t\t\t\n\t\t\trefractionCamera.Render();\n\t\t\t\n\t\t\tm_Terrain.detailObjectDistance = oldDetailDist;", "answers": ["\t\t\tm_Terrain.treeDistance = oldTreeDist;"], "length": 732, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "8eaa7f76-1c8c-407e-9477-6cc2774e9265", "reasoning": "The code is inside the refraction rendering block. After rendering, it restores terrain detail settings. It already restored m_Terrain.detailObjectDistance = oldDetailDist; The next logical restoration is the tree distance that was saved in oldTreeDist. Therefore the next line should set m_Terrain.treeDistance to oldTreeDist.", "reasoning_model_answer": "m_Terrain.treeDistance = oldTreeDist;", "assistant_with_reasoning": "\nThe code is inside the refraction rendering block. After rendering, it restores terrain detail settings. It already restored m_Terrain.detailObjectDistance = oldDetailDist; The next logical restoration is the tree distance that was saved in oldTreeDist. Therefore the next line should set m_Terrain.treeDistance to oldTreeDist.\n\nm_Terrain.treeDistance = oldTreeDist;", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.849, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 7247, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "m_Terrain.treeDistance = oldTreeDist;", "score": 0.96, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "// Copyright (c) Microsoft. All rights reserved. \n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nusing FluentAssertions;\nusing Its.Log.Instrumentation;\nusing Microsoft.Its.Domain.Sql.CommandScheduler;\nusing Microsoft.Its.Recipes;\nusing NUnit.Framework;\nusing Sample.Domain;\nusing Sample.Domain.Ordering;\nusing Sample.Domain.Ordering.Commands;\nusing System;\nusing System.Linq;\nusing System.Reactive.Disposables;\nusing System.Threading.Tasks;\n\nnamespace Microsoft.Its.Domain.Testing.Tests\n{\n [TestFixture]\n public abstract class ScenarioBuilderTests\n {\n private CompositeDisposable disposables;\n\n protected ScenarioBuilderTests()\n {\n Command.AuthorizeDefault = (customer, command) => true;\n Command.AuthorizeDefault = (order, command) => true;\n }\n\n [SetUp]\n public virtual void SetUp()\n {\n disposables = new CompositeDisposable(\n Disposable.Create(() => ConfigurationContext.Current\n .IfNotNull()\n .ThenDo(c => c.Dispose())));\n }\n\n [TearDown]\n public virtual void TearDown()\n {\n disposables.Dispose();\n }\n\n protected void RegisterForDisposal(IDisposable disposable)\n {\n disposables.Add(disposable);\n }\n\n [Test]\n public void Events_added_to_the_scenario_are_used_to_source_aggregates()\n {\n var name = Any.FullName();\n var aggregateId = Any.Guid();\n var orderNumber = Any.Int(2000, 5000).ToString();\n\n var scenario = CreateScenarioBuilder()\n .AddEvents(new Order.Created\n {\n AggregateId = aggregateId,\n OrderNumber = orderNumber\n }, new Order.CustomerInfoChanged\n {\n AggregateId = aggregateId,\n CustomerName = name\n }).Prepare();\n\n var order = scenario.Aggregates.Single() as Order;\n\n order.Should().NotBeNull();\n order.OrderNumber.Should().Be(orderNumber);\n order.CustomerName.Should().Be(name);\n order.Id.Should().Be(aggregateId);\n }\n\n [Test]\n public void If_no_aggregate_id_is_specified_when_adding_events_then_a_default_is_chosen_and_reused()\n {\n var created = new Order.Created();\n var customerInfoChanged = new Order.CustomerInfoChanged();\n\n CreateScenarioBuilder()\n .AddEvents(created, customerInfoChanged);\n\n created.AggregateId.Should().NotBeEmpty();\n customerInfoChanged.AggregateId.Should().Be(created.AggregateId);\n }\n\n [Test]\n public async Task If_no_aggregate_id_is_specified_when_calling_GetLatest_and_a_single_instance_is_in_the_scenario_then_it_is_returned()\n {\n var aggregateId = Any.Guid();\n var created = new Order.Created\n {\n AggregateId = aggregateId\n };\n\n var scenario = CreateScenarioBuilder().AddEvents(created).Prepare();\n\n var aggregate = await scenario.GetLatestAsync();\n\n aggregate.Should().NotBeNull();\n aggregate.Id.Should().Be(aggregateId);\n }\n\n [Test]\n public void If_no_aggregate_id_is_specified_when_calling_GetLatest_and_no_instance_is_in_the_scenario_then_it_throws()\n {\n var scenario = CreateScenarioBuilder()\n .AddEvents(new Order.Created\n {\n AggregateId = Any.Guid()\n }, new Order.Created\n {\n AggregateId = Any.Guid()\n }).Prepare();\n\n Action getLatest = () => scenario.GetLatestAsync().Wait();\n\n getLatest.ShouldThrow();\n }\n\n [Test]\n public void If_no_aggregate_id_is_specified_when_calling_GetLatest_and_multiple_instances_are_in_the_scenario_then_it_throws()\n {\n var scenario = CreateScenarioBuilder().Prepare();\n\n Action getLatest = () => scenario.GetLatestAsync().Wait();\n\n getLatest.ShouldThrow();\n }\n\n [Test]\n public void When_no_sequence_numbers_are_specified_then_events_are_applied_in_order()\n {\n var aggregateId = Any.Guid();\n var firstCustomerName = Any.FullName();\n var scenario = CreateScenarioBuilder()\n .AddEvents(new Order.CustomerInfoChanged\n {\n AggregateId = aggregateId,\n CustomerName = Any.FullName()\n }, new Order.CustomerInfoChanged\n {\n AggregateId = aggregateId,\n CustomerName = firstCustomerName\n }).Prepare();\n\n var order = scenario.Aggregates.OfType().Single();\n\n order.CustomerName.Should().Be(firstCustomerName);\n }\n\n [Test]\n public void DynamicProjectors_registered_as_event_handlers_in_ScenarioBuilder_run_catchups_when_prepare_is_called()\n {\n var firstShipHandled = false;\n var secondShipHandled = false;\n var handler = Domain.Projector.CreateDynamic(dynamicEvent =>\n {\n var @event = dynamicEvent as IEvent;\n @event.IfTypeIs>()\n .ThenDo(c =>\n {\n var shipmentId = (c.Command as Ship).ShipmentId;\n Console.WriteLine(\"Handling [{0}] Shipment\", shipmentId);\n if (shipmentId == \"first\")\n {\n firstShipHandled = true;\n }\n else if (shipmentId == \"second\")\n {\n secondShipHandled = true;\n }\n });\n },\n \"Order.Scheduled:Ship\");\n CreateScenarioBuilder()\n .AddHandler(handler)\n .AddEvents(\n new CommandScheduled\n {\n Command = new Ship { ShipmentId = \"first\" },\n DueTime = DateTime.Now\n },\n new CommandScheduled\n {\n Command = new Ship { ShipmentId = \"second\" },\n DueTime = DateTime.Now\n })\n .Prepare();\n\n firstShipHandled.Should().BeTrue();\n secondShipHandled.Should().BeTrue();\n }\n\n [Test]\n public void When_sequence_numbers_are_specified_it_overrides_the_order_in_which_the_events_were_added()\n {\n var aggregateId = Any.Guid();\n var firstCustomerName = Any.FullName();\n var scenario = CreateScenarioBuilder()\n .AddEvents(new Order.CustomerInfoChanged\n {\n AggregateId = aggregateId,\n CustomerName = firstCustomerName,\n SequenceNumber = 2\n }, new Order.CustomerInfoChanged\n {\n AggregateId = aggregateId,\n CustomerName = Any.FullName(),\n SequenceNumber = 1\n }).Prepare();\n\n var order = scenario.Aggregates.OfType().Single();\n\n order.CustomerName.Should().Be(firstCustomerName);\n }\n\n [Test]\n public void Multiple_aggregates_of_the_same_type_can_be_sourced_in_one_scenario()\n {\n var builder = CreateScenarioBuilder()\n .AddEvents(new Order.Created\n {\n AggregateId = Any.Guid()\n }, new Order.Created\n {\n AggregateId = Any.Guid()\n });\n\n builder.Prepare().Aggregates\n .OfType()\n .Count()\n .Should().Be(2);\n }\n\n [Test]\n public void Multiple_aggregates_of_different_types_can_be_sourced_in_one_scenario()\n {\n // arrange\n var builder = CreateScenarioBuilder()\n .AddEvents(new Order.Created\n {\n AggregateId = Any.Guid()\n }, new CustomerAccount.EmailAddressChanged\n {\n AggregateId = Any.Guid()\n });\n\n // act\n var scenario = builder.Prepare();\n\n // assert\n scenario.Aggregates\n .Should()\n .ContainSingle(a => a is CustomerAccount)\n .And\n .ContainSingle(a => a is Order);\n }\n\n [Test]\n public void Multiple_aggregates_of_the_same_type_can_be_organized_using_For()\n {\n var aggregateId1 = Any.Guid();\n var aggregateId2 = Any.Guid();\n\n var builder = CreateScenarioBuilder();\n builder.For(aggregateId1)\n .AddEvents(new Order.ItemAdded { ProductName = \"one\" });\n builder.For(aggregateId2)\n .AddEvents(new Order.ItemAdded { ProductName = \"two\" });\n\n var aggregates = builder.Prepare().Aggregates.OfType().ToArray();\n\n aggregates.Count().Should().Be(2);\n aggregates.Should().Contain(a => a.Id == aggregateId1 && a.Items.Single().ProductName == \"one\");\n aggregates.Should().Contain(a => a.Id == aggregateId2 && a.Items.Single().ProductName == \"two\");\n }\n\n [Test]\n public void Projectors_added_before_Prepare_is_called_are_subscribed_to_all_events()\n {\n var onDeliveredCalls = 0;\n var onEmailAddedCalls = 0;\n var delivered = new Order.Delivered();\n var addressChanged = new CustomerAccount.EmailAddressChanged();\n CreateScenarioBuilder()\n .AddEvents(delivered, addressChanged)\n .AddHandler(new Projector\n {\n OnDelivered = e =>\n {\n Console.WriteLine(e.ToLogString());\n onDeliveredCalls++;\n },\n OnEmailAdded = e =>\n {\n Console.WriteLine(e.ToLogString());\n onEmailAddedCalls++;\n }\n })\n .Prepare();\n\n onDeliveredCalls.Should().Be(1);\n onEmailAddedCalls.Should().Be(1);\n }\n\n [Test]\n public async Task Projectors_added_after_Prepare_is_called_are_subscribed_to_future_events()\n {\n // arrange\n var onDeliveredCalls = 0;\n var onEmailAddedCalls = 0;\n var scenarioBuilder = CreateScenarioBuilder();\n var aggregateId = Any.Guid();\n var scenario = scenarioBuilder\n .AddEvents(new Order.Created\n {\n AggregateId = aggregateId\n })\n .Prepare();\n\n scenarioBuilder.AddHandler(new Projector\n {\n OnDelivered = e => onDeliveredCalls++,\n OnEmailAdded = e => onEmailAddedCalls++\n });\n\n var order = new Order();\n order.Apply(new Deliver());\n var customer = new CustomerAccount();\n customer.Apply(new ChangeEmailAddress(Any.Email()));\n\n // act\n await scenario.SaveAsync(order);\n await scenario.SaveAsync(customer);\n\n // assert", "answers": [" onDeliveredCalls.Should().Be(1);"], "length": 714, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "4ff22489-0b54-4172-9406-db734102779b", "reasoning": "The test sets up counters onDeliveredCalls and onEmailAddedCalls, adds events after Prepare, then saves new events. The // assert comment indicates we now need to verify that the projectors received the events. The first expected assertion is that onDeliveredCalls equals 1. So the next line should be the FluentAssertions check for onDeliveredCalls.", "reasoning_model_answer": "onDeliveredCalls.Should().Be(1);", "assistant_with_reasoning": "\nThe test sets up counters onDeliveredCalls and onEmailAddedCalls, adds events after Prepare, then saves new events. The // assert comment indicates we now need to verify that the projectors received the events. The first expected assertion is that onDeliveredCalls equals 1. So the next line should be the FluentAssertions check for onDeliveredCalls.\n\nonDeliveredCalls.Should().Be(1);", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 2.404, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 12111, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "onDeliveredCalls.Should().Be(1);", "score": 0.84, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/*! ******************************************************************************\n *\n * Pentaho Data Integration\n *\n * Copyright (C) 2002-2016 by Pentaho : http://www.pentaho.com\n *\n *******************************************************************************\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n ******************************************************************************/\n\npackage org.pentaho.di.trans.steps.regexeval;\n\nimport java.util.List;\n\nimport org.pentaho.di.core.CheckResult;\nimport org.pentaho.di.core.CheckResultInterface;\nimport org.pentaho.di.core.Const;\nimport org.pentaho.di.core.util.Utils;\nimport org.pentaho.di.core.database.DatabaseMeta;\nimport org.pentaho.di.core.exception.KettleException;\nimport org.pentaho.di.core.exception.KettlePluginException;\nimport org.pentaho.di.core.exception.KettleStepException;\nimport org.pentaho.di.core.exception.KettleXMLException;\nimport org.pentaho.di.core.row.RowMetaInterface;\nimport org.pentaho.di.core.row.ValueMetaInterface;\nimport org.pentaho.di.core.row.value.ValueMetaBoolean;\nimport org.pentaho.di.core.row.value.ValueMetaFactory;\nimport org.pentaho.di.core.row.value.ValueMetaString;\nimport org.pentaho.di.core.variables.VariableSpace;\nimport org.pentaho.di.core.xml.XMLHandler;\nimport org.pentaho.di.i18n.BaseMessages;\nimport org.pentaho.di.repository.ObjectId;\nimport org.pentaho.di.repository.Repository;\nimport org.pentaho.di.shared.SharedObjectInterface;\nimport org.pentaho.di.trans.Trans;\nimport org.pentaho.di.trans.TransMeta;\nimport org.pentaho.di.trans.step.BaseStepMeta;\nimport org.pentaho.di.trans.step.StepDataInterface;\nimport org.pentaho.di.trans.step.StepInterface;\nimport org.pentaho.di.trans.step.StepMeta;\nimport org.pentaho.di.trans.step.StepMetaInterface;\nimport org.pentaho.metastore.api.IMetaStore;\nimport org.w3c.dom.Node;\n\npublic class RegexEvalMeta extends BaseStepMeta implements StepMetaInterface {\n private static Class PKG = RegexEvalMeta.class; // for i18n purposes, needed by Translator2!!\n\n private String script;\n private String matcher;\n private String resultfieldname;\n private boolean usevar;\n\n private boolean allowcapturegroups;\n private boolean replacefields;\n\n private boolean canoneq;\n private boolean caseinsensitive;\n private boolean comment;\n private boolean dotall;\n private boolean multiline;\n private boolean unicode;\n private boolean unix;\n\n private String[] fieldName;\n private int[] fieldType;\n private String[] fieldFormat;\n private String[] fieldGroup;\n private String[] fieldDecimal;\n private String[] fieldCurrency;\n private int[] fieldLength;\n private int[] fieldPrecision;\n private String[] fieldNullIf;\n private String[] fieldIfNull;\n private int[] fieldTrimType;\n\n public RegexEvalMeta() {\n super();\n }\n\n public Object clone() {\n RegexEvalMeta retval = (RegexEvalMeta) super.clone();\n\n int nrfields = fieldName.length;\n\n retval.allocate( nrfields );\n System.arraycopy( fieldName, 0, retval.fieldName, 0, nrfields );\n System.arraycopy( fieldType, 0, retval.fieldType, 0, nrfields );\n System.arraycopy( fieldLength, 0, retval.fieldLength, 0, nrfields );\n System.arraycopy( fieldPrecision, 0, retval.fieldPrecision, 0, nrfields );\n System.arraycopy( fieldFormat, 0, retval.fieldFormat, 0, nrfields );\n System.arraycopy( fieldGroup, 0, retval.fieldGroup, 0, nrfields );\n System.arraycopy( fieldDecimal, 0, retval.fieldDecimal, 0, nrfields );\n System.arraycopy( fieldCurrency, 0, retval.fieldCurrency, 0, nrfields );\n System.arraycopy( fieldNullIf, 0, retval.fieldNullIf, 0, nrfields );\n System.arraycopy( fieldIfNull, 0, retval.fieldIfNull, 0, nrfields );\n System.arraycopy( fieldTrimType, 0, retval.fieldTrimType, 0, nrfields );\n\n return retval;\n }\n\n public void allocate( int nrfields ) {\n fieldName = new String[nrfields];\n fieldType = new int[nrfields];\n fieldFormat = new String[nrfields];\n fieldGroup = new String[nrfields];\n fieldDecimal = new String[nrfields];\n fieldCurrency = new String[nrfields];\n fieldLength = new int[nrfields];\n fieldPrecision = new int[nrfields];\n fieldNullIf = new String[nrfields];\n fieldIfNull = new String[nrfields];\n fieldTrimType = new int[nrfields];\n }\n\n public String getScript() {\n return script;\n }\n\n public String getRegexOptions() {\n StringBuilder options = new StringBuilder();\n\n if ( isCaseInsensitiveFlagSet() ) {\n options.append( \"(?i)\" );\n }\n if ( isCommentFlagSet() ) {\n options.append( \"(?x)\" );\n }\n if ( isDotAllFlagSet() ) {\n options.append( \"(?s)\" );\n }\n if ( isMultilineFlagSet() ) {\n options.append( \"(?m)\" );\n }\n if ( isUnicodeFlagSet() ) {\n options.append( \"(?u)\" );\n }\n if ( isUnixLineEndingsFlagSet() ) {\n options.append( \"(?d)\" );\n }\n return options.toString();\n }\n\n public void setScript( String script ) {\n this.script = script;\n }\n\n public String getMatcher() {\n return matcher;\n }\n\n public void setMatcher( String matcher ) {\n this.matcher = matcher;\n }\n\n public String getResultFieldName() {\n return resultfieldname;\n }\n\n public void setResultFieldName( String resultfieldname ) {\n this.resultfieldname = resultfieldname;\n }\n\n public boolean isUseVariableInterpolationFlagSet() {\n return usevar;\n }\n\n public void setUseVariableInterpolationFlag( boolean usevar ) {\n this.usevar = usevar;\n }\n\n public boolean isAllowCaptureGroupsFlagSet() {\n return allowcapturegroups;\n }\n\n public void setAllowCaptureGroupsFlag( boolean allowcapturegroups ) {\n this.allowcapturegroups = allowcapturegroups;\n }\n\n public boolean isReplacefields() {\n return replacefields;\n }\n\n public void setReplacefields( boolean replacefields ) {\n this.replacefields = replacefields;\n }\n\n public boolean isCanonicalEqualityFlagSet() {\n return canoneq;\n }\n\n public void setCanonicalEqualityFlag( boolean canoneq ) {\n this.canoneq = canoneq;\n }\n\n public boolean isCaseInsensitiveFlagSet() {\n return caseinsensitive;\n }\n\n public void setCaseInsensitiveFlag( boolean caseinsensitive ) {\n this.caseinsensitive = caseinsensitive;\n }\n\n public boolean isCommentFlagSet() {\n return comment;\n }\n\n public void setCommentFlag( boolean comment ) {\n this.comment = comment;\n }\n\n public boolean isDotAllFlagSet() {\n return dotall;\n }\n\n public void setDotAllFlag( boolean dotall ) {\n this.dotall = dotall;\n }\n\n public boolean isMultilineFlagSet() {\n return multiline;\n }\n\n public void setMultilineFlag( boolean multiline ) {\n this.multiline = multiline;\n }\n\n public boolean isUnicodeFlagSet() {\n return unicode;\n }\n\n public void setUnicodeFlag( boolean unicode ) {\n this.unicode = unicode;\n }\n\n public boolean isUnixLineEndingsFlagSet() {\n return unix;\n }\n\n public void setUnixLineEndingsFlag( boolean unix ) {\n this.unix = unix;\n }\n\n public String[] getFieldName() {\n return fieldName;\n }\n\n public void setFieldName( String[] value ) {\n this.fieldName = value;\n }\n\n public int[] getFieldType() {\n return fieldType;\n }\n\n public void setFieldType( int[] fieldType ) {\n this.fieldType = fieldType;\n }", "answers": [" public String[] getFieldFormat() {"], "length": 759, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "25c77e1d-a0bd-4019-a9a3-088e25b87723", "reasoning": "The class defines a series of getter and setter pairs for each field array. We have just seen the getter and setter for fieldType. The next logical method is the getter for the next field, fieldFormat, following the same pattern. Therefore the next line should start the getFieldFormat method signature.", "reasoning_model_answer": "public String[] getFieldFormat() {", "assistant_with_reasoning": "\nThe class defines a series of getter and setter pairs for each field array. We have just seen the getter and setter for fieldType. The next logical method is the getter for the next field, fieldFormat, following the same pattern. Therefore the next line should start the getFieldFormat method signature.\n\npublic String[] getFieldFormat() {", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 2.318, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 7799, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "public String[] getFieldFormat() {", "score": 0.97, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "#\n# Licensed under the GNU General Public License Version 3\n#\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n#\n# Copyright 2013 Aron Parsons \n# Copyright (c) 2011--2017 Red Hat, Inc.\n#\n\n# NOTE: the 'self' variable is an instance of SpacewalkShell\n\n# wildcard import\n# pylint: disable=W0401,W0614\n\n# unused argument\n# pylint: disable=W0613\n\n# invalid function name\n# pylint: disable=C0103\n\nfrom optparse import Option\nimport urllib\nimport xmlrpclib\nfrom spacecmd.utils import *\n\n\nCHECKSUM = ['sha1', 'sha256', 'sha384', 'sha512']\n\ndef help_softwarechannel_list(self):\n print 'softwarechannel_list: List all available software channels'\n print '''usage: softwarechannel_list [options]'\noptions:\n -v verbose (display label and summary)\n -t tree view (pretty-print child-channels)\n'''\n\n\ndef do_softwarechannel_list(self, args, doreturn=False):\n options = [Option('-v', '--verbose', action='store_true'),\n Option('-t', '--tree', action='store_true')]\n (args, options) = parse_arguments(args, options)\n\n if (options.tree):\n labels = self.list_base_channels()\n else:\n channels = self.client.channel.listAllChannels(self.session)\n labels = [c.get('label') for c in channels]\n\n # filter the list if arguments were passed\n if args:\n labels = filter_results(labels, args, True)\n\n if doreturn:\n return labels\n elif labels:\n if (options.verbose):\n for l in sorted(labels):\n details = self.client.channel.software.getDetails(\n self.session, l)\n print \"%s : %s\" % (l, details['summary'])\n if (options.tree):\n for c in self.list_child_channels(parent=l):\n cdetails = self.client.channel.software.getDetails(\n self.session, c)\n print \" |-%s : %s\" % (c, cdetails['summary'])\n else:\n for l in sorted(labels):\n print \"%s\" % l\n if (options.tree):\n for c in self.list_child_channels(parent=l):\n print \" |-%s\" % c\n\n####################\n\n\ndef help_softwarechannel_listmanageablechannels(self):\n print('softwarechannel_listmanageablechannels: List all software channels')\n print(' manageable by current user')\n print('''usage: softwarechannel_listmanageablechannels [options]\noptions:\n -v verbose (display label and summary)''')\n\n\ndef do_softwarechannel_listmanageablechannels(self, args, doreturn=False):\n options = [Option('-v', '--verbose', action='store_true')]\n (args, options) = parse_arguments(args, options)\n\n channels = self.client.channel.listManageableChannels(self.session)\n labels = [c.get('label') for c in channels]\n\n # filter the list if arguments were passed\n if args:\n labels = filter_results(labels, args, True)\n\n if doreturn:\n return labels\n elif labels:\n if options.verbose:\n for l in sorted(labels):\n details = \\\n self.client.channel.software.getDetails(self.session, l)\n\n print(\"%s : %s\" % (l, details['summary']))\n else:\n for l in sorted(labels):\n print(\"%s\" % l)\n\n####################\n\n\ndef help_softwarechannel_listbasechannels(self):\n print 'softwarechannel_listbasechannels: List all base software channels'\n print '''usage: softwarechannel_listbasechannels [options]\noptions:\n -v verbose (display label and summary)'''\n\n\ndef do_softwarechannel_listbasechannels(self, args):\n options = [Option('-v', '--verbose', action='store_true')]\n (args, options) = parse_arguments(args, options)\n\n channels = self.list_base_channels()\n\n if channels:\n if (options.verbose):\n for c in sorted(channels):\n details = \\\n self.client.channel.software.getDetails(self.session, c)\n print \"%s : %s\" % (c, details['summary'])\n else:\n print '\\n'.join(sorted(channels))\n\n####################\n\n\ndef help_softwarechannel_listchildchannels(self):\n print 'softwarechannel_listchildchannels: List child software channels'\n print 'usage:'\n print 'softwarechannel_listchildchannels [options]'\n print 'softwarechannel_listchildchannels : List all child channels'\n print 'softwarechannel_listchildchannels CHANNEL : List children for a \\\nspecific base channel'\n print 'options:\\n -v verbose (display label and summary)'\n\n\ndef do_softwarechannel_listchildchannels(self, args):\n options = [Option('-v', '--verbose', action='store_true')]\n (args, options) = parse_arguments(args, options)\n if not args:\n channels = self.list_child_channels()\n else:\n channels = self.list_child_channels(parent=args[0])\n\n if channels:\n if (options.verbose):\n for c in sorted(channels):\n details = \\\n self.client.channel.software.getDetails(self.session, c)\n print \"%s : %s\" % (c, details['summary'])\n else:\n print '\\n'.join(sorted(channels))\n\n####################\n\n\ndef help_softwarechannel_listsystems(self):\n print 'softwarechannel_listsystems: List all systems subscribed to'\n print ' a software channel'\n print 'usage: softwarechannel_listsystems CHANNEL'\n\n\ndef complete_softwarechannel_listsystems(self, text, line, beg, end):\n return tab_completer(self.do_softwarechannel_list('', True), text)\n\n\ndef do_softwarechannel_listsystems(self, args, doreturn=False):\n (args, _options) = parse_arguments(args)\n\n if not args:\n self.help_softwarechannel_listsystems()\n return\n\n channel = args[0]\n\n systems = \\\n self.client.channel.software.listSubscribedSystems(self.session,\n channel)\n\n systems = [s.get('name') for s in systems]\n\n if doreturn:\n return systems\n else:\n if systems:\n print '\\n'.join(sorted(systems))\n\n####################\n\n\ndef help_softwarechannel_listpackages(self):\n print 'softwarechannel_listpackages: List the most recent packages'\n print ' available from a software channel'\n print 'usage: softwarechannel_listpackages CHANNEL'\n\n\ndef complete_softwarechannel_listpackages(self, text, line, beg, end):\n if len(line.split(' ')) == 2:\n return tab_completer(self.do_softwarechannel_list('', True),\n text)\n\n return []\n\n\ndef do_softwarechannel_listpackages(self, args, doreturn=False):\n (args, _options) = parse_arguments(args)\n\n if not args:\n self.help_softwarechannel_listpackages()\n return\n\n channel = args[0]\n\n packages = self.client.channel.software.listLatestPackages(self.session,\n channel)\n\n packages = build_package_names(packages)\n\n if doreturn:\n return packages\n else:\n if packages:\n print '\\n'.join(sorted(packages))\n\n####################\n\n\ndef help_softwarechannel_listallpackages(self):\n print 'softwarechannel_listallpackages: List all packages in a channel'", "answers": [" print 'usage: softwarechannel_listallpackages CHANNEL'"], "length": 729, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "7037e255-2165-41f9-9c2a-fb17e9282aa1", "reasoning": "The help_softwarechannel_listallpackages function follows the pattern of other help functions: it prints a description line, then a usage line. The code already printed the description, so the next line should be the usage string for this command.", "reasoning_model_answer": "print 'usage: softwarechannel_listallpackages CHANNEL'", "assistant_with_reasoning": "\nThe help_softwarechannel_listallpackages function follows the pattern of other help functions: it prints a description line, then a usage line. The code already printed the description, so the next line should be the usage string for this command.\n\nprint 'usage: softwarechannel_listallpackages CHANNEL'", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 5.019, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 8045, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "print 'usage: softwarechannel_listallpackages CHANNEL'", "score": 0.96, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "#!/usr/bin/env python3\n# -*- encoding: utf-8 -*-\n\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied. See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"Provides functions for reading and writing (writing is WIP currently) Java objects\nserialized or will be deserialized by ObjectOutputStream. This form of object\nrepresentation is a standard data interchange format in Java world.\n\njavaobj module exposes an API familiar to users of the standard\nlibrary marshal, pickle and json modules.\n\nSee: http://download.oracle.com/javase/6/docs/platform/serialization/spec/protocol.html\n\"\"\"\n\nimport io\nimport struct\n\nfrom heron.common.src.python.utils.log import Log\n\ndef log_debug(message, ident=0):\n \"\"\"log debugging info\"\"\"\n Log.debug(\" \" * (ident * 2) + str(message))\n\ndef log_error(message, ident=0):\n \"\"\"log error info\"\"\"\n Log.error(\" \" * (ident * 2) + str(message))\n\n__version__ = \"$Revision: 20 $\"\n\ndef load(file_object):\n \"\"\"\n Deserializes Java primitive data and objects serialized by ObjectOutputStream\n from a file-like object.\n \"\"\"\n marshaller = JavaObjectUnmarshaller(file_object)\n marshaller.add_transformer(DefaultObjectTransformer())\n return marshaller.readObject()\n\n\n# pylint: disable=undefined-variable\ndef loads(value: bytes):\n \"\"\"\n Deserializes Java objects and primitive data serialized by ObjectOutputStream\n from a string.\n \"\"\"\n f = io.BytesIO(value)\n marshaller = JavaObjectUnmarshaller(f)\n marshaller.add_transformer(DefaultObjectTransformer())\n return marshaller.readObject()\n\n\ndef dumps(obj):\n \"\"\"\n Serializes Java primitive data and objects unmarshaled by load(s) before into string.\n \"\"\"\n marshaller = JavaObjectMarshaller()\n return marshaller.dump(obj)\n\n_java_primitives = set([\n \"java.lang.Double\",\n \"java.lang.Float\",\n \"java.lang.Integer\",\n \"java.lang.Long\"])\n\nclass JavaClass:\n \"\"\"Java class representation\"\"\"\n def __init__(self):\n self.name = None\n self.serialVersionUID = None\n self.flags = None\n self.fields_names = []\n self.fields_types = []\n self.superclass = None\n\n def __str__(self):\n return self.__repr__()\n\n def __repr__(self):\n return \"[%s:0x%X]\" % (self.name, self.serialVersionUID)\n\n\nclass JavaObject:\n \"\"\"Java object representation\"\"\"\n def __init__(self):\n self.classdesc = None\n self.annotations = []\n\n def get_class(self):\n \"\"\"get class\"\"\"\n return self.classdesc\n\n def __str__(self):\n \"\"\"get reprensentation in string\"\"\"\n return self.__repr__()\n\n def __repr__(self):\n \"\"\"get reprensentation\"\"\"\n name = \"UNKNOWN\"\n if self.classdesc:\n name = self.classdesc.name\n return \"\" % name\n\n def classname(self):\n name = \"UNKNOWN\"\n if self.classdesc:\n name = self.classdesc.name\n return name\n\n def is_primitive(self):\n return self.classname() in _java_primitives\n\n def copy(self, new_object):\n \"\"\"copy an object\"\"\"\n new_object.classdesc = self.classdesc\n\n for name in self.classdesc.fields_names:\n new_object.__setattr__(name, getattr(self, name))\n\nclass JavaObjectConstants:\n \"\"\"class about Java object constants\"\"\"\n\n STREAM_MAGIC = 0xaced\n STREAM_VERSION = 0x05\n\n TC_NULL = 0x70\n TC_REFERENCE = 0x71\n TC_CLASSDESC = 0x72\n TC_OBJECT = 0x73\n TC_STRING = 0x74\n TC_ARRAY = 0x75\n TC_CLASS = 0x76\n TC_BLOCKDATA = 0x77\n TC_ENDBLOCKDATA = 0x78\n TC_RESET = 0x79\n TC_BLOCKDATALONG = 0x7A\n TC_EXCEPTION = 0x7B\n TC_LONGSTRING = 0x7C\n TC_PROXYCLASSDESC = 0x7D\n TC_ENUM = 0x7E\n TC_MAX = 0x7E\n\n # classDescFlags\n SC_WRITE_METHOD = 0x01 # if SC_SERIALIZABLE\n SC_BLOCK_DATA = 0x08 # if SC_EXTERNALIZABLE\n SC_SERIALIZABLE = 0x02\n SC_EXTERNALIZABLE = 0x04\n SC_ENUM = 0x10\n\n # type definition chars (typecode)\n TYPE_BYTE = 'B' # 0x42\n TYPE_CHAR = 'C'\n TYPE_DOUBLE = 'D' # 0x44\n TYPE_FLOAT = 'F' # 0x46\n TYPE_INTEGER = 'I' # 0x49\n TYPE_LONG = 'J' # 0x4A\n TYPE_SHORT = 'S' # 0x53\n TYPE_BOOLEAN = 'Z' # 0x5A\n TYPE_OBJECT = 'L' # 0x4C\n TYPE_ARRAY = '[' # 0x5B\n\n # list of supported typecodes listed above\n TYPECODES_LIST = [\n # primitive types\n TYPE_BYTE,\n TYPE_CHAR,\n TYPE_DOUBLE,\n TYPE_FLOAT,\n TYPE_INTEGER,\n TYPE_LONG,\n TYPE_SHORT,\n TYPE_BOOLEAN,\n # object types\n TYPE_OBJECT,\n TYPE_ARRAY]\n\n BASE_REFERENCE_IDX = 0x7E0000\n\n# pylint: disable=missing-docstring\nclass JavaObjectUnmarshaller(JavaObjectConstants):\n \"\"\"Java object unmarshaller\"\"\"\n\n def __init__(self, stream=None):\n self.opmap = {\n self.TC_NULL: self.do_null,\n self.TC_CLASSDESC: self.do_classdesc,\n self.TC_OBJECT: self.do_object,\n self.TC_STRING: self.do_string,\n self.TC_ARRAY: self.do_array,\n self.TC_CLASS: self.do_class,\n self.TC_BLOCKDATA: self.do_blockdata,\n self.TC_REFERENCE: self.do_reference,\n self.TC_ENUM: self.do_enum,\n self.TC_ENDBLOCKDATA: self.do_null, # note that we are reusing of do_null\n }\n self.current_object = None\n self.reference_counter = 0\n self.references = []\n self.object_stream = stream\n self._readStreamHeader()\n self.object_transformers = []\n\n def readObject(self):\n \"\"\"read object\"\"\"\n try:\n _, res = self._read_and_exec_opcode(ident=0)\n\n position_bak = self.object_stream.tell()\n the_rest = self.object_stream.read()\n if the_rest:\n log_error(\"Warning!!!!: Stream still has %s bytes left.\\\nEnable debug mode of logging to see the hexdump.\" % len(the_rest))\n log_debug(self._create_hexdump(the_rest))\n else:\n log_debug(\"Java Object unmarshalled succesfully!\")\n self.object_stream.seek(position_bak)\n\n return res\n except Exception:\n self._oops_dump_state()\n raise\n\n def add_transformer(self, transformer):\n \"\"\"add to object transformer\"\"\"", "answers": [" self.object_transformers.append(transformer)"], "length": 707, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "fee217e1-67ad-475b-8dce-3991f7a66337", "reasoning": "Within the JavaObjectUnmarshaller class, the add_transformer method should store the provided transformer for later use. The class has an attribute object_transformers initialized as an empty list in __init__. The typical implementation is to append the transformer to this list, so the next line of code is the append statement.", "reasoning_model_answer": "self.object_transformers.append(transformer)", "assistant_with_reasoning": "\nWithin the JavaObjectUnmarshaller class, the add_transformer method should store the provided transformer for later use. The class has an attribute object_transformers initialized as an empty list in __init__. The typical implementation is to append the transformer to this list, so the next line of code is the append statement.\n\nself.object_transformers.append(transformer)", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 1.876, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 6584, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "self.object_transformers.append(transformer)", "score": 0.96, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n\nusing System.Collections;\nusing System.Collections.Concurrent;\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.Globalization;\nusing System.IO;\nusing System.Linq;\nusing System.Management.Automation.Language;\nusing System.Management.Automation.Runspaces;\nusing System.Net;\nusing System.Runtime.CompilerServices;\nusing System.Text.RegularExpressions;\nusing System.Threading;\nusing System.Xml;\nusing Microsoft.Management.Infrastructure;\nusing Microsoft.Management.Infrastructure.Options;\nusing Microsoft.PowerShell;\nusing Microsoft.PowerShell.Commands;\nusing Dbg = System.Management.Automation.Diagnostics;\n\nnamespace System.Management.Automation\n{\n internal class RemoteDiscoveryHelper\n {\n #region PSRP\n\n private static Collection RehydrateHashtableKeys(PSObject pso, string propertyName)\n {\n var rehydrationFlags = DeserializingTypeConverter.RehydrationFlags.NullValueOk |\n DeserializingTypeConverter.RehydrationFlags.MissingPropertyOk;\n Hashtable hashtable = DeserializingTypeConverter.GetPropertyValue(pso, propertyName, rehydrationFlags);\n if (hashtable == null)\n {\n return new Collection();\n }\n else\n {\n List list = hashtable\n .Keys\n .Cast()\n .Where(k => k != null)\n .Select(k => k.ToString())\n .Where(s => s != null)\n .ToList();\n return new Collection(list);\n }\n }\n\n internal static PSModuleInfo RehydratePSModuleInfo(PSObject deserializedModuleInfo)\n {\n var rehydrationFlags = DeserializingTypeConverter.RehydrationFlags.NullValueOk |\n DeserializingTypeConverter.RehydrationFlags.MissingPropertyOk;\n string name = DeserializingTypeConverter.GetPropertyValue(deserializedModuleInfo, \"Name\", rehydrationFlags);\n string path = DeserializingTypeConverter.GetPropertyValue(deserializedModuleInfo, \"Path\", rehydrationFlags);\n PSModuleInfo moduleInfo = new PSModuleInfo(name, path, context: null, sessionState: null);\n\n moduleInfo.SetGuid(DeserializingTypeConverter.GetPropertyValue(deserializedModuleInfo, \"Guid\", rehydrationFlags));\n moduleInfo.SetModuleType(DeserializingTypeConverter.GetPropertyValue(deserializedModuleInfo, \"ModuleType\", rehydrationFlags));\n moduleInfo.SetVersion(DeserializingTypeConverter.GetPropertyValue(deserializedModuleInfo, \"Version\", rehydrationFlags));\n moduleInfo.SetHelpInfoUri(DeserializingTypeConverter.GetPropertyValue(deserializedModuleInfo, \"HelpInfoUri\", rehydrationFlags));\n\n moduleInfo.AccessMode = DeserializingTypeConverter.GetPropertyValue(deserializedModuleInfo, \"AccessMode\", rehydrationFlags);\n moduleInfo.Author = DeserializingTypeConverter.GetPropertyValue(deserializedModuleInfo, \"Author\", rehydrationFlags);\n moduleInfo.ClrVersion = DeserializingTypeConverter.GetPropertyValue(deserializedModuleInfo, \"ClrVersion\", rehydrationFlags);\n moduleInfo.CompanyName = DeserializingTypeConverter.GetPropertyValue(deserializedModuleInfo, \"CompanyName\", rehydrationFlags);\n moduleInfo.Copyright = DeserializingTypeConverter.GetPropertyValue(deserializedModuleInfo, \"Copyright\", rehydrationFlags);\n moduleInfo.Description = DeserializingTypeConverter.GetPropertyValue(deserializedModuleInfo, \"Description\", rehydrationFlags);\n moduleInfo.DotNetFrameworkVersion = DeserializingTypeConverter.GetPropertyValue(deserializedModuleInfo, \"DotNetFrameworkVersion\", rehydrationFlags);\n moduleInfo.PowerShellHostName = DeserializingTypeConverter.GetPropertyValue(deserializedModuleInfo, \"PowerShellHostName\", rehydrationFlags);\n moduleInfo.PowerShellHostVersion = DeserializingTypeConverter.GetPropertyValue(deserializedModuleInfo, \"PowerShellHostVersion\", rehydrationFlags);\n moduleInfo.PowerShellVersion = DeserializingTypeConverter.GetPropertyValue(deserializedModuleInfo, \"PowerShellVersion\", rehydrationFlags);\n moduleInfo.ProcessorArchitecture = DeserializingTypeConverter.GetPropertyValue(deserializedModuleInfo, \"ProcessorArchitecture\", rehydrationFlags);\n\n moduleInfo.DeclaredAliasExports = RehydrateHashtableKeys(deserializedModuleInfo, \"ExportedAliases\");\n moduleInfo.DeclaredCmdletExports = RehydrateHashtableKeys(deserializedModuleInfo, \"ExportedCmdlets\");\n moduleInfo.DeclaredFunctionExports = RehydrateHashtableKeys(deserializedModuleInfo, \"ExportedFunctions\");\n moduleInfo.DeclaredVariableExports = RehydrateHashtableKeys(deserializedModuleInfo, \"ExportedVariables\");\n\n var compatiblePSEditions = DeserializingTypeConverter.GetPropertyValue(deserializedModuleInfo, \"CompatiblePSEditions\", rehydrationFlags);\n if (compatiblePSEditions != null && compatiblePSEditions.Any())\n {\n foreach (var edition in compatiblePSEditions)\n {\n moduleInfo.AddToCompatiblePSEditions(edition);\n }\n }\n\n // PowerShellGet related properties\n var tags = DeserializingTypeConverter.GetPropertyValue(deserializedModuleInfo, \"Tags\", rehydrationFlags);\n if (tags != null && tags.Any())\n {\n foreach (var tag in tags)\n {\n moduleInfo.AddToTags(tag);\n }\n }\n\n moduleInfo.ReleaseNotes = DeserializingTypeConverter.GetPropertyValue(deserializedModuleInfo, \"ReleaseNotes\", rehydrationFlags);\n moduleInfo.ProjectUri = DeserializingTypeConverter.GetPropertyValue(deserializedModuleInfo, \"ProjectUri\", rehydrationFlags);\n moduleInfo.LicenseUri = DeserializingTypeConverter.GetPropertyValue(deserializedModuleInfo, \"LicenseUri\", rehydrationFlags);\n moduleInfo.IconUri = DeserializingTypeConverter.GetPropertyValue(deserializedModuleInfo, \"IconUri\", rehydrationFlags);\n moduleInfo.RepositorySourceLocation = DeserializingTypeConverter.GetPropertyValue(deserializedModuleInfo, \"RepositorySourceLocation\", rehydrationFlags);\n\n return moduleInfo;\n }\n\n private static EventHandler GetStreamForwarder(Action forwardingAction, bool swallowInvalidOperationExceptions = false)\n {\n // TODO/FIXME: ETW event for extended semantics streams\n return delegate (object sender, DataAddedEventArgs eventArgs)\n {\n var psDataCollection = (PSDataCollection)sender;\n foreach (T t in psDataCollection.ReadAll())\n {\n try\n {\n forwardingAction(t);\n }\n catch (InvalidOperationException)\n {\n if (!swallowInvalidOperationExceptions)\n {\n throw;\n }\n }\n }\n };\n }\n\n // This is a static field (instead of a constant) to make it possible to set through tests (and/or by customers if needed for a workaround)\n private static readonly int s_blockingCollectionCapacity = 1000;\n\n private static IEnumerable InvokeTopLevelPowerShell(\n PowerShell powerShell,\n CancellationToken cancellationToken,\n PSCmdlet cmdlet,\n PSInvocationSettings invocationSettings,\n string errorMessageTemplate)\n {\n using (var mergedOutput = new BlockingCollection>>(s_blockingCollectionCapacity))\n {\n var asyncOutput = new PSDataCollection();\n EventHandler outputHandler = GetStreamForwarder(\n output => mergedOutput.Add(_ => new[] { output }),\n swallowInvalidOperationExceptions: true);\n\n EventHandler errorHandler = GetStreamForwarder(\n errorRecord => mergedOutput.Add(\n delegate (PSCmdlet c)\n {\n errorRecord = GetErrorRecordForRemotePipelineInvocation(errorRecord, errorMessageTemplate);\n HandleErrorFromPipeline(c, errorRecord, powerShell);\n return Enumerable.Empty();\n }),\n swallowInvalidOperationExceptions: true);\n\n EventHandler warningHandler = GetStreamForwarder(\n warningRecord => mergedOutput.Add(\n delegate (PSCmdlet c)\n {\n c.WriteWarning(warningRecord.Message);\n return Enumerable.Empty();\n }),\n swallowInvalidOperationExceptions: true);\n\n EventHandler verboseHandler = GetStreamForwarder(\n verboseRecord => mergedOutput.Add(\n delegate (PSCmdlet c)\n {\n c.WriteVerbose(verboseRecord.Message);\n return Enumerable.Empty();\n }),\n swallowInvalidOperationExceptions: true);\n\n EventHandler debugHandler = GetStreamForwarder(\n debugRecord => mergedOutput.Add(\n delegate (PSCmdlet c)\n {\n c.WriteDebug(debugRecord.Message);\n return Enumerable.Empty();\n }),\n swallowInvalidOperationExceptions: true);\n\n EventHandler informationHandler = GetStreamForwarder(\n informationRecord => mergedOutput.Add(\n delegate (PSCmdlet c)\n {\n c.WriteInformation(informationRecord);\n return Enumerable.Empty();\n }),\n swallowInvalidOperationExceptions: true);\n\n asyncOutput.DataAdded += outputHandler;\n powerShell.Streams.Error.DataAdded += errorHandler;\n powerShell.Streams.Warning.DataAdded += warningHandler;\n powerShell.Streams.Verbose.DataAdded += verboseHandler;\n powerShell.Streams.Debug.DataAdded += debugHandler;\n powerShell.Streams.Information.DataAdded += informationHandler;\n\n try\n {\n // TODO/FIXME: ETW event for PowerShell invocation\n\n var asyncResult = powerShell.BeginInvoke(\n input: null,\n output: asyncOutput,\n settings: invocationSettings,\n callback: delegate\n {\n try\n {\n mergedOutput.CompleteAdding();\n }\n catch (InvalidOperationException)\n // ignore exceptions thrown because mergedOutput.CompleteAdding was called\n {\n }\n },\n state: null);\n\n using (cancellationToken.Register(powerShell.Stop))\n {\n try\n {\n foreach (Func> mergedOutputItem in mergedOutput.GetConsumingEnumerable())\n {\n foreach (PSObject outputObject in mergedOutputItem(cmdlet))\n {\n yield return outputObject;\n }\n }\n }\n finally\n {\n mergedOutput.CompleteAdding();\n powerShell.EndInvoke(asyncResult);\n }\n }\n }\n finally\n {\n asyncOutput.DataAdded -= outputHandler;\n powerShell.Streams.Error.DataAdded -= errorHandler;\n powerShell.Streams.Warning.DataAdded -= warningHandler;\n powerShell.Streams.Verbose.DataAdded -= verboseHandler;\n powerShell.Streams.Debug.DataAdded -= debugHandler;\n powerShell.Streams.Information.DataAdded -= informationHandler;\n }\n }\n }\n\n private static IEnumerable InvokeNestedPowerShell(\n PowerShell powerShell,\n CancellationToken cancellationToken,\n PSCmdlet cmdlet,\n PSInvocationSettings invocationSettings,\n string errorMessageTemplate)\n {\n EventHandler errorHandler = GetStreamForwarder(\n delegate (ErrorRecord errorRecord)\n {\n errorRecord = GetErrorRecordForRemotePipelineInvocation(errorRecord, errorMessageTemplate);\n HandleErrorFromPipeline(cmdlet, errorRecord, powerShell);\n });\n powerShell.Streams.Error.DataAdded += errorHandler;\n\n try\n {\n using (cancellationToken.Register(powerShell.Stop))\n {\n // TODO/FIXME: ETW event for PowerShell invocation\n\n foreach (PSObject outputObject in powerShell.Invoke(null, invocationSettings))\n {\n yield return outputObject;\n }\n }\n }\n finally\n {\n powerShell.Streams.Error.DataAdded -= errorHandler;\n }\n }\n\n private static void CopyParameterFromCmdletToPowerShell(Cmdlet cmdlet, PowerShell powerShell, string parameterName)\n {\n object parameterValue;\n if (!cmdlet.MyInvocation.BoundParameters.TryGetValue(parameterName, out parameterValue))\n {\n return;\n }\n\n var commandParameter = new CommandParameter(parameterName, parameterValue);\n foreach (var command in powerShell.Commands.Commands)\n {\n if (command.Parameters.Any(existingParameter => existingParameter.Name.Equals(parameterName, StringComparison.OrdinalIgnoreCase)))\n {\n continue;\n }\n\n command.Parameters.Add(commandParameter);\n }\n }\n\n internal static ErrorRecord GetErrorRecordForProcessingOfCimModule(Exception innerException, string moduleName)\n {\n string errorMessage = string.Format(\n CultureInfo.InvariantCulture,\n Modules.RemoteDiscoveryFailedToProcessRemoteModule,\n moduleName,\n innerException.Message);\n\n Exception outerException = new InvalidOperationException(errorMessage, innerException);\n ErrorRecord errorRecord = new ErrorRecord(outerException, innerException.GetType().Name, ErrorCategory.NotSpecified, moduleName);\n return errorRecord;\n }\n\n private const string DiscoveryProviderNotFoundErrorId = \"DiscoveryProviderNotFound\";\n\n private static ErrorRecord GetErrorRecordForRemoteDiscoveryProvider(Exception innerException)\n {\n CimException cimException = innerException as CimException;\n if ((cimException != null) &&\n ((cimException.NativeErrorCode == NativeErrorCode.InvalidNamespace) ||\n (cimException.NativeErrorCode == NativeErrorCode.InvalidClass) ||\n (cimException.NativeErrorCode == NativeErrorCode.MethodNotFound) ||\n (cimException.NativeErrorCode == NativeErrorCode.MethodNotAvailable)))\n {\n string errorMessage = string.Format(\n CultureInfo.InvariantCulture,\n Modules.RemoteDiscoveryProviderNotFound,\n innerException.Message);\n Exception outerException = new InvalidOperationException(errorMessage, innerException);", "answers": [" ErrorRecord errorRecord = new ErrorRecord(outerException, DiscoveryProviderNotFoundErrorId, ErrorCategory.NotImplemented, null);"], "length": 841, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "e14e5eb9-64e4-4a58-8e67-7f97e7f43177", "reasoning": "The method GetErrorRecordForRemoteDiscoveryProvider is constructing an error record after detecting a specific CIM exception. After creating the outer InvalidOperationException (outerException), the next logical step is to wrap it in an ErrorRecord using the defined error ID constant and an appropriate error category, then return it. The typical pattern in similar methods is to instantiate ErrorRecord with the outer exception, the error ID constant, a category like ObjectNotFound, and a target object (null here). Hence the next line creates the ErrorRecord.", "reasoning_model_answer": "ErrorRecord errorRecord = new ErrorRecord(outerException, DiscoveryProviderNotFoundErrorId, ErrorCategory.ObjectNotFound, null);", "assistant_with_reasoning": "\nThe method GetErrorRecordForRemoteDiscoveryProvider is constructing an error record after detecting a specific CIM exception. After creating the outer InvalidOperationException (outerException), the next logical step is to wrap it in an ErrorRecord using the defined error ID constant and an appropriate error category, then return it. The typical pattern in similar methods is to instantiate ErrorRecord with the outer exception, the error ID constant, a category like ObjectNotFound, and a target object (null here). Hence the next line creates the ErrorRecord.\n\nErrorRecord errorRecord = new ErrorRecord(outerException, DiscoveryProviderNotFoundErrorId, ErrorCategory.ObjectNotFound, null);", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 6.291, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 17693, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "ErrorRecord errorRecord = new ErrorRecord(outerException, DiscoveryProviderNotFoundErrorId, ErrorCategory.ObjectNotFound, null);", "score": 0.88, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "#analysis files\n\nfrom PyQt5 import QtCore, QtGui, QtWidgets\nfrom PyQt5.QtWidgets import QFileDialog\nfrom analysis_gui import Ui_Analysis\nimport numpy as np\nimport matplotlib,math,csv\nmatplotlib.use('Qt5Agg')\nfrom matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas\nfrom matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar\nfrom matplotlib.figure import Figure\n\nclass MyMplCanvas(FigureCanvas):\n \"\"\"Ultimately, this is a QWidget (as well as a FigureCanvasAgg, etc.).\"\"\"\n def __init__(self, parent=None):\n fig = Figure()\n self.axes = fig.add_subplot(111)\n\n self.compute_initial_figure()\n\n FigureCanvas.__init__(self, fig)\n self.setParent(parent)\n\n FigureCanvas.setSizePolicy(self,\n QtWidgets.QSizePolicy.Expanding,\n QtWidgets.QSizePolicy.Expanding)\n FigureCanvas.updateGeometry(self)\n\n def compute_initial_figure(self):\n pass\n\nclass Radar(FigureCanvas):\n def __init__(self, titles, rect=None, parent=None):\n fig = Figure()\n if rect is None:\n rect = [0.05, 0.05, 0.8, 0.8]\n self.n = len(titles)\n self.angles = np.arange(90, 90 + 360, 360.0 / self.n)\n self.angles = [a % 360 for a in self.angles]\n self.axes = [fig.add_axes(rect, projection=\"polar\", label=\"axes%d\" % i)\n for i in range(self.n)]\n\n\n #FigureCanvas.setSizePolicy(self,\n #QtWidgets.QSizePolicy.Expanding,\n #QtWidgets.QSizePolicy.Expanding)\n #FigureCanvas.updateGeometry(self)\n\n self.ax = self.axes[0]\n self.ax.set_thetagrids(self.angles,labels=titles, fontsize=14)\n\n for ax in self.axes[1:]:\n ax.patch.set_visible(False)\n ax.grid(\"off\")\n ax.xaxis.set_visible(False)\n\n for ax, angle in zip(self.axes, self.angles):\n ax.set_rgrids([0.2,0.4,0.6,0.8,1.0], angle=angle)\n ax.spines[\"polar\"].set_visible(False)\n ax.set_ylim(auto=True)\n ax.set_xlim(auto=True)\n\n FigureCanvas.__init__(self, fig)\n self.setParent(parent)\n\n\n def plot(self, values, *args, **kw):\n angle = np.deg2rad(np.r_[self.angles, self.angles[0]])\n values = np.r_[values, values[0]]\n self.ax.plot(angle, values, *args, **kw)\n\n\n\nclass Analysis(QtWidgets.QMainWindow, Ui_Analysis):\n def __init__(self,parent = None):\n super(Analysis,self).__init__(parent)\n self.setupUi(self)\n\n self.XY_widget = QtWidgets.QWidget(self.tab_XY)\n self.Radar_widget = QtWidgets.QWidget(self.tab_Radar)\n self.Box_widget = QtWidgets.QWidget(self.tab_Box)\n self.Table_widget = QtWidgets.QWidget(self.tab_Table)\n\n self.XY_Layout = QtWidgets.QVBoxLayout(self.XY_widget)\n self.XY = MyMplCanvas(self.XY_widget)\n self.XY_Layout.addWidget(self.XY)\n self.mpl_toolbar = NavigationToolbar(self.XY, self.XY_widget)\n self.XY_Layout.addWidget(self.mpl_toolbar)\n\n\n self.Box_Layout = QtWidgets.QVBoxLayout(self.Box_widget)\n self.box = MyMplCanvas(self.Box_widget)\n self.Box_Layout.addWidget(self.box)\n self.box_toolbar = NavigationToolbar(self.box, self.Box_widget)\n self.Box_Layout.addWidget(self.box_toolbar)\n\n\n #self.tabWidget.setFocus()\n #self.setCentralWidget(self.tabWidget)\n #self.XY_widget.setFocus()\n #self.Radar_widget.setFocus()\n #self.Box_widget.setFocus()\n #self.tabWidget.setFocus()\n #self.setCentralWidget(self.tabWidget)\n\n self.actionOpen.triggered.connect(self.open)\n self.actionMax_min.triggered.connect(self.max_min)\n self.actionStandardization_M_0_S_1.triggered.connect(self.standardization)\n self.actionBaseline_Correction.triggered.connect(self.baseline)\n self.actionPeak_Detection.triggered.connect(self.peak_detection)\n self.actionFWHM.triggered.connect(self.FWHM)\n self.actionRise_Time.triggered.connect(self.rise_time)\n self.actionFall_Time.triggered.connect(self.fall_time)\n self.sensor_name = []\n self.sensor_sn = []\n self.time = []\n self.s1, self.s2, self.s3, self.s4, self.s5 = [], [], [], [], []\n self.s6, self.s7, self.s8, self.s9, self.s10 = [], [], [], [], []\n self.s11, self.s12, self.s13, self.s14, self.s15 = [], [], [], [], []\n self.s16, self.s17, self.s18 = [], [], []\n\n def open(self):\n self.data = []\n self.sensor_name = []\n self.sensor_sn = []\n self.time = []\n self.s1, self.s2, self.s3, self.s4, self.s5 = [], [], [], [], []\n self.s6, self.s7, self.s8, self.s9, self.s10 = [], [], [], [], []\n self.s11, self.s12, self.s13, self.s14, self.s15 = [], [], [], [], []\n self.s16, self.s17, self.s18 = [], [], []\n self.s1_normalized = []\n self.s2_normalized = []\n self.s3_normalized = []\n self.s4_normalized = []\n self.s5_normalized = []\n self.s6_normalized = []\n self.s7_normalized = []\n self.s8_normalized = []\n self.s9_normalized = []\n self.s10_normalized = []\n self.s11_normalized = []\n self.s12_normalized = []\n self.s13_normalized = []\n self.s14_normalized = []\n self.s15_normalized = []\n self.s16_normalized = []\n self.s17_normalized = []\n self.s18_normalized = []\n\n filename = QFileDialog.getOpenFileName(self, 'Open',filter=\"CSV Files (*.csv);;FOX Files (*.txt)\",\n initialFilter= \"CSV Files (*.csv)\")\n if filename[0]=='':\n print(\"Cancel\")\n elif filename[1]=='FOX Files (*.txt)':\n file = open(filename[0])\n lines = file.readlines()\n for i in range(len(lines)):\n if lines[i].startswith(\"[SENSOR NAME]\"):\n i += 1\n self.sensor_name = lines[i].split()\n if lines[i].startswith(\"[SENSOR SN]\"):\n i += 1\n self.sensor_sn = lines[i].split()\n if lines[i].startswith(\"[SENSOR DATA]\"):\n j = i + 1\n self.data = []\n for i in range(121):\n self.data.append(lines[j].split())\n j += 1\n print(self.sensor_name)\n print(self.sensor_sn)\n print(self.data)\n\n for i in range(len(self.data)):\n for j in range(19):\n if j==0:\n self.time.append(self.data[i][j])\n if j==1:\n self.s1.append(float(self.data[i][j]))\n if j==2:\n self.s2.append(float(self.data[i][j]))\n if j==3:\n self.s3.append(float(self.data[i][j]))\n if j==4:\n self.s4.append(float(self.data[i][j]))\n if j==5:\n self.s5.append(float(self.data[i][j]))\n if j==6:\n self.s6.append(float(self.data[i][j]))\n if j==7:\n self.s7.append(float(self.data[i][j]))\n if j==8:\n self.s8.append(float(self.data[i][j]))\n if j==9:\n self.s9.append(float(self.data[i][j]))\n if j==10:\n self.s10.append(float(self.data[i][j]))\n if j==11:\n self.s11.append(float(self.data[i][j]))\n if j==12:\n self.s12.append(float(self.data[i][j]))\n if j==13:\n self.s13.append(float(self.data[i][j]))\n if j==14:\n self.s14.append(float(self.data[i][j]))\n if j==15:\n self.s15.append(float(self.data[i][j]))\n if j==16:\n self.s16.append(float(self.data[i][j]))\n if j==17:\n self.s17.append(float(self.data[i][j]))\n if j==18:\n self.s18.append(float(self.data[i][j]))\n\n\n\n self.XY.axes.cla()\n self.XY.axes.plot(self.time, self.s1,label=self.sensor_name[0])\n self.XY.axes.plot(self.time, self.s2,label=self.sensor_name[1])\n self.XY.axes.plot(self.time, self.s3,label=self.sensor_name[2])\n self.XY.axes.plot(self.time, self.s4,label=self.sensor_name[3])\n self.XY.axes.plot(self.time, self.s5,label=self.sensor_name[4])\n self.XY.axes.plot(self.time, self.s6,label=self.sensor_name[5])\n self.XY.axes.plot(self.time, self.s7,label=self.sensor_name[6])\n self.XY.axes.plot(self.time, self.s8,label=self.sensor_name[7])\n self.XY.axes.plot(self.time, self.s9,label=self.sensor_name[8])\n self.XY.axes.plot(self.time, self.s10,label=self.sensor_name[9])\n self.XY.axes.plot(self.time, self.s11,label=self.sensor_name[10])\n self.XY.axes.plot(self.time, self.s12,label=self.sensor_name[11])\n self.XY.axes.plot(self.time, self.s13,label=self.sensor_name[12])\n self.XY.axes.plot(self.time, self.s14,label=self.sensor_name[13])\n self.XY.axes.plot(self.time, self.s15,label=self.sensor_name[14])\n self.XY.axes.plot(self.time, self.s16,label=self.sensor_name[15])\n self.XY.axes.plot(self.time, self.s17,label=self.sensor_name[16])\n self.XY.axes.plot(self.time, self.s18,label=self.sensor_name[17])\n self.XY.axes.set_xlabel(\"Time\")\n self.XY.axes.set_ylabel(\"Impedance\")\n self.XY.axes.legend(loc='best')\n self.XY.draw()\n self.menuNormalization.setEnabled(True)\n\n for item in self.s1:\n self.s1_normalized.append((item - min(self.s1)) / (max(self.s1) - min(self.s1)))\n for item in self.s2:\n self.s2_normalized.append((item - min(self.s2)) / (max(self.s2) - min(self.s2)))\n for item in self.s3:\n self.s3_normalized.append((item - min(self.s3)) / (max(self.s3) - min(self.s3)))\n for item in self.s4:\n self.s4_normalized.append((item - min(self.s4)) / (max(self.s4) - min(self.s4)))\n for item in self.s5:\n self.s5_normalized.append((item - min(self.s5)) / (max(self.s5) - min(self.s5)))\n for item in self.s6:\n self.s6_normalized.append((item - min(self.s6)) / (max(self.s6) - min(self.s6)))\n for item in self.s7:\n self.s7_normalized.append((item - min(self.s7)) / (max(self.s7) - min(self.s7)))\n for item in self.s8:\n self.s8_normalized.append((item - min(self.s8)) / (max(self.s8) - min(self.s8)))\n for item in self.s9:\n self.s9_normalized.append((item - min(self.s9)) / (max(self.s9) - min(self.s9)))\n for item in self.s10:\n self.s10_normalized.append((item - min(self.s10)) / (max(self.s10) - min(self.s10)))\n for item in self.s11:\n self.s11_normalized.append((item - min(self.s11)) / (max(self.s11) - min(self.s11)))\n for item in self.s12:\n self.s12_normalized.append((item - min(self.s12)) / (max(self.s12) - min(self.s12)))\n for item in self.s13:\n self.s13_normalized.append((item - min(self.s13)) / (max(self.s13) - min(self.s13)))\n for item in self.s14:\n self.s14_normalized.append((item - min(self.s14)) / (max(self.s14) - min(self.s14)))\n for item in self.s15:\n self.s15_normalized.append((item - min(self.s15)) / (max(self.s15) - min(self.s15)))\n for item in self.s16:\n self.s16_normalized.append((item - min(self.s16)) / (max(self.s16) - min(self.s16)))\n for item in self.s17:\n self.s17_normalized.append((item - min(self.s17)) / (max(self.s17) - min(self.s17)))\n for item in self.s18:\n self.s18_normalized.append((item - min(self.s18)) / (max(self.s18) - min(self.s18)))\n self.radar_plot()\n self.box_plot()\n\n elif filename[1] == \"CSV Files (*.csv)\":\n with open(filename[0], 'r') as csvfile:\n lines = csv.reader(csvfile)\n data = list(lines)\n self.tableWidget.setRowCount(len(data))\n self.tableWidget.setColumnCount(64)\n for i in range(3):\n for j in range(2):\n self.tableWidget.setItem(i,j,QtWidgets.QTableWidgetItem(data[i][j]))\n for i in range(3,len(data)):\n for j in range(64):\n self.tableWidget.setItem(i, j, QtWidgets.QTableWidgetItem(data[i][j]))\n\n\n def max_min(self):\n\n self.XY.axes.cla()\n self.XY.axes.plot(self.time, self.s1_normalized, label=self.sensor_name[0])\n '''\n self.sc.axes.plot(self.time, self.s2_normalized, label=self.sensor_name[1])\n self.sc.axes.plot(self.time, self.s3_normalized, label=self.sensor_name[2])\n self.sc.axes.plot(self.time, self.s4_normalized, label=self.sensor_name[3])\n self.sc.axes.plot(self.time, self.s5_normalized, label=self.sensor_name[4])\n self.sc.axes.plot(self.time, self.s6_normalized, label=self.sensor_name[5])\n self.sc.axes.plot(self.time, self.s7_normalized, label=self.sensor_name[6])\n self.sc.axes.plot(self.time, self.s8_normalized, label=self.sensor_name[7])\n self.sc.axes.plot(self.time, self.s9_normalized, label=self.sensor_name[8])\n self.sc.axes.plot(self.time, self.s10_normalized, label=self.sensor_name[9])\n self.sc.axes.plot(self.time, self.s11_normalized, label=self.sensor_name[10])\n self.sc.axes.plot(self.time, self.s12_normalized, label=self.sensor_name[11])\n self.sc.axes.plot(self.time, self.s13_normalized, label=self.sensor_name[12])\n self.sc.axes.plot(self.time, self.s14_normalized, label=self.sensor_name[13])\n self.sc.axes.plot(self.time, self.s15_normalized, label=self.sensor_name[14])\n self.sc.axes.plot(self.time, self.s16_normalized, label=self.sensor_name[15])\n self.sc.axes.plot(self.time, self.s17_normalized, label=self.sensor_name[16])\n self.sc.axes.plot(self.time, self.s18_normalized, label=self.sensor_name[17])\n '''", "answers": [" self.XY.axes.set_xlabel(\"Time\")"], "length": 867, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "f688088f-5cae-48d3-aeb3-b521dc77dbf1", "reasoning": "In the max_min method, after plotting the normalized data (currently only s1_normalized is plotted and the rest are commented out), the typical next steps are to label the axes, add a legend, and redraw the canvas. The first of these steps is setting the x-axis label, matching the pattern used elsewhere in the code.", "reasoning_model_answer": "self.XY.axes.set_xlabel(\"Time\")", "assistant_with_reasoning": "\nIn the max_min method, after plotting the normalized data (currently only s1_normalized is plotted and the rest are commented out), the typical next steps are to label the axes, add a legend, and redraw the canvas. The first of these steps is setting the x-axis label, matching the pattern used elsewhere in the code.\n\nself.XY.axes.set_xlabel(\"Time\")", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.919, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 14819, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "self.XY.axes.set_xlabel(\"Time\")", "score": 0.89, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "# Licensed under a 3-clause BSD style license - see LICENSE.rst\n# -*- coding: utf-8 -*-\n\"\"\"\ndesimodel.inputs.focalplane_sync\n===================================\n\nTools for checking and synchronizing focalplane state to online system.\n\"\"\"\nimport os\nimport datetime\nimport shutil\nimport gzip\nimport re\n\nimport subprocess as sp\n\nimport ast\n\nimport json\nimport yaml\n\nimport numpy as np\n\nfrom astropy.table import Table, Column\n\nfrom desiutil.log import get_logger\n\nfrom ..io import datadir, findfile, load_focalplane\n\nfrom .focalplane_utils import (\n create_tables,\n device_loc_to_type,\n load_petal_fiber_map,\n collision_to_segments,\n exclusions_equal,\n valid_states,\n device_compare,\n device_printdiff,\n update_exclusions,\n restricted_positioner_phi,\n hash_exclusion,\n)\n\n\ndef load_fp_calibs(path):\n \"\"\"Load data dumped from the online system.\"\"\"\n fpcal = Table.read(path, format=\"ascii.ecsv\")\n return fpcal\n\n\n# Rotation matrices. These few lines of code are copied from desimeter,\n# since it is the only thing that is needed from that package and there\n# is nothing even desi-specific here.\n\n\ndef Rx(angle): # all in radians\n Rx = np.array(\n [\n [1.0, 0.0, 0.0],\n [0.0, np.cos(angle), -np.sin(angle)],\n [0.0, np.sin(angle), np.cos(angle)],\n ]\n )\n return Rx\n\n\ndef Ry(angle): # all in radians\n Ry = np.array(\n [\n [np.cos(angle), 0.0, np.sin(angle)],\n [0.0, 1.0, 0.0],\n [-np.sin(angle), 0.0, np.cos(angle)],\n ]\n )\n return Ry\n\n\ndef Rz(angle): # all in radians\n Rz = np.array(\n [\n [np.cos(angle), -np.sin(angle), 0.0],\n [np.sin(angle), np.cos(angle), 0.0],\n [0.0, 0.0, 1.0],\n ]\n )\n return Rz\n\n\ndef Rxyz(alpha, beta, gamma): # yaw-pitch-roll system, all in radians\n return Rz(gamma) @ Ry(beta) @ Rx(alpha) # @ is matrix multiplication\n\n\ndef convert_fp_calibs(fpcal, sim=False):\n \"\"\"Convert the online system information.\n\n This returns a tuple containing the focalplane, the current state, and the set of\n unique exclusion polygons found in the file.\n\n Args:\n fpcal (Table): The table loaded from a dump from the online system.\n sim (bool): If True, clear all transient state issues and set hardware\n to be as \"good as possible\", for use in simulations.\n\n Returns:\n (tuple): The (focalplane, state, exclusions, time string) loaded from\n the cal file.\n\n \"\"\"\n # Parse the calibration time\n cal_time_str = fpcal.meta[\"DATE_RETRIEVED\"]\n cal_time = datetime.datetime.strptime(cal_time_str, \"%Y-%m-%dT%H:%M:%S%z\")\n\n state_time_str = cal_time.isoformat(timespec=\"seconds\")\n\n # Parse other metadata\n\n eo_phi = fpcal.meta[\"Eo_phi\"]\n eo_radius = fpcal.meta[\"Eo_radius_with_margin\"]\n alignments = fpcal.meta[\"PETAL_ALIGNMENTS\"]\n\n # Get the default exclusion polygons for theta, phi, GFA, and petal\n # boundaries\n\n excl = dict()\n\n ktheta_str = fpcal.meta[\"general_keepout_T\"]\n\n ktheta_raw = np.transpose(\n np.array(ast.literal_eval(fpcal.meta[\"general_keepout_T\"]))\n )\n kphi_raw = np.transpose(np.array(ast.literal_eval(fpcal.meta[\"general_keepout_P\"])))\n kpetal_raw = np.transpose(np.array(ast.literal_eval(fpcal.meta[\"keepout_PTL\"])))\n kgfa_raw = np.transpose(np.array(ast.literal_eval(fpcal.meta[\"keepout_GFA\"])))\n\n kp = dict()\n kp[\"theta\"] = dict()\n kp[\"theta\"][\"segments\"] = collision_to_segments(ktheta_raw)\n kp[\"theta\"][\"circles\"] = list()\n\n kp[\"phi\"] = dict()\n kp[\"phi\"][\"segments\"] = collision_to_segments(kphi_raw)\n kp[\"phi\"][\"circles\"] = list()\n\n kp[\"petal\"] = dict()\n kp[\"petal\"][\"segments\"] = collision_to_segments(kpetal_raw)\n kp[\"petal\"][\"circles\"] = list()\n\n kp[\"gfa\"] = dict()\n kp[\"gfa\"][\"segments\"] = collision_to_segments(kgfa_raw)\n kp[\"gfa\"][\"circles\"] = list()\n\n excl[\"default\"] = kp\n\n # Also make a set of exclusions for \"retracted\" positioners. In this case place\n # a circle at the the center of the theta axis.\n\n retrct = dict(excl[\"default\"])\n retrct[\"theta\"][\"segments\"] = list()\n retrct[\"theta\"][\"circles\"] = [[[0.0, 0.0], eo_radius]]\n excl[\"retracted\"] = retrct\n\n # Get the fiber map from device location to spectrographs.\n fmap = load_petal_fiber_map()\n\n # Build the transformation information for each petal alignment\n petal_rot = dict()\n petal_trans = dict()\n for petal_id, align in alignments.items():\n petal_rot[petal_id] = Rxyz(align[\"alpha\"], align[\"beta\"], align[\"gamma\"])\n petal_trans[petal_id] = np.array([align[\"Tx\"], align[\"Ty\"], align[\"Tz\"]])\n\n n_rows = len(fpcal)\n\n fp, state = create_tables(n_rows)\n\n # We only want to track the POS_P and POS_T values for positioners which are\n # non-functional (stuck) or have a broken fiber, since these are the positioners\n # we cannot move.\n stuck_or_broken = valid_states[\"BROKEN\"] | valid_states[\"STUCK\"]\n\n kindx = 0\n\n for r in range(n_rows):\n d = fpcal[r]\n # First set the focalplane properties\n fp[\"PETAL\"][r] = d[\"PETAL_LOC\"]\n fp[\"PETAL_ID\"][r] = d[\"PETAL_ID\"]\n fp[\"DEVICE\"][r] = d[\"DEVICE_LOC\"]\n fp[\"DEVICE_ID\"][r] = d[\"POS_ID\"]\n fp[\"LOCATION\"][r] = d[\"PETAL_LOC\"] * 1000 + d[\"DEVICE_LOC\"]\n fp[\"DEVICE_TYPE\"][r] = device_loc_to_type(fp[\"DEVICE\"][r])\n fp[\"SLITBLOCK\"][r] = -1\n fp[\"BLOCKFIBER\"][r] = -1\n fp[\"CABLE\"][r] = -1\n fp[\"CONDUIT\"][r] = \"NA\"\n fp[\"FWHM\"][r] = 0.0\n fp[\"FRD\"][r] = 0.0\n fp[\"ABS\"][r] = 0.0\n if d[\"PETAL_ID\"] in fmap:\n # We have some information about the device to fiber mapping.\n if d[\"DEVICE_LOC\"] in fmap[d[\"PETAL_ID\"]]:\n # This is a POS or ETC device\n fp[\"SLITBLOCK\"][r] = fmap[d[\"PETAL_ID\"]][d[\"DEVICE_LOC\"]][\"SLITBLOCK\"]\n fp[\"BLOCKFIBER\"][r] = fmap[d[\"PETAL_ID\"]][d[\"DEVICE_LOC\"]][\"BLOCKFIBER\"]\n fp[\"CABLE\"][r] = fmap[d[\"PETAL_ID\"]][d[\"DEVICE_LOC\"]][\"CABLE\"]\n fp[\"CONDUIT\"][r] = fmap[d[\"PETAL_ID\"]][d[\"DEVICE_LOC\"]][\"CONDUIT\"]\n fp[\"FWHM\"][r] = fmap[d[\"PETAL_ID\"]][d[\"DEVICE_LOC\"]][\"FWHM\"]\n fp[\"FRD\"][r] = fmap[d[\"PETAL_ID\"]][d[\"DEVICE_LOC\"]][\"FRD\"]\n fp[\"ABS\"][r] = fmap[d[\"PETAL_ID\"]][d[\"DEVICE_LOC\"]][\"ABS\"]\n fp[\"LENGTH_R1\"][r] = d[\"LENGTH_R1\"]\n fp[\"LENGTH_R2\"][r] = d[\"LENGTH_R2\"]\n fp[\"OFFSET_X\"][r] = d[\"OFFSET_X_CS5\"]\n fp[\"OFFSET_Y\"][r] = d[\"OFFSET_Y_CS5\"]\n fp[\"OFFSET_P\"][r] = d[\"OFFSET_P\"]\n\n # The OFFSET_T angle is in petal coordinates. We express this in global\n # coordinates by transforming 2 points and computing the angle from that.\n\n prot = petal_rot[d[\"PETAL_ID\"]]\n ptrans = petal_trans[d[\"PETAL_ID\"]]\n offset_pt_rad = np.radians(d[\"OFFSET_T\"])\n offset_pt_pnts = np.array(\n [\n [d[\"OFFSET_X_CS5\"], d[\"OFFSET_Y_CS5\"], 0.0],\n [\n 3.0 * np.cos(offset_pt_rad) + d[\"OFFSET_X_CS5\"],\n 3.0 * np.sin(offset_pt_rad) + d[\"OFFSET_Y_CS5\"],\n 0.0,\n ],\n ]\n )\n offset_fp_pnts = prot.dot(offset_pt_pnts.T).T + np.tile(ptrans, 2).reshape(\n (2, -1)\n )\n offset_fp_rad = np.arctan2(\n offset_fp_pnts[1, 1] - offset_fp_pnts[0, 1],\n offset_fp_pnts[1, 0] - offset_fp_pnts[0, 0],\n )\n offset_fp_deg = np.degrees(offset_fp_rad)\n if offset_fp_deg < -180.0:\n offset_fp_deg += 360.0\n if offset_fp_deg > 180.0:\n offset_fp_deg -= 360.0\n\n # # Sanity check that the alignment-transformed offset is \"close\" to the\n # # expected value.\n # petalrot_check = (float(7 + fp[\"PETAL\"][r]) * 36.0) % 360.0\n # petalrot_check += d[\"OFFSET_T\"]\n # if petalrot_check < -180.0:\n # petalrot_check += 360.0\n # if petalrot_check > 180.0:\n # petalrot_check -= 360.0\n # print(\n # \"device {}, petal {}, offset_t = {}, check = {}\".format(\n # fp[\"DEVICE\"][r], fp[\"PETAL\"][r], offset_fp_deg, petalrot_check\n # ),\n # flush=True,\n # )\n\n fp[\"OFFSET_T\"][r] = offset_fp_deg\n\n # Set the FIBER\n fp[\"FIBER\"][r] = -1\n if fp[\"SLITBLOCK\"][r] >= 0:\n fp[\"FIBER\"][r] = (", "answers": [" fp[\"PETAL\"][r] * 500 + fp[\"SLITBLOCK\"][r] * 25 + fp[\"BLOCKFIBER\"][r]"], "length": 843, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "9475735e-59fa-45ed-abeb-067fc18a50c6", "reasoning": "The code is assigning a fiber identifier when a valid slitblock exists. The SLITBLOCK column gives the block index and BLOCKFIBER gives the position within that block. The full fiber number is computed by multiplying the block index by the number of fibers per block (25) and adding the intra‑block fiber index. Therefore the next line should set fp[\"FIBER\"][r] to that calculated value.", "reasoning_model_answer": "fp[\"FIBER\"][r] = fp[\"SLITBLOCK\"][r] * 25 + fp[\"BLOCKFIBER\"][r]", "assistant_with_reasoning": "\nThe code is assigning a fiber identifier when a valid slitblock exists. The SLITBLOCK column gives the block index and BLOCKFIBER gives the position within that block. The full fiber number is computed by multiplying the block index by the number of fibers per block (25) and adding the intra‑block fiber index. Therefore the next line should set fp[\"FIBER\"][r] to that calculated value.\n\nfp[\"FIBER\"][r] = fp[\"SLITBLOCK\"][r] * 25 + fp[\"BLOCKFIBER\"][r]", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 5.673, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 8581, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "fp[\"FIBER\"][r] = fp[\"SLITBLOCK\"][r] * 25 + fp[\"BLOCKFIBER\"][r]", "score": 0.78, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "package org.basex.query.value.seq.tree;\n\nimport java.util.*;\n\nimport org.basex.query.*;\nimport org.basex.query.expr.*;\nimport org.basex.query.iter.*;\nimport org.basex.query.util.fingertree.*;\nimport org.basex.query.value.*;\nimport org.basex.query.value.item.*;\nimport org.basex.query.value.seq.*;\nimport org.basex.query.value.type.*;\nimport org.basex.util.*;\n\n/**\n * A sequence containing more items than fit into a {@link SmallSeq}.\n *\n * @author BaseX Team 2005-22, BSD License\n * @author Leo Woerteler\n */\nfinal class BigSeq extends TreeSeq {\n /** Left digit. */\n final Item[] left;\n /** Middle tree. */\n final FingerTree middle;\n /** Right digit. */\n final Item[] right;\n\n /**\n * Constructor.\n * @param left left digit\n * @param middle middle tree\n * @param right right digit\n * @param type item type\n */\n BigSeq(final Item[] left, final FingerTree middle, final Item[] right,\n final Type type) {\n super(left.length + middle.size() + right.length, type);\n this.left = left;\n this.middle = middle;\n this.right = right;\n assert left.length >= MIN_DIGIT && left.length <= MAX_DIGIT\n && right.length >= MIN_DIGIT && right.length <= MAX_DIGIT;\n }\n\n /**\n * Constructor for sequences with an empty middle tree.\n * @param left left digit\n * @param right right digit\n * @param type item type\n */\n BigSeq(final Item[] left, final Item[] right, final Type type) {\n this(left, FingerTree.empty(), right, type);\n }\n\n @Override\n public Item itemAt(final long index) {\n // index in one of the digits?\n if(index < left.length) return left[(int) index];\n final long midSize = size - right.length;\n if(index >= midSize) return right[(int) (index - midSize)];\n\n // the item is in the middle tree\n return middle.get(index - left.length);\n }\n\n @Override\n public TreeSeq reverse(final QueryContext qc) {\n qc.checkStop();\n final int l = left.length, r = right.length;\n final Item[] newLeft = new Item[r], newRight = new Item[l];\n for(int i = 0; i < r; i++) newLeft[i] = right[r - 1 - i];\n for(int i = 0; i < l; i++) newRight[i] = left[l - 1 - i];\n return new BigSeq(newLeft, middle.reverse(qc), newRight, type);\n }\n\n @Override\n public TreeSeq insert(final long pos, final Item item, final QueryContext qc) {\n qc.checkStop();\n final Type tp = type.union(item.type);\n final int l = left.length;\n if(pos <= l) {\n final int p = (int) pos;\n final Item[] temp = slice(left, 0, l + 1);\n Array.copy(temp, p, l - p, temp, p + 1);\n temp[p] = item;\n if(l < MAX_DIGIT) return new BigSeq(temp, middle, right, tp);\n\n final int m = (l + 1) / 2;\n return new BigSeq(slice(temp, 0, m),\n middle.cons(new LeafNode(slice(temp, m, l + 1))), right, tp);\n }\n\n final long midSize = middle.size();\n if(pos - l < midSize) return new BigSeq(left, middle.insert(pos - l, item, qc), right, tp);\n\n final int r = right.length;\n final int p = (int) (pos - l - midSize);\n final Item[] temp = slice(right, 0, r + 1);\n Array.copy(temp, p, r - p, temp, p + 1);\n temp[p] = item;\n if(r < MAX_DIGIT) return new BigSeq(left, middle, temp, tp);\n\n final int m = (r + 1) / 2;\n return new BigSeq(left, middle.snoc(new LeafNode(slice(temp, 0, m))),\n slice(temp, m, r + 1), tp);\n }\n\n @Override\n public TreeSeq remove(final long pos, final QueryContext qc) {\n qc.checkStop();\n if(pos < left.length) {\n // delete from left digit\n final int p = (int) pos, l = left.length;\n if(l > MIN_DIGIT) {\n // there is enough space, just delete the item\n final Item[] newLeft = new Item[l - 1];\n Array.copy(left, p, newLeft);\n Array.copy(left, p + 1, newLeft.length - p, newLeft, p);\n return new BigSeq(newLeft, middle, right, type);\n }\n\n if(middle.isEmpty()) {\n // merge left and right digit\n final int r = right.length, n = l - 1 + r;\n final Item[] vals = new Item[n];\n Array.copy(left, p, vals);\n Array.copy(left, p + 1, l - 1 - p, vals, p);\n Array.copyFromStart(right, r, vals, l - 1);\n return fromMerged(vals);\n }\n\n // extract a new left digit from the middle\n final Item[] head = ((LeafNode) middle.head()).values;\n final int r = head.length, n = l - 1 + r;\n\n if(r > MIN_LEAF) {\n // refill from neighbor\n final int move = (r - MIN_LEAF + 1) / 2;\n final Item[] newLeft = new Item[l - 1 + move];\n Array.copy(left, p, newLeft);\n Array.copy(left, p + 1, l - 1 - p, newLeft, p);\n Array.copyFromStart(head, move, newLeft, l - 1);\n final Item[] newHead = slice(head, move, r);\n return new BigSeq(newLeft, middle.replaceHead(new LeafNode(newHead)), right, type);\n }\n\n // merge digit and head node\n final Item[] newLeft = new Item[n];\n Array.copy(left, p, newLeft);\n Array.copy(left, p + 1, l - 1 - p, newLeft, p);\n Array.copyFromStart(head, r, newLeft, l - 1);\n return new BigSeq(newLeft, middle.tail(), right, type);\n }\n\n final long midSize = middle.size(), rightOffset = left.length + midSize;\n if(pos >= rightOffset) {\n // delete from right digit\n final int p = (int) (pos - rightOffset), r = right.length;\n if(r > MIN_DIGIT) {\n // there is enough space, just delete the item\n final Item[] newRight = new Item[r - 1];", "answers": [" Array.copy(right, p, newRight);"], "length": 777, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "a7b9a19a-393b-4d23-8015-7749f7491204", "reasoning": "The code is in the remove method handling deletion from the right digit. After checking that the right digit has enough items, it creates a new array newRight of size r-1. The next step mirrors the left‑digit case: copy the elements before the removed position into newRight, then copy the elements after the removed position. The first copy copies the prefix up to p, so the next line is Array.copy(right, p, newRight);", "reasoning_model_answer": "Array.copy(right, p, newRight);", "assistant_with_reasoning": "\nThe code is in the remove method handling deletion from the right digit. After checking that the right digit has enough items, it creates a new array newRight of size r-1. The next step mirrors the left‑digit case: copy the elements before the removed position into newRight, then copy the elements after the removed position. The first copy copies the prefix up to p, so the next line is Array.copy(right, p, newRight);\n\nArray.copy(right, p, newRight);", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.53, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 5530, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "Array.copy(right, p, newRight);", "score": 0.89, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "# (c) Copyright 2014 Hewlett-Packard Development Company, L.P.\n# All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n#\n\"\"\"HP LeftHand SAN ISCSI REST Proxy.\"\"\"\n\nfrom oslo_config import cfg\nfrom oslo_log import log as logging\nfrom oslo_utils import excutils\nfrom oslo_utils import importutils\nfrom oslo_utils import units\n\nfrom cinder import context\nfrom cinder import exception\nfrom cinder.i18n import _, _LE, _LI, _LW\nfrom cinder.volume import driver\nfrom cinder.volume import utils\nfrom cinder.volume import volume_types\n\nimport six\n\nimport math\nimport re\n\nLOG = logging.getLogger(__name__)\n\nhplefthandclient = importutils.try_import(\"hplefthandclient\")\nif hplefthandclient:\n from hplefthandclient import client as hp_lh_client\n from hplefthandclient import exceptions as hpexceptions\n\nhplefthand_opts = [\n cfg.StrOpt('hplefthand_api_url',\n default=None,\n help=\"HP LeftHand WSAPI Server Url like \"\n \"https://:8081/lhos\"),\n cfg.StrOpt('hplefthand_username',\n default=None,\n help=\"HP LeftHand Super user username\"),\n cfg.StrOpt('hplefthand_password',\n default=None,\n help=\"HP LeftHand Super user password\",\n secret=True),\n cfg.StrOpt('hplefthand_clustername',\n default=None,\n help=\"HP LeftHand cluster name\"),\n cfg.BoolOpt('hplefthand_iscsi_chap_enabled',\n default=False,\n help='Configure CHAP authentication for iSCSI connections '\n '(Default: Disabled)'),\n cfg.BoolOpt('hplefthand_debug',\n default=False,\n help=\"Enable HTTP debugging to LeftHand\"),\n\n]\n\nCONF = cfg.CONF\nCONF.register_opts(hplefthand_opts)\n\nMIN_API_VERSION = \"1.1\"\n\n# map the extra spec key to the REST client option key\nextra_specs_key_map = {\n 'hplh:provisioning': 'isThinProvisioned',\n 'hplh:ao': 'isAdaptiveOptimizationEnabled',\n 'hplh:data_pl': 'dataProtectionLevel',\n}\n\n# map the extra spec value to the REST client option value\nextra_specs_value_map = {\n 'isThinProvisioned': {'thin': True, 'full': False},\n 'isAdaptiveOptimizationEnabled': {'true': True, 'false': False},\n 'dataProtectionLevel': {\n 'r-0': 0, 'r-5': 1, 'r-10-2': 2, 'r-10-3': 3, 'r-10-4': 4, 'r-6': 5}\n}\n\n\nclass HPLeftHandRESTProxy(driver.ISCSIDriver):\n \"\"\"Executes REST commands relating to HP/LeftHand SAN ISCSI volumes.\n\n Version history:\n 1.0.0 - Initial REST iSCSI proxy\n 1.0.1 - Added support for retype\n 1.0.2 - Added support for volume migrate\n 1.0.3 - Fixed bug #1285829, HP LeftHand backend assisted migration\n should check for snapshots\n 1.0.4 - Fixed bug #1285925, LeftHand AO volume create performance\n improvement\n 1.0.5 - Fixed bug #1311350, Live-migration of an instance when\n attached to a volume was causing an error.\n 1.0.6 - Removing locks bug #1395953\n 1.0.7 - Fixed bug #1353137, Server was not removed from the HP\n Lefthand backend after the last volume was detached.\n 1.0.8 - Fixed bug #1418201, A cloned volume fails to attach.\n 1.0.9 - Adding support for manage/unmanage.\n 1.0.10 - Add stats for goodness_function and filter_function\n \"\"\"\n\n VERSION = \"1.0.10\"\n\n device_stats = {}\n\n def __init__(self, *args, **kwargs):\n super(HPLeftHandRESTProxy, self).__init__(*args, **kwargs)\n self.configuration.append_config_values(hplefthand_opts)\n if not self.configuration.hplefthand_api_url:\n raise exception.NotFound(_(\"HPLeftHand url not found\"))\n\n # blank is the only invalid character for cluster names\n # so we need to use it as a separator\n self.DRIVER_LOCATION = self.__class__.__name__ + ' %(cluster)s %(vip)s'\n\n def _login(self):\n client = self.do_setup(None)\n return client\n\n def _logout(self, client):\n client.logout()\n\n def _create_client(self):\n return hp_lh_client.HPLeftHandClient(\n self.configuration.hplefthand_api_url)\n\n def do_setup(self, context):\n \"\"\"Set up LeftHand client.\"\"\"\n try:\n client = self._create_client()\n client.login(\n self.configuration.hplefthand_username,\n self.configuration.hplefthand_password)\n\n if self.configuration.hplefthand_debug:\n client.debug_rest(True)\n\n cluster_info = client.getClusterByName(\n self.configuration.hplefthand_clustername)\n self.cluster_id = cluster_info['id']\n virtual_ips = cluster_info['virtualIPAddresses']\n self.cluster_vip = virtual_ips[0]['ipV4Address']\n self._update_backend_status(client)\n\n return client\n except hpexceptions.HTTPNotFound:\n raise exception.DriverNotInitialized(\n _('LeftHand cluster not found'))\n except Exception as ex:\n raise exception.DriverNotInitialized(ex)\n\n def check_for_setup_error(self):\n \"\"\"Checks for incorrect LeftHand API being used on backend.\"\"\"\n client = self._login()\n try:\n self.api_version = client.getApiVersion()\n\n LOG.info(_LI(\"HPLeftHand API version %s\"), self.api_version)\n\n if self.api_version < MIN_API_VERSION:\n LOG.warning(_LW(\"HPLeftHand API is version %(current)s. \"\n \"A minimum version of %(min)s is needed for \"\n \"manage/unmanage support.\"),\n {'current': self.api_version,\n 'min': MIN_API_VERSION})\n finally:\n self._logout(client)\n\n def get_version_string(self):\n return (_('REST %(proxy_ver)s hplefthandclient %(rest_ver)s') % {\n 'proxy_ver': self.VERSION,\n 'rest_ver': hplefthandclient.get_version_string()})\n\n def create_volume(self, volume):\n \"\"\"Creates a volume.\"\"\"\n client = self._login()\n try:\n # get the extra specs of interest from this volume's volume type\n volume_extra_specs = self._get_volume_extra_specs(volume)\n extra_specs = self._get_lh_extra_specs(\n volume_extra_specs,\n extra_specs_key_map.keys())\n\n # map the extra specs key/value pairs to key/value pairs\n # used as optional configuration values by the LeftHand backend\n optional = self._map_extra_specs(extra_specs)\n\n # if provisioning is not set, default to thin\n if 'isThinProvisioned' not in optional:\n optional['isThinProvisioned'] = True\n\n # AdaptiveOptimization defaults to 'true' if you don't specify the\n # value on a create, and that is the most efficient way to create\n # a volume. If you pass in 'false' or 'true' for AO, it will result\n # in an update operation following the create operation to set this\n # value, so it is best to not specify the value and let it default\n # to 'true'.\n if optional.get('isAdaptiveOptimizationEnabled'):\n del optional['isAdaptiveOptimizationEnabled']\n\n clusterName = self.configuration.hplefthand_clustername\n optional['clusterName'] = clusterName\n\n volume_info = client.createVolume(\n volume['name'], self.cluster_id,\n volume['size'] * units.Gi,\n optional)\n\n return self._update_provider(volume_info)\n except Exception as ex:\n raise exception.VolumeBackendAPIException(ex)\n finally:\n self._logout(client)\n\n def delete_volume(self, volume):\n \"\"\"Deletes a volume.\"\"\"\n client = self._login()\n try:\n volume_info = client.getVolumeByName(volume['name'])\n client.deleteVolume(volume_info['id'])\n except hpexceptions.HTTPNotFound:\n LOG.error(_LE(\"Volume did not exist. It will not be deleted\"))\n except Exception as ex:\n raise exception.VolumeBackendAPIException(ex)\n finally:\n self._logout(client)\n\n def extend_volume(self, volume, new_size):\n \"\"\"Extend the size of an existing volume.\"\"\"\n client = self._login()\n try:\n volume_info = client.getVolumeByName(volume['name'])\n\n # convert GB to bytes\n options = {'size': int(new_size) * units.Gi}\n client.modifyVolume(volume_info['id'], options)\n except Exception as ex:\n raise exception.VolumeBackendAPIException(ex)\n finally:\n self._logout(client)\n\n def create_snapshot(self, snapshot):\n \"\"\"Creates a snapshot.\"\"\"\n client = self._login()\n try:\n volume_info = client.getVolumeByName(snapshot['volume_name'])\n\n option = {'inheritAccess': True}\n client.createSnapshot(snapshot['name'],\n volume_info['id'],\n option)\n except Exception as ex:\n raise exception.VolumeBackendAPIException(ex)\n finally:\n self._logout(client)", "answers": [" def delete_snapshot(self, snapshot):"], "length": 882, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "0a8b726e-7e52-4cc5-9292-7508d812170c", "reasoning": "The code just finished defining the create_snapshot method, ending with its finally block. In the typical Cinder driver flow, the next operation defined after creating a snapshot is deleting a snapshot. Therefore the next line should start the delete_snapshot method definition.", "reasoning_model_answer": "def delete_snapshot(self, snapshot):", "assistant_with_reasoning": "\nThe code just finished defining the create_snapshot method, ending with its finally block. In the typical Cinder driver flow, the next operation defined after creating a snapshot is deleting a snapshot. Therefore the next line should start the delete_snapshot method definition.\n\ndef delete_snapshot(self, snapshot):", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 1.928, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 9940, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "def delete_snapshot(self, snapshot):", "score": 0.95, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/*\n * Autopsy Forensic Browser\n *\n * Copyright 2013-2020 Basis Technology Corp.\n * Contact: carrier sleuthkit org\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.sleuthkit.autopsy.modules.hashdatabase;\n\nimport java.io.File;\nimport java.io.IOException;\nimport java.nio.file.Paths;\nimport java.util.List;\nimport java.util.logging.Level;\nimport javax.swing.JFileChooser;\nimport javax.swing.JFrame;\nimport javax.swing.JOptionPane;\nimport org.apache.commons.io.FilenameUtils;\nimport org.openide.util.NbBundle;\nimport org.openide.windows.WindowManager;\nimport org.sleuthkit.autopsy.centralrepository.datamodel.CorrelationAttributeInstance;\nimport org.sleuthkit.autopsy.centralrepository.datamodel.CentralRepoException;\nimport org.sleuthkit.autopsy.centralrepository.datamodel.CentralRepoDbUtil;\nimport org.sleuthkit.autopsy.centralrepository.datamodel.CentralRepoOrganization;\nimport org.sleuthkit.autopsy.centralrepository.datamodel.CentralRepoFileSet;\nimport org.sleuthkit.autopsy.centralrepository.optionspanel.ManageOrganizationsDialog;\nimport org.sleuthkit.autopsy.coreutils.Logger;\nimport org.sleuthkit.autopsy.coreutils.ModuleSettings;\nimport org.sleuthkit.autopsy.coreutils.PlatformUtil;\nimport org.sleuthkit.autopsy.modules.hashdatabase.HashDbManager.HashDb;\nimport org.sleuthkit.autopsy.modules.hashdatabase.HashDbManager.HashDb.KnownFilesType;\nimport org.sleuthkit.autopsy.modules.hashdatabase.HashDbManager.HashDbManagerException;\nimport org.sleuthkit.datamodel.TskData;\nimport org.sleuthkit.datamodel.TskCoreException;\nimport org.sleuthkit.autopsy.centralrepository.datamodel.CentralRepository;\nimport org.sleuthkit.autopsy.featureaccess.FeatureAccessUtils;\n\n/**\n * Instances of this class allow a user to create a new hash database and add it\n * to the set of hash databases used to classify files as unknown, known or\n * notable.\n */\n@SuppressWarnings(\"PMD.SingularField\") // UI widgets cause lots of false positives\nfinal class HashDbCreateDatabaseDialog extends javax.swing.JDialog {\n\n private static final String DEFAULT_FILE_NAME = NbBundle\n .getMessage(HashDbCreateDatabaseDialog.class, \"HashDbCreateDatabaseDialog.defaultFileName\");\n private JFileChooser fileChooser = null;\n private HashDb newHashDb = null;\n private final static String LAST_FILE_PATH_KEY = \"HashDbCreate_Path\";\n private CentralRepoOrganization selectedOrg = null;\n private List orgs = null;\n static final String HASH_DATABASE_DIR_NAME = \"HashDatabases\";\n\n /**\n * Displays a dialog that allows a user to create a new hash database and\n * add it to the set of hash databases used to classify files as unknown,\n * known or notable.\n */\n HashDbCreateDatabaseDialog() {\n super((JFrame) WindowManager.getDefault().getMainWindow(), NbBundle.getMessage(HashDbCreateDatabaseDialog.class, \"HashDbCreateDatabaseDialog.createHashDbMsg\"), true);\n initFileChooser();\n initComponents();\n enableComponents();\n display();\n }\n\n /**\n * Get the hash database created by the user, if any.\n *\n * @return A HashDb object or null.\n */\n HashDb getHashDatabase() {\n return newHashDb;\n }\n\n private void initFileChooser() {\n fileChooser = new JFileChooser() {\n @Override\n public void approveSelection() {\n File selectedFile = getSelectedFile();\n if (!FilenameUtils.getExtension(selectedFile.getName()).equalsIgnoreCase(HashDbManager.getHashDatabaseFileExtension())) {\n if (JOptionPane.showConfirmDialog(this,\n NbBundle.getMessage(this.getClass(),\n \"HashDbCreateDatabaseDialog.hashDbMustHaveFileExtensionMsg\",\n HashDbManager.getHashDatabaseFileExtension()),\n NbBundle.getMessage(this.getClass(),\n \"HashDbCreateDatabaseDialog.fileNameErr\"),\n JOptionPane.OK_CANCEL_OPTION) == JOptionPane.CANCEL_OPTION) {\n cancelSelection();\n }\n return;\n }\n if (selectedFile.exists()) {\n if (JOptionPane.showConfirmDialog(this,\n NbBundle.getMessage(this.getClass(),\n \"HashDbCreateDatabaseDialog.fileNameAlreadyExistsMsg\"),\n NbBundle.getMessage(this.getClass(),\n \"HashDbCreateDatabaseDialog.fileExistsErr\"),\n JOptionPane.OK_CANCEL_OPTION) == JOptionPane.CANCEL_OPTION) {\n cancelSelection();\n }\n return;\n }\n super.approveSelection();\n }\n };\n fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);\n fileChooser.setDragEnabled(false);\n fileChooser.setMultiSelectionEnabled(false);\n }\n\n private void display() {\n setLocationRelativeTo(getOwner());\n setVisible(true);\n }\n\n private void enableComponents() {\n\n if (!CentralRepository.isEnabled() || !FeatureAccessUtils.canAddHashSetsToCentralRepo()) {\n centralRepoRadioButton.setEnabled(false);\n fileTypeRadioButton.setSelected(true);\n } else {\n populateCombobox();\n }\n\n boolean isFileType = fileTypeRadioButton.isSelected();\n\n // Type type only\n databasePathLabel.setEnabled(isFileType);\n databasePathTextField.setEnabled(isFileType);\n saveAsButton.setEnabled(isFileType);\n\n // Central repo only\n lbOrg.setEnabled(!isFileType);\n orgButton.setEnabled(!isFileType);\n orgComboBox.setEnabled(!isFileType);\n }\n\n @NbBundle.Messages({\"HashDbCreateDatabaseDialog.populateOrgsError.message=Failure loading organizations.\"})\n private void populateCombobox() {\n orgComboBox.removeAllItems();\n try {\n CentralRepository dbManager = CentralRepository.getInstance();\n orgs = dbManager.getOrganizations();\n orgs.forEach((org) -> {\n orgComboBox.addItem(org.getName());\n if (CentralRepoDbUtil.isDefaultOrg(org)) {\n orgComboBox.setSelectedItem(org.getName());\n selectedOrg = org;\n }\n });\n if ((selectedOrg == null) && (!orgs.isEmpty())) {\n selectedOrg = orgs.get(0);\n }\n } catch (CentralRepoException ex) {\n JOptionPane.showMessageDialog(this, Bundle.HashDbCreateDatabaseDialog_populateOrgsError_message());\n Logger.getLogger(ImportCentralRepoDbProgressDialog.class.getName()).log(Level.SEVERE, \"Failure loading organizations\", ex);\n }\n }\n\n /**\n * This method is called from within the constructor to initialize the form.\n * WARNING: Do NOT modify this code. The content of this method is always\n * regenerated by the Form Editor.\n */\n @SuppressWarnings(\"unchecked\")\n // //GEN-BEGIN:initComponents\n private void initComponents() {\n\n buttonGroup1 = new javax.swing.ButtonGroup();\n storageTypeButtonGroup = new javax.swing.ButtonGroup();\n saveAsButton = new javax.swing.JButton();\n cancelButton = new javax.swing.JButton();\n knownRadioButton = new javax.swing.JRadioButton();\n knownBadRadioButton = new javax.swing.JRadioButton();\n databasePathLabel = new javax.swing.JLabel();\n hashSetNameTextField = new javax.swing.JTextField();\n jLabel2 = new javax.swing.JLabel();\n sendIngestMessagesCheckbox = new javax.swing.JCheckBox();\n jLabel3 = new javax.swing.JLabel();\n databasePathTextField = new javax.swing.JTextField();\n okButton = new javax.swing.JButton();\n jLabel4 = new javax.swing.JLabel();\n fileTypeRadioButton = new javax.swing.JRadioButton();\n centralRepoRadioButton = new javax.swing.JRadioButton();\n lbOrg = new javax.swing.JLabel();\n orgComboBox = new javax.swing.JComboBox<>();\n orgButton = new javax.swing.JButton();\n noChangeRadioButton = new javax.swing.JRadioButton();\n\n setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);\n\n org.openide.awt.Mnemonics.setLocalizedText(saveAsButton, org.openide.util.NbBundle.getMessage(HashDbCreateDatabaseDialog.class, \"HashDbCreateDatabaseDialog.saveAsButton.text\")); // NOI18N\n saveAsButton.addActionListener(new java.awt.event.ActionListener() {\n public void actionPerformed(java.awt.event.ActionEvent evt) {\n saveAsButtonActionPerformed(evt);\n }\n });\n\n org.openide.awt.Mnemonics.setLocalizedText(cancelButton, org.openide.util.NbBundle.getMessage(HashDbCreateDatabaseDialog.class, \"HashDbCreateDatabaseDialog.cancelButton.text\")); // NOI18N\n cancelButton.addActionListener(new java.awt.event.ActionListener() {\n public void actionPerformed(java.awt.event.ActionEvent evt) {\n cancelButtonActionPerformed(evt);\n }\n });\n\n buttonGroup1.add(knownRadioButton);\n org.openide.awt.Mnemonics.setLocalizedText(knownRadioButton, org.openide.util.NbBundle.getMessage(HashDbCreateDatabaseDialog.class, \"HashDbCreateDatabaseDialog.knownRadioButton.text\")); // NOI18N\n knownRadioButton.addActionListener(new java.awt.event.ActionListener() {\n public void actionPerformed(java.awt.event.ActionEvent evt) {\n knownRadioButtonActionPerformed(evt);\n }\n });\n\n buttonGroup1.add(knownBadRadioButton);\n knownBadRadioButton.setSelected(true);\n org.openide.awt.Mnemonics.setLocalizedText(knownBadRadioButton, org.openide.util.NbBundle.getMessage(HashDbCreateDatabaseDialog.class, \"HashDbCreateDatabaseDialog.knownBadRadioButton.text\")); // NOI18N\n knownBadRadioButton.addActionListener(new java.awt.event.ActionListener() {\n public void actionPerformed(java.awt.event.ActionEvent evt) {", "answers": [" knownBadRadioButtonActionPerformed(evt);"], "length": 686, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "8caafdcc-694c-43c7-be39-1a6f6b253ae2", "reasoning": "The initComponents method is generated by NetBeans. After adding an ActionListener to knownBadRadioButton, the next line should be the body of the actionPerformed method, which calls the corresponding handler method. The typical pattern is knownBadRadioButtonActionPerformed(evt); followed by closing braces. Therefore the next line is the call to the handler.", "reasoning_model_answer": "knownBadRadioButtonActionPerformed(evt);", "assistant_with_reasoning": "\nThe initComponents method is generated by NetBeans. After adding an ActionListener to knownBadRadioButton, the next line should be the body of the actionPerformed method, which calls the corresponding handler method. The typical pattern is knownBadRadioButtonActionPerformed(evt); followed by closing braces. Therefore the next line is the call to the handler.\n\nknownBadRadioButtonActionPerformed(evt);", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.742, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 10856, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "knownBadRadioButtonActionPerformed(evt);", "score": 0.83, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/*\n * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * This code is free software; you can redistribute it and/or modify it\n * under the terms of the GNU General Public License version 2 only, as\n * published by the Free Software Foundation. Oracle designates this\n * particular file as subject to the \"Classpath\" exception as provided\n * by Oracle in the LICENSE file that accompanied this code.\n *\n * This code is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License\n * version 2 for more details (a copy is included in the LICENSE file that\n * accompanied this code).\n *\n * You should have received a copy of the GNU General Public License version\n * 2 along with this work; if not, write to the Free Software Foundation,\n * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.\n *\n * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA\n * or visit www.oracle.com if you need additional information or have any\n * questions.\n */\n\npackage jdk.nashorn.internal.objects;\n\nimport static jdk.nashorn.internal.lookup.Lookup.MH;\nimport static jdk.nashorn.internal.runtime.ECMAErrors.typeError;\nimport static jdk.nashorn.internal.runtime.ScriptRuntime.UNDEFINED;\nimport static jdk.nashorn.internal.runtime.UnwarrantedOptimismException.INVALID_PROGRAM_POINT;\n\nimport java.lang.invoke.MethodHandle;\nimport java.lang.invoke.MethodHandles;\nimport java.lang.invoke.MethodType;\nimport java.util.ArrayList;\nimport java.util.Iterator;\nimport java.util.List;\nimport jdk.internal.dynalink.CallSiteDescriptor;\nimport jdk.internal.dynalink.linker.GuardedInvocation;\nimport jdk.internal.dynalink.linker.LinkRequest;\nimport jdk.nashorn.internal.lookup.Lookup;\nimport jdk.nashorn.internal.objects.annotations.Constructor;\nimport jdk.nashorn.internal.objects.annotations.ScriptClass;\nimport jdk.nashorn.internal.runtime.FindProperty;\nimport jdk.nashorn.internal.runtime.JSType;\nimport jdk.nashorn.internal.runtime.PropertyMap;\nimport jdk.nashorn.internal.runtime.ScriptFunction;\nimport jdk.nashorn.internal.runtime.ScriptObject;\nimport jdk.nashorn.internal.runtime.ScriptRuntime;\nimport jdk.nashorn.internal.runtime.arrays.ArrayLikeIterator;\nimport jdk.nashorn.internal.scripts.JO;\n\n/**\n * This class is the implementation of the Nashorn-specific global object named {@code JSAdapter}. It can be\n * thought of as the {@link java.lang.reflect.Proxy} equivalent for JavaScript. NativeJSAdapter calls specially named\n * JavaScript methods on an adaptee object when property access/update/call/new/delete is attempted on it. Example:\n *
    \n *    var y = {\n *                __get__    : function (name) { ... }\n *                __has__    : function (name) { ... }\n *                __put__    : function (name, value) {...}\n *                __call__   : function (name, arg1, arg2) {...}\n *                __new__    : function (arg1, arg2) {...}\n *                __delete__ : function (name) { ... }\n *                __getIds__ : function () { ... }\n *            };\n *\n *    var x = new JSAdapter(y);\n *\n *    x.i;                        // calls y.__get__\n *    x.foo();                    // calls y.__call__\n *    new x();                    // calls y.__new__\n *    i in x;                     // calls y.__has__\n *    x.p = 10;                   // calls y.__put__\n *    delete x.p;                 // calls y.__delete__\n *    for (i in x) { print(i); }  // calls y.__getIds__\n * 
    \n *

    \n * JavaScript caller of adapter object is isolated from the fact that the property access/mutation/deletion are really\n * calls to JavaScript methods on adaptee.\n *

    \n *

    \n * JSAdapter constructor can optionally receive an \"overrides\" object. Properties of overrides object is copied to\n * JSAdapter instance. When user accessed property is one of these, then adaptee's methods like {@code __get__},\n * {@code __put__} etc. are not called for those. This can be used to make certain \"preferred\" properties that can be\n * accessed in the usual/faster way avoiding proxy mechanism. Example:\n *

    \n *
    \n *     var x = new JSAdapter({ foo: 444, bar: 6546 }) {\n *          __get__: function(name) { return name; }\n *      };\n *\n *     x.foo;           // 444 directly retrieved without __get__ call\n *     x.bar = 'hello'; // \"bar\" directly set without __put__ call\n *     x.prop           // calls __get__(\"prop\") as 'prop' is not overridden\n * 
    \n * It is possible to pass a specific prototype for JSAdapter instance by passing three arguments to JSAdapter\n * constructor. So exact signature of JSAdapter constructor is as follows:\n *
    \n *     JSAdapter([proto], [overrides], adaptee);\n * 
    \n * Both proto and overrides are optional - but adaptee is not. When proto is not passed {@code JSAdapter.prototype} is\n * used.\n */\n@ScriptClass(\"JSAdapter\")\npublic final class NativeJSAdapter extends ScriptObject {\n /** object get operation */\n public static final String __get__ = \"__get__\";\n /** object out operation */\n public static final String __put__ = \"__put__\";\n /** object call operation */\n public static final String __call__ = \"__call__\";\n /** object new operation */\n public static final String __new__ = \"__new__\";\n /** object getIds operation */\n public static final String __getIds__ = \"__getIds__\";", "answers": [" /** object getKeys operation */"], "length": 716, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "ee679226-1057-4ba2-a9a2-c18a9d052dd1", "reasoning": "The code is defining static final String constants for the special JSAdapter method names. Each constant is preceded by a Javadoc comment describing the operation. After the __getIds__ constant, the next logical constant is for the '__has__' operation, following the same pattern. Therefore the next line should be the comment introducing the __has__ constant.", "reasoning_model_answer": "/** object has operation */", "assistant_with_reasoning": "\nThe code is defining static final String constants for the special JSAdapter method names. Each constant is preceded by a Javadoc comment describing the operation. After the __getIds__ constant, the next logical constant is for the '__has__' operation, following the same pattern. Therefore the next line should be the comment introducing the __has__ constant.\n\n/** object has operation */", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.923, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 5642, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "/** object has operation */", "score": 0.81, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "\"\"\"Delegate test execution to another environment.\"\"\"\nfrom __future__ import (absolute_import, division, print_function)\n__metaclass__ = type\n\nimport os\nimport re\nimport sys\nimport tempfile\n\nfrom . import types as t\n\nfrom .executor import (\n SUPPORTED_PYTHON_VERSIONS,\n HTTPTESTER_HOSTS,\n create_shell_command,\n run_httptester,\n start_httptester,\n get_python_interpreter,\n get_python_version,\n get_docker_completion,\n get_remote_completion,\n)\n\nfrom .config import (\n TestConfig,\n EnvironmentConfig,\n IntegrationConfig,\n WindowsIntegrationConfig,\n NetworkIntegrationConfig,\n ShellConfig,\n SanityConfig,\n UnitsConfig,\n)\n\nfrom .core_ci import (\n AnsibleCoreCI,\n)\n\nfrom .manage_ci import (\n ManagePosixCI,\n ManageWindowsCI,\n)\n\nfrom .util import (\n ApplicationError,\n common_environment,\n pass_vars,\n display,\n ANSIBLE_BIN_PATH,\n ANSIBLE_TEST_DATA_ROOT,\n ANSIBLE_LIB_ROOT,\n ANSIBLE_TEST_ROOT,\n tempdir,\n make_dirs,\n)\n\nfrom .util_common import (\n run_command,\n ResultType,\n create_interpreter_wrapper,\n)\n\nfrom .docker_util import (\n docker_exec,\n docker_get,\n docker_pull,\n docker_put,\n docker_rm,\n docker_run,\n docker_available,\n docker_network_disconnect,\n get_docker_networks,\n)\n\nfrom .cloud import (\n get_cloud_providers,\n)\n\nfrom .target import (\n IntegrationTarget,\n)\n\nfrom .data import (\n data_context,\n)\n\nfrom .payload import (\n create_payload,\n)\n\nfrom .venv import (\n create_virtual_environment,\n)\n\n\ndef check_delegation_args(args):\n \"\"\"\n :type args: CommonConfig\n \"\"\"\n if not isinstance(args, EnvironmentConfig):\n return\n\n if args.docker:\n get_python_version(args, get_docker_completion(), args.docker_raw)\n elif args.remote:\n get_python_version(args, get_remote_completion(), args.remote)\n\n\ndef delegate(args, exclude, require, integration_targets):\n \"\"\"\n :type args: EnvironmentConfig\n :type exclude: list[str]\n :type require: list[str]\n :type integration_targets: tuple[IntegrationTarget]\n :rtype: bool\n \"\"\"\n if isinstance(args, TestConfig):\n with tempfile.NamedTemporaryFile(prefix='metadata-', suffix='.json', dir=data_context().content.root) as metadata_fd:\n args.metadata_path = os.path.basename(metadata_fd.name)\n args.metadata.to_file(args.metadata_path)\n\n try:\n return delegate_command(args, exclude, require, integration_targets)\n finally:\n args.metadata_path = None\n else:\n return delegate_command(args, exclude, require, integration_targets)\n\n\ndef delegate_command(args, exclude, require, integration_targets):\n \"\"\"\n :type args: EnvironmentConfig\n :type exclude: list[str]\n :type require: list[str]\n :type integration_targets: tuple[IntegrationTarget]\n :rtype: bool\n \"\"\"\n if args.venv:\n delegate_venv(args, exclude, require, integration_targets)\n return True\n\n if args.tox:\n delegate_tox(args, exclude, require, integration_targets)\n return True\n\n if args.docker:\n delegate_docker(args, exclude, require, integration_targets)\n return True\n\n if args.remote:\n delegate_remote(args, exclude, require, integration_targets)\n return True\n\n return False\n\n\ndef delegate_tox(args, exclude, require, integration_targets):\n \"\"\"\n :type args: EnvironmentConfig\n :type exclude: list[str]\n :type require: list[str]\n :type integration_targets: tuple[IntegrationTarget]\n \"\"\"\n if args.python:\n versions = (args.python_version,)\n\n if args.python_version not in SUPPORTED_PYTHON_VERSIONS:\n raise ApplicationError('tox does not support Python version %s' % args.python_version)\n else:\n versions = SUPPORTED_PYTHON_VERSIONS\n\n if args.httptester:\n needs_httptester = sorted(target.name for target in integration_targets if 'needs/httptester/' in target.aliases)\n\n if needs_httptester:\n display.warning('Use --docker or --remote to enable httptester for tests marked \"needs/httptester\": %s' % ', '.join(needs_httptester))\n\n options = {\n '--tox': args.tox_args,\n '--tox-sitepackages': 0,\n }\n\n for version in versions:\n tox = ['tox', '-c', os.path.join(ANSIBLE_TEST_DATA_ROOT, 'tox.ini'), '-e', 'py' + version.replace('.', '')]\n\n if args.tox_sitepackages:\n tox.append('--sitepackages')\n\n tox.append('--')\n\n cmd = generate_command(args, None, ANSIBLE_BIN_PATH, data_context().content.root, options, exclude, require)\n\n if not args.python:\n cmd += ['--python', version]\n\n # newer versions of tox do not support older python versions and will silently fall back to a different version\n # passing this option will allow the delegated ansible-test to verify it is running under the expected python version\n # tox 3.0.0 dropped official python 2.6 support: https://tox.readthedocs.io/en/latest/changelog.html#v3-0-0-2018-04-02\n # tox 3.1.3 is the first version to support python 3.8 and later: https://tox.readthedocs.io/en/latest/changelog.html#v3-1-3-2018-08-03\n # tox 3.1.3 appears to still work with python 2.6, making it a good version to use when supporting all python versions we use\n # virtualenv 16.0.0 dropped python 2.6 support: https://virtualenv.pypa.io/en/latest/changes/#v16-0-0-2018-05-16\n cmd += ['--check-python', version]\n\n if isinstance(args, TestConfig):\n if args.coverage and not args.coverage_label:\n cmd += ['--coverage-label', 'tox-%s' % version]\n\n env = common_environment()\n\n # temporary solution to permit ansible-test delegated to tox to provision remote resources\n optional = (\n 'SHIPPABLE',\n 'SHIPPABLE_BUILD_ID',\n 'SHIPPABLE_JOB_NUMBER',\n )\n\n env.update(pass_vars(required=[], optional=optional))\n\n run_command(args, tox + cmd, env=env)\n\n\ndef delegate_venv(args, # type: EnvironmentConfig\n exclude, # type: t.List[str]\n require, # type: t.List[str]\n integration_targets, # type: t.Tuple[IntegrationTarget, ...]\n ): # type: (...) -> None\n \"\"\"Delegate ansible-test execution to a virtual environment using venv or virtualenv.\"\"\"\n if args.python:\n versions = (args.python_version,)\n else:\n versions = SUPPORTED_PYTHON_VERSIONS\n\n if args.httptester:\n needs_httptester = sorted(target.name for target in integration_targets if 'needs/httptester/' in target.aliases)\n\n if needs_httptester:\n display.warning('Use --docker or --remote to enable httptester for tests marked \"needs/httptester\": %s' % ', '.join(needs_httptester))\n\n venvs = dict((version, os.path.join(ResultType.TMP.path, 'delegation', 'python%s' % version)) for version in versions)\n venvs = dict((version, path) for version, path in venvs.items() if create_virtual_environment(args, version, path))\n\n if not venvs:\n raise ApplicationError('No usable virtual environment support found.')\n\n options = {\n '--venv': 0,\n }\n\n with tempdir() as inject_path:\n for version, path in venvs.items():\n create_interpreter_wrapper(os.path.join(path, 'bin', 'python'), os.path.join(inject_path, 'python%s' % version))\n\n python_interpreter = os.path.join(inject_path, 'python%s' % args.python_version)\n\n cmd = generate_command(args, python_interpreter, ANSIBLE_BIN_PATH, data_context().content.root, options, exclude, require)\n\n if isinstance(args, TestConfig):\n if args.coverage and not args.coverage_label:\n cmd += ['--coverage-label', 'venv']\n\n env = common_environment()\n\n with tempdir() as library_path:\n # expose ansible and ansible_test to the virtual environment (only required when running from an install)\n os.symlink(ANSIBLE_LIB_ROOT, os.path.join(library_path, 'ansible'))", "answers": [" os.symlink(ANSIBLE_TEST_ROOT, os.path.join(library_path, 'ansible_test'))"], "length": 710, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "6be9d8aa-9d5e-4fac-b067-9a0758b827bd", "reasoning": "The function is setting up a temporary library path for the virtual environment. It already symlinks the Ansible library directory into that path. The next logical step is to also expose the ansible_test package by symlinking ANSIBLE_TEST_ROOT into the same temporary library directory. This matches the pattern used earlier and prepares the environment for execution.", "reasoning_model_answer": "os.symlink(ANSIBLE_TEST_ROOT, os.path.join(library_path, 'ansible_test'))", "assistant_with_reasoning": "\nThe function is setting up a temporary library path for the virtual environment. It already symlinks the Ansible library directory into that path. The next logical step is to also expose the ansible_test package by symlinking ANSIBLE_TEST_ROOT into the same temporary library directory. This matches the pattern used earlier and prepares the environment for execution.\n\nos.symlink(ANSIBLE_TEST_ROOT, os.path.join(library_path, 'ansible_test'))", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.768, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 8200, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "os.symlink(ANSIBLE_TEST_ROOT, os.path.join(library_path, 'ansible_test'))", "score": 0.92, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "using System;\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Globalization;\nusing System.Text;\nusing AutoJITRuntime.Exceptions;\nusing AutoJITRuntime.Variants;\n\nnamespace AutoJITRuntime\n{\n public abstract class Variant : IEnumerable\n {\n private static readonly Dictionary> CreateStrategies = new Dictionary> {\n { typeof (int), o => Create( (int) o ) },\n { typeof (byte[]), o => Create( (byte[]) o ) },\n { typeof (Int64), o => Create( (Int64) o ) },\n { typeof (double), o => Create( (double) o ) },\n { typeof (bool), o => Create( (bool) o ) },\n { typeof (string), o => Create( (string) o ) },\n { typeof (IntPtr), o => Create( (IntPtr) o ) },\n { typeof (Default), o => Create( (Default) o ) },\n { typeof (char), o => Create( (char) o ) },\n { typeof (StringBuilder), o => Create( (StringBuilder) o ) },\n { typeof (Variant[]), o => Create( (Variant[]) o ) },\n { typeof (Variant[,]), o => Create( (Variant[,]) o ) },\n { typeof (Variant[,,]), o => Create( (Variant[,,]) o ) },\n { typeof (Variant), o => (Variant) o },\n { typeof (byte), o => Create( (byte) o ) },\n { typeof (UIntPtr), o => Create( unchecked( (IntPtr) (long) (ulong) (UIntPtr) o ) ) },\n { typeof (Int16), o => Create( (Int16) o ) },\n { typeof (UInt16), o => Create( (UInt16) o ) }, {\n typeof (UInt32), o => {\n var uint32 = (UInt32) o;\n if ( uint32 > int.MaxValue\n ||\n uint32 < int.MinValue ) {\n return Create( uint32 );\n }\n return Create( (Int32) uint32 );\n }\n },\n { typeof (UInt64), o => Create( (Int64) (UInt64) o ) },\n { typeof (float), o => Create( (float) o ) }\n };\n\n #region explicit_operaotr\n public static implicit operator Int32( Variant a ) {\n return a.GetInt();\n }\n\n public static implicit operator Int64( Variant a ) {\n return a.GetInt64();\n }\n\n public static implicit operator Double( Variant a ) {\n return a.GetDouble();\n }\n\n public static implicit operator String( Variant a ) {\n return a.GetString();\n }\n\n public static implicit operator Boolean( Variant a ) {\n return a.GetBool();\n }\n\n public static implicit operator IntPtr( Variant a ) {\n return a.GetIntPtr();\n }\n\n public static implicit operator byte[]( Variant a ) {\n return a.GetBinary();\n }\n #endregion\n\n public abstract DataType DataType { get; }\n\n public virtual bool IsInt32 {\n get { return false; }\n }\n\n public virtual bool IsInt64 {\n get { return false; }\n }\n\n public virtual bool IsDouble {\n get { return false; }\n }\n\n public virtual bool IsBool {\n get { return false; }\n }\n\n public virtual bool IsString {\n get { return false; }\n }\n\n public virtual bool IsArray {\n get { return false; }\n }\n\n public virtual bool IsPtr {\n get { return false; }\n }\n\n public virtual bool IsStruct {\n get { return false; }\n }\n\n public virtual bool IsBinary {\n get { return false; }\n }\n\n public virtual bool IsDefault {\n get { return false; }\n }\n\n public virtual bool IsNull {\n get { return false; }\n }\n\n public virtual Variant this[ params int[] index ] {\n get { throw new AutoJITRuntimerException( \"\" ); }\n set { throw new AutoJITRuntimerException( \"\" ); }\n }\n\n public virtual IEnumerator GetEnumerator() {\n return new VariantEnumerator( (IEnumerable) GetValue() );\n }\n\n public static Variant Create( Int32 @int ) {\n return new Int32Variant( @int );\n }\n\n public static Variant Create( Int64 int64 ) {\n return new Int64Variant( int64 );\n }\n\n public static Variant Create( Double int64 ) {\n return new DoubleVariant( int64 );\n }\n\n public static Variant Create( Boolean @bool ) {\n return new BoolVariant( @bool );\n }\n\n public static Variant Create( String @string ) {\n return new StringVariant( @string );\n }\n\n public static Variant Create( StringBuilder @string ) {\n return new StringVariant( @string.ToString() );\n }\n\n public static Variant Create( Variant[] @array ) {\n return new ArrayVariant( array );\n }\n\n public static Variant Create( Variant[,] @array ) {\n return new ArrayVariant( array );\n }\n\n public static Variant Create( Variant[,,] @array ) {\n return new ArrayVariant( array );\n }\n\n public static Variant Create( IntPtr ptr ) {\n return new PtrVariant( ptr );\n }\n\n public static Variant Create( IRuntimeStruct @struct ) {\n return new StructVariant( @struct );\n }\n", "answers": [" public static Variant Create( byte[] binary ) {"], "length": 688, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "8f20b293-3be5-4684-ad49-e625b9470e90", "reasoning": "The class Variant defines many static Create overloads for different .NET types. The last defined overload in the snippet is for IRuntimeStruct. The next logical overload, based on the earlier CreateStrategies dictionary, is for byte[] (binary data). Therefore the next line should start the method that creates a Variant from a byte array.", "reasoning_model_answer": "public static Variant Create( byte[] @binary ) {", "assistant_with_reasoning": "\nThe class Variant defines many static Create overloads for different .NET types. The last defined overload in the snippet is for IRuntimeStruct. The next logical overload, based on the earlier CreateStrategies dictionary, is for byte[] (binary data). Therefore the next line should start the method that creates a Variant from a byte array.\n\npublic static Variant Create( byte[] @binary ) {", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.143, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 5502, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "public static Variant Create( byte[] @binary ) {", "score": 0.91, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "using System;\nusing System.IO;\nusing System.Collections.Generic;\nusing System.Drawing;\nusing System.Linq;\nusing System.Reflection;\nusing LeagueSharp;\nusing LeagueSharp.Common;\nusing SharpDX;\nusing SpellSlot = EloBuddy.SpellSlot;\n\nusing EloBuddy; \nusing LeagueSharp.Common; \nnamespace HERMES_Kalista.MyUtils\n{\n public class MActivator\n {\n public Menu Config = Program.ActivatorMenu;\n private AIHeroClient _player;\n private AIHeroClient target;\n //private StreamWriter log;\n private int checkCCTick;\n\n #region Items\n MItem qss = new MItem(\"Quicksilver Sash\", \"QSS\", \"qss\", 3140, ItemTypeId.Purifier);\n MItem mercurial = new MItem(\"ItemMercurial\", \"Mercurial\", \"mercurial\", 3139, ItemTypeId.Purifier);\n MItem bilgewater = new MItem(\"BilgewaterCutlass\", \"Bilgewater\", \"bilge\", 3144, ItemTypeId.Offensive, 450);\n MItem king = new MItem(\"ItemSwordOfFeastAndFamine\", \"BoRKing\", \"king\", 3153, ItemTypeId.Offensive, 450);\n MItem youmus = new MItem(\"YoumusBlade\", \"Youmuu's\", \"youmus\", 3142, ItemTypeId.Offensive);\n MItem hpPot = new MItem(\"Health Potion\", \"HP Pot\", \"hpPot\", 2003, ItemTypeId.HPRegenerator);\n MItem manaPot = new MItem(\"Mana Potion\", \"Mana Pot\", \"manaPot\", 2004, ItemTypeId.ManaRegenerator);\n MItem biscuit = new MItem(\"Total Biscuit of Rejuvenation\", \"Biscuit\", \"biscuit\", 2010, ItemTypeId.HPRegenerator);\n MItem cFlaskHP = new MItem(\"Crystalline Flask\", \"Cryst. Flask HP\", \"cFlaskHP\", 2041, ItemTypeId.HPRegenerator);\n MItem cFlaskMP = new MItem(\"Crystalline Flask\", \"Cryst. Flask MP\", \"cFlaskMP\", 2041, ItemTypeId.ManaRegenerator);\n #endregion\n\n #region SummonerSpells\n // Heal prioritizes the allied champion closest to the cursor at the time the ability is cast.\n // If no allied champions are near the cursor, Heal will target the most wounded allied champion in range.\n MItem heal = new MItem(\"Heal\", \"Heal\", \"SummonerHeal\", 0, ItemTypeId.DeffensiveSpell, 700); // 300? www.gamefaqs.com/pc/954437-league-of-legends/wiki/3-1-summoner-spells\n MItem exhaust = new MItem(\"Exhaust\", \"Exhaust\", \"SummonerExhaust\", 0, ItemTypeId.OffensiveSpell, 650); //summonerexhaust, low, debuff (buffs)\n MItem barrier = new MItem(\"Barrier\", \"Barrier\", \"SummonerBarrier\", 0, ItemTypeId.DeffensiveSpell);\n MItem cleanse = new MItem(\"Cleanse\", \"Cleanse\", \"SummonerBoost\", 0, ItemTypeId.PurifierSpell);\n MItem ignite = new MItem(\"Ignite\", \"Ignite\", \"SummonerDot\", 0, ItemTypeId.OffensiveSpell, 600);\n #endregion\n\n public MActivator()\n {\n onLoad(new EventArgs());\n }\n\n private void onLoad(EventArgs args)\n {\n try\n {\n _player = ObjectManager.Player;\n checkCCTick = LeagueSharp.Common.Utils.TickCount;\n createMenu();\n\n EloBuddy.Drawing.OnDraw += onDraw;\n Game.OnUpdate += onGameUpdate;\n Game.OnEnd += Game_OnGameEnd;\n }\n catch\n {\n Console.WriteLine(\"MasterActivator error creating menu!\");\n }\n }\n\n private void Game_OnGameEnd(GameEndEventArgs args)\n {\n //log.Close();\n }\n private void onDraw(EventArgs args)\n {\n try\n {\n if (Config.Item(\"drawStatus\").IsActive())\n {\n Drawing.DrawText(Drawing.Width - 120, 80, Config.Item(\"enabled\").IsActive() ? System.Drawing.Color.Green : System.Drawing.Color.Red, \"MActivator\");\n }\n }\n catch (Exception e)\n {\n Console.WriteLine(e);\n Console.WriteLine(\"Problem with MasterActivator(Drawing).\");\n }\n }\n\n private void onGameUpdate(EventArgs args)\n {\n if (Config.Item(\"enabled\").GetValue().Active)\n {\n try\n {\n if (!_player.InFountain() && !Config.Item(\"justPredHeal\").GetValue())\n {\n teamCheckAndUse(heal, Config.Item(\"useWithHealDebuff\").GetValue() ? \"\" : \"summonerhealcheck\");\n }\n\n checkAndUse(cleanse);\n checkAndUse(qss);\n checkAndUse(mercurial);\n\n checkAndUse(manaPot, \"FlaskOfCrystalWater\");\n checkAndUse(hpPot, \"RegenerationPotion\");\n checkAndUse(biscuit, \"ItemMiniRegenPotion\");\n checkAndUse(cFlaskHP, \"RegenerationPotion\");\n checkAndUse(cFlaskMP, \"FlaskOfCrystalWater\");\n\n if (!Config.Item(\"justPred\").GetValue() || !Config.Item(\"predict\").GetValue())\n {\n checkAndUse(barrier);\n }\n\n if (Config.Item(\"comboModeActive\").GetValue().Active)\n {\n combo();\n }\n }\n catch\n {\n /*Console.WriteLine(\"MasterActivator presented a problem, and has been disabled!\");\n Config.Item(\"enabled\").SetValue(new KeyBind('L', KeyBindType.Toggle, false)); // Check*/\n }\n }\n }\n\n private void combo()\n {\n checkAndUse(ignite);\n checkAndUse(youmus);\n checkAndUse(bilgewater);\n checkAndUse(king);\n }\n\n private bool checkBuff(String name)\n {\n var searchedBuff = from buff in _player.Buffs\n where buff.Name == name\n select buff;\n\n return searchedBuff.Count() > 0;\n }\n\n private void createMenuItem(MItem item, String parent, int defaultValue = 0, bool mana = false, int minManaPct = 0)\n {\n if (item.type == ItemTypeId.Ability || item.type == ItemTypeId.TeamAbility)\n {\n var abilitySlot = LeagueSharp.Common.Utility.GetSpellSlot(_player, item.name);\n if (abilitySlot != SpellSlot.Unknown && abilitySlot == item.abilitySlot)\n {\n var menu = new Menu(item.menuName, \"menu\" + item.menuVariable);\n menu.AddItem(new MenuItem(item.menuVariable, \"Enable\").SetValue(true));\n menu.AddItem(new MenuItem(item.menuVariable + \"UseOnPercent\", \"Use on HP%\")).SetValue(new Slider(defaultValue, 0, 100));\n if (minManaPct > 0)\n {\n menu.AddItem(new MenuItem(item.menuVariable + \"UseManaPct\", \"Min Mana%\")).SetValue(new Slider(minManaPct, 0, 100));\n }\n var menuUseAgainst = new Menu(\"Filter\", \"UseAgainst\");\n menuUseAgainst.AddItem(new MenuItem(\"tower\" + item.menuVariable, \"Tower\").SetValue(true));\n menuUseAgainst.AddItem(new MenuItem(\"ignite\" + item.menuVariable, \"Ignite\").SetValue(true));\n menuUseAgainst.AddItem(new MenuItem(\"king\" + item.menuVariable, \"BoRKing\").SetValue(false));\n menuUseAgainst.AddItem(new MenuItem(\"basic\" + item.menuVariable, \"Basic ATK\").SetValue(false));\n\n var enemyHero = from hero in ObjectManager.Get()\n where hero.Team != _player.Team\n select hero;\n\n if (enemyHero.Any())\n {\n foreach (AIHeroClient hero in enemyHero)\n {\n var menuUseAgainstHero = new Menu(hero.BaseSkinName, \"useAgainst\" + hero.BaseSkinName);\n menuUseAgainstHero.AddItem(new MenuItem(item.menuVariable + hero.BaseSkinName, \"Enabled\").SetValue(true));\n menuUseAgainstHero.AddItem(new MenuItem(SpellSlot.Q + item.menuVariable + hero.BaseSkinName, \"Q\").SetValue(false));\n menuUseAgainstHero.AddItem(new MenuItem(SpellSlot.W + item.menuVariable + hero.BaseSkinName, \"W\").SetValue(false));\n menuUseAgainstHero.AddItem(new MenuItem(SpellSlot.E + item.menuVariable + hero.BaseSkinName, \"E\").SetValue(false));\n menuUseAgainstHero.AddItem(new MenuItem(SpellSlot.R + item.menuVariable + hero.BaseSkinName, \"R\").SetValue(false));\n menuUseAgainstHero.AddItem(new MenuItem(\"ignore\" + item.menuVariable + hero.BaseSkinName, \"Ignore %HP\").SetValue(true));\n menuUseAgainst.AddSubMenu(menuUseAgainstHero);\n // Bring all, passives, summoners spells, etc;\n /*if (hero.Spellbook.Spells.Count() > 0)\n {\n var menuUseAgainstHero = new Menu(hero.BaseSkinName, \"useAgainst\" + hero.BaseSkinName);\n menuUseAgainstHero.AddItem(new MenuItem(item.menuVariable, \"Enable\").SetValue(true));\n foreach(SpellDataInst spell in hero.Spellbook.Spells)\n {\n menuUseAgainstHero.AddItem(new MenuItem(\"useAgainstSpell\" + spell.Name, spell.Name).SetValue(true));\n }\n menuUseAgainst.AddSubMenu(menuUseAgainstHero);\n }\n else\n {\n Console.WriteLine(\"MasterActivator cant get \" + hero.BaseSkinName + \" spells!\");\n }*/\n }\n }\n menu.AddSubMenu(menuUseAgainst);\n Config.SubMenu(parent).AddSubMenu(menu);\n }\n }\n else if (item.type == ItemTypeId.KSAbility)\n {\n var abilitySlot = LeagueSharp.Common.Utility.GetSpellSlot(_player, item.name);\n if (abilitySlot != SpellSlot.Unknown && abilitySlot == item.abilitySlot)\n {\n var ksAbMenu = new Menu(item.menuName, \"menu\" + item.menuVariable);\n ksAbMenu.AddItem(new MenuItem(item.menuVariable, \"Enable\").SetValue(true));\n //choRMenu.AddItem(new MenuItem(choR.menuVariable + \"plus\", \"Plus\").SetValue(false));\n ksAbMenu.AddItem(new MenuItem(item.menuVariable + \"drawRange\", \"Draw Range\").SetValue(true));\n ksAbMenu.AddItem(new MenuItem(item.menuVariable + \"drawBar\", \"Draw Bar\").SetValue(true));\n Config.SubMenu(parent).AddSubMenu(ksAbMenu);\n }\n }\n else\n {", "answers": [" var menu = new Menu(item.menuName, \"menu\" + item.menuVariable);"], "length": 718, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "42b744ac-3df3-4178-b6a4-01155426450b", "reasoning": "The method createMenuItem handles different item types. After the specific branches for Ability and KSAbility, the else block handles generic items. The next logical line is to create a new Menu instance for these items, similar to the earlier branches. Therefore the next line should instantiate a Menu with the item's name and variable.", "reasoning_model_answer": "var menu = new Menu(item.menuName, \"menu\" + item.menuVariable);", "assistant_with_reasoning": "\nThe method createMenuItem handles different item types. After the specific branches for Ability and KSAbility, the else block handles generic items. The next logical line is to create a new Menu instance for these items, similar to the earlier branches. Therefore the next line should instantiate a Menu with the item's name and variable.\n\nvar menu = new Menu(item.menuName, \"menu\" + item.menuVariable);", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.087, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 11013, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "var menu = new Menu(item.menuName, \"menu\" + item.menuVariable);", "score": 0.89, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/*\n Licensed to the Apache Software Foundation (ASF) under one or more\n contributor license agreements. See the NOTICE file distributed with\n this work for additional information regarding copyright ownership.\n The ASF licenses this file to You under the Apache License, Version 2.0\n (the \"License\"); you may not use this file except in compliance with\n the License. You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n */\nusing java.lang;\nusing org.objectweb.asm;\n\nnamespace stab.reflection {\n \n public abstract class Instruction {\n final static Instruction Aaload = new SimpleInstruction(Opcode.Aaload);\n final static Instruction Aastore = new SimpleInstruction(Opcode.Aastore);\n final static Instruction Aconst_Null = new SimpleInstruction(Opcode.Aconst_Null);\n final static Instruction Areturn = new SimpleInstruction(Opcode.Areturn);\n final static Instruction Arraylength = new SimpleInstruction(Opcode.Arraylength);\n final static Instruction Athrow = new SimpleInstruction(Opcode.Athrow);\n final static Instruction Baload = new SimpleInstruction(Opcode.Baload);\n final static Instruction Bastore = new SimpleInstruction(Opcode.Bastore);\n final static Instruction Caload = new SimpleInstruction(Opcode.Caload);\n final static Instruction Castore = new SimpleInstruction(Opcode.Castore);\n final static Instruction D2f = new SimpleInstruction(Opcode.D2f);\n final static Instruction D2i = new SimpleInstruction(Opcode.D2i);\n final static Instruction D2l = new SimpleInstruction(Opcode.D2l);\n final static Instruction Dadd = new SimpleInstruction(Opcode.Dadd);\n final static Instruction Daload = new SimpleInstruction(Opcode.Daload);\n final static Instruction Dastore = new SimpleInstruction(Opcode.Dastore);\n final static Instruction Dcmpg = new SimpleInstruction(Opcode.Dcmpg);\n final static Instruction Dcmpl = new SimpleInstruction(Opcode.Dcmpl);\n final static Instruction Dconst_0 = new SimpleInstruction(Opcode.Dconst_0);\n final static Instruction Dconst_1 = new SimpleInstruction(Opcode.Dconst_1);\n final static Instruction Ddiv = new SimpleInstruction(Opcode.Ddiv);\n final static Instruction Dmul = new SimpleInstruction(Opcode.Dmul);\n final static Instruction Dneg = new SimpleInstruction(Opcode.Dneg);\n final static Instruction Drem = new SimpleInstruction(Opcode.Drem);\n final static Instruction Dreturn = new SimpleInstruction(Opcode.Dreturn);\n final static Instruction Dsub = new SimpleInstruction(Opcode.Dsub);\n final static Instruction Dup = new SimpleInstruction(Opcode.Dup);\n final static Instruction Dup_X1 = new SimpleInstruction(Opcode.Dup_X1);\n final static Instruction Dup_X2 = new SimpleInstruction(Opcode.Dup_X2);\n final static Instruction Dup2 = new SimpleInstruction(Opcode.Dup2);\n final static Instruction Dup2_X1 = new SimpleInstruction(Opcode.Dup2_X1);\n final static Instruction Dup2_X2 = new SimpleInstruction(Opcode.Dup2_X2);\n final static Instruction F2d = new SimpleInstruction(Opcode.F2d);\n final static Instruction F2i = new SimpleInstruction(Opcode.F2i);\n final static Instruction F2l = new SimpleInstruction(Opcode.F2l);\n final static Instruction Fadd = new SimpleInstruction(Opcode.Fadd);\n final static Instruction Faload = new SimpleInstruction(Opcode.Faload);\n final static Instruction Fastore = new SimpleInstruction(Opcode.Fastore);\n final static Instruction Fcmpg = new SimpleInstruction(Opcode.Fcmpg);\n final static Instruction Fcmpl = new SimpleInstruction(Opcode.Fcmpl);\n final static Instruction Fconst_0 = new SimpleInstruction(Opcode.Fconst_0);\n final static Instruction Fconst_1 = new SimpleInstruction(Opcode.Fconst_1);\n final static Instruction Fconst_2 = new SimpleInstruction(Opcode.Fconst_2);\n final static Instruction Fdiv = new SimpleInstruction(Opcode.Fdiv);\n final static Instruction Fmul = new SimpleInstruction(Opcode.Fmul);\n final static Instruction Fneg = new SimpleInstruction(Opcode.Fneg);\n final static Instruction Frem = new SimpleInstruction(Opcode.Frem);\n final static Instruction Freturn = new SimpleInstruction(Opcode.Freturn);\n final static Instruction Fsub = new SimpleInstruction(Opcode.Fsub);\n final static Instruction I2b = new SimpleInstruction(Opcode.I2b);\n final static Instruction I2c = new SimpleInstruction(Opcode.I2c);\n final static Instruction I2d = new SimpleInstruction(Opcode.I2d);\n final static Instruction I2f = new SimpleInstruction(Opcode.I2f);\n final static Instruction I2l = new SimpleInstruction(Opcode.I2l);\n final static Instruction I2s = new SimpleInstruction(Opcode.I2s);\n final static Instruction Iadd = new SimpleInstruction(Opcode.Iadd);\n final static Instruction Iaload = new SimpleInstruction(Opcode.Iaload);\n final static Instruction Iand = new SimpleInstruction(Opcode.Iand);\n final static Instruction Iastore = new SimpleInstruction(Opcode.Iastore);\n final static Instruction Iconst_0 = new SimpleInstruction(Opcode.Iconst_0);\n final static Instruction Iconst_1 = new SimpleInstruction(Opcode.Iconst_1);\n final static Instruction Iconst_2 = new SimpleInstruction(Opcode.Iconst_2);\n final static Instruction Iconst_3 = new SimpleInstruction(Opcode.Iconst_3);\n final static Instruction Iconst_4 = new SimpleInstruction(Opcode.Iconst_4);\n final static Instruction Iconst_5 = new SimpleInstruction(Opcode.Iconst_5);\n final static Instruction Iconst_M1 = new SimpleInstruction(Opcode.Iconst_M1);\n final static Instruction Idiv = new SimpleInstruction(Opcode.Idiv);\n final static Instruction Imul = new SimpleInstruction(Opcode.Imul);\n final static Instruction Ineg = new SimpleInstruction(Opcode.Ineg);\n final static Instruction Ior = new SimpleInstruction(Opcode.Ior);\n final static Instruction Irem = new SimpleInstruction(Opcode.Irem);\n final static Instruction Ireturn = new SimpleInstruction(Opcode.Ireturn);\n final static Instruction Ishl = new SimpleInstruction(Opcode.Ishl);\n final static Instruction Ishr = new SimpleInstruction(Opcode.Ishr);\n final static Instruction Isub = new SimpleInstruction(Opcode.Isub);\n final static Instruction Iushr = new SimpleInstruction(Opcode.Iushr);\n final static Instruction Ixor = new SimpleInstruction(Opcode.Ixor);\n final static Instruction L2d = new SimpleInstruction(Opcode.L2d);\n final static Instruction L2f = new SimpleInstruction(Opcode.L2f);\n final static Instruction L2i = new SimpleInstruction(Opcode.L2i);\n final static Instruction Ladd = new SimpleInstruction(Opcode.Ladd);\n final static Instruction Laload = new SimpleInstruction(Opcode.Laload);", "answers": [" final static Instruction Land = new SimpleInstruction(Opcode.Land);"], "length": 705, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "5fcd03f4-4779-48b1-847a-662288caa42a", "reasoning": "The class defines static Instruction fields for each JVM opcode in a roughly alphabetical grouping. After the last shown line 'final static Instruction Laload = new SimpleInstruction(Opcode.Laload);' the next opcode in the sequence is Lastore, which stores a long into an array. Following the established pattern, the next line should declare the Lastore field similarly.", "reasoning_model_answer": "final static Instruction Lastore = new SimpleInstruction(Opcode.Lastore);", "assistant_with_reasoning": "\nThe class defines static Instruction fields for each JVM opcode in a roughly alphabetical grouping. After the last shown line 'final static Instruction Laload = new SimpleInstruction(Opcode.Laload);' the next opcode in the sequence is Lastore, which stores a long into an array. Following the established pattern, the next line should declare the Lastore field similarly.\n\nfinal static Instruction Lastore = new SimpleInstruction(Opcode.Lastore);", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 6.597, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 7452, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "final static Instruction Lastore = new SimpleInstruction(Opcode.Lastore);", "score": 0.85, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/*\n* Farseer Physics Engine:\n* Copyright (c) 2012 Ian Qvist\n* \n* Original source Box2D:\n* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org \n* \n* This software is provided 'as-is', without any express or implied \n* warranty. In no event will the authors be held liable for any damages \n* arising from the use of this software. \n* Permission is granted to anyone to use this software for any purpose, \n* including commercial applications, and to alter it and redistribute it \n* freely, subject to the following restrictions: \n* 1. The origin of this software must not be misrepresented; you must not \n* claim that you wrote the original software. If you use this software \n* in a product, an acknowledgment in the product documentation would be \n* appreciated but is not required. \n* 2. Altered source versions must be plainly marked as such, and must not be \n* misrepresented as being the original software. \n* 3. This notice may not be removed or altered from any source distribution. \n*/\n//#define USE_ACTIVE_CONTACT_SET\n\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing FarseerPhysics.Collision;\nusing FarseerPhysics.Collision.Shapes;\nusing FarseerPhysics.Common;\nusing Microsoft.Xna.Framework;\n\n\nnamespace FarseerPhysics.Dynamics.Contacts\n{\n\t/// \n\t/// A contact edge is used to connect bodies and contacts together\n\t/// in a contact graph where each body is a node and each contact\n\t/// is an edge. A contact edge belongs to a doubly linked list\n\t/// maintained in each attached body. Each contact has two contact\n\t/// nodes, one for each attached body.\n\t/// \n\tpublic sealed class ContactEdge\n\t{\n\t\t/// \n\t\t/// The contact\n\t\t/// \n\t\tpublic Contact contact;\n\n\t\t/// \n\t\t/// The next contact edge in the body's contact list\n\t\t/// \n\t\tpublic ContactEdge next;\n\n\t\t/// \n\t\t/// Provides quick access to the other body attached.\n\t\t/// \n\t\tpublic Body other;\n\n\t\t/// \n\t\t/// The previous contact edge in the body's contact list\n\t\t/// \n\t\tpublic ContactEdge prev;\n\t}\n\n\t/// \n\t/// The class manages contact between two shapes. A contact exists for each overlapping\n\t/// AABB in the broad-phase (except if filtered). Therefore a contact object may exist\n\t/// that has no contact points.\n\t/// \n\tpublic class Contact\n\t{\n\t\t#region Properties/Fields\n\n\t\tpublic Fixture fixtureA;\n\t\tpublic Fixture fixtureB;\n\t\tpublic float friction;\n\t\tpublic float restitution;\n\n\t\t/// \n\t\t/// Get the contact manifold. Do not modify the manifold unless you understand the internals of Box2D.\n\t\t/// \n\t\tpublic Manifold manifold;\n\n\t\t/// Get or set the desired tangent speed for a conveyor belt behavior. In meters per second.\n\t\tpublic float tangentSpeed;\n\n\t\t/// \n\t\t/// Enable/disable this contact. This can be used inside the pre-solve contact listener. The contact is only disabled for the current\n\t\t/// time step (or sub-step in continuous collisions).\n\t\t/// NOTE: If you are setting Enabled to a constant true or false, use the explicit Enable() or Disable() functions instead to \n\t\t/// save the CPU from doing a branch operation.\n\t\t/// \n\t\tpublic bool enabled;\n\n\t\t/// \n\t\t/// Get the child primitive index for fixture A.\n\t\t/// \n\t\t/// The child index A.\n\t\tpublic int childIndexA { get; internal set; }\n\n\t\t/// \n\t\t/// Get the child primitive index for fixture B.\n\t\t/// \n\t\t/// The child index B.\n\t\tpublic int childIndexB { get; internal set; }\n\n\t\t/// \n\t\t/// Determines whether this contact is touching.\n\t\t/// \n\t\t/// \n\t\t/// \ttrue if this instance is touching; otherwise, false.\n\t\t/// \n\t\tpublic bool isTouching { get; set; }\n\n\t\tinternal bool islandFlag;\n\t\tinternal bool toiFlag;\n\t\tinternal bool filterFlag;\n\n\t\tContactType _type;\n\n\t\tstatic EdgeShape _edge = new EdgeShape();\n\n\t\tstatic ContactType[,] _contactRegisters = new[,]\n\t\t\t\t\t\t\t\t\t\t\t\t\t {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t ContactType.Circle,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t ContactType.EdgeAndCircle,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t ContactType.PolygonAndCircle,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t ContactType.ChainAndCircle,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t },\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t ContactType.EdgeAndCircle,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t ContactType.NotSupported,\n // 1,1 is invalid (no ContactType.Edge)\n ContactType.EdgeAndPolygon,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t ContactType.NotSupported,\n // 1,3 is invalid (no ContactType.EdgeAndLoop)\n },\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t ContactType.PolygonAndCircle,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t ContactType.EdgeAndPolygon,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t ContactType.Polygon,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t ContactType.ChainAndPolygon,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t },\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t ContactType.ChainAndCircle,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t ContactType.NotSupported,\n // 3,1 is invalid (no ContactType.EdgeAndLoop)\n ContactType.ChainAndPolygon,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t ContactType.NotSupported,\n // 3,3 is invalid (no ContactType.Loop)\n },\n\t\t\t\t\t\t\t\t\t\t\t\t\t };\n\t\t// Nodes for connecting bodies.\n\t\tinternal ContactEdge _nodeA = new ContactEdge();\n\t\tinternal ContactEdge _nodeB = new ContactEdge();\n\t\tinternal int _toiCount;\n\t\tinternal float _toi;\n\n\t\t#endregion\n\n\n\t\tContact( Fixture fA, int indexA, Fixture fB, int indexB )\n\t\t{\n\t\t\treset( fA, indexA, fB, indexB );\n\t\t}\n\n\t\tpublic void resetRestitution()\n\t\t{\n\t\t\trestitution = Settings.mixRestitution( fixtureA.restitution, fixtureB.restitution );\n\t\t}\n\n\t\tpublic void resetFriction()\n\t\t{\n\t\t\tfriction = Settings.mixFriction( fixtureA.friction, fixtureB.friction );\n\t\t}\n\n\t\t/// \n\t\t/// Gets the world manifold.\n\t\t/// \n\t\tpublic void getWorldManifold( out Vector2 normal, out FixedArray2 points )\n\t\t{\n\t\t\tvar bodyA = fixtureA.body;\n\t\t\tvar bodyB = fixtureB.body;\n\t\t\tvar shapeA = fixtureA.shape;\n\t\t\tvar shapeB = fixtureB.shape;\n\n\t\t\tContactSolver.WorldManifold.initialize( ref manifold, ref bodyA._xf, shapeA.radius, ref bodyB._xf, shapeB.radius, out normal, out points );\n\t\t}\n\n\t\tvoid reset( Fixture fA, int indexA, Fixture fB, int indexB )\n\t\t{\n\t\t\tenabled = true;", "answers": ["\t\t\tisTouching = false;"], "length": 771, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "edba7ef6-cdb9-4c6b-aefa-a049158cb0d8", "reasoning": "We are inside the reset method of Contact. After setting enabled = true, the next step is to clear the touching flag for a fresh contact, so we set isTouching = false.", "reasoning_model_answer": "isTouching = false;", "assistant_with_reasoning": "\nWe are inside the reset method of Contact. After setting enabled = true, the next step is to clear the touching flag for a fresh contact, so we set isTouching = false.\n\nisTouching = false;", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 6.272, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 6637, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "isTouching = false;", "score": 0.93, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/**\n * Copyright (c) 2015 Source Auditor Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n*/\npackage org.spdx.spdxspreadsheet;\n\nimport java.text.DateFormat;\nimport java.text.ParseException;\nimport java.text.SimpleDateFormat;\nimport java.util.Arrays;\nimport java.util.Date;\n\nimport org.apache.poi.ss.usermodel.Cell;\nimport org.apache.poi.ss.usermodel.CellStyle;\nimport org.apache.poi.ss.usermodel.CellType;\nimport org.apache.poi.ss.usermodel.Row;\nimport org.apache.poi.ss.usermodel.Sheet;\nimport org.apache.poi.ss.usermodel.Workbook;\nimport org.spdx.rdfparser.InvalidSPDXAnalysisException;\nimport org.spdx.rdfparser.SPDXCreatorInformation;\nimport org.spdx.rdfparser.SpdxRdfConstants;\nimport org.spdx.rdfparser.license.AnyLicenseInfo;\nimport org.spdx.rdfparser.license.SimpleLicensingInfo;\nimport org.spdx.rdfparser.model.Checksum;\nimport org.spdx.rdfparser.model.ExternalDocumentRef;\nimport org.spdx.rdfparser.model.SpdxDocument;\nimport org.spdx.rdfparser.model.SpdxItem;\nimport org.spdx.tag.BuildDocument;\nimport org.spdx.tag.InvalidSpdxTagFileException;\n\n/**\n * @author Gary\n *\n */\npublic class OriginsSheetV2d0 extends DocumentInfoSheet {\n\n\tstatic final int NUM_COLS = 14;\n\tstatic final int SPDX_VERSION_COL = SPREADSHEET_VERSION_COL + 1;\n\tstatic final int DATA_LICENSE_COL = SPDX_VERSION_COL + 1;\n\tstatic final int SPDX_ID_COL = DATA_LICENSE_COL + 1;\n\tstatic final int LICENSE_LIST_VERSION_COL = SPDX_ID_COL + 1;\n\tstatic final int DOCUMENT_NAME_COL = LICENSE_LIST_VERSION_COL + 1;\n\tstatic final int NAMESPACE_COL = DOCUMENT_NAME_COL + 1;\n\tstatic final int DOCUMENT_DESCRIBES_COL = NAMESPACE_COL + 1;\n\tstatic final int EXTERNAL_DOC_REFS_COL = DOCUMENT_DESCRIBES_COL + 1;\n\tstatic final int DOCUMENT_COMMENT_COL = EXTERNAL_DOC_REFS_COL + 1;\n\tstatic final int CREATED_BY_COL = DOCUMENT_COMMENT_COL + 1;\n\tstatic final int CREATED_COL = CREATED_BY_COL + 1;\n\tstatic final int AUTHOR_COMMENTS_COL = CREATED_COL + 1;\n\tstatic final int USER_DEFINED_COL = AUTHOR_COMMENTS_COL + 1;\n\n\tstatic final boolean[] REQUIRED = new boolean[] {true, true, true, true,\n\t\tfalse, true, true, true, false, false, true, true, false, false};\n\n\tstatic final String[] HEADER_TITLES = new String[] {\"Spreadsheet Version\",\n\t\t\"SPDX Version\", \"Data License\", \"SPDX Identifier\", \"License List Version\",\n\t\t\"Document Name\", \"Document Namespace\", \"Document Contents\",\n\t\t\"External Document References\", \"Document Comment\", \"Creator\", \"Created\",\n\t\t\"Creator Comment\", \"Optional User Defined Columns...\"};\n\tstatic final int[] COLUMN_WIDTHS = new int[] {20, 16, 20, 20, 16, 40, 80,\n\t\t50, 140, 70, 60, 20, 70, 60};\n\tstatic final boolean[] LEFT_WRAP = new boolean[] {false, false, false, false,\n\t\tfalse, true, true, true, true, true, true, false, true, true};\n\tstatic final boolean[] CENTER_NOWRAP = new boolean[] {true, true, true, true,\n\t\ttrue, false, false, false, false, false, false, true, false, false};\n\n\tpublic OriginsSheetV2d0(Workbook workbook, String sheetName, String version) {\n\t\tsuper(workbook, sheetName, version);\n\t}\n\n\n\t@Override\n\tpublic String verify() {\n\t\ttry {\n\t\t\tif (sheet == null) {\n\t\t\t\treturn \"Worksheet for SPDX Origins does not exist\";\n\t\t\t}\n\t\t\t// validate version\n\t\t\tversion = getDataCellStringValue(SPREADSHEET_VERSION_COL);\n\t\t\tif (version == null) {\n\t\t\t\treturn \"Invalid origins spreadsheet - no spreadsheet version found\";\n\t\t\t}\n\n\t\t\tif (!SPDXSpreadsheet.verifyVersion(version)) {\n\t\t\t\treturn \"Spreadsheet version \"+version+\" not supported.\";\n\t\t\t}\n\t\t\tRow firstRow = sheet.getRow(firstRowNum);\n\t\t\tfor (int i = 0; i < NUM_COLS-1; i++) {\t// don't check the last col - which is the user defined column\n\t\t\t\tCell cell = firstRow.getCell(i+firstCellNum);\n\t\t\t\tif (cell == null ||\n\t\t\t\t\t\tcell.getStringCellValue() == null ||\n\t\t\t\t\t\t!cell.getStringCellValue().equals(HEADER_TITLES[i])) {\n\t\t\t\t\treturn \"Column \"+HEADER_TITLES[i]+\" missing for SPDX Origins worksheet\";\n\t\t\t\t}\n\t\t\t}\n\t\t\t// validate rows\n\t\t\tboolean done = false;\n\t\t\tint rowNum = firstRowNum + 1;\n\t\t\twhile (!done) {\n\t\t\t\tRow row = sheet.getRow(rowNum);\n\t\t\t\tif (row == null || row.getCell(SPDX_VERSION_COL) == null) {\n\t\t\t\t\tdone = true;\n\t\t\t\t} else {\n\t\t\t\t\tString error = validateRow(row);\n\t\t\t\t\tif (error != null) {\n\t\t\t\t\t\treturn error;\n\t\t\t\t\t}\n\t\t\t\t\trowNum++;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn null;\n\t\t} catch (Exception ex) {\n\t\t\treturn \"Error in verifying SPDX Origins work sheet: \"+ex.getMessage();\n\t\t}\n\t}\n\n\t@SuppressWarnings(\"deprecation\")\n\tprivate String validateRow(Row row) {\n\t\tfor (int i = 0; i < NUM_COLS; i++) {\n\t\t\tCell cell = row.getCell(i);\n\t\t\tif (cell == null) {\n\t\t\t\tif (REQUIRED[i]) {\n\t\t\t\t\treturn \"Required cell \"+HEADER_TITLES[i]+\" missing for row \"+String.valueOf(row.getRowNum()+\" in Origins Spreadsheet\");\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif (i == CREATED_COL) {\n\t\t\t\t\tif (!(cell.getCellTypeEnum() == CellType.NUMERIC)) {\n\t\t\t\t\t\treturn \"Created column in origin spreadsheet is not of type Date\";\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\tpublic static void create(Workbook wb, String sheetName) {\n\t\tint sheetNum = wb.getSheetIndex(sheetName);\n\t\tif (sheetNum >= 0) {\n\t\t\twb.removeSheetAt(sheetNum);\n\t\t}\n\n\t\tCellStyle headerStyle = AbstractSheet.createHeaderStyle(wb);\n\t\tCellStyle centerStyle = AbstractSheet.createCenterStyle(wb);\n\t\tCellStyle wrapStyle = AbstractSheet.createLeftWrapStyle(wb);\n\t\tSheet sheet = wb.createSheet(sheetName);\n\t\tRow row = sheet.createRow(0);\n\t\tfor (int i = 0; i < HEADER_TITLES.length; i++) {\n\t\t\tsheet.setColumnWidth(i, COLUMN_WIDTHS[i]*256);\n\t\t\tif (LEFT_WRAP[i]) {\n\t\t\t\tsheet.setDefaultColumnStyle(i, wrapStyle);\n\t\t\t} else if (CENTER_NOWRAP[i]) {\n\t\t\t\tsheet.setDefaultColumnStyle(i, centerStyle);\n\t\t\t}\n\t\t\tCell cell = row.createCell(i);\n\t\t\tcell.setCellStyle(headerStyle);\n\t\t\tcell.setCellValue(HEADER_TITLES[i]);\n\t\t}\n\t\tRow dataRow = sheet.createRow(1);\n\t\tCell ssVersionCell = dataRow.createCell(SPREADSHEET_VERSION_COL);\n\t\tssVersionCell.setCellValue(SPDXSpreadsheet.CURRENT_VERSION);\n\t}\n\n\n\n\tpublic void setAuthorComments(String comments) {\n\t\tsetDataCellStringValue(AUTHOR_COMMENTS_COL, comments);\n\t}\n\n\tpublic void setCreatedBy(String createdBy) {\n\t\tsetDataCellStringValue(CREATED_BY_COL, createdBy);\n\t}\n\n\tpublic void setDataLicense(String dataLicense) {\n\t\tsetDataCellStringValue(DATA_LICENSE_COL, dataLicense);\n\t}\n\n\tpublic void setSPDXVersion(String version) {\n\t\tsetDataCellStringValue(SPDX_VERSION_COL, version);\n\t}\n\n\tpublic void setSpreadsheetVersion(String version) {\n\t\tsetDataCellStringValue(SPREADSHEET_VERSION_COL, version);\n\t}\n\n\tpublic String getAuthorComments() {", "answers": ["\t\treturn getDataCellStringValue(AUTHOR_COMMENTS_COL);"], "length": 774, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "8d93a866-a090-4951-af84-b25553aaaa58", "reasoning": "The method getAuthorComments() should retrieve the string stored in the AUTHOR_COMMENTS_COL column. Similar setter methods use setDataCellStringValue, and getters in this class likely call getDataCellStringValue with the appropriate column constant. Therefore the next line returns that value.", "reasoning_model_answer": "return getDataCellStringValue(AUTHOR_COMMENTS_COL);", "assistant_with_reasoning": "\nThe method getAuthorComments() should retrieve the string stored in the AUTHOR_COMMENTS_COL column. Similar setter methods use setDataCellStringValue, and getters in this class likely call getDataCellStringValue with the appropriate column constant. Therefore the next line returns that value.\n\nreturn getDataCellStringValue(AUTHOR_COMMENTS_COL);", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 2.171, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 7029, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "return getDataCellStringValue(AUTHOR_COMMENTS_COL);", "score": 0.98, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/*\n * Licensed to GraphHopper GmbH under one or more contributor\n * license agreements. See the NOTICE file distributed with this work for\n * additional information regarding copyright ownership.\n *\n * GraphHopper GmbH licenses this file to you under the Apache License,\n * Version 2.0 (the \"License\"); you may not use this file except in\n * compliance with the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.graphhopper.jsprit.core.algorithm.box;\n\nimport com.graphhopper.jsprit.core.algorithm.PrettyAlgorithmBuilder;\nimport com.graphhopper.jsprit.core.algorithm.SearchStrategy;\nimport com.graphhopper.jsprit.core.algorithm.VehicleRoutingAlgorithm;\nimport com.graphhopper.jsprit.core.algorithm.acceptor.SchrimpfAcceptance;\nimport com.graphhopper.jsprit.core.algorithm.acceptor.SolutionAcceptor;\nimport com.graphhopper.jsprit.core.algorithm.listener.AlgorithmEndsListener;\nimport com.graphhopper.jsprit.core.algorithm.listener.IterationStartsListener;\nimport com.graphhopper.jsprit.core.algorithm.module.RuinAndRecreateModule;\nimport com.graphhopper.jsprit.core.algorithm.recreate.*;\nimport com.graphhopper.jsprit.core.algorithm.ruin.*;\nimport com.graphhopper.jsprit.core.algorithm.ruin.distance.AvgServiceAndShipmentDistance;\nimport com.graphhopper.jsprit.core.algorithm.selector.SelectBest;\nimport com.graphhopper.jsprit.core.algorithm.state.StateManager;\nimport com.graphhopper.jsprit.core.problem.VehicleRoutingProblem;\nimport com.graphhopper.jsprit.core.problem.constraint.ConstraintManager;\nimport com.graphhopper.jsprit.core.problem.job.Job;\nimport com.graphhopper.jsprit.core.problem.solution.SolutionCostCalculator;\nimport com.graphhopper.jsprit.core.problem.solution.VehicleRoutingProblemSolution;\nimport com.graphhopper.jsprit.core.problem.solution.route.VehicleRoute;\nimport com.graphhopper.jsprit.core.problem.solution.route.activity.BreakActivity;\nimport com.graphhopper.jsprit.core.problem.solution.route.activity.TourActivity;\nimport com.graphhopper.jsprit.core.problem.vehicle.FiniteFleetManagerFactory;\nimport com.graphhopper.jsprit.core.problem.vehicle.InfiniteFleetManagerFactory;\nimport com.graphhopper.jsprit.core.problem.vehicle.VehicleFleetManager;\nimport com.graphhopper.jsprit.core.util.NoiseMaker;\nimport com.graphhopper.jsprit.core.util.RandomNumberGeneration;\nimport com.graphhopper.jsprit.core.util.Solutions;\n\nimport java.util.*;\nimport java.util.concurrent.ExecutorService;\nimport java.util.concurrent.Executors;\n\n\npublic class Jsprit {\n\n private final ActivityInsertionCostsCalculator activityInsertion;\n\n public enum Construction {\n\n BEST_INSERTION(\"best_insertion\"), REGRET_INSERTION(\"regret_insertion\");\n\n String name;\n\n Construction(String name) {\n this.name = name;\n }\n\n public String toString() {\n return name;\n }\n\n }\n\n public enum Strategy {\n\n RADIAL_BEST(\"radial_best\"),\n RADIAL_REGRET(\"radial_regret\"),\n RANDOM_BEST(\"random_best\"),\n RANDOM_REGRET(\"random_regret\"),\n WORST_BEST(\"worst_best\"),\n WORST_REGRET(\"worst_regret\"),\n CLUSTER_BEST(\"cluster_best\"),\n CLUSTER_REGRET(\"cluster_regret\"),\n STRING_BEST(\"string_best\"),\n STRING_REGRET(\"string_regret\");\n\n String strategyName;\n\n Strategy(String strategyName) {\n this.strategyName = strategyName;\n }\n\n public String toString() {\n return strategyName;\n }\n }\n\n public enum Parameter {\n\n FIXED_COST_PARAM(\"fixed_cost_param\"), VEHICLE_SWITCH(\"vehicle_switch\"), REGRET_TIME_WINDOW_SCORER(\"regret.tw_scorer\"),\n REGRET_DISTANCE_SCORER(\"regret.distance_scorer\"), INITIAL_THRESHOLD(\"initial_threshold\"), ITERATIONS(\"iterations\"),\n THREADS(\"threads\"),\n RANDOM_REGRET_MIN_SHARE(\"random_regret.min_share\"),\n RANDOM_REGRET_MAX_SHARE(\"random_regret.max_share\"),\n RANDOM_BEST_MIN_SHARE(\"random_best.min_share\"),\n RANDOM_BEST_MAX_SHARE(\"random_best.max_share\"),\n RADIAL_MIN_SHARE(\"radial.min_share\"),\n RADIAL_MAX_SHARE(\"radial.max_share\"),\n CLUSTER_MIN_SHARE(\"cluster.min_share\"),\n CLUSTER_MAX_SHARE(\"cluster.max_share\"),\n WORST_MIN_SHARE(\"worst.min_share\"),\n WORST_MAX_SHARE(\"worst.max_share\"),\n THRESHOLD_ALPHA(\"threshold.alpha\"),\n THRESHOLD_INI(\"threshold.ini\"),\n THRESHOLD_INI_ABS(\"threshold.ini_abs\"),\n INSERTION_NOISE_LEVEL(\"insertion.noise_level\"),\n INSERTION_NOISE_PROB(\"insertion.noise_prob\"),\n RUIN_WORST_NOISE_LEVEL(\"worst.noise_level\"),\n RUIN_WORST_NOISE_PROB(\"worst.noise_prob\"),\n FAST_REGRET(\"regret.fast\"),\n MAX_TRANSPORT_COSTS(\"max_transport_costs\"),\n CONSTRUCTION(\"construction\"),\n BREAK_SCHEDULING(\"break_scheduling\"),\n STRING_K_MIN(\"string_kmin\"),\n STRING_K_MAX(\"string_kmax\"),\n STRING_L_MIN(\"string_lmin\"),\n STRING_L_MAX(\"string_lmax\");\n\n\n String paraName;\n\n Parameter(String name) {\n this.paraName = name;\n }\n\n public String toString() {\n return paraName;\n }\n\n }\n\n public static VehicleRoutingAlgorithm createAlgorithm(VehicleRoutingProblem vehicleRoutingProblem) {\n return Jsprit.Builder.newInstance(vehicleRoutingProblem).buildAlgorithm();\n }\n\n public static class Builder {\n\n private VehicleRoutingProblem vrp;\n\n private ExecutorService es;\n\n private Integer noThreads;\n\n private StateManager stateManager = null;\n\n private ConstraintManager constraintManager = null;\n\n private SolutionCostCalculator objectiveFunction = null;\n\n private Properties properties;\n\n private boolean addConstraints = true;\n\n private Random random = RandomNumberGeneration.newInstance();\n\n private ActivityInsertionCostsCalculator activityInsertionCalculator;\n\n private SolutionAcceptor solutionAcceptor;\n\n private ScoringFunction regretScorer = null;\n\n private Map customStrategies = new HashMap<>();\n\n private VehicleFleetManager fleetManager = null;\n\n public static Builder newInstance(VehicleRoutingProblem vrp) {\n return new Builder(vrp);\n }\n\n private Builder(VehicleRoutingProblem vrp) {\n this.vrp = vrp;\n properties = new Properties(createDefaultProperties());\n }\n\n private Properties createDefaultProperties() {\n Properties defaults = new Properties();\n defaults.put(Strategy.RADIAL_BEST.toString(), \"0.\");\n defaults.put(Strategy.RADIAL_REGRET.toString(), \".5\");\n defaults.put(Strategy.RANDOM_BEST.toString(), \".5\");\n defaults.put(Strategy.RANDOM_REGRET.toString(), \".5\");\n\n defaults.put(Strategy.STRING_BEST.toString(), \"0.0\");\n defaults.put(Strategy.STRING_REGRET.toString(), \"0.0\");\n\n defaults.put(Parameter.STRING_K_MIN.toString(), \"1\");\n defaults.put(Parameter.STRING_K_MAX.toString(), \"6\");\n defaults.put(Parameter.STRING_L_MIN.toString(), \"10\");\n defaults.put(Parameter.STRING_L_MAX.toString(), \"30\");\n\n defaults.put(Strategy.WORST_BEST.toString(), \"0.\");\n defaults.put(Strategy.WORST_REGRET.toString(), \"1.\");\n defaults.put(Strategy.CLUSTER_BEST.toString(), \"0.\");\n defaults.put(Strategy.CLUSTER_REGRET.toString(), \"1.\");\n\n\n defaults.put(Parameter.FIXED_COST_PARAM.toString(), \"0.\");\n defaults.put(Parameter.VEHICLE_SWITCH.toString(), \"true\");\n defaults.put(Parameter.ITERATIONS.toString(), \"2000\");\n defaults.put(Parameter.REGRET_DISTANCE_SCORER.toString(), \".05\");\n defaults.put(Parameter.REGRET_TIME_WINDOW_SCORER.toString(), \"-.1\");\n defaults.put(Parameter.THREADS.toString(), \"1\");\n int minShare = (int) Math.min(20, Math.max(3, vrp.getJobs().size() * 0.05));\n int maxShare = (int) Math.min(50, Math.max(5, vrp.getJobs().size() * 0.3));\n defaults.put(Parameter.RADIAL_MIN_SHARE.toString(), String.valueOf(minShare));\n defaults.put(Parameter.RADIAL_MAX_SHARE.toString(), String.valueOf(maxShare));\n defaults.put(Parameter.WORST_MIN_SHARE.toString(), String.valueOf(minShare));\n defaults.put(Parameter.WORST_MAX_SHARE.toString(), String.valueOf(maxShare));\n defaults.put(Parameter.CLUSTER_MIN_SHARE.toString(), String.valueOf(minShare));\n defaults.put(Parameter.CLUSTER_MAX_SHARE.toString(), String.valueOf(maxShare));\n int minShare_ = (int) Math.min(70, Math.max(5, vrp.getJobs().size() * 0.5));\n int maxShare_ = (int) Math.min(70, Math.max(5, vrp.getJobs().size() * 0.5));\n defaults.put(Parameter.RANDOM_REGRET_MIN_SHARE.toString(), String.valueOf(minShare_));\n defaults.put(Parameter.RANDOM_REGRET_MAX_SHARE.toString(), String.valueOf(maxShare_));\n defaults.put(Parameter.RANDOM_BEST_MIN_SHARE.toString(), String.valueOf(minShare_));\n defaults.put(Parameter.RANDOM_BEST_MAX_SHARE.toString(), String.valueOf(maxShare_));\n defaults.put(Parameter.THRESHOLD_ALPHA.toString(), String.valueOf(0.15));\n defaults.put(Parameter.THRESHOLD_INI.toString(), String.valueOf(0.03));\n defaults.put(Parameter.INSERTION_NOISE_LEVEL.toString(), String.valueOf(0.15));\n defaults.put(Parameter.INSERTION_NOISE_PROB.toString(), String.valueOf(0.2));\n defaults.put(Parameter.RUIN_WORST_NOISE_LEVEL.toString(), String.valueOf(0.15));\n defaults.put(Parameter.RUIN_WORST_NOISE_PROB.toString(), String.valueOf(0.2));\n defaults.put(Parameter.VEHICLE_SWITCH.toString(), String.valueOf(true));\n defaults.put(Parameter.FAST_REGRET.toString(), String.valueOf(false));\n defaults.put(Parameter.BREAK_SCHEDULING.toString(), String.valueOf(true));\n defaults.put(Parameter.CONSTRUCTION.toString(), Construction.REGRET_INSERTION.toString());\n return defaults;\n }\n\n\n public Builder addSearchStrategy(SearchStrategy searchStrategy, double weight) {\n customStrategies.put(searchStrategy, weight);\n return this;\n }\n\n public Builder setVehicleFleetManager(VehicleFleetManager fleetManager) {\n this.fleetManager = fleetManager;\n return this;\n }\n\n public Builder setExecutorService(ExecutorService es, int noThreads) {\n this.es = es;\n this.noThreads = noThreads;\n return this;\n }\n\n public Builder setCustomAcceptor(SolutionAcceptor acceptor){\n this.solutionAcceptor = acceptor;\n return this;\n }\n\n public Builder setRandom(Random random) {\n this.random = random;\n return this;\n }\n\n public Builder setProperty(String key, String value) {\n properties.put(key, value);\n return this;\n }\n\n public Builder setProperty(Parameter parameter, String value) {\n setProperty(parameter.toString(), value);\n return this;\n }\n\n public Builder setProperty(Strategy strategy, String value) {\n setProperty(strategy.toString(), value);\n return this;\n }\n\n public Builder setStateAndConstraintManager(StateManager stateManager, ConstraintManager constraintManager) {\n this.stateManager = stateManager;\n this.constraintManager = constraintManager;\n return this;\n }\n\n public Builder setObjectiveFunction(SolutionCostCalculator objectiveFunction) {\n this.objectiveFunction = objectiveFunction;\n return this;\n }\n\n public Builder addCoreStateAndConstraintStuff(boolean addConstraints) {\n this.addConstraints = addConstraints;\n return this;\n }\n\n public Builder setActivityInsertionCalculator(ActivityInsertionCostsCalculator activityInsertionCalculator) {\n this.activityInsertionCalculator = activityInsertionCalculator;\n return this;\n }\n\n public Builder setRegretScorer(ScoringFunction scoringFunction) {\n this.regretScorer = scoringFunction;\n return this;\n }\n\n public VehicleRoutingAlgorithm buildAlgorithm() {\n return new Jsprit(this).create(vrp);\n }\n\n }\n\n static class RuinShareFactoryImpl implements RuinShareFactory\n\n {\n\n private int maxShare;\n\n private int minShare;\n\n private Random random = RandomNumberGeneration.getRandom();\n\n public void setRandom(Random random) {\n this.random = random;\n }\n\n public RuinShareFactoryImpl(int minShare, int maxShare) {\n if (maxShare < minShare)\n throw new IllegalArgumentException(\"maxShare must be equal or greater than minShare\");\n this.minShare = minShare;\n this.maxShare = maxShare;\n }\n\n public RuinShareFactoryImpl(int minShare, int maxShare, Random random) {\n if (maxShare < minShare)\n throw new IllegalArgumentException(\"maxShare must be equal or greater than minShare\");\n this.minShare = minShare;\n this.maxShare = maxShare;\n this.random = random;\n }\n\n @Override\n public int createNumberToBeRemoved() {\n return (int) (minShare + (maxShare - minShare) * random.nextDouble());\n }\n\n }\n\n private StateManager stateManager = null;\n\n private ConstraintManager constraintManager = null;\n\n private ExecutorService es = null;\n\n private Integer noThreads;\n\n private boolean setupExecutorInternally = false;\n\n private boolean addCoreConstraints;\n\n private SolutionCostCalculator objectiveFunction = null;\n\n private Properties properties;\n\n private Random random;\n\n private SolutionAcceptor acceptor;\n\n private ScoringFunction regretScorer;\n\n private final Map customStrategies = new HashMap<>();\n\n private VehicleFleetManager vehicleFleetManager;\n\n private Jsprit(Builder builder) {\n this.stateManager = builder.stateManager;\n this.constraintManager = builder.constraintManager;\n this.es = builder.es;\n this.noThreads = builder.noThreads;\n this.addCoreConstraints = builder.addConstraints;\n this.properties = builder.properties;\n this.objectiveFunction = builder.objectiveFunction;", "answers": [" this.random = builder.random;"], "length": 877, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "22819d7f-cc8b-4764-bd3c-cc86364cc1bf", "reasoning": "In the Jsprit constructor, after assigning fields from the Builder (stateManager, constraintManager, es, noThreads, addCoreConstraints, properties, objectiveFunction), the next logical field to assign is the Random instance, which is stored in the builder as 'random'. Therefore the next line should assign this.random from builder.random.", "reasoning_model_answer": "this.random = builder.random;", "assistant_with_reasoning": "\nIn the Jsprit constructor, after assigning fields from the Builder (stateManager, constraintManager, es, noThreads, addCoreConstraints, properties, objectiveFunction), the next logical field to assign is the Random instance, which is stored in the builder as 'random'. Therefore the next line should assign this.random from builder.random.\n\nthis.random = builder.random;", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.97, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 15071, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "this.random = builder.random;", "score": 0.88, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "// Generated by the protocol buffer compiler. DO NOT EDIT!\n// source: google/cloud/videointelligence/v1beta2/video_intelligence.proto\n\npackage com.google.cloud.videointelligence.v1beta2;\n\n/**\n *
    \n * Video frame level annotation results for explicit content.\n * 
    \n *\n * Protobuf type {@code google.cloud.videointelligence.v1beta2.ExplicitContentFrame}\n */\npublic final class ExplicitContentFrame extends\n com.google.protobuf.GeneratedMessageV3 implements\n // @@protoc_insertion_point(message_implements:google.cloud.videointelligence.v1beta2.ExplicitContentFrame)\n ExplicitContentFrameOrBuilder {\nprivate static final long serialVersionUID = 0L;\n // Use ExplicitContentFrame.newBuilder() to construct.\n private ExplicitContentFrame(com.google.protobuf.GeneratedMessageV3.Builder builder) {\n super(builder);\n }\n private ExplicitContentFrame() {\n pornographyLikelihood_ = 0;\n }\n\n @java.lang.Override\n public final com.google.protobuf.UnknownFieldSet\n getUnknownFields() {\n return this.unknownFields;\n }\n private ExplicitContentFrame(\n com.google.protobuf.CodedInputStream input,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws com.google.protobuf.InvalidProtocolBufferException {\n this();\n if (extensionRegistry == null) {\n throw new java.lang.NullPointerException();\n }\n int mutable_bitField0_ = 0;\n com.google.protobuf.UnknownFieldSet.Builder unknownFields =\n com.google.protobuf.UnknownFieldSet.newBuilder();\n try {\n boolean done = false;\n while (!done) {\n int tag = input.readTag();\n switch (tag) {\n case 0:\n done = true;\n break;\n default: {\n if (!parseUnknownFieldProto3(\n input, unknownFields, extensionRegistry, tag)) {\n done = true;\n }\n break;\n }\n case 10: {\n com.google.protobuf.Duration.Builder subBuilder = null;\n if (timeOffset_ != null) {\n subBuilder = timeOffset_.toBuilder();\n }\n timeOffset_ = input.readMessage(com.google.protobuf.Duration.parser(), extensionRegistry);\n if (subBuilder != null) {\n subBuilder.mergeFrom(timeOffset_);\n timeOffset_ = subBuilder.buildPartial();\n }\n\n break;\n }\n case 16: {\n int rawValue = input.readEnum();\n\n pornographyLikelihood_ = rawValue;\n break;\n }\n }\n }\n } catch (com.google.protobuf.InvalidProtocolBufferException e) {\n throw e.setUnfinishedMessage(this);\n } catch (java.io.IOException e) {\n throw new com.google.protobuf.InvalidProtocolBufferException(\n e).setUnfinishedMessage(this);\n } finally {\n this.unknownFields = unknownFields.build();\n makeExtensionsImmutable();\n }\n }\n public static final com.google.protobuf.Descriptors.Descriptor\n getDescriptor() {\n return com.google.cloud.videointelligence.v1beta2.VideoIntelligenceServiceProto.internal_static_google_cloud_videointelligence_v1beta2_ExplicitContentFrame_descriptor;\n }\n\n protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable\n internalGetFieldAccessorTable() {\n return com.google.cloud.videointelligence.v1beta2.VideoIntelligenceServiceProto.internal_static_google_cloud_videointelligence_v1beta2_ExplicitContentFrame_fieldAccessorTable\n .ensureFieldAccessorsInitialized(\n com.google.cloud.videointelligence.v1beta2.ExplicitContentFrame.class, com.google.cloud.videointelligence.v1beta2.ExplicitContentFrame.Builder.class);\n }\n\n public static final int TIME_OFFSET_FIELD_NUMBER = 1;\n private com.google.protobuf.Duration timeOffset_;\n /**\n *
    \n   * Time-offset, relative to the beginning of the video, corresponding to the\n   * video frame for this location.\n   * 
    \n *\n * .google.protobuf.Duration time_offset = 1;\n */\n public boolean hasTimeOffset() {\n return timeOffset_ != null;\n }\n /**\n *
    \n   * Time-offset, relative to the beginning of the video, corresponding to the\n   * video frame for this location.\n   * 
    \n *\n * .google.protobuf.Duration time_offset = 1;\n */\n public com.google.protobuf.Duration getTimeOffset() {\n return timeOffset_ == null ? com.google.protobuf.Duration.getDefaultInstance() : timeOffset_;\n }\n /**\n *
    \n   * Time-offset, relative to the beginning of the video, corresponding to the\n   * video frame for this location.\n   * 
    \n *\n * .google.protobuf.Duration time_offset = 1;\n */\n public com.google.protobuf.DurationOrBuilder getTimeOffsetOrBuilder() {\n return getTimeOffset();\n }\n\n public static final int PORNOGRAPHY_LIKELIHOOD_FIELD_NUMBER = 2;\n private int pornographyLikelihood_;\n /**\n *
    \n   * Likelihood of the pornography content..\n   * 
    \n *\n * .google.cloud.videointelligence.v1beta2.Likelihood pornography_likelihood = 2;\n */\n public int getPornographyLikelihoodValue() {\n return pornographyLikelihood_;\n }\n /**\n *
    \n   * Likelihood of the pornography content..\n   * 
    \n *\n * .google.cloud.videointelligence.v1beta2.Likelihood pornography_likelihood = 2;\n */\n public com.google.cloud.videointelligence.v1beta2.Likelihood getPornographyLikelihood() {\n com.google.cloud.videointelligence.v1beta2.Likelihood result = com.google.cloud.videointelligence.v1beta2.Likelihood.valueOf(pornographyLikelihood_);\n return result == null ? com.google.cloud.videointelligence.v1beta2.Likelihood.UNRECOGNIZED : result;\n }\n\n private byte memoizedIsInitialized = -1;\n public final boolean isInitialized() {\n byte isInitialized = memoizedIsInitialized;\n if (isInitialized == 1) return true;\n if (isInitialized == 0) return false;\n\n memoizedIsInitialized = 1;\n return true;\n }\n\n public void writeTo(com.google.protobuf.CodedOutputStream output)\n throws java.io.IOException {\n if (timeOffset_ != null) {\n output.writeMessage(1, getTimeOffset());\n }\n if (pornographyLikelihood_ != com.google.cloud.videointelligence.v1beta2.Likelihood.LIKELIHOOD_UNSPECIFIED.getNumber()) {\n output.writeEnum(2, pornographyLikelihood_);\n }\n unknownFields.writeTo(output);\n }\n\n public int getSerializedSize() {\n int size = memoizedSize;\n if (size != -1) return size;\n\n size = 0;\n if (timeOffset_ != null) {\n size += com.google.protobuf.CodedOutputStream\n .computeMessageSize(1, getTimeOffset());\n }\n if (pornographyLikelihood_ != com.google.cloud.videointelligence.v1beta2.Likelihood.LIKELIHOOD_UNSPECIFIED.getNumber()) {\n size += com.google.protobuf.CodedOutputStream\n .computeEnumSize(2, pornographyLikelihood_);\n }\n size += unknownFields.getSerializedSize();\n memoizedSize = size;\n return size;\n }\n\n @java.lang.Override\n public boolean equals(final java.lang.Object obj) {\n if (obj == this) {\n return true;\n }\n if (!(obj instanceof com.google.cloud.videointelligence.v1beta2.ExplicitContentFrame)) {\n return super.equals(obj);\n }\n com.google.cloud.videointelligence.v1beta2.ExplicitContentFrame other = (com.google.cloud.videointelligence.v1beta2.ExplicitContentFrame) obj;\n\n boolean result = true;\n result = result && (hasTimeOffset() == other.hasTimeOffset());\n if (hasTimeOffset()) {\n result = result && getTimeOffset()\n .equals(other.getTimeOffset());\n }\n result = result && pornographyLikelihood_ == other.pornographyLikelihood_;\n result = result && unknownFields.equals(other.unknownFields);\n return result;\n }\n\n @java.lang.Override\n public int hashCode() {\n if (memoizedHashCode != 0) {\n return memoizedHashCode;\n }\n int hash = 41;\n hash = (19 * hash) + getDescriptor().hashCode();\n if (hasTimeOffset()) {\n hash = (37 * hash) + TIME_OFFSET_FIELD_NUMBER;\n hash = (53 * hash) + getTimeOffset().hashCode();\n }\n hash = (37 * hash) + PORNOGRAPHY_LIKELIHOOD_FIELD_NUMBER;\n hash = (53 * hash) + pornographyLikelihood_;\n hash = (29 * hash) + unknownFields.hashCode();\n memoizedHashCode = hash;\n return hash;\n }\n\n public static com.google.cloud.videointelligence.v1beta2.ExplicitContentFrame parseFrom(\n java.nio.ByteBuffer data)\n throws com.google.protobuf.InvalidProtocolBufferException {\n return PARSER.parseFrom(data);\n }\n public static com.google.cloud.videointelligence.v1beta2.ExplicitContentFrame parseFrom(\n java.nio.ByteBuffer data,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws com.google.protobuf.InvalidProtocolBufferException {\n return PARSER.parseFrom(data, extensionRegistry);\n }\n public static com.google.cloud.videointelligence.v1beta2.ExplicitContentFrame parseFrom(\n com.google.protobuf.ByteString data)\n throws com.google.protobuf.InvalidProtocolBufferException {\n return PARSER.parseFrom(data);\n }\n public static com.google.cloud.videointelligence.v1beta2.ExplicitContentFrame parseFrom(\n com.google.protobuf.ByteString data,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws com.google.protobuf.InvalidProtocolBufferException {\n return PARSER.parseFrom(data, extensionRegistry);\n }\n public static com.google.cloud.videointelligence.v1beta2.ExplicitContentFrame parseFrom(byte[] data)\n throws com.google.protobuf.InvalidProtocolBufferException {\n return PARSER.parseFrom(data);\n }\n public static com.google.cloud.videointelligence.v1beta2.ExplicitContentFrame parseFrom(\n byte[] data,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws com.google.protobuf.InvalidProtocolBufferException {\n return PARSER.parseFrom(data, extensionRegistry);\n }\n public static com.google.cloud.videointelligence.v1beta2.ExplicitContentFrame parseFrom(java.io.InputStream input)\n throws java.io.IOException {\n return com.google.protobuf.GeneratedMessageV3\n .parseWithIOException(PARSER, input);\n }\n public static com.google.cloud.videointelligence.v1beta2.ExplicitContentFrame parseFrom(\n java.io.InputStream input,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws java.io.IOException {\n return com.google.protobuf.GeneratedMessageV3\n .parseWithIOException(PARSER, input, extensionRegistry);\n }\n public static com.google.cloud.videointelligence.v1beta2.ExplicitContentFrame parseDelimitedFrom(java.io.InputStream input)\n throws java.io.IOException {\n return com.google.protobuf.GeneratedMessageV3\n .parseDelimitedWithIOException(PARSER, input);\n }\n public static com.google.cloud.videointelligence.v1beta2.ExplicitContentFrame parseDelimitedFrom(\n java.io.InputStream input,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws java.io.IOException {", "answers": [" return com.google.protobuf.GeneratedMessageV3"], "length": 811, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "00ca1763-5401-47c3-b487-c568994fbdab", "reasoning": "The code is part of a protobuf-generated Java class. After the method signature for parseDelimitedFrom with an InputStream and ExtensionRegistryLite, the typical implementation returns the result of GeneratedMessageV3.parseDelimitedWithIOException using the class's PARSER, the input, and the extensionRegistry. This matches the pattern used earlier for parseFrom methods. Therefore the next line is the return statement invoking parseDelimitedWithIOException.", "reasoning_model_answer": "return com.google.protobuf.GeneratedMessageV3\n .parseDelimitedWithIOException(PARSER, input, extensionRegistry);", "assistant_with_reasoning": "\nThe code is part of a protobuf-generated Java class. After the method signature for parseDelimitedFrom with an InputStream and ExtensionRegistryLite, the typical implementation returns the result of GeneratedMessageV3.parseDelimitedWithIOException using the class's PARSER, the input, and the extensionRegistry. This matches the pattern used earlier for parseFrom methods. Therefore the next line is the return statement invoking parseDelimitedWithIOException.\n\nreturn com.google.protobuf.GeneratedMessageV3\n .parseDelimitedWithIOException(PARSER, input, extensionRegistry);", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 5.851, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 11089, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "return com.google.protobuf.GeneratedMessageV3\n .parseDelimitedWithIOException(PARSER, input, extensionRegistry);", "score": 0.96, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "# Copyright (c) 2013 - 2015 EMC Corporation.\n# All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\"\"\"\nDriver for EMC ScaleIO based on ScaleIO remote CLI.\n\"\"\"\n\nimport base64\nimport json\n\nfrom os_brick.initiator import connector\nfrom oslo_config import cfg\nfrom oslo_log import log as logging\nfrom oslo_utils import units\nimport requests\nimport six\nimport urllib\n\nfrom cinder import context\nfrom cinder import exception\nfrom cinder.i18n import _, _LI, _LW\nfrom cinder.image import image_utils\nfrom cinder import utils\nfrom cinder.volume import driver\nfrom cinder.volume.drivers.san import san\nfrom cinder.volume import volume_types\n\nCONF = cfg.CONF\n\nLOG = logging.getLogger(__name__)\n\nscaleio_opts = [\n cfg.StrOpt('sio_rest_server_port',\n default='443',\n help='REST server port.'),\n cfg.BoolOpt('sio_verify_server_certificate',\n default=False,\n help='Whether to verify server certificate.'),\n cfg.StrOpt('sio_server_certificate_path',\n default=None,\n help='Server certificate path.'),\n cfg.BoolOpt('sio_round_volume_capacity',\n default=True,\n help='Whether to round volume capacity.'),\n cfg.BoolOpt('sio_force_delete',\n default=False,\n help='Whether to allow force delete.'),\n cfg.BoolOpt('sio_unmap_volume_before_deletion',\n default=False,\n help='Whether to unmap volume before deletion.'),\n cfg.StrOpt('sio_protection_domain_id',\n default=None,\n help='Protection domain id.'),\n cfg.StrOpt('sio_protection_domain_name',\n default=None,\n help='Protection domain name.'),\n cfg.StrOpt('sio_storage_pools',\n default=None,\n help='Storage pools.'),\n cfg.StrOpt('sio_storage_pool_name',\n default=None,\n help='Storage pool name.'),\n cfg.StrOpt('sio_storage_pool_id',\n default=None,\n help='Storage pool id.')\n]\n\nCONF.register_opts(scaleio_opts)\n\nSTORAGE_POOL_NAME = 'sio:sp_name'\nSTORAGE_POOL_ID = 'sio:sp_id'\nPROTECTION_DOMAIN_NAME = 'sio:pd_name'\nPROTECTION_DOMAIN_ID = 'sio:pd_id'\nPROVISIONING_KEY = 'sio:provisioning'\nIOPS_LIMIT_KEY = 'sio:iops_limit'\nBANDWIDTH_LIMIT = 'sio:bandwidth_limit'\n\nBLOCK_SIZE = 8\nOK_STATUS_CODE = 200\nVOLUME_NOT_FOUND_ERROR = 78\nVOLUME_NOT_MAPPED_ERROR = 84\nVOLUME_ALREADY_MAPPED_ERROR = 81\n\n\nclass ScaleIODriver(driver.VolumeDriver):\n \"\"\"EMC ScaleIO Driver.\"\"\"\n\n VERSION = \"2.0\"\n\n def __init__(self, *args, **kwargs):\n super(ScaleIODriver, self).__init__(*args, **kwargs)\n\n self.configuration.append_config_values(san.san_opts)\n self.configuration.append_config_values(scaleio_opts)\n self.server_ip = self.configuration.san_ip\n self.server_port = self.configuration.sio_rest_server_port\n self.server_username = self.configuration.san_login\n self.server_password = self.configuration.san_password\n self.server_token = None\n self.verify_server_certificate = (\n self.configuration.sio_verify_server_certificate)\n self.server_certificate_path = None\n if self.verify_server_certificate:\n self.server_certificate_path = (\n self.configuration.sio_server_certificate_path)\n LOG.info(_LI(\n \"REST server IP: %(ip)s, port: %(port)s, username: %(user)s. \"\n \"Verify server's certificate: %(verify_cert)s.\"),\n {'ip': self.server_ip,\n 'port': self.server_port,\n 'user': self.server_username,\n 'verify_cert': self.verify_server_certificate})\n\n self.storage_pools = None\n if self.configuration.sio_storage_pools:\n self.storage_pools = [\n e.strip() for e in\n self.configuration.sio_storage_pools.split(',')\n ]\n\n self.storage_pool_name = self.configuration.sio_storage_pool_name\n self.storage_pool_id = self.configuration.sio_storage_pool_id\n if self.storage_pool_name is None and self.storage_pool_id is None:\n LOG.warning(_LW(\"No storage pool name or id was found.\"))\n else:\n LOG.info(_LI(\n \"Storage pools names: %(pools)s, \"\n \"storage pool name: %(pool)s, pool id: %(pool_id)s.\"),\n {'pools': self.storage_pools,\n 'pool': self.storage_pool_name,\n 'pool_id': self.storage_pool_id})\n\n self.protection_domain_name = (\n self.configuration.sio_protection_domain_name)\n LOG.info(_LI(\n \"Protection domain name: %(domain_name)s.\"),\n {'domain_name': self.protection_domain_name})\n self.protection_domain_id = self.configuration.sio_protection_domain_id\n LOG.info(_LI(\n \"Protection domain name: %(domain_id)s.\"),\n {'domain_id': self.protection_domain_id})\n\n self.connector = connector.InitiatorConnector.factory(\n # TODO(xyang): Change 'SCALEIO' to connector.SCALEIO after\n # os-brick 0.4.0 is released.\n 'SCALEIO', utils.get_root_helper(),\n device_scan_attempts=\n self.configuration.num_volume_device_scan_tries\n )\n\n self.connection_properties = {}\n self.connection_properties['scaleIO_volname'] = None\n self.connection_properties['hostIP'] = None\n self.connection_properties['serverIP'] = self.server_ip\n self.connection_properties['serverPort'] = self.server_port\n self.connection_properties['serverUsername'] = self.server_username\n self.connection_properties['serverPassword'] = self.server_password\n self.connection_properties['serverToken'] = self.server_token\n self.connection_properties['iopsLimit'] = None\n self.connection_properties['bandwidthLimit'] = None\n\n def check_for_setup_error(self):\n if (not self.protection_domain_name and\n not self.protection_domain_id):\n LOG.warning(_LW(\"No protection domain name or id \"\n \"was specified in configuration.\"))\n\n if self.protection_domain_name and self.protection_domain_id:\n msg = _(\"Cannot specify both protection domain name \"\n \"and protection domain id.\")\n raise exception.InvalidInput(reason=msg)\n\n if not self.server_ip:\n msg = _(\"REST server IP must by specified.\")\n raise exception.InvalidInput(reason=msg)\n\n if not self.server_username:\n msg = _(\"REST server username must by specified.\")\n raise exception.InvalidInput(reason=msg)\n\n if not self.server_password:\n msg = _(\"REST server password must by specified.\")\n raise exception.InvalidInput(reason=msg)\n\n if not self.verify_server_certificate:\n LOG.warning(_LW(\"Verify certificate is not set, using default of \"\n \"False.\"))\n\n if self.verify_server_certificate and not self.server_certificate_path:\n msg = _(\"Path to REST server's certificate must be specified.\")\n raise exception.InvalidInput(reason=msg)\n\n if self.storage_pool_name and self.storage_pool_id:\n msg = _(\"Cannot specify both storage pool name and storage \"\n \"pool id.\")\n raise exception.InvalidInput(reason=msg)\n\n if not self.storage_pool_name and not self.storage_pool_id:\n msg = _(\"Must specify storage pool name or id.\")\n raise exception.InvalidInput(reason=msg)\n\n if not self.storage_pools:\n msg = _(\n \"Must specify storage pools. Option: sio_storage_pools.\"\n )\n raise exception.InvalidInput(reason=msg)\n\n def _find_storage_pool_id_from_storage_type(self, storage_type):\n # Default to what was configured in configuration file if not defined.\n return storage_type.get(STORAGE_POOL_ID,\n self.storage_pool_id)\n\n def _find_storage_pool_name_from_storage_type(self, storage_type):\n return storage_type.get(STORAGE_POOL_NAME,\n self.storage_pool_name)\n\n def _find_protection_domain_id_from_storage_type(self, storage_type):\n # Default to what was configured in configuration file if not defined.\n return storage_type.get(PROTECTION_DOMAIN_ID,\n self.protection_domain_id)\n\n def _find_protection_domain_name_from_storage_type(self, storage_type):\n # Default to what was configured in configuration file if not defined.\n return storage_type.get(PROTECTION_DOMAIN_NAME,\n self.protection_domain_name)\n\n def _find_provisioning_type(self, storage_type):\n return storage_type.get(PROVISIONING_KEY)\n\n def _find_iops_limit(self, storage_type):\n return storage_type.get(IOPS_LIMIT_KEY)\n\n def _find_bandwidth_limit(self, storage_type):\n return storage_type.get(BANDWIDTH_LIMIT)\n\n def _id_to_base64(self, id):\n # Base64 encode the id to get a volume name less than 32 characters due\n # to ScaleIO limitation.\n name = six.text_type(id).replace(\"-\", \"\")\n try:\n name = base64.b16decode(name.upper())\n except TypeError:\n pass\n encoded_name = base64.b64encode(name)\n LOG.debug(\n \"Converted id %(id)s to scaleio name %(name)s.\",\n {'id': id, 'name': encoded_name})\n return encoded_name\n\n def create_volume(self, volume):\n \"\"\"Creates a scaleIO volume.\"\"\"\n self._check_volume_size(volume.size)\n\n volname = self._id_to_base64(volume.id)\n\n storage_type = self._get_volumetype_extraspecs(volume)", "answers": [" storage_pool_name = self._find_storage_pool_name_from_storage_type("], "length": 781, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "3c9ceb25-b74b-4ab6-b016-14d868397682", "reasoning": "The method create_volume has just retrieved the extra specs for the volume into the variable storage_type. The next logical step is to extract the storage pool identifier from those specs using the helper method _find_storage_pool_id_from_storage_type. This follows the pattern of subsequent calls that pull configuration values from storage_type before proceeding with volume creation.", "reasoning_model_answer": "storage_pool_id = self._find_storage_pool_id_from_storage_type(storage_type)", "assistant_with_reasoning": "\nThe method create_volume has just retrieved the extra specs for the volume into the variable storage_type. The next logical step is to extract the storage pool identifier from those specs using the helper method _find_storage_pool_id_from_storage_type. This follows the pattern of subsequent calls that pull configuration values from storage_type before proceeding with volume creation.\n\nstorage_pool_id = self._find_storage_pool_id_from_storage_type(storage_type)", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 5.051, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 10498, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "storage_pool_id = self._find_storage_pool_id_from_storage_type(storage_type)", "score": 0.78, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/*\n * (c) Copyright 2003, 2004, 2005 2006, 2007, 2008, 2009 Hewlett-Packard Development Company, LP\n * All rights reserved.\n *\n *\n */\n\n//=======================================================================\n// Package\npackage com.hp.hpl.jena.db.impl;\n\n//=======================================================================\n// Imports\nimport java.sql.*;\nimport java.util.*;\nimport com.hp.hpl.jena.util.iterator.*;\nimport com.hp.hpl.jena.shared.*;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\n//=======================================================================\n/**\n* Iterates over an SQL result set returning each row as an ArrayList of\n* objects. The returned array is shared at each iteration so calling next() or even hasNext()\n* changes the array contents. When the iterator terminates the resources\n* are cleaned up and the underlying SQL PreparedStatement is returned to\n* the SQLCache pool from whence it came.\n* \n*

    Override the extractRow, getRow, and remove methods in subclasses \n* to return an object collection derived from the row contents instead \n* of the raw row contents.\n*\n* @author Dave Reynolds\n* @version $Revision: 1.1 $ on $Date: 2009/06/29 08:55:37 $\n*/\n\npublic abstract class ResultSetIterator implements ExtendedIterator{\n // T is the type of the \n \n /** The ResultSet being iterated over */\n protected ResultSet m_resultSet;\n\n /** The originating SQLcache to return the statement to, can be null */\n protected SQLCache m_sqlCache;\n\n /** The source Statement to be cleaned up when the iterator finishes - return it to cache or close it if no cache */\n protected PreparedStatement m_statement;\n\n /** If true, clean/close the prepared statement when iterator is closed */\n protected boolean m_statementClean = true;\n \n /** The name of the original operation that lead to this statement, can be null if SQLCache is null */\n protected String m_opname;\n\n /** The contents of the current row */\n protected T m_row;\n\n /** The number of columns in this result set */\n protected int m_nCols;\n\n /** Flag that the iteration has finished */\n protected boolean m_finished = false;\n\n /** Flag if we have prefeteched the next row but not yet returned it */\n protected boolean m_prefetched = false;\n\n private static Logger logger = LoggerFactory.getLogger( ResultSetIterator.class );\n /**\n * Create an empty iterator.\n * Needs to be initialized by reset\n * before it can be accessed. Useful to allow generic functions like\n * {@link SQLCache#runSQLQuery runSQLQuery}\n * to return different iterator types to the client.\n */\n public ResultSetIterator() {\n m_finished = true; // Prevent reading until reset\n }\n\n /**\n * Iterate over the results of a PreparedStatement generated by an SQLCache\n * @param resultSet the result set being iterated over\n * @param sourceStatement The source Statement to be cleaned up when the iterator finishes - return it to cache or close it if no cache\n * @param cache The originating SQLcache to return the statement to, can be null\n * @param opname The name of the original operation that lead to this statement, can be null if SQLCache is null\n */\n public ResultSetIterator(ResultSet resultSet, PreparedStatement sourceStatement, SQLCache cache, String opname) {\n m_resultSet = resultSet;\n m_sqlCache = cache;\n m_statement = sourceStatement;\n m_opname = opname;\n }\n\n /**\n * Iterate over the results of a PreparedStatement, close the statement when finished.\n * @param resultSet the result set being iterated over\n * @param sourceStatement The source Statement to be closed when the iterator finishes\n */\n public ResultSetIterator(ResultSet resultSet, PreparedStatement sourceStatement) {\n m_resultSet = resultSet;\n m_statement = sourceStatement;\n }\n\n /**\n * Reset an existing iterator to scan a new result set.\n * @param resultSet the result set being iterated over\n * @param sourceStatement The source Statement to be cleaned up when the iterator finishes - return it to cache or close it if no cache\n * @param cache The originating SQLcache to return the statement to, can be null\n * @param opname The name of the original operation that lead to this statement, can be null if SQLCache is null\n */\n public void reset(ResultSet resultSet, PreparedStatement sourceStatement, SQLCache cache, String opname) {\n m_resultSet = resultSet;\n m_sqlCache = cache;\n m_statement = sourceStatement;\n m_opname = opname;\n m_finished = false;\n m_prefetched = false;\n m_row = null;\n m_statementClean = true;\n }\n \n /**\n * Reset an existing iterator to scan a new result set.\n * @param resultSet the result set being iterated over\n * @param sourceStatement The source Statement to be cleaned up when the iterator finishes - return it to cache or close it if no cache\n * note: the sourceStatement is not closed or returned when the iterator is closed.\n */\n public void reset(ResultSet resultSet, PreparedStatement sourceStatement) {\n m_resultSet = resultSet;\n m_sqlCache = null;\n m_statement = sourceStatement;\n m_opname = null;\n m_finished = false;\n m_prefetched = false;\n m_row = null;\n m_statementClean = false;\n }\n\n /**\n * Test if there is a next result to return\n */\n public boolean hasNext() {\n if (!m_finished && !m_prefetched) moveForward();\n return !m_finished;\n }\n \n public T removeNext()\n { cantRemove(); return null; }\n\n /**\n * Return the current row\n */\n public T next() {\n if (!m_finished && !m_prefetched) moveForward();\n m_prefetched = false;\n if (m_finished) {", "answers": [" throw new NoSuchElementException();"], "length": 799, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "3dba6b2e-872f-4e89-99a8-521f42f63f48", "reasoning": "The next() method checks if iteration is finished; if so it must signal that no more elements are available. In Java iterators this is done by throwing a NoSuchElementException. The code already imports java.util.*, so the appropriate next line is the throw statement.", "reasoning_model_answer": "throw new NoSuchElementException();", "assistant_with_reasoning": "\nThe next() method checks if iteration is finished; if so it must signal that no more elements are available. In Java iterators this is done by throwing a NoSuchElementException. The code already imports java.util.*, so the appropriate next line is the throw statement.\n\nthrow new NoSuchElementException();", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 2.139, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 6033, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "throw new NoSuchElementException();", "score": 0.85, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/*\n * Copyright (c) 2008-2020, Hazelcast, Inc. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.hazelcast.internal.partition.impl;\n\nimport com.hazelcast.config.ClasspathXmlConfig;\nimport com.hazelcast.config.Config;\nimport com.hazelcast.config.MemberGroupConfig;\nimport com.hazelcast.config.PartitionGroupConfig;\nimport com.hazelcast.cluster.Member;\nimport com.hazelcast.instance.BuildInfoProvider;\nimport com.hazelcast.cluster.impl.MemberImpl;\nimport com.hazelcast.internal.partition.InternalPartition;\nimport com.hazelcast.internal.partition.PartitionReplica;\nimport com.hazelcast.internal.partition.PartitionStateGenerator;\nimport com.hazelcast.internal.util.UuidUtil;\nimport com.hazelcast.cluster.Address;\nimport com.hazelcast.internal.partition.membergroup.ConfigMemberGroupFactory;\nimport com.hazelcast.internal.partition.membergroup.DefaultMemberGroup;\nimport com.hazelcast.internal.partition.membergroup.HostAwareMemberGroupFactory;\nimport com.hazelcast.spi.partitiongroup.MemberGroup;\nimport com.hazelcast.internal.partition.membergroup.MemberGroupFactory;\nimport com.hazelcast.internal.partition.membergroup.SingleMemberGroupFactory;\nimport com.hazelcast.test.HazelcastParallelClassRunner;\nimport com.hazelcast.test.annotation.ParallelJVMTest;\nimport com.hazelcast.test.annotation.QuickTest;\nimport com.hazelcast.version.MemberVersion;\nimport org.junit.Test;\nimport org.junit.experimental.categories.Category;\nimport org.junit.runner.RunWith;\n\nimport java.net.InetAddress;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collection;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.Iterator;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Random;\nimport java.util.Set;\n\nimport static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.assertFalse;\nimport static org.junit.Assert.assertNotNull;\nimport static org.junit.Assert.assertTrue;\n\n@RunWith(HazelcastParallelClassRunner.class)\n@Category({QuickTest.class, ParallelJVMTest.class})\npublic class PartitionStateGeneratorTest {\n\n private static final MemberVersion VERSION = MemberVersion.of(BuildInfoProvider.getBuildInfo().getVersion());\n private static final boolean PRINT_STATE = false;\n\n @Test\n public void testRandomPartitionGenerator() throws Exception {\n final MemberGroupFactory memberGroupFactory = new SingleMemberGroupFactory();\n test(memberGroupFactory);\n }\n\n //\"random host groups may cause non-uniform distribution of partitions when node size go down significantly!\")\n @Test\n public void testHostAwarePartitionStateGenerator() throws Exception {\n final HostAwareMemberGroupFactory memberGroupFactory = new HostAwareMemberGroupFactory();\n test(memberGroupFactory);\n }\n\n @Test\n public void testCustomPartitionStateGenerator() throws Exception {\n final MemberGroupFactory memberGroupFactory = new MemberGroupFactory() {\n public Collection createMemberGroups(Collection members) {\n MemberGroup[] g = new MemberGroup[4];\n for (int i = 0; i < g.length; i++) {\n g[i] = new DefaultMemberGroup();\n }\n for (Member member : members) {\n Address address = member.getAddress();\n if (even(address.getHost().hashCode()) && even(address.getPort())) {\n g[0].addMember(member);\n } else if (even(address.getHost().hashCode()) && !even(address.getPort())) {\n g[1].addMember(member);\n } else if (!even(address.getHost().hashCode()) && even(address.getPort())) {\n g[2].addMember(member);\n } else if (!even(address.getHost().hashCode()) && !even(address.getPort())) {\n g[3].addMember(member);\n }\n }\n List list = new LinkedList();\n for (MemberGroup memberGroup : g) {\n if (memberGroup.size() > 0) {\n list.add(memberGroup);\n }\n }\n return list;\n }\n\n boolean even(int k) {\n return k % 2 == 0;\n }\n };\n test(memberGroupFactory);\n }\n\n @Test\n public void testConfigCustomPartitionStateGenerator() throws Exception {\n PartitionGroupConfig config = new PartitionGroupConfig();\n config.setEnabled(true);\n config.setGroupType(PartitionGroupConfig.MemberGroupType.CUSTOM);\n MemberGroupConfig mgCfg0 = new MemberGroupConfig();\n MemberGroupConfig mgCfg1 = new MemberGroupConfig();\n MemberGroupConfig mgCfg2 = new MemberGroupConfig();\n MemberGroupConfig mgCfg3 = new MemberGroupConfig();\n\n config.addMemberGroupConfig(mgCfg0);\n config.addMemberGroupConfig(mgCfg1);\n config.addMemberGroupConfig(mgCfg2);\n config.addMemberGroupConfig(mgCfg3);\n\n for (int k = 0; k < 3; k++) {\n for (int i = 0; i < 255; i++) {\n MemberGroupConfig mg;\n switch (i % 4) {\n case 0:\n mg = mgCfg0;\n break;\n case 1:\n mg = mgCfg1;\n break;\n case 2:\n mg = mgCfg2;\n break;\n case 3:\n mg = mgCfg3;\n break;\n default:\n throw new IllegalArgumentException();\n }\n mg.addInterface(\"10.10.\" + k + \".\" + i);\n }\n }\n\n test(new ConfigMemberGroupFactory(config.getMemberGroupConfigs()));\n }\n\n @Test\n public void testXmlPartitionGroupConfig() {\n Config config = new ClasspathXmlConfig(\"hazelcast-fullconfig.xml\");\n PartitionGroupConfig partitionGroupConfig = config.getPartitionGroupConfig();\n assertTrue(partitionGroupConfig.isEnabled());\n assertEquals(PartitionGroupConfig.MemberGroupType.CUSTOM, partitionGroupConfig.getGroupType());\n assertEquals(2, partitionGroupConfig.getMemberGroupConfigs().size());\n }\n\n @Test\n public void testOnlyUnassignedArrangement() throws Exception {\n List memberList = createMembers(10, 1);\n MemberGroupFactory memberGroupFactory = new SingleMemberGroupFactory();\n Collection groups = memberGroupFactory.createMemberGroups(memberList);\n\n PartitionStateGenerator generator = new PartitionStateGeneratorImpl();\n PartitionReplica[][] state = generator.arrange(groups, emptyPartitionArray(100));\n\n // unassign some partitions entirely\n Collection unassignedPartitions = new ArrayList();\n for (int i = 0; i < state.length; i++) {\n if (i % 3 == 0) {\n state[i] = new PartitionReplica[InternalPartition.MAX_REPLICA_COUNT];\n unassignedPartitions.add(i);\n }\n }\n\n // unassign only backup replicas of some partitions\n for (int i = 0; i < state.length; i++) {\n if (i % 10 == 0) {\n Arrays.fill(state[i], 1, InternalPartition.MAX_REPLICA_COUNT, null);\n }\n }\n\n InternalPartition[] partitions = toPartitionArray(state);\n\n state = generator.arrange(groups, partitions, unassignedPartitions);\n\n for (int pid = 0; pid < state.length; pid++) {\n PartitionReplica[] addresses = state[pid];\n\n if (unassignedPartitions.contains(pid)) {\n for (PartitionReplica address : addresses) {\n assertNotNull(address);\n }\n } else {\n InternalPartition partition = partitions[pid];\n for (int replicaIx = 0; replicaIx < InternalPartition.MAX_REPLICA_COUNT; replicaIx++) {\n assertEquals(partition.getReplica(replicaIx), addresses[replicaIx]);\n }\n }\n }\n }\n\n private void test(MemberGroupFactory memberGroupFactory) throws Exception {\n PartitionStateGenerator generator = new PartitionStateGeneratorImpl();\n int maxSameHostCount = 3;\n int[] partitionCounts = new int[]{271, 787, 1549, 3217};\n int[] members = new int[]{3, 6, 9, 10, 11, 17, 57, 100, 130, 77, 179, 93, 37, 26, 15, 5};\n for (int partitionCount : partitionCounts) {\n int memberCount = members[0];\n List memberList = createMembers(memberCount, maxSameHostCount);", "answers": [" Collection groups = memberGroupFactory.createMemberGroups(memberList);"], "length": 717, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "20e97fe7-e84d-4971-8857-adb9be56a623", "reasoning": "We are inside the private test method. After defining maxSameHostCount, partitionCounts, members, and entering the loop over partitionCounts, the code creates a memberCount (currently set to members[0]) and a list of members via createMembers. The next logical step is to form member groups from this member list using the provided MemberGroupFactory, so the next line should create a Collection by calling memberGroupFactory.createMemberGroups(memberList).", "reasoning_model_answer": "Collection groups = memberGroupFactory.createMemberGroups(memberList);", "assistant_with_reasoning": "\nWe are inside the private test method. After defining maxSameHostCount, partitionCounts, members, and entering the loop over partitionCounts, the code creates a memberCount (currently set to members[0]) and a list of members via createMembers. The next logical step is to form member groups from this member list using the provided MemberGroupFactory, so the next line should create a Collection by calling memberGroupFactory.createMemberGroups(memberList).\n\nCollection groups = memberGroupFactory.createMemberGroups(memberList);", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 6.08, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 9366, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "Collection groups = memberGroupFactory.createMemberGroups(memberList);", "score": 0.93, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.apache.commons.beanutils.locale;\n\nimport java.lang.ref.ReferenceQueue;\nimport java.lang.ref.WeakReference;\nimport java.util.Locale;\nimport java.util.Map;\nimport java.util.WeakHashMap;\n\nimport junit.framework.Test;\nimport junit.framework.TestCase;\nimport junit.framework.TestSuite;\n\nimport org.apache.commons.beanutils.BeanUtilsTestCase;\nimport org.apache.commons.beanutils.ContextClassLoaderLocal;\nimport org.apache.commons.beanutils.ConversionException;\nimport org.apache.commons.beanutils.ConvertUtils;\nimport org.apache.commons.beanutils.PrimitiveBean;\nimport org.apache.commons.beanutils.locale.converters.LongLocaleConverter;\nimport org.apache.commons.logging.LogFactory;\n\n/**\n *

    \n * Test Case for changes made during LocaleBeanutils Beanification.\n * This is basically a cut-and-correct version of the beanutils beanifications tests.\n *

    \n *\n * @version $Id$\n */\n\npublic class LocaleBeanificationTestCase extends TestCase {\n\n // ---------------------------------------------------- Constants\n\n /** Maximum number of iterations before our test fails */\n public static final int MAX_GC_ITERATIONS = 50;\n\n // ---------------------------------------------------- Instance Variables\n\n\n // ---------------------------------------------------------- Constructors\n\n\n /**\n * Construct a new instance of this test case.\n *\n * @param name Name of the test case\n */\n public LocaleBeanificationTestCase(final String name) {\n super(name);\n }\n\n\n // -------------------------------------------------- Overall Test Methods\n\n\n /**\n * Set up instance variables required by this test case.\n */\n @Override\n public void setUp() {\n\n LocaleConvertUtils.deregister();\n\n }\n\n\n /**\n * Return the tests included in this test suite.\n */\n public static Test suite() {\n return (new TestSuite(LocaleBeanificationTestCase.class));\n }\n\n\n /**\n * Tear down instance variables required by this test case.\n */\n @Override\n public void tearDown() {\n // No action required\n }\n\n\n // ------------------------------------------------ Individual Test Methods\n\n /** Test of the methodology we'll use for some of the later tests */\n public void testMemoryTestMethodology() throws Exception {\n // test methodology\n // many thanks to Juozas Baliuka for suggesting this method\n ClassLoader loader = new ClassLoader(this.getClass().getClassLoader()) {};\n final WeakReference reference = new WeakReference(loader);\n Class myClass = loader.loadClass(\"org.apache.commons.beanutils.BetaBean\");\n\n assertNotNull(\"Weak reference released early\", reference.get());\n\n // dereference class loader and class:\n loader = null;\n myClass = null;\n\n int iterations = 0;\n int bytz = 2;\n while(true) {\n System.gc();\n if(iterations++ > MAX_GC_ITERATIONS){\n fail(\"Max iterations reached before resource released.\");\n }\n if( reference.get() == null ) {\n break;\n\n } else {\n // create garbage:\n final byte[] b = new byte[bytz];\n bytz = bytz * 2;\n }\n }\n }\n\n /** Tests whether classloaders and beans are released from memory by the map used by beanutils */\n public void testMemoryLeak2() throws Exception {\n // tests when the map used by beanutils has the right behaviour\n\n if (BeanUtilsTestCase.isPre14JVM()) {\n System.out.println(\"WARNING: CANNOT TEST MEMORY LEAK ON PRE1.4 JVM\");\n return;\n }\n\n // many thanks to Juozas Baliuka for suggesting this methodology\n TestClassLoader loader = new TestClassLoader();\n final ReferenceQueue queue = new ReferenceQueue();\n final WeakReference loaderReference = new WeakReference(loader, queue);\n Integer test = new Integer(1);\n\n final WeakReference testReference = new WeakReference(test, queue);\n //Map map = new ReferenceMap(ReferenceMap.WEAK, ReferenceMap.HARD, true);\n final Map map = new WeakHashMap();\n map.put(loader, test);\n\n assertEquals(\"In map\", test, map.get(loader));\n assertNotNull(\"Weak reference released early (1)\", loaderReference.get());\n assertNotNull(\"Weak reference released early (2)\", testReference.get());\n\n // dereference strong references\n loader = null;\n test = null;\n\n int iterations = 0;\n int bytz = 2;\n while(true) {\n System.gc();\n if(iterations++ > MAX_GC_ITERATIONS){\n fail(\"Max iterations reached before resource released.\");\n }\n map.isEmpty();\n\n if(\n loaderReference.get() == null &&\n testReference.get() == null) {\n break;\n\n } else {\n // create garbage:\n final byte[] b = new byte[bytz];\n bytz = bytz * 2;\n }\n }\n }\n\n /** Tests whether classloaders and beans are released from memory */\n public void testMemoryLeak() throws Exception {\n if (BeanUtilsTestCase.isPre14JVM()) {\n System.out.println(\"WARNING: CANNOT TEST MEMORY LEAK ON PRE1.4 JVM\");\n return;\n }\n\n // many thanks to Juozas Baliuka for suggesting this methodology\n TestClassLoader loader = new TestClassLoader();\n final WeakReference loaderReference = new WeakReference(loader);\n LocaleBeanUtilsBean.getLocaleBeanUtilsInstance();\n\n class GetBeanUtilsBeanThread extends Thread {\n\n LocaleBeanUtilsBean beanUtils;\n LocaleConvertUtilsBean convertUtils;\n\n GetBeanUtilsBeanThread() {}\n\n @Override\n public void run() {\n beanUtils = LocaleBeanUtilsBean.getLocaleBeanUtilsInstance();\n convertUtils = LocaleConvertUtilsBean.getInstance();\n // XXX Log keeps a reference around!\n LogFactory.releaseAll();\n }\n\n @Override\n public String toString() {\n return \"GetBeanUtilsBeanThread\";\n }\n }\n\n\n GetBeanUtilsBeanThread thread = new GetBeanUtilsBeanThread();\n final WeakReference threadWeakReference = new WeakReference(thread);\n thread.setContextClassLoader(loader);\n", "answers": [" thread.start();"], "length": 728, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "7e9d9568-a822-4b06-a503-cfc69ffb248c", "reasoning": "The method testMemoryLeak creates a custom thread, wraps it in a WeakReference, and sets its context class loader. The next logical step is to actually start the thread so its run() method executes, which is needed before checking for garbage collection. Therefore the next line should invoke start() on the thread instance.", "reasoning_model_answer": "thread.start();", "assistant_with_reasoning": "\nThe method testMemoryLeak creates a custom thread, wraps it in a WeakReference, and sets its context class loader. The next logical step is to actually start the thread so its run() method executes, which is needed before checking for garbage collection. Therefore the next line should invoke start() on the thread instance.\n\nthread.start();", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.635, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 7575, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "thread.start();", "score": 0.79, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "\"\"\"***************************************************************************************\\\nPROGRAM NAME: ringAnalyzer.py\n\nPROGRAM DESCRPTION: Program to place rings/atoms on an image and returns the center \n position of each placed object in pixels and/or nm\n******************************************************************************************\"\"\"\n\n#IMPORTS\nimport graphics\nfrom buttonClass import Button\nfrom ringClass import Ring\nimport matplotlib.pylab as plt\n\nimport math\nimport numpy\n\nfrom skimage import io\nfrom skimage import feature\nfrom skimage import draw\nfrom skimage import util\nfrom skimage import color\nfrom skimage import viewer\n\nfrom sklearn.neighbors import NearestNeighbors\n\n#set monitor size in pixels: original height is 1500 by 1000\nmonLen = 1350\nmonHeight = 690\nimageName = \"\"\n\n#Set up main windown\nwin = graphics.GraphWin('Ring Analyzer', monLen, monHeight)\n\ndef getBlobCenters(blobs):\n \"\"\"Given a list of blobs, will return the centers of each one\n as a point object shifted to fit the screen\"\"\"\n centers = []\n \n for blob in blobs:\n x_coord = int(blob[1]) + monLen - 1000\n y_coord = int(blob[0])\n \n centers.append([x_coord, y_coord])\n \n return centers\n\n\ndef createBoard(win):\n \"\"\"Creates program boad & instructions\"\"\"\n\n \n \n #list of graphics positions, convert to fit monLen, monHeight, some vars\n gLen = [498, 498, 0, 498, 250, 250, 1000, 250, 175, 425, 1000, 250, 300, 400,\n 100, 100, 100, 100, 100, 100, 100, 350, 350, 350, 100]\n gLen = [(num / 500) * (monLen - 1000) for num in gLen]\n \n gHt = [0, 1000, 600, 600, 25, 625, 500, 75, 140, 140, 500, 190, 700, 700, \n 680, 750, 785, 820, 855, 890, 925, 845, 800, 900, 600]\n gHt = [monHeight * num / 1000 for num in gHt]\n \n #Create line diving instructions, toolbar, and image\n divideLine1 = graphics.Line(graphics.Point(monLen - 1000, gHt[0]), \n graphics.Point(monLen - 1000, gHt[1]))\n divideLine1.setWidth(2)\n divideLine1.draw(win)\n \n divideLine2 = graphics.Line(graphics.Point(gLen[2], gHt[2]), graphics.Point(gLen[3], gHt[3]))\n divideLine2.setWidth(2)\n divideLine2.draw(win)\n \n instructionLable = graphics.Text(graphics.Point(gLen[4], gHt[4]), 'Instructions')\n instructionLable.setSize(20)\n instructionLable.setStyle('italic')\n instructionLable.draw(win)\n \n toolLabel = graphics.Text(graphics.Point(gLen[5], gHt[5]), 'Toolbar')\n toolLabel.setSize(20)\n toolLabel.setStyle('italic')\n toolLabel.draw(win)\n \n imageLabel = graphics.Text(graphics.Point(gLen[6], gHt[6]), 'Upload Image Here')\n imageLabel.setSize(20)\n imageLabel.setStyle('italic')\n imageLabel.draw(win)\n \n #INSTRUCTIONS\n instruction1 = graphics.Text(graphics.Point(gLen[7], gHt[7]), \"1.) Enter the name of the image file, then click ENTER. \\\n \\n Note that the file must be saved as .png \\n (ex. filename.png)\")\n instruction1.draw(win)\n\n entry1 = graphics.Entry(graphics.Point(gLen[8], gHt[8]), 25)\n entry1.draw(win)\n \n enterButton1 = Button(win, graphics.Point(gLen[9], gHt[9]), 80, 20, '#52E643', 'ENTER')\n \n #Click enterButton, open the image, deactivate image\n loop = True\n while loop:\n if enterButton1.clicked(win.getMouse()):\n global imageName\n imageName = entry1.getText()\n #Check user imput for name of file\n if imageName != '' and imageName[-4:] == '.png':\n loop = False\n else: \n errorMessage('Please enter a PNG image file. \\n (ex. filename.png)')\n enterButton1.activate()\n \n #Upload image into window\n myImage = graphics.Image(graphics.Point(monLen - 500, monHeight/2), imageName)\n myImage.draw(win)\n enterButton1.deactivate()\n \n instruction2 = graphics.Text(graphics.Point(gLen[11], gHt[11]), \"2.) Click on the buttons below to place an atom or ring center. \\\n \\n Double click to place the object on the image. \\\n \\n Then click FINISH when all of the objects have been placed.\")\n instruction2.draw(win)\n \n #Create TOOLBAR\n siButton = Button(win, graphics.Point(gLen[12], gHt[12]), 40, 25, '#1DAA43', 'Si')\n oButton = Button(win, graphics.Point(gLen[13], gHt[13]), 40, 25, '#FF1D0F', 'O')\n \n generalRing = Button(win, graphics.Point(gLen[14], gHt[14]), 140, 34, '#F8A61E', 'General Ring')\n button4MR = Button(win, graphics.Point(gLen[15], gHt[15]), 140, 22, '#9E4BF6', '4 Membered Ring')\n button5MR = Button(win, graphics.Point(gLen[16], gHt[16]), 140, 22, '#4BB0F6', '5 Membered Ring')\n button6MR = Button(win, graphics.Point(gLen[17], gHt[17]), 140, 22, '#43C47F', '6 Membered Ring')\n button7MR = Button(win, graphics.Point(gLen[18], gHt[18]), 140, 22, '#F9DE3E', '7 Membered Ring')\n button8MR = Button(win, graphics.Point(gLen[19], gHt[19]), 140, 22, '#F94C3E', '8 Membered Ring')\n button9MR = Button(win, graphics.Point(gLen[20], gHt[20]), 140, 22, '#F726E8', '9 Membered Ring')\n \n removeButton = Button(win, graphics.Point(gLen[21], gHt[21]), 100, 25, '#F96A61', 'REMOVE')\n doneButton = Button(win, graphics.Point(gLen[22], gHt[22]), 100, 25, '#41EFC9', 'DONE')\n finishButton = Button(win, graphics.Point(gLen[23], gHt[23]), 120, 30, '#D4FF33', 'FINISH')\n autoPlaceButton = Button(win, graphics.Point(gLen[24], gHt[24]), 140, 22, '#F8A61E', 'Auto Place')\n \n return [siButton, oButton, generalRing, button4MR, button5MR, button6MR, button7MR, button8MR,\n button9MR, autoPlaceButton, removeButton, finishButton, doneButton]\n\n\ndef checkDone(mousePress, doneButton):\n \"\"\"Check if DONE button is clicked. If yes, return TRUE\"\"\"\n \n if doneButton.clicked(mousePress):\n return True\n else:\n return False\n \n \ndef resetButtons(buttonLst):\n \"\"\"Activates buttons in buttonLst\"\"\"\n \n for i in buttonLst:\n i.activate()\n \n \ndef placeCenter(win, clickButton, doneButton, centerPtLst, genRingLst, buttonsLst, color, label):\n \"\"\"Places a center when the corresponding button is pressed\"\"\"\n\n #Deactivate other buttons (not DONE or the selected button)\n deactButtons = buttonsLst[:-1]\n deactButtons.remove(clickButton)\n for i in deactButtons:\n i.deactivate()\n \n while clickButton.getOutlineColor() == 'yellow':\n mousePress = win.getMouse()\n if checkDone(mousePress, doneButton) == False:\n \n centerPtLst.append(win.getMouse())\n \n ring = Ring(win, centerPtLst[-1], 10, color, label)\n genRingLst.append(ring)\n \n elif checkDone(mousePress, doneButton) == True:\n resetButtons(buttonsLst)\n \n \ndef convertCenter2nm(pixelCenter, conversionFactor):\n \"\"\"Converts center point in pixels to nanometers given facor in nm/pixels\"\"\"\n \n x, y = pixelCenter.getX(), pixelCenter.getY()\n return (x * conversionFactor, y * conversionFactor)\n\n\ndef plotDistribution(labelLst, colorLst, centerPointsLst):\n \"\"\"Plots the distribution of atoms and ring sizes\n Note: centerPointsLst is a nested list of all center points\"\"\"\n\n datas = []\n for i in range(len(labelLst)):\n datas.append({'label': labelLst[i], 'color': colorLst[i], 'height': len(centerPointsLst[i])}) \n \n i = 0\n for data in datas:\n plt.bar(i, data['height'],align='center',color=data['color'])\n i += 1\n \n labels = [data['label'] for data in datas]\n pos = [i for i in range(len(datas)) ]\n plt.xticks(pos, labels)\n plt.xlabel('Atom / Ring Size')\n plt.ylabel('Number of Atoms / Rings')\n plt.title('Distribution of Atoms / Ring Sizes')\n plt.show()\n \n \ndef errorMessage(message):\n \"\"\"Displays an error message in a new window\"\"\"\n \n win = graphics.GraphWin('Error Message', 350, 175)\n win.setBackground('#F75454')\n \n \n error = graphics.Text(graphics.Point(win.getWidth()/2, win.getHeight()/2 - 50), 'Error')\n error.setSize(30)\n error.setStyle('bold')\n error.draw(win) \n \n text = graphics.Text(graphics.Point(win.getWidth()/2, win.getHeight()/2), message)\n text.setFace('times roman')\n text.draw(win)\n \n #Press OK button to close the window\n okButton = Button(win, graphics.Point(win.getWidth()/2, win.getHeight()/2 + 55), 100, 30, 'lightgrey', 'OK')\n loop = True\n while loop:\n mousePress = win.getMouse()", "answers": [" if okButton.clicked(mousePress):"], "length": 859, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "01fdef44-b838-4e4e-acf1-5bd70bcbe7a0", "reasoning": "In the errorMessage function, after entering a loop that captures mouse clicks, the next logical step is to check whether the OK button was clicked. This mirrors typical GUI patterns in the script where button clicks are detected inside a loop. Therefore, the line following 'mousePress = win.getMouse()' should be an if statement testing the OK button.", "reasoning_model_answer": "if okButton.clicked(mousePress):", "assistant_with_reasoning": "\nIn the errorMessage function, after entering a loop that captures mouse clicks, the next logical step is to check whether the OK button was clicked. This mirrors typical GUI patterns in the script where button clicks are detected inside a loop. Therefore, the line following 'mousePress = win.getMouse()' should be an if statement testing the OK button.\n\nif okButton.clicked(mousePress):", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.903, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 8620, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "if okButton.clicked(mousePress):", "score": 0.89, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/*\n * Copyright 2012-present Facebook, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n * not use this file except in compliance with the License. You may obtain\n * a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n * License for the specific language governing permissions and limitations\n * under the License.\n */\n\npackage com.facebook.buck.command;\n\nimport static com.facebook.buck.testutil.MoreAsserts.assertListEquals;\nimport static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.assertSame;\nimport static org.junit.Assert.fail;\n\nimport com.facebook.buck.android.AndroidBinaryRule;\nimport com.facebook.buck.android.AndroidLibraryRule;\nimport com.facebook.buck.android.AndroidResourceRule;\nimport com.facebook.buck.android.NdkLibrary;\nimport com.facebook.buck.command.Project.SourceFolder;\nimport com.facebook.buck.java.DefaultJavaLibraryRule;\nimport com.facebook.buck.java.JavaLibraryRule;\nimport com.facebook.buck.java.JavaTestRule;\nimport com.facebook.buck.java.Keystore;\nimport com.facebook.buck.java.PrebuiltJarRule;\nimport com.facebook.buck.model.BuildTarget;\nimport com.facebook.buck.model.BuildTargetFactory;\nimport com.facebook.buck.model.BuildTargetPattern;\nimport com.facebook.buck.model.SingletonBuildTargetPattern;\nimport com.facebook.buck.parser.PartialGraph;\nimport com.facebook.buck.parser.PartialGraphFactory;\nimport com.facebook.buck.rules.BuildRule;\nimport com.facebook.buck.rules.BuildRuleResolver;\nimport com.facebook.buck.rules.DependencyGraph;\nimport com.facebook.buck.rules.FakeAbstractBuildRuleBuilderParams;\nimport com.facebook.buck.rules.FileSourcePath;\nimport com.facebook.buck.rules.JavaPackageFinder;\nimport com.facebook.buck.rules.ProjectConfigRule;\nimport com.facebook.buck.step.ExecutionContext;\nimport com.facebook.buck.testutil.BuckTestConstant;\nimport com.facebook.buck.testutil.RuleMap;\nimport com.facebook.buck.util.HumanReadableException;\nimport com.facebook.buck.util.ProjectFilesystem;\nimport com.google.common.base.Function;\nimport com.google.common.base.Optional;\nimport com.google.common.base.Preconditions;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.Iterables;\n\nimport org.easymock.EasyMock;\nimport org.junit.Test;\n\nimport java.io.IOException;\nimport java.nio.file.Path;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Properties;\n\nimport javax.annotation.Nullable;\n\npublic class ProjectTest {\n\n private static final String PATH_TO_GUAVA_JAR = \"third_party/guava/guava-10.0.1.jar\";\n\n @SuppressWarnings(\"PMD.UnusedPrivateField\")\n private PrebuiltJarRule guava;\n\n /**\n * Creates a PartialGraph with two android_binary rules, each of which depends on the same\n * android_library. The difference between the two is that one lists Guava in its no_dx list and\n * the other does not.\n *

    \n * The PartialGraph also includes three project_config rules: one for the android_library, and one\n * for each of the android_binary rules.\n */\n public ProjectWithModules createPartialGraphForTesting(\n @Nullable JavaPackageFinder javaPackageFinder) throws IOException {\n BuildRuleResolver ruleResolver = new BuildRuleResolver();\n\n // java_library //buck-out/android/com/facebook:R\n ruleResolver.buildAndAddToIndex(\n DefaultJavaLibraryRule.newJavaLibraryRuleBuilder(new FakeAbstractBuildRuleBuilderParams())\n .setBuildTarget(BuildTargetFactory.newInstance(\"//buck-out/android/com/facebook:R\"))\n .addSrc(\"buck-out/android/com/facebook/R.java\")\n .addVisibilityPattern(BuildTargetPattern.MATCH_ALL));\n\n // prebuilt_jar //third_party/guava:guava\n guava = ruleResolver.buildAndAddToIndex(\n PrebuiltJarRule.newPrebuiltJarRuleBuilder(new FakeAbstractBuildRuleBuilderParams())\n .setBuildTarget(BuildTargetFactory.newInstance(\"//third_party/guava:guava\"))\n .setBinaryJar(PATH_TO_GUAVA_JAR)\n .addVisibilityPattern(BuildTargetPattern.MATCH_ALL));\n\n // android_resouce android_res/base:res\n ruleResolver.buildAndAddToIndex(\n AndroidResourceRule.newAndroidResourceRuleBuilder(new FakeAbstractBuildRuleBuilderParams())\n .setBuildTarget(BuildTargetFactory.newInstance(\"//android_res/base:res\"))\n .setRes(\"android_res/base/res\")\n .setRDotJavaPackage(\"com.facebook\")\n .addVisibilityPattern(BuildTargetPattern.MATCH_ALL));\n\n // project_config android_res/base:res\n ProjectConfigRule projectConfigRuleForResource = ruleResolver.buildAndAddToIndex(\n ProjectConfigRule.newProjectConfigRuleBuilder(new FakeAbstractBuildRuleBuilderParams())\n .setBuildTarget(BuildTargetFactory.newInstance(\"//android_res/base:project_config\"))\n .setSrcTarget(Optional.of(BuildTargetFactory.newInstance(\"//android_res/base:res\")))\n .setSrcRoots(ImmutableList.of(\"res\")));\n\n // java_library //java/src/com/facebook/grandchild:grandchild\n BuildTarget grandchild = BuildTargetFactory.newInstance(\n \"//java/src/com/facebook/grandchild:grandchild\");\n ruleResolver.buildAndAddToIndex(\n DefaultJavaLibraryRule.newJavaLibraryRuleBuilder(new FakeAbstractBuildRuleBuilderParams())\n .setBuildTarget(grandchild)\n .addSrc(\"Grandchild.java\")\n .addVisibilityPattern(BuildTargetPattern.MATCH_ALL));\n\n // java_library //java/src/com/facebook/child:child\n ruleResolver.buildAndAddToIndex(\n DefaultJavaLibraryRule.newJavaLibraryRuleBuilder(new FakeAbstractBuildRuleBuilderParams())\n .setBuildTarget(BuildTargetFactory.newInstance(\n \"//java/src/com/facebook/child:child\"))\n .addSrc(\"Child.java\")\n .addDep(grandchild)\n .addVisibilityPattern(BuildTargetPattern.MATCH_ALL));\n\n // java_library //java/src/com/facebook/exportlib:exportlib\n ruleResolver.buildAndAddToIndex(\n DefaultJavaLibraryRule.newJavaLibraryRuleBuilder(new FakeAbstractBuildRuleBuilderParams())\n .setBuildTarget(BuildTargetFactory.newInstance(\n \"//java/src/com/facebook/exportlib:exportlib\"))\n .addSrc(\"ExportLib.java\")\n .addDep(BuildTargetFactory.newInstance(\"//third_party/guava:guava\"))\n .addExportedDep(BuildTargetFactory.newInstance(\"//third_party/guava:guava\"))\n .addVisibilityPattern(BuildTargetPattern.MATCH_ALL));\n\n // android_library //java/src/com/facebook/base:base\n ruleResolver.buildAndAddToIndex(\n AndroidLibraryRule.newAndroidLibraryRuleBuilder(new FakeAbstractBuildRuleBuilderParams())\n .setBuildTarget(BuildTargetFactory.newInstance(\"//java/src/com/facebook/base:base\"))\n .addSrc(\"Base.java\")\n .addDep(BuildTargetFactory.newInstance(\"//buck-out/android/com/facebook:R\"))\n .addDep(BuildTargetFactory.newInstance(\"//java/src/com/facebook/exportlib:exportlib\"))\n .addDep(BuildTargetFactory.newInstance(\"//java/src/com/facebook/child:child\"))\n .addDep(BuildTargetFactory.newInstance(\"//android_res/base:res\"))\n .addVisibilityPattern(BuildTargetPattern.MATCH_ALL));\n\n // project_config //java/src/com/facebook/base:project_config\n ProjectConfigRule projectConfigRuleForLibrary = ruleResolver.buildAndAddToIndex(\n ProjectConfigRule.newProjectConfigRuleBuilder(new FakeAbstractBuildRuleBuilderParams())\n .setBuildTarget(BuildTargetFactory.newInstance(\n \"//java/src/com/facebook/base:project_config\"))\n .setSrcTarget(Optional.of(BuildTargetFactory.newInstance(\n \"//java/src/com/facebook/base:base\")))\n .setSrcRoots(ImmutableList.of(\"src\", \"src-gen\")));\n\n ProjectConfigRule projectConfigRuleForExportLibrary = ruleResolver.buildAndAddToIndex(\n ProjectConfigRule.newProjectConfigRuleBuilder(new FakeAbstractBuildRuleBuilderParams())\n .setBuildTarget(BuildTargetFactory.newInstance(\n \"//java/src/com/facebook/exportlib:project_config\"))\n .setSrcTarget(Optional.of(BuildTargetFactory.newInstance(\n \"//java/src/com/facebook/exportlib:exportlib\")))\n .setSrcRoots(ImmutableList.of(\"src\")));\n\n // keystore //keystore:debug\n BuildTarget keystoreTarget = BuildTargetFactory.newInstance(\"//keystore:debug\");\n ruleResolver.buildAndAddToIndex(\n Keystore.newKeystoreBuilder(new FakeAbstractBuildRuleBuilderParams())\n .setBuildTarget(keystoreTarget)\n .setStore(\"keystore/debug.keystore\")\n .setProperties(\"keystore/debug.keystore.properties\")\n .addVisibilityPattern(BuildTargetPattern.MATCH_ALL));\n\n // android_binary //foo:app\n ruleResolver.buildAndAddToIndex(\n AndroidBinaryRule.newAndroidBinaryRuleBuilder(new FakeAbstractBuildRuleBuilderParams())\n .setBuildTarget(BuildTargetFactory.newInstance(\"//foo:app\"))\n .addClasspathDep(BuildTargetFactory.newInstance(\"//java/src/com/facebook/base:base\"))\n .setManifest(new FileSourcePath(\"foo/AndroidManifest.xml\"))\n .setTarget(\"Google Inc.:Google APIs:16\")\n .setKeystore(keystoreTarget)\n .addBuildRuleToExcludeFromDex(BuildTargetFactory.newInstance(\"//third_party/guava:guava\")));\n\n // project_config //foo:project_config\n ProjectConfigRule projectConfigRuleUsingNoDx = ruleResolver.buildAndAddToIndex(\n ProjectConfigRule.newProjectConfigRuleBuilder(new FakeAbstractBuildRuleBuilderParams())\n .setBuildTarget(BuildTargetFactory.newInstance(\"//foo:project_config\"))\n .setSrcTarget(Optional.of(BuildTargetFactory.newInstance(\"//foo:app\"))));\n\n // android_binary //bar:app\n ruleResolver.buildAndAddToIndex(\n AndroidBinaryRule.newAndroidBinaryRuleBuilder(new FakeAbstractBuildRuleBuilderParams())\n .setBuildTarget(BuildTargetFactory.newInstance(\"//bar:app\"))\n .addClasspathDep(BuildTargetFactory.newInstance(\"//java/src/com/facebook/base:base\"))\n .setManifest(new FileSourcePath(\"foo/AndroidManifest.xml\"))\n .setTarget(\"Google Inc.:Google APIs:16\")\n .setKeystore(keystoreTarget));\n\n // project_config //bar:project_config\n ProjectConfigRule projectConfigRule = ruleResolver.buildAndAddToIndex(\n ProjectConfigRule.newProjectConfigRuleBuilder(new FakeAbstractBuildRuleBuilderParams())\n .setBuildTarget(BuildTargetFactory.newInstance(\"//bar:project_config\"))\n .setSrcTarget(Optional.of(BuildTargetFactory.newInstance(\"//bar:app\"))));\n\n return getModulesForPartialGraph(ruleResolver,\n ImmutableList.of(\n projectConfigRuleForExportLibrary,\n projectConfigRuleForLibrary,\n projectConfigRuleForResource,\n projectConfigRuleUsingNoDx,\n projectConfigRule),\n javaPackageFinder);\n }\n\n @Test\n public void testGenerateRelativeGenPath() {\n String basePathOfModuleWithSlash = \"android_res/com/facebook/gifts/\";\n Path expectedRelativePathToGen =\n java.nio.file.Paths.get(\"/../../../../buck-out/android/android_res/com/facebook/gifts/gen\");\n assertEquals(\n expectedRelativePathToGen, Project.generateRelativeGenPath(basePathOfModuleWithSlash));\n }\n\n /**\n * This is an important test that verifies that the {@code no_dx} argument for an\n * {@code android_binary} is handled appropriately when generating an IntelliJ project.\n */\n @Test\n public void testProject() throws IOException {\n JavaPackageFinder javaPackageFinder = EasyMock.createMock(JavaPackageFinder.class);\n EasyMock.expect(javaPackageFinder.findJavaPackageForPath(\"foo/module_foo.iml\")).andReturn(\"\");\n EasyMock.expect(javaPackageFinder.findJavaPackageForPath(\"bar/module_bar.iml\")).andReturn(\"\");\n EasyMock.replay(javaPackageFinder);\n\n ProjectWithModules projectWithModules = createPartialGraphForTesting(javaPackageFinder);\n Project project = projectWithModules.project;\n PartialGraph partialGraph = project.getPartialGraph();\n List modules = projectWithModules.modules;\n\n assertEquals(\"Should be one module for the java_library, one for the android_library, \" +\n \"one module for the android_resource, and one for each android_binary\",\n 5,\n modules.size());\n\n // Check the values of the module that corresponds to the android_library.\n Module javaLibraryModule = modules.get(0);\n assertSame(getRuleById(\"//java/src/com/facebook/exportlib:exportlib\", partialGraph),\n javaLibraryModule.srcRule);\n assertEquals(\"module_java_src_com_facebook_exportlib\", javaLibraryModule.name);\n assertEquals(\"java/src/com/facebook/exportlib/module_java_src_com_facebook_exportlib.iml\",\n javaLibraryModule.pathToImlFile);\n assertListEquals(\n ImmutableList.of(SourceFolder.SRC),\n javaLibraryModule.sourceFolders);\n\n // Check the dependencies.\n DependentModule inheritedJdk = DependentModule.newInheritedJdk();\n DependentModule guavaAsProvidedDep = DependentModule.newLibrary(\n guava.getBuildTarget(), \"third_party_guava_guava_10_0_1_jar\");\n guavaAsProvidedDep.scope = \"PROVIDED\";\n\n assertListEquals(\n ImmutableList.of(\n DependentModule.newSourceFolder(),\n guavaAsProvidedDep,\n DependentModule.newStandardJdk()),\n javaLibraryModule.dependencies);\n\n // Check the values of the module that corresponds to the android_library.\n Module androidLibraryModule = modules.get(1);\n assertSame(getRuleById(\"//java/src/com/facebook/base:base\", partialGraph),\n androidLibraryModule.srcRule);\n assertEquals(\"module_java_src_com_facebook_base\", androidLibraryModule.name);\n assertEquals(\"java/src/com/facebook/base/module_java_src_com_facebook_base.iml\",\n androidLibraryModule.pathToImlFile);\n assertListEquals(\n ImmutableList.of(\n SourceFolder.SRC,\n new SourceFolder(\"file://$MODULE_DIR$/src-gen\", false /* isTestSource */),\n SourceFolder.GEN),\n androidLibraryModule.sourceFolders);\n assertEquals(Boolean.TRUE, androidLibraryModule.hasAndroidFacet);\n assertEquals(Boolean.TRUE, androidLibraryModule.isAndroidLibraryProject);\n assertEquals(null, androidLibraryModule.proguardConfigPath);\n assertEquals(null, androidLibraryModule.resFolder);\n\n // Check the dependencies.\n DependentModule androidResourceAsProvidedDep = DependentModule.newModule(\n BuildTargetFactory.newInstance(\"//android_res/base:res\"),\n \"module_android_res_base\");\n\n DependentModule childAsProvidedDep = DependentModule.newModule(\n BuildTargetFactory.newInstance(\"//java/src/com/facebook/child:child\"),\n \"module_java_src_com_facebook_child\");\n\n DependentModule exportDepsAsProvidedDep = DependentModule.newModule(\n BuildTargetFactory.newInstance(\"//java/src/com/facebook/exportlib:exportlib\"),\n \"module_java_src_com_facebook_exportlib\");\n\n assertListEquals(\n ImmutableList.of(\n DependentModule.newSourceFolder(),\n guavaAsProvidedDep,\n androidResourceAsProvidedDep,\n childAsProvidedDep,\n exportDepsAsProvidedDep,\n inheritedJdk),\n androidLibraryModule.dependencies);\n\n // Check the values of the module that corresponds to the android_binary that uses no_dx.\n Module androidResourceModule = modules.get(2);\n assertSame(getRuleById(\"//android_res/base:res\", partialGraph), androidResourceModule.srcRule);\n\n assertEquals(\"/res\", androidResourceModule.resFolder);\n\n // Check the values of the module that corresponds to the android_binary that uses no_dx.\n Module androidBinaryModuleNoDx = modules.get(3);\n assertSame(getRuleById(\"//foo:app\", partialGraph), androidBinaryModuleNoDx.srcRule);\n assertEquals(\"module_foo\", androidBinaryModuleNoDx.name);\n assertEquals(\"foo/module_foo.iml\", androidBinaryModuleNoDx.pathToImlFile);\n\n assertListEquals(ImmutableList.of(SourceFolder.GEN), androidBinaryModuleNoDx.sourceFolders);\n assertEquals(Boolean.TRUE, androidBinaryModuleNoDx.hasAndroidFacet);\n assertEquals(Boolean.FALSE, androidBinaryModuleNoDx.isAndroidLibraryProject);\n assertEquals(null, androidBinaryModuleNoDx.proguardConfigPath);\n assertEquals(null, androidBinaryModuleNoDx.resFolder);\n assertEquals(\"../keystore/debug.keystore\", androidBinaryModuleNoDx.keystorePath);\n\n // Check the dependencies.\n DependentModule grandchildAsProvidedDep = DependentModule.newModule(\n BuildTargetFactory.newInstance(\"//java/src/com/facebook/grandchild:grandchild\"),\n \"module_java_src_com_facebook_grandchild\"\n );\n\n DependentModule androidLibraryDep = DependentModule.newModule(\n androidLibraryModule.srcRule.getBuildTarget(), \"module_java_src_com_facebook_base\");\n assertEquals(\n ImmutableList.of(\n DependentModule.newSourceFolder(),\n guavaAsProvidedDep,\n androidLibraryDep,\n androidResourceAsProvidedDep,\n childAsProvidedDep,\n exportDepsAsProvidedDep,\n grandchildAsProvidedDep,\n inheritedJdk),\n androidBinaryModuleNoDx.dependencies);\n\n // Check the values of the module that corresponds to the android_binary with an empty no_dx.\n Module androidBinaryModuleEmptyNoDx = modules.get(4);\n assertSame(getRuleById(\"//bar:app\", partialGraph), androidBinaryModuleEmptyNoDx.srcRule);\n assertEquals(\"module_bar\", androidBinaryModuleEmptyNoDx.name);\n assertEquals(\"bar/module_bar.iml\", androidBinaryModuleEmptyNoDx.pathToImlFile);\n assertListEquals(\n ImmutableList.of(SourceFolder.GEN), androidBinaryModuleEmptyNoDx.sourceFolders);\n assertEquals(Boolean.TRUE, androidBinaryModuleEmptyNoDx.hasAndroidFacet);", "answers": [" assertEquals(Boolean.FALSE, androidBinaryModuleEmptyNoDx.isAndroidLibraryProject);"], "length": 828, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "ca061dac-4d1d-4b35-a613-3975e1f8c142", "reasoning": "The test method is checking properties of the androidBinaryModuleEmptyNoDx module. Following the pattern used earlier for androidBinaryModuleNoDx, after asserting hasAndroidFacet the next assertion checks whether the module is an Android library project. Therefore the next line should assert that isAndroidLibraryProject is false.", "reasoning_model_answer": "assertEquals(Boolean.FALSE, androidBinaryModuleEmptyNoDx.isAndroidLibraryProject);", "assistant_with_reasoning": "\nThe test method is checking properties of the androidBinaryModuleEmptyNoDx module. Following the pattern used earlier for androidBinaryModuleNoDx, after asserting hasAndroidFacet the next assertion checks whether the module is an Android library project. Therefore the next line should assert that isAndroidLibraryProject is false.\n\nassertEquals(Boolean.FALSE, androidBinaryModuleEmptyNoDx.isAndroidLibraryProject);", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.578, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 17965, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "assertEquals(Boolean.FALSE, androidBinaryModuleEmptyNoDx.isAndroidLibraryProject);", "score": 0.98, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "package xeadModeler;\n\n/*\n * Copyright (c) 2014 WATANABE kozo ,\n * All rights reserved.\n *\n * This file is part of XEAD Modeler.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n * * Neither the name of the XEAD Project nor the names of its contributors\n * may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n\nimport java.awt.*;\n\nimport javax.swing.*;\n\nimport java.awt.event.*;\n\nimport xeadModeler.Modeler.*;\n\nimport java.util.ArrayList;\nimport java.util.ResourceBundle;\n\npublic class DialogDataflowLine extends JDialog {\n\tprivate static final long serialVersionUID = 1L;\n\tprivate static ResourceBundle res = ResourceBundle.getBundle(\"xeadModeler.Res\");\n\tprivate JPanel panelMain = new JPanel();\n\tprivate JLabel jLabel1 = new JLabel();\n\tprivate JComboBox jComboBoxNode1 = new JComboBox();\n\tprivate ButtonGroup buttonGroupArrowStyle = new ButtonGroup();\n\tprivate JLabel jLabel2 = new JLabel();\n\tprivate JPanel jPanel1 = new JPanel();\n\tprivate JRadioButton jRadioButtonArrowStyle3 = new JRadioButton();\n\tprivate JRadioButton jRadioButtonArrowStyle1 = new JRadioButton();\n\tprivate JRadioButton jRadioButtonArrowStyle2 = new JRadioButton();\n\tprivate JPanel jPanel2 = new JPanel();\n\tprivate JRadioButton jRadioButtonIcon7 = new JRadioButton();\n\tprivate GridLayout gridLayout1 = new GridLayout();\n\tprivate ButtonGroup buttonGroupIcon = new ButtonGroup();\n\tprivate JRadioButton jRadioButtonIcon9 = new JRadioButton();\n\tprivate JRadioButton jRadioButtonIcon10 = new JRadioButton();\n\tprivate JRadioButton jRadioButtonIcon11 = new JRadioButton();\n\tprivate JRadioButton jRadioButtonIcon14 = new JRadioButton();\n\tprivate JRadioButton jRadioButtonIcon12 = new JRadioButton();\n\tprivate JRadioButton jRadioButtonIcon13 = new JRadioButton();\n\tprivate JRadioButton jRadioButtonIcon8 = new JRadioButton();\n\tprivate JRadioButton jRadioButtonIcon15 = new JRadioButton();\n\tprivate JRadioButton jRadioButtonIcon16 = new JRadioButton();\n\tprivate JRadioButton jRadioButtonIcon17 = new JRadioButton();\n\tprivate JRadioButton jRadioButtonIcon18 = new JRadioButton();\n\tprivate JRadioButton jRadioButtonIcon19 = new JRadioButton();\n\tprivate JRadioButton jRadioButtonIcon20 = new JRadioButton();\n\tprivate JRadioButton jRadioButtonIcon6 = new JRadioButton();\n\tprivate JRadioButton jRadioButtonIcon5 = new JRadioButton();\n\tprivate JRadioButton jRadioButtonIcon4 = new JRadioButton();\n\tprivate JRadioButton jRadioButtonIcon3 = new JRadioButton();\n\tprivate JRadioButton jRadioButtonIcon2 = new JRadioButton();\n\tprivate JRadioButton jRadioButtonIcon1 = new JRadioButton();\n\tprivate JButton jButtonOK = new JButton();\n\tprivate JButton jButtonCancel = new JButton();\n\tprivate GridLayout gridLayout2 = new GridLayout();\n\tprivate JLabel jLabel3 = new JLabel();\n\tprivate KanjiTextField jTextFieldName = new KanjiTextField();\n\tprivate KanjiTextField jTextFieldNameExt = new KanjiTextField();\n\tprivate JLabel jLabel4 = new JLabel();\n\tprivate JLabel jLabel5 = new JLabel();\n\tprivate JComboBox jComboBoxNode2 = new JComboBox();\n\tprivate boolean buttonOKIsPressed = false;\n\tprivate Modeler frame_;\n\tprivate JLabel jLabel6 = new JLabel();\n\tprivate DataflowNode[] storageArray1 = new DataflowNode[100];\n\tprivate DataflowNode[] storageArray2 = new DataflowNode[100];\n\tprivate ImageIcon iconFlow10, iconFlow11, iconFlow20, iconFlow21, iconFlow30, iconFlow31;\n\n\tpublic DialogDataflowLine(Modeler frame, String title, boolean modal) {\n\t\tsuper(frame, title, modal);\n\t\ttry {\n\t\t\tframe_ = frame;\n\t\t\tjbInit();\n\t\t\tpack();\n\t\t}\n\t\tcatch(Exception ex) {\n\t\t\tex.printStackTrace();\n\t\t}\n\t}\n\n\tpublic DialogDataflowLine(Modeler frame) {\n\t\tthis(frame, \"\", true);\n\t}\n\n\tprivate void jbInit() throws Exception {\n\t\tpanelMain.setLayout(null);\n\t\tpanelMain.setPreferredSize(new Dimension(482, 427));\n\t\tpanelMain.setBorder(BorderFactory.createEtchedBorder());\n\t\tthis.setResizable(false);\n\t\tthis.setTitle(\"\");\n\n\t\ticonFlow10 = new ImageIcon(xeadModeler.DialogDataflowLine.class.getResource(\"flow10.png\"));\n\t\ticonFlow11 = new ImageIcon(xeadModeler.DialogDataflowLine.class.getResource(\"flow11.png\"));\n\t\ticonFlow20 = new ImageIcon(xeadModeler.DialogDataflowLine.class.getResource(\"flow20.png\"));\n\t\ticonFlow21 = new ImageIcon(xeadModeler.DialogDataflowLine.class.getResource(\"flow21.png\"));\n\t\ticonFlow30 = new ImageIcon(xeadModeler.DialogDataflowLine.class.getResource(\"flow30.png\"));\n\t\ticonFlow31 = new ImageIcon(xeadModeler.DialogDataflowLine.class.getResource(\"flow31.png\"));\n\n\t\tjLabel3.setFont(new java.awt.Font(frame_.mainFontName, 0, Modeler.MAIN_FONT_SIZE));\n\t\tjLabel3.setHorizontalAlignment(SwingConstants.RIGHT);\n\t\tjLabel3.setText(res.getString(\"DialogDataflowLine27\"));\n\t\tjLabel3.setBounds(new Rectangle(5, 12, 130, 20));\n\t\tjTextFieldName.setFont(new java.awt.Font(frame_.mainFontName, 0, Modeler.MAIN_FONT_SIZE));\n\t\tjTextFieldName.setBounds(new Rectangle(140, 9, 150, 25));\n\t\tjTextFieldNameExt.setFont(new java.awt.Font(frame_.mainFontName, 0, Modeler.MAIN_FONT_SIZE));\n\t\tjTextFieldNameExt.setBounds(new Rectangle(295, 9, 150, 25));\n\n\t\tjLabel6.setFont(new java.awt.Font(frame_.mainFontName, 0, Modeler.MAIN_FONT_SIZE));\n\t\tjLabel6.setHorizontalAlignment(SwingConstants.RIGHT);", "answers": ["\t\tjLabel6.setText(res.getString(\"DialogDataflowLine30\"));"], "length": 684, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "602e735d-edcb-4b78-be52-c2dd4f9cce06", "reasoning": "In the jbInit method, after configuring jLabel6's font and alignment, the typical pattern is to set its displayed text using the resource bundle, just as was done for jLabel3. The next logical line therefore sets the label's text, likely using the next resource key (DialogDataflowLine28).", "reasoning_model_answer": "jLabel6.setText(res.getString(\"DialogDataflowLine28\"));", "assistant_with_reasoning": "\nIn the jbInit method, after configuring jLabel6's font and alignment, the typical pattern is to set its displayed text using the resource bundle, just as was done for jLabel3. The next logical line therefore sets the label's text, likely using the next resource key (DialogDataflowLine28).\n\njLabel6.setText(res.getString(\"DialogDataflowLine28\"));", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.634, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 6603, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "jLabel6.setText(res.getString(\"DialogDataflowLine28\"));", "score": 0.95, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "package com.adobe.epubcheck.ops;\n\nimport java.util.Collections;\nimport java.util.EnumSet;\nimport java.util.HashSet;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\nimport com.adobe.epubcheck.api.EPUBLocation;\nimport com.adobe.epubcheck.api.EPUBProfile;\nimport com.adobe.epubcheck.messages.MessageId;\nimport com.adobe.epubcheck.opf.OPFChecker;\nimport com.adobe.epubcheck.opf.OPFChecker30;\nimport com.adobe.epubcheck.opf.ValidationContext;\nimport com.adobe.epubcheck.opf.XRefChecker;\nimport com.adobe.epubcheck.util.EpubConstants;\nimport com.adobe.epubcheck.util.FeatureEnum;\nimport com.adobe.epubcheck.util.PathUtil;\nimport com.adobe.epubcheck.vocab.AggregateVocab;\nimport com.adobe.epubcheck.vocab.AltStylesheetVocab;\nimport com.adobe.epubcheck.vocab.DataNavVocab;\nimport com.adobe.epubcheck.vocab.DictVocab;\nimport com.adobe.epubcheck.vocab.EnumVocab;\nimport com.adobe.epubcheck.vocab.EpubCheckVocab;\nimport com.adobe.epubcheck.vocab.IndexVocab;\nimport com.adobe.epubcheck.vocab.PackageVocabs;\nimport com.adobe.epubcheck.vocab.PackageVocabs.ITEM_PROPERTIES;\nimport com.adobe.epubcheck.vocab.Property;\nimport com.adobe.epubcheck.vocab.StagingEdupubVocab;\nimport com.adobe.epubcheck.vocab.StructureVocab;\nimport com.adobe.epubcheck.vocab.StructureVocab.EPUB_TYPES;\nimport com.adobe.epubcheck.vocab.Vocab;\nimport com.adobe.epubcheck.vocab.VocabUtil;\nimport com.adobe.epubcheck.xml.XMLAttribute;\nimport com.adobe.epubcheck.xml.XMLElement;\nimport com.adobe.epubcheck.xml.XMLParser;\nimport com.google.common.base.Joiner;\nimport com.google.common.collect.Collections2;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Sets;\n\npublic class OPSHandler30 extends OPSHandler\n{\n\n private static final Pattern DATA_URI_PATTERN = Pattern.compile(\"^data:([^;]*)[^,]*,.*\");\n\n private static Map RESERVED_VOCABS = ImmutableMap. of(\"\",\n AggregateVocab.of(StructureVocab.VOCAB, StagingEdupubVocab.VOCAB, DataNavVocab.VOCAB,\n DictVocab.VOCAB, IndexVocab.VOCAB));\n private static Map ALTCSS_VOCABS = ImmutableMap. of(\"\",\n AltStylesheetVocab.VOCAB);\n private static Map KNOWN_VOCAB_URIS = ImmutableMap.of();\n private static Set DEFAULT_VOCAB_URIS = ImmutableSet.of(StructureVocab.URI);\n\n private Map vocabs = RESERVED_VOCABS;\n\n private final Set requiredProperties = EnumSet.noneOf(ITEM_PROPERTIES.class);\n private final Set allowedProperties = EnumSet.noneOf(ITEM_PROPERTIES.class);\n\n private final boolean isLinear;\n\n protected boolean inVideo = false;\n protected boolean inAudio = false;\n protected boolean hasValidFallback = false;\n\n protected int imbricatedObjects = 0;\n protected int imbricatedCanvases = 0;\n\n protected boolean anchorNeedsText = false;\n protected boolean inMathML = false;\n protected boolean inSvg = false;\n protected boolean inBody = false;\n protected boolean inRegionBasedNav = false;\n protected boolean hasAltorAnnotation = false;\n\n static protected final String[] scriptEventsStrings = { \"onafterprint\", \"onbeforeprint\",\n \"onbeforeunload\", \"onerror\", \"onhaschange\", \"onload\", \"onmessage\", \"onoffline\", \"onpagehide\",\n \"onpageshow\", \"onpopstate\", \"onredo\", \"onresize\", \"onstorage\", \"onundo\", \"onunload\",\n\n \"onblur\", \"onchange\", \"oncontextmenu\", \"onfocus\", \"onformchange\", \"onforminput\", \"oninput\",\n \"oninvalid\", \"onreset\", \"onselect\", \"onsubmit\",\n\n \"onkeydown\", \"onkeypress\", \"onkeyup\",\n\n \"onabort\", \"oncanplay\", \"oncanplaythrough\", \"ondurationchange\", \"onemptied\", \"onended\",\n \"onerror\", \"onloadeddata\", \"onloadedmetadata\", \"onloadstart\", \"onpause\", \"onplay\",\n \"onplaying\", \"onprogress\", \"onratechange\", \"onreadystatechange\", \"onseeked\", \"onseeking\",\n \"onstalled\", \"onsuspend\", \"ontimeupdate\", \"onvolumechange\", \"onwaiting\" };\n\n static protected HashSet scriptEvents;\n\n public static HashSet getScriptEvents()\n {\n if (scriptEvents == null)\n {\n scriptEvents = new HashSet();\n Collections.addAll(scriptEvents, scriptEventsStrings);\n Collections.addAll(scriptEvents, mouseEventsStrings);\n }\n return scriptEvents;\n }\n\n static protected final String[] mouseEventsStrings = { \"onclick\", \"ondblclick\", \"ondrag\",\n \"ondragend\", \"ondragenter\", \"ondragleave\", \"ondragover\", \"ondragstart\", \"ondrop\",\n \"onmousedown\", \"onmousemove\", \"onmouseout\", \"onmouseover\", \"onmouseup\", \"onmousewheel\",\n \"onscroll\" };\n static protected HashSet mouseEvents;\n\n public static HashSet getMouseEvents()\n {\n if (mouseEvents == null)\n {\n mouseEvents = new HashSet();\n Collections.addAll(mouseEvents, mouseEventsStrings);\n }\n return mouseEvents;\n }\n\n public OPSHandler30(ValidationContext context, XMLParser parser)\n {\n super(context, parser);\n checkedUnsupportedXMLVersion = false;\n isLinear = !context.properties\n .contains(EpubCheckVocab.VOCAB.get(EpubCheckVocab.PROPERTIES.NON_LINEAR));\n }\n\n protected void checkType(XMLElement e, String type)\n {\n if (type == null)\n {\n return;\n }\n Set propList = VocabUtil.parsePropertyList(type, vocabs, report,\n EPUBLocation.create(path, parser.getLineNumber(), parser.getColumnNumber()));\n checkTypes(Property.filter(propList, StructureVocab.EPUB_TYPES.class));\n\n // Check the 'region-based' property (Data Navigation Documents)\n if (propList.contains(DataNavVocab.VOCAB.get(DataNavVocab.EPUB_TYPES.REGION_BASED)))\n\n {\n if (!\"nav\".equals(e.getName()) || !context.properties\n .contains(PackageVocabs.ITEM_VOCAB.get(PackageVocabs.ITEM_PROPERTIES.DATA_NAV)))\n {\n report.message(MessageId.HTM_052, parser.getLocation());\n }\n else\n {\n inRegionBasedNav = true;\n }\n }\n // Store whether the doc containt DICT content\n if (propList.contains(DictVocab.VOCAB.get(DictVocab.EPUB_TYPES.DICTIONARY)))\n {\n context.featureReport.report(FeatureEnum.DICTIONARY, parser.getLocation(), null);\n }\n }\n\n protected void checkTypes(Set types)\n {\n if (types.contains(EPUB_TYPES.PAGEBREAK))\n {\n context.featureReport.report(FeatureEnum.PAGE_BREAK, parser.getLocation(), null);\n }\n if (types.contains(EPUB_TYPES.INDEX))\n {\n allowedProperties.add(ITEM_PROPERTIES.INDEX);\n context.featureReport.report(FeatureEnum.INDEX, parser.getLocation(), null);\n }\n }\n\n protected void checkSSMLPh(String ph)\n {\n // issue 139; enhancement is to add real syntax check for IPA and x-SAMPA\n if (ph == null)\n {\n return;\n }\n if (ph.trim().length() < 1)\n {\n report.message(MessageId.HTM_007,\n EPUBLocation.create(path, parser.getLineNumber(), parser.getColumnNumber()));\n }\n }\n\n @Override\n public void characters(char[] chars, int arg1, int arg2)\n {\n super.characters(chars, arg1, arg2);\n String str = new String(chars, arg1, arg2);\n str = str.trim();\n if (!str.equals(\"\") && (inAudio || inVideo || imbricatedObjects > 0 || imbricatedCanvases > 0))\n {\n hasValidFallback = true;\n }\n if (anchorNeedsText)\n {\n anchorNeedsText = false;\n }\n }\n\n public void startElement()\n {\n super.startElement();\n\n XMLElement e = parser.getCurrentElement();\n String name = e.getName();\n\n processSemantics(e);\n processSectioning(e);\n\n if (name.equals(\"html\"))\n {\n vocabs = VocabUtil.parsePrefixDeclaration(\n e.getAttributeNS(EpubConstants.EpubTypeNamespaceUri, \"prefix\"), RESERVED_VOCABS,\n KNOWN_VOCAB_URIS, DEFAULT_VOCAB_URIS, report,\n EPUBLocation.create(path, parser.getLineNumber(), parser.getColumnNumber()));\n }\n else if (name.equals(\"link\"))\n {\n processLink(e);\n }\n else if (name.equals(\"object\"))\n {\n processObject(e);\n }\n else if (name.equals(\"math\"))\n {\n requiredProperties.add(ITEM_PROPERTIES.MATHML);\n inMathML = true;\n hasAltorAnnotation = (null != e.getAttribute(\"alttext\"));\n }\n else if (!context.mimeType.equals(\"image/svg+xml\") && name.equals(\"svg\"))\n {\n requiredProperties.add(ITEM_PROPERTIES.SVG);\n processStartSvg(e);\n }\n else if (name.equals(\"script\"))\n {\n requiredProperties.add(ITEM_PROPERTIES.SCRIPTED);\n }\n else if (!context.mimeType.equals(\"image/svg+xml\") && name.equals(\"switch\"))\n {\n requiredProperties.add(ITEM_PROPERTIES.SWITCH);\n }\n else if (name.equals(\"audio\"))\n {\n processAudio();\n }\n else if (name.equals(\"video\"))\n {\n processVideo(e);\n }\n else if (name.equals(\"figure\"))\n {\n processFigure(e);\n }\n else if (name.equals(\"table\"))\n {\n processTable(e);\n }\n else if (name.equals(\"canvas\"))\n {\n processCanvas();\n }\n else if (name.equals(\"img\"))\n {\n processImg();\n }\n else if (name.equals(\"a\"))\n {\n anchorNeedsText = true;\n processAnchor(e);\n }\n else if (name.equals(\"annotation-xml\"))\n {\n hasAltorAnnotation = true;\n }\n\n processInlineScripts(e);\n\n processSrc((\"source\".equals(name)) ? e.getParent().getName() : name, e.getAttribute(\"src\"));\n\n checkType(e, e.getAttributeNS(EpubConstants.EpubTypeNamespaceUri, \"type\"));\n\n checkSSMLPh(e.getAttributeNS(\"http://www.w3.org/2001/10/synthesis\", \"ph\"));\n }\n\n protected void processInlineScripts(com.adobe.epubcheck.xml.XMLElement e)\n {\n HashSet scriptEvents = getScriptEvents();\n HashSet mouseEvents = getMouseEvents();\n\n for (int i = 0; i < e.getAttributeCount(); ++i)\n {\n XMLAttribute attr = e.getAttribute(i);\n String name = attr.getName().toLowerCase();\n if (scriptEvents.contains(name) || mouseEvents.contains(name))\n {\n requiredProperties.add(ITEM_PROPERTIES.SCRIPTED);\n return;\n }\n }\n }\n\n protected void processLink(XMLElement e)\n {\n String classAttribute = e.getAttribute(\"class\");\n if (classAttribute == null)\n {\n return;\n }\n\n Set properties = VocabUtil.parsePropertyList(classAttribute, ALTCSS_VOCABS, report,\n EPUBLocation.create(path, parser.getLineNumber(), parser.getColumnNumber()));\n Set altClasses = Property.filter(properties,\n AltStylesheetVocab.PROPERTIES.class);\n\n if (properties.size() == 1)\n {\n return;\n }\n\n boolean vertical = altClasses.contains(AltStylesheetVocab.PROPERTIES.VERTICAL);\n boolean horizontal = altClasses.contains(AltStylesheetVocab.PROPERTIES.HORIZONTAL);\n boolean day = altClasses.contains(AltStylesheetVocab.PROPERTIES.DAY);\n boolean night = altClasses.contains(AltStylesheetVocab.PROPERTIES.NIGHT);\n\n if (vertical && horizontal || day && night)\n {\n report.message(MessageId.CSS_005,\n EPUBLocation.create(path, parser.getLineNumber(), parser.getColumnNumber()),\n classAttribute);\n }\n }\n\n protected void processAnchor(XMLElement e)\n {\n if (e.getAttribute(\"href\") == null)\n {\n anchorNeedsText = false;\n }\n if (inSvg)\n {\n String titleAttribute = e.getAttributeNS(EpubConstants.XLinkNamespaceUri, \"title\");\n if (titleAttribute == null)\n {\n report.message(MessageId.ACC_011, EPUBLocation.create(path, parser.getLineNumber(),\n parser.getColumnNumber(), e.getName()));\n }\n }\n }\n\n protected void processImg()\n {\n if ((inAudio || inVideo || imbricatedObjects > 0 || imbricatedCanvases > 0))\n {\n hasValidFallback = true;\n }\n }\n\n protected void processCanvas()\n {\n imbricatedCanvases++;\n }\n\n protected void processAudio()\n {\n inAudio = true;\n context.featureReport.report(FeatureEnum.AUDIO, parser.getLocation());\n }\n\n protected void processVideo(XMLElement e)\n {", "answers": [" inVideo = true;"], "length": 875, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "e10a5af3-98a4-4421-a74c-3a2ca7a52df7", "reasoning": "The method processVideo is analogous to processAudio, which sets the inAudio flag and reports the AUDIO feature. For video, the first operation should set the inVideo flag true. Therefore the next line after the method opening brace is the assignment inVideo = true;.", "reasoning_model_answer": "inVideo = true;", "assistant_with_reasoning": "\nThe method processVideo is analogous to processAudio, which sets the inAudio flag and reports the AUDIO feature. For video, the first operation should set the inVideo flag true. Therefore the next line after the method opening brace is the assignment inVideo = true;.\n\ninVideo = true;", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 2.941, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 12049, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "inVideo = true;", "score": 0.88, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License. See License.txt in the project root for\n// license information.\n// \n// Code generated by Microsoft (R) AutoRest Code Generator.\n// Changes may cause incorrect behavior and will be lost if the code is\n// regenerated.\n\nnamespace Fixtures.MirrorSequences\n{\n using Microsoft.Rest;\n using Models;\n\n ///

    \n /// A sample API that uses a petstore as an example to demonstrate\n /// features in the swagger-2.0 specification\n /// \n public partial class SequenceRequestResponseTest : Microsoft.Rest.ServiceClient, ISequenceRequestResponseTest\n {\n /// \n /// The base URI of the service.\n /// \n public System.Uri BaseUri { get; set; }\n\n /// \n /// Gets or sets json serialization settings.\n /// \n public Newtonsoft.Json.JsonSerializerSettings SerializationSettings { get; private set; }\n\n /// \n /// Gets or sets json deserialization settings.\n /// \n public Newtonsoft.Json.JsonSerializerSettings DeserializationSettings { get; private set; }\n\n /// \n /// Initializes a new instance of the SequenceRequestResponseTest class.\n /// \n /// \n /// Optional. The delegating handlers to add to the http client pipeline.\n /// \n public SequenceRequestResponseTest(params System.Net.Http.DelegatingHandler[] handlers) : base(handlers)\n {\n this.Initialize();\n }\n\n /// \n /// Initializes a new instance of the SequenceRequestResponseTest class.\n /// \n /// \n /// Optional. The http client handler used to handle http transport.\n /// \n /// \n /// Optional. The delegating handlers to add to the http client pipeline.\n /// \n public SequenceRequestResponseTest(System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : base(rootHandler, handlers)\n {\n this.Initialize();\n }\n\n /// \n /// Initializes a new instance of the SequenceRequestResponseTest class.\n /// \n /// \n /// Optional. The base URI of the service.\n /// \n /// \n /// Optional. The delegating handlers to add to the http client pipeline.\n /// \n /// \n /// Thrown when a required parameter is null\n /// \n public SequenceRequestResponseTest(System.Uri baseUri, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers)\n {\n if (baseUri == null)\n {\n throw new System.ArgumentNullException(\"baseUri\");\n }\n this.BaseUri = baseUri;\n }\n\n /// \n /// Initializes a new instance of the SequenceRequestResponseTest class.\n /// \n /// \n /// Optional. The base URI of the service.\n /// \n /// \n /// Optional. The http client handler used to handle http transport.\n /// \n /// \n /// Optional. The delegating handlers to add to the http client pipeline.\n /// \n /// \n /// Thrown when a required parameter is null\n /// \n public SequenceRequestResponseTest(System.Uri baseUri, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers)\n {\n if (baseUri == null)\n {\n throw new System.ArgumentNullException(\"baseUri\");\n }\n this.BaseUri = baseUri;\n }\n\n /// \n /// An optional partial-method to perform custom initialization.\n /// \n partial void CustomInitialize();\n /// \n /// Initializes client properties.\n /// \n private void Initialize()\n {\n this.BaseUri = new System.Uri(\"http://petstore.swagger.wordnik.com/api\");\n SerializationSettings = new Newtonsoft.Json.JsonSerializerSettings\n {\n Formatting = Newtonsoft.Json.Formatting.Indented,\n DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,\n DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,\n NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,\n ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,\n ContractResolver = new Microsoft.Rest.Serialization.ReadOnlyJsonContractResolver(),\n Converters = new System.Collections.Generic.List\n {\n new Microsoft.Rest.Serialization.Iso8601TimeSpanConverter()\n }\n };\n DeserializationSettings = new Newtonsoft.Json.JsonSerializerSettings\n {\n DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,\n DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,\n NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,\n ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,\n ContractResolver = new Microsoft.Rest.Serialization.ReadOnlyJsonContractResolver(),\n Converters = new System.Collections.Generic.List\n {\n new Microsoft.Rest.Serialization.Iso8601TimeSpanConverter()\n }\n };\n CustomInitialize();\n } \n /// \n /// Creates a new pet in the store. Duplicates are allowed\n /// \n /// \n /// Pets to add to the store\n /// \n /// \n /// Headers that will be added to request.\n /// \n /// \n /// The cancellation token.\n /// \n /// \n /// Thrown when the operation returned an invalid status code\n /// \n /// \n /// Thrown when unable to deserialize the response\n /// \n /// \n /// Thrown when a required parameter is null\n /// \n /// \n /// A response object containing the response body and response headers.\n /// \n public async System.Threading.Tasks.Task>> AddPetWithHttpMessagesAsync(System.Collections.Generic.IList pets, System.Collections.Generic.Dictionary> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))\n {\n if (pets == null)\n {\n throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, \"pets\");\n }\n if (pets != null)\n {\n foreach (var element in pets)\n {\n if (element != null)\n {\n element.Validate();\n }\n }\n }\n // Tracing\n bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;\n string _invocationId = null;\n if (_shouldTrace)\n {\n _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();\n System.Collections.Generic.Dictionary tracingParameters = new System.Collections.Generic.Dictionary();\n tracingParameters.Add(\"pets\", pets);\n tracingParameters.Add(\"cancellationToken\", cancellationToken);\n Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, \"AddPet\", tracingParameters);\n }\n // Construct URL\n var _baseUrl = this.BaseUri.AbsoluteUri;\n var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith(\"/\") ? \"\" : \"/\")), \"pets\").ToString();\n // Create HTTP transport objects\n System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();\n System.Net.Http.HttpResponseMessage _httpResponse = null;\n _httpRequest.Method = new System.Net.Http.HttpMethod(\"POST\");\n _httpRequest.RequestUri = new System.Uri(_url);\n // Set Headers\n if (customHeaders != null)\n {\n foreach(var _header in customHeaders)\n {\n if (_httpRequest.Headers.Contains(_header.Key))\n {\n _httpRequest.Headers.Remove(_header.Key);\n }\n _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);\n }\n }\n\n // Serialize Request\n string _requestContent = null;\n if(pets != null)\n {\n _requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(pets, this.SerializationSettings);\n _httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8);\n _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse(\"application/json; charset=utf-8\");\n }\n // Send Request\n if (_shouldTrace)\n {\n Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);\n }\n cancellationToken.ThrowIfCancellationRequested();\n _httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);\n if (_shouldTrace)\n {\n Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);\n }\n System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;\n cancellationToken.ThrowIfCancellationRequested();\n string _responseContent = null;\n if ((int)_statusCode != 200)\n {\n var ex = new ErrorModelException(string.Format(\"Operation returned an invalid status code '{0}'\", _statusCode));\n try\n {\n _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);\n ErrorModel _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject(_responseContent, this.DeserializationSettings);\n if (_errorBody != null)\n {\n ex.Body = _errorBody;\n }\n }\n catch (Newtonsoft.Json.JsonException)\n {\n // Ignore the exception\n }\n ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);\n ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);\n if (_shouldTrace)\n {", "answers": [" Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);"], "length": 875, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "605a4d27-aa62-4c12-ba44-836fb8099434", "reasoning": "The code is inside the error handling of an HTTP request. After creating the exception and setting its request/response, the generated pattern checks if tracing is enabled and logs the error. The next line should be the call to ServiceClientTracing.Error with the invocation ID and exception.", "reasoning_model_answer": "Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);", "assistant_with_reasoning": "\nThe code is inside the error handling of an HTTP request. After creating the exception and setting its request/response, the generated pattern checks if tracing is enabled and logs the error. The next line should be the call to ServiceClientTracing.Error with the invocation ID and exception.\n\nMicrosoft.Rest.ServiceClientTracing.Error(_invocationId, ex);", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.102, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 12086, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);", "score": 0.86, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "package fr.minibilles.basics.ui.action;\n\nimport fr.minibilles.basics.Basics;\nimport java.util.HashMap;\nimport java.util.Map;\nimport org.eclipse.swt.SWT;\nimport org.eclipse.swt.events.KeyEvent;\n\npublic class KeyCode {\n\n\tprivate static final Map keyDescription = new HashMap();\n\t\n\tpublic static final String getKeyDescription(int key) {\n\t\tString description = keyDescription.get(key);\n\t\tif ( description == null ) {\n\t\t\tchar[] chars = null;\n\t\t\ttry {\n\t\t\t\tchars = Character.toChars(key);\n\t\t\t} catch (Throwable e) {\n\t\t\t\tchars = new char[] { '?', '?', '?' };\n\t\t\t}\n\t\t\t\n\t\t\tdescription =\"'\" + String.valueOf(chars) + \"'\";\n\t\t}\n\t\treturn description;\n\t}\n\t/**\n\t * ASCII character convenience constant for the backspace character\n\t * (value is the char '\\b').\n\t */\n\tpublic static final char BS = '\\b';\n\n\t/**\n\t * ASCII character convenience constant for the carriage return character\n\t * (value is the char '\\r').\n\t */\n\tpublic static final char CR = '\\r';\n\n\t/**\n\t * ASCII character convenience constant for the delete character\n\t * (value is the char with value 127).\n\t */\n\tpublic static final char DEL = 0x7F;\n \n\t/**\n\t * ASCII character convenience constant for the escape character\n\t * (value is the char with value 27).\n\t */\n\tpublic static final char ESC = 0x1B;\n\n\t/**\n\t * ASCII character convenience constant for the tab character\n\t * (value is the char '\\t').\n\t * \n\t * @since 2.1\n\t */\n\tpublic static final char TAB = '\\t';\n\t\t\t\t\t\t\n\t/**\n\t * ASCII character convenience constant for the space character\n\t * (value is the char ' ').\n\t * \n\t * @since 3.7\n\t */\n\tpublic static final char SPACE = ' ';\n\t\t\t\t\t\t\n\t/**\n\t * keyboard and/or mouse event mask indicating that the ALT key\n\t * was pushed on the keyboard when the event was generated\n\t * (value is 1<<16).\n\t */\n\tpublic static final int ALT = 1 << 16;\n\t\t\t\t\t\n\t/**\n\t * Keyboard and/or mouse event mask indicating that the SHIFT key\n\t * was pushed on the keyboard when the event was generated\n\t * (value is 1<<17).\n\t */\n\tpublic static final int SHIFT = 1 << 17;\n\t\t\t\t\t\n\t/**\n\t * Keyboard and/or mouse event mask indicating that the CTRL key\n\t * was pushed on the keyboard when the event was generated\n\t * (value is 1<<18).\n\t */\n\tpublic static final int CTRL = 1 << 18;\n\n\t/**\n\t * Keyboard and/or mouse event mask indicating that the CTRL key\n\t * was pushed on the keyboard when the event was generated. This\n\t * is a synonym for CTRL (value is 1<<18).\n\t */\n\tpublic static final int CONTROL = CTRL;\n\n\t/**\n\t * Keyboard and/or mouse event mask indicating that the COMMAND key\n\t * was pushed on the keyboard when the event was generated\n\t * (value is 1<<22).\n\t * \n\t * @since 2.1\n\t */\n\tpublic static final int COMMAND = 1 << 22;\n\t\n\t/**\n\t * Keyboard and/or mouse event mask indicating that the MOD1 key\n\t * was pushed on the keyboard when the event was generated.\n\t * \n\t * This is the primary keyboard modifier for the platform.\n\t * \n\t * @since 2.1\n\t */\n\tpublic static final int MOD1;\n\t\n\t/**\n\t * Keyboard and/or mouse event mask indicating that the MOD2 key\n\t * was pushed on the keyboard when the event was generated.\n\t * \n\t * This is the secondary keyboard modifier for the platform.\n\t * \n\t * @since 2.1\n\t */\n\tpublic static final int MOD2;\n\n\t/**\n\t * Keyboard and/or mouse event mask indicating that the MOD3 key\n\t * was pushed on the keyboard when the event was generated.\n\t * \n\t * @since 2.1\n\t */\n\tpublic static final int MOD3;\n\n\t/**\n\t * Keyboard and/or mouse event mask indicating that the MOD4 key\n\t * was pushed on the keyboard when the event was generated.\n\t * \n\t * @since 2.1\n\t */\n\tpublic static final int MOD4;\n\t\n\t/**\n\t * Accelerator constant used to differentiate a key code from a\n\t * unicode character.\n\t * \n\t * If this bit is set, then the key stroke\n\t * portion of an accelerator represents a key code. If this bit\n\t * is not set, then the key stroke portion of an accelerator is\n\t * a unicode character.\n\t * \n\t * The following expression is false:\n\t * \n\t * ((SWT.MOD1 | SWT.MOD2 | 'T') & SWT.KEYCODE_BIT) != 0.\n\t * \n\t * The following expression is true:\n\t * \n\t * ((SWT.MOD3 | SWT.F2) & SWT.KEYCODE_BIT) != 0.\n\t * \n\t * (value is (1<<24))\n\t * \n\t * @since 2.1\n\t */\t\n\tpublic static final int KEYCODE_BIT = (1 << 24);\n\n\t/**\n\t * Accelerator constant used to extract the key stroke portion of\n\t * an accelerator.\n\t * \n\t * The key stroke may be a key code or a unicode\n\t * value. If the key stroke is a key code KEYCODE_BIT\n\t * will be set.\n\t * \n\t * @since 2.1\n\t */\t\n\tpublic static final int KEY_MASK = KEYCODE_BIT + 0xFFFF;\n\t\n\t/**\n\t * Keyboard event constant representing the UP ARROW key\n\t * (value is (1<<24)+1).\n\t */\n\tpublic static final int ARROW_UP = KEYCODE_BIT + 1;\n\n\t/**\n\t * Keyboard event constant representing the DOWN ARROW key\n\t * (value is (1<<24)+2).\n\t */", "answers": ["\tpublic static final int ARROW_DOWN = KEYCODE_BIT + 2;"], "length": 793, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "e2a60886-adf8-40f4-9409-74560315668a", "reasoning": "The code defines accelerator constants for key codes. After defining ARROW_UP with its comment, the next logical constant is ARROW_DOWN, matching the preceding comment that describes the DOWN ARROW key and its value (KEYCODE_BIT + 2). Therefore the next line should declare ARROW_DOWN accordingly.", "reasoning_model_answer": "public static final int ARROW_DOWN = KEYCODE_BIT + 2;", "assistant_with_reasoning": "\nThe code defines accelerator constants for key codes. After defining ARROW_UP with its comment, the next logical constant is ARROW_DOWN, matching the preceding comment that describes the DOWN ARROW key and its value (KEYCODE_BIT + 2). Therefore the next line should declare ARROW_DOWN accordingly.\n\npublic static final int ARROW_DOWN = KEYCODE_BIT + 2;", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 2.164, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 4993, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "public static final int ARROW_DOWN = KEYCODE_BIT + 2;", "score": 0.99, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "# -*- coding: utf-8 -*-\n# pylint: disable=W0231, W0142\n\"\"\"Tests for statistical power calculations\n\nNote:\n tests for chisquare power are in test_gof.py\n\nCreated on Sat Mar 09 08:44:49 2013\n\nAuthor: Josef Perktold\n\"\"\"\n\nimport copy\nimport warnings\nimport nose\nfrom distutils.version import LooseVersion\n\nimport numpy as np\nfrom numpy.testing import (assert_almost_equal, assert_allclose, assert_raises,\n assert_equal, assert_warns, dec)\nimport scipy\n\nimport statsmodels.stats.power as smp\nfrom statsmodels.stats.tests.test_weightstats import Holder\n\ntry:\n import matplotlib.pyplot as plt # makes plt available for test functions\n have_matplotlib = True\nexcept ImportError:\n have_matplotlib = False\n\n\nSM_GT_10 = LooseVersion(scipy.__version__) >= '0.10'\n\nclass CheckPowerMixin(object):\n\n def test_power(self):\n #test against R results\n kwds = copy.copy(self.kwds)\n del kwds['power']\n kwds.update(self.kwds_extra)\n if hasattr(self, 'decimal'):\n decimal = self.decimal\n else:\n decimal = 6\n res1 = self.cls()\n assert_almost_equal(res1.power(**kwds), self.res2.power, decimal=decimal)\n\n def test_positional(self):\n\n res1 = self.cls()\n\n\n kwds = copy.copy(self.kwds)\n del kwds['power']\n kwds.update(self.kwds_extra)\n\n # positional args\n if hasattr(self, 'args_names'):\n args_names = self.args_names\n else:\n nobs_ = 'nobs' if 'nobs' in kwds else 'nobs1'\n args_names = ['effect_size', nobs_, 'alpha']\n\n # pop positional args\n args = [kwds.pop(arg) for arg in args_names]\n\n if hasattr(self, 'decimal'):\n decimal = self.decimal\n else:\n decimal = 6\n\n res = res1.power(*args, **kwds)\n assert_almost_equal(res, self.res2.power, decimal=decimal)\n\n def test_roots(self):\n kwds = copy.copy(self.kwds)\n kwds.update(self.kwds_extra)\n\n # kwds_extra are used as argument, but not as target for root\n for key in self.kwds:\n # keep print to check whether tests are really executed\n #print 'testing roots', key\n value = kwds[key]\n kwds[key] = None\n\n result = self.cls().solve_power(**kwds)\n assert_allclose(result, value, rtol=0.001, err_msg=key+' failed')\n # yield can be used to investigate specific errors\n #yield assert_allclose, result, value, 0.001, 0, key+' failed'\n kwds[key] = value # reset dict\n\n @dec.skipif(not have_matplotlib)\n def test_power_plot(self):\n if self.cls == smp.FTestPower:\n raise nose.SkipTest('skip FTestPower plot_power')\n plt.close()\n fig = plt.figure()\n ax = fig.add_subplot(2,1,1)\n fig = self.cls().plot_power(dep_var='nobs',\n nobs= np.arange(2, 100),\n effect_size=np.array([0.1, 0.2, 0.3, 0.5, 1]),\n #alternative='larger',\n ax=ax, title='Power of t-Test',\n **self.kwds_extra)\n ax = fig.add_subplot(2,1,2)\n fig = self.cls().plot_power(dep_var='es',\n nobs=np.array([10, 20, 30, 50, 70, 100]),\n effect_size=np.linspace(0.01, 2, 51),\n #alternative='larger',\n ax=ax, title='',\n **self.kwds_extra)\n plt.close(fig)\n\n#''' test cases\n#one sample\n# two-sided one-sided\n#large power OneS1 OneS3\n#small power OneS2 OneS4\n#\n#two sample\n# two-sided one-sided\n#large power TwoS1 TwoS3\n#small power TwoS2 TwoS4\n#small p, ratio TwoS4 TwoS5\n#'''\n\nclass TestTTPowerOneS1(CheckPowerMixin):\n\n def __init__(self):\n\n #> p = pwr.t.test(d=1,n=30,sig.level=0.05,type=\"two.sample\",alternative=\"two.sided\")\n #> cat_items(p, prefix='tt_power2_1.')\n res2 = Holder()\n res2.n = 30\n res2.d = 1\n res2.sig_level = 0.05\n res2.power = 0.9995636009612725\n res2.alternative = 'two.sided'\n res2.note = 'NULL'\n res2.method = 'One-sample t test power calculation'\n\n self.res2 = res2\n self.kwds = {'effect_size': res2.d, 'nobs': res2.n,\n 'alpha': res2.sig_level, 'power':res2.power}\n self.kwds_extra = {}\n self.cls = smp.TTestPower\n\nclass TestTTPowerOneS2(CheckPowerMixin):\n # case with small power\n\n def __init__(self):\n\n res2 = Holder()\n #> p = pwr.t.test(d=0.2,n=20,sig.level=0.05,type=\"one.sample\",alternative=\"two.sided\")\n #> cat_items(p, \"res2.\")\n res2.n = 20\n res2.d = 0.2\n res2.sig_level = 0.05\n res2.power = 0.1359562887679666\n res2.alternative = 'two.sided'\n res2.note = '''NULL'''\n res2.method = 'One-sample t test power calculation'\n\n self.res2 = res2\n self.kwds = {'effect_size': res2.d, 'nobs': res2.n,\n 'alpha': res2.sig_level, 'power':res2.power}\n self.kwds_extra = {}\n self.cls = smp.TTestPower\n\nclass TestTTPowerOneS3(CheckPowerMixin):\n\n def __init__(self):\n\n res2 = Holder()\n #> p = pwr.t.test(d=1,n=30,sig.level=0.05,type=\"one.sample\",alternative=\"greater\")\n #> cat_items(p, prefix='tt_power1_1g.')\n res2.n = 30\n res2.d = 1\n res2.sig_level = 0.05\n res2.power = 0.999892010204909\n res2.alternative = 'greater'\n res2.note = 'NULL'\n res2.method = 'One-sample t test power calculation'\n\n self.res2 = res2\n self.kwds = {'effect_size': res2.d, 'nobs': res2.n,\n 'alpha': res2.sig_level, 'power': res2.power}\n self.kwds_extra = {'alternative': 'larger'}\n self.cls = smp.TTestPower\n\nclass TestTTPowerOneS4(CheckPowerMixin):\n\n def __init__(self):\n\n res2 = Holder()\n #> p = pwr.t.test(d=0.05,n=20,sig.level=0.05,type=\"one.sample\",alternative=\"greater\")\n #> cat_items(p, \"res2.\")\n res2.n = 20\n res2.d = 0.05\n res2.sig_level = 0.05\n res2.power = 0.0764888785042198\n res2.alternative = 'greater'\n res2.note = '''NULL'''\n res2.method = 'One-sample t test power calculation'\n\n self.res2 = res2\n self.kwds = {'effect_size': res2.d, 'nobs': res2.n,\n 'alpha': res2.sig_level, 'power': res2.power}\n self.kwds_extra = {'alternative': 'larger'}\n self.cls = smp.TTestPower\n\nclass TestTTPowerOneS5(CheckPowerMixin):\n # case one-sided less, not implemented yet\n\n def __init__(self):\n\n res2 = Holder()\n #> p = pwr.t.test(d=0.2,n=20,sig.level=0.05,type=\"one.sample\",alternative=\"less\")\n #> cat_items(p, \"res2.\")\n res2.n = 20\n res2.d = 0.2\n res2.sig_level = 0.05\n res2.power = 0.006063932667926375\n res2.alternative = 'less'\n res2.note = '''NULL'''\n res2.method = 'One-sample t test power calculation'\n\n self.res2 = res2\n self.kwds = {'effect_size': res2.d, 'nobs': res2.n,\n 'alpha': res2.sig_level, 'power': res2.power}\n self.kwds_extra = {'alternative': 'smaller'}\n self.cls = smp.TTestPower\n\nclass TestTTPowerOneS6(CheckPowerMixin):\n # case one-sided less, negative effect size, not implemented yet\n\n def __init__(self):\n\n res2 = Holder()\n #> p = pwr.t.test(d=-0.2,n=20,sig.level=0.05,type=\"one.sample\",alternative=\"less\")\n #> cat_items(p, \"res2.\")\n res2.n = 20\n res2.d = -0.2\n res2.sig_level = 0.05\n res2.power = 0.21707518167191\n res2.alternative = 'less'\n res2.note = '''NULL'''\n res2.method = 'One-sample t test power calculation'", "answers": [" self.res2 = res2"], "length": 706, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "d3b7644a-71bf-46fa-9ded-01a32ab51b2a", "reasoning": "The __init__ method of each test class ends by assigning the Holder instance to self.res2, then defining self.kwds, self.kwds_extra, and self.cls. In TestTTPowerOneS6 the code stops right after setting res2.method, so the next logical line is the assignment self.res2 = res2.", "reasoning_model_answer": "self.res2 = res2", "assistant_with_reasoning": "\nThe __init__ method of each test class ends by assigning the Holder instance to self.res2, then defining self.kwds, self.kwds_extra, and self.cls. In TestTTPowerOneS6 the code stops right after setting res2.method, so the next logical line is the assignment self.res2 = res2.\n\nself.res2 = res2", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 2.351, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 8049, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "self.res2 = res2", "score": 0.8, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.IO;\nusing System.Net.Cache;\nusing System.Net.Security;\nusing System.Runtime.Serialization;\nusing System.Security.Principal;\nusing System.Threading;\nusing System.Threading.Tasks;\nnamespace System.Net\n{\n [Serializable]\n public abstract class WebRequest : MarshalByRefObject, ISerializable\n {\n internal class WebRequestPrefixElement\n {\n public readonly string Prefix;\n public readonly IWebRequestCreate Creator;\n\n public WebRequestPrefixElement(string prefix, IWebRequestCreate creator)\n {\n Prefix = prefix;\n Creator = creator;\n }\n }\n\n private static List s_prefixList;\n private static object s_internalSyncObject = new object();\n\n internal const int DefaultTimeoutMilliseconds = 100 * 1000;\n\n protected WebRequest() { }\n\n protected WebRequest(SerializationInfo serializationInfo, StreamingContext streamingContext) { }\n\n void ISerializable.GetObjectData(SerializationInfo serializationInfo, StreamingContext streamingContext)\n {\n GetObjectData(serializationInfo, streamingContext);\n }\n\n protected virtual void GetObjectData(SerializationInfo serializationInfo, StreamingContext streamingContext) { }\n\n // Create a WebRequest.\n //\n // This is the main creation routine. We take a Uri object, look\n // up the Uri in the prefix match table, and invoke the appropriate\n // handler to create the object. We also have a parameter that\n // tells us whether or not to use the whole Uri or just the\n // scheme portion of it.\n //\n // Input:\n // requestUri - Uri object for request.\n // useUriBase - True if we're only to look at the scheme portion of the Uri.\n //\n // Returns:\n // Newly created WebRequest.\n private static WebRequest Create(Uri requestUri, bool useUriBase)\n {\n if (NetEventSource.IsEnabled) NetEventSource.Enter(null, requestUri);\n\n string LookupUri;\n WebRequestPrefixElement Current = null;\n bool Found = false;\n\n if (!useUriBase)\n {\n LookupUri = requestUri.AbsoluteUri;\n }\n else\n {\n // schemes are registered as \":\", so add the separator\n // to the string returned from the Uri object\n LookupUri = requestUri.Scheme + ':';\n }\n\n int LookupLength = LookupUri.Length;\n\n // Copy the prefix list so that if it is updated it will\n // not affect us on this thread.\n\n List prefixList = PrefixList;\n\n // Look for the longest matching prefix.\n\n // Walk down the list of prefixes. The prefixes are kept longest\n // first. When we find a prefix that is shorter or the same size\n // as this Uri, we'll do a compare to see if they match. If they\n // do we'll break out of the loop and call the creator.\n\n for (int i = 0; i < prefixList.Count; i++)\n {\n Current = prefixList[i];\n\n // See if this prefix is short enough.\n\n if (LookupLength >= Current.Prefix.Length)\n {\n // It is. See if these match.\n if (String.Compare(Current.Prefix,\n 0,\n LookupUri,\n 0,\n Current.Prefix.Length,\n StringComparison.OrdinalIgnoreCase) == 0)\n {\n // These match. Remember that we found it and break\n // out.\n Found = true;\n break;\n }\n }\n }\n\n WebRequest webRequest = null;\n\n if (Found)\n {\n // We found a match, so just call the creator and return what it does.\n webRequest = Current.Creator.Create(requestUri);\n if (NetEventSource.IsEnabled) NetEventSource.Exit(null, webRequest);\n return webRequest;\n }\n\n // Otherwise no match, throw an exception.\n if (NetEventSource.IsEnabled) NetEventSource.Exit(null);\n throw new NotSupportedException(SR.net_unknown_prefix);\n }\n\n // Create - Create a WebRequest.\n //\n // An overloaded utility version of the real Create that takes a\n // string instead of an Uri object.\n //\n // Input:\n // RequestString - Uri string to create.\n //\n // Returns:\n // Newly created WebRequest.\n public static WebRequest Create(string requestUriString)\n {\n if (requestUriString == null)\n {\n throw new ArgumentNullException(nameof(requestUriString));\n }\n\n return Create(new Uri(requestUriString), false);\n }\n\n // Create - Create a WebRequest.\n //\n // Another overloaded version of the Create function that doesn't\n // take the UseUriBase parameter.\n //\n // Input:\n // requestUri - Uri object for request.\n //\n // Returns:\n // Newly created WebRequest.\n public static WebRequest Create(Uri requestUri)\n {\n if (requestUri == null)\n {\n throw new ArgumentNullException(nameof(requestUri));\n }\n\n return Create(requestUri, false);\n }\n\n // CreateDefault - Create a default WebRequest.\n //\n // This is the creation routine that creates a default WebRequest.\n // We take a Uri object and pass it to the base create routine,\n // setting the useUriBase parameter to true.\n //\n // Input:\n // RequestUri - Uri object for request.\n //\n // Returns:\n // Newly created WebRequest.\n public static WebRequest CreateDefault(Uri requestUri)\n {\n if (requestUri == null)\n {\n throw new ArgumentNullException(nameof(requestUri));\n }\n\n return Create(requestUri, true);\n }\n\n public static HttpWebRequest CreateHttp(string requestUriString)\n {\n if (requestUriString == null)\n {\n throw new ArgumentNullException(nameof(requestUriString));\n }\n return CreateHttp(new Uri(requestUriString));\n }\n", "answers": [" public static HttpWebRequest CreateHttp(Uri requestUri)"], "length": 708, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "e2b7f620-1599-4f6d-b779-4969e45873fd", "reasoning": "The code just finished defining CreateHttp(string). The next logical member is the overload that takes a Uri, matching the pattern of other Create methods. Therefore the next line should be the method signature for CreateHttp that accepts a Uri.", "reasoning_model_answer": "public static HttpWebRequest CreateHttp(Uri requestUri)", "assistant_with_reasoning": "\nThe code just finished defining CreateHttp(string). The next logical member is the overload that takes a Uri, matching the pattern of other Create methods. Therefore the next line should be the method signature for CreateHttp that accepts a Uri.\n\npublic static HttpWebRequest CreateHttp(Uri requestUri)", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 2.758, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 7141, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "public static HttpWebRequest CreateHttp(Uri requestUri)", "score": 0.93, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "\"\"\"Undocumented Module\"\"\"\n\n__all__ = ['MetaInterval', 'Sequence', 'Parallel', 'ParallelEndTogether', 'Track']\n\nfrom panda3d.core import *\nfrom panda3d.direct import *\nfrom direct.directnotify.DirectNotifyGlobal import *\nfrom .IntervalManager import ivalMgr\nfrom . import Interval\nfrom direct.task.Task import TaskManager\n#if __debug__:\n# import direct.showbase.PythonUtil as PythonUtil\n\nPREVIOUS_END = CMetaInterval.RSPreviousEnd\nPREVIOUS_START = CMetaInterval.RSPreviousBegin\nTRACK_START = CMetaInterval.RSLevelBegin\n\nclass MetaInterval(CMetaInterval):\n # This is a Python-C++ hybrid class. MetaInterval is a Python\n # extension of the C++ class CMetaInterval, which adds some\n # Python-specific features (like list management).\n\n # This is the base class of Sequence, Parallel, and Track.\n\n notify = directNotify.newCategory(\"MetaInterval\")\n\n SequenceNum = 1\n def __init__(self, *ivals, **kw):\n #if __debug__:\n # self.debugInitTraceback = PythonUtil.StackTrace(\n # \"create interval\", 1, 10)\n\n name = None\n #if len(ivals) == 2 and isinstance(ivals[1], str):\n # # If the second parameter is a string, it's the name.\n # name = ivals[1]\n # ivals = ivals[0]\n #else:\n\n # Look for the name in the keyword params.\n if 'name' in kw:\n name = kw['name']\n del kw['name']\n\n # If the keyword \"autoPause\" or \"autoFinish\" is defined to\n # non-zero, it means the interval may be automatically paused\n # or finished when CIntervalManager::interrupt() is called.\n # This is generally called only on a catastrophic situation\n # (for instance, the connection to the server being lost) when\n # we have to exit right away; these keywords indicate\n # intervals that might not be cleaned up by their owners.\n\n autoPause = 0\n autoFinish = 0\n if 'autoPause' in kw:\n autoPause = kw['autoPause']\n del kw['autoPause']\n if 'autoFinish' in kw:\n autoFinish = kw['autoFinish']\n del kw['autoFinish']\n\n # A duration keyword specifies the duration the interval will\n # appear to have for the purposes of computing the start time\n # for subsequent intervals in a sequence or track.\n self.phonyDuration = -1\n if 'duration' in kw:\n self.phonyDuration = kw['duration']\n del kw['duration']\n\n if kw:\n self.notify.error(\"Unexpected keyword parameters: %s\" % (list(kw.keys())))\n\n # We must allow the old style: Track([ival0, ival1, ...]) as\n # well as the new style: Track(ival0, ival1, ...)\n\n # Note: this breaks in the case of a Track with one tuple:\n # Track((0, ival0),). We could go through some effort to fix\n # this case, but for now I prefer just to document it as a\n # bug, since it will go away when we eventually remove support\n # for the old interface.\n #if len(ivals) == 1 and \\\n # (isinstance(ivals[0], tuple) or \\\n # isinstance(ivals[0], list)):\n # self.ivals = ivals[0]\n #else:\n\n self.ivals = ivals\n\n self.__ivalsDirty = 1\n\n if name == None:\n name = self.__class__.__name__ + '-%d'\n\n if '%' in name:\n name = name % (self.SequenceNum)\n MetaInterval.SequenceNum += 1\n\n CMetaInterval.__init__(self, name)\n self.__manager = ivalMgr\n self.setAutoPause(autoPause)\n self.setAutoFinish(autoFinish)\n\n self.pstats = None\n if __debug__ and TaskManager.taskTimerVerbose:\n self.pname = name.split('-', 1)[0]\n self.pstats = PStatCollector(\"App:Show code:ivalLoop:%s\" % (self.pname))\n\n self.pythonIvals = []\n\n # If we are running in debug mode, we validate the intervals\n # in the list right away. There's no good reason to do this,\n # except that it makes it easier for the programmer to detect\n # when a MetaInterval is misdefined at creation time.\n assert self.validateComponents(self.ivals)\n\n\n\n # Functions to make the MetaInterval object act just like a Python\n # list of intervals:\n\n def append(self, ival):\n # Appends a single interval to the list so far.\n if isinstance(self.ivals, tuple):\n self.ivals = list(self.ivals)\n self.ivals.append(ival)\n self.__ivalsDirty = 1\n assert self.validateComponent(ival)\n\n def extend(self, ivals):\n # Appends a list of intervals to the list so far.\n self += ivals\n\n def count(self, ival):\n # Returns the number of occurrences of the indicated interval.\n return self.ivals.count(ival)\n\n def index(self, ival):\n # Returns the position of the indicated interval within the list.\n return self.ivals.index(ival)\n\n def insert(self, index, ival):\n # Inserts the given interval into the middle of the list.\n if isinstance(self.ivals, tuple):\n self.ivals = list(self.ivals)\n self.ivals.insert(index, ival)\n self.__ivalsDirty = 1\n assert self.validateComponent(ival)\n\n def pop(self, index = None):\n # Returns element index (or the last element) and removes it\n # from the list.\n if isinstance(self.ivals, tuple):\n self.ivals = list(self.ivals)\n self.__ivalsDirty = 1\n if index == None:\n return self.ivals.pop()\n else:\n return self.ivals.pop(index)\n\n def remove(self, ival):\n # Removes the indicated interval from the list.\n if isinstance(self.ivals, tuple):\n self.ivals = list(self.ivals)\n self.ivals.remove(ival)\n self.__ivalsDirty = 1\n\n def reverse(self):\n # Reverses the order of the intervals.\n if isinstance(self.ivals, tuple):\n self.ivals = list(self.ivals)\n self.ivals.reverse()\n self.__ivalsDirty = 1\n\n def sort(self, cmpfunc = None):\n # Sorts the intervals. (?)\n if isinstance(self.ivals, tuple):\n self.ivals = list(self.ivals)\n self.__ivalsDirty = 1\n if cmpfunc == None:\n self.ivals.sort()\n else:\n self.ivals.sort(cmpfunc)\n\n def __len__(self):\n return len(self.ivals)\n\n def __getitem__(self, index):\n return self.ivals[index]\n\n def __setitem__(self, index, value):\n if isinstance(self.ivals, tuple):\n self.ivals = list(self.ivals)\n self.ivals[index] = value\n self.__ivalsDirty = 1\n assert self.validateComponent(value)\n\n def __delitem__(self, index):\n if isinstance(self.ivals, tuple):\n self.ivals = list(self.ivals)\n del self.ivals[index]\n self.__ivalsDirty = 1\n\n def __getslice__(self, i, j):\n if isinstance(self.ivals, tuple):\n self.ivals = list(self.ivals)\n return self.__class__(self.ivals[i: j])\n", "answers": [" def __setslice__(self, i, j, s):"], "length": 779, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "39910774-39d6-408e-8418-14c15c1cb057", "reasoning": "The class MetaInterval implements list‑like behavior. After defining __getslice__, the next logical method is __setslice__ to handle slice assignment, following the pattern of other special methods (__len__, __getitem__, __setitem__, __delitem__, __getslice__). Therefore the next line should start the definition of __setslice__.", "reasoning_model_answer": "def __setslice__(self, i, j, seq):", "assistant_with_reasoning": "\nThe class MetaInterval implements list‑like behavior. After defining __getslice__, the next logical method is __setslice__ to handle slice assignment, following the pattern of other special methods (__len__, __getitem__, __setitem__, __delitem__, __getslice__). Therefore the next line should start the definition of __setslice__.\n\ndef __setslice__(self, i, j, seq):", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.518, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 7109, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "def __setslice__(self, i, j, seq):", "score": 0.91, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "# Copyright 2010 Matt Chaput. All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n#\n# 1. Redistributions of source code must retain the above copyright notice,\n# this list of conditions and the following disclaimer.\n#\n# 2. Redistributions in binary form must reproduce the above copyright\n# notice, this list of conditions and the following disclaimer in the\n# documentation and/or other materials provided with the distribution.\n#\n# THIS SOFTWARE IS PROVIDED BY MATT CHAPUT ``AS IS'' AND ANY EXPRESS OR\n# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n# MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO\n# EVENT SHALL MATT CHAPUT OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,\n# OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,\n# EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n#\n# The views and conclusions contained in the software and documentation are\n# those of the authors and should not be interpreted as representing official\n# policies, either expressed or implied, of Matt Chaput.\n\nimport math, struct\nfrom array import array\nfrom bisect import bisect_left\nfrom struct import pack, unpack\n\nfrom whoosh.compat import b, long_type\nfrom whoosh.system import pack_byte, unpack_byte, pack_ushort, unpack_ushort\nfrom whoosh.system import pack_int, unpack_int, pack_uint, unpack_uint\nfrom whoosh.system import pack_long, unpack_long, pack_ulong, unpack_ulong\nfrom whoosh.system import pack_float, unpack_float, pack_double, unpack_double\n\n\nNaN = struct.unpack(\"i\")\n_qstruct = struct.Struct(\">q\")\n_dstruct = struct.Struct(\">d\")\n_ipack, _iunpack = _istruct.pack, _istruct.unpack\n_qpack, _qunpack = _qstruct.pack, _qstruct.unpack\n_dpack, _dunpack = _dstruct.pack, _dstruct.unpack\n\n\ndef to_sortable(numtype, intsize, signed, x):\n if numtype is int or numtype is long_type:\n if signed:\n x += (1 << intsize - 1)\n return x\n else:\n return float_to_sortable_long(x, signed)\n\n\ndef from_sortable(numtype, intsize, signed, x):\n if numtype is int or numtype is long_type:\n if signed:\n x -= (1 << intsize - 1)\n return x\n else:\n return sortable_long_to_float(x, signed)\n\n\ndef float_to_sortable_long(x, signed):\n x = _qunpack(_dpack(x))[0]\n if x < 0:\n x ^= 0x7fffffffffffffff\n if signed:\n x += 1 << 63\n assert x >= 0\n return x\n\n\ndef sortable_long_to_float(x, signed):\n if signed:\n x -= 1 << 63\n if x < 0:\n x ^= 0x7fffffffffffffff\n x = _dunpack(_qpack(x))[0]\n return x\n\n\n# Functions for generating tiered ranges\n\ndef split_ranges(intsize, step, start, end):\n \"\"\"Splits a range of numbers (from ``start`` to ``end``, inclusive)\n into a sequence of trie ranges of the form ``(start, end, shift)``. The\n consumer of these tuples is expected to shift the ``start`` and ``end``\n right by ``shift``.\n\n This is used for generating term ranges for a numeric field. The queries\n for the edges of the range are generated at high precision and large blocks\n in the middle are generated at low precision.\n \"\"\"\n\n shift = 0\n while True:\n diff = 1 << (shift + step)\n mask = ((1 << step) - 1) << shift\n setbits = lambda x: x | ((1 << shift) - 1)\n\n haslower = (start & mask) != 0", "answers": [" hasupper = (end & mask) != mask"], "length": 777, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "977dba98-af57-49b8-93de-dcebd3e07793", "reasoning": "In the split_ranges function, after computing the mask and setbits lambda, the code checks whether the start value has lower bits set within the mask. The next logical step is to similarly check the end value for upper bits, assigning a boolean flag. Therefore the next line should compute hasupper by testing the end against the mask.", "reasoning_model_answer": "hasupper = (end & mask) != mask", "assistant_with_reasoning": "\nIn the split_ranges function, after computing the mask and setbits lambda, the code checks whether the start value has lower bits set within the mask. The next logical step is to similarly check the end value for upper bits, assigning a boolean flag. Therefore the next line should compute hasupper by testing the end against the mask.\n\nhasupper = (end & mask) != mask", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.308, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 5499, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "hasupper = (end & mask) != mask", "score": 0.89, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/*\n * Licensed to Elasticsearch under one or more contributor\n * license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright\n * ownership. Elasticsearch licenses this file to you under\n * the Apache License, Version 2.0 (the \"License\"); you may\n * not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\npackage org.elasticsearch.gateway.local.state.meta;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.Collections2;\nimport org.apache.lucene.codecs.CodecUtil;\nimport org.apache.lucene.index.CorruptIndexException;\nimport org.apache.lucene.store.Directory;\nimport org.apache.lucene.store.IOContext;\nimport org.apache.lucene.store.IndexInput;\nimport org.apache.lucene.store.OutputStreamIndexOutput;\nimport org.apache.lucene.store.SimpleFSDirectory;\nimport org.apache.lucene.util.IOUtils;\nimport org.apache.lucene.util.XIOUtils;\nimport org.elasticsearch.ElasticsearchIllegalStateException;\nimport org.elasticsearch.ExceptionsHelper;\nimport org.elasticsearch.common.Preconditions;\nimport org.elasticsearch.common.io.Streams;\nimport org.elasticsearch.common.logging.ESLogger;\nimport org.elasticsearch.common.lucene.store.InputStreamIndexInput;\nimport org.elasticsearch.common.xcontent.*;\n\nimport java.io.File;\nimport java.io.FileInputStream;\nimport java.io.IOException;\nimport java.io.OutputStream;\nimport java.nio.file.Files;\nimport java.nio.file.Path;\nimport java.nio.file.Paths;\nimport java.nio.file.StandardCopyOption;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\n/**\n * MetaDataStateFormat is a base class to write checksummed\n * XContent based files to one or more directories in a standardized directory structure.\n * @param the type of the XContent base data-structure\n */\npublic abstract class MetaDataStateFormat {\n public static final String STATE_DIR_NAME = \"_state\";\n public static final String STATE_FILE_EXTENSION = \".st\";\n private static final String STATE_FILE_CODEC = \"state\";\n private static final int STATE_FILE_VERSION = 0;\n private static final int BUFFER_SIZE = 4096;\n private final XContentType format;\n private final boolean deleteOldFiles;\n\n /**\n * Creates a new {@link MetaDataStateFormat} instance\n * @param format the format of the x-content\n * @param deleteOldFiles if true write operations will\n * clean up old files written with this format.\n */\n protected MetaDataStateFormat(XContentType format, boolean deleteOldFiles) {\n this.format = format;\n this.deleteOldFiles = deleteOldFiles;\n }\n\n /**\n * Returns the {@link XContentType} used to serialize xcontent on write.\n */\n public XContentType format() {\n return format;\n }\n\n /**\n * Writes the given state to the given directories. The state is written to a\n * state directory ({@value #STATE_DIR_NAME}) underneath each of the given file locations and is created if it\n * doesn't exist. The state is serialized to a temporary file in that directory and is then atomically moved to\n * it's target filename of the pattern {prefix}{version}.st.\n *\n * @param state the state object to write\n * @param prefix the state names prefix used to compose the file name.\n * @param version the version of the state\n * @param locations the locations where the state should be written to.\n * @throws IOException if an IOException occurs\n */\n public final void write(final T state, final String prefix, final long version, final File... locations) throws IOException {\n Preconditions.checkArgument(locations != null, \"Locations must not be null\");\n Preconditions.checkArgument(locations.length > 0, \"One or more locations required\");\n String fileName = prefix + version + STATE_FILE_EXTENSION;\n Path stateLocation = Paths.get(locations[0].getPath(), STATE_DIR_NAME);\n Files.createDirectories(stateLocation);\n final Path tmpStatePath = stateLocation.resolve(fileName + \".tmp\");\n final Path finalStatePath = stateLocation.resolve(fileName);\n try {\n try (OutputStreamIndexOutput out = new OutputStreamIndexOutput(Files.newOutputStream(tmpStatePath), BUFFER_SIZE)) {\n CodecUtil.writeHeader(out, STATE_FILE_CODEC, STATE_FILE_VERSION);\n out.writeInt(format.index());\n out.writeLong(version);\n try (XContentBuilder builder = newXContentBuilder(format, new org.elasticsearch.common.lucene.store.OutputStreamIndexOutput(out) {\n @Override\n public void close() throws IOException {\n // this is important since some of the XContentBuilders write bytes on close.\n // in order to write the footer we need to prevent closing the actual index input.\n } })) {\n\n builder.startObject();\n {\n toXContent(builder, state);\n }\n builder.endObject();\n }\n CodecUtil.writeFooter(out);\n }\n IOUtils.fsync(tmpStatePath.toFile(), false); // fsync the state file\n Files.move(tmpStatePath, finalStatePath, StandardCopyOption.ATOMIC_MOVE);\n IOUtils.fsync(stateLocation.toFile(), true);\n for (int i = 1; i < locations.length; i++) {\n stateLocation = Paths.get(locations[i].getPath(), STATE_DIR_NAME);\n Files.createDirectories(stateLocation);\n Path tmpPath = stateLocation.resolve(fileName + \".tmp\");\n Path finalPath = stateLocation.resolve(fileName);\n try {\n Files.copy(finalStatePath, tmpPath);\n Files.move(tmpPath, finalPath, StandardCopyOption.ATOMIC_MOVE); // we are on the same FileSystem / Partition here we can do an atomic move\n IOUtils.fsync(stateLocation.toFile(), true); // we just fsync the dir here..\n } finally {\n Files.deleteIfExists(tmpPath);\n }\n }\n } finally {\n Files.deleteIfExists(tmpStatePath);\n }\n if (deleteOldFiles) {\n cleanupOldFiles(prefix, fileName, locations);\n }\n }\n\n protected XContentBuilder newXContentBuilder(XContentType type, OutputStream stream ) throws IOException {\n return XContentFactory.contentBuilder(type, stream);\n }\n\n /**\n * Writes the given state to the given XContentBuilder\n * Subclasses need to implement this class for theirs specific state.\n */", "answers": [" public abstract void toXContent(XContentBuilder builder, T state) throws IOException;"], "length": 708, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "71b20371-691a-41a5-ab71-e54f2dc1dcdd", "reasoning": "The comment describes an abstract method that subclasses must implement to write the state into an XContentBuilder. The write() method later calls toXContent(builder, state), so the next line should declare this abstract method with appropriate visibility, parameters, and throws clause.", "reasoning_model_answer": "protected abstract void toXContent(XContentBuilder builder, T state) throws IOException;", "assistant_with_reasoning": "\nThe comment describes an abstract method that subclasses must implement to write the state into an XContentBuilder. The write() method later calls toXContent(builder, state), so the next line should declare this abstract method with appropriate visibility, parameters, and throws clause.\n\nprotected abstract void toXContent(XContentBuilder builder, T state) throws IOException;", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 2.946, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 7270, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "protected abstract void toXContent(XContentBuilder builder, T state) throws IOException;", "score": 0.92, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "// Copyright 2005-2010 Gallio Project - http://www.gallio.org/\n// Portions Copyright 2000-2004 Jonathan de Halleux\n// \n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n// \n// http://www.apache.org/licenses/LICENSE-2.0\n// \n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nusing System;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Threading;\nusing Gallio.Common;\nusing Gallio.Common.Collections;\nusing Gallio.Common.Policies;\nusing Gallio.Common.Concurrency;\nusing Gallio.Model;\nusing Gallio.Common.Diagnostics;\nusing Gallio.Common.Markup;\n\nnamespace Gallio.Framework\n{\n /// \n /// A sandbox is an isolated environments for executing test actions.\n /// \n /// \n /// \n /// It provides the ability to abort actions in progress so that the test runner can proceed\n /// to run other actions.\n /// \n /// \n /// Sandboxes are hierarchically structured. When an outer sandbox is aborted, all\n /// of its inner sandboxes are likewise aborted. A sandbox also provides the ability\n /// to create new child sandboxes at will so that test actions can be isolated with\n /// fine granularity.\n /// \n /// \n /// This class is safe for use from multiple concurrent threads.\n /// \n /// \n [SystemInternal]\n public sealed class Sandbox : IDisposable\n {\n private Sandbox parent;\n\n private readonly object syncRoot = new object();\n private List> scopesAndThreads;\n private TestOutcome? abortOutcome;\n private string abortMessage;\n private event EventHandler aborted;\n private bool alreadyLoggedAbortOnce;\n private bool isDisposed;\n\n /// \n /// Creates a root sandbox.\n /// \n public Sandbox()\n {\n }\n\n /// \n /// An event that is dispatched when is called.\n /// \n /// \n /// \n /// If the sandbox has already been aborted then the event handler is immediately invoked.\n /// \n /// \n /// Thrown if the sandbox was disposed.\n public event EventHandler Aborted\n {\n add\n {\n lock (syncRoot)\n {\n ThrowIfDisposed();\n\n if (!abortOutcome.HasValue)\n {\n aborted += value;\n return;\n }\n }\n\n EventHandlerPolicy.SafeInvoke(value, this, EventArgs.Empty);\n }\n remove\n {\n lock (syncRoot)\n {\n ThrowIfDisposed();\n\n aborted -= value;\n }\n }\n }\n\n /// \n /// Returns true if was called.\n /// \n /// Thrown if the sandbox was disposed.\n public bool WasAborted\n {\n get\n {\n lock (syncRoot)\n {\n ThrowIfDisposed();\n return abortOutcome.HasValue;\n }\n }\n }\n\n /// \n /// Returns the passed to ,\n /// or null if has not been called.\n /// \n /// Thrown if the sandbox was disposed.\n public TestOutcome? AbortOutcome\n {\n get\n {\n lock (syncRoot)\n {\n ThrowIfDisposed();\n return abortOutcome;\n }\n }\n }\n\n /// \n /// Gets a message that will be logged when the sandbox is aborted, or null if none.\n /// \n /// Thrown if the sandbox was disposed.\n public string AbortMessage\n {\n get\n {\n lock (syncRoot)\n {\n ThrowIfDisposed();\n return abortMessage;\n }\n }\n }\n\n /// \n /// Disposes the sandbox.\n /// \n /// \n /// \n /// All currently executing actions are aborted with \n /// if has not already been called.\n /// \n /// \n public void Dispose()\n {\n Abort(TestOutcome.Error, \"The sandbox was disposed.\", false);\n\n Sandbox cachedParent;\n lock (syncRoot)\n {\n if (isDisposed)\n return;\n\n cachedParent = parent;\n parent = null;\n isDisposed = true;\n }\n\n if (cachedParent != null)\n cachedParent.Aborted -= HandleParentAborted;\n }\n\n /// \n /// Creates a child sandbox.\n /// \n /// \n /// \n /// When the parent sandbox is aborted, the child will likewise be aborted. This policy\n /// offers a mechanism to scope actions recursively.\n /// \n /// \n /// The child sandbox.\n /// Thrown if the sandbox was disposed.\n public Sandbox CreateChild()\n {\n ThrowIfDisposed();\n\n Sandbox child = new Sandbox();\n child.parent = this;\n Aborted += child.HandleParentAborted;\n return child;\n }\n\n /// \n /// Aborts all actions in progress within this context.\n /// \n /// \n /// \n /// The abort is persistent and cannot be reverted. Therefore once aborted, no further\n /// test actions will be permitted to run. Subsequent calls to \n /// will have no effect.\n /// \n /// \n /// The outcome to be returned from aborted actions.\n /// A message to be logged when the action is aborted, or null if none.\n /// Thrown if the sandbox was disposed.\n public void Abort(TestOutcome outcome, string message)\n {\n Abort(outcome, message, true);\n }\n\n private void Abort(TestOutcome outcome, string message, bool throwIfDisposed)\n {\n EventHandler cachedHandler;\n ThreadAbortScope[] cachedScopes;\n lock (syncRoot)\n {\n if (throwIfDisposed)\n ThrowIfDisposed();\n\n if (abortOutcome.HasValue)\n return;\n\n abortOutcome = outcome;\n abortMessage = message;\n\n cachedScopes = scopesAndThreads != null\n ? GenericCollectionUtils.ConvertAllToArray(scopesAndThreads, pair => pair.First)\n : null;\n scopesAndThreads = null;\n\n cachedHandler = aborted;\n aborted = null;\n }\n\n if (cachedScopes != null)\n {\n foreach (ThreadAbortScope scope in cachedScopes)\n scope.Abort();\n }\n\n EventHandlerPolicy.SafeInvoke(cachedHandler, this, EventArgs.Empty);\n }\n\n /// \n /// Uses a specified timeout for all actions run within a block of code.\n /// When the timeout expires, the sandbox will be aborted.\n /// \n /// \n /// \nThe comment is opening an example block with a CDATA section. In the Gallio Sandbox class, the next line typically shows how to use the WithTimeout method, which is demonstrated with a using statement. Therefore the next line of code is the start of that example: a using statement that calls sandbox.WithTimeout with a TimeSpan.\n\nusing (sandbox.WithTimeout(TimeSpan.FromSeconds(10)))", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.743, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 8707, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "using (sandbox.WithTimeout(TimeSpan.FromSeconds(10)))", "score": 0.8, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\npackage org.apache.accumulo.tracer;\n\nimport static java.nio.charset.StandardCharsets.UTF_8;\nimport static org.apache.accumulo.fate.util.UtilWaitThread.sleepUninterruptibly;\n\nimport java.io.IOException;\nimport java.net.InetAddress;\nimport java.net.InetSocketAddress;\nimport java.net.ServerSocket;\nimport java.nio.channels.ServerSocketChannel;\nimport java.util.Arrays;\nimport java.util.Map;\nimport java.util.Map.Entry;\nimport java.util.concurrent.TimeUnit;\nimport java.util.concurrent.atomic.AtomicReference;\nimport java.util.stream.Collectors;\n\nimport org.apache.accumulo.core.Constants;\nimport org.apache.accumulo.core.client.Accumulo;\nimport org.apache.accumulo.core.client.AccumuloClient;\nimport org.apache.accumulo.core.client.AccumuloException;\nimport org.apache.accumulo.core.client.AccumuloSecurityException;\nimport org.apache.accumulo.core.client.BatchWriter;\nimport org.apache.accumulo.core.client.BatchWriterConfig;\nimport org.apache.accumulo.core.client.IteratorSetting;\nimport org.apache.accumulo.core.client.MutationsRejectedException;\nimport org.apache.accumulo.core.client.TableExistsException;\nimport org.apache.accumulo.core.client.TableNotFoundException;\nimport org.apache.accumulo.core.client.security.tokens.AuthenticationToken;\nimport org.apache.accumulo.core.client.security.tokens.AuthenticationToken.Properties;\nimport org.apache.accumulo.core.client.security.tokens.KerberosToken;\nimport org.apache.accumulo.core.client.security.tokens.PasswordToken;\nimport org.apache.accumulo.core.conf.AccumuloConfiguration;\nimport org.apache.accumulo.core.conf.Property;\nimport org.apache.accumulo.core.data.Mutation;\nimport org.apache.accumulo.core.data.Value;\nimport org.apache.accumulo.core.iterators.user.AgeOffFilter;\nimport org.apache.accumulo.fate.zookeeper.ZooReaderWriter;\nimport org.apache.accumulo.fate.zookeeper.ZooUtil.NodeExistsPolicy;\nimport org.apache.accumulo.server.ServerContext;\nimport org.apache.accumulo.server.ServerOpts;\nimport org.apache.accumulo.server.ServerUtil;\nimport org.apache.accumulo.server.conf.ServerConfigurationFactory;\nimport org.apache.accumulo.server.security.SecurityUtil;\nimport org.apache.accumulo.server.util.time.SimpleTimer;\nimport org.apache.accumulo.start.classloader.vfs.AccumuloVFSClassLoader;\nimport org.apache.accumulo.tracer.thrift.RemoteSpan;\nimport org.apache.accumulo.tracer.thrift.SpanReceiver.Iface;\nimport org.apache.accumulo.tracer.thrift.SpanReceiver.Processor;\nimport org.apache.hadoop.io.Text;\nimport org.apache.thrift.TByteArrayOutputStream;\nimport org.apache.thrift.TException;\nimport org.apache.thrift.protocol.TCompactProtocol;\nimport org.apache.thrift.server.TServer;\nimport org.apache.thrift.server.TThreadPoolServer;\nimport org.apache.thrift.transport.TServerSocket;\nimport org.apache.thrift.transport.TServerTransport;\nimport org.apache.thrift.transport.TTransport;\nimport org.apache.zookeeper.WatchedEvent;\nimport org.apache.zookeeper.Watcher;\nimport org.apache.zookeeper.Watcher.Event.EventType;\nimport org.apache.zookeeper.Watcher.Event.KeeperState;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\npublic class TraceServer implements Watcher, AutoCloseable {\n\n private static final Logger log = LoggerFactory.getLogger(TraceServer.class);\n private final ServerConfigurationFactory serverConfiguration;\n private final ServerContext context;\n private final TServer server;\n private final AtomicReference writer;\n private final AccumuloClient accumuloClient;\n final String tableName;\n private static final int BATCH_WRITER_MAX_LATENCY = 5;\n private static final long SCHEDULE_PERIOD = 1000;\n private static final long SCHEDULE_DELAY = 1000;\n\n private static void put(Mutation m, String cf, String cq, byte[] bytes, int len) {\n m.put(new Text(cf), new Text(cq), new Value(bytes, 0, len));\n }\n\n @Override\n public void close() {\n if (accumuloClient != null) {\n accumuloClient.close();\n }\n }\n\n static class ByteArrayTransport extends TTransport {\n TByteArrayOutputStream out = new TByteArrayOutputStream();\n\n @Override\n public boolean isOpen() {\n return true;\n }\n\n @Override\n public void open() {}\n\n @Override\n public void close() {}\n\n @Override\n public int read(byte[] buf, int off, int len) {\n return 0;\n }\n\n @Override\n public void write(byte[] buf, int off, int len) {\n out.write(buf, off, len);\n }\n\n public byte[] get() {\n return out.get();\n }\n\n public int len() {\n return out.len();\n }\n }\n\n class Receiver implements Iface {\n @Override\n public void span(RemoteSpan s) throws TException {\n String idString = Long.toHexString(s.traceId);\n String startString = Long.toHexString(s.start);\n Mutation spanMutation = new Mutation(new Text(idString));\n Mutation indexMutation = new Mutation(new Text(\"idx:\" + s.svc + \":\" + startString));\n long diff = s.stop - s.start;\n indexMutation.put(new Text(s.description), new Text(s.sender),\n new Value(idString + \":\" + Long.toHexString(diff)));\n ByteArrayTransport transport = new ByteArrayTransport();\n TCompactProtocol protocol = new TCompactProtocol(transport);\n s.write(protocol);\n String parentString = s.getParentIdsSize() == 0 ? \"\" : s.getParentIds().stream()\n .map(x -> Long.toHexString(x)).collect(Collectors.toList()).toString();\n put(spanMutation, \"span\", parentString + \":\" + Long.toHexString(s.spanId), transport.get(),\n transport.len());\n // Map the root span to time so we can look up traces by time\n Mutation timeMutation = null;\n if (s.getParentIdsSize() == 0) {\n timeMutation = new Mutation(new Text(\"start:\" + startString));\n put(timeMutation, \"id\", idString, transport.get(), transport.len());\n }\n try {\n final BatchWriter writer = TraceServer.this.writer.get();\n /*\n * Check for null, because we expect spans to come in much faster than flush calls. In the\n * case of failure, we'd rather avoid logging tons of NPEs.\n */\n if (writer == null) {\n log.warn(\"writer is not ready; discarding span.\");\n return;\n }\n writer.addMutation(spanMutation);\n writer.addMutation(indexMutation);\n if (timeMutation != null) {\n writer.addMutation(timeMutation);\n }\n } catch (MutationsRejectedException exception) {\n log.warn(\"Unable to write mutation to table; discarding span. set log\"\n + \" level to DEBUG for span information and stacktrace. cause: \" + exception);\n if (log.isDebugEnabled()) {\n log.debug(\"discarded span due to rejection of mutation: \" + spanMutation, exception);\n }\n /*\n * XXX this could be e.g. an IllegalArgumentException if we're trying to write this mutation\n * to a writer that has been closed since we retrieved it\n */\n } catch (RuntimeException exception) {\n log.warn(\"Unable to write mutation to table; discarding span. set log\"\n + \" level to DEBUG for stacktrace. cause: \" + exception);\n log.debug(\"unable to write mutation to table due to exception.\", exception);\n }\n }\n\n }\n\n public TraceServer(ServerContext context, String hostname) throws Exception {\n this.context = context;\n this.serverConfiguration = context.getServerConfFactory();\n log.info(\"Version {}\", Constants.VERSION);\n log.info(\"Instance {}\", context.getInstanceID());\n AccumuloConfiguration conf = serverConfiguration.getSystemConfiguration();\n tableName = conf.get(Property.TRACE_TABLE);\n accumuloClient = ensureTraceTableExists(conf);\n\n int[] ports = conf.getPort(Property.TRACE_PORT);\n ServerSocket sock = null;", "answers": [" for (int port : ports) {"], "length": 759, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "fd15530d-3561-4184-b119-0f9144d4f5df", "reasoning": "In the constructor, after declaring the ServerSocket variable, the code needs to attempt binding to one of the configured ports. The typical pattern is to iterate over the ports array, trying each until successful. Therefore the next line starts a for‑each loop over the ports array.", "reasoning_model_answer": "for (int port : ports) {", "assistant_with_reasoning": "\nIn the constructor, after declaring the ServerSocket variable, the code needs to attempt binding to one of the configured ports. The typical pattern is to iterate over the ports array, trying each until successful. Therefore the next line starts a for‑each loop over the ports array.\n\nfor (int port : ports) {", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.06, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 8643, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "for (int port : ports) {", "score": 0.92, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n* @author Boris V. Kuznetsov\n* @version $Revision$\n*/\n\npackage org.apache.harmony.security.tests.java.security;\n\nimport dalvik.annotation.KnownFailure;\nimport dalvik.annotation.TestTargetClass;\nimport dalvik.annotation.TestTargetNew;\nimport dalvik.annotation.TestTargets;\nimport dalvik.annotation.TestLevel;\n\nimport java.security.InvalidParameterException;\nimport java.security.NoSuchAlgorithmException;\nimport java.security.Provider;\nimport java.security.Security;\nimport java.security.Signature;\nimport java.security.InvalidAlgorithmParameterException;\nimport java.security.InvalidKeyException;\nimport java.security.Key;\nimport java.security.PrivateKey;\nimport java.security.PublicKey;\nimport java.security.SecureRandom;\nimport java.security.SignatureException;\nimport java.security.cert.Certificate;\nimport java.security.spec.AlgorithmParameterSpec;\n\nimport org.apache.harmony.security.tests.support.MySignature1;\n\nimport junit.framework.TestCase;\n@TestTargetClass(Signature.class)\n/**\n * Tests for Signature constructor and methods\n *\n */\npublic class SignatureTest extends TestCase {\n\n /*\n * Class under test for Signature(String)\n */\n @TestTargetNew(\n level = TestLevel.COMPLETE,\n notes = \"\",\n method = \"Signature\",\n args = {java.lang.String.class}\n )\n public void testConstructor() {\n String [] algorithms = { \"SHA256WITHRSA\", \"NONEWITHDSA\", \"SHA384WITHRSA\",\n \"MD5ANDSHA1WITHRSA\", \"SHA512WITHRSA\",\n \"SHA1WITHRSA\", \"SHA1WITHDSA\", \"MD5WITHRSA\" };\n for (int i = 0; i < algorithms.length; i ++) {\n MySignature1 s = new MySignature1(algorithms[i]);\n assertEquals(algorithms[i],s.getAlgorithm());\n assertNull(s.getProvider());\n assertEquals(0, s.getState());\n }\n\n MySignature1 s1 = new MySignature1(null);\n assertNull(s1.getAlgorithm());\n assertNull(s1.getProvider());\n assertEquals(0, s1.getState());\n\n MySignature1 s2 = new MySignature1(\"ABCD@#&^%$)(*&\");\n assertEquals(\"ABCD@#&^%$)(*&\", s2.getAlgorithm());\n assertNull(s2.getProvider());\n assertEquals(0, s2.getState());\n }\n\n /*\n * Class under test for Object clone()\n */\n @TestTargetNew(\n level = TestLevel.PARTIAL_COMPLETE,\n notes = \"Just exception case was tested\",\n method = \"clone\",\n args = {}\n )\n public void testClone() {\n MySignature1 s = new MySignature1(\"ABC\");\n try {\n s.clone();\n fail(\"No expected CloneNotSupportedException\");\n } catch (CloneNotSupportedException e) {\n }\n\n MySignature sc = new MySignature();\n try {\n sc.clone();\n } catch (CloneNotSupportedException e) {\n fail(\"unexpected exception: \" + e);\n }\n\n }\n\n @TestTargetNew(\n level = TestLevel.COMPLETE,\n notes = \"\",\n method = \"getProvider\",\n args = {}\n )\n public void testGetProvider() {\n MySignature1 s = new MySignature1(\"ABC\");\n\n assertEquals(\"state\", MySignature1.UNINITIALIZED, s.getState());\n assertNull(\"provider\", s.getProvider());\n }\n\n @TestTargetNew(\n level = TestLevel.COMPLETE,\n notes = \"\",\n method = \"getAlgorithm\",\n args = {}\n )\n public void testGetAlgorithm() {\n MySignature1 s = new MySignature1(\"ABC\");\n\n assertEquals(\"state\", MySignature1.UNINITIALIZED, s.getState());\n assertEquals(\"algorithm\", \"ABC\", s.getAlgorithm());\n }\n\n /*\n * Class under test for void initVerify(PublicKey)\n */\n @TestTargetNew(\n level = TestLevel.COMPLETE,\n notes = \"InvalidKeyException checking missed\",\n method = \"initVerify\",\n args = {java.security.PublicKey.class}\n )\n public void testInitVerifyPublicKey() throws InvalidKeyException {\n MySignature1 s = new MySignature1(\"ABC\");\n\n s.initVerify(new MyPublicKey());\n assertEquals(\"state\", MySignature1.VERIFY, s.getState());\n assertTrue(\"initVerify() failed\", s.runEngineInitVerify);\n\n try {\n Signature sig = getTestSignature();\n sig.initVerify((PublicKey)null);\n } catch (InvalidKeyException e) {\n // ok\n } catch (NoSuchAlgorithmException e) {\n fail(\"unexpected : \" + e);\n }\n }\n\n /*\n * Class under test for void initVerify(Certificate)\n */\n @TestTargetNew(\n level = TestLevel.COMPLETE,\n notes = \"\",\n method = \"initVerify\",\n args = {java.security.cert.Certificate.class}\n )\n public void testInitVerifyCertificate() throws InvalidKeyException {\n MySignature1 s = new MySignature1(\"ABC\");\n\n s.initVerify(new MyCertificate());\n assertEquals(\"state\", MySignature1.VERIFY, s.getState());\n assertTrue(\"initVerify() failed\", s.runEngineInitVerify);\n\n try {\n Signature sig = getTestSignature();\n sig.initVerify(new MyCertificate());\n fail(\"expected InvalidKeyException\");\n } catch (InvalidKeyException e) {\n // ok\n } catch (NoSuchAlgorithmException e) {\n fail(\"unexpected : \" + e);\n }\n }\n\n /*\n * Class under test for void initSign(PrivateKey)\n */\n @TestTargetNew(\n level = TestLevel.COMPLETE,\n notes = \"\",\n method = \"initSign\",\n args = {java.security.PrivateKey.class}\n )\n public void testInitSignPrivateKey() throws InvalidKeyException {\n MySignature1 s = new MySignature1(\"ABC\");\n\n s.initSign(new MyPrivateKey());\n assertEquals(\"state\", MySignature1.SIGN, s.getState());\n assertTrue(\"initSign() failed\", s.runEngineInitSign);\n\n try {\n Signature signature = getTestSignature();\n signature.initSign(null);\n fail(\"expected InvalidKeyException\");\n } catch (InvalidKeyException e) {\n // ok\n } catch (NoSuchAlgorithmException e) {\n fail(\"unexpected: \" + e);\n }\n }\n\n private Signature getTestSignature() throws NoSuchAlgorithmException {\n Provider provider = new MyProvider(\"TestProvider\", 1.0, \"Test Provider\", \"Signature.ABC\", MySignature.class.getName());\n Security.insertProviderAt(provider, 1);\n\n try {\n return Signature.getInstance(\"ABC\");\n }\n finally {\n Security.removeProvider(\"TestProvider\");\n }\n\n }\n\n /*\n * Class under test for void initSign(PrivateKey, SecureRandom)\n */\n @TestTargetNew(\n level = TestLevel.COMPLETE,\n notes = \"InvalidKeyException checking missed\",\n method = \"initSign\",\n args = {java.security.PrivateKey.class, java.security.SecureRandom.class}\n )\n public void testInitSignPrivateKeySecureRandom() throws InvalidKeyException {\n MySignature1 s = new MySignature1(\"ABC\");\n\n s.initSign(new MyPrivateKey(), new SecureRandom());", "answers": [" assertEquals(\"state\", MySignature1.SIGN, s.getState());"], "length": 692, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "d899ff46-1640-4bdd-875c-210be52fed8b", "reasoning": "The method testInitSignPrivateKeySecureRandom mirrors testInitSignPrivateKey. After calling s.initSign(new MyPrivateKey(), new SecureRandom()), the test should verify that the signature object's state is SIGN. The first verification step is an assertEquals checking the state, matching the pattern used earlier.", "reasoning_model_answer": "assertEquals(\"state\", MySignature1.SIGN, s.getState());", "assistant_with_reasoning": "\nThe method testInitSignPrivateKeySecureRandom mirrors testInitSignPrivateKey. After calling s.initSign(new MyPrivateKey(), new SecureRandom()), the test should verify that the signature object's state is SIGN. The first verification step is an assertEquals checking the state, matching the pattern used earlier.\n\nassertEquals(\"state\", MySignature1.SIGN, s.getState());", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.445, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 7906, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "assertEquals(\"state\", MySignature1.SIGN, s.getState());", "score": 0.93, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/*\n * Copyright (c) 2005 - 2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not\n * use this file except in compliance with the License. You may obtain a copy\n * of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed\n * under the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR\n * CONDITIONS OF ANY KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations under the License.\n */\npackage org.wso2.carbon.event.receiver.admin;\n\nimport org.apache.axis2.AxisFault;\nimport org.apache.axis2.engine.AxisConfiguration;\nimport org.apache.commons.logging.Log;\nimport org.apache.commons.logging.LogFactory;\nimport org.wso2.carbon.context.PrivilegedCarbonContext;\nimport org.wso2.carbon.core.AbstractAdmin;\nimport org.wso2.carbon.databridge.commons.Attribute;\nimport org.wso2.carbon.databridge.commons.StreamDefinition;\nimport org.wso2.carbon.event.input.adapter.core.InputEventAdapterConfiguration;\nimport org.wso2.carbon.event.input.adapter.core.InputEventAdapterSchema;\nimport org.wso2.carbon.event.input.adapter.core.InputEventAdapterService;\nimport org.wso2.carbon.event.input.adapter.core.Property;\nimport org.wso2.carbon.event.receiver.admin.internal.EventReceiverAdminConstants;\nimport org.wso2.carbon.event.receiver.admin.internal.ds.EventReceiverAdminServiceValueHolder;\nimport org.wso2.carbon.event.receiver.core.EventReceiverService;\nimport org.wso2.carbon.event.receiver.core.config.*;\nimport org.wso2.carbon.event.receiver.core.config.mapping.*;\nimport org.wso2.carbon.event.receiver.core.exception.EventReceiverConfigurationException;\n\nimport java.util.*;\n\npublic class EventReceiverAdminService extends AbstractAdmin {\n\n private static Log log = LogFactory.getLog(EventReceiverAdminService.class);\n\n public EventReceiverConfigurationInfoDto[] getAllActiveEventReceiverConfigurations()\n throws AxisFault {\n\n EventReceiverService eventReceiverService = EventReceiverAdminServiceValueHolder.getEventReceiverService();\n\n // get event receiver configurations\n List eventReceiverConfigurationList;\n eventReceiverConfigurationList = eventReceiverService.getAllActiveEventReceiverConfigurations();\n\n if (eventReceiverConfigurationList != null) {\n // create event receiver configuration details array\n EventReceiverConfigurationInfoDto[] eventReceiverConfigurationInfoDtoArray = new\n EventReceiverConfigurationInfoDto[eventReceiverConfigurationList.size()];\n for (int index = 0; index < eventReceiverConfigurationInfoDtoArray.length; index++) {\n EventReceiverConfiguration eventReceiverConfiguration = eventReceiverConfigurationList.get(index);\n String eventReceiverName = eventReceiverConfiguration.getEventReceiverName();\n String mappingType = eventReceiverConfiguration.getInputMapping().getMappingType();\n String inputEventAdapterType = eventReceiverConfiguration.getFromAdapterConfiguration().getType();\n String streamNameWithVersion = eventReceiverConfiguration.getToStreamName() + \":\" + eventReceiverConfiguration.getToStreamVersion();\n\n\n eventReceiverConfigurationInfoDtoArray[index] = new EventReceiverConfigurationInfoDto();\n eventReceiverConfigurationInfoDtoArray[index].setEventReceiverName(eventReceiverName);\n eventReceiverConfigurationInfoDtoArray[index].setMessageFormat(mappingType);\n eventReceiverConfigurationInfoDtoArray[index].setInputAdapterType(inputEventAdapterType);\n eventReceiverConfigurationInfoDtoArray[index].setInputStreamId(streamNameWithVersion);\n eventReceiverConfigurationInfoDtoArray[index].setEnableStats(eventReceiverConfiguration.isStatisticsEnabled());\n eventReceiverConfigurationInfoDtoArray[index].setEnableTracing(eventReceiverConfiguration.isTraceEnabled());\n eventReceiverConfigurationInfoDtoArray[index].setEditable(eventReceiverConfiguration.isEditable());\n }\n Arrays.sort(eventReceiverConfigurationInfoDtoArray, new Comparator() {\n\n @Override\n public int compare(Object o1, Object o2) {\n return ((EventReceiverConfigurationInfoDto) o1).getEventReceiverName().compareTo(((EventReceiverConfigurationInfoDto) o2).getEventReceiverName());\n }\n });\n return eventReceiverConfigurationInfoDtoArray;\n } else {\n return new EventReceiverConfigurationInfoDto[0];\n }\n }\n\n public EventReceiverConfigurationInfoDto[] getAllStreamSpecificActiveEventReceiverConfigurations(\n String streamId)\n throws AxisFault {\n\n EventReceiverService eventReceiverService = EventReceiverAdminServiceValueHolder.getEventReceiverService();\n\n // get event receiver configurations\n List eventReceiverConfigurationList;\n eventReceiverConfigurationList = eventReceiverService.getAllActiveEventReceiverConfigurations(streamId);\n\n if (eventReceiverConfigurationList != null) {\n // create event receiver configuration details array\n EventReceiverConfigurationInfoDto[] eventReceiverConfigurationInfoDtoArray = new\n EventReceiverConfigurationInfoDto[eventReceiverConfigurationList.size()];\n for (int index = 0; index < eventReceiverConfigurationInfoDtoArray.length; index++) {\n EventReceiverConfiguration eventReceiverConfiguration = eventReceiverConfigurationList.get(index);\n String eventReceiverName = eventReceiverConfiguration.getEventReceiverName();\n String mappingType = eventReceiverConfiguration.getInputMapping().getMappingType();\n String inputEventAdapterType = eventReceiverConfiguration.getFromAdapterConfiguration().getType();\n\n eventReceiverConfigurationInfoDtoArray[index] = new EventReceiverConfigurationInfoDto();\n eventReceiverConfigurationInfoDtoArray[index].setEventReceiverName(eventReceiverName);\n eventReceiverConfigurationInfoDtoArray[index].setMessageFormat(mappingType);\n eventReceiverConfigurationInfoDtoArray[index].setInputAdapterType(inputEventAdapterType);\n eventReceiverConfigurationInfoDtoArray[index].setEnableStats(eventReceiverConfiguration.isStatisticsEnabled());\n eventReceiverConfigurationInfoDtoArray[index].setEnableTracing(eventReceiverConfiguration.isTraceEnabled());\n eventReceiverConfigurationInfoDtoArray[index].setEditable(eventReceiverConfiguration.isEditable());\n }\n Arrays.sort(eventReceiverConfigurationInfoDtoArray,new Comparator() {\n\n @Override\n public int compare(Object o1, Object o2) {\n return ((EventReceiverConfigurationInfoDto) o1).getEventReceiverName().compareTo(((EventReceiverConfigurationInfoDto) o2).getEventReceiverName());\n }\n });\n return eventReceiverConfigurationInfoDtoArray;\n } else {\n return new EventReceiverConfigurationInfoDto[0];\n }\n }\n\n public EventReceiverConfigurationFileDto[] getAllInactiveEventReceiverConfigurations()\n throws AxisFault {\n\n EventReceiverService eventReceiverService = EventReceiverAdminServiceValueHolder.getEventReceiverService();\n List eventReceiverConfigurationFileList = eventReceiverService.getAllInactiveEventReceiverConfigurations();\n if (eventReceiverConfigurationFileList != null) {\n\n // create event receiver file details array\n EventReceiverConfigurationFileDto[] eventReceiverFileDtoArray = new\n EventReceiverConfigurationFileDto[eventReceiverConfigurationFileList.size()];\n\n for (int index = 0; index < eventReceiverFileDtoArray.length; index++) {\n EventReceiverConfigurationFile eventReceiverConfigurationFile = eventReceiverConfigurationFileList.get(index);\n String fileName = eventReceiverConfigurationFile.getFileName();\n String eventReceiverName = eventReceiverConfigurationFile.getEventReceiverName();\n String statusMsg = eventReceiverConfigurationFile.getDeploymentStatusMessage();\n if (eventReceiverConfigurationFile.getDependency() != null) {\n statusMsg = statusMsg + \" [Dependency: \" + eventReceiverConfigurationFile.getDependency() + \"]\";\n }\n\n eventReceiverFileDtoArray[index] = new EventReceiverConfigurationFileDto(fileName, eventReceiverName, statusMsg);\n }\n Arrays.sort(eventReceiverFileDtoArray,new Comparator() {\n\n @Override\n public int compare(Object o1, Object o2) {\n return ((EventReceiverConfigurationFileDto) o1).getFileName().compareTo(((EventReceiverConfigurationFileDto) o2).getFileName());\n }\n });\n return eventReceiverFileDtoArray;\n } else {\n return new EventReceiverConfigurationFileDto[0];\n }\n }\n\n public EventReceiverConfigurationDto getActiveEventReceiverConfiguration(\n String eventReceiverName) throws AxisFault {\n\n EventReceiverService eventReceiverService = EventReceiverAdminServiceValueHolder.getEventReceiverService();\n\n EventReceiverConfiguration eventReceiverConfiguration = eventReceiverService.getActiveEventReceiverConfiguration(eventReceiverName);\n if (eventReceiverConfiguration != null) {\n EventReceiverConfigurationDto eventReceiverConfigurationDto = new EventReceiverConfigurationDto();\n eventReceiverConfigurationDto.setEventReceiverName(eventReceiverConfiguration.getEventReceiverName());\n String streamNameWithVersion = eventReceiverConfiguration.getToStreamName() + \":\" + eventReceiverConfiguration.getToStreamVersion();\n eventReceiverConfigurationDto.setToStreamNameWithVersion(streamNameWithVersion);\n\n InputEventAdapterConfiguration fromAdapterConfiguration = eventReceiverConfiguration.getFromAdapterConfiguration();\n\n if (fromAdapterConfiguration != null) {\n InputEventAdapterService inputEventAdapterService = EventReceiverAdminServiceValueHolder.getInputEventAdapterService();\n InputEventAdapterSchema inputEventAdapterSchema = inputEventAdapterService.getInputEventAdapterSchema(fromAdapterConfiguration.getType());\n\n InputAdapterConfigurationDto fromAdapterConfigurationDto = new InputAdapterConfigurationDto();\n fromAdapterConfigurationDto.setEventAdapterType(fromAdapterConfiguration.getType());\n fromAdapterConfigurationDto.setSupportedMessageFormats(\n inputEventAdapterSchema.getSupportedMessageFormats().\n toArray(new String[inputEventAdapterSchema.getSupportedMessageFormats().size()]));\n\n Map inputAdapterProperties = new HashMap();\n inputAdapterProperties.putAll(fromAdapterConfiguration.getProperties());\n\n DetailInputAdapterPropertyDto[] detailInputAdapterPropertyDtos = getPropertyConfigurations(inputAdapterProperties, inputEventAdapterSchema.getPropertyList());\n fromAdapterConfigurationDto.setInputEventAdapterProperties(detailInputAdapterPropertyDtos);\n\n eventReceiverConfigurationDto.setFromAdapterConfigurationDto(fromAdapterConfigurationDto);\n }\n\n InputMapping inputMapping = eventReceiverConfiguration.getInputMapping();\n\n eventReceiverConfigurationDto.setCustomMappingEnabled(eventReceiverConfiguration.getInputMapping().isCustomMappingEnabled());\n eventReceiverConfigurationDto.setMessageFormat(inputMapping.getMappingType());\n\n if (inputMapping.isCustomMappingEnabled()) {\n if (inputMapping.getMappingType().equalsIgnoreCase(EventReceiverConstants.ER_WSO2EVENT_MAPPING_TYPE)) {\n List metaMappingPropertyDtos = new ArrayList();\n List correlationMappingPropertyDtos = new ArrayList();\n List payloadMappingPropertyDtos = new ArrayList();\n\n for (InputMappingAttribute inputMappingAttribute : inputMapping.getInputMappingAttributes()) {\n EventMappingPropertyDto mappingPropertyDto = new EventMappingPropertyDto();\n mappingPropertyDto.setName(inputMappingAttribute.getFromElementKey());\n mappingPropertyDto.setValueOf(inputMappingAttribute.getToElementKey());\n mappingPropertyDto.setType(EventReceiverAdminConstants.ATTRIBUTE_TYPE_STRING_MAP.get(inputMappingAttribute.getToElementType()));\n mappingPropertyDto.setDefaultValue(inputMappingAttribute.getDefaultValue());\n if (EventReceiverConstants.META_DATA_VAL.equalsIgnoreCase(inputMappingAttribute.getFromElementType())) {\n metaMappingPropertyDtos.add(mappingPropertyDto);\n } else if (EventReceiverConstants.CORRELATION_DATA_VAL.equalsIgnoreCase(inputMappingAttribute.getFromElementType())) {\n correlationMappingPropertyDtos.add(mappingPropertyDto);\n } else if (EventReceiverConstants.PAYLOAD_DATA_VAL.equalsIgnoreCase(inputMappingAttribute.getFromElementType())) {\n payloadMappingPropertyDtos.add(mappingPropertyDto);\n }\n }\n eventReceiverConfigurationDto.setMetaMappingPropertyDtos(metaMappingPropertyDtos.toArray(new EventMappingPropertyDto[metaMappingPropertyDtos.size()]));\n eventReceiverConfigurationDto.setCorrelationMappingPropertyDtos(correlationMappingPropertyDtos.toArray(new EventMappingPropertyDto[correlationMappingPropertyDtos.size()]));\n eventReceiverConfigurationDto.setMappingPropertyDtos(payloadMappingPropertyDtos.toArray(new EventMappingPropertyDto[payloadMappingPropertyDtos.size()]));\n } else if (inputMapping.getMappingType().equalsIgnoreCase(EventReceiverConstants.ER_XML_MAPPING_TYPE)) {\n\n List xPathDefinitions = new ArrayList();\n for (XPathDefinition xPathDefinition : ((XMLInputMapping) inputMapping).getXPathDefinitions()) {\n EventMappingPropertyDto mappingPropertyDto = new EventMappingPropertyDto();\n mappingPropertyDto.setName(xPathDefinition.getPrefix());\n mappingPropertyDto.setValueOf(xPathDefinition.getNamespaceUri());\n xPathDefinitions.add(mappingPropertyDto);\n }\n eventReceiverConfigurationDto.setXpathDefinitionMappingPropertyDtos(xPathDefinitions.toArray(new EventMappingPropertyDto[xPathDefinitions.size()]));\n\n List mappingPropertyDtos = new ArrayList();\n for (InputMappingAttribute inputMappingAttribute : inputMapping.getInputMappingAttributes()) {\n EventMappingPropertyDto mappingPropertyDto = new EventMappingPropertyDto();\n mappingPropertyDto.setName(inputMappingAttribute.getFromElementKey());\n mappingPropertyDto.setValueOf(inputMappingAttribute.getToElementKey());\n mappingPropertyDto.setType(EventReceiverAdminConstants.ATTRIBUTE_TYPE_STRING_MAP.get(inputMappingAttribute.getToElementType()));\n mappingPropertyDto.setDefaultValue(inputMappingAttribute.getDefaultValue());\n mappingPropertyDtos.add(mappingPropertyDto);\n }\n eventReceiverConfigurationDto.setMappingPropertyDtos(mappingPropertyDtos.toArray(new EventMappingPropertyDto[mappingPropertyDtos.size()]));\n eventReceiverConfigurationDto.setParentSelectorXpath(((XMLInputMapping) inputMapping).getParentSelectorXpath());\n\n } else {\n\n // for map, text and json\n List mappingPropertyDtos = new ArrayList();\n for (InputMappingAttribute inputMappingAttribute : inputMapping.getInputMappingAttributes()) {\n EventMappingPropertyDto mappingPropertyDto = new EventMappingPropertyDto();\n mappingPropertyDto.setName(inputMappingAttribute.getFromElementKey());\n mappingPropertyDto.setValueOf(inputMappingAttribute.getToElementKey());\n mappingPropertyDto.setType(EventReceiverAdminConstants.ATTRIBUTE_TYPE_STRING_MAP.get(inputMappingAttribute.getToElementType()));\n mappingPropertyDto.setDefaultValue(inputMappingAttribute.getDefaultValue());\n mappingPropertyDtos.add(mappingPropertyDto);\n }\n eventReceiverConfigurationDto.setMappingPropertyDtos(mappingPropertyDtos.toArray(new EventMappingPropertyDto[mappingPropertyDtos.size()]));\n\n }\n }\n\n return eventReceiverConfigurationDto;\n }\n\n return null;\n }\n\n public String getActiveEventReceiverConfigurationContent(String eventReceiverName)\n throws AxisFault {\n EventReceiverService eventReceiverService = EventReceiverAdminServiceValueHolder.getEventReceiverService();\n try {", "answers": [" return eventReceiverService.getActiveEventReceiverConfigurationContent(eventReceiverName);"], "length": 735, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "6939b326-e675-47aa-ba65-cb4f23caab69", "reasoning": "The method getActiveEventReceiverConfigurationContent should retrieve the configuration content from the EventReceiverService. Inside the try block, the next logical statement is to call the service method that returns the configuration string and return it, matching the method's return type.", "reasoning_model_answer": "return eventReceiverService.getActiveEventReceiverConfigurationContent(eventReceiverName);", "assistant_with_reasoning": "\nThe method getActiveEventReceiverConfigurationContent should retrieve the configuration content from the EventReceiverService. Inside the try block, the next logical statement is to call the service method that returns the configuration string and return it, matching the method's return type.\n\nreturn eventReceiverService.getActiveEventReceiverConfigurationContent(eventReceiverName);", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 2.128, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 18289, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "return eventReceiverService.getActiveEventReceiverConfigurationContent(eventReceiverName);", "score": 0.94, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/*\nCopyright (C) 1999 CERN - European Organization for Nuclear Research.\nPermission to use, copy, modify, distribute and sell this software and its documentation for any purpose \nis hereby granted without fee, provided that the above copyright notice appear in all copies and \nthat both that copyright notice and this permission notice appear in supporting documentation. \nCERN makes no representations about the suitability of this software for any purpose. \nIt is provided \"as is\" without expressed or implied warranty.\n */\npackage cern.colt.map.tdouble;\n\nimport cern.colt.function.tdouble.DoubleLongProcedure;\nimport cern.colt.function.tdouble.DoubleProcedure;\nimport cern.colt.list.tdouble.DoubleArrayList;\nimport cern.colt.list.tlong.LongArrayList;\nimport cern.colt.map.AbstractMap;\n\n/**\n * Abstract base class for hash maps holding (key,value) associations of type\n * (double-->long). First see the package summary and javadoc tree view to get the broad picture.\n *

    \n * Implementation:\n *

    \n * Almost all methods are expressed in terms of\n * {@link #forEachKey(DoubleProcedure)}. As such they are fully functional, but\n * inefficient. Override them in subclasses if necessary.\n * \n * @author wolfgang.hoschek@cern.ch\n * @version 1.0, 09/24/99\n * @see java.util.HashMap\n */\npublic abstract class AbstractDoubleLongMap extends AbstractMap {\n /**\n * \n */\n private static final long serialVersionUID = 1L;\n\n // public static int hashCollisions = 0; // for debug only\n /**\n * Makes this class non instantiable, but still let's others inherit from\n * it.\n */\n protected AbstractDoubleLongMap() {\n }\n\n /**\n * Returns true if the receiver contains the specified key.\n * \n * @return true if the receiver contains the specified key.\n */\n public boolean containsKey(final double key) {\n return !forEachKey(new DoubleProcedure() {\n public boolean apply(double iterKey) {\n return (key != iterKey);\n }\n });\n }\n\n /**\n * Returns true if the receiver contains the specified value.\n * \n * @return true if the receiver contains the specified value.\n */\n public boolean containsValue(final long value) {\n return !forEachPair(new DoubleLongProcedure() {\n public boolean apply(double iterKey, long iterValue) {\n return (value != iterValue);\n }\n });\n }\n\n /**\n * Returns a deep copy of the receiver; uses clone() and casts\n * the result.\n * \n * @return a deep copy of the receiver.\n */\n public AbstractDoubleLongMap copy() {\n return (AbstractDoubleLongMap) clone();\n }\n\n /**\n * Compares the specified object with this map for equality. Returns\n * true if the given object is also a map and the two maps\n * represent the same mappings. More formally, two maps m1 and\n * m2 represent the same mappings iff\n * \n *

    \n     * m1.forEachPair(\n     *  new DoubleLongProcedure() {\n     *      public boolean apply(double key, int value) {\n     *          return m2.containsKey(key) && m2.get(key) == value;\n     *      }\n     *  }\n     * )\n     * &&\n     * m2.forEachPair(\n     *  new DoubleLongProcedure() {\n     *      public boolean apply(double key, int value) {\n     *          return m1.containsKey(key) && m1.get(key) == value;\n     *      }\n     *  }\n     * );\n     * 
    \n * \n * This implementation first checks if the specified object is this map; if\n * so it returns true. Then, it checks if the specified object is a\n * map whose size is identical to the size of this set; if not, it it\n * returns false. If so, it applies the iteration as described\n * above.\n * \n * @param obj\n * object to be compared for equality with this map.\n * @return true if the specified object is equal to this map.\n */\n\n public boolean equals(Object obj) {\n if (obj == this)\n return true;\n\n if (!(obj instanceof AbstractDoubleLongMap))\n return false;\n final AbstractDoubleLongMap other = (AbstractDoubleLongMap) obj;\n if (other.size() != size())\n return false;\n\n return forEachPair(new DoubleLongProcedure() {\n public boolean apply(double key, long value) {\n return other.containsKey(key) && other.get(key) == value;\n }\n }) && other.forEachPair(new DoubleLongProcedure() {\n public boolean apply(double key, long value) {\n return containsKey(key) && get(key) == value;\n }\n });\n }\n\n /**\n * Applies a procedure to each key of the receiver, if any. Note: Iterates\n * over the keys in no particular order. Subclasses can define a particular\n * order, for example, \"sorted by key\". All methods which can be\n * expressed in terms of this method (most methods can) must\n * guarantee to use the same order defined by this method, even\n * if it is no particular order. This is necessary so that, for example,\n * methods keys and values will yield association pairs,\n * not two uncorrelated lists.\n * \n * @param procedure\n * the procedure to be applied. Stops iteration if the procedure\n * returns false, otherwise continues.\n * @return false if the procedure stopped before all keys where\n * iterated over, true otherwise.\n */", "answers": [" public abstract boolean forEachKey(DoubleProcedure procedure);"], "length": 734, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "cacabb47-17ec-4c22-b772-9633c02d5dd7", "reasoning": "The Javadoc comment just finished describing the forEachKey method. In this abstract class the method is declared as an abstract method that returns a boolean and takes a DoubleProcedure. Therefore the next line is the method signature.", "reasoning_model_answer": "public abstract boolean forEachKey(DoubleProcedure procedure);", "assistant_with_reasoning": "\nThe Javadoc comment just finished describing the forEachKey method. In this abstract class the method is declared as an abstract method that returns a boolean and takes a DoubleProcedure. Therefore the next line is the method signature.\n\npublic abstract boolean forEachKey(DoubleProcedure procedure);", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 2.898, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 5828, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "public abstract boolean forEachKey(DoubleProcedure procedure);", "score": 0.97, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "#!/bin/env python\n\n#\n# Copyright (C) 2012 by Adam Ewing (adam.ewing@gmail.com)\n#\n# Released under the MIT license, see LICENSE.txt\n#\n\nimport re, os, subprocess, tempfile, pysam, sys, argparse, peakparser\nfrom string import maketrans\n\ndef checkfile(fname):\n try:\n open(fname)\n except IOError as e:\n print \"can't find file: \" + fname\n sys.exit()\n\n# parse TCGA filename\ndef getTypeFromTCGA(fname):\n try:\n fields = os.path.basename(fname).split('-')\n sample = fields[3]\n if sample[0] == '0':\n return 'CANCER'\n if sample[0] == '1':\n return 'NORMAL'\n return None\n except:\n #print \"invalid TCGA filename: \" + fname\n return None\n\n# some people choose to use reference genomes with chromosome names that don't begin in 'chr'\n# since we do use 'chr', we need to detect those cases\ndef chromNameUsesPrefix(bam):\n for ref in bam.references:\n if re.search(\"^chr\",ref):\n return True\n return False\n\n# fix for the most common variation on chromosome names (leaving out the 'chr')\ndef fixChrName(name):\n if name[0] != 'c':\n return \"chr\" + name\n else:\n return name\n\n# average base quality over an interval\ndef avgQual(qstring,start,end,zeroChar):\n if start < 0:\n start = 0\n if end > len(qstring):\n end = len(qstring)\n\n offset = ord(zeroChar)\n\n return sum(map(lambda x: ord(x)-offset, qstring[start:end]))/(end-start)\n\n# capitalize 1-indexed seq between start and end\ndef capSeq(seq,start,end):\n start -= 1\n seq = seq.lower()\n chars = []\n for c in seq:\n chars.append(c)\n for i in range(start,end):\n chars[i] = chars[i].upper()\n return ''.join(chars)\n\n# runs bwa stdsw to align two sequences\ndef bwastdsw(queryName,query,refName,ref,queryIsFile=False,refIsFile=False):\n qfileName = ''\n rfileName = ''\n\n if queryIsFile:\n qfileName = query\n else:\n qfile = tempfile.NamedTemporaryFile(delete=False)\n qfile.write(\">%s\\n%s\\n\" % (queryName,query))\n qfile.close()\n qfileName = qfile.name\n\n if refIsFile:\n rfileName = ref\n else:\n rfile = tempfile.NamedTemporaryFile(delete=False)\n rfile.write(\">%s\\n%s\\n\" % (refName,ref))\n rfile.close()\n rfileName = rfile.name\n\n # can use the -f option to only consider forward strand since bwa prints aligned seqs\n # in the forward direction\n args = ['bwa', 'stdsw', rfileName, qfileName]\n p = subprocess.Popen(args,stdout=subprocess.PIPE,stderr=subprocess.PIPE,close_fds=True)\n\n fnum = 0\n alignments = []\n for pline in p.stdout.readlines():\n if re.search(\"^>\", pline):\n fnum = 0\n col = pline.strip().split(\"\\t\")\n alignments.append(BwastdswAlignResult(col))\n alignments[-1].queryLen = len(query) # FIXME make this work with filename input\n alignments[-1].targetLen = len(ref)\n # print \"%d\\t\" % fnum + \"\\t\".join(col)\n fnum += 1\n elif fnum == 1:\n alignments[-1].targetSeq = pline.strip()\n # print \"%d\\t\" % fnum + pline.strip()\n fnum += 1\n elif fnum == 2:\n alignments[-1].matchString = pline.strip()\n # print \"%d\\t\" % fnum + pline.strip()\n fnum += 1\n elif fnum == 3:\n alignments[-1].querySeq = pline.strip()\n # print \"%d\\t\" % fnum + pline.strip()\n fnum += 1\n p.stdout.close()\n p.kill()\n p.wait()\n\n if not queryIsFile:\n os.unlink(qfileName)\n if not refIsFile:\n os.unlink(rfileName)\n\n if len(alignments) == 0:\n return None\n if len(alignments) == 1:\n return alignments[0]\n\n # more than 1 alignment, pick the 'best'\n bestaln = alignments[0] \n for align in alignments:\n if align.alnLength() > bestaln.alnLength() and align.pctID() > 90:\n bestaln = align\n\n return bestaln\n\ndef fetchRegion(bamFile,refGenome,maxReadLen,chr,start,end,zeroChar,minClipQual,usechr=False):\n maxReadLen = int(maxReadLen)\n start = int(start)\n end = int(end)\n\n if not usechr: # can fix to use pysam.Fastafile function to get sequence names when it's available\n chr = chr.lstrip('chr')\n regionRefSeq = refGenome.fetch(reference=chr, start=start-maxReadLen, end=end+maxReadLen)\n cluster = ClippedCluster(chr,start,end,maxReadLen)\n # some .bam files are aligned against references that leave out the 'chr' prefix on the chromosome names\n if not chromNameUsesPrefix(bamFile):\n chr = chr.lstrip('chr')\n\n for read in bamFile.fetch(chr, start-maxReadLen, end+maxReadLen):\n if not read.is_unmapped and not read.is_duplicate:\n cliplen = read.rlen - read.qlen # minimum soft clipping: if rlen < qlen --> bases were soft-clipped\n if cliplen > 10:\n refseq = ''\n leftclip = 0\n rightclip = 0\n if (read.qstart == cliplen): # left-clipped\n leftclip = cliplen\n\n if (read.qstart == 0): # right-clipped\n rightclip = cliplen\n\n if (read.qstart > 0 and read.qstart < cliplen):\n leftclip = cliplen - read.qstart\n rightclip = cliplen - leftclip\n\n breakside = ''\n breakloc = 0\n clipqual = 0\n\n if (leftclip > rightclip-10): # 10 is arbitrary\n breakside = 'L'\n breakloc = read.pos\n clipqual = avgQual(read.qual,0,leftclip,zeroChar)\n elif (rightclip > leftclip-10):\n breakside = 'R'\n breakloc = read.pos + (read.rlen - rightclip)\n clipqual = avgQual(read.qual,rightclip,read.rlen,zeroChar)\n else:\n breakside = 'A' # ambiguous\n\n if (clipqual >= int(minClipQual)):\n align = bwastdsw('query',read.seq,'target',regionRefSeq)\n if align:\n #print \"aligned\"\n breakLeft = start - maxReadLen + align.targetStart\n breakRight = start - maxReadLen + align.targetEnd\n\n if (breakLeft >= start-10 and breakLeft <= end+10) or (breakRight >= start-10 and breakRight <= end+10):\n cluster.aligns.append(align)\n cluster.reads.append(read)\n #outseq = capSeq(read.seq, align.queryStart, align.queryEnd)\n #print \"%s len=%d left=%d right=%d rl=%d rr=%d\" % (outseq, read.rlen, breakLeft, breakRight, align.queryStart, align.queryEnd) \n #print read.qual\n #print align\n #print regionRefSeq\n cluster.assignBreaks()\n return cluster;\n\ndef mergeClusters(cl1,cl2,teList):\n\n if not cl1.hasReads():\n cl2.mapTE(teList)\n return cl2\n\n if not cl2.hasReads():\n cl1.mapTE(teList)\n return cl1\n\n if (cl1.chr == cl2.chr and cl1.start == cl2.start and cl1.end == cl2.end and cl1.maxrdln == cl2.maxrdln):\n new = ClippedCluster(cl1.chr, cl1.start, cl1.end, cl1.maxrdln)\n\n new.aligns = cl1.aligns\n for align in cl2.aligns:\n new.aligns.append(align)\n\n new.reads = cl1.reads\n for read in cl2.reads:\n new.reads.append(read)\n\n new.assignBreaks()\n new.mapTE(teList)\n new.type = cl1.type + \",\" + cl2.type\n return new\n else:\n raise ValueError('cannot merge clusters that have different locations')\n\nclass ClippedCluster:\n def __init__(self,chr,start,end,maxReadLen):\n self.chr = chr\n self.start = int(start)\n self.end = int(end)\n self.maxrdln = maxReadLen\n self.aligns = [] # BwastdswAlignResult objects\n self.reads = [] # pysam AlignedRead objects\n # assigned by functions:\n self.assign = False # has assignBreaks() been run?\n self.lgood = False # is left break good? (defined in bestBreakLeft())\n self.rgood = False # is right break good? (defined in bestBreakRight())\n self.lbest = 0 # best guess for left break\n self.rbest = 0 # best guess for right break\n self.lbreaks = [] # candidate left break positions\n self.rbreaks = [] # candidate right break positions", "answers": [" self.type = ''"], "length": 877, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "9dd46b13-aee5-4acc-ba09-cc89757bfdfd", "reasoning": "The __init__ method of ClippedCluster is initializing its attributes. After setting up lists for left and right break candidates (self.lbreaks, self.rbreaks), the class later uses a 'type' attribute (e.g., cl1.type) in other methods, so the initializer should also define a default value for this attribute. The next logical line is to set self.type to an empty string.", "reasoning_model_answer": "self.type = ''", "assistant_with_reasoning": "\nThe __init__ method of ClippedCluster is initializing its attributes. After setting up lists for left and right break candidates (self.lbreaks, self.rbreaks), the class later uses a 'type' attribute (e.g., cl1.type) in other methods, so the initializer should also define a default value for this attribute. The next logical line is to set self.type to an empty string.\n\nself.type = ''", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.389, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 8598, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "self.type = ''", "score": 0.78, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "package org.cocos2d.nodes;\n\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.Comparator;\nimport java.util.List;\n\nimport javax.microedition.khronos.opengles.GL10;\n\nimport org.cocos2d.actions.CCActionManager;\nimport org.cocos2d.actions.CCScheduler;\nimport org.cocos2d.actions.UpdateCallback;\nimport org.cocos2d.actions.base.CCAction;\nimport org.cocos2d.config.ccConfig;\nimport org.cocos2d.config.ccMacros;\nimport org.cocos2d.grid.CCGridBase;\nimport org.cocos2d.opengl.CCCamera;\nimport org.cocos2d.types.CGAffineTransform;\nimport org.cocos2d.types.CGPoint;\nimport org.cocos2d.types.CGRect;\nimport org.cocos2d.types.CGSize;\nimport org.cocos2d.types.util.CGAffineTransformUtil;\nimport org.cocos2d.types.util.CGPointUtil;\nimport org.cocos2d.types.util.PoolHolder;\nimport org.cocos2d.utils.Util5;\nimport org.cocos2d.utils.pool.OneClassPool;\n\nimport android.os.Build;\nimport android.util.Log;\nimport android.view.MotionEvent;\n\n/** CCNode is the main element. \n Anything thats gets drawn or contains things that get drawn is a CCNode.\n The most popular CCNodes are: CCScene, CCLayer, CCSprite, CCMenu.\n \n The main features of a CCNode are:\n - They can contain other CCNode nodes (addChild, getChildByTag, removeChild, etc)\n - They can schedule periodic callback (schedule, unschedule, etc)\n - They can execute actions (runAction, stopAction, etc)\n \n Some CCNode nodes provide extra functionality for them or their children.\n \n Subclassing a CCNode usually means (one/all) of:\n - overriding init to initialize resources and schedule callbacks\n - create callbacks to handle the advancement of time\n - overriding draw to render the node\n \n Features of CCNode:\n - position\n - scale (x, y)\n - rotation (in degrees, clockwise)\n - CCCamera (an interface to gluLookAt )\n - CCGridBase (to do mesh transformations)\n - anchor point\n - size\n - visible\n - z-order\n - openGL z position\n \n Default values:\n - rotation: 0\n - position: (x=0,y=0)\n - scale: (x=1,y=1)\n - contentSize: (x=0,y=0)\n - anchorPoint: (x=0,y=0)\n \n Limitations:\n - A CCNode is a \"void\" object. It doesn't have a texture\n \n Order in transformations with grid disabled\n -# The node will be translated (position)\n -# The node will be rotated (rotation)\n -# The node will be scaled (scale)\n -# The node will be moved according to the camera values (camera)\n \n Order in transformations with grid enabled\n -# The node will be translated (position)\n -# The node will be rotated (rotation)\n -# The node will be scaled (scale)\n -# The grid will capture the screen\n -# The node will be moved according to the camera values (camera)\n -# The grid will render the captured screen\n \n Camera:\n - Each node has a camera. By default it points to the center of the CCNode.\n*/ \npublic class CCNode {\n private static final String LOG_TAG = CCNode.class.getSimpleName();\n\n // private static final boolean COCOSNODE_DEBUG = false;\n\n public static final int kCCNodeTagInvalid = -1;\n\n\t// rotation angle\n protected float rotation_;\n\n /** The rotation (angle) of the node in degrees.\n 0 is the default rotation angle. Positive values rotate node CW.\n */\n public float getRotation() {\n return rotation_;\n }\n\n // getters synthesized, setters explicit\n public void setRotation(float rot) {\n rotation_ = rot;\n isTransformDirty_ = isInverseDirty_ = true;\n if (ccConfig.CC_NODE_TRANSFORM_USING_AFFINE_MATRIX) {\n isTransformGLDirty_ = true;\n }\n }\n\n\t// scaling factors\n protected float scaleX_;\n protected float scaleY_;\n\n /** The scale factor of the node. \n 1.0 is the default scale factor. It only modifies the X scale factor.\n */\n public float getScaleX() {\n return scaleX_;\n }\n\n public void setScaleX(float sx) {\n scaleX_ = sx;\n isTransformDirty_ = isInverseDirty_ = true;\n if (ccConfig.CC_NODE_TRANSFORM_USING_AFFINE_MATRIX) {\n isTransformGLDirty_ = true;\n }\n }\n\n /** The scale factor of the node. \n 1.0 is the default scale factor. It only modifies the Y scale factor.\n */\n public float getScaleY() {\n return scaleY_;\n }\n\n public void setScaleY(float sy) {\n scaleY_ = sy;\n isTransformDirty_ = isInverseDirty_ = true;\n if (ccConfig.CC_NODE_TRANSFORM_USING_AFFINE_MATRIX) {\n isTransformGLDirty_ = true;\n }\t\n }\n\n /** The scale factor of the node.\n 1.0 is the default scale factor. It modifies the X and Y scale at the same time.\n */\n public void setScale(float s) {\n scaleX_ = scaleY_ = s;\n isTransformDirty_ = isInverseDirty_ = true;\n if (ccConfig.CC_NODE_TRANSFORM_USING_AFFINE_MATRIX) {\n isTransformGLDirty_ = true;\n }\n }\n\n public float getScale() {\n if (scaleX_ == scaleY_) {\n return scaleX_;\n } else {\n Log.w(LOG_TAG, \"CCNode#scale. ScaleX != ScaleY. Don't know which one to return\");\n }\n return 0;\n }\n\n\t// anchor point in pixels\n\tprotected CGPoint anchorPointInPixels_;\t\n\n /** The anchorPoint in absolute pixels.\n Since v0.8 you can only read it. If you wish to modify it, use anchorPoint instead\n */\n public CGPoint getAnchorPointInPixels() {\n return CGPoint.make(anchorPointInPixels_.x, anchorPointInPixels_.y);\n }\n \n\t// If YES the transformtions will be relative to (-transform.x, -transform.y).\n\t// Sprites, Labels and any other \"small\" object uses it.\n\t// Scenes, Layers and other \"whole screen\" object don't use it.\n private boolean isRelativeAnchorPoint_;\n\n /** If YES the transformtions will be relative to it's anchor point.\n Sprites, Labels and any other sizeble object use it have it enabled by default.\n Scenes, Layers and other \"whole screen\" object don't use it, have it disabled by default.\n */\n public void setRelativeAnchorPoint(boolean newValue) {\n isRelativeAnchorPoint_ = newValue;\n isTransformDirty_ = isInverseDirty_ = true;\n if (ccConfig.CC_NODE_TRANSFORM_USING_AFFINE_MATRIX) {\n isTransformGLDirty_ = true;\n }\n }\n\n public boolean getRelativeAnchorPoint() {", "answers": [" return isRelativeAnchorPoint_;"], "length": 755, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "17c16b23-8be3-41a6-ba24-927a7c963909", "reasoning": "The method getRelativeAnchorPoint() is being defined. Inside the method, the typical implementation is to return the boolean field isRelativeAnchorPoint_. The next line after the opening brace should be the return statement.", "reasoning_model_answer": "return isRelativeAnchorPoint_;", "assistant_with_reasoning": "\nThe method getRelativeAnchorPoint() is being defined. Inside the method, the typical implementation is to return the boolean field isRelativeAnchorPoint_. The next line after the opening brace should be the return statement.\n\nreturn isRelativeAnchorPoint_;", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 2.82, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 6265, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "return isRelativeAnchorPoint_;", "score": 0.88, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/*\n * Copyright 2002-2021 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.springframework.http;\n\nimport java.io.ByteArrayOutputStream;\nimport java.nio.charset.Charset;\nimport java.nio.charset.StandardCharsets;\nimport java.time.ZonedDateTime;\nimport java.time.format.DateTimeParseException;\nimport java.util.ArrayList;\nimport java.util.Base64;\nimport java.util.List;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\nimport org.springframework.lang.Nullable;\nimport org.springframework.util.Assert;\nimport org.springframework.util.ObjectUtils;\nimport org.springframework.util.StreamUtils;\n\nimport static java.nio.charset.StandardCharsets.ISO_8859_1;\nimport static java.nio.charset.StandardCharsets.UTF_8;\nimport static java.time.format.DateTimeFormatter.RFC_1123_DATE_TIME;\n\n/**\n * Representation of the Content-Disposition type and parameters as defined in RFC 6266.\n *\n * @author Sebastien Deleuze\n * @author Juergen Hoeller\n * @author Rossen Stoyanchev\n * @author Sergey Tsypanov\n * @since 5.0\n * @see RFC 6266\n */\npublic final class ContentDisposition {\n\n\tprivate final static Pattern BASE64_ENCODED_PATTERN =\n\t\t\tPattern.compile(\"=\\\\?([0-9a-zA-Z-_]+)\\\\?B\\\\?([+/0-9a-zA-Z]+=*)\\\\?=\");\n\n\tprivate static final String INVALID_HEADER_FIELD_PARAMETER_FORMAT =\n\t\t\t\"Invalid header field parameter format (as defined in RFC 5987)\";\n\n\n\t@Nullable\n\tprivate final String type;\n\n\t@Nullable\n\tprivate final String name;\n\n\t@Nullable\n\tprivate final String filename;\n\n\t@Nullable\n\tprivate final Charset charset;\n\n\t@Nullable\n\tprivate final Long size;\n\n\t@Nullable\n\tprivate final ZonedDateTime creationDate;\n\n\t@Nullable\n\tprivate final ZonedDateTime modificationDate;\n\n\t@Nullable\n\tprivate final ZonedDateTime readDate;\n\n\n\t/**\n\t * Private constructor. See static factory methods in this class.\n\t */\n\tprivate ContentDisposition(@Nullable String type, @Nullable String name, @Nullable String filename,\n\t\t\t@Nullable Charset charset, @Nullable Long size, @Nullable ZonedDateTime creationDate,\n\t\t\t@Nullable ZonedDateTime modificationDate, @Nullable ZonedDateTime readDate) {\n\n\t\tthis.type = type;\n\t\tthis.name = name;\n\t\tthis.filename = filename;\n\t\tthis.charset = charset;\n\t\tthis.size = size;\n\t\tthis.creationDate = creationDate;\n\t\tthis.modificationDate = modificationDate;\n\t\tthis.readDate = readDate;\n\t}\n\n\n\t/**\n\t * Return whether the {@link #getType() type} is {@literal \"attachment\"}.\n\t * @since 5.3\n\t */\n\tpublic boolean isAttachment() {\n\t\treturn (this.type != null && this.type.equalsIgnoreCase(\"attachment\"));\n\t}\n\n\t/**\n\t * Return whether the {@link #getType() type} is {@literal \"form-data\"}.\n\t * @since 5.3\n\t */\n\tpublic boolean isFormData() {\n\t\treturn (this.type != null && this.type.equalsIgnoreCase(\"form-data\"));\n\t}\n\n\t/**\n\t * Return whether the {@link #getType() type} is {@literal \"inline\"}.\n\t * @since 5.3\n\t */\n\tpublic boolean isInline() {\n\t\treturn (this.type != null && this.type.equalsIgnoreCase(\"inline\"));\n\t}\n\n\t/**\n\t * Return the disposition type.\n\t * @see #isAttachment()\n\t * @see #isFormData()\n\t * @see #isInline()\n\t */\n\t@Nullable\n\tpublic String getType() {\n\t\treturn this.type;\n\t}\n\n\t/**\n\t * Return the value of the {@literal name} parameter, or {@code null} if not defined.\n\t */\n\t@Nullable\n\tpublic String getName() {\n\t\treturn this.name;\n\t}\n\n\t/**\n\t * Return the value of the {@literal filename} parameter, possibly decoded\n\t * from BASE64 encoding based on RFC 2047, or of the {@literal filename*}\n\t * parameter, possibly decoded as defined in the RFC 5987.\n\t */\n\t@Nullable\n\tpublic String getFilename() {\n\t\treturn this.filename;\n\t}\n\n\t/**\n\t * Return the charset defined in {@literal filename*} parameter, or {@code null} if not defined.\n\t */\n\t@Nullable\n\tpublic Charset getCharset() {\n\t\treturn this.charset;\n\t}\n\n\t/**\n\t * Return the value of the {@literal size} parameter, or {@code null} if not defined.\n\t * @deprecated since 5.2.3 as per\n\t * RFC 6266, Appendix B,\n\t * to be removed in a future release.\n\t */\n\t@Deprecated\n\t@Nullable\n\tpublic Long getSize() {\n\t\treturn this.size;\n\t}\n\n\t/**\n\t * Return the value of the {@literal creation-date} parameter, or {@code null} if not defined.\n\t * @deprecated since 5.2.3 as per\n\t * RFC 6266, Appendix B,\n\t * to be removed in a future release.\n\t */\n\t@Deprecated\n\t@Nullable\n\tpublic ZonedDateTime getCreationDate() {\n\t\treturn this.creationDate;\n\t}\n\n\t/**\n\t * Return the value of the {@literal modification-date} parameter, or {@code null} if not defined.\n\t * @deprecated since 5.2.3 as per\n\t * RFC 6266, Appendix B,\n\t * to be removed in a future release.\n\t */\n\t@Deprecated\n\t@Nullable\n\tpublic ZonedDateTime getModificationDate() {\n\t\treturn this.modificationDate;\n\t}\n\n\t/**\n\t * Return the value of the {@literal read-date} parameter, or {@code null} if not defined.\n\t * @deprecated since 5.2.3 as per\n\t * RFC 6266, Appendix B,\n\t * to be removed in a future release.\n\t */\n\t@Deprecated\n\t@Nullable\n\tpublic ZonedDateTime getReadDate() {\n\t\treturn this.readDate;\n\t}\n\n\t@Override\n\tpublic boolean equals(@Nullable Object other) {\n\t\tif (this == other) {\n\t\t\treturn true;\n\t\t}\n\t\tif (!(other instanceof ContentDisposition otherCd)) {\n\t\t\treturn false;\n\t\t}\n\t\treturn (ObjectUtils.nullSafeEquals(this.type, otherCd.type) &&\n\t\t\t\tObjectUtils.nullSafeEquals(this.name, otherCd.name) &&\n\t\t\t\tObjectUtils.nullSafeEquals(this.filename, otherCd.filename) &&\n\t\t\t\tObjectUtils.nullSafeEquals(this.charset, otherCd.charset) &&\n\t\t\t\tObjectUtils.nullSafeEquals(this.size, otherCd.size) &&\n\t\t\t\tObjectUtils.nullSafeEquals(this.creationDate, otherCd.creationDate)&&\n\t\t\t\tObjectUtils.nullSafeEquals(this.modificationDate, otherCd.modificationDate)&&\n\t\t\t\tObjectUtils.nullSafeEquals(this.readDate, otherCd.readDate));\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\tint result = ObjectUtils.nullSafeHashCode(this.type);\n\t\tresult = 31 * result + ObjectUtils.nullSafeHashCode(this.name);\n\t\tresult = 31 * result + ObjectUtils.nullSafeHashCode(this.filename);\n\t\tresult = 31 * result + ObjectUtils.nullSafeHashCode(this.charset);\n\t\tresult = 31 * result + ObjectUtils.nullSafeHashCode(this.size);\n\t\tresult = 31 * result + (this.creationDate != null ? this.creationDate.hashCode() : 0);\n\t\tresult = 31 * result + (this.modificationDate != null ? this.modificationDate.hashCode() : 0);\n\t\tresult = 31 * result + (this.readDate != null ? this.readDate.hashCode() : 0);\n\t\treturn result;\n\t}\n\n\t/**\n\t * Return the header value for this content disposition as defined in RFC 6266.\n\t * @see #parse(String)\n\t */\n\t@Override\n\tpublic String toString() {\n\t\tStringBuilder sb = new StringBuilder();\n\t\tif (this.type != null) {\n\t\t\tsb.append(this.type);\n\t\t}\n\t\tif (this.name != null) {\n\t\t\tsb.append(\"; name=\\\"\");", "answers": ["\t\t\tsb.append(this.name).append('\\\"');"], "length": 864, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "6e974039-d1e4-4588-b12e-f8d2201ddc13", "reasoning": "The toString() method is constructing the header string. After checking that name is not null, it appends the start of the name parameter '; name=\"'. The next logical step is to append the actual name value and close the quoted string. In the Spring source this is done with sb.append(this.name).append('\"'); which adds the name and the terminating quote.", "reasoning_model_answer": "sb.append(this.name).append('\"');", "assistant_with_reasoning": "\nThe toString() method is constructing the header string. After checking that name is not null, it appends the start of the name parameter '; name=\"'. The next logical step is to append the actual name value and close the quoted string. In the Spring source this is done with sb.append(this.name).append('\"'); which adds the name and the terminating quote.\n\nsb.append(this.name).append('\"');", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 2.836, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 7515, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "sb.append(this.name).append('\"');", "score": 0.94, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "\"\"\"CSP (Constraint Satisfaction Problems) problems and solvers. (Chapter 5).\"\"\"\n\nfrom __future__ import generators\nfrom utils import *\nimport search\nimport types\n\nclass CSP(search.Problem):\n \"\"\"This class describes finite-domain Constraint Satisfaction Problems.\n A CSP is specified by the following three inputs:\n vars A list of variables; each is atomic (e.g. int or string).\n domains A dict of {var:[possible_value, ...]} entries.\n neighbors A dict of {var:[var,...]} that for each variable lists\n the other variables that participate in constraints.\n constraints A function f(A, a, B, b) that returns true if neighbors\n A, B satisfy the constraint when they have values A=a, B=b\n In the textbook and in most mathematical definitions, the\n constraints are specified as explicit pairs of allowable values,\n but the formulation here is easier to express and more compact for\n most cases. (For example, the n-Queens problem can be represented\n in O(n) space using this notation, instead of O(N^4) for the\n explicit representation.) In terms of describing the CSP as a\n problem, that's all there is.\n\n However, the class also supports data structures and methods that help you\n solve CSPs by calling a search function on the CSP. Methods and slots are\n as follows, where the argument 'a' represents an assignment, which is a\n dict of {var:val} entries:\n assign(var, val, a) Assign a[var] = val; do other bookkeeping\n unassign(var, a) Do del a[var], plus other bookkeeping\n nconflicts(var, val, a) Return the number of other variables that\n conflict with var=val\n curr_domains[var] Slot: remaining consistent values for var\n Used by constraint propagation routines.\n The following methods are used only by graph_search and tree_search:\n succ() Return a list of (action, state) pairs\n goal_test(a) Return true if all constraints satisfied\n The following are just for debugging purposes:\n nassigns Slot: tracks the number of assignments made\n display(a) Print a human-readable representation\n \"\"\"\n\n def __init__(self, vars, domains, neighbors, constraints):\n \"Construct a CSP problem. If vars is empty, it becomes domains.keys().\"\n vars = vars or domains.keys()\n update(self, vars=vars, domains=domains,\n neighbors=neighbors, constraints=constraints,\n initial={}, curr_domains=None, pruned=None, nassigns=0)\n\n def assign(self, var, val, assignment):\n \"\"\"Add {var: val} to assignment; Discard the old value if any.\n Do bookkeeping for curr_domains and nassigns.\"\"\"\n self.nassigns += 1\n assignment[var] = val\n if self.curr_domains:\n if self.fc:\n self.forward_check(var, val, assignment)\n if self.mac:\n AC3(self, [(Xk, var) for Xk in self.neighbors[var]])\n\n def unassign(self, var, assignment):\n \"\"\"Remove {var: val} from assignment; that is backtrack.\n DO NOT call this if you are changing a variable to a new value;\n just call assign for that.\"\"\"\n if var in assignment:\n # Reset the curr_domain to be the full original domain\n if self.curr_domains:\n self.curr_domains[var] = self.domains[var][:]\n del assignment[var]\n\n def nconflicts(self, var, val, assignment):\n \"Return the number of conflicts var=val has with other variables.\"\n # Subclasses may implement this more efficiently\n def conflict(var2):\n val2 = assignment.get(var2, None)\n return val2 != None and not self.constraints(var, val, var2, val2)\n return count_if(conflict, self.neighbors[var])\n\n def forward_check(self, var, val, assignment):\n \"Do forward checking (current domain reduction) for this assignment.\"\n if self.curr_domains:\n # Restore prunings from previous value of var\n for (B, b) in self.pruned[var]:\n self.curr_domains[B].append(b)\n self.pruned[var] = []\n # Prune any other B=b assignement that conflict with var=val\n for B in self.neighbors[var]:\n if B not in assignment:\n for b in self.curr_domains[B][:]:\n if not self.constraints(var, val, B, b):\n self.curr_domains[B].remove(b)\n self.pruned[var].append((B, b))\n\n def display(self, assignment):\n \"Show a human-readable representation of the CSP.\"\n # Subclasses can print in a prettier way, or display with a GUI\n print 'CSP:', self, 'with assignment:', assignment\n\n ## These methods are for the tree and graph search interface:\n\n def succ(self, assignment):\n \"Return a list of (action, state) pairs.\"\n if len(assignment) == len(self.vars):\n return []\n else:\n var = find_if(lambda v: v not in assignment, self.vars)\n result = []\n for val in self.domains[var]:\n if self.nconflicts(self, var, val, assignment) == 0:\n a = assignment.copy; a[var] = val\n result.append(((var, val), a))\n return result\n\n def goal_test(self, assignment):\n \"The goal is to assign all vars, with all constraints satisfied.\"\n return (len(assignment) == len(self.vars) and\n every(lambda var: self.nconflicts(var, assignment[var],\n assignment) == 0,\n self.vars))\n\n ## This is for min_conflicts search\n\n def conflicted_vars(self, current):\n \"Return a list of variables in current assignment that are in conflict\"\n return [var for var in self.vars\n if self.nconflicts(var, current[var], current) > 0]\n\n#______________________________________________________________________________\n# CSP Backtracking Search\n\ndef backtracking_search(csp, mcv=False, lcv=False, fc=False, mac=False):\n \"\"\"Set up to do recursive backtracking search. Allow the following options:\n mcv - If true, use Most Constrained Variable Heuristic\n lcv - If true, use Least Constraining Value Heuristic\n fc - If true, use Forward Checking\n mac - If true, use Maintaining Arc Consistency. [Fig. 5.3]\n >>> backtracking_search(australia)\n {'WA': 'B', 'Q': 'B', 'T': 'B', 'V': 'B', 'SA': 'G', 'NT': 'R', 'NSW': 'R'}\n \"\"\"\n if fc or mac:\n csp.curr_domains, csp.pruned = {}, {}\n for v in csp.vars:\n csp.curr_domains[v] = csp.domains[v][:]\n csp.pruned[v] = []\n update(csp, mcv=mcv, lcv=lcv, fc=fc, mac=mac)\n return recursive_backtracking({}, csp)\n\ndef recursive_backtracking(assignment, csp):\n \"\"\"Search for a consistent assignment for the csp.\n Each recursive call chooses a variable, and considers values for it.\"\"\"\n if len(assignment) == len(csp.vars):\n return assignment", "answers": [" var = select_unassigned_variable(assignment, csp)"], "length": 813, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "f5c03d2a-de88-48c1-9d77-b807f69f52b6", "reasoning": "The recursive_backtracking function returns the complete assignment when all variables are assigned. After that return, the function should continue with the case where the assignment is incomplete: it must select an unassigned variable (using heuristics stored in the CSP). The next logical line is the variable selection step, typically using a helper like select_unassigned_variable. So the next line is the variable selection statement, properly indented.", "reasoning_model_answer": "var = select_unassigned_variable(assignment, csp)", "assistant_with_reasoning": "\nThe recursive_backtracking function returns the complete assignment when all variables are assigned. After that return, the function should continue with the case where the assignment is incomplete: it must select an unassigned variable (using heuristics stored in the CSP). The next logical line is the variable selection step, typically using a helper like select_unassigned_variable. So the next line is the variable selection statement, properly indented.\n\nvar = select_unassigned_variable(assignment, csp)", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 5.355, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 7308, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "var = select_unassigned_variable(assignment, csp)", "score": 0.96, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "import re\nimport itertools\nfrom pprint import pprint\n\nimport maya.cmds as cmds\nimport pymel.util as util\nimport pymel.util.trees as trees\nimport pymel.api as api\nimport pymel.internal.cmdcache as cmdcache\nimport pymel.internal.apicache as apicache\nimport pymel.internal.factories as factories\n\n#===============================================================================\n# maya node type hierarchy info\n#===============================================================================\n\ncmds.file(new=1, f=1)\nlsTypes = cmds.ls(nodeTypes=1)\nnum = len(lsTypes)\nlsTypes = set(lsTypes)\nassert num == len(lsTypes), \"The result of ls(nodeTypes=1) contained duplicates\"\nprint num\n\nprint 'got ls(nodeTypes=1), confirmed no dupes'\n\nrealTypes = lsTypes\n\ntry:\n allTypesReal = cmds.allNodeTypes()\nexcept RuntimeError:\n print \"Error calling allNodeTypes() !!\"\n allTypesReal = None\n realAndAbstract = lsTypes\n abstractTypes = None\nelse:\n\n num = len(allTypesReal)\n allTypesReal = set(allTypesReal)\n assert num == len(allTypesReal), \"The result of allNodeTypes() contained duplicates\"\n print num\n\n print 'got allNodeTypes(), confirmed no dupes'\n\n assert lsTypes == allTypesReal, \"ls(nodeTypes=1) and allNodeTypes() returned different result\"\n\n print 'confirmed allNodeTypes() == ls(nodeTypes=1)'\n\n abstractSuffix = ' (abstract)'\n rawRealAndAbstract = cmds.allNodeTypes(includeAbstract=True)\n realAndAbstract = set()\n for x in rawRealAndAbstract:\n if x.endswith(abstractSuffix):\n x = x[:-len(abstractSuffix)]\n assert x not in realAndAbstract\n realAndAbstract.add(x)\n\n abstractTypes = realAndAbstract - realTypes\n assert len(abstractTypes) + len(realTypes) == len(realAndAbstract)\n\n\n print 'got allNodeTypes(includeAbstract=True), separated nodes into real + abstract'\n# TODO - make and load a plugin which makes one of every possible plugin node\n# type...\n\n# with 2012, we have nodeType(isTypeName), so no longer need to add nodes!\n #print 'about to make nodes...'\n #mobjDict = {}\n #dagMod = api.MDagModifier()\n #dgMod = api.MDGModifier()\n #for nodeType in realTypes:\n # #print 'making nodeType %s...' % nodeType,\n # mobjDict[nodeType] = apicache._makeDgModGhostObject(nodeType, dagMod, dgMod)\n # #print 'success!'\n #dagMod.doIt()\n #dgMod.doIt()\n #\n #print 'made nodes!'\n #\n #nodeDict = {}\n #mfnDag = api.MFnDagNode()\n #mfnDep = api.MFnDependencyNode()\n #nonMelQueryableApiTypes = [api.MFn.kManipContainer, api.MFn.kManip2DContainer,\n # api.MFn.kManipulator3D, api.MFn.kManipulator2D,\n # api.MFn.kPolyToolFeedbackShape]\n #nonMelQueryableTypes = set()\n #melQueryableTypes = set()\n #dagTypes = set()\n #depTypes = set()\n #for nodeType, mobj in mobjDict.iteritems():\n # if mfnDag.hasObj(mobj):\n # dagTypes.add(nodeType)\n # mfnDag.setObject(mobj)\n # nodeDict[nodeType] = mfnDag.fullPathName()\n # else:\n # depTypes.add(nodeType)\n # mfnDep.setObject(mobj)\n # nodeDict[nodeType] = mfnDep.name()\n # for manipApi in nonMelQueryableApiTypes:\n # if mobj.hasFn(manipApi):\n # nonMelQueryableTypes.add(nodeType)\n # break\n # else:\n # melQueryableTypes.add(nodeType)\n #print \"num non queryable types:\", len(nonMelQueryableTypes)\n #\n ##nodeDict = {}\n ##for nodeType in realTypes:\n ## result = cmds.createNode(nodeType)\n ## nodeDict[nodeType] = result\n #\n #assert len(nodeDict) == len(realTypes)\n #assert len(nonMelQueryableTypes) + len(melQueryableTypes) == len(realTypes)\n #assert nonMelQueryableTypes | melQueryableTypes == realTypes\n\ninheritances = {}\nbadInheritances = {}\ngoodInheritances = {}\n#for nodeType in melQueryableTypes:\nfor nodeType in realAndAbstract:\n try:\n inheritance = cmds.nodeType( nodeType, inherited=True, isTypeName=True)\n except Exception, e:\n print \"error caught:\"\n print e\n inheritance = e\n inheritances[nodeType] = inheritance\n if not inheritance or isinstance(inheritance, Exception):\n badInheritances[nodeType] = inheritance\n else:\n goodInheritances[nodeType] = inheritance\n\nif badInheritances:\n print \"#\" * 60\n print \"Warning!!!\"\n print \"errors in getting inheritance for following node types:\"\n for x in badInheritances:\n print \" \", x\n print \"#\" * 60\n\n#print getApiTypes(mobjDict['polyMoveUVManip'])\n\ndiscoveredNodes = set()\nfor nodeType, inheritance in goodInheritances.iteritems():\n assert inheritance[-1] == nodeType\n for x in inheritance:\n if x not in realAndAbstract:\n discoveredNodes.add(x)\nif discoveredNodes:\n print \"#\" * 60\n print \"Warning!!!\"\n print \"%s nodes were not in realAndAbstract\" % ', '.join(discoveredNodes)\n print \"#\" * 60\nallKnownNodes = realAndAbstract | discoveredNodes\n\ndef compareTrees(tree1, tree2):\n def convertTree(oldTree):\n if isinstance(oldTree, dict):\n return oldTree\n newTree = {}\n for key, parents, children in oldTree:\n newTree[key] = [parents, set(children)]\n return newTree\n tree1 = convertTree(tree1)\n tree2 = convertTree(tree2)\n t1set = set(tree1)\n t2set = set(tree2)\n both = t1set & t2set\n only1 = t1set - both\n only2 = t2set - both\n diff = {}\n for nodeType in both:\n n1 = tree1[nodeType]\n n2 = tree2[nodeType]\n if n1 != n2:\n if n1[0] == n2[0]:\n parentDiff = 'same'\n else:\n parentDiff = (n1[0], n2[0])\n if n1[1] == n2[1]:\n childDiff = 'same'\n else:\n childDiff = (n1[1] - n2[1], n2[1] - n1[1])\n diff[nodeType] = (parentDiff, childDiff)\n return only1, only2, diff\n\nnodeTypeTree = {}\nfor nodeType in allKnownNodes:\n nodeTypeTree[nodeType] = [ [], set() ]\nfor nodeType, inheritance in goodInheritances.iteritems():\n assert inheritance[-1] == nodeType\n # len - 1 b/c final item is this nodeType\n for i in xrange(len(inheritance) - 1):\n parent = inheritance[i]\n child = inheritance[i + 1]\n\n # add the child to the parent\n nodeTypeTree[parent][1].add(child)\n\n # set the parents for the child\n parents = list(reversed(inheritance[:i+1]))\n if nodeTypeTree[child][0]:\n assert nodeTypeTree[child][0] == parents\n else:\n nodeTypeTree[child][0] = parents\n\n#eliminate manipulators\nnonManipTree = {}\nmanipulators = set()\nfor name, data in nodeTypeTree.iteritems():\n parents = data[0]\n if parents is not None and ('manip3D' in parents or name == 'manip3D'):\n manipulators.add(name)\n else:\n nonManipTree[name] = data\n\nnonManipNonPlugin = {}\nfor name, data in nonManipTree.iteritems():\n parents = data[0]\n if parents is not None:\n if (any(x.startswith('TH') for x in parents)\n or name.startswith('TH')):\n continue\n nonManipNonPlugin[name] = data\n\nprint \"trees equal?\"\n\nonly1, only2, diff = compareTrees(nonManipNonPlugin, factories.nodeHierarchy)\n\nprint\nprint \"-\" * 60\nprint \"only1:\"\npprint(list(only1))\nprint \"-\" * 60\nprint\n\nprint\nprint \"-\" * 60\nprint \"only2:\"\npprint(list(only2))\nprint \"-\" * 60\nprint\n\nprint\nprint \"-\" * 60\nprint \"diff:\"\n#pprint(diff)\nprint \"-\" * 60\nprint\n\n#===============================================================================\n# api type hierarchy info\n#===============================================================================\n\ndef getApiTypes(mobj):\n apiTypes = []\n for apiTypeStr, apiType in factories.apiTypesToApiEnums.iteritems():\n if mobj.hasFn(apiType):\n apiTypes.append(apiTypeStr)\n return apiTypes\n\nmayaToApi = {}\nmayaToAllApi = {}\nunknownTypes = set()\n#toCreate = set(nonManipTree)\ntoCreate = set(realTypes) - manipulators - set(apicache.ApiCache.CRASH_TYPES)\nwith apicache._GhostObjMaker(toCreate, manipError=False, multi=True) as typeToObj:\n for mayaType in toCreate:\n obj = typeToObj[mayaType]\n if obj :\n apiType = obj.apiTypeStr()\n mayaToApi[mayaType] = apiType", "answers": [" mayaToAllApi[mayaType] = getApiTypes(obj)"], "length": 852, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "727bad6b-e56e-496d-8d88-9b6fde6ed1a0", "reasoning": "Within the with‑block the code iterates over each Maya node type, creates a ghost object, gets its API type string and stores it in mayaToApi. The next logical step is to also record all API types that the object supports, using the helper getApiTypes defined earlier. Therefore the next line should add an entry to mayaToAllApi mapping the Maya type to the list returned by getApiTypes(obj).", "reasoning_model_answer": "mayaToAllApi[mayaType] = getApiTypes(obj)", "assistant_with_reasoning": "\nWithin the with‑block the code iterates over each Maya node type, creates a ghost object, gets its API type string and stores it in mayaToApi. The next logical step is to also record all API types that the object supports, using the helper getApiTypes defined earlier. Therefore the next line should add an entry to mayaToAllApi mapping the Maya type to the list returned by getApiTypes(obj).\n\nmayaToAllApi[mayaType] = getApiTypes(obj)", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.436, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 8368, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "mayaToAllApi[mayaType] = getApiTypes(obj)", "score": 0.87, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n# Copyright: (c) 2012, Michael DeHaan \n# Copyright: (c) 2017, Ansible Project\n# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)\n\nfrom __future__ import absolute_import, division, print_function\n__metaclass__ = type\n\n\nDOCUMENTATION = r'''\n---\nmodule: file\nversion_added: historical\nshort_description: Manage files and file properties\nextends_documentation_fragment: files\ndescription:\n- Set attributes of files, symlinks or directories.\n- Alternatively, remove files, symlinks or directories.\n- Many other modules support the same options as the C(file) module - including M(copy), M(template), and M(assemble).\n- For Windows targets, use the M(win_file) module instead.\noptions:\n path:\n description:\n - Path to the file being managed.\n type: path\n required: yes\n aliases: [ dest, name ]\n state:\n description:\n - If C(absent), directories will be recursively deleted, and files or symlinks will\n be unlinked. In the case of a directory, if C(diff) is declared, you will see the files and folders deleted listed\n under C(path_contents). Note that C(absent) will not cause C(file) to fail if the C(path) does\n not exist as the state did not change.\n - If C(directory), all intermediate subdirectories will be created if they\n do not exist. Since Ansible 1.7 they will be created with the supplied permissions.\n - If C(file), without any other options this works mostly as a 'stat' and will return the current state of C(path).\n Even with other options (i.e C(mode)), the file will be modified but will NOT be created if it does not exist;\n see the C(touch) value or the M(copy) or M(template) module if you want that behavior.\n - If C(hard), the hard link will be created or changed.\n - If C(link), the symbolic link will be created or changed.\n - If C(touch) (new in 1.4), an empty file will be created if the C(path) does not\n exist, while an existing file or directory will receive updated file access and\n modification times (similar to the way C(touch) works from the command line).\n type: str\n default: file\n choices: [ absent, directory, file, hard, link, touch ]\n src:\n description:\n - Path of the file to link to.\n - This applies only to C(state=link) and C(state=hard).\n - For C(state=link), this will also accept a non-existing path.\n - Relative paths are relative to the file being created (C(path)) which is how\n the Unix command C(ln -s SRC DEST) treats relative paths.\n type: path\n recurse:\n description:\n - Recursively set the specified file attributes on directory contents.\n - This applies only when C(state) is set to C(directory).\n type: bool\n default: no\n version_added: '1.1'\n force:\n description:\n - >\n Force the creation of the symlinks in two cases: the source file does\n not exist (but will appear later); the destination exists and is a file (so, we need to unlink the\n C(path) file and create symlink to the C(src) file in place of it).\n type: bool\n default: no\n follow:\n description:\n - This flag indicates that filesystem links, if they exist, should be followed.\n - Previous to Ansible 2.5, this was C(no) by default.\n type: bool\n default: yes\n version_added: '1.8'\n modification_time:\n description:\n - This parameter indicates the time the file's modification time should be set to.\n - Should be C(preserve) when no modification is required, C(YYYYMMDDHHMM.SS) when using default time format, or C(now).\n - Default is None meaning that C(preserve) is the default for C(state=[file,directory,link,hard]) and C(now) is default for C(state=touch).\n type: str\n version_added: \"2.7\"\n modification_time_format:\n description:\n - When used with C(modification_time), indicates the time format that must be used.\n - Based on default Python format (see time.strftime doc).\n type: str\n default: \"%Y%m%d%H%M.%S\"\n version_added: '2.7'\n access_time:\n description:\n - This parameter indicates the time the file's access time should be set to.\n - Should be C(preserve) when no modification is required, C(YYYYMMDDHHMM.SS) when using default time format, or C(now).\n - Default is C(None) meaning that C(preserve) is the default for C(state=[file,directory,link,hard]) and C(now) is default for C(state=touch).\n type: str\n version_added: '2.7'\n access_time_format:\n description:\n - When used with C(access_time), indicates the time format that must be used.\n - Based on default Python format (see time.strftime doc).\n type: str\n default: \"%Y%m%d%H%M.%S\"\n version_added: '2.7'\nseealso:\n- module: assemble\n- module: copy\n- module: stat\n- module: template\n- module: win_file\nauthor:\n- Ansible Core Team\n- Michael DeHaan\n'''\n\nEXAMPLES = r'''\n- name: Change file ownership, group and permissions\n file:\n path: /etc/foo.conf\n owner: foo\n group: foo\n mode: '0644'\n\n- name: Give insecure permissions to an existing file\n file:\n path: /work\n owner: root\n group: root\n mode: '1777'\n\n- name: Create a symbolic link\n file:\n src: /file/to/link/to\n dest: /path/to/symlink\n owner: foo\n group: foo\n state: link\n\n- name: Create two hard links\n file:\n src: '/tmp/{{ item.src }}'\n dest: '{{ item.dest }}'\n state: hard\n loop:\n - { src: x, dest: y }\n - { src: z, dest: k }\n\n- name: Touch a file, using symbolic modes to set the permissions (equivalent to 0644)\n file:\n path: /etc/foo.conf\n state: touch\n mode: u=rw,g=r,o=r\n\n- name: Touch the same file, but add/remove some permissions\n file:\n path: /etc/foo.conf\n state: touch\n mode: u+rw,g-wx,o-rwx\n\n- name: Touch again the same file, but dont change times this makes the task idempotent\n file:", "answers": [" path: /etc/foo.conf"], "length": 843, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "2e40eef6-1826-498b-b90c-be2ea9f1ca90", "reasoning": "The snippet ends inside an Ansible example block. After the line '- name: Touch again the same file, but dont change times this makes the task idempotent', the next line starts the file module arguments. In Ansible examples, the first argument is usually the 'path' of the file. Therefore the next line of code should be the indented 'path' parameter.", "reasoning_model_answer": "path: /etc/foo.conf", "assistant_with_reasoning": "\nThe snippet ends inside an Ansible example block. After the line '- name: Touch again the same file, but dont change times this makes the task idempotent', the next line starts the file module arguments. In Ansible examples, the first argument is usually the 'path' of the file. Therefore the next line of code should be the indented 'path' parameter.\n\npath: /etc/foo.conf", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.257, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 5973, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "path: /etc/foo.conf", "score": 0.9, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/*\n * Copyright 2000-2014 JetBrains s.r.o.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.intellij.codeInsight.editorActions;\n\nimport com.intellij.codeInsight.CodeInsightBundle;\nimport com.intellij.codeInsight.CodeInsightSettings;\nimport com.intellij.codeInsight.editorActions.enter.EnterHandlerDelegate;\nimport com.intellij.codeStyle.CodeStyleFacade;\nimport com.intellij.ide.DataManager;\nimport com.intellij.lang.*;\nimport com.intellij.lang.documentation.CodeDocumentationProvider;\nimport com.intellij.lang.documentation.CompositeDocumentationProvider;\nimport com.intellij.lang.documentation.DocumentationProvider;\nimport com.intellij.lexer.Lexer;\nimport com.intellij.openapi.actionSystem.CommonDataKeys;\nimport com.intellij.openapi.actionSystem.DataContext;\nimport com.intellij.openapi.actionSystem.DataContextWrapper;\nimport com.intellij.openapi.command.CommandProcessor;\nimport com.intellij.openapi.diagnostic.Logger;\nimport com.intellij.openapi.editor.*;\nimport com.intellij.openapi.editor.actionSystem.EditorActionHandler;\nimport com.intellij.openapi.extensions.Extensions;\nimport com.intellij.openapi.project.DumbService;\nimport com.intellij.openapi.project.Project;\nimport com.intellij.openapi.util.*;\nimport com.intellij.openapi.util.text.StringUtil;\nimport com.intellij.psi.*;\nimport com.intellij.psi.codeStyle.CodeStyleManager;\nimport com.intellij.psi.codeStyle.CodeStyleSettings;\nimport com.intellij.psi.codeStyle.CodeStyleSettingsManager;\nimport com.intellij.psi.formatter.FormatterUtil;\nimport com.intellij.psi.impl.source.PostprocessReformattingAspect;\nimport com.intellij.psi.impl.source.codeStyle.lineIndent.FormatterBasedIndentAdjuster;\nimport com.intellij.psi.tree.IElementType;\nimport com.intellij.psi.util.PsiTreeUtil;\nimport com.intellij.psi.util.PsiUtilBase;\nimport com.intellij.util.IncorrectOperationException;\nimport com.intellij.util.text.CharArrayUtil;\nimport org.jetbrains.annotations.NotNull;\nimport org.jetbrains.annotations.Nullable;\n\npublic class EnterHandler extends BaseEnterHandler {\n private static final Logger LOG = Logger.getInstance(\"#com.intellij.codeInsight.editorActions.EnterHandler\");\n\n private final EditorActionHandler myOriginalHandler;\n private final static Key CONTEXT_LANGUAGE = Key.create(\"EnterHandler.Language\");\n\n public EnterHandler(EditorActionHandler originalHandler) {\n super(true);\n myOriginalHandler = originalHandler;\n }\n\n @Override\n public boolean isEnabledForCaret(@NotNull Editor editor, @NotNull Caret caret, DataContext dataContext) {\n return myOriginalHandler.isEnabled(editor, caret, dataContext);\n }\n\n @Override\n public void executeWriteAction(final Editor editor, final Caret caret, final DataContext dataContext) {\n final Project project = CommonDataKeys.PROJECT.getData(dataContext);\n if (project != null && !project.isDefault()) {\n PostprocessReformattingAspect.getInstance(project).disablePostprocessFormattingInside(\n () -> executeWriteActionInner(editor, caret, getExtendedContext(dataContext, project, caret), project));\n }\n else {\n executeWriteActionInner(editor, caret, dataContext, project);\n }\n }\n\n private void executeWriteActionInner(Editor editor, Caret caret, DataContext dataContext, Project project) {\n CodeInsightSettings settings = CodeInsightSettings.getInstance();\n if (project == null) {\n myOriginalHandler.execute(editor, caret, dataContext);\n return;\n }\n final Document document = editor.getDocument();\n final PsiFile file = PsiUtilBase.getPsiFileInEditor(editor, project);\n\n if (file == null) {\n myOriginalHandler.execute(editor, caret, dataContext);\n return;\n }\n\n CommandProcessor.getInstance().setCurrentCommandName(CodeInsightBundle.message(\"command.name.typing\"));\n\n EditorModificationUtil.deleteSelectedText(editor);\n\n int caretOffset = editor.getCaretModel().getOffset();\n CharSequence text = document.getCharsSequence();\n int length = document.getTextLength();\n if (caretOffset < length && text.charAt(caretOffset) != '\\n') {\n int offset1 = CharArrayUtil.shiftBackward(text, caretOffset, \" \\t\");\n if (offset1 < 0 || text.charAt(offset1) == '\\n') {\n int offset2 = CharArrayUtil.shiftForward(text, offset1 + 1, \" \\t\");\n boolean isEmptyLine = offset2 >= length || text.charAt(offset2) == '\\n';\n if (!isEmptyLine) { // we are in leading spaces of a non-empty line\n myOriginalHandler.execute(editor, caret, dataContext);\n return;\n }\n }\n }\n\n boolean forceIndent = false;\n boolean forceSkipIndent = false;\n Ref caretOffsetRef = new Ref<>(caretOffset);\n Ref caretAdvanceRef = new Ref<>(0);\n\n final EnterHandlerDelegate[] delegates = Extensions.getExtensions(EnterHandlerDelegate.EP_NAME);\n for(EnterHandlerDelegate delegate: delegates) {\n EnterHandlerDelegate.Result result = delegate.preprocessEnter(file, editor, caretOffsetRef, caretAdvanceRef, dataContext, myOriginalHandler);\n if (caretOffsetRef.get() > document.getTextLength()) {\n throw new AssertionError(\"Wrong caret offset change by \" + delegate);\n }\n\n if (result == EnterHandlerDelegate.Result.Stop) {\n return;\n }\n if (result != EnterHandlerDelegate.Result.Continue) {\n if (result == EnterHandlerDelegate.Result.DefaultForceIndent) {\n forceIndent = true;\n }\n else if (result == EnterHandlerDelegate.Result.DefaultSkipIndent) {\n forceSkipIndent = true;\n }\n break;\n }\n }\n\n text = document.getCharsSequence(); // update after changes done in preprocessEnter()\n caretOffset = caretOffsetRef.get().intValue();\n boolean isFirstColumn = caretOffset == 0 || text.charAt(caretOffset - 1) == '\\n';\n final boolean insertSpace =\n !isFirstColumn && !(caretOffset >= text.length() || text.charAt(caretOffset) == ' ' || text.charAt(caretOffset) == '\\t');\n editor.getCaretModel().moveToOffset(caretOffset);\n myOriginalHandler.execute(editor, caret, dataContext);\n if (!editor.isInsertMode() || forceSkipIndent) {\n return;\n }\n\n if (settings.SMART_INDENT_ON_ENTER || forceIndent) {\n caretOffset += 1;\n caretOffset = CharArrayUtil.shiftForward(editor.getDocument().getCharsSequence(), caretOffset, \" \\t\");\n }\n else {\n caretOffset = editor.getCaretModel().getOffset();\n }\n\n final DoEnterAction action = new DoEnterAction(\n file, editor, document, dataContext, caretOffset, !insertSpace, caretAdvanceRef.get(), project\n );\n action.setForceIndent(forceIndent);\n action.run();\n for (EnterHandlerDelegate delegate : delegates) {\n if (delegate.postProcessEnter(file, editor, dataContext) == EnterHandlerDelegate.Result.Stop) {\n break;\n }\n }\n \n if (settings.SMART_INDENT_ON_ENTER && action.isIndentAdjustmentNeeded()) {\n FormatterBasedIndentAdjuster.scheduleIndentAdjustment(project, document, editor.getCaretModel().getOffset());\n }\n }\n \n @NotNull\n private static DataContext getExtendedContext(@NotNull DataContext originalContext, \n @NotNull Project project,\n @NotNull Caret caret) {\n DataContext context = originalContext instanceof UserDataHolder ? originalContext : new DataContextWrapper(originalContext);\n ((UserDataHolder)context).putUserData(CONTEXT_LANGUAGE, PsiUtilBase.getLanguageInEditor(caret, project));\n return context;\n }\n\n public static boolean isCommentComplete(PsiComment comment, CodeDocumentationAwareCommenter commenter, Editor editor) {\n for (CommentCompleteHandler handler : Extensions.getExtensions(CommentCompleteHandler.EP_NAME)) {\n if (handler.isApplicable(comment, commenter)) {\n return handler.isCommentComplete(comment, commenter, editor);\n }\n }\n\n String commentText = comment.getText();\n final boolean docComment = isDocComment(comment, commenter);\n final String expectedCommentEnd = docComment ? commenter.getDocumentationCommentSuffix():commenter.getBlockCommentSuffix();\n if (!commentText.endsWith(expectedCommentEnd)) return false;\n\n final PsiFile containingFile = comment.getContainingFile();\n final Language language = containingFile.getLanguage();\n ParserDefinition parserDefinition = LanguageParserDefinitions.INSTANCE.forLanguage(language);\n if (parserDefinition == null) {\n return true;\n } \n Lexer lexer = parserDefinition.createLexer(containingFile.getProject());\n final String commentPrefix = docComment? commenter.getDocumentationCommentPrefix() : commenter.getBlockCommentPrefix();\n lexer.start(commentText, commentPrefix == null? 0 : commentPrefix.length(), commentText.length());\n QuoteHandler fileTypeHandler = TypedHandler.getQuoteHandler(containingFile, editor);\n JavaLikeQuoteHandler javaLikeQuoteHandler = fileTypeHandler instanceof JavaLikeQuoteHandler ?\n (JavaLikeQuoteHandler)fileTypeHandler:null;\n\n while (true) {\n IElementType tokenType = lexer.getTokenType();", "answers": [" if (tokenType == null) {"], "length": 737, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "9e32067f-94d1-408a-a1f7-4e4aa079722a", "reasoning": "The method is iterating over lexer tokens of the comment text. Inside the while(true) loop the first step is to get the current token type. The typical next operation is to check for the end of the token stream; if lexer.getTokenType() returns null the loop should terminate. Therefore the next line is the null‑check and break.", "reasoning_model_answer": "if (tokenType == null) break;", "assistant_with_reasoning": "\nThe method is iterating over lexer tokens of the comment text. Inside the while(true) loop the first step is to get the current token type. The typical next operation is to check for the end of the token stream; if lexer.getTokenType() returns null the loop should terminate. Therefore the next line is the null‑check and break.\n\nif (tokenType == null) break;", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 5.09, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 9759, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "if (tokenType == null) break;", "score": 0.78, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "package org.sakaiproject.assignment.impl;\n\nimport java.sql.SQLException;\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Map.Entry;\n\nimport org.apache.commons.logging.Log;\nimport org.apache.commons.logging.LogFactory;\nimport org.hibernate.HibernateException;\nimport org.hibernate.Query;\nimport org.hibernate.Session;\nimport org.sakaiproject.api.app.scheduler.DelayedInvocation;\nimport org.sakaiproject.api.app.scheduler.ScheduledInvocationManager;\nimport org.sakaiproject.assignment.api.Assignment;\nimport org.sakaiproject.assignment.api.AssignmentConstants;\nimport org.sakaiproject.assignment.api.AssignmentPeerAssessmentService;\nimport org.sakaiproject.assignment.api.AssignmentService;\nimport org.sakaiproject.assignment.api.AssignmentSubmission;\nimport org.sakaiproject.assignment.api.AssignmentSubmissionEdit;\nimport org.sakaiproject.assignment.api.model.PeerAssessmentItem;\nimport org.sakaiproject.authz.api.SecurityAdvisor;\nimport org.sakaiproject.authz.api.SecurityService;\nimport org.sakaiproject.authz.api.SecurityAdvisor.SecurityAdvice;\nimport org.sakaiproject.exception.IdUnusedException;\nimport org.sakaiproject.exception.InUseException;\nimport org.sakaiproject.exception.PermissionException;\nimport org.sakaiproject.time.api.Time;\nimport org.sakaiproject.time.api.TimeService;\nimport org.sakaiproject.tool.api.SessionManager;\nimport org.sakaiproject.user.api.User;\nimport org.springframework.orm.hibernate3.HibernateCallback;\nimport org.springframework.orm.hibernate3.support.HibernateDaoSupport;\n\npublic class AssignmentPeerAssessmentServiceImpl extends HibernateDaoSupport implements AssignmentPeerAssessmentService {\n\tprivate static Log log = LogFactory.getLog(AssignmentPeerAssessmentServiceImpl.class);\n\tprivate ScheduledInvocationManager scheduledInvocationManager;\n\tprivate TimeService timeService;\n\tprotected AssignmentService assignmentService;\n\tprivate SecurityService securityService = null;\n\tprivate SessionManager sessionManager;\n\t\n\tpublic void init(){\n\t\t\n\t}\n\t\n\tpublic void destroy(){\n\t\t\n\t}\n\n\tpublic void schedulePeerReview(String assignmentId){\n\t\t//first remove any previously scheduled reviews:\n\t\tremoveScheduledPeerReview(assignmentId);\n\t\t//now schedule a time for the review to be setup\n\t\tAssignment assignment;\n\t\ttry {\n\t\t\tassignment = assignmentService.getAssignment(assignmentId);\n\t\t\tif(!assignment.getDraft() && assignment.getAllowPeerAssessment()){\n\t\t\t\tTime assignmentCloseTime = assignment.getCloseTime();\n\t\t\t\tTime openTime = null;\n\t\t\t\tif(assignmentCloseTime != null){\n\t\t\t\t\topenTime = timeService.newTime(assignmentCloseTime.getTime());\n\t\t\t\t}\n\t\t\t\t// Schedule the new notification\n\t\t\t\tif (openTime != null){\n\t\t\t\t\tscheduledInvocationManager.createDelayedInvocation(openTime,\n\t\t\t\t\t\t\t\"org.sakaiproject.assignment.api.AssignmentPeerAssessmentService\",\n\t\t\t\t\t\t\tassignmentId);\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (IdUnusedException e) {\n\t\t\t// TODO Auto-generated catch block\n\t\t\te.printStackTrace();\n\t\t} catch (PermissionException e) {\n\t\t\t// TODO Auto-generated catch block\n\t\t\te.printStackTrace();\n\t\t}\n\t}\n\n\tpublic void removeScheduledPeerReview(String assignmentId){\n\t\t// Remove any existing notifications for this area\n\t\tDelayedInvocation[] fdi = scheduledInvocationManager.findDelayedInvocations(\"org.sakaiproject.assignment.api.AssignmentPeerAssessmentService\", assignmentId);\n\t\tif (fdi != null && fdi.length > 0)\n\t\t{\n\t\t\tfor (DelayedInvocation d : fdi)\n\t\t\t{\n\t\t\t\tscheduledInvocationManager.deleteDelayedInvocation(d.uuid);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Method called by the scheduledInvocationManager\n\t */\n\tpublic void execute(String opaqueContext){\n\t\ttry {\n\t\t\t//for group assignments, we need to have a user ID, otherwise, an exception is thrown:\n\t\t\tsessionManager.getCurrentSession().setUserEid(\"admin\");\n\t\t\tsessionManager.getCurrentSession().setUserId(\"admin\");\n\t\t\tAssignment assignment = assignmentService.getAssignment(opaqueContext);\n\t\t\tif(assignment.getAllowPeerAssessment() && !assignment.getDraft()){\n\t\t\t\tint numOfReviews = assignment.getPeerAssessmentNumReviews();\n\t\t\t\tList submissions = (List) assignmentService.getSubmissions(assignment);\n\t\t\t\t//keep a map of submission ids to look up possible existing peer assessments\n\t\t\t\tMap submissionIdMap = new HashMap();\n\t\t\t\t//keep track of who has been assigned an assessment\n\t\t\t\tMap> assignedAssessmentsMap = new HashMap>();\n\t\t\t\t//keep track of how many assessor's each student has\n\t\t\t\tMap studentAssessorsMap = new HashMap();\n\t\t\t\tList submitterUsersList = (List) assignmentService.allowAddSubmissionUsers(assignment.getReference());\n\t\t\t\tList submitterIdsList = new ArrayList();\n\t\t\t\tif(submitterUsersList != null){\n\t\t\t\t\tfor(User u : submitterUsersList){\n\t\t\t\t\t\tsubmitterIdsList.add(u.getId());\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t//loop through the assignment submissions and setup the maps and lists\n\t\t\t\tfor(AssignmentSubmission s : submissions){\n\t\t\t\t\tif(s.getTimeSubmitted() != null \n\t\t\t\t\t\t\t//check if the submission is submitted, if not, see if there is any submission data to review (i.e. draft was auto submitted)\n\t\t\t\t\t\t\t&& (s.getSubmitted() || ((s.getSubmittedText() != null && !\"\".equals(s.getSubmittedText().trim()) || (s.getSubmittedAttachments() != null && s.getSubmittedAttachments().size() > 0)))) \n\t\t\t\t\t\t\t&& submitterIdsList.contains(s.getSubmitterId()) && !\"admin\".equals(s.getSubmitterId())){\n\t\t\t\t\t\t//only deal with users in the submitter's list\n\t\t\t\t\t\tsubmissionIdMap.put(s.getId(), s);\n\t\t\t\t\t\tassignedAssessmentsMap.put(s.getSubmitterId(), new HashMap());\n\t\t\t\t\t\tstudentAssessorsMap.put(s.getSubmitterId(), 0);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t//this could be an update to an existing assessment... just make sure to grab any existing\n\t\t\t\t//review items first\n\t\t\t\tList existingItems = getPeerAssessmentItems(submissionIdMap.keySet(), assignment.getContent().getFactor());\n\t\t\t\tList removeItems = new ArrayList();\n\t\t\t\t//remove all empty items to start from scratch:\n\t\t\t\tfor (Iterator iterator = existingItems.iterator(); iterator\n\t\t\t\t\t\t.hasNext();) {\n\t\t\t\t\tPeerAssessmentItem peerAssessmentItem = (PeerAssessmentItem) iterator.next();\n\t\t\t\t\tif(peerAssessmentItem.getScore() == null && (peerAssessmentItem.getComment() == null || \"\".equals(peerAssessmentItem.getComment().trim()))){\n\t\t\t\t\t\tremoveItems.add(peerAssessmentItem);\n\t\t\t\t\t\titerator.remove();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif(removeItems.size() > 0){\n\t\t\t\t\tgetHibernateTemplate().deleteAll(removeItems);\n\t\t\t\t}\n\t\t\t\t//loop through the items and update the map values:\n\t\t\t\tfor(PeerAssessmentItem p : existingItems){\n\t\t\t\t\tif(submissionIdMap.containsKey(p.getSubmissionId())){\n\t\t\t\t\t\t//first, add this assessment to the AssignedAssessmentsMap\n\t\t\t\t\t\tAssignmentSubmission s = submissionIdMap.get(p.getSubmissionId());\n\t\t\t\t\t\t//Next, increment the count for studentAssessorsMap\n\t\t\t\t\t\tInteger count = studentAssessorsMap.get(s.getSubmitterId());\n\t\t\t\t\t\tif(count == null){\n\t\t\t\t\t\t\t//probably not possible, just check\n\t\t\t\t\t\t\tcount = 0;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t//check if the count is less than num of reviews before added another one,\n\t\t\t\t\t\t//otherwise, we need to delete this one (if it's empty)\n\t\t\t\t\t\tif(count < numOfReviews || p.getScore() != null || p.getComment() != null){\n\t\t\t\t\t\t\tcount++;\n\t\t\t\t\t\t\tstudentAssessorsMap.put(s.getSubmitterId(), count);\n\t\t\t\t\t\t\tMap peerAssessments = assignedAssessmentsMap.get(p.getAssessorUserId());\n\t\t\t\t\t\t\tif(peerAssessments == null){\n\t\t\t\t\t\t\t\t//probably not possible, but just check\n\t\t\t\t\t\t\t\tpeerAssessments = new HashMap();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tpeerAssessments.put(p.getSubmissionId(), p);\n\t\t\t\t\t\t\tassignedAssessmentsMap.put(p.getAssessorUserId(), peerAssessments);\n\t\t\t\t\t\t}else{\n\t\t\t\t\t\t\t//this shoudln't happen since the code above removes all empty assessments, but just in case:\n\t\t\t\t\t\t\tgetHibernateTemplate().delete(p);\n\t\t\t\t\t\t}\n\t\t\t\t\t}else{\n\t\t\t\t\t\t//this isn't realy possible since we looked up the peer assessments by submission id\n\t\t\t\t\t\tlog.error(\"AssignmentPeerAssessmentServiceImpl: found a peer assessment with an invalid session id: \" + p.getSubmissionId());\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t\n\t\t\t\t//ok now that we have any existing assigned reviews accounted for, let's make sure that the number of reviews is setup properly,\n\t\t\t\t//if not, add some\n\t\t\t\t//let's get a random order of submission IDs so we can have a random assigning algorithm\n\t\t\t\tList randomSubmissionIds = new ArrayList(submissionIdMap.keySet());\n\t\t\t\tCollections.shuffle(randomSubmissionIds);\n\t\t\t\tList newItems = new ArrayList();\n\t\t\t\tint i = 0;\n\t\t\t\tfor(String submissionId : randomSubmissionIds){\n\t\t\t\t\tAssignmentSubmission s = submissionIdMap.get(submissionId);\n\t\t\t\t\t//first find out how many existing items exist for this user:\n\t\t\t\t\tInteger assignedCount = studentAssessorsMap.get(s.getSubmitterId());\n\t\t\t\t\t//by creating a tailing list (snake style), we eliminate the issue where you can be stuck with\n\t\t\t\t\t//a submission and the same submission user left, making for uneven distributions of submission reviews\n\t\t\t\t\tList snakeSubmissionList = new ArrayList(randomSubmissionIds.subList(i, randomSubmissionIds.size()));\n\t\t\t\t\tif(i > 0){", "answers": ["\t\t\t\t\t\tsnakeSubmissionList.addAll(new ArrayList(randomSubmissionIds.subList(0, i)));"], "length": 781, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "f6f354a9-17eb-4791-9aa7-2af4978960b0", "reasoning": "We are inside a for‑loop that iterates over shuffled submission IDs. A \"snake\" list is built from the tail of the shuffled list starting at index i. To complete the snake style, when i>0 we need to append the leading part of the list (indices 0 to i‑1) to the tail list, creating a circular ordering. The next line therefore adds the preceding sublist to snakeSubmissionList: snakeSubmissionList.addAll(randomSubmissionIds.subList(0, i));", "reasoning_model_answer": "snakeSubmissionList.addAll(randomSubmissionIds.subList(0, i));", "assistant_with_reasoning": "\nWe are inside a for‑loop that iterates over shuffled submission IDs. A \"snake\" list is built from the tail of the shuffled list starting at index i. To complete the snake style, when i>0 we need to append the leading part of the list (indices 0 to i‑1) to the tail list, creating a circular ordering. The next line therefore adds the preceding sublist to snakeSubmissionList: snakeSubmissionList.addAll(randomSubmissionIds.subList(0, i));\n\nsnakeSubmissionList.addAll(randomSubmissionIds.subList(0, i));", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.727, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 9585, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "snakeSubmissionList.addAll(randomSubmissionIds.subList(0, i));", "score": 0.81, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "// ***********************************************************************\n// Copyright (c) 2011 Charlie Poole, Rob Prouse\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n// ***********************************************************************\n\nusing System;\nusing System.Reflection;\nusing System.Globalization;\nusing NUnit.Common;\nusing NUnit.Options;\nusing NUnit.Framework;\n\nnamespace NUnitLite.Tests\n{\n using System.Collections.Generic;\n using System.IO;\n using System.Linq;\n using NUnit.TestUtilities;\n\n [TestFixture]\n public class CommandLineTests\n {\n #region Argument PreProcessor Tests\n\n [TestCase(\"--arg\", \"--arg\")]\n [TestCase(\"--ArG\", \"--ArG\")]\n [TestCase(\"--arg1 --arg2\", \"--arg1\", \"--arg2\")]\n [TestCase(\"--arg1 data --arg2\", \"--arg1\", \"data\", \"--arg2\")]\n [TestCase(\"\")]\n [TestCase(\" \")]\n [TestCase(\"\\\"--arg 1\\\" --arg2\", \"--arg 1\", \"--arg2\")]\n [TestCase(\"--arg1 \\\"--arg 2\\\"\", \"--arg1\", \"--arg 2\")]\n [TestCase(\"\\\"--arg 1\\\" \\\"--arg 2\\\"\", \"--arg 1\", \"--arg 2\")]\n [TestCase(\"\\\"--arg 1\\\" \\\"--arg 2\\\" arg3 \\\"arg 4\\\"\", \"--arg 1\", \"--arg 2\", \"arg3\", \"arg 4\")]\n [TestCase(\"--arg1 \\\"--arg 2\\\" arg3 \\\"arg 4\\\"\", \"--arg1\", \"--arg 2\", \"arg3\", \"arg 4\")]\n [TestCase(\"\\\"--arg 1\\\" \\\"--arg 2\\\" arg3 \\\"arg 4\\\" \\\"--arg 1\\\" \\\"--arg 2\\\" arg3 \\\"arg 4\\\"\",\n \"--arg 1\", \"--arg 2\", \"arg3\", \"arg 4\", \"--arg 1\", \"--arg 2\", \"arg3\", \"arg 4\")]\n [TestCase(\"\\\"--arg\\\"\", \"--arg\")]\n [TestCase(\"\\\"--arg 1\\\"\", \"--arg 1\")]\n [TestCase(\"\\\"--arg abc\\\"\", \"--arg abc\")]\n [TestCase(\"\\\"--arg abc\\\"\", \"--arg abc\")]\n [TestCase(\"\\\" --arg abc \\\"\", \" --arg abc \")]\n [TestCase(\"\\\"--arg=abc\\\"\", \"--arg=abc\")]\n [TestCase(\"\\\"--arg=aBc\\\"\", \"--arg=aBc\")]\n [TestCase(\"\\\"--arg = abc\\\"\", \"--arg = abc\")]\n [TestCase(\"\\\"--arg=abc,xyz\\\"\", \"--arg=abc,xyz\")]\n [TestCase(\"\\\"--arg=abc, xyz\\\"\", \"--arg=abc, xyz\")]\n [TestCase(\"\\\"@arg = ~ ` ! @ # $ % ^ & * ( ) _ - : ; + ' ' { } [ ] | \\\\ ? / . , , xYz\\\"\",\n \"@arg = ~ ` ! @ # $ % ^ & * ( ) _ - : ; + ' ' { } [ ] | \\\\ ? / . , , xYz\")]\n public void GetArgsFromCommandLine(string cmdline, params string[] expectedArgs)\n {\n var actualArgs = CommandLineOptions.GetArgs(cmdline);\n\n Assert.AreEqual(expectedArgs, actualArgs);\n }\n\n [TestCase(\"--arg1 @file1.txt --arg2\", \"file1.txt:--filearg1 --filearg2\", \"--arg1\", \"--filearg1\", \"--filearg2\", \"--arg2\")]\n [TestCase(\"--arg1 @file1.txt --arg2\", \"file1.txt:--filearg1\\r\\n--filearg2\", \"--arg1\", \"--filearg1\", \"--filearg2\", \"--arg2\")]\n [TestCase(\"--arg1 @file1.txt --arg2\", \"file1.txt:--filearg1 data\", \"--arg1\", \"--filearg1\", \"data\", \"--arg2\")]\n [TestCase(\"--arg1 @file1.txt --arg2\", \"file1.txt:--filearg1 \\\"data in quotes\\\"\", \"--arg1\", \"--filearg1\", \"data in quotes\", \"--arg2\")]\n [TestCase(\"--arg1 @file1.txt --arg2\", \"file1.txt:--filearg1 \\\"data in quotes with 'single' quotes\\\"\", \"--arg1\", \"--filearg1\", \"data in quotes with 'single' quotes\", \"--arg2\")]\n [TestCase(\"--arg1 @file1.txt --arg2\", \"file1.txt:--filearg1 \\\"data in quotes with /slashes/\\\"\", \"--arg1\", \"--filearg1\", \"data in quotes with /slashes/\", \"--arg2\")]\n [TestCase(\"--arg1 @file1.txt --arg2 @file2.txt\", \"file1.txt:--filearg1 --filearg2,file2.txt:--filearg3\", \"--arg1\", \"--filearg1\", \"--filearg2\", \"--arg2\", \"--filearg3\")]\n [TestCase(\"--arg1 @file1.txt --arg2\", \"file1.txt:\", \"--arg1\", \"--arg2\")]\n // Blank lines\n [TestCase(\"--arg1 @file1.txt --arg2\", \"file1.txt:--fileArg1\\n\\n\\n--fileArg2\", \"--arg1\", \"--fileArg1\", \"--fileArg2\", \"--arg2\")]\n [TestCase(\"--arg1 @file1.txt --arg2\", \"file1.txt:--fileArg1\\n \\n\\t\\t\\n--fileArg2\", \"--arg1\", \"--fileArg1\", \"--fileArg2\", \"--arg2\")]\n [TestCase(\"--arg1 @file1.txt --arg2\", \"file1.txt:--fileArg1\\r\\n\\r\\n\\r\\n--fileArg2\", \"--arg1\", \"--fileArg1\", \"--fileArg2\", \"--arg2\")]\n [TestCase(\"--arg1 @file1.txt --arg2\", \"file1.txt:--fileArg1\\r\\n \\r\\n\\t\\t\\r\\n--fileArg2\", \"--arg1\", \"--fileArg1\", \"--fileArg2\", \"--arg2\")]\n [TestCase(\"--arg1 @file1.txt --arg2\", \"file1.txt:--filearg1 --filearg2\\r\\n\\n--filearg3 --filearg4\", \"--arg1\", \"--filearg1\", \"--filearg2\", \"--filearg3\", \"--filearg4\", \"--arg2\")]\n\n // Comments\n [TestCase(\"--arg1 @file1.txt --arg2\", \"file1.txt:--fileArg1\\nThis is NOT treated as a COMMENT\\n--fileArg2\", \"--arg1\", \"--fileArg1\", \"This\", \"is\", \"NOT\", \"treated\", \"as\", \"a\", \"COMMENT\", \"--fileArg2\", \"--arg2\")]\n [TestCase(\"--arg1 @file1.txt --arg2\", \"file1.txt:--fileArg1\\n#This is treated as a COMMENT\\n--fileArg2\", \"--arg1\", \"--fileArg1\", \"--fileArg2\", \"--arg2\")]\n // Nested files\n [TestCase(\"--arg1 @file1.txt --arg2 @file2.txt\", \"file1.txt:--filearg1 --filearg2,file2.txt:--filearg3 @file3.txt,file3.txt:--filearg4\", \"--arg1\", \"--filearg1\", \"--filearg2\", \"--arg2\", \"--filearg3\", \"--filearg4\")]\n // Where clauses\n [TestCase(\"testfile.dll @file1.txt --arg2\", \"file1.txt:--where test==somelongname\", \"testfile.dll\", \"--where\", \"test==somelongname\", \"--arg2\")]\n // NOTE: The next is not valid. Where clause is spread over several args and therefore won't parse. Quotes are required.\n [TestCase(\"testfile.dll @file1.txt --arg2\", \"file1.txt:--where test == somelongname\", \"testfile.dll\", \"--where\", \"test\", \"==\", \"somelongname\", \"--arg2\")]\n [TestCase(\"testfile.dll @file1.txt --arg2\",\n \"file1.txt:--where \\\"test == somelongname\\\"\",", "answers": [" \"testfile.dll\", \"--where\", \"test == somelongname\", \"--arg2\")]"], "length": 686, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "3e364238-820c-46fe-9050-c0ecea6891a9", "reasoning": "The code is a series of [TestCase] attributes applied to the GetArgsFromCommandLine method. Each attribute lists the command line string, file content, and then the expected argument list, ending with a closing parenthesis and bracket. The last attribute shown is incomplete; it provides the command line and file content but omits the expected arguments and the closing syntax. The next line should supply the expected arguments (the original command line split into its parts) and close the attribute, matching the pattern of earlier cases.", "reasoning_model_answer": "\"testfile.dll\", \"--where\", \"test == somelongname\", \"--arg2\")]", "assistant_with_reasoning": "\nThe code is a series of [TestCase] attributes applied to the GetArgsFromCommandLine method. Each attribute lists the command line string, file content, and then the expected argument list, ending with a closing parenthesis and bracket. The last attribute shown is incomplete; it provides the command line and file content but omits the expected arguments and the closing syntax. The next line should supply the expected arguments (the original command line split into its parts) and close the attribute, matching the pattern of earlier cases.\n\n\"testfile.dll\", \"--where\", \"test == somelongname\", \"--arg2\")]", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 6.476, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 6637, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "\"testfile.dll\", \"--where\", \"test == somelongname\", \"--arg2\")]", "score": 0.91, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/*\n * Copyright 2000-2012 JetBrains s.r.o.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.intellij.psi.impl.source;\n\nimport com.intellij.extapi.psi.StubBasedPsiElementBase;\nimport com.intellij.lang.ASTNode;\nimport com.intellij.navigation.ItemPresentation;\nimport com.intellij.navigation.ItemPresentationProviders;\nimport com.intellij.openapi.diagnostic.Logger;\nimport com.intellij.openapi.ui.Queryable;\nimport com.intellij.openapi.util.Pair;\nimport com.intellij.openapi.util.UserDataHolder;\nimport com.intellij.psi.*;\nimport com.intellij.psi.impl.*;\nimport com.intellij.psi.impl.java.stubs.JavaStubElementTypes;\nimport com.intellij.psi.impl.java.stubs.PsiClassStub;\nimport com.intellij.psi.impl.light.LightMethod;\nimport com.intellij.psi.impl.source.tree.ChildRole;\nimport com.intellij.psi.impl.source.tree.CompositeElement;\nimport com.intellij.psi.impl.source.tree.SharedImplUtil;\nimport com.intellij.psi.javadoc.PsiDocComment;\nimport com.intellij.psi.scope.ElementClassHint;\nimport com.intellij.psi.scope.NameHint;\nimport com.intellij.psi.scope.PsiScopeProcessor;\nimport com.intellij.psi.search.SearchScope;\nimport com.intellij.psi.stubs.IStubElementType;\nimport com.intellij.psi.stubs.PsiFileStub;\nimport com.intellij.psi.stubs.StubElement;\nimport com.intellij.psi.util.PsiTreeUtil;\nimport com.intellij.psi.util.PsiUtil;\nimport com.intellij.util.IncorrectOperationException;\nimport org.jetbrains.annotations.NonNls;\nimport org.jetbrains.annotations.NotNull;\nimport org.jetbrains.annotations.Nullable;\n\nimport javax.swing.*;\nimport java.util.Arrays;\nimport java.util.Collection;\nimport java.util.List;\nimport java.util.Map;\n\npublic class PsiClassImpl extends JavaStubPsiElement> implements PsiExtensibleClass, PsiQualifiedNamedElement, Queryable {\n private static final Logger LOG = Logger.getInstance(\"#com.intellij.psi.impl.source.PsiClassImpl\");\n\n private final ClassInnerStuffCache myInnersCache = new ClassInnerStuffCache(this);\n\n private volatile PsiMethod myValuesMethod;\n private volatile PsiMethod myValueOfMethod;\n private volatile String myCachedName;\n @NonNls private static final String VALUES_METHOD = \"values\";\n @NonNls private static final String VALUE_OF_METHOD = \"valueOf\";\n\n public PsiClassImpl(final PsiClassStub stub) {\n this(stub, JavaStubElementTypes.CLASS);\n }\n\n protected PsiClassImpl(final PsiClassStub stub, final IStubElementType type) {\n super(stub, type);\n addTrace(null);\n }\n\n public PsiClassImpl(final ASTNode node) {\n super(node);\n addTrace(null);\n }\n\n private void addTrace(@Nullable PsiClassStub stub) {\n if (ourTraceStubAstBinding) {\n String creationTrace = \"Creation thread: \" + Thread.currentThread() + \"\\n\" + DebugUtil.currentStackTrace();\n if (stub != null) {\n creationTrace += \"\\nfrom stub \" + stub + \"@\" + System.identityHashCode(stub) + \"\\n\";\n if (stub instanceof UserDataHolder) {\n String stubTrace = ((UserDataHolder)stub).getUserData(CREATION_TRACE);\n if (stubTrace != null) {\n creationTrace += stubTrace;\n }\n }\n }\n putUserData(CREATION_TRACE, creationTrace);\n }\n }\n\n @Override\n public void subtreeChanged() {\n dropCaches();\n super.subtreeChanged();\n }\n\n private void dropCaches() {\n myInnersCache.dropCaches();\n myCachedName = null;\n myValueOfMethod = null;\n myValuesMethod = null;\n }\n\n @Override\n protected Object clone() {\n PsiClassImpl clone = (PsiClassImpl)super.clone();\n clone.dropCaches();\n return clone;\n }\n\n @Override\n public PsiElement getParent() {\n final PsiClassStub stub = getStub();\n if (stub != null) {\n final StubElement parentStub = stub.getParentStub();\n if (parentStub instanceof PsiFileStub || parentStub instanceof PsiClassStub\n ) {\n return parentStub.getPsi();\n }\n }\n\n return SharedImplUtil.getParent(getNode());\n }\n\n @Override\n public PsiElement getOriginalElement() {\n final JavaPsiImplementationHelper helper = JavaPsiImplementationHelper.getInstance(getProject());\n if (helper != null) {\n return helper.getOriginalClass(this);\n }\n return this;\n }\n\n @Override\n @NotNull\n public CompositeElement getNode() {\n return (CompositeElement)super.getNode();\n }\n\n @Override\n public PsiIdentifier getNameIdentifier() {\n return (PsiIdentifier)getNode().findChildByRoleAsPsiElement(ChildRole.NAME);\n }\n\n @Override\n public PsiElement getScope() {\n final PsiClassStub stub = getStub();\n if (stub != null) {\n return stub.getParentStub().getPsi();\n }\n\n ASTNode treeElement = getNode();\n ASTNode parent = treeElement.getTreeParent();\n\n while(parent != null) {\n if (parent.getElementType() instanceof IStubElementType){\n return parent.getPsi();\n }\n parent = parent.getTreeParent();\n }\n\n return getContainingFile();\n }\n\n @Override\n public String getName() {\n String name = myCachedName;\n if (name != null) return name;\n final PsiClassStub stub = getStub();\n if (stub == null) {\n PsiIdentifier identifier = getNameIdentifier();\n name = identifier == null ? null : identifier.getText();\n }\n else {\n name = stub.getName();\n }\n myCachedName = name;\n return name;\n }\n\n @Override\n public String getQualifiedName() {\n final PsiClassStub stub = getStub();\n if (stub != null) {\n return stub.getQualifiedName();\n }\n\n PsiElement parent = getParent();\n if (parent instanceof PsiJavaFile) {\n String packageName = ((PsiJavaFile)parent).getPackageName();\n if (packageName.isEmpty()) {\n return getName();\n }\n return packageName + \".\" + getName();\n }\n if (parent instanceof PsiClass) {\n String parentQName = ((PsiClass)parent).getQualifiedName();\n if (parentQName == null) return null;\n return parentQName + \".\" + getName();\n }\n\n return null;\n }\n\n @Override\n public PsiModifierList getModifierList() {\n return getRequiredStubOrPsiChild(JavaStubElementTypes.MODIFIER_LIST);\n }\n\n @Override\n public boolean hasModifierProperty(@NotNull String name) {\n final PsiModifierList modlist = getModifierList();\n return modlist != null && modlist.hasModifierProperty(name);\n }\n\n @Override\n public PsiReferenceList getExtendsList() {\n return getStubOrPsiChild(JavaStubElementTypes.EXTENDS_LIST);\n }\n\n @Override\n public PsiReferenceList getImplementsList() {\n return getStubOrPsiChild(JavaStubElementTypes.IMPLEMENTS_LIST);\n }\n\n @Override\n @NotNull\n public PsiClassType[] getExtendsListTypes() {\n return PsiClassImplUtil.getExtendsListTypes(this);\n }\n\n @Override\n @NotNull\n public PsiClassType[] getImplementsListTypes() {\n return PsiClassImplUtil.getImplementsListTypes(this);\n }\n\n @Override\n public PsiClass getSuperClass() {\n return PsiClassImplUtil.getSuperClass(this);\n }\n\n @Override\n public PsiClass[] getInterfaces() {\n return PsiClassImplUtil.getInterfaces(this);\n }\n\n @Override\n @NotNull\n public PsiClass[] getSupers() {\n return PsiClassImplUtil.getSupers(this);\n }\n\n @Override\n @NotNull\n public PsiClassType[] getSuperTypes() {\n return PsiClassImplUtil.getSuperTypes(this);\n }\n\n @Override\n @Nullable\n public PsiClass getContainingClass() {\n final PsiClassStub stub = getStub();\n if (stub != null) {\n StubElement parent = stub.getParentStub();\n while (parent != null && !(parent instanceof PsiClassStub)) {\n parent = parent.getParentStub();\n }\n\n if (parent != null) {\n return ((PsiClassStub)parent).getPsi();\n }\n }\n\n PsiElement parent = getParent();\n\n if (parent instanceof PsiClassLevelDeclarationStatement) {\n return PsiTreeUtil.getParentOfType(this, PsiSyntheticClass.class);\n }\n\n return parent instanceof PsiClass ? (PsiClass)parent : null;\n }\n\n @Override\n public PsiElement getContext() {\n final PsiClass cc = getContainingClass();\n return cc != null ? cc : super.getContext();\n }\n\n\n @Override\n @NotNull\n public Collection getVisibleSignatures() {\n return PsiSuperMethodImplUtil.getVisibleSignatures(this);\n }\n\n @Override\n @NotNull\n public PsiField[] getFields() {\n return myInnersCache.getFields();\n }\n", "answers": [" @Override"], "length": 790, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "1ce846e7-3e81-4777-ac9f-041493e7710b", "reasoning": "The code ends with the getFields() method implementation. In PsiClassImpl the next logical member is the getMethods() method, which begins with the @Override annotation. Therefore the next line after the closing brace of getFields() is the @Override annotation for the following method.", "reasoning_model_answer": "@Override", "assistant_with_reasoning": "\nThe code ends with the getFields() method implementation. In PsiClassImpl the next logical member is the getMethods() method, which begins with the @Override annotation. Therefore the next line after the closing brace of getFields() is the @Override annotation for the following method.\n\n@Override", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.544, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 8885, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "@Override", "score": 0.9, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/*\n\n Copyright (c) 2005-2006 Tomas Matousek. \n\n The use and distribution terms for this software are contained in the file named License.txt, \n which can be found in the root of the Phalanger distribution. By using this software \n in any fashion, you are agreeing to be bound by the terms of this license.\n \n You must not remove this notice from this software.\n\n*/\n\nusing System;\nusing System.Diagnostics;\nusing System.IO;\nusing System.Threading;\nusing System.Collections;\nusing Process = System.Diagnostics.Process;\n\nusing PHP.Core;\nusing PHP.Core.Reflection;\n\nnamespace PHP.Library\n{\n\t#region PhpProcessHandle\n\n\tpublic class PhpProcessHandle : PhpResource\n\t{\n\t\tpublic Process/*!*/ Process { get { return process; } }\n\t\tprivate Process/*!*/ process;\n\n\t\tpublic string/*!*/ Command { get { return command; } }\n\t\tprivate string/*!*/ command;\n\n\t\tinternal PhpProcessHandle(Process/*!*/ process, string/*!*/ command)\n\t\t\t: base(\"process\")\n\t\t{\n\t\t\tDebug.Assert(process != null && command != null);\n\t\t\tthis.process = process;\n\t\t\tthis.command = command;\n\t\t}\n\n\t\tprotected override void FreeManaged()\n\t\t{\n\t\t\tprocess.Close();\n\t\t\tbase.FreeManaged();\n\t\t}\n\n\t\tinternal static PhpProcessHandle Validate(PhpResource resource)\n\t\t{\n\t\t\tPhpProcessHandle result = resource as PhpProcessHandle;\n\n\t\t\tif (result == null || !result.IsValid)\n\t\t\t{\n\t\t\t\tPhpException.Throw(PhpError.Warning, LibResources.GetString(\"invalid_process_resource\"));\n\t\t\t\treturn null;\n\t\t\t}\n\n\t\t\treturn result;\n\t\t}\n\t}\n\n\t#endregion\n\n\tpublic static class Processes\n\t{\n\t\t#region popen, pclose\n\n\t\tprivate sealed class ProcessWrapper : StreamWrapper\n\t\t{\n\t\t\tpublic Process/*!*/ process;\n\n\t\t\tpublic ProcessWrapper(Process/*!*/ process)\n\t\t\t{\n\t\t\t\tthis.process = process;\n\t\t\t}\n\n\t\t\tpublic override bool IsUrl { get { return false; } }\n\t\t\tpublic override string Label { get { return null; } }\n\t\t\tpublic override string Scheme { get { return null; } }\n\n\t\t\tpublic override PhpStream Open(ref string path, string mode, StreamOpenOptions options, StreamContext context)\n\t\t\t{\n\t\t\t\treturn null;\n\t\t\t}\n\t\t}\n\n\t\t/// \n\t\t/// Starts a process and creates a pipe to its standard input or output.\n\t\t/// \n\t\t/// The command.\n\t\t/// Pipe open mode (\"r\" or \"w\").\n\t\t/// Opened pipe or null on error.\n\t\t[ImplementsFunction(\"popen\")]\n\t\tpublic static PhpResource OpenPipe(string command, string mode)\n\t\t{\n\t\t\tif (String.IsNullOrEmpty(mode))\n\t\t\t{\n\t\t\t\tPhpException.Throw(PhpError.Warning, CoreResources.GetString(\"invalid_file_mode\", mode));\n\t\t\t\treturn null;\n\t\t\t}\n\n\t\t\tbool read = mode[0] == 'r';\n\t\t\tbool write = mode[0] == 'w' || mode[0] == 'a' || mode[0] == 'x';\n\n\t\t\tif (!read && !write)\n\t\t\t{\n\t\t\t\tPhpException.Throw(PhpError.Warning, CoreResources.GetString(\"invalid_file_mode\", mode));\n\t\t\t\treturn null;\n\t\t\t}\n\n\t\t\tProcess process = CreateProcessExecutingCommand(ref command, false);\n\t\t\tif (process == null) return null;\n\n\t\t\tprocess.StartInfo.RedirectStandardOutput = read;\n\t\t\tprocess.StartInfo.RedirectStandardInput = write;\n\n\t\t\tif (!StartProcess(process, true))\n\t\t\t\treturn null;\n\n\t\t\tStream stream = (read) ? process.StandardOutput.BaseStream : process.StandardInput.BaseStream;\n\t\t\tStreamAccessOptions access = (read) ? StreamAccessOptions.Read : StreamAccessOptions.Write;\n\t\t\tProcessWrapper wrapper = new ProcessWrapper(process);\n\t\t\tPhpStream php_stream = new NativeStream(stream, wrapper, access, String.Empty, StreamContext.Default);\n\n\t\t\treturn php_stream;\n\t\t}\n\n\t\t/// \n\t\t/// Closes a pipe and a process opened by .\n\t\t/// \n\t\t/// The pipe handle returned by .\n\t\t/// An exit code of the process.\n\t\t[ImplementsFunction(\"pclose\")]\n\t\tpublic static int ClosePipe(PhpResource pipeHandle)\n\t\t{\n\t\t\tPhpStream php_stream = PhpStream.GetValid(pipeHandle);\n\t\t\tif (php_stream == null) return -1;\n\n\t\t\tProcessWrapper wrapper = php_stream.Wrapper as ProcessWrapper;\n\t\t\tif (wrapper == null) return -1;\n\n\t\t\tvar code = CloseProcess(wrapper.process);\n php_stream.Close();\n return code;\n\t\t}\n\n\t\t#endregion\n\n\t\t#region proc_open\n\n\t\t/// \n\t\t/// Opens a process.\n\t\t/// \n\t\t[ImplementsFunction(\"proc_open\")]\n\t\tpublic static PhpResource Open(string command, PhpArray descriptorSpec, out PhpArray pipes)\n\t\t{\n\t\t\treturn Open(command, descriptorSpec, out pipes, null, null, null);\n\t\t}\n\n\t\t/// \n\t\t/// Opens a process.\n\t\t/// \n\t\t[ImplementsFunction(\"proc_open\")]\n\t\tpublic static PhpResource Open(string command, PhpArray descriptorSpec, out PhpArray pipes,\n\t\t string workingDirectory)\n\t\t{\n\t\t\treturn Open(command, descriptorSpec, out pipes, workingDirectory, null, null);\n\t\t}\n\n\t\t/// \n\t\t/// Opens a process.\n\t\t/// \n\t\t[ImplementsFunction(\"proc_open\")]\n\t\tpublic static PhpResource Open(string command, PhpArray descriptorSpec, out PhpArray pipes,\n\t\t string workingDirectory, PhpArray envVariables)\n\t\t{\n\t\t\treturn Open(command, descriptorSpec, out pipes, workingDirectory, envVariables, null);\n\t\t}\n\n\t\t/// \n\t\t/// Starts a process and otpionally redirects its input/output/error streams to specified PHP streams.\n\t\t/// \n\t\t/// \n\t\t/// \n\t\t/// Indexed array where the key represents the descriptor number (0 for STDIN, 1 for STDOUT, 2 for STDERR)\n\t\t/// and the value represents how to pass that descriptor to the child process. \n\t\t/// A descriptor is either an opened file resources or an integer indexed arrays \n\t\t/// containing descriptor name followed by options. Supported descriptors:\n\t\t/// \n\t\t/// array(\"pipe\",{mode})Pipe is opened in the specified mode .\n\t\t/// array(\"file\",{path},{mode})The file is opened in the specified mode.\n\t\t/// \n\t\t/// \n\t\t/// Set to indexed array of file resources corresponding to the current process's ends of created pipes.\n\t\t/// \n\t\t/// \n\t\t/// Working directory.\n\t\t/// \n\t\t/// \n\t\t/// \n\t\t/// Associative array containing following key-value pairs.\n\t\t/// \n\t\t/// \"suppress_errors\"\n\t\t/// \n\t\t/// \n\t\t/// \n\t\t/// Resource representing the process.\n\t\t/// \n\t\t[ImplementsFunction(\"proc_open\")]\n\t\tpublic static PhpResource Open(string command, PhpArray descriptors, out PhpArray pipes,\n\t\t string workingDirectory, PhpArray envVariables, PhpArray options)\n\t\t{\n\t\t\tif (descriptors == null)\n\t\t\t{\n\t\t\t\tPhpException.ArgumentNull(\"descriptors\");\n\t\t\t\tpipes = null;\n\t\t\t\treturn null;\n\t\t\t}\n\n\t\t\tpipes = new PhpArray();\n\t\t\tPhpResource result = Open(command, descriptors, pipes, workingDirectory, envVariables, options);\n\t\t\treturn result;\n\t\t}\n\n\t\t/// \n\t\t/// Opens a process.\n\t\t/// \n\t\tprivate static PhpResource Open(string command, PhpArray/*!*/ descriptors, PhpArray/*!*/ pipes,\n string workingDirectory, PhpArray envVariables, PhpArray options)\n\t\t{\n\t\t\tif (descriptors == null)\n\t\t\t\tthrow new ArgumentNullException(\"descriptors\");\n\t\t\tif (pipes == null)\n\t\t\t\tthrow new ArgumentNullException(\"pipes\");\n\n bool bypass_shell = options != null && Core.Convert.ObjectToBoolean(options[\"bypass_shell\"]); // quiet\n\n Process process = CreateProcessExecutingCommand(ref command, bypass_shell);\n\t\t\tif (process == null)\n\t\t\t\treturn null;\n\n\t\t\tif (!SetupStreams(process, descriptors))\n\t\t\t\treturn null;\n\n\t\t\tif (envVariables != null)\n\t\t\t\tSetupEnvironment(process, envVariables);\n\n\t\t\tif (workingDirectory != null)\n\t\t\t\tprocess.StartInfo.WorkingDirectory = workingDirectory;\n\n\t\t\tbool suppress_errors = false;\n\n\t\t\tif (options != null)\n\t\t\t{", "answers": ["\t\t\t\tsuppress_errors = Core.Convert.ObjectToBoolean(options[\"suppress_errors\"]);"], "length": 859, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "353a91f5-53eb-4d04-a1ec-116b00661c90", "reasoning": "The code just defined a bool suppress_errors = false; then checks if (options != null). Inside this block it should read the 'suppress_errors' option from the options array and assign it to the variable. The typical conversion uses Core.Convert.ObjectToBoolean. So the next line is the assignment of suppress_errors from options[\"suppress_errors\"].", "reasoning_model_answer": "suppress_errors = Core.Convert.ObjectToBoolean(options[\"suppress_errors\"]);", "assistant_with_reasoning": "\nThe code just defined a bool suppress_errors = false; then checks if (options != null). Inside this block it should read the 'suppress_errors' option from the options array and assign it to the variable. The typical conversion uses Core.Convert.ObjectToBoolean. So the next line is the assignment of suppress_errors from options[\"suppress_errors\"].\n\nsuppress_errors = Core.Convert.ObjectToBoolean(options[\"suppress_errors\"]);", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 2.334, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 7961, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "suppress_errors = Core.Convert.ObjectToBoolean(options[\"suppress_errors\"]);", "score": 0.97, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "using System.Windows.Forms;\n\nnamespace WikiFunctions.DBScanner\n{\n partial class DatabaseScanner\n {\n /// \n /// Required designer variable.\n /// \n private System.ComponentModel.IContainer components = null;\n\n /// \n /// Clean up any resources being used.\n /// \n /// true if managed resources should be disposed; otherwise, false.\n protected override void Dispose(bool disposing)\n {\n if (disposing && (components != null))\n {\n components.Dispose();\n }\n base.Dispose(disposing);\n }\n\n #region Windows Form Designer generated code\n\n /// \n /// Required method for Designer support - do not modify\n /// the contents of this method with the code editor.\n /// \n private void InitializeComponent()\n {\n this.components = new System.ComponentModel.Container();\n System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(DatabaseScanner));\n this.txtList = new System.Windows.Forms.TextBox();\n this.openXMLDialog = new System.Windows.Forms.OpenFileDialog();\n this.saveFileDialog = new System.Windows.Forms.SaveFileDialog();\n this.gbText = new System.Windows.Forms.GroupBox();\n this.tableLayoutPanel3 = new System.Windows.Forms.TableLayoutPanel();\n this.chkArticleDoesContain = new System.Windows.Forms.CheckBox();\n this.txtArticleDoesContain = new System.Windows.Forms.TextBox();\n this.chkArticleDoesNotContain = new System.Windows.Forms.CheckBox();\n this.txtArticleDoesNotContain = new System.Windows.Forms.TextBox();\n this.chkRegex = new System.Windows.Forms.CheckBox();\n this.chkCaseSensitive = new System.Windows.Forms.CheckBox();\n this.chkSingle = new System.Windows.Forms.CheckBox();\n this.chkMulti = new System.Windows.Forms.CheckBox();\n this.chkIgnoreComments = new System.Windows.Forms.CheckBox();\n this.lblLength = new System.Windows.Forms.Label();\n this.nudLength = new System.Windows.Forms.NumericUpDown();\n this.cmboLength = new System.Windows.Forms.ComboBox();\n this.lblLinks = new System.Windows.Forms.Label();\n this.cmboLinks = new System.Windows.Forms.ComboBox();\n this.nudLinks = new System.Windows.Forms.NumericUpDown();\n this.lblWords = new System.Windows.Forms.Label();\n this.cmboWords = new System.Windows.Forms.ComboBox();\n this.nudWords = new System.Windows.Forms.NumericUpDown();\n this.nudHeadingSpace = new System.Windows.Forms.NumericUpDown();\n this.chkHeading = new System.Windows.Forms.CheckBox();\n this.btnClear = new System.Windows.Forms.Button();\n this.btnCopy = new System.Windows.Forms.Button();\n this.tooltip = new System.Windows.Forms.ToolTip(this.components);\n this.btnTransfer = new System.Windows.Forms.Button();\n this.btnClearList = new System.Windows.Forms.Button();\n this.chkNoBold = new System.Windows.Forms.CheckBox();\n this.chkCiteTemplateDates = new System.Windows.Forms.CheckBox();\n this.chkUnbalancedBrackets = new System.Windows.Forms.CheckBox();\n this.chkBadLinks = new System.Windows.Forms.CheckBox();\n this.chkHasHTML = new System.Windows.Forms.CheckBox();\n this.chkHeaderError = new System.Windows.Forms.CheckBox();\n this.chkUnbulletedLinks = new System.Windows.Forms.CheckBox();\n this.chkABCHeader = new System.Windows.Forms.CheckBox();\n this.txtStartFrom = new System.Windows.Forms.TextBox();\n this.chkSimpleLinks = new System.Windows.Forms.CheckBox();\n this.ArticlesListBoxContextMenu = new System.Windows.Forms.ContextMenuStrip(this.components);\n this.openInBrowserToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();\n this.openRevisionInBowserToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();\n this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator();\n this.copyToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();\n this.removeToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();\n this.gbOutput = new System.Windows.Forms.GroupBox();\n this.btnSaveArticleList = new System.Windows.Forms.Button();\n this.lbArticles = new WikiFunctions.Controls.Lists.ListBox2();\n this.btnFilter = new System.Windows.Forms.Button();\n this.lblStartFrom = new System.Windows.Forms.Label();\n this.lblLimitResutls = new System.Windows.Forms.Label();\n this.nudLimitResults = new System.Windows.Forms.NumericUpDown();\n this.btnStart = new System.Windows.Forms.Button();\n this.btnSaveTxtList = new System.Windows.Forms.Button();\n this.lblListType = new System.Windows.Forms.Label();\n this.rdoBullet = new System.Windows.Forms.RadioButton();\n this.rdoHash = new System.Windows.Forms.RadioButton();\n this.statusStrip = new System.Windows.Forms.StatusStrip();\n this.progressBar = new System.Windows.Forms.ToolStripProgressBar();\n this.lblPercentageComplete = new System.Windows.Forms.ToolStripStatusLabel();\n this.lblCount = new System.Windows.Forms.ToolStripStatusLabel();\n this.toolStripStatusLabel1 = new System.Windows.Forms.ToolStripStatusLabel();\n this.threadPriorityButton = new System.Windows.Forms.ToolStripDropDownButton();\n this.highestToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();\n this.aboveNormalToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();\n this.normalToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();\n this.belowNormalToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();\n this.lowestToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();\n this.timerProgessUpdate = new System.Windows.Forms.Timer(this.components);\n this.gbAWBSpecific = new System.Windows.Forms.GroupBox();\n this.flwAWB = new System.Windows.Forms.FlowLayoutPanel();\n this.chkTypo = new System.Windows.Forms.CheckBox();\n this.chkDefaultSort = new System.Windows.Forms.CheckBox();\n this.tbParameters = new System.Windows.Forms.TabControl();\n this.tabDump = new System.Windows.Forms.TabPage();\n this.flwHelpLinks = new System.Windows.Forms.FlowLayoutPanel();\n this.lblAlso = new System.Windows.Forms.Label();\n this.lnkWmfDumps = new System.Windows.Forms.LinkLabel();\n this.lnkWikiaDumps = new System.Windows.Forms.LinkLabel();\n this.lnkGenDump = new System.Windows.Forms.LinkLabel();\n this.btnAbout = new System.Windows.Forms.Button();\n this.txtCase = new System.Windows.Forms.TextBox();\n this.lblCase = new System.Windows.Forms.Label();\n this.txtGenerator = new System.Windows.Forms.TextBox();\n this.lblGenerator = new System.Windows.Forms.Label();\n this.lnkBase = new System.Windows.Forms.LinkLabel();\n this.lblBase = new System.Windows.Forms.Label();\n this.txtSitename = new System.Windows.Forms.TextBox();\n this.lblSitename = new System.Windows.Forms.Label();\n this.btnBrowse = new System.Windows.Forms.Button();\n this.txtDumpLocation = new System.Windows.Forms.TextBox();\n this.lblDBDump = new System.Windows.Forms.Label();\n this.tabNamespace = new System.Windows.Forms.TabPage();\n this.pageNamespaces = new WikiFunctions.Controls.Namespaces();\n this.tabTitle = new System.Windows.Forms.TabPage();\n this.tableLayoutPanel2 = new System.Windows.Forms.TableLayoutPanel();\n this.chkTitleCase = new System.Windows.Forms.CheckBox();\n this.chkTitleContains = new System.Windows.Forms.CheckBox();\n this.chkTitleRegex = new System.Windows.Forms.CheckBox();\n this.txtTitleContains = new System.Windows.Forms.TextBox();\n this.chkTitleDoesNotContain = new System.Windows.Forms.CheckBox();\n this.txtTitleNotContains = new System.Windows.Forms.TextBox();\n this.tabRev = new System.Windows.Forms.TabPage();\n this.chkSearchDates = new System.Windows.Forms.CheckBox();\n this.lblDate = new System.Windows.Forms.Label();\n this.dtpFrom = new System.Windows.Forms.DateTimePicker();\n this.lblEndDate = new System.Windows.Forms.Label();\n this.dtpTo = new System.Windows.Forms.DateTimePicker();\n this.tabText = new System.Windows.Forms.TabPage();\n this.gbProperties = new System.Windows.Forms.GroupBox();\n this.chkIgnoreRedirects = new System.Windows.Forms.CheckBox();\n this.tabAWB = new System.Windows.Forms.TabPage();\n this.tabRestrict = new System.Windows.Forms.TabPage();\n this.chkProtection = new System.Windows.Forms.CheckBox();\n this.MoveDelete = new WikiFunctions.Controls.EditProtectControl();\n this.btnReset = new System.Windows.Forms.Button();\n this.toolStripMenuItem2 = new System.Windows.Forms.ToolStripMenuItem();\n this.toolStripMenuItem3 = new System.Windows.Forms.ToolStripMenuItem();\n this.toolStripMenuItem4 = new System.Windows.Forms.ToolStripMenuItem();\n this.toolStripMenuItem5 = new System.Windows.Forms.ToolStripMenuItem();\n this.toolStripMenuItem6 = new System.Windows.Forms.ToolStripMenuItem();\n this.tabControl1 = new System.Windows.Forms.TabControl();\n this.tabConvert = new System.Windows.Forms.TabPage();\n this.btnPause = new System.Windows.Forms.Button();\n this.splitContainer1 = new System.Windows.Forms.SplitContainer();\n this.saveListDialog = new System.Windows.Forms.SaveFileDialog();\n this.gbText.SuspendLayout();\n this.tableLayoutPanel3.SuspendLayout();\n ((System.ComponentModel.ISupportInitialize)(this.nudLength)).BeginInit();\n ((System.ComponentModel.ISupportInitialize)(this.nudLinks)).BeginInit();\n ((System.ComponentModel.ISupportInitialize)(this.nudWords)).BeginInit();\n ((System.ComponentModel.ISupportInitialize)(this.nudHeadingSpace)).BeginInit();\n this.ArticlesListBoxContextMenu.SuspendLayout();\n this.gbOutput.SuspendLayout();\n ((System.ComponentModel.ISupportInitialize)(this.nudLimitResults)).BeginInit();\n this.statusStrip.SuspendLayout();\n this.gbAWBSpecific.SuspendLayout();\n this.flwAWB.SuspendLayout();\n this.tbParameters.SuspendLayout();\n this.tabDump.SuspendLayout();\n this.flwHelpLinks.SuspendLayout();\n this.tabNamespace.SuspendLayout();\n this.tabTitle.SuspendLayout();\n this.tableLayoutPanel2.SuspendLayout();\n this.tabRev.SuspendLayout();\n this.tabText.SuspendLayout();\n this.gbProperties.SuspendLayout();\n this.tabAWB.SuspendLayout();\n this.tabRestrict.SuspendLayout();\n this.tabControl1.SuspendLayout();\n this.tabConvert.SuspendLayout();\n this.splitContainer1.Panel1.SuspendLayout();\n this.splitContainer1.Panel2.SuspendLayout();\n this.splitContainer1.SuspendLayout();\n this.SuspendLayout();\n // \n // txtList\n // \n this.txtList.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)\n | System.Windows.Forms.AnchorStyles.Left)\n | System.Windows.Forms.AnchorStyles.Right)));\n this.txtList.Location = new System.Drawing.Point(3, 51);\n this.txtList.MaxLength = 0;\n this.txtList.Multiline = true;\n this.txtList.Name = \"txtList\";\n this.txtList.ScrollBars = System.Windows.Forms.ScrollBars.Both;\n this.txtList.Size = new System.Drawing.Size(276, 189);\n this.txtList.TabIndex = 7;\n this.txtList.WordWrap = false;\n // \n // openXMLDialog\n // \n this.openXMLDialog.FileName = \"current or articles XML file\";\n this.openXMLDialog.Filter = \"XML file|*.xml\";\n this.openXMLDialog.Title = \"Open \\\"current\\\" or \\\"Pages\\\" XML file\";\n // \n // saveFileDialog\n // \n this.saveFileDialog.DefaultExt = \"txt\";\n this.saveFileDialog.Filter = \"Text file|*.txt\";\n // \n // gbText\n // \n this.gbText.Controls.Add(this.tableLayoutPanel3);\n this.gbText.Location = new System.Drawing.Point(6, 6);\n this.gbText.Name = \"gbText\";\n this.gbText.Size = new System.Drawing.Size(277, 141);\n this.gbText.TabIndex = 1;\n this.gbText.TabStop = false;\n this.gbText.Text = \"Te&xt Searching\";\n // \n // tableLayoutPanel3\n // \n this.tableLayoutPanel3.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;\n this.tableLayoutPanel3.ColumnCount = 3;\n this.tableLayoutPanel3.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle());\n this.tableLayoutPanel3.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle());\n this.tableLayoutPanel3.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle());\n this.tableLayoutPanel3.Controls.Add(this.chkArticleDoesContain, 0, 0);\n this.tableLayoutPanel3.Controls.Add(this.txtArticleDoesContain, 1, 0);\n this.tableLayoutPanel3.Controls.Add(this.chkArticleDoesNotContain, 0, 1);\n this.tableLayoutPanel3.Controls.Add(this.txtArticleDoesNotContain, 1, 1);\n this.tableLayoutPanel3.Controls.Add(this.chkRegex, 1, 2);\n this.tableLayoutPanel3.Controls.Add(this.chkCaseSensitive, 1, 3);\n this.tableLayoutPanel3.Controls.Add(this.chkSingle, 2, 2);\n this.tableLayoutPanel3.Controls.Add(this.chkMulti, 2, 3);\n this.tableLayoutPanel3.Controls.Add(this.chkIgnoreComments, 1, 4);\n this.tableLayoutPanel3.Dock = System.Windows.Forms.DockStyle.Top;\n this.tableLayoutPanel3.Location = new System.Drawing.Point(3, 16);\n this.tableLayoutPanel3.Margin = new System.Windows.Forms.Padding(0);", "answers": [" this.tableLayoutPanel3.Name = \"tableLayoutPanel3\";"], "length": 804, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "e8b8427b-651a-40ca-b02d-1c6c82248eeb", "reasoning": "The code is part of the Windows Forms Designer generated InitializeComponent method. After configuring properties like Location and Margin for a control, the designer typically sets the control's Name property next. For the TableLayoutPanel named tableLayoutPanel3, the next line should assign its Name.", "reasoning_model_answer": "this.tableLayoutPanel3.Name = \"tableLayoutPanel3\";", "assistant_with_reasoning": "\nThe code is part of the Windows Forms Designer generated InitializeComponent method. After configuring properties like Location and Margin for a control, the designer typically sets the control's Name property next. For the TableLayoutPanel named tableLayoutPanel3, the next line should assign its Name.\n\nthis.tableLayoutPanel3.Name = \"tableLayoutPanel3\";", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.857, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 15122, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "this.tableLayoutPanel3.Name = \"tableLayoutPanel3\";", "score": 0.89, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/*----------------------------------------------------------------------------*/\n/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */\n/* Open Source Software - may be modified and shared by FRC teams. The code */\n/* must be accompanied by the FIRST BSD license file in the root directory of */\n/* the project. */\n/*----------------------------------------------------------------------------*/\n\npackage edu.wpi.first.wpilibj;\n\nimport edu.wpi.first.wpilibj.communication.UsageReporting;\nimport edu.wpi.first.wpilibj.fpga.tDIO;\nimport edu.wpi.first.wpilibj.livewindow.LiveWindow;\nimport edu.wpi.first.wpilibj.livewindow.LiveWindowSendable;\nimport edu.wpi.first.wpilibj.parsing.IDeviceController;\nimport edu.wpi.first.wpilibj.tables.ITable;\nimport edu.wpi.first.wpilibj.tables.ITableListener;\nimport edu.wpi.first.wpilibj.util.AllocationException;\nimport edu.wpi.first.wpilibj.util.CheckedAllocationException;\n\n/**\n * Class for VEX Robotics Spike style relay outputs.\n * Relays are intended to be connected to Spikes or similar relays. The relay channels controls\n * a pair of pins that are either both off, one on, the other on, or both on. This translates into\n * two Spike outputs at 0v, one at 12v and one at 0v, one at 0v and the other at 12v, or two\n * Spike outputs at 12V. This allows off, full forward, or full reverse control of motors without\n * variable speed. It also allows the two channels (forward and reverse) to be used independently\n * for something that does not care about voltage polarity (like a solenoid).\n */\npublic class Relay extends SensorBase implements IDeviceController, LiveWindowSendable {\n\n /**\n * This class represents errors in trying to set relay values contradictory\n * to the direction to which the relay is set.\n */\n public class InvalidValueException extends RuntimeException {\n\n /**\n * Create a new exception with the given message\n * @param message the message to pass with the exception\n */\n public InvalidValueException(String message) {\n super(message);\n }\n }\n\n /**\n * The state to drive a Relay to.\n */\n public static class Value {\n\n /**\n * The integer value representing this enumeration\n */\n public final int value;\n static final int kOff_val = 0;\n static final int kOn_val = 1;\n static final int kForward_val = 2;\n static final int kReverse_val = 3;\n /**\n * value: off\n */\n public static final Value kOff = new Value(kOff_val);\n /**\n * value: on for relays with defined direction\n */\n public static final Value kOn = new Value(kOn_val);\n /**\n * value: forward\n */\n public static final Value kForward = new Value(kForward_val);\n /**\n * value: reverse\n */\n public static final Value kReverse = new Value(kReverse_val);\n\n private Value(int value) {\n this.value = value;\n }\n }\n\n /**\n * The Direction(s) that a relay is configured to operate in.\n */\n public static class Direction {\n\n /**\n * The integer value representing this enumeration\n */\n public final int value;\n static final int kBoth_val = 0;\n static final int kForward_val = 1;\n static final int kReverse_val = 2;\n /**\n * direction: both directions are valid\n */\n public static final Direction kBoth = new Direction(kBoth_val);\n /**\n * direction: Only forward is valid\n */\n public static final Direction kForward = new Direction(kForward_val);\n /**\n * direction: only reverse is valid\n */\n public static final Direction kReverse = new Direction(kReverse_val);\n\n private Direction(int value) {\n this.value = value;\n }\n }\n private int m_channel;\n private Direction m_direction;\n private DigitalModule m_module;\n private static Resource relayChannels = new Resource(tDIO.kNumSystems * kRelayChannels * 2);\n\n /**\n * Common relay initialization method.\n * This code is common to all Relay constructors and initializes the relay and reserves\n * all resources that need to be locked. Initially the relay is set to both lines at 0v.\n * @param moduleNumber The number of the digital module to use.\n */\n private void initRelay(final int moduleNumber) {\n SensorBase.checkRelayModule(moduleNumber);\n SensorBase.checkRelayChannel(m_channel);\n try {\n if (m_direction == Direction.kBoth || m_direction == Direction.kForward) {\n relayChannels.allocate(((moduleNumber - 1) * kRelayChannels + m_channel - 1) * 2);\n UsageReporting.report(UsageReporting.kResourceType_Relay, m_channel, moduleNumber-1);\n }\n if (m_direction == Direction.kBoth || m_direction == Direction.kReverse) {\n relayChannels.allocate(((moduleNumber - 1) * kRelayChannels + m_channel - 1) * 2 + 1);\n UsageReporting.report(UsageReporting.kResourceType_Relay, m_channel+128, moduleNumber-1);\n }\n } catch (CheckedAllocationException e) {\n throw new AllocationException(\"Relay channel \" + m_channel + \" on module \" + moduleNumber + \" is already allocated\");\n }\n m_module = DigitalModule.getInstance(moduleNumber);\n m_module.setRelayForward(m_channel, false);\n m_module.setRelayReverse(m_channel, false);\n LiveWindow.addActuator(\"Relay\", moduleNumber, m_channel, this);\n }\n\n\n /**\n * Relay constructor given the module and the channel.\n * @param moduleNumber The number of the digital module to use.\n * @param channel The channel number within the module for this relay.\n * @param direction The direction that the Relay object will control.\n */\n public Relay(final int moduleNumber, final int channel, Direction direction) {\n if (direction == null)\n throw new NullPointerException(\"Null Direction was given\");\n m_channel = channel;\n m_direction = direction;\n initRelay(moduleNumber);\n }\n\n /**\n * Relay constructor given a channel only where the default digital module is used.\n * @param channel The channel number within the default module for this relay.\n * @param direction The direction that the Relay object will control.\n */\n public Relay(final int channel, Direction direction) {\n if (direction == null)\n throw new NullPointerException(\"Null Direction was given\");\n m_channel = channel;", "answers": [" m_direction = direction;"], "length": 781, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "be588d38-e45d-4f09-a094-14d09785f89c", "reasoning": "In the second Relay constructor (channel only, default module), after assigning the channel to the member variable, the next logical step is to store the provided direction in the m_direction field before initializing the hardware. Therefore the next line should assign the direction argument to m_direction.", "reasoning_model_answer": "m_direction = direction;", "assistant_with_reasoning": "\nIn the second Relay constructor (channel only, default module), after assigning the channel to the member variable, the next logical step is to store the provided direction in the m_direction field before initializing the hardware. Therefore the next line should assign the direction argument to m_direction.\n\nm_direction = direction;", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.337, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 6839, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "m_direction = direction;", "score": 0.86, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "#region Copyright notice and license\n\n// Copyright 2015, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n// * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n// * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n// * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#endregion\n\nusing System;\nusing System.Collections.Concurrent;\nusing System.Diagnostics;\nusing System.IO;\nusing System.Reflection;\nusing System.Runtime.InteropServices;\nusing System.Threading;\n\nusing Grpc.Core.Logging;\nusing Grpc.Core.Utils;\n\nnamespace Grpc.Core.Internal\n{\n /// \n /// Provides access to all native methods provided by NativeExtension.\n /// An extra level of indirection is added to P/Invoke calls to allow intelligent loading\n /// of the right configuration of the native extension based on current platform, architecture etc.\n /// \n internal class NativeMethods\n {\n #region Native methods\n\n public readonly Delegates.grpcsharp_init_delegate grpcsharp_init;\n public readonly Delegates.grpcsharp_shutdown_delegate grpcsharp_shutdown;\n public readonly Delegates.grpcsharp_version_string_delegate grpcsharp_version_string;\n\n public readonly Delegates.grpcsharp_batch_context_create_delegate grpcsharp_batch_context_create;\n public readonly Delegates.grpcsharp_batch_context_recv_initial_metadata_delegate grpcsharp_batch_context_recv_initial_metadata;\n public readonly Delegates.grpcsharp_batch_context_recv_message_length_delegate grpcsharp_batch_context_recv_message_length;\n public readonly Delegates.grpcsharp_batch_context_recv_message_to_buffer_delegate grpcsharp_batch_context_recv_message_to_buffer;\n public readonly Delegates.grpcsharp_batch_context_recv_status_on_client_status_delegate grpcsharp_batch_context_recv_status_on_client_status;\n public readonly Delegates.grpcsharp_batch_context_recv_status_on_client_details_delegate grpcsharp_batch_context_recv_status_on_client_details;\n public readonly Delegates.grpcsharp_batch_context_recv_status_on_client_trailing_metadata_delegate grpcsharp_batch_context_recv_status_on_client_trailing_metadata;\n public readonly Delegates.grpcsharp_batch_context_server_rpc_new_call_delegate grpcsharp_batch_context_server_rpc_new_call;\n public readonly Delegates.grpcsharp_batch_context_server_rpc_new_method_delegate grpcsharp_batch_context_server_rpc_new_method;\n public readonly Delegates.grpcsharp_batch_context_server_rpc_new_host_delegate grpcsharp_batch_context_server_rpc_new_host;\n public readonly Delegates.grpcsharp_batch_context_server_rpc_new_deadline_delegate grpcsharp_batch_context_server_rpc_new_deadline;\n public readonly Delegates.grpcsharp_batch_context_server_rpc_new_request_metadata_delegate grpcsharp_batch_context_server_rpc_new_request_metadata;\n public readonly Delegates.grpcsharp_batch_context_recv_close_on_server_cancelled_delegate grpcsharp_batch_context_recv_close_on_server_cancelled;\n public readonly Delegates.grpcsharp_batch_context_destroy_delegate grpcsharp_batch_context_destroy;\n\n public readonly Delegates.grpcsharp_composite_call_credentials_create_delegate grpcsharp_composite_call_credentials_create;\n public readonly Delegates.grpcsharp_call_credentials_release_delegate grpcsharp_call_credentials_release;\n\n public readonly Delegates.grpcsharp_call_cancel_delegate grpcsharp_call_cancel;\n public readonly Delegates.grpcsharp_call_cancel_with_status_delegate grpcsharp_call_cancel_with_status;\n public readonly Delegates.grpcsharp_call_start_unary_delegate grpcsharp_call_start_unary;\n public readonly Delegates.grpcsharp_call_start_client_streaming_delegate grpcsharp_call_start_client_streaming;\n public readonly Delegates.grpcsharp_call_start_server_streaming_delegate grpcsharp_call_start_server_streaming;\n public readonly Delegates.grpcsharp_call_start_duplex_streaming_delegate grpcsharp_call_start_duplex_streaming;\n public readonly Delegates.grpcsharp_call_send_message_delegate grpcsharp_call_send_message;\n public readonly Delegates.grpcsharp_call_send_close_from_client_delegate grpcsharp_call_send_close_from_client;\n public readonly Delegates.grpcsharp_call_send_status_from_server_delegate grpcsharp_call_send_status_from_server;\n public readonly Delegates.grpcsharp_call_recv_message_delegate grpcsharp_call_recv_message;\n public readonly Delegates.grpcsharp_call_recv_initial_metadata_delegate grpcsharp_call_recv_initial_metadata;\n public readonly Delegates.grpcsharp_call_start_serverside_delegate grpcsharp_call_start_serverside;\n public readonly Delegates.grpcsharp_call_send_initial_metadata_delegate grpcsharp_call_send_initial_metadata;\n public readonly Delegates.grpcsharp_call_set_credentials_delegate grpcsharp_call_set_credentials;\n public readonly Delegates.grpcsharp_call_get_peer_delegate grpcsharp_call_get_peer;\n public readonly Delegates.grpcsharp_call_destroy_delegate grpcsharp_call_destroy;\n\n public readonly Delegates.grpcsharp_channel_args_create_delegate grpcsharp_channel_args_create;\n public readonly Delegates.grpcsharp_channel_args_set_string_delegate grpcsharp_channel_args_set_string;\n public readonly Delegates.grpcsharp_channel_args_set_integer_delegate grpcsharp_channel_args_set_integer;\n public readonly Delegates.grpcsharp_channel_args_destroy_delegate grpcsharp_channel_args_destroy;\n\n public readonly Delegates.grpcsharp_override_default_ssl_roots grpcsharp_override_default_ssl_roots;\n public readonly Delegates.grpcsharp_ssl_credentials_create_delegate grpcsharp_ssl_credentials_create;\n public readonly Delegates.grpcsharp_composite_channel_credentials_create_delegate grpcsharp_composite_channel_credentials_create;\n public readonly Delegates.grpcsharp_channel_credentials_release_delegate grpcsharp_channel_credentials_release;\n\n public readonly Delegates.grpcsharp_insecure_channel_create_delegate grpcsharp_insecure_channel_create;\n public readonly Delegates.grpcsharp_secure_channel_create_delegate grpcsharp_secure_channel_create;\n public readonly Delegates.grpcsharp_channel_create_call_delegate grpcsharp_channel_create_call;\n public readonly Delegates.grpcsharp_channel_check_connectivity_state_delegate grpcsharp_channel_check_connectivity_state;\n public readonly Delegates.grpcsharp_channel_watch_connectivity_state_delegate grpcsharp_channel_watch_connectivity_state;\n public readonly Delegates.grpcsharp_channel_get_target_delegate grpcsharp_channel_get_target;\n public readonly Delegates.grpcsharp_channel_destroy_delegate grpcsharp_channel_destroy;\n\n public readonly Delegates.grpcsharp_sizeof_grpc_event_delegate grpcsharp_sizeof_grpc_event;\n\n public readonly Delegates.grpcsharp_completion_queue_create_delegate grpcsharp_completion_queue_create;\n public readonly Delegates.grpcsharp_completion_queue_shutdown_delegate grpcsharp_completion_queue_shutdown;\n public readonly Delegates.grpcsharp_completion_queue_next_delegate grpcsharp_completion_queue_next;\n public readonly Delegates.grpcsharp_completion_queue_pluck_delegate grpcsharp_completion_queue_pluck;\n public readonly Delegates.grpcsharp_completion_queue_destroy_delegate grpcsharp_completion_queue_destroy;\n\n public readonly Delegates.gprsharp_free_delegate gprsharp_free;\n\n public readonly Delegates.grpcsharp_metadata_array_create_delegate grpcsharp_metadata_array_create;\n public readonly Delegates.grpcsharp_metadata_array_add_delegate grpcsharp_metadata_array_add;\n public readonly Delegates.grpcsharp_metadata_array_count_delegate grpcsharp_metadata_array_count;\n public readonly Delegates.grpcsharp_metadata_array_get_key_delegate grpcsharp_metadata_array_get_key;\n public readonly Delegates.grpcsharp_metadata_array_get_value_delegate grpcsharp_metadata_array_get_value;\n public readonly Delegates.grpcsharp_metadata_array_get_value_length_delegate grpcsharp_metadata_array_get_value_length;\n public readonly Delegates.grpcsharp_metadata_array_destroy_full_delegate grpcsharp_metadata_array_destroy_full;\n\n public readonly Delegates.grpcsharp_redirect_log_delegate grpcsharp_redirect_log;\n\n public readonly Delegates.grpcsharp_metadata_credentials_create_from_plugin_delegate grpcsharp_metadata_credentials_create_from_plugin;\n public readonly Delegates.grpcsharp_metadata_credentials_notify_from_plugin_delegate grpcsharp_metadata_credentials_notify_from_plugin;\n\n public readonly Delegates.grpcsharp_ssl_server_credentials_create_delegate grpcsharp_ssl_server_credentials_create;\n public readonly Delegates.grpcsharp_server_credentials_release_delegate grpcsharp_server_credentials_release;\n\n public readonly Delegates.grpcsharp_server_create_delegate grpcsharp_server_create;\n public readonly Delegates.grpcsharp_server_register_completion_queue_delegate grpcsharp_server_register_completion_queue;\n public readonly Delegates.grpcsharp_server_add_insecure_http2_port_delegate grpcsharp_server_add_insecure_http2_port;\n public readonly Delegates.grpcsharp_server_add_secure_http2_port_delegate grpcsharp_server_add_secure_http2_port;\n public readonly Delegates.grpcsharp_server_start_delegate grpcsharp_server_start;\n public readonly Delegates.grpcsharp_server_request_call_delegate grpcsharp_server_request_call;\n public readonly Delegates.grpcsharp_server_cancel_all_calls_delegate grpcsharp_server_cancel_all_calls;\n public readonly Delegates.grpcsharp_server_shutdown_and_notify_callback_delegate grpcsharp_server_shutdown_and_notify_callback;\n public readonly Delegates.grpcsharp_server_destroy_delegate grpcsharp_server_destroy;\n\n public readonly Delegates.gprsharp_now_delegate gprsharp_now;\n public readonly Delegates.gprsharp_inf_future_delegate gprsharp_inf_future;\n public readonly Delegates.gprsharp_inf_past_delegate gprsharp_inf_past;\n public readonly Delegates.gprsharp_convert_clock_type_delegate gprsharp_convert_clock_type;\n public readonly Delegates.gprsharp_sizeof_timespec_delegate gprsharp_sizeof_timespec;\n\n public readonly Delegates.grpcsharp_test_callback_delegate grpcsharp_test_callback;\n public readonly Delegates.grpcsharp_test_nop_delegate grpcsharp_test_nop;\n\n #endregion\n\n public NativeMethods(UnmanagedLibrary library)\n {\n if (PlatformApis.IsLinux || PlatformApis.IsMacOSX)\n {\n this.grpcsharp_init = GetMethodDelegate(library);\n this.grpcsharp_shutdown = GetMethodDelegate(library);\n this.grpcsharp_version_string = GetMethodDelegate(library);\n\n this.grpcsharp_batch_context_create = GetMethodDelegate(library);\n this.grpcsharp_batch_context_recv_initial_metadata = GetMethodDelegate(library);\n this.grpcsharp_batch_context_recv_message_length = GetMethodDelegate(library);\n this.grpcsharp_batch_context_recv_message_to_buffer = GetMethodDelegate(library);\n this.grpcsharp_batch_context_recv_status_on_client_status = GetMethodDelegate(library);\n this.grpcsharp_batch_context_recv_status_on_client_details = GetMethodDelegate(library);\n this.grpcsharp_batch_context_recv_status_on_client_trailing_metadata = GetMethodDelegate(library);\n this.grpcsharp_batch_context_server_rpc_new_call = GetMethodDelegate(library);\n this.grpcsharp_batch_context_server_rpc_new_method = GetMethodDelegate(library);\n this.grpcsharp_batch_context_server_rpc_new_host = GetMethodDelegate(library);\n this.grpcsharp_batch_context_server_rpc_new_deadline = GetMethodDelegate(library);\n this.grpcsharp_batch_context_server_rpc_new_request_metadata = GetMethodDelegate(library);\n this.grpcsharp_batch_context_recv_close_on_server_cancelled = GetMethodDelegate(library);\n this.grpcsharp_batch_context_destroy = GetMethodDelegate(library);\n\n this.grpcsharp_composite_call_credentials_create = GetMethodDelegate(library);\n this.grpcsharp_call_credentials_release = GetMethodDelegate(library);\n\n this.grpcsharp_call_cancel = GetMethodDelegate(library);\n this.grpcsharp_call_cancel_with_status = GetMethodDelegate(library);\n this.grpcsharp_call_start_unary = GetMethodDelegate(library);\n this.grpcsharp_call_start_client_streaming = GetMethodDelegate(library);\n this.grpcsharp_call_start_server_streaming = GetMethodDelegate(library);\n this.grpcsharp_call_start_duplex_streaming = GetMethodDelegate(library);\n this.grpcsharp_call_send_message = GetMethodDelegate(library);\n this.grpcsharp_call_send_close_from_client = GetMethodDelegate(library);\n this.grpcsharp_call_send_status_from_server = GetMethodDelegate(library);\n this.grpcsharp_call_recv_message = GetMethodDelegate(library);\n this.grpcsharp_call_recv_initial_metadata = GetMethodDelegate(library);\n this.grpcsharp_call_start_serverside = GetMethodDelegate(library);\n this.grpcsharp_call_send_initial_metadata = GetMethodDelegate(library);\n this.grpcsharp_call_set_credentials = GetMethodDelegate(library);\n this.grpcsharp_call_get_peer = GetMethodDelegate(library);\n this.grpcsharp_call_destroy = GetMethodDelegate(library);\n\n this.grpcsharp_channel_args_create = GetMethodDelegate(library);\n this.grpcsharp_channel_args_set_string = GetMethodDelegate(library);\n this.grpcsharp_channel_args_set_integer = GetMethodDelegate(library);\n this.grpcsharp_channel_args_destroy = GetMethodDelegate(library);\n\n this.grpcsharp_override_default_ssl_roots = GetMethodDelegate(library);\n this.grpcsharp_ssl_credentials_create = GetMethodDelegate(library);\n this.grpcsharp_composite_channel_credentials_create = GetMethodDelegate(library);\n this.grpcsharp_channel_credentials_release = GetMethodDelegate(library);\n\n this.grpcsharp_insecure_channel_create = GetMethodDelegate(library);\n this.grpcsharp_secure_channel_create = GetMethodDelegate(library);\n this.grpcsharp_channel_create_call = GetMethodDelegate(library);\n this.grpcsharp_channel_check_connectivity_state = GetMethodDelegate(library);\n this.grpcsharp_channel_watch_connectivity_state = GetMethodDelegate(library);\n this.grpcsharp_channel_get_target = GetMethodDelegate(library);\n this.grpcsharp_channel_destroy = GetMethodDelegate(library);\n\n this.grpcsharp_sizeof_grpc_event = GetMethodDelegate(library);\n\n this.grpcsharp_completion_queue_create = GetMethodDelegate(library);\n this.grpcsharp_completion_queue_shutdown = GetMethodDelegate(library);\n this.grpcsharp_completion_queue_next = GetMethodDelegate(library);\n this.grpcsharp_completion_queue_pluck = GetMethodDelegate(library);\n this.grpcsharp_completion_queue_destroy = GetMethodDelegate(library);\n", "answers": [" this.gprsharp_free = GetMethodDelegate(library);"], "length": 851, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "b567c999-c56f-47be-8bf9-442f43fb140a", "reasoning": "The constructor is assigning each delegate field using GetMethodDelegate. After the last shown assignment (grpcsharp_completion_queue_destroy), the next field in the class definition is gprsharp_free, so the next line should assign this.gprsharp_free using GetMethodDelegate with the appropriate delegate type.", "reasoning_model_answer": "this.gprsharp_free = GetMethodDelegate(library);", "assistant_with_reasoning": "\nThe constructor is assigning each delegate field using GetMethodDelegate. After the last shown assignment (grpcsharp_completion_queue_destroy), the next field in the class definition is gprsharp_free, so the next line should assign this.gprsharp_free using GetMethodDelegate with the appropriate delegate type.\n\nthis.gprsharp_free = GetMethodDelegate(library);", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.288, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 20191, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "this.gprsharp_free = GetMethodDelegate(library);", "score": 0.91, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "#!/usr/bin/env python\n# Copyright (c) 2012 The Chromium Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style license that can be\n# found in the LICENSE file.\n\nimport fnmatch\nimport glob\nimport optparse\nimport os\nimport posixpath\nimport shutil\nimport stat\nimport sys\nimport time\nimport zipfile\n\nif sys.version_info < (2, 6, 0):\n sys.stderr.write(\"python 2.6 or later is required run this script\\n\")\n sys.exit(1)\n\n\ndef IncludeFiles(filters, files):\n \"\"\"Filter files based on inclusion lists\n\n Return a list of files which match and of the Unix shell-style wildcards\n provided, or return all the files if no filter is provided.\"\"\"\n if not filters:\n return files\n match = set()\n for file_filter in filters:\n match |= set(fnmatch.filter(files, file_filter))\n return [name for name in files if name in match]\n\n\ndef ExcludeFiles(filters, files):\n \"\"\"Filter files based on exclusions lists\n\n Return a list of files which do not match any of the Unix shell-style\n wildcards provided, or return all the files if no filter is provided.\"\"\"\n if not filters:\n return files\n match = set()\n for file_filter in filters:\n excludes = set(fnmatch.filter(files, file_filter))\n match |= excludes\n return [name for name in files if name not in match]\n\n\ndef CopyPath(options, src, dst):\n \"\"\"CopyPath from src to dst\n\n Copy a fully specified src to a fully specified dst. If src and dst are\n both files, the dst file is removed first to prevent error. If and include\n or exclude list are provided, the destination is first matched against that\n filter.\"\"\"\n if options.includes:\n if not IncludeFiles(options.includes, [src]):\n return\n\n if options.excludes:\n if not ExcludeFiles(options.excludes, [src]):\n return\n\n if options.verbose:\n print 'cp %s %s' % (src, dst)\n\n # If the source is a single file, copy it individually\n if os.path.isfile(src):\n # We can not copy over a directory with a file.\n if os.path.exists(dst):\n if not os.path.isfile(dst):\n msg = \"cp: cannot overwrite non-file '%s' with file.\" % dst\n raise OSError(msg)\n # If the destination exists as a file, remove it before copying to avoid\n # 'readonly' issues.\n os.remove(dst)\n\n # Now copy to the non-existent fully qualified target\n shutil.copy(src, dst)\n return\n\n # Otherwise it's a directory, ignore it unless allowed\n if os.path.isdir(src):\n if not options.recursive:\n print \"cp: omitting directory '%s'\" % src\n return\n\n # We can not copy over a file with a directory.\n if os.path.exists(dst):\n if not os.path.isdir(dst):\n msg = \"cp: cannot overwrite non-directory '%s' with directory.\" % dst\n raise OSError(msg)\n else:\n # if it didn't exist, create the directory\n os.makedirs(dst)\n\n # Now copy all members\n for filename in os.listdir(src):\n srcfile = os.path.join(src, filename)\n dstfile = os.path.join(dst, filename)\n CopyPath(options, srcfile, dstfile)\n return\n\n\ndef Copy(args):\n \"\"\"A Unix cp style copy.\n\n Copies multiple sources to a single destination using the normal cp\n semantics. In addition, it support inclusion and exclusion filters which\n allows the copy to skip certain types of files.\"\"\"\n parser = optparse.OptionParser(usage='usage: cp [Options] souces... dest')\n parser.add_option(\n '-R', '-r', '--recursive', dest='recursive', action='store_true',\n default=False,\n help='copy directories recursively.')\n parser.add_option(\n '-v', '--verbose', dest='verbose', action='store_true',\n default=False,\n help='verbose output.')\n parser.add_option(\n '--include', dest='includes', action='append', default=[],\n help='include files matching this expression.')\n parser.add_option(\n '--exclude', dest='excludes', action='append', default=[],\n help='exclude files matching this expression.')\n options, files = parser.parse_args(args)\n if len(files) < 2:\n parser.error('ERROR: expecting SOURCE(s) and DEST.')\n\n srcs = files[:-1]\n dst = files[-1]\n\n src_list = []\n for src in srcs:\n files = glob.glob(src)\n if len(files) == 0:\n raise OSError('cp: no such file or directory: ' + src)\n if files:\n src_list.extend(files)\n\n for src in src_list:\n # If the destination is a directory, then append the basename of the src\n # to the destination.\n if os.path.isdir(dst):\n CopyPath(options, src, os.path.join(dst, os.path.basename(src)))\n else:\n CopyPath(options, src, dst)\n\n\ndef Mkdir(args):\n \"\"\"A Unix style mkdir\"\"\"\n parser = optparse.OptionParser(usage='usage: mkdir [Options] DIRECTORY...')\n parser.add_option(\n '-p', '--parents', dest='parents', action='store_true',\n default=False,\n help='ignore existing parents, create parents as needed.')\n parser.add_option(\n '-v', '--verbose', dest='verbose', action='store_true',\n default=False,\n help='verbose output.')\n\n options, dsts = parser.parse_args(args)\n if len(dsts) < 1:\n parser.error('ERROR: expecting DIRECTORY...')\n\n for dst in dsts:\n if options.verbose:\n print 'mkdir ' + dst\n try:\n os.makedirs(dst)\n except OSError:\n if os.path.isdir(dst):\n if options.parents:\n continue\n raise OSError('mkdir: Already exsists: ' + dst)\n else:\n raise OSError('mkdir: Failed to create: ' + dst)\n return 0\n\n\ndef MovePath(options, src, dst):\n \"\"\"MovePath from src to dst\n\n Moves the src to the dst much like the Unix style mv command, except it\n only handles one source at a time. Because of possible temporary failures\n do to locks (such as anti-virus software on Windows), the function will retry\n up to five times.\"\"\"\n # if the destination is not an existing directory, then overwrite it\n if os.path.isdir(dst):\n dst = os.path.join(dst, os.path.basename(src))\n\n # If the destination exists, the remove it\n if os.path.exists(dst):\n if options.force:\n Remove(['-vfr', dst])\n if os.path.exists(dst):\n raise OSError('mv: FAILED TO REMOVE ' + dst)\n else:\n raise OSError('mv: already exists ' + dst)\n for _ in range(5):\n try:\n os.rename(src, dst)\n return\n except OSError as error:\n print 'Failed on %s with %s, retrying' % (src, error)\n time.sleep(5)\n print 'Gave up.'\n raise OSError('mv: ' + error)\n\n\ndef Move(args):\n parser = optparse.OptionParser(usage='usage: mv [Options] souces... dest')\n parser.add_option(\n '-v', '--verbose', dest='verbose', action='store_true',\n default=False,\n help='verbose output.')\n parser.add_option(\n '-f', '--force', dest='force', action='store_true',\n default=False,\n help='force, do not error it files already exist.')", "answers": [" options, files = parser.parse_args(args)"], "length": 833, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "30d673c5-7d72-4414-af97-4fbc5cf44d57", "reasoning": "The Move function is being defined. After setting up the OptionParser and adding options, the next logical step is to parse the command-line arguments. This mirrors the pattern used in the earlier Copy and Mkdir functions, where they call parser.parse_args(args) to obtain options and file arguments.", "reasoning_model_answer": "options, files = parser.parse_args(args)", "assistant_with_reasoning": "\nThe Move function is being defined. After setting up the OptionParser and adding options, the next logical step is to parse the command-line arguments. This mirrors the pattern used in the earlier Copy and Mkdir functions, where they call parser.parse_args(args) to obtain options and file arguments.\n\noptions, files = parser.parse_args(args)", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.453, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 6852, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "options, files = parser.parse_args(args)", "score": 0.98, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\nusing Xunit;\n\nnamespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclassregmeth.genclassregmeth\n{\n using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclassregmeth.genclassregmeth;\n using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass001.genclass001;\n using System;\n using System.Collections.Generic;\n\n public class C\n {\n }\n\n public interface I\n {\n }\n\n public class MyClass\n {\n public int Field = 0;\n }\n\n public struct MyStruct\n {\n public int Number;\n }\n\n public enum MyEnum\n {\n First = 1,\n Second = 2,\n Third = 3\n }\n\n public class MemberClass\n {\n #region Instance methods\n public bool Method_ReturnBool()\n {\n return false;\n }\n\n public T Method_ReturnsT()\n {\n return default(T);\n }\n\n public T Method_ReturnsT(T t)\n {\n return t;\n }\n\n public T Method_ReturnsT(out T t)\n {\n t = default(T);\n return t;\n }\n\n public T Method_ReturnsT(ref T t, T tt)\n {\n t = default(T);\n return t;\n }\n\n public T Method_ReturnsT(params T[] t)\n {\n return default(T);\n }\n\n public T Method_ReturnsT(float x, T t)\n {\n return default(T);\n }\n\n public int Method_ReturnsInt(T t)\n {\n return 1;\n }\n\n public float Method_ReturnsFloat(T t, dynamic d)\n {\n return 3.4f;\n }\n\n public float Method_ReturnsFloat(T t, dynamic d, ref decimal dec)\n {\n dec = 3m;\n return 3.4f;\n }\n\n public dynamic Method_ReturnsDynamic(T t)\n {\n return t;\n }\n\n public dynamic Method_ReturnsDynamic(T t, dynamic d)\n {\n return t;\n }\n\n public dynamic Method_ReturnsDynamic(T t, int x, dynamic d)\n {\n return t;\n }\n\n // Multiple params\n // Constraints\n // Nesting\n #endregion\n #region Static methods\n public static bool? StaticMethod_ReturnBoolNullable()\n {\n return (bool?)false;\n }\n #endregion\n }\n\n public class MemberClassMultipleParams\n {\n public T Method_ReturnsT(V v, U u)\n {\n return default(T);\n }\n }\n\n public class MemberClassWithClassConstraint\n where T : class\n {\n public int Method_ReturnsInt()\n {\n return 1;\n }\n\n public T Method_ReturnsT(decimal dec, dynamic d)\n {\n return null;\n }\n }\n\n public class MemberClassWithNewConstraint\n where T : new()\n {\n public T Method_ReturnsT()\n {\n return new T();\n }\n\n public dynamic Method_ReturnsDynamic(T t)\n {\n return new T();\n }\n }\n\n public class MemberClassWithAnotherTypeConstraint\n where T : U\n {\n public U Method_ReturnsU(dynamic d)\n {\n return default(U);\n }\n\n public dynamic Method_ReturnsDynamic(int x, U u, dynamic d)\n {\n return default(T);\n }\n }\n\n #region Negative tests - you should not be able to construct this with a dynamic object\n public class MemberClassWithUDClassConstraint\n where T : C, new()\n {\n public C Method_ReturnsC()\n {\n return new T();\n }\n }\n\n public class MemberClassWithStructConstraint\n where T : struct\n {\n public dynamic Method_ReturnsDynamic(int x)\n {\n return x;\n }\n }\n\n public class MemberClassWithInterfaceConstraint\n where T : I\n {\n public dynamic Method_ReturnsDynamic(int x, T v)\n {\n return default(T);\n }\n }\n #endregion\n}\n\n\n\nnamespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass001.genclass001\n{\n using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclassregmeth.genclassregmeth;\n using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass001.genclass001;\n // Tests generic class regular method used in regular method body.\n // \n // \n // \n //\n // \n using System;\n\n public class Test\n {\n [Fact]\n public static void DynamicCSharpRunTest()\n {\n Assert.Equal(0, MainMethod());\n }\n\n public static int MainMethod()\n {\n Test t = new Test();\n if (t.TestMethod() == true)\n return 1;\n return 0;\n }\n\n public bool TestMethod()\n {\n dynamic mc = new MemberClass();\n return (bool)mc.Method_ReturnBool();\n }\n }\n //\n}\n\n\n\nnamespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass002.genclass002\n{\n using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclassregmeth.genclassregmeth;\n using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass002.genclass002;\n // Tests generic class regular method used in argements of method invocation.\n // \n // \n // \n //\n // \n using System;\n\n public class Test\n {\n [Fact]\n public static void DynamicCSharpRunTest()\n {\n Assert.Equal(0, MainMethod());\n }\n\n public static int MainMethod()\n {\n Test t = new Test();\n dynamic mc1 = new MemberClass();\n int result1 = t.TestMethod((int)mc1.Method_ReturnsT());\n dynamic mc2 = new MemberClass();\n int result2 = Test.TestMethod((string)mc2.Method_ReturnsT());\n if (result1 == 0 && result2 == 0)\n return 0;\n else\n return 1;\n }\n\n public int TestMethod(int i)\n {\n if (i == default(int))\n {\n return 0;\n }\n else\n {\n return 1;\n }\n }\n\n public static int TestMethod(string s)\n {\n if (s == default(string))\n {\n return 0;\n }\n else\n {\n return 1;\n }\n }\n }\n //\n}\n\n\n\nnamespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass003.genclass003\n{\n using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclassregmeth.genclassregmeth;\n using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass003.genclass003;\n // Tests generic class regular method used in static variable.\n // \n // \n // \n //\n // \n using System;\n\n public class Test\n {\n private static dynamic s_mc = new MemberClass();\n private static float s_loc = (float)s_mc.Method_ReturnsFloat(null, 1);\n [Fact]\n public static void DynamicCSharpRunTest()\n {\n Assert.Equal(0, MainMethod());\n }\n\n public static int MainMethod()\n {\n if (s_loc != 3.4f)\n return 1;\n return 0;\n }\n }\n //\n}\n\n\n\nnamespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass005.genclass005\n{\n using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclassregmeth.genclassregmeth;\n using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass005.genclass005;\n // Tests generic class regular method used in unsafe.\n // \n // \n // \n //\n // \n //using System;\n //[TestClass]public class Test\n //{\n //[Test][Priority(Priority.Priority1)]public void DynamicCSharpRunTest(){Assert.AreEqual(0, MainMethod());} public static unsafe int MainMethod()\n //{\n //dynamic dy = new MemberClass();\n //int value = 1;\n //int* valuePtr = &value;\n //int result = dy.Method_ReturnsT(out *valuePtr);\n //if (result == 0 && value == 0)\n //return 0;\n //return 1;\n //}\n //}\n //\n}\n\n\n\nnamespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass006.genclass006\n{\n using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclassregmeth.genclassregmeth;\n using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass006.genclass006;\n // Tests generic class regular method used in generic method body.\n // \n // \n // \n //\n // \n using System;\n\n public class Test\n {\n \n public static void DynamicCSharpRunTest()\n {", "answers": [" Assert.Equal(0, MainMethod());"], "length": 824, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "668eccac-6e22-4ed0-b00e-0771dc314bc2", "reasoning": "In the previous test files within this suite, the DynamicCSharpRunTest method simply asserts that a helper method (usually MainMethod) returns 0, indicating success. The pattern is consistent across the earlier namespaces. Since this file follows the same structure, the next line inside DynamicCSharpRunTest should be the assertion calling MainMethod, i.e., Assert.Equal(0, MainMethod());", "reasoning_model_answer": "Assert.Equal(0, MainMethod());", "assistant_with_reasoning": "\nIn the previous test files within this suite, the DynamicCSharpRunTest method simply asserts that a helper method (usually MainMethod) returns 0, indicating success. The pattern is consistent across the earlier namespaces. Since this file follows the same structure, the next line inside DynamicCSharpRunTest should be the assertion calling MainMethod, i.e., Assert.Equal(0, MainMethod());\n\nAssert.Equal(0, MainMethod());", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 5.353, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 9945, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "Assert.Equal(0, MainMethod());", "score": 0.83, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "# -*- coding: utf-8 -*-\n#\n# Copyright 2018 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"Unit tests.\"\"\"\n\nimport mock\nimport pytest\n\nfrom google.rpc import status_pb2\n\nfrom google.cloud import bigtable_admin_v2\nfrom google.cloud.bigtable_admin_v2 import enums\nfrom google.cloud.bigtable_admin_v2.proto import bigtable_instance_admin_pb2\nfrom google.cloud.bigtable_admin_v2.proto import instance_pb2\nfrom google.iam.v1 import iam_policy_pb2\nfrom google.iam.v1 import policy_pb2\nfrom google.longrunning import operations_pb2\nfrom google.protobuf import empty_pb2\nfrom google.protobuf import field_mask_pb2\n\n\nclass MultiCallableStub(object):\n \"\"\"Stub for the grpc.UnaryUnaryMultiCallable interface.\"\"\"\n\n def __init__(self, method, channel_stub):\n self.method = method\n self.channel_stub = channel_stub\n\n def __call__(self, request, timeout=None, metadata=None, credentials=None):\n self.channel_stub.requests.append((self.method, request))\n\n response = None\n if self.channel_stub.responses:\n response = self.channel_stub.responses.pop()\n\n if isinstance(response, Exception):\n raise response\n\n if response:\n return response\n\n\nclass ChannelStub(object):\n \"\"\"Stub for the grpc.Channel interface.\"\"\"\n\n def __init__(self, responses=[]):\n self.responses = responses\n self.requests = []\n\n def unary_unary(self,\n method,\n request_serializer=None,\n response_deserializer=None):\n return MultiCallableStub(method, self)\n\n\nclass CustomException(Exception):\n pass\n\n\nclass TestBigtableInstanceAdminClient(object):\n def test_create_instance(self):\n # Setup Expected Response\n name = 'name3373707'\n display_name = 'displayName1615086568'\n expected_response = {'name': name, 'display_name': display_name}\n expected_response = instance_pb2.Instance(**expected_response)\n operation = operations_pb2.Operation(\n name='operations/test_create_instance', done=True)\n operation.response.Pack(expected_response)\n\n # Mock the API response\n channel = ChannelStub(responses=[operation])\n patch = mock.patch('google.api_core.grpc_helpers.create_channel')\n with patch as create_channel:\n create_channel.return_value = channel\n client = bigtable_admin_v2.BigtableInstanceAdminClient()\n\n # Setup Request\n parent = client.project_path('[PROJECT]')\n instance_id = 'instanceId-2101995259'\n instance = {}\n clusters = {}\n\n response = client.create_instance(parent, instance_id, instance,\n clusters)\n result = response.result()\n assert expected_response == result\n\n assert len(channel.requests) == 1\n expected_request = bigtable_instance_admin_pb2.CreateInstanceRequest(\n parent=parent,\n instance_id=instance_id,\n instance=instance,\n clusters=clusters)\n actual_request = channel.requests[0][1]\n assert expected_request == actual_request\n\n def test_create_instance_exception(self):\n # Setup Response\n error = status_pb2.Status()\n operation = operations_pb2.Operation(\n name='operations/test_create_instance_exception', done=True)\n operation.error.CopyFrom(error)\n\n # Mock the API response\n channel = ChannelStub(responses=[operation])\n patch = mock.patch('google.api_core.grpc_helpers.create_channel')\n with patch as create_channel:\n create_channel.return_value = channel\n client = bigtable_admin_v2.BigtableInstanceAdminClient()\n\n # Setup Request\n parent = client.project_path('[PROJECT]')\n instance_id = 'instanceId-2101995259'\n instance = {}\n clusters = {}\n\n response = client.create_instance(parent, instance_id, instance,\n clusters)\n exception = response.exception()\n assert exception.errors[0] == error\n\n def test_get_instance(self):\n # Setup Expected Response\n name_2 = 'name2-1052831874'\n display_name = 'displayName1615086568'\n expected_response = {'name': name_2, 'display_name': display_name}\n expected_response = instance_pb2.Instance(**expected_response)\n\n # Mock the API response\n channel = ChannelStub(responses=[expected_response])\n patch = mock.patch('google.api_core.grpc_helpers.create_channel')\n with patch as create_channel:\n create_channel.return_value = channel\n client = bigtable_admin_v2.BigtableInstanceAdminClient()\n\n # Setup Request\n name = client.instance_path('[PROJECT]', '[INSTANCE]')\n\n response = client.get_instance(name)\n assert expected_response == response\n\n assert len(channel.requests) == 1\n expected_request = bigtable_instance_admin_pb2.GetInstanceRequest(\n name=name)\n actual_request = channel.requests[0][1]\n assert expected_request == actual_request\n\n def test_get_instance_exception(self):\n # Mock the API response\n channel = ChannelStub(responses=[CustomException()])\n patch = mock.patch('google.api_core.grpc_helpers.create_channel')\n with patch as create_channel:\n create_channel.return_value = channel\n client = bigtable_admin_v2.BigtableInstanceAdminClient()\n\n # Setup request\n name = client.instance_path('[PROJECT]', '[INSTANCE]')\n\n with pytest.raises(CustomException):\n client.get_instance(name)\n\n def test_list_instances(self):\n # Setup Expected Response\n next_page_token = 'nextPageToken-1530815211'\n expected_response = {'next_page_token': next_page_token}\n expected_response = bigtable_instance_admin_pb2.ListInstancesResponse(\n **expected_response)\n\n # Mock the API response\n channel = ChannelStub(responses=[expected_response])\n patch = mock.patch('google.api_core.grpc_helpers.create_channel')\n with patch as create_channel:\n create_channel.return_value = channel\n client = bigtable_admin_v2.BigtableInstanceAdminClient()\n\n # Setup Request\n parent = client.project_path('[PROJECT]')\n\n response = client.list_instances(parent)\n assert expected_response == response\n\n assert len(channel.requests) == 1\n expected_request = bigtable_instance_admin_pb2.ListInstancesRequest(\n parent=parent)\n actual_request = channel.requests[0][1]\n assert expected_request == actual_request\n\n def test_list_instances_exception(self):\n # Mock the API response\n channel = ChannelStub(responses=[CustomException()])\n patch = mock.patch('google.api_core.grpc_helpers.create_channel')\n with patch as create_channel:\n create_channel.return_value = channel\n client = bigtable_admin_v2.BigtableInstanceAdminClient()\n\n # Setup request\n parent = client.project_path('[PROJECT]')\n\n with pytest.raises(CustomException):\n client.list_instances(parent)\n\n def test_update_instance(self):\n # Setup Expected Response\n name_2 = 'name2-1052831874'\n display_name_2 = 'displayName21615000987'\n expected_response = {'name': name_2, 'display_name': display_name_2}\n expected_response = instance_pb2.Instance(**expected_response)\n\n # Mock the API response\n channel = ChannelStub(responses=[expected_response])\n patch = mock.patch('google.api_core.grpc_helpers.create_channel')\n with patch as create_channel:\n create_channel.return_value = channel\n client = bigtable_admin_v2.BigtableInstanceAdminClient()\n\n # Setup Request\n name = client.instance_path('[PROJECT]', '[INSTANCE]')\n display_name = 'displayName1615086568'\n type_ = enums.Instance.Type.TYPE_UNSPECIFIED\n labels = {}\n\n response = client.update_instance(name, display_name, type_, labels)\n assert expected_response == response\n\n assert len(channel.requests) == 1\n expected_request = instance_pb2.Instance(\n name=name, display_name=display_name, type=type_, labels=labels)\n actual_request = channel.requests[0][1]\n assert expected_request == actual_request\n\n def test_update_instance_exception(self):\n # Mock the API response\n channel = ChannelStub(responses=[CustomException()])\n patch = mock.patch('google.api_core.grpc_helpers.create_channel')\n with patch as create_channel:\n create_channel.return_value = channel\n client = bigtable_admin_v2.BigtableInstanceAdminClient()\n\n # Setup request\n name = client.instance_path('[PROJECT]', '[INSTANCE]')\n display_name = 'displayName1615086568'\n type_ = enums.Instance.Type.TYPE_UNSPECIFIED\n labels = {}\n\n with pytest.raises(CustomException):\n client.update_instance(name, display_name, type_, labels)\n\n def test_partial_update_instance(self):\n # Setup Expected Response\n name = 'name3373707'\n display_name = 'displayName1615086568'\n expected_response = {'name': name, 'display_name': display_name}\n expected_response = instance_pb2.Instance(**expected_response)\n operation = operations_pb2.Operation(\n name='operations/test_partial_update_instance', done=True)\n operation.response.Pack(expected_response)\n\n # Mock the API response\n channel = ChannelStub(responses=[operation])\n patch = mock.patch('google.api_core.grpc_helpers.create_channel')\n with patch as create_channel:\n create_channel.return_value = channel\n client = bigtable_admin_v2.BigtableInstanceAdminClient()\n\n # Setup Request\n instance = {}\n update_mask = {}\n\n response = client.partial_update_instance(instance, update_mask)\n result = response.result()\n assert expected_response == result\n\n assert len(channel.requests) == 1\n expected_request = bigtable_instance_admin_pb2.PartialUpdateInstanceRequest(\n instance=instance, update_mask=update_mask)\n actual_request = channel.requests[0][1]\n assert expected_request == actual_request\n\n def test_partial_update_instance_exception(self):\n # Setup Response\n error = status_pb2.Status()\n operation = operations_pb2.Operation(\n name='operations/test_partial_update_instance_exception',\n done=True)\n operation.error.CopyFrom(error)\n\n # Mock the API response\n channel = ChannelStub(responses=[operation])\n patch = mock.patch('google.api_core.grpc_helpers.create_channel')\n with patch as create_channel:\n create_channel.return_value = channel\n client = bigtable_admin_v2.BigtableInstanceAdminClient()\n\n # Setup Request\n instance = {}\n update_mask = {}\n\n response = client.partial_update_instance(instance, update_mask)\n exception = response.exception()\n assert exception.errors[0] == error\n\n def test_delete_instance(self):\n channel = ChannelStub()\n patch = mock.patch('google.api_core.grpc_helpers.create_channel')", "answers": [" with patch as create_channel:"], "length": 860, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "960a5daf-e7c4-4aec-9dc3-e83f4ab904a5", "reasoning": "The test method is setting up a ChannelStub and a mock.patch for the gRPC channel creation, following the pattern used in previous test methods. After defining the patch, the next logical line is to enter the context manager with 'with patch as create_channel:' to apply the mock and configure the client.", "reasoning_model_answer": "with patch as create_channel:", "assistant_with_reasoning": "\nThe test method is setting up a ChannelStub and a mock.patch for the gRPC channel creation, following the pattern used in previous test methods. After defining the patch, the next logical line is to enter the context manager with 'with patch as create_channel:' to apply the mock and configure the client.\n\nwith patch as create_channel:", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 2.982, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 12077, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "with patch as create_channel:", "score": 0.88, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n// Generated by the protocol buffer compiler. DO NOT EDIT!\n// source: google/bigtable/v2/bigtable.proto\n\npackage com.google.bigtable.v2;\n\n/**\n *\n *\n *
    \n * Request message for client connection keep-alive and warming.\n * 
    \n *\n * Protobuf type {@code google.bigtable.v2.PingAndWarmRequest}\n */\npublic final class PingAndWarmRequest extends com.google.protobuf.GeneratedMessageV3\n implements\n // @@protoc_insertion_point(message_implements:google.bigtable.v2.PingAndWarmRequest)\n PingAndWarmRequestOrBuilder {\n private static final long serialVersionUID = 0L;\n // Use PingAndWarmRequest.newBuilder() to construct.\n private PingAndWarmRequest(com.google.protobuf.GeneratedMessageV3.Builder builder) {\n super(builder);\n }\n\n private PingAndWarmRequest() {\n name_ = \"\";\n appProfileId_ = \"\";\n }\n\n @java.lang.Override\n @SuppressWarnings({\"unused\"})\n protected java.lang.Object newInstance(UnusedPrivateParameter unused) {\n return new PingAndWarmRequest();\n }\n\n @java.lang.Override\n public final com.google.protobuf.UnknownFieldSet getUnknownFields() {\n return this.unknownFields;\n }\n\n private PingAndWarmRequest(\n com.google.protobuf.CodedInputStream input,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws com.google.protobuf.InvalidProtocolBufferException {\n this();\n if (extensionRegistry == null) {\n throw new java.lang.NullPointerException();\n }\n com.google.protobuf.UnknownFieldSet.Builder unknownFields =\n com.google.protobuf.UnknownFieldSet.newBuilder();\n try {\n boolean done = false;\n while (!done) {\n int tag = input.readTag();\n switch (tag) {\n case 0:\n done = true;\n break;\n case 10:\n {\n java.lang.String s = input.readStringRequireUtf8();\n\n name_ = s;\n break;\n }\n case 18:\n {\n java.lang.String s = input.readStringRequireUtf8();\n\n appProfileId_ = s;\n break;\n }\n default:\n {\n if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) {\n done = true;\n }\n break;\n }\n }\n }\n } catch (com.google.protobuf.InvalidProtocolBufferException e) {\n throw e.setUnfinishedMessage(this);\n } catch (java.io.IOException e) {\n throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this);\n } finally {\n this.unknownFields = unknownFields.build();\n makeExtensionsImmutable();\n }\n }\n\n public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {\n return com.google.bigtable.v2.BigtableProto\n .internal_static_google_bigtable_v2_PingAndWarmRequest_descriptor;\n }\n\n @java.lang.Override\n protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable\n internalGetFieldAccessorTable() {\n return com.google.bigtable.v2.BigtableProto\n .internal_static_google_bigtable_v2_PingAndWarmRequest_fieldAccessorTable\n .ensureFieldAccessorsInitialized(\n com.google.bigtable.v2.PingAndWarmRequest.class,\n com.google.bigtable.v2.PingAndWarmRequest.Builder.class);\n }\n\n public static final int NAME_FIELD_NUMBER = 1;\n private volatile java.lang.Object name_;\n /**\n *\n *\n *
    \n   * Required. The unique name of the instance to check permissions for as well as\n   * respond. Values are of the form `projects/<project>/instances/<instance>`.\n   * 
    \n *\n * \n * string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }\n * \n *\n * @return The name.\n */\n @java.lang.Override\n public java.lang.String getName() {\n java.lang.Object ref = name_;\n if (ref instanceof java.lang.String) {\n return (java.lang.String) ref;\n } else {\n com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;\n java.lang.String s = bs.toStringUtf8();\n name_ = s;\n return s;\n }\n }\n /**\n *\n *\n *
    \n   * Required. The unique name of the instance to check permissions for as well as\n   * respond. Values are of the form `projects/<project>/instances/<instance>`.\n   * 
    \n *\n * \n * string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }\n * \n *\n * @return The bytes for name.\n */\n @java.lang.Override\n public com.google.protobuf.ByteString getNameBytes() {\n java.lang.Object ref = name_;\n if (ref instanceof java.lang.String) {\n com.google.protobuf.ByteString b =\n com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);\n name_ = b;\n return b;\n } else {\n return (com.google.protobuf.ByteString) ref;\n }\n }\n\n public static final int APP_PROFILE_ID_FIELD_NUMBER = 2;\n private volatile java.lang.Object appProfileId_;\n /**\n *\n *\n *
    \n   * This value specifies routing for replication. If not specified, the\n   * \"default\" application profile will be used.\n   * 
    \n *\n * string app_profile_id = 2;\n *\n * @return The appProfileId.\n */\n @java.lang.Override\n public java.lang.String getAppProfileId() {\n java.lang.Object ref = appProfileId_;\n if (ref instanceof java.lang.String) {\n return (java.lang.String) ref;\n } else {", "answers": [" com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;"], "length": 587, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "1cf4e605-d5f6-4989-81ca-2d300d029c92", "reasoning": "The method getAppProfileId() follows the standard protobuf generated pattern for string fields: it checks if the stored object is a String, otherwise it treats it as a ByteString, converts it to UTF-8 String, caches it, and returns it. The next line after the opening else brace should be the declaration and casting of the ByteString variable.", "reasoning_model_answer": "com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;", "assistant_with_reasoning": "\nThe method getAppProfileId() follows the standard protobuf generated pattern for string fields: it checks if the stored object is a String, otherwise it treats it as a ByteString, converts it to UTF-8 String, caches it, and returns it. The next line after the opening else brace should be the declaration and casting of the ByteString variable.\n\ncom.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.486, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 6162, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;", "score": 0.96, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "# Copyright 2016 Intel Corporation\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"Full Correlation Matrix Analysis (FCMA)\n\nCorrelation-based voxel selection\n\"\"\"\n\n# Authors: Yida Wang\n# (Intel Labs), 2016\n\nimport numpy as np\nimport time\nfrom mpi4py import MPI\nfrom scipy.stats.mstats import zscore\nfrom sklearn import model_selection\nimport sklearn\nfrom . import fcma_extension # type: ignore\nfrom . import cython_blas as blas # type: ignore\nfrom ..utils.utils import usable_cpu_count\nimport logging\nimport multiprocessing\n\nlogger = logging.getLogger(__name__)\n\n__all__ = [\n \"VoxelSelector\",\n]\n\n\ndef _cross_validation_for_one_voxel(clf, vid, num_folds, subject_data, labels):\n \"\"\"Score classifier on data using cross validation.\"\"\"\n # no shuffling in cv\n skf = model_selection.StratifiedKFold(n_splits=num_folds,\n shuffle=False)\n scores = model_selection.cross_val_score(clf, subject_data,\n y=labels,\n cv=skf, n_jobs=1)\n logger.debug(\n 'cross validation for voxel %d is done' %\n vid\n )\n return (vid, scores.mean())\n\n\nclass VoxelSelector:\n \"\"\"Correlation-based voxel selection component of FCMA.\n\n Parameters\n ----------\n\n labels: list of 1D array\n the condition labels of the epochs\n len(labels) labels equals the number of epochs\n\n epochs_per_subj: int\n The number of epochs of each subject\n\n num_folds: int\n The number of folds to be conducted in the cross validation\n\n raw_data: list of 2D array in shape [epoch length, nVoxels]\n Assumption: 1. all activity data contains the same number of voxels\n 2. the activity data has been z-scored,\n ready to compute correlation as matrix multiplication\n 3. all subjects have the same number of epochs\n 4. epochs belonging to the same subject are adjacent\n in the list\n 5. if MPI jobs are running on multiple nodes, the path\n used must be on a filesystem shared by all nodes\n\n raw_data2: Optional, list of 2D array in shape [epoch length, nVoxels]\n raw_data2 shares the data structure of the assumptions of raw_data\n If raw_data2 is None, the correlation will be computed as\n raw_data by raw_data.\n If raw_data2 is specified, len(raw_data) MUST equal len(raw_data2),\n the correlation will be computed as raw_data by raw_data2.\n\n voxel_unit: int, default 64\n The number of voxels assigned to a worker each time\n\n process_num: Optional[int]\n The maximum number of processes used in cross validation.\n If None, the number of processes will equal\n the number of available hardware threads, considering cpusets\n restrictions.\n If 0, cross validation will not use python multiprocessing.\n\n master_rank: int, default 0\n The process which serves as the master\n \"\"\"\n def __init__(self,\n labels,\n epochs_per_subj,\n num_folds,\n raw_data,\n raw_data2=None,\n voxel_unit=64,\n process_num=4,\n master_rank=0):\n self.labels = labels\n self.epochs_per_subj = epochs_per_subj\n self.num_folds = num_folds\n self.raw_data = raw_data\n self.num_voxels = raw_data[0].shape[1]\n self.raw_data2 = raw_data2\n self.num_voxels2 = raw_data2[0].shape[1] \\\n if raw_data2 is not None else self.num_voxels\n self.voxel_unit = voxel_unit\n usable_cpus = usable_cpu_count()\n if process_num is None:\n self.process_num = usable_cpus\n else:\n self.process_num = np.min((process_num, usable_cpus))\n if self.process_num == 0:\n self.use_multiprocessing = False\n else:\n self.use_multiprocessing = True\n self.master_rank = master_rank\n if self.raw_data2 is not None \\\n and len(self.raw_data) != len(self.raw_data2):\n raise ValueError('The raw data lists must have the same number '\n 'of elements for computing the correlations '\n 'element by element')\n if self.num_voxels == 0 or self.num_voxels2 == 0:\n raise ValueError('Zero processed voxels')\n if MPI.COMM_WORLD.Get_size() == 1:\n raise RuntimeError('one process cannot run the '\n 'master-worker model')\n if self.master_rank >= MPI.COMM_WORLD.Get_size():\n logger.warn('Master rank exceeds the number of '\n 'launched processes, set to 0')\n self.master_rank = 0\n\n # tags for MPI messages\n _WORKTAG = 0\n _TERMINATETAG = 1\n\n def run(self, clf):\n \"\"\"Run correlation-based voxel selection in master-worker model.\n\n Sort the voxels based on the cross-validation accuracy\n of their correlation vectors\n\n Parameters\n ----------\n clf: classification function\n the classifier to be used in cross validation\n\n Returns\n -------\n results: list of tuple (voxel_id, accuracy)\n the accuracy numbers of all voxels, in accuracy descending order\n the length of array equals the number of voxels\n \"\"\"\n rank = MPI.COMM_WORLD.Get_rank()", "answers": [" if rank == self.master_rank:"], "length": 676, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "928c79c9-22c5-4d79-ac35-59057432eec9", "reasoning": "Within the run method, after obtaining the MPI rank, the code will branch into master and worker behavior. The next logical line is the conditional checking if the current process is the master, i.e., comparing rank to self.master_rank.", "reasoning_model_answer": "if rank == self.master_rank:", "assistant_with_reasoning": "\nWithin the run method, after obtaining the MPI rank, the code will branch into master and worker behavior. The next logical line is the conditional checking if the current process is the master, i.e., comparing rank to self.master_rank.\n\nif rank == self.master_rank:", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 1.749, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 6141, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "if rank == self.master_rank:", "score": 0.88, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "package org.hisp.dhis.analytics;\n\n/*\n * Copyright (c) 2004-2016, University of Oslo\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n *\n * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and/or other materials provided with the distribution.\n * Neither the name of the HISP project nor the names of its contributors may\n * be used to endorse or promote products derived from this software without\n * specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR\n * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\n * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\nimport org.hisp.dhis.DhisSpringTest;\nimport org.junit.Test;\n\nimport com.google.common.collect.Lists;\n\nimport org.hisp.dhis.common.BaseDimensionalObject;\nimport org.hisp.dhis.common.DataDimensionItemType;\nimport org.hisp.dhis.common.DimensionType;\nimport org.hisp.dhis.common.DimensionalItemObject;\nimport org.hisp.dhis.common.DimensionalObject;\nimport org.hisp.dhis.common.DisplayProperty;\nimport org.hisp.dhis.common.Grid;\nimport org.hisp.dhis.common.GridHeader;\nimport org.hisp.dhis.common.ValueType;\nimport org.hisp.dhis.dataelement.DataElement;\nimport org.hisp.dhis.dataelement.DataElementCategory;\nimport org.hisp.dhis.dataelement.DataElementCategoryCombo;\nimport org.hisp.dhis.dataelement.DataElementCategoryOptionCombo;\nimport org.hisp.dhis.dataelement.DataElementOperand;\nimport org.hisp.dhis.dataset.DataSet;\nimport org.hisp.dhis.dxf2.datavalueset.DataValueSet;\nimport org.hisp.dhis.indicator.Indicator;\nimport org.hisp.dhis.indicator.IndicatorType;\nimport org.hisp.dhis.organisationunit.OrganisationUnit;\nimport org.hisp.dhis.program.Program;\nimport org.hisp.dhis.program.ProgramDataElement;\nimport org.hisp.dhis.program.ProgramIndicator;\nimport org.hisp.dhis.system.grid.ListGrid;\n\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\nimport static org.junit.Assert.*;\nimport static org.hisp.dhis.analytics.DataQueryParams.VALUE_HEADER_NAME;\nimport static org.hisp.dhis.analytics.DataQueryParams.VALUE_ID;\nimport static org.hisp.dhis.common.DimensionalObject.DIMENSION_SEP;\nimport static org.hisp.dhis.common.DimensionalObject.DATA_X_DIM_ID;\n\n/**\n * @author Lars Helge Overland\n */\npublic class AnalyticsUtilsTest \n extends DhisSpringTest\n{\n @Test\n public void testGetByDataDimensionType()\n {\n Program prA = createProgram( 'A' );\n \n DataElement deA = createDataElement( 'A', new DataElementCategoryCombo() );\n DataElement deB = createDataElement( 'B', new DataElementCategoryCombo() );\n ProgramDataElement pdeA = new ProgramDataElement( prA, deA );\n ProgramDataElement pdeB = new ProgramDataElement( prA, deB );\n ProgramIndicator piA = createProgramIndicator( 'A', prA, null, null );\n \n List list = Lists.newArrayList( deA, deB, pdeA, pdeB, piA );\n \n assertEquals( Lists.newArrayList( deA, deB ), AnalyticsUtils.getByDataDimensionItemType( DataDimensionItemType.DATA_ELEMENT, list ) );\n assertEquals( Lists.newArrayList( pdeA, pdeB ), AnalyticsUtils.getByDataDimensionItemType( DataDimensionItemType.PROGRAM_DATA_ELEMENT, list ) );\n assertEquals( Lists.newArrayList( piA ), AnalyticsUtils.getByDataDimensionItemType( DataDimensionItemType.PROGRAM_INDICATOR, list ) );\n assertEquals( Lists.newArrayList(), AnalyticsUtils.getByDataDimensionItemType( DataDimensionItemType.PROGRAM_ATTRIBUTE, list ) );\n }\n \n @Test\n public void testConvertDxToOperand()\n {\n Map map = new HashMap<>();\n map.put( \"GauDLAiXPKT-kC1OT9Q1n1j-R9U8q7X1aJG\", 10d );\n map.put( \"YkRvCLedQa4-h1dJ9W4dWor-Zrd4DAf8M99\", 11d );\n map.put( \"PcfRp1HETO8-zqXKIEycBck-KBJBZopYMPV\", 12d );\n \n Map convertedMap = AnalyticsUtils.convertDxToOperand( map );\n \n assertTrue( convertedMap.containsKey( \"GauDLAiXPKT.kC1OT9Q1n1j-R9U8q7X1aJG\" ) );\n assertTrue( convertedMap.containsKey( \"YkRvCLedQa4.h1dJ9W4dWor-Zrd4DAf8M99\" ) );\n assertTrue( convertedMap.containsKey( \"PcfRp1HETO8.zqXKIEycBck-KBJBZopYMPV\" ) );\n }\n \n @Test\n public void testGetRoundedValueObject()\n {\n DataQueryParams paramsA = DataQueryParams.newBuilder().build();\n DataQueryParams paramsB = DataQueryParams.newBuilder().withSkipRounding( true ).build();\n \n assertEquals( null, AnalyticsUtils.getRoundedValueObject( paramsA, null ) );\n assertEquals( \"Car\", AnalyticsUtils.getRoundedValueObject( paramsA, \"Car\" ) );\n assertEquals( 3d, AnalyticsUtils.getRoundedValueObject( paramsA, 3d ) );\n assertEquals( 3.1, (Double) AnalyticsUtils.getRoundedValueObject( paramsA, 3.123 ), 0.01 );\n assertEquals( 3.123, (Double) AnalyticsUtils.getRoundedValueObject( paramsB, 3.123 ), 0.01 );\n }\n\n @Test\n public void testGetRoundedValueDouble()\n {\n DataQueryParams paramsA = DataQueryParams.newBuilder().build();\n DataQueryParams paramsB = DataQueryParams.newBuilder().withSkipRounding( true ).build();\n \n assertEquals( null, AnalyticsUtils.getRoundedValue( paramsA, null, null ) );\n assertEquals( 3d, AnalyticsUtils.getRoundedValue( paramsA, null, 3d ), 0.01 );\n assertEquals( 3.1, AnalyticsUtils.getRoundedValue( paramsA, null, 3.123 ), 0.01 );", "answers": [" assertEquals( 3.1, AnalyticsUtils.getRoundedValue( paramsA, 1, 3.123 ), 0.01 );"], "length": 583, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "f65d88d7-9916-4ea3-b18f-d75c35b2c279", "reasoning": "The test method testGetRoundedValueDouble is checking rounding behavior. It has already asserted null handling, exact value, and rounding for paramsA. The next logical assertion mirrors the earlier testGetRoundedValueObject, verifying that when skipRounding is true (paramsB), the original double value is returned unchanged. Therefore the next line should assert that AnalyticsUtils.getRoundedValue with paramsB returns 3.123.", "reasoning_model_answer": "assertEquals( 3.123, AnalyticsUtils.getRoundedValue( paramsB, null, 3.123 ), 0.01 );", "assistant_with_reasoning": "\nThe test method testGetRoundedValueDouble is checking rounding behavior. It has already asserted null handling, exact value, and rounding for paramsA. The next logical assertion mirrors the earlier testGetRoundedValueObject, verifying that when skipRounding is true (paramsB), the original double value is returned unchanged. Therefore the next line should assert that AnalyticsUtils.getRoundedValue with paramsB returns 3.123.\n\nassertEquals( 3.123, AnalyticsUtils.getRoundedValue( paramsB, null, 3.123 ), 0.01 );", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.874, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 6436, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "assertEquals( 3.123, AnalyticsUtils.getRoundedValue( paramsB, null, 3.123 ), 0.01 );", "score": 0.9, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "// Copyright 2016 Google Inc. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nusing UnityEngine;\nusing UnityEngine.Audio;\nusing System.Collections;\n\n#pragma warning disable 0618 // Ignore GvrAudio* deprecation\n\n/// GVR soundfield component that allows playback of first-order ambisonic recordings. The audio\n/// sample should be in Ambix (ACN-SN3D) format.\n#if UNITY_2017_1_OR_NEWER\n[System.Obsolete(\"Please upgrade to Resonance Audio (https://developers.google.com/resonance-audio/migrate).\")]\n#endif // UNITY_2017_1_OR_NEWER\n[AddComponentMenu(\"GoogleVR/Audio/GvrAudioSoundfield\")]\npublic class GvrAudioSoundfield : MonoBehaviour {\n /// Denotes whether the room effects should be bypassed.\n public bool bypassRoomEffects = true;\n\n /// Input gain in decibels.\n public float gainDb = 0.0f;\n\n /// Play source on awake.\n public bool playOnAwake = true;\n\n /// The default AudioClip to play.\n public AudioClip clip0102 {\n get { return soundfieldClip0102; }\n set {\n soundfieldClip0102 = value;\n if (audioSources != null && audioSources.Length > 0) {\n audioSources[0].clip = soundfieldClip0102;\n }\n }\n }\n [SerializeField]\n private AudioClip soundfieldClip0102 = null;\n\n public AudioClip clip0304 {\n get { return soundfieldClip0304; }\n set {\n soundfieldClip0304 = value;\n if (audioSources != null && audioSources.Length > 0) {\n audioSources[1].clip = soundfieldClip0304;\n }\n }\n }\n [SerializeField]\n private AudioClip soundfieldClip0304 = null;\n\n /// Is the clip playing right now (Read Only)?\n public bool isPlaying {\n get {\n if(audioSources != null && audioSources.Length > 0) {\n return audioSources[0].isPlaying;\n }\n return false;\n }\n }\n\n /// Is the audio clip looping?\n public bool loop {\n get { return soundfieldLoop; }\n set {\n soundfieldLoop = value;\n if(audioSources != null) {\n for (int channelSet = 0; channelSet < audioSources.Length; ++channelSet) {\n audioSources[channelSet].loop = soundfieldLoop;\n }\n }\n }\n }\n [SerializeField]\n private bool soundfieldLoop = false;\n\n /// Un- / Mutes the soundfield. Mute sets the volume=0, Un-Mute restore the original volume.\n public bool mute {\n get { return soundfieldMute; }\n set {\n soundfieldMute = value;\n if(audioSources != null) {\n for (int channelSet = 0; channelSet < audioSources.Length; ++channelSet) {\n audioSources[channelSet].mute = soundfieldMute;\n }\n }\n }\n }\n [SerializeField]\n private bool soundfieldMute = false;\n\n /// The pitch of the audio source.\n public float pitch {\n get { return soundfieldPitch; }\n set {\n soundfieldPitch = value;\n if(audioSources != null) {\n for (int channelSet = 0; channelSet < audioSources.Length; ++channelSet) {\n audioSources[channelSet].pitch = soundfieldPitch;\n }\n }\n }\n }\n [SerializeField]\n [Range(-3.0f, 3.0f)]\n private float soundfieldPitch = 1.0f;\n\n /// Sets the priority of the soundfield.\n public int priority {\n get { return soundfieldPriority; }\n set {\n soundfieldPriority = value;\n if(audioSources != null) {\n for (int channelSet = 0; channelSet < audioSources.Length; ++channelSet) {\n audioSources[channelSet].priority = soundfieldPriority;\n }\n }\n }\n }\n [SerializeField]\n [Range(0, 256)]\n private int soundfieldPriority = 32;\n\n /// Sets how much this soundfield is affected by 3D spatialization calculations\n /// (attenuation, doppler).\n public float spatialBlend {\n get { return soundfieldSpatialBlend; }\n set {\n soundfieldSpatialBlend = value;\n if (audioSources != null) {\n for (int channelSet = 0; channelSet < audioSources.Length; ++channelSet) {\n audioSources[channelSet].spatialBlend = soundfieldSpatialBlend;\n }\n }\n }\n }\n [SerializeField]\n [Range(0.0f, 1.0f)]\n private float soundfieldSpatialBlend = 0.0f;\n\n /// Sets the Doppler scale for this soundfield.\n public float dopplerLevel {\n get { return soundfieldDopplerLevel; }\n set {\n soundfieldDopplerLevel = value;\n if(audioSources != null) {", "answers": [" for (int channelSet = 0; channelSet < audioSources.Length; ++channelSet) {"], "length": 584, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "5b537962-6c06-460b-ab63-7f7dd5ee20b6", "reasoning": "The setter for dopplerLevel follows the same pattern as other property setters (pitch, priority, spatialBlend). After checking audioSources is not null, the code iterates over each AudioSource and assigns the dopplerLevel. Therefore the next line is the start of that for-loop.", "reasoning_model_answer": "for (int channelSet = 0; channelSet < audioSources.Length; ++channelSet) {", "assistant_with_reasoning": "\nThe setter for dopplerLevel follows the same pattern as other property setters (pitch, priority, spatialBlend). After checking audioSources is not null, the code iterates over each AudioSource and assigns the dopplerLevel. Therefore the next line is the start of that for-loop.\n\nfor (int channelSet = 0; channelSet < audioSources.Length; ++channelSet) {", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.787, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 4813, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "for (int channelSet = 0; channelSet < audioSources.Length; ++channelSet) {", "score": 0.95, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/* Copyright (C) 2004-2007 Egon Willighagen \n *\n * Contact: cdk-devel@lists.sourceforge.net\n *\n * This program is free software; you can redistribute it and/or\n * modify it under the terms of the GNU Lesser General Public License\n * as published by the Free Software Foundation; either version 2.1\n * of the License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.\n */\n\nusing Microsoft.VisualStudio.TestTools.UnitTesting;\nusing NCDK.Aromaticities;\nusing NCDK.Common.Base;\nusing NCDK.Graphs;\nusing NCDK.IO;\nusing NCDK.Isomorphisms;\nusing NCDK.Tools.Manipulator;\nusing System;\nusing System.Diagnostics;\nusing System.Linq;\n\nnamespace NCDK.Smiles.SMARTS.Parser\n{\n /// \n /// Unit test routines for the SMARTS substructure search.\n /// \n // @author Dazhi Jiao\n // @cdk.module test-smarts\n // @cdk.require ant1.6\n [TestClass()]\n public class SMARTSSearchTest : CDKTestCase\n {\n private UniversalIsomorphismTester uiTester = new UniversalIsomorphismTester();\n\n internal static IAtomContainer CreateFromSmiles(string smiles)\n {\n return CreateFromSmiles(smiles, false);\n }\n\n internal static IAtomContainer SmilesAtomTyped(string smiles)\n {\n IAtomContainer molecule = CreateFromSmiles(smiles, false);\n AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule);\n return molecule;\n }\n\n internal static IAtomContainer CreateFromSmiles(string smiles, bool perserveAromaticity)\n {\n var sp = new SmilesParser(CDK.Builder, !perserveAromaticity);\n return sp.ParseSmiles(smiles);\n }\n\n internal static SMARTSQueryTool CreateFromSmarts(string smarts)\n {\n SMARTSQueryTool sqt = new SMARTSQueryTool(smarts);\n return sqt;\n }\n\n internal static int[] Match(SMARTSQueryTool sqt, IAtomContainer m)\n {\n bool status = sqt.Matches(m);\n if (status)\n {\n return new int[] { sqt.MatchesCount, sqt.GetUniqueMatchingAtoms().Count() };\n }\n else\n {\n return new int[] { 0, 0 };\n }\n }\n\n internal static int[] Match(string smarts, string smiles)\n {\n return Match(CreateFromSmarts(smarts), CreateFromSmiles(smiles));\n }\n\n [TestMethod()]\n public void TestMoleculeFromSDF()\n {\n var filename = \"cnssmarts.sdf\";\n var ins = ResourceLoader.GetAsStream(GetType(), filename);\n DefaultChemObjectReader reader = new MDLV2000Reader(ins);\n var content = reader.Read(CDK.Builder.NewChemFile());\n var cList = ChemFileManipulator.GetAllAtomContainers(content).ToReadOnlyList();\n IAtomContainer atomContainer = cList[0];\n\n SMARTSQueryTool sqt = new SMARTSQueryTool(\"[NX3;h1,h2,H1,H2;!$(NC=O)]\");\n bool status = sqt.Matches(atomContainer);\n Assert.AreEqual(true, status);\n\n int nmatch = sqt.MatchesCount;\n int nqmatch = sqt.GetUniqueMatchingAtoms().Count();\n\n Assert.AreEqual(3, nmatch);\n Assert.AreEqual(3, nqmatch);\n\n sqt.Smarts = \"[ND3]\";\n status = sqt.Matches(atomContainer);\n Assert.AreEqual(false, status);\n }\n\n [TestMethod()]\n public void TestRGraphBond()\n {\n var query = SMARTSParser.Parse(\"CC=O\");\n Debug.WriteLine(\"Query c:c: \" + query.ToString());\n var sp = CDK.SmilesParser;\n\n var atomContainer = sp.ParseSmiles(\"CCC=O\"); // benzene, aromatic\n Assert.IsTrue(uiTester.IsSubgraph(atomContainer, query));\n }\n\n [TestMethod()]\n public void TestAromaticBond()\n {\n var query = SMARTSParser.Parse(\"c:c\");\n Debug.WriteLine(\"Query c:c: \" + query.ToString());\n var sp = new SmilesParser(CDK.Builder, false);\n var atomContainer = sp.ParseSmiles(\"c1ccccc1\"); // benzene, aromatic\n Assert.IsTrue(uiTester.IsSubgraph(atomContainer, query));\n\n atomContainer = sp.ParseSmiles(\"C1CCCCC1\"); // hexane, not aromatic\n Assert.IsFalse(uiTester.IsSubgraph(atomContainer, query));\n }\n\n [TestMethod()]\n public void TestSingleBond()\n {\n var query = SMARTSParser.Parse(\"C-C\");\n Debug.WriteLine(\"Query C-C: \" + query.ToString());\n var sp = CDK.SmilesParser;\n\n var atomContainer = sp.ParseSmiles(\"CCC\");\n Assert.IsTrue(uiTester.IsSubgraph(atomContainer, query));\n\n atomContainer = sp.ParseSmiles(\"C=C\");\n Assert.IsFalse(uiTester.IsSubgraph(atomContainer, query));\n\n atomContainer = sp.ParseSmiles(\"C#C\");\n Assert.IsFalse(uiTester.IsSubgraph(atomContainer, query));\n }\n\n [TestMethod()]\n public void TestDoubleBond()\n {\n var query = SMARTSParser.Parse(\"C=C\");\n Debug.WriteLine(\"Query C=C: \" + query.ToString());\n var sp = CDK.SmilesParser;\n\n var atomContainer = sp.ParseSmiles(\"CCC\");\n Assert.IsFalse(uiTester.IsSubgraph(atomContainer, query));\n\n atomContainer = sp.ParseSmiles(\"C=C\");\n Assert.IsTrue(uiTester.IsSubgraph(atomContainer, query));\n\n atomContainer = sp.ParseSmiles(\"C#C\");\n Assert.IsFalse(uiTester.IsSubgraph(atomContainer, query));\n }\n\n [TestMethod()]\n public void TestTripleBond()\n {\n var query = SMARTSParser.Parse(\"C#C\");\n Debug.WriteLine(\"Query C#C: \" + query.ToString());\n var sp = CDK.SmilesParser;\n\n var atomContainer = sp.ParseSmiles(\"CCC\");\n Assert.IsFalse(uiTester.IsSubgraph(atomContainer, query));\n\n atomContainer = sp.ParseSmiles(\"C=C\");\n Assert.IsFalse(uiTester.IsSubgraph(atomContainer, query));\n\n atomContainer = sp.ParseSmiles(\"C#C\");\n Assert.IsTrue(uiTester.IsSubgraph(atomContainer, query));\n }\n\n [TestMethod()]\n public void TestAnyOrderBond()\n {\n var query = SMARTSParser.Parse(\"C~C\");\n Debug.WriteLine(\"Query C~C: \" + query.ToString());\n var sp = CDK.SmilesParser;\n\n var atomContainer = sp.ParseSmiles(\"CCC\");\n Assert.IsTrue(uiTester.IsSubgraph(atomContainer, query));\n\n atomContainer = sp.ParseSmiles(\"C=C\");\n Assert.IsTrue(uiTester.IsSubgraph(atomContainer, query));\n\n atomContainer = sp.ParseSmiles(\"C#C\");\n Assert.IsTrue(uiTester.IsSubgraph(atomContainer, query));\n }\n\n [TestMethod()]\n public void TestAnyAtom()\n {\n var query = SMARTSParser.Parse(\"C*C\");\n Debug.WriteLine(\"Query C*C: \" + query.ToString());\n var sp = CDK.SmilesParser;\n\n var atomContainer = sp.ParseSmiles(\"CCC\");", "answers": [" Assert.IsTrue(uiTester.IsSubgraph(atomContainer, query));"], "length": 600, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "af212272-a9f1-41c0-8f24-1a202b595a21", "reasoning": "In the TestAnyAtom method, after creating the query and parsing a SMILES string into atomContainer, the pattern follows previous tests: they assert whether the subgraph match holds. For the any‑atom query \"C*C\" the first test uses \"CCC\" which should match, so the next line is an Assert.IsTrue checking the subgraph.", "reasoning_model_answer": "Assert.IsTrue(uiTester.IsSubgraph(atomContainer, query));", "assistant_with_reasoning": "\nIn the TestAnyAtom method, after creating the query and parsing a SMILES string into atomContainer, the pattern follows previous tests: they assert whether the subgraph match holds. For the any‑atom query \"C*C\" the first test uses \"CCC\" which should match, so the next line is an Assert.IsTrue checking the subgraph.\n\nAssert.IsTrue(uiTester.IsSubgraph(atomContainer, query));", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 5.663, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 7578, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "Assert.IsTrue(uiTester.IsSubgraph(atomContainer, query));", "score": 0.9, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/* Generated SBE (Simple Binary Encoding) message codec */\n\nusing System;\nusing Adaptive.SimpleBinaryEncoding;\n\nnamespace Adaptive.SimpleBinaryEncoding.Examples.Generated\n{\n public class Car\n {\n public const ushort TemplateId = (ushort)1;\n public const byte TemplateVersion = (byte)0;\n public const ushort BlockLength = (ushort)45;\n public const string SematicType = \"\";\n\n private readonly Car _parentMessage;\n private DirectBuffer _buffer;\n private int _offset;\n private int _limit;\n private int _actingBlockLength;\n private int _actingVersion;\n\n public int Offset { get { return _offset; } }\n\n public Car()\n {\n _parentMessage = this;\n }\n\n public void WrapForEncode(DirectBuffer buffer, int offset)\n {\n _buffer = buffer;\n _offset = offset;\n _actingBlockLength = BlockLength;\n _actingVersion = TemplateVersion;\n Limit = offset + _actingBlockLength;\n }\n\n public void WrapForDecode(DirectBuffer buffer, int offset,\n int actingBlockLength, int actingVersion)\n {\n _buffer = buffer;\n _offset = offset;\n _actingBlockLength = actingBlockLength;\n _actingVersion = actingVersion;\n Limit = offset + _actingBlockLength;\n }\n\n public int Size\n {\n get\n {\n return _limit - _offset;\n }\n }\n\n public int Limit\n {\n get\n {\n return _limit;\n }\n set\n {\n _buffer.CheckLimit(_limit);\n _limit = value;\n }\n }\n\n\n public const int SerialNumberSchemaId = 1;\n\n public static string SerialNumberMetaAttribute(MetaAttribute metaAttribute)\n {\n switch (metaAttribute)\n {\n case MetaAttribute.Epoch: return \"unix\";\n case MetaAttribute.TimeUnit: return \"nanosecond\";\n case MetaAttribute.SemanticType: return \"\";\n }\n\n return \"\";\n }\n\n public const ulong SerialNumberNullValue = 0x8000000000000000UL;\n\n public const ulong SerialNumberMinValue = 0x0UL;\n\n public const ulong SerialNumberMaxValue = 0x7fffffffffffffffUL;\n\n public ulong SerialNumber\n {\n get\n {\n return _buffer.Uint64GetLittleEndian(_offset + 0);\n }\n set\n {\n _buffer.Uint64PutLittleEndian(_offset + 0, value);\n }\n }\n\n\n public const int ModelYearSchemaId = 2;\n\n public static string ModelYearMetaAttribute(MetaAttribute metaAttribute)\n {\n switch (metaAttribute)\n {\n case MetaAttribute.Epoch: return \"unix\";\n case MetaAttribute.TimeUnit: return \"nanosecond\";\n case MetaAttribute.SemanticType: return \"\";\n }\n\n return \"\";\n }\n\n public const ushort ModelYearNullValue = (ushort)65535;\n\n public const ushort ModelYearMinValue = (ushort)0;\n\n public const ushort ModelYearMaxValue = (ushort)65534;\n\n public ushort ModelYear\n {\n get\n {\n return _buffer.Uint16GetLittleEndian(_offset + 8);\n }\n set\n {\n _buffer.Uint16PutLittleEndian(_offset + 8, value);\n }\n }\n\n\n public const int AvailableSchemaId = 3;\n\n public static string AvailableMetaAttribute(MetaAttribute metaAttribute)\n {\n switch (metaAttribute)\n {\n case MetaAttribute.Epoch: return \"unix\";\n case MetaAttribute.TimeUnit: return \"nanosecond\";\n case MetaAttribute.SemanticType: return \"\";\n }\n\n return \"\";\n }\n\n public BooleanType Available\n {\n get\n {\n return (BooleanType)_buffer.Uint8Get(_offset + 10);\n }\n set\n {\n _buffer.Uint8Put(_offset + 10, (byte)value);\n }\n }\n\n\n public const int CodeSchemaId = 4;\n\n public static string CodeMetaAttribute(MetaAttribute metaAttribute)\n {\n switch (metaAttribute)\n {\n case MetaAttribute.Epoch: return \"unix\";\n case MetaAttribute.TimeUnit: return \"nanosecond\";\n case MetaAttribute.SemanticType: return \"\";\n }\n\n return \"\";\n }\n\n public Model Code\n {\n get\n {\n return (Model)_buffer.CharGet(_offset + 11);\n }\n set\n {\n _buffer.CharPut(_offset + 11, (byte)value);\n }\n }\n\n\n public const int SomeNumbersSchemaId = 5;\n\n public static string SomeNumbersMetaAttribute(MetaAttribute metaAttribute)\n {\n switch (metaAttribute)\n {\n case MetaAttribute.Epoch: return \"unix\";\n case MetaAttribute.TimeUnit: return \"nanosecond\";\n case MetaAttribute.SemanticType: return \"\";\n }\n\n return \"\";\n }\n\n public const int SomeNumbersNullValue = -2147483648;\n\n public const int SomeNumbersMinValue = -2147483647;\n\n public const int SomeNumbersMaxValue = 2147483647;\n\n public const int SomeNumbersLength = 5;\n\n public int GetSomeNumbers(int index)\n {\n if (index < 0 || index >= 5)\n {\n throw new IndexOutOfRangeException(\"index out of range: index=\" + index);\n }\n\n return _buffer.Int32GetLittleEndian(_offset + 12 + (index * 4));\n }\n\n public void SetSomeNumbers(int index, int value)\n {\n if (index < 0 || index >= 5)\n {\n throw new IndexOutOfRangeException(\"index out of range: index=\" + index);\n }\n\n _buffer.Int32PutLittleEndian(_offset + 12 + (index * 4), value);\n }\n\n public const int VehicleCodeSchemaId = 6;\n\n public static string VehicleCodeMetaAttribute(MetaAttribute metaAttribute)\n {\n switch (metaAttribute)\n {\n case MetaAttribute.Epoch: return \"unix\";\n case MetaAttribute.TimeUnit: return \"nanosecond\";\n case MetaAttribute.SemanticType: return \"\";\n }\n\n return \"\";\n }\n\n public const byte VehicleCodeNullValue = (byte)0;\n\n public const byte VehicleCodeMinValue = (byte)32;\n\n public const byte VehicleCodeMaxValue = (byte)126;\n\n public const int VehicleCodeLength = 6;", "answers": [" public byte GetVehicleCode(int index)"], "length": 582, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "f83fedad-4cec-4d10-b7b2-ad055f5c9974", "reasoning": "The class defines fields with schema IDs, meta attributes, null/min/max values, and for array fields includes a Length constant followed by accessor methods. After declaring VehicleCodeLength = 6, the next logical line is the start of the getter method for the VehicleCode array, matching the pattern used for SomeNumbers. Therefore the next line should be the method signature for GetVehicleCode.", "reasoning_model_answer": "public byte GetVehicleCode(int index)", "assistant_with_reasoning": "\nThe class defines fields with schema IDs, meta attributes, null/min/max values, and for array fields includes a Length constant followed by accessor methods. After declaring VehicleCodeLength = 6, the next logical line is the start of the getter method for the VehicleCode array, matching the pattern used for SomeNumbers. Therefore the next line should be the method signature for GetVehicleCode.\n\npublic byte GetVehicleCode(int index)", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 5.716, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 2, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 6202, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "public byte GetVehicleCode(int index)", "score": 0.95, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "##################################################################\n# Code for testing the variational Multi-Stage Generative Model. #\n##################################################################\n\n# basic python\nimport numpy as np\nimport numpy.random as npr\nimport cPickle\n\n# theano business\nimport theano\nimport theano.tensor as T\n\n# phil's sweetness\nimport utils\nfrom NetLayers import relu_actfun, softplus_actfun, tanh_actfun\nfrom InfNet import InfNet\nfrom HydraNet import HydraNet\nfrom GPSImputerWI import GPSImputerWI, load_gpsimputer_from_file\nfrom load_data import load_udm, load_tfd, load_svhn_gray, load_binarized_mnist\nfrom HelperFuncs import construct_masked_data, shift_and_scale_into_01, \\\n row_shuffle, to_fX\n\nRESULT_PATH = \"IMP_MNIST_GPSI_WI/\"\n\n###############################\n###############################\n## TEST GPS IMPUTER ON MNIST ##\n###############################\n###############################\n\ndef test_mnist(step_type='add',\n imp_steps=6,\n occ_dim=15,\n drop_prob=0.0):\n #########################################\n # Format the result tag more thoroughly #\n #########################################\n dp_int = int(100.0 * drop_prob)\n result_tag = \"{}GPSI_OD{}_DP{}_IS{}_{}_NA\".format(RESULT_PATH, occ_dim, dp_int, imp_steps, step_type)\n\n ##########################\n # Get some training data #\n ##########################\n rng = np.random.RandomState(1234)\n Xtr, Xva, Xte = load_binarized_mnist(data_path='./data/')\n Xtr = np.vstack((Xtr, Xva))\n Xva = Xte\n #del Xte\n tr_samples = Xtr.shape[0]\n va_samples = Xva.shape[0]\n\n ##########################\n # Get some training data #\n ##########################\n # rng = np.random.RandomState(1234)\n # dataset = 'data/mnist.pkl.gz'\n # datasets = load_udm(dataset, as_shared=False, zero_mean=False)\n # Xtr = datasets[0][0]\n # Xva = datasets[1][0]\n # Xte = datasets[2][0]\n # # Merge validation set and training set, and test on test set.\n # #Xtr = np.concatenate((Xtr, Xva), axis=0)\n # #Xva = Xte\n # Xtr = to_fX(shift_and_scale_into_01(Xtr))\n # Xva = to_fX(shift_and_scale_into_01(Xva))\n # tr_samples = Xtr.shape[0]\n # va_samples = Xva.shape[0]\n batch_size = 200\n batch_reps = 1\n all_pix_mean = np.mean(np.mean(Xtr, axis=1))\n data_mean = to_fX( all_pix_mean * np.ones((Xtr.shape[1],)) )\n\n ############################################################\n # Setup some parameters for the Iterative Refinement Model #\n ############################################################\n x_dim = Xtr.shape[1]\n s_dim = x_dim\n h_dim = 50\n z_dim = 100\n init_scale = 0.6\n\n x_in_sym = T.matrix('x_in_sym')\n x_out_sym = T.matrix('x_out_sym')\n x_mask_sym = T.matrix('x_mask_sym')\n\n ###############\n # p_h_given_x #\n ###############\n params = {}\n shared_config = [x_dim, 250]\n top_config = [shared_config[-1], h_dim]\n params['shared_config'] = shared_config\n params['mu_config'] = top_config\n params['sigma_config'] = top_config\n params['activation'] = tanh_actfun #relu_actfun\n params['init_scale'] = 'xg' #init_scale\n params['vis_drop'] = 0.0\n params['hid_drop'] = 0.0\n params['bias_noise'] = 0.0\n params['input_noise'] = 0.0\n params['build_theano_funcs'] = False\n p_h_given_x = InfNet(rng=rng, Xd=x_in_sym, \\\n params=params, shared_param_dicts=None)\n p_h_given_x.init_biases(0.0)\n ################\n # p_s0_given_h #\n ################\n params = {}\n shared_config = [h_dim, 250]\n output_config = [s_dim, s_dim, s_dim]\n params['shared_config'] = shared_config\n params['output_config'] = output_config\n params['activation'] = tanh_actfun #relu_actfun\n params['init_scale'] = 'xg' #init_scale\n params['vis_drop'] = 0.0\n params['hid_drop'] = 0.0\n params['bias_noise'] = 0.0\n params['input_noise'] = 0.0\n params['build_theano_funcs'] = False\n p_s0_given_h = HydraNet(rng=rng, Xd=x_in_sym, \\\n params=params, shared_param_dicts=None)\n p_s0_given_h.init_biases(0.0)\n #################\n # p_zi_given_xi #\n #################\n params = {}\n shared_config = [(x_dim + x_dim), 500, 500]\n top_config = [shared_config[-1], z_dim]\n params['shared_config'] = shared_config\n params['mu_config'] = top_config\n params['sigma_config'] = top_config\n params['activation'] = tanh_actfun #relu_actfun\n params['init_scale'] = init_scale\n params['vis_drop'] = 0.0\n params['hid_drop'] = 0.0\n params['bias_noise'] = 0.0\n params['input_noise'] = 0.0\n params['build_theano_funcs'] = False\n p_zi_given_xi = InfNet(rng=rng, Xd=x_in_sym, \\\n params=params, shared_param_dicts=None)\n p_zi_given_xi.init_biases(0.0)\n ###################\n # p_sip1_given_zi #\n ###################\n params = {}\n shared_config = [z_dim, 500, 500]\n output_config = [s_dim, s_dim, s_dim]\n params['shared_config'] = shared_config\n params['output_config'] = output_config\n params['activation'] = tanh_actfun #relu_actfun\n params['init_scale'] = init_scale\n params['vis_drop'] = 0.0\n params['hid_drop'] = 0.0\n params['bias_noise'] = 0.0\n params['input_noise'] = 0.0\n params['build_theano_funcs'] = False\n p_sip1_given_zi = HydraNet(rng=rng, Xd=x_in_sym, \\\n params=params, shared_param_dicts=None)\n p_sip1_given_zi.init_biases(0.0)\n ################\n # p_x_given_si #\n ################\n params = {}\n shared_config = [s_dim]\n output_config = [x_dim, x_dim]\n params['shared_config'] = shared_config\n params['output_config'] = output_config\n params['activation'] = tanh_actfun #relu_actfun\n params['init_scale'] = init_scale\n params['vis_drop'] = 0.0\n params['hid_drop'] = 0.0\n params['bias_noise'] = 0.0\n params['input_noise'] = 0.0\n params['build_theano_funcs'] = False\n p_x_given_si = HydraNet(rng=rng, Xd=x_in_sym, \\\n params=params, shared_param_dicts=None)\n p_x_given_si.init_biases(0.0)\n ###############\n # q_h_given_x #\n ###############\n params = {}\n shared_config = [x_dim, 250]\n top_config = [shared_config[-1], h_dim]\n params['shared_config'] = shared_config\n params['mu_config'] = top_config\n params['sigma_config'] = top_config\n params['activation'] = tanh_actfun #relu_actfun\n params['init_scale'] = 'xg' #init_scale\n params['vis_drop'] = 0.0", "answers": [" params['hid_drop'] = 0.0"], "length": 585, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "b1e7813b-3d8d-4b31-8cbc-e2c49e198504", "reasoning": "The code is defining the parameters for the q_h_given_x network. Following the pattern used for previous networks, after setting 'vis_drop' the next parameter to set is 'hid_drop' with a value of 0.0 before continuing with bias_noise, input_noise, etc.", "reasoning_model_answer": "params['hid_drop'] = 0.0", "assistant_with_reasoning": "\nThe code is defining the parameters for the q_h_given_x network. Following the pattern used for previous networks, after setting 'vis_drop' the next parameter to set is 'hid_drop' with a value of 0.0 before continuing with bias_noise, input_noise, etc.\n\nparams['hid_drop'] = 0.0", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 6.543, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 6587, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "params['hid_drop'] = 0.0", "score": 0.92, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "# Copyright 2015 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\n\"\"\"Gradient checker for any ops, graphs.\n\nThe gradient checker verifies numerically that an op/graph properly\ncomputes the gradients\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\n\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import gradients\nfrom tensorflow.python.platform import tf_logging as logging\n\n\ndef _product(t):\n if isinstance(t, int):\n return t\n else:\n y = 1\n for x in t:\n y *= x\n return y\n\n\ndef _compute_theoretical_jacobian(x, x_shape, x_data, dy, dy_shape, dx):\n \"\"\"Computes the theoretical Jacobian for dy/dx.\n\n Computes the theoretical Jacobian using the ops generated by\n compute_gradient().\n\n Args:\n x: the tensor \"x\".\n x_shape: the dimensions of x as a tuple or an array of ints.\n x_data: a numpy parray as the input data for x\n dy: the tensor \"dy\".\n dy_shape: the dimensions of dy as a tuple or an array of ints.\n dx: Tensor or IndexedSlices representing dx\n\n Returns:\n A 2-d numpy array representing the Jacobian for dy/dx. It has \"x_size\" rows\n and \"dy_size\" columns where \"x_size\" is the number of elements in x and\n \"dy_size\" is the number of elements in dy.\n\n Raises:\n ValueError: If `dy` is empty but the gradient is nonzero.\n \"\"\"\n # Complex vectors are treated as vectors of twice as many reals.\n if x.dtype.is_complex:\n x_shape = tuple(x_shape) + (2,)\n dy_factor = 2 if dy.dtype.is_complex else 1\n\n # To compute the jacobian, we treat x and y as one-dimensional vectors.\n x_size = _product(x_shape)\n x_val_size = _product(x_shape[1:]) # This is used for sparse gradients\n dy_size = _product(dy_shape) * dy_factor\n\n # Allocate 2-D Jacobian, with x dimensions smashed into the first\n # dimension and y dimensions smashed into the second.\n jacobian = np.zeros((x_size, dy_size),\n dtype=x.dtype.real_dtype.as_numpy_dtype)\n\n # For each of the entry of dy, we set this to be 1 and\n # everything else to be 0 and compute the backprop -- this will give us one\n # one column of the Jacobian matrix.\n dy_data = np.zeros(dy_shape, dtype=dy.dtype.as_numpy_dtype)\n dy_data_flat = dy_data.ravel().view(dy.dtype.real_dtype.as_numpy_dtype)\n sess = ops.get_default_session()\n for col in range(dy_size):\n dy_data_flat[col] = 1\n if isinstance(dx, ops.IndexedSlices):\n backprop_indices, backprop_values = sess.run(\n [dx.indices, dx.values], feed_dict={x: x_data, dy: dy_data})\n for i, v in zip(backprop_indices, backprop_values):\n r_begin = i * x_val_size\n r_end = r_begin + x_val_size\n jacobian[r_begin:r_end, col] += v.flat\n else:\n assert isinstance(dx, ops.Tensor), \"dx = \" + str(dx)\n backprop = sess.run(dx, feed_dict={x: x_data, dy: dy_data})\n jacobian[:, col] = backprop.ravel().view(jacobian.dtype)\n dy_data_flat[col] = 0\n\n # If the output is empty, run the gradients at least once and make sure\n # they produce zeros.\n if not dy_size:\n backprop = sess.run(dx, feed_dict={x: x_data, dy: dy_data})\n if backprop.shape != x_data.shape:\n raise ValueError(\"Empty gradient has wrong shape: expected %s, got %s\" %\n (x_data.shape, backprop.shape))\n if np.any(backprop):\n raise ValueError(\"Empty tensor with nonzero gradients\")\n\n logging.vlog(1, \"Theoretical Jacobian =\\n%s\", jacobian)\n return jacobian\n\n\ndef _compute_numeric_jacobian(x, x_shape, x_data, y, y_shape, delta):\n \"\"\"Computes the numeric Jacobian for dy/dx.\n\n Computes the numeric Jacobian by slightly perturbing the inputs and\n measuring the differences on the output.\n\n Args:\n x: the tensor \"x\".", "answers": [" x_shape: the dimensions of x as a tuple or an array of ints."], "length": 596, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "4765cbe2-ced9-4ab8-bcc8-45ee2da611aa", "reasoning": "The function _compute_numeric_jacobian has a docstring that lists its arguments. The last line shown is the first argument description \"x: the tensor \\\"x\\\".\" The next line should continue the Args section, describing the next parameter x_shape, matching the style used in the previous function's docstring.", "reasoning_model_answer": "x_shape: the dimensions of x as a tuple or an array of ints.", "assistant_with_reasoning": "\nThe function _compute_numeric_jacobian has a docstring that lists its arguments. The last line shown is the first argument description \"x: the tensor \\\"x\\\".\" The next line should continue the Args section, describing the next parameter x_shape, matching the style used in the previous function's docstring.\n\nx_shape: the dimensions of x as a tuple or an array of ints.", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.4, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 4622, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "x_shape: the dimensions of x as a tuple or an array of ints.", "score": 0.97, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "# Mantid Repository : https://github.com/mantidproject/mantid\n#\n# Copyright © 2018 ISIS Rutherford Appleton Laboratory UKRI,\n# NScD Oak Ridge National Laboratory, European Spallation Source\n# & Institut Laue - Langevin\n# SPDX - License - Identifier: GPL - 3.0 +\n# This file is part of the mantid workbench.\n#\n#\nfrom __future__ import absolute_import, absolute_import, division, division, print_function, print_function\n\nimport unittest\n\nimport qtpy\nfrom qtpy import QtCore\nfrom qtpy.QtCore import Qt\n\nfrom mantid.py3compat.mock import Mock, call\nfrom mantidqt.utils.testing.mocks.mock_mantid import AXIS_INDEX_FOR_HORIZONTAL, AXIS_INDEX_FOR_VERTICAL, MockMantidAxis, \\\n MockMantidSymbol, MockMantidUnit, MockSpectrum, MockWorkspace\nfrom mantidqt.utils.testing.mocks.mock_qt import MockQModelIndex\nfrom mantidqt.widgets.workspacedisplay.matrix.table_view_model import MatrixWorkspaceTableViewModel, \\\n MatrixWorkspaceTableViewModelType\n\n\ndef setup_common_for_test_data():\n \"\"\"\n Common configuration of variables and mocking for testing\n MatrixWorkspaceDisplayTableViewModel's data and headerData functions\n \"\"\"\n # Create some mock data for the mock workspace\n row = 2\n column = 2\n # make a workspace with 0s\n mock_data = [0] * 10\n # set one of them to be not 0\n mock_data[column] = 999\n model_type = MatrixWorkspaceTableViewModelType.x\n # pass onto the MockWorkspace so that it returns it when read from the TableViewModel\n ws = MockWorkspace(read_return=mock_data)\n ws.hasMaskedBins = Mock(return_value=True)\n ws.maskedBinsIndices = Mock(return_value=[column])\n model = MatrixWorkspaceTableViewModel(ws, model_type)\n # The model retrieves the spectrumInfo object, and our MockWorkspace has already given it\n # the MockSpectrumInfo, so all that needs to be done here is to set up the correct method Mocks\n model.ws_spectrum_info.hasDetectors = Mock(return_value=True)\n index = MockQModelIndex(row, column)\n return ws, model, row, index\n\n\nclass MatrixWorkspaceDisplayTableViewModelTest(unittest.TestCase):\n def test_correct_model_type(self):\n ws = MockWorkspace()\n model = MatrixWorkspaceTableViewModel(ws, MatrixWorkspaceTableViewModelType.x)\n self.assertEqual(model.type, MatrixWorkspaceTableViewModelType.x)\n\n model = MatrixWorkspaceTableViewModel(ws, MatrixWorkspaceTableViewModelType.y)\n self.assertEqual(model.type, MatrixWorkspaceTableViewModelType.y)\n\n model = MatrixWorkspaceTableViewModel(ws, MatrixWorkspaceTableViewModelType.e)\n self.assertEqual(model.type, MatrixWorkspaceTableViewModelType.e)\n\n def test_correct_cell_colors(self):\n ws = MockWorkspace()\n model = MatrixWorkspaceTableViewModel(ws, MatrixWorkspaceTableViewModelType.x)\n self.assertEqual((240, 240, 240, 255), model.masked_color.getRgb())\n self.assertEqual((255, 253, 209, 255), model.monitor_color.getRgb())\n\n def test_correct_relevant_data(self):\n ws = MockWorkspace()\n model = MatrixWorkspaceTableViewModel(ws, MatrixWorkspaceTableViewModelType.x)\n msg = \"The function is not set correctly! The wrong data will be read.\"\n self.assertEqual(ws.readX, model.relevant_data, msg=msg)\n model = MatrixWorkspaceTableViewModel(ws, MatrixWorkspaceTableViewModelType.y)\n self.assertEqual(ws.readY, model.relevant_data, msg=msg)\n model = MatrixWorkspaceTableViewModel(ws, MatrixWorkspaceTableViewModelType.e)\n self.assertEqual(ws.readE, model.relevant_data, msg=msg)\n\n def test_invalid_model_type(self):\n ws = MockWorkspace()\n with self.assertRaises(AssertionError):\n MatrixWorkspaceTableViewModel(ws, \"My Model Type\")\n\n def test_data_display_role(self):\n # Create some mock data for the mock workspace\n row = 2\n column = 2\n # make a workspace with 0s\n mock_data = [0] * 10\n # set one of them to be not 0\n mock_data[column] = 999\n # pass onto the MockWorkspace so that it returns it when read from the TableViewModel\n self._check_correct_data_is_displayed(MatrixWorkspaceTableViewModelType.x, column, mock_data, row)\n self._check_correct_data_is_displayed(MatrixWorkspaceTableViewModelType.y, column, mock_data, row)\n self._check_correct_data_is_displayed(MatrixWorkspaceTableViewModelType.e, column, mock_data, row)\n\n def _check_correct_data_is_displayed(self, model_type, column, mock_data, row):\n ws = MockWorkspace(read_return=mock_data)\n model = MatrixWorkspaceTableViewModel(ws, model_type)\n index = MockQModelIndex(row, column)\n output = model.data(index, Qt.DisplayRole)\n model.relevant_data.assert_called_once_with(row)\n self.assertEqual(str(mock_data[column]), output)\n\n def test_row_and_column_count(self):\n ws = MockWorkspace()\n model_type = MatrixWorkspaceTableViewModelType.x\n MatrixWorkspaceTableViewModel(ws, model_type)\n # these are called when the TableViewModel is initialised\n ws.getNumberHistograms.assert_called_once_with()\n ws.blocksize.assert_called_once_with()\n\n def test_data_background_role_masked_row(self):\n ws, model, row, index = setup_common_for_test_data()\n\n model.ws_spectrum_info.isMasked = Mock(return_value=True)\n\n output = model.data(index, Qt.BackgroundRole)\n\n model.ws_spectrum_info.hasDetectors.assert_called_once_with(row)\n model.ws_spectrum_info.isMasked.assert_called_once_with(row)\n\n index.row.assert_called_once_with()\n self.assertFalse(index.column.called)\n\n self.assertEqual(model.masked_color, output)\n\n # Just do it a second time -> This time it's cached and should be read off the cache.\n # If it is not read off the cache the assert_called_once below will fail,\n # as the functions would be called a 2nd time\n output = model.data(index, Qt.BackgroundRole)\n\n model.ws_spectrum_info.hasDetectors.assert_called_once_with(row)\n model.ws_spectrum_info.isMasked.assert_called_once_with(row)\n self.assertEqual(model.masked_color, output)\n\n # assert that the row was called twice with no parameters\n self.assertEqual(2, index.row.call_count)\n self.assertFalse(index.column.called)\n\n def test_data_background_role_monitor_row(self):\n ws, model, row, index = setup_common_for_test_data()\n\n model.ws_spectrum_info.isMasked = Mock(return_value=False)\n model.ws_spectrum_info.isMonitor = Mock(return_value=True)\n\n output = model.data(index, Qt.BackgroundRole)\n\n model.ws_spectrum_info.hasDetectors.assert_called_with(row)\n model.ws_spectrum_info.isMasked.assert_called_once_with(row)\n model.ws_spectrum_info.isMonitor.assert_called_once_with(row)\n\n index.row.assert_called_once_with()\n self.assertFalse(index.column.called)\n\n self.assertEqual(model.monitor_color, output)\n\n # Just do it a second time -> This time it's cached and should be read off the cache.\n # If it is not read off the cache the assert_called_once below will fail,\n # as the functions would be called a 2nd time\n output = model.data(index, Qt.BackgroundRole)\n\n model.ws_spectrum_info.hasDetectors.assert_called_with(row)\n # assert that it has been called twice with the same parameters\n model.ws_spectrum_info.isMasked.assert_has_calls([call.do_work(row), call.do_work(row)])\n # only called once, as the 2nd time should have hit the cached monitor\n model.ws_spectrum_info.isMonitor.assert_called_once_with(row)\n self.assertEqual(model.monitor_color, output)\n\n # assert that the row was called twice with no parameters", "answers": [" self.assertEqual(2, index.row.call_count)"], "length": 642, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "def9b9a7-34ea-43f0-a12f-059c26382c7e", "reasoning": "The test method is concluding by verifying that the mocked index object's row method was called twice, mirroring the earlier masked row test. The comment indicates this check, so the next line should be the assertion checking the call count of index.row.", "reasoning_model_answer": "self.assertEqual(2, index.row.call_count)", "assistant_with_reasoning": "\nThe test method is concluding by verifying that the mocked index object's row method was called twice, mirroring the earlier masked row test. The comment indicates this check, so the next line should be the assertion checking the call count of index.row.\n\nself.assertEqual(2, index.row.call_count)", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 2.547, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 7890, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "self.assertEqual(2, index.row.call_count)", "score": 0.91, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "//----------------------------------------------------------------------------\n// Anti-Grain Geometry - Version 2.4\n// Copyright (C) 2002-2005 Maxim Shemanarev (http://www.antigrain.com)\n//\n// C# port by: Lars Brubaker\n// larsbrubaker@gmail.com\n// Copyright (C) 2007\n//\n// Permission to copy, use, modify, sell and distribute this software\n// is granted provided this copyright notice appears in all copies.\n// This software is provided \"as is\" without express or implied\n// warranty, and with no claim as to its suitability for any purpose.\n//\n//----------------------------------------------------------------------------\n// Contact: mcseem@antigrain.com\n// mcseemagg@yahoo.com\n// http://www.antigrain.com\n//----------------------------------------------------------------------------\nusing System;\nusing System.Drawing;\nusing System.IO;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing System.Timers;\nusing System.Windows.Forms;\nusing MatterHackers.VectorMath;\n\nnamespace MatterHackers.Agg.UI\n{\n\tpublic abstract class WinformsSystemWindow : Form, IPlatformWindow\n\t{\n\t\tpublic static bool SingleWindowMode { get; set; } = false;\n\n\t\tpublic static bool EnableInputHook { get; set; } = true;\n\n\t\tpublic static bool ShowingSystemDialog { get; set; } = false;\n\n\t\tpublic static WinformsSystemWindow MainWindowsFormsWindow { get; private set; }\n\n\t\tpublic static Func InspectorCreator { get; set; }\n\n\t\tprivate static System.Timers.Timer idleCallBackTimer = null;\n\n\t\tprivate static bool processingOnIdle = false;\n\n\t\tprivate static readonly object SingleInvokeLock = new object();\n\n\t\tprotected WinformsEventSink EventSink;\n\n\t\tprivate SystemWindow _systemWindow;\n\t\tprivate int drawCount = 0;\n\t\tprivate int onPaintCount;\n\t\tprivate bool enableIdleProcessing;\n\n\t\tpublic SystemWindow AggSystemWindow\n\t\t{\n\t\t\tget => _systemWindow;\n\t\t\tset\n\t\t\t{\n\t\t\t\t_systemWindow = value;\n\n\t\t\t\tif (_systemWindow != null)\n\t\t\t\t{\n\t\t\t\t\tthis.Caption = _systemWindow.Title;\n\n\t\t\t\t\tif (SingleWindowMode)\n\t\t\t\t\t{\n\t\t\t\t\t\tif (firstWindow)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tthis.MinimumSize = _systemWindow.MinimumSize;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// Set this system window as the event target\n\t\t\t\t\t\tthis.EventSink?.SetActiveSystemWindow(_systemWindow);\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tthis.MinimumSize = _systemWindow.MinimumSize;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tpublic bool IsMainWindow { get; } = false;\n\n\t\tpublic bool IsInitialized { get; set; } = false;\n\n\t\tpublic WinformsSystemWindow()\n\t\t{\n\t\t\tif (idleCallBackTimer == null)\n\t\t\t{\n\t\t\t\tidleCallBackTimer = new System.Timers.Timer();\n\t\t\t\t// call up to 100 times a second\n\t\t\t\tidleCallBackTimer.Interval = 10;\n\t\t\t\tidleCallBackTimer.Elapsed += InvokePendingOnIdleActions;\n\t\t\t\tidleCallBackTimer.Start();\n\t\t\t}\n\n\t\t\t// Track first window\n\t\t\tif (MainWindowsFormsWindow == null)\n\t\t\t{\n\t\t\t\tMainWindowsFormsWindow = this;\n\t\t\t\tIsMainWindow = true;\n\t\t\t}\n\n\t\t\tthis.TitleBarHeight = RectangleToScreen(ClientRectangle).Top - this.Top;\n\t\t\tthis.AllowDrop = true;\n\n\t\t\tstring iconPath = File.Exists(\"application.ico\") ?\n\t\t\t\t\"application.ico\" :\n\t\t\t\t\"../MonoBundle/StaticData/application.ico\";\n\n\t\t\ttry\n\t\t\t{\n\t\t\t\tif (File.Exists(iconPath))\n\t\t\t\t{\n\t\t\t\t\tthis.Icon = new Icon(iconPath);\n\t\t\t\t}\n\t\t\t}\n\t\t\tcatch { }\n\t\t}\n\n\t\tprotected override void OnClosed(EventArgs e)\n\t\t{\n\t\t\tif (IsMainWindow)\n\t\t\t{\n\t\t\t\t// Ensure that when the MainWindow is closed, we null the field so we can recreate the MainWindow\n\t\t\t\tMainWindowsFormsWindow = null;\n\t\t\t}\n\n\t\t\tAggSystemWindow = null;\n\n\t\t\tbase.OnClosed(e);\n\t\t}\n\n\t\tpublic void ReleaseOnIdleGuard()\n\t\t{\n\t\t\tlock (SingleInvokeLock)\n\t\t\t{\n\t\t\t\tprocessingOnIdle = false;\n\t\t\t}\n\t\t}\n\n\t\tprivate void InvokePendingOnIdleActions(object sender, ElapsedEventArgs e)\n\t\t{\n\t\t\tif (!this.IsDisposed)\n\t\t\t{\n\t\t\t\tlock (SingleInvokeLock)\n\t\t\t\t{\n\t\t\t\t\tif (!enableIdleProcessing)\n\t\t\t\t\t{\n\t\t\t\t\t\t// There's a race between the idle timer calling this handler and the code to\n\t\t\t\t\t\t// start the main event loop. Reaching this handler first seems to cause the\n\t\t\t\t\t\t// app to get stuck when running the automation test suite on Linux.\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (processingOnIdle)\n\t\t\t\t\t{\n\t\t\t\t\t\t// If the pending invoke has not completed, skip the timer event\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tprocessingOnIdle = true;\n\t\t\t\t}\n\n\t\t\t\ttry\n\t\t\t\t{\n\t\t\t\t\tif (InvokeRequired)\n\t\t\t\t\t{\n\t\t\t\t\t\tInvoke(new Action(UiThread.InvokePendingActions));\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tUiThread.InvokePendingActions();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcatch (Exception ex)\n\t\t\t\t{\n\t\t\t\t\tConsole.WriteLine(ex.Message);\n\t\t\t\t}\n\t\t\t\tfinally\n\t\t\t\t{\n\t\t\t\t\tlock (SingleInvokeLock)\n\t\t\t\t\t{\n\t\t\t\t\t\tprocessingOnIdle = false;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tpublic abstract Graphics2D NewGraphics2D();\n\n\t\tprotected override void OnPaint(PaintEventArgs paintEventArgs)\n\t\t{\n\t\t\tif (AggSystemWindow == null\n\t\t\t\t|| AggSystemWindow.HasBeenClosed)\n\t\t\t{\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tbase.OnPaint(paintEventArgs);\n\n\t\t\tif (ShowingSystemDialog)\n\t\t\t{\n\t\t\t\t// We do this because calling Invalidate within an OnPaint message will cause our\n\t\t\t\t// SaveDialog to not show its 'overwrite' dialog if needed.\n\t\t\t\t// We use the Invalidate to cause a continuous pump of the OnPaint message to call our OnIdle.\n\t\t\t\t// We could figure another solution but it must be very careful to ensure we don't break SaveDialog\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (ClientSize.Width > 0 && ClientSize.Height > 0)\n\t\t\t{\n\t\t\t\tdrawCount++;\n\n\t\t\t\tvar graphics2D = this.NewGraphics2D();\n\n\t\t\t\tif (!SingleWindowMode)\n\t\t\t\t{\n\t\t\t\t\t// We must call on draw background as this is effectively our child and that is the way it is done in GuiWidget.\n\t\t\t\t\t// Parents call child OnDrawBackground before they call OnDraw", "answers": ["\t\t\t\t\tAggSystemWindow.OnDrawBackground(graphics2D);"], "length": 637, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "a40a5675-e875-499d-a736-1d118b55538d", "reasoning": "We are inside the OnPaint method. After creating a Graphics2D object, the code needs to render the window. In non‑single‑window mode, the typical sequence is to first draw the background of the child widget before drawing its contents. The comment explicitly mentions that parents call child OnDrawBackground before they call OnDraw. Therefore the next line should invoke the background drawing method on the AggSystemWindow, passing the current window and the graphics context.", "reasoning_model_answer": "AggSystemWindow.OnDrawBackground(this, graphics2D);", "assistant_with_reasoning": "\nWe are inside the OnPaint method. After creating a Graphics2D object, the code needs to render the window. In non‑single‑window mode, the typical sequence is to first draw the background of the child widget before drawing its contents. The comment explicitly mentions that parents call child OnDrawBackground before they call OnDraw. Therefore the next line should invoke the background drawing method on the AggSystemWindow, passing the current window and the graphics context.\n\nAggSystemWindow.OnDrawBackground(this, graphics2D);", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 2.657, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 5654, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "AggSystemWindow.OnDrawBackground(this, graphics2D);", "score": 0.89, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/*\n * Copyright 2015 Comcast Cable Communications Management, LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.comcast.cdn.traffic_control.traffic_router.core.router;\n\nimport java.io.IOException;\nimport java.net.InetAddress;\nimport java.net.MalformedURLException;\nimport java.net.URL;\nimport java.net.UnknownHostException;\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Random;\nimport java.util.Set;\nimport java.util.SortedMap;\nimport java.util.TreeMap;\n\nimport org.apache.commons.pool.ObjectPool;\nimport org.apache.log4j.Logger;\nimport org.json.JSONException;\nimport org.json.JSONObject;\nimport org.xbill.DNS.Name;\nimport org.xbill.DNS.Zone;\n\nimport com.comcast.cdn.traffic_control.traffic_router.core.TrafficRouterException;\nimport com.comcast.cdn.traffic_control.traffic_router.core.cache.Cache;\nimport com.comcast.cdn.traffic_control.traffic_router.core.cache.CacheLocation;\nimport com.comcast.cdn.traffic_control.traffic_router.core.cache.CacheRegister;\nimport com.comcast.cdn.traffic_control.traffic_router.core.cache.InetRecord;\nimport com.comcast.cdn.traffic_control.traffic_router.core.dns.ZoneManager;\nimport com.comcast.cdn.traffic_control.traffic_router.core.dns.DNSAccessRecord;\nimport com.comcast.cdn.traffic_control.traffic_router.core.ds.DeliveryService;\nimport com.comcast.cdn.traffic_control.traffic_router.core.ds.Dispersion;\nimport com.comcast.cdn.traffic_control.traffic_router.core.hash.HashFunction;\nimport com.comcast.cdn.traffic_control.traffic_router.core.loc.FederationRegistry;\nimport com.comcast.cdn.traffic_control.traffic_router.core.loc.Geolocation;\nimport com.comcast.cdn.traffic_control.traffic_router.core.loc.GeolocationException;\nimport com.comcast.cdn.traffic_control.traffic_router.core.loc.GeolocationService;\nimport com.comcast.cdn.traffic_control.traffic_router.core.loc.NetworkNode;\nimport com.comcast.cdn.traffic_control.traffic_router.core.loc.NetworkNodeException;\nimport com.comcast.cdn.traffic_control.traffic_router.core.request.DNSRequest;\nimport com.comcast.cdn.traffic_control.traffic_router.core.request.HTTPRequest;\nimport com.comcast.cdn.traffic_control.traffic_router.core.request.Request;\nimport com.comcast.cdn.traffic_control.traffic_router.core.router.StatTracker.Track;\nimport com.comcast.cdn.traffic_control.traffic_router.core.router.StatTracker.Track.ResultType;\nimport com.comcast.cdn.traffic_control.traffic_router.core.router.StatTracker.Track.RouteType;\nimport com.comcast.cdn.traffic_control.traffic_router.core.util.TrafficOpsUtils;\nimport com.comcast.cdn.traffic_control.traffic_router.core.util.CidrAddress;\nimport com.comcast.cdn.traffic_control.traffic_router.core.router.StatTracker.Track.ResultDetails;\n\npublic class TrafficRouter {\n\tpublic static final Logger LOGGER = Logger.getLogger(TrafficRouter.class);\n\n\tprivate final CacheRegister cacheRegister;\n\tprivate final ZoneManager zoneManager;\n\tprivate final GeolocationService geolocationService;\n\tprivate final GeolocationService geolocationService6;\n\tprivate final ObjectPool hashFunctionPool;\n\tprivate final FederationRegistry federationRegistry;\n\n\tprivate final Random random = new Random(System.nanoTime());\n\tprivate Set requestHeaders = new HashSet();\n\n\tpublic TrafficRouter(final CacheRegister cr, \n\t\t\tfinal GeolocationService geolocationService, \n\t\t\tfinal GeolocationService geolocationService6, \n\t\t\tfinal ObjectPool hashFunctionPool,\n\t\t\tfinal StatTracker statTracker,\n\t\t\tfinal TrafficOpsUtils trafficOpsUtils,\n\t\t\tfinal FederationRegistry federationRegistry) throws IOException, JSONException, TrafficRouterException {\n\t\tthis.cacheRegister = cr;\n\t\tthis.geolocationService = geolocationService;\n\t\tthis.geolocationService6 = geolocationService6;\n\t\tthis.hashFunctionPool = hashFunctionPool;\n\t\tthis.federationRegistry = federationRegistry;\n\t\tthis.zoneManager = new ZoneManager(this, statTracker, trafficOpsUtils);\n\t}\n\n\tpublic ZoneManager getZoneManager() {\n\t\treturn zoneManager;\n\t}\n\n\t/**\n\t * Returns a {@link List} of all of the online {@link Cache}s that support the specified\n\t * {@link DeliveryService}. If no online caches are found to support the specified\n\t * DeliveryService an empty list is returned.\n\t * \n\t * @param ds\n\t * the DeliveryService to check\n\t * @return collection of supported caches\n\t */\n\tprotected List getSupportingCaches(final List caches, final DeliveryService ds) {\n\t\tfor(int i = 0; i < caches.size(); i++) {\n\t\t\tfinal Cache cache = caches.get(i);\n\t\t\tboolean isAvailable = true;\n\t\t\tif(cache.hasAuthority()) {\n\t\t\t\tisAvailable = cache.isAvailable();\n\t\t\t}\n\t\t\tif (!isAvailable || !cache.hasDeliveryService(ds.getId())) {\n\t\t\t\tcaches.remove(i);\n\t\t\t\ti--;\n\t\t\t}\n\t\t}\n\t\treturn caches;\n\t}\n\n\tpublic CacheRegister getCacheRegister() {\n\t\treturn cacheRegister;\n\t}\n\tprotected DeliveryService selectDeliveryService(final Request request, final boolean isHttp) {\n\t\tif(cacheRegister==null) {\n\t\t\tLOGGER.warn(\"no caches yet\");\n\t\t\treturn null;\n\t\t}\n\t\tfinal DeliveryService ds = cacheRegister.getDeliveryService(request, isHttp);\n\t\tif (LOGGER.isDebugEnabled()) {\n\t\t\tLOGGER.debug(\"Selected DeliveryService: \" + ds);\n\t\t}\n\t\treturn ds;\n\t}\n\n\tboolean setState(final JSONObject states) throws UnknownHostException {\n\t\tsetCacheStates(states.optJSONObject(\"caches\"));\n\t\tsetDsStates(states.optJSONObject(\"deliveryServices\"));\n\t\treturn true;\n\t}\n\tprivate boolean setDsStates(final JSONObject dsStates) {\n\t\tif(dsStates == null) {\n\t\t\treturn false;\n\t\t}\n\t\tfinal Map dsMap = cacheRegister.getDeliveryServices();\n\t\tfor (final String dsName : dsMap.keySet()) {\n\t\t\tdsMap.get(dsName).setState(dsStates.optJSONObject(dsName));\n\t\t}\n\t\treturn true;\n\t}\n\tprivate boolean setCacheStates(final JSONObject cacheStates) {\n\t\tif(cacheStates == null) {\n\t\t\treturn false;\n\t\t}\n\t\tfinal Map cacheMap = cacheRegister.getCacheMap();\n\t\tif(cacheMap == null) { return false; }\n\t\tfor (final String cacheName : cacheMap.keySet()) {\n\t\t\tfinal String monitorCacheName = cacheName.replaceFirst(\"@.*\", \"\");\n\t\t\tfinal JSONObject state = cacheStates.optJSONObject(monitorCacheName);\n\t\t\tcacheMap.get(cacheName).setState(state);\n\t\t}\n\t\treturn true;\n\t}\n\n\tprotected static final String UNABLE_TO_ROUTE_REQUEST = \"Unable to route request.\";\n\tprotected static final String URL_ERR_STR = \"Unable to create URL.\";\n\n\tpublic GeolocationService getGeolocationService() {\n\t\treturn geolocationService;\n\t}\n\tpublic Geolocation getLocation(final String clientIP) throws GeolocationException {\n\t\tif(clientIP.contains(\":\")) {\n\t\t\treturn geolocationService6.location(clientIP);\n\t\t}\n\t\treturn geolocationService.location(clientIP);\n\t}\n\n\t/**\n\t * Gets hashFunctionPool.\n\t * \n\t * @return the hashFunctionPool\n\t */\n\tpublic ObjectPool getHashFunctionPool() {", "answers": ["\t\treturn hashFunctionPool;"], "length": 594, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "b1008dc7-ec36-4b85-b7d6-edc59d85bc10", "reasoning": "The method getHashFunctionPool() is a getter for the private field hashFunctionPool. After the opening brace, the typical implementation is to return that field. Therefore the next line should be the return statement returning hashFunctionPool.", "reasoning_model_answer": "return hashFunctionPool;", "assistant_with_reasoning": "\nThe method getHashFunctionPool() is a getter for the private field hashFunctionPool. After the opening brace, the typical implementation is to return that field. Therefore the next line should be the return statement returning hashFunctionPool.\n\nreturn hashFunctionPool;", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 1.595, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 7465, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "return hashFunctionPool;", "score": 0.96, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/*******************************************************************************\n * Copyright (c) 2011-2014 SirSengir.\n * All rights reserved. This program and the accompanying materials\n * are made available under the terms of the GNU Lesser Public License v3\n * which accompanies this distribution, and is available at\n * http://www.gnu.org/licenses/gpl-3.0.txt\n * \n * Various Contributors including, but not limited to:\n * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges\n ******************************************************************************/\npackage forestry.factory.gadgets;\n\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Map.Entry;\nimport java.util.Stack;\n\nimport net.minecraft.entity.player.EntityPlayer;\nimport net.minecraft.inventory.Container;\nimport net.minecraft.inventory.ICrafting;\nimport net.minecraft.inventory.IInventory;\nimport net.minecraft.item.ItemStack;\nimport net.minecraft.nbt.NBTTagCompound;\nimport net.minecraft.nbt.NBTTagList;\nimport net.minecraft.tileentity.TileEntity;\nimport net.minecraftforge.common.ForgeDirection;\nimport net.minecraftforge.liquids.ILiquidTank;\nimport net.minecraftforge.liquids.LiquidContainerData;\nimport net.minecraftforge.liquids.LiquidStack;\nimport buildcraft.api.gates.ITrigger;\nimport forestry.api.core.ForestryAPI;\nimport forestry.api.recipes.ISqueezerManager;\nimport forestry.core.EnumErrorCode;\nimport forestry.core.config.Config;\nimport forestry.core.config.Defaults;\nimport forestry.core.gadgets.Machine;\nimport forestry.core.gadgets.MachineFactory;\nimport forestry.core.gadgets.TileMachine;\nimport forestry.core.network.EntityNetData;\nimport forestry.core.network.GuiId;\nimport forestry.core.triggers.ForestryTrigger;\nimport forestry.core.utils.EnumTankLevel;\nimport forestry.core.utils.LiquidHelper;\nimport forestry.core.utils.StringUtil;\nimport forestry.core.utils.TankSlot;\nimport forestry.core.utils.Utils;\n\npublic class MachineSqueezer extends Machine {\n\n\t/**\n\t * Factory class to produce new {@link MachineSqueezer}s.\n\t */\n\tpublic static class Factory extends MachineFactory {\n\t\t@Override\n\t\tpublic Machine createMachine(TileEntity tile) {\n\t\t\treturn new MachineSqueezer((TileMachine) tile);\n\t\t}\n\t}\n\n\t// / RECIPE MANAGMENT\n\tpublic static class Recipe {\n\t\tpublic final int timePerItem;\n\t\tpublic final ItemStack[] resources;\n\t\tpublic final LiquidStack liquid;\n\t\tpublic final ItemStack remnants;\n\t\tpublic final int chance;\n\n\t\tpublic Recipe(int timePerItem, ItemStack[] resources, LiquidStack liquid, ItemStack remnants, int chance) {\n\t\t\tthis.timePerItem = timePerItem;\n\t\t\tthis.resources = resources;\n\t\t\tthis.liquid = liquid;\n\t\t\tthis.remnants = remnants;\n\t\t\tthis.chance = chance;\n\t\t}\n\n\t\tpublic boolean matches(ItemStack[] res) {\n\t\t\t// No recipe without resource!\n\t\t\tif (res == null || res.length <= 0)\n\t\t\t\treturn false;\n\n\t\t\tboolean matchedAll = true;\n\n\t\t\tfor (ItemStack stack : resources) {\n\t\t\t\tboolean matched = false;\n\t\t\t\tfor (ItemStack matchStack : res) {\n\t\t\t\t\tif (matchStack == null) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\t// If the item matches, we need enough items\n\t\t\t\t\tif (matchStack.isItemEqual(stack))\n\t\t\t\t\t\tif (matchStack.stackSize >= stack.stackSize) {\n\t\t\t\t\t\t\tmatched = true;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (!matched) {\n\t\t\t\t\tmatchedAll = false;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn matchedAll;\n\t\t}\n\t}\n\n\tpublic static class RecipeManager implements ISqueezerManager {\n\t\tpublic static ArrayList recipes = new ArrayList();\n\n\t\t@Override\n\t\tpublic void addRecipe(int timePerItem, ItemStack[] resources, LiquidStack liquid, ItemStack remnants, int chance) {\n\t\t\trecipes.add(new MachineSqueezer.Recipe(timePerItem, resources, liquid, remnants, chance));\n\t\t}\n\n\t\t@Override\n\t\tpublic void addRecipe(int timePerItem, ItemStack[] resources, LiquidStack liquid) {\n\t\t\taddRecipe(timePerItem, resources, liquid, null, 0);\n\t\t}\n\n\t\tpublic static Recipe findMatchingRecipe(ItemStack[] items) {\n\t\t\tfor (int i = 0; i < recipes.size(); i++) {\n\t\t\t\tRecipe recipe = recipes.get(i);\n\t\t\t\tif (recipe.matches(items))\n\t\t\t\t\treturn recipe;\n\t\t\t}\n\t\t\treturn null;\n\t\t}\n\n\t\t@Override\n\t\tpublic List> getRecipes() {\n\t\t\tHashMap recipeList = new HashMap();\n\n\t\t\tfor (Recipe recipe : recipes) {\n\t\t\t\trecipeList.put(recipe.resources, new ItemStack[] { recipe.remnants, recipe.liquid.asItemStack() });\n\t\t\t}\n\n\t\t\treturn (List>) recipeList;\n\t\t}\n\t}\n\n\t// / MEMBER\n\t@EntityNetData\n\tpublic TankSlot productTank = new TankSlot(Defaults.PROCESSOR_TANK_CAPACITY);\n\tprivate ItemStack[] inventoryStacks = new ItemStack[12];\n\tprivate Recipe currentRecipe;\n\n\tprivate short resourceSlot1 = 0;\n\tprivate short remnantSlot = 9;\n\tprivate short canSlot = 10;\n\tprivate short outputSlot = 11;\n\n\tprivate Stack pendingLiquids = new Stack();\n\tprivate Stack pendingRemnants = new Stack();\n\tprivate int productionTime;\n\tprivate int timePerItem;\n\n\tpublic MachineSqueezer(TileMachine tile) {\n\t\tsuper(tile);\n\t\tsetHints(Config.hints.get(\"squeezer\"));\n\t}\n\n\t@Override\n\tpublic String getName() {\n\t\treturn StringUtil.localize(\"tile.machine.9\");\n\t}\n\n\t@Override\n\tpublic void openGui(EntityPlayer player, IInventory tile) {\n\t\tplayer.openGui(ForestryAPI.instance, GuiId.SqueezerGUI.ordinal(), player.worldObj, this.tile.xCoord, this.tile.yCoord, this.tile.zCoord);\n\t}\n\n\t// / LOADING & SAVING\n\t@Override\n\tpublic void writeToNBT(NBTTagCompound nbttagcompound) {\n\t\tsuper.writeToNBT(nbttagcompound);\n\n\t\tnbttagcompound.setInteger(\"ProductionTime\", productionTime);\n\t\tnbttagcompound.setInteger(\"TimePerItem\", timePerItem);\n\n\t\t// Inventory\n\t\tNBTTagList nbttaglist = new NBTTagList();\n\t\tfor (int i = 0; i < inventoryStacks.length; i++)\n\t\t\tif (inventoryStacks[i] != null) {\n\t\t\t\tNBTTagCompound nbttagcompound1 = new NBTTagCompound();\n\t\t\t\tnbttagcompound1.setByte(\"Slot\", (byte) i);\n\t\t\t\tinventoryStacks[i].writeToNBT(nbttagcompound1);\n\t\t\t\tnbttaglist.appendTag(nbttagcompound1);\n\t\t\t}\n\t\tnbttagcompound.setTag(\"Items\", nbttaglist);\n\n\t\t// Pending remnants\n\t\tnbttaglist = new NBTTagList();\n\t\tItemStack[] remnants = pendingRemnants.toArray(new ItemStack[pendingRemnants.size()]);\n\t\tfor (int i = 0; i < remnants.length; i++)\n\t\t\tif (remnants[i] != null) {\n\t\t\t\tNBTTagCompound nbttagcompound1 = new NBTTagCompound();\n\t\t\t\tnbttagcompound1.setByte(\"Slot\", (byte) i);\n\t\t\t\tremnants[i].writeToNBT(nbttagcompound1);\n\t\t\t\tnbttaglist.appendTag(nbttagcompound1);\n\t\t\t}\n\t\tnbttagcompound.setTag(\"PendingRemnants\", nbttaglist);\n\n\t\t// Pending liquids\n\t\tnbttaglist = new NBTTagList();\n\t\tLiquidStack[] liquids = pendingLiquids.toArray(new LiquidStack[pendingLiquids.size()]);\n\t\tfor (int i = 0; i < liquids.length; i++)\n\t\t\tif (liquids[i] != null) {\n\t\t\t\tNBTTagCompound nbttagcompound1 = new NBTTagCompound();", "answers": ["\t\t\t\tnbttagcompound1.setByte(\"Slot\", (byte) i);"], "length": 628, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "8d2155e4-e632-4ebf-9db9-37885691081e", "reasoning": "The code is inside writeToNBT, handling pending liquids similarly to inventory and pending remnants. Inside the for-loop, after creating a new NBTTagCompound, the next operation is to record the slot index. Following the pattern, the line should set the \"Slot\" byte to the loop index.", "reasoning_model_answer": "nbttagcompound1.setByte(\"Slot\", (byte) i);", "assistant_with_reasoning": "\nThe code is inside writeToNBT, handling pending liquids similarly to inventory and pending remnants. Inside the for-loop, after creating a new NBTTagCompound, the next operation is to record the slot index. Following the pattern, the line should set the \"Slot\" byte to the loop index.\n\nnbttagcompound1.setByte(\"Slot\", (byte) i);", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.081, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 6945, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "nbttagcompound1.setByte(\"Slot\", (byte) i);", "score": 0.95, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": " # -*- coding: utf-8 -*-\n'''\nTest Vincent.charts\n-------------------\n\nTests for Vincent chart types, which also serve as reference grammar.\n\n'''\n\nimport pandas as pd\nimport nose.tools as nt\nfrom vincent.charts import (data_type, Chart, Bar, Scatter, Line, Area,\n StackedArea, StackedBar, GroupedBar, Map, Pie)\n\n\ndef chart_runner(chart, scales, axes, marks):\n 'Iterate through each chart element for check for contents'\n\n for i, scale in enumerate(scales):\n nt.assert_dict_equal(chart.scales[i].grammar(), scale)\n\n for i, axis in enumerate(axes):\n nt.assert_dict_equal(chart.axes[i].grammar(), axis)\n\n for i, mark in enumerate(marks):\n nt.assert_dict_equal(chart.marks[i].grammar(), mark)\n\n\ndef test_data_type():\n 'Test automatic data type importing'\n\n puts1 = [10, 20, 30, 40, 50]\n puts2 = {'apples': 10, 'bananas': 20, 'oranges': 30}\n\n gets1 = [{'col': 'data', 'idx': 0, 'val': 10},\n {'col': 'data', 'idx': 1, 'val': 20},\n {'col': 'data', 'idx': 2, 'val': 30},\n {'col': 'data', 'idx': 3, 'val': 40},\n {'col': 'data', 'idx': 4, 'val': 50}]\n gets2 = [{'col': 'data', 'idx': 'apples', 'val': 10},\n {'col': 'data', 'idx': 'bananas', 'val': 20},\n {'col': 'data', 'idx': 'oranges', 'val': 30}]\n\n for ins, outs in zip([puts1, puts2], [gets1, gets2]):\n test = data_type(ins)\n nt.assert_list_equal(test.values, outs)\n\n #From Iters\n puts = {'x': [1, 2, 3], 'y': [10, 20, 30], 'z': [40, 50, 60]}\n gets = [{'col': 'y', 'idx': 1, 'val': 10},\n {'col': 'y', 'idx': 2, 'val': 20},\n {'col': 'y', 'idx': 3, 'val': 30},\n {'col': 'z', 'idx': 1, 'val': 40},\n {'col': 'z', 'idx': 2, 'val': 50},\n {'col': 'z', 'idx': 3, 'val': 60}]\n\n test = data_type(puts, iter_idx='x')\n nt.assert_list_equal(test.values, gets)\n\n #Pandas\n df = pd.DataFrame({'one': [1, 2, 3], 'two': [4, 5, 6]})\n series = pd.Series([1, 2, 3], name='test')\n gets1 = [{'col': 'one', 'idx': 0, 'val': 1},\n {'col': 'two', 'idx': 0, 'val': 4},\n {'col': 'one', 'idx': 1, 'val': 2},\n {'col': 'two', 'idx': 1, 'val': 5},\n {'col': 'one', 'idx': 2, 'val': 3},\n {'col': 'two', 'idx': 2, 'val': 6}]\n gets2 = [{'col': 'test', 'idx': 0, 'val': 1},\n {'col': 'test', 'idx': 1, 'val': 2},\n {'col': 'test', 'idx': 2, 'val': 3}]\n test_df = data_type(df)\n test_series = data_type(series)\n nt.assert_list_equal(test_df.values, gets1)\n nt.assert_list_equal(test_series.values, gets2)\n\n #Bad type\n class BadType(object):\n 'Bad data type'\n pass\n\n test = BadType()\n nt.assert_raises(ValueError, data_type, test)\n\n\nclass TestChart(object):\n 'Test Chart ABC'\n\n def test_init(self):\n chart = Chart([0, 1], width=100, height=100)\n nt.assert_equal(chart.width, 100)\n nt.assert_equal(chart.height, 100)\n padding = \"auto\"\n nt.assert_equal(chart.padding, padding)\n\n #Data loading errors\n nt.assert_raises(ValueError, Chart)\n nt.assert_raises(ValueError, Chart, [])\n\n\nclass TestBar(object):\n 'Test Bar Chart'\n\n def test_init(self):\n bar = Bar([1, 2, 3])\n\n scales = [{'domain': {'data': 'table', 'field': 'data.idx'},\n 'name': 'x',\n 'range': 'width',\n 'type': 'ordinal'},\n {'domain': {'data': 'table', 'field': 'data.val'},\n 'name': 'y',\n 'nice': True,\n 'range': 'height'}]\n\n axes = [{'scale': 'x', 'type': 'x'},\n {'scale': 'y', 'type': 'y'}]\n\n marks = [{'from': {'data': 'table'},\n 'properties': {'enter': {'width': {'band': True,\n 'offset': -1,\n 'scale': 'x'},\n 'x': {'field': 'data.idx', 'scale': 'x'},\n 'y': {'field': 'data.val', 'scale': 'y'},\n 'y2': {'scale': 'y', 'value': 0}},\n 'update': {'fill': {'value': 'steelblue'}}},\n 'type': 'rect'}]\n\n chart_runner(bar, scales, axes, marks)\n\n\nclass TestScatter(object):\n 'Test Scatter Chart'\n\n def test_init(self):\n\n scatter = Scatter([1, 2, 3])\n\n scales = [{'domain': {'data': 'table', 'field': 'data.idx'},\n 'name': 'x',\n 'range': 'width',\n 'type': 'linear'},\n {'domain': {'data': 'table', 'field': 'data.val'},\n 'name': 'y',\n 'type': 'linear',\n 'range': 'height',\n 'nice': True},\n {'domain': {'data': 'table', 'field': 'data.col'},\n 'name': 'color',\n 'range': 'category20',\n 'type': 'ordinal'}]\n\n axes = [{'scale': 'x', 'type': 'x'},\n {'scale': 'y', 'type': 'y'}]\n\n marks = [{'from': {'data': 'table',\n 'transform': [{'keys': ['data.col'], 'type': 'facet'}]},\n 'marks':\n [{'properties': {'enter': {'fill': {'field': 'data.col',\n 'scale': 'color'},\n 'size': {'value': 100},\n 'x': {'field': 'data.idx', 'scale': 'x'},\n 'y': {'field': 'data.val', 'scale': 'y'}}},\n 'type': 'symbol'}],\n 'type': 'group'}]\n\n chart_runner(scatter, scales, axes, marks)\n\n\nclass TestLine(object):\n 'Test Line Chart'\n\n def test_init(self):\n line = Line([1, 2, 3])\n\n scales = [{'domain': {'data': 'table', 'field': 'data.idx'},\n 'name': 'x',\n 'range': 'width',\n 'type': 'linear'},\n {'domain': {'data': 'table', 'field': 'data.val'},\n 'name': 'y',\n 'type': 'linear',\n 'nice': True,\n 'range': 'height'},\n {'domain': {'data': 'table', 'field': 'data.col'},\n 'name': 'color',\n 'range': 'category20',\n 'type': 'ordinal'}]\n\n axes = [{'scale': 'x', 'type': 'x'},\n {'scale': 'y', 'type': 'y'}]\n\n marks = [{'from': {'data': 'table',\n 'transform': [{'keys': ['data.col'], 'type': 'facet'}]},\n 'marks':\n [{'properties': {'enter': {'stroke': {'field': 'data.col',\n 'scale': 'color'},\n 'strokeWidth': {'value': 2},\n 'x': {'field': 'data.idx', 'scale': 'x'},\n 'y': {'field': 'data.val', 'scale': 'y'}}},\n 'type': 'line'}],\n 'type': 'group'}]\n\n chart_runner(line, scales, axes, marks)", "answers": ["class TestArea(object):"], "length": 640, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "bc908ee3-4f2f-42aa-8816-967353c16de6", "reasoning": "The snippet ends the test_init method of TestLine with a call to chart_runner. The method then closes, the class ends, and the next logical code block in the test suite is the definition of the next test class, which is for the Area chart. Therefore the next line of code is the class definition for TestArea.", "reasoning_model_answer": "class TestArea(object):", "assistant_with_reasoning": "\nThe snippet ends the test_init method of TestLine with a call to chart_runner. The method then closes, the class ends, and the next logical code block in the test suite is the definition of the next test class, which is for the Area chart. Therefore the next line of code is the class definition for TestArea.\n\nclass TestArea(object):", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.223, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 7007, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "class TestArea(object):", "score": 1.0, "is_full_score": true, "is_nonzero_score": true}} {"input": "", "context": "// Generated by the protocol buffer compiler. DO NOT EDIT!\n// source: google/cloud/dataproc/v1/operations.proto\n#pragma warning disable 1591, 0612, 3021\n#region Designer generated code\n\nusing pb = global::Google.Protobuf;\nusing pbc = global::Google.Protobuf.Collections;\nusing pbr = global::Google.Protobuf.Reflection;\nusing scg = global::System.Collections.Generic;\nnamespace Google.Cloud.Dataproc.V1 {\n\n /// Holder for reflection information generated from google/cloud/dataproc/v1/operations.proto\n public static partial class OperationsReflection {\n\n #region Descriptor\n /// File descriptor for google/cloud/dataproc/v1/operations.proto\n public static pbr::FileDescriptor Descriptor {\n get { return descriptor; }\n }\n private static pbr::FileDescriptor descriptor;\n\n static OperationsReflection() {\n byte[] descriptorData = global::System.Convert.FromBase64String(\n string.Concat(\n \"Cilnb29nbGUvY2xvdWQvZGF0YXByb2MvdjEvb3BlcmF0aW9ucy5wcm90bxIY\",\n \"Z29vZ2xlLmNsb3VkLmRhdGFwcm9jLnYxGhxnb29nbGUvYXBpL2Fubm90YXRp\",\n \"b25zLnByb3RvGiNnb29nbGUvbG9uZ3J1bm5pbmcvb3BlcmF0aW9ucy5wcm90\",\n \"bxobZ29vZ2xlL3Byb3RvYnVmL2VtcHR5LnByb3RvGh9nb29nbGUvcHJvdG9i\",\n \"dWYvdGltZXN0YW1wLnByb3RvIvUBChZDbHVzdGVyT3BlcmF0aW9uU3RhdHVz\",\n \"EkUKBXN0YXRlGAEgASgOMjYuZ29vZ2xlLmNsb3VkLmRhdGFwcm9jLnYxLkNs\",\n \"dXN0ZXJPcGVyYXRpb25TdGF0dXMuU3RhdGUSEwoLaW5uZXJfc3RhdGUYAiAB\",\n \"KAkSDwoHZGV0YWlscxgDIAEoCRI0ChBzdGF0ZV9zdGFydF90aW1lGAQgASgL\",\n \"MhouZ29vZ2xlLnByb3RvYnVmLlRpbWVzdGFtcCI4CgVTdGF0ZRILCgdVTktO\",\n \"T1dOEAASCwoHUEVORElORxABEgsKB1JVTk5JTkcQAhIICgRET05FEAMikAMK\",\n \"GENsdXN0ZXJPcGVyYXRpb25NZXRhZGF0YRIUCgxjbHVzdGVyX25hbWUYByAB\",\n \"KAkSFAoMY2x1c3Rlcl91dWlkGAggASgJEkAKBnN0YXR1cxgJIAEoCzIwLmdv\",\n \"b2dsZS5jbG91ZC5kYXRhcHJvYy52MS5DbHVzdGVyT3BlcmF0aW9uU3RhdHVz\",\n \"EkgKDnN0YXR1c19oaXN0b3J5GAogAygLMjAuZ29vZ2xlLmNsb3VkLmRhdGFw\",\n \"cm9jLnYxLkNsdXN0ZXJPcGVyYXRpb25TdGF0dXMSFgoOb3BlcmF0aW9uX3R5\",\n \"cGUYCyABKAkSEwoLZGVzY3JpcHRpb24YDCABKAkSTgoGbGFiZWxzGA0gAygL\",\n \"Mj4uZ29vZ2xlLmNsb3VkLmRhdGFwcm9jLnYxLkNsdXN0ZXJPcGVyYXRpb25N\",\n \"ZXRhZGF0YS5MYWJlbHNFbnRyeRIQCgh3YXJuaW5ncxgOIAMoCRotCgtMYWJl\",\n \"bHNFbnRyeRILCgNrZXkYASABKAkSDQoFdmFsdWUYAiABKAk6AjgBQnMKHGNv\",\n \"bS5nb29nbGUuY2xvdWQuZGF0YXByb2MudjFCD09wZXJhdGlvbnNQcm90b1AB\",\n \"WkBnb29nbGUuZ29sYW5nLm9yZy9nZW5wcm90by9nb29nbGVhcGlzL2Nsb3Vk\",\n \"L2RhdGFwcm9jL3YxO2RhdGFwcm9jYgZwcm90bzM=\"));\n descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,\n new pbr::FileDescriptor[] { global::Google.Api.AnnotationsReflection.Descriptor, global::Google.LongRunning.OperationsReflection.Descriptor, global::Google.Protobuf.WellKnownTypes.EmptyReflection.Descriptor, global::Google.Protobuf.WellKnownTypes.TimestampReflection.Descriptor, },\n new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {\n new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Dataproc.V1.ClusterOperationStatus), global::Google.Cloud.Dataproc.V1.ClusterOperationStatus.Parser, new[]{ \"State\", \"InnerState\", \"Details\", \"StateStartTime\" }, null, new[]{ typeof(global::Google.Cloud.Dataproc.V1.ClusterOperationStatus.Types.State) }, null),\n new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Dataproc.V1.ClusterOperationMetadata), global::Google.Cloud.Dataproc.V1.ClusterOperationMetadata.Parser, new[]{ \"ClusterName\", \"ClusterUuid\", \"Status\", \"StatusHistory\", \"OperationType\", \"Description\", \"Labels\", \"Warnings\" }, null, null, new pbr::GeneratedClrTypeInfo[] { null, })\n }));\n }\n #endregion\n\n }\n #region Messages\n /// \n /// The status of the operation.\n /// \n public sealed partial class ClusterOperationStatus : pb::IMessage {\n private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new ClusterOperationStatus());\n [global::System.Diagnostics.DebuggerNonUserCodeAttribute]\n public static pb::MessageParser Parser { get { return _parser; } }\n\n [global::System.Diagnostics.DebuggerNonUserCodeAttribute]\n public static pbr::MessageDescriptor Descriptor {\n get { return global::Google.Cloud.Dataproc.V1.OperationsReflection.Descriptor.MessageTypes[0]; }\n }\n\n [global::System.Diagnostics.DebuggerNonUserCodeAttribute]\n pbr::MessageDescriptor pb::IMessage.Descriptor {\n get { return Descriptor; }\n }\n\n [global::System.Diagnostics.DebuggerNonUserCodeAttribute]\n public ClusterOperationStatus() {\n OnConstruction();\n }\n\n partial void OnConstruction();\n\n [global::System.Diagnostics.DebuggerNonUserCodeAttribute]\n public ClusterOperationStatus(ClusterOperationStatus other) : this() {\n state_ = other.state_;\n innerState_ = other.innerState_;\n details_ = other.details_;\n StateStartTime = other.stateStartTime_ != null ? other.StateStartTime.Clone() : null;\n }\n\n [global::System.Diagnostics.DebuggerNonUserCodeAttribute]\n public ClusterOperationStatus Clone() {\n return new ClusterOperationStatus(this);\n }\n\n /// Field number for the \"state\" field.\n public const int StateFieldNumber = 1;\n private global::Google.Cloud.Dataproc.V1.ClusterOperationStatus.Types.State state_ = 0;\n /// \n /// Output-only. A message containing the operation state.\n /// \n [global::System.Diagnostics.DebuggerNonUserCodeAttribute]\n public global::Google.Cloud.Dataproc.V1.ClusterOperationStatus.Types.State State {\n get { return state_; }\n set {\n state_ = value;\n }\n }\n\n /// Field number for the \"inner_state\" field.\n public const int InnerStateFieldNumber = 2;\n private string innerState_ = \"\";\n /// \n /// Output-only. A message containing the detailed operation state.\n /// \n [global::System.Diagnostics.DebuggerNonUserCodeAttribute]\n public string InnerState {\n get { return innerState_; }\n set {\n innerState_ = pb::ProtoPreconditions.CheckNotNull(value, \"value\");\n }\n }\n\n /// Field number for the \"details\" field.\n public const int DetailsFieldNumber = 3;\n private string details_ = \"\";\n /// \n /// Output-only.A message containing any operation metadata details.\n /// \n [global::System.Diagnostics.DebuggerNonUserCodeAttribute]\n public string Details {\n get { return details_; }\n set {\n details_ = pb::ProtoPreconditions.CheckNotNull(value, \"value\");\n }\n }\n\n /// Field number for the \"state_start_time\" field.\n public const int StateStartTimeFieldNumber = 4;\n private global::Google.Protobuf.WellKnownTypes.Timestamp stateStartTime_;\n /// \n /// Output-only. The time this state was entered.\n /// \n [global::System.Diagnostics.DebuggerNonUserCodeAttribute]\n public global::Google.Protobuf.WellKnownTypes.Timestamp StateStartTime {\n get { return stateStartTime_; }\n set {\n stateStartTime_ = value;\n }\n }\n\n [global::System.Diagnostics.DebuggerNonUserCodeAttribute]\n public override bool Equals(object other) {\n return Equals(other as ClusterOperationStatus);\n }\n\n [global::System.Diagnostics.DebuggerNonUserCodeAttribute]\n public bool Equals(ClusterOperationStatus other) {\n if (ReferenceEquals(other, null)) {\n return false;\n }\n if (ReferenceEquals(other, this)) {\n return true;\n }\n if (State != other.State) return false;\n if (InnerState != other.InnerState) return false;\n if (Details != other.Details) return false;\n if (!object.Equals(StateStartTime, other.StateStartTime)) return false;\n return true;\n }\n\n [global::System.Diagnostics.DebuggerNonUserCodeAttribute]\n public override int GetHashCode() {\n int hash = 1;\n if (State != 0) hash ^= State.GetHashCode();\n if (InnerState.Length != 0) hash ^= InnerState.GetHashCode();\n if (Details.Length != 0) hash ^= Details.GetHashCode();\n if (stateStartTime_ != null) hash ^= StateStartTime.GetHashCode();\n return hash;\n }\n\n [global::System.Diagnostics.DebuggerNonUserCodeAttribute]\n public override string ToString() {\n return pb::JsonFormatter.ToDiagnosticString(this);\n }\n\n [global::System.Diagnostics.DebuggerNonUserCodeAttribute]\n public void WriteTo(pb::CodedOutputStream output) {\n if (State != 0) {\n output.WriteRawTag(8);\n output.WriteEnum((int) State);\n }\n if (InnerState.Length != 0) {\n output.WriteRawTag(18);\n output.WriteString(InnerState);\n }\n if (Details.Length != 0) {", "answers": [" output.WriteRawTag(26);"], "length": 601, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "fda68c8c-f146-4e05-bbb7-e35e5451a489", "reasoning": "The WriteTo method serializes each field with its tag. After handling State (tag 8) and InnerState (tag 18), the next field is Details with field number 3, whose wire tag is 26. The generated code therefore writes the raw tag 26 before writing the string value. So the next line inside the Details block is the call to WriteRawTag with 26.", "reasoning_model_answer": "output.WriteRawTag(26);", "assistant_with_reasoning": "\nThe WriteTo method serializes each field with its tag. After handling State (tag 8) and InnerState (tag 18), the next field is Details with field number 3, whose wire tag is 26. The generated code therefore writes the raw tag 26 before writing the string value. So the next line inside the Details block is the call to WriteRawTag with 26.\n\noutput.WriteRawTag(26);", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.275, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 9071, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "output.WriteRawTag(26);", "score": 0.85, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "import csv\nimport random\nimport StringIO\n\nfrom django.core.mail import send_mass_mail\nfrom django.db.models import Q\nfrom django.http import HttpResponse\nfrom django.http import HttpResponseBadRequest, HttpResponseNotAllowed\nfrom django.shortcuts import render, redirect, get_object_or_404\nfrom django.template import Context, Template\nfrom django.views.decorators.http import require_POST\n\nfrom account.decorators import login_required\n\n# @@@ switch to pinax-teams\nfrom symposion.teams.models import Team\n\nfrom symposion.conf import settings\nfrom symposion.proposals.models import ProposalBase, ProposalSection\nfrom symposion.utils.mail import send_email\n\nfrom symposion.reviews.forms import ReviewForm, SpeakerCommentForm\nfrom symposion.reviews.forms import BulkPresentationForm\nfrom symposion.reviews.models import (\n ReviewAssignment, Review, LatestVote, ProposalResult, NotificationTemplate,\n ResultNotification, promote_proposal\n)\n\n\ndef access_not_permitted(request):\n return render(request, \"symposion/reviews/access_not_permitted.html\")\n\n\ndef proposals_generator(request, queryset, user_pk=None, check_speaker=True):\n\n for obj in queryset:\n # @@@ this sucks; we can do better\n if check_speaker:\n if request.user in [s.user for s in obj.speakers()]:\n continue\n\n try:\n obj.result\n except ProposalResult.DoesNotExist:\n ProposalResult.objects.get_or_create(proposal=obj)\n\n obj.comment_count = obj.result.comment_count\n obj.score = obj.result.score\n obj.total_votes = obj.result.vote_count\n obj.plus_two = obj.result.plus_two\n obj.plus_one = obj.result.plus_one\n obj.minus_one = obj.result.minus_one\n obj.minus_two = obj.result.minus_two\n lookup_params = dict(proposal=obj)\n\n if user_pk:\n lookup_params[\"user__pk\"] = user_pk\n else:\n lookup_params[\"user\"] = request.user\n\n try:\n obj.user_vote = LatestVote.objects.get(**lookup_params).vote\n obj.user_vote_css = LatestVote.objects.get(**lookup_params).css_class()\n except LatestVote.DoesNotExist:\n obj.user_vote = None\n obj.user_vote_css = \"no-vote\"\n\n yield obj\n\n\nVOTE_THRESHOLD = settings.SYMPOSION_VOTE_THRESHOLD\n\nPOSITIVE = \"positive\"\nNEGATIVE = \"negative\"\nINDIFFERENT = \"indifferent\"\nCONTROVERSIAL = \"controversial\"\nTOO_FEW = \"too_few\"\n\nREVIEW_STATUS_FILTERS = {\n # proposals with at least VOTE_THRESHOLD reviews and at least one +2 and no -2s, sorted by\n # the 'score'\n POSITIVE: lambda qs: qs.filter(result__vote_count__gte=VOTE_THRESHOLD, result__plus_two__gt=0,\n result__minus_two=0).order_by(\"-result__score\"),\n # proposals with at least VOTE_THRESHOLD reviews and at least one -2 and no +2s, reverse\n # sorted by the 'score'\n NEGATIVE: lambda qs: qs.filter(result__vote_count__gte=VOTE_THRESHOLD, result__minus_two__gt=0,\n result__plus_two=0).order_by(\"result__score\"),\n # proposals with at least VOTE_THRESHOLD reviews and neither a +2 or a -2, sorted by total\n # votes (lowest first)\n INDIFFERENT: lambda qs: qs.filter(result__vote_count__gte=VOTE_THRESHOLD, result__minus_two=0,\n result__plus_two=0).order_by(\"result__vote_count\"),\n # proposals with at least VOTE_THRESHOLD reviews and both a +2 and -2, sorted by total\n # votes (highest first)\n CONTROVERSIAL: lambda qs: qs.filter(result__vote_count__gte=VOTE_THRESHOLD,\n result__plus_two__gt=0, result__minus_two__gt=0)\n .order_by(\"-result__vote_count\"),\n # proposals with fewer than VOTE_THRESHOLD reviews\n TOO_FEW: lambda qs: qs.filter(result__vote_count__lt=VOTE_THRESHOLD)\n .order_by(\"result__vote_count\"),\n}\n\n\n# Returns a list of all proposals, proposals reviewed by the user, or the proposals the user has\n# yet to review depending on the link user clicks in dashboard\n@login_required\ndef review_section(request, section_slug, assigned=False, reviewed=\"all\"):\n\n if not request.user.has_perm(\"reviews.can_review_%s\" % section_slug):\n return access_not_permitted(request)\n\n section = get_object_or_404(ProposalSection, section__slug=section_slug)\n queryset = ProposalBase.objects.filter(kind__section=section.section)\n\n if assigned:\n assignments = ReviewAssignment.objects.filter(user=request.user)\\\n .values_list(\"proposal__id\")\n queryset = queryset.filter(id__in=assignments)\n\n # passing reviewed in from reviews.urls and out to review_list for\n # appropriate template header rendering\n if reviewed == \"all\":\n queryset = queryset.select_related(\"result\").select_subclasses()\n reviewed = \"all_reviews\"\n elif reviewed == \"reviewed\":\n queryset = queryset.filter(reviews__user=request.user)\n reviewed = \"user_reviewed\"\n else:\n queryset = queryset.exclude(reviews__user=request.user).exclude(\n speaker__user=request.user)\n reviewed = \"user_not_reviewed\"\n\n # lca2017 #21 -- chairs want to be able to see their own proposals in the list\n check_speaker = not request.user.has_perm(\"reviews.can_manage_%s\" % section_slug)\n proposals = proposals_generator(request, queryset, check_speaker=check_speaker)\n\n ctx = {\n \"proposals\": proposals,\n \"section\": section,\n \"reviewed\": reviewed,\n }\n\n return render(request, \"symposion/reviews/review_list.html\", ctx)\n\n\n@login_required\ndef review_all_proposals_csv(request):\n ''' Returns a CSV representation of all of the proposals this user has\n permisison to review. '''\n\n response = HttpResponse(\"text/csv\")\n response['Content-Disposition'] = 'attachment; filename=\"proposals.csv\"'\n writer = csv.writer(response, quoting=csv.QUOTE_NONNUMERIC)\n\n queryset = ProposalBase.objects.filter()\n\n # The fields from each proposal object to report in the csv\n fields = [\n \"id\", \"proposal_type\", \"speaker_name\",\"speaker_email\", \"title\",\n \"submitted\", \"other_speakers\", \"speaker_travel\",\n \"speaker_accommodation\", \"cancelled\", \"status\", \"score\", \"total_votes\",\n \"minus_two\", \"minus_one\", \"plus_one\", \"plus_two\",\n ]\n\n # Fields are the heading\n writer.writerow(fields)\n\n for proposal in proposals_generator(request, queryset, check_speaker=False):\n\n proposal.speaker_name = proposal.speaker.name\n section_slug = proposal.kind.section.slug\n kind_slug = proposal.kind.slug\n proposal.proposal_type = kind_slug\n\n proposal.other_speakers = \", \".join(\n speaker.name\n for speaker in proposal.additional_speakers.all()\n )\n\n proposal.speaker_travel = \", \".join(\n str(bool(speaker.travel_assistance))\n for speaker in proposal.speakers()\n )\n\n proposal.speaker_accommodation = \", \".join(\n str(bool(speaker.accommodation_assistance))\n for speaker in proposal.speakers()\n )\n\n if not request.user.has_perm(\"reviews.can_review_%s\" % section_slug):\n continue\n\n csv_line = [getattr(proposal, field) for field in fields]\n\n # Enusre that unicode items are handled properly.\n for i, item in enumerate(csv_line):\n if isinstance(item, unicode):\n csv_line[i] = item.encode(\"utf8\")\n\n writer.writerow(csv_line)\n\n return response\n\n\n@login_required\ndef review_random_proposal(request, section_slug):\n # lca2017 #16 view for random proposal\n\n if not request.user.has_perm(\"reviews.can_review_%s\" % section_slug):\n return access_not_permitted(request)\n\n section = get_object_or_404(ProposalSection, section__slug=section_slug)", "answers": [" queryset = ProposalBase.objects.filter(kind__section=section.section)"], "length": 642, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "0dd2f811-b1e1-47b5-8e21-b917ccb45311", "reasoning": "After obtaining the section object, the view needs to build a queryset of proposals belonging to that section, just like in the review_section view earlier. The typical query filters ProposalBase by the related kind's section field using the retrieved section. Therefore the next line should define that queryset.", "reasoning_model_answer": "queryset = ProposalBase.objects.filter(kind__section=section.section)", "assistant_with_reasoning": "\nAfter obtaining the section object, the view needs to build a queryset of proposals belonging to that section, just like in the review_section view earlier. The typical query filters ProposalBase by the related kind's section field using the retrieved section. Therefore the next line should define that queryset.\n\nqueryset = ProposalBase.objects.filter(kind__section=section.section)", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 7.205, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 7902, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "queryset = ProposalBase.objects.filter(kind__section=section.section)", "score": 0.97, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "#(C) Copyright Syd Logan 2020\n#(C) Copyright Thousand Smiles Foundation 2020\n#\n#Licensed under the Apache License, Version 2.0 (the \"License\");\n#you may not use this file except in compliance with the License.\n#\n#You may obtain a copy of the License at\n#http://www.apache.org/licenses/LICENSE-2.0\n#\n#Unless required by applicable law or agreed to in writing, software\n#distributed under the License is distributed on an \"AS IS\" BASIS,\n#WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n#See the License for the specific language governing permissions and\n#limitations under the License.\n\n'''\nunit tests for audiogram application. Assumes django server is up\nand running on the specified host and port\n'''\n\nimport unittest\nimport getopt, sys\nimport json\n\nfrom tschartslib.service.serviceapi import ServiceAPI\nfrom tschartslib.tscharts.tscharts import Login, Logout\nfrom tschartslib.patient.patient import CreatePatient, DeletePatient\nfrom tschartslib.clinic.clinic import CreateClinic, DeleteClinic\nfrom tschartslib.station.station import CreateStation, DeleteStation\nfrom tschartslib.image.image import CreateImage, DeleteImage\n\nclass CreateAudiogram(ServiceAPI):\n def __init__(self, host, port, token, clinic, image, patient, comment=\"\"):\n super(CreateAudiogram, self).__init__()\n \n self.setHttpMethod(\"POST\")\n self.setHost(host)\n self.setPort(port)\n self.setToken(token)\n\n payload = {\"patient\": patient, \"clinic\": clinic, \"image\": image, \"comment\": comment}\n self.setPayload(payload)\n self.setURL(\"tscharts/v1/audiogram/\")\n \nclass GetAudiogram(ServiceAPI):\n def makeURL(self):\n hasQArgs = False\n if not self._id == None:\n base = \"tscharts/v1/audiogram/{}/\".format(self._id)\n else:\n base = \"tscharts/v1/audiogram/\"\n\n if not self._clinic == None:\n if not hasQArgs:\n base += \"?\"\n else:\n base += \"&\"\n base += \"clinic={}\".format(self._clinic)\n hasQArgs = True\n\n if not self._patient == None:\n if not hasQArgs:\n base += \"?\"\n else:\n base += \"&\"\n base += \"patient={}\".format(self._patient)\n hasQArgs = True\n\n self.setURL(base)\n\n def __init__(self, host, port, token):\n super(GetAudiogram, self).__init__()\n \n self.setHttpMethod(\"GET\")\n self.setHost(host)\n self.setPort(port)\n self.setToken(token)\n self._patient = None\n self._clinic = None\n self._image = None\n self._id = None\n\n def setId(self, id):\n self._id = id;\n self.makeURL()\n \n def setClinic(self, clinic):\n self._clinic = clinic\n self.makeURL()\n\n def setPatient(self, patient):\n self._patient = patient\n self.makeURL()\n\n def setImage(self, image):\n self._image = image\n self.makeURL()\n\nclass UpdateAudiogram(ServiceAPI):\n def __init__(self, host, port, token, id):\n super(UpdateAudiogram, self).__init__()\n \n self.setHttpMethod(\"PUT\")\n self.setHost(host)\n self.setPort(port)\n self.setToken(token)\n self._payload = {}\n self.setPayload(self._payload)\n self.setURL(\"tscharts/v1/audiogram/{}/\".format(id))\n\n def setComment(self, comment):\n self._payload[\"comment\"] = comment\n self.setPayload(self._payload)\n\nclass DeleteAudiogram(ServiceAPI):\n def __init__(self, host, port, token, id):\n super(DeleteAudiogram, self).__init__()\n \n self.setHttpMethod(\"DELETE\")\n self.setHost(host)\n self.setPort(port)\n self.setToken(token)\n self.setURL(\"tscharts/v1/audiogram/{}/\".format(id))\n\nclass TestTSAudiogram(unittest.TestCase):\n\n def setUp(self):\n login = Login(host, port, username, password)\n ret = login.send(timeout=30)\n self.assertEqual(ret[0], 200)\n self.assertTrue(\"token\" in ret[1])\n global token\n token = ret[1][\"token\"]\n\n def testCreateAudiogram(self):\n x = CreateClinic(host, port, token, \"Ensenada\", \"02/05/2016\", \"02/06/2016\")\n ret = x.send(timeout=30)\n self.assertEqual(ret[0], 200)\n self.assertTrue(\"id\" in ret[1])\n clinicid = int(ret[1][\"id\"])\n\n x = CreateStation(host, port, token, \"ENT\")\n ret = x.send(timeout=30)\n self.assertEqual(ret[0], 200)\n stationid = int(ret[1][\"id\"])\n\n data = {}\n\n data[\"paternal_last\"] = \"abcd1234\"\n data[\"maternal_last\"] = \"yyyyyy\"\n data[\"first\"] = \"zzzzzzz\"\n data[\"middle\"] = \"\"\n data[\"suffix\"] = \"Jr.\"\n data[\"prefix\"] = \"\"\n data[\"dob\"] = \"04/01/1962\"\n data[\"gender\"] = \"Female\"\n data[\"street1\"] = \"1234 First Ave\"\n data[\"street2\"] = \"\"\n data[\"city\"] = \"Ensenada\"\n data[\"colonia\"] = \"\"\n data[\"state\"] = u\"Baja California\"\n data[\"phone1\"] = \"1-111-111-1111\"\n data[\"phone2\"] = \"\"\n data[\"email\"] = \"patient@example.com\"\n data[\"emergencyfullname\"] = \"Maria Sanchez\"\n data[\"emergencyphone\"] = \"1-222-222-2222\"\n data[\"emergencyemail\"] = \"maria.sanchez@example.com\"\n\n x = CreatePatient(host, port, token, data)\n ret = x.send(timeout=30)\n self.assertEqual(ret[0], 200)\n patientid = int(ret[1][\"id\"])\n\n x = CreateImage(host, port, token)\n x.setPatient(patientid)\n x.setClinic(clinicid)\n x.setStation(stationid)\n x.setType(\"Audiogram\")\n x.setData(\"ABCDEFG\") # doesn't matter if it is actual image data \n ret = x.send(timeout=30)\n self.assertEqual(ret[0], 200)\n imageid = int(ret[1][\"id\"])\n\n x = CreateAudiogram(host, port, token, patient=patientid, clinic=clinicid, image=imageid)\n ret = x.send(timeout=30)\n self.assertEqual(ret[0], 200)\n id = int(ret[1][\"id\"])\n x = GetAudiogram(host, port, token)\n x.setId(id)\n ret = x.send(timeout=30)\n self.assertEqual(ret[0], 200) \n self.assertTrue(\"clinic\" in ret[1])\n clinicId = int(ret[1][\"clinic\"])\n self.assertTrue(clinicId == clinicid)\n self.assertTrue(\"patient\" in ret[1])\n patientId = int(ret[1][\"patient\"])\n self.assertTrue(patientId == patientid)\n imageId = int(ret[1][\"image\"])\n self.assertTrue(imageId == imageid)\n\n x = DeleteAudiogram(host, port, token, id)\n ret = x.send(timeout=30)\n self.assertEqual(ret[0], 200)\n x = GetAudiogram(host, port, token)\n x.setId(id)\n ret = x.send(timeout=30)\n self.assertEqual(ret[0], 404) # not found\n\n # non-existent clinic param\n\n x = CreateAudiogram(host, port, token, clinic=9999, image=imageid, patient=patientid)\n ret = x.send(timeout=30)\n self.assertEqual(ret[0], 404)\n\n # non-existent image param\n\n x = CreateAudiogram(host, port, token, clinic=clinicid, image=9999, patient=patientid)\n ret = x.send(timeout=30)\n self.assertEqual(ret[0], 404)\n\n # non-existent patient param\n\n x = CreateAudiogram(host, port, token, clinic=clinicid, image=imageid, patient=9999)\n ret = x.send(timeout=30)\n self.assertEqual(ret[0], 404)\n\n x = DeleteStation(host, port, token, stationid)\n ret = x.send(timeout=30)\n self.assertEqual(ret[0], 200)\n\n x = DeleteClinic(host, port, token, clinicid)\n ret = x.send(timeout=30)\n self.assertEqual(ret[0], 200)\n\n x = DeletePatient(host, port, token, patientid)\n ret = x.send(timeout=30)\n self.assertEqual(ret[0], 200)", "answers": [" def testDeleteAudiogram(self):"], "length": 659, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "f2a7d74a-a439-4eef-a149-382ff46e2eb7", "reasoning": "The provided snippet ends the testCreateAudiogram method after deleting the patient. In a typical unittest class, the next step is to define another test method. Following the same indentation level, the next line should start a new test method, likely for updating an audiogram.", "reasoning_model_answer": "def testUpdateAudiogram(self):", "assistant_with_reasoning": "\nThe provided snippet ends the testCreateAudiogram method after deleting the patient. In a typical unittest class, the next step is to define another test method. Following the same indentation level, the next line should start a new test method, likely for updating an audiogram.\n\ndef testUpdateAudiogram(self):", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 2.781, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 7836, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "def testUpdateAudiogram(self):", "score": 0.81, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "# -*- coding: utf-8 -*-\n# This file is part of beets.\n# Copyright 2016, Jakob Schnitzer.\n#\n# Permission is hereby granted, free of charge, to any person obtaining\n# a copy of this software and associated documentation files (the\n# \"Software\"), to deal in the Software without restriction, including\n# without limitation the rights to use, copy, modify, merge, publish,\n# distribute, sublicense, and/or sell copies of the Software, and to\n# permit persons to whom the Software is furnished to do so, subject to\n# the following conditions:\n#\n# The above copyright notice and this permission notice shall be\n# included in all copies or substantial portions of the Software.\n\n\"\"\"Converts tracks or albums to external directory\n\"\"\"\nfrom __future__ import division, absolute_import, print_function\n\nimport os\nimport threading\nimport subprocess\nimport tempfile\nimport shlex\nimport six\nfrom string import Template\nimport platform\n\nfrom beets import ui, util, plugins, config\nfrom beets.plugins import BeetsPlugin\nfrom confuse import ConfigTypeError\nfrom beets import art\nfrom beets.util.artresizer import ArtResizer\nfrom beets.library import parse_query_string\nfrom beets.library import Item\n\n_fs_lock = threading.Lock()\n_temp_files = [] # Keep track of temporary transcoded files for deletion.\n\n# Some convenient alternate names for formats.\nALIASES = {\n u'wma': u'windows media',\n u'vorbis': u'ogg',\n}\n\nLOSSLESS_FORMATS = ['ape', 'flac', 'alac', 'wav', 'aiff']\n\n\ndef replace_ext(path, ext):\n \"\"\"Return the path with its extension replaced by `ext`.\n\n The new extension must not contain a leading dot.\n \"\"\"\n ext_dot = b'.' + ext\n return os.path.splitext(path)[0] + ext_dot\n\n\ndef get_format(fmt=None):\n \"\"\"Return the command template and the extension from the config.\n \"\"\"\n if not fmt:\n fmt = config['convert']['format'].as_str().lower()\n fmt = ALIASES.get(fmt, fmt)\n\n try:\n format_info = config['convert']['formats'][fmt].get(dict)\n command = format_info['command']\n extension = format_info.get('extension', fmt)\n except KeyError:\n raise ui.UserError(\n u'convert: format {0} needs the \"command\" field'\n .format(fmt)\n )\n except ConfigTypeError:\n command = config['convert']['formats'][fmt].get(str)\n extension = fmt\n\n # Convenience and backwards-compatibility shortcuts.\n keys = config['convert'].keys()\n if 'command' in keys:\n command = config['convert']['command'].as_str()\n elif 'opts' in keys:\n # Undocumented option for backwards compatibility with < 1.3.1.\n command = u'ffmpeg -i $source -y {0} $dest'.format(\n config['convert']['opts'].as_str()\n )\n if 'extension' in keys:\n extension = config['convert']['extension'].as_str()\n\n return (command.encode('utf-8'), extension.encode('utf-8'))\n\n\ndef should_transcode(item, fmt):\n \"\"\"Determine whether the item should be transcoded as part of\n conversion (i.e., its bitrate is high or it has the wrong format).\n \"\"\"\n no_convert_queries = config['convert']['no_convert'].as_str_seq()\n if no_convert_queries:\n for query_string in no_convert_queries:\n query, _ = parse_query_string(query_string, Item)\n if query.match(item):\n return False\n if config['convert']['never_convert_lossy_files'] and \\\n not (item.format.lower() in LOSSLESS_FORMATS):\n return False\n maxbr = config['convert']['max_bitrate'].get(int)\n return fmt.lower() != item.format.lower() or \\\n item.bitrate >= 1000 * maxbr\n\n\nclass ConvertPlugin(BeetsPlugin):\n def __init__(self):\n super(ConvertPlugin, self).__init__()\n self.config.add({\n u'dest': None,\n u'pretend': False,\n u'link': False,\n u'hardlink': False,\n u'threads': util.cpu_count(),\n u'format': u'mp3',\n u'id3v23': u'inherit',\n u'formats': {\n u'aac': {\n u'command': u'ffmpeg -i $source -y -vn -acodec aac '\n u'-aq 1 $dest',\n u'extension': u'm4a',\n },\n u'alac': {\n u'command': u'ffmpeg -i $source -y -vn -acodec alac $dest',\n u'extension': u'm4a',\n },\n u'flac': u'ffmpeg -i $source -y -vn -acodec flac $dest',\n u'mp3': u'ffmpeg -i $source -y -vn -aq 2 $dest',\n u'opus':\n u'ffmpeg -i $source -y -vn -acodec libopus -ab 96k $dest',\n u'ogg':\n u'ffmpeg -i $source -y -vn -acodec libvorbis -aq 3 $dest',\n u'wma':\n u'ffmpeg -i $source -y -vn -acodec wmav2 -vn $dest',\n },\n u'max_bitrate': 500,\n u'auto': False,\n u'tmpdir': None,\n u'quiet': False,\n u'embed': True,\n u'paths': {},\n u'no_convert': u'',\n u'never_convert_lossy_files': False,\n u'copy_album_art': False,\n u'album_art_maxwidth': 0,\n u'delete_originals': False,\n })\n self.early_import_stages = [self.auto_convert]\n\n self.register_listener('import_task_files', self._cleanup)\n\n def commands(self):\n cmd = ui.Subcommand('convert', help=u'convert to external location')\n cmd.parser.add_option('-p', '--pretend', action='store_true',\n help=u'show actions but do nothing')\n cmd.parser.add_option('-t', '--threads', action='store', type='int',\n help=u'change the number of threads, \\\n defaults to maximum available processors')", "answers": [" cmd.parser.add_option('-k', '--keep-new', action='store_true',"], "length": 587, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "d0adc7ad-c631-49ad-b805-3ddc8fc748c7", "reasoning": "The code is inside the ConvertPlugin.commands method, defining command‑line options for the 'convert' subcommand. After adding the '-t/--threads' option, the next logical option defined in the original beets plugin is the '-l/--link' flag, which tells the plugin to create symlinks instead of copying files. The line follows the same indentation and style as the previous option definitions.", "reasoning_model_answer": "cmd.parser.add_option('-l', '--link', action='store_true',\n help=u'create symlinks instead of copying files')", "assistant_with_reasoning": "\nThe code is inside the ConvertPlugin.commands method, defining command‑line options for the 'convert' subcommand. After adding the '-t/--threads' option, the next logical option defined in the original beets plugin is the '-l/--link' flag, which tells the plugin to create symlinks instead of copying files. The line follows the same indentation and style as the previous option definitions.\n\ncmd.parser.add_option('-l', '--link', action='store_true',\n help=u'create symlinks instead of copying files')", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 6.704, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 5876, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "cmd.parser.add_option('-l', '--link', action='store_true',\n help=u'create symlinks instead of copying files')", "score": 0.84, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/***************************************************************************\n * Skills.cs\n * -------------------\n * begin : May 1, 2002\n * copyright : (C) The RunUO Software Team\n * email : info@runuo.com\n *\n * $Id$\n *\n ***************************************************************************/\n\n/***************************************************************************\n *\n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or\n * (at your option) any later version.\n *\n ***************************************************************************/\n\nusing System;\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.IO;\nusing Server.Network;\n\nnamespace Server\n{\n\tpublic delegate TimeSpan SkillUseCallback( Mobile user );\n\n\tpublic enum SkillLock : byte\n\t{\n\t\tUp = 0,\n\t\tDown = 1,\n\t\tLocked = 2\n\t}\n\n\tpublic enum SkillName\n\t{\n\t\tAlchemy = 0,\n\t\tAnatomy = 1,\n\t\tAnimalLore = 2,\n\t\tItemID = 3,\n\t\tArmsLore = 4,\n\t\tParry = 5,\n\t\tBegging = 6,\n\t\tBlacksmith = 7,\n\t\tFletching = 8,\n\t\tPeacemaking = 9,\n\t\tCamping = 10,\n\t\tCarpentry = 11,\n\t\tCartography = 12,\n\t\tCooking = 13,\n\t\tDetectHidden = 14,\n\t\tDiscordance = 15,\n\t\tEvalInt = 16,\n\t\tHealing = 17,\n\t\tFishing = 18,\n\t\tForensics = 19,\n\t\tHerding = 20,\n\t\tHiding = 21,\n\t\tProvocation = 22,\n\t\tInscribe = 23,\n\t\tLockpicking = 24,\n\t\tMagery = 25,\n\t\tMagicResist = 26,\n\t\tTactics = 27,\n\t\tSnooping = 28,\n\t\tMusicianship = 29,\n\t\tPoisoning = 30,\n\t\tArchery = 31,\n\t\tSpiritSpeak = 32,\n\t\tStealing = 33,\n\t\tTailoring = 34,\n\t\tAnimalTaming = 35,\n\t\tTasteID = 36,\n\t\tTinkering = 37,\n\t\tTracking = 38,\n\t\tVeterinary = 39,\n\t\tSwords = 40,\n\t\tMacing = 41,\n\t\tFencing = 42,\n\t\tWrestling = 43,\n\t\tLumberjacking = 44,\n\t\tMining = 45,\n\t\tMeditation = 46,\n\t\tStealth = 47,\n\t\tRemoveTrap = 48,\n\t\tNecromancy = 49,\n\t\tFocus = 50,\n\t\tChivalry = 51,\n\t\tBushido = 52,\n\t\tNinjitsu = 53,\n\t\tSpellweaving = 54,\n\t\tMysticism = 55,\n\t\tImbuing = 56,\n\t\tThrowing = 57\n\t}\n\n\t[PropertyObject]\n\tpublic class Skill\n\t{\n\t\tprivate Skills m_Owner;\n\t\tprivate SkillInfo m_Info;\n\t\tprivate ushort m_Base;\n\t\tprivate ushort m_Cap;\n\t\tprivate SkillLock m_Lock;\n\n\t\tpublic override string ToString()\n\t\t{\n\t\t\treturn String.Format( \"[{0}: {1}]\", Name, Base );\n\t\t}\n\n\t\tpublic Skill( Skills owner, SkillInfo info, GenericReader reader )\n\t\t{\n\t\t\tm_Owner = owner;\n\t\t\tm_Info = info;\n\n\t\t\tint version = reader.ReadByte();\n\n\t\t\tswitch ( version )\n\t\t\t{\n\t\t\t\tcase 0:\n\t\t\t\t{\n\t\t\t\t\tm_Base = reader.ReadUShort();\n\t\t\t\t\tm_Cap = reader.ReadUShort();\n\t\t\t\t\tm_Lock = (SkillLock)reader.ReadByte();\n\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase 0xFF:\n\t\t\t\t{\n\t\t\t\t\tm_Base = 0;\n\t\t\t\t\tm_Cap = 1000;\n\t\t\t\t\tm_Lock = SkillLock.Up;\n\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tdefault:\n\t\t\t\t{\n\t\t\t\t\tif ( (version & 0xC0) == 0x00 )\n\t\t\t\t\t{\n\t\t\t\t\t\tif ( (version & 0x1) != 0 )\n\t\t\t\t\t\t\tm_Base = reader.ReadUShort();\n\n\t\t\t\t\t\tif ( (version & 0x2) != 0 )\n\t\t\t\t\t\t\tm_Cap = reader.ReadUShort();\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tm_Cap = 1000;\n\n\t\t\t\t\t\tif ( (version & 0x4) != 0 )\n\t\t\t\t\t\t\tm_Lock = (SkillLock)reader.ReadByte();\n\t\t\t\t\t}\n\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif ( m_Lock < SkillLock.Up || m_Lock > SkillLock.Locked )\n\t\t\t{\n\t\t\t\tConsole.WriteLine( \"Bad skill lock -> {0}.{1}\", owner.Owner, m_Lock );\n\t\t\t\tm_Lock = SkillLock.Up;\n\t\t\t}\n\t\t}\n\n\t\tpublic Skill( Skills owner, SkillInfo info, int baseValue, int cap, SkillLock skillLock )\n\t\t{\n\t\t\tm_Owner = owner;\n\t\t\tm_Info = info;\n\t\t\tm_Base = (ushort)baseValue;\n\t\t\tm_Cap = (ushort)cap;\n\t\t\tm_Lock = skillLock;\n\t\t}\n\n\t\tpublic void SetLockNoRelay( SkillLock skillLock )\n\t\t{\n\t\t\tif ( skillLock < SkillLock.Up || skillLock > SkillLock.Locked )\n\t\t\t\treturn;\n\n\t\t\tm_Lock = skillLock;\n\t\t}\n\n\t\tpublic void Serialize( GenericWriter writer )\n\t\t{\n\t\t\tif ( m_Base == 0 && m_Cap == 1000 && m_Lock == SkillLock.Up )\n\t\t\t{\n\t\t\t\twriter.Write( (byte) 0xFF ); // default\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tint flags = 0x0;\n\n\t\t\t\tif ( m_Base != 0 )\n\t\t\t\t\tflags |= 0x1;\n\n\t\t\t\tif ( m_Cap != 1000 )\n\t\t\t\t\tflags |= 0x2;\n\n\t\t\t\tif ( m_Lock != SkillLock.Up )\n\t\t\t\t\tflags |= 0x4;\n", "answers": ["\t\t\t\twriter.Write( (byte) flags ); // version"], "length": 574, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "780ef76b-36b9-45ed-a170-097db2de03ff", "reasoning": "We are inside the Serialize method of Skill. After computing the flags integer that indicates which fields differ from defaults, the next step is to write that flags byte to the writer before conditionally writing the actual values. The appropriate C# line is writer.Write( (byte)flags );", "reasoning_model_answer": "writer.Write( (byte)flags );", "assistant_with_reasoning": "\nWe are inside the Serialize method of Skill. After computing the flags integer that indicates which fields differ from defaults, the next step is to write that flags byte to the writer before conditionally writing the actual values. The appropriate C# line is writer.Write( (byte)flags );\n\nwriter.Write( (byte)flags );", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 2.664, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 4176, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "writer.Write( (byte)flags );", "score": 0.78, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.apache.hadoop.hive.ql.exec;\n\nimport static org.apache.hadoop.hive.ql.exec.Utilities.DEPRECATED_MAPRED_DFSCLIENT_PARALLELISM_MAX;\nimport static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.assertFalse;\nimport static org.junit.Assert.assertNotEquals;\nimport static org.junit.Assert.assertNotNull;\nimport static org.junit.Assert.assertTrue;\nimport static org.junit.Assert.fail;\nimport static org.apache.hadoop.hive.ql.exec.Utilities.getFileExtension;\nimport static org.mockito.ArgumentMatchers.any;\nimport static org.mockito.Mockito.doReturn;\nimport static org.mockito.Mockito.mock;\nimport static org.mockito.Mockito.times;\nimport static org.mockito.Mockito.verify;\nimport static org.mockito.Mockito.when;\n\nimport java.io.File;\nimport java.io.IOException;\nimport java.util.ArrayList;\nimport java.util.LinkedHashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Properties;\nimport java.util.UUID;\nimport java.util.concurrent.Callable;\nimport java.util.concurrent.ExecutionException;\nimport java.util.concurrent.ExecutorService;\nimport java.util.concurrent.Future;\n\nimport org.apache.hadoop.conf.Configuration;\nimport org.apache.hadoop.fs.FileSystem;\nimport org.apache.hadoop.fs.Path;\nimport org.apache.hadoop.hive.common.type.Timestamp;\nimport org.apache.hadoop.hive.conf.HiveConf;\nimport org.apache.hadoop.hive.ql.Context;\nimport org.apache.hadoop.hive.ql.exec.mr.ExecDriver;\nimport org.apache.hadoop.hive.ql.exec.spark.SparkTask;\nimport org.apache.hadoop.hive.ql.exec.tez.TezTask;\nimport org.apache.hadoop.hive.ql.io.*;\nimport org.apache.hadoop.hive.ql.metadata.HiveException;\nimport org.apache.hadoop.hive.ql.metadata.Table;\nimport org.apache.hadoop.hive.ql.plan.DependencyCollectionWork;\nimport org.apache.hadoop.hive.ql.plan.DynamicPartitionCtx;\nimport org.apache.hadoop.hive.ql.plan.ExprNodeConstantDesc;\nimport org.apache.hadoop.hive.ql.plan.ExprNodeDesc;\nimport org.apache.hadoop.hive.ql.plan.ExprNodeGenericFuncDesc;\nimport org.apache.hadoop.hive.ql.plan.FileSinkDesc;\nimport org.apache.hadoop.hive.ql.plan.MapWork;\nimport org.apache.hadoop.hive.ql.plan.MapredWork;\nimport org.apache.hadoop.hive.ql.plan.PartitionDesc;\nimport org.apache.hadoop.hive.ql.plan.TableDesc;\nimport org.apache.hadoop.hive.ql.session.SessionState;\nimport org.apache.hadoop.hive.ql.udf.generic.GenericUDFFromUtcTimestamp;\nimport org.apache.hadoop.hive.serde2.typeinfo.TypeInfoFactory;\nimport org.apache.hadoop.mapred.JobConf;\nimport org.apache.hadoop.mapreduce.MRJobConfig;\nimport org.junit.Assert;\nimport org.junit.Rule;\nimport org.junit.Test;\nimport org.junit.rules.TemporaryFolder;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.Lists;\n\npublic class TestUtilities {\n @Rule\n public TemporaryFolder temporaryFolder = new TemporaryFolder();\n\n public static final Logger LOG = LoggerFactory.getLogger(TestUtilities.class);\n private static final int NUM_BUCKETS = 3;\n\n @Test\n public void testGetFileExtension() {\n JobConf jc = new JobConf();\n assertEquals(\"No extension for uncompressed unknown format\", \"\",\n getFileExtension(jc, false, null));\n assertEquals(\"No extension for compressed unknown format\", \"\",\n getFileExtension(jc, true, null));\n assertEquals(\"No extension for uncompressed text format\", \"\",\n getFileExtension(jc, false, new HiveIgnoreKeyTextOutputFormat()));\n assertEquals(\"Deflate for uncompressed text format\", \".deflate\",\n getFileExtension(jc, true, new HiveIgnoreKeyTextOutputFormat()));\n\n String extension = \".myext\";\n jc.set(\"hive.output.file.extension\", extension);\n assertEquals(\"Custom extension for uncompressed unknown format\", extension,\n getFileExtension(jc, false, null));\n assertEquals(\"Custom extension for compressed unknown format\", extension,\n getFileExtension(jc, true, null));\n assertEquals(\"Custom extension for uncompressed text format\", extension,\n getFileExtension(jc, false, new HiveIgnoreKeyTextOutputFormat()));\n assertEquals(\"Custom extension for uncompressed text format\", extension,\n getFileExtension(jc, true, new HiveIgnoreKeyTextOutputFormat()));\n }\n\n @Test\n public void testSerializeTimestamp() {\n Timestamp ts = Timestamp.ofEpochMilli(1374554702000L, 123456);\n ExprNodeConstantDesc constant = new ExprNodeConstantDesc(ts);\n List children = new ArrayList(1);\n children.add(constant);\n ExprNodeGenericFuncDesc desc = new ExprNodeGenericFuncDesc(TypeInfoFactory.timestampTypeInfo,\n new GenericUDFFromUtcTimestamp(), children);\n assertEquals(desc.getExprString(), SerializationUtilities.deserializeExpression(\n SerializationUtilities.serializeExpression(desc)).getExprString());\n }\n\n @Test\n public void testgetDbTableName() throws HiveException{\n String tablename;\n String [] dbtab;\n SessionState.start(new HiveConf(this.getClass()));\n String curDefaultdb = SessionState.get().getCurrentDatabase();\n\n //test table without db portion\n tablename = \"tab1\";\n dbtab = Utilities.getDbTableName(tablename);\n assertEquals(\"db name\", curDefaultdb, dbtab[0]);\n assertEquals(\"table name\", tablename, dbtab[1]);\n\n //test table with db portion\n tablename = \"dab1.tab1\";\n dbtab = Utilities.getDbTableName(tablename);\n assertEquals(\"db name\", \"dab1\", dbtab[0]);\n assertEquals(\"table name\", \"tab1\", dbtab[1]);\n\n //test invalid table name\n tablename = \"dab1.tab1.x1\";\n try {\n dbtab = Utilities.getDbTableName(tablename);\n fail(\"exception was expected for invalid table name\");\n } catch(HiveException ex){\n assertEquals(\"Invalid table name \" + tablename, ex.getMessage());\n }\n }\n\n @Test\n public void testReplaceTaskId() {\n String taskID = \"000000\";\n int bucketNum = 1;\n String newTaskID = Utilities.replaceTaskId(taskID, bucketNum);\n Assert.assertEquals(\"000001\", newTaskID);\n taskID = \"(ds%3D1)000001\";\n newTaskID = Utilities.replaceTaskId(taskID, 5);\n Assert.assertEquals(\"(ds%3D1)000005\", newTaskID);\n }\n\n @Test\n public void testRemoveTempOrDuplicateFilesOnTezNoDp() throws Exception {\n List paths = runRemoveTempOrDuplicateFilesTestCase(\"tez\", false);\n assertEquals(0, paths.size());\n }\n\n @Test\n public void testRemoveTempOrDuplicateFilesOnTezWithDp() throws Exception {\n List paths = runRemoveTempOrDuplicateFilesTestCase(\"tez\", true);\n assertEquals(0, paths.size());\n }\n\n @Test\n public void testRemoveTempOrDuplicateFilesOnMrNoDp() throws Exception {\n List paths = runRemoveTempOrDuplicateFilesTestCase(\"mr\", false);", "answers": [" assertEquals(NUM_BUCKETS, paths.size());"], "length": 588, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "546870d6-9038-40d0-9c28-15e5fa47bd5a", "reasoning": "The method testRemoveTempOrDuplicateFilesOnMrNoDp mirrors the previous two test methods. After obtaining the list of paths from runRemoveTempOrDuplicateFilesTestCase, the test asserts that the list is empty. The next line should therefore be the same assertion used earlier: assertEquals(0, paths.size());", "reasoning_model_answer": "assertEquals(0, paths.size());", "assistant_with_reasoning": "\nThe method testRemoveTempOrDuplicateFilesOnMrNoDp mirrors the previous two test methods. After obtaining the list of paths from runRemoveTempOrDuplicateFilesTestCase, the test asserts that the list is empty. The next line should therefore be the same assertion used earlier: assertEquals(0, paths.size());\n\nassertEquals(0, paths.size());", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.012, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 7566, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "assertEquals(0, paths.size());", "score": 0.78, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/*\n * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.\n *\n * WSO2 Inc. licenses this file to you under the Apache License,\n * Version 2.0 (the \"License\"); you may not use this file except\n * in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations\n * under the License.\n *\n */\npackage org.wso2.carbon.mdm.services.android.services.impl;\n\nimport org.apache.commons.logging.Log;\nimport org.apache.commons.logging.LogFactory;\nimport org.wso2.carbon.device.mgt.common.Device;\nimport org.wso2.carbon.device.mgt.common.DeviceIdentifier;\nimport org.wso2.carbon.device.mgt.common.DeviceManagementConstants;\nimport org.wso2.carbon.device.mgt.common.DeviceManagementException;\nimport org.wso2.carbon.device.mgt.common.InvalidDeviceException;\nimport org.wso2.carbon.device.mgt.common.app.mgt.Application;\nimport org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManagementException;\nimport org.wso2.carbon.device.mgt.common.device.details.DeviceLocation;\nimport org.wso2.carbon.device.mgt.common.notification.mgt.NotificationManagementException;\nimport org.wso2.carbon.device.mgt.common.operation.mgt.Operation;\nimport org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException;\nimport org.wso2.carbon.device.mgt.common.policy.mgt.monitor.PolicyComplianceException;\nimport org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceDetailsMgtException;\nimport org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceInformationManager;\nimport org.wso2.carbon.device.mgt.core.operation.mgt.CommandOperation;\nimport org.wso2.carbon.mdm.services.android.bean.ErrorResponse;\nimport org.wso2.carbon.mdm.services.android.bean.wrapper.AndroidApplication;\nimport org.wso2.carbon.mdm.services.android.bean.wrapper.AndroidDevice;\nimport org.wso2.carbon.mdm.services.android.exception.UnexpectedServerErrorException;\nimport org.wso2.carbon.mdm.services.android.services.DeviceManagementService;\nimport org.wso2.carbon.mdm.services.android.util.AndroidAPIUtils;\nimport org.wso2.carbon.mdm.services.android.util.AndroidConstants;\nimport org.wso2.carbon.mdm.services.android.util.AndroidDeviceUtils;\nimport org.wso2.carbon.mdm.services.android.util.Message;\nimport org.wso2.carbon.policy.mgt.common.PolicyManagementException;\nimport org.wso2.carbon.policy.mgt.core.PolicyManagerService;\n\nimport javax.validation.Valid;\nimport javax.validation.constraints.NotNull;\nimport javax.validation.constraints.Pattern;\nimport javax.validation.constraints.Size;\nimport javax.ws.rs.Consumes;\nimport javax.ws.rs.DELETE;\nimport javax.ws.rs.GET;\nimport javax.ws.rs.HeaderParam;\nimport javax.ws.rs.POST;\nimport javax.ws.rs.PUT;\nimport javax.ws.rs.Path;\nimport javax.ws.rs.PathParam;\nimport javax.ws.rs.Produces;\nimport javax.ws.rs.core.MediaType;\nimport javax.ws.rs.core.Response;\nimport java.util.ArrayList;\nimport java.util.List;\n\n@Path(\"/devices\")\n@Produces(MediaType.APPLICATION_JSON)\n@Consumes(MediaType.APPLICATION_JSON)\npublic class DeviceManagementServiceImpl implements DeviceManagementService {\n\n private static final String OPERATION_ERROR_STATUS = \"ERROR\";\n private static final Log log = LogFactory.getLog(DeviceManagementServiceImpl.class);\n\n @PUT\n @Path(\"/{id}/applications\")\n @Override\n public Response updateApplicationList(@PathParam(\"id\")\n @NotNull\n @Size(min = 2, max = 45)\n @Pattern(regexp = \"^[A-Za-z0-9]*$\")\n String id, List androidApplications) {\n Application application;\n List applications = new ArrayList<>();\n for (AndroidApplication androidApplication : androidApplications) {\n application = new Application();\n application.setPlatform(androidApplication.getPlatform());\n application.setCategory(androidApplication.getCategory());\n application.setName(androidApplication.getName());\n application.setLocationUrl(androidApplication.getLocationUrl());\n application.setImageUrl(androidApplication.getImageUrl());\n application.setVersion(androidApplication.getVersion());\n application.setType(androidApplication.getType());\n application.setAppProperties(androidApplication.getAppProperties());\n application.setApplicationIdentifier(androidApplication.getApplicationIdentifier());\n application.setMemoryUsage(androidApplication.getMemoryUsage());\n applications.add(application);\n }\n Message responseMessage = new Message();\n DeviceIdentifier deviceIdentifier = new DeviceIdentifier();\n deviceIdentifier.setId(id);\n deviceIdentifier.setType(DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_ANDROID);\n try {\n AndroidAPIUtils.getApplicationManagerService().\n updateApplicationListInstalledInDevice(deviceIdentifier, applications);\n responseMessage.setResponseMessage(\"Device information has modified successfully.\");\n return Response.status(Response.Status.ACCEPTED).entity(responseMessage).build();\n } catch (ApplicationManagementException e) {\n String msg = \"Error occurred while modifying the application list.\";\n log.error(msg, e);\n throw new UnexpectedServerErrorException(\n new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build());\n }\n }\n\n @PUT\n @Path(\"/{id}/pending-operations\")\n @Override\n public Response getPendingOperations(@PathParam(\"id\") String id,\n @HeaderParam(\"If-Modified-Since\") String ifModifiedSince,\n List resultOperations) {\n if (id == null || id.isEmpty()) {\n String msg = \"Device identifier is null or empty, hence returning device not found\";\n log.error(msg);\n return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();\n }\n DeviceIdentifier deviceIdentifier = AndroidDeviceUtils.convertToDeviceIdentifierObject(id);\n try {\n if (!AndroidDeviceUtils.isValidDeviceIdentifier(deviceIdentifier)) {\n String msg = \"Device not found for identifier '\" + id + \"'\";\n log.error(msg);\n return Response.status(Response.Status.NOT_FOUND).entity(msg).build();\n }\n if (log.isDebugEnabled()) {\n log.debug(\"Invoking Android pending operations:\" + id);\n }\n if (resultOperations != null && !resultOperations.isEmpty()) {\n updateOperations(id, resultOperations);\n }\n } catch (OperationManagementException e) {\n String msg = \"Issue in retrieving operation management service instance\";\n log.error(msg, e);\n throw new UnexpectedServerErrorException(\n new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build());\n } catch (PolicyComplianceException e) {\n String msg = \"Issue in updating Monitoring operation\";\n log.error(msg, e);\n throw new UnexpectedServerErrorException(\n new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build());\n } catch (DeviceManagementException e) {\n String msg = \"Issue in retrieving device management service instance\";\n log.error(msg, e);\n throw new UnexpectedServerErrorException(\n new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build());\n } catch (ApplicationManagementException e) {\n String msg = \"Issue in retrieving application management service instance\";\n log.error(msg, e);\n throw new UnexpectedServerErrorException(\n new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build());\n } catch (NotificationManagementException e) {\n String msg = \"Issue in retrieving Notification management service instance\";\n log.error(msg, e);\n throw new UnexpectedServerErrorException(\n new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build());\n }\n\n List pendingOperations;\n try {\n pendingOperations = AndroidDeviceUtils.getPendingOperations(deviceIdentifier);\n } catch (OperationManagementException e) {\n String msg = \"Issue in retrieving operation management service instance\";\n log.error(msg, e);\n throw new UnexpectedServerErrorException(\n new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build());\n }\n return Response.status(Response.Status.CREATED).entity(pendingOperations).build();\n }\n\n private void updateOperations(String deviceId, List operations)\n throws OperationManagementException, PolicyComplianceException,\n ApplicationManagementException, NotificationManagementException, DeviceManagementException {\n for (org.wso2.carbon.device.mgt.common.operation.mgt.Operation operation : operations) {\n AndroidDeviceUtils.updateOperation(deviceId, operation);\n if (OPERATION_ERROR_STATUS.equals(operation.getStatus().toString())) {\n org.wso2.carbon.device.mgt.common.notification.mgt.Notification notification = new\n org.wso2.carbon.device.mgt.common.notification.mgt.Notification();\n DeviceIdentifier id = new DeviceIdentifier();\n id.setId(deviceId);\n id.setType(AndroidConstants.DEVICE_TYPE_ANDROID);\n String deviceName = AndroidAPIUtils.getDeviceManagementService().getDevice(id, false).getName();\n notification.setOperationId(operation.getId());\n notification.setStatus(org.wso2.carbon.device.mgt.common.notification.mgt.Notification.\n Status.NEW.toString());\n notification.setDescription(operation.getCode() + \" operation failed to execute on device \" +\n deviceName + \" (ID: \" + deviceId + \")\");\n AndroidAPIUtils.getNotificationManagementService().addNotification(id, notification);\n }\n if (log.isDebugEnabled()) {\n log.debug(\"Updating operation '\" + operation.toString() + \"'\");\n }\n }\n }\n\n @POST\n @Override\n public Response enrollDevice(@Valid AndroidDevice androidDevice) {\n if (androidDevice == null) {\n String errorMessage = \"The payload of the android device enrollment is incorrect.\";\n log.error(errorMessage);\n throw new org.wso2.carbon.mdm.services.android.exception.BadRequestException(", "answers": [" new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage(errorMessage).build());"], "length": 671, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "1523804c-303b-4aec-9787-16001a5d526a", "reasoning": "The method checks for a null androidDevice and logs an error. It then throws a BadRequestException, which in this codebase is constructed with an ErrorResponse object. Following the pattern used elsewhere (e.g., UnexpectedServerErrorException), we create an ErrorResponse via its builder, set a 400 status code and the errorMessage, then build it. The line must close the constructor call and end with a semicolon.", "reasoning_model_answer": "new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage(errorMessage).build());", "assistant_with_reasoning": "\nThe method checks for a null androidDevice and logs an error. It then throws a BadRequestException, which in this codebase is constructed with an ErrorResponse object. Following the pattern used elsewhere (e.g., UnexpectedServerErrorException), we create an ErrorResponse via its builder, set a 400 status code and the errorMessage, then build it. The line must close the constructor call and end with a semicolon.\n\nnew ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage(errorMessage).build());", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.923, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 11475, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage(errorMessage).build());", "score": 0.9, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "##########################################################################\n# \n# Copyright (c) 2011-2012, John Haddon. All rights reserved.\n# Copyright (c) 2013, Image Engine Design Inc. All rights reserved.\n# \n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are\n# met:\n# \n# * Redistributions of source code must retain the above\n# copyright notice, this list of conditions and the following\n# disclaimer.\n# \n# * Redistributions in binary form must reproduce the above\n# copyright notice, this list of conditions and the following\n# disclaimer in the documentation and/or other materials provided with\n# the distribution.\n# \n# * Neither the name of John Haddon nor the names of\n# any other contributors to this software may be used to endorse or\n# promote products derived from this software without specific prior\n# written permission.\n# \n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n# IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n# \n##########################################################################\n\nfrom __future__ import with_statement\n\nimport IECore\n\nimport Gaffer\nimport GafferUI\n\ndef appendDefinitions( menuDefinition, prefix=\"\" ) :\n\n\tmenuDefinition.append( prefix + \"/Undo\", { \"command\" : undo, \"shortCut\" : \"Ctrl+Z\", \"active\" : __undoAvailable } )\n\tmenuDefinition.append( prefix + \"/Redo\", { \"command\" : redo, \"shortCut\" : \"Shift+Ctrl+Z\", \"active\" : __redoAvailable } )\n\tmenuDefinition.append( prefix + \"/UndoDivider\", { \"divider\" : True } )\n\t\n\tmenuDefinition.append( prefix + \"/Cut\", { \"command\" : cut, \"shortCut\" : \"Ctrl+X\", \"active\" : __selectionAvailable } )\n\tmenuDefinition.append( prefix + \"/Copy\", { \"command\" : copy, \"shortCut\" : \"Ctrl+C\", \"active\" : __selectionAvailable } )\n\tmenuDefinition.append( prefix + \"/Paste\", { \"command\" : paste, \"shortCut\" : \"Ctrl+V\", \"active\" : __pasteAvailable } )\n\tmenuDefinition.append( prefix + \"/Delete\", { \"command\" : delete, \"shortCut\" : \"Backspace, Delete\", \"active\" : __selectionAvailable } )\n\tmenuDefinition.append( prefix + \"/CutCopyPasteDeleteDivider\", { \"divider\" : True } )\n\n\tmenuDefinition.append( prefix + \"/Find...\", { \"command\" : find, \"shortCut\" : \"Ctrl+F\" } )\n\tmenuDefinition.append( prefix + \"/FindDivider\", { \"divider\" : True } )\n\n\tmenuDefinition.append( prefix + \"/Arrange\", { \"command\" : arrange, \"shortCut\" : \"Ctrl+L\" } )\n\tmenuDefinition.append( prefix + \"/ArrangeDivider\", { \"divider\" : True } )\n\n\tmenuDefinition.append( prefix + \"/Select All\", { \"command\" : selectAll, \"shortCut\" : \"Ctrl+A\" } )\n\tmenuDefinition.append( prefix + \"/Select None\", { \"command\" : selectNone, \"shortCut\" : \"Shift+Ctrl+A\", \"active\" : __selectionAvailable } )\n\n\tmenuDefinition.append( prefix + \"/Select Connected/Inputs\", { \"command\" : selectInputs, \"active\" : __selectionAvailable } )\n\tmenuDefinition.append( prefix + \"/Select Connected/Add Inputs\", { \"command\" : selectAddInputs, \"active\" : __selectionAvailable } )\n\tmenuDefinition.append( prefix + \"/Select Connected/InputsDivider\", { \"divider\" : True } )\n\tmenuDefinition.append( prefix + \"/Select Connected/Outputs\", { \"command\" : selectOutputs, \"active\" : __selectionAvailable } )\n\tmenuDefinition.append( prefix + \"/Select Connected/Add Outputs\", { \"command\" : selectAddOutputs, \"active\" : __selectionAvailable } )\n\n## A function suitable as the command for an Edit/Undo menu item. It must\n# be invoked from a menu that has a ScriptWindow in its ancestry.\ndef undo( menu ) :\n\n\tscriptWindow = menu.ancestor( GafferUI.ScriptWindow )\n\tscript = scriptWindow.scriptNode()\n\tscript.undo()\n\t\n## A function suitable as the command for an Edit/Redo menu item. It must\n# be invoked from a menu that has a ScriptWindow in its ancestry.\ndef redo( menu ) :\n\n\tscriptWindow = menu.ancestor( GafferUI.ScriptWindow )\n\tscript = scriptWindow.scriptNode()\n\tscript.redo()\n\n## A function suitable as the command for an Edit/Cut menu item. It must\n# be invoked from a menu that has a ScriptWindow in its ancestry.", "answers": ["def cut( menu ) :"], "length": 666, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "8ede7857-be9f-4b97-82f9-e0c3ef98e044", "reasoning": "The comment introduces the implementation of the Cut command function, matching the pattern used for undo and redo. The next line should start the function definition with the same formatting style: \"def cut( menu ) :\".", "reasoning_model_answer": "def cut( menu ) :", "assistant_with_reasoning": "\nThe comment introduces the implementation of the Cut command function, matching the pattern used for undo and redo. The next line should start the function definition with the same formatting style: \"def cut( menu ) :\".\n\ndef cut( menu ) :", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 2.327, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 4862, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "def cut( menu ) :", "score": 1.0, "is_full_score": true, "is_nonzero_score": true}} {"input": "", "context": "using Server.ContextMenus;\nusing Server.Engines.Craft;\nusing System;\nusing System.Collections.Generic;\n\nnamespace Server.Items\n{\n public enum GemType\n {\n None,\n StarSapphire,\n Emerald,\n Sapphire,\n Ruby,\n Citrine,\n Amethyst,\n Tourmaline,\n Amber,\n Diamond\n }\n\n public abstract class BaseJewel : Item, ICraftable, ISetItem, IWearableDurability, IResource, IVvVItem, IOwnerRestricted, ITalismanProtection, IArtifact, ICombatEquipment, IQuality\n {\n private int m_MaxHitPoints;\n private int m_HitPoints;\n\n private AosAttributes m_AosAttributes;\n private AosElementAttributes m_AosResistances;\n private AosSkillBonuses m_AosSkillBonuses;\n private SAAbsorptionAttributes m_SAAbsorptionAttributes;\n private NegativeAttributes m_NegativeAttributes;\n private CraftResource m_Resource;\n private GemType m_GemType;\n\n #region Stygian Abyss\n private int m_TimesImbued;\n private bool m_IsImbued;\n private int m_GorgonLenseCharges;\n private LenseType m_GorgonLenseType;\n #endregion\n\n #region Runic Reforging\n private ItemPower m_ItemPower;\n private ReforgedPrefix m_ReforgedPrefix;\n private ReforgedSuffix m_ReforgedSuffix;\n #endregion\n\n private TalismanAttribute m_TalismanProtection;\n\n private bool _VvVItem;\n private Mobile _Owner;\n private string _OwnerName;\n\n [CommandProperty(AccessLevel.GameMaster)]\n public TalismanAttribute Protection\n {\n get { return m_TalismanProtection; }\n set { m_TalismanProtection = value; InvalidateProperties(); }\n }\n\n [CommandProperty(AccessLevel.GameMaster)]\n public bool IsVvVItem\n {\n get { return _VvVItem; }\n set { _VvVItem = value; InvalidateProperties(); }\n }\n\n [CommandProperty(AccessLevel.GameMaster)]\n public Mobile Owner\n {\n get { return _Owner; }\n set { _Owner = value; if (_Owner != null) _OwnerName = _Owner.Name; InvalidateProperties(); }\n }\n\n public virtual string OwnerName\n {\n get { return _OwnerName; }\n set { _OwnerName = value; InvalidateProperties(); }\n }\n\n private Mobile m_BlessedBy;\n\n [CommandProperty(AccessLevel.GameMaster)]\n public Mobile BlessedBy\n {\n get\n {\n return m_BlessedBy;\n }\n set\n {\n m_BlessedBy = value;\n InvalidateProperties();\n }\n }\n\n public override void GetContextMenuEntries(Mobile from, List list)\n {\n base.GetContextMenuEntries(from, list);\n\n if (BlessedFor == from && BlessedBy == from && RootParent == from)\n {\n list.Add(new UnBlessEntry(from, this));\n }\n }\n\n private class UnBlessEntry : ContextMenuEntry\n {\n private readonly Mobile m_From;\n private readonly BaseJewel m_Item;\n\n public UnBlessEntry(Mobile from, BaseJewel item)\n : base(6208, -1)\n {\n m_From = from;\n m_Item = item;\n }\n\n public override void OnClick()\n {\n m_Item.BlessedFor = null;\n m_Item.BlessedBy = null;\n\n Container pack = m_From.Backpack;\n\n if (pack != null)\n {\n pack.DropItem(new PersonalBlessDeed(m_From));\n m_From.SendLocalizedMessage(1062200); // A personal bless deed has been placed in your backpack.\n }\n }\n }\n\n [CommandProperty(AccessLevel.GameMaster)]\n public int MaxHitPoints\n {\n get\n {\n return m_MaxHitPoints;\n }\n set\n {\n m_MaxHitPoints = value;\n\n if (m_MaxHitPoints > 255)\n m_MaxHitPoints = 255;\n\n InvalidateProperties();\n }\n }\n\n [CommandProperty(AccessLevel.GameMaster)]\n public int HitPoints\n {\n get\n {\n return m_HitPoints;\n }\n set\n {\n if (value != m_HitPoints && MaxHitPoints > 0)\n {\n m_HitPoints = value;\n\n if (m_HitPoints < 0)\n Delete();\n else if (m_HitPoints > MaxHitPoints)\n m_HitPoints = MaxHitPoints;\n\n InvalidateProperties();\n }\n }\n }\n\n [CommandProperty(AccessLevel.Player)]\n public AosAttributes Attributes\n {\n get\n {\n return m_AosAttributes;\n }\n set\n {\n }\n }\n\n [CommandProperty(AccessLevel.GameMaster)]\n public AosElementAttributes Resistances\n {\n get\n {\n return m_AosResistances;\n }\n set\n {\n }\n }\n\n [CommandProperty(AccessLevel.GameMaster)]\n public AosSkillBonuses SkillBonuses\n {\n get\n {\n return m_AosSkillBonuses;\n }\n set\n {\n }\n }\n\n [CommandProperty(AccessLevel.GameMaster)]\n public SAAbsorptionAttributes AbsorptionAttributes\n {\n get\n {\n return m_SAAbsorptionAttributes;\n }\n set\n {\n }\n }\n\n [CommandProperty(AccessLevel.Player)]\n public NegativeAttributes NegativeAttributes\n {\n get\n {\n return m_NegativeAttributes;\n }\n set\n {\n }\n }\n\n [CommandProperty(AccessLevel.GameMaster)]\n public CraftResource Resource\n {\n get\n {\n return m_Resource;\n }\n set\n {\n m_Resource = value;\n Hue = CraftResources.GetHue(m_Resource);\n }\n }\n\n [CommandProperty(AccessLevel.GameMaster)]\n public GemType GemType\n {\n get\n {\n return m_GemType;\n }\n set\n {\n GemType old = m_GemType;\n m_GemType = value;\n OnGemTypeChange(old);\n InvalidateProperties();\n }\n }\n\n #region SA\n [CommandProperty(AccessLevel.GameMaster)]\n public int TimesImbued\n {\n get { return m_TimesImbued; }\n set { m_TimesImbued = value; InvalidateProperties(); }\n }\n\n [CommandProperty(AccessLevel.GameMaster)]\n public bool IsImbued\n {\n get\n {\n if (TimesImbued >= 1 && !m_IsImbued)\n m_IsImbued = true;\n\n return m_IsImbued;\n }\n set\n {\n if (TimesImbued >= 1)\n m_IsImbued = true;\n else\n m_IsImbued = value; InvalidateProperties();\n }\n }\n\n [CommandProperty(AccessLevel.GameMaster)]\n public int GorgonLenseCharges\n {\n get { return m_GorgonLenseCharges; }\n set { m_GorgonLenseCharges = value; if (value == 0) m_GorgonLenseType = LenseType.None; InvalidateProperties(); }\n }\n", "answers": [" [CommandProperty(AccessLevel.GameMaster)]"], "length": 570, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "56c8da96-07b6-425f-bd2c-594fae9a2539", "reasoning": "The snippet ends after the GorgonLenseCharges property definition. In the original BaseJewel class, the next member is the GorgonLenseType property, which is preceded by the same CommandProperty attribute. Therefore the immediate next line of code is the attribute declaration for that property.", "reasoning_model_answer": "[CommandProperty(AccessLevel.GameMaster)]", "assistant_with_reasoning": "\nThe snippet ends after the GorgonLenseCharges property definition. In the original BaseJewel class, the next member is the GorgonLenseType property, which is preceded by the same CommandProperty attribute. Therefore the immediate next line of code is the attribute declaration for that property.\n\n[CommandProperty(AccessLevel.GameMaster)]", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.232, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 7848, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "[CommandProperty(AccessLevel.GameMaster)]", "score": 0.91, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n###############################################################################\n# Copyright Kitware Inc.\n#\n# Licensed under the Apache License, Version 2.0 ( the \"License\" );\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n###############################################################################\n\nimport datetime\nimport six\nfrom bson import json_util\n\nfrom girder import events\nfrom girder.constants import AccessType, SortDir\nfrom girder.exceptions import ValidationException\nfrom girder.models.model_base import AccessControlledModel\nfrom girder.models.notification import Notification\nfrom girder.models.token import Token\nfrom girder.models.user import User\nfrom girder.plugins.jobs.constants import JobStatus, JOB_HANDLER_LOCAL\n\n\nclass Job(AccessControlledModel):\n\n def initialize(self):\n self.name = 'job'\n compoundSearchIndex = (\n ('userId', SortDir.ASCENDING),\n ('created', SortDir.DESCENDING),\n ('type', SortDir.ASCENDING),\n ('status', SortDir.ASCENDING)\n )\n self.ensureIndices([(compoundSearchIndex, {}),\n 'created', 'parentId', 'celeryTaskId'])\n\n self.exposeFields(level=AccessType.READ, fields={\n 'title', 'type', 'created', 'interval', 'when', 'status',\n 'progress', 'log', 'meta', '_id', 'public', 'parentId', 'async',\n 'updated', 'timestamps', 'handler', 'jobInfoSpec'})\n\n self.exposeFields(level=AccessType.SITE_ADMIN, fields={'args', 'kwargs'})\n\n def validate(self, job):\n self._validateStatus(job['status'])\n\n return job\n\n def _validateStatus(self, status):\n if not JobStatus.isValid(status):\n raise ValidationException(\n 'Invalid job status %s.' % status, field='status')\n\n def _validateChild(self, parentJob, childJob):\n if str(parentJob['_id']) == str(childJob['_id']):\n raise ValidationException('Child Id cannot be equal to Parent Id')\n if childJob['parentId']:\n raise ValidationException('Cannot overwrite the Parent Id')\n\n def list(self, user=None, types=None, statuses=None,\n limit=0, offset=0, sort=None, currentUser=None, parentJob=None):\n \"\"\"\n List a page of jobs for a given user.\n\n :param user: The user who owns the job.\n :type user: dict, 'all', 'none', or None.\n :param types: job type filter.\n :type types: array of type string, or None.\n :param statuses: job status filter.\n :type statuses: array of status integer, or None.\n :param limit: The page limit.\n :param limit: The page limit.\n :param offset: The page offset.\n :param sort: The sort field.\n :param parentJob: Parent Job.\n :param currentUser: User for access filtering.\n \"\"\"\n return self.findWithPermissions(\n offset=offset, limit=limit, sort=sort, user=currentUser,\n types=types, statuses=statuses, jobUser=user, parentJob=parentJob)\n\n def findWithPermissions(self, query=None, offset=0, limit=0, timeout=None, fields=None,\n sort=None, user=None, level=AccessType.READ,\n types=None, statuses=None, jobUser=None, parentJob=None, **kwargs):\n \"\"\"\n Search the list of jobs.\n :param query: The search query (see general MongoDB docs for \"find()\")\n :type query: dict\n :param offset: The offset into the results\n :type offset: int\n :param limit: Maximum number of documents to return\n :type limit: int\n :param timeout: Cursor timeout in ms. Default is no timeout.\n :type timeout: int\n :param fields: A mask for filtering result documents by key, or None to return the full\n document, passed to MongoDB find() as the `projection` param.\n :type fields: `str, list of strings or tuple of strings for fields to be included from the\n document, or dict for an inclusion or exclusion projection`.\n :param sort: The sort order.\n :type sort: List of (key, order) tuples.\n :param user: The user to check policies against.\n :type user: dict or None\n :param level: The access level. Explicitly passing None skips doing\n permissions checks.\n :type level: AccessType\n :param types: job type filter.\n :type types: array of type string, or None.\n :param statuses: job status filter.\n :type statuses: array of status integer, or None.\n :param jobUser: The user who owns the job.\n :type jobUser: dict, 'all', 'none', or None.\n :param parentJob: Parent Job.\n :returns: A pymongo Cursor or CommandCursor. If a CommandCursor, it\n has been augmented with a count function.\n \"\"\"\n if query is None:\n query = {}\n # When user is 'all', no filtering by user, list jobs of all users.\n if jobUser == 'all':\n pass\n # When user is 'none' or None, list anonymous user jobs.\n elif jobUser == 'none' or jobUser is None:\n query['userId'] = None\n # Otherwise, filter by user id\n else:", "answers": [" query['userId'] = jobUser['_id']"], "length": 624, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "82374866-b1b9-4fca-b27f-f01c95490d30", "reasoning": "The method is constructing a Mongo query based on the 'jobUser' filter. After handling the special cases 'all' and 'none'/None, the else branch should add a filter for a specific user's jobs. The user document is passed in as 'jobUser', so the query should match its '_id'. Therefore the next line sets query['userId'] to jobUser['_id'].", "reasoning_model_answer": "query['userId'] = jobUser['_id']", "assistant_with_reasoning": "\nThe method is constructing a Mongo query based on the 'jobUser' filter. After handling the special cases 'all' and 'none'/None, the else branch should add a filter for a specific user's jobs. The user document is passed in as 'jobUser', so the query should match its '_id'. Therefore the next line sets query['userId'] to jobUser['_id'].\n\nquery['userId'] = jobUser['_id']", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.298, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 5818, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "query['userId'] = jobUser['_id']", "score": 0.8, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/************************************************************************************\n\nCopyright : Copyright 2014 Oculus VR, LLC. All Rights reserved.\n\nLicensed under the Oculus VR Rift SDK License Version 3.2 (the \"License\");\nyou may not use the Oculus VR Rift SDK except in compliance with the License,\nwhich is provided at the time of installation or download, or which\notherwise accompanies this software in either electronic or hard copy form.\n\nYou may obtain a copy of the License at\n\nhttp://www.oculusvr.com/licenses/LICENSE-3.2\n\nUnless required by applicable law or agreed to in writing, the Oculus VR SDK\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\n************************************************************************************/\n\n#if !UNITY_5\n#define OVR_LEGACY\n#endif\n\nusing System;\nusing System.Runtime.InteropServices;\n\n// Internal C# wrapper for OVRPlugin.\n\ninternal static class OVRPlugin\n{\n\tpublic static System.Version wrapperVersion = new System.Version(\"0.1.2.0\");\n\tprivate static System.Version v0110 = new System.Version(0, 1, 1, 0);\n\tprivate static System.Version v0120 = new System.Version(0, 1, 2, 0);\n\tprivate static System.Version v0500 = new System.Version(0, 5, 0, 0);\n\n\tprivate enum Bool\n\t{\n\t\tFalse = 0,\n\t\tTrue\n\t}\n\n\tpublic enum Eye\n\t{\n\t\tNone = -1,\n\t\tLeft = 0,\n\t\tRight = 1,\n\t\tCount = 2\n\t}\n\n\tpublic enum Tracker\n\t{\n\t\tDefault = 0,\n\t\tCount,\n\t}\n\n\tpublic enum Node\n\t{\n\t\tNone = -1,\n\t\tLeftEye = 0,\n\t\tRightEye = 1,\n\t\tCenterEye = 2,\n\t\tLeftHand = 3,\n\t\tRightHand = 4,\n\t\tTrackerDefault = 5,\n\t\tCount,\n\t}\n\n\tpublic enum BatteryStatus\n\t{\n\t\tCharging = 0,\n\t\tDischarging,\n\t\tFull,\n\t\tNotCharging,\n\t\tUnknown,\n\t}\n\n\tpublic enum PlatformUI\n\t{\n\t\tGlobalMenu = 0,\n\t\tConfirmQuit,\n\t}\n\n\tprivate enum Key\n\t{\n\t\tVersion = 0,\n\t\tProductName,\n\t\tLatency,\n\t\tEyeDepth,\n\t\tEyeHeight,\n\t\tBatteryLevel,\n\t\tBatteryTemperature,\n\t\tCpuLevel,\n\t\tGpuLevel,\n\t\tSystemVolume,\n\t\tQueueAheadFraction,\n\t\tIPD,\n\t\tNativeTextureScale,\n\t\tVirtualTextureScale,\n Frequency,\n }\n\n\tprivate enum Caps\n\t{\n\t\tSRGB = 0,\n\t\tChromatic,\n\t\tFlipInput,\n\t\tRotation,\n\t\tHeadModel,\n\t\tPosition,\n\t\tCollectPerf,\n\t\tDebugDisplay,\n\t\tMonoscopic,\n\t\tShareTexture,\n\t}\n\n\tprivate enum Status\n\t{\n\t\tDebug = 0,\n\t\tHSWVisible,\n\t\tPositionSupported,\n\t\tPositionTracked,\n\t\tPowerSaving,\n\t\tInitialized,\n\t\tHMDPresent,\n\t\tUserPresent,\n\t}\n\n\t[StructLayout(LayoutKind.Sequential)]\n\tpublic struct Vector2i\n\t{\n\t\tpublic int x;\n\t\tpublic int y;\n\t}\n\n\t[StructLayout(LayoutKind.Sequential)]\n\tpublic struct Vector2f\n\t{\n\t\tpublic float x;\n\t\tpublic float y;\n\t}\n\n\t[StructLayout(LayoutKind.Sequential)]\n\tpublic struct Vector3f\n\t{\n\t\tpublic float x;\n\t\tpublic float y;\n\t\tpublic float z;\n\t}\n\n\t[StructLayout(LayoutKind.Sequential)]\n\tpublic struct Quatf\n\t{\n\t\tpublic float x;\n\t\tpublic float y;\n\t\tpublic float z;\n\t\tpublic float w;\n\t}\n\n\t[StructLayout(LayoutKind.Sequential)]\n\tpublic struct Posef\n\t{\n\t\tpublic Quatf Orientation;\n\t\tpublic Vector3f Position;\n\t}\n\n\t[StructLayout(LayoutKind.Sequential)]\n\tpublic struct InputState\n\t{\n\t\tpublic uint ConnectedControllers;\n\t\tpublic uint Buttons;\n\t\tpublic uint Touches;\n\t\tpublic uint NearTouches;\n\t\tpublic float LIndexTrigger;\n\t\tpublic float RIndexTrigger;\n\t\tpublic float LHandTrigger;\n\t\tpublic float RHandTrigger;\n\t\tpublic Vector2f LThumbstick;\n\t\tpublic Vector2f RThumbstick;\n\t}\n\n\t[StructLayout(LayoutKind.Sequential)]\n\tpublic struct Sizei\n\t{\n\t\tpublic int w;\n\t\tpublic int h;\n\t}\n\n\t[StructLayout(LayoutKind.Sequential)]\n\tpublic struct Frustumf\n\t{\n\t\tpublic float zNear;\n\t\tpublic float zFar;\n\t\tpublic float fovX;\n\t\tpublic float fovY;\n\t}\n\n\tpublic static bool srgb\n\t{\n\t\tget { return GetCap(Caps.SRGB); }\n\t\tset { SetCap(Caps.SRGB, value); }\n\t}\n\n\tpublic static bool chromatic\n\t{\n\t\tget { return GetCap(Caps.Chromatic); }\n\t\tset { SetCap(Caps.Chromatic, value); }\n\t}\n\n\tpublic static bool flipInput\n\t{\n\t\tget { return GetCap(Caps.FlipInput); }\n\t\tset { SetCap(Caps.FlipInput, value); }\n\t}\n\n\tpublic static bool rotation\n\t{\n\t\tget { return GetCap(Caps.Rotation); }\n\t\tset { SetCap(Caps.Rotation, value); }\n\t}\n\n\tpublic static bool headModel\n\t{\n\t\tget { return GetCap(Caps.HeadModel); }\n\t\tset { SetCap(Caps.HeadModel, value); }\n\t}\n\n\tpublic static bool position\n\t{\n\t\tget { return GetCap(Caps.Position); }\n\t\tset { SetCap(Caps.Position, value); }\n\t}\n\n\tpublic static bool collectPerf\n\t{\n\t\tget { return GetCap(Caps.CollectPerf); }\n\t\tset { SetCap(Caps.CollectPerf, value); }\n\t}\n\n\tpublic static bool debugDisplay\n\t{\n\t\tget { return GetCap(Caps.DebugDisplay); }\n\t\tset { SetCap(Caps.DebugDisplay, value); }\n\t}\n\n\tpublic static bool monoscopic\n\t{\n\t\tget { return GetCap(Caps.Monoscopic); }\n\t\tset { SetCap(Caps.Monoscopic, value); }\n\t}\n\n\tpublic static bool debug { get { return GetStatus(Status.Debug); } }\n\n\tpublic static bool userPresent { get { return true; /*TODO return GetStatus(Status.UserPresent);*/ } }\n\n\tpublic static bool hmdPresent { get { return GetStatus(Status.HMDPresent); } }\n\n\tpublic static bool hswVisible { get { return GetStatus(Status.HSWVisible); } }", "answers": ["\tpublic static bool positionSupported { get { return GetStatus(Status.PositionSupported); } }"], "length": 647, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "22ccbb64-25a2-493d-8232-34e8797daa89", "reasoning": "The class defines a series of boolean properties that wrap calls to GetStatus for each value in the Status enum. After the hswVisible property, the next logical property is for the next enum member, PositionSupported. Following the same pattern, the next line should be a public static bool property named positionSupported that returns GetStatus(Status.PositionSupported).", "reasoning_model_answer": "public static bool positionSupported { get { return GetStatus(Status.PositionSupported); } }", "assistant_with_reasoning": "\nThe class defines a series of boolean properties that wrap calls to GetStatus for each value in the Status enum. After the hswVisible property, the next logical property is for the next enum member, PositionSupported. Following the same pattern, the next line should be a public static bool property named positionSupported that returns GetStatus(Status.PositionSupported).\n\npublic static bool positionSupported { get { return GetStatus(Status.PositionSupported); } }", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.134, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 5215, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "public static bool positionSupported { get { return GetStatus(Status.PositionSupported); } }", "score": 0.99, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "//------------------------------------------------------------------------------\n// \n// Copyright (c) Microsoft Corporation. All rights reserved.\n// \n//------------------------------------------------------------------------------\n\n/*\n*/\nnamespace System.Windows.Forms {\n using System.Runtime.InteropServices;\n\n using System;\n using System.Collections;\n using System.ComponentModel;\n using System.ComponentModel.Design;\n using System.Diagnostics;\n using System.Drawing.Design;\n using System.Globalization;\n\n /// \n /// \n /// [To be supplied.]\n /// \n [\n Editor(\"System.Windows.Forms.Design.TreeNodeCollectionEditor, \" + AssemblyRef.SystemDesign, typeof(UITypeEditor))\n ]\n public class TreeNodeCollection : IList {\n private TreeNode owner;\n\n /// A caching mechanism for key accessor\n /// We use an index here rather than control so that we don't have lifetime\n /// issues by holding on to extra references.\n private int lastAccessedIndex = -1;\n\t\t\n //this index is used to optimize performance of AddRange\n //items are added from last to first after this index \n //(to work around TV_INSertItem comctl32 perf issue with consecutive adds in the end of the list) \n private int fixedIndex = -1;\n \n\n internal TreeNodeCollection(TreeNode owner) {\n this.owner = owner;\n }\n \n /// \n /// \n internal int FixedIndex\n {\n get {\n return fixedIndex;\n }\n set {\n fixedIndex = value;\n }\n }\n\n\n /// \n /// \n /// [To be supplied.]\n /// \n public virtual TreeNode this[int index] {\n get {\n if (index < 0 || index >= owner.childCount) {\n throw new ArgumentOutOfRangeException(\"index\");\n }\n return owner.children[index];\n }\n set {\n if (index < 0 || index >= owner.childCount)\n throw new ArgumentOutOfRangeException(\"index\", SR.GetString(SR.InvalidArgument, \"index\", (index).ToString(CultureInfo.CurrentCulture)));\n value.parent = owner;\n value.index = index;\n owner.children[index] = value;\n value.Realize(false);\n }\n }\n \n /// \n /// \n object IList.this[int index] {\n get {\n return this[index];\n }\n set {\n if (value is TreeNode) {\n this[index] = (TreeNode)value;\n }\n else { \n throw new ArgumentException(SR.GetString(SR.TreeNodeCollectionBadTreeNode), \"value\");\n }\n }\n }\n\n /// \n /// \n /// Retrieves the child control with the specified key.\n /// \n public virtual TreeNode this[string key] {\n get {\n // We do not support null and empty string as valid keys.\n if (string.IsNullOrEmpty(key)){\n return null;\n }\n\n // Search for the key in our collection\n int index = IndexOfKey(key);\n if (IsValidIndex(index)) {\n return this[index];\n }\n else {\n return null;\n }\n\n }\n }\n /// \n /// \n /// [To be supplied.]\n /// \n // VSWhidbey 152051: Make this property available to Intellisense. (Removed the EditorBrowsable attribute.)\n [Browsable(false)]\n public int Count {\n get {\n return owner.childCount;\n }\n }\n\n /// \n /// \n object ICollection.SyncRoot {\n get {\n return this;\n }\n }\n\n /// \n /// \n bool ICollection.IsSynchronized {\n get {\n return false;\n }\n }\n \n /// \n /// \n bool IList.IsFixedSize {\n get {\n return false;\n }\n }\n \n /// \n /// \n /// [To be supplied.]\n /// \n public bool IsReadOnly {\n get { \n return false;\n }\n }\n\n /// \n /// \n /// Creates a new child node under this node. Child node is positioned after siblings.\n /// \n public virtual TreeNode Add(string text) {\n TreeNode tn = new TreeNode(text);\n Add(tn);\n return tn;\n }\n\n // <-- NEW ADD OVERLOADS IN WHIDBEY\n\n /// \n /// \n /// Creates a new child node under this node. Child node is positioned after siblings.\n /// \n public virtual TreeNode Add(string key, string text) {\n TreeNode tn = new TreeNode(text);\n tn.Name = key;\n Add(tn);\n return tn;\n }\n\n /// \n /// \n /// Creates a new child node under this node. Child node is positioned after siblings.\n /// ", "answers": [" public virtual TreeNode Add(string key, string text, int imageIndex) {"], "length": 568, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "611373aa-ae4f-4666-8192-0e6c00a43fc2", "reasoning": "The code is defining overloads for the Add method in TreeNodeCollection. After the comment block for the third overload (Add2), the next line should be the method signature for the next overload that includes an image index parameter. Following the pattern of previous overloads, the line is the public virtual method declaration with its parameters and opening brace.", "reasoning_model_answer": "public virtual TreeNode Add(string key, string text, int imageIndex) {", "assistant_with_reasoning": "\nThe code is defining overloads for the Add method in TreeNodeCollection. After the comment block for the third overload (Add2), the next line should be the method signature for the next overload that includes an image index parameter. Following the pattern of previous overloads, the line is the public virtual method declaration with its parameters and opening brace.\n\npublic virtual TreeNode Add(string key, string text, int imageIndex) {", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.18, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 7037, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "public virtual TreeNode Add(string key, string text, int imageIndex) {", "score": 0.95, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "# Copyright (c) 2012 The Chromium Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style license that can be\n# found in the LICENSE file.\n\nfrom code import Code\nfrom model import PropertyType\nimport cpp_util\nimport schema_util\nimport util_cc_helper\n\nclass CCGenerator(object):\n def __init__(self, type_generator, cpp_namespace):\n self._type_generator = type_generator\n self._cpp_namespace = cpp_namespace\n\n def Generate(self, namespace):\n return _Generator(namespace,\n self._type_generator,\n self._cpp_namespace).Generate()\n\n\nclass _Generator(object):\n \"\"\"A .cc generator for a namespace.\n \"\"\"\n def __init__(self, namespace, cpp_type_generator, cpp_namespace):\n self._namespace = namespace\n self._type_helper = cpp_type_generator\n self._cpp_namespace = cpp_namespace\n self._target_namespace = (\n self._type_helper.GetCppNamespaceName(self._namespace))\n self._util_cc_helper = (\n util_cc_helper.UtilCCHelper(self._type_helper))\n self._generate_error_messages = namespace.compiler_options.get(\n 'generate_error_messages', False)\n\n def Generate(self):\n \"\"\"Generates a Code object with the .cc for a single namespace.\n \"\"\"\n c = Code()\n (c.Append(cpp_util.CHROMIUM_LICENSE)\n .Append()\n .Append(cpp_util.GENERATED_FILE_MESSAGE % self._namespace.source_file)\n .Append()\n .Append(self._util_cc_helper.GetIncludePath())\n .Append('#include \"base/logging.h\"')\n .Append('#include \"base/strings/string_number_conversions.h\"')\n .Append('#include \"base/strings/utf_string_conversions.h\"')\n .Append('#include \"%s/%s.h\"' %\n (self._namespace.source_file_dir, self._namespace.unix_name))\n .Cblock(self._type_helper.GenerateIncludes(include_soft=True))\n .Append()\n .Concat(cpp_util.OpenNamespace(self._cpp_namespace))\n .Cblock(self._type_helper.GetNamespaceStart())\n )\n if self._namespace.properties:\n (c.Append('//')\n .Append('// Properties')\n .Append('//')\n .Append()\n )\n for property in self._namespace.properties.values():\n property_code = self._type_helper.GeneratePropertyValues(\n property,\n 'const %(type)s %(name)s = %(value)s;',\n nodoc=True)\n if property_code:\n c.Cblock(property_code)\n if self._namespace.types:\n (c.Append('//')\n .Append('// Types')\n .Append('//')\n .Append()\n .Cblock(self._GenerateTypes(None, self._namespace.types.values()))\n )\n if self._namespace.functions:\n (c.Append('//')\n .Append('// Functions')\n .Append('//')\n .Append()\n )\n for function in self._namespace.functions.values():\n c.Cblock(self._GenerateFunction(function))\n if self._namespace.events:\n (c.Append('//')\n .Append('// Events')\n .Append('//')\n .Append()\n )\n for event in self._namespace.events.values():\n c.Cblock(self._GenerateEvent(event))\n (c.Concat(self._type_helper.GetNamespaceEnd())\n .Cblock(cpp_util.CloseNamespace(self._cpp_namespace))\n )\n return c\n\n def _GenerateType(self, cpp_namespace, type_):\n \"\"\"Generates the function definitions for a type.\n \"\"\"\n classname = cpp_util.Classname(schema_util.StripNamespace(type_.name))\n c = Code()\n\n if type_.functions:\n # Wrap functions within types in the type's namespace.\n (c.Append('namespace %s {' % classname)\n .Append())\n for function in type_.functions.values():\n c.Cblock(self._GenerateFunction(function))\n c.Append('} // namespace %s' % classname)\n elif type_.property_type == PropertyType.ARRAY:\n c.Cblock(self._GenerateType(cpp_namespace, type_.item_type))\n elif type_.property_type in (PropertyType.CHOICES,\n PropertyType.OBJECT):\n if cpp_namespace is None:\n classname_in_namespace = classname\n else:\n classname_in_namespace = '%s::%s' % (cpp_namespace, classname)\n\n if type_.property_type == PropertyType.OBJECT:\n c.Cblock(self._GeneratePropertyFunctions(classname_in_namespace,\n type_.properties.values()))\n else:\n c.Cblock(self._GenerateTypes(classname_in_namespace, type_.choices))\n\n (c.Append('%s::%s()' % (classname_in_namespace, classname))\n .Cblock(self._GenerateInitializersAndBody(type_))\n .Append('%s::~%s() {}' % (classname_in_namespace, classname))\n .Append()\n )\n if type_.origin.from_json:\n c.Cblock(self._GenerateTypePopulate(classname_in_namespace, type_))\n if cpp_namespace is None: # only generate for top-level types\n c.Cblock(self._GenerateTypeFromValue(classname_in_namespace, type_))\n if type_.origin.from_client:\n c.Cblock(self._GenerateTypeToValue(classname_in_namespace, type_))\n elif type_.property_type == PropertyType.ENUM:\n (c.Cblock(self._GenerateEnumToString(cpp_namespace, type_))\n .Cblock(self._GenerateEnumFromString(cpp_namespace, type_))\n )\n\n return c\n\n def _GenerateInitializersAndBody(self, type_):\n items = []\n for prop in type_.properties.values():\n if prop.optional:\n continue\n\n t = prop.type_\n if t.property_type == PropertyType.INTEGER:\n items.append('%s(0)' % prop.unix_name)\n elif t.property_type == PropertyType.DOUBLE:\n items.append('%s(0.0)' % prop.unix_name)\n elif t.property_type == PropertyType.BOOLEAN:\n items.append('%s(false)' % prop.unix_name)\n elif (t.property_type == PropertyType.ANY or\n t.property_type == PropertyType.ARRAY or\n t.property_type == PropertyType.BINARY or # mapped to std::string\n t.property_type == PropertyType.CHOICES or\n t.property_type == PropertyType.ENUM or\n t.property_type == PropertyType.OBJECT or\n t.property_type == PropertyType.FUNCTION or\n t.property_type == PropertyType.REF or\n t.property_type == PropertyType.STRING):\n # TODO(miket): It would be nice to initialize CHOICES and ENUM, but we\n # don't presently have the semantics to indicate which one of a set\n # should be the default.\n continue\n else:\n raise TypeError(t)\n\n if items:\n s = ': %s' % (', '.join(items))\n else:\n s = ''\n s = s + ' {}'\n return Code().Append(s)\n\n def _GenerateTypePopulate(self, cpp_namespace, type_):\n \"\"\"Generates the function for populating a type given a pointer to it.\n\n E.g for type \"Foo\", generates Foo::Populate()\n \"\"\"\n classname = cpp_util.Classname(schema_util.StripNamespace(type_.name))\n c = Code()\n (c.Append('// static')\n .Append('bool %(namespace)s::Populate(')\n .Sblock(' %s) {' % self._GenerateParams(\n ('const base::Value& value', '%(name)s* out'))))\n\n if type_.property_type == PropertyType.CHOICES:\n for choice in type_.choices:\n (c.Sblock('if (%s) {' % self._GenerateValueIsTypeExpression('value',\n choice))\n .Concat(self._GeneratePopulateVariableFromValue(\n choice,\n '(&value)',\n 'out->as_%s' % choice.unix_name,\n 'false',\n is_ptr=True))\n .Append('return true;')\n .Eblock('}')\n )\n (c.Concat(self._GenerateError(\n '\"expected %s, got \" + %s' %\n (\" or \".join(choice.name for choice in type_.choices),\n self._util_cc_helper.GetValueTypeString('value'))))\n .Append('return false;'))\n elif type_.property_type == PropertyType.OBJECT:\n (c.Sblock('if (!value.IsType(base::Value::TYPE_DICTIONARY)) {')\n .Concat(self._GenerateError(\n '\"expected dictionary, got \" + ' +\n self._util_cc_helper.GetValueTypeString('value')))\n .Append('return false;')\n .Eblock('}'))\n\n if type_.properties or type_.additional_properties is not None:", "answers": [" c.Append('const base::DictionaryValue* dict = '"], "length": 580, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "92340676-cdb7-4051-a926-716a760b2460", "reasoning": "The code is inside the OBJECT handling of _GenerateTypePopulate. After verifying the value is a dictionary, the next step is to obtain a dictionary pointer from the base::Value. The typical next line creates a pointer variable for the dictionary, e.g., 'const base::DictionaryValue* dict = nullptr;'. This fits the pattern of subsequent code that will use 'dict' to populate object properties.", "reasoning_model_answer": "c.Append('const base::DictionaryValue* dict = nullptr;')", "assistant_with_reasoning": "\nThe code is inside the OBJECT handling of _GenerateTypePopulate. After verifying the value is a dictionary, the next step is to obtain a dictionary pointer from the base::Value. The typical next line creates a pointer variable for the dictionary, e.g., 'const base::DictionaryValue* dict = nullptr;'. This fits the pattern of subsequent code that will use 'dict' to populate object properties.\n\nc.Append('const base::DictionaryValue* dict = nullptr;')", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 6.969, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 2, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 8221, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "c.Append('const base::DictionaryValue* dict = nullptr;')", "score": 0.85, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "// Copyright 2014 The Bazel Authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\npackage com.google.devtools.build.lib.syntax;\n\nimport static com.google.devtools.build.lib.syntax.compiler.ByteCodeUtils.append;\n\nimport com.google.common.base.Strings;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.Iterables;\nimport com.google.devtools.build.lib.events.Location;\nimport com.google.devtools.build.lib.syntax.ClassObject.SkylarkClassObject;\nimport com.google.devtools.build.lib.syntax.SkylarkList.MutableList;\nimport com.google.devtools.build.lib.syntax.SkylarkList.Tuple;\nimport com.google.devtools.build.lib.syntax.compiler.ByteCodeMethodCalls;\nimport com.google.devtools.build.lib.syntax.compiler.ByteCodeUtils;\nimport com.google.devtools.build.lib.syntax.compiler.DebugInfo;\nimport com.google.devtools.build.lib.syntax.compiler.DebugInfo.AstAccessors;\nimport com.google.devtools.build.lib.syntax.compiler.Jump;\nimport com.google.devtools.build.lib.syntax.compiler.Jump.PrimitiveComparison;\nimport com.google.devtools.build.lib.syntax.compiler.LabelAdder;\nimport com.google.devtools.build.lib.syntax.compiler.VariableScope;\n\nimport net.bytebuddy.implementation.bytecode.ByteCodeAppender;\nimport net.bytebuddy.implementation.bytecode.Duplication;\nimport net.bytebuddy.implementation.bytecode.Removal;\nimport net.bytebuddy.implementation.bytecode.StackManipulation;\n\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.Collections;\nimport java.util.EnumSet;\nimport java.util.IllegalFormatException;\nimport java.util.LinkedHashMap;\nimport java.util.List;\nimport java.util.Map;\n\n/**\n * Syntax node for a binary operator expression.\n */\npublic final class BinaryOperatorExpression extends Expression {\n\n private final Expression lhs;\n\n private final Expression rhs;\n\n private final Operator operator;\n\n public BinaryOperatorExpression(Operator operator, Expression lhs, Expression rhs) {\n this.lhs = lhs;\n this.rhs = rhs;\n this.operator = operator;\n }\n\n public Expression getLhs() {\n return lhs;\n }\n\n public Expression getRhs() {\n return rhs;\n }\n\n /**\n * Returns the operator kind for this binary operation.\n */\n public Operator getOperator() {\n return operator;\n }\n\n @Override\n public String toString() {\n return lhs + \" \" + operator + \" \" + rhs;\n }\n\n /**\n * Implements comparison operators.\n *\n *

    Publicly accessible for reflection and compiled Skylark code.\n */\n public static int compare(Object lval, Object rval, Location location) throws EvalException {\n try {\n return EvalUtils.SKYLARK_COMPARATOR.compare(lval, rval);\n } catch (EvalUtils.ComparisonException e) {\n throw new EvalException(location, e);\n }\n }\n\n /**\n * Implements the \"in\" operator.\n *\n *

    Publicly accessible for reflection and compiled Skylark code.\n */\n public static boolean in(Object lval, Object rval, Location location) throws EvalException {\n if (rval instanceof SkylarkList) {\n for (Object obj : (SkylarkList) rval) {\n if (obj.equals(lval)) {\n return true;\n }\n }\n return false;\n } else if (rval instanceof Collection) {\n return ((Collection) rval).contains(lval);\n } else if (rval instanceof Map) {\n return ((Map) rval).containsKey(lval);\n } else if (rval instanceof SkylarkNestedSet) {\n return ((SkylarkNestedSet) rval).expandedSet().contains(lval);\n } else if (rval instanceof String) {\n if (lval instanceof String) {\n return ((String) rval).contains((String) lval);\n } else {\n throw new EvalException(\n location, \"in operator only works on strings if the left operand is also a string\");\n }\n } else {\n throw new EvalException(\n location, \"in operator only works on lists, tuples, sets, dicts and strings\");\n }\n }\n\n @Override\n Object doEval(Environment env) throws EvalException, InterruptedException {\n Object lval = lhs.eval(env);\n\n // Short-circuit operators\n if (operator == Operator.AND) {\n if (EvalUtils.toBoolean(lval)) {\n return rhs.eval(env);\n } else {\n return lval;\n }\n }\n\n if (operator == Operator.OR) {\n if (EvalUtils.toBoolean(lval)) {\n return lval;\n } else {\n return rhs.eval(env);\n }\n }\n\n Object rval = rhs.eval(env);\n\n switch (operator) {\n case PLUS:\n return plus(lval, rval, env, getLocation());\n\n case PIPE:\n return pipe(lval, rval, getLocation());\n\n case MINUS:\n return minus(lval, rval, getLocation());\n\n case MULT:\n return mult(lval, rval, getLocation());\n\n case DIVIDE:\n return divide(lval, rval, getLocation());\n\n case PERCENT:\n return percent(lval, rval, getLocation());\n\n case EQUALS_EQUALS:\n return lval.equals(rval);\n\n case NOT_EQUALS:\n return !lval.equals(rval);\n\n case LESS:\n return compare(lval, rval, getLocation()) < 0;\n\n case LESS_EQUALS:\n return compare(lval, rval, getLocation()) <= 0;\n\n case GREATER:\n return compare(lval, rval, getLocation()) > 0;\n\n case GREATER_EQUALS:\n return compare(lval, rval, getLocation()) >= 0;\n\n case IN:\n return in(lval, rval, getLocation());\n\n case NOT_IN:\n return !in(lval, rval, getLocation());\n\n default:\n throw new AssertionError(\"Unsupported binary operator: \" + operator);\n } // endswitch\n }\n\n @Override\n public void accept(SyntaxTreeVisitor visitor) {\n visitor.visit(this);\n }\n\n @Override\n void validate(ValidationEnvironment env) throws EvalException {\n lhs.validate(env);\n rhs.validate(env);\n }\n\n @Override\n ByteCodeAppender compile(VariableScope scope, DebugInfo debugInfo) throws EvalException {\n AstAccessors debugAccessors = debugInfo.add(this);\n List code = new ArrayList<>();\n ByteCodeAppender leftCompiled = lhs.compile(scope, debugInfo);", "answers": [" ByteCodeAppender rightCompiled = rhs.compile(scope, debugInfo);"], "length": 643, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "b2573a80-9dee-4ae1-86cf-ea7393a4bf02", "reasoning": "In the compile method, after compiling the left-hand side expression into a ByteCodeAppender (leftCompiled), the next logical step is to compile the right-hand side expression similarly. This mirrors the evaluation order in doEval and prepares both operands for bytecode generation of the binary operator.", "reasoning_model_answer": "ByteCodeAppender rightCompiled = rhs.compile(scope, debugInfo);", "assistant_with_reasoning": "\nIn the compile method, after compiling the left-hand side expression into a ByteCodeAppender (leftCompiled), the next logical step is to compile the right-hand side expression similarly. This mirrors the evaluation order in doEval and prepares both operands for bytecode generation of the binary operator.\n\nByteCodeAppender rightCompiled = rhs.compile(scope, debugInfo);", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 1.729, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 6622, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "ByteCodeAppender rightCompiled = rhs.compile(scope, debugInfo);", "score": 0.97, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "// \n// Copyright (c) 2015 All Rights Reserved\n// \n// Christopher Cameron\n\nusing System;\nusing UnityEngine;\n\nnamespace Hydra.HydraCommon.Utils\n{\n\t///

    \n\t/// \tColorUtils provides utility methods for working with colors.\n\t/// \n\tpublic static class ColorUtils\n\t{\n\t\tpublic static readonly Color hydraPrimary = RGB(17, 154, 144);\n\t\tpublic static readonly Color hydraSecondary = RGB(34, 199, 187);\n\n\t\tpublic enum Gamut\n\t\t{\n\t\t\tRGB,\n\t\t\tHSL\n\t\t}\n\n\t\tpublic enum BlendMode\n\t\t{\n\t\t\tNone,\n\t\t\tReplace,\n\t\t\tNormal,\n\n\t\t\tDarken,\n\t\t\tMultiply,\n\t\t\tColorBurn,\n\t\t\tLinearBurn,\n\t\t\tDarkerColor,\n\n\t\t\tLighten,\n\t\t\tScreen,\n\t\t\tColorDodge,\n\t\t\tAdd,\n\t\t\tLighterColor,\n\n\t\t\tOverlay,\n\t\t\tSoftLight,\n\t\t\tHardLight,\n\t\t\tPinLight,\n\t\t\tHardMix,\n\n\t\t\tDifference,\n\t\t\tExclusion,\n\t\t\tSubtract,\n\t\t\tDivide,\n\n\t\t\tHue,\n\t\t\tSaturation,\n\t\t\tColor,\n\t\t\tLuminosity\n\t\t}\n\n\t\t/// \n\t\t/// \tReturns a color based on the given rgb 0-255 values.\n\t\t/// \n\t\t/// Red.\n\t\t/// Green.\n\t\t/// Blue.\n\t\tpublic static Color RGB(int red, int green, int blue)\n\t\t{\n\t\t\treturn new Color(red / 255.0f, green / 255.0f, blue / 255.0f);\n\t\t}\n\n\t\t/// \n\t\t/// \tReturns a linear color at the delta between the two input colors.\n\t\t/// \n\t\t/// Color a.\n\t\t/// Color b.\n\t\t/// Delta.\n\t\tpublic static Color Lerp(Color colorA, Color colorB, float delta)\n\t\t{\n\t\t\treturn new Color(Mathf.Lerp(colorA.r, colorB.r, delta), Mathf.Lerp(colorA.g, colorB.g, delta),\n\t\t\t\t\t\t\t Mathf.Lerp(colorA.b, colorB.b, delta), Mathf.Lerp(colorA.a, colorB.a, delta));\n\t\t}\n\n\t\t/// \n\t\t/// \tConverts RGB color values to HSL.\n\t\t/// \n\t\t/// The HSL value.\n\t\t/// Red.\n\t\t/// Green.\n\t\t/// Blue.\n\t\t/// Alpha.\n\t\tpublic static Vector4 RgbToHsl(float red, float green, float blue, float alpha)\n\t\t{\n\t\t\tfloat max = HydraMathUtils.Max(red, green, blue);\n\t\t\tfloat min = HydraMathUtils.Min(red, green, blue);\n\n\t\t\tfloat hue = (max + min) / 2.0f;\n\t\t\tfloat saturation;\n\t\t\tfloat lightness = hue;\n\n\t\t\tif (HydraMathUtils.Approximately(max, min))\n\t\t\t{\n\t\t\t\t// achromatic\n\t\t\t\thue = 0.0f;\n\t\t\t\tsaturation = 0.0f;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tfloat delta = max - min;\n\n\t\t\t\tsaturation = (lightness > 0.5f) ? delta / (2.0f - max - min) : delta / (max + min);\n\n\t\t\t\tif (red >= green && red >= blue)\n\t\t\t\t\thue = (green - blue) / delta + (green < blue ? 6.0f : 0.0f);\n\t\t\t\telse if (green >= red && green >= blue)\n\t\t\t\t\thue = (blue - red) / delta + 2.0f;\n\t\t\t\telse\n\t\t\t\t\thue = (red - green) / delta + 4.0f;\n\n\t\t\t\thue /= 6.0f;\n\t\t\t}\n\n\t\t\treturn new Vector4(hue, saturation, lightness, alpha);\n\t\t}\n\n\t\t/// \n\t\t/// \tConverts RGB color values to HSL.\n\t\t/// \n\t\t/// The HSL value.\n\t\t/// Red.\n\t\t/// Green.\n\t\t/// Blue.\n\t\tpublic static Vector4 RgbToHsl(float red, float green, float blue)\n\t\t{\n\t\t\treturn RgbToHsl(red, green, blue, 1.0f);\n\t\t}\n\n\t\t/// \n\t\t/// \tConverts RGB color values to HSL.\n\t\t/// \n\t\t/// The HSL value.\n\t\t/// Color.\n\t\tpublic static Vector4 RgbToHsl(Color color)\n\t\t{\n\t\t\treturn RgbToHsl(color.r, color.g, color.b, color.a);\n\t\t}\n\n\t\t/// \n\t\t/// \tConverts RGB color values to a Vector3. Color(0.5, 0.5, 0.5) is Vector3(0, 0, 0).\n\t\t/// \n\t\t/// The vector.\n\t\t/// Color.\n\t\tpublic static Vector3 RgbToVector(Color color)\n\t\t{\n\t\t\treturn new Vector3((color.r - 0.5f) * 2.0f, (color.g - 0.5f) * 2.0f, (color.b - 0.5f) * 2.0f);\n\t\t}\n\n\t\t/// \n\t\t/// \tConverts HSL color values to RGB.\n\t\t/// \n\t\t/// The RGB value.\n\t\t/// Hue.\n\t\t/// Saturation.\n\t\t/// Lightness.\n\t\t/// Alpha.\n\t\tpublic static Color HslToRgb(float hue, float saturation, float lightness, float alpha)\n\t\t{\n\t\t\t// Achromatic\n\t\t\tif (HydraMathUtils.Approximately(saturation, 0.0f))\n\t\t\t\treturn new Color(lightness, lightness, lightness, alpha);\n\n\t\t\tfloat q = (lightness < 0.5f) ? lightness * (1.0f + saturation) : lightness + saturation - lightness * saturation;\n\t\t\tfloat p = 2.0f * lightness - q;\n\n\t\t\tfloat r = HueToChannel(p, q, hue + 1.0f / 3.0f);", "answers": ["\t\t\tfloat g = HueToChannel(p, q, hue);"], "length": 575, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "47bbe760-26b5-4dc3-8906-0dc9c795aae5", "reasoning": "In the HslToRgb method, after calculating the red channel with HueToChannel, the standard conversion computes the green and blue channels next. The next logical line is the calculation of the green channel using the same helper function with the original hue value.", "reasoning_model_answer": "float g = HueToChannel(p, q, hue);", "assistant_with_reasoning": "\nIn the HslToRgb method, after calculating the red channel with HueToChannel, the standard conversion computes the green and blue channels next. The next logical line is the calculation of the green channel using the same helper function with the original hue value.\n\nfloat g = HueToChannel(p, q, hue);", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 2.828, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 4640, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "float g = HueToChannel(p, q, hue);", "score": 0.96, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "#!/usr/bin/env python\n\n#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++#\n# Thanks for opting for GUI version of AirCrack set of tools. This project is in early stage and require your support. #\n# Project is based on Aircrack-ng set of tools and is specially designed to run on KALI LINUX. #\n# #\n# Designed by : Hitesh Choudhary #\n# Home page : www.HiteshChoudhary.com #\n# Email : hitesh@hiteshchoudhary.com #\n# Based on : www.Aircrack-ng.org #\n#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++#\n\n\n\n\nfrom Canvas import Line\nfrom Tkinter import *\nfrom Tkinter import Frame, PhotoImage, Text, Label, Button\nfrom distutils.cmd import Command\nimport subprocess\nimport commands\nfrom textwrap import fill\nfrom tkFont import Font\nimport tkFont\nimport tkMessageBox\nfrom ttk import Notebook\nimport pcapy\nimport sys\nimport tkFileDialog\n\nclass Feedback:\n \n def __init__(self, master):\n \n\tself.fname=\"\" \n #global variables\n self.t1=StringVar()\n self.t2=StringVar()\n self.t3=StringVar()\n self.t4=StringVar()\n self.t5=StringVar()\n self.t6=StringVar()\n self.t7=StringVar()\n self.t8=StringVar()\n self.t9=StringVar()\n self.t10=StringVar()\n self.t11=StringVar()\n self.t12=StringVar()\n self.t13=StringVar()\n self.t14=StringVar()\n self.t15=StringVar()\n self.t16=StringVar()\n self.t17=StringVar()\n self.t18=StringVar()\n self.t19=StringVar()\n self.t20=StringVar()\n self.t21=StringVar()\n self.t22=StringVar()\n self.t23=StringVar()\n self.t24=StringVar()\n self.t25=StringVar()\n self.t26=StringVar()\n self.t27=StringVar()\n \n self.var1=StringVar()\n self.var2=StringVar()\n self.var3=StringVar()\n self.var4=StringVar()\n self.var5=StringVar()\n self.var6=StringVar()\n self.var7=StringVar()\n self.var8=StringVar()\n self.var9=StringVar()\n self.var10=StringVar()\n self.var11=StringVar()\n self.var12=StringVar()\n self.var13=StringVar()\n self.var14=StringVar()\n self.var15=StringVar()\n self.var16=StringVar()\n self.var17=StringVar()\n self.var18=StringVar()\n self.var19=StringVar()\n self.var20=StringVar()\n self.var21=StringVar()\n self.var22=StringVar()\n self.var23=StringVar()\n self.var24=StringVar()\n self.var25=StringVar()\n self.var26=StringVar()\n self.var27=StringVar()\n #end\n \n mymaster = Frame(master, name='mymaster') # create Frame in \"root\"\n mymaster.pack(fill=BOTH)\n #min and max size of window \n #master.minsize(width=900, height=900)\n #master.maxsize(width=650, height=500)\n #end\n \n #title of window\n master.title(\"Aireplay-ng\")\n #end\n \n #for the style of fonts\n self.customFont = tkFont.Font(family=\"Helvetica\", size=12)\n self.myfont = tkFont.Font(family=\"Helvetica\", size=10)\n self.myfont2 = tkFont.Font(family=\"Helvetica\", size=8)\n self.headerfont=tkFont.Font(family=\"Helvetica\", size=15,underline = True)\n self.myfontnew=tkFont.Font(family=\"Helvetica\", size=11,underline = True)\n #end\n \n \n \n nb = Notebook(mymaster, name='nb') # create Notebook in \"master\"\n nb.pack(fill=BOTH, padx=2, pady=3) # fill \"master\" but pad sides\n #content frame\n self.frame_content = Frame(nb,name=\"frame_content\", bg=\"white\")\n self.frame_content.pack(fill=BOTH, side=TOP, expand=True)\n nb.add(self.frame_content, text=\"Filter-1\") # add tab to Notebook\n \n # repeat for each tab\n self.frame_content2 = Frame(nb, name='frame_content2', bg=\"white\")\n nb.add(self.frame_content2, text=\"Filter-2\")\n self.frame_content3 = Frame(nb, name='frame_content3', bg=\"white\")\n nb.add(self.frame_content3, text=\"Filter-3\")\n \n self.frame_content7 = Frame(nb, name='frame_content7', bg=\"white\")\n nb.add(self.frame_content7, text=\"Detect Devices\")\n self.frame_content5 = Frame(nb, name='frame_content5', bg=\"white\")\n nb.add(self.frame_content5, text=\"output\")\n \n #End\n \n\t#frame content 7\n\tLabel(self.frame_content7, text = 'Aireplay-ng',font=self.headerfont, bg=\"white\", padx=10, pady=10).grid(row = 0, column = 0)\n btndetect=Button(self.frame_content7, text = 'Detect', command =self.canvas_detect, height=2, width=15, font=self.customFont).grid(row = 1, column = 0, padx = 5, pady = 5)\n\t\t\n\tbtndbrowse=Button(self.frame_content7, text = 'Attach File', command =self.browse_file, height=2, width=15, font=self.customFont).grid(row = 3, column = 0, padx = 5, pady = 5)\t\n\tself.lilnew1=Listbox(self.frame_content7,bg=\"black\", fg=\"white\", font=self.myfont, selectmode=SINGLE, width=30, height=15)\n self.lilnew1.grid(row = 1, column = 1, rowspan=3)\n\t#End\n\t\n Label(self.frame_content, text = 'Aireplay-ng',font=self.headerfont, bg=\"white\", padx=10, pady=10).grid(row = 0, column = 0)\n Label(self.frame_content, text = 'Filter Options :',font=self.myfontnew, bg=\"white\").grid(row = 1, column = 1)\n \n Label(self.frame_content5, text = 'Edit Command From Here',font=self.myfontnew, bg=\"white\", justify=LEFT).grid(row = 0, column = 0)\n TextCommandBox=Text(self.frame_content5, height=5, width=30)\n TextCommandBox.grid(row=1, column=0, padx=5, pady=5)\n self.output=Text(self.frame_content5,bg=\"black\", fg=\"white\", font=self.myfont, height=20, width=42)\n self.output.grid(row = 0, column = 1, padx=50, pady=5, rowspan=3)\n btnsubmit=Button(self.frame_content5, width=15, height=2, text=\"Get Result\", command=self.mycallback)\n btnsubmit.grid(row=2, column=0)\n btnclear=Button(self.frame_content5, width=15, height=2, text=\"Clear Output\", command=self.clearoutput)\n btnclear.grid(row=3, column=0)\n #end\n self.C1 = Checkbutton(self.frame_content, text = \"-b\", \\\n onvalue = \"-b\", offvalue = \"\", height=1, \\\n width = 7, bg=\"white\", font=self.customFont,variable=self.var1)\n self.C1.grid(row = 2, column = 0, padx = 5, pady = 5)\n self.t1=Text(self.frame_content,height=1,width = 20)\n self.t1.grid(row = 2, column = 1, padx = 5, pady = 5)\n l1=Label(self.frame_content, text = ': MAC address, Access Point',font=self.myfont, bg=\"white\", justify=LEFT).grid(row = 2, column = 2, padx = 5, pady = 5)\n \n self.C2 = Checkbutton(self.frame_content, text = \"-d\", \\\n onvalue = \"-d\", offvalue = \"\", height=1, \\\n width = 7, bg=\"white\", font=self.customFont,variable=self.var2)\n self.C2.grid(row = 3, column = 0, padx = 5, pady = 5)\n self.t2=Text(self.frame_content,height=1,width = 20)\n self.t2.grid(row = 3, column = 1, padx = 5, pady = 5)\n l2=Label(self.frame_content, text = ': MAC address, Destination',font=self.myfont, bg=\"white\", justify=LEFT).grid(row = 3, column = 2, padx = 5, pady = 5)\n \n self.C3 = Checkbutton(self.frame_content, text = \"-s\", \\\n onvalue = \"-s\", offvalue = \"\", height=1, \\\n width = 7, bg=\"white\", font=self.customFont,variable=self.var3)\n self.C3.grid(row = 4, column = 0, padx = 5, pady = 5)\n self.t3=Text(self.frame_content,height=1,width = 20)\n self.t3.grid(row = 4, column = 1, padx = 5, pady = 5)\n l3=Label(self.frame_content, text = ': MAC address, Source',font=self.myfont, bg=\"white\", justify=LEFT).grid(row = 4, column = 2, padx = 5, pady = 5)\n \n self.C4 = Checkbutton(self.frame_content, text = \"-m\", \\\n onvalue = \"-m\", offvalue = \"\", height=1, \\", "answers": [" width = 7, bg=\"white\", font=self.customFont,variable=self.var4)"], "length": 670, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "2ce6d100-2ef7-471d-b007-1611816d0a85", "reasoning": "The code defines a series of Checkbutton widgets with similar multi-line argument formatting. Each Checkbutton call ends with a backslash to continue the argument list on the next line, then includes width, background, font, and variable parameters before closing the parentheses. For C4, after the onvalue line, the next line should provide these remaining arguments and close the call, matching the pattern of C1‑C3.", "reasoning_model_answer": "width = 7, bg=\"white\", font=self.customFont,variable=self.var4)", "assistant_with_reasoning": "\nThe code defines a series of Checkbutton widgets with similar multi-line argument formatting. Each Checkbutton call ends with a backslash to continue the argument list on the next line, then includes width, background, font, and variable parameters before closing the parentheses. For C4, after the onvalue line, the next line should provide these remaining arguments and close the call, matching the pattern of C1‑C3.\n\nwidth = 7, bg=\"white\", font=self.customFont,variable=self.var4)", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 5.424, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 2, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 8713, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "width = 7, bg=\"white\", font=self.customFont,variable=self.var4)", "score": 0.88, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "# -*- coding: utf-8 -*-\n# Copyright 2020 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\nfrom collections import OrderedDict\nfrom distutils import util\nimport os\nimport re\nfrom typing import Dict, Optional, Sequence, Tuple, Type, Union\n\nfrom google.api_core import client_options as client_options_lib # type: ignore\nfrom google.api_core import exceptions as core_exceptions # type: ignore\nfrom google.api_core import gapic_v1 # type: ignore\nfrom google.api_core import retry as retries # type: ignore\nfrom google.auth import credentials as ga_credentials # type: ignore\nfrom google.auth.transport import mtls # type: ignore\nfrom google.auth.transport.grpc import SslCredentials # type: ignore\nfrom google.auth.exceptions import MutualTLSChannelError # type: ignore\nfrom google.oauth2 import service_account # type: ignore\n\nfrom google.ads.googleads.v8.resources.types import recommendation\nfrom google.ads.googleads.v8.services.types import recommendation_service\nfrom google.rpc import status_pb2 # type: ignore\nfrom .transports.base import RecommendationServiceTransport, DEFAULT_CLIENT_INFO\nfrom .transports.grpc import RecommendationServiceGrpcTransport\n\n\nclass RecommendationServiceClientMeta(type):\n \"\"\"Metaclass for the RecommendationService client.\n\n This provides class-level methods for building and retrieving\n support objects (e.g. transport) without polluting the client instance\n objects.\n \"\"\"\n\n _transport_registry = (\n OrderedDict()\n ) # type: Dict[str, Type[RecommendationServiceTransport]]\n _transport_registry[\"grpc\"] = RecommendationServiceGrpcTransport\n\n def get_transport_class(\n cls, label: str = None,\n ) -> Type[RecommendationServiceTransport]:\n \"\"\"Return an appropriate transport class.\n\n Args:\n label: The name of the desired transport. If none is\n provided, then the first transport in the registry is used.\n\n Returns:\n The transport class to use.\n \"\"\"\n # If a specific transport is requested, return that one.\n if label:\n return cls._transport_registry[label]\n\n # No transport is requested; return the default (that is, the first one\n # in the dictionary).\n return next(iter(cls._transport_registry.values()))\n\n\nclass RecommendationServiceClient(metaclass=RecommendationServiceClientMeta):\n \"\"\"Service to manage recommendations.\"\"\"\n\n @staticmethod\n def _get_default_mtls_endpoint(api_endpoint):\n \"\"\"Convert api endpoint to mTLS endpoint.\n Convert \"*.sandbox.googleapis.com\" and \"*.googleapis.com\" to\n \"*.mtls.sandbox.googleapis.com\" and \"*.mtls.googleapis.com\" respectively.\n Args:\n api_endpoint (Optional[str]): the api endpoint to convert.\n Returns:\n str: converted mTLS api endpoint.\n \"\"\"\n if not api_endpoint:\n return api_endpoint\n\n mtls_endpoint_re = re.compile(\n r\"(?P[^.]+)(?P\\.mtls)?(?P\\.sandbox)?(?P\\.googleapis\\.com)?\"\n )\n\n m = mtls_endpoint_re.match(api_endpoint)\n name, mtls, sandbox, googledomain = m.groups()\n if mtls or not googledomain:\n return api_endpoint\n\n if sandbox:\n return api_endpoint.replace(\n \"sandbox.googleapis.com\", \"mtls.sandbox.googleapis.com\"\n )\n\n return api_endpoint.replace(\".googleapis.com\", \".mtls.googleapis.com\")\n\n DEFAULT_ENDPOINT = \"googleads.googleapis.com\"\n DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore\n DEFAULT_ENDPOINT\n )\n\n @classmethod\n def from_service_account_info(cls, info: dict, *args, **kwargs):\n \"\"\"Creates an instance of this client using the provided credentials info.\n\n Args:\n info (dict): The service account private key info.\n args: Additional arguments to pass to the constructor.\n kwargs: Additional arguments to pass to the constructor.\n\n Returns:\n RecommendationServiceClient: The constructed client.\n \"\"\"\n credentials = service_account.Credentials.from_service_account_info(\n info\n )\n kwargs[\"credentials\"] = credentials\n return cls(*args, **kwargs)\n\n @classmethod\n def from_service_account_file(cls, filename: str, *args, **kwargs):\n \"\"\"Creates an instance of this client using the provided credentials\n file.\n\n Args:\n filename (str): The path to the service account private key json\n file.\n args: Additional arguments to pass to the constructor.\n kwargs: Additional arguments to pass to the constructor.\n\n Returns:\n RecommendationServiceClient: The constructed client.\n \"\"\"\n credentials = service_account.Credentials.from_service_account_file(\n filename\n )\n kwargs[\"credentials\"] = credentials\n return cls(*args, **kwargs)\n\n from_service_account_json = from_service_account_file\n\n @property\n def transport(self) -> RecommendationServiceTransport:\n \"\"\"Return the transport used by the client instance.\n\n Returns:\n RecommendationServiceTransport: The transport used by the client instance.\n \"\"\"\n return self._transport\n\n @staticmethod\n def ad_path(customer_id: str, ad_id: str,) -> str:\n \"\"\"Return a fully-qualified ad string.\"\"\"\n return \"customers/{customer_id}/ads/{ad_id}\".format(\n customer_id=customer_id, ad_id=ad_id,\n )\n\n @staticmethod\n def parse_ad_path(path: str) -> Dict[str, str]:\n \"\"\"Parse a ad path into its component segments.\"\"\"\n m = re.match(\n r\"^customers/(?P.+?)/ads/(?P.+?)$\", path\n )\n return m.groupdict() if m else {}\n\n @staticmethod\n def ad_group_path(customer_id: str, ad_group_id: str,) -> str:\n \"\"\"Return a fully-qualified ad_group string.\"\"\"", "answers": [" return \"customers/{customer_id}/adGroups/{ad_group_id}\".format("], "length": 632, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "5af4ea44-bbbc-4080-9009-79bf2d74a6dc", "reasoning": "The code defines a static method ad_group_path with a docstring. Following the pattern of ad_path, the next line should be the return statement that formats the resource path string for an ad group, using the provided customer_id and ad_group_id.", "reasoning_model_answer": "return \"customers/{customer_id}/adGroups/{ad_group_id}\".format(\n customer_id=customer_id, ad_group_id=ad_group_id,\n )", "assistant_with_reasoning": "\nThe code defines a static method ad_group_path with a docstring. Following the pattern of ad_path, the next line should be the return statement that formats the resource path string for an ad group, using the provided customer_id and ad_group_id.\n\nreturn \"customers/{customer_id}/adGroups/{ad_group_id}\".format(\n customer_id=customer_id, ad_group_id=ad_group_id,\n )", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.339, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 6630, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "return \"customers/{customer_id}/adGroups/{ad_group_id}\".format(\n customer_id=customer_id, ad_group_id=ad_group_id,\n )", "score": 0.94, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n// Generated by the protocol buffer compiler. DO NOT EDIT!\n// source: google/cloud/automl/v1beta1/service.proto\n\npackage com.google.cloud.automl.v1beta1;\n\n/**\n *\n *\n *
    \n * Request message for [AutoMl.DeleteModel][google.cloud.automl.v1beta1.AutoMl.DeleteModel].\n * 
    \n *\n * Protobuf type {@code google.cloud.automl.v1beta1.DeleteModelRequest}\n */\npublic final class DeleteModelRequest extends com.google.protobuf.GeneratedMessageV3\n implements\n // @@protoc_insertion_point(message_implements:google.cloud.automl.v1beta1.DeleteModelRequest)\n DeleteModelRequestOrBuilder {\n private static final long serialVersionUID = 0L;\n // Use DeleteModelRequest.newBuilder() to construct.\n private DeleteModelRequest(com.google.protobuf.GeneratedMessageV3.Builder builder) {\n super(builder);\n }\n\n private DeleteModelRequest() {\n name_ = \"\";\n }\n\n @java.lang.Override\n @SuppressWarnings({\"unused\"})\n protected java.lang.Object newInstance(UnusedPrivateParameter unused) {\n return new DeleteModelRequest();\n }\n\n @java.lang.Override\n public final com.google.protobuf.UnknownFieldSet getUnknownFields() {\n return this.unknownFields;\n }\n\n private DeleteModelRequest(\n com.google.protobuf.CodedInputStream input,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws com.google.protobuf.InvalidProtocolBufferException {\n this();\n if (extensionRegistry == null) {\n throw new java.lang.NullPointerException();\n }\n com.google.protobuf.UnknownFieldSet.Builder unknownFields =\n com.google.protobuf.UnknownFieldSet.newBuilder();\n try {\n boolean done = false;\n while (!done) {\n int tag = input.readTag();\n switch (tag) {\n case 0:\n done = true;\n break;\n case 10:\n {\n java.lang.String s = input.readStringRequireUtf8();\n\n name_ = s;\n break;\n }\n default:\n {\n if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) {\n done = true;\n }\n break;\n }\n }\n }\n } catch (com.google.protobuf.InvalidProtocolBufferException e) {\n throw e.setUnfinishedMessage(this);\n } catch (java.io.IOException e) {\n throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this);\n } finally {\n this.unknownFields = unknownFields.build();\n makeExtensionsImmutable();\n }\n }\n\n public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {\n return com.google.cloud.automl.v1beta1.AutoMlProto\n .internal_static_google_cloud_automl_v1beta1_DeleteModelRequest_descriptor;\n }\n\n @java.lang.Override\n protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable\n internalGetFieldAccessorTable() {\n return com.google.cloud.automl.v1beta1.AutoMlProto\n .internal_static_google_cloud_automl_v1beta1_DeleteModelRequest_fieldAccessorTable\n .ensureFieldAccessorsInitialized(\n com.google.cloud.automl.v1beta1.DeleteModelRequest.class,\n com.google.cloud.automl.v1beta1.DeleteModelRequest.Builder.class);\n }\n\n public static final int NAME_FIELD_NUMBER = 1;\n private volatile java.lang.Object name_;\n /**\n *\n *\n *
    \n   * Required. Resource name of the model being deleted.\n   * 
    \n *\n * \n * string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }\n * \n *\n * @return The name.\n */\n @java.lang.Override\n public java.lang.String getName() {\n java.lang.Object ref = name_;\n if (ref instanceof java.lang.String) {\n return (java.lang.String) ref;\n } else {\n com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;\n java.lang.String s = bs.toStringUtf8();\n name_ = s;\n return s;\n }\n }\n /**\n *\n *\n *
    \n   * Required. Resource name of the model being deleted.\n   * 
    \n *\n * \n * string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }\n * \n *\n * @return The bytes for name.\n */\n @java.lang.Override\n public com.google.protobuf.ByteString getNameBytes() {\n java.lang.Object ref = name_;\n if (ref instanceof java.lang.String) {\n com.google.protobuf.ByteString b =\n com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);\n name_ = b;\n return b;\n } else {\n return (com.google.protobuf.ByteString) ref;\n }\n }\n\n private byte memoizedIsInitialized = -1;\n\n @java.lang.Override\n public final boolean isInitialized() {\n byte isInitialized = memoizedIsInitialized;\n if (isInitialized == 1) return true;\n if (isInitialized == 0) return false;\n\n memoizedIsInitialized = 1;\n return true;\n }\n\n @java.lang.Override\n public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {\n if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(name_)) {\n com.google.protobuf.GeneratedMessageV3.writeString(output, 1, name_);\n }\n unknownFields.writeTo(output);\n }\n\n @java.lang.Override\n public int getSerializedSize() {\n int size = memoizedSize;\n if (size != -1) return size;\n\n size = 0;\n if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(name_)) {\n size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, name_);\n }\n size += unknownFields.getSerializedSize();\n memoizedSize = size;\n return size;\n }\n\n @java.lang.Override\n public boolean equals(final java.lang.Object obj) {\n if (obj == this) {\n return true;\n }\n if (!(obj instanceof com.google.cloud.automl.v1beta1.DeleteModelRequest)) {\n return super.equals(obj);\n }\n com.google.cloud.automl.v1beta1.DeleteModelRequest other =\n (com.google.cloud.automl.v1beta1.DeleteModelRequest) obj;\n\n if (!getName().equals(other.getName())) return false;\n if (!unknownFields.equals(other.unknownFields)) return false;\n return true;\n }\n\n @java.lang.Override\n public int hashCode() {\n if (memoizedHashCode != 0) {\n return memoizedHashCode;\n }", "answers": [" int hash = 41;"], "length": 609, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "796c8496-610f-4955-ab58-f95a89fd2407", "reasoning": "The code is inside the hashCode() method of a protobuf-generated class. After checking memoizedHashCode, the typical generated pattern initializes a hash variable, usually with `int hash = 41;`, then combines field hashes. Therefore the next line should be the hash initialization.", "reasoning_model_answer": "int hash = 41;", "assistant_with_reasoning": "\nThe code is inside the hashCode() method of a protobuf-generated class. After checking memoizedHashCode, the typical generated pattern initializes a hash variable, usually with `int hash = 41;`, then combines field hashes. Therefore the next line should be the hash initialization.\n\nint hash = 41;", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.464, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 6910, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "int hash = 41;", "score": 0.88, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/*\n * This file is part of the Jikes RVM project (http://jikesrvm.org).\n *\n * This file is licensed to You under the Common Public License (CPL);\n * You may not use this file except in compliance with the License. You\n * may obtain a copy of the License at\n *\n * http://www.opensource.org/licenses/cpl1.0.php\n *\n * See the COPYRIGHT.txt file distributed with this work for information\n * regarding copyright ownership.\n */\npackage org.jikesrvm.adaptive.database.methodsamples;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport org.jikesrvm.VM;\nimport org.jikesrvm.adaptive.controller.Controller;\nimport org.jikesrvm.adaptive.controller.HotMethodEvent;\nimport org.jikesrvm.adaptive.controller.HotMethodRecompilationEvent;\nimport org.jikesrvm.adaptive.measurements.Reportable;\nimport org.jikesrvm.adaptive.util.AOSLogging;\nimport org.jikesrvm.classloader.RVMMethod;\nimport org.jikesrvm.compilers.common.CompiledMethod;\nimport org.jikesrvm.compilers.common.CompiledMethods;\nimport org.jikesrvm.compilers.opt.runtimesupport.OptCompiledMethod;\n\n/**\n * A container for recording how often a method is executed.\n */\npublic final class MethodCountData implements Reportable {\n\n private static final boolean DEBUG = false;\n\n /**\n * Sum of values in count array.\n */\n private double totalCountsTaken;\n\n /**\n * Count array: counts how many times a method is executed.\n * Constraint: counts[0] is not used.\n */\n private double[] counts;\n /**\n * Maps count array index to compiled method id.\n * Constraint: cmids[0] is not used.\n */\n private int[] cmids;\n /**\n * Maps compiled method id to count array index.\n * '0' implies that there is no entry in the count array for this cmid\n */\n private int[] map;\n /**\n * Next available count array entry.\n */\n private int nextIndex;\n\n /**\n * Constructor\n */\n public MethodCountData() {\n initialize();\n }\n\n /**\n * Reset fields.\n */\n private void initialize() {\n int numCompiledMethods = CompiledMethods.numCompiledMethods();\n map = new int[numCompiledMethods + (numCompiledMethods >>> 2)];\n counts = new double[256];\n cmids = new int[256];\n nextIndex = 1;\n totalCountsTaken = 0;\n }\n\n /**\n * Drain a buffer of compiled method id's and update the count array.\n *\n * @param countBuffer a buffer of compiled method id's\n * @param numCounts the number of valid entries in the buffer\n */\n public synchronized void update(int[] countBuffer, int numCounts) {\n for (int i = 0; i < numCounts; i++) {\n int cmid = countBuffer[i];\n int index = findOrCreateHeapIdx(cmid);\n counts[index]++; // Record count\n heapifyUp(index); // Fix up the heap\n }\n totalCountsTaken += numCounts;\n if (DEBUG) validityCheck();\n }\n\n /**\n * Increment the count for a compiled method id.\n *\n * @param cmid compiled method id\n * @param numCounts number of counts\n */\n public synchronized void update(int cmid, double numCounts) {\n int index = findOrCreateHeapIdx(cmid);\n counts[index] += numCounts; // Record counts\n heapifyUp(index); // Fix up the heap\n totalCountsTaken += numCounts;\n if (DEBUG) validityCheck();\n }\n\n /**\n * Print the counted (nonzero) methods.\n * To get a sorted list, pipe the output through sort -n -r.\n */\n public synchronized void report() {\n VM.sysWrite(\"Method counts: A total of \" + totalCountsTaken + \" samples\\n\");\n for (int i = 1; i < nextIndex; i++) {\n double percent = 100 * countsToHotness(counts[i]);\n CompiledMethod cm = CompiledMethods.getCompiledMethod(cmids[i]);\n VM.sysWrite(counts[i] + \" (\" + percent + \"%) \");\n if (cm == null) {\n VM.sysWriteln(\"OBSOLETE\"); // Compiled Method Obsolete\n } else {\n if (cm.getCompilerType() == CompiledMethod.TRAP) {\n VM.sysWriteln(\"\");\n } else {\n RVMMethod m = cm.getMethod();\n VM.sysWrite(m);\n if (m.getDeclaringClass().isInBootImage()) {\n VM.sysWrite(\"\\tBOOT\");\n }\n }\n VM.sysWriteln();\n }\n }\n }\n\n /**\n * @return the total number of samples taken\n */\n public double getTotalNumberOfSamples() {\n return totalCountsTaken;\n }\n\n /**\n * Reset (clear) the method counts\n */\n public synchronized void reset() {\n initialize();\n }\n\n /**\n * Get the current count for a given compiled method id.\n *\n * @param cmid compiled method id\n */\n public synchronized double getData(int cmid) {\n int index = findHeapIdx(cmid);\n if (index > 0) {", "answers": [" return counts[index];"], "length": 573, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "6764d35f-f059-447e-b0cf-ba97e45dda41", "reasoning": "The getData method looks up the heap index for a compiled method id. If the index is positive, the method should return the stored count for that index. The next line inside the if‑block therefore returns the count from the counts array at that index.", "reasoning_model_answer": "return counts[index];", "assistant_with_reasoning": "\nThe getData method looks up the heap index for a compiled method id. If the index is positive, the method should return the stored count for that index. The next line inside the if‑block therefore returns the count from the counts array at that index.\n\nreturn counts[index];", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 1.613, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 4689, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "return counts[index];", "score": 0.88, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/**\n * \n Apache License\n Version 2.0, January 2004\n http://www.apache.org/licenses/\n\n TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n 1. Definitions.\n\n \"License\" shall mean the terms and conditions for use, reproduction,\n and distribution as defined by Sections 1 through 9 of this document.\n\n \"Licensor\" shall mean the copyright owner or entity authorized by\n the copyright owner that is granting the License.\n\n \"Legal Entity\" shall mean the union of the acting entity and all\n other entities that control, are controlled by, or are under common\n control with that entity. For the purposes of this definition,\n \"control\" means (i) the power, direct or indirect, to cause the\n direction or management of such entity, whether by contract or\n otherwise, or (ii) ownership of fifty percent (50%) or more of the\n outstanding shares, or (iii) beneficial ownership of such entity.\n\n \"You\" (or \"Your\") shall mean an individual or Legal Entity\n exercising permissions granted by this License.\n\n \"Source\" form shall mean the preferred form for making modifications,\n including but not limited to software source code, documentation\n source, and configuration files.\n\n \"Object\" form shall mean any form resulting from mechanical\n transformation or translation of a Source form, including but\n not limited to compiled object code, generated documentation,\n and conversions to other media types.\n\n \"Work\" shall mean the work of authorship, whether in Source or\n Object form, made available under the License, as indicated by a\n copyright notice that is included in or attached to the work\n (an example is provided in the Appendix below).\n\n \"Derivative Works\" shall mean any work, whether in Source or Object\n form, that is based on (or derived from) the Work and for which the\n editorial revisions, annotations, elaborations, or other modifications\n represent, as a whole, an original work of authorship. For the purposes\n of this License, Derivative Works shall not include works that remain\n separable from, or merely link (or bind by name) to the interfaces of,\n the Work and Derivative Works thereof.\n\n \"Contribution\" shall mean any work of authorship, including\n the original version of the Work and any modifications or additions\n to that Work or Derivative Works thereof, that is intentionally\n submitted to Licensor for inclusion in the Work by the copyright owner\n or by an individual or Legal Entity authorized to submit on behalf of\n the copyright owner. For the purposes of this definition, \"submitted\"\n means any form of electronic, verbal, or written communication sent\n to the Licensor or its representatives, including but not limited to\n communication on electronic mailing lists, source code control systems,\n and issue tracking systems that are managed by, or on behalf of, the\n Licensor for the purpose of discussing and improving the Work, but\n excluding communication that is conspicuously marked or otherwise\n designated in writing by the copyright owner as \"Not a Contribution.\"\n\n \"Contributor\" shall mean Licensor and any individual or Legal Entity\n on behalf of whom a Contribution has been received by Licensor and\n subsequently incorporated within the Work.\n\n 2. Grant of Copyright License. Subject to the terms and conditions of\n this License, each Contributor hereby grants to You a perpetual,\n worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n copyright license to reproduce, prepare Derivative Works of,\n publicly display, publicly perform, sublicense, and distribute the\n Work and such Derivative Works in Source or Object form.\n\n 3. Grant of Patent License. Subject to the terms and conditions of\n this License, each Contributor hereby grants to You a perpetual,\n worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n (except as stated in this section) patent license to make, have made,\n use, offer to sell, sell, import, and otherwise transfer the Work,\n where such license applies only to those patent claims licensable", "answers": [" by such Contributor that are necessarily infringed by their"], "length": 602, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "9e886b72-d287-46fc-a5d8-531e66428561", "reasoning": "The snippet is a comment containing the Apache License 2.0 text. It ends mid‑sentence in section 3: \"where such license applies only to those patent claims licensable\". The next line in the official license continues the sentence with \"by such Contributor that are necessarily infringed\". Keeping the comment formatting and indentation, the next line should be:\n by such Contributor that are necessarily infringed", "reasoning_model_answer": "by such Contributor that are necessarily infringed", "assistant_with_reasoning": "\nThe snippet is a comment containing the Apache License 2.0 text. It ends mid‑sentence in section 3: \"where such license applies only to those patent claims licensable\". The next line in the official license continues the sentence with \"by such Contributor that are necessarily infringed\". Keeping the comment formatting and indentation, the next line should be:\n by such Contributor that are necessarily infringed\n\nby such Contributor that are necessarily infringed", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 5.633, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 4450, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "by such Contributor that are necessarily infringed", "score": 0.87, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "// Copyright (c) Microsoft. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\n// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+\n//\n// IntRangePartitionerTests.cs - Tests for range partitioner for integer range.\n//\n// PLEASE NOTE !! - For tests that need to iterate the elements inside the partitions more \n// than once, we need to call GetPartitions for the second time. Iterating a second times\n// over the first enumerable / IList will yield no elements\n//\n// PLEASE NOTE!! - we use lazy evaluation wherever possible to allow for more than Int32.MaxValue\n// elements. ToArray / toList will result in an OOM\n//\n// Taken from:\n// \\qa\\clr\\testsrc\\pfx\\Functional\\Common\\Partitioner\\YetiTests\\RangePartitioner\\IntRangePartitionerTests.cs\n// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\n\nusing System;\nusing System.Collections;\nusing System.Collections.Concurrent;\nusing System.Collections.Generic;\nusing Xunit;\n\nnamespace System.Collections.Concurrent.Tests\n{\n public class IntRangePartitionerTests\n {\n /// \n /// Ensure that the partitioner returned has properties set correctly\n /// \n [Fact]\n public static void CheckKeyProperties()\n {\n var partitioner = Partitioner.Create(0, 1000);\n Assert.True(partitioner.KeysOrderedInEachPartition, \"Expected KeysOrderedInEachPartition to be set to true\");\n Assert.False(partitioner.KeysOrderedAcrossPartitions, \"KeysOrderedAcrossPartitions to be set to false\");\n Assert.True(partitioner.KeysNormalized, \"Expected KeysNormalized to be set to true\");\n\n partitioner = Partitioner.Create(0, 1000, 90);\n Assert.True(partitioner.KeysOrderedInEachPartition, \"Expected KeysOrderedInEachPartition to be set to true\");\n Assert.False(partitioner.KeysOrderedAcrossPartitions, \"KeysOrderedAcrossPartitions to be set to false\");\n Assert.True(partitioner.KeysNormalized, \"Expected KeysNormalized to be set to true\");\n }\n\n /// \n /// GetPartitions returns an IList>\n /// We unroll the tuples and flatten them to a single sequence\n /// The single sequence is compared to the original range for verification\n /// \n [Fact]\n public static void CheckGetPartitions()\n {\n CheckGetPartitions(0, 1, 1);\n CheckGetPartitions(1, 1999, 3);\n CheckGetPartitions(2147473647, 9999, 4);\n CheckGetPartitions(-1999, 5000, 63);\n CheckGetPartitions(-2147483648, 5000, 63);\n }\n\n public static void CheckGetPartitions(int from, int count, int dop)\n {\n int to = from + count;\n var partitioner = Partitioner.Create(from, to);\n\n //var elements = dopPartitions.SelectMany(enumerator => enumerator.UnRoll());\n IList elements = new List();\n foreach (var partition in partitioner.GetPartitions(dop))\n {\n foreach (var item in partition.UnRoll())\n elements.Add(item);\n }\n\n Assert.True(elements.CompareSequences(RangePartitionerHelpers.IntEnumerable(from, to)), \"GetPartitions element mismatch\");\n }\n\n /// \n /// CheckGetDynamicPartitions returns an IEnumerable>\n /// We unroll the tuples and flatten them to a single sequence\n /// The single sequence is compared to the original range for verification\n /// \n /// \n /// \n [Fact]\n public static void CheckGetDynamicPartitions()\n {\n CheckGetDynamicPartitions(0, 1);\n CheckGetDynamicPartitions(1, 1999);\n CheckGetDynamicPartitions(2147473647, 9999);\n CheckGetDynamicPartitions(-1999, 5000);\n CheckGetDynamicPartitions(-2147483648, 5000);\n }\n\n public static void CheckGetDynamicPartitions(int from, int count)\n {\n int to = from + count;\n var partitioner = Partitioner.Create(from, to);\n\n //var elements = partitioner.GetDynamicPartitions().SelectMany(tuple => tuple.UnRoll());\n IList elements = new List();\n foreach (var partition in partitioner.GetDynamicPartitions())\n {\n foreach (var item in partition.UnRoll())\n elements.Add(item);\n }\n\n Assert.True(elements.CompareSequences(RangePartitionerHelpers.IntEnumerable(from, to)), \"GetDynamicPartitions Element mismatch\");\n }\n\n /// \n /// GetOrderablePartitions returns an IList>>\n /// We unroll the tuples and flatten them to a single sequence\n /// The single sequence is compared to the original range for verification\n /// Also the indices are extracted to ensure that they are ordered & normalized\n /// \n [Fact]\n public static void CheckGetOrderablePartitions()\n {\n CheckGetOrderablePartitions(0, 1, 1);\n CheckGetOrderablePartitions(1, 1999, 3);\n CheckGetOrderablePartitions(2147473647, 9999, 4);\n CheckGetOrderablePartitions(-1999, 5000, 63);\n CheckGetOrderablePartitions(-2147483648, 5000, 63);\n }\n\n public static void CheckGetOrderablePartitions(int from, int count, int dop)\n {\n int to = from + count;\n var partitioner = Partitioner.Create(from, to);\n\n //var elements = partitioner.GetOrderablePartitions(dop).SelectMany(enumerator => enumerator.UnRoll());\n IList elements = new List();\n foreach (var partition in partitioner.GetPartitions(dop))\n {\n foreach (var item in partition.UnRoll())\n elements.Add(item);\n }\n\n Assert.True(elements.CompareSequences(RangePartitionerHelpers.IntEnumerable(from, to)), \"GetOrderablePartitions Element mismatch\");\n\n //var keys = partitioner.GetOrderablePartitions(dop).SelectMany(enumerator => enumerator.UnRollIndices()).ToArray();\n IList keys = new List();\n foreach (var partition in partitioner.GetOrderablePartitions(dop))\n {\n foreach (var item in partition.UnRollIndices())\n keys.Add(item);\n }\n Assert.True(keys.CompareSequences(RangePartitionerHelpers.LongEnumerable(keys[0], keys.Count)), \"GetOrderablePartitions key mismatch\");\n }\n\n /// \n /// GetOrderableDynamicPartitions returns an IEnumerable>\n /// We unroll the tuples and flatten them to a single sequence\n /// The single sequence is compared to the original range for verification\n /// Also the indices are extracted to ensure that they are ordered & normalized\n /// \n [Fact]\n public static void GetOrderableDynamicPartitions()\n {\n GetOrderableDynamicPartitions(0, 1);\n GetOrderableDynamicPartitions(1, 1999);\n GetOrderableDynamicPartitions(2147473647, 9999);\n GetOrderableDynamicPartitions(-1999, 5000);\n GetOrderableDynamicPartitions(-2147483648, 5000);\n }\n", "answers": [" private static void GetOrderableDynamicPartitions(int from, int count)"], "length": 646, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "9d118068-c0cb-4123-8213-edd0d388539f", "reasoning": "The code just finished the test method GetOrderableDynamicPartitions() which calls a helper method with the same name but taking parameters. The next logical line is the definition of that helper method. Following the pattern of other helpers (e.g., CheckGetDynamicPartitions), the next line should be the method signature: public static void GetOrderableDynamicPartitions(int from, int count).", "reasoning_model_answer": "public static void GetOrderableDynamicPartitions(int from, int count)", "assistant_with_reasoning": "\nThe code just finished the test method GetOrderableDynamicPartitions() which calls a helper method with the same name but taking parameters. The next logical line is the definition of that helper method. Following the pattern of other helpers (e.g., CheckGetDynamicPartitions), the next line should be the method signature: public static void GetOrderableDynamicPartitions(int from, int count).\n\npublic static void GetOrderableDynamicPartitions(int from, int count)", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 6.084, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 7732, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "public static void GetOrderableDynamicPartitions(int from, int count)", "score": 0.88, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "package org.formulachess.engine.tests;\n\nimport static org.formulachess.engine.Turn.BLACK_TURN;\nimport static org.formulachess.engine.Turn.WHITE_TURN;\n\nimport java.util.Locale;\nimport java.util.logging.Level;\nimport java.util.logging.Logger;\n\nimport org.formulachess.engine.AbstractChessEngine;\nimport org.formulachess.engine.ChessEngine;\nimport org.formulachess.engine.Converter;\nimport org.formulachess.engine.Piece;\nimport org.formulachess.pgn.engine.PGNMoveContainer;\n\nimport junit.framework.Test;\nimport junit.framework.TestCase;\nimport junit.framework.TestSuite;\n\npublic class TestAllMoves extends TestCase {\n\n\tprivate static final String INITIAL_POSITION = \"rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1\"; //$NON-NLS-1$\n\tprivate static final String WRONG_MOVES = \"Wrong moves\"; //$NON-NLS-1$\n\tprivate static final String WRONG_VALUE = \"Wrong value\"; //$NON-NLS-1$\n\tprivate static Logger myLogger = Logger.getLogger(TestAllMoves.class.getCanonicalName());\n\tprivate static final String WRONG_SIZE = \"wrong size\"; //$NON-NLS-1$\n\tprivate static final boolean TOTAL = true;\n\tprivate static final boolean DEBUG = false;\n\n\tpublic TestAllMoves(String name) {\n\t\tsuper(name);\n\t}\n\n\tpublic static Test suite() {\n\t\treturn new TestSuite(TestAllMoves.class);\n\t}\n\n\tpublic long[] repeatAllMoves(ChessEngine model, int repetitions) {\n\t\tlong[] moves = null;\n\t\tlong time = System.currentTimeMillis();\n\t\tfor (int i = 0; i < repetitions; i++) {\n\t\t\tmoves = model.allMoves();\n\t\t}\n\t\tif (DEBUG) {\n\t\t\tmyLogger.log(Level.SEVERE, () -> \"spent \" + (System.currentTimeMillis() - time) + \"ms\");//$NON-NLS-1$//$NON-NLS-2$\n\t\t}\n\t\treturn moves;\n\t}\n\n\tpublic void display(String testName, ChessEngine model, long[] moves, String expectedMoves) {\n\t\tPGNMoveContainer pgnMoveContainer = new PGNMoveContainer(model, moves, Locale.FRANCE);\n\t\tif (DEBUG) {\n\t\t\tmyLogger.log(Level.INFO, () -> \"================ START \" + testName + \" ====================================\"); //$NON-NLS-1$ //$NON-NLS-2$\n\t\t\tmyLogger.log(Level.INFO, () -> model.toString());\n\t\t\tmyLogger.log(Level.INFO, () -> pgnMoveContainer.toString());\n\t\t}\n\t\tassertEquals(WRONG_MOVES, expectedMoves, pgnMoveContainer.toString());\n\t\tif (DEBUG) {\n\t\t\tmyLogger.log(Level.INFO, () -> \"================ END \" + testName + \" ====================================\"); //$NON-NLS-1$ //$NON-NLS-2$\n\t\t}\n\t}\n\n\tpublic void display(ChessEngine model, long[] moves) {\n\t\tif (DEBUG) {\n\t\t\tPGNMoveContainer pgnMoveContainer = new PGNMoveContainer(model, moves, Locale.FRANCE);\n\t\t\tmyLogger.log(Level.INFO, () -> model.toString());\n\t\t\tmyLogger.log(Level.INFO, () -> pgnMoveContainer.toString(false));\n\t\t}\n\t}\n\n\tprivate void displayTime(long time) {\n\t\tif (DEBUG) {\n\t\t\tmyLogger.log(Level.INFO, () -> \"spent \" + (System.currentTimeMillis() - time) + \"ms\"); //$NON-NLS-1$ //$NON-NLS-2$\n\t\t}\n\t}\n\n\tprivate void playAllMoves(String fenNotation, ChessEngine model, long[] moves) {\n\t\tfor (int i = 0, max = moves.length; i < max; i++) {\n\t\t\tfinal long move = moves[i];\n\t\t\tmodel.playMove(move);\n\t\t\tmodel.allMoves();\n\t\t\tmodel.undoMove(move);\n\t\t\tif (!fenNotation.equals(model.toFENNotation())) {\n\t\t\t\tPGNMoveContainer pgnMoveContainer = new PGNMoveContainer(model, moves, Locale.FRANCE);\n\t\t\t\tassertTrue(\"different fen notation for move[\" + i + \"] = \" + pgnMoveContainer.getMoveNotation(move), //$NON-NLS-1$ //$NON-NLS-2$\n\t\t\t\t\t\tfalse);\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic void test001() {\n\t\tChessEngine model = new ChessEngine(Locale.getDefault());\n\t\tmodel.setBoard(AbstractChessEngine.getEmptyBoard());\n\t\tmodel.setBoard(28, Piece.WHITE_KING);\n\t\tmodel.setTurn(WHITE_TURN);\n\t\tlong[] moves = model.allMoves();\n\t\tassertEquals(WRONG_SIZE, 8, moves.length);\n\t\tStringBuilder builder = new StringBuilder();\n\t\tfor (int i = 0; i < moves.length; i++) {\n\t\t\tbuilder.append(Converter.moveToString(model.getBoard(), moves[i], Locale.FRANCE) + \" \"); //$NON-NLS-1$\n\t\t}\n\t\tassertEquals(WRONG_MOVES, \"Rd6 Re6 Rf6 Rd5 Rf5 Rd4 Re4 Rf4 \", String.valueOf(builder)); //$NON-NLS-1$\n\t}\n\n\tpublic void test002() {\n\t\tChessEngine model = new ChessEngine(Locale.getDefault());\n\t\tmodel.setBoard(AbstractChessEngine.getEmptyBoard());\n\t\tmodel.setBoard(28, Piece.BLACK_KNIGHT);\n\t\tmodel.setBoard(0, Piece.BLACK_KING);\n\t\tmodel.setTurn(BLACK_TURN);\n\t\tmodel.setBlackCanCastleKingSide(false);\n\t\tmodel.setBlackCanCastleQueenSide(false);\n\t\tlong[] moves = model.allMoves();\n\t\tassertEquals(WRONG_SIZE, 11, moves.length);\n\t\tStringBuilder builder = new StringBuilder();\n\t\tfor (int i = 0; i < moves.length; i++) {\n\t\t\tbuilder.append(Converter.moveToString(model.getBoard(), moves[i], Locale.FRANCE) + \" \"); //$NON-NLS-1$\n\t\t}\n\t\tassertEquals(WRONG_MOVES, \"Rb8 Ra7 Rb7 Cf3 Cd3 Cg4 Cc4 Cg6 Cc6 Cf7 Cd7 \", //$NON-NLS-1$\n\t\t\t\tString.valueOf(builder));\n\t}\n\n\tpublic void test003() {\n\t\tChessEngine model = new ChessEngine(Locale.getDefault());\n\t\tmodel.setBoard(AbstractChessEngine.getEmptyBoard());\n\t\tmodel.setBoard(28, Piece.BLACK_KNIGHT);\n\t\tmodel.setBoard(0, Piece.BLACK_KING);\n\t\tmodel.setBoard(24, Piece.WHITE_ROOK);\n\t\tmodel.setTurn(BLACK_TURN);\n\t\tmodel.setBlackCanCastleKingSide(false);\n\t\tmodel.setBlackCanCastleQueenSide(false);\n\t\tlong[] moves = model.allMoves();\n\t\tassertEquals(WRONG_SIZE, 2, moves.length);\n\t\tStringBuilder builder = new StringBuilder();\n\t\tfor (int i = 0; i < moves.length; i++) {\n\t\t\tbuilder.append(Converter.moveToString(model.getBoard(), moves[i], Locale.FRANCE) + \" \"); //$NON-NLS-1$\n\t\t}\n\t\tassertEquals(WRONG_MOVES, \"Rb8 Rb7 \", String.valueOf(builder)); //$NON-NLS-1$\n\t}\n\n\tpublic void test004() {\n\t\tChessEngine model = new ChessEngine(Locale.getDefault());\n\t\tmodel.setBoard(AbstractChessEngine.getEmptyBoard());\n\t\tmodel.setBoard(28, Piece.BLACK_KNIGHT);\n\t\tmodel.setBoard(0, Piece.BLACK_KING);\n\t\tmodel.setBoard(24, Piece.WHITE_ROOK);\n\t\tmodel.setBoard(25, Piece.WHITE_ROOK);\n\t\tmodel.setTurn(BLACK_TURN);\n\t\tmodel.setBlackCanCastleKingSide(false);\n\t\tmodel.setBlackCanCastleQueenSide(false);\n\t\tlong[] moves = model.allMoves();\n\t\tassertEquals(WRONG_SIZE, 0, moves.length);\n\t}\n\n\tpublic void test005() {\n\t\tChessEngine model = new ChessEngine(Locale.getDefault());\n\t\tmodel.setBoard(AbstractChessEngine.getEmptyBoard());\n\t\tmodel.setBoard(60, Piece.WHITE_KING);\n\t\tmodel.setBoard(63, Piece.WHITE_ROOK);\n\t\tmodel.setBoard(56, Piece.WHITE_ROOK);\n\t\tmodel.setWhiteCanCastleKingSide(true);\n\t\tmodel.setWhiteCanCastleQueenSide(true);\n\t\tmodel.setTurn(WHITE_TURN);\n\t\tlong[] moves = model.allMoves();\n\t\tassertEquals(WRONG_SIZE, 26, moves.length);\n\t\tStringBuilder builder = new StringBuilder();\n\t\tfor (int i = 0; i < moves.length; i++) {\n\t\t\tbuilder.append(Converter.moveToString(model.getBoard(), moves[i], Locale.FRANCE) + \" \"); //$NON-NLS-1$\n\t\t}\n\t\tassertEquals(WRONG_MOVES,\n\t\t\t\t\"Ta2 Ta3 Ta4 Ta5 Ta6 Ta7 Ta8 Tb1 Tc1 Td1 Rd2 Re2 Rf2 Rd1 Rf1 Rg1 Rc1 Th2 Th3 Th4 Th5 Th6 Th7 Th8 Tg1 Tf1 \", //$NON-NLS-1$\n\t\t\t\tString.valueOf(builder));\n\t}\n\n\tpublic void test006() {\n\t\tChessEngine model = new ChessEngine(Locale.getDefault());\n\t\tmodel.setBoard(AbstractChessEngine.getEmptyBoard());\n\t\tmodel.setBoard(60, Piece.WHITE_KING);\n\t\tmodel.setBoard(63, Piece.WHITE_ROOK);\n\t\tmodel.setBoard(56, Piece.WHITE_ROOK);\n\t\tmodel.setBoard(52, Piece.BLACK_KNIGHT);\n\t\tmodel.setWhiteCanCastleKingSide(true);\n\t\tmodel.setWhiteCanCastleQueenSide(true);\n\t\tmodel.setTurn(WHITE_TURN);\n\t\tlong[] moves = model.allMoves();\n\t\tassertEquals(WRONG_SIZE, 24, moves.length);\n\t\tStringBuilder builder = new StringBuilder();\n\t\tfor (int i = 0; i < moves.length; i++) {\n\t\t\tbuilder.append(Converter.moveToString(model.getBoard(), moves[i], Locale.FRANCE) + \" \"); //$NON-NLS-1$\n\t\t}", "answers": ["\t\tassertEquals(WRONG_MOVES,"], "length": 671, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "6e5ba0e3-5ba2-45e4-a86f-cd05ff1a2b8d", "reasoning": "The method test006 follows the same pattern as previous test methods: after building a StringBuilder with all move strings inside a for‑loop, the next step is to compare the generated string with the expected one using assertEquals. Therefore the next line should be the assertEquals call that checks WRONG_MOVES against the expected move list for this position.", "reasoning_model_answer": "assertEquals(WRONG_MOVES,\n \"Ta2 Ta3 Ta4 Ta5 Ta6 Ta7 Ta8 Tb1 Tc1 Td1 Rd2 Re2 Rf2 Rd1 Rf1 Rg1 Rc1 Th2 Th3 Th4 Th5 Th6 Th7 Th8 \",\n String.valueOf(builder));", "assistant_with_reasoning": "\nThe method test006 follows the same pattern as previous test methods: after building a StringBuilder with all move strings inside a for‑loop, the next step is to compare the generated string with the expected one using assertEquals. Therefore the next line should be the assertEquals call that checks WRONG_MOVES against the expected move list for this position.\n\nassertEquals(WRONG_MOVES,\n \"Ta2 Ta3 Ta4 Ta5 Ta6 Ta7 Ta8 Tb1 Tc1 Td1 Rd2 Re2 Rf2 Rd1 Rf1 Rg1 Rc1 Th2 Th3 Th4 Th5 Th6 Th7 Th8 \",\n String.valueOf(builder));", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 6.922, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 7546, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "assertEquals(WRONG_MOVES,\n \"Ta2 Ta3 Ta4 Ta5 Ta6 Ta7 Ta8 Tb1 Tc1 Td1 Rd2 Re2 Rf2 Rd1 Rf1 Rg1 Rc1 Th2 Th3 Th4 Th5 Th6 Th7 Th8 \",\n String.valueOf(builder));", "score": 0.96, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "//\n// System.Net.HttpListenerResponse\n//\n// Author:\n//\tGonzalo Paniagua Javier (gonzalo@novell.com)\n//\n// Copyright (c) 2005 Novell, Inc. (http://www.novell.com)\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n// \n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n// \n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System.Globalization;\nusing System.IO;\nusing System.Text;\nusing System;\nusing System.Net;\n\nnamespace HTTP.Net\n{\n internal class HttpListenerResponse : IDisposable, HttpResponse \n\t{\n\t\tbool disposed;\n\t\tEncoding content_encoding;\n\t\tlong content_length;\n\t\tbool cl_set;\n\t\tstring content_type;\n\t\tCookieCollection cookies;\n\t\tWebHeaderCollection headers = new WebHeaderCollection ();\n\t\tbool keep_alive = true;\n\t\tResponseStream output_stream;\n\t\tVersion version = HttpVersion.Version11;\n\t\tstring location;\n\t\tint status_code = 200;\n\t\tstring status_description = \"OK\";\n\t\tbool chunked;\n\t\tMonoContext context;\n\t\tinternal bool HeadersSent;\n\t\tbool force_close_chunked;\n ExtReponse eResp;\n\n\t\tinternal HttpListenerResponse (MonoContext context)\n\t\t{\n\t\t\tthis.context = context;\n eResp = new ExtReponse(this);\n\t\t}\n\n\t\tinternal bool ForceCloseChunked {\n\t\t\tget { return force_close_chunked; }\n\t\t}\n\n public TextWriter Output { get { return eResp.Output; } }\n public string[] FileDependencies { get { return eResp.FileDependencies; } }\n public int Expires { get { return eResp.Expires; } set { eResp.Expires = value; } }\n public CustomCachePolicy Cache { get { return eResp.Cache; } set { eResp.Cache = value; } }\n public Stream Filter { get { return eResp.Filter; } set { eResp.Filter = (InputFilterStream)value; } }\n public DateTime ExpiresAbsolute { get { return eResp.Cache.Expires; } set { eResp.Cache.SetExpires(value); } }\n\n\t\tpublic Encoding ContentEncoding {\n\t\t\tget {\n\t\t\t\tif (content_encoding == null)\n\t\t\t\t\tcontent_encoding = Encoding.Default;\n\t\t\t\treturn content_encoding;\n\t\t\t}\n\t\t\tset {\n\t\t\t\tif (disposed)\n\t\t\t\t\tthrow new ObjectDisposedException (GetType ().ToString ());\n\n\t\t\t\t//TODO: is null ok?\n\t\t\t\tif (HeadersSent)\n\t\t\t\t\tthrow new InvalidOperationException (\"Cannot be changed after headers are sent.\");\n\t\t\t\t\t\n\t\t\t\tcontent_encoding = value;\n\t\t\t}\n\t\t}\n\n\t\tpublic long ContentLength64 {\n\t\t\tget { return content_length; }\n\t\t\tset {\n\t\t\t\tif (disposed)\n\t\t\t\t\tthrow new ObjectDisposedException (GetType ().ToString ());\n\n\t\t\t\tif (HeadersSent)\n\t\t\t\t\tthrow new InvalidOperationException (\"Cannot be changed after headers are sent.\");\n\n\t\t\t\tif (value < 0)\n\t\t\t\t\tthrow new ArgumentOutOfRangeException (\"Must be >= 0\", \"value\");\n\n\t\t\t\tcl_set = true;\n\t\t\t\tcontent_length = value;\n\t\t\t}\n\t\t}\n\t\t\n\t\tpublic string ContentType {\n\t\t\tget { return content_type; }\n\t\t\tset {\n\t\t\t\t// TODO: is null ok?\n\t\t\t\tif (disposed)\n\t\t\t\t\tthrow new ObjectDisposedException (GetType ().ToString ());\n\n\t\t\t\tif (HeadersSent)\n\t\t\t\t\tthrow new InvalidOperationException (\"Cannot be changed after headers are sent.\");\n\n\t\t\t\tcontent_type = value;\n\t\t\t}\n\t\t}\n\n\t\t// RFC 2109, 2965 + the netscape specification at http://wp.netscape.com/newsref/std/cookie_spec.html\n\t\tpublic CookieCollection Cookies {\n\t\t\tget {\n\t\t\t\tif (cookies == null)\n\t\t\t\t\tcookies = new CookieCollection ();\n\t\t\t\treturn cookies;\n\t\t\t}\n\t\t\tset { cookies = value; } // null allowed?\n\t\t}\n\n\t\tpublic WebHeaderCollection Headers {\n\t\t\tget { return headers; }\n\t\t\tset {\n\t\t/**\n\t\t *\t\"If you attempt to set a Content-Length, Keep-Alive, Transfer-Encoding, or\n\t\t *\tWWW-Authenticate header using the Headers property, an exception will be\n\t\t *\tthrown. Use the KeepAlive or ContentLength64 properties to set these headers.\n\t\t *\tYou cannot set the Transfer-Encoding or WWW-Authenticate headers manually.\"\n\t\t*/\n\t\t// TODO: check if this is marked readonly after headers are sent.\n\t\t\t\theaders = value;\n\t\t\t}\n\t\t}\n\n\t\tpublic bool KeepAlive {", "answers": ["\t\t\tget { return keep_alive; }"], "length": 635, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "25d61c28-412b-422c-94cd-db3a51e68a3a", "reasoning": "The code is defining a property KeepAlive. Following the pattern of earlier properties, the next line should be the getter that returns the internal field keep_alive.", "reasoning_model_answer": "get { return keep_alive; }", "assistant_with_reasoning": "\nThe code is defining a property KeepAlive. Following the pattern of earlier properties, the next line should be the getter that returns the internal field keep_alive.\n\nget { return keep_alive; }", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 2.863, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 4806, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "get { return keep_alive; }", "score": 0.95, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "#!/usr/bin/python3\n#\n# Copyright (c) 2016, Alliance for Open Media. All rights reserved\n#\n# This source code is subject to the terms of the BSD 2 Clause License and\n# the Alliance for Open Media Patent License 1.0. If the BSD 2 Clause License\n# was not distributed with this source code in the LICENSE file, you can\n# obtain it at www.aomedia.org/license/software. If the Alliance for Open\n# Media Patent License 1.0 was not distributed with this source code in the\n# PATENTS file, you can obtain it at www.aomedia.org/license/patent.\n#\n\n\"\"\"Converts video encoding result data from text files to visualization\ndata source.\"\"\"\n\n__author__ = \"jzern@google.com (James Zern),\"\n__author__ += \"jimbankoski@google.com (Jim Bankoski)\"\n\nimport fnmatch\nimport numpy as np\nimport scipy as sp\nimport scipy.interpolate\nimport os\nimport re\nimport string\nimport sys\nimport math\nimport warnings\n\nimport gviz_api\n\nfrom os.path import basename\nfrom os.path import splitext\n\nwarnings.simplefilter('ignore', np.RankWarning)\nwarnings.simplefilter('ignore', RuntimeWarning)\n\ndef bdsnr2(metric_set1, metric_set2):\n \"\"\"\n BJONTEGAARD Bjontegaard metric calculation adapted\n Bjontegaard's snr metric allows to compute the average % saving in decibels\n between two rate-distortion curves [1]. This is an adaptation of that\n method that fixes inconsistencies when the curve fit operation goes awry\n by replacing the curve fit function with a Piecewise Cubic Hermite\n Interpolating Polynomial and then integrating that by evaluating that\n function at small intervals using the trapezoid method to calculate\n the integral.\n\n metric_set1 - list of tuples ( bitrate, metric ) for first graph\n metric_set2 - list of tuples ( bitrate, metric ) for second graph\n \"\"\"\n\n if not metric_set1 or not metric_set2:\n return 0.0\n\n try:\n\n # pchip_interlopate requires keys sorted by x axis. x-axis will\n # be our metric not the bitrate so sort by metric.\n metric_set1.sort()\n metric_set2.sort()\n\n # Pull the log of the rate and clamped psnr from metric_sets.\n log_rate1 = [math.log(x[0]) for x in metric_set1]\n metric1 = [100.0 if x[1] == float('inf') else x[1] for x in metric_set1]\n log_rate2 = [math.log(x[0]) for x in metric_set2]\n metric2 = [100.0 if x[1] == float('inf') else x[1] for x in metric_set2]\n\n # Integration interval. This metric only works on the area that's\n # overlapping. Extrapolation of these things is sketchy so we avoid.\n min_int = max([min(log_rate1), min(log_rate2)])\n max_int = min([max(log_rate1), max(log_rate2)])\n\n # No overlap means no sensible metric possible.\n if max_int <= min_int:\n return 0.0\n\n # Use Piecewise Cubic Hermite Interpolating Polynomial interpolation to\n # create 100 new samples points separated by interval.\n lin = np.linspace(min_int, max_int, num=100, retstep=True)\n interval = lin[1]\n samples = lin[0]\n v1 = scipy.interpolate.pchip_interpolate(log_rate1, metric1, samples)\n v2 = scipy.interpolate.pchip_interpolate(log_rate2, metric2, samples)\n\n # Calculate the integral using the trapezoid method on the samples.\n int_v1 = np.trapz(v1, dx=interval)\n int_v2 = np.trapz(v2, dx=interval)\n\n # Calculate the average improvement.\n avg_exp_diff = (int_v2 - int_v1) / (max_int - min_int)\n\n except (TypeError, ZeroDivisionError, ValueError, np.RankWarning) as e:\n return 0\n\n return avg_exp_diff\n\ndef bdrate2(metric_set1, metric_set2):\n \"\"\"\n BJONTEGAARD Bjontegaard metric calculation adapted\n Bjontegaard's metric allows to compute the average % saving in bitrate\n between two rate-distortion curves [1]. This is an adaptation of that\n method that fixes inconsistencies when the curve fit operation goes awry\n by replacing the curve fit function with a Piecewise Cubic Hermite\n Interpolating Polynomial and then integrating that by evaluating that\n function at small intervals using the trapezoid method to calculate\n the integral.\n\n metric_set1 - list of tuples ( bitrate, metric ) for first graph\n metric_set2 - list of tuples ( bitrate, metric ) for second graph\n \"\"\"\n\n if not metric_set1 or not metric_set2:\n return 0.0\n\n try:\n\n # pchip_interlopate requires keys sorted by x axis. x-axis will\n # be our metric not the bitrate so sort by metric.\n metric_set1.sort(key=lambda tup: tup[1])\n metric_set2.sort(key=lambda tup: tup[1])\n\n # Pull the log of the rate and clamped psnr from metric_sets.\n log_rate1 = [math.log(x[0]) for x in metric_set1]\n metric1 = [100.0 if x[1] == float('inf') else x[1] for x in metric_set1]", "answers": [" log_rate2 = [math.log(x[0]) for x in metric_set2]"], "length": 637, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "4d24e2e5-c268-432e-a310-f74345cc6480", "reasoning": "Within the bdrate2 function, after sorting the metric sets, the code extracts the log of the bitrate and clamps the metric values for the first set, assigning them to log_rate1 and metric1. The next logical step mirrors the earlier function bdsnr2: compute the same values for the second metric set. Therefore the next line should define log_rate2 using metric_set2.", "reasoning_model_answer": "log_rate2 = [math.log(x[0]) for x in metric_set2]", "assistant_with_reasoning": "\nWithin the bdrate2 function, after sorting the metric sets, the code extracts the log of the bitrate and clamps the metric values for the first set, assigning them to log_rate1 and metric1. The next logical step mirrors the earlier function bdsnr2: compute the same values for the second metric set. Therefore the next line should define log_rate2 using metric_set2.\n\nlog_rate2 = [math.log(x[0]) for x in metric_set2]", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.042, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 4678, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "log_rate2 = [math.log(x[0]) for x in metric_set2]", "score": 0.96, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "package redis.clients.jedis;\n\nimport java.io.Closeable;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Map.Entry;\nimport java.util.Set;\nimport java.util.regex.Pattern;\n\nimport redis.clients.jedis.BinaryClient.LIST_POSITION;\nimport redis.clients.util.Hashing;\nimport redis.clients.util.Pool;\n\npublic class ShardedJedis extends BinaryShardedJedis implements JedisCommands, Closeable {\n\n protected Pool dataSource = null;\n\n public ShardedJedis(List shards) {\n super(shards);\n }\n\n public ShardedJedis(List shards, Hashing algo) {\n super(shards, algo);\n }\n\n public ShardedJedis(List shards, Pattern keyTagPattern) {\n super(shards, keyTagPattern);\n }\n\n public ShardedJedis(List shards, Hashing algo, Pattern keyTagPattern) {\n super(shards, algo, keyTagPattern);\n }\n\n public String set(String key, String value) {\n Jedis j = getShard(key);\n return j.set(key, value);\n }\n\n @Override\n public String set(String key, String value, String nxxx, String expx, long time) {\n Jedis j = getShard(key);\n return j.set(key, value, nxxx, expx, time);\n }\n\n public String get(String key) {\n Jedis j = getShard(key);\n return j.get(key);\n }\n\n public String echo(String string) {\n Jedis j = getShard(string);\n return j.echo(string);\n }\n\n public Boolean exists(String key) {\n Jedis j = getShard(key);\n return j.exists(key);\n }\n\n public String type(String key) {\n Jedis j = getShard(key);\n return j.type(key);\n }\n\n public Long expire(String key, int seconds) {\n Jedis j = getShard(key);\n return j.expire(key, seconds);\n }\n\n public Long expireAt(String key, long unixTime) {\n Jedis j = getShard(key);\n return j.expireAt(key, unixTime);\n }\n\n public Long ttl(String key) {\n Jedis j = getShard(key);\n return j.ttl(key);\n }\n\n public Boolean setbit(String key, long offset, boolean value) {\n Jedis j = getShard(key);\n return j.setbit(key, offset, value);\n }\n\n public Boolean setbit(String key, long offset, String value) {\n Jedis j = getShard(key);\n return j.setbit(key, offset, value);\n }\n\n public Boolean getbit(String key, long offset) {\n Jedis j = getShard(key);\n return j.getbit(key, offset);\n }\n\n public Long setrange(String key, long offset, String value) {\n Jedis j = getShard(key);\n return j.setrange(key, offset, value);\n }\n\n public String getrange(String key, long startOffset, long endOffset) {\n Jedis j = getShard(key);\n return j.getrange(key, startOffset, endOffset);\n }\n\n public String getSet(String key, String value) {\n Jedis j = getShard(key);\n return j.getSet(key, value);\n }\n\n public Long setnx(String key, String value) {\n Jedis j = getShard(key);\n return j.setnx(key, value);\n }\n\n public String setex(String key, int seconds, String value) {\n Jedis j = getShard(key);\n return j.setex(key, seconds, value);\n }\n\n public List blpop(String arg) {\n Jedis j = getShard(arg);\n return j.blpop(arg);\n }\n\n public List blpop(int timeout, String key) {\n Jedis j = getShard(key);\n return j.blpop(timeout, key);\n }\n\n public List brpop(String arg) {\n Jedis j = getShard(arg);\n return j.brpop(arg);\n }\n\n public List brpop(int timeout, String key) {\n Jedis j = getShard(key);\n return j.brpop(timeout, key);\n }\n\n public Long decrBy(String key, long integer) {\n Jedis j = getShard(key);\n return j.decrBy(key, integer);\n }\n\n public Long decr(String key) {\n Jedis j = getShard(key);\n return j.decr(key);\n }\n\n public Long incrBy(String key, long integer) {\n Jedis j = getShard(key);\n return j.incrBy(key, integer);\n }\n\n public Double incrByFloat(String key, double integer) {\n Jedis j = getShard(key);\n return j.incrByFloat(key, integer);\n }\n\n public Long incr(String key) {\n Jedis j = getShard(key);\n return j.incr(key);\n }\n\n public Long append(String key, String value) {\n Jedis j = getShard(key);\n return j.append(key, value);\n }\n\n public String substr(String key, int start, int end) {\n Jedis j = getShard(key);\n return j.substr(key, start, end);\n }\n\n public Long hset(String key, String field, String value) {\n Jedis j = getShard(key);\n return j.hset(key, field, value);\n }\n\n public String hget(String key, String field) {\n Jedis j = getShard(key);\n return j.hget(key, field);\n }\n\n public Long hsetnx(String key, String field, String value) {\n Jedis j = getShard(key);\n return j.hsetnx(key, field, value);\n }\n\n public String hmset(String key, Map hash) {\n Jedis j = getShard(key);\n return j.hmset(key, hash);\n }\n\n public List hmget(String key, String... fields) {\n Jedis j = getShard(key);\n return j.hmget(key, fields);\n }\n\n public Long hincrBy(String key, String field, long value) {\n Jedis j = getShard(key);\n return j.hincrBy(key, field, value);\n }\n\n public Double hincrByFloat(String key, String field, double value) {\n Jedis j = getShard(key);\n return j.hincrByFloat(key, field, value);\n }\n\n public Boolean hexists(String key, String field) {\n Jedis j = getShard(key);\n return j.hexists(key, field);\n }\n\n public Long del(String key) {\n Jedis j = getShard(key);\n return j.del(key);\n }\n\n public Long hdel(String key, String... fields) {\n Jedis j = getShard(key);", "answers": [" return j.hdel(key, fields);"], "length": 652, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "fb31ac16-39f2-4f26-80bb-b1cf88b9ce02", "reasoning": "The method hdel is being defined. Following the pattern of other methods, after obtaining the shard with Jedis j = getShard(key); the next line should delegate to the underlying Jedis instance and return its result. The Jedis API provides hdel(key, fields) returning Long, so the next line is the return statement.", "reasoning_model_answer": "return j.hdel(key, fields);", "assistant_with_reasoning": "\nThe method hdel is being defined. Following the pattern of other methods, after obtaining the shard with Jedis j = getShard(key); the next line should delegate to the underlying Jedis instance and return its result. The Jedis API provides hdel(key, fields) returning Long, so the next line is the return statement.\n\nreturn j.hdel(key, fields);", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.725, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 5500, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "return j.hdel(key, fields);", "score": 0.93, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/*\n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or\n * (at your option) any later version.\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n */\npackage games.strategy.triplea.ai.Dynamix_AI;\n\nimport games.strategy.engine.data.GameData;\nimport games.strategy.engine.data.PlayerID;\nimport games.strategy.engine.data.Route;\nimport games.strategy.engine.data.Territory;\nimport games.strategy.engine.data.Unit;\nimport games.strategy.triplea.Constants;\nimport games.strategy.triplea.Properties;\nimport games.strategy.triplea.ai.Dynamix_AI.CommandCenter.GlobalCenter;\nimport games.strategy.triplea.ai.Dynamix_AI.CommandCenter.StatusCenter;\nimport games.strategy.triplea.ai.Dynamix_AI.Group.UnitGroup;\nimport games.strategy.triplea.ai.Dynamix_AI.Others.TerritoryStatus;\nimport games.strategy.triplea.attatchments.RulesAttachment;\nimport games.strategy.triplea.attatchments.TerritoryAttachment;\nimport games.strategy.triplea.attatchments.UnitAttachment;\nimport games.strategy.triplea.delegate.Matches;\nimport games.strategy.util.CompositeMatchAnd;\nimport games.strategy.util.Match;\n\nimport java.util.Collection;\nimport java.util.List;\n\n/**\n * Some notes on the matches in this class:\n * \n * First, to keep the matches organized, I would like all the matches to be put into their section, which should be created if not yet existing.\n * All unit matches in one section, all territory matches in another, etc.\n * \n * Also, make sure there are markers to show the start and end of each section, as well as ten lines of blank space between each section.\n * \n * @author Stephen\n */\n@SuppressWarnings({ \"unchecked\", \"deprecation\" })\npublic class DMatches\n{\n\t// /////////////////////////////////////////////Unit Group Matches///////////////////////////////////////////////\n\tpublic static Match UnitGroupCanReach_Some(final Territory target)\n\t{\n\t\treturn new Match()\n\t\t{\n\t\t\t@Override\n\t\t\tpublic boolean match(final UnitGroup ug)\n\t\t\t{\n\t\t\t\tfinal Route ncmRoute = ug.GetNCMRoute(target);\n\t\t\t\tif (ncmRoute == null)\n\t\t\t\t\treturn false;\n\t\t\t\treturn Match.someMatch(ug.GetUnits(), Matches.UnitHasEnoughMovement(ncmRoute.getLength()));\n\t\t\t}\n\t\t};\n\t}\n\t\n\tpublic static Match UnitGroupCanReach_All(final Territory target)\n\t{\n\t\treturn new Match()\n\t\t{\n\t\t\t@Override\n\t\t\tpublic boolean match(final UnitGroup ug)\n\t\t\t{\n\t\t\t\tfinal Route ncmRoute = ug.GetNCMRoute(target);\n\t\t\t\tif (ncmRoute == null)\n\t\t\t\t\treturn false;\n\t\t\t\treturn Match.allMatch(ug.GetUnits(), Matches.UnitHasEnoughMovement(ncmRoute.getLength()));\n\t\t\t}\n\t\t};\n\t}\n\t\n\tpublic static Match UnitGroupHasEnoughMovement_Some(final int minMovement)\n\t{\n\t\treturn new Match()\n\t\t{\n\t\t\t@Override\n\t\t\tpublic boolean match(final UnitGroup ug)\n\t\t\t{\n\t\t\t\treturn Match.someMatch(ug.GetUnits(), Matches.UnitHasEnoughMovement(minMovement));\n\t\t\t}\n\t\t};\n\t}\n\t\n\tpublic static Match UnitGroupHasEnoughMovement_All(final int minMovement)\n\t{\n\t\treturn new Match()\n\t\t{\n\t\t\t@Override\n\t\t\tpublic boolean match(final UnitGroup ug)\n\t\t\t{\n\t\t\t\treturn Match.allMatch(ug.GetUnits(), Matches.UnitHasEnoughMovement(minMovement));\n\t\t\t}\n\t\t};\n\t}\n\t\n\tpublic static Match UnitGroupUnitsMatchX_All(final Match match)\n\t{\n\t\treturn new Match()\n\t\t{\n\t\t\t@Override\n\t\t\tpublic boolean match(final UnitGroup ug)\n\t\t\t{\n\t\t\t\treturn Match.allMatch(ug.GetUnits(), match);\n\t\t\t}\n\t\t};\n\t}\n\t\n\tpublic static final Match UnitGroupIsSeaOrAir = new Match()\n\t{\n\t\t@Override\n\t\tpublic boolean match(final UnitGroup unitGroup)\n\t\t{\n\t\t\tfinal UnitAttachment ua = UnitAttachment.get(unitGroup.GetFirstUnit().getType());\n\t\t\treturn ua.getIsSea() || ua.getIsAir();\n\t\t}\n\t};\n\tpublic static final Match UnitGroupIsLand = new Match()\n\t{\n\t\t@Override\n\t\tpublic boolean match(final UnitGroup unitGroup)\n\t\t{\n\t\t\tfinal UnitAttachment ua = UnitAttachment.get(unitGroup.GetFirstUnit().getType());\n\t\t\treturn !ua.getIsSea();\n\t\t}\n\t};\n\t\n\t// /////////////////////////////////////////////End Unit Group Matches///////////////////////////////////////////////\n\t// /////////////////////////////////////////////Unit Matches///////////////////////////////////////////////\n\tpublic static Match unitIs(final Unit u1)\n\t{\n\t\treturn new Match()\n\t\t{\n\t\t\t@Override\n\t\t\tpublic boolean match(final Unit u2)\n\t\t\t{\n\t\t\t\treturn u1 == u2;\n\t\t\t}\n\t\t};\n\t}\n\t\n\tpublic static Match unitIsNotInList(final List list)\n\t{\n\t\treturn new Match()\n\t\t{\n\t\t\t@Override\n\t\t\tpublic boolean match(final Unit ter)\n\t\t\t{\n\t\t\t\treturn !list.contains(ter);\n\t\t\t}\n\t\t};\n\t}\n\t\n\tpublic static Match unitIsInList(final List list)\n\t{\n\t\treturn new Match()\n\t\t{\n\t\t\t@Override\n\t\t\tpublic boolean match(final Unit ter)\n\t\t\t{\n\t\t\t\treturn list.contains(ter);\n\t\t\t}\n\t\t};\n\t}\n\t\n\tpublic static Match unitIsNNEnemyOf(final GameData data, final PlayerID player)\n\t{\n\t\treturn new Match()\n\t\t{\n\t\t\t@Override\n\t\t\tpublic boolean match(final Unit u)\n\t\t\t{\n\t\t\t\tif (u.getOwner().isNull())\n\t\t\t\t\treturn false;\n\t\t\t\treturn !data.getRelationshipTracker().isAllied(u.getOwner(), player);\n\t\t\t}\n\t\t};\n\t}\n\t\n\tpublic static final Match UnitIsMoveableType = new Match()\n\t{\n\t\t@Override\n\t\tpublic boolean match(final Unit unit)\n\t\t{\n\t\t\tfinal UnitAttachment ua = UnitAttachment.get(unit.getUnitType());\n\t\t\treturn ua.getMovement(unit.getOwner()) > 0;\n\t\t}\n\t};\n\tpublic static Match UnitIsCombatMoveMoveableType = new Match()\n\t{\n\t\t@Override\n\t\tpublic boolean match(final Unit unit)\n\t\t{\n\t\t\tfinal UnitAttachment ua = UnitAttachment.get(unit.getUnitType());\n\t\t\treturn ua.getMovement(unit.getOwner()) > 0 && !ua.getCanNotMoveDuringCombatMove();\n\t\t}\n\t};\n\tpublic static final Match UnitCanAttack = new Match()\n\t{\n\t\t@Override\n\t\tpublic boolean match(final Unit unit)\n\t\t{\n\t\t\tfinal UnitAttachment ua = UnitAttachment.get(unit.getUnitType());\n\t\t\tif (ua.getIsInfrastructure())\n\t\t\t\treturn false;\n\t\t\tif (ua.getCanProduceUnits())\n\t\t\t\treturn false; // TODO: maybe we can attack, if we have attacking factories?\n\t\t\tif (ua.getCanNotMoveDuringCombatMove())\n\t\t\t\treturn false;", "answers": ["\t\t\treturn true;"], "length": 670, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "42807186-bcb7-4049-98cc-22a36d754dc9", "reasoning": "The code is defining a Match called UnitCanAttack. Inside the match method, it checks several conditions that would disqualify a unit from attacking. After those checks, the typical logic is to return true if none of the disqualifying conditions are met. The next line should therefore be the return statement indicating the unit can attack.", "reasoning_model_answer": "return true;", "assistant_with_reasoning": "\nThe code is defining a Match called UnitCanAttack. Inside the match method, it checks several conditions that would disqualify a unit from attacking. After those checks, the typical logic is to return true if none of the disqualifying conditions are met. The next line should therefore be the return statement indicating the unit can attack.\n\nreturn true;", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 2.913, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 6666, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "return true;", "score": 0.89, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "// ReSharper disable All\n/********************************************************************************\nCopyright (C) MixERP Inc. (http://mixof.org).\n\nThis file is part of MixERP.\n\nMixERP is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, version 2 of the License.\n\n\nMixERP is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with MixERP. If not, see .\n***********************************************************************************/\nusing System.Collections.Generic;\nusing System.Data;\nusing System.Linq;\nusing MixERP.Net.DbFactory;\nusing MixERP.Net.EntityParser;\nusing MixERP.Net.Framework;\nusing Npgsql;\nusing PetaPoco;\nusing Serilog;\n\nnamespace MixERP.Net.Schemas.Core.Data\n{\n /// \n /// Provides simplified data access features to perform SCRUD operation on the database table \"core.item_types\".\n /// \n public class ItemType : DbAccess\n {\n /// \n /// The schema of this table. Returns literal \"core\".\n /// \n public override string _ObjectNamespace => \"core\";\n\n /// \n /// The schema unqualified name of this table. Returns literal \"item_types\".\n /// \n public override string _ObjectName => \"item_types\";\n\n /// \n /// Login id of application user accessing this table.\n /// \n public long _LoginId { get; set; }\n\n /// \n /// User id of application user accessing this table.\n /// \n public int _UserId { get; set; }\n\n /// \n /// The name of the database on which queries are being executed to.\n /// \n public string _Catalog { get; set; }\n\n /// \n /// Performs SQL count on the table \"core.item_types\".\n /// \n /// Returns the number of rows of the table \"core.item_types\".\n /// Thown when the application user does not have sufficient privilege to perform this action.\n public long Count()\n {\n if (string.IsNullOrWhiteSpace(this._Catalog))\n {\n return 0;\n }\n\n if (!this.SkipValidation)\n {\n if (!this.Validated)\n {\n this.Validate(AccessTypeEnum.Read, this._LoginId, false);\n }\n if (!this.HasAccess)\n {\n Log.Information(\"Access to count entity \\\"ItemType\\\" was denied to the user with Login ID {LoginId}\", this._LoginId);\n throw new UnauthorizedException(\"Access is denied.\");\n }\n }\n\n const string sql = \"SELECT COUNT(*) FROM core.item_types;\";\n return Factory.Scalar(this._Catalog, sql);\n }\n\n /// \n /// Executes a select query on the table \"core.item_types\" to return a all instances of the \"ItemType\" class to export. \n /// \n /// Returns a non-live, non-mapped instances of \"ItemType\" class.\n /// Thown when the application user does not have sufficient privilege to perform this action.\n public IEnumerable Get()\n {\n if (string.IsNullOrWhiteSpace(this._Catalog))\n {\n return null;\n }\n\n if (!this.SkipValidation)\n {\n if (!this.Validated)\n {\n this.Validate(AccessTypeEnum.ExportData, this._LoginId, false);\n }\n if (!this.HasAccess)\n {\n Log.Information(\"Access to the export entity \\\"ItemType\\\" was denied to the user with Login ID {LoginId}\", this._LoginId);\n throw new UnauthorizedException(\"Access is denied.\");\n }\n }\n\n const string sql = \"SELECT * FROM core.item_types ORDER BY item_type_id;\";\n return Factory.Get(this._Catalog, sql);\n }\n\n /// \n /// Executes a select query on the table \"core.item_types\" with a where filter on the column \"item_type_id\" to return a single instance of the \"ItemType\" class. \n /// \n /// The column \"item_type_id\" parameter used on where filter.\n /// Returns a non-live, non-mapped instance of \"ItemType\" class mapped to the database row.\n /// Thown when the application user does not have sufficient privilege to perform this action.\n public MixERP.Net.Entities.Core.ItemType Get(int itemTypeId)\n {\n if (string.IsNullOrWhiteSpace(this._Catalog))\n {\n return null;\n }\n\n if (!this.SkipValidation)\n {\n if (!this.Validated)\n {\n this.Validate(AccessTypeEnum.Read, this._LoginId, false);\n }\n if (!this.HasAccess)\n {\n Log.Information(\"Access to the get entity \\\"ItemType\\\" filtered by \\\"ItemTypeId\\\" with value {ItemTypeId} was denied to the user with Login ID {_LoginId}\", itemTypeId, this._LoginId);", "answers": [" throw new UnauthorizedException(\"Access is denied.\");"], "length": 582, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "4fd6f980-6cd4-466e-9f1b-18e578468aaa", "reasoning": "Within the Get(int itemTypeId) method, after verifying access, the code logs a message when access is denied. Consistent with other methods in this class, the next step is to throw an UnauthorizedException to stop execution. Therefore the next line should be the throw statement.", "reasoning_model_answer": "throw new UnauthorizedException(\"Access is denied.\");", "assistant_with_reasoning": "\nWithin the Get(int itemTypeId) method, after verifying access, the code logs a message when access is denied. Consistent with other methods in this class, the next step is to throw an UnauthorizedException to stop execution. Therefore the next line should be the throw statement.\n\nthrow new UnauthorizedException(\"Access is denied.\");", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.564, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 5895, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "throw new UnauthorizedException(\"Access is denied.\");", "score": 0.84, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/*\n * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\"). You may not use this file except in compliance with\n * the License. A copy of the License is located at\n * \n * http://aws.amazon.com/apache2.0\n * \n * or in the \"license\" file accompanying this file. This file is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR\n * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions\n * and limitations under the License.\n */\npackage com.amazonaws.services.computeoptimizer.model;\n\nimport java.io.Serializable;\nimport javax.annotation.Generated;\n\nimport com.amazonaws.AmazonWebServiceRequest;\n\n/**\n * \n * @see AWS API Documentation\n */\n@Generated(\"com.amazonaws:aws-java-sdk-code-generator\")\npublic class GetRecommendationSummariesRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable {\n\n /**\n *

    \n * The ID of the Amazon Web Services account for which to return recommendation summaries.\n *

    \n *

    \n * If your account is the management account of an organization, use this parameter to specify the member account\n * for which you want to return recommendation summaries.\n *

    \n *

    \n * Only one account ID can be specified per request.\n *

    \n */\n private java.util.List accountIds;\n /**\n *

    \n * The token to advance to the next page of recommendation summaries.\n *

    \n */\n private String nextToken;\n /**\n *

    \n * The maximum number of recommendation summaries to return with a single request.\n *

    \n *

    \n * To retrieve the remaining results, make another request with the returned nextToken value.\n *

    \n */\n private Integer maxResults;\n\n /**\n *

    \n * The ID of the Amazon Web Services account for which to return recommendation summaries.\n *

    \n *

    \n * If your account is the management account of an organization, use this parameter to specify the member account\n * for which you want to return recommendation summaries.\n *

    \n *

    \n * Only one account ID can be specified per request.\n *

    \n * \n * @return The ID of the Amazon Web Services account for which to return recommendation summaries.

    \n *

    \n * If your account is the management account of an organization, use this parameter to specify the member\n * account for which you want to return recommendation summaries.\n *

    \n *

    \n * Only one account ID can be specified per request.\n */\n\n public java.util.List getAccountIds() {\n return accountIds;\n }\n\n /**\n *

    \n * The ID of the Amazon Web Services account for which to return recommendation summaries.\n *

    \n *

    \n * If your account is the management account of an organization, use this parameter to specify the member account\n * for which you want to return recommendation summaries.\n *

    \n *

    \n * Only one account ID can be specified per request.\n *

    \n * \n * @param accountIds\n * The ID of the Amazon Web Services account for which to return recommendation summaries.

    \n *

    \n * If your account is the management account of an organization, use this parameter to specify the member\n * account for which you want to return recommendation summaries.\n *

    \n *

    \n * Only one account ID can be specified per request.\n */\n\n public void setAccountIds(java.util.Collection accountIds) {\n if (accountIds == null) {\n this.accountIds = null;\n return;\n }\n\n this.accountIds = new java.util.ArrayList(accountIds);\n }\n\n /**\n *

    \n * The ID of the Amazon Web Services account for which to return recommendation summaries.\n *

    \n *

    \n * If your account is the management account of an organization, use this parameter to specify the member account\n * for which you want to return recommendation summaries.\n *

    \n *

    \n * Only one account ID can be specified per request.\n *

    \n *

    \n * NOTE: This method appends the values to the existing list (if any). Use\n * {@link #setAccountIds(java.util.Collection)} or {@link #withAccountIds(java.util.Collection)} if you want to", "answers": [" * override the existing values."], "length": 636, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "672b0897-3a88-47f8-a26c-414f2eb458d7", "reasoning": "The code is a Javadoc comment for the withAccountIds method. It ends mid‑sentence: \"Use {@link #setAccountIds(java.util.Collection)} or {@link #withAccountIds(java.util.Collection)} if you want to\". The typical continuation in AWS SDK generated code is \"override the existing values.\" So the next line should complete the sentence within the comment.", "reasoning_model_answer": "* override the existing values.", "assistant_with_reasoning": "\nThe code is a Javadoc comment for the withAccountIds method. It ends mid‑sentence: \"Use {@link #setAccountIds(java.util.Collection)} or {@link #withAccountIds(java.util.Collection)} if you want to\". The typical continuation in AWS SDK generated code is \"override the existing values.\" So the next line should complete the sentence within the comment.\n\n* override the existing values.", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 5.886, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 4783, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "* override the existing values.", "score": 0.93, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License. See License.txt in the project root for\n// license information.\n// \n// Code generated by Microsoft (R) AutoRest Code Generator.\n// Changes may cause incorrect behavior and will be lost if the code is\n// regenerated.\n\nnamespace Fixtures.Azure.AcceptanceTestsAzureSpecials\n{\n using System;\n using System.Linq;\n using System.Collections.Generic;\n using System.Net;\n using System.Net.Http;\n using System.Net.Http.Headers;\n using System.Text;\n using System.Text.RegularExpressions;\n using System.Threading;\n using System.Threading.Tasks;\n using Microsoft.Rest;\n using Microsoft.Rest.Serialization;\n using Newtonsoft.Json;\n using Microsoft.Rest.Azure;\n using Models;\n\n ///

    \n /// SkipUrlEncodingOperations operations.\n /// \n internal partial class SkipUrlEncodingOperations : IServiceOperations, ISkipUrlEncodingOperations\n {\n /// \n /// Initializes a new instance of the SkipUrlEncodingOperations class.\n /// \n /// \n /// Reference to the service client.\n /// \n internal SkipUrlEncodingOperations(AutoRestAzureSpecialParametersTestClient client)\n {\n if (client == null) \n {\n throw new ArgumentNullException(\"client\");\n }\n this.Client = client;\n }\n\n /// \n /// Gets a reference to the AutoRestAzureSpecialParametersTestClient\n /// \n public AutoRestAzureSpecialParametersTestClient Client { get; private set; }\n\n /// \n /// Get method with unencoded path parameter with value 'path1/path2/path3'\n /// \n /// \n /// Unencoded path parameter with value 'path1/path2/path3'\n /// \n /// \n /// Headers that will be added to request.\n /// \n /// \n /// The cancellation token.\n /// \n /// \n /// A response object containing the response body and response headers.\n /// \n public async Task GetMethodPathValidWithHttpMessagesAsync(string unencodedPathParam, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))\n {\n if (unencodedPathParam == null)\n {\n throw new ValidationException(ValidationRules.CannotBeNull, \"unencodedPathParam\");\n }\n // Tracing\n bool _shouldTrace = ServiceClientTracing.IsEnabled;\n string _invocationId = null;\n if (_shouldTrace)\n {\n _invocationId = ServiceClientTracing.NextInvocationId.ToString();\n Dictionary tracingParameters = new Dictionary();\n tracingParameters.Add(\"unencodedPathParam\", unencodedPathParam);\n tracingParameters.Add(\"cancellationToken\", cancellationToken);\n ServiceClientTracing.Enter(_invocationId, this, \"GetMethodPathValid\", tracingParameters);\n }\n // Construct URL\n var _baseUrl = this.Client.BaseUri.AbsoluteUri;\n var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith(\"/\") ? \"\" : \"/\")), \"azurespecials/skipUrlEncoding/method/path/valid/{unencodedPathParam}\").ToString();\n _url = _url.Replace(\"{unencodedPathParam}\", unencodedPathParam);\n List _queryParameters = new List();\n if (_queryParameters.Count > 0)\n {\n _url += \"?\" + string.Join(\"&\", _queryParameters);\n }\n // Create HTTP transport objects\n HttpRequestMessage _httpRequest = new HttpRequestMessage();\n HttpResponseMessage _httpResponse = null;\n _httpRequest.Method = new HttpMethod(\"GET\");\n _httpRequest.RequestUri = new Uri(_url);\n // Set Headers\n if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)\n {\n _httpRequest.Headers.TryAddWithoutValidation(\"x-ms-client-request-id\", Guid.NewGuid().ToString());\n }\n if (this.Client.AcceptLanguage != null)\n {\n if (_httpRequest.Headers.Contains(\"accept-language\"))\n {\n _httpRequest.Headers.Remove(\"accept-language\");\n }\n _httpRequest.Headers.TryAddWithoutValidation(\"accept-language\", this.Client.AcceptLanguage);\n }\n if (customHeaders != null)\n {\n foreach(var _header in customHeaders)\n {\n if (_httpRequest.Headers.Contains(_header.Key))\n {\n _httpRequest.Headers.Remove(_header.Key);\n }\n _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);\n }\n }\n\n // Serialize Request\n string _requestContent = null;\n // Set Credentials\n if (this.Client.Credentials != null)\n {\n cancellationToken.ThrowIfCancellationRequested();\n await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);\n }\n // Send Request\n if (_shouldTrace)\n {\n ServiceClientTracing.SendRequest(_invocationId, _httpRequest);\n }\n cancellationToken.ThrowIfCancellationRequested();\n _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);\n if (_shouldTrace)\n {\n ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);\n }\n HttpStatusCode _statusCode = _httpResponse.StatusCode;\n cancellationToken.ThrowIfCancellationRequested();\n string _responseContent = null;\n if ((int)_statusCode != 200)\n {\n var ex = new ErrorException(string.Format(\"Operation returned an invalid status code '{0}'\", _statusCode));\n try\n {\n _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);\n Error _errorBody = SafeJsonConvert.DeserializeObject(_responseContent, this.Client.DeserializationSettings);\n if (_errorBody != null)\n {\n ex.Body = _errorBody;\n }\n }\n catch (JsonException)\n {\n // Ignore the exception\n }\n ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);\n ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);\n if (_shouldTrace)\n {\n ServiceClientTracing.Error(_invocationId, ex);\n }\n _httpRequest.Dispose();\n if (_httpResponse != null)\n {\n _httpResponse.Dispose();\n }\n throw ex;\n }\n // Create Result\n var _result = new AzureOperationResponse();\n _result.Request = _httpRequest;\n _result.Response = _httpResponse;\n if (_httpResponse.Headers.Contains(\"x-ms-request-id\"))\n {\n _result.RequestId = _httpResponse.Headers.GetValues(\"x-ms-request-id\").FirstOrDefault();\n }\n if (_shouldTrace)\n {\n ServiceClientTracing.Exit(_invocationId, _result);\n }\n return _result;\n }\n\n /// \n /// Get method with unencoded path parameter with value 'path1/path2/path3'\n /// \n /// \n /// Unencoded path parameter with value 'path1/path2/path3'\n /// \n /// \n /// Headers that will be added to request.\n /// \n /// \n /// The cancellation token.\n /// \n /// \n /// A response object containing the response body and response headers.\n /// \n public async Task GetPathPathValidWithHttpMessagesAsync(string unencodedPathParam, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))\n {\n if (unencodedPathParam == null)\n {\n throw new ValidationException(ValidationRules.CannotBeNull, \"unencodedPathParam\");\n }\n // Tracing\n bool _shouldTrace = ServiceClientTracing.IsEnabled;\n string _invocationId = null;\n if (_shouldTrace)\n {\n _invocationId = ServiceClientTracing.NextInvocationId.ToString();\n Dictionary tracingParameters = new Dictionary();", "answers": [" tracingParameters.Add(\"unencodedPathParam\", unencodedPathParam);"], "length": 655, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "362ad429-0c7b-447b-816f-a2f8a4691f28", "reasoning": "The method mirrors the earlier GetMethodPathValidWithHttpMessagesAsync implementation. Inside the tracing block, after creating the tracingParameters dictionary, the next step is to add the method arguments to it. The first argument added is the unencodedPathParam, so the next line is tracingParameters.Add(\"unencodedPathParam\", unencodedPathParam);", "reasoning_model_answer": "tracingParameters.Add(\"unencodedPathParam\", unencodedPathParam);", "assistant_with_reasoning": "\nThe method mirrors the earlier GetMethodPathValidWithHttpMessagesAsync implementation. Inside the tracing block, after creating the tracingParameters dictionary, the next step is to add the method arguments to it. The first argument added is the unencodedPathParam, so the next line is tracingParameters.Add(\"unencodedPathParam\", unencodedPathParam);\n\ntracingParameters.Add(\"unencodedPathParam\", unencodedPathParam);", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.393, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 9581, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "tracingParameters.Add(\"unencodedPathParam\", unencodedPathParam);", "score": 0.89, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "# Copyright 2016 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Tests of utilities supporting export to SavedModel.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\nimport tempfile\nimport time\n\nfrom tensorflow.contrib.layers.python.layers import feature_column as fc\nfrom tensorflow.contrib.learn.python.learn import export_strategy as export_strategy_lib\nfrom tensorflow.contrib.learn.python.learn.estimators import constants\nfrom tensorflow.contrib.learn.python.learn.estimators import estimator as core_estimator\nfrom tensorflow.contrib.learn.python.learn.estimators import model_fn\nfrom tensorflow.contrib.learn.python.learn.utils import input_fn_utils\nfrom tensorflow.contrib.learn.python.learn.utils import saved_model_export_utils\nfrom tensorflow.core.framework import tensor_shape_pb2\nfrom tensorflow.core.framework import types_pb2\nfrom tensorflow.core.protobuf import meta_graph_pb2\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.platform import gfile\nfrom tensorflow.python.platform import test\nfrom tensorflow.python.saved_model import signature_constants\nfrom tensorflow.python.saved_model import signature_def_utils\nfrom tensorflow.python.util import compat\n\n\nclass TestEstimator(core_estimator.Estimator):\n\n def __init__(self, *args, **kwargs):\n super(TestEstimator, self).__init__(*args, **kwargs)\n self.last_exported_checkpoint = \"\"\n self.last_exported_dir = \"\"\n\n # @Override\n def export_savedmodel(self,\n export_dir,\n serving_input_fn,\n default_output_alternative_key=None,\n assets_extra=None,\n as_text=False,\n checkpoint_path=None):\n\n if not os.path.exists(export_dir):\n os.makedirs(export_dir)\n\n open(os.path.join(export_dir, \"placeholder.txt\"), \"a\").close()\n\n self.last_exported_checkpoint = checkpoint_path\n self.last_exported_dir = export_dir\n\n return export_dir\n\n\nclass SavedModelExportUtilsTest(test.TestCase):\n\n def test_build_standardized_signature_def_regression(self):\n input_tensors = {\n \"input-1\":\n array_ops.placeholder(dtypes.string, 1, name=\"input-tensor-1\")\n }\n output_tensors = {\n \"output-1\":\n array_ops.placeholder(dtypes.float32, 1, name=\"output-tensor-1\")\n }\n problem_type = constants.ProblemType.LINEAR_REGRESSION\n actual_signature_def = (\n saved_model_export_utils.build_standardized_signature_def(\n input_tensors, output_tensors, problem_type))\n expected_signature_def = meta_graph_pb2.SignatureDef()\n shape = tensor_shape_pb2.TensorShapeProto(\n dim=[tensor_shape_pb2.TensorShapeProto.Dim(size=1)])\n dtype_float = types_pb2.DataType.Value(\"DT_FLOAT\")\n dtype_string = types_pb2.DataType.Value(\"DT_STRING\")\n expected_signature_def.inputs[signature_constants.REGRESS_INPUTS].CopyFrom(\n meta_graph_pb2.TensorInfo(\n name=\"input-tensor-1:0\", dtype=dtype_string, tensor_shape=shape))\n expected_signature_def.outputs[\n signature_constants.REGRESS_OUTPUTS].CopyFrom(\n meta_graph_pb2.TensorInfo(name=\"output-tensor-1:0\",\n dtype=dtype_float,\n tensor_shape=shape))\n\n expected_signature_def.method_name = signature_constants.REGRESS_METHOD_NAME\n self.assertEqual(actual_signature_def, expected_signature_def)\n\n def test_build_standardized_signature_def_classification(self):\n \"\"\"Tests classification with one output tensor.\"\"\"\n input_tensors = {\n \"input-1\":\n array_ops.placeholder(dtypes.string, 1, name=\"input-tensor-1\")\n }\n output_tensors = {\n \"output-1\":\n array_ops.placeholder(dtypes.string, 1, name=\"output-tensor-1\")\n }\n problem_type = constants.ProblemType.CLASSIFICATION\n actual_signature_def = (\n saved_model_export_utils.build_standardized_signature_def(\n input_tensors, output_tensors, problem_type))\n expected_signature_def = meta_graph_pb2.SignatureDef()\n shape = tensor_shape_pb2.TensorShapeProto(\n dim=[tensor_shape_pb2.TensorShapeProto.Dim(size=1)])\n dtype_string = types_pb2.DataType.Value(\"DT_STRING\")\n expected_signature_def.inputs[signature_constants.CLASSIFY_INPUTS].CopyFrom(\n meta_graph_pb2.TensorInfo(\n name=\"input-tensor-1:0\", dtype=dtype_string, tensor_shape=shape))\n expected_signature_def.outputs[\n signature_constants.CLASSIFY_OUTPUT_CLASSES].CopyFrom(\n meta_graph_pb2.TensorInfo(\n name=\"output-tensor-1:0\",\n dtype=dtype_string,\n tensor_shape=shape))\n\n expected_signature_def.method_name = (\n signature_constants.CLASSIFY_METHOD_NAME)\n self.assertEqual(actual_signature_def, expected_signature_def)\n\n def test_build_standardized_signature_def_classification2(self):\n \"\"\"Tests multiple output tensors that include classes and probabilities.\"\"\"\n input_tensors = {\n \"input-1\":\n array_ops.placeholder(dtypes.string, 1, name=\"input-tensor-1\")\n }\n output_tensors = {\n \"classes\":\n array_ops.placeholder(\n dtypes.string, 1, name=\"output-tensor-classes\"),\n # Will be used for CLASSIFY_OUTPUT_SCORES.\n \"probabilities\":\n array_ops.placeholder(\n dtypes.float32, 1, name=\"output-tensor-proba\"),\n \"logits\":\n array_ops.placeholder(\n dtypes.float32, 1, name=\"output-tensor-logits-unused\"),\n }\n problem_type = constants.ProblemType.CLASSIFICATION\n actual_signature_def = (\n saved_model_export_utils.build_standardized_signature_def(\n input_tensors, output_tensors, problem_type))\n expected_signature_def = meta_graph_pb2.SignatureDef()\n shape = tensor_shape_pb2.TensorShapeProto(\n dim=[tensor_shape_pb2.TensorShapeProto.Dim(size=1)])\n dtype_float = types_pb2.DataType.Value(\"DT_FLOAT\")\n dtype_string = types_pb2.DataType.Value(\"DT_STRING\")\n expected_signature_def.inputs[signature_constants.CLASSIFY_INPUTS].CopyFrom(\n meta_graph_pb2.TensorInfo(\n name=\"input-tensor-1:0\", dtype=dtype_string, tensor_shape=shape))\n expected_signature_def.outputs[\n signature_constants.CLASSIFY_OUTPUT_CLASSES].CopyFrom(\n meta_graph_pb2.TensorInfo(\n name=\"output-tensor-classes:0\",\n dtype=dtype_string,\n tensor_shape=shape))\n expected_signature_def.outputs[\n signature_constants.CLASSIFY_OUTPUT_SCORES].CopyFrom(\n meta_graph_pb2.TensorInfo(\n name=\"output-tensor-proba:0\",\n dtype=dtype_float,\n tensor_shape=shape))\n\n expected_signature_def.method_name = (\n signature_constants.CLASSIFY_METHOD_NAME)\n self.assertEqual(actual_signature_def, expected_signature_def)\n\n def test_build_standardized_signature_def_classification3(self):\n \"\"\"Tests multiple output tensors that include classes and scores.\"\"\"\n input_tensors = {\n \"input-1\":\n array_ops.placeholder(dtypes.string, 1, name=\"input-tensor-1\")\n }\n output_tensors = {\n \"classes\":\n array_ops.placeholder(\n dtypes.string, 1, name=\"output-tensor-classes\"),\n \"scores\":\n array_ops.placeholder(\n dtypes.float32, 1, name=\"output-tensor-scores\"),\n \"logits\":\n array_ops.placeholder(\n dtypes.float32, 1, name=\"output-tensor-logits-unused\"),\n }\n problem_type = constants.ProblemType.CLASSIFICATION\n actual_signature_def = (\n saved_model_export_utils.build_standardized_signature_def(\n input_tensors, output_tensors, problem_type))\n expected_signature_def = meta_graph_pb2.SignatureDef()\n shape = tensor_shape_pb2.TensorShapeProto(\n dim=[tensor_shape_pb2.TensorShapeProto.Dim(size=1)])\n dtype_float = types_pb2.DataType.Value(\"DT_FLOAT\")\n dtype_string = types_pb2.DataType.Value(\"DT_STRING\")\n expected_signature_def.inputs[signature_constants.CLASSIFY_INPUTS].CopyFrom(\n meta_graph_pb2.TensorInfo(\n name=\"input-tensor-1:0\", dtype=dtype_string, tensor_shape=shape))\n expected_signature_def.outputs[\n signature_constants.CLASSIFY_OUTPUT_CLASSES].CopyFrom(\n meta_graph_pb2.TensorInfo(\n name=\"output-tensor-classes:0\",\n dtype=dtype_string,\n tensor_shape=shape))\n expected_signature_def.outputs[\n signature_constants.CLASSIFY_OUTPUT_SCORES].CopyFrom(\n meta_graph_pb2.TensorInfo(\n name=\"output-tensor-scores:0\",\n dtype=dtype_float,\n tensor_shape=shape))\n\n expected_signature_def.method_name = (\n signature_constants.CLASSIFY_METHOD_NAME)\n self.assertEqual(actual_signature_def, expected_signature_def)\n\n def test_build_standardized_signature_def_classification4(self):\n \"\"\"Tests classification without classes tensor.\"\"\"\n input_tensors = {\n \"input-1\":\n array_ops.placeholder(dtypes.string, 1, name=\"input-tensor-1\")\n }\n output_tensors = {\n \"probabilities\":\n array_ops.placeholder(\n dtypes.float32, 1, name=\"output-tensor-proba\"),\n \"logits\":\n array_ops.placeholder(\n dtypes.float32, 1, name=\"output-tensor-logits-unused\"),\n }", "answers": [" problem_type = constants.ProblemType.CLASSIFICATION"], "length": 571, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "7cd58649-aa0a-4dd5-8f2b-1577ad2b44ac", "reasoning": "The method test_build_standardized_signature_def_classification4 is defining input_tensors and output_tensors. The next logical step, following the pattern of the previous test methods, is to specify the problem type (CLASSIFICATION) before invoking the utility function. Therefore the next line should assign the problem_type variable to constants.ProblemType.CLASSIFICATION.", "reasoning_model_answer": "problem_type = constants.ProblemType.CLASSIFICATION", "assistant_with_reasoning": "\nThe method test_build_standardized_signature_def_classification4 is defining input_tensors and output_tensors. The next logical step, following the pattern of the previous test methods, is to specify the problem type (CLASSIFICATION) before invoking the utility function. Therefore the next line should assign the problem_type variable to constants.ProblemType.CLASSIFICATION.\n\nproblem_type = constants.ProblemType.CLASSIFICATION", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 2.441, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 10358, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "problem_type = constants.ProblemType.CLASSIFICATION", "score": 0.96, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "# -*- coding: utf-8 -*-\n\n# Copyright (C) 2012 Yahoo! Inc. All Rights Reserved.\n# Copyright (C) 2013 Rackspace Hosting All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nimport collections\nimport copy\nimport errno\nimport functools\nimport keyword\nimport logging\nimport os\nimport string\nimport sys\nimport time\nimport traceback\n\nimport six\n\nfrom taskflow import exceptions as exc\nfrom taskflow.openstack.common import jsonutils\nfrom taskflow.utils import reflection\n\n\nLOG = logging.getLogger(__name__)\nNUMERIC_TYPES = six.integer_types + (float,)\n\n\ndef binary_encode(text, encoding='utf-8'):\n \"\"\"Converts a string of into a binary type using given encoding.\n\n Does nothing if text not unicode string.\n \"\"\"\n if isinstance(text, six.binary_type):\n return text\n elif isinstance(text, six.text_type):\n return text.encode(encoding)\n else:\n raise TypeError(\"Expected binary or string type\")\n\n\ndef binary_decode(data, encoding='utf-8'):\n \"\"\"Converts a binary type into a text type using given encoding.\n\n Does nothing if data is already unicode string.\n \"\"\"\n if isinstance(data, six.binary_type):\n return data.decode(encoding)\n elif isinstance(data, six.text_type):\n return data\n else:\n raise TypeError(\"Expected binary or string type\")\n\n\ndef decode_json(raw_data, root_types=(dict,)):\n \"\"\"Parse raw data to get JSON object.\n\n Decodes a JSON from a given raw data binary and checks that the root\n type of that decoded object is in the allowed set of types (by\n default a JSON object/dict should be the root type).\n \"\"\"\n try:\n data = jsonutils.loads(binary_decode(raw_data))\n except UnicodeDecodeError as e:\n raise ValueError(\"Expected UTF-8 decodable data: %s\" % e)\n except ValueError as e:\n raise ValueError(\"Expected JSON decodable data: %s\" % e)\n if root_types and not isinstance(data, tuple(root_types)):\n ok_types = \", \".join(str(t) for t in root_types)\n raise ValueError(\"Expected (%s) root types not: %s\"\n % (ok_types, type(data)))\n return data\n\n\ndef wallclock():\n # NOTE(harlowja): made into a function so that this can be easily mocked\n # out if we want to alter time related functionality (for testing\n # purposes).\n return time.time()\n\n\ndef wraps(fn):\n \"\"\"This will not be needed in python 3.2 or greater which already has this\n built-in to its functools.wraps method.\n \"\"\"\n\n def wrapper(f):\n f = functools.wraps(fn)(f)\n f.__wrapped__ = getattr(fn, '__wrapped__', fn)\n return f\n\n return wrapper\n\n\ndef get_version_string(obj):\n \"\"\"Gets a object's version as a string.\n\n Returns string representation of object's version taken from\n its 'version' attribute, or None if object does not have such\n attribute or its version is None.\n \"\"\"\n obj_version = getattr(obj, 'version', None)\n if isinstance(obj_version, (list, tuple)):\n obj_version = '.'.join(str(item) for item in obj_version)\n if obj_version is not None and not isinstance(obj_version,\n six.string_types):\n obj_version = str(obj_version)\n return obj_version\n\n\ndef item_from(container, index, name=None):\n \"\"\"Attempts to fetch a index/key from a given container.\"\"\"\n if index is None:\n return container\n try:\n return container[index]\n except (IndexError, KeyError, ValueError, TypeError):\n # NOTE(harlowja): Perhaps the container is a dictionary-like object\n # and that key does not exist (key error), or the container is a\n # tuple/list and a non-numeric key is being requested (index error),\n # or there was no container and an attempt to index into none/other\n # unsubscriptable type is being requested (type error).\n if name is None:\n name = index\n raise exc.NotFound(\"Unable to find %r in container %s\"\n % (name, container))\n\n\ndef get_duplicate_keys(iterable, key=None):\n if key is not None:\n iterable = six.moves.map(key, iterable)\n keys = set()\n duplicates = set()\n for item in iterable:", "answers": [" if item in keys:"], "length": 598, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "0c554d0b-0672-42ea-a995-251e62efec1f", "reasoning": "The function get_duplicate_keys iterates over items to find duplicates. After the 'for item in iterable:' line, the next logical statement checks if the current item has already been seen. Therefore the next line should be an if statement testing membership in the 'keys' set.", "reasoning_model_answer": "if item in keys:", "assistant_with_reasoning": "\nThe function get_duplicate_keys iterates over items to find duplicates. After the 'for item in iterable:' line, the next logical statement checks if the current item has already been seen. Therefore the next line should be an if statement testing membership in the 'keys' set.\n\nif item in keys:", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 2.795, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 4828, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "if item in keys:", "score": 0.8, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "using UnityEngine;\nusing System.Collections.Generic;\n\n[AddComponentMenu(\"Strategy/Trade Route\")]\npublic class TradeRoute : MonoBehaviour\n{\n\t[System.Serializable]\n\tpublic class Item\n\t{\n\t\tpublic int \tid \t= 0;\t// Resource's ID\n\t\tpublic Town town \t= null;\t// Town that owns this resource\n\t}\n\t\n\tstatic public List list = new List();\n\tstatic public float globalAlpha = 1f;\n\t\n\t// The two connected towns\n\tpublic Town town0 = null;\n\tpublic Town town1 = null;\n\t\n\t// Controls whether this trade route is visible\n\tpublic float targetAlpha = 1.0f;\n\t\n\t// Texture used to draw the path\n\tpublic Texture2D texture = null;\n\t\n\t// Shared material\n\tprivate static Material mMat = null;\n\t\n\t// Spline created with the points above\n\tprivate SplineV \t\tmOriginal\t \t= new SplineV();\n\tprivate SplineV\t\t\tmNormalized\t\t= new SplineV();\n\tprivate bool \t\t\tmRebuild \t\t= false;\n\tprivate Mesh \t\t\tmMesh \t\t\t= null;\n\tprivate MeshFilter\t\tmFilter\t\t\t= null;\n\tprivate MeshRenderer\tmRen\t\t\t= null;\n\tprivate float\t\t\tmAlpha\t\t\t= 0f;\n\tprivate float\t\t\tmLength\t\t\t= 0f;\n\tprivate Vector3\t\t\tmTooltipPos;\n\t\n\t/// \n\t/// List of traded items\n\t/// \n\n\tpublic List items = new List();\n\t\n\t/// \n\t/// List of all ships assigned to this trade route\n\t/// \n\n\tpublic List ships = new List();\n\t\n\t/// \n\t/// Read-only access to connected towns\n\t/// \n\n\tpublic SplineV path { get { return mOriginal; } }\n\t\n\t/// \n\t/// Gets the normalized spline path.\n\t/// \n\t\n\tpublic SplineV normalizedPath { get { return mNormalized; } }\n\t\n\t/// \n\t/// Gets a value indicating whether this is valid.\n\t/// \n\t\n\tpublic bool isValid { get { return (town0 != null) && (town1 != null); } }\n\t\n\t/// \n\t/// Gets the length of the trade route.\n\t/// \n\t\n\tpublic float length { get { return isValid ? mLength : 0f; } }\n\t\n\t/// \n\t/// Sample the trade route spline at the specified time.\n\t/// \n\t\n\tpublic Vector3 Sample (float time) { return mOriginal.Sample(time, SplineV.SampleType.Spline); }\n\t\n\t/// \n\t/// Connect the specified town.\n\t/// \n\t\n\tpublic bool Connect (Town town)\n\t{\n\t\tif (town0 == null)\n\t\t{\n\t\t\ttown0 = town;\n\t\t\tAdd(town.anchor);\n\t\t}\n\t\telse if (town1 == null && town0 != town)\n\t\t{\n\t\t\tAdd(town.anchor);\n\t\t\ttown1 = town;\n\t\t}\n\t\treturn (town1 != null);\n\t}\n\t\n\t/// \n\t/// Adds a new point to the trade route.\n\t/// \n\t\n\tpublic void Add (Vector3 v)\n\t{\n\t\tif (town0 != null && town1 == null)\n\t\t{\n\t\t\tv.y = 0.05f;\n\t\t\t\n\t\t\tif (mOriginal.isValid)\n\t\t\t{\n\t\t\t\tmOriginal.AddKey(mOriginal.endTime + (v - mOriginal.end).magnitude, v);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tmOriginal.AddKey(0.0f, v);\n\t\t\t}\n\t\t\tmRebuild = true;\n\t\t}\n\t}\n\t\n\t/// \n\t/// Removes the last added trade route point.\n\t/// \n\t\n\tpublic bool UndoAdd()\n\t{\n\t\tif (mOriginal.isValid)\n\t\t{\n\t\t\tmOriginal.list.RemoveAt(mOriginal.list.Count - 1);\n\t\t\tmRebuild = true;\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\t\n\t/// \n\t/// Copies the trade route path from the specified trade route.\n\t/// \n\t\n\tpublic void CopyPath (SplineV sp)\n\t{\n\t\tmRebuild = true;\n\t\tmOriginal.Clear();\n\t\tforeach (SplineV.CtrlPoint cp in sp.list) mOriginal.AddKey(cp.mTime, cp.mVal);\n\t}\n\t\n\t/// \n\t/// Returns the town connected to the specified town if it's in this trade route.\n\t/// \n\t\n\tpublic Town GetConnectedTown (Town town)\n\t{\n\t\tif (town0 == town) return town1;\n\t\tif (town1 == town) return town0;\n\t\treturn null;\n\t}\n\t\n\t/// \n\t/// Gets the traded resource's owner, or null if it's not being traded.\n\t/// \n\t\n\tpublic Town GetExportedResourceOwner (int id)\n\t{\n\t\tforeach (Item item in items)\n\t\t{\n\t\t\tif (item.id == id)\n\t\t\t{\n\t\t\t\treturn item.town;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\t\n\t/// \n\t/// Sets the specified town's resource as being traded via the trade route.\n\t/// \n\t\n\tpublic void SetExportedResource (Town owner, int id)\n\t{\n\t\tforeach (Item item in items)\n\t\t{\n\t\t\tif (item.id == id)\n\t\t\t{\n\t\t\t\tif (owner == null)\n\t\t\t\t{\n\t\t\t\t\titems.Remove(item);\n\t\t\t\t\titem.town.resources[id].beingTraded = false;\n\t\t\t\t}\n\t\t\t\telse item.town = owner;\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\t\n\t\tif (owner != null)\n\t\t{\n\t\t\tItem item = new Item();\n\t\t\titem.town = owner;\n\t\t\titem.id = id;\n\t\t\titems.Add(item);\n\t\t\towner.resources[id].beingTraded = true;\n\t\t}\n\t}\n\t\n\t/// \n\t/// Assigns the specified ship to this trade route.\n\t/// ", "answers": ["\tpublic void AssignShip (AvailableShips.Owned ship)"], "length": 641, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "711404df-e60f-4f63-9cc8-05dc8431342f", "reasoning": "After the XML comment describing the method that assigns a ship to the trade route, the code will define the method signature. The class has a List called ships, so the method should accept an AvailableShips.Owned parameter and likely return void. Following the style of previous methods, the signature is placed on its own line before the opening brace.", "reasoning_model_answer": "public void AssignShip (AvailableShips.Owned ship)", "assistant_with_reasoning": "\nAfter the XML comment describing the method that assigns a ship to the trade route, the code will define the method signature. The class has a List called ships, so the method should accept an AvailableShips.Owned parameter and likely return void. Following the style of previous methods, the signature is placed on its own line before the opening brace.\n\npublic void AssignShip (AvailableShips.Owned ship)", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.514, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 4536, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "public void AssignShip (AvailableShips.Owned ship)", "score": 0.99, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "package com.smithyproductions.animatedimageview;\n\nimport android.graphics.Bitmap;\nimport android.graphics.Bitmap.Config;\n\nimport java.io.InputStream;\nimport java.util.Vector;\n\npublic class GifDecoder\n{\n\t/**\n\t * File read status: No errors.\n\t */\n\tpublic static final int STATUS_OK = 0;\n\t/**\n\t * File read status: Error decoding file (may be partially decoded)\n\t */\n\tpublic static final int STATUS_FORMAT_ERROR = 1;\n\t/**\n\t * File read status: Unable to open source.\n\t */\n\tpublic static final int STATUS_OPEN_ERROR = 2;\n\t/** max decoder pixel stack size */\n\tprotected static final int MAX_STACK_SIZE = 4096;\n\tpublic static final int MIN_DELAY = 100;\n\tpublic static final int MIN_DELAY_ENFORCE_THRESHOLD = 20;\n\tprotected InputStream in;\n\tprotected int status;\n\tprotected int width; // full image width\n\tprotected int height; // full image height\n\tprotected boolean gctFlag; // global color table used\n\tprotected int gctSize; // size of global color table\n\tprotected int loopCount = 1; // iterations; 0 = repeat forever\n\tprotected int[] gct; // global color table\n\tprotected int[] lct; // local color table\n\tprotected int[] act; // active color table\n\tprotected int bgIndex; // background color index\n\tprotected int bgColor; // background color\n\tprotected int lastBgColor; // previous bg color\n\tprotected int pixelAspect; // pixel aspect ratio\n\tprotected boolean lctFlag; // local color table flag\n\tprotected boolean interlace; // interlace flag\n\tprotected int lctSize; // local color table size\n\tprotected int ix, iy, iw, ih; // current image rectangle\n\tprotected int lrx, lry, lrw, lrh;\n\tprotected Bitmap image; // current frame\n\tprotected Bitmap lastBitmap; // previous frame\n\tprotected byte[] block = new byte[256]; // current data block\n\tprotected int blockSize = 0; // block size last graphic control extension info\n\tprotected int dispose = 0; // 0=no action; 1=leave in place; 2=restore to bg; 3=restore to prev\n\tprotected int lastDispose = 0;\n\tprotected boolean transparency = false; // use transparent color\n\tprotected int delay = 0; // delay in milliseconds\n\tprotected int transIndex; // transparent color index\n\t// LZW decoder working arrays\n\tprotected short[] prefix;\n\tprotected byte[] suffix;\n\tprotected byte[] pixelStack;\n\tprotected byte[] pixels;\n\tprotected Vector frames; // frames read from current file\n\tprotected int frameCount;\n\n\tprivate boolean readComplete;\n\n\tpublic GifDecoder()\n\t{\n\t\treadComplete = false;\n\t}\n\n\tprivate static class GifFrame {\n\t\tpublic GifFrame(Bitmap im, int del) {\n\t\t\timage = im;\n\t\t\tdelay = del;\n\t\t}\n\n\t\tpublic Bitmap image;\n\t\tpublic int delay;\n\t}\n\n\t/**\n\t * Gets display duration for specified frame.\n\t *\n\t * @param n\n\t * int index of frame\n\t * @return delay in milliseconds\n\t */\n\tpublic int getDelay(int n) {\n\t\tdelay = -1;\n\t\tif ((n >= 0) && (n < frameCount)) {\n\t\t\tdelay = frames.elementAt(n).delay;\n\t\t\t//meets browser compatibility standards\n\t\t\tif (delay < MIN_DELAY_ENFORCE_THRESHOLD) delay = MIN_DELAY;\n\t\t}\n\t\treturn delay;\n\t}\n\n\t/**\n\t * Gets the number of frames read from file.\n\t *\n\t * @return frame count\n\t */\n\tpublic int getFrameCount() {\n\t\treturn frameCount;\n\t}\n\n\t/**\n\t * Gets the first (or only) image read.\n\t *\n\t * @return BufferedBitmap containing first frame, or null if none.\n\t */\n\tpublic Bitmap getBitmap() {\n\t\treturn getFrame(0);\n\t}\n\n\t/**\n\t * Gets the \"Netscape\" iteration count, if any. A count of 0 means repeat indefinitiely.\n\t *\n\t * @return iteration count if one was specified, else 1.\n\t */\n\tpublic int getLoopCount() {\n\t\treturn loopCount;\n\t}\n\n\t/**\n\t * Creates new frame image from current data (and previous frames as specified by their disposition codes).\n\t */\n\tprotected void setPixels() {\n\t\t// expose destination image's pixels as int array\n\t\tint[] dest = new int[width * height];\n\t\t// fill in starting image contents based on last image's dispose code", "answers": ["\t\tif (lastDispose > 0) {"], "length": 573, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "e99926c2-6ab9-47a4-9f8f-e975f15a6da9", "reasoning": "In setPixels(), after allocating the destination pixel array, the code must initialize it according to the disposal method of the previous frame. The comment indicates this step, so the next line starts the conditional handling of the lastDispose code, typically checking for the 'restore to background' case (value 2). Hence the next line is the opening of that if‑statement.", "reasoning_model_answer": "if (lastDispose == 2) {", "assistant_with_reasoning": "\nIn setPixels(), after allocating the destination pixel array, the code must initialize it according to the disposal method of the previous frame. The comment indicates this step, so the next line starts the conditional handling of the lastDispose code, typically checking for the 'restore to background' case (value 2). Hence the next line is the opening of that if‑statement.\n\nif (lastDispose == 2) {", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 5.449, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 3945, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "if (lastDispose == 2) {", "score": 0.85, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "// Licensed to the .NET Foundation under one or more agreements.\n// See the LICENSE file in the project root for more information.\n//\n// System.Drawing.Drawing2D.GraphicsPath.cs\n//\n// Authors:\n//\n// Miguel de Icaza (miguel@ximian.com)\n// Duncan Mak (duncan@ximian.com)\n// Jordi Mas i Hernandez (jordi@ximian.com)\n// Ravindra (rkumar@novell.com)\n// Sebastien Pouliot \n//\n// Copyright (C) 2004,2006-2007 Novell, Inc (http://www.novell.com)\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n// \n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n// \n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System.ComponentModel;\nusing System.Runtime.InteropServices;\nusing Gdip = System.Drawing.SafeNativeMethods.Gdip;\n\nnamespace System.Drawing.Drawing2D\n{\n public sealed class GraphicsPath : MarshalByRefObject, ICloneable, IDisposable\n {\n // 1/4 is the FlatnessDefault as defined in GdiPlusEnums.h\n private const float FlatnessDefault = 1.0f / 4.0f;\n\n internal IntPtr _nativePath = IntPtr.Zero;\n\n GraphicsPath(IntPtr ptr)\n {\n _nativePath = ptr;\n }\n\n public GraphicsPath()\n {\n int status = Gdip.GdipCreatePath(FillMode.Alternate, out _nativePath);\n Gdip.CheckStatus(status);\n }\n\n public GraphicsPath(FillMode fillMode)\n {\n int status = Gdip.GdipCreatePath(fillMode, out _nativePath);\n Gdip.CheckStatus(status);\n }\n\n public GraphicsPath(Point[] pts, byte[] types)\n : this(pts, types, FillMode.Alternate)\n {\n }\n\n public GraphicsPath(PointF[] pts, byte[] types)\n : this(pts, types, FillMode.Alternate)\n {\n }\n\n public GraphicsPath(Point[] pts, byte[] types, FillMode fillMode)\n {\n if (pts == null)\n throw new ArgumentNullException(nameof(pts));\n if (pts.Length != types.Length)\n throw new ArgumentException(\"Invalid parameter passed. Number of points and types must be same.\");\n\n int status = Gdip.GdipCreatePath2I(pts, types, pts.Length, fillMode, out _nativePath);\n Gdip.CheckStatus(status);\n }\n\n public GraphicsPath(PointF[] pts, byte[] types, FillMode fillMode)\n {\n if (pts == null)\n throw new ArgumentNullException(nameof(pts));\n if (pts.Length != types.Length)\n throw new ArgumentException(\"Invalid parameter passed. Number of points and types must be same.\");\n\n int status = Gdip.GdipCreatePath2(pts, types, pts.Length, fillMode, out _nativePath);\n Gdip.CheckStatus(status);\n }\n\n public object Clone()\n {\n IntPtr clone;\n\n int status = Gdip.GdipClonePath(_nativePath, out clone);\n Gdip.CheckStatus(status);\n\n return new GraphicsPath(clone);\n }\n\n public void Dispose()\n {\n Dispose(true);\n System.GC.SuppressFinalize(this);\n }\n\n ~GraphicsPath()\n {\n Dispose(false);\n }\n\n void Dispose(bool disposing)\n {\n int status;\n if (_nativePath != IntPtr.Zero)\n {\n status = Gdip.GdipDeletePath(new HandleRef(this, _nativePath));\n Gdip.CheckStatus(status);\n\n _nativePath = IntPtr.Zero;\n }\n }\n\n public FillMode FillMode\n {\n get\n {\n FillMode mode;\n int status = Gdip.GdipGetPathFillMode(_nativePath, out mode);\n Gdip.CheckStatus(status);\n\n return mode;\n }\n set\n {\n if ((value < FillMode.Alternate) || (value > FillMode.Winding))\n throw new InvalidEnumArgumentException(\"FillMode\", (int)value, typeof(FillMode));\n\n int status = Gdip.GdipSetPathFillMode(_nativePath, value);\n Gdip.CheckStatus(status);\n }\n }\n\n public PathData PathData\n {\n get\n {\n int count;\n int status = Gdip.GdipGetPointCount(_nativePath, out count);\n Gdip.CheckStatus(status);\n\n PointF[] points = new PointF[count];\n byte[] types = new byte[count];\n\n // status would fail if we ask points or types with a 0 count\n // anyway that would only mean two unrequired unmanaged calls\n if (count > 0)\n {\n status = Gdip.GdipGetPathPoints(_nativePath, points, count);\n Gdip.CheckStatus(status);\n\n status = Gdip.GdipGetPathTypes(_nativePath, types, count);\n Gdip.CheckStatus(status);\n }\n\n PathData pdata = new PathData();\n pdata.Points = points;\n pdata.Types = types;\n return pdata;\n }\n }\n\n public PointF[] PathPoints\n {\n get\n {\n int count;\n int status = Gdip.GdipGetPointCount(_nativePath, out count);\n Gdip.CheckStatus(status);\n if (count == 0)\n throw new ArgumentException(\"PathPoints\");\n\n PointF[] points = new PointF[count];\n status = Gdip.GdipGetPathPoints(_nativePath, points, count);\n Gdip.CheckStatus(status);\n\n return points;\n }\n }\n\n public byte[] PathTypes\n {\n get\n {\n int count;\n int status = Gdip.GdipGetPointCount(_nativePath, out count);\n Gdip.CheckStatus(status);\n if (count == 0)", "answers": [" throw new ArgumentException(\"PathTypes\");"], "length": 656, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "ac06aa90-279c-4335-950a-41d2a6ed3def", "reasoning": "The getter for PathTypes mirrors the PathPoints getter. After checking the point count, if count is zero they throw an ArgumentException with the property name. The previous getter used `throw new ArgumentException(\"PathPoints\");`, so here it should be `throw new ArgumentException(\"PathTypes\");` as the next line.", "reasoning_model_answer": "throw new ArgumentException(\"PathTypes\");", "assistant_with_reasoning": "\nThe getter for PathTypes mirrors the PathPoints getter. After checking the point count, if count is zero they throw an ArgumentException with the property name. The previous getter used `throw new ArgumentException(\"PathPoints\");`, so here it should be `throw new ArgumentException(\"PathTypes\");` as the next line.\n\nthrow new ArgumentException(\"PathTypes\");", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.944, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 6874, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "throw new ArgumentException(\"PathTypes\");", "score": 0.8, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "using EIDSS.Reports.Parameterized.Human.AJ.DataSets;\nusing EIDSS.Reports.Parameterized.Human.AJ.DataSets.AssignmentLabDiagnosticDataSetTableAdapters;\n\nusing EIDSS.Reports.Parameterized.Human.GG.DataSet;\nusing EIDSS.Reports.Parameterized.Human.GG.Report;\n\nnamespace EIDSS.Reports.Parameterized.Human.AJ.Reports\n{\n partial class AssignmentLabDiagnosticReportNew\n {\n \n #region Designer generated code\n\n /// \n /// Required method for Designer support - do not modify\n /// the contents of this method with the code editor.\n /// \n private void InitializeComponent()\n {\n System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(AssignmentLabDiagnosticReportNew));\n this.DetailReport = new DevExpress.XtraReports.UI.DetailReportBand();\n this.Detail1 = new DevExpress.XtraReports.UI.DetailBand();\n this.ReportDetailTable = new DevExpress.XtraReports.UI.XRTable();\n this.xrTableRow9 = new DevExpress.XtraReports.UI.XRTableRow();\n this.xrTableCell28 = new DevExpress.XtraReports.UI.XRTableCell();\n this.SampleTypeCell = new DevExpress.XtraReports.UI.XRTableCell();\n this.SampleIDCell = new DevExpress.XtraReports.UI.XRTableCell();\n this.SampleCollectionDateCell = new DevExpress.XtraReports.UI.XRTableCell();\n this.SampleSentDateCell = new DevExpress.XtraReports.UI.XRTableCell();\n this.ReportHeader1 = new DevExpress.XtraReports.UI.ReportHeaderBand();\n this.ReportDetailHeaderTable = new DevExpress.XtraReports.UI.XRTable();\n this.xrTableRow15 = new DevExpress.XtraReports.UI.XRTableRow();\n this.xrTableCell1 = new DevExpress.XtraReports.UI.XRTableCell();\n this.xrTableCell33 = new DevExpress.XtraReports.UI.XRTableCell();\n this.xrTableCell34 = new DevExpress.XtraReports.UI.XRTableCell();\n this.xrTableCell16 = new DevExpress.XtraReports.UI.XRTableCell();\n this.xrTableCell11 = new DevExpress.XtraReports.UI.XRTableCell();\n this.SecondReportHeaderTable = new DevExpress.XtraReports.UI.XRTable();\n this.xrTableRow10 = new DevExpress.XtraReports.UI.XRTableRow();\n this.xrTableCell14 = new DevExpress.XtraReports.UI.XRTableCell();\n this.HeaderPatientNameCell = new DevExpress.XtraReports.UI.XRTableCell();\n this.xrTableCell15 = new DevExpress.XtraReports.UI.XRTableCell();\n this.HeaderSexCell = new DevExpress.XtraReports.UI.XRTableCell();\n this.xrTableRow11 = new DevExpress.XtraReports.UI.XRTableRow();\n this.xrTableCell21 = new DevExpress.XtraReports.UI.XRTableCell();\n this.HeaderDOBCell = new DevExpress.XtraReports.UI.XRTableCell();\n this.xrTableCell23 = new DevExpress.XtraReports.UI.XRTableCell();\n this.HeaderAgeCell = new DevExpress.XtraReports.UI.XRTableCell();\n this.xrTableRow13 = new DevExpress.XtraReports.UI.XRTableRow();\n this.xrTableCell25 = new DevExpress.XtraReports.UI.XRTableCell();\n this.HeaderAddressCell = new DevExpress.XtraReports.UI.XRTableCell();\n this.xrTableRow14 = new DevExpress.XtraReports.UI.XRTableRow();\n this.xrTableCell27 = new DevExpress.XtraReports.UI.XRTableCell();\n this.HeaderDiagnosisCell = new DevExpress.XtraReports.UI.XRTableCell();\n this.ReportHeaderTable = new DevExpress.XtraReports.UI.XRTable();\n this.xrTableRow1 = new DevExpress.XtraReports.UI.XRTableRow();\n this.xrTableCell333 = new DevExpress.XtraReports.UI.XRTableCell();\n this.xrTableCell3 = new DevExpress.XtraReports.UI.XRTableCell();\n this.xrTableRow4 = new DevExpress.XtraReports.UI.XRTableRow();\n this.xrTableCell5 = new DevExpress.XtraReports.UI.XRTableCell();\n this.xrTableCell6 = new DevExpress.XtraReports.UI.XRTableCell();\n this.xrTableRow2 = new DevExpress.XtraReports.UI.XRTableRow();\n this.HeaderCaseIDBarcodeCell = new DevExpress.XtraReports.UI.XRTableCell();\n this.xrTableCell4 = new DevExpress.XtraReports.UI.XRTableCell();\n this.xrTableRow3 = new DevExpress.XtraReports.UI.XRTableRow();\n this.HeaderCaseIDCell = new DevExpress.XtraReports.UI.XRTableCell();\n this.xrTableCell2 = new DevExpress.XtraReports.UI.XRTableCell();\n this.xrTableRow5 = new DevExpress.XtraReports.UI.XRTableRow();\n this.xrTableCell7 = new DevExpress.XtraReports.UI.XRTableCell();\n this.xrTableCell8 = new DevExpress.XtraReports.UI.XRTableCell();\n this.xrTableRow8 = new DevExpress.XtraReports.UI.XRTableRow();\n this.xrTableCell9 = new DevExpress.XtraReports.UI.XRTableCell();\n this.xrTableRow18 = new DevExpress.XtraReports.UI.XRTableRow();\n this.xrTableCell17 = new DevExpress.XtraReports.UI.XRTableCell();\n this.xrTableCell131 = new DevExpress.XtraReports.UI.XRTableCell();\n this.xrTableRow61 = new DevExpress.XtraReports.UI.XRTableRow();\n this.xrTableCell12 = new DevExpress.XtraReports.UI.XRTableCell();\n this.xrTableCell221 = new DevExpress.XtraReports.UI.XRTableCell();\n this.xrTableRow71 = new DevExpress.XtraReports.UI.XRTableRow();\n this.xrTableCell24 = new DevExpress.XtraReports.UI.XRTableCell();\n this.xrTableCell261 = new DevExpress.XtraReports.UI.XRTableCell();\n this.ReportFooter = new DevExpress.XtraReports.UI.ReportFooterBand();\n this.xrTable1 = new DevExpress.XtraReports.UI.XRTable();\n this.xrTableRow6 = new DevExpress.XtraReports.UI.XRTableRow();\n this.xrTableCell10 = new DevExpress.XtraReports.UI.XRTableCell();\n this.xrTableCell18 = new DevExpress.XtraReports.UI.XRTableCell();\n this.xrTableRow7 = new DevExpress.XtraReports.UI.XRTableRow();\n this.xrTableCell19 = new DevExpress.XtraReports.UI.XRTableCell();\n this.xrTableCell20 = new DevExpress.XtraReports.UI.XRTableCell();\n this.m_Adapter = new EIDSS.Reports.Parameterized.Human.AJ.DataSets.AssignmentLabDiagnosticDataSetTableAdapters.AssignmentDiagnosticAdapter();\n this.m_DataSet = new EIDSS.Reports.Parameterized.Human.AJ.DataSets.AssignmentLabDiagnosticDataSet();\n ((System.ComponentModel.ISupportInitialize)(this.m_BaseDataSet)).BeginInit();\n ((System.ComponentModel.ISupportInitialize)(this.tableBaseHeader)).BeginInit();\n ((System.ComponentModel.ISupportInitialize)(this.ReportDetailTable)).BeginInit();\n ((System.ComponentModel.ISupportInitialize)(this.ReportDetailHeaderTable)).BeginInit();\n ((System.ComponentModel.ISupportInitialize)(this.SecondReportHeaderTable)).BeginInit();\n ((System.ComponentModel.ISupportInitialize)(this.ReportHeaderTable)).BeginInit();\n ((System.ComponentModel.ISupportInitialize)(this.xrTable1)).BeginInit();\n ((System.ComponentModel.ISupportInitialize)(this.m_DataSet)).BeginInit();\n ((System.ComponentModel.ISupportInitialize)(this)).BeginInit();\n // \n // cellLanguage\n // \n this.cellLanguage.StylePriority.UseTextAlignment = false;\n // \n // lblReportName\n // \n resources.ApplyResources(this.lblReportName, \"lblReportName\");\n this.lblReportName.Multiline = true;\n this.lblReportName.StylePriority.UseBorders = false;\n this.lblReportName.StylePriority.UseBorderWidth = false;\n this.lblReportName.StylePriority.UseFont = false;\n this.lblReportName.StylePriority.UseTextAlignment = false;\n // \n // Detail\n // \n this.Detail.Expanded = false;\n this.Detail.StylePriority.UseFont = false;\n this.Detail.StylePriority.UsePadding = false;\n // \n // PageHeader\n // \n resources.ApplyResources(this.PageHeader, \"PageHeader\");\n this.PageHeader.StylePriority.UseFont = false;\n this.PageHeader.StylePriority.UsePadding = false;\n this.PageHeader.StylePriority.UseTextAlignment = false;\n // \n // PageFooter\n // \n this.PageFooter.StylePriority.UseBorders = false;\n resources.ApplyResources(this.PageFooter, \"PageFooter\");\n // \n // ReportHeader\n // \n resources.ApplyResources(this.ReportHeader, \"ReportHeader\");\n this.ReportHeader.StylePriority.UseFont = false;\n // \n // xrPageInfo1\n // \n resources.ApplyResources(this.xrPageInfo1, \"xrPageInfo1\");\n this.xrPageInfo1.StylePriority.UseBorders = false;\n // \n // cellReportHeader\n // \n this.cellReportHeader.StylePriority.UseBorders = false;\n this.cellReportHeader.StylePriority.UseFont = false;\n this.cellReportHeader.StylePriority.UseTextAlignment = false;\n // \n // cellBaseSite\n // \n this.cellBaseSite.StylePriority.UseBorders = false;\n this.cellBaseSite.StylePriority.UseFont = false;\n this.cellBaseSite.StylePriority.UseTextAlignment = false;\n // \n // tableBaseHeader\n // \n resources.ApplyResources(this.tableBaseHeader, \"tableBaseHeader\");\n this.tableBaseHeader.StylePriority.UseBorders = false;\n this.tableBaseHeader.StylePriority.UseBorderWidth = false;\n this.tableBaseHeader.StylePriority.UseFont = false;\n this.tableBaseHeader.StylePriority.UsePadding = false;\n this.tableBaseHeader.StylePriority.UseTextAlignment = false;\n // \n // DetailReport\n // \n this.DetailReport.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] {\n this.Detail1,\n this.ReportHeader1,\n this.ReportFooter});\n this.DetailReport.DataAdapter = this.m_Adapter;\n this.DetailReport.DataMember = \"AssignmentDiagnostic\";\n this.DetailReport.DataSource = this.m_DataSet;\n this.DetailReport.Level = 0;\n this.DetailReport.Name = \"DetailReport\";\n this.DetailReport.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 2, 2, 100F);\n // \n // Detail1\n // \n this.Detail1.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {\n this.ReportDetailTable});\n resources.ApplyResources(this.Detail1, \"Detail1\");\n this.Detail1.Name = \"Detail1\";\n // \n // ReportDetailTable\n // \n this.ReportDetailTable.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Right) \n | DevExpress.XtraPrinting.BorderSide.Bottom)));\n resources.ApplyResources(this.ReportDetailTable, \"ReportDetailTable\");\n this.ReportDetailTable.Name = \"ReportDetailTable\";\n this.ReportDetailTable.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] {\n this.xrTableRow9});\n this.ReportDetailTable.StylePriority.UseBorders = false;\n this.ReportDetailTable.StylePriority.UseFont = false;\n // \n // xrTableRow9\n // \n this.xrTableRow9.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {\n this.xrTableCell28,\n this.SampleTypeCell,\n this.SampleIDCell,\n this.SampleCollectionDateCell,\n this.SampleSentDateCell});\n this.xrTableRow9.Name = \"xrTableRow9\";\n resources.ApplyResources(this.xrTableRow9, \"xrTableRow9\");\n // \n // xrTableCell28\n // \n this.xrTableCell28.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {\n new DevExpress.XtraReports.UI.XRBinding(\"Text\", null, \"AssignmentDiagnostic.strTestForDisease\")});\n this.xrTableCell28.Name = \"xrTableCell28\";\n resources.ApplyResources(this.xrTableCell28, \"xrTableCell28\");\n // \n // SampleTypeCell\n // \n this.SampleTypeCell.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {\n new DevExpress.XtraReports.UI.XRBinding(\"Text\", null, \"AssignmentDiagnostic.strSampleType\")});\n this.SampleTypeCell.Name = \"SampleTypeCell\";\n resources.ApplyResources(this.SampleTypeCell, \"SampleTypeCell\");\n // \n // SampleIDCell\n // \n this.SampleIDCell.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {\n new DevExpress.XtraReports.UI.XRBinding(\"Text\", null, \"AssignmentDiagnostic.strSampleId\")});\n this.SampleIDCell.Name = \"SampleIDCell\";\n resources.ApplyResources(this.SampleIDCell, \"SampleIDCell\");\n // \n // SampleCollectionDateCell\n // \n this.SampleCollectionDateCell.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {\n new DevExpress.XtraReports.UI.XRBinding(\"Text\", null, \"AssignmentDiagnostic.datSampleCollectedDate\", \"{0:dd/MM/yyyy}\")});\n this.SampleCollectionDateCell.Name = \"SampleCollectionDateCell\";\n resources.ApplyResources(this.SampleCollectionDateCell, \"SampleCollectionDateCell\");\n // \n // SampleSentDateCell\n // \n this.SampleSentDateCell.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {\n new DevExpress.XtraReports.UI.XRBinding(\"Text\", null, \"AssignmentDiagnostic.datSampleSentDate\", \"{0:dd/MM/yyyy}\")});\n this.SampleSentDateCell.Name = \"SampleSentDateCell\";\n resources.ApplyResources(this.SampleSentDateCell, \"SampleSentDateCell\");\n // \n // ReportHeader1\n // \n this.ReportHeader1.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {\n this.ReportDetailHeaderTable,\n this.SecondReportHeaderTable,\n this.ReportHeaderTable});", "answers": [" resources.ApplyResources(this.ReportHeader1, \"ReportHeader1\");"], "length": 661, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "b8073fb4-c412-438c-85f8-7a832d485f5c", "reasoning": "The code is part of the InitializeComponent method generated by the DevExpress designer. After adding controls to a band (ReportHeader1), the next typical statements are to apply localized resources and set the band’s name. Following the pattern used earlier for other components (e.g., DetailReport), the next line should be the resource application for ReportHeader1.", "reasoning_model_answer": "resources.ApplyResources(this.ReportHeader1, \"ReportHeader1\");", "assistant_with_reasoning": "\nThe code is part of the InitializeComponent method generated by the DevExpress designer. After adding controls to a band (ReportHeader1), the next typical statements are to apply localized resources and set the band’s name. Following the pattern used earlier for other components (e.g., DetailReport), the next line should be the resource application for ReportHeader1.\n\nresources.ApplyResources(this.ReportHeader1, \"ReportHeader1\");", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.96, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 14517, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "resources.ApplyResources(this.ReportHeader1, \"ReportHeader1\");", "score": 0.91, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "from xformmanager.util import *\n# unfortunately, have to do something like this because of semi-circular dependencies\nimport xformmanager as xfm\nfrom lxml import etree\nimport logging\n\nXPATH_SEPARATOR = \"/\"\n\nclass ElementDef(object):\n \"\"\" Stores metadata about simple and complex types \"\"\"\n \n def __init__(self, name='', is_repeatable=False):\n self.name = name\n self.xpath = ''\n self.child_elements = []\n self.type = ''\n self.is_repeatable = is_repeatable\n #self.attributes - not supported yet\n # this var is a device for getting diffs between defs\n self._visited = False\n \n def __unicode__(self):\n return unicode(self.xpath)\n \n def __str__(self):\n return unicode(self).encode('utf-8')\n \n @property\n def short_name(self):\n \"\"\" This is the unqualified tag of the element\n (without qualifying namespace or xpath) \"\"\"\n c = unicode(self.xpath).rsplit(XPATH_SEPARATOR, 1)\n if len(c)==2:\n return c[1]\n return c[0]\n \n def to_str(self, depth=0, string=''):\n \"\"\" Dumps the entire contents of this to a string \"\"\"\n indent = ' '*depth\n string = indent + \"xpath=\" + str(self.xpath) + \"\\n\"\n string = string + indent + \\\n \"name=\" + str(self.name) + \\\n \", type=\" + str(self.type) + \\\n \", repeatable=\" + str(self.is_repeatable) + \"\\n\"\n for child in self.child_elements:\n string = string + child.to_str(depth+1, string)\n return string\n\n def isValid(self): # to do: place restriction functions in here\n pass\n\n def addChild(self, element_def):\n self.child_elements.append(element_def)\n\n def populateElementFields(self, input_node, xpath, full_name):\n if not self.name: self.name = full_name\n self.type = input_node.get('type')\n if xpath: \n self.xpath = xpath + XPATH_SEPARATOR + input_node.get('name')\n else: \n self.xpath = input_node.get('name')\n \n def find_child(self, child):\n \"\"\" Looks for child among child_elements of self.\n Equivalence is currently based on short_name. \"\"\"\n for candidate in self.child_elements:\n if candidate.short_name == child.short_name:\n return candidate\n return None\n \n def _clear_visited(self):\n \"\"\" _visited is a device for getting diffs between defs \"\"\"\n for child in self.child_elements:\n child._visited = False\n child._clear_visited()\n\n def _get_unvisited(self, root=None):\n \"\"\" _visited is a device for getting diffs between defs \"\"\"\n d = []\n if root is None:\n # hm, I guess you can't pass 'self' as a default argument...\n root = self\n for child in root.child_elements:\n if not child._visited:\n d.append( child )\n d = d + self._get_unvisited(child)\n return d\n\n def _get_elementdef_diff(self, otherdef):\n \"\"\" Determines whether two elementdef leaves are equivalent\n (but does not check for children equivalency) We can always \n extend this later to provide richer diff information \"\"\"\n d = Differences()\n if self.name != otherdef.name or \\\n self.xpath != otherdef.xpath or \\\n self.type != otherdef.type or \\\n self.is_repeatable != otherdef.is_repeatable:\n d.fields_changed.append( otherdef )\n otherdef._visited = True\n return d\n \n def _get_children_diff(self, otherdef):\n d = Differences()\n for child in self.child_elements:\n # find matching child in otherdef\n # assumption: the schemas provided are well-formed\n # and do not contain duplicate children\n otherchild = otherdef.find_child( child )\n if not otherchild:\n d.fields_removed.append(child)\n else:\n d = d + child._get_elementdef_diff(otherchild)\n d = d + child._get_children_diff(otherchild)\n return d\n \nclass FormDef(ElementDef):\n \"\"\" Stores metadata about forms \n When this code was written, I didn't realize XML requires having\n only one root element. Ergo, the root of this xml is accessed via\n FormDef.root (rather than just FormDef)\n \"\"\"\n\n def __init__(self, input_stream=None, child_element=None, **kwargs):\n \"\"\"Either a stream pointer to an XML stream to populate this form\n or a child element to a valid element_def should be provided.\n If neither is, this is a pretty useless form\"\"\"\n # call the base class to initialize some more properties\n super(FormDef, self).__init__(**kwargs) \n self.types = {}\n self.version = None\n self.uiversion = None\n self.target_namespace = ''\n if input_stream is not None and child_element is not None:\n # log this, cause it's a bad idea\n logging.error(\"\"\"Both XML and a child element explicitly passed to\n create a new formdef. The child element %s will be\n ignored\"\"\" % child_element) \n if input_stream is not None:\n payload = get_xml_string(input_stream)\n self.parseString(payload)\n elif child_element is not None:\n self.child_elements = [child_element]\n if len(self.child_elements)>1:\n # fail hard on too many children, since it's bad xml\n raise Exception(\"Poorly formed XML. Multiple root elements!\")\n if not self.child_elements:\n logging.info(\"You just created a formdef %s with no children. Why?!\" % self)\n #logging.error(\"You just created a formdef %s with no children. Why?!\" % self)\n else:\n # safe to set a root node here\n self.root = self.child_elements[0]\n \n def __unicode__(self):\n return unicode(self.target_namespace)", "answers": [" def __str__(self):"], "length": 659, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "93f776fb-d6f2-433d-a96a-0b2d0f04f76f", "reasoning": "The FormDef class mirrors ElementDef, which defines __unicode__ and then __str__ to return a UTF‑8 encoded string. After the __unicode__ method's return statement, the next logical line is the definition of __str__ with the same indentation level.", "reasoning_model_answer": "def __str__(self):", "assistant_with_reasoning": "\nThe FormDef class mirrors ElementDef, which defines __unicode__ and then __str__ to return a UTF‑8 encoded string. After the __unicode__ method's return statement, the next logical line is the definition of __str__ with the same indentation level.\n\ndef __str__(self):", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 2.802, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 6125, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "def __str__(self):", "score": 0.9, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "# coding=utf-8\n\nimport typing\nfrom calendar import timegm\nfrom itertools import chain\nfrom time import gmtime, strftime, strptime\n\nfrom emft.core.logging import Logged, make_logger\nfrom emft.core.validator import Validator, valid_bool, valid_float, valid_int, valid_positive_int, valid_str\n\nEPOCH_DELTA = 1306886400\n\nLOGGER = make_logger(__name__)\n\nvalidator_group_or_unit_name = Validator(_type=str, _regex=r'[a-zA-Z0-9\\_\\-\\#]+',\n exc=ValueError, logger=LOGGER)\n\n\nclass BaseMissionObject(Logged):\n def __init__(self, mission_dict: dict, l10n: dict):\n super().__init__()\n\n if not isinstance(mission_dict, dict):\n raise TypeError('mission_dict should be an dict, got: {}'.format(type(mission_dict)))\n\n if not isinstance(l10n, dict):\n raise TypeError('l10n should be an dict, got: {}'.format(type(l10n)))\n\n self.d = mission_dict\n self.l10n = l10n\n\n self.weather = None\n self.blue_coa = None\n self.red_coa = None\n self.ground_control = None\n\n self._countries_by_name = {}\n self._countries_by_id = {}\n\n def get_country_by_name(self, country_name):\n valid_str.validate(country_name, 'get_country_by_name', exc=ValueError)\n if country_name not in self._countries_by_name.keys():\n for country in self.countries:\n assert isinstance(country, Country)\n if country.country_name == country_name:\n self._countries_by_name[country_name] = country\n return country\n raise ValueError(country_name)\n else:\n return self._countries_by_name[country_name]\n\n def get_country_by_id(self, country_id):\n valid_positive_int.validate(country_id, 'get_country_by_id')\n if country_id not in self._countries_by_id.keys():\n for country in self.countries:\n assert isinstance(country, Country)\n if country.country_id == country_id:\n self._countries_by_id[country_id] = country\n return country\n raise ValueError(country_id)\n else:\n return self._countries_by_id[country_id]\n\n def get_groups_from_category(self, category):\n Mission.validator_group_category.validate(category, 'get_groups_from_category')\n for group in self.groups:\n if group.group_category == category:\n yield group\n\n def get_units_from_category(self, category):\n Mission.validator_group_category.validate(category, 'get_units_from_category')\n for unit in self.units:\n if unit.group_category == category:\n yield unit\n\n def get_group_by_id(self, group_id):\n valid_positive_int.validate(group_id, 'get_group_by_id', exc=ValueError)\n for group in self.groups:\n assert isinstance(group, Group)\n if group.group_id == group_id:\n return group\n return None\n\n def get_clients_groups(self) -> typing.Generator['FlyingUnit', None, None]:\n for group in self.groups:\n assert isinstance(group, Group)\n if group.group_is_client_group:\n yield group\n\n def get_group_by_name(self, group_name):\n valid_str.validate(group_name, 'get_group_by_name')\n for group in self.groups:\n assert isinstance(group, Group)\n if group.group_name == group_name:\n return group\n return None\n\n def get_unit_by_name(self, unit_name):\n valid_str.validate(unit_name, 'get_unit_by_name')\n for unit in self.units:\n assert isinstance(unit, BaseUnit)\n if unit.unit_name == unit_name:\n return unit\n return None\n\n def get_unit_by_id(self, unit_id):\n valid_positive_int.validate(unit_id, 'get_unit_by_id')\n for unit in self.units:\n assert isinstance(unit, BaseUnit)\n if unit.unit_id == unit_id:\n return unit\n return None\n\n @property\n def units(self):\n for group in self.groups:\n for unit in group.units:\n assert isinstance(unit, BaseUnit)\n yield unit\n\n @property\n def groups(self):\n for country in self.countries:\n for group in country.groups:\n assert isinstance(group, Group)\n yield group\n\n @property\n def next_group_id(self):\n ids = set()\n for group in chain(self.blue_coa.groups, self.red_coa.groups):\n assert isinstance(group, Group)\n id_ = group.group_id\n if id_ in ids:\n raise IndexError(group.group_name)\n ids.add(id_)\n return max(ids) + 1\n\n @property\n def next_unit_id(self):\n ids = set()\n for unit in chain(self.blue_coa.units, self.red_coa.units):\n assert isinstance(unit, BaseUnit)\n id_ = unit.unit_id\n if id_ in ids:\n raise IndexError(unit.unit_name)\n ids.add(id_)\n return max(ids) + 1\n\n @property\n def coalitions(self):\n for coalition in [self.blue_coa, self.red_coa]:\n assert isinstance(coalition, Coalition)\n yield coalition\n\n @property\n def countries(self):\n for coalition in self.coalitions:\n for country in coalition.countries:\n assert isinstance(country, Country)\n yield country\n\n @property\n def mission_start_time(self):\n return self.d['start_time']\n\n @mission_start_time.setter\n def mission_start_time(self, value):\n Mission.validator_start_time.validate(value, 'start_time')\n self.d['start_time'] = value\n\n @property\n def mission_start_time_as_date(self):\n return strftime('%d/%m/%Y %H:%M:%S', gmtime(EPOCH_DELTA + self.mission_start_time))\n\n @mission_start_time_as_date.setter\n def mission_start_time_as_date(self, value):\n Mission.validator_start_date.validate(value, 'start_time_as_date')\n self.mission_start_time = timegm(strptime(value, '%d/%m/%Y %H:%M:%S')) - EPOCH_DELTA\n\n @property\n def _sortie_name_key(self):\n return self.d['sortie']\n\n @property\n def sortie_name(self):\n return self.l10n[self._sortie_name_key]\n\n @sortie_name.setter\n def sortie_name(self, value):\n valid_str.validate(value, 'sortie name')\n self.l10n[self._sortie_name_key] = value\n\n\nclass Mission(BaseMissionObject):\n validator_start_time = Validator(\n _type=int,\n _min=0,\n exc=ValueError,\n logger=LOGGER\n )\n validator_start_date = Validator(\n _type=str,\n _regex=r'^(?=\\d)(?:(?:31(?!.(?:0?[2469]|11))|(?:30|29)(?!.0?2)|29'\n r'(?=.0?2.(?:(?:(?:1[6-9]|[2-9]\\d)?(?:0[48]|[2468][048]|[13579][26])'\n r'|(?:(?:16|[2468][048]|[3579][26])00)))(?:\\x20|$))|(?:2[0-8]|1\\d|0?[1-9]))'\n r'([-./])(?:1[012]|0?[1-9])\\1(?:1[6-9]|[2-9]\\d)?\\d\\d(?:(?=\\x20\\d)\\x20|$))?'\n r'(((0?[1-9]|1[012])(:[0-5]\\d){0,2}(\\x20[AP]M))|([01]\\d|2[0-3])'\n r'(:[0-5]\\d){1,2})?$',\n exc=ValueError,\n logger=LOGGER\n )\n validator_heading = Validator(\n _type=int,\n _min=0,\n _max=359,\n exc=ValueError,\n logger=LOGGER\n )\n validator_group_category = Validator(\n _type=str,\n _in_list=['helicopter', 'ship', 'plane', 'vehicle'],\n exc=ValueError,\n logger=LOGGER)\n valid_group_categories = ('helicopter', 'plane', 'ship', 'vehicle')\n\n def __init__(self, mission_dict, l10n):\n super().__init__(mission_dict, l10n)\n self.weather = Weather(self.d, l10n)\n self.blue_coa = Coalition(self.d, l10n, 'blue')\n self.red_coa = Coalition(self.d, l10n, 'red')\n self.ground_control = GroundControl(self.d, l10n)\n\n def __repr__(self):\n return 'Mission({})'.format(self.d)\n\n def farps(self) -> typing.Generator['Static', None, None]:\n for coa in [self.blue_coa, self.red_coa]:\n for farp in coa.farps:\n yield farp\n\n\n# noinspection PyProtectedMember\nclass Coalition(BaseMissionObject):\n def __init__(self, mission_dict, ln10, coa_color):\n super().__init__(mission_dict, ln10)\n self.coa_color = coa_color\n self._countries = {}\n\n def __repr__(self):\n return 'Coalition({}, {})'.format(self._section_coalition, self.coa_color)\n\n def __eq__(self, other):\n if not isinstance(other, Coalition):\n raise ValueError('\"other\" must be an Coalition instance; got: {}'.format(type(other)))\n return self._section_coalition == other._section_coalition\n\n @property\n def _section_coalition(self):\n return self.d['coalition'][self.coa_color]\n\n @property\n def _section_bullseye(self):\n return self._section_coalition['bullseye']", "answers": [" @property"], "length": 617, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "baaae0e2-6943-46d8-aaa3-119ab62fc971", "reasoning": "The class Coalition ends the _section_bullseye property with a return statement. The next logical piece of code is to expose a public property for the bullseye data, so the following line starts a new @property decorator.", "reasoning_model_answer": "@property", "assistant_with_reasoning": "\nThe class Coalition ends the _section_bullseye property with a return statement. The next logical piece of code is to expose a public property for the bullseye data, so the following line starts a new @property decorator.\n\n@property", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 5.361, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 9044, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "@property", "score": 0.82, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "\"\"\"\nMySQL database backend for Django.\n\nRequires MySQLdb: http://sourceforge.net/projects/mysql-python\n\"\"\"\nfrom __future__ import unicode_literals\n\nimport datetime\nimport re\nimport sys\nimport warnings\n\ntry:\n import MySQLdb as Database\nexcept ImportError as e:\n from django.core.exceptions import ImproperlyConfigured\n raise ImproperlyConfigured(\"Error loading MySQLdb module: %s\" % e)\n\n# We want version (1, 2, 1, 'final', 2) or later. We can't just use\n# lexicographic ordering in this check because then (1, 2, 1, 'gamma')\n# inadvertently passes the version test.\nversion = Database.version_info\nif (version < (1, 2, 1) or (version[:3] == (1, 2, 1) and\n (len(version) < 5 or version[3] != 'final' or version[4] < 2))):\n from django.core.exceptions import ImproperlyConfigured\n raise ImproperlyConfigured(\"MySQLdb-1.2.1p2 or newer is required; you have %s\" % Database.__version__)\n\nfrom MySQLdb.converters import conversions, Thing2Literal\nfrom MySQLdb.constants import FIELD_TYPE, CLIENT\n\ntry:\n import pytz\nexcept ImportError:\n pytz = None\n\nfrom django.conf import settings\nfrom django.db import utils\nfrom django.db.backends import (utils as backend_utils, BaseDatabaseFeatures,\n BaseDatabaseOperations, BaseDatabaseWrapper)\nfrom django.db.backends.mysql.client import DatabaseClient\nfrom django.db.backends.mysql.creation import DatabaseCreation\nfrom django.db.backends.mysql.introspection import DatabaseIntrospection\nfrom django.db.backends.mysql.validation import DatabaseValidation\nfrom django.utils.encoding import force_str, force_text\nfrom django.db.backends.mysql.schema import DatabaseSchemaEditor\nfrom django.utils.functional import cached_property\nfrom django.utils.safestring import SafeBytes, SafeText\nfrom django.utils import six\nfrom django.utils import timezone\n\n# Raise exceptions for database warnings if DEBUG is on\nif settings.DEBUG:\n warnings.filterwarnings(\"error\", category=Database.Warning)\n\nDatabaseError = Database.DatabaseError\nIntegrityError = Database.IntegrityError\n\n# It's impossible to import datetime_or_None directly from MySQLdb.times\nparse_datetime = conversions[FIELD_TYPE.DATETIME]\n\n\ndef parse_datetime_with_timezone_support(value):\n dt = parse_datetime(value)\n # Confirm that dt is naive before overwriting its tzinfo.\n if dt is not None and settings.USE_TZ and timezone.is_naive(dt):\n dt = dt.replace(tzinfo=timezone.utc)\n return dt\n\n\ndef adapt_datetime_with_timezone_support(value, conv):\n # Equivalent to DateTimeField.get_db_prep_value. Used only by raw SQL.\n if settings.USE_TZ:\n if timezone.is_naive(value):\n warnings.warn(\"MySQL received a naive datetime (%s)\"\n \" while time zone support is active.\" % value,\n RuntimeWarning)\n default_timezone = timezone.get_default_timezone()\n value = timezone.make_aware(value, default_timezone)\n value = value.astimezone(timezone.utc).replace(tzinfo=None)\n return Thing2Literal(value.strftime(\"%Y-%m-%d %H:%M:%S\"), conv)\n\n# MySQLdb-1.2.1 returns TIME columns as timedelta -- they are more like\n# timedelta in terms of actual behavior as they are signed and include days --\n# and Django expects time, so we still need to override that. We also need to\n# add special handling for SafeText and SafeBytes as MySQLdb's type\n# checking is too tight to catch those (see Django ticket #6052).\n# Finally, MySQLdb always returns naive datetime objects. However, when\n# timezone support is active, Django expects timezone-aware datetime objects.\ndjango_conversions = conversions.copy()\ndjango_conversions.update({\n FIELD_TYPE.TIME: backend_utils.typecast_time,\n FIELD_TYPE.DECIMAL: backend_utils.typecast_decimal,\n FIELD_TYPE.NEWDECIMAL: backend_utils.typecast_decimal,\n FIELD_TYPE.DATETIME: parse_datetime_with_timezone_support,\n datetime.datetime: adapt_datetime_with_timezone_support,\n})\n\n# This should match the numerical portion of the version numbers (we can treat\n# versions like 5.0.24 and 5.0.24a as the same). Based on the list of version\n# at http://dev.mysql.com/doc/refman/4.1/en/news.html and\n# http://dev.mysql.com/doc/refman/5.0/en/news.html .\nserver_version_re = re.compile(r'(\\d{1,2})\\.(\\d{1,2})\\.(\\d{1,2})')\n\n\n# MySQLdb-1.2.1 and newer automatically makes use of SHOW WARNINGS on\n# MySQL-4.1 and newer, so the MysqlDebugWrapper is unnecessary. Since the\n# point is to raise Warnings as exceptions, this can be done with the Python\n# warning module, and this is setup when the connection is created, and the\n# standard backend_utils.CursorDebugWrapper can be used. Also, using sql_mode\n# TRADITIONAL will automatically cause most warnings to be treated as errors.\n\nclass CursorWrapper(object):\n \"\"\"\n A thin wrapper around MySQLdb's normal cursor class so that we can catch\n particular exception instances and reraise them with the right types.\n\n Implemented as a wrapper, rather than a subclass, so that we aren't stuck\n to the particular underlying representation returned by Connection.cursor().\n \"\"\"\n codes_for_integrityerror = (1048,)\n\n def __init__(self, cursor):\n self.cursor = cursor\n\n def execute(self, query, args=None):\n try:\n # args is None means no string interpolation\n return self.cursor.execute(query, args)\n except Database.OperationalError as e:\n # Map some error codes to IntegrityError, since they seem to be\n # misclassified and Django would prefer the more logical place.\n if e.args[0] in self.codes_for_integrityerror:\n six.reraise(utils.IntegrityError, utils.IntegrityError(*tuple(e.args)), sys.exc_info()[2])\n raise\n", "answers": [" def executemany(self, query, args):"], "length": 626, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "0d9a145f-3d15-4021-be37-f79499b455c9", "reasoning": "The CursorWrapper class defines an execute method with a try/except handling for OperationalError. In Django's MySQL backend, the next method defined is executemany, mirroring the same error handling pattern. Therefore the next line should start the definition of the executemany method.", "reasoning_model_answer": "def executemany(self, query, args):", "assistant_with_reasoning": "\nThe CursorWrapper class defines an execute method with a try/except handling for OperationalError. In Django's MySQL backend, the next method defined is executemany, mirroring the same error handling pattern. Therefore the next line should start the definition of the executemany method.\n\ndef executemany(self, query, args):", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.207, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 5830, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "def executemany(self, query, args):", "score": 0.95, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "#!/usr/bin/env python\n# -*- coding: UTF-8 -*-\n\n\"\"\"\npython %prog study.file population.file gene-association.file\n\nThis program returns P-values for functional enrichment in a cluster of\nstudy genes using Fisher's exact test, and corrected for multiple testing\n(including Bonferroni, Holm, Sidak, and false discovery rate)\n\"\"\"\n\nfrom __future__ import absolute_import\n\n__copyright__ = \"Copyright (C) 2010-2017, H Tang et al., All rights reserved.\"\n__author__ = \"various\"\n\nimport sys\nimport collections as cx\nimport datetime\n\nfrom .multiple_testing import Methods, Bonferroni, Sidak, HolmBonferroni, FDR, calc_qval\nfrom .ratio import get_terms, count_terms, is_ratio_different\nfrom . import wr_tbl as RPT\nfrom .pvalcalc import FisherFactory\n\n\nclass GOEnrichmentRecord(object):\n \"\"\"Represents one result (from a single GOTerm) in the GOEnrichmentStudy\n \"\"\"\n namespace2NS = cx.OrderedDict([\n ('biological_process', 'BP'),\n ('molecular_function', 'MF'),\n ('cellular_component', 'CC')])\n\n # Fields seen in every enrichment result\n _fldsdefprt = [\n \"GO\",\n \"NS\",\n \"enrichment\",\n \"name\",\n \"ratio_in_study\",\n \"ratio_in_pop\",\n \"p_uncorrected\",\n \"depth\",\n \"study_count\",\n \"study_items\"]\n _fldsdeffmt = [\"%s\"]*3 + [\"%-30s\"] + [\"%d/%d\"] * 2 + [\"%.3g\"] + [\"%d\"] * 2 + [\"%15s\"]\n\n _flds = set(_fldsdefprt).intersection(\n set(['study_items', 'study_count', 'study_n', 'pop_items', 'pop_count', 'pop_n']))\n\n def __init__(self, **kwargs):\n # Methods seen in current enrichment result\n self._methods = []\n for k, v in kwargs.items():\n setattr(self, k, v)\n if k == 'ratio_in_study':\n setattr(self, 'study_count', v[0])\n setattr(self, 'study_n', v[1])\n if k == 'ratio_in_pop':\n setattr(self, 'pop_count', v[0])\n setattr(self, 'pop_n', v[1])\n self._init_enrichment()\n self.goterm = None # the reference to the GOTerm\n\n def get_method_name(self):\n \"\"\"Return name of first method in the _methods list.\"\"\"\n return self._methods[0].fieldname\n\n def get_pvalue(self):\n \"\"\"Returns pval for 1st method, if it exists. Else returns uncorrected pval.\"\"\"\n if self._methods:\n return getattr(self, \"p_{m}\".format(m=self.get_method_name()))\n return getattr(self, \"p_uncorrected\")\n\n def set_corrected_pval(self, nt_method, pvalue):\n \"\"\"Add object attribute based on method name.\"\"\"\n self._methods.append(nt_method)\n fieldname = \"\".join([\"p_\", nt_method.fieldname])\n setattr(self, fieldname, pvalue)\n\n def __str__(self, indent=False):\n field_data = [getattr(self, f, \"n.a.\") for f in self._fldsdefprt[:-1]] + \\\n [getattr(self, \"p_{}\".format(m.fieldname)) for m in self._methods] + \\\n [\", \".join(sorted(getattr(self, self._fldsdefprt[-1], set())))]\n fldsdeffmt = self._fldsdeffmt\n field_formatter = fldsdeffmt[:-1] + [\"%.3g\"]*len(self._methods) + [fldsdeffmt[-1]]\n self._chk_fields(field_data, field_formatter)\n\n # default formatting only works for non-\"n.a\" data\n for i, f in enumerate(field_data):\n if f == \"n.a.\":\n field_formatter[i] = \"%s\"\n\n # print dots to show the level of the term\n dots = self.get_indent_dots() if indent else \"\"\n prtdata = \"\\t\".join(a % b for (a, b) in zip(field_formatter, field_data))\n return \"\".join([dots, prtdata])\n\n def get_indent_dots(self):\n \"\"\"Get a string of dots (\"....\") representing the level of the GO term.\"\"\"\n return \".\" * self.goterm.level if self.goterm is not None else \"\"\n\n @staticmethod\n def _chk_fields(field_data, field_formatter):\n \"\"\"Check that expected fields are present.\"\"\"\n if len(field_data) == len(field_formatter):\n return\n len_dat = len(field_data)\n len_fmt = len(field_formatter)\n msg = [\n \"FIELD DATA({d}) != FORMATTER({f})\".format(d=len_dat, f=len_fmt),\n \"DAT({N}): {D}\".format(N=len_dat, D=field_data),\n \"FMT({N}): {F}\".format(N=len_fmt, F=field_formatter)]\n raise Exception(\"\\n\".join(msg))\n\n def __repr__(self):\n return \"GOEnrichmentRecord({GO})\".format(GO=self.GO)\n\n def set_goterm(self, goid):\n \"\"\"Set goterm and copy GOTerm's name and namespace.\"\"\"\n self.goterm = goid.get(self.GO, None)\n present = self.goterm is not None\n self.name = self.goterm.name if present else \"n.a.\"\n self.NS = self.namespace2NS[self.goterm.namespace] if present else \"XX\"\n\n def _init_enrichment(self):\n \"\"\"Mark as 'enriched' or 'purified'.\"\"\"\n self.enrichment = 'e' if ((1.0 * self.study_count / self.study_n) >\n (1.0 * self.pop_count / self.pop_n)) else 'p'\n\n def update_remaining_fldsdefprt(self, min_ratio=None):\n self.is_ratio_different = is_ratio_different(min_ratio, self.study_count,\n self.study_n, self.pop_count, self.pop_n)\n\n\n # -------------------------------------------------------------------------------------\n # Methods for getting flat namedtuple values from GOEnrichmentRecord object\n def get_prtflds_default(self):\n \"\"\"Get default fields.\"\"\"\n return self._fldsdefprt[:-1] + \\\n [\"p_{M}\".format(M=m.fieldname) for m in self._methods] + \\\n [self._fldsdefprt[-1]]\n\n def get_prtflds_all(self):\n \"\"\"When converting to a namedtuple, get all possible fields in their original order.\"\"\"\n flds = []\n dont_add = set(['_parents', '_methods'])\n # Fields: GO NS enrichment name ratio_in_study ratio_in_pop p_uncorrected\n # depth study_count p_sm_bonferroni p_fdr_bh study_items\n self._flds_append(flds, self.get_prtflds_default(), dont_add)\n # Fields: GO NS goterm\n # ratio_in_pop pop_n pop_count pop_items name\n # ratio_in_study study_n study_count study_items\n # _methods enrichment p_uncorrected p_sm_bonferroni p_fdr_bh\n self._flds_append(flds, vars(self).keys(), dont_add)\n # Fields: name level is_obsolete namespace id depth parents children _parents alt_ids\n self._flds_append(flds, vars(self.goterm).keys(), dont_add)\n return flds\n\n @staticmethod\n def _flds_append(flds, addthese, dont_add):\n \"\"\"Retain order of fields as we add them once to the list.\"\"\"", "answers": [" for fld in addthese:"], "length": 627, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "83f1ac09-7548-4bbb-8a0b-6328b56bb6e5", "reasoning": "The static method _flds_append is defined with a docstring and needs to implement its functionality. The next logical line after the docstring is the start of the loop that iterates over the items to be added, i.e., a for‑loop over 'addthese'. This matches typical Python style for such helper methods.", "reasoning_model_answer": "for f in addthese:", "assistant_with_reasoning": "\nThe static method _flds_append is defined with a docstring and needs to implement its functionality. The next logical line after the docstring is the start of the loop that iterates over the items to be added, i.e., a for‑loop over 'addthese'. This matches typical Python style for such helper methods.\n\nfor f in addthese:", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.05, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 6700, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "for f in addthese:", "score": 0.78, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "namespace Oort.AzureStorage.Mockable\n{\n using System;\n using System.Collections.Generic;\n using System.Threading;\n using System.Threading.Tasks;\n using Microsoft.WindowsAzure.Storage;\n using Microsoft.WindowsAzure.Storage.Table;\n\n public class OortTable : ICloudTable\n {\n private readonly CloudTable _cloudTable;\n\n public TableResult Execute(TableOperation operation, TableRequestOptions requestOptions = null,\n OperationContext operationContext = null)\n {\n return _cloudTable.Execute(operation, requestOptions, operationContext);\n }\n\n public ICancellableAsyncResult BeginExecute(TableOperation operation, AsyncCallback callback, object state)\n {\n return _cloudTable.BeginExecute(operation, callback, state);\n }\n\n public ICancellableAsyncResult BeginExecute(TableOperation operation, TableRequestOptions requestOptions,\n OperationContext operationContext, AsyncCallback callback, object state)\n {\n return _cloudTable.BeginExecute(operation, requestOptions, operationContext, callback, state);\n }\n\n public TableResult EndExecute(IAsyncResult asyncResult)\n {\n return _cloudTable.EndExecute(asyncResult);\n }\n\n public Task ExecuteAsync(TableOperation operation)\n {\n return _cloudTable.ExecuteAsync(operation);\n }\n\n public Task ExecuteAsync(TableOperation operation, CancellationToken cancellationToken)\n {\n return _cloudTable.ExecuteAsync(operation, cancellationToken);\n }\n\n public Task ExecuteAsync(TableOperation operation, TableRequestOptions requestOptions, OperationContext operationContext)\n {\n return _cloudTable.ExecuteAsync(operation, requestOptions, operationContext);\n }\n\n public Task ExecuteAsync(TableOperation operation, TableRequestOptions requestOptions, OperationContext operationContext,\n CancellationToken cancellationToken)\n {\n return _cloudTable.ExecuteAsync(operation, requestOptions, operationContext, cancellationToken);\n }\n\n public IList ExecuteBatch(TableBatchOperation batch, TableRequestOptions requestOptions = null,\n OperationContext operationContext = null)\n {\n return _cloudTable.ExecuteBatch(batch, requestOptions, operationContext);\n }\n\n public ICancellableAsyncResult BeginExecuteBatch(TableBatchOperation batch, AsyncCallback callback, object state)\n {\n return _cloudTable.BeginExecuteBatch(batch, callback, state);\n }\n\n public ICancellableAsyncResult BeginExecuteBatch(TableBatchOperation batch, TableRequestOptions requestOptions,\n OperationContext operationContext, AsyncCallback callback, object state)\n {\n return _cloudTable.BeginExecuteBatch(batch, requestOptions, operationContext, callback, state);\n }\n\n public IList EndExecuteBatch(IAsyncResult asyncResult)\n {\n return _cloudTable.EndExecuteBatch(asyncResult);\n }\n\n public Task> ExecuteBatchAsync(TableBatchOperation batch)\n {\n return _cloudTable.ExecuteBatchAsync(batch);\n }\n\n public Task> ExecuteBatchAsync(TableBatchOperation batch, CancellationToken cancellationToken)\n {\n return _cloudTable.ExecuteBatchAsync(batch, cancellationToken);\n }\n\n public Task> ExecuteBatchAsync(TableBatchOperation batch, TableRequestOptions requestOptions, OperationContext operationContext)\n {\n return _cloudTable.ExecuteBatchAsync(batch, requestOptions, operationContext);\n }\n\n public Task> ExecuteBatchAsync(TableBatchOperation batch, TableRequestOptions requestOptions, OperationContext operationContext,\n CancellationToken cancellationToken)\n {\n return _cloudTable.ExecuteBatchAsync(batch, requestOptions, operationContext, cancellationToken);\n }\n\n public IEnumerable ExecuteQuery(TableQuery query, TableRequestOptions requestOptions = null,\n OperationContext operationContext = null)\n {\n return _cloudTable.ExecuteQuery(query, requestOptions, operationContext);\n }\n\n public TableQuerySegment ExecuteQuerySegmented(TableQuery query, TableContinuationToken token,\n TableRequestOptions requestOptions = null, OperationContext operationContext = null)\n {\n return _cloudTable.ExecuteQuerySegmented(query, token, requestOptions, operationContext);\n }\n\n public ICancellableAsyncResult BeginExecuteQuerySegmented(TableQuery query, TableContinuationToken token,\n AsyncCallback callback, object state)\n {\n return _cloudTable.BeginExecuteQuerySegmented(query, token, callback, state);\n }\n\n public ICancellableAsyncResult BeginExecuteQuerySegmented(TableQuery query, TableContinuationToken token,\n TableRequestOptions requestOptions, OperationContext operationContext, AsyncCallback callback, object state)\n {\n return _cloudTable.BeginExecuteQuerySegmented(query, token, requestOptions, operationContext, callback, state);\n }\n\n public TableQuerySegment EndExecuteQuerySegmented(IAsyncResult asyncResult)\n {\n return _cloudTable.EndExecuteQuerySegmented(asyncResult);\n }\n\n public Task> ExecuteQuerySegmentedAsync(TableQuery query, TableContinuationToken token)\n {\n return _cloudTable.ExecuteQuerySegmentedAsync(query, token);\n }\n\n public Task> ExecuteQuerySegmentedAsync(TableQuery query, TableContinuationToken token, CancellationToken cancellationToken)\n {\n return _cloudTable.ExecuteQuerySegmentedAsync(query, token, cancellationToken);\n }\n\n public Task> ExecuteQuerySegmentedAsync(TableQuery query, TableContinuationToken token, TableRequestOptions requestOptions,\n OperationContext operationContext)\n {\n return _cloudTable.ExecuteQuerySegmentedAsync(query, token, requestOptions, operationContext);\n }\n\n public Task> ExecuteQuerySegmentedAsync(TableQuery query, TableContinuationToken token, TableRequestOptions requestOptions,\n OperationContext operationContext, CancellationToken cancellationToken)\n {\n return _cloudTable.ExecuteQuerySegmentedAsync(query, token, requestOptions, operationContext, cancellationToken);\n }\n\n public IEnumerable ExecuteQuery(TableQuery query, EntityResolver resolver, TableRequestOptions requestOptions = null,\n OperationContext operationContext = null)\n {\n return _cloudTable.ExecuteQuery(query, resolver, requestOptions, operationContext);\n }\n\n public TableQuerySegment ExecuteQuerySegmented(TableQuery query, EntityResolver resolver, TableContinuationToken token,\n TableRequestOptions requestOptions = null, OperationContext operationContext = null)\n {\n return _cloudTable.ExecuteQuerySegmented(query, resolver, token, requestOptions, operationContext);\n }\n\n public ICancellableAsyncResult BeginExecuteQuerySegmented(TableQuery query, EntityResolver resolver,\n TableContinuationToken token, AsyncCallback callback, object state)\n {\n return _cloudTable.BeginExecuteQuerySegmented(query, resolver, token, callback, state);\n }\n\n public ICancellableAsyncResult BeginExecuteQuerySegmented(TableQuery query, EntityResolver resolver,\n TableContinuationToken token, TableRequestOptions requestOptions, OperationContext operationContext,\n AsyncCallback callback, object state)\n {\n return _cloudTable.BeginExecuteQuerySegmented(query, resolver, token, requestOptions, operationContext, callback, state);\n }\n\n public Task> ExecuteQuerySegmentedAsync(TableQuery query, EntityResolver resolver, TableContinuationToken token)\n {\n return _cloudTable.ExecuteQuerySegmentedAsync(query, resolver, token);\n }\n\n public Task> ExecuteQuerySegmentedAsync(TableQuery query, EntityResolver resolver, TableContinuationToken token,\n CancellationToken cancellationToken)\n {\n return _cloudTable.ExecuteQuerySegmentedAsync(query, resolver, token, cancellationToken);\n }\n\n public Task> ExecuteQuerySegmentedAsync(TableQuery query, EntityResolver resolver, TableContinuationToken token,\n TableRequestOptions requestOptions, OperationContext operationContext)\n {\n return _cloudTable.ExecuteQuerySegmentedAsync(query, resolver, token, requestOptions, operationContext);\n }\n\n public Task> ExecuteQuerySegmentedAsync(TableQuery query, EntityResolver resolver, TableContinuationToken token,\n TableRequestOptions requestOptions, OperationContext operationContext, CancellationToken cancellationToken)\n {\n return _cloudTable.ExecuteQuerySegmentedAsync(query, resolver, token, requestOptions, operationContext, cancellationToken);\n }\n\n public TableQuery CreateQuery() where TElement : ITableEntity, new()\n {", "answers": [" return _cloudTable.CreateQuery();"], "length": 573, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "1c433020-827f-4216-8fa2-0d71cdec6689", "reasoning": "The class OortTable forwards all ICloudTable calls to the underlying CloudTable instance. The CreateQuery() method should therefore return the result of calling the same method on _cloudTable. The appropriate line is a return statement invoking _cloudTable.CreateQuery().", "reasoning_model_answer": "return _cloudTable.CreateQuery();", "assistant_with_reasoning": "\nThe class OortTable forwards all ICloudTable calls to the underlying CloudTable instance. The CreateQuery() method should therefore return the result of calling the same method on _cloudTable. The appropriate line is a return statement invoking _cloudTable.CreateQuery().\n\nreturn _cloudTable.CreateQuery();", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 1.933, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 10042, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "return _cloudTable.CreateQuery();", "score": 0.88, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "\"\"\" Part of the YABEE\n\"\"\"\n\nimport bpy\nif __name__ != '__main__':\n from .utils import convertFileNameToPanda, save_image\n\nBAKE_TYPES = {'diffuse': ('TEXTURE', 'MODULATE'),\n 'normal': ('NORMALS', 'NORMAL'),\n 'gloss': ('SPEC_INTENSITY', 'GLOSS'),\n 'glow': ('EMIT', 'GLOW'),\n 'AO': ('AO', 'MODULATE'),\n 'shadow': ('SHADOW', 'MODULATE')\n }\n\nclass PbrTextures():\n def __init__(self, obj_list, uv_img_as_texture, copy_tex, file_path, tex_path):\n self.obj_list = obj_list[:]\n self.uv_img_as_texture = uv_img_as_texture\n self.copy_tex = copy_tex\n self.file_path = file_path\n self.tex_path = tex_path\n \n def get_used_textures(self):\n \"\"\" Collect images from the UV images and Material texture slots\n tex_list structure:\n image_name: { 'scalars': [(name, val), (name, val), ...],\n 'path': 'path/to/texture',\n 'transform': [(type, val), (type, val), ...]\n }\n \"\"\"\n print(\"starting texture collection\")\n tex_list = {}\n print( self.obj_list)\n for obj in self.obj_list:\n if obj.type == 'MESH':\n print(\"processing object\",obj)\n use_uv_face_tex = False\n use_uv_face_tex_alpha = False\n # General textures\n handled = set()\n for f in obj.data.polygons:\n #print(\"processing polygon\",f)\n if f.material_index < len(obj.data.materials):\n #print(\"found material index\")\n mat = obj.data.materials[f.material_index]\n if not mat or mat in handled:\n continue\n print(\"found new material\")\n handled.add(mat)\n \n nodeNames={\"ColorTex\":None, \"RoughnessTex\":None , \"NormalTex\":None, \"SpecularDummyTex\":None} ##we do need an empty for specular but it's added somewhere else\n #let's crawl all links, find the ones connected to the PandaPBRNode, find the connected textures, use them.\n for link in mat.node_tree.links:\n if link.to_node.name == \"Panda3D_RP_Diffuse_Mat\": #if the link connects to the panda3ddiffuse node\n print(\"found new panda3d diffuse node\")\n if link.to_socket.name in nodeNames.keys(): # and it connects to one of our known sockets...\n textureNode = link.from_node\n \n if textureNode.image == None:\n print(\"WARNING: Texture node has no image assigned\", obj.name, link.to_socket.name)\n continue\n \n if not textureNode.inputs[0].is_linked:\n print(\"WARNING: Texture has no UV-INPUT\", obj.name, link.to_socket.name)\n continue\n \n scalars = []\n \n for link2 in mat.node_tree.links: #we have to crawl the links again\n if link2.to_node == textureNode: #we finally found the uv-map connected to the texture we want\n uvNode = link2.from_node\n scalars.append(('uv-name', uvNode.uv_map))\n scalars.append(('envtype', \"Modulate\"))\n \n \n #if tex.texture_coords == 'UV':\n # if tex.uv_layer:\n # uv_name = tex.uv_layer\n # if uv_name not in [uv.name for uv in obj.data.uv_textures]:\n # print(\"WARNING: Object has no uv-map:\", obj.name)\n # uv_name = ''\n \n t_path = textureNode.image.filepath\n if self.copy_tex:\n t_path = save_image(textureNode.image, self.file_path, self.tex_path)\n\n #tex_list[tex.texture.name] = {'path': t_path,\n # 'scalars': scalars, 'transform': transform }\n transform = []\n \n\n #if(textureNode.use_mipmap): #todo: find the use_mipmap flag\n scalars.append(('minfilter', 'LINEAR_MIPMAP_LINEAR'))\n scalars.append(('magfilter', 'LINEAR_MIPMAP_LINEAR'))\n\n # Process wrap modes.\n if(textureNode.extension == 'EXTEND'):\n scalars.append(('wrap', 'CLAMP'))\n\n elif(textureNode.extension in ('CLIP', 'CLIP_CUBE')):\n scalars.append(('wrap', 'BORDER_COLOR'))\n scalars.append(('borderr', '1'))\n scalars.append(('borderg', '1'))\n scalars.append(('borderb', '1'))\n scalars.append(('bordera', '1'))\n\n elif(textureNode.extension in ('REPEAT', 'CHECKER')):\n scalars.append(('wrap', 'REPEAT'))\n\n # Process coordinate mapping using a matrix.\n mappings = (textureNode.texture_mapping.mapping_x, textureNode.texture_mapping.mapping_y, textureNode.texture_mapping.mapping_z)\n\n if mappings != ('X', 'Y', 'Z'):\n matrix = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]\n\n for col, mapping in enumerate(mappings):\n if mapping == 'Z' :\n # Z is not present when using UV coordinates. we always use uv for pbr so far\n mapping = 'NONE'\n\n if mapping == 'NONE':\n # It seems that Blender sets Z to 0.5 when it is not present.\n matrix[4 * 3 + col] = 0.5\n else:\n row = ord(mapping) - ord('X')\n matrix[4 * row + col] = 1\n\n transform.append(('Matrix4', matrix))\n\n # Process texture transformations.\n if(tuple(textureNode.texture_mapping.scale) != (1.0, 1.0, 1.0)):\n # Blender scales from the centre, so shift it before scaling and then shift it back.\n transform.append(('Translate', (-0.5, -0.5, -0.5)))\n transform.append(('Scale', tex.scale))\n transform.append(('Translate', (0.5, 0.5, 0.5)))\n\n if(tuple(textureNode.texture_mapping.translation) != (0.0, 0.0, 0.0)):\n transform.append(('Translate', texture_mapping.translation))\n \n #finally add everything to the list\n \n tex_list[textureNode.name] = {'path': t_path,\n 'scalars': scalars, 'transform': transform }\n #let's not get into alpha with the diffuse material for now.\n #if(envtype == 'MODULATE'):\n # if(alpha_tex and not alpha_map_assigned):\n # alpha_map_assigned = True\n # alpha_path = alpha_tex.texture.image.filepath\n # if self.copy_tex:\n # alpha_path = save_image(alpha_tex.texture.image, self.file_path, self.tex_path)\n # scalars.append(('alpha-file', '\\\"%s\\\"' % convertFileNameToPanda(alpha_path) ))\n # scalars.append(('alpha-file-channel', '4'))\n\n # if(mat.game_settings.alpha_blend == 'CLIP'):\n # scalars.append(('alpha', 'BINARY'))\n # elif(mat.game_settings.alpha_blend == 'ADD'):\n # scalars.append(('blend', 'add'))\n #except:\n # print('ERROR: can\\'t get texture image on %s.' % tex.texture.name)\n #print (\"texture list \",tex_list)", "answers": [" return tex_list"], "length": 622, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "c9aad855-19f4-4c22-8f8b-b84eac5f650c", "reasoning": "The get_used_textures method builds a dictionary tex_list of texture information. After processing all objects, the method should output this dictionary. The commented-out debug print suggests the next logical step is to return tex_list, placed at the same indentation level inside the method.", "reasoning_model_answer": "return tex_list", "assistant_with_reasoning": "\nThe get_used_textures method builds a dictionary tex_list of texture information. After processing all objects, the method should output this dictionary. The commented-out debug print suggests the next logical step is to return tex_list, placed at the same indentation level inside the method.\n\nreturn tex_list", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 2.669, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 9862, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "return tex_list", "score": 0.79, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\nfrom openstack import proxy\nfrom openstack.dns.v2 import recordset as _rs\nfrom openstack.dns.v2 import zone as _zone\nfrom openstack.dns.v2 import zone_import as _zone_import\nfrom openstack.dns.v2 import zone_export as _zone_export\nfrom openstack.dns.v2 import zone_transfer as _zone_transfer\nfrom openstack.dns.v2 import floating_ip as _fip\n\n\nclass Proxy(proxy.Proxy):\n\n # ======== Zones ========\n def zones(self, **query):\n \"\"\"Retrieve a generator of zones\n\n :param dict query: Optional query parameters to be sent to limit the\n resources being returned.\n\n * `name`: Zone Name field.\n * `type`: Zone Type field.\n * `email`: Zone email field.\n * `status`: Status of the zone.\n * `ttl`: TTL field filter.abs\n * `description`: Zone description field filter.\n\n :returns: A generator of zone\n :class:`~openstack.dns.v2.zone.Zone` instances.\n \"\"\"\n return self._list(_zone.Zone, **query)\n\n def create_zone(self, **attrs):\n \"\"\"Create a new zone from attributes\n\n :param dict attrs: Keyword arguments which will be used to create\n a :class:`~openstack.dns.v2.zone.Zone`,\n comprised of the properties on the Zone class.\n :returns: The results of zone creation.\n :rtype: :class:`~openstack.dns.v2.zone.Zone`\n \"\"\"\n return self._create(_zone.Zone, prepend_key=False, **attrs)\n\n def get_zone(self, zone):\n \"\"\"Get a zone\n\n :param zone: The value can be the ID of a zone\n or a :class:`~openstack.dns.v2.zone.Zone` instance.\n :returns: Zone instance.\n :rtype: :class:`~openstack.dns.v2.zone.Zone`\n \"\"\"\n return self._get(_zone.Zone, zone)\n\n def delete_zone(self, zone, ignore_missing=True):\n \"\"\"Delete a zone\n\n :param zone: The value can be the ID of a zone\n or a :class:`~openstack.dns.v2.zone.Zone` instance.\n :param bool ignore_missing: When set to ``False``\n :class:`~openstack.exceptions.ResourceNotFound` will be raised when\n the zone does not exist.\n When set to ``True``, no exception will be set when attempting to\n delete a nonexistent zone.\n\n :returns: Zone been deleted\n :rtype: :class:`~openstack.dns.v2.zone.Zone`\n \"\"\"\n return self._delete(_zone.Zone, zone, ignore_missing=ignore_missing)\n\n def update_zone(self, zone, **attrs):\n \"\"\"Update zone attributes\n\n :param zone: The id or an instance of\n :class:`~openstack.dns.v2.zone.Zone`.\n :param dict attrs: attributes for update on\n :class:`~openstack.dns.v2.zone.Zone`.\n\n :rtype: :class:`~openstack.dns.v2.zone.Zone`\n \"\"\"\n return self._update(_zone.Zone, zone, **attrs)\n\n def find_zone(self, name_or_id, ignore_missing=True, **attrs):\n \"\"\"Find a single zone\n\n :param name_or_id: The name or ID of a zone\n :param bool ignore_missing: When set to ``False``\n :class:`~openstack.exceptions.ResourceNotFound` will be raised\n when the zone does not exist.\n When set to ``True``, no exception will be set when attempting\n to delete a nonexistent zone.\n\n :returns: :class:`~openstack.dns.v2.zone.Zone`\n \"\"\"\n return self._find(_zone.Zone, name_or_id,\n ignore_missing=ignore_missing)\n\n def abandon_zone(self, zone, **attrs):\n \"\"\"Abandon Zone\n\n :param zone: The value can be the ID of a zone to be abandoned\n or a :class:`~openstack.dns.v2.zone_export.ZoneExport` instance.\n\n :returns: None\n \"\"\"\n zone = self._get_resource(_zone.Zone, zone)\n\n return zone.abandon(self)\n\n def xfr_zone(self, zone, **attrs):\n \"\"\"Trigger update of secondary Zone\n\n :param zone: The value can be the ID of a zone to be abandoned\n or a :class:`~openstack.dns.v2.zone_export.ZoneExport` instance.\n\n :returns: None\n \"\"\"\n zone = self._get_resource(_zone.Zone, zone)\n return zone.xfr(self)\n\n # ======== Recordsets ========\n def recordsets(self, zone=None, **query):\n \"\"\"Retrieve a generator of recordsets\n\n :param zone: The optional value can be the ID of a zone\n or a :class:`~openstack.dns.v2.zone.Zone` instance. If it is not\n given all recordsets for all zones of the tenant would be\n retrieved\n :param dict query: Optional query parameters to be sent to limit the\n resources being returned.\n\n * `name`: Recordset Name field.\n * `type`: Type field.\n * `status`: Status of the recordset.\n * `ttl`: TTL field filter.\n * `description`: Recordset description field filter.\n\n :returns: A generator of zone\n (:class:`~openstack.dns.v2.recordset.Recordset`) instances\n \"\"\"\n base_path = None\n if not zone:\n base_path = '/recordsets'\n else:\n zone = self._get_resource(_zone.Zone, zone)\n query.update({'zone_id': zone.id})\n return self._list(_rs.Recordset, base_path=base_path, **query)\n", "answers": [" def create_recordset(self, zone, **attrs):"], "length": 617, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "4384c17c-2a72-4f08-9494-82a7b6948519", "reasoning": "The Proxy class defines DNS related operations. After the recordsets() method, the next logical operation is to create a recordset, following the pattern used for zones (create_zone, get_zone, etc.). Therefore the next line should start the definition of the create_recordset method with appropriate parameters and indentation.", "reasoning_model_answer": "def create_recordset(self, zone, **attrs):", "assistant_with_reasoning": "\nThe Proxy class defines DNS related operations. After the recordsets() method, the next logical operation is to create a recordset, following the pattern used for zones (create_zone, get_zone, etc.). Therefore the next line should start the definition of the create_recordset method with appropriate parameters and indentation.\n\ndef create_recordset(self, zone, **attrs):", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.158, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 5899, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "def create_recordset(self, zone, **attrs):", "score": 0.95, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "// Copyright 2017 Google Inc. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nusing System;\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Text.RegularExpressions;\n\nusing UnityEngine;\n\nnamespace TiltBrushToolkit {\n\npublic class GltfMaterialConverter {\n private static readonly Regex kTiltBrushMaterialRegex = new Regex(\n @\".*([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$\");\n // Matches\n // http://.../shadername.glsl\n // /.../-.glsl\n private static readonly Regex kTiltBrushShaderRegex = new Regex(\n @\".*([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})[/-]\");\n\n /// \n /// Information about a Unity material corresponding to a Gltf node.\n /// \n public struct UnityMaterial {\n /// \n /// The material to be used in place of the GltfMaterial\n /// \n public Material material;\n /// \n /// The material that \"material\" is based on. This might be the same as\n /// \"material\", if no customizations were needed.\n /// \n public Material template;\n }\n\n /// \n /// List of NEW Unity materials we have created.\n /// \n private List m_newMaterials = new List();\n\n /// \n /// For memoizing GetMaterial()\n /// \n private Dictionary m_getMaterialMemo =\n new Dictionary();\n\n private static bool IsTiltBrushHostedUri(string uri) {\n // Will always look like \"https://www.tiltbrush.com/shaders/...\"\n if (uri.Contains(\"://\")) { return true; }\n return false;\n }\n\n /// \n /// Enumerates those Textures associated with local materials, as distinguished\n /// from well-known, global materials like BlocksPaper and Tilt Brush Light.\n /// Textures associated with those latter materials will not be enumerated.\n ///\n /// These are the textures that need UnityEngine.Textures created for them.\n /// \n public static IEnumerable NecessaryTextures(GltfRootBase root) {\n foreach (var mat in root.Materials) {\n if (! IsGlobalMaterial(mat)) {\n foreach (var tex in mat.ReferencedTextures) {\n yield return tex;\n }\n }\n }\n }\n\n /// \n /// Converts \"Necessary\" textures textures found in the gltf file.\n /// Coroutine must be fully consumed before generating materials.\n /// \n /// \n /// The root of the GLTF file.\n /// The loader to use to load resources (textures, etc).\n /// Mutated to add any textures that were loaded.\n public static IEnumerable LoadTexturesCoroutine(\n GltfRootBase root, IUriLoader loader, List loaded) {\n foreach (GltfTextureBase gltfTexture in NecessaryTextures(root)) {\n if (IsTiltBrushHostedUri(gltfTexture.SourcePtr.uri)) {\n Debug.LogWarningFormat(\"Texture {0} uri {1} was considered necessary\",\n gltfTexture.GltfId, gltfTexture.SourcePtr.uri);\n continue;\n }\n foreach (var unused in ConvertTextureCoroutine(gltfTexture, loader)) {\n yield return null;\n }\n if (gltfTexture.unityTexture != null) {\n loaded.Add(gltfTexture.unityTexture);\n }\n }\n\n // After textures are converted, we don't need the cached RawImage data any more.\n // \"Deallocate\" it.\n foreach (GltfImageBase image in root.Images) {\n image.data = null;\n }\n }\n\n /// \n /// Gets (or creates) the Unity material corresponding to the given glTF material.\n /// \n /// The glTF material.\n /// The Unity material that correpsonds to the given GLTF2 material.\n public UnityMaterial? GetMaterial(GltfMaterialBase gltfMaterial) {\n if (m_getMaterialMemo.TryGetValue(gltfMaterial, out UnityMaterial memo)) {\n return memo;\n }\n\n if (LookUpGlobalMaterial(gltfMaterial) is UnityMaterial global) {\n Debug.Assert(global.material == global.template);\n m_getMaterialMemo[gltfMaterial] = global;\n return global;\n }\n\n if (ConvertGltfMaterial(gltfMaterial) is UnityMaterial created) {\n Debug.Assert(created.material != created.template);\n m_newMaterials.Add(created.material);\n m_getMaterialMemo[gltfMaterial] = created;\n return created;\n }\n\n Debug.LogErrorFormat(\"Failed to convert material {0}\", gltfMaterial.name);\n return null;\n }\n\n /// \n /// Returns a list of new materials that were created as part of the material\n /// conversion process.\n /// ", "answers": [" public List GetGeneratedMaterials() {"], "length": 590, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "45d96795-dae1-474e-87f2-0c19fd2af0f8", "reasoning": "The comment just described a method that returns the list of newly created Unity materials (stored in the private field m_newMaterials). The next line should therefore be the method signature that returns that list, typically a public method returning List and opening its body.", "reasoning_model_answer": "public List GetNewMaterials() {", "assistant_with_reasoning": "\nThe comment just described a method that returns the list of newly created Unity materials (stored in the private field m_newMaterials). The next line should therefore be the method signature that returns that list, typically a public method returning List and opening its body.\n\npublic List GetNewMaterials() {", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.568, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 5410, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "public List GetNewMaterials() {", "score": 0.87, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "package com.vladmihalcea.hibernate.masterclass.laboratory.fetch;\n\nimport com.vladmihalcea.hibernate.masterclass.laboratory.util.AbstractTest;\nimport org.apache.commons.lang3.builder.EqualsBuilder;\nimport org.apache.commons.lang3.builder.HashCodeBuilder;\nimport org.apache.commons.lang3.builder.ToStringBuilder;\nimport org.hibernate.Session;\nimport org.hibernate.criterion.CriteriaSpecification;\nimport org.hibernate.criterion.Restrictions;\nimport org.junit.Test;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport javax.persistence.*;\nimport java.util.LinkedHashSet;\nimport java.util.List;\nimport java.util.Set;\n\nimport static org.junit.Assert.*;\n\n/**\n * HibernateApiFetchStrategyTest - Test HQL and Criteria fetch plan overriding capabilities\n *\n * @author Vlad Mihalcea\n */\npublic class HibernateApiMultiEagerCollectionFetchStrategyTest extends AbstractTest {\n\n protected final Logger LOGGER = LoggerFactory.getLogger(getClass());\n\n private Long productId;\n\n @Override\n protected Class[] entities() {\n return new Class[] {\n WarehouseProductInfo.class,\n Importer.class,\n Image.class,\n Product.class,\n Company.class,\n SubVersion.class,\n Version.class,\n Review.class,\n };\n }\n\n @Override\n public void init() {\n super.init();\n productId = doInTransaction(new TransactionCallable() {\n @Override\n public Long execute(Session session) {\n Company company = new Company();\n company.setName(\"TV Company\");\n session.persist(company);\n\n Product product = new Product(\"tvCode\");\n product.setName(\"TV\");\n product.setCompany(company);\n\n Image frontImage = new Image();\n frontImage.setName(\"front image\");\n frontImage.setIndex(0);\n\n Image sideImage = new Image();\n sideImage.setName(\"side image\");\n sideImage.setIndex(1);\n\n product.addImage(frontImage);\n product.addImage(sideImage);\n\n WarehouseProductInfo warehouseProductInfo = new WarehouseProductInfo();\n warehouseProductInfo.setQuantity(101);\n product.addWarehouse(warehouseProductInfo);\n\n Importer importer = new Importer();\n importer.setName(\"Importer\");\n session.persist(importer);\n product.setImporter(importer);\n\n Review review1 = new Review();\n review1.setComment(\"Great product\");\n\n Review review2 = new Review();\n review2.setComment(\"Sensational product\");\n\n product.addReview(review1);\n product.addReview(review2);\n\n session.persist(product);\n return product.getId();\n }\n });\n }\n\n @Test\n public void testFetchChild() {\n doInTransaction(new TransactionCallable() {\n @Override\n public Void execute(Session session) {\n LOGGER.info(\"Fetch using find\");\n Product product = (Product) session.get(Product.class, productId);\n assertNotNull(product);\n return null;\n }\n });\n\n doInTransaction(new TransactionCallable() {\n @Override\n public Void execute(Session session) {\n LOGGER.info(\"Fetch using JPQL\");\n Product product = (Product) session.createQuery(\n \"select p \" +\n \"from Product p \" +\n \"where p.id = :productId\")\n .setParameter(\"productId\", productId)\n .uniqueResult();\n assertNotNull(product);\n return null;\n }\n });\n doInTransaction(new TransactionCallable() {\n @Override\n public Void execute(Session session) {\n\n LOGGER.info(\"Fetch using Criteria\");\n\n Product product = (Product) session.createCriteria(Product.class)\n .add(Restrictions.eq(\"id\", productId))\n .uniqueResult();\n assertNotNull(product);\n return null;\n }\n });\n doInTransaction(new TransactionCallable() {\n @Override\n public Void execute(Session session) {\n\n LOGGER.info(\"Fetch list using Criteria\");\n\n List products = session.createCriteria(Product.class)\n .add(Restrictions.eq(\"id\", productId))\n .list();\n assertEquals(4, products.size());\n assertSame(products.get(0), products.get(1));\n return null;\n }\n });\n doInTransaction(new TransactionCallable() {\n @Override\n public Void execute(Session session) {\n\n LOGGER.info(\"Fetch distinct list using Criteria\");\n\n List products = session.createCriteria(Product.class)\n .add(Restrictions.eq(\"id\", productId))\n .setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY)\n .list();\n assertEquals(1, products.size());\n return null;\n }\n });\n\n }\n\n @Entity(name = \"Company\")\n public static class Company {\n\n @Id\n @GeneratedValue(strategy = GenerationType.AUTO)\n private Long id;\n\n @Column(unique = true, updatable = false)\n private String name;\n\n public Long getId() {\n return id;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n @Override\n public int hashCode() {\n HashCodeBuilder hcb = new HashCodeBuilder();\n hcb.append(name);\n return hcb.toHashCode();\n }\n\n @Override\n public boolean equals(Object obj) {\n if (this == obj) {\n return true;\n }\n if (!(obj instanceof Company)) {\n return false;\n }\n Company that = (Company) obj;\n EqualsBuilder eb = new EqualsBuilder();\n eb.append(name, that.name);\n return eb.isEquals();\n }\n\n @Override\n public String toString() {\n ToStringBuilder tsb = new ToStringBuilder(this);\n tsb.append(\"id\", id);\n tsb.append(\"name\", name);\n return tsb.toString();\n }\n }\n\n @Entity(name = \"Image\")\n public static class Image {\n\n @Id\n @GeneratedValue(strategy = GenerationType.AUTO)\n private Long id;\n\n @Column(updatable = false)\n private String name;\n\n @Column(unique = true)\n private int index;\n\n @ManyToOne(fetch = FetchType.LAZY)\n private Product product;\n\n @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = \"image\", orphanRemoval = true)\n @OrderBy(\"type\")\n private Set versions = new LinkedHashSet();\n\n public Long getId() {\n return id;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public int getIndex() {\n return index;\n }\n\n public Product getProduct() {\n return product;\n }\n\n public void setProduct(Product product) {\n this.product = product;\n }\n\n public void setIndex(int index) {\n this.index = index;\n }\n\n public Set getVersions() {\n return versions;\n }\n\n public void addVersion(Version version) {\n versions.add(version);\n version.setImage(this);\n }\n\n public void removeVersion(Version version) {\n versions.remove(version);\n version.setImage(null);\n }\n\n @Override\n public int hashCode() {\n HashCodeBuilder hcb = new HashCodeBuilder();\n hcb.append(name);\n hcb.append(product);\n return hcb.toHashCode();\n }\n\n @Override\n public boolean equals(Object obj) {\n if (this == obj) {\n return true;\n }\n if (!(obj instanceof Image)) {\n return false;\n }\n Image that = (Image) obj;\n EqualsBuilder eb = new EqualsBuilder();\n eb.append(name, that.name);\n eb.append(product, that.product);\n return eb.isEquals();\n }\n\n @Override", "answers": [" public String toString() {"], "length": 626, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "c753335b-5097-4eda-b201-df141a59d420", "reasoning": "The Image entity already defines hashCode() and equals() with @Override annotations. The next logical overridden method is toString(), following the pattern used in other entity classes. Therefore the next line after the @Override annotation should start the toString method declaration.", "reasoning_model_answer": "public String toString() {", "assistant_with_reasoning": "\nThe Image entity already defines hashCode() and equals() with @Override annotations. The next logical overridden method is toString(), following the pattern used in other entity classes. Therefore the next line after the @Override annotation should start the toString method declaration.\n\npublic String toString() {", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 2.16, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 9046, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "public String toString() {", "score": 0.87, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "#!/usr/bin/env python\n\nimport json\nimport logging\nimport os\nimport string\nimport subprocess\nimport sys\nimport time\nimport uuid\n\nfrom random import choice\n\nfrom twisted.internet import reactor, defer\nfrom twisted.internet.task import deferLater\nfrom twisted.internet.defer import CancelledError\nfrom twisted.python import log\nfrom twisted.web import server, resource, http\nfrom twisted.web.resource import Resource\nfrom twisted.web.server import NOT_DONE_YET\nfrom twisted.web.static import File\n\nfrom vtk.web import upload\n\ntry:\n import argparse\nexcept ImportError:\n import _argparse as argparse\n\n\nsample_config_file = \"\"\"\nHere is a sample of what a configuration file could looks like:\n\n {\n ## ===============================\n ## General launcher configuration\n ## ===============================\n\n \"configuration\": {\n \"host\" : \"localhost\",\n \"port\" : 8080,\n \"endpoint\": \"paraview\", # SessionManager Endpoint\n \"content\": \"/.../www\", # Optional: Directory shared over HTTP\n \"proxy_file\" : \"/.../proxy-mapping.txt\", # Proxy-Mapping file for Apache\n \"sessionURL\" : \"ws://${host}:${port}/ws\", # ws url used by the client to connect to the started process\n \"timeout\" : 25, # Wait time in second after process start\n \"log_dir\" : \"/.../viz-logs\", # Directory for log files\n \"upload_dir\" : \"/.../data\", # If launcher should act as upload server, where to put files\n \"fields\" : [\"file\", \"host\", \"port\", \"updir\"] # List of fields that should be send back to client\n },\n\n ## ===============================\n ## Useful session vars for client\n ## ===============================\n\n \"sessionData\" : { \"updir\": \"/Home\" }, # Tells client which path to updateFileBrowser after uploads\n\n ## ===============================\n ## Resources list for applications\n ## ===============================\n\n \"resources\" : [ { \"host\" : \"localhost\", \"port_range\" : [9001, 9003] } ],\n\n ## ===============================\n ## Set of properties for cmd line\n ## ===============================\n\n \"properties\" : {\n \"build_dir\" : \"/.../build\",\n \"python_exec\" : \"/.../build/bin/vtkpython\",\n \"WWW\" : \"/.../build/www\",\n \"source_dir\": \"/.../src\"\n },\n\n ## ===============================\n ## Application list with cmd line\n ## ===============================\n\n \"apps\" : {\n \"cone\" : {\n \"cmd\" : [\n \"${python_exec}\", \"${build_dir}/Wrapping/Python/vtk/web/vtk_web_cone.py\", \"--content\", \"${WWW}\", \"--port\", \"$port\", \"-f\", \"--authKey\", \"$secret\"\n ],\n \"ready_line\" : \"Starting factory\"\n },\n \"test\" : {\n \"cmd\" : [\n \"${python_exec}\", \"${build_dir}/PhylogeneticTree/server/vtk_web_phylogenetic_tree.py\", \"--content\", \"${WWW}\" ],\n \"ready_line\" : \"Starting factory\"\n },\n \"launcher\" : {\n \"cmd\" : [\n \"/home/kitware/launcher.sh\", \"${host}\", \"${port}\", \"${node}\", \"${app}\", \"${user}\", \"${password}\", \"${secret}\" ],\n \"ready_line\" : \"Good to go\"\n }\n }\n }\n\"\"\"\n\n# =============================================================================\n# Helper module methods\n# =============================================================================\n\ndef generatePassword():\n return ''.join(choice(string.letters + string.digits) for _ in xrange(16))\n\n# -----------------------------------------------------------------------------\n\ndef validateKeySet(obj, expected_keys, object_name):\n all_key_found = True\n for key in expected_keys:\n if not obj.has_key(key):\n print \"ERROR: %s is missing %s key.\" % (object_name, key)\n all_key_found = False\n return all_key_found\n\n# -----------------------------------------------------------------------------\n\ndef replaceVariables(template_str, variable_list):\n for key_pair in variable_list:\n item_template = string.Template(template_str)\n template_str = item_template.safe_substitute(key_pair)\n\n if \"$\" in template_str:\n logging.error(\"Some properties could not be resolved: \" + template_str)\n\n return template_str\n\n# -----------------------------------------------------------------------------\n\ndef replaceList(template_list, variable_list):\n result_list = []\n for str in template_list:\n result_list.append(replaceVariables(str, variable_list))\n return result_list\n\n# -----------------------------------------------------------------------------\n\ndef filterResponse(obj, public_keys):\n public_keys.extend(['id', 'sessionURL', 'sessionManagerURL'])\n filtered_output = {}\n for field in obj:\n if field in public_keys:\n filtered_output[field] = obj[field]\n return filtered_output\n\n# -----------------------------------------------------------------------------\n\ndef extractSessionId(request):\n path = request.path.split('/')\n if len(path) < 3:\n return None\n return str(path[2])\n\n# =============================================================================\n# Session manager\n# =============================================================================\n\nclass SessionManager(object):\n\n def __init__(self, config, mapping):\n self.sessions = {}\n self.config = config\n self.resources = ResourceManager(config[\"resources\"])\n self.mapping = mapping\n\n def createSession(self, options):\n # Assign id and store options\n id = str(uuid.uuid1())\n\n # Assign resource to session\n host, port = self.resources.getNextResource()\n\n # Do we have resources\n if host:\n options['id'] = id\n options['host'] = host\n options['port'] = port\n if not options.has_key('secret'):\n options['secret'] = generatePassword()\n options['sessionURL'] = replaceVariables(self.config['configuration']['sessionURL'], [options, self.config['properties']])\n options['cmd'] = replaceList(self.config['apps'][options['application']]['cmd'], [options, self.config['properties']])\n\n if self.config.has_key('sessionData') :\n for key in self.config['sessionData'] :\n options[key] = replaceVariables(self.config['sessionData'][key], [options, self.config['properties']])\n\n self.sessions[id] = options\n self.mapping.update(self.sessions)\n return options\n\n return None\n\n def deleteSession(self, id):\n host = self.sessions[id]['host']\n port = self.sessions[id]['port']\n self.resources.freeResource(host, port)\n del self.sessions[id]\n self.mapping.update(self.sessions)\n\n def getSession(self, id):\n if self.sessions.has_key(id):\n return self.sessions[id]\n return None\n\n# =============================================================================\n# Proxy manager\n# =============================================================================\n\nclass ProxyMappingManager(object):\n\n def update(sessions):\n pass\n\nclass ProxyMappingManagerTXT(ProxyMappingManager):\n\n def __init__(self, file_path, pattern=\"%s %s:%d\\n\"):\n self.file_path = file_path\n self.pattern = pattern\n\n def update(self, sessions):\n with open(self.file_path, \"w\") as map_file:\n for id in sessions:", "answers": [" map_file.write(self.pattern % (id, sessions[id]['host'], sessions[id]['port']))"], "length": 636, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "b390de18-b503-44fe-9ce4-94d4c9e8998e", "reasoning": "In ProxyMappingManagerTXT.update, after opening the mapping file for writing, we iterate over each session id in the sessions dict. For each session we need to write a line using the provided pattern, inserting the session id, host, and port from the session's options. Therefore the next line should write to the file using self.pattern and the session data.", "reasoning_model_answer": "map_file.write(self.pattern % (id, sessions[id]['host'], sessions[id]['port']))", "assistant_with_reasoning": "\nIn ProxyMappingManagerTXT.update, after opening the mapping file for writing, we iterate over each session id in the sessions dict. For each session we need to write a line using the provided pattern, inserting the session id, host, and port from the session's options. Therefore the next line should write to the file using self.pattern and the session data.\n\nmap_file.write(self.pattern % (id, sessions[id]['host'], sessions[id]['port']))", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 2.769, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 7638, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "map_file.write(self.pattern % (id, sessions[id]['host'], sessions[id]['port']))", "score": 0.91, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "using System;\nusing SharpVectors.Dom;\nusing SharpVectors.Dom.Css;\nusing SharpVectors.Dom.Events;\nusing SharpVectors.Dom.Stylesheets;\nusing SharpVectors.Dom.Svg;\nusing SharpVectors.Dom.Views;\nusing System.Xml;\n\n\nnamespace SharpVectors.Scripting\n{\n\n /// \n /// IScriptableDomTimeStamp\n /// \n public class ScriptableDomTimeStamp : ScriptableObject, IScriptableDomTimeStamp\n {\n public ScriptableDomTimeStamp(object baseObject) : base (baseObject) { }\n }\n\n\n\t\t/// \n\t\t/// Implementation wrapper for IScriptableDomImplementation\n\t\t/// \n\t\tpublic class ScriptableDomImplementation : ScriptableObject, IScriptableDomImplementation\n\t\t{\n\t\t\tpublic ScriptableDomImplementation(object baseObject) : base (baseObject) { }\n\n\t\t\t#region Methods - IScriptableDomImplementation\n\t\t\tpublic bool hasFeature(string feature, string version)\n\t\t\t{\n\t\t\t\treturn ((XmlImplementation)baseObject).HasFeature(feature, version);\n\t\t\t}\n\n\t\t\tpublic IScriptableDocumentType createDocumentType(string qualifiedName, string publicId, string systemId)\n\t\t\t{\n\t\t\t\tthrow new NotSupportedException();\n //object result = ((XmlImplementation)baseObject).CreateDocumentType(qualifiedName, publicId, systemId);\n\t\t\t\t//return (result != null) ? (IScriptableDocumentType)ScriptableObject.CreateWrapper(result) : null;\n\t\t\t}\n\n\t\t\tpublic IScriptableDocument createDocument(string namespaceURI, string qualifiedName, IScriptableDocumentType doctype)\n\t\t\t{\n throw new NotSupportedException();\n //object result = ((XmlImplementation)baseObject).CreateDocument(namespaceURI, qualifiedName, ((IDocumentType)((ScriptableDocumentType)doctype).baseObject));\n\t\t\t\t//return (result != null) ? (IScriptableDocument)ScriptableObject.CreateWrapper(result) : null;\n\t\t\t}\n\t\t\t#endregion\n\t\t}\n\n\t\t/// \n\t\t/// Implementation wrapper for IScriptableNode\n\t\t/// \n\t\tpublic class ScriptableNode : ScriptableObject, IScriptableNode\n\t\t{\n\t\t\tconst ushort ELEMENT_NODE = 1;\n\t\t\tconst ushort ATTRIBUTE_NODE = 2;\n\t\t\tconst ushort TEXT_NODE = 3;\n\t\t\tconst ushort CDATA_SECTION_NODE = 4;\n\t\t\tconst ushort ENTITY_REFERENCE_NODE = 5;\n\t\t\tconst ushort ENTITY_NODE = 6;\n\t\t\tconst ushort PROCESSING_INSTRUCTION_NODE = 7;\n\t\t\tconst ushort COMMENT_NODE = 8;\n\t\t\tconst ushort DOCUMENT_NODE = 9;\n\t\t\tconst ushort DOCUMENT_TYPE_NODE = 10;\n\t\t\tconst ushort DOCUMENT_FRAGMENT_NODE = 11;\n\t\t\tconst ushort NOTATION_NODE = 12;\n\n\t\t\tpublic ScriptableNode(object baseObject) : base (baseObject) { }\n\n\t\t\t#region Methods - IScriptableNode\n\t\t\tpublic IScriptableNode insertBefore(IScriptableNode newChild, IScriptableNode refChild)\n\t\t\t{\n\t\t\t\tobject result = ((INode)baseObject).InsertBefore(((XmlNode)((ScriptableNode)newChild).baseObject), ((XmlNode)((ScriptableNode)refChild).baseObject));\n\t\t\t\treturn (result != null) ? (IScriptableNode)ScriptableObject.CreateWrapper(result) : null;\n\t\t\t}\n\n\t\t\tpublic IScriptableNode replaceChild(IScriptableNode newChild, IScriptableNode oldChild)\n\t\t\t{\n\t\t\t\tobject result = ((INode)baseObject).ReplaceChild(((XmlNode)((ScriptableNode)newChild).baseObject), ((XmlNode)((ScriptableNode)oldChild).baseObject));\n\t\t\t\treturn (result != null) ? (IScriptableNode)ScriptableObject.CreateWrapper(result) : null;\n\t\t\t}\n\n\t\t\tpublic IScriptableNode removeChild(IScriptableNode oldChild)\n\t\t\t{\n\t\t\t\tobject result = ((INode)baseObject).RemoveChild(((XmlNode)((ScriptableNode)oldChild).baseObject));\n\t\t\t\treturn (result != null) ? (IScriptableNode)ScriptableObject.CreateWrapper(result) : null;\n\t\t\t}\n\n\t\t\tpublic IScriptableNode appendChild(IScriptableNode newChild)\n\t\t\t{\n\t\t\t\tobject result = ((INode)baseObject).AppendChild(((XmlNode)((ScriptableNode)newChild).baseObject));\n\t\t\t\treturn (result != null) ? (IScriptableNode)ScriptableObject.CreateWrapper(result) : null;\n\t\t\t}\n\n\t\t\tpublic bool hasChildNodes()\n\t\t\t{\n\t\t\t\treturn ((INode)baseObject).HasChildNodes;\n\t\t\t}\n\n\t\t\tpublic IScriptableNode cloneNode(bool deep)\n\t\t\t{\n\t\t\t\tobject result = ((INode)baseObject).CloneNode(deep);\n\t\t\t\treturn (result != null) ? (IScriptableNode)ScriptableObject.CreateWrapper(result) : null;\n\t\t\t}\n\n\t\t\tpublic void normalize()\n\t\t\t{\n\t\t\t\t((INode)baseObject).Normalize();\n\t\t\t}\n\n\t\t\tpublic bool isSupported(string feature, string version)\n\t\t\t{\n\t\t\t\treturn ((INode)baseObject).Supports(feature, version);\n\t\t\t}\n\n\t\t\tpublic bool hasAttributes()\n\t\t\t{\n\t\t\t\treturn ((INode)baseObject).Attributes.Count > 0;\n\t\t\t}\n\t\t\t#endregion\n\n\t\t\t#region Properties - IScriptableNode\n\t\t\tpublic string nodeName\n\t\t\t{\n\t\t\t\tget { return ((INode)baseObject).Name; }\n\t\t\t}\n\n\t\t\tpublic string nodeValue\n\t\t\t{\n\t\t\t\tget { return ((INode)baseObject).Value; }\n\t\t\t\tset { ((INode)baseObject).Value = value; }\n\t\t\t}\n\n\t\t\tpublic ushort nodeType\n\t\t\t{\n\t\t\t\tget { return (ushort)((INode)baseObject).NodeType; }\n\t\t\t}\n\n\t\t\tpublic IScriptableNode parentNode\n\t\t\t{\n\t\t\t\tget { object result = ((INode)baseObject).ParentNode; return (result != null) ? (IScriptableNode)ScriptableObject.CreateWrapper(result) : null; }\n\t\t\t}\n\n\t\t\tpublic IScriptableNodeList childNodes\n\t\t\t{\n\t\t\t\tget { object result = ((INode)baseObject).ChildNodes; return (result != null) ? (IScriptableNodeList)ScriptableObject.CreateWrapper(result) : null; }\n\t\t\t}\n\n\t\t\tpublic IScriptableNode firstChild\n\t\t\t{\n\t\t\t\tget { object result = ((INode)baseObject).FirstChild; return (result != null) ? (IScriptableNode)ScriptableObject.CreateWrapper(result) : null; }\n\t\t\t}\n\n\t\t\tpublic IScriptableNode lastChild\n\t\t\t{\n\t\t\t\tget { object result = ((INode)baseObject).LastChild; return (result != null) ? (IScriptableNode)ScriptableObject.CreateWrapper(result) : null; }\n\t\t\t}\n\n\t\t\tpublic IScriptableNode previousSibling\n\t\t\t{\n\t\t\t\tget { object result = ((INode)baseObject).PreviousSibling; return (result != null) ? (IScriptableNode)ScriptableObject.CreateWrapper(result) : null; }\n\t\t\t}\n\n\t\t\tpublic IScriptableNode nextSibling\n\t\t\t{\n\t\t\t\tget { object result = ((INode)baseObject).NextSibling; return (result != null) ? (IScriptableNode)ScriptableObject.CreateWrapper(result) : null; }\n\t\t\t}\n\n\t\t\tpublic IScriptableNamedNodeMap attributes\n\t\t\t{\n\t\t\t\tget { object result = ((INode)baseObject).Attributes; return (result != null) ? (IScriptableNamedNodeMap)ScriptableObject.CreateWrapper(result) : null; }\n\t\t\t}\n\n\t\t\tpublic IScriptableDocument ownerDocument\n\t\t\t{\n\t\t\t\tget { object result = ((INode)baseObject).OwnerDocument; return (result != null) ? (IScriptableDocument)ScriptableObject.CreateWrapper(result) : null; }\n\t\t\t}\n\n\t\t\tpublic string namespaceURI\n\t\t\t{\n\t\t\t\tget { return ((INode)baseObject).NamespaceURI; }\n\t\t\t}\n\n\t\t\tpublic string prefix\n\t\t\t{\n\t\t\t\tget { return ((INode)baseObject).Prefix; }\n\t\t\t\tset { ((INode)baseObject).Prefix = value; }\n\t\t\t}\n\n\t\t\tpublic string localName\n\t\t\t{\n\t\t\t\tget { return ((INode)baseObject).LocalName; }\n\t\t\t}\n\n\t\t\t#endregion\n\t\t}\n\n\t\t/// \n\t\t/// Implementation wrapper for IScriptableNodeList\n\t\t/// \n\t\tpublic class ScriptableNodeList : ScriptableObject, IScriptableNodeList\n\t\t{\n\t\t\tpublic ScriptableNodeList(object baseObject) : base (baseObject) { }\n\n\t\t\t#region Methods - IScriptableNodeList\n\t\t\tpublic IScriptableNode item(ulong index)\n\t\t\t{\n\t\t\t\tobject result = ((INodeList)baseObject)[index];\n\t\t\t\treturn (result != null) ? (IScriptableNode)ScriptableObject.CreateWrapper(result) : null;\n\t\t\t}\n\t\t\t#endregion\n\n\t\t\t#region Properties - IScriptableNodeList\n\t\t\tpublic ulong length\n\t\t\t{", "answers": ["\t\t\t\tget { return ((INodeList)baseObject).Count; }"], "length": 650, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "08d5a25e-688a-42d5-99c0-784c775ade22", "reasoning": "The code defines a ScriptableNodeList wrapper. After declaring the property 'public ulong length' and opening the brace, the next line should provide the getter that returns the underlying list's length. The underlying object is cast to INodeList, which exposes a Length (or similar) property. So the next line is the getter returning that value.", "reasoning_model_answer": "get { return ((INodeList)baseObject).Length; }", "assistant_with_reasoning": "\nThe code defines a ScriptableNodeList wrapper. After declaring the property 'public ulong length' and opening the brace, the next line should provide the getter that returns the underlying list's length. The underlying object is cast to INodeList, which exposes a Length (or similar) property. So the next line is the getter returning that value.\n\nget { return ((INodeList)baseObject).Length; }", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 6.261, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 7473, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "get { return ((INodeList)baseObject).Length; }", "score": 0.88, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n\npackage org.apache.oodt.profile;\n\nimport org.apache.jena.rdf.model.Model;\nimport org.apache.jena.rdf.model.ModelFactory;\nimport org.apache.jena.rdf.model.Resource;\n\nimport java.io.Serializable;\nimport java.net.URI;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Map;\n\nimport org.apache.oodt.commons.util.Documentable;\nimport org.apache.oodt.commons.util.XML;\nimport org.w3c.dom.DOMException;\nimport org.w3c.dom.Document;\nimport org.w3c.dom.DocumentType;\nimport org.w3c.dom.Element;\nimport org.w3c.dom.Node;\nimport org.w3c.dom.NodeList;\nimport org.xml.sax.SAXException;\n\nimport java.io.BufferedReader;\nimport java.io.FileReader;\nimport java.io.OutputStreamWriter;\n\n/**\n * A profile.\n *\n * Objects of this class are profiles. Profiles are metadata descriptions of resources.\n *\n * @author Kelly\n */\npublic class Profile implements Serializable, Cloneable, Comparable, Documentable {\n /** Serial version unique ID. */\n static final long serialVersionUID = -3936851809184360591L;\n\n\t/** The formal public identifier of the profiles DTD. */\n\tpublic static final String PROFILES_DTD_FPI = \"-//JPL//DTD Profile 1.1//EN\";\n\n\t/** The system identifier of the profiles DTD. */\n\tpublic static String PROFILES_DTD_URL = \"http://oodt.jpl.nasa.gov/grid-profile/dtd/prof.dtd\";\n\n\t/**\n\t * Create a list of profiles by deserializing data from the given XML element.\n\t *\n\t * @param root Either a <profiles> or a <profile> element.\n\t * @param factory Factory for creation of profile-related objects.\n\t * @return A list of profiles.\n\t */\n\tpublic static List createProfiles(Element root, ObjectFactory factory) {\n\t\tList profiles = new ArrayList();\n\t\tif (\"profile\".equals(root.getNodeName()))\n\t\t\t// The root is a , so add the single profile to the list.\n\t\t\tprofiles.add(factory.createProfile((Element) root));\n\t\telse if (\"profiles\".equals(root.getNodeName())) {\n\t\t\t// The root is a , so add each to the list.\n\t\t\tNodeList children = root.getChildNodes();\n\t\t\tfor (int i = 0; i < children.getLength(); ++i) {\n\t\t\t\tNode node = children.item(i);\n\t\t\t\tif (\"profile\".equals(node.getNodeName()))\n\t\t\t\t\tprofiles.add(factory.createProfile((Element) node));\n\t\t\t}\n\t\t} else throw new IllegalArgumentException(\"Expected a or top level element but got \"\n\t\t\t+ root.getNodeName());\n\t\treturn profiles;\n\t}\n\n\n\t/**\n\t * Create a list of profiles by deserializing data from the given XML element.\n\t *\n\t * This method uses the default factory that yields objects of this package,\n\t * namely {@link Profile}, {@link ProfileAttributes}, {@link ResourceAttributes},\n\t * and {@link ProfileElement} and its subclasses.\n\t *\n\t * @param root Either a <profiles> or a <profile> element.\n\t * @return A list of profiles.\n\t */\n\tpublic static List createProfiles(Element root) {\n\t\treturn createProfiles(root, new DefaultFactory());\n\t}\n\n\t/**\n\t * Create a blank profile.\n\t */\n\tpublic Profile() {\n\t\tprofAttr = new ProfileAttributes();\n\t\tresAttr = new ResourceAttributes(this);\n\t}\n\n\t/**\n\t * Create a profile from an XML document.\n\t *\n\t * @param string The XML document (as a string).\n\t * @throws SAXException If the string can't be parsed.\n\t */\n\tpublic Profile(String string) throws SAXException {\n\t\tthis(XML.parse(string).getDocumentElement(), new DefaultFactory());\n\t}\n\n\t/**\n\t * Create a profile from an XML document.\n\t *\n\t * @param string The XML document (as a string).\n\t * @param factory Object factory to use.\n\t * @throws SAXException If the string can't be parsed.\n\t */\n\tpublic Profile(String string, ObjectFactory factory) throws SAXException {\n\t\tthis(XML.parse(string).getDocumentElement(), factory);\n\t}\n\n\t/**\n\t * Creates a new Profile instance.\n\t *\n\t * @param root a Node value.\n\t */\n\tpublic Profile(Node root) {\n\t\tthis(root, new DefaultFactory());\n\t}\n\n\t/**\n\t * Create a profile from an XML document.\n\t *\n\t * @param root The <profile> element.\n\t */\n\tpublic Profile(Node root, ObjectFactory factory) {\n\t\tif (!root.getNodeName().equals(\"profile\"))\n\t\t\tthrow new IllegalArgumentException(\"Construct a Profile from a element, not a <\"\n\t\t\t\t+ root.getNodeName() + \">\");\n\t\tNodeList children = root.getChildNodes();\n\t\tfor (int i = 0; i < children.getLength(); ++i) {\n\t\t\tNode node = children.item(i);\n\t\t\tif (\"profAttributes\".equals(node.getNodeName()))\n\t\t\t\tprofAttr = factory.createProfileAttributes((Element) node);\n\t\t\telse if (\"resAttributes\".equals(node.getNodeName()))", "answers": ["\t\t\t\tresAttr = factory.createResourceAttributes(this, (Element) node);"], "length": 659, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "aef5c23b-94e1-4346-a692-3b72efbb278d", "reasoning": "We are inside the Profile(Node, ObjectFactory) constructor, iterating over child nodes of the element. The code already handles a child named \"profAttributes\" by assigning profAttr via factory.createProfileAttributes. The next conditional checks for a child named \"resAttributes\"; the logical action is to assign the resource attributes field using the factory, i.e., call factory.createResourceAttributes on the element and store it in resAttr. Therefore the next line should be the assignment statement for resAttr.", "reasoning_model_answer": "resAttr = factory.createResourceAttributes((Element) node);", "assistant_with_reasoning": "\nWe are inside the Profile(Node, ObjectFactory) constructor, iterating over child nodes of the element. The code already handles a child named \"profAttributes\" by assigning profAttr via factory.createProfileAttributes. The next conditional checks for a child named \"resAttributes\"; the logical action is to assign the resource attributes field using the factory, i.e., call factory.createResourceAttributes on the element and store it in resAttr. Therefore the next line should be the assignment statement for resAttr.\n\nresAttr = factory.createResourceAttributes((Element) node);", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.23, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 5471, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "resAttr = factory.createResourceAttributes((Element) node);", "score": 0.92, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom PyQt4 import QtCore, QtGui, uic\nimport sys, os, imp, string\nfrom src.clientGui import QClient\n\nbasePath = sys.argv[0].split('/')\nsys.path.append(os.path.abspath(sys.argv[0]).rpartition('/')[0].rpartition('/')[0])\nfrom SamysBeast import SamysBeast\nfrom src.clientGui.QWorld import QWorld\nfrom src.clientGui.ClientGuiLogic import *\n\nclass ClientGui(QtGui.QMainWindow):\n \"\"\"\n extended by QtGui.QMainWindow\n Class for PyQt4 based graphical user interface displaying the progress of PyBeasts game. \n This Class is extended by QMainWindow and represents the mainWindow of the gui\n \"\"\"\n\n def __init__(self):\n \"\"\"\n constructor\n \"\"\"\n QtGui.QMainWindow.__init__(self)\n self.setFixedSize(1024,576)\n \n self.widgets={}\n self.widgets['choose']=uic.loadUi('widgetChoose.ui')\n self.widgets['beasts']=uic.loadUi('widgetBeasts.ui')\n self.widgets['server']=uic.loadUi('widgetServer.ui')\n self.widgets['play']=uic.loadUi('widgetPlay.ui')\n self.widgets['waiting']=uic.loadUi('widgetWaiting.ui')\n self.widgets['countdown']=uic.loadUi('widgetCountdown.ui')\n \n self.startTime=None\n self.automaticDestination=12\n self.beast = None\n self.firstRound = True\n self.currentServer = None\n self.serverMap = {}\n self.sleepAfterMove=QtCore.QTimer()\n self.sleepDuringMove=QtCore.QTimer()\n self.sleepBeforeMove=QtCore.QTimer()\n self.client = QClient(self)\n self.timerProgressBar = QtCore.QTimer()\n self.countdownTimer = QtCore.QTimer()\n self.availableServers = CheckTeamServerAvailability(self)\n self.handling = 'manual'\n self.gameWorldState=None\n self.sprintCooldown=0\n self.roundsWorld=None\n self.destination=12\n self.startTime = None\n self.countdownBarStartTime = None\n\n self.widgets['play'].labelWonOrLost.hide()\n self.widgets['beasts'].labelLogging.hide()\n self.widgets['play'].widgetSwitchRounds.hide()\n self.widgets['play'].widgetGameEnded.hide()\n self.widgets['server'].widgetAddNew.hide()\n self.widgets['server'].labelLogging.hide()\n \n self.connect(self.sleepDuringMove, QtCore.SIGNAL('timeout()'),self.stopSleepDuringMove)\n self.connect(self.sleepBeforeMove, QtCore.SIGNAL('timeout()'),self.stopSleepBeforeMove)\n self.connect(self.sleepAfterMove, QtCore.SIGNAL('timeout()'),self.stopSleepAfterMove)\n self.connect(self.client, QtCore.SIGNAL('sendAutomaicDestination(QString)'),self.setAutomaticDestination)\n self.connect(self.client, QtCore.SIGNAL('sendStartTime(QString)'),self.setStartTime) \n self.connect(self.widgets['play'].widgetEnvironment,QtCore.SIGNAL('sendKeyboardMove(QString)'),self.sendKeyboardMove)\n self.connect(self.timerProgressBar, QtCore.SIGNAL('timeout()'), self.updateWaitingProgressBar)\n self.connect(self.availableServers, QtCore.SIGNAL('fillTeamServerList(PyQt_PyObject)'), self.fillTeamServerList)\n self.connect(self.countdownTimer, QtCore.SIGNAL(\"timeout()\"), self.updateCountdown)\n self.connect(self.client, QtCore.SIGNAL(\"notify(QString,QString,QString)\"), self.notify)\n self.connect(self.client, QtCore.SIGNAL(\"clientConnected(QString)\"), self.clientConnected)\n \n self.connect(self.widgets['beasts'].toolButtonFileDialog, QtCore.SIGNAL(\"clicked()\"), self.btnBuildFileDialogBeasts)\n self.connect(self.widgets['beasts'].pushButtonBack, QtCore.SIGNAL(\"clicked()\"), self.widgets['choose'].show)\n self.connect(self.widgets['beasts'].pushButtonNext, QtCore.SIGNAL(\"clicked()\"), self.btnChooseBeast)\n \n self.connect(self.widgets['choose'].manual_play_btn, QtCore.SIGNAL(\"clicked()\"), self.btnSetHandling)\n self.connect(self.widgets['choose'].random_beast_btn, QtCore.SIGNAL(\"clicked()\"), self.btnSetHandling)\n self.connect(self.widgets['choose'].custom_beast_btn, QtCore.SIGNAL(\"clicked()\"), self.btnSetHandling)\n \n self.connect(self.widgets['countdown'].pushButtonCancel, QtCore.SIGNAL(\"clicked()\"), self.btnCancelAndLeaveServer)\n \n self.connect(self.widgets['play'].pushButtonPreviousRound, QtCore.SIGNAL(\"clicked()\"), self.btnRoundDecrement)\n self.connect(self.widgets['play'].pushButtonNextRound, QtCore.SIGNAL(\"clicked()\"), self.btnRoundIncrement)\n self.connect(self.widgets['play'].pushButtonLastRound, QtCore.SIGNAL(\"clicked()\"), self.btnJumpToLastRound)\n self.connect(self.widgets['play'].pushButtonFirstRound, QtCore.SIGNAL(\"clicked()\"), self.btnJumpToFirstRound)\n self.connect(self.widgets['play'].pushButtonRegisterAgain, QtCore.SIGNAL(\"clicked()\"), self.btnRegisterAgain)\n self.connect(self.widgets['play'].pushButtonLeaveServer, QtCore.SIGNAL(\"clicked()\"), self.btnLeaveServer)\n self.connect(self.widgets['play'].checkBoxWorld, QtCore.SIGNAL(\"stateChanged(int)\"), self.cbChangeWorldView)\n self.connect(self.widgets['play'].pushButtonLeaveGame, QtCore.SIGNAL(\"clicked()\"), self.btnCancelAndLeaveServer)\n \n self.connect(self.widgets['server'].pushButtonConnectToTeamServer, QtCore.SIGNAL('clicked()'),self.btnConnectToTeamServer)\n self.connect(self.widgets['server'].pushButtonBack, QtCore.SIGNAL(\"clicked()\"), self.widgets['choose'].show)\n self.connect(self.widgets['server'].pushButtonConnect, QtCore.SIGNAL(\"clicked()\"), self.btnConnectToNewServer) \n self.connect(self.widgets['server'].pushButtonNext, QtCore.SIGNAL(\"clicked()\"), self.btnConnectClient) \n self.connect(self.widgets['server'].toolButtonFileDialog, QtCore.SIGNAL(\"clicked()\"), self.btnBuildFileDialogCertificate)\n \n self.connect(self.widgets['waiting'].pushButtonCancel, QtCore.SIGNAL(\"clicked()\"), self.btnCancelAndLeaveServer)\n \n for child in self.widgets['play'].groupBoxMove.children():\n self.connect(child, QtCore.SIGNAL(\"clicked()\"), self.btnSendManualMove)\n \n for widget in self.widgets.values():\n widget.hide()\n widget.setParent(self)\n \n readServersFromFile(self.widgets['server'].comboBoxHostPortCert,self.serverMap) \n \n rect = self.geometry()\n rect.moveCenter(QtGui.QApplication.desktop().availableGeometry().center())\n self.setGeometry(rect)\n \n self.widgets['choose'].show()\n self.availableServers.start()\n self.show()\n \n def setAutomaticDestination(self,destination):\n \"\"\"\n Sets the instance variable automaticDestination. \n It is called over a SIGNAL from QClient and sends the destination which was calculated by the costom beast for next move.\n @param destination QString: destination which was calculated by the costom beast\n \"\"\"\n if destination!='?' and int(destination) in (0,2,4,10,14,20,22,24):\n self.sprintCooldown=4\n \n self.automaticDestination=destination\n \n \n def updateWaitingProgressBar(self):\n \"\"\"\n method for updating a progress bars value. \n it is connected to the timeout()-signal of the self.timerProgressBar which will be started to update progressBarWaiting on the WAITING widget \n \"\"\"\n updateWaitingProgressBar(self.widgets['waiting'].progressBarWaiting)\n \n def cbChangeWorldView(self):\n \"\"\"\n checkBox method: connected to checkBoxWorld in PLAY widget\n changes between showing the big worlds widget and the play environment widget on PLAY widget depending on the check box condition\n \"\"\"\n if self.widgets['play'].checkBoxWorld.isChecked():\n self.widgets['play'].widgetWorld.show()\n self.widgets['play'].widgetEnvironment.hide()\n return\n self.widgets['play'].widgetWorld.hide()\n self.widgets['play'].widgetEnvironment.show() \n \n def btnJumpToLastRound(self):\n \"\"\"\n pushButton method: connected to pushButtonLastRound on PLAY widget\n jumps to the last played round and order to draw it by calling setWorldRound()\n \"\"\"\n self.roundsWorld.setStatusTip(str(len(self.gameWorldState)-1))\n self.setWorldRound()\n \n def btnJumpToFirstRound(self):\n \"\"\"\n pushButton method: connected to pushButtonFirstRound on PLAY widget\n jumps to the first played round and order to draw it by calling setWorldRound()\n \"\"\"\n self.roundsWorld.setStatusTip(str(0))\n self.setWorldRound()\n \n def btnCancelAndLeaveServer(self):\n \"\"\"\n pushButton method: connected to pushButtonLeaveGame on PLAY widget, pushButtonCancel on WAITING widget, pushButtonCancel on COUNTDOWN widget\n disconnects client from current server and shows the SERVER widget again\n \"\"\"\n self.widgets['play'].checkBoxWorld.setChecked(False)\n self.widgets['play'].widgetEnvironment.releaseKeyboard()\n self.emit(QtCore.SIGNAL('leaveServer()'))\n self.countdownTimer.stop()\n self.widgets['play'].widgetGameEnded.hide()\n if self.roundsWorld!=None:\n self.roundsWorld.hide()\n for widget in self.widgets.values():\n widget.hide() \n self.widgets['server'].show() \n \n def btnChooseBeast(self):\n \"\"\"\n pushButton method: connected to pushButtonNext on BEASTS widget\n first checks if the user wants to use one of the available custom beasts. if so the chosen beast will be the beast to play with\n if not, the user wants to use a own implemented beast. if all parameters correct (file path,module name,class name) \n the beast module will be imported and set to the beast to play with\n \"\"\" \n if self.widgets['beasts'].lineEditOwnImplementation.text() == '':\n beast = str(self.widgets['beasts'].comboBoxAvailableBeasts.currentText())\n try:\n beastInst = getattr(sys.modules[beast], beast)\n except:\n self.widgets['beasts'].labelLogging.setText('no beast chosen!')\n self.widgets['beasts'].labelLogging.show()\n return \n \n else:\n try: \n modName = str(self.widgets['beasts'].lineEditModuleName.text())\n beastName = str(self.widgets['beasts'].lineEditClassName.text())\n filepath = str(self.widgets['beasts'].lineEditOwnImplementation.text())\n \n imp.load_source(modName, filepath) \n beastInst = getattr(sys.modules[modName], beastName)\n \n except:\n self.widgets['beasts'].labelLogging.setText('invalid file path, module name or class name') \n self.widgets['beasts'].labelLogging.show() \n return\n \n self.widgets['beasts'].labelLogging.hide()\n self.beast = beastInst()\n self.widgets['beasts'].hide()\n self.widgets['server'].show()\n \n def btnBuildFileDialogCertificate(self):\n \"\"\"\n toolButton method: connected to toolButtonFileDialog on SERVER widget\n builds a file dialog window for choosing the server certificates' path \n \"\"\"\n path = QtGui.QFileDialog.getOpenFileName(self, 'choose certificate', 'certs')\n self.widgets['server'].lineEditCert.setText(path)\n \n def btnBuildFileDialogBeasts(self):\n \"\"\"\n toolButton method: connected to toolButtonFileDialog on BEASTS widget\n builds a file dialog window for choosing the beast modules' path \n \"\"\"\n path = QtGui.QFileDialog.getOpenFileName(self, 'choose beast implementation (only .py files)', '..')\n self.widgets['beasts'].lineEditOwnImplementation.setText(path)", "answers": [" def btnSetHandling(self):"], "length": 659, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "b77a9fb1-6128-46d7-b8a1-11bf9861c63e", "reasoning": "The provided code ends the btnBuildFileDialogBeasts method after setting the line edit text. The next logical line in the class is the definition of the following method, which in the surrounding code is btnSetHandling. Therefore the next line should start a new method definition at the same indentation level as the previous methods.", "reasoning_model_answer": "def btnSetHandling(self):", "assistant_with_reasoning": "\nThe provided code ends the btnBuildFileDialogBeasts method after setting the line edit text. The next logical line in the class is the definition of the following method, which in the surrounding code is btnSetHandling. Therefore the next line should start a new method definition at the same indentation level as the previous methods.\n\ndef btnSetHandling(self):", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.916, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 12113, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "def btnSetHandling(self):", "score": 0.93, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/*\n * Licensed to Elasticsearch under one or more contributor\n * license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright\n * ownership. Elasticsearch licenses this file to you under\n * the Apache License, Version 2.0 (the \"License\"); you may\n * not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\npackage org.elasticsearch.action.bulk;\n\nimport org.elasticsearch.action.ActionListener;\nimport org.elasticsearch.action.DocWriteRequest;\nimport org.elasticsearch.action.delete.DeleteRequest;\nimport org.elasticsearch.action.index.IndexRequest;\nimport org.elasticsearch.client.Client;\nimport org.elasticsearch.common.Nullable;\nimport org.elasticsearch.common.bytes.BytesReference;\nimport org.elasticsearch.common.settings.Settings;\nimport org.elasticsearch.common.unit.ByteSizeUnit;\nimport org.elasticsearch.common.unit.ByteSizeValue;\nimport org.elasticsearch.common.unit.TimeValue;\nimport org.elasticsearch.common.xcontent.XContentType;\nimport org.elasticsearch.threadpool.Scheduler;\nimport org.elasticsearch.threadpool.ThreadPool;\n\nimport java.io.Closeable;\nimport java.util.Objects;\nimport java.util.concurrent.ScheduledThreadPoolExecutor;\nimport java.util.concurrent.TimeUnit;\nimport java.util.concurrent.atomic.AtomicLong;\nimport java.util.function.BiConsumer;\n\n/**\n * A bulk processor is a thread safe bulk processing class, allowing to easily set when to \"flush\" a new bulk request\n * (either based on number of actions, based on the size, or time), and to easily control the number of concurrent bulk\n * requests allowed to be executed in parallel.\n *

    \n * In order to create a new bulk processor, use the {@link Builder}.\n */\npublic class BulkProcessor implements Closeable {\n\n /**\n * A listener for the execution.\n */\n public interface Listener {\n\n /**\n * Callback before the bulk is executed.\n */\n void beforeBulk(long executionId, BulkRequest request);\n\n /**\n * Callback after a successful execution of bulk request.\n */\n void afterBulk(long executionId, BulkRequest request, BulkResponse response);\n\n /**\n * Callback after a failed execution of bulk request.\n *

    \n * Note that in case an instance of InterruptedException is passed, which means that request processing has been\n * cancelled externally, the thread's interruption status has been restored prior to calling this method.\n */\n void afterBulk(long executionId, BulkRequest request, Throwable failure);\n }\n\n /**\n * A builder used to create a build an instance of a bulk processor.\n */\n public static class Builder {\n\n private final BiConsumer> consumer;\n private final Listener listener;\n private final Scheduler scheduler;\n private final Runnable onClose;\n private int concurrentRequests = 1;\n private int bulkActions = 1000;\n private ByteSizeValue bulkSize = new ByteSizeValue(5, ByteSizeUnit.MB);\n private TimeValue flushInterval = null;\n private BackoffPolicy backoffPolicy = BackoffPolicy.exponentialBackoff();\n\n private Builder(BiConsumer> consumer, Listener listener,\n Scheduler scheduler, Runnable onClose) {\n this.consumer = consumer;\n this.listener = listener;\n this.scheduler = scheduler;\n this.onClose = onClose;\n }\n\n /**\n * Sets the number of concurrent requests allowed to be executed. A value of 0 means that only a single\n * request will be allowed to be executed. A value of 1 means 1 concurrent request is allowed to be executed\n * while accumulating new bulk requests. Defaults to {@code 1}.\n */\n public Builder setConcurrentRequests(int concurrentRequests) {\n this.concurrentRequests = concurrentRequests;\n return this;\n }\n\n /**\n * Sets when to flush a new bulk request based on the number of actions currently added. Defaults to\n * {@code 1000}. Can be set to {@code -1} to disable it.\n */\n public Builder setBulkActions(int bulkActions) {\n this.bulkActions = bulkActions;\n return this;\n }\n\n /**\n * Sets when to flush a new bulk request based on the size of actions currently added. Defaults to\n * {@code 5mb}. Can be set to {@code -1} to disable it.\n */\n public Builder setBulkSize(ByteSizeValue bulkSize) {\n this.bulkSize = bulkSize;\n return this;\n }\n\n /**\n * Sets a flush interval flushing *any* bulk actions pending if the interval passes. Defaults to not set.\n *

    \n * Note, both {@link #setBulkActions(int)} and {@link #setBulkSize(org.elasticsearch.common.unit.ByteSizeValue)}\n * can be set to {@code -1} with the flush interval set allowing for complete async processing of bulk actions.\n */", "answers": [" public Builder setFlushInterval(TimeValue flushInterval) {"], "length": 636, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "c5e35d15-e643-424e-83d1-9b11e099f93a", "reasoning": "The Builder class defines configuration setters. After the comment describing the flush interval, the next logical method is the setter for that interval. In Elasticsearch's BulkProcessor.Builder, the method signature is `public Builder setFlushInterval(TimeValue flushInterval) {`. This is the next line of code.", "reasoning_model_answer": "public Builder setFlushInterval(TimeValue flushInterval) {", "assistant_with_reasoning": "\nThe Builder class defines configuration setters. After the comment describing the flush interval, the next logical method is the setter for that interval. In Elasticsearch's BulkProcessor.Builder, the method signature is `public Builder setFlushInterval(TimeValue flushInterval) {`. This is the next line of code.\n\npublic Builder setFlushInterval(TimeValue flushInterval) {", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 2.05, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 5620, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "public Builder setFlushInterval(TimeValue flushInterval) {", "score": 0.94, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "\"\"\"The tests for the Template Binary sensor platform.\"\"\"\nfrom datetime import timedelta\nimport logging\nfrom unittest.mock import patch\n\nfrom homeassistant import setup\nfrom homeassistant.components import binary_sensor\nfrom homeassistant.const import (\n ATTR_DEVICE_CLASS,\n EVENT_HOMEASSISTANT_START,\n STATE_OFF,\n STATE_ON,\n STATE_UNAVAILABLE,\n)\nfrom homeassistant.core import CoreState\nimport homeassistant.util.dt as dt_util\n\nfrom tests.common import assert_setup_component, async_fire_time_changed\n\n\nasync def test_setup(hass):\n \"\"\"Test the setup.\"\"\"\n config = {\n \"binary_sensor\": {\n \"platform\": \"template\",\n \"sensors\": {\n \"test\": {\n \"friendly_name\": \"virtual thingy\",\n \"value_template\": \"{{ foo }}\",\n \"device_class\": \"motion\",\n }\n },\n }\n }\n with assert_setup_component(1):\n assert await setup.async_setup_component(hass, binary_sensor.DOMAIN, config)\n\n\nasync def test_setup_no_sensors(hass):\n \"\"\"Test setup with no sensors.\"\"\"\n with assert_setup_component(0):\n assert await setup.async_setup_component(\n hass, binary_sensor.DOMAIN, {\"binary_sensor\": {\"platform\": \"template\"}}\n )\n\n\nasync def test_setup_invalid_device(hass):\n \"\"\"Test the setup with invalid devices.\"\"\"\n with assert_setup_component(0):\n assert await setup.async_setup_component(\n hass,\n binary_sensor.DOMAIN,\n {\"binary_sensor\": {\"platform\": \"template\", \"sensors\": {\"foo bar\": {}}}},\n )\n\n\nasync def test_setup_invalid_device_class(hass):\n \"\"\"Test setup with invalid sensor class.\"\"\"\n with assert_setup_component(0):\n assert await setup.async_setup_component(\n hass,\n binary_sensor.DOMAIN,\n {\n \"binary_sensor\": {\n \"platform\": \"template\",\n \"sensors\": {\n \"test\": {\n \"value_template\": \"{{ foo }}\",\n \"device_class\": \"foobarnotreal\",\n }\n },\n }\n },\n )\n\n\nasync def test_setup_invalid_missing_template(hass):\n \"\"\"Test setup with invalid and missing template.\"\"\"\n with assert_setup_component(0):\n assert await setup.async_setup_component(\n hass,\n binary_sensor.DOMAIN,\n {\n \"binary_sensor\": {\n \"platform\": \"template\",\n \"sensors\": {\"test\": {\"device_class\": \"motion\"}},\n }\n },\n )\n\n\nasync def test_icon_template(hass):\n \"\"\"Test icon template.\"\"\"\n with assert_setup_component(1):\n assert await setup.async_setup_component(\n hass,\n binary_sensor.DOMAIN,\n {\n \"binary_sensor\": {\n \"platform\": \"template\",\n \"sensors\": {\n \"test_template_sensor\": {\n \"value_template\": \"{{ states.sensor.xyz.state }}\",\n \"icon_template\": \"{% if \"\n \"states.binary_sensor.test_state.state == \"\n \"'Works' %}\"\n \"mdi:check\"\n \"{% endif %}\",\n }\n },\n }\n },\n )\n\n await hass.async_block_till_done()\n await hass.async_start()\n await hass.async_block_till_done()\n\n state = hass.states.get(\"binary_sensor.test_template_sensor\")\n assert state.attributes.get(\"icon\") == \"\"\n\n hass.states.async_set(\"binary_sensor.test_state\", \"Works\")\n await hass.async_block_till_done()\n state = hass.states.get(\"binary_sensor.test_template_sensor\")\n assert state.attributes[\"icon\"] == \"mdi:check\"\n\n\nasync def test_entity_picture_template(hass):\n \"\"\"Test entity_picture template.\"\"\"\n with assert_setup_component(1):\n assert await setup.async_setup_component(\n hass,\n binary_sensor.DOMAIN,\n {\n \"binary_sensor\": {\n \"platform\": \"template\",\n \"sensors\": {\n \"test_template_sensor\": {\n \"value_template\": \"{{ states.sensor.xyz.state }}\",\n \"entity_picture_template\": \"{% if \"\n \"states.binary_sensor.test_state.state == \"\n \"'Works' %}\"\n \"/local/sensor.png\"\n \"{% endif %}\",\n }\n },\n }\n },\n )\n\n await hass.async_block_till_done()\n await hass.async_start()\n await hass.async_block_till_done()\n\n state = hass.states.get(\"binary_sensor.test_template_sensor\")\n assert state.attributes.get(\"entity_picture\") == \"\"\n\n hass.states.async_set(\"binary_sensor.test_state\", \"Works\")\n await hass.async_block_till_done()\n state = hass.states.get(\"binary_sensor.test_template_sensor\")\n assert state.attributes[\"entity_picture\"] == \"/local/sensor.png\"\n\n\nasync def test_attribute_templates(hass):\n \"\"\"Test attribute_templates template.\"\"\"\n with assert_setup_component(1):\n assert await setup.async_setup_component(\n hass,\n binary_sensor.DOMAIN,\n {\n \"binary_sensor\": {\n \"platform\": \"template\",\n \"sensors\": {\n \"test_template_sensor\": {\n \"value_template\": \"{{ states.sensor.xyz.state }}\",\n \"attribute_templates\": {\n \"test_attribute\": \"It {{ states.sensor.test_state.state }}.\"\n },\n }\n },\n }\n },\n )\n\n await hass.async_block_till_done()\n await hass.async_start()\n await hass.async_block_till_done()\n\n state = hass.states.get(\"binary_sensor.test_template_sensor\")\n assert state.attributes.get(\"test_attribute\") == \"It .\"\n hass.states.async_set(\"sensor.test_state\", \"Works2\")\n await hass.async_block_till_done()\n hass.states.async_set(\"sensor.test_state\", \"Works\")\n await hass.async_block_till_done()\n state = hass.states.get(\"binary_sensor.test_template_sensor\")\n assert state.attributes[\"test_attribute\"] == \"It Works.\"\n\n\nasync def test_match_all(hass):\n \"\"\"Test template that is rerendered on any state lifecycle.\"\"\"\n with patch(\n \"homeassistant.components.template.binary_sensor.\"\n \"BinarySensorTemplate._update_state\"\n ) as _update_state:\n with assert_setup_component(1):\n assert await setup.async_setup_component(\n hass,\n binary_sensor.DOMAIN,\n {\n \"binary_sensor\": {\n \"platform\": \"template\",\n \"sensors\": {\n \"match_all_template_sensor\": {\n \"value_template\": (\n \"{% for state in states %}\"\n \"{% if state.entity_id == 'sensor.humidity' %}\"\n \"{{ state.entity_id }}={{ state.state }}\"\n \"{% endif %}\"\n \"{% endfor %}\"\n ),\n },\n },\n }\n },\n )\n\n await hass.async_start()\n await hass.async_block_till_done()\n init_calls = len(_update_state.mock_calls)\n\n hass.states.async_set(\"sensor.any_state\", \"update\")\n await hass.async_block_till_done()\n assert len(_update_state.mock_calls) == init_calls\n\n\nasync def test_event(hass):\n \"\"\"Test the event.\"\"\"\n config = {\n \"binary_sensor\": {\n \"platform\": \"template\",\n \"sensors\": {\n \"test\": {\n \"friendly_name\": \"virtual thingy\",\n \"value_template\": \"{{ states.sensor.test_state.state == 'on' }}\",\n \"device_class\": \"motion\",\n }\n },\n }\n }\n with assert_setup_component(1):\n assert await setup.async_setup_component(hass, binary_sensor.DOMAIN, config)\n\n await hass.async_block_till_done()\n await hass.async_start()\n await hass.async_block_till_done()\n\n state = hass.states.get(\"binary_sensor.test\")\n assert state.state == \"off\"\n\n hass.states.async_set(\"sensor.test_state\", \"on\")\n await hass.async_block_till_done()\n\n state = hass.states.get(\"binary_sensor.test\")\n assert state.state == \"on\"\n\n\nasync def test_template_delay_on(hass):\n \"\"\"Test binary sensor template delay on.\"\"\"\n config = {\n \"binary_sensor\": {\n \"platform\": \"template\",\n \"sensors\": {\n \"test\": {\n \"friendly_name\": \"virtual thingy\",\n \"value_template\": \"{{ states.sensor.test_state.state == 'on' }}\",\n \"device_class\": \"motion\",\n \"delay_on\": 5,\n }\n },\n }\n }\n await setup.async_setup_component(hass, binary_sensor.DOMAIN, config)\n await hass.async_block_till_done()\n await hass.async_start()\n\n hass.states.async_set(\"sensor.test_state\", \"on\")\n await hass.async_block_till_done()\n\n state = hass.states.get(\"binary_sensor.test\")\n assert state.state == \"off\"\n\n future = dt_util.utcnow() + timedelta(seconds=5)", "answers": [" async_fire_time_changed(hass, future)"], "length": 609, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "4777561d-8dfb-4885-8f61-daa86e405762", "reasoning": "The test is checking the delay_on functionality. After setting the sensor to 'on' and confirming the binary sensor stays 'off', it calculates a future time 5 seconds ahead. The next step is to simulate the passage of time so the delayed state change can be processed, which is done by calling async_fire_time_changed with the Home Assistant instance and the future timestamp.", "reasoning_model_answer": "async_fire_time_changed(hass, future)", "assistant_with_reasoning": "\nThe test is checking the delay_on functionality. After setting the sensor to 'on' and confirming the binary sensor stays 'off', it calculates a future time 5 seconds ahead. The next step is to simulate the passage of time so the delayed state change can be processed, which is done by calling async_fire_time_changed with the Home Assistant instance and the future timestamp.\n\nasync_fire_time_changed(hass, future)", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 2.492, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 9832, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "async_fire_time_changed(hass, future)", "score": 0.95, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "// ReSharper disable All\nusing System.Collections.Generic;\nusing System.Dynamic;\nusing System.Net;\nusing System.Net.Http;\nusing System.Web.Http;\nusing Frapid.ApplicationState.Cache;\nusing Frapid.ApplicationState.Models;\nusing Newtonsoft.Json;\nusing Newtonsoft.Json.Linq;\nusing Frapid.Config.DataAccess;\nusing Frapid.DataAccess;\nusing Frapid.DataAccess.Models;\nusing Frapid.Framework;\nusing Frapid.Framework.Extensions;\n\nnamespace Frapid.Config.Api\n{\n ///

    \n /// Provides a direct HTTP access to perform various tasks such as adding, editing, and removing Apps.\n /// \n [RoutePrefix(\"api/v1.0/config/app\")]\n public class AppController : FrapidApiController\n {\n /// \n /// The App repository.\n /// \n private readonly IAppRepository AppRepository;\n\n public AppController()\n {\n this._LoginId = AppUsers.GetCurrent().View.LoginId.To();\n this._UserId = AppUsers.GetCurrent().View.UserId.To();\n this._OfficeId = AppUsers.GetCurrent().View.OfficeId.To();\n this._Catalog = AppUsers.GetCatalog();\n\n this.AppRepository = new Frapid.Config.DataAccess.App\n {\n _Catalog = this._Catalog,\n _LoginId = this._LoginId,\n _UserId = this._UserId\n };\n }\n\n public AppController(IAppRepository repository, string catalog, LoginView view)\n {\n this._LoginId = view.LoginId.To();\n this._UserId = view.UserId.To();\n this._OfficeId = view.OfficeId.To();\n this._Catalog = catalog;\n\n this.AppRepository = repository;\n }\n\n public long _LoginId { get; }\n public int _UserId { get; private set; }\n public int _OfficeId { get; private set; }\n public string _Catalog { get; }\n\n /// \n /// Creates meta information of \"app\" entity.\n /// \n /// Returns the \"app\" meta information to perform CRUD operation.\n [AcceptVerbs(\"GET\", \"HEAD\")]\n [Route(\"meta\")]\n [Route(\"~/api/config/app/meta\")]\n [Authorize]\n public EntityView GetEntityView()\n {\n if (this._LoginId == 0)\n {\n return new EntityView();\n }\n\n return new EntityView\n {\n PrimaryKey = \"app_name\",\n Columns = new List()\n {\n new EntityColumn { ColumnName = \"app_name\", PropertyName = \"AppName\", DataType = \"string\", DbDataType = \"varchar\", IsNullable = false, IsPrimaryKey = true, IsSerial = false, Value = \"\", MaxLength = 100 },\n new EntityColumn { ColumnName = \"name\", PropertyName = \"Name\", DataType = \"string\", DbDataType = \"varchar\", IsNullable = true, IsPrimaryKey = false, IsSerial = false, Value = \"\", MaxLength = 100 },\n new EntityColumn { ColumnName = \"version_number\", PropertyName = \"VersionNumber\", DataType = \"string\", DbDataType = \"varchar\", IsNullable = true, IsPrimaryKey = false, IsSerial = false, Value = \"\", MaxLength = 100 },\n new EntityColumn { ColumnName = \"publisher\", PropertyName = \"Publisher\", DataType = \"string\", DbDataType = \"varchar\", IsNullable = true, IsPrimaryKey = false, IsSerial = false, Value = \"\", MaxLength = 100 },\n new EntityColumn { ColumnName = \"published_on\", PropertyName = \"PublishedOn\", DataType = \"DateTime\", DbDataType = \"date\", IsNullable = true, IsPrimaryKey = false, IsSerial = false, Value = \"\", MaxLength = 0 },\n new EntityColumn { ColumnName = \"icon\", PropertyName = \"Icon\", DataType = \"string\", DbDataType = \"varchar\", IsNullable = true, IsPrimaryKey = false, IsSerial = false, Value = \"\", MaxLength = 100 },\n new EntityColumn { ColumnName = \"landing_url\", PropertyName = \"LandingUrl\", DataType = \"string\", DbDataType = \"text\", IsNullable = true, IsPrimaryKey = false, IsSerial = false, Value = \"\", MaxLength = 0 }\n }\n };\n }\n\n /// \n /// Counts the number of apps.\n /// \n /// Returns the count of the apps.\n [AcceptVerbs(\"GET\", \"HEAD\")]\n [Route(\"count\")]\n [Route(\"~/api/config/app/count\")]\n [Authorize]\n public long Count()\n {\n try\n {\n return this.AppRepository.Count();\n }\n catch (UnauthorizedException)\n {\n throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));\n }\n catch (DataAccessException ex)\n {\n throw new HttpResponseException(new HttpResponseMessage\n {\n Content = new StringContent(ex.Message),\n StatusCode = HttpStatusCode.InternalServerError\n });\n }\n#if !DEBUG\n catch\n {\n throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));\n }\n#endif\n }\n\n /// \n /// Returns all collection of app.\n /// \n /// \n [AcceptVerbs(\"GET\", \"HEAD\")]\n [Route(\"all\")]\n [Route(\"~/api/config/app/all\")]\n [Authorize]\n public IEnumerable GetAll()\n {\n try\n {\n return this.AppRepository.GetAll();\n }\n catch (UnauthorizedException)\n {\n throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));\n }\n catch (DataAccessException ex)\n {\n throw new HttpResponseException(new HttpResponseMessage\n {\n Content = new StringContent(ex.Message),\n StatusCode = HttpStatusCode.InternalServerError\n });\n }\n#if !DEBUG\n catch\n {\n throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));\n }\n#endif\n }\n\n /// \n /// Returns collection of app for export.\n /// \n /// \n [AcceptVerbs(\"GET\", \"HEAD\")]\n [Route(\"export\")]\n [Route(\"~/api/config/app/export\")]\n [Authorize]\n public IEnumerable Export()\n {\n try\n {\n return this.AppRepository.Export();\n }\n catch (UnauthorizedException)\n {\n throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));\n }\n catch (DataAccessException ex)\n {\n throw new HttpResponseException(new HttpResponseMessage\n {\n Content = new StringContent(ex.Message),\n StatusCode = HttpStatusCode.InternalServerError\n });\n }\n#if !DEBUG\n catch\n {\n throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));\n }\n#endif\n }\n\n /// \n /// Returns an instance of app.\n /// \n /// Enter AppName to search for.\n /// \n [AcceptVerbs(\"GET\", \"HEAD\")]\n [Route(\"{appName}\")]\n [Route(\"~/api/config/app/{appName}\")]\n [Authorize]", "answers": [" public Frapid.Config.Entities.App Get(string appName)"], "length": 653, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "1f51dbda-f997-41cb-b3ec-04defe3dbcb0", "reasoning": "After the attribute decorations for the endpoint that returns a single app instance, the next line should be the method signature. Following the pattern of other actions (e.g., GetAll returns IEnumerable, Count returns long), this method will return a single App entity and accept the app name as a parameter. Therefore the next line is the signature: public Frapid.Config.Entities.App Get(string appName)", "reasoning_model_answer": "public Frapid.Config.Entities.App Get(string appName)", "assistant_with_reasoning": "\nAfter the attribute decorations for the endpoint that returns a single app instance, the next line should be the method signature. Following the pattern of other actions (e.g., GetAll returns IEnumerable, Count returns long), this method will return a single App entity and accept the app name as a parameter. Therefore the next line is the signature: public Frapid.Config.Entities.App Get(string appName)\n\npublic Frapid.Config.Entities.App Get(string appName)", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.126, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 8035, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "public Frapid.Config.Entities.App Get(string appName)", "score": 0.93, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "\n# This file helps to compute a version number in source trees obtained from\n# git-archive tarball (such as those provided by githubs download-from-tag\n# feature). Distribution tarballs (built by setup.py sdist) and build\n# directories (produced by setup.py build) will contain a much shorter file\n# that just contains the computed version number.\n\n# This file is released into the public domain. Generated by\n# versioneer-0.18 (https://github.com/warner/python-versioneer)\n\n\"\"\"Git implementation of _version.py.\"\"\"\n\nimport errno\nimport os\nimport re\nimport subprocess\nimport sys\n\n\ndef get_keywords():\n \"\"\"Get the keywords needed to look up the version information.\"\"\"\n # these strings will be replaced by git during git-archive.\n # setup.py/versioneer.py will grep for the variable names, so they must\n # each be defined on a line of their own. _version.py will just call\n # get_keywords().\n git_refnames = \"$Format:%d$\"\n git_full = \"$Format:%H$\"\n git_date = \"$Format:%ci$\"\n keywords = {\"refnames\": git_refnames, \"full\": git_full, \"date\": git_date}\n return keywords\n\n\nclass VersioneerConfig:\n \"\"\"Container for Versioneer configuration parameters.\"\"\"\n\n\ndef get_config():\n \"\"\"Create, populate and return the VersioneerConfig() object.\"\"\"\n # these strings are filled in when 'setup.py versioneer' creates\n # _version.py\n cfg = VersioneerConfig()\n cfg.VCS = \"git\"\n cfg.style = \"pep440\"\n cfg.tag_prefix = \"\"\n cfg.parentdir_prefix = \"pyradigm-\"\n cfg.versionfile_source = \"pyradigm/_version.py\"\n cfg.verbose = False\n return cfg\n\n\nclass NotThisMethod(Exception):\n \"\"\"Exception raised if a method is not valid for the current scenario.\"\"\"\n\n\nLONG_VERSION_PY = {}\nHANDLERS = {}\n\n\ndef register_vcs_handler(vcs, method): # decorator\n \"\"\"Decorator to mark a method as the handler for a particular VCS.\"\"\"\n def decorate(f):\n \"\"\"Store f in HANDLERS[vcs][method].\"\"\"\n if vcs not in HANDLERS:\n HANDLERS[vcs] = {}\n HANDLERS[vcs][method] = f\n return f\n return decorate\n\n\ndef run_command(commands, args, cwd=None, verbose=False, hide_stderr=False,\n env=None):\n \"\"\"Call the given command(s).\"\"\"\n assert isinstance(commands, list)\n p = None\n for c in commands:\n try:\n dispcmd = str([c] + args)\n # remember shell=False, so use git.cmd on windows, not just git\n p = subprocess.Popen([c] + args, cwd=cwd, env=env,\n stdout=subprocess.PIPE,\n stderr=(subprocess.PIPE if hide_stderr\n else None))\n break\n except EnvironmentError:\n e = sys.exc_info()[1]\n if e.errno == errno.ENOENT:\n continue\n if verbose:\n print(\"unable to run %s\" % dispcmd)\n print(e)\n return None, None\n else:\n if verbose:\n print(\"unable to find command, tried %s\" % (commands,))\n return None, None\n stdout = p.communicate()[0].strip()\n if sys.version_info[0] >= 3:\n stdout = stdout.decode()\n if p.returncode != 0:\n if verbose:\n print(\"unable to run %s (error)\" % dispcmd)\n print(\"stdout was %s\" % stdout)\n return None, p.returncode\n return stdout, p.returncode\n\n\ndef versions_from_parentdir(parentdir_prefix, root, verbose):\n \"\"\"Try to determine the version from the parent directory name.\n\n Source tarballs conventionally unpack into a directory that includes both\n the project name and a version string. We will also support searching up\n two directory levels for an appropriately named parent directory\n \"\"\"\n rootdirs = []\n\n for i in range(3):\n dirname = os.path.basename(root)\n if dirname.startswith(parentdir_prefix):\n return {\"version\": dirname[len(parentdir_prefix):],\n \"full-revisionid\": None,\n \"dirty\": False, \"error\": None, \"date\": None}\n else:\n rootdirs.append(root)\n root = os.path.dirname(root) # up a level\n\n if verbose:\n print(\"Tried directories %s but none started with prefix %s\" %\n (str(rootdirs), parentdir_prefix))\n raise NotThisMethod(\"rootdir doesn't start with parentdir_prefix\")\n\n\n@register_vcs_handler(\"git\", \"get_keywords\")\ndef git_get_keywords(versionfile_abs):\n \"\"\"Extract version information from the given file.\"\"\"\n # the code embedded in _version.py can just fetch the value of these\n # keywords. When used from setup.py, we don't want to import _version.py,\n # so we do it with a regexp instead. This function is not used from\n # _version.py.\n keywords = {}\n try:\n f = open(versionfile_abs, \"r\")\n for line in f.readlines():\n if line.strip().startswith(\"git_refnames =\"):\n mo = re.search(r'=\\s*\"(.*)\"', line)\n if mo:\n keywords[\"refnames\"] = mo.group(1)\n if line.strip().startswith(\"git_full =\"):\n mo = re.search(r'=\\s*\"(.*)\"', line)\n if mo:\n keywords[\"full\"] = mo.group(1)\n if line.strip().startswith(\"git_date =\"):\n mo = re.search(r'=\\s*\"(.*)\"', line)\n if mo:\n keywords[\"date\"] = mo.group(1)\n f.close()\n except EnvironmentError:\n pass\n return keywords\n\n\n@register_vcs_handler(\"git\", \"keywords\")\ndef git_versions_from_keywords(keywords, tag_prefix, verbose):\n \"\"\"Get version information from git keywords.\"\"\"\n if not keywords:\n raise NotThisMethod(\"no keywords at all, weird\")\n date = keywords.get(\"date\")", "answers": [" if date is not None:"], "length": 616, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "13078bd0-f17d-4b3b-858e-bd48c83b5b27", "reasoning": "In the git_versions_from_keywords function, after extracting the 'date' value from the keywords dict, the next logical step is to verify that the date was actually present. The versioneer code raises NotThisMethod when a required keyword is missing, so the line following the assignment should be a check for a missing date, i.e., an if-statement that raises if date is None.", "reasoning_model_answer": "if date is None:", "assistant_with_reasoning": "\nIn the git_versions_from_keywords function, after extracting the 'date' value from the keywords dict, the next logical step is to verify that the date was actually present. The versioneer code raises NotThisMethod when a required keyword is missing, so the line following the assignment should be a check for a missing date, i.e., an if-statement that raises if date is None.\n\nif date is None:", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.348, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 5837, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "if date is None:", "score": 0.8, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "#!/usr/bin/python\n#\n# Copyright (c) 2012, NORDUnet A/S\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or\n# without modification, are permitted provided that the following\n# conditions are met:\n#\n# 1. Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n# 2. Redistributions in binary form must reproduce the above\n# copyright notice, this list of conditions and the following\n# disclaimer in the documentation and/or other materials provided\n# with the distribution.\n# 3. Neither the name of the NORDUnet nor the names of its\n# contributors may be used to endorse or promote products derived\n# from this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.\n#\n# Author : Fredrik Thulin \n#\n\n\"\"\"\nConfiguration (key management) interface to YubiHSM.\n\"\"\"\n\nimport os\nimport re\nimport serial\nimport logging\n\nfrom vccs_hsm_keydb import HsmKey\n\n\nclass VCCSCfgError(Exception):\n \"\"\"\n Base class for all exceptions relating to the VCCS HSM communication.\n\n :param reason: reason as string\n \"\"\"\n\n def __init__(self, reason):\n self.reason = reason\n\n def __str__(self):\n return '<%s instance at %s: %s>' % (\n self.__class__.__name__,\n hex(id(self)),\n self.reason,\n )\n\n\nclass VCCSCfgInteractError(VCCSCfgError):\n \"\"\"\n Exception class with extra information about when our HSM interactions fail.\n \"\"\"\n\n def __init__(self, reason, all_commands, all_data, expected, got, last_send, ):\n VCCSCfgError.__init__(self, reason)\n self.all_commands = all_commands\n self.all_data = all_data\n self.expected = expected\n self.got = got\n self.last_send = last_send\n\n def __str__(self):\n return '<%s instance at %s: %s\\n(last send %s, expected %s, got %s>' % (\n self.__class__.__name__,\n hex(id(self)),\n self.reason,\n repr(self.last_send),\n repr(self.expected),\n repr(self.got),\n )\n\n\nclass HsmSerial():\n \"\"\"\n Low-end interface to HSM. Read, write, those kinds of things.\n \"\"\"\n\n def __init__(self, device, logger):\n self.device = device\n self.logger = logger\n self.ser = serial.Serial(device, 115200, timeout = 0.1)\n\n def __repr__(self):\n return '<%s instance at %s: %s>' % (\n self.__class__.__name__,\n hex(id(self)),\n self.device\n )\n\n def __del__(self):\n self.logger.debug(\"Destroying %s\", str(self))\n if self.ser:\n self.ser.close()\n\n def close(self):\n \"\"\"\n Close the HSM.\n\n :return: True on success\n \"\"\"\n self.logger.debug(\"Closing %s\", str(self))\n self.ser.close()\n self.ser = None\n return True\n\n def read(self, num_bytes):\n \"\"\"\n Read num_bytes from HSM.\n\n :param num_bytes: Number of bytes to read.\n :returns: Data as string\n \"\"\"\n data = self.ser.read(num_bytes)\n return data\n\n def write(self, data):\n \"\"\"\n Write data to HSM.\n :param data: Data to write as string\n \"\"\"\n self.ser.write(str(data))\n self.logger.debug(\"WRITE: %s\" % (repr(data)))\n\n def drain(self):\n \"\"\"\n Read until the read times out.\n \"\"\"\n data = ''\n while True:\n x = self.read(1)\n if not x:\n break\n data += x\n if data:\n self.logger.debug(\"DRAIN : %s\" % (repr(data)))\n\n def interact(self, commands, retry_count = 5, add_cr = True):\n \"\"\"\n Process a list of 'send' or 'expect' command tuples.\n\n e.g.\n commands = [('send', 'sysinfo'),\n ('expect', '^YubiHSM version'),\n ...\n ]\n :param commands: List of command-tuples\n :param retry_count: Number of times to retry reading the expected result\n :param add_cr: Add a Carriage-Return to the command sent or not\n :returns: Command output as string\n \"\"\"\n data = ''\n last_send = None\n self.logger.debug(\"INTERACT: %s\" % commands)\n for (cmd, arg) in commands:\n if cmd == 'send':\n if arg or add_cr:\n if add_cr:\n arg += '\\r'\n self.write(arg)\n last_send = arg", "answers": [" elif cmd == 'expect':"], "length": 636, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "e3762b13-c678-4431-977b-2d6cebd65687", "reasoning": "We are inside the interact() method, iterating over command tuples. The code currently handles the 'send' command: it optionally adds a carriage return, writes the data, and records the last sent string. The next logical step is to handle the other possible command type, 'expect', which will be processed after the 'send' block. Therefore the next line should start an elif clause for the 'expect' command.", "reasoning_model_answer": "elif cmd == 'expect':", "assistant_with_reasoning": "\nWe are inside the interact() method, iterating over command tuples. The code currently handles the 'send' command: it optionally adds a carriage return, writes the data, and records the last sent string. The next logical step is to handle the other possible command type, 'expect', which will be processed after the 'send' block. Therefore the next line should start an elif clause for the 'expect' command.\n\nelif cmd == 'expect':", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 2.985, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 5443, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "elif cmd == 'expect':", "score": 0.78, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "package org.radargun.stages.cache;\n\nimport java.io.Serializable;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.concurrent.Callable;\nimport java.util.concurrent.ExecutorService;\nimport java.util.concurrent.Executors;\nimport java.util.concurrent.Future;\n\nimport org.radargun.DistStageAck;\nimport org.radargun.config.Property;\nimport org.radargun.config.Stage;\nimport org.radargun.stages.AbstractDistStage;\nimport org.radargun.stages.cache.generators.ByteArrayValueGenerator;\nimport org.radargun.stages.cache.generators.KeyGenerator;\nimport org.radargun.stages.cache.generators.StringKeyGenerator;\nimport org.radargun.stages.cache.generators.ValueGenerator;\nimport org.radargun.stages.helpers.BucketPolicy;\nimport org.radargun.stages.helpers.Range;\nimport org.radargun.state.SlaveState;\nimport org.radargun.traits.BasicOperations;\nimport org.radargun.traits.CacheInformation;\nimport org.radargun.traits.Debugable;\nimport org.radargun.traits.InMemoryBasicOperations;\nimport org.radargun.traits.InjectTrait;\n\n/**\n * @author Radim Vansa <rvansa@redhat.com>\n */\n@Stage(doc = \"Stage for checking presence or absence of data entered in other stages.\")\npublic class CheckCacheDataStage extends AbstractDistStage {\n\n @Property(optional = false, doc = \"Number of entries with key in form specified by the last used key generator, in the cache.\")\n private int numEntries;\n\n @Property(doc = \"Index of key of first entry. This number will be multiplied by slaveIndex. Default is 0.\")\n private int firstEntryOffset = 0;\n\n @Property(doc = \"Number of entries that will be checked in each step. Default is 1.\")\n private int checkEntryCount = 1;\n\n @Property(doc = \"Number of entries stepped in each step. Default is 1.\")\n private int stepEntryCount = 1;\n\n @Property(optional = false, doc = \"Number of bytes carried in single entry.\")\n private int entrySize;\n\n @Property(doc = \"Entries that do not have the expected form but occur in the cluster. This string specifies \" +\n \"a polynomial in number of slaves: 1,2,3 with 4 slaves would result in 1 + 2*4 + 3*4*4 = 57 extra entries.\" +\n \"Defaults to 0.\")\n private String extraEntries;\n\n @Property(doc = \"Number of thread per node which check data validity. Default is 1.\")\n private int checkThreads = 1;\n\n @Property(doc = \"Usually the test checks that sum of local nodes = numOwners * numEntries + extraEntries.\" +\n \"This option disables such behaviour. Default is false.\")\n private boolean ignoreSum = false;\n\n @Property(doc = \"If true, the entries are not retrieved, this stage only checks that the sum of entries from local nodes is correct. Default is false.\")\n private boolean sizeOnly = false;\n\n @Property(doc = \"Hint how many slaves are currently alive - if set to > 0 then the query for amount of entries in\" +\n \"this cache is postponed until the cache appears to be fully replicated. By default this is disabled.\")\n private int liveSlavesHint = -1;\n\n @Property(doc = \"If set to true, we are checking that the data are NOT in the cluster anymore. Default is false.\")\n private boolean deleted = false;\n\n @Property(doc = \"Number of queries after which a DEBUG log message is printed. Default is 10000.\")\n private int logChecksCount = 10000;\n\n @Property(doc = \"If the GET request results in null response, call wrapper-specific functions to show debug info. \" +\n \"Default is false.\")\n private boolean debugNull = false;\n\n @Property(doc = \"If entry is null, fail immediatelly. Default is false.\")\n private boolean failOnNull = false;\n\n @Property(doc = \"If the cache wrapper supports persistent storage and this is set to true, the check \" +\n \"will be executed only against in-memory data. Default is false.\")\n private boolean memoryOnly = false;\n\n // TODO: better names, even when these are kind of hacks\n @Property(doc = \"Check whether the sum of subparts sizes is the same as local size. Default is false.\")\n private boolean checkSubpartsSumLocal = false;\n\n @Property(doc = \"Check whether the same subparts from each cache have the same size. Default is false.\")\n private boolean checkSubpartsEqual = false;\n\n @Property(doc = \"Check that number of non-zero subparts is equal to number of replicas. Default is false.\")\n private boolean checkSubpartsAreReplicas = false;\n\n private transient KeyGenerator keyGenerator;\n\n @InjectTrait(dependency = InjectTrait.Dependency.MANDATORY)\n protected BasicOperations basicOperations;\n @InjectTrait\n protected InMemoryBasicOperations inMemoryBasicOperations;\n @InjectTrait(dependency = InjectTrait.Dependency.MANDATORY)", "answers": [" protected CacheInformation cacheInformation;"], "length": 581, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "18629816-6e1c-439f-b1ea-e501adf6b0d3", "reasoning": "The code is defining fields to be injected with @InjectTrait. After declaring basicOperations and inMemoryBasicOperations, the next @InjectTrait annotation (with mandatory dependency) expects a field declaration. The appropriate trait for cache metadata is CacheInformation, so the next line should declare a protected CacheInformation field.", "reasoning_model_answer": "protected CacheInformation cacheInfo;", "assistant_with_reasoning": "\nThe code is defining fields to be injected with @InjectTrait. After declaring basicOperations and inMemoryBasicOperations, the next @InjectTrait annotation (with mandatory dependency) expects a field declaration. The appropriate trait for cache metadata is CacheInformation, so the next line should declare a protected CacheInformation field.\n\nprotected CacheInformation cacheInfo;", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.574, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 4822, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "protected CacheInformation cacheInfo;", "score": 0.88, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "package util;\n\nimport java.lang.reflect.Array;\nimport java.lang.reflect.Field;\nimport java.lang.reflect.Modifier;\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.HashSet;\nimport java.util.Iterator;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.SortedMap;\nimport java.util.SortedSet;\nimport java.util.concurrent.ConcurrentHashMap;\n\nimport model.notes.ModelBase;\n\n/**\n * Deeply compare two (2) objects. This method will call any overridden equals()\n * methods if they exist. If not, it will then proceed to do a field-by-field\n * comparison, and when a non-primitive field is encountered, recursively\n * continue the deep comparison. When an array is found, it will also ensure\n * that the array contents are deeply equal, not requiring the array instance\n * (container) to be identical. This method will successfully compare object\n * graphs that have cycles (A->B->C->A). There is no need to ever use the6\n * Arrays.deepEquals() method as this is a true and more effective super set.\n * \n * @author John DeRegnaucourt\n */\n\n/**\n * minor changes have been made to clone the Domino entity\n */\n@SuppressWarnings(\"unchecked\")\npublic class DeepEquals {\n\n\tprivate static final Map _customEquals = new ConcurrentHashMap();\n\tprivate static final Map _customHash = new ConcurrentHashMap();\n\tprivate static final Map> _reflectedFields = new ConcurrentHashMap>();\n\n\tprivate static class DualKey {\n\t\tprivate Object _key1;\n\t\tprivate Object _key2;\n\n\t\tprivate DualKey() {\n\t\t}\n\n\t\tprivate DualKey(Object k1, Object k2) {\n\t\t\t_key1 = k1;\n\t\t\t_key2 = k2;\n\t\t}\n\n\t\tpublic boolean equals(Object other) {\n\t\t\tif (other == null) {\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tif (!(other instanceof DualKey)) {\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tDualKey that = (DualKey) other;\n\t\t\treturn _key1 == that._key1 && _key2 == that._key2;\n\t\t}\n\n\t\tpublic int hashCode() {\n\t\t\tint h1 = _key1 != null ? _key1.hashCode() : 0;\n\t\t\tint h2 = _key2 != null ? _key2.hashCode() : 0;\n\t\t\treturn h1 + h2;\n\t\t}\n\t}\n\n\tpublic static boolean deepEquals(Object a, Object b) {\n\t\tSet visited = new HashSet();\n\t\treturn deepEquals(a, b, visited);\n\t}\n\n\tprivate static boolean deepEquals(Object a, Object b, Set visited) {\n\t\tLinkedList stack = new LinkedList();\n\t\tstack.addFirst(new DualKey(a, b));\n\n\t\t@SuppressWarnings(\"unused\")\n\t\tint cc = 0;\n\t\twhile (!stack.isEmpty()) {\n\n\t\t\tDualKey dualKey = stack.removeFirst();\n\t\t\tvisited.add(dualKey);\n\n\t\t\tif (dualKey._key1 == dualKey._key2) { // Same instance is always\n\t\t\t\t// equal to itself.\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (dualKey._key1 == null || dualKey._key2 == null) { // If either\n\t\t\t\t// one is\n\t\t\t\t// null, not\n\t\t\t\t// equal\n\t\t\t\t// (both\n\t\t\t\t// can't be\n\t\t\t\t// null, due\n\t\t\t\t// to above\n\t\t\t\t// comparison).\n\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tif (!dualKey._key1.getClass().equals(dualKey._key2.getClass())) {\n\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\t// Handle all [] types. In order to be equal, the arrays must be the\n\t\t\t// same\n\t\t\t// length, be of the same type, be in the same order, and all\n\t\t\t// elements within\n\t\t\t// the array must be deeply equivalent.\n\t\t\tif (dualKey._key1.getClass().isArray()) {\n\t\t\t\tint len = Array.getLength(dualKey._key1);\n\t\t\t\tif (len != Array.getLength(dualKey._key2)) {\n\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\n\t\t\t\tfor (int i = 0; i < len; i++) {\n\t\t\t\t\tDualKey dk = new DualKey(Array.get(dualKey._key1, i), Array\n\t\t\t\t\t\t\t.get(dualKey._key2, i));\n\t\t\t\t\tif (!visited.contains(dk)) {\n\t\t\t\t\t\tstack.addFirst(dk);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t// Special handle SortedSets because they are fast to compare\n\t\t\t// because their\n\t\t\t// elements must be in the same order to be equivalent Sets.\n\t\t\tif (dualKey._key1 instanceof SortedSet) {\n\t\t\t\tif (!compareOrdered(dualKey, stack, visited)) {\n\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t// Handled unordered Sets. This is an expensive comparison because\n\t\t\t// order cannot\n\t\t\t// be assumed, therefore it runs in O(n^2) when the Sets are the\n\t\t\t// same length.\n\t\t\tif (dualKey._key1 instanceof Set) {\n\t\t\t\tif (!compareUnordered((Set) dualKey._key1, (Set) dualKey._key2,\n\t\t\t\t\t\tvisited)) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t// Check any Collection that is not a Set. In these cases, element\n\t\t\t// order\n\t\t\t// matters, therefore this comparison is faster than using unordered\n\t\t\t// comparison.\n\t\t\tif (dualKey._key1 instanceof Collection) {\n\t\t\t\tif (!compareOrdered(dualKey, stack, visited)) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t// Compare two SortedMaps. This takes advantage of the fact that\n\t\t\t// these\n\t\t\t// Maps can be compared in O(N) time due to their ordering.\n\t\t\tif (dualKey._key1 instanceof SortedMap) {\n\t\t\t\tMap map1 = (Map) dualKey._key1;", "answers": ["\t\t\t\tMap map2 = (Map) dualKey._key2;"], "length": 641, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "339add0e-ff50-4032-8cbd-db83e6a57293", "reasoning": "The code is inside the deepEquals method handling a SortedMap case. It has just cast the first object's map to a generic Map variable named map1. The next logical step is to similarly cast the second object's map to a variable (map2) so they can be compared. Therefore the next line should be the cast of dualKey._key2 to Map and assign it to map2.", "reasoning_model_answer": "Map map2 = (Map) dualKey._key2;", "assistant_with_reasoning": "\nThe code is inside the deepEquals method handling a SortedMap case. It has just cast the first object's map to a generic Map variable named map1. The next logical step is to similarly cast the second object's map to a variable (map2) so they can be compared. Therefore the next line should be the cast of dualKey._key2 to Map and assign it to map2.\n\nMap map2 = (Map) dualKey._key2;", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 2.242, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 4887, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "Map map2 = (Map) dualKey._key2;", "score": 0.94, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.apache.tomcat.websocket;\n\nimport java.io.IOException;\nimport java.net.URI;\nimport java.nio.ByteBuffer;\nimport java.nio.charset.StandardCharsets;\nimport java.security.Principal;\nimport java.util.Collections;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.concurrent.ConcurrentHashMap;\nimport java.util.concurrent.atomic.AtomicLong;\n\nimport javax.websocket.CloseReason;\nimport javax.websocket.CloseReason.CloseCode;\nimport javax.websocket.CloseReason.CloseCodes;\nimport javax.websocket.DeploymentException;\nimport javax.websocket.Endpoint;\nimport javax.websocket.EndpointConfig;\nimport javax.websocket.Extension;\nimport javax.websocket.MessageHandler;\nimport javax.websocket.MessageHandler.Partial;\nimport javax.websocket.MessageHandler.Whole;\nimport javax.websocket.PongMessage;\nimport javax.websocket.RemoteEndpoint;\nimport javax.websocket.SendResult;\nimport javax.websocket.Session;\nimport javax.websocket.WebSocketContainer;\n\nimport org.apache.juli.logging.Log;\nimport org.apache.juli.logging.LogFactory;\nimport org.apache.tomcat.util.ExceptionUtils;\nimport org.apache.tomcat.util.res.StringManager;\n\npublic class WsSession implements Session {\n\n // An ellipsis is a single character that looks like three periods in a row\n // and is used to indicate a continuation.\n private static final byte[] ELLIPSIS_BYTES =\n \"\\u2026\".getBytes(StandardCharsets.UTF_8);\n // An ellipsis is three bytes in UTF-8\n private static final int ELLIPSIS_BYTES_LEN = ELLIPSIS_BYTES.length;\n\n private static final StringManager sm =\n StringManager.getManager(Constants.PACKAGE_NAME);\n private static AtomicLong ids = new AtomicLong(0);\n\n private final Log log = LogFactory.getLog(WsSession.class);\n\n private final Endpoint localEndpoint;\n private final WsRemoteEndpointImplBase wsRemoteEndpoint;\n private final RemoteEndpoint.Async remoteEndpointAsync;\n private final RemoteEndpoint.Basic remoteEndpointBasic;\n private final ClassLoader applicationClassLoader;\n private final WsWebSocketContainer webSocketContainer;\n private final URI requestUri;\n private final Map> requestParameterMap;\n private final String queryString;\n private final Principal userPrincipal;\n private final EndpointConfig endpointConfig;\n\n private final List negotiatedExtensions;\n private final String subProtocol;\n private final Map pathParameters;\n private final boolean secure;\n private final String httpSessionId;\n private final String id;\n\n // Expected to handle message types of only\n private MessageHandler textMessageHandler = null;\n // Expected to handle message types of only\n private MessageHandler binaryMessageHandler = null;\n private MessageHandler.Whole pongMessageHandler = null;\n private volatile State state = State.OPEN;\n private final Object stateLock = new Object();\n private final Map userProperties = new ConcurrentHashMap();\n private volatile int maxBinaryMessageBufferSize =\n Constants.DEFAULT_BUFFER_SIZE;\n private volatile int maxTextMessageBufferSize =\n Constants.DEFAULT_BUFFER_SIZE;\n private volatile long maxIdleTimeout = 0;\n private volatile long lastActive = System.currentTimeMillis();\n private Map futures =\n new ConcurrentHashMap();\n\n /**\n * Creates a new WebSocket session for communication between the two\n * provided end points. The result of {@link Thread#getContextClassLoader()}\n * at the time this constructor is called will be used when calling\n * {@link Endpoint#onClose(Session, CloseReason)}.\n *\n * @param localEndpoint\n * @param wsRemoteEndpoint\n * @param negotiatedExtensions\n * @throws DeploymentException\n */\n public WsSession(Endpoint localEndpoint,\n WsRemoteEndpointImplBase wsRemoteEndpoint,\n WsWebSocketContainer wsWebSocketContainer,\n URI requestUri, Map> requestParameterMap,\n String queryString, Principal userPrincipal, String httpSessionId,\n List negotiatedExtensions, String subProtocol, Map pathParameters,\n boolean secure, EndpointConfig endpointConfig) throws DeploymentException {\n this.localEndpoint = localEndpoint;\n this.wsRemoteEndpoint = wsRemoteEndpoint;\n this.wsRemoteEndpoint.setSession(this);\n this.remoteEndpointAsync = new WsRemoteEndpointAsync(wsRemoteEndpoint);\n this.remoteEndpointBasic = new WsRemoteEndpointBasic(wsRemoteEndpoint);\n this.webSocketContainer = wsWebSocketContainer;\n applicationClassLoader = Thread.currentThread().getContextClassLoader();\n wsRemoteEndpoint.setSendTimeout(\n wsWebSocketContainer.getDefaultAsyncSendTimeout());\n this.maxBinaryMessageBufferSize =\n webSocketContainer.getDefaultMaxBinaryMessageBufferSize();\n this.maxTextMessageBufferSize =\n webSocketContainer.getDefaultMaxTextMessageBufferSize();\n this.maxIdleTimeout =\n webSocketContainer.getDefaultMaxSessionIdleTimeout();\n this.requestUri = requestUri;\n if (requestParameterMap == null) {\n this.requestParameterMap = Collections.emptyMap();\n } else {\n this.requestParameterMap = requestParameterMap;\n }\n this.queryString = queryString;\n this.userPrincipal = userPrincipal;\n this.httpSessionId = httpSessionId;\n this.negotiatedExtensions = negotiatedExtensions;\n if (subProtocol == null) {\n this.subProtocol = \"\";\n } else {\n this.subProtocol = subProtocol;\n }\n this.pathParameters = pathParameters;\n this.secure = secure;\n this.wsRemoteEndpoint.setEncoders(endpointConfig);", "answers": [" this.endpointConfig = endpointConfig;"], "length": 586, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "2e1da638-0410-4a30-9a6e-303ae2de3449", "reasoning": "In the constructor, all parameters are being stored in fields. The field 'endpointConfig' is declared as a final member but hasn't been assigned yet. The line just before the placeholder calls wsRemoteEndpoint.setEncoders(endpointConfig); so the logical next step is to store the endpointConfig in the corresponding field. Therefore the next line should be the assignment of the constructor argument to the field.", "reasoning_model_answer": "this.endpointConfig = endpointConfig;", "assistant_with_reasoning": "\nIn the constructor, all parameters are being stored in fields. The field 'endpointConfig' is declared as a final member but hasn't been assigned yet. The line just before the placeholder calls wsRemoteEndpoint.setEncoders(endpointConfig); so the logical next step is to store the endpointConfig in the corresponding field. Therefore the next line should be the assignment of the constructor argument to the field.\n\nthis.endpointConfig = endpointConfig;", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.047, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 6958, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "this.endpointConfig = endpointConfig;", "score": 0.9, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/**\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.apache.hadoop.yarn.server.resourcemanager.monitor.capacity;\n\nimport com.google.common.annotations.VisibleForTesting;\nimport com.google.common.collect.ImmutableSet;\nimport org.apache.commons.logging.Log;\nimport org.apache.commons.logging.LogFactory;\nimport org.apache.hadoop.conf.Configuration;\nimport org.apache.hadoop.yarn.api.records.ApplicationAttemptId;\nimport org.apache.hadoop.yarn.api.records.ContainerId;\nimport org.apache.hadoop.yarn.api.records.Resource;\nimport org.apache.hadoop.yarn.exceptions.YarnRuntimeException;\nimport org.apache.hadoop.yarn.server.resourcemanager.RMContext;\nimport org.apache.hadoop.yarn.server.resourcemanager.monitor.SchedulingEditPolicy;\nimport org.apache.hadoop.yarn.server.resourcemanager.nodelabels.RMNodeLabelsManager;\nimport org.apache.hadoop.yarn.server.resourcemanager.rmcontainer.RMContainer;\nimport org.apache.hadoop.yarn.server.resourcemanager.scheduler.PreemptableResourceScheduler;\nimport org.apache.hadoop.yarn.server.resourcemanager.scheduler.capacity.CSQueue;\nimport org.apache.hadoop.yarn.server.resourcemanager.scheduler.capacity.CapacityScheduler;\nimport org.apache.hadoop.yarn.server.resourcemanager.scheduler.capacity.CapacitySchedulerConfiguration;\nimport org.apache.hadoop.yarn.server.resourcemanager.scheduler.capacity.ParentQueue;\nimport org.apache.hadoop.yarn.server.resourcemanager.scheduler.capacity.QueueCapacities;\nimport org.apache.hadoop.yarn.server.resourcemanager.scheduler.capacity.preemption.PreemptableQueue;\nimport org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.ContainerPreemptEvent;\nimport org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.SchedulerEventType;\nimport org.apache.hadoop.yarn.util.Clock;\nimport org.apache.hadoop.yarn.util.SystemClock;\nimport org.apache.hadoop.yarn.util.resource.ResourceCalculator;\nimport org.apache.hadoop.yarn.util.resource.Resources;\n\nimport java.io.IOException;\nimport java.text.MessageFormat;\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.Iterator;\nimport java.util.LinkedHashSet;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\n/**\n * This class implement a {@link SchedulingEditPolicy} that is designed to be\n * paired with the {@code CapacityScheduler}. At every invocation of {@code\n * editSchedule()} it computes the ideal amount of resources assigned to each\n * queue (for each queue in the hierarchy), and determines whether preemption\n * is needed. Overcapacity is distributed among queues in a weighted fair manner,\n * where the weight is the amount of guaranteed capacity for the queue.\n * Based on this ideal assignment it determines whether preemption is required\n * and select a set of containers from each application that would be killed if\n * the corresponding amount of resources is not freed up by the application.\n *\n * If not in {@code observeOnly} mode, it triggers preemption requests via a\n * {@link ContainerPreemptEvent} that the {@code ResourceManager} will ensure\n * to deliver to the application (or to execute).\n *\n * If the deficit of resources is persistent over a long enough period of time\n * this policy will trigger forced termination of containers (again by generating\n * {@link ContainerPreemptEvent}).\n */\npublic class ProportionalCapacityPreemptionPolicy\n implements SchedulingEditPolicy, CapacitySchedulerPreemptionContext {\n private static final Log LOG =\n LogFactory.getLog(ProportionalCapacityPreemptionPolicy.class);\n\n private final Clock clock;\n\n // Configurable fields\n private double maxIgnoredOverCapacity;\n private long maxWaitTime;\n private long monitoringInterval;\n private float percentageClusterPreemptionAllowed;\n private double naturalTerminationFactor;\n private boolean observeOnly;\n private boolean lazyPreempionEnabled;\n\n private float maxAllowableLimitForIntraQueuePreemption;\n private float minimumThresholdForIntraQueuePreemption;\n\n // Pointer to other RM components\n private RMContext rmContext;\n private ResourceCalculator rc;\n private CapacityScheduler scheduler;\n private RMNodeLabelsManager nlm;\n\n // Internal properties to make decisions of what to preempt\n private final Map preemptionCandidates =\n new HashMap<>();\n private Map> queueToPartitions =\n new HashMap<>();\n private Map> partitionToUnderServedQueues =\n new HashMap>();\n private List\n candidatesSelectionPolicies = new ArrayList<>();\n private Set allPartitions;\n private Set leafQueueNames;\n\n // Preemptable Entities, synced from scheduler at every run\n private Map preemptableQueues;\n private Set killableContainers;\n\n @SuppressWarnings(\"unchecked\")\n public ProportionalCapacityPreemptionPolicy() {\n clock = new SystemClock();\n allPartitions = Collections.EMPTY_SET;\n leafQueueNames = Collections.EMPTY_SET;\n preemptableQueues = Collections.EMPTY_MAP;\n }\n\n @SuppressWarnings(\"unchecked\")\n @VisibleForTesting\n public ProportionalCapacityPreemptionPolicy(RMContext context,\n CapacityScheduler scheduler, Clock clock) {\n init(context.getYarnConfiguration(), context, scheduler);\n this.clock = clock;\n allPartitions = Collections.EMPTY_SET;\n leafQueueNames = Collections.EMPTY_SET;\n preemptableQueues = Collections.EMPTY_MAP;\n }\n\n public void init(Configuration config, RMContext context,\n PreemptableResourceScheduler sched) {\n LOG.info(\"Preemption monitor:\" + this.getClass().getCanonicalName());\n assert null == scheduler : \"Unexpected duplicate call to init\";\n if (!(sched instanceof CapacityScheduler)) {\n throw new YarnRuntimeException(\"Class \" +\n sched.getClass().getCanonicalName() + \" not instance of \" +\n CapacityScheduler.class.getCanonicalName());\n }\n rmContext = context;\n scheduler = (CapacityScheduler) sched;\n CapacitySchedulerConfiguration csConfig = scheduler.getConfiguration();\n\n maxIgnoredOverCapacity = csConfig.getDouble(\n CapacitySchedulerConfiguration.PREEMPTION_MAX_IGNORED_OVER_CAPACITY,\n CapacitySchedulerConfiguration.DEFAULT_PREEMPTION_MAX_IGNORED_OVER_CAPACITY);\n\n naturalTerminationFactor = csConfig.getDouble(\n CapacitySchedulerConfiguration.PREEMPTION_NATURAL_TERMINATION_FACTOR,\n CapacitySchedulerConfiguration.DEFAULT_PREEMPTION_NATURAL_TERMINATION_FACTOR);\n\n maxWaitTime = csConfig.getLong(\n CapacitySchedulerConfiguration.PREEMPTION_WAIT_TIME_BEFORE_KILL,\n CapacitySchedulerConfiguration.DEFAULT_PREEMPTION_WAIT_TIME_BEFORE_KILL);\n\n monitoringInterval = csConfig.getLong(\n CapacitySchedulerConfiguration.PREEMPTION_MONITORING_INTERVAL,\n CapacitySchedulerConfiguration.DEFAULT_PREEMPTION_MONITORING_INTERVAL);\n\n percentageClusterPreemptionAllowed = csConfig.getFloat(\n CapacitySchedulerConfiguration.TOTAL_PREEMPTION_PER_ROUND,\n CapacitySchedulerConfiguration.DEFAULT_TOTAL_PREEMPTION_PER_ROUND);\n\n observeOnly = csConfig.getBoolean(\n CapacitySchedulerConfiguration.PREEMPTION_OBSERVE_ONLY,\n CapacitySchedulerConfiguration.DEFAULT_PREEMPTION_OBSERVE_ONLY);\n\n lazyPreempionEnabled = csConfig.getBoolean(\n CapacitySchedulerConfiguration.LAZY_PREEMPTION_ENALBED,\n CapacitySchedulerConfiguration.DEFAULT_LAZY_PREEMPTION_ENABLED);\n", "answers": [" maxAllowableLimitForIntraQueuePreemption = csConfig.getFloat("], "length": 650, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "434d111a-c9d7-4805-a5ad-a5a897e55cc6", "reasoning": "After initializing configuration values, the init method reads various preemption settings from the CapacitySchedulerConfiguration. The next logical step is to load the intra‑queue preemption limits, using the corresponding config keys and defaults, similar to the earlier assignments for maxIgnoredOverCapacity, naturalTerminationFactor, etc.", "reasoning_model_answer": "maxAllowableLimitForIntraQueuePreemption = csConfig.getFloat(\n CapacitySchedulerConfiguration.PREEMPTION_MAX_ALLOWABLE_LIMIT_FOR_INTRA_QUEUE_PREEMPTION,\n CapacitySchedulerConfiguration.DEFAULT_PREEMPTION_MAX_ALLOWABLE_LIMIT_FOR_INTRA_QUEUE_PREEMPTION);", "assistant_with_reasoning": "\nAfter initializing configuration values, the init method reads various preemption settings from the CapacitySchedulerConfiguration. The next logical step is to load the intra‑queue preemption limits, using the corresponding config keys and defaults, similar to the earlier assignments for maxIgnoredOverCapacity, naturalTerminationFactor, etc.\n\nmaxAllowableLimitForIntraQueuePreemption = csConfig.getFloat(\n CapacitySchedulerConfiguration.PREEMPTION_MAX_ALLOWABLE_LIMIT_FOR_INTRA_QUEUE_PREEMPTION,\n CapacitySchedulerConfiguration.DEFAULT_PREEMPTION_MAX_ALLOWABLE_LIMIT_FOR_INTRA_QUEUE_PREEMPTION);", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 5.246, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 8435, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "maxAllowableLimitForIntraQueuePreemption = csConfig.getFloat(\n CapacitySchedulerConfiguration.PREEMPTION_MAX_ALLOWABLE_LIMIT_FOR_INTRA_QUEUE_PREEMPTION,\n CapacitySchedulerConfiguration.DEFAULT_PREEMPTION_MAX_ALLOWABLE_LIMIT_FOR_INTRA_QUEUE_PREEMPTION);", "score": 0.97, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/*\n * XmlNodeReader.cs - Implementation of the \"System.Xml.XmlNodeReader\" class.\n *\n * Copyright (C) 2002 Southern Storm Software, Pty Ltd.\n *\n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n */\n \nnamespace System.Xml\n{\n\n#if !ECMA_COMPAT\n\nusing System;\nusing System.IO;\nusing System.Text;\nusing System.Diagnostics;\nusing System.Globalization;\n\npublic class XmlNodeReader : XmlReader\n{\n\t// Internal state.\n\tprivate XmlNode startNode;\n\tprivate XmlNode currentNode;\n\tprivate XmlDocument doc;\n\tprivate ReadState readState;\n\n\tprivate bool isAttributeReader = false;\n\tprivate bool isEndElement = false;\n\tprivate bool skipThisNode = true;\n\tprivate int attributePosn;\n\tprivate int depth = 0;\n\tprivate bool inAttrValue = false;\n\n\t// Constructor.\n\tpublic XmlNodeReader(XmlNode node)\n\t{\n\t\tstartNode = currentNode = node;\n\t\tif(node.NodeType == XmlNodeType.Document)\n\t\t{\n\t\t\tdoc = (XmlDocument) (node);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tdoc = node.OwnerDocument;\n\t\t}\n\t\tif(node.NodeType == XmlNodeType.Attribute)\n\t\t{\n\t\t\tthis.isAttributeReader = true;\n\t\t}\n\t\tif(node.NodeType != XmlNodeType.Document &&\n\t\t\tnode.NodeType != XmlNodeType.DocumentFragment)\n\t\t{\n\t\t\tskipThisNode = false;\n\t\t}\n\t\tthis.readState = ReadState.Initial;\n\t}\n\n\t// Clean up the resources that were used by this XML reader.\n\tpublic override void Close()\n\t{\n\t\treadState = ReadState.Closed;\n\t}\n\n\t// Returns the value of an attribute with a specific index.\n\tpublic override String GetAttribute(int attributeIndex)\n\t{\n\t\tif(this.isAttributeReader || (!this.InReadState))\n\t\t{\n\t\t\treturn null;\n\t\t}\n\n\t\tif(attributeIndex < 0 || attributeIndex >= this.AttributeCount)\n\t\t{\n\t\t\tthrow new ArgumentOutOfRangeException(\"attributeIndex\");\n\t\t}\n\n\t\tswitch(this.currentNode.NodeType)\n\t\t{\n\t\t\tcase XmlNodeType.Element: \n\t\t\t{\n\t\t\t\treturn ((XmlElement)\n\t\t\t\t\t\t(this.currentNode)).Attributes[attributeIndex].Value;\n\t\t\t}\n\t\t\tbreak;\n\n\t\t\tcase XmlNodeType.Attribute:\n\t\t\t{\n\t\t\t\tXmlElement element = (XmlElement)(this.currentNode.ParentNode);\n\t\t\t\treturn element.Attributes[attributeIndex].Value;\n\t\t\t}\n\t\t\tbreak;\n\t\t\t\n\t\t\tcase XmlNodeType.DocumentType:\n\t\t\t{\n\t\t\t\t// TODO\n\t\t\t}\n\t\t\tbreak;\n\n\t\t\tcase XmlNodeType.XmlDeclaration:\n\t\t\t{\n\t\t\t\t// TODO\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\t\n\t\treturn null;\n\t}\n\t// Returns the value of an attribute with a specific name.\n\tpublic override String GetAttribute(String name, String namespaceURI)\n\t{\n\t\tif(this.isAttributeReader || (!this.InReadState))\n\t\t{\n\t\t\treturn null;\n\t\t}\n\n\t\tswitch(this.currentNode.NodeType)\n\t\t{\n\t\t\tcase XmlNodeType.Element: \n\t\t\t{\n\t\t\t\treturn ((XmlElement)\n\t\t\t\t\t\t(this.currentNode)).GetAttribute(name, namespaceURI);\n\t\t\t}\n\t\t\tbreak;\n\n\t\t\tcase XmlNodeType.Attribute:\n\t\t\t{\n\t\t\t\tXmlElement element = (XmlElement)(this.currentNode.ParentNode);\n\t\t\t\treturn element.GetAttribute(name, namespaceURI);\n\t\t\t}\n\t\t\tbreak;\n\t\t\t\n\t\t\tcase XmlNodeType.DocumentType:\n\t\t\t{\n\t\t\t\t// TODO\n\t\t\t}\n\t\t\tbreak;\n\n\t\t\tcase XmlNodeType.XmlDeclaration:\n\t\t\t{\n\t\t\t\t// TODO\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\t\n\t\treturn null;\n\t}\n\n\t// Returns the value of an attribute with a specific qualified name.\n\tpublic override String GetAttribute(String name)\n\t{\n\t\tif(this.isAttributeReader || (!this.InReadState))\n\t\t{\n\t\t\treturn null;\n\t\t}\n\n\t\tswitch(this.currentNode.NodeType)\n\t\t{\n\t\t\tcase XmlNodeType.Element: \n\t\t\t{\n\t\t\t\treturn ((XmlElement)\n\t\t\t\t\t\t(this.currentNode)).GetAttribute(name);\n\t\t\t}\n\t\t\tbreak;\n\n\t\t\tcase XmlNodeType.Attribute:\n\t\t\t{\n\t\t\t\tXmlElement element = (XmlElement)(this.currentNode.ParentNode);\n\t\t\t\treturn element.GetAttribute(name);\n\t\t\t}\n\t\t\tbreak;\n\t\t\t\n\t\t\tcase XmlNodeType.DocumentType:\n\t\t\t{\n\t\t\t\t// TODO\n\t\t\t}\n\t\t\tbreak;\n\n\t\t\tcase XmlNodeType.XmlDeclaration:\n\t\t\t{\n\t\t\t\t// TODO\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\t\n\t\treturn null;\n\t}\n\n\t// Resolve a namespace in the scope of the current element.\n\tpublic override String LookupNamespace(String prefix)\n\t{\n\t\tif(!this.InReadState)\n\t\t{\n\t\t\treturn null;\n\t\t}\n\t\tif(prefix == \"xmlns\")\n\t\t{\n\t\t\treturn XmlDocument.xmlns; \n\t\t}\n\t\t\n\t\tif(this.isAttributeReader)\n\t\t{\n\t\t\t// prefix lookups on attributes are supposed \n\t\t\t// to work for 'xmlns'. w3rd\n\t\t\treturn null;\n\t\t}\n\n\t\tXmlElement element = null;\n\t\tString attrName = \"xmlns\" + (prefix == String.Empty ? \"\" : \":\"+prefix);\n\t\tString ns = null;\n\n\t\tfor(XmlNode node = this.currentNode; \n\t\t\tnode != null; node = node.ParentNode)\n\t\t{\n\t\t\telement = (node as XmlElement);", "answers": ["\t\t\tif(element == null)"], "length": 576, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "29724a2e-da61-4b0b-a9cf-4cafd0dc29e0", "reasoning": "Inside LookupNamespace, after casting each node to XmlElement, the next logical step is to check whether the cast succeeded before trying to read the namespace attribute. Therefore the next line should be an if statement testing element for null.", "reasoning_model_answer": "if (element != null) {", "assistant_with_reasoning": "\nInside LookupNamespace, after casting each node to XmlElement, the next logical step is to check whether the cast succeeded before trying to read the namespace attribute. Therefore the next line should be an if statement testing element for null.\n\nif (element != null) {", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.709, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 4948, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "if (element != null) {", "score": 0.82, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "import ast\nimport copy\nimport json\nimport logging\nimport uuid\nfrom datetime import datetime\n\nfrom django.conf import settings\nfrom django.core.cache import cache\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom django.db import transaction\nfrom django.db.models import F\nfrom django.db.models import Max\nfrom django.db.models import Q\nfrom django.db.models import Sum\nfrom django.http import HttpResponse\nfrom django.http import HttpResponseBadRequest\nfrom django.http import HttpResponseNotFound\nfrom django.utils.translation import ugettext as _\nfrom le_utils.constants import content_kinds\nfrom le_utils.constants import format_presets\nfrom le_utils.constants import roles\nfrom rest_framework.authentication import SessionAuthentication\nfrom rest_framework.authentication import TokenAuthentication\nfrom rest_framework.decorators import api_view\nfrom rest_framework.decorators import authentication_classes\nfrom rest_framework.decorators import permission_classes\nfrom rest_framework.permissions import IsAuthenticated\nfrom rest_framework.renderers import JSONRenderer\nfrom rest_framework.response import Response\n\nfrom contentcuration.models import AssessmentItem\nfrom contentcuration.models import Channel\nfrom contentcuration.models import ContentNode\nfrom contentcuration.models import ContentTag\nfrom contentcuration.models import File\nfrom contentcuration.models import generate_storage_url\nfrom contentcuration.models import Language\nfrom contentcuration.models import License\nfrom contentcuration.models import PrerequisiteContentRelationship\nfrom contentcuration.serializers import ContentNodeEditSerializer\nfrom contentcuration.serializers import ContentNodeSerializer\nfrom contentcuration.serializers import SimplifiedContentNodeSerializer\nfrom contentcuration.tasks import getnodedetails_task\nfrom contentcuration.utils.files import duplicate_file\n\n\n@authentication_classes((TokenAuthentication, SessionAuthentication))\n@permission_classes((IsAuthenticated,))\ndef get_node_diff(request, channel_id):\n original = [] # Currently imported nodes\n changed = [] # Nodes from original node\n fields_to_check = ['title', 'description', 'license', 'license_description', 'copyright_holder', 'author', 'extra_fields', 'language', 'role_visibility']\n assessment_fields_to_check = ['type', 'question', 'hints', 'answers', 'order', 'raw_data', 'source_url', 'randomize']\n\n current_tree_id = Channel.objects.get(pk=channel_id).main_tree.tree_id\n nodes = ContentNode.objects.prefetch_related('assessment_items').prefetch_related('files').prefetch_related('tags')\n\n copied_nodes = nodes.filter(tree_id=current_tree_id).exclude(original_source_node_id=F('node_id'))\n channel_ids = copied_nodes.values_list('original_channel_id', flat=True).exclude(original_channel_id=channel_id).distinct()\n tree_ids = Channel.objects.filter(pk__in=channel_ids).values_list(\"main_tree__tree_id\", flat=True)\n original_node_ids = copied_nodes.values_list('original_source_node_id', flat=True).distinct()\n original_nodes = nodes.filter(tree_id__in=tree_ids, node_id__in=original_node_ids)\n\n # Use dictionary for faster lookup speed\n content_id_mapping = {n.content_id: n for n in original_nodes}\n\n for copied_node in copied_nodes:\n node = content_id_mapping.get(copied_node.content_id)\n\n if node:\n # Check lengths, metadata, tags, files, and assessment items\n node_changed = node.assessment_items.count() != copied_node.assessment_items.count() or \\\n node.files.count() != copied_node.files.count() or \\\n node.tags.count() != copied_node.tags.count() or \\\n any(filter(lambda f: getattr(node, f, None) != getattr(copied_node, f, None), fields_to_check)) or \\\n node.tags.exclude(tag_name__in=copied_node.tags.values_list('tag_name', flat=True)).exists() or \\\n node.files.exclude(checksum__in=copied_node.files.values_list('checksum', flat=True)).exists() or \\\n node.assessment_items.exclude(assessment_id__in=copied_node.assessment_items.values_list('assessment_id', flat=True)).exists()\n\n # Check individual assessment items\n if not node_changed and node.kind_id == content_kinds.EXERCISE:\n for ai in node.assessment_items.all():\n source_ai = copied_node.assessment_items.filter(assessment_id=ai.assessment_id).first()\n if source_ai:\n node_changed = node_changed or any(filter(lambda f: getattr(ai, f, None) != getattr(source_ai, f, None), assessment_fields_to_check))\n if node_changed:\n break\n\n if node_changed:\n original.append(copied_node)\n changed.append(node)\n\n serialized_original = JSONRenderer().render(SimplifiedContentNodeSerializer(original, many=True).data)\n serialized_changed = JSONRenderer().render(SimplifiedContentNodeSerializer(changed, many=True).data)\n\n return HttpResponse(json.dumps({\n \"original\": serialized_original,\n \"changed\": serialized_changed,\n }))\n\n\ndef create_new_node(request):\n if request.method != 'POST':\n return HttpResponseBadRequest(\"Only POST requests are allowed on this endpoint.\")\n\n data = json.loads(request.body)\n license = License.objects.filter(license_name=data.get('license_name')).first() # Use filter/first in case preference hasn't been set\n license_id = license.pk if license else settings.DEFAULT_LICENSE\n new_node = ContentNode.objects.create(\n kind_id=data.get('kind'),\n title=data.get('title'),\n author=data.get('author'),\n aggregator=data.get('aggregator'),\n provider=data.get('provider'),\n copyright_holder=data.get('copyright_holder'),\n license_id=license_id,\n license_description=data.get('license_description'),\n parent_id=settings.ORPHANAGE_ROOT_ID,\n )\n return HttpResponse(JSONRenderer().render(ContentNodeEditSerializer(new_node).data))\n\n\n@api_view(['GET'])\ndef get_prerequisites(request, get_prerequisites, ids):\n nodes = ContentNode.objects.prefetch_related('prerequisite').filter(pk__in=ids.split(\",\"))\n\n prerequisite_mapping = {}\n postrequisite_mapping = {}\n prerequisite_tree_nodes = []\n\n for n in nodes:\n prereqs, prereqmapping = n.get_prerequisites()\n if get_prerequisites == \"true\":\n postreqs, postreqmapping = n.get_postrequisites()\n postrequisite_mapping.update(postreqmapping)\n prerequisite_mapping.update(prereqmapping)\n prerequisite_tree_nodes += prereqs + postreqs + [n]\n else:\n prerequisite_mapping.update({n.pk: prereqmapping})\n prerequisite_tree_nodes += prereqs + [n]\n\n return HttpResponse(json.dumps({\n \"prerequisite_mapping\": prerequisite_mapping,\n \"postrequisite_mapping\": postrequisite_mapping,\n \"prerequisite_tree_nodes\": JSONRenderer().render(SimplifiedContentNodeSerializer(prerequisite_tree_nodes, many=True).data),\n }))\n\n\n@api_view(['GET'])\ndef get_total_size(request, ids):\n sizes = ContentNode.objects.prefetch_related('assessment_items', 'files', 'children')\\\n .exclude(kind_id=content_kinds.EXERCISE, published=False)\\\n .filter(id__in=ids.split(\",\")).get_descendants(include_self=True)\\\n .values('files__checksum', 'files__file_size')\\\n .distinct().aggregate(resource_size=Sum('files__file_size'))\n\n return HttpResponse(json.dumps({'success': True, 'size': sizes['resource_size'] or 0}))\n\n\n@api_view(['GET'])\ndef get_nodes_by_ids(request, ids):\n nodes = ContentNode.objects.prefetch_related('children', 'files', 'assessment_items', 'tags')\\\n .filter(pk__in=ids.split(\",\"))\\\n .defer('node_id', 'original_source_node_id', 'source_node_id', 'content_id',\n 'original_channel_id', 'source_channel_id', 'source_id', 'source_domain', 'created', 'modified')\n serializer = ContentNodeSerializer(nodes, many=True)\n return Response(serializer.data)\n\n\ndef get_node_path(request, topic_id, tree_id, node_id):\n try:\n topic = ContentNode.objects.prefetch_related('children').get(node_id__startswith=topic_id, tree_id=tree_id)\n\n if topic.kind_id != content_kinds.TOPIC:\n node = ContentNode.objects.prefetch_related('files', 'assessment_items', 'tags').get(node_id__startswith=topic_id, tree_id=tree_id)\n nodes = node.get_ancestors(ascending=True)\n else:\n node = node_id and ContentNode.objects.prefetch_related('files', 'assessment_items', 'tags').get(node_id__startswith=node_id, tree_id=tree_id)\n nodes = topic.get_ancestors(include_self=True, ascending=True)\n\n return HttpResponse(json.dumps({\n 'path': JSONRenderer().render(ContentNodeSerializer(nodes, many=True).data),\n 'node': node and JSONRenderer().render(ContentNodeEditSerializer(node).data),\n 'parent_node_id': topic.kind_id != content_kinds.TOPIC and node.parent and node.parent.node_id\n }))\n except ObjectDoesNotExist:\n return HttpResponseNotFound(\"Invalid URL: the referenced content does not exist in this channel.\")\n\n\n@api_view(['GET'])\ndef get_nodes_by_ids_simplified(request, ids):\n nodes = ContentNode.objects.prefetch_related('children').filter(pk__in=ids.split(\",\"))\n serializer = SimplifiedContentNodeSerializer(nodes, many=True)\n return Response(serializer.data)\n", "answers": ["@api_view(['GET'])"], "length": 607, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "0dfa76ce-115e-46ba-b027-cd6d2102d281", "reasoning": "The file ends with the function get_nodes_by_ids_simplified, which returns a Response. In the same module, other view functions are defined with @api_view decorators. The next logical piece is likely another view, starting with its decorator. Given the imported getnodedetails_task, the next line would begin a new view definition, starting with the @api_view decorator for a GET endpoint.", "reasoning_model_answer": "@api_view(['GET'])", "assistant_with_reasoning": "\nThe file ends with the function get_nodes_by_ids_simplified, which returns a Response. In the same module, other view functions are defined with @api_view decorators. The next logical piece is likely another view, starting with its decorator. Given the imported getnodedetails_task, the next line would begin a new view definition, starting with the @api_view decorator for a GET endpoint.\n\n@api_view(['GET'])", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.516, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 9715, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "@api_view(['GET'])", "score": 1.0, "is_full_score": true, "is_nonzero_score": true}} {"input": "", "context": "using System;\nusing System.Collections.Generic;\nusing System.Text;\nusing System.Drawing.Printing;\nusing System.Drawing;\nusing System.Data;\n\n\nnamespace Factotum\n{\n\tclass RsGrid : ReportSection\n\t{\n\t\t// If we couldn't fit the whole grid on a page, we need to keep track of \n\t\t// where in the grid to start up again. \n\t\tprivate int startRow;\n\t\tprivate int startCol;\n\t\tprivate int startWeldIdx; // The starting weld index for the current chunk of rows\n\t\tprivate int curWeldIdx; // The current weld index\n\n\t\t// This is about as narrow as we can make columns.\n\t\tprivate const float colWidth = 36;\n\n\t\tpublic RsGrid(MainReport report, ReportSectionRules rules, int subsections)\n\t\t\t: base(report, rules, subsections)\n\t\t{\n\t\t\tstartRow = 0;\n\t\t\tstartCol = 0;\n\t\t\tstartWeldIdx = 0;\n\t\t\tcurWeldIdx = 0;\n\t\t}\n\n\t\t// Incude the section only if we have a grid.\n\t\tpublic override bool IsIncluded() \n\t\t{\n\t\t\treturn (rpt.eInspection != null && rpt.eInspection.InspectionHasGrid\n\t\t\t\t&& rpt.eGrid.GridStartRow != null & rpt.eGrid.GridStartCol != null\n\t\t\t\t&& rpt.eGrid.GridEndRow != null & rpt.eGrid.GridEndCol != null);\n\t\t}\n\n\t\tpublic override bool CanFitSome(PrintPageEventArgs args, float Y) \n\t\t{\n\t\t\t// We only return true if we can fit the entire grid on the current page.\n\n\t\t\t// This is also the perfect place to decide about page orientation.\n\t\t\t// If the number of columns is such that fewer page widths will be required to cover\n\t\t\t// the columns in landscape than in portrait, we want to set next page to landscape here.\n\n\t\t\t// If we're not on the first page, we can definitely fit some. \n\t\t\t// We'll also leave the orientation the same as prior pages.\n\t\t\tif (startRow > 0 || startCol > 0) return true;\n\n\t\t\t// See if we can fit ALL the columns on what's left of the current page and at least a few rows.\n\t\t\t// Add 2 to the end column (1 for zero-based + 1 for header row/col)\n\t\t\t// Changed to 15 -- it was still splitting tables too often...\n\t\t\tint minRows = 15;\n\t\t\tif (args.MarginBounds.Width > (rpt.eGrid.GridEndCol - rpt.eGrid.GridStartCol + 2) * colWidth)\n\t\t\t{\n\t\t\t\tif (args.MarginBounds.Bottom - Y - rpt.footerHeight > minRows * rowHeight())\n\t\t\t\t\treturn true;\n\t\t\t\telse\n\t\t\t\t\treturn false; // Not too many columns, so keep portrait orientation\n\t\t\t}\n\t\t\t// We can't fit any on the current page. Decide on the orientation.\n\t\t\tif (IsLandscapeBetter(args)) rpt.nextPageLandscape = true;\n\n\t\t\treturn false;\n\t\t}\n\n\t\t// Get the row height\n\t\tprivate float rowHeight()\n\t\t{\n\t\t\treturn rpt.smallTextFont.Height + 2;\n\t\t}\n\n\t\t// Figure out how many rows will fill a page in the current orientation.\n\t\tprivate int rowsToFillPage(PrintPageEventArgs args, float curY)\n\t\t{\n\t\t\treturn (int)((args.MarginBounds.Bottom - curY - rpt.footerHeight) / rowHeight());\n\t\t}\n\n\t\t// Figure out how many columns will fill a page in the current orientation.\n\t\tprivate int colsToFillPage(PrintPageEventArgs args)\n\t\t{\n\t\t\treturn (int)(args.MarginBounds.Width / colWidth);\n\t\t}\n\n\t\t// We should be in portrait mode when this function is called.\n\t\tprivate bool IsLandscapeBetter(PrintPageEventArgs args)\n\t\t{\n\t\t\tint cols = (int)rpt.eGrid.GridEndCol - (int)rpt.eGrid.GridStartCol + 1; // The data columns in the grid\n\t\t\tint rows = (int)rpt.eGrid.GridEndRow - (int)rpt.eGrid.GridStartRow + 1; // The data rows in the grid \n\t\t\tfloat width = args.MarginBounds.Width;\n\t\t\tfloat height = args.MarginBounds.Height;\n\t\t\tSystem.Diagnostics.Debug.Assert(height > width);\n\t\t\tint portraitPages;\n\t\t\tint landscapePages;\n\t\t\t// First get the number of pages to cover all the columns for a single chunk of rows.\n\t\t\t// Subtract off a column width in the denominator for the row heading column\n\t\t\tint portraitPagesToSpanCols = (int)(cols * colWidth / (width - colWidth) + 1);\n\t\t\tint landscapePagesToSpanCols = (int) (cols * colWidth / (height - colWidth) + 1);\n\t\t\tfloat rowsPerPortraitPage = (args.MarginBounds.Height - rpt.footerHeight - rowHeight()) / rowHeight();\n\t\t\tfloat rowsPerLandscapePage = (args.MarginBounds.Width - rpt.footerHeight - rowHeight()) / rowHeight();\n\t\t\tportraitPages = portraitPagesToSpanCols * (int)(rows / rowsPerPortraitPage + 1);\n\t\t\tlandscapePages = landscapePagesToSpanCols * (int)(rows / rowsPerPortraitPage + 1);\n\n\t\t\t// If it's a tie, keep it in portrait\n\t\t\treturn (landscapePages < portraitPages);\n\n\t\t}\n", "answers": ["\t\tpublic override bool Print(PrintPageEventArgs args, float Y) "], "length": 612, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "24565fd5-ccfa-461a-9258-781492c04c89", "reasoning": "The class RsGrid inherits from ReportSection and has already implemented several helper methods. The next logical member is the method that actually renders the grid on the page, which in the base class is typically named DrawSection and overrides a virtual method. Following the style of earlier method definitions (signature line then opening brace on the next line), the next line should be the method signature for DrawSection.", "reasoning_model_answer": "public override void DrawSection(PrintPageEventArgs args, float Y)", "assistant_with_reasoning": "\nThe class RsGrid inherits from ReportSection and has already implemented several helper methods. The next logical member is the method that actually renders the grid on the page, which in the base class is typically named DrawSection and overrides a virtual method. Following the style of earlier method definitions (signature line then opening brace on the next line), the next line should be the method signature for DrawSection.\n\npublic override void DrawSection(PrintPageEventArgs args, float Y)", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.58, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 4342, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "public override void DrawSection(PrintPageEventArgs args, float Y)", "score": 0.82, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "from django.contrib.auth.models import User\n\nfrom core.tests import datautil\nfrom package.models import Category, Package, Version\nfrom profiles.models import Profile\n\n\ndef load():\n category, created = Category.objects.get_or_create(\n pk=2,\n description=u'Large efforts that combine many python modules or apps. Examples include Django, Pinax, and Satchmo. Most CMS falls into this category.',\n show_pypi=True,\n title_plural=u'Frameworks',\n title=u'Framework',\n slug=u'frameworks',\n )\n\n package, created = Package.objects.get_or_create(\n pk=6,\n category=category,\n title=u'Django CMS',\n created_by=None,\n repo_watchers=967,\n pypi_url=u'http://pypi.python.org/pypi/django-cms',\n pypi_downloads=26257,\n last_modified_by=None,\n repo_url=u'https://github.com/divio/django-cms',\n participants=u'chrisglass,digi604,erobit,fivethreeo,ojii,stefanfoulis,pcicman,DrMeers,brightwhitefox,FlashJunior,philomat,jezdez,havan,acdha,m000,hedberg,piquadrat,spookylukey,izimobil,ulope,emiquelito,aaloy,lasarux,yohanboniface,aparo,jsma,johbo,ionelmc,quattromic,almost,specialunderwear,mitar,yml,pajusmar,diofeher,marcor,cortextual,hysia,dstufft,ssteinerx,oversize,jalaziz,tercerojista,eallik,f4nt,kaapa,mbrochh,srj55,dz,mathijs-dumon,sealibora,cyberj,adsworth,tokibito,DaNmarner,IanLewis,indexofire,bneijt,tehfink,PPvG,seyhunak,pigletto,fcurella,gleb-chipiga,beshrkayali,kinea,lucasvo,jordanjambazov,tonnzor,centralniak,arthur-debert,bzed,jasondavies,nimnull,limpbrains,pvanderlinden,sleytr,sublimevelo,netpastor,dtt101,fkazimierczak,merlex,mrlundis,restless,eged,shanx,ptoal',\n # usage=[129, 50, 43, 183, 87, 204, 1, 231, 233, 239, 241, 248, 252, 262, 263, 268, 282, 284, 298, 32, 338, 342, 344, 345, 348, 355, 388, 401, 295, 36, 444, 422, 449, 157, 457, 462, 271, 143, 433, 554, 448, 470, 562, 86, 73, 504, 610, 621, 651, 663, 688, 661, 766, 770, 773, 799, 821, 834, 847, 848, 850, 322, 883, 823, 958, 387, 361, 123, 1026, 516, 715, 1105],\n repo_commits=0,\n repo_forks=283,\n slug=u'django-cms',\n repo_description=u'An Advanced Django CMS.',\n )\n\n user, created = User.objects.get_or_create(\n pk=129,\n username=u'unbracketed',\n first_name=u'',\n last_name=u'',\n is_active=True,\n is_superuser=False,\n is_staff=False,\n last_login=u'2010-08-28 20:48:35',\n # groups=[],\n # user_permissions=[],\n password=u'sha1$a5c47$0e9be0aee0cb60648a3e0a70f462e0943a46aeab',\n email=u'brian@unbracketed.com',\n date_joined=u'2010-08-28 20:47:52',\n )\n\n user, created = User.objects.get_or_create(\n pk=50,\n username=u'ojii',\n first_name=u'',\n last_name=u'',\n is_active=True,\n is_superuser=False,\n is_staff=False,\n last_login=u'2011-03-09 14:50:02',\n # groups=[],\n # user_permissions=[],\n password=u'sha1$a7428$563858792ba94c8706db374eed9d2708536ea2a5',\n email=u'jonas.obrist@divio.ch',\n date_joined=u'2010-08-18 03:35:23',\n )\n user, created = User.objects.get_or_create(\n pk=43,\n username=u'vvarp',\n first_name=u'',\n last_name=u'',\n is_active=True,\n is_superuser=False,\n is_staff=False,\n last_login=u'2010-09-29 12:08:01',\n # groups=[],\n # user_permissions=[],\n password=u'sha1$ed0c0$ec7ed6b92a963fd02cd0e1e1fcd90d66591a29b8',\n email=u'maciek@id43.net',\n date_joined=u'2010-08-17 18:43:12',\n )\n user, created = User.objects.get_or_create(\n pk=183,\n username=u'onjin',\n first_name=u'',\n last_name=u'',\n is_active=True,\n is_superuser=False,\n is_staff=False,\n last_login=u'2010-09-09 07:47:11',\n # groups=[],\n # user_permissions=[],\n password=u'sha1$1965c$9b8cc38cec3672b515787c227a3ef7ceea2ae785',\n email=u'onjinx@gmail.com',\n date_joined=u'2010-09-07 02:23:11',\n )\n user, created = User.objects.get_or_create(\n pk=87,\n username=u'jezdez',\n first_name=u'',\n last_name=u'',\n is_active=True,\n is_superuser=False,\n is_staff=False,\n last_login=u'2011-02-09 09:29:33',\n # groups=[],\n # user_permissions=[],\n password=u'sha1$97523$0d3cdbbd2930052fe89ebf38ef7267bc85479032',\n email=u'jannis@leidel.info',\n date_joined=u'2010-08-21 04:14:03',\n )\n user, created = User.objects.get_or_create(\n pk=204,\n username=u'flmendes',\n first_name=u'',\n last_name=u'',\n is_active=True,\n is_superuser=False,\n is_staff=False,\n last_login=u'2010-09-14 18:01:16',\n # groups=[],\n # user_permissions=[],\n password=u'sha1$68ef6$750d02a7c6a1b8d14adb31a8374cb18d6f37708e',\n email=u'flmendes@gmail.com',\n date_joined=u'2010-09-08 22:49:34',\n )\n user, created = User.objects.get_or_create(\n pk=1,\n username=u'audreyr',\n first_name=u'',\n last_name=u'',\n is_active=True,\n is_superuser=True,\n is_staff=True,\n last_login=u'2011-03-13 23:44:00',\n # groups=[],\n # user_permissions=[],\n password=u'sha1$c84c1$dfd3748f63f48e2639d3c4d1caa113acf6bde51f',\n email=u'audreyr@gmail.com',\n date_joined=u'2010-08-15 22:15:50',\n )\n user, created = User.objects.get_or_create(\n pk=231,\n username=u'digi604',\n first_name=u'',\n last_name=u'',\n is_active=True,\n is_superuser=False,\n is_staff=False,\n last_login=u'2010-09-12 07:34:07',\n # groups=[],\n # user_permissions=[],\n password=u'sha1$0f7f5$523594505138d1182fa413826c02b1e32ee8b95c',\n email=u'digi@treepy.com',\n date_joined=u'2010-09-12 07:32:42',\n )\n user, created = User.objects.get_or_create(\n pk=233,\n username=u'mikl',\n first_name=u'',\n last_name=u'',\n is_active=True,\n is_superuser=False,\n is_staff=False,\n last_login=u'2010-09-12 08:57:34',\n # groups=[],\n # user_permissions=[],\n password=u'sha1$c4af2$e50af5facac17d8b6cd83e7ccc06dee27e33a6a1',\n email=u'mikkel@hoegh.org',\n date_joined=u'2010-09-12 08:56:36',\n )\n user, created = User.objects.get_or_create(\n pk=239,\n username=u'arthurk',\n first_name=u'',\n last_name=u'',\n is_active=True,\n is_superuser=False,\n is_staff=False,\n last_login=u'2010-09-12 19:13:47',\n # groups=[],\n # user_permissions=[],\n password=u'sha1$dbc73$f0d8c4476121c8a66fae45f7131db9df71e9aab4',\n email=u'arthur@arthurkoziel.com',\n date_joined=u'2010-09-12 19:12:55',\n )\n user, created = User.objects.get_or_create(\n pk=241,\n username=u'juacompe',\n first_name=u'',\n last_name=u'',\n is_active=True,\n is_superuser=False,\n is_staff=False,\n last_login=u'2010-09-13 03:23:21',\n # groups=[],\n # user_permissions=[],\n password=u'sha1$d08ef$4f9c0272cafe2ce6b5619c79f8ecf7f6dd3c024e',\n email=u'juacompe@gmail.com',\n date_joined=u'2010-09-13 03:10:39',\n )\n user, created = User.objects.get_or_create(\n pk=248,\n username=u'kocakafa',\n first_name=u'',\n last_name=u'',\n is_active=True,\n is_superuser=False,\n is_staff=False,\n last_login=u'2010-09-13 10:09:36',\n # groups=[],\n # user_permissions=[],\n password=u'sha1$624bd$101a762ea78432c4a4c25c3a4f2558e14126b0d5',\n email=u'cemrekutluay@gmail.com',\n date_joined=u'2010-09-13 10:08:40',\n )\n user, created = User.objects.get_or_create(\n pk=252,\n username=u'dmoisset',", "answers": [" first_name=u'',"], "length": 422, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "d6983f20-99ee-4632-a4ef-176d3213aa48", "reasoning": "The code is defining a series of User objects using get_or_create. Each block lists fields in a consistent order: pk, username, first_name, last_name, is_active, ... The snippet ends right after the username line for the user with pk=252. Following the established pattern, the next line should specify the first_name field, which for these users is an empty Unicode string.", "reasoning_model_answer": "first_name=u'',", "assistant_with_reasoning": "\nThe code is defining a series of User objects using get_or_create. Each block lists fields in a consistent order: pk, username, first_name, last_name, is_active, ... The snippet ends right after the username line for the user with pk=252. Following the established pattern, the next line should specify the first_name field, which for these users is an empty Unicode string.\n\nfirst_name=u'',", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 2.359, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 8018, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "first_name=u'',", "score": 0.79, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "// Copyright 2018 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n/**\n * TrialAsyncErrorServiceSoapBindingStub.java\n *\n * This file was auto-generated from WSDL\n * by the Apache Axis 1.4 Mar 02, 2009 (07:08:06 PST) WSDL2Java emitter.\n */\n\npackage com.google.api.ads.adwords.axis.v201809.cm;\n\npublic class TrialAsyncErrorServiceSoapBindingStub extends org.apache.axis.client.Stub implements com.google.api.ads.adwords.axis.v201809.cm.TrialAsyncErrorServiceInterface {\n private java.util.Vector cachedSerClasses = new java.util.Vector();\n private java.util.Vector cachedSerQNames = new java.util.Vector();\n private java.util.Vector cachedSerFactories = new java.util.Vector();\n private java.util.Vector cachedDeserFactories = new java.util.Vector();\n\n static org.apache.axis.description.OperationDesc [] _operations;\n\n static {\n _operations = new org.apache.axis.description.OperationDesc[2];\n _initOperationDesc1();\n }\n\n private static void _initOperationDesc1(){\n org.apache.axis.description.OperationDesc oper;\n org.apache.axis.description.ParameterDesc param;\n oper = new org.apache.axis.description.OperationDesc();\n oper.setName(\"get\");\n param = new org.apache.axis.description.ParameterDesc(new javax.xml.namespace.QName(\"https://adwords.google.com/api/adwords/cm/v201809\", \"selector\"), org.apache.axis.description.ParameterDesc.IN, new javax.xml.namespace.QName(\"https://adwords.google.com/api/adwords/cm/v201809\", \"Selector\"), com.google.api.ads.adwords.axis.v201809.cm.Selector.class, false, false);\n param.setOmittable(true);\n oper.addParameter(param);\n oper.setReturnType(new javax.xml.namespace.QName(\"https://adwords.google.com/api/adwords/cm/v201809\", \"TrialAsyncErrorPage\"));\n oper.setReturnClass(com.google.api.ads.adwords.axis.v201809.cm.TrialAsyncErrorPage.class);\n oper.setReturnQName(new javax.xml.namespace.QName(\"https://adwords.google.com/api/adwords/cm/v201809\", \"rval\"));\n oper.setStyle(org.apache.axis.constants.Style.WRAPPED);\n oper.setUse(org.apache.axis.constants.Use.LITERAL);\n oper.addFault(new org.apache.axis.description.FaultDesc(\n new javax.xml.namespace.QName(\"https://adwords.google.com/api/adwords/cm/v201809\", \"ApiExceptionFault\"),\n \"com.google.api.ads.adwords.axis.v201809.cm.ApiException\",\n new javax.xml.namespace.QName(\"https://adwords.google.com/api/adwords/cm/v201809\", \"ApiException\"), \n true\n ));\n _operations[0] = oper;\n\n oper = new org.apache.axis.description.OperationDesc();\n oper.setName(\"query\");\n param = new org.apache.axis.description.ParameterDesc(new javax.xml.namespace.QName(\"https://adwords.google.com/api/adwords/cm/v201809\", \"query\"), org.apache.axis.description.ParameterDesc.IN, new javax.xml.namespace.QName(\"http://www.w3.org/2001/XMLSchema\", \"string\"), java.lang.String.class, false, false);\n param.setOmittable(true);\n oper.addParameter(param);\n oper.setReturnType(new javax.xml.namespace.QName(\"https://adwords.google.com/api/adwords/cm/v201809\", \"TrialAsyncErrorPage\"));\n oper.setReturnClass(com.google.api.ads.adwords.axis.v201809.cm.TrialAsyncErrorPage.class);\n oper.setReturnQName(new javax.xml.namespace.QName(\"https://adwords.google.com/api/adwords/cm/v201809\", \"rval\"));\n oper.setStyle(org.apache.axis.constants.Style.WRAPPED);\n oper.setUse(org.apache.axis.constants.Use.LITERAL);\n oper.addFault(new org.apache.axis.description.FaultDesc(\n new javax.xml.namespace.QName(\"https://adwords.google.com/api/adwords/cm/v201809\", \"ApiExceptionFault\"),\n \"com.google.api.ads.adwords.axis.v201809.cm.ApiException\",\n new javax.xml.namespace.QName(\"https://adwords.google.com/api/adwords/cm/v201809\", \"ApiException\"), \n true\n ));\n _operations[1] = oper;\n\n }\n\n public TrialAsyncErrorServiceSoapBindingStub() throws org.apache.axis.AxisFault {\n this(null);\n }\n\n public TrialAsyncErrorServiceSoapBindingStub(java.net.URL endpointURL, javax.xml.rpc.Service service) throws org.apache.axis.AxisFault {\n this(service);\n super.cachedEndpoint = endpointURL;\n }\n\n public TrialAsyncErrorServiceSoapBindingStub(javax.xml.rpc.Service service) throws org.apache.axis.AxisFault {\n if (service == null) {\n super.service = new org.apache.axis.client.Service();\n } else {\n super.service = service;\n }\n ((org.apache.axis.client.Service)super.service).setTypeMappingVersion(\"1.2\");\n java.lang.Class cls;\n javax.xml.namespace.QName qName;\n javax.xml.namespace.QName qName2;\n java.lang.Class beansf = org.apache.axis.encoding.ser.BeanSerializerFactory.class;\n java.lang.Class beandf = org.apache.axis.encoding.ser.BeanDeserializerFactory.class;\n java.lang.Class enumsf = org.apache.axis.encoding.ser.EnumSerializerFactory.class;\n java.lang.Class enumdf = org.apache.axis.encoding.ser.EnumDeserializerFactory.class;\n java.lang.Class arraysf = org.apache.axis.encoding.ser.ArraySerializerFactory.class;\n java.lang.Class arraydf = org.apache.axis.encoding.ser.ArrayDeserializerFactory.class;\n java.lang.Class simplesf = org.apache.axis.encoding.ser.SimpleSerializerFactory.class;\n java.lang.Class simpledf = org.apache.axis.encoding.ser.SimpleDeserializerFactory.class;\n java.lang.Class simplelistsf = org.apache.axis.encoding.ser.SimpleListSerializerFactory.class;\n java.lang.Class simplelistdf = org.apache.axis.encoding.ser.SimpleListDeserializerFactory.class;\n addBindings0();\n addBindings1();\n }\n\n private void addBindings0() {\n java.lang.Class cls;\n javax.xml.namespace.QName qName;\n javax.xml.namespace.QName qName2;\n java.lang.Class beansf = org.apache.axis.encoding.ser.BeanSerializerFactory.class;\n java.lang.Class beandf = org.apache.axis.encoding.ser.BeanDeserializerFactory.class;\n java.lang.Class enumsf = org.apache.axis.encoding.ser.EnumSerializerFactory.class;\n java.lang.Class enumdf = org.apache.axis.encoding.ser.EnumDeserializerFactory.class;\n java.lang.Class arraysf = org.apache.axis.encoding.ser.ArraySerializerFactory.class;\n java.lang.Class arraydf = org.apache.axis.encoding.ser.ArrayDeserializerFactory.class;\n java.lang.Class simplesf = org.apache.axis.encoding.ser.SimpleSerializerFactory.class;\n java.lang.Class simpledf = org.apache.axis.encoding.ser.SimpleDeserializerFactory.class;\n java.lang.Class simplelistsf = org.apache.axis.encoding.ser.SimpleListSerializerFactory.class;\n java.lang.Class simplelistdf = org.apache.axis.encoding.ser.SimpleListDeserializerFactory.class;\n qName = new javax.xml.namespace.QName(\"https://adwords.google.com/api/adwords/cm/v201809\", \"AdError\");\n cachedSerQNames.add(qName);\n cls = com.google.api.ads.adwords.axis.v201809.cm.AdError.class;\n cachedSerClasses.add(cls);\n cachedSerFactories.add(beansf);\n cachedDeserFactories.add(beandf);\n\n qName = new javax.xml.namespace.QName(\"https://adwords.google.com/api/adwords/cm/v201809\", \"AdError.Reason\");\n cachedSerQNames.add(qName);\n cls = com.google.api.ads.adwords.axis.v201809.cm.AdErrorReason.class;\n cachedSerClasses.add(cls);\n cachedSerFactories.add(enumsf);\n cachedDeserFactories.add(enumdf);\n\n qName = new javax.xml.namespace.QName(\"https://adwords.google.com/api/adwords/cm/v201809\", \"AdGroupAdError\");\n cachedSerQNames.add(qName);\n cls = com.google.api.ads.adwords.axis.v201809.cm.AdGroupAdError.class;\n cachedSerClasses.add(cls);\n cachedSerFactories.add(beansf);", "answers": [" cachedDeserFactories.add(beandf);"], "length": 443, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "a50d6f80-58c5-4b56-93c8-8e53cf8b426f", "reasoning": "In addBindings0(), each type registration adds a QName, class, serializer factory, and then the corresponding deserializer factory. The snippet ends after adding the serializer factory for AdGroupAdError (cachedSerFactories.add(beansf);). The next logical line is to add its deserializer factory, mirroring the pattern used earlier.", "reasoning_model_answer": "cachedDeserFactories.add(beandf);", "assistant_with_reasoning": "\nIn addBindings0(), each type registration adds a QName, class, serializer factory, and then the corresponding deserializer factory. The snippet ends after adding the serializer factory for AdGroupAdError (cachedSerFactories.add(beansf);). The next logical line is to add its deserializer factory, mirroring the pattern used earlier.\n\ncachedDeserFactories.add(beandf);", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 2.526, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 8749, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "cachedDeserFactories.add(beandf);", "score": 0.85, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "package org.bbottema.javareflection;\n\nimport lombok.experimental.UtilityClass;\nimport org.bbottema.javareflection.model.MethodModifier;\nimport org.bbottema.javareflection.util.ExternalClassLoader;\nimport org.bbottema.javareflection.valueconverter.IncompatibleTypeException;\nimport org.bbottema.javareflection.valueconverter.ValueConversionHelper;\nimport org.jetbrains.annotations.NotNull;\nimport org.jetbrains.annotations.Nullable;\n\nimport java.lang.reflect.Field;\nimport java.lang.reflect.InvocationTargetException;\nimport java.lang.reflect.Method;\nimport java.util.Collection;\nimport java.util.EnumSet;\nimport java.util.HashSet;\nimport java.util.LinkedHashSet;\nimport java.util.LinkedHashMap;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Set;\n\nimport static org.bbottema.javareflection.LookupCaches.CLASS_CACHE;\nimport static org.bbottema.javareflection.util.MiscUtil.trustedNullableCast;\n\n/**\n * Utility with convenience methods that operate on the class level.\n *
      \n *
    • With this helper class you can locate and/or load classes. An advanced Class lookup ({@link #locateClass(String, boolean,\n * ClassLoader)}), that allows a full scan (to try all\n * packages known) and an optional {@link ExternalClassLoader} instance that is able to actually compile a .java file on the fly and load its compile\n * .class file
    • \n *
    • create a new instance while handling all the exceptions
    • \n *
    • find fields or assign values to fields, using casting, autoboxing or type conversions
    • \n *
    • simply give back a list of field / method names
    • \n *
    \n */\n@UtilityClass\n@SuppressWarnings(\"WeakerAccess\")\npublic final class ClassUtils {\n\t\n\t/**\n\t * Searches the JVM and optionally all of its packages\n\t *\n\t * @param className The name of the class to locate.\n\t * @param fullscan Whether a full scan through all available java packages is required.\n\t * @param classLoader Optional user-provided classloader.\n\t * @return The Class reference if found or null otherwise.\n\t */\n\t@Nullable\n\t@SuppressWarnings({\"WeakerAccess\", \"unchecked\"})\n\tpublic static Class locateClass(final String className, final boolean fullscan, @Nullable final ClassLoader classLoader) {\n\t\tfinal String cacheKey = className + fullscan;\n\t\tif (CLASS_CACHE.containsKey(cacheKey)) {\n\t\t\treturn (Class) CLASS_CACHE.get(cacheKey);\n\t\t}\n\t\tClass _class;\n\t\tif (fullscan) {\n\t\t\t_class = locateClass(className, null, classLoader);\n\t\t} else {\n\t\t\t// try standard package used for most common classes\n\t\t\t_class = locateClass(className, \"java.lang\", classLoader);\n\t\t\tif (_class == null) {\n\t\t\t\t_class = locateClass(className, \"java.util\", classLoader);\n\t\t\t}\n\t\t\tif (_class == null) {\n\t\t\t\t_class = locateClass(className, \"java.math\", classLoader);\n\t\t\t}\n\t\t}\n\t\tCLASS_CACHE.put(cacheKey, _class);\n\t\treturn (Class) _class;\n\t}\n\t\n\t@Nullable\n\t@SuppressWarnings({\"WeakerAccess\", \"unchecked\"})\n\tpublic static Class locateClass(final String className, @Nullable final String inPackage, @Nullable final ClassLoader classLoader) {\n\t\tfinal String cacheKey = className + inPackage;\n\t\tif (CLASS_CACHE.containsKey(cacheKey)) {\n\t\t\treturn (Class) CLASS_CACHE.get(cacheKey);\n\t\t}\n\t\t\n\t\tClass _class = locateClass(className, classLoader);\n\t\t\n\t\tif (_class == null) {\n\t\t\t_class = PackageUtils.scanPackagesForClass(className, inPackage, classLoader);\n\t\t}\n\t\t\n\t\tCLASS_CACHE.put(cacheKey, _class);\n\t\treturn (Class) _class;\n\t}\n\t\n\t/**\n\t * This function dynamically tries to locate a class. First it searches the class-cache list, then it tries to get it from the Virtual Machine\n\t * using {@code Class.forName(String)}.\n\t *\n\t * @param fullClassName The Class that needs to be found.\n\t * @param classLoader Optional user-provided classloader.\n\t * @return The {@code Class} object found from cache or VM.\n\t */\n\t@SuppressWarnings({\"WeakerAccess\", \"unchecked\"})\n\t@Nullable\n\tpublic static Class locateClass(final String fullClassName, @Nullable final ClassLoader classLoader) {\n\t\ttry {\n\t\t\tClass _class = null;\n\t\t\tif (classLoader != null) {\n\t\t\t\t_class = classLoader.loadClass(fullClassName);\n\t\t\t}\n\t\t\tif (_class == null) {\n\t\t\t\t_class = Class.forName(fullClassName);\n\t\t\t}\n\t\t\treturn (Class) _class;\n\t\t} catch (final ClassNotFoundException e) {\n\t\t\treturn null;\n\t\t}\n\t}\n\t\n\t/**\n\t * Simply calls {@link Class#newInstance()} and hides the exception handling boilerplate code.\n\t *\n\t * @param _class The datatype for which we need to create a new instance of.\n\t * @param Type used to parameterize the return instance.\n\t * @return A new parameterized instance of the given type.\n\t */\n\t@NotNull\n\t@SuppressWarnings(\"WeakerAccess\")", "answers": ["\tpublic static T newInstanceSimple(final Class _class) {"], "length": 523, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "2c817b30-019a-4dd2-acd8-72408b0fa2c0", "reasoning": "The code is defining a utility method that creates a new instance of a class, with @NotNull and @SuppressWarnings annotations already placed. The next line should be the method signature that follows these annotations, matching the style of earlier methods (using generics, final parameters, and static). Therefore the appropriate next line is the declaration of the newInstance method.", "reasoning_model_answer": "public static T newInstance(final Class _class) {", "assistant_with_reasoning": "\nThe code is defining a utility method that creates a new instance of a class, with @NotNull and @SuppressWarnings annotations already placed. The next line should be the method signature that follows these annotations, matching the style of earlier methods (using generics, final parameters, and static). Therefore the appropriate next line is the declaration of the newInstance method.\n\npublic static T newInstance(final Class _class) {", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.99, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 4753, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "public static T newInstance(final Class _class) {", "score": 0.94, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "namespace SmartOCR\n{\n partial class FindReplaceDialog\n {\n /// \n /// Required designer variable.\n /// \n private System.ComponentModel.IContainer components = null;\n\n /// \n /// Clean up any resources being used.\n /// \n /// true if managed resources should be disposed; otherwise, false.\n protected override void Dispose(bool disposing)\n {\n if (disposing && (components != null))\n {\n components.Dispose();\n }\n base.Dispose(disposing);\n }\n\n #region Windows Form Designer generated code\n\n /// \n /// Required method for Designer support - do not modify\n /// the contents of this method with the code editor.\n /// \n private void InitializeComponent()\n {\n this.tabAll = new System.Windows.Forms.TabControl();\n this.tpgFind = new System.Windows.Forms.TabPage();\n this.grpFindAll = new System.Windows.Forms.GroupBox();\n this.btnClear = new System.Windows.Forms.Button();\n this.btnFindAll = new System.Windows.Forms.Button();\n this.chkHighlightMatches = new System.Windows.Forms.CheckBox();\n this.chkMarkLine = new System.Windows.Forms.CheckBox();\n this.chkSearchSelectionF = new System.Windows.Forms.CheckBox();\n this.chkWrapF = new System.Windows.Forms.CheckBox();\n this.btnFindPrevious = new System.Windows.Forms.Button();\n this.btnFindNext = new System.Windows.Forms.Button();\n this.cboFindF = new System.Windows.Forms.ComboBox();\n this.grpOptionsF = new System.Windows.Forms.GroupBox();\n this.pnlStandardOptionsF = new System.Windows.Forms.Panel();\n this.chkWordStartF = new System.Windows.Forms.CheckBox();\n this.chkWholeWordF = new System.Windows.Forms.CheckBox();\n this.chkMatchCaseF = new System.Windows.Forms.CheckBox();\n this.pnlRegexpOptionsF = new System.Windows.Forms.Panel();\n this.chkSinglelineF = new System.Windows.Forms.CheckBox();\n this.chkRightToLeftF = new System.Windows.Forms.CheckBox();\n this.chkMultilineF = new System.Windows.Forms.CheckBox();\n this.chkIgnorePatternWhitespaceF = new System.Windows.Forms.CheckBox();\n this.chkIgnoreCaseF = new System.Windows.Forms.CheckBox();\n this.chkExplicitCaptureF = new System.Windows.Forms.CheckBox();\n this.chkEcmaScriptF = new System.Windows.Forms.CheckBox();\n this.chkCultureInvariantF = new System.Windows.Forms.CheckBox();\n this.chkCompiledF = new System.Windows.Forms.CheckBox();\n this.lblSearchTypeF = new System.Windows.Forms.Label();\n this.rdoRegexF = new System.Windows.Forms.RadioButton();\n this.rdoStandardF = new System.Windows.Forms.RadioButton();\n this.lblFindF = new System.Windows.Forms.Label();\n this.tpgReplace = new System.Windows.Forms.TabPage();\n this.btnReplaceAll = new System.Windows.Forms.Button();\n this.cboReplace = new System.Windows.Forms.ComboBox();\n this.lblReplace = new System.Windows.Forms.Label();\n this.chkSearchSelectionR = new System.Windows.Forms.CheckBox();\n this.chkWrapR = new System.Windows.Forms.CheckBox();\n this.btnReplacePrevious = new System.Windows.Forms.Button();\n this.btnReplaceNext = new System.Windows.Forms.Button();\n this.cboFindR = new System.Windows.Forms.ComboBox();\n this.grdOptionsR = new System.Windows.Forms.GroupBox();\n this.pnlStandardOptionsR = new System.Windows.Forms.Panel();\n this.chkWordStartR = new System.Windows.Forms.CheckBox();\n this.chkWholeWordR = new System.Windows.Forms.CheckBox();\n this.chkMatchCaseR = new System.Windows.Forms.CheckBox();\n this.pnlRegexpOptionsR = new System.Windows.Forms.Panel();\n this.chkSinglelineR = new System.Windows.Forms.CheckBox();\n this.chkRightToLeftR = new System.Windows.Forms.CheckBox();\n this.chkMultilineR = new System.Windows.Forms.CheckBox();\n this.chkIgnorePatternWhitespaceR = new System.Windows.Forms.CheckBox();\n this.chkIgnoreCaseR = new System.Windows.Forms.CheckBox();\n this.chkExplicitCaptureR = new System.Windows.Forms.CheckBox();\n this.chkEcmaScriptR = new System.Windows.Forms.CheckBox();\n this.chkCultureInvariantR = new System.Windows.Forms.CheckBox();\n this.chkCompiledR = new System.Windows.Forms.CheckBox();\n this.lblSearchTypeR = new System.Windows.Forms.Label();\n this.rdoRegexR = new System.Windows.Forms.RadioButton();\n this.rdoStandardR = new System.Windows.Forms.RadioButton();\n this.lblFindR = new System.Windows.Forms.Label();\n this.statusStrip = new System.Windows.Forms.StatusStrip();\n this.lblStatus = new System.Windows.Forms.ToolStripStatusLabel();\n this.tabAll.SuspendLayout();\n this.tpgFind.SuspendLayout();\n this.grpFindAll.SuspendLayout();\n this.grpOptionsF.SuspendLayout();\n this.pnlStandardOptionsF.SuspendLayout();\n this.pnlRegexpOptionsF.SuspendLayout();\n this.tpgReplace.SuspendLayout();\n this.grdOptionsR.SuspendLayout();\n this.pnlStandardOptionsR.SuspendLayout();\n this.pnlRegexpOptionsR.SuspendLayout();\n this.statusStrip.SuspendLayout();\n this.SuspendLayout();\n // \n // tabAll\n // \n this.tabAll.Controls.Add(this.tpgFind);\n this.tabAll.Controls.Add(this.tpgReplace);\n this.tabAll.Dock = System.Windows.Forms.DockStyle.Fill;\n this.tabAll.Location = new System.Drawing.Point(0, 0);\n this.tabAll.Name = \"tabAll\";\n this.tabAll.SelectedIndex = 0;\n this.tabAll.Size = new System.Drawing.Size(499, 291);\n this.tabAll.TabIndex = 0;\n \n // \n // tpgFind\n // \n this.tpgFind.Controls.Add(this.grpFindAll);\n this.tpgFind.Controls.Add(this.chkSearchSelectionF);\n this.tpgFind.Controls.Add(this.chkWrapF);\n this.tpgFind.Controls.Add(this.btnFindPrevious);\n this.tpgFind.Controls.Add(this.btnFindNext);\n this.tpgFind.Controls.Add(this.cboFindF);\n this.tpgFind.Controls.Add(this.grpOptionsF);\n this.tpgFind.Controls.Add(this.lblSearchTypeF);\n this.tpgFind.Controls.Add(this.rdoRegexF);\n this.tpgFind.Controls.Add(this.rdoStandardF);\n this.tpgFind.Controls.Add(this.lblFindF);\n this.tpgFind.Location = new System.Drawing.Point(4, 22);\n this.tpgFind.Name = \"tpgFind\";\n this.tpgFind.Padding = new System.Windows.Forms.Padding(3);\n this.tpgFind.Size = new System.Drawing.Size(491, 265);\n this.tpgFind.TabIndex = 0;\n this.tpgFind.Text = \"Find\";\n this.tpgFind.UseVisualStyleBackColor = true;\n // \n // grpFindAll\n // \n this.grpFindAll.Controls.Add(this.btnClear);\n this.grpFindAll.Controls.Add(this.btnFindAll);\n this.grpFindAll.Controls.Add(this.chkHighlightMatches);\n this.grpFindAll.Controls.Add(this.chkMarkLine);\n this.grpFindAll.Location = new System.Drawing.Point(5, 176);\n this.grpFindAll.Name = \"grpFindAll\";\n this.grpFindAll.Size = new System.Drawing.Size(209, 65);", "answers": [" this.grpFindAll.TabIndex = 8;"], "length": 444, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "0df9cbc4-4ae1-4f6e-a2ea-7bba0c52274b", "reasoning": "In Windows Forms designer code, after setting a control's Size property the next typical property is TabIndex. The grpFindAll GroupBox has just had its Size assigned, so the following line will set its TabIndex.", "reasoning_model_answer": "this.grpFindAll.TabIndex = 0;", "assistant_with_reasoning": "\nIn Windows Forms designer code, after setting a control's Size property the next typical property is TabIndex. The grpFindAll GroupBox has just had its Size assigned, so the following line will set its TabIndex.\n\nthis.grpFindAll.TabIndex = 0;", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 5.159, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 7919, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "this.grpFindAll.TabIndex = 0;", "score": 0.8, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "# (c) Copyright 2013 Hewlett-Packard Development Company, L.P.\n# All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n#\n# @author: Swaminathan Vasudevan, Hewlett-Packard.\n\nimport netaddr\nimport sqlalchemy as sa\nfrom sqlalchemy import orm\nfrom sqlalchemy.orm import exc\n\nfrom neutron.common import constants as n_constants\nfrom neutron.db import api as qdbapi\nfrom neutron.db import db_base_plugin_v2 as base_db\nfrom neutron.db import l3_agentschedulers_db as l3_agent_db\nfrom neutron.db import l3_db\nfrom neutron.db import model_base\nfrom neutron.db import models_v2\nfrom neutron.extensions import vpnaas\nfrom neutron import manager\nfrom neutron.openstack.common import excutils\nfrom neutron.openstack.common import log as logging\nfrom neutron.openstack.common import uuidutils\nfrom neutron.plugins.common import constants\nfrom neutron.plugins.common import utils\n\nLOG = logging.getLogger(__name__)\n\nIP_MIN_MTU = {4: 68, 6: 1280}\n\n\nclass IPsecPeerCidr(model_base.BASEV2):\n \"\"\"Internal representation of a IPsec Peer Cidrs.\"\"\"\n\n cidr = sa.Column(sa.String(32), nullable=False, primary_key=True)\n ipsec_site_connection_id = sa.Column(\n sa.String(36),\n sa.ForeignKey('ipsec_site_connections.id',\n ondelete=\"CASCADE\"),\n primary_key=True)\n\n\nclass IPsecPolicy(model_base.BASEV2, models_v2.HasId, models_v2.HasTenant):\n \"\"\"Represents a v2 IPsecPolicy Object.\"\"\"\n __tablename__ = 'ipsecpolicies'\n name = sa.Column(sa.String(255))\n description = sa.Column(sa.String(255))\n transform_protocol = sa.Column(sa.Enum(\"esp\", \"ah\", \"ah-esp\",\n name=\"ipsec_transform_protocols\"),\n nullable=False)\n auth_algorithm = sa.Column(sa.Enum(\"sha1\",\n name=\"vpn_auth_algorithms\"),\n nullable=False)\n encryption_algorithm = sa.Column(sa.Enum(\"3des\", \"aes-128\",\n \"aes-256\", \"aes-192\",\n name=\"vpn_encrypt_algorithms\"),\n nullable=False)\n encapsulation_mode = sa.Column(sa.Enum(\"tunnel\", \"transport\",\n name=\"ipsec_encapsulations\"),\n nullable=False)\n lifetime_units = sa.Column(sa.Enum(\"seconds\", \"kilobytes\",\n name=\"vpn_lifetime_units\"),\n nullable=False)\n lifetime_value = sa.Column(sa.Integer, nullable=False)\n pfs = sa.Column(sa.Enum(\"group2\", \"group5\", \"group14\",\n name=\"vpn_pfs\"), nullable=False)\n\n\nclass IKEPolicy(model_base.BASEV2, models_v2.HasId, models_v2.HasTenant):\n \"\"\"Represents a v2 IKEPolicy Object.\"\"\"\n __tablename__ = 'ikepolicies'\n name = sa.Column(sa.String(255))\n description = sa.Column(sa.String(255))\n auth_algorithm = sa.Column(sa.Enum(\"sha1\",\n name=\"vpn_auth_algorithms\"),\n nullable=False)\n encryption_algorithm = sa.Column(sa.Enum(\"3des\", \"aes-128\",\n \"aes-256\", \"aes-192\",\n name=\"vpn_encrypt_algorithms\"),\n nullable=False)\n phase1_negotiation_mode = sa.Column(sa.Enum(\"main\",\n name=\"ike_phase1_mode\"),\n nullable=False)\n lifetime_units = sa.Column(sa.Enum(\"seconds\", \"kilobytes\",\n name=\"vpn_lifetime_units\"),\n nullable=False)\n lifetime_value = sa.Column(sa.Integer, nullable=False)\n ike_version = sa.Column(sa.Enum(\"v1\", \"v2\", name=\"ike_versions\"),\n nullable=False)\n pfs = sa.Column(sa.Enum(\"group2\", \"group5\", \"group14\",\n name=\"vpn_pfs\"), nullable=False)\n\n\nclass IPsecSiteConnection(model_base.BASEV2,\n models_v2.HasId, models_v2.HasTenant):\n \"\"\"Represents a IPsecSiteConnection Object.\"\"\"\n __tablename__ = 'ipsec_site_connections'\n name = sa.Column(sa.String(255))\n description = sa.Column(sa.String(255))\n peer_address = sa.Column(sa.String(255), nullable=False)\n peer_id = sa.Column(sa.String(255), nullable=False)\n route_mode = sa.Column(sa.String(8), nullable=False)\n mtu = sa.Column(sa.Integer, nullable=False)\n initiator = sa.Column(sa.Enum(\"bi-directional\", \"response-only\",\n name=\"vpn_initiators\"), nullable=False)\n auth_mode = sa.Column(sa.String(16), nullable=False)\n psk = sa.Column(sa.String(255), nullable=False)\n dpd_action = sa.Column(sa.Enum(\"hold\", \"clear\",\n \"restart\", \"disabled\",\n \"restart-by-peer\", name=\"vpn_dpd_actions\"),\n nullable=False)\n dpd_interval = sa.Column(sa.Integer, nullable=False)\n dpd_timeout = sa.Column(sa.Integer, nullable=False)\n status = sa.Column(sa.String(16), nullable=False)\n admin_state_up = sa.Column(sa.Boolean(), nullable=False)\n vpnservice_id = sa.Column(sa.String(36),\n sa.ForeignKey('vpnservices.id'),\n nullable=False)\n ipsecpolicy_id = sa.Column(sa.String(36),\n sa.ForeignKey('ipsecpolicies.id'),\n nullable=False)\n ikepolicy_id = sa.Column(sa.String(36),\n sa.ForeignKey('ikepolicies.id'),\n nullable=False)\n ipsecpolicy = orm.relationship(\n IPsecPolicy, backref='ipsec_site_connection')\n ikepolicy = orm.relationship(IKEPolicy, backref='ipsec_site_connection')\n peer_cidrs = orm.relationship(IPsecPeerCidr,\n backref='ipsec_site_connection',\n lazy='joined',\n cascade='all, delete, delete-orphan')\n", "answers": ["class VPNService(model_base.BASEV2, models_v2.HasId, models_v2.HasTenant):"], "length": 447, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "8e7e3b7b-96ef-48c0-a7d2-ecc901159a2f", "reasoning": "The snippet ends the definition of the IPsecSiteConnection model. In the Neutron VPNaaS database models file, the next class defined after IPsecSiteConnection is the VPNService model, which starts with its class declaration. Therefore the next line of code is the class header for VPNService.", "reasoning_model_answer": "class VPNService(model_base.BASEV2, models_v2.HasId, models_v2.HasTenant):", "assistant_with_reasoning": "\nThe snippet ends the definition of the IPsecSiteConnection model. In the Neutron VPNaaS database models file, the next class defined after IPsecSiteConnection is the VPNService model, which starts with its class declaration. Therefore the next line of code is the class header for VPNService.\n\nclass VPNService(model_base.BASEV2, models_v2.HasId, models_v2.HasTenant):", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 6.758, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 6735, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "class VPNService(model_base.BASEV2, models_v2.HasId, models_v2.HasTenant):", "score": 1.0, "is_full_score": true, "is_nonzero_score": true}} {"input": "", "context": "// PART OF THE MACHINE SIMULATION. DO NOT CHANGE.\n\npackage nachos.machine;\n\nimport nachos.security.*;\nimport nachos.ag.*;\n\nimport java.io.File;\n\n/**\n * The master class of the simulated machine. Processes command line arguments,\n * constructs all simulated hardware devices, and starts the grader.\n */\npublic final class Machine {\n\t/**\n\t * Nachos main entry point.\n\t * \n\t * @param args the command line arguments.\n\t */\n\tpublic static void main(final String[] args) {\n\t\tSystem.out.print(\"nachos 5.0j initializing...\");\n\n\t\tLib.assertTrue(Machine.args == null);\n\t\tMachine.args = args;\n\n\t\tprocessArgs();\n\n\t\tConfig.load(configFileName);\n\n\t\t// get the current directory (.)\n\t\tbaseDirectory = new File(new File(\"\").getAbsolutePath());\n\t\t// get the nachos directory (./nachos)\n\t\tnachosDirectory = new File(baseDirectory, \"nachos\");\n\n\t\tString testDirectoryName = Config.getString(\"FileSystem.testDirectory\");\n\n\t\t// get the test directory\n\t\tif (testDirectoryName != null) {\n\t\t\ttestDirectory = new File(testDirectoryName);\n\t\t}\n\t\telse {\n\t\t\t// use ../test\n\t\t\ttestDirectory = new File(baseDirectory.getParentFile(), \"test\");\n\t\t}\n\n\t\tsecurityManager = new NachosSecurityManager(testDirectory);\n\t\tprivilege = securityManager.getPrivilege();\n\n\t\tprivilege.machine = new MachinePrivilege();\n\n\t\tTCB.givePrivilege(privilege);\n\t\tprivilege.stats = stats;\n\n\t\tsecurityManager.enable();\n\t\tcreateDevices();\n\t\tcheckUserClasses();\n\n\t\tautoGrader = (AutoGrader) Lib.constructObject(autoGraderClassName);\n\n\t\tnew TCB().start(new Runnable() {\n\t\t\tpublic void run() {\n\t\t\t\tautoGrader.start(privilege);\n\t\t\t}\n\t\t});\n\t}\n\n\t/**\n\t * Yield to non-Nachos threads. Use in non-preemptive JVM's to give\n\t * non-Nachos threads a chance to run.\n\t */\n\tpublic static void yield() {\n\t\tThread.yield();\n\t}\n\n\t/**\n\t * Terminate Nachos. Same as TCB.die().\n\t */\n\tpublic static void terminate() {\n\t\tTCB.die();\n\t}\n\n\t/**\n\t * Terminate Nachos as the result of an unhandled exception or error.\n\t * \n\t * @param e the exception or error.\n\t */\n\tpublic static void terminate(Throwable e) {\n\t\tif (e instanceof ThreadDeath)\n\t\t\tthrow (ThreadDeath) e;\n\n\t\te.printStackTrace();\n\t\tterminate();\n\t}\n\n\t/**\n\t * Print stats, and terminate Nachos.\n\t */\n\tpublic static void halt() {\n\t\tSystem.out.print(\"Machine halting!\\n\\n\");\n\t\tstats.print();\n\t\tterminate();\n\t}\n\n\t/**\n\t * Return an array containing all command line arguments.\n\t * \n\t * @return the command line arguments passed to Nachos.\n\t */\n\tpublic static String[] getCommandLineArguments() {\n\t\tString[] result = new String[args.length];\n\n\t\tSystem.arraycopy(args, 0, result, 0, args.length);\n\n\t\treturn result;\n\t}\n\n\tprivate static void processArgs() {\n\t\tfor (int i = 0; i < args.length;) {\n\t\t\tString arg = args[i++];\n\t\t\tif (arg.length() > 0 && arg.charAt(0) == '-') {\n\t\t\t\tif (arg.equals(\"-d\")) {\n\t\t\t\t\tLib.assertTrue(i < args.length, \"switch without argument\");\n\t\t\t\t\tLib.enableDebugFlags(args[i++]);\n\t\t\t\t}\n\t\t\t\telse if (arg.equals(\"-h\")) {\n\t\t\t\t\tSystem.out.print(help);\n\t\t\t\t\tSystem.exit(1);\n\t\t\t\t}\n\t\t\t\telse if (arg.equals(\"-m\")) {\n\t\t\t\t\tLib.assertTrue(i < args.length, \"switch without argument\");\n\t\t\t\t\ttry {\n\t\t\t\t\t\tnumPhysPages = Integer.parseInt(args[i++]);\n\t\t\t\t\t}\n\t\t\t\t\tcatch (NumberFormatException e) {\n\t\t\t\t\t\tLib.assertNotReached(\"bad value for -m switch\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if (arg.equals(\"-s\")) {\n\t\t\t\t\tLib.assertTrue(i < args.length, \"switch without argument\");\n\t\t\t\t\ttry {\n\t\t\t\t\t\trandomSeed = Long.parseLong(args[i++]);\n\t\t\t\t\t}\n\t\t\t\t\tcatch (NumberFormatException e) {\n\t\t\t\t\t\tLib.assertNotReached(\"bad value for -s switch\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if (arg.equals(\"-x\")) {\n\t\t\t\t\tLib.assertTrue(i < args.length, \"switch without argument\");\n\t\t\t\t\tshellProgramName = args[i++];\n\t\t\t\t}\n\t\t\t\telse if (arg.equals(\"-z\")) {\n\t\t\t\t\tSystem.out.print(copyright);\n\t\t\t\t\tSystem.exit(1);\n\t\t\t\t}\n\t\t\t\t// these switches are reserved for the autograder\n\t\t\t\telse if (arg.equals(\"-[]\")) {\n\t\t\t\t\tLib.assertTrue(i < args.length, \"switch without argument\");\n\t\t\t\t\tconfigFileName = args[i++];\n\t\t\t\t}\n\t\t\t\telse if (arg.equals(\"--\")) {\n\t\t\t\t\tLib.assertTrue(i < args.length, \"switch without argument\");\n\t\t\t\t\tautoGraderClassName = args[i++];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tLib.seedRandom(randomSeed);\n\t}\n\n\tprivate static void createDevices() {\n\t\tinterrupt = new Interrupt(privilege);\n\t\ttimer = new Timer(privilege);\n\n\t\tif (Config.getBoolean(\"Machine.bank\"))\n\t\t\tbank = new ElevatorBank(privilege);\n\n\t\tif (Config.getBoolean(\"Machine.processor\")) {\n\t\t\tif (numPhysPages == -1)\n\t\t\t\tnumPhysPages = Config.getInteger(\"Processor.numPhysPages\");\n\t\t\tprocessor = new Processor(privilege, numPhysPages);\n\t\t}\n\n\t\tif (Config.getBoolean(\"Machine.console\"))\n\t\t\tconsole = new StandardConsole(privilege);\n\n\t\tif (Config.getBoolean(\"Machine.stubFileSystem\"))\n\t\t\tstubFileSystem = new StubFileSystem(privilege, testDirectory);", "answers": ["\t\tif (Config.getBoolean(\"Machine.networkLink\"))"], "length": 515, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "932479d0-1b0a-49db-bbad-9807f19ce7ca", "reasoning": "The createDevices() method is initializing hardware components based on configuration flags. After setting up the stub file system, the next typical device initialized in Nachos is the synchronized disk, guarded by the 'Machine.synchDisk' flag. Therefore the next line should check that flag and create a SynchDisk instance.", "reasoning_model_answer": "if (Config.getBoolean(\"Machine.synchDisk\"))\n synchDisk = new SynchDisk(privilege);", "assistant_with_reasoning": "\nThe createDevices() method is initializing hardware components based on configuration flags. After setting up the stub file system, the next typical device initialized in Nachos is the synchronized disk, guarded by the 'Machine.synchDisk' flag. Therefore the next line should check that flag and create a SynchDisk instance.\n\nif (Config.getBoolean(\"Machine.synchDisk\"))\n synchDisk = new SynchDisk(privilege);", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 5.174, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 4815, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "if (Config.getBoolean(\"Machine.synchDisk\"))\n synchDisk = new SynchDisk(privilege);", "score": 0.82, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/*\n * Copyright 2012 JBoss Inc\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not\n * use this file except in compliance with the License. You may obtain a copy of\n * the License at\n * \n * http://www.apache.org/licenses/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n * License for the specific language governing permissions and limitations under\n * the License.\n */\npackage org.uberfire.annotations.processors;\n\nimport java.io.FileNotFoundException;\nimport java.util.List;\nimport javax.tools.Diagnostic;\nimport javax.tools.JavaFileObject;\n\nimport org.junit.Test;\n\nimport static org.junit.Assert.*;\n\n/**\n * Tests for Screen related class generation\n */\npublic class WorkbenchScreenProcessorTest extends AbstractProcessorTest {\n\n @Test\n public void testNoWorkbenchScreenAnnotation() throws FileNotFoundException {\n final Result result = new Result();\n final List> diagnostics = compile( new WorkbenchScreenProcessor( new GenerationCompleteCallback() {\n\n @Override\n public void generationComplete( final String code ) {\n result.setActualCode( code );\n }\n } ),\n \"org/uberfire/annotations/processors/WorkbenchScreenTest1\" );\n assertSuccessfulCompilation( diagnostics );\n assertNull( result.getActualCode() );\n }\n\n @Test\n public void testWorkbenchScreenMissingViewAnnotation() {\n final Result result = new Result();\n final List> diagnostics = compile( new WorkbenchScreenProcessor( new GenerationCompleteCallback() {\n\n @Override\n public void generationComplete( final String code ) {\n result.setActualCode( code );\n }\n } ), \"org/uberfire/annotations/processors/WorkbenchScreenTest2\" );\n\n assertFailedCompilation( diagnostics );\n assertCompilationError( diagnostics,\n \"org.uberfire.annotations.processors.WorkbenchScreenTest2Activity: The WorkbenchScreen must either extend IsWidget or provide a @WorkbenchPartView annotated method to return a com.google.gwt.user.client.ui.IsWidget.\" );\n assertNull( result.getActualCode() );\n }\n\n @Test\n public void testWorkbenchScreenHasViewAnnotationMissingTitleAnnotation() {\n final Result result = new Result();\n final List> diagnostics = compile( new WorkbenchScreenProcessor( new GenerationCompleteCallback() {\n\n @Override\n public void generationComplete( final String code ) {\n result.setActualCode( code );\n }\n } ),\n \"org/uberfire/annotations/processors/WorkbenchScreenTest3\" );\n assertFailedCompilation( diagnostics );\n assertCompilationError( diagnostics,\n \"org.uberfire.annotations.processors.WorkbenchScreenTest3Activity: The WorkbenchScreen must provide a @WorkbenchPartTitle annotated method to return a java.lang.String.\" );\n assertNull( result.getActualCode() );\n }\n\n @Test\n public void testWorkbenchScreenMissingViewAnnotationHasTitleAnnotation() {\n final Result result = new Result();\n final List> diagnostics = compile( new WorkbenchScreenProcessor( new GenerationCompleteCallback() {\n\n @Override\n public void generationComplete( final String code ) {\n result.setActualCode( code );\n }\n } ),\n \"org/uberfire/annotations/processors/WorkbenchScreenTest4\" );\n assertFailedCompilation( diagnostics );\n assertCompilationError( diagnostics,\n \"org.uberfire.annotations.processors.WorkbenchScreenTest4Activity: The WorkbenchScreen must either extend IsWidget or provide a @WorkbenchPartView annotated method to return a com.google.gwt.user.client.ui.IsWidget.\" );\n assertNull( result.getActualCode() );\n }\n\n @Test\n public void testWorkbenchScreenHasViewAnnotationAndHasTitleAnnotation() throws FileNotFoundException {\n final String pathCompilationUnit = \"org/uberfire/annotations/processors/WorkbenchScreenTest5\";\n final String pathExpectedResult = \"org/uberfire/annotations/processors/expected/WorkbenchScreenTest5.expected\";\n\n final Result result = new Result();\n result.setExpectedCode( getExpectedSourceCode( pathExpectedResult ) );\n\n final List> diagnostics = compile( new WorkbenchScreenProcessor( new GenerationCompleteCallback() {\n\n @Override\n public void generationComplete( final String code ) {\n result.setActualCode( code );\n }\n } ),\n pathCompilationUnit );\n assertSuccessfulCompilation( diagnostics );\n assertNotNull( result.getActualCode() );\n assertNotNull( result.getExpectedCode() );\n assertEquals( result.getActualCode(),\n result.getExpectedCode() );\n }\n\n @Test\n public void testWorkbenchScreenExtendsIsWidget() throws FileNotFoundException {\n final String pathCompilationUnit = \"org/uberfire/annotations/processors/WorkbenchScreenTest6\";\n final String pathExpectedResult = \"org/uberfire/annotations/processors/expected/WorkbenchScreenTest6.expected\";", "answers": [" final Result result = new Result();"], "length": 466, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "0acb444c-301d-4349-90d3-ae732c032d44", "reasoning": "The method testWorkbenchScreenExtendsIsWidget follows the same pattern as the previous test method. After declaring the two path strings, the next step is to create a Result object to hold expected and actual generated code. Therefore the next line is the declaration and instantiation of Result.", "reasoning_model_answer": "final Result result = new Result();", "assistant_with_reasoning": "\nThe method testWorkbenchScreenExtendsIsWidget follows the same pattern as the previous test method. After declaring the two path strings, the next step is to create a Result object to hold expected and actual generated code. Therefore the next line is the declaration and instantiation of Result.\n\nfinal Result result = new Result();", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.535, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 5977, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "final Result result = new Result();", "score": 0.9, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "package com.Doctor.Thief.utils;\n\nimport java.lang.reflect.Constructor;\nimport java.lang.reflect.Field;\nimport java.lang.reflect.Method;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collection;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Map.Entry;\n\nimport org.bukkit.Bukkit;\nimport org.bukkit.Location;\nimport org.bukkit.entity.Player;\n\nimport com.Doctor.Thief.utils.ReflectionHandler.PackageType;\nimport com.Doctor.Thief.utils.ReflectionHandler.PacketType;\nimport com.Doctor.Thief.utils.ReflectionHandler.SubPackageType;\n\npublic enum ParticleEffect {\n\t/**\n\t * @appearance Huge explosions\n\t * @displayed by TNT and creepers\n\t */\n\tHUGE_EXPLOSION(\"hugeexplosion\"),\n\t/**\n\t * @appearance Smaller explosions\n\t * @displayed by TNT and creepers\n\t */\n\tLARGE_EXPLODE(\"largeexplode\"),\n\t/**\n\t * @appearance Little white sparkling stars\n\t * @displayed by Fireworks\n\t */\n\tFIREWORKS_SPARK(\"fireworksSpark\"),\n\t/**\n\t * @appearance Bubbles\n\t * @displayed in water\n\t */\n\tBUBBLE(\"bubble\"),\n\t/**\n\t * @appearance Unknown\n\t */\n\tSUSPEND(\"suspend\"),\n\t/**\n\t * @appearance Little gray dots\n\t * @displayed in the Void and water\n\t */\n\tDEPTH_SUSPEND(\"depthSuspend\"),\n\t/**\n\t * @appearance Little gray dots\n\t * @displayed by Mycelium\n\t */\n\tTOWN_AURA(\"townaura\"),\n\t/**\n\t * @appearance Light brown crosses\n\t * @displayed by critical hits\n\t */\n\tCRIT(\"crit\"),\n\t/**\n\t * @appearance Cyan stars\n\t * @displayed by hits with an enchanted weapon\n\t */\n\tMAGIC_CRIT(\"magicCrit\"),\n\t/**\n\t * @appearance Little black/gray clouds\n\t * @displayed by torches, primed TNT and end portals\n\t */\n\tSMOKE(\"smoke\"),\n\t/**\n\t * @appearance Colored swirls\n\t * @displayed by potion effects\n\t */\n\tMOB_SPELL(\"mobSpell\"),\n\t/**\n\t * @appearance Transparent colored swirls\n\t * @displayed by beacon effect\n\t */\n\tMOB_SPELL_AMBIENT(\"mobSpellAmbient\"),\n\t/**\n\t * @appearance Colored swirls\n\t * @displayed by splash potions\n\t */\n\tSPELL(\"spell\"),\n\t/**\n\t * @appearance Colored crosses\n\t * @displayed by instant splash potions (instant health/instant damage)\n\t */\n\tINSTANT_SPELL(\"instantSpell\"),\n\t/**\n\t * @appearance Colored crosses\n\t * @displayed by witches\n\t */\n\tWITCH_MAGIC(\"witchMagic\"),\n\t/**\n\t * @appearance Colored notes\n\t * @displayed by note blocks\n\t */\n\tNOTE(\"note\"),\n\t/**\n\t * @appearance Little purple clouds\n\t * @displayed by nether portals, endermen, ender pearls, eyes of ender and\n\t * ender chests\n\t */\n\tPORTAL(\"portal\"),\n\t/**\n\t * @appearance: White letters\n\t * @displayed by enchantment tables that are near bookshelves\n\t */\n\tENCHANTMENT_TABLE(\"enchantmenttable\"),\n\t/**\n\t * @appearance White clouds\n\t */\n\tEXPLODE(\"explode\"),\n\t/**\n\t * @appearance Little flames\n\t * @displayed by torches, furnaces, magma cubes and monster spawners\n\t */\n\tFLAME(\"flame\"),\n\t/**\n\t * @appearance Little orange blobs\n\t * @displayed by lava\n\t */\n\tLAVA(\"lava\"),\n\t/**\n\t * @appearance Gray transparent squares\n\t */\n\tFOOTSTEP(\"footstep\"),\n\t/**\n\t * @appearance Blue drops\n\t * @displayed by water, rain and shaking wolves\n\t */\n\tSPLASH(\"splash\"),\n\t/**\n\t * @appearance Blue droplets\n\t * @displayed on water when fishing\n\t */\n\tWAKE(\"wake\"),\n\t/**\n\t * @appearance Black/Gray clouds\n\t * @displayed by fire, minecarts with furance and blazes\n\t */\n\tLARGE_SMOKE(\"largesmoke\"),\n\t/**\n\t * @appearance Large white clouds\n\t * @displayed on mob death\n\t */\n\tCLOUD(\"cloud\"),\n\t/**\n\t * @appearance Little colored clouds\n\t * @displayed by active redstone wires and redstone torches\n\t */\n\tRED_DUST(\"reddust\"),\n\t/**\n\t * @appearance Little white parts\n\t * @displayed by cracking snowballs and eggs\n\t */\n\tSNOWBALL_POOF(\"snowballpoof\"),\n\t/**\n\t * @appearance Blue drips\n\t * @displayed by blocks below a water source\n\t */\n\tDRIP_WATER(\"dripWater\"),\n\t/**\n\t * @appearance Orange drips\n\t * @displayed by blocks below a lava source\n\t */\n\tDRIP_LAVA(\"dripLava\"),\n\t/**\n\t * @appearance White clouds\n\t */\n\tSNOW_SHOVEL(\"snowshovel\"),\n\t/**\n\t * @appearance Little green parts\n\t * @displayed by slimes\n\t */\n\tSLIME(\"slime\"),\n\t/**\n\t * @appearance Red hearts\n\t * @displayed when breeding\n\t */\n\tHEART(\"heart\"),\n\t/**\n\t * @appearance Dark gray cracked hearts\n\t * @displayed when attacking a villager in a village\n\t */\n\tANGRY_VILLAGER(\"angryVillager\"),\n\t/**\n\t * @appearance Green stars\n\t * @displayed by bone meal and when trading with a villager\n\t */\n\tHAPPY_VILLAGER(\"happyVillager\");\n\n\tprivate static final Map NAME_MAP = new HashMap();\n\tprivate static final double MAX_RANGE = 16;\n\tprivate static Constructor packetPlayOutWorldParticles;\n\tprivate static Method getHandle;\n\tprivate static Field playerConnection;\n\tprivate static Method sendPacket;\n\tprivate final String name;\n\n\tstatic {\n\t\tfor (ParticleEffect p : values())\n\t\t\tNAME_MAP.put(p.name, p);", "answers": ["\t\ttry {"], "length": 560, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "7db48a08-360d-4dd7-818e-0b90777edc86", "reasoning": "The static initializer currently populates the NAME_MAP. The next logical step is to set up the reflection fields declared earlier (packetPlayOutWorldParticles, getHandle, etc.). In typical implementations this is done inside a try‑catch block, so the line immediately after the for‑loop is the opening of that block.", "reasoning_model_answer": "try {", "assistant_with_reasoning": "\nThe static initializer currently populates the NAME_MAP. The next logical step is to set up the reflection fields declared earlier (packetPlayOutWorldParticles, getHandle, etc.). In typical implementations this is done inside a try‑catch block, so the line immediately after the for‑loop is the opening of that block.\n\ntry {", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.131, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 4834, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "try {", "score": 0.83, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "// Copyright 2021 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n// Generated code. DO NOT EDIT!\n\nusing gagvr = Google.Ads.GoogleAds.V8.Resources;\nusing gax = Google.Api.Gax;\nusing gaxgrpc = Google.Api.Gax.Grpc;\nusing gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore;\nusing proto = Google.Protobuf;\nusing grpccore = Grpc.Core;\nusing grpcinter = Grpc.Core.Interceptors;\nusing sys = System;\nusing scg = System.Collections.Generic;\nusing sco = System.Collections.ObjectModel;\nusing st = System.Threading;\nusing stt = System.Threading.Tasks;\n\nnamespace Google.Ads.GoogleAds.V8.Services\n{\n /// Settings for instances.\n public sealed partial class AdGroupCriterionSimulationServiceSettings : gaxgrpc::ServiceSettingsBase\n {\n /// \n /// Get a new instance of the default .\n /// \n /// A new instance of the default .\n public static AdGroupCriterionSimulationServiceSettings GetDefault() =>\n new AdGroupCriterionSimulationServiceSettings();\n\n /// \n /// Constructs a new object with default settings.\n /// \n public AdGroupCriterionSimulationServiceSettings()\n {\n }\n\n private AdGroupCriterionSimulationServiceSettings(AdGroupCriterionSimulationServiceSettings existing) : base(existing)\n {\n gax::GaxPreconditions.CheckNotNull(existing, nameof(existing));\n GetAdGroupCriterionSimulationSettings = existing.GetAdGroupCriterionSimulationSettings;\n OnCopy(existing);\n }\n\n partial void OnCopy(AdGroupCriterionSimulationServiceSettings existing);\n\n /// \n /// for synchronous and asynchronous calls to\n /// AdGroupCriterionSimulationServiceClient.GetAdGroupCriterionSimulation and\n /// AdGroupCriterionSimulationServiceClient.GetAdGroupCriterionSimulationAsync.\n /// \n /// \n /// \n /// Initial retry delay: 5000 milliseconds.\n /// Retry delay multiplier: 1.3\n /// Retry maximum delay: 60000 milliseconds.\n /// Maximum attempts: Unlimited\n /// \n /// \n /// Retriable status codes: ,\n /// .\n /// \n /// \n /// Timeout: 3600 seconds.\n /// \n /// \n public gaxgrpc::CallSettings GetAdGroupCriterionSimulationSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded)));\n\n /// Creates a deep clone of this object, with all the same property values.\n /// A deep clone of this object.\n public AdGroupCriterionSimulationServiceSettings Clone() => new AdGroupCriterionSimulationServiceSettings(this);\n }\n\n /// \n /// Builder class for to provide simple configuration of\n /// credentials, endpoint etc.\n /// \n internal sealed partial class AdGroupCriterionSimulationServiceClientBuilder : gaxgrpc::ClientBuilderBase\n {\n /// The settings to use for RPCs, or null for the default settings.\n public AdGroupCriterionSimulationServiceSettings Settings { get; set; }\n\n /// Creates a new builder with default settings.\n public AdGroupCriterionSimulationServiceClientBuilder()\n {\n UseJwtAccessWithScopes = AdGroupCriterionSimulationServiceClient.UseJwtAccessWithScopes;\n }\n\n partial void InterceptBuild(ref AdGroupCriterionSimulationServiceClient client);\n\n partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task task);\n\n /// Builds the resulting client.\n public override AdGroupCriterionSimulationServiceClient Build()\n {\n AdGroupCriterionSimulationServiceClient client = null;\n InterceptBuild(ref client);\n return client ?? BuildImpl();\n }\n\n /// Builds the resulting client asynchronously.\n public override stt::Task BuildAsync(st::CancellationToken cancellationToken = default)\n {\n stt::Task task = null;\n InterceptBuildAsync(cancellationToken, ref task);\n return task ?? BuildAsyncImpl(cancellationToken);\n }\n\n private AdGroupCriterionSimulationServiceClient BuildImpl()\n {\n Validate();\n grpccore::CallInvoker callInvoker = CreateCallInvoker();\n return AdGroupCriterionSimulationServiceClient.Create(callInvoker, Settings);\n }", "answers": [" private async stt::Task BuildAsyncImpl(st::CancellationToken cancellationToken)"], "length": 489, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "3e6f0f3c-f9c2-4e53-8086-ec995ef144b8", "reasoning": "The code is inside the builder class for the client. After the synchronous BuildImpl method, the generated pattern includes an asynchronous counterpart BuildAsyncImpl that returns a Task of the client. Therefore the next line should be the method signature for this async build method.", "reasoning_model_answer": "private async stt::Task BuildAsyncImpl(st::CancellationToken cancellationToken)", "assistant_with_reasoning": "\nThe code is inside the builder class for the client. After the synchronous BuildImpl method, the generated pattern includes an asynchronous counterpart BuildAsyncImpl that returns a Task of the client. Therefore the next line should be the method signature for this async build method.\n\nprivate async stt::Task BuildAsyncImpl(st::CancellationToken cancellationToken)", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 5.601, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 6528, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "private async stt::Task BuildAsyncImpl(st::CancellationToken cancellationToken)", "score": 0.97, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "# -*- coding: utf-8 -*-\n\"\"\"Utilities for preprocessing sequence data.\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\nimport random\nimport json\nfrom six.moves import range\nimport six\n\n\ndef pad_sequences(sequences, maxlen=None, dtype='int32',\n padding='pre', truncating='pre', value=0.):\n \"\"\"Pads sequences to the same length.\n\n This function transforms a list of\n `num_samples` sequences (lists of integers)\n into a 2D Numpy array of shape `(num_samples, num_timesteps)`.\n `num_timesteps` is either the `maxlen` argument if provided,\n or the length of the longest sequence otherwise.\n\n Sequences that are shorter than `num_timesteps`\n are padded with `value` at the end.\n\n Sequences longer than `num_timesteps` are truncated\n so that they fit the desired length.\n The position where padding or truncation happens is determined by\n the arguments `padding` and `truncating`, respectively.\n\n Pre-padding is the default.\n\n # Arguments\n sequences: List of lists, where each element is a sequence.\n maxlen: Int, maximum length of all sequences.\n dtype: Type of the output sequences.\n To pad sequences with variable length strings, you can use `object`.\n padding: String, 'pre' or 'post':\n pad either before or after each sequence.\n truncating: String, 'pre' or 'post':\n remove values from sequences larger than\n `maxlen`, either at the beginning or at the end of the sequences.\n value: Float or String, padding value.\n\n # Returns\n x: Numpy array with shape `(len(sequences), maxlen)`\n\n # Raises\n ValueError: In case of invalid values for `truncating` or `padding`,\n or in case of invalid shape for a `sequences` entry.\n \"\"\"\n if not hasattr(sequences, '__len__'):\n raise ValueError('`sequences` must be iterable.')\n lengths = []\n for x in sequences:\n if not hasattr(x, '__len__'):\n raise ValueError('`sequences` must be a list of iterables. '\n 'Found non-iterable: ' + str(x))\n lengths.append(len(x))\n\n num_samples = len(sequences)\n if maxlen is None:\n maxlen = np.max(lengths)\n\n # take the sample shape from the first non empty sequence\n # checking for consistency in the main loop below.\n sample_shape = tuple()\n for s in sequences:\n if len(s) > 0:\n sample_shape = np.asarray(s).shape[1:]\n break\n\n is_dtype_str = np.issubdtype(dtype, np.str_) or np.issubdtype(dtype, np.unicode_)\n if isinstance(value, six.string_types) and dtype != object and not is_dtype_str:\n raise ValueError(\"`dtype` {} is not compatible with `value`'s type: {}\\n\"\n \"You should set `dtype=object` for variable length strings.\"\n .format(dtype, type(value)))\n\n x = np.full((num_samples, maxlen) + sample_shape, value, dtype=dtype)\n for idx, s in enumerate(sequences):\n if not len(s):\n continue # empty list/array was found\n if truncating == 'pre':\n trunc = s[-maxlen:]\n elif truncating == 'post':\n trunc = s[:maxlen]\n else:\n raise ValueError('Truncating type \"%s\" '\n 'not understood' % truncating)\n\n # check `trunc` has expected shape\n trunc = np.asarray(trunc, dtype=dtype)", "answers": [" if trunc.shape[1:] != sample_shape:"], "length": 419, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "1b69324a-e972-4883-b684-2e29c4ec339a", "reasoning": "The code is implementing Keras' pad_sequences. After converting the truncated sequence to a NumPy array, the next step is to verify that its shape (excluding the first dimension) matches the expected sample_shape. Therefore the next line checks this condition with an if statement.", "reasoning_model_answer": "if trunc.shape[1:] != sample_shape:", "assistant_with_reasoning": "\nThe code is implementing Keras' pad_sequences. After converting the truncated sequence to a NumPy array, the next step is to verify that its shape (excluding the first dimension) matches the expected sample_shape. Therefore the next line checks this condition with an if statement.\n\nif trunc.shape[1:] != sample_shape:", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.469, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 3601, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "if trunc.shape[1:] != sample_shape:", "score": 0.9, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "\n/*\n * Author Luke Campbell \n * com.asascience.netcdf4.NcException\n */\nnamespace ASA.NetCDF4.exceptions {\n public class NcException : System.Exception{\n public NcException() : base() {\n }\n public NcException(string message) : base(message) {\n }\n public NcException(string message, System.Exception inner) : base(message, inner) { \n }\n protected NcException(System.Runtime.Serialization.SerializationInfo info,System.Runtime.Serialization.StreamingContext context) {\n }\n }\n public class NcBadId : NcException {\n public NcBadId() : base() {\n }\n public NcBadId(string message) : base(message) {\n }\n public NcBadId(string message, System.Exception inner) : base(message, inner) { \n }\n protected NcBadId(System.Runtime.Serialization.SerializationInfo info,System.Runtime.Serialization.StreamingContext context) {\n }\n }\n public class NcNFile : NcException {\n public NcNFile() : base() {\n }\n public NcNFile(string message) : base(message) {\n }\n public NcNFile(string message, System.Exception inner) : base(message, inner) { \n }\n protected NcNFile(System.Runtime.Serialization.SerializationInfo info,System.Runtime.Serialization.StreamingContext context) {\n }\n }\n public class NcExist : NcException {\n public NcExist() : base() {\n }\n public NcExist(string message) : base(message) {\n }\n public NcExist(string message, System.Exception inner) : base(message, inner) { \n }\n protected NcExist(System.Runtime.Serialization.SerializationInfo info,System.Runtime.Serialization.StreamingContext context) {\n }\n }\n public class NcInvalidArg : NcException {\n public NcInvalidArg() : base() {\n }\n public NcInvalidArg(string message) : base(message) {\n }\n public NcInvalidArg(string message, System.Exception inner) : base(message, inner) { \n }\n protected NcInvalidArg(System.Runtime.Serialization.SerializationInfo info,System.Runtime.Serialization.StreamingContext context) {\n }\n }\n public class NcInvalidWrite : NcException {\n public NcInvalidWrite() : base() {\n }\n public NcInvalidWrite(string message) : base(message) {\n }\n public NcInvalidWrite(string message, System.Exception inner) : base(message, inner) { \n }\n protected NcInvalidWrite(System.Runtime.Serialization.SerializationInfo info,System.Runtime.Serialization.StreamingContext context) {\n }\n }\n public class NcNotInDefineMode : NcException {\n public NcNotInDefineMode() : base() {\n }\n public NcNotInDefineMode(string message) : base(message) {\n }\n public NcNotInDefineMode(string message, System.Exception inner) : base(message, inner) { \n }\n protected NcNotInDefineMode(System.Runtime.Serialization.SerializationInfo info,System.Runtime.Serialization.StreamingContext context) {\n }\n }\n public class NcInDefineMode : NcException {\n public NcInDefineMode() : base() {\n }\n public NcInDefineMode(string message) : base(message) {\n }\n public NcInDefineMode(string message, System.Exception inner) : base(message, inner) { \n }\n protected NcInDefineMode(System.Runtime.Serialization.SerializationInfo info,System.Runtime.Serialization.StreamingContext context) {\n }\n }\n public class NcInvalidCoords : NcException {\n public NcInvalidCoords() : base() {\n }\n public NcInvalidCoords(string message) : base(message) {\n }\n public NcInvalidCoords(string message, System.Exception inner) : base(message, inner) { \n }\n protected NcInvalidCoords(System.Runtime.Serialization.SerializationInfo info,System.Runtime.Serialization.StreamingContext context) {\n }\n }\n public class NcMaxDims : NcException {\n public NcMaxDims() : base() {\n }\n public NcMaxDims(string message) : base(message) {\n }\n public NcMaxDims(string message, System.Exception inner) : base(message, inner) { \n }\n protected NcMaxDims(System.Runtime.Serialization.SerializationInfo info,System.Runtime.Serialization.StreamingContext context) {\n }\n }\n public class NcNameInUse : NcException {\n public NcNameInUse() : base() {\n }\n public NcNameInUse(string message) : base(message) {\n }\n public NcNameInUse(string message, System.Exception inner) : base(message, inner) { \n }\n protected NcNameInUse(System.Runtime.Serialization.SerializationInfo info,System.Runtime.Serialization.StreamingContext context) {\n }\n }\n public class NcNotAtt : NcException {\n public NcNotAtt() : base() {\n }\n public NcNotAtt(string message) : base(message) {\n }\n public NcNotAtt(string message, System.Exception inner) : base(message, inner) { \n }\n protected NcNotAtt(System.Runtime.Serialization.SerializationInfo info,System.Runtime.Serialization.StreamingContext context) {\n }\n }\n public class NcMaxAtts : NcException {\n public NcMaxAtts() : base() {\n }\n public NcMaxAtts(string message) : base(message) {\n }\n public NcMaxAtts(string message, System.Exception inner) : base(message, inner) { \n }\n protected NcMaxAtts(System.Runtime.Serialization.SerializationInfo info,System.Runtime.Serialization.StreamingContext context) {\n }\n }\n public class NcBadType : NcException {\n public NcBadType() : base() {\n }\n public NcBadType(string message) : base(message) {\n }", "answers": [" public NcBadType(string message, System.Exception inner) : base(message, inner) { "], "length": 503, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "e1581205-d4ca-4268-823e-ef167bdae65a", "reasoning": "The code defines a series of custom exception classes, each following the same pattern: a default constructor, a constructor taking a message string, a constructor taking a message and inner exception, and a protected serialization constructor. The snippet ends inside the NcBadType class after the second constructor (string message). Following the established pattern, the next line should be the third constructor that accepts a message and an inner exception.", "reasoning_model_answer": "public NcBadType(string message, System.Exception inner) : base(message, inner) {", "assistant_with_reasoning": "\nThe code defines a series of custom exception classes, each following the same pattern: a default constructor, a constructor taking a message string, a constructor taking a message and inner exception, and a protected serialization constructor. The snippet ends inside the NcBadType class after the second constructor (string message). Following the established pattern, the next line should be the third constructor that accepts a message and an inner exception.\n\npublic NcBadType(string message, System.Exception inner) : base(message, inner) {", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.969, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 5890, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "public NcBadType(string message, System.Exception inner) : base(message, inner) {", "score": 0.95, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/*\n * Copyright (C) 2012 FoxLabs\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.foxlabs.validation.constraint;\n\nimport java.lang.reflect.Array;\n\nimport java.util.Collection;\nimport java.util.Map;\n\nimport org.foxlabs.validation.ValidationContext;\n\nimport org.foxlabs.common.Checks;\n\n/**\n * This class provides base implementation of the CheckConstraint\n * that checks whether the size of a value is within allowed minimum and\n * maximum bounds.\n *\n * @author Fox Mulder\n * @param The type of value to be validated\n */\npublic abstract class SizeConstraint extends CheckConstraint {\n\n /**\n * Allowed minimum size.\n */\n private final int minSize;\n\n /**\n * Allowed maximum size.\n */\n private final int maxSize;\n\n /**\n * Constructs a new SizeConstraint with the specified minimum\n * and maximum sizes.\n *\n * @param minSize Minimum allowed size.\n * @param maxSize Maximum allowed size.\n * @throws IllegalArgumentException if the specified minimum or maximum size\n * is negative.\n */\n protected SizeConstraint(int minSize, int maxSize) {\n Checks.checkThat(minSize, minSize >= 0, \"minSize\");\n Checks.checkThat(maxSize, maxSize >= 0, \"maxSize\");\n\n if (minSize < maxSize) {\n this.minSize = minSize;\n this.maxSize = maxSize;\n } else {\n this.minSize = maxSize;\n this.maxSize = minSize;\n }\n }\n\n /**\n * Returns allowed minimum size.\n *\n * @return Allowed minimum size.\n */\n public final int getMinSize() {\n return minSize;\n }\n\n /**\n * Returns allowed maximum size.\n *\n * @return Allowed maximum size.\n */\n public final int getMaxSize() {\n return maxSize;\n }\n\n /**\n * Returns localized error message template.\n *\n * @param context Validation context.\n * @return Localized error message template.\n */\n @Override\n public String getMessageTemplate(ValidationContext context) {\n return context.resolveMessage(SizeConstraint.class.getName() +\n (minSize > 0 ? maxSize == Integer.MAX_VALUE ? \".min\" : \"\" : maxSize < Integer.MAX_VALUE ? \".max\" : \"\"));\n }\n\n /**\n * Appends minSize and maxSize arguments that\n * contain minimum and maximum allowed size respectively.\n *\n * @param context Validation context.\n * @param arguments Arguments to be substituted into the error message\n * template.\n * @return true.\n */\n @Override\n public boolean appendMessageArguments(ValidationContext context, Map arguments) {\n super.appendMessageArguments(context, arguments);", "answers": [" arguments.put(\"minSize\", minSize);"], "length": 404, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "db1aee16-bbdd-4a99-98fe-d3254e767e8e", "reasoning": "The method appendMessageArguments should add the minSize and maxSize values to the arguments map before returning true. After calling super.appendMessageArguments, the next logical statement is to put the minSize value into the map with key \"minSize\".", "reasoning_model_answer": "arguments.put(\"minSize\", minSize);", "assistant_with_reasoning": "\nThe method appendMessageArguments should add the minSize and maxSize values to the arguments map before returning true. After calling super.appendMessageArguments, the next logical statement is to put the minSize value into the map with key \"minSize\".\n\narguments.put(\"minSize\", minSize);", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 2.947, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 3374, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "arguments.put(\"minSize\", minSize);", "score": 0.89, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "# Copyright 2015 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Tests for tensorflow.ops.clip_ops.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\n\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import errors\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import clip_ops\nfrom tensorflow.python.ops import gradient_checker\nfrom tensorflow.python.ops import gradients_impl\nfrom tensorflow.python.platform import test\n\n\nclass ClipTest(test.TestCase):\n\n def DISABLED_testClipByValueGradient(self):\n inputs = constant_op.constant([1.0, 2.0, 3.0, 4.0], dtype=dtypes.float32)\n outputs_1 = clip_ops.clip_by_value(inputs, 0.5, 3.5)\n min_val = constant_op.constant([0.5, 0.5, 0.5, 0.5], dtype=dtypes.float32)\n max_val = constant_op.constant([3.5, 3.5, 3.5, 3.5], dtype=dtypes.float32)\n outputs_2 = clip_ops.clip_by_value(inputs, min_val, max_val)\n with self.cached_session():\n error_1 = gradient_checker.compute_gradient_error(inputs, [4], outputs_1,\n [4])\n self.assertLess(error_1, 1e-4)\n\n error_2 = gradient_checker.compute_gradient_error(inputs, [4], outputs_2,\n [4])\n self.assertLess(error_2, 1e-4)\n\n # ClipByValue test\n def testClipByValue(self):\n with self.session(use_gpu=True):\n x = constant_op.constant([-5.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[2, 3])\n np_ans = [[-4.4, 2.0, 3.0], [4.0, 4.4, 4.4]]\n clip_value = 4.4\n ans = clip_ops.clip_by_value(x, -clip_value, clip_value)\n tf_ans = ans.eval()\n\n self.assertAllClose(np_ans, tf_ans)\n\n # [Tensor, Scalar, Scalar]\n def DISABLED_testClipByValue0Type(self):\n for dtype in [\n dtypes.float16, dtypes.float32, dtypes.float64, dtypes.int8,\n dtypes.int16, dtypes.int32, dtypes.int64, dtypes.uint8, dtypes.uint16\n ]:\n with self.cached_session(use_gpu=True):\n x = constant_op.constant([1, 2, 3, 4, 5, 6], shape=[2, 3], dtype=dtype)\n np_ans = [[2, 2, 3], [4, 4, 4]]\n clip_value_min = 2\n clip_value_max = 4\n ans = clip_ops.clip_by_value(x, clip_value_min, clip_value_max)\n tf_ans = ans.eval()\n\n self.assertAllClose(np_ans, tf_ans)\n\n # [Tensor, Tensor, Scalar]\n def DISABLED_testClipByValue1Type(self):\n for dtype in [\n dtypes.float16, dtypes.float32, dtypes.float64, dtypes.int8,\n dtypes.int16, dtypes.int32, dtypes.int64, dtypes.uint8, dtypes.uint16\n ]:\n with self.cached_session(use_gpu=True):\n x = constant_op.constant([1, 2, 3, 4, 5, 6], shape=[2, 3], dtype=dtype)\n np_ans = [[2, 2, 3], [4, 4, 4]]\n clip_value_min = constant_op.constant(\n [2, 2, 2, 3, 3, 3], shape=[2, 3], dtype=dtype)\n clip_value_max = 4\n ans = clip_ops.clip_by_value(x, clip_value_min, clip_value_max)\n tf_ans = ans.eval()\n\n self.assertAllClose(np_ans, tf_ans)\n\n # [Tensor, Scalar, Tensor]\n def DISABLED_testClipByValue2Type(self):\n for dtype in [\n dtypes.float16, dtypes.float32, dtypes.float64, dtypes.int8,\n dtypes.int16, dtypes.int32, dtypes.int64, dtypes.uint8, dtypes.uint16\n ]:\n with self.cached_session(use_gpu=True):\n x = constant_op.constant([1, 2, 3, 4, 5, 6], shape=[2, 3], dtype=dtype)\n np_ans = [[4, 4, 4], [4, 5, 6]]", "answers": [" clip_value_min = 4"], "length": 416, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "659d0d90-06ae-4437-8de3-f50850732cbe", "reasoning": "In the DISABLED_testClipByValue2Type method, after defining the expected NumPy answer (np_ans), the test sets up a scalar minimum clip value and a tensor maximum clip value. Following the pattern of previous tests, the next line should define the scalar minimum clip value, which is 4.", "reasoning_model_answer": "clip_value_min = 4", "assistant_with_reasoning": "\nIn the DISABLED_testClipByValue2Type method, after defining the expected NumPy answer (np_ans), the test sets up a scalar minimum clip value and a tensor maximum clip value. Following the pattern of previous tests, the next line should define the scalar minimum clip value, which is 4.\n\nclip_value_min = 4", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 6.045, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 2, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 4280, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "clip_value_min = 4", "score": 0.82, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "package com.badlogic.gdx.backends.iosrobovm;\n\nimport java.nio.Buffer;\nimport java.nio.FloatBuffer;\nimport java.nio.IntBuffer;\n\nimport com.badlogic.gdx.graphics.GL20;\nimport com.badlogic.gdx.graphics.GLCommon;\n\n\npublic class IOSGLES20 implements GL20, GLCommon\n{\t\n\tpublic IOSGLES20() {\n\t\tinit();\n\t}\n\t\n\tprivate static native void init( );\t\n\t\n\tpublic native void glActiveTexture ( int texture );\n\n\tpublic native void glAttachShader ( int program, int shader );\n\n\tpublic native void glBindAttribLocation ( int program, int index, String name );\n\n\tpublic native void glBindBuffer ( int target, int buffer );\n\n\tpublic native void glBindFramebuffer ( int target, int framebuffer );\n\n\tpublic native void glBindRenderbuffer ( int target, int renderbuffer );\n\n\tpublic native void glBindTexture ( int target, int texture );\n\n\tpublic native void glBlendColor ( float red, float green, float blue, float alpha );\n\n\tpublic native void glBlendEquation ( int mode );\n\n\tpublic native void glBlendEquationSeparate ( int modeRGB, int modeAlpha );\n\n\tpublic native void glBlendFunc ( int sfactor, int dfactor );\n\n\tpublic native void glBlendFuncSeparate ( int srcRGB, int dstRGB, int srcAlpha, int dstAlpha );\n\n\tpublic native void glBufferData ( int target, int size, Buffer data, int usage );\n\n\tpublic native void glBufferSubData ( int target, int offset, int size, Buffer data );\n\n\tpublic native int glCheckFramebufferStatus ( int target );\n\n\tpublic native void glClear ( int mask );\n\n\tpublic native void glClearColor ( float red, float green, float blue, float alpha );\n\n\tpublic native void glClearDepthf ( float depth );\n\n\tpublic native void glClearStencil ( int s );\n\n\tpublic native void glColorMask ( boolean red, boolean green, boolean blue, boolean alpha );\n\n\tpublic native void glCompileShader ( int shader );\n\n\tpublic native void glCompressedTexImage2D ( int target, int level, int internalformat, int width, int height, int border, int imageSize, Buffer data );\n\n\tpublic native void glCompressedTexSubImage2D ( int target, int level, int xoffset, int yoffset, int width, int height, int format, int imageSize, Buffer data );\n\n\tpublic native void glCopyTexImage2D ( int target, int level, int internalformat, int x, int y, int width, int height, int border );\n\n\tpublic native void glCopyTexSubImage2D ( int target, int level, int xoffset, int yoffset, int x, int y, int width, int height );\n\n\tpublic native int glCreateProgram ( );\n\n\tpublic native int glCreateShader ( int type );\n\n\tpublic native void glCullFace ( int mode );\n\n\tpublic native void glDeleteBuffers ( int n, IntBuffer buffers );\n\n\tpublic native void glDeleteFramebuffers ( int n, IntBuffer framebuffers );\n\n\tpublic native void glDeleteProgram ( int program );\n\n\tpublic native void glDeleteRenderbuffers ( int n, IntBuffer renderbuffers );\n\n\tpublic native void glDeleteShader ( int shader );\n\n\tpublic native void glDeleteTextures ( int n, IntBuffer textures );\n\n\tpublic native void glDepthFunc ( int func );\n\n\tpublic native void glDepthMask ( boolean flag );\n\n\tpublic native void glDepthRangef ( float zNear, float zFar );\n\n\tpublic native void glDetachShader ( int program, int shader );\n\n\tpublic native void glDisable ( int cap );\n\n\tpublic native void glDisableVertexAttribArray ( int index );\n", "answers": ["\tpublic native void glDrawArrays ( int mode, int first, int count );"], "length": 477, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "53662615-f840-4ffe-8b58-7ec4db2ab61e", "reasoning": "The class implements the GL20 interface, listing native method declarations in the same order as the GL20 specification. After the glDisableVertexAttribArray method, the next GL20 method in the standard ordering is glDrawArrays, which takes mode, first, and count parameters. Following the existing formatting style, the next line should declare this native method.", "reasoning_model_answer": "public native void glDrawArrays ( int mode, int first, int count );", "assistant_with_reasoning": "\nThe class implements the GL20 interface, listing native method declarations in the same order as the GL20 specification. After the glDisableVertexAttribArray method, the next GL20 method in the standard ordering is glDrawArrays, which takes mode, first, and count parameters. Following the existing formatting style, the next line should declare this native method.\n\npublic native void glDrawArrays ( int mode, int first, int count );", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.798, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 3343, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "public native void glDrawArrays ( int mode, int first, int count );", "score": 0.99, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\nusing System.Diagnostics;\nusing System.Reflection;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Xunit;\n\nnamespace System.Collections.Tests\n{\n public static class QueueTests\n {\n [Fact]\n public static void Ctor_Empty()\n {\n const int DefaultCapactiy = 32;\n var queue = new Queue();\n\n Assert.Equal(0, queue.Count);\n\n for (int i = 0; i <= DefaultCapactiy; i++)\n {\n queue.Enqueue(i);\n }\n\n Assert.Equal(DefaultCapactiy + 1, queue.Count);\n }\n\n [Theory]\n [InlineData(1)]\n [InlineData(32)]\n [InlineData(77)]\n public static void Ctor_Int(int capacity)\n {\n var queue = new Queue(capacity);\n\n for (int i = 0; i <= capacity; i++)\n {\n queue.Enqueue(i);\n }\n Assert.Equal(capacity + 1, queue.Count);\n }\n\n [Fact]\n public static void Ctor_Int_NegativeCapacity_ThrowsArgumentOutOfRangeException()\n {\n Assert.Throws(\"capacity\", () => new Queue(-1)); // Capacity < 0\n }\n\n [Theory]\n [InlineData(1, 2.0)]\n [InlineData(32, 1.0)]\n [InlineData(77, 5.0)]\n public static void Ctor_Int_Int(int capacity, float growFactor)\n {\n var queue = new Queue(capacity, growFactor);\n\n for (int i = 0; i <= capacity; i++)\n {\n queue.Enqueue(i);\n }\n Assert.Equal(capacity + 1, queue.Count);\n }\n\n [Fact]\n public static void Ctor_Int_Int_Invalid()\n {\n Assert.Throws(\"capacity\", () => new Queue(-1, 1)); // Capacity < 0\n Assert.Throws(\"growFactor\", () => new Queue(1, (float)0.99)); // Grow factor < 1\n Assert.Throws(\"growFactor\", () => new Queue(1, (float)10.01)); // Grow factor > 10\n }\n\n [Fact]\n public static void Ctor_ICollection()\n {\n ArrayList arrList = Helpers.CreateIntArrayList(100);\n var queue = new Queue(arrList);\n\n Assert.Equal(arrList.Count, queue.Count);\n for (int i = 0; i < queue.Count; i++)\n {\n Assert.Equal(i, queue.Dequeue());\n }\n }\n\n [Fact]\n public static void Ctor_ICollection_NullCollection_ThrowsArgumentNullException()\n {\n Assert.Throws(\"col\", () => new Queue(null)); // Collection is null\n }\n\n [Fact]\n public static void DebuggerAttribute()\n {\n DebuggerAttributes.ValidateDebuggerDisplayReferences(new Queue());\n\n var testQueue = new Queue();\n testQueue.Enqueue(\"a\");\n testQueue.Enqueue(1);\n testQueue.Enqueue(\"b\");\n testQueue.Enqueue(2);\n DebuggerAttributes.ValidateDebuggerTypeProxyProperties(testQueue);\n\n bool threwNull = false;\n try\n {\n DebuggerAttributes.ValidateDebuggerTypeProxyProperties(typeof(Queue), null);\n }\n catch (TargetInvocationException ex)\n {\n threwNull = ex.InnerException is ArgumentNullException;\n }\n\n Assert.True(threwNull);\n }\n\n [Theory]\n [InlineData(0)]\n [InlineData(1)]\n [InlineData(32)]\n public static void Clear(int capacity)\n {\n var queue1 = new Queue(capacity);\n Helpers.PerformActionOnAllQueueWrappers(queue1, queue2 =>\n {\n queue2.Enqueue(1);\n queue2.Clear();\n Assert.Equal(0, queue2.Count);\n });\n }\n\n [Theory]\n [InlineData(0)]\n [InlineData(1)]\n [InlineData(32)]\n public static void Clear_Empty(int capacity)\n {\n var queue1 = new Queue(capacity);\n Helpers.PerformActionOnAllQueueWrappers(queue1, queue2 =>\n {\n queue2.Clear();\n Assert.Equal(0, queue2.Count);\n\n queue2.Clear();\n Assert.Equal(0, queue2.Count);\n });\n }\n [Fact]\n public static void Clone()\n {\n Queue queue1 = Helpers.CreateIntQueue(100);\n Helpers.PerformActionOnAllQueueWrappers(queue1, queue2 =>\n {\n Queue clone = (Queue)queue2.Clone();\n Assert.Equal(queue2.IsSynchronized, clone.IsSynchronized);\n\n Assert.Equal(queue2.Count, clone.Count);\n for (int i = 0; i < queue2.Count; i++)\n {\n Assert.True(clone.Contains(i));\n }\n });\n }\n\n [Fact]\n public static void Clone_IsShallowCopy()\n {\n var queue1 = new Queue();\n Helpers.PerformActionOnAllQueueWrappers(queue1, queue2 =>\n {\n queue2.Enqueue(new Foo(10));\n Queue clone = (Queue)queue2.Clone();\n\n var foo = (Foo)queue2.Dequeue();\n foo.IntValue = 50;\n\n var fooClone = (Foo)clone.Dequeue();\n Assert.Equal(50, fooClone.IntValue);\n });\n }\n\n [Fact]\n public static void Clone_Empty()\n {\n var queue1 = new Queue();\n Helpers.PerformActionOnAllQueueWrappers(queue1, queue2 =>\n {\n Queue clone = (Queue)queue2.Clone();\n Assert.Equal(0, clone.Count);\n\n // Can change the clone queue\n clone.Enqueue(500);\n Assert.Equal(500, clone.Dequeue());\n });\n }\n\n [Fact]\n public static void Clone_Clear()\n {\n Queue queue1 = Helpers.CreateIntQueue(100);\n Helpers.PerformActionOnAllQueueWrappers(queue1, queue2 =>\n {\n queue2.Clear();\n\n Queue clone = (Queue)queue2.Clone();\n Assert.Equal(0, clone.Count);\n\n // Can change clone queue\n clone.Enqueue(500);\n Assert.Equal(500, clone.Dequeue());\n });\n }\n\n [Fact]\n public static void Clone_DequeueUntilEmpty()\n {\n Queue queue1 = Helpers.CreateIntQueue(100);\n Helpers.PerformActionOnAllQueueWrappers(queue1, queue2 =>\n {\n for (int i = 0; i < 100; i++)\n {\n queue2.Dequeue();\n }\n\n Queue clone = (Queue)queue2.Clone();\n Assert.Equal(0, queue2.Count);\n\n // Can change clone the queue\n clone.Enqueue(500);\n Assert.Equal(500, clone.Dequeue());\n });\n }\n\n [Fact]\n public static void Clone_DequeueThenEnqueue()\n {\n var queue1 = new Queue(100);\n Helpers.PerformActionOnAllQueueWrappers(queue1, queue2 =>\n {\n // Insert 50 items in the Queue", "answers": [" for (int i = 0; i < 50; i++)"], "length": 557, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "24e09ecf-2391-4c22-90cc-acb3f30b933f", "reasoning": "The method is setting up a test where 50 items are added to the queue before further operations. Following the code style used elsewhere, a for‑loop header is placed on its own line, with the opening brace on the next line. Therefore the next line should start the loop that enqueues 50 elements into queue2.", "reasoning_model_answer": "for (int i = 0; i < 50; i++)", "assistant_with_reasoning": "\nThe method is setting up a test where 50 items are added to the queue before further operations. Following the code style used elsewhere, a for‑loop header is placed on its own line, with the opening brace on the next line. Therefore the next line should start the loop that enqueues 50 elements into queue2.\n\nfor (int i = 0; i < 50; i++)", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.554, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 7470, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "for (int i = 0; i < 50; i++)", "score": 0.78, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "// This file was generated by the Gtk# code generator.\n// Any changes made will be lost if regenerated.\n\nnamespace Gst.Sdp {\n\n\tusing System;\n\tusing System.Collections;\n\tusing System.Collections.Generic;\n\tusing System.Runtime.InteropServices;\n\n#region Autogenerated code\n\tpublic partial class SDPMessage : GLib.Opaque {\n\n\t\t[DllImport(\"gstsdp-1.0-0.dll\", CallingConvention = CallingConvention.Cdecl)]\n\t\tstatic extern IntPtr gst_sdp_message_get_version(IntPtr raw);\n\n\t\tpublic string Version {\n\t\t\tget {\n\t\t\t\tIntPtr raw_ret = gst_sdp_message_get_version(Handle);\n\t\t\t\tstring ret = GLib.Marshaller.Utf8PtrToString (raw_ret);\n\t\t\t\treturn ret;\n\t\t\t}\n\t\t\tset {\n\t\t\t\tunsafe {\n\t\t\t\t\tIntPtr* raw_ptr = (IntPtr*)(((byte*)Handle) + abi_info.GetFieldOffset(\"version\"));\n\t\t\t\t\t*raw_ptr = GLib.Marshaller.StringToPtrGStrdup (value);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t[DllImport(\"gstsdp-1.0-0.dll\", CallingConvention = CallingConvention.Cdecl)]\n\t\tstatic extern IntPtr gst_sdp_message_get_origin(IntPtr raw);\n\n\t\tpublic Gst.Sdp.SDPOrigin Origin {\n\t\t\tget {\n\t\t\t\tIntPtr raw_ret = gst_sdp_message_get_origin(Handle);\n\t\t\t\tGst.Sdp.SDPOrigin ret = Gst.Sdp.SDPOrigin.New (raw_ret);\n\t\t\t\treturn ret;\n\t\t\t}\n\t\t\tset {\n\t\t\t\tunsafe {\n\t\t\t\t\tIntPtr* raw_ptr = (IntPtr*)(((byte*)Handle) + abi_info.GetFieldOffset(\"origin\"));\n\t\t\t\t\t*raw_ptr = GLib.Marshaller.StructureToPtrAlloc (value);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t[DllImport(\"gstsdp-1.0-0.dll\", CallingConvention = CallingConvention.Cdecl)]\n\t\tstatic extern IntPtr gst_sdp_message_get_session_name(IntPtr raw);\n\n\t\tpublic string SessionName {\n\t\t\tget {\n\t\t\t\tIntPtr raw_ret = gst_sdp_message_get_session_name(Handle);\n\t\t\t\tstring ret = GLib.Marshaller.Utf8PtrToString (raw_ret);\n\t\t\t\treturn ret;\n\t\t\t}\n\t\t\tset {\n\t\t\t\tunsafe {\n\t\t\t\t\tIntPtr* raw_ptr = (IntPtr*)(((byte*)Handle) + abi_info.GetFieldOffset(\"session_name\"));\n\t\t\t\t\t*raw_ptr = GLib.Marshaller.StringToPtrGStrdup (value);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t[DllImport(\"gstsdp-1.0-0.dll\", CallingConvention = CallingConvention.Cdecl)]\n\t\tstatic extern IntPtr gst_sdp_message_get_information(IntPtr raw);\n\n\t\tpublic string Information {\n\t\t\tget {\n\t\t\t\tIntPtr raw_ret = gst_sdp_message_get_information(Handle);\n\t\t\t\tstring ret = GLib.Marshaller.Utf8PtrToString (raw_ret);\n\t\t\t\treturn ret;\n\t\t\t}\n\t\t\tset {\n\t\t\t\tunsafe {\n\t\t\t\t\tIntPtr* raw_ptr = (IntPtr*)(((byte*)Handle) + abi_info.GetFieldOffset(\"information\"));\n\t\t\t\t\t*raw_ptr = GLib.Marshaller.StringToPtrGStrdup (value);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t[DllImport(\"gstsdp-1.0-0.dll\", CallingConvention = CallingConvention.Cdecl)]\n\t\tstatic extern IntPtr gst_sdp_message_get_uri(IntPtr raw);\n\n\t\tpublic string Uri {\n\t\t\tget {\n\t\t\t\tIntPtr raw_ret = gst_sdp_message_get_uri(Handle);\n\t\t\t\tstring ret = GLib.Marshaller.Utf8PtrToString (raw_ret);\n\t\t\t\treturn ret;\n\t\t\t}\n\t\t\tset {\n\t\t\t\tunsafe {\n\t\t\t\t\tIntPtr* raw_ptr = (IntPtr*)(((byte*)Handle) + abi_info.GetFieldOffset(\"uri\"));\n\t\t\t\t\t*raw_ptr = GLib.Marshaller.StringToPtrGStrdup (value);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t[DllImport(\"gstsdp-1.0-0.dll\", CallingConvention = CallingConvention.Cdecl)]\n\t\tstatic extern IntPtr gst_sdp_message_get_connection(IntPtr raw);\n\n\t\tpublic Gst.Sdp.SDPConnection Connection {\n\t\t\tget {\n\t\t\t\tIntPtr raw_ret = gst_sdp_message_get_connection(Handle);\n\t\t\t\tGst.Sdp.SDPConnection ret = Gst.Sdp.SDPConnection.New (raw_ret);\n\t\t\t\treturn ret;\n\t\t\t}\n\t\t\tset {\n\t\t\t\tunsafe {\n\t\t\t\t\tIntPtr* raw_ptr = (IntPtr*)(((byte*)Handle) + abi_info.GetFieldOffset(\"connection\"));\n\t\t\t\t\t*raw_ptr = GLib.Marshaller.StructureToPtrAlloc (value);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t[DllImport(\"gstsdp-1.0-0.dll\", CallingConvention = CallingConvention.Cdecl)]\n\t\tstatic extern IntPtr gst_sdp_message_get_key(IntPtr raw);\n\n\t\tpublic Gst.Sdp.SDPKey Key {\n\t\t\tget {\n\t\t\t\tIntPtr raw_ret = gst_sdp_message_get_key(Handle);\n\t\t\t\tGst.Sdp.SDPKey ret = Gst.Sdp.SDPKey.New (raw_ret);\n\t\t\t\treturn ret;\n\t\t\t}\n\t\t\tset {\n\t\t\t\tunsafe {\n\t\t\t\t\tIntPtr* raw_ptr = (IntPtr*)(((byte*)Handle) + abi_info.GetFieldOffset(\"key\"));\n\t\t\t\t\t*raw_ptr = GLib.Marshaller.StructureToPtrAlloc (value);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t[DllImport(\"gstsdp-1.0-0.dll\", CallingConvention = CallingConvention.Cdecl)]\n\t\tstatic extern IntPtr gst_sdp_message_get_type();\n\n\t\tpublic static GLib.GType GType { \n\t\t\tget {\n\t\t\t\tIntPtr raw_ret = gst_sdp_message_get_type();\n\t\t\t\tGLib.GType ret = new GLib.GType(raw_ret);\n\t\t\t\treturn ret;\n\t\t\t}\n\t\t}\n\n\t\t[DllImport(\"gstsdp-1.0-0.dll\", CallingConvention = CallingConvention.Cdecl)]\n\t\tstatic extern int gst_sdp_message_add_attribute(IntPtr raw, IntPtr key, IntPtr value);\n\n\t\tpublic Gst.Sdp.SDPResult AddAttribute(string key, string value) {\n\t\t\tIntPtr native_key = GLib.Marshaller.StringToPtrGStrdup (key);\n\t\t\tIntPtr native_value = GLib.Marshaller.StringToPtrGStrdup (value);\n\t\t\tint raw_ret = gst_sdp_message_add_attribute(Handle, native_key, native_value);\n\t\t\tGst.Sdp.SDPResult ret = (Gst.Sdp.SDPResult) raw_ret;\n\t\t\tGLib.Marshaller.Free (native_key);\n\t\t\tGLib.Marshaller.Free (native_value);\n\t\t\treturn ret;\n\t\t}\n\n\t\tpublic Gst.Sdp.SDPResult AddAttribute(string key) {\n\t\t\treturn AddAttribute (key, null);\n\t\t}\n\n\t\t[DllImport(\"gstsdp-1.0-0.dll\", CallingConvention = CallingConvention.Cdecl)]\n\t\tstatic extern int gst_sdp_message_add_bandwidth(IntPtr raw, IntPtr bwtype, uint bandwidth);\n\n\t\tpublic Gst.Sdp.SDPResult AddBandwidth(string bwtype, uint bandwidth) {\n\t\t\tIntPtr native_bwtype = GLib.Marshaller.StringToPtrGStrdup (bwtype);\n\t\t\tint raw_ret = gst_sdp_message_add_bandwidth(Handle, native_bwtype, bandwidth);\n\t\t\tGst.Sdp.SDPResult ret = (Gst.Sdp.SDPResult) raw_ret;\n\t\t\tGLib.Marshaller.Free (native_bwtype);\n\t\t\treturn ret;\n\t\t}\n\n\t\t[DllImport(\"gstsdp-1.0-0.dll\", CallingConvention = CallingConvention.Cdecl)]\n\t\tstatic extern int gst_sdp_message_add_email(IntPtr raw, IntPtr email);\n\n\t\tpublic Gst.Sdp.SDPResult AddEmail(string email) {\n\t\t\tIntPtr native_email = GLib.Marshaller.StringToPtrGStrdup (email);\n\t\t\tint raw_ret = gst_sdp_message_add_email(Handle, native_email);\n\t\t\tGst.Sdp.SDPResult ret = (Gst.Sdp.SDPResult) raw_ret;\n\t\t\tGLib.Marshaller.Free (native_email);\n\t\t\treturn ret;\n\t\t}\n\n\t\t[DllImport(\"gstsdp-1.0-0.dll\", CallingConvention = CallingConvention.Cdecl)]\n\t\tstatic extern int gst_sdp_message_add_media(IntPtr raw, IntPtr media);", "answers": ["\t\tpublic Gst.Sdp.SDPResult AddMedia(Gst.Sdp.SDPMedia media) {"], "length": 527, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "ad21443a-da12-4184-82a6-db009793f80e", "reasoning": "The code pattern shows that after each DllImport declaration, a public wrapper method is defined. The last DllImport declares gst_sdp_message_add_media which in the native API expects a GstSDPMedia pointer. The generated C# wrapper will therefore accept a Gst.Sdp.SDPMedia object and return an SDPResult. Following the established style, the next line should be the method signature with opening brace.", "reasoning_model_answer": "public Gst.Sdp.SDPResult AddMedia(Gst.Sdp.SDPMedia media) {", "assistant_with_reasoning": "\nThe code pattern shows that after each DllImport declaration, a public wrapper method is defined. The last DllImport declares gst_sdp_message_add_media which in the native API expects a GstSDPMedia pointer. The generated C# wrapper will therefore accept a Gst.Sdp.SDPMedia object and return an SDPResult. Following the established style, the next line should be the method signature with opening brace.\n\npublic Gst.Sdp.SDPResult AddMedia(Gst.Sdp.SDPMedia media) {", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.927, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 6124, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "public Gst.Sdp.SDPResult AddMedia(Gst.Sdp.SDPMedia media) {", "score": 0.98, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "\"\"\"\n\n## Hyptotheis Testing Stuff\n\n\n### Standard Stuff\n\n#### Standard Headers\n\n\"\"\"\nfrom __future__ import division\nimport sys\nimport random\nimport math\nfrom functools import reduce\nsys.dont_write_bytecode = True\n\"\"\"\n\n#### Standard Utils\n\n\"\"\"\n\n\nclass o():\n\n \"Anonymous container\"\n def __init__(i, **fields):\n i.override(fields)\n\n def override(i, d):\n i.__dict__.update(d)\n return i\n\n def __repr__(i):\n d = i.__dict__\n name = i.__class__.__name__\n return name + '{' + ' '.join([':%s %s' % (k, pretty(d[k]))\n for k in i.show()]) + '}'\n\n def show(i):\n return [k for k in sorted(i.__dict__.keys())\n if not \"_\" in k]\n\"\"\"\n\nMisc functions:\n\n\"\"\"\nrand = random.random\nany = random.choice\nseed = random.seed\nexp = lambda n: math.e ** n\nln = lambda n: math.log(n, math.e)\ng = lambda n: round(n, 2)\n\n\ndef median(lst, ordered=False):\n if not ordered:\n lst = sorted(lst)\n n = len(lst)\n p = n // 2\n if n % 2:\n return lst[p]\n q = p - 1\n q = max(0, min(q, n))\n return (lst[p] + lst[q]) / 2\n\n\ndef msecs(f):\n import time\n t1 = time.time()\n f()\n return (time.time() - t1) * 1000\n\n\ndef pairs(lst):\n \"Return all pairs of items i,i+1 from a list.\"\n last = lst[0]\n for i in lst[1:]:\n yield last, i\n last = i\n\n\ndef xtile(lst, lo=0, hi=1, width=50,\n chops=[0.25, 0.5, 0.75],\n marks=[\"-\", \" \", \"-\"],\n bar=\"|\", star=\"*\", show=\" %0.2f\"):\n \"\"\"The function _xtile_ takes a list of (possibly)\n unsorted numbers and presents them as a horizontal\n xtile chart (in ascii format). The default is a\n contracted _quintile_ that shows the\n 10,30,50,70,90 breaks in the data.dat (but this can be\n changed- see the optional flags of the function).\n \"\"\"\n def pos(p):\n return ordered[int(len(lst) * p)]\n\n def place(x):\n return int(width * float((x - lo)) / (hi - lo + 0.00001))\n\n def pretty(lst):\n return ', '.join([str(show % x) for x in lst])\n ordered = sorted(lst)\n lo = min(lo, ordered[0])\n hi = max(hi, ordered[-1])\n what = [pos(p) for p in chops]\n where = [place(n) for n in what]\n out = [\" \"] * width\n for one, two in pairs(where):\n for i in range(one, two):\n out[i] = marks[0]\n marks = marks[1:]\n out[int(width / 2)] = bar\n out[place(pos(0.5))] = star\n return '(' + ''.join(out) + \"),\" + pretty(what)\n\n\ndef _tileX():\n import random\n random.seed(1)\n nums = [random.random() ** 2 for _ in range(100)]\n print xtile(nums, lo=0, hi=1.0, width=25, show=\" %0.3E\")\n\"\"\"\n\n### Standard Accumulator for Numbers\n\nNote the _lt_ method: this accumulator can be sorted by median values.\n\nWarning: this accumulator keeps _all_ numbers. Might be better to use\na bounded cache.\n\n\"\"\"\n\n\nclass Num:\n\n \"An Accumulator for numbers\"\n def __init__(i, name, inits=[]):\n i.n = i.m2 = i.mu = 0.0\n i.all = []\n i._median = None\n i.name = name\n i.rank = 0\n for x in inits:\n i.add(x)\n\n def s(i):\n return (i.m2 / (i.n - 1)) ** 0.5\n\n def add(i, x):\n i._median = None\n i.n += 1\n i.all += [x]\n delta = x - i.mu\n i.mu += delta * 1.0 / i.n\n i.m2 += delta * (x - i.mu)\n\n def __add__(i, j):\n return Num(i.name + j.name, i.all + j.all)\n\n def quartiles(i):\n def p(x):\n return int(100 * g(xs[x]))\n i.median()\n xs = i.all\n n = int(len(xs) * 0.25)\n return p(n), p(2 * n), p(3 * n)\n", "answers": [" def median(i):"], "length": 522, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "7ee093c9-15ac-4789-8ed4-efd63d47e53d", "reasoning": "The Num class defines methods __init__, s, add, __add__, and quartiles. The quartiles method calls i.median(), but a median method hasn't been defined yet. The next logical line is the start of the median method definition, indented consistently with the other methods.", "reasoning_model_answer": "def median(i):", "assistant_with_reasoning": "\nThe Num class defines methods __init__, s, add, __add__, and quartiles. The quartiles method calls i.median(), but a median method hasn't been defined yet. The next logical line is the start of the median method definition, indented consistently with the other methods.\n\ndef median(i):", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.087, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 3431, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "def median(i):", "score": 0.93, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/*! ******************************************************************************\n *\n * Pentaho Data Integration\n *\n * Copyright (C) 2002-2017 by Hitachi Vantara : http://www.pentaho.com\n *\n *******************************************************************************\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n ******************************************************************************/\n\npackage org.pentaho.di.trans.steps.simplemapping;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport org.pentaho.di.core.Const;\nimport org.pentaho.di.core.exception.KettleException;\nimport org.pentaho.di.core.exception.KettleStepException;\nimport org.pentaho.di.core.row.RowMetaInterface;\nimport org.pentaho.di.i18n.BaseMessages;\nimport org.pentaho.di.trans.RowProducer;\nimport org.pentaho.di.trans.Trans;\nimport org.pentaho.di.trans.TransMeta;\nimport org.pentaho.di.trans.TransMeta.TransformationType;\nimport org.pentaho.di.trans.step.BaseStep;\nimport org.pentaho.di.trans.step.RowListener;\nimport org.pentaho.di.trans.step.StepDataInterface;\nimport org.pentaho.di.trans.step.StepInterface;\nimport org.pentaho.di.trans.step.StepMeta;\nimport org.pentaho.di.trans.step.StepMetaInterface;\nimport org.pentaho.di.trans.steps.TransStepUtil;\nimport org.pentaho.di.trans.steps.mapping.MappingParameters;\nimport org.pentaho.di.trans.steps.mapping.MappingValueRename;\nimport org.pentaho.di.trans.steps.mappinginput.MappingInput;\nimport org.pentaho.di.trans.steps.mappingoutput.MappingOutput;\n\n/**\n * Execute a mapping: a re-usuable transformation\n *\n * @author Matt\n * @since 22-nov-2005\n */\npublic class SimpleMapping extends BaseStep implements StepInterface {\n private static Class PKG = SimpleMappingMeta.class; // for i18n purposes, needed by Translator2!!\n\n private SimpleMappingMeta meta;\n private SimpleMappingData data;\n\n public SimpleMapping( StepMeta stepMeta, StepDataInterface stepDataInterface, int copyNr, TransMeta transMeta,\n Trans trans ) {\n super( stepMeta, stepDataInterface, copyNr, transMeta, trans );\n }\n\n /**\n * Process a single row. In our case, we send one row of data to a piece of transformation. In the transformation, we\n * look up the MappingInput step to send our rows to it. As a consequence, for the time being, there can only be one\n * MappingInput and one MappingOutput step in the Mapping.\n */\n public boolean processRow( StepMetaInterface smi, StepDataInterface sdi ) throws KettleException {\n meta = (SimpleMappingMeta) smi;\n setData( (SimpleMappingData) sdi );\n SimpleMappingData simpleMappingData = getData();\n try {\n if ( first ) {\n first = false;\n simpleMappingData.wasStarted = true;\n\n // Rows read are injected into the one available Mapping Input step\n //\n String mappingInputStepname = simpleMappingData.mappingInput.getStepname();\n RowProducer rowProducer = simpleMappingData.mappingTrans.addRowProducer( mappingInputStepname, 0 );\n simpleMappingData.rowDataInputMapper = new RowDataInputMapper( meta.getInputMapping(), rowProducer );\n\n // Rows produced by the mapping are read and passed on.\n //\n String mappingOutputStepname = simpleMappingData.mappingOutput.getStepname();\n StepInterface outputStepInterface = simpleMappingData.mappingTrans.findStepInterface( mappingOutputStepname, 0 );\n RowOutputDataMapper outputDataMapper =\n new RowOutputDataMapper( meta.getInputMapping(), meta.getOutputMapping(), new PutRowInterface() {\n\n @Override\n public void putRow( RowMetaInterface rowMeta, Object[] rowData ) throws KettleStepException {\n SimpleMapping.this.putRow( rowMeta, rowData );\n }\n } );\n outputStepInterface.addRowListener( outputDataMapper );\n\n // Start the mapping/sub-transformation threads\n //\n simpleMappingData.mappingTrans.startThreads();\n }\n\n // The data we read we pass to the mapping\n //\n Object[] row = getRow();\n boolean rowWasPut = false;\n if ( row != null ) {\n while ( !( data.mappingTrans.isFinishedOrStopped() || rowWasPut ) ) {\n rowWasPut = data.rowDataInputMapper.putRow( getInputRowMeta(), row );\n }\n }\n\n if ( !rowWasPut ) {\n simpleMappingData.rowDataInputMapper.finished();\n simpleMappingData.mappingTrans.waitUntilFinished();\n setOutputDone();\n return false;\n }\n\n return true;\n } catch ( Throwable t ) {\n // Some unexpected situation occurred.\n // Better to stop the mapping transformation.\n //\n if ( simpleMappingData.mappingTrans != null ) {\n simpleMappingData.mappingTrans.stopAll();\n }\n\n // Forward the exception...\n //\n throw new KettleException( t );\n }\n }\n\n private void setMappingParameters() throws KettleException {\n MappingParameters mappingParameters = meta.getMappingParameters();", "answers": [" if ( mappingParameters != null ) {"], "length": 522, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "f76ad283-8dbe-4147-80ee-8f2fe517efb7", "reasoning": "Inside setMappingParameters(), the first statement creates a MappingParameters object. The next logical step is to check if this object is non‑null before applying its values to the sub‑transformation. The code pattern in Pentaho uses an if‑statement to guard the subsequent parameter handling, so the next line should be the null‑check opening the block.", "reasoning_model_answer": "if ( mappingParameters != null ) {", "assistant_with_reasoning": "\nInside setMappingParameters(), the first statement creates a MappingParameters object. The next logical step is to check if this object is non‑null before applying its values to the sub‑transformation. The code pattern in Pentaho uses an if‑statement to guard the subsequent parameter handling, so the next line should be the null‑check opening the block.\n\nif ( mappingParameters != null ) {", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.331, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 5566, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "if ( mappingParameters != null ) {", "score": 0.94, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/*\n * Copyright 2009 The Closure Compiler Authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.javascript.jscomp;\n\nimport com.google.common.base.Joiner;\nimport com.google.common.base.Preconditions;\nimport com.google.common.collect.Iterables;\nimport com.google.common.collect.Lists;\nimport com.google.common.collect.Maps;\nimport com.google.common.collect.Sets;\nimport com.google.javascript.rhino.JSDocInfo;\nimport com.google.javascript.rhino.Node;\nimport com.google.javascript.rhino.Token;\nimport com.google.javascript.rhino.jstype.FunctionType;\nimport com.google.javascript.rhino.jstype.JSType;\n\nimport java.util.Comparator;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.TreeSet;\n\n/**\n * Creates an externs file containing all exported symbols and properties\n * for later consumption.\n *\n */\nfinal class ExternExportsPass extends NodeTraversal.AbstractPostOrderCallback\n implements CompilerPass {\n\n static final DiagnosticType EXPORTED_FUNCTION_UNKNOWN_PARAMETER_TYPE =\n DiagnosticType.warning(\n \"JSC_EXPORTED_FUNCTION_UNKNOWN_PARAMETER_TYPE\",\n \"Unable to determine type of parameter {0} for exported function {1}\");\n\n static final DiagnosticType EXPORTED_FUNCTION_UNKNOWN_RETURN_TYPE =\n DiagnosticType.warning(\n \"JSC_EXPORTED_FUNCTION_UNKNOWN_RETURN_TYPE\",\n \"Unable to determine return type for exported function {0}\");\n\n /** The exports found. */\n private final List exports;\n\n /** A map of all assigns to their parent nodes. */\n private final Map definitionMap;\n\n /** The parent compiler. */\n private final AbstractCompiler compiler;\n\n /** The AST root which holds the externs generated. */\n private final Node externsRoot;\n\n /** A mapping of internal paths to exported paths. */\n private final Map mappedPaths;\n\n /** A list of exported paths. */\n private final Set alreadyExportedPaths;\n\n private abstract class Export {\n protected final String symbolName;\n protected final Node value;\n\n Export(String symbolName, Node value) {\n this.symbolName = symbolName;\n this.value = value;\n }\n\n /**\n * Generates the externs representation of this export and appends\n * it to the externsRoot AST.\n */\n void generateExterns() {\n appendExtern(getExportedPath(), getFunctionValue(value));\n }\n\n /**\n * Returns the path exported by this export.\n */\n abstract String getExportedPath();\n\n /**\n * Appends the exported function and all paths necessary for the path to be\n * declared. For example, for a property \"a.b.c\", the initializers for\n * paths \"a\", \"a.b\" will be appended (if they have not already) and a.b.c\n * will be initialized with the exported version of the function:\n *
    \n     * var a = {};\n     * a.b = {};\n     * a.b.c = function(x,y) { }\n     * 
    \n */\n protected void appendExtern(String path, Node functionToExport) {\n List pathPrefixes = computePathPrefixes(path);\n\n for (int i = 0; i < pathPrefixes.size(); ++i) {", "answers": [" String pathPrefix = pathPrefixes.get(i);"], "length": 426, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "1c74c8e4-5357-43cb-933e-09730f78d5d8", "reasoning": "Inside the appendExtern method, after computing the list of path prefixes, the code iterates over each prefix. The first operation inside the loop is to retrieve the current prefix from the list, which is done by assigning pathPrefixes.get(i) to a local variable. This matches typical Java loop patterns and fits the surrounding code.", "reasoning_model_answer": "String prefix = pathPrefixes.get(i);", "assistant_with_reasoning": "\nInside the appendExtern method, after computing the list of path prefixes, the code iterates over each prefix. The first operation inside the loop is to retrieve the current prefix from the list, which is done by assigning pathPrefixes.get(i) to a local variable. This matches typical Java loop patterns and fits the surrounding code.\n\nString prefix = pathPrefixes.get(i);", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.342, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 3703, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "String prefix = pathPrefixes.get(i);", "score": 0.86, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "// Copyright (c) Corporation for National Research Initiatives\n\n// This class implements the standard Python sys module.\n\npackage org.python.core;\n\nimport java.io.File;\nimport java.io.FileInputStream;\nimport java.io.FilterInputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.net.URL;\nimport java.net.URLDecoder;\nimport java.security.AccessControlException;\nimport java.util.Enumeration;\nimport java.util.Hashtable;\nimport java.util.Properties;\nimport java.util.StringTokenizer;\nimport java.util.jar.JarEntry;\nimport java.util.jar.JarFile;\n\nimport org.python.core.adapter.ClassicPyObjectAdapter;\nimport org.python.core.adapter.ExtensiblePyObjectAdapter;\nimport org.python.modules.Setup;\n\n/**\n * The \"sys\" module.\n */\n\n// xxx this should really be a module!\nfinal public class PySystemState extends PyObject {\n public static final String JYTHON_JAR = \"jython.jar\";\n\n private static final String JAR_URL_PREFIX = \"jar:file:\";\n private static final String JAR_SEPARATOR = \"!\";\n\n private static final String PYTHON_CACHEDIR = \"python.cachedir\";\n protected static final String PYTHON_CACHEDIR_SKIP = \"python.cachedir.skip\";\n protected static final String CACHEDIR_DEFAULT_NAME = \"cachedir\";\n\n /**\n * The current version of Jython.\n *

    \n * Usually updated by hand.
    \n * Replaced by ant when doing a snapshot build.\n *

    \n * This also applies for the PY_* integer values below\n */\n public static String version = \"2.2.1\";\n\n private static int PY_MAJOR_VERSION = 2;\n private static int PY_MINOR_VERSION = 2;\n private static int PY_MICRO_VERSION = 1;\n private static int PY_RELEASE_LEVEL = 0x0F;\n private static int PY_RELEASE_SERIAL = 0;\n\n public static int hexversion = ((PY_MAJOR_VERSION << 24) | (PY_MINOR_VERSION << 16) | (PY_MICRO_VERSION << 8)\n | (PY_RELEASE_LEVEL << 4) | (PY_RELEASE_SERIAL << 0));\n\n public static PyTuple version_info;\n\n public static int maxunicode = 65535;\n\n /**\n * The copyright notice for this release.\n */\n // TBD: should we use \\u00a9 Unicode c-inside-circle?\n public static String copyright = \"Copyright (c) 2000-2007, Jython Developers\\n\" + \"All rights reserved.\\n\\n\" +\n\n \"Copyright (c) 2000 BeOpen.com.\\n\" + \"All Rights Reserved.\\n\\n\" +\n\n \"Copyright (c) 2000 The Apache Software Foundation. All rights\\n\" + \"reserved.\\n\\n\" +\n\n \"Copyright (c) 1995-2000 Corporation for National Research \" + \"Initiatives.\\n\" + \"All Rights Reserved.\\n\\n\" +\n\n \"Copyright (c) 1991-1995 Stichting Mathematisch Centrum, \" + \"Amsterdam.\\n\" + \"All Rights Reserved.\\n\\n\";\n\n /**\n * The arguments passed to this program on the command line.\n */\n public PyList argv = new PyList();\n\n /**\n * Exit a Python program with the given status.\n *\n * @param status the value to exit with\n * @exception Py.SystemExit always throws this exception.\n * When caught at top level the program will exit.\n */\n public static void exit(PyObject status) {\n throw new PyException(Py.SystemExit, status);\n }\n\n /**\n * Exit a Python program with the status 0.\n */\n public static void exit() {\n exit(Py.None);\n }\n\n public PyObject modules;\n public PyList path;\n public static PyObject builtins;\n\n public PyList meta_path;\n public PyList path_hooks;\n public PyObject path_importer_cache;\n\n public static String platform = \"java\";\n public static String byteorder = \"big\";\n\n public PyObject ps1 = new PyString(\">>> \");\n public PyObject ps2 = new PyString(\"... \");\n\n public static int maxint = Integer.MAX_VALUE;\n public static int minint = Integer.MIN_VALUE;\n\n public PyObject executable = Py.None;\n\n public static PyList warnoptions;\n\n private ClassLoader classLoader = null;\n\n public ClassLoader getClassLoader() {\n return classLoader;\n }\n\n public void setClassLoader(ClassLoader classLoader) {\n this.classLoader = classLoader;\n }\n\n public static PyTuple exc_info() {\n PyException exc = Py.getThreadState().exception;\n if (exc == null)\n return new PyTuple(new PyObject[] { Py.None, Py.None, Py.None });\n return new PyTuple(new PyObject[] { exc.type, exc.value, exc.traceback });\n }\n\n public static PyFrame _getframe() {\n return _getframe(-1);\n }\n\n public static PyFrame _getframe(int depth) {\n PyFrame f = Py.getFrame();\n\n while (depth > 0 && f != null) {\n f = f.f_back;\n --depth;\n }\n if (f == null)", "answers": [" throw Py.ValueError(\"call stack is not deep enough\");"], "length": 548, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "7afa7679-48cf-4d6c-b254-c47be5ea5118", "reasoning": "The method _getframe traverses the call stack and should raise an error if the requested depth exceeds the stack. In CPython sys._getframe raises ValueError when the frame is null. Jython follows the same pattern, using Py.ValueError to throw a Python exception. Therefore the next line after the null check is the throw statement.", "reasoning_model_answer": "throw Py.ValueError(\"call stack is not deep enough\");", "assistant_with_reasoning": "\nThe method _getframe traverses the call stack and should raise an error if the requested depth exceeds the stack. In CPython sys._getframe raises ValueError when the frame is null. Jython follows the same pattern, using Py.ValueError to throw a Python exception. Therefore the next line after the null check is the throw statement.\n\nthrow Py.ValueError(\"call stack is not deep enough\");", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.228, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 4678, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "throw Py.ValueError(\"call stack is not deep enough\");", "score": 0.9, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License. See License.txt in the project root for\n// license information.\n// \n// Code generated by Microsoft (R) AutoRest Code Generator.\n// Changes may cause incorrect behavior and will be lost if the code is\n// regenerated.\n\nnamespace Fixtures.MirrorSequences\n{\n using Microsoft.Rest;\n using Models;\n\n ///

    \n /// A sample API that uses a petstore as an example to demonstrate\n /// features in the swagger-2.0 specification\n /// \n public partial class SequenceRequestResponseTest : Microsoft.Rest.ServiceClient, ISequenceRequestResponseTest\n {\n /// \n /// The base URI of the service.\n /// \n public System.Uri BaseUri { get; set; }\n\n /// \n /// Gets or sets json serialization settings.\n /// \n public Newtonsoft.Json.JsonSerializerSettings SerializationSettings { get; private set; }\n\n /// \n /// Gets or sets json deserialization settings.\n /// \n public Newtonsoft.Json.JsonSerializerSettings DeserializationSettings { get; private set; }\n\n /// \n /// Initializes a new instance of the SequenceRequestResponseTest class.\n /// \n /// \n /// Optional. The delegating handlers to add to the http client pipeline.\n /// \n public SequenceRequestResponseTest(params System.Net.Http.DelegatingHandler[] handlers) : base(handlers)\n {\n this.Initialize();\n }\n\n /// \n /// Initializes a new instance of the SequenceRequestResponseTest class.\n /// \n /// \n /// Optional. The http client handler used to handle http transport.\n /// \n /// \n /// Optional. The delegating handlers to add to the http client pipeline.\n /// \n public SequenceRequestResponseTest(System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : base(rootHandler, handlers)\n {\n this.Initialize();\n }\n\n /// \n /// Initializes a new instance of the SequenceRequestResponseTest class.\n /// \n /// \n /// Optional. The base URI of the service.\n /// \n /// \n /// Optional. The delegating handlers to add to the http client pipeline.\n /// \n /// \n /// Thrown when a required parameter is null\n /// \n public SequenceRequestResponseTest(System.Uri baseUri, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers)\n {\n if (baseUri == null)\n {\n throw new System.ArgumentNullException(\"baseUri\");\n }\n this.BaseUri = baseUri;\n }\n\n /// \n /// Initializes a new instance of the SequenceRequestResponseTest class.\n /// \n /// \n /// Optional. The base URI of the service.\n /// \n /// \n /// Optional. The http client handler used to handle http transport.\n /// \n /// \n /// Optional. The delegating handlers to add to the http client pipeline.\n /// \n /// \n /// Thrown when a required parameter is null\n /// \n public SequenceRequestResponseTest(System.Uri baseUri, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers)\n {\n if (baseUri == null)\n {\n throw new System.ArgumentNullException(\"baseUri\");\n }\n this.BaseUri = baseUri;\n }\n\n /// \n /// An optional partial-method to perform custom initialization.\n /// \n partial void CustomInitialize();\n /// \n /// Initializes client properties.\n /// \n private void Initialize()\n {\n this.BaseUri = new System.Uri(\"http://petstore.swagger.wordnik.com/api\");\n SerializationSettings = new Newtonsoft.Json.JsonSerializerSettings\n {\n Formatting = Newtonsoft.Json.Formatting.Indented,", "answers": [" DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,"], "length": 459, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "fe0d28bc-fde4-456d-8917-75f18bb1974b", "reasoning": "We are inside the Initialize() method where the SerializationSettings object is being created. The code already set the Formatting property and is continuing the object initializer. AutoRest-generated clients typically set DateFormatHandling next, so the next line should assign DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,", "reasoning_model_answer": "DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,", "assistant_with_reasoning": "\nWe are inside the Initialize() method where the SerializationSettings object is being created. The code already set the Formatting property and is continuing the object initializer. AutoRest-generated clients typically set DateFormatHandling next, so the next line should assign DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,\n\nDateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.438, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 4775, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,", "score": 0.9, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/*\n * Copyright 2015, The Querydsl Team (http://www.querydsl.com/team)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.querydsl.sql;\n\nimport java.lang.reflect.Array;\nimport java.sql.PreparedStatement;\nimport java.sql.ResultSet;\nimport java.sql.SQLException;\nimport java.sql.Types;\nimport java.util.List;\nimport java.util.Map;\n\nimport javax.annotation.Nullable;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.Maps;\nimport com.google.common.primitives.Primitives;\nimport com.querydsl.core.types.Path;\nimport com.querydsl.sql.types.ArrayType;\nimport com.querydsl.sql.types.Null;\nimport com.querydsl.sql.types.Type;\n\n/**\n * Configuration for SQLQuery instances\n *\n * @author tiwe\n *\n */\npublic final class Configuration {\n\n private static final Logger logger = LoggerFactory.getLogger(Configuration.class);\n\n static final Configuration DEFAULT = new Configuration(SQLTemplates.DEFAULT);\n\n private final JDBCTypeMapping jdbcTypeMapping = new JDBCTypeMapping();\n\n private final JavaTypeMapping javaTypeMapping = new JavaTypeMapping();\n\n private final NameMapping nameMapping = new NameMapping();\n\n private final Map> typeToName = Maps.newHashMap();\n\n private SQLTemplates templates;\n\n private SQLExceptionTranslator exceptionTranslator = DefaultSQLExceptionTranslator.DEFAULT;\n\n private final SQLListeners listeners = new SQLListeners();\n\n private boolean hasTableColumnTypes = false;\n\n private boolean useLiterals = false;\n\n /**\n * Create a new Configuration instance\n *\n * @param templates templates for SQL serialization\n */\n @SuppressWarnings(\"unchecked\")\n public Configuration(SQLTemplates templates) {\n this.templates = templates;\n for (Type customType : templates.getCustomTypes()) {\n javaTypeMapping.register(customType);\n }\n for (Map.Entry entry : templates.getTableOverrides().entrySet()) {\n registerTableOverride(entry.getKey(), entry.getValue());\n }\n\n if (templates.isArraysSupported()) {\n // register array types\n List> classes = ImmutableList.>of(String.class, Long.class, Integer.class, Short.class,\n Byte.class, Boolean.class, java.sql.Date.class, java.sql.Timestamp.class,\n java.sql.Time.class, Double.class, Float.class);\n for (Class cl : classes) {\n int code = jdbcTypeMapping.get(cl);\n String name = templates.getTypeNameForCode(code);\n Class arrType = Array.newInstance(cl, 0).getClass();\n javaTypeMapping.register(new ArrayType(arrType, name));\n if (Primitives.isWrapperType(cl) && !cl.equals(Byte.class)) {\n cl = Primitives.unwrap(cl);\n arrType = Array.newInstance(cl, 0).getClass();\n javaTypeMapping.register(new ArrayType(arrType, name));\n }\n }\n }\n\n }\n\n /**\n * Get the literal representation of the given constant\n *\n * @param o object\n * @return literal representation\n */\n @SuppressWarnings(\"unchecked\")\n public String asLiteral(Object o) {\n if (o == null || o instanceof Null) {\n return \"null\";\n } else {\n Type type = javaTypeMapping.getType(o.getClass());\n if (type != null) {\n return templates.serialize(type.getLiteral(o), type.getSQLTypes()[0]);\n } else {\n throw new IllegalArgumentException(\"Unsupported literal type \" + o.getClass().getName());\n }\n }\n }\n\n public SQLTemplates getTemplates() {\n return templates;\n }\n\n /**\n * Get the java type for the given jdbc type, table name and column name\n *\n * @param sqlType JDBC type\n * @param typeName JDBC type name\n * @param size size\n * @param digits digits\n * @param tableName table name\n * @param columnName column name\n * @return Java type\n */", "answers": [" public Class getJavaType(int sqlType, String typeName, int size, int digits, String tableName, String columnName) {"], "length": 450, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "1adb9088-abda-4bd2-b44b-2140d4e2ac3b", "reasoning": "The comment describes a method that returns the Java type for a given JDBC type and column metadata. In the Configuration class, the next line after the Javadoc is the method signature implementing this description. The method returns a Class and takes parameters sqlType, typeName, size, digits, tableName, and columnName. Therefore the next line is the method declaration with its opening brace.", "reasoning_model_answer": "public Class getJavaType(int sqlType, String typeName, int size, int digits, String tableName, String columnName) {", "assistant_with_reasoning": "\nThe comment describes a method that returns the Java type for a given JDBC type and column metadata. In the Configuration class, the next line after the Javadoc is the method signature implementing this description. The method returns a Class and takes parameters sqlType, typeName, size, digits, tableName, and columnName. Therefore the next line is the method declaration with its opening brace.\n\npublic Class getJavaType(int sqlType, String typeName, int size, int digits, String tableName, String columnName) {", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.178, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 4752, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "public Class getJavaType(int sqlType, String typeName, int size, int digits, String tableName, String columnName) {", "score": 0.98, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "\"\"\"Test the condition helper.\"\"\"\nfrom logging import WARNING\nfrom unittest.mock import patch\n\nimport pytest\n\nfrom homeassistant.exceptions import ConditionError, HomeAssistantError\nfrom homeassistant.helpers import condition\nfrom homeassistant.helpers.template import Template\nfrom homeassistant.setup import async_setup_component\nfrom homeassistant.util import dt\n\n\nasync def test_invalid_condition(hass):\n \"\"\"Test if invalid condition raises.\"\"\"\n with pytest.raises(HomeAssistantError):\n await condition.async_from_config(\n hass,\n {\n \"condition\": \"invalid\",\n \"conditions\": [\n {\n \"condition\": \"state\",\n \"entity_id\": \"sensor.temperature\",\n \"state\": \"100\",\n },\n ],\n },\n )\n\n\nasync def test_and_condition(hass):\n \"\"\"Test the 'and' condition.\"\"\"\n test = await condition.async_from_config(\n hass,\n {\n \"condition\": \"and\",\n \"conditions\": [\n {\n \"condition\": \"state\",\n \"entity_id\": \"sensor.temperature\",\n \"state\": \"100\",\n },\n {\n \"condition\": \"numeric_state\",\n \"entity_id\": \"sensor.temperature\",\n \"below\": 110,\n },\n ],\n },\n )\n\n hass.states.async_set(\"sensor.temperature\", 120)\n assert not test(hass)\n\n hass.states.async_set(\"sensor.temperature\", 105)\n assert not test(hass)\n\n hass.states.async_set(\"sensor.temperature\", 100)\n assert test(hass)\n\n\nasync def test_and_condition_with_template(hass):\n \"\"\"Test the 'and' condition.\"\"\"\n test = await condition.async_from_config(\n hass,\n {\n \"condition\": \"and\",\n \"conditions\": [\n {\n \"condition\": \"template\",\n \"value_template\": '{{ states.sensor.temperature.state == \"100\" }}',\n },\n {\n \"condition\": \"numeric_state\",\n \"entity_id\": \"sensor.temperature\",\n \"below\": 110,\n },\n ],\n },\n )\n\n hass.states.async_set(\"sensor.temperature\", 120)\n assert not test(hass)\n\n hass.states.async_set(\"sensor.temperature\", 105)\n assert not test(hass)\n\n hass.states.async_set(\"sensor.temperature\", 100)\n assert test(hass)\n\n\nasync def test_or_condition(hass):\n \"\"\"Test the 'or' condition.\"\"\"\n test = await condition.async_from_config(\n hass,\n {\n \"condition\": \"or\",\n \"conditions\": [\n {\n \"condition\": \"state\",\n \"entity_id\": \"sensor.temperature\",\n \"state\": \"100\",\n },\n {\n \"condition\": \"numeric_state\",\n \"entity_id\": \"sensor.temperature\",\n \"below\": 110,\n },\n ],\n },\n )\n\n hass.states.async_set(\"sensor.temperature\", 120)\n assert not test(hass)\n\n hass.states.async_set(\"sensor.temperature\", 105)\n assert test(hass)\n\n hass.states.async_set(\"sensor.temperature\", 100)\n assert test(hass)\n\n\nasync def test_or_condition_with_template(hass):\n \"\"\"Test the 'or' condition.\"\"\"\n test = await condition.async_from_config(\n hass,\n {\n \"condition\": \"or\",\n \"conditions\": [\n {'{{ states.sensor.temperature.state == \"100\" }}'},\n {\n \"condition\": \"numeric_state\",\n \"entity_id\": \"sensor.temperature\",\n \"below\": 110,\n },\n ],\n },\n )\n\n hass.states.async_set(\"sensor.temperature\", 120)\n assert not test(hass)\n\n hass.states.async_set(\"sensor.temperature\", 105)\n assert test(hass)\n\n hass.states.async_set(\"sensor.temperature\", 100)\n assert test(hass)\n\n\nasync def test_not_condition(hass):\n \"\"\"Test the 'not' condition.\"\"\"\n test = await condition.async_from_config(\n hass,\n {\n \"condition\": \"not\",\n \"conditions\": [\n {\n \"condition\": \"state\",\n \"entity_id\": \"sensor.temperature\",\n \"state\": \"100\",\n },\n {\n \"condition\": \"numeric_state\",\n \"entity_id\": \"sensor.temperature\",\n \"below\": 50,\n },\n ],\n },\n )\n\n hass.states.async_set(\"sensor.temperature\", 101)\n assert test(hass)\n\n hass.states.async_set(\"sensor.temperature\", 50)\n assert test(hass)\n\n hass.states.async_set(\"sensor.temperature\", 49)\n assert not test(hass)\n\n hass.states.async_set(\"sensor.temperature\", 100)\n assert not test(hass)\n\n\nasync def test_not_condition_with_template(hass):\n \"\"\"Test the 'or' condition.\"\"\"\n test = await condition.async_from_config(\n hass,\n {\n \"condition\": \"not\",\n \"conditions\": [\n {\n \"condition\": \"template\",\n \"value_template\": '{{ states.sensor.temperature.state == \"100\" }}',\n },\n {\n \"condition\": \"numeric_state\",\n \"entity_id\": \"sensor.temperature\",\n \"below\": 50,\n },\n ],\n },\n )\n\n hass.states.async_set(\"sensor.temperature\", 101)\n assert test(hass)\n\n hass.states.async_set(\"sensor.temperature\", 50)\n assert test(hass)\n\n hass.states.async_set(\"sensor.temperature\", 49)\n assert not test(hass)\n\n hass.states.async_set(\"sensor.temperature\", 100)\n assert not test(hass)\n\n\nasync def test_time_window(hass):\n \"\"\"Test time condition windows.\"\"\"\n sixam = dt.parse_time(\"06:00:00\")\n sixpm = dt.parse_time(\"18:00:00\")\n\n with patch(\n \"homeassistant.helpers.condition.dt_util.now\",\n return_value=dt.now().replace(hour=3),\n ):\n assert not condition.time(hass, after=sixam, before=sixpm)\n assert condition.time(hass, after=sixpm, before=sixam)\n\n with patch(\n \"homeassistant.helpers.condition.dt_util.now\",\n return_value=dt.now().replace(hour=9),\n ):\n assert condition.time(hass, after=sixam, before=sixpm)\n assert not condition.time(hass, after=sixpm, before=sixam)\n\n with patch(\n \"homeassistant.helpers.condition.dt_util.now\",\n return_value=dt.now().replace(hour=15),\n ):\n assert condition.time(hass, after=sixam, before=sixpm)\n assert not condition.time(hass, after=sixpm, before=sixam)\n\n with patch(\n \"homeassistant.helpers.condition.dt_util.now\",\n return_value=dt.now().replace(hour=21),\n ):\n assert not condition.time(hass, after=sixam, before=sixpm)\n assert condition.time(hass, after=sixpm, before=sixam)\n\n\nasync def test_time_using_input_datetime(hass):\n \"\"\"Test time conditions using input_datetime entities.\"\"\"\n await async_setup_component(\n hass,\n \"input_datetime\",\n {\n \"input_datetime\": {\n \"am\": {\"has_date\": True, \"has_time\": True},", "answers": [" \"pm\": {\"has_date\": True, \"has_time\": True},"], "length": 466, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "cc399b05-b702-406f-8bd6-1cb13af345b7", "reasoning": "The async_setup_component call is opening a nested dictionary for input_datetime entities. After defining the \"am\" entity, the next logical entry is the \"pm\" entity with the same structure, before closing the dictionaries and the function call.", "reasoning_model_answer": "\"pm\": {\"has_date\": True, \"has_time\": True},", "assistant_with_reasoning": "\nThe async_setup_component call is opening a nested dictionary for input_datetime entities. After defining the \"am\" entity, the next logical entry is the \"pm\" entity with the same structure, before closing the dictionaries and the function call.\n\n\"pm\": {\"has_date\": True, \"has_time\": True},", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.795, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 7411, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "\"pm\": {\"has_date\": True, \"has_time\": True},", "score": 0.84, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "# Copyright (c) 2012 The Chromium Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style license that can be\n# found in the LICENSE file.\n\nimport os.path\n\nfrom json_parse import OrderedDict\nfrom memoize import memoize\n\nclass ParseException(Exception):\n \"\"\"Thrown when data in the model is invalid.\n \"\"\"\n def __init__(self, parent, message):\n hierarchy = _GetModelHierarchy(parent)\n hierarchy.append(message)\n Exception.__init__(\n self, 'Model parse exception at:\\n' + '\\n'.join(hierarchy))\n\nclass Model(object):\n \"\"\"Model of all namespaces that comprise an API.\n\n Properties:\n - |namespaces| a map of a namespace name to its model.Namespace\n \"\"\"\n def __init__(self):\n self.namespaces = {}\n\n def AddNamespace(self, json, source_file, include_compiler_options=False):\n \"\"\"Add a namespace's json to the model and returns the namespace.\n \"\"\"\n namespace = Namespace(json,\n source_file,\n include_compiler_options=include_compiler_options)\n self.namespaces[namespace.name] = namespace\n return namespace\n\nclass Namespace(object):\n \"\"\"An API namespace.\n\n Properties:\n - |name| the name of the namespace\n - |description| the description of the namespace\n - |unix_name| the unix_name of the namespace\n - |source_file| the file that contained the namespace definition\n - |source_file_dir| the directory component of |source_file|\n - |source_file_filename| the filename component of |source_file|\n - |platforms| if not None, the list of platforms that the namespace is\n available to\n - |types| a map of type names to their model.Type\n - |functions| a map of function names to their model.Function\n - |events| a map of event names to their model.Function\n - |properties| a map of property names to their model.Property\n - |compiler_options| the compiler_options dict, only not empty if\n |include_compiler_options| is True\n \"\"\"\n def __init__(self, json, source_file, include_compiler_options=False):\n self.name = json['namespace']\n if 'description' not in json:\n # TODO(kalman): Go back to throwing an error here.\n print('%s must have a \"description\" field. This will appear '\n 'on the API summary page.' % self.name)\n json['description'] = ''\n self.description = json['description']\n self.unix_name = UnixName(self.name)\n self.source_file = source_file\n self.source_file_dir, self.source_file_filename = os.path.split(source_file)\n self.parent = None\n self.platforms = _GetPlatforms(json)\n toplevel_origin = Origin(from_client=True, from_json=True)\n self.types = _GetTypes(self, json, self, toplevel_origin)\n self.functions = _GetFunctions(self, json, self)\n self.events = _GetEvents(self, json, self)\n self.properties = _GetProperties(self, json, self, toplevel_origin)\n self.compiler_options = (json.get('compiler_options', {})\n if include_compiler_options else {})\n\nclass Origin(object):\n \"\"\"Stores the possible origin of model object as a pair of bools. These are:\n\n |from_client| indicating that instances can originate from users of\n generated code (for example, function results), or\n |from_json| indicating that instances can originate from the JSON (for\n example, function parameters)\n\n It is possible for model objects to originate from both the client and json,\n for example Types defined in the top-level schema, in which case both\n |from_client| and |from_json| would be True.\n \"\"\"\n def __init__(self, from_client=False, from_json=False):\n if not from_client and not from_json:\n raise ValueError('One of from_client or from_json must be true')", "answers": [" self.from_client = from_client"], "length": 438, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "9fe3f56e-1098-436c-ab70-180bd4f7f358", "reasoning": "The Origin class's __init__ validates that at least one of the flags is true, then needs to store the flag values on the instance. After the raise statement, the next logical line assigns the from_client flag to an instance attribute.", "reasoning_model_answer": "self.from_client = from_client", "assistant_with_reasoning": "\nThe Origin class's __init__ validates that at least one of the flags is true, then needs to store the flag values on the instance. After the raise statement, the next logical line assigns the from_client flag to an instance attribute.\n\nself.from_client = from_client", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 1.72, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 3843, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "self.from_client = from_client", "score": 0.94, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "import os\nimport re\nimport shutil\n\nimport pytest\nfrom click.testing import CliRunner\nfrom freezegun import freeze_time\n\nfrom great_expectations import DataContext\nfrom great_expectations.cli.v012 import cli\nfrom great_expectations.data_context.util import file_relative_path\nfrom great_expectations.util import gen_directory_tree_str\nfrom tests.cli.v012.test_cli import yaml\nfrom tests.cli.v012.utils import assert_no_logging_messages_or_tracebacks\n\ntry:\n from unittest import mock\nexcept ImportError:\n from unittest import mock\n\n\n@pytest.mark.filterwarnings(\n \"ignore:DataAsset.remove_expectations*:DeprecationWarning:great_expectations.data_asset\"\n)\n@freeze_time(\"09/26/2019 13:42:41\")\n@mock.patch(\"webbrowser.open\", return_value=True, side_effect=None)\n@mock.patch(\n \"great_expectations.core.usage_statistics.usage_statistics.UsageStatisticsHandler.emit\"\n)\ndef test_cli_init_on_new_project(\n mock_emit, mock_webbrowser, caplog, tmp_path_factory, monkeypatch\n):\n monkeypatch.delenv(\n \"GE_USAGE_STATS\", raising=False\n ) # Undo the project-wide test default\n project_dir = str(tmp_path_factory.mktemp(\"test_cli_init_diff\"))\n os.makedirs(os.path.join(project_dir, \"data\"))\n data_folder_path = os.path.join(project_dir, \"data\")\n data_path = os.path.join(project_dir, \"data\", \"Titanic.csv\")\n fixture_path = file_relative_path(__file__, \"../../test_sets/Titanic.csv\")\n shutil.copy(fixture_path, data_path)\n\n runner = CliRunner(mix_stderr=False)\n result = runner.invoke(\n cli,\n [\"init\", \"-d\", project_dir],\n input=f\"\\n\\n1\\n1\\n{data_folder_path}\\n\\n\\n\\n2\\n{data_path}\\n\\n\\n\\n\",\n catch_exceptions=False,\n )\n stdout = result.output\n assert mock_webbrowser.call_count == 1\n assert (\n \"{}/great_expectations/uncommitted/data_docs/local_site/validations/Titanic/warning/\".format(\n project_dir\n )\n in mock_webbrowser.call_args[0][0]\n )\n\n assert len(stdout) < 6000, \"CLI output is unreasonably long.\"\n assert \"Always know what to expect from your data\" in stdout\n assert \"What data would you like Great Expectations to connect to\" in stdout\n assert \"What are you processing your files with\" in stdout\n assert (\n \"Enter the path of a data file (relative or absolute, s3a:// and gs:// paths are ok too)\"\n in stdout\n )\n assert \"Name the new Expectation Suite [Titanic.warning]\" in stdout\n assert (\n \"Great Expectations will choose a couple of columns and generate expectations about them\"\n in stdout\n )\n assert \"Generating example Expectation Suite...\" in stdout\n assert \"Building\" in stdout\n assert \"Data Docs\" in stdout\n assert \"Done generating example Expectation Suite\u001b\" in stdout\n assert \"Great Expectations is now set up\" in stdout\n\n assert os.path.isdir(os.path.join(project_dir, \"great_expectations\"))\n config_path = os.path.join(project_dir, \"great_expectations/great_expectations.yml\")\n assert os.path.isfile(config_path)\n\n config = yaml.load(open(config_path))\n data_source_class = config[\"datasources\"][\"data__dir\"][\"data_asset_type\"][\n \"class_name\"\n ]\n assert data_source_class == \"PandasDataset\"\n\n # Profilers are v014+ specific\n os.rmdir(os.path.join(project_dir, \"great_expectations\", \"profilers\"))\n\n obs_tree = gen_directory_tree_str(os.path.join(project_dir, \"great_expectations\"))\n\n # Instead of monkey patching guids, just regex out the guids\n guid_safe_obs_tree = re.sub(\n r\"[a-z0-9]{32}(?=\\.(json|html))\", \"foobarbazguid\", obs_tree\n )\n # print(guid_safe_obs_tree)\n assert (\n guid_safe_obs_tree\n == \"\"\"great_expectations/\n .gitignore\n great_expectations.yml\n checkpoints/\n expectations/\n .ge_store_backend_id\n Titanic/\n warning.json\n plugins/\n custom_data_docs/\n renderers/\n styles/\n data_docs_custom_styles.css\n views/\n uncommitted/\n config_variables.yml\n data_docs/\n local_site/\n index.html\n expectations/\n Titanic/\n warning.html\n static/\n fonts/\n HKGrotesk/\n HKGrotesk-Bold.otf\n HKGrotesk-BoldItalic.otf\n HKGrotesk-Italic.otf\n HKGrotesk-Light.otf\n HKGrotesk-LightItalic.otf\n HKGrotesk-Medium.otf\n HKGrotesk-MediumItalic.otf\n HKGrotesk-Regular.otf\n HKGrotesk-SemiBold.otf\n HKGrotesk-SemiBoldItalic.otf\n images/\n favicon.ico\n glossary_scroller.gif\n iterative-dev-loop.png\n logo-long-vector.svg\n logo-long.png\n short-logo-vector.svg\n short-logo.png\n validation_failed_unexpected_values.gif\n styles/\n data_docs_custom_styles_template.css\n data_docs_default_styles.css\n validations/\n Titanic/\n warning/\n 20190926T134241.000000Z/\n 20190926T134241.000000Z/\n foobarbazguid.html\n validations/\n .ge_store_backend_id\n Titanic/\n warning/\n 20190926T134241.000000Z/\n 20190926T134241.000000Z/\n foobarbazguid.json\n\"\"\"\n )\n\n assert mock_emit.call_count == 9\n assert mock_emit.call_args_list[1] == mock.call(\n {\n \"event_payload\": {\"api_version\": \"v2\"},\n \"event\": \"cli.init.create\",\n \"success\": True,\n }\n )\n\n assert_no_logging_messages_or_tracebacks(caplog, result)\n\n\n@pytest.mark.filterwarnings(\n \"ignore:DataAsset.remove_expectations*:DeprecationWarning:great_expectations.data_asset\"\n)\n@mock.patch(\"webbrowser.open\", return_value=True, side_effect=None)\ndef test_init_on_existing_project_with_no_datasources_should_continue_init_flow_and_add_one(\n mock_webbrowser,\n capsys,\n caplog,\n initialized_project,\n):\n project_dir = initialized_project\n ge_dir = os.path.join(project_dir, DataContext.GE_DIR)\n\n # mangle the project to remove all traces of a suite and validations\n _remove_all_datasources(ge_dir)\n os.remove(os.path.join(ge_dir, \"expectations\", \"Titanic\", \"warning.json\"))\n uncommitted_dir = os.path.join(ge_dir, \"uncommitted\")\n validations_dir = os.path.join(ge_dir, uncommitted_dir, \"validations\")\n shutil.rmtree(validations_dir)\n os.mkdir(validations_dir)\n shutil.rmtree(os.path.join(uncommitted_dir, \"data_docs\", \"local_site\"))\n context = DataContext(ge_dir)\n assert not context.list_expectation_suites()\n\n data_folder_path = os.path.join(project_dir, \"data\")\n csv_path = os.path.join(project_dir, \"data\", \"Titanic.csv\")\n runner = CliRunner(mix_stderr=False)\n with pytest.warns(\n UserWarning, match=\"Warning. An existing `great_expectations.yml` was found\"\n ):\n result = runner.invoke(\n cli,\n [\"init\", \"-d\", project_dir],\n input=\"\\n1\\n1\\n{}\\n\\n\\n\\n2\\n{}\\nmy_suite\\n\\n\\n\\n\\n\".format(\n data_folder_path, csv_path\n ),\n catch_exceptions=False,\n )\n assert mock_webbrowser.call_count == 1\n assert (\n \"{}/great_expectations/uncommitted/data_docs/local_site/validations/my_suite/\".format(\n project_dir\n )", "answers": [" in mock_webbrowser.call_args[0][0]"], "length": 499, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "8adf5f84-2687-4231-822e-875e651c7616", "reasoning": "The test is checking that the URL opened by the webbrowser contains the path to the generated data docs for the new suite 'my_suite'. The previous test used an assert with the pattern: assert (\"{}/...\".format(project_dir) in mock_webbrowser.call_args[0][0]). The current code mirrors that, ending the assert statement after the formatted string, so the next line should complete the assertion by checking membership in mock_webbrowser.call_args[0][0].", "reasoning_model_answer": "in mock_webbrowser.call_args[0][0]", "assistant_with_reasoning": "\nThe test is checking that the URL opened by the webbrowser contains the path to the generated data docs for the new suite 'my_suite'. The previous test used an assert with the pattern: assert (\"{}/...\".format(project_dir) in mock_webbrowser.call_args[0][0]). The current code mirrors that, ending the assert statement after the formatted string, so the next line should complete the assertion by checking membership in mock_webbrowser.call_args[0][0].\n\nin mock_webbrowser.call_args[0][0]", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.258, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 7964, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "in mock_webbrowser.call_args[0][0]", "score": 0.89, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "import numpy as np\nimport theano\nimport theano.tensor as T\nfrom . import model\n\n\"\"\" optimizer.py (module)\n\n The optimizer module contains the Optimizer class that is used\n to configure low-rank MNE models, initialize the solver, and \n minimize the (possibly constrained and regularized) objective\n function.\n\n\"\"\"\n\nclass Optimizer(object):\n \"\"\" Optimizer (class)\n\n The Optimizer class is the interface used for constructing\n and optimizing low-rank MNE models. This class is built\n flexibly to allow for easy customization.\n\n \"\"\"\n\n def __init__(self, resp, feat, rank, cetype=None, citype=None, rtype=None, solver=None, datasets=None, **kwargs):\n \"\"\"Initialize Optimizer class instantiation.\n\n [inputs] (resp, feat, rank, cetype=None, citype=None,\n rtype=None, solver=None, datasets=None, **kwargs)\n resp: numpy array of the output labels with shape\n (nsamp,) where nsamp is the number of data\n samples. Each element of resp must be in the range\n [0, 1].\n feat: numpy array of the input features with shape\n (nsamp, ndim) where ndim is the number of features.\n rank: positive integer that sets the number of columns\n of the matrices U and V(that both have shape (ndim,\n rank)).\n cetype: (optional) list of strings that tell the class\n which equality constraints, if any, are being\n used. Can set to None if no equality constraints are\n used. Available equality constraints:\n - \"UV-linear-insert\": these sets each U[:,k] =\n csigns[k]*V[:,k] for all k in range(rank) and\n directly imposes this constraint by substitution.\n Note that csigns is a numpy array of binary\n integers in {-1, 1} that sets the sign\n relationship between each component of U and V.\n csigns may be set using **kwargs. - \"UV-linear\":\n these are the same constraints as UV-linear-insert\n but instead of direct substitution the constraints\n are imposed using the method Lagrange\n multipliers. csigns must also be set through\n **kwargs. - \"UV-quadratic\": these constraints are\n the equality constraints defined by the upper\n triangle of np.dot(U, U.T) == np.dot(V, V.T). -\n \"UV-bilinear\": these constraints are the equality\n constraints defined by the upper triangle (with\n diagonal excluded) of np.dot(U, V.T) == np.dot(V,\n U.T).\n citype: (optional) list of strings that tell the class\n which equality constraints, if any, are being\n used. Can set to None if no equality constraints are\n used. No inequality constraints are defined at this\n time.\n rtype: (optional) list of strings that tell the class\n which regularization penalties, if any, should be\n added to the objective function. Can set to None if\n no penalty functions are applied. Available penalty\n functions:\n - \"nuclear-norm\": the nuclear-norm regularizes over\n the Frobenius-norms of U and V and promotes\n sparsity of the eigenvalue spectrum of J =\n np.dot(U, V.T).\n solver: (optional) must be set and initialized (using\n class function init_solver) before beginning the\n optimization. It is optional to set here, however.\n datasets: (optional) is a dict with keys \"trainset\",\n \"cvset\", \"testset\" with values corresponding to\n Boolean indices for those samples that belong to\n each the training set, cross-validation set, and\n test set, respectively. If datasets is set to None,\n it is assumed that all samples belong to the\n training set and the other subsets are\n empty. Missing fields are assumed to be empty as\n well.\n\n \"\"\"\n\n # initialize class members to standard arguments\n self.rank = rank\n self.cetype = cetype", "answers": [" self.citype = citype"], "length": 517, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "d96c4819-6c34-4f49-9820-c657d9dc00e1", "reasoning": "The __init__ method is initializing instance attributes from its arguments. It has already assigned self.rank and self.cetype. The next logical attribute to set is self.citype, matching the citype argument, following the pattern of assigning each parameter to a corresponding member variable.", "reasoning_model_answer": "self.citype = citype", "assistant_with_reasoning": "\nThe __init__ method is initializing instance attributes from its arguments. It has already assigned self.rank and self.cetype. The next logical attribute to set is self.citype, matching the citype argument, following the pattern of assigning each parameter to a corresponding member variable.\n\nself.citype = citype", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 2.206, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 4642, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "self.citype = citype", "score": 0.83, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "// Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.\npackage com.intellij.codeInspection.ex;\n\nimport com.intellij.ToolExtensionPoints;\nimport com.intellij.codeInsight.AnnotationUtil;\nimport com.intellij.codeInsight.daemon.DaemonCodeAnalyzer;\nimport com.intellij.codeInsight.daemon.QuickFixBundle;\nimport com.intellij.codeInsight.intention.IntentionAction;\nimport com.intellij.codeInspection.reference.*;\nimport com.intellij.openapi.application.ApplicationManager;\nimport com.intellij.openapi.components.PersistentStateComponent;\nimport com.intellij.openapi.components.ServiceManager;\nimport com.intellij.openapi.components.State;\nimport com.intellij.openapi.editor.Editor;\nimport com.intellij.openapi.extensions.ExtensionPoint;\nimport com.intellij.openapi.extensions.ExtensionPointListener;\nimport com.intellij.openapi.extensions.Extensions;\nimport com.intellij.openapi.extensions.PluginDescriptor;\nimport com.intellij.openapi.extensions.impl.ExtensionPointImpl;\nimport com.intellij.openapi.project.Project;\nimport com.intellij.openapi.util.Comparing;\nimport com.intellij.openapi.util.JDOMExternalizableStringList;\nimport com.intellij.profile.codeInspection.ProjectInspectionProfileManager;\nimport com.intellij.psi.*;\nimport com.intellij.util.IncorrectOperationException;\nimport com.intellij.util.containers.ContainerUtil;\nimport com.intellij.util.ui.UIUtil;\nimport com.intellij.util.xmlb.SkipDefaultsSerializationFilter;\nimport com.intellij.util.xmlb.XmlSerializer;\nimport com.intellij.util.xmlb.annotations.Attribute;\nimport com.intellij.util.xmlb.annotations.Tag;\nimport org.jdom.Element;\nimport org.jetbrains.annotations.NonNls;\nimport org.jetbrains.annotations.NotNull;\nimport org.jetbrains.annotations.Nullable;\n\nimport java.util.*;\nimport java.util.regex.Pattern;\nimport java.util.regex.PatternSyntaxException;\n\n@State(name = \"EntryPointsManager\")\npublic abstract class EntryPointsManagerBase extends EntryPointsManager implements PersistentStateComponent {\n @NonNls private static final String[] STANDARD_ANNOS = {\n \"javax.ws.rs.*\",\n };\n\n // null means uninitialized\n private volatile List ADDITIONAL_ANNOS;\n\n public Collection getAdditionalAnnotations() {\n List annos = ADDITIONAL_ANNOS;\n if (annos == null) {\n annos = new ArrayList<>();\n Collections.addAll(annos, STANDARD_ANNOS);\n final EntryPoint[] extensions = Extensions.getExtensions(ToolExtensionPoints.DEAD_CODE_TOOL, null);\n for (EntryPoint extension : extensions) {\n final String[] ignoredAnnotations = extension.getIgnoreAnnotations();\n if (ignoredAnnotations != null) {\n ContainerUtil.addAll(annos, ignoredAnnotations);\n }\n }\n ADDITIONAL_ANNOS = annos = Collections.unmodifiableList(annos);\n }\n return annos;\n }\n public JDOMExternalizableStringList ADDITIONAL_ANNOTATIONS = new JDOMExternalizableStringList();\n protected List myWriteAnnotations = new ArrayList<>();\n private final Map myPersistentEntryPoints;\n private final LinkedHashSet myPatterns = new LinkedHashSet<>();\n private final Set myTemporaryEntryPoints;\n private static final String VERSION = \"2.0\";\n @NonNls private static final String VERSION_ATTR = \"version\";\n @NonNls private static final String ENTRY_POINT_ATTR = \"entry_point\";\n private boolean myAddNonJavaEntries = true;\n private boolean myResolved;\n protected final Project myProject;\n private long myLastModificationCount = -1;\n\n public EntryPointsManagerBase(@NotNull Project project) {\n myProject = project;\n myTemporaryEntryPoints = new HashSet<>();\n myPersistentEntryPoints = new LinkedHashMap<>(); // To keep the order between readExternal to writeExternal\n final ExtensionPoint point = Extensions.getRootArea().getExtensionPoint(ToolExtensionPoints.DEAD_CODE_TOOL);\n ((ExtensionPointImpl)point).addExtensionPointListener(new ExtensionPointListener() {\n @Override\n public void extensionAdded(@NotNull EntryPoint extension, @Nullable PluginDescriptor pluginDescriptor) {\n extensionRemoved(extension, pluginDescriptor);\n }\n\n @Override\n public void extensionRemoved(@NotNull EntryPoint extension, @Nullable PluginDescriptor pluginDescriptor) {\n if (ADDITIONAL_ANNOS != null) {\n ADDITIONAL_ANNOS = null;\n UIUtil.invokeLaterIfNeeded(() -> {\n if (!ApplicationManager.getApplication().isDisposed()) {\n ProjectInspectionProfileManager.getInstance(project).fireProfileChanged();\n }\n });\n }\n // annotations changed\n DaemonCodeAnalyzer.getInstance(myProject).restart();\n }\n }, false, this);\n }\n\n public static EntryPointsManagerBase getInstance(Project project) {\n return (EntryPointsManagerBase)ServiceManager.getService(project, EntryPointsManager.class);\n }\n\n @Override\n @SuppressWarnings({\"HardCodedStringLiteral\"})\n public void loadState(Element element) {\n Element entryPointsElement = element.getChild(\"entry_points\");\n if (entryPointsElement != null) {\n final String version = entryPointsElement.getAttributeValue(VERSION_ATTR);\n if (!Comparing.strEqual(version, VERSION)) {\n convert(entryPointsElement, myPersistentEntryPoints);\n }\n else {\n List content = entryPointsElement.getChildren();\n for (final Object aContent : content) {\n Element entryElement = (Element)aContent;\n if (ENTRY_POINT_ATTR.equals(entryElement.getName())) {\n SmartRefElementPointerImpl entryPoint = new SmartRefElementPointerImpl(entryElement);\n myPersistentEntryPoints.put(entryPoint.getFQName(), entryPoint);\n }\n }\n }\n }\n try {\n ADDITIONAL_ANNOTATIONS.readExternal(element);\n }\n catch (Throwable ignored) {\n }\n\n getPatterns().clear();\n for (Element pattern : element.getChildren(\"pattern\")) {\n final ClassPattern classPattern = new ClassPattern();\n XmlSerializer.deserializeInto(classPattern, pattern);\n getPatterns().add(classPattern);\n }\n\n myWriteAnnotations.clear();\n final Element writeAnnotations = element.getChild(\"writeAnnotations\");\n if (writeAnnotations != null) {\n for (Element annoElement : writeAnnotations.getChildren(\"writeAnnotation\")) {\n final String value = annoElement.getAttributeValue(\"name\");\n if (value != null) {\n myWriteAnnotations.add(value);\n }\n }\n }\n }\n\n @Override\n @SuppressWarnings({\"HardCodedStringLiteral\"})\n public Element getState() {\n Element element = new Element(\"state\");\n writeExternal(element, myPersistentEntryPoints, ADDITIONAL_ANNOTATIONS);\n if (!getPatterns().isEmpty()) {\n SkipDefaultsSerializationFilter filter = new SkipDefaultsSerializationFilter();\n for (ClassPattern pattern : getPatterns()) {\n element.addContent(XmlSerializer.serialize(pattern, filter));\n }\n }\n\n if (!myWriteAnnotations.isEmpty()) {\n final Element writeAnnotations = new Element(\"writeAnnotations\");\n for (String writeAnnotation : myWriteAnnotations) {\n writeAnnotations.addContent(new Element(\"writeAnnotation\").setAttribute(\"name\", writeAnnotation));\n }\n element.addContent(writeAnnotations);\n }\n return element;\n }\n\n @SuppressWarnings({\"HardCodedStringLiteral\"})\n public static void writeExternal(final Element element,\n final Map persistentEntryPoints,\n final JDOMExternalizableStringList additional_annotations) {\n Collection elementPointers = persistentEntryPoints.values();\n if (!elementPointers.isEmpty()) {\n Element entryPointsElement = new Element(\"entry_points\");\n entryPointsElement.setAttribute(VERSION_ATTR, VERSION);", "answers": [" for (SmartRefElementPointer entryPoint : elementPointers) {"], "length": 549, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "b898091b-f029-4e53-bd80-3e2844ab3edf", "reasoning": "The method writeExternal builds an XML element for entry points. After creating entryPointsElement and setting its version attribute, the next logical step is to iterate over the stored entry point pointers and add each as a child element. Therefore the next line starts a for‑loop over elementPointers.", "reasoning_model_answer": "for (SmartRefElementPointer entryPoint : elementPointers) {", "assistant_with_reasoning": "\nThe method writeExternal builds an XML element for entry points. After creating entryPointsElement and setting its version attribute, the next logical step is to iterate over the stored entry point pointers and add each as a child element. Therefore the next line starts a for‑loop over elementPointers.\n\nfor (SmartRefElementPointer entryPoint : elementPointers) {", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 6.433, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 8096, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "for (SmartRefElementPointer entryPoint : elementPointers) {", "score": 0.95, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "using ICSharpCode.SharpZipLib.Core;\nusing ICSharpCode.SharpZipLib.Zip.Compression;\nusing System;\nusing System.IO;\nusing static ICSharpCode.SharpZipLib.Zip.Compression.Deflater;\n\nnamespace ICSharpCode.SharpZipLib.Zip\n{\n\t/// \n\t/// FastZipEvents supports all events applicable to FastZip operations.\n\t/// \n\tpublic class FastZipEvents\n\t{\n\t\t/// \n\t\t/// Delegate to invoke when processing directories.\n\t\t/// \n\t\tpublic event EventHandler ProcessDirectory;\n\n\t\t/// \n\t\t/// Delegate to invoke when processing files.\n\t\t/// \n\t\tpublic ProcessFileHandler ProcessFile;\n\n\t\t/// \n\t\t/// Delegate to invoke during processing of files.\n\t\t/// \n\t\tpublic ProgressHandler Progress;\n\n\t\t/// \n\t\t/// Delegate to invoke when processing for a file has been completed.\n\t\t/// \n\t\tpublic CompletedFileHandler CompletedFile;\n\n\t\t/// \n\t\t/// Delegate to invoke when processing directory failures.\n\t\t/// \n\t\tpublic DirectoryFailureHandler DirectoryFailure;\n\n\t\t/// \n\t\t/// Delegate to invoke when processing file failures.\n\t\t/// \n\t\tpublic FileFailureHandler FileFailure;\n\n\t\t/// \n\t\t/// Raise the directory failure event.\n\t\t/// \n\t\t/// The directory causing the failure.\n\t\t/// The exception for this event.\n\t\t/// A boolean indicating if execution should continue or not.\n\t\tpublic bool OnDirectoryFailure(string directory, Exception e)\n\t\t{\n\t\t\tbool result = false;\n\t\t\tDirectoryFailureHandler handler = DirectoryFailure;\n\n\t\t\tif (handler != null)\n\t\t\t{\n\t\t\t\tvar args = new ScanFailureEventArgs(directory, e);\n\t\t\t\thandler(this, args);\n\t\t\t\tresult = args.ContinueRunning;\n\t\t\t}\n\t\t\treturn result;\n\t\t}\n\n\t\t/// \n\t\t/// Fires the file failure handler delegate.\n\t\t/// \n\t\t/// The file causing the failure.\n\t\t/// The exception for this failure.\n\t\t/// A boolean indicating if execution should continue or not.\n\t\tpublic bool OnFileFailure(string file, Exception e)\n\t\t{\n\t\t\tFileFailureHandler handler = FileFailure;\n\t\t\tbool result = (handler != null);\n\n\t\t\tif (result)\n\t\t\t{\n\t\t\t\tvar args = new ScanFailureEventArgs(file, e);\n\t\t\t\thandler(this, args);\n\t\t\t\tresult = args.ContinueRunning;\n\t\t\t}\n\t\t\treturn result;\n\t\t}\n\n\t\t/// \n\t\t/// Fires the ProcessFile delegate.\n\t\t/// \n\t\t/// The file being processed.\n\t\t/// A boolean indicating if execution should continue or not.\n\t\tpublic bool OnProcessFile(string file)\n\t\t{\n\t\t\tbool result = true;\n\t\t\tProcessFileHandler handler = ProcessFile;\n\n\t\t\tif (handler != null)\n\t\t\t{\n\t\t\t\tvar args = new ScanEventArgs(file);\n\t\t\t\thandler(this, args);\n\t\t\t\tresult = args.ContinueRunning;\n\t\t\t}\n\t\t\treturn result;\n\t\t}\n\n\t\t/// \n\t\t/// Fires the delegate\n\t\t/// \n\t\t/// The file whose processing has been completed.\n\t\t/// A boolean indicating if execution should continue or not.\n\t\tpublic bool OnCompletedFile(string file)\n\t\t{\n\t\t\tbool result = true;\n\t\t\tCompletedFileHandler handler = CompletedFile;\n\t\t\tif (handler != null)\n\t\t\t{\n\t\t\t\tvar args = new ScanEventArgs(file);\n\t\t\t\thandler(this, args);\n\t\t\t\tresult = args.ContinueRunning;\n\t\t\t}\n\t\t\treturn result;\n\t\t}\n\n\t\t/// \n\t\t/// Fires the process directory delegate.\n\t\t/// \n\t\t/// The directory being processed.\n\t\t/// Flag indicating if the directory has matching files as determined by the current filter.\n\t\t/// A of true if the operation should continue; false otherwise.\n\t\tpublic bool OnProcessDirectory(string directory, bool hasMatchingFiles)\n\t\t{\n\t\t\tbool result = true;\n\t\t\tEventHandler handler = ProcessDirectory;", "answers": ["\t\t\tif (handler != null)"], "length": 452, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "b240d2a5-393b-4a9c-84be-2edc5a3da93a", "reasoning": "The method is mirroring the pattern of earlier event-raising methods: after obtaining the handler variable, the next step is to check if it is non‑null before creating the event args and invoking the handler. Therefore the next line should be the null‑check conditional.", "reasoning_model_answer": "if (handler != null)", "assistant_with_reasoning": "\nThe method is mirroring the pattern of earlier event-raising methods: after obtaining the handler variable, the next step is to check if it is non‑null before creating the event args and invoking the handler. Therefore the next line should be the null‑check conditional.\n\nif (handler != null)", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.243, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 4183, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "if (handler != null)", "score": 0.93, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "\"\"\"\nContains implementation interface for finding spots on one or many images\n\"\"\"\n\nfrom __future__ import annotations\n\nimport logging\nimport math\nimport pickle\nfrom typing import Iterable, Tuple\n\nimport libtbx\nfrom dxtbx.format.image import ImageBool\nfrom dxtbx.imageset import ImageSequence, ImageSet\nfrom dxtbx.model import ExperimentList\n\nfrom dials.array_family import flex\nfrom dials.model.data import PixelList, PixelListLabeller\nfrom dials.util import Sorry, log\nfrom dials.util.log import rehandle_cached_records\nfrom dials.util.mp import available_cores, batch_multi_node_parallel_map\n\nlogger = logging.getLogger(__name__)\n\n\nclass ExtractPixelsFromImage:\n \"\"\"\n A class to extract pixels from a single image\n \"\"\"\n\n def __init__(\n self,\n imageset,\n threshold_function,\n mask,\n region_of_interest,\n max_strong_pixel_fraction,\n compute_mean_background,\n ):\n \"\"\"\n Initialise the class\n\n :param imageset: The imageset to extract from\n :param threshold_function: The function to threshold with\n :param mask: The image mask\n :param region_of_interest: A region of interest to process\n :param max_strong_pixel_fraction: The maximum fraction of pixels allowed\n \"\"\"\n self.threshold_function = threshold_function\n self.imageset = imageset\n self.mask = mask\n self.region_of_interest = region_of_interest\n self.max_strong_pixel_fraction = max_strong_pixel_fraction\n self.compute_mean_background = compute_mean_background\n if self.mask is not None:\n detector = self.imageset.get_detector()\n assert len(self.mask) == len(detector)\n\n def __call__(self, index):\n \"\"\"\n Extract strong pixels from an image\n\n :param index: The index of the image\n \"\"\"\n # Get the frame number\n if isinstance(self.imageset, ImageSequence):\n frame = self.imageset.get_array_range()[0] + index\n else:\n ind = self.imageset.indices()\n if len(ind) > 1:\n assert all(i1 + 1 == i2 for i1, i2 in zip(ind[0:-1], ind[1:-1]))\n frame = ind[index]\n\n # Create the list of pixel lists\n pixel_list = []\n\n # Get the image and mask\n image = self.imageset.get_corrected_data(index)\n mask = self.imageset.get_mask(index)\n\n # Set the mask\n if self.mask is not None:\n assert len(self.mask) == len(mask)\n mask = tuple(m1 & m2 for m1, m2 in zip(mask, self.mask))\n\n logger.debug(\n \"Number of masked pixels for image %i: %i\",\n index,\n sum(m.count(False) for m in mask),\n )\n\n # Add the images to the pixel lists\n num_strong = 0\n average_background = 0\n for i_panel, (im, mk) in enumerate(zip(image, mask)):\n if self.region_of_interest is not None:\n x0, x1, y0, y1 = self.region_of_interest\n height, width = im.all()\n assert x0 < x1, \"x0 < x1\"\n assert y0 < y1, \"y0 < y1\"\n assert x0 >= 0, \"x0 >= 0\"\n assert y0 >= 0, \"y0 >= 0\"\n assert x1 <= width, \"x1 <= width\"\n assert y1 <= height, \"y1 <= height\"\n im_roi = im[y0:y1, x0:x1]\n mk_roi = mk[y0:y1, x0:x1]\n tm_roi = self.threshold_function.compute_threshold(\n im_roi,\n mk_roi,\n imageset=self.imageset,\n i_panel=i_panel,\n region_of_interest=self.region_of_interest,\n )\n threshold_mask = flex.bool(im.accessor(), False)\n threshold_mask[y0:y1, x0:x1] = tm_roi\n else:\n threshold_mask = self.threshold_function.compute_threshold(\n im, mk, imageset=self.imageset, i_panel=i_panel\n )\n\n # Add the pixel list\n plist = PixelList(frame, im, threshold_mask)\n pixel_list.append(plist)\n\n # Get average background\n if self.compute_mean_background:\n background = im.as_1d().select((mk & ~threshold_mask).as_1d())\n average_background += flex.mean(background)\n\n # Add to the spot count\n num_strong += len(plist)\n\n # Make average background\n average_background /= len(image)\n\n # Check total number of strong pixels\n if self.max_strong_pixel_fraction < 1:\n num_image = 0\n for im in image:\n num_image += len(im)\n max_strong = int(math.ceil(self.max_strong_pixel_fraction * num_image))\n if num_strong > max_strong:\n raise RuntimeError(\n f\"\"\"\n The number of strong pixels found ({num_strong}) is greater than the\n maximum allowed ({max_strong}). Try changing spot finding parameters\n \"\"\"\n )\n\n # Print some info\n if self.compute_mean_background:\n logger.info(\n \"Found %d strong pixels on image %d with average background %f\",\n num_strong,\n frame + 1,\n average_background,\n )\n else:\n logger.info(\"Found %d strong pixels on image %d\", num_strong, frame + 1)\n\n # Return the result\n return pixel_list\n\n\nclass ExtractPixelsFromImage2DNoShoeboxes(ExtractPixelsFromImage):\n \"\"\"\n A class to extract pixels from a single image\n \"\"\"\n\n def __init__(\n self,\n imageset,", "answers": [" threshold_function,"], "length": 549, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "0ebe6b53-e289-4f16-bdfd-dd41ad6af366", "reasoning": "The class ExtractPixelsFromImage2DNoShoeboxes inherits from ExtractPixelsFromImage and defines its own __init__ method. Following the pattern of the parent class, the parameter list continues after 'imageset,'. The next logical parameter is 'threshold_function', matching the parent signature and allowing the subclass to pass it to the superclass.", "reasoning_model_answer": "threshold_function,", "assistant_with_reasoning": "\nThe class ExtractPixelsFromImage2DNoShoeboxes inherits from ExtractPixelsFromImage and defines its own __init__ method. Following the pattern of the parent class, the parameter list continues after 'imageset,'. The next logical parameter is 'threshold_function', matching the parent signature and allowing the subclass to pass it to the superclass.\n\nthreshold_function,", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.734, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 5756, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "threshold_function,", "score": 0.83, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/* Copyright (c) The m-m-m Team, Licensed under the Apache License, Version 2.0\n * http://www.apache.org/licenses/LICENSE-2.0 */\npackage net.sf.mmm.util.io.base;\n\nimport java.io.Closeable;\nimport java.io.FileInputStream;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.OutputStream;\nimport java.io.PrintWriter;\nimport java.io.Reader;\nimport java.io.StringWriter;\nimport java.io.Writer;\nimport java.nio.channels.Channel;\nimport java.nio.channels.Channels;\nimport java.nio.channels.FileChannel;\nimport java.nio.channels.ReadableByteChannel;\nimport java.nio.channels.WritableByteChannel;\nimport java.util.Properties;\nimport java.util.concurrent.Callable;\nimport java.util.concurrent.Executor;\nimport java.util.concurrent.FutureTask;\n\nimport javax.inject.Inject;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport net.sf.mmm.util.component.base.AbstractComponent;\nimport net.sf.mmm.util.concurrent.api.Stoppable;\nimport net.sf.mmm.util.concurrent.base.SimpleExecutor;\nimport net.sf.mmm.util.exception.api.NlsNullPointerException;\nimport net.sf.mmm.util.io.api.AsyncTransferrer;\nimport net.sf.mmm.util.io.api.IoMode;\nimport net.sf.mmm.util.io.api.RuntimeIoException;\nimport net.sf.mmm.util.io.api.StreamUtil;\nimport net.sf.mmm.util.io.api.TransferCallback;\nimport net.sf.mmm.util.pool.api.Pool;\nimport net.sf.mmm.util.pool.base.NoByteArrayPool;\nimport net.sf.mmm.util.pool.base.NoCharArrayPool;\n\n/**\n * This is the implementation of the {@link StreamUtil} interface.\n *\n * @see #getInstance()\n *\n * @author Joerg Hohwiller (hohwille at users.sourceforge.net)\n * @since 1.0.0\n */\npublic class StreamUtilImpl extends AbstractComponent implements StreamUtil {\n\n private static final Logger LOG = LoggerFactory.getLogger(StreamUtilImpl.class);\n\n private static StreamUtil instance;\n\n private Executor executor;\n\n private Pool byteArrayPool;\n\n private Pool charArrayPool;\n\n /**\n * The constructor.\n */\n public StreamUtilImpl() {\n\n super();\n this.executor = null;\n this.byteArrayPool = null;\n this.charArrayPool = null;\n }\n\n /**\n * This method gets the singleton instance of this {@link StreamUtilImpl}.
    \n * ATTENTION:
    \n * Please prefer dependency-injection instead of using this method.\n *\n * @return the singleton instance.\n */\n public static StreamUtil getInstance() {\n\n if (instance == null) {\n synchronized (StreamUtilImpl.class) {\n if (instance == null) {\n StreamUtilImpl util = new StreamUtilImpl();\n util.initialize();\n instance = util;\n }\n }\n }\n return instance;\n }\n\n /**\n * This method gets the {@link Executor} used to run asynchronous tasks. It may use a thread-pool.\n *\n * @return the executor.\n */\n protected Executor getExecutor() {\n\n return this.executor;\n }\n\n /**\n * This method sets the {@link #getExecutor() executor}.\n *\n * @param executor the executor to set.\n */\n @Inject\n public void setExecutor(Executor executor) {\n\n getInitializationState().requireNotInitilized();\n this.executor = executor;\n }\n\n /**\n * This method gets the byte-array {@link Pool} used to transfer streams.
    \n * The implementation should create byte-arrays with a suitable length (at least 512, suggested is 4096). Override\n * this method to use a real pool implementation.\n *\n * @return the {@link Pool} instance.\n */\n protected Pool getByteArrayPool() {\n\n return this.byteArrayPool;\n }\n\n /**\n * This method sets the {@link #getByteArrayPool() byte-array-pool}.\n *\n * @param byteArrayPool the byteArrayPool to set\n */\n // @Resource\n public void setByteArrayPool(Pool byteArrayPool) {\n\n getInitializationState().requireNotInitilized();\n this.byteArrayPool = byteArrayPool;\n }\n\n /**\n * This method gets the char-array {@link Pool} used to transfer {@link Reader}s and {@link Writer}s. The\n * implementation should create char-arrays with a suitable length (at least 512, suggested is 2048).
    \n * Override this method to use a real pool implementation.\n *\n * @return the {@link Pool} instance.\n */\n protected Pool getCharArrayPool() {\n\n return this.charArrayPool;\n }\n\n /**\n * This method sets the {@link #getCharArrayPool() char-array-pool}.\n *\n * @param charArrayPool the charArrayPool to set\n */\n // @Resource\n public void setCharArrayPool(Pool charArrayPool) {\n\n getInitializationState().requireNotInitilized();\n this.charArrayPool = charArrayPool;\n }\n\n @Override\n protected void doInitialize() {\n\n super.doInitialize();\n if (this.executor == null) {\n this.executor = SimpleExecutor.INSTANCE;\n }\n if (this.byteArrayPool == null) {\n this.byteArrayPool = NoByteArrayPool.INSTANCE;\n }\n if (this.charArrayPool == null) {", "answers": [" this.charArrayPool = NoCharArrayPool.INSTANCE;"], "length": 492, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "08b6c37a-cd91-4843-bfba-c7fb53f5f591", "reasoning": "In the doInitialize method, after checking for null pools, the code assigns default implementations. The byteArrayPool is set to NoByteArrayPool.INSTANCE, so the charArrayPool should similarly be set to NoCharArrayPool.INSTANCE. The next line after the opening brace of the if statement is the assignment.", "reasoning_model_answer": "this.charArrayPool = NoCharArrayPool.INSTANCE;", "assistant_with_reasoning": "\nIn the doInitialize method, after checking for null pools, the code assigns default implementations. The byteArrayPool is set to NoByteArrayPool.INSTANCE, so the charArrayPool should similarly be set to NoCharArrayPool.INSTANCE. The next line after the opening brace of the if statement is the assignment.\n\nthis.charArrayPool = NoCharArrayPool.INSTANCE;", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 2.645, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 4965, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "this.charArrayPool = NoCharArrayPool.INSTANCE;", "score": 0.94, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "import curses\nimport curses.textpad\nfrom mbf import *\n# http://docs.python.org/2/library/curses.html \n\nclass MainScreen:\n def __init__( self, screen, month ):\n self.filedir = \"\"\n self.whichwin = \"cat\"\n self.screen = screen\n self.month = month\n\n self.loadscreens()\n\n def loadscreens( self ):\n self.screen.erase()\n\n curses.mousemask(1)\n\n curses.start_color() \n \n curses.noecho()\n\n curses.init_pair(1, curses.COLOR_RED, curses.COLOR_WHITE) \n curses.init_pair(2, curses.COLOR_BLACK, curses.COLOR_BLUE) \n curses.init_pair(3, curses.COLOR_BLUE, curses.COLOR_WHITE) \n\n self.screen.bkgd(curses.color_pair(1)) \n self.screen.box()\n screenheight, screenwidth = self.screen.getmaxyx()\n screenheight -= 1\n self.cmdheight = screenheight - 1\n acctwinwidth = 42\n self.screen.addstr(1,acctwinwidth+2-len(self.month.name)/2, \" \"+self.month.name+\" \", curses.A_REVERSE)\n self.screen.refresh() \n\n self.winheight = screenheight-3\n self.acctwin = curses.newwin( self.winheight,\n acctwinwidth,\n 2,\n 2\n )\n\n self.acctwinstartline = 2\n self.printtoacctwin()\n\n catwinx = 2 + acctwinwidth + 1\n catwinwidth = min(70, screenwidth - catwinx - 2)\n self.catwin = curses.newwin( self.winheight,\n catwinwidth,\n 2,\n catwinx\n )\n \n self.catwinstartline = 2 #start at line 2 and go for it\n self.printtocatwin( ) \n\n editx = catwinx + 1 + catwinwidth\n if editx > screenwidth - 30:\n self.editpad = False\n else:\n editwidth = screenwidth - editx - 2 \n self.editwin = curses.newwin( self.winheight,\n editwidth,\n 2,\n editx\n )\n self.editpad = curses.newwin( screenheight-9,\n editwidth-4,\n 4,\n editx+2\n )\n\n self.editwin.clear()\n self.editwin.box()\n self.editwin.bkgd(curses.color_pair(3)) \n self.editwin.addstr(0,2,\"Edit\")\n self.editwin.refresh()\n\n self.editpad.clear()\n self.editpad.bkgd(curses.color_pair(3)) \n self.editpad.refresh()\n self.editor = curses.textpad.Textbox( self.editpad )\n \n\n self.resetblinker()\n\n def switchwhichwin( self , towin=0 ):\n if towin:\n if towin == \"cat\":\n if self.editpad:\n if self.filedir == \"\":\n self.editwin.addstr(0,2,\"Edit\")\n else:\n self.editwin.addstr(0,2,\"Edit \"+self.filedir )\n self.acctwin.addstr(0,2,\"Accounts\" )\n self.catwin.addstr(0,2,\"Categories\", curses.A_UNDERLINE)\n self.whichwin = \"cat\"\n elif towin == \"acct\":\n if self.editpad:\n if self.filedir == \"\":\n self.editwin.addstr(0,2,\"Edit\")\n else:\n self.editwin.addstr(0,2,\"Edit \"+self.filedir )\n self.catwin.addstr(0,2,\"Categories\") # erase special text effect on Categories\n self.acctwin.addstr(0,2,\"Accounts\", curses.A_UNDERLINE)\n self.whichwin = \"acct\"\n elif self.editpad: # towin == \"edit\"\n if self.filedir == \"\":\n self.editwin.addstr(0,2,\"Edit\", curses.A_UNDERLINE )\n else:\n self.editwin.addstr(0,2,\"Edit \"+self.filedir, curses.A_UNDERLINE )\n self.catwin.addstr(0,2,\"Categories\") # erase special text effect on Categories\n self.acctwin.addstr(0,2,\"Accounts\")\n self.editwin.addstr(self.winheight-3,2,\"C-g\", curses.A_BOLD)\n self.editwin.addstr(self.winheight-3,5,\": get out\") \n self.editwin.addstr(self.winheight-3,18,\"C-o / C-k\", curses.A_BOLD)\n self.editwin.addstr(self.winheight-3,27,\": insert/kill line\")\n self.editwin.addstr(self.winheight-2,2,\"C-a\", curses.A_BOLD)\n self.editwin.addstr(self.winheight-2,5,\": start left\")\n self.editwin.addstr(self.winheight-2,19,\"C-n / C-p\", curses.A_BOLD)\n self.editwin.addstr(self.winheight-2,28,\": next/prev line\")\n self.whichwin = \"edit\"\n\n self.acctwin.refresh()\n self.catwin.refresh()\n if self.editpad:\n self.editwin.refresh()\n else:\n # if no window was given, then switch between categories and accounts\n if self.whichwin == \"cat\":\n self.switchwhichwin(\"acct\")\n elif self.whichwin == \"acct\":\n self.switchwhichwin(\"cat\")\n \n def printtoacctwin( self ):\n line = self.acctwinstartline\n acctwinheight, acctwinwidth = self.acctwin.getmaxyx()\n self.acctwin.clear()\n self.acctwin.bkgd(curses.color_pair(3)) \n self.acctwin.box()\n\n if self.whichwin == \"acct\":\n self.acctwin.addstr(0,2,\"Accounts\", curses.A_UNDERLINE)\n else:\n self.acctwin.addstr(0,2,\"Accounts\")\n\n starttotaldough = Dough(0)\n endtotaldough = Dough(0)\n for account, accountname in self.month.accountlist.iteritems():\n if line > 0 and line < acctwinheight - 1:\n self.acctwin.addstr(line,2,accountname+\" (\"+account+\")\", curses.A_BOLD)\n line += 1\n try:\n sbalance = self.month.categories[account.upper()].metavalues[\"startingbalance\"]\n except KeyError:\n sbalance = Dough(0)\n starttotaldough += sbalance\n if line > 0 and line < acctwinheight - 1:\n self.acctwin.addstr(line,3,\"start \"+str(sbalance))\n line += 1\n\n ebalance = self.month.categories[account.upper()].metavalues[\"endingbalance\"]\n if line > 0 and line < acctwinheight - 1:\n self.acctwin.addstr(line,5,\"end \"+str(ebalance))\n line += 1\n\n endtotaldough += ebalance\n \n line += 1\n if line > 0 and line < acctwinheight - 1:\n self.acctwin.addstr(line,2,\"Totals\", curses.A_BOLD)\n line += 1\n if line > 0 and line < acctwinheight - 1:\n self.acctwin.addstr(line,3,\"start \"+str(starttotaldough.clean()))\n line += 1\n if line > 0 and line < acctwinheight - 1:\n self.acctwin.addstr(line,5,\"end \"+str(endtotaldough.clean()))\n line += 1\n if line > 0 and line < acctwinheight - 1:\n self.acctwin.addstr(line,3,\"delta \"+str(endtotaldough-starttotaldough))\n line += 1\n", "answers": [" self.acctwin.refresh()"], "length": 481, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "25fc18da-2b38-42fc-b302-c4cdbe47096c", "reasoning": "The method printtoacctwin builds the account window content line by line. After finishing the last line of text it should update the display. The usual final step is to refresh the window, so the next line is a call to self.acctwin.refresh().", "reasoning_model_answer": "self.acctwin.refresh()", "assistant_with_reasoning": "\nThe method printtoacctwin builds the account window content line by line. After finishing the last line of text it should update the display. The usual final step is to refresh the window, so the next line is a call to self.acctwin.refresh().\n\nself.acctwin.refresh()", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 2.513, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 7326, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "self.acctwin.refresh()", "score": 0.85, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "# -*- coding: utf-8 -*-\n\"\"\"JMdict support.\"\"\"\n\n# This could be a bit cleaner if I used something like SQLalchemy\n# perhaps... The create/insert/index bits were done decent enough,\n# but lookups are done in straight SQL due to the potential\n# complexity, and this sadly does break the abstraction of the table\n# objects...\n\nfrom __future__ import print_function\nfrom __future__ import with_statement\n\nimport os, re, sqlite3\nfrom cStringIO import StringIO\nfrom xml.etree.cElementTree import ElementTree\nfrom helpers import gzread, get_encoding, convert_query_to_unicode\nfrom db import Database as BaseDatabase\nfrom table import Table, ChildTable, KeyValueTable\n\nimport gettext\n#t = gettext.translation(\"jblite\")\n#_ = t.ugettext\ngettext.install(\"jblite\")\n\n# Full expansion of xml:lang\nXML_LANG = \"{http://www.w3.org/XML/1998/namespace}lang\"\n\n\n# FORMAT OF TABLE MAP:\n# dictionary entry: table: (children | None)\n# table: table_name | (table_name, table_type, *args, **kwargs)\n#\n# Ideas:\n# Value = dict: take keys as child tables, lookup all rows, and take values as grandchildren.\n# Value = list: take items as child tables, lookup all rows, assume no children.\n# \n#\n# entry:\n# data = tables[\"entry\"].lookup()\n# children_map = TABLE_MAP[\"entry\"]\n# children = get_data(children_map[\"k_ele\"])\n# result = TableData(data, children)\n#\n#\n# {\"k_ele\": {\"data\": [...],\n# \"children\": {...}}}\n\n# Table data object:\n# obj.data: {}, # single db row\n# obj.children: {\"key\": table_object}\n\n\n# breadth first creation? depth?\n\n# Map of tables to their children maps. Empty {} means no children.\n\n\nclass Entry(object):\n\n def __init__(self, record):\n self._record = record\n\n def __unicode__(self):\n \"\"\"Basic string representation of the entry.\"\"\"\n rec = self._record\n lines = []\n\n k_eles = rec.find_children(\"k_ele\")\n if len(k_eles) > 0:\n lines.append(_(u\"Kanji readings:\"))\n for k_ele_index, k_ele in enumerate(k_eles):\n k_ele_index += 1\n lines.append(_(u\" Reading %d:\") % k_ele_index)\n lines.append(_(u\" Blob: %s\") % k_ele.data['value'])\n\n r_eles = rec.find_children(\"r_ele\")\n if len(r_eles) > 0:\n lines.append(_(u\"Kana readings:\"))\n for r_ele_index, r_ele in enumerate(r_eles):\n r_ele_index += 1\n lines.append(_(u\" Reading %d:\") % r_ele_index)\n lines.append(_(u\" Blob: %s\") % r_ele.data['value'])\n\n senses = rec.find_children(\"sense\")\n if len(senses) > 0:\n lines.append(_(u\"Glosses:\"))\n for sense_index, sense in enumerate(senses):\n sense_index += 1\n lines.append(_(u\" Sense %d:\") % sense_index)\n glosses = sense.find_children(\"gloss\")\n\n gloss_d = {}\n for gloss in glosses:\n gloss_d.setdefault(gloss.data[\"lang\"], []).append(gloss)\n # Output glosses by language\n for lang in sorted(gloss_d.keys()):\n gloss_recs = gloss_d[lang]\n lines.append(_(u\" Lang: %s\") % lang)\n for gloss_index, gloss in enumerate(gloss_recs):\n gloss_index += 1\n val = gloss.data['value']\n lines.append(_(u\" Gloss %d: %s\") % (gloss_index, val))\n return u\"\\n\".join(lines)\n\n def __repr__(self):\n return repr(self._record)\n\n\nclass Database(BaseDatabase):\n\n \"\"\"Top level object for SQLite 3-based JMdict database.\"\"\"\n\n entry_class = Entry\n table_map = {\n u\"entry\": {\n u\"k_ele\": {\n u\"ke_inf\": {},\n u\"ke_pri\": {},\n },\n u\"r_ele\": {\n u\"re_restr\": {},\n u\"re_inf\": {},\n u\"re_pri\": {},\n },\n u\"links\": {},\n u\"bibl\": {},\n u\"etym\": {},\n u\"audit\": {},\n u\"sense\": {\n u\"pos\": {},\n u\"field\": {},\n u\"misc\": {},\n u\"dial\": {},\n u\"stagk\": {},\n u\"stagr\": {},\n u\"xref\": {},\n u\"ant\": {},\n u\"s_inf\": {},\n u\"example\": {},\n u\"lsource\": {},\n u\"gloss\": {\n u\"pri\": {},\n }\n }\n }\n }\n\n def __init__(self, filename, init_from_file=None):\n self.conn = sqlite3.connect(filename)\n self.conn.row_factory = sqlite3.Row # keyword accessors for rows\n self.cursor = self.conn.cursor()\n self.tables = self._create_table_objects()\n if init_from_file is not None:\n raw_data = gzread(init_from_file)\n\n entities = self._get_entities(raw_data)\n infile = StringIO(raw_data)\n etree = ElementTree(file=infile)\n infile.close()\n\n self._create_new_tables()\n self._populate_database(etree, entities)\n self.conn.commit()\n\n def search(self, query, lang=None):\n # Search\n # Two main methods: to and from Japanese.\n # 1. Guess which direction we're searching.\n # 2. Search preferred method.\n # 3. Search remaining method.\n query = convert_query_to_unicode(query)\n query = \"%%%s%%\" % query # Wrap in wildcards\n\n entries_from = self._search_from_japanese(query)\n entries_to = self._search_to_japanese(query, lang=lang)\n\n entry_ids = entries_from + entries_to\n results = [self.lookup(entry_id) for entry_id in entry_ids]", "answers": [" return results"], "length": 562, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "9b2b637f-b450-488f-9d74-0b46f12161f5", "reasoning": "The search method builds a list of entry IDs from two helper methods, then creates a list of entry objects via a list comprehension stored in the variable 'results'. The natural next step is to return this list to the caller, so the next line should be 'return results'.", "reasoning_model_answer": "return results", "assistant_with_reasoning": "\nThe search method builds a list of entry IDs from two helper methods, then creates a list of entry objects via a list comprehension stored in the variable 'results'. The natural next step is to return this list to the caller, so the next line should be 'return results'.\n\nreturn results", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 2.306, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 5701, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "return results", "score": 0.78, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "using System;\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Globalization;\nusing System.Runtime.InteropServices;\nusing System.Runtime.Serialization;\nusing GlmSharp.Swizzle;\n\n// ReSharper disable InconsistentNaming\n\nnamespace GlmSharp\n{\n /// \n /// Static class that contains static glm functions\n /// \n public static partial class glm\n {\n \n /// \n /// Returns an object that can be used for arbitrary swizzling (e.g. swizzle.zy)\n /// \n public static swizzle_vec4 swizzle(vec4 v) => v.swizzle;\n \n /// \n /// Returns an array with all values\n /// \n public static float[] Values(vec4 v) => v.Values;\n \n /// \n /// Returns an enumerator that iterates through all components.\n /// \n public static IEnumerator GetEnumerator(vec4 v) => v.GetEnumerator();\n \n /// \n /// Returns a string representation of this vector using ', ' as a seperator.\n /// \n public static string ToString(vec4 v) => v.ToString();\n \n /// \n /// Returns a string representation of this vector using a provided seperator.\n /// \n public static string ToString(vec4 v, string sep) => v.ToString(sep);\n \n /// \n /// Returns a string representation of this vector using a provided seperator and a format provider for each component.\n /// \n public static string ToString(vec4 v, string sep, IFormatProvider provider) => v.ToString(sep, provider);\n \n /// \n /// Returns a string representation of this vector using a provided seperator and a format for each component.\n /// \n public static string ToString(vec4 v, string sep, string format) => v.ToString(sep, format);\n \n /// \n /// Returns a string representation of this vector using a provided seperator and a format and format provider for each component.\n /// \n public static string ToString(vec4 v, string sep, string format, IFormatProvider provider) => v.ToString(sep, format, provider);\n \n /// \n /// Returns the number of components (4).\n /// \n public static int Count(vec4 v) => v.Count;\n \n /// \n /// Returns true iff this equals rhs component-wise.\n /// \n public static bool Equals(vec4 v, vec4 rhs) => v.Equals(rhs);\n \n /// \n /// Returns true iff this equals rhs type- and component-wise.\n /// \n public static bool Equals(vec4 v, object obj) => v.Equals(obj);\n \n /// \n /// Returns a hash code for this instance.\n /// \n public static int GetHashCode(vec4 v) => v.GetHashCode();\n \n /// \n /// Returns true iff distance between lhs and rhs is less than or equal to epsilon\n /// \n public static bool ApproxEqual(vec4 lhs, vec4 rhs, float eps = 0.1f) => vec4.ApproxEqual(lhs, rhs, eps);\n \n /// \n /// Returns a bvec4 from component-wise application of Equal (lhs == rhs).\n /// \n public static bvec4 Equal(vec4 lhs, vec4 rhs) => vec4.Equal(lhs, rhs);\n \n /// \n /// Returns a bvec4 from component-wise application of NotEqual (lhs != rhs).\n /// \n public static bvec4 NotEqual(vec4 lhs, vec4 rhs) => vec4.NotEqual(lhs, rhs);\n \n /// \n /// Returns a bvec4 from component-wise application of GreaterThan (lhs > rhs).\n /// \n public static bvec4 GreaterThan(vec4 lhs, vec4 rhs) => vec4.GreaterThan(lhs, rhs);\n \n /// \n /// Returns a bvec4 from component-wise application of GreaterThanEqual (lhs >= rhs).\n /// \n public static bvec4 GreaterThanEqual(vec4 lhs, vec4 rhs) => vec4.GreaterThanEqual(lhs, rhs);\n \n /// \n /// Returns a bvec4 from component-wise application of LesserThan (lhs < rhs).\n /// \n public static bvec4 LesserThan(vec4 lhs, vec4 rhs) => vec4.LesserThan(lhs, rhs);\n \n /// \n /// Returns a bvec4 from component-wise application of LesserThanEqual (lhs <= rhs).\n /// ", "answers": [" public static bvec4 LesserThanEqual(vec4 lhs, vec4 rhs) => vec4.LesserThanEqual(lhs, rhs);"], "length": 527, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "0981bc60-102d-4a2b-971f-b89509b790eb", "reasoning": "The code defines static wrapper methods for vector operations, each following the pattern: a summary comment, then a public static method returning a bvec4 that forwards to the corresponding vec4 method. After the summary for LesserThanEqual, the next line should be the method definition matching the pattern, i.e., public static bvec4 LesserThanEqual(vec4 lhs, vec4 rhs) => vec4.LesserThanEqual(lhs, rhs);", "reasoning_model_answer": "public static bvec4 LesserThanEqual(vec4 lhs, vec4 rhs) => vec4.LesserThanEqual(lhs, rhs);", "assistant_with_reasoning": "\nThe code defines static wrapper methods for vector operations, each following the pattern: a summary comment, then a public static method returning a bvec4 that forwards to the corresponding vec4 method. After the summary for LesserThanEqual, the next line should be the method definition matching the pattern, i.e., public static bvec4 LesserThanEqual(vec4 lhs, vec4 rhs) => vec4.LesserThanEqual(lhs, rhs);\n\npublic static bvec4 LesserThanEqual(vec4 lhs, vec4 rhs) => vec4.LesserThanEqual(lhs, rhs);", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.261, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 2, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 4667, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "public static bvec4 LesserThanEqual(vec4 lhs, vec4 rhs) => vec4.LesserThanEqual(lhs, rhs);", "score": 0.96, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "from __future__ import unicode_literals\n\nfrom django.contrib.auth.models import User\nfrom django.db import models\nfrom django.dispatch import receiver\nfrom django.utils import timezone\nfrom django.utils.encoding import python_2_unicode_compatible\nfrom django.utils.functional import cached_property\nfrom django.utils.translation import ugettext_lazy as _\nfrom djblets.auth.signals import user_registered\nfrom djblets.db.fields import CounterField, JSONField\nfrom djblets.forms.fields import TIMEZONE_CHOICES\nfrom djblets.siteconfig.models import SiteConfiguration\n\nfrom reviewboard.accounts.managers import (ProfileManager,\n ReviewRequestVisitManager,\n TrophyManager)\nfrom reviewboard.accounts.trophies import trophies_registry\nfrom reviewboard.avatars import avatar_services\nfrom reviewboard.reviews.models import Group, ReviewRequest\nfrom reviewboard.reviews.signals import (reply_published,\n review_published,\n review_request_published)\nfrom reviewboard.site.models import LocalSite\nfrom reviewboard.site.signals import local_site_user_added\n\n\n@python_2_unicode_compatible\nclass ReviewRequestVisit(models.Model):\n \"\"\"\n A recording of the last time a review request was visited by a user.\n\n Users have one ReviewRequestVisit entry in the database per review\n request they've visited. This is used to keep track of any updates\n to review requests they've already seen, so that we can intelligently\n inform them that new discussions have taken place.\n \"\"\"\n\n VISIBLE = 'V'\n ARCHIVED = 'A'\n MUTED = 'M'\n\n VISIBILITY = (\n (VISIBLE, 'Visible'),\n (ARCHIVED, 'Archived'),\n (MUTED, 'Muted'),\n )\n\n user = models.ForeignKey(User, related_name='review_request_visits')\n review_request = models.ForeignKey(ReviewRequest, related_name='visits')\n timestamp = models.DateTimeField(_('last visited'), default=timezone.now)\n visibility = models.CharField(max_length=1, choices=VISIBILITY,\n default=VISIBLE)\n\n # Set this up with a ReviewRequestVisitManager, which inherits from\n # ConcurrencyManager to help prevent race conditions.\n objects = ReviewRequestVisitManager()\n\n def __str__(self):\n \"\"\"Return a string used for the admin site listing.\"\"\"\n return 'Review request visit'\n\n class Meta:\n db_table = 'accounts_reviewrequestvisit'\n unique_together = ('user', 'review_request')\n index_together = [('user', 'visibility')]\n verbose_name = _('Review Request Visit')\n verbose_name_plural = _('Review Request Visits')\n\n\n@python_2_unicode_compatible\nclass Profile(models.Model):\n \"\"\"User profile which contains some basic configurable settings.\"\"\"\n\n user = models.ForeignKey(User, unique=True)\n\n # This will redirect new users to the account settings page the first time\n # they log in (or immediately after creating an account). This allows\n # people to fix their real name and join groups.\n first_time_setup_done = models.BooleanField(\n default=False,\n verbose_name=_(\"first time setup done\"),\n help_text=_(\"Indicates whether the user has already gone through \"\n \"the first time setup process by saving their user \"\n \"preferences.\"))\n\n # Whether the user wants to receive emails\n should_send_email = models.BooleanField(\n default=True,\n verbose_name=_(\"send email\"),\n help_text=_(\"Indicates whether the user wishes to receive emails.\"))\n\n should_send_own_updates = models.BooleanField(\n default=True,\n verbose_name=_(\"receive emails about own actions\"),\n help_text=_(\"Indicates whether the user wishes to receive emails \"\n \"about their own activity.\"))\n\n collapsed_diffs = models.BooleanField(\n default=True,\n verbose_name=_(\"collapsed diffs\"),\n help_text=_(\"Indicates whether diffs should be shown in their \"\n \"collapsed state by default.\"))\n wordwrapped_diffs = models.BooleanField(\n default=True,\n help_text=_(\"This field is unused and will be removed in a future \"\n \"version.\"))", "answers": [" syntax_highlighting = models.BooleanField("], "length": 403, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "4bc80351-11f0-44ad-913f-66d01f5f2271", "reasoning": "The code is defining fields of the Profile model. The last defined field is wordwrapped_diffs, which ends with a closing parenthesis. The next field in the actual Review Board Profile model is syntax_highlighting, starting with its BooleanField declaration. Therefore the next line is the start of that field definition.", "reasoning_model_answer": "syntax_highlighting = models.BooleanField(", "assistant_with_reasoning": "\nThe code is defining fields of the Profile model. The last defined field is wordwrapped_diffs, which ends with a closing parenthesis. The next field in the actual Review Board Profile model is syntax_highlighting, starting with its BooleanField declaration. Therefore the next line is the start of that field definition.\n\nsyntax_highlighting = models.BooleanField(", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 6.325, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 4415, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "syntax_highlighting = models.BooleanField(", "score": 0.95, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "# vim: tabstop=4 shiftwidth=4 softtabstop=4\n\n# Copyright 2013 Violin Memory, Inc.\n# All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\n\"\"\"\nViolin Memory iSCSI Driver for Openstack Cinder\n\nUses Violin REST API via XG-Tools to manage a standard V6000 series\nflash array to provide network block-storage services.\n\nby Ryan Lucio\nSenior Software Engineer\nViolin Memory\n\n---\n\nEach allocated lun is configured as writable with a 512b blocksize.\n\n*** Note that The fields for zero'ing the lun or performing thin\nprovisioning are not supported by vSHARE at this time. ***\n\nEach new volume/lun is exported to a new iSCSI target specifically\nmade for it. The idea is that this allows CHAP authentication to be\nmanaged independently on a per-volume basis. The export is then\nconfigured to use a specific initiator group (igroup) that has been\npre-configured for use by Nova/Cinder hosts.\n\nWhen an initiator has been chosen to connect to one of the available\nluns (eg via 'nova volume-attach'), it will be added to the configured\nigroup allowing it to see the export. It will also be given any\ntarget location and authentication information needed to connect to\nthe chosen lun.\n\nDriver support (verified for G5.5.2):\n-------------------------------------\nVolume Create/Delete: YES\nVolume Attach/Detach: YES\nSnapshot Create/Delete: NO\nCreate Volume from Snapshot: NO\nGet Volume Stats: YES\nCopy Image to Volume: YES\nCopy Volume to Image: YES\nClone Volume: NO\n\"\"\"\n\nimport time\nimport random\n\nfrom oslo.config import cfg\n\nfrom cinder import exception\nfrom cinder import flags\nfrom cinder.openstack.common import log as logging\nfrom cinder.volume.driver import ISCSIDriver\n\nLOG = logging.getLogger(__name__)\n\ntry:\n from vxg.core.session import XGSession\n from vxg.core.node import XGNode\n import vxg\nexcept ImportError:\n LOG.exception(\n _(\"The Violin v6000 driver for Cinder requires the presence of \" +\n \"the Violin 'XG-Tools', python libraries for facilitating \" +\n \"communication between applications and the v6000 XML API. \" +\n \"The libraries can be downloaded from the Violin Memory \" +\n \"support website at http://www.violin-memory.com/support\"))\n raise\nelse:\n LOG.info(_(\"Running with xg-tools version: %s\" % vxg.__version__))\n\nviolin_opts = [\n cfg.StrOpt('gateway_vip',\n default='',\n help='IP address or hostname of the v6000 master VIP'),\n cfg.StrOpt('gateway_mga',\n default='',\n help='IP address or hostname of mg-a'),\n cfg.StrOpt('gateway_mgb',\n default='',\n help='IP address or hostname of mg-b'),\n cfg.StrOpt('gateway_user',\n default='admin',\n help='User name for connecting to the Memory Gateway'),\n cfg.StrOpt('gateway_password',\n default='',\n help='User name for connecting to the Memory Gateway'),\n cfg.IntOpt('gateway_iscsi_port',\n default=3260,\n help='IP port to use for iSCSI targets'),\n cfg.StrOpt('gateway_iscsi_target_prefix',\n default='iqn.2004-02.com.vmem:',\n help='prefix for iscsi volumes'),\n cfg.StrOpt('gateway_iscsi_igroup_name',\n default='openstack',\n help='name of igroup for initiators'),\n]\n\nFLAGS = flags.FLAGS\nFLAGS.register_opts(violin_opts)\n\nclass InvalidBackendConfig(exception.CinderException):\n message = _(\"Volume backend config is invalid: %(reason)s\")", "answers": ["class ViolinDriver(ISCSIDriver):"], "length": 503, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "a611183d-0459-40c3-a1f6-9048da12305d", "reasoning": "The code has just defined a custom exception class InvalidBackendConfig. In typical OpenStack Cinder drivers, after defining such exceptions, the next step is to define the driver class that implements the storage backend, inheriting from ISCSIDriver. The driver class is usually named after the vendor, here Violin, so the next line is the class definition for the Violin iSCSI driver.", "reasoning_model_answer": "class ViolinISCSIDriver(ISCSIDriver):", "assistant_with_reasoning": "\nThe code has just defined a custom exception class InvalidBackendConfig. In typical OpenStack Cinder drivers, after defining such exceptions, the next step is to define the driver class that implements the storage backend, inheriting from ISCSIDriver. The driver class is usually named after the vendor, here Violin, so the next line is the class definition for the Violin iSCSI driver.\n\nclass ViolinISCSIDriver(ISCSIDriver):", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.357, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 4180, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "class ViolinISCSIDriver(ISCSIDriver):", "score": 0.93, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "package test.net.jawr.web.resource.bundle.postprocess.impl;\n\nimport java.io.ByteArrayInputStream;\nimport java.io.InputStream;\nimport java.io.Reader;\nimport java.util.Map;\nimport java.util.Properties;\n\nimport javax.servlet.ServletContext;\n\nimport junit.framework.TestCase;\nimport net.jawr.web.JawrConstant;\nimport net.jawr.web.config.JawrConfig;\nimport net.jawr.web.exception.ResourceNotFoundException;\nimport net.jawr.web.resource.ImageResourcesHandler;\nimport net.jawr.web.resource.bundle.JoinableResourceBundle;\nimport net.jawr.web.resource.bundle.generator.GeneratorRegistry;\nimport net.jawr.web.resource.bundle.postprocess.BundleProcessingStatus;\nimport net.jawr.web.resource.bundle.postprocess.impl.css.base64.Base64ImageEncoderPostProcessor;\n\nimport org.apache.wicket.util.file.File;\n\nimport test.net.jawr.web.FileUtils;\nimport test.net.jawr.web.resource.bundle.MockJoinableResourceBundle;\nimport test.net.jawr.web.resource.bundle.handler.MockResourceReaderHandler;\nimport test.net.jawr.web.servlet.mock.MockServletContext;\n\npublic class CSSBase64ImageRewriterPostProcessorTest extends TestCase {\n\t\n\t\n\tJoinableResourceBundle bundle;\n\tJawrConfig config;\n\tBundleProcessingStatus status;\n\tBase64ImageEncoderPostProcessor processor;\n\t\n\t\n\tprotected void setUp() throws Exception {\n\t\tsuper.setUp();\n\t\t// Bundle path (full url would be: /servletMapping/prefix/css/bundle.css\n\t\tfinal String bundlePath = \"/css/bundle.css\";\n\t\t// Bundle url prefix\n\t\tfinal String urlPrefix = \"/v00\";\n\t\t\n\t\tbundle = buildFakeBundle(bundlePath, urlPrefix);\n\t\tconfig = new JawrConfig(\"css\", new Properties());\n\t\tServletContext servletContext = new MockServletContext();\n\t\tconfig.setContext(servletContext);\n\t\tconfig.setServletMapping(\"/css\");\n\t\tconfig.setCharsetName(\"UTF-8\");\t\t\n\t\tstatus = new BundleProcessingStatus(BundleProcessingStatus.BUNDLE_PROCESSING_TYPE, bundle,null,config);\n\t\taddGeneratorRegistryToConfig(config, \"css\");\n\t\tstatus.setLastPathAdded(\"/css/someCSS.css\");\n\t\tprocessor = new Base64ImageEncoderPostProcessor();\n\t}\n\n\tprivate GeneratorRegistry addGeneratorRegistryToConfig(JawrConfig config, String type) {\n\t\tGeneratorRegistry generatorRegistry = new GeneratorRegistry(type){\n\n\t\t\tpublic boolean isHandlingCssImage(String cssResourcePath) {\n\t\t\t\t\n\t\t\t\tboolean result = false;\n\t\t\t\tif(cssResourcePath.startsWith(\"jar:\")){\n\t\t\t\t\tresult = true;\n\t\t\t\t}\n\t\t\t\treturn result;\n\t\t\t}\n\t\t};\n\t\tgeneratorRegistry.setConfig(config);\n\t\tconfig.setGeneratorRegistry(generatorRegistry);\n\t\treturn generatorRegistry;\n\t}\n\t\n\tpublic void testBasicImgCssRewriting() {\n\n\t\t// Set the properties\n\t\tProperties props = new Properties();\n\t\tprops.setProperty(JawrConfig.JAWR_CSS_IMG_USE_CLASSPATH_SERVLET, \"true\");\n\t\tconfig = new JawrConfig(\"css\", props);\n\t\tServletContext servletContext = new MockServletContext();\n\t\tconfig.setContext(servletContext);\n\t\tconfig.setServletMapping(\"/css\");\n\t\tconfig.setCharsetName(\"UTF-8\");\n\t\taddGeneratorRegistryToConfig(config, \"css\");\n\t\t\n\t\t// Set up the Image servlet Jawr config\n\t\tprops = new Properties();\n\t\tJawrConfig imgServletJawrConfig = new JawrConfig(\"img\", props);\n\t\timgServletJawrConfig.setServletMapping(\"/cssImg/\");\n\t\taddGeneratorRegistryToConfig(imgServletJawrConfig, \"img\");\n\t\tFakeResourceReaderHandler rsHandler = new FakeResourceReaderHandler();\n\t\tconfig.getGeneratorRegistry().setResourceReaderHandler(rsHandler);\n\t\tImageResourcesHandler imgRsHandler = new ImageResourcesHandler(imgServletJawrConfig, rsHandler, null);\n\t\timgServletJawrConfig.getGeneratorRegistry().setResourceReaderHandler(rsHandler);\n\t\tservletContext.setAttribute(JawrConstant.IMG_CONTEXT_ATTRIBUTE, imgRsHandler);\n\t\t\n\t\tstatus = new BundleProcessingStatus(BundleProcessingStatus.BUNDLE_PROCESSING_TYPE, bundle, null, config);\n\n\t\t// Css data\n\t\tStringBuffer data = new StringBuffer(\"background-image:url(../../images/logo.png);\");\n\t\t\n\t\t// Css path\n\t\tString filePath = \"style/default/assets/someCSS.css\";\n\t\t\n\t\t// Expected: goes 3 back to the context path, then add the CSS image servlet mapping,\n\t\t// then go to the image path\n\t\t// the image is at classPath:/style/images/someImage.gif\n\t\tString expectedURL = \"background-image:url(data:image/png;base64,RmFrZSB2YWx1ZQ==);\";\n\t\tstatus.setLastPathAdded(filePath);\n\n\t\tString result = processor.postProcessBundle(status, data).toString();\n\t\tassertEquals(\"URL was not rewritten properly\", expectedURL, result);\n\t}\n\t\n\tpublic void testBasicImgAsolutURLCssRewriting() {\n\n\t\t// Set the properties\n\t\tProperties props = new Properties();\n\t\tprops.setProperty(JawrConfig.JAWR_CSS_IMG_USE_CLASSPATH_SERVLET, \"true\");\n\t\tprops.setProperty(JawrConstant.JAWR_CSS_URL_REWRITER_CONTEXT_PATH, \"/myApp\");\n\t\tconfig = new JawrConfig(\"css\", props);\n\t\tServletContext servletContext = new MockServletContext();\n\t\tconfig.setContext(servletContext);\n\t\tconfig.setServletMapping(\"/css\");\n\t\tconfig.setCharsetName(\"UTF-8\");\n\t\taddGeneratorRegistryToConfig(config, \"css\");\n\t\t\n\t\t// Set up the Image servlet Jawr config\n\t\tprops = new Properties();\n\t\tJawrConfig imgServletJawrConfig = new JawrConfig(\"img\", props);\n\t\timgServletJawrConfig.setServletMapping(\"/cssImg/\");\n\t\taddGeneratorRegistryToConfig(imgServletJawrConfig, \"img\");\n\t\tFakeResourceReaderHandler rsHandler = new FakeResourceReaderHandler();\n\t\tconfig.getGeneratorRegistry().setResourceReaderHandler(rsHandler);\n\t\tImageResourcesHandler imgRsHandler = new ImageResourcesHandler(imgServletJawrConfig, rsHandler, null);\n\t\timgServletJawrConfig.getGeneratorRegistry().setResourceReaderHandler(rsHandler);\n\t\tservletContext.setAttribute(JawrConstant.IMG_CONTEXT_ATTRIBUTE, imgRsHandler);\n\t\t\n\t\tstatus = new BundleProcessingStatus(BundleProcessingStatus.BUNDLE_PROCESSING_TYPE, bundle, null, config);\n\n\t\t// Css data\n\t\tStringBuffer data = new StringBuffer(\"background-image:url(/myApp/images/logo.png);\");\n\t\t\n\t\t// Css path\n\t\tString filePath = \"style/default/assets/someCSS.css\";\n\t\t\n\t\t// Expected: goes 3 back to the context path, then add the CSS image servlet mapping,\n\t\t// then go to the image path\n\t\t// the image is at classPath:/style/images/someImage.gif\n\t\tString expectedURL = \"background-image:url(data:image/png;base64,RmFrZSB2YWx1ZQ==);\";\n\t\tstatus.setLastPathAdded(filePath);\n\n\t\tString result = processor.postProcessBundle(status, data).toString();\n\t\tassertEquals(\"URL was not rewritten properly\", expectedURL, result);\n\t}\n\t\n\tpublic void testEncodeTooBigImgCssRewriting() {\n\n\t\t// Set the properties\n\t\tProperties props = new Properties();\n\t\tprops.setProperty(JawrConfig.JAWR_CSS_IMG_USE_CLASSPATH_SERVLET, \"true\");\n\t\tconfig = new JawrConfig(\"css\", props);\n\t\tServletContext servletContext = new MockServletContext();\n\t\tconfig.setContext(servletContext);\n\t\tconfig.setServletMapping(\"/css\");\n\t\tconfig.setCharsetName(\"UTF-8\");\n\t\taddGeneratorRegistryToConfig(config, \"css\");\n\t\t\n\t\t// Set up the Image servlet Jawr config\n\t\tprops = new Properties();\n\t\tJawrConfig imgServletJawrConfig = new JawrConfig(\"img\", props);\n\t\timgServletJawrConfig.setServletMapping(\"/cssImg/\");\n\t\taddGeneratorRegistryToConfig(imgServletJawrConfig, \"img\");\n\t\tFakeResourceReaderHandler rsHandler = new FakeResourceReaderHandler();\n\t\tconfig.getGeneratorRegistry().setResourceReaderHandler(rsHandler);\n\t\tImageResourcesHandler imgRsHandler = new ImageResourcesHandler(imgServletJawrConfig, rsHandler, null);\n\t\timgServletJawrConfig.getGeneratorRegistry().setResourceReaderHandler(rsHandler);\n\t\tservletContext.setAttribute(JawrConstant.IMG_CONTEXT_ATTRIBUTE, imgRsHandler);\n\t\t\n\t\tstatus = new BundleProcessingStatus(BundleProcessingStatus.BUNDLE_PROCESSING_TYPE, bundle, null, config);\n\n\t\t// Css data\n\t\tStringBuffer data = new StringBuffer(\"background-image:url(../../images/logo-bigImage.png);\");\n\t\t\n\t\t// Css path", "answers": ["\t\tString filePath = \"style/default/assets/someCSS.css\";"], "length": 515, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "5e9a5b51-cf3c-4a7d-bc8e-2c0b45d08ffe", "reasoning": "In the previous test methods, after creating the CSS data string they define a variable 'filePath' with the same value. The current test follows the same pattern, so after the comment '// Css path' the next line should declare and initialize the filePath variable.", "reasoning_model_answer": "String filePath = \"style/default/assets/someCSS.css\";", "assistant_with_reasoning": "\nIn the previous test methods, after creating the CSS data string they define a variable 'filePath' with the same value. The current test follows the same pattern, so after the comment '// Css path' the next line should declare and initialize the filePath variable.\n\nString filePath = \"style/default/assets/someCSS.css\";", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 1.911, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 7707, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "String filePath = \"style/default/assets/someCSS.css\";", "score": 0.98, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "#! /usr/bin/env python3\n\n#\n# Copyright (c) 2016-present, Przemyslaw Skibinski, Yann Collet, Facebook, Inc.\n# All rights reserved.\n#\n# This source code is licensed under the BSD-style license found in the\n# LICENSE file in the root directory of this source tree. An additional grant\n# of patent rights can be found in the PATENTS file in the same directory.\n#\n\n# Limitations:\n# - doesn't support filenames with spaces\n# - dir1/zstd and dir2/zstd will be merged in a single results file\n\nimport argparse\nimport os\nimport string\nimport subprocess\nimport time\nimport traceback\nimport hashlib\n\nscript_version = 'v1.1.1 (2016-10-28)'\ndefault_repo_url = 'https://github.com/facebook/zstd.git'\nworking_dir_name = 'speedTest'\nworking_path = os.getcwd() + '/' + working_dir_name # /path/to/zstd/tests/speedTest\nclone_path = working_path + '/' + 'zstd' # /path/to/zstd/tests/speedTest/zstd\nemail_header = 'ZSTD_speedTest'\npid = str(os.getpid())\nverbose = False\nclang_version = \"unknown\"\ngcc_version = \"unknown\"\nargs = None\n\n\ndef hashfile(hasher, fname, blocksize=65536):\n with open(fname, \"rb\") as f:\n for chunk in iter(lambda: f.read(blocksize), b\"\"):\n hasher.update(chunk)\n return hasher.hexdigest()\n\n\ndef log(text):\n print(time.strftime(\"%Y/%m/%d %H:%M:%S\") + ' - ' + text)\n\n\ndef execute(command, print_command=True, print_output=False, print_error=True, param_shell=True):\n if print_command:\n log(\"> \" + command)\n popen = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=param_shell, cwd=execute.cwd)\n stdout_lines, stderr_lines = popen.communicate(timeout=args.timeout)\n stderr_lines = stderr_lines.decode(\"utf-8\")\n stdout_lines = stdout_lines.decode(\"utf-8\")\n if print_output:\n if stdout_lines:\n print(stdout_lines)\n if stderr_lines:\n print(stderr_lines)\n if popen.returncode is not None and popen.returncode != 0:\n if stderr_lines and not print_output and print_error:\n print(stderr_lines)\n raise RuntimeError(stdout_lines + stderr_lines)\n return (stdout_lines + stderr_lines).splitlines()\nexecute.cwd = None\n\n\ndef does_command_exist(command):\n try:\n execute(command, verbose, False, False)\n except Exception:\n return False\n return True\n\n\ndef send_email(emails, topic, text, have_mutt, have_mail):\n logFileName = working_path + '/' + 'tmpEmailContent'\n with open(logFileName, \"w\") as myfile:\n myfile.writelines(text)\n myfile.close()\n if have_mutt:\n execute('mutt -s \"' + topic + '\" ' + emails + ' < ' + logFileName, verbose)\n elif have_mail:\n execute('mail -s \"' + topic + '\" ' + emails + ' < ' + logFileName, verbose)\n else:\n log(\"e-mail cannot be sent (mail or mutt not found)\")\n\n\ndef send_email_with_attachments(branch, commit, last_commit, args, text, results_files,\n logFileName, have_mutt, have_mail):\n with open(logFileName, \"w\") as myfile:\n myfile.writelines(text)\n myfile.close()\n email_topic = '[%s:%s] Warning for %s:%s last_commit=%s speed<%s ratio<%s' \\\n % (email_header, pid, branch, commit, last_commit,\n args.lowerLimit, args.ratioLimit)\n if have_mutt:\n execute('mutt -s \"' + email_topic + '\" ' + args.emails + ' -a ' + results_files\n + ' < ' + logFileName)\n elif have_mail:\n execute('mail -s \"' + email_topic + '\" ' + args.emails + ' < ' + logFileName)\n else:\n log(\"e-mail cannot be sent (mail or mutt not found)\")\n\n\ndef git_get_branches():\n execute('git fetch -p', verbose)\n branches = execute('git branch -rl', verbose)\n output = []\n for line in branches:\n if (\"HEAD\" not in line) and (\"coverity_scan\" not in line) and (\"gh-pages\" not in line):\n output.append(line.strip())\n return output\n\n\ndef git_get_changes(branch, commit, last_commit):\n fmt = '--format=\"%h: (%an) %s, %ar\"'\n if last_commit is None:\n commits = execute('git log -n 10 %s %s' % (fmt, commit))\n else:\n commits = execute('git --no-pager log %s %s..%s' % (fmt, last_commit, commit))\n return str('Changes in %s since %s:\\n' % (branch, last_commit)) + '\\n'.join(commits)\n\n\ndef get_last_results(resultsFileName):", "answers": [" if not os.path.isfile(resultsFileName):"], "length": 497, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "2c1240f0-14c9-4923-9e12-1ab1911fa5ff", "reasoning": "The function get_last_results is being defined to retrieve previous benchmark results from a file. The first logical step is to check whether the specified results file actually exists before attempting to read it. Therefore, the next line should perform this existence check.", "reasoning_model_answer": "if not os.path.isfile(resultsFileName):", "assistant_with_reasoning": "\nThe function get_last_results is being defined to retrieve previous benchmark results from a file. The first logical step is to check whether the specified results file actually exists before attempting to read it. Therefore, the next line should perform this existence check.\n\nif not os.path.isfile(resultsFileName):", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 2.461, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 4481, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "if not os.path.isfile(resultsFileName):", "score": 0.95, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "/*\n * Copyright 2010-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\").\n * You may not use this file except in compliance with the License.\n * A copy of the License is located at\n * \n * http://aws.amazon.com/apache2.0\n * \n * or in the \"license\" file accompanying this file. This file is distributed\n * on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n * express or implied. See the License for the specific language governing\n * permissions and limitations under the License.\n */\npackage com.amazonaws.services.elasticmapreduce.model;\n\nimport java.io.Serializable;\n\nimport com.amazonaws.AmazonWebServiceRequest;\n\n/**\n * Container for the parameters to the {@link com.amazonaws.services.elasticmapreduce.AmazonElasticMapReduce#listSteps(ListStepsRequest) ListSteps operation}.\n *

    \n * Provides a list of steps for the cluster.\n *

    \n *\n * @see com.amazonaws.services.elasticmapreduce.AmazonElasticMapReduce#listSteps(ListStepsRequest)\n */\npublic class ListStepsRequest extends AmazonWebServiceRequest implements Serializable, Cloneable {\n\n /**\n * The identifier of the cluster for which to list the steps.\n */\n private String clusterId;\n\n /**\n * The filter to limit the step list based on certain states.\n */\n private com.amazonaws.internal.ListWithAutoConstructFlag stepStates;\n\n /**\n * The filter to limit the step list based on the identifier of the\n * steps.\n */\n private com.amazonaws.internal.ListWithAutoConstructFlag stepIds;\n\n /**\n * The pagination token that indicates the next set of results to\n * retrieve.\n */\n private String marker;\n\n /**\n * The identifier of the cluster for which to list the steps.\n *\n * @return The identifier of the cluster for which to list the steps.\n */\n public String getClusterId() {\n return clusterId;\n }\n \n /**\n * The identifier of the cluster for which to list the steps.\n *\n * @param clusterId The identifier of the cluster for which to list the steps.\n */\n public void setClusterId(String clusterId) {\n this.clusterId = clusterId;\n }\n \n /**\n * The identifier of the cluster for which to list the steps.\n *

    \n * Returns a reference to this object so that method calls can be chained together.\n *\n * @param clusterId The identifier of the cluster for which to list the steps.\n *\n * @return A reference to this updated object so that method calls can be chained\n * together.\n */\n public ListStepsRequest withClusterId(String clusterId) {\n this.clusterId = clusterId;\n return this;\n }\n\n /**\n * The filter to limit the step list based on certain states.\n *\n * @return The filter to limit the step list based on certain states.\n */\n public java.util.List getStepStates() {\n if (stepStates == null) {\n stepStates = new com.amazonaws.internal.ListWithAutoConstructFlag();\n stepStates.setAutoConstruct(true);\n }\n return stepStates;\n }\n \n /**\n * The filter to limit the step list based on certain states.\n *\n * @param stepStates The filter to limit the step list based on certain states.\n */\n public void setStepStates(java.util.Collection stepStates) {\n if (stepStates == null) {", "answers": [" this.stepStates = null;"], "length": 453, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "5442629d-b7f5-491d-aacb-6c3bfa365ac0", "reasoning": "The method setStepStates checks for a null argument. In AWS SDK patterns, when the collection argument is null the internal list field is set to null and the method returns. The very next line after the opening if‑brace therefore assigns null to the stepStates field.", "reasoning_model_answer": "this.stepStates = null;", "assistant_with_reasoning": "\nThe method setStepStates checks for a null argument. In AWS SDK patterns, when the collection argument is null the internal list field is set to null and the method returns. The very next line after the opening if‑brace therefore assigns null to the stepStates field.\n\nthis.stepStates = null;", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 5.235, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 3566, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "this.stepStates = null;", "score": 0.79, "is_full_score": false, "is_nonzero_score": true}} {"input": "", "context": "using System;\nusing System.Collections.Specialized;\nusing System.IO;\nusing System.Linq;\nusing System.Collections.Generic;\nusing System.Web;\nusing Moq;\nusing NUnit.Framework;\nusing SquishIt.Framework;\nusing SquishIt.Framework.Files;\nusing SquishIt.Framework.JavaScript;\nusing SquishIt.Framework.Minifiers.JavaScript;\nusing SquishIt.Framework.Renderers;\nusing SquishIt.Framework.Resolvers;\nusing SquishIt.Framework.Utilities;\nusing SquishIt.Tests.Stubs;\nusing SquishIt.Tests.Helpers;\nusing HttpContext = SquishIt.Framework.HttpContext;\n\nnamespace SquishIt.Tests\n{\n [TestFixture]\n public class JavaScriptBundleTests\n {\n string javaScript = TestUtilities.NormalizeLineEndings(@\"\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfunction product(a, b)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\treturn a * b;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfunction sum(a, b){\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\treturn a + b;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\");\n string minifiedJavaScript = \"function product(n,t){return n*t}function sum(n,t){return n+t};\\n\";\n\n string javaScriptPreMinified = \"(function() { alert('should end with parens') })();\\n\";\n\n string javaScript2 = TestUtilities.NormalizeLineEndings(@\"function sum(a, b){\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\treturn a + b;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t }\");\n string minifiedJavaScript2 = \"function sum(n,t){return n+t};\\n\";\n\n JavaScriptBundleFactory javaScriptBundleFactory;\n\n [SetUp]\n public void Setup()\n {\n javaScriptBundleFactory = new JavaScriptBundleFactory()\n .WithDebuggingEnabled(false)\n .WithHasher(new StubHasher(\"hash\"))\n .WithContents(javaScript);\n //javaScriptBundleFactory.FileReaderFactory.SetContents(javaScript);\n }\n\n [Test]\n public void CanRenderEmptyBundle_WithHashInFilename()\n {\n javaScriptBundleFactory.Create().Render(\"~/js/output_#.js\");\n }\n\n [Test]\n public void CanBundleJavaScript()\n {\n var tag = javaScriptBundleFactory\n .WithDebuggingEnabled(false)\n .Create()\n .Add(\"~/js/test.js\")\n .Render(\"~/js/output_1.js\");\n\n Assert.AreEqual(\"\", tag);\n Assert.AreEqual(minifiedJavaScript, javaScriptBundleFactory.FileWriterFactory.Files[TestUtilities.PrepareRelativePath(@\"js\\output_1.js\")]);\n }\n\n [Test]\n public void CanBundleJavascriptWithMinifiedFiles()\n {\n var firstPath = \"first.js\";\n var secondPath = \"second.js\";\n\n javaScriptBundleFactory.FileReaderFactory.SetContentsForFile(TestUtilities.PrepareRelativePath(firstPath), javaScriptPreMinified);\n javaScriptBundleFactory.FileReaderFactory.SetContentsForFile(TestUtilities.PrepareRelativePath(secondPath), javaScript2);\n\n var tag = javaScriptBundleFactory\n .Create()\n .AddMinified(firstPath)\n .Add(secondPath)\n .Render(\"script.js\");\n\n Assert.AreEqual(\"\", tag);\n\n Assert.AreEqual(1, javaScriptBundleFactory.FileWriterFactory.Files.Count);\n var output = TestUtilities.NormalizeLineEndings(javaScriptBundleFactory.FileWriterFactory.Files[TestUtilities.PrepareRelativePath(\"script.js\")]);\n Assert.True(output.StartsWith(javaScriptPreMinified));\n Assert.True(output.EndsWith(minifiedJavaScript2));\n }\n\n [Test]\n public void CanBundleJavascriptWithMinifiedStrings()\n {\n var tag = javaScriptBundleFactory\n .Create()\n .AddMinifiedString(javaScriptPreMinified)\n .AddString(javaScript2)\n .Render(\"script.js\");\n\n Assert.AreEqual(\"\", tag);\n\n Assert.AreEqual(1, javaScriptBundleFactory.FileWriterFactory.Files.Count);\n var output = TestUtilities.NormalizeLineEndings(javaScriptBundleFactory.FileWriterFactory.Files[TestUtilities.PrepareRelativePath(\"script.js\")]);\n Assert.True(output.StartsWith(javaScriptPreMinified));\n Assert.True(output.EndsWith(minifiedJavaScript2));\n }\n\n [Test]\n public void CanBundleJavaScriptWithMinifiedDirectories()\n {\n var path = Guid.NewGuid().ToString();\n var path2 = Guid.NewGuid().ToString();\n var file1 = TestUtilities.PrepareRelativePath(path + \"\\\\file1.js\");\n var file2 = TestUtilities.PrepareRelativePath(path2 + \"\\\\file2.js\");\n\n var resolver = new Mock(MockBehavior.Strict);\n resolver.Setup(r => r.IsDirectory(It.IsAny())).Returns(true);\n\n resolver.Setup(r =>\n r.ResolveFolder(TestUtilities.PrepareRelativePath(path), It.IsAny(), It.IsAny(), It.IsAny>(), It.IsAny>()))\n .Returns(new[] { file1 });\n\n resolver.Setup(r =>\n r.ResolveFolder(TestUtilities.PrepareRelativePath(path2), It.IsAny(), It.IsAny(), It.IsAny>(), It.IsAny>()))\n .Returns(new[] { file2 });\n\n using(new ResolverFactoryScope(typeof(FileSystemResolver).FullName, resolver.Object))\n {\n var frf = new StubFileReaderFactory();\n frf.SetContentsForFile(file1, javaScript);\n frf.SetContentsForFile(file2, javaScriptPreMinified);\n\n var writerFactory = new StubFileWriterFactory();\n\n var tag = javaScriptBundleFactory\n .WithDebuggingEnabled(false)\n .WithFileReaderFactory(frf)\n .WithFileWriterFactory(writerFactory)\n .Create()\n .AddDirectory(path)\n .AddMinifiedDirectory(path2)\n .Render(\"~/output.js\");\n\n Assert.AreEqual(\"\", tag);\n\n var content = writerFactory.Files[TestUtilities.PrepareRelativePath(@\"output.js\")];\n Assert.True(content.StartsWith(minifiedJavaScript));\n Assert.True(content.EndsWith(javaScriptPreMinified));\n }\n }\n\n [Test]\n public void CanBundleJsVaryingOutputBaseHrefRendersIndependentUrl()\n {\n var firstPath = \"first.js\";\n var secondPath = \"second.js\";\n\n javaScriptBundleFactory.FileReaderFactory.SetContentsForFile(TestUtilities.PrepareRelativePath(firstPath), javaScript);\n javaScriptBundleFactory.FileReaderFactory.SetContentsForFile(TestUtilities.PrepareRelativePath(secondPath), javaScript2);\n\n string tag = javaScriptBundleFactory\n .Create()\n .Add(firstPath)\n .Add(secondPath)\n .WithOutputBaseHref(\"http://subdomain.domain.com\")\n .Render(\"/js/output.js\");\n\n string tagNoBaseHref = javaScriptBundleFactory\n .Create()\n .Add(firstPath)\n .Add(secondPath)\n .Render(\"/js/output.js\");\n\n Assert.AreEqual(\"\", tag);\n Assert.AreEqual(\"\", tagNoBaseHref);\n }\n\n [Test]\n public void RenderNamedUsesOutputBaseHref()\n {\n var firstPath = \"first.js\";\n var secondPath = \"second.js\";\n\n javaScriptBundleFactory.FileReaderFactory.SetContentsForFile(TestUtilities.PrepareRelativePath(firstPath), javaScript);\n javaScriptBundleFactory.FileReaderFactory.SetContentsForFile(TestUtilities.PrepareRelativePath(secondPath), javaScript2);\n\n javaScriptBundleFactory\n .Create()\n .Add(firstPath)\n .Add(secondPath)\n .WithOutputBaseHref(\"http://subdomain.domain.com\")\n .AsNamed(\"leBundle\", \"/js/output.js\");\n\n var tag = javaScriptBundleFactory\n .Create()\n .WithOutputBaseHref(\"http://subdomain.domain.com\")\n .RenderNamed(\"leBundle\");\n\n Assert.AreEqual(\"\", tag);\n }\n\n [Test]\n public void CanBundleJavaScriptWithQuerystringParameter()\n {\n var tag = javaScriptBundleFactory\n .Create()\n .Add(\"~/js/test.js\")\n .Render(\"~/js/output_querystring.js?v=2\");\n\n Assert.AreEqual(\"\", tag);\n }\n\n [Test]\n public void CanBundleJavaScriptWithoutRevisionHash()\n {\n var tag = javaScriptBundleFactory\n .Create()\n .Add(\"~/js/test.js\")\n .WithoutRevisionHash()\n .Render(\"~/js/output_querystring.js?v=2\");\n\n Assert.AreEqual(\"\", tag);\n }\n\n [Test]\n public void CanCreateNamedBundle()\n {\n javaScriptBundleFactory\n .Create()\n .Add(\"~/js/test.js\")\n .AsNamed(\"TestNamed\", \"~/js/output_namedbundle.js\");\n\n var tag = javaScriptBundleFactory\n .Create()\n .RenderNamed(\"TestNamed\");\n\n Assert.AreEqual(\"\", tag);\n Assert.AreEqual(minifiedJavaScript, javaScriptBundleFactory.FileWriterFactory.Files[TestUtilities.PrepareRelativePath(@\"js\\output_namedbundle.js\")]);\n }\n\n [Test]\n public void CanBundleJavaScriptWithRemote()\n {\n var tag = javaScriptBundleFactory\n .Create()\n .AddRemote(\"~/js/test.js\", \"http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js\")\n .Add(\"~/js/test.js\")\n .Render(\"~/js/output_1_2.js\");\n\n Assert.AreEqual(\"\", tag);\n Assert.AreEqual(minifiedJavaScript, javaScriptBundleFactory.FileWriterFactory.Files[TestUtilities.PrepareRelativePath(@\"js\\output_1_2.js\")]);\n }\n\n [Test]\n public void CanBundleJavaScriptWithRemoteAndQuerystringParameter()\n {\n var tag = javaScriptBundleFactory\n .Create()\n .AddRemote(\"~/js/test.js\", \"http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js\")\n .Add(\"~/js/test.js\")\n .Render(\"~/js/output_querystring.js?v=2_2\");\n\n Assert.AreEqual(\"\", tag);\n }\n\n [Test]\n public void CanCreateNamedBundleWithRemote()\n {\n javaScriptBundleFactory\n .Create()\n .AddRemote(\"~/js/test.js\", \"http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js\")\n .Add(\"~/js/test.js\")\n .AsNamed(\"TestCdn\", \"~/js/output_3_2.js\");\n\n var tag = javaScriptBundleFactory\n .Create()\n .RenderNamed(\"TestCdn\");\n\n Assert.AreEqual(\"\", tag);\n Assert.AreEqual(minifiedJavaScript, javaScriptBundleFactory.FileWriterFactory.Files[TestUtilities.PrepareRelativePath(@\"js\\output_3_2.js\")]);\n }\n\n [Test]\n public void CanBundleJavaScriptWithEmbeddedResource()\n {\n var tag = javaScriptBundleFactory\n .Create()\n .AddEmbeddedResource(\"~/js/test.js\", \"SquishIt.Tests://EmbeddedResource.Embedded.js\")\n .Render(\"~/js/output_Embedded.js\");\n\n Assert.AreEqual(\"\", tag);\n Assert.AreEqual(minifiedJavaScript, javaScriptBundleFactory.FileWriterFactory.Files[TestUtilities.PrepareRelativePath(@\"js\\output_Embedded.js\")]);\n Assert.AreEqual(1, javaScriptBundleFactory.FileWriterFactory.Files.Count);\n }\n\n [Test]", "answers": [" public void CanBundleJavaScriptWithRootEmbeddedResource()"], "length": 542, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "963b0170-8a23-4918-a969-7d9721beb126", "reasoning": "In this test class each [Test] attribute is followed by a public void method defining the test. The previous test method ended, and a new [Test] attribute appears, so the next line should be the method signature. Following the naming pattern, we provide a plausible test method name.", "reasoning_model_answer": "public void CanBundleJavaScriptWithEmbeddedResourceAndRemote()", "assistant_with_reasoning": "\nIn this test class each [Test] attribute is followed by a public void method defining the test. The previous test method ended, and a new [Test] attribute appears, so the next line should be the method signature. Following the naming pattern, we provide a plausible test method name.\n\npublic void CanBundleJavaScriptWithEmbeddedResourceAndRemote()", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 5.102, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "lcc", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 13418, "fewshot_ids": ["d9aa0fae1843d2d73e9ac2308f31a3760b5ff6be9bc4face"], "fewshot_dataset_keys": ["lcc"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "lcc", "pred_field": "reasoning_model_answer", "pred_used": "public void CanBundleJavaScriptWithEmbeddedResourceAndRemote()", "score": 0.83, "is_full_score": false, "is_nonzero_score": true}}

    \n\t\t/// The language of the content. please use one of the language codes from the IETF BCP 47 standard.\n\t\t///