method_id stringlengths 36 36 | cyclomatic_complexity int32 0 9 | method_text stringlengths 14 410k |
|---|---|---|
5086bd59-7f8c-49b1-8697-f7c33c142677 | 4 | protected void updateLabeling(double slack) {
for (int w = 0; w < dim; w++) {
if (committedWorkers[w]) {
labelByWorker[w] += slack;
}
}
for (int j = 0; j < dim; j++) {
if (parentWorkerByCommittedJob[j] != -1) {
labelByJob[j] -= slack;
} else {
minSlackValueByJob[j] -= slack;
}
}
} |
374a1896-4e70-4280-96ee-c16b090c300b | 7 | public URL getAlias()
{
if (__checkAliases && !_aliasChecked)
{
try
{
String abs=_file.getAbsolutePath();
String can=_file.getCanonicalPath();
if (abs.length()!=can.length() || !abs.equals(can))
_alias=new File(can).toURI().toURL();
_aliasChecked=true;
if (_alias!=null && log.isDebugEnabled())
{
log.debug("ALIAS abs="+abs);
log.debug("ALIAS can="+can);
}
}
catch(Exception e)
{
log.warn(LogSupport.EXCEPTION,e);
return getURL();
}
}
return _alias;
} |
50934aa4-b862-4166-aee2-169547ed6969 | 8 | private static void createZip(File set) {
ZipOutputStream outputStream = null;
InputStream inputStream = null;
try {
ArrayList cards = new ArrayList();
for (final File card : set.listFiles()) {
cards.add(card);
}
File zipDir = new File(DeckFileHandler.getDatabaseFilePath() + "zips");
outputStream = new ZipOutputStream(new FileOutputStream(zipDir + "\\" + set.getName() + ".zip"));
ZipParameters parameters = new ZipParameters();
parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE); //deflate compression
parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_ULTRA);
parameters.setEncryptFiles(false); //no encryption
//loop
for (int i = 0; i < cards.size(); i++) {
File card = (File)cards.get(i);
outputStream.putNextEntry(card, parameters);
inputStream = new FileInputStream(card);
byte[] readBuff = new byte[4096];
int readLen = -1;
while ((readLen = inputStream.read(readBuff)) != -1) {
outputStream.write(readBuff, 0, readLen);
}
outputStream.closeEntry();
inputStream.close();
}
outputStream.finish();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
} |
b2940a94-6e36-40e0-ae1e-dbc79a64a895 | 8 | @Override
public void mouseClicked(final MouseEvent e) {
for (Map.Entry<Button.TYPE, Button> entry : buttons.entrySet()) {
if (entry.getValue().contains(e.getPoint())) {
processMouseClick(entry.getKey());
}
}
if (discardPlayer != null) {
Card best = null;
for (Map.Entry<Rectangle, Card> entry : cardPositions.entrySet()) {
if (entry.getKey().contains(e.getPoint())) {
best = entry.getValue();
}
}
if (best != null && discardPlayer.getPlayer().getCards().contains(best)) {
if (discards.contains(best)) {
discards.remove(best);
} else {
discards.add(best);
}
repaint();
}
}
} |
2f7998fa-b285-43ae-b0f9-8c666a8a75bd | 8 | public void generateSubSectorMeshForSector(GroupSector sector) {
clearMeshesOn(sector);
TriangleMesh mesh = new TriangleMesh("_mesh");
MeshNode meshDataNode = new MeshNode("_mesh", mesh);
sector.addChild(meshDataNode);
GeneralTriangle[] isfs;
boolean generated;
for (Direction d : Direction.values()) {
generated = false;
// if (foreignLinksInDirection(d, sector) == 0) {
//
// isfs = generateQuadFor(d, (SpaceRegion) sector);
//
// if (isfs != null) {
// for (GeneralTriangle isf : isfs) {
// sector.mesh.faces.add(isf);
// generated = true;
// }
// }
// }
for (SceneNode s : sector.getSons()) {
if (s instanceof GroupSector) {
generateSubSectorMeshForSector((GroupSector) s);
} else if (!generated && s instanceof SpaceRegion) {
if (((Sector) s).links[d.ordinal()] == null) {
isfs = generateQuadFor(d, (SpaceRegion) s);
if (isfs != null) {
for (GeneralTriangle isf : isfs) {
mesh.faces.add(isf);
}
}
}
}
}
}
} |
458cf853-b463-4054-aa39-04e41949cb9a | 3 | public int linearRegLookback( int optInTimePeriod )
{
if( (int)optInTimePeriod == ( Integer.MIN_VALUE ) )
optInTimePeriod = 14;
else if( ((int)optInTimePeriod < 2) || ((int)optInTimePeriod > 100000) )
return -1;
return optInTimePeriod-1;
} |
badb5a60-d4d9-4041-a614-154567cf5a68 | 4 | private Boolean checkAndSyncSchema(Class<?> c, Connection connection) throws SQLException{
if(!alreadyChecked.contains(c)){
try {
makeCreateTable(c, connection);
} catch (SQLException e) {
if(e.getMessage().indexOf("already exists") != -1){
makeAlterTable(c, connection);
}else{
throw e;
}
}
}
alreadyChecked.add(c);
return true;
} |
95ebc856-7cd3-4d0e-81c9-6b797547cb02 | 0 | public static void Info(String s){ log.info("[AprilonIRC] " + s);} |
12cec578-0d31-47f2-8515-cb6953bb8b63 | 2 | @Override
public String execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
try {
ClienteDao_Mysql oClienteDAO = new ClienteDao_Mysql(Conexion.getConection());
ClienteBean oCliente = new ClienteBean();
Gson gson = new Gson();
String jason = request.getParameter("json");
jason = EncodingUtil.decodeURIComponent(jason);
oCliente = gson.fromJson(jason, oCliente.getClass());
Map<String, String> data = new HashMap<>();
if (oCliente != null) {
oCliente = oClienteDAO.set(oCliente);
data.put("status", "200");
data.put("message", Integer.toString(oCliente.getId()));
} else {
data.put("status", "error");
data.put("message", "error");
}
String resultado = gson.toJson(data);
return resultado;
} catch (Exception e) {
throw new ServletException("ClienteSaveJson: View Error: " + e.getMessage());
}
} |
bbc99fc9-c61e-48eb-9c9d-d749e4ac456b | 5 | public void getCompleteBipartiteGraph(mxAnalysisGraph aGraph, int numVerticesGroup1, int numVerticesGroup2)
{
if (numVerticesGroup1 < 0 || numVerticesGroup2 < 0)
{
throw new IllegalArgumentException();
}
int numVertices = numVerticesGroup1 + numVerticesGroup2;
mxGraph graph = aGraph.getGraph();
Object parent = graph.getDefaultParent();
Object[] vertices = new Object[numVertices];
for (int i = 0; i < numVertices; i++)
{
vertices[i] = graph.insertVertex(parent, null, new Integer(i).toString(), 0, 0, 25, 25);
}
for (int i = 0; i < numVerticesGroup1; i++)
{
for (int j = numVerticesGroup1; j < numVertices; j++)
{
Object currVertex = vertices[i];
Object destVertex = vertices[j];
graph.insertEdge(parent, null, getNewEdgeValue(aGraph), currVertex, destVertex);
}
}
}; |
cc896f98-1726-480f-8586-56ade9e0c500 | 3 | public void cargarEmpleados(){
try {
Connection conn = Conexion.GetConnection();
try {
st = conn.createStatement();
emp = st.executeQuery("SELECT * FROM Empleados");
} catch (SQLException e) {
JOptionPane.showMessageDialog(this, e.getErrorCode() + ": " + e.getMessage());
}
String [] columns ={"idEmpleado","nombre","apellido_p","apellido_m","telefono","idPuesto"} ;
DefaultTableModel tm = new DefaultTableModel(null,columns){
@Override
public boolean isCellEditable(int rowIndex, int colIndex){
return false;
}
};
while(emp.next()){
String [] row = {emp.getString(1),emp.getString(2),emp.getString(3),emp.getString(4),emp.getString(5),emp.getString(6)};
tm.addRow(row);
}
jTblEmpleados.setModel(tm);
} catch (SQLException e) {
Logger.getLogger(GameCrush.class.getName()).log(Level.SEVERE,null,e);
}
} |
81a70330-c810-4dee-b017-e274462d55a5 | 6 | @Override
public byte[] getBytes() {
byte[] b = Util.getBytes(n);
byte[] varInt;
if (n < 0xfd && n >= 0) {
varInt = new byte[] { b[7] };
} else if (n < 0xffff && n >= 0) {
varInt = new byte[] { (byte) 0xfd, b[6], b[7] };
} else if (n < 0xffff_ffffL && n >= 0) {
varInt = new byte[] { (byte) 0xfe, b[4], b[5], b[6], b[7] };
} else {
varInt = new byte[] { (byte) 0xff, b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7] };
}
return varInt;
} |
1f272656-499d-4a92-934b-324236e82b69 | 6 | public void setEditValue(int n, EditInfo ei) {
if (n == 0 && ei.value > 0) {
triggerI = ei.value;
}
if (n == 1 && ei.value > 0) {
holdingI = ei.value;
}
if (n == 2 && ei.value > 0) {
cresistance = ei.value;
}
} |
4b80b6d5-ac9d-4b81-8f48-d3e85c7ec92b | 0 | @Test
public void delMinHeapIsEmptyAfterLastEntryCalled() {
h.insert(v);
h.delMin();
assertTrue(h.isEmpty());
} |
d94d8d18-6e79-4515-a30e-7c3961a7495c | 1 | public void WheelDown()
{
switch(Main.Screen)
{
case "inGame":
Main.inGameManager.WheelDown();
break;
}
} |
7801da7d-1ac2-4768-beb1-7d185bd475f7 | 8 | public static Binding getDirectBinding(Expression someExpression) {
if ((someExpression.bits & ASTNode.IgnoreNoEffectAssignCheck) != 0) {
return null;
}
if (someExpression instanceof SingleNameReference) {
return ((SingleNameReference)someExpression).binding;
} else if (someExpression instanceof FieldReference) {
FieldReference fieldRef = (FieldReference)someExpression;
if (fieldRef.receiver.isThis() && !(fieldRef.receiver instanceof QualifiedThisReference)) {
return fieldRef.binding;
}
} else if (someExpression instanceof Assignment) {
Expression lhs = ((Assignment)someExpression).lhs;
if ((lhs.bits & ASTNode.IsStrictlyAssigned) != 0) {
// i = i = ...; // eq to int i = ...;
return getDirectBinding (((Assignment)someExpression).lhs);
} else if (someExpression instanceof PrefixExpression) {
// i = i++; // eq to ++i;
return getDirectBinding (((Assignment)someExpression).lhs);
}
}
// } else if (someExpression instanceof PostfixExpression) { // recurse for postfix: i++ --> i
// // note: "b = b++" is equivalent to doing nothing, not to "b++"
// return getDirectBinding(((PostfixExpression) someExpression).lhs);
return null;
} |
013f3c46-141b-43e3-ae05-917c1b555837 | 4 | public static CommandType getCommandType(String command){
if(command.equals(GET_JOB))
return CommandType.GET_JOB;
else if(command.equals(CHECKOUT_JOB))
return CommandType.CHECKOUT_JOB;
else if(command.equals(COMPLETE_JOB))
return CommandType.COMPLETE_JOB;
else if (command.equals(HAVE_JOB))
return CommandType.HAVE_JOB;
return CommandType.UNKOWN;
} |
1b93d866-3feb-4351-81e0-b4ea3ea631b4 | 0 | @Override
public void setSocialId(final Long socialId) {
this.socialId = socialId;
} |
0f1a6bb2-dea2-4a4e-b3ac-0cef3b11bbbf | 3 | public boolean handleEnter(String line) {
line = line.trim();
int delim = line.indexOf(' ');
final String baseCommand;
final String[] args;
if (delim < 0) {
baseCommand = line;
args = NO_ARGS;
} else {
baseCommand = line.substring(0, delim);
args = line.substring(delim + 1).split(" ", 2);
}
if (baseCommand.equals("help")) {
helpCommands.get(null).call(args);
return true;
}
final Command c = commandMap.get(baseCommand);
if (c == null) {
return false;
}
c.call(args);
return true;
} |
391d24b9-5ade-4227-82e3-448d9e33934d | 6 | public boolean peutModifierCategorie(Utilisateur utilisateur) {
return (
utilisateur != null
&& (
utilisateur.getRole().getValeur() >= Role.Administrateur.getValeur()
|| (
utilisateur.getRole().getValeur() >= Role.Moderateur.getValeur()
&& getCategorieParent() != null
)
|| (getJeuAssocie() != null
&& (
getJeuAssocie().getCreateur().equals(utilisateur)
|| getJeuAssocie().getCollaborateurs().contains(utilisateur)
)
)
)
);
} |
de50ba4b-33b3-4f38-a951-fe1bd0327b9e | 0 | public Component getComponentBefore(Container container, Component component) {
return cycle(component, -1);
} |
b7a29dfb-300c-4160-86f3-32ef44271e5e | 6 | @Test
public void forEachToimii() {
Hakemisto<Integer, String> hakemisto = new Hakemisto<Integer, String> ();
hakemisto.put(7, "moikka");
hakemisto.put(4, "heippa");
hakemisto.put(65, "maara");
hakemisto.put(-8, "joku juttu");
for (Vektori<Integer,String> vektori : hakemisto) {
System.out.println(vektori.getKey() + " " + vektori.getValue());
}
int i = 0;
String oikea = "";
for (Vektori<Integer, String> vektori : hakemisto) {
if (i == 0) {
oikea = "moikka";
}
if (i == 1) {
oikea = "heippa";
}
if (i == 2) {
oikea = "maara";
}
if (i == 3) {
oikea = "joku juttu";
}
assertEquals(oikea, vektori.getValue());
i++;
}
assertEquals(4, i);
} |
d4efa840-dce7-4b28-8367-740ca56ec91c | 0 | public static void t(CanFight x) {
x.fight();
} |
00f34c70-b2e5-4feb-a882-11d8d72403ce | 1 | public Object clone()
{
try
{
return super.clone();
}
catch (CloneNotSupportedException ex)
{
throw new InternalError(this+": "+ex);
}
} |
8d1c411a-85a9-4bfd-8b21-a28f459c329e | 4 | private StringBuffer Get10kSearchPage(String urlStr)
{
/** the length of input stream */
int chByte = 0;
URL url = null;
/** HTTP connection */
HttpURLConnection httpConn = null;
InputStream in = null;
StringBuffer sb = new StringBuffer("");
try
{
//int len = 0;
url = new URL(urlStr);
httpConn = (HttpURLConnection) url.openConnection();
HttpURLConnection.setFollowRedirects(true);
httpConn.setRequestMethod("GET");
in = httpConn.getInputStream();
chByte = in.read();
while (chByte != -1)
{
//len++;
sb.append((char)chByte);
chByte = in.read();
}
//System.out.println(len);
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
try
{
in.close();
httpConn.disconnect();
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
return sb;
} |
0df83444-2fa0-4070-ba03-bcb957774e3d | 4 | public static ArrayList<String> readDomains(String filename){
ArrayList<String> list = new ArrayList<>();
try {
BufferedReader reader = new BufferedReader(new FileReader(new File(filename)));
while (true) {
String mail = reader.readLine();
if (mail == null) break;
list.add(mail.split("@")[1].toLowerCase());
}
} catch (FileNotFoundException ex) {
} catch (IOException ex) {
}
return list;
} |
4fef0d53-46e0-4add-bbfd-380fab4e4ebe | 8 | private void addCubeFace(IntPoint p1, IntPoint shift) {
IntPoint p2 = p1.add(shift);
int value1, value2, orientation;
if(shift.equals(IntPoint.UP) || shift.equals(IntPoint.DOWN)) {
orientation = CubeFace.Z_AXIS;
} else if(shift.equals(IntPoint.LEFT) || shift.equals(IntPoint.RIGHT)) {
orientation = CubeFace.X_AXIS;
} else {
orientation = CubeFace.Y_AXIS;
}
if(p1.inBounds(length, width, height)) {
value1 = chamber.getCubes()[p1.getX()][p1.getY()][p1.getZ()];
} else {
value1 = Piece.NOTHING;
}
if(p2.inBounds(length, width, height)) {
value2 = chamber.getCubes()[p2.getX()][p2.getY()][p2.getZ()];
} else {
value2 = Piece.NOTHING;
}
if(value1 == Piece.NOTHING) {
faces.add(new CubeFace(p1.midpoint(p2), orientation, value2));
} else if(value2 == Piece.NOTHING) {
faces.add(new CubeFace(p1.midpoint(p2), orientation, value1));
}
} |
b54f4a1e-d01e-49a6-8515-45c67f346c6e | 7 | public static int getExpRate(MapleCharacter noob){
if(noob.getGMSMode() > 0 && !noob.isJounin()){
return 0;
}
double expRate = Village.getExpRate(noob.getVillage());
if(Modes.getInstance(noob).hasKyubi()){
if(noob.getVillage() != 5) {
expRate *= 2;
} else {
expRate *= 1.3;
}
}
expRate += (noob.getExpBoost() * expRate / 100);
if(noob.isGenin()){
expRate += (expRate * 0.25);
}
if(noob.hasRasengan()){
expRate *= 0.70;
}
double reduce = Math.min((noob.getMaxStatItems() * 100), noob.getReborns());
reduce = Math.min(reduce, (expRate /2));
expRate -= reduce;
if(Village.isOtherVillage(noob)){
expRate /=2;
}
return (int) Math.floor(expRate);
} |
a313a4ac-b170-4618-ac9b-7ecd94a89c0e | 2 | public static String addResourcePathToPackagePath(Class<?> clazz,
String resourceName) {
Assert.notNull(resourceName, "Resource name must not be null");
if (!resourceName.startsWith("/")) {
return classPackageAsResourcePath(clazz) + "/" + resourceName;
}
return classPackageAsResourcePath(clazz) + resourceName;
} |
62038e11-cc3b-462d-88b9-14c4cf3708fb | 5 | public static double logGamma(double x) {
double xcopy = x;
double fg = 0.0D;
double first = x + lgfGamma + 0.5;
double second = lgfCoeff[0];
if (x >= 0.0) {
first -= (x + 0.5) * Math.log(first);
for (int i = 1; i <= lgfN; i++)
second += lgfCoeff[i] / ++xcopy;
fg = Math.log(Math.sqrt(2.0 * Math.PI) * second / x) - first;
} else {
fg = Math.PI / (Stat.gamma(1.0D - x) * Math.sin(Math.PI * x));
if (fg != 1.0 / 0.0 && fg != -1.0 / 0.0) {
if (fg < 0) {
throw new IllegalArgumentException("\nThe gamma function is negative");
} else {
fg = Math.log(fg);
}
}
}
return fg;
} |
58f89c7c-d058-43bd-8090-216d2a3963d6 | 4 | protected String getMethodHeader(ArrayList<JXScriptArgument<?>> arguments)
{
String methodHeader = "var obj = new Object();\n"
+ "obj.calc = function(";
if( arguments != null )
{
for( int i=0; i<arguments.size(); i++ )
{
methodHeader += arguments.get(i).getName();
if( i < (arguments.size()-1) )
methodHeader += ", ";
}
}
methodHeader += ")\n{\n";
return methodHeader;
} |
5bf5f73a-758c-471c-8a84-66f29baff6c3 | 3 | private List<Header> getExpandedHeaders(final Request request) {
final List<Header> headers = request.getHeaders();
final List<Variable> contextVariables = workflow.getContext().getVariables();
for (final Header header : headers) {
final String newValue = VariableHelper.substituteVariables(header.getValue(), contextVariables);
header.setValue(newValue);
if (header.getName().equals("Content-Type") && header.getValue().startsWith("multipart/form-data")) {
header.setValue("multipart/form-data;boundary=" + BOUNDARY);
}
println(" header:" + header.getName() + " = " + header.getValue());
}
return headers;
} |
ae25d0e0-0904-4da6-b272-57f6ba12c7a4 | 1 | final public CycVariable sentenceDenotingMetaVariable(boolean requireEOF) throws ParseException {
CycVariable val = null;
val = metaVariable(false);
eof(requireEOF);
{if (true) return val;}
throw new Error("Missing return statement in function");
} |
29e15e58-6cf6-4b79-addd-790c2e78b411 | 3 | public boolean equals(Object obj)
{
boolean isEqual = false;
if (obj != null && obj.getClass() == this.getClass()) {
TestRunInfo testRunInfo = (TestRunInfo) obj;
if (testRunInfo != null) {
isEqual = (this.toString().equals(testRunInfo.toString()));
}
}
return isEqual;
} |
45254711-247a-4eac-b90b-2a34881a755e | 3 | public GUI3() {
Dimension screenSize = GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds().getSize();
try {
INGRESS_FONT = Font.createFont(Font.TRUETYPE_FONT, new FileInputStream("Coda.ttf"));
} catch(Exception e) {
INGRESS_FONT = new Font("Courier New", Font.PLAIN, 15);
}
this.random = new Random().nextInt(3);
if(random == 0) guiColor = new Color(0, 191, 1);//green
else if(random == 1) guiColor = new Color(0, 147, 207);//blue
else guiColor = new Color(205, 106, 0);//orange
mainFrame = new JFrame();
mainPanel = new JPanel(new MigLayout("gap 0, insets 0, fill"));
mainPanel.setBackground(Color.BLACK);
Handler handler = new Handler(this);
menuPanel = new MenuPanel(handler, random);
mainPanel.add(titlePanel = new TitlePanel(handler), "dock north");
mainPanel.add(getMenuPanel(), "dock west, width " + menuPanelWidth + "!");
decoderPanel = new DecoderPanel(mainPanel.getWidth(), random);
scrollPanel = new JScrollPane(getDecoderPanel());
scrollPanel.setBorder(new EmptyBorder(0, 0, 0, 0));
scrollPanel.getVerticalScrollBar().setUnitIncrement(16);
mainPanel.add(codePanel = new CodePanel(handler, random), "growx,wrap");
mainPanel.add(scrollPanel, "grow, push");
mainFrame.add(mainPanel);
mainFrame.setMinimumSize(new Dimension(600, 400));
mainFrame.pack();
mainFrame.addComponentListener(new ComponentListener() {
@Override
public void componentResized(ComponentEvent e) {
updateDecoderPanel();
}
@Override
public void componentMoved(ComponentEvent e) {
}
@Override
public void componentShown(ComponentEvent e) {
mainPanel.revalidate();
}
@Override
public void componentHidden(ComponentEvent e) {
mainPanel.invalidate();
}
});
mainFrame.setSize((int) screenSize.getWidth() / 2, (int) screenSize.getHeight() / 2);
mainFrame.setLocation((int) screenSize.getWidth() / 4, (int) screenSize.getHeight() / 4);
mainFrame.setTitle("Ingress Cipher Tool");
mainFrame.setIconImage(makeImageIcon("/images/Ingress_Dual_middle.png").getImage());
mainFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
mainFrame.setExtendedState(JFrame.MAXIMIZED_BOTH);
mainFrame.setVisible(true);
} |
48862c3d-a4d7-4c7b-9547-7df30162f1ae | 9 | public static void main( String args[])
{
int opcao;
int vezes;
int intervalo =0;
do
{
opcao = interacao.lerInt("1. Random Int\n2.Random Float\n3.Random Double\n0.Sair");
if(opcao <0 || opcao > 3)
{
interacao.mensagem("Seu idiota! Escolha valor no intervalo!");
}
}while( opcao < 0 || opcao > 3);
do
{
vezes = interacao.lerInt("Quantas vezes deseja imprimir?!");
if( vezes < 1 || vezes >100)
{
interacao.mensagem("O valor está fora do intervalo de 1 - 100");
}
}while(vezes < 1 || vezes > 100);
if( opcao == 1)
{
intervalo = interacao.lerInt("Qual é o intervalo?!");
}
gerar(opcao, vezes, intervalo );
} |
34865ee7-0ae4-474f-a490-ddcd148fd766 | 0 | public Integer getProblemId() {
return this.problemId;
} |
1d1a5ec2-1ddf-43d4-8811-8f712275ae59 | 0 | public String getTableName() {
return tableName;
} |
06d04185-3ec8-4bbf-81ed-2b04405fc2b0 | 0 | public SymbolTable()
{
parent = null;
table = new LinkedHashMap<String, Symbol>();
} |
59df5c53-9edc-41b5-b930-bf4900cb062c | 9 | public boolean isBoxInFrustum(double par1, double par3, double par5, double par7, double par9, double par11)
{
for (int var13 = 0; var13 < 6; ++var13)
{
if ((double)this.frustum[var13][0] * par1 + (double)this.frustum[var13][1] * par3 + (double)this.frustum[var13][2] * par5 + (double)this.frustum[var13][3] <= 0.0D && (double)this.frustum[var13][0] * par7 + (double)this.frustum[var13][1] * par3 + (double)this.frustum[var13][2] * par5 + (double)this.frustum[var13][3] <= 0.0D && (double)this.frustum[var13][0] * par1 + (double)this.frustum[var13][1] * par9 + (double)this.frustum[var13][2] * par5 + (double)this.frustum[var13][3] <= 0.0D && (double)this.frustum[var13][0] * par7 + (double)this.frustum[var13][1] * par9 + (double)this.frustum[var13][2] * par5 + (double)this.frustum[var13][3] <= 0.0D && (double)this.frustum[var13][0] * par1 + (double)this.frustum[var13][1] * par3 + (double)this.frustum[var13][2] * par11 + (double)this.frustum[var13][3] <= 0.0D && (double)this.frustum[var13][0] * par7 + (double)this.frustum[var13][1] * par3 + (double)this.frustum[var13][2] * par11 + (double)this.frustum[var13][3] <= 0.0D && (double)this.frustum[var13][0] * par1 + (double)this.frustum[var13][1] * par9 + (double)this.frustum[var13][2] * par11 + (double)this.frustum[var13][3] <= 0.0D && (double)this.frustum[var13][0] * par7 + (double)this.frustum[var13][1] * par9 + (double)this.frustum[var13][2] * par11 + (double)this.frustum[var13][3] <= 0.0D)
{
return false;
}
}
return true;
} |
ab676bac-22d0-4cc9-a3ab-05d5d40bccf1 | 1 | public List<String> findItinerary(String[][] tickets) {
Map<String,PriorityQueue<String>> ticketMap=new HashMap<String, PriorityQueue<String>>();
for(String[] ticket : tickets){
// ticketMap.computeIfAbsent(ticket[0],k->new PriorityQueue<String>()).add(ticket[1]);
}
List<String> itinerary=new ArrayList<String>();
//递归解法
find(ticketMap,"JFK",itinerary);
//迭代解法
// Stack<String> stack=new Stack<String>();
// stack.push("JFK");
// while (!stack.isEmpty()){
// while (ticketMap.containsKey(stack.peek()) && !ticketMap.get(stack.peek()).isEmpty()){
// stack.push(ticketMap.get(stack.peek()).poll());
// }
// itinerary.add(0,stack.pop());
// }
return itinerary;
} |
6298eb74-894a-4365-83b2-e7406b80eb4b | 8 | public void setDisAppearLine(List<Integer> fulledLines, TScoreManager scoreMng) {
//remove squares in the fulled line
int cnt = fulledLines.size();
for (TBlock blk: blks) {
List<TSquare> sqRemove = new ArrayList<TSquare>();
TSquare[] sqs = blk.getSquares();
for (TSquare sq: sqs) {
int x = (int)sq.getSqCoordinate().getX();
int y = (int)sq.getSqCoordinate().getY();
boolean needRemove = false;
for (Integer disLineY: fulledLines) {
if (y == disLineY) {
needRemove = true;
break;
}
}
if (needRemove) {
sqRemove.add(sq);
}
}
blk.removeSquare(sqRemove);
//make square move down if the square is above the removed line
for (Integer disLineY: fulledLines) {
TSquare sqLeft[] = blk.getSquares();
for (TSquare s: sqLeft) {
int y = (int)s.getSqCoordinate().getY();
if (y > disLineY) {
int newY = y - cnt;
s.setSqCoordinate((int)s.getSqCoordinate().getX(), newY);
}
}
}
}
} |
ca0ea7fc-4eb9-434c-8e8f-d140b6045924 | 1 | public Account lookup (String id){
UUID searchAccountId = UUID.fromString(id);
Account searchAccount = null;
if(accounts.containsKey(searchAccountId))
searchAccount = accounts.get(searchAccountId);
return searchAccount;
} |
26c8f0ad-5cd0-4800-bcec-2b24695eb387 | 1 | public boolean isPrintMouseCoords() {
if(frame == null) buildGUI();
return printMouseCoords.isSelected();
} |
dc0e5af9-0191-46ab-a96c-c58dbecc85e1 | 7 | public void partialTreeAlignment(PriorityQueue<Tree<String>> sQ) {
Tree<String> ts = sQ.poll();
boolean flag = false;
PriorityQueue<Tree<String>> rQ = new PriorityQueue<Tree<String>>();
boolean i = false;// all unaligned items inserted
while (!sQ.isEmpty()) {
Tree<String> ti = sQ.poll();
int matcheCount = ts.simpleTreeMatching(ti);// matches and aligns
if (matcheCount < ti.size()) {/* if not node aligned */
i = insertIntoSeed(ts, ti);
if (!i) {/* if still not all aligned */
rQ.add(ti);
}
}
if (matcheCount > 0 || i) {
flag = true;
}
if (sQ.isEmpty() && flag) {
sQ = rQ;
rQ = new PriorityQueue<Tree<String>>();
flag = false;
i = false;
}
}
// TODO: output data item from each ti to the data table
//logger.info(arg0)
} |
107edadf-ec05-4855-b39d-e8f8ce519183 | 1 | public void paintComponent(Graphics g)
{
super.paintComponent(g);
int h = this.getHeight();
int w = this.getWidth();
g.setColor(background);
g.fillRect(0, 0, w, h);
if (this.image != null)
{
int wb = (w - this.image.getWidth()) / 2;
int hb = (h - this.image.getHeight()) / 2;
g.drawImage(image, wb, hb, this);
}
} |
caaa098e-69de-42bf-95df-9c00b46b34a5 | 1 | private JPanel buildWhatsnewPane()
{
JPanel panel = new JPanel(new BorderLayout());
try {
JEditorPane editor = new JEditorPane( Main.class.getResource("help/whatsnew.html") );
editor.setEditable(false);
panel.setBorder(BorderFactory.createEmptyBorder(8, 8, 8, 8));
panel.add(new JScrollPane(editor), BorderLayout.CENTER);
} catch (IOException e) {
}
return panel;
} |
e1c97b2c-34a9-4dce-bf69-6a6dab77279c | 9 | public Node findIdNode(String id, String scopeName) {
String nodetype = "I";
for (Scope scope : (LexParser.symtab).scopestack.subList(0, (LexParser.symtab).scopestack.size())) {
if(scope.Scopetype.equalsIgnoreCase(scopeName)) {
Symbol sym = scope.symbolMap.get(id);
if( sym == null && scope.Scopetype.equalsIgnoreCase("GLOBAL")) {
System.out.println(" variable "+id+ " not found in anyscope in findIdNode");
return null;
}
if(sym != null) {
if(sym.type.contains("INT")) nodetype = "I";
if(sym.type.contains("FLOAT")) nodetype = "F";
if(sym.type.contains("STRING")) nodetype = "S";
if(sym.nodePrefix == null)
return new Node(id, nodetype);
return new Node(sym.nodePrefix, nodetype);
}
}
}
return findIdNode(id, "GLOBAL");
} |
d2727c28-2d90-4b34-8493-ec3b71987246 | 7 | public static String getDay(int i)
{
switch(i){
case 1: return "Sunday";
case 2: return "Monday";
case 3: return "Tuesday";
case 4: return "Wednesday";
case 5: return "Thursday";
case 6: return "Friday";
case 7: return "Saturday";
}
return "";
} |
134611f3-8e51-4494-91e4-30de14b8df80 | 8 | public void save()
{
//create a buffered writer stream
FileOutputStream fileOutputStream = null;
OutputStreamWriter outputStreamWriter = null;
BufferedWriter out = null;
try{
fileOutputStream = new FileOutputStream(filename);
outputStreamWriter =
new OutputStreamWriter(fileOutputStream, fileFormat);
out = new BufferedWriter(outputStreamWriter);
ListIterator i;
//write each line in the buffer to the file
for (i = buffer.listIterator(); i.hasNext(); ){
out.write((String)i.next());
out.newLine();
}
//Note! You MUST flush to make sure everything is written.
out.flush();
}
catch(IOException e){}
finally{
try{if (out != null) {out.close();}}
catch(IOException e){}
try{if (outputStreamWriter != null) {outputStreamWriter.close();}}
catch(IOException e){}
try{if (fileOutputStream != null) {fileOutputStream.close();}}
catch(IOException e){}
}
}//end of IniFile::save |
1066ffbf-59dc-4442-9e2c-e86e20092cab | 7 | private void loadRiverCrossings(Path baseDir) throws IOException{
Path mapImagePath = getFilePath(MapFile.RIVERS, baseDir);
try(InputStream stream = new FileInputStream(mapImagePath.toString())) {
BufferedImage mapImage = ImageIO.read(stream);
int[] rgbValues = mapImage.getRGB(0, 0, width, height, null, 0, width);
int landRgb = 0xFFFFFFFF;
int waterRgb = 0xFF7A7A7A; // Seas and lakes
for(Province province : provinces){
if(province.provinceType != ProvinceType.LAND)
continue;
Point2D sourcePoint = province.PositionFor(PositionType.UNIT);
for(Province adjacency : province.adjacentProvinces){
if(adjacency.provinceType != ProvinceType.LAND)
continue;
Point2D destinationPoint = adjacency.PositionFor(PositionType.UNIT);
List<Coordinate> pointsBetween = MapUtilities.getPointsBetween(sourcePoint, destinationPoint);
for(Coordinate coordinate : pointsBetween) {
int rbgIndex = coordinate.x + width * coordinate.y;
int coordinateRgb = rgbValues[rbgIndex];
if (coordinateRgb != landRgb &&
coordinateRgb != waterRgb)
adjacency.riverCrossings.add(province);
}
}
}
}
} |
c5159065-6aa3-4c86-b58e-862f754c497b | 3 | private void setParsedResults(String[] prasedText) {
if (jcbSortOutput.isSelected()) {
Arrays.sort(prasedText);
}
DefaultListModel listModel = (DefaultListModel) jlOutputText.getModel();
cleanOutputs();
int parsedLinesCount = 0;
for (String line : prasedText) {
appendLineToOutput(line, listModel);
parsedLinesCount++;
}
if (jcbHighlightDuplicates.isSelected()) {
jtpOutputTabs.setSelectedIndex(LIST_TAB_INDEX);
ListUtils.highlightDuplicates(jlOutputText);
}
jlStatusLine.setText("Output: " + parsedLinesCount + " lines. Parsed with regex: ");
jlStatusLine2.setText(jtfParseExpression.getSelectedItem().toString());
} |
5318c9e2-0183-45be-be5e-acde6bc487c0 | 2 | public ArrayList viewBookingPayment() {
ArrayList temp = new ArrayList();
Query q = em.createQuery("SELECT t from BookingEntity t");
for (Object o : q.getResultList()) {
BookingEntity p = (BookingEntity) o;
if (p.getAccount().getId() == userId) {
temp.add(String.valueOf(p.getPayment().getAmountPaid()));
}
//System.out.println("viewbooking: " + temp.size());
}
return temp;
} |
bb8813bd-e061-45f2-b596-ee13414f8803 | 3 | public static void main(String[] args)
{
long startTime = System.currentTimeMillis();
if(args.length == 0){
System.out.println("Please provide the location of the workload file!");
System.exit(-1);
}
try {
String fileName = args[0];
// number of grid user entities + any Workload entities.
int num_user = 1;
Calendar calendar = Calendar.getInstance();
boolean trace_flag = false; // mean trace GridSim events
// Initialise the GridSim package without any statistical
// functionalities. Hence, no GridSim_stat.txt file is created.
System.out.println("Initialising GridSim package");
GridSim.init(num_user, calendar, trace_flag);
//////////////////////////////////////////
// Creates one GridResource entity
int rating = 377; // rating of each PE in MIPS
int totalPE = 9; // total number of PEs for each Machine
int totalMachine = 128; // total number of Machines
String resName = "Res_0";
GridResource resource = createGridResource(resName, rating, totalMachine, totalPE);
//////////////////////////////////////////
// Creates one Workload trace entity.
WorkloadFileReader model = new WorkloadFileReader(fileName, rating);
Workload workload = new Workload("Load_1", resource.get_name(), model);
//////////////////////////////////////////
// Starts the simulation in debug mode
boolean debug = true;
GridSim.startGridSimulation(debug);
if(!debug) {
long finishTime = System.currentTimeMillis();
System.out.println("The simulation took " + (finishTime - startTime) + " milliseconds");
}
// prints the Gridlets inside a Workload entity
// workload.printGridletList(trace_flag);
}
catch (Exception e) {
e.printStackTrace();
}
} |
b732309b-95c0-40c2-807b-ccacff9a8477 | 9 | private void readDatatypeArray(int type, Document document, String key) {
ValueList tempList = valueList.getNextList();
if (tempList == null) {
document.put(key,null);
return;
}
int len = tempList.length();
Object[] array = null;
if (type == ElementType.TYPE_STRING_ARRAY) {
array = new String[len];
for (int i=0;i<len;i++) {
array[i] = tempList.getNextString();
}
} else if (type == ElementType.TYPE_INTEGER_ARRAY) {
array = new Integer[len];
for (int i=0;i<len;i++) {
array[i] = tempList.getNextInt();
}
} else if (type == ElementType.TYPE_LONG_ARRAY) {
array = new Long[len];
for (int i=0;i<len;i++) {
array[i] = tempList.getNextLong();
}
} else if (type == ElementType.TYPE_DOUBLE_ARRAY) {
array = new Double[len];
for (int i=0;i<len;i++) {
array[i] = tempList.getNextDouble();
}
}
document.put(key,array);
} |
4131d264-114a-4b18-8017-cac64d961cd8 | 6 | @EventHandler
public void EnderDragonPoison(EntityDamageByEntityEvent event) {
Entity e = event.getEntity();
Entity damager = event.getDamager();
String world = e.getWorld().getName();
boolean dodged = false;
Random random = new Random();
double randomChance = plugin.getEnderDragonConfig().getDouble("EnderDragon.Poison.DodgeChance") / 100;
final double ChanceOfHappening = random.nextDouble();
if (ChanceOfHappening >= randomChance) {
dodged = true;
}
if (plugin.getEnderDragonConfig().getBoolean("EnderDragon.Poison.Enabled", true) && damager instanceof EnderDragon && e instanceof Player && plugin.getConfig().getStringList("Worlds").contains(world) && !dodged) {
Player player = (Player) e;
player.addPotionEffect(new PotionEffect(PotionEffectType.POISON, plugin.getEnderDragonConfig().getInt("EnderDragon.Poison.Time"), plugin.getEnderDragonConfig().getInt("EnderDragon.Poison.Power")));
}
} |
ce01cfb9-0a3c-4b92-b418-ade5f2b8b780 | 4 | public int uniquePaths(int m, int n) {
if (n == 1)
return 1;
if (m == 1)
return 1;
int[] arr = new int[n];
Arrays.fill(arr, 1);
for (int j = 1; j < m; j++) {
for (int i = 1; i < n; i++) {
arr[i] = arr[i - 1] + arr[i];
}
}
return arr[n - 1];
} |
7748e8a9-fc24-4d9d-a317-3b63d0d0ca50 | 9 | void dds() {
int ini_fevals = Math.max(5, (int) Math.round(0.005 * maxiter));
int ileft = maxiter - ini_fevals;
double fvalue = 0;
double Ftest;
for (int i = 0; i < ini_fevals; i++) {
// sample an initial solution candidate (uniform random sampling):
for (int j = 0; j < num_dec; j++) {
double ranval = rand.nextDouble();
stest[j] = s_min[j] + ranval * (s_max[j] - s_min[j]);
}
// Evaluate solution and return objective function value (fvalue), for example see grie10.f
fvalue = obj_func(stest);
Ftest = to_max * fvalue; // to_max is 1.0 for MIN problems, -1 for MAX problems
if (i == 1) {
// Fbest must be initialized
// track best solution found so far and corresponding obj function value
Fbest = Ftest;
sbest = stest;
}
if (Ftest <= Fbest) {
// update current (best) solution
Fbest = Ftest;
sbest = stest;
}
// accumulate DDS initialization outputs
f_count[i] = i;
Ftests[i] = to_max * Ftest; // candidate solution objective function value (untransformed)
Fbests[i] = to_max * Fbest; // best current solution objective function value (untransformed)
stests[i] = stest; // candidate solution (decision variable values)
// write(*,*) f_count(i), to_max*Fbest ! *** user uncomment if desired ***
}
for (int i = 0; i < ileft; i++) {
double Pn = 1.0 - Math.log((double) i+1) / Math.log((double) ileft); // probability each DV selected
int dvn_count = 0; // counter for how many DVs selected for perturbation
stest = sbest; // define stest initially as best current solution
for (int j = 0; j < num_dec; j++) {
double ranval = rand.nextDouble();
if (ranval < Pn) {
dvn_count++;
// call 1-D perturbation function to get new DV value (new_value)
double new_value = neigh_value(sbest[j], s_min[j], s_max[j], r_val);
// note that r_val is the value of the DDS r perturbation size parameter (0.2 by default)
stest[j] = new_value; //change relevant DV value in stest
}
}
if (dvn_count == 0) {
// no DVs selected at random, so select ONE
double ranval = rand.nextDouble();
int dv = (int) Math.ceil(num_dec * ranval);
// call 1-D perturbation function to get new DV value (new_value)
double new_value = neigh_value(sbest[dv], s_min[dv], s_max[dv], r_val);
stest[dv] = new_value; //change relevant DV value in stest
}
// Evaluate obj function value (fvalue) for stest, for example see grie10.f:
fvalue = obj_func(stest);
Ftest = to_max * fvalue; // to_max handles min (=1) and max (=-1) problems,
if (Ftest <= Fbest) { // update current best solution
Fbest = Ftest;
sbest = stest;
}
// accumulate DDS search history
int ind1 = i + ini_fevals; // proper index for storage
f_count[ind1] = ind1;
Ftests[ind1] = to_max * Ftest;
Fbests[ind1] = to_max * Fbest;
stests[ind1] = stest;
}
} |
caf0dae6-3294-4e9f-8dc9-db1b0150751b | 1 | public static void MakeFramesNotEnable(Boolean state)
{
for(int i =0;i<callFrameList.size();i++)
callFrameList.get(i).setEnabled(state);
} |
8b793a6b-c393-4444-8aaf-03b8cf659d44 | 3 | * @return the meeting with the requested ID, or null if it there is none.
* @throws IllegalArgumentException if there is a meeting with that ID happening in the past
*/
public FutureMeeting getFutureMeeting(int id) throws IllegalArgumentException
{
Meeting m = getMeeting(id);
if(m == null)
{
return (FutureMeeting)m;
}
now.setTime(new Date());
if(now.after(m.getDate()))
{
throw new IllegalArgumentException("Meeting is in the past");
}
if(!(m instanceof FutureMeeting))
{
throw new IllegalArgumentException("Meeting is not a Future Meeting");
}
return (FutureMeeting)m;
} |
b9ed6181-b131-4d9d-9170-a7b49450ae73 | 0 | public void setOpenEncoding(String openEncoding) {
this.openEncoding = openEncoding;
} |
afa2491c-673b-4985-9cd7-bf06a4acadb8 | 1 | public static boolean getKey(int key)
{
return (key < keys.length) ? keys[key] : false;
} |
0fab8d38-6709-4de3-9401-347e31637176 | 6 | public void setDefaultCommandHistory() {
// Insert default tools into command history for convenience.
File file = new File(".");
File files[] = file.listFiles();
for (int i = 0; i < files.length; ++i) {
String name = files[i].getName();
if (name.endsWith(".java")) {
name = name.substring(0, name.length() - 5);
try {
Class c = Class.forName("filters." + name);
Class s = c.getSuperclass();
if (s != null) {
String parent = s.getName();
if (parent != null &&
parent.equals("filters.Filter")) {
commandPanel.addToHistory(name);
}
}
} catch (ClassNotFoundException e) {
}
}
}
} |
35731d3f-394b-4737-910b-7599af3d7d7b | 6 | public boolean mapword(String word1, String word2){
if(word1 == null || word2 == null || word1.length() != word2.length())
return false;
HashMap<Character, Character> map = new HashMap<Character, Character>();
for(int i=0 ; i<word1.length(); i++){
char c = word2.charAt(i);
if(map.containsKey(c)){
if(map.get(c) != word1.charAt(i))
return false;
}
else map.put(c, word1.charAt(i));
}
return true;
} |
c49259c1-d549-42a4-a99f-abc31d42500b | 7 | private int getPoints(GeneralPath path, float[] mypoints) {
int count = 0;
float x = 0;
float y = 0;
float startx = 0;
float starty = 0;
float[] coords = new float[6];
PathIterator pi = path.getPathIterator(new AffineTransform());
while (!pi.isDone()) {
if (count >= mypoints.length) {
mypoints = null;
break;
}
int pathtype = pi.currentSegment(coords);
switch (pathtype) {
case PathIterator.SEG_MOVETO:
startx = x = coords[0];
starty = y = coords[1];
break;
case PathIterator.SEG_LINETO:
mypoints[count++] = x;
mypoints[count++] = y;
x = mypoints[count++] = coords[0];
y = mypoints[count++] = coords[1];
break;
case PathIterator.SEG_QUADTO:
x = coords[2];
y = coords[3];
break;
case PathIterator.SEG_CUBICTO:
x = mypoints[4];
y = mypoints[5];
break;
case PathIterator.SEG_CLOSE:
mypoints[count++] = x;
mypoints[count++] = y;
x = mypoints[count++] = startx;
y = mypoints[count++] = starty;
break;
}
pi.next();
}
return count;
} |
cdec698a-3b5b-4b75-94ca-72c58bf827fc | 6 | public boolean isCellEditable(int row, int col){
if (isEnabled && col == 1 && dataFormat != Format.BIN_FORMAT &&
(endEnabling == -1 || (row>= startEnabling && row <= endEnabling)))
return true;
else
return false;
} |
1041faf0-bb0d-4010-b242-adb4991f8834 | 3 | public void walkUp() {
face = 0;
if (!(y == 0) && !walkblockactive)
if (!Collision.check(new Position(x, y), face)) {
y -= walkspeed;
setWalkBlock(walkblocktick);
}
} |
25afed5a-356e-4c4e-b475-959105b67268 | 7 | private void writeFieldsToFile(HashMap <String,String> fields) {
// What is the write method going to do
// Well, it can read the old file
// Replace / Add valuues to it
// And then re-write it
// Let's save it as plain-text for now, maybe look at zipping it after
// Firstly, read the old values and replace them with any new ones
// Or add new ones if they don't exist
Set<String> newKeys = fields.keySet();
HashMap<String,String> oldValues = readFielldsFromFile();
for (String key : newKeys) {
if (oldValues.containsKey(key)) {
// Remove it for replacement
oldValues.remove(key);
}
oldValues.put(key, fields.get(key));
}
// Put this into a string and save it
StringBuffer file = new StringBuffer();
for (String key : oldValues.keySet()) {
file.append(key+LINE_SPLITTER+oldValues.get(key)+"\r\n");
}
String stateFile = MDFConfig.getStateFile();
FileOutputStream fout = null;
try {
File f = new File(stateFile);
if (f.exists()) {
f.delete();
}
fout = new FileOutputStream(f);
fout.write(file.toString().getBytes());
} catch (Exception e) {
log.log(Level.WARNING,"An error occurred writing the state file " + e.getMessage(),e);
} finally {
if (fout != null) {
try {fout.close();} catch (Exception e) {}
}
}
} |
6e8848a5-e8a0-4dc1-b976-9c5ca79ffe9a | 6 | private void autosave_game () {
Game game = freeColClient.getGame();
if (game == null) return;
// unconditional save per round (fix file "last-turn")
String autosave_text
= Messages.message("clientOptions.savegames.autosave.fileprefix");
String filename = autosave_text + "-"
+ Messages.message("clientOptions.savegames.autosave.lastturn")
+ ".fsg";
String beforeFilename = autosave_text + "-"
+ Messages.message("clientOptions.savegames.autosave.beforelastturn")
+ ".fsg";
File autosaveDir = FreeColDirectories.getAutosaveDirectory();
File saveGameFile = new File(autosaveDir, filename);
File beforeSaveFile = new File(autosaveDir, beforeFilename);
// if "last-turn" file exists, shift it to "before-last-turn" file
if (saveGameFile.exists()) {
beforeSaveFile.delete();
saveGameFile.renameTo(beforeSaveFile);
}
saveGame(saveGameFile);
// conditional save after user-set period
ClientOptions options = freeColClient.getClientOptions();
int savegamePeriod = options.getInteger(ClientOptions.AUTOSAVE_PERIOD);
int turnNumber = game.getTurn().getNumber();
if (savegamePeriod <= 1
|| (savegamePeriod != 0 && turnNumber % savegamePeriod == 0)) {
Player player = game.getCurrentPlayer();
String playerNation = player == null ? ""
: Messages.message(player.getNation().getNameKey());
String gid = Integer.toHexString(game.getUUID().hashCode());
filename = Messages.message("clientOptions.savegames.autosave.fileprefix")
+ '-' + gid + "_" + playerNation
+ "_" + getSaveGameString(game.getTurn()) + ".fsg";
saveGameFile = new File(autosaveDir, filename);
saveGame(saveGameFile);
}
} |
4305907e-7505-49e6-a92c-3ab1378ab72f | 4 | private static void sendStatus(Status status, String date, boolean publicStatus){
try{
for (int i = 0; i < Friends.friendList.size(); i++){
Friends friend = Friends.friendList.get(i);
if(publicStatus){
Message.postStatus(Main.userName + "##"+ date + "##" + status.getContent(), InetAddress.getByName(friend.getHost()));
}
else{
if (friend.getStatus()==true){
Message.postStatus(Main.userName + "##"+ date + "##" + status.getContent(), InetAddress.getByName(friend.getHost()));
}
}
}
}catch (Exception e){}
} |
3c51aff4-c63e-48ac-96f7-9a8ae6ceb6a1 | 3 | public void fromByteArray(byte[] array) throws Exception {
int i = -1;
while (array[++i] != -1 )
namensfeld = new String(new byte[] { array[i] }, "UTF-8") + namensfeld;
String sZahl = "";
while (array[++i] != -1 )
sZahl = new String(new byte[] { array[i] }, "UTF-8") + sZahl;
zahl = Integer.parseInt(sZahl, 10);
sZahl = "";
while (array[++i] != -1)
sZahl = new String(new byte[] { array[i] }, "UTF-8") + sZahl;
geburtsdatum.setTime(Long.parseLong(sZahl, 10));
} |
2c32dabd-7c4f-40ee-9aab-1f4e0e82e8cc | 6 | public static void main(String[] args) {
// TODO Auto-generated method stub
try{
String currentPath = new java.io.File( "." ).getCanonicalPath();
if(Utility.DBG)
System.out.println("Current dir:"+currentPath);
BufferedReader br = Utility.openFileToRead(currentPath+"\\src\\Input\\Problem1");
String count = br.readLine();
if(Utility.DBG)
Utility.DEBUG(count);
PrintWriter pw = new PrintWriter(currentPath+"\\src\\Output\\Problem1"); //output file
for(int i = 0;i<Integer.parseInt(count);i++){
String line = br.readLine();
if(Utility.DBG)
Utility.DEBUG(line);
line = Utility.RemoveChars(line);
if(Utility.DBG)
Utility.DEBUG(line);
pw.println(line);
}
pw.close();
}
catch(Exception e){
e.printStackTrace();
}
} |
25ccc503-0491-4c83-bc2f-349443cebbe9 | 0 | public static void main(String[] args) {
//Primitives
boolean aBoolean = true;
char aChar = 'x';
byte aByte = 0;
short aShort = 0;
int anInt = 0;
long aLong = 0L;
float aFloat = 0.0F;
double aDouble = 0.0D;
//Boxing
Boolean aBooleanClass = aBoolean;
Character aCharClass = aChar;
Byte aByteClass = aByte;
Short aShortClass = aShort;
Integer anIntClass = anInt;
Long aLongClass = aLong;
Float aFloatClass = aFloat;
Double aDoubleClass = aDouble;
//Unboxing
boolean bool = aBooleanClass;
char ch = aCharClass;
byte b = aByteClass;
short s = aShortClass;
int i = anIntClass;
long l = aLongClass;
float f = aFloatClass;
double d = aDoubleClass;
} |
d01b9224-a088-4aa0-87ea-f801ddf4987b | 5 | public static String encode(String str) {
byte[] buffer = str.getBytes();
int a = 0, i = 0, size = buffer.length;
char[] ch = new char[((size + 2) / 3) * 4];
while (i < size) {
byte b01 = buffer[i++];
byte b12 = i < size ? buffer[i++] : 0;
byte b23 = i < size ? buffer[i++] : 0;
int mask = 0x3F;
ch[a++] = ALPHABET[(b01 >> 2) & mask];
ch[a++] = ALPHABET[((b01 << 4) | ((b12 & 0xFF) >> 4)) & mask];
ch[a++] = ALPHABET[((b12 << 2) | ((b23 & 0xFF) >> 6)) & mask];
ch[a++] = ALPHABET[b23 & mask];
}
switch (size % 3) {
case 1:
ch[--a] = '=';
case 2:
ch[--a] = '=';
}
return new String(ch);
} |
cda7d148-8bfb-43d5-8708-3b63a736564c | 7 | public boolean hasPathSum(TreeNode root, int sum){
if(root == null) return false;
LinkedList<TreeNode> nodes = new LinkedList<TreeNode>();
LinkedList<Integer> sumValu = new LinkedList<Integer>();
nodes.add(root);
sumValu.add(root.val);
while(!nodes.isEmpty()){
TreeNode currentNode = nodes.poll();
int total = sumValu.poll();
if(currentNode.left == null && currentNode.right == null && total == sum){
return true;
}
if(currentNode.left != null){
nodes.add(currentNode.left);
sumValu.add(total+currentNode.left.val);
}
if(currentNode.right != null){
nodes.add(currentNode.right);
sumValu.add(total+currentNode.right.val);
}
}
return false;
} |
bbd6a6e7-1265-4d4c-b06d-9c4e8f5bad03 | 5 | public static void main (String agrs[])
{
try
{
droneControl = new CustomDroneControl();
}
catch(Exception e)
{
if(droneControl != null)
droneControl.Abort(e);
else
e.printStackTrace();
System.exit(-1);
}
if(droneControl.isInitiated())
{
SwingUtilities.invokeLater(new Runnable() {
public void run() {
CreateJFrame();
}
});
}
keyboardCommandManager = new KeyboardCommandManager(droneControl.Drone);
KeyboardFocusManager manager = KeyboardFocusManager.getCurrentKeyboardFocusManager();
manager.addKeyEventDispatcher( new KeyEventDispatcher() {
public boolean dispatchKeyEvent(KeyEvent e)
{
if (e.getID() == KeyEvent.KEY_PRESSED)
{
keyboardCommandManager.keyPressed(e);
}
else if (e.getID() == KeyEvent.KEY_RELEASED)
{
keyboardCommandManager.keyReleased(e);
}
return false;
}
});
} |
9708a809-da72-41a7-8a9e-3a7c9a7dabad | 1 | public static byte[] compressData(String zipEntryName, byte[] data) throws IOException {
if (Utils.isCompressedPath(zipEntryName)) {
throw new IllegalArgumentException("Zip entry name must have an uncompressed file extention");
}
ByteArrayInputStream inputStream = new ByteArrayInputStream(data);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ZipOutputStream zipOutputStream = getCompressedOutputStream(zipEntryName, outputStream);
IOUtils.copy(inputStream, zipOutputStream);
zipOutputStream.flush();
zipOutputStream.finish();
return outputStream.toByteArray();
} |
699476b0-073f-4912-8653-71700e802712 | 1 | @EventHandler
public void onJoin(PlayerJoinEvent event) {
Player p = event.getPlayer();
if (FileUtil.checkPlayerDat(p)) {
event.setJoinMessage("NEW PLAYER!");
}
PlayerUtil pu = new PlayerUtil(p);
pu.updateName();
} |
d0e084a7-7bb8-4fb0-8d28-3084ae4a7bfa | 3 | protected void paintTabBackground(Graphics g, int tabPlacement, int tabIndex, int x, int y, int w, int h, boolean isSelected) {
Polygon shape = new Polygon();
shape.addPoint(x - (h / 4), y + h);
shape.addPoint(x + (h / 4), y);
shape.addPoint(x + w - (h / 4), y);
if (isSelected || (tabIndex == (rects.length - 1))) {
if (isSelected) {
g.setColor(selectedColor);
} else {
g.setColor(unselectedColor);
}
shape.addPoint(x + w + (h / 4), y + h);
} else {
g.setColor(unselectedColor);
shape.addPoint(x + w, y + (h / 2));
shape.addPoint(x + w - (h / 4), y + h);
}
g.fillPolygon(shape);
} |
c26b3a95-4036-4c49-bc91-b3b394e1ae65 | 5 | public void decrementNutrientLevels(boolean slow) {
for (Nutrient nutrient : nutrientLevels.keySet()) {
int level = nutrientLevels.get(nutrient);
if (level > (double)Config.maxNutrientLevel / 2.0 && slow)
return;
else if (level <= (double)Config.maxNutrientLevel / 2.0 && !slow)
return;
addNutrientLevel(nutrient, -1);
}
} |
abc3e606-a4a5-4ac1-86c9-2605207c9147 | 8 | public void processRoute(ArrayList<String> rout, String fileName, boolean draw,
boolean writeToFile,
Filter filter) throws IOException {
ArrayList<Point> prout = new ArrayList<Point>();
double sumKm = 0;
for (int i = 1;i < rout.size();i++) {
double y = Math.abs(points.get(rout.get(i)).lon -
points.get(rout.get(i - 1)).lon);
double x = Math.abs(points.get(rout.get(i)).lat -
points.get(rout.get(i - 1)).lat);
sumKm += Math.sqrt((y * y * 111.2 * 111.2) + (x * x * 96.3 * 96.3));
}
for (int i = 0;i < rout.size();i++)
{
prout.add(points.get(rout.get(i)));
if (cameras.contains(rout.get(i)))
{
//System.out.println(fileName + " " + "cam!");
camHaving++;
}
}
if (filter.pass(rout, this)) {
System.out.println(fileName + " sumKm : " + sumKm);
passedRoute++;
//if (draw)
// Demo.drawLines(prout, fileName);
if (writeToFile) {
output.write(new Integer(rout.size()).toString());
output.newLine();
output.write(new Double(sumKm).toString());
output.newLine();
sumsumKm += sumKm;
for (int i = 0;i < rout.size();i++) {
double km = 0;
if (i != rout.size() - 1) {
/*
double y = Math.abs(points.get(rout.get(i)).lon -
points.get(rout.get(i + 1)).lon);
double x = Math.abs(points.get(rout.get(i)).lat -
points.get(rout.get(i + 1)).lat);
km = Math.sqrt((y * y * 111.2 * 111.2) + (x * x * 96.3 * 96.3));
*/
km = this.calc(points.get(rout.get(i)).lat, points.get(rout.get(i)).lon,
points.get(rout.get(i + 1)).lat, points.get(rout.get(i + 1)).lon);
}
String str = rout.get(i);
int isCam = 0;
if (cameras.contains(str))
isCam = 1;
output.write(str + " " + points.get(str).lon + " " + points.get(str).lat +
" " + isCam + " " + km);
output.newLine();
}
}
}
} |
96e7e597-fc15-4cec-bf00-c8b503d112b8 | 7 | private void optimize(int i) {
// look to see if there is overlap like this:
// t: <---i>
// t: <----->
if (i == size - 1) {
return;
}
int j = i + 1;
while (j < size && ranges[j] <= ranges[i]) {
j += 1;
}
if (j == size) {
size = i + 1;
} else {
int d = j - i - 1;
if (d % 2 == 0) {
// t: <----i>
// t: ...
// t: <j---->
if (ranges[j] == ranges[i] + 1) {
ranges[i] = ranges[j + 1];
j += 2;
d += 2;
}
// shrink below
} else {
// t: <----i>
// t: ...
// t: <----j>
ranges[i] = ranges[j];
j++;
d++;
}
// shrink
for (int k = j; k < size; k++) {
ranges[k - d] = ranges[k];
}
size -= d;
}
} |
761588fe-b24c-4e9f-a7a5-6ae9f32ef890 | 8 | public void formatStringTwo(char[] str, int length) {
boolean isWord = false;
int wordCount = 0;
for (int i = 0; i < length; i++) {
if (str[i] != ' ' && isWord == false) {
isWord = true;
if (wordCount > 0) {
System.out.print(' ');
}
wordCount++;
System.out.print(str[i]);
} else if (str[i] == ' ' && isWord == true) {
isWord = false;
} else if (str[i] != ' ' && isWord == true) {
System.out.print(str[i]);
}
}
} |
96ff367c-7409-4ec9-b3bc-eee954e02c27 | 6 | @Override
public void action() {
RConsole.println("Ball Has been detected");
// TODO Auto-generated method stub
int increased = 0;
Color colorSensed = Sputnik.colorSensor.getColor();
int blue = colorSensed.getBlue();
int red = colorSensed.getRed();
while (blue > 80 || red > 80) {
PathFollowing.ball = true;
Sputnik.pilot.stop();
detectedBalls++;
if (blue > 80) {
Sound.buzz();
Sputnik.robotMap.setBall();
} else if (red > 80) {
Sound.beepSequenceUp();
Sputnik.robotMap.setBall();
if (increased == 0) {
count_red++;
if (count_red == 1) {
System.exit(0);
}
increased = 1;
}
}
Thread.yield();
colorSensed = Sputnik.colorSensor.getColor();
blue = colorSensed.getBlue();
red = colorSensed.getRed();
}
} |
661663e8-16e4-416e-ac6b-00aed048dbfb | 5 | public static ArrayList<Song> download(long time, String userName, ArrayList<Song> songs)
{
ArrayList<Song> allSongs=songs;
ArrayList<String> dates= new ArrayList<String>();
ArrayList<String> names= new ArrayList<String>();
ArrayList<String> artists = new ArrayList<String>();
Elements dateList;
Elements nameList;
Elements artistList;
String lastDate;
String user= userName;
long cutOff=time;
// String user="rck24";
// String apiKey="2f8ae0c603413f99dd8e7d92a5bb430c";
TimeCalculator calc= new TimeCalculator();
System.out.println("Going to try and download your listening history now.");
try{
Document doc= Jsoup.connect("http://ws.audioscrobbler.com/2.0/?method=user.getrecenttracks&limit=200&user="+user+"&from="+cutOff+"&api_key=2f8ae0c603413f99dd8e7d92a5bb430c").get();
while(doc.hasText()){
dateList=doc.getElementsByTag("date");
nameList=doc.getElementsByTag("name");
artistList=doc.getElementsByTag("artist");
for(int i=0; i<dateList.size(); i++){
Element date= dateList.get(i);
Element name= nameList.get(i);
Element artist= artistList.get(i);
Node dateUnWrapped= date.unwrap();
Node nameUnWrapped=name.unwrap();
Node artistUnWrapped= artist.unwrap();
dates.add(dateUnWrapped.toString());
names.add(nameUnWrapped.toString());
artists.add(artistUnWrapped.toString());
}
if(dates.size()>0)
{
lastDate=dates.get(dates.size()-1);
System.out.println(lastDate);
lastTime=calc.calculte(lastDate);
String url="http://ws.audioscrobbler.com/2.0/?method=user.getrecenttracks&limit=200&user="+user+"&from="+cutOff+"&to="+lastTime+"&api_key=2f8ae0c603413f99dd8e7d92a5bb430c";
doc= Jsoup.connect(url).get();
}
else
{
System.out.println("Error with downloading dates.");
break;
}
}
System.out.println("Finnished downloading your listening history.");
System.out.println("Now preparing your library.");
getSongLibrary(allSongs, dates, names, artists);
} catch(Exception e){
System.out.println("Last.fm connection error");
lastTime=time;
}
if(dates.size()==0)
{
lastTime= time;
}
return allSongs;
} |
868b4aef-bc3a-4bdd-b3c0-31252a9f7a65 | 3 | @Override
public boolean delete(String question) {
// Man skal have valgt et spil for at kunne tilføje et spørgsmål
if (currentgame == null)
{
return false;
}
for (int i = 0; i < currentgame.getQuestions().size(); i++) {
if (question.equals(currentgame.getQuestions().get(i).getQuestion())) {
currentgame.getQuestions().remove(i);
return true;
}
}
return false;
} |
64d2b4fe-b780-4eed-9b3e-1b777185c7c4 | 1 | public static void main(String[] args) throws InterruptedException {
//creating Random numbers
Random random = new Random();
for (int i = 0; i < 10; i++) {
System.out.println("Integer random is: " + random.nextInt(10));
}
//semaphore , number of permits
Semaphore sem = new Semaphore(1);
sem.acquire();
sem.release();
sem.acquire();
System.out.println("Available Permits " + sem.availablePermits());
} |
5cc9e327-7b91-4315-8efd-87d23acc2f05 | 3 | private Link generateRandomizedGameLink(EntityManager em, Player player) {
Link outputLink = new Link("", "");
ArrayList<Long> friendIDs = player.getFriendList();
// You need at least 5 friends to play and generate a valid link
if (friendIDs.size() <= 4) {
outputLink.setHref("index.html");
outputLink
.setOnClickMethod("(function (){alert('You do not have enough friends to play the game.');return false;});");
em.persist(outputLink);
return outputLink;
}
Random randomGenerator = new Random();
ArrayList<Long> randomFriendIDs = new ArrayList<Long>();
ArrayList<User> friendUsers = new ArrayList<User>();
// Get 5 friendIDs from the list at random
for (int index = 0; index <= 4; ++index) {
// Grab a random integer from 0 to [friendIDs.size() - 1]
int randomInt = randomGenerator.nextInt(friendIDs.size());
// Use randomInt as the index in the friendIDs list as the next
// friend to use
// Make sure that friend hasn't been used in the link already
// though.
if (randomFriendIDs.contains(friendIDs.get(randomInt))) {
index--; // Repick this gameLink index, the friend's been used
// already
} else {
randomFriendIDs.add(friendIDs.get(randomInt));
friendUsers.add(getUserByFacebookID(em,
friendIDs.get(randomInt)));
}
}
// Now that we have the 5 friends to use, we'll display the images of
// the first 3
ArrayList<Long> friendImageIDs = new ArrayList<Long>();
friendImageIDs.add(randomFriendIDs.get(0));
friendImageIDs.add(randomFriendIDs.get(1));
friendImageIDs.add(randomFriendIDs.get(2));
// And re-randomize all 5 names to display at the top to make this a
// game
Collections.shuffle(friendUsers);
ArrayList<String> friendUserNames = new ArrayList<String>();
friendUserNames.add(friendUsers.get(0).getName());
friendUserNames.add(friendUsers.get(1).getName());
friendUserNames.add(friendUsers.get(2).getName());
friendUserNames.add(friendUsers.get(3).getName());
friendUserNames.add(friendUsers.get(4).getName());
outputLink.setHref("playGame.html?playerID="
+ player.getPlayerInfo().getFacebookID() + "&playerName="
+ player.getPlayerInfo().getName() + "&playerPoints="
+ player.getPoints() + "&friendIDList="
+ printList(friendImageIDs) + "&friendNameList="
+ printList(friendUserNames));
em.persist(outputLink);
em.flush();
return outputLink;
} |
beb5c160-e6fc-4d56-b983-f0fcec92ce81 | 9 | @Override
public void detectRelationships(Obituary obit) throws Exception {
List<List<Term>> sentences = extractor.tagEntities(obit);
for (List<Term> sentence : sentences) {
sentence = EntityUtils.combineEntities(sentence);
chunker.addBIOChunks(sentence);
List<String> lines = new ArrayList<String>();
List<Term> terms = new ArrayList<Term>();
for (int i=0; i < sentence.size(); i++) {
if (EntityUtils.isPerson(sentence.get(i))) {
lines.add(encodeTerm(sentence, i, null, false));
terms.add(sentence.get(i));
}
}
for (int i=0; i < lines.size(); i++) {
String name = terms.get(i).getText().replaceAll("_", " ");
Map<String,Double> prediction = model.getPredictions(lines, i);
String maxType = null;
double maxScore = 0.0d;
for (String key : prediction.keySet()) {
if (prediction.get(key) > maxScore) {
maxScore = prediction.get(key);
maxType = key;
}
}
if (maxType.equals("PARENT"))
obit.addParent(name);
else if (maxType.equals("SPOUSE"))
obit.addSpouse(name);
else if (maxType.equals("CHILD"))
obit.addChild(name);
}
}
} |
ea3c4f44-ea37-481a-b1de-dad213eb3e41 | 5 | public static void main(String[] args) throws IOException
{
BufferedInputStream bis = new BufferedInputStream(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = readInt(bis);
int r = 0;
TreeSet<Integer> a = new TreeSet<>();
for (int i = 0 ; i < n ; i++){
int y = readInt(bis);
a.add(y);
}
int max = a.last();
int min = a.first();
int m = readInt(bis);
for (int j = 0 ; j < m ; j ++){
int t = readInt(bis);
if ((t<=max)||(t>=min))
if (a.contains(t)){
r++;
}
}
out.println(r);
out.flush();
} |
1bea5f6b-60d4-4d72-95f4-daeefa545c3c | 0 | protected boolean isFinished() {
return false;
} |
a2f24d17-f7ca-4d20-82fe-cb9d6913b8e0 | 7 | public String getState()
{
if(type == 0 && hasFood)
{
return "<state>"+x+" "+y+" food hasFood</state>";
}
if(type == 2 && !doorOpen)
{
return "<state>"+x+" "+y+" door doorClosed</state>";
}
if((type == 0 || type == 2) && ant != null)
{
return "<state>"+x+" "+y+" antId "+ant.getId()+"</state>";
}
return "";
} |
eb6a2480-0fa3-4cf4-882c-60eabe2e3d3f | 8 | static final public void NonNewArrayExpr() throws ParseException {
if (jj_2_7(3)) {
Literal();
NonNewArrayExpr2();
} else if (jj_2_8(3)) {
jj_consume_token(THIS);
NonNewArrayExpr2();
} else if (jj_2_9(3)) {
jj_consume_token(LP);
Expression();
jj_consume_token(RP);
NonNewArrayExpr2();
} else if (jj_2_10(3)) {
jj_consume_token(NEW);
jj_consume_token(ID);
ActualArgs();
NonNewArrayExpr2();
} else if (jj_2_11(3)) {
jj_consume_token(ID);
ActualArgs();
NonNewArrayExpr2();
} else if (jj_2_12(3)) {
jj_consume_token(SUPER);
jj_consume_token(DOT);
jj_consume_token(ID);
ActualArgs();
NonNewArrayExpr2();
} else if (jj_2_13(3)) {
ArrayExpr();
NonNewArrayExpr2();
} else if (jj_2_14(3)) {
FieldExpr();
NonNewArrayExpr2();
} else {
jj_consume_token(-1);
throw new ParseException();
}
} |
4c2bf971-bbdd-4635-addc-e1c688fe2835 | 7 | private void draw()
{
Plot2DPanel plot = new Plot2DPanel();
Color[] couleurs = new Color[]{Color.red,Color.blue,Color.ORANGE,Color.green,Color.yellow};
plot.removePlotToolBar();
plot.addLegend("SOUTH");
plot.getAxis(0).setLabelText("X");
plot.getAxis(1).setLabelText("Y");
Map droites = new HashMap();
/*Vector<String> equations=new Vector();
equations.add("x1+x2=150");
equations.add("4x1+2x2=440");
equations.add("x1+4x2=480");
equations.add("x1=90");
Vector<Vector<Double>> valeurs = new Vector();
Vector<Double> val_eq = new Vector();
val_eq.add(1d);
val_eq.add(1d);
val_eq.add(150d);
valeurs.add(val_eq);
val_eq = new Vector();
val_eq.add(4d);
val_eq.add(2d);
val_eq.add(440d);
valeurs.add(val_eq);
val_eq = new Vector();
val_eq.add(1d);
val_eq.add(4d);
val_eq.add(480d);
valeurs.add(val_eq);
val_eq = new Vector();
val_eq.add(1d);
val_eq.add(0d);
val_eq.add(90d);
valeurs.add(val_eq);*/
plot.setFixedBounds(0, 0,200);
plot.setFixedBounds(1, 0,200);
double max =0;
for(int i=0;i<equations.size();i++)
{
if(valeurs.get(i).get(0)==0)
{
droites.put(equations.get(i),new double[][]{
{plot.plotCanvas.base.getMinBounds()[0],(valeurs.get(i).get(2)!=0)?(double)valeurs.get(i).get(2):0},
{plot.plotCanvas.base.getMaxBounds()[0],(double)valeurs.get(i).get(2)}
});
}else if(valeurs.get(i).get(0)==0)
{
droites.put(equations.get(i),new double[][]{
{(valeurs.get(i).get(2)!=0)?(double)valeurs.get(i).get(2):0,0},
{(double)valeurs.get(i).get(2),plot.plotCanvas.base.getMaxBounds()[0]}
});
}
else
{
droites.put(equations.get(i),new double[][]{
/*{0,(valeurs.get(0).get(2)!=0)?(double)valeurs.get(i).get(2)/valeurs.get(i).get(1):0},
{(valeurs.get(0).get(2)!=0)?(double)valeurs.get(i).get(2)/valeurs.get(i).get(0):0,0}*/
{(valeurs.get(i).get(2)!=0)?(double)valeurs.get(i).get(2)/valeurs.get(i).get(0):0,plot.plotCanvas.base.getMinBounds()[1]},
{(valeurs.get(i).get(2)!=0)?(double)(valeurs.get(i).get(2)-(plot.plotCanvas.base.getMaxBounds()[1]*valeurs.get(i).get(1)))/valeurs.get(i).get(0):0,plot.plotCanvas.base.getMaxBounds()[1]}
});
}
out.println("Equation : "+equations.get(i)+" coordonnées : "+((double[][])droites.get(equations.get(i)))[0][0]+","+((double[][])droites.get(equations.get(i)))[0][1]+" "+((double[][])droites.get(equations.get(i)))[1][0]+","+((double[][])droites.get(equations.get(i)))[1][1]);
plot.addLinePlot(equations.get(i),couleurs[i],((double[][])droites.get(equations.get(i)))[0],((double[][])droites.get(equations.get(i)))[1]);
max = Math.max(max,Math.max(Math.max(((double[][])droites.get(equations.get(i)))[0][0],((double[][])droites.get(equations.get(i)))[0][1]),Math.max(((double[][])droites.get(equations.get(i)))[1][0],((double[][])droites.get(equations.get(i)))[1][1])));
}
out.println("Le plus grand nombre : "+max);
plot.setFixedBounds(0, 0,200);
plot.setFixedBounds(1, 0,200);
//plot.setAutoBounds();
this.setContentPane(plot);
this.setVisible(true);
} |
1115c181-308b-44dc-bd15-fa0551387b34 | 7 | protected void loadCatalystActivity() {
String name = "CatalystActivity";
String fileName = dirName + name + ".txt";
if (verbose) Timer.showStdErr("Loading " + name + " from '" + fileName + "'");
int i = 1;
for (String line : Gpr.readFile(fileName).split("\n")) {
// Parse line
String rec[] = line.split("\t");
String id = rec[0];
String entityId = rec[1];
if (id.equals("DB_ID")) continue; // Skip title
// Add event to pathway
CatalystActivity reaction = (CatalystActivity) entityById.get(id);
if (reaction == null) continue; // Reaction not found? Skip
Entity e = getOrCreateEntity(entityId);
reaction.addInput(e);
if (verbose) Gpr.showMark(i++, SHOW_EVERY);
}
if (verbose) System.err.println("");
if (verbose) Timer.showStdErr("Total catalyst entities assigned: " + (i - 1));
} |
00fa2d17-3a7f-42fd-ae53-fea57f8f621d | 7 | public boolean sendMessageToServer(String message) {
InetAddress serverAddr;
try {
serverAddr = InetAddress.getByName(getStrServerAddress());
Socket sendSocket = new Socket();
sendSocket.connect(new InetSocketAddress(serverAddr, getIntServerPort()), TIMEOUT);
ObjectOutputStream oos = new ObjectOutputStream(sendSocket.getOutputStream());
ObjectInputStream ois = new ObjectInputStream(sendSocket.getInputStream());
oos.writeObject(message);
MessageLogger.log(String.format("Request sent to: %s\n", serverAddr.getHostName()));
Object response = ois.readObject();
MessageLogger.log(String.format("Response received from: %s\n", serverAddr.getHostName()));
if (response instanceof ImageMap) {
MessageLogger.log(" - Response is IMAGE LIST reply (see Table).\n");
ImageMap iMapResponse = (ImageMap) response;
System.out.println(iMapResponse.toString());
List<ImageData> iDataList = iMapResponse.getImageDataList();
for (ImageData iData : iDataList) {
bridClient.addImageToTable(iData);
}
}
else if (response instanceof String) {
String strResponse = (String) response;
if (strResponse.startsWith("SD")) {
MessageLogger.log(String.format(" - Response is STATUS reply: %s\n", strResponse));
Integer sWidth = Integer.valueOf(strResponse.substring(2, 6));
Integer sHeight = Integer.valueOf(strResponse.substring(6, 10));
Dimension dim = new Dimension(sWidth, sHeight);
sInfo.setScreenDimension(dim); // set in Model
bridClient.setScreenDimension(dim); // set in View
}
}
oos.close();
ois.close();
sendSocket.close();
return true;
}
catch (UnknownHostException e) {
MessageLogger.log(String.format("Error: Unknown Host: \"%s\"\n", e.getMessage()));
return false;
}
catch (IOException e) {
MessageLogger.log(String.format("Error: I/O Failure: \"%s\"\n", e.getMessage()));
e.printStackTrace();
return false;
}
catch (Exception e) {
MessageLogger.log(String.format("Error: \"%s\"\n", e.getMessage()));
return false;
}
} |
19848d29-eca3-4dcf-b743-d7fb907ab89f | 1 | public List<Double> getVarianceList() {
List<Double> result= new ArrayList<Double>();
double[] values= this.getVarianceArray();
for (int i= 0; i< values.length; ++i) {
result.add(Double.valueOf(values[i]));
}
return result;
} |
fd365f13-84b2-4545-94e5-f4f8be389d26 | 0 | public void setId(long id) {
this.id = id;
} |
6b83db51-8e8f-4a0f-b7b4-3806c77e37b3 | 8 | public void tick() {
Street end1 = streets.get(streets.size()-1);
for(Vehicle vdel:end1.getVehicles()) {
end1.leaveStreet(vdel);
vehicles.remove(vdel);
System.out.println("VEhicle removed: " + vdel);
}
for(Intersection i: intersections) {
i.iteratePhase();
}
for(Vehicle vehicle : vehicles){
vehicle.calcNewPos();
}
for(Vehicle v: vehicles) {
v.move();
}
if(Math.random()<NEW_CAR_RATIO) {
Street enter1 = streets.get(streets.size()-2);
// test if startpoint is free
int lane = ((int)(Math.random() * 100)) % enter1.getNumOfLanes();
Vehicle first = enter1.getFirstVehicle(lane);
if(first != null) {
if(first.getPosition().x != enter1.getLaneStart(lane).x || first.getPosition().y != enter1.getLaneStart(lane).y) {
vehicles.add(new Vehicle(streets.get(streets.size()-2),lane,"VX"));
} else {
System.out.println("WHAAAAT");
}
} else {
vehicles.add(new Vehicle(streets.get(streets.size()-2),lane,"VX"));
}
}
vehiclePanel.repaint();
controlPanel.updateTime();
} |
d5030ec3-3645-4aa5-be70-9556432b5ebf | 4 | public Alignment getAlignmentScore() {
int maxScore = Integer.MIN_VALUE;
int xMax = 0;
int yMax = 0;
for (int i = 0; i < matrixA.length; i++) {
if (matrixA[i][matrixA[i].length - 1] > maxScore) {
maxScore = matrixA[i][matrixA[i].length - 1];
xMax = i;
yMax = matrixA[i].length-1;
}
}
for (int j = 0; j < matrixA[0].length; j++) {
if (matrixA[matrixA.length-1][j] > maxScore) {
maxScore = matrixA[matrixA.length-1][j];
xMax = matrixA.length-1;
yMax = j;
}
}
return new Alignment(maxScore / (double) submatrix.multiplicationFactor, xMax, yMax);
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.