text stringlengths 14 410k | label int32 0 9 |
|---|---|
@Override
public void handle(HttpRequest request, HttpResponse response,
HttpContext context) throws HttpException, IOException {
String method = request.getRequestLine().getMethod()
.toUpperCase(Locale.ENGLISH);
if (!method.equals("GET") && !method.equals("HEAD")
&& !method.equals("POST")) {
throw new MethodNotSupportedException(method
+ " method not supported");
}
String target = request.getRequestLine().getUri();
String key = target.substring(5);
if(contents.containsKey(key)) {
String contentType = "text";
if(key.endsWith("css"))
contentType = "text/css";
else if (key.endsWith("js"))
contentType = "text/javascript";
else if (key.endsWith("woff"))
contentType = "application/x-woff";
StringEntity entity = new StringEntity(new String(contents.get(key)), ContentType.parse(contentType));
response.setEntity(entity);
response.setStatusCode(200);
} else {
response.setStatusCode(404);
}
} | 7 |
public String displayGW_ShipMMSI (List<Integer> mm,int totalDigits) {
StringBuilder sb=new StringBuilder();
int a,digitCounter=0;
for (a=0;a<6;a++) {
// High nibble
int hn=(mm.get(a)&240)>>4;
// Low nibble
int ln=mm.get(a)&15;
// The following nibble
int followingNibble;
// Look at the next byte for this unless this is the last byte
if (a<5) followingNibble=(mm.get(a+1)&240)>>4;
else followingNibble=0;
boolean alternate;
// Low nibble
// If the nibble following the low nibble (which is in the next byte) is 0x8 or greater
// then we use the alternate numbering method
if (followingNibble>=0x8) alternate=true;
else alternate=false;
sb.append(convertMMSI(ln,alternate));
digitCounter++;
// Once digit counter is totalDigits then we are done
if (digitCounter==totalDigits) return sb.toString();
// High nibble
// If the nibble following the high nibble (which is the low nibble) is 0x8 or greater
// then we use the alternate numbering scheme
if (ln>=0x8) alternate=true;
else alternate=false;
sb.append(convertMMSI(hn,alternate));
digitCounter++;
// Once the digit counter is totalDigits then we are done
if (digitCounter==totalDigits) return sb.toString();
}
return sb.toString();
} | 6 |
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Paciente)) {
return false;
}
Paciente other = (Paciente) object;
if ((this.idPaciente == null && other.idPaciente != null) || (this.idPaciente != null && !this.idPaciente.equals(other.idPaciente))) {
return false;
}
return true;
} | 5 |
@Override
public void run() {
ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
lastSample = System.nanoTime();
lastCPUSample = threadMXBean.getThreadCpuTime(monitoredThread.getId());
while (true) {
try {
Thread.sleep(interval);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
String currentMethod = getCurrentMethod();
long currentSample = System.nanoTime();
long currentCPUSample = threadMXBean.getThreadCpuTime(monitoredThread.getId());
addMeasurementsIfStillInMethod(currentMethod, currentSample, currentCPUSample);
lastMethod = currentMethod;
lastSample = currentSample;
overhead += System.nanoTime() - currentSample;
}
} | 2 |
public static TruthValue strengthenTruthValue(TruthValue tv1, TruthValue tv2) {
if (((tv2 == Logic.TRUE_TRUTH_VALUE) ||
(tv2 == Logic.FALSE_TRUTH_VALUE)) &&
((tv1 == Logic.DEFAULT_TRUE_TRUTH_VALUE) ||
(tv1 == Logic.DEFAULT_FALSE_TRUTH_VALUE))) {
if ((tv1 == Logic.TRUE_TRUTH_VALUE) ||
(tv1 == Logic.DEFAULT_TRUE_TRUTH_VALUE)) {
return (Logic.TRUE_TRUTH_VALUE);
}
if ((tv1 == Logic.FALSE_TRUTH_VALUE) ||
(tv1 == Logic.DEFAULT_FALSE_TRUTH_VALUE)) {
return (Logic.FALSE_TRUTH_VALUE);
}
}
return (tv1);
} | 8 |
private final AStarNode obtainOpenWithLowestCost() {
Iterator<Entry<Float, Vector<AStarNode>>> entries = open.entrySet().iterator();
if (!entries.hasNext())
return null;
Vector<AStarNode> costEntry = entries.next().getValue();
int lastCostEntry = costEntry.size() - 1;
AStarNode lowestCostNode = costEntry.get(lastCostEntry);
costEntry.remove(lastCostEntry);
if (costEntry.size() == 0)
entries.remove();
isOpen[(int)lowestCostNode.getLocation().getX()][(int)lowestCostNode.getLocation().getY()] = false;
return lowestCostNode;
} | 2 |
public void commit() {
Connection conn = getConnection();
try{
conn.setAutoCommit(false);
for(EntityBase ent : added.keySet() )
{
switch(ent.getOperation())
{
case insert:
{
added.get(ent).persistAdd(ent);
}
case delete:
{
added.get(ent).persistDelete(ent);
}
case update:
{
added.get(ent).persistUpdate(ent);
}
}
}
conn.commit();
conn.setAutoCommit(true);
}catch(SQLException ex)
{
ex.printStackTrace();
}
} | 5 |
private void detectAnnotation(Method method, int index, Annotation annotation, Map<String, Integer> paramIndexes,
Map<String, Integer> batchParamIndexMap, Class<?>[] paramTypes) throws DaoGenerateException {
Class<? extends Annotation> annotationType = annotation.annotationType();
if (Param.class.equals(annotationType)) {
Param param = (Param) annotation;
String value = param.value();
if (RESULT_PARAM_VALUE.equals(value)) {
throw new DaoGenerateException("方法[" + method + "]配置错误:不能使用@Param(\"" + RESULT_PARAM_VALUE
+ "\")注解作为参数:\"" + RESULT_PARAM_VALUE + "\"为系统保留关键字");
}
addParam(value, index, paramIndexes);
}
if (BatchParam.class.equals(annotationType) && batchParamIndexMap != null) {
BatchParam param = (BatchParam) annotation;
String value = param.value();
if (!ClassHelper.isTypeArray(paramTypes[index]) && !ClassHelper.isTypeList(paramTypes[index])) {
throw new DaoGenerateException("方法[" + method + "]配置错误:@BatchParam只能配置在数组或者List实现类上");
}
addBatchParam(value, index, batchParamIndexMap);
}
if (GenericTable.class.equals(annotationType)) {
GenericTable genericTable = (GenericTable) annotation;
int order = genericTable.index();
addGenericTable(index, order);
}
} | 9 |
public static ClauseSet get(File file) {
ClauseSet clauseSet = new ClauseSet();
Scanner scan = null;
try {
scan = new Scanner(file);
while (scan.nextLine().startsWith("c")) {/* skip commments */
}
Clause clause = new Clause();
while (scan.hasNextInt()) {
int var = scan.nextInt();
if (var == 0) {
clauseSet.add(clause);
clause = new Clause();
} else {
clause.add(var);
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (NoSuchElementException e) {
System.out.println("No DIMACS format");
return null;
} finally {
scan.close();
}
return clauseSet;
} | 5 |
public void loadProperties(String fileName) throws FileNotFoundException {
InputStream in = null;
try {
in = PropertiesReader.class.getClassLoader().getResourceAsStream(fileName);
if(in == null ){
in = new FileInputStream(System.getProperty("user.dir")+ File.separator+fileName);
}
if(in != null){
properties.load(in);
String value = "";
for(String key : properties.stringPropertyNames()){
value = "";
if(StringUtils.isBlank(key)){
continue;
}
value = (String) properties.get(key);
if(StringUtils.isNotBlank(value)){
// value = RegexUtil.replayWithSysProps(value, sys_properties);
value = replaceWithUsrProps(value, properties);
}
properties.setProperty(key, value);
}
}
}catch (FileNotFoundException e){
throw e;
}
catch (Exception e) {
log.error(e);
}finally {
IOUtils.close(in);
}
} | 7 |
public CommandWarn(CreeperWarningMain plugin) {
this.plugin = plugin;
this.pds = new playerDataSave(plugin);
} | 0 |
protected boolean collidingWithGround() {
if(!collidable)
return false;
if(!crouch || !crouchable){
if(game.getCurrentLevel().isBlockAtPixelCollidable(x,y-(height/4)) ){
return true;
}
} else if(crouchable){
if(game.getCurrentLevel().isBlockAtPixelCollidable(x,y-(height/4)+(int)((tempHeight/crouchAmount)*1.5)) ){
return true;
}
}
return false;
} | 6 |
public String toString() {
if (kind.equals(Kind.ERROR)) {
return String.format(error, kind, lexeme, lineNumber, charPosition);
}
if (kind.equals(Kind.INTEGER) || kind.equals(Kind.FLOAT)
|| kind.equals(Kind.IDENTIFIER)) {
return String.format(responseValue, kind, lexeme, lineNumber,
charPosition);
}
return String.format(responseNoValue, kind, lineNumber, charPosition);
} | 4 |
public AStarNode obtainOpenNodeWithLowestCost() {
Iterator<Entry<Float, Vector<AStarNodeVector3D>>> entries = open.entrySet().iterator();
if (!entries.hasNext())
return null;
Vector<AStarNodeVector3D> costEntry = entries.next().getValue();
int lastCostEntry = costEntry.size() - 1;
AStarNode lowestCostNode = costEntry.get(lastCostEntry);
costEntry.remove(lastCostEntry);
if (costEntry.size() == 0)
entries.remove();
removeOpen(lowestCostNode);
return lowestCostNode;
} | 2 |
public void setComando(List<?> list)
{
for(PComando e : this._comando_)
{
e.parent(null);
}
this._comando_.clear();
for(Object obj_e : list)
{
PComando e = (PComando) obj_e;
if(e.parent() != null)
{
e.parent().removeChild(e);
}
e.parent(this);
this._comando_.add(e);
}
} | 4 |
@Test
public void testRecursion() {
Recursion recursion = new Recursion();
assertTrue(recursion.nthFibonacci(0) == 0);
assertTrue(recursion.nthFibonacci(1)==1);
assertTrue(recursion.nthFibonacci(2)==1);
assertTrue(recursion.nthFibonacci(3)==2);
assertTrue(recursion.nthFibonacci(10)==55);
Set<String> stringPermutations = recursion.getPermutations("", "Tes");
assertTrue(stringPermutations.contains("Tes"));
assertTrue(stringPermutations.contains("seT"));
assertTrue(stringPermutations.contains("Tse"));
assertTrue(stringPermutations.contains("sTe"));
assertTrue(stringPermutations.contains("esT"));
assertTrue(stringPermutations.contains("eTs"));
Set<String> set = new HashSet<String>();
set.add("hi");
set.add("bye");
set.add("lol");
Set<Set<String>> setSet = recursion.getSubsets(set); //6 sets. Hi, Bye, Lol, Hi-Bye, Bye-Lol, Hi-Lol
Set<String> set1 = new HashSet<String>();
set1.add("hi");
set1.add("bye");
Set<String> set2 = new HashSet<String>();
set2.add("hi");
set2.add("lol");
Set<String> set3 = new HashSet<String>();
set3.add("bye");
set3.add("lol");
Set<String> set4 = new HashSet<String>();
set4.add("hi");
Set<String> set5 = new HashSet<String>();
set5.add("bye");
Set<String> set6 = new HashSet<String>();
set6.add("lol");
assertTrue(setSet.contains(set1));
assertTrue(setSet.contains(set2));
assertTrue(setSet.contains(set3));
assertTrue(setSet.contains(set4));
assertTrue(setSet.contains(set5));
assertTrue(setSet.contains(set6));
Set<String> parenthesis = recursion.printParenthesis(3);
assertTrue(parenthesis.contains("()()()"));
assertTrue(parenthesis.contains("((()))"));
assertTrue(parenthesis.contains("(()())"));
assertTrue(parenthesis.contains("()(())"));
assertTrue(parenthesis.contains("(())()"));
Integer[][] grid = new Integer[5][5];
for(int i=0; i<5; i++){
for(int j=0; j<5; j++){
grid[i][j] = Recursion.COLOR_BLUE;
}
}
for(int i=0; i<5; i++){
grid[0][i] = Recursion.COLOR_RED;
grid[4][i] = Recursion.COLOR_RED;
grid[i][0] = Recursion.COLOR_RED;
grid[i][4] = Recursion.COLOR_RED;
}
recursion.paintFill(3, 2, Recursion.COLOR_RED, grid);
for(int i=0; i<5; i++){
for(int j=0; j<5; j++){
assertTrue(grid[i][j] == Recursion.COLOR_RED);
}
}
assertTrue(recursion.waysToCreateAmount(1)==1);
assertTrue(recursion.waysToCreateAmount(5)==2);
assertTrue(recursion.waysToCreateAmount(10)==4);
assertTrue(recursion.printQueens(8));
//Commenting out because it takes forever to compute false
//assertFalse(recursion.printQueens(9));
} | 5 |
public void mouseDoubleClicked(Point p){
//update current index
curr=mygraph.findIndex(p);
//pop up the curr location's property
if(curr!=-1){
JOptionPane mypane=new JOptionPane();
String display="Name:"+getCurrName()+"\n(x,y)=("
+getCurrPoint().getX()+","+getCurrPoint().getY()+")\nID="+getCurrID()
+"\nNew location name:";
String s = mypane.showInputDialog(display);
if(s==null){
return;
}
while(s.length()==0){
display="Invalid new Name!\nName:"+getCurrName()+"\n(x,y)=("
+getCurrPoint().getX()+","+getCurrPoint().getY()+")\nID="+getCurrID()
+"\nNew location name:";
s = mypane.showInputDialog(display);
if(s==null){
return;
}
}
setCurrName(s);
}
} | 4 |
protected void doAction(int type, int bonus) {
if (!mapGenerate)
if (type == 1) {
isAttack = true;
attackDamage = getAttack(bonus);
if (Parameters.getInstance().isDebug())
logger.info("Attack damage = " + attackDamage);
} else if (type == 2) {
getAtk(bonus);
} else if (type == 3) {
getDef(bonus);
} else if (type == 4) {
getHeal(bonus);
}
} | 6 |
public void push(ArrayList<Card> list, int card) {
try {
list.add(this.card[card]);
} catch (Exception ex) {
// if arrayList becomes empty handle exception here...
}
} | 1 |
public boolean addFFmpegArgument(FFmpegArguments arguments)
{
boolean ret = false;
if (connection == null
|| arguments == null || arguments.getName() == null || arguments.getArguments() == null || arguments.getFileExtension() == null
|| hasFFmpegArgumentsName(arguments.getName()))
return ret;
try {
PreparedStatement stat = connection.prepareStatement("INSERT INTO " + FFmpegArgumentsTableName + " VALUES(?, ?, ?)");
stat.setString(1, arguments.getName());
stat.setString(2, arguments.getArguments());
stat.setString(3, arguments.getFileExtension());
stat.execute();
stat.close();
if (hasFFmpegArgumentsName(arguments.getName()))
ret = true;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return ret;
} | 8 |
@Override
public double[] get2DData(int px, int pz, int sx, int sz)
{
double[] da = a.get2DData(px, pz, sx, sz);
double[] db;
if(a == b)
db = da;
else
db = b.get2DData(px, pz, sx, sz);
int s = sx*sz;
for(int i = 0; i < s; i++)
da[i] = da[i] < db[i] ? da[i] : db[i];
return da;
} | 3 |
private Run prepInsertionRun(int x, int y) {
Run currentRun = getFirst();
int insertionPoint = wrap(x, y);
int position = 0;
int totalLength = width * height;
while(position < totalLength) {
if(insertionPoint > currentRun.getRunLength() + position - 1) {
position += currentRun.getRunLength();
currentRun = currentRun.getNext();
continue;
}
break;
}
if((position >= totalLength) || (currentRun.getRunType() != Ocean.EMPTY))
return null; // Either this is a run of type EMPTY or insertionPoint is out of bounds
Run start = currentRun.getPrev();
int currentLength = currentRun.getRunLength();
int currentType = Ocean.EMPTY;
int currentHunger = -1;
insertAfter(start, new Run(insertionPoint - position, currentType, currentHunger));
insertAfter(currentRun, new Run(currentLength - currentRun.getPrev().getRunLength() - 1, currentType, currentHunger));
currentRun.setRunLength(1);
return currentRun;
} | 4 |
List<CourseListing> getByType(String selectedType) {
List<CourseListing> courseListing = new ArrayList<CourseListing>();
try {
//Connect to database
conn = DriverManager.getConnection(url, userName, password);
stmt = conn.createStatement();
ResultSet rset = null, rset1 = null;
PreparedStatement pstmt = null, pstmt1 = null;
pstmt = conn.prepareStatement("select * FROM CourseProduct "
+ "INNER JOIN Course "
+ "ON CourseProduct.number=Course.number "
+ "inner join Product "
+ "on CourseProduct.P_ID=Product.P_ID "
+ "where type = ? "
+ "group by Course.number");
pstmt.setString(1, selectedType);
rset = pstmt.executeQuery();
while (rset.next()) {
String tempNumber = rset.getString("number");
pstmt1 = conn.prepareStatement("select distinct product FROM "
+ "CourseProduct INNER JOIN Course "
+ "ON CourseProduct.number=Course.number "
+ "inner join Product "
+ "on CourseProduct.P_ID=Product.P_ID "
+ "WHERE "
+ "Course.number = ? order by product");
pstmt1.setString(1, tempNumber);
rset1 = pstmt1.executeQuery();
String tempProduct = "";
while (rset1.next()) {
tempProduct += " " + rset1.getString("product") + ",";
}
tempProduct = tempProduct.substring(0, tempProduct.length() - 1);
courseListing.add(new CourseListing(
rset.getDouble("price"),
rset.getString("number"),
rset.getString("name"),
rset.getString("location"),
rset.getString("unit"),
rset.getString("duration"),
rset.getString("type"),
rset.getString("role"),
rset.getString("category"),
rset.getString("maxNumStudents"),
rset.getString("superProduct"),
rset.getString("subProduct"),
tempProduct));
}
} catch (SQLException e) {
response = "SQLException: " + e.getMessage();
while ((e = e.getNextException()) != null) {
response = e.getMessage();
}
} finally {
try {
if (stmt != null) {
stmt.close();
}
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
response = "SQLException: " + e.getMessage();
while ((e = e.getNextException()) != null) {
response = e.getMessage();
}
}
}
this.response = "Done";
return courseListing;
} | 8 |
final public void setFooter(String firstLine, String... additionalLines) {
footer.clear();
footer.add(firstLine);
if (additionalLines != null) {
for (String line : additionalLines) {
footer.add(line);
}
}
onChange();
} | 2 |
public ArrayList<Gridspot> findVertices(Gridspot take, Gridspot goal)
{
ArrayList<Gridspot> retur = new ArrayList<Gridspot>();
int x = take.getXIndex(); int y = take.getYIndex();
if (!getG(x+1,y).occupied || getG(x+1,y) == goal )
{
retur.add(getG(x+1,y));
}
if (!getG(x-1,y).occupied || getG(x-1,y) == goal)
{
retur.add(getG(x-1,y));
}
if (!getG(x,y+1).occupied || getG(x,y+1) == goal)
{
retur.add(getG(x,y+1));
}
if (!getG(x,y-1).occupied || getG(x,y-1) == goal)
{
retur.add(getG(x,y-1));
}
return retur;
} | 8 |
public boolean irrigated(int r, int c)
{
boolean temp = false;
if (c > 0)
{
temp = temp || verticalRivers[r][c-1];
}
if (c < cols - 1)
{
temp = temp || verticalRivers[r][c];
}
if (r > 0)
{
temp = temp || horizontalRivers[r-1][c];
}
if (r < rows - 1)
{
temp = temp || horizontalRivers[r][c];
}
return temp;
} | 8 |
public static int[] generate(int n) {
Random random = new Random();
int[] list = new int[n];
for (int i = 0; i < n; ++i) {
list[i] = random.nextInt() % n;
}
return list;
} | 1 |
protected int getCorrectDirToOriginRoom(Room R, int v)
{
if(v<0)
return -1;
int dir=-1;
Room R2=null;
Exit E2=null;
int lowest=v;
for(int d=Directions.NUM_DIRECTIONS()-1;d>=0;d--)
{
R2=R.getRoomInDir(d);
E2=R.getExitInDir(d);
if((R2!=null)&&(E2!=null)&&(E2.isOpen()))
{
final int dx=commonRoomSet.indexOf(R2);
if((dx>=0)&&(dx<lowest))
{
lowest=dx;
dir=d;
}
}
}
return dir;
} | 7 |
public String getAnswer() throws Exception {
Map<Integer,Integer> cache = new HashMap<Integer, Integer>();
Stack<Integer> currChain = new Stack<Integer>();
int[] digitFactorials = getDigitFactorials();
int retVal = 0;
for (int i = 1;i<1000000;i++) {
if (cache.containsKey(i))
continue;
currChain.push(i);
int lastElement = getNextItem(i, digitFactorials);
while (!currChain.contains(lastElement) && !cache.containsKey(lastElement)) {
currChain.push(lastElement);
lastElement = getNextItem(lastElement, digitFactorials);
}
int additionalAmount = 0;
if (cache.containsKey(lastElement)) {
additionalAmount = cache.get(lastElement);
} else {
//every element in the cycle will have same cycle size, so pop all of them off.
additionalAmount = currChain.size() - currChain.indexOf(lastElement);
boolean found = false;
while (!found) {
int currVal = currChain.pop();
found = (currVal == lastElement);
cache.put(currVal,additionalAmount);
}
}
int n = 1;
while (!currChain.empty()) {
cache.put(currChain.pop(),n+additionalAmount);
n++;
}
}
for (Integer chainLen : cache.values())
if(chainLen>=60)
retVal++;
return Integer.toString(retVal);
} | 9 |
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
throw new RuntimeException();
} | 0 |
@Test
@TestLink(externalId = "T2")
public void testFailed() {
assertTrue("Failed", false);
} | 0 |
public String encrypt(String word){
if(word == null||word.length()==0) throw new IllegalArgumentException();
String result = "";
String wordLower = word.toLowerCase();
for(int i=0; i<wordLower.length(); i++){
if(wordLower.charAt(i)<97 || wordLower.charAt(i)>122)
throw new IllegalArgumentException();
int a = (wordLower.charAt(i)-97)*this.keyA;
int b = a+this.keyB;
int k = (b%26)+97;
result += Character.toString((char)k);
}
return result;
} | 5 |
public void fillDeck()
{
int z = 0;
for(int i = 0; i < 20; i++)
{
switch (z)
{
case 0: addCard(new pieThrow()); z++; break;
case 1: addCard(new attack()); z++; break;
case 2: addCard(new fireEverything());z++;break;
case 3: addCard(new fireAllMissiles()); z++; break;
case 4: addCard(new fireAllLasers()); z++; break;
case 5: addCard(new fireAllGuns()); z++; break;
case 6: addCard(new addHardPoint()); z = 0; break;
}
}
} | 8 |
public void makePayment(int amount) {
this.balance = this.balance - amount;
} | 0 |
protected Transition createTransition(State from, State to, Node node,
Map e2t, boolean bool) {
String read = (String) e2t.get(TRANSITION_READ_NAME);
String pop = (String) e2t.get(TRANSITION_POP_NAME);
String push = (String) e2t.get(TRANSITION_PUSH_NAME);
if (read == null)
read = ""; // Allow lambda transition.
if (pop == null)
pop = ""; // Allow lambda transition.
if (push == null)
push = ""; // Allow lambda transition.
try {
return new PDATransition(from, to, read, pop, push);
} catch (IllegalArgumentException e) {
throw new DataException(e.getMessage());
}
} | 4 |
public void setDesc(String value) {
this.desc = value;
} | 0 |
public boolean isSheetExist(String sheetName){
int index = workbook.getSheetIndex(sheetName);
if(index==-1){
index=workbook.getSheetIndex(sheetName.toUpperCase());
if(index==-1)
return false;
else
return true;
}
else
return true;
} | 2 |
public void openFacts(){
int returnVal = fileChooser2.showOpenDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fileChooser2.getSelectedFile();
String filepath = file.getAbsolutePath();
factsLocation.setText(filepath);
try{
ParseXML parser = new ParseXML(filepath);
queryCase = parser.getCaseBase();
if(queryCase != null){
query = queryCase.getCases().get(0);
FactsFileText.read(new FileReader(file), file);
ActionLog.setForeground(Color.blue);
actionLog = "Facts file parsed successfully! ";
if(queryCase.getSize() > 1){
ActionLog.setForeground(Color.yellow);
actionLog += "More than one query case found. Selecting first case as query case. ";
}
ActionLog.setText(actionLog);
}
else{
ActionLog.setForeground(Color.red);
actionLog = "Facts failed to parse successfully! ";
ActionLog.setText(actionLog);
}
update();
}catch(ParserConfigurationException e){
}catch(SAXException e){
}catch(IOException e){
}
} else {
System.out.println("File access cancelled by user.");
}
} | 6 |
public void generateComb2(ArrayList<ArrayList<Integer>> result,ArrayList<Integer> list,int[] num,int target,int index){
if (target == 0){
ArrayList<Integer> temp = new ArrayList<Integer>();
for (int i = list.size()-1;i>=0;i--){
temp.add(list.get(i));
}
result.add(temp);
return;
}
else {
for (int i = index;i>=0;i--){
if (num[i]<=target&&(i==index||num[i]!=num[i+1])){
list.add(num[i]);
generateComb2(result,list,num,target-num[i],i-1);
list.remove(list.size()-1);
}
}
}
} | 6 |
public String hornGen(){
rand = new Random();
int hornRoll = (rand.nextInt(100)+1);
if(hornRoll <= 40){
horn = "Silver";
} else if(hornRoll <= 75){
horn = "Brass";
} else if(hornRoll <= 90){
horn = "Bronze";
} else if(hornRoll <= 100){
horn = "Iron";
}
return horn;
} | 4 |
private DrawableTree phyloXMLToTree(org.w3c.dom.Document doc) throws FileParseException {
Node documentRoot = doc.getDocumentElement();
Node child = documentRoot.getFirstChild();
DrawableNode root = null;
//Search for (the first) phylogeny element
while(child != null) {
if (child.getNodeType() == Node.ELEMENT_NODE && child.getNodeName().equalsIgnoreCase(XML_PHYLOGENY))
break;
child = child.getNextSibling();
}
//Child should now be 'pointing' at phylogeny element, so search within it for the first clade element
if (child == null) {
throw new FileParseException("No phylogeny tag found in XML, cannot create tree");
}
Node grandChild = child.getFirstChild();
while(grandChild != null) {
if (grandChild.getNodeType() == Node.ELEMENT_NODE && grandChild.getNodeName().equalsIgnoreCase(XML_CLADE)) {
root = new DrawableNode();
recurseAddNodes( root, grandChild );
break;
}
grandChild = grandChild.getNextSibling();
}
if (root == null) {
throw new FileParseException("No clades found in XML, cannot create tree");
}
//TODO add support for multiple trees
DrawableTree tree = new SquareTree(root);
convertDatesToBranchLengths(tree);
return tree;
} | 8 |
public void deleteTask(jpvmTaskId tid) {
if(tasks == null) return;
jpvmTaskListRecord tmp = tasks;
// Check head
if(tmp.tid.equals(tid)) {
if (iter == tmp) iter=tmp.next;
tasks = tasks.next;
num_tasks --;
return;
}
// Check body
while(tmp.next != null) {
if(tmp.next.tid.equals(tid)) {
if(iter==tmp.next) iter=tmp.next.next;
tmp.next = tmp.next.next;
num_tasks --;
return;
}
tmp = tmp.next;
}
} | 6 |
@Override
public boolean equals(Object obj)
{
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
WifiId other = (WifiId) obj;
if (BSSID == null)
{
if (other.BSSID != null)
return false;
}
else if (!BSSID.equals(other.BSSID))
return false;
if (SSID == null)
{
if (other.SSID != null)
return false;
}
else if (!SSID.equals(other.SSID))
return false;
return true;
} | 9 |
public Proceso(int pid, boolean esTiempoReal, int prioridadEstatica, ArrayList<Integer> tiempoCPU, ArrayList<Integer> tiempoIO, int tiempoEntrada) {
this.pid = pid;
this.esTiempoReal = esTiempoReal;
this.prioridadEstatica = prioridadEstatica;
this.tiemposCPU = tiempoCPU;
this.tiemposIO = tiempoIO;
/*Nos aseguramos que el ultimo tiempo del CPU y/o IO sea 0, evita problemas
con valores extranos al final de las listas*/
if (this.tiemposCPU != null) {
this.tiemposCPU.add(0);
}
if (this.tiemposIO != null) {
this.tiemposIO.add(0);
}
this.tiempoEntrada = tiempoEntrada;
this.estado = Constantes.TASK_RUNNING;
/* Si el proceso es Tiempo Real */
if (esTiempoReal) {
this.prioridadDinamica = 100;
} else {
this.prioridadDinamica = prioridadEstatica;
}
this.tiempoDurmiendo = 0;
this.esPrimerQuantum = true;
/*Calculo del cuantum*/
this.quantum = (140 - prioridadEstatica) * (prioridadEstatica < 120 ? 20 : 5);
this.quantum = java.lang.Math.min(this.quantum, tiempoCPU.get(0));
tiempoTotalDurmiendo = 0;
} | 4 |
private void moveDown() {
int[] rows = table.getSelectedRows();
DefaultTableModel model = (DefaultTableModel) table.getModel();
try {
if (model.getRowCount() >= 2) {
model.moveRow(rows[0], rows[rows.length - 1], rows[0] + 1);
table.setRowSelectionInterval(rows[0] + 1,
rows[rows.length - 1] + 1);
}
} catch (ArrayIndexOutOfBoundsException ex) {
}
} | 2 |
public static long[] getKPrimes(int k, boolean print) {
long[] primes = new long[k];
primes[0] = 2;
int currPrimeCount = 1;
for(int i=3;currPrimeCount<k;i+=2) { // even number cannot be prime
boolean isPrime = true;
long sqrt = (long) Math.sqrt(i);
for(int j=0; j<currPrimeCount && primes[j]<=sqrt; j++) {
if (i % primes[j] == 0) { // test the prime, to see if the prime is the factor of i
isPrime = false;
break;
}
}
if (isPrime) {
primes[currPrimeCount++] = i;
}
}
if(print) {
System.out.print("First " + k + "th primes are: ");
System.out.print(Arrays.toString(primes));
System.out.println();
}
return primes;
} | 6 |
public String getName() {
return name;
} | 0 |
@Override
public long split(long count, LongBitSet rightTree, PointWriter left, PointWriter right, boolean doClearBits) throws IOException {
if (left instanceof OfflinePointWriter == false ||
right instanceof OfflinePointWriter == false) {
return super.split(count, rightTree, left, right, doClearBits);
}
// We specialize the offline -> offline split since the default impl
// is somewhat wasteful otherwise (e.g. decoding docID when we don't
// need to)
int packedBytesLength = packedValue.length;
int bytesPerDoc = packedBytesLength + Integer.BYTES;
if (singleValuePerDoc == false) {
if (longOrds) {
bytesPerDoc += Long.BYTES;
} else {
bytesPerDoc += Integer.BYTES;
}
}
long rightCount = 0;
IndexOutput rightOut = ((OfflinePointWriter) right).out;
IndexOutput leftOut = ((OfflinePointWriter) left).out;
assert count <= countLeft: "count=" + count + " countLeft=" + countLeft;
countLeft -= count;
long countStart = count;
byte[] buffer = new byte[bytesPerDoc];
while (count > 0) {
in.readBytes(buffer, 0, buffer.length);
long ord;
if (longOrds) {
// A long ord, after the docID:
ord = readLong(buffer, packedBytesLength+Integer.BYTES);
} else if (singleValuePerDoc) {
// docID is the ord:
ord = readInt(buffer, packedBytesLength);
} else {
// An int ord, after the docID:
ord = readInt(buffer, packedBytesLength+Integer.BYTES);
}
if (rightTree.get(ord)) {
rightOut.writeBytes(buffer, 0, bytesPerDoc);
if (doClearBits) {
rightTree.clear(ord);
}
rightCount++;
} else {
leftOut.writeBytes(buffer, 0, bytesPerDoc);
}
count--;
}
((OfflinePointWriter) right).count = rightCount;
((OfflinePointWriter) left).count = countStart-rightCount;
return rightCount;
} | 9 |
protected void readAttribute(String name, int length, ConstantPool cp,
DataInputStream input, int howMuch) throws IOException {
if ((howMuch & KNOWNATTRIBS) != 0 && name.equals("ConstantValue")) {
if (length != 2)
throw new ClassFormatException("ConstantValue attribute"
+ " has wrong length");
int index = input.readUnsignedShort();
constant = cp.getConstant(index);
} else if (name.equals("Synthetic")) {
syntheticFlag = true;
if (length != 0)
throw new ClassFormatException(
"Synthetic attribute has wrong length");
} else if (name.equals("Deprecated")) {
deprecatedFlag = true;
if (length != 0)
throw new ClassFormatException(
"Deprecated attribute has wrong length");
} else
super.readAttribute(name, length, cp, input, howMuch);
} | 7 |
public void setCombination(int x, int y, int z){
if(x < 0 || x > dialSize){
throw new IllegalArgumentException(x +
" is not a valid combination number");
}else
this.x = x;
if(y < 0 || y > dialSize){
throw new IllegalArgumentException(y +
" is not a valid combination number");
}else
this.y = y;
if(z < 0 || z > dialSize){
throw new IllegalArgumentException(z +
" is not a valid combination number");
}else
this.z = z;
//with out this I noticed when I changed combos the lock
//would not open correctly so the top number gets reset to 0
do{
dialItr.next();
}while((Integer)dialItr.current.getValue() != 0);
currentTopNumber = (Integer)dialItr.current.getValue();
} | 7 |
private boolean inPoly(FastVector ob, double x, double y) {
int count = 0;
double vecx, vecy;
double change;
double x1, y1, x2, y2;
for (int noa = 1; noa < ob.size() - 2; noa += 2) {
y1 = ((Double)ob.elementAt(noa+1)).doubleValue();
y2 = ((Double)ob.elementAt(noa+3)).doubleValue();
if ((y1 <= y && y < y2) || (y2 < y && y <= y1)) {
//then continue tests.
vecy = y2 - y1;
if (vecy == 0) {
//then lines are parallel stop tests for this line
}
else {
x1 = ((Double)ob.elementAt(noa)).doubleValue();
x2 = ((Double)ob.elementAt(noa+2)).doubleValue();
vecx = x2 - x1;
change = (y - y1) / vecy;
if (vecx * change + x1 >= x) {
//then add to count as an intersected line
count++;
}
}
}
}
if ((count % 2) == 1) {
//then lies inside polygon
//System.out.println("in");
return true;
}
else {
//System.out.println("out");
return false;
}
//System.out.println("WHAT?!?!?!?!!?!??!?!");
//return false;
} | 8 |
public void setExceptionHandlers(final Catch[] handlers) {
if (code != null) {
code.setExceptionHandlers(handlers);
}
} | 1 |
@Test
public void findHandFromCardSet_whenFlushOrStraightPossible_returnsFlush() {
Hand hand = findHandFromCardSet(sixFlushWithStraight());
assertEquals(HandRank.Flush, hand.handRank);
assertEquals(Rank.Jack, hand.ranks.get(0));
assertEquals(Rank.Ten, hand.ranks.get(1));
assertEquals(Rank.Nine, hand.ranks.get(2));
assertEquals(Rank.Eight, hand.ranks.get(3));
assertEquals(Rank.Four, hand.ranks.get(4));
} | 0 |
private void registerAll(final Path start) throws IOException {
// register directory and sub-directories
Files.walkFileTree(start, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
throws IOException
{
if(dir.getFileName().toString().startsWith("."))
return FileVisitResult.SKIP_SUBTREE;
register(dir);
return FileVisitResult.CONTINUE;
}
});
} | 1 |
static boolean sqlQueryP(String sqlExpression) {
{ int start = 0;
int end = 0;
String operator = "";
while (Stella.$CHARACTER_TYPE_TABLE$[(int) (sqlExpression.charAt(start))] == Sdbc.KWD_WHITE_SPACE) {
start = start + 1;
}
end = start;
while (Stella.$CHARACTER_TYPE_TABLE$[(int) (sqlExpression.charAt(end))] == Sdbc.KWD_LETTER) {
end = end + 1;
}
operator = Native.string_subsequence(sqlExpression, start, end);
return (Stella.stringEqualP(operator, "SELECT") ||
(Stella.stringEqualP(operator, "SHOW") ||
(Stella.stringEqualP(operator, "DESCRIBE") ||
(Stella.stringEqualP(operator, "EXPLAIN") ||
Stella.stringEqualP(operator, "ANALYZE")))));
}
} | 6 |
public boolean findAtNorth(int piece, int x, int y){
if(x==0 || b.get(x-1, y)==EMPTY_PIECE) return false;
else if(b.get(x-1, y)==piece) return true;
else return findAtNorth(piece,x-1,y); // there is an opponent
} // end findAtNorth | 3 |
public void dumpStrings(String filter) throws FileNotFoundException {
System.out.println("Dumping Strings");
PrintWriter writer = new PrintWriter("Ressources.txt");
for(Map.Entry<String,ArrayList<RAFFile>> file : archives.entrySet())
{
for(RAFFile rafFile : file.getValue()) {
for(ArchiveFile archiveFile : rafFile.getArchiveFiles().getArchiveFiles())
{
String filepath = archiveFile.getFilePath().toLowerCase();
String ttest = filter.toLowerCase();
if(filepath.contains(ttest))
{
writer.write(archiveFile.getFilePath()+"\n");
writer.flush();
}
}
}
}
writer.close();
} | 4 |
public static double logNormalPDF(double mu, double sigma, double x) {
if (sigma < 0) throw new IllegalArgumentException("The parameter sigma, " + sigma + ", must be greater than or equal to zero");
if (x < 0) {
return 0.0D;
} else {
return Math.exp(-0.5D * Fmath.square((Math.log(x) - mu) / sigma)) / (x * sigma * Math.sqrt(2.0D * Math.PI));
}
} | 2 |
private void doStuff(Point temp){
if(!ifOutOfMaze(temp)){
if(pathSize[temp.x][temp.y] == -1){
if(Game.get().level.getBlock(temp.x, temp.y).getType() == Block.AIR){
toCheck.add(temp);
}
for(Teleporter t : teleporters){
if(t.type.equals("in"))
toCheck.add(new Point(t.toX, t.toY));
}
}
}
} | 5 |
@Override
public void actionPerformed(ActionEvent e)
{
if(e.getSource().equals(playButton))
{
if(gui.getSimulator().isPaused())
{
if(gui.getSimulator().play())
{
playButton.setIcon(pauseIcon);
stepButton.setEnabled(false);
}
}
else
{
if(gui.getSimulator().pause())
{
playButton.setIcon(playIcon);
stepButton.setEnabled(true);
}
}
}
else if(e.getSource().equals(stepButton))
{
if(gui.getSimulator().isPaused())
{
try
{
gui.getSimulator().step();
}
catch (TuringException ex)
{
Main.err.displayError(ex);
}
}
}
} | 7 |
private List<T> calcPath(T start, T goal) {
// TODO if invalid nodes are given (eg cannot find from
// goal to start, this method will result in an infinite loop!)
LinkedList<T> path = new LinkedList<T>();
T curr = goal;
int i = 0;
boolean done = false;
while (!done) {
path.addFirst(curr);
curr = (T) curr.getPrevious();
if(curr == null)continue;
if (curr.equals(start)) {
done = true;
}
i++;
if(i >1000){
System.out.println("Ran 1000 times, looping?");
break;
}
}
return path;
} | 4 |
public int[] addInstance(BallNode node, Instance inst) throws Exception {
double leftDist, rightDist;
if (node.m_Left!=null && node.m_Right!=null) { //if node is not a leaf
// go further down the tree to look for the leaf the instance should be in
leftDist = m_DistanceFunction.distance(inst, node.m_Left.getPivot(),
Double.POSITIVE_INFINITY); //instance.value(m_SplitDim);
rightDist = m_DistanceFunction.distance(inst, node.m_Right.getPivot(),
Double.POSITIVE_INFINITY);
if (leftDist < rightDist) {
addInstance(node.m_Left, inst);
// go into right branch to correct instance list boundaries
processNodesAfterAddInstance(node.m_Right);
}
else {
addInstance(node.m_Right, inst);
}
// correct end index of instance list of this node
node.m_End++;
}
else if(node.m_Left!=null || node.m_Right!=null) {
throw new Exception("Error: Only one leaf of the built ball tree is " +
"assigned. Please check code.");
}
else { // found the leaf to insert instance
int index = m_Instances.numInstances() - 1;
int instList[] = new int[m_Instances.numInstances()];
System.arraycopy(m_InstList, 0, instList, 0, node.m_End+1);
if(node.m_End < m_InstList.length-1)
System.arraycopy(m_InstList, node.m_End+2, instList, node.m_End+2, m_InstList.length-node.m_End-1);
instList[node.m_End+1] = index;
node.m_End++;
node.m_NumInstances++;
m_InstList = instList;
m_Splitter.setInstanceList(m_InstList);
if(node.m_NumInstances > m_MaxInstancesInLeaf) {
m_Splitter.splitNode(node, m_NumNodes);
m_NumNodes += 2;
}
}
return m_InstList;
} | 7 |
@Override
public boolean selectFileToOpen(DocumentInfo docInfo, int type) {
// we'll customize the approve button
// [srk] this is done here, rather than in configureForOpen/Import, to workaround a bug
String approveButtonText = null;
// make sure we're all set up
lazyInstantiation();
// Setup the File Chooser to open or import
switch (type) {
case FileProtocol.OPEN:
chooser.configureForOpen(getName(), Preferences.getPreferenceString(Preferences.MOST_RECENT_OPEN_DIR).cur);
approveButtonText = "Open";
break;
case FileProtocol.IMPORT:
chooser.configureForImport(getName(), Preferences.getPreferenceString(Preferences.MOST_RECENT_OPEN_DIR).cur);
approveButtonText = "Import";
break;
default:
System.out.println("ERROR: invalid open/import type used. (" + type +")");
return false;
}
// run the File Chooser
int option = chooser.showDialog(Outliner.outliner, approveButtonText) ;
// Update the most recent open dir preference
// TBD [srk] set up a MOST_RECENT_IMPORT_DIR, then have this code act appropriately
Preferences.getPreferenceString(Preferences.MOST_RECENT_OPEN_DIR).cur = chooser.getCurrentDirectory().getPath();
Preferences.getPreferenceString(Preferences.MOST_RECENT_OPEN_DIR).restoreTemporaryToCurrent();
// Handle User Input
if (option == JFileChooser.APPROVE_OPTION) {
String filename = chooser.getSelectedFile().getPath();
String encoding;
String fileFormat;
// pull proper preference values from the file chooser
switch (type) {
case FileProtocol.OPEN:
encoding = chooser.getOpenEncoding();
fileFormat = chooser.getOpenFileFormat();
break;
case FileProtocol.IMPORT:
encoding = chooser.getImportEncoding();
fileFormat = chooser.getImportFileFormat();
break;
default:
System.out.println("ERROR: invalid open/import type used. (" + type +")");
return false;
}
// store data into docInfo structure
PropertyContainerUtil.setPropertyAsString(docInfo, DocumentInfo.KEY_PATH, filename);
PropertyContainerUtil.setPropertyAsString(docInfo, DocumentInfo.KEY_ENCODING_TYPE, encoding);
PropertyContainerUtil.setPropertyAsString(docInfo, DocumentInfo.KEY_FILE_FORMAT, fileFormat);
return true;
} else {
return false;
}
} | 5 |
public void addPlayer(int playerID, String name, Team t) {
Area spawnArea = board.getSpawnArea(t);
Location spawnLoc = new NullLocation();
for (Tile tile: spawnArea.getTiles()) {
if (tile.isClear()) {
spawnLoc = tile.getCoords();
if (isFree(spawnLoc)) {
break;
}
}
}
server.queuePlayerUpdate(new CreateLocalPlayerEvent(playerID, spawnLoc), playerID);
Player p = new Player(name, t, playerID, spawnLoc);
playerIDs.put(playerID, p);
for (int id: playerIDs.keySet()) {
Player other = playerIDs.get(id);
server.queuePlayerUpdate(new CreatePlayerEvent(id, other.name, other.getLocation(), other.getTeam()), playerID);
server.queuePlayerUpdate(new CreatePlayerEvent(playerID, name, spawnLoc, t), id);
}
} | 4 |
@Override
public void addExperienceRecord(StatisticDto statisticDto) {
if (warehouse.containsKey(statisticDto.userId)) {
List<StatisticDto> userRecords = warehouse.get(statisticDto.userId);
userRecords.add(statisticDto);
} else {
List<StatisticDto> userRecords = new ArrayList<StatisticDto>();
userRecords.add(statisticDto);
warehouse.put(statisticDto.userId, userRecords);
}
} | 1 |
public int selectCount(BoardModel boardModel) {
int totalCount = 0;
String searchType = boardModel.getSearchType();
String searchText = boardModel.getSearchText();
String whereSQL = "";
try {
// 검색어 쿼리문 생성
if (!"".equals(searchText)) {
if ("ALL".equals(searchType)) {
whereSQL = " WHERE SUBJECT LIKE CONCAT('%',?,'%') OR WRITER LIKE CONCAT('%',?,'%') OR CONTENTS LIKE CONCAT('%',?,'%') ";
} else if ("SUBJECT".equals(searchType)) {
whereSQL = " WHERE SUBJECT LIKE CONCAT('%',?,'%') ";
} else if ("WRITER".equals(searchType)) {
whereSQL = " WHERE WRITER LIKE CONCAT('%',?,'%') ";
} else if ("CONTENTS".equals(searchType)) {
whereSQL = " WHERE CONTENTS LIKE CONCAT('%',?,'%') ";
}
}
// 데이터베이스 객체 생성
Class.forName(this.JDBC_DRIVER);
this.conn = DriverManager.getConnection(this.DB_URL, this.DB_ID, this.DB_PWD);
// 게시물의 총 수를 얻는 쿼리 실행
this.pstmt = this.conn.prepareStatement("SELECT COUNT(NUM) AS TOTAL FROM BOARD" + whereSQL);
if (!"".equals(whereSQL)) {
if ("ALL".equals(searchType)) {
this.pstmt.setString(1, searchText);
this.pstmt.setString(2, searchText);
this.pstmt.setString(3, searchText);
} else {
this.pstmt.setString(1, searchText);
}
}
this.rs = this.pstmt.executeQuery();
if (this.rs.next()) {
totalCount = this.rs.getInt("TOTAL");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// 사용한 객체 종료
close(this.rs, this.pstmt, this.conn);
}
return totalCount;
} | 9 |
public boolean setPlayer1(Player p) {
boolean test = false;
if (test || m_test) {
System.out.println("FileManager :: setPlayer1() BEGIN");
}
m_player1 = p;
if (test || m_test) {
System.out.println("FileManager :: setPlayer1() END");
}
return true;
} | 4 |
public void updateTxtBoard(String message){
txtBoard.append(message);
txtBoard.setCaretPosition(txtBoard.getDocument().getLength());
} | 0 |
private void btnEkleMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnEkleMousePressed
if(!btnEkle.isEnabled())
return;
HashMap<String, String> values = new HashMap<>();
values.put("ad", txtAd.getText().trim());
values.put("soyad", txtSoyad.getText().trim());
values.put("telefon", txtTelefon.getText().trim());
values.put("resimURL", "C:\\");
values.put("kullaniciAdi", txtKullaniciAdi.getText().trim());
values.put("sifre1", txtSifre.getText().trim());
values.put("sifre2", txtSifreTekrar.getText().trim());
values.put("kullanilanSure", txtKullanilanSure.getText().trim());
values.put("kalanSure", txtKalanSure.getText().trim());
values.put("borc", txtBorc.getText().trim());
values.put("indirim", txtIndirim.getText().trim());
values.put("bitisTarihYil", comboYil.getSelectedItem().toString());
values.put("bitisTarihAy", (comboAy.getSelectedIndex()) +"");
values.put("bitisTarihGun", (comboGun.getSelectedItem().toString()));
String ucretSecenek;
if(radioStandar.isSelected())
ucretSecenek = MusteriC.UCRET_STANDART;
else if(radioUcretsiz.isSelected())
ucretSecenek = MusteriC.UCRET_UCRETSIZ;
else
ucretSecenek = MusteriC.UCRET_UYE;
values.put("ucretSecenek", ucretSecenek);
String odemeSekli;
if(radioOnceden.isSelected())
odemeSekli = MusteriC.ODEME_ONCEDEN;
else
odemeSekli = MusteriC.ODEME_SONRADAN;
values.put("odemeSecenek", odemeSekli);
Musteri m = mutlakkafe.MutlakKafe.mainCont.getMusteriCont().getMusteri(values);
if(m != null){
mutlakkafe.MutlakKafe.mainCont.getMusteriCont().kisiEkle(m);
lstKullaniciListesi.setModel(
mutlakkafe.MutlakKafe.mainCont.getMusteriCont().kullaniciAdiList());
lblToplamKayit.setText("Toplam Kayıt : " + lstKullaniciListesi.getModel().getSize());
kilitle();
temizle();
}
}//GEN-LAST:event_btnEkleMousePressed | 5 |
public void switchPhase(){
if(this.gamePhase!=null){
switch(gamePhase){
case BlockPhase1:
this.gamePhase = GamePhase.PowerupPhase;
break;
case PowerupPhase:
this.gamePhase = GamePhase.BlockPhase2;
break;
case BlockPhase2:
switchTurn();
this.gamePhase = GamePhase.BlockPhase1;
break;
}
}
gui.setPhase(this.gamePhase);
} | 4 |
private void initialize(QuadTree quadTree, List<PolygonShape> landShapePolygons, List<PolygonShape> landUsePolygons)
{
quadTreeToDraw = quadTree;
visibleArea = new VisibleArea();
this.landShapePolygons = landShapePolygons;
this.landUseShapePolygons = landUsePolygons;
this.routeNodes = new ArrayList<>();
timer = new Timer();
try
{
toIcon = ImageIO.read(new File("assets/to.png"));
fromIcon = ImageIO.read(new File("assets/from.png"));
} catch (IOException ex)
{
Logger.getLogger(MapComponent.class.getName()).log(Level.SEVERE, null, ex);
}
visibleArea.setCoord(quadTreeToDraw.getQuadTreeX() - quadTreeToDraw.getQuadTreeLength() / 8, quadTreeToDraw.getQuadTreeY() - quadTreeToDraw.getQuadTreeLength() / 50, quadTreeToDraw.getQuadTreeLength() / 15 * 16, quadTreeToDraw.getQuadTreeLength() / 15 * 10);
moveIconX = 0;
moveIconY = 0;
// set the initial Color scheme to Standard Color scheme
this.setColorScheme("Standard");
} | 1 |
public static String getString(Node node, String xpath) {
NodeList nodeList = getNodeList(node, xpath);
if (nodeList == null || nodeList.getLength() == 0) {
return "";
}
if (xpath.endsWith(ELEMENT_NAME_FUNC)) {
if (nodeList.getLength() > 0) {
return nodeList.item(0).getNodeName();
} else {
return "";
}
} else {
return serialize(nodeList);
}
} | 4 |
public AutomatonDrawer getDrawer() {
return pane.getDrawer();
} | 0 |
public int getFileIndex()
{
return fileIndex;
} | 0 |
@Override
public void run() {
initializeLogger();
this.log.fine("Start FileReceiver");
this.log.fine("Get current thread");
Thread currentThread = Thread.currentThread();
if (currentThread.isInterrupted()) return;
ServerSocket fileServerSocket = null;
try {
fileServerSocket = new ServerSocket(this.port);
this.log.info("Create Server Socket: " + fileServerSocket.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Socket clientFileSocket = null;
try {
clientFileSocket = fileServerSocket.accept();
this.log.info("Accept client socket: " + clientFileSocket.toString());
fileServerSocket.close();
this.log.info("Close server scoket: " + fileServerSocket.toString());
} catch (IOException e) {
e.printStackTrace();
this.log.info("Catch IOException");
}
try {
File file = new File(fileName);
this.log.fine("Create new file: " + fileName);
FileOutputStream fileWriter = new FileOutputStream(file);
this.log.fine("Create new FileOutputStream: " + fileWriter.toString());
InputStream streamReader = clientFileSocket.getInputStream();
this.log.fine("get Input Stream from client File Socket");
byte buffer[] = new byte[packageSize];
this.log.fine("create byte array: " + packageSize);
while (!clientFileSocket.isInputShutdown())
if (currentThread.isInterrupted())
{
this.log.fine("FileReceiver is interrupted");
clientFileSocket.close();
fileWriter.close();
this.log.fine("FileReceiver is finish");
return;
}
while (streamReader.available() > 0) {
if (currentThread.isInterrupted())
{
this.log.fine("FileReceiver is interrupted");
clientFileSocket.close();
fileWriter.close();
this.log.fine("FileReceiver is finish");
return;
}
streamReader.read(buffer);
this.log.fine("Read from streamReader");
fileWriter.write(buffer);
this.log.fine("write with fileWriter");
}
fileWriter.close();
this.log.fine("fileWriter.close");
clientFileSocket.close();
this.log.fine("clientFileSocket.close");
fileServerSocket.close();
this.log.fine("fileServerSocket.close");
} catch (IOException e) {
e.printStackTrace();
}
this.log.fine("FileReceiver finish");
} | 8 |
private void btnAlterarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAlterarActionPerformed
UsuarioSistema usuario = null;
UsuarioSistemaDAO daoUsuario = new UsuarioSistemaDAO();
try {
usuario = dao.Abrir(this.idUsuarioRemover);
} catch (Exception ex) {
Logger.getLogger(frmListarUsuariosSistema.class.getName()).log(Level.SEVERE, null, ex);
}
frmEditarUsuarioSistema janela = new frmEditarUsuarioSistema(usuario);
janela.setVisible(true);
this.getParent().add(janela);
this.dispose();
}//GEN-LAST:event_btnAlterarActionPerformed | 1 |
private boolean jj_2_5(int xla) {
jj_la = xla; jj_lastpos = jj_scanpos = token;
try { return !jj_3_5(); }
catch(LookaheadSuccess ls) { return true; }
finally { jj_save(4, xla); }
} | 1 |
public static Method findMethod(Class<?> clazz, String name, Object... args) {
if (args != null && args.length > 0) {
int size = args.length;
Class<?>[] argsClazz = new Class<?>[size];
for (int i = 0; i < size; i++) {
argsClazz[i] = args[i].getClass();
}
try {
return clazz.getMethod(name, argsClazz);
} catch (NoSuchMethodException e) {
return null;
}
} else {
try {
return clazz.getMethod(name, new Class<?>[0]);
} catch (NoSuchMethodException e) {
return null;
}
}
} | 9 |
public void alterar(Medico medicoAnt) throws Exception {
if(medicoAnt.getNome().isEmpty()){
throw new Exception("Nome Invalido !!");
}else{
this.verificarNome(medicoAnt.getNome());
}
if(medicoAnt.getCpf().equals(" . . - ")){
throw new Exception("CPF Invalido !!");
}else{
this.verificaCPF(medicoAnt.getCpf());
}
if(medicoAnt.getCrm() == null){
throw new Exception("CRM Invalido !!");
}else{
this.verificaCRM(medicoAnt.getCrm());
}
if(medicoAnt.getCodigoEspecialidade().equals(0)){
throw new Exception("Especialidade Invalido !!");
}
if(medicoAnt.getTelefone().isEmpty()){
throw new Exception("Telefone Invalido !!");
}
if(medicoAnt.getEndereco().isEmpty()){
throw new Exception("Endereço Invalido !!");
}
MedicoDao.obterInstancia().alterar(medicoAnt);
} | 6 |
public static Set<String> getClassName(String packageName, boolean isRecursion) {
Set<String> classNames = null;
ClassLoader loader = Thread.currentThread().getContextClassLoader();
String packagePath = packageName.replace(".", "/");
URL url = loader.getResource(packagePath);
if (url != null) {
String protocol = url.getProtocol();
if (protocol.equals("file")) {
classNames = getClassNameFromDir(url.getPath(), packageName, isRecursion);
} else if (protocol.equals("jar")) {
JarFile jarFile = null;
try{
jarFile = ((JarURLConnection) url.openConnection()).getJarFile();
} catch(Exception e){
e.printStackTrace();
}
if(jarFile != null){
getClassNameFromJar(jarFile.entries(), packageName, isRecursion);
}
}
} else {
/*从所有的jar包中查找包名*/
classNames = getClassNameFromJars(((URLClassLoader)loader).getURLs(), packageName, isRecursion);
}
return classNames;
} | 5 |
public static void main(String[] args) {
String s = "aaabbbbcccaab";
List<String> result = new ArrayList<String>();
for (int i = 0, j = i + 1, l = s.length(); i < l; i = j) {
char temp = s.charAt(i);
for (; j < l; j++) {
if (temp != s.charAt(j)) {
result.add(s.substring(i, j));
break;
}
}
// 边界
if (j == l) {
result.add(s.substring(i, j));
}
}
// 直接插入排序
int len = result.size();
for (int i = 1; i < len; i++) {
for (int j = i; j > 0 && result.get(j - 1).length() < result.get(j).length(); j--) {
String t = result.get(j);
result.set(j, result.get(j - 1));
result.set(j - 1, t);
}
}
System.out.println(result);
} | 7 |
public String loginAction() {
String returned = null;
FacesContext context = FacesContext.getCurrentInstance();
User user = userService.getUserByEmail(userName);
if (user == null){
user = userService.getUserByUserName(userName);
if (user == null){
context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Błąd logowania", "Użytkownik \"" + userName + "\" nie istnieje."));
logIn = false;
return returned;
}else{
logIn = true;
}
}else{
logIn = true;
}
if (!user.getPassword().equals(stringUtils.getMD5Sum(password))){
context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Błąd logowania", "Podane hasło jest niepoprawne"));
logIn = false;
}
if (!user.getEnabled()){
context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Błąd logowania", "Użytkownik został zablokowany."));
logIn = false;
}
if (logIn){
try {
Authentication result = null;
if (rememberMe) {
UserDetails userDetails = userDetailsService.loadUserByUsername(user.getEmail());
RememberMeAuthenticationToken rememberMeAuthenticationToken = new RememberMeAuthenticationToken("jsfspring-sec", userDetails,userDetails.getAuthorities());
HttpServletRequest httpServletRequest = (HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest();
HttpServletResponse httpServletResponse = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
rememberMeServices.loginSuccess(httpServletRequest, httpServletResponse, rememberMeAuthenticationToken);
result = rememberMeAuthenticationToken;
returned = "Protected";
} else {
Authentication request = new UsernamePasswordAuthenticationToken(getUserName(), getPassword());
result = authenticationManager.authenticate(request);
returned = "Protected";
}
SecurityContextHolder.getContext().setAuthentication(result);
} catch (AuthenticationException e) {
log.error("AuthenticationException" , e);
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Błędne dane logowania.", ""));
}
}else{
}
return returned;
} | 7 |
node mutateRecurse(node nodeptr, doublePointer ratioptr , mutations newmuts,
double tree_age, double threshold, double loc)
{
node mutatenode = null;
if (nodeptr.getDescendents()[0] != null) {
if (segFactory.segContains(nodeptr.getDescendents()[0].getSegment(), loc)) {
double temp = (double)(nodeptr.getGen() - nodeptr.getDescendents()[0].getGen())/ tree_age;
ratioptr.setDouble(ratioptr.getDouble()+temp);
if (ratioptr.getDouble() > threshold) {
newmuts.setAncNode1(nodeptr);
newmuts.setAncNode2(nodeptr.getDescendents()[0]);
return nodeptr.getDescendents()[0];
}
mutatenode = mutateRecurse (nodeptr.getDescendents()[0],
ratioptr,
newmuts, tree_age,
threshold, loc);
if (mutatenode != null) return mutatenode;
/* this happens if we place a mutation inside this recursion. */
}
}
else return null;
if ((nodeptr.getDescendents()[1]!= null) &&
(segFactory.segContains(nodeptr.getDescendents()[1].getSegment(), loc))) {
double temp = (double) (nodeptr.getGen()
- nodeptr.getDescendents()[1].getGen())
/ tree_age;
ratioptr.setDouble(ratioptr.getDouble() + temp);
if (ratioptr.getDouble() > threshold) {
newmuts.setAncNode1(nodeptr);
newmuts.setAncNode2(nodeptr.getDescendents()[1]);
return nodeptr.getDescendents()[1];
}
mutatenode = mutateRecurse (nodeptr.getDescendents()[1],
ratioptr,
newmuts, tree_age,
threshold, loc);
if (mutatenode != null) return mutatenode;
/* this happens if we place a mutation inside this recursion. */
}
return null;
} | 8 |
public void requestBlock(int pieceIndex, int pieceOffset, int length) {
if (this.peer_choking) {
return;
}
// busy = true;
byte[] message = Message.buildRequest(pieceIndex, pieceOffset, length);
sendMessage(message);
// TODO
} | 1 |
protected void setLabel(String label)
{
/*
* The null check should not be needed as label should not be null
* so this is being too careful.
*/
if(label == null)
myLabel = "";
else
myLabel = label;
} | 1 |
public void maskRect(int x, int y, int w, int h, int[] pix, byte[] mask) {
assert data instanceof int[];
int maskBytesPerRow = (w + 7) / 8;
for (int j = 0; j < h; j++) {
int cy = y + j;
if (cy < 0 || cy >= height_)
continue;
for (int i = 0; i < w; i++) {
int cx = x + i;
if (cx < 0 || cx >= width_)
continue;
int byte_ = j * maskBytesPerRow + i / 8;
int bit = 7 - i % 8;
if ((mask[byte_] & (1 << bit)) != 0)
((int[])data)[cy * width_ + cx] = pix[j * w + i];
}
}
} | 7 |
protected void multiply(int rows) throws MatrixIndexOutOfBoundsException {
//temporary variable
double temp = 0;
//It is one-tenth of the number of rows of the matrix
int stepProgress = rowsA / 10;
//this quantity of rows which the thread takes
int step = matrixA.getStepRow();
//limiter
int range = rows + step;
for (int i = rows; i < range; i++) {
if ((rowsA >= 1000) && (i % stepProgress == 0)) {
//Multiplication progress
System.out.println("Multiplication progress " + i / stepProgress * 10 + "%.");
}
for (int j = 0; j < colsB; j++) {
for (int k = 0; k < colsA; k++) {
temp += matrixA.getValue(i, k) * matrixB.getValue(k, j);
}
matrixC.setValue(i, j, temp);
temp = 0;
}
}
} | 5 |
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ProductList other = (ProductList) obj;
if (maxIndex != other.maxIndex)
return false;
if (productList == null) {
if (other.productList != null)
return false;
} else if (!productList.equals(other.productList))
return false;
if (Double.doubleToLongBits(totalPrice) != Double.doubleToLongBits(other.totalPrice))
return false;
return true;
} | 8 |
private float computeTempObj(List<JstatItem> subList, JvmModel fPhaseMax, Reducer fReducer) {
float tempObj = 0;
float shuffleBytesMB = (float) ((double)fReducer.getReducerCounters().getReduce_shuffle_raw_bytes() / (1024 * 1024));
JstatItem lastJstat = subList.get(subList.size() - 1);
if(lastJstat.getFGC() == 0 && lastJstat.getYGC() == 0)
tempObj = lastJstat.getEU() - shuffleBytesMB;
else {
float ascend = 0;
float descend = 0;
int size = subList.size();
float[] c = new float[size];
for(int i = 0; i < size; i++) {
JstatItem item = subList.get(i);
c[i] = item.getEU() + item.getS0U() + item.getS1U() + item.getOU();
}
ascend += c[0];
for(int i = 1; i < c.length; i++) {
if(c[i] > c[i-1])
ascend += c[i] - c[i-1]; // contains InMemorySegments and accompanying temp objects
else if(c[i] < c[i-1]) {
descend += (c[i-1] - c[i]); // revoke InMemorySegments(merged to disk) and temp objects
}
}
if(ascend > shuffleBytesMB)
tempObj = ascend - shuffleBytesMB; // conservative
else
tempObj = descend; // conservative
}
return tempObj;
} | 7 |
static final void method587(int i, int j, int k, int l, int i1, int j1, boolean flag, int k1, int l1, int i2) {
if (flag) {
method585(null, 72);
}
if (k == l && i == i1 && ~i2 == ~l1 && k1 == j1) {
Class1.method70(i, j1, i2, j, false, k);
return;
}
int j2 = k;
int k2 = i;
int i3 = 3 * i;
int l2 = 3 * k;
int l3 = l1 * 3;
int i4 = 3 * k1;
int k3 = 3 * i1;
int j3 = l * 3;
int j4 = -k + -l3 + (i2 - -j3);
int k4 = k3 + ((j1 + -i4) - i);
int l4 = (l2 + l3) - (j3 + j3);
int k5 = k3 - i3;
int j5 = j3 - l2;
int i5 = -k3 + (i4 - k3 - -i3);
for (int l5 = 128; l5 <= 4096; l5 += 128) {
int i6 = l5 * l5 >> 12;
int i7 = l4 * i6;
int j6 = i6 * l5 >> 12;
int j7 = i6 * i5;
int k7 = l5 * j5;
int k6 = j6 * j4;
int l6 = j6 * k4;
int l7 = k5 * l5;
int j8 = (j7 + (l6 - -l7) >> 12) + i;
int i8 = k - -(i7 + (k6 + k7) >> 12);
Class1.method70(k2, j8, i8, j, false, j2);
k2 = j8;
j2 = i8;
}
} | 6 |
private Expression matchDesignator(DesignatorType designatorType) {
dispatchEvent(ParserEvent.BEGAN_PARSING_NON_TERMINAL_SYMBOL, "Designator");
SyntacticValidator.getInstance().matchNextToken(ProductionRule.REQUIRED, Token.Type.IDENTIFIER);
SemanticValidator.getInstance().validateDeclarationIsNotAType(SemanticValidator.getInstance().validateDeclarationWasPreviouslyDeclared(TokenIterator.getInstance().getCurrent()));
Declaration declaration = ScopeManager.getInstance().getCurrentScope().find(TokenIterator.getInstance().getCurrent().getValue().toString());
SemanticValidator.getInstance().validateDesignatorIdentifier(declaration, designatorType);
Expression expression = new InvalidExpression();
if (declaration instanceof Variable) {
Variable variable = (Variable) declaration;
if (declaration instanceof Parameter) {
Parameter parameter = (Parameter) declaration;
return new parser.semanticAnalysis.abstractSyntaxTree.expressions.locations.Variable(parameter, parameter.getType());
}
Location location = matchSelector(variable);
if (location == null) {
if (designatorType == DesignatorType.READ) {
SemanticValidator.getInstance().validateDeclarationIsAVariableWhoseTypeIsInteger(variable);
}
expression = new parser.semanticAnalysis.abstractSyntaxTree.expressions.locations.Variable(variable, variable.getType());
} else {
if (designatorType == DesignatorType.READ) {
SemanticValidator.getInstance().validateDeclarationIsAVariableWhoseTypeIsInteger(location);
}
expression = location;
}
} else if (declaration instanceof Constant && designatorType == DesignatorType.FACTOR) {
return new Number(new Constant(((Constant) declaration).getValue()));
} else {
matchSelector(new InvalidVariable());// TODO ELSE (DISABLED)
}
dispatchEvent(ParserEvent.FINISHED_PARSING_NON_TERMINAL_SYMBOL, "Designator");
return expression;
} | 7 |
@Override
public byte[] getContent() throws IOException {
if (content == null) {
try (BufferedInputStream is = new BufferedInputStream(fullUrl.openStream())) {
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int n;
byte[] data = new byte[10000];
while ((n = is.read(data, 0, data.length)) != -1) {
buffer.write(data, 0, n);
}
content = buffer.toByteArray();
}
}
return content;
} | 2 |
public AnnotationVisitor visitAnnotation(final String desc,
final boolean visible) {
if (!ClassReader.ANNOTATIONS) {
return null;
}
ByteVector bv = new ByteVector();
// write type, and reserve space for values count
bv.putShort(newUTF8(desc)).putShort(0);
AnnotationWriter aw = new AnnotationWriter(this, true, bv, bv, 2);
if (visible) {
aw.next = anns;
anns = aw;
} else {
aw.next = ianns;
ianns = aw;
}
return aw;
} | 2 |
private void processSelectedKeys(Set keys) throws Exception {
Iterator itr = keys.iterator();
while (itr.hasNext()) {
SelectionKey key = (SelectionKey) itr.next();
if (key.isReadable()) processRead(key);
if (key.isWritable()) processWrite(key);
if (key.isConnectable()) processConnect(key);
if (key.isAcceptable()) ;
itr.remove();
}
} | 5 |
private void sendGuessSet() {
Dot[] dots = guessSet.getDots();
boolean isInvalid = false;
// Check if dots in guess set are default color (not changed).
for (int i = 0; i < dots.length; i++) {
if (dots[i].getColor().equals(GameColor.DEFAULT.getColor()))
isInvalid = true;
}
// Send guess set to session.
if (!isInvalid) {
int[] dotValues = new int[dots.length];
// Convert dot colors to integer values.
for (int i = 0; i < dots.length; i++) {
dotValues[i] = getIntValueOfColor(dots[i].getColor());
}
frame.sendGuessSet(dotValues);
Color[] colors = new Color[4];
for (int i = 0; i < colors.length; i++)
colors[i] = dots[i].getColor();
gameGrid.changeSetColors(triesLeft - 1, 0, colors);
if (triesLeft != 0)
triesLeft--; // Lose one try
// Sets a warning by changing foreground color
if (triesLeft <= 3)
lblTriesLeft.setForeground(GameColor.RED.getColor());
lblTriesLeft.setText("" + triesLeft);
}
} | 7 |
public int getPlayerGem()
{
return karel.getGemCount();
} | 0 |
public void saveConfig() {
this.plugin.saveConfig();
} | 0 |
private ArrayList<Pawn> getAllPawn(Board board) {
ArrayList<Pawn> pawns = new ArrayList<Pawn>();
int numberOfPawns = board.numberOfPawns();
for (int i = 0; i < numberOfPawns; i++) {
pawns.add(board.getNextPawn());
}
return pawns;
} | 1 |
private void promoteAvatarToDrawable(List<DrawableAvatar> drawables,
int x, int y, int width, int height, int offset) {
double spacing = offset * avatarSpacing;
double avatarPosition = this.avatarPosition + spacing;
if (avatarIndex + offset < 0 ||
avatarIndex + offset >= avatars.size()) {
return;
}
int avatarWidth = displayWidth;
int avatarHeight = displayHeight;
double result = computeModifier(avatarPosition);
int newWidth = (int)(avatarWidth * result);
if(newWidth == 0)
return;
int newHeight = (int)(avatarHeight * result);
if(newHeight == 0)
return;
double avatar_x = x + (width - newWidth) / 2.0;
double avatar_y = y + (height - newHeight / 2.0) / 2.0;
double semiWidth = width / 2.0;
avatar_x += avatarPosition * semiWidth;
if (avatar_x >= width || avatar_x < -newWidth) {
return;
}
drawables.add(new DrawableAvatar(avatarIndex + offset,
avatar_x, avatar_y, newWidth, newHeight, avatarPosition, result));
} | 6 |
public void write(char[] b, int off, int len) throws IOException {
if (!initialized) {
area.setText("");
initialized = true;
}
// /#ifdef AWT10
// / area.appendText(new String(b, off, len));
// /#else
area.append(new String(b, off, len));
// /#endif
} | 1 |
Subsets and Splits
SQL Console for giganticode/java-cmpx-v1
The query retrieves a limited number of text entries within a specific length range, providing basic filtering but minimal analytical insight.