code
stringlengths 10
174k
| nl
stringlengths 3
129k
|
---|---|
public static <T extends ServiceDocument>boolean documentEquals(Class<T> type,T document1,T document2) throws IllegalAccessException {
ServiceDocumentDescription documentDescription=ServiceDocumentDescription.Builder.create().buildDescription(type,EnumSet.noneOf(Service.ServiceOption.class));
return ServiceDocument.equals(documentDescription,document1,document2);
}
| Compare the hash of two documents. |
public Map<String,String> find(String userId,String keyFilter) throws ServerException {
requireNonNull(userId,"Required non-null user id");
return preferenceDao.getPreferences(userId,keyFilter);
}
| Finds user's preferences. |
private void checkField(final boolean invalid,final String failLabel,final String fieldLabel) throws RequestProcessAdviceException {
if (invalid) {
throw new RequestProcessAdviceException(new JSONObject().put(Keys.MSG,langPropsService.get(failLabel) + " - " + langPropsService.get(fieldLabel)));
}
}
| Checks field. |
public void addSuperClass(ClassType type){
addSuperClassNoBidirectionalUpdate(type);
type.addSubclassNoBidirectionalUpdate(this);
}
| Adds a superclass of this class and ensures that the back-reference on the referred entity is set as well. |
public GivenName(){
super(KEY);
}
| Constructs an instance using the default key. |
public void removeGrid(String gridName){
gridNames.remove(gridName);
}
| Remove grid name. |
protected void engineInit(int opmode,Key key,AlgorithmParameterSpec params,SecureRandom random) throws InvalidKeyException, InvalidAlgorithmParameterException {
core.init(opmode,key,params,random);
}
| Initializes this cipher with a key, a set of algorithm parameters, and a source of randomness. <p>The cipher is initialized for one of the following four operations: encryption, decryption, key wrapping or key unwrapping, depending on the value of <code>opmode</code>. <p>If this cipher (including its underlying feedback or padding scheme) requires any random bytes, it will get them from <code>random</code>. |
public ResultSet monitor(ResultSet rs){
return (ResultSet)monitorJDBC(rs);
}
| Monitor a resultSets methods. Note the version that takes an explicit class is used for when the class is a proxy |
public CharClassInterval(int start,int end,int charClass){
this.start=start;
this.end=end;
this.charClass=charClass;
}
| Creates a new CharClassInterval from <CODE>start</code> to <CODE>end</code> that belongs to character class <CODE>charClass</code>. |
public static void removeMonitor(DependencyMonitor monitor){
monitors.remove(monitor);
}
| Unregister a dependency monitor. |
private byte readAndCheckByte() throws IOException, EOFException {
int b1=in.read();
if (-1 == b1) {
throw new EOFException();
}
return (byte)b1;
}
| Reads a byte from the input stream checking that the end of file (EOF) has not been encountered. |
@Override public void configureHyperlinkLabelProvider(com.google.inject.Binder binder){
binder.bind(org.eclipse.jface.viewers.ILabelProvider.class).annotatedWith(org.eclipse.xtext.ui.editor.hyperlinking.HyperlinkLabelProvider.class).to(N4JSHyperlinkLabelProvider.class);
}
| Binds a specific label provider for the hyper linking use case. |
private synchronized long waitForAtLeastOneAvailableConnection(long waitTime) throws PoolExhaustedException {
while (availableSize() == 0) {
if (waitTime <= 0) throw new PoolExhaustedException("ConnectionPool: pool is empty - increase either maxPoolSize or borrowConnectionTimeout");
long before=System.currentTimeMillis();
try {
if (LOGGER.isTraceEnabled()) LOGGER.logTrace(this + ": about to wait for connection during " + waitTime+ "ms...");
this.wait(waitTime);
}
catch ( InterruptedException ex) {
InterruptedExceptionHelper.handleInterruptedException(ex);
if (LOGGER.isTraceEnabled()) LOGGER.logTrace(this + ": interrupted during wait",ex);
}
if (LOGGER.isTraceEnabled()) LOGGER.logTrace(this + ": done waiting.");
long now=System.currentTimeMillis();
waitTime-=(now - before);
}
return waitTime;
}
| Wait until the connection pool contains an available connection or a timeout happens. Returns immediately if the pool already contains a connection in state available. |
protected void sendFunctionGroup1(){
byte[] result=jmri.NmraPacket.function0Through4Packet(address.getNumber(),address.isLongAddress(),getF0(),getF1(),getF2(),getF3(),getF4());
station.sendPacket(result,1);
}
| Send the message to set the state of functions F0, F1, F2, F3, F4. |
TaskProgress(String stageName,int taskId){
this.stageName=stageName;
this.taskId=taskId;
}
| Defines a new task progress tracker for the given task ID. |
public static final LoginManager acquireLoginManager(LoginType loginType,Map<String,?> configs) throws IOException, LoginException {
synchronized (LoginManager.class) {
LoginManager loginManager=CACHED_INSTANCES.get(loginType);
if (loginManager == null) {
loginManager=new LoginManager(loginType,configs);
CACHED_INSTANCES.put(loginType,loginManager);
}
return loginManager.acquire();
}
}
| Returns an instance of `LoginManager` and increases its reference count. `release()` should be invoked when the `LoginManager` is no longer needed. This method will try to reuse an existing `LoginManager` for the provided `mode` if available. However, it expects `configs` to be the same for every invocation and it will ignore them in the case where it's returning a cached instance of `LoginManager`. This is a bit ugly and it would be nicer if we could pass the `LoginManager` to `ChannelBuilders.create` and shut it down when the broker or clients are closed. It's straightforward to do the former, but it's more complicated to do the latter without making the consumer API more complex. |
public String current(){
return this.currentState;
}
| Get the current group name of the callback. |
public static boolean lineLocationContainment(Location loc1,Location loc2){
return (loc1.beginLine() >= loc2.beginLine()) && (loc2.endLine() >= loc1.endLine());
}
| True iff the range of lines specified by loc1 is a subset of the range of lines specified by loc2. |
public File makeLargeGzipFile(int kbytes) throws IOException {
final byte[] line=new byte[1024];
final File file=File.createTempFile("test","GzipAsynch.gz");
try (GZIPOutputStream out=new GZIPOutputStream(new FileOutputStream(file))){
for (int i=0; i < kbytes; i++) {
for (int pos=0; pos < 1024; pos++) {
line[pos]=(byte)('!' + (pos * (long)i) % 91);
}
line[1023]=(byte)'\n';
out.write(line);
}
}
return file;
}
| Creates a largish gzipped file containing <code>numCopies</code> of <code>line</code>. |
@Override public void clear(){
}
| Clears any cached information. |
@Override public RabbitGroup saveGroup(RabbitGroup group){
return groupRepository.save(group);
}
| Save rabbit group to repository |
public void dispose(){
if (glHandle == 0) return;
delete();
if (data.isManaged()) if (managedTextures.get(Gdx.app) != null) managedTextures.get(Gdx.app).removeValue(this,true);
}
| Disposes all resources associated with the texture |
public static String toString(InputStream input) throws IOException {
return toString(input,null);
}
| Get the contents of an <code>InputStream</code> as a String using the default character encoding of the platform. <p> This method buffers the input internally, so there is no need to use a <code>BufferedInputStream</code>. |
public final static VersionInfo loadVersionInfo(final String pckg,ClassLoader clsldr){
if (pckg == null) {
throw new IllegalArgumentException("Package identifier must not be null.");
}
if (clsldr == null) clsldr=Thread.currentThread().getContextClassLoader();
Properties vip=null;
try {
InputStream is=clsldr.getResourceAsStream(pckg.replace('.','/') + "/" + VERSION_PROPERTY_FILE);
if (is != null) {
try {
Properties props=new Properties();
props.load(is);
vip=props;
}
finally {
is.close();
}
}
}
catch ( IOException ex) {
}
VersionInfo result=null;
if (vip != null) result=fromMap(pckg,vip,clsldr);
return result;
}
| Loads version information for a package. |
public DgKSNetwork convertNetworkLanesAndSignals(Network network,Lanes lanes,SignalsData signals,Envelope signalsBoundingBox,double startTime,double endTime){
log.info("Checking cycle time...");
this.cycle=readCycle(signals);
log.info("cycle set to " + this.cycle);
signalizedLinks=this.getSignalizedLinkIds(signals.getSignalSystemsData());
log.info("Converting network ...");
this.timeInterval=endTime - startTime;
this.signalsBoundingBox=signalsBoundingBox;
this.dgNetwork=this.convertNetwork(network,lanes,signals);
log.info("Network converted.");
return this.dgNetwork;
}
| converts the given matsim network into a ks-model network with crossings and streets and returns it |
private static String formatNumberCroreFormat(final BigDecimal num){
final double absAmount=num.abs().doubleValue();
final long numLakhs=(long)(absAmount / 100000);
final double numThousands=absAmount - (numLakhs * 100000);
final DecimalFormat formatter=new DecimalFormat("#,##");
final String firstPart=(num.doubleValue() < 0 ? "-" : "") + (numLakhs > 0 ? formatter.format(numLakhs) + "," : "");
formatter.applyPattern("00,000.00");
return (firstPart + formatter.format(numThousands));
}
| Formats given number in Indian format (CRORE format). e.g. 1234567890.5 will be formatted as 1,23,45,67,890.50 |
public static int ELIBSCN(){
return 81;
}
| .lib section in a.out corrupted |
public void run(){
while (this.stop) {
System.out.print("\b ");
}
}
| Implementation of <code>run</code> method |
public static synchronized int pollId(final Class<?> clazz){
Class<?> matchClass=null;
if (COUNTERS.containsKey(clazz)) {
matchClass=clazz;
}
else if (!NO_COUNTERS.contains(clazz)) {
for ( Class<?> key : COUNTERS.keySet()) {
if (key.isAssignableFrom(clazz)) {
matchClass=key;
break;
}
}
}
int result=-1;
if (matchClass == null) {
NO_COUNTERS.add(clazz);
result=pollGlobalId();
}
else {
result=COUNTERS.get(matchClass);
COUNTERS.put(matchClass,result + 1);
}
if (result < 0) {
throw new IllegalStateException("The generated id for class:" + clazz.getName() + " is negative. Possible integer overflow.");
}
return result;
}
| Returns a valid id for the specified class. |
public boolean isSupportedLookAndFeel(){
return true;
}
| Returns <code>true</code>; every platform permits this look and feel. |
public String toGnuStepASCIIPropertyList(){
StringBuilder ascii=new StringBuilder();
toASCIIGnuStep(ascii,0);
ascii.append(NEWLINE);
return ascii.toString();
}
| Generates a valid ASCII property list in GnuStep format which has this NSDictionary as its root object. The generated property list complies with the format as described in <a href="http://www.gnustep.org/resources/documentation/Developer/Base/Reference/NSPropertyList.html"> GnuStep - NSPropertyListSerialization class documentation </a> |
public SafeTimeTracker(long delay,long random){
internalDelay=delay;
randomRange=random;
}
| In many situations, it is a bad idea to have all objects of the same kind to be waiting for the exact same amount of time, as that can lead to some situation where they're all synchronized and got to work all at the same time. When created with a random range, the mark that is set when reaching the expect delay will be added with a random number between [0, range[, meaning that the event will take between 0 and range more tick to run. |
private static void scrapeLink(String episodeURL,int episodeNum,Series series){
StringBuilder episodeTextBuffer=new StringBuilder("Episode Number: " + episodeNum + "<br>");
String episodeText;
URL url;
InputStream is=null;
BufferedReader br;
String line;
try {
url=new URL(episodeURL);
is=url.openStream();
br=new BufferedReader(new InputStreamReader(is));
while ((line=br.readLine()) != null) {
episodeTextBuffer.append(line);
episodeTextBuffer.append(" ");
}
}
catch ( IOException ioe) {
ioe.printStackTrace();
}
finally {
try {
if (is != null) is.close();
}
catch ( IOException ioe) {
}
}
episodeText=episodeTextBuffer.toString();
episodeText=episodeText.replaceAll("\\n","");
episodeText=episodeText.replaceAll("<br>","\n");
episodeText=episodeText.replaceAll("</div>(.*\n)*.*","\n");
episodeText=episodeText.replaceAll("<[^>]*>","\n");
episodeText=episodeText.replace(" ","");
episodeText=episodeText.replaceAll("\\n+\\s*","\n");
episodeText=episodeText.replaceAll("\\n{2,}","\n");
episodeText=episodeText.replaceAll(":;",": ");
saveEpisode(episodeText,episodeNum,series);
}
| Scrape the given episode using the provided information |
public static boolean isConfigFileKeyword(String name){
return CONFIG_KEYWORDS.contains(name);
}
| Checks if name is a configuration file keyword |
public void replaceAnnFile(Reader readerAnnFile){
m_pathAnnFile=null;
m_readerAnnFile=readerAnnFile;
m_isUpdateAnnFile=true;
if (!isModified()) setEditFlag(FolderEditFlag.UPDATE);
}
| Reemplaza el fichero de anotaciones asociado al documento |
public IntStack(int blocksize){
super(blocksize);
}
| Construct a IntVector, using the given block size. |
private GrantorRequestProcessor(InternalDistributedSystem system,InternalDistributedMember elder){
super(system,elder);
}
| Creates a new instance of GrantorRequestProcessor |
public static SecureConnectionMode parse(String value,String defaultValue){
SecureConnectionMode mode=parse(value);
if (mode == null && defaultValue != null) mode=parse(defaultValue);
return mode;
}
| Determine if the supplied value is one of the predefined options. |
public void testServerResponseRetransmissions() throws Exception {
String oldRetransValue=System.getProperty(StackProperties.MAX_CTRAN_RETRANSMISSIONS);
System.setProperty(StackProperties.MAX_CTRAN_RETRANSMISSIONS,"2");
System.setProperty(StackProperties.MAX_CTRAN_RETRANS_TIMER,"100");
System.setProperty(StackProperties.KEEP_CRANS_AFTER_A_RESPONSE,"true");
stunStack.addRequestListener(serverAddress,requestCollector);
stunStack.sendRequest(bindingRequest,serverAddress,clientAddress,responseCollector);
requestCollector.waitForRequest();
Vector<StunMessageEvent> reqs=requestCollector.getRequestsForTransaction(bindingRequest.getTransactionID());
StunMessageEvent evt=reqs.get(0);
byte[] tid=evt.getMessage().getTransactionID();
stunStack.sendResponse(tid,bindingResponse,serverAddress,clientAddress);
Thread.sleep(500);
assertTrue("There were too few retransmissions of a binding response: " + responseCollector.receivedResponses.size(),responseCollector.receivedResponses.size() < 3);
if (oldRetransValue != null) System.getProperty(StackProperties.MAX_CTRAN_RETRANSMISSIONS,oldRetransValue);
else System.clearProperty(StackProperties.MAX_CTRAN_RETRANSMISSIONS);
System.clearProperty(StackProperties.MAX_CTRAN_RETRANS_TIMER);
}
| Makes sure that once a request has been answered by the server, retransmissions of this request are not propagated to the UA and are automatically handled with a retransmission of the last seen response |
@DSComment("Private Method") @DSBan(DSCat.PRIVATE_METHOD) @DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 13:01:21.661 -0500",hash_original_method="9928E14A90ED22F7792AF824C555C38E",hash_generated_method="FD09E15A05B5DCDBEE2328F70AACD50E") private TextImpl firstTextNodeInCurrentRun(){
TextImpl firstTextInCurrentRun=this;
for (Node p=getPreviousSibling(); p != null; p=p.getPreviousSibling()) {
short nodeType=p.getNodeType();
if (nodeType == Node.TEXT_NODE || nodeType == Node.CDATA_SECTION_NODE) {
firstTextInCurrentRun=(TextImpl)p;
}
else {
break;
}
}
return firstTextInCurrentRun;
}
| Returns the first text or CDATA node in the current sequence of text and CDATA nodes. |
private static void addDefaultProfile(SpringApplication app,SimpleCommandLinePropertySource source){
if (!source.containsProperty("spring.profiles.active") && !System.getenv().containsKey("SPRING_PROFILES_ACTIVE")) {
app.setAdditionalProfiles(Constants.SPRING_PROFILE_DEVELOPMENT);
}
}
| If no profile has been configured, set by default the "dev" profile. |
public ApproximationSetPlot(DiagnosticTool frame,String metric){
super(frame,metric);
setLayout(new BorderLayout());
}
| Constructs a new plot do display the Pareto approximation set. |
public static void assertNotNull(Object object){
assertTrue(object != null);
}
| Assert that a value is not null. |
private static boolean oRule(String s){
int pos=s.length() - 1;
if (pos < 2) return false;
if (!isVowel(s,pos) && isVowel(s,pos - 1) && !isVowel(s,pos - 2)) {
switch (s.charAt(pos)) {
case 'w':
case 'x':
case 'y':
return false;
default :
return true;
}
}
return false;
}
| *o - the stem ends cvc, where the second c is not W, X or Y (e.g. -WIL, -HOP). |
void refreshAccessPoints(){
if (mWifiManager.isWifiEnabled()) {
mScanner.resume();
}
getPreferenceScreen().removeAll();
}
| Refreshes acccess points and ask Wifi module to scan networks again. |
public boolean isDefaultButton(){
JRootPane root=SwingUtilities.getRootPane(this);
if (root != null) {
return root.getDefaultButton() == this;
}
return false;
}
| Gets the value of the <code>defaultButton</code> property, which if <code>true</code> means that this button is the current default button for its <code>JRootPane</code>. Most look and feels render the default button differently, and may potentially provide bindings to access the default button. |
public void testCase16(){
byte aBytes[]={-127,100,56,7,98,-1,39,-128,127};
byte bBytes[]={-127,100,56,7,98,-1,39,-128,127};
int aSign=1;
int bSign=1;
byte rBytes[]={0};
BigInteger aNumber=new BigInteger(aSign,aBytes);
BigInteger bNumber=new BigInteger(bSign,bBytes);
BigInteger result=aNumber.remainder(bNumber);
byte resBytes[]=new byte[rBytes.length];
resBytes=result.toByteArray();
for (int i=0; i < resBytes.length; i++) {
assertTrue(resBytes[i] == rBytes[i]);
}
assertEquals("incorrect sign",0,result.signum());
}
| Remainder of division of equal numbers |
public EditableOMRect(OMRect omc){
setGraphic(omc);
}
| Create the EditableOMRect with an OMRect already defined, ready for editing. |
protected Node export(Node n,AbstractDocument d){
super.export(n,d);
AbstractElement ae=(AbstractElement)n;
if (attributes != null) {
NamedNodeMap map=attributes;
for (int i=map.getLength() - 1; i >= 0; i--) {
AbstractAttr aa=(AbstractAttr)map.item(i);
if (aa.getSpecified()) {
Attr attr=(Attr)aa.deepExport(aa.cloneNode(false),d);
if (aa instanceof AbstractAttrNS) {
ae.setAttributeNodeNS(attr);
}
else {
ae.setAttributeNode(attr);
}
}
}
}
return n;
}
| Exports this node to the given document. |
public static void main(String[] args) throws IOException {
long t1=Util.getTimestamp(2003,4,1);
long t2=Util.getTimestamp(2003,5,1);
System.out.println("t1 = " + t1);
System.out.println("t2 = " + t2);
String rrdPath=Util.getRrd4jDemoPath("demo.rrd");
DataProcessor dp=new DataProcessor(t1,t2);
dp.addDatasource("X",rrdPath,"sun",ConsolFun.AVERAGE);
dp.addDatasource("Y",rrdPath,"shade",ConsolFun.AVERAGE);
dp.addDatasource("Z","X,Y,+,2,/");
dp.addDatasource("DERIVE[Z]","Z,PREV(Z),-,STEP,/");
dp.addDatasource("TREND[Z]","DERIVE[Z],SIGN");
dp.addDatasource("AVG[Z]","Z",ConsolFun.AVERAGE);
dp.addDatasource("DELTA","Z,AVG[Z],-");
long laptime=System.currentTimeMillis();
dp.processData();
System.out.println("Data processed in " + (System.currentTimeMillis() - laptime) + " milliseconds\n---");
System.out.println(dp.dump());
System.out.println("\nAggregates for X");
Aggregates agg=dp.getAggregates("X");
System.out.println(agg.dump());
System.out.println("\nAggregates for Y");
agg=dp.getAggregates("Y");
System.out.println(agg.dump());
System.out.println("\n95-percentile for X: " + Util.formatDouble(dp.get95Percentile("X")));
System.out.println("95-percentile for Y: " + Util.formatDouble(dp.get95Percentile("Y")));
System.out.println("\nLast archive update time was: " + dp.getLastRrdArchiveUpdateTime());
}
| Cute little demo. Uses demo.rrd file previously created by basic Rrd4j demo. |
private void afterServerCommit(TXCommitMessage txcm){
if (this.internalAfterSendCommit != null) {
this.internalAfterSendCommit.run();
}
GemFireCacheImpl cache=GemFireCacheImpl.getInstance();
if (cache == null) {
return;
}
cache.getCancelCriterion().checkCancelInProgress(null);
InternalDistributedSystem ds=cache.getDistributedSystem();
DM dm=ds.getDistributionManager();
txcm.setDM(dm);
txcm.setAckRequired(false);
txcm.setDisableListeners(true);
cache.getTxManager().setTXState(null);
txcm.hookupRegions(dm);
txcm.basicProcess();
}
| perform local cache modifications using the server's TXCommitMessage |
private boolean conditionCH1(String value,int index){
return ((contains(value,0,4,"VAN ","VON ") || contains(value,0,3,"SCH")) || contains(value,index - 2,6,"ORCHES","ARCHIT","ORCHID") || contains(value,index + 2,1,"T","S")|| ((contains(value,index - 1,1,"A","O","U","E") || index == 0) && (contains(value,index + 2,1,L_R_N_M_B_H_F_V_W_SPACE) || index + 1 == value.length() - 1)));
}
| Complex condition 1 for 'CH' |
public static void toggleBreakpointStatus(final BreakpointManager manager,final INaviModule module,final UnrelocatedAddress unrelocatedAddress){
Preconditions.checkNotNull(manager,"IE01723: Manager argument can not be null");
Preconditions.checkNotNull(module,"IE01724: Module argument can not be null");
Preconditions.checkNotNull(unrelocatedAddress,"IE01725: Address argument can not be null");
final BreakpointAddress address=new BreakpointAddress(module,unrelocatedAddress);
toggleBreakpoint(manager,address);
}
| Disables or enables a breakpoint at a given address. |
@Override public String toString(){
return getClass().getName() + "[data=" + data+ "]";
}
| Returns a String representation of this RootNotification. |
public static PcRunner serializableInstance(){
return PcRunner.serializableInstance();
}
| Generates a simple exemplar of this class to test serialization. |
@Override public boolean visitTree(VisitContext visitContext,VisitCallback callback){
if (!isVisitable(visitContext)) {
return false;
}
FacesContext facesContext=visitContext.getFacesContext();
boolean visitRows=requiresRowIteration(visitContext);
Integer oldRowKey=null;
if (visitRows) {
oldRowKey=getRowKey();
setRowKey(facesContext,null);
}
pushComponentToEL(facesContext,null);
try {
VisitResult result=visitContext.invokeVisitCallback(this,callback);
if (result == VisitResult.COMPLETE) {
return true;
}
if ((result == VisitResult.ACCEPT)) {
if (visitDataChildren(visitContext,callback,visitRows)) {
return true;
}
}
}
catch ( IOException e) {
LOG.log(Level.SEVERE,e.getMessage(),e);
}
finally {
popComponentFromEL(facesContext);
if (visitRows) {
try {
setRowKey(facesContext,oldRowKey);
restoreOrigValue(facesContext);
}
catch ( Exception e) {
LOG.log(Level.SEVERE,e.getMessage(),e);
}
}
}
return false;
}
| Copied from Richfaces UIDataAdapter#visitTree. |
public TestBase(String name){
testName=name;
}
| Creates a new instance of StreamReader |
private LRAction searchSingleReduction(){
Reduce act=null;
for ( Terminal t : table.getActionTable().getColumns()) {
LRAction act2=table.getActionTable().get(rdState,t);
if (act2 instanceof Reduce) {
if (act == null) act=(Reduce)act2;
else if (((Reduce)act2).getProduction() != act.getProduction()) return null;
}
else if (act2 instanceof Shift) return null;
}
return act;
}
| If in the current state only one single reduction is possible, this function returns it. Otherwise returns null. |
public static String joinSizeTagToKey(String key,String tag){
return new StringBuilder(key).append(SIZE_SP).append(tag).toString();
}
| Join the tag with the key. |
public PriceListProduct(int M_Product_ID,String value,String name,String description,String help,String documentNote,String imageURL,String descriptionURL,BigDecimal price,String uomName,String uomSymbol){
m_Product_ID=M_Product_ID;
m_value=value;
m_name=name;
m_description=description;
m_help=help;
m_documentNote=documentNote;
m_imageURL=imageURL;
m_descriptionURL=descriptionURL;
m_price=price;
m_uomName=uomName;
m_uomSymbol=uomSymbol;
}
| Price List Product. |
private void prepareNativeDaemon(){
mBandwidthControlEnabled=false;
final boolean hasKernelSupport=new File("/proc/net/xt_qtaguid/ctrl").exists();
if (hasKernelSupport) {
Slog.d(TAG,"enabling bandwidth control");
try {
mConnector.execute("bandwidth","enable");
mBandwidthControlEnabled=true;
}
catch ( NativeDaemonConnectorException e) {
Log.wtf(TAG,"problem enabling bandwidth controls",e);
}
}
else {
Slog.d(TAG,"not enabling bandwidth control");
}
SystemProperties.set(PROP_QTAGUID_ENABLED,mBandwidthControlEnabled ? "1" : "0");
synchronized (mQuotaLock) {
int size=mActiveQuotas.size();
if (size > 0) {
Slog.d(TAG,"pushing " + size + " active quota rules");
final HashMap<String,Long> activeQuotas=mActiveQuotas;
mActiveQuotas=Maps.newHashMap();
for ( Map.Entry<String,Long> entry : activeQuotas.entrySet()) {
setInterfaceQuota(entry.getKey(),entry.getValue());
}
}
size=mActiveAlerts.size();
if (size > 0) {
Slog.d(TAG,"pushing " + size + " active alert rules");
final HashMap<String,Long> activeAlerts=mActiveAlerts;
mActiveAlerts=Maps.newHashMap();
for ( Map.Entry<String,Long> entry : activeAlerts.entrySet()) {
setInterfaceAlert(entry.getKey(),entry.getValue());
}
}
size=mUidRejectOnQuota.size();
if (size > 0) {
Slog.d(TAG,"pushing " + size + " active uid rules");
final SparseBooleanArray uidRejectOnQuota=mUidRejectOnQuota;
mUidRejectOnQuota=new SparseBooleanArray();
for (int i=0; i < uidRejectOnQuota.size(); i++) {
setUidNetworkRules(uidRejectOnQuota.keyAt(i),uidRejectOnQuota.valueAt(i));
}
}
}
setFirewallEnabled(mFirewallEnabled || LockdownVpnTracker.isEnabled());
}
| Prepare native daemon once connected, enabling modules and pushing any existing in-memory rules. |
public static final int signedToInt(byte b){
return ((int)b & 0xff);
}
| Converts a byte in the range of -128 to 127 to an int in the range 0 - 255. |
public SamlCodeEvent(Object source,String code){
super(source,code);
}
| Create a new SamlCodeEvent |
public Set<String> addContent(String variable,double value){
if (!paused) {
curState.addToState(new Assignment(variable,value));
return update();
}
else {
log.info("system is paused, ignoring " + variable + "="+ value);
return Collections.emptySet();
}
}
| Adds the content (expressed as a pair of variable=value) to the current dialogue state, and subsequently updates the dialogue state. |
public float interpolate(float x){
final int n=mX.length;
if (Float.isNaN(x)) {
return x;
}
if (x <= mX[0]) {
return mY[0];
}
if (x >= mX[n - 1]) {
return mY[n - 1];
}
int i=0;
while (x >= mX[i + 1]) {
i+=1;
if (x == mX[i]) {
return mY[i];
}
}
float h=mX[i + 1] - mX[i];
float t=(x - mX[i]) / h;
return (mY[i] * (1 + 2 * t) + h * mM[i] * t) * (1 - t) * (1 - t) + (mY[i + 1] * (3 - 2 * t) + h * mM[i + 1] * (t - 1)) * t * t;
}
| Interpolates the value of Y = f(X) for given X. Clamps X to the domain of the spline. |
public static void showToast(Context context,int resourceId){
Toast.makeText(context,context.getString(resourceId),Toast.LENGTH_LONG).show();
}
| Shows a (long) toast. |
private static final PublicKey constructPublicKey(byte[] encodedKey,String encodedKeyAlgorithm) throws InvalidKeyException, NoSuchAlgorithmException {
try {
KeyFactory keyFactory=KeyFactory.getInstance(encodedKeyAlgorithm);
X509EncodedKeySpec keySpec=new X509EncodedKeySpec(encodedKey);
return keyFactory.generatePublic(keySpec);
}
catch ( NoSuchAlgorithmException nsae) {
throw new NoSuchAlgorithmException("No installed providers " + "can create keys for the " + encodedKeyAlgorithm + "algorithm",nsae);
}
catch ( InvalidKeySpecException ike) {
throw new InvalidKeyException("Cannot construct public key",ike);
}
}
| Construct a public key from its encoding. |
public <T>T mapTo(final Class<T> mappingClass,final JBBPMapperCustomFieldProcessor customFieldProcessor,final int flags){
return JBBPMapper.map(this,mappingClass,customFieldProcessor,flags);
}
| Map the structure fields to a class fields. |
public static void unregisterSemanticNodes(){
semanticNodes=new LinkedList();
}
| Deletes the information about semantic nodes used with tool-specific information |
public boolean doWindowDeActivated(){
return true;
}
| Method doWindowDeActivated. |
public TrieIterator(TrieNode node){
super();
m_Root=node;
m_CurrentLeaf=(TrieNode)m_Root.getFirstLeaf();
m_LastLeaf=(TrieNode)m_Root.getLastLeaf();
}
| initializes the iterator |
public static JavacNode injectField(JavacNode typeNode,JCVariableDecl field){
return injectField(typeNode,field,false);
}
| Adds the given new field declaration to the provided type AST Node. Also takes care of updating the JavacAST. |
private static boolean checkAppSignature(String facetId,Context context){
try {
PackageInfo packageInfo=context.getPackageManager().getPackageInfo(context.getPackageName(),PackageManager.GET_SIGNATURES);
for ( Signature sign : packageInfo.signatures) {
byte[] sB=sign.toByteArray();
MessageDigest messageDigest=MessageDigest.getInstance("SHA1");
messageDigest.update(sign.toByteArray());
String currentSignature=Base64.encodeToString(messageDigest.digest(),Base64.DEFAULT);
if (currentSignature.toLowerCase().contains(facetId.split(":")[2].toLowerCase())) {
return true;
}
}
}
catch ( PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
catch ( NoSuchAlgorithmException e) {
e.printStackTrace();
}
return false;
}
| A double check about app signature that was passed by MainActivity as facetID. |
public static RemoveHealthListenerRequest create(int id){
RemoveHealthListenerRequest m=new RemoveHealthListenerRequest();
m.id=id;
return m;
}
| Returns a <code>RemoveHealthListenerRequest</code> to be sent to the specified recipient. |
public void close(){
if (getParentInternalFrame() != null) {
getParentInternalFrame().doDefaultCloseAction();
}
else if (getParentFrame() != null) {
((Window)getParentFrame()).dispatchEvent(new WindowEvent(getParentFrame(),WindowEvent.WINDOW_CLOSING));
}
}
| closes the window, i.e., if the parent is not null and implements the WindowListener interface it calls the windowClosing method |
public static SRegResponse createSRegResponse(SRegRequest req,Map userData) throws MessageException {
SRegResponse resp=new SRegResponse();
List attributes=req.getAttributes();
Iterator iter=attributes.iterator();
while (iter.hasNext()) {
String attr=(String)iter.next();
String value=(String)userData.get(attr);
if (value != null) resp.addAttribute(attr,value);
}
return resp;
}
| Creates a SRegResponse from a SRegRequest message and the data released by the user. |
@Override public int size(){
final Segment<V>[] segments=this.segments;
long sum=0;
long check=0;
int[] mc=new int[segments.length];
for (int k=0; k < RETRIES_BEFORE_LOCK; ++k) {
check=0;
sum=0;
int mcsum=0;
for (int i=0; i < segments.length; ++i) {
sum+=segments[i].count;
mcsum+=mc[i]=segments[i].modCount;
}
if (mcsum != 0) {
for (int i=0; i < segments.length; ++i) {
check+=segments[i].count;
if (mc[i] != segments[i].modCount) {
check=-1;
break;
}
}
}
if (check == sum) break;
}
if (check != sum) {
sum=0;
for (int i=0; i < segments.length; ++i) segments[i].lock();
for (int i=0; i < segments.length; ++i) sum+=segments[i].count;
for (int i=0; i < segments.length; ++i) segments[i].unlock();
}
if (sum > Integer.MAX_VALUE) return Integer.MAX_VALUE;
return (int)sum;
}
| Returns the number of key-value mappings in this map. If the map contains more than <tt>Integer.MAX_VALUE</tt> elements, returns <tt>Integer.MAX_VALUE</tt>. |
public void testParallelExhausted() throws Exception {
String algLines[]={"# ----- properties ","content.source=org.apache.lucene.benchmark.byTask.feeds.LineDocSource","docs.file=" + getReuters20LinesFile(),"content.source.log.step=3","doc.term.vector=false","content.source.forever=false","directory=RAMDirectory","doc.stored=false","doc.tokenized=false","task.max.depth.log=1","# ----- alg ","CreateIndex","{ [ AddDoc]: 4} : * ","ResetInputs ","{ [ AddDoc]: 4} : * ","CloseIndex"};
Benchmark benchmark=execBenchmark(algLines);
IndexReader ir=DirectoryReader.open(benchmark.getRunData().getDirectory());
int ndocsExpected=2 * 20;
assertEquals("wrong number of docs in the index!",ndocsExpected,ir.numDocs());
ir.close();
}
| Test that " {[AddDoc(4000)]: 4} : * " works corrcetly (for LUCENE-941) |
protected void verifyMatch(Object target,Object deserialized){
CronExpression targetCronExpression=(CronExpression)target;
CronExpression deserializedCronExpression=(CronExpression)deserialized;
assertNotNull(deserializedCronExpression);
assertEquals(targetCronExpression.getCronExpression(),deserializedCronExpression.getCronExpression());
assertEquals(targetCronExpression.getTimeZone(),deserializedCronExpression.getTimeZone());
}
| Verify that the target object and the object we just deserialized match. |
public static boolean ISK(int x){
return 0 != ((x) & BITRK);
}
| test whether value is a constant |
public boolean isDependentEntities(){
Object oo=get_Value(COLUMNNAME_IsDependentEntities);
if (oo != null) {
if (oo instanceof Boolean) return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
| Get Dependent Entities. |
private void removeWaiter(WaitNode node){
if (node != null) {
node.thread=null;
retry: for (; ; ) {
for (WaitNode pred=null, q=waiters, s; q != null; q=s) {
s=q.next;
if (q.thread != null) pred=q;
else if (pred != null) {
pred.next=s;
if (pred.thread == null) continue retry;
}
else if (!UNSAFE.compareAndSwapObject(this,waitersOffset,q,s)) continue retry;
}
break;
}
}
}
| Tries to unlink a timed-out or interrupted wait node to avoid accumulating garbage. Internal nodes are simply unspliced without CAS since it is harmless if they are traversed anyway by releasers. To avoid effects of unsplicing from already removed nodes, the list is retraversed in case of an apparent race. This is slow when there are a lot of nodes, but we don't expect lists to be long enough to outweigh higher-overhead schemes. |
@DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 12:27:51.378 -0500",hash_original_method="212FDF834FF8F6725237F29A41B6704B",hash_generated_method="46C0413BA03B9DE945DBF06FA8B5E0CE") public static String convertPreDial(String phoneNumber){
if (phoneNumber == null) {
return null;
}
int len=phoneNumber.length();
StringBuilder ret=new StringBuilder(len);
for (int i=0; i < len; i++) {
char c=phoneNumber.charAt(i);
if (isPause(c)) {
c=PAUSE;
}
else if (isToneWait(c)) {
c=WAIT;
}
ret.append(c);
}
return ret.toString();
}
| Converts pause and tonewait pause characters to Android representation. RFC 3601 says pause is 'p' and tonewait is 'w'. |
@Override public boolean execute(String sql,String[] columnNames) throws SQLException {
try {
if (isDebugEnabled()) {
debugCode("execute(" + quote(sql) + ", "+ quoteArray(columnNames)+ ");");
}
throw DbException.get(ErrorCode.METHOD_NOT_ALLOWED_FOR_PREPARED_STATEMENT);
}
catch ( Exception e) {
throw logAndConvert(e);
}
}
| Calling this method is not legal on a PreparedStatement. |
@Override public void increment(double coord,float value){
if (cachefill >= 0) {
if (cachefill < cachec.length) {
cachec[cachefill]=coord;
cachev[cachefill]=value;
cachefill++;
return;
}
else {
materialize();
}
}
testResample(coord);
super.increment(coord,value);
}
| Put fresh data into the histogram (or into the cache) |
public WPAttributeDialog(int M_AttributeSetInstance_ID,int M_Product_ID,int C_BPartner_ID,boolean productWindow,int AD_Column_ID,int WindowNo){
super();
this.setTitle(Msg.translate(Env.getCtx(),"M_AttributeSetInstance_ID"));
this.setAttribute("modal",Boolean.TRUE);
this.setBorder("normal");
this.setWidth("500px");
this.setHeight("600px");
this.setSizable(true);
log.config("M_AttributeSetInstance_ID=" + M_AttributeSetInstance_ID + ", M_Product_ID="+ M_Product_ID+ ", C_BPartner_ID="+ C_BPartner_ID+ ", ProductW="+ productWindow+ ", Column="+ AD_Column_ID);
m_WindowNo=SessionManager.getAppDesktop().registerWindow(this);
m_M_AttributeSetInstance_ID=M_AttributeSetInstance_ID;
m_M_Product_ID=M_Product_ID;
m_C_BPartner_ID=C_BPartner_ID;
m_productWindow=productWindow;
m_AD_Column_ID=AD_Column_ID;
m_WindowNoParent=WindowNo;
m_columnName=MColumn.getColumnName(Env.getCtx(),AD_Column_ID);
if (m_columnName == null || m_columnName.trim().length() == 0) {
m_columnName="M_AttributeSetInstance_ID";
}
try {
init();
}
catch ( Exception ex) {
log.log(Level.SEVERE,"VPAttributeDialog" + ex);
}
if (!initAttributes()) {
dispose();
return;
}
AEnv.showCenterScreen(this);
}
| Product Attribute Instance Dialog |
public Vector multiply(double n){
return new Vector(this.x * n,this.y * n,this.z * n);
}
| Perform scalar multiplication and return a new vector. |
public static String date2String_yyyy_MM_dd_HH_mm_ss(Date date){
return getSimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
}
| format date to yyyy-MM-dd HH:mm:ss string |
public void init(java.net.URL url){
init(null,url);
}
| Initialize the LayerHandler by having it construct it's layers from a URL containing an openmap.properties file. |
@Override public boolean isValidCombination(int weeklyMinutes,DatePattern datePattern,TimePattern timePattern){
if (timePattern.getType() != null && timePattern.getType() == TimePattern.sTypeExactTime) return true;
if (datePattern == null) return false;
if (datePattern.getType() != null && datePattern.getType() == DatePattern.sTypePatternSet) {
for ( DatePattern child : datePattern.findChildren()) if (isValidCombination(weeklyMinutes,child,timePattern)) return true;
return false;
}
else {
return weeklyMinutes == datePattern.getEffectiveNumberOfWeeks() * timePattern.getNrMeetings() * timePattern.getMinPerMtg() / getSemesterWeeks(datePattern);
}
}
| A combination is valid when the number of semester minutes matches the number of meetings times number of minutes per week of the time pattern, multiplied by the number of weeks of the date pattern.<br> <code>weekly minutes == number of meetings x number of minutes per meeting x number of weeks / semester weeks</code><br> Semester weeks are provided with the given parameter or (if not set) taken from the default date pattern. |
private void calcNextPos(int dx,int minX,int maxX,int dy,int minY,int maxY){
if (dx != 0) {
leadColumn+=dx;
if (leadColumn > maxX) {
leadColumn=minX;
leadRow++;
if (leadRow > maxY) {
leadRow=minY;
}
}
else if (leadColumn < minX) {
leadColumn=maxX;
leadRow--;
if (leadRow < minY) {
leadRow=maxY;
}
}
}
else {
leadRow+=dy;
if (leadRow > maxY) {
leadRow=minY;
leadColumn++;
if (leadColumn > maxX) {
leadColumn=minX;
}
}
else if (leadRow < minY) {
leadRow=maxY;
leadColumn--;
if (leadColumn < minX) {
leadColumn=maxX;
}
}
}
}
| Find the next lead row and column based on the given dx/dy and max/min values. |
@Override public void exportGroupDelete(URI export,String opId) throws ControllerException {
ExportTaskCompleter taskCompleter=new ExportDeleteCompleter(export,false,opId);
Workflow workflow=null;
try {
ExportGroup exportGroup=_dbClient.queryObject(ExportGroup.class,export);
if (exportGroup != null && exportGroup.getExportMasks() != null) {
workflow=_wfUtils.newWorkflow("exportGroupDelete",false,opId);
Set<URI> storageSystemURIs=new HashSet<URI>();
List<ExportMask> tempExportMasks=ExportMaskUtils.getExportMasks(_dbClient,exportGroup);
for ( ExportMask tempExportMask : tempExportMasks) {
List<String> lockKeys=ControllerLockingUtil.getHostStorageLockKeys(_dbClient,ExportGroup.ExportGroupType.valueOf(exportGroup.getType()),StringSetUtil.stringSetToUriList(exportGroup.getInitiators()),tempExportMask.getStorageDevice());
boolean acquiredLocks=_wfUtils.getWorkflowService().acquireWorkflowLocks(workflow,lockKeys,LockTimeoutValue.get(LockType.EXPORT_GROUP_OPS));
if (!acquiredLocks) {
throw DeviceControllerException.exceptions.failedToAcquireLock(lockKeys.toString(),"ExportGroupDelete: " + exportGroup.getLabel());
}
if (tempExportMask != null && tempExportMask.getVolumes() != null) {
List<URI> uriList=getExportRemovableObjects(exportGroup,tempExportMask);
Map<URI,List<URI>> storageToVolumes=getStorageToVolumes(uriList);
for ( URI storageURI : storageToVolumes.keySet()) {
if (!storageSystemURIs.contains(storageURI)) {
storageSystemURIs.add(storageURI);
_wfUtils.generateExportGroupDeleteWorkflow(workflow,null,null,storageURI,export);
}
}
}
else {
exportGroup.removeExportMask(tempExportMask.getId());
_dbClient.persistObject(exportGroup);
}
}
workflow.executePlan(taskCompleter,"Removed export from all devices.");
}
else {
taskCompleter.ready(_dbClient);
}
}
catch ( Exception ex) {
String message="exportGroupDelete caught an exception.";
_log.error(message,ex);
if (workflow != null) {
_wfUtils.getWorkflowService().releaseAllWorkflowLocks(workflow);
}
ServiceError serviceError=DeviceControllerException.errors.jobFailed(ex);
taskCompleter.error(_dbClient,serviceError);
}
}
| Delete the export. |
public NoInitialContextException(String explanation){
super(explanation);
}
| Constructs an instance of NoInitialContextException with an explanation. All other fields are initialized to null. |
protected void animateToNearestState(){
final PanelState nearestState=findNearestPanelStateFromHeight(getHeight());
final float displacement=getPanelHeightFromState(nearestState) - getHeight();
final long duration=calculateAnimationDuration(INITIAL_ANIMATION_VELOCITY_DP_PER_SECOND,displacement);
animatePanelToState(nearestState,StateChangeReason.SWIPE,duration);
}
| Animates the Panel to its nearest state. |
synchronized void checkThreshold(){
Ratio successRatio=circuit.getSuccessThreshold();
Ratio failureRatio=circuit.getFailureThreshold();
if (successRatio != null) {
if (bitSet.occupiedBits() == successRatio.denominator || (successRatio.ratio == 1.0 && bitSet.positiveRatio() < 1.0)) if (bitSet.positiveRatio() >= successRatio.ratio) circuit.close();
else circuit.open();
}
else if (failureRatio != null) {
if (bitSet.occupiedBits() == failureRatio.denominator || (failureRatio.ratio == 1.0 && bitSet.negativeRatio() < 1.0)) if (bitSet.negativeRatio() >= failureRatio.ratio) circuit.open();
else circuit.close();
}
else {
if (bitSet.positiveRatio() == 1) circuit.close();
else circuit.open();
}
}
| Checks to determine if a threshold has been met and the circuit should be opened or closed. <p> If a success ratio is configured, the circuit is opened or closed after the expected number of executions based on whether the ratio was exceeded. <p> Else if a failure ratio is configured, the circuit is opened or closed after the expected number of executions based on whether the ratio was not exceeded. <p> Else when no thresholds are configured, the circuit opens or closes on a single failure or success. |
public synchronized void channelDone(int channel){
if (!chBusy[channel]) throw new IllegalStateException("channel " + channel + " is not busy");
chBusy[channel]=false;
gate.release();
}
| Signal that the channel is done processing the splitter supplied tuple. |
protected void sequence_SimpleQuantifier(ISerializationContext context,SimpleQuantifier semanticObject){
genericSequencer.createSequence(context,semanticObject);
}
| Contexts: Quantifier returns SimpleQuantifier SimpleQuantifier returns SimpleQuantifier Constraint: ((quantifier='+' | quantifier='*' | quantifier='?') nonGreedy?='?'?) |
public void testBaselineParameters() throws Exception {
SweetSpotSimilarity sim=getSimilarity("text_baseline",SweetSpotSimilarity.class);
ClassicSimilarity d=new ClassicSimilarity();
for (int i=1; i <= 6; i++) {
assertEquals("tf i=" + i,1.5F,sim.tf(i),0.0F);
}
for (int i=6; i <= 1000; i++) {
assertTrue("tf: i=" + i + " : s="+ sim.tf(i)+ " < d="+ d.tf(i),sim.tf(i) < d.tf(i));
}
assertEquals("norm 1 == 7",sim.computeLengthNorm(1),sim.computeLengthNorm(7),0.0F);
assertEquals("norm 2 == 6",sim.computeLengthNorm(1),sim.computeLengthNorm(7),0.0F);
assertEquals("norm 3",1.00F,sim.computeLengthNorm(3),0.0F);
assertEquals("norm 4",1.00F,sim.computeLengthNorm(4),0.0F);
assertEquals("norm 5",1.00F,sim.computeLengthNorm(5),0.0F);
assertTrue("norm 6 too high: " + sim.computeLengthNorm(6),sim.computeLengthNorm(6) < 1.0F);
assertTrue("norm 7 higher then norm 6",sim.computeLengthNorm(7) < sim.computeLengthNorm(6));
assertEquals("norm 20",0.25F,sim.computeLengthNorm(20),0.0F);
}
| baseline with parameters |
private void dumpComplexTypeAttribute(XSComplexType type){
Iterator itr;
itr=type.iterateAttGroups();
while (itr.hasNext()) {
dumpRef((XSAttGroupDecl)itr.next());
}
itr=type.iterateDeclaredAttributeUses();
while (itr.hasNext()) {
attributeUse((XSAttributeUse)itr.next());
}
}
| Creates node for complex type. |
public static double computePerspectiveNearDistance(Angle fieldOfView,double distanceToObject){
if (fieldOfView == null) {
String msg=Logging.getMessage("nullValue.FOVIsNull");
Logging.logger().severe(msg);
throw new IllegalArgumentException(msg);
}
if (distanceToObject < 0) {
String msg=Logging.getMessage("generic.DistanceLessThanZero");
Logging.logger().severe(msg);
throw new IllegalArgumentException(msg);
}
double tanHalfFov=fieldOfView.tanHalfAngle();
return distanceToObject / (2 * Math.sqrt(2 * tanHalfFov * tanHalfFov + 1));
}
| Computes the maximum near clip distance for a perspective projection that avoids clipping an object at a given distance from the eye point. The given distance should specify the smallest distance between the eye and the object being viewed, but may be an approximation if an exact clip distance is not required. |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.