code
stringlengths 10
174k
| nl
stringlengths 3
129k
|
---|---|
public Object createImplementation(){
return new JavaSEPort();
}
| Factory method to create the implementation instance |
public InvalidConfigurationException(){
}
| Creates a new instance of InvalidConfigurationException without a message or cause. |
public static void d(String tag,String msg,Throwable throwable){
if (sLevel > LEVEL_DEBUG) {
return;
}
Log.d(tag,msg,throwable);
}
| Send a DEBUG log message |
public void fireGroupChanged(final NetworkEvent<Group> event,final String changeDescription){
for ( GroupListener listener : groupListeners) {
listener.groupChanged(event,changeDescription);
}
}
| This version of fireGroupChanged fires a pre-set event, which may have an auxiliary object set. |
public long run(String[] args) throws Exception {
int nbatches=Integer.parseInt(args[0]);
int ncycles=Integer.parseInt(args[1]);
StreamBuffer sbuf=new StreamBuffer();
ObjectOutputStream oout=new ObjectOutputStream(sbuf.getOutputStream());
ObjectInputStream oin=new ObjectInputStream(sbuf.getInputStream());
doReps(oout,oin,sbuf,1,ncycles);
long start=System.currentTimeMillis();
doReps(oout,oin,sbuf,nbatches,ncycles);
return System.currentTimeMillis() - start;
}
| Write and read boolean values to/from a stream. The benchmark is run in batches: each "batch" consists of a fixed number of read/write cycles, and the stream is flushed (and underlying stream buffer cleared) in between each batch. Arguments: <# batches> <# cycles per batch> |
void doReps(ObjectOutputStream oout,ObjectInputStream oin,StreamBuffer sbuf,Node[] trees,int nbatches) throws Exception {
int ncycles=trees.length;
for (int i=0; i < nbatches; i++) {
sbuf.reset();
oout.reset();
for (int j=0; j < ncycles; j++) {
oout.writeObject(trees[j]);
}
oout.flush();
for (int j=0; j < ncycles; j++) {
oin.readObject();
}
}
}
| Run benchmark for given number of batches, with each batch containing the given number of cycles. |
public static Toast makeText(Context context,CharSequence text,int duration){
Toast result=new Toast(context);
LayoutInflater inflate=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v=inflate.inflate(com.android.internal.R.layout.transient_notification,null);
TextView tv=(TextView)v.findViewById(com.android.internal.R.id.message);
tv.setText(text);
result.mNextView=v;
result.mDuration=duration;
return result;
}
| Make a standard toast that just contains a text view. |
@DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 12:33:36.626 -0500",hash_original_method="E95F1FE0EF3EE3193ED648BBE2C98991",hash_generated_method="4ECAF7C88D126E501DD7015D1C03A00B") public int describeContents(){
int mask=0;
if (hasFileDescriptors()) {
mask|=Parcelable.CONTENTS_FILE_DESCRIPTOR;
}
return mask;
}
| Report the nature of this Parcelable's contents |
public void runTest() throws Throwable {
Document doc;
NodeList elementList;
Node child;
NodeList employeeIdList;
Node employeeNode;
Node textNode;
boolean state;
doc=(Document)load("staff",false);
elementList=doc.getElementsByTagName("employee");
child=elementList.item(1);
employeeIdList=child.getChildNodes();
employeeNode=employeeIdList.item(1);
textNode=employeeNode.getFirstChild();
state=textNode.hasChildNodes();
assertFalse("nodeHasChildFalseAssert1",state);
}
| Runs the test case. |
public int max_inlinee_size(){
return soot.PhaseOptions.getInt(options,"max-inlinee-size");
}
| Max Inlinee Size -- . Determines the maximum number of Jimple statements for an inlinee method. If a method has more than this number of Jimple statements, then it will not be inlined into other methods. |
public void onEvent(Event e) throws Exception {
if (e.getTarget() == bUp) setLine(-1,false);
else if (e.getTarget() == bDown) setLine(+1,false);
else if (e.getTarget() == bNew) setLine(0,true);
else {
if (e.getTarget() == bDelete) cmd_delete();
else if (e.getTarget().getId().equals(ConfirmPanel.A_OK)) {
if (!cmd_save()) return;
}
dispose();
}
}
| Action Listener |
private static boolean isAssignableFrom(Type from,ParameterizedType to,Map<String,Type> typeVarMap){
if (from == null) {
return false;
}
if (to.equals(from)) {
return true;
}
Class<?> clazz=$Gson$Types.getRawType(from);
ParameterizedType ptype=null;
if (from instanceof ParameterizedType) {
ptype=(ParameterizedType)from;
}
if (ptype != null) {
Type[] tArgs=ptype.getActualTypeArguments();
TypeVariable<?>[] tParams=clazz.getTypeParameters();
for (int i=0; i < tArgs.length; i++) {
Type arg=tArgs[i];
TypeVariable<?> var=tParams[i];
while (arg instanceof TypeVariable<?>) {
TypeVariable<?> v=(TypeVariable<?>)arg;
arg=typeVarMap.get(v.getName());
}
typeVarMap.put(var.getName(),arg);
}
if (typeEquals(ptype,to,typeVarMap)) {
return true;
}
}
for ( Type itype : clazz.getGenericInterfaces()) {
if (isAssignableFrom(itype,to,new HashMap<String,Type>(typeVarMap))) {
return true;
}
}
Type sType=clazz.getGenericSuperclass();
return isAssignableFrom(sType,to,new HashMap<String,Type>(typeVarMap));
}
| Private recursive helper function to actually do the type-safe checking of assignability. |
@Override protected CommandLine createCommandLine(BuilderConfiguration config) throws BuilderException {
final CommandLine commandLine=new CommandLine("grunt");
switch (config.getTaskType()) {
case DEFAULT:
commandLine.add("build");
break;
default :
}
commandLine.add(config.getOptions());
return commandLine;
}
| Creates the grunt build command line |
Vset check(Environment env,Context ctx,Vset vset,Hashtable exp){
checkLabel(env,ctx);
CheckContext newctx=new CheckContext(ctx,this);
Vset vsEntry=vset.copy();
ConditionVars cvars=cond.checkCondition(env,newctx,reach(env,vset),exp);
cond=convert(env,newctx,Type.tBoolean,cond);
vset=body.check(env,newctx,cvars.vsTrue,exp);
vset=vset.join(newctx.vsContinue);
ctx.checkBackBranch(env,this,vsEntry,vset);
vset=newctx.vsBreak.join(cvars.vsFalse);
return ctx.removeAdditionalVars(vset);
}
| Check a while statement |
public int describeContents(){
return 0;
}
| Implement the Parcelable interface |
public void dispose(){
m_buttonSynchronizer.dispose();
}
| Frees allocated resources. |
public void addLocalEventListener(GridLocalEventListener lsnr,int type,@Nullable int... types){
assert lsnr != null;
if (!enterBusy()) return;
try {
getOrCreate(type).add(lsnr);
if (!isRecordable(type)) U.warn(log,"Added listener for disabled event type: " + U.gridEventName(type));
if (types != null) {
for ( int t : types) {
getOrCreate(t).add(lsnr);
if (!isRecordable(t)) U.warn(log,"Added listener for disabled event type: " + U.gridEventName(t));
}
}
}
finally {
leaveBusy();
}
}
| Adds local event listener. |
public Element addAttribute(String attribute_name,Integer attribute_value){
getElementHashEntry().put(attribute_name,attribute_value);
return (this);
}
| Add an attribute to the element. |
public void testGetGameState() throws ChessParseError {
Game game=new Game(null,new TimeControlData());
assertEquals(Game.GameState.ALIVE,game.getGameState());
game.processString("f3");
game.processString("e5");
game.processString("g4");
game.processString("Qh4");
assertEquals(Game.GameState.BLACK_MATE,game.getGameState());
game.setPos(TextIO.readFEN("5k2/5P2/5K2/8/8/8/8/8 b - - 0 1"));
assertEquals(Game.GameState.BLACK_STALEMATE,game.getGameState());
}
| Test of getGameState method, of class Game. |
public void runTest() throws Throwable {
Document doc;
Element elementNode;
String elementValue;
doc=(Document)load("staff",false);
elementNode=doc.getDocumentElement();
elementValue=elementNode.getNodeValue();
assertNull("elementNodeValueNull",elementValue);
}
| Runs the test case. |
public int removeDupStandard(int[] A){
int count=0;
int len=A.length;
for (int i=0; i < len; i++) {
if (count == 0 || A[i] != A[count - 1]) {
A[count++]=A[i];
}
}
return count;
}
| Use count to remember current position |
private static <T>void blockyTandemMergeSortRecursion(final T[] keySrc,final long[] valSrc,final T[] keyDst,final long[] valDst,final int grpStart,final int grpLen,final int blkSize,final int arrLim,final Comparator<? super T> comparator){
assert (grpLen > 0);
if (grpLen == 1) return;
int grpLen1=grpLen / 2;
int grpLen2=grpLen - grpLen1;
assert (grpLen1 >= 1);
assert (grpLen2 >= grpLen1);
final int grpStart1=grpStart;
final int grpStart2=grpStart + grpLen1;
blockyTandemMergeSortRecursion(keyDst,valDst,keySrc,valSrc,grpStart1,grpLen1,blkSize,arrLim,comparator);
blockyTandemMergeSortRecursion(keyDst,valDst,keySrc,valSrc,grpStart2,grpLen2,blkSize,arrLim,comparator);
final int arrStart1=grpStart1 * blkSize;
final int arrStart2=grpStart2 * blkSize;
final int arrLen1=grpLen1 * blkSize;
int arrLen2=grpLen2 * blkSize;
if (arrStart2 + arrLen2 > arrLim) arrLen2=arrLim - arrStart2;
tandemMerge(keySrc,valSrc,arrStart1,arrLen1,arrStart2,arrLen2,keyDst,valDst,arrStart1,comparator);
}
| blockyTandemMergeSortRecursion() is called by blockyTandemMergeSort(). In addition to performing the algorithm's top down recursion, it manages the buffer swapping that eliminates most copying. It also maps the input's pre-sorted blocks into the subarrays that are processed by tandemMerge(). |
public boolean equals(Object other){
if (!(other instanceof TFloatIntHashMap)) {
return false;
}
TFloatIntHashMap that=(TFloatIntHashMap)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. |
@DSComment("Package priviledge") @DSBan(DSCat.DEFAULT_MODIFIER) @DSSource({DSSourceKind.NETWORK}) @DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 12:58:46.418 -0500",hash_original_method="0EF2E0F94875209BDFD349217543907F",hash_generated_method="0EF2E0F94875209BDFD349217543907F") CallerInfo markAsEmergency(Context context){
phoneNumber=context.getString(com.android.internal.R.string.emergency_call_dialog_number_for_display);
photoResource=com.android.internal.R.drawable.picture_emergency;
mIsEmergency=true;
return this;
}
| Mark this CallerInfo as an emergency call. |
public GFElement add(GFElement addend) throws RuntimeException {
GF2nPolynomialElement result=new GF2nPolynomialElement(this);
result.addToThis(addend);
return result;
}
| Compute the sum of this element and <tt>addend</tt>. |
@Override public void onRegistered(Context context,String registration){
try {
Log.i(CloudNotesActivity.TAG,"Registered Device Start:" + registration);
getDeviceinfoendpoint().insertDeviceInfo(new DeviceInfo().setDeviceRegistrationID(registration)).execute();
Log.i(CloudNotesActivity.TAG,"Registered Device End:" + registration);
}
catch ( IOException e) {
e.printStackTrace();
}
}
| Called when a registration token has been received. |
public Name toName(String name){
return ast.toName(name);
}
| Convenient shortcut to the owning JavacAST object's toName method. |
public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
request.getSession().setAttribute("school","hualixy");
response.sendRedirect("servlet/SchoolServlet");
return;
}
| The doGet method of the servlet. <br> This method is called when a form has its tag value method equals to get. |
public ByteVector putUTF8(final String s){
int charLength=s.length();
if (charLength > 65535) {
throw new IllegalArgumentException();
}
int len=length;
if (len + 2 + charLength > data.length) {
enlarge(2 + charLength);
}
byte[] data=this.data;
data[len++]=(byte)(charLength >>> 8);
data[len++]=(byte)charLength;
for (int i=0; i < charLength; ++i) {
char c=s.charAt(i);
if (c >= '\001' && c <= '\177') {
data[len++]=(byte)c;
}
else {
length=len;
return encodeUTF8(s,i,65535);
}
}
length=len;
return this;
}
| Puts an UTF8 string into this byte vector. The byte vector is automatically enlarged if necessary. |
public static <T>List<T> asList(@Nullable T t){
return t == null ? Collections.<T>emptyList() : Collections.singletonList(t);
}
| Creates read-only list with given values. |
@Override public void doFilter(ServletRequest request,ServletResponse response,FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpRequest=(HttpServletRequest)request;
HttpServletResponse httpResponse=(HttpServletResponse)response;
if (!httpRequest.getServletPath().matches(excludeUrlPattern)) {
String mId=httpRequest.getParameter(Constants.REQ_PARAM_MARKETPLACE_ID);
if (mId == null || "".equals(mId)) {
mId=(String)httpRequest.getSession().getAttribute(Constants.REQ_PARAM_MARKETPLACE_ID);
}
VOUserDetails voUserDetails=(VOUserDetails)httpRequest.getSession().getAttribute(Constants.SESS_ATTR_USER);
if (mId == null || mId.equals("")) {
chain.doFilter(request,response);
return;
}
MarketplaceConfiguration config=getConfig(mId);
if (config != null && config.isRestricted()) {
if (voUserDetails != null && voUserDetails.getOrganizationId() != null) {
if (!config.getAllowedOrganizations().contains(voUserDetails.getOrganizationId())) {
forwardToErrorPage(httpRequest,httpResponse);
return;
}
else {
chain.doFilter(request,response);
return;
}
}
if (config.hasLandingPage() && !isSAMLAuthentication()) {
chain.doFilter(request,response);
return;
}
}
}
chain.doFilter(request,response);
}
| If the request does not match exclude pattern, it is checked in the context of restricted marketplace. If requested marketplace is restricted, current user is checked if he has access to it. If not the request is forwarded to the page informing about insufficient rights. See web.xml for excluded url pattern. |
@Override public Object clone() throws CloneNotSupportedException {
DateAxis clone=(DateAxis)super.clone();
if (this.dateFormatOverride != null) {
clone.dateFormatOverride=(DateFormat)this.dateFormatOverride.clone();
}
return clone;
}
| Returns a clone of the object. |
public SpeechInputPanel(AudioModule recorder){
this.recorder=recorder;
recorder.attachPanel(this);
setLayout(new BorderLayout());
final JCheckBox checkbox=new JCheckBox("Voice Activity Detection");
add(checkbox,BorderLayout.LINE_START);
Container container=new Container();
container.setLayout(new FlowLayout());
container.add(new JLabel(""));
JButton button=new JButton("<html> Press & hold to record speech </html>");
button.addMouseListener(this);
container.add(button);
container.add(new JLabel(""));
add(container);
slm=new JProgressBar();
slm.setMaximum(2000);
slm.setBorderPainted(true);
slm.setString("System is talking...");
slm.setPreferredSize(new Dimension(200,25));
add(slm,BorderLayout.LINE_END);
this.setBorder(BorderFactory.createEmptyBorder(0,0,0,10));
checkbox.addActionListener(null);
}
| Creates the speech input panel, composed of a press and hold button and a sound level meter. |
void helpDelete(Node<V> b,Node<V> f){
if (f == next && this == b.next) {
if (f == null || f.value != f) appendMarker(f);
else b.casNext(this,f.next);
}
}
| Helps out a deletion by appending marker or unlinking from predecessor. This is called during traversals when value field seen to be null. |
public static boolean isCovered(Mutation mutation){
return testMap.containsKey(mutation);
}
| <p> isCovered </p> |
@Override public void disconnectionNotification(String eventName,Object source){
if (m_listenee == source) {
m_listenee=null;
}
}
| Notify this object that it has been deregistered as a listener with a source for named event. This object is responsible for recording this fact. |
public static List<String> split(String str,String delim,int limit){
List<String> splitList=null;
String[] st=null;
if (str == null) return splitList;
if (delim != null) st=Pattern.compile(delim).split(str,limit);
else st=str.split("\\s");
if (st != null && st.length > 0) {
splitList=new LinkedList<String>();
for (int i=0; i < st.length; i++) splitList.add(st[i]);
}
return splitList;
}
| Splits a String on a delimiter into a List of Strings. |
protected Vector<String> determineColumnNames(String list,String defaultList,Instances inst){
Vector<String> result;
Vector<String> atts;
StringTokenizer tok;
int i;
String item;
atts=new Vector<String>();
for (i=0; i < inst.numAttributes(); i++) {
atts.add(inst.attribute(i).name().toLowerCase());
}
result=new Vector<String>();
tok=new StringTokenizer(list,",");
while (tok.hasMoreTokens()) {
item=tok.nextToken().toLowerCase();
if (atts.contains(item)) {
result.add(item);
}
else {
result.clear();
break;
}
}
if (result.size() == 0) {
tok=new StringTokenizer(defaultList,",");
while (tok.hasMoreTokens()) {
result.add(tok.nextToken().toLowerCase());
}
}
return result;
}
| Returns a vector with column names of the dataset, listed in "list". If a column cannot be found or the list is empty the ones from the default list are returned. |
public static void hideToast(){
if (null != toast) {
toast.cancel();
}
}
| Hide the toast, if any. |
public void testCalculateContainerArtifactId(){
assertEquals("cargo-core-container-jboss",AbstractCargoMojo.calculateContainerArtifactId("jboss42x"));
assertEquals("cargo-core-container-oc4j",AbstractCargoMojo.calculateContainerArtifactId("oc4j10x"));
assertEquals("cargo-core-container-liberty",AbstractCargoMojo.calculateContainerArtifactId("liberty"));
}
| Test the calculation of container artifact IDs. |
private boolean hasIdAttribute(Attributes a){
for (int i=0; i < a.getLength(); i++) {
if (a.getQName(i).equals("id")) {
return true;
}
}
return false;
}
| <p>Check element to make sure that the id attribute is present.</p> |
@DSComment("Private Method") @DSBan(DSCat.PRIVATE_METHOD) @DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 12:55:27.391 -0500",hash_original_method="769119032395AFB8B9E88BC54405133A",hash_generated_method="4B6E1E27D98E77409B64EB34497F78A1") private void sendMessage(byte[] msg,boolean retry) throws IOException {
Socket sock=this.sipStack.ioHandler.sendBytes(this.getMessageProcessor().getIpAddress(),this.peerAddress,this.peerPort,this.peerProtocol,msg,retry,this);
if (sock != mySock && sock != null) {
try {
if (mySock != null) mySock.close();
}
catch ( IOException ex) {
}
mySock=sock;
this.myClientInputStream=mySock.getInputStream();
Thread thread=new Thread(this);
thread.setDaemon(true);
thread.setName("TLSMessageChannelThread");
thread.start();
}
}
| Send message to whoever is connected to us. Uses the topmost via address to send to. |
protected boolean isOuterBoundaryValid(){
return this.boundaries.size() > 0 && this.boundaries.get(0).size() > 2;
}
| Indicates whether this shape's outer boundary exists and has more than two points. |
@Override protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
Log.d(TAG,"onCreate(): activity re-created");
}
else {
Log.d(TAG,"onCreate(): activity created anew");
}
}
| Hook method called when a new instance of Activity is created. One time initialization code should go here e.g. UI layout, some class scope variable initialization. if finish() is called from onCreate no other lifecycle callbacks are called except for onDestroy(). |
public SQLWarning(String reason,String SQLState,Throwable cause){
super(reason,SQLState,cause);
}
| Creates an SQLWarning object. The Reason string is set to reason, the SQLState string is set to given SQLState and the Error Code is set to 0, cause is set to the given cause |
@LogMessageDoc(level="WARN",message="Reasserting master role on switch {SWITCH}, " + "likely a configruation error with multiple masters",explanation="The controller keeps getting permission error " + "from switch, likely due to switch connected to another " + "controller also in master mode",recommendation=LogMessageDoc.CHECK_SWITCH) synchronized void sendRoleRequestIfNotPending(OFControllerRole role,long xid) throws IOException {
long now=System.nanoTime();
if (now - lastAssertTimeNs < assertTimeIntervalNs) {
return;
}
lastAssertTimeNs=now;
if (assertTimeIntervalNs < MAX_ASSERT_TIME_INTERVAL_NS) {
assertTimeIntervalNs<<=1;
}
else if (role == OFControllerRole.ROLE_MASTER) {
log.warn("Reasserting master role on switch {}, " + "likely a switch config error with multiple masters",role,sw);
}
if (!requestPending) sendRoleRequest(role,xid);
else switchManagerCounters.roleNotResentBecauseRolePending.increment();
}
| Send a role request for the given role only if no other role request is currently pending. |
public void checkInterval(IInterval interval){
int begin=interval.getLeft();
int end=interval.getRight();
if (begin >= end) {
throw new IllegalArgumentException("Invalid SegmentTreeNode insert: begin (" + begin + ") must be strictly less than end ("+ end+ ")");
}
}
| Used to validate IInterval before being incorporated into this data structure. |
public void testAddPropertyChangeListener(){
PropertyChangeListener l=null;
AbstractThrottle instance=new AbstractThrottleImpl();
instance.addPropertyChangeListener(l);
}
| Test of addPropertyChangeListener method, of class AbstractThrottle. |
public static int runJava(List<String> commands) throws Exception {
return runJava(commands,DEFAULT_WAIT_TIME);
}
| Runs java command with provided arguments. Caller should not pass java command in the argument list. |
private void printInvoices(){
if (m_ids == null) return;
if (!ADialog.ask(m_WindowNo,this,"PrintInvoices")) return;
m_messageText.append("<p>").append(Msg.getMsg(Env.getCtx(),"PrintInvoices")).append("</p>");
message.setText(m_messageText.toString());
int retValue=ADialogDialog.A_CANCEL;
do {
for (int i=0; i < m_ids.length; i++) {
int AD_Invoice_ID=m_ids[i];
ReportCtl.startDocumentPrint(ReportEngine.INVOICE,AD_Invoice_ID,this,Env.getWindowNo(this),true);
}
ADialogDialog d=new ADialogDialog(this,Env.getHeader(Env.getCtx(),m_WindowNo),Msg.getMsg(Env.getCtx(),"PrintoutOK?"),JOptionPane.QUESTION_MESSAGE);
retValue=d.getReturnCode();
}
while (retValue == ADialogDialog.A_CANCEL);
}
| Print Invoices |
@Override public UIViewRoot restoreView(FacesContext context,String viewId,String renderKitId){
if (LOGGER.isLoggable(Level.FINEST)) {
LOGGER.log(Level.FINEST,"restoreView",new Object[]{viewId,renderKitId});
}
UIViewRoot result=null;
ResponseStateManager rsm=RenderKitUtils.getResponseStateManager(context,renderKitId);
Object[] state=(Object[])rsm.getState(context,viewId);
if (state != null && state.length >= 2) {
if (state[0] != null) {
result=restoreTree(context,renderKitId,((Object[])state[0]).clone());
context.setViewRoot(result);
}
if (result != null && state[1] != null) {
result.processRestoreState(context,state[1]);
}
}
return result;
}
| Restore the view. |
public boolean isBefore(MonthDay other){
return compareTo(other) < 0;
}
| Checks if this month-day is before the specified month-day. |
public Days negated(){
return Days.days(FieldUtils.safeNegate(getValue()));
}
| Returns a new instance with the days value negated. |
public static void apply(SharedPreferences.Editor editor){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
editor.apply();
}
else {
editor.commit();
}
}
| use new api to reduce file operate |
public BasicPermission(String name){
super(name);
init(name);
}
| Creates a new BasicPermission with the specified name. Name is the symbolic name of the permission, such as "setFactory", "print.queueJob", or "topLevelWindow", etc. |
public static VcpcFastRunner serializableInstance(){
return new VcpcFastRunner(Dag.serializableInstance(),new Parameters());
}
| Generates a simple exemplar of this class to test serialization. |
@Override public Cursor swapCursor(Cursor newCursor){
Cursor old=super.swapCursor(newCursor);
resetMappings();
return old;
}
| Swaps Cursor and clears list-Cursor mapping. |
protected void mergeSchemas(KMLDocument sourceDocument){
List<KMLSchema> schemaListCopy=new ArrayList<KMLSchema>(this.getSchemas().size());
Collections.copy(schemaListCopy,this.getSchemas());
for ( KMLSchema sourceSchema : sourceDocument.getSchemas()) {
String id=sourceSchema.getId();
if (!WWUtil.isEmpty(id)) {
for ( KMLSchema existingSchema : schemaListCopy) {
String currentId=existingSchema.getId();
if (!WWUtil.isEmpty(currentId) && currentId.equals(id)) this.getSchemas().remove(existingSchema);
}
}
this.getSchemas().add(sourceSchema);
}
}
| Merge a list of incoming schemas with the current list. If an incoming schema has the same ID as an existing one, replace the existing one, otherwise just add the incoming one. |
public InputMismatchException(){
super();
}
| Constructs an <code>InputMismatchException</code> with <tt>null</tt> as its error message string. |
public AttributedString(AttributedCharacterIterator text,int beginIndex,int endIndex,Attribute[] attributes){
if (text == null) {
throw new NullPointerException();
}
int textBeginIndex=text.getBeginIndex();
int textEndIndex=text.getEndIndex();
if (beginIndex < textBeginIndex || endIndex > textEndIndex || beginIndex > endIndex) throw new IllegalArgumentException("Invalid substring range");
StringBuffer textBuffer=new StringBuffer();
text.setIndex(beginIndex);
for (char c=text.current(); text.getIndex() < endIndex; c=text.next()) textBuffer.append(c);
this.text=textBuffer.toString();
if (beginIndex == endIndex) return;
HashSet<Attribute> keys=new HashSet<>();
if (attributes == null) {
keys.addAll(text.getAllAttributeKeys());
}
else {
for (int i=0; i < attributes.length; i++) keys.add(attributes[i]);
keys.retainAll(text.getAllAttributeKeys());
}
if (keys.isEmpty()) return;
Iterator<Attribute> itr=keys.iterator();
while (itr.hasNext()) {
Attribute attributeKey=itr.next();
text.setIndex(textBeginIndex);
while (text.getIndex() < endIndex) {
int start=text.getRunStart(attributeKey);
int limit=text.getRunLimit(attributeKey);
Object value=text.getAttribute(attributeKey);
if (value != null) {
if (value instanceof Annotation) {
if (start >= beginIndex && limit <= endIndex) {
addAttribute(attributeKey,value,start - beginIndex,limit - beginIndex);
}
else {
if (limit > endIndex) break;
}
}
else {
if (start >= endIndex) break;
if (limit > beginIndex) {
if (start < beginIndex) start=beginIndex;
if (limit > endIndex) limit=endIndex;
if (start != limit) {
addAttribute(attributeKey,value,start - beginIndex,limit - beginIndex);
}
}
}
}
text.setIndex(limit);
}
}
}
| Constructs an AttributedString instance with the subrange of the given attributed text represented by AttributedCharacterIterator. Only attributes that match the given attributes will be incorporated into the instance. If the given range produces an empty text, all attributes will be discarded. Note that any attributes wrapped by an Annotation object are discarded for a subrange of the original attribute range. |
public void connect(String address){
BluetoothDevice device=null;
try {
device=mAdapter.getRemoteDevice(address);
}
catch ( IllegalArgumentException e) {
Log.e(TAG,"Device not found!");
}
if (device != null) connect(device);
}
| Connect to a remote Bluetooth device with the specified MAC address. |
public static void upto(Double self,Number to,@ClosureParams(FirstParam.class) Closure closure){
double to1=to.doubleValue();
if (self <= to1) {
for (double i=self; i <= to1; i++) {
closure.call(i);
}
}
else throw new GroovyRuntimeException("The argument (" + to + ") to upto() cannot be less than the value ("+ self+ ") it's called on.");
}
| Iterates from this number up to the given number, inclusive, incrementing by one each time. |
public static void multCol(Matrix A,int j,double c){
multCol(A,j,0,A.rows(),c);
}
| Updates the values of column <tt>j</tt> in the given matrix to be A[:,j] = A[:,j]* c |
public boolean isQuestInState(final String name,final int index,final String... states){
final String questState=getQuest(name,index);
if (questState != null) {
for ( final String state : states) {
if (questState.equals(state)) {
return true;
}
}
}
return false;
}
| Is the named quest in one of the listed states? |
public Object clone(){
try {
Class<?> clazz=this.getClass();
Constructor<?> cons=clazz.getConstructor((Class[])null);
SIPHeaderList<HDR> retval=(SIPHeaderList<HDR>)cons.newInstance((Object[])null);
retval.headerName=this.headerName;
retval.myClass=this.myClass;
return retval.clonehlist(this.hlist);
}
catch ( Exception ex) {
throw new RuntimeException("Could not clone!",ex);
}
}
| make a clone of this header list. |
public JavaModelStatus(int code){
super(ERROR,JavaCore.PLUGIN_ID,code,"JavaModelStatus",null);
this.elements=JavaElement.NO_ELEMENTS;
}
| Constructs an Java model status with no corresponding elements. |
protected boolean canActivate(){
if (this.activated) {
return false;
}
return true;
}
| Checks the activation state of the item for activation. |
public void mergeSortFromTo(int from,int to){
if (size == 0) return;
checkRangeFromTo(from,to,size);
java.util.Arrays.sort(elements,from,to + 1);
}
| Sorts the specified range of the receiver into ascending order, according to the <i>natural ordering</i> of its elements. All elements in this range must implement the <tt>Comparable</tt> interface. Furthermore, all elements in this range must be <i>mutually comparable</i> (that is, <tt>e1.compareTo(e2)</tt> must not throw a <tt>ClassCastException</tt> for any elements <tt>e1</tt> and <tt>e2</tt> in the array).<p> This sort is guaranteed to be <i>stable</i>: equal elements will not be reordered as a result of the sort.<p> The sorting algorithm is a modified mergesort (in which the merge is omitted if the highest element in the low sublist is less than the lowest element in the high sublist). This algorithm offers guaranteed n*log(n) performance, and can approach linear performance on nearly sorted lists. <p><b>You should never call this method unless you are sure that this particular sorting algorithm is the right one for your data set.</b> It is generally better to call <tt>sort()</tt> or <tt>sortFromTo(...)</tt> instead, because those methods automatically choose the best sorting algorithm. |
public SabresQuery<T> whereGraterThan(String key,Object value){
addWhere(key,Where.greaterThan(key,SabresValue.create(value)));
return this;
}
| Add a constraint to the query that requires a particular key's value to be greater than the provided value. |
public OptionSet addOption(Option option){
switch (option.getNumber()) {
case OptionNumberRegistry.IF_MATCH:
addIfMatch(option.getValue());
break;
case OptionNumberRegistry.URI_HOST:
setUriHost(option.getStringValue());
break;
case OptionNumberRegistry.ETAG:
addETag(option.getValue());
break;
case OptionNumberRegistry.IF_NONE_MATCH:
setIfNoneMatch(true);
break;
case OptionNumberRegistry.URI_PORT:
setUriPort(option.getIntegerValue());
break;
case OptionNumberRegistry.LOCATION_PATH:
addLocationPath(option.getStringValue());
break;
case OptionNumberRegistry.URI_PATH:
addUriPath(option.getStringValue());
break;
case OptionNumberRegistry.CONTENT_FORMAT:
setContentFormat(option.getIntegerValue());
break;
case OptionNumberRegistry.MAX_AGE:
setMaxAge(option.getLongValue());
break;
case OptionNumberRegistry.URI_QUERY:
addUriQuery(option.getStringValue());
break;
case OptionNumberRegistry.ACCEPT:
setAccept(option.getIntegerValue());
break;
case OptionNumberRegistry.LOCATION_QUERY:
addLocationQuery(option.getStringValue());
break;
case OptionNumberRegistry.PROXY_URI:
setProxyUri(option.getStringValue());
break;
case OptionNumberRegistry.PROXY_SCHEME:
setProxyScheme(option.getStringValue());
break;
case OptionNumberRegistry.BLOCK1:
setBlock1(option.getValue());
break;
case OptionNumberRegistry.BLOCK2:
setBlock2(option.getValue());
break;
case OptionNumberRegistry.SIZE1:
setSize1(option.getIntegerValue());
break;
case OptionNumberRegistry.SIZE2:
setSize2(option.getIntegerValue());
break;
case OptionNumberRegistry.OBSERVE:
setObserve(option.getIntegerValue());
break;
default :
getOthers().add(option);
}
return this;
}
| Allows adding arbitrary options. Known options are checked if they are repeatable. |
protected ArrayTypeSpecifierImpl(){
super();
}
| <!-- begin-user-doc --> <!-- end-user-doc --> |
public Image flipVertically(boolean maintainOpacity){
return Display.impl.flipImageVertically(this,maintainOpacity);
}
| Flips this image on the vertical axis |
public SetQuestAction(final String questname,final String state){
this.questname=checkNotNull(questname);
this.index=-1;
this.state=state;
}
| Creates a new SetQuestAction. |
private void updateProgress(int progress){
if (myHost != null && progress != previousProgress) {
myHost.updateProgress(progress);
}
previousProgress=progress;
}
| Used to communicate a progress update between a plugin tool and the main Whitebox user interface. |
public ClientsResult calculateAllNodesResult(){
final List<String> childNodePaths=getChildren(electionRootPath,false);
_logger.info("Total peers = {} ",childNodePaths.size());
Collections.sort(childNodePaths);
int index=childNodePaths.indexOf(clientNodePath.substring(clientNodePath.lastIndexOf('/') + 1));
return new ClientsResult(index,childNodePaths.size());
}
| Gets node index and its peer count |
private void ItoOSP(int i,byte[] sp){
sp[0]=(byte)(i >>> 24);
sp[1]=(byte)(i >>> 16);
sp[2]=(byte)(i >>> 8);
sp[3]=(byte)(i >>> 0);
}
| int to octet string. |
private void swap(T[] d,int a,int b){
T t=d[a];
d[a]=d[b];
d[b]=t;
}
| Swap two elements in the array. |
public Schema(Database database,int id,String schemaName,User owner,boolean system){
tablesAndViews=database.newStringMap();
indexes=database.newStringMap();
sequences=database.newStringMap();
constants=database.newStringMap();
functions=database.newStringMap();
initDbObjectBase(database,id,schemaName,Trace.SCHEMA);
this.owner=owner;
this.system=system;
}
| Create a new schema object. |
@Override public void close(){
LogManager.getLogManager().checkAccess();
close(true);
}
| Closes this handler. The tail string of the formatter associated with this handler is written out. A flush operation and a subsequent close operation is then performed upon the output stream. Client applications should not use a handler after closing it. |
public static int writeMessageFully(Message msg,OutputStream out,ByteBuffer buf,MessageWriter writer) throws IOException {
assert msg != null;
assert out != null;
assert buf != null;
assert buf.hasArray();
if (writer != null) writer.setCurrentWriteClass(msg.getClass());
boolean finished=false;
int cnt=0;
while (!finished) {
finished=msg.writeTo(buf,writer);
out.write(buf.array(),0,buf.position());
cnt+=buf.position();
buf.clear();
}
return cnt;
}
| Fully writes communication message to provided stream. |
public final boolean compareAndSet(double expect,double update){
return updater.compareAndSet(this,doubleToRawLongBits(expect),doubleToRawLongBits(update));
}
| Atomically sets the value to the given updated value if the current value is <a href="#bitEquals">bitwise equal</a> to the expected value. |
public byte[] toByteArray(){
return data;
}
| Get bytes representing the internal data structure with which an <code>LongArrayCompressed</code> can be reconstructed. |
public static LineNumberReader openScriptReader(String fileName,String compressionAlgorithm,String cipher,String password,String charset) throws IOException {
try {
InputStream in;
if (cipher != null) {
byte[] key=SHA256.getKeyPasswordHash("script",password.toCharArray());
FileStore store=FileStore.open(null,fileName,"rw",cipher,key);
store.init();
in=new FileStoreInputStream(store,null,compressionAlgorithm != null,false);
in=new BufferedInputStream(in,Constants.IO_BUFFER_SIZE_COMPRESS);
}
else {
in=FileUtils.newInputStream(fileName);
in=new BufferedInputStream(in,Constants.IO_BUFFER_SIZE);
in=CompressTool.wrapInputStream(in,compressionAlgorithm,"script.sql");
if (in == null) {
throw new IOException("Entry not found: script.sql in " + fileName);
}
}
return new LineNumberReader(new InputStreamReader(in,charset));
}
catch ( Exception e) {
throw new IOException(e.getMessage(),e);
}
}
| Open a script reader. |
public void testOpenAndClose(){
for (int i=0; i < SUGGESTION_STARTS; i++) sh.addToUserBigram(pair1);
assertTrue(sh.isUserBigramSuggestion("user",'b',"bigram"));
sh.changeUserBigramLocale(getTestContext(),Locale.FRANCE);
for (int i=0; i < SUGGESTION_STARTS; i++) sh.addToUserBigram(pair3);
assertTrue(sh.isUserBigramSuggestion("locale",'f',"france"));
assertFalse(sh.isUserBigramSuggestion("user",'b',"bigram"));
sh.changeUserBigramLocale(getTestContext(),Locale.US);
assertFalse(sh.isUserBigramSuggestion("locale",'f',"france"));
assertTrue(sh.isUserBigramSuggestion("user",'b',"bigram"));
}
| Test loading correct (locale) bigrams |
public void hidePalette(){
if (palette == null) {
return;
}
if (Environment.getBoolean(Environment.UseInternalFrames)) {
try {
((JInternalFrame)palette).setClosed(true);
}
catch ( java.beans.PropertyVetoException evt) {
com.bbn.openmap.util.Assert.assertExp(false,"Pilot.hidePalette(): internal error!");
}
}
else {
palette.setVisible(false);
}
}
| Hide the Pilot's palette. |
private void assertSchemaColumnsNotEmpty(BusinessObjectFormat businessObjectFormat,BusinessObjectFormatEntity businessObjectFormatEntity){
Assert.notEmpty(businessObjectFormat.getSchema().getColumns(),String.format("No schema columns specified for business object format {%s}.",businessObjectFormatHelper.businessObjectFormatEntityAltKeyToString(businessObjectFormatEntity)));
}
| Asserts that there exists at least one column specified in the business object format schema. |
public static PcRunner serializableInstance(){
return PcRunner.serializableInstance();
}
| Generates a simple exemplar of this class to test serialization. |
private RegexUtil(){
throw new Error("do not instantiate");
}
| This class is a collection of methods; it does not represent anything. |
public AttributedString(String text,Map<? extends Attribute,?> attributes){
if (text == null || attributes == null) {
throw new NullPointerException();
}
this.text=text;
if (text.length() == 0) {
if (attributes.isEmpty()) return;
throw new IllegalArgumentException("Can't add attribute to 0-length text");
}
int attributeCount=attributes.size();
if (attributeCount > 0) {
createRunAttributeDataVectors();
Vector<Attribute> newRunAttributes=new Vector<>(attributeCount);
Vector<Object> newRunAttributeValues=new Vector<>(attributeCount);
runAttributes[0]=newRunAttributes;
runAttributeValues[0]=newRunAttributeValues;
Iterator<? extends Map.Entry<? extends Attribute,?>> iterator=attributes.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<? extends Attribute,?> entry=iterator.next();
newRunAttributes.addElement(entry.getKey());
newRunAttributeValues.addElement(entry.getValue());
}
}
}
| Constructs an AttributedString instance with the given text and attributes. |
public void addItineraries(List<TransitJourneyID> transitJourneyIDs,ZoneId timeZone){
for ( Integer accessIdx : accessIndexes.values()) {
for ( Integer egressIdx : egressIndexes.values()) {
addItinerary(accessIdx,egressIdx,transitJourneyIDs,timeZone);
}
}
}
| Creates itineraries for all access index and egress index combinations |
private void addValue(final byte[] baseKey,final byte[] val){
final byte[] fromKey=baseKey;
final byte[] toKey=SuccessorUtil.successor(fromKey.clone());
final long rangeCount=termsIndex.rangeCount(fromKey,toKey);
if (rangeCount >= Byte.MAX_VALUE) {
throw new RuntimeException("Too many hash collisions: ncoll=" + rangeCount);
}
final byte counter=(byte)rangeCount;
if (rangeCount == 0) {
final byte[] key=keyBuilder.reset().append(fromKey).appendSigned(counter).getKey();
if (termsIndex.insert(key,val) != null) {
throw new AssertionError();
}
c.ninserted.incrementAndGet();
c.totalKeyBytes.addAndGet(key.length);
c.totalValBytes.addAndGet(val.length);
return;
}
final ITupleIterator<?> itr=termsIndex.rangeIterator(fromKey,toKey,0,IRangeQuery.VALS,null);
boolean found=false;
while (itr.hasNext()) {
final ITuple<?> tuple=itr.next();
final byte[] tmp=tuple.getValue();
if (false) System.out.println(getValue(tmp));
if (BytesUtil.bytesEqual(val,tmp)) {
found=true;
break;
}
}
if (found) {
return;
}
if (rangeCount > c.maxCollisions.get()) {
c.maxCollisions.set(rangeCount);
log.warn("MAX COLLISIONS NOW: " + c.maxCollisions.get());
}
final byte[] key=keyBuilder.reset().append(fromKey).appendSigned(counter).getKey();
if (termsIndex.insert(key,val) != null) {
throw new AssertionError();
}
c.ninserted.incrementAndGet();
c.totalKeyBytes.addAndGet(key.length);
c.totalValBytes.addAndGet(val.length);
c.totalCollisions.incrementAndGet();
if (rangeCount > 128) {
log.warn("Collision: hashCode=" + BytesUtil.toString(key) + ", nstmts="+ c.nstmts+ ", nshortLiterals="+ c.nshortLiterals+ ", nshortURIs="+ c.nshortURIs+ ", ninserted="+ c.ninserted+ ", totalCollisions="+ c.totalCollisions+ ", maxCollisions="+ c.maxCollisions+ ", ncollThisTerm="+ rangeCount+ ", resource="+ getValue(val));
}
else if (log.isDebugEnabled()) log.debug("Collision: hashCode=" + BytesUtil.toString(key) + ", nstmts="+ c.nstmts+ ", nshortLiterals="+ c.nshortLiterals+ ", nshortURIs="+ c.nshortURIs+ ", ninserted="+ c.ninserted+ ", totalCollisions="+ c.totalCollisions+ ", maxCollisions="+ c.maxCollisions+ ", ncollThisTerm="+ rangeCount+ ", resource="+ getValue(val));
}
| Insert a record into the TERMS index. |
private void updateProgress(int progress){
if (myHost != null && progress != previousProgress) {
myHost.updateProgress(progress);
}
previousProgress=progress;
}
| Used to communicate a progress update between a plugin tool and the main Whitebox user interface. |
public static String localize(String s){
return StatCollector.translateToLocal(s);
}
| Localizes the defined string. |
public void insertRow() throws SQLException {
checkUpdatable();
rowUpdater.insertRow();
fbFetcher.insertRow(rowUpdater.getInsertRow());
notifyRowUpdater();
}
| Inserts the contents of the insert row into this <code>ResultSet</code> objaect and into the database. The cursor must be on the insert row when this method is called. |
public static RestorableSupport newRestorableSupport(String documentElementName){
if (WWUtil.isEmpty(documentElementName)) {
String message=Logging.getMessage("nullValue.DocumentElementNameIsNull");
Logging.logger().severe(message);
throw new IllegalArgumentException(message);
}
javax.xml.parsers.DocumentBuilderFactory docBuilderFactory=javax.xml.parsers.DocumentBuilderFactory.newInstance();
try {
javax.xml.parsers.DocumentBuilder docBuilder=docBuilderFactory.newDocumentBuilder();
org.w3c.dom.Document doc=docBuilder.newDocument();
createDocumentElement(doc,documentElementName);
return new RestorableSupport(doc);
}
catch ( javax.xml.parsers.ParserConfigurationException e) {
String message=Logging.getMessage("generic.ExceptionCreatingParser");
Logging.logger().severe(message);
throw new IllegalStateException(message,e);
}
}
| Creates a new RestorableSupport with no contents. |
private void handleFormChange(){
view.setEnableCustomRevision(view.isCustomRevision());
if (view.isCustomRevision() && view.getRevision().isEmpty()) {
view.setEnableUpdateButton(false);
}
else {
view.setEnableUpdateButton(true);
}
}
| Helper method to enable/disable form fields based on form state changes. |
public boolean isAutoShow(){
return autoShow;
}
| Shows the progress automatically when the request processing is started |
public WaveHeader(){
}
| Construct a WaveHeader, with all fields defaulting to zero. |
public boolean verify(X509Certificate cert,Provider sigProvider) throws NoSuchAlgorithmException, CertificateExpiredException, CertificateNotYetValidException, CMSException {
Time signingTime=getSigningTime();
if (signingTime != null) {
cert.checkValidity(signingTime.getDate());
}
return doVerify(cert.getPublicKey(),sigProvider);
}
| verify that the given certificate successfully handles and confirms the signature associated with this signer and, if a signingTime attribute is available, that the certificate was valid at the time the signature was generated. |
private void flushCache(){
if (scrape != null) {
scrape.flushCache();
}
if (dsScrape != null) {
dsScrape.flushCache();
}
}
| Discards already loaded data. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.