code
stringlengths 10
174k
| nl
stringlengths 3
129k
|
---|---|
protected void startClients(RPCChannelInitializer channelInitializer){
final Bootstrap bootstrap=new Bootstrap();
bootstrap.group(workerGroup).channel(NioSocketChannel.class).option(ChannelOption.SO_REUSEADDR,true).option(ChannelOption.SO_KEEPALIVE,true).option(ChannelOption.TCP_NODELAY,true).option(ChannelOption.SO_SNDBUF,SEND_BUFFER_SIZE).option(ChannelOption.CONNECT_TIMEOUT_MILLIS,CONNECT_TIMEOUT).handler(channelInitializer);
clientBootstrap=bootstrap;
ScheduledExecutorService ses=syncManager.getThreadPool().getScheduledExecutor();
reconnectTask=new SingletonTask(ses,new ConnectTask());
reconnectTask.reschedule(0,TimeUnit.SECONDS);
}
| Connect to remote servers. We'll initiate the connection to any nodes with a lower ID so that there will be a single connection between each pair of nodes which we'll use symmetrically |
@Override @Transient public boolean isFullTextSearchable(){
return true;
}
| Override the gisFeature value.<br> Default to true;<br> If this field is set to false, then the object won't be synchronized with the fullText search engine |
public static long copyFile(File input,OutputStream output) throws IOException {
final FileInputStream fis=new FileInputStream(input);
try {
return IOUtils.copyLarge(fis,output);
}
finally {
fis.close();
}
}
| Copy bytes from a <code>File</code> to an <code>OutputStream</code>. <p> This method buffers the input internally, so there is no need to use a <code>BufferedInputStream</code>. </p> |
private int handleEqual(){
try {
Region line=fDocument.getLineInformationOfOffset(fPosition);
int nonWS=fScanner.findNonWhitespaceBackward(line.getOffset(),JavaHeuristicScanner.UNBOUND);
if (nonWS != Symbols.TokenEOF) {
int tokenAtPreviousLine=fScanner.nextToken(nonWS,nonWS + 1);
if (tokenAtPreviousLine != Symbols.TokenSEMICOLON && tokenAtPreviousLine != Symbols.TokenRBRACE && tokenAtPreviousLine != Symbols.TokenLBRACE && tokenAtPreviousLine != Symbols.TokenEOF) return fPosition;
}
}
catch ( BadLocationException e) {
return fPosition;
}
fIndent=fPrefs.prefContinuationIndent;
return fPosition;
}
| Checks if the statement at position is itself a continuation of the previous, else sets the indentation to Continuation Indent. |
public Drawable loadIcon(PackageManager pm){
return mReceiver.loadIcon(pm);
}
| Load the user-displayed icon for this device admin. |
public UnsupportedAttributeTypeException(String message){
super(message);
}
| Creates a new UnsupportedAttributeTypeException. |
public void updateAsciiStream(int columnIndex,java.io.InputStream x) throws SQLException {
throw new SQLFeatureNotSupportedException(resBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
}
| Updates the designated column with an ascii stream value. The updater methods are used to update column values in the current row or the insert row. The updater methods do not update the underlying database; instead the <code>updateRow</code> or <code>insertRow</code> methods are called to update the database. <P><B>Note:</B> Consult your JDBC driver documentation to determine if it might be more efficient to use a version of <code>updateAsciiStream</code> which takes a length parameter. |
LdapReferralException(Name resolvedName,Object resolvedObj,Name remainingName,String explanation,Hashtable<?,?> envprops,String nextName,int handleReferrals,Control[] reqCtls){
super(explanation);
if (debug) System.out.println("LdapReferralException constructor");
setResolvedName(resolvedName);
setResolvedObj(resolvedObj);
setRemainingName(remainingName);
this.envprops=envprops;
this.nextName=nextName;
this.handleReferrals=handleReferrals;
this.reqCtls=(handleReferrals == LdapClient.LDAP_REF_FOLLOW ? reqCtls : null);
}
| Constructs a new instance of LdapReferralException. |
protected void read(long offset,byte[] b) throws IOException {
rafile.seek(offset);
if (rafile.read(b) != b.length) {
throw new IOException("Not enough bytes available in file " + getPath());
}
}
| Reads a number of bytes from the RRD file on the disk |
public static SQLException unmarshalError(byte[] bytes) throws SQLException {
return unmarshal(bytes);
}
| Unmarshals exception from byte array. |
public static String toHtml(Explanation explanation){
StringBuilder buffer=new StringBuilder();
buffer.append("<ul>\n");
buffer.append("<li>");
buffer.append(explanation.getValue()).append(" = ").append(explanation.getDescription());
buffer.append("<br />\n");
Explanation[] details=explanation.getDetails();
for (int i=0; i < details.length; i++) {
buffer.append(toHtml(details[i]));
}
buffer.append("</li>\n");
buffer.append("</ul>\n");
return buffer.toString();
}
| Render an explanation as HTML. |
public static void reloadIfNeeded(){
if (appPropertiesLastModified >= 0) {
URL appPropertiesUrl=ApplicationProperties.class.getClassLoader().getResource("application.properties");
long appPropTS=-1;
try {
try {
appPropTS=new File(appPropertiesUrl.toURI()).lastModified();
}
catch ( URISyntaxException e) {
appPropTS=new File(appPropertiesUrl.getPath()).lastModified();
}
}
catch ( Exception e) {
}
String customProperties=System.getProperty("tmtbl.custom.properties");
if (customProperties == null) customProperties=props.getProperty("tmtbl.custom.properties","custom.properties");
URL custPropertiesUrl=ApplicationProperties.class.getClassLoader().getResource(customProperties);
long custPropTS=-1;
try {
if (custPropertiesUrl != null) {
try {
custPropTS=new File(custPropertiesUrl.toURI()).lastModified();
}
catch ( URISyntaxException e) {
custPropTS=new File(custPropertiesUrl.getPath()).lastModified();
}
}
else if (new File(customProperties).exists()) {
custPropTS=new File(customProperties).lastModified();
}
}
catch ( Exception e) {
}
if (appPropTS > appPropertiesLastModified || custPropTS > custPropertiesLastModified) load();
}
}
| Reload properties from file application.properties |
@Override public String toString(){
String pattern=printerParser.toString();
pattern=pattern.startsWith("[") ? pattern : pattern.substring(1,pattern.length() - 1);
return pattern;
}
| Returns a description of the underlying formatters. |
public void allowNull(){
setIsNullAllowed(true);
}
| PUBLIC: If <em>all</em> the fields in the database row for the aggregate object are NULL, then, by default, the mapping will place a null in the appropriate source object (as opposed to an aggregate object filled with nulls). This behavior can be explicitly set by calling #allowNull(). To change this behavior, call #dontAllowNull(). Then the mapping will build a new instance of the aggregate object that is filled with nulls and place it in the source object. In either situation, when writing, the mapping will place a NULL in all the fields in the database row for the aggregate object. Note: Any aggregate that has a relationship mapping automatically does not allow null. |
public Array(final Array array,final Set<Address.Flags> flags){
super(1,array.size(),null);
this.addr=new DirectArrayRowAddress(this.$,0,null,0,array.size(),array.flags(),true,1,array.size());
if (array.addr.isContiguous()) {
final int begin=array.addr.col0() + (addr.isFortran() ? 1 : 0);
System.arraycopy(array.$,begin,$,0,this.size());
}
else {
for (int i=0; i < array.size(); i++) {
this.$[i]=array.get(i);
}
}
}
| Creates a Matrix given a double[][] array |
@Override public void eSet(int featureID,Object newValue){
switch (featureID) {
case ExpressionsPackage.BITWISE_XOR_EXPRESSION__LEFT_OPERAND:
setLeftOperand((Expression)newValue);
return;
case ExpressionsPackage.BITWISE_XOR_EXPRESSION__RIGHT_OPERAND:
setRightOperand((Expression)newValue);
return;
}
super.eSet(featureID,newValue);
}
| <!-- begin-user-doc --> <!-- end-user-doc --> |
@Override public boolean add(E obj){
int index=insertionIndex(obj);
if (index < 0) {
return false;
}
Object old=_set[index];
_set[index]=obj;
postInsertHook(old == null);
return true;
}
| Inserts a value into the set. |
public CharacterClassElement createCharacterClassElement(){
CharacterClassElementImpl characterClassElement=new CharacterClassElementImpl();
return characterClassElement;
}
| <!-- begin-user-doc --> <!-- end-user-doc --> |
public String toString(){
return "null";
}
| Get the "null" string value. |
protected Key engineUnwrap(byte[] wrappedKey,String wrappedKeyAlgorithm,int wrappedKeyType) throws InvalidKeyException, NoSuchAlgorithmException {
byte[] encodedKey;
return core.unwrap(wrappedKey,wrappedKeyAlgorithm,wrappedKeyType);
}
| Unwrap a previously wrapped key. |
private boolean movePrimaries(){
Move bestMove=model.findBestPrimaryMove();
if (bestMove == null) {
return false;
}
model.movePrimary(bestMove);
return true;
}
| Move a single primary from one member to another |
public EntityContext newEntityContextSharingTransaction(){
EntityContext entityContext=newEntityContext();
env.joinTransaction(entityContext,this);
return entityContext;
}
| creates a new entity context which shares the same transaction as the current entity context. |
@Override public boolean onTouchEvent(MotionEvent event){
if (!(text instanceof Spanned)) return super.onTouchEvent(event);
Spannable spannedText=(Spannable)text;
boolean handled=false;
if (event.getAction() == MotionEvent.ACTION_DOWN) {
pressedSpan=getPressedSpan(spannedText,event);
if (pressedSpan != null) {
pressedSpan.setPressed(true);
Selection.setSelection(spannedText,spannedText.getSpanStart(pressedSpan),spannedText.getSpanEnd(pressedSpan));
handled=true;
postInvalidateOnAnimation();
}
}
else if (event.getAction() == MotionEvent.ACTION_MOVE) {
TouchableUrlSpan touchedSpan=getPressedSpan(spannedText,event);
if (pressedSpan != null && touchedSpan != pressedSpan) {
pressedSpan.setPressed(false);
pressedSpan=null;
Selection.removeSelection(spannedText);
postInvalidateOnAnimation();
}
}
else if (event.getAction() == MotionEvent.ACTION_UP) {
if (pressedSpan != null) {
pressedSpan.setPressed(false);
pressedSpan.onClick(this);
handled=true;
postInvalidateOnAnimation();
}
pressedSpan=null;
Selection.removeSelection(spannedText);
}
else {
if (pressedSpan != null) {
pressedSpan.setPressed(false);
handled=true;
postInvalidateOnAnimation();
}
pressedSpan=null;
Selection.removeSelection(spannedText);
}
return handled;
}
| This is why you don't implement your own TextView kids; you have to handle everything! |
protected int makePressColor(){
int r=(this.backgroundColor >> 16) & 0xFF;
int g=(this.backgroundColor >> 8) & 0xFF;
int b=(this.backgroundColor >> 0) & 0xFF;
return Color.argb(128,r,g,b);
}
| Make a dark color to ripple effect |
@JsonValue public String value(){
return this.toString();
}
| Returns the name of the trigger type. |
public void testBug23212347() throws Exception {
boolean useSPS=false;
do {
String testCase=String.format("Case [SPS: %s]",useSPS ? "Y" : "N");
createTable("testBug23212347","(id INT)");
Properties props=new Properties();
props.setProperty("useServerPrepStmts",Boolean.toString(useSPS));
Connection testConn=getConnectionWithProps(props);
Statement testStmt=testConn.createStatement();
testStmt.execute("INSERT INTO testBug23212347 VALUES (1)");
this.pstmt=testConn.prepareStatement("SELECT * FROM testBug23212347 WHERE id = 1");
this.rs=this.pstmt.executeQuery();
assertTrue(testCase,this.rs.next());
assertEquals(testCase,1,this.rs.getInt(1));
assertFalse(testCase,this.rs.next());
ResultSetMetaData rsmd=this.pstmt.getMetaData();
assertEquals(testCase,"id",rsmd.getColumnName(1));
this.pstmt=testConn.prepareStatement("SELECT * FROM testBug23212347 WHERE id = ?");
this.pstmt.setInt(1,1);
this.rs=this.pstmt.executeQuery();
assertTrue(testCase,this.rs.next());
assertEquals(testCase,1,this.rs.getInt(1));
assertFalse(this.rs.next());
rsmd=this.pstmt.getMetaData();
assertEquals(testCase,"id",rsmd.getColumnName(1));
}
while (useSPS=!useSPS);
}
| Tests fix for Bug#23212347, ALL API CALLS ON RESULTSET METADATA RESULTS IN NPE WHEN USESERVERPREPSTMTS=TRUE. |
public boolean execute(){
PsiDocumentManager.getInstance(myTarget.getProject()).commitAllDocuments();
if (!myTarget.isValid()) return false;
if ((myTarget instanceof PyQualifiedExpression) && ((((PyQualifiedExpression)myTarget).isQualified()))) return false;
for ( ImportCandidateHolder item : mySources) {
if (!item.getImportable().isValid()) return false;
if (!item.getFile().isValid()) return false;
if (item.getImportElement() != null && !item.getImportElement().isValid()) return false;
}
if (mySources.isEmpty()) {
return false;
}
if (mySources.size() > 1) {
selectSourceAndDo();
}
else doWriteAction(mySources.get(0));
return true;
}
| Alters either target (by qualifying a name) or source (by explicitly importing the name). |
public ModbusUDPTransaction(ModbusRequest request){
setRequest(request);
}
| Constructs a new <tt>ModbusUDPTransaction</tt> instance with a given <tt>ModbusRequest</tt> to be send when the transaction is executed. <p> |
public static String replace(String source,String searchFor,String replaceWith){
if (source.length() < 1) {
return "";
}
int p=0;
while (p < source.length() && (p=source.indexOf(searchFor,p)) >= 0) {
source=source.substring(0,p) + replaceWith + source.substring(p + searchFor.length(),source.length());
p+=replaceWith.length();
}
return source;
}
| Replaces substrings in a string. |
protected void pushBidirectionalVipRoutes(IOFSwitch sw,OFPacketIn pi,FloodlightContext cntx,IPClient client,LBMember member){
IDevice srcDevice=null;
IDevice dstDevice=null;
Collection<? extends IDevice> allDevices=deviceManager.getAllDevices();
for ( IDevice d : allDevices) {
for (int j=0; j < d.getIPv4Addresses().length; j++) {
if (srcDevice == null && client.ipAddress == d.getIPv4Addresses()[j]) srcDevice=d;
if (dstDevice == null && member.address == d.getIPv4Addresses()[j]) {
dstDevice=d;
member.macString=dstDevice.getMACAddressString();
}
if (srcDevice != null && dstDevice != null) break;
}
}
if (srcDevice == null || dstDevice == null) return;
Long srcIsland=topology.getL2DomainId(sw.getId());
if (srcIsland == null) {
log.debug("No openflow island found for source {}/{}",sw.getStringId(),pi.getInPort());
return;
}
boolean on_same_island=false;
boolean on_same_if=false;
for ( SwitchPort dstDap : dstDevice.getAttachmentPoints()) {
long dstSwDpid=dstDap.getSwitchDPID();
Long dstIsland=topology.getL2DomainId(dstSwDpid);
if ((dstIsland != null) && dstIsland.equals(srcIsland)) {
on_same_island=true;
if ((sw.getId() == dstSwDpid) && (pi.getInPort() == dstDap.getPort())) {
on_same_if=true;
}
break;
}
}
if (!on_same_island) {
if (log.isTraceEnabled()) {
log.trace("No first hop island found for destination " + "device {}, Action = flooding",dstDevice);
}
return;
}
if (on_same_if) {
if (log.isTraceEnabled()) {
log.trace("Both source and destination are on the same " + "switch/port {}/{}, Action = NOP",sw.toString(),pi.getInPort());
}
return;
}
SwitchPort[] srcDaps=srcDevice.getAttachmentPoints();
Arrays.sort(srcDaps,clusterIdComparator);
SwitchPort[] dstDaps=dstDevice.getAttachmentPoints();
Arrays.sort(dstDaps,clusterIdComparator);
int iSrcDaps=0, iDstDaps=0;
while ((iSrcDaps < srcDaps.length) && (iDstDaps < dstDaps.length)) {
SwitchPort srcDap=srcDaps[iSrcDaps];
SwitchPort dstDap=dstDaps[iDstDaps];
Long srcCluster=topology.getL2DomainId(srcDap.getSwitchDPID());
Long dstCluster=topology.getL2DomainId(dstDap.getSwitchDPID());
int srcVsDest=srcCluster.compareTo(dstCluster);
if (srcVsDest == 0) {
if (!srcDap.equals(dstDap) && (srcCluster != null) && (dstCluster != null)) {
Route routeIn=routingEngine.getRoute(srcDap.getSwitchDPID(),(short)srcDap.getPort(),dstDap.getSwitchDPID(),(short)dstDap.getPort(),0);
Route routeOut=routingEngine.getRoute(dstDap.getSwitchDPID(),(short)dstDap.getPort(),srcDap.getSwitchDPID(),(short)srcDap.getPort(),0);
if (routeIn != null) {
pushStaticVipRoute(true,routeIn,client,member,sw.getId());
}
if (routeOut != null) {
pushStaticVipRoute(false,routeOut,client,member,sw.getId());
}
}
iSrcDaps++;
iDstDaps++;
}
else if (srcVsDest < 0) {
iSrcDaps++;
}
else {
iDstDaps++;
}
}
return;
}
| used to find and push in-bound and out-bound routes using StaticFlowEntryPusher |
public MutableDateTime roundFloor(){
iInstant.setMillis(getField().roundFloor(iInstant.getMillis()));
return iInstant;
}
| Round to the lowest whole unit of this field. |
public void characters(org.w3c.dom.Node node) throws org.xml.sax.SAXException {
flushPending();
String data=node.getNodeValue();
if (data != null) {
final int length=data.length();
if (length > m_charsBuff.length) {
m_charsBuff=new char[length * 2 + 1];
}
data.getChars(0,length,m_charsBuff,0);
characters(m_charsBuff,0,length);
}
}
| This method gets the nodes value as a String and uses that String as if it were an input character notification. |
private void validateContextId(RequestSecurityTokenResponseType response) throws ParserException {
String contextId=response.getContext();
if (contextId == null) {
log.debug(PROCESS_RSTR_ERROR + ": Context is null");
throw new ParserException(PROCESS_RSTR_ERROR);
}
}
| Helper: validate the Context attribute of the given RequestSecurityTokenResponse (and throw ParseException if it is not valid). |
public boolean start() throws LDIFException, LDAPException, IOException, FileOperationFailedException, GeneralSecurityException, DirectoryOrFileNotFoundException {
if (_isRunning) {
_log.info("LDAP Service is already running.");
return false;
}
_log.info("Starting LDAP Service.");
addLDAPBindCredentials();
_log.info("Importing Schema Ldifs");
importLDAPSchemaLdifs();
List<InMemoryListenerConfig> listenerConfigs=getInMemoryListenerConfigs();
_inMemoryDSConfig.setListenerConfigs(listenerConfigs);
_inMemoryDS=new InMemoryDirectoryServer(_inMemoryDSConfig);
_log.info("Importing Config Ldifs");
importLDAPConfigLdifs();
_log.info("Star listening...");
_inMemoryDS.startListening();
_isRunning=true;
return _isRunning;
}
| Stars the in memory ldap server by reading all the schema and config ldif files. Once all the configurations are loaded to the in memory ldap server, it starts listening for both ldap and ldaps connections from clients. |
public boolean isSet(_Fields field){
if (field == null) {
throw new IllegalArgumentException();
}
switch (field) {
case HEADER:
return isSetHeader();
case NODE:
return isSetNode();
}
throw new IllegalStateException();
}
| Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise |
public static double staticNextDouble(double tau){
synchronized (shared) {
return shared.nextDouble(tau);
}
}
| Returns a random number from the distribution. |
private void insert(float sample){
mBuffer[mBufferPointer++]=sample;
mBufferPointer=mBufferPointer % mBufferSize;
}
| Inserts the sample into the circular buffer, overwriting the oldest value |
public ObjectReference loadObjectReference(Offset offset){
return null;
}
| Loads a reference from the memory location pointed to by the current instance. |
private static void explicitPromotionTest(final ISchemaVersion schemaVersion) throws IOException {
final Writer output=openOutput(schemaVersion,"explicit_promotion",TestType.UNION);
final Random random=new Random(randomLong());
final HLL hll=newHLL(HLLType.EMPTY);
final HLL emptyHLL=newHLL(HLLType.EMPTY);
cumulativeUnionLine(output,hll,emptyHLL,schemaVersion);
for (int i=0; i < (EXPLICIT_THRESHOLD + 500); i++) {
final HLL explicitHLL=newHLL(HLLType.EXPLICIT);
explicitHLL.addRaw(random.nextLong());
cumulativeUnionLine(output,hll,explicitHLL,schemaVersion);
}
output.flush();
output.close();
}
| Unions an EMPTY accumulator with EXPLICIT HLLs, each containing a single random value. Format: cumulative union Tests: - EMPTY U EXPLICIT - EXPLICIT U EXPLICIT - EXPLICIT to SPARSE promotion - SPARSE U EXPLICIT |
public boolean isOverrideContentType(){
return overrideContentType;
}
| Checks whether the content type should be overridden. |
public static CustomTabsHelperFragment attachTo(FragmentActivity activity){
FragmentManager fragmentManager=activity.getSupportFragmentManager();
CustomTabsHelperFragment fragment=(CustomTabsHelperFragment)fragmentManager.findFragmentByTag(FRAGMENT_TAG);
if (fragment == null) {
fragment=new CustomTabsHelperFragment();
fragmentManager.beginTransaction().add(fragment,FRAGMENT_TAG).commit();
}
return fragment;
}
| Ensure that an instance of this fragment is attached to an activity. |
public static int unionSize(long[] x,long[] y){
final int lx=x.length, ly=y.length;
final int min=(lx < ly) ? lx : ly;
int i=0, res=0;
for (; i < min; i++) {
res+=Long.bitCount(x[i] | y[i]);
}
for (; i < lx; i++) {
res+=Long.bitCount(x[i]);
}
for (; i < ly; i++) {
res+=Long.bitCount(y[i]);
}
return res;
}
| Compute the union size of two Bitsets. |
private static ValueAnimator loadAnimator(Context c,Resources res,Resources.Theme theme,AttributeSet attrs,ValueAnimator anim,float pathErrorScale) throws Resources.NotFoundException {
TypedArray arrayAnimator=null;
TypedArray arrayObjectAnimator=null;
if (theme != null) {
arrayAnimator=theme.obtainStyledAttributes(attrs,R.styleable.Animator,0,0);
}
else {
arrayAnimator=res.obtainAttributes(attrs,R.styleable.Animator);
}
if (anim != null) {
if (theme != null) {
arrayObjectAnimator=theme.obtainStyledAttributes(attrs,R.styleable.PropertyAnimator,0,0);
}
else {
arrayObjectAnimator=res.obtainAttributes(attrs,R.styleable.PropertyAnimator);
}
}
if (anim == null) {
anim=new ValueAnimator();
}
parseAnimatorFromTypeArray(anim,arrayAnimator,arrayObjectAnimator);
final int resId=arrayAnimator.getResourceId(R.styleable.Animator_android_interpolator,0);
if (resId > 0) {
anim.setInterpolator(AnimationUtils.loadInterpolator(c,resId));
}
arrayAnimator.recycle();
if (arrayObjectAnimator != null) {
arrayObjectAnimator.recycle();
}
return anim;
}
| Creates a new animation whose parameters come from the specified context and attributes set. |
@DSSink({DSSinkKind.IO}) @DSSpec(DSCat.IO) @DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2014-09-03 14:59:51.855 -0400",hash_original_method="72E9EA9CB4D496A22134A9DE55B8B91A",hash_generated_method="C5CFE166C9FCDBCC793D313229493905") @Override public void write(int b) throws IOException {
write(new byte[]{(byte)b},0,1);
}
| Write a single byte to the stream. |
private int readAnnotationValues(int v,final char[] buf,final boolean named,final AnnotationVisitor av){
int i=readUnsignedShort(v);
v+=2;
if (named) {
for (; i > 0; --i) {
v=readAnnotationValue(v + 2,buf,readUTF8(v,buf),av);
}
}
else {
for (; i > 0; --i) {
v=readAnnotationValue(v,buf,null,av);
}
}
if (av != null) {
av.visitEnd();
}
return v;
}
| Reads the values of an annotation and makes the given visitor visit them. |
@Override public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ptr_list_fragment);
mPullRefreshListFragment=(PullToRefreshListFragment)getSupportFragmentManager().findFragmentById(R.id.frag_ptr_list);
mPullRefreshListView=mPullRefreshListFragment.getPullToRefreshListView();
mPullRefreshListView.setOnRefreshListener(this);
ListView actualListView=mPullRefreshListView.getRefreshableView();
mListItems=new LinkedList<String>();
mListItems.addAll(Arrays.asList(mStrings));
mAdapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,mListItems);
actualListView.setAdapter(mAdapter);
mPullRefreshListFragment.setListShown(true);
}
| Called when the activity is first created. |
public Space S(Domain domain) throws ScopeException {
if (domain.getId().getProjectId().equals(getProject().getId().getProjectId())) {
return new Space(this,domain);
}
else {
throw new ScopeException("Domain '" + domain + "' does not belong to that Universe");
}
}
| return the direct Space associated to a Domain |
private boolean[] sampleLine(Point p1,Point p2,int size){
boolean[] res=new boolean[size];
float d=distance(p1,p2);
float moduleSize=d / (size - 1);
float dx=moduleSize * (p2.x - p1.x) / d;
float dy=moduleSize * (p2.y - p1.y) / d;
float px=p1.x;
float py=p1.y;
for (int i=0; i < size; i++) {
res[i]=image.get(MathUtils.round(px),MathUtils.round(py));
px+=dx;
py+=dy;
}
return res;
}
| Samples a line |
private void moveCursorBackward(int columnsToMove){
}
| This method moves the cursor backward <i>columnsToMove</i> columns, but won't move the cursor past the left edge of the screen, nor will it move the cursor onto the previous line. This method does not cause any scrolling. |
protected void dropCar(PrintWriter file,Car car,boolean isManifest){
if (isManifest) {
StringBuffer buf=new StringBuffer(padAndTruncateString(Setup.getDropCarPrefix(),Setup.getManifestPrefixLength()));
String[] format=Setup.getDropManifestMessageFormat();
boolean isLocal=isLocalMove(car);
if (isLocal) {
buf=new StringBuffer(padAndTruncateString(Setup.getLocalPrefix(),Setup.getManifestPrefixLength()));
format=Setup.getLocalManifestMessageFormat();
}
dropCar(file,car,buf,format,isLocal,isManifest);
}
else {
StringBuffer buf=new StringBuffer(padAndTruncateString(Setup.getSwitchListDropCarPrefix(),Setup.getSwitchListPrefixLength()));
String[] format=Setup.getDropSwitchListMessageFormat();
boolean isLocal=isLocalMove(car);
if (isLocal) {
buf=new StringBuffer(padAndTruncateString(Setup.getSwitchListLocalPrefix(),Setup.getSwitchListPrefixLength()));
format=Setup.getLocalSwitchListMessageFormat();
}
dropCar(file,car,buf,format,isLocal,isManifest);
}
}
| Adds the car's set out string to the output file using the manifest or switch list format |
boolean distribute(){
CacheDistributionAdvisor advisor=this.r.getCacheDistributionAdvisor();
Set recipients=advisor.adviseCacheOpRole(this.role);
if (recipients.isEmpty()) {
return false;
}
ReplyProcessor21 processor=new ReplyProcessor21(this.dm,recipients);
SendQueueMessage msg=new SendQueueMessage();
msg.setRecipients(recipients);
msg.setRegionPath(this.r.getFullPath());
msg.setProcessorId(processor.getProcessorId());
msg.setOperations(this.l);
dm.putOutgoing(msg);
try {
processor.waitForReplies();
}
catch ( InterruptedException ex) {
Thread.currentThread().interrupt();
}
catch ( ReplyException ex) {
ex.handleAsUnexpected();
}
if (msg.getSuccessfulRecipients().isEmpty()) {
return false;
}
this.r.getCachePerfStats().incReliableQueuedOps(-l.size());
this.l.clear();
return true;
}
| Returns true if distribution successful. Also modifies message list by removing messages sent to the required role. |
public void resetLayout(){
Point p0=new Point(0,0);
for (int i=0; i < centerPanel.getComponentCount(); i++) {
Component comp=centerPanel.getComponent(i);
comp.setLocation(p0);
}
centerPanel.validate();
}
| Reset Layout |
public HeaderSection(DexFile file){
super(null,file,4);
HeaderItem item=new HeaderItem();
item.setIndex(0);
this.list=Collections.singletonList(item);
}
| Constructs an instance. The file offset is initially unknown. |
static void testLoadWithoutEncoding() throws IOException {
System.out.println("testLoadWithoutEncoding");
Properties expected=new Properties();
expected.put("foo","bar");
String s="<?xml version=\"1.0\"?>" + "<!DOCTYPE properties SYSTEM \"http://java.sun.com/dtd/properties.dtd\">" + "<properties>"+ "<entry key=\"foo\">bar</entry>"+ "</properties>";
ByteArrayInputStream in=new ByteArrayInputStream(s.getBytes("UTF-8"));
Properties props=new Properties();
props.loadFromXML(in);
if (!props.equals(expected)) {
System.err.println("loaded: " + props + ", expected: "+ expected);
throw new RuntimeException("Test failed");
}
}
| Test loadFromXML with a document that does not have an encoding declaration |
public String toString(){
return (sun.security.util.ResourcesMgr.getString("LoginModuleControlFlag.") + controlFlag);
}
| Return a String representation of this controlFlag. <p> The String has the format, "LoginModuleControlFlag: <i>flag</i>", where <i>flag</i> is either <i>required</i>, <i>requisite</i>, <i>sufficient</i>, or <i>optional</i>. |
protected void loadRMA(int M_RMA_ID,int M_Locator_ID){
loadTableOIS(getRMAData(M_RMA_ID,M_Locator_ID));
}
| Load Data - RMA |
public static String makeLogTag(Class cls){
return makeLogTag(cls.getSimpleName());
}
| Don't use this when obfuscating class names! |
public EOFException(){
super();
}
| Constructs an <code>EOFException</code> with <code>null</code> as its error detail message. |
public BOSHException(final String msg,final Throwable cause){
super(msg,cause);
}
| Creates a new exception isntance with the specified descriptive message and the underlying root cause of the exceptional condition. |
public boolean isIgnoreInactive(){
return this.ignoreInactive;
}
| Returns true if inactive bodies are ignored. |
public EquipmentMonitor(LivingEntity entity){
this.entity=entity;
}
| Create a new monitor for the given entity. |
public FastStringBuffer(){
this(128);
}
| Initializes with a default initial size (128 chars) |
public InstanceNode clone(){
InstanceNode result=new InstanceNode();
result.NodeId=NodeId;
result.NodeClass=NodeClass;
result.BrowseName=BrowseName;
result.DisplayName=DisplayName;
result.Description=Description;
result.WriteMask=WriteMask;
result.UserWriteMask=UserWriteMask;
if (References != null) {
result.References=new ReferenceNode[References.length];
for (int i=0; i < References.length; i++) result.References[i]=References[i].clone();
}
return result;
}
| Deep clone |
public static boolean matchApilevelMax(Integer apilevelMax){
if (apilevelMax == null) return true;
if (getBuildVersion() <= apilevelMax) return true;
else return false;
}
| Match max API level |
public void restoreSession(){
board.restoreSession();
}
| Ask to restore the game from a properties file with confirmation |
public static Number or(Number left,Number right){
return NumberMath.or(left,right);
}
| Bitwise OR together two numbers. |
RegistrarWhoisResponse(Registrar registrar,DateTime timestamp){
super(timestamp);
this.registrar=checkNotNull(registrar,"registrar");
}
| Creates a new WHOIS registrar response on the given registrar object. |
public ToStringBuilder append(final String fieldName,final byte[] array,final boolean fullDetail){
style.append(buffer,fieldName,array,Boolean.valueOf(fullDetail));
return this;
}
| <p>Append to the <code>toString</code> a <code>byte</code> array.</p> <p>A boolean parameter controls the level of detail to show. Setting <code>true</code> will output the array in full. Setting <code>false</code> will output a summary, typically the size of the array. |
private void rehash(){
java.util.Set<MyMap.Entry<K,V>> set=entrySet();
capacity<<=1;
table=new LinkedList[capacity];
size=0;
for ( Entry<K,V> entry : set) {
put(entry.getKey(),entry.getValue());
}
}
| Rehash the map |
public Task createCluster(String projectId,ClusterCreateSpec clusterCreateSpec) throws IOException {
String path=String.format("%s/%s/clusters",getBasePath(),projectId);
HttpResponse response=this.restClient.perform(RestClient.Method.POST,path,serializeObjectAsJson(clusterCreateSpec));
this.restClient.checkResponse(response,HttpStatus.SC_CREATED);
return parseTaskFromHttpResponse(response);
}
| Create a cluster in the specified project. |
@DSSafe(DSCat.SAFE_LIST) @DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2014-09-03 14:59:50.413 -0400",hash_original_method="6FE2119F7B8AFCCC639C0C89F4C2E725",hash_generated_method="F20B5F67B150930B74BEA51952901832") public static float readSwappedFloat(byte[] data,int offset){
return Float.intBitsToFloat(readSwappedInteger(data,offset));
}
| Reads a "float" value from a byte array at a given offset. The value is converted to the opposed endian system while reading. |
private boolean checkConfigurationLocation(URL locationUrl){
if (locationUrl == null || !"file".equals(locationUrl.getProtocol())) return true;
if (Boolean.valueOf(System.getProperty(PROP_CONFIG_AREA + READ_ONLY_AREA_SUFFIX)).booleanValue()) {
return true;
}
File configDir=new File(locationUrl.getFile()).getAbsoluteFile();
if (!configDir.exists()) {
configDir.mkdirs();
if (!configDir.exists()) {
System.getProperties().put(PROP_EXITCODE,"15");
System.getProperties().put(PROP_EXITDATA,"<title>Invalid Configuration Location</title>The configuration area at '" + configDir + "' could not be created. Please choose a writable location using the '-configuration' command line option.");
return false;
}
}
if (!canWrite(configDir)) {
System.getProperties().put(PROP_EXITCODE,"15");
System.getProperties().put(PROP_EXITDATA,"<title>Invalid Configuration Location</title>The configuration area at '" + configDir + "' is not writable. Please choose a writable location using the '-configuration' command line option.");
return false;
}
return true;
}
| Checks whether the given location can be created and is writable. If the system property "osgi.configuration.area.readOnly" is set the check always succeeds. <p>Will set PROP_EXITCODE/PROP_EXITDATA accordingly if check fails.</p> |
public void initOptions(){
BROWSER.setText(URLHandlerSettings.BROWSER.getValue());
}
| Sets the options for the fields in this <tt>PaneItem</tt> when the window is shown. |
public CharSequence loadLabel(PackageManager pm){
if (nonLocalizedLabel != null) {
return nonLocalizedLabel;
}
if (labelRes != 0) {
CharSequence label=pm.getText(packageName,labelRes,getApplicationInfo());
if (label != null) {
return label.toString().trim();
}
}
if (name != null) {
return name;
}
return packageName;
}
| Retrieve the current textual label associated with this item. This will call back on the given PackageManager to load the label from the application. |
@Override public final double classProb(int classIndex,Instance instance,int theSubset) throws Exception {
if (theSubset <= -1) {
double[] weights=weights(instance);
if (weights == null) {
return m_distribution.prob(classIndex);
}
else {
double prob=0;
for (int i=0; i < weights.length; i++) {
prob+=weights[i] * m_distribution.prob(classIndex,i);
}
return prob;
}
}
else {
if (Utils.gr(m_distribution.perBag(theSubset),0)) {
return m_distribution.prob(classIndex,theSubset);
}
else {
return m_distribution.prob(classIndex);
}
}
}
| Gets class probability for instance. |
public synchronized boolean isRunning() throws ReplicatorException {
String command=vmrrControlScript + " status";
if (logger.isDebugEnabled()) {
logger.debug("Checking vmrr process status: " + command);
}
int result=this.execAndReturnExitValue(command);
return (result == 0);
}
| Checks the status of the vmrr process and returns true if it is running. |
private void doSetMode(boolean newValue){
int modeBit=getArg0(0);
switch (modeBit) {
case 4:
mInsertMode=newValue;
break;
case 20:
unknownParameter(modeBit);
break;
case 34:
break;
default :
unknownParameter(modeBit);
break;
}
}
| "CSI P_m h" for set or "CSI P_m l" for reset ANSI mode. |
public static boolean putInt(ContentResolver cr,String name,int value){
return putIntForUser(cr,name,value,UserHandle.myUserId());
}
| Convenience function for updating a single settings value as an integer. This will either create a new entry in the table if the given name does not exist, or modify the value of the existing row with that name. Note that internally setting values are always stored as strings, so this function converts the given value to a string before storing it. |
public static void logOrderState(OrderState orderState){
_log.debug("Status: " + orderState.m_status + " Comms Amt: "+ orderState.m_commission+ " Comms Currency: "+ orderState.m_commissionCurrency+ " Warning txt: "+ orderState.m_warningText+ " Init Margin: "+ orderState.m_initMargin+ " Maint Margin: "+ orderState.m_maintMargin+ " Min Comms: "+ orderState.m_minCommission+ " Max Comms: "+ orderState.m_maxCommission);
}
| Method logOrderState. |
protected void printComponent(Graphics g){
boolean wasHighQuality=m_highQuality;
try {
m_highQuality=true;
paintDisplay((Graphics2D)g,getSize());
}
finally {
m_highQuality=wasHighQuality;
}
}
| Paints the graph to the provided graphics context, for output to a printer. This method does not double buffer the painting, in order to provide the maximum print quality. <b>This method may not be working correctly, and will be repaired at a later date.</b> |
private void pushTerm(BytesRef text) throws IOException {
int limit=Math.min(lastTerm.length(),text.length);
int pos=0;
while (pos < limit && lastTerm.byteAt(pos) == text.bytes[text.offset + pos]) {
pos++;
}
for (int i=lastTerm.length() - 1; i >= pos; i--) {
int prefixTopSize=pending.size() - prefixStarts[i];
if (prefixTopSize >= minItemsInBlock) {
writeBlocks(i + 1,prefixTopSize);
prefixStarts[i]-=prefixTopSize - 1;
}
}
if (prefixStarts.length < text.length) {
prefixStarts=ArrayUtil.grow(prefixStarts,text.length);
}
for (int i=pos; i < text.length; i++) {
prefixStarts[i]=pending.size();
}
lastTerm.copyBytes(text);
}
| Pushes the new term to the top of the stack, and writes new blocks. |
public IOException(java.lang.String s){
}
| Constructs an IOException with the specified detail message. The error message string s can later be retrieved by the method of class java.lang.Throwable. s - the detail message. |
public boolean activateController(){
if (!hasController()) {
throw new IllegalStateException("hasController() == false!");
}
return getController().activate(this);
}
| Activates the installed <code>IIOParamController</code> for this <code>IIOParam</code> object and returns the resulting value. When this method returns <code>true</code>, all values for this <code>IIOParam</code> object will be ready for the next read or write operation. If <code>false</code> is returned, no settings in this object will have been disturbed (<i>i.e.</i>, the user canceled the operation). <p> Ordinarily, the controller will be a GUI providing a user interface for a subclass of <code>IIOParam</code> for a particular plug-in. Controllers need not be GUIs, however. |
public long count(){
return count;
}
| Returns the number of values. |
protected POInfo initPO(Properties ctx){
POInfo poi=POInfo.getPOInfo(ctx,Table_ID,get_TrxName());
return poi;
}
| Load Meta Data |
private void onTrackPointStart(Attributes attributes){
latitude=attributes.getValue(ATTRIBUTE_LAT);
longitude=attributes.getValue(ATTRIBUTE_LON);
altitude=null;
time=null;
}
| On track point start. |
@DSComment("Private Method") @DSBan(DSCat.PRIVATE_METHOD) @DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 13:01:50.767 -0500",hash_original_method="9056910A11B8F7E2130B8014667A5810",hash_generated_method="CEECFF6F08063F48651117F1E4FF30DE") private EncodingUtils(){
}
| This class should not be instantiated. |
private void updateInternal() throws Exception {
long uptime=runtimeMXBean.getUptime();
long cpuTime=proxyClient.getProcessCpuTime();
long gcTime=sumGCTimes();
gcCount=sumGCCount();
if (lastUpTime > 0 && lastCPUTime > 0 && gcTime > 0) {
deltaUptime_=uptime - lastUpTime;
deltaCpuTime_=(cpuTime - lastCPUTime) / 1000000;
deltaGcTime_=gcTime - lastGcTime;
gcLoad=calcLoad(deltaCpuTime_,deltaGcTime_);
cpuLoad=calcLoad(deltaUptime_,deltaCpuTime_);
}
lastUpTime=uptime;
lastCPUTime=cpuTime;
lastGcTime=gcTime;
totalLoadedClassCount_=classLoadingMXBean_.getTotalLoadedClassCount();
threadCount_=threadMXBean.getThreadCount();
}
| calculates internal delta metrics |
public SlotNameInList(List<String> slotNames){
this.slotNames=ImmutableList.copyOf(slotNames);
}
| a predicate which tests that the name of a slot is in list |
@DSComment("no security concern") @DSSafe(DSCat.SAFE_OTHERS) @DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 12:56:40.172 -0500",hash_original_method="C1E29F96DEA4D8E16CD646B2E66B7808",hash_generated_method="49067DA9501AEFB1EA5D29AE5A00F09E") @Override public void close() throws IOException {
}
| Closes this stream. This implementation closes the target stream. |
public SelfSignSslOkHttpStack(Map<String,SSLSocketFactory> factoryMap){
this(new OkHttpClient(),factoryMap);
}
| Create a OkHttpStack with default OkHttpClient. |
protected void putCombination(KeyCombination keyCombination,CombinationCallback combinationCallback){
synchronized (combinations) {
if (!combinations.containsKey(keyCombination)) {
combinations.put(keyCombination,new HashSet<>());
}
synchronized (combinations.get(keyCombination)) {
combinations.get(keyCombination).add(combinationCallback);
}
}
}
| Bind a KeyCombination to a callback function. |
public boolean hasMoney(){
return hasRepeatingExtension(Money.class);
}
| Returns whether it has the monetary value of the total gain. |
private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException {
s.defaultWriteObject();
s.writeInt(size);
int entriesToBeWritten=size;
for (int i=0; entriesToBeWritten > 0; i++) {
if (null != vals[i]) {
s.writeObject(keyUniverse[i]);
s.writeObject(unmaskNull(vals[i]));
entriesToBeWritten--;
}
}
}
| Save the state of the <tt>EnumMap</tt> instance to a stream (i.e., serialize it). |
public int updateId(DatabaseConnection databaseConnection,T data,ID newId,ObjectCache objectCache) throws SQLException {
if (mappedUpdateId == null) {
mappedUpdateId=MappedUpdateId.build(databaseType,tableInfo);
}
return mappedUpdateId.execute(databaseConnection,data,newId,objectCache);
}
| Update an object in the database to change its id to the newId parameter. |
@DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 12:31:09.080 -0500",hash_original_method="54011F5D28450E17A088B23862CB14CB",hash_generated_method="8DBF2298F55DC953A20252E1B37D6A63") public void copyFromUnchecked(short[] d){
mRS.validate();
copy1DRangeFromUnchecked(0,mCurrentCount,d);
}
| Copy an allocation from an array. This variant is not type checked which allows an application to fill in structured data from an array. |
protected static ArrayList<GeoPoint> parseKmlCoordinates(String input){
LinkedList<GeoPoint> tmpCoords=new LinkedList<GeoPoint>();
int i=0;
int tupleStart=0;
int length=input.length();
boolean startReadingTuple=false;
while (i < length) {
char c=input.charAt(i);
if (c == ' ' || c == '\n' || c == '\t') {
if (startReadingTuple) {
String tuple=input.substring(tupleStart,i);
GeoPoint p=parseKmlCoord(tuple);
if (p != null) tmpCoords.add(p);
startReadingTuple=false;
}
}
else {
if (!startReadingTuple) {
startReadingTuple=true;
tupleStart=i;
}
if (i == length - 1) {
String tuple=input.substring(tupleStart,i + 1);
GeoPoint p=parseKmlCoord(tuple);
if (p != null) tmpCoords.add(p);
}
}
i++;
}
ArrayList<GeoPoint> coordinates=new ArrayList<GeoPoint>(tmpCoords.size());
coordinates.addAll(tmpCoords);
return coordinates;
}
| KML coordinates are: lon,lat{,alt} tuples separated by separators (space, tab, cr). |
static public Timestamp addDays(Timestamp day,int offset){
if (day == null) day=new Timestamp(System.currentTimeMillis());
GregorianCalendar cal=new GregorianCalendar();
cal.setTime(day);
cal.set(Calendar.HOUR_OF_DAY,0);
cal.set(Calendar.MINUTE,0);
cal.set(Calendar.SECOND,0);
cal.set(Calendar.MILLISECOND,0);
if (offset != 0) cal.add(Calendar.DAY_OF_YEAR,offset);
java.util.Date temp=cal.getTime();
return new Timestamp(temp.getTime());
}
| Return Day + offset (truncates) |
public static void addPrecisionSawmillRecipe(ItemStack input,ItemStack primaryOutput,ItemStack secondaryOutput,double chance){
addRecipe(Recipe.PRECISION_SAWMILL,new SawmillRecipe(input,primaryOutput,secondaryOutput,chance));
}
| Add a Precision Sawmill recipe. |
public Script parse(URI uri) throws CompilationFailedException, IOException {
return parse(new GroovyCodeSource(uri));
}
| Parses the given script and returns it ready to be run |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.