code
stringlengths 10
174k
| nl
stringlengths 3
129k
|
---|---|
public synchronized CtClass makeInterface(String name,CtClass superclass) throws RuntimeException {
checkNotFrozen(name);
CtClass clazz=new CtNewClass(name,this,true,superclass);
cacheCtClass(name,clazz,true);
return clazz;
}
| Creates a new public interface. If there already exists a class/interface with the same name, the new interface overwrites that previous one. |
public static void assertAllIntents(Speechlet speechlet,Session session) throws SpeechletException, IllegalAccessException {
Field[] fields=ObaIntent.class.getFields();
SpeechletResponse sr;
HashMap<String,Slot> slots=new HashMap<>();
slots.put(CITY_NAME,Slot.builder().withName(CITY_NAME).withValue("Tampa").build());
slots.put(STOP_NUMBER,Slot.builder().withName(STOP_NUMBER).withValue("6497").build());
for ( Field f : fields) {
sr=speechlet.onIntent(IntentRequest.builder().withRequestId("test-request-id").withIntent(Intent.builder().withName(f.get(String.class).toString()).withSlots(slots).build()).build(),session);
assertNotNull(sr);
}
}
| Check to make sure that the provided speechlet correctly handles all intents defined in ObaIntent |
public legend addElement(String hashcode,String element){
addElementToRegistry(hashcode,element);
return (this);
}
| Adds an Element to the element. |
private boolean isRepeatSearchEnabled(){
return FILTER != null;
}
| Determines whether or not repeat search is currently enabled. Repeat search will be disabled if, for example, the original search was performed too recently. |
@Inline public static void doubleBulkCopy(double[] src,Offset srcOffset,double[] dst,Offset dstOffset,int bytes){
if (VM.VerifyAssertions) VM._assert(DOUBLE_BULK_COPY_SUPPORTED);
if (!Selected.Mutator.get().doubleBulkCopy(ObjectReference.fromObject(src),srcOffset,ObjectReference.fromObject(dst),dstOffset,bytes)) {
Memory.aligned64Copy(Magic.objectAsAddress(dst).plus(dstOffset),Magic.objectAsAddress(src).plus(srcOffset),bytes);
}
}
| Barrier for a bulk copy of doubles (i.e. in an array copy). |
public LinkActionList(Link link,Layer layer,Projection proj,OMGridGenerator generator) throws IOException, EOFException {
this.link=link;
linkStatus=readGestureResponses(layer,proj,generator);
}
| Read the gesture section off the link, from the client. |
public void purgeCacheForProvider(ProviderIdentifier id){
List<String> keysToRemove;
synchronized (mPlaylists) {
Set<Map.Entry<String,Playlist>> playlists=mPlaylists.entrySet();
keysToRemove=new ArrayList<>();
for ( Map.Entry<String,Playlist> item : playlists) {
if (item.getValue() == null || item.getValue().getProvider().equals(id)) {
keysToRemove.add(item.getKey());
}
}
for ( String key : keysToRemove) {
mPlaylists.remove(key);
}
}
synchronized (mSongs) {
Set<Map.Entry<String,Song>> songs=mSongs.entrySet();
keysToRemove.clear();
for ( Map.Entry<String,Song> item : songs) {
if (item.getValue().getProvider() != null && item.getValue().getProvider().equals(id)) {
keysToRemove.add(item.getKey());
}
}
for ( String key : keysToRemove) {
mSongs.remove(key);
}
}
synchronized (mAlbums) {
Set<Map.Entry<String,Album>> albums=mAlbums.entrySet();
keysToRemove.clear();
for ( Map.Entry<String,Album> item : albums) {
if (item.getValue().getProvider().equals(id)) {
keysToRemove.add(item.getKey());
}
}
for ( String key : keysToRemove) {
mAlbums.remove(key);
}
}
synchronized (mArtists) {
Set<Map.Entry<String,Artist>> artists=mArtists.entrySet();
keysToRemove.clear();
for ( Map.Entry<String,Artist> item : artists) {
if (item.getValue().getProvider().equals(id)) {
keysToRemove.add(item.getKey());
}
}
for ( String key : keysToRemove) {
mArtists.remove(key);
}
}
}
| Purges the cache in case the provider may change for the specified provider |
public GeneralAlgorithmRunner(DataWrapper dataWrapper,Parameters parameters,KnowledgeBoxModel knowledgeBoxModel,IndependenceFactsModel facts){
this(dataWrapper,null,parameters,knowledgeBoxModel,facts);
}
| Constructs a wrapper for the given DataWrapper. The DatWrapper must contain a DataSet that is either a DataSet or a DataSet or a DataList containing either a DataSet or a DataSet as its selected model. |
public static void registerFactory(String type,AllocationCommand.Factory factory){
factories.put(type,factory);
}
| Register a custom index meta data factory. Make sure to call it from a static block. |
private void validateInitiatorsData(List<Initiator> initiators,Set<URI> initiatorsHosts,ExportGroup exportGroup){
if (initiatorsHosts.size() != 1) {
throw APIException.badRequests.initiatorExportGroupInitiatorsBelongToSameHost();
}
Host host=queryObject(Host.class,initiatorsHosts.iterator().next(),true);
if (!NullColumnValueGetter.isNullURI(host.getProject())) {
if (!host.getProject().equals(exportGroup.getProject().getURI())) {
throw APIException.badRequests.invalidParameterExportGroupHostAssignedToDifferentProject(host.getHostName(),exportGroup.getProject().getName());
}
}
else {
Project project=queryObject(Project.class,exportGroup.getProject().getURI(),true);
if (!host.getTenant().equals(project.getTenantOrg().getURI())) {
throw APIException.badRequests.invalidParameterExportGroupHostAssignedToDifferentTenant(host.getHostName(),project.getLabel());
}
}
validatePortConnectivity(exportGroup,initiators);
_log.info("The initiators were validated successfully.");
}
| Validates that the host belongs to same tenant org and/or project as the export group. Also validates that the host has connectivity to all the storage systems that the export group has block objects in. |
public void exitToConfig() throws NetworkDeviceControllerException {
if (!inConfigMode) {
throw NetworkDeviceControllerException.exceptions.mdsDeviceNotInConfigMode();
}
SSHPrompt[] prompts={SSHPrompt.MDS_CONFIG};
StringBuilder buf=new StringBuilder();
lastPrompt=sendWaitFor(MDSDialogProperties.getString("MDSDialog.exitToConfig.exit.cmd"),defaultTimeout,prompts,buf);
}
| Exits from an inner config mode to config mode. |
public void removeDivider(int divId) throws Exception {
m_fdr.getDocumentTree().removeDivider(divId);
}
| Elimina un clasificador |
public T caseTypeRefAnnotationArgument(TypeRefAnnotationArgument object){
return null;
}
| Returns the result of interpreting the object as an instance of '<em>Type Ref Annotation Argument</em>'. <!-- begin-user-doc --> This implementation returns null; returning a non-null result will terminate the switch. <!-- end-user-doc --> |
static void appendConstant(final StringBuffer buf,final Object cst){
if (cst == null) {
buf.append("null");
}
else if (cst instanceof String) {
appendString(buf,(String)cst);
}
else if (cst instanceof Type) {
buf.append("Type.getType(\"");
buf.append(((Type)cst).getDescriptor());
buf.append("\")");
}
else if (cst instanceof Handle) {
buf.append("new Handle(");
Handle h=(Handle)cst;
buf.append("Opcodes.").append(HANDLE_TAG[h.getTag()]).append(", \"");
buf.append(h.getOwner()).append("\", \"");
buf.append(h.getName()).append("\", \"");
buf.append(h.getDesc()).append("\")");
}
else if (cst instanceof Byte) {
buf.append("new Byte((byte)").append(cst).append(')');
}
else if (cst instanceof Boolean) {
buf.append(((Boolean)cst).booleanValue() ? "Boolean.TRUE" : "Boolean.FALSE");
}
else if (cst instanceof Short) {
buf.append("new Short((short)").append(cst).append(')');
}
else if (cst instanceof Character) {
int c=((Character)cst).charValue();
buf.append("new Character((char)").append(c).append(')');
}
else if (cst instanceof Integer) {
buf.append("new Integer(").append(cst).append(')');
}
else if (cst instanceof Float) {
buf.append("new Float(\"").append(cst).append("\")");
}
else if (cst instanceof Long) {
buf.append("new Long(").append(cst).append("L)");
}
else if (cst instanceof Double) {
buf.append("new Double(\"").append(cst).append("\")");
}
else if (cst instanceof byte[]) {
byte[] v=(byte[])cst;
buf.append("new byte[] {");
for (int i=0; i < v.length; i++) {
buf.append(i == 0 ? "" : ",").append(v[i]);
}
buf.append('}');
}
else if (cst instanceof boolean[]) {
boolean[] v=(boolean[])cst;
buf.append("new boolean[] {");
for (int i=0; i < v.length; i++) {
buf.append(i == 0 ? "" : ",").append(v[i]);
}
buf.append('}');
}
else if (cst instanceof short[]) {
short[] v=(short[])cst;
buf.append("new short[] {");
for (int i=0; i < v.length; i++) {
buf.append(i == 0 ? "" : ",").append("(short)").append(v[i]);
}
buf.append('}');
}
else if (cst instanceof char[]) {
char[] v=(char[])cst;
buf.append("new char[] {");
for (int i=0; i < v.length; i++) {
buf.append(i == 0 ? "" : ",").append("(char)").append((int)v[i]);
}
buf.append('}');
}
else if (cst instanceof int[]) {
int[] v=(int[])cst;
buf.append("new int[] {");
for (int i=0; i < v.length; i++) {
buf.append(i == 0 ? "" : ",").append(v[i]);
}
buf.append('}');
}
else if (cst instanceof long[]) {
long[] v=(long[])cst;
buf.append("new long[] {");
for (int i=0; i < v.length; i++) {
buf.append(i == 0 ? "" : ",").append(v[i]).append('L');
}
buf.append('}');
}
else if (cst instanceof float[]) {
float[] v=(float[])cst;
buf.append("new float[] {");
for (int i=0; i < v.length; i++) {
buf.append(i == 0 ? "" : ",").append(v[i]).append('f');
}
buf.append('}');
}
else if (cst instanceof double[]) {
double[] v=(double[])cst;
buf.append("new double[] {");
for (int i=0; i < v.length; i++) {
buf.append(i == 0 ? "" : ",").append(v[i]).append('d');
}
buf.append('}');
}
}
| Appends a string representation of the given constant to the given buffer. |
public ItemBuilder amount(final ItemStack src){
this.itemStack.setAmount(src.getAmount());
return this;
}
| Set amount of material of item. |
@Override public Project store(AppContext ctx,Project newProject){
boolean updateMode;
ProjectPK id=newProject.getId();
if (id.getObjectId() == null) {
id.setObjectId(ObjectId.get().toString());
newProject.setId(id);
newProject.copyInternalVersion(null);
updateMode=false;
}
else {
Optional<Project> read=DAOFactory.getDAOFactory().getDAO(Project.class).read(ctx,id);
if (read.isPresent()) {
newProject.copyInternalVersion(read.get());
updateMode=true;
}
else {
updateMode=false;
}
}
if (!updateMode) {
String projectOid=newProject.getId().getProjectId();
Persistent<? extends GenericPK> parent=newProject.getParentObject(ctx);
AccessRightsUtils.getInstance().checkRole(ctx,parent,Role.WRITE);
AccessRightsUtils.getInstance().setAccessRights(ctx,newProject,parent);
Set<AccessRight> projectAccessRights=newProject.getAccessRights();
UserGroup adminGroup=new UserGroup();
adminGroup.setId(new UserGroupPK(ctx.getCustomerId(),CoreConstants.PRJ_DEFAULT_GROUP_ADMIN + projectOid));
adminGroup.setName("Administrators for project " + newProject.getName());
UserGroup newAdminGroup=DAOFactory.getDAOFactory().getDAO(UserGroup.class).create(ctx,adminGroup);
AccessRight writeRight=new AccessRight();
writeRight.setRole(Role.WRITE);
writeRight.setGroupId(newAdminGroup.getId().getUserGroupId());
projectAccessRights.add(writeRight);
UserGroup guestGroup=new UserGroup();
guestGroup.setId(new UserGroupPK(ctx.getCustomerId(),CoreConstants.PRJ_DEFAULT_GROUP_GUEST + projectOid));
guestGroup.setName("Guests for project " + newProject.getName());
UserGroup newGuestGroup=DAOFactory.getDAOFactory().getDAO(UserGroup.class).create(ctx,guestGroup);
AccessRight readRight=new AccessRight();
readRight.setRole(Role.READ);
readRight.setGroupId(newGuestGroup.getId().getUserGroupId());
projectAccessRights.add(readRight);
}
newProject=super.store(ctx,newProject);
return newProject;
}
| Create a project. The creation includes the following steps: <ul> <li>Create the project</li> <li>Create the admin group called admin_<projectId></li> <li>Grant WRITE access right to admin_<projectId> group</li> <li>Create the guest group called guest_<projectId></li> <li>Grant READ access right to guest_<projectId> group</li> </ul> |
public IntBag(final IntBag other){
if (other == null) {
numObjs=0;
objs=new int[1];
}
else {
numObjs=other.numObjs;
objs=new int[numObjs];
System.arraycopy(other.objs,0,objs,0,numObjs);
}
}
| Adds the ints from the other IntBag without copying them. The size of the new IntBag is the minimum necessary size to hold the ints. If the Other IntBag is null, a new empty IntBag is created. |
public ColladaFile(File file){
if (file == null) {
String message=Logging.getMessage("nullValue.FileIsNull");
Logging.logger().severe(message);
throw new IllegalArgumentException(message);
}
this.colladaFile=file;
}
| Create a new instance from a file. |
public SoapFaultToClientProxy(){
requestFileName="fault.query";
responseFile="getstate.answer";
}
| Constructs the test case. |
public boolean visitVariableOrParamDecl(ElemVariable elem){
return true;
}
| Visit an XSLT variable or parameter declaration. |
private void readOutlineLevel(final Element root,final PdfObjectReader currentPdfFile,PdfObject outlineObj,final int level,boolean isClosed){
String ID;
int page;
Element child=OutlineDataXML.createElement("title");
PdfObject FirstObj, NextObj;
while (true) {
ID=outlineObj.getObjectRefAsString();
FirstObj=outlineObj.getDictionary(PdfDictionary.First);
currentPdfFile.checkResolved(FirstObj);
NextObj=outlineObj.getDictionary(PdfDictionary.Next);
currentPdfFile.checkResolved(NextObj);
final int numberOfItems=outlineObj.getInt(PdfDictionary.Count);
if (numberOfItems != 0) {
isClosed=numberOfItems < 0;
}
page=DestHandler.getPageNumberFromLink(getDestFromObject(outlineObj,currentPdfFile),currentPdfFile);
final byte[] titleData=outlineObj.getTextStreamValueAsByte(PdfDictionary.Title);
if (titleData != null) {
final String title=StringUtils.getTextString(titleData,false);
child=OutlineDataXML.createElement("title");
root.appendChild(child);
child.setAttribute("title",title);
}
child.setAttribute("isClosed",String.valueOf(isClosed));
if (outlineObj != null) {
DestObjs.put(ID,outlineObj);
}
if (page == PdfDictionary.Null) {
child.setAttribute("page","-1");
}
else if (page != -1) {
child.setAttribute("page",String.valueOf(page));
}
child.setAttribute("level",String.valueOf(level));
child.setAttribute("objectRef",ID);
if (FirstObj != null) {
readOutlineLevel(child,currentPdfFile,FirstObj,level + 1,isClosed);
}
if (NextObj == null) {
break;
}
outlineObj=NextObj;
}
}
| read a level |
@Override protected void initViews(Bundle savedInstanceState){
this.aidlTV=(TextView)this.findViewById(R.id.aidl_tv);
}
| Initialize the view in the layout |
private void replaceTop(JsonScope newTop){
stack.set(stack.size() - 1,newTop);
}
| Replace the value on the top of the stack with the given value. |
public FactLine reverse(String description){
FactLine reversal=new FactLine(getCtx(),getAD_Table_ID(),getRecord_ID(),getLine_ID(),get_TrxName());
reversal.setClientOrg(this);
reversal.setDocumentInfo(m_doc,m_docLine);
reversal.setAccount(m_acctSchema,m_acct);
reversal.setPostingType(getPostingType());
reversal.setAmtSource(getC_Currency_ID(),getAmtSourceDr().negate(),getAmtSourceCr().negate());
reversal.setQty(getQty().negate());
reversal.convert();
reversal.setDescription(description);
return reversal;
}
| Create Reversal (negate DR/CR) of the line |
public ProvidedRuntimeLibraryDependency createProvidedRuntimeLibraryDependency(){
ProvidedRuntimeLibraryDependencyImpl providedRuntimeLibraryDependency=new ProvidedRuntimeLibraryDependencyImpl();
return providedRuntimeLibraryDependency;
}
| <!-- begin-user-doc --> <!-- end-user-doc --> |
public void addSufficientVerifier(int uid){
mSufficientVerifierUids.put(uid,true);
}
| Add a verifier which is added to our sufficient list. |
public void debug(BoundedObject o){
System.out.println("debug: target bounding box " + o.getBounds());
debug(o,root,0);
}
| Find an object in the tree without using bounding boxes |
public boolean isInRange(int index){
if (m_Upper == -1) {
throw new RuntimeException("No upper limit has been specified for range");
}
if (m_Invert) {
return !m_SelectFlags[index];
}
else {
return m_SelectFlags[index];
}
}
| Gets whether the supplied cardinal number is included in the current range. |
public void onError(DiagnosticListener<JavaFileObject> callback){
errorsDelegate=callback;
}
| Send all errors to callback, replacing any existing callback |
@Override public int hashCode(){
return (first == null ? 0 : first.hashCode()) ^ (second == null ? 0 : second.hashCode());
}
| Compute a hash code using the hash codes of the underlying objects |
public static String encodeNumericKeyId(long keyId){
return String.format("%016X",keyId);
}
| *********************************************************************************** Hex encode given numeric key id. |
public void testLogReadback() throws Exception {
File logDir=prepareLogDir("testLogReadback");
DiskLog log=openLog(logDir,false);
this.writeEventsToLog(log,10000);
assertEquals("Should have stored 10000 events",9999,log.getMaxSeqno());
log.release();
DiskLog log2=openLog(logDir,true);
log.validate();
assertEquals("Should have stored 10000 events",9999,log2.getMaxSeqno());
this.readBackStoredEvents(log2,0,10000);
log2.release();
}
| Confirm that we can write to and read back from the log. |
public static int nextInt(int max){
return random.nextInt(max);
}
| <p> nextInt </p> |
public void process(Grammar g,boolean gencode){
g.loadImportedGrammars();
GrammarTransformPipeline transform=new GrammarTransformPipeline(g,this);
transform.process();
LexerGrammar lexerg;
GrammarRootAST lexerAST;
if (g.ast != null && g.ast.grammarType == ANTLRParser.COMBINED && !g.ast.hasErrors) {
lexerAST=transform.extractImplicitLexer(g);
if (lexerAST != null) {
if (grammarOptions != null) {
lexerAST.cmdLineOptions=grammarOptions;
}
lexerg=new LexerGrammar(this,lexerAST);
lexerg.fileName=g.fileName;
lexerg.originalGrammar=g;
g.implicitLexer=lexerg;
lexerg.implicitLexerOwner=g;
processNonCombinedGrammar(lexerg,gencode);
}
}
if (g.implicitLexer != null) g.importVocab(g.implicitLexer);
processNonCombinedGrammar(g,gencode);
}
| To process a grammar, we load all of its imported grammars into subordinate grammar objects. Then we merge the imported rules into the root grammar. If a root grammar is a combined grammar, we have to extract the implicit lexer. Once all this is done, we process the lexer first, if present, and then the parser grammar |
public static TextAnnotation buildTextAnnotation(String corpusId,String textId,String text,String[] tokens,int[] sentenceEndPositions,String sentenceViewGenerator,double sentenceViewScore){
if (sentenceEndPositions[sentenceEndPositions.length - 1] != tokens.length) throw new IllegalArgumentException("Invalid sentence boundary. Last element should be the number of tokens");
IntPair[] offsets=TokenUtils.getTokenOffsets(text,tokens);
assert offsets.length == tokens.length;
TextAnnotation ta=new TextAnnotation(corpusId,textId,text,offsets,tokens,sentenceEndPositions);
SpanLabelView view=new SpanLabelView(ViewNames.SENTENCE,sentenceViewGenerator,ta,sentenceViewScore);
int start=0;
for ( int s : sentenceEndPositions) {
view.addSpanLabel(start,s,ViewNames.SENTENCE,1d);
start=s;
}
ta.addView(ViewNames.SENTENCE,view);
SpanLabelView tokView=new SpanLabelView(ViewNames.TOKENS,sentenceViewGenerator,ta,sentenceViewScore);
for (int tokIndex=0; tokIndex < tokens.length; ++tokIndex) {
tokView.addSpanLabel(tokIndex,tokIndex + 1,tokens[tokIndex],1d);
}
ta.addView(ViewNames.TOKENS,tokView);
return ta;
}
| instantiate a TextAnnotation using a SentenceViewGenerator to create an explicit Sentence view |
private static String guessContentType(String url){
url=url.toLowerCase();
if (url.endsWith(".webm")) {
return "video/webm";
}
else if (url.endsWith(".mp4")) {
return "video/mp4";
}
else if (url.matches(".*\\.jpe?g")) {
return "image/jpeg";
}
else if (url.endsWith(".png")) {
return "image/png";
}
else if (url.endsWith(".gif")) {
return "image/gif";
}
else {
return "application/octet-stream";
}
}
| Guess a content type from the URL. |
public FilteredTollHandler(final double simulationEndTime,final int numberOfTimeBins){
this(simulationEndTime,numberOfTimeBins,null,null);
LOGGER.info("No filtering is used, result will include all links, persons from all user groups.");
}
| No filtering will be used, result will include all links, persons from all user groups. |
public boolean isSecondHandVisible(){
return secondHandVisible;
}
| Return secondHandVisible |
public XMLDocument addStylesheet(String href,String type){
PI pi=new PI();
pi.setTarget("xml-stylesheet").addInstruction("href",href).addInstruction("type",type);
prolog.addElement(pi);
return (this);
}
| This adds a stylesheet to the XML document. |
public GenericMTreeDistanceSearchCandidate(final double mindist,final int nodeID,final DBID routingObjectID){
this.mindist=mindist;
this.nodeID=nodeID;
this.routingObjectID=routingObjectID;
}
| Creates a new heap node with the specified parameters. |
private static int lf_delta1(int x){
return lf_S(x,17) ^ lf_S(x,19) ^ lf_R(x,10);
}
| logical function delta1(x) - xor of results of right shifts/rotations |
public Tree<String> extractBestMaxRuleParse(int start,int end,List<String> sentence){
return extractBestMaxRuleParse1(start,end,0,sentence);
}
| Returns the best parse, the one with maximum expected labelled recall. Assumes that the maxc* arrays have been filled. |
public int lastIndexOf(char ch){
return lastIndexOf(ch,size - 1);
}
| Searches the string builder to find the last reference to the specified char. |
public Matrix4x3f m00(float m00){
this.m00=m00;
properties&=~(PROPERTY_IDENTITY | PROPERTY_TRANSLATION);
return this;
}
| Set the value of the matrix element at column 0 and row 0 |
private List<HostStorageDomain> processTargetPortsToFormHSDs(HDSApiClient hdsApiClient,StorageSystem storage,List<URI> targetURIList,String hostName,ExportMask exportMask,Pair<String,String> hostModeInfo,String systemObjectID) throws Exception {
List<HostStorageDomain> hsdList=new ArrayList<HostStorageDomain>();
String hostMode=null, hostModeOption=null;
if (hostModeInfo != null) {
hostMode=hostModeInfo.first;
hostModeOption=hostModeInfo.second;
}
for ( URI targetPortURI : targetURIList) {
StoragePort storagePort=dbClient.queryObject(StoragePort.class,targetPortURI);
String storagePortNumber=getStoragePortNumber(storagePort.getNativeGuid());
DataSource dataSource=dataSourceFactory.createHSDNickNameDataSource(hostName,storagePortNumber,storage);
String hsdNickName=customConfigHandler.getComputedCustomConfigValue(CustomConfigConstants.HDS_HOST_STORAGE_DOMAIN_NICKNAME_MASK_NAME,storage.getSystemType(),dataSource);
if (Transport.IP.name().equalsIgnoreCase(storagePort.getTransportType())) {
log.info("Populating iSCSI HSD for storage: {}",storage.getSerialNumber());
HostStorageDomain hostGroup=new HostStorageDomain(storagePortNumber,exportMask.getMaskName(),HDSConstants.ISCSI_TARGET_DOMAIN_TYPE,hsdNickName);
hostGroup.setHostMode(hostMode);
hostGroup.setHostModeOption(hostModeOption);
hsdList.add(hostGroup);
}
if (Transport.FC.name().equalsIgnoreCase(storagePort.getTransportType())) {
log.info("Populating FC HSD for storage: {}",storage.getSerialNumber());
HostStorageDomain hostGroup=new HostStorageDomain(storagePortNumber,exportMask.getMaskName(),HDSConstants.HOST_GROUP_DOMAIN_TYPE,hsdNickName);
hostGroup.setHostMode(hostMode);
hostGroup.setHostModeOption(hostModeOption);
hsdList.add(hostGroup);
}
}
return hsdList;
}
| This routine iterates through the target ports and prepares a batch of HostStorageDomain Objects with required information. |
private int isInResults(ArrayList<Media> results,String id){
int i=0;
for ( Media item : results) {
if (item.videoId.equals(id)) return i;
i++;
}
return -1;
}
| Test if there is an item that already exists |
private String parseToken(final char[] terminators){
char ch;
i1=pos;
i2=pos;
while (hasChar()) {
ch=chars[pos];
if (isOneOf(ch,terminators)) {
break;
}
i2++;
pos++;
}
return getToken(false);
}
| Parse out a token until any of the given terminators is encountered. |
@Ignore("TODO: disabled because rather than throwing an exception, getAll catches all exceptions and logs a warning message") @Test public void testNonColocatedGetAll(){
doNonColocatedbulkOp(OP.GETALL);
}
| disabled because rather than throwing an exception, getAll catches all exceptions and logs a warning message |
@Override protected PfScanRawMatch buildMatchObject(String sequenceIdentifier,String model,String signatureLibraryRelease,int seqStart,int seqEnd,String cigarAlign,Double score,ProfileScanRawMatch.Level profileLevel,PatternScanMatch.PatternScanLocation.Level patternLevel){
return new HamapRawMatch(sequenceIdentifier,model,signatureLibraryRelease,seqStart,seqEnd,cigarAlign,score,profileLevel);
}
| Method to be implemented that builds the correct kind of PfScanRawMatch. |
private void updateServerStatus(){
try {
StringBuffer page=new StringBuffer();
page.append("<?php\n");
page.append("session_start();\n");
page.append("$username = 'Guest';\n");
page.append("if (array_key_exists('username', $_SESSION)) { $username = $_SESSION['username']; }\n");
page.append("?>\n");
page.append("<html>\n<head>\n <title>R Server</title>\n");
page.append(" <script>\n");
page.append(" function reload() { \n");
page.append(" var isIE = /*@cc_on!@*/false || !!document.documentMode;\n");
page.append(" if (!isIE) location.reload();\n");
page.append(" }\n");
page.append(" setTimeout(reload, " + pageRefreshTime + ")\n");
page.append(" </script>\n");
page.append(" <link rel=\"stylesheet\" type=\"text/css\" href=\"rserver.css\">\n");
page.append("</head>\n<body>\n");
page.append("<div id=\"MainDiv\">\n\n");
page.append("<div id=\"HeaderDiv\">\n");
page.append(" <div id=\"NavHeaderDiv\"></div>\n");
page.append(" <div id=\"NavLogo\"></div>\n");
page.append(" <a id=\"newHeaderNavigation-logo\" href=\"/RServer\" title=\"R Server\"></a>\n");
page.append(" <ul id=\"NavBar\">\n");
page.append(" <li><a href=\"https://github.com/bgweber/RServer\">EA RServer</a></li>\n");
page.append(" <li><a href=\"NewTask.php\">Submit New Task</a>\n");
page.append(" <li><a href=\"Reports.php\">Reports</a></li>\n");
page.append(" <li><a href=\"logs\">Server Logs</a></li>\n");
page.append(" <li><a href=\"Rout\">Script Results</a></li>\n");
page.append(" <li><a href=\"reports/RServer/RServerTasks.html\">Task Report</a></li>\n");
page.append(" </ul>\n\n");
page.append("</div>\n\n");
page.append(" <div id=\"SubHeaderDiv\">\n");
page.append(" <h2 id=\"RHeader\">R Server: </h2>\n");
page.append("<?php if ((time() - " + System.currentTimeMillis() / 1000 + ") < 10) { " + "echo \"<h2 id=\\\"ServerOnline\\\">Online</h2>\"; } else { " + "echo \"<h2 id=\\\"ServerOffline\\\">Offline</h2>\"; } ?>\n");
page.append(" </div>\n\n");
page.append(" <div id=\"ContentDiv\">\n");
page.append(" <script>\n");
page.append(" var isIE = /*@cc_on!@*/false || !!document.documentMode;\n");
page.append(" if (isIE) document.write('<p><h2>Note: Auto-reload is disabled for Internet Explorer. Please use Chrome, Firefox, or Opera.<h2>'); \n");
page.append(" </script>\n");
page.append("<h3 id=\"StatsHeader\">Server Statistics</h3>\n");
page.append("<table id=\"StatsTable\">\n");
page.append(" <thead>\n");
page.append(" <th>Property</th>\n <th>Value</th>\n");
page.append(" </thead>\n");
if (fullHostName != null) {
page.append(" <tr><td>Server Name</td><td>" + fullHostName + "</td></tr>\n");
}
page.append(" <tr><td>Server Updated</td><td>" + new Date(System.currentTimeMillis()).toString() + "</td></tr>\n");
Runtime runtime=Runtime.getRuntime();
String memory=((runtime.totalMemory() - runtime.freeMemory()) / 1024 / 1024) + " / " + ((runtime.totalMemory()) / 1024 / 1024)+ " MB";
try {
double totalMem=sigar.getMem().getTotal() / 1024 / 1024/ 1024.0;
double usedMem=(sigar.getMem().getTotal() - sigar.getMem().getFree()) / 1024 / 1024/ 1024.0;
cpuLoad=1 - sigar.getCpuPerc().getIdle();
totalMem=((int)(totalMem * 10)) / 10.0;
usedMem=((int)(usedMem * 10)) / 10.0;
page.append(" <tr><td>Server CPU Usage</td><td>" + (((int)(cpuLoad * 1000)) / 10.0) + "%</td></tr>\n");
page.append(" <tr><td>Server Memory</td><td>" + usedMem + " / "+ totalMem+ " GB</td></tr>\n");
}
catch ( Exception e) {
log("ERROR: unable to update system stats: " + e.getMessage());
}
page.append(" <tr><td>Application Memory</td><td>" + memory + "</td></tr>\n");
page.append(" <tr><td>Thread Count</td><td>" + Thread.activeCount() + "</td></tr>\n");
page.append(" <tr><td>Git Updated</td><td>" + (lastPerforceUpdate > 0 ? new Date(lastPerforceUpdate).toString() : "No history") + "</td></tr>\n");
page.append(" <tr><td>Server Launched</td><td>" + new Date(bootTime).toString() + "</td></tr>\n");
page.append(" <tr><td>Server Version</td><td>" + ServerDate + "</td></tr>\n");
page.append("</table>\n\n");
page.append("<h3 id=\"LogHeader\">R Server Reports</h3>\n");
page.append("<ul id=\"LogList\">\n");
page.append(" <li><a href=\"reports/RServer/RServerReport.html\">R Server Activity</a></li>\n");
page.append(" <li><a href=\"reports/RServer/RServerTasks.html\">Task Report</a></li>\n");
page.append("</ul>\n");
page.append("<h3 id=\"RunningHeader\">Running Tasks</h3>\n");
page.append("<table id=\"RunningTable\">\n");
page.append(" <thead>\n");
page.append(" <th>Task Name</th>\n <th>Log File</th>\n <th>Start Time</th>\n <th>Duration</th>\n " + "<th>Runtime Parameters</th>\n <th>Owner</th>\n <th>End Process</th>\n");
page.append(" </thead>\n");
synchronized (RServer.this) {
for ( Task task : runningTasks.values()) {
long startTime=task.getStartTime();
long duration=(System.currentTimeMillis() - startTime) / 1000;
page.append(" <tr>\n");
page.append(" <td>" + (task.getShinyApp() ? "<a href=\"" + task.getShinyUrl() + "\">" : "") + task.getTaskName()+ (task.getShinyApp() ? "</a>" : "")+ "</td>");
if (task.getrScript().toLowerCase().contains(".r") || task.getIsPython()) {
String link="<a href=\"Rout.php?task=" + task.getTaskName() + "&log="+ (task.getrScript().contains(".r") ? task.getrScript() + ".Rout" : task.getrScript().split("\\.")[0] + ".Rout")+ "\">"+ task.getrScript()+ "</a>";
page.append("\n <td>" + link + "</td>");
}
else {
page.append("\n <td> </td>");
}
page.append("\n <td>" + new Date(startTime).toString() + "</td>");
page.append("\n <td>" + (task.getShinyApp() ? "" : (duration / 60 + " m " + duration % 60 + " s")) + "</td>");
page.append("\n <td>" + task.getParameters() + "</td>");
page.append("\n <td>" + task.getOwner() + "</td>");
if (PerforceTask.equalsIgnoreCase(task.getTaskName())) {
page.append("\n <td> </td>");
}
else {
page.append("\n <td><form onsubmit=\"return confirm('Are you sure?')\"" + " action=\"KillTask.php\" method=\"post\">" + "\n <input type=\"hidden\" name=\"name\" value=\"" + task.getTaskName() + "\" />"+ "\n <button"+ " >Terminate</button>\n </form></td>");
}
page.append("\n </tr>\n");
}
}
page.append("</table>\n\n");
page.append("<h3 id=\"LogHeader\">Recent Log Entries</h3>\n");
synchronized (RServer.this) {
page.append("<ul id=\"LogList\">\n");
for ( String log : logEntries) {
if (log.contains("ERROR:")) {
page.append(" <li class=\"FontLogError\">" + log + "</li>\n");
}
else {
page.append(" <li>" + log + "</li>\n");
}
}
page.append("</ul>\n\n");
}
page.append("<h3 id=\"SchedulesHeader\">Scheduled Tasks</h3>\n");
page.append("<table id=\"ScheduleTable\">\n");
page.append(" <thead>\n");
page.append(" <th>Task Name</th>\n <th>R Script</th>\n <th>Runtime Parameters</th>\n <th>Frequency</th>\n " + "<th>Next Run Time</th>\n <th>Owner</th>\n <th>Run Now</th>\n");
page.append(" </thead>\n");
page.append("<ul id=\"LogList\">\n");
if (schedulePath.split("//").length > 1) {
page.append(" <li>Schedule File: //" + schedulePath.split("//")[1] + "</li>\n");
}
else {
page.append(" <li>Schedule File: " + schedulePath + "</li>\n");
}
page.append("</ul>\n");
for ( Schedule schedule : regularSchedules) {
page.append(" <tr>\n");
page.append(" <td>" + schedule.getTaskName().replace("_"," ") + "</td>\n "+ "<td>"+ schedule.getrScript().replace("_"," ")+ "</td>\n "+ "<td>"+ schedule.getParameters()+ "</td>\n "+ "<td>"+ (schedule.getFrequency() == Schedule.Frequency.Now ? "Startup" : schedule.getFrequency())+ "</td>\n <td>"+ (schedule.getFrequency() == Schedule.Frequency.Now || schedule.getFrequency() == Schedule.Frequency.Never ? " " : new Date(schedule.getNextRunTime()).toString())+ "</td>\n <td>"+ schedule.getOwner()+ "</td>\n "+ "<td><form onsubmit=\"return confirm('Are you sure?')\""+ " action=\"SubmitTask.php\" method=\"post\">"+ "\n <input type=\"hidden\" name=\"name\" value=\""+ schedule.getTaskName()+ "\" />"+ "\n <input type=\"hidden\" name=\"path\" value=\""+ schedule.getPerforcePath()+ "\" />"+ "\n <input type=\"hidden\" name=\"rscript\" value=\""+ schedule.getrScript()+ "\" />"+ "\n <input type=\"hidden\" name=\"email\" value=\""+ schedule.getOwner()+ "\" />"+ "\n <input type=\"hidden\" name=\"sendemail\" value=\""+ schedule.getEmailOnSuccess()+ "\" />"+ "\n <input type=\"hidden\" name=\"params\" value=\""+ schedule.getParameters()+ "\" />"+ "\n <input type=\"hidden\" name=\"shiny\" value=\""+ schedule.getShinyApp()+ "\" />"+ "\n <button"+ ">Start</button>\n </form></td>\n");
page.append(" </tr>\n");
}
page.append("</table>\n\n");
page.append("<h3 id=\"CompletedHeader\">Completed Tasks</h3>\n");
page.append("<table id=\"CompletedTable\">\n");
page.append(" <thead>\n");
page.append(" <th>Task Name</th>\n <th>Completion Time</th>\n <th>Duration</th>\n " + "<th>Runtime Parameters</th>\n <th>Outcome</th><th>.Rout log</th>\n <th>Owner</th>\n");
page.append(" </thead>\n");
synchronized (RServer.this) {
for ( Task task : completed) {
long duration=(task.getEndTime() - task.getStartTime()) / 1000;
page.append(" <tr>\n");
page.append(" <td>" + task.getTaskName().replace("_"," ") + "</td>\n <td>");
page.append(" " + new Date(task.getEndTime()).toString() + "</td>\n <td>");
page.append(" " + (duration / 60 + " m " + duration % 60 + " s ") + "</td>\n <td>");
page.append(" " + task.getParameters() + "</td>\n <td>");
page.append(" " + (task.getOutcome().equals("Success") ? "<font class=\"FontTaskSuccess\">" : "<font class=\"FontTaskFailure\">"));
page.append(" " + task.getOutcome() + "</font></td>\n <td>");
if (task.getRout() != null) {
page.append("<a href=\"Rout.php?path=" + task.getRout() + "&log="+ task.getrScript()+ ".Rout\">"+ task.getrScript().replace("_"," ")+ "</a></td>\n");
}
else {
page.append(" </td>\n");
}
page.append(" " + "<td>" + task.getOwner() + "</td>\n");
page.append(" </tr>\n");
}
}
page.append("</table>\n\n");
page.append("</div>\n\n");
page.append("<div id=\"FooterDiv\">\n");
page.append(" <a href=\"https://github.com/bgweber/RServer\">RServer on GitHub</a>\n");
page.append("</div>\n\n");
page.append("</div>\n</body>\n</html>\n");
BufferedWriter writer=new BufferedWriter(new FileWriter(indexPagePath));
writer.write(page.toString());
writer.close();
}
catch ( Exception e) {
log("ERROR: failure updating server status: " + e.getMessage());
e.printStackTrace();
}
}
| Generates the index.php file for the server dashboard. |
public void removeServerById(int serverId){
servers.remove(serverId);
}
| Remove server with given unique id from list |
public TreeSet(Comparator c){
this(new TreeMap(c));
}
| Constructs a new, empty set, sorted according to the specified comparator. All elements inserted into the set must be <i>mutually comparable</i> by the specified comparator: <tt>comparator.compare(e1, e2)</tt> must not throw a <tt>ClassCastException</tt> for any elements <tt>e1</tt> and <tt>e2</tt> in the set. If the user attempts to add an element to the set that violates this constraint, the <tt>add(Object)</tt> call will throw a <tt>ClassCastException</tt>. |
public <T>T read(Supplier<T> operation){
try {
lock.readLock().lock();
return operation.get();
}
finally {
lock.readLock().unlock();
}
}
| Obtain a read lock, perform the operation, and release the read lock. |
public void test_nCopiesILjava_lang_Object(){
Object o=new Object();
List l=Collections.nCopies(100,o);
Iterator i=l.iterator();
Object first=i.next();
assertTrue("Returned list consists of copies not refs",first == o);
assertEquals("Returned list of incorrect size",100,l.size());
assertTrue("Contains",l.contains(o));
assertTrue("Contains null",!l.contains(null));
assertTrue("null nCopies contains",!Collections.nCopies(2,null).contains(o));
assertTrue("null nCopies contains null",Collections.nCopies(2,null).contains(null));
l=Collections.nCopies(20,null);
i=l.iterator();
for (int counter=0; i.hasNext(); counter++) {
assertTrue("List is too large",counter < 20);
assertNull("Element should be null: " + counter,i.next());
}
try {
l.add(o);
fail("Returned list is not immutable");
}
catch ( UnsupportedOperationException e) {
return;
}
try {
Collections.nCopies(-2,new HashSet());
fail("nCopies with negative arg didn't throw IAE");
}
catch ( IllegalArgumentException e) {
}
}
| java.util.Collections#nCopies(int, java.lang.Object) |
private void adjust(byte[] a,int aOff,byte[] b){
int x=(b[b.length - 1] & 0xff) + (a[aOff + b.length - 1] & 0xff) + 1;
a[aOff + b.length - 1]=(byte)x;
x>>>=8;
for (int i=b.length - 2; i >= 0; i--) {
x+=(b[i] & 0xff) + (a[aOff + i] & 0xff);
a[aOff + i]=(byte)x;
x>>>=8;
}
}
| add a + b + 1, returning the result in a. The a value is treated as a BigInteger of length (b.length * 8) bits. The result is modulo 2^b.length in case of overflow. |
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. |
@NonNull public DividerAdapterBuilder outerResource(@LayoutRes int resource){
return outerView(asViewFactory(resource));
}
| Sets the divider that appears before and after the wrapped adapters items. |
protected ExecutionEntryImpl(){
super();
}
| <!-- begin-user-doc --> <!-- end-user-doc --> |
protected void logDiagnostic(String msg){
if (isDiagnosticsEnabled()) {
logRawDiagnostic(diagnosticPrefix + msg);
}
}
| Output a diagnostic message to a user-specified destination (if the user has enabled diagnostic logging). |
public Code39Reader(boolean usingCheckDigit,boolean extendedMode){
this.usingCheckDigit=usingCheckDigit;
this.extendedMode=extendedMode;
}
| Creates a reader that can be configured to check the last character as a check digit, or optionally attempt to decode "extended Code 39" sequences that are used to encode the full ASCII character set. |
@Override protected EClass eStaticClass(){
return SexecPackage.Literals.UNSCHEDULE_TIME_EVENT;
}
| <!-- begin-user-doc --> <!-- end-user-doc --> |
@Override public void insertIfAbsent(final K s,final V v){
this.arc[getPartition(s)].insertIfAbsent(s,v);
}
| put a value to the cache if there was not an entry before do not return a previous content value |
private Tokenizer(final CharSequence text){
this.text=text;
this.matcher=WHITESPACE.matcher(text);
skipWhitespace();
nextToken();
}
| Construct a tokenizer that parses tokens from the given text. |
private BucketAdvisor(Bucket bucket,RegionAdvisor regionAdvisor){
super(bucket);
this.regionAdvisor=regionAdvisor;
this.pRegion=this.regionAdvisor.getPartitionedRegion();
resetParentAdvisor(bucket.getId());
}
| Constructs a new BucketAdvisor for the Bucket owned by RegionAdvisor. |
protected void prepareYLegend(){
ArrayList<Float> yLegend=new ArrayList<Float>();
if (mRoundedYLegend) {
float interval=(mDeltaY) / (mYLegendCount - 1);
double log10=Math.log10(interval);
int exp=(int)Math.floor(log10);
if (exp < 0) {
exp=0;
}
double tenPowExp=POW_10[exp + 5];
double multi=Math.round(interval / tenPowExp);
if (multi >= 1) {
if (multi > 2 && multi <= 3) {
multi=3;
}
else if (multi > 3 && multi <= 5) {
multi=5;
}
else if (multi > 5 && multi < 10) {
multi=10;
}
}
else {
multi=1;
}
float step=(float)(multi * tenPowExp);
log(" log10 is " + log10 + " interval is "+ interval+ " mDeltaY is "+ mDeltaY+ " tenPowExp is "+ tenPowExp+ " multi is "+ multi+ " mYChartMin is "+ mYChartMin+ " step is "+ step);
float val=0;
if (step >= 1f) {
val=(int)(mYChartMin / step) * step;
}
else {
val=mYChartMin;
}
while (val <= mDeltaY + step + mYChartMin) {
yLegend.add(val);
val=val + step;
}
if (step >= 1f) {
mYChartMin=(int)(mYChartMin / step) * step;
log("mYChartMin write --- step >= 1f -- and mYChartMin is " + mYChartMin);
}
mDeltaY=val - step - mYChartMin;
mYChartMax=yLegend.get(yLegend.size() - 1);
}
else {
float interval=(mDeltaY) / (mYLegendCount - 1);
yLegend.add(mYChartMin);
int i=1;
if (!isDrawOutline) {
i=0;
}
for (; i < mYLegendCount - 1; i++) {
yLegend.add(mYChartMin + ((float)i * interval));
}
yLegend.add(mDeltaY + mYChartMin);
}
mYLegend=yLegend.toArray(new Float[0]);
}
| setup the Y legend |
private static void displayHeaders(List<AdsenseReportsGenerateResponse.Headers> headers){
for ( AdsenseReportsGenerateResponse.Headers header : headers) {
System.out.printf("%25s",header.getName());
}
System.out.println();
}
| Displays the headers for the report. |
@Override protected void initData(){
ClassLoader classLoader=this.getClassLoader();
if (classLoader != null) {
TextView t1=this.createdView();
t1.setText("[onCreate] classLoader " + ++i + " : "+ classLoader.toString());
this.classLoaderRootLayout.addView(t1);
while (classLoader.getParent() != null) {
classLoader=classLoader.getParent();
TextView t2=this.createdView();
t2.setText("[onCreate] classLoader " + ++i + " : "+ classLoader.toString());
this.classLoaderRootLayout.addView(t2);
}
}
}
| Initialize the Activity data |
Object toType(String value,String pattern,Locale locale){
Calendar calendar=toCalendar(value,pattern,locale);
return toType(calendar);
}
| Parse a String value to the required type |
public void toggleSong(final Long songId,final String songName,final String albumName,final String artistName){
if (getSongId(songId) == null) {
addSongId(songId,songName,albumName,artistName);
}
else {
removeItem(songId);
}
}
| Toggle the current song as favorite |
@DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 12:55:07.260 -0500",hash_original_method="03611E3BB30258B8EC4FDC9F783CBCCF",hash_generated_method="75EED4D564C6A1FA0F492FBBD941CE61") public RouteHeader createRouteHeader(Address address){
if (address == null) throw new NullPointerException("null address arg");
Route route=new Route();
route.setAddress(address);
return route;
}
| Creates a new RouteHeader based on the newly supplied address value. |
public NominalItem(Attribute att,int valueIndex) throws Exception {
super(att);
if (att.isNumeric()) {
throw new Exception("NominalItem must be constructed using a nominal attribute");
}
m_attribute=att;
if (m_attribute.numValues() == 1) {
m_valueIndex=0;
}
else {
m_valueIndex=valueIndex;
}
}
| Constructs a new NominalItem. |
public static Class inferType(TupleSet tuples,String field){
if (tuples instanceof Table) {
return ((Table)tuples).getColumnType(field);
}
else {
Class type=null, type2=null;
Iterator iter=tuples.tuples();
while (iter.hasNext()) {
Tuple t=(Tuple)iter.next();
if (type == null) {
type=t.getColumnType(field);
}
else if (!type.equals(type2=t.getColumnType(field))) {
if (type2.isAssignableFrom(type)) {
type=type2;
}
else if (!type.isAssignableFrom(type2)) {
throw new IllegalArgumentException("The data field [" + field + "] does not have "+ "a consistent type across provided Tuples");
}
}
}
return type;
}
}
| Infer the data field type across all tuples in a TupleSet. |
private DoubleMinMax exactMinMax(Relation<O> relation,DistanceQuery<O> distFunc){
final FiniteProgress progress=LOG.isVerbose() ? new FiniteProgress("Exact fitting distance computations",relation.size(),LOG) : null;
DoubleMinMax minmax=new DoubleMinMax();
for (DBIDIter iditer=relation.iterDBIDs(); iditer.valid(); iditer.advance()) {
for (DBIDIter iditer2=relation.iterDBIDs(); iditer2.valid(); iditer2.advance()) {
if (DBIDUtil.equal(iditer,iditer2)) {
continue;
}
double d=distFunc.distance(iditer,iditer2);
minmax.put(d);
}
LOG.incrementProcessed(progress);
}
LOG.ensureCompleted(progress);
return minmax;
}
| Compute the exact maximum and minimum. |
public void testDoubleValueMinusZero(){
String a="-123809648392384754573567356745735.63567890295784902768787678287E-400";
BigDecimal aNumber=new BigDecimal(a);
long minusZero=-9223372036854775808L;
double result=aNumber.doubleValue();
assertTrue("incorrect value",Double.doubleToLongBits(result) == minusZero);
}
| Double value of a small negative BigDecimal |
public SeaGlassContext(JComponent component,Region region,SynthStyle style,int state){
super(component,region,style,state);
if (component == fakeComponent) {
this.component=null;
this.region=null;
this.style=null;
return;
}
if (component == null || region == null || style == null) {
throw new NullPointerException("You must supply a non-null component, region and style");
}
reset(component,region,style,state);
}
| Creates a SeaGlassContext with the specified values. This is meant for subclasses and custom UI implementors. You very rarely need to construct a SeaGlassContext, though some methods will take one. |
boolean same(ArrayList<LinkedHashMap<String,String>> tags1,ArrayList<LinkedHashMap<String,String>> tags2){
if (tags1.size() != tags2.size()) {
return false;
}
for (int i=0; i < tags1.size(); i++) {
if (!tags1.get(i).equals(tags2.get(i))) {
return false;
}
}
return true;
}
| Check if two lists of tags are the same Note: this considers order relevant |
@Override public TemplateEffect copy(){
return new TemplateEffect(labelTemplate,valueTemplate,priority,exclusive,negated);
}
| Returns a copy of the effect. |
public RegionMBeanBridge(CachePerfStats cachePerfStats){
this.regionStats=cachePerfStats;
this.regionMonitor=new MBeanStatsMonitor(ManagementStrings.REGION_MONITOR.toLocalizedString());
regionMonitor.addStatisticsToMonitor(cachePerfStats.getStats());
configureRegionMetrics();
}
| Statistic related Methods |
public void Set(final Class cl){
OptionInstance=false;
PlugInObject=cl;
ObjectName=((Class)PlugInObject).getSimpleName();
ObjectName=Convert(ObjectName);
}
| Defines the stored object as a class. |
public void include(DefaultFaceletContext ctx,UIComponent parent,URL url) throws IOException {
DefaultFacelet f=(DefaultFacelet)this.factory.getFacelet(ctx.getFacesContext(),url);
f.include(ctx,parent);
}
| Grabs a DefaultFacelet from referenced DefaultFaceletFacotry |
@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.241 -0500",hash_original_method="6B85F90491881D2C299E5BF02CCF5806",hash_generated_method="82489B93E2C39EE14F117933CF49B12C") public static String toHexString(long v){
return IntegralToString.longToHexString(v);
}
| Converts the specified long value into its hexadecimal string representation. The returned string is a concatenation of characters from '0' to '9' and 'a' to 'f'. |
private void initializeProgressView(LayoutInflater inflater,ViewGroup actionArea){
if (mCard.mCardProgress != null) {
View progressView=inflater.inflate(R.layout.card_progress,actionArea,false);
ProgressBar progressBar=(ProgressBar)progressView.findViewById(R.id.card_progress);
((TextView)progressView.findViewById(R.id.card_progress_text)).setText(mCard.mCardProgress.label);
progressBar.setMax(mCard.mCardProgress.maxValue);
progressBar.setProgress(0);
mCard.mCardProgress.progressView=progressView;
mCard.mCardProgress.setProgressType(mCard.getProgressType());
actionArea.addView(progressView);
}
}
| Build the progress view into the given ViewGroup. |
public synchronized void resetReaders(){
readers=null;
}
| Resets a to-many relationship, making the next get call to query for a fresh result. |
@Override protected void register(ContainerFactory containerFactory){
containerFactory.registerContainer("wildfly8x",ContainerType.INSTALLED,WildFly8xInstalledLocalContainer.class);
containerFactory.registerContainer("wildfly8x",ContainerType.REMOTE,WildFly8xRemoteContainer.class);
containerFactory.registerContainer("wildfly9x",ContainerType.INSTALLED,WildFly9xInstalledLocalContainer.class);
containerFactory.registerContainer("wildfly9x",ContainerType.REMOTE,WildFly9xRemoteContainer.class);
containerFactory.registerContainer("wildfly10x",ContainerType.INSTALLED,WildFly10xInstalledLocalContainer.class);
containerFactory.registerContainer("wildfly10x",ContainerType.REMOTE,WildFly10xRemoteContainer.class);
}
| Register container. |
public static byte[] decode(String encoded){
if (encoded == null) {
return null;
}
char[] base64Data=encoded.toCharArray();
int len=removeWhiteSpace(base64Data);
if (len % FOURBYTE != 0) {
return null;
}
int numberQuadruple=(len / FOURBYTE);
if (numberQuadruple == 0) {
return new byte[0];
}
byte decodedData[]=null;
byte b1=0, b2=0, b3=0, b4=0;
char d1=0, d2=0, d3=0, d4=0;
int i=0;
int encodedIndex=0;
int dataIndex=0;
decodedData=new byte[(numberQuadruple) * 3];
for (; i < numberQuadruple - 1; i++) {
if (!isData((d1=base64Data[dataIndex++])) || !isData((d2=base64Data[dataIndex++])) || !isData((d3=base64Data[dataIndex++]))|| !isData((d4=base64Data[dataIndex++]))) {
return null;
}
b1=base64Alphabet[d1];
b2=base64Alphabet[d2];
b3=base64Alphabet[d3];
b4=base64Alphabet[d4];
decodedData[encodedIndex++]=(byte)(b1 << 2 | b2 >> 4);
decodedData[encodedIndex++]=(byte)(((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
decodedData[encodedIndex++]=(byte)(b3 << 6 | b4);
}
if (!isData((d1=base64Data[dataIndex++])) || !isData((d2=base64Data[dataIndex++]))) {
return null;
}
b1=base64Alphabet[d1];
b2=base64Alphabet[d2];
d3=base64Data[dataIndex++];
d4=base64Data[dataIndex++];
if (!isData((d3)) || !isData((d4))) {
if (isPad(d3) && isPad(d4)) {
if ((b2 & 0xf) != 0) {
return null;
}
byte[] tmp=new byte[i * 3 + 1];
System.arraycopy(decodedData,0,tmp,0,i * 3);
tmp[encodedIndex]=(byte)(b1 << 2 | b2 >> 4);
return tmp;
}
else if (!isPad(d3) && isPad(d4)) {
b3=base64Alphabet[d3];
if ((b3 & 0x3) != 0) {
return null;
}
byte[] tmp=new byte[i * 3 + 2];
System.arraycopy(decodedData,0,tmp,0,i * 3);
tmp[encodedIndex++]=(byte)(b1 << 2 | b2 >> 4);
tmp[encodedIndex]=(byte)(((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
return tmp;
}
else {
return null;
}
}
else {
b3=base64Alphabet[d3];
b4=base64Alphabet[d4];
decodedData[encodedIndex++]=(byte)(b1 << 2 | b2 >> 4);
decodedData[encodedIndex++]=(byte)(((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
decodedData[encodedIndex++]=(byte)(b3 << 6 | b4);
}
return decodedData;
}
| Decodes Base64 data into octects |
@DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 12:55:34.017 -0500",hash_original_method="647E85AB615972325C277E376A221EF0",hash_generated_method="9835D90D4E0E7CCFFD07C436051E80EB") public boolean hasIsdnSubaddress(){
return hasParm(ISUB);
}
| return true if the isdn subaddress exists. |
private void tryScrollBackToTopWhileLoading(){
tryScrollBackToTop();
}
| just make easier to understand |
private Map<String,String> extractVariables(final String variablesBody){
final Map<String,String> map=new HashMap<String,String>();
final Matcher m=PATTERN_VARIABLES_BODY.matcher(variablesBody);
LOG.debug("parsing variables body");
while (m.find()) {
final String key=m.group(1);
final String value=m.group(2);
if (map.containsKey(key)) {
LOG.warn("A duplicate variable name found with name: {} and value: {}.",key,value);
}
map.put(key,value);
}
return map;
}
| Extract variables map from variables body. |
public int hashCode(){
int fh=first == null ? 0 : first.hashCode();
int sh=second == null ? 0 : second.hashCode();
return (fh << 16) | (sh & 0xFFFF);
}
| Returns this Pair's hash code, of which the 16 high bits are the 16 low bits of <tt>getFirst().hashCode()</tt> are identical to the 16 low bits and the 16 low bits of <tt>getSecond().hashCode()</tt> |
private static void CallStaticVoidMethod(JNIEnvironment env,int classJREF,int methodID) throws Exception {
if (VM.VerifyAssertions) {
VM._assert(VM.BuildForPowerPC,ERROR_MSG_WRONG_IMPLEMENTATION);
}
if (traceJNI) VM.sysWrite("JNI called: CallStaticVoidMethod \n");
RuntimeEntrypoints.checkJNICountDownToGC();
try {
JNIHelpers.invokeWithDotDotVarArg(methodID,TypeReference.Void);
}
catch ( Throwable unexpected) {
if (traceJNI) unexpected.printStackTrace(System.err);
env.recordException(unexpected);
}
}
| CallStaticVoidMethod: invoke a static method that returns void arguments passed using the vararg ... style NOTE: the vararg's are not visible in the method signature here; they are saved in the caller frame and the glue frame <p> <strong>NOTE: This implementation is NOT used for IA32. On IA32, it is overwritten with a C implementation in the bootloader when the VM starts.</strong> |
public SignatureVisitor visitInterface(){
return this;
}
| Visits the type of an interface implemented by the class. |
public Vec4 intersect(Line line){
Intersection intersection=intersect(line,this.a,this.b,this.c);
return intersection != null ? intersection.getIntersectionPoint() : null;
}
| Determine the intersection of the triangle with a specified line. |
public void lostOwnership(Clipboard clipboard,Transferable contents){
}
| Notifies this object that it is no longer the owner of the contents of the clipboard. |
static void testExample(){
Locale.setDefault(new Locale("en","UK"));
doTestExample("fr","CH",new String[]{"_fr_CH.class","_fr.properties",".class"});
doTestExample("fr","FR",new String[]{"_fr.properties",".class"});
doTestExample("de","DE",new String[]{"_en.properties",".class"});
doTestExample("en","US",new String[]{"_en.properties",".class"});
doTestExample("es","ES",new String[]{"_es_ES.class",".class"});
}
| Verifies the example from the getBundle specification. |
public PubSubManager(Connection connection,String toAddress){
con=connection;
to=toAddress;
}
| Create a pubsub manager associated to the specified connection where the pubsub requests require a specific to address for packets. |
protected void discoverOnAllPorts(){
log.info("Sending LLDP packets out of all the enabled ports");
for ( DatapathId sw : switchService.getAllSwitchDpids()) {
IOFSwitch iofSwitch=switchService.getSwitch(sw);
if (iofSwitch == null) continue;
if (!iofSwitch.isActive()) continue;
Collection<OFPort> c=iofSwitch.getEnabledPortNumbers();
if (c != null) {
for ( OFPort ofp : c) {
if (isLinkDiscoverySuppressed(sw,ofp)) {
continue;
}
log.trace("Enabled port: {}",ofp);
sendDiscoveryMessage(sw,ofp,true,false);
NodePortTuple npt=new NodePortTuple(sw,ofp);
addToMaintenanceQueue(npt);
}
}
}
}
| Send LLDPs to all switch-ports |
public static Map<String,String> parseQuerystring(String queryString){
Map<String,String> map=new HashMap<String,String>();
if ((queryString == null) || (queryString.equals(""))) {
return map;
}
String[] params=queryString.split("&");
for ( String param : params) {
try {
String[] keyValuePair=param.split("=",2);
String name=URLDecoder.decode(keyValuePair[0],"UTF-8");
if (name == "") {
continue;
}
String value=keyValuePair.length > 1 ? URLDecoder.decode(keyValuePair[1],"UTF-8") : "";
map.put(name,value);
}
catch ( UnsupportedEncodingException e) {
}
}
return map;
}
| Parse a querystring into a map of key/value pairs. |
public boolean isDiscardVisible(){
return m_ButtonDiscard.isVisible();
}
| Returns the visibility of the discard button. |
private void editNote(int noteId){
hideSoftKeyboard();
Intent intent=new Intent(MainActivity.this,NoteActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
intent.putExtra("id",String.valueOf(noteId));
startActivity(intent);
}
| Method used to enter note edition mode |
private JPanel createLeftSide(){
JPanel leftPanel=new JPanel();
listModel=new CustomListModel();
leftPanel.setLayout(new BorderLayout());
listBox=new JList<String>(listModel);
listBox.setCellRenderer(new JlistRenderer());
listBox.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
listBox.addListSelectionListener(new CustomListSelectionListener());
JScrollPane scrollPane=new JScrollPane(listBox);
scrollPane.setBorder(BorderFactory.createEmptyBorder());
leftPanel.add(scrollPane,BorderLayout.CENTER);
scrollPane.setBorder(BorderFactory.createTitledBorder("Dialogue states:"));
JPanel controlPanel=createControlPanel();
leftPanel.add(controlPanel,BorderLayout.SOUTH);
return leftPanel;
}
| Creates the panel on the left side of the window |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.