code
stringlengths 10
174k
| nl
stringlengths 3
129k
|
---|---|
public int size(){
return this.list.size();
}
| Returns number of elements in this list. |
public MType build(){
isClean=true;
return getMessage();
}
| Builds the message and returns it. |
protected void callSubtreeVisitors(XPathVisitor visitor){
if (null != m_predicates) {
int n=m_predicates.length;
for (int i=0; i < n; i++) {
ExpressionOwner predOwner=new PredOwner(i);
if (visitor.visitPredicate(predOwner,m_predicates[i])) {
m_predicates[i].callVisitors(predOwner,visitor);
}
}
}
if (null != m_relativePathPattern) {
m_relativePathPattern.callVisitors(this,visitor);
}
}
| Call the visitors on the subtree. Factored out from callVisitors so it may be called by derived classes. |
@Override public boolean equals(Object o){
if (this == o) {
return true;
}
if (!(o instanceof OPTICSHeapEntry)) {
return false;
}
final OPTICSHeapEntry that=(OPTICSHeapEntry)o;
return DBIDUtil.equal(objectID,that.objectID);
}
| Indicates whether some other object is "equal to" this one. NOTE: for the use in an UpdatableHeap, only the ID is compared! |
public static void main(String[] args){
ResourceManager rm=new POSConfigurator().getDefaultConfig();
String testingFile=rm.getString("testData");
TestDiscrete.testDiscrete(new TestDiscrete(),new POSTagger(),new POSLabel(),new POSBracketToToken(testingFile),true,0);
}
| Implements the program described above. |
public static TransformMatrix2D translate(double x,double y){
return new TransformMatrix2D(1.0d,0.0d,0.0d,1.0d,x,y);
}
| Produces a transformation matrix representing a translation operation. |
public boolean optBoolean(int index){
return this.optBoolean(index,false);
}
| Get the optional boolean value associated with an index. It returns false if there is no value at that index, or if the value is not Boolean.TRUE or the String "true". |
private final int yystate(){
return zzLexicalState;
}
| Returns the current lexical state. |
public static RDFParser createParser(RDFFormat format,ValueFactory valueFactory) throws UnsupportedRDFormatException {
RDFParser rdfParser=createParser(format);
rdfParser.setValueFactory(valueFactory);
return rdfParser;
}
| Convenience methods for creating RDFParser objects that use the specified ValueFactory to create RDF model objects. |
public static void swap(int[] arr,int index1,int index2){
if (index1 == index2) {
}
else {
int tmp=arr[index1];
arr[index1]=arr[index2];
arr[index2]=tmp;
}
}
| Swap two elements in an array |
public CipherParameters generateDerivedParameters(int keySize){
keySize=keySize / 8;
byte[] dKey=generateDerivedKey(keySize);
return new KeyParameter(dKey,0,keySize);
}
| Generate a key parameter derived from the password, salt, and iteration count we are currently initialised with. |
public TlsKeyMaterialSpec(SecretKey clientMacKey,SecretKey serverMacKey,SecretKey clientCipherKey,IvParameterSpec clientIv,SecretKey serverCipherKey,IvParameterSpec serverIv){
this.clientMacKey=clientMacKey;
this.serverMacKey=serverMacKey;
this.clientCipherKey=clientCipherKey;
this.serverCipherKey=serverCipherKey;
this.clientIv=clientIv;
this.serverIv=serverIv;
}
| Constructs a new TlsKeymaterialSpec from the client and server MAC keys, client and server cipher keys, and client and server initialization vectors. |
public DefaultRetryPolicy(int initialTimeoutMs,int maxNumRetries,float backoffMultiplier){
mCurrentTimeoutMs=initialTimeoutMs;
mMaxNumRetries=maxNumRetries;
mBackoffMultiplier=backoffMultiplier;
}
| Constructs a new retry policy. |
public boolean isUsePointAsDefaultImage(){
return usePointAsDefaultImage;
}
| Indicates whether to draw a point when the current source image is null. |
public void addItem(T item){
contents.add(item);
notifyItemInserted(contents.size() - 1);
}
| Adds an item into the contents |
@Override public void initChannel(SocketChannel ch){
ChannelPipeline p=ch.pipeline();
ch.config().setAllocator(NettyChannelContext.ALLOCATOR);
ch.config().setSendBufferSize(NettyChannelContext.BUFFER_SIZE);
ch.config().setReceiveBufferSize(NettyChannelContext.BUFFER_SIZE);
if (this.pool.getSSLContext() != null) {
if (this.isHttp2Only) {
throw new IllegalArgumentException("HTTP/2 with SSL is not supported");
}
SSLEngine engine=this.pool.getSSLContext().createSSLEngine();
engine.setUseClientMode(true);
p.addLast(SSL_HANDLER,new SslHandler(engine));
}
HttpClientCodec http1_codec=new HttpClientCodec(NettyChannelContext.MAX_INITIAL_LINE_LENGTH,NettyChannelContext.MAX_HEADER_SIZE,NettyChannelContext.MAX_CHUNK_SIZE,false,false);
p.addLast(HTTP1_CODEC,http1_codec);
if (this.isHttp2Only) {
try {
NettyHttpToHttp2Handler connectionHandler=makeHttp2ConnectionHandler();
Http2ClientUpgradeCodec upgradeCodec=new Http2ClientUpgradeCodec(connectionHandler);
HttpClientUpgradeHandler upgradeHandler=new HttpClientUpgradeHandler(http1_codec,upgradeCodec,this.requestPayloadSizeLimit);
p.addLast(UPGRADE_HANDLER,upgradeHandler);
p.addLast(UPGRADE_REQUEST,new UpgradeRequestHandler());
ChannelPromise settingsPromise=ch.newPromise();
p.addLast("settings-handler",new Http2SettingsHandler(settingsPromise));
ch.attr(NettyChannelContext.SETTINGS_PROMISE_KEY).set(settingsPromise);
p.addLast(EVENT_LOGGER,new NettyHttp2UserEventLogger(this.debugLogging));
}
catch ( Throwable ex) {
Utils.log(NettyHttpClientRequestInitializer.class,NettyHttpClientRequestInitializer.class.getSimpleName(),Level.WARNING,"Channel Initializer exception: %s",ex);
throw ex;
}
}
else {
p.addLast(AGGREGATOR_HANDLER,new HttpObjectAggregator(this.requestPayloadSizeLimit));
}
p.addLast(XENON_HANDLER,new NettyHttpServerResponseHandler(this.pool));
}
| initChannel is called by Netty when a channel is first used. |
public final double[][] matrix(){
return m_perClassPerBag;
}
| Returns matrix with distribution of class values. |
public void substituteForAll(Vector exprs,Vector strs) throws TLAExprException {
substituteForAll(exprs,strs,true);
}
| Substitutes clones of the expressions in exprs for the corresponding strings of strs in the current expression. This is called with parenthesize = true only during the initial parsing phase (the execution of ParseAlgorithm.getAlgorithm). It is called with parenthesize = false by: PcalFixIDs.FixExpr : replaces the string of an IDENT token with a new one to perform renaming in case of name conflicts. PcalTLAGen.AddSubscriptsToExpr: adds the primes and "[self]" subscripts to variables when needed. This method was modified by LL on 10 August 2012 to do the substitutions "simultaneously" rather than one after the other. The original code first did all the substitutions for the first string, then all the substitutions for the second string, etc. This yielded a bug if the expression substituted for the first string contained the second string. For example, the substitutions a <- F(b), b <- c in a + b produced F(c) + c instead of the correct F(b) + c . |
public void handleInstanceExecutor(){
for ( InstanceExecutor executor : taskIdToInstanceExecutor.values()) {
boolean isLocalSpout=spoutSets.contains(executor.getComponentName());
int taskId=executor.getTaskId();
int items=executor.getStreamOutQueue().size();
for (int i=0; i < items; i++) {
HeronTuples.HeronTupleSet tupleSet=executor.getStreamOutQueue().poll();
if (tupleSet == null) {
break;
}
if (tupleSet.hasData()) {
HeronTuples.HeronDataTupleSet d=tupleSet.getData();
TopologyAPI.StreamId streamId=d.getStream();
StreamConsumers consumers=streamIdStreamConsumersMap.get(streamId);
if (consumers != null) {
for ( HeronTuples.HeronDataTuple tuple : d.getTuplesList()) {
List<Integer> outTasks=consumers.getListToSend(tuple);
outTasks.addAll(tuple.getDestTaskIdsList());
if (outTasks.isEmpty()) {
LOG.severe("Nobody to sent the tuple to");
}
copyDataOutBound(taskId,isLocalSpout,streamId,tuple,outTasks);
}
}
else {
LOG.severe("Nobody consumes stream: " + streamId);
}
}
if (tupleSet.hasControl()) {
HeronTuples.HeronControlTupleSet c=tupleSet.getControl();
for ( HeronTuples.AckTuple ack : c.getAcksList()) {
copyControlOutBound(ack,true);
}
for ( HeronTuples.AckTuple fail : c.getFailsList()) {
copyControlOutBound(fail,false);
}
}
}
}
}
| Handle the execution of the instance |
public static void main(String args[]) throws IOException {
String star="M 48,54 L 31,42 15,54 21,35 6,23 25,23 25,23 25,23 25,23 32,4 40,23 58,23 42,35 z";
String arrow="M 12, 4 L 10.59,5.41 L 16.17,11 L 18.99,11 L 12,4 z M 4, 11 L 4, 13 L 18.99, 13 L 20, 12 L 18.99, 11 L 4, 11 z M 12,20 L 10.59, 18.59 L 16.17, 13 L 18.99, 13 L 12, 20z";
String triangle="M 91.095527,384.35546 L 254.23312,110.62095 L 405.71803,386.1926 z";
String polystar="M 177.11729,247.88609 L 256.31153,96.745452 L 217.85024,262.98609 L 388.33899,255.99999 L 225.13973,305.81185 L 316.43424,449.96639 L 191.69628,333.53762 L 112.50204,484.67825 L 150.96333,318.43762 L -19.525418,325.42372 L 143.67384,275.61186 L 52.379325,131.45732 z";
String fromSequence=null;
String toSequence=null;
VectAlign.Mode mode=VectAlign.Mode.BASE;
Options options=initCommandLineOptions();
try {
CommandLineParser parser=new DefaultParser();
CommandLine commandLine=parser.parse(options,args);
if (commandLine.getOptions() == null || commandLine.getOptions().length == 0 || commandLine.hasOption(OPTION_GUI)) {
VectAlignViewer.startVectAlignGUI();
return;
}
else if (commandLine.hasOption(OPTION_VERSION)) {
System.out.println(NAME + " v" + VERSION);
return;
}
else if (commandLine.hasOption(OPTION_HELP)) {
printHelp(options);
return;
}
if (commandLine.hasOption(OPTION_MODE)) {
mode=VectAlign.Mode.valueOf(commandLine.getOptionValue(OPTION_MODE).toUpperCase());
}
File tmpFile;
if (commandLine.hasOption(OPTION_FROM)) {
fromSequence=commandLine.getOptionValue(OPTION_FROM);
tmpFile=new File(fromSequence);
if (tmpFile.isFile() && tmpFile.exists()) {
if (SVGParser.isSVGImage(tmpFile)) fromSequence=SVGParser.getPathDataFromSVGFile(tmpFile);
else fromSequence=Utils.readSequenceFromFile(tmpFile);
}
}
if (commandLine.hasOption(OPTION_TO)) {
toSequence=commandLine.getOptionValue(OPTION_TO);
tmpFile=new File(toSequence);
if (tmpFile.isFile() && tmpFile.exists()) {
if (SVGParser.isSVGImage(tmpFile)) toSequence=SVGParser.getPathDataFromSVGFile(tmpFile);
else toSequence=Utils.readSequenceFromFile(tmpFile);
}
}
if (fromSequence == null || toSequence == null) {
if (fromSequence == null) System.out.println("Missing START path sequence. Specify the starting path using -s (or --start)");
else System.out.println("Missing END path sequence. Specify the ending path using -e (or --end)");
return;
}
String[] align=null;
try {
align=VectAlign.align(fromSequence,toSequence,mode);
}
catch ( Exception e) {
System.out.println("###################### EXCEPTION #####################");
e.printStackTrace();
System.out.println("######################################################");
System.out.println("\nFor contributions or issues reporting, please visit " + Utils.ANSI_CYAN + "https://github.com/bonnyfone/vectalign \n "+ Utils.ANSI_RESET);
}
if (align == null) {
return;
}
System.out.println("\n--------------------");
System.out.println(" ALIGNMENT RESULT ");
System.out.println("-------------------- ");
System.out.println("\n# new START path: \n" + Utils.ANSI_GREEN + align[0]+ Utils.ANSI_RESET);
System.out.println("\n# new END path: \n" + Utils.ANSI_YELLOW + align[1]+ Utils.ANSI_RESET);
System.out.println("\nThese sequences are morphable and can be used as 'pathData' attributes inside of VectorDrawable files.\n");
}
catch ( ParseException e) {
System.out.println("Wrong parameters!\n");
printHelp(options);
}
}
| VectAlign commandLine main |
private static int[] subtract(int[] big,long val){
int highWord=(int)(val >>> 32);
int bigIndex=big.length;
int result[]=new int[bigIndex];
long difference=0;
if (highWord == 0) {
difference=(big[--bigIndex] & LONG_MASK) - val;
result[bigIndex]=(int)difference;
}
else {
difference=(big[--bigIndex] & LONG_MASK) - (val & LONG_MASK);
result[bigIndex]=(int)difference;
difference=(big[--bigIndex] & LONG_MASK) - (highWord & LONG_MASK) + (difference >> 32);
result[bigIndex]=(int)difference;
}
boolean borrow=(difference >> 32 != 0);
while (bigIndex > 0 && borrow) borrow=((result[--bigIndex]=big[bigIndex] - 1) == -1);
while (bigIndex > 0) result[--bigIndex]=big[bigIndex];
return result;
}
| Subtracts the contents of the second argument (val) from the first (big). The first int array (big) must represent a larger number than the second. This method allocates the space necessary to hold the answer. assumes val >= 0 |
public Boolean isImageStabilization(){
return imageStabilization;
}
| Ruft den Wert der imageStabilization-Eigenschaft ab. |
@DSSafe(DSCat.SAFE_LIST) @DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2014-09-03 14:59:57.529 -0400",hash_original_method="DAF76BB129F2DF1AEBFCF7AF03B53BD1",hash_generated_method="8EAA6A21405527077C09CC32684C9130") public static String separatorsToWindows(String path){
if (path == null || path.indexOf(UNIX_SEPARATOR) == -1) {
return path;
}
return path.replace(UNIX_SEPARATOR,WINDOWS_SEPARATOR);
}
| Converts all separators to the Windows separator of backslash. |
public void warn(XPathContext xctxt,String msg,Object args[]) throws javax.xml.transform.TransformerException {
String formattedMsg=XSLMessages.createWarning(msg,args);
ErrorListener errHandler=xctxt.getErrorListener();
errHandler.warning(new TransformerException(formattedMsg,(SAXSourceLocator)xctxt.getSAXLocator()));
}
| Warn the user of a problem. |
private void writeQName(javax.xml.namespace.QName qname,javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException {
java.lang.String namespaceURI=qname.getNamespaceURI();
if (namespaceURI != null) {
java.lang.String prefix=xmlWriter.getPrefix(namespaceURI);
if (prefix == null) {
prefix=generatePrefix(namespaceURI);
xmlWriter.writeNamespace(prefix,namespaceURI);
xmlWriter.setPrefix(prefix,namespaceURI);
}
if (prefix.trim().length() > 0) {
xmlWriter.writeCharacters(prefix + ":" + org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qname));
}
else {
xmlWriter.writeCharacters(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qname));
}
}
else {
xmlWriter.writeCharacters(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qname));
}
}
| method to handle Qnames |
@Override public void addDeviceKey(KeyPair deviceKey,Certificate deviceCert,String deviceName){
try {
this.keyStore.setKeyEntry(deviceName,deviceKey.getPrivate(),KeyConstants.OPEN_KEYSTORE_PASSWORD,new java.security.cert.Certificate[]{deviceCert});
}
catch ( KeyStoreException e) {
logger.error("Could not add device key for device " + deviceName + " to identity's keystore",e);
}
}
| Stores a given device key and its certificate in the keystore of this identity |
protected PersistentResource(@NonNull T obj,PersistentResource<?> parent,String id,RequestScope requestScope){
this.obj=obj;
this.uuid=Optional.ofNullable(id);
this.parent=Optional.ofNullable(parent);
this.lineage=this.parent.isPresent() ? new ResourceLineage(parent.lineage,parent) : new ResourceLineage();
this.dictionary=requestScope.getDictionary();
this.type=dictionary.getJsonAliasFor(obj.getClass());
this.user=requestScope.getUser();
this.entityCache=requestScope.getObjectEntityCache();
this.transaction=requestScope.getTransaction();
this.requestScope=requestScope;
dictionary.initializeEntity(obj);
}
| Construct a new resource from the ID provided. |
public static <T extends Key<T>>GroupMatcher<T> groupStartsWith(String compareTo){
return new GroupMatcher<T>(compareTo,StringOperatorName.STARTS_WITH);
}
| Create a GroupMatcher that matches groups starting with the given string. |
public AiffFileWriter(){
super(new AudioFileFormat.Type[]{AudioFileFormat.Type.AIFF});
}
| Constructs a new AiffFileWriter object. |
public void testKeyPairGenerator05() throws NoSuchProviderException, IllegalArgumentException {
if (!DSASupported) {
fail(NotSupportMsg);
return;
}
try {
KeyPairGenerator.getInstance(null,validProviderName);
fail("NullPointerException or NoSuchAlgorithmException must be thrown when algorithm is null");
}
catch ( NoSuchAlgorithmException e) {
}
catch ( NullPointerException e) {
}
for (int i=0; i < invalidValues.length; i++) {
try {
KeyPairGenerator.getInstance(invalidValues[i],validProviderName);
fail("NoSuchAlgorithmException must be thrown (algorithm: ".concat(algs[i]).concat(" provider: ").concat(validProviderName).concat(")"));
}
catch ( NoSuchAlgorithmException e) {
}
}
}
| Test for <code>getInstance(String algorithm, String provider)</code> method Assertion: throws NoSuchAlgorithmException when algorithm is not available throws NullPointerException when algorithm is null throws NoSuchAlgorithmException when algorithm is incorrect; |
public K lastKey(){
K k=map.lastKey();
while (true) {
if (k == null) {
return null;
}
if (get(k) != null) {
return k;
}
k=map.lowerKey(k);
}
}
| Get the last key. |
public void insert(String name,long cnt){
if (_values == null) {
_values=new ArrayList<>(30);
}
_values.add(0,new Count(this,name,cnt));
}
| Insert at the beginning of the list. |
public final void add(Action action,ActionManager actionManager){
add(action,Constraints.LAST,actionManager);
}
| Adds the specified action to the tail. |
public static double cosToSin(double angle,double cos){
if ((-1e-5 < cos && cos < 1e-5) || cos > 0.99999 || cos < -0.99999) {
return Math.sin(angle);
}
angle=normAngle(angle);
final double s=Math.sqrt(1 - cos * cos);
return (angle < Math.PI) ? s : -s;
}
| <b>Fast</b> way of computing sin(x) from x and cos(x). |
@Override public Object eGet(int featureID,boolean resolve,boolean coreType){
switch (featureID) {
case TypesPackage.TANNOTABLE_ELEMENT__ANNOTATIONS:
return getAnnotations();
}
return super.eGet(featureID,resolve,coreType);
}
| <!-- begin-user-doc --> <!-- end-user-doc --> |
public boolean isMathMode(){
return ignoreWhiteSpace;
}
| Return a boolean indicating if the parser is in math mode |
@Override public boolean equals(Object obj){
if (obj == this) {
return true;
}
if (!(obj instanceof XYErrorRenderer)) {
return false;
}
XYErrorRenderer that=(XYErrorRenderer)obj;
if (this.drawXError != that.drawXError) {
return false;
}
if (this.drawYError != that.drawYError) {
return false;
}
if (this.capLength != that.capLength) {
return false;
}
if (!PaintUtilities.equal(this.errorPaint,that.errorPaint)) {
return false;
}
if (!ObjectUtilities.equal(this.errorStroke,that.errorStroke)) {
return false;
}
return super.equals(obj);
}
| Tests this instance for equality with an arbitrary object. |
public static PermissionCondition create(Class<? extends Annotation> permission,PersistentResource resource,String field,ChangeSpec changes){
if (resource != null) {
if (changes != null) {
if (field != null && changes.getFieldName() == null) {
return new PermissionCondition(permission,resource,field);
}
return new PermissionCondition(permission,resource,changes);
}
else if (field == null) {
return new PermissionCondition(permission,resource);
}
else {
return new PermissionCondition(permission,resource,field);
}
}
throw new IllegalArgumentException("Resource cannot be null");
}
| This function attempts to create the appropriate PermissionCondition based on parameters that may or may not be null. This is a temporary workaround given that the caller functions duplicate data in their signatures and pass nulls. The calling code needs to be cleaned up - and then this function can be disposed of. |
public FloatRange(float min,float max){
this.min=min;
this.max=max;
}
| Construct new range. |
private Collection<IQuest> findCompletedQuests(Player player){
List<IQuest> res=new ArrayList<IQuest>();
for ( IQuest quest : quests) {
if (quest.isCompleted(player) && quest.isVisibleOnQuestStatus()) {
res.add(quest);
}
}
return res;
}
| Find the quests that a player has completed. |
public void testXformLoadSucceeded_ReenablesXformFetch(){
mController.init();
mFakeGlobalEventBus.post(new FetchXformSucceededEvent());
verify(mMockUi).reEnableFetch();
}
| Tests that the xform can be fetched again if the first fetch succeeds. |
public static void addSingleCrystallization(Item input,ItemStack output,float xp){
addCrystallization(input,output,null,xp);
}
| Single-output Crystallization |
private void checkOneNode(int id) throws Exception {
try (Ignite ignite=G.start(getConfiguration("grid" + id))){
String id8=U.id8(ignite.cluster().localNode().id());
String logPath="work/log/ignite-" + id8 + ".log";
File logFile=U.resolveIgnitePath(logPath);
assertNotNull("Failed to resolve path: " + logPath,logFile);
assertTrue("Log file does not exist: " + logFile,logFile.exists());
String logContent=U.readFileToString(logFile.getAbsolutePath(),"UTF-8");
assertTrue("Log file does not contain it's node ID: " + logFile,logContent.contains(">>> Local node [ID=" + id8.toUpperCase()));
}
}
| Starts the local node and checks for presence of log file. Also checks that this is really a log of a started node. |
public void openDB(){
if (mSQLiteDatabase.isOpen() == false) mSQLiteDatabase=SQLiteDatabase.openOrCreateDatabase(dbPath,null);
}
| open database |
public static Matrix random(int m,int n){
Matrix A=new Matrix(m,n);
double[][] X=A.getArray();
for (int i=0; i < m; i++) {
for (int j=0; j < n; j++) {
X[i][j]=Math.random();
}
}
return A;
}
| Generate matrix with random elements |
private int defaultThreadID(){
long tid=Thread.currentThread().getId();
if (tid < MIN_SEQUENTIAL_THREAD_ID) {
return (int)tid;
}
else {
Integer id=threadIds.get();
if (id == null) {
id=nextThreadId.getAndIncrement();
threadIds.set(id);
}
return id;
}
}
| Returns the default value for a new LogRecord's threadID. |
public FindBugsCommandLine(boolean modernGui){
this();
addOption("-f","font size","set font size");
addSwitch("-clear","clear saved GUI settings and exit");
addOption("-priority","thread priority","set analysis thread priority");
addOption("-loadbugs","saved analysis results","load bugs from saved analysis results");
makeOptionUnlisted("-loadbugs");
addOption("-loadBugs","saved analysis results","load bugs from saved analysis results");
addSwitch("-d","disable docking");
addSwitch("--nodock","disable docking");
addSwitchWithOptionalExtraPart("-look","plastic|gtk|native","set UI look and feel");
}
| Additional constuctor just as hack for decoupling the core package from gui2 package |
private String makeFullStatus(){
if (online) {
String fullStatus=status;
if (status == null || status.isEmpty()) {
fullStatus="No stream title set";
}
if (game != null && !game.isEmpty()) {
fullStatus+=" (" + game + ")";
}
return fullStatus;
}
else if (!updateSucceeded) {
return "";
}
else {
return "Stream offline";
}
}
| Makes the full status based on the current data. |
private String createViewName(QualifiedName name){
return String.format("%s_%s_%s",name.getDatabaseName(),name.getTableName(),name.getViewName());
}
| The view is going to be represented by a table in a special db in Franklin. As such there must be a conversion from view id -> view table id like so: [dbName]_[tableName]_[viewName] |
protected double numericDistribution(double[][] props,double[][][] dists,int att,double[][] subsetWeights,Instances data,double[] vals) throws Exception {
double splitPoint=Double.NaN;
Attribute attribute=data.attribute(att);
double[][] dist=null;
double[] sums=null;
double[] sumSquared=null;
double[] sumOfWeights=null;
double totalSum=0, totalSumSquared=0, totalSumOfWeights=0;
int indexOfFirstMissingValue=data.numInstances();
if (attribute.isNominal()) {
sums=new double[attribute.numValues()];
sumSquared=new double[attribute.numValues()];
sumOfWeights=new double[attribute.numValues()];
int attVal;
for (int i=0; i < data.numInstances(); i++) {
Instance inst=data.instance(i);
if (inst.isMissing(att)) {
if (indexOfFirstMissingValue == data.numInstances()) {
indexOfFirstMissingValue=i;
}
continue;
}
attVal=(int)inst.value(att);
sums[attVal]+=inst.classValue() * inst.weight();
sumSquared[attVal]+=inst.classValue() * inst.classValue() * inst.weight();
sumOfWeights[attVal]+=inst.weight();
}
totalSum=Utils.sum(sums);
totalSumSquared=Utils.sum(sumSquared);
totalSumOfWeights=Utils.sum(sumOfWeights);
}
else {
sums=new double[2];
sumSquared=new double[2];
sumOfWeights=new double[2];
double[] currSums=new double[2];
double[] currSumSquared=new double[2];
double[] currSumOfWeights=new double[2];
data.sort(att);
for (int j=0; j < data.numInstances(); j++) {
Instance inst=data.instance(j);
if (inst.isMissing(att)) {
indexOfFirstMissingValue=j;
break;
}
currSums[1]+=inst.classValue() * inst.weight();
currSumSquared[1]+=inst.classValue() * inst.classValue() * inst.weight();
currSumOfWeights[1]+=inst.weight();
}
totalSum=currSums[1];
totalSumSquared=currSumSquared[1];
totalSumOfWeights=currSumOfWeights[1];
sums[1]=currSums[1];
sumSquared[1]=currSumSquared[1];
sumOfWeights[1]=currSumOfWeights[1];
double currSplit=data.instance(0).value(att);
double currVal, bestVal=Double.MAX_VALUE;
for (int i=0; i < indexOfFirstMissingValue; i++) {
Instance inst=data.instance(i);
if (inst.value(att) > currSplit) {
currVal=RandomTree.variance(currSums,currSumSquared,currSumOfWeights);
if (currVal < bestVal) {
bestVal=currVal;
splitPoint=(inst.value(att) + currSplit) / 2.0;
if (splitPoint <= currSplit) {
splitPoint=inst.value(att);
}
for (int j=0; j < 2; j++) {
sums[j]=currSums[j];
sumSquared[j]=currSumSquared[j];
sumOfWeights[j]=currSumOfWeights[j];
}
}
}
currSplit=inst.value(att);
double classVal=inst.classValue() * inst.weight();
double classValSquared=inst.classValue() * classVal;
currSums[0]+=classVal;
currSumSquared[0]+=classValSquared;
currSumOfWeights[0]+=inst.weight();
currSums[1]-=classVal;
currSumSquared[1]-=classValSquared;
currSumOfWeights[1]-=inst.weight();
}
}
props[0]=new double[sums.length];
for (int k=0; k < props[0].length; k++) {
props[0][k]=sumOfWeights[k];
}
if (!(Utils.sum(props[0]) > 0)) {
for (int k=0; k < props[0].length; k++) {
props[0][k]=1.0 / props[0].length;
}
}
else {
Utils.normalize(props[0]);
}
for (int i=indexOfFirstMissingValue; i < data.numInstances(); i++) {
Instance inst=data.instance(i);
for (int j=0; j < sums.length; j++) {
sums[j]+=props[0][j] * inst.classValue() * inst.weight();
sumSquared[j]+=props[0][j] * inst.classValue() * inst.classValue()* inst.weight();
sumOfWeights[j]+=props[0][j] * inst.weight();
}
totalSum+=inst.classValue() * inst.weight();
totalSumSquared+=inst.classValue() * inst.classValue() * inst.weight();
totalSumOfWeights+=inst.weight();
}
dist=new double[sums.length][data.numClasses()];
for (int j=0; j < sums.length; j++) {
if (sumOfWeights[j] > 0) {
dist[j][0]=sums[j] / sumOfWeights[j];
}
else {
dist[j][0]=totalSum / totalSumOfWeights;
}
}
double priorVar=singleVariance(totalSum,totalSumSquared,totalSumOfWeights);
double var=variance(sums,sumSquared,sumOfWeights);
double gain=priorVar - var;
subsetWeights[att]=sumOfWeights;
dists[0]=dist;
vals[att]=gain;
return splitPoint;
}
| Computes numeric class distribution for an attribute |
public static void moveRowsUp(double[][] matrix,int upBy){
int rows=matrix.length;
int cols=matrix[0].length;
for (int r=0; r < rows - upBy; r++) {
for (int c=0; c < cols; c++) {
matrix[r][c]=matrix[r + upBy][c];
}
}
for (int r=rows - upBy; r < rows; r++) {
for (int c=0; c < cols; c++) {
matrix[r][c]=0;
}
}
}
| Moves the rows of the array up by upBy. Inserts zeros at the bottom |
@Override public T defaultCase(EObject object){
return null;
}
| Returns the result of interpreting the object as an instance of '<em>EObject</em>'. <!-- begin-user-doc --> This implementation returns null; returning a non-null result will terminate the switch, but this is the last case anyway. <!-- end-user-doc --> |
public static void writeGzip(String fileName,Iterable<String> list) throws IOException {
writeGZip(fileName,list,identityTransformer);
}
| Writes a list of strings to a file gzipped, one per line. |
public static DefaultRefactoringDescriptor[] readRefactoringDescriptors(final InputStream stream) throws CoreException {
final List list=new ArrayList(64);
readRefactoringDescriptors(stream,list,new NullProgressMonitor());
return (DefaultRefactoringDescriptor[])list.toArray(new DefaultRefactoringDescriptor[list.size()]);
}
| Reads default refactoring descriptors from the specified input stream. <p> The refactoring descriptors are returned in no particular order. </p> |
public static InteriorIntersectionFinder createAllIntersectionsFinder(LineIntersector li){
InteriorIntersectionFinder finder=new InteriorIntersectionFinder(li);
finder.setFindAllIntersections(true);
return finder;
}
| Creates an intersection finder which finds all interior intersections. The intersections are recorded for later inspection. |
public static final SpellCheckedMetadata constructSpellCheckedMetadata(){
SpellCheckedMetadata scmd=new SpellCheckedMetadata();
scmd.add("Content-type","foo/bar");
scmd.add("Connection","close");
scmd.add("Last-Modified","Sat, 09 Dec 2006 15:09:57 GMT");
scmd.add("Server","Foobar");
scmd.add("Date","Sat, 09 Dec 2006 18:07:20 GMT");
scmd.add("Accept-Ranges","bytes");
scmd.add("ETag","\"1234567-89-01234567\"");
scmd.add("Content-Length","123");
scmd.add(Nutch.BATCH_NAME_KEY,"batchzzz");
scmd.add(Nutch.SIGNATURE_KEY,"123");
return scmd;
}
| Assembles a Spellchecked metadata Object. |
public int processor(){
return Integer.parseInt(fields[38]);
}
| (since Linux 2.2.8) CPU number last executed on. |
private void showFeedback(String message){
if (myHost != null) {
myHost.showFeedback(message);
}
else {
System.out.println(message);
}
}
| Used to communicate feedback pop-up messages between a plugin tool and the main Whitebox user-interface. |
public final byte[] acceptSecContext(InputStream is,int mechTokenSize) throws GSSException {
byte[] retVal=null;
if (DEBUG) {
System.out.println("Entered Krb5Context.acceptSecContext with " + "state=" + printState(state));
}
if (isInitiator()) {
throw new GSSException(GSSException.FAILURE,-1,"acceptSecContext on an initiator " + "GSSContext");
}
try {
if (state == STATE_NEW) {
state=STATE_IN_PROCESS;
if (myCred == null) {
myCred=Krb5AcceptCredential.getInstance(caller,myName);
}
else if (!myCred.isAcceptorCredential()) {
throw new GSSException(GSSException.NO_CRED,-1,"No Secret Key available");
}
myName=(Krb5NameElement)myCred.getName();
if (myName != null) {
Krb5MechFactory.checkAcceptCredPermission(myName,myName);
}
InitSecContextToken token=new InitSecContextToken(this,(Krb5AcceptCredential)myCred,is);
PrincipalName clientName=token.getKrbApReq().getClient();
peerName=Krb5NameElement.getInstance(clientName);
if (myName == null) {
myName=Krb5NameElement.getInstance(token.getKrbApReq().getCreds().getServer());
Krb5MechFactory.checkAcceptCredPermission(myName,myName);
}
if (getMutualAuthState()) {
retVal=new AcceptSecContextToken(this,token.getKrbApReq()).encode();
}
serviceTicket=token.getKrbApReq().getCreds().getTicket();
myCred=null;
state=STATE_DONE;
}
else {
if (DEBUG) {
System.out.println(state);
}
}
}
catch ( KrbException e) {
GSSException gssException=new GSSException(GSSException.FAILURE,-1,e.getMessage());
gssException.initCause(e);
throw gssException;
}
catch ( IOException e) {
if (DEBUG) {
e.printStackTrace();
}
GSSException gssException=new GSSException(GSSException.FAILURE,-1,e.getMessage());
gssException.initCause(e);
throw gssException;
}
return retVal;
}
| Acceptor's context establishment call. This method may be required to be called several times. A CONTINUE_NEEDED return call indicates that more calls are needed after the next token is received from the peer. |
public static void reverse(final boolean[] array){
if (array == null) {
return;
}
int i=0;
int j=array.length - 1;
boolean tmp;
while (j > i) {
tmp=array[j];
array[j]=array[i];
array[i]=tmp;
j--;
i++;
}
}
| <p>Reverses the order of the given array.</p> <p>This method does nothing for a <code>null</code> input array.</p> |
private Vector<Vector<Object>> queryProduct(){
String sql="SELECT p.Name,l.PriceActual,l.PriceList,l.QtyInvoiced," + "i.DateInvoiced,dt.PrintName || ' ' || i.DocumentNo As DocumentNo," + "o.Name, "+ "NULL, i.M_PriceList_ID "+ "FROM C_Invoice i"+ " INNER JOIN C_InvoiceLine l ON (i.C_Invoice_ID=l.C_Invoice_ID)"+ " INNER JOIN C_DocType dt ON (i.C_DocType_ID=dt.C_DocType_ID)"+ " INNER JOIN AD_Org o ON (i.AD_Org_ID=o.AD_Org_ID)"+ " INNER JOIN M_Product p ON (l.M_Product_ID=p.M_Product_ID) "+ "WHERE i.C_BPartner_ID=? "+ "ORDER BY i.DateInvoiced DESC";
Vector<Vector<Object>> data=fillTable(sql,m_C_BPartner_ID);
sql="SELECT Name from C_BPartner WHERE C_BPartner_ID=?";
fillLabel(sql,m_C_BPartner_ID);
return data;
}
| Get Info for Product for given Business Parner |
public MRUSet(int maxSize){
Assert.isLegal(maxSize > 0);
fMaxSize=maxSize;
}
| Creates a new <code>MRUSet</code> with the given size. |
void initFromCameraParameters(Camera camera){
Camera.Parameters parameters=camera.getParameters();
WindowManager manager=(WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
Display display=manager.getDefaultDisplay();
Point theScreenResolution=new Point();
theScreenResolution=getDisplaySize(display);
screenResolution=theScreenResolution;
Log.i(TAG,"Screen resolution: " + screenResolution);
cameraResolution=findBestPreviewSizeValue(parameters,screenResolution);
Log.i(TAG,"Camera resolution: " + cameraResolution);
}
| Reads, one time, values from the camera that are needed by the app. |
public void registerDisruption(DisruptionEntry disruption){
for ( DisruptionEntry entry : disruptions) if (disruption.getUnlocalizedName().equals(entry.getUnlocalizedName())) {
FMLLog.log("DisruptionHandler",Level.ERROR,"Disruption Entry already registered: %s",disruption.getUnlocalizedName());
return;
}
disruptions.add(disruption);
}
| Registers a Disruption Entry |
private java.util.HashMap<Float,java.awt.Color> recalculate(final java.util.List<Float> FRACTION_LIST,final java.util.List<java.awt.Color> COLOR_LIST,final float OFFSET){
final int MAX_FRACTIONS=FRACTION_LIST.size();
final java.util.HashMap<Float,java.awt.Color> FRACTION_COLORS=new java.util.HashMap<Float,java.awt.Color>(MAX_FRACTIONS);
for (int i=0; i < MAX_FRACTIONS; i++) {
final float TMP_FRACTION=FRACTION_LIST.get(i) + OFFSET;
final java.awt.Color TMP_COLOR=COLOR_LIST.get(i);
if (TMP_FRACTION <= 0) {
FRACTION_COLORS.put(1.0f + TMP_FRACTION + 0.0001f,TMP_COLOR);
final float NEXT_FRACTION;
final java.awt.Color NEXT_COLOR;
if (i < MAX_FRACTIONS - 1) {
NEXT_FRACTION=FRACTION_LIST.get(i + 1) + OFFSET;
NEXT_COLOR=COLOR_LIST.get(i + 1);
}
else {
NEXT_FRACTION=1 - FRACTION_LIST.get(0) + OFFSET;
NEXT_COLOR=COLOR_LIST.get(0);
}
if (NEXT_FRACTION > 0) {
final java.awt.Color NEW_FRACTION_COLOR=getColorFromFraction(TMP_COLOR,NEXT_COLOR,(int)((NEXT_FRACTION - TMP_FRACTION) * 10000),(int)((-TMP_FRACTION) * 10000));
FRACTION_COLORS.put(0.0f,NEW_FRACTION_COLOR);
FRACTION_COLORS.put(1.0f,NEW_FRACTION_COLOR);
}
}
else if (TMP_FRACTION >= 1) {
FRACTION_COLORS.put(TMP_FRACTION - 1.0f - 0.0001f,TMP_COLOR);
final float PREVIOUS_FRACTION;
final java.awt.Color PREVIOUS_COLOR;
if (i > 0) {
PREVIOUS_FRACTION=FRACTION_LIST.get(i - 1) + OFFSET;
PREVIOUS_COLOR=COLOR_LIST.get(i - 1);
}
else {
PREVIOUS_FRACTION=FRACTION_LIST.get(MAX_FRACTIONS - 1) + OFFSET;
PREVIOUS_COLOR=COLOR_LIST.get(MAX_FRACTIONS - 1);
}
if (PREVIOUS_FRACTION < 1) {
final java.awt.Color NEW_FRACTION_COLOR=getColorFromFraction(TMP_COLOR,PREVIOUS_COLOR,(int)((TMP_FRACTION - PREVIOUS_FRACTION) * 10000),(int)(TMP_FRACTION - 1.0f) * 10000);
FRACTION_COLORS.put(1.0f,NEW_FRACTION_COLOR);
FRACTION_COLORS.put(0.0f,NEW_FRACTION_COLOR);
}
}
else {
FRACTION_COLORS.put(TMP_FRACTION,TMP_COLOR);
}
}
FRACTION_LIST.clear();
COLOR_LIST.clear();
return FRACTION_COLORS;
}
| Recalculates the fractions in the FRACTION_LIST and their associated colors in the COLOR_LIST with a given OFFSET. Because the conical gradients always starts with 0 at the top and clockwise direction you could rotate the defined conical gradient from -180 to 180 degrees which equals values from -0.5 to +0.5 |
private static void rangeCheck(int arrayLen,int fromIndex,int toIndex){
if (fromIndex > toIndex) throw new IllegalArgumentException("fromIndex(" + fromIndex + ") > toIndex("+ toIndex+ ")");
if (fromIndex < 0) throw new ArrayIndexOutOfBoundsException(fromIndex);
if (toIndex > arrayLen) throw new ArrayIndexOutOfBoundsException(toIndex);
}
| Check that fromIndex and toIndex are in range, and throw an appropriate exception if they aren't. |
public CreatePixelMatrixDialog(final VisionWorld visionWorld){
super();
if (visionWorld == null) {
throw new IllegalArgumentException("visionWorld must not be null");
}
this.visionWorld=visionWorld;
setTitle("Create Pixel Matrix");
initComponents();
layoutComponents();
}
| Create a new pixel matrix dialog. |
public static void main(final String[] args){
Config config=ConfigUtils.createConfig();
config.addModule(PublicTransitMappingConfigGroup.createDefaultConfig());
Set<String> toRemove=config.getModules().keySet().stream().filter(null).collect(Collectors.toSet());
toRemove.forEach(null);
new ConfigWriter(config).write(args[0]);
}
| Creates a default publicTransitMapping config file. |
protected void addCameraButton(String key,String[][] imageSuffixes,boolean isLeftClickTemp,int[][] statePinValues){
final Integer state=prefs.getButtonState(key);
buttons.put(key,new CameraButton(key,imageSuffixes,isLeftClickTemp,statePinValues,this,(state == null ? 0 : state)));
}
| Adds a button to the front panel |
private static int hash(int x,int z){
int hash=HASH_SEED;
hash+=x;
hash*=HASH_SEED;
hash+=z;
hash*=HASH_SEED;
return hash;
}
| Computes a 32b hash based on the given coordinates. |
public static void drag(InstrumentationTestCase test,float fromX,float toX,float fromY,float toY,int stepCount){
Instrumentation inst=test.getInstrumentation();
long downTime=SystemClock.uptimeMillis();
long eventTime=SystemClock.uptimeMillis();
float y=fromY;
float x=fromX;
float yStep=(toY - fromY) / stepCount;
float xStep=(toX - fromX) / stepCount;
MotionEvent event=MotionEvent.obtain(downTime,eventTime,MotionEvent.ACTION_DOWN,x,y,0);
inst.sendPointerSync(event);
inst.waitForIdleSync();
for (int i=0; i < stepCount; ++i) {
y+=yStep;
x+=xStep;
eventTime=SystemClock.uptimeMillis();
event=MotionEvent.obtain(downTime,eventTime,MotionEvent.ACTION_MOVE,x,y,0);
inst.sendPointerSync(event);
inst.waitForIdleSync();
}
eventTime=SystemClock.uptimeMillis();
event=MotionEvent.obtain(downTime,eventTime,MotionEvent.ACTION_UP,x,y,0);
inst.sendPointerSync(event);
inst.waitForIdleSync();
}
| Simulate touching a specific location and dragging to a new location. |
public void add(PaletteWidget w){
dragController.makeDraggable(w);
super.add(w);
}
| Overloaded method that makes widgets draggable. |
public static synchronized BufferedImage loadBufferedImage(URL url,int imageType){
BufferedImage image=null;
if (url == null || !url.toString().toLowerCase().endsWith(".jpg")) {
Image tmpImage=loadImage(url);
if (tmpImage != null) {
image=new BufferedImage(tmpImage.getWidth(null),tmpImage.getHeight(null),imageType);
Graphics2D g=image.createGraphics();
g.drawImage(tmpImage,0,0,null);
g.dispose();
}
}
else {
BufferedImage tmpImage=loadBufferedJPEGImage(url);
if (tmpImage != null) {
if (tmpImage.getType() != imageType) {
log.config("Incompatible JPEG image type: creating new buffer image");
image=new BufferedImage(tmpImage.getWidth(null),tmpImage.getHeight(null),imageType);
Graphics2D g=image.createGraphics();
g.drawImage(tmpImage,0,0,null);
g.dispose();
}
else image=tmpImage;
}
}
return image;
}
| Loads an image from a given URL into a BufferedImage. The image is returned in the format defined by the imageType parameter. Note that this is special cased for JPEG images where loading is performed outside the standard media tracker, for efficiency reasons. |
public void addSparseFeatureVector(IFeatureVector sfv,float alpha){
addSparseFeatureVector(sfv,(double)alpha);
}
| w = w + alpha * sfv |
public void commit() throws IOException {
if (hasErrors) {
completeEdit(this,false);
remove(entry.key);
}
else {
completeEdit(this,true);
}
committed=true;
}
| Commits this edit so it is visible to readers. This releases the edit lock so another edit may be started on the same key. |
public static boolean handleFiles(final File[] files){
String fileFolder=files[0].isFile() ? I18n.tr("file") : I18n.tr("folder");
DialogOption result=GUIMediator.showYesNoMessage(I18n.tr("Do you want to send this {0} to a friend?",fileFolder) + "\n\n\"" + files[0].getName()+ "\"",I18n.tr("Send files with FrostWire"),JOptionPane.QUESTION_MESSAGE);
if (result == DialogOption.YES) {
new SendFileProgressDialog(GUIMediator.getAppFrame(),files[0]).setVisible(true);
GUIMediator.instance().showTransfers(TransfersTab.FilterMode.ALL);
UXStats.instance().log(UXAction.SHARING_TORRENT_CREATED_WITH_SEND_TO_FRIEND_FROM_DND);
return true;
}
return false;
}
| Returns true if files were shared |
public void put(E e){
offer(e);
}
| Inserts the specified element into this priority queue. As the queue is unbounded, this method will never block. |
public OrderedRowIterator(final String table,final Pattern wherePattern,final boolean up) throws IOException {
this.whereColumn=null;
this.whereValue=null;
this.wherePattern=wherePattern == null || wherePattern.toString().isEmpty() ? null : wherePattern;
this.heap=getHeap(table);
this.i=heap.keys(up,false);
}
| iterator that iterates all elements in the given table where a given column matches with a given value |
private void fillHead(){
MPPProductPlanning pp=MPPProductPlanning.find(getCtx(),getAD_Org_ID(),getM_Warehouse_ID(),getS_Resource_ID(),getM_Product_ID(),null);
if (pp == null) pp=new MPPProductPlanning(getCtx(),0,null);
fMaster.setSelected(pp.isMPS());
fMRPReq.setSelected(pp.isRequiredMRP());
fCreatePlan.setSelected(pp.isCreatePlan());
fOrderPeriod.setValue(pp.getOrder_Period());
fLeadtime.setValue(pp.getDeliveryTime_Promised());
fTimefence.setValue(pp.getTimeFence());
fMinOrd.setValue(pp.getOrder_Min());
fMaxOrd.setValue(pp.getOrder_Max());
fOrdMult.setValue(pp.getOrder_Pack());
fOrderQty.setValue(pp.getOrder_Qty());
fYield.setValue(pp.getYield());
fType.setText(MRefList.getListName(getCtx(),X_PP_Product_Planning.ORDER_POLICY_AD_Reference_ID,pp.getOrder_Policy()));
fSafetyStock.setValue(pp.getSafetyStock());
}
| Fill the head value |
public static void takeCamera(Activity activity,int requestCode){
Intent intent=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
activity.startActivityForResult(intent,requestCode);
}
| Take camera, this photo data will be returned in onActivityResult() |
public void testRemoveNonComparableFromEmptyMap(){
tm=new TreeMap();
try {
tm.remove(new Object());
}
catch ( ClassCastException expected) {
}
}
| Android's TreeMap requires every element to be comparable, even if there's no other element to compare it to. This is more strict than the RI. See Harmony-2474. |
public StrTokenizer(char[] input,char delim,char quote){
this(input,delim);
setQuoteChar(quote);
}
| Constructs a tokenizer splitting on the specified delimiter character and handling quotes using the specified quote character. <p> The input character array is not cloned, and must not be altered after passing in to this method. |
protected CordovaWebView makeWebView(){
return new CordovaWebView(CordovaActivity.this);
}
| Construct the default web view object. This is intended to be overridable by subclasses of CordovaIntent which require a more specialized web view. |
private static final int nextPieceSafe(Position pos,int sq,int delta){
int dx=0, dy=0;
switch (delta) {
case 1:
dx=1;
dy=0;
break;
case 9:
dx=1;
dy=1;
break;
case 8:
dx=0;
dy=1;
break;
case 7:
dx=-1;
dy=1;
break;
case -1:
dx=-1;
dy=0;
break;
case -9:
dx=-1;
dy=-1;
break;
case -8:
dx=0;
dy=-1;
break;
case -7:
dx=1;
dy=-1;
break;
}
int x=Position.getX(sq);
int y=Position.getY(sq);
while (true) {
x+=dx;
y+=dy;
if ((x < 0) || (x > 7) || (y < 0)|| (y > 7)) {
return Piece.EMPTY;
}
int p=pos.getPiece(Position.getSquare(x,y));
if (p != Piece.EMPTY) return p;
}
}
| Like nextPiece(), but handles board edges. |
private boolean isDriverRegistered(Driver d){
boolean foundDriver=false;
java.util.Enumeration e=DriverManager.getDrivers();
while (e.hasMoreElements()) {
if (d == (Driver)e.nextElement()) {
foundDriver=true;
break;
}
}
return foundDriver;
}
| Utility method to see if a driver is registered |
public void executeEpp(SessionMetadata sessionMetadata,TransportCredentials credentials,EppRequestSource eppRequestSource,boolean isDryRun,boolean isSuperuser,byte[] inputXmlBytes){
try {
response.setPayload(new String(marshalWithLenientRetry(eppController.handleEppCommand(sessionMetadata,credentials,eppRequestSource,isDryRun,isSuperuser,inputXmlBytes)),UTF_8));
response.setContentType(APPLICATION_EPP_XML);
response.setStatus(SC_OK);
}
catch ( Exception e) {
logger.warning(e,"handleEppCommand general exception");
response.setStatus(SC_BAD_REQUEST);
}
}
| Handle an EPP request and write out a servlet response. |
public void addPriorityPackage(String priorityPackage){
_classLoader.addPriorityPackage(priorityPackage);
}
| priority-package: used with servlet-hack Add a package for which this class loader will take precendence over the parent. Any class that has a qualified name that starts with the passed value will be loaded from this classloader instead of the parent classloader. |
public static SipResponse create200OkOptionsResponse(SipRequest options,ContactHeader contact,String[] featureTags,String sdp) throws PayloadException {
try {
Response response=SipUtils.MSG_FACTORY.createResponse(200,options.getStackMessage());
ToHeader to=(ToHeader)response.getHeader(ToHeader.NAME);
to.setTag(IdGenerator.getIdentifier());
response.addHeader(contact);
SipUtils.setFeatureTags(response,featureTags);
SipUtils.buildAllowHeader(response);
response.addHeader(SipUtils.buildServerHeader());
if (sdp != null) {
response.setContent(sdp,SipUtils.HEADER_FACTORY.createContentTypeHeader("application","sdp"));
response.setContentLength(SipUtils.HEADER_FACTORY.createContentLengthHeader(sdp.getBytes(UTF8).length));
}
SipResponse resp=new SipResponse(response);
resp.setStackTransaction(options.getStackTransaction());
return resp;
}
catch ( ParseException|InvalidArgumentException e) {
throw new PayloadException("Can't create SIP response for SDP : " + sdp,e);
}
}
| Create a 200 OK response for OPTIONS request |
public void start(XmlPullParser parser) throws XmlPullParserException, IOException {
JDiffClassDescription currentClass=null;
String currentPackage="";
JDiffMethod currentMethod=null;
SignatureTest.beginDocument(parser,TAG_ROOT);
int type;
while (true) {
while ((type=parser.next()) != XmlPullParser.START_TAG && type != XmlPullParser.END_DOCUMENT && type != XmlPullParser.END_TAG) {
}
if (type == XmlPullParser.END_TAG) {
if (TAG_CLASS.equals(parser.getName()) || TAG_INTERFACE.equals(parser.getName())) {
currentClass.checkSignatureCompliance();
}
else if (TAG_PACKAGE.equals(parser.getName())) {
currentPackage="";
}
continue;
}
if (type == XmlPullParser.END_DOCUMENT) {
break;
}
String tagname=parser.getName();
if (!mKeyTagSet.contains(tagname)) {
continue;
}
switch (tagname) {
case TAG_PACKAGE:
currentPackage=parser.getAttributeValue(null,ATTRIBUTE_NAME);
break;
case TAG_CLASS:
currentClass=loadClassInfo(parser,false,currentPackage);
break;
case TAG_INTERFACE:
currentClass=loadClassInfo(parser,true,currentPackage);
break;
case TAG_IMPLEMENTS:
currentClass.addImplInterface(parser.getAttributeValue(null,ATTRIBUTE_NAME));
break;
case TAG_CONSTRUCTOR:
JDiffConstructor constructor=loadConstructorInfo(parser,currentClass);
currentClass.addConstructor(constructor);
currentMethod=constructor;
break;
case TAG_METHOD:
currentMethod=loadMethodInfo(currentClass.getClassName(),parser);
currentClass.addMethod(currentMethod);
break;
case TAG_PARAM:
currentMethod.addParam(parser.getAttributeValue(null,ATTRIBUTE_TYPE));
break;
case TAG_EXCEPTION:
currentMethod.addException(parser.getAttributeValue(null,ATTRIBUTE_TYPE));
break;
case TAG_FIELD:
JDiffField field=loadFieldInfo(currentClass.getClassName(),parser);
currentClass.addField(field);
break;
default :
throw new RuntimeException("unknow tag exception:" + tagname);
}
}
}
| Signature test entry point. |
protected void addIndexInfo(IndexInfo index){
indexes.put(index.id,index);
}
| Add an index. |
public int addIndxCV(String cvName,String piCv,int piVal,String siCv,int siVal,String iCv,boolean readOnly,boolean infoOnly,boolean writeOnly){
int existingRow=getCvByName(cvName);
int row;
if (existingRow == -1) {
row=_numRows++;
CvValue indxCv=new CvValue(cvName,cvName,piCv,piVal,siCv,siVal,iCv,mProgrammer);
_indxCvAllMap.put(cvName,indxCv);
if (log.isDebugEnabled()) {
log.debug("created new indexed CV with name " + cvName);
}
indxCv.setReadOnly(readOnly);
indxCv.setInfoOnly(infoOnly);
_indxCvAllVector.setElementAt(indxCv,row);
_indxCvDisplayVector.addElement(indxCv);
indxCv.addPropertyChangeListener(this);
JButton bw=new JButton("Write");
_indxWriteButtons.addElement(bw);
JButton br=new JButton("Read");
_indxReadButtons.addElement(br);
JButton bc=new JButton("Compare");
_indxCompareButtons.addElement(bc);
if (infoOnly || readOnly) {
if (writeOnly) {
bw.setEnabled(true);
bw.setActionCommand("W" + row);
bw.addActionListener(this);
}
else {
bw.setEnabled(false);
}
if (infoOnly) {
br.setEnabled(false);
bc.setEnabled(false);
}
else {
br.setEnabled(true);
br.setActionCommand("R" + row);
br.addActionListener(this);
bc.setEnabled(true);
bc.setActionCommand("C" + row);
bc.addActionListener(this);
}
}
else {
bw.setEnabled(true);
bw.setActionCommand("W" + row);
bw.addActionListener(this);
if (writeOnly) {
br.setEnabled(false);
bc.setEnabled(false);
}
else {
br.setEnabled(true);
br.setActionCommand("R" + row);
br.addActionListener(this);
bc.setEnabled(true);
bc.setActionCommand("C" + row);
bc.addActionListener(this);
}
}
if (log.isDebugEnabled()) {
log.debug("addIndxCV adds row at " + row);
}
fireTableDataChanged();
}
else {
if (log.isDebugEnabled()) {
log.debug("addIndxCV finds existing row of " + existingRow + " with numRows "+ _numRows);
}
row=existingRow;
}
if (row > -1 && row < _indxCvAllVector.size()) {
CvValue indxcv=_indxCvAllVector.elementAt(row);
if (readOnly) {
indxcv.setReadOnly(readOnly);
}
if (infoOnly) {
indxcv.setReadOnly(infoOnly);
indxcv.setInfoOnly(infoOnly);
}
if (writeOnly) {
indxcv.setWriteOnly(writeOnly);
}
}
return row;
}
| return is the current row or the row of an existing Indexed CV |
@SuppressWarnings("unchecked") public static <T>T[] emptyArray(Class<T> kind){
if (kind == Object.class) {
return (T[])EMPTY;
}
int bucket=((System.identityHashCode(kind) / 8) & 0x7FFFFFFF) % CACHE_SIZE;
Object cache=sCache[bucket];
if (cache == null || cache.getClass().getComponentType() != kind) {
cache=Array.newInstance(kind,0);
sCache[bucket]=cache;
}
return (T[])cache;
}
| Returns an empty array of the specified type. The intent is that it will return the same empty array every time to avoid reallocation, although this is not guaranteed. |
private void createSampler(){
this.sampler=glGenSamplers();
glSamplerParameteri(this.sampler,GL_TEXTURE_MIN_FILTER,GL_NEAREST);
glSamplerParameteri(this.sampler,GL_TEXTURE_MAG_FILTER,GL_NEAREST);
}
| Create the sampler to sample the framebuffer texture within the shader. |
public boolean isSetAuthChallengeResponse(){
return this.authChallengeResponse != null;
}
| Returns true if field authChallengeResponse is set (has been assigned a value) and false otherwise |
public final Coords translated(int dir){
return translated(dir,1);
}
| Returns a new coordinate that represents the coordinate 1 unit in the specified direction. |
protected int hash(Object key){
int h=key.hashCode();
h+=~(h << 9);
h^=(h >>> 14);
h+=(h << 4);
h^=(h >>> 10);
return h;
}
| Gets the hash code for the key specified. This implementation uses the additional hashing routine from JDK1.4. Subclasses can override this to return alternate hash codes. |
public void deleteTransit(Transit z){
deregister(z);
z.dispose();
}
| Remove an existing Transit |
public UserConnection user(){
return this.userConnection;
}
| Get the user associated with this Packet |
public void removeDeliveredMessage(String id){
if (this.hasMessage(id)) {
for ( Connection c : this.sendingConnections) {
if (c.getMessage().getId().equals(id)) {
c.abortTransfer();
}
}
this.deleteMessage(id,false);
}
}
| Removes the message with the given ID from this router, if the router has that message; otherwise does nothing. If the router was transferring the message, the transfer is aborted. |
public void sortRenderQueue(){
sort(ritems,rscores,rsize);
}
| Sort the rendering queue. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.