method_id stringlengths 36 36 | cyclomatic_complexity int32 0 9 | method_text stringlengths 14 410k |
|---|---|---|
a46bfcd1-7c37-4ddd-8db0-f04b02f3b9cc | 4 | private int partition(char[] arr, int left, int right) {
char pivotEle = arr[(left + right) / 2];//just pick the middle one
while (left <= right) {
while (arr[left] < pivotEle)
left++;
while (arr[right] > pivotEle)
right--;
if (left <= right) {
swap(arr, left, right);
left++;
right--;
}
}
return left;
} |
d253c51d-f916-4a40-8006-d7144346ad2e | 1 | public static String trimExtension(String text, String separator) {
int index = text.lastIndexOf(separator);
if (index == -1) {
return text;
} else {
return text.substring(0, index);
}
} |
5accb855-0afa-4369-a52d-590e5f3fec20 | 0 | @Before
public void setUp() {
} |
617fd5b7-b294-4c56-9657-45103ee81996 | 8 | private Content processParamTags(boolean isNonTypeParams,
ParamTag[] paramTags, Map<String, String> rankMap, TagletWriter writer,
Set<String> alreadyDocumented) {
Content result = writer.getOutputInstance();
if (paramTags.length > 0) {
for (int i = 0; i < paramTags.length; ++i) {
ParamTag pt = paramTags[i];
String paramName = isNonTypeParams ?
pt.parameterName() : "<" + pt.parameterName() + ">";
if (! rankMap.containsKey(pt.parameterName())) {
writer.getMsgRetriever().warning(pt.position(),
isNonTypeParams ?
"doclet.Parameters_warn" :
"doclet.Type_Parameters_warn",
paramName);
}
String rank = rankMap.get(pt.parameterName());
if (rank != null && alreadyDocumented.contains(rank)) {
writer.getMsgRetriever().warning(pt.position(),
isNonTypeParams ?
"doclet.Parameters_dup_warn" :
"doclet.Type_Parameters_dup_warn",
paramName);
}
result.addContent(processParamTag(isNonTypeParams, writer, pt,
pt.parameterName(), alreadyDocumented.size() == 0));
alreadyDocumented.add(rank);
}
}
return result;
} |
49e085aa-3e3e-4d8c-9467-50d8c69be11e | 9 | public static BufferedImage gaussianFilterWithDepthMap(File file) {
// Get depthMap
DepthImage depthImage = new DepthImage(file);
if (!depthImage.isValid())
return null;
BufferedImage depthMap = toGrayScale(depthImage.getDepthMapImage());
BufferedImage originImage = depthImage.getOriginalColorImage();
BufferedImage result = new BufferedImage(depthMap.getWidth(),
depthMap.getHeight(), BufferedImage.TYPE_INT_RGB);
// Store the depth value of the depth map for further calculation
int maxDepthValue = 0;
int minDepthValue = 999;
int depthValues[][] = new int[result.getWidth()][result.getHeight()];
// Scan through each row of the image
for (int j = 0; j < result.getHeight(); j++) {
// Scan through each columns of the image
for (int i = 0; i < result.getWidth(); i++) {
// Returns an integer pixel in the default RGB color model
int values = depthMap.getRGB(i, j);
// Convert the single integer pixel value to RGB color
Color color = new Color(values);
// Store all the gray value as the depth value
depthValues[i][j] = color.getRed();
if (depthValues[i][j] < minDepthValue)
minDepthValue = depthValues[i][j];
if (depthValues[i][j] > maxDepthValue)
maxDepthValue = depthValues[i][j];
}
}
System.out.println("maxDepthValue: "+maxDepthValue);
System.out.println("minDepthValue: "+minDepthValue);
System.out.println("((maxDepthValue - minDepthValue) / 3): "+((maxDepthValue - minDepthValue) / 3));
System.out.println("(((maxDepthValue - minDepthValue) / 3) * 2): "+(((maxDepthValue - minDepthValue) / 3) * 2));
// TODO: Set color of the result image according to the gray value
// (depth value)
// Proof: Depth can be extract from the depthMap
int color[] = { 255, 0, 0 };
for (int j = 0; j < result.getHeight(); j++) {
for (int i = 0; i < result.getWidth(); i++) {
int depthValue = depthValues[i][j];
// int relativeDepthColor = (int) (255 * ((depthValue - minDepthValue) * 1.0 / (maxDepthValue - minDepthValue)));
color[RED] = 255;
color[GREEN] = 0;
color[BLUE] = 0;
if ((depthValue - minDepthValue) > ((maxDepthValue - minDepthValue) / 3)) {
color[RED] = 0;
color[GREEN] = 255;
color[BLUE] = 0;
}
if ((depthValue - minDepthValue) > (((maxDepthValue - minDepthValue) / 3) * 2)) {
color[RED] = 0;
color[GREEN] = 0;
color[BLUE] = 255;
}
// int depthDifference = depthValue - lastDepth;
// if (depthDifference > 5) {
// // depth increase
// int temp = color[0];
// color[0] = color[1];
// color[1] = color[2];
// color[2] = temp;
// } else if (depthDifference < -5) {
// // depth decrease
// int temp = color[0];
// color[0] = color[2];
// color[2] = color[1];
// color[1] = temp;
// }
// lastDepth = depthValues[i][j];
result.setRGB(i, j,
new Color(color[RED], color[GREEN], color[BLUE]).getRGB());
}
}
return result;
} |
1cc0dfd1-59f8-46ff-b0d1-bdfe961aaa54 | 7 | public void think() {
List<MouseEvent> mouseEvents = board.getMouseEvents();
//System.out.println("MOUSEVENTS: " + mouseEvents.size());
if(mouseEvents.size() > 0) {
MouseEvent e = mouseEvents.get(0);
//System.out.println("Clicked: " + e.getX() + "-" + e.getY());
int x = e.getX() / (int)Chess.SQUARE_PIXEL_WIDTH;
int y = e.getY() / (int)Chess.SQUARE_PIXEL_HEIGHT;
if(game.getActive() != null && game.getActive().getPiece() != null && game.getActive().getPiece().getColor() == game.getLocal()) {
//System.out.println("Active");
if(game.canMove(x, y)) {
nextMove[0] = game.getActive().getX();
nextMove[1] = game.getActive().getY();
nextMove[2] = x;
nextMove[3] = y;
moved = true;
board.clearMouseEvents();
return;
}
}
game.setActive(x, y);
if(game.getActive().getPiece() != null && game.getActive().getPiece().getColor() == game.getLocal()) {
//game.getActive().getPiece().createPossibleMoves();
}
}
board.clearMouseEvents();
} |
c3324bc5-0631-48b0-b436-4b1e8a1dfe42 | 4 | public static DoorDirection makeFromChar(char initial) {
switch(initial) {
case 'U':
return UP;
case 'D':
return DOWN;
case 'L':
return LEFT;
case 'R':
return RIGHT;
default:
return NONE;
}
} |
83b93e3d-8596-4bac-90bb-153d2aef5f56 | 7 | public void expandsLeaf(Coordinate coord) {
Coordinate subCoord;
for (int i = 0; i < 4; i++) {
subCoord = coord.copy();
switch (i) {
case 0:
subCoord.moveNorth();
break;
case 1:
subCoord.moveEast(dimension);
break;
case 2:
subCoord.moveSouth(dimension);
break;
case 3:
subCoord.moveWest();
break;
default:
break;
}
Element elem = getCell(subCoord);
if (elem.getElementType() == ElementType.WATER)
setCell(subCoord, LeafWater.getInstance());
else if (elem.getElementType() == ElementType.GRASS)
setCell(subCoord, Leaf.getInstance());
}
} |
f3d6d729-646f-4c35-a913-2db6798b8027 | 8 | public synchronized boolean setLevel(String str,int level){
//返回是否拥有这个属性 如果有则返回true 没有就返回false
//如果没有 会自动为你添加属性
boolean has = false;
for (int i = 0; i < getLoreSize() ; i++) {
String line = getString(i);
if(line.contains(str)) {
if(line.contains(": ")) {
has = true;
String strs[] = line.split(": ");
String newer = null;
if((!Main.other.contains(strs[0]))&&(!Main.special.contains(strs[0]))){
newer = strs[0]+": "+level;
}else if(Main.other.contains(strs[0])){
newer = strs[0]+": "+level+".0"+"%";
}else if(Main.special.contains(strs[0])){
newer = strs[0]+": "+("+"+level+".0-"+(level+5)+".0");
}
setStringAt(i,newer);
}
}
}
if(!has){
addString(str+": "+level);
}
return has;
} |
3876df14-06e0-4a71-b4d9-c50cf4126cfe | 6 | public Object invokeAdvice(Method method, Object invoker) throws Throwable
{
Object result;
final long tid = Thread.currentThread().getId();
final ThreadMXBean bean = ManagementFactory.getThreadMXBean();
MethodInfo caller = null;
if (Cpu.getInstance().getThreadProfiler(tid) != null)
{
caller = Cpu.getInstance().getThreadProfiler(tid).peekMethodInfo();
}
final MethodInfo called = Cpu.getInstance().monitor(method, caller);
called.setTimes(new Times(tid));
try
{
if (bean != null)
{
called.getTimes().setCpuTime(new Period(bean.getCurrentThreadCpuTime()));
called.getTimes().setUserTime(new Period(bean.getCurrentThreadUserTime()));
}
if (caller != null)
{
caller.getTimer().suspend();
}
called.getTimer().restart();
result = proceed(invoker);
}
finally
{
called.getTimer().stop();
Cpu.getInstance().getThreadProfiler(tid).popStack();
if (bean != null)
{
long cpuTime = bean.getCurrentThreadCpuTime();
long userTime = bean.getCurrentThreadUserTime();
called.getTimes().getCpuTime().setEndTime(cpuTime);
called.getTimes().getUserTime().setEndTime(userTime);
}
if ("main".equalsIgnoreCase(method.getName()))
{
Cpu.getInstance().getThreadProfiler(tid).stop(called.getTimes().getUserTime().time());
Cpu.getInstance().getThread(tid).getTimer().stop();
}
if (caller != null)
{
caller.getTimer().resume();
}
}
return result;
} |
9c044743-6ba1-477a-8c63-ccd663b58308 | 5 | @Override
public void execute(CommandSender sender, String worldName, List<String> args) {
this.sender = sender;
if (worldName == null) {
error("No gate given.");
reply("Usage: /gworld setweather <worldname> <sun|storm>");
} else if (args.size() == 0) {
error("No weather given.");
reply("Usage: /gworld setweather <worldname> <sun|storm>");
} else if (!hasWorld(worldName)) {
reply("World not found: " + worldName);
} else {
for (Weather thisWeather : DataWorld.Weather.values()) {
if (thisWeather.toString().equalsIgnoreCase(args.get(0))) {
getWorld(worldName).setWeather(thisWeather);
reply("Weather of world " + worldName + " changed to " + args.get(0) + ".");
return;
}
}
reply("Unknown weather type: " + args.get(0) + ". Use \"sun\" or \"storm\"");
}
} |
725eb951-b7de-4206-ae61-6f929ace99d0 | 3 | public List<String> getNextLink() {
if (inFile == null) {
openFile();
}
if (open) {
try {
return inFile.readLine();
} catch (IOException ex) {
closeFile();
Logger.getLogger(ReadSimpleLinksFile.class.getName()).log(Level.SEVERE, null, ex);
return null;
}
} else {
return null;
}
} |
7e4d3812-aa9b-431b-81c6-abd91eb00001 | 3 | public static DayTypeEnumeration fromString(String v) {
if (v != null) {
for (DayTypeEnumeration c : DayTypeEnumeration.values()) {
if (v.equalsIgnoreCase(c.toString())) {
return c;
}
}
}
throw new IllegalArgumentException(v);
} |
5b75c9b2-eeb4-460f-8806-87224b4e6599 | 9 | private int[] getNumbers () {
boolean numberBegin = false;
boolean addDigit = false;
boolean isDigit;
int numberBeginPos = -1;
int[] vector;
int position = 0;
char eachChar;
String vector1;
String temporary = "";
vector = new int[50];
vector1 = this.input.nextLine();
for (int counter = 0, stringLength = vector1.length(); counter < stringLength; counter += 1) {
eachChar = vector1.charAt(counter);
isDigit = Character.isDigit(eachChar);
if (isDigit) {
temporary += eachChar;
numberBegin = !(counter == stringLength - 1);
if (numberBegin) {
numberBeginPos = counter;
}
if (!numberBegin) {
addDigit = true;
}
}
if (!isDigit && numberBegin) {
addDigit = true;
numberBegin = false;
}
if (addDigit) {
addDigit = false;
vector[position] = Integer.parseInt(temporary);
if (numberBeginPos > 0 && vector1.charAt(numberBeginPos - 1) == '-') {
vector[position] *= - 1;
System.out.println(vector[position]);
}
position += 1;
temporary = "";
}
}
return vector;
} |
60979b30-b5e2-4825-ae56-3c0eb0a4c946 | 2 | public static void main(String[] args){
List<String[]> list = new N_Queens().solveNQueens(4);
String[] board;
for(int i = 0; i< list.size();i++){
board = list.get(i);
for(int j = 0 ; j < board.length;j++)
System.out.println(board[j].toString());
System.out.println("*****************");
}
} |
05e1e029-9b76-418b-b7c7-60189c382a37 | 0 | protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
} |
2b04e591-87e8-4e9d-87e6-3fc80b27e151 | 9 | void populateWinPanel(){
setLayout(new BoxLayout(this, BoxLayout.LINE_AXIS));
panelWidth = getWidth();
panelHeight = getHeight();
labelWidth = panelWidth/(BrackEm.bracketData.getTotalRoundsW() + 1); // Include final winner (+1)
int startingLabels = 2*(BrackEm.bracketData.getSecondPlayersW());
if (BrackEm.debug){
System.out.println("BracketPanel (populateWinPanel): winPanel width: " + panelWidth);
System.out.println("BracketPanel (populateWinPanel): winPanel height: " + panelHeight);
System.out.println("BracketPanel (populateWinPanel): Rounds: " + BrackEm.bracketData.getTotalRoundsW());
System.out.println("BracketPanel (populateWinPanel): Label width: " + labelWidth);
System.out.println("BracketPanel (populateWinPanel): Start labels: " + startingLabels);
}
for(int i=0;i<=BrackEm.bracketData.getTotalRoundsW();i++) { // Include final winner (<=)
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
int numOfLabels = (int) (startingLabels/(Math.pow(2, i)));
labelHeight = panelHeight/numOfLabels;
if (BrackEm.debug){
System.out.println("BracketPanel (populateWinPanel): Number of labels: " + numOfLabels);
System.out.println("BracketPanel (populateWinPanel): Label height: " + labelHeight);
}
boolean upper = true;
boolean individual = false;
if (i==BrackEm.bracketData.getTotalRoundsW()){ // Last panel is individual
individual = true;
}
HashMap<Bracket, Integer> tempHashMap = new HashMap<Bracket, Integer>();
for(int ii=1;ii<=numOfLabels;ii++) { // Placement index, Where the label is placed on the panel (vs. Mapping index)
if ( (ii % 2) == 0){ // Check even/odd for upper/lower
upper = false;
} else {
upper = true;
}
if (i==0){ // First round placement
if (BrackEm.bracketData.getFirstRoundByW()!=0) { // First round Bys
int[] mapVals = BracketCalc.getFirstOrder(numOfLabels); // Ordered values to enter in hashmap
if (mapVals[ii-1]<=BrackEm.bracketData.getFirstPlayersW()){ // Placement value is less than the number of first round players
// Bracket bracket = new Bracket(labelWidth,labelHeight,individual,upper,mapVals[ii-1]);
Bracket bracket = new Bracket(labelWidth,labelHeight,individual,upper,ii,i); // Retain placement index
bracket.setEditable(true);
tempHashMap.put(bracket,mapVals[ii-1]); // Follow mapping index
panel.add(bracket);
} else {
panel.add(Box.createRigidArea(new Dimension(0,labelHeight)));
}
} else {
Bracket bracket = new Bracket(labelWidth,labelHeight,individual,upper,ii,i);
bracket.setEditable(true);
tempHashMap.put(bracket,ii);
panel.add(bracket);
}
} else {
Bracket bracket = new Bracket(labelWidth,labelHeight,individual,upper,ii,i);
tempHashMap.put(bracket,ii);
panel.add(bracket);
}
}
hashList.add(tempHashMap);
this.add(panel);
}
} |
c808cb2b-4afc-47ae-9694-e451d701de4a | 8 | public Client_Part2(){
Socket socket = null;
ObjectOutputStream out = null;
ObjectInputStream in = null;
try {
Object[] input = new Object[4];
Object[] output;
socket = new Socket("127.0.0.1", 4444);
out = new ObjectOutputStream(socket.getOutputStream());
in = new ObjectInputStream(socket.getInputStream());
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
boolean running = true;
System.out.println("waiting for server input");
String inputMethods = (String) in.readObject();
System.out.println("got input");
String[] methods = inputMethods.split(";");
System.out.println("Here are the possible methods to call:");
int count = 1;
for(String method : methods){
System.out.println((count) + ": " + method);
count++;
}
while(running){
System.out.println("Input a number corresponding to the method you want to call or 'bye' to quit");
Scanner scan = new Scanner(System.in);
String methodChoice = scan.nextLine();
int[] serverOutput = new int[3];
if(methodChoice.toLowerCase().equals("bye") || input == null){
running = false;
methodChoice = -1 +"";
}
else if(running){
System.out.println("Enter the first int: ");
serverOutput[1] = scan.nextInt();
System.out.println("Enter the second int: ");
serverOutput[2] = scan.nextInt();
}
serverOutput[0] = Integer.parseInt(methodChoice);
out.writeObject(serverOutput);
String response = (String)in.readObject();
System.out.println("Server: " + response);
}
out.close();
in.close();
stdIn.close();
socket.close();
} catch (UnknownHostException e) {
System.err.println("Don't know about host: taranis.");
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to: taranis.");
System.exit(1);
} catch (ClassNotFoundException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
} |
67acbe83-54d3-45bd-ac61-5738af709e2e | 5 | @Override
public void render() {
if(previousScreen != null && previousScreen instanceof GameScreen){
GameScreen prevGameScreen = (GameScreen) previousScreen;
if(!prevGameScreen.outTransitionFinished()){
prevGameScreen.renderOut(Gdx.graphics.getDeltaTime());
return;
}
else{
previousScreen = null;
}
}
if(currentScreen instanceof GameScreen){
GameScreen currGameScreen = (GameScreen) currentScreen;
if(!currGameScreen.inTransitionFinished()){
currGameScreen.renderIn(Gdx.graphics.getDeltaTime());
return;
}
}
currentScreen.render(Gdx.graphics.getDeltaTime());
} |
8015f36a-034a-42ec-b0e4-1f7f4f50dd2f | 6 | private void addFileMenu() {
JMenuBar jb = this.getJMenuBar();
if (jb == null)
jb = new JMenuBar();
JMenu menu = new JMenu("file");
JMenuItem newItem = new JMenuItem("new simulation ...");
saveItem = new JMenuItem("save");
saveAsItem = new JMenuItem("save as");
JMenuItem openItem = new JMenuItem("open ...");
JCheckBox toolBox = new JCheckBox("component tools", true);
exitItem = new JMenuItem("exit");
exitItem.addActionListener(this);
saveItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
saveDesign(file);
saveItem.setEnabled(false);
}
});
saveItem.setEnabled(false);
newItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
setFile(null);
panel.clear();
saveItem.setEnabled(false);
}
});
saveAsItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
saveDesignToNewFile();
saveItem.setEnabled(false);
}
});
saveAsItem.setEnabled(false);
openItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (saveItem.isEnabled() || saveAsItem.isEnabled()) {
queryToSave();
}
JFileChooser fc = new JFileChooser();
if (file != null)
fc.setSelectedFile(file);
FileNameExtensionFilter filter = new FileNameExtensionFilter(
"Simu Files", "smu");
fc.setFileFilter(filter);
int returnVal = fc.showOpenDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File fileTmp = fc.getSelectedFile();
try {
panel.clear();
panel.readFrom(fileTmp);
setFile(fileTmp);
saveItem.setEnabled(false);
} catch (Exception e1) {
JOptionPane.showMessageDialog(null,
"Error in reading in file\n "
+ fileTmp.getName()
+ "\nError Message:\n "
+ e1.getMessage());
}
}
}
});
toolBox.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JCheckBox cb = (JCheckBox) e.getSource();
componentTB.setVisible(cb.isSelected());
}
});
menu.add(newItem);
menu.add(openItem);
menu.add(new JSeparator());
menu.add(saveItem);
menu.add(saveAsItem);
menu.add(new JSeparator());
menu.add(toolBox);
menu.add(new JSeparator());
menu.add(exitItem);
jb.add(menu);
this.setJMenuBar(jb);
} |
722b4b3d-305f-4355-9412-4e2062ed98aa | 1 | private boolean shouldCollide(PositionChangedObservable o) {
ShouldCollideWithPowerFailureVisitor visitor = new ShouldCollideWithPowerFailureVisitor(o);
for(PositionChangedObservable e : hoveringElements)
e.accept(visitor);
return visitor.shouldCollide();
} |
c09aa9b8-99da-4095-b92f-a5be5f40fa5d | 9 | public static ClassData getPrimitiveClassFor(TypeType type) {
switch (type) {
case BOOLEAN: return boolClassData;
case BYTE: return byteClassData;
case CHAR: return charClassData;
case SHORT: return shortClassData;
case INT: return intClassData;
case LONG: return longClassData;
case FLOAT: return floatClassData;
case DOUBLE: return doubleClassData;
case VOID: return voidClassData;
default: throw new IllegalArgumentException("Type is not supported:" + type);
}
} |
d820311b-4624-4191-8498-cd7ba94d3a76 | 8 | private ByteBuffer createQueue(String queueName, String address) {
ClientConnectionLogRecord record = new ClientConnectionLogRecord(
address, SystemEvent.QUEUE_CREATION,
"Received request to create queue " + queueName + " from "
+ address + ".");
LOGGER.log(record);
Connection conn = null;
try {
conn = dbConnectionDispatcher.retrieveDatabaseConnection();
CreateQueue.execute(queueName, conn);
conn.commit();
record = new ClientConnectionLogRecord(address,
SystemEvent.QUEUE_CREATION, "Queue " + queueName
+ " created for " + address + ".", record);
LOGGER.log(record);
RequestResponse successResponse = new RequestResponse(
Status.SUCCESS);
return ProtocolMessage.toBytes(successResponse);
} catch (SQLException e) {
LOGGER.log(new ClientConnectionLogRecord(address,
SystemEvent.QUEUE_CREATION,
"Caught exception while trying to create queue " + "for "
+ address + ".", record, e));
RequestResponse errorResponse = new RequestResponse(
Status.EXCEPTION, e.toString());
if (conn != null)
try {
conn.rollback();
} catch (SQLException e1) {
logRollbackException(e1);
}
return ProtocolMessage.toBytes(errorResponse);
} catch (QueueAlreadyExistsException e) {
LOGGER.log(new ClientConnectionLogRecord(address,
SystemEvent.QUEUE_CREATION,
"Responded with failure to create queue request from "
+ address + " because queue " + queueName
+ " already exists.", record));
RequestResponse failureResponse = new RequestResponse(
Status.QUEUE_EXISTS);
if (conn != null)
try {
conn.rollback();
} catch (SQLException e1) {
logRollbackException(e1);
}
return ProtocolMessage.toBytes(failureResponse);
} finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
logCloseException(e);
}
}
}
} |
6da4078f-6e8d-4f78-b9a5-e4fafe5a968d | 9 | public static PlotData2D setUpVisualizableInstances(Instances testInstances,
ClusterEvaluation eval)
throws Exception {
int numClusters = eval.getNumClusters();
double [] clusterAssignments = eval.getClusterAssignments();
FastVector hv = new FastVector();
Instances newInsts;
Attribute predictedCluster;
FastVector clustVals = new FastVector();
for (int i = 0; i < numClusters; i++) {
clustVals.addElement("cluster"+i);
}
predictedCluster = new Attribute("Cluster", clustVals);
for (int i = 0; i < testInstances.numAttributes(); i++) {
hv.addElement(testInstances.attribute(i).copy());
}
hv.addElement(predictedCluster);
newInsts = new Instances(testInstances.relationName()+"_clustered", hv,
testInstances.numInstances());
double [] values;
int j;
int [] pointShapes = null;
int [] classAssignments = null;
if (testInstances.classIndex() >= 0) {
classAssignments = eval.getClassesToClusters();
pointShapes = new int[testInstances.numInstances()];
for (int i = 0; i < testInstances.numInstances(); i++) {
pointShapes[i] = Plot2D.CONST_AUTOMATIC_SHAPE;
}
}
for (int i = 0; i < testInstances.numInstances(); i++) {
values = new double[newInsts.numAttributes()];
for (j = 0; j < testInstances.numAttributes(); j++) {
values[j] = testInstances.instance(i).value(j);
}
values[j] = clusterAssignments[i];
newInsts.add(new Instance(1.0, values));
if (pointShapes != null) {
if ((int)testInstances.instance(i).classValue() !=
classAssignments[(int)clusterAssignments[i]]) {
pointShapes[i] = Plot2D.ERROR_SHAPE;
}
}
}
PlotData2D plotData = new PlotData2D(newInsts);
if (pointShapes != null) {
plotData.setShapeType(pointShapes);
}
plotData.addInstanceNumberAttribute();
return plotData;
} |
0a112a0a-d1de-45e3-a5e4-e6a542e8c1fd | 2 | public Counter nextTurn(Counter lastPlaced, Board b) {
Counter next = Counter.EMPTY;
if (lastPlaced == Counter.BLACK) {
next = Counter.WHITE;
} else if (lastPlaced == Counter.WHITE) {
next = Counter.BLACK;
}
return next;
} |
567468a4-168a-4897-a99f-7c0c2032cd4d | 6 | public int t3Lookback( int optInTimePeriod,
double optInVFactor )
{
if( (int)optInTimePeriod == ( Integer.MIN_VALUE ) )
optInTimePeriod = 5;
else if( ((int)optInTimePeriod < 2) || ((int)optInTimePeriod > 100000) )
return -1;
if( optInVFactor == (-4e+37) )
optInVFactor = 7.000000e-1;
else if( (optInVFactor < 0.000000e+0) || (optInVFactor > 1.000000e+0) )
return -1;
return 6 * (optInTimePeriod-1) + (this.unstablePeriod[FuncUnstId.T3.ordinal()]) ;
} |
179386bc-eb71-47b0-a897-c4bad01f789e | 2 | public ZoomDataRecord next() {
// Is there a need to fetch next data block?
if (zoomRecordIndex < zoomRecordList.size())
return (zoomRecordList.get(zoomRecordIndex++));
// attempt to get next leaf item data block
else {
int nHits = getHitRegion(selectionRegion, isContained);
if (nHits > 0) {
// Note: getDataBlock initializes bed feature index to 0
return (zoomRecordList.get(zoomRecordIndex++)); // return 1st Data Block item
} else {
String result = String.format("Failed to find data for zoom region (%d,%d,%d,%d)\n",
hitRegion.getStartChromID(), hitRegion.getStartBase(),
hitRegion.getEndChromID(), hitRegion.getEndBase());
log.error(result);
return null;
//throw new NoSuchElementException(result);
}
}
} |
e08ba8dc-df95-432f-a529-c7ecdd9ce47c | 4 | private void fechavenceFieldKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_fechavenceFieldKeyTyped
// TODO add your handling code here:
if (!Character.isDigit(evt.getKeyChar()) && evt.getKeyChar() !='-' && !Character.isISOControl(evt.getKeyChar()))
{
Toolkit.getDefaultToolkit().beep();
evt.consume();
}
if(fechavenceField.getText().length() == 10)
{
Toolkit.getDefaultToolkit().beep();
evt.consume();
JOptionPane.showMessageDialog(this, "Fecha de vencimiento demasiado larga. \n El formato correcto es (YYYY-MM-DD)", "ADVERTENCIA", WIDTH);
}
}//GEN-LAST:event_fechavenceFieldKeyTyped |
1cae4f3d-6eeb-44fe-91e4-a55ce8fbb3bc | 5 | public boolean addClient(String s){
boolean added = false;
for(byte i = 0; i < maxPlayers; i++){
if(!added){//make sure not to add a person multiple times
if(clients[i] == ""){
clients[i] = s;
added = true; //they've been added.
currentPlayers++;
}
}
}
System.out.println("current players waiting:"+currentPlayers); //visibility of what's going on
System.out.println("maximum players waiting:"+maxPlayers);
if(currentPlayers == maxPlayers){//The game shall begin
for(byte i = 0; i < currentPlayers; i++){
model.addPlayer(clients[i]);
clients[i] = "";
}
currentPlayers = 0;
model = new SetGame(); //the model now refers to a new game in case others join
System.out.println(maxPlayers+" player game started");//visibility
return true; //game has started.
}
System.out.println("someone just joined a "+maxPlayers+"game");//visibility
return false; //not enough players, game hasn't started yet.
} |
5f400241-4241-4616-a5ae-90d4da397091 | 0 | public void clearSelected() {
selectedNodes.clear();
} |
a012958d-a08d-445f-a253-28008d2e6147 | 4 | public synchronized void broadcast(String message, Player player) {
for (Player client : players) {
if (client == null)
continue;
if (player == client)
continue;
if (client.getUser().getGameSocket() != null)
client.getUser().getGameSocket().sendMessage(message);
}
} |
5b7525b0-2b32-4802-b629-930a8cb11aab | 6 | public void drawInverse(int i, int j) {
i += offsetX;
j += offsetY;
int l = i + j * DrawingArea.width;
int i1 = 0;
int j1 = height;
int k1 = width;
int l1 = DrawingArea.width - k1;
int i2 = 0;
if (j < DrawingArea.topY) {
int j2 = DrawingArea.topY - j;
j1 -= j2;
j = DrawingArea.topY;
i1 += j2 * k1;
l += j2 * DrawingArea.width;
}
if (j + j1 > DrawingArea.bottomY)
j1 -= (j + j1) - DrawingArea.bottomY;
if (i < DrawingArea.topX) {
int k2 = DrawingArea.topX - i;
k1 -= k2;
i = DrawingArea.topX;
i1 += k2;
l += k2;
i2 += k2;
l1 += k2;
}
if (i + k1 > DrawingArea.bottomX) {
int l2 = (i + k1) - DrawingArea.bottomX;
k1 -= l2;
i2 += l2;
l1 += l2;
}
if (k1 <= 0 || j1 <= 0) {
} else {
blockCopy(l, k1, j1, i2, i1, l1, pixels, DrawingArea.pixels);
}
} |
b0874dcf-9ed6-4451-bad8-602966f0256b | 8 | public static void main(String[] args) {
//创建一个serversocket
try(AsynchronousServerSocketChannel serverSocketChannel = AsynchronousServerSocketChannel.open()) {
//判断是否打开
if (serverSocketChannel.isOpen()) {
//判断支持那些optiosn
Set<SocketOption<?>> socketOptions = serverSocketChannel.supportedOptions();
System.out.println(socketOptions);
//设置options
serverSocketChannel.setOption(StandardSocketOptions.SO_RCVBUF, 4 * 1024);
serverSocketChannel.setOption(StandardSocketOptions.SO_REUSEADDR, true);
//绑定本地地址
System.out.println(serverSocketChannel.getLocalAddress());
serverSocketChannel.bind(new InetSocketAddress("127.0.0.1", 5555));
System.out.println(serverSocketChannel.getLocalAddress());
//接受连接
Future<AsynchronousSocketChannel> future = serverSocketChannel.accept();
while (!future.isDone()) {
System.out.println("waiting for complete.....");
}
AsynchronousSocketChannel asynchronousSocketChannel = future.get();
//获取远程地址
SocketAddress remoteAddress = asynchronousSocketChannel.getRemoteAddress();
System.out.println(remoteAddress);
//读取数据
ByteBuffer byteBuffer = ByteBuffer.allocate(2048);
int count = 0;
while ((count = asynchronousSocketChannel.read(byteBuffer).get()) != -1) {
System.out.println("read count :" + count);
byteBuffer.flip();
Integer integer = asynchronousSocketChannel.write(byteBuffer).get();
System.out.println("write count :"+integer);
if (byteBuffer.hasRemaining()) {
byteBuffer.compact();
}else{
byteBuffer.clear();
}
}
asynchronousSocketChannel.close();
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
} |
14859e64-dfa7-427d-bd0d-35eea0489d61 | 4 | public List<String> getFirstDefinition(Collection<PearsonDictionaryEntry> entries) {
List<String> definition = new ArrayList<String>();
for (PearsonDictionaryEntry entry : entries) {
for (PearsonWordSense sense : entry.getSenses()) {
if (sense.getDefinition() != null && !"".equals(sense.getDefinition())) {
String[] ems = sense.getDefinition().split(" ");
definition = Arrays.asList(ems);
break;
}
}
}
return definition;
} |
80749a69-3b36-41b3-a855-951e19791e41 | 3 | @Override
public Object execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
Contexto oContexto = (Contexto) request.getAttribute("contexto");
//Parte para saber el tipo de usuario
UsuarioBean oUsuarioBean;
oUsuarioBean = (UsuarioBean) request.getSession().getAttribute("usuarioBean");
java.lang.Enum tipoUsuario = oUsuarioBean.getTipoUsuario();
//Hasta aquí
//Validación
if (tipoUsuario.equals(net.daw.helper.Enum.TipoUsuario.Profesor)) {
oContexto.setVista("jsp/profesor/list.jsp");
try {
ProfesorDao oProfesorDao = new ProfesorDao(oContexto.getEnumTipoConexion());
Integer intPages = oProfesorDao.getPages(oContexto.getNrpp(), oContexto.getAlFilter(), oContexto.getHmOrder());
Integer intRegisters = oProfesorDao.getCount(oContexto.getAlFilter());
if (oContexto.getPage() >= intPages) {
oContexto.setPage(intPages);
}
ArrayList<ProfesorBean> listado = (ArrayList<ProfesorBean>) oProfesorDao.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("ProfesorList1: View Error: " + e.getMessage());
}
} else {
//Mostramos el MENSAJE
oContexto.setVista("jsp/mensaje.jsp");
return "<span class=\"label label-important\">¡¡¡ No estás autorizado a entrar aquí !!!<span>";
}
} |
6dcf64a0-3a1a-463b-99a7-bed1b985ef56 | 0 | public long getId(){
return id;
} |
5e0b12df-e051-42e2-a17d-6965dfe03424 | 7 | public static void main(String[] args) {
// TODO Auto-generated method stub
ticTACtoe game1 = new ticTACtoe();
game1.table = new char[3][3];
game1.populate();
game1.print();
boolean win = true;
int x1 = 0, y1 = 0;
int x2 = 0, y2 = 0;
int last=0;
System.out.println("You will play against the computer and have the mark X");
while (win) {
boolean comp = true;
System.out.println("enter a x and y value:");
x1 = sc.nextInt();
y1 = sc.nextInt();
if (game1.set1(x1, y1))
System.out.println("You set X at " + x1 + " , " + y1);
else
continue;
if (game1.checkwin()) {
System.out.println("It seems we have a winner");
break;
}
while (comp) {
x2 = game1.setterofcompx();
y2 = game1.setterofcompy();
if (game1.set2(x2, y2)) {
System.out.println("Comp set O at " + x2 + " , " + y2);
comp = false;
} else
comp = true;
}
System.out.println(countX);
System.out.println(countO);
game1.print();
if (game1.checkwin()) {
System.out.println("It seems we have a winner");
break;
}
}
if (countX > countO)
System.out.println("Winner is player1");
else
System.out.println("Winner is computer");
} |
cfd984b0-6e90-46b6-af8b-e5a9aa94b27f | 9 | public static void insert(User currUser, Tables tables, Statement stmt,
String query) {
ResultSet rset = null;
if (query.toLowerCase().contains("users")) {
} else {
Iterator tableIter = tables.getIter();
while (tableIter.hasNext()) {
String table = (String) tableIter.next();
// System.out.println(table + " ");
if (query.toUpperCase().contains(table)) {
try {
System.out.println("SELECT INTLEVEL " + "from TABLEINT"
+ " where TABLENAME =" + "'"
+ table.toUpperCase() + "'");
rset = stmt.executeQuery("SELECT INTLEVEL "
+ "from TABLEINT" + " where TABLENAME =" + "'"
+ table.toUpperCase() + "'");
} catch (Exception e) {
e.printStackTrace();
}
}
}
int tablelevel = -1;
try {
while (rset.next()) {
tablelevel = Integer.parseInt(rset.getString(1));
// System.out.println(rset.getString(1));
}
if (tablelevel <= currUser.intLevel && tablelevel != -1) {
query = query.substring(0, query.lastIndexOf(')')) + ","
+ currUser.intLevel + ")";
// System.out.println(query);
stmt.executeUpdate(query);
}
} catch (NumberFormatException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
} |
d3cf1235-2fd6-4d91-8c36-1b92c7290d25 | 1 | public DisjointSet(int n) {
root = new int[n + 1];
for (int i = 0; i < root.length; i++) {
root[i] = i;
}
rank = new int[n + 1];
} |
30dfd4bb-4417-4416-b76b-99dce8bb34f3 | 8 | public boolean equals(Object obj) {
if (obj == this) return true;
if (obj == null) return false;
if (obj.getClass() != this.getClass()) return false;
Picture that = (Picture) obj;
if (this.width() != that.width()) return false;
if (this.height() != that.height()) return false;
for (int x = 0; x < width(); x++)
for (int y = 0; y < height(); y++)
if (!this.get(x, y).equals(that.get(x, y))) return false;
return true;
} |
7d369bf5-2a2f-43b3-835d-77dc189c7c62 | 3 | private void parseDocument() throws XPathExpressionException {
XPath xpath = XPathFactory.newInstance().newXPath();
NodeList forceList;
NodeList cityList;
NodeList characterList;
Node structure;
Node technology;
Database db = Database.getInstance();
String string;
int id;
// Parse ForceList
string = "force";
forceList = (NodeList) xpath.evaluate(string, doc, XPathConstants.NODESET);
for (int i = 0; i < forceList.getLength(); i++) {
// Parse Attributes
string = "@id";
id = (int) xpath.evaluate(string, forceList.item(i), XPathConstants.NUMBER);
string = "@silver";
int silver = (int) xpath.evaluate(string, forceList.item(i), XPathConstants.NUMBER);
string = "@grain";
int grain = (int) xpath.evaluate(string, forceList.item(i), XPathConstants.NUMBER);
// Parse CityList
string = "city";
cityList = (NodeList) xpath.evaluate(string, forceList.item(i),XPathConstants.NODESET);
for (int j = 0; j < cityList.getLength(); j++) {
// Parse Attributes
string = "@id";
id = (int) xpath.evaluate(string, cityList.item(j), XPathConstants.NUMBER);
string = "@soldiers";
int soldiers = (int) xpath.evaluate(string, cityList.item(j), XPathConstants.NUMBER);
// Parse CharacterList
string = "character";
characterList = (NodeList) xpath.evaluate(string, cityList.item(j), XPathConstants.NODESET);
for (int k = 0; k < characterList.getLength(); k++) {
// Parse Attributes
string = "@id";
id = (int) xpath.evaluate(string, characterList.item(k), XPathConstants.NUMBER);
}
// Parser StructuresList
string = "structures";
structure = (Node) xpath.evaluate(string, cityList.item(j), XPathConstants.NODE);
}
// Parser Technology
string = "technology";
technology = (Node) xpath.evaluate(string, forceList.item(i), XPathConstants.NODE);
}
// Update
} |
9a5aad50-1a20-4f72-b223-94620d2e121e | 7 | @Override
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();
if (gameOver) {
if (keyCode == KeyEvent.VK_F2) {
startGame();
return;
}
}
pt.flag = false;
switch (keyCode) {
case KeyEvent.VK_LEFT:
currentTetro.toLeft();
break;
case KeyEvent.VK_RIGHT:
currentTetro.toRight();
break;
case KeyEvent.VK_DOWN:
currentTetro.toDown();
break;
case KeyEvent.VK_UP:
Tetromino t1 = currentTetro.toUp();
if (t1 != null) {
currentTetro = t1;
}
break;
}
repaint();
pt.flag = true;
} |
a498d46a-1372-4dc1-ade4-c862110def5b | 8 | public static void main(String[] args) throws IOException {
Scanner in = new Scanner(new File("transform.in"));
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("transform.out")));
int N = in.nextInt();in.nextLine();
char[][] before = new char[N][N];
for (int i = 0; i < N; i++) {
before[i] = in.nextLine().toCharArray();
}
char[][] after = new char[N][N];
for (int i = 0; i < N; i++) {
after[i] = in.nextLine().toCharArray();
}
// check #1, #2, #3
char[][] tmp = before.clone();
for (int i = 1; i <= 3; i++) {
tmp = rotate90(tmp, N);
if (equals(tmp, after)) {
out.println(i);
exit(in, out);
}
}
// check #4
tmp = reflect(before, N);
if (equals(tmp, after)) {
out.println(4);
exit(in, out);
}
// check #5
for (int i = 1; i <= 3; i++) {
tmp = rotate90(tmp, N);
if (equals(tmp, after)) {
out.println(5);
exit(in, out);
}
}
//check #6
if (equals(before, after)) {
out.println(6);
exit(in, out);
}
//check #7
out.println(7);
exit(in, out);
} |
f60872fa-f2a3-4595-8274-ad6fd47b6444 | 3 | @Override
public int hashCode() {
int result;
long temp;
result = boxId;
result = 31 * result + (boxDate != null ? boxDate.hashCode() : 0);
temp = amount != +0.0d ? Double.doubleToLongBits(amount) : 0L;
result = 31 * result + (int) (temp ^ (temp >>> 32));
temp = vale != +0.0d ? Double.doubleToLongBits(vale) : 0L;
result = 31 * result + (int) (temp ^ (temp >>> 32));
return result;
} |
5264b5ab-6ba9-4b74-9d34-158b39d1cec6 | 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(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
} |
12d41351-3eb1-40fb-a215-15b755a9f241 | 0 | public ROUI() {
robotInstance = new RORobotInstance();
robotInstance.getDashboardData().addObserver(this);
robotInstance.getJoystickHandler().addObserver(this);
addKeyListener (this);
buildGUI();
} |
8a4a6995-2de1-4365-a9ef-de120058a71a | 9 | public void mouseReleased(MouseEvent e) {
if (e.getModifiers() == MouseEvent.BUTTON1_MASK) {
if (isValidPosition(e.getX(), e.getY())) {
mouseX = e.getX();
mouseY = e.getY();
}
selectObstacle(e.getX(), e.getY());
mouseLeftClick = false;
} else {
if (mouseRightClick) {
mouseEndX = e.getX();
mouseEndY = e.getY();
if (Math.max(mouseStartX, mouseEndX) - Math.min(mouseStartX, mouseEndX) > 2
&& Math.max(mouseStartY, mouseEndY) - Math.min(mouseStartY, mouseEndY) > 2) {
if (xBak < Math.max(mouseStartX, mouseEndX) && xBak > Math.min(mouseStartX, mouseEndX)
&& yBak < Math.max(mouseStartY, mouseEndY) && yBak > Math.min(mouseStartY, mouseEndY)) {
System.out.println("Overlapping Obstacle");
} else {
dataBus.getObstacles().add(new PdoRectangle(mouseStartX, mouseStartY, mouseEndX, mouseEndY, DataBus.RECTANGLE_ARC_SIZE));
}
}
mouseRightClick = false;
} else {
treeMenu.show(this, e.getX(), e.getY());
}
}
} |
6fe47e46-aba4-462c-97c1-626cfb99656f | 3 | public SignatureVisitor visitInterfaceBound() {
if (state != FORMAL && state != BOUND) {
throw new IllegalArgumentException();
}
SignatureVisitor v = sv == null ? null : sv.visitInterfaceBound();
return new CheckSignatureAdapter(TYPE_SIGNATURE, v);
} |
638e97f5-7736-4903-b83b-f13eda013f54 | 3 | public List<Card> removeOne(List<Card> mutableCards, final List<Card> constCards ) {
List<Card> copyRun = new ArrayList<Card>(constCards);
ListIterator<Card> cardsIterator = copyRun.listIterator();
while(cardsIterator.nextIndex() < copyRun.size() && mutableCards.size() >= 0) {
int potentialmatch = cardsIterator.nextIndex();
if(mutableCards.contains(run.get(potentialmatch))) {
mutableCards.remove(potentialmatch);
copyRun.remove(potentialmatch);
cardsIterator = copyRun.listIterator();
}
else
cardsIterator.next();
}
return mutableCards;
} |
314b06f1-ac67-4fa4-a0c3-0607a93429ac | 0 | public CtrlConnexion getCtrl() {
return ctrl;
} |
81b439c0-0595-4a17-8a7b-a62c335aadcb | 9 | static final void method2165(boolean bool, String string) {
anInt6287++;
if (string != null) {
if (string.startsWith("*"))
string = string.substring(1);
String string_0_ = Class285_Sub1.unformatUsername(string);
if (string_0_ != null) {
for (int i = 0;
((i ^ 0xffffffff)
> (Class348_Sub40_Sub30.friendListLength ^ 0xffffffff));
i++) {
String string_1_ = Class83.friendListUsernames[i];
if (string_1_.startsWith("*"))
string_1_ = string_1_.substring(1);
string_1_ = Class285_Sub1.unformatUsername(string_1_);
if (string_1_ != null && string_1_.equals(string_0_)) {
Class348_Sub40_Sub30.friendListLength--;
for (int i_2_ = i;
i_2_ < Class348_Sub40_Sub30.friendListLength; i_2_++) {
Class83.friendListUsernames[i_2_]
= Class83.friendListUsernames[i_2_ - -1];
Class286_Sub2.friendListGamenames[i_2_]
= Class286_Sub2.friendListGamenames[1 + i_2_];
AbstractToolkit.anIntArray4578[i_2_]
= AbstractToolkit.anIntArray4578[i_2_ - -1];
Class285.clanChatWorld[i_2_]
= Class285.clanChatWorld[1 + i_2_];
Class172.clanChatRanking[i_2_]
= Class172.clanChatRanking[i_2_ - -1];
Class122.aBooleanArray1806[i_2_]
= Class122.aBooleanArray1806[1 + i_2_];
}
Class126.anInt4985 = LoadingHandler.anInt3918;
Class348_Sub42_Sub7.anInt9540++;
BufferedPacket class348_sub47
= Class286_Sub3.createBufferedPacket(Class357.aClass351_4394,
(Class348_Sub23_Sub2
.outgoingGameIsaac));
((BufferedPacket) class348_sub47)
.buffer.putByte
(Class239_Sub6.getStringLength(string, -65));
((BufferedPacket) class348_sub47)
.buffer
.putJStr((byte) -5, string);
Class348_Sub42_Sub14.queuePacket(117, class348_sub47);
break;
}
}
if (bool != true)
aBoolean6289 = true;
}
}
} |
26f15081-b7d6-479b-8610-901f69b43371 | 3 | public void delAll(String path)
{
File file = new File(path);
if (file.isFile() || (file.list().length == 0)) {
file.delete();
} else {
String[] files = file.list();
for (String f : files) {
System.out.println(file.getPath());
delAll((file.getPath()) + File.separator + f);
new File((file.getPath()) + File.separator + f).delete();
}
}
} |
6560bc88-2e19-43c1-99b6-2ccd7509870f | 9 | public ArrayList<HashMap<List<Integer>, HashSet<Integer>>> lshBucketA(HashMap<Integer, ArrayList<Integer>> sigList, HashMap<Integer, ArrayList<Integer>> semanList) {
ArrayList<HashMap<List<Integer>, HashSet<Integer>>> lshBuckets = lshBucket(sigList);
for (int j = 0; j < lshBuckets.size(); j++) {
HashMap<List<Integer>, HashSet<Integer>> newlshBucket = new HashMap<>();
for (List<Integer> sigs : lshBuckets.get(j).keySet()) {
List<Integer> temp = CollectionOperator.deepCopy(sigs);
HashSet<Integer> block = lshBuckets.get(j).get(sigs);
ArrayList<HashSet<Integer>> setList = new ArrayList<>();
for (int i = 0; i < n; i++) {
setList.add(new HashSet<Integer>());
}
for (int record : block) {
for (int i = 0; i < n; i++) {
if (semanList.get(record).get(i) == 1) {
setList.get(i).add(record);
}
}
}
HashSet<HashSet<Integer>> setSet = new HashSet<>(setList);
ArrayList<HashSet<Integer>> pureSetList = new ArrayList<>();
for (HashSet<Integer> set : setSet) {
if (!set.isEmpty()) {
pureSetList.add(set);
}
}
for (int i = 0; i < pureSetList.size(); i++) {
temp.add(i);
List<Integer> temptemp=CollectionOperator.deepCopy(temp);
newlshBucket.put(temptemp, pureSetList.get(i));
}
}
lshBuckets.set(j, newlshBucket);
// for(List<Integer> key:lshBuckets.get(j).keySet()){
// System.out.println(lshBuckets.get(j).get(key));
// }
}
return lshBuckets;
} |
c4031099-312b-425c-a3f8-085675877918 | 0 | public Being split() {
dynamicStats.get(StatType.D_EATEN).addToValue(-30.0);
return new CellCreature(new Point3(pos), constStats, childDynamicStats.clone(), classID);
} |
ea7ae33b-7fb7-414e-a580-8dcd95d05449 | 5 | public void save(){
if(this.getId() != null){
String q = "SELECT id, name " +
"FROM positions " +
"WHERE id = ?";
try {
PreparedStatement statement = Speciality.getConnection().prepareStatement(q,
ResultSet.TYPE_FORWARD_ONLY,
ResultSet.CONCUR_UPDATABLE);
statement.setInt(1, this.getId());
ResultSet resultSet = statement.executeQuery();
if(resultSet.next()){
resultSet.updateString("name", this.getName());
resultSet.updateRow();
}
} catch (SQLException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
} else {
String q = "INSERT INTO positions (name) " +
"VALUES (?)";
try {
PreparedStatement statement = Speciality.getConnection().prepareStatement(q,
Statement.RETURN_GENERATED_KEYS);
statement.setString(1, this.getName());
statement.executeUpdate();
ResultSet resultSet = statement.getGeneratedKeys();
if(resultSet.next()){
this.setId(resultSet.getInt(1));
}
} catch (SQLException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
} |
1c29b9f6-6904-42a7-b2e0-6128b3376bb9 | 3 | private void printLet(Node t, int n)
{
if (t.getCdr().isNull())
{
t.getCar().print(n+4, false);
System.out.println();
if (n > 0)
{
for (int i = 0; i < n; i++)
System.out.print(" ");
}
t.getCdr().print(n+4, true);
return;
}
t.getCar().print(n+4, false);
System.out.println();
printLet(t.getCdr(), n);
} |
9d968eb1-51f1-4f64-b8fd-058c2a0144e4 | 0 | public void add(
int i,
String name,
String find,
String replace,
boolean ignoreCase,
boolean regExp
) {
addName(i,name);
addFind(i,find);
addReplace(i,replace);
addIgnoreCase(i,ignoreCase);
addRegExp(i,regExp);
} |
2f462cac-b9dc-429a-b1d7-c71bb8fe6bf6 | 9 | private long readLong()
{
switch ( type )
{
case MatDataTypes.miUINT8:
return (long)( buf.get() & 0xFF);
case MatDataTypes.miINT8:
return (long) buf.get();
case MatDataTypes.miUINT16:
return (long)( buf.getShort() & 0xFFFF);
case MatDataTypes.miINT16:
return (long) buf.getShort();
case MatDataTypes.miUINT32:
return (long)( buf.getInt() & 0xFFFFFFFF);
case MatDataTypes.miINT32:
return (long) buf.getInt();
case MatDataTypes.miUINT64:
return (long) buf.getLong();
case MatDataTypes.miINT64:
return (long) buf.getLong();
case MatDataTypes.miDOUBLE:
return (long) buf.getDouble();
default:
throw new IllegalArgumentException("Unknown data type: " + type);
}
} |
acec542f-ac3c-4535-ba21-ffa5e17e7ac8 | 2 | private int checkInteger(String integer) throws Exception {
try {
int res = Integer.parseInt(integer);
if(res<0)
throw new Exception("Valeur négative interdite");
return res;
} catch (NumberFormatException e) {
throw new Exception("Champ numerique non valide");
} // Integer.parseInt
} |
fc1bd67e-f5e5-4796-baf0-458a5228bb55 | 4 | public void setFieldValue(FieldAccessCommand fac, Object value) throws Throwable {
Object object = ObjectResolver.resolveObjectReference(fac.getObjectName());
System.out.println("Found Object: " + object);
Field field = null;
try {
field = object.getClass().getField(fac.getMemberName());
} catch (Exception ex) {
Field[] fields = object.getClass().getDeclaredFields();
for (Field field1 : fields) {
if (field1.getName().contentEquals(fac.getMemberName())) {
field = field1;
field.setAccessible(true);
break;
}
}
}
if (field != null) {
field.set(object, value);
} else {
throw new Exception("Unable to find field " + fac.getMemberName() + " in object " + fac.getObjectName());
}
} |
5735734e-5e54-4bc3-b3cf-00d8b2c1a7c7 | 9 | public Object getValueAt(int rowIndex, int column) {
if (rowIndex >= hits.size()) {
// Feature row
CDDFeature feature = features.get(rowIndex-hits.size());
switch (column) {
case 0:
return feature.getAccession();
case 1:
return feature.getFeatureType()+" feature";
case 2:
return feature.getFeatureSite();
case 3:
return shown.get(rowIndex);
}
} else {
// Hits row
CDDHit hit = hits.get(rowIndex);
switch (column) {
case 0:
return "<html>"+NetUtils.makeCDDLink(hit.getName(), hit.getAccession())+"</html>";
case 1:
return hit.getHitType()+" domain";
case 2:
return ""+hit.getFrom()+"-"+hit.getTo();
case 3:
return shown.get(rowIndex);
}
}
return null;
} |
59d2fd7a-49e0-480c-bcd4-5c2d9e063887 | 1 | public String taulukkoTulostusmuotoon(String[] taulukko){
String palautettava = "";
for (int i = 0; i < taulukko.length; i++) {
palautettava += taulukko[i] + "\t";
}
return palautettava.substring(0, palautettava.length()-1);
} |
356eabf8-70df-45e6-bc2d-b599928671e1 | 2 | public void testGetField() {
YearMonth test = new YearMonth(COPTIC_PARIS);
assertSame(COPTIC_UTC.year(), test.getField(0));
assertSame(COPTIC_UTC.monthOfYear(), test.getField(1));
try {
test.getField(-1);
} catch (IndexOutOfBoundsException ex) {}
try {
test.getField(2);
} catch (IndexOutOfBoundsException ex) {}
} |
5fa85824-174c-4656-bbfc-4c085c22b608 | 3 | public void collision(PhysicsCollisionEvent event) {
System.out.println("Ghosty Collision impulse is "+event.getAppliedImpulse());
if (event.getObjectA() == this || event.getObjectB() == this){
if(event.getAppliedImpulse()>50){
playHitSound(event.getPositionWorldOnA(),event.getAppliedImpulse()*2);
//playHitSound(Vector3f.ZERO, mass);
}
}
} |
6bfeeed1-6270-4310-8c78-af0bbcd4d31f | 3 | public static RelatedToEnumeration fromString(String v) {
if (v != null) {
for (RelatedToEnumeration c : RelatedToEnumeration.values()) {
if (v.equalsIgnoreCase(c.toString())) {
return c;
}
}
}
throw new IllegalArgumentException(v);
} |
5c34629c-48da-4a9b-9266-e4d76e3a23bf | 6 | public Integer getValue(int x, int y, int z)
{
VariableResolver resolver = this.resolver.clone();
for (Enumeration<String> e = modifiers.keys(); e.hasMoreElements();)
{
String key = e.nextElement();
resolver.setVariable(key, modifiers.get(key).getValue(x, y, z));
}
resolver.setVariable("xPos", x);
resolver.setVariable("yPos", y);
resolver.setVariable("zPos", z);
if (assignments != null)
{
for (Assignment assignment : assignments)
{
assignment.evaluate(rng, resolver);
}
}
for (int i = 0; i < drawConstraints.size(); i++)
{
if (drawConstraints.get(i) == null || drawConstraints.get(i).evaluate(rng, resolver).intValue() != 0)
{
return typeIDs.get(i);
}
}
return null;
} |
4270e8cb-2f3d-4732-ba83-80af7223b0dd | 6 | public synchronized void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals(BUTTON_NEW_GAME)) {
if (JOptionPane.showConfirmDialog(view,
"Start a new game of the current size?",
"New Game?",
JOptionPane.OK_CANCEL_OPTION) == JOptionPane.OK_OPTION) {
System.out.println(e);
view.removeController(); // This is going to take a while.
board = new JManBoard();
view.addController(this);
view.repaint(); // Repaint the board & exit handler
return;
}
}
/** Set field nextJManDirection to the direction in which JMan should move.
* It should be one of the JManBoard constants MOVE_UP, MOVE_DOWN,
* MOVE_LEFT, or MOVE_RIGHT */
if (e.getActionCommand().equals(BUTTON_UP)) {
board.changeJManDirection(JManBoard.MOVE_UP);
} else if (e.getActionCommand().equals(BUTTON_DOWN)) {
board.changeJManDirection(JManBoard.MOVE_DOWN);
} else if (e.getActionCommand().equals(BUTTON_LEFT)) {
board.changeJManDirection(JManBoard.MOVE_LEFT);
} else if (e.getActionCommand().equals(BUTTON_RIGHT)) {
board.changeJManDirection(JManBoard.MOVE_RIGHT);
} else {
throw new RuntimeException("Unknown button pressed in Application J*Man");
}
board.act(); // Move the computer controller pieces.
view.repaint(); // Redisplay for the user.
} |
3d6e788a-984b-4c30-9ec5-e0dd15e84f92 | 4 | public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
UsermanForm usermanForm = (UsermanForm) form;// TODO Auto-generated method stub
String output ="doneedit";
String login = usermanForm.getLogin();
String password = usermanForm.getPassword();
String name = usermanForm.getName();
String surname = usermanForm.getSurname();
String title = usermanForm.getTitle();
String address = usermanForm.getAddress();
String mailpass = usermanForm.getMailpass();
String right = usermanForm.getRight();
String man = usermanForm.getMan();
Logger log = Logger.getLogger(TextAction.class);
PrivilegeDAO pridao = new PrivilegeDAO();
Privilege pri = new Privilege();
CompteDAO codao = new CompteDAO();
Compte comp = codao.findById(login);
if (right.equals("super"))
pri= pridao.findById((long) 3);
else if (right.equals("admin"))
pri= pridao.findById((long) 2);
else
pri= pridao.findById((long) 2);
if (man.contains("Add")){
comp.setPrivilege(pri);
comp.setLogin(login);
comp.setPassword(password);
comp.setNom(surname);
comp.setPrenom(name);
comp.setTitre(title);
comp.setAdresseMail(address);
comp.setMailpassword(mailpass);
Session hsf = HibernateSessionFactory.getSession();
Transaction trans = hsf.beginTransaction();
hsf.saveOrUpdate(comp);
trans.commit();
hsf.close();
request.getSession().setAttribute("info", "User has been added.");
log.info("User " + comp.getLogin() + " has been added.");
output ="doneadd";
}
else if (man.contains("Save")){
comp = codao.findById(login);
comp.setPrivilege(pri);
comp.setPassword(password);
comp.setNom(surname);
comp.setPrenom(name);
comp.setTitre(title);
comp.setAdresseMail(address);
comp.setMailpassword(mailpass);
Session hsf = HibernateSessionFactory.getSession();
Transaction trans = hsf.beginTransaction();
hsf.saveOrUpdate(comp);
trans.commit();
hsf.close();
request.getSession().setAttribute("info", "User has been modified.");
log.info("User " + comp.getLogin() + " has been modified.");
output ="doneedit";
}
return mapping.findForward(output);
} |
76adfca2-0c8d-4a00-ba6e-22369eafe08d | 7 | public void draw(Graphics g) {
towerFrame.draw(g);
barrelCell.draw(g);
ammoCell.draw(g);
baseCell.draw(g);
/*************************
*** Taarn og knapper ****
*************************/
for(int i = 0; i < towerButtons.size(); i++){
if(i == activeTowerIndex)g.setColor(Colors.red);
else if(towerButtons.get(i).contains(Screen.CURSOR))g.setColor(Colors.transparentRed);
else g.setColor(Colors.transparentBlack);
Rectangle towerButton = towerButtons.get(i);
g.fillRect(towerButton.x, towerButton.y, towerButton.width, towerButton.height);
GameData.modelTowers.get(i).drawButton(g, towerButton);
}
if(newTower != null){
if(newTower.contains(Screen.CURSOR))g.setColor(Colors.red);
else g.setColor(Colors.transparentRed);
g.fillRect(newTower.x, newTower.y, newTower.width, newTower.height);
g.drawImage(Tilesets.button_tileset[GameData.newTower], newTower.x, newTower.y, newTower.width, newTower.height, null);
}
if(goToBoard.contains(Screen.CURSOR))g.setColor(Colors.red);
else g.setColor(Colors.transparentRed);
g.fillRect(goToBoard.x, goToBoard.y, goToBoard.width, goToBoard.height);
g.drawImage(Tilesets.button_tileset[GameData.goToBoard], goToBoard.x, goToBoard.y, goToBoard.width, goToBoard.height, null);
// Liste, hvis det trengs
if(componentList != null)componentList.draw(g);
} |
0ee60bb2-d535-47be-9ae5-741ccf8327e1 | 4 | public void update(float dt) {
music.update(dt);
if (tempSong)
prevSong.update(dt);
Array<Song> rmv = new Array<>();
for (Song s : songsToKill) {
s.update(dt);
if (!s.fading)
rmv.add(s);
}
songsToKill.removeAll(rmv, false);
if(!menus.isEmpty())
menus.peek().update(dt);
} |
36c48f68-ca76-4f15-a902-24fa5314ef0e | 5 | @Override
public boolean onCommand(final CommandSender sender, final Command command, final String label, final String[] args) {
if (args.length == 0) {
Main.courier.send(sender, "requires-argument", "message", 0);
return false;
}
final String text = Edit.join(args, " ");
if (text == null) return false;
final long submitted = System.currentTimeMillis();
final String from = ( sender instanceof Player ? ((Player) sender).getDisplayName() : Main.courier.format("+console", sender.getName()) );
this.records.edit(submitted, from, ChatColor.translateAlternateColorCodes('&', text));
this.doorman.clearLast();
for (final Player player : Bukkit.getOnlinePlayers()) {
Main.courier.submit(RecipientList.Sender.create(player), this.records.declare(player));
this.doorman.updateLast(player.getName());
}
if (!(sender instanceof Player)) {
Main.courier.submit(RecipientList.Sender.create(sender), this.records.declare(sender));
this.doorman.updateLast(sender.getName());
}
return true;
} |
6e22b012-a5b5-482a-be37-9457daf62543 | 8 | public void setupOverlay(Hashtable<String, Connection> connections)
{
//add all nodes to graph
addNodesToGraph(connections);
List<Connection> connList = new ArrayList<Connection>(connections.values());
//first iteration
for(int i = 0; i < connList.size(); ++ i)
{
int destinationIndex;
if(i == connList.size() - 1) //if this is the last node
{
destinationIndex = 0; //sets to first node
}else
{
destinationIndex = i + 1;
}
//create request and specify random link weight
int linkWeight = (int)(1 + Math.random() * (10));
LinkRequest linkRequest = new LinkRequest(connList.get(destinationIndex).getIP(), connList.get(destinationIndex).getListeningPort(), linkWeight);
//add edge to graph
System.out.println(connList.get(i).getIP() + connList.get(i).getPort());
Vertex source = _graph.getVertex(connList.get(i).getIP(), connList.get(i).getPort());
System.out.println("Source: " + source);
System.out.println(connList.get(destinationIndex).getIP() + connList.get(destinationIndex).getPort());
Vertex destination = _graph.getVertex(connList.get(destinationIndex).getIP(), connList.get(destinationIndex).getPort());
System.out.println("Dest: " + destination);
_graph.addEdge(new Edge(source, destination, linkWeight));
//send data
try
{
connList.get(i).sendData(linkRequest.getBytes());
TimeUnit.MILLISECONDS.sleep(20);
}catch(IOException ioe)
{
ioe.printStackTrace();
}catch(InterruptedException ie)
{
ie.printStackTrace();
}
}
//second iteration
for(int i = 0; i < connList.size(); ++ i)
{
int destinationIndex;
if(i == connList.size() - 2) //if this is the second to last node
{
destinationIndex = 0;
}else if(i == connList.size() - 1) //if this is the last node
{
destinationIndex = 1; //sets to first node
}else
{
destinationIndex = i + 2;
}
//create request and specify random link weight
int linkWeight = (int)(1 + Math.random() * (10));
LinkRequest linkRequest = new LinkRequest(connList.get(destinationIndex).getIP(), connList.get(destinationIndex).getListeningPort(), linkWeight);
//add edge to graph
Vertex source = _graph.getVertex(connList.get(i).getIP(), connList.get(i).getPort());
Vertex destination = _graph.getVertex(connList.get(destinationIndex).getIP(), connList.get(destinationIndex).getPort());
_graph.addEdge(new Edge(source, destination, linkWeight));
//send data
try
{
connList.get(i).sendData(linkRequest.getBytes());
}catch(IOException ioe)
{
ioe.printStackTrace();
}
}
} |
99dafce0-70cf-42e7-bb74-05fd2c47f449 | 5 | public String interpreterWeatherCondition(String conditionRating){
String weatherCondition = "";
switch (conditionRating){
case "0.0":
weatherCondition = "veryBad";
break;
case "0.25":
weatherCondition = "bad";
break;
case "0.5":
weatherCondition = "ok";
break;
case "0.75":
weatherCondition = "good";
break;
case "1.0":
weatherCondition = "veryGood";
break;
default:
weatherCondition = "ok";
break;
}
return weatherCondition;
} |
cee1ec5b-2e2e-4ee3-8ac5-1151780a6ef2 | 5 | private static void deleteFile(File file) {
if (file == null || !file.exists()) {
return;
}
// 单文件
if (!file.isDirectory()) {
boolean delFlag = file.delete();
if (!delFlag) {
throw new RuntimeException(file.getPath() + "删除失败!");
} else {
return;
}
}
// 删除子目录
for (File child : file.listFiles()) {
deleteFile(child);
}
// 删除自己
file.delete();
} |
7588f8fd-4727-4e96-b1c5-c071a32c256c | 2 | public void doGet(HttpServletRequest request, HttpServletResponse response) {
response.setContentType("text/html");//设置服务器响应的内容格式
// response.setCharacterEncoding("gb2312");//设置服务器响应的字符编码格式。
DButil ab = new DButil();
try {
PrintWriter pw = response.getWriter();
String tep=new String(request.getParameter("tid").getBytes("ISO-8859-1"));
// String name = new String(request.getParameter("name").getBytes("ISO-8859-1"));//能显示中文
int id=Integer.valueOf(tep);
System.out.println("delete id"+id);
if(ab.deletestudent(id)) {
request.getRequestDispatcher("succ.jsp?info='delete success'").forward(request, response);
}
} catch (Exception e) {
}
} |
fb7ab612-7469-43ea-bf97-d248e374e49f | 8 | private void detectEncoding( char[] cbuf, int off, int len )
throws IOException
{
int size = len;
StringBuffer xmlProlog = xmlPrologWriter.getBuffer();
if ( xmlProlog.length() + len > BUFFER_SIZE )
{
size = BUFFER_SIZE - xmlProlog.length();
}
xmlPrologWriter.write( cbuf, off, size );
// try to determine encoding
if ( xmlProlog.length() >= 5 )
{
if ( xmlProlog.substring( 0, 5 ).equals( "<?xml" ) )
{
// try to extract encoding from XML prolog
int xmlPrologEnd = xmlProlog.indexOf( "?>" );
if ( xmlPrologEnd > 0 )
{
// ok, full XML prolog written: let's extract encoding
Matcher m = ENCODING_PATTERN.matcher( xmlProlog.substring( 0, xmlPrologEnd ) );
if ( m.find() )
{
encoding = m.group( 1 ).toUpperCase( Locale.ENGLISH );
encoding = encoding.substring( 1, encoding.length() - 1 );
}
else
{
// no encoding found in XML prolog: using default encoding
encoding = "UTF-8";
}
}
else
{
if ( xmlProlog.length() >= BUFFER_SIZE )
{
// no encoding found in first characters: using default encoding
encoding = "UTF-8";
}
}
}
else
{
// no XML prolog: using default encoding
encoding = "UTF-8";
}
if ( encoding != null )
{
// encoding has been chosen: let's do it
xmlPrologWriter = null;
writer = new OutputStreamWriter( out, encoding );
writer.write( xmlProlog.toString() );
if ( len > size )
{
writer.write( cbuf, off + size, len - size );
}
}
}
} |
2a8ecea5-08a1-4957-9bb3-4152e8defe0a | 6 | public static void main(String[] args) throws IOException, FileNotFoundException{
long startTime = System.currentTimeMillis();
BufferedReader br = new BufferedReader(new FileReader("knapsack_big.txt"));
String[] split = br.readLine().trim().split("(\\s)+");
int weightCapacity = Integer.parseInt(split[0]);
int numItem = Integer.parseInt(split[1]);
int[] valueArray = new int[numItem+1];
int[] weightArray = new int[numItem+1];
int kk = 1;
String line;
while((line = br.readLine())!=null){
split = line.trim().split("(\\s)+");
valueArray[kk] = Integer.parseInt(split[0]);
weightArray[kk] = Integer.parseInt(split[1]);
kk++;
}
br.close(); // done with reading
int[][] knapsackMatrix = new int[2][weightCapacity+1];
for(int i = 0; i <= weightCapacity; i++){
knapsackMatrix[0][i] = 0;
}
for (int i = 0; i < numItem; i++){
for(int x = 0; x <= weightCapacity; x++){
int j = 0;
if (x < weightArray[i]){
knapsackMatrix[1][x] = knapsackMatrix[j][x];
}else{
knapsackMatrix[1][x] = Math.max(knapsackMatrix[j][x], knapsackMatrix[j][x-weightArray[i]]+valueArray[i]);
}
} // end of x loop
//cache knapsackMatrix[1] to knapsackMatrix[0] for next i loop
for(int k = 0; k <= weightCapacity;k++)
knapsackMatrix[0][k] = knapsackMatrix[1][k];
}
long stopTime = System.currentTimeMillis();
System.out.println("running time: " + (stopTime-startTime));
System.out.println(knapsackMatrix[1][weightCapacity]);
} |
62b1b5bd-e254-477e-8ec3-dec63a15b1a8 | 0 | public Chlodzenie produkujemyChlodzenie(){
return new ChlodzenieDlaLaptopa();
} |
2340341c-4e40-4229-a3c1-e1c44af77625 | 0 | public int getNeedReport() {
return NeedReport;
} |
43a9b221-fc4b-49a3-a28a-eb4b8b6f4154 | 3 | public static TreeNode commomAncestorWithBinaryTreeHasParent(TreeNode p,TreeNode q){
Map<TreeNode,Boolean> ancestorPath = new HashMap<TreeNode,Boolean>();
while(p.parent != null){
ancestorPath.put(p, true);
p = p.parent;
}
while(q.parent != null){
if(ancestorPath.get(q)){
return q;
}
q = q.parent;
}
return null;
} |
42b28b76-9d2c-4c40-bde9-6865a2e165d6 | 7 | public static ReplicationResult SendAndRecv2(HttpClient client,
ContentExchange exchange) throws BookStoreException {
int exchangeState;
try {
client.send(exchange);
} catch (IOException ex) {
throw new BookStoreException(
BookStoreClientConstants.strERR_CLIENT_REQUEST_SENDING, ex);
}
try {
exchangeState = exchange.waitForDone(); // block until the response
// is available
} catch (InterruptedException ex) {
throw new BookStoreException(
BookStoreClientConstants.strERR_CLIENT_REQUEST_SENDING, ex);
}
if (exchangeState == HttpExchange.STATUS_COMPLETED) {
try {
ReplicationResult bookStoreResponse = (ReplicationResult) BookStoreUtility
.deserializeXMLStringToObject(exchange
.getResponseContent().trim());
if (bookStoreResponse == null) {
throw new BookStoreException(
BookStoreClientConstants.strERR_CLIENT_RESPONSE_DECODING);
}
/*//In case a replication was not successful
boolean succesfull = bookStoreResponse.isReplicationSuccessful();
if (!succesfull) {
return null;
*/
return bookStoreResponse;
} catch (UnsupportedEncodingException ex) {
throw new BookStoreException(
BookStoreClientConstants.strERR_CLIENT_RESPONSE_DECODING,
ex);
}
} else if (exchangeState == HttpExchange.STATUS_EXCEPTED) {
throw new BookStoreException(
BookStoreClientConstants.strERR_CLIENT_REQUEST_EXCEPTION);
} else if (exchangeState == HttpExchange.STATUS_EXPIRED) {
throw new BookStoreException(
BookStoreClientConstants.strERR_CLIENT_REQUEST_TIMEOUT);
} else {
throw new BookStoreException(
BookStoreClientConstants.strERR_CLIENT_UNKNOWN);
}
} |
6f4d5432-1be1-4242-8ccf-281cdfec626e | 9 | public static void parseAndRegister(Node convertorsNode) {
NodeList nodeList = convertorsNode.getChildNodes();
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
if ("convertor".equals(node.getNodeName())) {
Node aliasNode = node.getAttributes().getNamedItem("alias");
Node clazzNode = node.getAttributes().getNamedItem("class");
Node srcClassNode = node.getAttributes().getNamedItem("srcClass");
Node targetClassNode = node.getAttributes().getNamedItem("targetClass");
if (clazzNode != null) {
Class clazz = ReflectionHelper.forName(clazzNode.getNodeValue());
if (!Convertor.class.isAssignableFrom(clazz)) { // 检查下必须为Convertor的子类
throw new BeanMappingException(clazz.toString() + " is not implements Convertor");
}
Convertor convertor = (Convertor) ReflectionHelper.newInstance(clazz);
if (aliasNode != null) {
// 注册为别名
String alias = aliasNode.getNodeValue();
ConvertorHelper.getInstance().registerConvertor(alias, convertor);
if (logger.isDebugEnabled()) {
logger.debug("register Convertor[" + clazz.toString() + "] to alias[" + alias + "]");
}
} else {
String srcClass = srcClassNode.getNodeValue();
String targetClass = targetClassNode.getNodeValue();
if (StringUtils.isEmpty(srcClass) || StringUtils.isEmpty(targetClass)) {
throw new BeanMappingException(clazz.toString() + " should fix srcClass and targetClass!");
}
Class srcClazz = ReflectionHelper.forName(srcClassNode.getNodeValue());
Class targetClazz = ReflectionHelper.forName(targetClassNode.getNodeValue());
// 根据srcClass/targetClass进行自动匹配
ConvertorHelper.getInstance().registerConvertor(srcClazz, targetClazz, convertor);
if (logger.isDebugEnabled()) {
logger.debug("register Convertor[" + clazz.toString() + "] used by srcClass["
+ srcClass.toString() + "]" + " targetClass[" + targetClass.toString() + "]");
}
}
}
}
}
} |
3fe05df6-a915-4858-86bb-405d95afac3b | 8 | public static byte[] B64tobyte(String ec) {
String dc = "";
int k = -1;
while (k < (ec.length() - 1)) {
int right = 0;
int left = 0;
int v = 0;
int w = 0;
int z = 0;
for (int i = 0; i < 6; i++) {
k++;
v = B64.indexOf(ec.charAt(k));
right |= v << (i * 6);
}
for (int i = 0; i < 6; i++) {
k++;
v = B64.indexOf(ec.charAt(k));
left |= v << (i * 6);
}
for (int i = 0; i < 4; i++) {
w = ((left & (0xFF << ((3 - i) * 8))));
z = w >> ((3 - i) * 8);
if(z < 0) {z = z + 256;}
dc += (char)z;
}
for (int i = 0; i < 4; i++) {
w = ((right & (0xFF << ((3 - i) * 8))));
z = w >> ((3 - i) * 8);
if(z < 0) {z = z + 256;}
dc += (char)z;
}
}
byte[] Result = new byte[1024];
try {
// Force the encoding result string
Result = dc.getBytes("8859_1");
} catch (UnsupportedEncodingException e) {e.printStackTrace();}
return Result;
} |
24e405ea-e493-4888-936f-56d272fd81e1 | 6 | public void loadCenter(FileSystem fs, Path path, Configuration conf){
SequenceFile.Reader reader ;
try {
reader = new SequenceFile.Reader(fs, path, conf);
IntWritable key = (IntWritable) reader.getKeyClass().newInstance();
FloatArrayWritable value = (FloatArrayWritable) reader.getValueClass().newInstance();
while(reader.next(key, value)) {
//System.out.println("key="+key.toString()+"value"+value.toString());
int centerId = key.get();
chkCenter[centerId] = true;
FloatWritable[] vect = (FloatWritable[]) value.toArray();
for(int i=0; i<10; i++) {
centers[centerId][i]=vect[i].get();
}
}
//generate new center for empty ones
for(int i =0 ;i<Constant.NFLIX_K;i++) {
if(!chkCenter[i]) {
for(int j=0; j<10;j++) {
float fet = (float) (-1+Kmath.getRandom()*2);
centers[i][j]=fet;
}
}
}
reader.close();
} catch(Exception e) {
System.out.println("WARNING: No "+path.toString()+":Couldn't read cache file:"+e.toString());
}
} |
cb284547-297b-4191-8377-397fe3df4812 | 9 | public static void main(String[] args) {
Scanner input = new Scanner( System.in );
int num1 = 0;
int num2 = 0;
int num3 = 0;
int sum = 0;
int product = 0;
int average = 0;
int smallest = 0;
int largest = 0;
System.out.print( "Please enter first integer: ");
num1 = input.nextInt();
System.out.print( "Please enter second integer: ");
num2 = input.nextInt();
System.out.print( "Please enter third integer: ");
num3 = input.nextInt();
sum = num1 + num2 + num3;
product = num1 * num2 * num3;
average = sum / 3;
if ( num1 > num2 && num1 > num3 ) {
largest = num1;
if ( num2 < num3 ) {
smallest = num2;
}
else {
smallest = num3;
}
}
else if ( num2 > num1 && num2 > num3 ) {
largest = num2;
if ( num1 < num3 ){
smallest = num1;
}
else {
smallest = num3;
}
}
else if ( num3 > num1 && num3 > num2 ) {
largest = num3;
if ( num1 < num2 ){
smallest = num1;
}
else {
smallest = num2;
}
}
System.out.printf( "Sum: %d\nProduct: %d\nAverage: %d\nLargest: %d\nSmallest: %d", sum, product, average, largest, smallest);
} |
d47a521b-7846-46ad-a4b9-7152aaa3a0b0 | 9 | public void putchar(ArrayList<String> ret,char c){
if(c=='1'){
ret.add("");
}
else if(c=='2'){
ret.add("a");
ret.add("b");
ret.add("c");
}
else if(c=='3'){
ret.add("d");
ret.add("e");
ret.add("f");
}
else if(c=='4'){
ret.add("g");
ret.add("h");
ret.add("i");
}
else if(c=='5'){
ret.add("j");
ret.add("k");
ret.add("l");
}
else if(c=='6'){
ret.add("m");
ret.add("n");
ret.add("o");
}
else if(c=='7'){
ret.add("p");
ret.add("q");
ret.add("r");
ret.add("s");
}
else if(c=='8'){
ret.add("t");
ret.add("u");
ret.add("v");
}
else if(c=='9'){
ret.add("w");
ret.add("x");
ret.add("y");
ret.add("z");
}
} |
4ee75090-7b1c-4b2d-9699-9d072fab28e2 | 4 | private boolean isDisplayModeAvailable(
int screenWidth, int screenHeight, int screenColorDepth ) {
DisplayMode[] displayModes = this.graphicsDevice.getDisplayModes();
for( DisplayMode mode : displayModes ) {
if( screenWidth == mode.getWidth() && screenHeight == mode.getHeight()
&& screenColorDepth == mode.getBitDepth() )
return true;
}
return false;
} |
a63858bf-e894-4865-b596-fabb5a249022 | 9 | @SuppressWarnings("unchecked")
private void createObjectReceiveServer() {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(Integer.parseInt(port));
while (true) {
byte[] data = readData(serverSocket);
//convert bytes from socket into an object
if ((data[0] == -84) && (data[1] == -19)) {
ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(data));
Object objectOut = ois.readObject();
//write object to the queue
if (objectOut != null && this.type.isAssignableFrom(objectOut.getClass())) {
//This cast is guaranteed because of the if statement above
q.put((T)objectOut);
}
}
}
}
catch (IOException ioe) {
ioe.printStackTrace();
}
catch (ClassNotFoundException cnfe) {
cnfe.printStackTrace();
}
finally {
if (serverSocket != null) {
try {
serverSocket.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
} |
f686b224-a0ca-46ee-aa31-a4deea34e80e | 8 | public static void main(String[] args) {
Watch.start();
int lim = 1_000_000;
boolean[] primeTable = Utils.primeTable(lim);
List<Integer> primes = new ArrayList<>();
for (int i = 0; i < lim; i++)
if (primeTable[i]) primes.add(i);
int maxLen = 0, s = 0, maxS = 0;
for (int end = 0; s < lim; end++, s += primes.get(end - 1))
if (primeTable[s]) {
maxLen = end;
maxS = s;
}
s = maxS - primes.get(0) + primes.get(maxLen);
for (int start = 1, end = maxLen; s < lim; start++, end++, s += primes.get(end) - primes.get(start - 1))
for (int newS = s, newEnd = end; newS < lim; newEnd++, newS += primes.get(newEnd))
if (primeTable[newS] && newEnd - start > maxLen) {
maxLen = newEnd - start;
maxS = newS;
}
System.out.println(maxS);
Watch.stop();
} |
b11691b0-54fc-427e-bbde-26930cdf512d | 5 | @EventHandler
public void onPlayerInteract(PlayerInteractEvent event)
{
Block block = event.getClickedBlock();
Player player = event.getPlayer();
if (!worldmanager.isHiddenWorld(player.getWorld()))
{
return;
}
if (event.getAction().equals(Action.RIGHT_CLICK_BLOCK)
&& (block.getType().equals(Material.SIGN)
|| block.getType().equals(Material.WALL_SIGN)
|| block.getType().equals(Material.SIGN_POST)))
{
BlockState state = block.getState();
Sign sign = ((Sign) state);
String[] signtext = sign.getLines();
signHandler.runSignClickHandler(event.getPlayer(), signtext);
}
} |
e2fd3a55-e840-4621-b8f7-c0ade4edccf7 | 8 | public static void main(String[] args) {
byte op = 0;
do{
System.out.print("\n\t***GESTION DE PRESTAMOS*\n1. Agregar Prestamos.\n" +
"2. Pagar cuota.\n3. Ver informacion de prestamo.\n4. Salir.\n" +
"Ingrese el numero de su opcion: ");
try{
op = lea.nextByte();
switch (op){
case 1:
agregarPrestamo();
break;
case 2:
pagarCuota();
break;
case 3:
infoPrestamo();
break;
case 4:
System.out.println("SALIENDO...");
break;
default:
System.out.println("Opcion invalida.");
}
}catch (LoanInvalidException lie){
System.out.println(lie.getMessage());
}catch (InputMismatchException ime){
System.out.println("Ingrese un entero por favor.");
lea.next();
}catch(Exception e){
System.out.println(e.getMessage());
e.printStackTrace();
}
}while (op != 4);
} |
55eeeb76-7d72-4af3-af94-f421056aa733 | 7 | public void run() {
Scanner scanner = new Scanner(System.in);
do {
if (level == null) {
if (scanner.hasNextLine()) {
level = scanner.nextLine();
}
message("Enter level: ");
level = scanner.nextLine();
}
program.init(level);
program.run(this);
Integer result = null;
while (result == null) {
if (scanner.hasNextLine()) {
String line = scanner.nextLine();
result = program.doLine(line);
} else {
result = 0;
}
}
message("Game over" + (result != 0 ? "" : ", no result") + "!");
if (result > 0) {
level = null;
}
message("Another go (true/false)?");
} while (scanner.nextBoolean());
scanner.close();
} |
a1d0f0c7-9df5-4d32-b0da-3307fa363a6b | 3 | public static boolean calcWaterNeeded(double playerGuess) {
boolean result;
if (playerGuess < 0 || playerGuess > 25) {
result = false;
} else {
int berrieEaten = (int) (Math.random() * 15);
System.out.println("Berries Eaten = " + berrieEaten);
double waterToDrink = (berrieEaten / 3) * 5;
System.out.println("Water to drink = " + waterToDrink);
if (waterToDrink == playerGuess) {
result = true;
} else {
result = false;
}
}
return result;
} |
35ede4b8-2a3d-4544-b80d-29db111778e2 | 1 | @Override
public void draw(FrameBuffer buffer) {
buffer.blit(texture, 0, 0, buffer.getOutputWidth() - x, y, width, height, widthDest, heightDest, 0, false);
for(String str : namePrimitives)
primitives.get(str).blit(buffer);
} |
8ea8bd5e-a43e-47f4-a573-fa2b911736db | 4 | @Override
public boolean importData(TransferHandler.TransferSupport dataInfo) {
if (!dataInfo.isDrop()) {
return false;
}
if (!dataInfo.isDataFlavorSupported(DataFlavor.stringFlavor)) {
return false;
}
JList list = (JList) dataInfo.getComponent();
DefaultListModel listModel = (DefaultListModel) list.getModel();
JList.DropLocation dropLocation = (JList.DropLocation) dataInfo.getDropLocation();
int index = dropLocation.getIndex();
indiceFinal = index;
boolean insert = dropLocation.isInsert();
Transferable transfer = dataInfo.getTransferable();
String datos;
try {
datos = (String) transfer.getTransferData(DataFlavor.stringFlavor);
} catch (UnsupportedFlavorException | IOException e) {
return false;
}
if (insert) {
listModel.add(index, datos);
} else {
listModel.set(index, datos);
}
return true;
} |
be8ea809-a5fa-492f-af86-a3c51f2789cb | 4 | @Override
public List<Bounty> getOwnBounties(String issuer) throws DataStorageException {
List<Bounty> bounties = new ArrayList<Bounty>();
Set<String> keys = this.config.getConfigurationSection("bounties").getKeys(false);
for (String key : keys) {
try {
int keyValue = Integer.valueOf(key);
ConfigurationSection section = config.getConfigurationSection("bounties").getConfigurationSection(key);
if (issuer.equalsIgnoreCase(section.getString("issuer")) && section.getString("hunter") == null) {
bounties.add(Bounty.fromConfigurationSection(keyValue, section));
}
} catch (NumberFormatException e) {
this.plugin.getLogger().warning("Picked up an invalid key at bounties." + key);
continue;
}
}
return bounties;
} |
6368f75f-4176-4d35-9fbf-a1a0e49ca4f2 | 7 | public static void q4(String[] args) throws Exception{
//Question 7.4: Write methods to implement the multiply, subtract, and divide
//operation for integers. Use only the add operator.
SOP("Running q4");
Scanner s = new Scanner(System.in);
SOP("Please Enter two numbers to perform computation on");
SOP2("Number 1: ");
int num1 = s.nextInt();
SOP2("Number 2: ");
int num2 = s.nextInt();
int option = -1;
while(option == -1){
SOP("");
SOP("========");
SOP("Please specify option");
SOP("1\tMultiply");
SOP("2\tSubtract");
SOP("3\tDivide");
SOP("");
SOP2("Option: ");
option = s.nextInt();
if(option != 1 && option != 2 && option != 3){
SOP("Invalid Option. Please Try again");
option = -1;
}
}
if(option == 1) SOP("\""+num1+"\" * \""+num2 +"\" = " + mMultiply(num1, num2));
else if(option == 2) SOP("\""+num1+"\" - \""+num2 +"\" = " + mSubtract(num1, num2));
else if(option == 3) SOP("\""+num1+"\" \\ \""+num2 +"\" = " + mDivide(num1, num2));
else {};
} |
3feb1bf3-d0fc-442c-9d64-92df369f4aa2 | 9 | public static Method[] getterMethodDrilldown(Class<?> type, String property)
throws NoSuchMethodException {
Class<?> innerClass = type;
Method method;
if (property.startsWith("./")) {
property = property.substring(2);
}
String[] path = property.split("[./]");
Method[] methods = new Method[path.length];
for (int p = 0; p < path.length; p++) {
if (path[p].indexOf('[') >= 0) {
method = innerClass.getMethod(
getter(path[p].substring(0, path[p].indexOf('['))), (Class<?>[]) null);
} else {
try {
method = innerClass.getMethod(getter(path[p]), (Class<?>[]) null);
} catch (NoSuchMethodException ex) {
method = innerClass.getMethod("is" + StringTool.capitalize(path[p]),
(Class<?>[]) null);
}
}
methods[p] = method;
innerClass = method.getReturnType();
}
return methods;
} |
a14cac34-3cac-421c-8ee2-50fcd2c1c721 | 9 | public List<Interval> merge(List<Interval> intervals) {
List<Interval> result = new ArrayList<Interval>();
if (intervals == null || intervals.size() == 0)
return result;
HashMap<Integer, Integer> processedIntervals = new HashMap<Integer, Integer>();
ArrayList<Integer> starts = new ArrayList<Integer>();
for (Interval interval : intervals) {
if (processedIntervals.containsKey(interval.start) == false)
starts.add(interval.start);
if (processedIntervals.containsKey(interval.start)
&& processedIntervals.get(interval.start) >= interval.end);
else
processedIntervals.put(interval.start, interval.end);
}
Integer[] startsArray = starts.toArray(new Integer[starts.size()]);
Arrays.sort(startsArray);
if (startsArray.length == 1) {
result.add(new Interval(startsArray[0], processedIntervals.get(startsArray[0])));
return result;
}
Interval tmp = new Interval(startsArray[0], processedIntervals.get(startsArray[0]));
for (int i = 1; i < startsArray.length; i ++) {
if (tmp.end >= startsArray[i])
tmp.end = Math.max(tmp.end, processedIntervals.get(startsArray[i]));
else {
result.add(tmp);
tmp = new Interval(startsArray[i], processedIntervals.get(startsArray[i]));
}
}
result.add(tmp);
return result;
} |
5108ea6e-e20d-4025-8397-f5531dd45168 | 1 | public String encodeFromFile( String rawfile )
{
byte[] ebytes = readFile( rawfile, ENCODE );
return ebytes == null ? null : new String( ebytes );
} // end encodeFromFile |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.