method_id stringlengths 36 36 | cyclomatic_complexity int32 0 9 | method_text stringlengths 14 410k |
|---|---|---|
3b2ae304-8371-4103-bff6-27230dd22f47 | 1 | public void leftClick(Tile tile, boolean shift){
if(shift)
{
}
else
{
select(tile);
}
} |
c1e43ea0-7b25-46ba-af62-bad75c8cd25f | 0 | @Test
public void test_Divide() throws DivideByZeroException {
assertEquals("FAILED: test_Divide", simpleObject.divide(4,2), 2);
} |
e88d96dc-c168-4fd9-b564-f60278238b36 | 1 | public int hashCode() {
return myCurrentState.hashCode()
^ (parent == null ? 0 : parent.primitiveHashCode());
} |
c4310177-87a8-4356-95fc-6f81967e642b | 9 | public static void main(String[] args) throws IOException, ExecutionException, InterruptedException
{
log.info("Loading data.");
final Map<String, Repository> repositories = DataLoader.loadRepositories();
final DataSet data_set = DataLoader.loadWatchings();
if (args.length > 0)
{
// Perform cross-validation.
final List<DataSet> folds = data_set.stratify(100);
for (int i = 0; i < folds.size(); i++)
{
log.info(String.format("Starting fold %d.", i + 1));
final DataSet test_set = folds.remove(0);
final DataSet training_set = DataSet.combine(folds);
log.info("Training");
final NearestNeighbors knn = new NearestNeighbors(training_set);
log.info("Classifying");
final Map<String, Map<String, Collection<Float>>> evaluations = knn.evaluate(test_set.getWatchers().values());
final Set<Watcher> prediction = NearestNeighbors.predict(knn, evaluations, 10, test_set.getWatchers());
final Set<Watcher> all_predictions = NearestNeighbors.predict(knn, evaluations, 1000, test_set.getWatchers());
analyze(test_set, training_set, prediction, all_predictions, knn, evaluations);
log.info(String.format(">>> Results for fold %d: %f%% / %f%%", i + 1, NearestNeighbors.score(test_set, prediction) * 100, NearestNeighbors.score(test_set, all_predictions) * 100));
folds.add(test_set);
write_predictions(prediction);
}
}
else
{
log.info("Training.");
final NearestNeighbors knn = new NearestNeighbors(data_set);
log.info("Evaluating.");
final Set<Watcher> predictings = DataLoader.loadPredictings();
final Map<String, Map<String, Collection<Float>>> evaluations = knn.evaluate(predictings);
final Set<Watcher> predictions = NearestNeighbors.predict(knn, evaluations, 10, null);
final List<Map.Entry<String, NeighborRegion>> sorted_regions = MyUtils.sortRegionsByPopularity(knn.training_regions, new Comparator<Map.Entry<String, NeighborRegion>>(){
public int compare(final Map.Entry<String, NeighborRegion> first, final Map.Entry<String, NeighborRegion> second)
{
int firstValue = first.getValue().watchers.size();
int secondValue = second.getValue().watchers.size();
if (secondValue > firstValue)
{
return 1;
}
else if (firstValue < secondValue)
{
return -1;
}
return 0;
}
});
// Fill in repositories for any watchers with fewer than 10 repos.
log.info("Filling in repositories");
for (final Watcher w : predictions)
{
if (w.repositories.size() < 10)
{
for (final Map.Entry<String, NeighborRegion> pair : sorted_regions)
{
final NeighborRegion region = pair.getValue();
if (!region.most_forked.watchers.contains(w))
{
w.associate(region.most_forked);
}
if (w.repositories.size() == 10)
{
break;
}
}
}
}
log.info ("Printing results file.");
write_predictions(predictions);
/*
#repos_by_popularity = []
#sorted_regions = knn.training_regions.values.sort { |x,y| y.most_popular.watchers.size <=> x.most_popular.watchers.size }
#repos_by_popularity = sorted_regions.collect {|x| x.most_popular.id}
#
#$LOG.info "Printing results file."
#File.open('results.txt', 'w') do |file|
#
# predictions.each do |watcher|
# # Add the ten most popular repositories that the user is not already a watcher of to his repo list if
# # we don't have any predictions.
# if watcher.repositories.empty?
# if knn.training_watchers[watcher.id].nil?
# puts "No data for watcher: #{watcher.id}"
# repos_by_popularity[0..10].each do |repo_id|
# watcher.repositories << repo_id
# end
# else
# added_repo_count = 0
# repos_by_popularity.each do |suggested_repo_id|
# unless knn.training_watchers[watcher.id].repositories.include?(suggested_repo_id)
# watcher.repositories << suggested_repo_id
# added_repo_count += 1
# end
#
# break if added_repo_count == 10
# end
# end
# end
#
## $LOG.debug "Score (#{watcher.id}): #{NearestNeighbors.accuracy(knn.training_watchers[watcher.id], watcher)} -- #{watcher.to_s}"
# file.puts watcher.to_s
# end
#end
*/
}
System.exit(0);
} |
99a21af6-3870-4b3b-b7fc-6c4059282358 | 6 | protected Object readObject() throws IOException {
Field[] objTable = readObjectTable();
Object[] newTable = new Object[objTable.length];
Object obj;
for (int i = 0; i < newTable.length; i++) {
obj = createObject(objTable[i].id, objTable[i].fields);
if (obj == null) {
newTable[i] = objTable[i];
} else {
newTable[i] = obj;
}
}
fixReferences(objTable, newTable);
for (int i = newTable.length - 1; i >= 0; i--) {
obj = newTable[i];
if (obj instanceof ISerializable) {
((ISerializable) obj).initFromFields(objTable[i].fields);
}
}
for (int i = newTable.length - 1; i >= 0; i--) {
obj = newTable[i];
if (obj instanceof ISerializable) {
((ISerializable) obj).init();
}
}
return newTable[0];
} |
f41eb954-58d1-4562-9203-8181e56b6e5d | 7 | public void generateCode ( ) {
// generate the output code for the menus
StringBuilder sb = new StringBuilder( 8192 );
StringBuilder sbCode = new StringBuilder( 4096 );
String sLabels = ""; //$NON-NLS-1$
String sMenus = "PROGMEM const char *menu_items[] = {\r\n"; //$NON-NLS-1$
String s;
sb.append( "#include <avr/pgmspace.h>\r\n" ); //$NON-NLS-1$
for ( int i = 0; i < iMenuQuantity; i++ ) {
s =
String.format( "prog_char menu%d_label[] PROGMEM = \"%s\";\r\n", //$NON-NLS-1$
i, saLabels[i] );
sLabels += s;
s = String.format( "menu%d_label%c ", i, //$NON-NLS-1$
(i + 1 == iMenuQuantity) ? ' ' : ',' );
sMenus += s;
s = String.format( "void MenuEntry%d()\r\n{\r\n", i + 1 ); //$NON-NLS-1$
sbCode.append( s );
sbCode.append( saCode[i] );
sbCode.append( "\r\n}\r\n" ); //$NON-NLS-1$
}
sMenus += "};\r\n\r\n"; //$NON-NLS-1$
sb.append( sLabels );
sb.append( sMenus );
sb.append( sbCode );
String sInit =
"// Initialize the menu\r\nReefAngel.InitMenu(pgm_read_word(&(menu_items[0])),SIZE(menu_items));"; //$NON-NLS-1$
CodeWindow cw = null;
boolean canProceed = true;
Window[] dialogs = JDialog.getWindows();
for ( Window dlg : dialogs ) {
if ( dlg.getClass().equals( CodeWindow.class ) ) {
if ( dlg.isDisplayable() ) {
cw = (CodeWindow) dlg;
canProceed = false;
}
if ( !canProceed ) {
break;
}
}
}
if ( canProceed ) {
cw = new CodeWindow( MenuApp.getFrame() );
}
cw.setCodeText( sb );
cw.setCodeSetup( sInit );
cw.setLocationRelativeTo( cw.getParent() );
cw.setVisible( true );
} |
8155f713-223a-4fd9-ae37-4150e379284f | 9 | static final boolean method2496(int i, int i_9_, boolean bool) {
if (bool != true)
method2497(null, (byte) -29, null, 73);
anInt6396++;
if (i >= 1000 && (i_9_ ^ 0xffffffff) > -1001)
return true;
if ((i ^ 0xffffffff) > -1001 && i_9_ < 1000) {
if (NativeLibTracker.method2308((byte) 26, i_9_))
return true;
if (NativeLibTracker.method2308((byte) 26, i))
return false;
return true;
}
if ((i ^ 0xffffffff) <= -1001 && (i_9_ ^ 0xffffffff) <= -1001)
return true;
return false;
} |
e45ec665-55c4-4719-8233-68fb3e0b7e43 | 2 | private static void test_itostrx(TestCase t) {
// Print the name of the function to the log
pw.printf("\nTesting %s:\n", t.name);
// Run each test for this test case
int score = 0;
for (int i = 0; i < t.tests.length; i += 2) {
String exp = (String) t.tests[i];
int arg1 = (Integer) t.tests[i + 1];
String res = HW2Bases.itostrx(arg1);
boolean cor = exp.equals(res);
if (cor) {
++score;
}
pw.printf("%s(%8X): Expected: %8s Result: %8s Correct: %5b\n",
t.name, arg1, exp, res, cor);
pw.flush();
}
// Set the score for this test case
t.score = (double) score / (t.tests.length / 2);
} |
0b750d55-9d97-4df8-9ff4-5a6cc186eb01 | 0 | @Override
public void startSetup(Attributes atts) {
// Add this menuItem to the parent menu.
Preference pref = (Preference) GUITreeLoader.elementStack.get(GUITreeLoader.elementStack.size() - 2);
pref.setValidator(this);
} |
cb701035-1889-4039-9b52-a434b39cd2e4 | 6 | @Override
public String intern(String s) {
int h = s.hashCode();
// In the future, it may be worth augmenting the string hash
// if the lower bits need better distribution.
int slot = h & (cache.length-1);
Entry first = this.cache[slot];
Entry nextToLast = null;
int chainLength = 0;
for(Entry e=first; e!=null; e=e.next) {
if (e.hash == h && (e.str == s || e.str.compareTo(s)==0)) {
// if (e.str == s || (e.hash == h && e.str.compareTo(s)==0)) {
return e.str;
}
chainLength++;
if (e.next != null) {
nextToLast = e;
}
}
// insertion-order cache: add new entry at head
s = s.intern();
this.cache[slot] = new Entry(s, h, first);
if (chainLength >= maxChainLength) {
// prune last entry
nextToLast.next = null;
}
return s;
} |
bb7f862e-84a5-4599-9f6b-19f48a35f986 | 3 | public String getTypeString(Type type) {
if (type instanceof ArrayType)
return getTypeString(((ArrayType) type).getElementType()) + "[]";
else if (type instanceof ClassInterfacesType)
return getClassString(((ClassInterfacesType) type).getClassInfo());
else if (type instanceof NullType)
return "Object";
else
return type.toString();
} |
07146397-9521-4257-a1e3-c0f6776939dd | 0 | private void resetOders() {
this.orderTotal = BigDecimal.valueOf(0);
this.order=null;
this.order="";
this.lastErrors.clear();
} |
ddc8081a-9782-4d22-af60-1e9fc15c59ae | 4 | public static void offset(int x, int y)
{
xOff = x >= 0 && x <= map.width - fieldWidth ? x : xOff;
yOff = y >= 0 && y <= map.height - fieldHeight ? y : yOff;
} |
f6812396-1ed3-4ca5-8274-931a179f555c | 0 | public void setRole(Role role) {
this.role = role;
} |
dc003e91-942d-4df7-b899-caa9292dad58 | 6 | public boolean coalesceText(boolean recursively) {
final Iterator<Content> it = recursively ? getDescendants()
: content.iterator();
Text tfirst = null;
boolean changed = false;
while (it.hasNext()) {
final Content c = it.next();
if (c.getCType() == CType.Text) {
// Text, and no CDATA!
final Text text = (Text)c;
if ("".equals(text.getValue())) {
it.remove();
changed = true;
} else if (tfirst == null ||
tfirst.getParent() != text.getParent()) {
// previous item in the iterator was not text, or
// we are the next Text item after coming up the tree.
tfirst = text;
} else {
// add our text to the first in the sequence
tfirst.append(text.getValue());
// remove us from the sequence
it.remove();
changed = true;
}
} else {
// the end of the sequence
tfirst = null;
}
}
return changed;
} |
4a1dd4fb-d37c-4e70-9c18-1e458fe9cff4 | 2 | public static boolean isTerminalInProduction(String terminal,
Production production) {
String[] terminals = production.getTerminals();
for (int k = 0; k < terminals.length; k++) {
if (terminals[k].equals(terminal))
return true;
}
return false;
} |
35073a69-7972-4be2-8344-00c17f3f41fd | 7 | protected String buildQualifyingClassList(MOB mob, List<CharClass> classes, String finalConnector)
{
final StringBuilder list = new StringBuilder("");
int highestAttribute=-1;
for(final int attrib : CharStats.CODES.BASECODES())
{
if((highestAttribute<0)
||(mob.baseCharStats().getStat(attrib)>mob.baseCharStats().getStat(highestAttribute)))
highestAttribute=attrib;
}
for(final Iterator<CharClass> i=classes.iterator(); i.hasNext(); )
{
final CharClass C = i.next();
final String color=(C.getAttackAttribute()==highestAttribute)?"^H":"^w";
if(!i.hasNext())
{
if (list.length()>0)
{
list.append("^N"+finalConnector+" "+color);
}
list.append(C.name());
}
else
{
list.append(color+C.name()+"^N, ");
}
}
return list.toString();
} |
9f7b58b1-b6af-45d4-97b3-ef0cefe0f19d | 3 | public List<AsciiPoint> getPointList(char color) {
List<AsciiPoint> points = new LinkedList<AsciiPoint>();
for (int x = 0; x < getWidth(); ++x)
for (int y = 0; y < getHeight(); ++y)
if (getPixel(x, y) == color)
points.add(new AsciiPoint(x, y));
return points;
} |
b83fbc0c-522b-42f3-ac54-f2d408f2ea4d | 8 | public static WavFile newWavFile(File file, int numChannels, long numFrames, int validBits, long sampleRate) throws IOException, WavFileException
{
// Instantiate new Wavfile and initialise
WavFile wavFile = new WavFile();
wavFile.file = file;
wavFile.numChannels = numChannels;
wavFile.numFrames = numFrames;
wavFile.sampleRate = sampleRate;
wavFile.bytesPerSample = (validBits + 7) / 8;
wavFile.blockAlign = wavFile.bytesPerSample * numChannels;
wavFile.validBits = validBits;
// Sanity check arguments
if (numChannels < 1 || numChannels > 65535) throw new WavFileException("Illegal number of channels, valid range 1 to 65536");
if (numFrames < 0) throw new WavFileException("Number of frames must be positive");
if (validBits < 2 || validBits > 65535) throw new WavFileException("Illegal number of valid bits, valid range 2 to 65536");
if (sampleRate < 0) throw new WavFileException("Sample rate must be positive");
// Create output stream for writing data
wavFile.oStream = new FileOutputStream(file);
// Calculate the chunk sizes
long dataChunkSize = wavFile.blockAlign * numFrames;
long mainChunkSize = 4 + // Riff Type
8 + // Format ID and size
16 + // Format data
8 + // Data ID and size
dataChunkSize;
// Chunks must be word aligned, so if odd number of audio data bytes
// adjust the main chunk size
if (dataChunkSize % 2 == 1) {
mainChunkSize += 1;
wavFile.wordAlignAdjust = true;
}
else {
wavFile.wordAlignAdjust = false;
}
// Set the main chunk size
putLE(RIFF_CHUNK_ID, wavFile.buffer, 0, 4);
putLE(mainChunkSize, wavFile.buffer, 4, 4);
putLE(RIFF_TYPE_ID, wavFile.buffer, 8, 4);
// Write out the header
wavFile.oStream.write(wavFile.buffer, 0, 12);
// Put format data in buffer
long averageBytesPerSecond = sampleRate * wavFile.blockAlign;
putLE(FMT_CHUNK_ID, wavFile.buffer, 0, 4); // Chunk ID
putLE(16, wavFile.buffer, 4, 4); // Chunk Data Size
putLE(1, wavFile.buffer, 8, 2); // Compression Code (Uncompressed)
putLE(numChannels, wavFile.buffer, 10, 2); // Number of channels
putLE(sampleRate, wavFile.buffer, 12, 4); // Sample Rate
putLE(averageBytesPerSecond, wavFile.buffer, 16, 4); // Average Bytes Per Second
putLE(wavFile.blockAlign, wavFile.buffer, 20, 2); // Block Align
putLE(validBits, wavFile.buffer, 22, 2); // Valid Bits
// Write Format Chunk
wavFile.oStream.write(wavFile.buffer, 0, 24);
// Start Data Chunk
putLE(DATA_CHUNK_ID, wavFile.buffer, 0, 4); // Chunk ID
putLE(dataChunkSize, wavFile.buffer, 4, 4); // Chunk Data Size
// Write Format Chunk
wavFile.oStream.write(wavFile.buffer, 0, 8);
// Calculate the scaling factor for converting to a normalised double
if (wavFile.validBits > 8)
{
// If more than 8 validBits, data is signed
// Conversion required multiplying by magnitude of max positive value
wavFile.floatOffset = 0;
wavFile.floatScale = Long.MAX_VALUE >> (64 - wavFile.validBits);
}
else
{
// Else if 8 or less validBits, data is unsigned
// Conversion required dividing by max positive value
wavFile.floatOffset = 1;
wavFile.floatScale = 0.5 * ((1 << wavFile.validBits) - 1);
}
// Finally, set the IO State
wavFile.bufferPointer = 0;
wavFile.bytesRead = 0;
wavFile.frameCounter = 0;
wavFile.ioState = IOState.WRITING;
return wavFile;
} |
70ced347-cb34-4d8c-b932-7c23332582f7 | 1 | private String getCacheDescription(CacheDefinition cache) {
String desc = "@Cache(key=[" + cache.getKey() + "],pool=[" + cache.getPool() + "],expire=[" + cache.getExpire()
+ "(毫秒)]";
if (StringUtils.isNotBlank(cache.getVkey())) {
desc = desc + ",vkey=[" + cache.getVkey() + "]";
}
desc = desc + ")";
return desc;
} |
5a9e9b0c-c589-4f7a-aa6c-df3425834193 | 2 | public BufferedImage scaleBufferedImage(BufferedImage image, Dimension size){
int imageWidth = image.getWidth();
double scalingFactorWidth = (double)size.getWidth() / imageWidth;
int imageHeight = image.getHeight();
double scalingFactorHeight = (double)size.getHeight() / imageHeight;
if(scalingFactorHeight == 1.0 && scalingFactorWidth == 1.0){
return image;
}
AffineTransform at = new AffineTransform();
at.scale(scalingFactorWidth, scalingFactorHeight);
AffineTransformOp scaleOp = new AffineTransformOp(at, AffineTransformOp.TYPE_BILINEAR);
return scaleOp.filter(image, null);
} |
3328e5db-b531-4070-afcd-7399a9ab7824 | 5 | public void initDependancies() {
if (!setupEconomy() ) {
logger.severe(String.format("[%s] - Disabled due to no Vault dependency found!", getDescription().getName()));
getServer().getPluginManager().disablePlugin(this);
return;
}
setupPermissions();
Plugin WGplugin = getServer().getPluginManager().getPlugin("WorldGuard");
// WorldGuard may not be loaded
if (WGplugin == null || !(WGplugin instanceof WorldGuardPlugin)) {
logger.info("WorldGuardError");
this.WorldGuardEnabled=false;
logger.severe("WorldGuard not Found. Disabling dependant sections.");
} else {
this.WorldGuardEnabled=true;
}
Plugin jailPlugin = getServer().getPluginManager().getPlugin("Jail");
if (jailPlugin != null){
jail = ((Jail) jailPlugin).API;
this.JailAPIEnabled=true;
}
else {
this.JailAPIEnabled=false;
}
Plugin TagAPIPlugin = getServer().getPluginManager().getPlugin("TagAPI");
if (TagAPIPlugin != null){
this.TagAPIEnabled=true;
}
else {
this.TagAPIEnabled=false;
logger.severe("TagAPI Not Found. Disabling dependant sections.");
}
} |
972fc8ab-ce79-4161-8da5-702f2173a884 | 4 | public Smoothie createSmoothie(String s){
Smoothie smoothie = null;
SmoothieIngredientFactory sif = new StoreIngredientFactory();
if(s.equals("Banana")) {
smoothie = new BananaSmoothie(sif);
smoothie = new Milk(smoothie);
return smoothie;
//Smoothie drink = sif.createBanana();
//drink = new Milk(drink);
//return drink;
}
if(s.equals("Orange")) {
Smoothie drink = new FreshOrange();
drink = new Milk(drink);
return drink;
}
if(s.equals("Strawberry")) {
Smoothie drink = new FreshStrawberry();
drink = new Milk(drink);
return drink;
}
if(s.equals("Mango")) {
Smoothie drink = new FreshMango();
drink = new Milk(drink);
return drink;
}
else
return null;
} |
22eeacb9-f961-46a7-9f36-cea928e9ffc4 | 4 | @SuppressWarnings("unchecked")
public <T extends Event> void registerEvent(T event , EventHandler<T> handler){
String eventType = event.getEventType();
List<EventHandler<? super Event>> handles = handleStore.get(eventType);
if(handles == null){
handles = new ArrayList<EventHandler<? super Event>>();
handleStore.put(eventType, handles);
}
handles.add((EventHandler<? super Event>) handler);
} |
7988957b-b8ec-47ee-9edc-a15730da3768 | 8 | public void print() {
switch(ordinal()){
case 0: System.out.println("KKMMM"); break;
case 1: System.out.println("HHMMM"); break;
case 2: System.out.println("MMMKM"); break;
case 3: System.out.println("MMMHH"); break;
case 4: System.out.println("MMKHH"); break;
case 5: System.out.println("MMKHM"); break;
case 6: System.out.println("MMHHM"); break;
case 7: System.out.println("MMKKM"); break;
default: break;
}
} |
50a38f71-26de-4b79-9cb1-082b5b58c637 | 9 | private static String calc(String s) {
Stack<String> num = new Stack<String>();
Stack<Character> op = new Stack<Character>();
char[] cs = (s + "#").toCharArray();
StringBuilder numV = new StringBuilder();
boolean inputNum = false;
op.push('#');
int i = 0;
while (cs[i] != '#' || op.peek() != '#') {
char c = cs[i];
if (isOp(c)) {
if (inputNum) {
num.push(numV.toString());
numV.delete(0, numV.length());
inputNum = false;
}
if (op.isEmpty()) {
op.push(c);
} else {
switch (compare(op.peek(), c)) {
case 0 :
op.pop();
break;
case -1 :
op.push(c);
break;
case 1 :
String num2 = num.pop();
String num1 = num.pop();
num.push(calculate(op.pop(), num1, num2));
continue;
}
}
} else {
numV.append(c);
inputNum = true;
}
if (c != '#') {
i++;
}
}
return num.pop();
} |
30b3dbfa-bbcd-41f1-9b00-7b341af6bd64 | 0 | private long getSlot(int i) {
return this.startOfDay + i * Appointment.TIME_UNIT;
} |
e70f9aba-399b-4d8e-8950-a33eacbfc7fb | 7 | private static void computeSplitMap(int[] splitMBs, Configuration fConf, String jobNameDir, Boolean hasSplitFile) {
if(hasSplitFile) {
try {
BufferedReader reader = new BufferedReader(new FileReader(jobNameDir + File.separator + "splits.txt"));
String line;
int splitMB;
long splitByte;
while((line = reader.readLine()) != null) {
line = line.replaceAll("[^0-9]", " ");
Scanner scanner = new Scanner(line);
splitMB = scanner.nextInt();
List<Long> splitByteList = new ArrayList<Long>();
while(scanner.hasNext()) {
splitByte = scanner.nextLong();
splitByteList.add(splitByte);
}
splitMap.put(splitMB, splitByteList);
}
reader.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else {
try {
PrintWriter splitWriter = new PrintWriter(new BufferedWriter(new FileWriter(jobNameDir + File.separator + "splits.txt")));
// ~/MR-MEM/BigExperiments/BigBuildInvertedIndex/split.txt
for(int i = 0; i < splitMBs.length; i++) {
int splitMB = splitMBs[i];
Configuration conf = fConf.copyConfiguration();
long newSplitSize = splitMB * 1024 * 1024l;
conf.set("split.size", String.valueOf(newSplitSize));
conf.set("mapred.min.split.size", String.valueOf(newSplitSize));
conf.set("mapred.max.split.size", String.valueOf(newSplitSize));
//setNewConf(conf);
List<Long> splitsSizeList = InputSplitCalculator.getSplitsLength(conf);
splitMap.put(splitMB, splitsSizeList);
splitWriter.println(splitMB + ":" + splitsSizeList);
}
splitWriter.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} |
0f35b8d5-f84f-402f-aabb-1796c3dd8f08 | 0 | private void resetButtons(){
startStrategyButton.setEnabled(true);
pauseButton.setEnabled(false);
continueButton.setEnabled(false);
cancelButton.setEnabled(false);
} |
166ef5ce-4254-4bd8-bff5-a060d090d6aa | 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(AgregarUsuario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(AgregarUsuario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(AgregarUsuario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(AgregarUsuario.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 AgregarUsuario().setVisible(true);
}
});
} |
f02b06d0-9645-43cb-ac48-b7fb90a43e21 | 7 | public String toString()
{
String result;
/* catch any internal errors */
try {
result = "production [" + index() + "]: ";
result += ((lhs() != null) ? lhs().toString() : "$$NULL-LHS$$");
result += " :: = ";
for (int i = 0; i<rhs_length(); i++)
result += rhs(i) + " ";
result += ";";
if (action() != null && action().code_string() != null)
result += " {" + action().code_string() + "}";
if (nullable_known())
if (nullable())
result += "[NULLABLE]";
else
result += "[NOT NULLABLE]";
} catch (internal_error e) {
/* crash on internal error since we can't throw it from here (because
superclass does not throw anything. */
e.crash();
result = null;
}
return result;
} |
bee06002-7a16-4e69-9089-a50c30531de0 | 4 | public boolean checkForPlayer(int x, int y) {
for (Player p : PlayerHandler.players) {
if (p != null) {
if (p.getX() == x && p.getY() == y)
return true;
}
}
return false;
} |
1c51695a-e1c4-4c38-8463-834ce71ce2c3 | 7 | private Integer[] determineWinnerTaIds() {
BufferedReader reader = null;
ArrayList<Integer> winnerTas = new ArrayList<Integer>();
try
{
reader = new BufferedReader(new FileReader("TransactionLog"));
String line = reader.readLine();
String[] values;
while (line != null)
{
values = line.split("\\|");
switch (values[2].split("\\:")[1]) {
case "committed": {
winnerTas.add(Integer.parseInt(values[1].split("\\:")[1]));
break;
}
case "BOT": {
// BOT
break;
}
default: {
// data
break;
}
}
line = reader.readLine();
}
} catch (FileNotFoundException e)
{
System.err.println("No TransactionLog File found. Crash Recovery is impossible\nSkipping Crash Recovery..");
return null;
} catch (Exception e)
{
e.printStackTrace();
} finally
{
try
{
if (reader != null)
{
reader.close();
}
} catch (Exception ex)
{
ex.printStackTrace();
}
}
return (Integer[]) winnerTas.toArray(new Integer[winnerTas.size()]);
} |
6fee3ccc-27b4-45e2-9567-917753bc48a1 | 6 | public void draw(Graphics g) {
int cid = id > 8 ? id - 8 : id;
Color c = COLORS[cid];
if (id <= 8) {
g.setColor(c);
} else {
g.setColor(Color.WHITE);
}
g.fillArc((int)pos.x - SIZE, (int)pos.y - SIZE, SIZE * 2, SIZE * 2, 0, 360);
if (id > 8) {
g.setColor(c);
g.fillArc((int)pos.x - SIZE, (int)pos.y - SIZE, SIZE * 2, SIZE * 2, 15, 60);
g.fillArc((int)pos.x - SIZE, (int)pos.y - SIZE, SIZE * 2, SIZE * 2, 195, 60);
g.fillPolygon(
new int[] {
(int)(pos.x - Math.cos(Math.PI*2.0/24.0) * SIZE),//15
(int)(pos.x - Math.cos(Math.PI*10.0/24.0) * SIZE),//75
(int)(pos.x - Math.cos(Math.PI*26.0/24.0) * SIZE),//195
(int)(pos.x - Math.cos(Math.PI*34.0/24.0) * SIZE) },//255
new int[] {
(int)(pos.y + Math.sin(Math.PI*2.0/24.0) * SIZE),
(int)(pos.y + Math.sin(Math.PI*10.0/24.0) * SIZE),
(int)(pos.y + Math.sin(Math.PI*26.0/24.0) * SIZE),
(int)(pos.y + Math.sin(Math.PI*34.0/24.0) * SIZE) },
4);
}
g.setColor(Color.BLACK);
if (id != 0) {
g.setColor(Color.WHITE);
g.fillArc((int)pos.x-SIZE/4, (int)pos.y-SIZE*3/4, SIZE, SIZE, 0, 360);
g.setColor(Color.BLACK);
g.drawString(Integer.toString(id),(int)pos.x-(id > 9 ? 5 : 0),(int)pos.y);
}
if (showDebugLine) {
g.drawLine((int)pos.x, (int)pos.y, (int)(pos.x + v.dx * 10), (int)(pos.y + v.dy * 10));
}
} |
44298b75-f476-4b86-a1b6-c7cce0204c5e | 0 | public List<String> getErrors() {
return errors;
} |
be6536d3-6c3f-433a-92bc-72127c53472c | 1 | public boolean isSymmetric(TreeNode root) {
if(root == null)
return true;
return isSymmetricLevel(root.left,root.right);
} |
598628f7-50d9-422c-bfed-23f23dee785a | 8 | private void executeReadRequestOnReadQuorum(
HashMap<Machine, String> responseMap,
HashSet<Machine> successfulServers, HashSet<Machine> failedServers,
int articleReadFrom) {
if (failedServers != null) {
if (failedServers.contains(myInfo)) {
/*
* as we have already implemented local read in the final step
* of merge of bbs, no need to read now.
*/
successfulServers.add(myInfo);
failedServers.remove(myInfo);
logger.info("Removed from local read;myInfo=" + myInfo);
}
List<ReadService> threadsToRead = new ArrayList<ReadService>(
failedServers.size());
final CountDownLatch readQuorumlatch = new CountDownLatch(
failedServers.size());
for (Machine server : failedServers) {
ReadService t = new ReadService(server, readQuorumlatch,
articleReadFrom);
threadsToRead.add(t);
t.start();
}
try {
if (!readQuorumlatch.await(Props.NETWORK_TIMEOUT,
TimeUnit.MILLISECONDS)) {
interruptReadThreads(threadsToRead);
}
for (ReadService rs : threadsToRead) {
String str = null;
str = Utils.byteToString(rs.dataRead, Props.ENCODING);
responseMap.put(rs.serverToRead, str);
}
} catch (InterruptedException ie) {
logger.error("Error", ie);
// interrupt all other threads
// TODO other servers should kill
interruptReadThreads(threadsToRead);
} finally {
// if not thread has some value add it to the success servers
// else let
// it be in failed set
for (ReadService rs : threadsToRead) {
if (rs.dataRead != null) {
successfulServers.add(rs.serverToRead);
failedServers.remove(rs.serverToRead);
}
}
}
}
} |
29535aa4-59f4-4f43-99dd-25cae2e7a9a5 | 3 | private boolean message_ready() {
// Message is completely read. Push it further and start reading
// new message. (in_progress is a 0-byte message after this point.)
if (msg_sink == null)
return false;
boolean rc = msg_sink.push_msg (in_progress);
if (!rc) {
if (!ZError.is (ZError.EAGAIN))
decoding_error ();
return false;
}
next_step (tmpbuf, 1, flags_ready);
return true;
} |
fe1ef08c-7769-4eae-85d4-289fbc596e3d | 5 | public static AuthenticationInfo extractAuthenticationInfo(String login, String encodedPassword) {
try {
char[] clearPwd;
if (encodedPassword != null && !encodedPassword.isEmpty()) {
clearPwd = decodePassword(encodedPassword);
} else {
clearPwd = null;
}
if (clearPwd == null) {
clearPwd = new char[0];
}
String decodedLogin = URLDecoder.decode(login, "UTF-8");
return new AuthenticationInfo(decodedLogin, clearPwd);
} catch (GeneralSecurityException ex) {
Logger.getLogger(OfficeOnline.class.getName()).log(Level.SEVERE, "can't retrieve credentials", ex);
System.exit(-1);
} catch (UnsupportedEncodingException ex) {
Logger.getLogger(OfficeOnline.class.getName()).log(Level.SEVERE, "can't retrieve credentials", ex);
System.exit(-1);
}
return null;
} |
f088250a-6906-4d73-9e23-6ca51555b9ed | 9 | private void addNewCounterEvidence() {
String titleValue = titleNAJtxt.getText()
, descriptionValue = descriptionNAJtxa.getText()
, parentClaimTitle = null;
Object parentClaimO = listOfClaimsNAJcbx.getSelectedItem();
Claim parentClaim = null;
if (parentClaimO != null) {
parentClaimTitle = parentClaimO.toString();
selfCounterClaimResultList = claim.getClaims(fileName, CLAIM, teamType);
for (int i = 0; i < selfCounterClaimResultList.size(); i++) {
if (selfCounterClaimResultList.get(i).getTitle().equals(parentClaimTitle)) {
parentClaim = selfCounterClaimResultList.get(i);
break;
}
}
}
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm a");
Date date = new Date();
if (titleValue == null || titleValue.equals("")) {
JOptionPane.showMessageDialog(newActionJfme, "The title of the new Counter Evidence cannot be null", "Title", JOptionPane.WARNING_MESSAGE);
} else if (descriptionValue == null || descriptionValue.equals("")) {
JOptionPane.showMessageDialog(newActionJfme, "The description of the new Counter Evidence cannot be null", "Description", JOptionPane.WARNING_MESSAGE);
} else if (parentClaim == null) {
JOptionPane.showMessageDialog(newActionJfme, "The parent of the new Counter Evidence cannot be null", "Parent", JOptionPane.WARNING_MESSAGE);
} else {
Evidence evidenceFlag = new Evidence(titleValue, descriptionValue, COUNTEREVIDENCE, dateFormat.format(date)
, parentClaim.getId(), userLogin.getName(), debateSelected.getId());
Chat c = new Chat("Made a new CounterEvidence: " + titleValue, dateFormat.format(date), userLogin.getName(), debateSelected.getId());
if (action.add(fileName, evidenceFlag, teamType)) {
chat.addChat(fileName, c);
JOptionPane.showMessageDialog(newActionJfme, "You have sucessfully created a new counter evidence", "Success", JOptionPane.OK_OPTION);
newActionJfme.dispose();
// Refresh Claim list
getEvidenceList("counterevidence");
getChatHistory();
} else {
JOptionPane.showMessageDialog(newActionJfme, "You have failed created a new counter evidence", "Fail", JOptionPane.WARNING_MESSAGE);
}
}
} |
3f39ec1b-2f6d-4e8c-8a4f-df558aa8c677 | 8 | public static void main(String[] args){
for(int iloscWatkow=10; iloscWatkow<51; iloscWatkow+=10)
{
watki++;
for(int czasMetody=0; czasMetody<101; czasMetody+=20)
{
Main.ile=0;
System.out.println("WATKI "+ iloscWatkow + " CZAS " + czasMetody);
czasy++;
sleep=czasMetody;
int iloscProducentow =iloscWatkow/2, iloscKonsumetow=iloscWatkow/2;
Bufor bufor = new Bufor();
Thread producenci[];
Thread konsumenci[];
producenci = new Thread[iloscProducentow];
konsumenci = new Thread[iloscKonsumetow];
for(int i=0; i<iloscProducentow; ++i){
producenci[i] = new Producent(bufor, i);
}
for(int i=0; i<iloscKonsumetow; ++i){
konsumenci[i] = new Konsument(bufor, i);
}
for(int i=0; i<iloscProducentow; ++i){
producenci[i].start();
}
for(int i=0; i<iloscKonsumetow; ++i){
konsumenci[i].start();
}
try{
//if(czasMetody==0) Thread.sleep(3000);
Thread.sleep(60000);
}catch(Exception e){}
for(int i=0; i<iloscWatkow/2; ++i){
producenci[i].interrupt();
konsumenci[i].interrupt();
}
wypisz();
}
czasy=-1;
}
System.out.println();
wypisz();
} |
51ec999e-2327-4532-9969-02833b422924 | 6 | private void analyseInstructionFormat(String line) throws AssemblerException {
if (line.trim().length() == 0)
return;
foundInsFormat = true;
line = line.trim();
// Legit instruction format:
// (!(space|colon))+ space* colon space* (letters|numbers)+ openBracket
// 0-9+ closeBracket
// (space* (letter|numbers)+ openBracket 0-9+ closeBracket)*
boolean validInsFormat = Pattern
.matches("[^\\s:]+\\s*:\\s*[a-zA-Z0-9]+\\([0-9]+\\)(\\s*[a-zA-Z0-9]+\\([0-9]+\\))*",
line);
if (!validInsFormat) {
throw new AssemblerException(
"InstructionFormat error: Syntax error, <instructionName> : <fieldName>(<bitLength>) expected. For example:\n"
+ "\nopcode : op(6) d(1) s(1)");
}
InstructionFormat insF = new InstructionFormat();
String[] tokens = line.split(":");
String insName = tokens[0].trim();
String fieldsAndValues = tokens[1].trim();
String[] fieldTokens = fieldsAndValues.split("\\s+");
for (String field : fieldTokens) {
String[] fieldAndSize = field.split("\\(|\\)");
String fieldName = fieldAndSize[0];
int bitSize = Integer.parseInt(fieldAndSize[1]);
if(bitSize == 0)
throw new AssemblerException(
"InstructionFormat error: Can not have 0 bit field length.");
if(insF.getFields().contains(fieldName))
throw new AssemblerException(
"InstructionFormat error: Field \""+fieldName+"\" defined multiple times in instruction.");
insF.getFields().add(fieldName);
insF.getFieldBitHash().put(fieldName, bitSize);
}
insF.setInstructionName(insName);
insF.setRawLineString(line.trim());
if(data.getInstructionFormatHash().get(insName) != null)
throw new AssemblerException(
"InstructionFormat error: Instruction \""+ insName + "\" already defined");
data.getInstructionFormatHash().put(insName, insF);
} |
0df22339-6fd4-4b8d-92a9-a4efbd910797 | 9 | @Override
public Page next() {
boolean insidePage = false;
Page page = new Page();
try {
pageCount++;
loop:
while (true) {
xmlr.next();
switch (xmlr.getEventType()) {
case XMLStreamConstants.START_ELEMENT:
if (xmlr.getLocalName().equals("page")) {
insidePage = true;
}
if (insidePage) {
if (xmlr.getLocalName().equals("title")) {
page.setTitle(xmlr.getElementText());
}
if (xmlr.getLocalName().equals("text")) {
page.setText(xmlr.getElementText());
}
}
break;
case XMLStreamConstants.END_ELEMENT:
if (xmlr.getLocalName().equals("page")) {
break loop;
}
break;
default:
break;
}
}
} catch (XMLStreamException e) {
e.printStackTrace();
}
return page;
} |
7f37576d-112c-4400-ab0d-a252a7c0c69d | 8 | public void do_ls(ParamHolder myParamHolder) {
Connection dbConnection = null;
PreparedStatement pstatement = null;
String SelectTabSQL = "select File_Name\n" +
" ," + myParamHolder.keyFieldName.toUpperCase() + "\n" +
" ,round(dbms_lob.getlength(" + myParamHolder.clobFieldName.toUpperCase() + ")/1024) as Kb_size\n" +
" ,Load_Date\n" +
" ,Load_By\n" +
" from " + myParamHolder.table.toUpperCase() + " order by Load_Date desc";
try {
dbConnection = myParamHolder.conn;
pstatement = myParamHolder.conn.prepareStatement(SelectTabSQL);
ResultSet rs = pstatement.executeQuery();
System.out.printf("====================================================\n");
System.out.printf("=======FileName====== ; ==========KeyVal============ \n");
while (rs.next()) {
//Retrieve by column name
String FileNameHead = rs.getString("File_Name");
String keyFieldNameHead = rs.getString(myParamHolder.keyFieldName.toUpperCase());
//Display values
System.out.print("" + FileNameHead + " ; ");
System.out.print("" + keyFieldNameHead + "");
System.out.print("\n");
}
rs.close();
} catch (SQLException se) {
if (se.getErrorCode() == 942) {
System.out.print("!!!! Table not exists");
} else {
//Handle errors for JDBC
se.printStackTrace();
}
} catch (Exception e) {
//Handle errors for Class.forName
e.printStackTrace();
} finally {
//finally block used to close resources
try {
if (pstatement != null)
myParamHolder.conn.close();
} catch (SQLException se) {
}// do nothing
try {
if (myParamHolder.conn != null)
myParamHolder.conn.close();
} catch (SQLException se) {
se.printStackTrace();
}//end finally try
}//end try
}//end main |
976e7fb5-e2a4-4056-ba29-ee6b8b3c4e75 | 3 | public static List<String> getAllTablesNames() {
List<String> allTables = new ArrayList<String>();
try {
DatabaseMetaData md = connection.getMetaData();
ResultSet rs = md.getTables(null, null, "%", null);
while (rs.next()) {
allTables.add(rs.getString(3));
}
} catch (SQLException e) {
while (e != null) {
e.printStackTrace();
e = e.getNextException();
}
}
return allTables;
} |
c197e334-7e66-47a0-9fb8-aed2a0a97b3e | 8 | public static void main(String[] args) {
// Diamond types are awesome. They let us create a container of explicit type without actually
// specifying the needed type, as it can be inferred from the declaration.
// This was introduced in Java 7.
// ...
// An example of this is the call to new ArrayList<>(); below.
// ...
// I'd usually use Long but the question specified integers
List<Integer> integers = new ArrayList<>();
if (args.length < 1) {
// This is a lot more realistic than using a Scanner..
System.out.println("Please provide some numbers as arguments.");
return;
}
for (String element : args) {
int input;
try {
input = Integer.parseInt(element);
} catch (java.lang.NumberFormatException e) {
// ..at least, in part..
System.out.println("Unknown number: '" + element + "' - skipping..");
continue;
}
// We use two loops because we need to get rid of the numbers that are invalid.
// An alternative approach would be to terminate instead, but we're writing a
// "nice" program. \o/
integers.add(input);
}
Integer first = -1;
Integer last = -1;
for (int i = 0; i < integers.size(); i += 1) {
// This is the actual logic.
if (first.equals(-1)) {
// Then we know for sure it's the first index
if (integers.get(i).equals(12)) {
first = i;
last = i;
}
} else {
// It's not the first index, of course
if (integers.get(i).equals(12)) {
last = i;
}
}
}
if (first.equals(last)) {
System.out.println("Both indexes: " + first);
} else {
System.out.println("First index: " + first);
System.out.println("Last index: " + last);
}
} |
1d92e1b0-6d7f-4b9f-ab19-2d8ae8c21fef | 3 | public JSONWriter object() throws JSONException {
if (this.mode == 'i') {
this.mode = 'o';
}
if (this.mode == 'o' || this.mode == 'a') {
this.append("{");
this.push(new JSONObject());
this.comma = false;
return this;
}
throw new JSONException("Misplaced object.");
} |
0fa460b8-c7b5-4ed4-9e76-ff0da54e5d2a | 5 | public static ArrayList<String> restoreIpAddresses(String s) {
ArrayList<ArrayList<String>> resultLists = new ArrayList<ArrayList<String>>();
ArrayList<String> result = new ArrayList<String>();
if (s.length() == 0)
return result;
ArrayList<String> list = new ArrayList<String>();
restoreIpAddressesHelper(s, list, resultLists);
outerloop: while (resultLists.size() != 0) {
if (resultLists.get(0).size() == 4) {
StringBuilder sb = new StringBuilder();
for (String str : resultLists.get(0)) {
int i = Integer.parseInt(str);
if (str.length() != String.valueOf(i).length()) {
resultLists.remove(0);
continue outerloop;
}
sb.append(str + ".");
}
sb.deleteCharAt(sb.length() - 1);
result.add(sb.toString());
}
resultLists.remove(0);
}
return result;
} |
ab34f9ef-b188-4523-81b0-c88209daa276 | 2 | public void load(String fileName) {
boolean header = true;
for (String line : Gpr.readFile(fileName).split("\n")) {
if (header) {
header = false;
continue;
}
// Split line and parse data
String recs[] = line.split("\t");
String mtype = recs[0];
countBases.inc(mtype, Gpr.parseIntSafe(recs[1]));
countMarkers.inc(mtype, Gpr.parseIntSafe(recs[2]));
}
} |
431412cb-465c-4565-93a9-b35a22d88efa | 4 | @Override
public void execute(Joueur jou) {
Joueur proprio = this.getProprietaire();
if(proprio == null){
Scanner sc = new Scanner(System.in);
if(this.getLoyerBase() <= jou.getCash()){
System.out.println("Voulez-vous acheter cette gare : y/n Cela vous coutera : " + getPrixAchat() + "(toute autre réponses sont considerer comme 'n')");
String Answer = sc.nextLine();
if("y".equals(Answer)){
jou.addGare(this);
jou.setCash(jou.getCash() - getPrixAchat());
this.setProprietaire(jou);
System.out.println("Achat effectué !\n");
}
else {
System.out.println("Vous n'achetez pas !");
}
}
else{
System.out.println("Vous ne pouvez pas acheter ce terrain, trop cher !");
}
}
else if(jou.equals(proprio)){return;}
else{
int aDebiter = getLoyerBase() * proprio.getNbGare();
jou.setCash(jou.getCash() - aDebiter);
proprio.setCash(proprio.getCash() + aDebiter);
}
} |
252af50b-ba82-442b-a863-86cddd2ffd98 | 2 | private void drawFields(Graphics g){
for (int[][] a : Position.time){
for (int []b : a){
//System.out.println(" x: " + b[0] + " y: " + b[1]);
Position.drawEmptyCircle(g, b[0], b[1]);
}
}
} |
51a94a34-95c4-410c-9924-a8c65110d327 | 8 | public String TitikHanya2(String strQty){
char [] data = strQty.toCharArray();
String newStrQty = "";
int JmlTitik = 0, PosTitik=0;
int Pencacah=0;
for (char c : data){
if (c != getTheSeparator().charAt(0)) {
newStrQty = newStrQty + String.valueOf(c);
} else if (c == getTheSeparator().charAt(0)){
JmlTitik++;
PosTitik=Pencacah;
if (JmlTitik<3){
newStrQty = newStrQty + String.valueOf(c);
}
}
Pencacah++;
}
//System.out.println(newStrQty);
String newStrQty2="";
//Jika Jumlah titik cuma 1 maka paksa titik harus 2
if (JmlTitik==0){
newStrQty2 = newStrQty + getTheSeparator() + getTheSeparator();
} else if (JmlTitik==1){
for(int i=0;i < newStrQty.length();i++){
if (i==PosTitik){
newStrQty2 = newStrQty2 + getTheSeparator();
}
newStrQty2= newStrQty2 + String.valueOf(newStrQty.charAt(i));
}
//Bisa jadi sebetulnya jumlah titik adalah 3 tapi sudah dibuat 2
} else {
newStrQty2 = newStrQty;
}
return newStrQty2;
} |
62323d07-8144-497a-adc5-985651e088a5 | 0 | public Task getTask() {
return new Task();
} |
f4b14c82-14d5-4157-ac92-383f1daf38a2 | 5 | private static void whichTrack(String track, String dir, int[] startingPoint, LinkedList<int[]> locations) {
switch (track) {
case "strR":
case "strL":
case "statR":
case "statL":
straightTrack(dir, startingPoint, locations);
break;
case "turnR":
curveRight(dir, startingPoint, locations);
break;
}
} |
ba65370f-ce1b-43b0-a8e8-3e6a1c5c2f44 | 6 | public void paintComponent(Graphics g){
switch(dice){
case 1:
g.setColor(Color.DARK_GRAY);
g.fillRect(0, 0, 81, 81);
g.setColor(Color.WHITE);
g.fillRect(v2, v2, 9, 9);
break;
case 2:
g.setColor(Color.DARK_GRAY);
g.fillRect(0, 0, 81, 81);
g.setColor(Color.WHITE);
g.fillRect(v1, v1, 9, 9);
g.fillRect(v3, v3, 9, 9);
break;
case 3:
g.setColor(Color.DARK_GRAY);
g.fillRect(0, 0, 81, 81);
g.setColor(Color.WHITE);
g.fillRect(v1, v1, 9, 9);
g.fillRect(v2, v2, 9, 9);
g.fillRect(v3, v3, 9, 9);
break;
case 4:
g.setColor(Color.DARK_GRAY);
g.fillRect(0, 0, 81, 81);
g.setColor(Color.WHITE);
g.fillRect(v1, v1, 9, 9);
g.fillRect(v1, v3, 9, 9);
g.fillRect(v3, v1, 9, 9);
g.fillRect(v3, v3, 9, 9);
break;
case 5:
g.setColor(Color.DARK_GRAY);
g.fillRect(0, 0, 81, 81);
g.setColor(Color.WHITE);
g.fillRect(v1, v1, 9, 9);
g.fillRect(v1, v3, 9, 9);
g.fillRect(v2, v2, 9, 9);
g.fillRect(v3, v1, 9, 9);
g.fillRect(v3, v3, 9, 9);
break;
case 6:
g.setColor(Color.DARK_GRAY);
g.fillRect(0, 0, 81, 81);
g.setColor(Color.WHITE);
g.fillRect(v1, v1, 9, 9);
g.fillRect(v3, v1, 9, 9);
g.fillRect(v1, v2, 9, 9);
g.fillRect(v3, v2, 9, 9);
g.fillRect(v1, v3, 9, 9);
g.fillRect(v3, v3, 9, 9);
break;
default:
g.setColor(Color.RED);
g.drawString("Error", 5, 40);
}
//draws Dice
} |
da0b9d12-7342-4a80-9c71-202001f31da8 | 4 | public void bounceOffWalls() {
if (y > FRAME_HEIGHT - FONT_SIZE || y < 0) {
vy = -vy;
}
if (x + FONT_SIZE/2 > FRAME_WIDTH || x < 0) {
vx = -vx;
}
} |
c8c1ab17-5d6d-4c25-b2a1-93d0861dc32e | 2 | @Override
public int compare(Creature o1, Creature o2) {
float distance1 = o1.getTarget2().getDistance(o1.getPos());
float distance2 = o2.getTarget2().getDistance(o2.getPos());
float dif = distance1 - distance2;
if (dif < 0) return -1;
else if (dif > 0) return 1;
return 0;
} |
10c36cc2-af38-4d3c-a030-75ae15ad1738 | 0 | public static ScoreManager getInstance()
{
return instance;
} |
8b00293c-ea8c-48ae-a63a-0582f89eeaf3 | 0 | protected Transition initTransition(State from, State to) {
return new FSATransition(from, to, "");
} |
e55bb8c6-c200-48d2-8176-3845fb9e0882 | 7 | private int findLeftRight(String program, Character symbol) {
int leftCount = 0, rightCount = 0;
int maxLeft = 0, maxRight = 0;
for (int i = 0; i < program.length(); i++) {
if (program.charAt(i) == symbol) {
if (rightCount > 0) {
rightCount--;
} else {
leftCount++;
if (maxLeft < leftCount)
maxLeft = leftCount;
}
} else {
if (leftCount > 0) {
leftCount--;
} else {
rightCount++;
if (maxRight < rightCount)
maxRight = rightCount;
}
}
}
return maxLeft > maxRight ? maxLeft : maxRight;
} |
dd03666a-a219-4fea-ba31-4608f60499a2 | 0 | @Override
public String toString() {
return ToStringBuilder.reflectionToString(this,
ToStringStyle.MULTI_LINE_STYLE);
} |
da5cbc9e-99fd-46ae-83d4-14fffa37e762 | 0 | public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
JFrame frame = new BounceFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
} |
91589db7-d6ba-4cd8-8051-47c555bb1c1a | 1 | @Override
public void setEnabled( boolean enabled ) {
if( !enabled ){
moving = false;
mousePressedPoint = null;
items.clear();
}
} |
8d092c5a-06f4-4485-a25c-394f431f25df | 7 | @Override
public final void mouseDragged(MouseEvent me)
{
if (slider.inUse)
if (orientation == VERTICAL)
{
slider.y = me.getY() - 12.5f;
if (slider.y < y)
slider.y = y;
else if (slider.y > y + length - 25)
slider.y = y + length - 25;
sendTScrollEvent(new TScrollEvent(this, TScrollEvent.TSCROLLBARSCROLLED, getSliderPercent(), 0));
}
else if (orientation == HORIZONTAL)
{
slider.x = me.getX() - 12.5f;
if (slider.x < x)
slider.x = x;
else if (slider.x > x + length - 25)
slider.x = x + length - 25;
sendTScrollEvent(new TScrollEvent(this, TScrollEvent.TSCROLLBARSCROLLED, getSliderPercent(), 0));
}
} |
59812c88-6c5a-4b81-af55-8feb95046d61 | 6 | public void printSymbol(Integer type) {
String string = program.getMainPanel().getTextField().getText();
string = string.substring(0, program.getMainPanel().getTextField()
.getCaretPosition());
switch (type) {
case 0:
string = string + "*";
break;
case 1:
string = string + "+";
break;
case 2:
string = string + "!";
;
break;
case 3:
string = string + "|";
;
break;
case 4:
string = string + "/";
;
break;
case 5:
string = string + "^";
;
break;
}
string = string
+ program
.getMainPanel()
.getTextField()
.getText()
.substring(
string.length() - 1,
program.getMainPanel().getTextField().getText()
.length());
program.getMainPanel().getTextField().setText(string);
program.getMainPanel().getTextField().requestFocus();
} |
fea82260-6240-40f8-bc57-906951089074 | 3 | final Entry<V> removeEntryForKey(long key) {
int hash = hash(key);
int i = indexFor(hash, this.table.length);
Entry prev = this.table[i];
Entry e = prev;
while (e != null) {
Entry next = e.next;
if (e.key == key) {
this.modCount += 1;
this.size -= 1;
if (prev == e) this.table[i] = next; else
prev.next = next;
return e;
}
prev = e;
e = next;
}
return e;
} |
e842a573-be31-4022-86cf-edd6c8899661 | 5 | public String getTypeFrench() {
String res = "";
switch(this.type) {
case "calculation":
res = "Calcul arithmétique";
break;
case "fraction":
res = "Calcul fractionnaire";
break;
case "equation":
res = "Résolution d'équation";
break;
case "power":
res = "Calcul de puissances";
break;
case "custom":
res = "Personnalisé";
break;
default:
res = "Personnalisé";
break;
}
return res;
} |
934b3f32-5fb9-49cc-8327-1b540d5ef73e | 7 | public void importTriples ( List<Triple> listOfTriples )
{
Node subject_obj;
Predicate predicate_obj;
Node object_obj;
String subject;
String predicate;
String object;
String triple;
// go through the list of triples to populate KnowledgeGraph with input data
for ( Triple element : listOfTriples )
{
triple = element.getIdentifier();
String[] tempResult = triple.split( " " );
subject = tempResult[0];
subject_obj = new Node ( subject );
object = tempResult[2];
object_obj = new Node ( object );
predicate = tempResult[1];
predicate_obj = new Predicate ( predicate );
//stuff input data into different maps
if ( !nodeMap.containsKey( subject ) )
{
nodeMap.put( subject, subject_obj );
}
if ( !nodeMap.containsKey( object ) )
{
nodeMap.put( object, object_obj );
}
if ( !predicateMap.containsKey( predicate ) )
{
predicateMap.put( predicate, predicate_obj );
}
if ( !tripleMap.containsKey( triple ) )
{
tripleMap.put( triple, element );
}
if ( !queryMapSet.containsKey( triple ) )
{
Set<Triple> setOfTriples = new HashSet<Triple>();
// use binary table representing decimal numbers from 0 to 7 to create 8 unique combinations of triple elements
// 1s are used as a flag for replacing the triple element with "?"
for ( int i = 0; i < binTable.size(); i++)
{
// create and store unique combination of triple elements to setOfTriple
setOfTriples.add( createQueryTriple ( binTable.get(i), subject, predicate, object ) );
}
queryMapSet.put(triple, setOfTriples);
}
}
} |
7d1306ca-1eec-4048-9315-b086b75c243f | 5 | @Override
public void add(int id_task, int id_user) {
try {
connection = getConnection();
ptmt = connection.prepareStatement("INSERT INTO Task_executors(id_task, id_user) VALUES(?,?);");
ptmt.setInt(1, id_task);
ptmt.setInt(2, id_user);
ptmt.executeUpdate();
} catch (SQLException ex) {
Logger.getLogger(TaskExecutorsDAO.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
if (ptmt != null) {
ptmt.close();
}
if (connection != null) {
connection.close();
}
if (resultSet != null) {
resultSet.close();
}
} catch (SQLException ex) {
Logger.getLogger(UserDAO.class.getName()).log(Level.SEVERE, null, ex);
}
}
} |
64b6749f-f0d8-4a4a-9f0b-ce6762dc65d6 | 6 | @Override
public void mouseExited(MouseEvent e) {
if(!czyRozmieszczonoLosowo)
{
if(widokRozmiesc.cb_RodzajStatku.getItemCount() > 0)
for(int i = 0;i < 10; i++)
for(int j = 0;j < 10; j++)
if(e.getSource() == lb_polaGry[j][i])
if(widokRozmiesc.uzytkownik.plansza.sprawdzWspolrzedneUstawianegoStatku(widokRozmiesc.cb_RodzajStatku.getSelectedItem().toString(),
widokRozmiesc.cb_Rozmieszczenie.getSelectedItem().toString(), j, i))
{
zaznaczMaszty(false ,j, i, widokRozmiesc.cb_RodzajStatku, widokRozmiesc.cb_Rozmieszczenie);
}
}
} |
966f02f4-cb96-458f-85ff-7cb290ef0946 | 9 | static public Double[][] readFile(String fileName) {
// default initializations
int nbDim = 0;
int nbPoints = 0;
boolean textOnFirstLine = false;
// count lines (points = rows) and dimensions (columns)
try {
BufferedReader countReader = new BufferedReader(new FileReader("data/" + fileName));
int lines = 0;
String currLine;
while ((currLine = countReader.readLine()) != null) {
try {
// make the program raise an exception if the line does not begin with a number
Double.parseDouble(currLine.split("\\t")[0].replace(",", "."));
lines++;
} catch (NumberFormatException nfe) {
textOnFirstLine = true;
// Ignore exception gracefully
}
if (lines == 1) {
nbDim = currLine.split("\\t").length;
}
}
countReader.close();
nbPoints = lines;
} catch(Exception e) {
e.printStackTrace();
}
Double[][] data = new Double[nbPoints][nbDim];
// parse data file
try{
// open file
FileInputStream fstream = new FileInputStream("data/" + fileName);
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
// read file line by line
String strLine, splitLine[];
int lineIndex = 0;
boolean firstLoop = true;
while ((strLine = br.readLine()) != null) {
if (firstLoop && textOnFirstLine) {
firstLoop = false;
continue;
}
splitLine = strLine.split("\\t");
for (int i = 0; i < nbDim; ++i) {
data[lineIndex][i] = Double.parseDouble(
splitLine[i].replace(",", "."));
}
++lineIndex;
}
in.close();
//displayData(data);
} catch (Exception e) {
e.printStackTrace();
}
return data;
} |
e9feffe9-032c-4af1-bfc7-4d0f065bee9c | 9 | @Override
public SourceValue unaryOperation(final AbstractInsnNode insn,
final SourceValue value) {
int size;
switch (insn.getOpcode()) {
case LNEG:
case DNEG:
case I2L:
case I2D:
case L2D:
case F2L:
case F2D:
case D2L:
size = 2;
break;
case GETFIELD:
size = Type.getType(((FieldInsnNode) insn).desc).getSize();
break;
default:
size = 1;
}
return new SourceValue(size, insn);
} |
5d48916f-ad17-43ef-8ad9-ccaa56468bd5 | 6 | public void renderTile(int xp, int yp, Tile tile) {
for (int y = 0; y < 32; y++) {
int ya = yp + y;
for (int x = 0; x < 32; x++) {
int xa = xp + x;
if (xa < -32 || xa >= WIDTH || ya < 0 || ya >= HEIGHT) {
break;
}
pixels[xa + ya * WIDTH] = tile.sprite.pixels[x + y * 32];
}
}
} |
50cc6820-ff8d-444a-8416-0e1ce96c5bf7 | 2 | public String esp(String entree){
String str = new String();
int nbCar = 0;
int taille = getTailleLigne();
if(taille % 2 == 1){
nbCar = (taille / 2)+1;
}
else{
nbCar = taille / 2;
}
for(int i=0; i < nbCar; i++){
str += entree;
}
return str;
} |
9e542503-2ed3-425b-b37a-0fd8ae3776e5 | 6 | public int findMOOLAH(){
int index=-1;
for(int q=0;q<objects.size();q++) {
if ((objects.get(q).kind!=0))
continue;
int searchRadius = h/2+10; //radius of whether the object will be findable
boolean search = collisionCircle(getX(),getY(),searchRadius,objects.get(q).getX(),objects.get(q).getY(),objects.get(q).h/2); // whether the object is close enough to be considered
boolean facing = isFacing(q,45); //whether it's facing the object
if(search&&facing) {
if(index==-1) {
index = q;
}
int distance1 = (int)Math.sqrt(Math.pow(x-objects.get(q).x,2)+Math.pow(y-objects.get(q).y,2)); //distance possible object
int distance2 = ((int)Math.sqrt(Math.pow(x-objects.get(index).x,2)+Math.pow(y-objects.get(index).y,2))); // distance for current closest object
if (distance1<distance2) {
index = q;
}
}
}
return index;
} |
baad5cec-7cbc-4053-a656-0b7af5a78eb3 | 8 | public ArrayList<ArrayList<Integer>> fourSum(int[] num, int target) {
// similar to 3 sum; keep two pointers, start and end;
// then keep two middle pointers and compare with the target
// so as to decide to move which middle pointer
ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
if (num.length < 4)
return res;
Arrays.sort(num);
for (int i = 0; i < num.length-3; i++) {
for (int j = num.length; j > i+2; j--) {
int p1 = i+1;
int p2 = j-1;
while (p1 < p2) {
if (num[i]+num[j]+num[p1]+num[p2] == target) {
ArrayList<Integer> r = new ArrayList<Integer>();
r.add(num[i]);
r.add(num[p1]);
r.add(num[p2]);
r.add(num[j]);
if (!contains(res, r))
res.add(r);
p1 += 1;
p2 -= 1;
}
else if (num[i]+num[j]+num[p1]+num[p2] < target) {
p1 += 1;
}
else if ((num[i]+num[j]+num[p1]+num[p2] > target)) {
p2 -= 1;
}
}
}
}
return res;
} |
861e2e6e-48b6-46d3-a0b6-793824743323 | 1 | public void deleteMin()
{
if (isEmpty())
throw new RuntimeException("Symbol table underflow error");
delete(min());
} |
25fd09f2-2d1d-41c9-b60a-ac4c3b03d537 | 9 | public void testLoadInEurope() {
Game game = ServerTestHelper.startServerGame(getTestMap());
InGameController igc = ServerTestHelper.getInGameController();
ServerPlayer dutch = (ServerPlayer) game.getPlayer("model.nation.dutch");
Goods cotton = new Goods(game, null, cottonType, 75);
Europe europe = dutch.getEurope();
Map america = game.getMap();
Unit privateer1 = new ServerUnit(game, europe, dutch, privateerType);
Unit privateer2 = new ServerUnit(game, europe, dutch, privateerType);
// While source in Europe, target in Europe
cotton.setLocation(privateer1);
igc.moveGoods(cotton, privateer2);
assertEquals(privateer2, cotton.getLocation());
// Can not unload directly to Europe
try {
igc.moveGoods(cotton, europe);
fail();
} catch (IllegalStateException e) {
}
// While source moving from America, target in Europe
cotton.setLocation(privateer1);
assertEquals(europe, privateer1.getLocation());
igc.moveTo(dutch, privateer1, america);
try {
igc.moveGoods(cotton, privateer2);
fail();
} catch (IllegalStateException e) {
}
// While source moving to America, target in Europe
cotton.setLocation(privateer1);
igc.moveTo(dutch, privateer1, europe);
try {
igc.moveGoods(cotton, privateer2);
fail();
} catch (IllegalStateException e) {
}
// While source in Europe, target moving to America
privateer1.setLocation(europe);
igc.moveTo(dutch, privateer2, america);
cotton.setLocation(privateer1);
try {
igc.moveGoods(cotton, privateer2);
fail();
} catch (IllegalStateException e) {
}
// While source moving to America, target moving to America
cotton.setLocation(privateer1);
igc.moveTo(dutch, privateer1, america);
try {
igc.moveGoods(cotton, privateer2);
fail();
} catch (IllegalStateException e) {
}
// While source moving from America, target moving to America
cotton.setLocation(privateer1);
igc.moveTo(dutch, privateer1, europe);
try {
igc.moveGoods(cotton, privateer2);
fail();
} catch (IllegalStateException e) {
}
// While source in Europe, target moving from America
privateer1.setLocation(europe);
igc.moveTo(dutch, privateer2, europe);
cotton.setLocation(privateer1);
try {
igc.moveGoods(cotton, privateer2);
fail();
} catch (IllegalStateException e) {
}
// While source moving to America, target moving from America
cotton.setLocation(privateer1);
igc.moveTo(dutch, privateer1, america);
try {
igc.moveGoods(cotton, privateer2);
fail();
} catch (IllegalStateException e) {
}
// While source moving from America, target moving from America
cotton.setLocation(privateer1);
igc.moveTo(dutch, privateer1, europe);
try {
igc.moveGoods(cotton, privateer2);
fail();
} catch (IllegalStateException e) {
}
} |
6a382433-3bee-4ee3-9c8f-7332535f6305 | 0 | public String getArea() {
return Area;
} |
f8be31d5-87e8-4753-8564-c64ac735b22c | 4 | @Override
public void actionPerformed(ActionEvent e)
{
Object actionObject = e.getSource();
if (actionObject instanceof JComboBox)
{
JComboBox selected = (JComboBox)actionObject;
if (selected.equals(this.instrumentOptions))
{
this.controlsController.loadInstrumentSelected();
}
else if (selected.equals(this.soundOptions))
{
VIPlayable sound = (VIPlayable)selected.getSelectedItem();
this.controlsController.setElement(sound);
}
else if (selected.equals(this.keyOptions))
{
VKey key = (VKey)selected.getSelectedItem();
this.controlsController.setKey(key);
}
}
} |
63c62d8f-cf0e-4f7c-96d6-fd3f015e4547 | 8 | void applyTorque() {
if (torque == null)
return;
if (Math.abs(torque.getForce()) < Particle.ZERO)
return;
computeCenter();
int[] exclusion = torque.getExclusion();
double k, sinx, cosx;
outerloop2: for (Atom a : atoms) {
if (exclusion != null && exclusion.length > 0) {
for (int i : exclusion) {
if (i == a.index)
continue outerloop2;
}
}
k = (xCenter - a.rx) / (a.ry - yCenter);
cosx = (a.ry > yCenter ? -torque.getForce() : torque.getForce()) / Math.sqrt(1.0 + k * k);
sinx = k * cosx;
a.fx += cosx;
a.fy += sinx;
}
} |
cd35147c-b20f-4c18-b359-6f9119d63c55 | 8 | public boolean loadSign(World world, ProtectedRegion region) {
ConfigurationSection sign = datacfg.getConfigurationSection("SellSigns." + world.getName() + "." + region);
if (sign == null) {
sign = datacfg.getConfigurationSection("RentSigns." + world.getName() + "." + region);
}
Block block = world.getBlockAt(sign.getInt("X"), sign.getInt("Y"), sign.getInt("Z"));
if (block.getType().equals(Material.SIGN_POST) || block.getType().equals(Material.WALL_SIGN)) {
Type type = Type.valueOf(sign.getString("Type"));
if ((type == Type.RENTING) || (type == Type.RENTED)) { // [rented]
Date paytime = null;
try {
paytime = date.parse(sign.getString("Paytime"));
} catch (ParseException e) {
e.printStackTrace();
}
mh.add(new RentSign(block, region, type, sign.getString("Account"), sign.getDouble("Price"), mh
.getGlobalPrice(sign.getString("GP")), sign.getString("Renter"), sign.getString("Intervall"),
paytime));
} else if ((type == Type.SELLING) || (type == Type.SOLD)) {
mh.add(new SellSign(block, region, type, sign.getString("Account"), sign.getDouble("Price"), mh
.getGlobalPrice(sign.getString("GP"))));
}
} else {
plugin.log.warning(plugin.getCName() + "Could not find a sign block for region " + region
+ ". The marketsign has not been loaded!");
return false;
}
return true;
} |
d73f23eb-b5d2-46cc-b3e9-3ac87b54e6ac | 9 | static private short atos(byte[] in, int fromIndex, int byteLen)
{
int i = fromIndex;
int endIndex = i + byteLen;
int sign = 1;
int r = 0;
while (i < endIndex && Character.isWhitespace((char)in[i]))
{
i++;
}
if (i < endIndex && in[i] == '-')
{
sign = -1;
i++;
}
else if (i < endIndex && in[i] == '+')
{
i++;
}
while (i < endIndex)
{
char ch = (char)in[i];
if ('0' <= ch && ch < '0' + 1)
r = r * 10 + ch - '0';
i++;
}
return (short)(r * sign);
} |
4d43e504-a0e3-4196-8c72-3530bebd0d21 | 5 | public boolean commit(){
synchronized (fatherTable){
for(Map.Entry<Column, ValueWithTimestamp> entry:localData.entrySet()){
Column col=entry.getKey();
ValueWithTimestamp data=entry.getValue();
Long oldNow=fatherTable.getLatestTimestamp(row, col);
if(prevData==null)
System.out.println(null+"");
Long oldPrev=prevData.get(col);
if(oldPrev==null)
oldPrev=(long)-1;
if( oldNow>oldPrev){
System.out.println("OldNow:"+oldNow);
System.out.println("OldPrev:"+oldPrev);
return false; //Some else with a later timestamp has committed first
}
}
//valid to commit
for(Map.Entry<Column, ValueWithTimestamp> entry:localData.entrySet()){
Column col=entry.getKey();
ValueWithTimestamp data=entry.getValue();
fatherTable.write(row, col, data.timestamp, data.value);
}
return true;
}
} |
8aa773b9-72b8-4443-85e4-78bf57ed8903 | 2 | public void mutate(double prob, double variance) {
Random rnd = new Random();
for (int i = 0; i < genes.size(); i++) {
if (rnd.nextDouble() < prob) {
double orig = genes.get(i);
orig += randGaussian(variance, rnd);
genes.set(i, orig);
}
}
} |
a09544c8-b9f6-4f49-b7ae-61886f6b3df2 | 9 | @Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
LocationSQL other = (LocationSQL) obj;
if (worldName == null) {
if (other.worldName != null)
return false;
} else if (!worldName.equals(other.worldName))
return false;
if (x != other.x)
return false;
if (y != other.y)
return false;
if (z != other.z)
return false;
return true;
} |
2160d73a-0450-494a-952b-10301d115226 | 1 | public void readMessage() {
try {
String statement = new String("UPDATE " + DBTable + " SET "
+ "isRead = true"
+ " WHERE mid=?");
PreparedStatement stmt = DBConnection.con.prepareStatement(statement);
stmt.setInt(1, messageID);
stmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
} |
c2233a5a-19a0-414a-80a2-35f94572af9d | 0 | public void setLevelString(String newLevel)
{
level = newLevel;
} |
6b0f02e2-389c-4a52-a5c0-ea183d8f791e | 9 | private int jjMoveStringLiteralDfa8_0(long old0, long active0, long old1, long active1) {
if (((active0 &= old0) | (active1 &= old1)) == 0L) return jjStartNfa_0(6, old0, old1);
try {
curChar = input_stream.readChar();
} catch (IOException e) {
jjStopStringLiteralDfa_0(7, active0, active1);
return 8;
}
switch (curChar) {
case 97:
return jjMoveStringLiteralDfa9_0(active0, 0L, active1, 0x20000L);
case 101:
if ((active0 & 0x2000000L) != 0L) return jjStopAtPos(8, 25);
break;
case 105:
return jjMoveStringLiteralDfa9_0(active0, 0x80000L, active1, 0L);
case 110:
return jjMoveStringLiteralDfa9_0(active0, 0x20000000000L, active1, 0L);
case 115:
return jjMoveStringLiteralDfa9_0(active0, 0x800000L, active1, 0L);
case 116:
return jjMoveStringLiteralDfa9_0(active0, 0x1100000L, active1, 0L);
default :
break;
}
return jjStartNfa_0(7, active0, active1);
} |
4f9fea72-eb35-4086-ba11-ed1e40fd5c14 | 1 | public void testStations() throws Exception {
File climateInput = new File("c:/tmp/clim_data_test.csv");
int staid;
String staname;
String state;
double lng;
double lat;
int elev;
CSTable table = DataIO.table(climateInput, "Data for met test");
Iterator<String[]> inp = table.rows().iterator();
while (inp.hasNext()) {
String[] row = inp.next();
System.out.println(Arrays.toString(row));
staid = Integer.parseInt(row[0]);
staname = row[1];
state = row[2];
lng = Double.parseDouble(row[3]);
lat = Double.parseDouble(row[4]);
elev = Integer.parseInt(row[5]);
}
} |
fcf8f73f-7a82-40ca-a7b8-b0da5148a103 | 4 | private void loadParameters() {
if (loaded.get()) {
return;
}
loaded.set(true);
parameters = new LinkedHashMap<Parameter, Object>();
for (Parameter parameter : Parameter.values()) {
if (clientScriptData.containsKey(parameter.value())) {
parameters.put(parameter, clientScriptData.get(parameter.value()));
}
}
unknowns = new LinkedHashMap<Integer, Object>(clientScriptData);
for (Parameter parameter : parameters.keySet()) {
unknowns.remove(parameter.value());
}
} |
3559ee2a-7b14-4ffc-a4a2-aa389aa9493a | 8 | @Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
CompiledAutomaton other = (CompiledAutomaton) obj;
if (type != other.type) return false;
if (type == AUTOMATON_TYPE.SINGLE) {
if (!term.equals(other.term)) return false;
} else if (type == AUTOMATON_TYPE.NORMAL) {
if (!runAutomaton.equals(other.runAutomaton)) return false;
}
return true;
} |
e312099c-db95-4827-8bc5-98273ca02fa3 | 2 | private boolean Transferencia(Cuenta cuentaReceptora, float importe) {
float interes = importe*this.tipoInteres/100;
if (this.Recargo(importe+interes)) {
if (cuentaReceptora.Ingreso(importe)) {
this.registerMovement(new Recargo("Intereses transferencia "+this.tipoInteres+"% "+importe, interes));
Banco.BancoCuenta.doMovement(new Ingreso("Transferencia de: "+ this.cuenta+ " a "+ cuentaReceptora.cuenta, interes));
return true;
}
//si no se hace la transferencia, me devuelve el saldo.
this.saldo += importe;
}
return false;
} |
4c1eb8c9-ed12-4487-8f02-8f9aa0c02b9c | 2 | protected int findTagByCategory (HashMap<String,TagCategory> tcHM, String strCategory, String strText) {
int pos = -1;
if (tcHM.containsKey(strCategory)) {
TreeSet<TagCategory.Pair> pairSet = tcHM.get(strCategory).getTaggedText(strText.toString(), true);
if (!pairSet.isEmpty()) {
TagCategory.Pair pair = pairSet.first();
pos = pair.getTaggedText().getStartPos();
}
}
return pos;
} |
3b092fab-425d-4829-9523-3c6db0f8b0cd | 2 | public void windowClosing(WindowEvent e) {
if (Game.getThis() == null) {
System.exit(0);
}
else if (confirmQuit("Exit")) {
System.exit(0);
}
} |
8499d908-a8a2-4f45-a895-1149dda87239 | 3 | @SuppressWarnings("deprecation")
public static PacketPlayOutSpawnEntityLiving getMobPacket(String text, Location loc) {
PacketPlayOutSpawnEntityLiving mobPacket = new PacketPlayOutSpawnEntityLiving();
try {
Field a = ReflectionUtil.getDeclaredField(mobPacket.getClass(), "a");
a.setAccessible(true);
a.set(mobPacket, (int) ENTITY_ID);
Field b = ReflectionUtil.getDeclaredField(mobPacket.getClass(), "b");
b.setAccessible(true);
b.set(mobPacket, (byte) EntityType.WITHER.getTypeId());
Field c = ReflectionUtil.getDeclaredField(mobPacket.getClass(), "c");
c.setAccessible(true);
c.set(mobPacket, (int) Math.floor(loc.getBlockX() * 32.0D));
Field d = ReflectionUtil.getDeclaredField(mobPacket.getClass(), "d");
d.setAccessible(true);
d.set(mobPacket, (int) Math.floor(loc.getBlockY() * 32.0D));
Field e = ReflectionUtil.getDeclaredField(mobPacket.getClass(), "e");
e.setAccessible(true);
e.set(mobPacket, (int) Math.floor(loc.getBlockZ() * 32.0D));
Field f = ReflectionUtil.getDeclaredField(mobPacket.getClass(), "f");
f.setAccessible(true);
f.set(mobPacket, (byte) 0);
Field g = ReflectionUtil.getDeclaredField(mobPacket.getClass(), "g");
g.setAccessible(true);
g.set(mobPacket, (byte) 0);
Field h = ReflectionUtil.getDeclaredField(mobPacket.getClass(), "h");
h.setAccessible(true);
h.set(mobPacket, (byte) 0);
Field i = ReflectionUtil.getDeclaredField(mobPacket.getClass(), "i");
i.setAccessible(true);
i.set(mobPacket, (byte) 0);
Field j = ReflectionUtil.getDeclaredField(mobPacket.getClass(), "j");
j.setAccessible(true);
j.set(mobPacket, (byte) 0);
Field k = ReflectionUtil.getDeclaredField(mobPacket.getClass(), "k");
k.setAccessible(true);
k.set(mobPacket, (byte) 0);
} catch (IllegalArgumentException e1) {
e1.printStackTrace();
} catch (IllegalAccessException e1) {
e1.printStackTrace();
}
DataWatcher watcher = getWatcher(text, 300);
try {
Field t = PacketPlayOutSpawnEntityLiving.class.getDeclaredField("l");
t.setAccessible(true);
t.set(mobPacket, watcher);
} catch (Exception ex) {
ex.printStackTrace();
}
return mobPacket;
} |
e67d842c-fc12-426c-be28-eb245fb9fde5 | 2 | public Edge getEdge(Tile t1, Tile t2, Direction d1) {
Edge newEdge=null;
if (type.endsWith("Door")) {
String keyName = getDatumValue("Key Name");
Item key = new Item(keyName, 1);
newEdge = new Exit(t1, t2, true, d1, d1.getOppositeDirection(), key);
}
if (type.endsWith("Wall")) {
newEdge = new Edge(t1, t2, false, d1, d1.getOppositeDirection());
}
return newEdge;
} |
a5f33886-9d85-432f-8d1a-02f127790fb4 | 6 | public void reshuffle(CardArray p1cards, CardArray p2cards) {
Deck newdeck = new Deck();
CardArray shouldRemoved = new CardArray();
cards = (CardArray) newdeck.cards.clone();
shouldRemoved.add(downcard);
for (Card i : p1cards) {
shouldRemoved.add(i);
}
for (Card i : p2cards) {
shouldRemoved.add(i);
}
for (Card i : shouldRemoved) {
for (Card y : cards) {
if (i.num() == y.num() && i.suit() == y.suit()) {
cards.remove(y);
break;
}
}
}
shuffle();
} |
06859e02-9ca1-4cb9-879c-a905ac675734 | 6 | @Override
public void doPromote(ScriptRunner pScriptRunner, PromotionFile pFile)
throws ExPromote {
long lStart = System.currentTimeMillis();
Logger.logInfo("\nPromote DatabaseSource " + pFile.getFilePath());
//Read the DBSource file in
String lFileContents;
try {
lFileContents = FileUtils.readFileToString(pScriptRunner.resolveFile(pFile.getFilePath()));
}
catch (IOException e) {
throw new ExFatalError("Failed to read contents of file " + pFile.getFilePath(), e);
}
List<ScriptExecutable> lExecutableList;
try {
lExecutableList = ScriptExecutableParser.parseScriptExecutables(lFileContents, false);
}
catch (ExParser e) {
throw new ExFatalError("Failed to read contents of file " + pFile.getFilePath() + ": " + e.getMessage(), e);
}
Logger.logDebug("Validating source file");
//Validate contents
for(ScriptExecutable lExecutable : lExecutableList){
if(!(lExecutable instanceof ScriptSQL)){
throw new ExPromote("File " + pFile.getFilePath() + " has invalid contents: non-SQL markup not permitted in Database Source, " +
"but a " + lExecutable.getDisplayString() + " command was found");
}
}
try {
for(ScriptExecutable lExecutable : lExecutableList){
lExecutable.execute(pScriptRunner.getDatabaseConnection());
}
}
catch (Throwable th){
throw new ExPromote("Failed to promote DatabaseSource " + pFile.getFilePath() + ": " + th.getMessage(), th);
}
long lTime = System.currentTimeMillis() - lStart;
Logger.logInfo("OK (took " + lTime + "ms)");
} |
cb1311ae-2b8a-46f9-8c52-f7a234e9639b | 9 | public static User getUser(int id) {
String url = "jdbc:mysql://ouaamou.com.mysql:3306/ouaamou_com";
String username = "ouaamou_com";
String password = "7ttrBnUR";
try {
Class.forName("com.mysql.jdbc.Driver");
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
User user = new User();
Connection connection = null;
Statement statement = null;
ResultSet result = null;
try {
connection = DriverManager.getConnection(url, username, password);
statement = connection.createStatement();
result = statement.executeQuery("SELECT id, first_name, last_name, email, phone_number FROM dw_user WHERE id = " + id);
if(result.next()) {
user.setId(result.getInt("id"));
user.setFirstName(result.getString("first_name"));
user.setLastName(result.getString("last_name"));
user.setEmail(result.getString("email"));
user.setPhoneNumber(result.getString("phone_number"));
}
else {
user = null;
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (result != null) {
try {
result.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
return user;
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.