code
stringlengths 10
174k
| nl
stringlengths 3
129k
|
---|---|
int measureNullChild(int childIndex){
return 0;
}
| <p>Returns the size (width or height) that should be occupied by a null child.</p> |
public synchronized boolean authenticateWithPublicKey(String user,char[] pemPrivateKey,String password) throws IOException {
if (tm == null) throw new IllegalStateException("Connection is not established!");
if (authenticated) throw new IllegalStateException("Connection is already authenticated!");
if (am == null) am=new AuthenticationManager(tm);
if (cm == null) cm=new ChannelManager(tm);
if (user == null) throw new IllegalArgumentException("user argument is null");
if (pemPrivateKey == null) throw new IllegalArgumentException("pemPrivateKey argument is null");
authenticated=am.authenticatePublicKey(user,pemPrivateKey,password,getOrCreateSecureRND());
return authenticated;
}
| After a successful connect, one has to authenticate oneself. The authentication method "publickey" works by signing a challenge sent by the server. The signature is either DSA or RSA based - it just depends on the type of private key you specify, either a DSA or RSA private key in PEM format. And yes, this is may seem to be a little confusing, the method is called "publickey" in the SSH-2 protocol specification, however since we need to generate a signature, you actually have to supply a private key =). <p> The private key contained in the PEM file may also be encrypted ("Proc-Type: 4,ENCRYPTED"). The library supports DES-CBC and DES-EDE3-CBC encryption, as well as the more exotic PEM encrpytions AES-128-CBC, AES-192-CBC and AES-256-CBC. <p> If the authentication phase is complete, <code>true</code> will be returned. If the server does not accept the request (or if further authentication steps are needed), <code>false</code> is returned and one can retry either by using this or any other authentication method (use the <code>getRemainingAuthMethods</code> method to get a list of the remaining possible methods). <p> NOTE PUTTY USERS: Event though your key file may start with "-----BEGIN..." it is not in the expected format. You have to convert it to the OpenSSH key format by using the "puttygen" tool (can be downloaded from the Putty website). Simply load your key and then use the "Conversions/Export OpenSSH key" functionality to get a proper PEM file. |
public OptionScanNode buildTreeFromWindowList(List<AccessibilityWindowInfo> windowList,AccessibilityService service){
OptionScanNode tree;
List<GlobalActionNode> globalActions=GlobalActionNode.getGlobalActionList(service);
if (mOptionScanningEnabled) {
tree=mOptionScanTreeBuilder.buildContextMenuTree(globalActions);
}
else {
tree=LinearScanTreeBuilder.buildContextMenuTree(globalActions);
}
if (windowList != null) {
List<SwitchAccessWindowInfo> wList=SwitchAccessWindowInfo.convertZOrderWindowList(windowList);
sortWindowListForTraversalOrder(wList);
removeSystemButtonsWindowFromWindowList(wList);
if (mOptionScanningEnabled) {
return mOptionScanTreeBuilder.buildTreeFromWindowList(wList,tree);
}
for ( SwitchAccessWindowInfo window : wList) {
SwitchAccessNodeCompat windowRoot=window.getRoot();
if (windowRoot != null) {
if (window.getType() == AccessibilityWindowInfo.TYPE_INPUT_METHOD) {
tree=mBuilderForIMEs.buildTreeFromNodeTree(windowRoot,tree);
}
else {
tree=mBuilderForViews.buildTreeFromNodeTree(windowRoot,tree);
}
windowRoot.recycle();
}
}
}
return tree;
}
| Build a tree of nodes from a window list, including global actions |
protected int _dataOrQName(int identity){
if (identity < m_size) return m_dataOrQName.elementAt(identity);
while (true) {
boolean isMore=nextNode();
if (!isMore) return NULL;
else if (identity < m_size) return m_dataOrQName.elementAt(identity);
}
}
| Get the data or qualified name for the given node identity. |
static RouteBuilder put(String path){
return builder().put(path);
}
| Configures a route corresponding to HTTP PUT method |
public static void sort(short[] a,int fromIndex,int toIndex){
rangeCheck(a.length,fromIndex,toIndex);
sort1(a,fromIndex,toIndex - fromIndex);
}
| Sorts the specified range of the specified array of shorts into ascending numerical order. The range to be sorted extends from index <tt>fromIndex</tt>, inclusive, to index <tt>toIndex</tt>, exclusive. (If <tt>fromIndex==toIndex</tt>, the range to be sorted is empty.)<p> The sorting algorithm is a tuned quicksort, adapted from Jon L. Bentley and M. Douglas McIlroy's "Engineering a Sort Function", Software-Practice and Experience, Vol. 23(11) P. 1249-1265 (November 1993). This algorithm offers n*log(n) performance on many data sets that cause other quicksorts to degrade to quadratic performance. |
public void pushDat11(long[] l){
tmp.push(l);
}
| Pushes a dat_11 onto the stack |
private void onFailureDetectorEvent(FailureDetectorEvent fdEvent){
MembershipRecord r0=membershipTable.get(fdEvent.member().id());
if (r0 == null) {
return;
}
if (r0.status() == fdEvent.status()) {
return;
}
LOGGER.debug("Received status change on failure detector event: {}",fdEvent);
if (fdEvent.status() == MemberStatus.ALIVE) {
Message syncMsg=prepareSyncDataMsg(SYNC,null);
transport.send(fdEvent.member().address(),syncMsg);
}
else {
MembershipRecord r1=new MembershipRecord(r0.member(),fdEvent.status(),r0.incarnation());
updateMembership(r1,true);
}
}
| Merges FD updates and processes them. |
public E hole(BaseLineStringBuilder<?> hole){
holes.add(hole);
return thisRef();
}
| Add a new hole to the polygon |
private void centerTabs(int tabCount,int totalLength,int tabAreaLength){
Insets tabAreaInsets=getTabAreaInsets(tabPlacement);
Point corner=new Point(tabAreaRect.x + tabAreaInsets.left,tabAreaRect.y + tabAreaInsets.top);
int startPosition=orientation.getPosition(corner);
int offset=orientation.getOrthogonalOffset(corner);
int thickness=(orientation == ControlOrientation.HORIZONTAL) ? maxTabHeight : maxTabWidth;
int delta=-(tabAreaLength - totalLength) / 2 - startPosition;
for (int i=leadingTabIndex; i <= trailingTabIndex; i++) {
int position=orientation.getPosition(rects[i]) - delta;
int length=orientation.getLength(rects[i]);
rects[i].setBounds(orientation.createBounds(position,offset,length,thickness));
}
}
| Center the tabs in the tab area. |
public Filter(String name,FilterType type,FilterPred pred){
this(name,type,pred,true);
}
| Constructs a Filter with the given name, type, and predicate. |
public Iterable<FieldAccessor> ownedOrMixedIn(){
if (getter != null) {
if (setter != null) {
return Arrays.asList(getter,setter);
}
else {
return singletonList(getter);
}
}
else if (setter != null) {
return singletonList(setter);
}
return emptyList();
}
| Returns the getter and setter as iterable, inherited accessors are ignored. |
public static Double checkLatitude(String name,Double latitude){
if (latitude == null) {
throw new IndexException("{} required",name);
}
else if (latitude < MIN_LATITUDE || latitude > MAX_LATITUDE) {
throw new IndexException("{} must be in range [{}, {}], but found {}",name,MIN_LATITUDE,MAX_LATITUDE,latitude);
}
return latitude;
}
| Checks if the specified latitude is correct. |
public MessageCommand(){
handler=new MessageHandler();
}
| Testing only. |
public BerDecoder(byte b[]){
bytes=b;
reset();
}
| Constructs a new decoder and attaches it to the specified byte string. |
public VisibilityFilter(Visualization vis,String group,Predicate p){
super(vis,group);
setPredicate(p);
}
| Create a new VisibilityFilter. |
private static Solution search(INode initial,INode goal){
if (initial.equals(goal)) {
return new Solution(initial,goal);
}
open=StateStorageFactory.create(StateStorageFactory.STACK);
open.insert(initial.copy());
closed=StateStorageFactory.create(StateStorageFactory.HASH);
while (!open.isEmpty()) {
INode n=open.remove();
closed.insert(n);
DepthTransition trans=(DepthTransition)n.storedData();
DoubleLinkedList<IMove> moves=n.validMoves();
for (Iterator<IMove> it=moves.iterator(); it.hasNext(); ) {
IMove move=it.next();
INode successor=n.copy();
move.execute(successor);
if (closed.contains(successor) != null) {
if (ge.eval(successor) < closedMax) {
closedMax=ge.eval(successor);
System.out.println("closed and not inspecting (" + closedMax + "):\n"+ successor);
}
continue;
}
int depth=1;
if (trans != null) {
depth=trans.depth + 1;
}
successor.storedData(new DepthTransition(move,n,depth));
if (successor.equals(goal)) {
return new Solution(initial,successor);
}
if (depth < maxDepth) {
open.insert(successor);
}
else {
withinOne(successor,goal);
}
}
}
return new Solution(initial,goal,false);
}
| Initiate the search for the target state. Store with each INode object a Transition (Move m, INode prev) so we can retrace steps to the original solution. |
public TPrimitiveHash(int initialCapacity,float loadFactor){
super(initialCapacity,loadFactor);
}
| Creates a new <code>TPrimitiveHash</code> instance with a prime capacity at or near the minimum needed to hold <tt>initialCapacity<tt> elements with load factor <tt>loadFactor</tt> without triggering a rehash. |
public static int murmurhash3_x86_32(CharSequence data,int offset,int len,int seed){
final int c1=0xcc9e2d51;
final int c2=0x1b873593;
int h1=seed;
int pos=offset;
int end=offset + len;
int k1=0;
int k2=0;
int shift=0;
int bits=0;
int nBytes=0;
while (pos < end) {
int code=data.charAt(pos++);
if (code < 0x80) {
k2=code;
bits=8;
}
else if (code < 0x800) {
k2=(0xC0 | (code >> 6)) | ((0x80 | (code & 0x3F)) << 8);
bits=16;
}
else if (code < 0xD800 || code > 0xDFFF || pos >= end) {
k2=(0xE0 | (code >> 12)) | ((0x80 | ((code >> 6) & 0x3F)) << 8) | ((0x80 | (code & 0x3F)) << 16);
bits=24;
}
else {
int utf32=(int)data.charAt(pos++);
utf32=((code - 0xD7C0) << 10) + (utf32 & 0x3FF);
k2=(0xff & (0xF0 | (utf32 >> 18))) | ((0x80 | ((utf32 >> 12) & 0x3F))) << 8 | ((0x80 | ((utf32 >> 6) & 0x3F))) << 16 | (0x80 | (utf32 & 0x3F)) << 24;
bits=32;
}
k1|=k2 << shift;
shift+=bits;
if (shift >= 32) {
k1*=c1;
k1=(k1 << 15) | (k1 >>> 17);
k1*=c2;
h1^=k1;
h1=(h1 << 13) | (h1 >>> 19);
h1=h1 * 5 + 0xe6546b64;
shift-=32;
if (shift != 0) {
k1=k2 >>> (bits - shift);
}
else {
k1=0;
}
nBytes+=4;
}
}
if (shift > 0) {
nBytes+=shift >> 3;
k1*=c1;
k1=(k1 << 15) | (k1 >>> 17);
k1*=c2;
h1^=k1;
}
h1^=nBytes;
h1^=h1 >>> 16;
h1*=0x85ebca6b;
h1^=h1 >>> 13;
h1*=0xc2b2ae35;
h1^=h1 >>> 16;
return h1;
}
| Returns the MurmurHash3_x86_32 hash of the UTF-8 bytes of the String without actually encoding the string to a temporary buffer. This is more than 2x faster than hashing the result of String.getBytes(). |
protected void runOperation(MultiOperation op,IJavaElement[] elements,IJavaElement[] siblings,String[] renamings,IProgressMonitor monitor) throws JavaModelException {
op.setRenamings(renamings);
if (siblings != null) {
for (int i=0; i < elements.length; i++) {
op.setInsertBefore(elements[i],siblings[i]);
}
}
op.runOperation(monitor);
}
| Configures and runs the <code>MultiOperation</code>. |
private void waiting(){
try {
new ConsoleReader().resetPromptLine(textWait,"",1);
}
catch ( IOException e) {
throw new IllegalStateException("Unable to write",e);
}
List<String> progress=Arrays.asList("|","/","-","\\");
int index=0;
while (wait) {
try {
new ConsoleReader().resetPromptLine(textWait,progress.get(index),1);
}
catch ( IOException e) {
throw new IllegalStateException("Unable to write",e);
}
try {
Thread.sleep(2000L);
}
catch ( InterruptedException e) {
throw new IllegalStateException("Unable to wait",e);
}
index++;
if (index >= progress.size()) {
index=0;
}
}
try {
new ConsoleReader().resetPromptLine(textAfter,"",0);
}
catch ( IOException e) {
throw new IllegalStateException("Unable to write",e);
}
System.out.println();
runnerStopped.countDown();
}
| Display a spinning wait action. |
public ListenableFuture<String> pull(final Expression expr){
return pullRaw(expr.toHaskell());
}
| Returns the result of evaluating a Haskell expression. |
@Override public synchronized void reset() throws IOException {
if (buf == null) {
throw new IOException("Stream is closed");
}
if (-1 == markpos) {
throw new IOException("Mark has been invalidated.");
}
pos=markpos;
}
| Resets this stream to the last marked location. |
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 final boolean isClosed(){
return closed.get();
}
| Checks whether this Iterator has been closed. |
public static int showConfirmDialog(Component parentComponent,Object message,String title,int optionType) throws HeadlessException {
return showConfirmDialog(parentComponent,message,title,optionType,QUESTION_MESSAGE);
}
| Brings up a dialog where the number of choices is determined by the <code>optionType</code> parameter. |
void toFarSideData(DataOutput out,boolean largeModCount,boolean sendVersionTag,boolean sendShadowKey) throws IOException {
Operation operation=getFarSideOperation();
out.writeByte(operation.ordinal);
if (largeModCount) {
out.writeInt(this.modSerialNum);
}
else {
out.writeByte(this.modSerialNum);
}
DataSerializer.writeObject(getCallbackArgument(),out);
DataSerializer.writeObject(getFilterRoutingInfo(),out);
if (sendVersionTag) {
DataSerializer.writeObject(getVersionTag(),out);
assert getVersionTag() != null || !txRegionState.getRegion().concurrencyChecksEnabled || txRegionState.getRegion().dataPolicy != DataPolicy.REPLICATE : "tag:" + getVersionTag() + " r:"+ txRegionState.getRegion()+ " op:"+ opToString()+ " key:";
}
if (sendShadowKey) {
out.writeLong(this.tailKey);
}
out.writeInt(getFarSideEventOffset());
if (!operation.isDestroy()) {
out.writeBoolean(didDistributedDestroy());
if (!operation.isInvalidate()) {
boolean sendObject=Token.isInvalidOrRemoved(getPendingValue());
sendObject=sendObject || getPendingValue() instanceof byte[];
out.writeBoolean(sendObject);
if (sendObject) {
DataSerializer.writeObject(getPendingValue(),out);
}
else {
DataSerializer.writeObjectAsByteArray(getPendingValue(),out);
}
}
}
}
| Serializes this entry state to a data output stream for a far side consumer. Make sure this method is backwards compatible if changes are made. |
public static boolean migrationSupportedForVolume(Volume volume,URI varrayURI,DbClient dbClient){
boolean supported=true;
if (volume.isIngestedVolumeWithoutBackend(dbClient)) {
VirtualPool vpool=dbClient.queryObject(VirtualPool.class,volume.getVirtualPool());
if (VirtualPool.HighAvailabilityType.vplex_distributed.name().equals(vpool.getHighAvailability())) {
StorageSystem vplexSystem=dbClient.queryObject(StorageSystem.class,volume.getStorageController());
try {
VPlexApiFactory apiFactory=VPlexApiFactory.getInstance();
VPlexApiClient client=getVPlexAPIClient(apiFactory,vplexSystem,dbClient);
VPlexVirtualVolumeInfo vvInfo=client.getVirtualVolumeStructure(volume.getDeviceLabel());
VPlexDistributedDeviceInfo ddInfo=(VPlexDistributedDeviceInfo)vvInfo.getSupportingDeviceInfo();
List<VPlexDeviceInfo> localDeviceInfoList=ddInfo.getLocalDeviceInfo();
for ( VPlexDeviceInfo localDeviceInfo : localDeviceInfoList) {
_log.info("localDeviceInfo: {}, {}",localDeviceInfo.getName(),localDeviceInfo.getCluster());
if (varrayURI != null) {
_log.info("varrayURI:{}",varrayURI);
String varrayCluster=ConnectivityUtil.getVplexClusterForVarray(varrayURI,vplexSystem.getId(),dbClient);
_log.info("varrayCluster:{}",varrayCluster);
if (!localDeviceInfo.getCluster().contains(varrayCluster)) {
continue;
}
}
_log.info("Local device: {}",localDeviceInfo.getName());
_log.info("Extent count: {}",localDeviceInfo.getExtentInfo().size());
if (localDeviceInfo.getExtentInfo().size() != 1) {
supported=false;
break;
}
}
}
catch ( VPlexApiException vae) {
_log.error("Exception checking if migration supported for volume:",vae);
throw vae;
}
catch ( Exception ex) {
_log.error("Exception checking if migration supported for volume",ex);
throw VPlexApiException.exceptions.failedGettingMigrationSupportedForVolume(vplexSystem.getId().toString(),volume.getLabel());
}
}
}
return supported;
}
| Determines if the controller can support migration for the passed VPLEX volume. |
private void addCombinedOccurence(List<AttributeSource> originalAttributeSources,List<Attribute> unionAttributeList,MemoryExampleTable unionTable,Example leftExample,Example rightExample){
double[] unionDataRow=new double[unionAttributeList.size()];
int attributeIndex=0;
for ( AttributeSource attributeSource : originalAttributeSources) {
if (attributeSource.getSource() == AttributeSource.FIRST_SOURCE) {
unionDataRow[attributeIndex]=leftExample.getValue(attributeSource.getAttribute());
}
else if (attributeSource.getSource() == AttributeSource.SECOND_SOURCE) {
unionDataRow[attributeIndex]=rightExample.getValue(attributeSource.getAttribute());
}
attributeIndex++;
}
unionTable.addDataRow(new DoubleArrayDataRow(unionDataRow));
}
| Creates an example which consists of the combination of leftExample an rightExample. Only those attributes are added, which are present in originalAttributeSources. The newly constructed example is added to unionTable. |
public TreeViewerBuilder(Composite parent,int style){
mappings=Collections.emptyMap();
checkable=(style & SWT.CHECK) == SWT.CHECK;
if (checkable) {
viewer=new CheckboxTreeViewer(parent,style);
}
else {
viewer=new TreeViewer(parent,style);
}
ColumnViewerToolTipSupport.enableFor(viewer,ToolTip.NO_RECREATE);
}
| Creates a new TreeViewerBuilder. |
public DriverTask createVolumeMirror(List<VolumeMirror> mirrors){
LOG.info("Creating volume mirror");
DriverTask task=new DellSCDriverTask("createVolumeMirror");
StringBuilder errBuffer=new StringBuilder();
int mirrorsCreated=0;
for ( VolumeMirror mirror : mirrors) {
LOG.debug("Creating mirror of volume {}",mirror.getParentId());
String ssn=mirror.getStorageSystemId();
try {
StorageCenterAPI api=connectionManager.getConnection(ssn);
ScVolume srcVol=api.getVolume(mirror.getParentId());
ScVolume destVol=api.createVolume(ssn,mirror.getDisplayName(),srcVol.storageType.instanceId,SizeUtil.byteToMeg(SizeUtil.sizeStrToBytes(srcVol.configuredSize)),null);
ScCopyMirrorMigrate scCmm=api.createMirror(ssn,srcVol.instanceId,destVol.instanceId);
mirror.setNativeId(scCmm.instanceId);
mirror.setSyncState(SynchronizationState.COPYINPROGRESS);
mirrorsCreated++;
LOG.info("Created volume mirror '{}'",scCmm.instanceId);
}
catch ( StorageCenterAPIException|DellSCDriverException dex) {
String error=String.format("Error creating volume mirror %s: %s",mirror.getDisplayName(),dex);
LOG.error(error);
errBuffer.append(String.format("%s%n",error));
}
}
task.setMessage(errBuffer.toString());
if (mirrorsCreated == mirrors.size()) {
task.setStatus(TaskStatus.READY);
}
else if (mirrorsCreated == 0) {
task.setStatus(TaskStatus.FAILED);
}
else {
task.setStatus(TaskStatus.PARTIALLY_FAILED);
}
return task;
}
| Create volume mirrors. |
public boolean subsampleinwindow(){
return subsampleinwindow;
}
| Word2vec approach for approximating "ramped" weighting of a sliding window by sampling the window size uniformly such that the proximal parts of the window have a higher probability of not being ignored |
public T vertexProcessor(final BiConsumer<Vertex,Map<String,Object>> vertexProcessor){
this.vertexProcessor=Optional.ofNullable(vertexProcessor);
return extendingClass.cast(this);
}
| The function supplied here may be called more than once per vertex depending on the implementation. |
public boolean isModifyPrice(){
Object oo=get_Value(COLUMNNAME_IsModifyPrice);
if (oo != null) {
if (oo instanceof Boolean) return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
| Get Modify Price. |
private HashMap duplicate(HashMap funcs,boolean deepCopy){
if (deepCopy) throw new PageRuntimeException(new ExpressionException("deep copy not supported"));
Iterator it=funcs.entrySet().iterator();
Map.Entry entry;
HashMap cm=new HashMap();
while (it.hasNext()) {
entry=(Entry)it.next();
cm.put(entry.getKey(),deepCopy ? entry.getValue() : entry.getValue());
}
return cm;
}
| duplcate a hashmap with FunctionLibFunction's |
public static byte[] encode(byte[] data){
return encode(data,0,data.length);
}
| encode the input data producing a base 64 encoded byte array. |
public void saveVoice(VoiceConfig config){
config.addCredentials(this);
POST(this.url + "/save-voice",config.toXML());
}
| Save the bot's voice configuration. |
protected void basicOperateOnRegion(EntryEventImpl ev,DistributedRegion rgn){
if (logger.isDebugEnabled()) {
logger.debug("Processing {}",this);
}
try {
long time=this.lastModified;
if (ev.getVersionTag() != null) {
checkVersionTag(rgn,ev.getVersionTag());
time=ev.getVersionTag().getVersionTimeStamp();
}
this.appliedOperation=doPutOrCreate(rgn,ev,time);
}
catch ( ConcurrentCacheModificationException e) {
dispatchElidedEvent(rgn,ev);
this.appliedOperation=false;
}
}
| Do the actual update after operationOnRegion has confirmed work needs to be done Note this is the default implementation used by UpdateOperation. DistributedPutAllOperation overrides and then calls back using super to this implementation. NOTE: be careful to not use methods like getEvent(); defer to the ev passed as a parameter instead. |
public static boolean isDrive(final File file){
Preconditions.checkNotNull(file,"IE01493: File argument can not be null");
return file.getParent() == null;
}
| Determines whether a given file is a drive or not. |
public boolean __gt__(final Object rhs){
return getBigInteger(this).compareTo(getBigInteger(rhs)) > 0;
}
| Used to support > operations on addresses in Python scripts. |
Scope enterScope(Env<AttrContext> env){
return (env.tree.hasTag(JCTree.Tag.CLASSDEF)) ? ((JCClassDecl)env.tree).sym.members_field : env.info.scope;
}
| The scope in which a member definition in environment env is to be entered This is usually the environment's scope, except for class environments, where the local scope is for type variables, and the this and super symbol only, and members go into the class member scope. |
public void addScrollingListener(OnWheelScrollListener listener){
scrollingListeners.add(listener);
}
| Adds wheel scrolling listener |
public URI normalize(){
String thisPath=getPath();
StringTokenizer st=new StringTokenizer(thisPath,String.valueOf(PATH_SEPARATOR));
List<String> segments=new ArrayList<String>();
while (st.hasMoreTokens()) {
segments.add(st.nextToken());
}
List<Integer> removals=new ArrayList<Integer>();
for (int i=0; i < segments.size(); i++) {
String segment=segments.get(i);
if (segment.equals(".")) {
removals.add(0,i);
continue;
}
else if (i > 0 && segment.equals("..")) {
if (segments.get(i - 1).equals("..") == false) {
removals.add(0,i - 1);
removals.add(0,i);
continue;
}
}
}
Iterator<Integer> iter=removals.iterator();
while (iter.hasNext()) {
segments.remove(iter.next());
}
StringBuffer buffer=new StringBuffer();
for (int i=0; i < segments.size(); i++) {
String segment=segments.get(i);
if (i == 0) {
if (isAbsolute()) {
buffer.append(PATH_SEPARATOR);
}
else if (segment.indexOf(SCHEME_SEPARATOR) != -1) {
buffer.append('.');
buffer.append(PATH_SEPARATOR);
}
buffer.append(segment);
continue;
}
buffer.append(PATH_SEPARATOR);
buffer.append(segment);
}
try {
return new URI(getScheme(),getUserInfo(),getHost(),getPort(),buffer.toString(),getQuery(),getFragment());
}
catch ( URISyntaxException e) {
throw new IllegalArgumentException(e.getMessage());
}
}
| Normalize a URI by removing any "./" segments, and "path/../" segments. |
public static void main(String[] args) throws Exception {
int order1=ORDER_MEDIUM;
int order2=ORDER_SMALL;
int order3=ORDER_KARATSUBA;
int order4=ORDER_TOOM_COOK;
if (args.length > 0) order1=(int)((Integer.parseInt(args[0])) * 3.333);
if (args.length > 1) order2=(int)((Integer.parseInt(args[1])) * 3.333);
if (args.length > 2) order3=(int)((Integer.parseInt(args[2])) * 3.333);
if (args.length > 3) order4=(int)((Integer.parseInt(args[3])) * 3.333);
prime();
nextProbablePrime();
arithmetic(order1);
arithmetic(order3);
arithmetic(order4);
divideAndRemainder(order1);
divideAndRemainder(order3);
divideAndRemainder(order4);
pow(order1);
pow(order3);
pow(order4);
square(ORDER_MEDIUM);
square(ORDER_KARATSUBA_SQUARE);
square(ORDER_TOOM_COOK_SQUARE);
bitCount();
bitLength();
bitOps(order1);
bitwise(order1);
shift(order1);
byteArrayConv(order1);
modInv(order1);
modInv(order3);
modInv(order4);
modExp(order1,order2);
modExp2(order1);
stringConv();
serialize();
multiplyLarge();
squareLarge();
divideLarge();
if (failure) throw new RuntimeException("Failure in BigIntegerTest.");
}
| Main to interpret arguments and run several tests. Up to three arguments may be given to specify the SIZE of BigIntegers used for call parameters 1, 2, and 3. The SIZE is interpreted as the maximum number of decimal digits that the parameters will have. |
static int threshold(int size) throws Throwable {
IdentityHashMap<Object,Object> m=new IdentityHashMap<>(size);
int initialCapacity=capacity(m);
while (capacity(m) == initialCapacity) growUsingPut(m,1);
return m.size() - 1;
}
| Given the expected size, computes such a number N of items that inserting (N+1) items will trigger resizing of the internal storage |
public static <T>org.hamcrest.Matcher<T> theInstance(T target){
return org.hamcrest.core.IsSame.theInstance(target);
}
| Creates a matcher that matches only when the examined object is the same instance as the specified target object. |
public AlphabetIndexer(Cursor cursor,int sortedColumnIndex,CharSequence alphabet){
mDataCursor=cursor;
mColumnIndex=sortedColumnIndex;
mAlphabet=alphabet;
mAlphabetLength=alphabet.length();
mAlphabetArray=new String[mAlphabetLength];
for (int i=0; i < mAlphabetLength; i++) {
mAlphabetArray[i]=Character.toString(mAlphabet.charAt(i));
}
mAlphaMap=new SparseIntArray(mAlphabetLength);
if (cursor != null) {
cursor.registerDataSetObserver(this);
}
mCollator=java.text.Collator.getInstance();
mCollator.setStrength(java.text.Collator.PRIMARY);
}
| Constructs the indexer. |
public Effect(BasicEffect effect){
subeffects=Arrays.asList(effect);
fullyGrounded=!effect.containsSlots();
valueTable=new HashMap<String,Map<Value,Double>>();
randomsToGenerate=new HashSet<String>();
if (effect instanceof TemplateEffect) {
((TemplateEffect)effect).getAllSlots().stream().filter(null).forEach(null);
}
}
| Creates a new complex effect with a single effect |
public synchronized void terminatedByServer(){
if (!mSubscribed) {
return;
}
if (sLogger.isActivated()) {
sLogger.info("Subscription has been terminated by server");
}
stopTimer();
resetDialogPath();
mSubscribed=false;
}
| Subscription has been terminated by server |
public void putListBoolean(String key,ArrayList<Boolean> boolList){
ArrayList<String> newList=new ArrayList<String>();
for ( Boolean item : boolList) {
if (item) {
newList.add("true");
}
else {
newList.add("false");
}
}
putListString(key,newList);
}
| Put ArrayList of Boolean into SharedPreferences with 'key' and save |
public double volume(){
if (cachedVolume < 0) {
cachedVolume=1.0;
IHypercube cube=this.region;
int nd=cube.dimensionality();
for (int d=1; d <= nd; d++) {
double right=cube.getRight(d);
double left=cube.getLeft(d);
if (Double.isInfinite(right)) {
right=+1;
}
if (Double.isInfinite(left)) {
left=-1;
}
if (left == -1 && right == +1) {
}
else {
cachedVolume*=(right - left);
}
}
}
return cachedVolume;
}
| Return volume of hypercube region associated with node. <p> Volume is useful to be able to set threshold values when considering when to apply threads to sub-problems. <p> Compute using lazy evaluation and store for use; also assume points are drawn from within the unit square, so convert infinities into -1 and +1. |
public static double interpolate(double start,double end,double lambda){
return (start + (3 * lambda * lambda - 2 * lambda * lambda* lambda) * (end - start));
}
| An interpolation function to smoothly interpolate between start at lambda = 0 and end at lambda = 1 |
public PriorityQueue(){
this(DEFAULT_CAPACITY);
}
| Constructs a priority queue with an initial capacity of 11 and natural ordering. |
private void splitFullName(){
int firstEnd=fullName.indexOf('.');
int secondEnd=fullName.indexOf('.',firstEnd + 1);
timestamp=fullName.substring(0,firstEnd);
uniqueString=fullName.substring(firstEnd + 1,secondEnd);
hostnameAndMeta=fullName.substring(secondEnd + 1,fullName.length());
}
| Splits up the full file name into its main components timestamp, uniqueString and hostNameAndMeta and fills the respective variables. |
public double[] RGBtoIHS(double r,double g,double b){
double[] ret=new double[3];
double i, h, s;
double minRGB=b;
i=r + g + b;
if (g < minRGB) {
minRGB=g;
}
if (r < minRGB) {
minRGB=r;
}
if (i == 3) {
h=0;
}
else if (b == minRGB) {
h=(g - b) / (i - 3 * b);
}
else if (r == minRGB) {
h=(b - r) / (i - 3 * r) + 1;
}
else {
h=(r - g) / (i - 3 * g) + 2;
}
if (h <= 1) {
s=(i - 3 * b) / i;
}
else if (h <= 2) {
s=(i - 3 * r) / i;
}
else {
s=(i - 3 * g) / i;
}
ret[0]=i;
ret[1]=h;
ret[2]=s;
return ret;
}
| Converts RGB colour values to IHS colour values |
@Override public void runWatchers(){
device.runWatchers();
}
| Force to run all watchers. |
protected SVGOMFlowRootElement(){
}
| Creates a new BatikRegularPolygonElement object. |
public static void main(String[] args) throws Exception {
if (args.length != 1) {
System.err.println("Use: java -cp <classPath> org.apache.activemq.artemis.utils.DefaultSensitiveStringCodec password-to-encode");
System.err.println("Error: no password on the args");
System.exit(-1);
}
DefaultSensitiveStringCodec codec=new DefaultSensitiveStringCodec();
Object encode=codec.encode(args[0]);
System.out.println("Encoded password (without quotes): \"" + encode + "\"");
}
| This main class is as documented on configuration-index.md, where the user can mask the password here. |
public void drawString(String s,float x,float y){
if (textAsShapes) {
GlyphVector gv=getFont().createGlyphVector(getFontRenderContext(),s);
drawGlyphVector(gv,x,y);
return;
}
if (generatorCtx.svgFont) {
domTreeManager.gcConverter.getFontConverter().recordFontUsage(s,getFont());
}
AffineTransform savTxf=getTransform();
AffineTransform txtTxf=transformText(x,y);
Element text=getDOMFactory().createElementNS(SVG_NAMESPACE_URI,SVG_TEXT_TAG);
text.setAttributeNS(null,SVG_X_ATTRIBUTE,generatorCtx.doubleString(x));
text.setAttributeNS(null,SVG_Y_ATTRIBUTE,generatorCtx.doubleString(y));
text.setAttributeNS(XML_NAMESPACE_URI,XML_SPACE_QNAME,XML_PRESERVE_VALUE);
text.appendChild(getDOMFactory().createTextNode(s));
domGroupManager.addElement(text,DOMGroupManager.FILL);
if (txtTxf != null) {
this.setTransform(savTxf);
}
}
| Renders the text specified by the specified <code>String</code>, using the current <code>Font</code> and <code>Paint</code> attributes in the <code>Graphics2D</code> context. The baseline of the first character is at position (<i>x</i>, <i>y</i>) in the User Space. The rendering attributes applied include the <code>Clip</code>, <code>Transform</code>, <code>Paint</code>, <code>Font</code> and <code>Composite</code> attributes. For characters in script systems such as Hebrew and Arabic, the glyphs can be rendered from right to left, in which case the coordinate supplied is the location of the leftmost character on the baseline. |
public Tasks<BlockConsistencyGroupRestRep> detachFullCopy(URI consistencyGroupId,URI fullCopyId){
final String url=getIdUrl() + "/protection/full-copies/{fcid}/detach";
return postTasks(url,consistencyGroupId,fullCopyId);
}
| Detach consistency group full copy <p> API Call: <tt>POST /block/consistency-groups/{id}/protection/full-copies/{fcid}/detach</tt> |
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 String delete(String request) throws IOException {
HttpDelete httpDelete=new HttpDelete(getBaseURL() + request);
return getResponse(httpDelete);
}
| Processes a DELETE request using a URL path (with no context path) + optional query params, e.g. "/schema/analysis/protwords/english", and returns the response content. |
@Override public void dispose(){
super.dispose();
_finishedWorkers=null;
_failedWorkers=null;
_runningWorkers=null;
}
| dispose the object |
public XmlHandler addAttributes(Class<?> aClass,Attribute... attributes){
try {
xml.addAttributes(aClass,attributes);
xml.write();
}
catch ( Exception e) {
JmapperLog.ERROR(e);
}
return this;
}
| Adds the attributes from the existent Class in the Xml configuration. |
private String buildTask1GoldElem(StringBuilder textBuilder,List<String> goldElems){
String strGold;
textBuilder.setLength(0);
textBuilder.append("[");
textBuilder.append(concatWithSeparator(goldElems,","));
textBuilder.append("]");
strGold=new String(textBuilder);
return strGold;
}
| Helper method for generateTask1Data, concatenates all JSON formatted tokens (sorted by position) which is then the gold solution and contains markers to all NE in the text fragment. This same format is produced by the JS in the crowdflower.com task1. |
protected void bindView(ViewInterface<T,? extends ViewModel> viewInterface){
mView=viewInterface;
}
| Bind a new View instance |
public void endPrefixMapping(String prefix) throws SAXException {
if (contentHandler != null) {
contentHandler.endPrefixMapping(prefix);
}
}
| Filter an end Namespace prefix mapping event. |
public boolean isLowerInclusive(){
return lowerInclusive;
}
| Returns <code>true</code> if this interval is lower inclusive. |
public static void restore(final Context context){
SharedPreferences prefs=PreferenceManager.getDefaultSharedPreferences(context);
if (LongTermOrbits.isSupported() && prefs.getBoolean(KEY_LOCATION_TOGGLE,false)) {
saveDownloadDataWifiOnlyPref(context);
AlarmManager am=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent intent=new Intent(context,LtoService.class);
PendingIntent pi=PendingIntent.getService(context,0,intent,PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_ONE_SHOT);
long nextLtoDownload=System.currentTimeMillis() + (1000 * 60 * 2L);
am.set(AlarmManager.RTC,nextLtoDownload,pi);
}
}
| Restore the properties associated with this preference on boot |
public int size(){
return strings.size();
}
| Return the number of string elements present. |
public void mark(){
mark(1);
}
| Mark the occurrence of an event. |
public Suspend(){
super();
}
| Suspends the system running XBMC |
public T caseFunctionBlock(FunctionBlock object){
return null;
}
| Returns the result of interpreting the object as an instance of '<em>Function Block</em>'. <!-- begin-user-doc --> This implementation returns null; returning a non-null result will terminate the switch. <!-- end-user-doc --> |
public boolean booleanPrimitiveValueOfParameterNamed(final String parameterName){
final Boolean value=this.fromApiJsonHelper.extractBooleanNamed(parameterName,this.parsedCommand);
return (Boolean)ObjectUtils.defaultIfNull(value,Boolean.FALSE);
}
| always returns true or false |
public static boolean equalDirs(Configuration conf,Path src,Path dest,Optional<PathFilter> filter,boolean compareModificationTimes) throws IOException {
boolean srcExists=src.getFileSystem(conf).exists(src);
boolean destExists=dest.getFileSystem(conf).exists(dest);
if (!srcExists || !destExists) {
return false;
}
Set<FileStatus> srcFileStatuses=getFileStatusesRecursive(conf,src,filter);
Set<FileStatus> destFileStatuses=getFileStatusesRecursive(conf,dest,filter);
Map<String,Long> srcFileSizes=null;
Map<String,Long> destFileSizes=null;
try {
srcFileSizes=getRelPathToSizes(src,srcFileStatuses);
destFileSizes=getRelPathToSizes(dest,destFileStatuses);
}
catch ( ArgumentException e) {
throw new IOException("Invalid file statuses!",e);
}
long srcSize=totalSize(srcFileSizes);
long destSize=totalSize(destFileSizes);
LOG.debug("Size of " + src + " is "+ srcSize);
LOG.debug("Size of " + dest + " is "+ destSize);
if (srcSize != destSize) {
LOG.debug(String.format("Size of %s and %s do not match!",src,dest));
return false;
}
if (srcFileSizes.size() != destFileSizes.size()) {
LOG.warn(String.format("Number of files in %s (%d) and %s (%d) " + "do not match!",src,srcFileSizes.size(),dest,destFileSizes.size()));
return false;
}
for ( String file : srcFileSizes.keySet()) {
if (!destFileSizes.containsKey(file)) {
LOG.warn(String.format("%s missing from %s!",file,dest));
return false;
}
if (!srcFileSizes.get(file).equals(destFileSizes.get(file))) {
LOG.warn(String.format("Size mismatch between %s (%d) in %s " + "and %s (%d) in %s",file,srcFileSizes.get(file),src,file,destFileSizes.get(file),dest));
return false;
}
}
if (compareModificationTimes) {
Map<String,Long> srcFileModificationTimes=null;
Map<String,Long> destFileModificationTimes=null;
try {
srcFileModificationTimes=getRelativePathToModificationTime(src,srcFileStatuses);
destFileModificationTimes=getRelativePathToModificationTime(dest,destFileStatuses);
}
catch ( ArgumentException e) {
throw new IOException("Invalid file statuses!",e);
}
for ( String file : srcFileModificationTimes.keySet()) {
if (!srcFileModificationTimes.get(file).equals(destFileModificationTimes.get(file))) {
LOG.warn(String.format("Modification time mismatch between " + "%s (%d) in %s and %s (%d) in %s",file,srcFileModificationTimes.get(file),src,file,destFileModificationTimes.get(file),dest));
return false;
}
}
}
LOG.debug(String.format("%s and %s are the same",src,dest));
return true;
}
| Checks to see if two directories are equal. The directories are considered equal if they have the same non-zero files with the same sizes in the same paths (with the same modification times if applicable) |
public boolean minLength(String input,int length){
return GenericValidator.minLength(input,length);
}
| Checks if the input value's adjusted length is greater than or equal to the minimum specified by length. |
public WeakIdentityHashMap(int initialCapacity){
this(initialCapacity,DEFAULT_LOAD_FACTOR);
}
| Constructs a new, empty <tt>WeakIdentityHashMap</tt> with the given initial capacity and the default load factor, which is <tt>0.75</tt>. |
@GridifySetToValue(gridName="GridifySetToValueTarget",threshold=2,splitSize=2) @Override public Long findMaximum(Collection<Long> input){
return findMaximum0(input);
}
| Find maximum value in collection. |
public EpsilonBoxDominanceArchive(double[] epsilon){
super(new EpsilonBoxDominanceComparator(epsilon));
}
| Constructs an empty ε-box dominance archive using an additive ε-box dominance comparator with the specified ε values. |
public static void saveImage(final Bitmap bitmap,final File saveToFile){
if (saveToFile.exists()) {
saveToFile.delete();
}
try {
final FileOutputStream out=new FileOutputStream(saveToFile);
bitmap.compress(Bitmap.CompressFormat.PNG,90,out);
out.flush();
out.close();
}
catch ( final Exception e) {
e.printStackTrace();
}
}
| Save the image locally (only for temporary purpose) This function needs to be default or need to be overhauled |
private void jbInit() throws Exception {
panel.setLayout(mainLayout);
treeLabel.setText(Msg.translate(Env.getCtx(),"AD_Tree_ID"));
cbAllNodes.setEnabled(false);
cbAllNodes.setText(Msg.translate(Env.getCtx(),"IsAllNodes"));
treeInfo.setText(" ");
bAdd.setToolTipText("Add to Tree");
bAddAll.setToolTipText("Add ALL to Tree");
bDelete.setToolTipText("Delete from Tree");
bDeleteAll.setToolTipText("Delete ALL from Tree");
bAdd.addActionListener(this);
bAddAll.addActionListener(this);
bDelete.addActionListener(this);
bDeleteAll.addActionListener(this);
northPanel.setLayout(northLayout);
northLayout.setAlignment(FlowLayout.LEFT);
panel.add(northPanel,BorderLayout.NORTH);
northPanel.add(treeLabel,null);
northPanel.add(treeField,null);
northPanel.add(cbAllNodes,null);
northPanel.add(treeInfo,null);
northPanel.add(bAddAll,null);
northPanel.add(bAdd,null);
northPanel.add(bDelete,null);
northPanel.add(bDeleteAll,null);
panel.add(splitPane,BorderLayout.CENTER);
splitPane.add(centerTree,JSplitPane.LEFT);
splitPane.add(new JScrollPane(centerList),JSplitPane.RIGHT);
centerList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
centerList.addListSelectionListener(this);
}
| Static init |
public static boolean isNative(int mod){
return (mod & NATIVE) != 0;
}
| Returns true if the modifiers include the <tt>native</tt> modifier. |
public String toASCIIString(){
StringBuilder result=new StringBuilder();
ASCII_ONLY.appendEncoded(result,toString());
return result.toString();
}
| Returns the textual string representation of this URI instance using the US-ASCII encoding. |
@Override public void put(double[] val,double weight){
assert (val.length == elements.length);
if (weight == 0) {
return;
}
final double nwsum=weight + wsum;
for (int i=BitsUtil.nextSetBit(dims,0); i >= 0; i=BitsUtil.nextSetBit(dims,i + 1)) {
final double delta=val[i] - elements[i];
final double rval=delta * weight / nwsum;
elements[i]+=rval;
}
wsum=nwsum;
}
| Add data with a given weight. |
public static Text valueOf(float f){
TextBuilder tb=new TextBuilder();
return tb.append(f).toText();
}
| Returns the textual representation of the specified <code>float</code> instance. |
public Object runSafely(Catbert.FastStack stack) throws Exception {
DShowMediaPlayer.setUseVmr();
return null;
}
| Sets the video renderer to use the Video Mixing Renderer 9 (Windows Only). This will only work if accelerated rendering is enabled (3D acceleration). If it's not then Overlay will be used as the video renderer instead of VMR9. Applies to all files except DVDs. |
@Deprecated public String unescapeName(final String name){
return super.decodeNode(name);
}
| Unescapes name re-enstating '$' and '_' when replacement strings are found |
public String more(){
return "again";
}
| Called when the "More" button is pressed |
public Rect createFromParcel(Parcel in){
Rect r=new Rect();
r.readFromParcel(in);
return r;
}
| Return a new rectangle from the data in the specified parcel. |
public void visitJumpInsn(int opcode,Label label){
if (mv != null) {
mv.visitJumpInsn(opcode,label);
}
}
| Visits a jump instruction. A jump instruction is an instruction that may jump to another instruction. |
public static boolean isConnectedMobile(Context context){
NetworkInfo info=Connectivity.getNetworkInfo(context);
return (info != null && info.isConnected() && info.getType() == ConnectivityManager.TYPE_MOBILE);
}
| Check if there is any connectivity to a mobile network |
public ClosedConnectionException(){
}
| Constructs a <tt>ClosedConnectionException</tt> with no detail message. |
CSVReader(Reader reader,int line,CSVParser csvParser,boolean keepCR,boolean verifyReader){
this.br=(reader instanceof BufferedReader ? (BufferedReader)reader : new BufferedReader(reader));
this.lineReader=new LineReader(br,keepCR);
this.skipLines=line;
this.parser=csvParser;
this.keepCR=keepCR;
this.verifyReader=verifyReader;
}
| Constructs CSVReader with supplied CSVParser. |
public StaticMap format(Format format){
this.format=format;
return this;
}
| Images may be returned in several common web graphics formats: GIF, JPEG and PNG. |
public static int fastModPrime(long data){
int high=(int)(data >>> 32);
int alpha=((int)data) + (high << 2 + high);
if (alpha < 0 && alpha > -5) {
alpha=alpha + 5;
}
return alpha;
}
| Fast modulo operation for the largest unsigned integer prime. |
long interfaceHash(){
return interfaceHash;
}
| Returns the "interface hash" used to match a stub/skeleton pair for this remote implementation class in the JDK 1.1 version of the JRMP stub/skeleton protocol. |
@Override public void startPrefixMapping(String str,String str1) throws SAXException {
}
| This method does nothing. |
void insertFileNodes(String name,String path,DefaultMutableTreeNode parent){
File fp=new File(path);
if (!fp.exists()) {
return;
}
if (fp.getName().startsWith(".")) {
return;
}
if (fp.getName().equals("CVS")) {
return;
}
DefaultMutableTreeNode newElement=new DefaultMutableTreeNode(name);
insertNodeInto(newElement,parent,parent.getChildCount());
if (fp.isDirectory()) {
String[] sp=fp.list();
for (int i=0; i < sp.length; i++) {
insertFileNodes(sp[i],path + "/" + sp[i],newElement);
}
}
}
| Recursively add a representation of the files below a particular file |
public static void showTabErrors(Project project,String title,List<VcsException> errors){
AbstractVcsHelper.getInstance(project).showErrors(errors,title);
}
| Show errors on the tab |
boolean doSimStep(final double time){
if (withindayEngine != null) withindayEngine.doSimStep(time);
for ( MobsimEngine mobsimEngine : mobsimEngines) {
if (mobsimEngine == this.withindayEngine) continue;
mobsimEngine.doSimStep(time);
}
this.printSimLog(time);
return (this.agentCounter.isLiving() && (this.stopTime > time));
}
| Do one step of the simulation run. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.