_id
stringlengths 2
7
| title
stringlengths 3
140
| partition
stringclasses 3
values | text
stringlengths 73
34.1k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q1500
|
JulianChronology.date
|
train
|
@Override
public JulianDate date(int prolepticYear, int month, int dayOfMonth) {
return JulianDate.of(prolepticYear, month, dayOfMonth);
}
|
java
|
{
"resource": ""
}
|
q1501
|
JulianChronology.dateYearDay
|
train
|
@Override
public JulianDate dateYearDay(Era era, int yearOfEra, int dayOfYear) {
return dateYearDay(prolepticYear(era, yearOfEra), dayOfYear);
}
|
java
|
{
"resource": ""
}
|
q1502
|
JulianChronology.localDateTime
|
train
|
@Override
@SuppressWarnings("unchecked")
public ChronoLocalDateTime<JulianDate> localDateTime(TemporalAccessor temporal) {
return (ChronoLocalDateTime<JulianDate>) super.localDateTime(temporal);
}
|
java
|
{
"resource": ""
}
|
q1503
|
JulianChronology.zonedDateTime
|
train
|
@Override
@SuppressWarnings("unchecked")
public ChronoZonedDateTime<JulianDate> zonedDateTime(TemporalAccessor temporal) {
return (ChronoZonedDateTime<JulianDate>) super.zonedDateTime(temporal);
}
|
java
|
{
"resource": ""
}
|
q1504
|
Symmetry454Chronology.date
|
train
|
@Override
public Symmetry454Date date(int prolepticYear, int month, int dayOfMonth) {
return Symmetry454Date.of(prolepticYear, month, dayOfMonth);
}
|
java
|
{
"resource": ""
}
|
q1505
|
Symmetry454Chronology.dateYearDay
|
train
|
@Override
public Symmetry454Date dateYearDay(Era era, int yearOfEra, int dayOfYear) {
return dateYearDay(prolepticYear(era, yearOfEra), dayOfYear);
}
|
java
|
{
"resource": ""
}
|
q1506
|
Symmetry454Chronology.localDateTime
|
train
|
@Override
@SuppressWarnings("unchecked")
public ChronoLocalDateTime<Symmetry454Date> localDateTime(TemporalAccessor temporal) {
return (ChronoLocalDateTime<Symmetry454Date>) super.localDateTime(temporal);
}
|
java
|
{
"resource": ""
}
|
q1507
|
Symmetry454Chronology.zonedDateTime
|
train
|
@Override
@SuppressWarnings("unchecked")
public ChronoZonedDateTime<Symmetry454Date> zonedDateTime(TemporalAccessor temporal) {
return (ChronoZonedDateTime<Symmetry454Date>) super.zonedDateTime(temporal);
}
|
java
|
{
"resource": ""
}
|
q1508
|
Symmetry010Chronology.date
|
train
|
@Override
public Symmetry010Date date(int prolepticYear, int month, int dayOfMonth) {
return Symmetry010Date.of(prolepticYear, month, dayOfMonth);
}
|
java
|
{
"resource": ""
}
|
q1509
|
Symmetry010Chronology.dateYearDay
|
train
|
@Override
public Symmetry010Date dateYearDay(Era era, int yearOfEra, int dayOfYear) {
return dateYearDay(prolepticYear(era, yearOfEra), dayOfYear);
}
|
java
|
{
"resource": ""
}
|
q1510
|
Symmetry010Chronology.localDateTime
|
train
|
@Override
@SuppressWarnings("unchecked")
public ChronoLocalDateTime<Symmetry010Date> localDateTime(TemporalAccessor temporal) {
return (ChronoLocalDateTime<Symmetry010Date>) super.localDateTime(temporal);
}
|
java
|
{
"resource": ""
}
|
q1511
|
Symmetry010Chronology.zonedDateTime
|
train
|
@Override
@SuppressWarnings("unchecked")
public ChronoZonedDateTime<Symmetry010Date> zonedDateTime(TemporalAccessor temporal) {
return (ChronoZonedDateTime<Symmetry010Date>) super.zonedDateTime(temporal);
}
|
java
|
{
"resource": ""
}
|
q1512
|
PaxChronology.date
|
train
|
@Override
public PaxDate date(int prolepticYear, int month, int dayOfMonth) {
return PaxDate.of(prolepticYear, month, dayOfMonth);
}
|
java
|
{
"resource": ""
}
|
q1513
|
PaxChronology.dateYearDay
|
train
|
@Override
public PaxDate dateYearDay(Era era, int yearOfEra, int dayOfYear) {
return dateYearDay(prolepticYear(era, yearOfEra), dayOfYear);
}
|
java
|
{
"resource": ""
}
|
q1514
|
PaxChronology.localDateTime
|
train
|
@Override
@SuppressWarnings("unchecked")
public ChronoLocalDateTime<PaxDate> localDateTime(TemporalAccessor temporal) {
return (ChronoLocalDateTime<PaxDate>) super.localDateTime(temporal);
}
|
java
|
{
"resource": ""
}
|
q1515
|
PaxChronology.zonedDateTime
|
train
|
@Override
@SuppressWarnings("unchecked")
public ChronoZonedDateTime<PaxDate> zonedDateTime(TemporalAccessor temporal) {
return (ChronoZonedDateTime<PaxDate>) super.zonedDateTime(temporal);
}
|
java
|
{
"resource": ""
}
|
q1516
|
EthiopicChronology.date
|
train
|
@Override
public EthiopicDate date(Era era, int yearOfEra, int month, int dayOfMonth) {
return date(prolepticYear(era, yearOfEra), month, dayOfMonth);
}
|
java
|
{
"resource": ""
}
|
q1517
|
EthiopicChronology.date
|
train
|
@Override
public EthiopicDate date(int prolepticYear, int month, int dayOfMonth) {
return EthiopicDate.of(prolepticYear, month, dayOfMonth);
}
|
java
|
{
"resource": ""
}
|
q1518
|
EthiopicChronology.dateYearDay
|
train
|
@Override
public EthiopicDate dateYearDay(Era era, int yearOfEra, int dayOfYear) {
return dateYearDay(prolepticYear(era, yearOfEra), dayOfYear);
}
|
java
|
{
"resource": ""
}
|
q1519
|
EthiopicChronology.localDateTime
|
train
|
@Override
@SuppressWarnings("unchecked")
public ChronoLocalDateTime<EthiopicDate> localDateTime(TemporalAccessor temporal) {
return (ChronoLocalDateTime<EthiopicDate>) super.localDateTime(temporal);
}
|
java
|
{
"resource": ""
}
|
q1520
|
EthiopicChronology.zonedDateTime
|
train
|
@Override
@SuppressWarnings("unchecked")
public ChronoZonedDateTime<EthiopicDate> zonedDateTime(TemporalAccessor temporal) {
return (ChronoZonedDateTime<EthiopicDate>) super.zonedDateTime(temporal);
}
|
java
|
{
"resource": ""
}
|
q1521
|
DiscordianChronology.date
|
train
|
@Override
public DiscordianDate date(int prolepticYear, int month, int dayOfMonth) {
return DiscordianDate.of(prolepticYear, month, dayOfMonth);
}
|
java
|
{
"resource": ""
}
|
q1522
|
DiscordianChronology.dateYearDay
|
train
|
@Override
public DiscordianDate dateYearDay(Era era, int yearOfEra, int dayOfYear) {
return dateYearDay(prolepticYear(era, yearOfEra), dayOfYear);
}
|
java
|
{
"resource": ""
}
|
q1523
|
DiscordianChronology.localDateTime
|
train
|
@Override
@SuppressWarnings("unchecked")
public ChronoLocalDateTime<DiscordianDate> localDateTime(TemporalAccessor temporal) {
return (ChronoLocalDateTime<DiscordianDate>) super.localDateTime(temporal);
}
|
java
|
{
"resource": ""
}
|
q1524
|
DiscordianChronology.zonedDateTime
|
train
|
@Override
@SuppressWarnings("unchecked")
public ChronoZonedDateTime<DiscordianDate> zonedDateTime(TemporalAccessor temporal) {
return (ChronoZonedDateTime<DiscordianDate>) super.zonedDateTime(temporal);
}
|
java
|
{
"resource": ""
}
|
q1525
|
InternationalFixedChronology.date
|
train
|
@Override
public InternationalFixedDate date(int prolepticYear, int month, int dayOfMonth) {
return InternationalFixedDate.of(prolepticYear, month, dayOfMonth);
}
|
java
|
{
"resource": ""
}
|
q1526
|
InternationalFixedChronology.dateYearDay
|
train
|
@Override
public InternationalFixedDate dateYearDay(Era era, int yearOfEra, int dayOfYear) {
return dateYearDay(prolepticYear(era, yearOfEra), dayOfYear);
}
|
java
|
{
"resource": ""
}
|
q1527
|
InternationalFixedChronology.localDateTime
|
train
|
@Override
@SuppressWarnings("unchecked")
public ChronoLocalDateTime<InternationalFixedDate> localDateTime(TemporalAccessor temporal) {
return (ChronoLocalDateTime<InternationalFixedDate>) super.localDateTime(temporal);
}
|
java
|
{
"resource": ""
}
|
q1528
|
InternationalFixedChronology.zonedDateTime
|
train
|
@Override
@SuppressWarnings("unchecked")
public ChronoZonedDateTime<InternationalFixedDate> zonedDateTime(TemporalAccessor temporal) {
return (ChronoZonedDateTime<InternationalFixedDate>) super.zonedDateTime(temporal);
}
|
java
|
{
"resource": ""
}
|
q1529
|
GoogleMap.boundsProperty
|
train
|
public final ReadOnlyObjectProperty<LatLongBounds> boundsProperty() {
if (bounds == null) {
bounds = new ReadOnlyObjectWrapper<>(getBounds());
addStateEventHandler(MapStateEventType.idle, () -> {
bounds.set(getBounds());
});
}
return bounds.getReadOnlyProperty();
}
|
java
|
{
"resource": ""
}
|
q1530
|
GoogleMap.addMarker
|
train
|
public void addMarker(Marker marker) {
if (markers == null) {
markers = new HashSet<>();
}
markers.add(marker);
marker.setMap(this);
}
|
java
|
{
"resource": ""
}
|
q1531
|
GoogleMap.removeMarker
|
train
|
public void removeMarker(Marker marker) {
if (markers != null && markers.contains(marker)) {
markers.remove(marker);
}
marker.setMap(null);
}
|
java
|
{
"resource": ""
}
|
q1532
|
GoogleMap.clearMarkers
|
train
|
public void clearMarkers() {
if (markers != null && !markers.isEmpty()) {
markers.forEach((m) -> {
m.setMap(null);
});
markers.clear();
}
|
java
|
{
"resource": ""
}
|
q1533
|
JavascriptObject.setProperty
|
train
|
protected void setProperty(String propertyName, JavascriptObject propertyValue) {
jsObject.setMember(propertyName, propertyValue.getJSObject());
}
|
java
|
{
"resource": ""
}
|
q1534
|
JavascriptObject.setProperty
|
train
|
protected void setProperty(String propertyName, JavascriptEnum propertyValue) {
jsObject.setMember(propertyName, propertyValue.getEnumValue());
}
|
java
|
{
"resource": ""
}
|
q1535
|
JavascriptObject.getProperty
|
train
|
protected <T> T getProperty(String key, Class<T> type) {
Object returnValue = getProperty(key);
if (returnValue != null) {
return (T) returnValue;
} else {
return null;
}
}
|
java
|
{
"resource": ""
}
|
q1536
|
JavascriptObject.invokeJavascriptReturnValue
|
train
|
protected <T> T invokeJavascriptReturnValue(String function, Class<T> returnType) {
Object returnObject = invokeJavascript(function);
if (returnObject instanceof JSObject) {
try {
Constructor<T> constructor = returnType.getConstructor(JSObject.class);
return constructor.newInstance((JSObject) returnObject);
} catch (Exception ex) {
throw new IllegalStateException(ex);
}
} else {
return (T) returnObject;
}
}
|
java
|
{
"resource": ""
}
|
q1537
|
JavascriptObject.checkUndefined
|
train
|
protected Object checkUndefined(Object val) {
if (val instanceof String && ((String) val).equals("undefined")) {
return null;
}
return val;
}
|
java
|
{
"resource": ""
}
|
q1538
|
JavascriptObject.checkBoolean
|
train
|
protected Boolean checkBoolean(Object val, Boolean def) {
return (val == null) ? def : (Boolean) val;
}
|
java
|
{
"resource": ""
}
|
q1539
|
EventHandlers.registerHandler
|
train
|
public String registerHandler(GFXEventHandler handler) {
String uuid = UUID.randomUUID().toString();
handlers.put(uuid, handler);
return uuid;
}
|
java
|
{
"resource": ""
}
|
q1540
|
EventHandlers.handleStateEvent
|
train
|
public void handleStateEvent(String callbackKey) {
if (handlers.containsKey(callbackKey) && handlers.get(callbackKey) instanceof StateEventHandler) {
((StateEventHandler) handlers.get(callbackKey)).handle();
} else {
System.err.println("Error in handle: " + callbackKey + " for state handler ");
}
}
|
java
|
{
"resource": ""
}
|
q1541
|
ArcBuilder.buildClosedArc
|
train
|
public static final PolygonOptions buildClosedArc(LatLong center, LatLong start, LatLong end, ArcType arcType) {
MVCArray res = buildArcPoints(center, start, end);
if (ArcType.ROUND.equals(arcType)) {
res.push(center);
}
return new PolygonOptions().paths(res);
}
|
java
|
{
"resource": ""
}
|
q1542
|
ArcBuilder.buildOpenArc
|
train
|
public static final PolylineOptions buildOpenArc(LatLong center, LatLong start, LatLong end) {
MVCArray res = buildArcPoints(center, start, end);
return new PolylineOptions().path(res);
}
|
java
|
{
"resource": ""
}
|
q1543
|
ArcBuilder.buildArcPoints
|
train
|
public static final MVCArray buildArcPoints(LatLong center, double startBearing, double endBearing, double radius) {
int points = DEFAULT_ARC_POINTS;
MVCArray res = new MVCArray();
if (startBearing > endBearing) {
endBearing += 360.0;
}
double deltaBearing = endBearing - startBearing;
deltaBearing = deltaBearing / points;
for (int i = 0; (i < points + 1); i++) {
res.push(center.getDestinationPoint(startBearing + i * deltaBearing, radius));
}
return res;
}
|
java
|
{
"resource": ""
}
|
q1544
|
ElevationResult.getLocation
|
train
|
public LatLong getLocation() {
if (location == null) {
location = new LatLong((JSObject) (getJSObject().getMember("location")));
}
return location;
}
|
java
|
{
"resource": ""
}
|
q1545
|
JavascriptRuntime.getArgString
|
train
|
protected String getArgString(Object arg) {
//if (arg instanceof LatLong) {
// return ((LatLong) arg).getVariableName();
//} else
if (arg instanceof JavascriptObject) {
return ((JavascriptObject) arg).getVariableName();
// return ((JavascriptObject) arg).getPropertiesAsString();
} else if( arg instanceof JavascriptEnum ) {
return ((JavascriptEnum) arg).getEnumValue().toString();
} else {
return arg.toString();
}
}
|
java
|
{
"resource": ""
}
|
q1546
|
DirectionsPane.registerEventHandler
|
train
|
private String registerEventHandler(GFXEventHandler h) {
//checkInitialized();
if (!registeredOnJS) {
JSObject doc = (JSObject) runtime.execute("document");
doc.setMember("jsHandlers", jsHandlers);
registeredOnJS = true;
}
return jsHandlers.registerHandler(h);
}
|
java
|
{
"resource": ""
}
|
q1547
|
DirectionsPane.addUIEventHandler
|
train
|
public void addUIEventHandler(JavascriptObject obj, UIEventType type, UIEventHandler h) {
String key = registerEventHandler(h);
String mcall = "google.maps.event.addListener(" + obj.getVariableName() + ", '" + type.name() + "', "
+ "function(event) {document.jsHandlers.handleUIEvent('" + key + "', event);});";//.latLng
//System.out.println("addUIEventHandler mcall: " + mcall);
runtime.execute(mcall);
}
|
java
|
{
"resource": ""
}
|
q1548
|
LatLong.distanceFrom
|
train
|
public double distanceFrom(LatLong end) {
double dLat = (end.getLatitude() - getLatitude()) * Math.PI / 180;
double dLon = (end.getLongitude() - getLongitude()) * Math.PI / 180;
double a = Math.sin(dLat / 2) * Math.sin(dLat / 2)
+ Math.cos(getLatitude() * Math.PI / 180)
* Math.cos(end.getLatitude() * Math.PI / 180)
* Math.sin(dLon / 2) * Math.sin(dLon / 2);
double c = 2.0 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
double d = EarthRadiusMeters * c;
return d;
}
|
java
|
{
"resource": ""
}
|
q1549
|
LatLong.getDestinationPoint
|
train
|
public LatLong getDestinationPoint(double bearing, double distance) {
double brng = Math.toRadians(bearing);
double lat1 = latToRadians();
double lon1 = longToRadians();
double lat2 = Math.asin(Math.sin(lat1)
* Math.cos(distance / EarthRadiusMeters)
+ Math.cos(lat1) * Math.sin(distance / EarthRadiusMeters)
* Math.cos(brng));
double lon2 = lon1 + Math.atan2(Math.sin(brng)
* Math.sin(distance / EarthRadiusMeters) * Math.cos(lat1),
Math.cos(distance / EarthRadiusMeters)
- Math.sin(lat1) * Math.sin(lat2));
return new LatLong(Math.toDegrees(lat2), Math.toDegrees(lon2));
}
|
java
|
{
"resource": ""
}
|
q1550
|
LatLong.getBearing
|
train
|
public double getBearing(LatLong end) {
if (this.equals(end)) {
return 0;
}
double lat1 = latToRadians();
double lon1 = longToRadians();
double lat2 = end.latToRadians();
double lon2 = end.longToRadians();
double angle = -Math.atan2(Math.sin(lon1 - lon2) * Math.cos(lat2),
Math.cos(lat1) * Math.sin(lat2) - Math.sin(lat1)
* Math.cos(lat2) * Math.cos(lon1 - lon2));
if (angle < 0.0) {
angle += Math.PI * 2.0;
}
if (angle > Math.PI) {
angle -= Math.PI * 2.0;
}
return Math.toDegrees(angle);
}
|
java
|
{
"resource": ""
}
|
q1551
|
ElevationService.getElevationForLocations
|
train
|
public void getElevationForLocations(LocationElevationRequest req, ElevationServiceCallback callback) {
this.callback = callback;
JSObject doc = (JSObject) getJSObject().eval("document");
doc.setMember(getVariableName(), this);
StringBuilder r = new StringBuilder(getVariableName())
.append(".")
.append("getElevationForLocations(")
.append(req.getVariableName())
.append(", ")
.append("function(results, status) {alert('rec:'+status);\ndocument.")
.append(getVariableName())
.append(".processResponse(results, status);});");
LOG.trace("ElevationService direct call: " + r.toString());
getJSObject().eval(r.toString());
}
|
java
|
{
"resource": ""
}
|
q1552
|
ElevationService.getElevationAlongPath
|
train
|
public void getElevationAlongPath(PathElevationRequest req, ElevationServiceCallback callback) {
this.callback = callback;
JSObject doc = (JSObject) getJSObject().eval("document");
doc.setMember(getVariableName(), this);
StringBuilder r = new StringBuilder(getVariableName())
.append(".")
.append("getElevationAlongPath(")
.append(req.getVariableName())
.append(", ")
.append("function(results, status) {document.")
.append(getVariableName())
.append(".processResponse(results, status);});");
getJSObject().eval(r.toString());
}
|
java
|
{
"resource": ""
}
|
q1553
|
GeopositionComparator.distance
|
train
|
public static double distance(double lat1, double lon1,
double lat2, double lon2) {
double dLat = Math.toRadians(lat2-lat1);
double dLon = Math.toRadians(lon2-lon1);
lat1 = Math.toRadians(lat1);
lat2 = Math.toRadians(lat2);
double a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(lat1) * Math.cos(lat2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
return R * c;
}
|
java
|
{
"resource": ""
}
|
q1554
|
SoundexComparator.soundex
|
train
|
public static String soundex(String str) {
if (str.length() < 1)
return ""; // no soundex key for the empty string (could use 000)
char[] key = new char[4];
key[0] = str.charAt(0);
int pos = 1;
char prev = '0';
for (int ix = 1; ix < str.length() && pos < 4; ix++) {
char ch = str.charAt(ix);
int charno;
if (ch >= 'A' && ch <= 'Z')
charno = ch - 'A';
else if (ch >= 'a' && ch <= 'z')
charno = ch - 'a';
else
continue;
if (number[charno] != '0' && number[charno] != prev)
key[pos++] = number[charno];
prev = number[charno];
}
for ( ; pos < 4; pos++)
key[pos] = '0';
return new String(key);
}
|
java
|
{
"resource": ""
}
|
q1555
|
SoundexComparator.buildTable
|
train
|
private static char[] buildTable() {
char[] table = new char[26];
for (int ix = 0; ix < table.length; ix++)
table[ix] = '0';
table['B' - 'A'] = '1';
table['P' - 'A'] = '1';
table['F' - 'A'] = '1';
table['V' - 'A'] = '1';
table['C' - 'A'] = '2';
table['S' - 'A'] = '2';
table['K' - 'A'] = '2';
table['G' - 'A'] = '2';
table['J' - 'A'] = '2';
table['Q' - 'A'] = '2';
table['X' - 'A'] = '2';
table['Z' - 'A'] = '2';
table['D' - 'A'] = '3';
table['T' - 'A'] = '3';
table['L' - 'A'] = '4';
table['M' - 'A'] = '5';
table['N' - 'A'] = '5';
table['R' - 'A'] = '6';
return table;
}
|
java
|
{
"resource": ""
}
|
q1556
|
NTriplesDataSource.addStatement
|
train
|
private void addStatement(RecordImpl record,
String subject,
String property,
String object) {
Collection<Column> cols = columns.get(property);
if (cols == null) {
if (property.equals(RDF_TYPE) && !types.isEmpty())
addValue(record, subject, property, object);
return;
}
for (Column col : cols) {
String cleaned = object;
if (col.getCleaner() != null)
cleaned = col.getCleaner().clean(object);
if (cleaned != null && !cleaned.equals(""))
addValue(record, subject, col.getProperty(), cleaned);
}
}
|
java
|
{
"resource": ""
}
|
q1557
|
GeoProperty.geoSearch
|
train
|
public Filter geoSearch(String value) {
GeopositionComparator comp = (GeopositionComparator) prop.getComparator();
double dist = comp.getMaxDistance();
double degrees = DistanceUtils.dist2Degrees(dist, DistanceUtils.EARTH_MEAN_RADIUS_KM * 1000.0);
Shape circle = spatialctx.makeCircle(parsePoint(value), degrees);
SpatialArgs args = new SpatialArgs(SpatialOperation.Intersects, circle);
return strategy.makeFilter(args);
}
|
java
|
{
"resource": ""
}
|
q1558
|
GeoProperty.parsePoint
|
train
|
private Point parsePoint(String point) {
int comma = point.indexOf(',');
if (comma == -1)
return null;
float lat = Float.valueOf(point.substring(0, comma));
float lng = Float.valueOf(point.substring(comma + 1));
return spatialctx.makePoint(lng, lat);
}
|
java
|
{
"resource": ""
}
|
q1559
|
JDBCUtils.open
|
train
|
public static Statement open(String jndiPath) {
try {
Context ctx = new InitialContext();
DataSource ds = (DataSource) ctx.lookup(jndiPath);
Connection conn = ds.getConnection();
return conn.createStatement();
} catch (NamingException e) {
throw new DukeException("No database configuration found via JNDI at " +
jndiPath, e);
} catch (SQLException e) {
throw new DukeException("Error connecting to database via " +
jndiPath, e);
}
}
|
java
|
{
"resource": ""
}
|
q1560
|
JDBCUtils.open
|
train
|
public static Statement open(String driverklass, String jdbcuri,
Properties props) {
try {
Driver driver = (Driver) ObjectUtils.instantiate(driverklass);
Connection conn = driver.connect(jdbcuri, props);
if (conn == null)
throw new DukeException("Couldn't connect to database at " +
jdbcuri);
return conn.createStatement();
} catch (SQLException e) {
throw new DukeException(e);
}
}
|
java
|
{
"resource": ""
}
|
q1561
|
JDBCUtils.close
|
train
|
public static void close(Statement stmt) {
try {
Connection conn = stmt.getConnection();
try {
if (!stmt.isClosed())
stmt.close();
} catch (UnsupportedOperationException e) {
// not all JDBC drivers implement the isClosed() method.
// ugly, but probably the only way to get around this.
// http://stackoverflow.com/questions/12845385/duke-fast-deduplication-java-lang-unsupportedoperationexception-operation-not
stmt.close();
}
if (conn != null && !conn.isClosed())
conn.close();
} catch (SQLException e) {
throw new DukeException(e);
}
}
|
java
|
{
"resource": ""
}
|
q1562
|
JDBCUtils.validate
|
train
|
public static boolean validate(Statement stmt) {
try {
Connection conn = stmt.getConnection();
if (conn == null)
return false;
if (!conn.isClosed() && conn.isValid(10))
return true;
stmt.close();
conn.close();
} catch (SQLException e) {
// this may well fail. that doesn't matter. we're just making an
// attempt to clean up, and if we can't, that's just too bad.
}
return false;
}
|
java
|
{
"resource": ""
}
|
q1563
|
JDBCUtils.queryForInt
|
train
|
public static int queryForInt(Statement stmt, String sql, int nullvalue) {
try {
ResultSet rs = stmt.executeQuery(sql);
try {
if (!rs.next())
return nullvalue;
return rs.getInt(1);
} finally {
rs.close();
}
} catch (SQLException e) {
throw new DukeException(e);
}
}
|
java
|
{
"resource": ""
}
|
q1564
|
JDBCUtils.queryHasResult
|
train
|
public static boolean queryHasResult(Statement stmt, String sql) {
try {
ResultSet rs = stmt.executeQuery(sql);
try {
return rs.next();
} finally {
rs.close();
}
} catch (SQLException e) {
throw new DukeException(e);
}
}
|
java
|
{
"resource": ""
}
|
q1565
|
StringUtils.replaceAnyOf
|
train
|
public static String replaceAnyOf(String value, String chars,
char replacement) {
char[] tmp = new char[value.length()];
int pos = 0;
for (int ix = 0; ix < tmp.length; ix++) {
char ch = value.charAt(ix);
if (chars.indexOf(ch) != -1)
tmp[pos++] = replacement;
else
tmp[pos++] = ch;
}
return new String(tmp, 0, tmp.length);
}
|
java
|
{
"resource": ""
}
|
q1566
|
StringUtils.normalizeWS
|
train
|
public static String normalizeWS(String value) {
char[] tmp = new char[value.length()];
int pos = 0;
boolean prevws = false;
for (int ix = 0; ix < tmp.length; ix++) {
char ch = value.charAt(ix);
if (ch != ' ' && ch != '\t' && ch != '\n' && ch != '\r') {
if (prevws && pos != 0)
tmp[pos++] = ' ';
tmp[pos++] = ch;
prevws = false;
} else
prevws = true;
}
return new String(tmp, 0, pos);
}
|
java
|
{
"resource": ""
}
|
q1567
|
PropertyUtils.get
|
train
|
public static String get(Properties props, String name, String defval) {
String value = props.getProperty(name);
if (value == null)
value = defval;
return value;
}
|
java
|
{
"resource": ""
}
|
q1568
|
ConfigurationImpl.getDataSources
|
train
|
public Collection<DataSource> getDataSources(int groupno) {
if (groupno == 1)
return group1;
else if (groupno == 2)
return group2;
else
throw new DukeConfigException("Invalid group number: " + groupno);
}
|
java
|
{
"resource": ""
}
|
q1569
|
ConfigurationImpl.addDataSource
|
train
|
public void addDataSource(int groupno, DataSource datasource) {
// the loader takes care of validation
if (groupno == 0)
datasources.add(datasource);
else if (groupno == 1)
group1.add(datasource);
else if (groupno == 2)
group2.add(datasource);
}
|
java
|
{
"resource": ""
}
|
q1570
|
PropertyImpl.compare
|
train
|
public double compare(String v1, String v2) {
// FIXME: it should be possible here to say that, actually, we
// didn't learn anything from comparing these two values, so that
// probability is set to 0.5.
if (comparator == null)
return 0.5; // we ignore properties with no comparator
// first, we call the comparator, to get a measure of how similar
// these two values are. note that this is not the same as what we
// are going to return, which is a probability.
double sim = comparator.compare(v1, v2);
// we have been configured with a high probability (for equal
// values) and a low probability (for different values). given
// sim, which is a measure of the similarity somewhere in between
// equal and different, we now compute our estimate of the
// probability.
// if sim = 1.0, we return high. if sim = 0.0, we return low. for
// values in between we need to compute a little. the obvious
// formula to use would be (sim * (high - low)) + low, which
// spreads the values out equally spaced between high and low.
// however, if the similarity is higher than 0.5 we don't want to
// consider this negative evidence, and so there's a threshold
// there. also, users felt Duke was too eager to merge records,
// and wanted probabilities to fall off faster with lower
// probabilities, and so we square sim in order to achieve this.
if (sim >= 0.5)
return ((high - 0.5) * (sim * sim)) + 0.5;
else
return low;
}
|
java
|
{
"resource": ""
}
|
q1571
|
SparqlDataSource.runQuery
|
train
|
public SparqlResult runQuery(String endpoint, String query) {
return SparqlClient.execute(endpoint, query, username, password);
}
|
java
|
{
"resource": ""
}
|
q1572
|
InMemoryClassDatabase.merge
|
train
|
private void merge(Integer cid1, Integer cid2) {
Collection<String> klass1 = classix.get(cid1);
Collection<String> klass2 = classix.get(cid2);
// if klass1 is the smaller, swap the two
if (klass1.size() < klass2.size()) {
Collection<String> tmp = klass2;
klass2 = klass1;
klass1 = tmp;
Integer itmp = cid2;
cid2 = cid1;
cid1 = itmp;
}
// now perform the actual merge
for (String id : klass2) {
klass1.add(id);
recordix.put(id, cid1);
}
// delete the smaller class, and we're done
classix.remove(cid2);
}
|
java
|
{
"resource": ""
}
|
q1573
|
KeyValueDatabase.bumpScores
|
train
|
private void bumpScores(Map<Long, Score> candidates,
List<Bucket> buckets,
int ix) {
for (; ix < buckets.size(); ix++) {
Bucket b = buckets.get(ix);
if (b.nextfree > CUTOFF_FACTOR_2 * candidates.size())
return;
double score = b.getScore();
for (Score s : candidates.values())
if (b.contains(s.id))
s.score += score;
}
}
|
java
|
{
"resource": ""
}
|
q1574
|
KeyValueDatabase.collectCandidates
|
train
|
private int collectCandidates(Map<Long, Score> candidates,
List<Bucket> buckets,
int threshold) {
int ix;
for (ix = 0; ix < threshold &&
candidates.size() < (CUTOFF_FACTOR_1 * max_search_hits); ix++) {
Bucket b = buckets.get(ix);
long[] ids = b.records;
double score = b.getScore();
for (int ix2 = 0; ix2 < b.nextfree; ix2++) {
Score s = candidates.get(ids[ix2]);
if (s == null) {
s = new Score(ids[ix2]);
candidates.put(ids[ix2], s);
}
s.score += score;
}
if (DEBUG)
System.out.println("Bucket " + b.nextfree + " -> " + candidates.size());
}
return ix;
}
|
java
|
{
"resource": ""
}
|
q1575
|
KeyValueDatabase.lookup
|
train
|
private List<Bucket> lookup(Record record) {
List<Bucket> buckets = new ArrayList();
for (Property p : config.getLookupProperties()) {
String propname = p.getName();
Collection<String> values = record.getValues(propname);
if (values == null)
continue;
for (String value : values) {
String[] tokens = StringUtils.split(value);
for (int ix = 0; ix < tokens.length; ix++) {
Bucket b = store.lookupToken(propname, tokens[ix]);
if (b == null || b.records == null)
continue;
long[] ids = b.records;
if (DEBUG)
System.out.println(propname + ", " + tokens[ix] + ": " + b.nextfree + " (" + b.getScore() + ")");
buckets.add(b);
}
}
}
return buckets;
}
|
java
|
{
"resource": ""
}
|
q1576
|
CommonJTimer.spawnThread
|
train
|
public void spawnThread(DukeController controller, int check_interval) {
this.controller = controller;
timer = mgr.schedule(this, 0, check_interval * 1000); // convert to ms
}
|
java
|
{
"resource": ""
}
|
q1577
|
AbstractCmdlineTool.init
|
train
|
public String[] init(String[] argv, int min, int max,
Collection<CommandLineParser.Option> options)
throws IOException, SAXException {
// parse command line
parser = new CommandLineParser();
parser.setMinimumArguments(min);
parser.setMaximumArguments(max);
parser.registerOption(new CommandLineParser.BooleanOption("reindex", 'I'));
if (options != null)
for (CommandLineParser.Option option : options)
parser.registerOption(option);
try {
argv = parser.parse(argv);
} catch (CommandLineParser.CommandLineParserException e) {
System.err.println("ERROR: " + e.getMessage());
usage();
System.exit(1);
}
// do we need to reindex?
boolean reindex = parser.getOptionState("reindex");
// load configuration
config = ConfigLoader.load(argv[0]);
database = config.getDatabase(reindex); // overwrite iff reindex
if (database.isInMemory())
reindex = true; // no other way to do it in this case
// reindex, if requested
if (reindex)
reindex(config, database);
return argv;
}
|
java
|
{
"resource": ""
}
|
q1578
|
Utils.createTempDirectory
|
train
|
public static File createTempDirectory(String prefix) {
File temp = null;
try {
temp = File.createTempFile(prefix != null ? prefix : "temp", Long.toString(System.nanoTime()));
if (!(temp.delete())) {
throw new IOException("Could not delete temp file: "
+ temp.getAbsolutePath());
}
if (!(temp.mkdir())) {
throw new IOException("Could not create temp directory: "
+ temp.getAbsolutePath());
}
} catch (IOException e) {
throw new DukeException("Unable to create temporary directory with prefix " + prefix, e);
}
return temp;
}
|
java
|
{
"resource": ""
}
|
q1579
|
ConfigLoader.loadFromString
|
train
|
public static Configuration loadFromString(String config)
throws IOException, SAXException {
ConfigurationImpl cfg = new ConfigurationImpl();
XMLReader parser = XMLReaderFactory.createXMLReader();
parser.setContentHandler(new ConfigHandler(cfg, null));
Reader reader = new StringReader(config);
parser.parse(new InputSource(reader));
return cfg;
}
|
java
|
{
"resource": ""
}
|
q1580
|
LinkDatabaseMatchListener.endRecord_
|
train
|
public void endRecord_() {
// this is where we actually update the link database. basically,
// all we need to do is to retract those links which weren't seen
// this time around, and that can be done via assertLink, since it
// can override existing links.
// get all the existing links
Collection<Link> oldlinks = linkdb.getAllLinksFor(getIdentity(current));
// build a hashmap so we can look up corresponding old links from
// new links
if (oldlinks != null) {
Map<String, Link> oldmap = new HashMap(oldlinks.size());
for (Link l : oldlinks)
oldmap.put(makeKey(l), l);
// removing all the links we found this time around from the set of
// old links. any links remaining after this will be stale, and need
// to be retracted
for (Link newl : new ArrayList<Link>(curlinks)) {
String key = makeKey(newl);
Link oldl = oldmap.get(key);
if (oldl == null)
continue;
if (oldl.overrides(newl))
// previous information overrides this link, so ignore
curlinks.remove(newl);
else if (sameAs(oldl, newl)) {
// there's no new information here, so just ignore this
curlinks.remove(newl);
oldmap.remove(key); // we don't want to retract the old one
} else
// the link is out of date, but will be overwritten, so remove
oldmap.remove(key);
}
// all the inferred links left in oldmap are now old links we
// didn't find on this pass. there is no longer any evidence
// supporting them, and so we can retract them.
for (Link oldl : oldmap.values())
if (oldl.getStatus() == LinkStatus.INFERRED) {
oldl.retract(); // changes to retracted, updates timestamp
curlinks.add(oldl);
}
}
// okay, now we write it all to the database
for (Link l : curlinks)
linkdb.assertLink(l);
}
|
java
|
{
"resource": ""
}
|
q1581
|
ConfigWriter.write
|
train
|
public void write(Configuration config)
throws IOException {
pp.startDocument();
pp.startElement("duke", null);
// FIXME: here we should write the objects, but that's not
// possible with the current API. we don't need that for the
// genetic algorithm at the moment, but it would be useful.
pp.startElement("schema", null);
writeElement("threshold", "" + config.getThreshold());
if (config.getMaybeThreshold() != 0.0)
writeElement("maybe-threshold", "" + config.getMaybeThreshold());
for (Property p : config.getProperties())
writeProperty(p);
pp.endElement("schema");
String dbclass = config.getDatabase(false).getClass().getName();
AttributeListImpl atts = new AttributeListImpl();
atts.addAttribute("class", "CDATA", dbclass);
pp.startElement("database", atts);
pp.endElement("database");
if (config.isDeduplicationMode())
for (DataSource src : config.getDataSources())
writeDataSource(src);
else {
pp.startElement("group", null);
for (DataSource src : config.getDataSources(1))
writeDataSource(src);
pp.endElement("group");
pp.startElement("group", null);
for (DataSource src : config.getDataSources(2))
writeDataSource(src);
pp.endElement("group");
}
pp.endElement("duke");
pp.endDocument();
}
|
java
|
{
"resource": ""
}
|
q1582
|
NTriplesParser.parse
|
train
|
public static void parse(Reader src, StatementHandler handler)
throws IOException {
new NTriplesParser(src, handler).parse();
}
|
java
|
{
"resource": ""
}
|
q1583
|
Levenshtein.distance
|
train
|
public static int distance(String s1, String s2) {
if (s1.length() == 0)
return s2.length();
if (s2.length() == 0)
return s1.length();
int s1len = s1.length();
// we use a flat array for better performance. we address it by
// s1ix + s1len * s2ix. this modification improves performance
// by about 30%, which is definitely worth the extra complexity.
int[] matrix = new int[(s1len + 1) * (s2.length() + 1)];
for (int col = 0; col <= s2.length(); col++)
matrix[col * s1len] = col;
for (int row = 0; row <= s1len; row++)
matrix[row] = row;
for (int ix1 = 0; ix1 < s1len; ix1++) {
char ch1 = s1.charAt(ix1);
for (int ix2 = 0; ix2 < s2.length(); ix2++) {
int cost;
if (ch1 == s2.charAt(ix2))
cost = 0;
else
cost = 1;
int left = matrix[ix1 + ((ix2 + 1) * s1len)] + 1;
int above = matrix[ix1 + 1 + (ix2 * s1len)] + 1;
int aboveleft = matrix[ix1 + (ix2 * s1len)] + cost;
matrix[ix1 + 1 + ((ix2 + 1) * s1len)] =
Math.min(left, Math.min(above, aboveleft));
}
}
// for (int ix1 = 0; ix1 <= s1len; ix1++) {
// for (int ix2 = 0; ix2 <= s2.length(); ix2++) {
// System.out.print(matrix[ix1 + (ix2 * s1len)] + " ");
// }
// System.out.println();
// }
return matrix[s1len + (s2.length() * s1len)];
}
|
java
|
{
"resource": ""
}
|
q1584
|
Levenshtein.compactDistance
|
train
|
public static int compactDistance(String s1, String s2) {
if (s1.length() == 0)
return s2.length();
if (s2.length() == 0)
return s1.length();
// the maximum edit distance there is any point in reporting.
int maxdist = Math.min(s1.length(), s2.length()) / 2;
// we allocate just one column instead of the entire matrix, in
// order to save space. this also enables us to implement the
// algorithm somewhat faster. the first cell is always the
// virtual first row.
int s1len = s1.length();
int[] column = new int[s1len + 1];
// first we need to fill in the initial column. we use a separate
// loop for this, because in this case our basis for comparison is
// not the previous column, but a virtual first column.
int ix2 = 0;
char ch2 = s2.charAt(ix2);
column[0] = 1; // virtual first row
for (int ix1 = 1; ix1 <= s1len; ix1++) {
int cost = s1.charAt(ix1 - 1) == ch2 ? 0 : 1;
// Lowest of three: above (column[ix1 - 1]), aboveleft: ix1 - 1,
// left: ix1. Latter cannot possibly be lowest, so is
// ignored.
column[ix1] = Math.min(column[ix1 - 1], ix1 - 1) + cost;
}
// okay, now we have an initialized first column, and we can
// compute the rest of the matrix.
int above = 0;
for (ix2 = 1; ix2 < s2.length(); ix2++) {
ch2 = s2.charAt(ix2);
above = ix2 + 1; // virtual first row
int smallest = s1len * 2; // used to implement cutoff
for (int ix1 = 1; ix1 <= s1len; ix1++) {
int cost = s1.charAt(ix1 - 1) == ch2 ? 0 : 1;
// above: above
// aboveleft: column[ix1 - 1]
// left: column[ix1]
int value = Math.min(Math.min(above, column[ix1 - 1]), column[ix1]) +
cost;
column[ix1 - 1] = above; // write previous
above = value; // keep current
smallest = Math.min(smallest, value);
}
column[s1len] = above;
// check if we can stop because we'll be going over the max distance
if (smallest > maxdist)
return smallest;
}
// ok, we're done
return above;
}
|
java
|
{
"resource": ""
}
|
q1585
|
LuceneDatabase.commit
|
train
|
public void commit() {
if (directory == null)
return;
try {
if (reader != null)
reader.close();
// it turns out that IndexWriter.optimize actually slows
// searches down, because it invalidates the cache. therefore
// not calling it any more.
// http://www.searchworkings.org/blog/-/blogs/uwe-says%3A-is-your-reader-atomic
// iwriter.optimize();
iwriter.commit();
openSearchers();
} catch (IOException e) {
throw new DukeException(e);
}
}
|
java
|
{
"resource": ""
}
|
q1586
|
LuceneDatabase.findRecordById
|
train
|
public Record findRecordById(String id) {
if (directory == null)
init();
Property idprop = config.getIdentityProperties().iterator().next();
for (Record r : lookup(idprop, id))
if (r.getValue(idprop.getName()).equals(id))
return r;
return null; // not found
}
|
java
|
{
"resource": ""
}
|
q1587
|
PhoneNumberCleaner.clean
|
train
|
public String clean(String value) {
String orig = value;
// check if there's a + before the first digit
boolean initialplus = findPlus(value);
// remove everything but digits
value = sub.clean(value);
if (value == null)
return null;
// check for initial '00'
boolean zerozero = !initialplus && value.startsWith("00");
if (zerozero)
value = value.substring(2); // strip off the zeros
// look for country code
CountryCode ccode = findCountryCode(value);
if (ccode == null) {
// no country code, let's do what little we can
if (initialplus || zerozero)
return orig; // this number is messed up. dare not touch
return value;
} else {
value = value.substring(ccode.getPrefix().length()); // strip off ccode
if (ccode.getStripZero() && value.startsWith("0"))
value = value.substring(1); // strip the zero
if (ccode.isRightFormat(value))
return "+" + ccode.getPrefix() + " " + value;
else
return orig; // don't dare touch this
}
}
|
java
|
{
"resource": ""
}
|
q1588
|
Link.overrides
|
train
|
public boolean overrides(Link other) {
if (other.getStatus() == LinkStatus.ASSERTED &&
status != LinkStatus.ASSERTED)
return false;
else if (status == LinkStatus.ASSERTED &&
other.getStatus() != LinkStatus.ASSERTED)
return true;
// the two links are from equivalent sources of information, so we
// believe the most recent
return timestamp > other.getTimestamp();
}
|
java
|
{
"resource": ""
}
|
q1589
|
DukeController.process
|
train
|
public void process() {
// are we ready to process yet, or have we had an error, and are
// waiting a bit longer in the hope that it will resolve itself?
if (error_skips > 0) {
error_skips--;
return;
}
try {
if (logger != null)
logger.debug("Starting processing");
status = "Processing";
lastCheck = System.currentTimeMillis();
// FIXME: how to break off processing if we don't want to keep going?
processor.deduplicate(batch_size);
status = "Sleeping";
if (logger != null)
logger.debug("Finished processing");
} catch (Throwable e) {
status = "Thread blocked on error: " + e;
if (logger != null)
logger.error("Error in processing; waiting", e);
error_skips = error_factor;
}
}
|
java
|
{
"resource": ""
}
|
q1590
|
DukeController.reportError
|
train
|
void reportError(Throwable throwable) {
if (logger != null)
logger.error("Timer reported error", throwable);
status = "Thread blocked on error: " + throwable;
error_skips = error_factor;
}
|
java
|
{
"resource": ""
}
|
q1591
|
ObjectUtils.makePropertyName
|
train
|
public static String makePropertyName(String name) {
char[] buf = new char[name.length() + 3];
int pos = 0;
buf[pos++] = 's';
buf[pos++] = 'e';
buf[pos++] = 't';
for (int ix = 0; ix < name.length(); ix++) {
char ch = name.charAt(ix);
if (ix == 0)
ch = Character.toUpperCase(ch);
else if (ch == '-') {
ix++;
if (ix == name.length())
break;
ch = Character.toUpperCase(name.charAt(ix));
}
buf[pos++] = ch;
}
return new String(buf, 0, pos);
}
|
java
|
{
"resource": ""
}
|
q1592
|
MediaSharedElementCallback.mapObsoleteElements
|
train
|
@NonNull
private List<String> mapObsoleteElements(List<String> names) {
List<String> elementsToRemove = new ArrayList<>(names.size());
for (String name : names) {
if (name.startsWith("android")) continue;
elementsToRemove.add(name);
}
return elementsToRemove;
}
|
java
|
{
"resource": ""
}
|
q1593
|
MediaSharedElementCallback.removeObsoleteElements
|
train
|
private void removeObsoleteElements(List<String> names,
Map<String, View> sharedElements,
List<String> elementsToRemove) {
if (elementsToRemove.size() > 0) {
names.removeAll(elementsToRemove);
for (String elementToRemove : elementsToRemove) {
sharedElements.remove(elementToRemove);
}
}
}
|
java
|
{
"resource": ""
}
|
q1594
|
GalleryAdapter.onBindViewHolder
|
train
|
@Override
public void onBindViewHolder(GalleryAdapter.ViewHolder holder, int position, List<Object> payloads) {
if (payloads.isEmpty()) { // If doesn't have any payload then bind the fully item
super.onBindViewHolder(holder, position, payloads);
} else {
for (Object payload : payloads) {
boolean selected = isSelected(position);
if (SELECTION_PAYLOAD.equals(payload)) {
if (VIEW_TYPE_MEDIA == getItemViewType(position)) {
MediaViewHolder viewHolder = (MediaViewHolder) holder;
viewHolder.mCheckView.setChecked(selected);
if (selected) {
AnimationHelper.scaleView(holder.mImageView, SELECTED_SCALE);
} else {
AnimationHelper.scaleView(holder.mImageView, UNSELECTED_SCALE);
}
}
}
}
}
}
|
java
|
{
"resource": ""
}
|
q1595
|
UnsafeSliceFactory.newSlice
|
train
|
public Slice newSlice(long address, int size)
{
if (address <= 0) {
throw new IllegalArgumentException("Invalid address: " + address);
}
if (size == 0) {
return Slices.EMPTY_SLICE;
}
return new Slice(null, address, size, 0, null);
}
|
java
|
{
"resource": ""
}
|
q1596
|
UnsafeSliceFactory.newSlice
|
train
|
public Slice newSlice(long address, int size, Object reference)
{
if (address <= 0) {
throw new IllegalArgumentException("Invalid address: " + address);
}
if (reference == null) {
throw new NullPointerException("Object reference is null");
}
if (size == 0) {
return Slices.EMPTY_SLICE;
}
return new Slice(null, address, size, size, reference);
}
|
java
|
{
"resource": ""
}
|
q1597
|
Murmur3Hash32.hash
|
train
|
public static int hash(int input)
{
int k1 = mixK1(input);
int h1 = mixH1(DEFAULT_SEED, k1);
return fmix(h1, SizeOf.SIZE_OF_INT);
}
|
java
|
{
"resource": ""
}
|
q1598
|
SliceUtf8.isAscii
|
train
|
public static boolean isAscii(Slice utf8)
{
int length = utf8.length();
int offset = 0;
// Length rounded to 8 bytes
int length8 = length & 0x7FFF_FFF8;
for (; offset < length8; offset += 8) {
if ((utf8.getLongUnchecked(offset) & TOP_MASK64) != 0) {
return false;
}
}
// Enough bytes left for 32 bits?
if (offset + 4 < length) {
if ((utf8.getIntUnchecked(offset) & TOP_MASK32) != 0) {
return false;
}
offset += 4;
}
// Do the rest one by one
for (; offset < length; offset++) {
if ((utf8.getByteUnchecked(offset) & 0x80) != 0) {
return false;
}
}
return true;
}
|
java
|
{
"resource": ""
}
|
q1599
|
SliceUtf8.lengthOfCodePoint
|
train
|
public static int lengthOfCodePoint(int codePoint)
{
if (codePoint < 0) {
throw new InvalidCodePointException(codePoint);
}
if (codePoint < 0x80) {
// normal ASCII
// 0xxx_xxxx
return 1;
}
if (codePoint < 0x800) {
return 2;
}
if (codePoint < 0x1_0000) {
return 3;
}
if (codePoint < 0x11_0000) {
return 4;
}
// Per RFC3629, UTF-8 is limited to 4 bytes, so more bytes are illegal
throw new InvalidCodePointException(codePoint);
}
|
java
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.