method_id stringlengths 36 36 | cyclomatic_complexity int32 0 9 | method_text stringlengths 14 410k |
|---|---|---|
39c7cd0f-3d75-47a4-9db1-b93ac9c78e1a | 1 | public static Cliente convertToCliente(ClienteDTO clienteDTO) {
if (clienteDTO == null) {
return new Cliente();
}
return new Cliente(clienteDTO.getId(), clienteDTO.getNome(), clienteDTO.getSobrenome(),
clienteDTO.getEndereco(), clienteDTO.getCep(),
clienteDTO.getDtNascimento(), clienteDTO.getTelefone());
} |
ebc96661-be1d-42e7-a8d1-9125a65441b6 | 1 | public static long getCRC32(String filename)
{
// Attempt to read the file from disk
try
{
RandomAccessFile file = new RandomAccessFile(filename, "r");
// Convert the file to a buffer
byte[] buffer = new byte[(int)file.length()];
file.read(buffer);
// Generate the CRC from the buffer
CRC32 crc = new CRC32();
crc.update(buffer);
file.close();
// Return the generated CRC
return crc.getValue();
}
catch(IOException e)
{
// If the file doesn't exist, return 0 as CRC
return 0;
}
} |
d4cace2d-fb3b-4d8a-8ec5-c38acae95863 | 3 | protected void revertButtonActionPerformed(@SuppressWarnings("unused") final ActionEvent arg0) {
for (int i = 0; i < this.fileStateTable.getSelectedRows().length; i++) {
final int rowIndex = this.fileStateTable.getSelectedRows()[i];
// We have to know the absolute path of the selected file
// Indexes of files in the AvailableTextFiles are correspond with the
// indexes of rows in our fileStateTable
final TextFile selectedFile = AvailableTextFiles.getInstance().getAvailableTextFiles().get(rowIndex);
final boolean isRevertDoneSuccessfully = SVNClient.getInstance().revert(new File(selectedFile.getAbsolutePath()));
if (isRevertDoneSuccessfully) {
try {
selectedFile.setText(TextFileUtil.getInstance().readFileAsString(selectedFile.getAbsolutePath()));
selectedFile.setInitialTextState(selectedFile.getText());
selectedFile.setChanged(false);
selectedFile.setStored(true);
selectedFile.setSvnStatus("NORMAL");
}
catch (final IOException e) {
e.printStackTrace();
}
}
}
this.fileStateTable.repaint();
} |
59297086-a624-45c9-b21e-8308981f2b5e | 3 | public HashSet<String> getIgnores(String player){
HashSet<String> ignorelist = new HashSet<String>();
sql.initialise();
ResultSet res = null;
try {
res = sql.sqlQuery("SELECT Ignoring FROM BungeeIgnores WHERE PlayerName = '"+player+"'");
} catch (SQLException e) {
e.printStackTrace();
}
try {
while(res.next()){
ignorelist.add(res.getString("Ignoring"));
}
} catch (SQLException e) {
e.printStackTrace();
}
sql.closeConnection();
return ignorelist;
} |
0ed594e2-61fe-443d-8fcb-afa6a8ff7a5d | 0 | @Override
public void speak()
{
System.out.println("The Rottweiler says (in a very deep voice) \"WOOF!\"");
} |
481eb3a6-6449-4958-a8b5-5c9d5d93cbee | 9 | public void run()
{
sendRulesToPlayers();
Connection activePlayer = players.get(0);
while(true)
{
row = null;
column = null;
row = activePlayer.received.pollLast();
System.out.println("%%%%%"+row);
column = activePlayer.received.pollLast();
System.out.println("%%%%%"+column);
activePlayer.send(YOUR_TURN);
sendMessageToPlayers(WAITING_FOR+";"+activePlayer.playerID, activePlayer);
if(row!=null && column != null){
if(!row.matches("[0-9]+") || !column.matches("[0-9]+"))
activePlayer.send(INVALID_COORDINATES);
if(used_cords.contains(row+";"+column))
activePlayer.send(CORDINATE_ALREADY_USED);
else{
activePlayer.send(OK);
used_cords.add(row+";"+column);
sendMessageToPlayers(COORIDANTES_TO_OTHER_PLAYERS+";"+activePlayer.playerID+";"+row+";"+column, activePlayer);
}
}
if(EXIT.equalsIgnoreCase(activePlayer.received.pollLast())){
players.remove(activePlayer);
sendMessageToPlayers(EXIT+";"+activePlayer.playerID, null);
activePlayer.endSender();
}
if(row!=null && column!=null)
activePlayer = nextPlayer(activePlayer);
}
} |
14c996f6-4535-4bd3-8c51-a0392dc5c803 | 3 | public ReleaseType getLatestType() {
this.waitForThread();
if (this.versionType != null) {
for (ReleaseType type : ReleaseType.values()) {
if (this.versionType.equals(type.name().toLowerCase())) {
return type;
}
}
}
return null;
} |
8e313142-e976-4eb1-bd65-cf5a8c1ee79d | 5 | public boolean contains(AABB other) {
return minX <= other.minX && other.maxX <= maxX && minY <= other.minY
&& other.maxY <= maxY && minZ <= other.minZ
&& other.maxZ <= maxZ;
} |
1db57c1a-5a33-4836-a086-c48adad9e9a2 | 3 | public static int poisson(double lambda) {
if (!(lambda > 0.0))
throw new IllegalArgumentException("Parameter lambda must be positive");
if (Double.isInfinite(lambda))
throw new IllegalArgumentException("Parameter lambda must not be infinite");
// using algorithm given by Knuth
// see http://en.wikipedia.org/wiki/Poisson_distribution
int k = 0;
double p = 1.0;
double L = Math.exp(-lambda);
do {
k++;
p *= uniform();
} while (p >= L);
return k-1;
} |
969369e6-c156-48fa-a4ff-1335a53a2827 | 0 | public CheckResultMessage checkF01(int day) {
return checkReport.checkF01(day);
} |
74149528-3738-4162-bf1d-7dac2e0df55b | 0 | public static String sign(byte[] data, String privateKey) throws Exception {
// 解密由base64编码的私钥
byte[] keyBytes = SecurityCoder.base64Decoder(privateKey);
// 构造PKCS8EncodedKeySpec对象
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
// KEY_ALGORITHM 指定的加密算法
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
// 取私钥匙对象
PrivateKey priKey = keyFactory.generatePrivate(pkcs8KeySpec);
// 用私钥对信息生成数字签名
Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
signature.initSign(priKey);
signature.update(data);
return SecurityCoder.base64Encoder(signature.sign());
} |
d4d68a9d-3e5c-4971-8d01-19ed94c076fa | 5 | @BeforeTest
@Test(groups = { "Random BST", "Insertion" })
public void testRandomBSTInsertion() throws DuplicateKeyException {
Integer count = 0;
Reporter.log("[ ** Random BST Insertion ** ]\n");
try {
timeKeeper = System.currentTimeMillis();
for (int i = 0; i < seed; i++) {
randomBST.put(i, randomCharArray[i]);
}
Reporter.log("Insert -- Passed : "
+ (System.currentTimeMillis() - timeKeeper) + " ms\n");
timeKeeper = System.currentTimeMillis();
for (Integer i = 0; i < seed; i++) {
try {
randomBST.put(i, 'r');
} catch (DuplicateKeyException e) {
count++;
}
}
if (count == seed) {
Reporter.log("Fake Insert -- Passed : "
+ (System.currentTimeMillis() - timeKeeper) + " ms\n");
} else {
throw new DuplicateKeyException();
}
} catch (DuplicateKeyException e) {
Reporter.log("Insertion -- Failed!!!\n");
throw e;
}
} |
2f56c9d6-e807-43df-a63d-18a271f80fe4 | 9 | */
protected void getResponseBipolarDetail(String title) {
if (title != null) {
for (int i = 0; i < bipolarQuestionList.size(); i++) {
if (bipolarQuestionList.get(i).getTitle().equals(title)) {
if (!(bipolarQuestionList.get(i).getDescription() == null
|| bipolarQuestionList.get(i).getDescription().equals("null"))) {
descriptionJtxa.setText(bipolarQuestionList.get(i).getDescription());
}
bipolarQuestionCurrent = bipolarQuestionList.get(i);
String challengeParent = "None";
responseBipolarQuestionParents = bipolarQuestion.getBipolars(fileName, BIPOLARQUESTION, teamType);
for (int j = 0; j < responseBipolarQuestionParents.size(); j++) {
if(responseBipolarQuestionParents.get(j).getId().equals(bipolarQuestionCurrent.getParentId())) {
challengeParent = responseBipolarQuestionParents.get(j).getTitle();
}
}
parentContentJlbl.setText(challengeParent); // Store parent title
parentIdJlbl.setText(bipolarQuestionCurrent.getParentId()); // Store Parent id
dialogContentJlbl.setText(bipolarQuestionCurrent.getDialogType());
playerContentJlbl.setText(bipolarQuestionCurrent.getUserId());
if (bipolarQuestionCurrent.getUserId().equals(userLogin.getName())
&& bipolarQuestionCurrent.getDialogType().equals(ACTIONPRIVATE)) {
editDetailsJbtn.setEnabled(true);
deleteActionJbtn.setEnabled(true);
} else {
editDetailsJbtn.setEnabled(false);
deleteActionJbtn.setEnabled(false);
}
break;
}
}
}
} |
e25f2451-82d3-4af3-ac4d-da1137728c53 | 4 | public Entry search_level(int slevel, String myid) {
if (slevel > level) {
return null;
}
if (slevel < 0) { // be defensive
System.err.println("oops slevel<0 " + slevel);
System.exit(1);
}
// go directly to right block:
ArrayList<Entry> block = st.elementAt(level-slevel);
// now search that block:
for( Entry p : block) {
if( p.getName().equals(myid) ){
return p;
}
}
return null;
} |
d9fb4369-9b57-4824-9719-b6f2f0b99986 | 3 | private void start() {
try {
Connection connection;
int i;
int option;
UI.printHeader();
System.out.println(connections.size() + " conexiones activas:");
System.out.println("");
for (i = 0; i < connections.size(); i++) {
connection = connections.get(i);
System.out.println((i + 1) + ") Conexión: "
+ connection.getAlias() + " Estado: " + connection.getStatus());
}
System.out.println("");
System.out.print("Elige la conexión para reactivar: ");
BufferedReader bufferRead = new BufferedReader(
new InputStreamReader(System.in));
option = Integer.parseInt(bufferRead.readLine());
connections.get(option - 1).start();
} catch (NumberFormatException e) {
UI.setError("Opción no válida");
} catch (IOException e) {
e.printStackTrace();
}
} |
51ed6a81-dc26-4cae-b02b-5c051f757178 | 1 | private Connection initDBConnection() throws SQLException {
try {
Class.forName(CLASSNAME);
con = DriverManager.getConnection(CONNECTIONSTRING);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return con;
} |
4d318388-10b8-4cd5-923d-b4cf001e6dba | 5 | public LinkedNode nthToLastElement(LinkedNode head, int elementToRemove){
//Can't remove negative element
if(elementToRemove<0){
return head;
}
LinkedNode current = head;
int size = 1;
while(current.getNext()!=null){
current=current.getNext();
size++;
}
//Can't remove an element equal to or greater than the size of linked list
if(elementToRemove>=size){
return head;
}
current = head;
for(int i=0; i<size-2-elementToRemove; i++){
current=current.getNext();
}
if(head.getNext().getNext()!=null){
current.nextNode = current.getNext().getNext();
}
else{
current.nextNode = null;
}
return head;
} |
12d5d76e-8730-4f66-89b7-71b9d20676c3 | 1 | public static String addressFichier(String addresse, String str)
{
StringBuffer res = new StringBuffer();
for (int i = 0; i < addresse.length() - str.length(); i++) {
res.append(addresse.charAt(i));
}
return res.toString();
} |
044dd24e-52b1-4db3-bf90-e66e0d4b2ee6 | 1 | @RequestMapping(value = "/speaker-room-event-list/{speakerId}", method = RequestMethod.GET)
@ResponseBody
public RoomEventListResponse speakerRoomEventList(
@PathVariable(value = "speakerId") final String speakerIdStr
) {
Boolean success = true;
String errorMessage = null;
List<RoomEvent> roomEventList = null;
Long speakerId = null;
try {
speakerId = controllerUtils.convertStringToLong(speakerIdStr, true);
roomEventList = roomEventPresenter.findRoomEventsBySpeakerId(speakerId);
} catch (UrlParameterException e) {
success = false;
errorMessage = "Speaker ID is wrong or empty";
}
return new RoomEventListResponse(success, errorMessage, roomEventList);
} |
67cb2821-20c1-4003-afdb-4077ff696ad3 | 3 | public BeanLens(String fieldName, Class<A> theType) {
for (Method m : theType.getMethods()) {
if (m.getName().toLowerCase()
.equals("get" + fieldName.toLowerCase())) {
this.getMethod = m;
}
if (m.getName().toLowerCase()
.equals("set" + fieldName.toLowerCase())) {
this.setMethod = m;
}
}
} |
7e229292-4949-4605-be5c-52071b15344d | 1 | public static void main(String[] args) {
InterfaceControlador ic;
System.out.println("Controller object created");
try
{
ic = new Controller();
System.out.println("Binding controller " + ic);
Naming.rebind("rmi://localhost/Controller", ic);
System.out.println("Controller Binded!");
}
catch(Exception e)
{
e.printStackTrace();
System.exit(1);
}
System.out.println("Controller Running!\n\n");
} |
0b0e97cc-7f8d-4474-a272-9032f47cc368 | 8 | public synchronized void publishLastSale(String product, Price p, int v) throws Exception {
String thisClass = "publishers.LastSalePublisher#publishLastSale.";
if (ExceptionHandler.checkString(product, thisClass) && ExceptionHandler.checkIntNegative(v, thisClass)
&& ExceptionHandler.checkIntZero(v, thisClass)) {
p = check(p);
if (myPublisher.getSubscribers() != null) {
HashMap<String, HashMap> subscribers = myPublisher.getSubscribers();
if (subscribers.get(product) != null) {
HashMap<String, User> users = (HashMap<String, User>) subscribers.get(product);
if (!users.isEmpty()) {
Iterator it = users.entrySet().iterator();
while (it.hasNext()) {
Map.Entry userEntry = (Map.Entry) it.next();
if (userEntry.getValue() != null) {
User u = (User) userEntry.getValue();
u.acceptLastSale(product, p, v);
}
}
TickerPublisher.getInstance().publishTicker(product, p);
}
}
}
}
} |
2d0ac645-41d2-404a-9b68-098b8923ed52 | 4 | @Override
public void update(GameContainer container, int delta) throws SlickException {
if (winner == null) {
itemEffectHandler.processDelta(delta);
players.forEach(p -> p.update(delta));
itemSpawnTimer += delta;
if (itemSpawnTimer > TPBJGConfig.ITEM_SPAWN_TIME) {
itemSpawnTimer = 0;
Item itemToAdd = null;
if (Rnd.nextBoolean())
itemToAdd = ItemGenerator.getInstance().generateRandomItem(this.gameMap);
else
itemToAdd = ItemGenerator.getInstance().generateRandomStartItem(this.gameMap);
if (Objects.nonNull(itemToAdd))
;
this.gameMap.getItemsOnMap().add(itemToAdd);
}
}
} |
1d5a1d0e-676c-452e-b5a7-93c15de3377f | 0 | public void setAlgorythmType(String type){
algorythmType = type;
} |
3adf506f-1b37-4719-8d54-d622466841aa | 2 | public int getIndex(Weapon w) {
for(int i = 0; i < this.getWeapons().length; i++) {
if(this.getWeapons()[i] == w) {
return i;
}
}
return -1;
} |
16094527-ad28-4b14-90b6-8e48191cc53f | 6 | public PermutationIterator(List<T> list, int size){
outSize = size;
totalSize = list.size();
index = new ArrayList<T>(totalSize);
current = new ArrayList<Integer>(outSize);
for(int i = 0; i < outSize; i++){
current.add(0);
}
map = new TreeMap<Integer, Integer>();
int i = 0;
for(T t : list){
if(index.contains(t)){
int n = index.lastIndexOf(t);
map.put(n + 1, map.get(n + 1) + 1);
}
else{
index.add(t);
map.put(++i, 1);
}
}
if(map.size() == 0){
next = false;
}
else if(totalSize < outSize){
next = false;
}
else{
fill(0);
ArrayList<Integer> nextCacheValue = new ArrayList<Integer>(outSize);
nextCacheValue.addAll(current);
nextCache = nextCacheValue;
if(nextCache == null){
next = false;
}
else{
next = true;
}
}
} |
15f0e335-a884-448f-91bf-e805306de5a9 | 6 | public static byte[] encrypt(byte[] data, byte[] key) {
int lenght=0;
byte[] padding = new byte[1];
int i;
lenght = 8 - data.length % 8;
padding = new byte[lenght];
padding[0] = (byte) 0x80;
for (i = 1; i < lenght; i++)
padding[i] = 0;
byte[] tmp = new byte[data.length + lenght];
byte[] bloc = new byte[8];
K = generateSubKeys(key);
int count = 0;
for (i = 0; i < data.length + lenght; i++) {
if (i > 0 && i % 8 == 0) {
bloc = encrypt64Bloc(bloc,K, false);
System.arraycopy(bloc, 0, tmp, i - 8, bloc.length);
}
if (i < data.length)
bloc[i % 8] = data[i];
else{
bloc[i % 8] = padding[count % 8];
count++;
}
}
if(bloc.length == 8){
bloc = encrypt64Bloc(bloc,K, false);
System.arraycopy(bloc, 0, tmp, i - 8, bloc.length);
}
return tmp;
} |
078d4551-be7f-4cea-830d-c653e3fbbdd3 | 8 | public static void writeMaze(PrintStream mazeStream, Set<Integer> knockdowns,
int height, int width) {
// draw maze except lower border
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
mazeStream.print("+");
// negative elements in knockdowns denote walls above or below a cell
if (!knockdowns.contains(-(j + i * width)))
mazeStream.print("-");
else
mazeStream.print(" ");
}
mazeStream.println("+");
for (int j = 0; j < width; j++)
// Positive elements in knockdowns denote walls to the left or right of a
// cell. i + j test in if is to make the entrance to the maze be the
// upper left corner.
if (!knockdowns.contains(j + i * width) && i + j != 0)
mazeStream.print("| ");
else
mazeStream.print(" ");
if (i < height - 1) // in every case except last row
mazeStream.println("|");
else
mazeStream.println(); // make maze exit in lower right corner
}
// draw bottom border
for (int i = 0; i < width; i++)
mazeStream.print("+-");
mazeStream.println("+");
} |
f347709b-9e14-4c46-be42-a8fb2c6e5a16 | 6 | @Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
Simulation other = (Simulation) obj;
if (computers == null) {
if (other.computers != null) {
return false;
}
} else if (!computers.equals(other.computers)) {
return false;
}
return true;
} |
e1e7f9c0-5450-4549-8808-9763f53e16ef | 8 | public boolean exportSammellastschrift(
List<DataLastschriftMandat> lastschriften,
BeitragSammelLastschrift sl) {
// Gibt an, ob bisher alle Sammellastschriften erfolgreich an Hibiscus
// übergeben wurden
boolean allSuccessful = true;
SqlSession session = sqlSessionFactory.openSession();
try {
// Client-Config erzeugen
XmlRpcClientConfigImpl config = new XmlRpcClientConfigImpl();
// config.setBasicPassword(<Master-Passwort>);
// config.setBasicUserName("admin");
config.setServerURL(new URL(url));
config.setEnabledForExtensions(true);
config.setEncoding("ISO-8859-1");
XmlRpcClient client = new XmlRpcClient();
client.setConfig(config);
List<Map<String, Object>> buchungenRcur = new LinkedList<>();
List<Map<String, Object>> buchungenFrst = new LinkedList<>();
MandateMapper mapper = session.getMapper(MandateMapper.class);
for (DataLastschriftMandat ls : lastschriften) {
BeitragLastschrift lastschrift = ls.getLastschrift();
BeitragSepaMandat mandat = ls.getMandat();
Map<String, Object> params = new HashMap<>();
params.put("blz", mandat.getBic());
params.put("kontonummer", mandat.getIban());
params.put("name",
MyStringUtils.replaceUmlauts(mandat.getKontoinhaber()));
params.put("betrag", formatBetrag(lastschrift.getBetrag()
.negate()));
params.put("verwendungszweck", MyStringUtils
.replaceUmlauts(lastschrift.getVerwendungszweck()));
params.put("mandateid",
mrefPrefix + Integer.toString(mandat.getMandatId()));
params.put("creditorid", creditorId);
params.put("sigdate", formatDate(mandat.getDatum()));
// Sequenztyp bestimmen (dazu wird überprüft, ob bereits eine
// Lastschrift von diesem Mandat gezogen wurde)
if (mapper.isMandatUsed(ls.getMandat().getMandatId())) {
buchungenRcur.add(params);
} else {
buchungenFrst.add(params);
}
}
// Objekt zur Übergabe an Hibiscus vorbereiten
Map<String, Object> params = new HashMap<>();
params.put("konto", kontoId);
params.put("termin", formatDate(sl.getFaelligkeit()));
params.put("sepatype", sepatype);
params.put("targetdate", formatDate(sl.getFaelligkeit()));
if (!buchungenFrst.isEmpty()) {
params.put("name", "FRST - " + sl.getBezeichnung());
params.put("sequencetype", "FRST");
params.put("buchungen", buchungenFrst);
// Aufruf der RPC-Funktion
Object result = client.execute(
"hibiscus.xmlrpc.sepasammellastschrift.create",
new Object[] { params });
// Rückgabe überprüfen
if (result != null) {
logger.log(Level.WARNING,
"Fehler beim Senden an Hibiscus (FRST): " + result);
allSuccessful = false;
}
}
if (!buchungenRcur.isEmpty()) {
params.put("name", "RCUR - " + sl.getBezeichnung());
params.put("sequencetype", "RCUR");
params.put("buchungen", buchungenRcur);
// Aufruf der RPC-Funktion
Object result = client.execute(
"hibiscus.xmlrpc.sepasammellastschrift.create",
new Object[] { params });
// Rückgabe überprüfen
if (result != null) {
logger.log(Level.WARNING,
"Fehler beim Senden an Hibiscus (RCUR): " + result);
allSuccessful = false;
}
}
return allSuccessful;
} catch (MalformedURLException e) {
logger.log(Level.SEVERE, "Invalid URL for Hibiscus export", e);
} catch (XmlRpcException e) {
logger.log(Level.SEVERE,
"Error in XML-RPC call for Hibiscus export", e);
} finally {
session.close();
}
return false;
} |
516b931b-5961-4dc5-8af3-f1732ee5d099 | 4 | @Override
public void paint(Graphics g)
{
g.setColor(Color.BLACK);
g.fillRect(0,0,getWidth(),getHeight());
Rectangle r = g.getClipBounds();
g.setColor(Color.WHITE);
g.fillRect(r.x,0,KEYLENGTH,getHeight());
g.setColor(Color.BLUE);
for (int y = 0, keyIndBase = 0; y < getHeight(); y += BARHEIGHT * 12, keyIndBase += 12)
{
for (int yy = y, yo = 0; yo < octaveKeys.length; yy += octaveKeys[yo++])
reJava.Draw.drawLightKey(g,r.x,yy,KEYLENGTH,octaveKeys[yo],
(keyIndBase + lightKeyNum[yo] == highlightedKey),
(keyIndBase + lightKeyNum[yo] == depressedKey),2);
int yy = y + BARHEIGHT;
for (int i = 0; i < 3; ++i, yy += BARHEIGHT * 2)
reJava.Draw.drawDarkKey(g, r.x,yy,DARKKEYLENGTH,BARHEIGHT,
(keyIndBase + darkKeyNum[i] == highlightedKey),
(keyIndBase + darkKeyNum[i] == depressedKey),2,2,4,2);
yy += BARHEIGHT;
for (int i = 0; i < 2; ++i, yy += BARHEIGHT * 2)
reJava.Draw.drawDarkKey(g, r.x,yy,DARKKEYLENGTH,BARHEIGHT,
(keyIndBase + darkKeyNum[i+3] == highlightedKey),
(keyIndBase + darkKeyNum[i+3] == depressedKey),2,2,4,2);
}
} |
b5ad5dbb-42f4-4127-9552-4076a9635a1d | 7 | private void writeNumber ( int side, int ln, long numb, boolean FF )
{
long r = numb;
byte[] g = new byte[ln];
for(int i=0, l=ln;l>0;l--)
{
if(side>0) r=(l==1? numb : numb>>((l-1)<<3) );
int b = (int)((FF && numb==-1) ? 0xff : (r & 0xff));
g[i++]=(byte)b;
if(side==0) r>>=8;
}
try { fidx.write(g); }
catch (IOException e) { e.printStackTrace(); }
} |
b399fcba-0e5f-4f38-856b-5f8a0b7311eb | 4 | public void putRunBits(int i, int len) throws IOException {
for (int j = len - 1; j >= 0;) {
if (bits_left != 0 || j < 8) {
putBit(i);
j--;
} else {
if (i == 0)
out.write(0x00);
else
out.write(0xFF);
j -= 8;
}
}
} |
dd4ec486-1ff3-4be5-a67b-7e1675c2d099 | 9 | public static long projectEulerNumber43() {
long sum = 0;
long startNum = 1406357289;
long endNum = 1406357289;
for (long i = startNum; i <= endNum; i++) {
if (!isPandigital(i)) {
continue;
}
long d1 = i / 1000000000l;
long d2 = (i - (d1 * 1000000000l)) / 100000000l;
long d3 = (i - (d2 * 100000000l)) / 10000000l;
long d4 = (i - (d3 * 10000000l)) / 1000000l;
System.out.println((d2 * 100000000l));
long d5 = (i - (d4 * 1000000l)) / 100000l;
long d6 = (i - (d5 * 100000l)) / 10000l;
long d7 = (i - (d6 * 10000l)) / 1000l;
long d8 = (i - (d7 * 1000l)) / 100;
long d9 = (i - (d8 * 100l)) / 10;
long d10 = (i - (d9 * 10l)) / 1;
System.out.println(i);
System.out.print(d1);
System.out.print(d2);
System.out.print(d3);
// System.out.print(d4);
// System.out.print(d5);
// System.out.print(d6);
// System.out.print(d7);
// System.out.print(d8);
// System.out.print(d9);
// System.out.print(d10);
// System.out.println("Me");
if (Integer.parseInt(d2 + "" + d3 + "" + d4) % 2 != 0) {
continue;
}
if (Integer.parseInt(d3 + "" + d4 + "" + d5) % 3 != 0) {
continue;
}
if (Integer.parseInt(d4 + "" + d5 + "" + d6) % 5 != 0) {
continue;
}
if (Integer.parseInt(d5 + "" + d6 + "" + d7) % 7 != 0) {
continue;
}
if (Integer.parseInt(d6 + "" + d7 + "" + d8) % 11 != 0) {
continue;
}
if (Integer.parseInt(d7 + "" + d8 + "" + d9) % 13 != 0) {
continue;
}
if (Integer.parseInt(d8 + "" + d9 + "" + d10) % 17 != 0) {
continue;
}
sum += i;
}
return sum;
} |
f4cadfa8-8979-4c92-9eea-43c19fc68803 | 7 | protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Get session object.
HttpSession session = request.getSession();
// Attempt to get POJO stored inside session object.
Video_27_POJO pojo = (Video_27_POJO)session.getAttribute("pojo");
// If POJO object isn't in session object, put it in there
if(pojo == null){
pojo = new Video_27_POJO();
session.setAttribute("pojo", pojo);
}
String director = request.getParameter("director");
if(director == null){
director = "Video_27_displayPojo.jsp";
}else{
// Re-assign director to URL
if(director.equals("vid27")){
director = "Video_27_displayPojo.jsp";
}else if(director.equals("vid28")){
director = "Video_28_displayPojo.jsp";
}
}
/*
* A bit of Video 32 has to go up here.
* If you're on a video prior to that, ignore this small bit about cookies.
* You'll get here soon enough :)
*/
// create cookie
Cookie cookie = new Cookie("key", "fabulous cookie value");
// Increase shelf life of cookie (seconds)
cookie.setMaxAge(300);
// add cookie to response HTTP header
response.addCookie(cookie);
// Video 27 - 32 results generally shown in Video_27_displayPojo.jsp
request.getRequestDispatcher(director).forward(request, response);
// VIDEO 29 Stuff:
// Get ServletContext object
ServletContext context = getServletContext();
// Get attribute from context object
Integer hitCounterForSomeURL = (Integer)context.getAttribute("hitCounterForSomeURL");
if(hitCounterForSomeURL == null){
hitCounterForSomeURL = 0;
}else{
hitCounterForSomeURL++;
}
// Set an attribute on the SevletContext object
context.setAttribute("hitCounterForSomeURL", hitCounterForSomeURL);
// VIDEO 30 Stuff:
// located in Video_27_displayPojo.jsp
// Tried this but cannot do it after the servlet has been initialized:
// context.setInitParameter("adminname", "test value");
// VIDEO 32 Stuff:
// See Video_27_displayPojo.jsp
/* The following is for testing */
// Get all the cookies sent to the server in the browsers HTTP request header
Cookie[] cookies = request.getCookies();
if(cookies == null){
System.out.println("No cookies");
}else{
// Loop through cookies and display in console
for(int i = 0; i < cookies.length; i++){
String name = cookies[i].getName();
String value = cookies[i].getValue();
System.out.println("Cookie " +i +": name=" +name +", value=" +value);
}
}
} |
42c81f8e-8b11-4c52-b46c-b9f4bf60cf94 | 3 | public String mahdollisetYhdistelmatToString(){
String s="";
ArrayList<Yhdistelma> y = mahdollisetYhdistelmat();
int ind=y.size();
for(int i=0; i<y.size(); i++){
s=s+(i+1)+" - "+y.get(i).getNimi()+": "+y.get(i).getPisteet()+"p"+"\n";
if(i==y.size()-1){
s=s+"---------------------yliviivaa---------------------"+"\n";
}
}
y=yliviivattavat();
for(int i=0; i<y.size(); i++){
s=s+(ind+i+1)+" - "+y.get(i).getNimi()+": "+y.get(i).getPisteet()+"p"+"\n";
}
return s;
} |
40d601eb-111d-4966-9e71-2bc19d0a55ca | 7 | public void add(Explorable e) throws ExplorationException {
assert (e instanceof Conflict);
Conflict c = (Conflict) e;
/*
* Relative ID should always be complete, it's an ID after all.
* Therefore we throw an exception if it's too long.
*/
String relativeId = c.getRelativeId();
if (relativeId.length() > JdbcExplorablesDatabase.RELATIVE_ID_LENGTH) {
throw new ExplorationException("Explorable relative ID exceeds database column size: " + relativeId);
}
/*
* Comment length should be controlled in the UI layer, not allowing the
* user to exceed the limit. Therefore here we can safely throw an
* exception if it's too long.
*/
String comment = c.getComment();
if (comment != null && comment.length() > COMMENT_LENGTH) {
throw new ExplorationException("Conflict's comment length exceeds database column size: " + comment);
}
try {
stmtInsertConflict.setInt(1, c.getId()); // id
stmtInsertConflict.setInt(2, c.getParentId()); // parentId
if (c.getReference() == null) { // referenceId
stmtInsertConflict.setNull(3, Types.INTEGER);
} else {
stmtInsertConflict.setInt(3, c.getReference().getId());
}
if (c.getActual() == null) { // actualId
stmtInsertConflict.setNull(4, Types.INTEGER);
} else {
stmtInsertConflict.setInt(4, c.getActual().getId());
}
stmtInsertConflict.setShort(5, (short) c.getType().ordinal()); // conflictType
if (comment == null) { // comment
stmtInsertConflict.setNull(6, Types.VARCHAR);
} else {
stmtInsertConflict.setString(6, comment);
}
stmtInsertConflict.executeUpdate();
} catch (SQLException ex) {
throw new ExplorationException("Unable to insert conflict to database: " + c, ex);
}
} |
3d79378f-579b-4427-b811-5c40d0a6d2da | 6 | public int countBonusFromIngwer(GameBoard gb) throws Exception {
int bonusCount = 0;
try {
bonusCount += getValue(gb, new Coordinates(1, 1));
bonusCount += getValue(gb, new Coordinates(boardSize, 1));
bonusCount += getValue(gb, new Coordinates(1, boardSize));
bonusCount += getValue(gb, new Coordinates(boardSize, boardSize));
bonusCount *= cornerBonus;
int edgebonus = 0;
int val = 0;
for (int x = 1; x <= boardSize; x++) {
val = getValue(gb, new Coordinates(x, 1));
if (val > 0) {
edgebonus++;
}
val = getValue(gb, new Coordinates(x, boardSize));
if (val > 0) {
edgebonus++;
}
val = getValue(gb, new Coordinates(1, x));
if (val > 0) {
edgebonus++;
}
val = getValue(gb, new Coordinates(boardSize, x));
if (val > 0) {
edgebonus++;
}
}
bonusCount += edgebonus;
} catch (Exception e) {
}
return bonusCount;
} |
ed0b0404-4d04-4325-924f-8dc2472dfe63 | 7 | public static int addReverse(Node a, Node b, int carry, String work){
System.out.println("Work : " + work);
if (a != null && b != null){
int digit = a.data + b.data + carry;
int c = 0;
if (digit >= 10){
digit = digit%10;
}
addReverse(a.next, b.next,c, Integer.toString(digit) + work);
}
if (a != null && b == null){
addReverse(a.next, b,0, Integer.toString(a.data) + work);
}
if (a == null && b != null){
addReverse(a,b.next,0, Integer.toString(b.data) + work);
}
return Integer.parseInt(work);
} |
ee92d2c1-7db7-4895-81da-b4c27b40a3b7 | 1 | public void update() {
mapX += velocityX;
mapY += velocityY;
velocityY -= 0.25f;
if (pixelizeManager.checkForBlock(getCenterPoint()) != 0) {
isDirty = true;
}
} |
218486bf-d3c8-49d2-a84f-41ab23130fc9 | 2 | public static List<Entreprise> selectEntreprise() throws SQLException {
String query = null;
List<Entreprise> entreprise = new ArrayList<Entreprise>();
ResultSet resultat;
try {
query = "SELECT * from ENTREPRISE order by ENTNOM";
PreparedStatement pStatement = (PreparedStatement) ConnectionBDD.getInstance().getPreparedStatement(query);
resultat = pStatement.executeQuery(query);
while (resultat.next()) {
// System.out.println(resultat.getString("PAYS"));
Entreprise ee = new Entreprise(resultat.getInt("ID_ENTREPRISE"),resultat.getInt("ID_VILLE"), resultat.getString("ENTNOM"), resultat.getString("ENTADRESSE1"), resultat.getString("ENTADRESSE2"));
entreprise.add(ee);
}
} catch (SQLException ex) {
Logger.getLogger(RequetesEntreprise.class.getName()).log(Level.SEVERE, null, ex);
}
return entreprise;
} |
4d5b5ace-37ad-4e12-8f58-bbb7497d2371 | 3 | private final static OSType determineOSType() {
final String osName = System.getProperty("os.name");
if (osName.startsWith("Windows")) {
return OSType.WINDOWS.setSubtype(osName.substring(8));
} else if (osName.startsWith("Unix") || osName.startsWith("Linux")) {
return OSType.UNIX;
}
// } else if (osName.startsWith("Linux")) {
// return OSType.LINUX;
throw new UnrecognizedOSException();
} |
c63a3499-9279-4585-9ef3-35977c991843 | 0 | public float getVelocityY() {
return dy;
} |
e374196e-43e8-4cbd-8da3-727d387b687d | 9 | public eState toContinue() {
double relNorm = gNormLast / gNormInit;
int size = values.size();
double newestVal = values.get(size - 1);
double previousVal = (size >= 10 ? values.get(size - 10) : values.get(0));
double averageImprovement = (previousVal - newestVal) / size;
// This is used to be able to reproduce results that were trained on the
// QNMinimizer before
// convergence criterea was updated.
if (useAveImprovement
&& (size > 5 && Math.abs(averageImprovement / newestVal) < TOL)) {
return eState.TERMINATE_AVERAGEIMPROVE;
}
// Check to see if the gradient is sufficiently small
if (useRelativeNorm && relNorm <= relativeTOL) {
return eState.TERMINATE_RELATIVENORM;
}
if (useNumericalZero) {
// This checks if the gradient is sufficiently small compared to x that
// it is treated as zero.
if (gNormLast < EPS * Math.max(1.0, ArrayMath.norm_1(xLast))) {
// |g| < |x|_1
// First we do the one norm, because that's easiest, and always bigger.
if (gNormLast < EPS * Math.max(1.0, ArrayMath.norm(xLast))) {
// |g| < max(1,|x|)
// Now acually compare with the two norm if we have to.
System.err
.println("Gradient is numerically zero, stopped on machine epsilon.");
return eState.TERMINATE_GRADNORM;
}
}
// give user information about the norms.
}
say(" |" + nf.format(gNormLast) + "| {" + nf.format(relNorm) + "} "
+ nf.format(Math.abs(averageImprovement / newestVal)) + " ");
return eState.CONTINUE;
} |
56ea57dc-be74-4c77-8795-8c17cc38c5d8 | 9 | static final void method220(int i, int i_0_, float[] fs, int[] is, int i_1_, float[] fs_2_, int i_3_, int i_4_, int[] is_5_, int i_6_, int i_7_, int i_8_, int i_9_) {
if (i_8_ == -5) {
anInt221++;
int i_10_ = i_9_ * i_1_ - -i_7_;
int i_11_ = i * i_3_ + i_4_;
int i_12_ = -i_0_ + i_1_;
int i_13_ = -i_0_ + i_3_;
if (is != null) {
if (fs != null) {
for (int i_14_ = 0; (i_14_ ^ 0xffffffff) > (i_6_ ^ 0xffffffff); i_14_++) {
int i_15_ = i_0_ + i_10_;
while ((i_15_ ^ 0xffffffff) < (i_10_ ^ 0xffffffff)) {
is_5_[i_11_] = is[i_10_];
fs_2_[i_11_++] = fs[i_10_++];
}
i_10_ += i_12_;
i_11_ += i_13_;
}
} else {
for (int i_16_ = 0; i_6_ > i_16_; i_16_++) {
int i_17_ = i_10_ + i_0_;
while (i_17_ > i_10_)
is_5_[i_11_++] = is[i_10_++];
i_11_ += i_13_;
i_10_ += i_12_;
}
}
} else {
for (int i_18_ = 0; i_18_ < i_6_; i_18_++) {
int i_19_ = i_0_ + i_10_;
while ((i_10_ ^ 0xffffffff) > (i_19_ ^ 0xffffffff))
fs_2_[i_11_++] = fs[i_10_++];
i_10_ += i_12_;
i_11_ += i_13_;
}
}
}
} |
70612a13-c74d-4dea-8373-ac50b2585eb2 | 0 | @Override
public void windowClosed(WindowEvent e) {
} |
82f8b046-1e67-4cfe-82c8-c1fd63aab5bf | 8 | @Override
public boolean equals(Object eql) {
if (!(eql instanceof Parameters))
return false;
// We are dealing with an Instance of Parameters:
boolean areBlastParamsEqual = true;
for (String blastDb : getBlastDbParameters().keySet()) {
for (String iterKey : getParametersOfBlastDb(blastDb).keySet()) {
areBlastParamsEqual = areBlastParamsEqual
&& getParametersOfBlastDb(blastDb).get(iterKey).equals(
((Parameters) eql).getParametersOfBlastDb(
blastDb).get(iterKey));
}
}
return areBlastParamsEqual
&& ((Parameters) eql).getTokenScoreBitScoreWeight().equals(
this.getTokenScoreBitScoreWeight())
&& ((Parameters) eql).getTokenScoreDatabaseScoreWeight()
.equals(this.getTokenScoreDatabaseScoreWeight())
&& ((Parameters) eql).getTokenScoreOverlapScoreWeight().equals(
this.getTokenScoreOverlapScoreWeight())
&& ((Parameters) eql).getDescriptionScorePatternFactorWeight()
.equals(this.getDescriptionScorePatternFactorWeight());
} |
271241ae-51e1-47d0-aa18-856d24efd62b | 6 | protected int[] mapColumnsToProperties(ResultSetMetaData rsmd,
PropertyDescriptor[] props) throws SQLException {
int cols = rsmd.getColumnCount();
int[] columnToProperty = new int[cols + 1];
Arrays.fill(columnToProperty, PROPERTY_NOT_FOUND);
for (int col = 1; col <= cols; col++) {
String columnName = rsmd.getColumnLabel(col);
if (null == columnName || 0 == columnName.length()) {
columnName = rsmd.getColumnName(col);
}
String propertyName = columnToPropertyOverrides.get(columnName);
if (propertyName == null) {
propertyName = columnName;
}
for (int i = 0; i < props.length; i++) {
if (propertyName.equalsIgnoreCase(props[i].getName())) {
columnToProperty[col] = i;
break;
}
}
}
return columnToProperty;
} |
04a608e3-b69d-47a6-9339-a0048ec6a8f9 | 8 | public void actionPerformed(ActionEvent arg0) {
String command = arg0.getActionCommand();
System.out.println(command);
String current = screen.getText();
current = current.replaceAll("\\s+", " ");
if (current.contains("ERROR")) {
current = "";
screen.setText("");
}
if (command.equals("Calculate")){
current += " =";
try {
screen.setText(calculate(current));
} catch (TooManyValuesException e) {
screen.setText("ERROR: TOO MANY VALUES");
System.out.println(e.toString());
} catch (NumberFormatException e) {
screen.setText("ERROR: SYMBOL FORMAT");
System.out.println(e.toString());
} catch (EmptyStackException e) {
screen.setText("ERROR: TOO MANY OPERATORS");
System.out.println(e.toString());
} catch (Exception e) {
screen.setText("UNHANDLED ERROR");
System.out.println(e.toString());
}
} else if (command.equals("C")) {
// Clear screen
screen.setText("");
} else if (command.equals("_")) {
screen.setText(current + " ");
} else {
screen.setText(current + command);
}
} |
06f59608-f2ac-4fbc-8d5f-71960c2374ea | 7 | public static void randTest() {
double labelCeil = 10.0;
Double unLabel = new Double(1.0);
double fracCon = 0.3;
int numVertices = 10;
int numLabels = 3;
Random rand = new Random(1847860);
HashMap<Integer,Double> ls = new HashMap<Integer,Double>(numLabels);
for (int i=0; i < numLabels; ) {
Integer newl = new Integer(rand.nextInt(numVertices));
if (!ls.containsKey(newl)) {
ls.put(newl, new Double (rand.nextDouble()*labelCeil));
i++;
}
}
HashMap<Integer,Double> allLabels = new HashMap<Integer,Double>(numVertices);
HashMap<Integer,HashMap<Integer,Double>> weights = new HashMap<Integer,HashMap<Integer,Double>>(numVertices);
for (int i=0; i < numVertices; i++) {
Integer me = new Integer(i);
HashMap<Integer,Double> neighbors = new HashMap<Integer,Double>();
for (int j=0; j < numVertices; j++) {
if (rand.nextDouble() < fracCon) {
neighbors.put(new Integer(j), new Double(rand.nextDouble()));
}
}
weights.put(me, neighbors);
if (ls.containsKey(me)) {
allLabels.put(me, ls.get(me));
} else {
allLabels.put(me, unLabel);
}
}
HarmonicLabels harm = new HarmonicLabels();
harm.test_labels = ls;
harm.test_weights = weights;
HashMap<Integer,Double> oldLabels = allLabels;
printMap(oldLabels);
HashMap<Integer,Double> newLabels = harm.calcNewLabels(oldLabels);
double diff = getDiff(oldLabels, newLabels);
oldLabels = newLabels;
printMap(newLabels);
System.out.println(diff);
while (diff > epsilon) {
newLabels = harm.calcNewLabels(oldLabels);
diff = getDiff(oldLabels, newLabels);
oldLabels = newLabels;
printMap(newLabels);
System.out.println(diff);
}
} |
4098a419-6bca-4af1-88f7-5ffb82a36aa2 | 1 | public void setButtonGap(int gap) {
if (this.buttonGap == gap) {
return;
}
this.buttonGap = gap;
installGUI();
} |
3b382eee-ff81-4318-810d-14ee60df4d4f | 4 | public void unreadFrame() throws BitstreamException
{
if (wordpointer==-1 && bitindex==-1 && (framesize>0))
{
try
{
source.unread(frame_bytes, 0, framesize);
}
catch (IOException ex)
{
throw newBitstreamException(STREAM_ERROR);
}
}
} |
090b45c6-bb96-4277-b35d-7a43f4438f7e | 9 | public boolean checkInterleave(int idx1, int idx2, int idx3)
{
if (idx1 == -1 && idx2 == -1 && idx3 == -1)
return true;
if (idx1 >= 0 && in1.charAt(idx1) == out.charAt(idx3)
&& checkInterleave(idx1-1, idx2, idx3-1))
return true;
if (idx2 >= 0 && in2.charAt(idx2) == out.charAt(idx3)
&& checkInterleave(idx1, idx2-1, idx3-1))
return true;
return false;
} |
d303e4a0-e83f-429f-8907-3f400718cea7 | 4 | public int maxProfit(int[] prices) {
int profit =0;
if(prices.length == 0)
return 0;
int up = prices[0];
int low = prices[0];
for (int i = 0; i < prices.length ;i++ ){
if(prices[i] > up){
up = prices[i];
profit = Math.max(up- low,profit);
}
else if(prices[i] < low) {
low = prices[i];
up = low;
}
}
return profit;
} |
36c62edf-dec6-4a75-a21c-4b76de9e5f1b | 1 | public boolean method286(int arg0, int arg1, Entity entity, int arg3, int arg4, int arg5, int arg6, int arg7, int arg8, int arg9, int arg10) {
return entity == null || method287(arg0, arg7, arg10, arg8 - arg7 + 1, arg4 - arg10 + 1, arg5, arg1, arg6, entity, arg3, true, arg9, (byte) 0);
} |
8970ee1c-b654-498a-af82-15c18d7abe09 | 1 | public ByteVector putLong(final long l) {
int length = this.length;
if (length + 8 > data.length) {
enlarge(8);
}
byte[] data = this.data;
int i = (int) (l >>> 32);
data[length++] = (byte) (i >>> 24);
data[length++] = (byte) (i >>> 16);
data[length++] = (byte) (i >>> 8);
data[length++] = (byte) i;
i = (int) l;
data[length++] = (byte) (i >>> 24);
data[length++] = (byte) (i >>> 16);
data[length++] = (byte) (i >>> 8);
data[length++] = (byte) i;
this.length = length;
return this;
} |
86912911-d24d-484c-81a4-7847319400e8 | 2 | public String determineMatchWinner() {
String winner = "";
if (wins == losses) {
winner = "Tie";
} else if (wins > losses) {
winner = "User";
} else {
winner = "CPU";
}
return winner;
} |
7ed72e17-642d-4440-81df-323e102048ab | 3 | @Override
public void processWalks(final WalkArray walks, final int[] atVertices) throws RemoteException {
try {
pendingQueue.put(new WalkSubmission(walks, atVertices));
int pending = pendingQueue.size();
if (pending > 50 && pending % 20 == 0) {
logger.info("Warning, pending queue size: " + pending);
}
} catch (Exception err) {
err.printStackTrace();
}
} |
f659a9d1-dd45-4c85-b286-64d29cfc3ce4 | 3 | @Override
public void objectReceived(Object o) {
try {
NetMessage n = NetMessage.parseFrom((byte[])o);
System.out.println(n.getType().toString() + " message received");
switch (n.getType()) {
case CHAT_MESSAGE:
chatWindow.addMessage(n.getChatMessage().getMessage());
break;
case LIST_UPDATE:
chatWindow.updateChatPersonList(n.getChatList().getPersonList());
break;
default:
System.err.println("Unhandled NetMessage in ChatAgent");
break;
}
} catch (InvalidProtocolBufferException e) {
e.printStackTrace();
}
} |
85ad316d-782c-4aa4-835e-d76c36a92041 | 0 | public String getName() {
return this.name;
} |
b8d24a0e-1dc5-4841-82de-fb8de7716dfa | 0 | @Basic
@Column(name = "user_agent")
public String getUserAgent() {
return userAgent;
} |
b0228f7d-758d-4bec-820d-08e2cf497af9 | 5 | public Object getAggregateColumnValue(String table, Column column, QUERY_TYPE aggregate) throws SQLException, NoValueException{
Object res = new Object();
Statement s = DBAccess.getConnection().createStatement();
String query = "SELECT " + aggregate + "(" + column.getColumnName() + ") FROM " + table + " ;";
ResultSet r = s.executeQuery(query);
if(r.next() && res != null) {
do{
res = r.getObject(1);
}while(r.next());
} else if(res == null){
String aggVal = "";
aggVal = (aggregate == QUERY_TYPE.MAX) ? "Massimo" : "Minimo";
throw new NoValueException("Errore! - Impossibile calcolare: " + aggVal + " sulla colonna: " + column.getColumnName());
}else
throw new NoValueException("Errore! - Risultato della query vuoto, nessuna tupla!");
r.close();
return res;
} |
65bf4801-d779-4c46-afd9-09bafb043b06 | 2 | private JsonObject readFiles() throws IOException {
JsonObject json = new JsonObject();
Set<File> files = getsubFileList(this.config.getPath());
BufferedReader read = null;
for(File file :files){
JsonObject fileData = new JsonObject();
read = new BufferedReader(new FileReader(file));
int i= 1;
while(read.ready()){
fileData.addProperty(i++ + "", read.readLine());
}
json.add(file.getName(), fileData);
}
return json;
} |
5fb5464f-8d7f-477c-b2cf-09671ccbfa13 | 7 | @Override
public MOB determineMonster(MOB caster, int material)
{
final MOB victim=caster.getVictim();
final MOB newMOB=CMClass.getMOB("GenMOB");
int level=adjustedLevel(caster,0);
if(level<1)
level=1;
newMOB.basePhyStats().setLevel(level);
newMOB.basePhyStats().setAbility(13);
newMOB.baseCharStats().setMyRace(CMClass.getRace("Vine"));
final String name="a poisonous vine";
newMOB.setName(name);
newMOB.setDisplayText(L("@x1 looks enraged!",name));
newMOB.setDescription("");
CMLib.factions().setAlignment(newMOB,Faction.Align.NEUTRAL);
Ability A=CMClass.getAbility("Fighter_Rescue");
A.setProficiency(100);
newMOB.addAbility(A);
A=null;
final int classlevel=CMLib.ableMapper().qualifyingClassLevel(caster,this)-CMLib.ableMapper().qualifyingLevel(caster,this);
switch(classlevel/5)
{
case 0: A=CMClass.getAbility("Poison_Sting"); break;
case 1: A=CMClass.getAbility("Poison_Bloodboil"); break;
case 2: A=CMClass.getAbility("Poison_Venom"); break;
default: A=CMClass.getAbility("Poison_Decreptifier"); break;
}
if(A!=null)
{
A.setProficiency(100);
newMOB.addAbility(A);
}
newMOB.addBehavior(CMClass.getBehavior("CombatAbilities"));
newMOB.setVictim(victim);
newMOB.basePhyStats().setSensesMask(newMOB.basePhyStats().sensesMask()|PhyStats.CAN_SEE_DARK);
newMOB.setLocation(caster.location());
newMOB.basePhyStats().setRejuv(PhyStats.NO_REJUV);
newMOB.basePhyStats().setDamage(6+(5*(level/5)));
newMOB.basePhyStats().setAttackAdjustment(10);
newMOB.basePhyStats().setArmor(100-(30+(level/2)));
newMOB.baseCharStats().setStat(CharStats.STAT_GENDER,'N');
newMOB.addNonUninvokableEffect(CMClass.getAbility("Prop_ModExperience"));
newMOB.setMiscText(newMOB.text());
newMOB.recoverCharStats();
newMOB.recoverPhyStats();
newMOB.recoverMaxState();
newMOB.resetToMaxState();
newMOB.bringToLife(caster.location(),true);
CMLib.beanCounter().clearZeroMoney(newMOB,null);
newMOB.setStartRoom(null); // keep before postFollow for Conquest
CMLib.commands().postFollow(newMOB,caster,true);
if(newMOB.amFollowing()!=caster)
caster.tell(L("@x1 seems unwilling to follow you.",newMOB.name()));
else
{
if(newMOB.getVictim()!=victim)
newMOB.setVictim(victim);
newMOB.location().showOthers(newMOB,victim,CMMsg.MSG_OK_ACTION,L("<S-NAME> start(s) attacking <T-NAMESELF>!"));
}
return(newMOB);
} |
ded5ef82-88f1-4a01-924b-a628d6892e29 | 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(Homework_current.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Homework_current.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Homework_current.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Homework_current.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Homework_current().setVisible(true);
}
});
} |
4cbfd5d2-c9f3-47ae-8350-76dc5c14f49b | 3 | public static String compressedToString(String str)
{
String strBuild="";
if(str.charAt(1) == '1') strBuild += "Ctrl + ";
if(str.charAt(0) == '1') strBuild += "Shift + ";
if(str.charAt(2) == '1') strBuild += "Alt + ";
strBuild += KeyEvent.getKeyText(Integer.parseInt(str.substring(3)));
return strBuild;
} |
c3d74787-4f16-45a8-99a2-ee4a8520842f | 6 | protected static byte[] decrypt(byte[] encryptedData, Algorithm algorithm,
SecretKey secretKey, byte[] iv) throws JironException {
Cipher cipher;
try {
cipher = Cipher.getInstance(algorithm.transformation);
} catch (NoSuchAlgorithmException e) {
throw new JironException("Encryption algorithm "
+ algorithm.transformation + " not found", e);
} catch (NoSuchPaddingException e) {
throw new JironException("Cannot work with padding given by "
+ algorithm.transformation, e);
}
try {
cipher.init(Cipher.DECRYPT_MODE, secretKey, new IvParameterSpec(iv));
} catch (InvalidKeyException e) {
throw new JironException("Key " + secretKey.toString()
+ " is invalid", e);
} catch (InvalidAlgorithmParameterException e) {
throw new JironException(
"Initialization vector passed to cipher initialization seems to be invalid algorithm parameter",
e);
}
try {
return cipher.doFinal(encryptedData);
} catch (IllegalBlockSizeException e) {
throw new JironException("Illegal block size when decrypting", e);
} catch (BadPaddingException e) {
throw new JironException("Bad padding when decrypting", e);
}
} |
24ca5e99-4935-4b8d-bb0d-4d7e7bae846a | 9 | /* */ public String attemptingToConnectNewAccount(String username, char[] password, char[] passwordConfirm)
/* */ {
/* 160 */ if (username.length() < 3)
/* */ {
/* 162 */ return "Your username must contain at least 3 characters.";
/* */ }
/* */
/* 165 */ if (password.length < 6)
/* */ {
/* 167 */ return "Password is too short, minimum 6 characters.";
/* */ }
/* */
/* 170 */ if (!verifyPassword(password, passwordConfirm))
/* */ {
/* 173 */ System.out.println("Wrong password");
/* 174 */ return "Passwords do not match";
/* */ }
/* */
/* 178 */ Pattern p = Pattern.compile("^[0-9a-zA-Z\\s]*$");
/* 179 */ boolean hasSpecialChar = p.matcher(username).find();
/* */
/* 181 */ if (!hasSpecialChar) {
/* 182 */ return "Your username can only be letters , numbers, and spaces.";
/* */ }
/* 184 */ String actualPassword = "";
/* */
/* 186 */ for (int i = 0; i < password.length; i++)
/* */ {
/* 188 */ actualPassword = actualPassword + password[i];
/* */ }
/* */
/* */ try
/* */ {
/* 195 */ String rawStringToSend = "NEW=" + username + "," + actualPassword;
/* */
/* 197 */ byte[] encryptedBytesToSend = PublicKeyManager.encrypt(rawStringToSend, Config.PUBLIC_KEY);
/* 198 */ int byteLength = encryptedBytesToSend.length;
/* */
/* 202 */ this.socket = new Socket("38.89.137.25", 3336);
/* 203 */ DataOutputStream outputStream = new DataOutputStream(this.socket.getOutputStream());
/* 204 */ outputStream.writeInt(byteLength);
/* 205 */ outputStream.write(encryptedBytesToSend);
/* 206 */ outputStream.flush();
/* */
/* 210 */ BufferedReader in = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
/* */
/* 214 */ String serverResponse = in.readLine();
/* 215 */ System.out.println(serverResponse);
/* */
/* 217 */ if (serverResponse.equals("ERROR=Username already exsists!")) {
/* 218 */ return "This username has already been taken.";
/* */ }
/* 220 */ if (serverResponse.equals("USERCREATED")) {
/* 221 */ attemptingToConnect(username, password);
/* */ }
/* */
/* */ }
/* */ catch (UnknownHostException e)
/* */ {
/* 227 */ e.printStackTrace();
/* */ } catch (IOException e) {
/* 229 */ e.printStackTrace();
/* */ }
/* */
/* 234 */ return "";
/* */ } |
90996fd0-37d1-429e-8f79-3e6234ce1801 | 3 | public Element insertChildren(int index, Collection<? extends Node> children) {
Validate.notNull(children, "Children collection to be inserted must not be null.");
int currentSize = childNodeSize();
if (index < 0) index += currentSize +1; // roll around
Validate.isTrue(index >= 0 && index <= currentSize, "Insert position out of bounds.");
ArrayList<Node> nodes = new ArrayList<Node>(children);
Node[] nodeArray = nodes.toArray(new Node[nodes.size()]);
addChildren(index, nodeArray);
return this;
} |
779819a4-489b-405f-a325-1f3a436c2377 | 5 | public static int findMagicIndex(int[] array, int i, int j){
//Since the array is sorted, we can perform a binary search in log(n) time
//WHAT about if elements are not distinct? If elements are not distinct, this
//algorithm will not work. Instead we must iterate through each element and search
//in O(n) time
if(j < i || i < 0 || j >= array.length) return -1;
int mid = (i+j)/2;
if(array[mid] == mid) return mid;
if(array[mid] < mid) return findMagicIndex(array, mid+1, j);
else return findMagicIndex(array, i, mid-1);
} |
2dbc6708-27af-4303-8433-e65f34d07159 | 9 | public void execute() throws MojoExecutionException, MojoFailureException {
// Temp file
File tempFile = null;
try {
this.getLog().info("Starting OpenCms Local Mojo...");
this.getLog().info(
"OpenCms Zip File: " + this.getOpenCmsEnvironmentZipFile());
this.getLog().info(
"Destory Environment: " + this.isDestroyEnvironment());
this.getLog()
.info("Target Directory: " + this.getTargetDirectory());
// Check to see if environment should be destroyed
if (this.isDestroyEnvironment()) {
// Delete existing directory
if (this.getTargetDirectory().exists()) {
this.getLog().info(
"Destroying Local OpenCms Environment...");
// Clean out the directory
FileUtils.cleanDirectory(this.getTargetDirectory());
this.getLog().info(
"Target Directory contents deleted: "
+ this.getTargetDirectory().getPath());
}
}
// Check that output directory is a folder and exists
if (!this.getTargetDirectory().exists()) {
if (!this.getTargetDirectory().mkdir()) {
throw new Exception(
"Creating target directory was not successfull: "
+ this.getTargetDirectory().getPath());
}
}
// Check if starting jar already exists
if (!this.getStartupJar().exists()) {
// Create Temp FIle
tempFile = File.createTempFile("ocm", null,
this.getTargetDirectory());
if (tempFile != null) {
this.getLog().info(
"Downloading OpenCms Zip File ("
+ this.getOpenCmsEnvironmentZipFile()
+ ") to " + tempFile.getPath() + "...");
// Download
FileUtils.copyURLToFile(
new URL(this.getOpenCmsEnvironmentZipFile()),
tempFile);
this.getLog().info("OpenCms Zip File Download Complete!");
this.getLog().info(
"Unzipping " + tempFile.getPath() + " to "
+ this.getTargetDirectory().getPath());
// Unzip to target directory
ZipFile zipFile = new ZipFile(tempFile);
zipFile.extractAll(this.getTargetDirectory().getPath());
this.getLog().info(
"Unzipping " + tempFile.getPath() + " to "
+ this.getTargetDirectory().getPath()
+ " complete!");
} else {
this.getLog().error("Error creating temp file");
}
} else {
this.getLog()
.info("Startup Jar already exists so not redownloading environment zip file");
}
} catch (Exception ec) {
this.getLog().error("Error executing OpenCms Environment mojo", ec);
// Throw Mojo Execution Exception
MojoExecutionException mojoException = new MojoExecutionException(
"Error executing OpenCms Environment mojo");
mojoException.initCause(ec);
throw mojoException;
} finally {
// Delete temp file
if (tempFile != null) {
if (tempFile.exists()) {
// Delete
tempFile.delete();
this.getLog().info(
"Temp file deleted: " + tempFile.getAbsolutePath());
}
}
}
} |
f74e298e-c46d-44b0-ac5b-23bbba0207a5 | 5 | protected static List<Card> getAllFlushCards(Set<Card> cardSet) {
if (cardSet.size() < 5) {
return null;
}
// Note that we could return more than 5 cards here.
Map<Suit, List<Card>> suitMap = new HashMap<Suit, List<Card>>();
for (Card card : cardSet) {
List<Card> flushLists = suitMap.get(card.suit);
if (flushLists == null) {
flushLists = new ArrayList<Card>();
}
flushLists.add(card);
suitMap.put(card.suit, flushLists);
}
for (Suit suit : suitMap.keySet()) {
/*
* This presumes the first flush we find is the
* definitive flush. Since we don't have more than seven cards,
* two five-flush hands are impossible.
*/
if (suitMap.get(suit).size() > 4) {
Collections.sort(suitMap.get(suit));
return suitMap.get(suit);
}
}
return null;
} |
bb0565be-8edc-4b19-8b0f-1e637e2cdf76 | 1 | public static int getShort(int num, int which)
{
if(which == 0){
num = num << 16;
}
num = num >>> 16;
return num;
} |
9c5dd54f-fead-44cb-84aa-56bc6e54a3be | 1 | public static byte intToByte(int number){
return (byte) ((number<0?-number:number) & 0xff);
} |
2a8e2d34-a835-4e1f-9dfc-f7aadaaa25e5 | 4 | @Override
public void handleNotification(Object producer, String name, Object data) {
if (name == TreeNotificationKeys.ROW_REMOVED) {
for (TreeRow row : new TreeRowIterator((TreeRow[]) data)) {
mSelectedRows.remove(row);
if (row instanceof TreeContainerRow) {
mOpenRows.remove(row);
}
if (mRowHeight < 1) {
mRowHeightMap.remove(row);
}
}
}
} |
475db700-ec4a-4b14-b5cd-6ebc6ac494c5 | 4 | private void leftMouseButtonClicked(int x, int y)
{
if (!isPaused && !gameOver) {
if(this.currentPlayer!=null && this.currentSelectedBlock!=null){
setPlaceBlockFlag(true);
}
}
} |
71d2cdc8-7394-4ab5-ba9b-f06b24a53610 | 4 | @Override
public Class<?> loadClass(String name) throws ClassNotFoundException {
Class clazz;
try {
clazz = getParent().loadClass(name);
return clazz;
}
catch (ClassNotFoundException e) {
}
String classFileLocation = name.substring(name.lastIndexOf(".") + 1) + ".class";
Path path = FileSystems.getDefault().getPath(pluginLocation.getAbsolutePath(), classFileLocation);
if (!path.toFile().exists()) {
System.out.println("Unable to find class " + path);
throw new ClassNotFoundException(name);
}
byte[] bytes = null;
try {
bytes = Files.readAllBytes(path);
}
catch (IOException e) {
throw new RuntimeException(e);
}
return defineClass(name, bytes, 0, bytes.length);
} |
e11b329c-f414-44e9-a50c-c10913f7d03f | 5 | public void setLAN(Boolean x)
{
if(x!=null)
{
blLAN = x;
}
//Kill/Reset connection
if(blLAN == true && conProt == null)
{
conProt = new RCEstablishConnection(true);
conProt.setBase(me);
conProt.setName(strName);
}
if(blLAN == false && conProt != null)
{
conProt.killCurrent();
conProt = null;
}
} |
93b12dd1-c8cb-4962-aadf-4ccf5e64ac75 | 7 | public GrupoVO[] consultar (GrupoVO grupo){
String query = "SELECT * FROM grupos WHERE";
Statement consulta = Conexion.getConexion().hacerConsulta();
boolean bandera = false;
GrupoVO [] grupos = null;
if(grupo.getEnAutorizado() != null){}
if(grupo.getIdGrupo() != null){}
if(grupo.getJefeGrupo() != null){}
if(grupo.getMaxAlumnos() != null){}
if(grupo.getOrientador() != null){}
if(grupo.getTurno() != null){}
if(bandera){
query.substring(0, query.length()-4);
}else{
query.substring(0, query.length()-6);
}
query +=";";
System.out.println(query);
return grupos;
} |
148bfd2b-afd2-48b3-97c2-94b6887db0e5 | 5 | @Override
public String toString()
{
String informacio = "[Mida: " + mida + ", num. fitxes jugador A: " + num_fitxes_a + ", " +
"num. fitxes jugador B: " + num_fitxes_b + ", estat de les caselles:\n";
for ( EstatCasella[] fila : caselles )
{
informacio = informacio + "\t";
for ( EstatCasella actual : fila )
{
switch ( actual )
{
case JUGADOR_A:
informacio = informacio + "A";
break;
case JUGADOR_B:
informacio = informacio + "B";
break;
case BUIDA:
informacio = informacio + "·";
break;
}
}
informacio = informacio + "\n";
}
informacio = informacio + "]";
return informacio;
} |
a5f0a2a5-0413-4d14-9498-efb7f5e66006 | 6 | public static void main(String[] args){
try {
String name = "main2";
int num_rand;
ArrayList<JvnObjectImpl> array = new ArrayList<JvnObjectImpl>();
MonObjet o1 = new MonObjet("objet2");
JvnObjectImpl shared_object_2 = (JvnObjectImpl) JvnServerImpl.jvnGetServer().jvnCreateObject(o1);
JvnServerImpl.jvnGetServer().jvnRegisterObject("objet2", shared_object_2);
Thread.sleep(5000);
JvnObjectImpl shared_object_1 = (JvnObjectImpl) JvnServerImpl.jvnGetServer().jvnLookupObject("objet1");
JvnObjectImpl shared_object_3 = (JvnObjectImpl) JvnServerImpl.jvnGetServer().jvnLookupObject("objet3");
array.add(shared_object_1);
array.add(shared_object_2);
array.add(shared_object_3);
for(int i = 0; i < 10; i++){
for(JvnObjectImpl obj : array){
num_rand = (int) Math.round(Math.random());
switch(num_rand){
case 0 :
System.out.println("Lock write on "+obj.jvnGetObjectId()+" by "+name);
obj.jvnLockWrite();
System.out.println("Lock acquire");
((MonObjet)obj.jvnGetObjectState()).setString("lock by"+name);
Thread.sleep(1000*(num_rand+1));
obj.jvnUnLock();
System.out.println("Unlock done");
break;
case 1 :
System.out.println("Lock read on "+obj.jvnGetObjectId()+" by "+name);
obj.jvnLockRead();
System.out.println("Actual value : "+((MonObjet)obj.jvnGetObjectState()).getString());
Thread.sleep(1000*(num_rand+1));
obj.jvnUnLock();
System.out.println("Unlock done");
break;
}
}
}
JvnServerImpl.jvnGetServer().jvnTerminate();
System.out.println("YES fin du test pour "+name);
System.exit(0);
} catch (JvnException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} |
a0e2b163-2657-4c19-963f-6bd4041a6ef1 | 5 | private void waitSockClose(Sock sock) {
boolean loop = true;
Timing new_timer = new Timing();
while (loop) {
if ((sock.getSocket() == null && sock.getIn() == null && sock.getOut() == null) || new_timer.getTime() > timeout) {
loop = false;
}
}
Assert.assertEquals(sock.getSocket(), null, "Sock socket not set to null");
Assert.assertEquals(sock.getIn(), null, "Sock in not set to null");
Assert.assertEquals(sock.getOut(), null, "Sock out not set to null");
} |
f956adb8-c83b-494d-b459-415614a52111 | 5 | private Model generateTerrain(String heightMap) {
BufferedImage image = null;
try {
image = ImageIO.read(new File("assets/terrain/" + heightMap + ".png"));
} catch (IOException e) {
e.printStackTrace();
}
int vertexCount = image.getHeight();
heights = new float[vertexCount][vertexCount];
int count = vertexCount * vertexCount;
float[] vertices = new float[count * 3];
float[] normals = new float[count * 3];
float[] textureCoords = new float[count * 2];
int[] indices = new int[6 * (vertexCount - 1) * (vertexCount * 1)];
int vertexPointer = 0;
for (int i = 0; i < vertexCount; i++) {
for (int j = 0; j < vertexCount; j++) {
float height = getHeight(j, i, image);
heights[j][i] = height;
vertices[vertexPointer * 3] = (float) j / ((float) vertexCount - 1) * SIZE;
vertices[vertexPointer * 3 + 1] = height;
vertices[vertexPointer * 3 + 2] = (float) i / ((float) vertexCount - 1) * SIZE;
Vector3f normal = calculateNormal(j, i, image);
normals[vertexPointer * 3] = normal.x;
normals[vertexPointer * 3 + 1] = normal.y;
normals[vertexPointer * 3 + 2] = normal.z;
textureCoords[vertexPointer * 2] = (float) j / ((float) vertexCount - 1);
textureCoords[vertexPointer * 2 + 1] = (float) i / ((float) vertexCount - 1);
vertexPointer++;
}
}
int pointer = 0;
for (int gz = 0; gz < vertexCount - 1; gz++) {
for (int gx = 0; gx < vertexCount - 1; gx++) {
int topLeft = (gz * vertexCount) + gx;
int topRight = topLeft + 1;
int bottomLeft = ((gz + 1) * vertexCount) + gx;
int bottomRight = bottomLeft + 1;
indices[pointer++] = topLeft;
indices[pointer++] = bottomLeft;
indices[pointer++] = topRight;
indices[pointer++] = topRight;
indices[pointer++] = bottomLeft;
indices[pointer++] = bottomRight;
}
}
return new Model(vertices, indices, textureCoords, normals);
} |
78d7a131-f59d-4a69-a2cf-90a1a090ff5b | 3 | @Override
public void actionPerformed(ActionEvent e) {
OutlinerDocument doc = (OutlinerDocument) Outliner.documents.getMostRecentDocumentTouched();
OutlinerCellRendererImpl textArea = doc.panel.layout.getUIComponent(doc.tree.getEditingNode());
if (textArea == null) {
return;
}
Node node = textArea.node;
JoeTree tree = node.getTree();
OutlineLayoutManager layout = tree.getDocument().panel.layout;
if (doc.tree.getComponentFocus() == OutlineLayoutManager.TEXT) {
DeleteAction.deleteText(textArea, tree, layout);
} else if (doc.tree.getComponentFocus() == OutlineLayoutManager.ICON) {
DeleteAction.delete(tree, layout, true);
}
} |
ff65b5d7-119a-49bc-bf88-e3203f32c373 | 4 | @Override
public void messageHandler(String messageName, Object messagePayload) {
if (messagePayload != null) {
System.out.println("MSG: received by model: "+messageName+" | "+messagePayload.toString());
} else {
System.out.println("MSG: received by model: "+messageName+" | No data sent");
}
MessagePayload payload = (MessagePayload)messagePayload;
int field = payload.getField();
int direction = payload.getDirection();
if (direction == Constants.UP) {
if (field == 1) {
setVariable1(getVariable1()+Constants.FIELD_1_INCREMENT);
} else {
setVariable2(getVariable2()+Constants.FIELD_2_INCREMENT);
}
} else {
if (field == 1) {
setVariable1(getVariable1()-Constants.FIELD_1_INCREMENT);
} else {
setVariable2(getVariable2()-Constants.FIELD_2_INCREMENT);
}
}
} |
d88ea139-eb14-4394-9fa3-d1aff74783c6 | 0 | public void setId(Integer id) {
this.id = id;
} |
6805ccbd-9952-406f-99af-31562ad5a8d5 | 4 | protected Tile pickSample() {
final int range = World.SECTOR_SIZE * 2 ;
Tile picked = null ;
float bestRating = 0 ;
for (int n = 10 ; n-- > 0 ;) {
final Tile s = Spacing.pickRandomTile(this, range, world) ;
if (s == null || s.pathType() != Tile.PATH_CLEAR) continue ;
float rating = s.habitat().minerals() ;
rating /= 10 + Spacing.distance(s, this) ;
if (rating > bestRating) { picked = s ; bestRating = rating ; }
}
return picked ;
} |
2bcb022f-a965-43b4-b5e8-6bca417fd997 | 6 | public void tick(){
tickCount++;
for(cell[] p1: bitMap.Map){ // foreach grade in grades
for(cell q1: p1){
try{
q1.Resident.ready = 1;
}catch(NullPointerException e ){
}
}}
for(cell[] p: bitMap.Map){ // foreach grade in grades
for(cell q: p){
try{
q.Resident.tick();
// q.Resident.move(-1,1);
}catch(NullPointerException e ){
}
} }
//pixels[i] = i + tickCount;
//pixels[i] = i % tickCount * tickCount;
pixels = bitMap.mark();} |
8389edac-e3a0-4e05-b67c-1e5407adca5c | 8 | public static int countNeighbours(long world, int col, int row){
int total = 0;
total = getCell(world, col-1, row-1) ? total + 1 : total;
total = getCell(world, col , row-1) ? total + 1 : total;
total = getCell(world, col+1, row-1) ? total + 1 : total;
total = getCell(world, col-1, row ) ? total + 1 : total;
total = getCell(world, col+1, row ) ? total + 1 : total;
total = getCell(world, col-1, row+1) ? total + 1 : total;
total = getCell(world, col , row+1) ? total + 1 : total;
total = getCell(world, col+1, row+1) ? total + 1 : total;
return total;
} |
2d21b322-7791-478f-b14e-065a60991340 | 0 | public static void main(String[] args) {
split(" "); // Doesn't have to contain regex chars
split("\\W+"); // Non-word characters
split("n\\W+"); // 'n' followed by non-word characters
} |
92fdc96c-7d51-422a-a658-d0ed82a5af41 | 6 | private String getFile(String link)
{
String download = null;
try
{
// Open a connection to the page
URL url = new URL(link);
URLConnection urlConn = url.openConnection();
InputStreamReader inStream = new InputStreamReader(urlConn.getInputStream());
BufferedReader buff = new BufferedReader(inStream);
int counter = 0;
String line;
while((line = buff.readLine()) != null)
{
counter++;
// Search for the download link
if(line.contains("<li class=\"user-action user-action-download\">"))
{
// Get the raw link
download = line.split("<a href=\"")[1].split("\">Download</a>")[0];
}
// Search for size
else if (line.contains("<dt>Size</dt>"))
{
sizeLine = counter+1;
}
else if(counter == sizeLine)
{
String size = line.replaceAll("<dd>", "").replaceAll("</dd>", "");
multiplier = size.contains("MiB") ? 1048576 : 1024;
size = size.replace(" KiB", "").replace(" MiB", "");
totalSize = (long)(Double.parseDouble(size)*multiplier);
}
}
urlConn = null;
inStream = null;
buff.close();
buff = null;
}
catch (Exception ex)
{
ex.printStackTrace();
plugin.getLogger().warning("The auto-updater tried to contact dev.bukkit.org, but was unsuccessful.");
result = Updater.UpdateResult.FAIL_DBO;
return null;
}
return download;
} |
3cd712c9-6e42-47fa-b99d-07fe7ddf9ef8 | 4 | public static List<Archive> getPlugins() {
List<Archive> plugins = new ArrayList<Archive>();
for (File file : DIRECTORIES[0].listFiles()) {
String name = file.getName();
if (name.endsWith(".class"))
plugins.add(new ClassFile(file));
else if (name.endsWith(".jar"))
try {
plugins.add(new JavaArchive(new JarFile(file)));
} catch (IOException e) {
e.printStackTrace();
}
}
return plugins;
} |
b5719893-5a72-49a3-a2ef-f7e1fceb0cdf | 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(Principal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Principal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Principal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Principal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Principal().setVisible(true);
}
});
} |
45f6e88d-d74d-40b8-b259-1ba3a4a0d005 | 5 | public static void borderize(MapView mv, Gob player, Coord sz,
Coord border) {
if (Config.noborders) {
return;
}
Coord mc = mv.mc;
Coord oc = m2s(mc).inv();
int bt = -((sz.y / 2) - border.y);
int bb = (sz.y / 2) - border.y;
int bl = -((sz.x / 2) - border.x);
int br = (sz.x / 2) - border.x;
Coord sc = m2s(player.position()).add(oc);
if (sc.x < bl)
mc = mc.add(s2m(new Coord(sc.x - bl, 0)));
if (sc.x > br)
mc = mc.add(s2m(new Coord(sc.x - br, 0)));
if (sc.y < bt)
mc = mc.add(s2m(new Coord(0, sc.y - bt)));
if (sc.y > bb)
mc = mc.add(s2m(new Coord(0, sc.y - bb)));
mv.mc = mc;
} |
1143b1a4-1fe5-4964-9ee9-c7f168cef825 | 6 | public SourceType getSourceType(Stmt sCallSite, InterproceduralCFG<Unit, SootMethod> cfg) {
assert cfg != null;
assert cfg instanceof BiDiInterproceduralCFG;
// This might be a normal source method
if (super.isSource(sCallSite, cfg))
return SourceType.MethodCall;
// This call might read out sensitive data from the UI
if (isUISource(sCallSite, cfg))
return SourceType.UISource;
// This statement might access a sensitive parameter in a callback
// method
if (sCallSite instanceof IdentityStmt) {
IdentityStmt is = (IdentityStmt) sCallSite;
if (is.getRightOp() instanceof ParameterRef)
for (AndroidMethod am : this.callbackMethods)
if (am.getSignature().equals(cfg.getMethodOf(sCallSite).getSignature()))
return SourceType.Callback;
}
return SourceType.NoSource;
} |
f8923421-a754-4a4b-926a-721e3bf146f5 | 8 | public Object down(Event evt) {
switch(evt.getType()) {
case Event.VIEW_CHANGE:
View view=evt.getArg();
handleView(view);
break;
case Event.SET_LOCAL_ADDRESS:
local_addr=evt.getArg();
break;
case Event.CONNECT:
case Event.CONNECT_USE_FLUSH:
case Event.CONNECT_WITH_STATE_TRANSFER:
case Event.CONNECT_WITH_STATE_TRANSFER_USE_FLUSH:
local_host=getHostFor(local_addr);
break;
case Event.DISCONNECT:
Object retval=down_prot.down(evt);
local_host=null;
return retval;
case Event.UNSUSPECT:
Address mbr=evt.getArg();
unsuspect(mbr);
break;
}
return down_prot.down(evt);
} |
7182b4d0-df9a-4d6f-a7e0-b04ef0c4d653 | 5 | public void checkCustomUp(Node node) {
this.up = -1; // reset value to -1
// Prevent out of bounds (negative coordinates)
if((node.getX()-2) >= 0) {
if(checkWall(new Node( (node.getX()-2), (node.getY()) ))) {
if(this.closedNodes.size()==0)
this.up = 1;
else {
for(int i = 0; i < this.closedNodes.size(); i++) {
// Check with closed nodes to differenciate explored or not
if(new Node(node.getX()-2, node.getY()).compareTo(this.closedNodes.get(i))==1) {
this.up = 2; // explored node
break;
}
else
this.up = 1; // empty
}
}
} else {
this.up = 0; // set 0 to specify as wall
}
}
} |
2cfb9d57-9038-4906-9ec3-09c387603421 | 6 | @Override
public boolean equals(Object other){
if(other == null || other.getClass() != getClass())
return false;
if(other == this)
return true;
Movie otherMovie = (Movie)other;
if(name.equals(otherMovie.name) && director.equals(otherMovie.director) && rating == otherMovie.rating)
return true;
return false;
} |
e506fe94-7b1b-427f-ab24-be6f1493ade7 | 1 | public int resend(int clientId, int originalMessageId, String message) throws CouldNotSendPacketException {
synchronized(CONNECTION_LOCK) {
Packet packet = Packet.createApplicationPacket(clientId, message);
packet.setDuplicateSequenceNumber(originalMessageId);
//if the client isn't connected then throw an exception
if(!clients.containsKey(clientId)) {
logger.fine("Could not resend message to client " + clientId + ": Client not connected.");
throw new ClientNotConnectedException(clientId, packet);
}
logger.fine("Resending message to client " + clientId + ": " + message);
ClientInfo client = clients.get(clientId);
return sendPacket(packet, client);
}
} |
00c7e4ef-c571-4888-b7ca-3b03256b40ac | 3 | public void start() throws TooManyListenersException {
if (isStarted()) {
throw new TooManyListenersException();
}
setStarted(true);
Thread engine = new Thread() {
@Override
public void run() {
Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
Listener.getInstance().listen();
while (true) {
TaskController.getSingleton().sortTasks();
EventExecutor.getSingleton().executeEvents();
try {
Thread.sleep(250);
} catch (InterruptedException ex) {
Logger.getLogger(DORS.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
};
engine.start();
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.