code
stringlengths 10
174k
| nl
stringlengths 3
129k
|
|---|---|
public static void notify(final String title,final String text,final NotifierTheme theme){
notify(null,title,text,theme);
}
|
Starts a notification. A window will appear in the bottom of the screen, then will disappear after 4.5 s
|
public String evalString(INode state){
EightPuzzleNode node=(EightPuzzleNode)state;
int misplaced=0;
for (int r=0; r <= EightPuzzleNode.MaxR; r++) {
for (int c=0; c <= EightPuzzleNode.MaxC; c++) {
if (node.isEmpty(r,c)) {
continue;
}
if (node.cell(r,c) != goal.cell(r,c)) {
misplaced++;
}
}
}
DepthTransition t=(DepthTransition)state.storedData();
if (t == null) return "" + misplaced;
String eval="";
if (t.depth > 0) {
eval=eval + t.depth + "+"+ misplaced+ "="+ (t.depth + misplaced);
}
else {
eval=eval + misplaced;
}
return eval;
}
|
Return string representing the evaluation gn) + W(n) where g(n) is length of the path from initial to node n, and W(n) counts number of misplaced tiles in the state description
|
@Override public InputStream resourceStream() throws IOException {
return new FileInputStream(new File(filePath));
}
|
Files on the local file system are easily accessed as InputStreams.
|
@DSSafe(DSCat.SAFE_LIST) @DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2014-09-03 14:59:51.206 -0400",hash_original_method="30C6AD04EA1FBD0DAE5C136947812A29",hash_generated_method="1EDB856DC010FCC78F29D6381EEACFB1") public static boolean isFileOlder(File file,Date date){
if (date == null) {
throw new IllegalArgumentException("No specified date");
}
return isFileOlder(file,date.getTime());
}
|
Tests if the specified <code>File</code> is older than the specified <code>Date</code>.
|
@Override public void stop(){
if (m_Executor != null) {
debug("pre: shutdownNow");
m_Executor.shutdownNow();
debug("post: shutdownNow");
}
super.stop();
}
|
Stops the evaluation, if possible.
|
public synchronized void registerExtractor() throws ReplicatorException {
String command=vmrrControlScript + " command PROCESS DISCONNECTED_APPLY REGISTER " + this.replicateApplyName;
logger.info("Registering with mine process: " + command);
execAndReturnStdout(command,false);
}
|
Ask mine to register our extractor, so it can then set last obsolete plog. We call this on every start of extractor, as it is harmless to do it repeatedly.
|
@DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2014-09-03 14:59:48.439 -0400",hash_original_method="AA7B08876B9A676C82049B1527C60A7E",hash_generated_method="164655E4934D4D0FC15D1158974949D7") public String soundex(String str){
if (str == null) {
return null;
}
str=SoundexUtils.clean(str);
if (str.length() == 0) {
return str;
}
StringBuffer sBuf=new StringBuffer();
sBuf.append(str.charAt(0));
char last, current;
last='*';
for (int i=0; i < str.length(); i++) {
current=getMappingCode(str.charAt(i));
if (current == last) {
continue;
}
else if (current != 0) {
sBuf.append(current);
}
last=current;
}
return sBuf.toString();
}
|
Retreives the Refined Soundex code for a given String object.
|
private boolean[] calcRelevantVars(int nodeIndex){
boolean[] relevantVars=new boolean[evidence.getNumNodes()];
for (int i=0; i < relevantVars.length; i++) {
relevantVars[i]=false;
}
Node node=bayesIm.getNode(nodeIndex);
List<Node> variablesInEvidence=evidence.getVariablesInEvidence();
List<Node> nodesInEvidence=new LinkedList<>();
for ( Node _node : variablesInEvidence) {
nodesInEvidence.add(bayesIm.getBayesPm().getNode(_node.getName()));
}
List<Node> conditionedNodes=new LinkedList<>(nodesInEvidence);
conditionedNodes.addAll(bayesIm.getDag().getParents(node));
for (int i=0; i < bayesIm.getNumNodes(); i++) {
Node node2=bayesIm.getNode(i);
if (node == node2 || bayesIm.getDag().isDConnectedTo(node,node2,conditionedNodes)) {
relevantVars[i]=true;
}
}
return relevantVars;
}
|
Calculates the set of descendants of the given node that are d-connected to the node given its parents and all evidence variables.
|
public LinkedList(Collection c){
this();
addAll(c);
}
|
Constructs a list containing the elements of the specified collection, in the order they are returned by the collection's iterator.
|
private void removeRetainMessage(List<String> topicLevels,int retainId){
long b=this.list().lrem(RedisKey.topicRetainList(topicLevels),1,String.valueOf(retainId));
if (b == 1) {
List<String> keys=new ArrayList<>();
List<String> argv=new ArrayList<>();
for (int i=0; i < topicLevels.size(); i++) {
keys.add(RedisKey.topicRetainChild(topicLevels.subList(0,i)));
argv.add(topicLevels.get(i));
}
this.script().eval("local length = table.getn(KEYS)\n" + "for i = 1, length do\n" + " local count = redis.call('HINCRBY', KEYS[i], ARGV[i], -1)\n"+ " if count == 0\n"+ " then\n"+ " redis.call('HDEL', KEYS[i], ARGV[i])\n"+ " end\n"+ "end\n"+ "return redis.status_reply('OK')",ScriptOutputType.STATUS,keys.toArray(new String[keys.size()]),argv.toArray(new String[argv.size()]));
}
this.key().del(RedisKey.topicRemainMessage(topicLevels,retainId));
}
|
Remove the specific retain message
|
public void append(final CharBuffer cb){
if (cb == null) {
return;
}
provideCapacity(length + cb.length);
System.arraycopy(cb.c,0,c,length,cb.length);
length+=cb.length;
}
|
Appends the contents of <code>cb</code> to the end of this CharBuffer.
|
public static List propertyDescriptors(int apiLevel){
return PROPERTY_DESCRIPTORS;
}
|
Returns a list of structural property descriptors for this node type. Clients must not modify the result.
|
public void enumConstValue(int typeNameIndex,int constNameIndex) throws IOException {
output.write('e');
write16bit(typeNameIndex);
write16bit(constNameIndex);
}
|
Writes <code>tag</code> and <code>enum_const_value</code> in <code>element_value</code>.
|
public BDS(int featureCount,Classifier evaluator,int folds){
setFeatureCount(featureCount);
setFolds(folds);
setEvaluator(evaluator);
}
|
Creates a BDS feature selection for a classification problem
|
public double relativeDL(int index,double expFPRate,boolean checkErr){
return (minDataDLIfExists(index,expFPRate,checkErr) + theoryDL(index) - minDataDLIfDeleted(index,expFPRate,checkErr));
}
|
The description length (DL) of the ruleset relative to if the rule in the given position is deleted, which is obtained by: <br> MDL if the rule exists - MDL if the rule does not exist <br> Note the minimal possible DL of the ruleset is calculated(i.e. some other rules may also be deleted) instead of the DL of the current ruleset. <p>
|
public boolean match(Event matchTarget){
if (matchTarget.eventType == null && this.eventType != null) return false;
else if (matchTarget.eventType != null && this.eventType == null) return false;
else if (this.eventType == null && matchTarget.eventType == null) return false;
else if (getEventId() == null && matchTarget.getEventId() != null) return false;
else if (getEventId() != null && matchTarget.getEventId() == null) return false;
return matchTarget.eventType.equalsIgnoreCase(this.eventType) && ((this.getEventId() == matchTarget.getEventId()) || this.getEventId().equalsIgnoreCase(matchTarget.getEventId()));
}
|
Return true if the given event header matches the supplied one.
|
@AfterClass public static void tearDownClass() throws Exception {
}
|
Cleanup after testing.
|
public void updateDurableTimeout(int newValue){
DurableClientAttributes dca=getDurableAttributes();
if (dca != null) {
dca.updateTimeout(newValue);
}
}
|
Used to update the timeout when a durable client comes back to a server
|
@Override public TreeNode processMerge(TreeNode node){
DefaultMutableTreeNode masterNode=(DefaultMutableTreeNode)node;
if (masterNode.equals(slaveTopNode)) {
return masterNode;
}
if (slaveTopNode.getChildCount() == 0) {
return masterNode;
}
mergeNodes(masterNode,slaveTopNode);
return masterNode;
}
|
Processes unite-append merge
|
private void writeLegsDistributionWRTSelectedPlan(final String plansFile,final String outputFile){
SortedMap<Id<Person>,List<String>> personId2legs=getLegsForAllPlansInChoiceSet(plansFile);
SortedMap<Double,Double> selectedCar2OtherLegs=new TreeMap<>();
SortedMap<Double,Double> selectedPt2OtherLegs=new TreeMap<>();
double[] intervals={0.0,.20,.40,.60,.80,.90,1.00};
for ( double d : intervals) {
selectedCar2OtherLegs.put(d,0.);
selectedPt2OtherLegs.put(d,0.);
}
for ( Id<Person> pId : personId2legs.keySet()) {
List<String> legs=personId2legs.get(pId);
double carCounter=0;
if (legs.get(0).equals("car")) {
for (int i=1; i < legs.size(); i++) {
if (legs.get(i).equals("car")) carCounter++;
}
double carShare=carCounter / (legs.size() - 1);
double interval=0;
for (int i=0; i < intervals.length - 1; i++) {
if (carShare > intervals[i] && carShare <= intervals[i + 1]) interval=intervals[i + 1];
}
selectedCar2OtherLegs.put(interval,selectedCar2OtherLegs.get(interval) + 1);
}
else if (legs.get(0).equals("pt")) {
for (int i=1; i < legs.size(); i++) {
if (legs.get(i).equals("car")) carCounter++;
}
double carShare=carCounter / (legs.size() - 1);
double interval=0;
for (int i=0; i < intervals.length - 1; i++) {
if (carShare > intervals[i] && carShare <= intervals[i + 1]) interval=intervals[i + 1];
}
selectedPt2OtherLegs.put(interval,selectedPt2OtherLegs.get(interval) + 1);
}
}
BufferedWriter writer=IOUtils.getBufferedWriter(outputFile);
try {
writer.write(" interval \t carCounts \t ptCounts \n");
for ( Double d : selectedCar2OtherLegs.keySet()) {
writer.write(d + "\t" + selectedCar2OtherLegs.get(d)+ "\t"+ selectedPt2OtherLegs.get(d)+ "\n");
}
writer.close();
}
catch ( Exception e) {
throw new RuntimeException("Data is not written in File. Reason " + e);
}
log.info("Data has written to " + outputFile);
}
|
for each (car/pt) leg in selected plan, it counts number of cars in remaining plans in choice set of each person and then write the distribution for predefined intervals. For e.g. ==0.2 37.0 153.0== indicates that 37 persons have more than 0% and less than or equal to 20% cars in their choice set and car is leg in selected plan and similarly 153 persons have more than 0% and less than or equal to 20% cars in their choice set and pt is leg in selected plan.
|
public static String xmlAttr(String name,String value){
return " " + name + "=\""+ xmlText(value)+ "\"";
}
|
Creates an XML attribute of the form name="value". A single space is prepended to the name, so that multiple attributes can be concatenated.
|
@Override public CharSequence convertToString(Cursor cursor){
if (cursor == null) {
return null;
}
String query=getColumnString(cursor,SearchManager.SUGGEST_COLUMN_QUERY);
if (query != null) {
return query;
}
return null;
}
|
Gets the text to show in the query field when a suggestion is selected.
|
public int length(){
return bytes.length;
}
|
Gets the amount of data stored in this object.
|
protected void updateTimerButton(){
if (timerButton != null) {
timerButton.setEnabled(timer != null);
timerButton.setSelected(timer != null && timer.isRunning());
}
}
|
Enable the timer button if there is a timer, check it on if the timer is running.
|
public static Coordinate minCoordinate(Coordinate[] coordinates){
Coordinate minCoord=null;
for (int i=0; i < coordinates.length; i++) {
if (minCoord == null || minCoord.compareTo(coordinates[i]) > 0) {
minCoord=coordinates[i];
}
}
return minCoord;
}
|
Returns the minimum coordinate, using the usual lexicographic comparison.
|
public Index refreshSeconds(Number refreshSeconds){
this.refreshSeconds=refreshSeconds;
return this;
}
|
Sets the index searcher refresh period.
|
protected boolean beforeDelete(){
for ( MMigrationData data : m_migrationData) {
data.deleteEx(true);
}
return true;
}
|
Before Delete
|
public Block deepCopy(){
Block copy=new Block.Builder(this).build();
if (mNextConnection != null) {
copyConnection(mNextConnection,copy.mNextConnection);
}
for (int i=0; i < mInputList.size(); i++) {
Input sourceInput=mInputList.get(i);
if (sourceInput.getConnection() == null) {
continue;
}
Input destInput=copy.getInputByName(sourceInput.getName());
copyConnection(sourceInput.getConnection(),destInput.getConnection());
}
return copy;
}
|
Creates a copy of this block and all inferior blocks connected to it.
|
public boolean isDeclared(AttributeKey<?> key){
return attributes.containsKey(key.getId());
}
|
Returns true if the attributes contain the given attribute key, based on its ID.
|
public static int hashArrayInsert(final long[] srcArr,final long[] hashTable,final int lgArrLongs,final long thetaLong){
int count=0;
final int arrLen=srcArr.length;
checkThetaCorruption(thetaLong);
for (int i=0; i < arrLen; i++) {
final long hash=srcArr[i];
checkHashCorruption(hash);
if (continueCondition(thetaLong,hash)) {
continue;
}
if (hashSearchOrInsert(hashTable,lgArrLongs,hash) < 0) {
count++;
}
}
return count;
}
|
Inserts the given long array into the given hash table array of the target size, removes any negative input values, ignores duplicates and counts the values inserted. The given hash table may have values, but they must have been inserted by this method or one of the other OADH insert methods in this class and they may not be dirty. This method performs additional checks against potentially invalid hash values or theta values.
|
public ObjectMapper nextLevel(ObjectMapper level){
ObjectMapper previous=levelStack.peek();
levelStack.push(level);
return previous;
}
|
Sets the new current nested level and pushes old current nested level down the stack returns that level.
|
public AnvilCommands(WorldEdit worldEdit){
checkNotNull(worldEdit);
this.worldEdit=worldEdit;
}
|
Create a new instance.
|
public CActionExpandNode(final CGroupNode node){
super("Expand Group");
m_node=node;
}
|
Creates a new action object.
|
public LinkedList(){
header.next=header.previous=header;
}
|
Constructs an empty list.
|
public boolean isProcessing(){
Object oo=get_Value(COLUMNNAME_Processing);
if (oo != null) {
if (oo instanceof Boolean) return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
|
Get Process Now.
|
public String missingModeTipText(){
return "Determines how missing attribute values are treated.";
}
|
Returns the tip text for this property
|
public void prepareSession(MediaInput player,String remoteAddress,int remotePort,RtpStreamListener rtpStreamListener) throws RtpException {
try {
inputStream=new VideoCaptureStream(format,player);
inputStream.open();
outputStream=new RtpOutputStream(remoteAddress,remotePort,localRtpPort,RtpOutputStream.RTCP_SOCKET_TIMEOUT);
outputStream.addRtpStreamListener(rtpStreamListener);
outputStream.open();
Codec[] codecChain=MediaRegistry.generateEncodingCodecChain(format.getCodec());
processor=new Processor(inputStream,outputStream,codecChain);
}
catch ( Exception e) {
throw new RtpException("Can't prepare resources");
}
}
|
Prepare the RTP session
|
public void reset(){
intAtt=0;
integerAtt=0;
boolAtt=false;
booleanAtt=Boolean.FALSE;
stringAtt=null;
dateAtt=null;
objectNameAtt=null;
}
|
Reset all attributes
|
protected void finishInit(){
}
|
finishes the initialization, by setting size/location.
|
private XmlEntityBuilder(){
xmlEntity=new XmlEntity();
}
|
Private contstructor.
|
@Override public boolean postTurnSummary(final String summary,final String subject){
try {
login();
final String s_forumId="20";
final String url=WAR_CLUB_FORUM_URL + "/reply.php?forum=" + s_forumId+ "&topic_id="+ m_topicId;
GetMethod get=new GetMethod(url);
String XOOPS_TOKEN_REQUEST;
try {
final int status=m_client.executeMethod(m_hostConfiguration,get,m_httpState);
if (status != 200) {
throw new Exception("Could not load reply page: " + url + ". Site returned "+ status);
}
final String body=get.getResponseBodyAsString();
final Matcher m=s_XOOPS_TOKEN_REQUEST.matcher(body);
if (!m.matches()) {
throw new Exception("Unable to find 'XOOPS_TOKEN_REQUEST' form field on reply page");
}
XOOPS_TOKEN_REQUEST=m.group(1);
}
finally {
get.releaseConnection();
}
final List<Part> parts=new ArrayList<>();
parts.add(createStringPart("subject",subject));
parts.add(createStringPart("message",summary));
parts.add(createStringPart("forum",s_forumId));
parts.add(createStringPart("topic_id",m_topicId));
parts.add(createStringPart("XOOPS_TOKEN_REQUEST",XOOPS_TOKEN_REQUEST));
parts.add(createStringPart("xoops_upload_file[]","userfile"));
parts.add(createStringPart("contents_submit","Submit"));
parts.add(createStringPart("doxcode","1"));
parts.add(createStringPart("dosmiley","1"));
parts.add(createStringPart("dohtml","1"));
parts.add(createStringPart("dobr","1"));
parts.add(createStringPart("editor","dhtmltextarea"));
if (m_includeSaveGame && m_saveGameFile != null) {
final FilePart part=new FilePart("userfile",m_saveGameFileName,m_saveGameFile);
part.setContentType("application/octet-stream");
part.setTransferEncoding(null);
part.setCharSet(null);
parts.add(part);
}
final MultipartRequestEntity entity=new MultipartRequestEntity(parts.toArray(new Part[parts.size()]),new HttpMethodParams());
final PostMethod post=new PostMethod(WAR_CLUB_FORUM_URL + "/post.php");
post.setRequestEntity(entity);
try {
final int status=m_client.executeMethod(m_hostConfiguration,post,m_httpState);
if (status != 200) {
throw new Exception("Posting summary failed, the server returned status: " + status);
}
final String body=post.getResponseBodyAsString();
if (!body.toLowerCase().contains("thanks for your submission!")) {
throw new Exception("Posting summary failed, the server didn't respond with thank you message");
}
m_turnSummaryRef="www.tripleawarclub.org/modules/newbb/viewtopic.php?topic_id=" + m_topicId + "&forum="+ s_forumId;
get=new GetMethod("http://www.tripleawarclub.org/user.php?op=logout");
try {
m_client.executeMethod(m_hostConfiguration,get,m_httpState);
}
finally {
get.releaseConnection();
}
}
finally {
post.releaseConnection();
}
}
catch ( final Exception e) {
m_turnSummaryRef=e.getMessage();
ClientLogger.logQuietly(e);
return false;
}
return true;
}
|
Post the turn summary and save game to the forum After login we must load the post page to get the XOOPS_TOKEN_REQUEST (which I think is CSRF nounce) then we can post the reply
|
public IntArray grow(IntArray array,long minSize){
if (minSize <= array.size()) {
return array;
}
final long newSize=overSize(minSize,INT_PAGE_SIZE,RamUsageEstimator.NUM_BYTES_INT);
return resize(array,newSize);
}
|
Grow an array to a size that is larger than <code>minSize</code>, preserving content, and potentially reusing part of the provided array.
|
@Override protected void cleanup(){
die();
this.activeAudioFactory=null;
super.cleanup();
}
|
Shuts this thread down and clears references to created objects
|
private void saveState(){
SharedPreferences prefs=mApplicationContext.getSharedPreferences(PREF_PACKAGE,Context.MODE_PRIVATE);
SharedPreferences.Editor editor=prefs.edit();
editor.putBoolean(PREF_SEND_INSTALL_EVENT,mSendInstallEvent);
setIsFreshInstallOrDataHasBeenCleared(mApplicationContext);
editor.putLong(PREF_TIMESTAMP_OF_INSTALL,mTimestampOfInstall);
editor.putLong(PREF_TIMESTAMP_FOR_NEXT_POST_ATTEMPT,mTimestampForNextPostAttempt);
editor.putLong(PREF_TIMESTAMP_FOR_NEW_REQUEST,mTimestampForNewRequest);
editor.putLong(PREF_TIMESTAMP_OF_REQUEST,hasRequest() ? mCurrentRequest.getCreationTimestamp() : INVALID_TIMESTAMP);
editor.putString(PREF_PERSISTED_REQUEST_ID,hasRequest() ? mCurrentRequest.getRequestID() : INVALID_REQUEST_ID);
editor.putString(PREF_LATEST_VERSION,mLatestVersion == null ? "" : mLatestVersion);
editor.putString(PREF_MARKET_URL,mMarketURL == null ? "" : mMarketURL);
if (mInstallSource != null) editor.putString(PREF_INSTALL_SOURCE,mInstallSource);
editor.apply();
}
|
Writes out the current state to a file.
|
@Override public <R>Eval<R> collect(final Supplier<R> supplier,final BiConsumer<R,? super T> accumulator,final BiConsumer<R,R> combiner){
return Eval.later(null);
}
|
Asynchronously perform a Stream collection
|
public Bag extractMin(Bag putInHere){
Comparable min=getMinKey();
if (min == null) {
if (putInHere == null) return new Bag(0);
else return putInHere;
}
if (putInHere == null) putInHere=new Bag();
putInHere.add(extractMin());
return extractMin(min,putInHere);
}
|
Removes all key-equal minimum elements and adds them to a Bag, which is then is returned. You may provide a Bag -- putInHere -- to be filled in.
|
public int hashCode(){
int myhash=37 + policyIdentifier.hashCode();
myhash=37 * myhash + policyQualifiers.hashCode();
return myhash;
}
|
Returns the hash code for this PolicyInformation.
|
public void test_getInstanceLjava_lang_StringLjava_security_Provider01() throws NoSuchAlgorithmException {
if (!DEFSupported) {
fail(NotSupportMsg);
return;
}
Provider provider=null;
for (int i=0; i < validValues.length; i++) {
try {
SSLContext.getInstance(validValues[i],provider);
fail("IllegalArgumentException must be thrown when provider is null");
}
catch ( IllegalArgumentException e) {
}
}
}
|
Test for <code>getInstance(String protocol, Provider provider)</code> method Assertion: throws IllegalArgumentException when provider is null
|
@Override public void init() throws MessagingException {
super.init();
messageString=getInitParameter("messageString","Hi. This is the James mail server at [machine].\nI'm afraid I wasn't able to deliver your message to the following addresses.\nThis is a permanent error; I've given up. Sorry it didn't work out. Below\nI include the list of recipients and the reason why I was unable to deliver\nyour message.\n");
}
|
Initialize the mailet
|
@Override public void eUnset(int featureID){
switch (featureID) {
case UmplePackage.IS_SORTED___PRIORITY_1:
setPriority_1(PRIORITY_1_EDEFAULT);
return;
}
super.eUnset(featureID);
}
|
<!-- begin-user-doc --> <!-- end-user-doc -->
|
public boolean canReplicateYeast(ItemStack stack){
if (stack.stackSize >= stack.getMaxStackSize()) return false;
if (!CellarRegistry.instance().yeast().isYeast(stack)) return false;
return true;
}
|
Determines if the given item stack can be replicated as a yeast item
|
public List<JCCatch> translateCatchers(List<JCCatch> trees){
for (List<JCCatch> l=trees; l.nonEmpty(); l=l.tail) l.head=translate(l.head);
return trees;
}
|
Visitor method: translate a list of catch clauses in try statements.
|
public static int encodeOneChar(CharsetEncoder encoder,int uchar){
ByteBuffer bb=ByteBuffer.allocate(10);
CharBuffer cb=CharBuffer.wrap(new char[]{(char)uchar});
CoderResult result=encoder.encode(cb,bb,true);
if (result.isError()) {
return 0;
}
if (bb.position() > 4) {
return 0;
}
int encChar=0;
for (int position=0; position < bb.position(); position++) {
encChar<<=8;
encChar|=(bb.get(position) & 0xff);
}
return encChar;
}
|
Encode a single character in UTF-16.
|
public void randomizeRow(int nodeIndex,int rowIndex){
final int size=getNumColumns(nodeIndex);
probs[nodeIndex][rowIndex]=getRandomWeights3(size);
}
|
Assigns random probability values to the child values of this row that add to 1.
|
protected void addDataSource(String dataSource){
if (!StringUtils.isEmpty(dataSource)) {
dataSources.add(dataSource);
}
}
|
Import a dataSource into view
|
public void test_getAlgorithm() throws NoSuchAlgorithmException, NoSuchProviderException {
assertEquals("Incorrect algorithm",getDefaultAlgorithm(),TrustManagerFactory.getInstance(getDefaultAlgorithm()).getAlgorithm());
assertEquals("Incorrect algorithm",getDefaultAlgorithm(),TrustManagerFactory.getInstance(getDefaultAlgorithm(),getDefaultProviderName()).getAlgorithm());
assertEquals("Incorrect algorithm",getDefaultAlgorithm(),TrustManagerFactory.getInstance(getDefaultAlgorithm(),getDefaultProvider()).getAlgorithm());
}
|
Test for <code>getAlgorithm()</code> method Assertion: returns the algorithm name of this object
|
public void clearSnapshot(String tag,String... keyspaceNames) throws IOException {
if (tag == null) tag="";
Set<String> keyspaces=new HashSet<>();
for ( String dataDir : DatabaseDescriptor.getAllDataFileLocations()) {
for ( String keyspaceDir : new File(dataDir).list()) {
if (keyspaceNames.length > 0 && !Arrays.asList(keyspaceNames).contains(keyspaceDir)) continue;
keyspaces.add(keyspaceDir);
}
}
for ( String keyspace : keyspaces) Keyspace.clearSnapshot(tag,keyspace);
if (logger.isDebugEnabled()) logger.debug("Cleared out snapshot directories");
}
|
Remove the snapshot with the given name from the given keyspaces. If no tag is specified we will remove all snapshots.
|
public void put(int i,double value){
if (i < 0 || i >= d) throw new IndexOutOfBoundsException("Illegal index");
if (value == 0.0) st.delete(i);
else st.put(i,value);
}
|
Sets the ith coordinate of this vector to the specified value.
|
public void updateVolumeInfo(StorageVolume volume,long newCapacity){
volume.setRequestedCapacity(newCapacity);
volume.setProvisionedCapacity(newCapacity);
volume.setAllocatedCapacity(newCapacity);
}
|
Update the storage volume information after a successful expansion.
|
public static List<String> listURLs(String text){
ArrayList<String> URLs=new ArrayList<>();
if (!TextUtils.isEmpty(text)) {
Matcher matcher=mUrlPattern.matcher(text);
while (matcher.find()) {
int matchStart=matcher.start(1);
int matchEnd=matcher.end();
String charBef="";
String charAfter="";
if (matchStart > 2) {
charBef=text.substring(matchStart - 2,matchStart);
}
if ((matchEnd - 1) < text.length()) {
charAfter=text.substring(matchEnd - 1,matchEnd);
}
if (!TextUtils.equals(charAfter,")") || !TextUtils.equals(charBef,"](")) {
String url=text.substring(matchStart,matchEnd);
if (URLs.indexOf(url) < 0) {
URLs.add(url);
}
}
}
}
return URLs;
}
|
List the URLs in a text.
|
public void testArriveAndDeregister4(){
Phaser parent=new Phaser();
Phaser child=new Phaser(parent);
assertEquals(0,parent.register());
assertEquals(0,child.register());
assertState(child,0,1,1);
assertState(parent,0,2,2);
assertEquals(0,child.arriveAndDeregister());
assertState(child,0,0,0);
assertState(parent,0,1,1);
}
|
arriveAndDeregister deregisters one party from its parent when the number of parties of child is zero after deregistration
|
public IPackageFragment findPackageFragment(IPath path){
if (!path.isAbsolute()) {
throw new IllegalArgumentException(Messages.path_mustBeAbsolute);
}
IResource possibleFragment=ResourcesPlugin.getWorkspace().getRoot().findMember(path);
if (possibleFragment == null) {
for (int i=0; i < this.packageFragmentRoots.length; i++) {
IPackageFragmentRoot root=this.packageFragmentRoots[i];
if (!root.isExternal()) {
continue;
}
IPath rootPath=root.getPath();
if (rootPath.isPrefixOf(path)) {
String name=path.toOSString();
name=name.substring(rootPath.toOSString().length() + 1,name.length());
name=name.replace(File.separatorChar,'.');
IJavaElement[] list=null;
try {
list=root.getChildren();
}
catch ( JavaModelException npe) {
continue;
}
int elementCount=list.length;
for (int j=0; j < elementCount; j++) {
IPackageFragment packageFragment=(IPackageFragment)list[j];
if (nameMatches(name,packageFragment,false)) {
return packageFragment;
}
}
}
}
}
else {
IJavaElement fromFactory=JavaCore.create(possibleFragment);
if (fromFactory == null) {
return null;
}
switch (fromFactory.getElementType()) {
case IJavaElement.PACKAGE_FRAGMENT:
return (IPackageFragment)fromFactory;
case IJavaElement.JAVA_PROJECT:
JavaProject project=(JavaProject)fromFactory;
try {
IClasspathEntry entry=project.getClasspathEntryFor(path);
if (entry != null) {
IPackageFragmentRoot root=project.getPackageFragmentRoot(project.getResource());
Object defaultPkgRoot=this.packageFragments.get(CharOperation.NO_STRINGS);
if (defaultPkgRoot == null) {
return null;
}
if (defaultPkgRoot instanceof PackageFragmentRoot && defaultPkgRoot.equals(root)) return ((PackageFragmentRoot)root).getPackageFragment(CharOperation.NO_STRINGS);
else {
IPackageFragmentRoot[] roots=(IPackageFragmentRoot[])defaultPkgRoot;
for (int i=0; i < roots.length; i++) {
if (roots[i].equals(root)) {
return ((PackageFragmentRoot)root).getPackageFragment(CharOperation.NO_STRINGS);
}
}
}
}
}
catch ( JavaModelException e) {
return null;
}
return null;
case IJavaElement.PACKAGE_FRAGMENT_ROOT:
return ((PackageFragmentRoot)fromFactory).getPackageFragment(CharOperation.NO_STRINGS);
}
}
return null;
}
|
Returns the package fragment whose path matches the given (absolute) path, or <code>null</code> if none exist. The domain of the search is bounded by the classpath of the <code>IJavaProject</code> this <code>NameLookup</code> was obtained from. The path can be: - internal to the workbench: "/Project/src" - external to the workbench: "c:/jdk/classes.zip/java/lang"
|
public static Dcs cs_permute(Dcs A,int[] pinv,int[] q,boolean values){
int t, j, k, nz=0, m, n, Ap[], Ai[], Cp[], Ci[];
double Cx[], Ax[];
Dcs C;
if (!Dcs_util.CS_CSC(A)) return (null);
m=A.m;
n=A.n;
Ap=A.p;
Ai=A.i;
Ax=A.x;
C=Dcs_util.cs_spalloc(m,n,Ap[n],values && Ax != null,false);
Cp=C.p;
Ci=C.i;
Cx=C.x;
for (k=0; k < n; k++) {
Cp[k]=nz;
j=q != null ? (q[k]) : k;
for (t=Ap[j]; t < Ap[j + 1]; t++) {
if (Cx != null) Cx[nz]=Ax[t];
Ci[nz++]=pinv != null ? (pinv[Ai[t]]) : Ai[t];
}
}
Cp[n]=nz;
return C;
}
|
Permutes a sparse matrix, C = PAQ.
|
public static void closeSilently(Reader reader){
if (reader != null) {
try {
reader.close();
}
catch ( Exception e) {
}
}
}
|
Close a reader without throwing an exception.
|
public FluentSupplier<R> partiallyApply(final T1 param1,final T2 param2){
return new FluentSupplier<>(PartialApplicator.partial2(param1,param2,fn));
}
|
Partially apply the provided parameters to this BiFunction to generate a Supplier (that takes no inputs)
|
public Builder deletePhoneNumbers(){
deleteFields.add("phoneNumbers");
return this;
}
|
deletes all phonenumbers of a existing user
|
protected ScriptDocValues.Longs docFieldLongs(String field){
return (ScriptDocValues.Longs)doc().get(field);
}
|
Returns field data long (integers) access for the provided field.
|
protected double computePixelSize(DrawContext dc,SurfaceTileDrawContext sdc){
return dc.getGlobe().getRadius() * sdc.getSector().getDeltaLatRadians() / sdc.getViewport().height;
}
|
Compute the size of a pixel in the surface tile.
|
public Vset checkMethod(Environment env,Context ctx,Vset vset,Hashtable exp){
CheckContext mctx=new CheckContext(ctx,new Statement(METHOD,0));
ctx=mctx;
vset=check(env,ctx,vset,exp);
if (!ctx.field.getType().getReturnType().isType(TC_VOID)) {
if (!vset.isDeadEnd()) {
env.error(ctx.field.getWhere(),"return.required.at.end",ctx.field);
}
}
vset=vset.join(mctx.vsBreak);
return vset;
}
|
Check a statement
|
public Shop(){
super();
}
|
Needed by CGLib
|
public ScrambledZipfianGenerator(long _items){
this(0,_items - 1);
}
|
Create a zipfian generator for the specified number of items.
|
public void resetData(){
for (int i=0; i < data.length; i++) data[i]=defaultValue;
}
|
Reset all data in this stream to default values.
|
public DefaultDownloadRequest(String url,RequestMethod requestMethod,String fileFolder,boolean isDeleteOld){
this(url,requestMethod,fileFolder,null,true,false,isDeleteOld);
}
|
Create download request.
|
private void showFeedback(String message){
if (myHost != null) {
myHost.showFeedback(message);
}
else {
System.out.println(message);
}
}
|
Used to communicate feedback pop-up messages between a plugin tool and the main Whitebox user-interface.
|
public static int hash(int hash,Object item){
if (item == null) {
return hash * prime;
}
return hash * prime + item.hashCode();
}
|
Add an object to a given hash.
|
public String noSizeDeterminationTipText(){
return "If enabled, the size determination for train/test/classifier is skipped.";
}
|
Returns the tip text for this property
|
@Override public int eBaseStructuralFeatureID(int derivedFeatureID,Class<?> baseClass){
if (baseClass == StrictModeRelevant.class) {
switch (derivedFeatureID) {
case N4JSPackage.IDENTIFIER_REF__STRICT_MODE:
return N4JSPackage.STRICT_MODE_RELEVANT__STRICT_MODE;
default :
return -1;
}
}
return super.eBaseStructuralFeatureID(derivedFeatureID,baseClass);
}
|
<!-- begin-user-doc --> <!-- end-user-doc -->
|
public static double enlargement(SpatialComparable exist,SpatialComparable addit){
final int dim=assertSameDimensionality(exist,addit);
double v1=1.;
double v2=1.;
for (int i=0; i < dim; i++) {
final double emin=exist.getMin(i);
final double emax=exist.getMax(i);
final double amin=addit.getMin(i);
final double amax=addit.getMax(i);
final double min=Math.min(emin,amin);
final double max=Math.max(emax,amax);
v1*=(max - min);
v2*=(emax - emin);
}
return v2 - v1;
}
|
Compute the enlargement obtained by adding an object to an existing object.
|
protected static void midPoint(int hilliness,int width,int height,int elevationMap[][]){
int size;
int steps=1;
int tmpElevation[][];
size=(width > height) ? width : height;
while (size > 0) {
steps++;
size/=2;
}
size=(1 << steps) + 1;
tmpElevation=new int[size + 1][size + 1];
for (int w=0; w < size; w++) {
for (int h=0; h < size; h++) {
if ((w < width) && (h < height)) {
tmpElevation[w][h]=elevationMap[w][h];
}
else {
tmpElevation[w][h]=0;
}
}
}
for (int i=steps; i > 0; i--) {
midPointStep((double)hilliness / 100,size,100,tmpElevation,i,true);
}
for (int w=0; w < width; w++) {
for (int h=0; h < height; h++) {
elevationMap[w][h]=tmpElevation[w][h];
}
}
}
|
midpoint algorithm for landscape generartion
|
@SuppressWarnings("unchecked") @Override public void init(NamedList args){
inclusions=parseSelectorParams(args);
exclusions=parseSelectorExclusionParams(args);
if (0 < args.size()) {
throw new SolrException(SolrException.ErrorCode.SERVER_ERROR,"Unexpected init param(s): '" + args.getName(0) + "'");
}
}
|
Handles common initialization related to source fields for constructing the FieldNameSelector to be used. Will error if any unexpected init args are found, so subclasses should remove any subclass-specific init args before calling this method.
|
public Versioned<T> cloneVersioned(){
return new Versioned<T>(this.getValue(),this.version.clone());
}
|
Create a clone of this Versioned object such that the object pointed to is the same, but the VectorClock and Versioned wrapper is a shallow copy.
|
public boolean isAnnotation(){
return false;
}
|
Determines whether this object represents an annotation type. It returns <code>true</code> if this object represents an annotation type.
|
private void safety(){
if (gamePoss) {
awayScore+=2;
gameEventLog+=getEventPrefix() + "SAFETY!\n" + homeTeam.abbr+ " QB "+ homeTeam.getQB(0).name+ " was tackled in the endzone! Result is a safety and "+ awayTeam.abbr+ " will get possession.";
freeKick(homeTeam);
}
else {
homeScore+=2;
gameEventLog+=getEventPrefix() + "SAFETY!\n" + awayTeam.abbr+ " QB "+ awayTeam.getQB(0).name+ " was tackled in the endzone! Result is a safety and "+ homeTeam.abbr+ " will get possession.";
freeKick(awayTeam);
}
}
|
Perform safety. Will add 2 to the correct team and give the ball over via a free kick.
|
public void clearValues(){
mDataSets.clear();
notifyDataChanged();
}
|
Clears this data object from all DataSets and removes all Entries. Don't forget to invalidate the chart after this.
|
public Value sample(Assignment condition){
if (distrib instanceof IndependentDistribution) {
return ((IndependentDistribution)distrib).sample();
}
return distrib.sample(condition);
}
|
Returns a sample value for the node, given a condition. The sample is selected according to the probability distribution for the node.
|
public ASN1Implicit(int tagNumber,ASN1Type type){
super(CLASS_CONTEXTSPECIFIC,tagNumber);
if ((type instanceof ASN1Choice) || (type instanceof ASN1Any)) {
throw new IllegalArgumentException("Implicit tagging can not be used for ASN.1 ANY or CHOICE type");
}
this.type=type;
if (type.checkTag(type.id)) {
if (type.checkTag(type.constrId)) {
taggingType=TAGGING_STRING;
}
else {
taggingType=TAGGING_PRIMITIVE;
}
}
else {
taggingType=TAGGING_CONSTRUCTED;
}
}
|
Constructs implicitly tagged ASN.1 type with context-specific tag class and specified tag number.
|
public MalformedURIException(String p_msg){
super(p_msg);
}
|
Constructs a <code>MalformedURIException</code> with the specified detail message.
|
private void finishScan(int state){
switch (state) {
case SEEK_ALGORITHM:
pcalStartCommentOffset=-1;
pcalStartOffset=-1;
pcalEndCommentOffset=-1;
break;
case START_ALGORITHM:
break;
case IN_ALGORITHM:
break;
}
}
|
Called by documentChanged2, when it has finished calling the scanner, to set the information about the existence and location of a PlusCal partition.
|
public CPerspectiveModel(final IGraphModel model){
m_models.put(PerspectiveType.DebugPerspective,new CDebugPerspectiveModel(model));
}
|
Creates a new perspective model.
|
@Override public Object eGet(int featureID,boolean resolve,boolean coreType){
switch (featureID) {
case GamlPackage.IMPORT__IMPORT_URI:
return getImportURI();
}
return super.eGet(featureID,resolve,coreType);
}
|
<!-- begin-user-doc --> <!-- end-user-doc -->
|
private FetchBufferPart fetch(long pos,int size){
long remaining=limit - pos;
size=(int)Math.min(size,remaining);
return size <= 0 ? null : new FetchBufferPart(delegate.hadoop().readData(delegate,pos,size,null,0,0),pos,size);
}
|
Starts asynchronous fetch for given region.
|
@DSComment("Private Method") @DSBan(DSCat.PRIVATE_METHOD) @DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 12:55:20.488 -0500",hash_original_method="A02B6100DC58EB921085C7ED44EE1D0C",hash_generated_method="48084A26E40A2F235318545FF3404AE3") private void addTransactionHash(SIPTransaction sipTransaction){
SIPRequest sipRequest=sipTransaction.getOriginalRequest();
if (sipTransaction instanceof SIPClientTransaction) {
if (!this.unlimitedClientTransactionTableSize) {
if (this.activeClientTransactionCount.get() > clientTransactionTableHiwaterMark) {
try {
synchronized (this.clientTransactionTable) {
this.clientTransactionTable.wait();
this.activeClientTransactionCount.incrementAndGet();
}
}
catch ( Exception ex) {
if (stackLogger.isLoggingEnabled()) {
stackLogger.logError("Exception occured while waiting for room",ex);
}
}
}
}
else {
this.activeClientTransactionCount.incrementAndGet();
}
String key=sipRequest.getTransactionId();
clientTransactionTable.put(key,(SIPClientTransaction)sipTransaction);
if (stackLogger.isLoggingEnabled()) {
stackLogger.logDebug(" putTransactionHash : " + " key = " + key);
}
}
else {
String key=sipRequest.getTransactionId();
if (stackLogger.isLoggingEnabled()) {
stackLogger.logDebug(" putTransactionHash : " + " key = " + key);
}
serverTransactionTable.put(key,(SIPServerTransaction)sipTransaction);
}
}
|
Hash table for quick lookup of transactions. Here we wait for room if needed.
|
public MATSimState(final Population population,final Vector vectorRepresentation){
this.population=population;
for ( Person person : population.getPersons().values()) {
if (person.getSelectedPlan() == null) {
this.person2selectedPlanIndex.put(person.getId(),null);
}
else {
final int selectedPlanIndex=person.getPlans().indexOf(person.getSelectedPlan());
if (selectedPlanIndex < 0) {
throw new RuntimeException("The selected plan of person " + person.getId() + " cannot be found in its plan list.");
}
this.person2selectedPlanIndex.put(person.getId(),selectedPlanIndex);
}
this.person2planList.put(person.getId(),newDeepCopy(person.getPlans()));
}
this.vectorRepresentation=vectorRepresentation;
}
|
Takes over a <em>deep copy</em> of the population's plans and a <em>reference</em> to the vector representation.
|
public static <L,R>ImmutablePair<L,R> of(final L left,final R right){
return new ImmutablePair<L,R>(left,right);
}
|
<p>Obtains an immutable pair of from two objects inferring the generic types.</p> <p>This factory allows the pair to be created using inference to obtain the generic types.</p>
|
public static MapPro duplicateDataMember(ComponentImpl c,MapPro map,MapPro newMap,boolean deepCopy){
Iterator it=map.entrySet().iterator();
Map.Entry entry;
Object value;
while (it.hasNext()) {
entry=(Entry)it.next();
value=entry.getValue();
if (!(value instanceof UDF)) {
if (deepCopy) value=Duplicator.duplicate(value,deepCopy);
newMap.put(entry.getKey(),value);
}
}
return newMap;
}
|
duplicate the datamember in the map, ignores the udfs
|
protected final void updateDrawable(int featureId,boolean fromActive){
final DrawableFeatureState st=getDrawableState(featureId,false);
if (st != null) {
updateDrawable(featureId,st,fromActive);
}
}
|
Update the state of a drawable feature. This should be called, for every drawable feature supported, as part of onActive(), to make sure that the contents of a containing window is properly updated.
|
protected void assertValidResponse(ArgusHttpClient.ArgusResponse response,String requestUrl) throws ArgusServiceException {
if (response.getErrorMessage() != null) {
throw new ArgusServiceException(response.getStatus(),response.getErrorMessage(),requestUrl,response.getResult());
}
}
|
Throws an exception if a request results in an error.
|
public HindiStemFilterFactory(Map<String,String> args){
super(args);
if (!args.isEmpty()) {
throw new IllegalArgumentException("Unknown parameters: " + args);
}
}
|
Creates a new HindiStemFilterFactory
|
public static String encodeBytes(byte[] source,int off,int len){
byte[] encoded=encodeBytesToBytes(source,off,len);
try {
return new String(encoded,PREFERRED_ENCODING);
}
catch ( UnsupportedEncodingException uue) {
return new String(encoded);
}
}
|
Encodes a byte array into Base64 notation.
|
public static IJavaElement findNextSibling(IJavaElement member) throws JavaModelException {
IJavaElement parent=member.getParent();
if (parent instanceof IParent) {
IJavaElement[] elements=((IParent)parent).getChildren();
for (int i=elements.length - 2; i >= 0; i--) {
if (member.equals(elements[i])) {
return elements[i + 1];
}
}
}
return null;
}
|
Returns the element after the give element.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.