code
stringlengths 10
174k
| nl
stringlengths 3
129k
|
---|---|
final public void enable_tracing(){
}
| Enable tracing. |
@Override public void endElement(String uri,String localName,String qName){
try {
this.handler.endElement();
}
catch ( RuntimeException exception) {
handleException(exception);
}
finally {
this.handler=this.handler.getParent();
}
}
| Parses closing tag of XML element using corresponding element handler. |
public void init(CredentialInfo info,APIAccessCallBack apiAccessCallBack,Context context){
IdentityProxy.clientID=info.getClientID();
IdentityProxy.clientSecret=info.getClientSecret();
this.apiAccessCallBack=apiAccessCallBack;
this.context=context;
SharedPreferences mainPref=context.getSharedPreferences(Constants.APPLICATION_PACKAGE,Context.MODE_PRIVATE);
Editor editor=mainPref.edit();
editor.putString(Constants.CLIENT_ID,clientID);
editor.putString(Constants.CLIENT_SECRET,clientSecret);
editor.putString(Constants.TOKEN_ENDPOINT,info.getTokenEndPoint());
editor.commit();
setAccessTokenURL(info.getTokenEndPoint());
AccessTokenHandler accessTokenHandler=new AccessTokenHandler(info,this);
accessTokenHandler.obtainAccessToken();
}
| Initializing the IDP plugin and obrtaining the access token. |
static TemplateModelException newMethodArgInvalidValueException(String methodName,int argIdx,Object... details){
return new _TemplateModelException(methodName,"(...) argument #",Integer.valueOf(argIdx + 1)," had invalid value: ",details);
}
| The type of the argument was good, but it's value wasn't. |
public static Typeface androidNation(Context context){
return FontSourceProcessor.process(R.raw.androidnation,context);
}
| Android Nation font face |
public static boolean[] toBooleanArray(double[] array){
boolean[] result=new boolean[array.length];
for (int i=0; i < array.length; i++) {
result[i]=array[i] > 0;
}
return result;
}
| Coverts given doubles array to array of booleans. |
@SuppressWarnings({"rawtypes","unchecked"}) private static Object convertArray(Object array,Class<?> fieldType,Class<?> itemType){
int len=Array.getLength(array);
if (fieldType.equals(List.class)) {
List list=new ArrayList();
for (int i=0; i < len; i++) {
list.add(Array.get(array,i));
}
return list;
}
else if (fieldType.isArray() && fieldType.getComponentType().isAssignableFrom(itemType)) {
if (itemType.equals(fieldType.getComponentType())) {
return array;
}
Object targetArray=Array.newInstance(fieldType.getComponentType(),len);
for (int i=0; i < len; i++) {
Array.set(targetArray,i,Array.get(array,i));
}
return targetArray;
}
else {
String message=String.format("Cannot convert array of %s to %s",itemType,fieldType);
throw new BindingException(message);
}
}
| Converts the array to the appropriate type for binding. |
private final int addStdMove(GameTree gt,String moveStr){
return gt.addMove(moveStr,"",0,"","");
}
| Add a move to the game tree, with no comments or annotations. |
public BasicStroke(Cap cap,Join join,float miter,float[] intervals,float phase){
mCap=cap;
mJoin=join;
mMiter=miter;
mIntervals=intervals;
}
| Build a new basic stroke style. |
public BasicArchImpl(){
_id=ISicresAdminDefsKeys.NULL_ID;
_name="";
}
| Construye un objeto de la clase. |
public Notification(String title){
this(title,null,null,null);
}
| Creates notification object with specified title. |
synchronized void ensureValid(){
if (isClosed()) {
throw new ClosedException();
}
}
| Validates that the bytebuffer instance is valid (aka not closed). If it is closed, then we raise a ClosedException This doesn't really need to be synchronized, but lint won't shut up otherwise |
static public Boolean isPortMetricsAllocationEnabled(StorageSystem.Type systemType){
Boolean portMetricsAllocationEnabled=true;
try {
portMetricsAllocationEnabled=Boolean.valueOf(customConfigHandler.getComputedCustomConfigValue(CustomConfigConstants.PORT_ALLOCATION_METRICS_ENABLED,getStorageSystemTypeName(systemType),null));
}
catch ( Exception e) {
_log.debug(e.getMessage());
}
return portMetricsAllocationEnabled;
}
| Check whether port metrics allocation is enabled. |
private void syncEmlWithResource(Resource resource){
resource.getEml().setEmlVersion(resource.getEmlVersion());
if (resource.getKey() != null) {
resource.getEml().setGuid(resource.getKey().toString());
}
else {
resource.getEml().setGuid(cfg.getResourceGuid(resource.getShortname()));
}
updateKeywordsWithDatasetTypeAndSubtype(resource);
}
| Updates the EML version and EML GUID. The GUID is set to the Registry UUID if the resource is registered, otherwise it is set to the resource URL. </br> This method also updates the EML list of KeywordSet with the dataset type and subtype. </br> This method must be called before persisting the EML file to ensure that the EML file and resource are in sync. |
private double[] prepareExtendedBatch(ExampleSet extendedBatch){
int[] classCount=new int[2];
Iterator<Example> reader=extendedBatch.iterator();
while (reader.hasNext()) {
Example example=reader.next();
example.setWeight(1);
classCount[(int)example.getLabel()]++;
}
double[] classPriors=new double[2];
int sum=classCount[0] + classCount[1];
classPriors[0]=(double)classCount[0] / sum;
classPriors[1]=(double)classCount[1] / sum;
return classPriors;
}
| Similar to prepareBatch, but for extended batches. |
public synchronized void returnBuf(byte[] buf){
if (buf == null || buf.length > mSizeLimit) {
return;
}
mBuffersByLastUse.add(buf);
int pos=Collections.binarySearch(mBuffersBySize,buf,BUF_COMPARATOR);
if (pos < 0) {
pos=-pos - 1;
}
mBuffersBySize.add(pos,buf);
mCurrentSize+=buf.length;
trim();
}
| Returns a buffer to the pool, throwing away old buffers if the pool would exceed its allotted size. |
public void readFully(byte[] b,int off,int len){
if (SysProperties.CHECK && (len < 0 || len % Constants.FILE_BLOCK_SIZE != 0)) {
DbException.throwInternalError("unaligned read " + name + " len "+ len);
}
checkPowerOff();
try {
FileUtils.readFully(file,ByteBuffer.wrap(b,off,len));
}
catch ( IOException e) {
throw DbException.convertIOException(e,name);
}
filePos+=len;
}
| Read a number of bytes. |
private void findValidation(Class<?> vaultClass,Class<?> assetClass,Class<?> idClass){
for ( Method method : vaultClass.getMethods()) {
if (!method.getName().startsWith("find")) {
continue;
}
if (!Modifier.isAbstract(method.getModifiers())) {
continue;
}
TypeRef resultRef=findResult(method.getParameters());
if (resultRef == null) {
continue;
}
TypeRef typeRef=resultRef.to(Result.class).param(0);
Class<?> typeClass=typeRef.rawClass();
if (unbox(idClass).equals(unbox(typeClass))) {
continue;
}
if (Collection.class.isAssignableFrom(typeClass)) {
continue;
}
else if (Stream.class.isAssignableFrom(typeClass)) {
continue;
}
else if (Modifier.isAbstract(typeClass.getModifiers())) {
continue;
}
new ShimConverter<>(assetClass,typeClass);
}
}
| Validate the find methods. |
public boolean isReadable(){
return true;
}
| <!-- begin-user-doc --> <!-- end-user-doc --> |
public void testD() throws IOException {
SimilarityBase sim=new DFRSimilarity(new BasicModelD(),new AfterEffect.NoAfterEffect(),new Normalization.NoNormalization());
double totalTermFreqNorm=TOTAL_TERM_FREQ + FREQ + 1;
double p=1.0 / (NUMBER_OF_DOCUMENTS + 1);
double phi=FREQ / totalTermFreqNorm;
double D=phi * SimilarityBase.log2(phi / p) + (1 - phi) * SimilarityBase.log2((1 - phi) / (1 - p));
float gold=(float)(totalTermFreqNorm * D + 0.5 * SimilarityBase.log2(1 + 2 * Math.PI * FREQ* (1 - phi)));
correctnessTestCore(sim,gold);
}
| Correctness test for the D DFR model (basic model only). |
public ActionErrors validate(ActionMapping mapping,HttpServletRequest request){
ActionErrors errors=new ActionErrors();
if (StringUtils.isBlank(nombre)) {
errors.add(ActionErrors.GLOBAL_MESSAGE,new ActionError(Constants.ERROR_REQUIRED,Messages.getString(DescripcionConstants.DESCRIPCION_LISTADESCRIPTORAS_NOMBRE,request.getLocale())));
}
if (tipo < 0) {
errors.add(ActionErrors.GLOBAL_MESSAGE,new ActionError(Constants.ERROR_REQUIRED,Messages.getString(DescripcionConstants.DESCRIPCION_LISTADESCRIPTORAS_TIPO,request.getLocale())));
}
if (tipoDescriptor < 0) {
errors.add(ActionErrors.GLOBAL_MESSAGE,new ActionError(Constants.ERROR_REQUIRED,Messages.getString(DescripcionConstants.DESCRIPCION_LISTADESCRIPTORAS_TIPO_DESCRIPTOR,request.getLocale())));
}
if ((tipoDescriptor == TipoDescriptor.ENTIDAD) && StringUtils.isBlank(idFichaDescrPref)) {
errors.add(ActionErrors.GLOBAL_MESSAGE,new ActionError(Constants.ERROR_REQUIRED,Messages.getString(DescripcionConstants.DESCRIPCION_LISTADESCRIPTORAS_TIPO_NOMBRE_FICHA_DESCR_PREF,request.getLocale())));
}
return errors;
}
| Valida el formulario |
private void allocatePort(StoragePort allocatedPort,Set<String> allocatedPorts,Set<String> allocatedEngines,Set<String> allocatedDirectorTypes,Set<String> allocatedDirectors,Set<String> allocatedCpus,Set<String> allocatedSwitches,List<StoragePort> allocatedStoragePorts,PortAllocationContext context){
allocatedPorts.add(allocatedPort.getPortNetworkId());
allocatedStoragePorts.add(allocatedPort);
String engine=context._storagePortToEngine.get(allocatedPort);
if (engine != null) {
allocatedEngines.add(engine);
context._alreadyAllocatedEngines.add(engine);
}
String directorType=context._storagePortToDirectorType.get(allocatedPort);
if (directorType != null) {
allocatedDirectorTypes.add(directorType);
context._alreadyAllocatedDirectorTypes.add(directorType);
}
String director=context._storagePortToDirector.get(allocatedPort);
if (director != null) {
allocatedDirectors.add(director);
context._alreadyAllocatedDirectors.add(director);
}
String cpu=context._storagePortToCpu.get(allocatedPort);
if (cpu != null) {
allocatedCpus.add(cpu);
context._alreadyAllocatedCpus.add(cpu);
}
if (context._storagePortToSwitchName.get(allocatedPort) != null) {
allocatedSwitches.add(context._storagePortToSwitchName.get(allocatedPort));
context._alreadyAllocatedSwitches.add(context._storagePortToSwitchName.get(allocatedPort));
}
}
| Handles the book-keeping of allocating a port. Called in two places - once for ports already allocated, and once for ports that are being allocated. |
private void returnData(Object ret){
if (myHost != null) {
myHost.returnData(ret);
}
}
| Used to communicate a return object from a plugin tool to the main Whitebox user-interface. |
public void writeStatement(Statement oldStat){
if (oldStat == null) {
throw new NullPointerException();
}
Statement newStat=createNewStatement(oldStat);
try {
newStat.execute();
}
catch ( Exception e) {
listener.exceptionThrown(new Exception("failed to write statement: " + oldStat,e));
}
}
| Write a statement of old objects. <p> A new statement is created by using the new versions of the target and arguments. If any of the objects do not have its new copy yet, <code>writeObject()</code> is called to create one. </p> <p> The new statement is then executed to change the state of the new object. </p> |
public TourGuide playInSequence(Sequence sequence){
setSequence(sequence);
next();
return this;
}
| Sequence related method |
@ReactMethod public void showPopupMenu(int reactTag,ReadableArray items,Callback error,Callback success){
assertViewExists(reactTag,"showPopupMenu");
mOperationsQueue.enqueueShowPopupMenu(reactTag,items,error,success);
}
| Show a PopupMenu. |
public static DateTime fromBigqueryTimestampString(String timestampString){
return BIGQUERY_TIMESTAMP_FORMAT.parseDateTime(timestampString);
}
| Returns the DateTime for a given human-readable string-formatted BigQuery timestamp. |
public boolean isRejectRemoteReceivedHeaderInvalid(){
return fieldRejectRemoteReceivedHeaderInvalid;
}
| Returns the rejectRemoteReceivedHeaderInvalid. |
public static void addFileDependencyCondition(ParameterType parameter,ParameterHandler parameterHandler,PortProvider portProvider){
parameter.registerDependencyCondition(new PortConnectedCondition(parameterHandler,portProvider,true,false));
}
| Adds a new (file-)OutputPortNotConnectedCondition for a given parameter. |
public static void main(String[] args){
Scanner input=new Scanner(System.in);
String[][] statesAndCapitals=getData();
int count=0;
for (int i=0; i < statesAndCapitals.length; i++) {
System.out.print("What is the capital of " + statesAndCapitals[i][0] + "? ");
String capital=input.nextLine();
if (isEqual(statesAndCapitals[i][1],capital)) {
System.out.println("Your answer is correct");
count++;
}
else {
System.out.println("The correct answer should be " + statesAndCapitals[i][1]);
}
}
System.out.println("\nThe correct count is " + count);
}
| Main method |
public void compressBlockDXT3(ColorBlock4x4 colorBlock,DXTCompressionAttributes attributes,BlockDXT3 dxtBlock){
if (colorBlock == null) {
String message=Logging.getMessage("nullValue.ColorBlockIsNull");
Logging.logger().severe(message);
throw new IllegalArgumentException(message);
}
if (attributes == null) {
String message=Logging.getMessage("nullValue.AttributesIsNull");
Logging.logger().severe(message);
throw new IllegalArgumentException(message);
}
if (dxtBlock == null) {
String message=Logging.getMessage("nullValue.DXTBlockIsNull");
Logging.logger().severe(message);
throw new IllegalArgumentException(message);
}
this.dxt1Compressor.compressBlockDXT1(colorBlock,attributes,dxtBlock.colorBlock);
this.compressBlockDXT3a(colorBlock,dxtBlock.alphaBlock);
}
| Compress the 4x4 color block into a DXT2/DXT3 block using 16 4 bit alpha values, and four colors. This method compresses the color block exactly as a DXT1 compressor, except that it guarantees that the DXT1 block will use four colors. <p/> Access to this method must be synchronized by the caller. This method is frequently invoked by the DXT compressor, so in order to reduce garbage each instance of this class has unsynchronized properties that are reused during each call. |
public static Tree fromString(String ptbStr){
PennTreeReader reader=new PennTreeReader(new StringReader(ptbStr));
return reader.next();
}
| This is a convenience function for producing a fragment from its string representation. |
public void unregisterVASACertificate(String existingCertificate) throws InvalidCertificate, InvalidSession, StorageFault {
final String methodName="unregisterVASACertificate(): ";
log.info(methodName + "Entry with existingCertificate[" + (existingCertificate != null ? "****" : null)+ "]");
contextManager.unregisterVASACertificate(existingCertificate);
log.info(methodName + "Exit");
}
| Unregisters (removes) VASA provider from vCenter server |
public T archive(String value){
return attr("archive",value);
}
| Sets the <code>archive</code> attribute on the last started tag that has not been closed. |
public void enableMobileProvisioning(String url){
if (DBG) log("enableMobileProvisioning(url=" + url + ")");
final AsyncChannel channel=mDataConnectionTrackerAc;
if (channel != null) {
Message msg=Message.obtain();
msg.what=DctConstants.CMD_ENABLE_MOBILE_PROVISIONING;
msg.setData(Bundle.forPair(DctConstants.PROVISIONING_URL_KEY,url));
channel.sendMessage(msg);
}
}
| Inform DCT mobile provisioning has started, it ends when provisioning completes. |
@Override public void run(){
amIActive=true;
String inputHeader=null;
String outputHeader=null;
int row, col, x, y;
double z, min, max;
float progress=0;
int a;
int filterSizeX=3;
int filterSizeY=3;
int dX[];
int dY[];
int midPointX;
int midPointY;
int numPixelsInFilter;
boolean filterRounded=false;
double[] filterShape;
boolean reflectAtBorders=false;
if (args.length <= 0) {
showFeedback("Plugin parameters have not been set.");
return;
}
for (int i=0; i < args.length; i++) {
if (i == 0) {
inputHeader=args[i];
}
else if (i == 1) {
outputHeader=args[i];
}
else if (i == 2) {
filterSizeX=Integer.parseInt(args[i]);
}
else if (i == 3) {
filterSizeY=Integer.parseInt(args[i]);
}
else if (i == 4) {
filterRounded=Boolean.parseBoolean(args[i]);
}
else if (i == 5) {
reflectAtBorders=Boolean.parseBoolean(args[i]);
}
}
if ((inputHeader == null) || (outputHeader == null)) {
showFeedback("One or more of the input parameters have not been set properly.");
return;
}
try {
WhiteboxRaster inputFile=new WhiteboxRaster(inputHeader,"r");
inputFile.isReflectedAtEdges=reflectAtBorders;
int rows=inputFile.getNumberRows();
int cols=inputFile.getNumberColumns();
double noData=inputFile.getNoDataValue();
WhiteboxRaster outputFile=new WhiteboxRaster(outputHeader,"rw",inputHeader,WhiteboxRaster.DataType.FLOAT,noData);
outputFile.setPreferredPalette(inputFile.getPreferredPalette());
if (Math.floor(filterSizeX / 2d) == (filterSizeX / 2d)) {
showFeedback("Filter dimensions must be odd numbers. The specified filter x-dimension" + " has been modified.");
filterSizeX++;
}
if (Math.floor(filterSizeY / 2d) == (filterSizeY / 2d)) {
showFeedback("Filter dimensions must be odd numbers. The specified filter y-dimension" + " has been modified.");
filterSizeY++;
}
numPixelsInFilter=filterSizeX * filterSizeY;
dX=new int[numPixelsInFilter];
dY=new int[numPixelsInFilter];
filterShape=new double[numPixelsInFilter];
midPointX=(int)Math.floor(filterSizeX / 2);
midPointY=(int)Math.floor(filterSizeY / 2);
if (!filterRounded) {
a=0;
for (row=0; row < filterSizeY; row++) {
for (col=0; col < filterSizeX; col++) {
dX[a]=col - midPointX;
dY[a]=row - midPointY;
filterShape[a]=1;
a++;
}
}
}
else {
double aSqr=midPointX * midPointX;
double bSqr=midPointY * midPointY;
a=0;
for (row=0; row < filterSizeY; row++) {
for (col=0; col < filterSizeX; col++) {
dX[a]=col - midPointX;
dY[a]=row - midPointY;
z=(dX[a] * dX[a]) / aSqr + (dY[a] * dY[a]) / bSqr;
if (z > 1) {
filterShape[a]=0;
}
else {
filterShape[a]=1;
}
a++;
}
}
}
for (row=0; row < rows; row++) {
for (col=0; col < cols; col++) {
z=inputFile.getValue(row,col);
if (z != noData) {
min=z;
max=z;
for (a=0; a < numPixelsInFilter; a++) {
x=col + dX[a];
y=row + dY[a];
z=inputFile.getValue(y,x);
if (z != noData) {
if (z < min) {
min=z;
}
if (z > max) {
max=z;
}
}
}
outputFile.setValue(row,col,(max - min));
}
else {
outputFile.setValue(row,col,noData);
}
}
if (cancelOp) {
cancelOperation();
return;
}
progress=(float)(100f * row / (rows - 1));
updateProgress((int)progress);
}
outputFile.addMetadataEntry("Created by the " + getDescriptiveName() + " tool.");
outputFile.addMetadataEntry("Created on " + new Date());
inputFile.close();
outputFile.close();
returnData(outputHeader);
}
catch ( OutOfMemoryError oe) {
myHost.showFeedback("An out-of-memory error has occurred during operation.");
}
catch ( Exception e) {
myHost.showFeedback("An error has occurred during operation. See log file for details.");
myHost.logException("Error in " + getDescriptiveName(),e);
}
finally {
updateProgress("Progress: ",0);
amIActive=false;
myHost.pluginComplete();
}
}
| Used to execute this plugin tool. |
public int size(){
return feature2Id.size();
}
| The number of features in this lexicon |
public SerialNode(){
}
| Creates a new instance of AbstractNode |
private boolean tryPublicKey(final Connection c,final String keyPath){
try {
final File file=new File(keyPath);
if (file.exists()) {
String passphrase=null;
char[] text=FileUtilRt.loadFileText(file);
if (isEncryptedKey(text)) {
int i;
for (i=0; i < myHost.getNumberOfPasswordPrompts(); i++) {
passphrase=myXmlRpcClient.askPassphrase(myHandlerNo,getUserHostString(),keyPath,i != 0,myLastError);
if (passphrase == null) {
return false;
}
else {
try {
PEMDecoder.decode(text,passphrase);
myLastError="";
}
catch ( IOException e) {
myLastError=SSHMainBundle.message("sshmain.invalidpassphrase",keyPath);
myErrorCause=e;
continue;
}
break;
}
}
if (i == myHost.getNumberOfPasswordPrompts()) {
myLastError=SSHMainBundle.message("sshmain.too.mush.passphrase.guesses",keyPath,myHost.getNumberOfPasswordPrompts());
return false;
}
}
if (c.authenticateWithPublicKey(myHost.getUser(),text,passphrase)) {
myLastError="";
myXmlRpcClient.setLastSuccessful(myHandlerNo,getUserHostString(),PUBLIC_KEY_METHOD,"");
return true;
}
else {
if (passphrase != null) {
myLastError=SSHMainBundle.message("sshmain.pk.authenitication.failed",keyPath);
}
else {
myLastError="";
}
}
}
return false;
}
catch ( Exception e) {
myErrorCause=e;
return false;
}
}
| Try public key |
public List<String> command(){
return command;
}
| Returns this process builder's current program and arguments. Note that the returned list is not a copy and modifications to it will change the state of this instance. |
public boolean isBlocked(String permissionName){
return !doCanPerform(permissionName,false,true);
}
| True if the user is blocked from using this permission. |
protected synchronized void clearBuffers(){
while (m_firstBuffer.size() > 0 && m_secondBuffer.size() > 0) {
m_throughput.updateStart();
Instance newInst=processBuffers();
m_throughput.updateEnd(m_log);
if (newInst != null) {
m_ie.setInstance(newInst);
m_ie.setStatus(InstanceEvent.INSTANCE_AVAILABLE);
notifyInstanceListeners(m_ie);
}
}
m_ie.setInstance(null);
m_ie.setStatus(InstanceEvent.BATCH_FINISHED);
notifyInstanceListeners(m_ie);
if (m_log != null) {
m_log.statusMessage(statusMessagePrefix() + "Finished");
}
m_headerOne=null;
m_headerTwo=null;
m_mergedHeader=null;
m_firstBuffer=null;
m_secondBuffer=null;
m_firstFinished=false;
m_secondFinished=false;
m_busy=false;
}
| Clear remaining instances in the buffers |
public static RegionSizeRequest create(){
RegionSizeRequest m=new RegionSizeRequest();
return m;
}
| Returns a <code>ObjectNamesRequest</code> to be sent to the specified recipient. |
@Override public int size(){
return this._map.size();
}
| Returns the number of entries in the map. |
public TaskResourceRep restoreSnapshotSession(URI snapSessionURI){
s_logger.info("START restore snapshot session {}",snapSessionURI);
BlockSnapshotSession snapSession=BlockSnapshotSessionUtils.querySnapshotSession(snapSessionURI,_uriInfo,_dbClient,true);
BlockObject snapSessionSourceObj=null;
List<BlockObject> snapSessionSourceObjs=getAllSnapshotSessionSources(snapSession);
snapSessionSourceObj=snapSessionSourceObjs.get(0);
Project project=BlockSnapshotSessionUtils.querySnapshotSessionSourceProject(snapSessionSourceObj,_dbClient);
BlockSnapshotSessionApi snapSessionApiImpl=determinePlatformSpecificImplForSource(snapSessionSourceObj);
snapSessionApiImpl.validateRestoreSnapshotSession(snapSessionSourceObjs,project);
String taskId=UUID.randomUUID().toString();
Operation op=new Operation();
op.setResourceType(ResourceOperationTypeEnum.RESTORE_SNAPSHOT_SESSION);
_dbClient.createTaskOpStatus(BlockSnapshotSession.class,snapSessionURI,taskId,op);
snapSession.getOpStatus().put(taskId,op);
TaskResourceRep resourceRep=toTask(snapSession,taskId);
try {
snapSessionApiImpl.restoreSnapshotSession(snapSession,snapSessionSourceObjs.get(0),taskId);
}
catch ( Exception e) {
String errorMsg=format("Failed to restore snapshot session %s: %s",snapSessionURI,e.getMessage());
ServiceCoded sc=null;
if (e instanceof ServiceCoded) {
sc=(ServiceCoded)e;
}
else {
sc=APIException.internalServerErrors.genericApisvcError(errorMsg,e);
}
cleanupFailure(Lists.newArrayList(resourceRep),new ArrayList<DataObject>(),errorMsg,taskId,sc);
throw e;
}
auditOp(OperationTypeEnum.RESTORE_SNAPSHOT_SESSION,true,AuditLogManager.AUDITOP_BEGIN,snapSessionURI.toString(),snapSessionSourceObjs.get(0).getId().toString(),snapSessionSourceObjs.get(0).getStorageController().toString());
s_logger.info("FINISH restore snapshot session {}",snapSessionURI);
return resourceRep;
}
| Restores the data on the array snapshot point-in-time copy represented by the BlockSnapshotSession instance with the passed URI, to the snapshot session source object. |
public LayersMenu(LayerHandler lHandler){
this(lHandler,"Layers",LAYERS_ON_OFF);
}
| Construct LayersMenu. |
private Individual searchBest(){
try {
return Collections.max(individuals,PERFORMANCE_COMPARATOR);
}
catch ( NullPointerException e) {
return null;
}
catch ( NoSuchElementException e) {
return null;
}
}
| Finds the current generation's best individual. Returns null, if there are unevaluated individuals. Probably you will want to use <tt>bestEver()</tt> or <tt>lastBest()</tt> because they don't cause comparisons. |
private void emitDeserializer(List<Method> getters,StringBuilder builder){
builder.append(" public static ").append(getImplClassName()).append(" fromJsonElement(JsonElement jsonElem) {\n");
builder.append(" return fromJsonElement(jsonElem, true);\n");
builder.append(" }\n");
builder.append(" public static ").append(getImplClassName()).append(" fromJsonElement(JsonElement jsonElem, boolean ").append(COPY_JSONS_PARAM).append(") {\n");
builder.append(" if (jsonElem == null || jsonElem.isJsonNull()) {\n");
builder.append(" return null;\n");
builder.append(" }\n\n");
builder.append(" ").append(getImplClassName()).append(" dto = new ").append(getImplClassName()).append("();\n");
if (isCompactJson()) {
builder.append(" JsonArray json = jsonElem.getAsJsonArray();\n");
for ( Method method : getters) {
emitDeserializeFieldForMethodCompact(method,builder);
}
}
else {
builder.append(" JsonObject json = jsonElem.getAsJsonObject();\n");
for ( Method getter : getters) {
emitDeserializeFieldForMethod(getter,builder);
}
}
builder.append("\n return dto;\n");
builder.append(" }\n\n");
}
| Generates a static factory method that creates a new instance based on a JsonElement. |
public boolean isInAllowed(int x,int y){
for ( Shape r : arrivingBarriers) {
if (r.contains(x,y)) {
return false;
}
}
return true;
}
| Check if teleporting to a location is allowed. |
public void write(byte[] b) throws IOException {
write(b,0,b.length);
}
| Writes <code>b.length</code> bytes from the specified byte array to this output stream. <p> The <code>write</code> method of <code>CipherOutputStream</code> calls the <code>write</code> method of three arguments with the three arguments <code>b</code>, <code>0</code>, and <code>b.length</code>. |
public Accumulator(){
data=new HashMap<String,List<Serializable>>();
}
| Constructs an empty accumulator. |
public DbManagerOps(MBeanServerConnection mbsc) throws IOException, MalformedObjectNameException {
initMbean(mbsc);
}
| Create an DbManagerOps object using given MBeanServerConnection. The connection is built outside of this object's control. |
public void testSharedMode() throws Exception {
processSharedModeTest(DeploymentMode.SHARED);
}
| Test GridDeploymentMode.SHARED mode. |
public SystemWebViewEngine(Context context,CordovaPreferences preferences){
this(new SystemWebView(context));
}
| Used when created via reflection. |
public Affiliation(String jid,String node,Type affiliation){
this.jid=jid;
this.node=node;
type=affiliation;
}
| Constructs an affiliation. |
public void testCreateIdForEAR() throws Exception {
EAR ear=createEAR();
String name=deployer.createIdForDeployable(ear);
assertEquals("cargo.war",name);
}
| Test EAR identifier creation. |
public boolean sameAs(Cache other){
boolean sameConfig=other.getLockLease() == this.getLockLease() && other.getLockTimeout() == this.getLockTimeout() && other.getSearchTimeout() == this.getSearchTimeout() && other.getMessageSyncInterval() == this.getMessageSyncInterval() && other.getCopyOnRead() == this.getCopyOnRead() && other.isServer() == this.isServer();
if (!sameConfig) {
throw new RuntimeException(LocalizedStrings.CacheCreation_SAMECONFIG.toLocalizedString());
}
else {
DynamicRegionFactory.Config drc1=this.getDynamicRegionFactoryConfig();
if (drc1 != null) {
DynamicRegionFactory.Config drc2=null;
if (other instanceof CacheCreation) {
drc2=((CacheCreation)other).getDynamicRegionFactoryConfig();
}
else {
drc2=DynamicRegionFactory.get().getConfig();
}
if (drc2 == null) {
return false;
}
if (!drc1.equals(drc2)) {
return false;
}
}
else {
if (other instanceof CacheCreation) {
if (((CacheCreation)other).getDynamicRegionFactoryConfig() != null) {
return false;
}
}
else {
if (DynamicRegionFactory.get().isOpen()) {
return false;
}
}
}
Collection myBridges=this.getCacheServers();
Collection otherBridges=other.getCacheServers();
if (myBridges.size() != otherBridges.size()) {
throw new RuntimeException(LocalizedStrings.CacheCreation_CACHESERVERS_SIZE.toLocalizedString());
}
for (Iterator myIter=myBridges.iterator(); myIter.hasNext(); ) {
CacheServerCreation myBridge=(CacheServerCreation)myIter.next();
boolean found=false;
for (Iterator otherIter=otherBridges.iterator(); otherIter.hasNext(); ) {
CacheServer otherBridge=(CacheServer)otherIter.next();
if (myBridge.sameAs(otherBridge)) {
found=true;
break;
}
}
if (!found) {
throw new RuntimeException(LocalizedStrings.CacheCreation_CACHE_SERVER_0_NOT_FOUND.toLocalizedString(myBridge));
}
}
{
Map m1=getPools();
Map m2=(other instanceof CacheCreation) ? ((CacheCreation)other).getPools() : PoolManager.getAll();
int m1Size=m1.size();
{
Iterator it1=m1.values().iterator();
while (it1.hasNext()) {
Pool cp=(Pool)it1.next();
if (((PoolImpl)cp).isUsedByGateway()) {
m1Size--;
}
}
}
int m2Size=m2.size();
{
Iterator it2=m2.values().iterator();
while (it2.hasNext()) {
Pool cp=(Pool)it2.next();
if (((PoolImpl)cp).isUsedByGateway()) {
m2Size--;
}
}
}
if (m2Size == 1) {
Pool p=(Pool)m2.values().iterator().next();
if (p.getName().equals("DEFAULT")) {
m2Size=0;
}
}
if (m1Size != m2Size) {
throw new RuntimeException("pool sizes differ m1Size=" + m1Size + " m2Size="+ m2Size+ " m1="+ m1.values()+ " m2="+ m2.values());
}
if (m1Size > 0) {
Iterator it1=m1.values().iterator();
while (it1.hasNext()) {
PoolImpl cp=(PoolImpl)it1.next();
if (!(cp).isUsedByGateway()) {
cp.sameAs(m2.get(cp.getName()));
}
}
}
}
for (Iterator myIter=diskStores.values().iterator(); myIter.hasNext(); ) {
DiskStoreAttributesCreation dsac=(DiskStoreAttributesCreation)myIter.next();
String name=dsac.getName();
DiskStore ds=other.findDiskStore(name);
if (ds == null) {
getLogger().fine("Disk store " + name + " not found.");
throw new RuntimeException(LocalizedStrings.CacheCreation_DISKSTORE_NOTFOUND_0.toLocalizedString(name));
}
else {
if (!dsac.sameAs(ds)) {
getLogger().fine("Attributes for disk store " + name + " do not match");
throw new RuntimeException(LocalizedStrings.CacheCreation_ATTRIBUTES_FOR_DISKSTORE_0_DO_NOT_MATCH.toLocalizedString(name));
}
}
}
Map myNamedAttributes=this.listRegionAttributes();
Map otherNamedAttributes=other.listRegionAttributes();
if (myNamedAttributes.size() != otherNamedAttributes.size()) {
throw new RuntimeException(LocalizedStrings.CacheCreation_NAMEDATTRIBUTES_SIZE.toLocalizedString());
}
for (Iterator myIter=myNamedAttributes.entrySet().iterator(); myIter.hasNext(); ) {
Map.Entry myEntry=(Map.Entry)myIter.next();
String myId=(String)myEntry.getKey();
Assert.assertTrue(myEntry.getValue() instanceof RegionAttributesCreation,"Entry value is a " + myEntry.getValue().getClass().getName());
RegionAttributesCreation myAttrs=(RegionAttributesCreation)myEntry.getValue();
RegionAttributes otherAttrs=other.getRegionAttributes(myId);
if (otherAttrs == null) {
getLogger().fine("No attributes for " + myId);
throw new RuntimeException(LocalizedStrings.CacheCreation_NO_ATTRIBUTES_FOR_0.toLocalizedString(myId));
}
else {
if (!myAttrs.sameAs(otherAttrs)) {
getLogger().fine("Attributes for " + myId + " do not match");
throw new RuntimeException(LocalizedStrings.CacheCreation_ATTRIBUTES_FOR_0_DO_NOT_MATCH.toLocalizedString(myId));
}
}
}
Collection myRoots=this.roots.values();
Collection otherRoots=other.rootRegions();
if (myRoots.size() != otherRoots.size()) {
throw new RuntimeException(LocalizedStrings.CacheCreation_ROOTS_SIZE.toLocalizedString());
}
Iterator it=myRoots.iterator();
while (it.hasNext()) {
RegionCreation r=(RegionCreation)it.next();
Region r2=other.getRegion(r.getName());
if (r2 == null) {
throw new RuntimeException(LocalizedStrings.CacheCreation_NO_ROOT_0.toLocalizedString(r.getName()));
}
else if (!r.sameAs(r2)) {
throw new RuntimeException(LocalizedStrings.CacheCreation_REGIONS_DIFFER.toLocalizedString());
}
}
if (getCacheTransactionManager() != null) {
List otherTxListeners=Arrays.asList(other.getCacheTransactionManager().getListeners());
List thisTxListeners=Arrays.asList(getCacheTransactionManager().getListeners());
if (!thisTxListeners.equals(otherTxListeners)) {
throw new RuntimeException(LocalizedStrings.CacheCreation_TXLISTENER.toLocalizedString());
}
}
}
if (hasResourceManager()) {
getResourceManager().sameAs(other.getResourceManager());
}
return true;
}
| Returns whether or not this <code>CacheCreation</code> is equivalent to another <code>Cache</code>. |
protected void writeModelRetriever() throws IOException {
out("require('",JsCompiler.scriptPath(module),"-model').$CCMM$");
}
| Write the function to retrieve or define the model JSON map. |
@Override public boolean supportsSchemasInProcedureCalls(){
debugCodeCall("supportsSchemasInProcedureCalls");
return true;
}
| Returns whether the schema name in procedure calls is supported. |
public void fillInNotifierBundle(Bundle bundleToFill){
bundleToFill.putInt("baseStationId",this.mBaseStationId);
bundleToFill.putInt("baseStationLatitude",this.mBaseStationLatitude);
bundleToFill.putInt("baseStationLongitude",this.mBaseStationLongitude);
bundleToFill.putInt("systemId",this.mSystemId);
bundleToFill.putInt("networkId",this.mNetworkId);
}
| Fill the cell location data into the intent notifier Bundle based on service state |
public String write(Enum value) throws Exception {
return value.name();
}
| This method is used to convert the provided value into an XML usable format. This is used in the serialization process when there is a need to convert a field value in to a string so that that value can be written as a valid XML entity. |
public static double[] f(double[] M,Function func){
double[] fM=new double[M.length];
for (int i=0; i < fM.length; i++) fM[i]=func.f(M[i]);
return fM;
}
| Apply a scalar function to every element of an array. Must import groovySci.math.array.util.*; to get Function interface. Example:<br> <code> double[] b = {1,2,3,4};<br> Function inverse = new Function() { public double f(double x) { return 1/x; }};<br> double[] z = f(b, inverse);<br> Result is: <br> 1.00 0.50 0.33 0.25 </code> |
private void deleteNode(BFINode<E> childNode,InsDelUpdateStatistics stat){
if (this.root.children.size() < 2) {
System.err.println("ERROR: nb children of root is " + this.root.children.size());
System.err.println(this.toString());
assert false;
}
BFINode<E> node=childNode.parent;
boolean ok=node.children.remove(childNode);
assert ok;
stat.nbBFNodesAccessed+=2;
if (node == this.root && node.children.size() == 1) {
if (!node.children.get(0).isLeaf()) {
this.root=node.children.get(0);
this.root.parent=null;
stat.nbBFNodesAccessed++;
return;
}
}
stat.nbBFNodesAccessed++;
if (!node.needMerge()) {
recomputeValueToTheRoot(node,stat);
}
else {
int index=node.parent.children.indexOf(node);
stat.nbBFNodesAccessed+=2;
BFINode<E> sibling;
boolean isRightSibling=false;
if (index + 1 < node.parent.children.size()) {
isRightSibling=true;
sibling=(BFINode<E>)node.parent.children.get(index + 1);
}
else {
if (index - 1 < 0) {
System.err.println("Error " + this.toString() + " node: "+ node.toString()+ "childNode: "+ childNode.toString());
assert false;
}
isRightSibling=false;
sibling=(BFINode<E>)node.parent.children.get(index - 1);
}
stat.nbBFNodesAccessed++;
stat.nbBFNodesAccessed++;
if (sibling.canRedistribute()) {
redistribute(node,sibling,isRightSibling,stat);
}
else {
merge(node,sibling,isRightSibling,stat);
deleteNode(node,stat);
}
}
return;
}
| Delete the given node from the index. The deletion moves bottom up |
public void writeFormatted(Geometry geometry,Writer writer) throws IOException {
writeFormatted(geometry,true,writer);
}
| Same as <code>write</code>, but with newlines and spaces to make the well-known text more readable. |
public NegativeResponseException(int commandStatus){
super("Negative response " + IntUtil.toHexString(commandStatus) + " found");
this.commandStatus=commandStatus;
}
| Construct with specified command_status. |
public void addOptionIfValueNonEmpty(String option,String value){
if (value != null && !value.isEmpty()) {
addOption(option,value);
}
}
| Adds the option only if value is a non-null, non-empty String |
public void executeCallback(SceKernelThreadInfo thread,int address,IAction afterAction,boolean returnVoid,int registerA0){
if (log.isDebugEnabled()) {
log.debug(String.format("Execute callback 0x%08X($a0=0x%08X), afterAction=%s, returnVoid=%b",address,registerA0,afterAction,returnVoid));
}
callAddress(thread,address,afterAction,returnVoid,false,new int[]{registerA0});
}
| Trigger a call to a callback in the context of a thread. This call can return before the completion of the callback. Use the "afterAction" parameter to trigger some actions that need to be executed after the callback (e.g. to evaluate a return value in cpu.gpr[2]). |
protected JavacElements(Context context){
setContext(context);
}
| Public for use only by JavacProcessingEnvironment |
public void write(BufferedImage img) throws IOException {
super.write(img);
String fileExtension=getExtension(destinationFile);
String formatName=outputFormat;
if (formatName != null && (fileExtension == null || !isMatchingFormat(formatName,fileExtension))) {
destinationFile=new File(destinationFile.getAbsolutePath() + "." + formatName);
}
if (!allowOverwrite && destinationFile.exists()) {
throw new IllegalArgumentException("The destination file exists.");
}
if (formatName == null && fileExtension != null) {
Iterator<ImageReader> rIter=ImageIO.getImageReadersBySuffix(fileExtension);
if (rIter.hasNext()) {
formatName=rIter.next().getFormatName();
}
}
if (formatName == null) {
throw new UnsupportedFormatException(formatName,"Could not determine output format.");
}
Iterator<ImageWriter> writers=ImageIO.getImageWritersByFormatName(formatName);
if (!writers.hasNext()) {
throw new UnsupportedFormatException(formatName,"No suitable ImageWriter found for " + formatName + ".");
}
ImageWriter writer=writers.next();
ImageWriteParam writeParam=writer.getDefaultWriteParam();
if (writeParam.canWriteCompressed() && param != null) {
writeParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
if (param.getOutputFormatType() != ThumbnailParameter.DEFAULT_FORMAT_TYPE) {
writeParam.setCompressionType(param.getOutputFormatType());
}
else {
List<String> supportedFormats=ThumbnailatorUtils.getSupportedOutputFormatTypes(formatName);
if (!supportedFormats.isEmpty()) {
writeParam.setCompressionType(supportedFormats.get(0));
}
}
if (!Float.isNaN(param.getOutputQuality())) {
writeParam.setCompressionQuality(param.getOutputQuality());
}
}
ImageOutputStream ios;
FileOutputStream fos;
fos=new FileOutputStream(destinationFile);
ios=ImageIO.createImageOutputStream(fos);
if (ios == null || fos == null) {
throw new IOException("Could not open output file.");
}
if (formatName.equalsIgnoreCase("jpg") || formatName.equalsIgnoreCase("jpeg") || formatName.equalsIgnoreCase("bmp")) {
img=BufferedImages.copy(img,BufferedImage.TYPE_INT_RGB);
}
writer.setOutput(ios);
writer.write(null,new IIOImage(img,null,null),writeParam);
writer.dispose();
ios.close();
fos.close();
}
| Writes the resulting image to a file. |
K lowestKey(){
Comparator<? super K> cmp=m.comparator;
ConcurrentSkipListMap.Node<K,V> n=loNode(cmp);
if (isBeforeEnd(n,cmp)) return n.key;
else throw new NoSuchElementException();
}
| Returns lowest absolute key (ignoring directonality). |
private void exportFolderToText(String folderId,PrintStream ps){
Cursor notesCursor=mContext.getContentResolver().query(Notes.CONTENT_NOTE_URI,NOTE_PROJECTION,NoteColumns.PARENT_ID + "=?",new String[]{folderId},null);
if (notesCursor != null) {
if (notesCursor.moveToFirst()) {
do {
ps.println(String.format(getFormat(FORMAT_NOTE_DATE),DateFormat.format(mContext.getString(R.string.format_datetime_mdhm),notesCursor.getLong(NOTE_COLUMN_MODIFIED_DATE))));
String noteId=notesCursor.getString(NOTE_COLUMN_ID);
exportNoteToText(noteId,ps);
}
while (notesCursor.moveToNext());
}
notesCursor.close();
}
}
| Export the folder identified by folder id to text |
@DSComment("From safe class list") @DSSafe(DSCat.SAFE_LIST) @DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 12:34:18.877 -0500",hash_original_method="B472369E445B34AFDD84E5B389A9601D",hash_generated_method="7E96FE508A65015DCC33416C426C9ABB") protected final RectF rect(){
return mRect;
}
| Returns the RectF that defines this rectangle's bounds. |
public void putAsString(String key,double value){
String strValue=Double.toString(value);
super.put(key,strValue);
}
| <p> Adds the given <code>double</code> value as a string version to the <code>Job</code>'s data map. </p> |
public ZebraJTree(javax.swing.tree.TreeModel newModel){
super(newModel);
}
| Instantiates a new zebra j tree. |
public Node nextNode(){
if (!hasNext()) {
return null;
}
currentNode=nodes.pop();
currentChildren=currentNode.getChildNodes();
int childLen=(currentChildren != null) ? currentChildren.getLength() : 0;
for (int i=childLen - 1; i >= 0; i--) {
nodes.add(currentChildren.item(i));
}
return currentNode;
}
| <p> Returns the next <code>Node</code> on the stack and pushes all of its children onto the stack, allowing us to walk the node tree without the use of recursion. If there are no more nodes on the stack then null is returned. </p> |
public DefaultPseudoStateContext(PseudoState<S,E> pseudoState,PseudoAction pseudoAction){
this.pseudoState=pseudoState;
this.pseudoAction=pseudoAction;
}
| Instantiates a new default pseudo state context. |
public void initView(Context context,EditableImage editableImage){
this.editableImage=editableImage;
selectionView=new SelectionView(context,lineWidth,cornerWidth,cornerLength,lineColor,cornerColor,shadowColor,editableImage);
imageView=new ImageView(context);
imageView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT));
selectionView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT));
addView(imageView,0);
addView(selectionView,1);
}
| update view with editable image |
@Override public boolean doesMaxRowSizeIncludeBlobs(){
debugCodeCall("doesMaxRowSizeIncludeBlobs");
return false;
}
| Returns whether the maximum row size includes blobs. |
public DocumentExportEntry insert(URL exportFeedUrl,List<QueryParameter> params) throws IOException, ServiceException {
DocumentExportEntry entry=new DocumentExportEntry();
for ( QueryParameter param : params) {
entry.addQuery(param);
}
return insert(exportFeedUrl,entry);
}
| Start a new request to download the documents that match all search criteria as a zip file. |
public AttributeTagTestCase(String name){
super(name);
}
| Construct a new instance of this test case. |
public static Short toShort(CharSequence self){
return Short.valueOf(self.toString().trim());
}
| Parse a CharSequence into a Short |
public AllCapsTransformationMethod(Context context){
mLocale=context.getResources().getConfiguration().locale;
}
| Uses current locale. |
@LargeTest public void testThumbnailH264AnIFrame() throws Exception {
final String videoItemFilename=INPUT_FILE_PATH + "H264_BP_1080x720_30fps_800kbps_1_17.mp4";
final int outWidth=1080;
final int outHeight=720;
final int atTime=3000;
int renderingMode=MediaItem.RENDERING_MODE_BLACK_BORDER;
final String[] loggingInfo=new String[1];
long durationToAddObjects=0;
final MediaVideoItem mediaVideoItem=new MediaVideoItem(mVideoEditor,"m1",videoItemFilename,renderingMode);
assertNotNull("MediaVideoItem",mediaVideoItem);
for (int i=0; i < NUM_OF_ITERATIONS; i++) {
final long duration1=SystemClock.uptimeMillis();
mediaVideoItem.getThumbnail(outWidth,outHeight,atTime + i);
final long duration2=SystemClock.uptimeMillis();
durationToAddObjects+=(duration2 - duration1);
}
final float timeTaken=(float)durationToAddObjects * 1.0f / (float)NUM_OF_ITERATIONS;
loggingInfo[0]="Time taken Thumbnail generation :" + timeTaken;
writeTimingInfo("testThumbnailH264AnIFrame",loggingInfo);
}
| To test ThumbnailList for H264 |
@DSSource({DSSourceKind.SENSITIVE_UNCATEGORIZED}) @DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 12:55:52.757 -0500",hash_original_method="79DF1B5079137D62C29C5EAC0F3F40E2",hash_generated_method="A015978186413157B4AD18DBEEDB9864") public Socket createSocket(InetAddress address,int port,InetAddress myAddress,int myPort) throws IOException {
if (myAddress != null) return new Socket(address,port,myAddress,myPort);
else if (port != 0) {
Socket sock=new Socket();
sock.bind(new InetSocketAddress(port));
sock.connect(new InetSocketAddress(address,port));
return sock;
}
else return new Socket(address,port);
}
| Creates a new Socket, binds it to myAddress:myPort and connects it to address:port. |
protected void initializeTerminalSize(){
slotsTall=6;
slotsAcross=9;
startX=69;
startY=0;
playerInventoryOffsetX=0;
playerInventoryOffsetY=37;
hasCraftingMatrix=true;
}
| If overridden, <b>do not call super</b>. |
private void logWarning(String msg,Throwable e){
EnvironmentStream.logStderr(msg,e);
}
| error messages from the log itself |
public static float[] cmykFromRgb(int rgbColor){
int red=(0xff0000 & rgbColor) >> 16;
int green=(0xff00 & rgbColor) >> 8;
int blue=(0xff & rgbColor);
float black=Math.min(1.0f - red / 255.0f,Math.min(1.0f - green / 255.0f,1.0f - blue / 255.0f));
float cyan=1.0f;
float magenta=1.0f;
float yellow=1.0f;
if (black != 1.0f) {
cyan=(1.0f - (red / 255.0f) - black) / (1.0f - black);
magenta=(1.0f - (green / 255.0f) - black) / (1.0f - black);
yellow=(1.0f - (blue / 255.0f) - black) / (1.0f - black);
}
return new float[]{cyan,magenta,yellow,black};
}
| Convert RGB color to CMYK color. |
public void updateCheckout(final Checkout checkout,final Callback<Checkout> callback){
buyClient.updateCheckout(checkout,wrapCheckoutCallback(callback));
}
| Update a checkout. |
public static void applyDecidedIconOrSetGone(ImageHolder imageHolder,ImageView imageView,int iconColor,boolean tint,int paddingDp){
if (imageHolder != null && imageView != null) {
Drawable drawable=ImageHolder.decideIcon(imageHolder,imageView.getContext(),iconColor,tint,paddingDp);
if (drawable != null) {
imageView.setImageDrawable(drawable);
imageView.setVisibility(View.VISIBLE);
}
else if (imageHolder.getBitmap() != null) {
imageView.setImageBitmap(imageHolder.getBitmap());
imageView.setVisibility(View.VISIBLE);
}
else {
imageView.setVisibility(View.GONE);
}
}
else if (imageView != null) {
imageView.setVisibility(View.GONE);
}
}
| decides which icon to apply or hide this view |
public static String toStream(String channel){
if (channel == null) {
return null;
}
if (channel.startsWith("#")) {
return channel.substring(1);
}
return channel;
}
| Removes a leading # from the channel, if present. |
@SuppressWarnings({"MagicConstant","TypeMayBeWeakened"}) public static IgniteProductVersion fromString(String verStr){
assert verStr != null;
if (verStr.endsWith("-DEV") || verStr.endsWith("-n/a")) verStr=verStr.substring(0,verStr.length() - 4);
Matcher match=VER_PATTERN.matcher(verStr);
if (match.matches()) {
try {
byte major=Byte.parseByte(match.group(1));
byte minor=Byte.parseByte(match.group(2));
byte maintenance=Byte.parseByte(match.group(3));
String stage="";
if (match.group(4) != null) stage=match.group(4).substring(1);
long revTs=0;
if (match.group(7) != null) revTs=Long.parseLong(match.group(8));
byte[] revHash=null;
if (match.group(9) != null) revHash=U.decodeHex(match.group(10).toCharArray());
return new IgniteProductVersion(major,minor,maintenance,stage,revTs,revHash);
}
catch ( IllegalStateException|IndexOutOfBoundsException|NumberFormatException|IgniteCheckedException e) {
throw new IllegalStateException("Failed to parse version: " + verStr,e);
}
}
else throw new IllegalStateException("Failed to parse version: " + verStr);
}
| Tries to parse product version from it's string representation. |
public static synchronized TypeReference findOrCreate(ClassLoader cl,Atom tn) throws IllegalArgumentException {
TypeDescriptorParsing.validateAsTypeDescriptor(tn);
ClassLoader bootstrapCL=BootstrapClassLoader.getBootstrapClassLoader();
if (cl == null) {
cl=bootstrapCL;
}
else if (cl != bootstrapCL) {
if (tn.isClassDescriptor()) {
if (tn.isBootstrapClassDescriptor()) {
cl=bootstrapCL;
}
}
else if (tn.isArrayDescriptor()) {
Atom innermostElementType=tn.parseForInnermostArrayElementDescriptor();
if (innermostElementType.isClassDescriptor()) {
if (innermostElementType.isBootstrapClassDescriptor()) {
cl=bootstrapCL;
}
}
else {
cl=bootstrapCL;
}
}
else {
cl=bootstrapCL;
}
}
return findOrCreateInternal(cl,tn);
}
| Find or create the canonical TypeReference instance for the given pair. |
public void clear(){
oredCriteria.clear();
orderByClause=null;
distinct=false;
}
| This method was generated by MyBatis Generator. This method corresponds to the database table user_groups |
public Response handle(final String rawRequest){
final Request req=requestParser.parse(rawRequest);
return handleRequest(req);
}
| Handle the request by first parsing the string then evaluating the request method and uri |
public ReferenceQueue(){
}
| Creates a new empty reference queue. |
public double[] update(JunctionTreeNode node){
if (node.m_P == null) {
return null;
}
double[] fi=new double[m_nCardinality];
int[] values=new int[node.m_nNodes.length];
int[] order=new int[m_bayesNet.getNrOfNodes()];
for (int iNode=0; iNode < node.m_nNodes.length; iNode++) {
order[node.m_nNodes[iNode]]=iNode;
}
for (int iPos=0; iPos < node.m_nCardinality; iPos++) {
int iNodeCPT=getCPT(node.m_nNodes,node.m_nNodes.length,values,order,m_bayesNet);
int iSepCPT=getCPT(m_nNodes,m_nNodes.length,values,order,m_bayesNet);
fi[iSepCPT]+=node.m_P[iNodeCPT];
int i=0;
values[i]++;
while (i < node.m_nNodes.length && values[i] == m_bayesNet.getCardinality(node.m_nNodes[i])) {
values[i]=0;
i++;
if (i < node.m_nNodes.length) {
values[i]++;
}
}
}
return fi;
}
| marginalize junciontTreeNode node over all nodes outside the separator set |
public void process(NodeWorkList workList){
assert !(start instanceof Invoke);
workList.addAll(start.successors());
for ( Node current : workList) {
assert current.isAlive();
if (current instanceof Invoke) {
nodeRelevances.put((FixedNode)current,computeInvokeRelevance((Invoke)current));
workList.addAll(current.successors());
}
else if (current instanceof LoopBeginNode) {
((LoopBeginNode)current).loopExits().forEach(null);
}
else if (current instanceof LoopEndNode) {
}
else if (current instanceof LoopExitNode) {
}
else if (current instanceof FixedWithNextNode) {
workList.add(((FixedWithNextNode)current).next());
}
else if (current instanceof EndNode) {
workList.add(((EndNode)current).merge());
}
else if (current instanceof ControlSinkNode) {
}
else if (current instanceof ControlSplitNode) {
workList.addAll(current.successors());
}
else {
assert false : current;
}
}
}
| Processes all invokes in this scope by starting at the scope's start node and iterating all fixed nodes. Child loops are skipped by going from loop entries directly to the loop exits. Processing stops at loop exits of the current loop. |
public void runTest() throws Throwable {
Document doc;
Element root;
String tagname;
doc=(Document)load("staff",false);
root=doc.getDocumentElement();
tagname=root.getTagName();
if (("image/svg+xml".equals(getContentType()))) {
assertEquals("svgTagName","svg",tagname);
}
else {
assertEquals("elementGetTagNameAssert","staff",tagname);
}
}
| Runs the test case. |
private void determineCoverageGoals(){
List<InputCoverageTestFitness> goals=new InputCoverageFactory().getCoverageGoals();
for ( InputCoverageTestFitness goal : goals) {
inputCoverageMap.add(goal);
if (Properties.TEST_ARCHIVE) TestsArchive.instance.addGoalToCover(this,goal);
}
}
| Initialize the set of known coverage goals |
public static void unregisterFieldPrefix(final String prefix){
fieldPrefixes.remove(prefix);
}
| If a prefix is no longer needed unregister it here. |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.