code
stringlengths 10
174k
| nl
stringlengths 3
129k
|
---|---|
@Override public AxisSpace reserveSpace(Graphics2D g2,Plot plot,Rectangle2D plotArea,RectangleEdge edge,AxisSpace space){
this.internalMarkerCycleBoundTick=null;
AxisSpace ret=super.reserveSpace(g2,plot,plotArea,edge,space);
if (this.internalMarkerCycleBoundTick == null) {
return ret;
}
FontMetrics fm=g2.getFontMetrics(getTickLabelFont());
Rectangle2D r=TextUtilities.getTextBounds(this.internalMarkerCycleBoundTick.getText(),g2,fm);
if (RectangleEdge.isTopOrBottom(edge)) {
if (isVerticalTickLabels()) {
space.add(r.getHeight() / 2,RectangleEdge.RIGHT);
}
else {
space.add(r.getWidth() / 2,RectangleEdge.RIGHT);
}
}
else if (RectangleEdge.isLeftOrRight(edge)) {
if (isVerticalTickLabels()) {
space.add(r.getWidth() / 2,RectangleEdge.TOP);
}
else {
space.add(r.getHeight() / 2,RectangleEdge.TOP);
}
}
return ret;
}
| Reserve some space on each axis side because we draw a centered label at each extremity. |
private void LtoOSP(long l,byte[] sp){
sp[0]=(byte)(l >>> 56);
sp[1]=(byte)(l >>> 48);
sp[2]=(byte)(l >>> 40);
sp[3]=(byte)(l >>> 32);
sp[4]=(byte)(l >>> 24);
sp[5]=(byte)(l >>> 16);
sp[6]=(byte)(l >>> 8);
sp[7]=(byte)(l >>> 0);
}
| long to octet string. |
@Override public void validate(final StatementDescription description){
final SpeciesDescription species=description.getSpeciesContext();
final SkillDescription control=species.getControl();
if (!SimpleBdiArchitecture.class.isAssignableFrom(control.getJavaBase())) {
description.error("A plan can only be defined in a simple_bdi architecture species",IGamlIssue.WRONG_CONTEXT);
return;
}
}
| Method validate() |
public void destroy() throws DestroyFailedException {
if (!destroyed) {
Arrays.fill(asn1Encoding,(byte)0);
client=null;
server=null;
sessionKey.destroy();
flags=null;
authTime=null;
startTime=null;
endTime=null;
renewTill=null;
clientAddresses=null;
destroyed=true;
}
}
| Destroys the ticket and destroys any sensitive information stored in it. |
protected void emit_ArrowFunctionTypeExpression_FunctionTypeExpressionOLD_LeftParenthesisKeyword_1_or___LeftCurlyBracketKeyword_1_FunctionKeyword_3_LeftParenthesisKeyword_5__(EObject semanticObject,ISynNavigable transition,List<INode> nodes){
acceptNodes(transition,nodes);
}
| Ambiguous syntax: '(' | ('{' 'function' '(') This ambiguous syntax occurs at: (rule start) (ambiguity) fpars+=TAnonymousFormalParameter |
public boolean isXmtBusy(){
if (controller == null) {
return false;
}
return (!controller.okToSend());
}
| Implement abstract method to signal if there's a backlog of information waiting to be sent. |
public PlaylistMark(sage.io.SageDataFile inStream) throws java.io.IOException {
inStream.skipBytes(1);
type=inStream.read();
playItemIdRef=inStream.readUnsignedShort();
timestamp=inStream.readInt();
entryESPID=inStream.readUnsignedShort();
duration=inStream.readInt();
}
| Creates a new instance of PlaylistMark |
@Override public boolean onUnbind(Intent intent){
((FileDownloaderBinder)mBinder).clearListeners();
return false;
}
| Called when ALL the bound clients were onbound. |
public static long parseXsDateTime(String value) throws ParseException {
Matcher matcher=XS_DATE_TIME_PATTERN.matcher(value);
if (!matcher.matches()) {
throw new ParseException("Invalid date/time format: " + value,0);
}
int timezoneShift;
if (matcher.group(9) == null) {
timezoneShift=0;
}
else if (matcher.group(9).equalsIgnoreCase("Z")) {
timezoneShift=0;
}
else {
timezoneShift=((Integer.parseInt(matcher.group(12)) * 60 + Integer.parseInt(matcher.group(13))));
if (matcher.group(11).equals("-")) {
timezoneShift*=-1;
}
}
Calendar dateTime=new GregorianCalendar(TimeZone.getTimeZone("GMT"));
dateTime.clear();
dateTime.set(Integer.parseInt(matcher.group(1)),Integer.parseInt(matcher.group(2)) - 1,Integer.parseInt(matcher.group(3)),Integer.parseInt(matcher.group(4)),Integer.parseInt(matcher.group(5)),Integer.parseInt(matcher.group(6)));
if (!TextUtils.isEmpty(matcher.group(8))) {
final BigDecimal bd=new BigDecimal("0." + matcher.group(8));
dateTime.set(Calendar.MILLISECOND,bd.movePointRight(3).intValue());
}
long time=dateTime.getTimeInMillis();
if (timezoneShift != 0) {
time-=timezoneShift * 60000;
}
return time;
}
| Parses an xs:dateTime attribute value, returning the parsed timestamp in milliseconds since the epoch. |
public static String replaceAll(String orig,String toBeReplaced,String replacement){
int quarryLength=toBeReplaced.length();
if (quarryLength <= 0) {
return orig;
}
int index=orig.indexOf(toBeReplaced);
if (index < 0) {
return orig;
}
else {
int from=0;
StringBuffer sb;
if (quarryLength < replacement.length()) {
sb=new StringBuffer(orig.length());
}
else {
sb=new StringBuffer(orig.length() * 2);
}
do {
sb.append(orig.substring(from,index));
sb.append(replacement);
from=index + quarryLength;
index=orig.indexOf(toBeReplaced,from);
}
while (index >= 0);
sb.append(orig.substring(from));
return sb.toString();
}
}
| Replaces all occurrences of the given substring with the given replacement string. |
public static void evolve(BinaryVariable v1,BinaryVariable v2){
if (v1.getNumberOfBits() != v2.getNumberOfBits()) {
throw new FrameworkException("binary variables not same length");
}
for (int i=0; i < v1.getNumberOfBits(); i++) {
boolean value=v1.get(i);
if ((value != v2.get(i)) && PRNG.nextBoolean()) {
v1.set(i,!value);
v2.set(i,value);
}
}
}
| Evolves the specified variables using the HUX operator. |
protected void callChildVisitors(XSLTVisitor visitor,boolean callAttrs){
if (callAttrs) m_selectExpression.getExpression().callVisitors(m_selectExpression,visitor);
super.callChildVisitors(visitor,callAttrs);
}
| Call the children visitors. |
public JSONObject put(String key,Collection value) throws JSONException {
put(key,new JSONArray(value));
return this;
}
| Put a key/value pair in the JSONObject, where the value will be a JSONArray which is produced from a Collection. |
public float toReal(){
return _real;
}
| Returns the real value. |
private void assertFirstTaskIsAsync(BpmnModel bpmnModel){
if (Boolean.TRUE.equals(configurationHelper.getProperty(ConfigurationValue.ACTIVITI_JOB_DEFINITION_ASSERT_ASYNC,Boolean.class))) {
Process process=bpmnModel.getMainProcess();
for ( StartEvent startEvent : process.findFlowElementsOfType(StartEvent.class)) {
for ( SequenceFlow sequenceFlow : startEvent.getOutgoingFlows()) {
String targetRef=sequenceFlow.getTargetRef();
FlowElement targetFlowElement=process.getFlowElement(targetRef);
if (targetFlowElement instanceof Activity) {
Assert.isTrue(((Activity)targetFlowElement).isAsynchronous(),"Element with id \"" + targetRef + "\" must be set to activiti:async=true. All tasks which start the workflow must be asynchronous to prevent certain undesired "+ "transactional behavior, such as records of workflow not being saved on errors. Please refer to Activiti and herd documentations "+ "for details.");
}
}
}
}
}
| Asserts that the first asyncable task in the given model is indeed asynchronous. Only asserts when the configuration is set to true. |
public WampClientBuilder withAuthMethod(ClientSideAuthentication authMethod){
this.authMethods.add(authMethod);
return this;
}
| Use a specific auth method. Can be called multiple times to specify multiple supported auth methods. If this method is not called, anonymous auth is used. |
ResponseHandler executeRequest(HttpServletRequest httpRequest,String url) throws MethodNotAllowedException, IOException, HttpException {
RequestHandler requestHandler=RequestHandlerFactory.createRequestMethod(httpRequest.getMethod());
HttpMethod method=requestHandler.process(httpRequest,url);
method.setFollowRedirects(false);
if (!((HttpMethodBase)method).isAborted()) {
httpClient.executeMethod(method);
if (method.getStatusCode() == 405) {
Header allow=method.getResponseHeader("allow");
String value=allow.getValue();
throw new MethodNotAllowedException("Status code 405 from server",AllowedMethodHandler.processAllowHeader(value));
}
}
return ResponseHandlerFactory.createResponseHandler(method);
}
| Will create the method and execute it. After this the method is sent to a ResponseHandler that is returned. |
public void completePendingPageChanges(){
if (!mPendingAnimations.isEmpty()) {
HashMap<View,Runnable> pendingViews=new HashMap<>(mPendingAnimations);
for ( Map.Entry<View,Runnable> e : pendingViews.entrySet()) {
e.getKey().animate().cancel();
e.getValue().run();
}
}
}
| Finish animation all the views which are animating across pages |
public static int gType(int dim,int lrsDim,int geomType){
return dim * 1000 + lrsDim * 100 + geomType;
}
| Computes the SDO_GTYPE code for the given D, L, and TT components. |
public static int reverse(int number){
String reverse="";
String n=number + "";
for (int i=n.length() - 1; i >= 0; i--) {
reverse+=n.charAt(i);
}
return Integer.parseInt(reverse);
}
| Method reverse returns the reversal of an integer |
@DSComment("From safe class list") @DSSafe(DSCat.SAFE_LIST) @DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 12:56:30.239 -0500",hash_original_method="054A3F820797F764C7C7D974F4C364D1",hash_generated_method="7F5E73E17D01222EB9B6DC63B047D775") public static String toBinaryString(long v){
return IntegralToString.longToBinaryString(v);
}
| Converts the specified long value into its binary string representation. The returned string is a concatenation of '0' and '1' characters. |
public DefaultDependencyManager(Pattern... ignoredPatterns){
ignorePatterns=Stream.of(ignoredPatterns).collect(collectingAndThen(toSet(),null));
}
| Initializes the DependencyManager. |
public boolean hasPreviousPage(){
return getCurrentPage() > 0;
}
| Returns true when the current page is not the first page. |
static String md5(final InputStream in,final int bufferLength) throws IOException {
final byte[] buffer=new byte[bufferLength];
try {
final MessageDigest md=MessageDigest.getInstance("MD5");
final DigestInputStream dis=new DigestInputStream(in,md);
while (dis.read(buffer) != -1) {
}
final byte[] digest=md.digest();
return digestToString(digest);
}
catch ( final NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}
| Read all of the input stream and return it's MD5 digest. |
private boolean isCallerValid(Context context,int authRequirements,String packageToMatch){
boolean shouldBeGoogleSigned=(authRequirements & FLAG_SHOULD_BE_GOOGLE_SIGNED) != 0;
boolean shouldBeSystem=(authRequirements & FLAG_SHOULD_BE_SYSTEM) != 0;
String[] callingPackages=getCallingPackages(context);
PackageManager pm=context.getApplicationContext().getPackageManager();
boolean matchFound=false;
for ( String packageName : callingPackages) {
if (!TextUtils.isEmpty(packageToMatch) && !packageName.equals(packageToMatch)) continue;
matchFound=true;
if ((shouldBeGoogleSigned && !isGoogleSigned(pm,packageName)) || (shouldBeSystem && !isSystemBuild(pm,packageName))) {
return false;
}
}
return matchFound;
}
| Returns whether the callers of the current transaction contains a package that matches the give authentication requirements. |
public void xor(int offset,int width,int value){
BinaryMessage mask=new BinaryMessage(this.size());
mask.load(offset,width,value);
this.xor(mask);
}
| Performs exclusive or of the value against this bitset starting at the offset position using width bits from the value. |
public void clearPeekedIDs(){
peekedEventsContext.set(null);
}
| Use caution while using it! |
private String createDisplayName(Target target,Object[] customConfigurations){
HttpPrefixFetchFilter subtreeFecthFilter=getUriPrefixFecthFilter(customConfigurations);
if (subtreeFecthFilter != null) {
return abbreviateDisplayName(subtreeFecthFilter.getNormalisedPrefix());
}
if (target.getContext() != null) {
return Constant.messages.getString("context.prefixName",target.getContext().getName());
}
else if (target.isInScopeOnly()) {
return Constant.messages.getString("target.allInScope");
}
else if (target.getStartNode() == null) {
if (customConfigurations != null) {
for ( Object customConfiguration : customConfigurations) {
if (customConfiguration instanceof URI) {
return abbreviateDisplayName(((URI)customConfiguration).toString());
}
}
}
return Constant.messages.getString("target.empty");
}
return abbreviateDisplayName(target.getStartNode().getHierarchicNodeName(false));
}
| Creates the display name for the given target and, optionally, the given custom configurations. |
@Nullable public Object row(){
return row;
}
| Gets read results set row. |
ServerSessionManager unregisterConnection(Connection connection){
Iterator<Map.Entry<UUID,Connection>> iterator=connections.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<UUID,Connection> entry=iterator.next();
if (entry.getValue().equals(connection)) {
ServerSessionContext session=clients.get(entry.getKey());
if (session != null) {
session.setConnection(null);
}
iterator.remove();
}
}
return this;
}
| Unregisters a connection. |
protected void drawRobot(boolean initialized){
robotInitialized=initialized;
repaint();
}
| Draws the actual position of the robot. |
private void updateDesiresForUnsuccessfulReading(long spareReadingTime){
long totalWantedGpsTimeMs=(long)(shortTimeWanted * prefs.extraWaitTimeShortTimeMultiplier + shortTimeWanted) + 1;
waitTimeMs=calculateAbsTimeNeeded(totalWantedGpsTimeMs);
if (totalWantedGpsTimeMs + spareReadingTime >= longTimeWanted) {
currTimeWanted=longTimeWanted;
longTimeWanted=(long)(longTimeWanted * prefs.longTimeMultiplier) + 1;
if (longTimeWanted > prefs.maxLongTimeWantedMs) longTimeWanted=prefs.maxLongTimeWantedMs;
}
else {
currTimeWanted=shortTimeWanted;
shortTimeWanted*=prefs.shortTimeUnsuccessfulMultiplier;
if (shortTimeWanted > prefs.shortTimeMaxMs) shortTimeWanted=prefs.shortTimeMaxMs;
}
}
| Updates what this strategy wants to do next given that the last gps reading was unsuccessful |
private void updatePostFailoverPersonalities(Volume volume) throws InternalException {
_log.info("Changing personality of source and targets");
ProtectionSet protectionSet=_dbClient.queryObject(ProtectionSet.class,volume.getProtectionSet());
List<URI> volumeIDs=new ArrayList<URI>();
for ( String volumeString : protectionSet.getVolumes()) {
URI volumeURI;
try {
volumeURI=new URI(volumeString);
volumeIDs.add(volumeURI);
}
catch ( URISyntaxException e) {
_log.error("URI syntax incorrect: ",e);
}
}
for ( URI protectionVolumeID : volumeIDs) {
Volume protectionVolume=_dbClient.queryObject(Volume.class,protectionVolumeID);
if ((protectionVolume.getPersonality().equals(Volume.PersonalityTypes.TARGET.toString())) && (protectionVolume.getRpCopyName().equals(volume.getRpCopyName()))) {
for ( URI potentialTargetVolumeID : volumeIDs) {
Volume potentialTargetVolume=_dbClient.queryObject(Volume.class,potentialTargetVolumeID);
if (potentialTargetVolume.getRSetName() != null && potentialTargetVolume.getRSetName().equals(protectionVolume.getRSetName()) && !potentialTargetVolumeID.equals(protectionVolume.getId())) {
if (protectionVolume.getRpTargets() == null) {
protectionVolume.setRpTargets(new StringSet());
}
protectionVolume.getRpTargets().add(String.valueOf(potentialTargetVolume.getId()));
}
}
_log.info("Change personality of failover target " + protectionVolume.getWWN() + " to source");
protectionVolume.setPersonality(Volume.PersonalityTypes.SOURCE.toString());
volume.setAccessState(Volume.VolumeAccessState.READWRITE.name());
_dbClient.persistObject(protectionVolume);
}
else if (protectionVolume.getPersonality().equals(Volume.PersonalityTypes.SOURCE.toString())) {
_log.info("Change personality of source volume " + protectionVolume.getWWN() + " to target");
protectionVolume.setPersonality(Volume.PersonalityTypes.TARGET.toString());
volume.setAccessState(Volume.VolumeAccessState.NOT_READY.name());
protectionVolume.setRpTargets(new StringSet());
_dbClient.persistObject(protectionVolume);
}
else if (!protectionVolume.getPersonality().equals(Volume.PersonalityTypes.METADATA.toString())) {
_log.info("Target " + protectionVolume.getWWN() + " is a target that remains a target");
}
}
}
| After a failover, we need to swap personalities of source and target volumes, and reset the target lists in each volume. |
public boolean isRangeZoomable(){
return this.rangeZoomable;
}
| Returns the flag that determines whether or not zooming is enabled for the range axis. |
public static String locateChrome(){
String os=Platform.getOS();
List<File> locationsToCheck=new ArrayList<File>();
if (Platform.OS_WIN32.equals(os)) {
String[] envVariables=new String[]{"home","userprofile","home","userprofile","ProgramFiles(X86)","ProgramFiles"};
String[] appendedPaths=new String[]{"\\Local Settings\\Application Data\\Google\\Chrome\\Application\\chrome.exe","\\Local Settings\\Application Data\\Google\\Chrome\\Application\\chrome.exe","\\AppData\\Local\\Google\\Chrome\\Application\\chrome.exe","\\AppData\\Local\\Google\\Chrome\\Application\\chrome.exe","\\Google\\Chrome\\Application\\chrome.exe","\\Google\\Chrome\\Application\\chrome.exe"};
assert envVariables.length == appendedPaths.length;
for (int i=0; i < envVariables.length; i++) {
String envValue=System.getenv(envVariables[i]);
if (envValue != null) {
locationsToCheck.add(new File(envValue + appendedPaths[i]));
}
}
}
else if (Platform.OS_MACOSX.equals(os)) {
locationsToCheck.add(new File("/Applications/ChromeWithSpeedTracer.app"));
String homeDir=System.getenv("HOME");
if (homeDir != null) {
locationsToCheck.add(new File(homeDir + "/Applications/ChromeWithSpeedTracer.app"));
}
}
else {
locationsToCheck.add(new File("/usr/bin/chrome"));
locationsToCheck.add(new File("/usr/local/bin/chrome"));
locationsToCheck.add(new File("/usr/bin/google-chrome"));
locationsToCheck.add(new File("/usr/local/bin/google-chrome"));
locationsToCheck.add(new File("/usr/bin/chromium"));
locationsToCheck.add(new File("/usr/local/bin/chromium"));
locationsToCheck.add(new File("/usr/bin/chromium-browser"));
locationsToCheck.add(new File("/usr/local/bin/chromium-browser"));
}
for ( File location : locationsToCheck) {
if (location.exists() && (Platform.OS_MACOSX.equals(os) || location.isFile())) {
return location.getAbsolutePath();
}
}
return null;
}
| Locates a Chrome installation in one of the default installation directories. |
private void removeMarketingPermission(TechnicalProduct tpRef,MarketingPermission permission,Set<Long> affectedOrgRefs,String orgId,StringBuffer orgIdsThatFailed){
if (permission == null) {
appendIdToString(orgId,orgIdsThatFailed);
}
else {
affectedOrgRefs.add(Long.valueOf(permission.getOrganizationReference().getKey()));
updateStateOfMarketingProducts(tpRef,permission.getOrganizationReference().getTarget(),ServiceStatus.OBSOLETE);
ds.remove(permission);
}
}
| Removes the marketing permission if existing, or appends the organization identifier to the provided string buffer in case the operation failed. |
public static _Fields findByThriftIdOrThrow(int fieldId){
_Fields fields=findByThriftId(fieldId);
if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!");
return fields;
}
| Find the _Fields constant that matches fieldId, throwing an exception if it is not found. |
public ViewChangeEvent(int x,int y){
super(Events.VIEW_CHANGE);
put("x",x);
put("y",y);
}
| Create a new view change event. |
@Override public int onStartCommand(Intent intent,int flags,int startid){
log.info("MurmurService onStartCommand.");
return START_STICKY;
}
| Called whenever the service is requested to start. If the service is already running, this does /not/ create a new instance of the service. Rather, onStartCommand is called again on the existing instance. |
public CTagManager(final Tree<CTag> tagTree,final TagType type,final SQLProvider provider){
m_tagTree=Preconditions.checkNotNull(tagTree,"IE00853: Tag tree argument can't be null");
m_type=Preconditions.checkNotNull(type,"IE00854: Type argument can't be null");
m_provider=Preconditions.checkNotNull(provider,"IE00855: Provider argument can't be null");
}
| Creates a new tag manager object. |
public boolean changeDistance(double dist){
location.set(camera.getDirection());
location.negateLocal();
location.scaleAddLocal(dist,camera.getLookAt());
if (!locInBounds(location)) return (false);
camera.setLocation(location);
updateFromCamera();
updateCrosshair();
updateGeometricState(0);
changed.set(true);
return (true);
}
| Change the distance from the center of rotation while retaining the viewpoint direction. |
public void execute(TransformerImpl transformer) throws TransformerException {
}
| This is the normal call when xsl:fallback is instantiated. In accordance with the XSLT 1.0 Recommendation, chapter 15, "Normally, instantiating an xsl:fallback element does nothing." |
public static <T>T withDataInputStream(Path self,@ClosureParams(value=SimpleType.class,options="java.io.DataInputStream") Closure<T> closure) throws IOException {
return IOGroovyMethods.withStream(newDataInputStream(self),closure);
}
| Create a new DataInputStream for this file and passes it into the closure. This method ensures the stream is closed after the closure returns. |
public XObject execute(XPathContext xctxt) throws javax.xml.transform.TransformerException {
int context=xctxt.getCurrentNode();
DTMIterator nl=m_functionExpr.asIterator(xctxt,context);
XNumber score=SCORE_NONE;
if (null != nl) {
int n;
while (DTM.NULL != (n=nl.nextNode())) {
score=(n == context) ? SCORE_OTHER : SCORE_NONE;
if (score == SCORE_OTHER) {
context=n;
break;
}
}
nl.detach();
}
return score;
}
| Test a node to see if it matches the given node test. |
public static void createTable(SQLiteDatabase db,boolean ifNotExists){
String constraint=ifNotExists ? "IF NOT EXISTS " : "";
db.execSQL("CREATE TABLE " + constraint + "'ADDRESS_BOOK' ("+ "'_id' INTEGER PRIMARY KEY ,"+ "'NAME' TEXT,"+ "'AUTHOR' TEXT);");
}
| Creates the underlying database table. |
public ArrayList<Integer> elementsStartingWith(String s){
ArrayList<Integer> alist=new ArrayList<Integer>();
for (int i=0; i < m_size; i++) if (getString(i).startsWith(s)) alist.add(new Integer(i));
return alist;
}
| Sequentially walk through the entire list matching the String components against the given string |
public CompressorStreamDeflater(IDatChunkWriter idatCw,int maxBlockLen,long totalLen,Deflater def){
super(idatCw,maxBlockLen,totalLen);
this.deflater=def == null ? new Deflater() : def;
this.deflaterIsOwn=def == null;
}
| if a deflater is passed, it must be already reset. It will not be released on close |
public static int cs_dropzeros(Dcs A){
return (Dcs_fkeep.cs_fkeep(A,new Cs_nonzero(),null));
}
| Removes numerically zero entries from a matrix. |
public void updateNCharacterStream(int columnIndex,java.io.Reader x) throws SQLException {
throw new SQLFeatureNotSupportedException(resBundle.handleGetObject("cachedrowsetimpl.featnotsupp").toString());
}
| Updates the designated column with a character stream value. The driver does the necessary conversion from Java character format to the national character set in the database. It is intended for use when updating <code>NCHAR</code>,<code>NVARCHAR</code> and <code>LONGNVARCHAR</code> columns. The updater methods are used to update column values in the current row or the insert row. The updater methods do not update the underlying database; instead the <code>updateRow</code> or <code>insertRow</code> methods are called to update the database. <P><B>Note:</B> Consult your JDBC driver documentation to determine if it might be more efficient to use a version of <code>updateNCharacterStream</code> which takes a length parameter. |
public ClassificationDataSet(DataSet dataSet,int predicting){
this(dataSet.getDataPoints(),predicting);
if (numericalVariableNames == null) {
numericalVariableNames=new ArrayList<String>();
String s="";
for (int i=0; i < getNumNumericalVars(); i++) numericalVariableNames.add(s);
}
for (int i=0; i < getNumNumericalVars(); i++) this.numericalVariableNames.set(i,dataSet.getNumericName(i));
}
| Creates a new data set for classification problems. |
@Override public ServiceExceptionExecution rethrow(String msg){
return new ServiceExceptionExecution(msg,this);
}
| Rethrows an exception to record the full stack trace, both caller and callee. |
public void removeSingleInterest(Object key,int interestType,boolean isDurable,boolean receiveUpdatesAsInvalidates){
this.pool.getRITracker().removeSingleInterest(this.region,key,interestType,isDurable,receiveUpdatesAsInvalidates);
}
| Support for server-side interest registration |
public CssPropertyData cssPropertyToData(String key,CssPropertySignature sig){
CssPropertyData data=new CssPropertyData(key,sig);
new Inspector(data).inspect();
return data;
}
| Generates a data map for the given signature. |
public static void drawRotatedString(AttributedString text,Graphics2D g2,float x,float y,TextAnchor textAnchor,double angle,TextAnchor rotationAnchor){
ParamChecks.nullNotPermitted(text,"text");
float[] textAdj=deriveTextBoundsAnchorOffsets(g2,text,textAnchor,null);
float[] rotateAdj=deriveRotationAnchorOffsets(g2,text,rotationAnchor);
drawRotatedString(text,g2,x + textAdj[0],y + textAdj[1],angle,x + textAdj[0] + rotateAdj[0],y + textAdj[1] + rotateAdj[1]);
}
| Draws a rotated string. |
public boolean hasBatchId(){
return hasExtension(BatchId.class);
}
| Returns whether it has the batch identifier. |
static void appendTime(StringBuilder buff,long nanos,boolean alwaysAddMillis){
if (nanos < 0) {
buff.append('-');
nanos=-nanos;
}
long ms=nanos / 1000000;
nanos-=ms * 1000000;
long s=ms / 1000;
ms-=s * 1000;
long m=s / 60;
s-=m * 60;
long h=m / 60;
m-=h * 60;
StringUtils.appendZeroPadded(buff,2,h);
buff.append(':');
StringUtils.appendZeroPadded(buff,2,m);
buff.append(':');
StringUtils.appendZeroPadded(buff,2,s);
if (alwaysAddMillis || ms > 0 || nanos > 0) {
buff.append('.');
int start=buff.length();
StringUtils.appendZeroPadded(buff,3,ms);
if (nanos > 0) {
StringUtils.appendZeroPadded(buff,6,nanos);
}
for (int i=buff.length() - 1; i > start; i--) {
if (buff.charAt(i) != '0') {
break;
}
buff.deleteCharAt(i);
}
}
}
| Append a time to the string builder. |
public Criteria or(){
Criteria criteria=createCriteriaInternal();
oredCriteria.add(criteria);
return criteria;
}
| This method was generated by MyBatis Generator. This method corresponds to the database table invitation_projects |
public boolean isProcessed(){
Object oo=get_Value(COLUMNNAME_Processed);
if (oo != null) {
if (oo instanceof Boolean) return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
| Get Processed. |
static void changeClassName(Identifier oldName,Identifier newName){
((ClassType)Type.tClass(oldName)).className=newName;
}
| We have learned that a signature means something other that what we thought it meant. Live with it: Change all affected data structures to reflect the new name of the old type. <p> (This is necessary because of an ambiguity between the low-level signatures of inner types and their manglings. Note that the latter are also valid class names.) |
private String extractPath(final String uri){
return DefaultWildcardStreamLocator.stripQueryPath(uri.replace(PREFIX,StringUtils.EMPTY));
}
| Replaces the protocol specific prefix and removes the query path if it exist, since it should not be accepted. |
public void invoke(BasicBlock bb){
BURS_StateCoder burs=makeCoder();
for (Enumeration<Instruction> e=bb.forwardRealInstrEnumerator(); e.hasMoreElements(); ) {
Instruction s=e.nextElement();
AbstractBURS_TreeNode tn=buildTree(s);
label(tn);
mark(tn,(byte)1);
generateTree(tn,burs);
}
}
| Build BURS trees for the basic block <code>bb</code>, label the trees, and then generate MIR instructions based on the labeling. |
@DSComment("From safe class list") @DSSafe(DSCat.SAFE_LIST) @DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 12:57:40.009 -0500",hash_original_method="B36EFEED8A01C5AB548445C2A30D3515",hash_generated_method="AB254B7381DE3B17EA718AC261CF38C6") public static void fill(byte[] array,byte value){
for (int i=0; i < array.length; i++) {
array[i]=value;
}
}
| Fills the specified array with the specified element. |
public EmpiricalDistribution(Collection<? extends Assignment> samples){
this();
for ( Assignment a : samples) {
addSample(a);
}
}
| Constructs a new empirical distribution with a set of samples samples |
private static void createInitialEdges(final View view,final Collection<FunctionBlock> passedFunctions,final Map<BasicBlock,ViewNode> nodeMap){
for ( final FunctionBlock functionBlock : passedFunctions) {
final Function function=functionBlock.getFunction();
for ( final BlockEdge edge : function.getGraph().getEdges()) {
final ViewEdge newEdge=view.createEdge(nodeMap.get(edge.getSource()),nodeMap.get(edge.getTarget()),edge.getType());
newEdge.setColor(getEdgeColor(edge));
}
}
}
| Creates view edges for all edges in the passed functions. |
public void writeFile(String directoryName) throws CannotCompileException, IOException {
DataOutputStream out=makeFileOutput(directoryName);
try {
toBytecode(out);
}
finally {
out.close();
}
}
| Writes a class file represented by this <code>CtClass</code> object on a local disk. Once this method is called, further modifications are not possible any more. |
public static VOSubscriptionDetails toVOSubscriptionDetails(Subscription subscription,LocalizerFacade facade){
if (subscription == null) {
return null;
}
VOSubscriptionDetails voSubDet=new VOSubscriptionDetails();
fillAllFields(voSubDet,subscription,facade);
fillVOSubscriptionDetails(voSubDet,subscription,facade);
updateValueObject(voSubDet,subscription);
return voSubDet;
}
| Converts the given domain object to a value object containing the identifying attributes. |
public static String encode(byte[] input){
if (input.length == 0) {
return "";
}
int zeros=0;
while (zeros < input.length && input[zeros] == 0) {
++zeros;
}
input=Arrays.copyOf(input,input.length);
char[] encoded=new char[input.length * 2];
int outputStart=encoded.length;
for (int inputStart=zeros; inputStart < input.length; ) {
encoded[--outputStart]=ALPHABET[divmod(input,inputStart,256,58)];
if (input[inputStart] == 0) {
++inputStart;
}
}
while (outputStart < encoded.length && encoded[outputStart] == ENCODED_ZERO) {
++outputStart;
}
while (--zeros >= 0) {
encoded[--outputStart]=ENCODED_ZERO;
}
return new String(encoded,outputStart,encoded.length - outputStart);
}
| Encodes the given bytes as a base58 string (no checksum is appended). |
public ProblemException build(){
if (this.message == null) {
this.message=this.cause != null ? this.cause.getMessage() : null;
}
if (this.message == null) {
this.message="Empty message in exception";
}
return new ProblemException(this);
}
| Builds the exception. |
public RetrievalPerformanceResult run(Database database,Relation<O> relation,Relation<?> lrelation){
final DistanceQuery<O> distQuery=database.getDistanceQuery(relation,getDistanceFunction());
final DBIDs ids=DBIDUtil.randomSample(relation.getDBIDs(),sampling,random);
ModifiableDBIDs posn=DBIDUtil.newHashSet();
ModifiableDoubleDBIDList nlist=DBIDUtil.newDistanceDBIDList(relation.size());
TObjectIntHashMap<Object> counters=new TObjectIntHashMap<>();
double map=0., mroc=0.;
double[] knnperf=new double[maxk];
int samples=0;
FiniteProgress objloop=LOG.isVerbose() ? new FiniteProgress("Processing query objects",ids.size(),LOG) : null;
for (DBIDIter iter=ids.iter(); iter.valid(); iter.advance()) {
Object label=lrelation.get(iter);
findMatches(posn,lrelation,label);
if (posn.size() > 0) {
computeDistances(nlist,iter,distQuery,relation);
if (nlist.size() != relation.size() - (includeSelf ? 0 : 1)) {
LOG.warning("Neighbor list does not have the desired size: " + nlist.size());
}
map+=AveragePrecisionEvaluation.STATIC.evaluate(posn,nlist);
mroc+=ROCEvaluation.STATIC.evaluate(posn,nlist);
KNNEvaluator.STATIC.evaluateKNN(knnperf,nlist,lrelation,counters,label);
samples+=1;
}
LOG.incrementProcessed(objloop);
}
LOG.ensureCompleted(objloop);
if (samples < 1) {
throw new AbortException("No object matched - are labels parsed correctly?");
}
if (!(map >= 0) || !(mroc >= 0)) {
throw new AbortException("NaN in MAP/ROC.");
}
map/=samples;
mroc/=samples;
LOG.statistics(new DoubleStatistic(PREFIX + ".map",map));
LOG.statistics(new DoubleStatistic(PREFIX + ".rocauc",mroc));
LOG.statistics(new DoubleStatistic(PREFIX + ".samples",samples));
for (int k=0; k < maxk; k++) {
knnperf[k]=knnperf[k] / samples;
LOG.statistics(new DoubleStatistic(PREFIX + ".knn-" + (k + 1),knnperf[k]));
}
return new RetrievalPerformanceResult(samples,map,mroc,knnperf);
}
| Run the algorithm |
public int addBigrams(String word1,String word2){
if (mIme != null && mIme.getCurrentWord().isAutoCapitalized()) {
word2=Character.toLowerCase(word2.charAt(0)) + word2.substring(1);
}
int freq=super.addBigram(word1,word2,FREQUENCY_FOR_TYPED);
if (freq > FREQUENCY_MAX) freq=FREQUENCY_MAX;
synchronized (mPendingWritesLock) {
if (freq == FREQUENCY_FOR_TYPED || mPendingWrites.isEmpty()) {
mPendingWrites.add(new Bigram(word1,word2,freq));
}
else {
Bigram bi=new Bigram(word1,word2,freq);
mPendingWrites.remove(bi);
mPendingWrites.add(bi);
}
}
return freq;
}
| Pair will be added to the userbigram database. |
public boolean requiresFiles(){
boolean result=false;
if (getRequiredFiles() != null && getRequiredFiles().size() > 0) {
result=true;
}
return result;
}
| Checks whether this cloudlet requires any files or not. |
public void cancelScheduledEvent(URI eventId){
client.post(String.class,PathConstants.SCHEDULED_EVENTS_CANCELLATION_URL,eventId);
}
| Cancellation an recurring event <p> API Call: <tt>POST /catalog/events/{id}/cancel</tt> |
@DSComment("Private Method") @DSBan(DSCat.PRIVATE_METHOD) @DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 12:31:30.612 -0500",hash_original_method="614329ACA245384517EF28FF3609B04B",hash_generated_method="9BACAE2057F7A0E8F3874F7616D578C1") private void adjustViewsUpOrDown(){
final int childCount=getChildCount();
if (childCount > 0) {
int delta;
View child;
if (!mStackFromBottom) {
child=getChildAt(0);
delta=child.getTop() - mListPadding.top;
if (mFirstPosition != 0) {
delta-=mVerticalSpacing;
}
if (delta < 0) {
delta=0;
}
}
else {
child=getChildAt(childCount - 1);
delta=child.getBottom() - (getHeight() - mListPadding.bottom);
if (mFirstPosition + childCount < mItemCount) {
delta+=mVerticalSpacing;
}
if (delta > 0) {
delta=0;
}
}
if (delta != 0) {
offsetChildrenTopAndBottom(-delta);
}
}
}
| Make sure views are touching the top or bottom edge, as appropriate for our gravity |
@Override protected AccessCheckingPortal createPortal(final ConfigurableFactoryContext ctx){
String rejectedMessage=getStringValue(ctx,"rejected");
ChatCondition condition=getCondition(ctx);
ChatAction action=getAction(ctx);
if (rejectedMessage != null) {
return new ConditionAndActionPortal(condition,rejectedMessage,action);
}
else {
return new ConditionAndActionPortal(condition,action);
}
}
| Create a condition checking portal. |
public CustomMediaSizeName findCustomMedia(MediaSizeName media){
if (customMediaSizeNames == null) {
return null;
}
for (int i=0; i < customMediaSizeNames.length; i++) {
CustomMediaSizeName custom=(CustomMediaSizeName)customMediaSizeNames[i];
MediaSizeName msn=custom.getStandardMedia();
if (media.equals(msn)) {
return customMediaSizeNames[i];
}
}
return null;
}
| Finds matching CustomMediaSizeName of given media. |
@Override public void eUnset(int featureID){
switch (featureID) {
case DatatypePackage.OBJECT_PROPERTY_TYPE__TYPE:
setType((Type)null);
return;
}
super.eUnset(featureID);
}
| <!-- begin-user-doc --> <!-- end-user-doc --> |
public void addCostsPerUser(final UserAssignmentCostsType userAssigmentCostsType,final UserAssignmentFactors userAssignmentsFactors){
final Set<Long> userKeys=userAssignmentsFactors.getUserKeys();
for ( long userKey : userKeys) {
final UserAssignmentDetails user=userAssignmentsFactors.getUserAssignmentDetails(Long.valueOf(userKey));
final UserAssignmentCostsByUserType userAssignmentCostsByUserType=factory.createUserAssignmentCostsByUserType();
userAssignmentCostsByUserType.setUserId(user.getUserId());
userAssignmentCostsByUserType.setFactor(BigDecimal.valueOf(user.getUsageDetails().getFactor()));
userAssigmentCostsType.getUserAssignmentCostsByUser().add(userAssignmentCostsByUserType);
}
}
| Adds a UserAssignmentCostsByUser node for one user assignment with userid, factor and price. |
private void createNewLineString(Fusiontables fusiontables,String tableId,Track track) throws IOException {
String values=SendFusionTablesUtils.formatSqlValues(track.getName(),track.getDescription(),SendFusionTablesUtils.getKmlLineString(track.getLocations()));
String sql="INSERT INTO " + tableId + " (name,description,geometry) VALUES "+ values;
HttpContent content=ByteArrayContent.fromString(null,"sql=" + sql);
GoogleUrl url=new GoogleUrl("https://www.googleapis.com/fusiontables/v1/query");
fusiontables.getRequestFactory().buildPostRequest(url,content).execute();
}
| Creates a new row in Google Fusion Tables representing the track as a line segment. |
public GridSpacingDecoration(int spacing,int numColumns,int viewType){
this.spacing=spacing;
this.numColumns=numColumns;
this.viewType=viewType;
}
| Create a new ItemDecorator for use with a RecyclerView |
public MethodRefITCase(String name){
super(name);
}
| Construct a new instance of this test case. |
@Override public Object importService(ImportedServiceDescriptor serviceDescriptor) throws ServiceImporterException {
try {
return serviceDescriptor.metaInfo(ApplicationContext.class).getBean(serviceDescriptor.identity().toString(),serviceDescriptor.type());
}
catch ( Throwable e) {
throw new ServiceImporterException("Could not import Spring service with id " + serviceDescriptor.identity(),e);
}
}
| Import a service from Spring by looking it up in the ApplicationContext. |
private void readQuantSpectralCoeffs(int selector,int codingFlag,int[] mantissas,int numCodes){
if (selector == 1) {
numCodes/=2;
}
if (codingFlag != 0) {
int numBits=clc_length_tab[selector];
if (selector > 1) {
for (int i=0; i < numCodes; i++) {
int code=(numBits != 0 ? signExtend(br.read(numBits),numBits) : 0);
mantissas[i]=code;
}
}
else {
for (int i=0; i < numCodes; i++) {
int code=(numBits != 0 ? br.read(numBits) : 0);
mantissas[i * 2]=mantissa_clc_tab[code >> 2];
mantissas[i * 2 + 1]=mantissa_clc_tab[code & 3];
}
}
}
else {
if (selector != 1) {
for (int i=0; i < numCodes; i++) {
int huffSymb=spectral_coeff_tab[selector - 1].getVLC2(br,3);
huffSymb+=1;
int code=huffSymb >> 1;
if ((huffSymb & 1) != 0) {
code=-code;
}
mantissas[i]=code;
}
}
else {
for (int i=0; i < numCodes; i++) {
int huffSymb=spectral_coeff_tab[selector - 1].getVLC2(br,3);
mantissas[i * 2]=mantissa_vlc_tab[huffSymb * 2];
mantissas[i * 2 + 1]=mantissa_vlc_tab[huffSymb * 2 + 1];
}
}
}
}
| Mantissa decoding |
public void eliminarConsultaExecuteLogic(ActionMapping mappings,ActionForm form,HttpServletRequest request,HttpServletResponse response){
String id=request.getParameter(Constants.ID);
if (StringUtils.isNotBlank(id)) {
try {
getGestionConsultasBI(request).eliminarConsultas(new String[]{id});
goBackExecuteLogic(mappings,form,request,response);
return;
}
catch ( ConsultaActionNotAllowedException e) {
obtenerErrores(request,true).add(ExceptionMapper.getErrorsExcepcion(request,e));
}
}
goLastClientExecuteLogic(mappings,form,request,response);
}
| Elimina la consulta actual. |
public static RemoveNetworkParams create(@NotNull String netId){
return new RemoveNetworkParams().withNetworkId(netId);
}
| Creates arguments holder with required parameters. |
public static void initialize(Class<?>... classes){
for ( Class<?> clazz : classes) {
try {
Class.forName(clazz.getName(),true,clazz.getClassLoader());
}
catch ( ClassNotFoundException e) {
throw new AssertionError(e);
}
}
}
| Ensures that the given classes are initialized, as described in <a href="http://java.sun.com/docs/books/jls/third_edition/html/execution.html#12.4.2"> JLS Section 12.4.2</a>. <p>WARNING: Normally it's a smell if a class needs to be explicitly initialized, because static state hurts system maintainability and testability. In cases when you have no choice while inter-operating with a legacy framework, this method helps to keep the code less ugly. |
protected boolean isInfoEnabled(){
return trace.isInfoEnabled();
}
| Check if info trace level is enabled. |
public Iterator fieldValuesIterator(){
return super.iterator();
}
| Returns an iterator over the fieldValues Object[] instances |
public KillsQuestSlotNeedUpdateCondition(String quest,int index,List<String> creatures,boolean do_update){
this.questSlot=checkNotNull(quest);
this.questIndex=index;
this.creatures=creatures;
this.do_update=do_update;
this.questGroupIndex=-1;
this.allcreatures=null;
}
| Creates a new KillsQuestSlotNeedUpdateCondition. |
public static char toLowerAscii(char c){
if (isUppercaseAlpha(c)) {
c+=(char)0x20;
}
return c;
}
| Lowers uppercase ASCII char. |
public void configureManagersPR2(){
mode=PR3MODE;
InstanceManager.store(getPowerManager(),jmri.PowerManager.class);
InstanceManager.setThrottleManager(getThrottleManager());
jmri.InstanceManager.setProgrammerManager(getProgrammerManager());
}
| Configure the subset of LocoNet managers valid for the PR3 in PR2 mode. |
public void testLogReadbackWithFiltering() throws Exception {
File logDir=prepareLogDir("testLogReadbackWithFiltering");
DiskLog log=openLog(logDir,false);
long seqno=0;
for (int i=1; i <= 3; i++) {
this.writeEventsToLog(log,seqno,7);
seqno+=7;
LogConnection conn=log.connect(false);
THLEvent e=this.createFilteredTHLEvent(seqno,seqno + 2,(short)i);
conn.store(e,false);
conn.commit();
conn.release();
seqno+=3;
}
assertEquals("Should have seqno 27 as last entry",27,log.getMaxSeqno());
log.validate();
log.release();
DiskLog log2=openLog(logDir,true);
log2.validate();
LogConnection conn2=log2.connect(true);
assertEquals("Should have seqno 27 as last entry on reopen",27,log.getMaxSeqno());
seqno=0;
assertTrue("Seeking sequence number 1",conn2.seek(seqno,(short)0));
for (int i=1; i <= 24; i++) {
THLEvent e=conn2.next();
ReplDBMSEvent replEvent=(ReplDBMSEvent)e.getReplEvent();
if (i % 8 == 0) {
assertTrue("Expect a ReplDBMSFilteredEvent",replEvent instanceof ReplDBMSFilteredEvent);
ReplDBMSFilteredEvent filterEvent=(ReplDBMSFilteredEvent)replEvent;
assertEquals("Expected start seqno of filtered events",seqno,filterEvent.getSeqno());
assertEquals("Expected end seqno of filtered events",seqno + 2,filterEvent.getSeqnoEnd());
seqno+=3;
}
else {
assertEquals("Expected seqno of next event",seqno,replEvent.getSeqno());
seqno++;
}
}
log2.release();
}
| Confirm that we can write to and read from the log a stream of events that include filtered events. |
public NodeMetaData(final String platform,final String application,final NodeVersion version,final int networkId,final int featuresBitmask){
this.platform=platform;
this.application=application;
this.version=null == version ? NodeVersion.ZERO : version;
this.networkId=networkId;
this.featuresBitmask=featuresBitmask;
}
| Creates a new node meta data. |
private void storeComputes(String rpLink,ServiceDocumentQueryResult queryResult){
Map<String,ComputeState> computes=new HashMap<>();
queryResult.documentLinks.forEach(null);
if (rpLink != null) {
ResourcePoolData rpData=this.result.resourcesPools.get(rpLink);
rpData.computeStateLinks.addAll(computes.keySet());
}
for ( Map.Entry<String,ComputeState> computeEntry : computes.entrySet()) {
String computeLink=computeEntry.getKey();
ComputeState compute=computeEntry.getValue();
this.result.computesByLink.put(computeLink,compute);
Set<String> rpLinks=this.result.rpLinksByComputeLink.get(computeLink);
if (rpLinks == null) {
rpLinks=new HashSet<String>();
this.result.rpLinksByComputeLink.put(computeLink,rpLinks);
}
if (rpLink != null) {
rpLinks.add(rpLink);
}
}
}
| Stores the retrieved compute states into the QueryResult instance. The rpLink may be null in case the given computes do not fall into any resource pool. |
public static TypeReference findCommonSuperclass(TypeReference t1,TypeReference t2){
if (t1 == t2) {
return t1;
}
if (t1.isPrimitiveType() || t2.isPrimitiveType()) {
if (t1.isIntLikeType() && t2.isIntLikeType()) {
if (t1.isIntType() || t2.isIntType()) {
return TypeReference.Int;
}
else if (t1.isCharType() || t2.isCharType()) {
return TypeReference.Char;
}
else if (t1.isShortType() || t2.isShortType()) {
return TypeReference.Short;
}
else if (t1.isByteType() || t2.isByteType()) {
return TypeReference.Byte;
}
else {
if (VM.VerifyAssertions) VM._assert(VM.NOT_REACHED);
return null;
}
}
else if (t1.isWordLikeType() && t2.isWordLikeType()) {
return TypeReference.Word;
}
else {
return null;
}
}
if (t1 == TypeReference.NULL_TYPE) {
return t2;
}
else if (t2 == TypeReference.NULL_TYPE) {
return t1;
}
if (DBG_TYPE) {
VM.sysWrite("finding common supertype of " + t1 + " and "+ t2);
}
int arrayDimensions=0;
while (t1.isArrayType() && t2.isArrayType()) {
++arrayDimensions;
t1=t1.getArrayElementType();
t2=t2.getArrayElementType();
}
if (t1.isPrimitiveType() || t2.isPrimitiveType()) {
TypeReference type=TypeReference.JavaLangObject;
if (t1 == t2) {
if (t1.isUnboxedType()) {
arrayDimensions++;
type=t1;
}
else {
if (VM.VerifyAssertions) VM._assert(VM.NOT_REACHED);
}
}
--arrayDimensions;
while (arrayDimensions-- > 0) {
type=type.getArrayTypeForElementType();
}
if (DBG_TYPE) {
VM.sysWrite("one is a primitive array, so supertype is " + type);
}
return type;
}
if (t1.isArrayType() || t2.isArrayType()) {
TypeReference type=TypeReference.JavaLangObject;
while (arrayDimensions-- > 0) {
type=type.getArrayTypeForElementType();
}
if (DBG_TYPE) {
VM.sysWrite("differing dimensionalities for arrays, so supertype is " + type);
}
return type;
}
RVMClass c1=(RVMClass)t1.peekType();
RVMClass c2=(RVMClass)t2.peekType();
if (c1 != null && c2 != null) {
Stack<RVMClass> s1=new Stack<RVMClass>();
do {
s1.push(c1);
c1=c1.getSuperClass();
}
while (c1 != null);
Stack<RVMClass> s2=new Stack<RVMClass>();
do {
s2.push(c2);
c2=c2.getSuperClass();
}
while (c2 != null);
if (DBG_TYPE) {
VM.sysWrite("stack 1: " + s1);
}
if (DBG_TYPE) {
VM.sysWrite("stack 2: " + s2);
}
TypeReference best=TypeReference.JavaLangObject;
while (!s1.empty() && !s2.empty()) {
RVMClass temp=s1.pop();
if (temp == s2.pop()) {
best=temp.getTypeRef();
}
else {
break;
}
}
if (DBG_TYPE) {
VM.sysWrite("common supertype of the two classes is " + best);
}
while (arrayDimensions-- > 0) {
best=best.getArrayTypeForElementType();
}
return best;
}
else {
if (DBG_TYPE && c1 == null) {
VM.sysWrite(c1 + " is not loaded, using Object as common supertype");
}
if (DBG_TYPE && c2 == null) {
VM.sysWrite(c2 + " is not loaded, using Object as common supertype");
}
TypeReference common=TypeReference.JavaLangObject;
while (arrayDimensions-- > 0) {
common=common.getArrayTypeForElementType();
}
return common;
}
}
| Returns a common superclass of the two types. NOTE: If both types are references, but are not both loaded, then this may be a conservative approximation (java.lang.Object). |
public void done(){
if (resultNumber == (end + 1)) {
getPreviousAndNextLinksForPagination(start != 0,true,requestAndResponse,result);
}
else if (start == 0 && !anyMatches) {
result.append(noMatchesText);
}
else if (start != 0 && !anyMatches) {
result.append(servletText.sentenceNoMoreResults());
}
else if (start != 0) {
getPreviousAndNextLinksForPagination(true,false,requestAndResponse,result);
}
}
| The iterator should call this when it has finished iterating to print out the right message. |
public DataSource_Definition(Service parentService,String name,String hostname){
super(parentService);
this.name=name;
this.hostname=hostname;
}
| Creates a new <code>Server_Definition</code> object |
protected void parseAuthority(final String original,final boolean escaped) throws URIException {
_is_reg_name=_is_server=_is_hostname=_is_IPv4address=_is_IPv6reference=false;
final String charset=getProtocolCharset();
boolean hasPort=true;
int from=0;
int next=original.indexOf('@');
if (next != -1) {
_userinfo=(escaped) ? original.substring(0,next).toCharArray() : encode(original.substring(0,next),allowed_userinfo,charset);
from=next + 1;
}
next=original.indexOf('[',from);
if (next >= from) {
next=original.indexOf(']',from);
if (next == -1) {
throw new URIException(URIException.PARSING,"IPv6reference");
}
else {
next++;
}
_host=(escaped) ? original.substring(from,next).toCharArray() : encode(original.substring(from,next),allowed_IPv6reference,charset);
_is_IPv6reference=true;
}
else {
next=original.indexOf(':',from);
if (next == -1) {
next=original.length();
hasPort=false;
}
_host=original.substring(from,next).toCharArray();
if (validate(_host,IPv4address)) {
_is_IPv4address=true;
}
else if (validate(_host,hostname)) {
_is_hostname=true;
}
else {
_is_reg_name=true;
}
}
if (_is_reg_name) {
_is_server=_is_hostname=_is_IPv4address=_is_IPv6reference=false;
if (escaped) {
_authority=original.toCharArray();
if (!validate(_authority,reg_name)) {
throw new URIException("Invalid authority");
}
}
else {
_authority=encode(original,allowed_reg_name,charset);
}
}
else {
if (original.length() - 1 > next && hasPort && original.charAt(next) == ':') {
from=next + 1;
try {
_port=Integer.parseInt(original.substring(from));
}
catch ( final NumberFormatException error) {
throw new URIException(URIException.PARSING,"invalid port number");
}
}
final StringBuffer buf=new StringBuffer();
if (_userinfo != null) {
buf.append(_userinfo);
buf.append('@');
}
if (_host != null) {
buf.append(_host);
if (_port != -1) {
buf.append(':');
buf.append(_port);
}
}
_authority=buf.toString().toCharArray();
_is_server=true;
}
}
| Parse the authority component. |
public static void printf(String format,Object... args){
out.printf(LOCALE,format,args);
out.flush();
}
| Print a formatted string to standard output using the specified format string and arguments, and flush standard output. |
public JSONWriter endObject() throws JSONException {
return this.end('k','}');
}
| End an object. This method most be called to balance calls to <code>object</code>. |
protected Object readResolve() throws ObjectStreamException {
EnumSyntax[] theTable=getEnumValueTable();
if (theTable == null) {
throw new InvalidObjectException("Null enumeration value table for class " + getClass());
}
int theOffset=getOffset();
int theIndex=value - theOffset;
if (0 > theIndex || theIndex >= theTable.length) {
throw new InvalidObjectException("Integer value = " + value + " not in valid range "+ theOffset+ ".."+ (theOffset + theTable.length - 1)+ "for class "+ getClass());
}
EnumSyntax result=theTable[theIndex];
if (result == null) {
throw new InvalidObjectException("No enumeration value for integer value = " + value + "for class "+ getClass());
}
return result;
}
| During object input, convert this deserialized enumeration instance to the proper enumeration value defined in the enumeration attribute class. |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.