text stringlengths 14 410k | label int32 0 9 |
|---|---|
final void _parseName_() {
final int start = this.index();
for (int symbol = this.skip(); symbol >= 0; symbol = this.skip()) {
if (symbol == '>') {
if (this.skip() != '>') {
this._put_('!', start);
return;
}
} else if (symbol == '<') {
if (this.skip() != '<') {
break;
}
}
}
this._put_('?', start);
} | 5 |
@Override
public void execute(VirtualMachine vm) {
vm.setRunning(false);
} | 0 |
public void moveToLocation (Location newLocation) {
try {
newLocation.add(this);
}
catch(Exception e) {
}
currentLocation = newLocation;
if(newLocation instanceof Hangar) {
this.status = waitingToDepart;
}
else if(newLocation instanceof Workshop) {
this.status = beingRepaired;
}
else if(newLocation instanceof Airspace) {
this.status = waitingToLand;
}
else if(newLocation instanceof Runway) {
if(currentLocation instanceof Hangar || currentLocation instanceof Workshop) {
this.status = departing;
}
else if(currentLocation instanceof Airspace) {
this.status = landing;
}
}
if(currentLocation != null) {
currentLocation.remove(this);
}
} | 9 |
public Node lowerNode(T k) {
Node x = root;
while (x != NULL) {
if (k.compareTo(x.key) >0) {
if(x.right != NULL){
x = x.right;
}else{
return x;
}
} else {
if(x.left != NULL){
x = x.left;
}else{
Node current = x;
while(current.parent != NULL && current.parent.left == current) {
current = current.parent;
}
return current.parent;
}
}
}
return NULL;
} | 6 |
@Override
public boolean equals(Object o)
{
FlipHash other = (FlipHash)o;
return other.cursorX == cursorX &&
other.cursorY == cursorY &&
other.board.equals( board );
} | 2 |
public void displayTree()
{
if (this.isLeaf()) {
System.out.print("(" + this.caractere + ":" + this.poids + ")");
}
else {
System.out.print("(");
this.fGauche.displayTree();
this.fDroit.displayTree();
System.out.print(")");
}
} | 1 |
public void UpdateDep(Departamento DEP) throws SQLException, excecaoDepartamento {
DepartamentoDAO depDAO = new DepartamentoDAO();
Departamento DepExistente = null;
DepExistente = depDAO.selectDepartamentoPorNome(DEP.getNome());
if (DepExistente == null || DepExistente.getCodigo().equals(DEP.getCodigo())) {
depDAO.UpdateDepartamento(DEP, DEP.getCodigo());
} else {
throw new excecaoDepartamento();
}
} | 2 |
private Player resultSetToPlayer(ResultSet rs) throws SQLException {
Player player = new Player();
player.setId(rs.getLong("id"));
player.setName(rs.getString("name"));
player.setSurname(rs.getString("surname"));
player.setPlayerNumber(rs.getByte("number"));
player.setTeamID(rs.getLong("teamid"));
player.setHome(rs.getInt("home") != 0);
player.setAway(rs.getInt("away") != 0);
switch (rs.getString("position")){
case "GOALTENDER" :
player.setPlayerPosition(PlayerPosition.GOALTENDER);
break;
case "DEFENCEMAN" :
player.setPlayerPosition(PlayerPosition.DEFENCEMAN);
break;
case "FORWARD" :
player.setPlayerPosition(PlayerPosition.FORWARD);
break;
case "ALTERNATE" :
player.setPlayerPosition(PlayerPosition.ALTERNATE);
break;
}
return player;
} | 4 |
public boolean rendre(Emprunt emprunt) throws Exception {
boolean retour = false;
if (emprunt.getLivre() == null) {
throw new NullPointerException("Livre null !");
}
if (emprunt.getAdherent() == null) {
throw new NullPointerException("Adhérent null !");
}
if (emprunt.getLivre().isDisponibilite()) {
throw new Exception("Ce livre n'a pas été emprunté !");
}
List<Emprunt> listEmpruntByAdherent = empruntMetierService.getByAdherent(emprunt.getAdherent());
boolean trouve = false;
for (int i = 0; i < listEmpruntByAdherent.size(); i++) {
if (listEmpruntByAdherent.get(i).getLivre().equals(emprunt.getLivre())) {
trouve = true;
i = listEmpruntByAdherent.size();
}
}
if (!trouve) {
throw new Exception("Cet adhérent n'a pas emprunté ce livre !");
}
emprunt.getLivre().setTitre(emprunt.getLivre().getTitre().replace("\'", "\\'"));
emprunt.getLivre().setAuteur(emprunt.getLivre().getAuteur().replace("\'", "\\'"));
retour = empruntMetierService.remove(emprunt);
return retour;
} | 6 |
private void updateHistogram(ArrayList<Chord> chords) {
Chord prev, next;
for(int i=0; i<chords.size()-1; i++){
prev = chords.get(i);
next = chords.get(i+1);
String previousChord = prev.toString();
String nextChord = next.toString();
if(!chordList.containsKey(previousChord)){
chordList.put(previousChord, prev);
}
if(!chordList.containsKey(nextChord)){
chordList.put(nextChord, next);
}
if(histogram.containsKey(previousChord)){
if(histogram.get(previousChord).containsKey(nextChord)){
int count = histogram.get(previousChord).get(nextChord);
histogram.get(previousChord).put(nextChord, count+1);
}else{
histogram.get(previousChord).put(nextChord, 1);
}
}else{
HashMap<String, Integer> notesAfter = new HashMap<String, Integer>();
histogram.put(previousChord, notesAfter);
}
}
} | 5 |
@Override
public int actionOnBoard(Territory territory, int player){
if(victory){
if(territory.getFamily()==model.getFamily(player) && territory.getTroup()!=null && territory.getTroup().getTroops()[1]>0){
territory.getTroup().addToop(0, 0, 1, 0);
territory.getTroup().rmToop(0, 1, 0, 0);
numberKnight[0]--;
if(!family.knightAvailable()) numberKnight[0]=0;
}
}else{
if(territory.getFamily()==model.getFamily(player) && territory.getTroup()!=null && territory.getTroup().getTroops()[2]>0){
territory.getTroup().addToop(0, 1, 0, 0);
territory.getTroup().rmToop(0, 0, 1, 0);
numberKnight[getPlaceOnTrack(player)]--;
if(!haveKnightOnBoard(model.getFamily(player))) numberKnight[getPlaceOnTrack(player)]=0;
}
}
checkFinish();
return 0;
} | 9 |
protected Operation [] getOptimalOperations(BayesNet bayesNet, Instances instances, int nrOfLookAheadSteps, int nrOfGoodOperations) throws Exception {
if (nrOfLookAheadSteps == 1) { // Abbruch der Rekursion
Operation [] bestOperation = new Operation [1];
bestOperation [0] = getOptimalOperation(bayesNet, instances);
return(bestOperation); // Abbruch der Rekursion
} else {
double bestDeltaScore = 0;
double currentDeltaScore = 0;
Operation [] bestOperation = new Operation [nrOfLookAheadSteps];
Operation [] goodOperations = new Operation [nrOfGoodOperations];
Operation [] tempOperation = new Operation [nrOfLookAheadSteps-1];
goodOperations = getGoodOperations(bayesNet, instances, nrOfGoodOperations);
for (int i = 0; i < nrOfGoodOperations; i++) {
if (goodOperations[i] != null) {
performOperation(bayesNet, instances, goodOperations [i]);
tempOperation = getOptimalOperations(bayesNet, instances, nrOfLookAheadSteps-1, nrOfGoodOperations); // rekursiver Abstieg
currentDeltaScore = goodOperations [i].m_fDeltaScore;
for (int j = 0; j < nrOfLookAheadSteps-1; j++) {
if (tempOperation [j] != null) {
currentDeltaScore += tempOperation [j].m_fDeltaScore;
}
}
performOperation(bayesNet, instances, getAntiOperation(goodOperations [i]));
if (currentDeltaScore > bestDeltaScore) {
bestDeltaScore = currentDeltaScore;
bestOperation [0] = goodOperations [i];
for (int j = 1; j < nrOfLookAheadSteps; j++) {
bestOperation [j] = tempOperation [j-1];
}
}
} else i=nrOfGoodOperations;
}
return(bestOperation);
}
} // getOptimalOperations | 7 |
private void forecastGridlet()
{
// if no Gridlets available in exec list, then exit this method
if (gridletInExecList_.size() == 0) {
return;
}
// checks whether Gridlets have finished or not. If yes, then remove
// them since they will effect the MIShare calculation.
checkGridletCompletion();
// Identify MIPS share for all Gridlets for 1 second, considering
// current Gridlets + No of PEs.
MIShares share = getMIShare( 1.0, gridletInExecList_.size() );
ResGridlet rgl = null;
int i = 0;
double time = 0.0;
double rating = 0.0;
double smallestTime = 0.0;
// For each Gridlet, determines their finish time
Iterator iter = gridletInExecList_.iterator();
while ( iter.hasNext() )
{
rgl = (ResGridlet) iter.next();
// If a Gridlet locates before the max count then it will be given
// the max. MIPS rating
if (i < share.maxCount) {
rating = share.max;
}
else { // otherwise, it will be given the min. MIPS Rating
rating = share.min;
}
time = forecastFinishTime(rating, rgl.getRemainingGridletLength() );
int roundUpTime = (int) (time+1); // rounding up
rgl.setFinishTime(roundUpTime);
// get the smallest time of all Gridlets
if (i == 0 || smallestTime > time) {
smallestTime = time;
}
i++;
}
// sends to itself as an internal event
super.sendInternalEvent(smallestTime);
} | 5 |
public static HSSFWorkbook html2Excel(HSSFWorkbook wb, Html html, int i)
throws Exception {
HSSFSheet sheet = wb.createSheet(html.getHead().getTitle().getElementText());
// sheet.setColumnWidth(5,14*36);
Style htmlStyle = html.getHead().getStyle();
Table htmlTable = html.getBody().getTable();
List<CellRangeAddress> cras = new ArrayList<CellRangeAddress>();
for (int row = 0; row < htmlTable.getTrlist().size(); row++) {
Tr tr = htmlTable.getTrlist().get(row);
// String[][] trattr = tr.getAttr();
HSSFRow hssfrow = sheet.createRow(row + ROW_OFFSET);
for (int col = 0; col < tr.getTdlist().size(); col++) {
Td td = tr.getTdlist().get(col);
if (td.getAddress() != null) {
int[] address = new int[2];
address[0] = td.getAddress()[0] + ROW_OFFSET;
address[1] = td.getAddress()[1] + COL_OFFSET;
td.setAddress(address);
}
/**
* 检查是否有单元格,若有就进行合并
*/
CellRangeAddress cra = mergeRegion(td);
if (cra != null) {
cras.add(cra);
}
if (td.getElementName() != null) {
HSSFCellStyle cellStyle = wb.createCellStyle();
HSSFCell hssfcell = hssfrow.createCell(col + COL_OFFSET);
hssfcell.setCellValue(td.getElementText());
HSSFCellStyle defaultStyle = StyleUtil.getDefaultStyle(wb,
cellStyle);
cellStyle = StyleUtil.getStyle(wb, defaultStyle, htmlStyle,
td.getAttr());
StyleUtil
.setColumnAndRowHW(hssfrow, hssfcell, td.getAttr());
if (cellStyle != null) {
hssfcell.setCellStyle(cellStyle);
} else {
hssfcell.setCellStyle(defaultStyle);
}
}
}
}
for (int cranum = 0; cranum < cras.size(); cranum++) {
sheet.addMergedRegion(cras.get(cranum));
StyleUtil.setRegionStyle(sheet, cras.get(cranum));
}
sheet = null;
return wb;
} | 7 |
public static void main(String[] args) throws FileNotFoundException {
Data d = Reader.getDataFromFile(new File("files/restaurant2.arff"));
int size = d.getAttributes().size();
Random r = new Random();
for (int i = 0; i < 100; i++) {
ArrayList<String> row = new ArrayList<String>();
for (int j = 0; j < size; j++) {
String[] options = d.getattributeValues().get(d.getAttributes().get(j));
int index = r.nextInt(options.length);
row.add("'" + options[index] + "'");
}
String output = row.toString();
System.out.println(output.substring(1,output.length()-1));
}
} | 2 |
private void resize() {
width = getSkinnable().getWidth();
height = getSkinnable().getHeight();
if (getSkinnable().isKeepAspect()) {
if (aspectRatio * width > height) {
width = 1 / (aspectRatio / height);
} else if (1 / (aspectRatio / height) > width) {
height = aspectRatio * width;
}
}
if (width > 0 && height > 0) {
main.setPrefSize(width, height);
mainInnerShadow0.setRadius(3.0 / 132.0 * height);
mainInnerShadow1.setRadius(2.0 / 132.0 * height);
if (crystalOverlay.isVisible()) {
crystalClip.setWidth(width);
crystalClip.setHeight(height);
crystalOverlay.setImage(createNoiseImage(width, height, DARK_NOISE_COLOR, BRIGHT_NOISE_COLOR, 8));
crystalOverlay.setCache(true);
}
threshold.setPrefSize(0.20 * height, 0.20 * height);
threshold.setTranslateX(0.027961994662429348 * width);
threshold.setTranslateY(0.75 * height - 2);
trendDown.setPrefSize(0.06718573425755356 * width, 0.1333622932434082 * height);
trendDown.setTranslateX(0.1439393939 * width);
trendDown.setTranslateY(0.8125 * height - 2);
trendFalling.setPrefSize(0.06982171896732214 * width, 0.13879903157552084 * height);
trendFalling.setTranslateX(0.1439393939 * width);
trendFalling.setTranslateY(0.8061291376749674 * height - 2);
trendSteady.setPrefSize(0.0676060878869259 * width, 0.1342292626698812 * height);
trendSteady.setTranslateX(0.1439393939 * width);
trendSteady.setTranslateY(0.8078853289286295 * height - 2);
trendRising.setPrefSize(0.06982171896732214 * width, 0.13879903157552084 * height);
trendRising.setTranslateX(0.1439393939 * width);
trendRising.setTranslateY(0.8050718307495117 * height - 2);
trendUp.setPrefSize(0.06718573425755356 * width, 0.1333622932434082 * height);
trendUp.setTranslateX(0.1439393939 * width);
trendUp.setTranslateY(0.8041377067565918 * height - 2);
battery.setPrefSize(0.0833333333 * width, 0.1458333333 * height);
battery.setTranslateX(0.6439393939 * width);
battery.setTranslateY(0.81 * height - 2);
signal.setPrefSize(0.0416666667 * height, 0.5 * height);
signal.setTranslateX(0.0151515152 * width);
signal.setTranslateY(0.25 * height);
alarm.setPrefSize(0.1666666667 * height, 0.1666666667 * height);
alarm.setTranslateX(0.2651515152 * width);
alarm.setTranslateY(0.7916666667 * height - 2);
updateFonts();
// Setup the lcd unit
unitText.setFont(unitFont);
unitText.setTextOrigin(VPos.BASELINE);
unitText.setTextAlignment(TextAlignment.RIGHT);
unitText.setText(getSkinnable().getUnit());
if (unitText.visibleProperty().isBound()) {
unitText.visibleProperty().unbind();
}
unitText.visibleProperty().bind(getSkinnable().unitVisibleProperty());
valueOffsetLeft = height * 0.04;
if (getSkinnable().isUnitVisible()) {
unitText.setX((width - unitText.getLayoutBounds().getWidth()) - height * 0.04);
unitText.setY(height - (text.getLayoutBounds().getHeight() * digitalFontSizeFactor) * 0.5);
valueOffsetRight = (unitText.getLayoutBounds().getWidth() + height * 0.0833333333); // distance between value and unit
text.setX(width - 2 - text.getLayoutBounds().getWidth() - valueOffsetRight);
} else {
valueOffsetRight = height * 0.0833333333;
text.setX((width - text.getLayoutBounds().getWidth()) - valueOffsetRight);
}
text.setY(height - (text.getLayoutBounds().getHeight() * digitalFontSizeFactor) * 0.5);
// Visualize the lcd semitransparent background text
updateBackgroundText();
if (getSkinnable().isUnitVisible()) {
backgroundText.setX(width - 2 - backgroundText.getLayoutBounds().getWidth() - valueOffsetRight);
} else {
backgroundText.setX((width - backgroundText.getLayoutBounds().getWidth()) - valueOffsetRight);
}
backgroundText.setY(height - (backgroundText.getLayoutBounds().getHeight() * digitalFontSizeFactor) * 0.5);
// Setup the font for the lcd title, number system, min measured, max measure and former value
// Title
title.setFont(titleFont);
title.setTextOrigin(VPos.BASELINE);
title.setTextAlignment(TextAlignment.CENTER);
title.setText(getSkinnable().getTitle());
title.setX((width - title.getLayoutBounds().getWidth()) * 0.5);
title.setY(main.getLayoutY() + title.getLayoutBounds().getHeight() - 0.04 * height + 2);
// Info Text
lowerRightText.setFont(smallFont);
lowerRightText.setTextOrigin(VPos.BASELINE);
lowerRightText.setTextAlignment(TextAlignment.RIGHT);
lowerRightText.setText(getSkinnable().getNumberSystem().toString());
lowerRightText.setX(main.getLayoutX() + (main.getLayoutBounds().getWidth() - lowerRightText.getLayoutBounds().getWidth()) * 0.5);
lowerRightText.setY(main.getLayoutY() + height - 3 - 0.0416666667 * height);
// Min measured value
upperLeftText.setFont(smallFont);
upperLeftText.setTextOrigin(VPos.BASELINE);
upperLeftText.setTextAlignment(TextAlignment.RIGHT);
upperLeftText.setX(main.getLayoutX() + 0.0416666667 * height);
upperLeftText.setY(main.getLayoutY() + upperLeftText.getLayoutBounds().getHeight() - 0.04 * height + 2);
// Max measured value
upperRightText.setFont(smallFont);
upperRightText.setTextOrigin(VPos.BASELINE);
upperRightText.setTextAlignment(TextAlignment.RIGHT);
upperRightText.setY(main.getLayoutY() + upperRightText.getLayoutBounds().getHeight() - 0.04 * height + 2);
// Former value
lowerCenterText.setFont(smallFont);
lowerCenterText.setTextOrigin(VPos.BASELINE);
lowerCenterText.setTextAlignment(TextAlignment.CENTER);
lowerCenterText.setX((width - lowerCenterText.getLayoutBounds().getWidth()) * 0.5);
lowerCenterText.setY(main.getLayoutY() + height - 3 - 0.0416666667 * height);
}
} | 9 |
private static CtMethod delegator0(CtMethod delegate, CtClass declaring)
throws CannotCompileException, NotFoundException
{
MethodInfo deleInfo = delegate.getMethodInfo2();
String methodName = deleInfo.getName();
String desc = deleInfo.getDescriptor();
ConstPool cp = declaring.getClassFile2().getConstPool();
MethodInfo minfo = new MethodInfo(cp, methodName, desc);
minfo.setAccessFlags(deleInfo.getAccessFlags());
ExceptionsAttribute eattr = deleInfo.getExceptionsAttribute();
if (eattr != null)
minfo.setExceptionsAttribute(
(ExceptionsAttribute)eattr.copy(cp, null));
Bytecode code = new Bytecode(cp, 0, 0);
boolean isStatic = Modifier.isStatic(delegate.getModifiers());
CtClass deleClass = delegate.getDeclaringClass();
CtClass[] params = delegate.getParameterTypes();
int s;
if (isStatic) {
s = code.addLoadParameters(params, 0);
code.addInvokestatic(deleClass, methodName, desc);
}
else {
code.addLoad(0, deleClass);
s = code.addLoadParameters(params, 1);
code.addInvokespecial(deleClass, methodName, desc);
}
code.addReturn(delegate.getReturnType());
code.setMaxLocals(++s);
code.setMaxStack(s < 2 ? 2 : s); // for a 2-word return value
minfo.setCodeAttribute(code.toCodeAttribute());
return new CtMethod(minfo, declaring);
} | 3 |
public void paintComponent(Graphics g) {
super.paintComponent(g);
if(image != null){
g.drawImage(image, 0, 0, getWidth(), getHeight(), null);
}
} | 1 |
public void computeWords2(String spelling) {
String[] segmentedSpelling = segment(spelling).split(" ");
String[] seg = segmentedSpelling;
ArrayList<String> waitingSentence = new ArrayList<String>();
ArrayList<Integer> waitingCount = new ArrayList<Integer>();
char[] firstWords = findWaitingWords(seg[0]).toCharArray();
for(char ch: firstWords) {
//use wordCount instead of word probability, maybe it's good
StringBuffer sb = new StringBuffer();
sb.append(ch);
waitingSentence.add(sb.toString());
waitingCount.add((wordCount_.indexOf(words_.indexOf(ch))) + 1);
}
//waitingSentence
//waitingPr
/**
* CORE
*/
for(int k = 1; k < seg.length; k++) {
//char[] words0 = findWaitingWords(seg[k - 1]).toCharArray();
//System.out.println(findWaitingWords(seg[k]));
char[] words = findWaitingWords(seg[k]).toCharArray();
//probability for this round under k
String[][] laterSentence = new String[waitingSentence.size()][words.length];
int[][] laterCount = new int[waitingSentence.size()][words.length];
for(int sentence_i = 0; sentence_i < waitingSentence.size(); sentence_i++) {
//取出候选句子中最后一个字
String sentence = waitingSentence.get(sentence_i);
char[] words0 = sentence.toCharArray();
char lastWord = words0[words0.length - 1];
//得到候选句子的count之积
int sentenceCount = waitingCount.get(sentence_i);
//遍历当前字的所有可能
for(int word_i = 0; word_i < words.length; word_i++) {
char thisWord = words[word_i];
int row = words_.indexOf(lastWord);
int col = words_.indexOf(thisWord);
int eachCount = 1;
if(row >= 0 && col >= 0) {
eachCount = this.phraseCount_[row][col] + 1;
}
//处理句子,加入候选矩阵
StringBuffer sb = new StringBuffer(sentence);
sb.append(thisWord);
laterSentence[sentence_i][word_i] = sb.toString();
//处理出现次数,加入候选矩阵
int c = sentenceCount * eachCount;
laterCount[sentence_i][word_i] = c;
}
}
int waitingSentenceSize = waitingSentence.size();
waitingSentence.clear();
waitingCount.clear();
for(int sentenceCount = 0; sentenceCount < waitingSentenceSize; sentenceCount++) {
for(int wordCount = 0; wordCount < words.length; wordCount++) {
waitingSentence.add(laterSentence[sentenceCount][wordCount]);
waitingCount.add(laterCount[sentenceCount][wordCount]);
}
}
}
System.out.println(waitingCount.size());
@SuppressWarnings("unchecked")
ArrayList<Integer> waitingCountCopy = (ArrayList<Integer>) waitingCount.clone();
Collections.sort(waitingCountCopy, Collections.reverseOrder());
for(int i = 0; i < 5; i++){
int index = waitingCount.indexOf(waitingCountCopy.get(i));
String sentence = waitingSentence.get(index);
System.out.println(sentence + waitingCountCopy.get(i));
}
} | 9 |
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
for (FiguraGeometrica d : objetos) {
d.desenhar(g2);
}
} | 1 |
private int evalState(State s) {
int score = evalStateSide(s, "red") - evalStateSide(s, "blue");
return (me == "red")?score:-score;
} | 1 |
public static String getPage(CommandParameter commandParameter) {
String pageName = null;
if (commandParameter.getRequestURI().contains(FrontController.HOME_PAGE.replace("jsp", "ctrl"))) {
return commandParameter.getContextPath() + "/" + FrontController.HOME_PAGE;
}
pageName = commandParameter.getRequestURI().substring(commandParameter.getContextPath().length());
String page = pageName.replace("ctrl", "jsp");
return page;
} | 1 |
public static final String convertColorNameToRGB(String name) {
int c = convertNamedColor(name.toLowerCase());
if (c >= 0) {
//int rgb = c.getRGB();
char[] buf = new char[7];
buf[0] = '#';
for (int pos = 1, shift = 20; shift >= 0; ++pos, shift -= 4) {
int d = 0xF & (c >> shift);
buf[pos] = (char) ((d < 10) ? d + '0' : d + 'A' - 10);
}
name = new String(buf, 0, 7);
}
return name;
} | 3 |
static public ParseException generateParseException() {
jj_expentries.clear();
boolean[] la1tokens = new boolean[24];
if (jj_kind >= 0) {
la1tokens[jj_kind] = true;
jj_kind = -1;
}
for (int i = 0; i < 19; i++) {
if (jj_la1[i] == jj_gen) {
for (int j = 0; j < 32; j++) {
if ((jj_la1_0[i] & (1<<j)) != 0) {
la1tokens[j] = true;
}
}
}
}
for (int i = 0; i < 24; i++) {
if (la1tokens[i]) {
jj_expentry = new int[1];
jj_expentry[0] = i;
jj_expentries.add(jj_expentry);
}
}
jj_endpos = 0;
jj_rescan_token();
jj_add_error_token(0, 0);
int[][] exptokseq = new int[jj_expentries.size()][];
for (int i = 0; i < jj_expentries.size(); i++) {
exptokseq[i] = jj_expentries.get(i);
}
return new ParseException(token, exptokseq, tokenImage);
} | 8 |
public FSList getAnnotationsFromChapter(FsNode chapter) {
if (chapter != null) {
if (this.annotations == null) {
System.out.println("getting annotations");
getAnnotations();
}
FSList annotations = new FSList("chapter/"+chapter.getId());
float start = chapter.getStarttime();
float duration = chapter.getDuration();
List<FsNode> nodes = this.annotations.getNodes();
for (FsNode node : nodes) {
if (node != null) {
if (node.getStarttime() >= start && node.getStarttime() <= start+duration) {
annotations.addNode(node);
}
}
}
return annotations;
} else {
System.out.println("Empty chapter");
}
return new FSList();
} | 6 |
public static void main(String[] args) {
if (args.length != 2) {
System.err.println("Usage: java TextComparer <file name> <file name>");
System.exit(-1);
}
BufferedReader reader1 = null;
BufferedReader reader2 = null;
try {
reader1 = new BufferedReader(new FileReader(args[0]));
} catch (IOException ioe) {
System.err.println("Cannot open " + args[0]);
System.exit(-1);
}
try {
reader2 = new BufferedReader(new FileReader(args[1]));
} catch (IOException ioe) {
System.err.println("Cannot open " + args[1]);
System.exit(-1);
}
String line1, line2;
int count = 0;
try {
while ((line1 = reader1.readLine()) != null) {
line1 = removeSpaces(line1);
line2 = reader2.readLine();
if (line2 == null) {
System.out.println("Second file is shorter (only " + count + " lines)");
System.exit(-1);
}
else {
line2 = removeSpaces(line2);
if (!line1.equals(line2)) {
System.out.println("Comparison failure in line " + count + ":");
System.out.println(line1);
System.out.println(line2);
System.exit(-1);
}
}
count++;
}
if (reader2.readLine() != null) {
System.out.println("First file is shorter (only " + count + " lines)");
System.exit(-1);
}
} catch (IOException ioe) {
System.err.println("IO error while reading files");
System.exit(-1);
}
try {
reader1.close();
reader2.close();
} catch (IOException ioe) {
System.err.println("Could not close files");
System.exit(-1);
}
System.out.println("Comparison ended successfully");
} | 9 |
public static void main(String[] args) {
try {
QuestionCalculation qcal = new QuestionCalculation();
ArrayList<Integer> opd = new ArrayList<Integer>();
opd.add(12);
opd.add(84);
opd.add(45);
opd.add(90);
ArrayList<Character> opt = new ArrayList<Character>();
opt.add('+');
opt.add('/');
opt.add('-');
qcal.setOperands(opd);
qcal.setOperators(opt);
qcal.setLength(4);
qcal.setDifficulty(1);
qcal.setID(2);
qcal.setText("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed vulputate lacus eu odio ultricies porta.");
String str = new String();
try {
str = qcal.encode();
//System.out.println("encode 1 qcal :" + str);
QuestionCalculation qcal2 = QuestionCalculation.decode(str);
//System.out.println("decode 1 qcal2 : " + qcal2);
str = qcal2.encode();
//System.out.println(str+ "\n");
} catch (EncodeException ee) {
} catch (DecodeException de) {}
QuestionFraction qfra = new QuestionFraction();
ArrayList<Integer> num = new ArrayList<Integer>();
num.add(12);
num.add(84);
num.add(45);
num.add(90);
ArrayList<Integer> dnm = new ArrayList<Integer>();
dnm.add(5);
dnm.add(3);
dnm.add(2);
dnm.add(45);
opt = new ArrayList<Character>();
opt.add('+');
opt.add('/');
opt.add('-');
qfra.setNumerators(num);
qfra.setDenominators(dnm);
qfra.setOperators(opt);
qfra.setLength(4);
qfra.setDifficulty(3);
qfra.setID(8);
qfra.setText("Sed vulputate lacus eu odio ultricies porta. Lorem ipsum dolor sit amet, consectetur adipiscing elit.");
//System.out.println(qfra.encode()+ "\n");
QuestionEquation qequ = new QuestionEquation();
opd = new ArrayList<Integer>();
opd.add(12);
opd.add(84);
opd.add(45);
opd.add(90);
ArrayList<Integer> ukn = new ArrayList<Integer>();
ukn.add(0);
ukn.add(0);
ukn.add(1);
ukn.add(0);
opt = new ArrayList<Character>();
opt.add('+');
opt.add('/');
opt.add('=');
qequ.setOperands(opd);
qequ.setOperators(opt);
qequ.setUnknowns(ukn);
qequ.setLength(4);
//System.out.println(qequ.encode());
QuestionPower qpow = new QuestionPower();
opt = new ArrayList<Character>();
opt.add('*');
opt.add('/');
opt.add('*');
qpow.setOperand(4);
qpow.setPowers(dnm);
qpow.setOperators(opt);
qpow.setLength(4);
qpow.setDifficulty(3);
qpow.setID(8);
qpow.setText("Sed vulputate lacus eu odio ultricies porta. Lorem ipsum dolor sit amet, consectetur adipiscing elit.");
Exercise ex = new Exercise();
ex.setTitle("machin");
ex.setID(3);
Object[] tval = {78,"ezr",9.32,34,'c',24};
ex.setWording(new Wording("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed vulputate lacus eu odio ultricies porta. Cras blandit aliquam nisi at iaculis. Pellentesque tincidunt neque et est ultrices, nec luctus risus consequat. Pellentesque sed est magna. Phasellus ullamcorper ligula eu est vehicula, sit amet hendrerit leo malesuada. Cras fringilla lorem sit amet pharetra porttitor. Nullam venenatis convallis nisi. Nulla sem sem. ", tval));
ex.setType("calculation");
ex.setDifficulty(4);
ex.addQuestion(qcal);
ex.addQuestion(qfra);
ex.addQuestion(qpow);
ex.update_ready();
try {
System.out.println("\n\n" + ex);
str = ex.encode();
System.out.println("\n\n" + str);
Exercise e = Exercise.decode(str);
System.out.println(e);
} catch (EncodeException ee) {
} catch (DecodeException de) {}
System.out.println(qpow.solve());
System.out.println();
double d = 1.0 / 3;
System.out.println(d);
System.out.println(d * 3);
QuestionEquation qe = QuestionEquation.decode("#QuestionEquation<9:3:7:3><1:0:2:2><-:*:=><4><-1><$<Solve.>$><0>");
double[] res = qe.solve();
System.out.println("\n" + res[0]);
System.out.println(res[1]);
} catch (DecodeException ex1) {
Logger.getLogger(TestKernel57.class.getName()).log(Level.SEVERE, null, ex1);
}
} | 5 |
int[] getMaxCardOrder(boolean[][] bAdjacencyMatrix) {
int nNodes = bAdjacencyMatrix.length;
int[] order = new int[nNodes];
if (nNodes==0) {return order;}
boolean[] bDone = new boolean[nNodes];
// start with node 0
order[0] = 0;
bDone[0] = true;
// order remaining nodes
for (int iNode = 1; iNode < nNodes; iNode++) {
int nMaxCard = -1;
int iBestNode = -1;
// find node with higest cardinality of previously ordered nodes
for (int iNode2 = 0; iNode2 < nNodes; iNode2++) {
if (!bDone[iNode2]) {
int nCard = 0;
// calculate cardinality for node iNode2
for (int iNode3 = 0; iNode3 < nNodes; iNode3++) {
if (bAdjacencyMatrix[iNode2][iNode3] && bDone[iNode3]) {
nCard++;
}
}
if (nCard > nMaxCard) {
nMaxCard = nCard;
iBestNode = iNode2;
}
}
}
order[iNode] = iBestNode;
bDone[iBestNode] = true;
}
return order;
} // getMaxCardOrder | 8 |
private void checkMeltdownAdvance() {
if ((! structure.intact()) && meltdown == 0) return ;
float chance = meltdownChance() / World.STANDARD_DAY_LENGTH ;
chance += meltdown / 10f ;
if (isManned()) chance /= 2 ;
if (Rand.num() < chance) {
final float melt = 0.1f * Rand.num() ;
meltdown += melt ;
if (verbose) I.say(" MELTDOWN LEVEL: "+meltdown) ;
if (meltdown >= 1) performMeltdown() ;
final float damage = melt * meltdown * 2 * Rand.num() ;
structure.takeDamage(damage) ;
structure.setBurning(true) ;
}
} | 6 |
public static JSONObject toJSONObject(String string) throws JSONException {
String name;
JSONObject jo = new JSONObject();
Object value;
JSONTokener x = new JSONTokener(string);
jo.put("name", x.nextTo('='));
x.next('=');
jo.put("value", x.nextTo(';'));
x.next();
while (x.more()) {
name = unescape(x.nextTo("=;"));
if (x.next() != '=') {
if (name.equals("secure")) {
value = Boolean.TRUE;
} else {
throw x.syntaxError("Missing '=' in cookie parameter.");
}
} else {
value = unescape(x.nextTo(';'));
x.next();
}
jo.put(name, value);
}
return jo;
} | 3 |
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Update other = (Update) obj;
if (version == null) {
if (other.version != null) {
return false;
}
} else if (!version.equals(other.version)) {
return false;
}
return true;
} | 6 |
static protected void FillBuff() throws java.io.IOException
{
if (maxNextCharInd == available)
{
if (available == bufsize)
{
if (tokenBegin > 2048)
{
bufpos = maxNextCharInd = 0;
available = tokenBegin;
}
else if (tokenBegin < 0)
bufpos = maxNextCharInd = 0;
else
ExpandBuff(false);
}
else if (available > tokenBegin)
available = bufsize;
else if ((tokenBegin - available) < 2048)
ExpandBuff(true);
else
available = tokenBegin;
}
int i;
try {
if ((i = inputStream.read(buffer, maxNextCharInd, available - maxNextCharInd)) == -1)
{
inputStream.close();
throw new java.io.IOException();
}
else
maxNextCharInd += i;
return;
}
catch(java.io.IOException e) {
--bufpos;
backup(0);
if (tokenBegin == -1)
tokenBegin = bufpos;
throw e;
}
} | 9 |
public void visit_aaload(final Instruction inst) {
stackHeight -= 2;
if (stackHeight < minStackHeight) {
minStackHeight = stackHeight;
}
stackHeight += 1;
} | 1 |
@Override
public void setEditPane(Contestant c, boolean newContestant) {
GameData g = GameData.getCurrentGame();
tfContID.setEnabled(!g.isSeasonStarted());
if (newContestant || c == null) {
// set default values
tfContID.setText("");
tfFirstName.setText("First Name");
tfLastName.setText("Last Name");
cbTribe.setSelectedIndex(0);
updateContPicture(DEFAULT_PICTURE);
return;
}
tfFirstName.setText(c.getFirstName());
tfLastName.setText(c.getLastName());
cbTribe.setSelectedItem(c.getTribe());
tfContID.setText(c.getID());
if (c.isCastOff())
cbCastDate.setSelectedIndex(g.getCurrentWeek()-c.getCastDate()+1);
else
cbCastDate.setSelectedIndex(0);
updateContPicture(c.getPicture());
} | 3 |
public synchronized void register(Action action) {
if(action instanceof OrderDependentAction || !action.activate(getRemainingTime()))
actions.add(action);
} | 2 |
private boolean isValidPlayer(Entity entity) {
boolean isValidPlayer = false;
if (entity instanceof Player) {
boolean isNPC = false;
if (plugin.cititzensPlugin != null) {
try {
isNPC = plugin.cititzensPlugin.getDescription().getVersion().startsWith("2") ?
CitizensAPI.getNPCRegistry().isNPC(entity) : CitizensManager.isNPC(entity);
} catch (NumberFormatException e) {
// move along, nothing to see here :)
}
}
isValidPlayer = isNPC ? false : true;
}
return isValidPlayer;
} | 5 |
@Override
public FileVisitResult preVisitDirectory(Path pDir, BasicFileAttributes attr) {
if (!pDir.toString().contains(
"dynmap" + System.getProperty("file.separator") + "web")) {// Comment out this if to allow copying of files in a folder called dynmap\web
try {
dirNum++;
if (dirNum > 1) {
String sDir = pDir.toString();
copyToNewDir = Paths.get(fullPath
+ System.getProperty("file.separator")
+ sDir.substring(copyPath.toString().length()));
} else {
copyToNewDir = fullPath;
}
Files.copy(pDir, copyToNewDir);
System.out.println("Copying folder " + pDir + " to "
+ copyToNewDir);
} catch (IOException e) {
System.out.println("Copying folder " + pDir
+ " failed to copy to " + copyToNewDir);
System.out.println(e);
}
} //end of the if to comment out
return CONTINUE;
} | 3 |
public void setAddressCompany(Address addressCompany) {
this.addressCompany = addressCompany;
} | 0 |
public void setWorkingDay(String workingDay) {
WorkingDay = workingDay;
} | 0 |
public void improveCity() {
if ( selected.getClass() == Worker.class ) {
Tile tile = selected.getTile();
if ( tile.getCity() != null ) {
((Unit)selected).owner.removeUnit( (Unit)selected );
tile.getCity().Production += IMPROVE_CITY_PRODUCTION;
tile.getCity().PP += IMPROVE_CITY_PRODUCTION;
selected = tile.getCity();
}
}
} | 2 |
public void destroy(String id) throws IllegalOrphanException, NonexistentEntityException, RollbackFailureException, Exception {
EntityManager em = null;
try {
em = getEntityManager();
em.getTransaction().begin();
Telecommunications telecommunications;
try {
telecommunications = em.getReference(Telecommunications.class, id);
telecommunications.getIdTelecom();
} catch (EntityNotFoundException enfe) {
throw new NonexistentEntityException("The telecommunications with id " + id + " no longer exists.", enfe);
}
List<String> illegalOrphanMessages = null;
Collection<ItItem> itItemCollectionOrphanCheck = telecommunications.getItItemCollection();
for (ItItem itItemCollectionOrphanCheckItItem : itItemCollectionOrphanCheck) {
if (illegalOrphanMessages == null) {
illegalOrphanMessages = new ArrayList<String>();
}
illegalOrphanMessages.add("This Telecommunications (" + telecommunications + ") cannot be destroyed since the ItItem " + itItemCollectionOrphanCheckItItem + " in its itItemCollection field has a non-nullable telecommunicationsidTelecom field.");
}
if (illegalOrphanMessages != null) {
throw new IllegalOrphanException(illegalOrphanMessages);
}
em.remove(telecommunications);
em.getTransaction().commit();
} catch (Exception ex) {
try {
em.getTransaction().rollback();
} catch (Exception re) {
throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
}
throw ex;
} finally {
if (em != null) {
em.close();
}
}
} | 7 |
protected String toJSONFragment() {
StringBuffer json = new StringBuffer();
boolean first = true;
if (isSetDate()) {
if (!first) json.append(", ");
json.append(quoteJSON("Date"));
json.append(" : ");
json.append(quoteJSON(getDate() + ""));
first = false;
}
if (isSetTransactionStatus()) {
if (!first) json.append(", ");
json.append(quoteJSON("TransactionStatus"));
json.append(" : ");
json.append(quoteJSON(getTransactionStatus().value()));
first = false;
}
if (isSetStatusCode()) {
if (!first) json.append(", ");
json.append(quoteJSON("StatusCode"));
json.append(" : ");
json.append(quoteJSON(getStatusCode()));
first = false;
}
if (isSetAmount()) {
if (!first) json.append(", ");
json.append("\"Amount\" : {");
Amount amount = getAmount();
json.append(amount.toJSONFragment());
json.append("}");
first = false;
}
return json.toString();
} | 8 |
char[][] getMap() {
char[][] map = new char[activeBoardSize+2][activeBoardSize+2];
for(int i=0; i<map.length; i++) {
for(int j=0; j<map[0].length; j++) {
map[i][j] = ' ';
}
}
for(Fence f:staticFences) {
map[f.getX()][f.getY()] = 'f';
}
for(Fence f:activeFences) {
map[f.getX()][f.getY()] = 'f';
}
for(Mho m:mhos) {
map[m.getX()][m.getY()] = 'm';
}
map[p1.getX()][p1.getY()] = 'p';
return map;
} | 5 |
public void updatePosition(Level terrain)
{
boolean collision = false;
while (detectHorizontalCollision(terrain) == true)
{
collision = true;
if (heroxSpeed < 0)
{
heroxSpeed = (int)(heroxSpeed + 1);
}
else if (heroxSpeed > 0)
{
heroxSpeed = (int)(heroxSpeed - 1);
}
}
herox += heroxSpeed;
if (collision)
heroxSpeed = 0;
collision = false;
while (detectVerticalCollision(terrain) == true)
{
collision = true;
if (heroySpeed < 0)
{
heroySpeed = (int)(heroySpeed + 1);
}
else if (heroySpeed > 0)
{
heroySpeed = (int)(heroySpeed - 1);
}
}
heroy += heroySpeed;
if (collision)
heroySpeed = 0;
} | 8 |
@Override
public String getTileUrl(int x, int y, int zoom)
{
int ty = y;
int tx = x;
// int width_in_tiles = (int)Math.pow(2,pyramid_top-zoom);
int width_in_tiles = getMapWidthInTilesAtZoom(zoom);
// System.out.println("width in tiles = " + width_in_tiles + " x = " + tx + " y = " + ty);
if (ty < 0)
{
return null;
}
if (zoom < midpoint)
{
if (ty >= width_in_tiles / 2)
{
return null;
}
}
else
{
if (ty != 0)
{
return null;
}
}
String url = this.baseURL + "/" + zoom + "/" + ty + "/" + tx + ".jpg";
// System.out.println("returning: " + url);
return url;
} | 4 |
public final Object nextValue() throws JSONException {
char c = nextClean();
String s;
switch (c) {
case '"':
case '\'':
return nextString(c);
case '{':
back();
return new JSONObject(this);
case '[':
case '(':
back();
return new JSONArray(this);
}
/*
* Handle unquoted text. This could be the values true, false, or
* null, or it can be a number. An implementation (such as this one)
* is allowed to also accept non-standard forms.
*
* Accumulate characters until we reach the end of the text or a
* formatting character.
*/
StringBuffer sb = new StringBuffer();
while (c >= ' ' && ",:]}/\\\"[{;=#".indexOf(c) < 0) {
sb.append(c);
c = next();
}
back();
s = sb.toString().trim();
if (s.equals("")) {
throw syntaxError("Missing value");
}
return JSONObject.stringToValue(s);
} | 8 |
public static void main(String[] args)
{
Scanner eingabeScanner = new Scanner(System.in);
String[] namen = null;
boolean wiederholen = true;
// do ... while Schleife wird mindestens einmal ausgefuehrt
do
{
System.out.println("Bitte eine Nummer wählen: 1.Erstellen, 2.Suchen oder 3.Anzeigen ");
// nur wenn eine Ganzzahl eingegeben wird machen wir weiter
if (eingabeScanner.hasNextInt())
{
int wahl = eingabeScanner.nextInt();
if (namen == null && (wahl == 2 || wahl == 3)) {
System.out.println("Bitte zuerst eine Liste erstellen! ");
} else {
// die Zahl im case bezieht sich immer auf die Variable beim switch
switch (wahl) {
case 1:
namen = erstellen();
break;
case 2:
System.out.println("Bitte ein Wort ohne Leerzeichen eingeben: ");
if (eingabeScanner.hasNext())
{
String suchText = eingabeScanner.next();
suchen(suchText, namen);
}
break;
case 3:
anzeigen(namen);
break;
default:
System.out.println("Ende ...");
wiederholen = false;
}
}
} else
{
System.out.println("falsche Eingabe!!!");
wiederholen = false;
}
} while (wiederholen);
eingabeScanner.close();
} | 9 |
public void muteToType(EntityType newType) {
if (type != EntityType.ABSTRACT_CLASS && type != EntityType.CLASS && type != EntityType.ENUM
&& type != EntityType.INTERFACE) {
throw new IllegalArgumentException("type=" + type);
}
if (newType != EntityType.ABSTRACT_CLASS && newType != EntityType.CLASS && newType != EntityType.ENUM
&& newType != EntityType.INTERFACE) {
throw new IllegalArgumentException("newtype=" + newType);
}
this.type = newType;
} | 8 |
public void starteSpiel() {
for (int zeile = 0; zeile < spielfeld.length; zeile++) {
for (int spalte = 0; spalte < spielfeld[zeile].length; spalte++) {
spielfeld[zeile][spalte] = "[ ]";
}
}
platziereSpieler();
Spieler gewinner = null;
int runde = 0;
GamePrinter.printSpielfeld(spielfeld, spielerReihenfolge);
Date startZeit = new Date();
Date endZeit = null;
do {
runde++;
spiel: for (Spieler aktuellerSpieler : spielerReihenfolge) {
GamePrinter.printAktuellerSpieler(aktuellerSpieler, runde);
Figur gewaehlteFigur = aktuellerSpieler.waehleFigur(spielfeld);
boolean weitererZugMoeglich = true;
ArrayList<int[]> mglZuege = gewaehlteFigur
.findeZuege(spielfeld);
ArrayList<int[]> altePos = new ArrayList<int[]>();
int index = 0;
while (weitererZugMoeglich) {
altePos.add(index, gewaehlteFigur.getPosition());
aktuellerSpieler.waehleZug(mglZuege, gewaehlteFigur,
spielfeld);
bewegeFigur(altePos.get(index), gewaehlteFigur);
GamePrinter.printSpielzug(aktuellerSpieler,
altePos.get(index), gewaehlteFigur.getPosition());
GamePrinter.printSpielfeld(spielfeld, spielerReihenfolge);
mglZuege = moeglicheSpruenge(gewaehlteFigur, spielfeld,
altePos);
if (mglZuege.isEmpty()) {
weitererZugMoeglich = false;
// Testzweck
System.out.println("Kein weiterer Zug möglich.");
} else {
weitererZugMoeglich = true;
weitererZugMoeglich = aktuellerSpieler
.zugWeiterfuehren();
// Testzweck
if (weitererZugMoeglich == false) {
System.out.println("Kein weiterer Zug.");
} else {
System.out.println("Zieht weiter.");
}
}
sleep(100);
index++;
if (isGewonnen(aktuellerSpieler.getFigurenArray(),
aktuellerSpieler.berechneZielPositionen())) {
endZeit = new Date();
gewinner = aktuellerSpieler;
break spiel;
}
}
}
} while (gewinner == null);
beendeSpiel(gewinner, runde, startZeit, endZeit);
} | 8 |
public RequestWrapper getRequestWrapper() {
return requestWrapper;
} | 0 |
private void updateElement() {
try {
SortedMap<String, Object> map = updateElementTableModel.getProperties();
ElementListViewHelper helper = (ElementListViewHelper) updateElementsComboBox.getSelectedItem();
if(helper == null)
return;
NetworkHardware nh = (NetworkHardware) helper.getNetworkHardware();
for(String s : map.keySet()) {
nh.setProperty(map.get(s), s);
}
DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
dos.writeBytes(ServerFrame.updateElementCmd + "\n");
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
oos.writeObject(nh);
} catch(Exception e) {
e.printStackTrace();
}
} | 3 |
public static void main(String[] args) {
List<Integer> topList = new ArrayList<Integer>();
for(int j= 1;j<100;j++){
System.out.println("team size = " + j);
for(int i = 1 ; i <= j ;i++){
topList.add(i);
}
if(topList.size() % 2 ==0 && topList.size() %4 !=0){
int size = topList.size();
int f1 = topList.remove(size-1);
int f2 = topList.remove(size-2);
matching(f1, f2);
}
while (topList.size()%4!=0){
topList.add(0);
}
for(int i=0;i<topList.size();){
int f1 = topList.get(i++);
int f2 = topList.get(i++);
int f3 = topList.get(i++);
int f4 = topList.get(i++);
Random r = new Random();
if(r.nextInt(2) == 0){
matching(f1, f2);
matching(f3, f4);
}else{
matching(f1, f3);
matching(f2, f4);
}
}
System.out.println("--------------------");
topList.clear();
}
} | 7 |
public void processVideo() throws Exception {
if (converterThread != null && converterThread.isAlive()) {
throw new Exception("Convert is already running");
}
if (videoInputPath == null) {
throw new Exception("Video input is not specified.");
}
if (videoOutputPath == null) {
throw new Exception("Video output is not specified.");
}
delegate.disableRenderButton();
converterThread = new ConverterThread(this, videoInputPath, videoOutputPath);
converterThread.start();
} | 4 |
private void menuItemSaveAsActionPerformed(ActionEvent evt)
{
JFileChooser fc = new JFileChooser();
fc.setAcceptAllFileFilterUsed(false);
fc.setFileFilter(new FileFilter()
{
public boolean accept( File f )
{
return f.isDirectory() || f.getName().toLowerCase().endsWith(".ser");
}
public String getDescription()
{
return "Datei" + " (*.ser)";
}
});
int result = fc.showSaveDialog(drawComponent1);
if(result == JFileChooser.APPROVE_OPTION)
{
File file = fc.getSelectedFile();
path = file.getPath();
if(file.exists())
{
result = JOptionPane.showOptionDialog(drawComponent1, "Datei ueberschreiben?", null,
JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE,
null, null, null);
switch(result)
{
case 0: saveAs((path));
break;
case 1: menuItemSaveAsActionPerformed(evt);
break;
case 2: break;
}
}
else
{
saveAs((path + ".ser"));
path = path + ".ser";
}
}
} | 6 |
public static void main( String[] argv ) {
try {
String filename;
String stopMark;
if( argv.length >= 1 ) filename = argv[0];
else filename = "document_root_alpha/example.POST_DATA.txt";
if( argv.length >= 2 ) stopMark = argv[1];
else stopMark = "----WebKitFormBoundaryeANQMKoBwsmwQrYZ";
System.out.println( "Using stopMark: " + stopMark );
System.out.println( "Reading file until stopMark will be found ... ");
java.io.FileInputStream fin = new java.io.FileInputStream( new java.io.File(filename) );
MultipartMIMETokenizer tokenizer = new MultipartMIMETokenizer( fin,
stopMark );
InputStream token;
int i = 0;
while( (token = tokenizer.getNextToken()) != null ) {
int b;
System.out.println( "Reading bytes from token ["+i+"] ..." );
int len = 0;
while( (b = token.read()) != -1 ) {
System.out.print( (char)b );
len++;
}
System.out.println( "\n" + len +" bytes read from token [" + i+ "]." );
System.out.println( "----------------------------------------------" );
token.close();
i++;
}
} catch( IOException e ) {
e.printStackTrace();
}
} | 5 |
public void render() {
RoofObject[][] SubArea = getVisibleMap(Screen.getPlayer());
for (int x = 0; x < SubArea.length; x++) {
for (int y = 0; y < SubArea[0].length; y++) {
if (!(SubArea[x][y] == null))
renderObject(x, y, SubArea[x][y]);
}
}
} | 3 |
public static void setPlayerAFK( String player, boolean sendGlobal, boolean hasDisplayPerm ) {
BSPlayer p = getPlayer( player );
if ( !p.isAFK() ) {
p.setAFK( true );
if ( sendGlobal ) {
sendBroadcast( Messages.PLAYER_AFK.replace( "{player}", p.getDisplayingName() ) );
} else {
sendServerMessage( p.getServer(), Messages.PLAYER_AFK.replace( "{player}", p.getDisplayingName() ) );
}
if ( hasDisplayPerm ) {
p.setTempName( Messages.AFK_DISPLAY + p.getDisplayingName() );
}
} else {
p.setAFK( false );
if ( hasDisplayPerm ) {
p.revertName();
}
if ( sendGlobal ) {
sendBroadcast( Messages.PLAYER_NOT_AFK.replace( "{player}", p.getDisplayingName() ) );
} else {
sendServerMessage( p.getServer(), Messages.PLAYER_NOT_AFK.replace( "{player}", p.getDisplayingName() ) );
}
}
} | 5 |
private static int count(String filename) throws IOException {
InputStream is = new BufferedInputStream(new FileInputStream(
filename));
try {
byte[] c = new byte[1024];
int count = 0;
int readChars = 0;
boolean empty = true;
while ((readChars = is.read(c)) != -1) {
empty = false;
for (int i = 0; i < readChars; ++i) {
if (c[i] == '\n') {
++count;
}
}
}
return (count == 0 && !empty) ? 1 : count;
} finally {
is.close();
}
} | 5 |
@Override
public void insertString(int offs, String str, AttributeSet a)
throws BadLocationException {
if (str == null) {
return;
}
char[] chars = str.toCharArray();
boolean ok = true;
for (int i = 0; i < chars.length; i++) {
try {
Integer.parseInt(String.valueOf(chars[i]));
} catch (NumberFormatException exc) {
ok = false;
break;
}
}
if (ok)
super.insertString(offs, new String(chars), a);
} | 4 |
public String longestPalindrome_3(String s){// greedy solution
String res = "";
for(int i = 0; i < s.length(); ++i){
String ex = extend(s, i, i);
res = res.length() < ex.length() ? ex : res;
}
for(int i = 0; i < s.length() - 1; ++i){
String ex = extend(s, i, i+1);
res = res.length() < ex.length() ? ex : res;
}
return res;
} | 4 |
public Path BestPath(Path p1, Path p2) {
Path output = p1;
if (p1 == null
|| (p2 != null && playerCount != 3 && p2.getAverageWorth() > p1
.getAverageWorth())) {
output = p2;
} else if (p2 != null
&& p2.getAverageWorthNeutral() > p1.getAverageWorth()) {
output = p2;
}
return output;
} | 6 |
public PokeSelectWin()
{
this.setTitle("????");
this.setSize(300,400);
this.setResizable(false);
this.setLayout(null);
this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
this.setVisible(false);
visible = false;
this.setLocationRelativeTo(null);
cp = this.getContentPane();
close = new JButton();
close.setText("Close Window");
close.addActionListener(this);
cp.add(close);
for (int i = 0; i<poke.length; i++)
{
pokeInfo[i] = new JLabel();
poke[i] = new JButton();
poke[i].addActionListener(this);
}
for (int i = 0; i<moves.length; i++)
{
moveInfo[i] = new JLabel();
moves[i] = new JButton();
moves[i].addActionListener(this);
}
messageDisplay = new JLabel("");
} | 2 |
public static String compress(String s) {
if(s.length() <= 1) {
return s;
}
char c = s.charAt(0);
StringBuilder sb = new StringBuilder();
int count = 0;
for(int i = 0; i < s.length(); i++) {
if(c == s.charAt(i)) {
count++;
}
else {
sb.append(c);
sb.append(count);
c = s.charAt(i);
count = 1;
}
}
sb.append(c);
sb.append(count);
return s.length() <= sb.length() ? s : sb.toString();
} | 4 |
public static ArrayList<String> getPlayerOwnList(String playerUUID) {
ArrayList<String> places = new ArrayList<String>();
if (Spectacles.storedPlayerData == null) {
return places;
} else {
places = Spectacles.storedPlayerData.get(playerUUID);
return places;
}
} | 1 |
AbstractCar(RegistrationNumber registrationNumber, int fuelCapacity, int fuelInCar, boolean carRented){
this.registrationNumber = RegistrationNumber.getInstance(registrationNumber.getLetterIdentifier(), registrationNumber.getNumberIdentifier());
if (RegistrationNumber.getInstance(registrationNumber.getLetterIdentifier(), registrationNumber.getNumberIdentifier()).equals(null))
throw new IllegalArgumentException("That is not a valid Registration Number.");
this.fuelCapacity = fuelCapacity;
if(fuelCapacity <= 0)
throw new IllegalArgumentException("The fuel capacity is inappropriate.");
this.fuelInCar = fuelInCar;
if (fuelInCar > fuelCapacity || fuelInCar < 0)
throw new IllegalArgumentException("The fuel in car is a unacceptable amount.");
this.carRented = carRented;
} | 4 |
private void checkPrintFunction() throws Exception {
if(iterator < tokenList.size() && tokenList.get(iterator++).getType() != TokenType.L_PAR) {
// missing opening parenthesis
throw new Exception("Syntax Error at line " + tokenList.get(iterator-1).getLine() +
": Expected ( and got \"" + tokenList.get(iterator-1).getKey() + "\" instead");
}
checkMessage();
if(iterator < tokenList.size() && tokenList.get(iterator++).getType() != TokenType.R_PAR) {
// missing closing parenthesis
throw new Exception("Syntax Error at line " + tokenList.get(iterator-1).getLine() +
": Expected ) and got \"" + tokenList.get(iterator-1).getKey() + "\" instead");
}
if(iterator < tokenList.size() && tokenList.get(iterator++).getType() != TokenType.SEMICOLLON) {
// missing semicollon
throw new Exception("Syntax Error at line " + tokenList.get(iterator-1).getLine() +
": Expected ; and got \"" + tokenList.get(iterator-1).getKey() + "\" instead");
}
} | 6 |
public static RealVector solve(RealMatrix A, RealVector y, int k) {
RealVector xest = new ArrayRealVector(new double[A.getColumnDimension()]);
RealMatrix z = A;
RealVector v = y;
int t = 0;
int[] T2=null;
while (t < 100) {
//System.out.println(String.valueOf(t) + " th iteration");
double[] v_d = (A.transpose().operate(v)).toArray();
for (int i = 0; i < v_d.length; i++)
v_d[i] = Math.abs(v_d[i]);
//CSUtils.showVector(new ArrayRealVector(v_d));
ArrayIndexComparator comparator = new ArrayIndexComparator(v_d);
Integer[] z1 = comparator.createIndexArray();
Arrays.sort(z1, comparator);
Arrays.sort(v_d);
flipud(v_d, z1);
Integer[] Omega = Arrays.copyOfRange(z1, 0, 2 * k);
int[] T;
if (t != 0) {
T = unionSort(convertToIntArray(Omega), T2);
} else {
T = convertToIntArray(Omega);
Arrays.sort(T);
}
//CSUtils.showIndexVector(T);
RealMatrix At = MatrixUtils.createRealMatrix(A.getRowDimension(), T.length);
//CSUtils.showMatrix(A);
for(int i=0; i<T.length; i++){
// System.out.println(String.valueOf(A.getColumnVector(T[i])));
At.setColumnVector(i, A.getColumnVector(T[i]));
}
//Algorithm...
RealMatrix At_I = new SingularValueDecomposition(At).getSolver().getInverse();
RealVector b = At_I.operate(y);
absRealVector(b);
double[] k3 = b.toArray();
ArrayIndexComparator comparator1 = new ArrayIndexComparator(k3);
Integer[] z3 = comparator1.createIndexArray();
Arrays.sort(z3,comparator1);
Arrays.sort(k3);
flipud(k3, z3);
xest = new ArrayRealVector(A.getColumnDimension());
Integer[] z3_1 = Arrays.copyOfRange(z3, 0, k);
int count = 0;
for(int i : z3_1){
xest.setEntry(T[i],Math.abs(b.getEntry(i)));
count++;
}
absRealVector(xest);
double[] k2 = xest.toArray();
ArrayIndexComparator comparator2 = new ArrayIndexComparator(k2);
Integer[] z2 = comparator2.createIndexArray();
Arrays.sort(z2,comparator2);
Arrays.sort(k2);
flipud(k2,z2);
//xest = new ArrayealVector(xest_a);
T2 = convertToIntArray(Arrays.copyOfRange(z2, 0, k));
v = y.subtract(A.operate(xest));
absRealVector(v);
double n2 = v.getLInfNorm();
if(n2<tol){
break;
}
//System.out.println(xest);
t++;
}
return xest;
} | 6 |
@Override
public List<Autor> ListByNome(String nome) {
Connection conn = null;
PreparedStatement pstm = null;
ResultSet rs = null;
List<Autor> autores = new ArrayList<>();
try{
conn = ConnectionFactory.getConnection();
pstm = conn.prepareStatement(LISTBYNOME);
pstm.setString(1,"%" + nome + "%");
rs = pstm.executeQuery();
while(rs.next()){
Autor a = new Autor();
a.setId_autor(rs.getInt("id_autor"));
a.setNome(rs.getString("nome_au"));
a.setSobrenome(rs.getString("sobrenome_au"));
a.setEmail(rs.getString("email_au"));
autores.add(a);
}
}catch(Exception e){
JOptionPane.showMessageDialog(null,"Erro ao listar autor por nome " + e);
}finally{
try{
ConnectionFactory.closeConnection(conn, pstm, rs);
}catch(Exception e){
JOptionPane.showMessageDialog(null,"Erro ao desconectar com o banco " + e);
}
}
return autores;
} | 3 |
private void swap(Object[] array, int i, int change) {
Object helper = array[i];
array[i] = array[change];
array[change] = helper;
} | 0 |
public void putAll( Map<? extends Long, ? extends Long> map ) {
Iterator<? extends Entry<? extends Long,? extends Long>> it =
map.entrySet().iterator();
for ( int i = map.size(); i-- > 0; ) {
Entry<? extends Long,? extends Long> e = it.next();
this.put( e.getKey(), e.getValue() );
}
} | 8 |
public void draw(GOut g) {
Coord dc = new Coord();
if (drawbg)
for (dc.y = 0; dc.y < sz.y; dc.y += texpap.sz().y) {
for (dc.x = 0; dc.x < sz.x; dc.x += texpap.sz().x) {
g.image(texpap, dc);
}
}
g.chcolor();
int y = -cury;
synchronized (lines) {
for (Text line : lines) {
int dy1 = sz.y + y;
int dy2 = dy1 + line.sz().y;
if ((dy2 > 0) && (dy1 < sz.y))
g.image(line.tex(), new Coord(margin, dy1));
y += line.sz().y;
}
}
if (maxy > sz.y) {
int fx = sz.x - sflarp.sz().x;
int cx = fx + (sflarp.sz().x / 2) - (schain.sz().x / 2);
for (y = 0; y < sz.y; y += schain.sz().y - 1)
g.image(schain, new Coord(cx, y));
double a = (double) (cury - sz.y) / (double) (maxy - sz.y);
int fy = (int) ((sz.y - sflarp.sz().y) * a);
g.image(sflarp, new Coord(fx, fy));
}
} | 8 |
public void update(GameContainer gc, StateBasedGame sb, int delta) {
Input in = gc.getInput();
if(in.isKeyDown(Input.KEY_L))
{
Mob mob = RPG372.gameInstance.getNearestMob();
if(mob != null){
FightState fs = (FightState)sb.getState(RPG372.FIGHT);
fs.setMob(mob);
fs.setCurrentPlayer(RPG372.gameInstance.getCurrentPlayer());
sb.enterState(RPG372.FIGHT);
}else{
Vendor vend = RPG372.gameInstance.getNearestVendor();
if(vend != null){
TradeState ts = (TradeState)sb.getState(RPG372.TRADE);
ts.setPlayer(RPG372.gameInstance.getCurrentPlayer());
ts.setVendor(vend);
sb.enterState(RPG372.TRADE);
}
}
}
} | 3 |
private void read(Reader reader) throws IOException {
ScanfReader scanReader = new ScanfReader(reader);
try {
doread(scanReader);
} catch (Exception e) {
throw new IOException(e.getMessage() + ", line " + scanReader.getLineNumber());
}
//bulding the construction view straight from vc
if (!con.init) {
setConst();
con.setInit(true);
}
con.setChart(this);
// set prim obj list for rolling up the absolute tree
prims = new HashMap<String, BaseTableContainer>();
setPrims(mainPane);
for (BaseTableContainer btc : prims.values()) {
btc.setRollUp();
if (mainPane.getDepth() <= 2) {
btc.setWidth(headerWidth*3/2);
btc.repaint();
}
}
((BaseTableContainer) mainPane.rowList.get(0)).setAbstractRatios();
setConnectingFields();
if (isNew) {
menuOptions.setSelectedItems();
}
} | 5 |
public void findBestSystemEP() {
for (SoftwareSystem softwareSystem : systemsEP)
softwareSystem.refine();
bestSoftwareSystemEP = systemsEP.get(0);
worstSoftwareSystemEP = systemsEP.get(0);
for (SoftwareSystem softwareSystem : systemsEP) {
if (softwareSystem.getSystemConsumptionEP() < bestSoftwareSystemEP.getSystemConsumptionEP())
bestSoftwareSystemEP = softwareSystem;
else if (softwareSystem.getSystemConsumptionEP() > worstSoftwareSystemEP.getSystemConsumptionEP())
worstSoftwareSystemEP = softwareSystem;
}
} | 4 |
public void syncToGlobal() {
lineEnd.cur = Preferences.getPreferenceLineEnding(Preferences.SAVE_LINE_END).cur;
saveEncoding.cur = Preferences.getPreferenceString(Preferences.SAVE_ENCODING).cur;
saveFormat.cur = Preferences.getPreferenceString(Preferences.SAVE_FORMAT).cur;
ownerName.cur = Preferences.getPreferenceString(Preferences.OWNER_NAME).cur;
ownerEmail.cur = Preferences.getPreferenceString(Preferences.OWNER_EMAIL).cur;
applyFontStyleForComments.cur = Preferences.getPreferenceBoolean(Preferences.APPLY_FONT_STYLE_FOR_COMMENTS).cur;
applyFontStyleForEditability.cur = Preferences.getPreferenceBoolean(Preferences.APPLY_FONT_STYLE_FOR_EDITABILITY).cur;
applyFontStyleForMoveability.cur = Preferences.getPreferenceBoolean(Preferences.APPLY_FONT_STYLE_FOR_MOVEABILITY).cur;
useCreateModDates.cur = Preferences.getPreferenceBoolean(Preferences.USE_CREATE_MOD_DATES).cur;
createModDatesFormat.cur = Preferences.getPreferenceString(Preferences.CREATE_MOD_DATES_FORMAT).cur;
} | 0 |
public void updateEnemies(long time, Game game) {
// Loop through all the available enemies
for(int i = 0; i < enemies.length; i++) {
// Try block for safety.
try {
// If the enemy is alive, then let's update it.
if(enemies[i].living == true) { enemies[i].update(time,game); }
}
// If the enemy was never initialized, it'd throw a null pointer exception.
catch(NullPointerException e) {
break; // We won't check any more bullets after this one.
}
}
} | 3 |
public ArrayList<UserTuple> buildFriends(){
ArrayList<UserTuple> friendList = new ArrayList<UserTuple>();;
try {
ResultSet rslSet = dbMgr.executeQuery("select usrid1 from friend where usrid2='"+userId+"'");
if(rslSet !=null)
{
while(rslSet.next()){
ResultSet rslSet1 = dbMgr.executeQuery("select id,fname,lname,emailid,avatar from userinfo where id='"+rslSet.getString("usrid1")+"'");
if(rslSet1.next())
//friendList.add(new UserTuple(rslSet1.getString("id"), rslSet1.getString("fname") , rslSet1.getString("lname"), rslSet1.getString("emailid")));
friendList.add(buildUserTuple(rslSet1));
}
}
dbMgr.disconnect();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return friendList;
} | 4 |
private static boolean isType(String argument, ArgumentTypes arg)
{
switch(arg)
{
case NUMBER:
{
return isInteger(argument);
}
case QUEUE:
{
try
{
Queue.valueOf(argument);
return true;
}
catch(IllegalArgumentException e)
{
return false;
}
}
case SEASON:
{
try
{
Season.valueOf(argument);
return true;
}
catch(IllegalArgumentException e)
{
//Both numbers and written out versions of Season numbers are valid
if(isInteger(argument) && Integer.valueOf(argument) <= Season.CURRENT.getSeasonInt())
{
return true;
}
return false;
}
}
case GAMEMODE:
{
try
{
GameMode.valueOf(argument);
return true;
}
catch(IllegalArgumentException e)
{
return false;
}
}
default:
{
return false;
}
}
} | 9 |
@Override
public void executeMsg(Environmental host, CMMsg msg)
{
if((msg.target()==affected)
&&((msg.targetMinor()==CMMsg.TYP_LOOK)||(msg.targetMinor()==CMMsg.TYP_EXAMINE))
&&(CMLib.flags().canBeSeenBy(affected,msg.source()))
&&(affected instanceof MOB)
&&((daysRemaining>0)&&(monthsRemaining<=3)))
{
msg.addTrailerMsg(CMClass.getMsg(msg.source(),null,null,
CMMsg.MSG_OK_VISUAL,L("\n\r<S-NAME> <S-IS-ARE> obviously with child.\n\r"),
CMMsg.NO_EFFECT,null,
CMMsg.NO_EFFECT,null));
}
super.executeMsg(host,msg);
} | 7 |
public boolean optimize(final int numSteps, final double convergenceDelta) throws InvalidConfigurationException {
if (!configured) {
configure();
}
final int deltaNumSteps = numSteps/10;
final Genotype population = Genotype.randomInitialGenotype(configuration);
final boolean converged;
int timesFitnessStable = 0;
double previousFitness = -1;
progressLogger.expectedUpdates = numSteps;
progressLogger.start("optimization");
IChromosome fitestChromosome = null;
double fitness = -2;
for (int i = 0; i < numSteps; i++) {
// writeCurrentPopulation(population);
fitestChromosome = population.getFittestChromosome();
fitness = fitnessFunction.getFitnessValue(fitestChromosome);
fitestFunctionValue = fitness;
if (i % moduloProgressReport == 1) {
log.info("Current solution has a fitness value of " +
formatDouble(Math.log(fitestChromosome.getFitnessValue())) +
" absolute: " + formatDouble(Math.log(fitness)) +
"or raw: " + fitness);
log.debug(fitestChromosome.getGene(0).toString());
}
if (fitness >= previousFitness && fitness - previousFitness < Math.abs(convergenceDelta)) {
timesFitnessStable++;
log.trace("fitness function value stable " + timesFitnessStable);
} else {
timesFitnessStable = 0;
log.trace("fitness function not stable, old: " + previousFitness + " new fitness: " + fitness);
}
previousFitness = fitness;
if (timesFitnessStable >= deltaNumSteps) {
break;
}
numberOfIterationsPerformed = i;
if (i != numSteps - 1) {
// do not evolve if this is the last step.
population.evolve();
progressLogger.lightUpdate();
}
}
if (fitness - previousFitness < Math.abs(convergenceDelta)) {
converged = true;
} else {
converged = false;
}
progressLogger.stop("optimization");
convertFittestToSolution(fitestChromosome);
return converged;
} | 8 |
public Wave28(){
super();
MobBuilder m = super.mobBuilder;
for(int i = 0; i < 1000; i++){
if(i % 5 == 0)
add(m.buildMob(MobID.DODRIO));
else if(i % 4 == 0)
add(m.buildMob(MobID.FEAROW));
else if(i % 3 == 0)
add(m.buildMob(MobID.RATICATE));
else if(i % 2 == 0)
add(m.buildMob(MobID.DODUO));
else
add(m.buildMob(MobID.SPEAROW));
}
} | 5 |
public static void fillVacancies(Venue venue) {
//
// We automatically fill any positions available when the venue is
// established. This is done for free, but candidates cannot be screened.
if (venue.careers() == null) return ;
for (Background v : venue.careers()) {
final int numOpen = venue.numOpenings(v) ;
if (numOpen <= 0) continue ;
for (int i = numOpen ; i-- > 0 ;) {
final Human worker = new Human(v, venue.base()) ;
worker.mind.setWork(venue) ;
if (GameSettings.hireFree) {
final Tile e = venue.mainEntrance() ;
worker.enterWorldAt(e.x, e.y, venue.world()) ;
}
else {
venue.base().commerce.addImmigrant(worker) ;
}
}
}
} | 5 |
public static List<String> decodificarError(String errorJSON) {
List<String> resultado = new ArrayList<String>();
JSONParser parser = new JSONParser();
try {
Object objeto = parser.parse(errorJSON);
JSONObject objetoJSON = (JSONObject) objeto;
String error = (String) objetoJSON.get(ERROR);
resultado.add(ERROR);
resultado.add(error);
} catch (ParseException e) {
e.printStackTrace();
}
return resultado;
} | 1 |
public static String addBinary(String a, String b) {
int len = Math.max(a.length(), b.length());
a = padding(a, len);
b = padding(b, len);
String res = "";
char flag = '0';
for(int i = len -1; i >= 0; i--){
char c = a.charAt(i);
if(flag == '0') {
if(c == '0'){
res = b.charAt(i) + res;
} else {
if(b.charAt(i) == '0')
res = '1' + res;
else {
res = '0' + res;
flag = '1';
}
}
}else {
if(c == '0'){
if(b.charAt(i) == '1'){
res = '0' + res;
} else {
res = '1' + res;
flag = '0';
}
} else {
res = b.charAt(i) + res;
flag = '1';
}
}
}
if(flag == '1') return '1' + res;
return res;
} | 7 |
public int copyin(int [] a){
if (a.length == st.length)
st = (int[])a.clone();
else return -1;
return 0;
} | 1 |
@Override
public boolean mutate(DeterministicFiniteAutomaton dfa) {
Random rnd = new Random();
Set<State> states = dfa.getStates();
State[] stateArr = states.toArray(new State[0]);
if(states.size() <= 2){
return false;
}else{
//index of the state to be removed
int i;
State oldState = null;
//Start state shall not be removed
do{
i = rnd.nextInt(states.size());
oldState = stateArr[i];
}while(dfa.getStartState() == oldState || (dfa.getAcceptingStates().contains(oldState) && dfa.getAcceptingStates().size() == 1));
//replace links to the to-be-removed state from all other states
for(State s : states){
//TODO: Evaluate if self link or random link is to be prefered
//s.getTransitionTable().replaceTarget(oldState, s); //self link
//get a replacement state
State newState = null;
do{
newState = stateArr[rnd.nextInt(states.size())];
}while(newState == oldState);
s.getTransitionTable().replaceTarget(oldState, newState); // random link
}
if(dfa.getAcceptingStates().contains(oldState)){
dfa.getAcceptingStates().remove(oldState);
}
//remove the old state
states.remove(oldState);
return true;
}
} | 7 |
@Override
public void removeServerEventListener(IServerEventListener listener) {
serverEventListenerList.remove(IServerEventListener.class, listener);
} | 0 |
public final String getTitle() {
Object value = getValue(NAME);
return value != null ? value.toString() : null;
} | 1 |
public People updatePeople(String peopleID, String personName, String projectID, String role) {
People people = manager.find(People.class, peopleID);
if (people != null) {
people.setProjectID(projectID);
people.setPersonID(peopleID);
people.setRole(role);
people.setName(personName);
}
return people;
} | 1 |
@Override
public long doRead(Master master, ReadRequest readRequest) {
incrementAccessAndMaybeRecalibrate(master);
long fileId = readRequest.getFileId();
Location accessLoc = readRequest.getLocation();
MasterMeta fm = master.map.get(fileId);
if (fm == null || fm.instances.size() == 0) {
return -1;
}
long delay = -1;
Set<Cluster> attemptedClusters = new HashSet<Cluster>();
while (delay == -1 && attemptedClusters.size() < fm.instances.size()) {
double minDistance = Double.MAX_VALUE;
Cluster closest = null;
for (Cluster c : fm.instances) {
if (!c.isHealthy()) {
attemptedClusters.add(c);
continue;
}
if (attemptedClusters.contains(c)) {
continue;
}
double cDistance = c.getLocation().distance(accessLoc);
if (cDistance < minDistance) {
minDistance = cDistance;
closest = c;
}
}
FileRead fr = closest.read(fileId);
if (fr.time > 0) {
delay = fr.time + Util.networkTime(fr.file.getSize(), minDistance);
}
attemptedClusters.add(closest);
}
return delay;
} | 9 |
public Normal(double mu, double sigmaSquared) throws ParameterException {
if (sigmaSquared <= 0) {
throw new ParameterException("Normal parameters mu real, sigmaSquared > 0.");
}
rand = new Random();
this.mu = mu;
this.sigmaSquared = sigmaSquared;
sigma = Math.sqrt(sigmaSquared);
} | 1 |
private void getColor() {
color = new int[] { 0xFF111111, 0xFF000000, 0xFFC2FEFF };
switch (random.nextInt(8)) {
case 0: {
// red color
color[1] = 0xFFFF0000;
break;
}
case 1: {
// gold color
color[1] = 0xFFCFB53B;
break;
}
case 2: {
// blue color
color[1] = 0xFF005AFF;
break;
}
case 3: {
// silver color
color[1] = 0xFFCCCCCC;
break;
}
case 4: {
// black color
color[1] = 0xFF111111;
break;
}
case 5: {
// green color
color[1] = 0xFF066518;
break;
}
case 6: {
// purple color
color[1] = 0xFF580271;
break;
}
default: {
// White
color[1] = 0xFFFFFFFF;
break;
}
}
} | 7 |
void checkWorld(){
PVector toBest = new PVector(); //create a temp vector to keep track of the direction of the best condition
float maxV = 0;
//loop through pixels
for (int i = -p5.searchRad; i <= p5.searchRad; i++){
for (int j = -p5.searchRad; j <= p5.searchRad; j++){
if(!(i == 0 && j == 0)){
//checks for edges
int x = Stig2D.floor(location.x)+i;
x = Stig2D.constrain(x, 0, p5.width-1);
int y = Stig2D.floor(location.y)+j;
y = Stig2D.constrain(y, 0, p5.height-1);
//check to see if this is the smallest current value
//scale by the distance to the value
float v = p5.world.getAt(x, y);
PVector toV = new PVector(i, j);
//limit the angle of vision
if(PVector.angleBetween(toV,velocity)<Stig2D.PI/2){
//check to see if the current value is larger than
//the current best
if((v) > maxV){
//reset all our variables that keep track of the best option
float d = toV.mag();
toV.mult(1/d);
toBest = toV;
maxV = v;
}
}
}
}
}
//only effect if finding something above a tolerance
if(maxV>20){
applyForce(toBest);
}
} | 7 |
@Override
public void execute(CommandSender sender, String worldName, List<String> args) {
this.sender = sender;
if (worldName == null) {
error("No world given.");
reply("Usage: /gworld setannouncedeath <worldname> <true|false>");
} else if (!hasWorld(worldName)) {
reply("World not found: " + worldName);
} else {
Boolean announce;
announce = (args.size() == 0 || !args.get(0).equalsIgnoreCase("false")) ? true : false;
getWorld(worldName).setAnnouncePlayerDeath(announce);
reply("Death announcements on " + worldName + (announce ? " enabled." : " disabled."));
}
} | 5 |
public void actionPerformed(ActionEvent e)
{
for(int i = 0; i < Main.list.size(); i++)
{
if(Main.list.get(i).getStatic() == false)
{
if(Main.list.get(i).getX() < 47 || Main.list.get(i).getX() > 1198)
{
Utility.tableCollision(Main.list.get(i), true);
}
if(Main.list.get(i).getY() < 47 || Main.list.get(i).getX() > 598)
{
Utility.tableCollision(Main.list.get(i), false);
}
for(int a = 0; a < Main.list.size(); a++)
{
//check if the balls have collided
if(Math.sqrt(Math.pow(Main.list.get(i).getX() + Main.list.get(a).getX(), 2) + Math.pow(Main.list.get(i).getY() + Main.list.get(a).getY(), 2)) <= 23)
{
Utility.ballCollision(Main.list.get(i), Main.list.get(a));
}
}
}
}
} | 8 |
private List<Block> getGolemBlocks(EntityType type, Block base) {
ArrayList<Block> blocks = new ArrayList<Block>();
blocks.add(base);
base = base.getRelative(BlockFace.UP);
blocks.add(base);
if (type == EntityType.IRON_GOLEM) {
for (BlockFace face : new BlockFace[]{ BlockFace.NORTH, BlockFace.SOUTH, BlockFace.EAST, BlockFace.WEST }) {
Block arm = base.getRelative(face);
if (arm.getType() == Material.IRON_BLOCK)
blocks.add(arm);
}
}
base = base.getRelative(BlockFace.UP);
blocks.add(base);
return blocks;
} | 3 |
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable
{
method.invoke(obj, args); //利用反射调用需要调用的方法
return null;
} | 0 |
public ConfigurationLoader getConfiguration() {
return this.cloader;
} | 0 |
public void updateDatabase(){
//Temos alguma valor para inserir?
if(toInsert != null){
//Verificando a posição que ele vai entrar:
int temp = checkIfMadeIt(toInsert.getM_maxCoins());
if(temp >= 0){
m_scoreBoard.add(temp, new HighScoreEntry(toInsert.getM_playerName(), toInsert.getM_maxCoins()));
}
//Apagando a fila:
toInsert = null;
newEntry = false;
}
} | 2 |
@Override
public ArrayList<Delta> apply(Color c, int x, int y, Color[][] colorArr) {
if (start == null) {
start = new Point(x, y);
return new ArrayList<>();
} else {
Point p1 = start;
Point p2 = new Point(x,y);
ArrayList<Point> ch = bresenham(p1,p2);
ArrayList<Delta> deltas = new ArrayList<>();
for (Point d : ch) {
Delta del = new Delta(d.x,d.y,colorArr[d.x][d.y],c);
deltas.add(del);
colorArr[d.x][d.y] = c;
}
start = null;
return deltas;
}
} | 2 |
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.