code
stringlengths 10
174k
| nl
stringlengths 3
129k
|
---|---|
private void populateCache() throws KettleException {
String carbonStorePath=CarbonProperties.getInstance().getProperty(CarbonCommonConstants.STORE_LOCATION_HDFS);
String[] dimColumnNames=columnsInfo.getDimColNames();
String[] dimColumnIds=columnsInfo.getDimensionColumnIds();
String databaseName=columnsInfo.getSchemaName();
String tableName=columnsInfo.getTableName();
CarbonTable carbonTable=CarbonMetadata.getInstance().getCarbonTable(databaseName + CarbonCommonConstants.UNDERSCORE + tableName);
CarbonTableIdentifier carbonTableIdentifier=carbonTable.getCarbonTableIdentifier();
CacheProvider cacheProvider=CacheProvider.getInstance();
Cache reverseDictionaryCache=cacheProvider.createCache(CacheType.REVERSE_DICTIONARY,carbonStorePath);
List<String> dictionaryKeys=new ArrayList<>(dimColumnNames.length);
List<DictionaryColumnUniqueIdentifier> dictionaryColumnUniqueIdentifiers=new ArrayList<>(dimColumnNames.length);
ColumnSchemaDetailsWrapper columnSchemaDetailsWrapper=columnsInfo.getColumnSchemaDetailsWrapper();
for (int i=0; i < dimColumnNames.length; i++) {
String dimColName=dimColumnNames[i].substring(tableName.length() + 1);
ColumnSchemaDetails details=columnSchemaDetailsWrapper.get(dimColumnIds[i]);
if (details.isDirectDictionary()) {
continue;
}
GenericDataType complexType=columnsInfo.getComplexTypesMap().get(dimColName);
if (complexType != null) {
List<GenericDataType> primitiveChild=new ArrayList<GenericDataType>();
complexType.getAllPrimitiveChildren(primitiveChild);
for ( GenericDataType eachPrimitive : primitiveChild) {
details=columnSchemaDetailsWrapper.get(eachPrimitive.getColumnId());
if (details.isDirectDictionary()) {
continue;
}
ColumnIdentifier columnIdentifier=new ColumnIdentifier(eachPrimitive.getColumnId(),columnsInfo.getColumnProperties(eachPrimitive.getName()),details.getColumnType());
String dimColumnName=tableName + CarbonCommonConstants.UNDERSCORE + eachPrimitive.getName();
DictionaryColumnUniqueIdentifier dictionaryColumnUniqueIdentifier=new DictionaryColumnUniqueIdentifier(carbonTableIdentifier,columnIdentifier);
dictionaryColumnUniqueIdentifiers.add(dictionaryColumnUniqueIdentifier);
dictionaryKeys.add(dimColumnName);
}
}
else {
ColumnIdentifier columnIdentifier=new ColumnIdentifier(dimColumnIds[i],columnsInfo.getColumnProperties(dimColName),details.getColumnType());
DictionaryColumnUniqueIdentifier dictionaryColumnUniqueIdentifier=new DictionaryColumnUniqueIdentifier(carbonTableIdentifier,columnIdentifier);
dictionaryColumnUniqueIdentifiers.add(dictionaryColumnUniqueIdentifier);
dictionaryKeys.add(dimColumnNames[i]);
}
}
initDictionaryCacheInfo(dictionaryKeys,dictionaryColumnUniqueIdentifiers,reverseDictionaryCache,carbonStorePath);
}
| This method will generate cache for all the global dictionaries during data loading. |
public long rsslim(){
return Long.parseLong(fields[24]);
}
| Current soft limit in bytes on the rss of the process; see the description of RLIMIT_RSS in getrlimit(2). |
public boolean isSourceFileKnown(){
return !UNKNOWN_SOURCE_FILE.equals(sourceFile);
}
| Is the source file known? |
public AttachmentEntry uploadAttachment(File file,BasePageEntry<?> parentPage,String title) throws IOException, ServiceException {
return uploadAttachment(file,parentPage.getSelfLink().getHref(),title,"");
}
| Uploads an attachment to a selected parent page. |
public static boolean isSyntheticInit(JCTree stat){
if (stat.hasTag(EXEC)) {
JCExpressionStatement exec=(JCExpressionStatement)stat;
if (exec.expr.hasTag(ASSIGN)) {
JCAssign assign=(JCAssign)exec.expr;
if (assign.lhs.hasTag(SELECT)) {
JCFieldAccess select=(JCFieldAccess)assign.lhs;
if (select.sym != null && (select.sym.flags() & SYNTHETIC) != 0) {
Name selected=name(select.selected);
if (selected != null && selected == selected.table.names._this) return true;
}
}
}
}
return false;
}
| Is statement an initializer for a synthetic field? |
@Override public void minus(int value){
this.value-=value;
}
| operation minus |
public void write(SWFActions swfactions) throws IOException {
ActionParser parser=new ActionParser(swfactions);
swfactions.start(conditions);
parser.parse(bytes);
swfactions.done();
}
| Parse the action contents and write them to the SWFActions interface |
public void initializeSections(ChunkSection... initSections){
if (isLoaded()) {
GlowServer.logger.log(Level.SEVERE,"Tried to initialize already loaded chunk (" + x + ","+ z+ ")",new Throwable());
return;
}
sections=new ChunkSection[DEPTH / SEC_DEPTH];
System.arraycopy(initSections,0,sections,0,Math.min(sections.length,initSections.length));
biomes=new byte[WIDTH * HEIGHT];
heightMap=new byte[WIDTH * HEIGHT];
for (int i=0; i < sections.length; ++i) {
if (sections[i] == null) continue;
int by=16 * i;
for (int cx=0; cx < WIDTH; ++cx) {
for (int cz=0; cz < HEIGHT; ++cz) {
for (int cy=by; cy < by + 16; ++cy) {
createEntity(cx,cy,cz,getType(cx,cz,cy));
}
}
}
}
}
| Initialize this chunk from the given sections. |
@Override public boolean equals(Object obj){
if (obj == this) {
return true;
}
if (!(obj instanceof DialPointer.Pointer)) {
return false;
}
DialPointer.Pointer that=(DialPointer.Pointer)obj;
if (this.widthRadius != that.widthRadius) {
return false;
}
if (!PaintUtilities.equal(this.fillPaint,that.fillPaint)) {
return false;
}
if (!PaintUtilities.equal(this.outlinePaint,that.outlinePaint)) {
return false;
}
return super.equals(obj);
}
| Tests this pointer for equality with an arbitrary object. |
protected void createUserDictSettings(PreferenceGroup userDictGroup){
final Activity activity=getActivity();
userDictGroup.removeAll();
final TreeSet<String> localeList=UserDictionaryList.getUserDictionaryLocalesSet(activity);
if (localeList.isEmpty()) {
userDictGroup.addPreference(createUserDictionaryPreference(null,activity));
}
else {
for ( String locale : localeList) {
userDictGroup.addPreference(createUserDictionaryPreference(locale,activity));
}
}
}
| Creates the entries that allow the user to go into the user dictionary for each locale. |
private Ref functionArgDeclaration() throws PageException {
Ref ref=impOp();
if (cfml.forwardIfCurrent(':') || cfml.forwardIfCurrent('=')) {
cfml.removeSpace();
ref=new LFunctionValue(ref,assignOp());
}
return ref;
}
| Liest einen gelableten Funktionsparamter ein <br /> EBNF:<br /> <code>assignOp [":" spaces assignOp];</code> |
private void applyFilter(){
filteredModelMap.clear();
for ( Entry<String,List<FunctionDescription>> entry : modelMap.entrySet()) {
List<FunctionDescription> newList=new LinkedList<>();
for ( FunctionDescription function : entry.getValue()) {
newList.add(function);
}
filteredModelMap.put(entry.getKey(),newList);
}
if (!getFilterNameString().isEmpty()) {
for ( Entry<String,List<FunctionDescription>> entry : filteredModelMap.entrySet()) {
if (entry.getKey().toLowerCase(Locale.ENGLISH).contains(filterNameStringLowerCase)) {
continue;
}
for (int i=entry.getValue().size() - 1; i >= 0; i--) {
FunctionDescription function=entry.getValue().get(i);
if (!function.getDisplayName().toLowerCase(Locale.ENGLISH).contains(filterNameStringLowerCase) && !function.getHelpTextName().toLowerCase(Locale.ENGLISH).contains(filterNameStringLowerCase) && !function.getFunctionNameWithParameters().toLowerCase(Locale.ENGLISH).contains(filterNameStringLowerCase)&& !function.getDescription().toLowerCase(Locale.ENGLISH).contains(filterNameStringLowerCase)) {
filteredModelMap.get(entry.getKey()).remove(i);
}
}
}
for ( String key : modelMap.keySet()) {
List<FunctionDescription> list=filteredModelMap.get(key);
if (list.isEmpty()) {
filteredModelMap.remove(key);
}
}
}
}
| Applies the current filter. |
private void fillBeforeAndAfter(View sel,int position){
final int dividerWidth=mDividerWidth;
if (!mStackFromRight) {
fillLeft(position - 1,sel.getLeft() - dividerWidth);
adjustViewsLeftOrRight();
fillRight(position + 1,sel.getRight() + dividerWidth);
}
else {
fillRight(position + 1,sel.getRight() + dividerWidth);
adjustViewsLeftOrRight();
fillLeft(position - 1,sel.getLeft() - dividerWidth);
}
}
| Once the selected view as been placed, fill up the visible area above and below it. |
@SuppressWarnings("fallthrough") protected void decodeAtom(PushbackInputStream inStream,OutputStream outStream,int rem) throws java.io.IOException {
int i;
byte a=-1, b=-1, c=-1, d=-1;
if (rem < 2) {
throw new CEFormatException("BASE64Decoder: Not enough bytes for an atom.");
}
do {
i=inStream.read();
if (i == -1) {
throw new CEStreamExhausted();
}
}
while (i == '\n' || i == '\r');
decode_buffer[0]=(byte)i;
i=readFully(inStream,decode_buffer,1,rem - 1);
if (i == -1) {
throw new CEStreamExhausted();
}
if (rem > 3 && decode_buffer[3] == '=') {
rem=3;
}
if (rem > 2 && decode_buffer[2] == '=') {
rem=2;
}
switch (rem) {
case 4:
d=pem_convert_array[decode_buffer[3] & 0xff];
case 3:
c=pem_convert_array[decode_buffer[2] & 0xff];
case 2:
b=pem_convert_array[decode_buffer[1] & 0xff];
a=pem_convert_array[decode_buffer[0] & 0xff];
break;
}
switch (rem) {
case 2:
outStream.write((byte)(((a << 2) & 0xfc) | ((b >>> 4) & 3)));
break;
case 3:
outStream.write((byte)(((a << 2) & 0xfc) | ((b >>> 4) & 3)));
outStream.write((byte)(((b << 4) & 0xf0) | ((c >>> 2) & 0xf)));
break;
case 4:
outStream.write((byte)(((a << 2) & 0xfc) | ((b >>> 4) & 3)));
outStream.write((byte)(((b << 4) & 0xf0) | ((c >>> 2) & 0xf)));
outStream.write((byte)(((c << 6) & 0xc0) | (d & 0x3f)));
break;
}
return;
}
| Decode one BASE64 atom into 1, 2, or 3 bytes of data. |
public void mousePressed(MouseEvent e){
events.clear();
if (mapDragOperationFromModifiers(e) != DnDConstants.ACTION_NONE) {
try {
motionThreshold=DragSource.getDragThreshold();
}
catch ( Exception exc) {
motionThreshold=5;
}
appendEvent(e);
}
}
| Invoked when a mouse button has been pressed on a component. |
private void testRow(){
int testRow=((NumericTable)table.getData()).getCurrentRow();
if (testRow >= ((NumericTable)table.getData()).getRowCount()) {
testRow=0;
}
table.updateRowSelection();
for (int j=0; j < inputNeurons.size(); j++) {
inputNeurons.get(j).forceSetActivation(((NumericTable)table.getData()).getLogicalValueAt(testRow,j));
}
if (network != null) {
network.update();
network.fireNeuronsUpdated(inputNeurons);
}
else {
inputNeurons.get(0).getNetwork().update();
inputNeurons.get(0).getNetwork().fireNeuronsUpdated(inputNeurons);
}
if (iterationMode) {
advanceRow();
}
}
| Test the selected row. |
private Document createDocument(String path){
return createDocument(path,null,null);
}
| Creates an HttpDocument if path starts with "http://" or "https://"; creates a FileDocument otherwise. |
boolean isExport(){
return this.export;
}
| True if visibility fix includes insertion of an export modifier |
@DELETE @Produces(MediaType.APPLICATION_JSON) @Path("/{dashboardId}") @Description("Deletes the dashboard having the given ID.") public Response deleteDashboard(@Context HttpServletRequest req,@PathParam("dashboardId") BigInteger dashboardId){
if (dashboardId == null || dashboardId.compareTo(BigInteger.ZERO) < 1) {
throw new WebApplicationException("Dashboard Id cannot be null and must be a positive non-zero number.",Status.BAD_REQUEST);
}
Dashboard dashboard=dService.findDashboardByPrimaryKey(dashboardId);
if (dashboard != null) {
validateResourceAuthorization(req,dashboard.getOwner(),getRemoteUser(req));
dService.deleteDashboard(dashboard);
return Response.status(Status.OK).build();
}
throw new WebApplicationException(Response.Status.NOT_FOUND.getReasonPhrase(),Response.Status.NOT_FOUND);
}
| Deletes the dashboard having the given ID. |
public IndexPartitionCause(){
}
| De-serialization ctor. |
public DImportKeyPairType(JFrame parent){
super(parent,Dialog.ModalityType.DOCUMENT_MODAL);
setTitle(res.getString("DImportKeyPairType.Title"));
initComponents();
}
| Creates a new DImportKeyPairType dialog. |
@Beta public static <K,V>ImmutableSortedMap<K,V> copyOf(Iterable<? extends Entry<? extends K,? extends V>> entries){
@SuppressWarnings("unchecked") Ordering<K> naturalOrder=(Ordering<K>)NATURAL_ORDER;
return copyOf(entries,naturalOrder);
}
| Returns an immutable map containing the given entries, with keys sorted by the provided comparator. <p>This method is not type-safe, as it may be called on a map with keys that are not mutually comparable. |
public static boolean assertEquals(final long a,final long b){
if (a == b) {
return true;
}
throw new ExamException(a + " != " + b);
}
| Check if two longs are equal. |
public Channel sessionConnectGenerateChannel(Session session) throws JSchException {
session.connect(sshMeta.getSshConnectionTimeoutMillis());
ChannelExec channel=(ChannelExec)session.openChannel("exec");
channel.setCommand(sshMeta.getCommandLine());
if (sshMeta.isRunAsSuperUser()) {
try {
channel.setInputStream(null,true);
OutputStream out=channel.getOutputStream();
channel.setOutputStream(System.out,true);
channel.setExtOutputStream(System.err,true);
channel.setPty(true);
channel.connect();
out.write((sshMeta.getPassword() + "\n").getBytes());
out.flush();
}
catch ( IOException e) {
logger.error("error in sessionConnectGenerateChannel for super user",e);
}
}
else {
channel.setInputStream(null);
channel.connect();
}
return channel;
}
| Session connect generate channel. |
public CButton(Icon icon){
this(null,icon);
}
| Creates a button with an icon. |
public static String createQueryString(Map<String,?> options) throws URISyntaxException {
try {
if (options.size() > 0) {
StringBuffer rc=new StringBuffer();
boolean first=true;
for ( Entry<String,?> entry : options.entrySet()) {
if (first) {
first=false;
}
else {
rc.append("&");
}
rc.append(URLEncoder.encode(entry.getKey(),"UTF-8"));
rc.append("=");
rc.append(URLEncoder.encode((String)entry.getValue(),"UTF-8"));
}
return rc.toString();
}
else {
return "";
}
}
catch ( UnsupportedEncodingException e) {
throw (URISyntaxException)new URISyntaxException(e.toString(),"Invalid encoding").initCause(e);
}
}
| Given a key / value mapping, create and return a URI formatted query string that is valid and can be appended to a URI. |
private static int unsignedByteToInt(byte b){
return b & 0xFF;
}
| Convert a signed byte to an unsigned int. |
public synchronized static boolean initSkinXMLHandler(String fileName){
udSpec=null;
if (fileName == null) {
System.out.println("ERROR: Bad skin specification file: " + "null filename!");
return false;
}
File file=new File(Configuration.skinsDir(),fileName);
if (!file.exists() || !file.isFile()) {
System.out.println("ERROR: Bad skin specification file: " + "file doesn't exist! File name: " + fileName);
return false;
}
DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
try {
DocumentBuilder builder=dbf.newDocumentBuilder();
System.out.println("Parsing " + file.getName());
Document doc=builder.parse(file);
System.out.println("Parsing finished.");
NodeList listOfComponents=doc.getElementsByTagName(UI_ELEMENT);
int totalComponents=listOfComponents.getLength();
skinSpecs=new HashMap<String,SkinSpecification>((int)(totalComponents * 1.25));
for (int comp=0; comp < totalComponents; comp++) {
Element borderList=(Element)listOfComponents.item(comp);
String name=borderList.getElementsByTagName(NAME).item(0).getTextContent();
if (name.equals(SkinSpecification.UIComponents.UnitDisplay.getComp())) {
parseUnitDisplaySkinSpec(borderList);
continue;
}
SkinSpecification skinSpec;
Element noBorderEle=(Element)borderList.getElementsByTagName(NO_BORDER).item(0);
boolean noBorder=false;
if (noBorderEle != null) {
noBorder=Boolean.parseBoolean(noBorderEle.getTextContent());
}
Element plainTag=(Element)borderList.getElementsByTagName(PLAIN).item(0);
if (plainTag == null && !noBorder) {
Element border=(Element)borderList.getElementsByTagName(BORDER).item(0);
if (border == null) {
System.err.println("Missing <" + BORDER + "> tag in element #"+ comp);
continue;
}
skinSpec=parseBorderTag(border);
}
else {
skinSpec=new SkinSpecification();
skinSpec.noBorder=noBorder;
}
if (plainTag == null) {
NodeList backgrounds=borderList.getElementsByTagName(BACKGROUND_IMAGE);
if (backgrounds != null) {
for (int bg=0; bg < backgrounds.getLength(); bg++) {
skinSpec.backgrounds.add(backgrounds.item(bg).getTextContent());
}
}
}
Element showScrollEle=(Element)borderList.getElementsByTagName(SHOW_SCROLL_BARS).item(0);
if (showScrollEle != null) {
skinSpec.showScrollBars=Boolean.parseBoolean(showScrollEle.getTextContent());
}
NodeList fontColors=borderList.getElementsByTagName(FONT_COLOR);
if (fontColors.getLength() > 0) {
skinSpec.fontColors.clear();
for (int fc=0; fc < fontColors.getLength(); fc++) {
String fontColorContent=fontColors.item(fc).getTextContent();
skinSpec.fontColors.add(Color.decode(fontColorContent));
}
}
Element tileBGEle=(Element)borderList.getElementsByTagName(TILE_BACKGROUND).item(0);
if (tileBGEle != null) {
skinSpec.tileBackground=Boolean.parseBoolean(tileBGEle.getTextContent());
}
if (SkinSpecification.UIComponents.getUIComponent(name) == null) {
System.out.println("SKIN ERROR: " + "Unable to add unrecognized UI component: " + name + "!");
}
else {
skinSpecs.put(name,skinSpec);
}
}
if (!skinSpecs.containsKey(UIComponents.DefaultUIElement.getComp()) || !skinSpecs.containsKey(UIComponents.DefaultButton.getComp())) {
System.out.println("SKIN ERROR: Bad skin specification file: " + "file doesn't specify " + UIComponents.DefaultUIElement + " or "+ UIComponents.DefaultButton+ "!");
return false;
}
}
catch ( Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
return false;
}
if (udSpec == null) {
udSpec=new UnitDisplaySkinSpecification();
}
return true;
}
| Initializes using the supplied skin file. |
public boolean isEmpty(){
return size() == 0;
}
| Is the set empty? |
public static void init(){
logger=Logger.getLogger("");
logger.getHandlers()[0].setFormatter(new BriefLogFormatter());
}
| Configures JDK logging to use this class for everything. |
@Override public void configureZone(final StendhalRPZone zone,final Map<String,String> attributes){
buildNPC(zone);
}
| Configure a zone. |
public void removeLayersFromBeanContext(List<Layer> layers){
BeanContext bc=getBeanContext();
if (bc == null || layers == null) {
return;
}
for ( Layer layer : layers) {
bc.remove(layer);
}
}
| Add layers to the BeanContext, if they want to be. Since the BeanContext is a Collection, it doesn't matter if a layer is already there because duplicates aren't allowed. |
public boolean isShowLibraryFunctions(){
return m_libraryFunctionCheckbox.isSelected();
}
| Returns whether library functions should be shown. |
@Override public boolean test(final Array params){
return c1.test(params) && c2.test(params);
}
| Tests if params satisfy the constraint. |
@Override public boolean isResponsible(Class<?> clazz){
return clazz == Date.class;
}
| The DateSerializer can handle instances of the Date class. |
private long normalizeTimestamp(long timestampMicros,long binDurationMillis){
long timeMillis=TimeUnit.MICROSECONDS.toMillis(timestampMicros);
timeMillis-=(timeMillis % binDurationMillis);
return timeMillis;
}
| This method normalizes the input timestamp at UTC time boundaries based on the bin size, effectively creating time series that are comparable to each other |
void showInputBox(String message,Predicate<String> filter,Consumer<String> resultCallback){
Text text=createMessage(message);
TextField field=new TextField();
field.setMaxWidth(Math.max(text.getLayoutBounds().getWidth(),200));
field.setFont(FXGL.getUIFactory().newFont(18));
FXGLButton btnOK=new FXGLButton("OK");
field.textProperty().addListener(null);
btnOK.setDisable(true);
btnOK.setOnAction(null);
VBox vbox=new VBox(50,text,field,btnOK);
vbox.setAlignment(Pos.CENTER);
vbox.setUserData(new Point2D(Math.max(text.getLayoutBounds().getWidth(),200),text.getLayoutBounds().getHeight() * 3 + 50 * 2));
setContent("Input",vbox);
show();
}
| Shows input box with input field and OK button. The button will stay disabled until the input passes given filter. <p> The callback function will be invoked with input field text as parameter. <p> Opening more than 1 dialog box is not allowed. |
@TargetApi(Build.VERSION_CODES.LOLLIPOP) private static boolean relaunchTask(int tabId){
if (tabId == Tab.INVALID_TAB_ID) return false;
Context context=ApplicationStatus.getApplicationContext();
ActivityManager manager=(ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
for ( AppTask task : manager.getAppTasks()) {
RecentTaskInfo info=DocumentUtils.getTaskInfoFromTask(task);
if (info == null) continue;
int id=ActivityDelegate.getTabIdFromIntent(info.baseIntent);
if (id != tabId) continue;
DocumentTabModelSelector.setPrioritizedTabId(id);
if (!moveToFront(task)) continue;
return true;
}
return false;
}
| Bring the task matching the given tab ID to the front. |
private static void copyRowStyle(FlexTable sourceTable,FlexTable targetTable,int sourceRow,int targetRow){
String rowStyle=sourceTable.getRowFormatter().getStyleName(sourceRow);
targetTable.getRowFormatter().setStyleName(targetRow,rowStyle);
}
| Copies the CSS style of a source row to a target row. |
private Object readResolve(){
if (iChronology == null) {
return new LocalDate(iLocalMillis,ISOChronology.getInstanceUTC());
}
if (DateTimeZone.UTC.equals(iChronology.getZone()) == false) {
return new LocalDate(iLocalMillis,iChronology.withUTC());
}
return this;
}
| Handle broken serialization from other tools. |
public static Lock newLock(String name){
return factory.newLock(name);
}
| Create a new Lock instance using the appropriate VM-specific concrete Lock sub-class. |
public boolean optBoolean(int index,boolean defaultValue){
try {
return this.getBoolean(index);
}
catch ( Exception e) {
return defaultValue;
}
}
| Get the optional boolean value associated with an index. It returns the defaultValue if there is no value at that index or if it is not a Boolean or the String "true" or "false" (case insensitive). |
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. |
@RequestMapping(method=RequestMethod.GET) public String displayCategories(){
return "m_startPage_def";
}
| For the standard path a page with all categories will be displayed |
public void replace(String statement) throws CannotCompileException {
thisClass.getClassFile();
ConstPool constPool=getConstPool();
int pos=currentPos;
int index=iterator.u16bitAt(pos + 1);
Javac jc=new Javac(thisClass);
ClassPool cp=thisClass.getClassPool();
CodeAttribute ca=iterator.get();
try {
CtClass[] params=new CtClass[]{cp.get(javaLangObject)};
CtClass retType=CtClass.booleanType;
int paramVar=ca.getMaxLocals();
jc.recordParams(javaLangObject,params,true,paramVar,withinStatic());
int retVar=jc.recordReturnType(retType,true);
jc.recordProceed(new ProceedForInstanceof(index));
jc.recordType(getType());
checkResultValue(retType,statement);
Bytecode bytecode=jc.getBytecode();
storeStack(params,true,paramVar,bytecode);
jc.recordLocalVariables(ca,pos);
bytecode.addConstZero(retType);
bytecode.addStore(retVar,retType);
jc.compileStmnt(statement);
bytecode.addLoad(retVar,retType);
replace0(pos,bytecode,3);
}
catch ( CompileError e) {
throw new CannotCompileException(e);
}
catch ( NotFoundException e) {
throw new CannotCompileException(e);
}
catch ( BadBytecode e) {
throw new CannotCompileException("broken method");
}
}
| Replaces the instanceof operator with the bytecode derived from the given source text. <p>$0 is available but the value is <code>null</code>. |
public static float calculateAspectRatio(float left,float top,float right,float bottom){
final float width=right - left;
final float height=bottom - top;
final float aspectRatio=width / height;
return aspectRatio;
}
| Calculates the aspect ratio given a rectangle. |
private String generateUrl(String outfit,int i){
try {
String hash=hmac(i + "_" + outfit,Configuration.getConfiguration().get("stendhal.secret"));
StringBuilder sb=new StringBuilder();
sb.append("https://stendhalgame.org/content/game/photo.php?outfit=");
sb.append(outfit);
sb.append("&i=");
sb.append(i);
sb.append("&h=");
sb.append(hash.toLowerCase(Locale.ENGLISH));
return sb.toString();
}
catch ( Exception e) {
logger.error(e,e);
return "";
}
}
| generates the images url |
@Override public void agg(Object newVal){
if (firstTime) {
aggVal=(BigDecimal)newVal;
firstTime=false;
}
else {
aggVal=aggVal.add((BigDecimal)newVal);
}
}
| This method will update the aggVal it will add new value to aggVal |
protected void engineInitVerify(PublicKey publicKey) throws InvalidKeyException {
BigInteger p, q, y;
int n1;
if (publicKey == null || !(publicKey instanceof DSAPublicKey)) {
throw new InvalidKeyException("publicKey is not an instance of DSAPublicKey");
}
DSAParams params=((DSAPublicKey)publicKey).getParams();
p=params.getP();
q=params.getQ();
y=((DSAPublicKey)publicKey).getY();
n1=p.bitLength();
if (p.compareTo(BigInteger.valueOf(1)) != 1 || n1 < 512 || n1 > 1024 || (n1 & 077) != 0) {
throw new InvalidKeyException("bad p");
}
if (q.signum() != 1 || q.bitLength() != 160) {
throw new InvalidKeyException("bad q");
}
if (y.signum() != 1) {
throw new InvalidKeyException("y <= 0");
}
dsaKey=(DSAKey)publicKey;
msgDigest.reset();
}
| Initializes this signature object with PublicKey object passed as argument to the method. |
public boolean trim(){
final int l=arraySize(size,f);
if (l >= n || size > maxFill(l,f)) return true;
try {
rehash(l);
}
catch ( OutOfMemoryError cantDoIt) {
return false;
}
return true;
}
| Rehashes the map, making the table as small as possible. <P>This method rehashes the table to the smallest size satisfying the load factor. It can be used when the set will not be changed anymore, so to optimize access speed and size. <P>If the table size is already the minimum possible, this method does nothing. |
public LogisticGrowthModel(String name,Parameter N0Parameter,Parameter growthRateParameter,Parameter shapeParameter,double alpha,Type units,boolean usingGrowthRate){
super(name);
logisticGrowth=new LogisticGrowth(units);
this.N0Parameter=N0Parameter;
addVariable(N0Parameter);
N0Parameter.addBounds(new Parameter.DefaultBounds(Double.POSITIVE_INFINITY,0.0,1));
this.growthRateParameter=growthRateParameter;
addVariable(growthRateParameter);
growthRateParameter.addBounds(new Parameter.DefaultBounds(Double.POSITIVE_INFINITY,0.0,1));
this.shapeParameter=shapeParameter;
addVariable(shapeParameter);
shapeParameter.addBounds(new Parameter.DefaultBounds(Double.POSITIVE_INFINITY,0.0,1));
this.alpha=alpha;
this.usingGrowthRate=usingGrowthRate;
setUnits(units);
}
| Construct demographic model with default settings |
public void logResults(){
if (!OracleLog.isLoggingEnabled() || (currentLogLevel > FINE_LOG_LEVEL)) return;
boolean chatty_logging=(currentLogLevel < FINE_LOG_LEVEL);
StringBuilder sb=new StringBuilder();
sb.append("\n\n");
if (chatty_logging || (dbConnectNanos > 0L)) logMsgTime(sb,"JDBC connect in: ",dbConnectNanos);
if (chatty_logging || (dbTransactionNanos > 0L)) logMsgTime(sb,"JDBC commit/rollback in: ",dbTransactionNanos);
if (chatty_logging || (ioReadBytes > 0) || (ioReadNanos > 0L)) logMsgCountTime(sb,"IO read: ",ioReadBytes,ioReadNanos);
if (chatty_logging || (ioWrites > 0)) {
sb.append("IO writes: ");
sb.append(Integer.toString(ioWrites));
sb.append(" of ");
sb.append(Integer.toString(ioWriteBytes));
sb.append(" bytes in ");
sb.append(nanosToString(ioWriteNanos));
sb.append("\n");
}
if ((chatty_logging) || (checksums > 0)) logMsgCountTime(sb,"Checksums: ",checksums,checksumNanos);
if (chatty_logging || (dbDDLs > 0)) logMsgCountTime(sb,"DDLS: ",dbDDLs,dbDDLNanos);
if (chatty_logging || (dbGUIDs > 0)) logMsgCountTime(sb,"GUID fetches: ",dbGUIDs,dbGUIDNanos);
if (chatty_logging || (dbTimestampReads > 0)) logMsgCountTime(sb,"SYSTIMESTAMP reads: ",dbTimestampReads,dbTimestampNanons);
if (chatty_logging || (dbSequenceBatch > 0)) logMsgCountTime(sb,"Sequence batch fetches: ",dbSequenceBatch,dbSequenceBatchNanos);
if (chatty_logging || (dbCursorReads > 0)) {
logMsgCount(sb,"Cursor reads: ",dbCursorReads);
}
if (chatty_logging || (dbLobReads > 0) || (dbLobWrites > 0)) {
logMsgCountTime(sb,"LOB reads: ",dbLobReads,dbLobReadNanos);
logMsgCountTime(sb,"LOB writes: ",dbLobWrites,dbLobWriteNanos);
}
if (chatty_logging || (dbProcCalls > 0)) logMsgCountTime(sb,"PLSQL calls: ",dbProcCalls,dbProcCallNanos);
if ((chatty_logging) || (dbDocReadRoundTrips > 0) || (dbDocWriteRoundTrips > 0)) {
logMsgCountTime(sb,"Doc read round-trips: ",dbDocReadRoundTrips,dbDocReadNanos);
logMsgCountTime(sb,"Doc write round-trips: ",dbDocWriteRoundTrips,dbDocWriteNanos);
}
if (encounteredNegativeTimeDiff) {
sb.append("Warning: timings might be off, encountered negative time diff!!!\n");
}
long elapsed=getTime() - total_time;
logMsgTime(sb,"\nElapsed total: ",elapsed);
log.fine(sb.toString());
}
| Print the metrics to the log file |
public Set<Key> keySet(int access){
Set<Key> set=new LinkedHashSet<Key>();
Map.Entry<Key,Member> entry;
Iterator<Entry<Key,Member>> it=_data.entrySet().iterator();
while (it.hasNext()) {
entry=it.next();
if (entry.getValue().getAccess() <= access) set.add(entry.getKey());
}
return set;
}
| list of keys |
public static Map<String,Object> cancelOrderItem(DispatchContext ctx,Map<String,? extends Object> context){
LocalDispatcher dispatcher=ctx.getDispatcher();
Delegator delegator=ctx.getDelegator();
Locale locale=(Locale)context.get("locale");
GenericValue userLogin=(GenericValue)context.get("userLogin");
BigDecimal cancelQuantity=(BigDecimal)context.get("cancelQuantity");
String orderId=(String)context.get("orderId");
String orderItemSeqId=(String)context.get("orderItemSeqId");
String shipGroupSeqId=(String)context.get("shipGroupSeqId");
Map<String,String> itemReasonMap=UtilGenerics.checkMap(context.get("itemReasonMap"));
Map<String,String> itemCommentMap=UtilGenerics.checkMap(context.get("itemCommentMap"));
String itemMsgInfo=orderId + " / " + orderItemSeqId+ " / "+ shipGroupSeqId;
Security security=ctx.getSecurity();
boolean hasPermission=OrderServices.hasPermission(orderId,userLogin,"UPDATE",security,delegator);
if (!hasPermission) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource_error,"OrderYouDoNotHavePermissionToChangeThisOrdersStatus",locale));
}
Map<String,String> fields=UtilMisc.<String,String>toMap("orderId",orderId);
if (orderItemSeqId != null) {
fields.put("orderItemSeqId",orderItemSeqId);
}
if (shipGroupSeqId != null) {
fields.put("shipGroupSeqId",shipGroupSeqId);
}
List<GenericValue> orderItemShipGroupAssocs=null;
try {
orderItemShipGroupAssocs=EntityQuery.use(delegator).from("OrderItemShipGroupAssoc").where(fields).queryList();
}
catch ( GenericEntityException e) {
Debug.logError(e,module);
return ServiceUtil.returnError(UtilProperties.getMessage(resource_error,"OrderErrorCannotGetOrderItemAssocEntity",UtilMisc.toMap("itemMsgInfo",itemMsgInfo),locale));
}
if (orderItemShipGroupAssocs != null) {
for ( GenericValue orderItemShipGroupAssoc : orderItemShipGroupAssocs) {
GenericValue orderItem=null;
try {
orderItem=orderItemShipGroupAssoc.getRelatedOne("OrderItem",false);
}
catch ( GenericEntityException e) {
Debug.logError(e,module);
}
if (orderItem == null) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource_error,"OrderErrorCannotCancelItemItemNotFound",UtilMisc.toMap("itemMsgInfo",itemMsgInfo),locale));
}
BigDecimal aisgaCancelQuantity=orderItemShipGroupAssoc.getBigDecimal("cancelQuantity");
if (aisgaCancelQuantity == null) {
aisgaCancelQuantity=BigDecimal.ZERO;
}
BigDecimal availableQuantity=orderItemShipGroupAssoc.getBigDecimal("quantity").subtract(aisgaCancelQuantity);
BigDecimal itemCancelQuantity=orderItem.getBigDecimal("cancelQuantity");
if (itemCancelQuantity == null) {
itemCancelQuantity=BigDecimal.ZERO;
}
BigDecimal itemQuantity=orderItem.getBigDecimal("quantity").subtract(itemCancelQuantity);
if (availableQuantity == null) availableQuantity=BigDecimal.ZERO;
if (itemQuantity == null) itemQuantity=BigDecimal.ZERO;
BigDecimal thisCancelQty=null;
if (cancelQuantity != null) {
thisCancelQty=cancelQuantity;
}
else {
thisCancelQty=availableQuantity;
}
if (availableQuantity.compareTo(thisCancelQty) >= 0) {
if (availableQuantity.compareTo(BigDecimal.ZERO) == 0) {
continue;
}
orderItem.set("cancelQuantity",itemCancelQuantity.add(thisCancelQty));
orderItemShipGroupAssoc.set("cancelQuantity",aisgaCancelQuantity.add(thisCancelQty));
try {
List<GenericValue> toStore=UtilMisc.toList(orderItem,orderItemShipGroupAssoc);
delegator.storeAll(toStore);
}
catch ( GenericEntityException e) {
Debug.logError(e,module);
return ServiceUtil.returnError(UtilProperties.getMessage(resource_error,"OrderUnableToSetCancelQuantity",UtilMisc.toMap("itemMsgInfo",itemMsgInfo),locale));
}
Map<String,Object> localCtx=UtilMisc.toMap("userLogin",userLogin,"orderId",orderItem.getString("orderId"),"orderItemSeqId",orderItem.getString("orderItemSeqId"),"shipGroupSeqId",orderItemShipGroupAssoc.getString("shipGroupSeqId"));
try {
dispatcher.runSync("deleteOrderItemShipGroupAssoc",localCtx);
}
catch ( GenericServiceException e) {
Debug.logError(e,module);
return ServiceUtil.returnError(e.getMessage());
}
if (!"Y".equals(orderItem.getString("isPromo"))) {
String reasonEnumId=null;
String changeComments=null;
if (UtilValidate.isNotEmpty(itemReasonMap)) {
reasonEnumId=itemReasonMap.get(orderItem.getString("orderItemSeqId"));
}
if (UtilValidate.isNotEmpty(itemCommentMap)) {
changeComments=itemCommentMap.get(orderItem.getString("orderItemSeqId"));
}
Map<String,Object> serviceCtx=FastMap.newInstance();
serviceCtx.put("orderId",orderItem.getString("orderId"));
serviceCtx.put("orderItemSeqId",orderItem.getString("orderItemSeqId"));
serviceCtx.put("cancelQuantity",thisCancelQty);
serviceCtx.put("changeTypeEnumId","ODR_ITM_CANCEL");
serviceCtx.put("reasonEnumId",reasonEnumId);
serviceCtx.put("changeComments",changeComments);
serviceCtx.put("userLogin",userLogin);
Map<String,Object> resp=null;
try {
resp=dispatcher.runSync("createOrderItemChange",serviceCtx);
}
catch ( GenericServiceException e) {
Debug.logError(e,module);
return ServiceUtil.returnError(e.getMessage());
}
if (ServiceUtil.isError(resp)) {
return ServiceUtil.returnError((String)resp.get(ModelService.ERROR_MESSAGE));
}
}
try {
BigDecimal quantity=thisCancelQty.setScale(1,orderRounding);
String cancelledItemToOrder=UtilProperties.getMessage(resource,"OrderCancelledItemToOrder",locale);
dispatcher.runSync("createOrderNote",UtilMisc.<String,Object>toMap("orderId",orderId,"note",cancelledItemToOrder + orderItem.getString("productId") + " ("+ quantity+ ")","internalNote","Y","userLogin",userLogin));
}
catch ( GenericServiceException e) {
Debug.logError(e,module);
}
if (thisCancelQty.compareTo(itemQuantity) >= 0) {
Map<String,Object> statusCtx=UtilMisc.<String,Object>toMap("orderId",orderId,"orderItemSeqId",orderItem.getString("orderItemSeqId"),"statusId","ITEM_CANCELLED","userLogin",userLogin);
try {
dispatcher.runSyncIgnore("changeOrderItemStatus",statusCtx);
}
catch ( GenericServiceException e) {
Debug.logError(e,module);
return ServiceUtil.returnError(UtilProperties.getMessage(resource_error,"OrderUnableToCancelOrderLine",UtilMisc.toMap("itemMsgInfo",itemMsgInfo),locale));
}
}
else {
Map<String,Object> invCtx=UtilMisc.<String,Object>toMap("orderId",orderId,"orderItemSeqId",orderItem.getString("orderItemSeqId"),"shipGroupSeqId",shipGroupSeqId,"cancelQuantity",thisCancelQty,"userLogin",userLogin);
try {
dispatcher.runSyncIgnore("cancelOrderItemInvResQty",invCtx);
}
catch ( GenericServiceException e) {
Debug.logError(e,module);
return ServiceUtil.returnError(UtilProperties.getMessage(resource_error,"OrderUnableToUpdateInventoryReservations",UtilMisc.toMap("itemMsgInfo",itemMsgInfo),locale));
}
}
}
else {
return ServiceUtil.returnError(UtilProperties.getMessage(resource_error,"OrderInvalidCancelQuantityCannotCancel",UtilMisc.toMap("thisCancelQty",thisCancelQty),locale));
}
}
}
else {
return ServiceUtil.returnError(UtilProperties.getMessage(resource_error,"OrderErrorCannotCancelItemItemNotFound",UtilMisc.toMap("itemMsgInfo",itemMsgInfo),locale));
}
return ServiceUtil.returnSuccess();
}
| Service to cancel an order item quantity |
@Check public void checkInterfaceDeclaration(N4InterfaceDeclaration n4InterfaceDecl){
holdsNoKeywordInsteadOfComma(n4InterfaceDecl);
ICompositeNode node=NodeModelUtils.findActualNodeFor(n4InterfaceDecl);
ILeafNode keywordNode;
keywordNode=findLeafWithKeyword(n4InterfaceDecl,"{",node,"implements",false);
if (keywordNode != null) {
TInterface tinterface=n4InterfaceDecl.getDefinedTypeAsInterface();
if (tinterface == null) {
return;
}
if (tinterface.getSuperInterfaceRefs().isEmpty()) {
return;
}
if (tinterface.getSuperInterfaceRefs().stream().allMatch(null)) {
List<? extends IdentifiableElement> interfaces=tinterface.getSuperInterfaceRefs().stream().flatMap(null).collect(Collectors.toList());
String message=getMessageForSYN_KW_EXTENDS_IMPLEMENTS_MIXED_UP(validatorMessageHelper.description(tinterface),"implement","interface" + (interfaces.size() > 1 ? "s" : "") + validatorMessageHelper.names(interfaces),"extends");
addIssue(message,n4InterfaceDecl,keywordNode.getTotalOffset(),keywordNode.getLength(),SYN_KW_EXTENDS_IMPLEMENTS_MIXED_UP);
}
}
}
| Checks that no "with" or "role" is used and that list of implemented interfaces is separated with commas and not with keywords. These checks (with some warnings created instead of errors) should help the transition from roles to interfaces. However, they may be useful later on as well, e.g., if an interface is manually refactored into a class or vice versa. <p> Note that "with" is used in Dart for roles, so maybe it is useful to have a user-friendly message instead of a parser error. <p> "role" will be removed in grammar. |
@Override protected Size2D arrangeRR(Graphics2D g2,Range widthRange,Range heightRange){
g2.setFont(getFont());
FontMetrics fm=g2.getFontMetrics(getFont());
Rectangle2D bounds=TextUtilities.getTextBounds(getText(),g2,fm);
if (bounds.getWidth() <= widthRange.getUpperBound() && bounds.getHeight() <= heightRange.getUpperBound()) {
return new Size2D(bounds.getWidth(),bounds.getHeight());
}
else {
return new Size2D(0.0,0.0);
}
}
| Returns the content size for the title. |
private void removeListeners(){
m_debugger.removeListener(m_debuggerListener);
m_debugger.getProcessManager().removeListener(m_processListener);
}
| Removes all attached listeners. |
@Override public List<E> lowerHalf(){
long a=0;
for ( E entry : this) a+=get(entry);
a=a / this.size();
ArrayList<E> list=new ArrayList<E>();
for ( E entry : this) if (get(entry) < a) list.add(entry);
return list;
}
| divide the map into two halve parts using the count of the entries |
private double computeFastPathMinProbability(FixedNode scopeStart){
ArrayList<FixedNode> pathBeginNodes=new ArrayList<>();
pathBeginNodes.add(scopeStart);
double minPathProbability=nodeProbabilities.applyAsDouble(scopeStart);
boolean isLoopScope=scopeStart instanceof LoopBeginNode;
do {
Node current=pathBeginNodes.remove(pathBeginNodes.size() - 1);
do {
if (isLoopScope && current instanceof LoopExitNode && ((LoopBeginNode)scopeStart).loopExits().contains((LoopExitNode)current)) {
return minPathProbability;
}
else if (current instanceof LoopBeginNode && current != scopeStart) {
current=getMaxProbabilityLoopExit((LoopBeginNode)current,pathBeginNodes);
minPathProbability=getMinPathProbability((FixedNode)current,minPathProbability);
}
else if (current instanceof ControlSplitNode) {
current=getMaxProbabilitySux((ControlSplitNode)current,pathBeginNodes);
minPathProbability=getMinPathProbability((FixedNode)current,minPathProbability);
}
else {
assert current.successors().count() <= 1;
current=current.successors().first();
}
}
while (current != null);
}
while (!pathBeginNodes.isEmpty());
return minPathProbability;
}
| Computes the minimum probability along the most probable path within the scope. During iteration, the method returns immediately once a loop exit is discovered. |
public static <T>T narrow(Object narrowFrom,Class<T> narrowTo){
ensureAvailable();
return proxy.narrow(narrowFrom,narrowTo);
}
| Checks to ensure that an object of a remote or abstract interface type can be cast to a desired type. |
public static void render(Node node,Namespaces ns,RenderContext rc){
render(node,ns,rc,false);
}
| Serializes the given DOM node to HTML or XML. |
public static GaplessInfo createFromXingHeaderValue(int value){
int encoderDelay=value >> 12;
int encoderPadding=value & 0x0FFF;
return encoderDelay == 0 && encoderPadding == 0 ? null : new GaplessInfo(encoderDelay,encoderPadding);
}
| Parses gapless playback information associated with an MP3 Xing header. |
public static void loop(Listener listener,final List<HostAddress> addresses,SearchFilter searchFilter) throws QueryException {
MasterProtocol protocol;
ArrayDeque<HostAddress> loopAddresses=new ArrayDeque<>((!addresses.isEmpty()) ? addresses : listener.getBlacklistKeys());
if (loopAddresses.isEmpty()) {
loopAddresses.addAll(listener.getUrlParser().getHostAddresses());
}
int maxConnectionTry=listener.getRetriesAllDown();
QueryException lastQueryException=null;
while (!loopAddresses.isEmpty() || (!searchFilter.isFailoverLoop() && maxConnectionTry > 0)) {
protocol=getNewProtocol(listener.getProxy(),listener.getUrlParser());
if (listener.isExplicitClosed()) {
return;
}
maxConnectionTry--;
try {
HostAddress host=loopAddresses.pollFirst();
if (host == null) {
loopAddresses.addAll(listener.getUrlParser().getHostAddresses());
host=loopAddresses.pollFirst();
}
protocol.setHostAddress(host);
protocol.connect();
if (listener.isExplicitClosed()) {
protocol.close();
return;
}
listener.removeFromBlacklist(protocol.getHostAddress());
listener.foundActiveMaster(protocol);
return;
}
catch ( QueryException e) {
listener.addToBlacklist(protocol.getHostAddress());
lastQueryException=e;
}
if (loopAddresses.isEmpty() && !searchFilter.isFailoverLoop() && maxConnectionTry > 0) {
loopAddresses=new ArrayDeque<>(listener.getBlacklistKeys());
}
}
if (lastQueryException != null) {
throw new QueryException("No active connection found for master : " + lastQueryException.getMessage(),lastQueryException.getErrorCode(),lastQueryException.getSqlState(),lastQueryException);
}
throw new QueryException("No active connection found for master");
}
| loop until found the failed connection. |
public void test_encode_decode_randomBits_stress(){
final Random r=new Random();
for (int i=0; i < 10000000; i++) {
final int nbits=r.nextInt(32);
final int pid=r.nextInt();
final int ctr=r.nextInt();
if (pid == 0 && ctr == 0) {
continue;
}
final TermIdEncoder encoder=new TermIdEncoder(nbits);
doEncodeDecodeTest(encoder,pid,ctr);
}
}
| Stress test using an encoder with a random number of bits reversed and rotated into the high bits of the long value and random values for the partition identifier and the local counter. |
public FirstInnerOperatorCondition(Class[] willGet,boolean allowEmptyChains){
this.willGet=willGet;
this.allowEmptyChains=allowEmptyChains;
}
| Creates an inner operator condition. The first operator in the chain gets the input of the operator chain and additionally the given classes <code>willGet</code>. Each operator must be able to handle the output of the predecessor. The last operator must provide all classes in the given <code>mustDeliver</code> class array. |
public boolean isProxied(){
return (!(null == proxyHostName || 0 >= proxyPortNumber));
}
| Returns <tt>true</tt> if the connection is established via a proxy, <tt>false</tt> otherwise. |
protected SurfaceData initAcceleratedSurface(){
return null;
}
| Returns null to indicate failure in creating the accelerated surface. Note that this method should not ever be called since creation of accelerated surfaces should be preceded by calls to the above isAccelerationEnabled() method. But we need to override this method since it is abstract in our parent class. |
String formatNumberToPlainText(TemplateNumberModel number,Expression exp,boolean useTempModelExc) throws TemplateException {
return formatNumberToPlainText(number,getTemplateNumberFormat(exp,useTempModelExc),exp,useTempModelExc);
}
| Format number with the default number format. |
public void add(final Number operand){
this.value+=operand.byteValue();
}
| Adds a value to the value of this instance. |
@Override public Adapter createAdapter(Notifier target){
return modelSwitch.doSwitch((EObject)target);
}
| Creates an adapter for the <code>target</code>. <!-- begin-user-doc --> <!-- end-user-doc --> |
public Component add(Action action){
Component c=((TaskPaneGroupUI)ui).createAction(action);
add(c);
return c;
}
| Adds an action to this <code>JTaskPaneGroup</code>. Returns a component built from the action. The returned component has been added to the <code>JTaskPaneGroup</code>. |
public void printReport(PrintWriter out) throws AdeException {
out.println("% msg-id1" + DELIM + "msg-internal-id"+ DELIM+ "msg-id2"+ DELIM+ "msg-internal-id2"+ DELIM+ "information");
final DbDictionary dictionary=AdeInternal.getAdeImpl().getDataStore().getAdeDictionaries().getMessageIdDictionary();
int msgId1, msgId2;
String msgStr1, msgStr2;
for (int i=0; i < mCoOccurrencesAndMiMatrix.getRowNum(); i++) {
for (int j=0; j <= i; j++) {
msgId1=m_msgIndices2msgIdMap[i];
msgId2=m_msgIndices2msgIdMap[j];
msgStr1=dictionary.getWordById(msgId1);
msgStr2=dictionary.getWordById(msgId2);
out.println(msgStr1 + DELIM + msgId1+ DELIM+ msgStr2+ DELIM+ msgId2+ DELIM+ mCoOccurrencesAndMiMatrix.get(i,j));
}
}
}
| Prints the MI matrix to a given output stream. Report contains only pair that (both) passed the threshold. This method may only be called after eof() and before compact() Note: this method outputs a different output than it's previous versions. |
public CoapResource(String name){
this(name,true);
}
| Constructs a new resource with the specified name. |
@Inline @Uninterruptible public static void scanObject(int code,int id,Object object,TransitiveClosure trace){
scanObject(code,id,object,trace,SpecializedScanMethod.ENABLED);
}
| Hand-inlined scanning of objects. The cases of the conditional are ordered in descending frequency of patterns. This entry point falls back to specialized scanning if it is enabled. |
@ApiOperation(value="Load a configuration file to the single engine") @RequestMapping(value="engine/install",method=RequestMethod.POST) @ResponseStatus(HttpStatus.NO_CONTENT) @ResponseBody public final void postInstall(@RequestParam MultipartFile file){
try {
Properties properties=new Properties();
properties.load(file.getInputStream());
getSymmetricEngineHolder().install(properties);
}
catch ( RuntimeException ex) {
throw ex;
}
catch ( Exception ex) {
throw new RuntimeException(ex);
}
}
| Installs and starts a new node |
public JSONObject(JSONTokener x) throws JSONException {
this();
char c;
String key;
if (x.nextClean() != '{') {
throw x.syntaxError("A JSONObject text must begin with '{'");
}
for (; ; ) {
c=x.nextClean();
switch (c) {
case 0:
throw x.syntaxError("A JSONObject text must end with '}'");
case '}':
return;
default :
x.back();
key=x.nextValue().toString();
}
c=x.nextClean();
if (c != ':') {
throw x.syntaxError("Expected a ':' after a key");
}
this.putOnce(key,x.nextValue());
switch (x.nextClean()) {
case ';':
case ',':
if (x.nextClean() == '}') {
return;
}
x.back();
break;
case '}':
return;
default :
throw x.syntaxError("Expected a ',' or '}'");
}
}
}
| Construct a JSONObject from a JSONTokener. |
public void loadMetaData(){
loadMetaData(null,null);
}
| find out the metadata for this connection |
private void refreshTasks(){
for ( Task<T> task : tasks.getTasks()) {
task.refresh();
}
}
| Refreshes all tasks. |
public View build(){
View view=new View(subst);
while (true) {
View simpler=view.simplify(requestedVars);
if (simpler.map.size() == view.map.size()) {
return simpler;
}
view=simpler;
}
}
| Builds a view with variables that only appear once out of all substitutions replaced with their mapping, and their mapping removed. Also, removes variables from the substitution mapping that are not used. |
public synchronized StringBuffer append(char ch){
append0(ch);
return this;
}
| Adds the specified character to the end of this buffer. |
public void configure(){
XNetTrafficController packets=new XNetPacketizer(new LenzCommandStation());
packets.connectPort(this);
this.getSystemConnectionMemo().setXNetTrafficController(packets);
new XNetInitializationManager(this.getSystemConnectionMemo());
}
| set up all of the other objects to operate with a LI101 connected to this port |
public StripedLockIntObjectConcurrentHashMap(int initialCapacity,float loadFactor){
int cap=getInitCap(initialCapacity,loadFactor);
setTable(new IntHashEntry[cap]);
}
| Creates a new, empty map with the specified initial capacity, load factor, and concurrency level. |
@DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2014-09-03 15:00:08.148 -0400",hash_original_method="C8AEE2334DE35BDFE5D79AEDA5278F3C",hash_generated_method="BDB2785D6763AFBD54AB81AD10712999") public static synchronized int insertProviderAt(Provider provider,int position){
int size=providers.size();
if ((position < 1) || (position > size)) {
position=size + 1;
}
providers.add(position - 1,provider);
providersNames.put(provider.getName(),provider);
setNeedRefresh();
return position;
}
| Inserts a provider at a specified 1-based position. |
public void back() throws JSONException {
if (this.usePrevious || this.index <= 0) {
throw new JSONException("Stepping back two steps is not supported");
}
this.index-=1;
this.character-=1;
this.usePrevious=true;
this.eof=false;
}
| Back up one character. This provides a sort of lookahead capability, so that you can test for a digit or letter before attempting to parse the next number or identifier. |
public static String formatAddressType(String address){
if (InetAddressUtils.isIPv6Address(address)) {
return "IN IP6 ".concat(address);
}
return "IN IP4 ".concat(address);
}
| Format "IN IP" attribute (4 or 6) |
public ActionForward execute(ActionMapping mapping,ActionForm form,HttpServletRequest request,HttpServletResponse response) throws Exception {
EditRoomPrefForm editRoomPrefForm=(EditRoomPrefForm)form;
MessageResources rsc=getResources(request);
String doit=editRoomPrefForm.getDoit();
if (doit != null && doit.equals(rsc.getMessage("button.returnToRoomDetail"))) {
response.sendRedirect("roomDetail.do?id=" + editRoomPrefForm.getId());
return null;
}
if (doit != null && doit.equals(rsc.getMessage("button.update"))) {
ActionMessages errors=new ActionMessages();
errors=editRoomPrefForm.validate(mapping,request);
if (errors != null && errors.size() != 0) {
saveErrors(request,errors);
}
else {
doUpdate(editRoomPrefForm,request);
return mapping.findForward("showRoomDetail");
}
}
Long id=Long.valueOf(request.getParameter("id"));
LocationDAO ldao=new LocationDAO();
Location location=ldao.get(id);
if (location instanceof Room) {
Room r=(Room)location;
editRoomPrefForm.setName(r.getLabel());
}
else if (location instanceof NonUniversityLocation) {
NonUniversityLocation nonUnivLocation=(NonUniversityLocation)location;
editRoomPrefForm.setName(nonUnivLocation.getName());
}
else {
ActionMessages errors=new ActionMessages();
errors.add("editRoomGroup",new ActionMessage("errors.lookup.notFound","Room Group"));
saveErrors(request,errors);
}
sessionContext.checkPermission(location,Right.RoomEditPreference);
TreeSet<Department> departments=Department.getUserDepartments(sessionContext.getUser());
TreeSet<Department> availableDepts=new TreeSet<Department>();
for ( RoomDept rd : location.getRoomDepts()) {
if (departments.contains(rd.getDepartment())) availableDepts.add(rd.getDepartment());
}
editRoomPrefForm.setDepts(new ArrayList<Department>(availableDepts));
ArrayList depts=new ArrayList();
ArrayList selectedPrefs=new ArrayList();
for ( Department dept : availableDepts) {
RoomPref roomPref=location.getRoomPreference(dept);
if (roomPref != null) {
selectedPrefs.add(roomPref.getPrefLevel().getUniqueId().toString());
}
else {
selectedPrefs.add(PreferenceLevel.PREF_LEVEL_NEUTRAL);
}
depts.add(new LabelValueBean(dept.getDeptCode() + "-" + dept.getAbbreviation(),dept.getDeptCode()));
}
editRoomPrefForm.setRoomPrefLevels(selectedPrefs);
request.setAttribute(Department.DEPT_ATTR_NAME,depts);
if (departments.size() == 1) {
editRoomPrefForm.setDeptCode(departments.first().getDeptCode());
}
else if (sessionContext.getAttribute(SessionAttribute.DepartmentCodeRoom) != null) {
editRoomPrefForm.setDeptCode((String)sessionContext.getAttribute(SessionAttribute.DepartmentCodeRoom));
}
Vector<PreferenceLevel> prefs=new Vector<PreferenceLevel>();
for ( PreferenceLevel pref : PreferenceLevel.getPreferenceLevelList()) {
if (!pref.getPrefProlog().equalsIgnoreCase(PreferenceLevel.sRequired)) prefs.addElement(pref);
}
request.setAttribute(PreferenceLevel.PREF_LEVEL_ATTR_NAME,prefs);
return mapping.findForward("showEditRoomPref");
}
| Method execute |
@DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 12:35:20.799 -0500",hash_original_method="A776EE9CD94492AC9830F6D90123EF80",hash_generated_method="4AF9EA9654FEF9F99B4CC125624506F1") public void launchQuerySearch(){
launchQuerySearch(KeyEvent.KEYCODE_UNKNOWN,null);
}
| Launch a search for the text in the query text field. |
public Base64OutputStream(OutputStream out,int flags,boolean encode){
super(out);
this.flags=flags;
if (encode) {
coder=new Base64.Encoder(flags,null);
}
else {
coder=new Base64.Decoder(flags,null);
}
}
| Performs Base64 encoding or decoding on the data written to the stream, writing the encoded/decoded data to another OutputStream. |
static <T>List<T> cast(Iterable<T> iterable){
return (List<T>)iterable;
}
| Used to avoid http://bugs.sun.com/view_bug.do?bug_id=6558557 |
public PeriodAxis(String label,RegularTimePeriod first,RegularTimePeriod last,TimeZone timeZone){
this(label,first,last,timeZone,Locale.getDefault());
}
| Creates a new axis. |
public ItemCollectionRequestBuilder(final String requestUrl,final IOneDriveClient client,final List<Option> options){
super(requestUrl,client,options);
}
| The request builder for this collection of Item |
public Industry(int id,String name,List<Industry> segments){
this.id=id;
this.name=name;
this.segments=segments;
}
| Construct an industry with it's list of segments. |
protected Filter cursorHrefToFilter(Element cursorElement,ParsedURL purl,Point2D hotSpot){
AffineRable8Bit f=null;
String uriStr=purl.toString();
Dimension cursorSize=null;
DocumentLoader loader=ctx.getDocumentLoader();
SVGDocument svgDoc=(SVGDocument)cursorElement.getOwnerDocument();
URIResolver resolver=ctx.createURIResolver(svgDoc,loader);
try {
Element rootElement=null;
Node n=resolver.getNode(uriStr,cursorElement);
if (n.getNodeType() == Node.DOCUMENT_NODE) {
SVGDocument doc=(SVGDocument)n;
ctx.initializeDocument(doc);
rootElement=doc.getRootElement();
}
else {
throw new BridgeException(ctx,cursorElement,ERR_URI_IMAGE_INVALID,new Object[]{uriStr});
}
GraphicsNode node=ctx.getGVTBuilder().build(ctx,rootElement);
float width=DEFAULT_PREFERRED_WIDTH;
float height=DEFAULT_PREFERRED_HEIGHT;
UnitProcessor.Context uctx=UnitProcessor.createContext(ctx,rootElement);
String s=rootElement.getAttribute(SVG_WIDTH_ATTRIBUTE);
if (s.length() != 0) {
width=UnitProcessor.svgHorizontalLengthToUserSpace(s,SVG_WIDTH_ATTRIBUTE,uctx);
}
s=rootElement.getAttribute(SVG_HEIGHT_ATTRIBUTE);
if (s.length() != 0) {
height=UnitProcessor.svgVerticalLengthToUserSpace(s,SVG_HEIGHT_ATTRIBUTE,uctx);
}
cursorSize=Toolkit.getDefaultToolkit().getBestCursorSize(Math.round(width),Math.round(height));
AffineTransform at=ViewBox.getPreserveAspectRatioTransform(rootElement,cursorSize.width,cursorSize.height,ctx);
Filter filter=node.getGraphicsNodeRable(true);
f=new AffineRable8Bit(filter,at);
}
catch ( BridgeException ex) {
throw ex;
}
catch ( SecurityException ex) {
throw new BridgeException(ctx,cursorElement,ex,ERR_URI_UNSECURE,new Object[]{uriStr});
}
catch ( Exception ex) {
}
if (f == null) {
ImageTagRegistry reg=ImageTagRegistry.getRegistry();
Filter filter=reg.readURL(purl);
if (filter == null) {
return null;
}
if (BrokenLinkProvider.hasBrokenLinkProperty(filter)) {
return null;
}
Rectangle preferredSize=filter.getBounds2D().getBounds();
cursorSize=Toolkit.getDefaultToolkit().getBestCursorSize(preferredSize.width,preferredSize.height);
if (preferredSize != null && preferredSize.width > 0 && preferredSize.height > 0) {
AffineTransform at=new AffineTransform();
if (preferredSize.width > cursorSize.width || preferredSize.height > cursorSize.height) {
at=ViewBox.getPreserveAspectRatioTransform(new float[]{0,0,preferredSize.width,preferredSize.height},SVGPreserveAspectRatio.SVG_PRESERVEASPECTRATIO_XMINYMIN,true,cursorSize.width,cursorSize.height);
}
f=new AffineRable8Bit(filter,at);
}
else {
return null;
}
}
AffineTransform at=f.getAffine();
at.transform(hotSpot,hotSpot);
Rectangle cursorViewport=new Rectangle(0,0,cursorSize.width,cursorSize.height);
PadRable8Bit cursorImage=new PadRable8Bit(f,cursorViewport,PadMode.ZERO_PAD);
return cursorImage;
}
| Converts the input ParsedURL into a Filter and transforms the input hotSpot point (in image space) to cursor space |
public void addExceptionDates(ExceptionDates exceptionDates){
addProperty(exceptionDates);
}
| Adds a list of exceptions to the timezone observance. Note that this property can contain multiple dates. |
public void write(int c) throws IOException {
m_os.write(c);
}
| Write a single character. The character to be written is contained in the 16 low-order bits of the given integer value; the 16 high-order bits are ignored. <p> Subclasses that intend to support efficient single-character output should override this method. |
public static JCTree referencedStatement(JCLabeledStatement tree){
JCTree t=tree;
do t=((JCLabeledStatement)t).body;
while (t.hasTag(LABELLED));
switch (t.getTag()) {
case DOLOOP:
case WHILELOOP:
case FORLOOP:
case FOREACHLOOP:
case SWITCH:
return t;
default :
return tree;
}
}
| Return the statement referenced by a label. If the label refers to a loop or switch, return that switch otherwise return the labelled statement itself |
public static String sanitizeJsonString(String value){
if (value == null) {
return null;
}
value=sanitize(value);
return value;
}
| The sanitizer fixes missing punctuation, end quotes, and mismatched or missing close brackets. If an input contains only white-space then the valid JSON string null is substituted. |
public RhythmGroup addOverlay(RhythmOverlay overlay){
mOverlays.add(overlay);
if (mCurrentOverlayIndex == NO_OVERLAY) {
selectOverlay(0);
}
return this;
}
| Add Rhythm overlay to this group |
public static String rename(String desc,String oldname,String newname){
if (desc.indexOf(oldname) < 0) return desc;
StringBuffer newdesc=new StringBuffer();
int head=0;
int i=0;
for (; ; ) {
int j=desc.indexOf('L',i);
if (j < 0) break;
else if (desc.startsWith(oldname,j + 1) && desc.charAt(j + oldname.length() + 1) == ';') {
newdesc.append(desc.substring(head,j));
newdesc.append('L');
newdesc.append(newname);
newdesc.append(';');
head=i=j + oldname.length() + 2;
}
else {
i=desc.indexOf(';',j) + 1;
if (i < 1) break;
}
}
if (head == 0) return desc;
else {
int len=desc.length();
if (head < len) newdesc.append(desc.substring(head,len));
return newdesc.toString();
}
}
| Substitutes a class name in the given descriptor string. |
public DeepMLTest(String name){
super(name);
}
| Initializes the test. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.