code
stringlengths 10
174k
| nl
stringlengths 3
129k
|
|---|---|
private void $$$setupUI$$$(){
contentPanel=new JPanel();
contentPanel.setLayout(new GridLayoutManager(7,1,new Insets(0,0,0,0),-1,-1));
commentLabel=new JLabel();
this.$$$loadLabelText$$$(commentLabel,ResourceBundle.getBundle("com/microsoft/alm/plugin/idea/ui/tfplugin").getString("FeedbackDialog.CommentLabel.Smile"));
contentPanel.add(commentLabel,new GridConstraints(1,0,1,1,GridConstraints.ANCHOR_WEST,GridConstraints.FILL_NONE,GridConstraints.SIZEPOLICY_FIXED,GridConstraints.SIZEPOLICY_FIXED,null,null,null,0,false));
privacyLink=new Hyperlink();
this.$$$loadLabelText$$$(privacyLink,ResourceBundle.getBundle("com/microsoft/alm/plugin/idea/ui/tfplugin").getString("FeedbackForm.PrivacyLink"));
contentPanel.add(privacyLink,new GridConstraints(6,0,1,1,GridConstraints.ANCHOR_WEST,GridConstraints.FILL_NONE,GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,null,null,null,0,false));
final JLabel label1=new JLabel();
this.$$$loadLabelText$$$(label1,ResourceBundle.getBundle("com/microsoft/alm/plugin/idea/ui/tfplugin").getString("FeedbackForm.EmailLabel"));
contentPanel.add(label1,new GridConstraints(3,0,1,1,GridConstraints.ANCHOR_WEST,GridConstraints.FILL_NONE,GridConstraints.SIZEPOLICY_FIXED,GridConstraints.SIZEPOLICY_FIXED,null,null,null,0,false));
email=new JTextField();
contentPanel.add(email,new GridConstraints(4,0,1,1,GridConstraints.ANCHOR_WEST,GridConstraints.FILL_HORIZONTAL,GridConstraints.SIZEPOLICY_WANT_GROW,GridConstraints.SIZEPOLICY_FIXED,null,new Dimension(150,-1),null,0,false));
commentScrollPane=new JScrollPane();
contentPanel.add(commentScrollPane,new GridConstraints(2,0,1,1,GridConstraints.ANCHOR_CENTER,GridConstraints.FILL_BOTH,GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW,GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW,null,null,null,0,false));
comment=new JTextArea();
comment.setLineWrap(true);
comment.setWrapStyleWord(true);
commentScrollPane.setViewportView(comment);
thankYouLabel=new WrappingLabel();
thankYouLabel.setText(ResourceBundle.getBundle("com/microsoft/alm/plugin/idea/ui/tfplugin").getString("FeedbackForm.ThankYouLabel"));
contentPanel.add(thankYouLabel,new GridConstraints(5,0,1,1,GridConstraints.ANCHOR_CENTER,GridConstraints.FILL_BOTH,GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,null,null,null,0,false));
final JLabel label2=new JLabel();
this.$$$loadLabelText$$$(label2,ResourceBundle.getBundle("com/microsoft/alm/plugin/idea/ui/tfplugin").getString("FeedbackDialog.HeaderLabel"));
contentPanel.add(label2,new GridConstraints(0,0,1,1,GridConstraints.ANCHOR_WEST,GridConstraints.FILL_NONE,GridConstraints.SIZEPOLICY_FIXED,GridConstraints.SIZEPOLICY_FIXED,null,null,null,0,false));
commentLabel.setLabelFor(comment);
label1.setLabelFor(email);
}
|
Method generated by IntelliJ IDEA GUI Designer >>> IMPORTANT!! <<< DO NOT edit this method OR call it in your code!
|
public void emitDirect(int taskId,List<Object> tuple,Object messageId){
emitDirect(taskId,Utils.DEFAULT_STREAM_ID,tuple,messageId);
}
|
Emits a tuple to the specified task on the default output stream. This output stream must have been declared as a direct stream, and the specified task must use a direct grouping on this stream to receive the message. The emitted values must be immutable.
|
public boolean isPingDisabled(){
return (null != healthcheck && !healthcheck.exists());
}
|
Returns true if the healthcheck flag-file is enabled but does not exist, otherwise (no file configured, or file configured and exists) returns false.
|
private boolean isLink(){
return ((state & LINK_FLAG) == LINK_FLAG);
}
|
Returns true if this image within a link?
|
public void removeTab(Component comp){
if (tabs.getTabCount() == 0) {
if (firstComp == null || firstComp != comp) {
return;
}
super.remove(firstComp);
firstComp=null;
this.validate();
this.repaint();
return;
}
tabs.remove(comp);
if (tabs.getTabCount() == 1) {
if (firstComp != tabs.getSelectedComponent()) {
firstComp=tabs.getSelectedComponent();
}
tabs.remove(firstComp);
add(firstComp,BorderLayout.CENTER);
super.remove(tabs);
}
}
|
Removes a Component. If after removing the Component there is only one left, remove the JTabbedPane and add the remaining Component directly to the JPanel.
|
public static void modifySpanAnnotation(AnnotationFS aOldFs,AnnotationFS aNewFs,JCas aJCas){
Feature[] features=getAllFeatures(aOldFs);
for ( Feature f : features) {
if (isLinkOrBasicFeatures(aOldFs,f)) {
continue;
}
setFeatureValue(aNewFs,f,getFeatureValue(aOldFs,f));
}
aJCas.addFsToIndexes(aNewFs);
}
|
Modify existing non-stackable annotations from one of the users annotation
|
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.
|
public static void close(Connection conn) throws SQLException {
if (conn != null) {
conn.close();
}
}
|
Close a <code>Connection</code>, avoid closing if null.
|
public TollAnalyzer(final String eventsFile,final double simulationEndTime,final int noOfTimeBins,final String shapeFile,final Network network){
this(eventsFile,simulationEndTime,noOfTimeBins,shapeFile,network,null);
}
|
Area filtering will be used, result will include links falls inside the given shape and persons from all user groups.
|
private void genId(){
setId(Long.valueOf(System.currentTimeMillis() % Long.MAX_VALUE).toString());
}
|
Generates a unique exception ID. The current implementation is based on the system time stamp and is therefore only unique per millisecond (and for about 317 years)
|
public NSGAII(Problem problem,NondominatedSortingPopulation population,EpsilonBoxDominanceArchive archive,Selection selection,Variation variation,Initialization initialization){
super(problem,population,archive,initialization);
this.variation=variation;
this.selection=selection;
}
|
Constructs the NSGA-II algorithm with the specified components.
|
public Grammar(int size){
this(new int[size]);
}
|
Constructs a grammar variable with the specified initial size.
|
public void attrAdded(Attr node,String newv){
if (!changing) {
if (pathSegs != null) {
pathSegs.invalidate();
}
if (normalizedPathSegs != null) {
normalizedPathSegs.invalidate();
}
}
fireBaseAttributeListeners();
if (!hasAnimVal) {
fireAnimatedAttributeListeners();
}
}
|
Called when an Attr node has been added.
|
public HttpSessionsSite(ExtensionHttpSessions extension,String site){
super();
this.extension=extension;
this.site=site;
this.sessions=new LinkedHashSet<>();
this.model=new HttpSessionsTableModel(this);
this.activeSession=null;
}
|
Instantiates a new site http sessions object.
|
public void buildDistanceTables(Geometry rebuildZone){
LOG.info("Finding distances from transit stops to street vertices.");
if (rebuildZone != null) {
LOG.info("Selectively finding distances for only those stops potentially affected by scenario application.");
}
LambdaCounter buildCounter=new LambdaCounter(LOG,getStopCount(),1000,"Computed distances to street vertices from {} of {} transit stops.");
stopToVertexDistanceTables=IntStream.range(0,getStopCount()).parallel().mapToObj(null).collect(Collectors.toList());
buildCounter.done();
}
|
Run a distance-constrained street search from every transit stop in the graph. Store the distance to every reachable street vertex for each of these origin stops. If a scenario has been applied, we need to build tables for any newly created stops and any stops within transfer distance or access/egress distance of those new stops. In that case a rebuildZone geometry should be supplied. If rebuildZone is null, a complete rebuild of all tables will occur for all stops.
|
public Timer(String name){
this.name=name;
duration=0;
}
|
Creates a new timer with the given name.
|
public void delete() throws IOException {
close();
deleteContents(directory);
}
|
Closes the cache and deletes all of its stored values. This will delete all files in the cache directory including files that weren't created by the cache.
|
protected void NCName(){
m_ops.setOp(m_ops.getOp(OpMap.MAPINDEX_LENGTH),m_queueMark - 1);
m_ops.setOp(OpMap.MAPINDEX_LENGTH,m_ops.getOp(OpMap.MAPINDEX_LENGTH) + 1);
nextToken();
}
|
NCName ::= (Letter | '_') (NCNameChar) NCNameChar ::= Letter | Digit | '.' | '-' | '_' | CombiningChar | Extender
|
public static void main(final String[] args){
DOMTestCase.doMain(elementgetelementempty.class,args);
}
|
Runs this test from the command line.
|
protected void sequence_RequiredRuntimeLibraries(ISerializationContext context,RequiredRuntimeLibraries semanticObject){
genericSequencer.createSequence(context,semanticObject);
}
|
Contexts: RequiredRuntimeLibraries returns RequiredRuntimeLibraries Constraint: (requiredRuntimeLibraries+=RequiredRuntimeLibraryDependency requiredRuntimeLibraries+=RequiredRuntimeLibraryDependency*)?
|
@TargetApi(21) public static TVShowDetailsFragment newInstance(TVShowListFragment.ViewHolder vh){
TVShowDetailsFragment fragment=new TVShowDetailsFragment();
Bundle args=new Bundle();
args.putInt(BUNDLE_KEY_TVSHOWID,vh.tvshowId);
args.putInt(BUNDLE_KEY_EPISODE,vh.episode);
args.putString(BUNDLE_KEY_GENRES,vh.genres);
args.putString(BUNDLE_KEY_PLOT,vh.plot);
args.putString(BUNDLE_KEY_PREMIERED,vh.premiered);
args.putDouble(BUNDLE_KEY_RATING,vh.rating);
args.putString(BUNDLE_KEY_STUDIO,vh.studio);
args.putString(BUNDLE_KEY_TITLE,vh.tvshowTitle);
args.putInt(BUNDLE_KEY_WATCHEDEPISODES,vh.watchedEpisodes);
if (Utils.isLollipopOrLater()) {
args.putString(POSTER_TRANS_NAME,vh.artView.getTransitionName());
}
fragment.setArguments(args);
return fragment;
}
|
Create a new instance of this, initialized to show tvshowId
|
@Override public void process(V tuple){
if (!flag) {
low=tuple;
flag=true;
}
else if (low.doubleValue() > tuple.doubleValue()) {
low=tuple;
}
}
|
Unifier process function.
|
@Override public String findNumBinsTipText(){
return "Ignored.";
}
|
Returns the tip text for this property
|
public float seconds(){
return ((float)millis()) / UNIT;
}
|
Returns the elapsed time in seconds; does not stop the timer, if started.
|
public static <DTO>List<DTO> createListDtoFromJson(String json,Class<DTO> dtoInterface){
return DtoFactory.getInstance().createListDtoFromJson(json,dtoInterface);
}
|
Translates JSON to the list of DTO objects.
|
public LoadFactor60ScoringFunctionFactory(ScoringFunctionFactory delegate,EventsManager events,ScoreTracker scoreTracker,Scenario scenario){
this.delegate=delegate;
this.events=events;
this.scoreTracker=scoreTracker;
this.scenario=scenario;
}
|
Constructs a ScoringFunctionFactory that adds disutilities for crowdedness on top of the ScoringFunctions generated by the delegate ScoringFunction. If an EventManager is supplied, CrowdedPenaltyEvents will be passed to the EventManager, which can be useful to find the penalties for crowdedness afterwards.
|
public PerFieldAnalyzerWrapper(Analyzer defaultAnalyzer,Map<String,Analyzer> fieldAnalyzers){
super(PER_FIELD_REUSE_STRATEGY);
this.defaultAnalyzer=defaultAnalyzer;
this.fieldAnalyzers=(fieldAnalyzers != null) ? fieldAnalyzers : Collections.<String,Analyzer>emptyMap();
}
|
Constructs with default analyzer and a map of analyzers to use for specific fields.
|
protected void readImage(){
ix=readShort();
iy=readShort();
iw=readShort();
ih=readShort();
int packed=read();
lctFlag=(packed & 0x80) != 0;
interlace=(packed & 0x40) != 0;
lctSize=2 << (packed & 7);
if (lctFlag) {
lct=readColorTable(lctSize);
act=lct;
}
else {
act=gct;
if (bgIndex == transIndex) bgColor=0;
}
int save=0;
if (transparency) {
save=act[transIndex];
act[transIndex]=0;
}
if (act == null) {
status=STATUS_FORMAT_ERROR;
}
if (err()) return;
decodeImageData();
skip();
if (err()) return;
frameCount++;
image=new BufferedImage(width,height,BufferedImage.TYPE_INT_ARGB_PRE);
setPixels();
frames.add(new GifFrame(image,delay));
if (transparency) {
act[transIndex]=save;
}
resetFrame();
}
|
Reads next frame image
|
private void returnJson500(RequestAndResponse requestAndResponse,String text) throws ServletException, IOException {
requestAndResponse.setResponseContentTypeJson();
requestAndResponse.response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
requestAndResponse.print("{\"errors\":[" + JsonBuilder.quote(text) + "] }");
}
|
Returns a JSON 500.
|
private static void writeItems(final Collection<Item> itemCollection,final DataOutput dos,final boolean dotted) throws IOException {
int size=itemCollection.size();
Item[] items=itemCollection.toArray(new Item[size]);
Arrays.sort(items);
for (int i=0; i < size; i++) {
dos.writeUTF(items[i].name);
dos.writeInt(items[i].access);
dos.writeUTF(dotted ? items[i].desc.replace('/','.') : items[i].desc);
}
}
|
Sorts the items in the collection and writes it to the data output stream
|
public static Drawable generateRoundBorderDrawable(Resources res,float radii,int pressColor,int defaultColor){
radii=dpToPx(res,radii);
float[] outRadii=new float[]{radii,radii,radii,radii,radii,radii,radii,radii};
Shape roundRectShape=new RoundRectShape(outRadii,null,null);
ShapeDrawable shopDrawablePress=new ShapeDrawable(roundRectShape);
shopDrawablePress.getPaint().setColor(pressColor);
Shape roundRectShapeNormal=new RoundRectShape(outRadii,null,null);
ShapeDrawable shopDrawableNormal=new ShapeDrawable(roundRectShapeNormal);
shopDrawableNormal.getPaint().setColor(defaultColor);
StateListDrawable bgStateDrawable=new StateListDrawable();
bgStateDrawable.addState(new int[]{android.R.attr.state_pressed},shopDrawablePress);
bgStateDrawable.addState(new int[]{},shopDrawableNormal);
return bgStateDrawable;
}
|
Generate bg drawable drawable.
|
@Override public boolean supportsDb(String type){
return true;
}
|
No database tables used, so all supported
|
protected SingleAssociationEnd_Impl(){
super();
}
|
<!-- begin-user-doc --> <!-- end-user-doc -->
|
protected static DHPublicKeyParameters decodeDHPublicKey(byte[] encoded){
BigInteger i=new BigInteger(encoded);
return new DHPublicKeyParameters(i,DH_GROUP_PARAMETERS);
}
|
Creates a public key object from the given encoded key.
|
public DrawerBuilder withScrollToTopAfterClick(boolean scrollToTopAfterClick){
this.mScrollToTopAfterClick=scrollToTopAfterClick;
return this;
}
|
defines if the drawer should scroll to top after click
|
public synchronized void notifyWaitingThread(final HostConnectionPool hostPool){
WaitingThread waitingThread=null;
if (hostPool.waitingThreads.size() > 0) {
if (LOG.isDebugEnabled()) {
LOG.debug("Notifying thread waiting on host pool, hostConfig=" + hostPool.hostConfiguration);
}
waitingThread=(WaitingThread)hostPool.waitingThreads.removeFirst();
waitingThreads.remove(waitingThread);
}
else if (waitingThreads.size() > 0) {
if (LOG.isDebugEnabled()) {
LOG.debug("No-one waiting on host pool, notifying next waiting thread.");
}
waitingThread=(WaitingThread)waitingThreads.removeFirst();
waitingThread.hostConnectionPool.waitingThreads.remove(waitingThread);
}
else if (LOG.isDebugEnabled()) {
LOG.debug("Notifying no-one, there are no waiting threads");
}
if (waitingThread != null) {
waitingThread.interruptedByConnectionPool=true;
waitingThread.thread.interrupt();
}
}
|
Notifies a waiting thread that a connection for the given configuration is available. This will wake a thread waiting in this host pool or if there is not one a thread in the connection pool will be notified.
|
public static char[] toCharArray(Reader input) throws IOException {
CharArrayWriter sw=new CharArrayWriter();
copy(input,sw);
return sw.toCharArray();
}
|
Get the contents of a <code>Reader</code> as a character array. <p/> This method buffers the input internally, so there is no need to use a <code>BufferedReader</code>.
|
public void removeSetting(final int index){
Assert.isTrue(index >= 0);
fSettings.remove(index);
}
|
Removes the setting at the specified index.
|
public void addProgressListener(ChartProgressListener listener){
this.progressListeners.add(ChartProgressListener.class,listener);
}
|
Registers an object for notification of progress events relating to the chart.
|
@Override public void run(){
amIActive=true;
String outputHeader="";
int row, col;
double rowYCoord, value, z;
int progress=0;
double cellSizeX, cellSizeY;
int rows, topRow, bottomRow;
int cols;
int inputRow, inputCol;
double inputX, inputY;
double east;
double west;
double north;
double south;
BoundingBox box;
double[][] geometry;
int numPoints, numParts, i, part, numEdges;
int stCol, endCol;
int startingPointInPart, endingPointInPart;
double x1, y1, x2, y2, xPrime;
boolean foundIntersection;
ArrayList<Integer> edgeList=new ArrayList<>();
DecimalFormat df=new DecimalFormat("###,###,###,###");
if (args.length <= 0) {
showFeedback("Plugin parameters have not been set.");
return;
}
String inputFilesString=args[0];
String[] inputFiles=inputFilesString.split(";");
int numFiles=inputFiles.length;
String clipFile=args[1];
if (inputFilesString.isEmpty() || numFiles < 1) {
showFeedback("One or more of the input parameters have not been set properly.");
return;
}
try {
long heapSize=Runtime.getRuntime().totalMemory();
int flushSize=(int)(heapSize / 32);
int j, numCellsToWrite;
PriorityQueue<RowPriorityGridCell> pq=new PriorityQueue<>(flushSize);
ShapeFile clip=new ShapeFile(clipFile);
BoundingBox clipBox=new BoundingBox();
clipBox.setMaxX(clip.getxMax());
clipBox.setMaxY(clip.getyMax());
clipBox.setMinX(clip.getxMin());
clipBox.setMinY(clip.getyMin());
if (clip.getShapeType().getBaseType() != ShapeType.POLYGON) {
showFeedback("The input shapefile must be of a 'polygon' data type.");
return;
}
ArrayList<RecordInfo> myList=new ArrayList<>();
for ( ShapeFileRecord record : clip.records) {
i=record.getRecordNumber();
box=getBoundingBoxFromShapefileRecord(record);
myList.add(new RecordInfo(box.getMaxY(),i));
}
Collections.sort(myList);
for (int k=0; k < numFiles; k++) {
WhiteboxRaster input=new WhiteboxRaster(inputFiles[k],"r");
outputHeader=inputFiles[k].replace(".dep","_erased.dep");
double noData=input.getNoDataValue();
DataType dataType=input.getDataType();
WhiteboxRaster output=new WhiteboxRaster(outputHeader,"rw",inputFiles[k],dataType,noData);
rows=input.getNumberRows();
cols=input.getNumberColumns();
double[] data;
for (row=0; row < rows; row++) {
data=input.getRowValues(row);
for (col=0; col < cols; col++) {
if (data[col] != noData) {
output.setValue(row,col,data[col]);
}
}
if (cancelOp) {
cancelOperation();
return;
}
progress=(int)(100f * row / (rows - 1));
updateProgress(progress);
}
pq.clear();
RowPriorityGridCell cell;
int numRecords=clip.getNumberOfRecords();
int count=0;
int progressCount=(int)(numRecords / 100.0);
if (progressCount <= 0) {
progressCount=1;
}
ShapeFileRecord record;
for ( RecordInfo ri : myList) {
record=clip.getRecord(ri.recNumber - 1);
geometry=getXYFromShapefileRecord(record);
numPoints=geometry.length;
numParts=partData.length;
for (part=0; part < numParts; part++) {
if (!partHoleData[part]) {
box=new BoundingBox();
startingPointInPart=partData[part];
if (part < numParts - 1) {
endingPointInPart=partData[part + 1];
}
else {
endingPointInPart=numPoints;
}
for (i=startingPointInPart; i < endingPointInPart; i++) {
if (geometry[i][1] < box.getMinY()) {
box.setMinY(geometry[i][1]);
}
if (geometry[i][1] > box.getMaxY()) {
box.setMaxY(geometry[i][1]);
}
}
topRow=output.getRowFromYCoordinate(box.getMaxY());
bottomRow=output.getRowFromYCoordinate(box.getMinY());
for (row=topRow; row <= bottomRow; row++) {
edgeList.clear();
foundIntersection=false;
rowYCoord=output.getYCoordinateFromRow(row);
for (i=startingPointInPart; i < endingPointInPart - 1; i++) {
if (isBetween(rowYCoord,geometry[i][1],geometry[i + 1][1])) {
y1=geometry[i][1];
y2=geometry[i + 1][1];
if (y2 != y1) {
x1=geometry[i][0];
x2=geometry[i + 1][0];
xPrime=(x1 + (rowYCoord - y1) / (y2 - y1) * (x2 - x1));
edgeList.add(output.getColumnFromXCoordinate(xPrime));
foundIntersection=true;
}
}
}
if (foundIntersection) {
numEdges=edgeList.size();
if (numEdges == 2) {
stCol=Math.min(edgeList.get(0),edgeList.get(1));
endCol=Math.max(edgeList.get(0),edgeList.get(1));
for (col=stCol; col <= endCol; col++) {
pq.add(new RowPriorityGridCell(row,col,noData));
}
}
else {
Integer[] edgeArray=new Integer[numEdges];
edgeList.toArray(edgeArray);
Arrays.sort(edgeArray);
boolean fillFlag=true;
for (i=0; i < numEdges - 1; i++) {
stCol=edgeArray[i];
endCol=edgeArray[i + 1];
if (fillFlag) {
for (col=stCol; col <= endCol; col++) {
pq.add(new RowPriorityGridCell(row,col,noData));
}
}
fillFlag=!fillFlag;
}
}
}
}
}
}
for (part=0; part < numParts; part++) {
if (partHoleData[part]) {
box=new BoundingBox();
startingPointInPart=partData[part];
if (part < numParts - 1) {
endingPointInPart=partData[part + 1];
}
else {
endingPointInPart=numPoints;
}
for (i=startingPointInPart; i < endingPointInPart; i++) {
if (geometry[i][1] < box.getMinY()) {
box.setMinY(geometry[i][1]);
}
if (geometry[i][1] > box.getMaxY()) {
box.setMaxY(geometry[i][1]);
}
}
topRow=output.getRowFromYCoordinate(box.getMaxY());
bottomRow=output.getRowFromYCoordinate(box.getMinY());
for (row=topRow; row <= bottomRow; row++) {
edgeList.clear();
foundIntersection=false;
rowYCoord=output.getYCoordinateFromRow(row);
for (i=startingPointInPart; i < endingPointInPart - 1; i++) {
if (isBetween(rowYCoord,geometry[i][1],geometry[i + 1][1])) {
y1=geometry[i][1];
y2=geometry[i + 1][1];
if (y2 != y1) {
x1=geometry[i][0];
x2=geometry[i + 1][0];
xPrime=(x1 + (rowYCoord - y1) / (y2 - y1) * (x2 - x1));
edgeList.add(output.getColumnFromXCoordinate(xPrime));
foundIntersection=true;
}
}
}
if (foundIntersection) {
numEdges=edgeList.size();
if (numEdges == 2) {
stCol=Math.min(edgeList.get(0),edgeList.get(1));
endCol=Math.max(edgeList.get(0),edgeList.get(1));
for (col=stCol; col <= endCol; col++) {
pq.add(new RowPriorityGridCell(row,col,input.getValue(row,col)));
}
}
else {
Integer[] edgeArray=new Integer[numEdges];
edgeList.toArray(edgeArray);
Arrays.sort(edgeArray);
boolean fillFlag=true;
for (i=0; i < numEdges - 1; i++) {
stCol=edgeArray[i];
endCol=edgeArray[i + 1];
if (fillFlag) {
for (col=stCol; col <= endCol; col++) {
pq.add(new RowPriorityGridCell(row,col,input.getValue(row,col)));
}
}
fillFlag=!fillFlag;
}
}
}
}
}
}
if (pq.size() >= flushSize) {
j=0;
numCellsToWrite=pq.size();
do {
cell=pq.poll();
output.setValue(cell.row,cell.col,cell.z);
j++;
if (j % 1000 == 0) {
if (cancelOp) {
cancelOperation();
return;
}
updateProgress("Writing to Output (" + df.format(j) + " of "+ df.format(numCellsToWrite)+ "):",(int)(j * 100.0 / numCellsToWrite));
}
}
while (pq.size() > 0);
}
if (cancelOp) {
cancelOperation();
return;
}
count++;
if (count % progressCount == 0) {
progress++;
updateProgress(progress);
}
}
j=0;
numCellsToWrite=pq.size();
if (numCellsToWrite > 0) {
do {
cell=pq.poll();
output.setValue(cell.row,cell.col,cell.z);
j++;
if (j % 1000 == 0) {
if (cancelOp) {
cancelOperation();
return;
}
updateProgress("Writing to Output (" + df.format(j) + " of "+ df.format(numCellsToWrite)+ "):",(int)(j * 100.0 / numCellsToWrite));
}
}
while (pq.size() > 0);
}
output.addMetadataEntry("Created by the " + getDescriptiveName() + " tool.");
output.addMetadataEntry("Created on " + new Date());
output.flush();
output.close();
}
returnData(outputHeader);
}
catch ( OutOfMemoryError oe) {
myHost.showFeedback("An out-of-memory error has occurred during operation.");
}
catch ( Exception e) {
myHost.showFeedback("An error has occurred during operation. See log file for details.");
myHost.logException("Error in " + getDescriptiveName(),e);
}
finally {
updateProgress("Progress: ",0);
amIActive=false;
myHost.pluginComplete();
}
}
|
Used to execute this plugin tool.
|
public static void execAndCheckOutput(ProcessBuilder builder,String expectedOut,String expectedErr) throws Exception {
Process process=builder.start();
ExecutorService executorService=Executors.newFixedThreadPool(2);
try {
Future<String> errFuture=executorService.submit(streamToStringCallable(process.getErrorStream()));
Future<String> outFuture=executorService.submit(streamToStringCallable(process.getInputStream()));
assertEquals(expectedOut,outFuture.get(10,TimeUnit.SECONDS));
assertEquals(expectedErr,errFuture.get(10,TimeUnit.SECONDS));
}
finally {
executorService.shutdown();
process.waitFor();
}
}
|
Starts the process described by 'builder', and asserts that it sees 'expectedOut' on stdout and 'expectedErr' on stderr. Times out after 10s.
|
private void updateProgress(String progressLabel,int progress){
if (myHost != null && ((progress != previousProgress) || (!progressLabel.equals(previousProgressLabel)))) {
myHost.updateProgress(progressLabel,progress);
}
previousProgress=progress;
previousProgressLabel=progressLabel;
}
|
Used to communicate a progress update between a plugin tool and the main Whitebox user interface.
|
public static void sinhAndCosh(double value,DoubleWrapper hsine,DoubleWrapper hcosine){
if (USE_JDK_MATH) {
hsine.value=STRICT_MATH ? StrictMath.sinh(value) : Math.sinh(value);
hcosine.value=STRICT_MATH ? StrictMath.cosh(value) : Math.cosh(value);
return;
}
double h;
if (value < 0.0) {
value=-value;
h=-0.5;
}
else {
h=0.5;
}
if (value < LOG_TWO_POW_27) {
if (value < TWO_POW_N28) {
hsine.value=(h < 0.0) ? -value : value;
}
else {
double t=FastMath.expm1(value);
hsine.value=h * (t + t / (t + 1.0));
}
if (value < TWO_POW_N27) {
hcosine.value=1;
}
else {
double t=FastMath.exp(value);
hcosine.value=0.5 * (t + 1 / t);
}
}
else if (value < 22.0) {
double t=FastMath.expm1(value);
hsine.value=h * (t + t / (t + 1.0));
hcosine.value=0.5 * (t + 1.0);
}
else {
if (value < LOG_DOUBLE_MAX_VALUE) {
hsine.value=h * FastMath.exp(value);
}
else {
double t=FastMath.exp(value * 0.5);
hsine.value=(h * t) * t;
}
hcosine.value=Math.abs(hsine.value);
}
}
|
Computes hyperbolic sine and hyperbolic cosine together, at the cost of... a dependency of this class with DoubleWrapper.
|
public static SpannableString typeface(Context context,int strResId){
if (sDefaultTypefaceCollection == null) {
throw new IllegalStateException("Default typeface collection not initialized. Forgot to call init()?");
}
return typeface(context.getString(strResId),sDefaultTypefaceCollection,Typeface.NORMAL);
}
|
Return spannable string with default typeface style (style: Typeface.NORMAL) see: http://stackoverflow.com/questions/8607707/how-to-set-a-custom-font-in-the-actionbar-title
|
@Override public void onAccept(){
}
|
onAccept called on connection accept.
|
public int findReferencePosition(int offset,boolean danglingElse,boolean matchBrace,boolean matchParen,boolean matchCase,boolean throwsClause){
fIndent=0;
fAlign=JavaHeuristicScanner.NOT_FOUND;
fPosition=offset;
if (matchBrace) {
if (skipScope(Symbols.TokenLBRACE,Symbols.TokenRBRACE)) {
try {
int lineOffset=fDocument.getLineOffset(fLine);
if (lineOffset <= fPosition && fDocument.get(lineOffset,fPosition - lineOffset).trim().length() == 0) return fPosition;
}
catch ( BadLocationException e) {
}
int pos=skipToStatementStart(true,true);
fIndent=0;
return pos;
}
else {
int pos=findReferencePosition(offset,danglingElse,false,matchParen,matchCase,throwsClause);
fIndent--;
return pos;
}
}
if (matchParen) {
if (skipScope(Symbols.TokenLPAREN,Symbols.TokenRPAREN)) {
fIndent=fPrefs.prefContinuationIndent;
return fPosition;
}
else {
int pos=findReferencePosition(offset,danglingElse,matchBrace,false,matchCase,throwsClause);
fIndent--;
return pos;
}
}
if (matchCase) {
return matchCaseAlignment();
}
nextToken();
switch (fToken) {
case Symbols.TokenGREATERTHAN:
case Symbols.TokenRBRACE:
int pos=fPosition;
if (!skipScope()) fPosition=pos;
return skipToStatementStart(danglingElse,false);
case Symbols.TokenSEMICOLON:
pos=fPosition;
if (isSemicolonPartOfForStatement()) {
fIndent=fPrefs.prefContinuationIndent;
return fPosition;
}
else {
fPosition=pos;
if (isTryWithResources()) {
fIndent=fPrefs.prefContinuationIndent;
return fPosition;
}
else {
fPosition=pos;
return skipToStatementStart(danglingElse,false);
}
}
case Symbols.TokenLPAREN:
case Symbols.TokenLBRACE:
case Symbols.TokenLBRACKET:
return handleScopeIntroduction(offset + 1);
case Symbols.TokenEOF:
return JavaHeuristicScanner.NOT_FOUND;
case Symbols.TokenEQUAL:
return handleEqual();
case Symbols.TokenCOLON:
fIndent=fPrefs.prefCaseBlockIndent;
return fPosition;
case Symbols.TokenQUESTIONMARK:
if (fPrefs.prefTernaryDeepAlign) {
setFirstElementAlignment(fPosition,offset + 1);
return fPosition;
}
else {
fIndent=fPrefs.prefTernaryIndent;
return fPosition;
}
case Symbols.TokenDO:
case Symbols.TokenWHILE:
case Symbols.TokenELSE:
fIndent=fPrefs.prefSimpleIndent;
return fPosition;
case Symbols.TokenTRY:
return skipToStatementStart(danglingElse,false);
case Symbols.TokenRBRACKET:
fIndent=fPrefs.prefContinuationIndent;
return fPosition;
case Symbols.TokenRPAREN:
if (throwsClause) {
fIndent=fPrefs.prefContinuationIndent;
return fPosition;
}
int line=fLine;
if (skipScope(Symbols.TokenLPAREN,Symbols.TokenRPAREN)) {
int scope=fPosition;
nextToken();
if (fToken == Symbols.TokenIF || fToken == Symbols.TokenWHILE || fToken == Symbols.TokenFOR) {
fIndent=fPrefs.prefSimpleIndent;
return fPosition;
}
fPosition=scope;
if (looksLikeMethodDecl()) {
return skipToStatementStart(danglingElse,false);
}
if (fToken == Symbols.TokenCATCH) {
return skipToStatementStart(danglingElse,false);
}
fPosition=scope;
if (looksLikeAnonymousTypeDecl()) {
return skipToStatementStart(danglingElse,false);
}
fPosition=scope;
if (looksLikeAnnotation()) {
return skipToStatementStart(danglingElse,false);
}
}
fPosition=offset;
fLine=line;
return skipToPreviousListItemOrListStart();
case Symbols.TokenRETURN:
fIndent=fPrefs.prefContinuationIndent;
return fPosition;
case Symbols.TokenPLUS:
if (isStringContinuation(fPosition)) {
try {
if (isSecondLineOfStringContinuation(offset)) {
fAlign=JavaHeuristicScanner.NOT_FOUND;
fIndent=fPrefs.prefContinuationIndent;
}
else {
int previousLineOffset=fDocument.getLineOffset(fDocument.getLineOfOffset(offset) - 1);
fAlign=fScanner.findNonWhitespaceForwardInAnyPartition(previousLineOffset,JavaHeuristicScanner.UNBOUND);
}
}
catch (BadLocationException e) {
Log.error(JavaIndenter.class,e);
}
return fPosition;
}
fPosition=offset;
return skipToPreviousListItemOrListStart();
case Symbols.TokenCOMMA:
default :
return skipToPreviousListItemOrListStart();
}
}
|
Returns the reference position regarding to indentation for <code>position</code>, or <code>NOT_FOUND</code>.<code>fIndent</code> will contain the relative indentation (in indentation units, not characters) after the call. If there is a special alignment (e.g. for a method declaration where parameters should be aligned), <code>fAlign</code> will contain the absolute position of the alignment reference in <code>fDocument</code>, otherwise <code>fAlign</code> is set to <code>JavaHeuristicScanner.NOT_FOUND</code>.
|
public boolean isDrawerOpen(){
return mDrawerLayout != null && mDrawerLayout.isDrawerOpen(GravityCompat.START);
}
|
checks if the drawer exists and is opened.
|
public Builder withOpenSettingsButton(@StringRes int buttonTextResourceId){
return withOpenSettingsButton(rootView.getContext().getString(buttonTextResourceId));
}
|
Adds a button that opens the application settings when clicked
|
public static boolean withinGetter(Tree.Declaration decl){
return withinGetter(decl.getDeclarationModel());
}
|
Determines whether the declaration's containing scope is a getter
|
public Translation translate(Sentence sentence){
LOG.info("Input {}: {}",sentence.id(),sentence.fullSource());
if (sentence.target() != null) LOG.info("Input {}: Constraining to target sentence '{}'",sentence.id(),sentence.target());
if (sentence.isEmpty()) {
LOG.info("Translation {}: Translation took 0 seconds",sentence.id());
return new Translation(sentence,null,featureFunctions,joshuaConfiguration);
}
long startTime=System.currentTimeMillis();
int numGrammars=allGrammars.size();
Grammar[] grammars=new Grammar[numGrammars];
for (int i=0; i < allGrammars.size(); i++) grammars[i]=allGrammars.get(i);
if (joshuaConfiguration.segment_oovs) sentence.segmentOOVs(grammars);
HyperGraph hypergraph=null;
try {
if (joshuaConfiguration.search_algorithm.equals("stack")) {
Stacks stacks=new Stacks(sentence,this.featureFunctions,grammars,joshuaConfiguration);
hypergraph=stacks.search();
}
else {
Chart chart=new Chart(sentence,this.featureFunctions,grammars,joshuaConfiguration.goal_symbol,joshuaConfiguration);
hypergraph=(joshuaConfiguration.use_dot_chart) ? chart.expand() : chart.expandSansDotChart();
}
}
catch ( java.lang.OutOfMemoryError e) {
LOG.error("Input {}: out of memory",sentence.id());
hypergraph=null;
}
float seconds=(System.currentTimeMillis() - startTime) / 1000.0f;
LOG.info("Input {}: Translation took {} seconds",sentence.id(),seconds);
LOG.info("Input {}: Memory used is {} MB",sentence.id(),(Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / 1000000.0);
if (!joshuaConfiguration.parse || hypergraph == null) {
return new Translation(sentence,hypergraph,featureFunctions,joshuaConfiguration);
}
Grammar newGrammar=getGrammarFromHyperGraph(joshuaConfiguration.goal_symbol,hypergraph);
newGrammar.sortGrammar(this.featureFunctions);
long sortTime=System.currentTimeMillis();
LOG.info("Sentence {}: New grammar has {} rules.",sentence.id(),newGrammar.getNumRules());
Grammar[] newGrammarArray=new Grammar[]{newGrammar};
Sentence targetSentence=new Sentence(sentence.target(),sentence.id(),joshuaConfiguration);
Chart chart=new Chart(targetSentence,featureFunctions,newGrammarArray,"GOAL",joshuaConfiguration);
int goalSymbol=GrammarBuilderWalkerFunction.goalSymbol(hypergraph);
String goalSymbolString=Vocabulary.word(goalSymbol);
LOG.info("Sentence {}: goal symbol is {} ({}).",sentence.id(),goalSymbolString,goalSymbol);
chart.setGoalSymbolID(goalSymbol);
HyperGraph englishParse=chart.expand();
long secondParseTime=System.currentTimeMillis();
LOG.info("Sentence {}: Finished second chart expansion ({} seconds).",sentence.id(),(secondParseTime - sortTime) / 1000);
LOG.info("Sentence {} total time: {} seconds.\n",sentence.id(),(secondParseTime - startTime) / 1000);
LOG.info("Memory used after sentence {} is {} MB",sentence.id(),(Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / 1000000.0);
return new Translation(sentence,englishParse,featureFunctions,joshuaConfiguration);
}
|
Translate a sentence.
|
public <T extends Fragment>T into(T fragment){
fragment.setArguments(get());
return fragment;
}
|
Set the argument of Fragment.
|
protected void addIntermediateNode(BTreeNode curNode,List<BTreeNode[]> childNodeGroups,BTreeNode[] currentGroup,List<List<IndexKey>> interNSKeyList,int numberOfInternalNode){
int groupCounter;
int remainder;
int nHigh=numberOfInternalNode;
boolean bRootBuilt=false;
remainder=nLeaf % (maxNumberOfEntriesInNonLeafNodes);
List<IndexKey> interNSKeys=null;
while (nHigh > 1 || !bRootBuilt) {
List<BTreeNode[]> internalNodeGroups=new ArrayList<BTreeNode[]>(CarbonCommonConstants.CONSTANT_SIZE_TEN);
List<List<IndexKey>> interNSKeyTmpList=new ArrayList<List<IndexKey>>(CarbonCommonConstants.CONSTANT_SIZE_TEN);
numberOfInternalNode=0;
for (int i=0; i < nHigh; i++) {
curNode=new BTreeNonLeafNode();
groupCounter=i % (maxNumberOfEntriesInNonLeafNodes);
if (groupCounter == 0) {
currentGroup=new BTreeNonLeafNode[maxNumberOfEntriesInNonLeafNodes];
internalNodeGroups.add(currentGroup);
numberOfInternalNode++;
interNSKeys=new ArrayList<IndexKey>(CarbonCommonConstants.CONSTANT_SIZE_TEN);
interNSKeyTmpList.add(interNSKeys);
}
if (null != currentGroup) {
currentGroup[groupCounter]=curNode;
}
int nNodes;
if (i == nHigh - 1 && remainder != 0) {
nNodes=remainder;
}
else {
nNodes=maxNumberOfEntriesInNonLeafNodes;
}
curNode.setChildren(childNodeGroups.get(i));
for (int j=0; j < nNodes; j++) {
curNode.setKey(interNSKeyList.get(i).get(j));
if (j == 0 && null != interNSKeys) {
interNSKeys.add(interNSKeyList.get(i).get(j));
}
}
}
if (nHigh == 1) {
bRootBuilt=true;
}
remainder=nHigh % (maxNumberOfEntriesInNonLeafNodes);
nHigh=numberOfInternalNode;
childNodeGroups=internalNodeGroups;
interNSKeyList=interNSKeyTmpList;
}
root=curNode;
}
|
Below method is to build the intermediate node of the btree
|
public void updateClusterGroupsFromGossiper(){
for ( Entry<InetAddress,EndpointState> entry : Gossiper.instance.getEndpointStates()) {
DiscoveryNodeStatus status=(entry.getValue().isAlive()) ? DiscoveryNode.DiscoveryNodeStatus.ALIVE : DiscoveryNode.DiscoveryNodeStatus.DEAD;
if (DatabaseDescriptor.getEndpointSnitch().getDatacenter(entry.getKey()).equals(localDc)) {
VersionedValue vv=entry.getValue().getApplicationState(ApplicationState.HOST_ID);
if (vv != null) {
String hostId=vv.value;
DiscoveryNode dn=clusterGroup.get(hostId);
if (dn == null) {
Map<String,String> attrs=Maps.newHashMap();
attrs.put("data","true");
attrs.put("master","true");
attrs.put("data_center",localDc);
attrs.put("rack",DatabaseDescriptor.getEndpointSnitch().getRack(entry.getKey()));
InetAddress rpc_address=com.google.common.net.InetAddresses.forString(entry.getValue().getApplicationState(ApplicationState.RPC_ADDRESS).value);
dn=new DiscoveryNode(buildNodeName(entry.getKey()),hostId.toString(),new InetSocketTransportAddress(rpc_address,publishPort()),attrs,version);
dn.status(status);
if (localAddress.equals(entry.getKey())) {
logger.debug("Update local node host_id={} status={} timestamp={}",entry.getKey().toString(),dn.getId(),dn.getName(),entry.getValue().isAlive(),entry.getValue().getUpdateTimestamp());
clusterGroup.remove(this.localNode.id());
this.localNode=dn;
}
else {
logger.debug("New node addr_ip={} node_name={} host_id={} status={} timestamp={}",entry.getKey().toString(),dn.getId(),dn.getName(),entry.getValue().isAlive(),entry.getValue().getUpdateTimestamp());
}
clusterGroup.put(dn.getId(),dn);
if (entry.getValue().getApplicationState(ApplicationState.X1) != null || entry.getValue().getApplicationState(ApplicationState.X2) != null) {
SystemKeyspace.updatePeerInfo(entry.getKey(),"workload","elasticsearch");
}
}
else {
if (!dn.getStatus().equals(status)) {
dn.status(status);
}
}
}
}
}
}
|
Update cluster group members from cassandra topology (should only be triggered by IEndpointStateChangeSubscriber events). This should trigger re-sharding of index for new nodes (when token distribution change).
|
@Override public boolean updatesAreDetected(int type){
debugCodeCall("updatesAreDetected",type);
return false;
}
|
Returns whether updates are detected.
|
protected int findAndEliminateRedundant(int start,int firstOccuranceIndex,ExpressionOwner firstOccuranceOwner,ElemTemplateElement psuedoVarRecipient,Vector paths) throws org.w3c.dom.DOMException {
MultistepExprHolder head=null;
MultistepExprHolder tail=null;
int numPathsFound=0;
int n=paths.size();
Expression expr1=firstOccuranceOwner.getExpression();
if (DEBUG) assertIsLocPathIterator(expr1,firstOccuranceOwner);
boolean isGlobal=(paths == m_absPaths);
LocPathIterator lpi=(LocPathIterator)expr1;
int stepCount=countSteps(lpi);
for (int j=start; j < n; j++) {
ExpressionOwner owner2=(ExpressionOwner)paths.elementAt(j);
if (null != owner2) {
Expression expr2=owner2.getExpression();
boolean isEqual=expr2.deepEquals(lpi);
if (isEqual) {
LocPathIterator lpi2=(LocPathIterator)expr2;
if (null == head) {
head=new MultistepExprHolder(firstOccuranceOwner,stepCount,null);
tail=head;
numPathsFound++;
}
tail.m_next=new MultistepExprHolder(owner2,stepCount,null);
tail=tail.m_next;
paths.setElementAt(null,j);
numPathsFound++;
}
}
}
if ((0 == numPathsFound) && isGlobal) {
head=new MultistepExprHolder(firstOccuranceOwner,stepCount,null);
numPathsFound++;
}
if (null != head) {
ElemTemplateElement root=isGlobal ? psuedoVarRecipient : findCommonAncestor(head);
LocPathIterator sharedIter=(LocPathIterator)head.m_exprOwner.getExpression();
ElemVariable var=createPseudoVarDecl(root,sharedIter,isGlobal);
if (DIAGNOSE_MULTISTEPLIST) System.err.println("Created var: " + var.getName() + (isGlobal ? "(Global)" : ""));
QName uniquePseudoVarName=var.getName();
while (null != head) {
ExpressionOwner owner=head.m_exprOwner;
if (DIAGNOSE_MULTISTEPLIST) diagnoseLineNumber(owner.getExpression());
changeToVarRef(uniquePseudoVarName,owner,paths,root);
head=head.m_next;
}
paths.setElementAt(var.getSelect(),firstOccuranceIndex);
}
return numPathsFound;
}
|
Look through the vector from start point, looking for redundant occurances. When one or more are found, create a psuedo variable declaration, insert it into the stylesheet, and replace the occurance with a reference to the psuedo variable. When a redundent variable is found, it's slot in the vector will be replaced by null.
|
private synchronized void rebuildJournal() throws IOException {
if (journalWriter != null) {
journalWriter.close();
}
Writer writer=new BufferedWriter(new FileWriter(journalFileTmp),IO_BUFFER_SIZE);
writer.write(MAGIC);
writer.write("\n");
writer.write(VERSION_1);
writer.write("\n");
writer.write(Integer.toString(appVersion));
writer.write("\n");
writer.write(Integer.toString(valueCount));
writer.write("\n");
writer.write("\n");
for ( Entry entry : lruEntries.values()) {
if (entry.currentEditor != null) {
writer.write(DIRTY + ' ' + entry.key+ '\n');
}
else {
writer.write(CLEAN + ' ' + entry.key+ entry.getLengths()+ '\n');
}
}
writer.close();
journalFileTmp.renameTo(journalFile);
journalWriter=new BufferedWriter(new FileWriter(journalFile,true),IO_BUFFER_SIZE);
}
|
Creates a new journal that omits redundant information. This replaces the current journal if it exists.
|
static void testAccess1(ClassLoader loader){
Class altClass;
try {
altClass=loader.loadClass("Inaccessible1");
}
catch ( ClassNotFoundException cnfe) {
System.err.println("loadClass failed");
cnfe.printStackTrace();
return;
}
Object obj;
try {
obj=altClass.newInstance();
System.err.println("ERROR: Inaccessible1 was accessible");
}
catch ( InstantiationException ie) {
System.err.println("newInstance failed: " + ie);
return;
}
catch ( IllegalAccessException iae) {
System.out.println("Got expected access exception #1");
return;
}
}
|
See if we can load a class that isn't public to us. We should be able to load it but not instantiate it.
|
public SignatureVisitor visitReturnType(){
return this;
}
|
Visits the return type of the method.
|
public static _Fields findByName(String name){
return byName.get(name);
}
|
Find the _Fields constant that matches name, or null if its not found.
|
public static double incompleteBeta(double aa,double bb,double xx){
double a, b, t, x, xc, w, y;
boolean flag;
if (aa <= 0.0 || bb <= 0.0) throw new ArithmeticException("ibeta: Domain error!");
if ((xx <= 0.0) || (xx >= 1.0)) {
if (xx == 0.0) return 0.0;
if (xx == 1.0) return 1.0;
throw new ArithmeticException("ibeta: Domain error!");
}
flag=false;
if ((bb * xx) <= 1.0 && xx <= 0.95) {
t=powerSeries(aa,bb,xx);
return t;
}
w=1.0 - xx;
if (xx > (aa / (aa + bb))) {
flag=true;
a=bb;
b=aa;
xc=xx;
x=w;
}
else {
a=aa;
b=bb;
xc=w;
x=xx;
}
if (flag && (b * x) <= 1.0 && x <= 0.95) {
t=powerSeries(a,b,x);
if (t <= MACHEP) t=1.0 - MACHEP;
else t=1.0 - t;
return t;
}
y=x * (a + b - 2.0) - (a - 1.0);
if (y < 0.0) w=incompleteBetaFraction1(a,b,x);
else w=incompleteBetaFraction2(a,b,x) / xc;
y=a * Math.log(x);
t=b * Math.log(xc);
if ((a + b) < MAXGAM && Math.abs(y) < MAXLOG && Math.abs(t) < MAXLOG) {
t=Math.pow(xc,b);
t*=Math.pow(x,a);
t/=a;
t*=w;
t*=gamma(a + b) / (gamma(a) * gamma(b));
if (flag) {
if (t <= MACHEP) t=1.0 - MACHEP;
else t=1.0 - t;
}
return t;
}
y+=t + lnGamma(a + b) - lnGamma(a) - lnGamma(b);
y+=Math.log(w / a);
if (y < MINLOG) t=0.0;
else t=Math.exp(y);
if (flag) {
if (t <= MACHEP) t=1.0 - MACHEP;
else t=1.0 - t;
}
return t;
}
|
Returns the Incomplete Beta Function evaluated from zero to <tt>xx</tt>.
|
public void finer(String msg){
log(Level.FINER,msg);
}
|
Log a FINER message. <p> If the logger is currently enabled for the FINER message level then the given message is forwarded to all the registered output Handler objects. <p>
|
public LinkedList(){
}
|
Constructs an empty list.
|
public SkinFileChooserUI(JFileChooser filechooser){
super(filechooser);
}
|
Creates the UI delegate for the specified file chooser.
|
public synchronized void resetAddressItemList(){
addressItemList=null;
}
|
Resets a to-many relationship, making the next get call to query for a fresh result.
|
private void loadMap(String extension,String mimeType){
if (!mimeTypeToExtensionMap.containsKey(mimeType)) {
mimeTypeToExtensionMap.put(mimeType,extension);
}
extensionToMimeTypeMap.put(extension,mimeType);
if (isImageType(mimeType)) {
imageMimeTypeSet.add(mimeType);
}
}
|
Load an entry into the map.
|
static String instructionToString(IR ir,Instruction instr){
StringBuilder sb=new StringBuilder();
sb.append(instr.getBytecodeIndex()).append("\t").append(instr.isPEI() ? "E" : " ").append(instr.isGCPoint() ? "G " : " ");
if (instr.operator() == LABEL) {
sb.append("LABEL").append(Label.getBlock(instr).block.getNumber());
if (Label.getBlock(instr).block.getInfrequent()) {
sb.append(" (Infrequent)");
}
}
else {
IREnumeration.AllDefsEnum defs=new IREnumeration.AllDefsEnum(ir,instr);
IREnumeration.AllUsesEnum uses=new IREnumeration.AllUsesEnum(ir,instr);
sb.append(instr.operator()).append("\n\t defs: ");
while (defs.hasMoreElements()) {
sb.append(defs.nextElement().toString());
if (defs.hasMoreElements()) {
sb.append(", ");
}
}
sb.append("\n\t uses: ");
while (uses.hasMoreElements()) {
sb.append(uses.nextElement().toString());
if (uses.hasMoreElements()) {
sb.append(", ");
}
}
}
sb.append("\n");
return sb.toString();
}
|
Converts instruction to String in of AnnotatedLSTNode format.
|
protected void createChildrenLazily(SourcePrinter out,WidgetCreatorContext context){
out.println(context.getWidget() + ".addAttachHandler(new " + Handler.class.getCanonicalName()+ "(){");
out.println("private boolean childrenCreated = false;");
out.println("public void onAttachOrDetach(" + AttachEvent.class.getCanonicalName() + " event){");
out.println("if (!childrenCreated && event.isAttached()){");
createPostProcessingScope();
createChildrenWidgets(out,context);
commitPostProcessing(out);
out.println("childrenCreated = true;");
out.println("}");
out.println("}");
out.println("});");
}
|
Create the children widgets lazily. It means, only process the HTML panel children creation when the panel is attached to DOM. This strategy is less secure, but faster, that eager loading strategy.
|
static <E>ImmutableList<E> asImmutableList(Object[] elements,int length){
switch (length) {
case 0:
return of();
case 1:
@SuppressWarnings("unchecked") ImmutableList<E> list=new SingletonImmutableList<E>((E)elements[0]);
return list;
default :
if (length < elements.length) {
elements=arraysCopyOf(elements,length);
}
return new RegularImmutableList<E>(elements);
}
}
|
Views the array as an immutable list. Copies if the specified range does not cover the complete array. Does not check for nulls.
|
protected void checkIndex(int index){
if (index < 0 || index >= size) throw new IndexOutOfBoundsException("Attempted to access " + toStringShort() + " at index="+ index);
}
|
Sanity check for operations requiring an index to be within bounds.
|
@Override public boolean equals(Object o){
if (o instanceof ChannelInfo) {
ChannelInfo other=(ChannelInfo)o;
if (this.channelId != null) {
if (this.channelId.equals(other.channelId)) return true;
}
else if (this.channelName != null && this.channelNumber != null) {
return this.channelName.equals(other.channelName) && this.channelNumber.equals(other.channelNumber) && this.majorNumber == other.majorNumber && this.minorNumber == other.minorNumber;
}
Log.d(Util.T,"Could not compare channel values, no data to compare against");
Log.d(Util.T,"This channel info: \n" + this.rawData.toString());
Log.d(Util.T,"Other channel info: \n" + other.rawData.toString());
return false;
}
return super.equals(o);
}
|
Compares two ChannelInfo objects.
|
public Editor edit() throws IOException {
return DiskLruCache.this.edit(key,sequenceNumber);
}
|
Returns an editor for this snapshot's entry, or null if either the entry has changed since this snapshot was created or if another edit is in progress.
|
private View findChildUnder(float x,float y){
return findChildUnder(this,x,y);
}
|
Note: this method doesn't take Z into account for overlapping views since it is only used in contexts where this doesn't affect the outcome.
|
public QRBase(){
}
|
Creates a query base object with nothing set.
|
private static byte[] encode3to4(byte[] b4,byte[] threeBytes,int numSigBytes,int options){
encode3to4(threeBytes,0,numSigBytes,b4,0,options);
return b4;
}
|
Encodes up to the first three bytes of array <var>threeBytes</var> and returns a four-byte array in Base64 notation. The actual number of significant bytes in your array is given by <var>numSigBytes</var>. The array <var>threeBytes</var> needs only be as big as <var>numSigBytes</var>. Code can reuse a byte array by passing a four-byte array as <var>b4</var>.
|
@DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 12:32:24.646 -0500",hash_original_method="439F40B8AE0DFA06D4CE3EB843023A82",hash_generated_method="EAF5CD1C7D4E570AFF0CBE3F9A1D9217") public void switchToHeader(Header header){
if (mCurHeader == header) {
getFragmentManager().popBackStack(BACK_STACK_PREFS,FragmentManager.POP_BACK_STACK_INCLUSIVE);
}
else {
int direction=mHeaders.indexOf(header) - mHeaders.indexOf(mCurHeader);
switchToHeaderInner(header.fragment,header.fragmentArguments,direction);
setSelectedHeader(header);
}
}
|
When in two-pane mode, switch to the fragment pane to show the given preference fragment.
|
protected boolean isOnlyReceipt(){
super.setIsOnlyReceipt(pickcombo.getSelectedIndex() == 2);
return super.isOnlyReceipt();
}
|
Determines whether the Delivery Rule is set to 'OnlyReciept'
|
public SuggestRequest routing(String... routings){
this.routing=Strings.arrayToCommaDelimitedString(routings);
return this;
}
|
The routing values to control the shards that the search will be executed on.
|
private void returnData(Object ret){
if (myHost != null) {
myHost.returnData(ret);
}
}
|
Used to communicate a return object from a plugin tool to the main Whitebox user-interface.
|
@Override public void createFieldEditors(){
Composite fep=getFieldEditorParent();
addField(new BooleanFieldEditor(PreferenceConstants.CRYPTO_VERINICE_SSL_SECURITY_ENABLED,Messages.getString("CryptoPreferencePage.0"),fep));
addField(new BooleanFieldEditor(PreferenceConstants.CRYPTO_SERVER_AUTHENTICATION_VIA_CERTIFICATE_ENABLED,Messages.getString("CryptoPreferencePage.1"),fep));
if (isPKCS11Supported()) {
RadioGroupFieldEditor trustStoreSourceRadioField=new RadioGroupFieldEditor(PreferenceConstants.CRYPTO_TRUSTSTORE_SOURCE,Messages.getString("CryptoPreferencePage.2"),1,new String[][]{{Messages.getString("CryptoPreferencePage.3"),PreferenceConstants.CRYPTO_TRUSTSTORE_SOURCE_FROM_FILE},{Messages.getString("CryptoPreferencePage.4"),PreferenceConstants.CRYPTO_TRUSTSTORE_SOURCE_FROM_PKCS11_LIBRARY}},fep);
addField(trustStoreSourceRadioField);
}
else {
RadioGroupFieldEditor trustStoreSourceRadioFieldWin=new RadioGroupFieldEditor(PreferenceConstants.CRYPTO_TRUSTSTORE_SOURCE,Messages.getString("CryptoPreferencePage.2"),1,new String[][]{{Messages.getString("CryptoPreferencePage.3"),PreferenceConstants.CRYPTO_TRUSTSTORE_SOURCE_FROM_FILE}},fep);
addField(trustStoreSourceRadioFieldWin);
}
if (isPKCS11Supported()) {
RadioGroupFieldEditor keyStoreSourceRadioField=new RadioGroupFieldEditor(PreferenceConstants.CRYPTO_KEYSTORE_SOURCE,Messages.getString("CryptoPreferencePage.5"),1,new String[][]{{Messages.getString("CryptoPreferencePage.6"),PreferenceConstants.CRYPTO_KEYSTORE_SOURCE_NONE},{Messages.getString("CryptoPreferencePage.7"),PreferenceConstants.CRYPTO_KEYSTORE_SOURCE_FROM_FILE},{Messages.getString("CryptoPreferencePage.8"),PreferenceConstants.CRYPTO_KEYSTORE_SOURCE_FROM_PKCS11_LIBRARY}},fep);
addField(keyStoreSourceRadioField);
}
else {
RadioGroupFieldEditor keyStoreSourceRadioFieldWin=new RadioGroupFieldEditor(PreferenceConstants.CRYPTO_KEYSTORE_SOURCE,Messages.getString("CryptoPreferencePage.5"),1,new String[][]{{Messages.getString("CryptoPreferencePage.6"),PreferenceConstants.CRYPTO_KEYSTORE_SOURCE_NONE},{Messages.getString("CryptoPreferencePage.7"),PreferenceConstants.CRYPTO_KEYSTORE_SOURCE_FROM_FILE}},fep);
addField(keyStoreSourceRadioFieldWin);
}
addField(new FileFieldEditor(PreferenceConstants.CRYPTO_KEYSTORE_FILE,Messages.getString("CryptoPreferencePage.9"),fep));
addField(new FileFieldEditor(PreferenceConstants.CRYPTO_TRUSTSTORE_FILE,Messages.getString("CryptoPreferencePage.10"),fep));
if (isPKCS11Supported()) {
addField(new FileFieldEditor(PreferenceConstants.CRYPTO_PKCS11_LIBRARY_PATH,Messages.getString("CryptoPreferencePage.11"),fep));
addField(new StringFieldEditor(PreferenceConstants.CRYPTO_PKCS11_CERTIFICATE_ALIAS,Messages.getString("CryptoPreferencePage.15"),fep));
}
}
|
Creates the field editors. Field editors are abstractions of the common GUI blocks needed to manipulate various types of preferences. Each field editor knows how to save and restore itself.
|
public void updateItem(int identifier){
if (mDrawer != null && mDrawerAdapter != null && mDrawerAdapter.getDrawerItems() != null && identifier != -1) {
IDrawerItem drawerItem=mDrawer.getDrawerItem(identifier);
for (int i=0; i < mDrawerAdapter.getDrawerItems().size(); i++) {
if (mDrawerAdapter.getDrawerItems().get(i).getIdentifier() == drawerItem.getIdentifier()) {
IDrawerItem miniDrawerItem=generateMiniDrawerItem(drawerItem);
if (miniDrawerItem != null) {
mDrawerAdapter.setDrawerItem(i,miniDrawerItem);
}
}
}
}
}
|
update a MiniDrawerItem (after updating the main Drawer) via its identifier
|
public boolean equals(Object obj){
if (this == obj) return true;
if (!(obj instanceof RFC822Name)) return false;
RFC822Name other=(RFC822Name)obj;
return name.equalsIgnoreCase(other.name);
}
|
Compares this name with another, for equality.
|
public static int compare(String id1,String id2){
int result=-1;
String seed1=IdGenerator.getSeedFromId(id1);
String seed2=IdGenerator.getSeedFromId(id2);
if (seed1 != null && seed2 != null) {
result=seed1.compareTo(seed2);
if (result == 0) {
long count1=IdGenerator.getSequenceFromId(id1);
long count2=IdGenerator.getSequenceFromId(id2);
result=(int)(count1 - count2);
}
}
return result;
}
|
Does a proper compare on the Id's
|
public boolean isPublic(){
return Modifier.isPublic(_method.getModifiers());
}
|
Returns true for a public method.
|
private void cmd_history(){
log.info("");
if (m_mWorkbench.getMWindow(getWindowIndex()).isTransaction()) {
if (m_curTab.needSave(true,true) && !cmd_save(false)) return;
Point pt=new Point(0,aHistory.getButton().getBounds().height);
SwingUtilities.convertPointToScreen(pt,aHistory.getButton());
VOnlyCurrentDays ocd=new VOnlyCurrentDays(Env.getFrame(this),pt);
if (!ocd.isCancel()) {
m_onlyCurrentDays=ocd.getCurrentDays();
if (m_onlyCurrentDays == 1) {
m_onlyCurrentRows=true;
m_onlyCurrentDays=0;
}
else m_onlyCurrentRows=false;
m_curTab.setQuery(null);
MRole role=MRole.getDefault();
int maxRows=role.getMaxQueryRecords();
log.config("OnlyCurrent=" + m_onlyCurrentRows + ", Days="+ m_onlyCurrentDays+ ", MaxRows="+ maxRows);
m_curGC.query(m_onlyCurrentRows,m_onlyCurrentDays,maxRows);
}
else {
if (isFirstTab()) aHistory.setPressed(!m_curTab.isOnlyCurrentRows());
}
}
}
|
Toggle History
|
final String[] tokenize(String cmdLine){
cmdLine=cmdLine.trim();
return cmdLine.split("\\s+");
}
|
Convert a string to tokens by splitting at whitespace characters.
|
public boolean hasAttributes(){
return this.hasAttributes;
}
|
Returns true if someone explicitly added region attributes to this region.
|
public Drawer buildView(){
mSliderLayout=(ScrimInsetsRelativeLayout)mActivity.getLayoutInflater().inflate(R.layout.material_drawer_slider,mDrawerLayout,false);
mSliderLayout.setBackgroundColor(UIUtils.getThemeColorFromAttrOrRes(mActivity,R.attr.material_drawer_background,R.color.material_drawer_background));
DrawerLayout.LayoutParams params=(DrawerLayout.LayoutParams)mSliderLayout.getLayoutParams();
if (params != null) {
params.gravity=mDrawerGravity;
params=DrawerUtils.processDrawerLayoutParams(this,params);
mSliderLayout.setLayoutParams(params);
}
createContent();
Drawer result=new Drawer(this);
if (mAccountHeader != null) {
mAccountHeader.setDrawer(result);
}
if (mSavedInstance != null && mSavedInstance.getBoolean(Drawer.BUNDLE_DRAWER_CONTENT_SWITCHED,false)) {
mAccountHeader.toggleSelectionList(mActivity);
}
handleShowOnFirstLaunch();
if (!mAppended && mGenerateMiniDrawer) {
mMiniDrawer=new MiniDrawer().withDrawer(result).withAccountHeader(mAccountHeader).withPositionBasedStateManagement(mPositionBasedStateManagement);
}
mActivity=null;
return result;
}
|
build the drawers content only. This will still return a Result object, but only with the content set. No inflating of a DrawerLayout.
|
private List<CompletionProposal> jsToList(List<AngularJSCompletionProposal> autocompletions,InvocationContext context){
final List<CompletionProposal> proposals=new ArrayList<>();
if (autocompletions != null) {
for ( AngularJSCompletionProposal proposal : autocompletions) {
proposals.add(proposal);
proposal.setInvocationContext(context);
}
}
return proposals;
}
|
Convert Javascript array and apply invocation context
|
public String[] validBaudRates(){
return new String[]{"57,600 baud"};
}
|
Get an array of valid baud rates.
|
public ValidationWarnings validate(VCardVersion version){
ValidationWarnings warnings=new ValidationWarnings();
if (getStructuredName() == null && (version == VCardVersion.V2_1 || version == VCardVersion.V3_0)) {
warnings.add(null,new Warning(0));
}
if (getFormattedName() == null && (version == VCardVersion.V3_0 || version == VCardVersion.V4_0)) {
warnings.add(null,new Warning(1));
}
for ( VCardProperty property : this) {
List<Warning> propWarnings=property.validate(version,this);
if (!propWarnings.isEmpty()) {
warnings.add(property,propWarnings);
}
}
return warnings;
}
|
Checks this vCard for data consistency problems or deviations from the spec. These problems will not prevent the vCard from being written to a data stream, but may prevent it from being parsed correctly by the consuming application. These problems can largely be avoided by reading the Javadocs of the property classes, or by being familiar with the vCard standard.
|
@Override public boolean isClosed(){
return getDelegate().isClosed();
}
|
Returns true if the stream is closed.
|
@Override public boolean spawnPig(World world,double x,double y,double z){
final EntityPig pig=new EntityPig(world);
pig.setPosition(x,y,z);
return world.spawnEntityInWorld(pig);
}
|
Spawn a pig at the specified position.
|
public boolean isBasic(){
return equals(basic());
}
|
Checks if this filter is a basic filter. A filter is basic, if it has no tag/likes or username-filter.
|
public ProjectComparisonEntry compareModules(TModule module,String implementationID){
return compareModules(module,implementationID,false);
}
|
Get the comparison for a module in a specific implementation specified by it's ID.
|
private int handleW(String value,DoubleMetaphoneResult result,int index){
if (contains(value,index,2,"WR")) {
result.append('R');
index+=2;
}
else {
if (index == 0 && (isVowel(charAt(value,index + 1)) || contains(value,index,2,"WH"))) {
if (isVowel(charAt(value,index + 1))) {
result.append('A','F');
}
else {
result.append('A');
}
index++;
}
else if ((index == value.length() - 1 && isVowel(charAt(value,index - 1))) || contains(value,index - 1,5,"EWSKI","EWSKY","OWSKI","OWSKY") || contains(value,0,3,"SCH")) {
result.appendAlternate('F');
index++;
}
else if (contains(value,index,4,"WICZ","WITZ")) {
result.append("TS","FX");
index+=4;
}
else {
index++;
}
}
return index;
}
|
Handles 'W' cases
|
public void createAccrualBasedJournalEntriesAndReversalsForLoan(final Office office,final String currencyCode,final Integer accountTypeToBeDebited,final Integer accountTypeToBeCredited,final Long loanProductId,final Long paymentTypeId,final Long loanId,final String transactionId,final Date transactionDate,final BigDecimal amount,final Boolean isReversal){
int accountTypeToDebitId=accountTypeToBeDebited;
int accountTypeToCreditId=accountTypeToBeCredited;
if (isReversal) {
accountTypeToDebitId=accountTypeToBeCredited;
accountTypeToCreditId=accountTypeToBeDebited;
}
createJournalEntriesForLoan(office,currencyCode,accountTypeToDebitId,accountTypeToCreditId,loanProductId,paymentTypeId,loanId,transactionId,transactionDate,amount);
}
|
Convenience method that creates a pair of related Debits and Credits for Accrual Based accounting. The target accounts for debits and credits are switched in case of a reversal
|
public ObjectName createDistributionLocator(String host,int port,String workingDirectory,String productDirectory) throws MalformedObjectNameException {
return createDistributionLocator(host,port,workingDirectory,productDirectory,getRemoteCommand());
}
|
Creates a new DistributionLocator for this system and registers an MBean for managing it. <p> If the Locator already exists, then this will simply register an MBean for it.
|
@AfterClass public static void tearDownAfterClass() throws Exception {
}
|
Method tearDownAfterClass.
|
public JSearchPanel(Visualization vis,String group,String searchGroup,String[] fields,boolean autoIndex,boolean monitorKeystrokes){
m_lock=vis;
m_fields=fields;
m_autoIndex=autoIndex;
m_monitorKeys=monitorKeystrokes;
TupleSet search=vis.getGroup(searchGroup);
if (search != null) {
if (search instanceof SearchTupleSet) {
m_searcher=(SearchTupleSet)search;
}
else {
throw new IllegalStateException("Search focus set not instance of SearchTupleSet!");
}
}
else {
m_searcher=new PrefixSearchTupleSet();
vis.addFocusGroup(searchGroup,m_searcher);
}
init(vis.getGroup(group));
}
|
Create a new JSearchPanel.
|
public static _Fields findByThriftId(int fieldId){
switch (fieldId) {
case 1:
return SESSION_IDS;
case 2:
return PACKET;
default :
return null;
}
}
|
Find the _Fields constant that matches fieldId, or null if its not found.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.