code
stringlengths 10
174k
| nl
stringlengths 3
129k
|
---|---|
public boolean hasAbPageVariationId(){
return hasExtension(GwoAbPageVariationId.class);
}
| Returns whether it has the A/B experiment page variation ID. |
private void showFeedback(String message){
if (myHost != null) {
myHost.showFeedback(message);
}
else {
System.out.println(message);
}
}
| Used to communicate feedback pop-up messages between a plugin tool and the main Whitebox user-interface. |
public NotificationChain basicSetActualThisTypeRef(ParameterizedTypeRef newActualThisTypeRef,NotificationChain msgs){
ParameterizedTypeRef oldActualThisTypeRef=actualThisTypeRef;
actualThisTypeRef=newActualThisTypeRef;
if (eNotificationRequired()) {
ENotificationImpl notification=new ENotificationImpl(this,Notification.SET,TypeRefsPackage.BOUND_THIS_TYPE_REF__ACTUAL_THIS_TYPE_REF,oldActualThisTypeRef,newActualThisTypeRef);
if (msgs == null) msgs=notification;
else msgs.add(notification);
}
return msgs;
}
| <!-- begin-user-doc --> <!-- end-user-doc --> |
@SafeVarargs public static <T>OutputMatcher<T> anyOf(OutputMatcher<T>... matchers){
return OutputMatcherFactory.create(AnyOf.anyOf(matchers));
}
| Creates a matcher that matches if the examined object matches <b>ANY</b> of the specified matchers. |
public int executeRawNoArgs(DatabaseConnection connection,String statement) throws SQLException {
logger.debug("running raw execute statement: {}",statement);
return connection.executeStatement(statement,DatabaseConnection.DEFAULT_RESULT_FLAGS);
}
| Return true if it worked else false. |
public synchronized void addObserver(Observer o){
if (o == null) throw new NullPointerException();
if (!obs.contains(o)) {
obs.addElement(o);
}
}
| Adds an observer to the set of observers for this object, provided that it is not the same as some observer already in the set. The order in which notifications will be delivered to multiple observers is not specified. See the class comment. |
public void close() throws IOException {
manager.sendClose(info);
}
| Close this connection. |
public void waitDbNodesStable(DbJmxClient geoInstance,String vdcShortId,int vdcHosts){
String prefix="Waiting for DB cluster become stable for VDC with shortId ' " + vdcShortId + "'...";
log.info(prefix);
long start=System.currentTimeMillis();
int numHosts=(vdcHosts / 2 + 2) > vdcHosts ? vdcHosts : vdcHosts / 2 + 2;
while (System.currentTimeMillis() - start < DB_STABLE_TIMEOUT) {
try {
List<String> liveNodes=geoInstance.getDcLiveNodes(vdcShortId);
log.info("{} has live nodes of {}",vdcShortId,liveNodes);
if (liveNodes.size() >= numHosts) {
int i=0;
for ( String host : liveNodes) {
if (!geoInstance.getJoiningNodes().contains(host) && !geoInstance.getLeavingNodes().contains(host) && !geoInstance.getMovingNodes().contains(host)) {
log.info("Node {} jumps to NORMAL",host);
++i;
}
}
if (i >= numHosts) {
log.info("Living nodes {} meet the requirement: {}",liveNodes.toString(),numHosts);
log.info("{} Done",prefix);
return;
}
}
else {
log.info("db {} not meet {} hosts yet",vdcShortId,numHosts);
}
TimeUnit.SECONDS.sleep(WAIT_INTERVAL_IN_SEC);
}
catch ( InterruptedException ex) {
}
catch ( Exception ex) {
log.error("Exception checking DB cluster status",ex);
}
}
log.info("{} Timed out",prefix);
throw new IllegalStateException(String.format("%s : Timed out",prefix));
}
| Wait for num of db instances joined in a vdc. |
public void testStatistic() throws Exception {
CountStatisticImpl stat=new CountStatisticImpl("myCounter","seconds","myDescription");
stat.setEnabled(true);
assertStatistic(stat,"myCounter","seconds","myDescription");
assertEquals(0,stat.getCount());
stat.increment();
assertEquals(1,stat.getCount());
stat.increment();
assertEquals(2,stat.getCount());
stat.decrement();
assertEquals(1,stat.getCount());
Thread.sleep(500);
stat.increment();
assertLastTimeNotStartTime(stat);
LOG.info("Counter is: " + stat);
stat.reset();
assertEquals(0,stat.getCount());
}
| Use case for CountStatisticImple class. |
public Where<T,ID> exists(QueryBuilder<?,?> subQueryBuilder){
subQueryBuilder.enableInnerQuery();
addClause(new Exists(new InternalQueryBuilderWrapper(subQueryBuilder)));
return this;
}
| Add a EXISTS clause with a sub-query inside of parenthesis. <p> <b>NOTE:</b> The sub-query will be prepared at the same time that the outside query is. </p> |
@Override public void eUnset(int featureID){
switch (featureID) {
case N4JSPackage.FUNCTION_EXPRESSION__ANNOTATION_LIST:
setAnnotationList((ExpressionAnnotationList)null);
return;
case N4JSPackage.FUNCTION_EXPRESSION__TYPE_VARS:
getTypeVars().clear();
return;
case N4JSPackage.FUNCTION_EXPRESSION__NAME:
setName(NAME_EDEFAULT);
return;
}
super.eUnset(featureID);
}
| <!-- begin-user-doc --> <!-- end-user-doc --> |
public static String toNTriplesString(Value value){
return toNTriplesString(value,BasicWriterSettings.XSD_STRING_TO_PLAIN_LITERAL.getDefaultValue());
}
| Creates an N-Triples string for the supplied value. |
public CHM(int initialCapacity,float loadFactor){
this(initialCapacity,loadFactor,DFLT_CONC_LVL);
}
| Creates a new, empty map with the specified initial capacity and load factor and with the default concurrencyLevel (16). |
public void insert(String s){
tree.insert(s,true);
}
| Insert the string into our collection. <p> Note that since there are no duplicates, attempts to insert the same string multiple times are silently ignored. |
public void selectInitialValue(){
OptionPaneUI ui=getUI();
if (ui != null) {
ui.selectInitialValue(this);
}
}
| Requests that the initial value be selected, which will set focus to the initial value. This method should be invoked after the window containing the option pane is made visible. |
public Maybe<Zipper<A>> maybeModifyNext(UnaryOperator<A> operator){
return Maybe.JustWhenTrue(!isEnd(),null);
}
| Modifies the element after the focus position, if possible. |
public void activate(){
node.activate();
}
| hook for JSVC |
String encodedQuery(){
if (queryNamesAndValues == null) return null;
int queryStart=url.indexOf('?') + 1;
int queryEnd=delimiterOffset(url,queryStart + 1,url.length(),"#");
return url.substring(queryStart,queryEnd);
}
| Returns the query of this URL, encoded for use in HTTP resource resolution. The returned string may be null (for URLs with no query), empty (for URLs with an empty query) or non-empty (all other URLs). |
static String changeLess32toXML(String string) throws IOException {
StringBuilder sb=new StringBuilder();
StringReader sr=new StringReader(string);
int i=0;
while ((i=sr.read()) > -1) {
if (i < 32) {
sb.append('\\');
sb.append(Integer.toHexString(i));
}
else {
sb.append((char)i);
}
}
return sb.toString();
}
| Method changeLess32toXML |
public boolean voidIt(){
log.info("voidIt - " + toString());
m_processMsg=ModelValidationEngine.get().fireDocValidate(this,ModelValidator.TIMING_BEFORE_VOID);
if (m_processMsg != null) return false;
m_processMsg=ModelValidationEngine.get().fireDocValidate(this,ModelValidator.TIMING_AFTER_VOID);
if (m_processMsg != null) return false;
return false;
}
| Void Document. |
public static final SandboxBody show(Window owner){
AddBodyDialog dialog=new AddBodyDialog(owner);
dialog.setLocationRelativeTo(owner);
dialog.setIconImage(Icons.ADD_BODY.getImage());
dialog.setVisible(true);
if (!dialog.canceled) {
SandboxBody body=dialog.body;
body.translate(dialog.pnlTransform.getTranslation());
body.rotateAboutCenter(dialog.pnlTransform.getRotation());
synchronized (AddBodyDialog.class) {
N++;
}
return body;
}
return null;
}
| Shows an add new body dialog and returns a new body if the user clicked the add button. <p> Returns null if the user clicked the cancel button or closed the dialog. |
protected POInfo initPO(Properties ctx){
POInfo poi=POInfo.getPOInfo(ctx,Table_ID,get_TrxName());
return poi;
}
| Load Meta Data |
private static void unregisterKeyForClient(DistributedMember clientId,Object key){
try {
ClientSession cs=server.getClientSession(clientId);
if (cs.isPrimary()) {
cs.unregisterInterest(Region.SEPARATOR + REGION_NAME,key,false);
}
}
catch ( Exception ex) {
Assert.fail("failed while un-registering key(" + key + ") for client "+ clientId,ex);
}
}
| unregister a key for a particular client in the server |
@Override public boolean isActive(){
return amIActive;
}
| Used by the Whitebox GUI to tell if this plugin is still running. |
public void simulate(int tics,int ticsBetweenDraw){
for (int i=0; i < tics; i++) {
g.tic();
if ((i % ticsBetweenDraw) == 0) {
g.drawWorld();
StdDraw.show(PAUSE_TIME_PER_SIMSTEP);
}
}
}
| Simulates the world for TICS tics, simulating TICSBETWEENDRAW in between world drawing events. |
public ProblemEvaluator(Problem problem,Solution solution){
super();
this.problem=problem;
this.solution=solution;
}
| Constructs a distributed job to evaluate the specified solution. |
public NounTag(String name){
super(name);
}
| Create a new NounTag. |
public static double norm(double t){
return mod(t,_2_PI);
}
| Normalizes an angle onto <code>[0, 2 pi)</code>. |
public boolean isInputMandatory(){
return (udaDefinition.getConfigurationType() == UdaConfigurationType.USER_OPTION_MANDATORY);
}
| decide if an input field is mandatory |
@Override public void postProcess() throws Exception {
m_ResultListener.postProcess(this);
if (m_debugOutput) {
if (m_ZipDest != null) {
m_ZipDest.finished();
m_ZipDest=null;
}
}
}
| Perform any postprocessing. When this method is called, it indicates that no more requests to generate results for the current experiment will be sent. |
public boolean isStylesheetParsingComplete(){
return m_parsingComplete;
}
| Test whether the _last_ endDocument() has been processed. This is needed as guidance for stylesheet optimization and compilation engines, which generally don't want to start until all included and imported stylesheets have been fully parsed. |
public boolean isDiscoveryBye(){
return discoveryBye;
}
| Ruft den Wert der discoveryBye-Eigenschaft ab. |
protected void addBuffer(IBuffer buffer){
if (VERBOSE) {
String owner=((Openable)buffer.getOwner()).toStringWithAncestors();
System.out.println("Adding buffer for " + owner);
}
synchronized (this.openBuffers) {
this.openBuffers.put(buffer.getOwner(),buffer);
}
this.openBuffers.closeBuffers();
if (VERBOSE) {
System.out.println("-> Buffer cache filling ratio = " + NumberFormat.getInstance().format(this.openBuffers.fillingRatio()) + "%");
}
}
| Adds a buffer to the table of open buffers. |
public static Coordinate centre(Envelope envelope){
return new Coordinate(avg(envelope.getMinX(),envelope.getMaxX()),avg(envelope.getMinY(),envelope.getMaxY()));
}
| Returns the centre point of the envelope. |
public static <T>Response<T> startRequestSync(IParserRequest<T> request){
return SyncRequestExecutor.INSTANCE.execute(request);
}
| Initiate a synchronization request. |
public void add(int element){
ensureCapacity(size + 1);
array[size++]=element;
}
| Appends the specified element to the end of this list. |
public TFloatObjectHashMap(int initialCapacity,float loadFactor,TFloatHashingStrategy strategy){
super(initialCapacity,loadFactor);
_hashingStrategy=strategy;
}
| Creates a new <code>TFloatObjectHashMap</code> instance with a prime value at or near the specified capacity and load factor. |
public boolean isPositive(){
return signum() == 1;
}
| Returns true if and only if this instance represents a monetary value greater than zero, otherwise false. |
public static void put(@NotNull List<String> parameters,boolean condition,@NotNull String value){
if (condition) {
parameters.add(value);
}
}
| Puts given value to parameters if condition is satisfied |
public static List<URI> filterNonVplexInitiatorsByExportGroupVarray(ExportGroup exportGroup,List<URI> newInitiators,URI storageURI,DbClient dbClient){
List<URI> filteredInitiators=new ArrayList<URI>(newInitiators);
StorageSystem storageSystem=dbClient.queryObject(StorageSystem.class,storageURI);
if (storageSystem != null && !storageSystem.getSystemType().equals(DiscoveredDataObject.Type.vplex.name())) {
filterOutInitiatorsNotAssociatedWithVArray(exportGroup.getVirtualArray(),filteredInitiators,dbClient);
}
return filteredInitiators;
}
| Filters Initiators for non-VPLEX systems by the ExportGroup varray. Initiators not in the Varray are removed from the newInitiators list. |
protected void injectIntoVolumeCharactersticContainer(Map<String,String> volumeCharacterstic,String charactersticKey,String altCharKey,CIMInstance volumeInstance){
Object value=getCIMPropertyValue(volumeInstance,charactersticKey);
if (null == value) {
value=getCIMPropertyValue(volumeInstance,altCharKey);
}
String charactersticName=SupportedVolumeCharacterstics.getVolumeCharacterstic(charactersticKey);
if (null != value && null != charactersticName) {
volumeCharacterstic.put(charactersticName,value.toString());
}
}
| Extract value from Provider for given volume info key, and then get its Name and use that to inject to Map. |
public DaemonJvmLauncher(){
}
| Creates a new launcher. |
public void saveSavingsToAssetAccountMapping(final JsonElement element,final String paramName,final Long productId,final int placeHolderTypeId){
saveProductToAccountMapping(element,paramName,productId,placeHolderTypeId,GLAccountType.ASSET,PortfolioProductType.SAVING);
}
| Set of abstractions for saving Saving Products to GL Account Mappings |
public static String enclose(String s){
if (s.startsWith("(")) {
return s;
}
return "(" + s + ")";
}
| Enclose a string with '(' and ')' if this is not yet done. |
public ReferenceMap(final ReferenceStrength keyType,final ReferenceStrength valueType,final boolean purgeValues){
super(keyType,valueType,DEFAULT_CAPACITY,DEFAULT_LOAD_FACTOR,purgeValues);
}
| Constructs a new <code>ReferenceMap</code> that will use the specified types of references. |
private void showFeedback(String message){
if (myHost != null) {
myHost.showFeedback(message);
}
else {
System.out.println(message);
}
}
| Used to communicate feedback pop-up messages between a plugin tool and the main Whitebox user-interface. |
private static int dpToPx(Context context,int dp){
float density=context.getResources().getDisplayMetrics().density;
return Math.round((float)dp * density);
}
| Convets dp to px. |
@DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 12:54:57.308 -0500",hash_original_method="C66B8514DBF734E1693DCAFADDDE494C",hash_generated_method="A676E7B94E7A1D16D3D9DF2FED8715D4") public String encodeBody(){
return this.privacy;
}
| Encode into a canonical string. |
public void push(ElementType type){
stack.add(type);
}
| Adds an element type to the stack. |
private synchronized void migrateAPI(SQLiteDatabase db){
Log.d(LOGTAG,"Migrating API");
String user=prefs.getString(r.getString(R.string.config_username_key),"");
String pass=prefs.getString(r.getString(R.string.config_password_key),"");
String name="OpenStreetMap";
Log.d(LOGTAG,"Adding default URL with user '" + user + "'");
addAPI(db,ID_DEFAULT,name,API_DEFAULT,null,null,user,pass,ID_DEFAULT,true,true);
Log.d(LOGTAG,"Adding default URL without https");
addAPI(db,ID_DEFAULT_NO_HTTPS,"OpenStreetMap no https",API_DEFAULT_NO_HTTPS,null,null,"","",ID_DEFAULT_NO_HTTPS,true,true);
Log.d(LOGTAG,"Selecting default API");
selectAPI(db,ID_DEFAULT);
Log.d(LOGTAG,"Deleting old user/pass settings");
Editor editor=prefs.edit();
editor.remove(r.getString(R.string.config_username_key));
editor.remove(r.getString(R.string.config_password_key));
editor.commit();
Log.d(LOGTAG,"Migration finished");
}
| Creates the default API entry using the old-style username/password |
final static String parseLanguage(String lang){
if (lang == null) {
return null;
}
String code=null;
String language=null;
String langs[]=lang.split(",| |;|\\.|\\(|\\)|=",-1);
int i=0;
while ((language == null) && (i < langs.length)) {
code=langs[i].split("-")[0];
code=code.split("_")[0];
language=(String)LANGUAGES_MAP.get(code.toLowerCase());
i++;
}
return language;
}
| Parse a language string and return an ISO 639 primary code, or <code>null</code> if something wrong occurs, or if no language is found. |
@Override public void addBatch() throws SQLException {
try {
debugCodeCall("addBatch");
checkClosedForWrite();
try {
ArrayList<? extends ParameterInterface> parameters=command.getParameters();
int size=parameters.size();
Value[] set=new Value[size];
for (int i=0; i < size; i++) {
ParameterInterface param=parameters.get(i);
Value value=param.getParamValue();
set[i]=value;
}
if (batchParameters == null) {
batchParameters=New.arrayList();
}
batchParameters.add(set);
}
finally {
afterWriting();
}
}
catch ( Exception e) {
throw logAndConvert(e);
}
}
| Adds the current settings to the batch. |
public void perRaceDriverEpilog(DriverThread dt){
if (verbose) System.out.println(dt.getName() + ": perRaceDriverEpilog() called");
}
| Handle end-of-race items for the DriverThread. Called by the DriverThread after it has been released from resetBarrier and before the DriverThread checks in again with startBarrier. Can execute in parallel with perRaceWorkerEpilog(). If this is not the last race, can execute in parallel with perRaceWorkerInit(). If this is the last race, can execute in parallel with oneTimeWorkerEpilog(). |
@DSComment("From safe class list") @DSSafe(DSCat.SAFE_LIST) @DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 12:57:40.015 -0500",hash_original_method="0C56D37E9DF08871E792A0F50E2C2D13",hash_generated_method="1CF19802A5E86A6D8957B67EF29CF63E") public static void fill(short[] array,short value){
for (int i=0; i < array.length; i++) {
array[i]=value;
}
}
| Fills the specified array with the specified element. |
@Override protected void doGet(HttpServletRequest request,HttpServletResponse response){
processGetRequest(request,response);
}
| Handles the HTTP <code>GET</code> method. |
private void ensureRestartPositionConsistency() throws ReplicatorException, InterruptedException {
if (!logConsistencyCheck) {
logger.info("Restart consistency checking is disabled");
return;
}
if (commitSeqno == null) {
logger.info("Restart consistency checking skipped because catalog is disabled");
return;
}
if (!"master".equals(context.getLastOnlineRoleName()) || !context.isSlave()) {
logger.info("Restart consistency checking skipped as we are not recovering a master to a slave");
return;
}
ReplDBMSHeader lastLogEvent=getLastLoggedEvent();
ReplDBMSHeader lastCatalogEvent=commitSeqno.minCommitSeqno();
if (lastCatalogEvent == null) {
logger.info("Restart consistency checking skipped as there is no restart point in catalog");
return;
}
if (lastLogEvent == null) {
logger.info("Restart consistency checking skipped as THL does not contain events");
return;
}
logger.info("Checking restart consistency when recovering master to slave: THL seqno=" + lastLogEvent.getSeqno() + " catalog seqno="+ lastCatalogEvent.getSeqno());
if (lastLogEvent.getSeqno() > lastCatalogEvent.getSeqno()) {
if (lastLogEvent.getEpochNumber() == lastCatalogEvent.getEpochNumber()) {
logger.info("Updating catalog seqno position to match THL");
THLEvent thlEvent=new THLEvent(lastLogEvent.getSeqno(),lastLogEvent.getFragno(),lastLogEvent.getLastFrag(),lastLogEvent.getSourceId(),THLEvent.REPL_DBMS_EVENT,lastLogEvent.getEpochNumber(),(Timestamp)null,lastLogEvent.getExtractedTstamp(),lastLogEvent.getEventId(),lastLogEvent.getShardId(),(ReplEvent)null);
this.updateCommitSeqno(thlEvent);
}
else {
logger.warn("Unable to update catalog position as epoch numbers do not match: seqno=" + lastLogEvent.getSeqno() + " THL epoch number="+ lastLogEvent.getEpochNumber()+ " catalog epoch number="+ lastCatalogEvent.getEpochNumber());
}
}
else if (lastLogEvent.getSeqno() < lastCatalogEvent.getSeqno()) {
logger.info("Unable to update catalog position as last THL record is lower than catalog seqno");
logger.info("This condition may occur naturally if the THL has been truncated");
}
else {
logger.info("Restart position is consistent; no need to update");
}
}
| Ensure that the log and catalog restart point are consistent. If we are going online as a slave and the last online role was master, we expect the trep_commit_seqno restart position matches the end of the THL. Since masters cannot always update the commit position before going offline, we must in that case adjust the position to avoid errors. <p/> This check is a separate function as there are numerous boundary conditions for a successful check. |
public final void testGetMidTermsOfReductionPolynomial01(){
int[] a=new int[]{981,2,1};
int[] b=new ECFieldF2m(2000,BigInteger.valueOf(0L).setBit(0).setBit(1).setBit(2).setBit(981).setBit(2000)).getMidTermsOfReductionPolynomial();
assertTrue(Arrays.equals(a,b));
}
| Test #1 for <code>getMidTermsOfReductionPolynomial()</code> method.<br> Assertion: returns mid terms of reduction polynomial |
final void putByte(int offset,byte value){
unsafe.putByte(offset + address,value);
}
| Writes a byte at the specified offset from this native object's base address. |
public final boolean isOrEnclosedByPrivateType(){
if (isLocalType()) return true;
ReferenceBinding type=this;
while (type != null) {
if ((type.modifiers & ClassFileConstants.AccPrivate) != 0) return true;
type=type.enclosingType();
}
return false;
}
| Answer true if the receiver or any of its enclosing types have private visibility |
private static int decode4to3(byte[] source,int srcOffset,byte[] destination,int destOffset,byte[] decodabet){
if (source[srcOffset + 2] == EQUALS_SIGN) {
int outBuff=((decodabet[source[srcOffset]] << 24) >>> 6) | ((decodabet[source[srcOffset + 1]] << 24) >>> 12);
destination[destOffset]=(byte)(outBuff >>> 16);
return 1;
}
else if (source[srcOffset + 3] == EQUALS_SIGN) {
int outBuff=((decodabet[source[srcOffset]] << 24) >>> 6) | ((decodabet[source[srcOffset + 1]] << 24) >>> 12) | ((decodabet[source[srcOffset + 2]] << 24) >>> 18);
destination[destOffset]=(byte)(outBuff >>> 16);
destination[destOffset + 1]=(byte)(outBuff >>> 8);
return 2;
}
else {
int outBuff=((decodabet[source[srcOffset]] << 24) >>> 6) | ((decodabet[source[srcOffset + 1]] << 24) >>> 12) | ((decodabet[source[srcOffset + 2]] << 24) >>> 18)| ((decodabet[source[srcOffset + 3]] << 24) >>> 24);
destination[destOffset]=(byte)(outBuff >> 16);
destination[destOffset + 1]=(byte)(outBuff >> 8);
destination[destOffset + 2]=(byte)(outBuff);
return 3;
}
}
| Decodes four bytes from array <var>source</var> and writes the resulting bytes (up to three of them) to <var>destination</var>. The source and destination arrays can be manipulated anywhere along their length by specifying <var>srcOffset</var> and <var>destOffset</var>. This method does not check to make sure your arrays are large enough to accommodate <var>srcOffset</var> + 4 for the <var>source</var> array or <var>destOffset</var> + 3 for the <var>destination</var> array. This method returns the actual number of bytes that were converted from the Base64 encoding. |
protected POInfo initPO(Properties ctx){
POInfo poi=POInfo.getPOInfo(ctx,Table_ID,get_TrxName());
return poi;
}
| Load Meta Data |
public Configurator errorBackgroundResource(int backgroundRes){
if (backgroundRes > 0) {
viewErrorBackgroundResource=backgroundRes;
}
return this;
}
| Customize the error view background. |
public void writeToParcel(Parcel dest,int flags){
linkProperties.writeToParcel(dest,flags);
dest.writeInt(leaseDuration);
if (serverAddress != null) {
dest.writeByte((byte)1);
dest.writeByteArray(serverAddress.getAddress());
}
else {
dest.writeByte((byte)0);
}
dest.writeString(vendorInfo);
}
| Implement the Parcelable interface |
public static final int BuildInteger(byte bytevec[],boolean MSBFirst){
if (MSBFirst) return BuildIntegerBE(bytevec,0);
else return BuildIntegerLE(bytevec,0);
}
| Build int out of bytes. |
public ViewRefRender(ViewRender<T> view){
Objects.requireNonNull(view);
_view=view;
_type=typeOf(view);
_priority=priorityOf(view);
}
| Creates the view and analyzes the type |
public static <T1,T2,T3,T4,T5,T6,T7,R>BiFunction<T6,T7,R> partial7(final T1 t1,final T2 t2,final T3 t3,final T4 t4,final T5 t5,final HeptFunction<T1,T2,T3,T4,T5,T6,T7,R> heptFunc){
return null;
}
| Returns a BiFunction with 5 arguments applied to the supplied HeptFunction |
public static boolean contains(Polygon rectangle,Geometry b){
RectangleContains rc=new RectangleContains(rectangle);
return rc.contains(b);
}
| Tests whether a rectangle contains a given geometry. |
private String encode(Variable variable) throws IOException {
StringBuilder sb=new StringBuilder();
if (variable instanceof RealVariable) {
RealVariable rv=(RealVariable)variable;
sb.append(rv.getValue());
}
else if (variable instanceof BinaryVariable) {
BinaryVariable bv=(BinaryVariable)variable;
for (int i=0; i < bv.getNumberOfBits(); i++) {
sb.append(bv.get(i) ? "1" : "0");
}
}
else if (variable instanceof Permutation) {
Permutation p=(Permutation)variable;
for (int i=0; i < p.size(); i++) {
if (i > 0) {
sb.append(',');
}
sb.append(p.get(i));
}
}
else {
throw new IOException("unable to serialize variable");
}
return sb.toString();
}
| Serializes a variable to a string form. |
private void initModel(boolean allConfigurables,RemoteRepository source){
this.listOfConfigurables=Collections.synchronizedList(new LinkedList<Configurable>());
this.originalParameters=new HashMap<>();
this.originalNames=new HashMap<>();
this.originalPermittedUserGroups=new HashMap<>();
this.source=source;
checkForAdminRights();
if (source != null) {
originalCredentials=Wallet.getInstance().getEntry(source.getAlias(),source.getBaseUrl().toString());
if (originalCredentials == null) {
originalCredentials=new UserCredential(source.getBaseUrl().toString(),source.getUsername(),null);
}
}
for ( Configurable configurable : ConfigurationManager.getInstance().getAllConfigurables()) {
boolean sameLocalSource=source == null && configurable.getSource() == null;
boolean sameRemoteSource=source != null && configurable.getSource() != null && configurable.getSource().getName().equals(source.getName());
if (allConfigurables || sameLocalSource || sameRemoteSource) {
this.listOfConfigurables.add(configurable);
Map<String,String> parameterMap=new HashMap<>();
for ( String key : configurable.getParameters().keySet()) {
if (configurable instanceof AbstractConfigurable) {
parameterMap.put(key,((AbstractConfigurable)configurable).getParameterAsXMLString(key));
}
else {
parameterMap.put(key,configurable.getParameter(key));
}
}
originalParameters.put(configurable,new HashMap<>(parameterMap));
originalNames.put(configurable,configurable.getName());
originalPermittedUserGroups.put(configurable,ConfigurationManager.getInstance().getPermittedGroupsForConfigurable(configurable));
}
}
ConfigurationManager.getInstance().addObserver(this,false);
}
| Creates the model either for all available configurables or for all configurables of the given source |
@Override public void drawDomainGridline(Graphics2D g2,CategoryPlot plot,Rectangle2D dataArea,double value){
Line2D line=null;
PlotOrientation orientation=plot.getOrientation();
if (orientation == PlotOrientation.HORIZONTAL) {
line=new Line2D.Double(dataArea.getMinX(),value,dataArea.getMaxX(),value);
}
else if (orientation == PlotOrientation.VERTICAL) {
line=new Line2D.Double(value,dataArea.getMinY(),value,dataArea.getMaxY());
}
Paint paint=plot.getDomainGridlinePaint();
if (paint == null) {
paint=CategoryPlot.DEFAULT_GRIDLINE_PAINT;
}
g2.setPaint(paint);
Stroke stroke=plot.getDomainGridlineStroke();
if (stroke == null) {
stroke=CategoryPlot.DEFAULT_GRIDLINE_STROKE;
}
g2.setStroke(stroke);
g2.draw(line);
}
| Draws a grid line against the domain axis. <P> Note that this default implementation assumes that the horizontal axis is the domain axis. If this is not the case, you will need to override this method. |
public SmbFile[] listFiles(SmbFileFilter filter) throws SmbException {
return listFiles("*",ATTR_DIRECTORY | ATTR_HIDDEN | ATTR_SYSTEM,null,filter);
}
| List the contents of this SMB resource. The list returned will be identical to the list returned by the parameterless <code>listFiles()</code> method minus filenames filtered by the specified filter. |
private Connection tableSetup(String insertEntryQuery) throws Throwable {
Connection connection=null;
Statement statement=null;
try {
connection=getNewConnection(true);
statement=connection.createStatement();
statement.executeQuery("DROP TABLE IF EXISTS replica_host_status");
statement.executeQuery("CREATE TABLE replica_host_status (SERVER_ID VARCHAR(255), SESSION_ID VARCHAR(255), " + "LAST_UPDATE_TIMESTAMP TIMESTAMP DEFAULT NOW())");
ResultSet resultSet=statement.executeQuery("SELECT SERVER_ID, SESSION_ID, LAST_UPDATE_TIMESTAMP " + "FROM information_schema.replica_host_status " + "WHERE LAST_UPDATE_TIMESTAMP = ("+ "SELECT MAX(LAST_UPDATE_TIMESTAMP) "+ "FROM information_schema.replica_host_status)");
while (resultSet.next()) {
String values="";
for (int i=1; i < 4; i++) {
values+=(i == 1) ? "'localhost'" : ",'" + resultSet.getString(i) + "'";
}
statement.executeQuery("INSERT INTO replica_host_status (SERVER_ID, SESSION_ID, LAST_UPDATE_TIMESTAMP) " + "VALUES (" + values + ")");
}
if (insertEntryQuery != null) {
statement.executeQuery(insertEntryQuery);
}
try {
setDbName(connection,"testj");
}
catch ( Throwable t) {
fail("Unable to set database for testing");
}
int serverId=getServerId(connection);
stopProxy(serverId,1);
statement=connection.createStatement();
statement.executeQuery("select 1");
}
catch ( SQLException se) {
fail("Unable to execute queries to set up table: " + se);
}
finally {
if (statement != null) {
statement.close();
}
}
return connection;
}
| Creates a mock replica_host_status table to imitate the database used to retrieve information about the endpoints. |
public static NamedList<NamedList<?>> unwrapStats(NamedList<NamedList<NamedList<?>>> stats){
if (null == stats) return null;
return stats.get("stats_fields");
}
| Helper to pull the "stats_fields" out of the extra "stats" wrapper |
public boolean logout() throws LoginException {
reset();
return true;
}
| Logs the user out |
public void addBugCodeToFilter(BugCode code){
elementChecked(code,true);
}
| Accessor method for tests to simulate the user selecting a bug code. |
public static boolean isGrounded(InferenceEngine inf,TempTripleStore focusStore,AbstractTripleStore db,SPO head,boolean testHead,boolean testFocusStore){
final VisitedSPOSet visited=new VisitedSPOSet(focusStore.getIndexManager());
try {
boolean ret=isGrounded(inf,focusStore,db,head,testHead,testFocusStore,visited);
if (log.isInfoEnabled()) log.info("head=" + head + " is "+ (ret ? "" : "NOT ")+ "grounded : testHead="+ testHead+ ", testFocusStore="+ testFocusStore+ ", #visited="+ visited.size());
return ret;
}
finally {
visited.close();
}
}
| Return true iff a grounded justification chain exists for the statement. |
@DSComment("From safe class list") @DSSafe(DSCat.SAFE_LIST) @DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 12:56:09.817 -0500",hash_original_method="65449F4F2C00BF62B7AB916EB2126B60",hash_generated_method="96254BD74FAC45D2698DDBC33FF69A6A") public void applyLocalizedPattern(String pattern){
dform.applyLocalizedPattern(pattern);
}
| Changes the pattern of this decimal format to the specified pattern which uses localized pattern characters. |
public boolean isLocalAndExists(){
return loc.isLocalAndExists();
}
| Returns whether this is a local file that already exists. |
private void fillPolyPolygon(Graphics2D g2d,List pols){
if (pols.size() == 1) g2d.fill((Polygon2D)(pols.get(0)));
else {
GeneralPath path=new GeneralPath(GeneralPath.WIND_EVEN_ODD);
for (int i=0; i < pols.size(); i++) {
Polygon2D pol=(Polygon2D)(pols.get(i));
path.append(pol,false);
}
g2d.fill(path);
}
}
| Need to do this for POLYPOLYGON, because only GeneralPaths can handle complex WMF shapes. |
public ArrayNode arrayNode(){
return new ArrayNode(this);
}
| Factory method for constructing an empty JSON Array node |
private static void convertActivityToTranslucentAfterL(Activity activity){
try {
Method getActivityOptions=Activity.class.getDeclaredMethod("getActivityOptions");
getActivityOptions.setAccessible(true);
Object options=getActivityOptions.invoke(activity);
Class<?>[] classes=Activity.class.getDeclaredClasses();
Class<?> translucentConversionListenerClazz=null;
for ( Class clazz : classes) {
if (clazz.getSimpleName().contains("TranslucentConversionListener")) {
translucentConversionListenerClazz=clazz;
}
}
Method convertToTranslucent=Activity.class.getDeclaredMethod("convertToTranslucent",translucentConversionListenerClazz,ActivityOptions.class);
convertToTranslucent.setAccessible(true);
convertToTranslucent.invoke(activity,null,options);
}
catch ( Throwable t) {
}
}
| Calling the convertToTranslucent method on platforms after Android 5.0 |
@Override protected EClass eStaticClass(){
return TypeRefsPackage.Literals.FUNCTION_TYPE_REF;
}
| <!-- begin-user-doc --> <!-- end-user-doc --> |
private static StepRefType stepRef(int stepCount){
StepRefType stepRef=new StepRefType();
stepRef.setURI("#" + STEP + stepCount);
return stepRef;
}
| Creates reference to another hash step. |
private static Object _toAxisType(TypeMapping tm,TimeZone tz,TypeEntry typeEntry,QName type,Class targetClass,Object value,Set<Object> done) throws PageException {
if (value instanceof ObjectWrap) {
value=((ObjectWrap)value).getEmbededObject();
}
if (done.contains(value)) {
return null;
}
done.add(value);
try {
if (type != null) {
if (type.getLocalPart().startsWith("ArrayOf")) {
return toArray(tm,typeEntry,type,value,done);
}
for (int i=0; i < Constants.URIS_SCHEMA_XSD.length; i++) {
if (Constants.URIS_SCHEMA_XSD[i].equals(type.getNamespaceURI())) {
return toAxisTypeXSD(tm,tz,type.getLocalPart(),value,done);
}
}
if (StringUtil.startsWithIgnoreCase(type.getLocalPart(),"xsd_")) {
return toAxisTypeXSD(tm,tz,type.getLocalPart().substring(4),value,done);
}
if (type.getNamespaceURI().indexOf("soap") != -1) {
return toAxisTypeSoap(tm,type.getLocalPart(),value,done);
}
if (StringUtil.startsWithIgnoreCase(type.getLocalPart(),"soap_")) {
return toAxisTypeSoap(tm,type.getLocalPart().substring(5),value,done);
}
}
return _toDefinedType(tm,typeEntry,type,targetClass,value,done);
}
finally {
done.remove(value);
}
}
| cast a value to a Axis Compatible Type |
public X509Name(Vector oids,Vector values){
this(oids,values,new X509DefaultEntryConverter());
}
| Takes two vectors one of the oids and the other of the values. |
public synchronized byte[] toByteArray(){
int remaining=count;
if (remaining == 0) {
return EMPTY_BYTE_ARRAY;
}
byte newbuf[]=new byte[remaining];
int pos=0;
for ( byte[] buf : buffers) {
int c=Math.min(buf.length,remaining);
System.arraycopy(buf,0,newbuf,pos,c);
pos+=c;
remaining-=c;
if (remaining == 0) {
break;
}
}
return newbuf;
}
| Gets the curent contents of this byte stream as a byte array. The result is independent of this stream. |
protected String validateCoordinateSystem(AVList params){
Object o=params.getValue(AVKey.COORDINATE_SYSTEM);
if (!this.hasKey(AVKey.COORDINATE_SYSTEM)) {
Logging.logger().warning(Logging.getMessage("generic.UnspecifiedCoordinateSystem",this.getStringValue(AVKey.DISPLAY_NAME)));
return null;
}
else if (AVKey.COORDINATE_SYSTEM_GEOGRAPHIC.equals(o)) {
return null;
}
else if (AVKey.COORDINATE_SYSTEM_PROJECTED.equals(o)) {
return this.validateProjection(params);
}
else {
return Logging.getMessage("generic.UnsupportedCoordinateSystem",o);
}
}
| Returns a string indicating an error with the Shapefile's coordinate system parameters, or null to indicate that the coordinate parameters are valid. |
private void fieldInsn(final int opcode,final Type ownerType,final String name,final Type fieldType){
mv.visitFieldInsn(opcode,ownerType.getInternalName(),name,fieldType.getDescriptor());
}
| Generates a get field or set field instruction. |
public GeoDistanceBuilder addUnboundedFrom(String key,double from){
ranges.add(new Range(key,from,null));
return this;
}
| Add a new range with no upper bound. |
public void update(byte[] buffer){
update(buffer,0,buffer.length);
}
| Updates the current checksum with the specified array of bytes. Equivalent to calling <code>update(buffer, 0, buffer.length)</code>. |
private String toUrl(){
final HttpUrl.Builder builder=httpUrl.newBuilder();
for ( final NameValue param : queryParams) {
builder.addQueryParameter(param.getName(),param.getValue());
}
return builder.build().url().toString();
}
| Return the request url including query parameters. |
public void closeConnection(){
try {
producer.close();
session.close();
connection.close();
}
catch ( JMSException ex) {
logger.debug(ex.getLocalizedMessage());
}
}
| Close connection resources. |
protected void verifyCGVolumeRequestCount(int count){
if (count > 1) {
throw APIException.badRequests.invalidFullCopyCountForVolumesInConsistencyGroup();
}
}
| Verify the requested full copy count for volume in CG is valid. For array where group clone is not supported, override this method in platform specific impl. |
public boolean check(final char c){
current=current.get(c);
if (current == null) {
reset();
}
return current.isKeyword();
}
| Checks whether the character is related to the currently used node. If the comparison fails the keyword tree will be reseted to its root node, otherwise the related node will replace the current node. |
public boolean isReadWrite(){
return super.isEnabled();
}
| Get ReadWrite |
protected UndefinedTypeImpl(){
super();
}
| <!-- begin-user-doc --> <!-- end-user-doc --> |
public static boolean isFilesystemCaseSensitive(){
return !areFilenamesEqual("a","A");
}
| Returns whether the platform treates file paths in a case-sensitive manner. (e.g. Unix allows sibling files to have names that differ only by case, but Windows does not) |
private void updateProgress(int progress){
if (myHost != null && progress != previousProgress) {
myHost.updateProgress(progress);
}
previousProgress=progress;
}
| Used to communicate a progress update between a plugin tool and the main Whitebox user interface. |
@Override @Transient public boolean isFullTextSearchable(){
return true;
}
| Override the gisFeature value.<br> Default to true;<br> If this field is set to false, then the object won't be synchronized with the fullText search engine |
@Override public synchronized void put(String key,Entry entry){
pruneIfNeeded(entry.data.length);
File file=getFileForKey(key);
try {
FileOutputStream fos=new FileOutputStream(file);
CacheHeader e=new CacheHeader(key,entry);
boolean success=e.writeHeader(fos);
if (!success) {
fos.close();
VolleyLog.d("Failed to write header for %s",file.getAbsolutePath());
throw new IOException();
}
fos.write(entry.data);
fos.close();
putEntry(key,e);
return;
}
catch ( IOException e) {
}
boolean deleted=file.delete();
if (!deleted) {
VolleyLog.d("Could not clean up file %s",file.getAbsolutePath());
}
}
| Puts the entry with the specified key into the cache. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.