method_id
stringlengths 36
36
| cyclomatic_complexity
int32 0
9
| method_text
stringlengths 14
410k
|
---|---|---|
9b41acee-0591-4ae8-8b51-ab91f356e8e8 | 7 | private boolean restPost(String restRequest, String[] pName, String[] pValue) {
String result = "";
String value = "";
if (pName != null && pValue != null && ! pName[0].isEmpty()) {
for (int i=0; i < pName.length; i++) {
value += "&" + pName[i] + "=" + pValue[i];
}
value = value.substring(1);
}
try {
// set up authorization for the redirected webpage (ie, $_POST variable)
String reqString = "" + m_apiHost + "/" + restRequest;
String rfcdate = setDate();
String sb = this.setAuth(restRequest, rfcdate);
// set up connection
URL postURL = new URL(reqString);
HttpURLConnection apiConn = (HttpURLConnection) postURL.openConnection();
setUpConn(apiConn, sb, rfcdate, value, "POST");
// get output
BufferedReader in = new BufferedReader(new InputStreamReader(apiConn.getInputStream()));
String tmp;
while ((tmp = in.readLine()) != null) {
result += tmp + "\n";
}
in.close();
// buffer
runBuffer();
if (apiConn.getResponseCode() != HttpURLConnection.HTTP_OK) {
throw new RuntimeException("Failed : HTTP error : "
+ apiConn.getResponseMessage() + ": returned data: " + result);
}
} catch (Exception e) {
pushFailedApi("restPost", restRequest, pName, pValue);
return false;
}
return true;
} |
c59a10fd-df47-43ef-9853-54b6a7c01d38 | 7 | protected void handleControlPropertyChanged(final String PROPERTY) {
if ("RESIZE".equals(PROPERTY)) {
resize();
} else if ("SWITCH_COLOR".equals(PROPERTY)) {
background.setStyle("-switch-color: " + Util.colorToCss((Color) getSkinnable().getSwitchColor()) + ";");
} else if ("THUMB_COLOR".equals(PROPERTY)) {
thumb.setStyle("-thumb-color: " + Util.colorToCss((Color) getSkinnable().getThumbColor()) + ";");
} else if ("SYMBOL_COLOR".equals(PROPERTY)) {
text.setTextFill(getSkinnable().getSymbolColor());
resize();
} else if ("TEXT".equals(PROPERTY)) {
text.setText(getSkinnable().getText());
resize();
} else if ("SELECTED".equals(PROPERTY)) {
if (getSkinnable().isSelected()) {
moveToSelected.play();
} else {
moveToDeselected.play();
}
}
} |
2ad1e26b-d459-44d2-830b-a1d7a7ec6c80 | 3 | protected void popFilters(String op, Filterable... queries) {
FilterGroup group = new FilterGroup().op(op);
for(Filterable q : queries) {
List<Filter> list = getFilterList(q);
if (list != null)
if (!list.isEmpty())
group.add(list.remove(list.size()-1));
}
add(group);
} |
daf18270-d814-41b3-b441-5323baec55c5 | 0 | public Integer getId() {
return id;
} |
a5f0f1c0-cf4e-4ac1-96f3-0c0c65eaafb7 | 6 | public String getParameterString(){
String retString = super.getParameterString();
try{
if(cQuery!=null) retString+="&cquery="+URLEncoder.encode(cQuery,"UTF-8");
if(xPath!=null) retString+="&xpath="+URLEncoder.encode(xPath,"UTF-8");
if(maxRetrieve!=null) retString+="&maxRetrieve="+maxRetrieve.toString();
if(imagePostMode!=null) retString+="&imagePostMode="+URLEncoder.encode(imagePostMode,"UTF-8");
if(baseUrl!=null) retString+="&baseUrl="+URLEncoder.encode(baseUrl,"UTF-8");
}
catch(UnsupportedEncodingException e ){
retString = "";
}
return retString;
} |
c52cbe5e-3366-4ddb-83c7-49a396c3578f | 5 | public void actionPerformed(ActionEvent e)
{
if (e.getSource() == cancel)
{
setVisible(false);
dispose();
}
else if (e.getSource() == submitClose)
{
if (submitClose.getText().equals(SUBMIT) && oneSelected())
{
enableButtons(false);
cancel.setEnabled(false);
submitClose.setText(CLOSE);
updateStats();
}
else if (submitClose.getText().equals(CLOSE))
{
setVisible(false);
dispose();
}
}
} |
87838a0a-4fb9-4e4b-895f-298bdd256bcc | 2 | public static void StopFillTask() {
if (fillTask != null && fillTask.valid())
fillTask.cancel();
} |
c99d4bd2-0563-47d4-b5bd-a4df2a54f871 | 0 | public void setPcaIdElemento(Integer pcaIdElemento) {
this.pcaIdElemento = pcaIdElemento;
} |
d3ffcbd5-13fd-4a9b-aec0-2b1fae61fdc6 | 5 | public void refresh(){
g2d[0].setColor(Color.BLACK);g2d[0].fillRect(0,0,width*20+height*20,width*15+height*15);
for (int h = 0 ;h<2;h++)
for (int j = 0 ;j<height;j++){
for (int i = 0 ;i<width;i++){
if (field[h][i][j] != null && field[h][i][j] != "") g2d[h].drawImage(Cursor.getTile(field[h][i][j]),convert.px(new Point(i,j)).x+height*20-Cursor.getTile(field[h][i][j]).getWidth()/2, convert.px(new Point(i,j)).y-Cursor.getTile(field[h][i][j]).getHeight()+30, null);
}
}
panel.setImage(img);
} |
a255ef97-3b88-4657-ba69-5b2730bf7abf | 4 | private int getDaysInMonth(int month, int year) {
int[] days_in_month = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int days = days_in_month[month];
if (month == 1 && year % 4 == 0) {
if (year % 100 == 0) {
if (year % 400 == 0) {
days += 1;
}
} else {
days += 1;
}
}
return days;
} |
ce647f0a-f112-42e2-9c46-c0a26d468d46 | 4 | public static void main(String[] args) {
int players = 5;
int pound = 10;
ScoreBoard sb = new ScoreBoard(players);
Lane lane = new Lane();
Bowl bowl = new Bowl(pound);
for (int currentFrame = 1; currentFrame < RunBowling.FRAMES-1; currentFrame++) {
for (int currentPlayer = 0; currentPlayer < players; currentPlayer++) {
lane.resetLane();
bowl.hitPins();
int fallenPins1 = lane.getNumberOfFallenPins(0);
sb.setScore(currentFrame, currentPlayer, 0, fallenPins1);
sb.printScoreBoard(currentFrame);
if ((currentFrame == RunBowling.FRAMES) || fallenPins1 < 10) {
bowl.hitPins();
int fallenPins2 = lane.getNumberOfFallenPins(1);
sb.setScore(currentFrame, currentPlayer, 1, fallenPins2
- fallenPins1);
sb.printScoreBoard(currentFrame);
}
}
}
} |
a7fe55dd-46de-4734-a25a-653770210090 | 1 | @Override
public void render (float delta) {
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
countdown.update(delta);
if(countdown.isDone()){
Objects.playScreen.finished((int)chunk.x, (int)chunk.y);
ld.setScreen(Objects.playScreen);
}
camera.update();
Objects.BATCH.setProjectionMatrix(camera.combined);
Objects.BATCH.begin();
Objects.FONT.drawMultiLine(Objects.BATCH, message, 0, Gdx.graphics.getHeight() / 2);
Objects.BATCH.end();
} |
589aba25-e377-4b55-8574-c0ac0271849b | 4 | public void inverseSelection() {
expandMenu();
for(int i = 0; i < methodTree.getRowCount(); i++) {
TreePath path = methodTree.getPathForRow(i);
if(path == null) return;
DefaultMutableTreeNode treeNode = (DefaultMutableTreeNode) path.getLastPathComponent();
if(treeNode.getUserObject() instanceof TreeNodeObject) {
TreeNodeObject co = (TreeNodeObject) treeNode.getUserObject();
if(co.isNoCategory()) {
co.setSelected(!co.isSelected());
handler.toggleDecodingMethod(co.getMethodID());
}
}
}
methodTree.repaint();
} |
a56333e5-9524-4504-8c49-cd534306146f | 3 | public static int min3(int a, int b, int c) {
if (a < b) {
return (a < c) ? a : c;
}
return (b < c) ? b : c;
} |
2b611f71-4bb6-497e-a293-cd16a9d44a54 | 9 | public List<QuestionInfo> getAnnotatedData(String corpusPath,
final String prefix, final String ext, final String chunkExt)
throws Exception {
if (corpusPath == null) {
throw new Exception("Corpus path is missing");
}
List<QuestionInfo> trainingData = new ArrayList<QuestionInfo>();
File folder = new File(corpusPath);
File[] fileList = folder.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.toLowerCase().endsWith(ext.toLowerCase())
&& name.toLowerCase().startsWith(prefix.toLowerCase());
}
});
File[] chunkList = folder.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.toLowerCase().endsWith(chunkExt.toLowerCase())
&& name.toLowerCase().startsWith(prefix.toLowerCase());
}
});
for (int i = 0; i < fileList.length; i++) {
File file = fileList[i];
File chunkFile = chunkList[i];
int questionCount = 0;
BufferedReader br = null;
ArrayList<String> lines = new ArrayList<String>();
ArrayList<String> chunkLines = new ArrayList<String>();
try {
String line;
br = new BufferedReader(new FileReader(file));
while ((line = br.readLine()) != null) {
lines.add(line);
}
br.close();
br = new BufferedReader(new FileReader(chunkFile));
while ((line = br.readLine()) != null) {
chunkLines.add(line);
}
br.close();
for (int j = 0; j < lines.size(); j++) {
questionCount++;
trainingData.add(getQuestionInfo(lines.get(j),
chunkLines.get(j)));
}
System.out.printf("Data set: %s [ %d questions]\n",
file.getName(), questionCount);
} catch (FileNotFoundException e) {
ApplicationHelper.printError(String.format("Question Classifier: Corpus not found: %s/%s*%s",
corpusPath, prefix, ext), e);
} catch (IOException e) {
ApplicationHelper.printError(String.format(
"Question Classifier: Unable to read corpus: %s/%s*%s", corpusPath, prefix,
ext), e);
}
}
return trainingData;
} |
1638f08d-3d0e-4c19-924a-958dd4c995e3 | 3 | public TestHolder(final char commandChar, final String args, final String fileName, final int lineNumber) {
super();
String commandString = new String(new char[] {commandChar});
if (commandChar == '<')
command = Command.SOURCE;
else if (commandChar == '=')
command = Command.SET;
else try {
command = Command.valueOf(commandString);
} catch (IllegalArgumentException e) {
System.err.printf("Could not handle command `%s'%n", commandString);
throw e;
}
this.args = args;
this.fileName = fileName;
this.lineNumber = lineNumber;
} |
4b8894c3-5a70-4290-b427-aec78425882d | 3 | private static Rectangle minimumCropRect(Vector<BufferedImage> spriteSet)
{
Rectangle cropRect = null;
for (BufferedImage sprite : spriteSet) {
Rectangle frameCropRect = determineCropRect(sprite);
if (cropRect == null) {
cropRect = frameCropRect;
} else {
cropRect.add(frameCropRect);
}
}
// Make crop rect one pixel larger (since we want an inclusive rect)
if (cropRect != null) {
cropRect.add(
cropRect.x + cropRect.width + 1,
cropRect.y + cropRect.height + 1);
}
return cropRect;
} |
250015ca-7b68-44f5-9cdb-799578cf05c7 | 1 | private void findAds(File video, IMediator mediator) {
System.out.println("Processing started");
int granularity = 5, numberOfContinuousSections = 8, calibrationIntervalLength = 40;
double maxElevation = 1.5;
long videoLength = VideoUtils.getVideoDurationInSeconds(video);
manager = new ScreenShotsManager(video.getName());
VolumeElevationDetectorAdapter volumeAdapter =
new VolumeElevationDetectorAdapter(
numberOfContinuousSections,
maxElevation,
granularity,
calibrationIntervalLength,
manager);
ProgressReportingAdapter
progressReporter = new ProgressReportingAdapter(mediator, videoLength);
AmplitudeGraphAdapter amplitudeGraphAdapter = new AmplitudeGraphAdapter();
AmplitudeMaxesGraphAdapter amplitudeMaxesGraphAdapter
= new AmplitudeMaxesGraphAdapter(videoLength);
try
{
// Create tool to browse the video file and register audio/video sample listeners
MediaToolApplier applier = new MediaToolApplier(video);
applier.apply(new ImageSnapAdapter(manager));
applier.apply(volumeAdapter);
applier.apply(amplitudeGraphAdapter);
applier.apply(amplitudeMaxesGraphAdapter);
applier.apply(progressReporter);
// Process the video
applier.run();
// Show amplitude graphs
System.out.println("Showing graphs...");
amplitudeGraphAdapter.show();
amplitudeMaxesGraphAdapter.show();
// Report results
System.out.println("publishing results...");
progressReporter.reportFinish();
mediator.publishResults(volumeAdapter.getLouderSections());
//TODO: debugmediator.publishResults(getProcessingResults());
System.out.println("Processing finished.");
}
catch (Exception ex)
{
mediator.reportActionFailed("Failed to process the whole video file. More info in STDOUT.");
System.out.println(ex.getMessage());
ex.printStackTrace();
}
finally
{
stopVideoProcessing();
}
} |
da86dd8e-0d38-4242-b6e8-c5fbf49a8985 | 0 | synchronized public static int nextID() {
return globalID++;
} |
8a94cc64-0dae-4bdc-93ce-44f369946af5 | 5 | @Override
public void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
g.setColor(DEF_BACKGROUND_COLOUR);
g.fillRect(0, 0, Util.IMAGE_SIZE, Util.IMAGE_SIZE); //clear the screen to remove artifacts
if(image != null) { // if there is an image to draw, draw it
for(int row = 0;row<Util.IMAGE_SIZE;row+=Util.GRID_SECTIONS) {
for(int col = 0;col<Util.IMAGE_SIZE;col+=Util.GRID_SECTIONS) {
int rowIndex = row/Util.GRID_SECTIONS;
int colIndex = col/Util.GRID_SECTIONS;
g2d.drawImage(image, col, row, col+Util.GRID_SECTIONS, row+Util.GRID_SECTIONS, //draw the background content
levelLayout[rowIndex][colIndex].x, levelLayout[rowIndex][colIndex].y,
levelLayout[rowIndex][colIndex].x+Util.GRID_SECTIONS, levelLayout[rowIndex][colIndex].y+Util.GRID_SECTIONS, null);
if(levelObjects[rowIndex][colIndex] != null) { //if there is a level Object there, draw it
g2d.drawImage(image, col, row, col+Util.GRID_SECTIONS, row+Util.GRID_SECTIONS,
levelObjects[rowIndex][colIndex].x, levelObjects[rowIndex][colIndex].y,
levelObjects[rowIndex][colIndex].x+Util.GRID_SECTIONS, levelObjects[rowIndex][colIndex].y+Util.GRID_SECTIONS, null);
}
}
}
}
if(gridVisible) {
drawGrid(g); //draw the grid
}
//Draw the selector to the screen over top of everything else
g2d.drawImage(selector, selectorLocation.x, selectorLocation.y, selectorLocation.x+Util.GRID_SECTIONS, selectorLocation.y+Util.GRID_SECTIONS,
0, 0, Util.GRID_SECTIONS, Util.GRID_SECTIONS, null);
} |
68ca2df6-6592-4dbd-8f85-3b9464cc8b0d | 8 | public ArrayList<ArrayList<String>> partition(String s) {
// Start typing your Java solution below
// DO NOT write main() function
ArrayList<ArrayList<String>> resArr = new ArrayList<ArrayList<String>>();
int n = s.length();
if (n == 0)
return resArr;
boolean[][] res = new boolean[n][n];
for (int i = 0; i < n; i++)
res[i][i] = true; // 第一层初始化
for (int i = 0; i < n - 1; i++)
res[i][i + 1] = (s.charAt(i) == s.charAt(i + 1)); // 第二层初始化
for (int k = 2; k < n; k++) {
for (int i = 0; i < n - k; i++) {
res[i][i + k] = (s.charAt(i) == s.charAt(i + k) && res[i + 1][i + k
- 1]); // 递推公式
}
}
HashMap<Integer, ArrayList<Stack<String>>> dp = new HashMap<Integer, ArrayList<Stack<String>>>();
ArrayList<Stack<String>> resSta = join(res, 0, s, dp); // 拼接结果
for (Stack<String> sta : resSta) {
ArrayList<String> arr = new ArrayList<String>();
while (!sta.isEmpty()) {
arr.add(sta.pop());
}
resArr.add(arr);
}
return resArr;
} |
d0ba4c43-1c8f-4435-9c4e-2cac0ee14421 | 0 | public String getPropertiesFilePath() {
return propertiesFilePath;
} |
c01ecc66-be30-412d-af01-9859755b453f | 4 | public static int posteY(int rangee,int orientation){
int centreY = centrePositionY(rangee) ;
switch(orientation){
case Orientation.NORD :
centreY -= 20 ;
break ;
case Orientation.EST :
centreY -= 25 ;
break ;
case Orientation.SUD :
break ;
case Orientation.OUEST :
centreY -= 25 ;
break ;
}
return centreY ;
} |
ba9ab335-54d7-4667-a87b-58bd30adf6d7 | 5 | @Override
public void doing(Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException {
// String count = request.getParameter("count");
// int max = 1;
// if (count != null && !count.equals(""))
// max = Integer.valueOf(count);
JSONArray lstJSON = new JSONArray();
logger.debug(ConfigDialog.phones + "-----------------------");
for (int i = 0; i < ConfigDialog.phones; i++) {
Long num = getNum();
logger.debug("---------------------" + num);
if (num == null || num == -1) {
print("任务完成");
if (but != null)
but.setEnabled(true);
response.getOutputStream().write("".getBytes("utf-8"));
response.getOutputStream().flush();
return;
}
JSONObject phone = new JSONObject();
String strNum = num + "";
phone.put("phone", strNum);
lstJSON.add(phone);
// 输出状态信息
print(num + "-下发成功-------已下发:" + (sendCount() + ConfigDialog.sendCount) + "/" + (sum + ConfigDialog.taskCount) + "-------成功:" + (success.size() + ConfigDialog.successCount));
}
if (lstJSON.size() == 0)
return;
JSONObject resJSON = new JSONObject();
resJSON.put("text", text);
resJSON.put("phone", lstJSON);
response.getOutputStream().write(resJSON.toJSONString().getBytes("utf-8"));
response.getOutputStream().flush();
} |
03a8d8e1-10e4-4c50-908c-9815c85a59d7 | 3 | public boolean shouldExtract(String path) {
if (this.exclude != null) {
for (String rule : this.exclude) {
if (path.startsWith(rule)) return false;
}
}
return true;
} |
62010b32-618e-4d41-b085-ada7bd5ca97f | 9 | public void start()
{
// variables: g = generation, n = population size, ff = fitness function
Generation g = this.getGeneration();
int n = g.getPopulationSize();
SpiderBotFitnessFunction ff = new SpiderBotFitnessFunction();
// main loop
do
{
// determine the generation number
int gen_count = g.getCount();
// looping through the population
for (int i = 0; i < n; i++)
{
// get the chromosome and decode it
SpiderChromosome chr = (SpiderChromosome)g.getChromosomeAtIndex(i);
MotorData[] motors = (MotorData[])chr.decode();
MotorData m1 = motors[0], m2 = motors[1], m3 = motors[2];
// scale the motor speeds to the proper NXT context
double scale = 360./256;
int spd_l = (int)(m1.getMotorSpeed() * scale);
int spd_r = (int)(m2.getMotorSpeed() * scale);
int spd_b = (int)(m3.getMotorSpeed() * scale);
// print out chromosome information to screen
System.out.println( "Generation " + gen_count);
System.out.println( "Chomosome " + (gen_count*n+i+1) );
System.out.print( chr.toEnglishString() );
String fitness = String.valueOf(ff.rate(chr));
if (fitness.length() > 7) fitness = fitness.substring( 0, 7 );
System.out.println( "fitness: " +fitness+ "\n" );
// set the motor speeds and run
left_m.setSpeed(spd_l);
back_m.setSpeed(spd_b);
right_m.setSpeed(spd_r);
if (m1.getDirection()) left_m.backward(); else left_m.forward();
if (m2.getDirection()) right_m.backward(); else right_m.forward();
if (m3.getDirection()) back_m.backward(); else back_m.forward();
//
// pick one: wait for user input or wait 3 sec to continue
//
/*
Button.waitForAnyPress();
if (Button.ENTER.isDown()) break;
if (Button.ESCAPE.isDown()) return;
if (Button.LEFT.isDown()) if (i>2) i-=2;
if (Button.RIGHT.isDown()) continue;
*/
Delay.msDelay(this.wait);
}
// evolve the population to the next generation
bestFound = super.evolve();
} while (!bestFound); // until the best chromosome is found
// get the best chromosome and display its information
Chromosome chr = this.generation.getMostFit();
String msg = "";
msg += "target found:\n" ;
msg += "Generation " + g.getCount() + "\n";
msg += chr.toEnglishString();
double rate = ff.rate(chr);
rate = Math.round(rate*10000)/10000.0;
msg += "fit: "+rate;
System.out.println(msg);
// decode its motor speeds
MotorData[] motors = (MotorData[])chr.decode();
left_m.setSpeed(motors[0].getMotorSpeed());
right_m.setSpeed(motors[1].getMotorSpeed());
back_m.setSpeed(motors[2].getMotorSpeed());
// set the motors
if (motors[0].getDirection()) left_m.backward(); else left_m.forward();
if (motors[1].getDirection()) right_m.backward(); else right_m.forward();
if (motors[2].getDirection()) back_m.backward(); else back_m.forward();
// wait one minute
Delay.msDelay(20000);
// stop the motors
left_m.stop();
back_m.stop();
right_m.stop();
} |
aeafef31-9ce3-48a6-9e68-eae6e653a95c | 8 | public String toString() {
if(this.image.trim().equals(":~")) { //weak constraint
ASTbody body=(ASTbody) this.jjtGetChild(0);
if(this.jjtGetNumChildren()>1) {
ASTconstraintParams params =(ASTconstraintParams) this.jjtGetChild(1);
return ":~"+body.toString()+". "+params.toString();
}
else {
return ":~"+body.toString()+".";
}
}
else if (jjtGetNumChildren() > 0
&& ((SimpleNode) jjtGetChild(0)).getId() == ElpsTranslatorTreeConstants.JJTPREDSYMBOL) {
/*
* image contain the name of a predicate and range of integers from
* its argument, p(1..3) results into "p 1 3" image
*/
String[] image = this.image.split(" ");
return image[0] + "(" + image[1] + ".." + image[2] + ").";
} else {
StringBuilder result = new StringBuilder();
if (((SimpleNode) this.jjtGetChild(0)).getId() == ElpsTranslatorTreeConstants.JJTHEAD) {
result.append(((SimpleNode) this.jjtGetChild(0)).toString());
}
ASTbody body = null;
if (this.jjtGetNumChildren() > 1) {
body = (ASTbody) this.jjtGetChild(1);
}
if (((SimpleNode) this.jjtGetChild(0)).getId() == ElpsTranslatorTreeConstants.JJTBODY) {
body = ((ASTbody) this.jjtGetChild(0));
}
if (body != null) {
result.append(":-");
result.append(body.toString());
}
result.append(".");
return result.toString();
}
} |
c58137fa-517b-44bf-ad8f-52020e6e3d80 | 9 | @Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Jump other = (Jump) obj;
if (captureX != other.captureX) {
return false;
}
if (captureY != other.captureY) {
return false;
}
if (x1 != other.x1) {
return false;
}
if (x2 != other.x2) {
return false;
}
if (y1 != other.y1) {
return false;
}
if (y2 != other.y2) {
return false;
}
return true;
} |
7bffc703-6af6-43ee-8fa8-9358be5dc3b2 | 0 | public PlayerListener getPlayerListener() {
return playerListener;
} |
cd7c4163-964c-4dec-8b66-7e3d8344c77c | 0 | @Override
public void setData(Object data) {
this.data = data;
} |
c3500a45-1c18-46c0-bfa3-b67e3c3b5d82 | 8 | private int getDirection(double x, double y) {
if (y < 0 && x < 0) {
return (int) (180 + Math.toDegrees(Math.atan(Math.abs(y) / Math.abs(x))));
}
if (y < 0 && x > 0) {
return (int) (360-Math.toDegrees(Math.atan(Math.abs(y) / Math.abs(x))));
}
if (y > 0 && x < 0) {
return (int) (180-Math.toDegrees(Math.atan(Math.abs(y) / Math.abs(x))));
}
if (y > 0 && x > 0) {
return (int) Math.toDegrees(Math.atan(Math.abs(y) / Math.abs(x)));
}
return (int) Math.toDegrees(Math.asin(x / y));
} |
841815a0-70bd-4674-950c-7678c068c9f4 | 5 | public CheckResultMessage check5(int day) {
int r = get(17, 5);
int c = get(18, 5);
if (checkVersion(file).equals("2003")) {
try {
in = new FileInputStream(file);
hWorkbook = new HSSFWorkbook(in);
if (0 != (getValue(r + day, c, 4).compareTo(getValue(r + day
- 1, c + 5, 4)))) {
return error("支付机构汇总报表<" + fileName + ">客户资金账户余额延续性E01:"
+ day + "日错误");
}
in.close();
} catch (Exception e) {
e.printStackTrace();
}
} else {
try {
in = new FileInputStream(file);
xWorkbook = new XSSFWorkbook(in);
if (0 != (getValue1(r + day, c, 4).compareTo(getValue1(r + day
- 1, c + 5, 4)))) {
return error("支付机构汇总报表<" + fileName + ">客户资金账户余额延续性:" + day
+ "日错误");
}
in.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return pass("支付机构汇总报表<" + fileName + ">客户资金账户余额延续性:" + day + "日正确");
} |
7a9dc2ef-3e2b-44e3-88d9-b836e9b84f44 | 8 | protected void encodeElements(mxCodec enc, Object obj, Node node)
{
if (obj.getClass().isArray())
{
Object[] tmp = (Object[]) obj;
for (int i = 0; i < tmp.length; i++)
{
encodeValue(enc, obj, null, tmp[i], node);
}
}
else if (obj instanceof Map)
{
Iterator<Map.Entry> it = ((Map) obj).entrySet().iterator();
while (it.hasNext())
{
Map.Entry e = it.next();
encodeValue(enc, obj, String.valueOf(e.getKey()), e.getValue(),
node);
}
}
else if (obj instanceof Collection)
{
Iterator<?> it = ((Collection<?>) obj).iterator();
while (it.hasNext())
{
Object value = it.next();
encodeValue(enc, obj, null, value, node);
}
}
} |
be18cb69-129f-4cf9-b90f-0f220ca3e91c | 3 | private void checkForMessages() throws IOException {
while (!messageQueue.isEmpty()) {
Message message = messageQueue.poll();
for (SocketChannel channel : acceptedConnections) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutput out = null;
out = new ObjectOutputStream(bos);
out.writeObject(message);
ByteBuffer buf = ByteBuffer.wrap(bos.toByteArray());
try {
channel.write(buf);
} catch (IOException ex) {
System.out.println(channel.getRemoteAddress() + "is disconnected");
acceptedConnections.remove(channel);
}
bos.close();
out.close();
}
}
} |
d9b29135-b9aa-4bc2-8cef-aaeb2bd1729e | 6 | public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Gui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Gui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Gui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Gui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Gui().setVisible(true);
}
});
} |
ecb76230-2085-43e1-9b9a-d2c97756ce34 | 1 | public void printLines(int indent, String line) {
if (startPos == -1) {
pw.print(line);
} else {
pw.print(line.substring(0, startPos));
printRegion(indent + startPos, line);
pw.print(line.substring(endPos));
}
} |
5070e486-c8d6-4373-8d8a-ae4b18955bd8 | 1 | private void propogateState() {
MultiType source = mergeSource;
while (source != null) {
source.interfaces = interfaces;
source.potentialClass = potentialClass;
source = source.mergeSource;
}
} |
e4025f21-6ca3-4d1e-86c2-fb10b72e642c | 8 | public void nextPermutation(int[] num) {
int i,j,k,notde,firstlar,temp;
int len=num.length;
if(len==1) return;
for(i=len-1;i>0;i--)
{
if(num[i-1]<num[i])
break;
}
notde=i-1;
if(num[0]>=num[1])
{
for(j=0;len-j-1>j;j++)
{
temp=num[j];
num[j]=num[len-j-1];
num[len-j-1]=temp;
}
return;
}
for(i=len-1;i>notde;i--)
{
if(num[i]>num[notde])
{
temp=num[notde];
num[notde]=num[i];
num[i]=temp;
break;
}
}
for(j=notde+1;len-(j-notde)>j;j++)
{
temp=num[j];
num[j]=num[len-(j-notde)];
num[len-(j-notde)]=temp;
}
} |
63052e99-f328-4988-b9f4-6d8198212170 | 2 | @Override
public Object stringToValue(String text) throws ParseException {
return new Double(Math.min(Math.max(Numbers.getLocalizedDouble(text, mMinValue <= 0 && mMaxValue >= 0 ? 0 : mMinValue), mMinValue), mMaxValue));
} |
d83a85ef-ae54-48ee-b4b2-e17870b0fbfc | 0 | public void specificRequest() {
// 具体的功能处理
System.out.println("this is in Adaptee!");
} |
a4a9b02c-1f57-4f7b-911a-9e759c7fb3b3 | 0 | protected void fillShape(DrawableItem di, Graphics2D g) {
g.setColor(di.getFill());
g.fill(di.getShape());
} |
75b0e9f7-530c-4d1c-96db-c0a52983bd7d | 0 | public boolean isAdd() {
return myAdd;
} |
c0e94be8-7275-4ef4-a4ab-a8d18fe92f78 | 4 | private static void clearArea(CellState[][] states, int x, int y, Location gLoc){
Grid<Actor> gr = GridWorldLife.instance.world.getGrid();
for(int r = 0; r < states.length; r++){
for(int c = 0; c < states[0].length; c++){
int row = gLoc.getRow() + (r - y);
int col = gLoc.getCol() + (c - x);
Location tmp = new Location(row, col);
if(!gr.isValid(tmp)) continue;
Actor a = gr.get(tmp);
if(a instanceof Cell){
((Cell) a).setState(CellState.OFF);
}
}
}
} |
d2ed35fd-8590-49b5-adaa-0fc0c5034f92 | 8 | public synchronized void updateDisplay()
{
// check that x and y are at least 0
if (xPos < 0)
xPos = 0;
if (yPos < 0)
yPos = 0;
// if picture
if (picture != null)
{
if (xPos >= picture.getWidth())
xPos = picture.getWidth() - 1;
if (yPos >= picture.getHeight())
yPos = picture.getHeight() - 1;
Graphics g = picture.getGraphics();
paintComponent(g);
}
else if (modelDisplay != null)
{
if (xPos >= modelDisplay.getWidth())
xPos = modelDisplay.getWidth() - 1;
if (yPos >= modelDisplay.getHeight())
yPos = modelDisplay.getHeight() - 1;
modelDisplay.modelChanged();
}
} |
2f75dc08-4d26-4369-9402-ac2153e07d39 | 5 | public void run() {
while (true) {
TACMessage msg = getMessage();
boolean sent;
for (int errors = 0; !(sent = sendMsg(msg)) && errors < 3; errors++) {
log.warning("failed to send message " + msg.getType()
+ " (retry " + (errors + 1) + ')');
try {
Thread.sleep(1000);
} catch (Exception e) {
e.printStackTrace();
}
}
if (!sent) {
agent.fatalError("could not send message " + msg.getType()
+ " to server");
}
}
} |
240126bd-4401-412f-a63e-236082354246 | 6 | public static void main(String[] args) {
List<Rider> riders = new ArrayList<Rider>();
// Rider rider = new Rider(name, raceCode) ??? what is race code
riders.add(new Rider("Human", Rider.HUMAN_CODE));
riders.add(new Rider("Hobbit", Rider.HOBBIT_CODE));
riders.add(new Rider("bug", -1)); // I am a bug rider
riders.add(new Rider("Giant", Rider.GIANT_CODE));// I am a giant rider
riders.add(new Rider("Giant", Rider.GIANT)); // I am a giant rider
Map<Raceable, Integer> raceables = new HashMap<Raceable, Integer>();
for (Rider rider : riders) {
raceables.put(AnimalFactory.optAnimal(rider), 0);
}
int round = 10;
int firstDistance = 0;
for (int i = 0; i < round; i++) {
for (Raceable raceable : raceables.keySet()) {
int runDistance = 0;
runDistance = raceable.run();
if (raceables.get(raceable) + runDistance > firstDistance) {
firstDistance = raceables.get(raceable) + runDistance;
}
raceables.put(raceable, raceables.get(raceable) + runDistance);
}
}
Raceable winner = null;
int maxDistance = 0;
for (Raceable raceable : raceables.keySet()) {
if (raceables.get(raceable) > maxDistance) {
maxDistance = raceables.get(raceable);
winner = raceable;
}
}
winner.onWin();
System.out.println(String.format("winner runs %d miles ", raceables.get(winner)));
} |
e657b652-1f8e-468e-97e5-cd5fcb37dee1 | 5 | public void translateAll() {
for (DrawableItem pa : l.getDrawable()) {
if (pa instanceof Panel && !((Panel) pa).deleted) {
Point p = getPanelAnchor((Panel) pa);
double hfactor = -(p.x - (((double) variables.THUMBNAIL_WIDTH * p.x) / (double) variables.CANVAS_WIDTH));
double wfactor = -(p.y - (((double) variables.THUMBNAIL_HEIGHT * p.y) / (double) variables.CANVAS_HEIGHT));
Rectangle newRect = (Rectangle) ((Rectangle) ((Panel) pa).getShape()).clone();
newRect.translate((int) hfactor, ((int) wfactor));
panels.add(newRect);
} else if (l.isBlueLayer) {
if (((PathItem) pa).getPanel() != null) {
Point p = getPanelAnchor(((PathItem) pa).getPanel());
double hfactor = -(p.x - (((double) variables.THUMBNAIL_WIDTH * p.x) / (double) variables.CANVAS_WIDTH));
double wfactor = -(p.y - (((double) variables.THUMBNAIL_HEIGHT * p.y) / (double) variables.CANVAS_HEIGHT));
AffineTransform at = new AffineTransform();
at.translate((int) Math.ceil(hfactor), (int) Math.ceil(wfactor));
}
}
}
} |
5692793f-f67d-442f-aedb-e44695041bfc | 3 | private double calculateRisk(Vector pos) {
double risk = 100.0 / pos.distanceSq(getTargetPosition());
for(double[] edge : State.wavelessField.getEdges()) {
risk += 5.0 / (1.0 + Line2D.ptSegDistSq(edge[0], edge[1], edge[2], edge[3], pos.x, pos.y));
}
/*
* Get points between enemy location and corner and add risk! these
* are really bad places to be! Our hitbox is larger here if nothing else!
*/
for(double[] corner : State.wavelessField.getCorners()) {
Vector targetPos = getTargetPosition();
corner[0] = (corner[0] + targetPos.x) / 2.0;
corner[1] = (corner[1] + targetPos.y) / 2.0;
if(targetPos.distanceSq(corner[0], corner[1]) < 22500) {
risk += 5.0 / (1.0 + pos.distanceSq(corner[0], corner[1]));
}
}
return risk;
} |
b1287fdd-45d8-4459-8e51-22408075e79a | 5 | private static final void speedCheck(final List<LifeMovementFragment> res, final MapleClient c) {
double speedMod, playerSpeedMod = c.getPlayer().getStat().getSpeedMod() + 0.005;
for (LifeMovementFragment lmf : res) {
if (lmf.getClass() == AbsoluteLifeMovement.class) {
final AbsoluteLifeMovement alm = (AbsoluteLifeMovement) lmf;
speedMod = Math.abs(alm.getPixelsPerSecond().x) / 125.0;
if (speedMod > playerSpeedMod) {
if (alm.getUnk() != 0) {
if (speedMod > playerSpeedMod) {
c.getPlayer().getCheatTracker().registerOffense(CheatingOffense.FAST_MOVE);
break;
}
}
}
}
}
} |
a3e2f01b-b822-41a5-b006-a3b82e4fcec4 | 3 | @Override
public Object execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
Contexto oContexto = (Contexto) request.getAttribute("contexto");
oContexto.setVista("jsp/entrada/list.jsp");
try {
EntradaDao oEntradaDao = new EntradaDao(oContexto.getEnumTipoConexion());
Integer intPages = oEntradaDao.getPages(oContexto.getNrpp(), oContexto.getAlFilter(), oContexto.getHmOrder());
Integer intRegisters = oEntradaDao.getCount(oContexto.getAlFilter());
if (oContexto.getPage() >= intPages) {
oContexto.setPage(intPages);
}
if (oContexto.getPage() < 1) {
oContexto.setPage(1);
}
ArrayList<EntradaBean> listado = oEntradaDao.getPage(oContexto.getNrpp(), oContexto.getPage(), oContexto.getAlFilter(), oContexto.getHmOrder());
String strUrl = "<a href=\"Controller?" + oContexto.getSerializedParamsExceptPage() + "&page=";
ArrayList<String> botonera = Pagination.getButtonPad(strUrl, oContexto.getPage(), intPages, 2);
ArrayList<Object> a = new ArrayList<>();
a.add(listado);
a.add(botonera);
a.add(intRegisters);
return a;
} catch (Exception e) {
throw new ServletException("EntradaList1: Error: " + e.getMessage());
}
} |
50fff62e-0558-4ee5-bb39-5ed631713b20 | 2 | public void touch(Entity e, Level level)
{
if (e instanceof CoinEntity)
{
CoinEntity ce = ((CoinEntity) e);
if (!ce.collected)
{
score++;
Sound.coin.play();
ce.collected = true;
}
}
} |
0a82dc40-f9fd-4130-abc7-790b6453ba9e | 5 | public static ArrayList<Interval> insert(ArrayList<Interval> intervals,
Interval newInterval) {
ArrayList<Interval> result = new ArrayList<Interval>();
// loop intervals
for (Interval interval : intervals) {
if (interval.end < newInterval.start) {
result.add(interval);
} else if (interval.start > newInterval.end) {
result.add(newInterval);
newInterval = interval;
} else if (interval.end >= newInterval.start
|| interval.start <= newInterval.end) {
newInterval = new Interval(Math.min(interval.start,
newInterval.start), Math.max(newInterval.end,
interval.end));
}
}
result.add(newInterval);
return result;
} |
699e4a90-6829-467a-9f91-79d773c49e50 | 0 | public static ModelClassDesc getClassDesc(TableDesc tableDesc,
String packageName) {
return MySQLUtils.tableParseToMode(tableDesc);
} |
14c2be87-00e4-49e9-9405-78c2e41655b0 | 4 | public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
ArrayList<Character> list = new ArrayList<>();
ArrayList<Character> combinedList = new ArrayList<>();
// read chars from first list;
// with "replaceAll" method remove all whitespace
for (char c : scanner.nextLine().replaceAll("\\s+", "").toCharArray()) {
list.add(c);
}
combinedList.addAll(list);
// add chars from second list to combined one,
// but only those chars, which do not exist in first list
for (char c : scanner.nextLine().replaceAll("\\s+", "").toCharArray()) {
if (!list.contains(c)) {
combinedList.add(c);
}
// there's no need to save these chars
}
for (char c : combinedList) {
System.out.print(c + " ");
}
} |
8d739b74-cf86-4973-aaf2-442915d2e54f | 9 | @Override
protected boolean xsend (Msg msg_, int flags_)
{
// If this is the first part of the message it's the ID of the
// peer to send the message to.
if (!more_out) {
assert (current_out == null);
// If we have malformed message (prefix with no subsequent message)
// then just silently ignore it.
// TODO: The connections should be killed instead.
if (msg_.has_more()) {
more_out = true;
// Find the pipe associated with the identity stored in the prefix.
// If there's no such pipe just silently ignore the message, unless
// mandatory is set.
Blob identity = new Blob(msg_.data());
Outpipe op = outpipes.get(identity);
if (op != null) {
current_out = op.pipe;
if (!current_out.check_write ()) {
op.active = false;
current_out = null;
if (mandatory) {
more_out = false;
ZError.errno(ZError.EAGAIN);
return false;
}
}
} else if (mandatory) {
more_out = false;
ZError.errno(ZError.EHOSTUNREACH);
return false;
}
}
return true;
}
// Check whether this is the last part of the message.
more_out = msg_.has_more();
// Push the message into the pipe. If there's no out pipe, just drop it.
if (current_out != null) {
boolean ok = current_out.write (msg_);
if (!ok)
current_out = null;
else if (!more_out) {
current_out.flush ();
current_out = null;
}
}
// Detach the message from the data buffer.
return true;
} |
7d0d9b97-29a4-4ff8-b8f2-f3f710f8970c | 9 | private void secondRun() {
// compute the cumulative distribution function
double cdf[] = new double[maxIter + 1];
double t = 0;
int min = maxIter, max = 0;
for (int j = 0; j <= maxIter && active(); ++j) {
t += Math.pow((double)histogram[j].get()/total, 1/4.);
cdf[j] = t;
}
for (int i = 0; i < total; ++i) {
int x = (int)Math.floor(iterations[i]);
if (x < min) min = x;
if (x > max) max = x;
}
int idx;
while ((idx = secondIndex.getAndIncrement()) < total && active()) {
final double iter = iterations[idx];
final int d = (int)Math.floor(iter);
// the relative gradient key point
double r = cdf[d] - (cdf[d] - (d > 0 ? cdf[d-1] : 0)) * (1 - iter % 1);
r = (r - cdf[min]) / (cdf[max] - cdf[min]);
r = Math.min(Math.max(r, 0), 1);
// compute the interpolated color
double colorIter = r * maxIter;
int color = Algorithm.interpolateColor(
palette[(int)Math.floor(colorIter)],
palette[(int)Math.ceil(colorIter)],
colorIter % 1);
// write color
final int xy = indexes[idx];
image.setRGB(xy % width, xy / width,
iter >= maxIter ? 0xff000000 : color);
processed.incrementAndGet();
}
} |
479c4ca8-240e-415c-b05e-e528684e635f | 3 | public FiltersMenu() {
super("Filter");
setEnabled(true);
JMenuItem gaussianFilter = new JMenuItem("Gaussian");
gaussianFilter.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
Panel panel = (((Window) getTopLevelAncestor()).getPanel());
if (panel.getImage() == null) {
return;
}
JDialog dialog = new GaussianFilterDialog(panel);
dialog.setVisible(true);
}
});
JMenuItem meanFilter = new JMenuItem("Mean");
meanFilter.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
Panel panel = (((Window) getTopLevelAncestor()).getPanel());
if (panel.getImage() == null) {
return;
}
JDialog dialog = new MeanFilterDialog(panel);
dialog.setVisible(true);
}
});
JMenuItem medianFilter = new JMenuItem("Median");
medianFilter.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
Panel panel = (((Window) getTopLevelAncestor()).getPanel());
if (panel.getImage() == null) {
return;
}
JDialog dialog = new MedianFilterDialog(panel);
dialog.setVisible(true);
}
});
add(meanFilter);
add(medianFilter);
add(gaussianFilter);
} |
e8017f7e-8f0f-4c5c-a1cf-dd55aa26f4c6 | 3 | public List<ApiKey> apiKeys() throws EasyPostException {
ApiKeys parentKeys = ApiKeys.all();
if (this.getId() == parentKeys.getId()) {
return parentKeys.getKeys();
}
for(int i=0; i < parentKeys.children.size(); i++) {
if(this.getId().equals(parentKeys.children.get(i).getId())) {
return parentKeys.children.get(i).getKeys();
}
}
throw new EasyPostException("Unable to find api key. Please contact [email protected]");
} |
4e20253e-1e52-4b28-8943-4aa5deb5aa38 | 3 | @Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Npc other = (Npc) obj;
if (!Objects.equals(this.name, other.name)) {
return false;
}
return true;
} |
b48004a6-c143-4a97-87a8-720fa742eaa5 | 1 | @Override
public String value(int index) {
return index < value.length? value[index]:null;
} |
e05e2d1c-cbed-44ac-b3af-12fc6ad9a6c5 | 0 | private void initComponents() {
setLayout(new GroupLayout());
add(getJLabel0(), new Constraints(new Leading(26, 10, 10), new Leading(55, 12, 12)));
add(getJLabel2(), new Constraints(new Leading(115, 10, 10), new Leading(17, 12, 12)));
add(getJButton0(), new Constraints(new Leading(66, 81, 10, 10), new Leading(232, 10, 10)));
add(getJButton1(), new Constraints(new Leading(188, 75, 10, 10), new Leading(232, 12, 12)));
add(getJLabel3(), new Constraints(new Leading(26, 63, 10, 10), new Leading(189, 12, 12)));
add(getJLabel1(), new Constraints(new Leading(26, 12, 12), new Leading(102, 10, 10)));
add(getJComboBox0(), new Constraints(new Leading(105, 10, 10), new Leading(100, 10, 10)));
add(getJLabel4(), new Constraints(new Leading(26, 99, 12, 12), new Leading(143, 12, 12)));
add(getJComboBox1(), new Constraints(new Leading(131, 10, 10), new Leading(139, 12, 12)));
add(getJTextField0(), new Constraints(new Leading(52, 261, 10, 10), new Leading(53, 24, 10, 10)));
add(getJTextField1(), new Constraints(new Leading(103, 179, 12, 12), new Leading(187, 25, 10, 10)));
setSize(343, 274);
} |
897db2a0-fb41-4e2d-8264-3ddaac3b967b | 2 | public double[] rawPersonRanges(){
if(!this.dataPreprocessed)this.preprocessData();
if(!this.variancesCalculated)this.meansAndVariances();
return this.rawPersonRanges;
} |
18882c67-3b72-4e2b-a4a1-7e96e93a81e5 | 0 | public ConfigurationWriter() {} |
b44dbc11-3bc1-42e9-b926-e5c9d6123960 | 8 | public void compute()
{
String tr = inpGtria.getText() ;
String[] trias = new String[4] ;
/* Read the trias configuration from inpGtria into trias[0..2], skipping lines
* that start with a hash mark.
*/
Scanner s = new Scanner(tr) ;
for(int l=0 ; l < 3 ; )
{
try
{
trias[l] = s.nextLine().trim() ;
if ( ! trias[l].startsWith("#") )
l++ ;
}
catch(Exception e)
{
outG.setText("ERROR: less than 3 lines in the triad definition") ;
return ;
}
}
/* Read the J values from inpGjval into trias[3] in a loop
*/
String j = inpGjval.getText() ;
s = new Scanner(j) ;
while ( true)
{
try
{
trias[3] = s.nextLine().trim() ;
}
catch(Exception e)
{
return ;
}
if ( ! trias[3].startsWith("#") )
{
try {
BigSurdVec w = Wigner3j.wigner3j(trias[0],trias[1],trias[2],trias[3]) ;
outG.append(w.toString()+ " = " + w.doubleValue()) ;
}
catch (Exception e)
{
outG.append(e.toString()) ;
e.printStackTrace() ;
}
outG.append(" # J = ") ;
Scanner num = new Scanner(trias[3]) ;
while( num.hasNextInt() )
{
int twoj1 = num.nextInt() ;
Rational jfrac = new Rational(twoj1-1,2) ;
outG.append(jfrac.toString() + " ") ;
}
outG.append("\n") ;
}
}
} /* compute */ |
da0a1a32-272c-4f70-9e89-4e0f7198a64d | 4 | public byte[] genKey(int index, int permuted_index) {
int i, bit;
byte[] key = null;
assert (index < (1 << n_inputs)) : "gen_key: index >= 2^n_inputs (too big)";
MyUtil.md.reset();
MyUtil.md.update(MyUtil.toByteArray(gate_index));
MyUtil.md.update(MyUtil.toByteArray(permuted_index));
if (n_inputs == 0) {
key = MyUtil.md.digest();
} else {
for (i = 0 ; i < n_inputs ; i++) {
if (index >= 0) {
bit = (index >> i) & 1;
MyUtil.md.update(in_gates[i].getCode(bit));
} else
MyUtil.md.update(in_gates[i].garbled_value);
if (i == 0) key = MyUtil.md.digest();
else key = MyUtil.xorArrays (key, MyUtil.md.digest());
}
}
return key;
} |
6cdd01e6-b26a-4113-948b-da1cdd8e3235 | 5 | public boolean liveRangesIntersect(final VarExpr a, final VarExpr b) {
Assert.isTrue((a != null) && (b != null),
"Cannot get intersections for null def");
Assert.isTrue(a.isDef() && b.isDef(),
"Cannot get intersections for variable uses");
if (a == b) {
return false;
}
// If all locals should have unique colors, return true.
if (Liveness.UNIQUE) {
return true;
}
final IGNode na = (IGNode) ig.getNode(a);
final IGNode nb = (IGNode) ig.getNode(b);
Assert.isTrue((na != null) && (nb != null));
return ig.hasEdge(na, nb);
} |
903471c4-b265-443e-9726-b51ccda64b75 | 8 | static ImageIcon getKarelImage(int direction) {
switch (direction) {
case NORTH: {
if (nkarel == null)
nkarel = new ImageIcon(Display.class.getResource(nkarelLocation));
return nkarel;
}
case EAST: {
if (ekarel == null)
ekarel = new ImageIcon(Display.class.getResource(ekarelLocation));
return ekarel;
}
case SOUTH: {
if (skarel == null)
skarel = new ImageIcon(Display.class.getResource(skarelLocation));
return skarel;
}
case WEST: {
if (wkarel == null)
wkarel = new ImageIcon(Display.class.getResource(wkarelLocation));
return wkarel;
}
default:
Debug.printError("Karel image for direction " + direction + " not found! Aborting...");
System.exit(7);
return null;
}
} |
7b112a95-cc1f-4953-b7f4-aac24c1998e1 | 3 | private boolean intersectVertical(KDPoint q, double distActual, boolean left) {
return q.getY() >= yi && q.getY() <= yf && Math.abs(q.getX() - (left ? xi : xf)) <= distActual;
} |
a5eb0135-f4f9-4351-97a0-03f95e3c9103 | 9 | void expand(ArrayList<Integer> C,ArrayList<Integer> P){
if (timeLimit > 0 && System.currentTimeMillis() - cpuTime >= timeLimit) return;
nodes++;
for (int i=P.size()-1;i>=0;i--){
if (C.size() + P.size() <= maxSize) return;
int v = P.get(i);
C.add(v);
ArrayList<Integer> newP = new ArrayList<Integer>();
for (int w : P) if (A[v][w] == 1) newP.add(w);
if (newP.isEmpty() && C.size() > maxSize) saveSolution(C);
if (!newP.isEmpty()) expand(C,newP);
C.remove((Integer)v);
P.remove((Integer)v);
}
} |
53c0d650-c4ed-4142-8e4a-c239ec275458 | 9 | protected void writeJSON()throws JsonParseException, IOException
{
JsonFactory jsonF = new JsonFactory();
JsonParser jp = null;
JsonGenerator jg = null;
try
{
jp = jsonF.createJsonParser(is);
jg = jsonF.createJsonGenerator(os);
jg.useDefaultPrettyPrinter(); // enable indentation just to make debug/testing easier
if (jp.nextToken() != JsonToken.START_OBJECT) {
throw new IOException("Expected data to start with an Object");
}
while ((jp.nextToken() != null))
{
String fieldName = jp.getCurrentName();
// Let's move to value
jp.nextToken();//value or start_object or start_array
if ("rows".equals(fieldName)) {
jg.writeStartObject();
jp.nextToken();//start object, start array was taken care by prev nextToken() call
String currentEntityId = null;
while(jp.nextToken() != JsonToken.END_OBJECT) //reads the key
{
String keyName = jp.getCurrentName();
jp.nextToken();//value or start_object or start_array
if("key".equals(keyName))
{
String entityId = jp.getText();
if(currentEntityId != null && !currentEntityId.equals(entityId))
{
currentEntityId = entityId;
jg.writeEndArray();//Close array for prev entity
jg.writeFieldName(entityId);
jg.writeStartArray();//start array for this entity
}
else if(currentEntityId == null)
{
currentEntityId = entityId;
jg.writeFieldName(entityId);
jg.writeStartArray();
}
}
else if("value".equals(keyName))
{
Map<String, Object> row = new LinkedHashMap<String, Object>();
readJsonObject(jp, row);
JSONObject json = JSONObject.fromObject(row);
jg.writeRaw(json.toString()+ "\r\n");
jp.nextToken(); //move it off the END_OBJECT
jp.nextToken(); //move it off the END_OBJECT
}
}
//Close array for the last entityId
jg.writeEndArray();
jg.writeEndObject();
}
}
}
finally
{
jp.close();
jg.close();
}
} |
fdeea88b-aee0-4607-9370-a9867f66fb9c | 3 | public static IList<Integer> divide(IList<Integer> ls) {
if (ls.length() <= 1) {
return ls;
}
IList<Integer> ll = new MLinkedList<>();
IList<Integer> lr = new MLinkedList<>();
int len = ls.length();
int pivotindex = len / 2;
INode<Integer> currNode = ls.getFirst();
while (currNode != null) {
if (ll.length() < pivotindex) {
ll.append(currNode.getElem());
} else {
lr.append(currNode.getElem());
}
currNode = currNode.getNext();
}
return merge(divide(ll), divide(lr));
} |
cc0dcf22-83cc-4693-8935-ff81c5bca8ef | 3 | public static String eliminarCerosString(String s){
String temp = s.trim();
if (esNumero(temp) && !temp.isEmpty()){
Integer i = Integer.parseInt(temp);
if (i != 0)
temp = i.toString();
else
temp = "";
}
return temp;
} |
554f5328-98e6-4338-bda6-e08fe170bc4b | 1 | public static void insertCommandeFournisseur( int idutilisateur, String referencefournisseur, Date datecommandefournisseur, Float remisefournisseur) throws SQLException {
String query = "";
try {
query = "INSERT INTO COMMANDE_FOURNISSEUR (ID_UTILISATEUR,COMFOUREF,COMFOUDATE,COMFOUREMISE) VALUES (?,?,?,?); ";
PreparedStatement pStatement = ConnectionBDD.getInstance().getPreparedStatement(query);
pStatement.setInt(1, idutilisateur);
pStatement.setString(2, referencefournisseur);
pStatement.setObject(3, datecommandefournisseur);
pStatement.setFloat(4, remisefournisseur);
pStatement.executeUpdate();
} catch (SQLException ex) {
Logger.getLogger(RequetesCommandeFournisseur.class.getName()).log(Level.SEVERE, null, ex);
}
} |
e72db868-332a-4eeb-99f9-f8eef5c3b86d | 5 | public String getMaxGain( TextProcessing TextPro ) {
double Entropy_S = getInformationEntroy(TextPro.objResult.Result_Count);
HashMap<String, Double> GainMap = new HashMap<String, Double>();
for ( int i = 0; i < TextPro.objAttributeList.size(); i ++ ) {
Attribute objAttr = TextPro.objAttributeList.get(i);
ArrayList<Integer> CalcuParamInt = new ArrayList<Integer>();
ArrayList<Double> CalcuParamDou = new ArrayList<Double>();
for ( String SituName:objAttr.Situation_Count.keySet() ) {
CalcuParamInt.add(objAttr.Situation_Count.get(SituName));
CalcuParamDou.add(getInformationEntroy(objAttr.SituationMap.get(SituName).Result_Count));
}
double Gain = getInformationGain(Entropy_S, CalcuParamInt, CalcuParamDou);
double Split = getInformationSplit(CalcuParamInt);
double GainRatio = getInformationGainRatio(Gain, Split);
GainMap.put(objAttr.AttributeName, GainRatio);
}
Double MaxGain = null;
String MaxGainName = null;
for ( String SingleGainName:GainMap.keySet()) {
if ( MaxGain == null ) {
MaxGain = GainMap.get(SingleGainName);
MaxGainName = SingleGainName;
}
else {
if ( MaxGain < GainMap.get(SingleGainName) ) {
MaxGain = GainMap.get(SingleGainName);
MaxGainName = SingleGainName;
}
}
}
return MaxGainName;
} |
c3523270-eff9-4256-9caa-3db206556afe | 6 | private void expand() {
if (nextRecord == null)
return;
//System.out.println("Pushing record starting at : " + nextRecord.getAlignmentStart());
records.push(new MappedRead(nextRecord));
//Find next suitable record
try {
nextRecord = recordIt.next();
}
catch(NoSuchElementException ex) {
nextRecord = null;
}
//Automagically skip unmapped reads and reads with unmapped mates
while(nextRecord != null && (nextRecord.getMappingQuality()==0 || nextRecord.getMateUnmappedFlag())) {
try {
nextRecord = recordIt.next();
}
catch (NoSuchElementException ex) {
nextRecord = null;
}
}
} |
8fb2c504-1551-4d2d-832a-e023eb800925 | 6 | public void click() {
Rectangle upArrow = new Rectangle(PotatoHead.CORNER_X + 400, PotatoHead.CORNER_Y + 0, 80, 40);
Rectangle downArrow = new Rectangle(PotatoHead.CORNER_X + 400, PotatoHead.CORNER_Y + 560, 80, 40);
if (upArrow.contains(Mouse.mse)) {
scrollUp();
} else if (downArrow.contains(Mouse.mse)) {
scrollDown();
} else {
for (Accessory a : accessories) {
if (a.contains(Mouse.mse)) {
// put an accessory down
if (Mouse.held != null && Mouse.held.getID() == a.getID()) {
Mouse.held = null;
// take an accessory
} else {
Mouse.held = new Accessory(a);
}
}
}
}
} |
5ad61de0-ec9c-4068-be42-7e87b3dd2789 | 6 | private void closeResourceSilently(ResultSet res, PreparedStatement pstt,
Connection conn) {
if (res != null)
try {
res.close();
} catch (SQLException ignore) {
}
if (pstt != null)
try {
pstt.close();
} catch (SQLException ignore) {
}
if (conn != null)
try {
conn.close();
} catch (SQLException ignore) {
}
} |
354bc917-ed1f-41bf-9aa5-31c8e2aeb972 | 6 | private void initReference(){
File f = new File(PATH_RESSOURCE+REFERENCE_MORSE);
FileReader fr;
try {
fr = new FileReader(f);
BufferedReader b = new BufferedReader(fr);
int i = 0, j = 0;
int tmp = b.read();
while(tmp != -1){
if(tmp != 44 && tmp != 10){ //44 = ' ' et 10 = '\n'
reference[i][j] = tmp-48; //Dans la table ascii, 0 vaut 48, 1 vaut 49...
j++;
if(j>3){
j=0;
i++;
}
}
tmp = b.read();
}
}
catch (FileNotFoundException e) {
System.out.println("Le fichier de configuration referenceMorse ne peut pas etre ouvert.");
}
catch (IOException e){
System.out.println("La lecture dans le fichier referenceMorse a rencontrer un probleme.");
}
} |
f5e0229b-9f50-4b90-b213-854ad8e633d1 | 4 | public void setPixel(int color, int x, int y) {
if (x < 0 || x >= width || y < 0 || y >= height)
return;
pixels[x + y * width] = color;
} |
011878fa-8809-4c18-a944-1c9d34232da1 | 2 | @Override
public void characters(char[] ch, int start, int length)
throws SAXException {
String value = new String(ch, start, length).trim();
if (lastFieldName != null) {
logger.info(String.format(Messages.getString("parsing_field"), //$NON-NLS-1$
lastFieldName, value));
if (currentParser.parseField(lastFieldName, value)) {
lastFieldName = null;
} else {
throw new SAXException(String.format(
Messages.getString("unable_to_parse_field"), lastFieldName)); //$NON-NLS-1$
}
}
} |
77c723a4-9f4c-4495-a239-6b03926d0145 | 0 | public static void main(String[] args) throws Exception {
Thread t = new Thread(new Blocked2());
t.start();
TimeUnit.SECONDS.sleep(1);
System.out.println("Issuing t.interrupt()");
t.interrupt();
} |
e649a2ee-bed5-4e20-939d-ca2e00721b11 | 6 | public static void pascalTriangle(int n) {
int[][] pascal = new int[n+1][n+1];
for( int i = 0; i< n+1; i++) {
for( int j = 0; j< i; j++) {
if(i-1 >= 0 && j-1 >= 0) {
pascal[i][j] = pascal[i-1][j] + pascal[i-1][j-1];
} else {
pascal[i][j] = 1;
}
}
}
for( int i = 0; i< n+1; i++) {
for (int j = 0; j < i; j++) {
System.out.print(" "+ pascal[i][j]+" ");
}
System.out.println();
}
} |
0a71fb39-a7b4-4202-b468-543dc94644b5 | 2 | public static final long extractTime(String text) {
if (text != null) {
Matcher matcher = TIME_PATTERN.matcher(text);
if (matcher.find()) {
long time = TimeUnit.MILLISECONDS.convert(Numbers.extractInteger(matcher.group(1), 0, false), TimeUnit.HOURS);
time += TimeUnit.MILLISECONDS.convert(Numbers.extractInteger(matcher.group(2), 0, false), TimeUnit.MINUTES);
time += TimeUnit.MILLISECONDS.convert(Numbers.extractInteger(matcher.group(3), 0, false), TimeUnit.SECONDS);
return time;
}
}
return 0;
} |
43098dec-2a16-4bd9-8fac-f2080a4ef46d | 9 | public void scrollCellToView(JTable table, int rowIndex, int vColIndex) {
if (!(table.getParent() instanceof JViewport)) {
return;
}
JViewport viewport = (JViewport) table.getParent();
Rectangle rect = table.getCellRect(rowIndex, vColIndex, true);
Rectangle viewRect = viewport.getViewRect();
int x = viewRect.x;
int y = viewRect.y;
if (rect.x >= viewRect.x && rect.x <= (viewRect.x + viewRect.width - rect.width)){
} else if (rect.x < viewRect.x){
x = rect.x;
} else if (rect.x > (viewRect.x + viewRect.width - rect.width)) {
x = rect.x - viewRect.width + rect.width;
}
if (rect.y >= viewRect.y && rect.y <= (viewRect.y + viewRect.height - rect.height)){
} else if (rect.y < viewRect.y){
y = rect.y;
} else if (rect.y > (viewRect.y + viewRect.height - rect.height)){
y = rect.y - viewRect.height + rect.height;
}
viewport.setViewPosition(new Point(x,y));
} |
030750ee-39c6-45b0-ab10-ab1055e3f738 | 9 | @Override
public void run() {
Gson convert = new Gson();
try {
// ----------------
// Login Protocol
// ----------------
ChatSocket = new DatagramSocket(Storage.getPort(),InetAddress.getByName("0.0.0.0"));
ChatSocket.setBroadcast(true);
// Get JSON Interpretation
String HELLO = convert.toJson(new Message(MessageProtocol.LOGIN));
// Get Packet as Byte array
byte[] HelloData = HELLO.getBytes();
// Try 255.255.255.255
try {
// Send Hello Packet
DatagramPacket HELLOPacket = new DatagramPacket(HelloData,
HelloData.length,
InetAddress.getByName("255.255.255.255"),
Storage.getPort());
ChatSocket.send(HELLOPacket);
} catch (Exception e) {/* Silently let the error die */
}
// Try all other Interfaces
Enumeration<NetworkInterface> interfaces = NetworkInterface
.getNetworkInterfaces();
while (interfaces.hasMoreElements()) {
NetworkInterface netInterface = interfaces.nextElement();
if (netInterface.isLoopback() || !netInterface.isUp()) {
continue;
}
// Send to all Addresses
for (InterfaceAddress interAddress : netInterface
.getInterfaceAddresses()) {
InetAddress broadcastAddress = interAddress.getBroadcast();
if (broadcastAddress == null) {
continue;
}
// Send Hello to Broadcast OTN
try {
// Send Hello Packet
DatagramPacket HELLOPacket = new DatagramPacket(
HelloData, HelloData.length, broadcastAddress,
Storage.getPort());
ChatSocket.send(HELLOPacket);
} catch (Exception e) {/* Silently let the error die */
}
}
}
//--------------------
// Start Server
//--------------------
ChattrLoad.loaded = true;
Thread Client = new Thread(new UDPClient(ChatSocket));
Client.start();
while(true){
//Receive Packet
byte[] recieveBuffer = new byte[65536];
DatagramPacket receivePacket = new DatagramPacket(recieveBuffer,recieveBuffer.length);
ChatSocket.receive(receivePacket);
Postbox.Process(receivePacket.getData(),receivePacket.getAddress().getHostAddress());
}
} catch (Exception e) {
e.printStackTrace();
}
} |
390b5101-0da3-48e3-8bd0-c93543c0674c | 3 | public void run() {
running = true;
final int CASH_PORT = 4713;
try {
ServerSocket cashServerSocket = new ServerSocket(CASH_PORT);
ServerDataBaseManager sDBM = new ServerDataBaseManager();
while (true) {
if (running) {
new CashServerExecutionThread(cashServerSocket.accept(), sDBM).start();
}
}
} catch (Exception e) {
e.printStackTrace();
}
} |
229e923e-bf66-4e78-8c3d-0442d11b9c45 | 6 | public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(FPrincipalFinal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(FPrincipalFinal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(FPrincipalFinal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(FPrincipalFinal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new FPrincipalFinal().setVisible(true);
}
});
} |
15c8a0eb-a11f-46b0-837e-f406760716d7 | 5 | public boolean matches(@NotNull String labelStr) {
for (Label exclude : excludes) {
if(exclude.getName().equals(labelStr)) {
return false;
}
}
if(includes.isEmpty()) {
return true; //We either have nothing or only excludes
}
for (Label include : includes) {
if(include.getName().equals(labelStr)) {
return true;
}
}
return false;
} |
190f474a-6fc2-48d9-93ea-d271c3ee44a1 | 1 | public static void main(String [] args) throws IOException, InterruptedException
{
init();
StringBuilder s = null;
while(true)
{
s = grabVal();
String temp = constructString(s);
write(temp);
Thread.sleep(1000000);
}
} |
4a37fed1-45d3-48e9-9861-238c8392f7e3 | 9 | private void processMultipart(Multipart multipart, PrintWriter printwriter)
throws Exception
{
boolean flag = true;
String s = "";
int i = 0;
for(int j = multipart.getCount(); i < j; i++)
{
BodyPart bodypart = multipart.getBodyPart(i);
String s1 = bodypart.getDisposition();
if(s1 != null && (s1.equalsIgnoreCase("attachment") || s1.equalsIgnoreCase("inline")))
saveFile(bodypart.getFileName(), bodypart.getInputStream());
if(s1 != null)
continue;
if(bodypart.isMimeType("text/html"))
{
flag = false;
InputStreamReader inputstreamreader = new InputStreamReader(bodypart.getInputStream());
BufferedReader bufferedreader = new BufferedReader(inputstreamreader);
for(String s2 = bufferedreader.readLine(); s2 != null; s2 = bufferedreader.readLine())
printwriter.print(s2);
bufferedreader.close();
continue;
}
if(bodypart.isMimeType("text/plain"))
{
s = (new StringBuilder()).append(s).append((String)bodypart.getContent()).toString();
} else
{
Multipart multipart1 = (Multipart)bodypart.getContent();
processMultipart(multipart1, printwriter);
}
}
if(flag)
printwriter.print(s);
} |
5d6f2248-5eb0-4ce2-888e-ca68efc8f1aa | 2 | private static Drug getDrug(Drug bean, PreparedStatement stmt, ResultSet rs) throws SQLException{
if(bean.getDrugId()!=0)
stmt.setInt(1, bean.getDrugId());
else
stmt.setString(1, bean.getDrugName());
rs = stmt.executeQuery();
if (rs.next()) {
Drug newBean = new Drug();
newBean.setDrugId(rs.getInt("drugid"));
newBean.setDrugName(rs.getString("drugname"));
newBean.setDescription(rs.getString("description"));
newBean.setQuantity(rs.getInt("quantity"));
newBean.setControlFlag(rs.getBoolean("controlflag"));
newBean.setSideEffect(rs.getString("sideeffect"));
newBean.setPrice(rs.getBigDecimal("price"));
newBean.setInterACtion(rs.getString("interaction"));
return newBean;
} else {
System.out.println("unable to retrieve drug info");
return null;
}
} |
58a63fcd-f7ff-4626-95e4-71f663ddd59f | 9 | @Override
public void run(){
//trick so that _ONLY_ send() can run this method!
//only send() sets isStarted to true.
//if send() is called with true isStarted it'll throw an exception
//thus it's impossible to call this function more than once.
if (!isStarted) return;
isReady = false;
try{
//method = {GET, POST, HEAD, OPTIONS, PUT, DELETE, TRACE};
switch(method){
//safe methods
case GET:
GET();
break;
case HEAD:
HEAD();
break;
case OPTIONS:
OPTIONS();
break;
case TRACE:
TRACE();
break;
//unsafe methods
case POST:
POST();
break;
case PUT:
PUT();
break;
case DELETE:
DELETE();
break;
//non-existing call -> what the f*ck ?!
default:
exception(new IllegalArgumentException("ERROR: invalid method: "+method));
responseCode = -1;
responseMessage = null;
break;
}
}catch(Exception e){
exception(e);
}
time = System.currentTimeMillis();
isReady = true;
//wake up waiting Network(s)
synchronized(this){
this.notifyAll();
}
} |
56990c89-65ca-4050-aafc-01f49d50cf19 | 9 | private void save() {
try {
RecordStore.deleteRecordStore(RECORDSTORE_SESSION); // Clear data
}
catch (Exception e) { /* Nothing to delete */ }
RecordStore rs = null;
ByteArrayOutputStream baos = null;
DataOutputStream dos = null;
try {
rs = RecordStore.openRecordStore(RECORDSTORE_SESSION, true);
baos = new ByteArrayOutputStream();
dos = new DataOutputStream(baos);
dos.writeUTF(category == null ? "" : category);
dos.writeUTF(username == null ? "" : username);
dos.writeUTF(modhash == null ? "" : modhash);
// Store the cookieTable: first an integer telling how many UTF-8
// encoded string entries to expect, then the Strings themselves
dos.writeInt(cookieTable.size());
Enumeration keys = cookieTable.keys();
while (keys.hasMoreElements()) {
String key = (String) keys.nextElement();
String value = (String) cookieTable.get(key);
dos.writeUTF(key + "|" + value);
}
// Add it to the record store
byte[] b = baos.toByteArray();
rs.addRecord(b, 0, b.length);
}
catch (RecordStoreException rse) {
rse.printStackTrace();
}
catch (IOException ioe) {
ioe.printStackTrace();
}
finally {
if (rs != null) {
try {
rs.closeRecordStore();
}
catch (Exception ex) {}
}
}
} |
a7647bd3-69fb-405b-9854-983fc807e991 | 3 | int dataSize() throws UnsupportedEncodingException
{
if ( parent!=null || isHint() )
return 0;
else if ( data == null )
return 0;
else
return byteLength();
} |
18f1c563-cd4a-4a44-9211-8ee9e823bd49 | 4 | public static void main(String[] args) throws NoSuchFileException, IllegalArgumentException {
if (args.length >= 5) {
Draft.checkHash( args[0] );
Draft.checkRange(args[1], 4, 15);
Draft.checkRange(args[2], 1, 50);
Draft.checkRange(args[3], 0., 1.);
for(int j=4; j < args.length; j++)
Draft.checkPath( args[j] );
String[] files = new String[args.length - 4];
for(int j=4; j<args.length; j++)
files[j-4]=args[j];
exec(files, Integer.parseInt(args[2]), Integer.parseInt(args[1]), args[0],
Double.parseDouble(args[3]));
} else if (args.length == 0) {
String hash = GetInput.askHash("Hash function");
String[] urls = GetInput.askPathSet("Paths to the files");
int b = GetInput.askParameterInRange("Parameter b", 4, 15);
int k = GetInput.askParameterInRange("Parameter k", 1, 50);
double threshold = GetInput.askParameterInRange("Threshold", 0., 1.);
exec(urls, k, b, hash, threshold);
} else
throw new IllegalArgumentException("Wrong number of arguments (5 or more expected)");
} |
aadfb99e-9371-44b6-bb14-c2a68743099b | 7 | private boolean searchCombo(int x, int y, int type) {
int slot = y * 15 + x + 1;
for (int i = 0; i < 5; i++) {
if (piece[slot + i] == type) {
if (i == 4) {
return true;
}
} else {
break;
}
}
for (int j = 15; j < 17; j++) {
for (int i = 0; i < 5; i++) {
if (piece[slot + i * j] == type) {
if (i == 4) {
return true;
}
} else {
break;
}
}
}
return false;
} |
6c16b8eb-049e-4df8-9292-8bd2bf711d0c | 4 | public void getCollidingBoundingBoxes(World var1, int var2, int var3, int var4, AxisAlignedBB var5, ArrayList var6) {
int var7 = var1.getBlockMetadata(var2, var3, var4);
if(var7 == 0) {
this.setBlockBounds(0.0F, 0.0F, 0.0F, 0.5F, 0.5F, 1.0F);
super.getCollidingBoundingBoxes(var1, var2, var3, var4, var5, var6);
this.setBlockBounds(0.5F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F);
super.getCollidingBoundingBoxes(var1, var2, var3, var4, var5, var6);
} else if(var7 == 1) {
this.setBlockBounds(0.0F, 0.0F, 0.0F, 0.5F, 1.0F, 1.0F);
super.getCollidingBoundingBoxes(var1, var2, var3, var4, var5, var6);
this.setBlockBounds(0.5F, 0.0F, 0.0F, 1.0F, 0.5F, 1.0F);
super.getCollidingBoundingBoxes(var1, var2, var3, var4, var5, var6);
} else if(var7 == 2) {
this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 0.5F, 0.5F);
super.getCollidingBoundingBoxes(var1, var2, var3, var4, var5, var6);
this.setBlockBounds(0.0F, 0.0F, 0.5F, 1.0F, 1.0F, 1.0F);
super.getCollidingBoundingBoxes(var1, var2, var3, var4, var5, var6);
} else if(var7 == 3) {
this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 0.5F);
super.getCollidingBoundingBoxes(var1, var2, var3, var4, var5, var6);
this.setBlockBounds(0.0F, 0.0F, 0.5F, 1.0F, 0.5F, 1.0F);
super.getCollidingBoundingBoxes(var1, var2, var3, var4, var5, var6);
}
this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F);
} |
409b195f-bb54-459a-bae8-bc6ed6707c1e | 8 | public void update()
{
int xa = 0, ya = 0;
counter++;
if(counter > 2)
{
if(game.xPlayer > x) xa++;
if(game.xPlayer < x) xa--;
if(game.yPlayer > y) ya++;
if(game.yPlayer < y) ya--;
counter = 0;
}
if(xa != 0 || ya != 0) {
move (xa, ya);
walking = true;
} else {
walking = false;
}
if(health <= 0)
{
remove(this);
}
} |
7a9c74db-0f6b-4993-b933-d54933e73234 | 2 | public static void handleUnsubscribeReply(HTSMsg msg, HTSPClient client) {
Collection<String> requiredFields = Arrays.asList(new String[]{});
if (msg.keySet().containsAll(requiredFields)){
//TODO
} else if (msg.get("error") != null){
//TODO
} else{
System.out.println("Faulty reply");
}
} |
e627547d-1dc6-4291-b11a-b2ceffeec08c | 5 | public void insert(int obj, int entry, int score)
{
try{
if (writeInvFile[entry]==null){
String newDirectory=indexDirectory+"/new";
File pl_f=new File(newDirectory+"/pl_e"+entry+".dat");
if(!pl_f.exists()){
File indexDirectory_f=new File(indexDirectory);
if(!indexDirectory_f.exists())
indexDirectory_f.mkdirs();
File newDirectory_f=new File(newDirectory);
if(!newDirectory_f.exists())
newDirectory_f.mkdirs();
pl_f.createNewFile();
}
writeInvFile[entry]=new BufferedOutputStream(new FileOutputStream(pl_f,true),bufferSize);
}
byte[] obj_buff=it.cnr.isti.SimilaritySearch.MI_File.Conversions.intToByteArray(obj);
byte[] score_buff=it.cnr.isti.SimilaritySearch.MI_File.Conversions.intToByteArray(score);
writeInvFile[entry].write(obj_buff);
writeInvFile[entry].write(score_buff);
// pl_w.close();
}catch(Exception e)
{
System.err.println("Cannot create or insert entry in posting list for entry "+entry+" and score "+score);
e.printStackTrace();
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.