code
stringlengths 10
174k
| nl
stringlengths 3
129k
|
---|---|
public synchronized int size(){
return this.count;
}
| Return the current size of the byte array. |
private String readString(int len){
byte[] buff=data;
int p=pos;
char[] chars=new char[len];
for (int i=0; i < len; i++) {
int x=buff[p++] & 0xff;
if (x < 0x80) {
chars[i]=(char)x;
}
else if (x >= 0xe0) {
chars[i]=(char)(((x & 0xf) << 12) + ((buff[p++] & 0x3f) << 6) + (buff[p++] & 0x3f));
}
else {
chars[i]=(char)(((x & 0x1f) << 6) + (buff[p++] & 0x3f));
}
}
pos=p;
return new String(chars);
}
| Read a String from the byte array. <p> For performance reasons the internal representation of a String is similar to UTF-8, but not exactly UTF-8. |
public static Class<?> tryGetCanonicalClass(String canonicalName){
try {
return Class.forName(canonicalName);
}
catch ( ClassNotFoundException e) {
return null;
}
}
| Return class for given name or null. |
public void loadTable(PO[] pos){
int row=0;
int col=0;
int poIndex=0;
String columnName;
Object data;
Class columnClass;
if (m_layout == null) {
throw new UnsupportedOperationException("Layout not defined");
}
clearTable();
for (poIndex=0; poIndex < pos.length; poIndex++) {
PO myPO=pos[poIndex];
row=getRowCount();
setRowCount(row + 1);
for (col=0; col < m_layout.length; col++) {
columnName=m_layout[col].getColSQL();
data=myPO.get_Value(columnName);
if (data != null) {
columnClass=m_layout[col].getColClass();
if (isColumnClassMismatch(col,columnClass)) {
throw new ApplicationException("Cannot enter a " + columnClass.getName() + " in column "+ col+ ". "+ "An object of type "+ m_modelHeaderClass.get(col).getSimpleName()+ " was expected.");
}
if (columnClass == IDColumn.class) {
data=new IDColumn(((Integer)data).intValue());
}
else if (columnClass == Double.class) {
data=new Double(((BigDecimal)data).doubleValue());
}
}
getModel().setDataAt(data,row,col);
}
}
autoSize();
if (getShowTotals()) addTotals(m_layout);
this.repaint();
logger.config("Row(array)=" + getRowCount());
return;
}
| Load Table from Object Array. |
private void createPartitionRegion(List vmList,int startIndexForRegion,int endIndexForRegion,int localMaxMemory,int redundancy,boolean firstCreationFlag,boolean multipleVMFlag){
Iterator nodeIterator=vmList.iterator();
while (nodeIterator.hasNext()) {
VM vm=(VM)nodeIterator.next();
vm.invoke(createMultiplePartitionRegion(prPrefix,startIndexForRegion,endIndexForRegion,redundancy,localMaxMemory,firstCreationFlag,multipleVMFlag));
}
}
| This function createas multiple partition regions on nodes specified in the vmList |
public void update(byte[] input,int inOff,int length){
digest.update(input,inOff,length);
}
| update the internal digest with the byte array in |
public int compareTo(SimpleResult o){
int compareValue=(int)Math.signum(distance - ((SimpleResult)o).distance);
if (compareValue == 0 && indexNumber != o.indexNumber) {
return (int)Math.signum(indexNumber - o.indexNumber);
}
return compareValue;
}
| Compare the distance values to allow sorting in a tree map. If the distance value is the same, but the document is different, the index number within the index is used to distinguishing the results. Otherwise the TreeMap implementation wouldn't add the result. |
public static void overScrollBy(final PullToRefreshBase<?> view,final int deltaX,final int scrollX,final int deltaY,final int scrollY,final int scrollRange,final int fuzzyThreshold,final float scaleFactor,final boolean isTouchEvent){
final int deltaValue, currentScrollValue, scrollValue;
switch (view.getPullToRefreshScrollDirection()) {
case HORIZONTAL:
deltaValue=deltaX;
scrollValue=scrollX;
currentScrollValue=view.getScrollX();
break;
case VERTICAL:
default :
deltaValue=deltaY;
scrollValue=scrollY;
currentScrollValue=view.getScrollY();
break;
}
if (view.isPullToRefreshOverScrollEnabled() && !view.isRefreshing()) {
final Mode mode=view.getMode();
if (mode.permitsPullToRefresh() && !isTouchEvent && deltaValue != 0) {
final int newScrollValue=(deltaValue + scrollValue);
if (PullToRefreshBase.DEBUG) {
Log.d(LOG_TAG,"OverScroll. DeltaX: " + deltaX + ", ScrollX: "+ scrollX+ ", DeltaY: "+ deltaY+ ", ScrollY: "+ scrollY+ ", NewY: "+ newScrollValue+ ", ScrollRange: "+ scrollRange+ ", CurrentScroll: "+ currentScrollValue);
}
if (newScrollValue < (0 - fuzzyThreshold)) {
if (mode.showHeaderLoadingLayout()) {
if (currentScrollValue == 0) {
view.setState(State.OVERSCROLLING);
}
view.setHeaderScroll((int)(scaleFactor * (currentScrollValue + newScrollValue)));
}
}
else if (newScrollValue > (scrollRange + fuzzyThreshold)) {
if (mode.showFooterLoadingLayout()) {
if (currentScrollValue == 0) {
view.setState(State.OVERSCROLLING);
}
view.setHeaderScroll((int)(scaleFactor * (currentScrollValue + newScrollValue - scrollRange)));
}
}
else if (Math.abs(newScrollValue) <= fuzzyThreshold || Math.abs(newScrollValue - scrollRange) <= fuzzyThreshold) {
view.setState(State.RESET);
}
}
else if (isTouchEvent && State.OVERSCROLLING == view.getState()) {
view.setState(State.RESET);
}
}
}
| Helper method for Overscrolling that encapsulates all of the necessary function. This is the advanced version of the call. |
private void createVirtualVolume(String devicePath,Boolean thinEnabled) throws VPlexApiException {
ClientResponse response=null;
try {
s_logger.info("Create virtual volume for device {}",devicePath);
URI requestURI=_vplexApiClient.getBaseURI().resolve(VPlexApiConstants.URI_CREATE_VIRTUAL_VOLUME);
s_logger.info("Create virtual volume URI is {}",requestURI.toString());
Map<String,String> argsMap=new HashMap<String,String>();
argsMap.put(VPlexApiConstants.ARG_DASH_R,devicePath);
if (thinEnabled) {
argsMap.put(VPlexApiConstants.ARG_THIN_ENABLED,"");
}
JSONObject postDataObject=VPlexApiUtils.createPostData(argsMap,false);
s_logger.info("Create virtual volume POST data is {}",postDataObject.toString());
response=_vplexApiClient.post(requestURI,postDataObject.toString());
String responseStr=response.getEntity(String.class);
s_logger.info("Create virtual volume response is {}",responseStr);
if (response.getStatus() != VPlexApiConstants.SUCCESS_STATUS) {
if (response.getStatus() == VPlexApiConstants.ASYNC_STATUS) {
s_logger.info("Virtual volume creation completing asynchronously");
_vplexApiClient.waitForCompletion(response);
}
else {
String cause=VPlexApiUtils.getCauseOfFailureFromResponse(responseStr);
throw VPlexApiException.exceptions.createVolumeFailureStatus(String.valueOf(response.getStatus()),cause);
}
}
s_logger.info("Successfully created virtual volume for device {}",devicePath);
}
catch ( VPlexApiException vae) {
throw vae;
}
catch ( Exception e) {
throw VPlexApiException.exceptions.failedCreateVolume(e);
}
finally {
if (response != null) {
response.close();
}
}
}
| Creates a virtual volume for the device with the passed context path. |
public void destroy(){
if (_zombieMarker == null) {
_zombieMarker=new ZombieClassLoaderMarker();
}
try {
stop();
}
catch ( Throwable e) {
}
if (!_lifecycle.toDestroying()) {
return;
}
try {
ClassLoader parent=getParent();
for (; parent != null; parent=parent.getParent()) {
if (parent instanceof DynamicClassLoader) {
DynamicClassLoader loader=(DynamicClassLoader)parent;
if (_closeListener != null) {
loader.removeListener(_closeListener);
}
}
}
ArrayList<EnvLoaderListener> listeners=_listeners;
_listeners=null;
Thread thread=Thread.currentThread();
ClassLoader oldLoader=thread.getContextClassLoader();
try {
if (listeners != null) {
Collections.sort(listeners,LISTENER_SORT);
for (int i=listeners.size() - 1; i >= 0; i--) {
EnvLoaderListener listener=listeners.get(i);
try {
thread.setContextClassLoader(this);
listener.classLoaderDestroy(this);
}
catch ( Throwable e) {
log().log(Level.FINE,e.toString(),e);
}
}
}
}
finally {
thread.setContextClassLoader(oldLoader);
}
ArrayList<Loader> loaders=getLoaders();
for (int i=loaders.size() - 1; i >= 0; i--) {
Loader loader=loaders.get(i);
try {
loader.destroy();
}
catch ( Throwable e) {
log().log(Level.FINE,e.toString(),e);
}
}
}
finally {
_loaders=null;
_nativePath=null;
_entryCache=null;
_resourceCache=null;
_dependencies=null;
_makeList=null;
_listeners=null;
_permissions=null;
_codeSource=null;
_urls=null;
_lifecycle.toDestroy();
}
}
| Destroys the class loader. |
public ConfigurableLineTracker(String[] legalLineDelimiters){
Assert.isTrue(legalLineDelimiters != null && legalLineDelimiters.length > 0);
fDelimiters=TextUtilities.copy(legalLineDelimiters);
}
| Creates a standard line tracker for the given line delimiters. |
public void test_concurrentClients() throws InterruptedException {
final Properties properties=getProperties();
final Journal journal=new Journal(properties);
try {
doConcurrentClientTest(journal,Long.MAX_VALUE,3,1,2,500,3,1000,0.02d,0.10d);
}
finally {
journal.destroy();
}
}
| A stress test with a small pool of concurrent clients. |
public Builder addMatch2Method(Match2MethodSpec match2MethodSpec,int maxArity){
checkArgument(maxArity <= MAX_ARITY,"Arity greater than " + MAX_ARITY + "is not currently supported");
match2Methods.addAll(new Match2MethodPermutationBuilder(matchType,match2MethodSpec,maxArity).build());
return this;
}
| Adds a 2-arity match method. |
public BitmapSize scaleDown(int sampleSize){
return new BitmapSize(width / sampleSize,height / sampleSize);
}
| Scales down dimensions in <b>sampleSize</b> times. Returns new object. |
public String toString(){
StringBuilder sb=new StringBuilder(getClass().getName());
sb.append("[name=").append(this.name);
appendTo(sb,"displayName",this.displayName);
appendTo(sb,"shortDescription",this.shortDescription);
appendTo(sb,"preferred",this.preferred);
appendTo(sb,"hidden",this.hidden);
appendTo(sb,"expert",this.expert);
if ((this.table != null) && !this.table.isEmpty()) {
sb.append("; values={");
for ( Entry<String,Object> entry : this.table.entrySet()) {
sb.append(entry.getKey()).append("=").append(entry.getValue()).append("; ");
}
sb.setLength(sb.length() - 2);
sb.append("}");
}
appendTo(sb);
return sb.append("]").toString();
}
| Returns a string representation of the object. |
public static boolean isBold(AttributeSet a){
Boolean bold=(Boolean)a.getAttribute(Bold);
if (bold != null) {
return bold.booleanValue();
}
return false;
}
| Checks whether the bold attribute is set. |
public void testOneNodeSubmitCommand() throws Throwable {
testSubmitCommand(1);
}
| Tests submitting a command. |
private void unifyUsernameByEmail(Map<String,List<LogCommitInfo>> usernameMap){
for ( Entry<String,List<LogCommitInfo>> entry : usernameMap.entrySet()) {
List<String> names=getNamesList(entry.getValue());
String newUserName=names.get(0);
if (names.size() > 1) newUserName=getNewName(names);
for ( LogCommitInfo commit : entry.getValue()) {
commit.setUserName(newUserName);
}
}
}
| Treat different names for the same e-mail case |
@Deprecated protected final Class<?> defineClass(byte[] classRep,int offset,int length) throws ClassFormatError {
throw new UnsupportedOperationException("can't load this type of class file");
}
| Constructs a new class from an array of bytes containing a class definition in class file format. |
public void testAddUsers() throws Exception {
Configuration configurationElement=new Configuration();
configurationElement.setImplementation(StandaloneLocalConfigurationStub.class.getName());
User user=new User();
user.setName("someName");
user.setPassword("passW0rd");
String[] roles=new String[]{"cargo"};
user.setRoles(roles);
configurationElement.setUsers(new User[]{user});
org.codehaus.cargo.container.configuration.Configuration configuration=configurationElement.createConfiguration("testContainer",ContainerType.INSTALLED,null,new CargoProject(null,null,null,null,null,Collections.<Artifact>emptySet(),null));
StandaloneLocalConfigurationStub conf=(StandaloneLocalConfigurationStub)configuration;
List<org.codehaus.cargo.container.property.User> users=conf.getUsers();
assertEquals("users not of correct size",1,users.size());
org.codehaus.cargo.container.property.User userProperty=users.get(0);
assertEquals("name not correct","someName",userProperty.getName());
assertEquals("password not correct","passW0rd",userProperty.getPassword());
assertEquals("roles not of correct size",1,userProperty.getRoles().size());
assertEquals("role not correct","cargo",userProperty.getRoles().get(0));
}
| Test adding users to the configuration. |
public void projectionChanged(ProjectionEvent e){
}
| ProjectionListener interface method. |
public void onDestroy(){
mListener=null;
if (mIsInternalExecutor) {
mAsyncExecutor.shutdown();
}
}
| Terminates event transmission and all pending requests. |
public AsynchronousSteppable[] asynchronousRegistry(){
synchronized (asynchronousLock) {
AsynchronousSteppable[] b=new AsynchronousSteppable[asynchronous.size()];
int x=0;
Iterator i=asynchronous.iterator();
while (i.hasNext()) b[x++]=(AsynchronousSteppable)(i.next());
return b;
}
}
| Returns all the AsynchronousSteppable items presently in the registry. The returned array is not used internally -- you are free to modify it. |
@Override public String toString(){
StringBuffer sb=new StringBuffer(2048);
sb.append("File Index (" + fileIndex.size() + " entries):\n");
for ( Entry<IPath,Set<IIndexedJavaRef>> fileIndexEntry : fileIndex.entrySet()) {
sb.append(fileIndexEntry.getKey().toString());
sb.append(" => \n");
for ( IIndexedJavaRef ref : fileIndexEntry.getValue()) {
sb.append(MessageFormat.format(" {0}\n",ref));
}
}
sb.append("\n\nElement Index (" + elementIndex.size() + " entries):\n");
for ( Entry<String,Set<IIndexedJavaRef>> elementIndexEntry : elementIndex.entrySet()) {
sb.append(elementIndexEntry.getKey());
sb.append(" => \n");
for ( IIndexedJavaRef ref : elementIndexEntry.getValue()) {
sb.append(MessageFormat.format(" {0}\n",ref));
}
}
return sb.toString();
}
| For debugging purposes only. |
@DSSink({DSSinkKind.SENSITIVE_UNCATEGORIZED}) @DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 13:01:11.201 -0500",hash_original_method="A0319C4335A825139157822F68CBECCE",hash_generated_method="ADE86886EFEDCE64F50DB21D25A6794B") @Override protected byte[] decrypt(byte type,byte[] fragment,int offset,int len){
byte[] data=decCipher.update(fragment,offset,len);
byte[] content;
if (block_size != 0) {
int padding_length=data[data.length - 1];
for (int i=0; i < padding_length; i++) {
if (data[data.length - 2 - i] != padding_length) {
throw new AlertException(AlertProtocol.DECRYPTION_FAILED,new SSLProtocolException("Received message has bad padding"));
}
}
content=new byte[data.length - hash_size - padding_length- 1];
}
else {
content=new byte[data.length - hash_size];
}
mac_material_header[0]=type;
mac_material_header[3]=(byte)((0x00FF00 & content.length) >> 8);
mac_material_header[4]=(byte)(0x0000FF & content.length);
decMac.update(read_seq_num);
decMac.update(mac_material_header);
decMac.update(data,0,content.length);
byte[] mac_value=decMac.doFinal();
if (logger != null) {
logger.println("Decrypted:");
logger.print(data);
logger.println("Expected mac value:");
logger.print(mac_value);
}
for (int i=0; i < hash_size; i++) {
if (mac_value[i] != data[i + content.length]) {
throw new AlertException(AlertProtocol.BAD_RECORD_MAC,new SSLProtocolException("Bad record MAC"));
}
}
System.arraycopy(data,0,content,0,content.length);
incSequenceNumber(read_seq_num);
return content;
}
| Retrieves the fragment of the Plaintext structure of the specified type from the provided data representing the Generic[Stream|Block]Cipher structure. |
public static PropertyHandler configurePropertyHandler(String propertiesFile){
try {
return new PropertyHandler.Builder().setPropertiesFile(propertiesFile).setPropertyPrefix("main").build();
}
catch ( MalformedURLException murle) {
getLogger().log(Level.WARNING,murle.getMessage(),murle);
}
catch ( IOException ioe) {
getLogger().log(Level.WARNING,ioe.getMessage(),ioe);
}
return new PropertyHandler();
}
| Given a path to a properties file, try to configure a PropertyHandler with it. If the properties file is not valid, the returned PropertyHandler will look for the openmap.properties file in the classpath and the user's home directory. |
public void cancelAll(){
for ( Map.Entry<String,Request> entry : requestMap.entrySet()) {
entry.getValue().task.cancel(false);
}
requestMap.clear();
}
| Cancel all request in SoBitmap |
private StoragePort chooseCandidate(Set<StoragePort> candidates,Map<StoragePort,Long> usageMap){
StoragePort chosenPort=null;
long minUsage=Long.MAX_VALUE;
for ( StoragePort sp : candidates) {
Long usage=usageMap.get(sp);
_log.debug(String.format("Port %s usage %d",sp.getPortName(),usage));
if (usage < minUsage) {
minUsage=usage;
chosenPort=sp;
}
}
return chosenPort;
}
| Choose one of the ports with minimum usage from the candidate list. |
public int compareTo(Object arg0){
if (arg0 instanceof WeightedCellSorter) {
if (weightedValue > ((WeightedCellSorter)arg0).weightedValue) {
return -1;
}
else if (weightedValue < ((WeightedCellSorter)arg0).weightedValue) {
return 1;
}
else {
if (nudge) {
return -1;
}
else {
return 1;
}
}
}
else {
return 0;
}
}
| comparator on the medianValue |
public Builder widthDp(int drawerWidthDp){
return this;
}
| Set the Drawer width with a dp value |
public static List<Intersection> intersectTriStrip(final Line line,Vec4[] vertices,IntBuffer indices){
if (line == null) {
String msg=Logging.getMessage("nullValue.LineIsNull");
Logging.logger().severe(msg);
throw new IllegalArgumentException(msg);
}
if (vertices == null) {
String msg=Logging.getMessage("nullValue.ArrayIsNull");
Logging.logger().severe(msg);
throw new IllegalArgumentException(msg);
}
if (indices == null) {
String msg=Logging.getMessage("nullValue.BufferIsNull");
Logging.logger().severe(msg);
throw new IllegalArgumentException(msg);
}
List<Intersection> intersections=null;
for (int n=indices.position(); n < indices.limit() - 1; n++) {
Intersection intersection;
int i=indices.get(n) * 3;
int j=indices.get(n + 1) * 3;
int k=indices.get(n + 2) * 3;
intersection=intersect(line,vertices[i],vertices[j],vertices[k]);
if (intersection != null) {
if (intersections == null) intersections=new ArrayList<Intersection>();
intersections.add(intersection);
}
}
return intersections;
}
| Compute the intersections of a line with a triangle strip. |
public boolean isProcessedOK(){
return m_ok;
}
| Is Processed OK |
public EntityResult updateEntities(Referenceable... entities) throws AtlasServiceException {
return updateEntities(Arrays.asList(entities));
}
| Replaces entity definitions identified by their guid or unique attribute Updates properties set in the definition for the entity corresponding to guid |
protected AlgorithmParameters engineGetParameters(){
return core.getParameters("DESede");
}
| Returns the parameters used with this cipher. <p>The returned parameters may be the same that were used to initialize this cipher, or may contain the default set of parameters or a set of randomly generated parameters used by the underlying cipher implementation (provided that the underlying cipher implementation uses a default set of parameters or creates new parameters if it needs parameters but was not initialized with any). |
public <T extends ResourceObject>List<T> execute(Class<T> type) throws ParseException, RepositoryException, MalformedQueryException, QueryEvaluationException {
URI rootType=connection.getObjectFactory().getNameOf(type);
if (rootType == null) {
throw new IllegalArgumentException("Can't query for: " + type + " not found in name map. Is @Iri annotation set?");
}
Query sparql=EvalQuery.evaluate(queryServiceDTO,rootType);
sparql.setDistinct(true);
if (limit != null) {
sparql.setLimit(limit);
}
if (offset != null) {
sparql.setOffset(offset);
}
String q=sparql.serialize();
logger.debug("Initial query:\n" + queryOptimizer.prettyPrint(q));
q=queryOptimizer.optimizeJoinOrder(q);
logger.debug("Query after join order optimization:\n " + q);
ObjectQuery query=connection.prepareObjectQuery(q);
if (query.getDataset() != null) {
logger.info("\nGRAPH CONTEXT = " + query.getDataset().getDefaultGraphs() + "\nFINAL QUERY :\n"+ q);
}
else {
logger.info("\nFINAL QUERY :\n" + q);
}
return (List<T>)query.evaluate().asList();
}
| Creates and executes the SPARQL query according to the criteria specified by the user. |
public static CCAnimate action(CCAnimation anim){
assert anim != null : "Animate: argument Animation must be non-null";
return new CCAnimate(anim,true);
}
| creates the action with an Animation and will restore the original frame when the animation is over |
public static void main(String[] args) throws Exception {
int res=ToolRunner.run(new EncodeBfsGraph(),args);
System.exit(res);
}
| Dispatches command-line arguments to the tool via the <code>ToolRunner</code>. |
public void addFooter(@NonNull View view){
if (view == null) {
throw new IllegalArgumentException("You can't have a null footer!");
}
mFooters.add(view);
}
| Adds a footer view. |
NotifyingTask(){
}
| No qualifier |
@Override protected void doGet(final HttpServletRequest request,HttpServletResponse response) throws IOException {
response.setStatus(HttpServletResponse.SC_OK);
response.setHeader("Connection","Keep-Alive");
if (request.getAttribute("result") != null) {
JsonNode result=(JsonNode)request.getAttribute("result");
int code=result.path(DATA).path(CODE).asInt(HttpServletResponse.SC_OK);
if (code == HttpServletResponse.SC_OK) {
response.getWriter().write(this.mapper.writeValueAsString(result));
}
else {
this.sendError(response,code,this.mapper.writeValueAsString(result));
}
return;
}
String[] rest=request.getPathInfo().split("/");
String type=(rest.length > 1) ? rest[1] : null;
if (type != null) {
response.setContentType(UTF8_APPLICATION_JSON);
ServletUtil.getInstance().setNonCachingHeaders(response);
final String name=(rest.length > 2) ? URLDecoder.decode(rest[2],StandardCharsets.UTF_8.name()) : null;
ObjectNode parameters=this.mapper.createObjectNode();
for ( Map.Entry<String,String[]> entry : request.getParameterMap().entrySet()) {
parameters.put(entry.getKey(),URLDecoder.decode(entry.getValue()[0],"UTF-8"));
}
JsonNode reply=null;
try {
if (name == null) {
if (this.services.get(type) != null) {
ArrayNode array=this.mapper.createArrayNode();
JsonException exception=null;
try {
for ( JsonHttpService service : this.services.get(type)) {
array.add(service.doGetList(type,request.getLocale()));
}
}
catch ( JsonException ex) {
exception=ex;
}
switch (array.size()) {
case 0:
if (exception != null) {
throw exception;
}
reply=array;
break;
case 1:
reply=array.get(0);
break;
default :
reply=array;
break;
}
}
if (reply == null) {
log.warn("Type {} unknown.",type);
throw new JsonException(HttpServletResponse.SC_NOT_FOUND,Bundle.getMessage(request.getLocale(),"ErrorUnknownType",type));
}
}
else {
if (this.services.get(type) != null) {
ArrayNode array=this.mapper.createArrayNode();
JsonException exception=null;
try {
for (JsonHttpService service : this.services.get(type)) {
array.add(service.doGet(type,name,request.getLocale()));
}
}
catch (JsonException ex) {
exception=ex;
}
switch (array.size()) {
case 0:
if (exception != null) {
throw exception;
}
reply=array;
break;
case 1:
reply=array.get(0);
break;
default :
reply=array;
break;
}
}
if (reply == null) {
log.warn("Requested type '{}' unknown.",type);
throw new JsonException(HttpServletResponse.SC_NOT_FOUND,Bundle.getMessage(request.getLocale(),"ErrorUnknownType",type));
}
}
}
catch (JsonException ex) {
reply=ex.getJsonMessage();
}
int code=reply.path(DATA).path(CODE).asInt(HttpServletResponse.SC_OK);
if (code == HttpServletResponse.SC_OK) {
response.getWriter().write(this.mapper.writeValueAsString(reply));
}
else {
this.sendError(response,code,this.mapper.writeValueAsString(reply));
}
}
else {
response.setContentType(ServletUtil.UTF8_TEXT_HTML);
response.getWriter().print(String.format(request.getLocale(),FileUtil.readURL(FileUtil.findURL(Bundle.getMessage(request.getLocale(),"Json.html"))),String.format(request.getLocale(),Bundle.getMessage(request.getLocale(),"HtmlTitle"),ServletUtil.getInstance().getRailroadName(false),Bundle.getMessage(request.getLocale(),"JsonTitle")),ServletUtil.getInstance().getNavBar(request.getLocale(),request.getContextPath()),ServletUtil.getInstance().getRailroadName(false),ServletUtil.getInstance().getFooter(request.getLocale(),request.getContextPath())));
}
}
| Handle HTTP get requests for JSON data. Examples: <ul> <li>/json/sensor/IS22 (return data for sensor with system name "IS22")</li> <li>/json/sensors (returns a list of all sensors known to JMRI)</li> </ul> sample responses: <ul> <li>{"type":"sensor","data":{"name":"IS22","userName":"FarEast","comment":null,"inverted":false,"state":4}}</li> <li>[{"type":"sensor","data":{"name":"IS22","userName":"FarEast","comment":null,"inverted":false,"state":4}}]</li> </ul> Note that data will vary for each type. |
public static S2CellId fromFaceIJSame(int face,int i,int j,boolean sameFace){
if (sameFace) {
return S2CellId.fromFaceIJ(face,i,j);
}
else {
return S2CellId.fromFaceIJWrap(face,i,j);
}
}
| Public helper function that calls FromFaceIJ if sameFace is true, or FromFaceIJWrap if sameFace is false. |
protected boolean afterDelete(boolean success){
log.info("*** Success=" + success);
return success;
}
| After Delete |
public static String extractPostDialPortion(String phoneNumber){
if (phoneNumber == null) return null;
int trimIndex;
StringBuilder ret=new StringBuilder();
trimIndex=indexOfLastNetworkChar(phoneNumber);
for (int i=trimIndex + 1, s=phoneNumber.length(); i < s; i++) {
char c=phoneNumber.charAt(i);
if (isNonSeparator(c)) {
ret.append(c);
}
}
return ret.toString();
}
| Extracts the post-dial sequence of DTMF control digits, pauses, and waits. Strips separators. This string may be empty, but will not be null unless phoneNumber == null. Returns null if phoneNumber == null |
public List<Tuple<String,Coord>> readNextMovements(){
ArrayList<Tuple<String,Coord>> moves=new ArrayList<Tuple<String,Coord>>();
if (!scanner.hasNextLine()) {
return moves;
}
Scanner lineScan=new Scanner(lastLine);
double time=lineScan.nextDouble();
String id=lineScan.next();
double x=lineScan.nextDouble();
double y=lineScan.nextDouble();
if (normalize) {
time-=minTime;
x-=minX;
y-=minY;
}
lastTimeStamp=time;
while (scanner.hasNextLine() && lastTimeStamp == time) {
lastLine=scanner.nextLine();
if (lastLine.trim().length() == 0 || lastLine.startsWith(COMMENT_PREFIX)) {
continue;
}
moves.add(new Tuple<String,Coord>(id,new Coord(x,y)));
lineScan=new Scanner(lastLine);
try {
time=lineScan.nextDouble();
id=lineScan.next();
x=lineScan.nextDouble();
y=lineScan.nextDouble();
}
catch ( Exception e) {
throw new SettingsError("Invalid line '" + lastLine + "'");
}
if (normalize) {
time-=minTime;
x-=minX;
y-=minY;
}
}
if (!scanner.hasNextLine()) {
moves.add(new Tuple<String,Coord>(id,new Coord(x,y)));
}
return moves;
}
| Reads all new id-coordinate tuples that belong to the same time instance |
public ShipFilterGroupDialog(Shell parent){
super(parent,ShipFilterGroupBean.class);
}
| Create the dialog. |
public void onEvent(Event e) throws Exception {
if (m_actionActive) return;
m_actionActive=true;
if (e.getTarget().equals(orderField)) {
KeyNamePair pp=orderField.getSelectedItem().toKeyNamePair();
if (pp == null || pp.getKey() == 0) ;
else {
int C_Order_ID=pp.getKey();
invoiceField.setSelectedIndex(-1);
rmaField.setSelectedIndex(-1);
loadOrder(C_Order_ID,false,locatorField.getValue() != null ? ((Integer)locatorField.getValue()).intValue() : 0);
m_invoice=null;
}
}
else if (e.getTarget().equals(invoiceField)) {
KeyNamePair pp=invoiceField.getSelectedItem().toKeyNamePair();
if (pp == null || pp.getKey() == 0) ;
else {
int C_Invoice_ID=pp.getKey();
orderField.setSelectedIndex(-1);
rmaField.setSelectedIndex(-1);
loadInvoice(C_Invoice_ID,locatorField.getValue() != null ? ((Integer)locatorField.getValue()).intValue() : 0);
}
}
else if (e.getTarget().equals(rmaField)) {
KeyNamePair pp=rmaField.getSelectedItem().toKeyNamePair();
if (pp == null || pp.getKey() == 0) ;
else {
int M_RMA_ID=pp.getKey();
orderField.setSelectedIndex(-1);
invoiceField.setSelectedIndex(-1);
loadRMA(M_RMA_ID,locatorField.getValue() != null ? ((Integer)locatorField.getValue()).intValue() : 0);
}
}
else if (e.getTarget().equals(sameWarehouseCb)) {
initBPOrderDetails(((Integer)bPartnerField.getValue()).intValue(),false);
}
else if (e.getTarget().equals(upcField.getComponent())) {
checkProductUsingUPC();
}
m_actionActive=false;
}
| Action Listener |
public List<ScheduledEvent> findByScheduledEventType(ScheduledEventType scheduledEventType){
List<NamedElement> scheduledEventIds=client.findByAlternateId(ScheduledEvent.class,ScheduledEvent.EVENT_TYPE,scheduledEventType.name());
return findByIds(toURIs(scheduledEventIds));
}
| Finds scheduled events by type. This method is intended for use by the scheduler only, in general use |
@DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 12:58:05.690 -0500",hash_original_method="23308A79A2D2396A98D81E8541E78934",hash_generated_method="5B5626C5475713791C9CEDB0AAE28C29") public boolean isPointToPoint() throws SocketException {
return hasFlag(IFF_POINTOPOINT);
}
| Returns true if this network interface is a point-to-point interface. (For example, a PPP connection using a modem.) |
public Model(Option taggerOpt,Maps taggerMaps,Dictionary taggerDict,FeatureGen taggerFGen,Viterbi taggerVtb){
this.taggerOpt=taggerOpt;
this.taggerMaps=taggerMaps;
this.taggerDict=taggerDict;
this.taggerFGen=taggerFGen;
this.taggerVtb=taggerVtb;
}
| Instantiates a new model. |
public static double[][] I(Instances D,int L){
double M[][]=new double[L][L];
for (int j=0; j < L; j++) {
for (int k=j + 1; k < L; k++) {
M[j][k]=I(D,j,k);
}
}
return M;
}
| I - Get an Unconditional Depndency Matrix. (Works for both ML and MT data). |
public void map(){
if (!mappings.isEmpty()) {
for ( GridDhtAtomicUpdateRequest req : mappings.values()) {
try {
cctx.io().send(req.nodeId(),req,cctx.ioPolicy());
if (msgLog.isDebugEnabled()) {
msgLog.debug("DTH update fut, sent request [futId=" + futVer + ", writeVer="+ writeVer+ ", node="+ req.nodeId()+ ']');
}
}
catch ( ClusterTopologyCheckedException ignored) {
if (msgLog.isDebugEnabled()) {
msgLog.debug("DTH update fut, failed to send request, node left [futId=" + futVer + ", writeVer="+ writeVer+ ", node="+ req.nodeId()+ ']');
}
registerResponse(req.nodeId());
}
catch ( IgniteCheckedException e) {
U.error(msgLog,"Failed to send request [futId=" + futVer + ", writeVer="+ writeVer+ ", node="+ req.nodeId()+ ']');
registerResponse(req.nodeId());
}
}
}
else onDone();
if (updateReq.writeSynchronizationMode() != FULL_SYNC) completionCb.apply(updateReq,updateRes);
}
| Sends requests to remote nodes. |
public OperationCanceledException(String message){
super(message);
}
| Creates a new exception with the given message. |
public void attemptRecover(){
String email=edit_email.getText().toString();
boolean cancel=false;
View focusView=null;
ValidateUserInfo validate=new ValidateUserInfo();
if (TextUtils.isEmpty(email)) {
edit_email.setError(getString(R.string.error_field_required));
focusView=edit_email;
cancel=true;
}
else if (!validate.isEmailValid(email)) {
edit_email.setError(getString(R.string.error_invalid_email));
focusView=edit_email;
cancel=true;
}
if (cancel) {
focusView.requestFocus();
}
else {
mForgotTask=new ForgotPassTask(email);
mForgotTask.execute((Void)null);
}
}
| Attempts to recover the account specified by the login form. If there are form errors (invalid email, missing fields, etc.), the errors are presented and no actual login attempt is made. |
public Vector product(Vector v) throws IllegalDimension {
int n=this.rows();
int m=this.columns();
if (v.dimension() != m) throw new IllegalDimension("Product error: " + n + " by "+ m+ " matrix cannot by multiplied with vector of dimension "+ v.dimension());
return secureProduct(v);
}
| Computes the product of the matrix with a vector. |
public List<IComment> appendLocalCodeNodeComment(final String commentText) throws CouldntSaveDataException, CouldntLoadDataException {
return CommentManager.get(m_provider).appendLocalCodeNodeComment(m_codeNode,commentText);
}
| Appends a new local code node comment to the list of current local code node comments. |
void onMapped(){
isMapped=true;
}
| Call back for job mapped event. |
static public String startupInfo(String program){
return (program + " version " + jmri.Version.name()+ " starts under Java "+ System.getProperty("java.version","<unknown>"));
}
| Static method to return a first logging statement. Used for logging startup, etc. |
public EpsilonMOEA(Problem problem,Population population,EpsilonBoxDominanceArchive archive,Selection selection,Variation variation,Initialization initialization){
this(problem,population,archive,selection,variation,initialization,new ParetoDominanceComparator());
}
| Constructs the ε-MOEA algorithm with the specified components. |
public boolean autoCapSentences(){
return preferences.getBoolean(resources.getString(R.string.key_autocap_sentences),Boolean.parseBoolean(resources.getString(R.string.default_autocap_sentences)));
}
| Whether sentences in messages should be automatically capitalized. |
public Builder(Builder otherBuilder){
this.webIrcEnabled=otherBuilder.isWebIrcEnabled();
this.webIrcUsername=otherBuilder.getWebIrcUsername();
this.webIrcHostname=otherBuilder.getWebIrcHostname();
this.webIrcAddress=otherBuilder.getWebIrcAddress();
this.webIrcPassword=otherBuilder.getWebIrcPassword();
this.name=otherBuilder.getName();
this.login=otherBuilder.getLogin();
this.version=otherBuilder.getVersion();
this.finger=otherBuilder.getFinger();
this.realName=otherBuilder.getRealName();
this.channelPrefixes=otherBuilder.getChannelPrefixes();
this.userLevelPrefixes=otherBuilder.getUserLevelPrefixes();
this.snapshotsEnabled=otherBuilder.isSnapshotsEnabled();
this.dccFilenameQuotes=otherBuilder.isDccFilenameQuotes();
this.dccPorts.clear();
this.dccPorts.addAll(otherBuilder.getDccPorts());
this.dccLocalAddress=otherBuilder.getDccLocalAddress();
this.dccPublicAddress=otherBuilder.getDccPublicAddress();
this.dccAcceptTimeout=otherBuilder.getDccAcceptTimeout();
this.dccResumeAcceptTimeout=otherBuilder.getDccResumeAcceptTimeout();
this.dccTransferBufferSize=otherBuilder.getDccTransferBufferSize();
this.dccPassiveRequest=otherBuilder.isDccPassiveRequest();
this.servers.clear();
this.servers.addAll(otherBuilder.getServers());
this.serverPassword=otherBuilder.getServerPassword();
this.socketFactory=otherBuilder.getSocketFactory();
this.localAddress=otherBuilder.getLocalAddress();
this.encoding=otherBuilder.getEncoding();
this.locale=otherBuilder.getLocale();
this.socketConnectTimeout=otherBuilder.getSocketConnectTimeout();
this.socketTimeout=otherBuilder.getSocketTimeout();
this.maxLineLength=otherBuilder.getMaxLineLength();
this.autoSplitMessage=otherBuilder.isAutoSplitMessage();
this.autoNickChange=otherBuilder.isAutoNickChange();
this.messageDelay=otherBuilder.getMessageDelay();
this.listenerManager=otherBuilder.getListenerManager();
this.nickservPassword=otherBuilder.getNickservPassword();
this.nickservOnSuccess=otherBuilder.getNickservOnSuccess();
this.nickservNick=otherBuilder.getNickservNick();
this.nickservCustomMessage=otherBuilder.getNickservCustomMessage();
this.nickservDelayJoin=otherBuilder.isNickservDelayJoin();
this.userModeHideRealHost=otherBuilder.isUserModeHideRealHost();
this.autoReconnect=otherBuilder.isAutoReconnect();
this.autoReconnectDelay=otherBuilder.getAutoReconnectDelay();
this.autoReconnectAttempts=otherBuilder.getAutoReconnectAttempts();
this.autoJoinChannels.putAll(otherBuilder.getAutoJoinChannels());
this.onJoinWhoEnabled=otherBuilder.isOnJoinWhoEnabled();
this.identServerEnabled=otherBuilder.isIdentServerEnabled();
this.capEnabled=otherBuilder.isCapEnabled();
this.capHandlers.clear();
this.capHandlers.addAll(otherBuilder.getCapHandlers());
this.channelModeHandlers.clear();
this.channelModeHandlers.addAll(otherBuilder.getChannelModeHandlers());
this.shutdownHookEnabled=otherBuilder.isShutdownHookEnabled();
this.botFactory=otherBuilder.getBotFactory();
}
| Copy values from another builder. |
protected String paramString(){
String editableString=(editable ? "true" : "false");
String caretColorString=(caretColor != null ? caretColor.toString() : "");
String selectionColorString=(selectionColor != null ? selectionColor.toString() : "");
String selectedTextColorString=(selectedTextColor != null ? selectedTextColor.toString() : "");
String disabledTextColorString=(disabledTextColor != null ? disabledTextColor.toString() : "");
String marginString=(margin != null ? margin.toString() : "");
return super.paramString() + ",caretColor=" + caretColorString+ ",disabledTextColor="+ disabledTextColorString+ ",editable="+ editableString+ ",margin="+ marginString+ ",selectedTextColor="+ selectedTextColorString+ ",selectionColor="+ selectionColorString;
}
| Returns a string representation of this <code>JTextComponent</code>. This method is intended to be used only for debugging purposes, and the content and format of the returned string may vary between implementations. The returned string may be empty but may not be <code>null</code>. <P> Overriding <code>paramString</code> to provide information about the specific new aspects of the JFC components. |
protected String doIt() throws Exception {
m_C_Project_ID=getRecord_ID();
log.info("doIt - C_Project_ID=" + m_C_Project_ID + ", C_ProjectType_ID="+ m_C_ProjectType_ID);
MProject project=new MProject(getCtx(),m_C_Project_ID,get_TrxName());
if (project.getC_Project_ID() == 0 || project.getC_Project_ID() != m_C_Project_ID) throw new IllegalArgumentException("Project not found C_Project_ID=" + m_C_Project_ID);
if (project.getC_ProjectType_ID_Int() > 0) throw new IllegalArgumentException("Project already has Type (Cannot overwrite) " + project.getC_ProjectType_ID());
MProjectType type=new MProjectType(getCtx(),m_C_ProjectType_ID,get_TrxName());
if (type.getC_ProjectType_ID() == 0 || type.getC_ProjectType_ID() != m_C_ProjectType_ID) throw new IllegalArgumentException("Project Type not found C_ProjectType_ID=" + m_C_ProjectType_ID);
project.setProjectType(type);
if (!project.save()) throw new Exception("@Error@");
return "@OK@";
}
| Perform process. |
IMemberValuePairBinding resolveMemberValuePair(MemberValuePair memberValuePair){
return null;
}
| Resolves the given member value pair and returns the binding for it. <p> The implementation of <code>MemberValuePair.resolveMemberValuePairBinding</code> forwards to this method. How the name resolves is often a function of the context in which the name node is embedded as well as the name itself. </p> <p> The default implementation of this method returns <code>null</code>. Subclasses may reimplement. </p> |
public TimingSpecifierParser(boolean useSVG11AccessKeys,boolean useSVG12AccessKeys){
super(useSVG11AccessKeys,useSVG12AccessKeys);
timingSpecifierHandler=DefaultTimingSpecifierHandler.INSTANCE;
}
| Creates a new TimingSpecifierParser. |
public void cut(){
if (isEditable() && isEnabled()) {
invokeAction("cut",TransferHandler.getCutAction());
}
}
| Transfers the currently selected range in the associated text model to the system clipboard, removing the contents from the model. The current selection is reset. Does nothing for <code>null</code> selections. |
private Map<String,String> makeWorkerProps() throws IOException {
Map<String,String> props=new HashMap<>();
props.put(WorkerConfig.INTERNAL_KEY_CONVERTER_CLASS_CONFIG,"org.apache.kafka.connect.storage.StringConverter");
props.put(WorkerConfig.INTERNAL_VALUE_CONVERTER_CLASS_CONFIG,"org.apache.kafka.connect.storage.StringConverter");
props.put("internal.key.converter.schemas.enable","false");
props.put("internal.value.converter.schemas.enable","false");
props.put(WorkerConfig.KEY_CONVERTER_CLASS_CONFIG,"org.apache.kafka.connect.storage.StringConverter");
props.put(WorkerConfig.VALUE_CONVERTER_CLASS_CONFIG,"org.apache.ignite.stream.kafka.connect.serialization.CacheEventConverter");
props.put("key.converter.schemas.enable","false");
props.put("value.converter.schemas.enable","false");
props.put(WorkerConfig.BOOTSTRAP_SERVERS_CONFIG,kafkaBroker.getBrokerAddress());
props.put("offset.storage.file.filename","/tmp/connect.offsets");
props.put(WorkerConfig.OFFSET_COMMIT_INTERVAL_MS_CONFIG,"10");
return props;
}
| Creates properties for Kafka Connect workers. |
@Override public int eDerivedOperationID(int baseOperationID,Class<?> baseClass){
if (baseClass == TypableElement.class) {
switch (baseOperationID) {
default :
return -1;
}
}
if (baseClass == Expression.class) {
switch (baseOperationID) {
case N4JSPackage.EXPRESSION___IS_VALID_SIMPLE_ASSIGNMENT_TARGET:
return ImPackage.REFERENCING_ELEMENT_EXPRESSION_IM___IS_VALID_SIMPLE_ASSIGNMENT_TARGET;
default :
return -1;
}
}
return super.eDerivedOperationID(baseOperationID,baseClass);
}
| <!-- begin-user-doc --> <!-- end-user-doc --> |
public int next(){
int node=_currentNode;
if (node == DTM.NULL) return DTM.NULL;
final int nodeType=_nodeType;
if (nodeType != DTM.ELEMENT_NODE) {
while (node != DTM.NULL && _exptype2(node) != nodeType) {
node=_nextsib2(node);
}
}
else {
int eType;
while (node != DTM.NULL) {
eType=_exptype2(node);
if (eType >= DTM.NTYPES) break;
else node=_nextsib2(node);
}
}
if (node == DTM.NULL) {
_currentNode=DTM.NULL;
return DTM.NULL;
}
else {
_currentNode=_nextsib2(node);
return returnNode(makeNodeHandle(node));
}
}
| Get the next node in the iteration. |
public void expectationOnly(){
expectation(estimatedIm);
}
| This method is for use in the unit test for EmBayesEstimator. It tests the expectation method without iterating. |
public boolean isClassOk(){
return mCode >= 200 && mCode < 300;
}
| Test if event represents a command success. |
public void createAndCompareList(RawByteCache cache,int localBufferSize,int objectCount) throws IOException {
LargeObjectArray<SampleObject> loa=new LargeObjectArray<SampleObject>(cache,localBufferSize);
List<SampleObject> objects=this.createObjectList(loa,objectCount);
LargeObjectScanner<SampleObject> scanner=loa.scanner();
int count=0;
while (scanner.hasNext()) {
SampleObject original=objects.get(count);
SampleObject stored=scanner.next();
Assert.assertEquals("Original vs. stored object: object=" + original,original,stored);
if (count > 0 && (count + 1) % 50 == 0) logger.info("Checked objects: " + count);
count++;
}
Assert.assertEquals("Checking scanned object count",objects.size(),count);
loa.release();
}
| Creates a list and compares values. |
public void endViewTarget() throws ParseException {
}
| Invoked when a view target specification ends. |
@Override public int hashCode(){
return Objects.hashCode(name,url,duration);
}
| Two Videos will generate the same hashcode if they have exactly the same values for their name, url, and duration. |
public static Socket createSocket() throws IOException {
return new Socket(ADB_HOST,ADB_PORT);
}
| Creates a new socket that can be configured to serve as a transparent proxy to a remote machine. This can be achieved by calling configureSocket() |
private void computeLabelSide(int geomIndex,int side){
for (Iterator it=iterator(); it.hasNext(); ) {
EdgeEnd e=(EdgeEnd)it.next();
if (e.getLabel().isArea()) {
int loc=e.getLabel().getLocation(geomIndex,side);
if (loc == Location.INTERIOR) {
label.setLocation(geomIndex,side,Location.INTERIOR);
return;
}
else if (loc == Location.EXTERIOR) label.setLocation(geomIndex,side,Location.EXTERIOR);
}
}
}
| To compute the summary label for a side, the algorithm is: FOR all edges IF any edge's location is INTERIOR for the side, side location = INTERIOR ELSE IF there is at least one EXTERIOR attribute, side location = EXTERIOR ELSE side location = NULL <br> Note that it is possible for two sides to have apparently contradictory information i.e. one edge side may indicate that it is in the interior of a geometry, while another edge side may indicate the exterior of the same geometry. This is not an incompatibility - GeometryCollections may contain two Polygons that touch along an edge. This is the reason for Interior-primacy rule above - it results in the summary label having the Geometry interior on <b>both</b> sides. |
public static boolean hasService(Class<?> service,URL[] urls) throws ServiceConfigurationError {
for ( URL url : urls) {
try {
String fullName=prefix + service.getName();
URL u=new URL(url,fullName);
boolean found=parse(service,u);
if (found) return true;
}
catch ( MalformedURLException e) {
}
}
return false;
}
| Return true if a description for at least one service is found in the service configuration files in the given URLs. |
private void sendFriends() throws IOException {
log.debug("sending local contacts list");
ArrayList<ByteString> blindedFriends=SecurityManager.getCurrentProfile(mContext).isUseTrust() ? Crypto.byteArraysToStrings(mClientPSI.encodeBlindedItems()) : new ArrayList<ByteString>();
ClientMessage cm=new ClientMessage(null,blindedFriends);
if (!lengthValueWrite(out,cm.toJSON())) {
setExchangeStatus(Status.ERROR);
setErrorMessage("Length/value write of client friends failed.");
throw new IOException("Length/value write of client friends failed, but exception is hidden (see Exchange.java)");
}
}
| Construct and send a ClientMessage to the remote party including blinded friends from the friend store. |
@Override public void deliver(WriteStream os,OutHttp2 outHttp) throws IOException {
try {
os.flush();
}
finally {
_future.ok(null);
}
}
| Deliver the message |
public String serialize(TreeNode root){
if (root == null) {
return "#,";
}
String mid=root.val + ",";
String left=serialize(root.left);
String right=serialize(root.right);
mid+=left + right;
return mid;
}
| This method will be invoked first, you should design your own algorithm to serialize a binary tree which denote by a root node to a string which can be easily deserialized by your own "deserialize" method later. |
public TransportTimeoutException(){
}
| Constructs a <tt>TransportTimeoutException</tt> with no detail message. |
public int digest(byte[] buf,int offset,int len) throws DigestException {
if (buf == null) {
throw new IllegalArgumentException("No output buffer given");
}
if (buf.length - offset < len) {
throw new IllegalArgumentException("Output buffer too small for specified offset and length");
}
int numBytes=engineDigest(buf,offset,len);
state=INITIAL;
return numBytes;
}
| Completes the hash computation by performing final operations such as padding. The digest is reset after this call is made. |
public Enumeration<String> enumerateMeasures(){
Vector<String> newVector=new Vector<String>(1);
newVector.addElement("measureNumIterations");
return newVector.elements();
}
| Returns an enumeration of the additional measure names |
public CylinderPortrayal3D(Color color){
this(color,1f);
}
| Constructs a CylinderPortrayal3D with a flat opaque appearance of the given color and a scale of 1.0. |
public void initTimeEvent(String typeArg,AbstractView viewArg,int detailArg){
initEvent(typeArg,false,false);
this.view=viewArg;
this.detail=detailArg;
}
| Initializes the values of the TimeEvent object. |
public N4ClassDeclaration createN4ClassDeclaration(){
N4ClassDeclarationImpl n4ClassDeclaration=new N4ClassDeclarationImpl();
return n4ClassDeclaration;
}
| <!-- begin-user-doc --> <!-- end-user-doc --> |
@DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 12:59:51.879 -0500",hash_original_method="41BD172CDA07BE5F4D9598EFF8EB9D29",hash_generated_method="54B8312A3A41C9C5C3658A17557380D4") private static void applyInvokeWithSecurityPolicy(Arguments args,Credentials peer) throws ZygoteSecurityException {
int peerUid=peer.getUid();
if (args.invokeWith != null && peerUid != 0) {
throw new ZygoteSecurityException("Peer is not permitted to specify " + "an explicit invoke-with wrapper command");
}
}
| Applies zygote security policy. Based on the credentials of the process issuing a zygote command: <ol> <li> uid 0 (root) may specify --invoke-with to launch Zygote with a wrapper command. <li> Any other uid may not specify any invoke-with argument. </ul> |
private int crypt(byte[] in,int inOff,int len,byte[] out,int outOff){
int result=len;
while (len-- > 0) {
if (used >= blockSize) {
embeddedCipher.encryptBlock(counter,0,encryptedCounter,0);
increment(counter);
used=0;
}
out[outOff++]=(byte)(in[inOff++] ^ encryptedCounter[used++]);
}
return result;
}
| Do the actual encryption/decryption operation. Essentially we XOR the input plaintext/ciphertext stream with a keystream generated by encrypting the counter values. Counter values are encrypted on demand. |
public PythonRIntegrator(String baseFolder){
File folder=new File(baseFolder);
if (!folder.exists() || !folder.isDirectory()) {
throw new RuntimeException("The base folder is invalid. ABORTING");
}
this.baseFolder=baseFolder;
DateString ds=new DateString();
ds.setTimeInMillis(System.currentTimeMillis());
File of=new File(baseFolder + "output_" + ds.toString()+ "/");
boolean createdOutputFolder=of.mkdirs();
if (!createdOutputFolder) {
throw new RuntimeException("Could not create output folder ... ABORTING.");
}
this.outputFolder=of.getAbsolutePath() + "/";
this.controlTotalsMap=parseControlTotals(this.baseFolder + "template/controlTotals.csv");
this.zoneList=new ArrayList<String>();
for ( String id : this.controlTotalsMap.keySet()) {
this.zoneList.add(id);
}
}
| Instantiating the Python-R-integration. The existence of the base folder is checked, and the zones that must be fitted is parsed from the control totals file. |
@Override public Settings init(String tag){
if (tag == null) {
throw new NullPointerException("tag may not be null");
}
if (tag.trim().length() == 0) {
throw new IllegalStateException("tag may not be empty");
}
this.tag=tag;
return settings;
}
| It is used to change the tag |
public GeoBoundsBuilder wrapLongitude(boolean wrapLongitude){
this.wrapLongitude=wrapLongitude;
return this;
}
| Set whether to wrap longitudes. Defaults to true. |
@LargeTest public void testCameraPairwiseScenario04() throws Exception {
genericPairwiseTestCase(Flash.OFF,Exposure.MAX,WhiteBalance.CLOUDY,SceneMode.AUTO,PictureSize.MEDIUM,Geotagging.OFF);
}
| Flash: Off / Exposure: Max / WB: Cloudy Scene: Auto / Pic: Med / Geo: off |
public static void assertStopped(){
if (!CLOCK_STATE.get().inHarness()) {
new AssertionError().printStackTrace();
}
assert CLOCK_STATE.get().inHarness();
}
| Throw an assertion error when the clock is not stopped. |
public OperationDefinition createOperationDefinition(){
OperationDefinitionImpl operationDefinition=new OperationDefinitionImpl();
return operationDefinition;
}
| <!-- begin-user-doc --> <!-- end-user-doc --> |
public final void writeDouble(double d) throws IOException {
this.writeLong(Double.doubleToLongBits(d));
}
| Writes an 8 byte Java double to the underlying output stream in little endian order. |
public static Vector3m toVector3m(Vector2 o){
return new Vector3m(o.x,0,o.z);
}
| Returns a Vector3m object with a y-value of 0. The x of the Vector2 becomes the x of the Vector3m, the y of the Vector2 becomes the z of the Vector3m. |
public FakeClock incrementTime(ReadableDuration duration){
incrementTime(duration.getMillis());
return this;
}
| Increments the clock time by the given duration. |
@Override protected Message createKeepAliveMessage(LocalCandidate candidate) throws StunException {
switch (candidate.getType()) {
case RELAYED_CANDIDATE:
return MessageFactory.createRefreshRequest();
case SERVER_REFLEXIVE_CANDIDATE:
boolean existsRelayedCandidate=false;
for (Candidate<?> aCandidate : getCandidates()) {
if (CandidateType.RELAYED_CANDIDATE.equals(aCandidate.getType())) {
existsRelayedCandidate=true;
break;
}
}
return existsRelayedCandidate ? null : super.createKeepAliveMessage(candidate);
default :
return super.createKeepAliveMessage(candidate);
}
}
| Creates a new STUN <tt>Message</tt> to be sent to the STUN server associated with the <tt>StunCandidateHarvester</tt> of this instance in order to keep a specific <tt>LocalCandidate</tt> (harvested by this instance) alive. |
public static BlockHeight readFrom(final Deserializer deserializer,final String label){
return new BlockHeight(deserializer.readLong(label));
}
| Reads a block height object. |
public synchronized void inverseAssociateAll(Primitive associate,Vertex target,Primitive type){
inverseAssociateAll(this.network.createVertex(associate),target,this.network.createVertex(type));
}
| Dissociate the source with each of the relationship targets by the type. |
private Eml copyMetadata(String shortname,File emlFile) throws ImportException {
File emlFile2=dataDir.resourceEmlFile(shortname);
try {
FileUtils.copyFile(emlFile,emlFile2);
}
catch ( IOException e1) {
log.error("Unable to copy EML File",e1);
}
Eml eml;
try {
InputStream in=new FileInputStream(emlFile2);
eml=EmlFactory.build(in);
}
catch ( FileNotFoundException e) {
eml=new Eml();
}
catch ( Exception e) {
deleteDirectoryContainingSingleFile(emlFile2);
throw new ImportException("Invalid EML document",e);
}
return eml;
}
| Copies incoming eml file to resource directory with name eml.xml. </br> This method retrieves a file handle to the eml.xml file in resource directory. It then copies the incoming emlFile over to this file. From this file an Eml instance is then populated and returned. </br> If the incoming eml file was invalid, meaning a valid eml.xml failed to be created, this method deletes the resource directory. To be safe, the resource directory will only be deleted if it exclusively contained the invalid eml.xml file. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.