_id
stringlengths 2
7
| title
stringlengths 3
140
| partition
stringclasses 3
values | text
stringlengths 73
34.1k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q180000
|
StateMachineParser.toJSON
|
test
|
protected String toJSON() {
ObjectMapper mapper = new ObjectMapper();
try {
String jsonINString = mapper.writeValueAsString(notationContainer);
jsonINString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(notationContainer);
return jsonINString;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
|
java
|
{
"resource": ""
}
|
q180001
|
HELM2Notation.getSimplePolymer
|
test
|
public PolymerNotation getSimplePolymer(String string) {
for (PolymerNotation polymer : listOfPolymers) {
if (polymer.getPolymerID().getId().equals(string)) {
return polymer;
}
}
return null;
}
|
java
|
{
"resource": ""
}
|
q180002
|
HELM2Notation.getCurrentGroupingNotation
|
test
|
@JsonIgnore
public GroupingNotation getCurrentGroupingNotation() {
if (listOfGroupings.size() == 0) {
return null;
}
return listOfGroupings.get(listOfGroupings.size() - 1);
}
|
java
|
{
"resource": ""
}
|
q180003
|
HELM2Notation.toHELM2
|
test
|
public String toHELM2() {
String output = "";
/* first section: simple polymer section */
output += polymerToHELM2() + "$";
/* second section: connection section */
output += connectionToHELM2() + "$";
/* third section: grouping section */
output += groupingToHELM2() + "$";
/* fourth section: annotation section */
output += annotationToHELM2() + "$";
/* add version number */
output += "V2.0";
return output;
}
|
java
|
{
"resource": ""
}
|
q180004
|
HELM2Notation.polymerToHELM2
|
test
|
public String polymerToHELM2() {
StringBuilder notation = new StringBuilder();
for (int i = 0; i < listOfPolymers.size(); i++) {
if (listOfPolymers.get(i).isAnnotationHere()) {
notation.append(listOfPolymers.get(i).getPolymerID() + "{" + listOfPolymers.get(i).toHELM2() + "}\""
+ listOfPolymers.get(i).getAnnotation() + "\"|");
} else {
notation.append(listOfPolymers.get(i).getPolymerID() + "{" + listOfPolymers.get(i).toHELM2() + "}" + "|");
}
}
notation.setLength(notation.length() - 1);
return notation.toString();
}
|
java
|
{
"resource": ""
}
|
q180005
|
HELM2Notation.connectionToHELM2
|
test
|
public String connectionToHELM2() {
if (listOfConnections.size() == 0) {
return "";
}
StringBuilder notation = new StringBuilder();
for (int i = 0; i < listOfConnections.size(); i++) {
notation.append(listOfConnections.get(i).toHELM2() + "|");
}
notation.setLength(notation.length() - 1);
return notation.toString();
}
|
java
|
{
"resource": ""
}
|
q180006
|
HELM2Notation.groupingToHELM2
|
test
|
public String groupingToHELM2() {
if (listOfGroupings.size() == 0) {
return "";
}
StringBuilder notation = new StringBuilder();
for (int i = 0; i < listOfGroupings.size(); i++) {
notation.append(listOfGroupings.get(i).toHELM2() + "|");
}
notation.setLength(notation.length() - 1);
return notation.toString();
}
|
java
|
{
"resource": ""
}
|
q180007
|
HELM2Notation.annotationToHELM2
|
test
|
public String annotationToHELM2() {
if (!(annotationSection.isEmpty())) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < annotationSection.size(); i++) {
sb.append(annotationSection.get(i).toHELM2() + "|");
}
sb.setLength(sb.length() - 1);
return sb.toString();
}
return "";
}
|
java
|
{
"resource": ""
}
|
q180008
|
HELM2Notation.getPolymerAndGroupingIDs
|
test
|
@JsonIgnore
public List<String> getPolymerAndGroupingIDs() {
List<String> listOfIDs = new ArrayList<String>();
for (PolymerNotation polymer : listOfPolymers) {
listOfIDs.add(polymer.getPolymerID().getId());
}
for (GroupingNotation grouping : listOfGroupings) {
listOfIDs.add(grouping.getGroupID().getId());
}
return listOfIDs;
}
|
java
|
{
"resource": ""
}
|
q180009
|
HELM2Notation.getPolymerNotation
|
test
|
@JsonIgnore
public PolymerNotation getPolymerNotation(String id) {
for (PolymerNotation polymer : listOfPolymers) {
if (polymer.getPolymerID().getId().equals(id)) {
return polymer;
}
}
return null;
}
|
java
|
{
"resource": ""
}
|
q180010
|
PolymerNotation.setPolymerElements
|
test
|
private void setPolymerElements() {
if (polymerID instanceof RNAEntity || polymerID instanceof PeptideEntity) {
this.polymerElements = new PolymerListElements(polymerID);
} else {
this.polymerElements = new PolymerSingleElements(polymerID);
}
}
|
java
|
{
"resource": ""
}
|
q180011
|
ConverterHELM1ToHELM2.doConvert
|
test
|
public String doConvert(String str) {
//check for just missing V2.0
ParserHELM2 parser = new ParserHELM2();
try{
parser.parse(str + "V2.0");
return str + "V2.0";
}
catch(Exception e){
/* Use String Builder */
/* simple add character -> split works then */
String helm1 = str + "f";
StringBuilder helm2 = new StringBuilder();
String[] sections = helm1.split("}\\$");
/* Section 1 is accepted in full, no changes necessary, Section 1 has to be there */
helm2.append(sections[0] + "}$");
StringBuilder sb = new StringBuilder();
for (int i = 1; i < sections.length; i++) {
sb.append(sections[i] + "}$");
}
helm1 = "$" + sb.toString();
sections = helm1.split("\\$");
/*
* Section 2 connection section; section 3 is added to the second section,
* Section 2 is not necessary, is this section really there
*/
if (sections.length >= 2) {
if (!(sections[1].isEmpty())) {
helm2.append(sections[1]);
}
}
/* Add hydrogen bonds to the connection section */
if (sections.length >= 3) {
if (!(sections[2].isEmpty())) {
if (!(sections[1].isEmpty())) {
helm2.append("|" + sections[2]);
} else {
helm2.append(sections[2]);
}
}
/*Group section*/
helm2.append("$");
helm2.append("$");
/*Add annotation to the annotation section*/
if (sections.length >= 4) {
if (!(sections[3].isEmpty())) {
helm2.append(sections[3]);
}
}
}
/* Add version number to indicate HELM2 notation */
helm2.append("$V2.0");
return helm2.toString();
}
}
|
java
|
{
"resource": ""
}
|
q180012
|
MonomerNotation.setAnnotation
|
test
|
public void setAnnotation(String str) {
if (str != null) {
annotation = str;
isAnnotationHere = true;
} else {
annotation = null;
isAnnotationHere = false;
}
}
|
java
|
{
"resource": ""
}
|
q180013
|
MonomerNotation.setCount
|
test
|
public void setCount(String str) {
isDefault = false;
if (str.equals("1")) {
isDefault = true;
}
count = str;
}
|
java
|
{
"resource": ""
}
|
q180014
|
ValidationMethod.decideWhichMonomerNotation
|
test
|
public static MonomerNotation decideWhichMonomerNotation(String str, String type)
throws NotationException {
MonomerNotation mon;
/* group ? */
if (str.startsWith("(") && str.endsWith(")")) {
String str2 = str.substring(1, str.length() - 1);
Pattern patternAND = Pattern.compile("\\+");
Pattern patternOR = Pattern.compile(",");
/* Mixture of elements */
if (patternAND.matcher(str).find()) {
mon = new MonomerNotationGroupMixture(str2, type);
} /* or - groups */ else if (patternOR.matcher(str).find()) {
mon = new MonomerNotationGroupOr(str2, type);
} else {
if (str.contains(".")) {
mon = new MonomerNotationList(str2, type);
} else {
/* monomer unit is just in brackets */
if (type == "RNA") {
mon = new MonomerNotationUnitRNA(str2, type);
} else {
if (str2.length() > 1) {
if (!(str2.startsWith("[") && str2.endsWith("]"))) {
throw new NotationException("Monomers have to be in brackets: " + str);
}
}
mon = new MonomerNotationUnit(str2, type);
}
}
}
} else {
if (type == "RNA") {
// if (str.startsWith("[") && str.endsWith("]")) {
// mon = new MonomerNotationUnitRNA(str, type);
// }
mon = new MonomerNotationUnitRNA(str, type);
} else if (type != "BLOB") {
if (str.length() > 1) {
if (!(str.startsWith("[") && str.endsWith("]"))) {
throw new NotationException("Monomers have to be in brackets: " + str);
}
}
mon = new MonomerNotationUnit(str, type);
}
else{
mon = new MonomerNotationUnit(str, type);
}
}
return mon;
}
|
java
|
{
"resource": ""
}
|
q180015
|
ValidationMethod.decideWhichMonomerNotationInGroup
|
test
|
public static MonomerNotationGroupElement decideWhichMonomerNotationInGroup(String str, String type, double one,
double two, boolean interval, boolean isDefault) throws NotationException{
MonomerNotation element;
element = decideWhichMonomerNotation(str, type);
if (interval) {
return new MonomerNotationGroupElement(element, one, two);
} else {
return new MonomerNotationGroupElement(element, one, isDefault);
}
}
|
java
|
{
"resource": ""
}
|
q180016
|
ValidationMethod.decideWhichEntity
|
test
|
public static HELMEntity decideWhichEntity(String str) throws NotationException {
HELMEntity item;
if (str.toUpperCase().matches("PEPTIDE[1-9][0-9]*")) {
item = new PeptideEntity(str.toUpperCase());
} else if (str.toUpperCase().matches("RNA[1-9][0-9]*")) {
item = new RNAEntity(str.toUpperCase());
} else if (str.toUpperCase().matches("BLOB[1-9][0-9]*")) {
item = new BlobEntity(str.toUpperCase());
} else if (str.toUpperCase().matches("CHEM[1-9][0-9]*")) {
item = new ChemEntity(str.toUpperCase());
} else if (str.toUpperCase().matches("G[1-9][0-9]*")) {
item = new GroupEntity(str.toUpperCase());
} else {
throw new NotationException("ID is wrong: " + str);
}
return item;
}
|
java
|
{
"resource": ""
}
|
q180017
|
MonomerNotationGroupElement.getValue
|
test
|
public List<Double> getValue() {
if (this.isInterval) {
return new ArrayList<Double>(Arrays.asList(numberOne, numberTwo));
} else {
return new ArrayList<Double>(Arrays.asList(numberOne));
}
}
|
java
|
{
"resource": ""
}
|
q180018
|
ParserHELM2.parse
|
test
|
public void parse(String test) throws ExceptionState {
parser = new StateMachineParser();
test = test.trim();
if (test.substring(test.length() - 4).matches("V2\\.0") || test.substring(test.length() - 4).matches("v2\\.0")) {
for (int i = 0; i < test.length() - 4; i++) {
parser.doAction(test.charAt(i));
}
if (!(parser.getState() instanceof FinalState)) {
LOG.error("Invalid input: Final State was not reached:");
throw new FinalStateException("Invalid input: Final State was not reached");
}
} else {
LOG.error("Invalid input: HELM2 standard is missing:");
throw new NotValidHELM2Exception("Invalid input: HELM2 standard is missing");
}
}
|
java
|
{
"resource": ""
}
|
q180019
|
MonomerNotationUnitRNA.setRNAContents
|
test
|
private void setRNAContents(String str) throws NotationException {
/* Nucleotide with all contents */
String[] list;
// if (str.contains("(")) {
List<String> items = extractContents(str);
for (String item : items) {
if(item.length()> 1){
if(!(item.startsWith("[") && item.endsWith("]"))){
throw new NotationException("Monomers have to be in brackets "+ item);
}
}
contents.add(new MonomerNotationUnit(item, type));
}
// } /* nucleotide contains no base, but a modified sugar or phosphat */
// else if (str.contains("[")) {
// if (str.startsWith("[")) {
// str = str.replace("]", "]$");
// } else {
// str = str.replace("[", "$[");
// }
// list = str.split("\\$");
// for (int i = 0; i < list.length; i++) {
// contents.add(new MonomerNotationUnit(list[i], type));
// }
// } /* nucleotide contains only standard sugar and/or phosphat */ else {
// for (int i = 0; i < str.length(); i++) {
// contents.add(new MonomerNotationUnit(Character.toString(str.charAt(i)),
// type));
// }
// }
}
|
java
|
{
"resource": ""
}
|
q180020
|
GroupingNotation.defineAmbiguity
|
test
|
private void defineAmbiguity(String a) throws NotationException {
Pattern patternAND = Pattern.compile("\\+");
Matcher m = patternAND.matcher(a);
/* mixture */
if (m.find()) {
setAmbiguity(new GroupingMixture(a));
} /* or case */ else {
setAmbiguity(new GroupingOr(a));
}
}
|
java
|
{
"resource": ""
}
|
q180021
|
WorkerThread.getStatistics
|
test
|
AWorkerThreadStatistics getStatistics() {
return new AWorkerThreadStatistics (getState (), getId (),
stat_numTasksExecuted, stat_numSharedTasksExecuted, stat_numSteals, stat_numExceptions, stat_numParks, stat_numFalseAlarmUnparks, stat_numSharedQueueSwitches, stat_numLocalSubmits, localQueue.approximateSize ());
}
|
java
|
{
"resource": ""
}
|
q180022
|
ADiGraph.create
|
test
|
public static <N, E extends AEdge<N>> ADiGraph<N,E> create (Collection<E> edges) {
final Set<N> result = new HashSet<> ();
for (E edge: edges) {
result.add (edge.getFrom ());
result.add (edge.getTo ());
}
return create (result, edges);
}
|
java
|
{
"resource": ""
}
|
q180023
|
ADiGraph.create
|
test
|
public static <N, E extends AEdge<N>> ADiGraph<N,E> create (Collection<N> nodes, Collection<E> edges) {
final Object[] nodeArr = new Object[nodes.size ()];
final AEdge[] edgeArr = new AEdge[edges.size ()];
int idx = 0;
for (N node: nodes) {
nodeArr[idx] = node;
idx += 1;
}
idx = 0;
for (E edge: edges) {
edgeArr[idx] = edge;
idx += 1;
}
return new ADiGraph<N,E> (nodeArr, edgeArr);
}
|
java
|
{
"resource": ""
}
|
q180024
|
ADiGraph.initPathsInternal
|
test
|
private void initPathsInternal() {
synchronized (LOCK) {
if (_incomingPathsInternal == null) {
AMap<N, AList<AEdgePath<N, E>>> incomingPaths = AHashMap.empty ();
//noinspection unchecked
incomingPaths = incomingPaths.withDefaultValue (AList.nil);
AMap<N, AList<AEdgePath<N, E>>> outgoingPaths = AHashMap.empty ();
//noinspection unchecked
outgoingPaths = outgoingPaths.withDefaultValue (AList.nil);
AList<AEdgePath<N, E>> cycles = AList.nil ();
for (N curNode : nodes ()) { // iterate over nodes, treat 'curNode' as a target
final Iterable<E> curIncoming = incomingEdges (curNode);
List<AEdgePath<N, E>> unfinishedBusiness = new ArrayList<> ();
for (E incomingEdge : curIncoming) {
unfinishedBusiness.add (AEdgePath.create (incomingEdge));
}
AList<AEdgePath<N, E>> nonCycles = AList.nil ();
while (unfinishedBusiness.size () > 0) {
final List<AEdgePath<N, E>> curBusiness = unfinishedBusiness;
for (AEdgePath<N, E> p : unfinishedBusiness) {
if (!p.hasCycle () || p.isMinimalCycle ()) nonCycles = nonCycles.cons (p);
if (p.isMinimalCycle ()) cycles = cycles.cons (p);
}
unfinishedBusiness = new ArrayList<> ();
for (AEdgePath<N, E> curPath : curBusiness) {
final Iterable<E> l = incomingEdges (curPath.getFrom ());
for (E newEdge : l) {
final AEdgePath<N, E> pathCandidate = curPath.prepend (newEdge);
if (!pathCandidate.hasNonMinimalCycle ()) {
unfinishedBusiness.add (pathCandidate);
}
}
}
}
incomingPaths = incomingPaths.updated (curNode, nonCycles);
for (AEdgePath<N, E> p : nonCycles) {
outgoingPaths = outgoingPaths.updated (p.getFrom (), outgoingPaths.getRequired (p.getFrom ()).cons (p));
}
}
_incomingPathsInternal = incomingPaths;
_outgoingPathsInternal = outgoingPaths;
_cyclesInternal = cycles;
}
}
}
|
java
|
{
"resource": ""
}
|
q180025
|
ADiGraph.sortedNodesByReachability
|
test
|
public List<N> sortedNodesByReachability() throws AGraphCircularityException {
if (hasCycles()) {
throw new AGraphCircularityException ();
}
final Object[] result = new Object[nodes.length];
int nextIdx = 0;
final Set<N> unprocessed = new HashSet<> ();
for (Object node: nodes) {
//noinspection unchecked
unprocessed.add ((N) node);
}
//TODO Map<N,Integer> with 'remaining' incoming edges, decrement when a node is 'processed' --> JMH
while (! unprocessed.isEmpty ()) {
final Set<N> nextBatch = ACollectionHelper.filter (unprocessed, new APredicateNoThrow<N> () {
@Override public boolean apply (N n) {
for (E e : incomingEdges (n)) {
if (unprocessed.contains (e.getFrom ())) {
return false;
}
}
return true;
}
});
unprocessed.removeAll (nextBatch);
for (N n: nextBatch) {
result[nextIdx] = n;
nextIdx += 1;
}
}
return new ArrayIterable<> (result);
}
|
java
|
{
"resource": ""
}
|
q180026
|
API.subscribe
|
test
|
public void subscribe(final String pattern,
final Class<?> clazz,
final String methodName)
throws NoSuchMethodException
{
this.subscribe(pattern, new FunctionObject9(this, clazz, methodName));
}
|
java
|
{
"resource": ""
}
|
q180027
|
API.subscribe_count
|
test
|
public int subscribe_count(final String pattern)
throws InvalidInputException,
TerminateException
{
OtpOutputStream subscribe_count = new OtpOutputStream();
subscribe_count.write(OtpExternal.versionTag);
final OtpErlangObject[] tuple = {new OtpErlangAtom("subscribe_count"),
new OtpErlangString(pattern)};
subscribe_count.write_any(new OtpErlangTuple(tuple));
send(subscribe_count);
try
{
return (Integer) poll_request(null, false);
}
catch (MessageDecodingException e)
{
e.printStackTrace(API.err);
return -1;
}
}
|
java
|
{
"resource": ""
}
|
q180028
|
API.unsubscribe
|
test
|
public void unsubscribe(final String pattern)
throws InvalidInputException
{
final String s = this.prefix + pattern;
LinkedList<FunctionInterface9> callback_list = this.callbacks.get(s);
if (callback_list == null)
{
throw new InvalidInputException();
}
else
{
callback_list.removeFirst();
if (callback_list.isEmpty())
{
this.callbacks.remove(s);
}
}
OtpOutputStream unsubscribe = new OtpOutputStream();
unsubscribe.write(OtpExternal.versionTag);
final OtpErlangObject[] tuple = {new OtpErlangAtom("unsubscribe"),
new OtpErlangString(pattern)};
unsubscribe.write_any(new OtpErlangTuple(tuple));
send(unsubscribe);
}
|
java
|
{
"resource": ""
}
|
q180029
|
API.return_
|
test
|
public void return_(final Integer request_type,
final String name,
final String pattern,
final byte[] response_info,
final byte[] response,
final Integer timeout,
final byte[] trans_id,
final OtpErlangPid pid)
throws ReturnAsyncException,
ReturnSyncException,
InvalidInputException
{
if (request_type == API.ASYNC)
return_async(name, pattern, response_info, response,
timeout, trans_id, pid);
else if (request_type == API.SYNC)
return_sync(name, pattern, response_info, response,
timeout, trans_id, pid);
else
throw new InvalidInputException();
}
|
java
|
{
"resource": ""
}
|
q180030
|
API.return_sync
|
test
|
public void return_sync(final String name,
final String pattern,
byte[] response_info,
byte[] response,
Integer timeout,
final byte[] trans_id,
final OtpErlangPid pid)
throws ReturnSyncException
{
try
{
OtpOutputStream return_sync = new OtpOutputStream();
return_sync.write(OtpExternal.versionTag);
final OtpErlangObject[] tuple = {new OtpErlangAtom("return_sync"),
new OtpErlangString(name),
new OtpErlangString(pattern),
new OtpErlangBinary(response_info),
new OtpErlangBinary(response),
new OtpErlangUInt(timeout),
new OtpErlangBinary(trans_id),
pid};
return_sync.write_any(new OtpErlangTuple(tuple));
send(return_sync);
}
catch (OtpErlangRangeException e)
{
e.printStackTrace(API.err);
return;
}
throw new ReturnSyncException();
}
|
java
|
{
"resource": ""
}
|
q180031
|
API.poll
|
test
|
public boolean poll(final int timeout)
throws InvalidInputException,
MessageDecodingException,
TerminateException
{
if (Boolean.TRUE == poll_request(timeout, true))
return true;
return false;
}
|
java
|
{
"resource": ""
}
|
q180032
|
API.shutdown
|
test
|
public void shutdown(final String reason)
{
OtpOutputStream shutdown = new OtpOutputStream();
shutdown.write(OtpExternal.versionTag);
final OtpErlangObject[] tuple = {new OtpErlangAtom("shutdown"),
new OtpErlangString(reason)};
shutdown.write_any(new OtpErlangTuple(tuple));
send(shutdown);
}
|
java
|
{
"resource": ""
}
|
q180033
|
AExceptionFilter.forLocalHandling
|
test
|
public static <T extends Throwable> T forLocalHandling (T th) {
if (requiresNonLocalHandling (th)) {
AUnchecker.throwUnchecked (th);
}
return th;
}
|
java
|
{
"resource": ""
}
|
q180034
|
ForkJoinPool.unlockRunState
|
test
|
private void unlockRunState(int oldRunState, int newRunState) {
if (!U.compareAndSwapInt(this, RUNSTATE, oldRunState, newRunState)) {
Object lock = stealCounter;
runState = newRunState; // clears RSIGNAL bit
if (lock != null)
synchronized (lock) { lock.notifyAll(); }
}
}
|
java
|
{
"resource": ""
}
|
q180035
|
ForkJoinPool.createWorker
|
test
|
private boolean createWorker() {
ForkJoinWorkerThreadFactory fac = factory;
Throwable ex = null;
ForkJoinWorkerThread wt = null;
try {
if (fac != null && (wt = fac.newThread(this)) != null) {
wt.start();
return true;
}
} catch (Throwable rex) {
ex = rex;
}
deregisterWorker(wt, ex);
return false;
}
|
java
|
{
"resource": ""
}
|
q180036
|
ForkJoinPool.tryAddWorker
|
test
|
private void tryAddWorker(long c) {
boolean add = false;
do {
long nc = ((AC_MASK & (c + AC_UNIT)) |
(TC_MASK & (c + TC_UNIT)));
if (ctl == c) {
int rs, stop; // check if terminating
if ((stop = (rs = lockRunState()) & STOP) == 0)
add = U.compareAndSwapLong(this, CTL, c, nc);
unlockRunState(rs, rs & ~RSLOCK);
if (stop != 0)
break;
if (add) {
createWorker();
break;
}
}
} while (((c = ctl) & ADD_WORKER) != 0L && (int)c == 0);
}
|
java
|
{
"resource": ""
}
|
q180037
|
ForkJoinPool.registerWorker
|
test
|
final WorkQueue registerWorker(ForkJoinWorkerThread wt) {
UncaughtExceptionHandler handler;
wt.setDaemon(true); // configure thread
if ((handler = ueh) != null)
wt.setUncaughtExceptionHandler(handler);
WorkQueue w = new WorkQueue(this, wt);
int i = 0; // assign a pool index
int mode = config & MODE_MASK;
int rs = lockRunState();
try {
WorkQueue[] ws; int n; // skip if no array
if ((ws = workQueues) != null && (n = ws.length) > 0) {
int s = indexSeed += SEED_INCREMENT; // unlikely to collide
int m = n - 1;
i = ((s << 1) | 1) & m; // odd-numbered indices
if (ws[i] != null) { // collision
int probes = 0; // step by approx half n
int step = (n <= 4) ? 2 : ((n >>> 1) & EVENMASK) + 2;
while (ws[i = (i + step) & m] != null) {
if (++probes >= n) {
workQueues = ws = Arrays.copyOf(ws, n <<= 1);
m = n - 1;
probes = 0;
}
}
}
w.hint = s; // use as random seed
w.config = i | mode;
w.scanState = i; // publication fence
ws[i] = w;
}
} finally {
unlockRunState(rs, rs & ~RSLOCK);
}
wt.setName(workerNamePrefix.concat(Integer.toString(i >>> 1)));
return w;
}
|
java
|
{
"resource": ""
}
|
q180038
|
ForkJoinPool.deregisterWorker
|
test
|
final void deregisterWorker(ForkJoinWorkerThread wt, Throwable ex) {
WorkQueue w = null;
if (wt != null && (w = wt.workQueue) != null) {
WorkQueue[] ws; // remove index from array
int idx = w.config & SMASK;
int rs = lockRunState();
if ((ws = workQueues) != null && ws.length > idx && ws[idx] == w)
ws[idx] = null;
unlockRunState(rs, rs & ~RSLOCK);
}
long c; // decrement counts
do {} while (!U.compareAndSwapLong
(this, CTL, c = ctl, ((AC_MASK & (c - AC_UNIT)) |
(TC_MASK & (c - TC_UNIT)) |
(SP_MASK & c))));
if (w != null) {
w.qlock = -1; // ensure set
w.transferStealCount(this);
w.cancelAll(); // cancel remaining tasks
}
for (;;) { // possibly replace
WorkQueue[] ws; int m, sp;
if (tryTerminate(false, false) || w == null || w.array == null ||
(runState & STOP) != 0 || (ws = workQueues) == null ||
(m = ws.length - 1) < 0) // already terminating
break;
if ((sp = (int)(c = ctl)) != 0) { // wake up replacement
if (tryRelease(c, ws[sp & m], AC_UNIT))
break;
}
else if (ex != null && (c & ADD_WORKER) != 0L) {
tryAddWorker(c); // create replacement
break;
}
else // don't need replacement
break;
}
if (ex == null) // help clean on way out
ForkJoinTask.helpExpungeStaleExceptions();
else // rethrow
ForkJoinTask.rethrow(ex);
}
|
java
|
{
"resource": ""
}
|
q180039
|
ForkJoinPool.signalWork
|
test
|
final void signalWork(WorkQueue[] ws, WorkQueue q) {
long c; int sp, i; WorkQueue v; Thread p;
while ((c = ctl) < 0L) { // too few active
if ((sp = (int)c) == 0) { // no idle workers
if ((c & ADD_WORKER) != 0L) // too few workers
tryAddWorker(c);
break;
}
if (ws == null) // unstarted/terminated
break;
if (ws.length <= (i = sp & SMASK)) // terminated
break;
if ((v = ws[i]) == null) // terminating
break;
int vs = (sp + SS_SEQ) & ~INACTIVE; // next scanState
int d = sp - v.scanState; // screen CAS
long nc = (UC_MASK & (c + AC_UNIT)) | (SP_MASK & v.stackPred);
if (d == 0 && U.compareAndSwapLong(this, CTL, c, nc)) {
v.scanState = vs; // activate v
if ((p = v.parker) != null)
U.unpark(p);
break;
}
if (q != null && q.base == q.top) // no more work
break;
}
}
|
java
|
{
"resource": ""
}
|
q180040
|
ForkJoinPool.runWorker
|
test
|
final void runWorker(WorkQueue w) {
w.growArray(); // allocate queue
int seed = w.hint; // initially holds randomization hint
int r = (seed == 0) ? 1 : seed; // avoid 0 for xorShift
for (ForkJoinTask<?> t;;) {
if ((t = scan(w, r)) != null)
w.runTask(t);
else if (!awaitWork(w, r))
break;
r ^= r << 13; r ^= r >>> 17; r ^= r << 5; // xorshift
}
}
|
java
|
{
"resource": ""
}
|
q180041
|
ForkJoinPool.awaitWork
|
test
|
private boolean awaitWork(WorkQueue w, int r) {
if (w == null || w.qlock < 0) // w is terminating
return false;
for (int pred = w.stackPred, spins = SPINS, ss;;) {
if ((ss = w.scanState) >= 0)
break;
else if (spins > 0) {
r ^= r << 6; r ^= r >>> 21; r ^= r << 7;
if (r >= 0 && --spins == 0) { // randomize spins
WorkQueue v; WorkQueue[] ws; int s, j; AtomicLong sc;
if (pred != 0 && (ws = workQueues) != null &&
(j = pred & SMASK) < ws.length &&
(v = ws[j]) != null && // see if pred parking
(v.parker == null || v.scanState >= 0))
spins = SPINS; // continue spinning
}
}
else if (w.qlock < 0) // recheck after spins
return false;
else if (!Thread.interrupted()) {
long c, prevctl, parkTime, deadline;
int ac = (int)((c = ctl) >> AC_SHIFT) + (config & SMASK);
if ((ac <= 0 && tryTerminate(false, false)) ||
(runState & STOP) != 0) // pool terminating
return false;
if (ac <= 0 && ss == (int)c) { // is last waiter
prevctl = (UC_MASK & (c + AC_UNIT)) | (SP_MASK & pred);
int t = (short)(c >>> TC_SHIFT); // shrink excess spares
if (t > 2 && U.compareAndSwapLong(this, CTL, c, prevctl))
return false; // else use timed wait
parkTime = IDLE_TIMEOUT * ((t >= 0) ? 1 : 1 - t);
deadline = System.nanoTime() + parkTime - TIMEOUT_SLOP;
}
else
prevctl = parkTime = deadline = 0L;
Thread wt = Thread.currentThread();
U.putObject(wt, PARKBLOCKER, this); // emulate LockSupport
w.parker = wt;
if (w.scanState < 0 && ctl == c) // recheck before park
U.park(false, parkTime);
U.putOrderedObject(w, QPARKER, null);
U.putObject(wt, PARKBLOCKER, null);
if (w.scanState >= 0)
break;
if (parkTime != 0L && ctl == c &&
deadline - System.nanoTime() <= 0L &&
U.compareAndSwapLong(this, CTL, c, prevctl))
return false; // shrink pool
}
}
return true;
}
|
java
|
{
"resource": ""
}
|
q180042
|
ForkJoinPool.getSurplusQueuedTaskCount
|
test
|
static int getSurplusQueuedTaskCount() {
Thread t; ForkJoinWorkerThread wt; ForkJoinPool pool; WorkQueue q;
if (((t = Thread.currentThread()) instanceof ForkJoinWorkerThread)) {
int p = (pool = (wt = (ForkJoinWorkerThread)t).pool).
config & SMASK;
int n = (q = wt.workQueue).top - q.base;
int a = (int)(pool.ctl >> AC_SHIFT) + p;
return n - (a > (p >>>= 1) ? 0 :
a > (p >>>= 1) ? 1 :
a > (p >>>= 1) ? 2 :
a > (p >>>= 1) ? 4 :
8);
}
return 0;
}
|
java
|
{
"resource": ""
}
|
q180043
|
ForkJoinPool.commonSubmitterQueue
|
test
|
static WorkQueue commonSubmitterQueue() {
ForkJoinPool p = common;
int r = ThreadLocalRandomHelper.getProbe();
WorkQueue[] ws; int m;
return (p != null && (ws = p.workQueues) != null &&
(m = ws.length - 1) >= 0) ?
ws[m & r & SQMASK] : null;
}
|
java
|
{
"resource": ""
}
|
q180044
|
ForkJoinPool.externalHelpComplete
|
test
|
final int externalHelpComplete(CountedCompleter<?> task, int maxTasks) {
WorkQueue[] ws; int n;
int r = ThreadLocalRandomHelper.getProbe();
return ((ws = workQueues) == null || (n = ws.length) == 0) ? 0 :
helpComplete(ws[(n - 1) & r & SQMASK], task, maxTasks);
}
|
java
|
{
"resource": ""
}
|
q180045
|
ForkJoinPool.submit
|
test
|
public <T> ForkJoinTask<T> submit(ForkJoinTask<T> task) {
if (task == null)
throw new NullPointerException();
externalPush(task);
return task;
}
|
java
|
{
"resource": ""
}
|
q180046
|
ForkJoinPool.makeCommonPool
|
test
|
private static ForkJoinPool makeCommonPool() {
int parallelism = -1;
ForkJoinWorkerThreadFactory factory = null;
UncaughtExceptionHandler handler = null;
try { // ignore exceptions in accessing/parsing properties
String pp = System.getProperty
("java.util.concurrent.ForkJoinPool.common.parallelism");
String fp = System.getProperty
("java.util.concurrent.ForkJoinPool.common.threadFactory");
String hp = System.getProperty
("java.util.concurrent.ForkJoinPool.common.exceptionHandler");
String mp = System.getProperty
("java.util.concurrent.ForkJoinPool.common.maximumSpares");
if (pp != null)
parallelism = Integer.parseInt(pp);
if (fp != null)
factory = ((ForkJoinWorkerThreadFactory)ClassLoader.
getSystemClassLoader().loadClass(fp).newInstance());
if (hp != null)
handler = ((UncaughtExceptionHandler)ClassLoader.
getSystemClassLoader().loadClass(hp).newInstance());
if (mp != null)
commonMaxSpares = Integer.parseInt(mp);
} catch (Exception ignore) {
}
if (factory == null) {
if (System.getSecurityManager() == null)
factory = defaultForkJoinWorkerThreadFactory;
else // use security-managed default
factory = new InnocuousForkJoinWorkerThreadFactory();
}
if (parallelism < 0 && // default 1 less than #cores
(parallelism = Runtime.getRuntime().availableProcessors() - 1) <= 0)
parallelism = 1;
if (parallelism > MAX_CAP)
parallelism = MAX_CAP;
return new ForkJoinPool (parallelism, factory, handler, LIFO_QUEUE,
"ForkJoinPool.commonPool-worker-");
}
|
java
|
{
"resource": ""
}
|
q180047
|
ForkJoinTask.get
|
test
|
public final V get(long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException {
int s;
long nanos = unit.toNanos(timeout);
if (Thread.interrupted())
throw new InterruptedException();
if ((s = status) >= 0 && nanos > 0L) {
long d = System.nanoTime() + nanos;
long deadline = (d == 0L) ? 1L : d; // avoid 0
Thread t = Thread.currentThread();
if (t instanceof ForkJoinWorkerThread) {
ForkJoinWorkerThread wt = (ForkJoinWorkerThread)t;
s = wt.pool.awaitJoin(wt.workQueue, this, deadline);
}
else if ((s = ((this instanceof CountedCompleter) ?
ForkJoinPool.common.externalHelpComplete(
(CountedCompleter<?>)this, 0) :
ForkJoinPool.common.tryExternalUnpush(this) ?
doExec() : 0)) >= 0) {
long ns, ms; // measure in nanosecs, but wait in millisecs
while ((s = status) >= 0 &&
(ns = deadline - System.nanoTime()) > 0L) {
if ((ms = TimeUnit.NANOSECONDS.toMillis(ns)) > 0L &&
U.compareAndSwapInt(this, STATUS, s, s | SIGNAL)) {
synchronized (this) {
if (status >= 0)
wait(ms); // OK to throw InterruptedException
else
notifyAll();
}
}
}
}
}
if (s >= 0)
s = status;
if ((s &= DONE_MASK) != NORMAL) {
Throwable ex;
if (s == CANCELLED)
throw new CancellationException();
if (s != EXCEPTIONAL)
throw new TimeoutException();
if ((ex = getThrowableException()) != null)
throw new ExecutionException(ex);
}
return getRawResult();
}
|
java
|
{
"resource": ""
}
|
q180048
|
AJsonSerHelper.buildString
|
test
|
public static <E extends Throwable> String buildString (AStatement1<AJsonSerHelper, E> code) throws E {
final ByteArrayOutputStream baos = new ByteArrayOutputStream ();
code.apply (new AJsonSerHelper (baos));
return new String (baos.toByteArray (), UTF_8);
}
|
java
|
{
"resource": ""
}
|
q180049
|
AThreadPoolImpl.getStatistics
|
test
|
@Override public AThreadPoolStatistics getStatistics() {
final AWorkerThreadStatistics[] workerStats = new AWorkerThreadStatistics[localQueues.length];
for (int i=0; i<localQueues.length; i++) {
//noinspection ConstantConditions
workerStats[i] = localQueues[i].thread.getStatistics ();
}
final ASharedQueueStatistics[] sharedQueueStats = new ASharedQueueStatistics[sharedQueues.length];
for (int i=0; i<sharedQueues.length; i++) {
sharedQueueStats[i] = new ASharedQueueStatistics (sharedQueues[i].approximateSize());
}
return new AThreadPoolStatistics (workerStats, sharedQueueStats);
}
|
java
|
{
"resource": ""
}
|
q180050
|
AList.create
|
test
|
@SafeVarargs
public static <T> AList<T> create(T... elements) {
return create(Arrays.asList(elements));
}
|
java
|
{
"resource": ""
}
|
q180051
|
AList.reverse
|
test
|
public AList<T> reverse() {
AList<T> remaining = this;
AList<T> result = nil();
while(! remaining.isEmpty()) {
result = result.cons(remaining.head());
remaining = remaining.tail();
}
return result;
}
|
java
|
{
"resource": ""
}
|
q180052
|
ACollectionHelper.forAll
|
test
|
public static <T, E extends Throwable> boolean forAll(Iterable<T> coll, APredicate<? super T, E> pred) throws E {
for(T o: coll) {
if(!pred.apply(o)) {
return false;
}
}
return true;
}
|
java
|
{
"resource": ""
}
|
q180053
|
ACollectionHelper.foldLeft
|
test
|
public static <T, R, E extends Throwable> R foldLeft (Iterable<T> coll, R startValue, AFunction2<R, ? super T, R, E> f) throws E {
R result = startValue;
for (T e: coll) {
result = f.apply (result, e);
}
return result;
}
|
java
|
{
"resource": ""
}
|
q180054
|
ACollectionHelper.foldRight
|
test
|
public static <T, R, E extends Throwable> R foldRight (List<T> coll, R startValue, AFunction2<R, ? super T, R, E> f) throws E {
R result = startValue;
ListIterator<T> i = coll.listIterator(coll.size());
while ( i.hasPrevious() ) {
result = f.apply (result, i.previous());
}
return result;
}
|
java
|
{
"resource": ""
}
|
q180055
|
LocalQueue.push
|
test
|
void push (Runnable task) {
final long _base = UNSAFE.getLongVolatile (this, OFFS_BASE); // read base first (and only once)
final long _top = top;
if (_top == _base + mask) {
throw new RejectedExecutionExceptionWithoutStacktrace ("local queue overflow");
}
tasks[asArrayindex (_top)] = task;
// 'top' is only ever modified by the owning thread, so we need no CAS here. Storing 'top' with volatile semantics publishes the task and ensures that changes to the task
// can never overtake changes to 'top' wrt visibility.
UNSAFE.putLongVolatile (this, OFFS_TOP, _top+1);
// Notify pool only for the first added item per queue.
if (_top - _base <= 1) {
pool.onAvailableTask();
}
}
|
java
|
{
"resource": ""
}
|
q180056
|
AOption.fromNullable
|
test
|
public static <T> AOption<T> fromNullable(T nullable) {
return nullable != null ? some(nullable) : AOption.<T>none();
}
|
java
|
{
"resource": ""
}
|
q180057
|
ALongHashMap.fromKeysAndValues
|
test
|
public static <V> ALongHashMap<V> fromKeysAndValues(Iterable<? extends Number> keys, Iterable<V> values) {
final Iterator<? extends Number> ki = keys.iterator();
final Iterator<V> vi = values.iterator();
ALongHashMap<V> result = ALongHashMap.empty ();
while(ki.hasNext()) {
final Number key = ki.next();
final V value = vi.next();
result = result.updated(key.longValue (), value);
}
return result;
}
|
java
|
{
"resource": ""
}
|
q180058
|
AListMap.empty
|
test
|
@SuppressWarnings("unchecked")
public static <K,V> AListMap<K,V> empty(AEquality equality) {
if(equality == AEquality.EQUALS) return (AListMap<K, V>) emptyEquals;
if(equality == AEquality.IDENTITY) return (AListMap<K, V>) emptyIdentity;
return new AListMap<> (equality);
}
|
java
|
{
"resource": ""
}
|
q180059
|
AListMap.fromKeysAndValues
|
test
|
public static <K,V> AListMap<K,V> fromKeysAndValues(AEquality equality, Iterable<ATuple2<K,V>> elements) {
AListMap<K,V> result = empty(equality);
for(ATuple2<K,V> el: elements) {
result = result.updated(el._1, el._2);
}
return result;
}
|
java
|
{
"resource": ""
}
|
q180060
|
AListMap.fromKeysAndValues
|
test
|
public static <K,V> AListMap<K,V> fromKeysAndValues(AEquality equality, Iterable<K> keys, Iterable<V> values) {
final Iterator<K> ki = keys.iterator();
final Iterator<V> vi = values.iterator();
AListMap<K,V> result = empty (equality);
while(ki.hasNext()) {
final K key = ki.next();
final V value = vi.next();
result = result.updated(key, value);
}
return result;
}
|
java
|
{
"resource": ""
}
|
q180061
|
JavaUtilMapWrapper.keySet
|
test
|
@Override
public Set<K> keySet() {
return new AbstractSet<K>() {
@Override
public Iterator<K> iterator() {
return new Iterator<K>() {
final Iterator<AMapEntry<K,V>> it = inner.iterator();
@Override
public boolean hasNext() {
return it.hasNext();
}
@Override
public K next() {
return it.next().getKey ();
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
@Override
public int size() {
return inner.size();
}
};
}
|
java
|
{
"resource": ""
}
|
q180062
|
UriLoader.normalizeResourceName
|
test
|
private String normalizeResourceName(String name) {
if (name.startsWith("//")) {
return "classpath:" + name;
}
final int firstProtocol = name.indexOf("://");
final int secondProtocol = name.indexOf("://", firstProtocol + 1);
final int protocol = secondProtocol < 0 ? firstProtocol : secondProtocol;
final int endOfFirst = name.lastIndexOf("/", protocol);
if (endOfFirst >= 0) {
return name.substring(endOfFirst + 1);
}
return name;
}
|
java
|
{
"resource": ""
}
|
q180063
|
ValueTypeXmlAdapter.marshal
|
test
|
@Override
public String marshal(BoundType v) throws Exception {
Class<? extends Object> type = v.getClass();
if (!Types.isUserDefinedValueType(type)) {
throw new IllegalArgumentException("Type [" + type
+ "] must be an user-defined value type; "
+ "@XmlJavaTypeAdapter(ValueTypeXmlAdapter.class) "
+ "can be annotated to user-defined value type and field only");
}
Converter converter = ConvertUtils.lookup(type);
if ((converter != null && converter instanceof AbstractConverter)) {
String string = (String) ConvertUtils.convert(v, String.class);
if (string != null) {
return string;
}
}
return v.toString();
}
|
java
|
{
"resource": ""
}
|
q180064
|
FastCharBuffer.subSequence
|
test
|
public CharSequence subSequence(int start, int end) {
int len = end - start;
return new StringBuilder(len).append(toArray(start, len));
}
|
java
|
{
"resource": ""
}
|
q180065
|
BinarySearch.forList
|
test
|
public static <T extends Comparable> BinarySearch<T> forList(final List<T> list) {
return new BinarySearch<T>() {
@Override
@SuppressWarnings({"unchecked"})
protected int compare(int index, T element) {
return list.get(index).compareTo(element);
}
@Override
protected int getLastIndex() {
return list.size() - 1;
}
};
}
|
java
|
{
"resource": ""
}
|
q180066
|
BinarySearch.forList
|
test
|
public static <T> BinarySearch<T> forList(final List<T> list, final Comparator<T> comparator) {
return new BinarySearch<T>() {
@Override
@SuppressWarnings({"unchecked"})
protected int compare(int index, T element) {
return comparator.compare(list.get(index), element);
}
@Override
protected int getLastIndex() {
return list.size() - 1;
}
};
}
|
java
|
{
"resource": ""
}
|
q180067
|
EMail.send
|
test
|
public static Future<Boolean> send(Email email) {
try {
email = buildMessage(email);
if (GojaConfig.getProperty("mail.smtp", StringPool.EMPTY).equals("mock")
&& GojaConfig.getApplicationMode().isDev()) {
Mock.send(email);
return new Future<Boolean>() {
@Override
public boolean cancel(boolean mayInterruptIfRunning) {
return false;
}
@Override
public boolean isCancelled() {
return false;
}
@Override
public boolean isDone() {
return true;
}
@Override
public Boolean get() throws InterruptedException, ExecutionException {
return true;
}
@Override
public Boolean get(long timeout, final TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException {
return true;
}
};
}
email.setMailSession(getSession());
return sendMessage(email);
} catch (EmailException ex) {
throw new MailException("Cannot send email", ex);
}
}
|
java
|
{
"resource": ""
}
|
q180068
|
EMail.sendMessage
|
test
|
public static Future<Boolean> sendMessage(final Email msg) {
if (asynchronousSend) {
return executor.submit(new Callable<Boolean>() {
public Boolean call() {
try {
msg.setSentDate(new Date());
msg.send();
return true;
} catch (Throwable e) {
MailException me = new MailException("Error while sending email", e);
logger.error("The email has not been sent", me);
return false;
}
}
});
} else {
final StringBuffer result = new StringBuffer();
try {
msg.setSentDate(new Date());
msg.send();
} catch (Throwable e) {
MailException me = new MailException("Error while sending email", e);
logger.error("The email has not been sent", me);
result.append("oops");
}
return new Future<Boolean>() {
public boolean cancel(boolean mayInterruptIfRunning) {
return false;
}
public boolean isCancelled() {
return false;
}
public boolean isDone() {
return true;
}
public Boolean get() throws InterruptedException, ExecutionException {
return result.length() == 0;
}
public Boolean get(long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException {
return result.length() == 0;
}
};
}
}
|
java
|
{
"resource": ""
}
|
q180069
|
ApplicationRouter.bind
|
test
|
public void bind( final RouteBinding handler )
{
final Method method = handler.getMethod();
logger.info( "Using appId: {} and default version: {}", appAcceptId, defaultVersion );
List<String> versions = handler.getVersions();
if ( versions == null || versions.isEmpty() )
{
versions = Collections.singletonList( defaultVersion );
}
for ( final String version : versions )
{
final Set<Method> methods = new HashSet<>();
if ( method == Method.ANY )
{
for ( final Method m : Method.values() )
{
methods.add( m );
}
}
else
{
methods.add( method );
}
for ( final Method m : methods )
{
final BindingKey key = new BindingKey( m, version );
List<PatternRouteBinding> b = routeBindings.get( key );
if ( b == null )
{
b = new ArrayList<>();
routeBindings.put( key, b );
}
logger.info( "ADD: {}, Pattern: {}, Route: {}\n", key, handler.getPath(), handler );
addPattern( handler, b );
}
}
}
|
java
|
{
"resource": ""
}
|
q180070
|
ApplicationRouter.bind
|
test
|
public void bind( final FilterBinding handler )
{
final Method method = handler.getMethod();
final String path = handler.getPath();
logger.info( "Using appId: {} and default version: {}", appAcceptId, defaultVersion );
List<String> versions = handler.getVersions();
if ( versions == null || versions.isEmpty() )
{
versions = Collections.singletonList( defaultVersion );
}
for ( final String version : versions )
{
final Set<Method> methods = new HashSet<>();
if ( method == Method.ANY )
{
for ( final Method m : Method.values() )
{
methods.add( m );
}
}
else
{
methods.add( method );
}
for ( final Method m : methods )
{
final BindingKey key = new BindingKey( m, version );
logger.info( "ADD: {}, Pattern: {}, Filter: {}\n", key, path, handler );
List<PatternFilterBinding> allFilterBindings = this.filterBindings.get( key );
if ( allFilterBindings == null )
{
allFilterBindings = new ArrayList<>();
this.filterBindings.put( key, allFilterBindings );
}
boolean found = false;
for ( final PatternFilterBinding binding : allFilterBindings )
{
if ( binding.getPattern()
.pattern()
.equals( handler.getPath() ) )
{
binding.addFilter( handler );
found = true;
break;
}
}
if ( !found )
{
final PatternFilterBinding binding = new PatternFilterBinding( handler.getPath(), handler );
allFilterBindings.add( binding );
}
}
}
}
|
java
|
{
"resource": ""
}
|
q180071
|
HasAnyRolesTag.showTagBody
|
test
|
@Override
protected boolean showTagBody(String roleName) {
boolean hasAnyRole = false;
Subject subject = getSubject();
if (subject != null) {
// Iterate through roles and check to see if the user has one of the roles
for (String role : roleName.split(StringPool.COMMA)) {
if (subject.hasRole(role.trim())) {
hasAnyRole = true;
break;
}
}
}
return hasAnyRole;
}
|
java
|
{
"resource": ""
}
|
q180072
|
DataKit.getInt
|
test
|
public static int getInt(Long l) {
return (l == null || l > Integer.MAX_VALUE) ? 0 : l.intValue();
}
|
java
|
{
"resource": ""
}
|
q180073
|
Strs.removeDuplicateStrings
|
test
|
public static String[] removeDuplicateStrings(String[] array) {
if (ObjectKit.isEmpty(array)) {
return array;
}
Set<String> set = new TreeSet<String>();
for (String element : array) {
set.add(element);
}
return toStringArray(set);
}
|
java
|
{
"resource": ""
}
|
q180074
|
Strs.like
|
test
|
public static String like(String value) {
return StringPool.PERCENT + Strings.nullToEmpty(value) + StringPool.PERCENT;
}
|
java
|
{
"resource": ""
}
|
q180075
|
PeriodicService.doRun
|
test
|
public void doRun() throws Exception {
if (inProgress.compareAndSet(false,true)) {
try {
run();
} finally {
inProgress.set(false);
}
} else {
throw new IllegalStateException("Another run is already in progress");
}
}
|
java
|
{
"resource": ""
}
|
q180076
|
SecurityKit.login
|
test
|
public static <T extends Model> boolean login(T user, String password, boolean remember
, HttpServletRequest request, HttpServletResponse response) {
boolean matcher =
SecurityKit.checkPassword(user.getStr("salt"), user.getStr("password"), password);
if (matcher) {
SecurityKit.setLoginMember(request, response, user, remember);
}
return matcher;
}
|
java
|
{
"resource": ""
}
|
q180077
|
SecurityKit.getLoginWithDb
|
test
|
public static <T extends Model> T getLoginWithDb(HttpServletRequest req
, HttpServletResponse response
, Function<Long, T> function) {
T loginUser = getLoginUser(req);
if (loginUser == null) {
//从Cookie中解析出用户id
CookieUser cookie_user = getUserFromCookie(req);
if (cookie_user == null) return null;
T user = CacheKit.get(LOGIN_CACHE_SESSION, LOGIN_CACHE_SESSION + cookie_user.getId());
if (user == null) {
user = function.apply(cookie_user.getId());
CacheKit.put(LOGIN_CACHE_SESSION, LOGIN_CACHE_SESSION + cookie_user.getId(), user);
}
// 用户密码和cookie中存储的密码一致
if (user != null && StringUtils.equalsIgnoreCase(user.getStr("password"),
cookie_user.getPassword())) {
setLoginMember(req, response, user, true);
return user;
} else {
return null;
}
} else {
return loginUser;
}
}
|
java
|
{
"resource": ""
}
|
q180078
|
SecurityKit.getLoginUser
|
test
|
public static <T extends Model> T getLoginUser(HttpServletRequest req) {
return (T) req.getSession().getAttribute(LOGIN_SESSION_KEY);
}
|
java
|
{
"resource": ""
}
|
q180079
|
SecurityKit.checkPassword
|
test
|
public static boolean checkPassword(String salt, String password, String plainPassword) {
byte[] saltHex = EncodeKit.decodeHex(salt);
byte[] hashPassword =
DigestsKit.sha1(plainPassword.getBytes(), saltHex, EncodeKit.HASH_INTERATIONS);
return StringUtils.equals(EncodeKit.encodeHex(hashPassword), password);
}
|
java
|
{
"resource": ""
}
|
q180080
|
SecurityKit.saveMemberInCookie
|
test
|
public static <T extends Model> void saveMemberInCookie(T user, boolean save,
HttpServletRequest request, HttpServletResponse response) {
String new_value =
getLoginKey(user, Requests.remoteIP(request), request.getHeader("user-agent"));
int max_age = save ? MAX_AGE : -1;
Requests.deleteCookie(request, response, COOKIE_LOGIN, true);
Requests.setCookie(request, response, COOKIE_LOGIN, new_value, max_age, true);
}
|
java
|
{
"resource": ""
}
|
q180081
|
SecurityKit.getLoginKey
|
test
|
private static <T extends Model> String getLoginKey(T user, String ip, String user_agent) {
return encrypt(String.valueOf(user.getNumber(StringPool.PK_COLUMN)) + '|'
+ user.getStr("password") + '|' + ip + '|' + ((user_agent == null) ? 0
: user_agent.hashCode()) + '|' + System.currentTimeMillis());
}
|
java
|
{
"resource": ""
}
|
q180082
|
SecurityKit.userForCookie
|
test
|
private static CookieUser userForCookie(String uuid, HttpServletRequest request) {
if (StringUtils.isBlank(uuid)) {
return null;
}
String ck = decrypt(uuid);
final String[] items = StringUtils.split(ck, '|');
if (items.length == 5) {
String ua = request.getHeader("user-agent");
int ua_code = (ua == null) ? 0 : ua.hashCode();
int old_ua_code = Integer.parseInt(items[3]);
if (ua_code == old_ua_code) {
return new CookieUser(NumberUtils.toLong(items[0], -1L), items[1], false);
}
}
return null;
}
|
java
|
{
"resource": ""
}
|
q180083
|
Forward.to
|
test
|
public void to(WebContext context) {
HttpServletRequest request = context.request();
HttpServletResponse response = context.response();
try {
request.getRequestDispatcher(path).forward(request, response);
} catch (ServletException e) {
throw new UncheckedException(e);
} catch (IOException e) {
throw new UncheckedException(e);
}
}
|
java
|
{
"resource": ""
}
|
q180084
|
FileRenamePolicyWrapper.appendFileSeparator
|
test
|
public String appendFileSeparator(String path) {
if (null == path) {
return File.separator;
}
// add "/" prefix
if (!path.startsWith(StringPool.SLASH) && !path.startsWith(StringPool.BACK_SLASH)) {
path = File.separator + path;
}
// add "/" postfix
if (!path.endsWith(StringPool.SLASH) && !path.endsWith(StringPool.BACK_SLASH)) {
path = path + File.separator;
}
return path;
}
|
java
|
{
"resource": ""
}
|
q180085
|
Requests.param
|
test
|
public static long param(HttpServletRequest request, String param, long defaultValue) {
return NumberUtils.toLong(request.getParameter(param), defaultValue);
}
|
java
|
{
"resource": ""
}
|
q180086
|
Logger.debug
|
test
|
public static void debug(String message, Object... args) {
if (recordCaller) {
LoggerFactory.getLogger(getCallerClassName()).debug(message, args);
} else {
slf4j.debug(message, args);
}
}
|
java
|
{
"resource": ""
}
|
q180087
|
Logger.getCallerInformations
|
test
|
static CallInfo getCallerInformations(int level) {
StackTraceElement[] callStack = Thread.currentThread().getStackTrace();
StackTraceElement caller = callStack[level];
return new CallInfo(caller.getClassName(), caller.getMethodName());
}
|
java
|
{
"resource": ""
}
|
q180088
|
CharKit.toSimpleByteArray
|
test
|
public static byte[] toSimpleByteArray(char[] carr) {
byte[] barr = new byte[carr.length];
for (int i = 0; i < carr.length; i++) {
barr[i] = (byte) carr[i];
}
return barr;
}
|
java
|
{
"resource": ""
}
|
q180089
|
CharKit.toSimpleByteArray
|
test
|
public static byte[] toSimpleByteArray(CharSequence charSequence) {
byte[] barr = new byte[charSequence.length()];
for (int i = 0; i < barr.length; i++) {
barr[i] = (byte) charSequence.charAt(i);
}
return barr;
}
|
java
|
{
"resource": ""
}
|
q180090
|
CharKit.toSimpleCharArray
|
test
|
public static char[] toSimpleCharArray(byte[] barr) {
char[] carr = new char[barr.length];
for (int i = 0; i < barr.length; i++) {
carr[i] = (char) (barr[i] & 0xFF);
}
return carr;
}
|
java
|
{
"resource": ""
}
|
q180091
|
CharKit.toAsciiByteArray
|
test
|
public static byte[] toAsciiByteArray(CharSequence charSequence) {
byte[] barr = new byte[charSequence.length()];
for (int i = 0; i < barr.length; i++) {
char c = charSequence.charAt(i);
barr[i] = (byte) ((int) (c <= 0xFF ? c : 0x3F));
}
return barr;
}
|
java
|
{
"resource": ""
}
|
q180092
|
LocaleKit.lookupLocaleData
|
test
|
protected static LocaleData lookupLocaleData(String code) {
LocaleData localeData = locales.get(code);
if (localeData == null) {
String[] data = decodeLocaleCode(code);
localeData = new LocaleData(new Locale(data[0], data[1], data[2]));
locales.put(code, localeData);
}
return localeData;
}
|
java
|
{
"resource": ""
}
|
q180093
|
Job.in
|
test
|
public Promise<V> in(int seconds) {
final Promise<V> smartFuture = new Promise<V>();
JobsPlugin.executor.schedule(getJobCallingCallable(smartFuture), seconds, TimeUnit.SECONDS);
return smartFuture;
}
|
java
|
{
"resource": ""
}
|
q180094
|
Images.crop
|
test
|
public static void crop(File originalImage, File to, int x1, int y1, int x2, int y2) {
try {
BufferedImage source = ImageIO.read(originalImage);
String mimeType = "image/jpeg";
if (to.getName().endsWith(".png")) {
mimeType = "image/png";
}
if (to.getName().endsWith(".gif")) {
mimeType = "image/gif";
}
int width = x2 - x1;
int height = y2 - y1;
// out
BufferedImage dest = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Image croppedImage = source.getSubimage(x1, y1, width, height);
Graphics graphics = dest.getGraphics();
graphics.setColor(Color.WHITE);
graphics.fillRect(0, 0, width, height);
graphics.drawImage(croppedImage, 0, 0, null);
ImageWriter writer = ImageIO.getImageWritersByMIMEType(mimeType).next();
ImageWriteParam params = writer.getDefaultWriteParam();
writer.setOutput(new FileImageOutputStream(to));
IIOImage image = new IIOImage(dest, null, null);
writer.write(null, image, params);
writer.dispose();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
|
java
|
{
"resource": ""
}
|
q180095
|
Invoker.invoke
|
test
|
public static Future<?> invoke(final Invocation invocation, long millis) {
return executor.schedule(invocation, millis, TimeUnit.MILLISECONDS);
}
|
java
|
{
"resource": ""
}
|
q180096
|
Invoker.invokeInThread
|
test
|
public static void invokeInThread(DirectInvocation invocation) {
boolean retry = true;
while (retry) {
invocation.run();
if (invocation.retry == null) {
retry = false;
} else {
try {
if (invocation.retry.task != null) {
invocation.retry.task.get();
} else {
Thread.sleep(invocation.retry.timeout);
}
} catch (Exception e) {
throw new UnexpectedException(e);
}
retry = true;
}
}
}
|
java
|
{
"resource": ""
}
|
q180097
|
RestOperationsFactory.getRestOperations
|
test
|
@Nonnull
public RestOperations getRestOperations() {
final HttpClientBuilder builder = HttpClientBuilder.create();
initDefaultHttpClientBuilder(builder);
httpRequestFactory = new HttpComponentsClientHttpRequestFactory(builder.build());
final RestTemplate restTemplate = new RestTemplate(messageConverters);
restTemplate.setRequestFactory(httpRequestFactory);
return restTemplate;
}
|
java
|
{
"resource": ""
}
|
q180098
|
Controller.renderAjaxError
|
test
|
protected void renderAjaxError(String error, Exception e) {
renderJson(AjaxMessage.error(error, e));
}
|
java
|
{
"resource": ""
}
|
q180099
|
Controller.renderAjaxForbidden
|
test
|
protected <T> void renderAjaxForbidden(String message, T data) {
renderJson(AjaxMessage.forbidden(message, data));
}
|
java
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.