method_id
stringlengths 36
36
| cyclomatic_complexity
int32 0
9
| method_text
stringlengths 14
410k
|
|---|---|---|
191c6725-0d7b-471f-b2b7-8f72bbc4843a
| 2
|
public void addMessage(String message) {
boolean scrollDown = isChatAtBottom();
if (!isFirst)
textArea.append("\n" + message);
else {
textArea.append(message);
isFirst = false;
}
if (scrollDown) {
moveChat2Bottom();
}
}
|
276f75ca-548c-4895-a3f2-fef72e794140
| 4
|
@Override
public void startListening() {
if (this.state == ServerState.Running) return;
this.state = ServerState.Running;
this.serverRunner = new Thread(new Runnable() {
@Override
public void run() {
while (state == ServerState.Running && !serverRunner.isInterrupted())
{
try
{
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
});
this.serverRunner.start();
}
|
ed2319eb-89b2-44d5-8495-d4c7db9f01a5
| 1
|
public void makeDeclaration(Set done) {
if (constant != null) {
constant.makeDeclaration(done);
constant = constant.simplify();
}
}
|
0549ca8e-440f-47d8-9ccc-610bc9a26280
| 3
|
private synchronized ByteBuffer unwrap() throws SSLException {
int rem;
do {
rem = inData.remaining();
engineResult = sslEngine.unwrap( inCrypt, inData );
engineStatus = engineResult.getStatus();
} while ( engineStatus == SSLEngineResult.Status.OK && ( rem != inData.remaining() || engineResult.getHandshakeStatus() == HandshakeStatus.NEED_UNWRAP ) );
inData.flip();
return inData;
}
|
6136418a-bd13-4a49-a6ed-04de5be29050
| 7
|
public int availableMissile(){
mCurTime=System.nanoTime();
if(missileTime<=1500000000l){
if(mSparks){
if(index==3){
temp = User.getMissile1Pos();
rot.rotX(Math.PI/2);
temp.mul(rot);
new WrapParticles(75,20,1,init,last,10000,temp,sceneBG).run();
}
if(index==4){
temp = User.getMissile2Pos();
rot.rotX(-Math.PI/2);
temp.mul(rot);
new WrapParticles(75,20,1,init,last,10000,temp,sceneBG).run();
}
mSparks = false;
}
}
else {
if(mCurTime - mLastTime < mStartHeat){
missileTime -= (mStartHeat - (mCurTime - mLastTime));
bars.updateMissile(missileTime);
}
mLastTime = mCurTime;
mSparks = true;
for(int i=0;i<noMissiles;i++)
if(missiles[i].getFinishedShot())
return i;
}
return -1;
}
|
fece87c0-6545-414d-8995-1f722e86eb5c
| 3
|
private void init(Stage primaryStage) {
Group root = new Group();
Scene scene = new Scene(root);
primaryStage.setResizable(true);
primaryStage.setScene(scene);
primaryStage.setTitle("Draw App");
final MainWindow mainWindow = new MainWindow();
root.getChildren().add(mainWindow);
Reader reader;
if (TEST) {
reader = new StringReader(TEST_PARSE);
} else {
reader = new InputStreamReader(System.in);
}
final JavaFxParser parser = new JavaFxParser(reader, mainWindow,
primaryStage);
mainWindow.getNextStepButton().setOnAction(
new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent arg0) {
parser.singleStepParse();
}
});
mainWindow.getCompleteButton().setOnAction(
new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent arg0) {
parser.parse();
}
});
mainWindow.getSnapshotButton().setOnAction(
new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent arg0) {
int width = (int) mainWindow.getImagePanel().getWidth();
int height = (int) mainWindow.getImagePanel()
.getHeight();
WritableImage writableImage = new WritableImage(width,
height);
Image image = mainWindow.getImagePanel().snapshot(
SnapshotParametersBuilder.create().build(),
writableImage);
try {
// TODO
File file = new File(".");
for (File f : file.listFiles()) {
System.out.println(f.getAbsolutePath());
}
ImageIO.write(
SwingFXUtils.fromFXImage(image, null),
"png", new File("screenshot.png"));
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
|
be5f1ed4-8e1e-4c51-af2f-3da801ccc3c9
| 5
|
private int determineCurrentFrame() {
boolean animationJustCompleted = false;
if (animinationStartTime == -1)
animinationStartTime = System.nanoTime() / 1000000;
long currentTime = System.nanoTime() / 1000000;
// Check if the animation has exceeded its specified overall duration
if (playCount > 0) {
if (currentTime - animinationStartTime
> (long) playCount * animationPeriodms) {
animationJustCompleted = true;
playCount = 0;
// Notify any observers that the animation has completed
setChanged();
notifyObservers("AnimationCompleted");
}
}
// If the sequence is not animation then return the homeframe, unless
// the animation was stopped as part of this call, in which case return
// the last image within the sequence (this ensures that an animation
// will always finish by displaying the last image in the sequence).
if (playCount == 0) {
if (animationJustCompleted) {
currentFrame = images.length - 1;
} else {
currentFrame = homeFrame;
}
} else {
// Determine the correct image to display within the sequence based
// upon the elapsed time from the start of the animation.
long timeIntoAniminationPeriod
= (currentTime - animinationStartTime) % animationPeriodms;
currentFrame = (int) ( (timeIntoAniminationPeriod * (long)images.length )
/ animationPeriodms );
}
return currentFrame;
}
|
3d834f01-1351-48b8-88ee-106728d0594e
| 9
|
public ValueRepresentation evaluateVariable(XPathContext context) throws XPathException {
Controller controller = context.getController();
Bindery b = controller.getBindery();
boolean wasSupplied;
try {
wasSupplied = b.useGlobalParameter(
getVariableQName(), getSlotNumber(), getRequiredType(), context);
} catch (XPathException e) {
e.setLocator(this);
throw e;
}
ValueRepresentation val = b.getGlobalVariableValue(this);
if (wasSupplied || val!=null) {
return val;
} else {
if (isRequiredParam()) {
XPathException e = new XPathException("No value supplied for required parameter $" +
getVariableQName().getDisplayName());
e.setXPathContext(context);
e.setLocator(getSourceLocator());
e.setErrorCode(isXSLT() ? "XTDE0050" : "XPDY0002");
throw e;
} else if (isImplicitlyRequiredParam()) {
XPathException e = new XPathException("A value must be supplied for parameter $" +
getVariableQName().getDisplayName() +
" because there is no default value for the required type");
e.setXPathContext(context);
e.setLocator(getSourceLocator());
e.setErrorCode("XTDE0610");
throw e;
}
// This is the first reference to a global variable; try to evaluate it now.
// But first set a flag to stop looping. This flag is set in the Bindery because
// the VariableReference itself can be used by multiple threads simultaneously
try {
b.setExecuting(this, true);
ValueRepresentation value = getSelectValue(context);
b.defineGlobalVariable(this, value);
b.setExecuting(this, false);
return value;
} catch (XPathException err) {
b.setExecuting(this, false);
if (err instanceof XPathException.Circularity) {
XPathException e = new XPathException("Circular definition of parameter " +
getVariableQName().getDisplayName());
e.setXPathContext(context);
e.setErrorCode(isXSLT() ? "XTDE0640" : "XQST0054");
// Detect it more quickly the next time (in a pattern, the error is recoverable)
select = new ErrorExpression(e);
throw e;
} else {
throw err;
}
}
}
}
|
4063fcaa-0325-4940-8634-a5b2167c8154
| 2
|
public DistanceBall(Ball b, double referencePoint) {
double xVelocity = b.getXVelocity();
double yVelocity = b.getYVelocity();
double centerX = b.getCenterX();
double centerY = b.getCenterY();
double radius = b.getRadius();
this.numberMoves = Math.abs((int) Math.floor(distance(referencePoint, xVelocity, centerX, radius) / xVelocity));
double adjustedHeight = centerY + yVelocity * numberMoves;
if (adjustedHeight < 0) {
adjustedHeight *= -1;
} else if (adjustedHeight > Constants.stageHeight) {
adjustedHeight = Constants.stageHeight - (adjustedHeight - Constants.stageHeight);
}
this.adjustedHeight = adjustedHeight;
}
|
94e5c9ee-912e-4c5f-9238-26effbf5c685
| 2
|
public static Language createNew(Connection con, String id, String name, String persPron)
{
Language lang = null;
try
{
PreparedStatement ps = con.prepareStatement(
"INSERT INTO " + tableInfo.tableName
+ " VALUES (?, ?, ?)",
Statement.RETURN_GENERATED_KEYS);
ps.setString(1, id);
ps.setString(2, name);
ps.setString(3, persPron);
ps.executeUpdate();
ps.close();
lang = new Language(con, id);
}
catch(SQLException sqle)
{
if (sqle.getSQLState().equals("42X05")) // table does not exist
{
DBObject.createTable(con, tableInfo);
return Language.createNew(con, id, name, persPron);
}
}
return lang;
}
|
ccfa31bf-7049-4806-88c3-c407a9a3ee3e
| 8
|
public ReflectionCache(Class<?> serviceInterface) {
if (!serviceInterface.isInterface()) {
throw new ClassFormatError(String.format("Class '%s' is not an interface!", serviceInterface.getName()));
}
Method[] methods = serviceInterface.getMethods();
methodIdToName = new HashMap<Short, String>(methods.length);
methodIdToMethod = new HashMap<Short, Method>(methods.length);
methodNameToId = new HashMap<String, Short>(methods.length);
for (Method method : methods) {
//Checking for prelogin annotation
RpcAfterConnect afterConnectAnnotation = method.getAnnotation(RpcAfterConnect.class);
if (afterConnectAnnotation != null) {
this.afterConnectMethod = method;
}
//Getting methodId
RpcMethod methodIdAnnotation = method.getAnnotation(RpcMethod.class);
if (methodIdAnnotation != null) {
Short methodId = methodIdAnnotation.methodId();
//Reading parameter types and their schemas
Class<?>[] parameterTypes = method.getParameterTypes();
for (Class<?> parameterType : parameterTypes) {
//Caching schemas. No need to store them
RuntimeSchema.getSchema(parameterType.getClass());
}
//Putting everything to collections
methodIdToMethod.put(methodId, method);
methodIdToName.put(methodId, method.getName());
methodNameToId.put(method.getName(), methodId);
}
}
}
|
08b98cb2-58d0-4ca8-98f0-0a42f1d28ce1
| 9
|
public int translate(int va, int size, boolean inst, boolean priv, boolean read) {
int paL1, entryL1, typeL1, pa;
boolean validAlign;
if (isFault()) {
//フォルト状態がクリアされず残っている
throw new IllegalStateException("Fault status not cleared.");
}
//TODO: アドレス以外の条件がある?
/*if (!inst && 0x00 <= va && va <= 0x1f) {
//ベクタ例外
faultMMU(FS_VECT, 0, va, inst, priv, read,
"MMU vector");
return 0;
}*/
if (!isEnable()) {
//MMU 無効なので変換しない
return va;
}
validAlign = (va & (size - 1)) == 0;
if (isAlignmentCheck() && !validAlign) {
//アラインメントフォルト
faultMMU(FS_ALIGN1, 0, va, inst, priv, read,
String.format("MMU align, size:%d", size));
return 0;
}
paL1 = getL1Address(va);
if (!getCPU().tryRead_a32(paL1, 4)) {
//変換時の外部アボート、第1レベル
faultMMU(FS_TRANS_L1, 0, va, inst, priv, read,
String.format("MMU trans L1, paL1:0x%08x", paL1));
return 0;
}
entryL1 = getCPU().read32_a32(paL1);
typeL1 = BitOp.getField32(entryL1, 0, 2);
switch (typeL1) {
case 0:
//フォルト
//変換フォルト、セクション
faultMMU(FS_TRANS_SEC, 0, va, inst, priv, read,
String.format("MMU trans sec, paL1:0x%08x, entryL1:0x%08x",
paL1, entryL1));
return 0;
case 1:
//概略ページテーブル
pa = translateCoarse(va, inst, priv, read, entryL1);
break;
case 2:
//セクション
pa = translateSection(va, inst, priv, read, entryL1);
break;
case 3:
//詳細ページテーブル
pa = translateFine(va, inst, priv, read, entryL1);
break;
default:
throw new IllegalArgumentException("Unknown L1 table " +
String.format("paL1:0x%08x, entryL1:0x%08x, typeL1:%d.",
paL1, entryL1, typeL1));
}
return pa;
}
|
7f44452a-1583-408e-abb5-2524d5d78bae
| 1
|
@Override
public void first (String host, String db_name, String user, String pw) {
try {
this.host = host;
this.db_name = db_name;
this.user = user;
this.pw = pw;
connect();
} catch (SQLException ex) {
Error_Frame.Error(ex.toString());
}
}
|
df349747-6a9c-4193-9e49-5735a30ec33b
| 9
|
public void playerPlays(Card card) {
if (card == null) {
/* 1) den exei na paiksei kai dn exei traviksei karta
* 2) den exei na paiksei kai exei traviksei karta
* 3) katw einai 7 ari kai den exei 7 na paiksei = pairnei 2
* 4) katw einai 7 ari alla einai apo ton proigoumeno paikti
* 5) katw einai 7 ari kai den exei genika na paiksei = pairnei 1
* 6) katw einai 7 ari kai den exei genika na paiksei k exei idi parei = xanei tin seira t
*
*/
if ((this.openedCards.getLastCard().getRank().equals(Rank.SEVEN)) && (CardNo7.isMustTakeCards())) {//an einai gia ton eauto tou
for (int i = 0; i < CardNo7.getNCardsAll(); i++) {
this.playerDrawsCard();
}
CardNo7.makeNCardsAllNormal();
return;
}
if (this.players.get(CurrentPlayer).getDrawCard()) { //an exei idi traviksei karta
this.players.get(CurrentPlayer).setDrawCard(false);
this.setCurrentPlayer();// paizei o epomenos
} else {
this.playerDrawsCard();
this.players.get(CurrentPlayer).setDrawCard(true);
}
} else {
this.players.get(CurrentPlayer).setDrawCard(false);
this.openedCards.openCard(card);
this.tmpCard.setRank(card.getRank());
this.tmpCard.setSuit(card.getSuit());
this.tmpCard.setPic(card.getPic());
switch (card.getRank()) {
case ACE:
this.setCurrentPlayer();
break;
case EIGHT:
break;
case NINE:
checkIfGameIsOver();
this.setCurrentPlayer();//o epomenos xanei ti seira toy
this.setCurrentPlayer();//paizei o methepomenos
break;
case SEVEN:
checkIfGameIsOver();
CardNo7.increaseNCardsAll();
this.setCurrentPlayer();
break;
default:
checkIfGameIsOver();
this.setCurrentPlayer();
}
//TODO elegxos an einai end of game o computer player den bgainei pote nikitis akoma kai an petaxei oles tis kares toy
//TODO an o xristis rixei 8 tleytaia karta den bgainei. prepei na travixei mia
}
}
|
770cfcc0-f9c8-4370-9dbc-da8c6785ea1a
| 4
|
public List getIPEntriesDebug(String s) {
List<IPEntry> ret = new ArrayList<IPEntry>();
long endOffset = ipEnd + 4;
for (long offset = ipBegin + 4; offset <= endOffset; offset += IP_RECORD_LENGTH) {
// 读取结束IP偏移
long temp = readLong3(offset);
// 如果temp不等于-1,读取IP的地点信息
if (temp != -1) {
IPLocation ipLoc = getIPLocation(temp);
// 判断是否这个地点里面包含了s子串,如果包含了,添加这个记录到List中,如果没有,继续
if (ipLoc.getCountry().indexOf(s) != -1
|| ipLoc.getArea().indexOf(s) != -1) {
IPEntry entry = new IPEntry();
entry.country = ipLoc.getCountry();
entry.area = ipLoc.getArea();
// 得到起始IP
readIP(offset - 4, b4);
entry.beginIp = Util.getIpStringFromBytes(b4);
// 得到结束IP
readIP(temp, b4);
entry.endIp = Util.getIpStringFromBytes(b4);
// 添加该记录
ret.add(entry);
}
}
}
return ret;
}
|
c2a64947-fb90-4a8d-af5a-e2eb800c655f
| 9
|
@Override
public Status live() {
super.live();
// Insects will only act every ANTACTIONDELAY milliseconds
if (this.getTimeManager().getCurrentDate().getTime() - this.lastTime < Consts.ANTACTIONDELAY
&& this.lastTime != 0) {
return null;
}
InsectBody body = this.getBody();
//If their is no body, the agent is waiting to die
if (body == null) {
return null;
}
// If the side is defeated
if (body.getSide().isDefeated()) {
// Stop all
return null;
}
// If an action is already planned, wait for it to be resolved
if (body.getAction() != null) {
return null;
}
// Update the relative and current position
updatePositions(body);
if (eatIfNeed(body)) {
return null;
}
if (dropPheromoneIfNeeded()) {
return null;
}
switch (this.currentBehaviour) {
case GO_HOME:
goHome();
break;
case PATROL:
patrol();
break;
default:
generateWanderMovement();
break;
}
doNextMovement(body);
// Success
return null;
}
|
fa0cf245-00dd-4c01-bb15-23f1d3f540bc
| 4
|
public boolean isValid() {
if (this.port == null || this.port.isEmpty()) {
return false;
}
if (this.ip == null || this.ip.isEmpty()) {
return false;
}
return true;
}
|
12b9037e-60d0-4cc3-bb65-efd83d81e617
| 3
|
public int[] PlusOne(int[] digits){
int carry =1,sum=0;
int[] result = new int[digits.length];
for(int i = digits.length -1; i>=0; i--){
sum = carry+digits[i];
carry = sum/10;
result[i] = sum%10;
}
if(carry == 1){
int[] plusone = new int[digits.length+1];
plusone[0] = carry; int i = 1;
for(int a: result){
plusone[i++] = a;
}
return plusone;
}else{
return result;
}
}
|
ca0e791b-1a0a-43f6-bf9a-436cb4ad305d
| 1
|
double acceptanceProbability(int energy, int newEnergy, double temperature){
if(newEnergy < energy) return 1;
return Math.exp((energy - newEnergy) / temperature);
}
|
c6486a57-18f8-4891-ac1b-a7500d63c35c
| 6
|
private static void add(Map<Class<?>, Class<?>> forward,
Map<Class<?>, Class<?>> backward, Class<?> key, Class<?> value) {
forward.put(key, value);
backward.put(value, key);
}
|
fc89f555-82f2-4e85-ba50-acb0c370104c
| 3
|
String commandLineStr(boolean splitLines) {
StringBuilder argsList = new StringBuilder();
argsList.append("SnpEff " + command + " ");
int size = argsList.length();
for (String arg : args) {
argsList.append(arg);
size += arg.length();
if (splitLines && (size > COMMAND_LINE_WIDTH)) {
argsList.append(" \n");
size = 0;
} else {
argsList.append(" ");
size++;
}
}
return argsList.toString();
}
|
551398ee-fa43-4a69-ba59-10aa8f8009eb
| 7
|
private static void parseFiles(final Map<String, String> args, final CommandLineArguments result)
throws ParseException
{
if (args.containsKey("binary"))
{
result.binary = Boolean.parseBoolean(args.get("binary"));
}
if (args.containsKey("dir"))
{
final File directory = new File(args.get("dir"));
if (directory.exists() && directory.isDirectory())
{
result.directory = directory;
}
}
final String tmpFilename = "ldcr_graph_"
+ new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss").format(new Date());
result.output = new File(result.directory, tmpFilename);
if (args.containsKey("output"))
{
final File outFile = new File(result.directory, args.get("output"));
if (outFile.exists())
{
throw new ParseException("Output file already exists: " + outFile.getAbsolutePath());
}
result.output = outFile;
}
/*
* If a parameter file is processed, then the output files have to
* be numbered.
*/
if (args.containsKey("positionInFile"))
{
final int pos = Integer.parseInt(args.get("positionInFile"));
result.output = new File(result.output.getAbsolutePath() + "_"
+ String.format("%04d", (pos + 1)) + ".graphj");
}
else
{
result.output = new File(result.output.getAbsolutePath() + ".graphj");
}
}
|
376ff0f3-cdb8-4b40-bf4c-8a1ecd803da6
| 9
|
public boolean hasCycles() {
// check for cycles
boolean[] bDone = new boolean[m_nNodes];
for (int iNode = 0; iNode < m_nNodes; iNode++) {
// find a node for which all parents are 'done'
boolean bFound = false;
for (int iNode2 = 0; !bFound && iNode2 < m_nNodes; iNode2++) {
if (!bDone[iNode2]) {
boolean bHasNoParents = true;
for (int iParent = 0; iParent < m_nNodes; iParent++) {
if (m_bits[iParent + iNode2 * m_nNodes] && !bDone[iParent]) {
bHasNoParents = false;
}
}
if (bHasNoParents) {
bDone[iNode2] = true;
bFound = true;
}
}
}
if (!bFound) {
return true;
}
}
return false;
} // hasCycles
|
07df811a-e446-468e-848a-dad5fd8a1682
| 7
|
public void searchForSMClasses(Class clazzLocation, Field[] lof){
//System.out.println("NOW LOOKING AT:" + clazz.getName());
JSONObject jObj = new JSONObject();
for(Field f: lof){
//Get generic type.
Class genericType = getFieldGenericType(f);
//If SM object as a generic type.
if(!genericType.getCanonicalName().endsWith("Boolean") && !genericType.getName().startsWith("java")){
listOfClasses.add(genericType);
Field[] SMInGenericClass = getAllFields(genericType);
JSONObject jsonGeneric = new JSONObject();
jsonGeneric.put("name", f.getGenericType().toString());
jsonGeneric.put("replace", genericType.getName());
jObj.put(f.getName(),jsonGeneric);
generateJSON(genericType);
}
//If regular SM object.
else if(!f.getType().isPrimitive()
&& !(f.getType().getName().startsWith("java."))
&& !listOfClasses.contains(f.getType())){
listOfClasses.add(f.getType());
Class clazz = f.getType();
Field[] SMClasses = getAllFields(f.getType());
JSONObject jsonObj = new JSONObject();
jsonObj.put("Name", f.getGenericType().toString());
jsonObj.put("replace", f.getName());
jObj.put(f.getName(), jsonObj);
generateJSON(f.getType());
}
//Else
else{
jObj.put(f.getName(), f.getGenericType().toString());
}
}
String JSONClass = this.location + clazzLocation.getName() + ".json";
//write the JSONObject to a file.
try {
FileWriter file = new FileWriter(JSONClass);
file.write(jObj.toJSONString());
file.flush();
file.close();
} catch (IOException e) {
e.printStackTrace();
}
}
|
47bcfcc7-571d-4179-a232-69dcde8a1d2f
| 2
|
public byte[] toByteArray(){
try{
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutput out = null;
out = new ObjectOutputStream(bos);
out.writeObject(this);
byte[] yourBytes = bos.toByteArray();
try{
bos.close();
out.close();
}catch(Exception e){System.out.println("A Memory Leak Has Happened!");e.printStackTrace();}
return yourBytes;
}catch(Exception e){
return null;
}
}
|
f0ce776a-7716-4a34-8403-e59a6b1a33cb
| 8
|
@SuppressWarnings({"unchecked"})
protected void doEncodeAll(FacesContext ctx) throws IOException {
String strValue = null;
try {
if (getSubject() != null) {
// Get the principal to print out
Object principal;
if (type == null) {
principal = getSubject().getPrincipal();
} else {
principal = getPrincipalFromClassName();
}
// Get the string value of the principal
if (principal != null) {
if (property == null) {
strValue = principal.toString();
} else {
strValue = getPrincipalProperty(principal, property);
}
}
}
} catch (Exception e) {
log.error("Error getting principal type [" + type + "], property [" + property + "]: " + e.getMessage(), e);
}
if (strValue == null) {
strValue = defaultValue;
}
// Print out the principal value if not null
if (strValue != null) {
try {
ctx.getResponseWriter().write(strValue);
} catch (IOException e) {
throw new IOException("Error writing [" + strValue + "] to output.");
}
}
}
|
251e6fe0-502e-4916-a8e8-100b64418c81
| 4
|
static double[][] minor(double[][] A, int i, int j){
double[][] minor = new double[A.length-1][A.length-1];
int n = 0, m = 0;
for(int k = 0; k < A.length; k++){
if(k == i)
continue;
for(int l = 0; l < A.length; l++){
if(l == j)
continue;
minor[n][m] = A[k][l];
m++;
}
n++;
m = 0;
}
return minor;
}
|
818a75e2-d328-45a7-8ef2-c279453b83f5
| 1
|
public ImprovedStack reverse() {
ImprovedStackImpl output = new ImprovedStackImpl();
output.list.array = new Object[size()];
for (int i = size() - 1; i >= 0; i--) {
output.push(list.get(i).getReturnValue());
System.out.println(list.get(i).getReturnValue());
}
return output;
}
|
e9322daf-b506-41c6-920c-6a0bd756fc3e
| 2
|
private void initStreamOrSource() throws FileNotFoundException {
if (dataSourceStream != null) {
final Reader r = new InputStreamReader(dataSourceStream);
setDataSourceReader(r);
addToCloseReaderList(r);
} else if (dataSource != null) {
final Reader r = new FileReader(dataSource);
setDataSourceReader(r);
addToCloseReaderList(r);
}
}
|
d40e15e7-4828-4714-b548-a734001dc911
| 1
|
public void delete(String query){
try {
this.statement.executeUpdate(query);
} catch (SQLException ex) {
Logger.getLogger(DatabaseConnection.class.getName()).log(Level.SEVERE, null, ex);
}
}
|
a8f29299-9f07-4b0f-9915-c3e6a1de65c5
| 9
|
private ParameterSweep readParameter(Configuration configFile,
String paramName, String paramSweep, String paramType,
String paramValue, int paramNum) {
ParameterSweep sweep = null;
if (paramSweep.equalsIgnoreCase("list")) {
List<Object> values = configFile.getList(paramValue);
sweep = new ListSweep<>(paramName, values);
} else if (paramSweep.equalsIgnoreCase("single")) {
if (paramType.equalsIgnoreCase("int")) {
int value = configFile.getInt(paramValue);
sweep = new SingleValueSweep<Integer>(paramName, value);
} else if (paramType.equalsIgnoreCase("double")) {
double value = configFile.getDouble(paramValue);
sweep = new SingleValueSweep<Double>(paramName, value);
} else if (paramType.equalsIgnoreCase("string")) {
String value = configFile.getString(paramValue);
sweep = new SingleValueSweep<String>(paramName, value);
} else if (paramType.equalsIgnoreCase("boolean")) {
boolean value = configFile.getBoolean(paramValue);
sweep = new SingleValueSweep<Boolean>(paramName, value);
} else {
// invalid parameter type
throw new RuntimeException(
"Invalid parameter type given for parameter "
+ paramNum
+ ", you must use \"int\", \"double\", \"string\" or \"boolean\"");
}
} else if (paramSweep.equalsIgnoreCase("sequence")) {
String fromKey = paramValue + ".from";
String toKey = paramValue + ".to";
String stepKey = paramValue + ".step";
if (paramType.equalsIgnoreCase("int")) {
int from = configFile.getInt(fromKey);
int to = configFile.getInt(toKey);
int step = configFile.getInt(stepKey);
sweep = new IntegerSequenceSweep(paramName, from, to, step);
} else if (paramType.equalsIgnoreCase("double")) {
double from = configFile.getDouble(fromKey);
double to = configFile.getDouble(toKey);
double step = configFile.getDouble(stepKey);
sweep = new DoubleSequenceSweep(paramName, from, to, step);
} else {// invalid parameter type
throw new RuntimeException(
"Invalid parameter type given for parameter "
+ paramNum
+ ", \"int\" or \"double\" must be used");
}
}
return sweep;
}
|
948921db-bd65-4284-bf67-3986cfde2de6
| 6
|
public void update(GameTimer gameTime)
{
// Make a copy of the master screen list, to avoid confusion if
// the process of updating one screen adds or removes others.
_ScreensToUpdate.clear();
for (GameScreen screen : _Screens)
{
_ScreensToUpdate.add(screen);
}
boolean otherScreenHasFocus = false;
boolean coveredByOtherScreen = false;
// Loop as long as there are screens waiting to be updated.
while (_ScreensToUpdate.size() > 0)
{
// Pop the topmost screen off the waiting list.
GameScreen screen = _ScreensToUpdate.get(_ScreensToUpdate.size() - 1);
_ScreensToUpdate.remove(_ScreensToUpdate.size() - 1);
// Update the screen.
screen.update(gameTime, otherScreenHasFocus, coveredByOtherScreen);
if (screen.getScreenState() == ScreenState.TransitionOn || screen.getScreenState() == ScreenState.Active)
{
// If this is the first active screen we came across, give it a chance to handle input.
if (!otherScreenHasFocus)
{
screen.handleInput(_Input);
otherScreenHasFocus = true;
}
// If this is an active non-popup, inform any subsequent screens that they are covered by it.
if (!screen.getIsPopup())
{
coveredByOtherScreen = true;
}
}
}
}
|
171fd56c-ca6e-4d9a-a516-b359dab46eca
| 9
|
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ZapposSearchResponse other = (ZapposSearchResponse) obj;
if (currentResultCount != other.currentResultCount)
return false;
if (results == null) {
if (other.results != null)
return false;
} else if (!results.equals(other.results))
return false;
if (statusCode != other.statusCode)
return false;
if (totalResultCount != other.totalResultCount)
return false;
return true;
}
|
5c51dbf6-4a4a-498a-97c8-0943e4ce647e
| 2
|
public float readFloat() throws IOException {
int code = readNextCode();
float result;
switch (code) {
case Codes.FLOAT:
result = is.readRawFloat();
break;
default: {
Object o = read(code);
if (o instanceof Float) {
return (Float) o;
} else {
throw expected("float", code, o);
}
}
}
return result;
}
|
bab0c5e6-a646-4f50-816a-6d96b443cdb9
| 0
|
@Override
public void componentMoved(ComponentEvent e) {}
|
f1f0a8fc-bc1f-4270-bf89-89167d7a37a1
| 5
|
private void commit() {
LinkedList<Vec2> pointsList = new LinkedList<>();
for (Curve curve : draftform.getCurves()) {
for (draftform.Vec2 dVec : curve.linearize(curve.recommendedSubdivisions()))
pointsList.add(new Vec2(dVec.getX(), dVec.getY()));
pointsList.removeLast();
}
Vec2[] points = new Vec2[pointsList.size()];
pointsList.toArray(points);
if (!physics.Polygon.isWindingCCW(points))
physics.Polygon.reverseWinding(points);
if (physics.Polygon.selfIntersects(points)) {
System.out.println("polygon is self-intersecting");
return;
}
MaterialEntity newEntity = new MaterialEntity();
newEntity.setLevel(Engine.level);
Material material = new Material();
material.setModelGenerator(new SimpleModelGenerator());
newEntity.setMaterial(material);
newEntity.setShape(points);
BodyDef objectDef = new BodyDef();
objectDef.setType(BodyType.DYNAMIC);
Body object = newEntity.setPhysicsObject(objectDef);
for (org.jbox2d.collision.shapes.Shape shape : shapeFromPolygon(points))
object.createFixture(shape, 0.1f);
draftform.getCurves().clear();
draftform.getVerts().clear();
drawDraftform();
}
|
940b9766-0c23-4bf9-a4e0-eec947589d73
| 1
|
public void togglePaused(){
paused = !paused;
if (paused) {
pauseObjects();
numAsteroids = asteroids.size();
}
}
|
c25422c2-d27b-472c-ad4a-50ab31351fe0
| 0
|
@Override
public void keyReleased(KeyEvent e) {}
|
0a480947-0ae1-4a16-8122-7b11795cf680
| 9
|
protected static Object getParamArg(Class cl)
{
if (! cl.isPrimitive())
return null;
else if (boolean.class.equals(cl))
return Boolean.FALSE;
else if (byte.class.equals(cl))
return Byte.valueOf((byte) 0);
else if (short.class.equals(cl))
return Short.valueOf((short) 0);
else if (char.class.equals(cl))
return Character.valueOf((char) 0);
else if (int.class.equals(cl))
return Integer.valueOf(0);
else if (long.class.equals(cl))
return Long.valueOf(0);
else if (float.class.equals(cl))
return Double.valueOf(0);
else if (double.class.equals(cl))
return Double.valueOf(0);
else
throw new UnsupportedOperationException();
}
|
6ea1df08-d77f-41e3-b192-8477c77f144e
| 3
|
public void preencher()
{
list = new ArrayList();
jlist = new JList(new DefaultListModel());
adicionar = new JButton("Adicionar");
adicionar.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent arg0)
{
if (pesquisa.getSelectedIndex() >= 0)
inserir();
}
});
remover = new JButton("Remover");
remover.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
int x = jlist.getSelectedIndex();
if (x >= 0)
{
list.remove(x);
((DefaultListModel) jlist.getModel()).removeElementAt(x);
}
else
JOptionPane
.showMessageDialog(null,
"Nenhum item foi selecionado para remoção",
"Alerta", JOptionPane.WARNING_MESSAGE);
}
});
DesignGridLayout layout = new DesignGridLayout(this);
if (novo != null)
layout.row().grid().add(pesquisa, adicionar, remover, novo);
else
layout.row().grid().add(pesquisa, adicionar, remover);
layout.row().grid().add(new JScrollPane(jlist));
setMinimumSize(getPreferredSize());
}
|
ceec63d4-3236-42b5-abb6-b3a2c59f108f
| 7
|
public Content getCrossClassLink(String qualifiedClassName, String refMemName,
Content label, boolean strong, String style,
boolean code) {
String className = "";
String packageName = qualifiedClassName == null ? "" : qualifiedClassName;
int periodIndex;
while ((periodIndex = packageName.lastIndexOf('.')) != -1) {
className = packageName.substring(periodIndex + 1, packageName.length()) +
(className.length() > 0 ? "." + className : "");
Content defaultLabel = new StringContent(className);
if (code)
defaultLabel = HtmlTree.CODE(defaultLabel);
packageName = packageName.substring(0, periodIndex);
if (getCrossPackageLink(packageName) != null) {
//The package exists in external documentation, so link to the external
//class (assuming that it exists). This is definitely a limitation of
//the -link option. There are ways to determine if an external package
//exists, but no way to determine if the external class exists. We just
//have to assume that it does.
DocLink link = configuration.extern.getExternalLink(packageName, pathToRoot,
className + ".html", refMemName);
return getHyperLink(link,
(label == null) || label.isEmpty() ? defaultLabel : label,
strong, style,
configuration.getText("doclet.Href_Class_Or_Interface_Title", packageName),
"");
}
}
return null;
}
|
62f9bba4-a22f-4ebe-8655-6b6a90f149da
| 6
|
protected KeyListener createKeyListener() {
return new KeyListener() {
public void keyPressed(KeyEvent e) {
if (e.getKeyChar() == KeyEvent.CHAR_UNDEFINED || e.getKeyCode() == KeyEvent.VK_DELETE) {
if (editMode)
handleKeyPressed(e.getKeyCode());
else
buffer(e);
}
}
public void keyReleased(KeyEvent e) {
if (e.getKeyChar() == KeyEvent.CHAR_UNDEFINED) {
if (editMode)
handleKeyReleased(e.getKeyCode());
else
buffer(e);
}
}
public void keyTyped(KeyEvent e) {
if (editMode)
handleKeyTyped(e.getKeyChar());
else
buffer(e);
}
};
}
|
99386dfd-53c5-4906-85f8-0c97650042b0
| 6
|
private int getBonuses() {
int bonus = 0;
if (developments.isDevelopmentBought(DevelopmentList.ARCHITECTURE)) {
for (int i = 0; i < monuments.length; i++) {
if (monuments[i].isFull()) {
bonus++;
}
}
}
if (developments.isDevelopmentBought(DevelopmentList.EMPIRE)) {
for (int i = 0; i < cities.length; i++) {
if (cities[i].isFull()) {
bonus++;
}
}
}
return bonus;
}
|
42772666-f264-4d6e-af63-cc888f0fe9d0
| 2
|
public static void main(String s[]) throws IOException
{
FileInputStream fis = new FileInputStream("/Users/arun/Hack/file-ip-test.txt");
Scanner sc = new Scanner (fis, "UTF-8");
ArrayList<bean1> al = new ArrayList<bean1>();
log("Input from file:");
while(sc.hasNextLine())
{
String s1;
System.out.println( s1 = sc.nextLine());
String inArr[] = s1.split("-");
al.add(new bean1(inArr[0],Integer.parseInt(inArr[1])));
}
//Collections.sort(al,new BeanComparator() );
Collections.sort(al);
FileOutputStream fos = new FileOutputStream ("/Users/arun/Hack/file-op-test.txt");
OutputStreamWriter dos = new OutputStreamWriter (fos,"UTF-8");
StringBuilder sb = new StringBuilder();
for (bean1 b1: al){
sb.append(b1.name+"-"+b1.sal+"\n");
}
log("\nSorted content to write to file:");
log(sb.toString());
dos.append(sb);
dos.close(); sc.close();
}
|
82963136-3579-4198-995b-11d8a5c0fed0
| 1
|
public void register(){
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
|
82e41eda-822a-45a0-a620-adeafd288392
| 1
|
public AnnotationVisitor visitParameterAnnotation(
final int parameter,
final String desc,
final boolean visible)
{
return new SAXAnnotationAdapter(getContentHandler(),
"parameterAnnotation",
visible ? 1 : -1,
parameter,
desc);
}
|
67720cd5-e209-41d7-984b-5ca3623664f6
| 6
|
private static void generatedConsolidatedHTML(final Map<File, AnalysisData> processedWorkflows) {
try {
final File globalAnalyze = new File("global-analyze.html");
final FileWriter gaWriter = new FileWriter(globalAnalyze);
gaWriter.write("<html>");
gaWriter.write("<body>");
// Consolidated analyze
final File consolidatedAnalysisHTML = new File("analyze.html");
if(consolidatedAnalysisHTML.exists() && consolidatedAnalysisHTML.isFile()) {
final String consolidatedAnalyse = stringify(new FileInputStream(consolidatedAnalysisHTML));
gaWriter.write(consolidatedAnalyse);
}
// Workflow analyzes
for (final File processedWorkflowDirectory : processedWorkflows.keySet()) {
final File analyseFile = new File(processedWorkflowDirectory, "analyze.html");
if(analyseFile.exists() && analyseFile.isFile()) {
final String fragmentAnalyse = stringify(new FileInputStream(analyseFile));
gaWriter.write(fragmentAnalyse);
}
}
gaWriter.write("</body>");
gaWriter.write("</html>");
gaWriter.flush();
gaWriter.close();
} catch (final IOException e) {
e.printStackTrace();
}
}
|
e8a08d18-665b-4947-82e3-4f7680ea524d
| 9
|
public List<THandler> readClass(Class<?> clazz) {
List<THandler> handlers = new ArrayList<THandler>();
ClassHelper classHelper = new ClassHelper(clazz);
TClassMeta classMeta = metadataReader.readClass(clazz, classHelper);
if(classMeta == null) {
return handlers;
}
Method[] methods = clazz.getDeclaredMethods();
for(Method method : methods) {
MethodHelper methodHelper = new MethodHelper(method);
TMethodMeta methodMeta = metadataReader.readMethod(
classMeta,
method,
methodHelper);
if(methodMeta == null) {
continue;
}
List<TParameterMeta> parameterMetas = new ArrayList<TParameterMeta>();
Class<?>[] parameterTypes = method.getParameterTypes();
Annotation[][] parameterAnnotationArrays = method.getParameterAnnotations();
int numberOfParameters = parameterTypes.length;
for(int i = 0; i < numberOfParameters; ++i) {
Class<?> parameterClass = parameterTypes[i];
Annotation[] parameterAnnotations = parameterAnnotationArrays[i];
ParameterHelper parameterHelper = new ParameterHelper(parameterClass, parameterAnnotations);
TParameterMeta parameterContext = metadataReader.readParameter(
classMeta,
methodMeta,
parameterClass,
parameterAnnotations,
parameterHelper);
if(parameterContext == null) {
continue;
}
parameterMetas.add(parameterContext);
}
if(parameterMetas.size() != numberOfParameters) {
continue;
}
THandler handler = metadataReader.makeHandler(
classMeta,
methodMeta,
parameterMetas);
handlers.add(handler);
}
return handlers;
}
|
68d524ab-a91d-44dc-b26b-9974c630a4c0
| 4
|
@Test
public void findsCorrectDefaultInputs()
{
assertTrue(settings.getControl(KeyEvent.VK_RIGHT) == Input.PLR1RIGHT &&
settings.getControl(KeyEvent.VK_LEFT) == Input.PLR1LEFT &&
settings.getControl(KeyEvent.VK_UP) == Input.PLR1UP &&
settings.getControl(KeyEvent.VK_DOWN) == Input.PLR1DOWN &&
settings.getControl(KeyEvent.VK_P) == Input.PAUSE);
}
|
174f1c26-bbf9-42a5-98a8-6bd8e5fac079
| 9
|
public String tokenType(int priorState){
switch(priorState){
case 0:
return "ESPACIO";
case 8:
return "IF"; //Palabra reservada if
case 11:
return "ELSE"; //Palabra reservada else
case 1:
return "ID"; //Identificador
case 12:
return "SPECIAL"; //Caracteres especiales
case 2:
return "OP_ASIG"; //Operador de Asignacion
case 3:
return "OP_ARIT"; //Operadores aritmeticos
case 4:
return "E";//Enetero
case 7:
return "F";//Flotante
default:
return "ERROR";
}
}
|
f2af7c84-ad69-47fa-be10-d12eacadcb0c
| 0
|
public void initTextures(AssetManager assetManagere){
Glass.glassTexture = assetManagere.loadTexture("Textures/Blocks/glass.png");
}
|
d36e1f56-3c4e-4320-9e1d-ed2b32399034
| 9
|
public int layoutProjectedRectangle(ArrayList<Rectangle> rectangles){
/*
0 is no intersections.
1 is ground intersection
2 is wall intersection
*/
Rectangle projectedRectangle=new Rectangle((int)(_xcor+_xvel),(int)(_ycor+_yvel+GRAVITY+ 0.99),PLAYER_WIDTH,PLAYER_HEIGHT);
for(int i = 0; i < rectangles.size(); i++) {
if (rectangles.get(i).intersects(projectedRectangle)) {
// System.out.println("intersert");
// if player is above
// System.out.println("plyr: " + (projectedRectangle.getY()+PLAYER_HEIGHT) + "| rect: " + rectangles.get(i).getY());
if(_yvel>0){
if (projectedRectangle.getY()+PLAYER_HEIGHT>=rectangles.get(i).getY() && projectedRectangle.getY()+PLAYER_HEIGHT<=rectangles.get(i).getY() + 10) {
return 1 + i * 10;
}
// if player is to left
if(_xvel>0){
if(projectedRectangle.getX()+PLAYER_WIDTH>=rectangles.get(i).getX()) {
// return 2 + i* 10 ;// implement later
}
}
// if player is to the right
if(_xvel<0){
if(projectedRectangle.getX()<=rectangles.get(i).getX()+rectangles.get(i).getWidth()){
// return 2 + i * 10 ;// implement later
}
}
}
}
}
return 0; //Either the player didn't hit anything or he hit his head, which is fine.
}
|
6d6c0391-d86c-4701-9ae7-e6b7faa7b2a6
| 6
|
public AbsGameObject getMapObject(EnGameObjectType gameObjectType, Coordinate coordinate) {
AbsGameObject absGO = null;
switch (gameObjectType) {
case EXIT:
absGO = new Exit(coordinate);
break;
case MONSTER:
absGO = new Monster(coordinate);
break;
case TREASURE:
absGO = new Treasure(coordinate);
break;
case WALL:
absGO = new Wall(coordinate);
break;
case GOLDDIGGER:
absGO = new Golddigger(coordinate);
break;
case NOTHING:
absGO = new Nothing(coordinate);
break;
default:
throw new IllegalArgumentException("Can't create object type: " + gameObjectType);
}
return absGO;
}
|
867d2044-22b1-4c0f-bc1b-5e4e9061eb74
| 1
|
public void setTilesetImageFilename(String name) {
if (name != null) {
tilebmpFile = new File(name);
tilebmpFileLastModified = tilebmpFile.lastModified();
}
else {
tilebmpFile = null;
}
}
|
a9db90da-7ada-45da-977c-af1870ced612
| 9
|
@Override
public boolean onCommand(CommandSender sender, Command command, String commandlabel, final String[] args) {
if(sender instanceof Player) {
Player player = (Player) sender;
// Valid command format
if(args.length >= 1) {
// casino add
if(args[0].equalsIgnoreCase("add")) {
cmd = new CasinoAdd(plugin, args, player);
}
// casino addmanaged
else if(args[0].equalsIgnoreCase("addmanaged")) {
cmd = new CasinoAddManaged(plugin, args, player);
}
// casino remove
else if(args[0].equalsIgnoreCase("remove")) {
cmd = new CasinoRemove(plugin, args, player);
}
// casino list
else if(args[0].equalsIgnoreCase("list")) {
cmd = new CasinoList(plugin, args, player);
}
// casino reload
else if(args[0].equalsIgnoreCase("reload")) {
cmd = new CasinoReload(plugin, args, player);
}
// casino stats
else if(args[0].equalsIgnoreCase("stats")) {
cmd = new CasinoStats(plugin, args, player);
}
// casino edit
else if(args[0].equalsIgnoreCase("type")) {
cmd = new CasinoType(plugin, args, player);
}
// invalid command
else {
return false;
}
}
// no arguments
else {
cmd = new Casino(plugin, args, player);
}
return cmd.process();
}
// No commands by console
else {
plugin.logger.info("This command cannot be executed as console.");
}
return true;
}
|
f453cea7-ab4f-4b0f-902e-6528045ab9a7
| 9
|
public final void update() {
// timestamp of last update
float secondsSinceLastUpdate = ((float) World.getWorld().getCurrentTS() - lastUpdateTS) / 1000;
lastUpdateTS = World.getWorld().getCurrentTS();
if (secondsSinceLastUpdate == 0f) {
return;
}
applyForces();
posSpeed.x += posAccel.x * secondsSinceLastUpdate;
posSpeed.y += posAccel.y * secondsSinceLastUpdate;
posSpeed.z += posAccel.z * secondsSinceLastUpdate;
LOGGER.trace("posAccel: " + posAccel + ", posSpeed: " + posSpeed);
// The drag factor is reduced to take into account the fact that we update the position since last TS and not from a full second ago.
float reducedDragFactor = 1 - (1 - getDragFactor()) * secondsSinceLastUpdate;
posSpeed.x = Math.abs(posSpeed.x * reducedDragFactor) > ModelConstants.MIN_SPEED ? posSpeed.x * reducedDragFactor : 0;
posSpeed.y = Math.abs(posSpeed.y * reducedDragFactor) > ModelConstants.MIN_SPEED ? posSpeed.y * reducedDragFactor : 0;
posSpeed.z = Math.abs(posSpeed.z * reducedDragFactor) > ModelConstants.MIN_SPEED ? posSpeed.z * reducedDragFactor : 0;
// If this ship is stopped, fire a shipStopped event
if (posSpeed.x == 0 && posSpeed.y == 0 && posSpeed.z == 0) {
fireShipStopped(new ShipEvent(this));
}
pos.x += posSpeed.x * secondsSinceLastUpdate;
pos.y += posSpeed.y * secondsSinceLastUpdate;
pos.z += posSpeed.z * secondsSinceLastUpdate;
rotSpeed += rotAccel * secondsSinceLastUpdate;
// rotSpeed = 5; // FIXME Remove that
// The drag factor is reduced to take into account the fact that we update the position since last TS and not from a full second ago.
float reducedRotDragFactor = 1 - (1 - ModelConstants.ROT_DRAG_FACTOR) * secondsSinceLastUpdate;
rotSpeed = Math.abs(rotSpeed * reducedRotDragFactor * 0.995f) > ModelConstants.MIN_SPEED ? rotSpeed * reducedRotDragFactor * 0.995f : 0;
rot = (rot + rotSpeed * secondsSinceLastUpdate) % 360;
// rot = 90; // FIXME remove that
updateMorphs();
// execute the behaviors
for (Behavior<Ship> behavior : alwaysActiveBehaviors) {
behavior.tryToExecute();
}
}
|
f53a9e9e-8bcf-46eb-b062-3d8a736122d2
| 4
|
public void test_20_Nmers_read_write() {
String testFile = "/tmp/nmer_test.bin";
int nmerSize = 32;
int numNmers = 100000;
try {
// Initialize
FileOutputStream os = new FileOutputStream(new File(testFile));
Random rand = new Random(20100825);
ArrayList<Nmer> list = new ArrayList<Nmer>();
// Create Nmers and write them to file
for( int i = 0; i < numNmers; i++ ) {
Nmer nmer = new Nmer(nmerSize);
nmer.setNmer(rand.nextLong());
list.add(nmer);
nmer.write(os);
}
os.close();
// Read nmers from file and compare to originals
Nmer nmer = new Nmer(nmerSize);
FileInputStream is = new FileInputStream(new File(testFile));
for( int i = 0; nmer.read(is) >= 0; i++ ) {
Nmer nmerOri = list.get(i);
if( nmerOri.getNmer() != nmer.getNmer() ) throw new RuntimeException("Nmers differ:\n\t" + nmerOri + "\t" + Long.toHexString(nmerOri.getNmer()) + "\n\t" + nmer + "\t" + Long.toHexString(nmer.getNmer()));
}
is.close();
} catch(Exception e) {
throw new RuntimeException(e);
}
}
|
0ff0592f-3615-4517-9fc9-315a719fc173
| 0
|
public String toString()
{
return super.toString() + ": \"" + getLabel() + "/" + getOutput() + "\"";
}
|
18cef091-4946-4fce-8e40-ea99b61859b6
| 8
|
public static SubmitBatch_Result submitBatch(Database database, SubmitBatch_Param params) {
Logger.getLogger(API.class.getName()).log(Level.FINE, "Entering API.submitBatch()");
SubmitBatch_Result result;
try { // validate user
ValidateUser_Result vResult = validateUser(database, new ValidateUser_Param(params.username(), params.password()));
if (vResult == null || !vResult.validated()) { // not validated
result = null;
}
else { // user validated
// Get the Image
Image tImage = new Image();
tImage.setImageId(params.batchId());
ArrayList<Image> images = (ArrayList) database.get(tImage);
// Should only return one result, since image IDs are unique
assert images.size() == 1;
int firstImageIndex = 0;
Image thisImage = images.get(firstImageIndex);
if (thisImage.currentUser() != vResult.userId()) { // If the batch ID was wrong
throw new APIException(String.format(
"This batch does not belong to user ID %d", vResult.userId()));
}
// Get all Fields from this Image's project
Field tField = new Field();
tField.setProjectId(thisImage.projectId());
ArrayList<Field> fields = (ArrayList) database.get(tField);
// Get the Project for the number of records
Project tProject = new Project();
tProject.setProjectId(thisImage.projectId());
ArrayList<Project> projects = (ArrayList) database.get(tProject);
// Should only get one Project
assert projects.size() == 1;
int firstProjectIndex = 0;
Project thisProject = projects.get(firstProjectIndex);
// Split the records on ';' character
String[] records = params.records().split(";");
if (records.length != thisProject.recordCount()) {
throw new APIException(String.format(
"Invalid number of records given. %d given, %d required.",
records.length, thisProject.recordCount()));
}
for (int rowNumber = 0; rowNumber < records.length; ++rowNumber) {
// Split the record values on ',' character
String[] values = records[rowNumber].split(",", -1);
if (values.length != fields.size()) {
throw new APIException(String.format(
"Invalid number of values given. %d given, %d required.",
values.length, fields.size()));
}
for (int column = 1; column <= values.length; ++column) {
Field currentField = fields.get(column - 1);
// Insert the value for this record into the database
database.insert(new Record(params.batchId(), currentField.fieldId(), rowNumber, values[column - 1]));
}
}
// Update Current user for the image to -1 (complete Image)
thisImage.setCurrentUser(Images.IMAGE_COMPLETED);
database.update(thisImage);
// Update the number of indexed records for this user
User user = new User();
user.setUserId(vResult.userId());
user.setIndexedRecords(vResult.recordsIndexed() + records.length);
database.update(user);
result = new SubmitBatch_Result(true);
}
}
catch (DatabaseException
| InsertFailedException
| GetFailedException
| APIException
| UpdateFailedException ex) {
result = null;
Logger.getLogger(API.class.getName()).log(Level.WARNING, "submitBatch request failed.", ex);
}
Logger.getLogger(API.class.getName()).log(Level.FINE, "Exiting API.submitBatch()");
return result;
}
|
929a001e-6c68-4af2-a91d-7d1dabed911f
| 7
|
public PointPathFinding trouverPoint(PointPathFinding point, double diffX, double diffY, ArrayList<PointPathFinding> visites) {
double x = point.getX();
double y = point.getY();
int cout = point.getCout();
PointPathFinding trouve = getPointExistant(x+diffX, y+diffY, visites);
if(trouve==null) {
trouve = new PointPathFinding(x+diffX, y+diffY, cout+1);
if(deplacementPossible(trouve)) {
if(trouve.getX()>=0.09 && trouve.getX()<=0.1900875 &&
trouve.getY()>=49.448 && trouve.getY()<=49.488) {
trouve.setDistance(trouve.distance(_destination));
trouve.setCout(cout+1);
} else {
return null;
}
} else {
return null;
}
} else {
trouve.setDistance(trouve.distance(_destination));
if(trouve.getCout()+1<point.getCout()) {
trouve.setCout(point.getCout()+1);
}
}
return trouve;
}
|
eea0fd4a-7214-40c6-90e1-c1bbd9e54e5f
| 0
|
@Override
public void restoreTemporaryToDefault() {tmp = def;}
|
7a43b9d9-87d2-4bb8-8c99-db6f1aea3967
| 8
|
public static String escapeXml( String str ) {
if ( str == null ) {
return str;
}
int len = str.length();
if ( len == 0 ) {
return str;
}
StringBuffer encodedBuffer = new StringBuffer();
// parse string and encode characters
for (int i = 0; i < len; i++) {
char chr= str.charAt(i);
if ( chr== '<' ) {
encodedBuffer.append( "<" );
} else if ( chr == '>' ) {
encodedBuffer.append( ">" );
} else if ( chr == '\"' ) {
encodedBuffer.append( """ );
} else if ( chr == '\'' ) {
encodedBuffer.append( "'" );
} else if ( chr == '&' ) {
encodedBuffer.append( "&" );
} else {
encodedBuffer.append( chr );
}
}
return encodedBuffer.toString();
}
|
884c80b6-048b-4550-ab81-43f0df4be2ea
| 5
|
public void drawCurrentBlock(Graphics g){
//画指针
g.setColor(Color.red);
switch(this.current_type){
case 0:
g.drawRect(pointer_y * 10 + 50, pointer_x * 10 + 50, 10, 10);
break ;
case 1:
g.drawImage(grass, pointer_y * 10 + 50, pointer_x * 10 + 50, 10, 10, this);
break ;
case 2:
g.drawImage(this.wall, pointer_y * 10 + 50, pointer_x * 10 + 50, 10, 10, this);
break ;
case 3:
g.drawImage(this.wallUndefeted, pointer_y * 10 + 50, pointer_x * 10 + 50, 10, 10, this);
break ;
case 4:
g.drawImage(this.water, pointer_y * 10 + 50, pointer_x * 10 + 50, 10, 10, this);
break ;
default:
break;
}
g.drawRect(pointer_y * 10 + 50, pointer_x * 10 + 50, 10, 10);
}
|
9fe26510-334f-41a0-88c2-e07853e0d618
| 9
|
public static void main(String[] args) throws Throwable{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
for (String line ; (line=in.readLine())!=null;) {
int cantL = Integer.parseInt(line);
if(cantL == 0 )break;
boolean pass = true;
int nocturnas=0;
int total=0;
for (int i = 0; i < cantL; i++) {
line = in.readLine();
String[] horas = line.split(" ");
String[] n = horas[0].split(":");
int hs = Integer.parseInt(n[0]);
int ms = Integer.parseInt(n[1]);
n = horas[1].split(":");
int hss = Integer.parseInt(n[0]);
int mss = Integer.parseInt(n[1]);
n = horas[2].split(":");
int hi = Integer.parseInt(n[0]);
int mi = Integer.parseInt(n[1]);
n = horas[3].split(":");
int he = Integer.parseInt(n[0]);
int me = Integer.parseInt(n[1]);
double parcial = clockToMinutes(hi, mi, he, me);
if(parcial > 120) pass = false;
else if( beforeSunrise(clockToMinutes(hi, mi), clockToMinutes(hs, ms), parcial)){
total+=parcial;
nocturnas+=parcial;
}else if( afterSunset(clockToMinutes(he, me), clockToMinutes(hss, mss), parcial)){
total+=parcial;
nocturnas+=parcial;
}else{
total+=parcial;
}
}
if(nocturnas<MIN_NOC || total<MIN_TOT)
pass = false;
System.out.println(pass?"PASS":"NON");
}
}
|
b4f2a962-2fb8-4131-85c5-9275f0b71b51
| 5
|
private void findFile(File file, String filename)
{
if (file.isDirectory() && isApplication(file) == false)
{
// System.out.println("Checking Directory: " + file);
File[] files = file.listFiles(this);
if (files != null)
{
for (int i = 0; i < files.length; i++)
{
findFile(files[i], filename);
}
}
}
else if (file.getName().toLowerCase().indexOf(filename) != -1)
{
matchedFiles.add(file);
}
}
|
c5519186-fedc-4852-a0ef-7360f639dfe6
| 3
|
public JSONArray toJSONArray(JSONArray names) throws JSONException {
if (names == null || names.length() == 0) {
return null;
}
JSONArray ja = new JSONArray();
for (int i = 0; i < names.length(); i += 1) {
ja.put(this.opt(names.getString(i)));
}
return ja;
}
|
2ad7c79e-ca29-4828-913c-b185670e367d
| 1
|
public E poll()
{
if (count == 0) return null;
E r = peek();
head = (head + 1) % elements.length;
count--;
modcount++;
return r;
}
|
830b9dcf-2f02-4178-9b3a-c4b20142adde
| 2
|
@Override
public void startDocument() throws SAXException {
try {
response = clazz.newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
|
5d32cf32-799c-41f8-ac18-388dce1d75a5
| 8
|
private static void Poda_CreaArbol(Nodo ini, int limite) {
if(limite==0){
ini.calcula_utilidad();
}
else{
ArrayList<Nodo> sucesores= ini.getSucesores();
if(ini.esHoja()){
ini.calcula_utilidad();
}
else{
Iterator<Nodo> it=sucesores.iterator();
while(it.hasNext()&&ini.alfa<ini.beta){
Nodo actual=it.next();
actual.alfa=ini.alfa;
actual.beta=ini.beta;
Poda_CreaArbol(actual,limite-1);
if(ini.Jugador==Nodo.MAX && actual.utilidad>ini.alfa){
ini.alfa=actual.utilidad;
ini.utilidad=actual.utilidad;
}
if(ini.Jugador==Nodo.MIN && actual.utilidad<ini.beta){
ini.beta=actual.utilidad;
ini.utilidad=actual.utilidad;
}
}
//if(ini.alfa>=ini.beta) System.out.println("HE PODADO");
}
}
}
|
6a34ba46-5334-426f-85f2-27821be491b6
| 5
|
public static String getDateFormatPattern( String ifmt )
{
if( ifmt.equals( "14" ) )
{
return "m/d/yy";
}
if( ifmt.equals( "15" ) )
{
return "d-mmm-yy";
}
if( ifmt.equals( "16" ) )
{
return "d-mmm";
}
if( ifmt.equals( "17" ) )
{
return "mmm-yy";
}
if( ifmt.equals( "22" ) )
{
return "m/d/yy h:mm";
}
return "m/d/yy";
}
|
32458e26-dc15-4f5b-a4ab-54b42b44c8e5
| 7
|
public String login() {
Application app=new ConnectClass().connect();
try
{
app.label("Markets").verify();
app.label("Login").tap();
}
catch(MonkeyTalkFailure ex)
{
System.out.println("Login Page");
}
app.input("701").enterText(user);
app.input("702").enterText(password);
app.button("703").tap();
try {
app.label("Cancel").verify();
app.label("Cancel").tap();
}
catch(MonkeyTalkFailure ex){
try{
app.label("Not Now").verify();
app.label("Not Now").tap();
}
catch(MonkeyTalkFailure ex2){
}
}
finally{
try{
app.button("Continue").verify();
app.button("Continue").tap();
}
catch(MonkeyTalkFailure ex)
{
}
try {
app.label("Close").verify();
app.label("Close").tap();
}
catch(MonkeyTalkFailure ex){
}
try{
app.label("Messages").verify();
app.label("Done").tap();
}
catch(MonkeyTalkFailure ex){
}
}
try
{
app.label("Login").verify();
return "fail";
}
catch(MonkeyTalkFailure ex2)
{
return "pass";
}
}
|
694c27fd-056f-4be6-9f3c-364e11c6a2ff
| 4
|
@Override
public void run() {
Object o;
try {
while ((o = obInputStream.readObject()) != null) {
Order rOrder = (Order) o;
if(warehouse.authUser(rOrder.getUsername(),rOrder.getPassword())){
warehouse.addOrder(rOrder);
outThread.sentOrder(rOrder);
} else {
System.out.println("Käuferanfrage abgelehnt! Ungültige Authentifizierung!");
}
}
} catch (ClassNotFoundException | IOException e) {
e.printStackTrace();
} finally {
try {
obInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
|
c5c53037-e950-4e06-aefb-0873300e336e
| 9
|
public void log(String text, LOG_TYPES type) {
if (!can)
return;
switch (type) {
case DEBUG:
if (ConstantHandler.LOG_DEBUG)
out.println("DEBUG: " + System.nanoTime() + " " + text);
break;
case EVENT:
if (ConstantHandler.LOG_EVENT)
out.println("EVENT: " + System.nanoTime() + " " + text);
break;
case WORNING:
if (ConstantHandler.LOG_WORNING)
out.println("WORNING: " + System.nanoTime() + " " + text);
break;
case ERROR:
if (ConstantHandler.LOG_DEBUG)
out.println("ERROR: " + System.nanoTime() + " " + text);
break;
default:
out.println("UNKNOWN: " + System.nanoTime() + " " + text);
break;
}
}
|
21dc6b4d-f36b-4c82-90a1-805ef6fabc3a
| 5
|
public static float[][] generator(int rows, int cols){
float edgefraction[][] = new float[rows][cols];
//Edge fraction (random numbers between 0-1)
for (int i = 0; i < rows; i++){
for (int j = 0; j < cols; j++){
Random rnd = new Random();
edgefraction[i][j] = rnd.nextFloat();
}
}
//Normalize the edge weight and return normalized weight
for (int i = 0; i < rows; i++){
float sum = 0;
for (int j = 0; j < cols; j++){
sum = sum + edgefraction[i][j];
}
for (int j = 0; j < cols; j++){
edgefraction[i][j] = edgefraction[i][j]/sum;
}
}
return edgefraction;
}
|
8e371b47-0fe8-452d-8b3f-b3914c67384c
| 0
|
public void setBoxId(int boxId) {
this.boxId = boxId;
}
|
20529e93-2556-4e79-a4f7-25386bca7ef9
| 5
|
private static Class[] getClassType(String desc, int descLen,
int start, int num) {
int end = start;
while (desc.charAt(end) == '[')
++end;
if (desc.charAt(end) == 'L') {
end = desc.indexOf(';', end);
if (end < 0)
throw new IndexOutOfBoundsException("bad descriptor");
}
String cname;
if (desc.charAt(start) == 'L')
cname = desc.substring(start + 1, end);
else
cname = desc.substring(start, end + 1);
Class[] result = getType(desc, descLen, end + 1, num + 1);
try {
result[num] = getClassObject(cname.replace('/', '.'));
}
catch (ClassNotFoundException e) {
// "new RuntimeException(e)" is not available in JDK 1.3.
throw new RuntimeException(e.getMessage());
}
return result;
}
|
f8c0ac3b-dcab-4fd8-9302-9e5549192bf1
| 9
|
protected void loadFields(com.sforce.ws.parser.XmlInputStream __in,
com.sforce.ws.bind.TypeMapper __typeMapper) throws java.io.IOException, com.sforce.ws.ConnectionException {
super.loadFields(__in, __typeMapper);
__in.peekTag();
if (__typeMapper.isElement(__in, CreatedBy__typeInfo)) {
setCreatedBy((com.sforce.soap.enterprise.sobject.Name)__typeMapper.readObject(__in, CreatedBy__typeInfo, com.sforce.soap.enterprise.sobject.Name.class));
}
__in.peekTag();
if (__typeMapper.isElement(__in, CreatedById__typeInfo)) {
setCreatedById(__typeMapper.readString(__in, CreatedById__typeInfo, java.lang.String.class));
}
__in.peekTag();
if (__typeMapper.isElement(__in, CreatedDate__typeInfo)) {
setCreatedDate((java.util.Calendar)__typeMapper.readObject(__in, CreatedDate__typeInfo, java.util.Calendar.class));
}
__in.peekTag();
if (__typeMapper.isElement(__in, Field__typeInfo)) {
setField(__typeMapper.readString(__in, Field__typeInfo, java.lang.String.class));
}
__in.peekTag();
if (__typeMapper.isElement(__in, IsDeleted__typeInfo)) {
setIsDeleted((java.lang.Boolean)__typeMapper.readObject(__in, IsDeleted__typeInfo, java.lang.Boolean.class));
}
__in.peekTag();
if (__typeMapper.isElement(__in, NewValue__typeInfo)) {
setNewValue((java.lang.Object)__typeMapper.readObject(__in, NewValue__typeInfo, java.lang.Object.class));
}
__in.peekTag();
if (__typeMapper.isElement(__in, OldValue__typeInfo)) {
setOldValue((java.lang.Object)__typeMapper.readObject(__in, OldValue__typeInfo, java.lang.Object.class));
}
__in.peekTag();
if (__typeMapper.isElement(__in, Parent__typeInfo)) {
setParent((com.sforce.soap.enterprise.sobject.Servicio__c)__typeMapper.readObject(__in, Parent__typeInfo, com.sforce.soap.enterprise.sobject.Servicio__c.class));
}
__in.peekTag();
if (__typeMapper.isElement(__in, ParentId__typeInfo)) {
setParentId(__typeMapper.readString(__in, ParentId__typeInfo, java.lang.String.class));
}
}
|
80a3946c-1d6d-40de-8cd3-528e9d5f0ed9
| 1
|
@Override
public void draw(Graphics page) {
planeImage.drawImage(page, xLocation, yLocation);//Draws the plane on the component
//Draws the collision Border
if(this.getBorderVisibility())
{
drawCollisionBorder(page,xLocation,yLocation,planeImage.getWidth(),planeImage.getHeight());
}
}
|
317ce0c5-6a0d-43da-ae9a-c06e44bcfe08
| 6
|
public void changeHighScore(int newscore, String name){
if (newscore > first){ //if the new score is the first one on the new table
this.fifth= this.forth;
this.forth= this.third;
this.third= this.second;
this.second= this.first;
this.first= newscore;
this.fifthHighScore.setText("5." + (this.forthHighScore.getText()).substring(2));
this.forthHighScore.setText("4." + (this.thirdHighScore.getText()).substring(2));
this.thirdHighScore.setText("3." + (this.secondHighScore.getText()).substring(2));
this.secondHighScore.setText("2." + (this.firstHighScore.getText()).substring(2));
this.firstHighScore.setText("1. " + name + ": " + newscore);
} //if the new score is at least the second one on the new table
else if (newscore > this.second){
this.fifth= this.forth;
this.forth= this.third;
this.third= this.second;
this.second= newscore;
this.fifthHighScore.setText("5." + (this.forthHighScore.getText()).substring(2));
this.forthHighScore.setText("4." + (this.thirdHighScore.getText()).substring(2));
this.thirdHighScore.setText("3." + (this.secondHighScore.getText()).substring(2));
this.secondHighScore.setText("2. " + name + ": " + newscore);
} //if the new score is at least the third one on the new table
else if (newscore > this.third){
this.fifth= this.forth;
this.forth= this.third;
this.third= newscore;
this.fifthHighScore.setText("5." + (this.forthHighScore.getText()).substring(2));
this.forthHighScore.setText("4." + (this.thirdHighScore.getText()).substring(2));
this.thirdHighScore.setText("3. " + name + ": " + newscore);
} //if the new score is at least the forth one on the new table
else if (newscore > this.forth){
this.fifth= this.forth;
this.forth= newscore;
this.fifthHighScore.setText("5." + (this.forthHighScore.getText()).substring(2));
this.forthHighScore.setText("4. " + name + ": " + newscore);
} //if the new score is at least the fifth one on the new table
else if (newscore > this.fifth){
this.fifth= newscore;
this.forthHighScore.setText("5. " + name + ": " + newscore);
}
try { //after updating the table, saves it to file
FileOutputStream fileOutputStream = new FileOutputStream(GameFrame.HIGHSCORES_FILE);
ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
objectOutputStream.writeObject(this);
objectOutputStream.close();
fileOutputStream.close();
}
catch (Exception e){
JOptionPane.showMessageDialog(this, "error while saving highscores", "", JOptionPane.ERROR_MESSAGE);
}
}//changeHighScore(int, String)
|
80da818a-a6ac-4643-8eb1-b71a6f42da9e
| 4
|
public boolean removeWhen(SingleObject bl){
boolean remove=bl.inRange(stage.player)
|| !bl.inArea(-20,stage.getWidth()+20,-50,stage.getHeight()-100)
|| stage.second()>16;
if(remove && grade=='f'){
stage.getSound("audio/f_explode.wav").play();
stage.impact=true;
stage.impactx=(int)bl.x;
stage.impacty=(int)bl.y;
}
return remove;
}
|
24ecf018-ca97-4f5c-8170-c400570c1a7c
| 7
|
@Override
public boolean okMessage(final Environmental myHost, final CMMsg msg)
{
if(!super.okMessage(myHost,msg))
return false;
if(affected==null)
return true;
if(!(affected instanceof MOB))
return true;
if(msg.target()==affected)
{
if((msg.tool()!=null)
&&(CMLib.dice().rollPercentage()>50)
&&((msg.targetMinor()==CMMsg.TYP_POISON)))
{
msg.source().location().show((MOB)affected,null,CMMsg.MSG_OK_VISUAL,L("<S-NAME> magically repell(s) the poison."));
return false;
}
}
return true;
}
|
90ebbee4-de0f-4b5f-819a-5a7b12e9d00c
| 7
|
@Override
public boolean invoke(MOB mob, List<String> commands, Physical givenTarget, boolean auto, int asLevel)
{
final MOB target=this.getTarget(mob,commands,givenTarget);
if(target==null)
return false;
if(!super.invoke(mob,commands,givenTarget,auto,asLevel))
return false;
boolean success=proficiencyCheck(mob,0,auto);
if(success)
{
invoker=mob;
final CMMsg msg=CMClass.getMsg(mob,target,this,verbalCastCode(mob,target,auto),auto?"":L("^S<S-NAME> invoke(s) the void at <T-NAMESELF>.^?"));
if(mob.location().okMessage(mob,msg))
{
mob.location().send(mob,msg);
if(msg.value()<=0)
{
if(target.location()==mob.location())
{
target.location().show(target,null,CMMsg.MSG_OK_ACTION,L("<S-NAME> stand(s) dazed and quiet!"));
success=maliciousAffect(mob,target,asLevel,0,-1)!=null;
}
}
}
}
else
return maliciousFizzle(mob,target,L("<S-NAME> invoke(s) at <T-NAMESELF>, but the spell fizzles."));
// return whether it worked
return success;
}
|
589dd7e0-fbf1-44cf-82dd-e8a459359b05
| 3
|
public void run() {
Object o;
try {
while ((o = obInputStream.readObject()) != null) {
Order rOrder = (Order) o;
controllerCoustomerShop.setreceivedOrder(rOrder);
}
} catch (ClassNotFoundException | IOException e) {
e.printStackTrace();
} finally {
try {
obInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
|
79e1a25a-155b-4460-a538-0cd08663a5df
| 0
|
public String getCalle() {
return Calle;
}
|
b5759046-3d3e-40ad-badf-eefefda8310a
| 8
|
public int compare(Problem a, Problem b) {
int result = 0;
Problem pa = (Problem)a;
Problem pb = (Problem)b;
if (sortField.equals("host_name")) {
result = pa.getHost().getHostName().compareTo(pb.getHost().getHostName());
}
else if (sortField.equals("pretty_name") || sortField.equals("server_name")) {
result = pa.getHost().getNagiosSource().compareTo(pb.getHost().getNagiosSource());
}
else {
Service pas = pa.getService();
Service pbs = pb.getService();
if (pas != null && pbs != null)
{
if (sortNumeric)
result = (int)(Long.valueOf(pbs.getParameter(sortField)) - Long.valueOf(pas.getParameter(sortField)));
else
result = pas.getParameter(sortField).compareTo(pbs.getParameter(sortField));
}
else
{
Host pah = pa.getHost();
Host pbh = pb.getHost();
if (sortNumeric)
result = (int)(Long.valueOf(pbh.getParameter(sortField)) - Long.valueOf(pah.getParameter(sortField)));
else
result = pah.getParameter(sortField).compareTo(pbh.getParameter(sortField));
}
}
if (sortReverse)
result = -result;
return result;
}
|
39882611-8602-4dc0-8aa9-d228c4b37114
| 9
|
public static byte[] decodeBytes(byte[] encdata, int encoff, int enclen, com.grey.base.utils.ByteChars arrh)
{
if (enclen == 0) return null;
int enclimit = encoff + enclen;
int rawoff = 0;
int datalimit = enclimit;
int paddinglen = 0;
int linecnt = 0;
// count pad chars - there's no legal encoded sequence that consists entirely of padding, so no need to test for loop termination
while (encdata[datalimit - 1] == PADCHAR)
{
paddinglen++;
datalimit--;
}
// count the number of line breaks
for (int idx = encoff; idx != datalimit; idx++)
{
if (encdata[idx] == CRLF1)
{
linecnt++;
idx++; //skip past the following CRLF2 as well
}
}
// now we can work out the size of the final decoded byte buffer
int rawlen = (((enclen - (linecnt * 2)) / UNITCHARS) * UNITBYTES) - paddinglen;
byte[] rawdata;
if (arrh != null)
{
arrh.ensureCapacity(arrh.ar_len + rawlen);
rawdata = arrh.ar_buf;
rawoff = arrh.ar_off + arrh.ar_len;
arrh.ar_len += rawlen;
}
else
{
rawdata = new byte[rawlen];
}
int rawlimit = rawoff + rawlen;
int ridx = rawoff;
int eidx = encoff;
while (eidx != enclimit)
{
if (encdata[eidx] == CRLF1)
{
eidx += 2;
continue;
}
// no need to test for PADCHAR as a special case, as it's map64 slot already returns zero
int c1 = map64[encdata[eidx++]];
int c2 = map64[encdata[eidx++]];
int c3 = map64[encdata[eidx++]];
int c4 = map64[encdata[eidx++]];
int unitval = (c1 << 18) | (c2 << 12) | (c3 << 6) | c4;
// there can be at most 2 pad chars, so we'll definitely output at least one byte, but must test for next two
rawdata[ridx++] = (byte)(unitval >> 16);
if (ridx != rawlimit)
{
rawdata[ridx++] = (byte)(unitval >> 8);
if (ridx != rawlimit) rawdata[ridx++] = (byte)(unitval);
}
}
return rawdata;
}
|
359d30e4-c464-45c7-88d9-e0abd11cb134
| 6
|
public static void main(String[] argv)
{
try
{
Controllers.create();
}
catch (Exception e)
{
e.printStackTrace();
System.exit(0);
}
int count = Controllers.getControllerCount();
System.out.println(count + " Controllers Found");
for (int i = 0; i < count; i++)
{
Controller controller = Controllers.getController(i);
System.out.println(controller.getName());
if (controller.getName().contains("Logitech Dual Action"))
//if (controller.getName().contains("Joystick"))
{
joystick = controller;
System.out.println("Gamepad found at index " + i);
break;
}
}
if (joystick == null)
{
System.out.println("Gamepad not found");
System.exit(0);
}
buttonCount = joystick.getButtonCount();
boolean running = true;
while (running)
{
try
{
Thread.sleep(100);
}
catch (Exception e)
{
}
update();
}
}
|
024a8586-e922-470a-a192-fa4b891943df
| 7
|
static AdjGraph segmentArrangement(Line[] segs, List<Point> ps) {
int n = segs.length;
TreeSet<Point> set = new TreeSet<Point>(); // JavaのリストにはC++のuniqueがないので…
for (int i = 0; i < n; i++) {
set.add(segs[i].a);
set.add(segs[i].b);
for (int j = i + 1; j < n; j++) {
if (intersectsSS(segs[i].a, segs[i].b, segs[j].a, segs[j].b)) {
// assert !intersectsSS(segs[i].a, segs[j].a, segs[i].b, segs[i].b);
set.add(crosspointLL(segs[i].a, segs[i].b, segs[j].a, segs[j].b));
}
}
}
ps.addAll(set);
AdjGraph g = new AdjGraph(ps.size());
class CP implements Comparable<CP> { // JAVAにpairはない!!!
final int i;
final double d;
CP(int i, double d) {
this.i = i;
this.d = d;
}
@Override
public int compareTo(CP o) {
return (int) Math.signum(d - o.d);
}
}
ArrayList<CP> list = new ArrayList<CP>(ps.size());
for (int i = 0; i < n; i++) {
list.clear();
for (int j = 0; j < ps.size(); j++) {
if (intersectsSP(segs[i].a, segs[i].b, ps.get(j))) list.add(new CP(j,
segs[i].a.distanceSq(ps.get(j))));
}
Collections.sort(list);
for (int j = 0; j + 1 < list.size(); j++) {
int a = list.get(j).i;
int b = list.get(j + 1).i;
g.addEdge(new Edge(a, b, ps.get(a).distance(ps.get(b))));
}
}
return g;
}
|
87b69114-2710-443d-8b53-46f58be226ba
| 9
|
@Override
public List<Map<String, ?>> Listar_dat_actual(String ID_TRABAJADOR) {
List<Map<String, ?>> lista = new ArrayList<Map<String, ?>>();
try {
this.cnn = FactoryConnectionDB.open(FactoryConnectionDB.ORACLE);
String sql = "SELECT * FROM RHVD_NEW_TRABAJADOR \n"
+ "WHERE ID_TRABAJADOR='" + ID_TRABAJADOR + "' \n"
+ " and rownum=1";
ResultSet rs = this.cnn.query(sql);
if (rs.next()) {
Map<String, Object> rec = new HashMap<String, Object>();
for (int i = 1; i < 75; i++) {
if (rs.getString(i) == null) {
rec.put("col" + i, "SIN DATOS");
} else {
rec.put("col" + i, rs.getString(i));
}
}
lista.add(rec);
}
rs.close();
} catch (SQLException e) {
throw new RuntimeException(e.getMessage());
} catch (Exception e) {
throw new RuntimeException("ERROR");
} finally {
try {
this.cnn.close();
} catch (Exception e) {
}
}
return lista;
}
|
eb16bd3a-e210-455d-85b7-a073e489d3a7
| 8
|
static Method[] getMethodList(Class clazz) {
Method[] methods = null;
try {
// getDeclaredMethods may be rejected by the security manager
// but getMethods is more expensive
if (!sawSecurityException)
methods = clazz.getDeclaredMethods();
} catch (SecurityException e) {
// If we get an exception once, give up on getDeclaredMethods
sawSecurityException = true;
}
if (methods == null) {
methods = clazz.getMethods();
}
int count = 0;
for (int i=0; i < methods.length; i++) {
if (sawSecurityException
? methods[i].getDeclaringClass() != clazz
: !Modifier.isPublic(methods[i].getModifiers()))
{
methods[i] = null;
} else {
count++;
}
}
Method[] result = new Method[count];
int j=0;
for (int i=0; i < methods.length; i++) {
if (methods[i] != null)
result[j++] = methods[i];
}
return result;
}
|
e5e9be7d-aa23-4628-81f5-797e4b906c21
| 2
|
public GeometricNodeEnumeration(Node n){
if(sNLE == null){
sNLE = new GeometricNodeListEnumeration(n);
}
else{
sNLE.resetForNode(n);
}
if(sNLE.hasMoreElements()){
nI = sNLE.nextElement().iterator();
}
}
|
854f7fd1-d9f5-4ccc-adb9-8d19bbca6927
| 9
|
public void determineValues(Instances inst) {
int i;
AttributeStats stats;
int attIdx;
int min;
int max;
int count;
m_AttIndex.setUpper(inst.numAttributes() - 1);
attIdx = m_AttIndex.getIndex();
// init names
m_Values = new HashSet();
if (inst == null)
return;
// number of values to retain
stats = inst.attributeStats(attIdx);
if (m_Invert)
count = stats.nominalCounts.length - m_NumValues;
else
count = m_NumValues;
// out of bounds? -> fix
if (count < 1)
count = 1; // at least one value!
if (count > stats.nominalCounts.length)
count = stats.nominalCounts.length; // at max the existing values
// determine min/max occurences
Arrays.sort(stats.nominalCounts);
if (m_LeastValues) {
min = stats.nominalCounts[0];
max = stats.nominalCounts[count - 1];
}
else {
min = stats.nominalCounts[(stats.nominalCounts.length - 1) - count + 1];
max = stats.nominalCounts[stats.nominalCounts.length - 1];
}
// add values if they are inside min/max (incl. borders) and not more than count
stats = inst.attributeStats(attIdx);
for (i = 0; i < stats.nominalCounts.length; i++) {
if ( (stats.nominalCounts[i] >= min) && (stats.nominalCounts[i] <= max) && (m_Values.size() < count) )
m_Values.add(inst.attribute(attIdx).value(i));
}
}
|
6353eefd-3b8d-4090-aa33-b4e17f81c4ff
| 2
|
private ByteBuffer getReader(int bytes)
{
ByteBuffer reader = buffers[readerIndex];
if (readerPosition + bytes > reader.limit())
{
if (readerPosition == reader.limit()) {
reader = nextReader();
}
else {
reader = nextCompactedReader(bytes);
}
}
return reader;
}
|
2bfcef95-6597-4e80-84f7-8ed530a9785b
| 3
|
public void run()
{
try
{
this.MPrio.acquire();
this.MReading.acquire();
this.MPrioR.acquire();
if(this.counter == 0)
this.MWriting.acquire();
this.counter++;
this.MPrioR.release();
this.MReading.release();
System.out.println("Lecture");
Thread.sleep(100);
this.MPrioR.acquire();
this.counter--;
if(this.counter == 0)
this.MWriting.release();
this.MPrioR.release();
this.MPrio.release();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
|
6ace6061-b805-4908-b64d-93a977d414de
| 1
|
@Override
public Message postMessage(Message msg) throws JSONException, BadResponseException {
Representation r = new JsonRepresentation(msg.toJSON());
r = serv.postResource("intervention/" + interId + "/message", msg.getUniqueID(), r);
Message message = null;
try {
message = new Message(new JsonRepresentation(r).getJsonObject());
} catch (IOException e) {
e.printStackTrace();
}
return message;
}
|
ea92f476-11d2-429e-80f7-ff0b57c28019
| 6
|
public Jagd(JSONObject setup) {
super("Wörterjagd");
try {
letterMin = setup.getInt("min");
} catch (JSONException e) {
}
try {
letterMax = setup.getInt("max");
} catch (JSONException e) {
}
try {
percent = setup.getInt("Prozent");
} catch (JSONException e) {
}
try {
luck = setup.getBoolean("Versuchen");
} catch (JSONException e) {
}
if (percent > 100) {
percent = 100;
}
if (percent < 0) {
percent = 0;
}
}
|
6fbd2054-1d6c-49a5-9d2a-c6a3d14b4e48
| 0
|
public String getCode() {
return code;
}
|
a9f10a39-9b05-45f5-bde2-239d28967cb9
| 9
|
private void finishText() {
if (currentText != null) {
String strValue = currentText.toString();
if (currentTextContent != null) {
if (DefaultXmlNames.ELEMENT_Unicode.equals(insideElement)) {
currentTextContent.setText(strValue);
}
else if (DefaultXmlNames.ELEMENT_PlainText.equals(insideElement)) {
currentTextContent.setPlainText(strValue);
}
}
if (metaData != null) {
if (DefaultXmlNames.ELEMENT_Creator.equals(insideElement)) {
metaData.setCreator(strValue);
}
else if (DefaultXmlNames.ELEMENT_Comments.equals(insideElement)) {
metaData.setComments(strValue);
}
else if (DefaultXmlNames.ELEMENT_Created.equals(insideElement)) {
metaData.setCreationTime(parseDate(strValue));
}
else if (DefaultXmlNames.ELEMENT_LastChange.equals(insideElement)) {
metaData.setLastModifiedTime(parseDate(strValue));
}
}
currentText = null;
}
}
|
02c49bd7-236c-40a3-b3b3-b30c73722b0b
| 3
|
public static ProgressRateEnumeration fromString(String v) {
if (v != null) {
for (ProgressRateEnumeration c : ProgressRateEnumeration.values()) {
if (v.equalsIgnoreCase(c.toString())) {
return c;
}
}
}
throw new IllegalArgumentException(v);
}
|
b678dcc7-f6c6-43a3-b96a-608c3cd37668
| 6
|
@Override
public void run() {
long lastTime = System.nanoTime();
double nsPerTick = 1000000000D / 60D;
long lastTimer = System.currentTimeMillis();
delta = 0D;
while (running) {
long now = System.nanoTime();
delta += (now - lastTime) / nsPerTick;
lastTime = now;
// If you want to limit frame rate, shouldRender = false
shouldRender = false;
// If the time between ticks = 1, then various things (shouldRender = true, keeps FPS locked at UPS)
while (delta >= 1) {
ticks++;
tick();
delta -= 1;
shouldRender = true;
}
if (!limitFrameRate && ticks > 0)
shouldRender = true;
// If you should render, render!
if (shouldRender) {
frames++;
render();
}
// Reset stuff every second for the new "FPS" and "UPS"
if (System.currentTimeMillis() - lastTimer >= 1000) {
lastTimer += 1000;
FPS = frames;
UPS = ticks;
frames = 0;
ticks = 0;
frame.setTitle(TITLE + " FPS: " + FPS + " UPS: " + UPS);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.