code
stringlengths
130
281k
code_dependency
stringlengths
182
306k
public class class_name { public void register(InstanceInfo registrant, int leaseDuration, boolean isReplication) { try { read.lock(); Map<String, Lease<InstanceInfo>> gMap = registry.get(registrant.getAppName()); REGISTER.increment(isReplication); if (gMap == null) { final ConcurrentHashMap<String, Lease<InstanceInfo>> gNewMap = new ConcurrentHashMap<String, Lease<InstanceInfo>>(); gMap = registry.putIfAbsent(registrant.getAppName(), gNewMap); if (gMap == null) { gMap = gNewMap; } } Lease<InstanceInfo> existingLease = gMap.get(registrant.getId()); // Retain the last dirty timestamp without overwriting it, if there is already a lease if (existingLease != null && (existingLease.getHolder() != null)) { Long existingLastDirtyTimestamp = existingLease.getHolder().getLastDirtyTimestamp(); Long registrationLastDirtyTimestamp = registrant.getLastDirtyTimestamp(); logger.debug("Existing lease found (existing={}, provided={}", existingLastDirtyTimestamp, registrationLastDirtyTimestamp); // this is a > instead of a >= because if the timestamps are equal, we still take the remote transmitted // InstanceInfo instead of the server local copy. if (existingLastDirtyTimestamp > registrationLastDirtyTimestamp) { logger.warn("There is an existing lease and the existing lease's dirty timestamp {} is greater" + " than the one that is being registered {}", existingLastDirtyTimestamp, registrationLastDirtyTimestamp); logger.warn("Using the existing instanceInfo instead of the new instanceInfo as the registrant"); registrant = existingLease.getHolder(); } } else { // The lease does not exist and hence it is a new registration synchronized (lock) { if (this.expectedNumberOfClientsSendingRenews > 0) { // Since the client wants to register it, increase the number of clients sending renews this.expectedNumberOfClientsSendingRenews = this.expectedNumberOfClientsSendingRenews + 1; updateRenewsPerMinThreshold(); } } logger.debug("No previous lease information found; it is new registration"); } Lease<InstanceInfo> lease = new Lease<InstanceInfo>(registrant, leaseDuration); if (existingLease != null) { lease.setServiceUpTimestamp(existingLease.getServiceUpTimestamp()); } gMap.put(registrant.getId(), lease); synchronized (recentRegisteredQueue) { recentRegisteredQueue.add(new Pair<Long, String>( System.currentTimeMillis(), registrant.getAppName() + "(" + registrant.getId() + ")")); } // This is where the initial state transfer of overridden status happens if (!InstanceStatus.UNKNOWN.equals(registrant.getOverriddenStatus())) { logger.debug("Found overridden status {} for instance {}. Checking to see if needs to be add to the " + "overrides", registrant.getOverriddenStatus(), registrant.getId()); if (!overriddenInstanceStatusMap.containsKey(registrant.getId())) { logger.info("Not found overridden id {} and hence adding it", registrant.getId()); overriddenInstanceStatusMap.put(registrant.getId(), registrant.getOverriddenStatus()); } } InstanceStatus overriddenStatusFromMap = overriddenInstanceStatusMap.get(registrant.getId()); if (overriddenStatusFromMap != null) { logger.info("Storing overridden status {} from map", overriddenStatusFromMap); registrant.setOverriddenStatus(overriddenStatusFromMap); } // Set the status based on the overridden status rules InstanceStatus overriddenInstanceStatus = getOverriddenInstanceStatus(registrant, existingLease, isReplication); registrant.setStatusWithoutDirty(overriddenInstanceStatus); // If the lease is registered with UP status, set lease service up timestamp if (InstanceStatus.UP.equals(registrant.getStatus())) { lease.serviceUp(); } registrant.setActionType(ActionType.ADDED); recentlyChangedQueue.add(new RecentlyChangedItem(lease)); registrant.setLastUpdatedTimestamp(); invalidateCache(registrant.getAppName(), registrant.getVIPAddress(), registrant.getSecureVipAddress()); logger.info("Registered instance {}/{} with status {} (replication={})", registrant.getAppName(), registrant.getId(), registrant.getStatus(), isReplication); } finally { read.unlock(); } } }
public class class_name { public void register(InstanceInfo registrant, int leaseDuration, boolean isReplication) { try { read.lock(); // depends on control dependency: [try], data = [none] Map<String, Lease<InstanceInfo>> gMap = registry.get(registrant.getAppName()); REGISTER.increment(isReplication); // depends on control dependency: [try], data = [none] if (gMap == null) { final ConcurrentHashMap<String, Lease<InstanceInfo>> gNewMap = new ConcurrentHashMap<String, Lease<InstanceInfo>>(); gMap = registry.putIfAbsent(registrant.getAppName(), gNewMap); // depends on control dependency: [if], data = [none] if (gMap == null) { gMap = gNewMap; // depends on control dependency: [if], data = [none] } } Lease<InstanceInfo> existingLease = gMap.get(registrant.getId()); // Retain the last dirty timestamp without overwriting it, if there is already a lease if (existingLease != null && (existingLease.getHolder() != null)) { Long existingLastDirtyTimestamp = existingLease.getHolder().getLastDirtyTimestamp(); Long registrationLastDirtyTimestamp = registrant.getLastDirtyTimestamp(); logger.debug("Existing lease found (existing={}, provided={}", existingLastDirtyTimestamp, registrationLastDirtyTimestamp); // depends on control dependency: [if], data = [none] // this is a > instead of a >= because if the timestamps are equal, we still take the remote transmitted // InstanceInfo instead of the server local copy. if (existingLastDirtyTimestamp > registrationLastDirtyTimestamp) { logger.warn("There is an existing lease and the existing lease's dirty timestamp {} is greater" + " than the one that is being registered {}", existingLastDirtyTimestamp, registrationLastDirtyTimestamp); // depends on control dependency: [if], data = [none] logger.warn("Using the existing instanceInfo instead of the new instanceInfo as the registrant"); // depends on control dependency: [if], data = [none] registrant = existingLease.getHolder(); // depends on control dependency: [if], data = [none] } } else { // The lease does not exist and hence it is a new registration synchronized (lock) { // depends on control dependency: [if], data = [none] if (this.expectedNumberOfClientsSendingRenews > 0) { // Since the client wants to register it, increase the number of clients sending renews this.expectedNumberOfClientsSendingRenews = this.expectedNumberOfClientsSendingRenews + 1; // depends on control dependency: [if], data = [none] updateRenewsPerMinThreshold(); // depends on control dependency: [if], data = [none] } } logger.debug("No previous lease information found; it is new registration"); // depends on control dependency: [if], data = [none] } Lease<InstanceInfo> lease = new Lease<InstanceInfo>(registrant, leaseDuration); if (existingLease != null) { lease.setServiceUpTimestamp(existingLease.getServiceUpTimestamp()); // depends on control dependency: [if], data = [(existingLease] } gMap.put(registrant.getId(), lease); // depends on control dependency: [try], data = [none] synchronized (recentRegisteredQueue) { // depends on control dependency: [try], data = [none] recentRegisteredQueue.add(new Pair<Long, String>( System.currentTimeMillis(), registrant.getAppName() + "(" + registrant.getId() + ")")); } // This is where the initial state transfer of overridden status happens if (!InstanceStatus.UNKNOWN.equals(registrant.getOverriddenStatus())) { logger.debug("Found overridden status {} for instance {}. Checking to see if needs to be add to the " + "overrides", registrant.getOverriddenStatus(), registrant.getId()); // depends on control dependency: [if], data = [none] if (!overriddenInstanceStatusMap.containsKey(registrant.getId())) { logger.info("Not found overridden id {} and hence adding it", registrant.getId()); // depends on control dependency: [if], data = [none] overriddenInstanceStatusMap.put(registrant.getId(), registrant.getOverriddenStatus()); // depends on control dependency: [if], data = [none] } } InstanceStatus overriddenStatusFromMap = overriddenInstanceStatusMap.get(registrant.getId()); if (overriddenStatusFromMap != null) { logger.info("Storing overridden status {} from map", overriddenStatusFromMap); // depends on control dependency: [if], data = [none] registrant.setOverriddenStatus(overriddenStatusFromMap); // depends on control dependency: [if], data = [(overriddenStatusFromMap] } // Set the status based on the overridden status rules InstanceStatus overriddenInstanceStatus = getOverriddenInstanceStatus(registrant, existingLease, isReplication); registrant.setStatusWithoutDirty(overriddenInstanceStatus); // depends on control dependency: [try], data = [none] // If the lease is registered with UP status, set lease service up timestamp if (InstanceStatus.UP.equals(registrant.getStatus())) { lease.serviceUp(); // depends on control dependency: [if], data = [none] } registrant.setActionType(ActionType.ADDED); // depends on control dependency: [try], data = [none] recentlyChangedQueue.add(new RecentlyChangedItem(lease)); // depends on control dependency: [try], data = [none] registrant.setLastUpdatedTimestamp(); // depends on control dependency: [try], data = [none] invalidateCache(registrant.getAppName(), registrant.getVIPAddress(), registrant.getSecureVipAddress()); // depends on control dependency: [try], data = [none] logger.info("Registered instance {}/{} with status {} (replication={})", registrant.getAppName(), registrant.getId(), registrant.getStatus(), isReplication); // depends on control dependency: [try], data = [none] } finally { read.unlock(); } } }
public class class_name { public OIndex<?> createIndex(final String iType) { acquireSchemaReadLock(); try { return owner.createIndex(getFullName(), iType, globalRef.getName()); } finally { releaseSchemaReadLock(); } } }
public class class_name { public OIndex<?> createIndex(final String iType) { acquireSchemaReadLock(); try { return owner.createIndex(getFullName(), iType, globalRef.getName()); // depends on control dependency: [try], data = [none] } finally { releaseSchemaReadLock(); } } }
public class class_name { public void setSize(I_CmsButton.Size size) { if (m_size != null) { removeStyleName(m_size.getCssClassName()); } if (size != null) { addStyleName(size.getCssClassName()); } m_size = size; } }
public class class_name { public void setSize(I_CmsButton.Size size) { if (m_size != null) { removeStyleName(m_size.getCssClassName()); // depends on control dependency: [if], data = [(m_size] } if (size != null) { addStyleName(size.getCssClassName()); // depends on control dependency: [if], data = [(size] } m_size = size; } }
public class class_name { @SuppressWarnings("unchecked") @Override public <WB extends WaveBean> WB waveBean(final Class<WB> waveBeanClass) { if (!getWaveBeanMap().containsKey(waveBeanClass)) { try { final WB waveBean = waveBeanClass.newInstance(); getWaveBeanMap().put(waveBeanClass, waveBean); } catch (InstantiationException | IllegalAccessException e) { LOGGER.error(WAVE_BEAN_CREATION_ERROR, e, waveBeanClass.toString()); } finally { // if (this.waveBean == null) { // this.waveBean = new DefaultWaveBean(); // } } } return (WB) getWaveBeanMap().get(waveBeanClass); } }
public class class_name { @SuppressWarnings("unchecked") @Override public <WB extends WaveBean> WB waveBean(final Class<WB> waveBeanClass) { if (!getWaveBeanMap().containsKey(waveBeanClass)) { try { final WB waveBean = waveBeanClass.newInstance(); getWaveBeanMap().put(waveBeanClass, waveBean); // depends on control dependency: [try], data = [none] } catch (InstantiationException | IllegalAccessException e) { LOGGER.error(WAVE_BEAN_CREATION_ERROR, e, waveBeanClass.toString()); } finally { // depends on control dependency: [catch], data = [none] // if (this.waveBean == null) { // this.waveBean = new DefaultWaveBean(); // } } } return (WB) getWaveBeanMap().get(waveBeanClass); } }
public class class_name { public void setTextFontFamilyName(byte[] fields, String[] fontFamilies) { if (fontFamilies == null) fontFamilies = new String[0]; for (byte field : fields) { getFieldInfos(field).m_fontFamilyNames = fontFamilies; } notifyListeners(); } }
public class class_name { public void setTextFontFamilyName(byte[] fields, String[] fontFamilies) { if (fontFamilies == null) fontFamilies = new String[0]; for (byte field : fields) { getFieldInfos(field).m_fontFamilyNames = fontFamilies; // depends on control dependency: [for], data = [field] } notifyListeners(); } }
public class class_name { protected void onSetColumnNames() { columnNames = ReflectionExtensions.getDeclaredFieldNames(getType(), "serialVersionUID"); for(int i = 0; i < columnNames.length; i++){ columnNames[i] = StringUtils.capitalize(columnNames[i]); } } }
public class class_name { protected void onSetColumnNames() { columnNames = ReflectionExtensions.getDeclaredFieldNames(getType(), "serialVersionUID"); for(int i = 0; i < columnNames.length; i++){ columnNames[i] = StringUtils.capitalize(columnNames[i]); // depends on control dependency: [for], data = [i] } } }
public class class_name { public static String generateDigitsString(int length) { StringBuffer buf = new StringBuffer(length); SecureRandom rand = new SecureRandom(); for (int i = 0; i < length; i++) { buf.append(rand.nextInt(digits.length)); } return buf.toString(); } }
public class class_name { public static String generateDigitsString(int length) { StringBuffer buf = new StringBuffer(length); SecureRandom rand = new SecureRandom(); for (int i = 0; i < length; i++) { buf.append(rand.nextInt(digits.length)); // depends on control dependency: [for], data = [none] } return buf.toString(); } }
public class class_name { public void initializeRangesEmpty(int numAtt, double[][] ranges) { for (int j = 0; j < numAtt; j++) { ranges[j][R_MIN] = Double.POSITIVE_INFINITY; ranges[j][R_MAX] = -Double.POSITIVE_INFINITY; ranges[j][R_WIDTH] = Double.POSITIVE_INFINITY; } } }
public class class_name { public void initializeRangesEmpty(int numAtt, double[][] ranges) { for (int j = 0; j < numAtt; j++) { ranges[j][R_MIN] = Double.POSITIVE_INFINITY; // depends on control dependency: [for], data = [j] ranges[j][R_MAX] = -Double.POSITIVE_INFINITY; // depends on control dependency: [for], data = [j] ranges[j][R_WIDTH] = Double.POSITIVE_INFINITY; // depends on control dependency: [for], data = [j] } } }
public class class_name { private static int calculateWidthOfJustifiedSpaceInPixels(final Font font, final String s, final int leftWidth) { int space = 0; // hold total space; hold space width in pixel int curpos = 0; // current string position // count total space while (curpos < s.length()) { if (s.charAt(curpos++) == ' ') { space++; } } if (space > 0) { // width left plus with total space // space width (in pixel) = width left / total space space = (leftWidth + (font.getWidth(" ") * space)) / space; } return space; } }
public class class_name { private static int calculateWidthOfJustifiedSpaceInPixels(final Font font, final String s, final int leftWidth) { int space = 0; // hold total space; hold space width in pixel int curpos = 0; // current string position // count total space while (curpos < s.length()) { if (s.charAt(curpos++) == ' ') { space++; // depends on control dependency: [if], data = [none] } } if (space > 0) { // width left plus with total space // space width (in pixel) = width left / total space space = (leftWidth + (font.getWidth(" ") * space)) / space; // depends on control dependency: [if], data = [none] } return space; } }
public class class_name { public void setRecordDetails(java.util.Collection<RecordDetail> recordDetails) { if (recordDetails == null) { this.recordDetails = null; return; } this.recordDetails = new java.util.ArrayList<RecordDetail>(recordDetails); } }
public class class_name { public void setRecordDetails(java.util.Collection<RecordDetail> recordDetails) { if (recordDetails == null) { this.recordDetails = null; // depends on control dependency: [if], data = [none] return; // depends on control dependency: [if], data = [none] } this.recordDetails = new java.util.ArrayList<RecordDetail>(recordDetails); } }
public class class_name { @Deprecated @Override public int getContentLength () { try { return (int) ( length() & 0xFFFFFFFFL ); } catch ( SmbException se ) { log.debug("getContentLength", se); } return 0; } }
public class class_name { @Deprecated @Override public int getContentLength () { try { return (int) ( length() & 0xFFFFFFFFL ); // depends on control dependency: [try], data = [none] } catch ( SmbException se ) { log.debug("getContentLength", se); } // depends on control dependency: [catch], data = [none] return 0; } }
public class class_name { public static boolean isElementPresent(String locator) { logger.entering(locator); boolean flag = false; try { flag = HtmlElementUtils.locateElement(locator) != null; } catch (NoSuchElementException e) { // NOSONAR } logger.exiting(flag); return flag; } }
public class class_name { public static boolean isElementPresent(String locator) { logger.entering(locator); boolean flag = false; try { flag = HtmlElementUtils.locateElement(locator) != null; // depends on control dependency: [try], data = [none] } catch (NoSuchElementException e) { // NOSONAR } // depends on control dependency: [catch], data = [none] logger.exiting(flag); return flag; } }
public class class_name { @Override public Positions merge(Positions other) { if (other instanceof SinglePosition) { SinglePosition that = (SinglePosition) other; return builder().addSinglePosition(that).build(); } else if (other instanceof LinearPositions) { LinearPositions that = (LinearPositions) other; return AreaPositions.builder().addLinearPosition(this).addLinearPosition(that).build(); } else { return other.merge(this); } } }
public class class_name { @Override public Positions merge(Positions other) { if (other instanceof SinglePosition) { SinglePosition that = (SinglePosition) other; return builder().addSinglePosition(that).build(); // depends on control dependency: [if], data = [none] } else if (other instanceof LinearPositions) { LinearPositions that = (LinearPositions) other; return AreaPositions.builder().addLinearPosition(this).addLinearPosition(that).build(); // depends on control dependency: [if], data = [none] } else { return other.merge(this); // depends on control dependency: [if], data = [none] } } }
public class class_name { public static PebbleDictionary fromJson(String jsonString) throws JSONException { PebbleDictionary d = new PebbleDictionary(); JSONArray elements = new JSONArray(jsonString); for (int idx = 0; idx < elements.length(); ++idx) { JSONObject o = elements.getJSONObject(idx); final int key = o.getInt(KEY); final PebbleTuple.TupleType type = PebbleTuple.TYPE_NAMES.get(o.getString(TYPE)); final PebbleTuple.Width width = PebbleTuple.WIDTH_MAP.get(o.getInt(LENGTH)); switch (type) { case BYTES: byte[] bytes = Base64.decode(o.getString(VALUE), Base64.NO_WRAP); d.addBytes(key, bytes); break; case STRING: d.addString(key, o.getString(VALUE)); break; case INT: if (width == PebbleTuple.Width.BYTE) { d.addInt8(key, (byte) o.getInt(VALUE)); } else if (width == PebbleTuple.Width.SHORT) { d.addInt16(key, (short) o.getInt(VALUE)); } else if (width == PebbleTuple.Width.WORD) { d.addInt32(key, o.getInt(VALUE)); } break; case UINT: if (width == PebbleTuple.Width.BYTE) { d.addUint8(key, (byte) o.getInt(VALUE)); } else if (width == PebbleTuple.Width.SHORT) { d.addUint16(key, (short) o.getInt(VALUE)); } else if (width == PebbleTuple.Width.WORD) { d.addUint32(key, o.getInt(VALUE)); } break; } } return d; } }
public class class_name { public static PebbleDictionary fromJson(String jsonString) throws JSONException { PebbleDictionary d = new PebbleDictionary(); JSONArray elements = new JSONArray(jsonString); for (int idx = 0; idx < elements.length(); ++idx) { JSONObject o = elements.getJSONObject(idx); final int key = o.getInt(KEY); final PebbleTuple.TupleType type = PebbleTuple.TYPE_NAMES.get(o.getString(TYPE)); final PebbleTuple.Width width = PebbleTuple.WIDTH_MAP.get(o.getInt(LENGTH)); switch (type) { case BYTES: byte[] bytes = Base64.decode(o.getString(VALUE), Base64.NO_WRAP); d.addBytes(key, bytes); break; case STRING: d.addString(key, o.getString(VALUE)); break; case INT: if (width == PebbleTuple.Width.BYTE) { d.addInt8(key, (byte) o.getInt(VALUE)); // depends on control dependency: [if], data = [none] } else if (width == PebbleTuple.Width.SHORT) { d.addInt16(key, (short) o.getInt(VALUE)); // depends on control dependency: [if], data = [none] } else if (width == PebbleTuple.Width.WORD) { d.addInt32(key, o.getInt(VALUE)); // depends on control dependency: [if], data = [none] } break; case UINT: if (width == PebbleTuple.Width.BYTE) { d.addUint8(key, (byte) o.getInt(VALUE)); // depends on control dependency: [if], data = [none] } else if (width == PebbleTuple.Width.SHORT) { d.addUint16(key, (short) o.getInt(VALUE)); // depends on control dependency: [if], data = [none] } else if (width == PebbleTuple.Width.WORD) { d.addUint32(key, o.getInt(VALUE)); // depends on control dependency: [if], data = [none] } break; } } return d; } }
public class class_name { public List<SDVariable> getVariablesAssociatedWithFunctions(List<DifferentialFunction> functions) { List<SDVariable> ret = new ArrayList<>(functions.size()); for (DifferentialFunction function : functions) { ret.addAll(Arrays.asList(function.outputVariables())); } return ret; } }
public class class_name { public List<SDVariable> getVariablesAssociatedWithFunctions(List<DifferentialFunction> functions) { List<SDVariable> ret = new ArrayList<>(functions.size()); for (DifferentialFunction function : functions) { ret.addAll(Arrays.asList(function.outputVariables())); // depends on control dependency: [for], data = [function] } return ret; } }
public class class_name { static public Collection<URI> removeRedundantPaths(Collection<URI> uris) { List<URI> result = new ArrayList<URI>(); for (URI uri : uris) { String path = uri.getPath(); if (!path.endsWith("/")) { //$NON-NLS-1$ path += "/"; //$NON-NLS-1$ } boolean addIt = true; for (int i = 0; i < result.size(); i++) { URI testUri = result.get(i); if (!StringUtils.equals(testUri.getScheme(), uri.getScheme()) || !StringUtils.equals(testUri.getHost(), uri.getHost()) || testUri.getPort() != uri.getPort()) { continue; } String test = testUri.getPath(); if (!test.endsWith("/")) { //$NON-NLS-1$ test += "/"; //$NON-NLS-1$ } if (path.equals(test) || path.startsWith(test)) { addIt = false; break; } else if (test.startsWith(path)) { result.remove(i); } } if (addIt) result.add(uri); } // Now copy the trimmed list back to the original return result; } }
public class class_name { static public Collection<URI> removeRedundantPaths(Collection<URI> uris) { List<URI> result = new ArrayList<URI>(); for (URI uri : uris) { String path = uri.getPath(); if (!path.endsWith("/")) { //$NON-NLS-1$ path += "/"; //$NON-NLS-1$ // depends on control dependency: [if], data = [none] } boolean addIt = true; for (int i = 0; i < result.size(); i++) { URI testUri = result.get(i); if (!StringUtils.equals(testUri.getScheme(), uri.getScheme()) || !StringUtils.equals(testUri.getHost(), uri.getHost()) || testUri.getPort() != uri.getPort()) { continue; } String test = testUri.getPath(); if (!test.endsWith("/")) { //$NON-NLS-1$ test += "/"; //$NON-NLS-1$ // depends on control dependency: [if], data = [none] } if (path.equals(test) || path.startsWith(test)) { addIt = false; // depends on control dependency: [if], data = [none] break; } else if (test.startsWith(path)) { result.remove(i); // depends on control dependency: [if], data = [none] } } if (addIt) result.add(uri); } // Now copy the trimmed list back to the original return result; } }
public class class_name { public static void clearBeanProperty(final Object bean, final String name) { Validate.notNull(bean, "Bean required"); Validate.notEmpty(name, "Not empty property name required"); final String methodName = new StringBuilder("set") .append(name.substring(0, 1).toUpperCase()) .append(name.substring(1)).toString(); for (Method method : bean.getClass().getMethods()) { if (method.getName().equals(methodName)) { try { method.invoke(bean, (Object) null); return; } catch (Exception exc) { throw new RuntimeException("Failed to clear property: " + name); } } } throw new RuntimeException("Setter of property not found: " + name); } }
public class class_name { public static void clearBeanProperty(final Object bean, final String name) { Validate.notNull(bean, "Bean required"); Validate.notEmpty(name, "Not empty property name required"); final String methodName = new StringBuilder("set") .append(name.substring(0, 1).toUpperCase()) .append(name.substring(1)).toString(); for (Method method : bean.getClass().getMethods()) { if (method.getName().equals(methodName)) { try { method.invoke(bean, (Object) null); // depends on control dependency: [try], data = [none] return; // depends on control dependency: [try], data = [none] } catch (Exception exc) { throw new RuntimeException("Failed to clear property: " + name); } // depends on control dependency: [catch], data = [none] } } throw new RuntimeException("Setter of property not found: " + name); } }
public class class_name { public static <K,V> AListMap<K,V> fromKeysAndValues(AEquality equality, Iterable<K> keys, Iterable<V> values) { final Iterator<K> ki = keys.iterator(); final Iterator<V> vi = values.iterator(); AListMap<K,V> result = empty (equality); while(ki.hasNext()) { final K key = ki.next(); final V value = vi.next(); result = result.updated(key, value); } return result; } }
public class class_name { public static <K,V> AListMap<K,V> fromKeysAndValues(AEquality equality, Iterable<K> keys, Iterable<V> values) { final Iterator<K> ki = keys.iterator(); final Iterator<V> vi = values.iterator(); AListMap<K,V> result = empty (equality); while(ki.hasNext()) { final K key = ki.next(); final V value = vi.next(); result = result.updated(key, value); // depends on control dependency: [while], data = [none] } return result; } }
public class class_name { protected boolean isSendAllowed(String message, List<?> arguments) { // check internal handlers first for (ISharedObjectSecurity handler : securityHandlers) { if (!handler.isSendAllowed(this, message, arguments)) { return false; } } // check global SO handlers next final Set<ISharedObjectSecurity> handlers = getSecurityHandlers(); if (handlers == null) { return true; } for (ISharedObjectSecurity handler : handlers) { if (!handler.isSendAllowed(this, message, arguments)) { return false; } } return true; } }
public class class_name { protected boolean isSendAllowed(String message, List<?> arguments) { // check internal handlers first for (ISharedObjectSecurity handler : securityHandlers) { if (!handler.isSendAllowed(this, message, arguments)) { return false; // depends on control dependency: [if], data = [none] } } // check global SO handlers next final Set<ISharedObjectSecurity> handlers = getSecurityHandlers(); if (handlers == null) { return true; // depends on control dependency: [if], data = [none] } for (ISharedObjectSecurity handler : handlers) { if (!handler.isSendAllowed(this, message, arguments)) { return false; // depends on control dependency: [if], data = [none] } } return true; } }
public class class_name { public static void clearallLocalDBs() { for (final Map.Entry<MongoClient, Boolean> entry : localInstances.entrySet()) { for (final String dbName : entry.getKey().listDatabaseNames()) { entry.getKey().getDatabase(dbName).drop(); } } } }
public class class_name { public static void clearallLocalDBs() { for (final Map.Entry<MongoClient, Boolean> entry : localInstances.entrySet()) { for (final String dbName : entry.getKey().listDatabaseNames()) { entry.getKey().getDatabase(dbName).drop(); // depends on control dependency: [for], data = [dbName] } } } }
public class class_name { public boolean matches(String httpMethod, String uri) { if (this.httpMethod.equalsIgnoreCase(httpMethod)) { Matcher matcher = regex.matcher(uri); return matcher.matches(); } else { return false; } } }
public class class_name { public boolean matches(String httpMethod, String uri) { if (this.httpMethod.equalsIgnoreCase(httpMethod)) { Matcher matcher = regex.matcher(uri); return matcher.matches(); // depends on control dependency: [if], data = [none] } else { return false; // depends on control dependency: [if], data = [none] } } }
public class class_name { public static Dynamic bootstrap(String name, MethodDescription.InDefinedShape bootstrapMethod, List<?> rawArguments) { if (name.length() == 0 || name.contains(".")) { throw new IllegalArgumentException("Not a valid field name: " + name); } List<Object> arguments = new ArrayList<Object>(rawArguments.size()); for (Object argument : rawArguments) { if (argument == null) { argument = ofNullConstant(); } else if (argument instanceof Class) { argument = ((Class<?>) argument).isPrimitive() ? ofPrimitiveType((Class<?>) argument) : TypeDescription.ForLoadedType.of((Class<?>) argument); } else if (argument instanceof TypeDescription && ((TypeDescription) argument).isPrimitive()) { argument = ofPrimitiveType((TypeDescription) argument); } else if (JavaType.METHOD_HANDLE.isInstance(argument)) { argument = MethodHandle.ofLoaded(argument); } else if (JavaType.METHOD_TYPE.isInstance(argument)) { argument = MethodType.ofLoaded(argument); } arguments.add(argument); } if (!bootstrapMethod.isConstantBootstrap(arguments)) { throw new IllegalArgumentException("Not a valid bootstrap method " + bootstrapMethod + " for " + arguments); } Object[] asmifiedArgument = new Object[arguments.size()]; int index = 0; for (Object argument : arguments) { if (argument instanceof TypeDescription) { argument = Type.getType(((TypeDescription) argument).getDescriptor()); } else if (argument instanceof JavaConstant) { argument = ((JavaConstant) argument).asConstantPoolValue(); } asmifiedArgument[index++] = argument; } return new Dynamic(new ConstantDynamic(name, (bootstrapMethod.isConstructor() ? bootstrapMethod.getDeclaringType() : bootstrapMethod.getReturnType().asErasure()).getDescriptor(), new Handle(bootstrapMethod.isConstructor() ? Opcodes.H_NEWINVOKESPECIAL : Opcodes.H_INVOKESTATIC, bootstrapMethod.getDeclaringType().getInternalName(), bootstrapMethod.getInternalName(), bootstrapMethod.getDescriptor(), false), asmifiedArgument), bootstrapMethod.isConstructor() ? bootstrapMethod.getDeclaringType() : bootstrapMethod.getReturnType().asErasure()); } }
public class class_name { public static Dynamic bootstrap(String name, MethodDescription.InDefinedShape bootstrapMethod, List<?> rawArguments) { if (name.length() == 0 || name.contains(".")) { throw new IllegalArgumentException("Not a valid field name: " + name); } List<Object> arguments = new ArrayList<Object>(rawArguments.size()); for (Object argument : rawArguments) { if (argument == null) { argument = ofNullConstant(); // depends on control dependency: [if], data = [none] } else if (argument instanceof Class) { argument = ((Class<?>) argument).isPrimitive() ? ofPrimitiveType((Class<?>) argument) : TypeDescription.ForLoadedType.of((Class<?>) argument); // depends on control dependency: [if], data = [none] } else if (argument instanceof TypeDescription && ((TypeDescription) argument).isPrimitive()) { argument = ofPrimitiveType((TypeDescription) argument); // depends on control dependency: [if], data = [none] } else if (JavaType.METHOD_HANDLE.isInstance(argument)) { argument = MethodHandle.ofLoaded(argument); // depends on control dependency: [if], data = [none] } else if (JavaType.METHOD_TYPE.isInstance(argument)) { argument = MethodType.ofLoaded(argument); // depends on control dependency: [if], data = [none] } arguments.add(argument); // depends on control dependency: [for], data = [argument] } if (!bootstrapMethod.isConstantBootstrap(arguments)) { throw new IllegalArgumentException("Not a valid bootstrap method " + bootstrapMethod + " for " + arguments); } Object[] asmifiedArgument = new Object[arguments.size()]; int index = 0; for (Object argument : arguments) { if (argument instanceof TypeDescription) { argument = Type.getType(((TypeDescription) argument).getDescriptor()); // depends on control dependency: [if], data = [none] } else if (argument instanceof JavaConstant) { argument = ((JavaConstant) argument).asConstantPoolValue(); // depends on control dependency: [if], data = [none] } asmifiedArgument[index++] = argument; // depends on control dependency: [for], data = [argument] } return new Dynamic(new ConstantDynamic(name, (bootstrapMethod.isConstructor() ? bootstrapMethod.getDeclaringType() : bootstrapMethod.getReturnType().asErasure()).getDescriptor(), new Handle(bootstrapMethod.isConstructor() ? Opcodes.H_NEWINVOKESPECIAL : Opcodes.H_INVOKESTATIC, bootstrapMethod.getDeclaringType().getInternalName(), bootstrapMethod.getInternalName(), bootstrapMethod.getDescriptor(), false), asmifiedArgument), bootstrapMethod.isConstructor() ? bootstrapMethod.getDeclaringType() : bootstrapMethod.getReturnType().asErasure()); } }
public class class_name { public void marshall(QueryInfo queryInfo, ProtocolMarshaller protocolMarshaller) { if (queryInfo == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(queryInfo.getSelectFields(), SELECTFIELDS_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
public class class_name { public void marshall(QueryInfo queryInfo, ProtocolMarshaller protocolMarshaller) { if (queryInfo == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(queryInfo.getSelectFields(), SELECTFIELDS_BINDING); // depends on control dependency: [try], data = [none] } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } // depends on control dependency: [catch], data = [none] } }
public class class_name { public void marshall(DeletePolicyRequest deletePolicyRequest, ProtocolMarshaller protocolMarshaller) { if (deletePolicyRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(deletePolicyRequest.getPolicyId(), POLICYID_BINDING); protocolMarshaller.marshall(deletePolicyRequest.getDeleteAllPolicyResources(), DELETEALLPOLICYRESOURCES_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
public class class_name { public void marshall(DeletePolicyRequest deletePolicyRequest, ProtocolMarshaller protocolMarshaller) { if (deletePolicyRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(deletePolicyRequest.getPolicyId(), POLICYID_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(deletePolicyRequest.getDeleteAllPolicyResources(), DELETEALLPOLICYRESOURCES_BINDING); // depends on control dependency: [try], data = [none] } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } // depends on control dependency: [catch], data = [none] } }
public class class_name { public Coin fiatToCoin(Fiat convertFiat) { checkArgument(convertFiat.currencyCode.equals(fiat.currencyCode), "Currency mismatch: %s vs %s", convertFiat.currencyCode, fiat.currencyCode); // Use BigInteger because it's much easier to maintain full precision without overflowing. final BigInteger converted = BigInteger.valueOf(convertFiat.value).multiply(BigInteger.valueOf(coin.value)) .divide(BigInteger.valueOf(fiat.value)); if (converted.compareTo(BigInteger.valueOf(Long.MAX_VALUE)) > 0 || converted.compareTo(BigInteger.valueOf(Long.MIN_VALUE)) < 0) throw new ArithmeticException("Overflow"); try { return Coin.valueOf(converted.longValue()); } catch (IllegalArgumentException x) { throw new ArithmeticException("Overflow: " + x.getMessage()); } } }
public class class_name { public Coin fiatToCoin(Fiat convertFiat) { checkArgument(convertFiat.currencyCode.equals(fiat.currencyCode), "Currency mismatch: %s vs %s", convertFiat.currencyCode, fiat.currencyCode); // Use BigInteger because it's much easier to maintain full precision without overflowing. final BigInteger converted = BigInteger.valueOf(convertFiat.value).multiply(BigInteger.valueOf(coin.value)) .divide(BigInteger.valueOf(fiat.value)); if (converted.compareTo(BigInteger.valueOf(Long.MAX_VALUE)) > 0 || converted.compareTo(BigInteger.valueOf(Long.MIN_VALUE)) < 0) throw new ArithmeticException("Overflow"); try { return Coin.valueOf(converted.longValue()); // depends on control dependency: [try], data = [none] } catch (IllegalArgumentException x) { throw new ArithmeticException("Overflow: " + x.getMessage()); } // depends on control dependency: [catch], data = [none] } }
public class class_name { public Object put(Object key, Object value) { if (key == null) { throw new NullPointerException("Null key is not permitted"); } // Makes sure the key is not already in the HashMap. Entry tab[] = mTable; int hash = System.identityHashCode(key); int index = (hash & 0x7FFFFFFF) % tab.length; for (Entry e = tab[index], prev = null; e != null; e = e.mNext) { Object entryKey = e.getKey(); if (entryKey == null) { // Clean up after a cleared Reference. mModCount++; if (prev != null) { prev.mNext = e.mNext; } else { tab[index] = e.mNext; } mCount--; } else if (e.mHash == hash && key == entryKey) { Object old = e.mValue; e.mValue = value; return old; } else { prev = e; } } mModCount++; if (mCount >= mThreshold) { // Cleanup the table if the threshold is exceeded. cleanup(); } if (mCount >= mThreshold) { // Rehash the table if the threshold is still exceeded. rehash(); tab = mTable; index = (hash & 0x7FFFFFFF) % tab.length; } // Creates the new entry. Entry e = new Entry(hash, key, value, tab[index]); tab[index] = e; mCount++; return null; } }
public class class_name { public Object put(Object key, Object value) { if (key == null) { throw new NullPointerException("Null key is not permitted"); } // Makes sure the key is not already in the HashMap. Entry tab[] = mTable; int hash = System.identityHashCode(key); int index = (hash & 0x7FFFFFFF) % tab.length; for (Entry e = tab[index], prev = null; e != null; e = e.mNext) { Object entryKey = e.getKey(); if (entryKey == null) { // Clean up after a cleared Reference. mModCount++; // depends on control dependency: [if], data = [none] if (prev != null) { prev.mNext = e.mNext; // depends on control dependency: [if], data = [none] } else { tab[index] = e.mNext; // depends on control dependency: [if], data = [none] } mCount--; // depends on control dependency: [if], data = [none] } else if (e.mHash == hash && key == entryKey) { Object old = e.mValue; e.mValue = value; // depends on control dependency: [if], data = [none] return old; // depends on control dependency: [if], data = [none] } else { prev = e; // depends on control dependency: [if], data = [none] } } mModCount++; if (mCount >= mThreshold) { // Cleanup the table if the threshold is exceeded. cleanup(); // depends on control dependency: [if], data = [none] } if (mCount >= mThreshold) { // Rehash the table if the threshold is still exceeded. rehash(); // depends on control dependency: [if], data = [none] tab = mTable; // depends on control dependency: [if], data = [none] index = (hash & 0x7FFFFFFF) % tab.length; // depends on control dependency: [if], data = [none] } // Creates the new entry. Entry e = new Entry(hash, key, value, tab[index]); tab[index] = e; mCount++; return null; } }
public class class_name { private void removeRange(int fromIndex, int toIndex) { final ReentrantLock lock = this.lock; lock.lock(); try { Object[] elements = getArray(); int len = elements.length; if (fromIndex < 0 || toIndex > len || toIndex < fromIndex) throw new IndexOutOfBoundsException(); int newlen = len - (toIndex - fromIndex); int numMoved = len - toIndex; if (numMoved == 0) setArray(Arrays.copyOf(elements, newlen)); else { Object[] newElements = new Object[newlen]; System.arraycopy(elements, 0, newElements, 0, fromIndex); System.arraycopy(elements, toIndex, newElements, fromIndex, numMoved); setArray(newElements); } } finally { lock.unlock(); } } }
public class class_name { private void removeRange(int fromIndex, int toIndex) { final ReentrantLock lock = this.lock; lock.lock(); try { Object[] elements = getArray(); int len = elements.length; if (fromIndex < 0 || toIndex > len || toIndex < fromIndex) throw new IndexOutOfBoundsException(); int newlen = len - (toIndex - fromIndex); int numMoved = len - toIndex; if (numMoved == 0) setArray(Arrays.copyOf(elements, newlen)); else { Object[] newElements = new Object[newlen]; System.arraycopy(elements, 0, newElements, 0, fromIndex); // depends on control dependency: [if], data = [none] System.arraycopy(elements, toIndex, newElements, fromIndex, numMoved); // depends on control dependency: [if], data = [none] setArray(newElements); // depends on control dependency: [if], data = [none] } } finally { lock.unlock(); } } }
public class class_name { public LdapUser getUserTemplate(String uid) { LdapUser user = new LdapUser(uid, this); user.set("dn", getDNForNode(user)); for (String oc : userObjectClasses) { user.addObjectClass(oc.trim()); } user = (LdapUser) updateObjectClasses(user); // TODO this needs to be cleaner :-/. // for inetOrgPerson if (user.getObjectClasses().contains("inetOrgPerson") || user.getObjectClasses().contains("person")) { user.set("sn", uid); } // for JabberAccount if (user.getObjectClasses().contains("JabberAccount")) { user.set("jabberID", uid + "@" + defaultValues.get("jabberServer")); user.set("jabberAccess", "TRUE"); } // for posixAccount if (user.getObjectClasses().contains("posixAccount")) { user.set("uidNumber", "99999"); user.set("gidNumber", "99999"); user.set("cn", uid); user.set("homeDirectory", "/dev/null"); } // for ldapPublicKey if (user.getObjectClasses().contains("ldapPublicKey")) { user.set("sshPublicKey", defaultValues.get("sshKey")); } return user; } }
public class class_name { public LdapUser getUserTemplate(String uid) { LdapUser user = new LdapUser(uid, this); user.set("dn", getDNForNode(user)); for (String oc : userObjectClasses) { user.addObjectClass(oc.trim()); // depends on control dependency: [for], data = [oc] } user = (LdapUser) updateObjectClasses(user); // TODO this needs to be cleaner :-/. // for inetOrgPerson if (user.getObjectClasses().contains("inetOrgPerson") || user.getObjectClasses().contains("person")) { user.set("sn", uid); // depends on control dependency: [if], data = [none] } // for JabberAccount if (user.getObjectClasses().contains("JabberAccount")) { user.set("jabberID", uid + "@" + defaultValues.get("jabberServer")); // depends on control dependency: [if], data = [none] user.set("jabberAccess", "TRUE"); // depends on control dependency: [if], data = [none] } // for posixAccount if (user.getObjectClasses().contains("posixAccount")) { user.set("uidNumber", "99999"); // depends on control dependency: [if], data = [none] user.set("gidNumber", "99999"); // depends on control dependency: [if], data = [none] user.set("cn", uid); // depends on control dependency: [if], data = [none] user.set("homeDirectory", "/dev/null"); // depends on control dependency: [if], data = [none] } // for ldapPublicKey if (user.getObjectClasses().contains("ldapPublicKey")) { user.set("sshPublicKey", defaultValues.get("sshKey")); // depends on control dependency: [if], data = [none] } return user; } }
public class class_name { public void marshall(ElasticsearchVersionStatus elasticsearchVersionStatus, ProtocolMarshaller protocolMarshaller) { if (elasticsearchVersionStatus == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(elasticsearchVersionStatus.getOptions(), OPTIONS_BINDING); protocolMarshaller.marshall(elasticsearchVersionStatus.getStatus(), STATUS_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
public class class_name { public void marshall(ElasticsearchVersionStatus elasticsearchVersionStatus, ProtocolMarshaller protocolMarshaller) { if (elasticsearchVersionStatus == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(elasticsearchVersionStatus.getOptions(), OPTIONS_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(elasticsearchVersionStatus.getStatus(), STATUS_BINDING); // depends on control dependency: [try], data = [none] } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } // depends on control dependency: [catch], data = [none] } }
public class class_name { @Override public void engineUndeployed() { try { if (jmxAgent != null) { jmxAgent.unregister(new ObjectName(JMXAgent.JMX_DOMAIN+":type=Engines,engine="+engine.getName()+",children=async-managers,name=notification")); jmxAgent.unregister(new ObjectName(JMXAgent.JMX_DOMAIN+":type=Engines,engine="+engine.getName()+",children=async-managers,name=delivery")); jmxAgent.unregister(new ObjectName(JMXAgent.JMX_DOMAIN+":type=Engines,engine="+engine.getName()+",children=async-managers,name=disk-io")); } } catch (Exception e) { log.error("Cannot unregister local engine async managers from JMX agent",e); } } }
public class class_name { @Override public void engineUndeployed() { try { if (jmxAgent != null) { jmxAgent.unregister(new ObjectName(JMXAgent.JMX_DOMAIN+":type=Engines,engine="+engine.getName()+",children=async-managers,name=notification")); // depends on control dependency: [if], data = [none] jmxAgent.unregister(new ObjectName(JMXAgent.JMX_DOMAIN+":type=Engines,engine="+engine.getName()+",children=async-managers,name=delivery")); // depends on control dependency: [if], data = [none] jmxAgent.unregister(new ObjectName(JMXAgent.JMX_DOMAIN+":type=Engines,engine="+engine.getName()+",children=async-managers,name=disk-io")); // depends on control dependency: [if], data = [none] } } catch (Exception e) { log.error("Cannot unregister local engine async managers from JMX agent",e); } // depends on control dependency: [catch], data = [none] } }
public class class_name { private void cleanGlobalBlockList() { for (Iterator<Block> globalBlockListIterator=globalBlockList.keySet().iterator(); globalBlockListIterator.hasNext();) { Block block = globalBlockListIterator.next(); if(!movedBlocks.contains(block)) { globalBlockListIterator.remove(); } } } }
public class class_name { private void cleanGlobalBlockList() { for (Iterator<Block> globalBlockListIterator=globalBlockList.keySet().iterator(); globalBlockListIterator.hasNext();) { Block block = globalBlockListIterator.next(); if(!movedBlocks.contains(block)) { globalBlockListIterator.remove(); // depends on control dependency: [if], data = [none] } } } }
public class class_name { int getValue() { if (this.matches(Selector.NORTHERN_COURT)) { return (this.index - NORTHERN_NENGOS.length + NENGO_OEI.index - Nengo.SHOWA.index + 1); } return (this.index - Nengo.SHOWA.index + 1); } }
public class class_name { int getValue() { if (this.matches(Selector.NORTHERN_COURT)) { return (this.index - NORTHERN_NENGOS.length + NENGO_OEI.index - Nengo.SHOWA.index + 1); // depends on control dependency: [if], data = [none] } return (this.index - Nengo.SHOWA.index + 1); } }
public class class_name { @Override public Attachment updateAttachment(String assetId, AttachmentSummary summary) throws IOException, BadVersionException, RequestFailureException { // First find the attachment to update Asset ass = getAsset(assetId); List<Attachment> attachments = ass.getAttachments(); if (attachments != null) { for (Attachment attachment : attachments) { if (attachment.getName().equals(summary.getName())) { this.deleteAttachment(assetId, attachment.get_id()); break; } } } return this.addAttachment(assetId, summary); } }
public class class_name { @Override public Attachment updateAttachment(String assetId, AttachmentSummary summary) throws IOException, BadVersionException, RequestFailureException { // First find the attachment to update Asset ass = getAsset(assetId); List<Attachment> attachments = ass.getAttachments(); if (attachments != null) { for (Attachment attachment : attachments) { if (attachment.getName().equals(summary.getName())) { this.deleteAttachment(assetId, attachment.get_id()); // depends on control dependency: [if], data = [none] break; } } } return this.addAttachment(assetId, summary); } }
public class class_name { public java.util.List<String> getGrantTokens() { if (grantTokens == null) { grantTokens = new com.amazonaws.internal.SdkInternalList<String>(); } return grantTokens; } }
public class class_name { public java.util.List<String> getGrantTokens() { if (grantTokens == null) { grantTokens = new com.amazonaws.internal.SdkInternalList<String>(); // depends on control dependency: [if], data = [none] } return grantTokens; } }
public class class_name { public static TranslatecontentResult translatecontent(String accessToken, String lfrom, String lto, File content, String charsetName) { HttpPost httpPost = new HttpPost(BASE_URI + "/cgi-bin/media/voice/translatecontent"); byte[] data; try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(content), charsetName))) { String line; StringBuilder sb = new StringBuilder(); while ((line = reader.readLine()) != null) { sb.append(line); } data = sb.toString().getBytes("UTF-8"); } catch (IOException e) { e.printStackTrace(); throw new RuntimeException(e); } HttpEntity reqEntity = MultipartEntityBuilder.create() .addBinaryBody("media", data, ContentType.DEFAULT_BINARY, "temp.txt") .addTextBody(PARAM_ACCESS_TOKEN, API.accessToken(accessToken)) .addTextBody("lfrom", lfrom) .addTextBody("lto", lto) .build(); httpPost.setEntity(reqEntity); return LocalHttpClient.executeJsonResult(httpPost, TranslatecontentResult.class); } }
public class class_name { public static TranslatecontentResult translatecontent(String accessToken, String lfrom, String lto, File content, String charsetName) { HttpPost httpPost = new HttpPost(BASE_URI + "/cgi-bin/media/voice/translatecontent"); byte[] data; try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(content), charsetName))) { String line; StringBuilder sb = new StringBuilder(); while ((line = reader.readLine()) != null) { sb.append(line); // depends on control dependency: [while], data = [none] } data = sb.toString().getBytes("UTF-8"); } catch (IOException e) { e.printStackTrace(); throw new RuntimeException(e); } HttpEntity reqEntity = MultipartEntityBuilder.create() .addBinaryBody("media", data, ContentType.DEFAULT_BINARY, "temp.txt") .addTextBody(PARAM_ACCESS_TOKEN, API.accessToken(accessToken)) .addTextBody("lfrom", lfrom) .addTextBody("lto", lto) .build(); httpPost.setEntity(reqEntity); return LocalHttpClient.executeJsonResult(httpPost, TranslatecontentResult.class); } }
public class class_name { private String refactorString(String original) { StringBuilder sb = new StringBuilder(); int argCount = 0; for (int i = 0; i < original.length(); i++) { if (original.charAt(i) == '{' && i < original.length() - 1 && original.charAt(i + 1) == '}') { sb.append(String.format("{%d}", argCount)); argCount++; i++; } else { sb.append(original.charAt(i)); } } return sb.toString(); } }
public class class_name { private String refactorString(String original) { StringBuilder sb = new StringBuilder(); int argCount = 0; for (int i = 0; i < original.length(); i++) { if (original.charAt(i) == '{' && i < original.length() - 1 && original.charAt(i + 1) == '}') { sb.append(String.format("{%d}", argCount)); // depends on control dependency: [if], data = [none] argCount++; // depends on control dependency: [if], data = [none] i++; // depends on control dependency: [if], data = [none] } else { sb.append(original.charAt(i)); // depends on control dependency: [if], data = [(original.charAt(i)] } } return sb.toString(); } }
public class class_name { @SuppressWarnings("unused") public void destroy() { if (cacheProducers != null) { for (Entry<ProducerType, KafkaProducer<String, byte[]>> entry : cacheProducers .entrySet()) { try { KafkaProducer<String, byte[]> producer = entry.getValue(); producer.close(); } catch (Exception e) { LOGGER.warn(e.getMessage(), e); } } cacheProducers.clear(); cacheProducers = null; } try { if (metadataConsumer != null) { metadataConsumer.close(); } } catch (Exception e) { LOGGER.warn(e.getMessage(), e); } finally { metadataConsumer = null; } if (cacheConsumers != null) { for (Entry<String, KafkaMsgConsumer> entry : cacheConsumers.entrySet()) { try { KafkaMsgConsumer consumer = entry.getValue(); consumer.destroy(); } catch (Exception e) { LOGGER.warn(e.getMessage(), e); } } cacheConsumers.clear(); cacheConsumers = null; } // // to fix the error // // // "thread Thread[metrics-meter-tick-thread-1...] was interrupted but is // still alive..." // // since Kafka does not shutdown Metrics registry on close. // Metrics.defaultRegistry().shutdown(); if (executorService != null && myOwnExecutorService) { try { List<Runnable> tasks = executorService.shutdownNow(); } catch (Exception e) { LOGGER.warn(e.getMessage(), e); } finally { executorService = null; } } } }
public class class_name { @SuppressWarnings("unused") public void destroy() { if (cacheProducers != null) { for (Entry<ProducerType, KafkaProducer<String, byte[]>> entry : cacheProducers .entrySet()) { try { KafkaProducer<String, byte[]> producer = entry.getValue(); producer.close(); // depends on control dependency: [try], data = [none] } catch (Exception e) { LOGGER.warn(e.getMessage(), e); } // depends on control dependency: [catch], data = [none] } cacheProducers.clear(); // depends on control dependency: [if], data = [none] cacheProducers = null; // depends on control dependency: [if], data = [none] } try { if (metadataConsumer != null) { metadataConsumer.close(); // depends on control dependency: [if], data = [none] } } catch (Exception e) { LOGGER.warn(e.getMessage(), e); } finally { // depends on control dependency: [catch], data = [none] metadataConsumer = null; } if (cacheConsumers != null) { for (Entry<String, KafkaMsgConsumer> entry : cacheConsumers.entrySet()) { try { KafkaMsgConsumer consumer = entry.getValue(); consumer.destroy(); // depends on control dependency: [try], data = [none] } catch (Exception e) { LOGGER.warn(e.getMessage(), e); } // depends on control dependency: [catch], data = [none] } cacheConsumers.clear(); // depends on control dependency: [if], data = [none] cacheConsumers = null; // depends on control dependency: [if], data = [none] } // // to fix the error // // // "thread Thread[metrics-meter-tick-thread-1...] was interrupted but is // still alive..." // // since Kafka does not shutdown Metrics registry on close. // Metrics.defaultRegistry().shutdown(); if (executorService != null && myOwnExecutorService) { try { List<Runnable> tasks = executorService.shutdownNow(); } catch (Exception e) { LOGGER.warn(e.getMessage(), e); } finally { // depends on control dependency: [catch], data = [none] executorService = null; } } } }
public class class_name { public void marshall(FailedRemediationBatch failedRemediationBatch, ProtocolMarshaller protocolMarshaller) { if (failedRemediationBatch == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(failedRemediationBatch.getFailureMessage(), FAILUREMESSAGE_BINDING); protocolMarshaller.marshall(failedRemediationBatch.getFailedItems(), FAILEDITEMS_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
public class class_name { public void marshall(FailedRemediationBatch failedRemediationBatch, ProtocolMarshaller protocolMarshaller) { if (failedRemediationBatch == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(failedRemediationBatch.getFailureMessage(), FAILUREMESSAGE_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(failedRemediationBatch.getFailedItems(), FAILEDITEMS_BINDING); // depends on control dependency: [try], data = [none] } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } // depends on control dependency: [catch], data = [none] } }
public class class_name { public synchronized long getDataPointLimit(final String metric) { if (metric == null || metric.isEmpty()) { return default_data_points_limit; } for (final QueryLimitOverrideItem item : overrides.values()) { if (item.matches(metric)) { return item.getDataPointsLimit(); } } return default_data_points_limit; } }
public class class_name { public synchronized long getDataPointLimit(final String metric) { if (metric == null || metric.isEmpty()) { return default_data_points_limit; // depends on control dependency: [if], data = [none] } for (final QueryLimitOverrideItem item : overrides.values()) { if (item.matches(metric)) { return item.getDataPointsLimit(); // depends on control dependency: [if], data = [none] } } return default_data_points_limit; } }
public class class_name { public static RoaringBitmap naive_and(RoaringBitmap... bitmaps) { if (bitmaps.length == 0) { return new RoaringBitmap(); } RoaringBitmap answer = bitmaps[0].clone(); for (int k = 1; k < bitmaps.length; ++k) { answer.and(bitmaps[k]); } return answer; } }
public class class_name { public static RoaringBitmap naive_and(RoaringBitmap... bitmaps) { if (bitmaps.length == 0) { return new RoaringBitmap(); // depends on control dependency: [if], data = [none] } RoaringBitmap answer = bitmaps[0].clone(); for (int k = 1; k < bitmaps.length; ++k) { answer.and(bitmaps[k]); // depends on control dependency: [for], data = [k] } return answer; } }
public class class_name { Object insertByRightShift( int ix, Object new1) { Object old1 = null; if (isFull()) { old1 = rightMostKey(); rightMove(ix+1); _nodeKey[ix+1] = new1; } else { rightShift(ix+1); _nodeKey[ix+1] = new1; _population++; if (midPoint() > rightMostIndex()) _nodeKey[midPoint()] = rightMostKey(); } return old1; } }
public class class_name { Object insertByRightShift( int ix, Object new1) { Object old1 = null; if (isFull()) { old1 = rightMostKey(); // depends on control dependency: [if], data = [none] rightMove(ix+1); // depends on control dependency: [if], data = [none] _nodeKey[ix+1] = new1; // depends on control dependency: [if], data = [none] } else { rightShift(ix+1); // depends on control dependency: [if], data = [none] _nodeKey[ix+1] = new1; // depends on control dependency: [if], data = [none] _population++; // depends on control dependency: [if], data = [none] if (midPoint() > rightMostIndex()) _nodeKey[midPoint()] = rightMostKey(); } return old1; } }
public class class_name { public static RouteInfo of(ActionContext context) { H.Method m = context.req().method(); String path = context.req().url(); RequestHandler handler = context.handler(); if (null == handler) { handler = UNKNOWN_HANDLER; } return new RouteInfo(m, path, handler); } }
public class class_name { public static RouteInfo of(ActionContext context) { H.Method m = context.req().method(); String path = context.req().url(); RequestHandler handler = context.handler(); if (null == handler) { handler = UNKNOWN_HANDLER; // depends on control dependency: [if], data = [none] } return new RouteInfo(m, path, handler); } }
public class class_name { public void traverseHierarchy() { String pdbId = "4HHB"; // download SCOP if required and load into memory ScopDatabase scop = ScopFactory.getSCOP(); List<ScopDomain> domains = scop.getDomainsForPDB(pdbId); // show the hierachy for the first domain: ScopNode node = scop.getScopNode(domains.get(0).getSunid()); while (node != null){ System.out.println("This node: sunid:" + node.getSunid() ); System.out.println(scop.getScopDescriptionBySunid(node.getSunid())); node = scop.getScopNode(node.getParentSunid()); } } }
public class class_name { public void traverseHierarchy() { String pdbId = "4HHB"; // download SCOP if required and load into memory ScopDatabase scop = ScopFactory.getSCOP(); List<ScopDomain> domains = scop.getDomainsForPDB(pdbId); // show the hierachy for the first domain: ScopNode node = scop.getScopNode(domains.get(0).getSunid()); while (node != null){ System.out.println("This node: sunid:" + node.getSunid() ); // depends on control dependency: [while], data = [none] System.out.println(scop.getScopDescriptionBySunid(node.getSunid())); // depends on control dependency: [while], data = [(node] node = scop.getScopNode(node.getParentSunid()); // depends on control dependency: [while], data = [(node] } } }
public class class_name { public static void removeScopedSessionAttr( String attrName, HttpServletRequest request ) { HttpSession session = request.getSession( false ); if ( session != null ) { session.removeAttribute( getScopedSessionAttrName( attrName, request ) ); } } }
public class class_name { public static void removeScopedSessionAttr( String attrName, HttpServletRequest request ) { HttpSession session = request.getSession( false ); if ( session != null ) { session.removeAttribute( getScopedSessionAttrName( attrName, request ) ); // depends on control dependency: [if], data = [none] } } }
public class class_name { @FFDCIgnore({ SSLPeerUnverifiedException.class, Exception.class }) private Subject tryToAuthenticate(SSLSession session) throws SASException { Subject transportSubject = null; try { transportSubject = authenticateWithCertificateChain(session); } catch (SSLPeerUnverifiedException e) { throwExceptionIfClientCertificateAuthenticationIsRequired(e); if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "The peer could not be verified, but ignoring because client certificate authentication is not required. The exception is: " + e.getMessage()); } } catch (Exception e) { /* * All the possible exceptions, including AuthenticationException, CredentialExpiredException * and CredentialDestroyedException are caught here, and re-thrown */ throwExceptionIfClientCertificateAuthenticationIsRequired(e); } return transportSubject; } }
public class class_name { @FFDCIgnore({ SSLPeerUnverifiedException.class, Exception.class }) private Subject tryToAuthenticate(SSLSession session) throws SASException { Subject transportSubject = null; try { transportSubject = authenticateWithCertificateChain(session); } catch (SSLPeerUnverifiedException e) { throwExceptionIfClientCertificateAuthenticationIsRequired(e); if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "The peer could not be verified, but ignoring because client certificate authentication is not required. The exception is: " + e.getMessage()); // depends on control dependency: [if], data = [none] } } catch (Exception e) { /* * All the possible exceptions, including AuthenticationException, CredentialExpiredException * and CredentialDestroyedException are caught here, and re-thrown */ throwExceptionIfClientCertificateAuthenticationIsRequired(e); } return transportSubject; } }
public class class_name { public static int levenshteinDistance(CharSequence one, CharSequence another, int threshold) { int n = one.length(); int m = another.length(); // if one string is empty, the edit distance is necessarily the length of the other if (n == 0) { return m <= threshold ? m : -1; } else if (m == 0) { return n <= threshold ? n : -1; } if (n > m) { // swap the two strings to consume less memory final CharSequence tmp = one; one = another; another = tmp; n = m; m = another.length(); } int p[] = new int[n + 1]; // 'previous' cost array, horizontally int d[] = new int[n + 1]; // cost array, horizontally int _d[]; // placeholder to assist in swapping p and d // fill in starting table values final int boundary = Math.min(n, threshold) + 1; for (int i = 0; i < boundary; i++) { p[i] = i; } // these fills ensure that the value above the rightmost entry of our // stripe will be ignored in following loop iterations Arrays.fill(p, boundary, p.length, Integer.MAX_VALUE); Arrays.fill(d, Integer.MAX_VALUE); for (int j = 1; j <= m; j++) { final char t_j = another.charAt(j - 1); d[0] = j; // compute stripe indices, constrain to array size final int min = Math.max(1, j - threshold); final int max = (j > Integer.MAX_VALUE - threshold) ? n : Math.min(n, j + threshold); // the stripe may lead off of the table if s and t are of different sizes if (min > max) { return -1; } // ignore entry left of leftmost if (min > 1) { d[min - 1] = Integer.MAX_VALUE; } // iterates through [min, max] in s for (int i = min; i <= max; i++) { if (one.charAt(i - 1) == t_j) { // diagonally left and up d[i] = p[i - 1]; } else { // 1 + minimum of cell to the left, to the top, diagonally left and up d[i] = 1 + Math.min(Math.min(d[i - 1], p[i]), p[i - 1]); } } // copy current distance counts to 'previous row' distance counts _d = p; p = d; d = _d; } // if p[n] is greater than the threshold, there's no guarantee on it being the correct // distance if (p[n] <= threshold) { return p[n]; } return -1; } }
public class class_name { public static int levenshteinDistance(CharSequence one, CharSequence another, int threshold) { int n = one.length(); int m = another.length(); // if one string is empty, the edit distance is necessarily the length of the other if (n == 0) { return m <= threshold ? m : -1; // depends on control dependency: [if], data = [none] } else if (m == 0) { return n <= threshold ? n : -1; // depends on control dependency: [if], data = [none] } if (n > m) { // swap the two strings to consume less memory final CharSequence tmp = one; one = another; // depends on control dependency: [if], data = [none] another = tmp; // depends on control dependency: [if], data = [none] n = m; // depends on control dependency: [if], data = [none] m = another.length(); // depends on control dependency: [if], data = [none] } int p[] = new int[n + 1]; // 'previous' cost array, horizontally int d[] = new int[n + 1]; // cost array, horizontally int _d[]; // placeholder to assist in swapping p and d // fill in starting table values final int boundary = Math.min(n, threshold) + 1; for (int i = 0; i < boundary; i++) { p[i] = i; // depends on control dependency: [for], data = [i] } // these fills ensure that the value above the rightmost entry of our // stripe will be ignored in following loop iterations Arrays.fill(p, boundary, p.length, Integer.MAX_VALUE); Arrays.fill(d, Integer.MAX_VALUE); for (int j = 1; j <= m; j++) { final char t_j = another.charAt(j - 1); d[0] = j; // depends on control dependency: [for], data = [j] // compute stripe indices, constrain to array size final int min = Math.max(1, j - threshold); final int max = (j > Integer.MAX_VALUE - threshold) ? n : Math.min(n, j + threshold); // the stripe may lead off of the table if s and t are of different sizes if (min > max) { return -1; // depends on control dependency: [if], data = [none] } // ignore entry left of leftmost if (min > 1) { d[min - 1] = Integer.MAX_VALUE; // depends on control dependency: [if], data = [none] } // iterates through [min, max] in s for (int i = min; i <= max; i++) { if (one.charAt(i - 1) == t_j) { // diagonally left and up d[i] = p[i - 1]; // depends on control dependency: [if], data = [none] } else { // 1 + minimum of cell to the left, to the top, diagonally left and up d[i] = 1 + Math.min(Math.min(d[i - 1], p[i]), p[i - 1]); // depends on control dependency: [if], data = [none] } } // copy current distance counts to 'previous row' distance counts _d = p; // depends on control dependency: [for], data = [none] p = d; // depends on control dependency: [for], data = [none] d = _d; // depends on control dependency: [for], data = [none] } // if p[n] is greater than the threshold, there's no guarantee on it being the correct // distance if (p[n] <= threshold) { return p[n]; // depends on control dependency: [if], data = [none] } return -1; } }
public class class_name { private String checkProperty(String propName) throws AttributeNotSupportedException { final String METHODNAME = "checkProperty"; boolean inRepos = false; boolean inLA = false; if (propName.equals(xsiType)) { /* * if (trcLogger.isLoggable(Level.FINER)) { * trcLogger.exiting(CLASSNAME, METHODNAME, " " + propName * + " is defined in Repository " + repos); * } */ return repos; } inRepos = false; for (int i = 0; i < entityTypes.size() && !inRepos; i++) { inRepos = _metaDataMapper.isPropertyInRepository(propName, entityTypes.get(i)); } if (!inRepos) { for (int i = 0; i < entityTypes.size(); i++) { inLA = _metaDataMapper.isPropertyInLookAside(propName, entityTypes.get(i)); } } else { /* * if (trcLogger.isLoggable(Level.FINER)) { * trcLogger.exiting(CLASSNAME, METHODNAME, "Property " + propName * + " is defined in Repository " + repos); * } */ return repos; } if (!inRepos && !inLA) { throw new AttributeNotSupportedException(WIMMessageKey.ATTRIBUTE_NOT_SUPPORTED, WIMMessageKey.ATTRIBUTE_NOT_SUPPORTED); } /* * if (trcLogger.isLoggable(Level.FINER)) { * trcLogger.exiting(CLASSNAME, METHODNAME, "Property " + propName * + " is defined in Repository " + la); * } */ return la; } }
public class class_name { private String checkProperty(String propName) throws AttributeNotSupportedException { final String METHODNAME = "checkProperty"; boolean inRepos = false; boolean inLA = false; if (propName.equals(xsiType)) { /* * if (trcLogger.isLoggable(Level.FINER)) { * trcLogger.exiting(CLASSNAME, METHODNAME, " " + propName * + " is defined in Repository " + repos); * } */ return repos; } inRepos = false; for (int i = 0; i < entityTypes.size() && !inRepos; i++) { inRepos = _metaDataMapper.isPropertyInRepository(propName, entityTypes.get(i)); } if (!inRepos) { for (int i = 0; i < entityTypes.size(); i++) { inLA = _metaDataMapper.isPropertyInLookAside(propName, entityTypes.get(i)); // depends on control dependency: [for], data = [none] } } else { /* * if (trcLogger.isLoggable(Level.FINER)) { * trcLogger.exiting(CLASSNAME, METHODNAME, "Property " + propName * + " is defined in Repository " + repos); * } */ return repos; } if (!inRepos && !inLA) { throw new AttributeNotSupportedException(WIMMessageKey.ATTRIBUTE_NOT_SUPPORTED, WIMMessageKey.ATTRIBUTE_NOT_SUPPORTED); } /* * if (trcLogger.isLoggable(Level.FINER)) { * trcLogger.exiting(CLASSNAME, METHODNAME, "Property " + propName * + " is defined in Repository " + la); * } */ return la; } }
public class class_name { private void preInsert(MkMaxEntry q, MkMaxEntry nodeEntry, KNNHeap knns_q) { if (LOG.isDebugging()) { LOG.debugFine("preInsert " + q + " - " + nodeEntry + "\n"); } double knnDist_q = knns_q.getKNNDistance(); MkMaxTreeNode<O> node = getNode(nodeEntry); double knnDist_node = 0.; // leaf node if (node.isLeaf()) { for (int i = 0; i < node.getNumEntries(); i++) { MkMaxEntry p = node.getEntry(i); double dist_pq = distance(p.getRoutingObjectID(), q.getRoutingObjectID()); // p is nearer to q than the farthest kNN-candidate of q // ==> p becomes a knn-candidate if (dist_pq <= knnDist_q) { knns_q.insert(dist_pq, p.getRoutingObjectID()); if (knns_q.size() >= getKmax()) { knnDist_q = knns_q.getKNNDistance(); q.setKnnDistance(knnDist_q); } } // p is nearer to q than to its farthest knn-candidate // q becomes knn of p if (dist_pq <= p.getKnnDistance()) { KNNList knns_p = knnq.getKNNForDBID(p.getRoutingObjectID(), getKmax() - 1); if (knns_p.size() + 1 < getKmax()) { p.setKnnDistance(Double.NaN); } else { double knnDist_p = Math.max(dist_pq, knns_p.getKNNDistance()); p.setKnnDistance(knnDist_p); } } knnDist_node = Math.max(knnDist_node, p.getKnnDistance()); } } // directory node else { List<DoubleIntPair> entries = getSortedEntries(node, q.getRoutingObjectID()); for (DoubleIntPair distEntry : entries) { MkMaxEntry dirEntry = node.getEntry(distEntry.second); double entry_knnDist = dirEntry.getKnnDistance(); if (distEntry.second < entry_knnDist || distEntry.second < knnDist_q) { preInsert(q, dirEntry, knns_q); knnDist_q = knns_q.getKNNDistance(); } knnDist_node = Math.max(knnDist_node, dirEntry.getKnnDistance()); } } if (LOG.isDebugging()) { LOG.debugFine(nodeEntry + "set knn dist " + knnDist_node); } nodeEntry.setKnnDistance(knnDist_node); } }
public class class_name { private void preInsert(MkMaxEntry q, MkMaxEntry nodeEntry, KNNHeap knns_q) { if (LOG.isDebugging()) { LOG.debugFine("preInsert " + q + " - " + nodeEntry + "\n"); // depends on control dependency: [if], data = [none] } double knnDist_q = knns_q.getKNNDistance(); MkMaxTreeNode<O> node = getNode(nodeEntry); double knnDist_node = 0.; // leaf node if (node.isLeaf()) { for (int i = 0; i < node.getNumEntries(); i++) { MkMaxEntry p = node.getEntry(i); double dist_pq = distance(p.getRoutingObjectID(), q.getRoutingObjectID()); // p is nearer to q than the farthest kNN-candidate of q // ==> p becomes a knn-candidate if (dist_pq <= knnDist_q) { knns_q.insert(dist_pq, p.getRoutingObjectID()); // depends on control dependency: [if], data = [(dist_pq] if (knns_q.size() >= getKmax()) { knnDist_q = knns_q.getKNNDistance(); // depends on control dependency: [if], data = [none] q.setKnnDistance(knnDist_q); // depends on control dependency: [if], data = [none] } } // p is nearer to q than to its farthest knn-candidate // q becomes knn of p if (dist_pq <= p.getKnnDistance()) { KNNList knns_p = knnq.getKNNForDBID(p.getRoutingObjectID(), getKmax() - 1); if (knns_p.size() + 1 < getKmax()) { p.setKnnDistance(Double.NaN); // depends on control dependency: [if], data = [none] } else { double knnDist_p = Math.max(dist_pq, knns_p.getKNNDistance()); p.setKnnDistance(knnDist_p); // depends on control dependency: [if], data = [none] } } knnDist_node = Math.max(knnDist_node, p.getKnnDistance()); // depends on control dependency: [for], data = [none] } } // directory node else { List<DoubleIntPair> entries = getSortedEntries(node, q.getRoutingObjectID()); for (DoubleIntPair distEntry : entries) { MkMaxEntry dirEntry = node.getEntry(distEntry.second); double entry_knnDist = dirEntry.getKnnDistance(); if (distEntry.second < entry_knnDist || distEntry.second < knnDist_q) { preInsert(q, dirEntry, knns_q); // depends on control dependency: [if], data = [none] knnDist_q = knns_q.getKNNDistance(); // depends on control dependency: [if], data = [none] } knnDist_node = Math.max(knnDist_node, dirEntry.getKnnDistance()); // depends on control dependency: [for], data = [none] } } if (LOG.isDebugging()) { LOG.debugFine(nodeEntry + "set knn dist " + knnDist_node); // depends on control dependency: [if], data = [none] } nodeEntry.setKnnDistance(knnDist_node); } }
public class class_name { public void loadKeys(DataStructureAdapter<Object, ?> adapter) { if (!storeFile.exists()) { logger.info(format("Skipped loading keys of Near Cache %s since storage file doesn't exist (%s)", nearCacheName, storeFile.getAbsolutePath())); return; } long startedNanos = System.nanoTime(); BufferingInputStream bis = null; try { bis = new BufferingInputStream(new FileInputStream(storeFile), BUFFER_SIZE); if (!checkHeader(bis)) { return; } int loadedKeys = loadKeySet(bis, adapter); long elapsedMillis = getElapsedMillis(startedNanos); logger.info(format("Loaded %d keys of Near Cache %s in %d ms", loadedKeys, nearCacheName, elapsedMillis)); } catch (Exception e) { logger.warning(format("Could not pre-load Near Cache %s (%s)", nearCacheName, storeFile.getAbsolutePath()), e); } finally { closeResource(bis); } } }
public class class_name { public void loadKeys(DataStructureAdapter<Object, ?> adapter) { if (!storeFile.exists()) { logger.info(format("Skipped loading keys of Near Cache %s since storage file doesn't exist (%s)", nearCacheName, storeFile.getAbsolutePath())); // depends on control dependency: [if], data = [none] return; // depends on control dependency: [if], data = [none] } long startedNanos = System.nanoTime(); BufferingInputStream bis = null; try { bis = new BufferingInputStream(new FileInputStream(storeFile), BUFFER_SIZE); // depends on control dependency: [try], data = [none] if (!checkHeader(bis)) { return; // depends on control dependency: [if], data = [none] } int loadedKeys = loadKeySet(bis, adapter); long elapsedMillis = getElapsedMillis(startedNanos); logger.info(format("Loaded %d keys of Near Cache %s in %d ms", loadedKeys, nearCacheName, elapsedMillis)); // depends on control dependency: [try], data = [none] } catch (Exception e) { logger.warning(format("Could not pre-load Near Cache %s (%s)", nearCacheName, storeFile.getAbsolutePath()), e); } finally { // depends on control dependency: [catch], data = [none] closeResource(bis); } } }
public class class_name { public void put(ItemData item) { // There is different commit processing for NullNodeData and ordinary ItemData. if (item instanceof NullItemData) { putNullItem((NullItemData)item); return; } boolean inTransaction = cache.isTransactionActive(); try { if (!inTransaction) { cache.beginTransaction(); } cache.setLocal(true); if (item.isNode()) { putNode((NodeData)item, ModifyChildOption.NOT_MODIFY); } else { putProperty((PropertyData)item, ModifyChildOption.NOT_MODIFY); } } finally { cache.setLocal(false); if (!inTransaction) { dedicatedTxCommit(); } } } }
public class class_name { public void put(ItemData item) { // There is different commit processing for NullNodeData and ordinary ItemData. if (item instanceof NullItemData) { putNullItem((NullItemData)item); // depends on control dependency: [if], data = [none] return; // depends on control dependency: [if], data = [none] } boolean inTransaction = cache.isTransactionActive(); try { if (!inTransaction) { cache.beginTransaction(); // depends on control dependency: [if], data = [none] } cache.setLocal(true); // depends on control dependency: [try], data = [none] if (item.isNode()) { putNode((NodeData)item, ModifyChildOption.NOT_MODIFY); // depends on control dependency: [if], data = [none] } else { putProperty((PropertyData)item, ModifyChildOption.NOT_MODIFY); // depends on control dependency: [if], data = [none] } } finally { cache.setLocal(false); if (!inTransaction) { dedicatedTxCommit(); // depends on control dependency: [if], data = [none] } } } }
public class class_name { public static int solveQuad (double[] eqn, double[] res) { double a = eqn[2]; double b = eqn[1]; double c = eqn[0]; int rc = 0; if (a == 0f) { if (b == 0f) { return -1; } res[rc++] = -c / b; } else { double d = b * b - 4f * a * c; // d < 0f if (d < 0f) { return 0; } d = Math.sqrt(d); res[rc++] = (-b + d) / (a * 2f); // d != 0f if (d != 0f) { res[rc++] = (-b - d) / (a * 2f); } } return fixRoots(res, rc); } }
public class class_name { public static int solveQuad (double[] eqn, double[] res) { double a = eqn[2]; double b = eqn[1]; double c = eqn[0]; int rc = 0; if (a == 0f) { if (b == 0f) { return -1; // depends on control dependency: [if], data = [none] } res[rc++] = -c / b; // depends on control dependency: [if], data = [none] } else { double d = b * b - 4f * a * c; // d < 0f if (d < 0f) { return 0; // depends on control dependency: [if], data = [none] } d = Math.sqrt(d); // depends on control dependency: [if], data = [none] res[rc++] = (-b + d) / (a * 2f); // depends on control dependency: [if], data = [(a] // d != 0f if (d != 0f) { res[rc++] = (-b - d) / (a * 2f); // depends on control dependency: [if], data = [none] } } return fixRoots(res, rc); } }
public class class_name { public String getContentTypeWithVersion() { if (!StringUtils.hasText(this.contentTypeTemplate) || !StringUtils.hasText(this.version)) { return ""; } return this.contentTypeTemplate.replaceAll(VERSION_PLACEHOLDER_REGEX, this.version); } }
public class class_name { public String getContentTypeWithVersion() { if (!StringUtils.hasText(this.contentTypeTemplate) || !StringUtils.hasText(this.version)) { return ""; // depends on control dependency: [if], data = [none] } return this.contentTypeTemplate.replaceAll(VERSION_PLACEHOLDER_REGEX, this.version); } }
public class class_name { public void marshall(ScalingConstraints scalingConstraints, ProtocolMarshaller protocolMarshaller) { if (scalingConstraints == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(scalingConstraints.getMinCapacity(), MINCAPACITY_BINDING); protocolMarshaller.marshall(scalingConstraints.getMaxCapacity(), MAXCAPACITY_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
public class class_name { public void marshall(ScalingConstraints scalingConstraints, ProtocolMarshaller protocolMarshaller) { if (scalingConstraints == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(scalingConstraints.getMinCapacity(), MINCAPACITY_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(scalingConstraints.getMaxCapacity(), MAXCAPACITY_BINDING); // depends on control dependency: [try], data = [none] } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } // depends on control dependency: [catch], data = [none] } }
public class class_name { private void loadCategories(SQLiteDatabase db) throws UnknownPoiCategoryException { // Maximum ID (for root node) int maxID = 0; // Maps categories to their parent IDs Map<PoiCategory, Integer> parentMap = new HashMap<>(); Cursor cursor = null; try { cursor = db.rawQuery(SELECT_STATEMENT, null); while (cursor.moveToNext()) { // Column values int categoryID = cursor.getInt(0); String categoryTitle = cursor.getString(1); int categoryParentID = cursor.getInt(2); PoiCategory pc = new DoubleLinkedPoiCategory(categoryTitle, null, categoryID); this.categoryMap.put(categoryID, pc); // category --> parent ID parentMap.put(pc, categoryParentID); // check for root node if (categoryID > maxID) { maxID = categoryID; } } } catch (Exception e) { LOGGER.log(Level.SEVERE, e.getMessage(), e); } finally { try { if (cursor != null) { cursor.close(); } } catch (Exception e) { LOGGER.log(Level.SEVERE, e.getMessage(), e); } } // Set root category and remove it from parents map this.rootCategory = getPoiCategoryByID(maxID); parentMap.remove(this.rootCategory); // Assign parent categories for (PoiCategory c : parentMap.keySet()) { c.setParent(getPoiCategoryByID(parentMap.get(c))); } } }
public class class_name { private void loadCategories(SQLiteDatabase db) throws UnknownPoiCategoryException { // Maximum ID (for root node) int maxID = 0; // Maps categories to their parent IDs Map<PoiCategory, Integer> parentMap = new HashMap<>(); Cursor cursor = null; try { cursor = db.rawQuery(SELECT_STATEMENT, null); while (cursor.moveToNext()) { // Column values int categoryID = cursor.getInt(0); String categoryTitle = cursor.getString(1); int categoryParentID = cursor.getInt(2); PoiCategory pc = new DoubleLinkedPoiCategory(categoryTitle, null, categoryID); this.categoryMap.put(categoryID, pc); // depends on control dependency: [while], data = [none] // category --> parent ID parentMap.put(pc, categoryParentID); // depends on control dependency: [while], data = [none] // check for root node if (categoryID > maxID) { maxID = categoryID; // depends on control dependency: [if], data = [none] } } } catch (Exception e) { LOGGER.log(Level.SEVERE, e.getMessage(), e); } finally { try { if (cursor != null) { cursor.close(); // depends on control dependency: [if], data = [none] } } catch (Exception e) { LOGGER.log(Level.SEVERE, e.getMessage(), e); } // depends on control dependency: [catch], data = [none] } // Set root category and remove it from parents map this.rootCategory = getPoiCategoryByID(maxID); parentMap.remove(this.rootCategory); // Assign parent categories for (PoiCategory c : parentMap.keySet()) { c.setParent(getPoiCategoryByID(parentMap.get(c))); } } }
public class class_name { public static Inet6Address forIPv6String(String ipString) { requireNonNull(ipString); try{ InetAddress parsed = forString(ipString); if (parsed instanceof Inet6Address) return (Inet6Address) parsed; } catch(Exception ignored){} throw new IllegalArgumentException(format("Invalid IPv6 representation: %s", ipString)); } }
public class class_name { public static Inet6Address forIPv6String(String ipString) { requireNonNull(ipString); try{ InetAddress parsed = forString(ipString); if (parsed instanceof Inet6Address) return (Inet6Address) parsed; } catch(Exception ignored){} // depends on control dependency: [catch], data = [none] throw new IllegalArgumentException(format("Invalid IPv6 representation: %s", ipString)); } }
public class class_name { public static Object createInstance(Class<?> type) { Object instance=null; try { //create instance instance=type.newInstance(); } catch(Exception exception) { throw new FaxException("Unable to create new instance of type: "+type,exception); } return instance; } }
public class class_name { public static Object createInstance(Class<?> type) { Object instance=null; try { //create instance instance=type.newInstance(); // depends on control dependency: [try], data = [none] } catch(Exception exception) { throw new FaxException("Unable to create new instance of type: "+type,exception); } // depends on control dependency: [catch], data = [none] return instance; } }
public class class_name { private void ensureAvailable(int index) { if (data.get(index) != null) { // Already have this item. return; } if (client == null) { throw new RuntimeException("no remoting client configured"); } Object result; int start = index; int count; if (mode.equals(MODE_ONDEMAND)) { // Only get requested item count = 1; } else if (mode.equals(MODE_FETCHALL)) { // Get remaining items count = totalCount - cursor; } else if (mode.equals(MODE_PAGE)) { // Get next page // TODO: implement prefetching of multiple pages count = 1; for (int i = 1; i < pageSize; i++) { if (this.data.get(start + i) == null) { count += 1; } } } else { // Default to "ondemand" count = 1; } result = client.invokeMethod(serviceName + ".getRecords", new Object[] { id, start + 1, count }); if (!(result instanceof RecordSetPage)) { throw new RuntimeException("expected RecordSetPage but got " + result); } RecordSetPage page = (RecordSetPage) result; if (page.getCursor() != start + 1) { throw new RuntimeException("expected offset " + (start + 1) + " but got " + page.getCursor()); } List<List<Object>> data = page.getData(); if (data.size() != count) { throw new RuntimeException("expected " + count + " results but got " + data.size()); } // Store received items for (int i = 0; i < count; i++) { this.data.add(start + i, data.get(i)); } } }
public class class_name { private void ensureAvailable(int index) { if (data.get(index) != null) { // Already have this item. return; // depends on control dependency: [if], data = [none] } if (client == null) { throw new RuntimeException("no remoting client configured"); } Object result; int start = index; int count; if (mode.equals(MODE_ONDEMAND)) { // Only get requested item count = 1; // depends on control dependency: [if], data = [none] } else if (mode.equals(MODE_FETCHALL)) { // Get remaining items count = totalCount - cursor; // depends on control dependency: [if], data = [none] } else if (mode.equals(MODE_PAGE)) { // Get next page // TODO: implement prefetching of multiple pages count = 1; // depends on control dependency: [if], data = [none] for (int i = 1; i < pageSize; i++) { if (this.data.get(start + i) == null) { count += 1; // depends on control dependency: [if], data = [none] } } } else { // Default to "ondemand" count = 1; // depends on control dependency: [if], data = [none] } result = client.invokeMethod(serviceName + ".getRecords", new Object[] { id, start + 1, count }); if (!(result instanceof RecordSetPage)) { throw new RuntimeException("expected RecordSetPage but got " + result); } RecordSetPage page = (RecordSetPage) result; if (page.getCursor() != start + 1) { throw new RuntimeException("expected offset " + (start + 1) + " but got " + page.getCursor()); } List<List<Object>> data = page.getData(); if (data.size() != count) { throw new RuntimeException("expected " + count + " results but got " + data.size()); } // Store received items for (int i = 0; i < count; i++) { this.data.add(start + i, data.get(i)); // depends on control dependency: [for], data = [i] } } }
public class class_name { @Override public EClass getIfcElectricChargeMeasure() { if (ifcElectricChargeMeasureEClass == null) { ifcElectricChargeMeasureEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI) .getEClassifiers().get(800); } return ifcElectricChargeMeasureEClass; } }
public class class_name { @Override public EClass getIfcElectricChargeMeasure() { if (ifcElectricChargeMeasureEClass == null) { ifcElectricChargeMeasureEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI) .getEClassifiers().get(800); // depends on control dependency: [if], data = [none] } return ifcElectricChargeMeasureEClass; } }
public class class_name { public int getViewType(@NonNull AdapterDelegate<T> delegate) { if (delegate == null) { throw new NullPointerException("Delegate is null"); } int index = delegates.indexOfValue(delegate); if (index == -1) { return -1; } return delegates.keyAt(index); } }
public class class_name { public int getViewType(@NonNull AdapterDelegate<T> delegate) { if (delegate == null) { throw new NullPointerException("Delegate is null"); } int index = delegates.indexOfValue(delegate); if (index == -1) { return -1; // depends on control dependency: [if], data = [none] } return delegates.keyAt(index); } }
public class class_name { public static Map<String, Map<String, Map<String, Map<String, ?>>>> getCoreValidationConstraints() { if (CORE_CONSTRAINTS.isEmpty()) { for (Map.Entry<String, Class<? extends ParaObject>> e : ParaObjectUtils.getCoreClassesMap().entrySet()) { String type = e.getKey(); List<Field> fieldlist = Utils.getAllDeclaredFields(e.getValue()); for (Field field : fieldlist) { Annotation[] annos = field.getAnnotations(); if (annos.length > 1) { Map<String, Map<String, ?>> constrMap = new HashMap<>(); for (Annotation anno : annos) { if (isValidConstraintType(anno.annotationType())) { Constraint c = fromAnnotation(anno); if (c != null) { constrMap.put(c.getName(), c.getPayload()); } } } if (!constrMap.isEmpty()) { if (!CORE_CONSTRAINTS.containsKey(type)) { CORE_CONSTRAINTS.put(type, new HashMap<>()); } CORE_CONSTRAINTS.get(type).put(field.getName(), constrMap); } } } } } return Collections.unmodifiableMap(CORE_CONSTRAINTS); } }
public class class_name { public static Map<String, Map<String, Map<String, Map<String, ?>>>> getCoreValidationConstraints() { if (CORE_CONSTRAINTS.isEmpty()) { for (Map.Entry<String, Class<? extends ParaObject>> e : ParaObjectUtils.getCoreClassesMap().entrySet()) { String type = e.getKey(); List<Field> fieldlist = Utils.getAllDeclaredFields(e.getValue()); for (Field field : fieldlist) { Annotation[] annos = field.getAnnotations(); if (annos.length > 1) { Map<String, Map<String, ?>> constrMap = new HashMap<>(); // depends on control dependency: [if], data = [none] for (Annotation anno : annos) { if (isValidConstraintType(anno.annotationType())) { Constraint c = fromAnnotation(anno); if (c != null) { constrMap.put(c.getName(), c.getPayload()); // depends on control dependency: [if], data = [(c] } } } if (!constrMap.isEmpty()) { if (!CORE_CONSTRAINTS.containsKey(type)) { CORE_CONSTRAINTS.put(type, new HashMap<>()); // depends on control dependency: [if], data = [none] } CORE_CONSTRAINTS.get(type).put(field.getName(), constrMap); // depends on control dependency: [if], data = [none] } } } } } return Collections.unmodifiableMap(CORE_CONSTRAINTS); } }
public class class_name { public static String buildPath(String first, String... parts) { StringBuilder result = new StringBuilder(first); for (String part : parts) { if (result.length() == 0) { if (part.startsWith("/")) { result.append(part.substring(1)); } else { result.append(part); } } else { if (result.toString().endsWith("/") && part.startsWith("/")) { result.append(part.substring(1)); } else if (!result.toString().endsWith("/") && !part.startsWith("/") && !part.isEmpty()) { result.append("/").append(part); } else { result.append(part); } } } return result.toString(); } }
public class class_name { public static String buildPath(String first, String... parts) { StringBuilder result = new StringBuilder(first); for (String part : parts) { if (result.length() == 0) { if (part.startsWith("/")) { result.append(part.substring(1)); // depends on control dependency: [if], data = [none] } else { result.append(part); // depends on control dependency: [if], data = [none] } } else { if (result.toString().endsWith("/") && part.startsWith("/")) { result.append(part.substring(1)); // depends on control dependency: [if], data = [none] } else if (!result.toString().endsWith("/") && !part.startsWith("/") && !part.isEmpty()) { result.append("/").append(part); // depends on control dependency: [if], data = [none] } else { result.append(part); // depends on control dependency: [if], data = [none] } } } return result.toString(); } }
public class class_name { @Override public Boolean fromString(final String rawValue) { try { return PrimitiveObjectFactory.parseBoolean(rawValue); } catch (final IllegalArgumentException e) { throw new ObjectParseException(e,Boolean.class, rawValue); } } }
public class class_name { @Override public Boolean fromString(final String rawValue) { try { return PrimitiveObjectFactory.parseBoolean(rawValue); // depends on control dependency: [try], data = [none] } catch (final IllegalArgumentException e) { throw new ObjectParseException(e,Boolean.class, rawValue); } // depends on control dependency: [catch], data = [none] } }
public class class_name { @CheckReturnValue @BackpressureSupport(BackpressureKind.SPECIAL) @SchedulerSupport(SchedulerSupport.NONE) public final <R> R to(Function<? super Flowable<T>, R> converter) { try { return ObjectHelper.requireNonNull(converter, "converter is null").apply(this); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); throw ExceptionHelper.wrapOrThrow(ex); } } }
public class class_name { @CheckReturnValue @BackpressureSupport(BackpressureKind.SPECIAL) @SchedulerSupport(SchedulerSupport.NONE) public final <R> R to(Function<? super Flowable<T>, R> converter) { try { return ObjectHelper.requireNonNull(converter, "converter is null").apply(this); // depends on control dependency: [try], data = [none] } catch (Throwable ex) { Exceptions.throwIfFatal(ex); throw ExceptionHelper.wrapOrThrow(ex); } // depends on control dependency: [catch], data = [none] } }
public class class_name { public JSONObject createTask(String name, String templateContent, String inputMappingFile, String outputFile, String urlPattern, HashMap<String, String> options) { AipRequest request = new AipRequest(); preOperation(request); request.addBody("name", name); request.addBody("template_content", templateContent); request.addBody("input_mapping_file", inputMappingFile); request.addBody("output_file", outputFile); request.addBody("url_pattern", urlPattern); if (options != null) { request.addBody(options); } request.setUri(KnowledgeGraphicConsts.CREATE_TASK); postOperation(request); return requestServer(request); } }
public class class_name { public JSONObject createTask(String name, String templateContent, String inputMappingFile, String outputFile, String urlPattern, HashMap<String, String> options) { AipRequest request = new AipRequest(); preOperation(request); request.addBody("name", name); request.addBody("template_content", templateContent); request.addBody("input_mapping_file", inputMappingFile); request.addBody("output_file", outputFile); request.addBody("url_pattern", urlPattern); if (options != null) { request.addBody(options); // depends on control dependency: [if], data = [(options] } request.setUri(KnowledgeGraphicConsts.CREATE_TASK); postOperation(request); return requestServer(request); } }
public class class_name { public void attachView(View view) { if (view == null) { throw new IllegalArgumentException("Mvp view must be not null"); } boolean isViewAdded = mViews.add(view); if (!isViewAdded) { return; } mInRestoreState.add(view); Set<ViewCommand<View>> currentState = mViewStates.get(view); currentState = currentState == null ? Collections.<ViewCommand<View>>emptySet() : currentState; restoreState(view, currentState); mViewStates.remove(view); mInRestoreState.remove(view); } }
public class class_name { public void attachView(View view) { if (view == null) { throw new IllegalArgumentException("Mvp view must be not null"); } boolean isViewAdded = mViews.add(view); if (!isViewAdded) { return; // depends on control dependency: [if], data = [none] } mInRestoreState.add(view); Set<ViewCommand<View>> currentState = mViewStates.get(view); currentState = currentState == null ? Collections.<ViewCommand<View>>emptySet() : currentState; restoreState(view, currentState); mViewStates.remove(view); mInRestoreState.remove(view); } }
public class class_name { public Quaternionf set(Quaternionfc q) { if (q instanceof Quaternionf) MemUtil.INSTANCE.copy((Quaternionf) q, this); else { this.x = q.x(); this.y = q.y(); this.z = q.z(); this.w = q.w(); } return this; } }
public class class_name { public Quaternionf set(Quaternionfc q) { if (q instanceof Quaternionf) MemUtil.INSTANCE.copy((Quaternionf) q, this); else { this.x = q.x(); // depends on control dependency: [if], data = [none] this.y = q.y(); // depends on control dependency: [if], data = [none] this.z = q.z(); // depends on control dependency: [if], data = [none] this.w = q.w(); // depends on control dependency: [if], data = [none] } return this; } }
public class class_name { public static ExtendedEntityManager[] getDeferredEntityManagers() { List<ExtendedEntityManager> store = deferToPostConstruct.get(); try { if(store.isEmpty()) { return EMPTY; } else { return store.toArray(new ExtendedEntityManager[store.size()]); } } finally { store.clear(); } } }
public class class_name { public static ExtendedEntityManager[] getDeferredEntityManagers() { List<ExtendedEntityManager> store = deferToPostConstruct.get(); try { if(store.isEmpty()) { return EMPTY; // depends on control dependency: [if], data = [none] } else { return store.toArray(new ExtendedEntityManager[store.size()]); // depends on control dependency: [if], data = [none] } } finally { store.clear(); } } }
public class class_name { @Override public <R> Try<R> flatMap(ThrowableFunction1<T, Try<R>> function) { try { return function.apply(value); } catch(Throwable t) { return new Failure<>(t); } } }
public class class_name { @Override public <R> Try<R> flatMap(ThrowableFunction1<T, Try<R>> function) { try { return function.apply(value); // depends on control dependency: [try], data = [none] } catch(Throwable t) { return new Failure<>(t); } // depends on control dependency: [catch], data = [none] } }
public class class_name { public final void ifStatement() throws RecognitionException { int ifStatement_StartIndex = input.index(); Token s=null; Token y=null; ParserRuleReturnScope x =null; ParserRuleReturnScope z =null; JavaIfBlockDescr id = null; JavaElseBlockDescr ed = null; try { if ( state.backtracking>0 && alreadyParsedRule(input, 85) ) { return; } // src/main/resources/org/drools/compiler/semantics/java/parser/Java.g:771:5: (s= 'if' parExpression x= statement (y= 'else' ( 'if' parExpression )? z= statement )* ) // src/main/resources/org/drools/compiler/semantics/java/parser/Java.g:773:5: s= 'if' parExpression x= statement (y= 'else' ( 'if' parExpression )? z= statement )* { s=(Token)match(input,87,FOLLOW_87_in_ifStatement3243); if (state.failed) return; pushFollow(FOLLOW_parExpression_in_ifStatement3245); parExpression(); state._fsp--; if (state.failed) return; if ( state.backtracking==0 ) { increaseLevel(); id = new JavaIfBlockDescr(); id.setStart( ((CommonToken)s).getStartIndex() ); pushContainerBlockDescr(id, true); } pushFollow(FOLLOW_statement_in_ifStatement3263); x=statement(); state._fsp--; if (state.failed) return; if ( state.backtracking==0 ) { decreaseLevel(); id.setTextStart(((CommonToken)(x!=null?(x.start):null)).getStartIndex() ); id.setEnd(((CommonToken)(x!=null?(x.stop):null)).getStopIndex() ); popContainerBlockDescr(); } // src/main/resources/org/drools/compiler/semantics/java/parser/Java.g:786:5: (y= 'else' ( 'if' parExpression )? z= statement )* loop113: while (true) { int alt113=2; alt113 = dfa113.predict(input); switch (alt113) { case 1 : // src/main/resources/org/drools/compiler/semantics/java/parser/Java.g:787:6: y= 'else' ( 'if' parExpression )? z= statement { y=(Token)match(input,78,FOLLOW_78_in_ifStatement3290); if (state.failed) return; // src/main/resources/org/drools/compiler/semantics/java/parser/Java.g:787:16: ( 'if' parExpression )? int alt112=2; int LA112_0 = input.LA(1); if ( (LA112_0==87) ) { int LA112_1 = input.LA(2); if ( (LA112_1==36) ) { int LA112_43 = input.LA(3); if ( (synpred171_Java()) ) { alt112=1; } } } switch (alt112) { case 1 : // src/main/resources/org/drools/compiler/semantics/java/parser/Java.g:787:17: 'if' parExpression { match(input,87,FOLLOW_87_in_ifStatement3294); if (state.failed) return; pushFollow(FOLLOW_parExpression_in_ifStatement3296); parExpression(); state._fsp--; if (state.failed) return; } break; } if ( state.backtracking==0 ) { increaseLevel(); ed = new JavaElseBlockDescr(); ed.setStart( ((CommonToken)y).getStartIndex() ); pushContainerBlockDescr(ed, true); } pushFollow(FOLLOW_statement_in_ifStatement3327); z=statement(); state._fsp--; if (state.failed) return; if ( state.backtracking==0 ) { decreaseLevel(); ed.setTextStart(((CommonToken)(z!=null?(z.start):null)).getStartIndex() ); ed.setEnd(((CommonToken)(z!=null?(z.stop):null)).getStopIndex() ); popContainerBlockDescr(); } } break; default : break loop113; } } } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { // do for sure before leaving if ( state.backtracking>0 ) { memoize(input, 85, ifStatement_StartIndex); } } } }
public class class_name { public final void ifStatement() throws RecognitionException { int ifStatement_StartIndex = input.index(); Token s=null; Token y=null; ParserRuleReturnScope x =null; ParserRuleReturnScope z =null; JavaIfBlockDescr id = null; JavaElseBlockDescr ed = null; try { if ( state.backtracking>0 && alreadyParsedRule(input, 85) ) { return; } // depends on control dependency: [if], data = [none] // src/main/resources/org/drools/compiler/semantics/java/parser/Java.g:771:5: (s= 'if' parExpression x= statement (y= 'else' ( 'if' parExpression )? z= statement )* ) // src/main/resources/org/drools/compiler/semantics/java/parser/Java.g:773:5: s= 'if' parExpression x= statement (y= 'else' ( 'if' parExpression )? z= statement )* { s=(Token)match(input,87,FOLLOW_87_in_ifStatement3243); if (state.failed) return; pushFollow(FOLLOW_parExpression_in_ifStatement3245); parExpression(); state._fsp--; if (state.failed) return; if ( state.backtracking==0 ) { increaseLevel(); // depends on control dependency: [if], data = [none] id = new JavaIfBlockDescr(); // depends on control dependency: [if], data = [none] id.setStart( ((CommonToken)s).getStartIndex() ); pushContainerBlockDescr(id, true); // depends on control dependency: [if], data = [none] // depends on control dependency: [if], data = [none] } pushFollow(FOLLOW_statement_in_ifStatement3263); x=statement(); state._fsp--; if (state.failed) return; if ( state.backtracking==0 ) { decreaseLevel(); // depends on control dependency: [if], data = [none] id.setTextStart(((CommonToken)(x!=null?(x.start):null)).getStartIndex() ); // depends on control dependency: [if], data = [none] id.setEnd(((CommonToken)(x!=null?(x.stop):null)).getStopIndex() ); popContainerBlockDescr(); // depends on control dependency: [if], data = [none] // depends on control dependency: [if], data = [none] } // src/main/resources/org/drools/compiler/semantics/java/parser/Java.g:786:5: (y= 'else' ( 'if' parExpression )? z= statement )* loop113: while (true) { int alt113=2; alt113 = dfa113.predict(input); // depends on control dependency: [while], data = [none] switch (alt113) { case 1 : // src/main/resources/org/drools/compiler/semantics/java/parser/Java.g:787:6: y= 'else' ( 'if' parExpression )? z= statement { y=(Token)match(input,78,FOLLOW_78_in_ifStatement3290); if (state.failed) return; // src/main/resources/org/drools/compiler/semantics/java/parser/Java.g:787:16: ( 'if' parExpression )? int alt112=2; int LA112_0 = input.LA(1); if ( (LA112_0==87) ) { int LA112_1 = input.LA(2); if ( (LA112_1==36) ) { int LA112_43 = input.LA(3); if ( (synpred171_Java()) ) { alt112=1; // depends on control dependency: [if], data = [none] } } } switch (alt112) { case 1 : // src/main/resources/org/drools/compiler/semantics/java/parser/Java.g:787:17: 'if' parExpression { match(input,87,FOLLOW_87_in_ifStatement3294); if (state.failed) return; pushFollow(FOLLOW_parExpression_in_ifStatement3296); parExpression(); state._fsp--; if (state.failed) return; } break; } if ( state.backtracking==0 ) { increaseLevel(); // depends on control dependency: [if], data = [none] ed = new JavaElseBlockDescr(); // depends on control dependency: [if], data = [none] ed.setStart( ((CommonToken)y).getStartIndex() ); pushContainerBlockDescr(ed, true); // depends on control dependency: [if], data = [none] // depends on control dependency: [if], data = [none] } pushFollow(FOLLOW_statement_in_ifStatement3327); z=statement(); state._fsp--; if (state.failed) return; if ( state.backtracking==0 ) { decreaseLevel(); // depends on control dependency: [if], data = [none] ed.setTextStart(((CommonToken)(z!=null?(z.start):null)).getStartIndex() ); // depends on control dependency: [if], data = [none] ed.setEnd(((CommonToken)(z!=null?(z.stop):null)).getStopIndex() ); popContainerBlockDescr(); // depends on control dependency: [if], data = [none] // depends on control dependency: [if], data = [none] } } break; default : break loop113; } } } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { // do for sure before leaving if ( state.backtracking>0 ) { memoize(input, 85, ifStatement_StartIndex); } // depends on control dependency: [if], data = [none] } } }
public class class_name { public void moveThisFile(File fileSource, File fileDestDir, String strDestName) { // Step 1 - Find the class name for this file: String className = fileSource.getPath().replace('/', '.'); if (className.endsWith(".xml")) className = className.substring(0, className.length() - 4); boolean classFound = false; Record record = null; String databaseName = null; Map<String,String> oldProperties = new HashMap<String,String>(); if (className.endsWith(DatabaseInfo.DATABASE_INFO_FILE)) { record = new DatabaseInfo(); databaseName = this.getDatabaseInfoDatabaseName(className); ((DatabaseInfo)record).setDatabaseName(databaseName); if (databaseName.indexOf('_') != -1) { String tableName = "DatabaseInfo_" + databaseName.substring(0, databaseName.indexOf('_')); record.setTableNames(tableName); } record.init(this.m_parent); this.saveOldProperties(oldProperties, record); } else { while (!classFound) { record = (Record)ClassServiceUtility.getClassService().makeObjectFromClassName(className); if (record != null) { record.init(this.m_parent); classFound = true; } else { if (className.indexOf('.') == -1) { System.out.println("Class not found: " + fileSource.toString()); return; } databaseName = className.substring(0, className.indexOf('.')); className = className.substring(className.indexOf('.') + 1); } } this.saveOldProperties(oldProperties, record); databaseName = this.fixDatabaseName(databaseName, record, oldProperties); } String recordDBName = record.getDatabaseName(); System.out.println("Process import: " + className + " (" + databaseName + ") to " + record.getRecordName() + " (" + recordDBName + ")"); if (!inout.importXML(record.getTable(), fileSource.getPath(), null)) System.exit(1); this.restoreOldProperties(oldProperties, record); record.free(); } }
public class class_name { public void moveThisFile(File fileSource, File fileDestDir, String strDestName) { // Step 1 - Find the class name for this file: String className = fileSource.getPath().replace('/', '.'); if (className.endsWith(".xml")) className = className.substring(0, className.length() - 4); boolean classFound = false; Record record = null; String databaseName = null; Map<String,String> oldProperties = new HashMap<String,String>(); if (className.endsWith(DatabaseInfo.DATABASE_INFO_FILE)) { record = new DatabaseInfo(); // depends on control dependency: [if], data = [none] databaseName = this.getDatabaseInfoDatabaseName(className); // depends on control dependency: [if], data = [none] ((DatabaseInfo)record).setDatabaseName(databaseName); // depends on control dependency: [if], data = [none] if (databaseName.indexOf('_') != -1) { String tableName = "DatabaseInfo_" + databaseName.substring(0, databaseName.indexOf('_')); record.setTableNames(tableName); // depends on control dependency: [if], data = [none] } record.init(this.m_parent); // depends on control dependency: [if], data = [none] this.saveOldProperties(oldProperties, record); // depends on control dependency: [if], data = [none] } else { while (!classFound) { record = (Record)ClassServiceUtility.getClassService().makeObjectFromClassName(className); // depends on control dependency: [while], data = [none] if (record != null) { record.init(this.m_parent); // depends on control dependency: [if], data = [none] classFound = true; // depends on control dependency: [if], data = [none] } else { if (className.indexOf('.') == -1) { System.out.println("Class not found: " + fileSource.toString()); // depends on control dependency: [if], data = [none] return; // depends on control dependency: [if], data = [none] } databaseName = className.substring(0, className.indexOf('.')); // depends on control dependency: [if], data = [none] className = className.substring(className.indexOf('.') + 1); // depends on control dependency: [if], data = [none] } } this.saveOldProperties(oldProperties, record); // depends on control dependency: [if], data = [none] databaseName = this.fixDatabaseName(databaseName, record, oldProperties); // depends on control dependency: [if], data = [none] } String recordDBName = record.getDatabaseName(); System.out.println("Process import: " + className + " (" + databaseName + ") to " + record.getRecordName() + " (" + recordDBName + ")"); if (!inout.importXML(record.getTable(), fileSource.getPath(), null)) System.exit(1); this.restoreOldProperties(oldProperties, record); record.free(); } }
public class class_name { private void mapExecutable(ExecutableMemberDoc em) { boolean isConstructor = em.isConstructor(); Set<Type> classArgs = new TreeSet<>(utils.makeTypeComparator()); for (Parameter param : em.parameters()) { Type pcd = param.type(); // ignore primitives and typevars, typevars are handled elsewhere if ((!param.type().isPrimitive()) && !(pcd instanceof TypeVariable)) { // avoid dups if (classArgs.add(pcd)) { add(isConstructor ? classToConstructorArgs : classToMethodArgs, pcd.asClassDoc(), em); mapTypeParameters(isConstructor ? classToConstructorDocArgTypeParam : classToExecMemberDocArgTypeParam, pcd, em); } } mapAnnotations(isConstructor ? classToConstructorParamAnnotation : classToExecMemberDocParamAnnotation, param, em); } for (ClassDoc anException : em.thrownExceptions()) { add(isConstructor ? classToConstructorThrows : classToMethodThrows, anException, em); } } }
public class class_name { private void mapExecutable(ExecutableMemberDoc em) { boolean isConstructor = em.isConstructor(); Set<Type> classArgs = new TreeSet<>(utils.makeTypeComparator()); for (Parameter param : em.parameters()) { Type pcd = param.type(); // ignore primitives and typevars, typevars are handled elsewhere if ((!param.type().isPrimitive()) && !(pcd instanceof TypeVariable)) { // avoid dups if (classArgs.add(pcd)) { add(isConstructor ? classToConstructorArgs : classToMethodArgs, pcd.asClassDoc(), em); // depends on control dependency: [if], data = [none] mapTypeParameters(isConstructor ? classToConstructorDocArgTypeParam : classToExecMemberDocArgTypeParam, pcd, em); // depends on control dependency: [if], data = [none] } } mapAnnotations(isConstructor ? classToConstructorParamAnnotation : classToExecMemberDocParamAnnotation, param, em); // depends on control dependency: [for], data = [none] } for (ClassDoc anException : em.thrownExceptions()) { add(isConstructor ? classToConstructorThrows : classToMethodThrows, anException, em); // depends on control dependency: [for], data = [none] } } }
public class class_name { public java.util.List<ObjectId> getObjectId() { if (objectId == null) { objectId = new ArrayList<ObjectId>(); } return this.objectId; } }
public class class_name { public java.util.List<ObjectId> getObjectId() { if (objectId == null) { objectId = new ArrayList<ObjectId>(); // depends on control dependency: [if], data = [none] } return this.objectId; } }
public class class_name { public Map<String, Object> getDebugInfo() { Preconditions.checkArgument(lifecycleLock.awaitStarted(1, TimeUnit.MILLISECONDS)); Map<String, Object> result = new HashMap<>(servers.size()); for (Map.Entry<String, DruidServerHolder> e : servers.entrySet()) { DruidServerHolder serverHolder = e.getValue(); result.put( e.getKey(), serverHolder.syncer.getDebugInfo() ); } return result; } }
public class class_name { public Map<String, Object> getDebugInfo() { Preconditions.checkArgument(lifecycleLock.awaitStarted(1, TimeUnit.MILLISECONDS)); Map<String, Object> result = new HashMap<>(servers.size()); for (Map.Entry<String, DruidServerHolder> e : servers.entrySet()) { DruidServerHolder serverHolder = e.getValue(); result.put( e.getKey(), serverHolder.syncer.getDebugInfo() ); // depends on control dependency: [for], data = [e] } return result; } }
public class class_name { public void setProxy(Proxy proxy) { if(proxy != null) { java.net.Proxy p = new java.net.Proxy(java.net.Proxy.Type.HTTP, new InetSocketAddress(proxy.getHost(), proxy.getPort())); client.setProxy(p); } else client.setProxy(java.net.Proxy.NO_PROXY); } }
public class class_name { public void setProxy(Proxy proxy) { if(proxy != null) { java.net.Proxy p = new java.net.Proxy(java.net.Proxy.Type.HTTP, new InetSocketAddress(proxy.getHost(), proxy.getPort())); client.setProxy(p); // depends on control dependency: [if], data = [none] } else client.setProxy(java.net.Proxy.NO_PROXY); } }
public class class_name { protected void handleAppendResponseError(RaftMemberContext member, AppendRequest request, AppendResponse response) { // If we've received a greater term, update the term and transition back to follower. if (response.term() > raft.getTerm()) { log.debug("Received higher term from {}", member.getMember().memberId()); raft.setTerm(response.term()); raft.setLeader(null); raft.transition(RaftServer.Role.FOLLOWER); } else { super.handleAppendResponseError(member, request, response); } } }
public class class_name { protected void handleAppendResponseError(RaftMemberContext member, AppendRequest request, AppendResponse response) { // If we've received a greater term, update the term and transition back to follower. if (response.term() > raft.getTerm()) { log.debug("Received higher term from {}", member.getMember().memberId()); // depends on control dependency: [if], data = [none] raft.setTerm(response.term()); // depends on control dependency: [if], data = [(response.term()] raft.setLeader(null); // depends on control dependency: [if], data = [none] raft.transition(RaftServer.Role.FOLLOWER); // depends on control dependency: [if], data = [none] } else { super.handleAppendResponseError(member, request, response); // depends on control dependency: [if], data = [none] } } }
public class class_name { private void jCheckBoxMaxPointsActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jCheckBoxMaxPointsActionPerformed {//GEN-HEADEREND:event_jCheckBoxMaxPointsActionPerformed if (jCheckBoxMaxPoints.isSelected()) { parent.getGraphPanelChart().getChartSettings().setMaxPointPerRow(getValueFromString((String) jComboBoxMaxPoints.getSelectedItem())); } else { parent.getGraphPanelChart().getChartSettings().setMaxPointPerRow(-1); } refreshGraphPreview(); } }
public class class_name { private void jCheckBoxMaxPointsActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jCheckBoxMaxPointsActionPerformed {//GEN-HEADEREND:event_jCheckBoxMaxPointsActionPerformed if (jCheckBoxMaxPoints.isSelected()) { parent.getGraphPanelChart().getChartSettings().setMaxPointPerRow(getValueFromString((String) jComboBoxMaxPoints.getSelectedItem())); // depends on control dependency: [if], data = [none] } else { parent.getGraphPanelChart().getChartSettings().setMaxPointPerRow(-1); // depends on control dependency: [if], data = [none] } refreshGraphPreview(); } }
public class class_name { public static String format(String messageFormat, Object... arguments) { for (int i = 0; i < arguments.length; i++) { arguments[i] = convert(arguments[i]); } return String.format(messageFormat, arguments); } }
public class class_name { public static String format(String messageFormat, Object... arguments) { for (int i = 0; i < arguments.length; i++) { arguments[i] = convert(arguments[i]); // depends on control dependency: [for], data = [i] } return String.format(messageFormat, arguments); } }
public class class_name { public void setCursor(Object object, String cursor) { if (object == null) { Dom.setStyleAttribute(getRootElement(), "cursor", cursor); } else { Element element = getGroup(object); if (element != null) { Dom.setStyleAttribute(element, "cursor", cursor); } } } }
public class class_name { public void setCursor(Object object, String cursor) { if (object == null) { Dom.setStyleAttribute(getRootElement(), "cursor", cursor); // depends on control dependency: [if], data = [none] } else { Element element = getGroup(object); if (element != null) { Dom.setStyleAttribute(element, "cursor", cursor); // depends on control dependency: [if], data = [(element] } } } }
public class class_name { private void completeMultipart(String bucketName, String objectName, String uploadId, Part[] parts) throws InvalidBucketNameException, NoSuchAlgorithmException, InsufficientDataException, IOException, InvalidKeyException, NoResponseException, XmlPullParserException, ErrorResponseException, InternalException { Map<String,String> queryParamMap = new HashMap<>(); queryParamMap.put(UPLOAD_ID, uploadId); CompleteMultipartUpload completeManifest = new CompleteMultipartUpload(parts); HttpResponse response = executePost(bucketName, objectName, null, queryParamMap, completeManifest); // Fixing issue https://github.com/minio/minio-java/issues/391 String bodyContent = ""; Scanner scanner = new Scanner(response.body().charStream()); try { // read entire body stream to string. scanner.useDelimiter("\\A"); if (scanner.hasNext()) { bodyContent = scanner.next(); } } finally { response.body().close(); scanner.close(); } bodyContent = bodyContent.trim(); if (!bodyContent.isEmpty()) { ErrorResponse errorResponse = new ErrorResponse(new StringReader(bodyContent)); if (errorResponse.code() != null) { throw new ErrorResponseException(errorResponse, response.response()); } } } }
public class class_name { private void completeMultipart(String bucketName, String objectName, String uploadId, Part[] parts) throws InvalidBucketNameException, NoSuchAlgorithmException, InsufficientDataException, IOException, InvalidKeyException, NoResponseException, XmlPullParserException, ErrorResponseException, InternalException { Map<String,String> queryParamMap = new HashMap<>(); queryParamMap.put(UPLOAD_ID, uploadId); CompleteMultipartUpload completeManifest = new CompleteMultipartUpload(parts); HttpResponse response = executePost(bucketName, objectName, null, queryParamMap, completeManifest); // Fixing issue https://github.com/minio/minio-java/issues/391 String bodyContent = ""; Scanner scanner = new Scanner(response.body().charStream()); try { // read entire body stream to string. scanner.useDelimiter("\\A"); if (scanner.hasNext()) { bodyContent = scanner.next(); // depends on control dependency: [if], data = [none] } } finally { response.body().close(); scanner.close(); } bodyContent = bodyContent.trim(); if (!bodyContent.isEmpty()) { ErrorResponse errorResponse = new ErrorResponse(new StringReader(bodyContent)); if (errorResponse.code() != null) { throw new ErrorResponseException(errorResponse, response.response()); } } } }
public class class_name { public Map<String, Double> getFMeasureForLabels() { Map<String, Double> fMeasure = new LinkedHashMap<>(); Map<String, Double> precisionForLabels = getPrecisionForLabels(); Map<String, Double> recallForLabels = getRecallForLabels(); for (String label : allGoldLabels) { double p = precisionForLabels.get(label); double r = recallForLabels.get(label); double fm = 0; if ((p + r) > 0) { fm = (2 * p * r) / (p + r); } fMeasure.put(label, fm); } return fMeasure; } }
public class class_name { public Map<String, Double> getFMeasureForLabels() { Map<String, Double> fMeasure = new LinkedHashMap<>(); Map<String, Double> precisionForLabels = getPrecisionForLabels(); Map<String, Double> recallForLabels = getRecallForLabels(); for (String label : allGoldLabels) { double p = precisionForLabels.get(label); double r = recallForLabels.get(label); double fm = 0; if ((p + r) > 0) { fm = (2 * p * r) / (p + r); // depends on control dependency: [if], data = [none] } fMeasure.put(label, fm); // depends on control dependency: [for], data = [label] } return fMeasure; } }
public class class_name { public void findMatchingSelectorSubs(String theTopic, Set consumerSet) throws SIDiscriminatorSyntaxException { if (tc.isEntryEnabled()) SibTr.entry( tc, "findMatchingSelectorSubs", new Object[] { theTopic}); // We can string match against consumers with fully qualified discriminators findMatchingExactSelectorSubs(theTopic, consumerSet); // Use MatchSpace direct evaluation code once we've isolated candidate // expressions through string matching if(_areWildcardSelectorSubs) { // Iterate through the map Iterator i = _wildcardSelectorSubs.keySet().iterator(); while (i.hasNext()) { String consumerTopic = (String)i.next(); // Retrieve the non-wildcarded stem String stem = _mpm.retrieveNonWildcardStem(consumerTopic); if (tc.isDebugEnabled()) SibTr.debug(tc, "Found consumer topic: " + consumerTopic + "with stem: " + stem); // Add candidates to the list if(theTopic.startsWith(stem)) { if (tc.isDebugEnabled()) SibTr.debug(tc, "Drive direct evaluation for topic: " + consumerTopic); if(_mpm.evaluateDiscriminator(theTopic,consumerTopic)) { ArrayList consumerList = (ArrayList)_wildcardSelectorSubs.get(consumerTopic); if (tc.isDebugEnabled()) SibTr.debug(tc, "Add members of list to set"); consumerSet.addAll(consumerList); } } } } if (tc.isEntryEnabled()) SibTr.exit(tc, "findMatchingSelectorSubs"); } }
public class class_name { public void findMatchingSelectorSubs(String theTopic, Set consumerSet) throws SIDiscriminatorSyntaxException { if (tc.isEntryEnabled()) SibTr.entry( tc, "findMatchingSelectorSubs", new Object[] { theTopic}); // We can string match against consumers with fully qualified discriminators findMatchingExactSelectorSubs(theTopic, consumerSet); // Use MatchSpace direct evaluation code once we've isolated candidate // expressions through string matching if(_areWildcardSelectorSubs) { // Iterate through the map Iterator i = _wildcardSelectorSubs.keySet().iterator(); while (i.hasNext()) { String consumerTopic = (String)i.next(); // Retrieve the non-wildcarded stem String stem = _mpm.retrieveNonWildcardStem(consumerTopic); if (tc.isDebugEnabled()) SibTr.debug(tc, "Found consumer topic: " + consumerTopic + "with stem: " + stem); // Add candidates to the list if(theTopic.startsWith(stem)) { if (tc.isDebugEnabled()) SibTr.debug(tc, "Drive direct evaluation for topic: " + consumerTopic); if(_mpm.evaluateDiscriminator(theTopic,consumerTopic)) { ArrayList consumerList = (ArrayList)_wildcardSelectorSubs.get(consumerTopic); if (tc.isDebugEnabled()) SibTr.debug(tc, "Add members of list to set"); consumerSet.addAll(consumerList); // depends on control dependency: [if], data = [none] } } } } if (tc.isEntryEnabled()) SibTr.exit(tc, "findMatchingSelectorSubs"); } }
public class class_name { public static void logThreads( final Logger logger, final Level level, final String prefix, final String threadPrefix, final String stackElementPrefix) { if (logger.isLoggable(level)) { logger.log(level, getFormattedThreadList(prefix, threadPrefix, stackElementPrefix)); } } }
public class class_name { public static void logThreads( final Logger logger, final Level level, final String prefix, final String threadPrefix, final String stackElementPrefix) { if (logger.isLoggable(level)) { logger.log(level, getFormattedThreadList(prefix, threadPrefix, stackElementPrefix)); // depends on control dependency: [if], data = [none] } } }
public class class_name { @SuppressWarnings({"unchecked", "checkstyle:cyclomaticcomplexity", "checkstyle:npathcomplexity", "checkstyle:nestedifdepth"}) private static <P extends GISPrimitive, N extends AbstractGISTreeSetNode<P, N>> boolean addInside(AbstractGISTreeSet<P, N> tree, N insertionNode, P element, GISTreeSetNodeFactory<P, N> builder, boolean enableRearrange) { if (element == null) { return false; } final GeoLocation location = element.getGeoLocation(); if (location == null) { return false; } N insNode = insertionNode; if (insNode == null) { insNode = tree.getTree().getRoot(); // The insertion node is the root. if (insNode == null) { if (tree.worldBounds == null) { insNode = builder.newRootNode(element); } else { insNode = builder.newRootNode( element, tree.worldBounds.getMinX(), tree.worldBounds.getMinY(), tree.worldBounds.getWidth(), tree.worldBounds.getHeight()); } tree.getTree().setRoot(insNode); tree.updateComponentType(element); return true; } } // Go through the tree to retreive the leaf where to put the element final boolean isRearrangable = enableRearrange && tree.worldBounds == null; while (insNode != null) { if (insNode.isLeaf()) { // The node is a leaf. Add the element inside the node only if // the splitting count is not reached. Otherwise split this node if (insNode.getUserDataCount() >= GISTreeSetConstants.SPLIT_COUNT) { if (isRearrangable && isOutsideNodeBuildingBounds(insNode, location.toBounds2D())) { if (!insNode.addUserData(element)) { return false; } // Make the building bounds of the node larger rearrangeTree(tree, insNode, union(insNode, location.toBounds2D()), builder); } else { // Split the node int classification; final int count = insNode.getChildCount(); // Prepare the list of elements for each child GeoLocation dataLocation; final List<P>[] collections = (List<P>[]) Array.newInstance(List.class, count); int subBranchCount = 0; // compute the positions of the data for (final P data : insNode.getAllUserData()) { dataLocation = data.getGeoLocation(); classification = GISTreeSetUtil.classifies(insNode, dataLocation); if (collections[classification] == null) { collections[classification] = new LinkedList<>(); ++subBranchCount; } collections[classification].add(data); } classification = GISTreeSetUtil.classifies(insNode, location); if (collections[classification] == null) { collections[classification] = new LinkedList<>(); ++subBranchCount; } collections[classification].add(element); // save the data into the children if (subBranchCount > 1) { for (int region = 0; region < count; ++region) { if (collections[region] != null) { final N newNode = createNode(insNode, IcosepQuadTreeZone.values()[region], builder); assert newNode != null; if (!newNode.addUserData(collections[region])) { return false; } if (!insNode.setChildAt(region, newNode)) { return false; } } } insNode.removeAllUserData(); } else if (subBranchCount == 1) { insNode.addUserData(element); } } insNode = null; } else { // Insert inside this node, and stop the loop on the tree nodes if (!insNode.addUserData(element)) { return false; } if (isRearrangable && isOutsideNodeBuildingBounds(insNode, location.toBounds2D())) { // Make the building bounds of the node larger rearrangeTree(tree, insNode, union(insNode, location.toBounds2D()), builder); } insNode = null; } } else { // The node is not a leaf. Insert the element inside one of the subtrees final int region = classifies(insNode, location); final N child = insNode.getChildAt(region); if (child == null) { final N newNode = createNode(insNode, IcosepQuadTreeZone.values()[region], builder); insNode.setChildAt(region, newNode); insNode = newNode; } else { insNode = child; } } } tree.updateComponentType(element); return true; } }
public class class_name { @SuppressWarnings({"unchecked", "checkstyle:cyclomaticcomplexity", "checkstyle:npathcomplexity", "checkstyle:nestedifdepth"}) private static <P extends GISPrimitive, N extends AbstractGISTreeSetNode<P, N>> boolean addInside(AbstractGISTreeSet<P, N> tree, N insertionNode, P element, GISTreeSetNodeFactory<P, N> builder, boolean enableRearrange) { if (element == null) { return false; // depends on control dependency: [if], data = [none] } final GeoLocation location = element.getGeoLocation(); if (location == null) { return false; // depends on control dependency: [if], data = [none] } N insNode = insertionNode; if (insNode == null) { insNode = tree.getTree().getRoot(); // depends on control dependency: [if], data = [none] // The insertion node is the root. if (insNode == null) { if (tree.worldBounds == null) { insNode = builder.newRootNode(element); // depends on control dependency: [if], data = [none] } else { insNode = builder.newRootNode( element, tree.worldBounds.getMinX(), tree.worldBounds.getMinY(), tree.worldBounds.getWidth(), tree.worldBounds.getHeight()); // depends on control dependency: [if], data = [none] } tree.getTree().setRoot(insNode); // depends on control dependency: [if], data = [(insNode] tree.updateComponentType(element); // depends on control dependency: [if], data = [none] return true; // depends on control dependency: [if], data = [none] } } // Go through the tree to retreive the leaf where to put the element final boolean isRearrangable = enableRearrange && tree.worldBounds == null; while (insNode != null) { if (insNode.isLeaf()) { // The node is a leaf. Add the element inside the node only if // the splitting count is not reached. Otherwise split this node if (insNode.getUserDataCount() >= GISTreeSetConstants.SPLIT_COUNT) { if (isRearrangable && isOutsideNodeBuildingBounds(insNode, location.toBounds2D())) { if (!insNode.addUserData(element)) { return false; // depends on control dependency: [if], data = [none] } // Make the building bounds of the node larger rearrangeTree(tree, insNode, union(insNode, location.toBounds2D()), builder); // depends on control dependency: [if], data = [none] } else { // Split the node int classification; final int count = insNode.getChildCount(); // Prepare the list of elements for each child GeoLocation dataLocation; final List<P>[] collections = (List<P>[]) Array.newInstance(List.class, count); int subBranchCount = 0; // compute the positions of the data for (final P data : insNode.getAllUserData()) { dataLocation = data.getGeoLocation(); // depends on control dependency: [for], data = [data] classification = GISTreeSetUtil.classifies(insNode, dataLocation); // depends on control dependency: [for], data = [data] if (collections[classification] == null) { collections[classification] = new LinkedList<>(); // depends on control dependency: [if], data = [none] ++subBranchCount; // depends on control dependency: [if], data = [none] } collections[classification].add(data); // depends on control dependency: [for], data = [data] } classification = GISTreeSetUtil.classifies(insNode, location); // depends on control dependency: [if], data = [none] if (collections[classification] == null) { collections[classification] = new LinkedList<>(); // depends on control dependency: [if], data = [none] ++subBranchCount; // depends on control dependency: [if], data = [none] } collections[classification].add(element); // depends on control dependency: [if], data = [none] // save the data into the children if (subBranchCount > 1) { for (int region = 0; region < count; ++region) { if (collections[region] != null) { final N newNode = createNode(insNode, IcosepQuadTreeZone.values()[region], builder); assert newNode != null; if (!newNode.addUserData(collections[region])) { return false; // depends on control dependency: [if], data = [none] } if (!insNode.setChildAt(region, newNode)) { return false; // depends on control dependency: [if], data = [none] } } } insNode.removeAllUserData(); // depends on control dependency: [if], data = [none] } else if (subBranchCount == 1) { insNode.addUserData(element); // depends on control dependency: [if], data = [none] } } insNode = null; // depends on control dependency: [if], data = [none] } else { // Insert inside this node, and stop the loop on the tree nodes if (!insNode.addUserData(element)) { return false; // depends on control dependency: [if], data = [none] } if (isRearrangable && isOutsideNodeBuildingBounds(insNode, location.toBounds2D())) { // Make the building bounds of the node larger rearrangeTree(tree, insNode, union(insNode, location.toBounds2D()), builder); // depends on control dependency: [if], data = [none] } insNode = null; // depends on control dependency: [if], data = [none] } } else { // The node is not a leaf. Insert the element inside one of the subtrees final int region = classifies(insNode, location); final N child = insNode.getChildAt(region); if (child == null) { final N newNode = createNode(insNode, IcosepQuadTreeZone.values()[region], builder); insNode.setChildAt(region, newNode); // depends on control dependency: [if], data = [none] insNode = newNode; // depends on control dependency: [if], data = [none] } else { insNode = child; // depends on control dependency: [if], data = [none] } } } tree.updateComponentType(element); return true; } }
public class class_name { public CloudhopperBuilder password(String... password) { for (String p : password) { if (p != null) { passwords.add(p); } } return this; } }
public class class_name { public CloudhopperBuilder password(String... password) { for (String p : password) { if (p != null) { passwords.add(p); // depends on control dependency: [if], data = [(p] } } return this; } }
public class class_name { @Nonnull @ReturnsMutableCopy public static ICommonsList <IHCNode> getMergedInlineCSSAndJSNodes (@Nonnull final Iterable <? extends IHCNode> aNodes, @Nullable final IHCOnDocumentReadyProvider aOnDocumentReadyProvider) { ValueEnforcer.notNull (aNodes, "Nodes"); // Apply all modifiers final Iterable <? extends IHCNode> aRealSpecialNodes = applyModifiers (aNodes); // Do standard aggregations of CSS and JS final ICommonsList <IHCNode> ret = new CommonsArrayList<> (); final CollectingJSCodeProvider aJSOnDocumentReadyBefore = new CollectingJSCodeProvider (); final CollectingJSCodeProvider aJSOnDocumentReadyAfter = new CollectingJSCodeProvider (); final CollectingJSCodeProvider aJSInlineBefore = new CollectingJSCodeProvider (); final CollectingJSCodeProvider aJSInlineAfter = new CollectingJSCodeProvider (); final InlineCSSList aCSSInlineBefore = new InlineCSSList (); final InlineCSSList aCSSInlineAfter = new InlineCSSList (); for (final IHCNode aNode : aRealSpecialNodes) { // Note: do not unwrap the node, because it is not allowed to merge JS/CSS // with a conditional comment with JS/CSS without a conditional comment! if (HCJSNodeDetector.isDirectJSInlineNode (aNode)) { // Check HCScriptInlineOnDocumentReady first, because it is a subclass // of IHCScriptInline if (aNode instanceof HCScriptInlineOnDocumentReady) { // Inline JS final HCScriptInlineOnDocumentReady aScript = (HCScriptInlineOnDocumentReady) aNode; (aScript.isEmitAfterFiles () ? aJSOnDocumentReadyAfter : aJSOnDocumentReadyBefore).appendFlattened (aScript.getOnDocumentReadyCode ()); } else { // Inline JS final IHCScriptInline <?> aScript = (IHCScriptInline <?>) aNode; (aScript.isEmitAfterFiles () ? aJSInlineAfter : aJSInlineBefore).appendFlattened (aScript.getJSCodeProvider ()); } } else if (HCCSSNodeDetector.isDirectCSSInlineNode (aNode)) { // Inline CSS final HCStyle aStyle = (HCStyle) aNode; (aStyle.isEmitAfterFiles () ? aCSSInlineAfter : aCSSInlineBefore).addInlineCSS (aStyle.getMedia (), aStyle.getStyleContent ()); } else { // HCLink // HCScriptFile // HCConditionalCommentNode if (!(aNode instanceof HCLink) && !(aNode instanceof HCScriptFile) && !(aNode instanceof IHCConditionalCommentNode)) LOGGER.warn ("Found unexpected node to merge inline CSS/JS: " + aNode); // Add always! // These nodes are either file based nodes ot conditional comment // nodes ret.add (aNode); } } // on-document-ready JS always as last inline JS! if (!aJSOnDocumentReadyBefore.isEmpty ()) if (aOnDocumentReadyProvider != null) aJSInlineBefore.append (aOnDocumentReadyProvider.createOnDocumentReady (aJSOnDocumentReadyBefore)); else aJSInlineBefore.append (aJSOnDocumentReadyBefore); if (!aJSOnDocumentReadyAfter.isEmpty ()) if (aOnDocumentReadyProvider != null) aJSInlineAfter.append (aOnDocumentReadyProvider.createOnDocumentReady (aJSOnDocumentReadyAfter)); else aJSInlineAfter.append (aJSOnDocumentReadyAfter); // Finally add the inline JS if (!aJSInlineBefore.isEmpty ()) { // Add at the beginning final HCScriptInline aScript = new HCScriptInline (aJSInlineBefore).setEmitAfterFiles (false); aScript.internalSetNodeState (EHCNodeState.RESOURCES_REGISTERED); ret.add (0, aScript); } if (!aJSInlineAfter.isEmpty ()) { // Add at the end final HCScriptInline aScript = new HCScriptInline (aJSInlineAfter).setEmitAfterFiles (true); aScript.internalSetNodeState (EHCNodeState.RESOURCES_REGISTERED); ret.add (aScript); } // Add all merged inline CSSs grouped by their media list if (aCSSInlineBefore.isNotEmpty ()) { // Add at the beginning int nIndex = 0; for (final ICSSCodeProvider aEntry : aCSSInlineBefore.getAll ()) { final HCStyle aStyle = new HCStyle (aEntry.getCSSCode ()).setMedia (aEntry.getMediaList ()) .setEmitAfterFiles (false); aStyle.internalSetNodeState (EHCNodeState.RESOURCES_REGISTERED); ret.add (nIndex, aStyle); ++nIndex; } } if (aCSSInlineAfter.isNotEmpty ()) { // Add at the end for (final ICSSCodeProvider aEntry : aCSSInlineAfter.getAll ()) { final HCStyle aStyle = new HCStyle (aEntry.getCSSCode ()).setMedia (aEntry.getMediaList ()) .setEmitAfterFiles (true); aStyle.internalSetNodeState (EHCNodeState.RESOURCES_REGISTERED); ret.add (aStyle); } } return ret; } }
public class class_name { @Nonnull @ReturnsMutableCopy public static ICommonsList <IHCNode> getMergedInlineCSSAndJSNodes (@Nonnull final Iterable <? extends IHCNode> aNodes, @Nullable final IHCOnDocumentReadyProvider aOnDocumentReadyProvider) { ValueEnforcer.notNull (aNodes, "Nodes"); // Apply all modifiers final Iterable <? extends IHCNode> aRealSpecialNodes = applyModifiers (aNodes); // Do standard aggregations of CSS and JS final ICommonsList <IHCNode> ret = new CommonsArrayList<> (); final CollectingJSCodeProvider aJSOnDocumentReadyBefore = new CollectingJSCodeProvider (); final CollectingJSCodeProvider aJSOnDocumentReadyAfter = new CollectingJSCodeProvider (); final CollectingJSCodeProvider aJSInlineBefore = new CollectingJSCodeProvider (); final CollectingJSCodeProvider aJSInlineAfter = new CollectingJSCodeProvider (); final InlineCSSList aCSSInlineBefore = new InlineCSSList (); final InlineCSSList aCSSInlineAfter = new InlineCSSList (); for (final IHCNode aNode : aRealSpecialNodes) { // Note: do not unwrap the node, because it is not allowed to merge JS/CSS // with a conditional comment with JS/CSS without a conditional comment! if (HCJSNodeDetector.isDirectJSInlineNode (aNode)) { // Check HCScriptInlineOnDocumentReady first, because it is a subclass // of IHCScriptInline if (aNode instanceof HCScriptInlineOnDocumentReady) { // Inline JS final HCScriptInlineOnDocumentReady aScript = (HCScriptInlineOnDocumentReady) aNode; (aScript.isEmitAfterFiles () ? aJSOnDocumentReadyAfter : aJSOnDocumentReadyBefore).appendFlattened (aScript.getOnDocumentReadyCode ()); // depends on control dependency: [if], data = [none] } else { // Inline JS final IHCScriptInline <?> aScript = (IHCScriptInline <?>) aNode; (aScript.isEmitAfterFiles () ? aJSInlineAfter : aJSInlineBefore).appendFlattened (aScript.getJSCodeProvider ()); // depends on control dependency: [if], data = [none] } } else if (HCCSSNodeDetector.isDirectCSSInlineNode (aNode)) { // Inline CSS final HCStyle aStyle = (HCStyle) aNode; (aStyle.isEmitAfterFiles () ? aCSSInlineAfter : aCSSInlineBefore).addInlineCSS (aStyle.getMedia (), aStyle.getStyleContent ()); // depends on control dependency: [if], data = [none] } else { // HCLink // HCScriptFile // HCConditionalCommentNode if (!(aNode instanceof HCLink) && !(aNode instanceof HCScriptFile) && !(aNode instanceof IHCConditionalCommentNode)) LOGGER.warn ("Found unexpected node to merge inline CSS/JS: " + aNode); // Add always! // These nodes are either file based nodes ot conditional comment // nodes ret.add (aNode); // depends on control dependency: [if], data = [none] } } // on-document-ready JS always as last inline JS! if (!aJSOnDocumentReadyBefore.isEmpty ()) if (aOnDocumentReadyProvider != null) aJSInlineBefore.append (aOnDocumentReadyProvider.createOnDocumentReady (aJSOnDocumentReadyBefore)); else aJSInlineBefore.append (aJSOnDocumentReadyBefore); if (!aJSOnDocumentReadyAfter.isEmpty ()) if (aOnDocumentReadyProvider != null) aJSInlineAfter.append (aOnDocumentReadyProvider.createOnDocumentReady (aJSOnDocumentReadyAfter)); else aJSInlineAfter.append (aJSOnDocumentReadyAfter); // Finally add the inline JS if (!aJSInlineBefore.isEmpty ()) { // Add at the beginning final HCScriptInline aScript = new HCScriptInline (aJSInlineBefore).setEmitAfterFiles (false); aScript.internalSetNodeState (EHCNodeState.RESOURCES_REGISTERED); // depends on control dependency: [if], data = [none] ret.add (0, aScript); // depends on control dependency: [if], data = [none] } if (!aJSInlineAfter.isEmpty ()) { // Add at the end final HCScriptInline aScript = new HCScriptInline (aJSInlineAfter).setEmitAfterFiles (true); aScript.internalSetNodeState (EHCNodeState.RESOURCES_REGISTERED); // depends on control dependency: [if], data = [none] ret.add (aScript); // depends on control dependency: [if], data = [none] } // Add all merged inline CSSs grouped by their media list if (aCSSInlineBefore.isNotEmpty ()) { // Add at the beginning int nIndex = 0; for (final ICSSCodeProvider aEntry : aCSSInlineBefore.getAll ()) { final HCStyle aStyle = new HCStyle (aEntry.getCSSCode ()).setMedia (aEntry.getMediaList ()) .setEmitAfterFiles (false); aStyle.internalSetNodeState (EHCNodeState.RESOURCES_REGISTERED); // depends on control dependency: [for], data = [none] ret.add (nIndex, aStyle); // depends on control dependency: [for], data = [none] ++nIndex; // depends on control dependency: [for], data = [none] } } if (aCSSInlineAfter.isNotEmpty ()) { // Add at the end for (final ICSSCodeProvider aEntry : aCSSInlineAfter.getAll ()) { final HCStyle aStyle = new HCStyle (aEntry.getCSSCode ()).setMedia (aEntry.getMediaList ()) .setEmitAfterFiles (true); aStyle.internalSetNodeState (EHCNodeState.RESOURCES_REGISTERED); // depends on control dependency: [for], data = [none] ret.add (aStyle); // depends on control dependency: [for], data = [none] } } return ret; } }
public class class_name { public synchronized void deregister(String id) { assert !(Thread.currentThread() instanceof PartitionOperationThread); if (!id2InterceptorMap.containsKey(id)) { return; } Map<String, MapInterceptor> tmpMap = new HashMap<>(id2InterceptorMap); MapInterceptor removedInterceptor = tmpMap.remove(id); id2InterceptorMap = unmodifiableMap(tmpMap); List<MapInterceptor> tmpInterceptors = new ArrayList<>(interceptors); tmpInterceptors.remove(removedInterceptor); interceptors = unmodifiableList(tmpInterceptors); } }
public class class_name { public synchronized void deregister(String id) { assert !(Thread.currentThread() instanceof PartitionOperationThread); if (!id2InterceptorMap.containsKey(id)) { return; // depends on control dependency: [if], data = [none] } Map<String, MapInterceptor> tmpMap = new HashMap<>(id2InterceptorMap); MapInterceptor removedInterceptor = tmpMap.remove(id); id2InterceptorMap = unmodifiableMap(tmpMap); List<MapInterceptor> tmpInterceptors = new ArrayList<>(interceptors); tmpInterceptors.remove(removedInterceptor); interceptors = unmodifiableList(tmpInterceptors); } }
public class class_name { private JTree getTreeParam() { if (treeParam == null) { treeParam = new JTree(); treeParam.setModel(getTreeModel()); treeParam.setShowsRootHandles(true); treeParam.setRootVisible(true); treeParam.addTreeSelectionListener(new javax.swing.event.TreeSelectionListener() { @Override public void valueChanged(javax.swing.event.TreeSelectionEvent e) { DefaultMutableTreeNode node = (DefaultMutableTreeNode) getTreeParam().getLastSelectedPathComponent(); if (node == null) { return; } String name = (String) node.getUserObject(); showParamPanel(name); } }); DefaultTreeCellRenderer renderer = new DefaultTreeCellRenderer(); renderer.setLeafIcon(null); renderer.setOpenIcon(null); renderer.setClosedIcon(null); treeParam.setCellRenderer(renderer); treeParam.setRowHeight(DisplayUtils.getScaledSize(18)); treeParam.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { TreePath path = treeParam.getClosestPathForLocation(e.getX(), e.getY()); if (path != null && !treeParam.isPathSelected(path)) { treeParam.setSelectionPath(path); } } }); } return treeParam; } }
public class class_name { private JTree getTreeParam() { if (treeParam == null) { treeParam = new JTree(); // depends on control dependency: [if], data = [none] treeParam.setModel(getTreeModel()); // depends on control dependency: [if], data = [none] treeParam.setShowsRootHandles(true); // depends on control dependency: [if], data = [none] treeParam.setRootVisible(true); // depends on control dependency: [if], data = [none] treeParam.addTreeSelectionListener(new javax.swing.event.TreeSelectionListener() { @Override public void valueChanged(javax.swing.event.TreeSelectionEvent e) { DefaultMutableTreeNode node = (DefaultMutableTreeNode) getTreeParam().getLastSelectedPathComponent(); if (node == null) { return; // depends on control dependency: [if], data = [none] } String name = (String) node.getUserObject(); showParamPanel(name); } }); // depends on control dependency: [if], data = [none] DefaultTreeCellRenderer renderer = new DefaultTreeCellRenderer(); renderer.setLeafIcon(null); // depends on control dependency: [if], data = [null)] renderer.setOpenIcon(null); // depends on control dependency: [if], data = [null)] renderer.setClosedIcon(null); // depends on control dependency: [if], data = [null)] treeParam.setCellRenderer(renderer); // depends on control dependency: [if], data = [none] treeParam.setRowHeight(DisplayUtils.getScaledSize(18)); // depends on control dependency: [if], data = [none] treeParam.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { TreePath path = treeParam.getClosestPathForLocation(e.getX(), e.getY()); if (path != null && !treeParam.isPathSelected(path)) { treeParam.setSelectionPath(path); // depends on control dependency: [if], data = [(path] } } }); // depends on control dependency: [if], data = [none] } return treeParam; } }
public class class_name { private List<double[]> calculateMeanMeasurementsForParam( int numEntriesPerPreview, int numParamValues, int paramValue) { List<double[]> paramMeasurementsSum = new ArrayList<double[]>(numEntriesPerPreview); List<double[]> meanParamMeasurements = new ArrayList<double[]>(numEntriesPerPreview); int numCompleteFolds = 0; // sum up measurement values for (PreviewCollection<Preview> foldPreview : this.origMultiRunPreviews.subPreviews) { // check if there is a preview for each parameter value if (foldPreview.getPreviews().size() == numParamValues) { numCompleteFolds++; Preview foldParamPreview = foldPreview.getPreviews().get(paramValue); // add this Preview's measurements to the overall sum this.addPreviewMeasurementsToSum( paramMeasurementsSum, foldParamPreview, numEntriesPerPreview); } } // divide sum by number of folds for (int entryIdx = 0; entryIdx < numEntriesPerPreview; entryIdx++) { double[] sumEntry = paramMeasurementsSum.get(entryIdx); double[] meanEntry = new double[sumEntry.length]; // first measurement is used for indexing -> simply copy meanEntry[0] = sumEntry[0]; // calculate mean for remaining measurements for (int m = 1; m < sumEntry.length; m++) { meanEntry[m] = sumEntry[m] / numCompleteFolds; } meanParamMeasurements.add(meanEntry); } return meanParamMeasurements; } }
public class class_name { private List<double[]> calculateMeanMeasurementsForParam( int numEntriesPerPreview, int numParamValues, int paramValue) { List<double[]> paramMeasurementsSum = new ArrayList<double[]>(numEntriesPerPreview); List<double[]> meanParamMeasurements = new ArrayList<double[]>(numEntriesPerPreview); int numCompleteFolds = 0; // sum up measurement values for (PreviewCollection<Preview> foldPreview : this.origMultiRunPreviews.subPreviews) { // check if there is a preview for each parameter value if (foldPreview.getPreviews().size() == numParamValues) { numCompleteFolds++; // depends on control dependency: [if], data = [none] Preview foldParamPreview = foldPreview.getPreviews().get(paramValue); // add this Preview's measurements to the overall sum this.addPreviewMeasurementsToSum( paramMeasurementsSum, foldParamPreview, numEntriesPerPreview); // depends on control dependency: [if], data = [none] } } // divide sum by number of folds for (int entryIdx = 0; entryIdx < numEntriesPerPreview; entryIdx++) { double[] sumEntry = paramMeasurementsSum.get(entryIdx); double[] meanEntry = new double[sumEntry.length]; // first measurement is used for indexing -> simply copy meanEntry[0] = sumEntry[0]; // depends on control dependency: [for], data = [none] // calculate mean for remaining measurements for (int m = 1; m < sumEntry.length; m++) { meanEntry[m] = sumEntry[m] / numCompleteFolds; // depends on control dependency: [for], data = [m] } meanParamMeasurements.add(meanEntry); // depends on control dependency: [for], data = [none] } return meanParamMeasurements; } }
public class class_name { public static BigDecimal durationNs(String durationP) { if (durationP == null) { return null; } String duration = durationP.trim(); if (duration.length() == 0) { return null; } int unitPos = 1; while (unitPos < duration.length() && (Character.isDigit(duration.charAt(unitPos)) || duration.charAt(unitPos) == '.')) { unitPos++; } if (unitPos >= duration.length()) { throw new IllegalArgumentException("Time unit not found in string: " + duration); } String tail = duration.substring(unitPos); Long multiplier = null; Integer unitEnd = null; for(int i=0; i<TIME_UNITS.length; i++) { if (tail.startsWith(TIME_UNITS[i])) { multiplier = UNIT_MULTIPLIERS[i]; unitEnd = unitPos + TIME_UNITS[i].length(); break; } } if (multiplier == null) { throw new IllegalArgumentException("Unknown time unit in string: " + duration); } BigDecimal value = new BigDecimal(duration.substring(0, unitPos)); value = value.multiply(BigDecimal.valueOf(multiplier)); String remaining = duration.substring(unitEnd); BigDecimal remainingValue = durationNs(remaining); if (remainingValue != null) { value = value.add(remainingValue); } return value; } }
public class class_name { public static BigDecimal durationNs(String durationP) { if (durationP == null) { return null; // depends on control dependency: [if], data = [none] } String duration = durationP.trim(); if (duration.length() == 0) { return null; // depends on control dependency: [if], data = [none] } int unitPos = 1; while (unitPos < duration.length() && (Character.isDigit(duration.charAt(unitPos)) || duration.charAt(unitPos) == '.')) { unitPos++; // depends on control dependency: [while], data = [none] } if (unitPos >= duration.length()) { throw new IllegalArgumentException("Time unit not found in string: " + duration); } String tail = duration.substring(unitPos); Long multiplier = null; Integer unitEnd = null; for(int i=0; i<TIME_UNITS.length; i++) { if (tail.startsWith(TIME_UNITS[i])) { multiplier = UNIT_MULTIPLIERS[i]; // depends on control dependency: [if], data = [none] unitEnd = unitPos + TIME_UNITS[i].length(); // depends on control dependency: [if], data = [none] break; } } if (multiplier == null) { throw new IllegalArgumentException("Unknown time unit in string: " + duration); } BigDecimal value = new BigDecimal(duration.substring(0, unitPos)); value = value.multiply(BigDecimal.valueOf(multiplier)); String remaining = duration.substring(unitEnd); BigDecimal remainingValue = durationNs(remaining); if (remainingValue != null) { value = value.add(remainingValue); // depends on control dependency: [if], data = [(remainingValue] } return value; } }
public class class_name { private GenericKieSessionMonitoringImpl getKnowledgeSessionBean(CBSKey cbsKey, KieRuntimeEventManager ksession) { if (mbeansRefs.get(cbsKey) != null) { return (GenericKieSessionMonitoringImpl) mbeansRefs.get(cbsKey); } else { if (ksession instanceof StatelessKnowledgeSession) { synchronized (mbeansRefs) { if (mbeansRefs.get(cbsKey) != null) { return (GenericKieSessionMonitoringImpl) mbeansRefs.get(cbsKey); } else { try { StatelessKieSessionMonitoringImpl mbean = new StatelessKieSessionMonitoringImpl( cbsKey.kcontainerId, cbsKey.kbaseId, cbsKey.ksessionName ); registerMBean( cbsKey, mbean, mbean.getName() ); mbeansRefs.put(cbsKey, mbean); return mbean; } catch ( Exception e ) { logger.error("Unable to instantiate and register StatelessKieSessionMonitoringMBean"); } return null; } } } else { synchronized (mbeansRefs) { if (mbeansRefs.get(cbsKey) != null) { return (GenericKieSessionMonitoringImpl) mbeansRefs.get(cbsKey); } else { try { KieSessionMonitoringImpl mbean = new KieSessionMonitoringImpl( cbsKey.kcontainerId, cbsKey.kbaseId, cbsKey.ksessionName ); registerMBean( cbsKey, mbean, mbean.getName() ); mbeansRefs.put(cbsKey, mbean); return mbean; } catch ( Exception e ) { logger.error("Unable to instantiate and register (stateful) KieSessionMonitoringMBean"); } return null; } } } } } }
public class class_name { private GenericKieSessionMonitoringImpl getKnowledgeSessionBean(CBSKey cbsKey, KieRuntimeEventManager ksession) { if (mbeansRefs.get(cbsKey) != null) { return (GenericKieSessionMonitoringImpl) mbeansRefs.get(cbsKey); // depends on control dependency: [if], data = [none] } else { if (ksession instanceof StatelessKnowledgeSession) { synchronized (mbeansRefs) { // depends on control dependency: [if], data = [none] if (mbeansRefs.get(cbsKey) != null) { return (GenericKieSessionMonitoringImpl) mbeansRefs.get(cbsKey); // depends on control dependency: [if], data = [none] } else { try { StatelessKieSessionMonitoringImpl mbean = new StatelessKieSessionMonitoringImpl( cbsKey.kcontainerId, cbsKey.kbaseId, cbsKey.ksessionName ); registerMBean( cbsKey, mbean, mbean.getName() ); // depends on control dependency: [try], data = [none] mbeansRefs.put(cbsKey, mbean); // depends on control dependency: [try], data = [none] return mbean; // depends on control dependency: [try], data = [none] } catch ( Exception e ) { logger.error("Unable to instantiate and register StatelessKieSessionMonitoringMBean"); } // depends on control dependency: [catch], data = [none] return null; // depends on control dependency: [if], data = [none] } } } else { synchronized (mbeansRefs) { // depends on control dependency: [if], data = [none] if (mbeansRefs.get(cbsKey) != null) { return (GenericKieSessionMonitoringImpl) mbeansRefs.get(cbsKey); // depends on control dependency: [if], data = [none] } else { try { KieSessionMonitoringImpl mbean = new KieSessionMonitoringImpl( cbsKey.kcontainerId, cbsKey.kbaseId, cbsKey.ksessionName ); registerMBean( cbsKey, mbean, mbean.getName() ); // depends on control dependency: [try], data = [none] mbeansRefs.put(cbsKey, mbean); // depends on control dependency: [try], data = [none] return mbean; // depends on control dependency: [try], data = [none] } catch ( Exception e ) { logger.error("Unable to instantiate and register (stateful) KieSessionMonitoringMBean"); } // depends on control dependency: [catch], data = [none] return null; // depends on control dependency: [if], data = [none] } } } } } }
public class class_name { public void callArgVisitors(XPathVisitor visitor) { for (int i = 0; i < m_argVec.size(); i++) { Expression exp = (Expression)m_argVec.elementAt(i); exp.callVisitors(new ArgExtOwner(exp), visitor); } } }
public class class_name { public void callArgVisitors(XPathVisitor visitor) { for (int i = 0; i < m_argVec.size(); i++) { Expression exp = (Expression)m_argVec.elementAt(i); exp.callVisitors(new ArgExtOwner(exp), visitor); // depends on control dependency: [for], data = [none] } } }
public class class_name { public static boolean shouldAutoCastTo(PrimitiveType from, PrimitiveType to) { InternalType[] castTypes = POSSIBLE_CAST_MAP.get(from); if (castTypes != null) { for (InternalType type : POSSIBLE_CAST_MAP.get(from)) { if (type.equals(to)) { return true; } } } return false; } }
public class class_name { public static boolean shouldAutoCastTo(PrimitiveType from, PrimitiveType to) { InternalType[] castTypes = POSSIBLE_CAST_MAP.get(from); if (castTypes != null) { for (InternalType type : POSSIBLE_CAST_MAP.get(from)) { if (type.equals(to)) { return true; // depends on control dependency: [if], data = [none] } } } return false; } }
public class class_name { @Override public StringBuffer format(double number, StringBuffer toAppendTo, FieldPosition ignore) { // this is one of the inherited format() methods. Since it doesn't // have a way to select the rule set to use, it just uses the // default one // Note, the BigInteger/BigDecimal methods below currently go through this. if (toAppendTo.length() == 0) { toAppendTo.append(adjustForContext(format(number, defaultRuleSet))); } else { // appending to other text, don't capitalize toAppendTo.append(format(number, defaultRuleSet)); } return toAppendTo; } }
public class class_name { @Override public StringBuffer format(double number, StringBuffer toAppendTo, FieldPosition ignore) { // this is one of the inherited format() methods. Since it doesn't // have a way to select the rule set to use, it just uses the // default one // Note, the BigInteger/BigDecimal methods below currently go through this. if (toAppendTo.length() == 0) { toAppendTo.append(adjustForContext(format(number, defaultRuleSet))); // depends on control dependency: [if], data = [none] } else { // appending to other text, don't capitalize toAppendTo.append(format(number, defaultRuleSet)); // depends on control dependency: [if], data = [none] } return toAppendTo; } }
public class class_name { protected String getConfig(IConfigKey key) { if (configs == null) { loadConfigs(); } String value = configs.getProperty(key.getKeyString()); if (value == null && key instanceof IConfigKeyHaveDefault) { return ((IConfigKeyHaveDefault) key).getDefaultValueStr(); } return value; } }
public class class_name { protected String getConfig(IConfigKey key) { if (configs == null) { loadConfigs(); // depends on control dependency: [if], data = [none] } String value = configs.getProperty(key.getKeyString()); if (value == null && key instanceof IConfigKeyHaveDefault) { return ((IConfigKeyHaveDefault) key).getDefaultValueStr(); // depends on control dependency: [if], data = [none] } return value; } }
public class class_name { private void setVectorLayerOnWhichSearchIsHappeningVisible() { if (searchPanel.getFeatureSearchVectorLayer() != null && !searchPanel.getFeatureSearchVectorLayer().isVisible()) { searchPanel.getFeatureSearchVectorLayer().setVisible(true); } } }
public class class_name { private void setVectorLayerOnWhichSearchIsHappeningVisible() { if (searchPanel.getFeatureSearchVectorLayer() != null && !searchPanel.getFeatureSearchVectorLayer().isVisible()) { searchPanel.getFeatureSearchVectorLayer().setVisible(true); // depends on control dependency: [if], data = [none] } } }
public class class_name { public static void mv(File src, File dst) throws IOException { Parameters.checkNotNull(dst); if (!src.equals(dst)) { cp(src, dst); try { rm(src); } catch (IOException e) { rm(dst); throw new IOException("Can't move " + src, e); } } } }
public class class_name { public static void mv(File src, File dst) throws IOException { Parameters.checkNotNull(dst); if (!src.equals(dst)) { cp(src, dst); try { rm(src); // depends on control dependency: [try], data = [none] } catch (IOException e) { rm(dst); throw new IOException("Can't move " + src, e); } // depends on control dependency: [catch], data = [none] } } }
public class class_name { public int unpackBinaryHeader() throws IOException { byte b = readByte(); if (Code.isFixedRaw(b)) { // FixRaw return b & 0x1f; } int len = tryReadBinaryHeader(b); if (len >= 0) { return len; } if (allowReadingStringAsBinary) { len = tryReadStringHeader(b); if (len >= 0) { return len; } } throw unexpected("Binary", b); } }
public class class_name { public int unpackBinaryHeader() throws IOException { byte b = readByte(); if (Code.isFixedRaw(b)) { // FixRaw return b & 0x1f; } int len = tryReadBinaryHeader(b); if (len >= 0) { return len; } if (allowReadingStringAsBinary) { len = tryReadStringHeader(b); if (len >= 0) { return len; // depends on control dependency: [if], data = [none] } } throw unexpected("Binary", b); } }
public class class_name { private PrettyExpression buildPrettyExpression(Class<?> clazz, String component) { if (log.isTraceEnabled()) { log.trace("Searching name of bean: " + clazz.getName()); } // get name from internal map build from @URLBeanName annotations and // previously resolved names String beanName = beanNameMap.get(clazz); // return a constant expression if (beanName != null) { if (log.isTraceEnabled()) { log.trace("Got bean name from @URLBeanName annotation: " + beanName); } return new ConstantExpression("#{" + beanName + "." + component + "}"); } // build a lazy expression else { if (log.isTraceEnabled()) { log.trace("Name of bean not found. Building lazy expression for: " + clazz.getName()); } return new LazyExpression(beanNameFinder, clazz, component); } } }
public class class_name { private PrettyExpression buildPrettyExpression(Class<?> clazz, String component) { if (log.isTraceEnabled()) { log.trace("Searching name of bean: " + clazz.getName()); // depends on control dependency: [if], data = [none] } // get name from internal map build from @URLBeanName annotations and // previously resolved names String beanName = beanNameMap.get(clazz); // return a constant expression if (beanName != null) { if (log.isTraceEnabled()) { log.trace("Got bean name from @URLBeanName annotation: " + beanName); // depends on control dependency: [if], data = [none] } return new ConstantExpression("#{" + beanName + "." + component + "}"); // depends on control dependency: [if], data = [none] } // build a lazy expression else { if (log.isTraceEnabled()) { log.trace("Name of bean not found. Building lazy expression for: " + clazz.getName()); // depends on control dependency: [if], data = [none] } return new LazyExpression(beanNameFinder, clazz, component); // depends on control dependency: [if], data = [(beanName] } } }
public class class_name { public static Pair<Descriptor,String> fromFilename(File directory, String name, boolean skipComponent) { // tokenize the filename StringTokenizer st = new StringTokenizer(name, String.valueOf(separator)); String nexttok; // all filenames must start with keyspace and column family String ksname = st.nextToken(); String cfname = st.nextToken(); // optional temporary marker nexttok = st.nextToken(); Type type = Type.FINAL; if (nexttok.equals(Type.TEMP.marker)) { type = Type.TEMP; nexttok = st.nextToken(); } else if (nexttok.equals(Type.TEMPLINK.marker)) { type = Type.TEMPLINK; nexttok = st.nextToken(); } if (!Version.validate(nexttok)) throw new UnsupportedOperationException("SSTable " + name + " is too old to open. Upgrade to 2.0 first, and run upgradesstables"); Version version = new Version(nexttok); nexttok = st.nextToken(); int generation = Integer.parseInt(nexttok); // component suffix String component = null; if (!skipComponent) component = st.nextToken(); directory = directory != null ? directory : new File("."); return Pair.create(new Descriptor(version, directory, ksname, cfname, generation, type), component); } }
public class class_name { public static Pair<Descriptor,String> fromFilename(File directory, String name, boolean skipComponent) { // tokenize the filename StringTokenizer st = new StringTokenizer(name, String.valueOf(separator)); String nexttok; // all filenames must start with keyspace and column family String ksname = st.nextToken(); String cfname = st.nextToken(); // optional temporary marker nexttok = st.nextToken(); Type type = Type.FINAL; if (nexttok.equals(Type.TEMP.marker)) { type = Type.TEMP; // depends on control dependency: [if], data = [none] nexttok = st.nextToken(); // depends on control dependency: [if], data = [none] } else if (nexttok.equals(Type.TEMPLINK.marker)) { type = Type.TEMPLINK; // depends on control dependency: [if], data = [none] nexttok = st.nextToken(); // depends on control dependency: [if], data = [none] } if (!Version.validate(nexttok)) throw new UnsupportedOperationException("SSTable " + name + " is too old to open. Upgrade to 2.0 first, and run upgradesstables"); Version version = new Version(nexttok); nexttok = st.nextToken(); int generation = Integer.parseInt(nexttok); // component suffix String component = null; if (!skipComponent) component = st.nextToken(); directory = directory != null ? directory : new File("."); return Pair.create(new Descriptor(version, directory, ksname, cfname, generation, type), component); } }
public class class_name { public void marshall(CreateExportJobRequest createExportJobRequest, ProtocolMarshaller protocolMarshaller) { if (createExportJobRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(createExportJobRequest.getApplicationId(), APPLICATIONID_BINDING); protocolMarshaller.marshall(createExportJobRequest.getExportJobRequest(), EXPORTJOBREQUEST_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
public class class_name { public void marshall(CreateExportJobRequest createExportJobRequest, ProtocolMarshaller protocolMarshaller) { if (createExportJobRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(createExportJobRequest.getApplicationId(), APPLICATIONID_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(createExportJobRequest.getExportJobRequest(), EXPORTJOBREQUEST_BINDING); // depends on control dependency: [try], data = [none] } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } // depends on control dependency: [catch], data = [none] } }