_id
stringlengths
2
7
title
stringlengths
3
140
partition
stringclasses
3 values
text
stringlengths
73
34.1k
language
stringclasses
1 value
meta_information
dict
q181000
ExecS.main
test
public static void main(String[] args) { ExecS run = new ExecS(); int ret = run.execute(args); System.exit(ret); }
java
{ "resource": "" }
q181001
MuteEvent.createMuteEvent
test
public static Optional<MuteEvent> createMuteEvent(Identification source, Identification target) { if (target == null || target.equals(source)) return Optional.empty(); try { MuteEvent muteRequest = new MuteEvent(source); muteRequest.addResource(new SelectorResource(source, target)); return Optional.of(muteRequest); } catch (IllegalArgumentException e) { return Optional.empty(); } }
java
{ "resource": "" }
q181002
MuteEvent.createMuteEvent
test
public static Optional<MuteEvent> createMuteEvent(Identification source) { if (source == null) return Optional.empty(); try { MuteEvent muteRequest = new MuteEvent(source); return Optional.of(muteRequest); } catch (IllegalArgumentException e) { return Optional.empty(); } }
java
{ "resource": "" }
q181003
CachingGoodwillAccessor.getSchema
test
public GoodwillSchema getSchema(final String schemaName) { GoodwillSchema schema = knownSchemata.get(schemaName); if (schema == null) { refreshSchemataCache(); schema = knownSchemata.get(schemaName); } return schema; }
java
{ "resource": "" }
q181004
Gen_ExecJarScripts.writeFile
test
public boolean writeFile(File file, List<String> lines){ if(file.exists()){ file.delete(); } try { FileWriter out = new FileWriter(file); for(String s : lines){ out.write(s); out.write(System.getProperty("line.separator")); } out.close(); file.setExecutable(true); } catch (IOException ex) { System.err.println(this.getAppName() + ": IO exception while writing to file - " + file + " with message: " + ex.getMessage()); return false; } return true; }
java
{ "resource": "" }
q181005
Gen_ExecJarScripts.inExecJar
test
protected boolean inExecJar(){ Class<Gen_ExecJarScripts> clazz = Gen_ExecJarScripts.class; String className = clazz.getSimpleName() + ".class"; String classPath = clazz.getResource(className).toString(); if (!classPath.startsWith("jar")) { System.err.println(this.getAppName() + ": not started in a jar, cannot proceed"); return false; } String manifestPath = classPath.substring(0, classPath.lastIndexOf("!") + 1) + "/META-INF/MANIFEST.MF"; Manifest manifest; try { manifest = new Manifest(new URL(manifestPath).openStream()); } catch (IOException ex) { System.err.println(this.getAppName() + ": exception while retrieving manifest: " + ex.getMessage()); return false; } Attributes attr = manifest.getMainAttributes(); if(StringUtils.isBlank(attr.getValue("Main-Class"))){ System.err.println(this.getAppName() + ": no main class in manifest, probably not an executable JAR, cannot continue"); return false; } return true; }
java
{ "resource": "" }
q181006
Gen_ExecJarScripts.addOption
test
protected void addOption(ApplicationOption<?> option){ if(option!=null){ this.getCli().addOption(option); this.options.add(option); } }
java
{ "resource": "" }
q181007
GoodwillSchema.getSchema
test
public ArrayList<GoodwillSchemaField> getSchema() { final ArrayList<GoodwillSchemaField> items = new ArrayList<GoodwillSchemaField>(thriftItems.values()); Collections.sort(items, new Comparator<GoodwillSchemaField>() { @Override public int compare(final GoodwillSchemaField left, final GoodwillSchemaField right) { return Short.valueOf(left.getId()).compareTo(right.getId()); } }); return items; }
java
{ "resource": "" }
q181008
GoodwillSchema.getFieldByName
test
public GoodwillSchemaField getFieldByName(final String name) { for (final GoodwillSchemaField field : thriftItems.values()) { if (field.getName().equals(name)) { return field; } } return null; }
java
{ "resource": "" }
q181009
CF_Utils.getPkgName
test
public final static String getPkgName(JarEntry entry){ if(entry==null){ return ""; } String s = entry.getName(); if(s==null){ return ""; } if(s.length()==0){ return s; } if(s.startsWith("/")){ s = s.substring(1, s.length()); } if(s.endsWith("/")){ s = s.substring(0, s.length()-1); } return s.replace('/', '.'); }
java
{ "resource": "" }
q181010
ContentMap.mapContentToValues
test
private ImmutableMap<C, V> mapContentToValues( final ImmutableMap<K, V> base ) { final ImmutableMap.Builder<C, V> builder = ImmutableMap.builder(); for (final Entry<K, V> entry : base.entrySet()) { builder.put( this.key(entry.getKey()), entry.getValue() ); } return builder.build(); }
java
{ "resource": "" }
q181011
EventListener.createEventListener
test
public static Optional<EventListener> createEventListener(String descriptor, String description, String descriptorID, Identifiable identifiable) throws IllegalArgumentException{ if (!descriptorID.matches("[\\w\\-_]+")) throw new IllegalArgumentException("descriptorID: " + descriptorID + " contains illegal characters"); return IdentificationManagerM.getInstance().getIdentification(identifiable) .flatMap(id -> Event.createEvent(CommonEvents.Type.NOTIFICATION_TYPE, id, Collections.singletonList(descriptor))) .map(event -> new EventListener(event, descriptor, description, descriptorID)); }
java
{ "resource": "" }
q181012
IterativeCallback.setState
test
public IterativeState<T,R> setState(IterativeState<T,R> new_state) { IterativeState<T,R> old_state = this.state; this.state = new_state; return old_state; }
java
{ "resource": "" }
q181013
IterativeCallback.iterate
test
public R iterate(final FilterableCollection<? extends T> c) { initState(); checkUsed(); // If collection is decorated with a syncronized wrapper then synchronize the iteration if (c instanceof SynchronizedFilterableCollection) { return SyncUtils.synchronizeRead(c, new Callback<R>() { @Override protected void doAction() { _return(doIteration(c.iterator())); } }); } return doIteration(c.iterator()); }
java
{ "resource": "" }
q181014
IterativeCallback.doIteration
test
private R doIteration(Iterator<? extends T> it) { // save the iterator into member variable state.i = it; state.iterations = 0; if (state.do_break == true) return state.return_object; // do the iteration calling nextobject on each while (state.i.hasNext()) { T o = state.i.next(); if (delegate != null) delegate.delegate(o); else iterateObject(o); if (state.do_break == true) return state.return_object; } return state.amended_object; }
java
{ "resource": "" }
q181015
TrackInfoResource.getTrackInfo
test
public static Optional<TrackInfo> getTrackInfo(EventModel eventModel) { if (eventModel.getListResourceContainer().containsResourcesFromSource(RESOURCE_ID)) { return eventModel .getListResourceContainer() .provideResource(RESOURCE_ID) .stream() .findAny() .flatMap(TrackInfo::importFromResource); } else { return Optional.empty(); } }
java
{ "resource": "" }
q181016
Progress.export
test
public HashMap<String, Long> export() { HashMap<String, Long> data = new HashMap<>(); data.put(lengthDescriptor, length); data.put(knownPositionDescriptor, knownPosition); data.put(knownMillisTimeStampDescriptor, knownMillisTimeStamp); return data; }
java
{ "resource": "" }
q181017
Progress.importResource
test
public static Optional<Progress> importResource(ResourceModel resourceModel) { Object resource = resourceModel.getResource(); try { //noinspection unchecked HashMap<String, Long> data = (HashMap<String, Long>) resource; long length = data.get(lengthDescriptor); long knownPosition = data.get(knownPositionDescriptor); long knownTimestamp = data.get(knownMillisTimeStampDescriptor); return Optional.of(new Progress(length, knownPosition, knownTimestamp)); } catch (Exception e) { return Optional.empty(); } }
java
{ "resource": "" }
q181018
FireREST.errorImage
test
public BufferedImage errorImage(String... lines) { if (imageBuffer == null || imageBuffer.getWidth() != imageWidth || imageBuffer.getHeight() != imageHeight) { imageBuffer = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_RGB); } Graphics2D g = (Graphics2D) imageBuffer.getGraphics(); g.setBackground(new Color(64, 32, 32)); g.setColor(new Color(255, 64, 64)); g.clearRect(0, 0, imageWidth, imageHeight); int maxLen = 0; for (String line : lines) { if (line != null) { for (String innerLine : line.split("\n")) { maxLen = Math.max(innerLine.length(), maxLen); } } } int padding = 20; float sizeForWidth = 1.8f * (imageWidth - padding - padding) / maxLen; // should use TextLayout float sizeForHeight = (imageHeight - padding - padding) / lines.length; float lineHeight = Math.min(80, Math.max(12, Math.min(sizeForWidth, sizeForHeight))); float fontSize = 0.8f * lineHeight; Font font = g.getFont().deriveFont(fontSize); g.setFont(font); float y = fontSize + padding; for (String line : lines) { if (line != null) { g.drawString(line, padding, y); y += lineHeight; } } return imageBuffer; }
java
{ "resource": "" }
q181019
FireREST.getImage
test
public BufferedImage getImage(URL url) { String now = new Date().toString(); if (url == null) { return errorImage(now, "(No image url)"); } try { HttpURLConnection urlconn = (HttpURLConnection) url.openConnection(); urlconn.setReadTimeout(msTimeout); urlconn.setConnectTimeout(msTimeout); urlconn.setRequestMethod("GET"); urlconn.connect(); BufferedImage image = ImageIO.read(urlconn.getInputStream()); if (image == null) { return errorImage(now, "(Null image read)"); } imageWidth = image.getWidth(); imageHeight = image.getHeight(); return image; } catch (SocketTimeoutException e) { logger.warn("getImage({}) => {} {}", url, e.getClass().getCanonicalName(), e.getMessage()); return errorImage(now, msTimeout+"ms TIMEOUT"); } catch (Exception e) { logger.warn("getImage({}) => {} {}", url, e.getClass().getCanonicalName(), e.getMessage()); return errorImage(now, "(No image)", url.toString(), e.getMessage()); } }
java
{ "resource": "" }
q181020
FireREST.getJSON
test
public JSONResult getJSON(URL url) { try { logger.debug("Requesting {}", url); StringBuilder text = new StringBuilder(); String line; HttpURLConnection urlconn = (HttpURLConnection) url.openConnection(); urlconn.setReadTimeout(msTimeout); urlconn.setConnectTimeout(msTimeout); urlconn.setRequestMethod("GET"); urlconn.connect(); BufferedReader br = new BufferedReader(new InputStreamReader(urlconn.getInputStream())); while ((line = br.readLine()) != null) { text.append(line); } return new JSONResult(text.toString()); } catch (Throwable e) { throw new FireRESTException(url.toString(), e); } }
java
{ "resource": "" }
q181021
CollectionUtilities.reverse
test
public static <K,V> void reverse(Map<K,V> source, Map<V,K> target) { Iterator<K> i = source.keySet().iterator(); while (i.hasNext()) { K key = i.next(); V value = source.get(key); target.put(value, key); } }
java
{ "resource": "" }
q181022
CartesianProduct.multiplication
test
private Set<R> multiplication() { final Set<R> answer = new LinkedHashSet<>( this.one.size() * this.two.size() ); for (final A left : this.one) { for (final B right : this.two) { final R element = this.function.apply(left, right); if (answer.contains(element)) { throw new IllegalStateException( String.format( "Cartesian product result contains duplicated element %s", element ) ); } answer.add(element); } } return ImmutableSet.copyOf(answer); }
java
{ "resource": "" }
q181023
WorkerThread.start
test
@Override public synchronized void start() { if (!running && !used) { this.running = true; this.used = true; this.setDaemon(true); super.start(); } }
java
{ "resource": "" }
q181024
WorkerThread.returnToPool
test
private void returnToPool() { if(pool != null) { try { pool.returnObject(this); } catch (Exception e1) { log.error("Exception :", e1); } this.pool = null; } }
java
{ "resource": "" }
q181025
EndedEvent.createEndedEvent
test
public static Optional<EndedEvent> createEndedEvent(Identification source) { try { EndedEvent stopRequest = new EndedEvent(source); return Optional.of(stopRequest); } catch (IllegalArgumentException e) { return Optional.empty(); } }
java
{ "resource": "" }
q181026
Playlist.getCurrent
test
public TrackInfo getCurrent() { TrackInfo trackInfo = null; try { trackInfo = queue.get(position); } catch (IndexOutOfBoundsException e) { trackInfo = null; } return trackInfo; }
java
{ "resource": "" }
q181027
Playlist.update
test
public Playlist update(TrackInfo old, TrackInfo newTrackInfo) { List<TrackInfo> list = new ArrayList<>(queue); list.set(list.indexOf(old), newTrackInfo); return new Playlist(queue, name, playbackModes, position); }
java
{ "resource": "" }
q181028
Playlist.shuffle
test
public Playlist shuffle() { int position = getPosition(); long seed = System.nanoTime(); if (position >= 0 && position < queue.size()) { List<TrackInfo> trackInfos = queue.subList(0, position); List<TrackInfo> notPlayed = queue.subList(position, queue.size()); List<TrackInfo> shuffledNotPlayed = new ArrayList<>(notPlayed); Collections.shuffle(shuffledNotPlayed, new Random(seed)); trackInfos.addAll(shuffledNotPlayed); return new Playlist(trackInfos); } else { List<TrackInfo> trackInfos = new ArrayList<>(queue); Collections.shuffle(trackInfos, new Random(seed)); return new Playlist(trackInfos); } }
java
{ "resource": "" }
q181029
Playlist.verify
test
public boolean verify(Capabilities capabilities) { for (PlaybackMode playbackMode : playbackModes) { switch (playbackMode) { case REPEAT: if (!capabilities.canRepeatPlayback()) { return false; } else { break; } case REPEAT_SONG: if (!capabilities.canRepeatPlaybackOfSong()) { return false; } else { break; } case SHUFFLE: if (!capabilities.canShufflePlayback()) { return false; } else { break; } } } return true; }
java
{ "resource": "" }
q181030
Playlist.export
test
public HashMap<String, Object> export() { HashMap<String, Object> data = new HashMap<>(); for (int i = 0; i < queue.size(); i++) { data.put(QUEUE_DESCRIPTOR+i, queue.get(i).export()); } for (int i = 0; i < playbackModes.size(); i++) { data.put(PLAYBACK_MODE_DESCRIPTOR+i, playbackModes.get(i).name()); } data.put(NAME_DESCRIPTOR, name); data.put(POSITION_DESCRIPTOR, position); data.put(DATA_DESCRIPTOR, this.data); return data; }
java
{ "resource": "" }
q181031
StringUtils.escapeForXML
test
public static final String escapeForXML(String string) { if (string == null) { return null; } char ch; int i = 0; int last = 0; char[] input = string.toCharArray(); int len = input.length; StringBuffer out = new StringBuffer((int) (len * 1.3)); for (; i < len; i++) { ch = input[i]; if (ch > '>') { continue; } else if (ch == '<') { if (i > last) { out.append(input, last, i - last); } last = i + 1; out.append(LT_ENCODE); } else if (ch == '>') { if (i > last) { out.append(input, last, i - last); } last = i + 1; out.append(GT_ENCODE); } else if (ch == '&') { if (i > last) { out.append(input, last, i - last); } // Do nothing if the string is of the form &#235; (unicode // value) if (!(len > i + 5 && input[i + 1] == '#' && Character.isDigit(input[i + 2]) && Character.isDigit(input[i + 3]) && Character.isDigit(input[i + 4]) && input[i + 5] == ';')) { last = i + 1; out.append(AMP_ENCODE); } } else if (ch == '"') { if (i > last) { out.append(input, last, i - last); } last = i + 1; out.append(QUOTE_ENCODE); } } if (last == 0) { return string; } if (i > last) { out.append(input, last, i - last); } return out.toString(); }
java
{ "resource": "" }
q181032
SASLMechanism.challengeReceived
test
public void challengeReceived(String challenge) throws IOException { byte response[]; if (challenge != null) { response = sc .evaluateChallenge(StringUtils.decodeBase64(challenge)); } else { response = sc.evaluateChallenge(new byte[0]); } Packet responseStanza; if (response == null) { responseStanza = new Response(); } else { responseStanza = new Response(StringUtils.encodeBase64(response, false)); } // Send the authentication to the server getSASLAuthentication().send(responseStanza); }
java
{ "resource": "" }
q181033
GoodwillSchemaField.toJSON
test
public ByteArrayOutputStream toJSON() throws IOException { final ByteArrayOutputStream out = new ByteArrayOutputStream(); mapper.writeValue(out, this); return out; }
java
{ "resource": "" }
q181034
OutputPluginArgument.run
test
@Override public void run() { while (!stop) { EventModel event; try { event = blockingQueueHandling(); //gets the new Event if one was added to the blockingQueue } catch (InterruptedException e) { getContext().getLogger().warn(e); continue; } List<CompletableFuture<X>> outputExtensions = getContext().getOutput() .generateAllOutputExtensions(this, getArgument(), event); try { outputExtensions = timeOut(outputExtensions, getTimeoutLimit()); } catch (InterruptedException e) { getContext().getLogger().warn(e); } handleFutures(outputExtensions, event); //notifies output-manager when done processing isDone(event); } }
java
{ "resource": "" }
q181035
ContentEventListener.handleEvent
test
public void handleEvent(Event event) { String topic = event.getTopic(); LOGGER.debug("Got Event {} {} ", event, handlers); Collection<IndexingHandler> contentIndexHandler = handlers.get(topic); if (contentIndexHandler != null && contentIndexHandler.size() > 0) { try { int ttl = Utils.toInt(event.getProperty(TopicIndexer.TTL), Integer.MAX_VALUE); for ( IndexingHandler indexingHandler : contentIndexHandler ) { if ( indexingHandler instanceof QoSIndexHandler ) { ttl = Math.min(ttl, Utils.defaultMax(((QoSIndexHandler)indexingHandler).getTtl(event))); } } QueueManager q = null; // queues is ordered by ascending ttl, so the fastest queue is queues[0], // if the ttl is less that that, we can't satisfy it, so we will put it // in the fastest queue if ( ttl < queues[0].batchDelay ) { LOGGER.warn("Unable to satisfy TTL of {} on event {}, posting to the highest priority queue. " + "If this message is logged a lot please adjust the queues or change the event ttl to something that can be satisfied. " + "Filling the highest priority queue is counter productive. ", ttl, event); queues[0].saveEvent(event); } else { for (QueueManager qm : queues) { if (ttl < qm.batchDelay) { q.saveEvent(event); q = null; break; } q = qm; } if (q != null) { q.saveEvent(event); } } } catch (IOException e) { LOGGER.warn(e.getMessage(), e); } } }
java
{ "resource": "" }
q181036
ContentEventListener.joinAll
test
protected void joinAll() throws InterruptedException { if (queues != null) { for (QueueManager q : queues) { q.getQueueDispatcher().join(); } } }
java
{ "resource": "" }
q181037
Authorizable.setProperty
test
public void setProperty(String name, Object value) { if (!readOnly && !FILTER_PROPERTIES.contains(name)) { Object cv = authorizableMap.get(name); if ( value == null ) { if ( cv != null && !(cv instanceof RemoveProperty)) { modifiedMap.put(name, new RemoveProperty()); } } else if (!value.equals(cv)) { modifiedMap.put(name, value); } else if (modifiedMap.containsKey(name) && !value.equals(modifiedMap.get(name))) { modifiedMap.put(name, value); } } }
java
{ "resource": "" }
q181038
Authorizable.removeProperty
test
public void removeProperty(String key) { if (!readOnly && (authorizableMap.containsKey(key) || modifiedMap.containsKey(key))) { modifiedMap.put(key, new RemoveProperty()); } }
java
{ "resource": "" }
q181039
Authorizable.addPrincipal
test
public void addPrincipal(String principal) { if (!readOnly && !principals.contains(principal)) { principals.add(principal); principalsModified = true; } }
java
{ "resource": "" }
q181040
Authorizable.removePrincipal
test
public void removePrincipal(String principal) { if (!readOnly && principals.contains(principal)) { principals.remove(principal); principalsModified = true; } }
java
{ "resource": "" }
q181041
LiteDebugger.rootWindowClosing
test
public void rootWindowClosing(WindowEvent evt) { connection.removePacketListener(listener); ((ObservableReader) reader).removeReaderListener(readerListener); ((ObservableWriter) writer).removeWriterListener(writerListener); }
java
{ "resource": "" }
q181042
PresenceNonConstant.userEncountered
test
@SuppressWarnings("unused") public void userEncountered() { List<String> descriptors = new ArrayList<>(); /* if (strict && ((!present && !fireUnknownIfNotPresent)|| !strictPresent) && addResponseDescriptors) { if (lastSeen.until(LocalDateTime.now(), ChronoUnit.MINUTES) > getMajorMinuteThresholdNotPresent()) { descriptors.add(CommonEvents.Response.MAJOR_RESPONSE_DESCRIPTOR); } else if (lastSeen.until(LocalDateTime.now(), ChronoUnit.MINUTES) > getMinorMinuteThresholdNotPresent()) { descriptors.add(CommonEvents.Response.MINOR_RESPONSE_DESCRIPTOR); } } else if (present && strict && addResponseDescriptors) { if (lastSeen.until(LocalDateTime.now(), ChronoUnit.MINUTES) > getMajorMinuteThresholdPresent()) { descriptors.add(CommonEvents.Response.MAJOR_RESPONSE_DESCRIPTOR); } else if (lastSeen.until(LocalDateTime.now(), ChronoUnit.MINUTES) > getMinorMinuteThresholdNotPresent()) { descriptors.add(CommonEvents.Response.MINOR_RESPONSE_DESCRIPTOR); } }*/ descriptors.add(CommonEvents.Descriptors.NOT_INTERRUPT); boolean known = !fireUnknownIfNotPresent || present; boolean firstPresent = (!strict && !present) || (strict && !strictPresent); long lastSeen = this.lastSeen.until(LocalDateTime.now(), ChronoUnit.SECONDS); Optional<Event> presenceEvent = IdentificationManagerM.getInstance() .getIdentification(this) .flatMap(id -> PresenceEvent.createPresenceEvent(id, strict, known, firstPresent, descriptors, lastSeen)) .map(event -> event.addEventLifeCycleListener(EventLifeCycle.APPROVED, lifeCycle -> { if (known) { this.lastSeen = LocalDateTime.now(); if (strict) this.strictPresent = true; present = true; } })); if (!presenceEvent.isPresent()) { error("unable to create PresenceEvent"); } else { fire(presenceEvent.get(), 5); } }
java
{ "resource": "" }
q181043
PresenceNonConstant.eventFired
test
@Override public void eventFired(EventModel event) { if (event.containsDescriptor(LeavingEvent.ID) || event.containsDescriptor(PresenceEvent.ID)) { if (event.containsDescriptor(LeavingEvent.ID)) { if (event.containsDescriptor(LeavingEvent.GENERAL_DESCRIPTOR)) { present = false; strictPresent = false; } else if (event.containsDescriptor(LeavingEvent.STRICT_DESCRIPTOR)) { nonStrictAvailable().thenAccept(available -> { if (!available) present = false; strictPresent = false; }); } } else { present = true; if (event.containsDescriptor(PresenceEvent.STRICT_DESCRIPTOR)) strictPresent = true; } if (event.containsDescriptor(PresenceEvent.STRICT_DESCRIPTOR)) lastSeen = LocalDateTime.now(); } }
java
{ "resource": "" }
q181044
MusicUsageResource.isPermanent
test
public static boolean isPermanent(ResourceModel resourceModel) { Object resource = resourceModel.getResource(); try { return (Boolean) resource; } catch (ClassCastException e) { return false; } }
java
{ "resource": "" }
q181045
RosterGroup.setName
test
public void setName(String name) { synchronized (entries) { for (RosterEntry entry : entries) { Roster packet = new Roster(); packet.setType(IQ.Type.set); List<String> groupNames = new LinkedList<String>( entry.getGroupNames()); groupNames.remove(this.name); groupNames.add(name); packet.addItem(new JID(entry.getUser()), entry.getName(), entry.getAsk(), entry.getSubscription(), groupNames); connection.sendPacket(packet); } } }
java
{ "resource": "" }
q181046
AbstractHashedMap.containsKey
test
public boolean containsKey(Object key) { int hashCode = hash((key == null) ? NULL : key); HashEntry entry = data[hashIndex(hashCode, data.length)]; // no local // for hash // index while (entry != null) { if (entry.hashCode == hashCode && isEqualKey(key, entry.getKey())) { return true; } entry = entry.next; } return false; }
java
{ "resource": "" }
q181047
AbstractHashedMap.containsValue
test
public boolean containsValue(Object value) { if (value == null) { for (int i = 0, isize = data.length; i < isize; i++) { HashEntry entry = data[i]; while (entry != null) { if (entry.getValue() == null) { return true; } entry = entry.next; } } } else { for (int i = 0, isize = data.length; i < isize; i++) { HashEntry entry = data[i]; while (entry != null) { if (isEqualValue(value, entry.getValue())) { return true; } entry = entry.next; } } } return false; }
java
{ "resource": "" }
q181048
AbstractHashedMap.put
test
public V put(K key, V value) { int hashCode = hash((key == null) ? NULL : key); int index = hashIndex(hashCode, data.length); HashEntry<K, V> entry = data[index]; while (entry != null) { if (entry.hashCode == hashCode && isEqualKey(key, entry.getKey())) { V oldValue = entry.getValue(); updateEntry(entry, value); return oldValue; } entry = entry.next; } addMapping(index, hashCode, key, value); return null; }
java
{ "resource": "" }
q181049
AbstractHashedMap.clear
test
public void clear() { modCount++; HashEntry[] data = this.data; for (int i = data.length - 1; i >= 0; i--) { data[i] = null; } size = 0; }
java
{ "resource": "" }
q181050
AbstractHashedMap.hash
test
protected int hash(Object key) { // same as JDK 1.4 int h = key.hashCode(); h += ~(h << 9); h ^= (h >>> 14); h += (h << 4); h ^= (h >>> 10); return h; }
java
{ "resource": "" }
q181051
AbstractHashedMap.isEqualKey
test
protected boolean isEqualKey(Object key1, Object key2) { return (key1 == key2 || ((key1 != null) && key1.equals(key2))); }
java
{ "resource": "" }
q181052
AbstractHashedMap.isEqualValue
test
protected boolean isEqualValue(Object value1, Object value2) { return (value1 == value2 || value1.equals(value2)); }
java
{ "resource": "" }
q181053
AbstractHashedMap.ensureCapacity
test
protected void ensureCapacity(int newCapacity) { int oldCapacity = data.length; if (newCapacity <= oldCapacity) { return; } if (size == 0) { threshold = calculateThreshold(newCapacity, loadFactor); data = new HashEntry[newCapacity]; } else { HashEntry<K, V> oldEntries[] = data; HashEntry<K, V> newEntries[] = new HashEntry[newCapacity]; modCount++; for (int i = oldCapacity - 1; i >= 0; i--) { HashEntry<K, V> entry = oldEntries[i]; if (entry != null) { oldEntries[i] = null; // gc do { HashEntry<K, V> next = entry.next; int index = hashIndex(entry.hashCode, newCapacity); entry.next = newEntries[index]; newEntries[index] = entry; entry = next; } while (entry != null); } } threshold = calculateThreshold(newCapacity, loadFactor); data = newEntries; } }
java
{ "resource": "" }
q181054
AbstractHashedMap.calculateNewCapacity
test
protected int calculateNewCapacity(int proposedCapacity) { int newCapacity = 1; if (proposedCapacity > MAXIMUM_CAPACITY) { newCapacity = MAXIMUM_CAPACITY; } else { while (newCapacity < proposedCapacity) { newCapacity <<= 1; // multiply by two } if (newCapacity > MAXIMUM_CAPACITY) { newCapacity = MAXIMUM_CAPACITY; } } return newCapacity; }
java
{ "resource": "" }
q181055
AbstractHashedMap.createEntrySetIterator
test
protected Iterator<Map.Entry<K, V>> createEntrySetIterator() { if (size() == 0) { return EmptyIterator.INSTANCE; } return new EntrySetIterator<K, V>(this); }
java
{ "resource": "" }
q181056
Types.loadFromStream
test
public static void loadFromStream(String key, Map<String, Object> output, InputStream binaryStream, String type) throws IOException { DataInputStream dis = new DataInputStream(binaryStream); String ckey = dis.readUTF(); if (!key.equals(ckey)) { throw new IOException("Body Key does not match row key, unable to read"); } readMapFromStream(output, dis); String cftype = null; try { cftype = dis.readUTF(); } catch (IOException e) { LOGGER.debug("No type specified"); } if (cftype != null && !cftype.equals(type)) { throw new IOException( "Object is not of expected column family, unable to read expected [" + type + "] was [" + cftype + "]"); } LOGGER.debug("Finished Reading"); dis.close(); binaryStream.close(); }
java
{ "resource": "" }
q181057
AddOn.register
test
@Override public void register() { prepare(); ContentGenerator[] contentGenerators = registerContentGenerator(); if (contentGenerators != null) { for (ContentGenerator contentGenerator : contentGenerators) { try { getContext().getContentGenerators().registerContentGenerator(contentGenerator); } catch (IllegalIDException e) { context.getLogger().fatal("Illegal Id for Module: " + contentGenerator.getID(), e); } } } EventsControllerModel[] eventsControllerModels = registerEventController(); if (eventsControllerModels != null) { for (EventsControllerModel eventsController : eventsControllerModels) { try { getContext().getEvents().distributor().registerEventsController(eventsController); } catch (IllegalIDException e) { context.getLogger().fatal("Illegal Id for Module: " + eventsController.getID(), e); } } } OutputPluginModel[] outputPluginModels = registerOutputPlugin(); if (outputPluginModels != null) { for (OutputPluginModel outputPlugin : outputPluginModels) { try { getContext().getOutput().addOutputPlugin(outputPlugin); } catch (IllegalIDException e) { context.getLogger().fatal("Illegal Id for Module: " + outputPlugin.getID(), e); } } } OutputExtensionModel[] outputExtensionModels = registerOutputExtension(); if (outputExtensionModels != null) { for (OutputExtensionModel outputExtension : outputExtensionModels) { try { getContext().getOutput().addOutputExtension(outputExtension); } catch (IllegalIDException e) { context.getLogger().fatal("Illegal Id for Module: " + outputExtension.getID(), e); } } } OutputControllerModel[] outputControllerModels = registerOutputController(); if (outputControllerModels != null) { for (OutputControllerModel outputController : outputControllerModels) { try { getContext().getOutput().addOutputController(outputController); } catch (IllegalIDException e) { context.getLogger().fatal("Illegal Id for Module: " + outputController.getID(), e); } } } ActivatorModel[] activatorModels = registerActivator(); getContext().getSystem().registerInitializedListener(() -> { if (activatorModels != null) { for (ActivatorModel activator : activatorModels) { try { getContext().getActivators().addActivator(activator); } catch (IllegalIDException e) { context.getLogger().fatal("Illegal Id for Module: " + activator.getID(), e); } } } }); }
java
{ "resource": "" }
q181058
AddOn.initAddOn
test
@Override public void initAddOn(org.intellimate.izou.system.Context context) { this.context = new Context(context); }
java
{ "resource": "" }
q181059
ReconnectionManager.notifyReconnectionFailed
test
protected void notifyReconnectionFailed(Exception exception) { if (isReconnectionAllowed()) { for (ConnectionListener listener : connection.connectionListeners) { listener.reconnectionFailed(exception); } } }
java
{ "resource": "" }
q181060
ReconnectionManager.notifyAttemptToReconnectIn
test
protected void notifyAttemptToReconnectIn(int seconds) { if (isReconnectionAllowed()) { for (ConnectionListener listener : connection.connectionListeners) { listener.reconnectingIn(seconds); } } }
java
{ "resource": "" }