code
stringlengths 10
174k
| nl
stringlengths 3
129k
|
---|---|
private RE concat(RE x,RE y){
if (rec == Recursion.RIGHT) {
return x.concat(y);
}
else {
return y.concat(x);
}
}
| Given a pair of regular expressions, concatenate them in a manner consistent with this production's recursion form (left- or right-recursive). |
public boolean updateEntry(int i,File file){
if (file == null) {
log.warning("No File");
return false;
}
if (!file.exists() || file.isDirectory() || !file.canRead()) {
log.warning("not added - " + file + ", Exists="+ file.exists()+ ", Directory="+ file.isDirectory());
return false;
}
log.fine("updateEntry - " + file);
String name=file.getName();
byte[] data=null;
try {
FileInputStream fis=new FileInputStream(file);
ByteArrayOutputStream os=new ByteArrayOutputStream();
byte[] buffer=new byte[1024 * 8];
int length=-1;
while ((length=fis.read(buffer)) != -1) os.write(buffer,0,length);
fis.close();
data=os.toByteArray();
os.close();
}
catch ( IOException ioe) {
log.log(Level.SEVERE,"(file)",ioe);
}
return updateEntry(i,data);
}
| Update existing entry |
public boolean shouldRewriteQueryFromText(){
return 0 != (mSearchMode & SEARCH_MODE_QUERY_REWRITE_FROM_TEXT);
}
| Checks whether the text in the query field should come from the suggestion title. |
public static String state(){
String value=_state;
_state="";
return value;
}
| Returns state and clears internal state variable |
public boolean checkForAttributeType(int attType){
int i=0;
while (i < m_Attributes.size()) {
if (attribute(i++).type() == attType) {
return true;
}
}
return false;
}
| Checks for attributes of the given type in the dataset |
public void removeAllTextures(){
for ( WeakReference<CCTexture2D> texSR : textures.values()) {
CCTexture2D tex=texSR.get();
if (tex != null) tex.releaseTexture(CCDirector.gl);
}
textures.clear();
}
| Purges the dictionary of loaded textures. Call this method if you receive the "Memory Warning" In the short term: it will free some resources preventing your app from being killed In the medium term: it will allocate more resources In the long term: it will be the same |
public boolean shouldStartDownload(){
return startDownload;
}
| Should start download. |
public synchronized void throwing(String sourceClass,String sourceMethod,Throwable thrown){
LogRecord record=new LogRecord(Level.FINER,"THROWN");
record.setSourceClassName(sourceClass);
record.setSourceMethodName(sourceMethod);
record.setThrown(thrown);
log(record);
}
| Log throwing an exception. The logging is done using the FINER level. |
protected boolean beforeSave(boolean newRecord){
BigDecimal difference=getTargetQty();
difference=difference.subtract(getConfirmedQty());
difference=difference.subtract(getScrappedQty());
setDifferenceQty(difference);
return true;
}
| Before Save |
public void clear(){
this.size=0;
}
| Sets the receiver's size to zero. In other words, forgets about any internally buffered elements. |
private String toIndentedString(Object o){
if (o == null) {
return "null";
}
return o.toString().replace("\n","\n ");
}
| Convert the given object to string with each line indented by 4 spaces (except the first line). |
@Override public void close() throws java.io.IOException {
flushBase64();
super.close();
buffer=null;
out=null;
}
| Flushes and closes (I think, in the superclass) the stream. |
public SpatialKey(long id,float... minMax){
this.id=id;
this.minMax=minMax;
}
| Create a new key. |
private void updateProgress(String progressLabel,int progress){
if (myHost != null && ((progress != previousProgress) || (!progressLabel.equals(previousProgressLabel)))) {
myHost.updateProgress(progressLabel,progress);
}
previousProgress=progress;
previousProgressLabel=progressLabel;
}
| Used to communicate a progress update between a plugin tool and the main Whitebox user interface. |
Item(final int index,final Item i){
this.index=index;
type=i.type;
intVal=i.intVal;
longVal=i.longVal;
strVal1=i.strVal1;
strVal2=i.strVal2;
strVal3=i.strVal3;
hashCode=i.hashCode;
}
| Constructs a copy of the given item. |
public static double vectorDistance(double[] vec1,double[] vec2,double power){
double oneOverPower=(power == 0 || power == 1.0 || power == 2.0) ? Double.NaN : 1.0 / power;
return vectorDistance(vec1,vec2,power,oneOverPower);
}
| Calculate the p-norm (i.e. length) between two vectors. <p/> See <a href="http://en.wikipedia.org/wiki/Lp_space">Lp space</a> |
@LogMessageDoc(level="ERROR",message="Tried to write OFFlowMod to {switch} but got {error}",explanation="An I/O error occured while trying to write a " + "static flow to a switch",recommendation=LogMessageDoc.CHECK_SWITCH) private void writeFlowModToSwitch(IOFSwitch sw,OFFlowMod flowMod){
try {
sw.write(flowMod,null);
sw.flush();
}
catch ( IOException e) {
log.error("Tried to write OFFlowMod to {} but failed: {}",HexString.toHexString(sw.getId()),e.getMessage());
}
}
| Writes an OFFlowMod to a switch |
public boolean hasAnyProtection(){
if (getRecoverPoint() != null || getContinuousCopies() != null || getSnapshots() != null || getRemoteCopies() != null) {
return true;
}
return false;
}
| Convenience method to tell if any of the subfields have content |
public SwitchPreference(Context context){
this(context,null);
}
| Construct a new SwitchPreference with default style options. |
public void focusGlobalField(){
}
| Focused the editing field of the global comment. TODO(thomasdullien): Focusing still needs to be sorted & made visible somehow. |
private void clean(){
}
| Remove nodes with no connections from the graph. While this does not guarantee that any two nodes in the remaining graph are connected, we can reasonably assume this since typically roads are connected. |
protected Instance convertInstance(Instance instance) throws Exception {
Instance result;
double[] newVals;
Instance tempInst;
double cumulative;
int i;
int j;
double tempval;
int numAttsLowerBound;
newVals=new double[m_OutputNumAtts];
tempInst=(Instance)instance.copy();
m_ReplaceMissingFilter.input(tempInst);
m_ReplaceMissingFilter.batchFinished();
tempInst=m_ReplaceMissingFilter.output();
m_NominalToBinaryFilter.input(tempInst);
m_NominalToBinaryFilter.batchFinished();
tempInst=m_NominalToBinaryFilter.output();
if (m_AttributeFilter != null) {
m_AttributeFilter.input(tempInst);
m_AttributeFilter.batchFinished();
tempInst=m_AttributeFilter.output();
}
if (!m_center) {
m_standardizeFilter.input(tempInst);
m_standardizeFilter.batchFinished();
tempInst=m_standardizeFilter.output();
}
else {
m_centerFilter.input(tempInst);
m_centerFilter.batchFinished();
tempInst=m_centerFilter.output();
}
if (m_HasClass) {
newVals[m_OutputNumAtts - 1]=instance.value(instance.classIndex());
}
if (m_MaxAttributes > 0) {
numAttsLowerBound=m_NumAttribs - m_MaxAttributes;
}
else {
numAttsLowerBound=0;
}
if (numAttsLowerBound < 0) {
numAttsLowerBound=0;
}
cumulative=0;
for (i=m_NumAttribs - 1; i >= numAttsLowerBound; i--) {
tempval=0.0;
for (j=0; j < m_NumAttribs; j++) {
tempval+=m_Eigenvectors[j][m_SortedEigens[i]] * tempInst.value(j);
}
newVals[m_NumAttribs - i - 1]=tempval;
cumulative+=m_Eigenvalues[m_SortedEigens[i]];
if ((cumulative / m_SumOfEigenValues) >= m_CoverVariance) {
break;
}
}
if (instance instanceof SparseInstance) {
result=new SparseInstance(instance.weight(),newVals);
}
else {
result=new DenseInstance(instance.weight(),newVals);
}
return result;
}
| Transform an instance in original (unormalized) format. |
protected void addRedemptionsToCashflows(final List<Double> redemptions){
calculateNotionalsFromCashflows();
redemptions_.clear();
for (int i=1; i < notionalSchedule_.size(); ++i) {
final double R=i < redemptions.size() ? redemptions.get(i) : !redemptions.isEmpty() ? redemptions.get(redemptions.size() - 1) : 100.0;
final double amount=(R / 100.0) * (notionals_.get(i - 1) - notionals_.get(i));
final CashFlow redemption=new SimpleCashFlow(amount,notionalSchedule_.get(i));
cashflows_.add(redemption);
redemptions_.add(redemption);
}
Collections.sort(cashflows_,new EarlierThanCashFlowComparator());
}
| This method can be called by derived classes in order to build redemption payments from the existing cash flows. It must be called after setting up the cashflows_ vector and will fill the notionalSchedule_, notionals_, and redemptions_ data members. If given, the elements of the redemptions vector will multiply the amount of the redemption cash flow. The elements will be taken in base 100, i.e., a redemption equal to 100 does not modify the amount. The cashflows_ vector must contain at least one coupon and must be sorted by date. |
@Deprecated static public void updateState(String taskId,Workflow.StepState state,String message) throws WorkflowException {
WorkflowService.completerUpdateStep(taskId,state,message);
}
| Native call that uses Workflow StepState to express additional states such as EXECUTING, CANCELLED, etc. |
public RedirectException(final String message){
super(message);
}
| Creates a new RedirectException with the specified detail message. |
@Override public String toString(){
if (eIsProxy()) return super.toString();
StringBuffer result=new StringBuffer(fqName != null ? fqName : "");
return result.toString();
}
| <!-- begin-user-doc --> <!-- end-user-doc --> |
public void addToFirst(E ent,double dist,int pos){
firstAssignments.add(new DistanceEntry<>(ent,dist,pos));
}
| Add an entry to the first set. |
public V put(K key,V value){
int hashCode=hash((key == null) ? NULL : key);
int index=hashIndex(hashCode,data.length);
HashEntry<K,V> entry=data[index];
while (entry != null) {
if (entry.hashCode == hashCode && isEqualKey(key,entry.getKey())) {
V oldValue=entry.getValue();
updateEntry(entry,value);
return oldValue;
}
entry=entry.next;
}
addMapping(index,hashCode,key,value);
return null;
}
| Puts a key-value mapping into this map. |
private static void validateBodyLoggingOverrideParamNotUsed(boolean enable,boolean local){
if (!getSoapBodyLoggingOverrideParameter(enable,local).isEmpty()) {
throw new IllegalStateException(getSoapBodyLoggingOverrideParameterName(enable,local) + " should not be used when " + SOAP_BODY_LOGGING_ENABLED+ " is "+ isSoapBodyLoggingEnabled());
}
}
| Check that given parameter is not in use, and if it is throws IllegalStateException |
private void shutdown(){
synchronized (mJobs) {
mProcessJobs=false;
mJobs.notifyAll();
}
}
| Stops the thread pool |
public int indexOf(AbstractOption option){
return options.indexOf(option);
}
| gets the index of an option this can be used for adding options after/before another |
private LogUtil(){
}
| Utility class |
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 |
public static void stop(Context context){
Intent intent=new Intent(context,EspPushService.class);
context.stopService(intent);
}
| Stop EspPushService |
protected void flush() throws IOException {
setFileLength();
}
| Forces any buffered output to be written. |
public void testDoConfigureSetsDefaultPort() throws Exception {
configuration.configure(container);
String config=configuration.getFileHandler().readTextFile(configuration.getHome() + "/config/config.xml","UTF-8");
XMLAssert.assertXpathEvaluatesTo(configuration.getPropertyValue(ServletPropertySet.PORT),"//weblogic:listen-port",config);
}
| Test default port. |
protected void prepare(){
ProcessInfoParameter[] para=getParameter();
for (int i=0; i < para.length; i++) {
String name=para[i].getParameterName();
if (para[i].getParameter() == null) ;
else if (name.equals("EntityType")) p_EntityType=(String)para[i].getParameter();
else if (name.equals("AllTables")) p_AllTables="Y".equals(para[i].getParameter());
else log.log(Level.SEVERE,"Unknown Parameter: " + name);
}
p_AD_Table_ID=getRecord_ID();
}
| Prepare - e.g., get Parameters. |
public static URI buildUri(String uri){
try {
return new URI(uri);
}
catch ( Throwable e) {
Utils.log(Utils.class,Utils.class.getSimpleName(),Level.SEVERE,"Failure building uri %s: %s",uri,Utils.toString(e));
}
return null;
}
| Build new URI based on a canonical URL, i.e., "http://example.com/example") |
public synchronized boolean delete() throws IOException {
close(false);
return nioFile.delete();
}
| Deletes the allocated nodes file. |
public void publishError(Throwable t){
if (logger.isTraceEnabled()) {
logger.trace(this.state + " publishError: " + t);
}
this.state.get().publishError(this,t);
}
| Publishes the given error signal to the subscriber of this publisher. |
public static void d(String msg,Throwable thr){
if (DEBUG) Log.d(TAG,buildMessage(msg),thr);
}
| Send a DEBUG log message and log the exception. |
public ReplDBMSEvent filter(ReplDBMSEvent event) throws ReplicatorException, InterruptedException {
ArrayList<DBMSData> data=event.getData();
if (data == null) return event;
for (Iterator<DBMSData> iterator=data.iterator(); iterator.hasNext(); ) {
DBMSData dataElem=iterator.next();
if (dataElem instanceof RowChangeData) {
RowChangeData rdata=(RowChangeData)dataElem;
for (Iterator<OneRowChange> iterator2=rdata.getRowChanges().iterator(); iterator2.hasNext(); ) {
OneRowChange orc=iterator2.next();
if (filterRowChange(orc.getSchemaName(),orc.getTableName(),orc.getAction())) {
iterator2.remove();
}
}
if (rdata.getRowChanges().isEmpty()) {
iterator.remove();
}
}
else if (dataElem instanceof StatementData) {
StatementData sdata=(StatementData)dataElem;
String schema=null;
String table=null;
int operation=-1;
Object parsingMetadata=sdata.getParsingMetadata();
if (parsingMetadata == null) {
String query=sdata.getQuery();
parsingMetadata=parser.match(query);
sdata.setParsingMetadata(parsingMetadata);
}
if (parsingMetadata != null && parsingMetadata instanceof SqlOperation) {
SqlOperation parsed=(SqlOperation)parsingMetadata;
schema=parsed.getSchema();
table=parsed.getName();
operation=parsed.getOperation();
if (logger.isDebugEnabled()) logger.debug("Parsing found schema = " + schema + " / table = "+ table);
}
if (schema == null) schema=sdata.getDefaultSchema();
if (schema == null) {
if (logger.isDebugEnabled()) {
final String query=sdata.getQuery();
logger.warn("Ignoring query : No schema found for this query from event " + event.getSeqno() + logQuery(query));
}
continue;
}
if (table == null) {
if (logger.isDebugEnabled()) {
final String query=sdata.getQuery();
logger.warn("Ignoring query : No table found for this query from event " + event.getSeqno() + logQuery(query));
}
continue;
}
if (filterStatement(schema,table,operation)) {
iterator.remove();
}
}
}
if (event.getFragno() == 0 && event.getLastFrag() && data.isEmpty()) {
return null;
}
return event;
}
| Filters catalog data using rules from the class header. |
private static Scriptable js_reverse(Context cx,Scriptable thisObj,Object[] args){
if (thisObj instanceof NativeArray) {
NativeArray na=(NativeArray)thisObj;
if (na.denseOnly) {
for (int i=0, j=((int)na.length) - 1; i < j; i++, j--) {
Object temp=na.dense[i];
na.dense[i]=na.dense[j];
na.dense[j]=temp;
}
return thisObj;
}
}
long len=getLengthProperty(cx,thisObj);
long half=len / 2;
for (long i=0; i < half; i++) {
long j=len - i - 1;
Object temp1=getElem(cx,thisObj,i);
Object temp2=getElem(cx,thisObj,j);
setElem(cx,thisObj,i,temp2);
setElem(cx,thisObj,j,temp1);
}
return thisObj;
}
| See ECMA 15.4.4.4 |
public boolean equals(Object other){
if (!(other instanceof TIntIntHashMap)) {
return false;
}
TIntIntHashMap that=(TIntIntHashMap)other;
if (that.size() != this.size()) {
return false;
}
return forEachEntry(new EqProcedure(that));
}
| Compares this map with another map for equality of their stored entries. |
public void updateDirty(){
dirtysteps++;
if (dirtysteps == Integer.MAX_VALUE) {
clearDirty();
}
}
| update the dirty state, that is, decrement the dirty tag by 1 |
private void encounter(Person p1,Person p2){
p1.encounter(p2);
p2.encounter(p1);
}
| When p1 and p2 encounter one another, we call p1.encounter(p2) and vice versa. |
public static void postCollection(){
traceBusy=true;
findDeaths();
traceBusy=false;
trace.process();
}
| Do the work necessary following each garbage collection. This HAS to be called after EACH collection. |
public static GracePeriod forBillingEvent(GracePeriodStatus type,BillingEvent.OneTime billingEvent){
return create(type,billingEvent.getBillingTime(),billingEvent.getClientId(),Key.create(billingEvent));
}
| Constructs a GracePeriod of the given type from the provided one-time BillingEvent. |
@Override public boolean equals(Object object){
if (this == object) {
return true;
}
if (object instanceof Map) {
Map<?,?> map=(Map)object;
if (size() != map.size()) {
return false;
}
Set<Map.Entry<K,V>> set=entrySet();
return set.equals(map.entrySet());
}
return false;
}
| Compares this map with other objects. This map is equal to another map is it represents the same set of mappings. With this map, two mappings are the same if both the key and the value are equal by reference. When compared with a map that is not an IdentityHashMap, the equals method is neither necessarily symmetric (a.equals(b) implies b.equals(a)) nor transitive (a.equals(b) and b.equals(c) implies a.equals(c)). |
public static UiObjectMatcher withTextContaining(String text){
return withTextContaining(text,null);
}
| Find a view based on the text contained within the view. The matching is case-sensitive. |
public void removeRange(int fromIndex,int toIndex){
if (fromIndex >= size || toIndex > size) {
throwException3(fromIndex,toIndex);
}
int moveCount=size - toIndex;
System.arraycopy(data,toIndex,data,fromIndex,moveCount);
size-=(toIndex - fromIndex);
}
| Removes the <code>int</code>s in the specified range from this array object. |
public synchronized void merge(Network network){
super.merge(network);
this.size=-1;
}
| Merge the vertices and relations of the network into this network. |
@Override protected void doRun(){
Jython jython;
Class<?>[] classes;
Object[] params;
String argv;
String arg;
int i;
classes=new Class[]{String.class};
params=new Object[]{m_Owner.getFilename().getPath()};
argv="sys.argv = ['" + Utils.backQuoteChars(m_Owner.getFilename().getPath()) + "'";
for (i=0; i < getArgs().length; i++) {
arg=Utils.backQuoteChars(getArgs()[i]);
argv+=", '" + arg + "'";
}
argv+="]";
jython=new Jython();
jython.invoke("exec",new Class[]{String.class},new Object[]{"import sys"});
jython.invoke("exec",new Class[]{String.class},new Object[]{argv});
jython.invoke("execfile",classes,params);
}
| Performs the actual run. |
public double func(EvolutionState state,double[] xs,int benchmark) throws IllegalArgumentException {
double x=xs[0];
double y=(xs.length > 1 ? xs[1] : 0);
double z=(xs.length > 2 ? xs[2] : 0);
switch (benchmark) {
case KOZA1:
return x * x * x* x + x * x * x + x * x + x;
case KOZA2:
return x * x * x* x* x - 2.0 * x * x* x + x;
case KOZA3:
return x * x * x* x* x* x - 2.0 * x * x* x* x + x * x;
case NGUYEN1:
return x * x * x + x * x + x;
case NGUYEN2:
return x * x * x* x + x * x * x + x * x + x;
case NGUYEN3:
return x * x * x* x* x + x * x * x* x + x * x * x + x * x + x;
case NGUYEN4:
return x * x * x* x* x* x + x * x * x* x* x + x * x * x* x + x * x * x + x * x + x;
case NGUYEN5:
return Math.sin(x * x) * Math.cos(x) - 1.0;
case NGUYEN6:
return Math.sin(x) + Math.sin(x * x + x);
case NGUYEN7:
return Math.log(x + 1) + Math.log(x * x + 1.0);
case NGUYEN8:
return Math.sqrt(x);
case NGUYEN9:
return Math.sin(x) + Math.sin(y * y);
case NGUYEN10:
return 2 * Math.sin(x) * Math.cos(y);
case PAGIE1:
return 1.0 / (1.0 + 1.0 / (x * x * x* x)) + 1.0 / (1.0 + 1.0 / (y * y * y* y));
case PAGIE2:
return 1.0 / (1.0 + 1.0 / (x * x * x* x)) + 1.0 / (1.0 + 1.0 / (y * y * y* y)) + 1.0 / (1.0 + 1.0 / (z * z * z* z));
case KORNS1:
return 1.57 + (24.3 * xs[3]);
case KORNS2:
return 0.23 + (14.2 * ((xs[3] + xs[1]) / (3.0 * xs[4])));
case KORNS3:
return -5.41 + (4.9 * (((xs[3] - xs[0]) + (xs[1] / xs[4])) / (3 * xs[4])));
case KORNS4:
return -2.3 + (0.13 * Math.sin(xs[2]));
case KORNS5:
return 3.0 + (2.13 * Math.log(xs[4]));
case KORNS6:
return 1.3 + (0.13 * Math.sqrt(xs[0]));
case KORNS7:
return 213.80940889 - (213.80940889 * Math.exp(-0.54723748542 * xs[0]));
case KORNS8:
return 6.87 + (11.0 * Math.sqrt(7.23 * xs[0] * xs[3]* xs[4]));
case KORNS9:
return Math.sqrt(xs[0]) / Math.log(xs[1]) * Math.exp(xs[2]) / (xs[3] * xs[3]);
case KORNS10:
return 0.81 + (24.3 * (((2.0 * xs[1]) + (3.0 * (xs[2] * xs[2]))) / ((4.0 * (xs[3] * xs[3] * xs[3])) + (5.0 * (xs[4] * xs[4] * xs[4]* xs[4])))));
case KORNS11:
return 6.87 + (11.0 * Math.cos(7.23 * xs[0] * xs[0]* xs[0]));
case KORNS12:
return 2.0 - (2.1 * (Math.cos(9.8 * xs[0]) * Math.sin(1.3 * xs[4])));
case KORNS13:
return 32.0 - (3.0 * ((Math.tan(xs[0]) / Math.tan(xs[1])) * (Math.tan(xs[2]) / Math.tan(xs[3]))));
case KORNS14:
return 22.0 - (4.2 * ((Math.cos(xs[0]) - Math.tan(xs[1])) * (Math.tanh(xs[2]) / Math.sin(xs[3]))));
case KORNS15:
return 12.0 - (6.0 * ((Math.tan(xs[0]) / Math.exp(xs[1])) * (Math.log(xs[2]) - Math.tan(xs[3]))));
case KEIJZER1:
case KEIJZER2:
case KEIJZER3:
return 0.3 * x * Math.sin(2 * Math.PI * x);
case KEIJZER4:
return x * x * x* Math.exp(-x)* Math.cos(x)* Math.sin(x)* (Math.sin(x) * Math.sin(x) * Math.cos(x) - 1);
case KEIJZER5:
return (30.0 * x * z) / ((x - 10.0) * y * y);
case KEIJZER6:
{
double sum=0;
double fx=Math.floor(x);
for (int i=1; i < fx + 1; i++) sum+=(1.0 / i);
return sum;
}
case KEIJZER7:
return Math.log(x);
case KEIJZER8:
return Math.sqrt(x);
case KEIJZER9:
return asinh(x);
case KEIJZER10:
return Math.pow(x,y);
case KEIJZER11:
return x * y + Math.sin((x - 1.0) * (y - 1.0));
case KEIJZER12:
return x * x * x* x - x * x * x + y * y / 2.0 - y;
case KEIJZER13:
return 6.0 * Math.sin(x) * Math.cos(y);
case KEIJZER14:
return 8.0 / (2.0 + x * x + y * y);
case KEIJZER15:
return x * x * x / 5.0 + y * y * y / 2.0 - y - x;
case VLADISLAVLEVA1:
return Math.exp(-(x - 1) * (x - 1)) / (1.2 + (y - 2.5) * (y - 2.5));
case VLADISLAVLEVA2:
return Math.exp(-x) * x * x* x* Math.cos(x)* Math.sin(x)* (Math.cos(x) * Math.sin(x) * Math.sin(x) - 1);
case VLADISLAVLEVA3:
return Math.exp(-x) * x * x* x* Math.cos(x)* Math.sin(x)* (Math.cos(x) * Math.sin(x) * Math.sin(x) - 1)* (y - 5);
case VLADISLAVLEVA4:
{
double sum=0;
for (int i=0; i < 5; i++) sum+=(xs[i] - 3) * (xs[i] - 3);
return 10.0 / (5.0 + sum);
}
case VLADISLAVLEVA5:
return (30.0 * (x - 1.0) * (z - 1.0)) / (y * y * (x - 10.0));
case VLADISLAVLEVA6:
return 6.0 * Math.sin(x) * Math.cos(y);
case VLADISLAVLEVA7:
return (x - 3.0) * (y - 3.0) + 2 * Math.sin((x - 4.0) * (y - 4.0));
case VLADISLAVLEVA8:
return ((x - 3.0) * (x - 3.0) * (x - 3.0)* (x - 3.0) + (y - 3.0) * (y - 3.0) * (y - 3.0) - (y - 3.0)) / ((y - 2.0) * (y - 2.0) * (y - 2.0)* (y - 2.0) + 10.0);
default :
throw new IllegalArgumentException("Invalid benchmark value " + benchmark);
}
}
| Return the function applied to the given data by benchmark problem. |
public final void update(){
update((String)this.getSelectedItem());
}
| Update the combo box and reselect the current selection. |
private static String readFile(String location) throws IOException {
FileInputStream is=new FileInputStream(new File(location));
BufferedReader br=new BufferedReader(new InputStreamReader(is));
StringBuffer fileContents=new StringBuffer();
String newLine=br.readLine();
while (newLine != null) {
fileContents.append(newLine);
fileContents.append("\r\n");
newLine=br.readLine();
}
br.close();
return fileContents.toString();
}
| Helper method to read a file and return its contents as a text string, with lines separated by "\r\n" (CR+LF) style newlines. |
protected POInfo initPO(Properties ctx){
POInfo poi=POInfo.getPOInfo(ctx,Table_ID,get_TrxName());
return poi;
}
| Load Meta Data |
@Override void decodeAttributeBody(byte[] attributeValue,char offset,char length) throws StunException {
if (length != DATA_LENGTH) {
throw new StunException("length invalid: " + length);
}
family=(char)(attributeValue[offset] & 0xff);
if (family != IPv4 && family != IPv6) {
throw new StunException("invalid family value: " + family);
}
}
| Sets this attribute's fields according to attributeValue array. |
public SecP256K1DsaSigner(final KeyPair keyPair){
this.keyPair=keyPair;
}
| Creates a SECP256K1 DSA signer. |
public boolean hasCategories(){
return super.hasElement(Category.KEY);
}
| Returns whether it has the categories. |
public static PhotoGalleryFragment newInstance(){
PhotoGalleryFragment fragment=new PhotoGalleryFragment();
return fragment;
}
| Use this factory method to create a new instance of this fragment using the provided parameters. |
private void onActionUp(MotionEvent event){
if (isDown) {
this.startX=0F;
this.startY=0F;
this.isDown=false;
}
}
| This method defines processes on MotionEvent.ACTION_DOWN |
public static void FindToken(String token,Vector inputVec,IntPair curLoc,String errorMsg) throws ParseAlgorithmException {
boolean found=false;
while ((!found) && (curLoc.one < inputVec.size())) {
String curLine=GotoNextNonSpace(inputVec,curLoc);
if (curLine.substring(curLoc.two).startsWith(token)) {
int endLoc=curLoc.two + token.length();
if ((endLoc >= curLine.length()) || !(Character.isLetter(curLine.charAt(endLoc)) || (curLine.charAt(endLoc) == '_'))) {
found=true;
curLoc.two=endLoc;
}
}
curLoc.two=NextSpaceCol(curLine,curLoc.two);
}
if (!found) {
throw new ParseAlgorithmException(errorMsg);
}
;
return;
}
| Searches for token, starting from curLoc in the String Vector inputVec, and updates curLoc to the position immediately after the token if it's found. Otherwise, it throws a ParseAlgorithmException. The token must be a sequence of letters, numbers, and "_" characters that is terminated by any other kind of character or the end of a line. See the comments above for an explanation of the arguments. |
public static Date toDate(String datestring,String format){
return parse(datestring,format);
}
| Returns a date from a given string using the provided format. |
public void indexLibrary(IPath path,URL indexURL,final boolean updateIndex){
IndexLocation indexFile=null;
if (indexURL != null) {
if (IS_MANAGING_PRODUCT_INDEXES_PROPERTY) {
indexFile=computeIndexLocation(path,indexURL);
}
else {
indexFile=IndexLocation.createIndexLocation(indexURL);
}
}
IndexRequest request=null;
boolean forceIndexUpdate=IS_MANAGING_PRODUCT_INDEXES_PROPERTY && updateIndex;
request=new AddJarFileToIndex(path,indexFile,this,forceIndexUpdate,javaProject);
if (!isJobWaiting(request)) request(request);
}
| Trigger addition of a library to an index Note: the actual operation is performed in background |
public void runTest() throws Throwable {
Document doc;
NodeList acronymList;
Node testNode;
NamedNodeMap attributes;
Attr titleAttr;
String value;
Text textNode;
Node retval;
Node firstChild;
Node secondChild;
doc=(Document)load("hc_staff",true);
acronymList=doc.getElementsByTagName("acronym");
testNode=acronymList.item(3);
attributes=testNode.getAttributes();
titleAttr=(Attr)attributes.getNamedItem("title");
textNode=doc.createTextNode("terday");
retval=titleAttr.appendChild(textNode);
textNode=doc.createTextNode("");
retval=titleAttr.appendChild(textNode);
((Element)testNode).normalize();
value=titleAttr.getNodeValue();
assertEquals("attrNodeValue","Yesterday",value);
firstChild=titleAttr.getFirstChild();
value=firstChild.getNodeValue();
assertEquals("firstChildValue","Yesterday",value);
secondChild=firstChild.getNextSibling();
assertNull("secondChildIsNull",secondChild);
}
| Runs the test case. |
public GPUImageBoxBlurFilter(){
this(1f);
}
| Construct new BoxBlurFilter with default blur size of 1.0. |
public int[] toArray(){
return codon.clone();
}
| Returns the integer codon representation of this grammar. The returned object is a clone of the internal storage, and thus can be modified independently of this instance. |
private static void raiseOverflowException(Number number,Class<?> targetClass){
throw new IllegalArgumentException("Could not convert number [" + number + "] of type ["+ number.getClass().getName()+ "] to target class ["+ targetClass.getName()+ "]: overflow");
}
| Raise an overflow exception for the given number and target class. |
private static String initialise(Token currentToken,int[][] expectedTokenSequences,String[] tokenImage){
String eol=System.getProperty("line.separator","\n");
StringBuffer expected=new StringBuffer();
int maxSize=0;
for (int i=0; i < expectedTokenSequences.length; i++) {
if (maxSize < expectedTokenSequences[i].length) {
maxSize=expectedTokenSequences[i].length;
}
for (int j=0; j < expectedTokenSequences[i].length; j++) {
expected.append(tokenImage[expectedTokenSequences[i][j]]).append(' ');
}
if (expectedTokenSequences[i][expectedTokenSequences[i].length - 1] != 0) {
expected.append("...");
}
expected.append(eol).append(" ");
}
String retval="Encountered \"";
Token tok=currentToken.next;
for (int i=0; i < maxSize; i++) {
if (i != 0) retval+=" ";
if (tok.kind == 0) {
retval+=tokenImage[0];
break;
}
retval+=" " + tokenImage[tok.kind];
retval+=" \"";
retval+=add_escapes(tok.image);
retval+=" \"";
tok=tok.next;
}
retval+="\" at line " + currentToken.next.beginLine + ", column "+ currentToken.next.beginColumn;
retval+="." + eol;
if (expectedTokenSequences.length == 1) {
retval+="Was expecting:" + eol + " ";
}
else {
retval+="Was expecting one of:" + eol + " ";
}
retval+=expected.toString();
return retval;
}
| It uses "currentToken" and "expectedTokenSequences" to generate a parse error message and returns it. If this object has been created due to a parse error, and you do not catch it (it gets thrown from the parser) the correct error message gets displayed. |
public void processEvent(World world){
}
| Processes the external event. |
@Override public boolean equals(Object obj){
if (obj == this) {
return true;
}
if (!(obj instanceof KeyedValues2DItemKey)) {
return false;
}
KeyedValues2DItemKey that=(KeyedValues2DItemKey)obj;
if (!this.rowKey.equals(that.rowKey)) {
return false;
}
if (!this.columnKey.equals(that.columnKey)) {
return false;
}
return true;
}
| Tests this key for equality with an arbitrary object. |
public VersionException(String s){
super(s);
}
| Constructs a new <code>VersionException</code> with a message string. |
public void handleSetTemperatureClick(int idx){
listener.onSetTemperatureClick(idx);
}
| Handles the temperature click |
public ListProcessesReply(final int packetId,final int errorCode,final ProcessList processList){
super(packetId,errorCode);
if (success()) {
Preconditions.checkNotNull(processList,"IE01062: Process list argument can not be null");
}
else {
if (processList != null) {
throw new IllegalArgumentException("IE01063: Process list argument must be null");
}
}
this.processList=processList;
}
| Creates a new list processes reply. |
protected int calcnCluster(){
return 1;
}
| Calculate the clustering of the hits |
protected void verprestamoExecuteLogic(ActionMapping mapping,ActionForm form,HttpServletRequest request,HttpServletResponse response){
String codigo=((PrestamoForm)form).getId();
if (StringUtils.isEmpty(codigo)) codigo=(String)request.getParameter("idprestamo");
verprestamoCodeLogic(codigo,mapping,form,request,response);
saveCurrentInvocation(KeysClientsInvocations.SOLICITUDES_VER_PRESTAMO,request);
}
| Muestra el detalle de un prestamo. |
private boolean contains(String[] names,String name){
assert name != null;
for (int i=0; i < names.length; i++) {
if (name.equals(names[i])) {
return true;
}
}
return false;
}
| Simple utility method that searchs the given array of Strings for the given string. This method is only called from getExtendedState if the developer has specified a specific state for the component to be in (ie, has "wedged" the component in that state) by specifying they client property "SeaGlass.State". |
public SoftwareModuleEvent(final BaseEntityEventType entityEventType,final SoftwareModule softwareModule){
super(entityEventType,softwareModule);
}
| Creates software module event. |
public boolean isUsePersistentConnections(){
return usePersistentConnections;
}
| Defaults to <code>false</code>, avoiding obscure bugs in the JDK. |
public static Date parseDateStrictly(final String str,final String... parsePatterns) throws ParseException {
return parseDateStrictly(str,null,parsePatterns);
}
| <p>Parses a string representing a date by trying a variety of different parsers.</p> <p>The parse will try each parse pattern in turn. A parse is only deemed successful if it parses the whole of the input string. If no parse patterns match, a ParseException is thrown.</p> The parser parses strictly - it does not allow for dates such as "February 942, 1996". |
private void configureParent(){
EasyMock.expect(myView.getSelectedParent()).andReturn(getClassByName("Parent")).anyTimes();
}
| Makes view to return class "Parent" as selected parent |
private void writeQNameAttribute(java.lang.String namespace,java.lang.String attName,javax.xml.namespace.QName qname,javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException {
java.lang.String attributeNamespace=qname.getNamespaceURI();
java.lang.String attributePrefix=xmlWriter.getPrefix(attributeNamespace);
if (attributePrefix == null) {
attributePrefix=registerPrefix(xmlWriter,attributeNamespace);
}
java.lang.String attributeValue;
if (attributePrefix.trim().length() > 0) {
attributeValue=attributePrefix + ":" + qname.getLocalPart();
}
else {
attributeValue=qname.getLocalPart();
}
if (namespace.equals("")) {
xmlWriter.writeAttribute(attName,attributeValue);
}
else {
registerPrefix(xmlWriter,namespace);
xmlWriter.writeAttribute(namespace,attName,attributeValue);
}
}
| Util method to write an attribute without the ns prefix |
public void play() throws CastException, TransientNetworkDisconnectionException, NoConnectionException {
play(null);
}
| Resumes the playback from where it was left (can be the beginning). |
private void animatePropertyBy(int constantName,float startValue,float byValue){
if (mAnimatorMap.size() > 0) {
Animator animatorToCancel=null;
Set<Animator> animatorSet=mAnimatorMap.keySet();
for ( Animator runningAnim : animatorSet) {
PropertyBundle bundle=mAnimatorMap.get(runningAnim);
if (bundle.cancel(constantName)) {
if (bundle.mPropertyMask == NONE) {
animatorToCancel=runningAnim;
break;
}
}
}
if (animatorToCancel != null) {
animatorToCancel.cancel();
}
}
NameValuesHolder nameValuePair=new NameValuesHolder(constantName,startValue,byValue);
mPendingAnimations.add(nameValuePair);
View v=mView.get();
if (v != null) {
v.removeCallbacks(mAnimationStarter);
v.post(mAnimationStarter);
}
}
| Utility function, called by animateProperty() and animatePropertyBy(), which handles the details of adding a pending animation and posting the request to start the animation. |
public void testUnsupportedCallbackException05(){
myCallback c=new myCallback();
assertNotNull("Callback object is null",c);
UnsupportedCallbackException ucE=new UnsupportedCallbackException(c,null);
assertNull("getMessage() must return null.",ucE.getMessage());
assertEquals("Incorrect callback object was returned",c,ucE.getCallback());
}
| javax.security.auth.callback.UnsupportedCallbackExceptionTest#UnsupportedCallbackException(Callback callback, String msg) Assertion: constructs with not null callback parameter and null message. |
public boolean contains(Key key){
if (key == null) throw new NullPointerException("argument to contains() is null");
return get(key) != null;
}
| Does this symbol table contain the given key? |
public GenericEntry retrieveAccountInfoRequest(String user,String requestId) throws AppsForYourDomainException, IOException, ServiceException {
URL url=new URL(BASE_URL + "account/" + domain+ "/"+ user+ "/"+ requestId);
return getEntry(url,GenericEntry.class);
}
| Retrieves a previously created account/services related information request for the given user. |
public void addCheckObject(RuleDescription object){
this.ruleDescriptions.add(object);
}
| Add another rule description |
public int endObject(){
if (vtable == null || !nested) throw new AssertionError("FlatBuffers: endObject called without startObject");
addInt(0);
int vtableloc=offset();
for (int i=vtable_in_use - 1; i >= 0; i--) {
short off=(short)(vtable[i] != 0 ? vtableloc - vtable[i] : 0);
addShort(off);
}
final int standard_fields=2;
addShort((short)(vtableloc - object_start));
addShort((short)((vtable_in_use + standard_fields) * SIZEOF_SHORT));
int existing_vtable=0;
outer_loop: for (int i=0; i < num_vtables; i++) {
int vt1=bb.capacity() - vtables[i];
int vt2=space;
short len=bb.getShort(vt1);
if (len == bb.getShort(vt2)) {
for (int j=SIZEOF_SHORT; j < len; j+=SIZEOF_SHORT) {
if (bb.getShort(vt1 + j) != bb.getShort(vt2 + j)) {
continue outer_loop;
}
}
existing_vtable=vtables[i];
break outer_loop;
}
}
if (existing_vtable != 0) {
space=bb.capacity() - vtableloc;
bb.putInt(space,existing_vtable - vtableloc);
}
else {
if (num_vtables == vtables.length) vtables=Arrays.copyOf(vtables,num_vtables * 2);
vtables[num_vtables++]=offset();
bb.putInt(bb.capacity() - vtableloc,offset() - vtableloc);
}
nested=false;
return vtableloc;
}
| Finish off writing the object that is under construction. |
public static RectF amendRectF(RectF rectF){
if (rectF.bottom - rectF.top < 1.0f && rectF.bottom > rectF.top) {
float centerY=rectF.centerY();
rectF.top=centerY - 0.5f;
rectF.bottom=centerY + 0.5f;
}
if (rectF.right - rectF.left < 1.0f && rectF.right > rectF.left) {
float centerX=rectF.centerX();
rectF.left=centerX - 0.5f;
rectF.right=centerX + 0.5f;
}
return rectF;
}
| Modifies slightly the rectangle if it's too thin to be drawn on a canvas. |
public ReciprocalFloatFunction(ValueSource source,float m,float a,float b){
this.source=source;
this.m=m;
this.a=a;
this.b=b;
}
| f(source) = a/(m*float(source)+b) |
public static void previousMonth(int year,int month,int[] previousDate){
if (month == 0) {
year--;
month=11;
}
else {
month--;
}
previousDate[0]=year;
previousDate[1]=month;
}
| Set the previous month for the details passed |
@Override protected void onCreate(Bundle savedInstanceState){
setContentView(R.layout.main_activity);
mEditText=(EditText)findViewById(R.id.editText1);
mListView=(ListView)findViewById(R.id.listView1);
mAdapter=new AcronymDataArrayAdapter(this);
mListView.setAdapter(mAdapter);
super.onCreate(savedInstanceState,AcronymOps.class);
}
| Hook method called when a new instance of Activity is created. One time initialization code goes here, e.g., runtime configuration changes. |
public CoordinateSequenceComparator(){
dimensionLimit=Integer.MAX_VALUE;
}
| Creates a comparator which will test all dimensions. |
public Socks5Message(int cmd){
super(cmd,null,0);
data=new byte[3];
data[0]=SOCKS_VERSION;
data[1]=(byte)cmd;
data[2]=0;
}
| Server error response. |
public UnixTerminal() throws IOException {
this(System.in,System.out,Charset.defaultCharset());
}
| Creates a UnixTerminal with default settings, using System.in and System.out for input/output, using the default character set on the system as the encoding and trap ctrl+c signal instead of killing the application. |
public static <T extends AbstractBlockBase<T>>AbstractBlockBase<?>[] computeCodeEmittingOrder(int blockCount,T startBlock){
List<T> order=new ArrayList<>();
BitSet visitedBlocks=new BitSet(blockCount);
PriorityQueue<T> worklist=initializeWorklist(startBlock,visitedBlocks);
computeCodeEmittingOrder(order,worklist,visitedBlocks);
assert checkOrder(order,blockCount);
return order.toArray(new AbstractBlockBase<?>[0]);
}
| Computes the block order used for code emission. |
Node<E> findLast(){
Index<E> q=head;
for (; ; ) {
Index<E> d, r;
if ((r=q.right) != null) {
if (r.indexesDeletedNode()) {
q.unlink(r);
q=head;
}
else q=r;
}
else if ((d=q.down) != null) {
q=d;
}
else {
Node<E> b=q.node;
Node<E> n=b.next;
for (; ; ) {
if (n == null) return b.isBaseHeader() ? null : b;
Node<E> f=n.next;
if (n != b.next) break;
Object v=n.value;
if (v == null) {
n.helpDelete(b,f);
break;
}
if (v == n || b.value == null) break;
b=n;
n=f;
}
q=head;
}
}
}
| Specialized version of find to get last valid node. |
public void yypushback(int number){
if (number > yylength()) zzScanError(ZZ_PUSHBACK_2BIG);
zzMarkedPos-=number;
}
| Pushes the specified amount of characters back into the input stream. They will be read again by then next call of the scanning method |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.