code
stringlengths 10
174k
| nl
stringlengths 3
129k
|
---|---|
public static void assertEqualStreams(InputStream expIn,InputStream actIn,@Nullable Long expSize) throws IOException {
int bufSize=2345;
byte buf1[]=new byte[bufSize];
byte buf2[]=new byte[bufSize];
long pos=0;
while (true) {
int i1=actIn.read(buf1,0,bufSize);
int i2;
if (i1 == -1) i2=expIn.read(buf2,0,1);
else IOUtils.readFully(expIn,buf2,0,i2=i1);
if (i1 != i2) fail("Expects the same data [pos=" + pos + ", i1="+ i1+ ", i2="+ i2+ ']');
if (i1 == -1) break;
assertTrue("Expects the same data [pos=" + pos + ", i1="+ i1+ ", i2="+ i2+ ']',Arrays.equals(buf1,buf2));
pos+=i1;
}
if (expSize != null) assertEquals(expSize.longValue(),pos);
}
| Validate streams generate the same output. |
private boolean needFlip(long pos){
return second != null && second.contains(pos);
}
| Checks if position shifted enough to forget previous buffer. |
public static void loadRootUserDataCacheOnStart(){
EFLogger.debug("loadRootUserDataCacheOnStart");
users.put("root",UserData.restoreFromESData("root",rootPassword,"/*"));
}
| load authentication info when ES instance starts |
@Override public StatisticViewHolder onCreateViewHolder(ViewGroup parent,int viewType){
View v;
int layout;
Context parentContext=parent.getContext();
if (viewType == StatisticViewHolder.TYPE_LARGE) {
layout=R.layout.list_item_statistic_most_played;
}
else if (viewType == StatisticViewHolder.TYPE_SMALL) {
layout=R.layout.list_item_statistic_pie_chart;
}
else {
throw new RuntimeException("Invalid view type!");
}
v=LayoutInflater.from(parentContext).inflate(layout,parent,false);
LinearLayoutCompat.LayoutParams layoutParams=new LinearLayoutCompat.LayoutParams(LinearLayoutCompat.LayoutParams.MATCH_PARENT,LinearLayoutCompat.LayoutParams.WRAP_CONTENT);
v.setLayoutParams(layoutParams);
return new StatisticViewHolder(v,mUserLogicFactory,mChallengeDataSource,mApplication,mUser,mCategoryId);
}
| Called to create the ViewHolder at the given position. |
public void reserve(int len) throws IOException {
if (len > (buf.length - pos)) flushBuffer();
}
| reserve at least len bytes at the end of the buffer. Invalid if len > buffer.length |
public <T>T fromXML(final URL url,final T root){
return unmarshal(hierarchicalStreamDriver.createReader(url),root);
}
| Deserialize an object from a URL, populating the fields of the given root object instead of instantiating a new one. Note, that this is a special use case! With the ReflectionConverter XStream will write directly into the raw memory area of the existing object. Use with care! Depending on the parser implementation, some might take the file path as SystemId to resolve additional references. |
public boolean isDrawRoundedSlicesEnabled(){
return mDrawRoundedSlices;
}
| Returns true if the chart is set to draw each end of a pie-slice "rounded". |
public void cleanTemplate(Integer ID){
cleanTemplate("" + ID);
}
| Clean Template cache for this ID |
private void testGaussianDistribution(double mu,double sigma,DescriptiveStatistics statistics){
Assert.assertEquals(mu,statistics.getMean(),TestThresholds.STATISTICS_EPS);
Assert.assertEquals(sigma * sigma,statistics.getVariance(),TestThresholds.STATISTICS_EPS);
Assert.assertEquals(0.0,statistics.getSkewness(),TestThresholds.STATISTICS_EPS);
Assert.assertEquals(0.0,statistics.getKurtosis(),TestThresholds.STATISTICS_EPS);
}
| Asserts that the statistical distribution satisfies the properties of a Gaussian distribution with the specified mean and standard deviation. |
public SearchSourceBuilder sort(SortBuilder sort){
if (sorts == null) {
sorts=new ArrayList<>();
}
sorts.add(sort);
return this;
}
| Adds a sort builder. |
public void post(Object event){
post(event,EventType.DEFAULT_TAG);
}
| post a event |
@Override public void handlePatch(Operation patch){
if (!patch.hasBody()) {
patch.fail(new IllegalArgumentException("Body is required"));
return;
}
if (Operation.TX_ENSURE_COMMIT.equals(patch.getRequestHeader(Operation.TRANSACTION_HEADER))) {
handleCheckConflicts(patch);
return;
}
ResolutionRequest resolution=patch.getBody(ResolutionRequest.class);
if (resolution.kind != ResolutionRequest.KIND) {
patch.fail(new IllegalArgumentException("Unrecognized request kind: " + resolution.kind));
return;
}
TransactionServiceState currentState=getState(patch);
if (resolution.resolutionKind == ResolutionKind.ABORT) {
if (currentState.taskSubStage == SubStage.COMMITTED || currentState.taskSubStage == SubStage.COMMITTING) {
patch.fail(new IllegalStateException(String.format("Already %s",currentState.taskSubStage)));
return;
}
if (currentState.taskSubStage == SubStage.ABORTING || currentState.taskSubStage == SubStage.ABORTED) {
logInfo("Alreading in sub-stage %s. Completing request.",currentState.taskSubStage);
patch.complete();
return;
}
updateStage(patch,SubStage.ABORTING);
patch.complete();
handleAbort(currentState);
}
else if (resolution.resolutionKind == ResolutionKind.COMMIT) {
if (currentState.taskSubStage == SubStage.ABORTED || currentState.taskSubStage == SubStage.ABORTING) {
patch.fail(new IllegalStateException("Already aborted"));
return;
}
if (currentState.taskSubStage == SubStage.COMMITTED || currentState.taskSubStage == SubStage.COMMITTING) {
logInfo("Alreading in sub-stage %s. Completing request.",currentState.taskSubStage);
patch.complete();
return;
}
updateStage(patch,SubStage.RESOLVING);
patch.complete();
handleCommit(currentState);
}
else if (resolution.resolutionKind == ResolutionKind.COMMITTING) {
if (currentState.taskSubStage == SubStage.ABORTED || currentState.taskSubStage == SubStage.ABORTING) {
patch.fail(new IllegalStateException("Already aborted"));
return;
}
updateStage(patch,SubStage.COMMITTING);
patch.complete();
notifyServicesToCommit(currentState);
}
else if (resolution.resolutionKind == ResolutionKind.COMMITTED) {
updateStage(patch,SubStage.COMMITTED);
patch.complete();
}
else if (resolution.resolutionKind == ResolutionKind.ABORTED) {
updateStage(patch,SubStage.ABORTED);
patch.complete();
}
else {
patch.fail(new IllegalArgumentException("Unrecognized resolution kind: " + resolution.resolutionKind));
}
}
| Handles commits and aborts (requests to cancel/rollback). TODO 1: Should allow receiving number of transactions in flight TODO 2: Does not support 2PC for integrity checks yet! This will require specific handler from services TODO 3: Should eventually shield commit/abort against operations not coming via the /resolve utility suffix |
private List<AbstractOption> addConfigOptions(){
List<AbstractOption> result;
if (getPlugin() == null) {
log().debug("No plugin set?");
result=Collections.<AbstractOption>emptyList();
}
else {
List<AbstractOption> newOptions=new ArrayList<AbstractOption>();
log().info("Adding OptionSoapAction");
newOptions.add(0,m_OptionSoapAction);
log().info("Adding OptionNoSchema");
newOptions.add(1,m_OptionUseSchema);
log().info("Adding OptionSchemaFiles");
newOptions.add(2,m_OptionSchemaFiles);
if (m_OptionPayloadList.size() > 0) {
log().info("Adding Enc Pays ");
newOptions.add(3,m_OptionEncPays);
log().info("Adding Server Error Response table ");
newOptions.add(4,m_OptionServerResponse);
}
result=newOptions;
}
return result;
}
| This methods add the default config options to the OptionManagerEncryption. Those are: - Option for changing the SOAPAction. - Option for aborting the attack if one XSW message is accepted. - Option to not use any XML Schema. - Option to selected XML Schema files. - Option to add a search string. - The View Button - The Payload-Chooser Combobox |
protected Class loadArrayClassByComponentType(String className,ClassLoader classLoader) throws ClassNotFoundException {
int ndx=className.indexOf('[');
int multi=StringUtil.count(className,'[');
String componentTypeName=className.substring(0,ndx);
Class componentType=loadClass(componentTypeName,classLoader);
if (multi == 1) {
return Array.newInstance(componentType,0).getClass();
}
int[] multiSizes;
if (multi == 2) {
multiSizes=new int[]{0,0};
}
else if (multi == 3) {
multiSizes=new int[]{0,0,0};
}
else {
multiSizes=(int[])Array.newInstance(int.class,multi);
}
return Array.newInstance(componentType,multiSizes).getClass();
}
| Loads array class using component type. |
public static IMouseStateChange enterEdgeLabel(final CStateFactory<?,?> m_factory,final MouseEvent event,final HitInfo hitInfo){
final EdgeLabel l=hitInfo.getHitEdgeLabel();
return new CStateChange(m_factory.createEdgeLabelEnterState(l,event),true);
}
| Changes the state to edge label enter state. |
protected void flushRequirementChanges(){
AbstractDocument doc=(AbstractDocument)getDocument();
try {
doc.readLock();
View parent=null;
boolean horizontal=false;
boolean vertical=false;
synchronized (this) {
synchronized (stats) {
int n=getViewCount();
if ((n > 0) && (minorChanged || estimatedMajorSpan)) {
LayoutQueue q=getLayoutQueue();
ChildState min=getChildState(0);
ChildState pref=getChildState(0);
float span=0f;
for (int i=1; i < n; i++) {
ChildState cs=getChildState(i);
if (minorChanged) {
if (cs.min > min.min) {
min=cs;
}
if (cs.pref > pref.pref) {
pref=cs;
}
}
if (estimatedMajorSpan) {
span+=cs.getMajorSpan();
}
}
if (minorChanged) {
minRequest=min;
prefRequest=pref;
}
if (estimatedMajorSpan) {
majorSpan=span;
estimatedMajorSpan=false;
majorChanged=true;
}
}
}
if (majorChanged || minorChanged) {
parent=getParent();
if (parent != null) {
if (axis == X_AXIS) {
horizontal=majorChanged;
vertical=minorChanged;
}
else {
vertical=majorChanged;
horizontal=minorChanged;
}
}
majorChanged=false;
minorChanged=false;
}
}
if (parent != null) {
parent.preferenceChanged(this,horizontal,vertical);
Component c=getContainer();
if (c != null) {
c.repaint();
}
}
}
finally {
doc.readUnlock();
}
}
| Publish the changes in preferences upward to the parent view. This is normally called by the layout thread. |
public void test_addEdge_correctRejection_001(){
final int CAPACITY=5;
TxDag dag=new TxDag(CAPACITY);
Object tx1="tx1";
Object tx2="tx2";
dag.addEdge(tx1,tx2);
try {
dag.addEdge(tx1,tx2);
fail("Expecting exception: " + IllegalStateException.class);
}
catch ( IllegalStateException ex) {
log.info("Expected exception: " + ex);
}
}
| Test for correct rejection of addEdge() when edge already exists. |
public boolean createLifetimeReplacementConnection(ServerLocation currentServer,boolean idlePossible){
HashSet excludedServers=new HashSet();
ServerLocation sl=this.connectionFactory.findBestServer(currentServer,excludedServers);
while (sl != null) {
if (sl.equals(currentServer)) {
this.allConnectionsMap.extendLifeOfCnxToServer(currentServer);
break;
}
else {
if (!this.allConnectionsMap.hasExpiredCnxToServer(currentServer)) {
break;
}
Connection con=null;
try {
con=this.connectionFactory.createClientToServerConnection(sl,false);
}
catch ( GemFireSecurityException e) {
securityLogWriter.warning(LocalizedStrings.ConnectionManagerImpl_SECURITY_EXCEPTION_CONNECTING_TO_SERVER_0_1,new Object[]{sl,e});
}
catch ( ServerRefusedConnectionException srce) {
logger.warn(LocalizedMessage.create(LocalizedStrings.ConnectionManagerImpl_SERVER_0_REFUSED_NEW_CONNECTION_1,new Object[]{sl,srce}));
}
if (con == null) {
excludedServers.add(sl);
sl=this.connectionFactory.findBestServer(currentServer,excludedServers);
}
else {
getPoolStats().incLoadConditioningConnect();
if (!this.allConnectionsMap.hasExpiredCnxToServer(currentServer)) {
getPoolStats().incLoadConditioningReplaceTimeouts();
con.destroy();
break;
}
offerReplacementConnection(con,currentServer);
break;
}
}
}
if (sl == null) {
this.allConnectionsMap.extendLifeOfCnxToServer(currentServer);
}
return this.allConnectionsMap.checkForReschedule(true);
}
| An existing connections lifetime has expired. We only want to create one replacement connection at a time so this guy should block until this connection replaces an existing one. Note that if a connection is created here it must not count against the pool max and its idle time and lifetime must not begin until it actually replaces the existing one. |
public static IGeoRectangle parseLatLon(String path){
if (path != null) {
String[] minMax=getLastPath(path).split(GeoRectangle.DELIM_FIELD);
if ((minMax == null) || (minMax.length == 0)) return null;
String[] elements=minMax[0].split(GeoRectangle.DELIM_SUB_FIELD);
if ((elements != null) && (elements.length == 2)) {
String lat=elements[0];
String lon=elements[1];
GeoRectangle result=new GeoRectangle();
result.setLatitudeMin(getLatLon(lat));
result.setLogituedMin(getLatLon(lon));
if (minMax.length == 1) {
double delta=1;
if (lat.startsWith(" ")) {
delta=10.0;
}
else {
int posDecimal=lat.indexOf(".");
if (posDecimal >= 0) {
int numberDecimals=lat.length() - posDecimal - 1;
while (numberDecimals > 0) {
delta=delta / 10.0;
numberDecimals--;
}
}
}
result.setLatitudeMax(result.getLatitudeMin() + delta);
result.setLogituedMax(result.getLogituedMin() + delta);
return result;
}
else if (minMax.length == 2) {
elements=minMax[1].split(GeoRectangle.DELIM_SUB_FIELD);
if ((elements != null) && (elements.length == 2)) {
lat=elements[0];
lon=elements[1];
result.setLatitudeMax(getLatLon(lat));
result.setLogituedMax(getLatLon(lon));
return result;
}
}
}
}
return null;
}
| Format "lat,lon" or "lat,lon-lat,lon" |
@DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 12:33:59.600 -0500",hash_original_method="1719055BB7B83C8257DECB960F96EA3B",hash_generated_method="057AC4294C52FE0AC14AB3E2D4532546") @Deprecated public static Uri createPersonInMyContactsGroup(ContentResolver resolver,ContentValues values){
Uri contactUri=resolver.insert(People.CONTENT_URI,values);
if (contactUri == null) {
Log.e(TAG,"Failed to create the contact");
return null;
}
if (addToMyContactsGroup(resolver,ContentUris.parseId(contactUri)) == null) {
resolver.delete(contactUri,null,null);
return null;
}
return contactUri;
}
| Creates a new contacts and adds it to the "My Contacts" group. |
public MosaicDefinition(final Deserializer deserializer){
this.creator=Account.readFrom(deserializer,"creator",AddressEncoding.PUBLIC_KEY);
this.id=deserializer.readObject("id",null);
this.descriptor=MosaicDescriptor.readFrom(deserializer,"description");
this.properties=new DefaultMosaicProperties(deserializer.readObjectArray("properties",null));
this.levy=deserializer.readOptionalObject("levy",null);
this.validateFields();
}
| Deserializes a mosaic definition. |
private boolean processKeyUp(int keyCode){
if (keyCode == KeyEvent.KEYCODE_DEL) {
if (mInKbMode) {
if (!mTypedTimes.isEmpty()) {
int deleted=deleteLastTypedKey();
String deletedKeyStr;
if (deleted == getAmOrPmKeyCode(AM)) {
deletedKeyStr=mAmText;
}
else if (deleted == getAmOrPmKeyCode(PM)) {
deletedKeyStr=mPmText;
}
else {
deletedKeyStr=String.format("%d",getValFromKeyCode(deleted));
}
ViewCompatUtils.announceForAccessibility(mDelegator,String.format(mDeletedKeyFormat,deletedKeyStr));
updateDisplay(true);
}
}
}
else if (keyCode == KeyEvent.KEYCODE_0 || keyCode == KeyEvent.KEYCODE_1 || keyCode == KeyEvent.KEYCODE_2 || keyCode == KeyEvent.KEYCODE_3 || keyCode == KeyEvent.KEYCODE_4 || keyCode == KeyEvent.KEYCODE_5 || keyCode == KeyEvent.KEYCODE_6 || keyCode == KeyEvent.KEYCODE_7 || keyCode == KeyEvent.KEYCODE_8 || keyCode == KeyEvent.KEYCODE_9 || (!mIs24HourView && (keyCode == getAmOrPmKeyCode(AM) || keyCode == getAmOrPmKeyCode(PM)))) {
if (!mInKbMode) {
if (mRadialTimePickerView == null) {
Log.e(TAG,"Unable to initiate keyboard mode, TimePicker was null.");
return true;
}
mTypedTimes.clear();
tryStartingKbMode(keyCode);
return true;
}
if (addKeyIfLegal(keyCode)) {
updateDisplay(false);
}
return true;
}
return false;
}
| For keyboard mode, processes key events. |
private static List<String> addTargetClassesImport(List<String> lines,List<Attribute> attributes,Class<?> aClass){
List<Class<?>> classes=new ArrayList<Class<?>>();
for ( Attribute attribute : attributes) if (attribute.getClasses() != null && attribute.getClasses().length > 0) for ( Class<?> clazz : attribute.getClasses()) if (!classes.contains(clazz) && !aClass.getPackage().getName().equals(clazz.getPackage().getName())) classes.add(clazz);
if (classes.isEmpty()) return lines;
List<Class<?>> alreadyImported=new ArrayList<Class<?>>();
for ( Class<?> clazz : classes) if (existImport(lines,clazz)) alreadyImported.add(clazz);
classes.removeAll(alreadyImported);
List<String> result=new ArrayList<String>();
for ( String line : lines) {
result.add(line);
if (!packageFound(line,aClass)) continue;
for ( Class<?> clazz : classes) result.add("import " + clazz.getName() + ";");
}
return result;
}
| This method adds to lines the import of target classes. |
public static Put metadataToPut(MailboxMessage message){
Put put=new Put(messageRowKey(message));
put.add(MESSAGES_META_CF,MESSAGE_MODSEQ,Bytes.toBytes(message.getModSeq()));
put.add(MESSAGES_META_CF,MESSAGE_INTERNALDATE,Bytes.toBytes(message.getInternalDate().getTime()));
put.add(MESSAGES_META_CF,MESSAGE_MEDIA_TYPE,Bytes.toBytes(message.getMediaType()));
put.add(MESSAGES_META_CF,MESSAGE_SUB_TYPE,Bytes.toBytes(message.getSubType()));
put.add(MESSAGES_META_CF,MESSAGE_CONTENT_OCTETS,Bytes.toBytes(message.getFullContentOctets()));
put.add(MESSAGES_META_CF,MESSAGE_BODY_OCTETS,Bytes.toBytes(message.getBodyOctets()));
if (message.getTextualLineCount() != null) {
put.add(MESSAGES_META_CF,MESSAGE_TEXT_LINE_COUNT,Bytes.toBytes(message.getTextualLineCount()));
}
Flags flags=message.createFlags();
if (flags.contains(Flag.ANSWERED)) {
put.add(MESSAGES_META_CF,FLAGS_ANSWERED,MARKER_PRESENT);
}
if (flags.contains(Flag.DELETED)) {
put.add(MESSAGES_META_CF,FLAGS_DELETED,MARKER_PRESENT);
}
if (flags.contains(Flag.DRAFT)) {
put.add(MESSAGES_META_CF,FLAGS_DRAFT,MARKER_PRESENT);
}
if (flags.contains(Flag.FLAGGED)) {
put.add(MESSAGES_META_CF,FLAGS_FLAGGED,MARKER_PRESENT);
}
if (flags.contains(Flag.RECENT)) {
put.add(MESSAGES_META_CF,FLAGS_RECENT,MARKER_PRESENT);
}
if (flags.contains(Flag.SEEN)) {
put.add(MESSAGES_META_CF,FLAGS_SEEN,MARKER_PRESENT);
}
if (flags.contains(Flag.USER)) {
put.add(MESSAGES_META_CF,FLAGS_USER,MARKER_PRESENT);
}
for ( String flag : flags.getUserFlags()) {
put.add(MESSAGES_META_CF,userFlagToBytes(flag),MARKER_PRESENT);
}
int propNumber=0;
for ( Property prop : message.getProperties()) {
put.add(MESSAGES_META_CF,getQualifier(propNumber++),getValue(prop));
}
return put;
}
| Transforms only the metadata into a Put object. The rest of the message will be transfered using multiple Puts if size requires it. |
private void enablePlugins(PluginLoadOrder type){
if (type == PluginLoadOrder.STARTUP) {
helpMap.clear();
helpMap.loadConfig(config.getConfigFile(Key.HELP_FILE));
}
Plugin[] plugins=pluginManager.getPlugins();
for ( Plugin plugin : plugins) {
if (!plugin.isEnabled() && plugin.getDescription().getLoad() == type) {
List<Permission> perms=plugin.getDescription().getPermissions();
for ( Permission perm : perms) {
try {
pluginManager.addPermission(perm);
}
catch ( IllegalArgumentException ex) {
getLogger().log(Level.WARNING,"Plugin " + plugin.getDescription().getFullName() + " tried to register permission '"+ perm.getName()+ "' but it's already registered",ex);
}
}
try {
pluginManager.enablePlugin(plugin);
}
catch ( Throwable ex) {
logger.log(Level.SEVERE,"Error loading " + plugin.getDescription().getFullName(),ex);
}
}
}
if (type == PluginLoadOrder.POSTWORLD) {
commandMap.setFallbackCommands();
commandMap.registerServerAliases();
DefaultPermissions.registerCorePermissions();
helpMap.initializeCommands();
helpMap.amendTopics(config.getConfigFile(Key.HELP_FILE));
ConfigurationSection permConfig=config.getConfigFile(Key.PERMISSIONS_FILE);
List<Permission> perms=Permission.loadPermissions(permConfig.getValues(false),"Permission node '%s' in permissions config is invalid",PermissionDefault.OP);
for ( Permission perm : perms) {
try {
pluginManager.addPermission(perm);
}
catch ( IllegalArgumentException ex) {
getLogger().log(Level.WARNING,"Permission config tried to register '" + perm.getName() + "' but it's already registered",ex);
}
}
}
}
| Enable all plugins of the given load order type. |
public static void fill(int[] array,int start,int end,int value){
Arrays.checkStartAndEnd(array.length,start,end);
for (int i=start; i < end; i++) {
array[i]=value;
}
}
| Fills the specified range in the array with the specified element. |
public static PrivKey load(File file,final String password) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException, InvalidParameterSpecException {
if (file.length() < 3) throw new IllegalArgumentException("file is not a valid private key (too short file)");
byte[] keyData=FileUtil.readFile(file);
return load(keyData,password);
}
| Load private key from a PEM encoded file |
protected void loadTableOIS(Vector<?> data){
window.getWListbox().clear();
window.getWListbox().getModel().removeTableModelListener(window);
ListModelTable model=new ListModelTable(data);
model.addTableModelListener(window);
window.getWListbox().setData(model,getOISColumnNames());
configureMiniTable(window.getWListbox());
}
| Load Order/Invoice/Shipment data into Table |
public static void writeIgniteConfiguration(BinaryRawWriter w,IgniteConfiguration cfg){
assert w != null;
assert cfg != null;
w.writeBoolean(true);
w.writeBoolean(cfg.isClientMode());
w.writeIntArray(cfg.getIncludeEventTypes());
w.writeBoolean(true);
w.writeLong(cfg.getMetricsExpireTime());
w.writeBoolean(true);
w.writeInt(cfg.getMetricsHistorySize());
w.writeBoolean(true);
w.writeLong(cfg.getMetricsLogFrequency());
w.writeBoolean(true);
w.writeLong(cfg.getMetricsUpdateFrequency());
w.writeBoolean(true);
w.writeInt(cfg.getNetworkSendRetryCount());
w.writeBoolean(true);
w.writeLong(cfg.getNetworkSendRetryDelay());
w.writeBoolean(true);
w.writeLong(cfg.getNetworkTimeout());
w.writeString(cfg.getWorkDirectory());
w.writeString(cfg.getLocalHost());
w.writeBoolean(true);
w.writeBoolean(cfg.isDaemon());
w.writeBoolean(true);
w.writeBoolean(cfg.isLateAffinityAssignment());
CacheConfiguration[] cacheCfg=cfg.getCacheConfiguration();
if (cacheCfg != null) {
w.writeInt(cacheCfg.length);
for ( CacheConfiguration ccfg : cacheCfg) writeCacheConfiguration(w,ccfg);
}
else w.writeInt(0);
writeDiscoveryConfiguration(w,cfg.getDiscoverySpi());
CommunicationSpi comm=cfg.getCommunicationSpi();
if (comm instanceof TcpCommunicationSpi) {
w.writeBoolean(true);
TcpCommunicationSpiMBean tcp=(TcpCommunicationSpiMBean)comm;
w.writeInt(tcp.getAckSendThreshold());
w.writeLong(tcp.getConnectTimeout());
w.writeBoolean(tcp.isDirectBuffer());
w.writeBoolean(tcp.isDirectSendBuffer());
w.writeLong(tcp.getIdleConnectionTimeout());
w.writeString(tcp.getLocalAddress());
w.writeInt(tcp.getLocalPort());
w.writeInt(tcp.getLocalPortRange());
w.writeLong(tcp.getMaxConnectTimeout());
w.writeInt(tcp.getMessageQueueLimit());
w.writeInt(tcp.getReconnectCount());
w.writeInt(tcp.getSelectorsCount());
w.writeInt(tcp.getSlowClientQueueLimit());
w.writeInt(tcp.getSocketReceiveBuffer());
w.writeInt(tcp.getSocketSendBuffer());
w.writeBoolean(tcp.isTcpNoDelay());
w.writeInt(tcp.getUnacknowledgedMessagesBufferSize());
}
else w.writeBoolean(false);
BinaryConfiguration bc=cfg.getBinaryConfiguration();
w.writeBoolean(bc != null);
if (bc != null) w.writeBoolean(bc.isCompactFooter());
Map<String,?> attrs=cfg.getUserAttributes();
if (attrs != null) {
w.writeInt(attrs.size());
for ( Map.Entry<String,?> e : attrs.entrySet()) {
w.writeString(e.getKey());
w.writeObject(e.getValue());
}
}
else w.writeInt(0);
AtomicConfiguration atomic=cfg.getAtomicConfiguration();
if (atomic != null) {
w.writeBoolean(true);
w.writeInt(atomic.getAtomicSequenceReserveSize());
w.writeInt(atomic.getBackups());
writeEnumInt(w,atomic.getCacheMode(),AtomicConfiguration.DFLT_CACHE_MODE);
}
else w.writeBoolean(false);
TransactionConfiguration tx=cfg.getTransactionConfiguration();
if (tx != null) {
w.writeBoolean(true);
w.writeInt(tx.getPessimisticTxLogSize());
writeEnumInt(w,tx.getDefaultTxConcurrency(),TransactionConfiguration.DFLT_TX_CONCURRENCY);
writeEnumInt(w,tx.getDefaultTxIsolation(),TransactionConfiguration.DFLT_TX_ISOLATION);
w.writeLong(tx.getDefaultTxTimeout());
w.writeInt(tx.getPessimisticTxLogLinger());
}
else w.writeBoolean(false);
w.writeString(cfg.getIgniteHome());
w.writeLong(ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getInit());
w.writeLong(ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getMax());
}
| Writes Ignite configuration. |
public void flushFileContent(String mimeType,String charset,String fileName,String fileContent) throws IOException {
generateFileContent(mimeType,charset,fileName,fileContent);
this.response.flushBuffer();
}
| Flushes the response as a file. |
public AtomicIntChunks(final long length){
this(length,CHUNK_BITS);
}
| Constructs an index by splitting into array chunks. |
@Override public AmpException rethrow(String msg){
return new AmpException(msg,this);
}
| Rethrow the exception to include the proper stack trace. |
public boolean logout() throws IOException {
return FTPReply.isPositiveCompletion(quit());
}
| Logout of the FTP server by sending the QUIT command. <p> |
public Map<NetworkLite,List<StoragePort>> selectStoragePortsInNetworks(List<StoragePort> storagePorts,Collection<NetworkLite> networks,URI varrayURI,ExportPathParams pathParams){
Map<NetworkLite,List<StoragePort>> portsInNetwork=new HashMap<>();
for ( NetworkLite networkLite : networks) {
URI networkURI=networkLite.getId();
_log.info("Selecting ports for network {} {}",networkLite.getLabel(),networkLite.getId());
List<StoragePort> spList=new ArrayList<StoragePort>();
List<StoragePort> rspList=new ArrayList<StoragePort>();
List<String> unroutedPorts=new ArrayList<String>();
List<String> routedPorts=new ArrayList<String>();
List<String> wrongNetwork=new ArrayList<String>();
for ( StoragePort sp : storagePorts) {
if (sp.getNetwork().equals(networkURI) || (networkLite != null && networkLite.hasRoutedNetworks(sp.getNetwork()))) {
if (sp.getNetwork().equals(networkURI)) {
spList.add(sp);
unroutedPorts.add(portName(sp));
}
else {
_log.debug("Storage port {} is not in the requested network {} " + "but it is routed to it.",sp.getNativeGuid(),networkURI);
rspList.add(sp);
routedPorts.add(portName(sp));
}
}
else {
_log.debug("Storage port {} not selected because its network {} " + "is not the requested network {}",new Object[]{sp.getNativeGuid(),sp.getNetwork(),networkURI});
wrongNetwork.add(portName(sp));
}
}
if (!wrongNetwork.isEmpty()) {
_log.info("Ports not selected because they are not in the requested network: " + networkURI + " "+ Joiner.on(" ").join(wrongNetwork));
}
if (!rspList.isEmpty() && !spList.isEmpty()) {
_log.info("Ports not selected because they are routed and local ports are available: " + networkURI + " "+ Joiner.on(" ").join(routedPorts));
}
_log.info("Ports that were selected: " + (spList.isEmpty() ? Joiner.on(" ").join(routedPorts) : Joiner.on(" ").join(unroutedPorts)));
portsInNetwork.put(networkLite,spList.isEmpty() ? rspList : spList);
}
return portsInNetwork;
}
| Return list of storage ports from the given storage ports connected to the given network and with connectivity to the passed virtual array. |
protected synchronized void onResized(int columns,int rows){
onResized(new TerminalSize(columns,rows));
}
| Call this method when the terminal has been resized or the initial size of the terminal has been discovered. It will trigger all resize listeners, but only if the size has changed from before. |
public T coords(String value){
return attr("coords",value);
}
| Sets the <code>coords</code> attribute on the last started tag that has not been closed. |
protected EqualityOp_Impl(){
super();
}
| <!-- begin-user-doc --> <!-- end-user-doc --> |
private boolean isLeapYear(long year){
return !((year % 4) != 0 || (year % 100) == 0 && (year % 400) != 0);
}
| Returns true if the given year is a leap year. |
@Override public String createInitialLoadSqlFor(Node node,TriggerRouter trigger,Table table,TriggerHistory triggerHistory,Channel channel,String overrideSelectSql){
String sql=super.createInitialLoadSqlFor(node,trigger,table,triggerHistory,channel,overrideSelectSql);
sql=sql.replace("''","'");
return sql;
}
| All the templates have ' escaped because the SQL is inserted into a view. When returning the raw SQL for use as SQL it needs to be un-escaped. |
protected AbstractTParser(TokenStream input){
super(input);
}
| Create a new parser instance, pre-supplying the input token stream. |
public void sortArray(T[] d,Comparator<T> c){
this.data=d;
this.comp=c;
int len=Math.max((int)(100 * Math.log(d.length)),TEMP_SIZE);
len=Math.min(d.length,len);
@SuppressWarnings("unchecked") T[] t=(T[])new Object[len];
this.temp=t;
mergeSort(0,d.length - 1);
}
| Sort an array using the given comparator. |
public UnicodeReader(InputStream in) throws IOException {
this(in,null);
}
| Creates a reader using the encoding specified by the BOM in the file; if there is no recognized BOM, then a system default encoding is used. |
public String optString(String key,String defaultValue){
Object o=opt(key);
return o != null ? o.toString() : defaultValue;
}
| Get an optional string associated with a key. It returns the defaultValue if there is no such key. |
public final Cursor increment(int i){
index+=i;
return this;
}
| Increments the cursor index by the specified value. |
public void put(String key,Integer value){
mValues.put(key,value);
}
| Adds a value to the set. |
public static boolean isSkipPosting(final GameData data){
final boolean skipPosting;
data.acquireReadLock();
try {
skipPosting=Boolean.parseBoolean(data.getSequence().getStep().getProperties().getProperty(GameStep.PROPERTY_skipPosting,"false"));
}
finally {
data.releaseReadLock();
}
return skipPosting;
}
| Do we skip posting the game summary and save to a forum or email? |
public SpecialTextUnit showStrikeThrough(){
isShowStrikeThrough=true;
return this;
}
| Show StrikeThrough |
public Boolean isSnapshotLocked(){
return snapshotLocked;
}
| Gets the value of the snapshotLocked property. |
public void incFunctionExecutionsCompleted(){
this._stats.incInt(_functionExecutionsCompletedId,1);
}
| Increments the "FunctionExecutionsCompleted" stat. |
private static IgfsBlockLocation location(long start,long len,UUID... nodeIds){
assert nodeIds != null && nodeIds.length > 0;
Collection<ClusterNode> nodes=new ArrayList<>(nodeIds.length);
for ( UUID id : nodeIds) nodes.add(new GridTestNode(id));
return new IgfsBlockLocationImpl(start,len,nodes);
}
| Create block location. |
public static Map<String,Object> updateUserLoginId(DispatchContext ctx,Map<String,?> context){
Map<String,Object> result=new LinkedHashMap<String,Object>();
Delegator delegator=ctx.getDelegator();
GenericValue loggedInUserLogin=(GenericValue)context.get("userLogin");
List<String> errorMessageList=new LinkedList<String>();
Locale locale=(Locale)context.get("locale");
String userLoginId=(String)context.get("userLoginId");
String errMsg=null;
if ((userLoginId != null) && ("true".equals(EntityUtilProperties.getPropertyValue("security.properties","username.lowercase",delegator)))) {
userLoginId=userLoginId.toLowerCase();
}
String partyId=loggedInUserLogin.getString("partyId");
String password=loggedInUserLogin.getString("currentPassword");
String passwordHint=loggedInUserLogin.getString("passwordHint");
if (UtilValidate.isNotEmpty(partyId)) {
if (!loggedInUserLogin.isEmpty()) {
if (!partyId.equals(loggedInUserLogin.getString("partyId"))) {
errMsg=UtilProperties.getMessage(resource,"loginservices.party_with_party_id_exists_not_permission_create_user_login",locale);
errorMessageList.add(errMsg);
}
}
else {
errMsg=UtilProperties.getMessage(resource,"loginservices.must_logged_in_have_permission_create_user_login_exists",locale);
errorMessageList.add(errMsg);
}
}
GenericValue newUserLogin=null;
boolean doCreate=true;
try {
newUserLogin=EntityQuery.use(delegator).from("UserLogin").where("userLoginId",userLoginId).queryOne();
}
catch ( GenericEntityException e) {
Debug.logWarning(e,"",module);
Map<String,String> messageMap=UtilMisc.toMap("errorMessage",e.getMessage());
errMsg=UtilProperties.getMessage(resource,"loginservices.could_not_create_login_user_read_failure",messageMap,locale);
errorMessageList.add(errMsg);
}
if (newUserLogin != null) {
if (!newUserLogin.get("partyId").equals(partyId)) {
Map<String,String> messageMap=UtilMisc.toMap("userLoginId",userLoginId);
errMsg=UtilProperties.getMessage(resource,"loginservices.could_not_create_login_user_with_ID_exists",messageMap,locale);
errorMessageList.add(errMsg);
}
else {
doCreate=false;
}
}
else {
newUserLogin=delegator.makeValue("UserLogin",UtilMisc.toMap("userLoginId",userLoginId));
}
newUserLogin.set("passwordHint",passwordHint);
newUserLogin.set("partyId",partyId);
newUserLogin.set("currentPassword",password);
newUserLogin.set("enabled","Y");
newUserLogin.set("disabledDateTime",null);
if (errorMessageList.size() > 0) {
return ServiceUtil.returnError(errorMessageList);
}
try {
if (doCreate) {
newUserLogin.create();
}
else {
newUserLogin.store();
}
}
catch ( GenericEntityException e) {
Debug.logWarning(e,"",module);
Map<String,String> messageMap=UtilMisc.toMap("errorMessage",e.getMessage());
errMsg=UtilProperties.getMessage(resource,"loginservices.could_not_create_login_user_write_failure",messageMap,locale);
return ServiceUtil.returnError(errMsg);
}
loggedInUserLogin.set("enabled","N");
loggedInUserLogin.set("disabledDateTime",UtilDateTime.nowTimestamp());
try {
loggedInUserLogin.store();
}
catch ( GenericEntityException e) {
Debug.logWarning(e,"",module);
Map<String,String> messageMap=UtilMisc.toMap("errorMessage",e.getMessage());
errMsg=UtilProperties.getMessage(resource,"loginservices.could_not_disable_old_login_user_write_failure",messageMap,locale);
return ServiceUtil.returnError(errMsg);
}
result.put(ModelService.RESPONSE_MESSAGE,ModelService.RESPOND_SUCCESS);
result.put("newUserLogin",newUserLogin);
return result;
}
| Updates the UserLoginId for a party, replicating password, etc from current login and expiring the old login. |
public Object runSafely(Catbert.FastStack stack) throws Exception {
return stack.getUIMgrSafe().getSTVVersion();
}
| Returns the value of the 'STVVersion' Attribute under the Global Theme Widget. This is used for dependencies relating to plugins. |
@Override public void run(){
amIActive=true;
String inputHeader=null;
String outputHeader=null;
int row, col, x, y;
double z, min, max;
float progress=0;
int a;
int filterSizeX=3;
int filterSizeY=3;
int dX[];
int dY[];
int midPointX;
int midPointY;
int numPixelsInFilter;
boolean filterRounded=false;
double[] filterShape;
boolean reflectAtBorders=false;
if (args.length <= 0) {
showFeedback("Plugin parameters have not been set.");
return;
}
for (int i=0; i < args.length; i++) {
if (i == 0) {
inputHeader=args[i];
}
else if (i == 1) {
outputHeader=args[i];
}
else if (i == 2) {
filterSizeX=Integer.parseInt(args[i]);
}
else if (i == 3) {
filterSizeY=Integer.parseInt(args[i]);
}
else if (i == 4) {
filterRounded=Boolean.parseBoolean(args[i]);
}
else if (i == 5) {
reflectAtBorders=Boolean.parseBoolean(args[i]);
}
}
if ((inputHeader == null) || (outputHeader == null)) {
showFeedback("One or more of the input parameters have not been set properly.");
return;
}
try {
WhiteboxRaster inputFile=new WhiteboxRaster(inputHeader,"r");
inputFile.isReflectedAtEdges=reflectAtBorders;
int rows=inputFile.getNumberRows();
int cols=inputFile.getNumberColumns();
double noData=inputFile.getNoDataValue();
WhiteboxRaster outputFile=new WhiteboxRaster(outputHeader,"rw",inputHeader,WhiteboxRaster.DataType.FLOAT,noData);
outputFile.setPreferredPalette(inputFile.getPreferredPalette());
if (Math.floor(filterSizeX / 2d) == (filterSizeX / 2d)) {
showFeedback("Filter dimensions must be odd numbers. The specified filter x-dimension" + " has been modified.");
filterSizeX++;
}
if (Math.floor(filterSizeY / 2d) == (filterSizeY / 2d)) {
showFeedback("Filter dimensions must be odd numbers. The specified filter y-dimension" + " has been modified.");
filterSizeY++;
}
numPixelsInFilter=filterSizeX * filterSizeY;
dX=new int[numPixelsInFilter];
dY=new int[numPixelsInFilter];
filterShape=new double[numPixelsInFilter];
midPointX=(int)Math.floor(filterSizeX / 2);
midPointY=(int)Math.floor(filterSizeY / 2);
if (!filterRounded) {
a=0;
for (row=0; row < filterSizeY; row++) {
for (col=0; col < filterSizeX; col++) {
dX[a]=col - midPointX;
dY[a]=row - midPointY;
filterShape[a]=1;
a++;
}
}
}
else {
double aSqr=midPointX * midPointX;
double bSqr=midPointY * midPointY;
a=0;
for (row=0; row < filterSizeY; row++) {
for (col=0; col < filterSizeX; col++) {
dX[a]=col - midPointX;
dY[a]=row - midPointY;
z=(dX[a] * dX[a]) / aSqr + (dY[a] * dY[a]) / bSqr;
if (z > 1) {
filterShape[a]=0;
}
else {
filterShape[a]=1;
}
a++;
}
}
}
for (row=0; row < rows; row++) {
for (col=0; col < cols; col++) {
z=inputFile.getValue(row,col);
if (z != noData) {
min=z;
max=z;
for (a=0; a < numPixelsInFilter; a++) {
x=col + dX[a];
y=row + dY[a];
z=inputFile.getValue(y,x);
if (z != noData) {
if (z < min) {
min=z;
}
if (z > max) {
max=z;
}
}
}
outputFile.setValue(row,col,(max - min));
}
else {
outputFile.setValue(row,col,noData);
}
}
if (cancelOp) {
cancelOperation();
return;
}
progress=(float)(100f * row / (rows - 1));
updateProgress((int)progress);
}
outputFile.addMetadataEntry("Created by the " + getDescriptiveName() + " tool.");
outputFile.addMetadataEntry("Created on " + new Date());
inputFile.close();
outputFile.close();
returnData(outputHeader);
}
catch ( OutOfMemoryError oe) {
myHost.showFeedback("An out-of-memory error has occurred during operation.");
}
catch ( Exception e) {
myHost.showFeedback("An error has occurred during operation. See log file for details.");
myHost.logException("Error in " + getDescriptiveName(),e);
}
finally {
updateProgress("Progress: ",0);
amIActive=false;
myHost.pluginComplete();
}
}
| Used to execute this plugin tool. |
public void drawCube(){
GLES20.glUseProgram(cubeProgram);
GLES20.glUniform3fv(cubeLightPosParam,1,lightPosInEyeSpace,0);
GLES20.glUniformMatrix4fv(cubeModelParam,1,false,modelCube,0);
GLES20.glUniformMatrix4fv(cubeModelViewParam,1,false,modelView,0);
GLES20.glVertexAttribPointer(cubePositionParam,COORDS_PER_VERTEX,GLES20.GL_FLOAT,false,0,cubeVertices);
GLES20.glUniformMatrix4fv(cubeModelViewProjectionParam,1,false,modelViewProjection,0);
GLES20.glVertexAttribPointer(cubeNormalParam,3,GLES20.GL_FLOAT,false,0,cubeNormals);
GLES20.glVertexAttribPointer(cubeColorParam,4,GLES20.GL_FLOAT,false,0,isLookingAtObject() ? cubeFoundColors : cubeColors);
GLES20.glDrawArrays(GLES20.GL_TRIANGLES,0,36);
checkGLError("Drawing cube");
}
| Draw the cube. <p>We've set all of our transformation matrices. Now we simply pass them into the shader. |
@Override public boolean equals(Object theObject){
if (theObject instanceof Timestamp) {
return equals((Timestamp)theObject);
}
return false;
}
| Tests to see if this timestamp is equal to a supplied object. |
public byte[] peek(long wait) throws KeeperException, InterruptedException {
Preconditions.checkArgument(wait > 0);
TimerContext time;
if (wait == Long.MAX_VALUE) {
time=stats.time(dir + "_peek_wait_forever");
}
else {
time=stats.time(dir + "_peek_wait" + wait);
}
updateLock.lockInterruptibly();
try {
long waitNanos=TimeUnit.MILLISECONDS.toNanos(wait);
while (waitNanos > 0) {
byte[] result=firstElement();
if (result != null) {
return result;
}
waitNanos=changed.awaitNanos(waitNanos);
}
return null;
}
finally {
updateLock.unlock();
time.stop();
}
}
| Returns the data at the first element of the queue, or null if the queue is empty after wait ms. |
public static CacheHeader readHeader(InputStream is) throws IOException {
CacheHeader entry=new CacheHeader();
int magic=readInt(is);
if (magic != CACHE_MAGIC) {
throw new IOException();
}
entry.key=readString(is);
entry.etag=readString(is);
if (entry.etag.equals("")) {
entry.etag=null;
}
entry.serverDate=readLong(is);
entry.ttl=readLong(is);
entry.responseHeaders=readStringStringMap(is);
return entry;
}
| Reads the header off of an InputStream and returns a CacheHeader object. |
public synchronized void flush() throws IOException {
if (!initialized) return;
checkNotClosed();
trimToSize();
journalWriter.flush();
}
| Force buffered operations to the filesystem. |
public void testDivideBigDecimalScaleRoundingModeHALF_EVEN(){
String a="3736186567876876578956958765675671119238118911893939591735";
int aScale=5;
String b="74723342238476237823787879183470";
int bScale=15;
int newScale=7;
RoundingMode rm=RoundingMode.HALF_EVEN;
String c="500002603731642864013619132621009722.1803810";
BigDecimal aNumber=new BigDecimal(new BigInteger(a),aScale);
BigDecimal bNumber=new BigDecimal(new BigInteger(b),bScale);
BigDecimal result=aNumber.divide(bNumber,newScale,rm);
assertEquals("incorrect value",c,result.toString());
assertEquals("incorrect scale",newScale,result.scale());
}
| divide(BigDecimal, scale, RoundingMode) |
public static boolean needToDo(String tag){
return toDoSet.contains(tag);
}
| Checks if a tag is currently marked as 'to do'. |
public ExecutionState basicGetState(){
return state;
}
| <!-- begin-user-doc --> <!-- end-user-doc --> |
@Override protected boolean accept(String propertyValue){
int major;
int minor;
Matcher matcher=MAJOR_MINOR_VERSION_PATTERN.matcher(propertyValue);
if (matcher.matches()) {
major=Integer.parseInt(matcher.group(1));
minor=Integer.parseInt(matcher.group(2));
}
else {
throw new RuntimeException("Malformed Age property value '" + propertyValue + "'");
}
return unicodeVersion.majorVersion > major || (unicodeVersion.majorVersion == major && unicodeVersion.minorVersion >= minor);
}
| Returns true if the given property value, which is a major.minor Unicode version, is less than or equal to the Unicode version, false otherwise. |
public boolean isValidRepository() throws LocalRepositoryException {
final String prefix="isValidRepository: ";
_log.debug(prefix);
final String[] cmd={_SYSTOOL_CMD,_SYSTOOL_IS_APPLIANCE};
final String[] ret=exec(prefix,cmd);
if (ret == null) {
throw SyssvcException.syssvcExceptions.localRepoError(prefix + "Internal error. Null output");
}
else if (ret.length != 1) {
throw SyssvcException.syssvcExceptions.localRepoError(prefix + "Internal error. No results.");
}
_log.info(prefix + ret[0]);
return Boolean.valueOf(ret[0]);
}
| Check if the current deployment is an appliance |
public void testProperties() throws Exception {
ReplicatorCapabilities caps1=new ReplicatorCapabilities();
TungstenProperties cprops=caps1.asProperties();
ReplicatorCapabilities caps2=new ReplicatorCapabilities(cprops);
testEquality(caps1,caps2);
caps1=new ReplicatorCapabilities();
caps1.addRole("master");
caps1.addRole("slave");
caps1.setConsistencyCheck(true);
caps1.setFlush(true);
caps1.setHeartbeat(true);
caps1.setProvisionDriver(ReplicatorCapabilities.PROVISION_DONOR);
caps1.setModel(ReplicatorCapabilities.MODEL_PEER);
cprops=caps1.asProperties();
caps2=new ReplicatorCapabilities(cprops);
testEquality(caps1,caps2);
}
| Tests round trip storage in properties. |
public void run(final String[] args){
if (args.length == 0) {
System.out.println("Too few arguments.");
printUsage();
System.exit(1);
}
Iterator<String> argIter=new ArgumentParser(args).iterator();
String arg=argIter.next();
if (arg.equals("-h") || arg.equals("--help")) {
printUsage();
System.exit(0);
}
else {
String inputFile=arg;
if (!argIter.hasNext()) {
System.out.println("Too few arguments.");
printUsage();
System.exit(1);
}
String outputFile=argIter.next();
if (argIter.hasNext()) {
System.out.println("Too many arguments.");
printUsage();
System.exit(1);
}
run(inputFile,outputFile);
}
}
| Runs the network cleaning algorithms over the network read in from the argument list, and writing the resulting network out to a file again |
public void registerInterestRegistrationListener(InterestRegistrationListener listener){
final String s=LocalizedStrings.RemoteBridgeServer_INTERESTREGISTRATIONLISTENERS_CANNOT_BE_REGISTERED_ON_A_REMOTE_BRIDGESERVER.toLocalizedString();
throw new UnsupportedOperationException(s);
}
| Registers a new <code>InterestRegistrationListener</code> with the set of <code>InterestRegistrationListener</code>s. |
@Override public String toString(){
return toString(5,false);
}
| Convert the DoubleVecor to a string |
private void zInternalSetDateTextField(String text){
skipTextFieldChangedFunctionWhileTrue=true;
dateTextField.setText(text);
skipTextFieldChangedFunctionWhileTrue=false;
zEventTextFieldChanged();
}
| zInternalSetDateTextField, This is called whenever we need to programmatically change the date text field. The purpose of this function is to make sure that text field change events only occur once per programmatic text change, instead of occurring twice. The default behavior is that the text change event will fire twice. (By default, it changes once to clear the text, and changes once to change it to new text.) |
@Override public Iterator<Instruction> iterator(){
return m_instructions.iterator();
}
| Can be used to iterate over all instructions in the basic block. |
protected String handleTime(Time time){
return time == null ? null : time.toString();
}
| Return time read from ResultSet. |
private static String decodeBase900toBase10(int[] codewords,int count) throws FormatException {
BigInteger result=BigInteger.ZERO;
for (int i=0; i < count; i++) {
result=result.add(EXP900[count - i - 1].multiply(BigInteger.valueOf(codewords[i])));
}
String resultString=result.toString();
if (resultString.charAt(0) != '1') {
throw FormatException.getFormatInstance();
}
return resultString.substring(1);
}
| Convert a list of Numeric Compacted codewords from Base 900 to Base 10. |
public TextEditorPane(int textMode,boolean wordWrapEnabled){
super(textMode);
setLineWrap(wordWrapEnabled);
try {
init(null,null);
}
catch ( IOException ioe) {
ioe.printStackTrace();
}
}
| Creates a new <code>TextEditorPane</code>. The file will be given a default name. |
@Override public int hashCode(){
return mID;
}
| Calculates the hash code value for a BaseObj. |
public static double stirlingFormula(double x){
double STIR[]={7.87311395793093628397E-4,-2.29549961613378126380E-4,-2.68132617805781232825E-3,3.47222221605458667310E-3,8.33333333333482257126E-2};
double MAXSTIR=143.01608;
double w=1.0 / x;
double y=Math.exp(x);
w=1.0 + w * polevl(w,STIR,4);
if (x > MAXSTIR) {
double v=Math.pow(x,0.5 * x - 0.25);
y=v * (v / y);
}
else {
y=Math.pow(x,x - 0.5) / y;
}
y=SQTPI * y * w;
return y;
}
| Returns the Gamma function computed by Stirling's formula. The polynomial STIR is valid for 33 <= x <= 172. |
public void reset(ActionMapping mapping,HttpServletRequest request){
super.reset(mapping,request);
niveles=new String[0];
}
| Inicia el formulario. |
public String serializedClustererFileTipText(){
return "A file containing the serialized model of a built clusterer.";
}
| Returns the tip text for this property. |
void unSelect(){
if (mHideOnSelect) {
show(true);
}
}
| callback from bottom navigation tab when it is un-selected |
public void connectToTangoCamera(Tango tango,int cameraId){
mRenderer.connectCamera(tango,cameraId);
}
| Gets a textureId from a valid OpenGL Context through Rajawali and connects it to the TangoRajawaliView. Use OnFrameAvailable events or updateTexture calls to update the view with the latest camera data. Only the RGB and fisheye cameras are currently supported. |
public static MContainer copy(MWebProject project,MCStage stage,String path){
MContainer cc=getDirect(stage.getCtx(),stage.getCM_CStage_ID(),stage.get_TrxName());
if (cc == null) cc=new MContainer(stage.getCtx(),0,stage.get_TrxName());
cc.setStage(project,stage,path);
cc.save();
if (!stage.isSummary()) {
cc.updateElements(project,stage,stage.get_TrxName());
cc.updateTTables(project,stage,stage.get_TrxName());
}
return cc;
}
| Copy Stage into Container |
private void discoverUnManagedCifsShares(AccessProfile profile){
URI storageSystemId=profile.getSystemId();
StorageSystem storageSystem=_dbClient.queryObject(StorageSystem.class,storageSystemId);
if (null == storageSystem) {
return;
}
storageSystem.setDiscoveryStatus(DiscoveredDataObject.DataCollectionJobStatus.IN_PROGRESS.toString());
String detailedStatusMessage="Discovery of NetAppC Unmanaged Cifs started";
NetAppClusterApi netAppCApi=new NetAppClusterApi.Builder(storageSystem.getIpAddress(),storageSystem.getPortNumber(),storageSystem.getUsername(),storageSystem.getPassword()).https(true).build();
Collection<String> attrs=new ArrayList<String>();
for ( String property : ntpPropertiesList) {
attrs.add(SupportedNtpFileSystemInformation.getFileSystemInformation(property));
}
try {
List<UnManagedCifsShareACL> unManagedCifsShareACLList=new ArrayList<UnManagedCifsShareACL>();
List<UnManagedCifsShareACL> oldunManagedCifsShareACLList=new ArrayList<UnManagedCifsShareACL>();
HashSet<UnManagedSMBFileShare> unManagedSMBFileShareHashSet=null;
List<Map<String,String>> fileSystemInfo=netAppCApi.listVolumeInfo(null,attrs);
List<StorageVirtualMachineInfo> svms=netAppCApi.listSVM();
for ( StorageVirtualMachineInfo svmInfo : svms) {
netAppCApi=new NetAppClusterApi.Builder(storageSystem.getIpAddress(),storageSystem.getPortNumber(),storageSystem.getUsername(),storageSystem.getPassword()).https(true).svm(svmInfo.getName()).build();
List<Map<String,String>> listShares=netAppCApi.listShares(null);
if (listShares != null && !listShares.isEmpty()) {
_logger.info("total no of shares in netappC system (s) {}",listShares.size());
}
HashMap<String,HashSet<UnManagedSMBFileShare>> unMangedSMBFileShareMapSet=getAllCifsShares(listShares);
for ( String key : unMangedSMBFileShareMapSet.keySet()) {
unManagedSMBFileShareHashSet=unMangedSMBFileShareMapSet.get(key);
String fileSystem=key;
String nativeId=fileSystem;
int index=fileSystem.indexOf('/',1);
if (-1 != index) {
fileSystem=fileSystem.substring(0,index);
_logger.info("Unmanaged FileSystem Name {}",fileSystem);
}
String fsUnManagedFsNativeGuid=NativeGUIDGenerator.generateNativeGuidForPreExistingFileSystem(storageSystem.getSystemType(),storageSystem.getSerialNumber().toUpperCase(),fileSystem);
UnManagedFileSystem unManagedFs=checkUnManagedFileSystemExistsInDB(fsUnManagedFsNativeGuid);
boolean fsAlreadyExists=unManagedFs == null ? false : true;
if (fsAlreadyExists) {
_logger.debug("retrieve info for file system: " + fileSystem);
String svm=getOwningSVM(fileSystem,fileSystemInfo);
String addr=getSVMAddress(svm,svms);
UnManagedSMBShareMap tempUnManagedSMBShareMap=new UnManagedSMBShareMap();
createSMBShareMap(unManagedSMBFileShareHashSet,tempUnManagedSMBShareMap,addr,nativeId);
if (tempUnManagedSMBShareMap.size() > 0 && !tempUnManagedSMBShareMap.isEmpty()) {
unManagedFs.setUnManagedSmbShareMap(tempUnManagedSMBShareMap);
unManagedFs.setHasShares(true);
unManagedFs.putFileSystemCharacterstics(UnManagedFileSystem.SupportedFileSystemCharacterstics.IS_FILESYSTEM_EXPORTED.toString(),TRUE);
_logger.debug("SMB Share map for NetAppC UMFS {} = {}",unManagedFs.getLabel(),unManagedFs.getUnManagedSmbShareMap());
}
UnManagedCifsShareACL existingACL=null;
List<UnManagedCifsShareACL> tempUnManagedCifsShareAclList=getACLs(unManagedSMBFileShareHashSet,netAppCApi,storageSystem,unManagedFs.getId());
if (tempUnManagedCifsShareAclList != null && !tempUnManagedCifsShareAclList.isEmpty()) {
for ( UnManagedCifsShareACL unManagedCifsShareACL : tempUnManagedCifsShareAclList) {
existingACL=checkUnManagedFsCifsACLExistsInDB(_dbClient,unManagedCifsShareACL.getNativeGuid());
if (existingACL == null) {
unManagedCifsShareACLList.add(unManagedCifsShareACL);
}
else {
existingACL.setInactive(true);
oldunManagedCifsShareACLList.add(existingACL);
unManagedCifsShareACLList.add(unManagedCifsShareACL);
}
}
}
if (unManagedSMBFileShareHashSet != null && !unManagedSMBFileShareHashSet.isEmpty()) {
_dbClient.persistObject(unManagedFs);
_logger.info("File System {} has Shares and their Count is {}",unManagedFs.getId(),tempUnManagedSMBShareMap.size());
}
if (unManagedCifsShareACLList.size() >= MAX_UMFS_RECORD_SIZE) {
_logger.info("Saving Number of New UnManagedCifsShareACL(s) {}",unManagedCifsShareACLList.size());
_partitionManager.insertInBatches(unManagedCifsShareACLList,Constants.DEFAULT_PARTITION_SIZE,_dbClient,UNMANAGED_SHARE_ACL);
unManagedCifsShareACLList.clear();
}
if (!oldunManagedCifsShareACLList.isEmpty() && oldunManagedCifsShareACLList.size() >= MAX_UMFS_RECORD_SIZE) {
_logger.info("Update Number of Old UnManagedCifsShareACL(s) {}",oldunManagedCifsShareACLList.size());
_partitionManager.updateInBatches(oldunManagedCifsShareACLList,Constants.DEFAULT_PARTITION_SIZE,_dbClient,UNMANAGED_SHARE_ACL);
oldunManagedCifsShareACLList.clear();
}
}
else {
_logger.info("FileSystem " + unManagedFs + "is not present in ViPR DB. Hence ignoring "+ fileSystem+ " share");
}
}
}
if (unManagedCifsShareACLList != null && !unManagedCifsShareACLList.isEmpty()) {
_logger.info("Saving Number of New UnManagedCifsShareACL(s) {}",unManagedCifsShareACLList.size());
_partitionManager.insertInBatches(unManagedCifsShareACLList,Constants.DEFAULT_PARTITION_SIZE,_dbClient,UNMANAGED_SHARE_ACL);
unManagedCifsShareACLList.clear();
}
if (oldunManagedCifsShareACLList != null && !oldunManagedCifsShareACLList.isEmpty()) {
_logger.info("Saving Number of Old UnManagedCifsShareACL(s) {}",oldunManagedCifsShareACLList.size());
_partitionManager.updateInBatches(oldunManagedCifsShareACLList,Constants.DEFAULT_PARTITION_SIZE,_dbClient,UNMANAGED_SHARE_ACL);
oldunManagedCifsShareACLList.clear();
}
storageSystem.setDiscoveryStatus(DiscoveredDataObject.DataCollectionJobStatus.COMPLETE.toString());
detailedStatusMessage=String.format("Discovery completed successfully for NetAppC: %s",storageSystemId.toString());
}
catch ( NetAppCException ve) {
if (null != storageSystem) {
cleanupDiscovery(storageSystem);
storageSystem.setDiscoveryStatus(DiscoveredDataObject.DataCollectionJobStatus.ERROR.toString());
}
_logger.error("discoverStorage failed. Storage system: " + storageSystemId);
}
catch ( Exception e) {
if (null != storageSystem) {
cleanupDiscovery(storageSystem);
storageSystem.setDiscoveryStatus(DiscoveredDataObject.DataCollectionJobStatus.ERROR.toString());
}
_logger.error("discoverStorage failed. Storage system: " + storageSystemId,e);
}
finally {
if (storageSystem != null) {
try {
storageSystem.setLastDiscoveryStatusMessage(detailedStatusMessage);
_dbClient.persistObject(storageSystem);
}
catch ( Exception ex) {
_logger.error("Error while persisting object to DB",ex);
}
}
}
}
| discover the unmanaged cifs shares and add shares to ViPR db |
public boolean isDefaultPrf(){
return prf == null || prf.equals(algid_hmacWithSHA1);
}
| Return true if the PRF is the default (hmacWithSHA1) |
public Path tools(){
return root.resolve("tools");
}
| Gets the tools directory. |
public static void listDatasets(final Bigquery bigquery,final String projectId) throws IOException {
Datasets.List datasetRequest=bigquery.datasets().list(projectId);
DatasetList datasetList=datasetRequest.execute();
if (datasetList.getDatasets() != null) {
List<DatasetList.Datasets> datasets=datasetList.getDatasets();
System.out.println("Available datasets\n----------------");
System.out.println(datasets.toString());
for ( DatasetList.Datasets dataset : datasets) {
System.out.format("%s\n",dataset.getDatasetReference().getDatasetId());
}
}
}
| Display all BigQuery datasets associated with a project. |
public TransactionImpl(){
}
| Constructs an instance of a Transaction |
public Vertex discover(boolean details,boolean fork,String filter,Vertex vertex,Vertex vertex2,Vertex vertex3,Vertex vertex4,Vertex vertex5){
String keywords=vertex.getDataValue();
String keywordscaps=Utils.capitalize(vertex.getDataValue());
if ((vertex2 != null) && !vertex2.is(Primitive.NULL)) {
keywords=keywords + " " + vertex2.getDataValue();
keywordscaps=keywordscaps + " " + Utils.capitalize(vertex2.getDataValue());
}
if ((vertex3 != null) && !vertex3.is(Primitive.NULL)) {
keywords=keywords + " " + vertex3.getDataValue();
keywordscaps=keywordscaps + " " + Utils.capitalize(vertex3.getDataValue());
}
if ((vertex4 != null) && !vertex4.is(Primitive.NULL)) {
keywords=keywords + " " + vertex4.getDataValue();
keywordscaps=keywordscaps + " " + Utils.capitalize(vertex4.getDataValue());
}
if ((vertex5 != null) && !vertex5.is(Primitive.NULL)) {
keywords=keywords + " " + vertex5.getDataValue();
keywordscaps=keywordscaps + " " + Utils.capitalize(vertex5.getDataValue());
}
if (keywords != null) {
if (vertex.instanceOf(Primitive.PRONOUN) || vertex.instanceOf(Primitive.ARTICLE) || vertex.instanceOf(Primitive.PUNCTUATION)|| (vertex.hasRelationship(Primitive.MEANING) && (vertex.getRelationship(Primitive.MEANING).instanceOf(Primitive.NUMBER)))|| vertex.instanceOf(Primitive.QUESTION)|| this.discoveryIgnoreWords.contains(vertex.getData())) {
return null;
}
Vertex compoundWord=vertex.getNetwork().createVertex(keywords);
Vertex lastChecked=compoundWord.getRelationship(getPrimitive());
if (lastChecked == null) {
compoundWord.addRelationship(getPrimitive(),compoundWord.getNetwork().createTimestamp());
try {
int cascade=0;
if (!details) {
cascade=-1;
}
Vertex result=null;
if (result == null) {
result=processSearch(keywords,cascade,fork,filter,vertex.getNetwork(),new HashMap<String,Vertex>());
}
if (result != null) {
compoundWord=vertex.getNetwork().createWord(keywords);
compoundWord.addRelationship(Primitive.MEANING,result);
compoundWord=vertex.getNetwork().createWord(keywords.toLowerCase());
compoundWord.addRelationship(Primitive.MEANING,result);
compoundWord=vertex.getNetwork().createWord(keywordscaps);
compoundWord.addRelationship(Primitive.MEANING,result);
}
return result;
}
catch ( Exception failed) {
log(failed);
}
}
return compoundWord.mostConscious(Primitive.MEANING);
}
return null;
}
| Self API Discover the meaning of the word. |
public AttributeCertificateHolder(int digestedObjectType,ASN1ObjectIdentifier digestAlgorithm,ASN1ObjectIdentifier otherObjectTypeID,byte[] objectDigest){
holder=new Holder(new ObjectDigestInfo(digestedObjectType,otherObjectTypeID,new AlgorithmIdentifier(digestAlgorithm),Arrays.clone(objectDigest)));
}
| Constructs a holder for v2 attribute certificates with a hash value for some type of object. <p> <code>digestedObjectType</code> can be one of the following: <ul> <li>0 - publicKey - A hash of the public key of the holder must be passed. <li>1 - publicKeyCert - A hash of the public key certificate of the holder must be passed. <li>2 - otherObjectDigest - A hash of some other object type must be passed. <code>otherObjectTypeID</code> must not be empty. </ul> <p> This cannot be used if a v1 attribute certificate is used. |
private static boolean matchIntlPrefix(String a,int len){
int state=0;
for (int i=0; i < len; i++) {
char c=a.charAt(i);
switch (state) {
case 0:
if (c == '+') state=1;
else if (c == '0') state=2;
else if (isNonSeparator(c)) return false;
break;
case 2:
if (c == '0') state=3;
else if (c == '1') state=4;
else if (isNonSeparator(c)) return false;
break;
case 4:
if (c == '1') state=5;
else if (isNonSeparator(c)) return false;
break;
default :
if (isNonSeparator(c)) return false;
break;
}
}
return state == 1 || state == 3 || state == 5;
}
| all of a up to len must be an international prefix or separators/non-dialing digits |
List<NamedRange> removeSurrogates(int startCodePoint,int endCodePoint){
assert startCodePoint <= endCodePoint;
if (startCodePoint >= 0xD800 && endCodePoint <= 0xDFFF) {
return Collections.emptyList();
}
List<NamedRange> ranges=new ArrayList<NamedRange>();
if (endCodePoint < 0xD800 || startCodePoint > 0xDFFF) {
ranges.add(new NamedRange(startCodePoint,endCodePoint));
return ranges;
}
if (startCodePoint < 0xD800) {
ranges.add(new NamedRange(startCodePoint,0xD7FF));
}
if (endCodePoint > 0xDFFF) {
ranges.add(new NamedRange(0xE000,endCodePoint));
}
return ranges;
}
| Returns 0, 1, or 2 ranges for the given interval, depending on whether it is contained within; is entirely outside of or starts or ends within; or straddles the surrogate range 0xD800-0xDFFF, respectively. |
public void printMap(HashMap<String,HashMap<String,HashSet<Integer>>> map){
map.forEach(null);
}
| Depub method which write the filter "value" map to std::out |
public DenseVector(int n){
u=new float[n];
}
| Constructs a new vector with the specified capacity |
public InlineQueryResultVideo.InlineQueryResultVideoBuilder videoHeight(int videoHeight){
this.video_height=videoHeight;
return this;
}
| *Optional Sets the height of the video file being sent for this result |
public void visitEnd(){
if (fv != null) {
fv.visitEnd();
}
}
| Visits the end of the field. This method, which is the last one to be called, is used to inform the visitor that all the annotations and attributes of the field have been visited. |
public SizedTextField(final int columns,final Dimension dim){
super(columns);
setPreferredSize(dim);
setMaximumSize(dim);
}
| Creates a <tt>JTextField</tt> with a standard size and with the specified number of columns and the specified <tt>Dimension</tt>.. |
@Override public void clear(){
stackTop=0;
}
| clear the stack |
public void createSubscription(final Color color,final boolean subscribe,final TabbedSubscriptionDetails subscriptionDetails,final MqttAsyncConnection connection,final MqttConnectionController connectionController,final Object parent){
logger.info("Creating subscription for " + subscriptionDetails.getTopic());
final MqttSubscription subscription=new MqttSubscription(subscriptionDetails.getTopic(),subscriptionDetails.getQos(),color,connection.getProperties().getConfiguredProperties().getMinMessagesStoredPerTopic(),connection.getPreferredStoreSize(),uiEventQueue,eventBus,connection.getStore().getFormattingManager(),UiProperties.getSummaryMaxPayloadLength(configurationManager.getUiPropertyFile()));
subscription.setConnection(connection);
subscription.setDetails(subscriptionDetails);
final SubscriptionController subscriptionController=createSubscriptionTab(false,subscription.getStore(),subscription,connection,connectionController);
subscriptionController.getTab().setContextMenu(ContextMenuUtils.createSubscriptionTabContextMenu(connection,subscription,eventBus,this,configurationManager,subscriptionController));
subscriptionController.setConnectionController(connectionController);
subscriptionController.setFormatters(configurationManager.getFormatters());
subscriptionController.setTabStatus(new TabStatus());
subscriptionController.getTabStatus().setVisibility(PaneVisibilityStatus.NOT_VISIBLE);
subscriptionController.init();
subscriptionController.onSubscriptionStatusChanged(new SubscriptionStatusChangeEvent(subscription));
subscription.setSubscriptionController(subscriptionController);
final SpyPerspective perspective=viewManager.getPerspective();
subscriptionController.setViewVisibility(MqttViewManager.getDetailedViewStatus(perspective),MqttViewManager.getBasicViewStatus(perspective));
subscriptionController.getTabStatus().setVisibility(PaneVisibilityStatus.ATTACHED);
subscriptionController.getTabStatus().setParent(connectionController.getSubscriptionTabs());
final TabPane subscriptionTabs=connectionController.getSubscriptionTabs();
subscriptionTabs.getTabs().add(subscriptionController.getTab());
subscriptionTabs.getTabs().get(ALL_SUBSCRIPTIONS_TAB_INDEX).setDisable(false);
if (subscribe) {
logger.debug("Trying to subscribe {}",subscription.getTopic());
connection.subscribe(subscription);
}
else {
connection.addSubscription(subscription);
subscription.setActive(false);
}
}
| Creates a subscription and a tab for it. |
public static List<TriggerMessage> create(TriggerType triggerType,List<TriggerProcessParameter> params,Organization receiver){
List<TriggerMessage> messages=Collections.singletonList((new TriggerMessage(triggerType,params,Collections.singletonList(receiver))));
return messages;
}
| Convenience method to constructs a new trigger message list based on the given parameters. |
@DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 12:55:31.650 -0500",hash_original_method="97FF8506F533416A8B40E097933B45CB",hash_generated_method="E01E632F05C3B4BB240F0FFBFCB3F338") public javax.sip.address.SipURI createSipURI(String user,String host) throws ParseException {
if (host == null) throw new NullPointerException("null host");
StringBuffer uriString=new StringBuffer("sip:");
if (user != null) {
uriString.append(user);
uriString.append("@");
}
if (host.indexOf(':') != host.lastIndexOf(':') && host.trim().charAt(0) != '[') host='[' + host + ']';
uriString.append(host);
StringMsgParser smp=new StringMsgParser();
try {
SipUri sipUri=smp.parseSIPUrl(uriString.toString());
return sipUri;
}
catch ( ParseException ex) {
throw new ParseException(ex.getMessage(),0);
}
}
| Create a SipURI |
public EntryLink(Class<E> entryClass){
this.entryClass=entryClass;
}
| Constructs an entry link that points to the given entry type. |
public SMJReportViewer(Integer AD_PInstance_ID,String nameTrx,Integer idReport,Integer C_Period_ID,Integer AD_PrintFont_ID,MReportColumn[] columns){
super();
reportId=idReport;
m_AD_PInstance_ID=AD_PInstance_ID;
trxName=nameTrx;
p_C_Period_ID=C_Period_ID;
p_AD_PrintFont_ID=AD_PrintFont_ID;
m_columns=columns;
if (!MRole.getDefault().isCanReport(m_AD_Table_ID)) {
this.onClose();
}
try {
m_ctx=Env.getCtx();
dynInit();
init();
}
catch ( Exception e) {
log.log(Level.SEVERE,"",e);
FDialog.error(m_WindowNo,this,"LoadError",e.getLocalizedMessage());
this.onClose();
}
}
| Static Layout |
protected void decrypt(byte[] b,int off,int len,long fp){
for (int i=off; i < off + len; i++) {
b[i]=(byte)decrypt(b[i],fp++);
}
}
| Decrypt a range within a byte array. |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.