code
stringlengths
73
34.1k
label
stringclasses
1 value
public static IssueStatus parseStatus(JSONObject object) throws JSONException { final int id = JsonInput.getInt(object, "id"); final String name = JsonInput.getStringNotNull(object, "name"); final IssueStatus result = new IssueStatus(id, name); if (object.has("is_default")) result.setDefaultStatus(JsonInp...
java
public static Project parseMinimalProject(JSONObject content) throws JSONException { final Project result = new Project(); result.setId(JsonInput.getInt(content, "id")); result.setIdentifier(JsonInput.getStringOrNull(content, "identifier")); result.setName(JsonInput.getStringNotNull(content, "name")); retu...
java
public static Project parseProject(JSONObject content) throws JSONException { final Project result = new Project(); result.setId(JsonInput.getInt(content, "id")); result.setIdentifier(JsonInput.getStringOrNull(content, "identifier")); result.setName(JsonInput.getStringNotNull(content, "name")); result.setDesc...
java
public int getRenderPriority (String action, String component, int orientation) { // because we expect there to be relatively few priority overrides, we simply search // linearly through the list for the closest match int ocount = (_overrides != null) ? _overrides.size() : 0; for (in...
java
public void addPriorityOverride (PriorityOverride override) { if (_overrides == null) { _overrides = new ComparableArrayList<PriorityOverride>(); } _overrides.insertSorted(override); }
java
public int fringesOn (int first, int second) { FringeRecord f1 = _frecs.get(first); // we better have a fringe record for the first if (null != f1) { // it had better have some tilesets defined if (f1.tilesets.size() > 0) { FringeRecord f2 = _frecs....
java
public FringeTileSetRecord getFringe (int baseset, int hashValue) { FringeRecord f = _frecs.get(baseset); return f.tilesets.get( hashValue % f.tilesets.size()); }
java
public Window getWindow () { Component parent = getParent(); while (!(parent instanceof Window) && parent != null) { parent = parent.getParent(); } return (Window)parent; }
java
public String getAttributeString(String attName) { Object o = attributes.get(attName); if (o == null) { return null; } else { return (String) o; } }
java
private void maybeSetProperty(final String name, final String value) { if (System.getProperty(name) == null) { System.setProperty(name, value); } }
java
public void render (Graphics2D gfx) { Object oalias = SwingUtil.activateAntiAliasing(gfx); gfx.setColor(getBackground()); gfx.fill(_shape); gfx.setColor(_outline); gfx.draw(_shape); SwingUtil.restoreAntiAliasing(gfx, oalias); if (_icon != null) { ...
java
public void translate (int dx, int dy) { setLocation(_bounds.x + dx, _bounds.y + dy); }
java
public static MisoSceneMetrics getSceneMetrics () { return new MisoSceneMetrics( config.getValue(TILE_WIDTH_KEY, DEF_TILE_WIDTH), config.getValue(TILE_HEIGHT_KEY, DEF_TILE_HEIGHT), config.getValue(FINE_GRAN_KEY, DEF_FINE_GRAN)); }
java
@Override public void onCreate(SQLiteDatabase db) { try { if(builder.tables == null){ throw new SQLiteHelperException("The array of String tables can't be null!!"); } executePragma(db); builder.onCreateCallback.onCreate(db); } catch (S...
java
@Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { try { if (builder.tableNames == null) { throw new SQLiteHelperException("The array of String tableNames can't be null!!"); } builder.onUpgradeCallback.onUpgrade(db, oldVe...
java
static String getHex(Color color) { return String.format("#%02x%02x%02x%02x", color.getRed(), color.getGreen(), color.getBlue(), color.getAlpha()); }
java
public List<ConnectionListener> getConnectionListeners() { if (changes == null) { return (List<ConnectionListener>)Collections.EMPTY_LIST; } List<EventListener> listeners = changes.getListenerList(AMQP); if ((listeners == null) || listeners.isEmpty()) { return (L...
java
public void connect(String url, String virtualHost, String username, String password) { if (websocket != null) { throw new IllegalStateException("AmqpClient already connected"); } this.readyState = ReadyState.CONNECTING; this.url = url; this.userName = username; ...
java
public void disconnect() { if (readyState == ReadyState.OPEN) { // readyState should be set to ReadyState.CLOSED ONLY AFTER the // the WebSocket has been successfully closed in // socketClosedHandler(). this.closeConnection(0, "", 0, 0, null, null); } else...
java
public AmqpChannel openChannel() { int id = ++this.channelCount; AmqpChannel chan = new AmqpChannel(id, this); channels.put(id, chan); return chan; }
java
void closedHandler(Object context, String input, Object frame, String stateName) { if (getReadyState() == ReadyState.CLOSED) { return; } // TODO: Determine whether channels need to be cleaned up. if (this.channels.size() != 0) { for (int i = 1; i <= this....
java
private void socketClosedHandler() { // If the book-keeping has already been completed earlier, then // we should just bail. if (getReadyState() == ReadyState.CLOSED) { return; } // TODO: Determine whether channels need to be cleaned up if (this.chann...
java
AmqpClient tuneOkConnection(int channelMax, int frameMax, int heartbeat) { this.tuneOkConnection(channelMax, frameMax, heartbeat, null, null); return this; }
java
AmqpClient closeOkConnection(Continuation callback, ErrorHandler error) { Object[] args = {}; AmqpBuffer bodyArg = null; String methodName = "closeOkConnection"; String methodId = "10" + "50"; AmqpMethod amqpMethod = MethodLookup.LookupMethod(methodId); Object[] argument...
java
private void fireOnClosed(ConnectionEvent e) { List<EventListener> listeners = changes.getListenerList(AMQP); for (EventListener listener : listeners) { ConnectionListener amqpListener = (ConnectionListener)listener; amqpListener.onConnectionClose(e); } }
java
protected CompositedMirage createCompositedMirage (int index) { if (_sources.length == 1 && _sources[0].frames instanceof TileSetFrameImage) { TileSetFrameImage frames = (TileSetFrameImage)_sources[0].frames; Rectangle tbounds = new Rectangle(); frames.getTrimmedBounds(_o...
java
protected void createComponent ( int componentId, String cclass, String cname, FrameProvider fprov) { // look up the component class information ComponentClass clazz = _classes.get(cclass); if (clazz == null) { log.warning("Non-existent component class", "...
java
public void setFrames (MultiFrameImage frames) { if (frames == null) { // log.warning("Someone set up us the null frames!", "sprite", this); return; } // if these are the same frames we already had, no need to do a bunch of pointless business if (frames == _f...
java
protected void setFrameIndex (int frameIdx, boolean forceUpdate) { // make sure we're displaying a valid frame frameIdx = (frameIdx % _frames.getFrameCount()); // if this is the same frame we're already displaying and we're // not being forced to update, we can stop now if (...
java
private MetricGroup up_down_host_(String host, boolean up) { final GroupName group = GroupName.valueOf( getBasePath(), Tags.valueOf(singletonMap("host", MetricValue.fromStrValue(host)))); return new SimpleMetricGroup(group, singleton(up ? UP_METRIC : DOWN_METRIC)); }
java
public static synchronized JspFactory getDefaultFactory() { if (deflt == null) { try { Class factory = Class.forName("org.apache.jasper.runtime.JspFactoryImpl"); if (factory != null) { deflt = (JspFactory) factory.newInstance(); } ...
java
public VariableInfo[] getVariableInfo(TagData data) { VariableInfo[] result = null; TagExtraInfo tei = getTagExtraInfo(); if (tei != null) { result = tei.getVariableInfo( data ); } return result; }
java
@Nullable private String getProperty(final String name) { assert name != null; ensureConfigured(); return evaluate(System.getProperty(name, props.getProperty(name))); }
java
public static Collection<Attribute> fromJson(ObjectNode object) throws IOException { Collection<Attribute> attributes = new HashSet<>(); convertJsonObject(attributes, object, "", 0, new HashMap<>()); return attributes; }
java
public static String toJsonString(Collection<Attribute> attributeCollection, ObjectMapper objectMapper) throws JsonProcessingException { return objectMapper.writeValueAsString(toObject(attributeCollection)); }
java
public BaseTile getFringeTile (MisoSceneModel scene, int col, int row, Map<FringeTile, WeakReference<FringeTile>> fringes, Map<Long, BufferedImage> masks) { // get the tileset id of the base tile we are considering int underset = adjustTileSetId(scene.getBaseTileId(col, row) >> 16); ...
java
protected FringeTile composeFringeTile (FringerRec[] fringers, Map<FringeTile, WeakReference<FringeTile>> fringes, int hashValue, boolean passable, Map<Long, BufferedImage> masks) { // sort the array so that higher priority fringers get drawn first QuickSort.sort(fringers); ...
java
protected BufferedImage getTileImage (BufferedImage img, FringeConfiguration.FringeTileSetRecord tsr, int baseset, int index, int hashValue, Map<Long, BufferedImage> masks) throws NoSuchTileSetException { int fringeset = tsr.fringe_tsid; TileSet fset = _tmgr.getTileSet(fringe...
java
protected int[] getFringeIndexes (int bits) { int index = BITS_TO_INDEX[bits]; if (index != -1) { int[] ret = new int[1]; ret[0] = index; return ret; } // otherwise, split the bits into contiguous components // look for a zero and start o...
java
public Sound getSound (String path) { ClipBuffer buffer = null; if (_manager.isInitialized()) { buffer = _manager.getClip(_provider, path); } return (buffer == null) ? new BlankSound() : new Sound(this, buffer); }
java
public void dispose () { reclaimAll(); for (PooledSource pooled : _sources) { pooled.source.delete(); } _sources.clear(); // remove from the manager _manager.removeGroup(this); }
java
public void reclaimAll () { // make sure any bound sources are released for (PooledSource pooled : _sources) { if (pooled.holder != null) { pooled.holder.stop(); pooled.holder.reclaim(); pooled.holder = null; } } }
java
protected void baseGainChanged () { // notify any sound currently holding a source for (int ii = 0, nn = _sources.size(); ii < nn; ii++) { Sound holder = _sources.get(ii).holder; if (holder != null) { holder.updateSourceGain(); } } }
java
protected void setFrameIndex (int fidx) { _fidx = fidx; _bounds.width = _frames.getWidth(_fidx); _bounds.height = _frames.getHeight(_fidx); }
java
@Override public synchronized T read(T dto) throws Exception { Cursor cursor = db.query(transformer.getTableName(), transformer.getFields(), transformer.getWhereClause(dto),null, null,null,null); T object = null; if (cursor.moveToFirst()){ object = transformer.transform(cursor); ...
java
@Override public synchronized Collection<T> readAll() throws Exception { Cursor cursor = db.query(transformer.getTableName(), transformer.getFields(), null, null, null, null, null); Collection<T> list = getAllCursor(cursor); return list; }
java
public static int dot (Point v1s, Point v1e, Point v2s, Point v2e) { return ((v1e.x - v1s.x) * (v2e.x - v2s.x) + (v1e.y - v1s.y) * (v2e.y - v2s.y)); }
java
public static int dot (Point vs, Point v1e, Point v2e) { return ((v1e.x - vs.x) * (v2e.x - vs.x) + (v1e.y - vs.y) * (v2e.y - vs.y)); }
java
public static boolean lineIntersection (Point2D p1, Point2D p2, boolean seg1, Point2D p3, Point2D p4, boolean seg2, Point2D result) { // see http://astronomy.swin.edu.au/~pbourke/geometry/lineline2d/ double y43 = p4.getY() - p3.getY(); double x21 =...
java
public static Rectangle grow (Rectangle source, Rectangle target) { if (target == null) { log.warning("Can't grow with null rectangle [src=" + source + ", tgt=" + target + "].", new Exception()); } else if (source == null) { source = new Rectangle(targ...
java
public static Rectangle getTile ( int width, int height, int tileWidth, int tileHeight, int tileIndex) { Rectangle bounds = new Rectangle(); getTile(width, height, tileWidth, tileHeight, tileIndex, bounds); return bounds; }
java
public static void getTile (int width, int height, int tileWidth, int tileHeight, int tileIndex, Rectangle bounds) { // figure out from whence to crop the tile int tilesPerRow = width / tileWidth; // if we got a bogus region, return bogus tile bounds ...
java
private void setNegotiatedExtensions(String extensionsHeader) { if ((extensionsHeader == null) || (extensionsHeader.trim().length() == 0)) { _negotiatedExtensions = null; return; } String[] extns = extensionsHeader.split(","); List<String...
java
public static int scrollToIndex(String listRef, int itemIndex) throws Exception { int listViewIndex = getListViewIndex(listRef); if (itemIndex >= numItemsInList(listRef)) throw new Exception("Item index is greater than number of items in the list"); // scroll to the top of this vie...
java
public int value () { int end = Math.min(_history.length, _index); int value = 0; for (int ii = 0; ii < end; ii++) { value += _history[ii]; } return (end > 0) ? (value/end) : 0; }
java
protected Frob loop (String pkgPath, String key, float pan, byte cmd) { SoundKey skey = new SoundKey(cmd, pkgPath, key, 0, _clipVol, pan); addToPlayQueue(skey); return skey; // it is a frob }
java
protected void addToPlayQueue (SoundKey skey) { boolean queued = enqueue(skey, true); if (queued) { if (_verbose.getValue()) { log.info("Sound request [key=" + skey.key + "]."); } } else /* if (_verbose.getValue()) */ { log.warning("SoundM...
java
protected boolean enqueue (SoundKey key, boolean okToStartNew) { boolean add; boolean queued; synchronized (_queue) { if (key.cmd == PLAY && _queue.size() > MAX_QUEUE_SIZE) { queued = add = false; } else { _queue.appendLoud(key); ...
java
protected void spoolerRun () { while (true) { try { SoundKey key; synchronized (_queue) { _freeSpoolers++; key = _queue.get(MAX_WAIT_TIME); _freeSpoolers--; if (key == null || key.cmd...
java
protected void processKey (SoundKey key) throws Exception { switch (key.cmd) { case PLAY: case LOOP: playSound(key); break; case LOCK: if (!isTesting()) { synchronized (_clipCache) { try { ...
java
protected byte[] getClipData (SoundKey key) throws IOException, UnsupportedAudioFileException { byte[][] data; synchronized (_clipCache) { // if we're testing, clear all non-locked sounds every time if (isTesting()) { _clipCache.clear(); } ...
java
protected static void adjustVolume (Line line, float vol) { FloatControl control = (FloatControl) line.getControl(FloatControl.Type.MASTER_GAIN); // the only problem is that gain is specified in decibals, which is a logarithmic scale. // Since we want max volume to leave the sample unchange...
java
protected static void adjustPan (Line line, float pan) { try { FloatControl control = (FloatControl) line.getControl(FloatControl.Type.PAN); control.setValue(pan); } catch (Exception e) { log.debug("Cannot set pan on line: " + e); } }
java
public void tick (long tickStamp) { if (_nextTime == -1) { // First time through _nextTime = tickStamp + _initDelay; } else if (tickStamp >= _nextTime) { // If we're repeating, set the next time to run, otherwise, reset if (_repeatDelay != 0L) { ...
java
private AffineTransform getRotationTransform () { double theta; switch (_orient) { case NORTH: default: theta = 0.0; break; case SOUTH: theta = Math.PI; break; case EAST: ...
java
public Stream<Entry<MatchedName, MetricValue>> filter(Context t) { return t.getTSData().getCurrentCollection().get(this::match, x -> true).stream() .flatMap(this::filterMetricsInTsv); }
java
public static final Color blend (Color c1, Color c2) { return new Color((c1.getRed() + c2.getRed()) >> 1, (c1.getGreen() + c2.getGreen()) >> 1, (c1.getBlue() + c2.getBlue()) >> 1); }
java
public static final Color blend (Color c1, Color c2, float firstperc) { float p2 = 1.0f - firstperc; return new Color((int) (c1.getRed() * firstperc + c2.getRed() * p2), (int) (c1.getGreen() * firstperc + c2.getGreen() * p2), (int) (c1.getBlue() * firstperc + c2.get...
java
protected void setupLogging(@Nullable final Level level) { // install JUL adapter SLF4JBridgeHandler.removeHandlersForRootLogger(); SLF4JBridgeHandler.install(); // conifgure gossip bootstrap loggers with target factory Log.configure(LoggerFactory.getILoggerFactory()); log.debug("Logging setup;...
java
public void addAnimations (Animation[] anims) { int acount = anims.length; for (int ii = 0; ii < acount; ii++) { addAnimation(anims[ii]); } }
java
public static SoundManager createSoundManager (RunQueue rqueue) { if (_soundmgr != null) { throw new IllegalStateException("A sound manager has already been created."); } _soundmgr = new SoundManager(rqueue); return _soundmgr; }
java
public void updateStreams (float time) { // iterate backwards through the list so that streams can dispose of themselves during // their update for (int ii = _streams.size() - 1; ii >= 0; ii--) { _streams.get(ii).update(time); } // delete any finalized objects ...
java
public void loadClip (ClipProvider provider, String path, Observer observer) { getClip(provider, path, observer); }
java
protected synchronized void deleteFinalizedObjects () { if (_finalizedSources != null) { IntBuffer idbuf = BufferUtils.createIntBuffer(_finalizedSources.length); idbuf.put(_finalizedSources).rewind(); AL10.alDeleteSources(idbuf); _finalizedSources = null; ...
java
protected void paintLabels (Graphics2D gfx, int x, int y) { _label.render(gfx, x, y); }
java
public void addRule(ValidationData vd) { this.rules.addAll(vd.getValidationRules().stream().filter(vr -> vr.isUse()).collect(Collectors.toList())); }
java
public void initDataGroup(ParamType paramType, List<ValidationData> lists) { this.paramType = paramType; lists.forEach(vd -> { this.addRule(vd); }); }
java
@Override public HandlerRegistration addMapZoomEndHandler(final Runnable zoomHandler){ return mapWidget.addZoomChangeHandler(zoomChangeMapEvent -> zoomHandler.run()); }
java
public boolean sameProduct(JProduct p, Map<String, String> featLinks, boolean exactContent) { List<JCell> tempCells = new ArrayList<>(this.cells); if(p.getCells().size() != this.cells.size()){ return false; } for(JCell pC : p.getCells()){ for(JCell thisC: this.cells){ if(tempCells.contains(thisC)){ ...
java
public static Annotation getAnnotation(Annotation[] annotations, Class<?> annotationClass) { return Arrays.stream(annotations).filter(annotation -> annotation.annotationType().equals(annotationClass)).findFirst().orElse(null); }
java
public List<ValidationData> getValidationDatas(ParamType paramType, String key) { if (this.urlMap == null || this.validationDataRuleListMap == null) { log.info("url map is empty :: " + key ); return null; } if (key == null || paramType == null) { throw new Va...
java
public static AssistType all() { AssistType assistType = new AssistType(); assistType.nullable = true; assistType.string = true; assistType.number = true; assistType.enumType = true; assistType.list = true; assistType.obj = true; return assistType; }
java
public List<ReqUrl> getReqUrls() { String url = this.getClassMappingUrl(this.getParentClass()); RequestAnnotation requestAnnotation = new RequestAnnotation(this.getParentMethod()); url += this.getRequestMappingUrl(requestAnnotation.getValue()); List<ReqUrl> list = new ArrayList<>(); ...
java
public boolean sameJSONFormat(JSONFormat jf){ Map<String,String> featLinks = new HashMap<>(); if(!this.name.equals(jf.name) || !this.creator.equals(jf.creator) || !this.license.equals(jf.license) || !this.source.equals(jf.source)){ return false; }else if(!this.sameFeatures(jf, featLinks)){ System.out.print...
java
private void validateFacetFields(String[] facetFieldList) { if(facetFieldList == null || facetFieldList.length == 0){ return; } for (String facetfield : facetFieldList){ if(schema.getColumnIndex(facetfield) < 0){ throw new IllegalArgumentException("Facet f...
java
private FacetList calculateFacetList(AbstractDataTable table, String[] facetFields) { if(facetFields == null || facetFields.length == 0){ throw new NullPointerException("Facet field list empty"); } FacetList facetList = new FacetList(); for (String facetField : facetFields) ...
java
public DataProvider getDataProvider(){ if(this.dataProvider == null){ // EventLogger.logEvent("org.wwarn.surveyor.client.mvp.SimpleClientFactory", "getDataProvider", "begin"); // EventLogger.logEvent("org.wwarn.surveyor.client.mvp.SimpleClientFactory", "getSchema", "begin"); D...
java
@Override public void setConfigDynamically(Config viewConfig) { if(viewConfig instanceof MapViewConfig) { MapViewConfig newMapViewConfig = (MapViewConfig) viewConfig; updateMapViewConfig(newMapViewConfig); } }
java
public void sessionCheck(HttpServletRequest req) { String authHeader = req.getHeader("Authorization"); if (authHeader != null && this.validationSessionCheck(authHeader)) { return; } if (req.getCookies() != null) { Cookie cookie = Arrays.stream(req.getCookies()).f...
java
public ValidationSessionInfo checkAuth(ValidationLoginInfo info, HttpServletRequest req, HttpServletResponse res) { if (info.getToken() == null || info.getToken().isEmpty()) { throw new ValidationLibException("UnAuthorization", HttpStatus.UNAUTHORIZED); } if (this.validationConfig.g...
java
public ValidationSessionInfo createSession(HttpServletRequest req, HttpServletResponse res) { String key = this.getSessionKey(); ValidationSessionInfo sessionInfo = new ValidationSessionInfo(req, key); this.sessionMap.put(key, sessionInfo); res.addCookie(new Cookie("AuthToken", key)); ...
java
public Object getSession(HttpServletRequest req) { if (req.getCookies() == null) { return null; } Cookie cookie = Arrays.stream(req.getCookies()).filter(c -> c.getName().equalsIgnoreCase("ValidationSession")).findFirst().orElse(null); if (cookie == null) { retur...
java
private String response(HttpURLConnection connection) throws LightblueHttpClientException { try (InputStream responseStream = connection.getInputStream()) { return readResponseStream(responseStream, connection); } catch (IOException e) { return readErrorStream(connection,e); ...
java
private String readResponseStream(InputStream responseStream, HttpURLConnection connection) throws IOException { LOGGER.debug("Reading response stream"); InputStream decodedStream = responseStream; if (compression == Compression.LZF && "lzf".equals(connection.getHeaderField("Content-...
java
protected void openConnection() throws SQLException { if (connection == null) { try { Class.forName(configuration.getJdbcDriver()); } catch (NullPointerException npe) { throw new RuntimeException("error while lookup jdbc driver class. jdbc driver is not co...
java
protected void closeConnection() throws SQLException { if (connection != null && !connection.isClosed()) { connection.close(); connection = null; } }
java
protected void executeScript(final String filename, final Statement statement) throws SQLException { LOG.info("Executing sql script: " + filename); InputStream fileInputStream; try { fileInputStream = ConfigurationLoader.loadResource(filename); } catch (FileNotFoundException...
java
@SuppressWarnings("unchecked") public <T> HandlerRegistration register(Deserializer<T> deserializer) { final HandlerRegistration reg = bindDeserializerToType(deserializer, deserializer.handledType()); if (deserializer instanceof HasImpl) { Class[] impls = ((HasImpl) deserializer).implTy...
java
@SuppressWarnings("unchecked") public <T> HandlerRegistration register(Serializer<T> serializer) { final HandlerRegistration reg = bindSerializerToType(serializer, serializer.handledType()); if (serializer instanceof HasImpl) { Class[] impls = ((HasImpl) serializer).implTypes(); ...
java
@SuppressWarnings("unchecked") public <T> Deserializer<T> getDeserializer(Class<T> type, String mediaType) throws SerializationException { checkNotNull(type, "Type (Class<T>) cannot be null."); checkNotNull(mediaType, "Media-Type cannot be null."); final String typeName = getClassName(type)...
java