code
stringlengths
130
281k
code_dependency
stringlengths
182
306k
public class class_name { public static void logReadTaskOutOfMemoryError(final Logger logger, final Task<Diff> task, final OutOfMemoryError e) { if (task != null) { logger.logError(Level.WARN, "Error while reading a task: " + task.toString(), e); } else { logger.logError(Level.WARN, "Error while reading an unknown task", e); } } }
public class class_name { public static void logReadTaskOutOfMemoryError(final Logger logger, final Task<Diff> task, final OutOfMemoryError e) { if (task != null) { logger.logError(Level.WARN, "Error while reading a task: " + task.toString(), e); // depends on control dependency: [if], data = [none] } else { logger.logError(Level.WARN, "Error while reading an unknown task", e); // depends on control dependency: [if], data = [none] } } }
public class class_name { protected final void initializeSystemConfiguration() { try { attemptSystemConfiguration(); } catch (IOException e) { // Can't recover from this final String err = SYSCFG_READ_FAILURE; throw new BELRuntimeException(err, ExitCode.UNRECOVERABLE_ERROR, e); } } }
public class class_name { protected final void initializeSystemConfiguration() { try { attemptSystemConfiguration(); // depends on control dependency: [try], data = [none] } catch (IOException e) { // Can't recover from this final String err = SYSCFG_READ_FAILURE; throw new BELRuntimeException(err, ExitCode.UNRECOVERABLE_ERROR, e); } // depends on control dependency: [catch], data = [none] } }
public class class_name { public void configureLabel(JLabel label) { Assert.notNull(label, "label"); label.setText(this.text); label.setDisplayedMnemonic(getMnemonic()); if (getMnemonicIndex() >= -1) { label.setDisplayedMnemonicIndex(getMnemonicIndex()); } } }
public class class_name { public void configureLabel(JLabel label) { Assert.notNull(label, "label"); label.setText(this.text); label.setDisplayedMnemonic(getMnemonic()); if (getMnemonicIndex() >= -1) { label.setDisplayedMnemonicIndex(getMnemonicIndex()); // depends on control dependency: [if], data = [(getMnemonicIndex()] } } }
public class class_name { protected void prepareForLoginPage(final RequestContext context) { val currentService = WebUtils.getService(context); val service = authenticationRequestServiceSelectionStrategies.resolveService(currentService, WebApplicationService.class); val request = WebUtils.getHttpServletRequestFromExternalWebflowContext(context); val response = WebUtils.getHttpServletResponseFromExternalWebflowContext(context); val webContext = new J2EContext(request, response, this.sessionStore); val urls = new LinkedHashSet<ProviderLoginPageConfiguration>(); this.clients .findAllClients() .stream() .filter(client -> client instanceof IndirectClient && isDelegatedClientAuthorizedForService(client, service)) .map(IndirectClient.class::cast) .forEach(client -> { try { val provider = buildProviderConfiguration(client, webContext, currentService); provider.ifPresent(p -> { urls.add(p); if (p.isAutoRedirect()) { WebUtils.putDelegatedAuthenticationProviderPrimary(context, p); } }); } catch (final Exception e) { LOGGER.error("Cannot process client [{}]", client, e); } }); if (!urls.isEmpty()) { context.getFlowScope().put(FLOW_ATTRIBUTE_PROVIDER_URLS, urls); } else if (response.getStatus() != HttpStatus.UNAUTHORIZED.value()) { LOGGER.warn("No delegated authentication providers could be determined based on the provided configuration. " + "Either no clients are configured, or the current access strategy rules prohibit CAS from using authentication providers for this request."); } } }
public class class_name { protected void prepareForLoginPage(final RequestContext context) { val currentService = WebUtils.getService(context); val service = authenticationRequestServiceSelectionStrategies.resolveService(currentService, WebApplicationService.class); val request = WebUtils.getHttpServletRequestFromExternalWebflowContext(context); val response = WebUtils.getHttpServletResponseFromExternalWebflowContext(context); val webContext = new J2EContext(request, response, this.sessionStore); val urls = new LinkedHashSet<ProviderLoginPageConfiguration>(); this.clients .findAllClients() .stream() .filter(client -> client instanceof IndirectClient && isDelegatedClientAuthorizedForService(client, service)) .map(IndirectClient.class::cast) .forEach(client -> { try { val provider = buildProviderConfiguration(client, webContext, currentService); provider.ifPresent(p -> { urls.add(p); if (p.isAutoRedirect()) { WebUtils.putDelegatedAuthenticationProviderPrimary(context, p); // depends on control dependency: [if], data = [none] } }); } catch (final Exception e) { LOGGER.error("Cannot process client [{}]", client, e); } }); if (!urls.isEmpty()) { context.getFlowScope().put(FLOW_ATTRIBUTE_PROVIDER_URLS, urls); } else if (response.getStatus() != HttpStatus.UNAUTHORIZED.value()) { LOGGER.warn("No delegated authentication providers could be determined based on the provided configuration. " + "Either no clients are configured, or the current access strategy rules prohibit CAS from using authentication providers for this request."); } } }
public class class_name { private long doMemoryManagementAndPerFrameCallbacks() { long currentTime = GVRTime.getCurrentTime(); mFrameTime = (currentTime - mPreviousTimeNanos) / 1e9f; mPreviousTimeNanos = currentTime; /* * Without the sensor data, can't draw a scene properly. */ if (!(mSensoredScene == null || !mMainScene.equals(mSensoredScene))) { Runnable runnable; while ((runnable = mRunnables.poll()) != null) { try { runnable.run(); } catch (final Exception exc) { Log.e(TAG, "Runnable-on-GL %s threw %s", runnable, exc.toString()); exc.printStackTrace(); } } final List<GVRDrawFrameListener> frameListeners = mFrameListeners; for (GVRDrawFrameListener listener : frameListeners) { try { listener.onDrawFrame(mFrameTime); } catch (final Exception exc) { Log.e(TAG, "DrawFrameListener %s threw %s", listener, exc.toString()); exc.printStackTrace(); } } } return currentTime; } }
public class class_name { private long doMemoryManagementAndPerFrameCallbacks() { long currentTime = GVRTime.getCurrentTime(); mFrameTime = (currentTime - mPreviousTimeNanos) / 1e9f; mPreviousTimeNanos = currentTime; /* * Without the sensor data, can't draw a scene properly. */ if (!(mSensoredScene == null || !mMainScene.equals(mSensoredScene))) { Runnable runnable; while ((runnable = mRunnables.poll()) != null) { try { runnable.run(); // depends on control dependency: [try], data = [none] } catch (final Exception exc) { Log.e(TAG, "Runnable-on-GL %s threw %s", runnable, exc.toString()); exc.printStackTrace(); } // depends on control dependency: [catch], data = [none] } final List<GVRDrawFrameListener> frameListeners = mFrameListeners; for (GVRDrawFrameListener listener : frameListeners) { try { listener.onDrawFrame(mFrameTime); // depends on control dependency: [try], data = [none] } catch (final Exception exc) { Log.e(TAG, "DrawFrameListener %s threw %s", listener, exc.toString()); exc.printStackTrace(); } // depends on control dependency: [catch], data = [none] } } return currentTime; } }
public class class_name { public final EObject ruleXTypeLiteral() throws RecognitionException { EObject current = null; Token otherlv_1=null; Token otherlv_2=null; Token otherlv_5=null; AntlrDatatypeRuleToken lv_arrayDimensions_4_0 = null; enterRule(); try { // InternalPureXbase.g:5457:2: ( ( () otherlv_1= 'typeof' otherlv_2= '(' ( ( ruleQualifiedName ) ) ( (lv_arrayDimensions_4_0= ruleArrayBrackets ) )* otherlv_5= ')' ) ) // InternalPureXbase.g:5458:2: ( () otherlv_1= 'typeof' otherlv_2= '(' ( ( ruleQualifiedName ) ) ( (lv_arrayDimensions_4_0= ruleArrayBrackets ) )* otherlv_5= ')' ) { // InternalPureXbase.g:5458:2: ( () otherlv_1= 'typeof' otherlv_2= '(' ( ( ruleQualifiedName ) ) ( (lv_arrayDimensions_4_0= ruleArrayBrackets ) )* otherlv_5= ')' ) // InternalPureXbase.g:5459:3: () otherlv_1= 'typeof' otherlv_2= '(' ( ( ruleQualifiedName ) ) ( (lv_arrayDimensions_4_0= ruleArrayBrackets ) )* otherlv_5= ')' { // InternalPureXbase.g:5459:3: () // InternalPureXbase.g:5460:4: { if ( state.backtracking==0 ) { current = forceCreateModelElement( grammarAccess.getXTypeLiteralAccess().getXTypeLiteralAction_0(), current); } } otherlv_1=(Token)match(input,77,FOLLOW_49); if (state.failed) return current; if ( state.backtracking==0 ) { newLeafNode(otherlv_1, grammarAccess.getXTypeLiteralAccess().getTypeofKeyword_1()); } otherlv_2=(Token)match(input,15,FOLLOW_12); if (state.failed) return current; if ( state.backtracking==0 ) { newLeafNode(otherlv_2, grammarAccess.getXTypeLiteralAccess().getLeftParenthesisKeyword_2()); } // InternalPureXbase.g:5474:3: ( ( ruleQualifiedName ) ) // InternalPureXbase.g:5475:4: ( ruleQualifiedName ) { // InternalPureXbase.g:5475:4: ( ruleQualifiedName ) // InternalPureXbase.g:5476:5: ruleQualifiedName { if ( state.backtracking==0 ) { if (current==null) { current = createModelElement(grammarAccess.getXTypeLiteralRule()); } } if ( state.backtracking==0 ) { newCompositeNode(grammarAccess.getXTypeLiteralAccess().getTypeJvmTypeCrossReference_3_0()); } pushFollow(FOLLOW_67); ruleQualifiedName(); state._fsp--; if (state.failed) return current; if ( state.backtracking==0 ) { afterParserOrEnumRuleCall(); } } } // InternalPureXbase.g:5490:3: ( (lv_arrayDimensions_4_0= ruleArrayBrackets ) )* loop98: do { int alt98=2; int LA98_0 = input.LA(1); if ( (LA98_0==61) ) { alt98=1; } switch (alt98) { case 1 : // InternalPureXbase.g:5491:4: (lv_arrayDimensions_4_0= ruleArrayBrackets ) { // InternalPureXbase.g:5491:4: (lv_arrayDimensions_4_0= ruleArrayBrackets ) // InternalPureXbase.g:5492:5: lv_arrayDimensions_4_0= ruleArrayBrackets { if ( state.backtracking==0 ) { newCompositeNode(grammarAccess.getXTypeLiteralAccess().getArrayDimensionsArrayBracketsParserRuleCall_4_0()); } pushFollow(FOLLOW_67); lv_arrayDimensions_4_0=ruleArrayBrackets(); state._fsp--; if (state.failed) return current; if ( state.backtracking==0 ) { if (current==null) { current = createModelElementForParent(grammarAccess.getXTypeLiteralRule()); } add( current, "arrayDimensions", lv_arrayDimensions_4_0, "org.eclipse.xtext.xbase.Xtype.ArrayBrackets"); afterParserOrEnumRuleCall(); } } } break; default : break loop98; } } while (true); otherlv_5=(Token)match(input,16,FOLLOW_2); if (state.failed) return current; if ( state.backtracking==0 ) { newLeafNode(otherlv_5, grammarAccess.getXTypeLiteralAccess().getRightParenthesisKeyword_5()); } } } if ( state.backtracking==0 ) { leaveRule(); } } catch (RecognitionException re) { recover(input,re); appendSkippedTokens(); } finally { } return current; } }
public class class_name { public final EObject ruleXTypeLiteral() throws RecognitionException { EObject current = null; Token otherlv_1=null; Token otherlv_2=null; Token otherlv_5=null; AntlrDatatypeRuleToken lv_arrayDimensions_4_0 = null; enterRule(); try { // InternalPureXbase.g:5457:2: ( ( () otherlv_1= 'typeof' otherlv_2= '(' ( ( ruleQualifiedName ) ) ( (lv_arrayDimensions_4_0= ruleArrayBrackets ) )* otherlv_5= ')' ) ) // InternalPureXbase.g:5458:2: ( () otherlv_1= 'typeof' otherlv_2= '(' ( ( ruleQualifiedName ) ) ( (lv_arrayDimensions_4_0= ruleArrayBrackets ) )* otherlv_5= ')' ) { // InternalPureXbase.g:5458:2: ( () otherlv_1= 'typeof' otherlv_2= '(' ( ( ruleQualifiedName ) ) ( (lv_arrayDimensions_4_0= ruleArrayBrackets ) )* otherlv_5= ')' ) // InternalPureXbase.g:5459:3: () otherlv_1= 'typeof' otherlv_2= '(' ( ( ruleQualifiedName ) ) ( (lv_arrayDimensions_4_0= ruleArrayBrackets ) )* otherlv_5= ')' { // InternalPureXbase.g:5459:3: () // InternalPureXbase.g:5460:4: { if ( state.backtracking==0 ) { current = forceCreateModelElement( grammarAccess.getXTypeLiteralAccess().getXTypeLiteralAction_0(), current); // depends on control dependency: [if], data = [none] } } otherlv_1=(Token)match(input,77,FOLLOW_49); if (state.failed) return current; if ( state.backtracking==0 ) { newLeafNode(otherlv_1, grammarAccess.getXTypeLiteralAccess().getTypeofKeyword_1()); // depends on control dependency: [if], data = [none] } otherlv_2=(Token)match(input,15,FOLLOW_12); if (state.failed) return current; if ( state.backtracking==0 ) { newLeafNode(otherlv_2, grammarAccess.getXTypeLiteralAccess().getLeftParenthesisKeyword_2()); // depends on control dependency: [if], data = [none] } // InternalPureXbase.g:5474:3: ( ( ruleQualifiedName ) ) // InternalPureXbase.g:5475:4: ( ruleQualifiedName ) { // InternalPureXbase.g:5475:4: ( ruleQualifiedName ) // InternalPureXbase.g:5476:5: ruleQualifiedName { if ( state.backtracking==0 ) { if (current==null) { current = createModelElement(grammarAccess.getXTypeLiteralRule()); // depends on control dependency: [if], data = [none] } } if ( state.backtracking==0 ) { newCompositeNode(grammarAccess.getXTypeLiteralAccess().getTypeJvmTypeCrossReference_3_0()); // depends on control dependency: [if], data = [none] } pushFollow(FOLLOW_67); ruleQualifiedName(); state._fsp--; if (state.failed) return current; if ( state.backtracking==0 ) { afterParserOrEnumRuleCall(); // depends on control dependency: [if], data = [none] } } } // InternalPureXbase.g:5490:3: ( (lv_arrayDimensions_4_0= ruleArrayBrackets ) )* loop98: do { int alt98=2; int LA98_0 = input.LA(1); if ( (LA98_0==61) ) { alt98=1; // depends on control dependency: [if], data = [none] } switch (alt98) { case 1 : // InternalPureXbase.g:5491:4: (lv_arrayDimensions_4_0= ruleArrayBrackets ) { // InternalPureXbase.g:5491:4: (lv_arrayDimensions_4_0= ruleArrayBrackets ) // InternalPureXbase.g:5492:5: lv_arrayDimensions_4_0= ruleArrayBrackets { if ( state.backtracking==0 ) { newCompositeNode(grammarAccess.getXTypeLiteralAccess().getArrayDimensionsArrayBracketsParserRuleCall_4_0()); // depends on control dependency: [if], data = [none] } pushFollow(FOLLOW_67); lv_arrayDimensions_4_0=ruleArrayBrackets(); state._fsp--; if (state.failed) return current; if ( state.backtracking==0 ) { if (current==null) { current = createModelElementForParent(grammarAccess.getXTypeLiteralRule()); // depends on control dependency: [if], data = [none] } add( current, "arrayDimensions", lv_arrayDimensions_4_0, "org.eclipse.xtext.xbase.Xtype.ArrayBrackets"); // depends on control dependency: [if], data = [none] afterParserOrEnumRuleCall(); // depends on control dependency: [if], data = [none] } } } break; default : break loop98; } } while (true); otherlv_5=(Token)match(input,16,FOLLOW_2); if (state.failed) return current; if ( state.backtracking==0 ) { newLeafNode(otherlv_5, grammarAccess.getXTypeLiteralAccess().getRightParenthesisKeyword_5()); // depends on control dependency: [if], data = [none] } } } if ( state.backtracking==0 ) { leaveRule(); // depends on control dependency: [if], data = [none] } } catch (RecognitionException re) { recover(input,re); appendSkippedTokens(); } finally { } return current; } }
public class class_name { public static void createToken(Controller controller, String tokenName, int secondsOfTimeOut) { if (tokenCache == null) { String tokenId = String.valueOf(random.nextLong()); controller.setAttr(tokenName, tokenId); controller.setSessionAttr(tokenName, tokenId); createTokenHiddenField(controller, tokenName, tokenId); } else { createTokenUseTokenIdGenerator(controller, tokenName, secondsOfTimeOut); } } }
public class class_name { public static void createToken(Controller controller, String tokenName, int secondsOfTimeOut) { if (tokenCache == null) { String tokenId = String.valueOf(random.nextLong()); controller.setAttr(tokenName, tokenId); // depends on control dependency: [if], data = [none] controller.setSessionAttr(tokenName, tokenId); // depends on control dependency: [if], data = [none] createTokenHiddenField(controller, tokenName, tokenId); // depends on control dependency: [if], data = [none] } else { createTokenUseTokenIdGenerator(controller, tokenName, secondsOfTimeOut); // depends on control dependency: [if], data = [none] } } }
public class class_name { public void setAlbum(String newAlbum) { if (newAlbum.length() > ALBUM_SIZE) { album = newAlbum.substring(0, ALBUM_SIZE); } else { album = newAlbum; } } }
public class class_name { public void setAlbum(String newAlbum) { if (newAlbum.length() > ALBUM_SIZE) { album = newAlbum.substring(0, ALBUM_SIZE); // depends on control dependency: [if], data = [ALBUM_SIZE)] } else { album = newAlbum; // depends on control dependency: [if], data = [none] } } }
public class class_name { public Optional<Server> chooseRandomlyAfterFiltering(List<Server> servers) { List<Server> eligible = getEligibleServers(servers); if (eligible.size() == 0) { return Optional.absent(); } return Optional.of(eligible.get(random.nextInt(eligible.size()))); } }
public class class_name { public Optional<Server> chooseRandomlyAfterFiltering(List<Server> servers) { List<Server> eligible = getEligibleServers(servers); if (eligible.size() == 0) { return Optional.absent(); // depends on control dependency: [if], data = [none] } return Optional.of(eligible.get(random.nextInt(eligible.size()))); } }
public class class_name { public static List<String> getServiceUrlsFromDNS(EurekaClientConfig clientConfig, String instanceZone, boolean preferSameZone, ServiceUrlRandomizer randomizer) { String region = getRegion(clientConfig); // Get zone-specific DNS names for the given region so that we can get a // list of available zones Map<String, List<String>> zoneDnsNamesMap = getZoneBasedDiscoveryUrlsFromRegion(clientConfig, region); Set<String> availableZones = zoneDnsNamesMap.keySet(); List<String> zones = new ArrayList<String>(availableZones); if (zones.isEmpty()) { throw new RuntimeException("No available zones configured for the instanceZone " + instanceZone); } int zoneIndex = 0; boolean zoneFound = false; for (String zone : zones) { logger.debug("Checking if the instance zone {} is the same as the zone from DNS {}", instanceZone, zone); if (preferSameZone) { if (instanceZone.equalsIgnoreCase(zone)) { zoneFound = true; } } else { if (!instanceZone.equalsIgnoreCase(zone)) { zoneFound = true; } } if (zoneFound) { logger.debug("The zone index from the list {} that matches the instance zone {} is {}", zones, instanceZone, zoneIndex); break; } zoneIndex++; } if (zoneIndex >= zones.size()) { if (logger.isWarnEnabled()) { logger.warn("No match for the zone {} in the list of available zones {}", instanceZone, zones.toArray()); } } else { // Rearrange the zones with the instance zone first for (int i = 0; i < zoneIndex; i++) { String zone = zones.remove(0); zones.add(zone); } } // Now get the eureka urls for all the zones in the order and return it List<String> serviceUrls = new ArrayList<String>(); for (String zone : zones) { for (String zoneCname : zoneDnsNamesMap.get(zone)) { List<String> ec2Urls = new ArrayList<String>(getEC2DiscoveryUrlsFromZone(zoneCname, DiscoveryUrlType.CNAME)); // Rearrange the list to distribute the load in case of multiple servers if (ec2Urls.size() > 1) { randomizer.randomize(ec2Urls); } for (String ec2Url : ec2Urls) { StringBuilder sb = new StringBuilder() .append("http://") .append(ec2Url) .append(":") .append(clientConfig.getEurekaServerPort()); if (clientConfig.getEurekaServerURLContext() != null) { if (!clientConfig.getEurekaServerURLContext().startsWith("/")) { sb.append("/"); } sb.append(clientConfig.getEurekaServerURLContext()); if (!clientConfig.getEurekaServerURLContext().endsWith("/")) { sb.append("/"); } } else { sb.append("/"); } String serviceUrl = sb.toString(); logger.debug("The EC2 url is {}", serviceUrl); serviceUrls.add(serviceUrl); } } } // Rearrange the fail over server list to distribute the load String primaryServiceUrl = serviceUrls.remove(0); randomizer.randomize(serviceUrls); serviceUrls.add(0, primaryServiceUrl); if (logger.isDebugEnabled()) { logger.debug("This client will talk to the following serviceUrls in order : {} ", (Object) serviceUrls.toArray()); } return serviceUrls; } }
public class class_name { public static List<String> getServiceUrlsFromDNS(EurekaClientConfig clientConfig, String instanceZone, boolean preferSameZone, ServiceUrlRandomizer randomizer) { String region = getRegion(clientConfig); // Get zone-specific DNS names for the given region so that we can get a // list of available zones Map<String, List<String>> zoneDnsNamesMap = getZoneBasedDiscoveryUrlsFromRegion(clientConfig, region); Set<String> availableZones = zoneDnsNamesMap.keySet(); List<String> zones = new ArrayList<String>(availableZones); if (zones.isEmpty()) { throw new RuntimeException("No available zones configured for the instanceZone " + instanceZone); } int zoneIndex = 0; boolean zoneFound = false; for (String zone : zones) { logger.debug("Checking if the instance zone {} is the same as the zone from DNS {}", instanceZone, zone); // depends on control dependency: [for], data = [zone] if (preferSameZone) { if (instanceZone.equalsIgnoreCase(zone)) { zoneFound = true; // depends on control dependency: [if], data = [none] } } else { if (!instanceZone.equalsIgnoreCase(zone)) { zoneFound = true; // depends on control dependency: [if], data = [none] } } if (zoneFound) { logger.debug("The zone index from the list {} that matches the instance zone {} is {}", zones, instanceZone, zoneIndex); // depends on control dependency: [if], data = [none] break; } zoneIndex++; // depends on control dependency: [for], data = [zone] } if (zoneIndex >= zones.size()) { if (logger.isWarnEnabled()) { logger.warn("No match for the zone {} in the list of available zones {}", instanceZone, zones.toArray()); // depends on control dependency: [if], data = [none] } } else { // Rearrange the zones with the instance zone first for (int i = 0; i < zoneIndex; i++) { String zone = zones.remove(0); zones.add(zone); // depends on control dependency: [for], data = [none] } } // Now get the eureka urls for all the zones in the order and return it List<String> serviceUrls = new ArrayList<String>(); for (String zone : zones) { for (String zoneCname : zoneDnsNamesMap.get(zone)) { List<String> ec2Urls = new ArrayList<String>(getEC2DiscoveryUrlsFromZone(zoneCname, DiscoveryUrlType.CNAME)); // Rearrange the list to distribute the load in case of multiple servers if (ec2Urls.size() > 1) { randomizer.randomize(ec2Urls); // depends on control dependency: [if], data = [none] } for (String ec2Url : ec2Urls) { StringBuilder sb = new StringBuilder() .append("http://") .append(ec2Url) .append(":") .append(clientConfig.getEurekaServerPort()); if (clientConfig.getEurekaServerURLContext() != null) { if (!clientConfig.getEurekaServerURLContext().startsWith("/")) { sb.append("/"); // depends on control dependency: [if], data = [none] } sb.append(clientConfig.getEurekaServerURLContext()); // depends on control dependency: [if], data = [(clientConfig.getEurekaServerURLContext()] if (!clientConfig.getEurekaServerURLContext().endsWith("/")) { sb.append("/"); // depends on control dependency: [if], data = [none] } } else { sb.append("/"); // depends on control dependency: [if], data = [none] } String serviceUrl = sb.toString(); logger.debug("The EC2 url is {}", serviceUrl); // depends on control dependency: [for], data = [none] serviceUrls.add(serviceUrl); // depends on control dependency: [for], data = [none] } } } // Rearrange the fail over server list to distribute the load String primaryServiceUrl = serviceUrls.remove(0); randomizer.randomize(serviceUrls); serviceUrls.add(0, primaryServiceUrl); if (logger.isDebugEnabled()) { logger.debug("This client will talk to the following serviceUrls in order : {} ", (Object) serviceUrls.toArray()); // depends on control dependency: [if], data = [none] } return serviceUrls; } }
public class class_name { public static void main(final String[] args) { CowsayCli.addCowthinkOption(); String cowsay = say(args); if (cowsay != null && cowsay.length() > 0) { System.out.println(cowsay); } } }
public class class_name { public static void main(final String[] args) { CowsayCli.addCowthinkOption(); String cowsay = say(args); if (cowsay != null && cowsay.length() > 0) { System.out.println(cowsay); // depends on control dependency: [if], data = [(cowsay] } } }
public class class_name { public void setPreferences(OperaPreferences newPreferences) { if (!(newPreferences instanceof OperaFilePreferences)) { OperaFilePreferences convertedPreferences = new OperaFilePreferences(preferenceFile); convertedPreferences.merge(newPreferences); preferences = convertedPreferences; } else { preferences = newPreferences; } } }
public class class_name { public void setPreferences(OperaPreferences newPreferences) { if (!(newPreferences instanceof OperaFilePreferences)) { OperaFilePreferences convertedPreferences = new OperaFilePreferences(preferenceFile); convertedPreferences.merge(newPreferences); // depends on control dependency: [if], data = [none] preferences = convertedPreferences; // depends on control dependency: [if], data = [none] } else { preferences = newPreferences; // depends on control dependency: [if], data = [none] } } }
public class class_name { public int count(final String word) { if (word == null) { throw new NullPointerException("the word parameter was null."); } else if (word.length() == 0) { return 0; } else if (word.length() == 1) { return 1; } final String lowerCase = word.toLowerCase(Locale.ENGLISH); if (exceptions.containsKey(lowerCase)) { return exceptions.get(lowerCase); } final String prunned; if (lowerCase.charAt(lowerCase.length() - 1) == 'e') { prunned = lowerCase.substring(0, lowerCase.length() - 1); } else { prunned = lowerCase; } int count = 0; boolean prevIsVowel = false; for (char c : prunned.toCharArray()) { final boolean isVowel = vowels.contains(c); if (isVowel && !prevIsVowel) { ++count; } prevIsVowel = isVowel; } count += addSyls.stream() .filter(pattern -> pattern.matcher(prunned).find()) .count(); count -= subSyls.stream() .filter(pattern -> pattern.matcher(prunned).find()) .count(); return count > 0 ? count : 1; } }
public class class_name { public int count(final String word) { if (word == null) { throw new NullPointerException("the word parameter was null."); } else if (word.length() == 0) { return 0; // depends on control dependency: [if], data = [none] } else if (word.length() == 1) { return 1; // depends on control dependency: [if], data = [none] } final String lowerCase = word.toLowerCase(Locale.ENGLISH); if (exceptions.containsKey(lowerCase)) { return exceptions.get(lowerCase); // depends on control dependency: [if], data = [none] } final String prunned; if (lowerCase.charAt(lowerCase.length() - 1) == 'e') { prunned = lowerCase.substring(0, lowerCase.length() - 1); // depends on control dependency: [if], data = [none] } else { prunned = lowerCase; // depends on control dependency: [if], data = [none] } int count = 0; boolean prevIsVowel = false; for (char c : prunned.toCharArray()) { final boolean isVowel = vowels.contains(c); if (isVowel && !prevIsVowel) { ++count; // depends on control dependency: [if], data = [none] } prevIsVowel = isVowel; // depends on control dependency: [for], data = [none] } count += addSyls.stream() .filter(pattern -> pattern.matcher(prunned).find()) .count(); count -= subSyls.stream() .filter(pattern -> pattern.matcher(prunned).find()) .count(); return count > 0 ? count : 1; } }
public class class_name { private String writeEmulatorStartScriptWindows() throws MojoExecutionException { String filename = SCRIPT_FOLDER + "\\android-maven-plugin-emulator-start.vbs"; File file = new File( filename ); PrintWriter writer = null; try { writer = new PrintWriter( new FileWriter( file ) ); // command needs to be assembled before unique window title since it parses settings and sets up parsedAvd // and others. String command = assembleStartCommandLine(); String uniqueWindowTitle = "AndroidMavenPlugin-AVD" + parsedAvd; writer.println( "Dim oShell" ); writer.println( "Set oShell = WScript.CreateObject(\"WScript.shell\")" ); String cmdPath = System.getenv( "COMSPEC" ); if ( cmdPath == null ) { cmdPath = "cmd.exe"; } String cmd = cmdPath + " /X /C START /SEPARATE \"\"" + uniqueWindowTitle + "\"\" " + command.trim(); writer.println( "oShell.run \"" + cmd + "\"" ); } catch ( IOException e ) { getLog().error( "Failure writing file " + filename ); } finally { if ( writer != null ) { writer.flush(); writer.close(); } } file.setExecutable( true ); return filename; } }
public class class_name { private String writeEmulatorStartScriptWindows() throws MojoExecutionException { String filename = SCRIPT_FOLDER + "\\android-maven-plugin-emulator-start.vbs"; File file = new File( filename ); PrintWriter writer = null; try { writer = new PrintWriter( new FileWriter( file ) ); // command needs to be assembled before unique window title since it parses settings and sets up parsedAvd // and others. String command = assembleStartCommandLine(); String uniqueWindowTitle = "AndroidMavenPlugin-AVD" + parsedAvd; writer.println( "Dim oShell" ); writer.println( "Set oShell = WScript.CreateObject(\"WScript.shell\")" ); String cmdPath = System.getenv( "COMSPEC" ); if ( cmdPath == null ) { cmdPath = "cmd.exe"; } String cmd = cmdPath + " /X /C START /SEPARATE \"\"" + uniqueWindowTitle + "\"\" " + command.trim(); writer.println( "oShell.run \"" + cmd + "\"" ); } catch ( IOException e ) { getLog().error( "Failure writing file " + filename ); } finally { if ( writer != null ) { writer.flush(); // depends on control dependency: [if], data = [none] writer.close(); // depends on control dependency: [if], data = [none] } } file.setExecutable( true ); return filename; } }
public class class_name { public CalendarWeek minus(Weeks weeks) { if (weeks.isEmpty()) { return this; } PlainDate date = this.start.getTemporal().minus(weeks.getAmount(), CalendarUnit.WEEKS); int y = date.getInt(YEAR_OF_WEEKDATE); int w = date.getInt(WEEK_OF_YEAR); return CalendarWeek.of(y, w); } }
public class class_name { public CalendarWeek minus(Weeks weeks) { if (weeks.isEmpty()) { return this; // depends on control dependency: [if], data = [none] } PlainDate date = this.start.getTemporal().minus(weeks.getAmount(), CalendarUnit.WEEKS); int y = date.getInt(YEAR_OF_WEEKDATE); int w = date.getInt(WEEK_OF_YEAR); return CalendarWeek.of(y, w); } }
public class class_name { private CompletableFuture<Void> establishConnection(PravegaNodeUri location, FlowHandler handler) { final Bootstrap b = getNettyBootstrap().handler(getChannelInitializer(location, handler)); // Initiate Connection. final CompletableFuture<Void> connectionComplete = new CompletableFuture<>(); try { b.connect(location.getEndpoint(), location.getPort()).addListener((ChannelFutureListener) future -> { if (future.isSuccess()) { //since ChannelFuture is complete future.channel() is not a blocking call. Channel ch = future.channel(); log.debug("Connect operation completed for channel:{}, local address:{}, remote address:{}", ch.id(), ch.localAddress(), ch.remoteAddress()); channelGroup.add(ch); // Once a channel is closed the channel group implementation removes it. connectionComplete.complete(null); } else { connectionComplete.completeExceptionally(new ConnectionFailedException(future.cause())); } }); } catch (Exception e) { connectionComplete.completeExceptionally(new ConnectionFailedException(e)); } final CompletableFuture<Void> channelRegisteredFuture = new CompletableFuture<>(); //to track channel registration. handler.completeWhenRegistered(channelRegisteredFuture); return CompletableFuture.allOf(connectionComplete, channelRegisteredFuture); } }
public class class_name { private CompletableFuture<Void> establishConnection(PravegaNodeUri location, FlowHandler handler) { final Bootstrap b = getNettyBootstrap().handler(getChannelInitializer(location, handler)); // Initiate Connection. final CompletableFuture<Void> connectionComplete = new CompletableFuture<>(); try { b.connect(location.getEndpoint(), location.getPort()).addListener((ChannelFutureListener) future -> { if (future.isSuccess()) { //since ChannelFuture is complete future.channel() is not a blocking call. Channel ch = future.channel(); log.debug("Connect operation completed for channel:{}, local address:{}, remote address:{}", ch.id(), ch.localAddress(), ch.remoteAddress()); channelGroup.add(ch); // Once a channel is closed the channel group implementation removes it. connectionComplete.complete(null); } else { connectionComplete.completeExceptionally(new ConnectionFailedException(future.cause())); // depends on control dependency: [try], data = [none] } }); } catch (Exception e) { connectionComplete.completeExceptionally(new ConnectionFailedException(e)); } // depends on control dependency: [catch], data = [none] final CompletableFuture<Void> channelRegisteredFuture = new CompletableFuture<>(); //to track channel registration. handler.completeWhenRegistered(channelRegisteredFuture); return CompletableFuture.allOf(connectionComplete, channelRegisteredFuture); } }
public class class_name { public void unlock() { for (Locale l : m_lockedBundleFiles.keySet()) { LockedFile f = m_lockedBundleFiles.get(l); f.tryUnlock(); } if (null != m_descFile) { m_descFile.tryUnlock(); } } }
public class class_name { public void unlock() { for (Locale l : m_lockedBundleFiles.keySet()) { LockedFile f = m_lockedBundleFiles.get(l); f.tryUnlock(); // depends on control dependency: [for], data = [l] } if (null != m_descFile) { m_descFile.tryUnlock(); // depends on control dependency: [if], data = [none] } } }
public class class_name { public void pullUpTo(Phase phase) { // get if (!phase.contains(GET)) { return; } T targetValue = target.getValue(); // validate-post-get if (!phase.contains(VALIDATE_POST_GET)) { return; } Collection<V> oldViolations = new ArrayList<V>(violations); violations.clear(); if (validate(targetValidator, targetValue) && phase.contains(CONVERT)) { // convert boolean converted = true; S sourceValue = null; try { sourceValue = converter.unconvert(targetValue); } // TODO: catch all other exceptions and terminate too? catch (UnsupportedOperationException exception) { converted = false; } // validate-pre-set if (converted && phase.contains(VALIDATE_PRE_SET) && validate(sourceValidator, sourceValue) && phase.contains(SET)) { // set source.setValue(sourceValue); } } support.fireValueChanged(oldViolations, new ArrayList<V>(violations)); } }
public class class_name { public void pullUpTo(Phase phase) { // get if (!phase.contains(GET)) { return; // depends on control dependency: [if], data = [none] } T targetValue = target.getValue(); // validate-post-get if (!phase.contains(VALIDATE_POST_GET)) { return; // depends on control dependency: [if], data = [none] } Collection<V> oldViolations = new ArrayList<V>(violations); violations.clear(); if (validate(targetValidator, targetValue) && phase.contains(CONVERT)) { // convert boolean converted = true; S sourceValue = null; try { sourceValue = converter.unconvert(targetValue); // depends on control dependency: [try], data = [none] } // TODO: catch all other exceptions and terminate too? catch (UnsupportedOperationException exception) { converted = false; } // depends on control dependency: [catch], data = [none] // validate-pre-set if (converted && phase.contains(VALIDATE_PRE_SET) && validate(sourceValidator, sourceValue) && phase.contains(SET)) { // set source.setValue(sourceValue); // depends on control dependency: [if], data = [none] } } support.fireValueChanged(oldViolations, new ArrayList<V>(violations)); } }
public class class_name { public void serve() throws IOException { ServerSocket serverSocket = new ServerSocket(port); while (true) { try { final Socket socket = serverSocket.accept(); Thread thread = new Thread("EnvServerSocketHandler") { public void run() { boolean running = false; try { checkHello(socket); while (true) { DataInputStream din = new DataInputStream(socket.getInputStream()); int hdr = din.readInt(); byte[] data = new byte[hdr]; din.readFully(data); String command = new String(data, utf8); if (command.startsWith("<Step")) { step(command, socket, din); } else if (command.startsWith("<Peek")) { peek(command, socket, din); } else if (command.startsWith("<Init")) { init(command, socket); } else if (command.startsWith("<Find")) { find(command, socket); } else if (command.startsWith("<MissionInit")) { if (missionInit(din, command, socket)) running = true; } else if (command.startsWith("<Quit")) { quit(command, socket); } else if (command.startsWith("<Exit")) { exit(command, socket); } else if (command.startsWith("<Close")) { close(command, socket); } else if (command.startsWith("<Status")) { status(command, socket); } else if (command.startsWith("<Echo")) { command = "<Echo>" + command + "</Echo>"; data = command.getBytes(utf8); hdr = data.length; DataOutputStream dout = new DataOutputStream(socket.getOutputStream()); dout.writeInt(hdr); dout.write(data, 0, hdr); dout.flush(); } else { throw new IOException("Unknown env service command"); } } } catch (IOException ioe) { TCPUtils.Log(Level.SEVERE, "MalmoEnv socket error: " + ioe + " (can be on disconnect)"); try { if (running) { TCPUtils.Log(Level.INFO,"Want to quit on disconnect."); setWantToQuit(); } socket.close(); } catch (IOException ioe2) { } } } }; thread.start(); } catch (IOException ioe) { TCPUtils.Log(Level.SEVERE, "MalmoEnv service exits on " + ioe); } } } }
public class class_name { public void serve() throws IOException { ServerSocket serverSocket = new ServerSocket(port); while (true) { try { final Socket socket = serverSocket.accept(); Thread thread = new Thread("EnvServerSocketHandler") { public void run() { boolean running = false; try { checkHello(socket); while (true) { DataInputStream din = new DataInputStream(socket.getInputStream()); int hdr = din.readInt(); byte[] data = new byte[hdr]; din.readFully(data); // depends on control dependency: [while], data = [none] String command = new String(data, utf8); if (command.startsWith("<Step")) { step(command, socket, din); // depends on control dependency: [if], data = [none] } else if (command.startsWith("<Peek")) { peek(command, socket, din); // depends on control dependency: [if], data = [none] } else if (command.startsWith("<Init")) { init(command, socket); // depends on control dependency: [if], data = [none] } else if (command.startsWith("<Find")) { find(command, socket); // depends on control dependency: [if], data = [none] } else if (command.startsWith("<MissionInit")) { if (missionInit(din, command, socket)) running = true; } else if (command.startsWith("<Quit")) { quit(command, socket); // depends on control dependency: [if], data = [none] } else if (command.startsWith("<Exit")) { exit(command, socket); // depends on control dependency: [if], data = [none] } else if (command.startsWith("<Close")) { close(command, socket); // depends on control dependency: [if], data = [none] } else if (command.startsWith("<Status")) { status(command, socket); // depends on control dependency: [if], data = [none] } else if (command.startsWith("<Echo")) { command = "<Echo>" + command + "</Echo>"; // depends on control dependency: [if], data = [none] data = command.getBytes(utf8); // depends on control dependency: [if], data = [none] hdr = data.length; // depends on control dependency: [if], data = [none] DataOutputStream dout = new DataOutputStream(socket.getOutputStream()); dout.writeInt(hdr); // depends on control dependency: [if], data = [none] dout.write(data, 0, hdr); // depends on control dependency: [if], data = [none] dout.flush(); // depends on control dependency: [if], data = [none] } else { throw new IOException("Unknown env service command"); } } } catch (IOException ioe) { TCPUtils.Log(Level.SEVERE, "MalmoEnv socket error: " + ioe + " (can be on disconnect)"); try { if (running) { TCPUtils.Log(Level.INFO,"Want to quit on disconnect."); setWantToQuit(); } socket.close(); } catch (IOException ioe2) { } } } }; thread.start(); } catch (IOException ioe) { TCPUtils.Log(Level.SEVERE, "MalmoEnv service exits on " + ioe); } } } }
public class class_name { public String getStringArgument(String argument) { if (line != null && line.hasOption(argument)) { return line.getOptionValue(argument); } return null; } }
public class class_name { public String getStringArgument(String argument) { if (line != null && line.hasOption(argument)) { return line.getOptionValue(argument); // depends on control dependency: [if], data = [none] } return null; } }
public class class_name { protected void addSlideItem(final VBox vbox, final SlideItem item) { Node node = null; if (item.isLink()) { final Hyperlink link = HyperlinkBuilder.create() .opacity(1.0) .text(item.getValue()) .build(); link.getStyleClass().add("link" + item.getLevel()); link.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(final ActionEvent e) { final ClipboardContent content = new ClipboardContent(); content.putString("http://" + ((Hyperlink) e.getSource()).getText()); Clipboard.getSystemClipboard().setContent(content); } }); node = link; } else if (item.isHtml()) { final WebView web = WebViewBuilder.create() .fontScale(1.4) // .effect(ReflectionBuilder.create().fraction(0.4).build()) .build(); web.getEngine().loadContent(item.getValue()); VBox.setVgrow(web, Priority.NEVER); node = web; // StackPaneBuilder.create().children(web).style("-fx-border-width:2;-fx-border-color:#000000").build(); } else if (item.getImage() != null) { final Image image = Resources.create(new RelImage(item.getImage())).get(); final ImageView imageViewer = ImageViewBuilder.create() .styleClass(ITEM_CLASS_PREFIX + item.getLevel()) .image(image) // .effect(ReflectionBuilder.create().fraction(0.9).build()) .build(); node = imageViewer; } else { final Text text = TextBuilder.create() .styleClass(ITEM_CLASS_PREFIX + item.getLevel()) .text(item.getValue() == null ? "" : item.getValue()) .build(); node = text; } if (item.getStyle() != null) { node.getStyleClass().add(item.getStyle()); } if (item.getScale() != 1.0) { node.setScaleX(item.getScale()); node.setScaleY(item.getScale()); } vbox.getChildren().add(node); } }
public class class_name { protected void addSlideItem(final VBox vbox, final SlideItem item) { Node node = null; if (item.isLink()) { final Hyperlink link = HyperlinkBuilder.create() .opacity(1.0) .text(item.getValue()) .build(); link.getStyleClass().add("link" + item.getLevel()); // depends on control dependency: [if], data = [none] link.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(final ActionEvent e) { final ClipboardContent content = new ClipboardContent(); content.putString("http://" + ((Hyperlink) e.getSource()).getText()); Clipboard.getSystemClipboard().setContent(content); } }); // depends on control dependency: [if], data = [none] node = link; // depends on control dependency: [if], data = [none] } else if (item.isHtml()) { final WebView web = WebViewBuilder.create() .fontScale(1.4) // .effect(ReflectionBuilder.create().fraction(0.4).build()) .build(); web.getEngine().loadContent(item.getValue()); // depends on control dependency: [if], data = [none] VBox.setVgrow(web, Priority.NEVER); // depends on control dependency: [if], data = [none] node = web; // StackPaneBuilder.create().children(web).style("-fx-border-width:2;-fx-border-color:#000000").build(); // depends on control dependency: [if], data = [none] } else if (item.getImage() != null) { final Image image = Resources.create(new RelImage(item.getImage())).get(); final ImageView imageViewer = ImageViewBuilder.create() .styleClass(ITEM_CLASS_PREFIX + item.getLevel()) .image(image) // .effect(ReflectionBuilder.create().fraction(0.9).build()) .build(); node = imageViewer; // depends on control dependency: [if], data = [none] } else { final Text text = TextBuilder.create() .styleClass(ITEM_CLASS_PREFIX + item.getLevel()) .text(item.getValue() == null ? "" : item.getValue()) .build(); node = text; // depends on control dependency: [if], data = [none] } if (item.getStyle() != null) { node.getStyleClass().add(item.getStyle()); // depends on control dependency: [if], data = [(item.getStyle()] } if (item.getScale() != 1.0) { node.setScaleX(item.getScale()); // depends on control dependency: [if], data = [(item.getScale()] node.setScaleY(item.getScale()); // depends on control dependency: [if], data = [(item.getScale()] } vbox.getChildren().add(node); } }
public class class_name { public void showAlertEditDialog(Alert alert) { if (dialogAlertAdd == null || !dialogAlertAdd.isVisible()) { dialogAlertAdd = new AlertAddDialog(getView().getMainFrame(), false); dialogAlertAdd.setVisible(true); dialogAlertAdd.setAlert(alert); } } }
public class class_name { public void showAlertEditDialog(Alert alert) { if (dialogAlertAdd == null || !dialogAlertAdd.isVisible()) { dialogAlertAdd = new AlertAddDialog(getView().getMainFrame(), false); // depends on control dependency: [if], data = [none] dialogAlertAdd.setVisible(true); // depends on control dependency: [if], data = [none] dialogAlertAdd.setAlert(alert); // depends on control dependency: [if], data = [none] } } }
public class class_name { private void postcheckMappingConditions(MtasParserObject object, List<Map<String, String>> mappingConditions, Map<String, List<MtasParserObject>> currentList) throws MtasParserException { precheckMappingConditions(object, mappingConditions, currentList); for (Map<String, String> mappingCondition : mappingConditions) { // condition on text if (mappingCondition.get("type") .equals(MtasParserMapping.PARSER_TYPE_TEXT)) { MtasParserObject[] checkObjects = computeObjectFromMappingValue(object, mappingCondition, currentList); if (checkObjects != null) { String textCondition = mappingCondition.get(MAPPING_VALUE_CONDITION); String textValue = object.getText(); Boolean notCondition = false; if (mappingCondition.get("not") != null) { notCondition = true; } if ((textCondition == null) && ((textValue == null) || textValue.isEmpty())) { if (!notCondition) { throw new MtasParserException("no text available"); } } else if ((textCondition != null) && (textValue == null)) { if (!notCondition) { throw new MtasParserException("condition " + textCondition + " on text not matched (is null)"); } } else if (textCondition != null) { if (!notCondition && !textCondition.equals(textValue)) { throw new MtasParserException("condition " + textCondition + " on text not matched (is " + textValue + ")"); } else if (notCondition && textCondition.equals(textValue)) { throw new MtasParserException("condition NOT " + textCondition + " on text not matched (is " + textValue + ")"); } } } } } } }
public class class_name { private void postcheckMappingConditions(MtasParserObject object, List<Map<String, String>> mappingConditions, Map<String, List<MtasParserObject>> currentList) throws MtasParserException { precheckMappingConditions(object, mappingConditions, currentList); for (Map<String, String> mappingCondition : mappingConditions) { // condition on text if (mappingCondition.get("type") .equals(MtasParserMapping.PARSER_TYPE_TEXT)) { MtasParserObject[] checkObjects = computeObjectFromMappingValue(object, mappingCondition, currentList); if (checkObjects != null) { String textCondition = mappingCondition.get(MAPPING_VALUE_CONDITION); String textValue = object.getText(); Boolean notCondition = false; if (mappingCondition.get("not") != null) { notCondition = true; // depends on control dependency: [if], data = [none] } if ((textCondition == null) && ((textValue == null) || textValue.isEmpty())) { if (!notCondition) { throw new MtasParserException("no text available"); } } else if ((textCondition != null) && (textValue == null)) { if (!notCondition) { throw new MtasParserException("condition " + textCondition + " on text not matched (is null)"); } } else if (textCondition != null) { if (!notCondition && !textCondition.equals(textValue)) { throw new MtasParserException("condition " + textCondition + " on text not matched (is " + textValue + ")"); } else if (notCondition && textCondition.equals(textValue)) { throw new MtasParserException("condition NOT " + textCondition + " on text not matched (is " + textValue + ")"); } } } } } } }
public class class_name { @Override public Object getDisplayValue(final String object) { final String splitString = "=>"; final String[] splittedValue = object.split(splitString); final StringBuilder sb = new StringBuilder(); if (splittedValue.length == 1) { final IModel<String> resourceModel = ResourceModelFactory.newResourceModel( ResourceBundleKey.builder().key(splittedValue[0]).defaultValue("").build(), component); sb.append(resourceModel.getObject()); } else { IModel<String> resourceModel = ResourceModelFactory.newResourceModel( ResourceBundleKey.builder().key(splittedValue[0]).defaultValue("").build(), component); sb.append(resourceModel.getObject()); sb.append(splitString); resourceModel = ResourceModelFactory.newResourceModel( ResourceBundleKey.builder().key(splittedValue[1]).defaultValue("").build(), component); sb.append(resourceModel.getObject()); } return sb.toString(); } }
public class class_name { @Override public Object getDisplayValue(final String object) { final String splitString = "=>"; final String[] splittedValue = object.split(splitString); final StringBuilder sb = new StringBuilder(); if (splittedValue.length == 1) { final IModel<String> resourceModel = ResourceModelFactory.newResourceModel( ResourceBundleKey.builder().key(splittedValue[0]).defaultValue("").build(), component); sb.append(resourceModel.getObject()); // depends on control dependency: [if], data = [none] } else { IModel<String> resourceModel = ResourceModelFactory.newResourceModel( ResourceBundleKey.builder().key(splittedValue[0]).defaultValue("").build(), component); sb.append(resourceModel.getObject()); // depends on control dependency: [if], data = [none] sb.append(splitString); // depends on control dependency: [if], data = [none] resourceModel = ResourceModelFactory.newResourceModel( ResourceBundleKey.builder().key(splittedValue[1]).defaultValue("").build(), component); // depends on control dependency: [if], data = [none] sb.append(resourceModel.getObject()); // depends on control dependency: [if], data = [none] } return sb.toString(); } }
public class class_name { @Override public DataBuffer getVectorCoordinates() { int idx; if (isRowVector()) { idx = 1; } else if (isColumnVector()) { idx = 0; } else { throw new UnsupportedOperationException(); } // FIXME: int cast int[] temp = new int[(int) length()]; for (int i = 0; i < length(); i++) { temp[i] = getUnderlyingIndicesOf(i).getInt(idx); } return Nd4j.createBuffer(temp); } }
public class class_name { @Override public DataBuffer getVectorCoordinates() { int idx; if (isRowVector()) { idx = 1; // depends on control dependency: [if], data = [none] } else if (isColumnVector()) { idx = 0; // depends on control dependency: [if], data = [none] } else { throw new UnsupportedOperationException(); } // FIXME: int cast int[] temp = new int[(int) length()]; for (int i = 0; i < length(); i++) { temp[i] = getUnderlyingIndicesOf(i).getInt(idx); // depends on control dependency: [for], data = [i] } return Nd4j.createBuffer(temp); } }
public class class_name { private void updateDts() { double dt = 0.1; ArrayList<Double> u = new ArrayList<Double>(); ArrayList<Double> s = new ArrayList<Double>(); //u = u + a * dt; //s = s + u * dt; s.add(0.0); u.add(0.0); double totDistance = 0.0; for (int i = 1; i < dts.length; i++) { Coordinate prev = getPositions()[i-1]; Coordinate current = getPositions()[i]; totDistance += prev.distance(current); } while (s.get(s.size()-1) < totDistance) { double percentComplete = 0.01; double newPercent = s.get(s.size()-1)/totDistance; if (newPercent > percentComplete) percentComplete = newPercent; // System.out.println(percentComplete*100 + "% --> " + getAcceleration(percentComplete)); u.add(u.get(u.size()-1)+getAcceleration(percentComplete)*dt); s.add(s.get(s.size()-1)+u.get(u.size()-1)*dt); } totDistance = 0.0; dts[0] = 0.0; double prevSum = 0.0; for (int i = 1; i < dts.length; i++) { Coordinate prev = getPositions()[i-1]; Coordinate current = getPositions()[i]; totDistance += prev.distance(current); int countDts = 0; for (int j = 0; j < s.size(); j++) { if (s.get(j) > totDistance) { countDts = j-1; break; } } prevSum += dts[i-1]; dts[i] = Math.max(countDts*dt-prevSum,0.001); } } }
public class class_name { private void updateDts() { double dt = 0.1; ArrayList<Double> u = new ArrayList<Double>(); ArrayList<Double> s = new ArrayList<Double>(); //u = u + a * dt; //s = s + u * dt; s.add(0.0); u.add(0.0); double totDistance = 0.0; for (int i = 1; i < dts.length; i++) { Coordinate prev = getPositions()[i-1]; Coordinate current = getPositions()[i]; totDistance += prev.distance(current); // depends on control dependency: [for], data = [none] } while (s.get(s.size()-1) < totDistance) { double percentComplete = 0.01; double newPercent = s.get(s.size()-1)/totDistance; if (newPercent > percentComplete) percentComplete = newPercent; // System.out.println(percentComplete*100 + "% --> " + getAcceleration(percentComplete)); u.add(u.get(u.size()-1)+getAcceleration(percentComplete)*dt); // depends on control dependency: [while], data = [none] s.add(s.get(s.size()-1)+u.get(u.size()-1)*dt); // depends on control dependency: [while], data = [(s.get(s.size()-1)] } totDistance = 0.0; dts[0] = 0.0; double prevSum = 0.0; for (int i = 1; i < dts.length; i++) { Coordinate prev = getPositions()[i-1]; Coordinate current = getPositions()[i]; totDistance += prev.distance(current); // depends on control dependency: [for], data = [none] int countDts = 0; for (int j = 0; j < s.size(); j++) { if (s.get(j) > totDistance) { countDts = j-1; // depends on control dependency: [if], data = [none] break; } } prevSum += dts[i-1]; // depends on control dependency: [for], data = [i] dts[i] = Math.max(countDts*dt-prevSum,0.001); // depends on control dependency: [for], data = [i] } } }
public class class_name { private static <T> T coerceObject(String value) { T result; //try boolean first if ("true".equals(value) || "false".equals(value)) { result = (T) (Boolean) Boolean.parseBoolean(value); } //then float numbers else if (floatPattern.matcher(value).matches()) { //handle overflow by converting to BigDecimal BigDecimal bd = new BigDecimal(value); Double d = bd.doubleValue(); result = (T) ((d == Double.NEGATIVE_INFINITY || d == Double.POSITIVE_INFINITY) ? bd : d); } //then int numbers else if (intPattern.matcher(value).matches()) { //handle overflow by converting to BigInteger BigInteger bd = new BigInteger(value); result = (T) (bd.compareTo(BigInteger.valueOf(Long.MAX_VALUE)) == 1 ? bd : bd.longValue()); } //else just pass the String value to the Object parameter else { result = (T) value; } return result; } }
public class class_name { private static <T> T coerceObject(String value) { T result; //try boolean first if ("true".equals(value) || "false".equals(value)) { result = (T) (Boolean) Boolean.parseBoolean(value); // depends on control dependency: [if], data = [none] } //then float numbers else if (floatPattern.matcher(value).matches()) { //handle overflow by converting to BigDecimal BigDecimal bd = new BigDecimal(value); Double d = bd.doubleValue(); result = (T) ((d == Double.NEGATIVE_INFINITY || d == Double.POSITIVE_INFINITY) ? bd : d); // depends on control dependency: [if], data = [none] } //then int numbers else if (intPattern.matcher(value).matches()) { //handle overflow by converting to BigInteger BigInteger bd = new BigInteger(value); result = (T) (bd.compareTo(BigInteger.valueOf(Long.MAX_VALUE)) == 1 ? bd : bd.longValue()); // depends on control dependency: [if], data = [none] } //else just pass the String value to the Object parameter else { result = (T) value; // depends on control dependency: [if], data = [none] } return result; } }
public class class_name { protected static String urlEncode(String value, boolean path) { try { value = URLEncoder.encode(value, DEFAULT_ENCODING); } catch (Exception e) { throw wrap(e); } value = replaceAll(value, plusPtn, "%20"); value = replaceAll(value, asteriskPtn, "%2A"); value = replaceAll(value, pct7EPtn, "~"); if (path) { value = replaceAll(value, pct2FPtn, "/"); } return value; } }
public class class_name { protected static String urlEncode(String value, boolean path) { try { value = URLEncoder.encode(value, DEFAULT_ENCODING); // depends on control dependency: [try], data = [none] } catch (Exception e) { throw wrap(e); } // depends on control dependency: [catch], data = [none] value = replaceAll(value, plusPtn, "%20"); value = replaceAll(value, asteriskPtn, "%2A"); value = replaceAll(value, pct7EPtn, "~"); if (path) { value = replaceAll(value, pct2FPtn, "/"); // depends on control dependency: [if], data = [none] } return value; } }
public class class_name { public ListSubscribedWorkteamsResult withSubscribedWorkteams(SubscribedWorkteam... subscribedWorkteams) { if (this.subscribedWorkteams == null) { setSubscribedWorkteams(new java.util.ArrayList<SubscribedWorkteam>(subscribedWorkteams.length)); } for (SubscribedWorkteam ele : subscribedWorkteams) { this.subscribedWorkteams.add(ele); } return this; } }
public class class_name { public ListSubscribedWorkteamsResult withSubscribedWorkteams(SubscribedWorkteam... subscribedWorkteams) { if (this.subscribedWorkteams == null) { setSubscribedWorkteams(new java.util.ArrayList<SubscribedWorkteam>(subscribedWorkteams.length)); // depends on control dependency: [if], data = [none] } for (SubscribedWorkteam ele : subscribedWorkteams) { this.subscribedWorkteams.add(ele); // depends on control dependency: [for], data = [ele] } return this; } }
public class class_name { public boolean removeLastOccurrence(Object o) { Objects.requireNonNull(o); for (Node<E> p = last(); p != null; p = pred(p)) { final E item; if ((item = p.item) != null && o.equals(item) && ITEM.compareAndSet(p, item, null)) { unlink(p); return true; } } return false; } }
public class class_name { public boolean removeLastOccurrence(Object o) { Objects.requireNonNull(o); for (Node<E> p = last(); p != null; p = pred(p)) { final E item; if ((item = p.item) != null && o.equals(item) && ITEM.compareAndSet(p, item, null)) { unlink(p); // depends on control dependency: [if], data = [none] return true; // depends on control dependency: [if], data = [none] } } return false; } }
public class class_name { @Override public <D, F, P> Promise<D, F, P> when(Promise<D, F, P> promise) { if (promise instanceof AndroidDeferredObject) { return promise; } return new AndroidDeferredObject<D, F, P>(promise).promise(); } }
public class class_name { @Override public <D, F, P> Promise<D, F, P> when(Promise<D, F, P> promise) { if (promise instanceof AndroidDeferredObject) { return promise; // depends on control dependency: [if], data = [none] } return new AndroidDeferredObject<D, F, P>(promise).promise(); } }
public class class_name { public NamespaceNotification getNamespaceNotification() throws IOException { FSEditLogOp op = null; NamespaceNotification notification = null; // Keep looping until we reach an operation that can be // considered a notification. while (true) { if (LOG.isDebugEnabled()) { LOG.debug("edits.size=" + editsFile.length() + " editsNew.size=" + editsNewFile.length()); } try { op = inputStream.readOp(); if (LOG.isDebugEnabled()) { LOG.debug("inputStream.readOP() returned " + op); } } catch (IOException e) { LOG.warn("inputStream.readOp() failed", e); tryReloadingEditLog(); return null; } catch (Exception e2) { LOG.error("Error reading log operation", e2); throw new IOException(e2); } // No operation to read at the moment from the transaction log if (op == null) { core.getMetrics().reachedEditLogEnd.inc(); handleNullRead(); trySwitchingEditLog(); return null; } else { core.getMetrics().readOperations.inc(); readNullAfterStreamFinished = false; } if (LOG.isDebugEnabled()) { LOG.debug("Read operation: " + op + " with txId=" + op.getTransactionId()); } if (ServerLogReaderUtil.shouldSkipOp(expectedTransactionId, op)) { updateStreamPosition(); continue; } expectedTransactionId = ServerLogReaderUtil.checkTransactionId( expectedTransactionId, op); updateStreamPosition(); // Test if it can be considered a notification notification = ServerLogReaderUtil.createNotification(op); if (notification != null) { if (LOG.isDebugEnabled()) { LOG.debug("Emitting " + NotifierUtils.asString(notification)); } core.getMetrics().readNotifications.inc(); return notification; } } } }
public class class_name { public NamespaceNotification getNamespaceNotification() throws IOException { FSEditLogOp op = null; NamespaceNotification notification = null; // Keep looping until we reach an operation that can be // considered a notification. while (true) { if (LOG.isDebugEnabled()) { LOG.debug("edits.size=" + editsFile.length() + " editsNew.size=" + editsNewFile.length()); // depends on control dependency: [if], data = [none] } try { op = inputStream.readOp(); // depends on control dependency: [try], data = [none] if (LOG.isDebugEnabled()) { LOG.debug("inputStream.readOP() returned " + op); // depends on control dependency: [if], data = [none] } } catch (IOException e) { LOG.warn("inputStream.readOp() failed", e); tryReloadingEditLog(); return null; } catch (Exception e2) { // depends on control dependency: [catch], data = [none] LOG.error("Error reading log operation", e2); throw new IOException(e2); } // depends on control dependency: [catch], data = [none] // No operation to read at the moment from the transaction log if (op == null) { core.getMetrics().reachedEditLogEnd.inc(); // depends on control dependency: [if], data = [none] handleNullRead(); // depends on control dependency: [if], data = [none] trySwitchingEditLog(); // depends on control dependency: [if], data = [none] return null; // depends on control dependency: [if], data = [none] } else { core.getMetrics().readOperations.inc(); // depends on control dependency: [if], data = [none] readNullAfterStreamFinished = false; // depends on control dependency: [if], data = [none] } if (LOG.isDebugEnabled()) { LOG.debug("Read operation: " + op + " with txId=" + op.getTransactionId()); // depends on control dependency: [if], data = [none] } if (ServerLogReaderUtil.shouldSkipOp(expectedTransactionId, op)) { updateStreamPosition(); // depends on control dependency: [if], data = [none] continue; } expectedTransactionId = ServerLogReaderUtil.checkTransactionId( expectedTransactionId, op); updateStreamPosition(); // Test if it can be considered a notification notification = ServerLogReaderUtil.createNotification(op); if (notification != null) { if (LOG.isDebugEnabled()) { LOG.debug("Emitting " + NotifierUtils.asString(notification)); // depends on control dependency: [if], data = [none] } core.getMetrics().readNotifications.inc(); // depends on control dependency: [if], data = [none] return notification; // depends on control dependency: [if], data = [none] } } } }
public class class_name { public static @Nonnull Logger getLogger(@Nonnull Class type) { if (ENABLE_CLASS_LOADER_LOGGING) { return LoggerFactory.getLogger(type); } else { return NOPLogger.NOP_LOGGER; } } }
public class class_name { public static @Nonnull Logger getLogger(@Nonnull Class type) { if (ENABLE_CLASS_LOADER_LOGGING) { return LoggerFactory.getLogger(type); // depends on control dependency: [if], data = [none] } else { return NOPLogger.NOP_LOGGER; // depends on control dependency: [if], data = [none] } } }
public class class_name { public void setProcessors(java.util.Collection<Processor> processors) { if (processors == null) { this.processors = null; return; } this.processors = new java.util.ArrayList<Processor>(processors); } }
public class class_name { public void setProcessors(java.util.Collection<Processor> processors) { if (processors == null) { this.processors = null; // depends on control dependency: [if], data = [none] return; // depends on control dependency: [if], data = [none] } this.processors = new java.util.ArrayList<Processor>(processors); } }
public class class_name { public static ITextProcessor wrap(final ITextProcessor processor, final IProcessorDialect dialect) { Validate.notNull(dialect, "Dialect cannot be null"); if (processor == null) { return null; } return new TextProcessorWrapper(processor, dialect); } }
public class class_name { public static ITextProcessor wrap(final ITextProcessor processor, final IProcessorDialect dialect) { Validate.notNull(dialect, "Dialect cannot be null"); if (processor == null) { return null; // depends on control dependency: [if], data = [none] } return new TextProcessorWrapper(processor, dialect); } }
public class class_name { public IPersonAttributesGroupDefinition getPagsDefinitionByName(IPerson person, String name) { IPersonAttributesGroupDefinition rslt = getPagsGroupDefByName(name); if (rslt == null) { // Better to produce exception? I'm thinking not, but open-minded. return null; } if (!hasPermission( person, IPermission.VIEW_GROUP_ACTIVITY, rslt.getCompositeEntityIdentifierForGroup().getKey())) { throw new RuntimeAuthorizationException(person, IPermission.VIEW_GROUP_ACTIVITY, name); } logger.debug("Returning PAGS definition '{}' for user '{}'", rslt, person.getUserName()); return rslt; } }
public class class_name { public IPersonAttributesGroupDefinition getPagsDefinitionByName(IPerson person, String name) { IPersonAttributesGroupDefinition rslt = getPagsGroupDefByName(name); if (rslt == null) { // Better to produce exception? I'm thinking not, but open-minded. return null; // depends on control dependency: [if], data = [none] } if (!hasPermission( person, IPermission.VIEW_GROUP_ACTIVITY, rslt.getCompositeEntityIdentifierForGroup().getKey())) { throw new RuntimeAuthorizationException(person, IPermission.VIEW_GROUP_ACTIVITY, name); } logger.debug("Returning PAGS definition '{}' for user '{}'", rslt, person.getUserName()); return rslt; } }
public class class_name { protected final ByteBuf copyAndCompose(ByteBufAllocator alloc, ByteBuf cumulation, ByteBuf next) { ByteBuf newCumulation = alloc.ioBuffer(cumulation.readableBytes() + next.readableBytes()); try { newCumulation.writeBytes(cumulation).writeBytes(next); } catch (Throwable cause) { newCumulation.release(); safeRelease(next); throwException(cause); } cumulation.release(); next.release(); return newCumulation; } }
public class class_name { protected final ByteBuf copyAndCompose(ByteBufAllocator alloc, ByteBuf cumulation, ByteBuf next) { ByteBuf newCumulation = alloc.ioBuffer(cumulation.readableBytes() + next.readableBytes()); try { newCumulation.writeBytes(cumulation).writeBytes(next); // depends on control dependency: [try], data = [none] } catch (Throwable cause) { newCumulation.release(); safeRelease(next); throwException(cause); } // depends on control dependency: [catch], data = [none] cumulation.release(); next.release(); return newCumulation; } }
public class class_name { private void unloadSpectraConditionally(NavigableMap<Integer, IScan> scansInSubsetByNumber, LCMSDataSubset subset, Set<LCMSDataSubset> exlude) { boolean isOkToUnload; for (IScan scan : scansInSubsetByNumber.values()) { if (subset.isInSubset(scan)) { isOkToUnload = true; for (LCMSDataSubset exludedSubset : exlude) { if (exludedSubset.isInSubset(scan)) { isOkToUnload = false; break; } } if (isOkToUnload) { scan.setSpectrum(null, false); } } } } }
public class class_name { private void unloadSpectraConditionally(NavigableMap<Integer, IScan> scansInSubsetByNumber, LCMSDataSubset subset, Set<LCMSDataSubset> exlude) { boolean isOkToUnload; for (IScan scan : scansInSubsetByNumber.values()) { if (subset.isInSubset(scan)) { isOkToUnload = true; // depends on control dependency: [if], data = [none] for (LCMSDataSubset exludedSubset : exlude) { if (exludedSubset.isInSubset(scan)) { isOkToUnload = false; // depends on control dependency: [if], data = [none] break; } } if (isOkToUnload) { scan.setSpectrum(null, false); // depends on control dependency: [if], data = [none] } } } } }
public class class_name { void section(int nclusters) { if (size() < nclusters) return; sectioned_clusters_ = new ArrayList<Cluster<K>>(nclusters); List<Document> centroids = new ArrayList<Document>(nclusters); // choose_randomly(nclusters, centroids); choose_smartly(nclusters, centroids); for (int i = 0; i < centroids.size(); i++) { Cluster<K> cluster = new Cluster<K>(); sectioned_clusters_.add(cluster); } for (Document<K> d : documents_) { double max_similarity = -1.0; int max_index = 0; for (int j = 0; j < centroids.size(); j++) { double similarity = SparseVector.inner_product(d.feature(), centroids.get(j).feature()); if (max_similarity < similarity) { max_similarity = similarity; max_index = j; } } sectioned_clusters_.get(max_index).add_document(d); } } }
public class class_name { void section(int nclusters) { if (size() < nclusters) return; sectioned_clusters_ = new ArrayList<Cluster<K>>(nclusters); List<Document> centroids = new ArrayList<Document>(nclusters); // choose_randomly(nclusters, centroids); choose_smartly(nclusters, centroids); for (int i = 0; i < centroids.size(); i++) { Cluster<K> cluster = new Cluster<K>(); sectioned_clusters_.add(cluster); // depends on control dependency: [for], data = [none] } for (Document<K> d : documents_) { double max_similarity = -1.0; int max_index = 0; for (int j = 0; j < centroids.size(); j++) { double similarity = SparseVector.inner_product(d.feature(), centroids.get(j).feature()); if (max_similarity < similarity) { max_similarity = similarity; // depends on control dependency: [if], data = [none] max_index = j; // depends on control dependency: [if], data = [none] } } sectioned_clusters_.get(max_index).add_document(d); // depends on control dependency: [for], data = [d] } } }
public class class_name { public static void main(String[] args) throws InterruptedException { StringBuilder errbuf = new StringBuilder(); try { PcapIf pcapIf = pcapIf(errbuf); Pcap.Builder builder = new Pcap.Builder() .source(pcapIf.getName()) .snaplen(SNAPLEN) .promiscuousMode(PROMISCUOUS) .timeout(TIMEOUT) .immediateMode(IMMEDIATE) .timestampType(TIMESTAMP_TYPE) .timestampPrecision(TIMESTAMP_PRECISION) .rfmon(RFMON) .enableNonBlock(nonBlock) .dataLinkType(LINK_TYPE) .fileName(FILE_NAME) .errbuf(errbuf) .pcapType(PCAP_TYPE); com.ardikars.jxnet.context.Application.run("application", "Application", "", builder); final Context context = com.ardikars.jxnet.context.Application.getApplicationContext(); LOGGER.info("Network Interface : " + pcapIf.getName()); LOGGER.info("Addresses : "); for (PcapAddr addr : pcapIf.getAddresses()) { if (addr.getAddr().getSaFamily() == SockAddr.Family.AF_INET) { LOGGER.info("\tAddress : " + Inet4Address.valueOf(addr.getAddr().getData())); LOGGER.info("\tNetwork : " + Inet4Address.valueOf(addr.getNetmask().getData())); } } if (Platforms.isWindows()) { try { byte[] hardwareAddress = Jxnet.FindHardwareAddress(pcapIf.getName()); LOGGER.info("\tMAC Address : " + MacAddress.valueOf(hardwareAddress)); } catch (PlatformNotSupportedException e) { LOGGER.warning(e.getMessage()); } catch (DeviceNotFoundException e) { LOGGER.warning(e.getMessage()); } } else { try { LOGGER.info("\tMAC Address : " + MacAddress.fromNicName(pcapIf.getName())); } catch (SocketException e) { LOGGER.warning(e.getMessage()); } } final ExecutorService pool = Executors.newCachedThreadPool(); Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { pool.shutdownNow(); } }); final int linktype = context.pcapDataLink().getValue(); context.pcapLoop(MAX_PACKET, new RawPcapHandler<String>() { @Override public void nextPacket(String user, int capLen, int len, int tvSec, long tvUsec, long memoryAddress) { Memory buffer = Memories.wrap(memoryAddress, len); buffer.writerIndex(buffer.capacity()); Packet packet; if (linktype == 1) { packet = Ethernet.newPacket(buffer); } else { packet = UnknownPacket.newPacket(buffer); } print(Tuple.of(PcapPktHdr.newInstance(capLen, len, tvSec, tvUsec), packet)); } }, "Jxnet!", pool); pool.shutdown(); pool.awaitTermination(WAIT_TIME_FOR_THREAD_TERMINATION, TimeUnit.MICROSECONDS); } catch (DeviceNotFoundException e) { LOGGER.warning(e.getMessage()); } } }
public class class_name { public static void main(String[] args) throws InterruptedException { StringBuilder errbuf = new StringBuilder(); try { PcapIf pcapIf = pcapIf(errbuf); Pcap.Builder builder = new Pcap.Builder() .source(pcapIf.getName()) .snaplen(SNAPLEN) .promiscuousMode(PROMISCUOUS) .timeout(TIMEOUT) .immediateMode(IMMEDIATE) .timestampType(TIMESTAMP_TYPE) .timestampPrecision(TIMESTAMP_PRECISION) .rfmon(RFMON) .enableNonBlock(nonBlock) .dataLinkType(LINK_TYPE) .fileName(FILE_NAME) .errbuf(errbuf) .pcapType(PCAP_TYPE); com.ardikars.jxnet.context.Application.run("application", "Application", "", builder); final Context context = com.ardikars.jxnet.context.Application.getApplicationContext(); LOGGER.info("Network Interface : " + pcapIf.getName()); LOGGER.info("Addresses : "); for (PcapAddr addr : pcapIf.getAddresses()) { if (addr.getAddr().getSaFamily() == SockAddr.Family.AF_INET) { LOGGER.info("\tAddress : " + Inet4Address.valueOf(addr.getAddr().getData())); // depends on control dependency: [if], data = [none] LOGGER.info("\tNetwork : " + Inet4Address.valueOf(addr.getNetmask().getData())); // depends on control dependency: [if], data = [none] } } if (Platforms.isWindows()) { try { byte[] hardwareAddress = Jxnet.FindHardwareAddress(pcapIf.getName()); LOGGER.info("\tMAC Address : " + MacAddress.valueOf(hardwareAddress)); // depends on control dependency: [try], data = [none] } catch (PlatformNotSupportedException e) { LOGGER.warning(e.getMessage()); } catch (DeviceNotFoundException e) { // depends on control dependency: [catch], data = [none] LOGGER.warning(e.getMessage()); } // depends on control dependency: [catch], data = [none] } else { try { LOGGER.info("\tMAC Address : " + MacAddress.fromNicName(pcapIf.getName())); // depends on control dependency: [try], data = [none] } catch (SocketException e) { LOGGER.warning(e.getMessage()); } // depends on control dependency: [catch], data = [none] } final ExecutorService pool = Executors.newCachedThreadPool(); Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { pool.shutdownNow(); } }); final int linktype = context.pcapDataLink().getValue(); context.pcapLoop(MAX_PACKET, new RawPcapHandler<String>() { @Override public void nextPacket(String user, int capLen, int len, int tvSec, long tvUsec, long memoryAddress) { Memory buffer = Memories.wrap(memoryAddress, len); buffer.writerIndex(buffer.capacity()); Packet packet; if (linktype == 1) { packet = Ethernet.newPacket(buffer); // depends on control dependency: [if], data = [none] } else { packet = UnknownPacket.newPacket(buffer); // depends on control dependency: [if], data = [none] } print(Tuple.of(PcapPktHdr.newInstance(capLen, len, tvSec, tvUsec), packet)); } }, "Jxnet!", pool); pool.shutdown(); pool.awaitTermination(WAIT_TIME_FOR_THREAD_TERMINATION, TimeUnit.MICROSECONDS); } catch (DeviceNotFoundException e) { LOGGER.warning(e.getMessage()); } } }
public class class_name { private int inOrderAnalyse(StructuralNode node) { int subtreeNodes = 0; if (isStop) { return 0; } if (node == null) { return 0; } // analyse entity if not root and not leaf. // Leaf is not analysed because only folder entity is used to determine if path exist. try { if (!node.isRoot()) { if (!node.isLeaf() || node.isLeaf() && node.getParent().isRoot()) { analyse(node); } else { //ZAP: it's a Leaf then no children are available return 1; } } } catch (Exception e) { } Iterator<StructuralNode> iter = node.getChildIterator(); while (iter.hasNext()) { subtreeNodes += inOrderAnalyse(iter.next()); } return subtreeNodes + 1; } }
public class class_name { private int inOrderAnalyse(StructuralNode node) { int subtreeNodes = 0; if (isStop) { return 0; // depends on control dependency: [if], data = [none] } if (node == null) { return 0; // depends on control dependency: [if], data = [none] } // analyse entity if not root and not leaf. // Leaf is not analysed because only folder entity is used to determine if path exist. try { if (!node.isRoot()) { if (!node.isLeaf() || node.isLeaf() && node.getParent().isRoot()) { analyse(node); // depends on control dependency: [if], data = [none] } else { //ZAP: it's a Leaf then no children are available return 1; // depends on control dependency: [if], data = [none] } } } catch (Exception e) { } // depends on control dependency: [catch], data = [none] Iterator<StructuralNode> iter = node.getChildIterator(); while (iter.hasNext()) { subtreeNodes += inOrderAnalyse(iter.next()); // depends on control dependency: [while], data = [none] } return subtreeNodes + 1; } }
public class class_name { private ParseTree parseMemberExpressionNoNew() { SourcePosition start = getTreeStartLocation(); ParseTree operand; if (peekAsyncFunctionStart()) { operand = parseAsyncFunctionExpression(); } else if (peekFunction()) { operand = parseFunctionExpression(); } else { operand = parsePrimaryExpression(); } while (peekMemberExpressionSuffix()) { switch (peekType()) { case OPEN_SQUARE: eat(TokenType.OPEN_SQUARE); ParseTree member = parseExpression(); eat(TokenType.CLOSE_SQUARE); operand = new MemberLookupExpressionTree( getTreeLocation(start), operand, member); break; case PERIOD: eat(TokenType.PERIOD); IdentifierToken id = eatIdOrKeywordAsId(); operand = new MemberExpressionTree(getTreeLocation(start), operand, id); break; case NO_SUBSTITUTION_TEMPLATE: case TEMPLATE_HEAD: operand = parseTemplateLiteral(operand); break; default: throw new RuntimeException("unreachable"); } } return operand; } }
public class class_name { private ParseTree parseMemberExpressionNoNew() { SourcePosition start = getTreeStartLocation(); ParseTree operand; if (peekAsyncFunctionStart()) { operand = parseAsyncFunctionExpression(); // depends on control dependency: [if], data = [none] } else if (peekFunction()) { operand = parseFunctionExpression(); // depends on control dependency: [if], data = [none] } else { operand = parsePrimaryExpression(); // depends on control dependency: [if], data = [none] } while (peekMemberExpressionSuffix()) { switch (peekType()) { case OPEN_SQUARE: eat(TokenType.OPEN_SQUARE); ParseTree member = parseExpression(); eat(TokenType.CLOSE_SQUARE); operand = new MemberLookupExpressionTree( getTreeLocation(start), operand, member); break; case PERIOD: eat(TokenType.PERIOD); IdentifierToken id = eatIdOrKeywordAsId(); operand = new MemberExpressionTree(getTreeLocation(start), operand, id); break; case NO_SUBSTITUTION_TEMPLATE: case TEMPLATE_HEAD: operand = parseTemplateLiteral(operand); break; default: throw new RuntimeException("unreachable"); } } return operand; } }
public class class_name { @Override public INDArray linspace(int lower, int upper, int num) { double[] data = new double[num]; for (int i = 0; i < num; i++) { double t = (double) i / (num - 1); data[i] = lower * (1 - t) + t * upper; } //edge case for scalars INDArray ret = Nd4j.create(data.length); if (ret.isScalar()) return ret; for (int i = 0; i < ret.length(); i++) ret.putScalar(i, data[i]); return ret; } }
public class class_name { @Override public INDArray linspace(int lower, int upper, int num) { double[] data = new double[num]; for (int i = 0; i < num; i++) { double t = (double) i / (num - 1); data[i] = lower * (1 - t) + t * upper; // depends on control dependency: [for], data = [i] } //edge case for scalars INDArray ret = Nd4j.create(data.length); if (ret.isScalar()) return ret; for (int i = 0; i < ret.length(); i++) ret.putScalar(i, data[i]); return ret; } }
public class class_name { private void ensureBuiltInDefaultQPContainsRules(DbSession dbSession) { Map<String, RulesProfileDto> rulesProfilesByLanguage = dbClient.qualityProfileDao().selectBuiltInRuleProfilesWithActiveRules(dbSession).stream() .collect(toMap(RulesProfileDto::getLanguage, Function.identity(), (oldValue, newValue) -> oldValue)); dbClient.qualityProfileDao().selectDefaultBuiltInProfilesWithoutActiveRules(dbSession, rulesProfilesByLanguage.keySet()) .forEach(qp -> { RulesProfileDto rulesProfile = rulesProfilesByLanguage.get(qp.getLanguage()); if (rulesProfile == null) { return; } QProfileDto qualityProfile = dbClient.qualityProfileDao().selectByRuleProfileUuid(dbSession, qp.getOrganizationUuid(), rulesProfile.getKee()); if (qualityProfile == null) { return; } Set<String> uuids = dbClient.defaultQProfileDao().selectExistingQProfileUuids(dbSession, qp.getOrganizationUuid(), Collections.singleton(qp.getKee())); dbClient.defaultQProfileDao().deleteByQProfileUuids(dbSession, uuids); dbClient.defaultQProfileDao().insertOrUpdate(dbSession, new DefaultQProfileDto() .setQProfileUuid(qualityProfile.getKee()) .setLanguage(qp.getLanguage()) .setOrganizationUuid(qp.getOrganizationUuid()) ); LOGGER.info("Default built-in quality profile for language [{}] has been updated from [{}] to [{}] since previous default does not have active rules.", qp.getLanguage(), qp.getName(), rulesProfile.getName()); }); dbSession.commit(); } }
public class class_name { private void ensureBuiltInDefaultQPContainsRules(DbSession dbSession) { Map<String, RulesProfileDto> rulesProfilesByLanguage = dbClient.qualityProfileDao().selectBuiltInRuleProfilesWithActiveRules(dbSession).stream() .collect(toMap(RulesProfileDto::getLanguage, Function.identity(), (oldValue, newValue) -> oldValue)); dbClient.qualityProfileDao().selectDefaultBuiltInProfilesWithoutActiveRules(dbSession, rulesProfilesByLanguage.keySet()) .forEach(qp -> { RulesProfileDto rulesProfile = rulesProfilesByLanguage.get(qp.getLanguage()); if (rulesProfile == null) { return; // depends on control dependency: [if], data = [none] } QProfileDto qualityProfile = dbClient.qualityProfileDao().selectByRuleProfileUuid(dbSession, qp.getOrganizationUuid(), rulesProfile.getKee()); if (qualityProfile == null) { return; // depends on control dependency: [if], data = [none] } Set<String> uuids = dbClient.defaultQProfileDao().selectExistingQProfileUuids(dbSession, qp.getOrganizationUuid(), Collections.singleton(qp.getKee())); dbClient.defaultQProfileDao().deleteByQProfileUuids(dbSession, uuids); dbClient.defaultQProfileDao().insertOrUpdate(dbSession, new DefaultQProfileDto() .setQProfileUuid(qualityProfile.getKee()) .setLanguage(qp.getLanguage()) .setOrganizationUuid(qp.getOrganizationUuid()) ); LOGGER.info("Default built-in quality profile for language [{}] has been updated from [{}] to [{}] since previous default does not have active rules.", qp.getLanguage(), qp.getName(), rulesProfile.getName()); }); dbSession.commit(); } }
public class class_name { private void removePropertyStrings(Service s) { String type = s.getType(); String algorithm = s.getAlgorithm(); // use super() to avoid permission check and other processing super.remove(type + "." + algorithm); for (String alias : s.getAliases()) { super.remove(ALIAS_PREFIX + type + "." + alias); } for (Map.Entry<UString,String> entry : s.attributes.entrySet()) { String key = type + "." + algorithm + " " + entry.getKey(); super.remove(key); } if (registered) { Security.increaseVersion(); } } }
public class class_name { private void removePropertyStrings(Service s) { String type = s.getType(); String algorithm = s.getAlgorithm(); // use super() to avoid permission check and other processing super.remove(type + "." + algorithm); for (String alias : s.getAliases()) { super.remove(ALIAS_PREFIX + type + "." + alias); // depends on control dependency: [for], data = [alias] } for (Map.Entry<UString,String> entry : s.attributes.entrySet()) { String key = type + "." + algorithm + " " + entry.getKey(); super.remove(key); // depends on control dependency: [for], data = [none] } if (registered) { Security.increaseVersion(); // depends on control dependency: [if], data = [none] } } }
public class class_name { @Controller(next = "askWhetherToRepeat") public void askTimeForMeeting(WebSocketSession session, Event event) { if (event.getText().contains("yes")) { reply(session, event, "Okay. Would you like me to set a reminder for you?"); nextConversation(event); // jump to next question in conversation } else { reply(session, event, "No problem. You can always schedule one with 'setup meeting' command."); stopConversation(event); // stop conversation only if user says no } } }
public class class_name { @Controller(next = "askWhetherToRepeat") public void askTimeForMeeting(WebSocketSession session, Event event) { if (event.getText().contains("yes")) { reply(session, event, "Okay. Would you like me to set a reminder for you?"); // depends on control dependency: [if], data = [none] nextConversation(event); // jump to next question in conversation // depends on control dependency: [if], data = [none] } else { reply(session, event, "No problem. You can always schedule one with 'setup meeting' command."); // depends on control dependency: [if], data = [none] stopConversation(event); // stop conversation only if user says no // depends on control dependency: [if], data = [none] } } }
public class class_name { public EasyJaSubDictionaryEntry getEntry(String word) { if (word == null || word.length() == 0) { throw new RuntimeException("Invalid word"); } EasyJaSubTrie.Value<EasyJaSubDictionaryEntry> value = trie .get(new CharacterIterator(word)); if (value == null) { return null; } return value.getValue(); } }
public class class_name { public EasyJaSubDictionaryEntry getEntry(String word) { if (word == null || word.length() == 0) { throw new RuntimeException("Invalid word"); } EasyJaSubTrie.Value<EasyJaSubDictionaryEntry> value = trie .get(new CharacterIterator(word)); if (value == null) { return null; // depends on control dependency: [if], data = [none] } return value.getValue(); } }
public class class_name { public static <T> void bindExtras(T target, Intent intent) { @SuppressWarnings("unchecked") IntentBinding<T> binding = (IntentBinding<T>) getIntentBinding(target.getClass().getClassLoader(), target.getClass()); if (binding != null) { binding.bindExtras(target, intent); } } }
public class class_name { public static <T> void bindExtras(T target, Intent intent) { @SuppressWarnings("unchecked") IntentBinding<T> binding = (IntentBinding<T>) getIntentBinding(target.getClass().getClassLoader(), target.getClass()); if (binding != null) { binding.bindExtras(target, intent); // depends on control dependency: [if], data = [none] } } }
public class class_name { private int readTypeAnnotationTarget(final Context context, final int typeAnnotationOffset) { int currentOffset = typeAnnotationOffset; // Parse and store the target_type structure. int targetType = readInt(typeAnnotationOffset); switch (targetType >>> 24) { case TypeReference.CLASS_TYPE_PARAMETER: case TypeReference.METHOD_TYPE_PARAMETER: case TypeReference.METHOD_FORMAL_PARAMETER: targetType &= 0xFFFF0000; currentOffset += 2; break; case TypeReference.FIELD: case TypeReference.METHOD_RETURN: case TypeReference.METHOD_RECEIVER: targetType &= 0xFF000000; currentOffset += 1; break; case TypeReference.LOCAL_VARIABLE: case TypeReference.RESOURCE_VARIABLE: targetType &= 0xFF000000; int tableLength = readUnsignedShort(currentOffset + 1); currentOffset += 3; context.currentLocalVariableAnnotationRangeStarts = new Label[tableLength]; context.currentLocalVariableAnnotationRangeEnds = new Label[tableLength]; context.currentLocalVariableAnnotationRangeIndices = new int[tableLength]; for (int i = 0; i < tableLength; ++i) { int startPc = readUnsignedShort(currentOffset); int length = readUnsignedShort(currentOffset + 2); int index = readUnsignedShort(currentOffset + 4); currentOffset += 6; context.currentLocalVariableAnnotationRangeStarts[i] = createLabel(startPc, context.currentMethodLabels); context.currentLocalVariableAnnotationRangeEnds[i] = createLabel(startPc + length, context.currentMethodLabels); context.currentLocalVariableAnnotationRangeIndices[i] = index; } break; case TypeReference.CAST: case TypeReference.CONSTRUCTOR_INVOCATION_TYPE_ARGUMENT: case TypeReference.METHOD_INVOCATION_TYPE_ARGUMENT: case TypeReference.CONSTRUCTOR_REFERENCE_TYPE_ARGUMENT: case TypeReference.METHOD_REFERENCE_TYPE_ARGUMENT: targetType &= 0xFF0000FF; currentOffset += 4; break; case TypeReference.CLASS_EXTENDS: case TypeReference.CLASS_TYPE_PARAMETER_BOUND: case TypeReference.METHOD_TYPE_PARAMETER_BOUND: case TypeReference.THROWS: case TypeReference.EXCEPTION_PARAMETER: targetType &= 0xFFFFFF00; currentOffset += 3; break; case TypeReference.INSTANCEOF: case TypeReference.NEW: case TypeReference.CONSTRUCTOR_REFERENCE: case TypeReference.METHOD_REFERENCE: targetType &= 0xFF000000; currentOffset += 3; break; default: throw new IllegalArgumentException(); } context.currentTypeAnnotationTarget = targetType; // Parse and store the target_path structure. int pathLength = readByte(currentOffset); context.currentTypeAnnotationTargetPath = pathLength == 0 ? null : new TypePath(b, currentOffset); // Return the start offset of the rest of the type_annotation structure. return currentOffset + 1 + 2 * pathLength; } }
public class class_name { private int readTypeAnnotationTarget(final Context context, final int typeAnnotationOffset) { int currentOffset = typeAnnotationOffset; // Parse and store the target_type structure. int targetType = readInt(typeAnnotationOffset); switch (targetType >>> 24) { case TypeReference.CLASS_TYPE_PARAMETER: case TypeReference.METHOD_TYPE_PARAMETER: case TypeReference.METHOD_FORMAL_PARAMETER: targetType &= 0xFFFF0000; currentOffset += 2; break; case TypeReference.FIELD: case TypeReference.METHOD_RETURN: case TypeReference.METHOD_RECEIVER: targetType &= 0xFF000000; currentOffset += 1; break; case TypeReference.LOCAL_VARIABLE: case TypeReference.RESOURCE_VARIABLE: targetType &= 0xFF000000; int tableLength = readUnsignedShort(currentOffset + 1); currentOffset += 3; context.currentLocalVariableAnnotationRangeStarts = new Label[tableLength]; context.currentLocalVariableAnnotationRangeEnds = new Label[tableLength]; context.currentLocalVariableAnnotationRangeIndices = new int[tableLength]; for (int i = 0; i < tableLength; ++i) { int startPc = readUnsignedShort(currentOffset); int length = readUnsignedShort(currentOffset + 2); int index = readUnsignedShort(currentOffset + 4); currentOffset += 6; // depends on control dependency: [for], data = [none] context.currentLocalVariableAnnotationRangeStarts[i] = createLabel(startPc, context.currentMethodLabels); // depends on control dependency: [for], data = [i] context.currentLocalVariableAnnotationRangeEnds[i] = createLabel(startPc + length, context.currentMethodLabels); // depends on control dependency: [for], data = [i] context.currentLocalVariableAnnotationRangeIndices[i] = index; // depends on control dependency: [for], data = [i] } break; case TypeReference.CAST: case TypeReference.CONSTRUCTOR_INVOCATION_TYPE_ARGUMENT: case TypeReference.METHOD_INVOCATION_TYPE_ARGUMENT: case TypeReference.CONSTRUCTOR_REFERENCE_TYPE_ARGUMENT: case TypeReference.METHOD_REFERENCE_TYPE_ARGUMENT: targetType &= 0xFF0000FF; currentOffset += 4; break; case TypeReference.CLASS_EXTENDS: case TypeReference.CLASS_TYPE_PARAMETER_BOUND: case TypeReference.METHOD_TYPE_PARAMETER_BOUND: case TypeReference.THROWS: case TypeReference.EXCEPTION_PARAMETER: targetType &= 0xFFFFFF00; currentOffset += 3; break; case TypeReference.INSTANCEOF: case TypeReference.NEW: case TypeReference.CONSTRUCTOR_REFERENCE: case TypeReference.METHOD_REFERENCE: targetType &= 0xFF000000; currentOffset += 3; break; default: throw new IllegalArgumentException(); } context.currentTypeAnnotationTarget = targetType; // Parse and store the target_path structure. int pathLength = readByte(currentOffset); context.currentTypeAnnotationTargetPath = pathLength == 0 ? null : new TypePath(b, currentOffset); // Return the start offset of the rest of the type_annotation structure. return currentOffset + 1 + 2 * pathLength; } }
public class class_name { private <T> ImmutableList<Case<T>> compactCases(ImmutableList<Case<T>> cases, T defaultCaseSpec) { // Determine the fallback/other case value. ImmutableList<SoyMsgPart> defaultValue = null; for (Case<T> caseAndValue : cases) { if (Objects.equals(caseAndValue.spec(), defaultCaseSpec)) { defaultValue = caseAndValue.parts(); break; } } ImmutableList.Builder<Case<T>> builder = ImmutableList.builder(); for (Case<T> caseAndValue : cases) { // See if this case is the same as the default/other case, but isn't itself the default/other // case, and can be pruned. if (defaultValue != null && !Objects.equals(caseAndValue.spec(), defaultCaseSpec) && defaultValue.equals(caseAndValue.parts())) { continue; } // Intern the case value, since they tend to be very common among templates. For select, // they tend to be strings like "male" or "female", and for plurals, it tends to be one // of the few in the enum. builder.add( Case.create( caseAndValue.spec() != null ? intern(caseAndValue.spec()) : null, compactParts(caseAndValue.parts()))); } return builder.build(); } }
public class class_name { private <T> ImmutableList<Case<T>> compactCases(ImmutableList<Case<T>> cases, T defaultCaseSpec) { // Determine the fallback/other case value. ImmutableList<SoyMsgPart> defaultValue = null; for (Case<T> caseAndValue : cases) { if (Objects.equals(caseAndValue.spec(), defaultCaseSpec)) { defaultValue = caseAndValue.parts(); // depends on control dependency: [if], data = [none] break; } } ImmutableList.Builder<Case<T>> builder = ImmutableList.builder(); for (Case<T> caseAndValue : cases) { // See if this case is the same as the default/other case, but isn't itself the default/other // case, and can be pruned. if (defaultValue != null && !Objects.equals(caseAndValue.spec(), defaultCaseSpec) && defaultValue.equals(caseAndValue.parts())) { continue; } // Intern the case value, since they tend to be very common among templates. For select, // they tend to be strings like "male" or "female", and for plurals, it tends to be one // of the few in the enum. builder.add( Case.create( caseAndValue.spec() != null ? intern(caseAndValue.spec()) : null, compactParts(caseAndValue.parts()))); // depends on control dependency: [for], data = [none] } return builder.build(); } }
public class class_name { public static void createNewFile(@NonNull final File file, final boolean overwrite) throws IOException { Condition.INSTANCE.ensureNotNull(file, "The file may not be null"); boolean result = file.createNewFile(); if (!result) { if (overwrite) { try { delete(file); createNewFile(file, false); } catch (IOException e) { throw new IOException("Failed to overwrite file \"" + file + "\""); } } else if (file.exists()) { throw new IOException("File \"" + file + "\" does already exist"); } else { throw new IllegalArgumentException("The file must not be a directory"); } } } }
public class class_name { public static void createNewFile(@NonNull final File file, final boolean overwrite) throws IOException { Condition.INSTANCE.ensureNotNull(file, "The file may not be null"); boolean result = file.createNewFile(); if (!result) { if (overwrite) { try { delete(file); // depends on control dependency: [try], data = [none] createNewFile(file, false); // depends on control dependency: [try], data = [none] } catch (IOException e) { throw new IOException("Failed to overwrite file \"" + file + "\""); } // depends on control dependency: [catch], data = [none] } else if (file.exists()) { throw new IOException("File \"" + file + "\" does already exist"); } else { throw new IllegalArgumentException("The file must not be a directory"); } } } }
public class class_name { public static void downloadFile(URL url, File destination) throws IOException { int count = 0; int maxTries = 10; int timeout = 60000; //60 sec File tempFile = File.createTempFile(getFilePrefix(destination), "." + getFileExtension(destination)); // Took following recipe from stackoverflow: // http://stackoverflow.com/questions/921262/how-to-download-and-save-a-file-from-internet-using-java // It seems to be the most efficient way to transfer a file // See: http://docs.oracle.com/javase/7/docs/api/java/nio/channels/FileChannel.html ReadableByteChannel rbc = null; FileOutputStream fos = null; while (true) { try { URLConnection connection = prepareURLConnection(url.toString(), timeout); connection.connect(); InputStream inputStream = connection.getInputStream(); rbc = Channels.newChannel(inputStream); fos = new FileOutputStream(tempFile); fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); break; } catch (SocketTimeoutException e) { if (++count == maxTries) throw e; } finally { if (rbc != null) { rbc.close(); } if (fos != null) { fos.close(); } } } logger.debug("Copying temp file {} to final location {}", tempFile, destination); copy(tempFile, destination); // delete the tmp file tempFile.delete(); } }
public class class_name { public static void downloadFile(URL url, File destination) throws IOException { int count = 0; int maxTries = 10; int timeout = 60000; //60 sec File tempFile = File.createTempFile(getFilePrefix(destination), "." + getFileExtension(destination)); // Took following recipe from stackoverflow: // http://stackoverflow.com/questions/921262/how-to-download-and-save-a-file-from-internet-using-java // It seems to be the most efficient way to transfer a file // See: http://docs.oracle.com/javase/7/docs/api/java/nio/channels/FileChannel.html ReadableByteChannel rbc = null; FileOutputStream fos = null; while (true) { try { URLConnection connection = prepareURLConnection(url.toString(), timeout); connection.connect(); // depends on control dependency: [try], data = [none] InputStream inputStream = connection.getInputStream(); rbc = Channels.newChannel(inputStream); // depends on control dependency: [try], data = [none] fos = new FileOutputStream(tempFile); // depends on control dependency: [try], data = [none] fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); // depends on control dependency: [try], data = [none] break; } catch (SocketTimeoutException e) { if (++count == maxTries) throw e; } finally { // depends on control dependency: [catch], data = [none] if (rbc != null) { rbc.close(); // depends on control dependency: [if], data = [none] } if (fos != null) { fos.close(); // depends on control dependency: [if], data = [none] } } } logger.debug("Copying temp file {} to final location {}", tempFile, destination); copy(tempFile, destination); // delete the tmp file tempFile.delete(); } }
public class class_name { public int compare(Alternative ab) { if (production != ab.production) { throw new IllegalArgumentException(); } // TODO: compare two ups if (resultOfs != -1 || ab.resultOfs != -1) { return NE; } if (argsOfs.size() == 0 && ab.argsOfs.size() == 0) { return EQ; } if (argsOfs.size() == 0 || ab.argsOfs.size() == 0) { return ALT; } if (max(argsOfs) < min(ab.argsOfs)) { return LT; } if (min(argsOfs) > max(ab.argsOfs)) { return GT; } if (argsOfs.size() != 1 || ab.argsOfs.size() != 1) { return NE; } else { if (argsOfs.get(0) != ab.argsOfs.get(0)) { throw new IllegalStateException(); } return EQ; } } }
public class class_name { public int compare(Alternative ab) { if (production != ab.production) { throw new IllegalArgumentException(); } // TODO: compare two ups if (resultOfs != -1 || ab.resultOfs != -1) { return NE; // depends on control dependency: [if], data = [none] } if (argsOfs.size() == 0 && ab.argsOfs.size() == 0) { return EQ; // depends on control dependency: [if], data = [none] } if (argsOfs.size() == 0 || ab.argsOfs.size() == 0) { return ALT; // depends on control dependency: [if], data = [none] } if (max(argsOfs) < min(ab.argsOfs)) { return LT; // depends on control dependency: [if], data = [none] } if (min(argsOfs) > max(ab.argsOfs)) { return GT; // depends on control dependency: [if], data = [none] } if (argsOfs.size() != 1 || ab.argsOfs.size() != 1) { return NE; // depends on control dependency: [if], data = [none] } else { if (argsOfs.get(0) != ab.argsOfs.get(0)) { throw new IllegalStateException(); } return EQ; // depends on control dependency: [if], data = [none] } } }
public class class_name { private void markPendingInitialization(JvmDeclaredTypeImplCustom type) { type.setPendingInitialization(true); for (JvmMember member : type.basicGetMembers()) { if (member instanceof JvmDeclaredTypeImplCustom) { markPendingInitialization((JvmDeclaredTypeImplCustom) member); } } } }
public class class_name { private void markPendingInitialization(JvmDeclaredTypeImplCustom type) { type.setPendingInitialization(true); for (JvmMember member : type.basicGetMembers()) { if (member instanceof JvmDeclaredTypeImplCustom) { markPendingInitialization((JvmDeclaredTypeImplCustom) member); // depends on control dependency: [if], data = [none] } } } }
public class class_name { protected void updateClassnames(HashMap<String,List<String>> list, String superclass, List<String> names) { if (!list.containsKey(superclass)) { list.put(superclass, names); } else { for (String name: names) { if (!list.get(superclass).contains(name)) list.get(superclass).add(name); } } } }
public class class_name { protected void updateClassnames(HashMap<String,List<String>> list, String superclass, List<String> names) { if (!list.containsKey(superclass)) { list.put(superclass, names); // depends on control dependency: [if], data = [none] } else { for (String name: names) { if (!list.get(superclass).contains(name)) list.get(superclass).add(name); } } } }
public class class_name { public static MeterValue valueOf(String value) { if (isNumber(value)) { return new MeterValue(Long.parseLong(value)); } return new MeterValue(durationConverter.convert(value)); } }
public class class_name { public static MeterValue valueOf(String value) { if (isNumber(value)) { return new MeterValue(Long.parseLong(value)); // depends on control dependency: [if], data = [none] } return new MeterValue(durationConverter.convert(value)); } }
public class class_name { @InterfaceAudience.Public public boolean isDeleted() { try { return getCurrentRevision() == null && getLeafRevisions().size() > 0; } catch (CouchbaseLiteException e) { throw new RuntimeException(e); } } }
public class class_name { @InterfaceAudience.Public public boolean isDeleted() { try { return getCurrentRevision() == null && getLeafRevisions().size() > 0; // depends on control dependency: [try], data = [none] } catch (CouchbaseLiteException e) { throw new RuntimeException(e); } // depends on control dependency: [catch], data = [none] } }
public class class_name { public static int getNCNameSuffixIndex(CharSequence s) { // identify bnode labels and do not try to split them if (s.length() > 1 && s.charAt(0) == '_' && s.charAt(1) == ':') { return -1; } int index = -1; for (int i = s.length() - 1; i > -1; i--) { if (!Character.isLowSurrogate(s.charAt(i))) { int codePoint = Character.codePointAt(s, i); if (isNCNameStartChar(codePoint)) { index = i; } if (!isNCNameChar(codePoint)) { break; } } } return index; } }
public class class_name { public static int getNCNameSuffixIndex(CharSequence s) { // identify bnode labels and do not try to split them if (s.length() > 1 && s.charAt(0) == '_' && s.charAt(1) == ':') { return -1; // depends on control dependency: [if], data = [none] } int index = -1; for (int i = s.length() - 1; i > -1; i--) { if (!Character.isLowSurrogate(s.charAt(i))) { int codePoint = Character.codePointAt(s, i); if (isNCNameStartChar(codePoint)) { index = i; // depends on control dependency: [if], data = [none] } if (!isNCNameChar(codePoint)) { break; } } } return index; } }
public class class_name { public void marshall(SetCognitoEventsRequest setCognitoEventsRequest, ProtocolMarshaller protocolMarshaller) { if (setCognitoEventsRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(setCognitoEventsRequest.getIdentityPoolId(), IDENTITYPOOLID_BINDING); protocolMarshaller.marshall(setCognitoEventsRequest.getEvents(), EVENTS_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
public class class_name { public void marshall(SetCognitoEventsRequest setCognitoEventsRequest, ProtocolMarshaller protocolMarshaller) { if (setCognitoEventsRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(setCognitoEventsRequest.getIdentityPoolId(), IDENTITYPOOLID_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(setCognitoEventsRequest.getEvents(), EVENTS_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 java.util.List<LoadBalancerDescription> getLoadBalancerDescriptions() { if (loadBalancerDescriptions == null) { loadBalancerDescriptions = new com.amazonaws.internal.SdkInternalList<LoadBalancerDescription>(); } return loadBalancerDescriptions; } }
public class class_name { public java.util.List<LoadBalancerDescription> getLoadBalancerDescriptions() { if (loadBalancerDescriptions == null) { loadBalancerDescriptions = new com.amazonaws.internal.SdkInternalList<LoadBalancerDescription>(); // depends on control dependency: [if], data = [none] } return loadBalancerDescriptions; } }
public class class_name { public static <T> T getValueOfCertainColumnOfCertainRecord(String sql, Object... arg) { List<T> list = DBUtils.getValueOfCertainColumnOfAllRecord(sql, arg); if (list.isEmpty()) { return null; } return list.get(0); } }
public class class_name { public static <T> T getValueOfCertainColumnOfCertainRecord(String sql, Object... arg) { List<T> list = DBUtils.getValueOfCertainColumnOfAllRecord(sql, arg); if (list.isEmpty()) { return null; // depends on control dependency: [if], data = [none] } return list.get(0); } }
public class class_name { static BaseDoubleColumnValueSelector makeColumnValueSelectorWithDoubleDefault( final ColumnSelectorFactory metricFactory, final ExprMacroTable macroTable, @Nullable final String fieldName, @Nullable final String fieldExpression, final double nullValue ) { if ((fieldName == null) == (fieldExpression == null)) { throw new IllegalArgumentException("Only one of fieldName and fieldExpression should be non-null"); } if (fieldName != null) { return metricFactory.makeColumnValueSelector(fieldName); } else { final Expr expr = Parser.parse(fieldExpression, macroTable); final ColumnValueSelector<ExprEval> baseSelector = ExpressionSelectors.makeExprEvalSelector(metricFactory, expr); class ExpressionDoubleColumnSelector implements DoubleColumnSelector { @Override public double getDouble() { final ExprEval exprEval = baseSelector.getObject(); return exprEval.isNumericNull() ? nullValue : exprEval.asDouble(); } @Override public void inspectRuntimeShape(RuntimeShapeInspector inspector) { inspector.visit("baseSelector", baseSelector); } @Override public boolean isNull() { final ExprEval exprEval = baseSelector.getObject(); return exprEval == null || exprEval.isNumericNull(); } } return new ExpressionDoubleColumnSelector(); } } }
public class class_name { static BaseDoubleColumnValueSelector makeColumnValueSelectorWithDoubleDefault( final ColumnSelectorFactory metricFactory, final ExprMacroTable macroTable, @Nullable final String fieldName, @Nullable final String fieldExpression, final double nullValue ) { if ((fieldName == null) == (fieldExpression == null)) { throw new IllegalArgumentException("Only one of fieldName and fieldExpression should be non-null"); } if (fieldName != null) { return metricFactory.makeColumnValueSelector(fieldName); // depends on control dependency: [if], data = [(fieldName] } else { final Expr expr = Parser.parse(fieldExpression, macroTable); final ColumnValueSelector<ExprEval> baseSelector = ExpressionSelectors.makeExprEvalSelector(metricFactory, expr); class ExpressionDoubleColumnSelector implements DoubleColumnSelector { @Override public double getDouble() { final ExprEval exprEval = baseSelector.getObject(); return exprEval.isNumericNull() ? nullValue : exprEval.asDouble(); } @Override public void inspectRuntimeShape(RuntimeShapeInspector inspector) { inspector.visit("baseSelector", baseSelector); } @Override public boolean isNull() { final ExprEval exprEval = baseSelector.getObject(); return exprEval == null || exprEval.isNumericNull(); } } return new ExpressionDoubleColumnSelector(); // depends on control dependency: [if], data = [none] } } }
public class class_name { public void switchToFrameAccordingToAnnotationParams(Method annotatedMethod) { RequireSwitchingToFrame annotation = getAnnotationData(annotatedMethod); int frameIndex = annotation.index(); LocatorType locatorType = annotation.locatorType(); String locatorValue = annotation.locatorValue(); String nameOrId = annotation.frameNameOrId(); if (nameOrId.length() > 0) { String xpathLocator = String.format("//*[@name='%1$s' or @id='%1$s']", nameOrId); SeleniumUtils.findElementWithTimeout(driver, By.xpath(xpathLocator), 20); driver.switchTo().frame(nameOrId); } else if (locatorType != LocatorType.NONE && locatorValue.length() > 0) { switchToFrameByWebElement(locatorType, locatorValue); } else { driver.switchTo().frame(frameIndex); } } }
public class class_name { public void switchToFrameAccordingToAnnotationParams(Method annotatedMethod) { RequireSwitchingToFrame annotation = getAnnotationData(annotatedMethod); int frameIndex = annotation.index(); LocatorType locatorType = annotation.locatorType(); String locatorValue = annotation.locatorValue(); String nameOrId = annotation.frameNameOrId(); if (nameOrId.length() > 0) { String xpathLocator = String.format("//*[@name='%1$s' or @id='%1$s']", nameOrId); SeleniumUtils.findElementWithTimeout(driver, By.xpath(xpathLocator), 20); driver.switchTo().frame(nameOrId); // depends on control dependency: [if], data = [none] } else if (locatorType != LocatorType.NONE && locatorValue.length() > 0) { switchToFrameByWebElement(locatorType, locatorValue); // depends on control dependency: [if], data = [(locatorType] } else { driver.switchTo().frame(frameIndex); // depends on control dependency: [if], data = [none] } } }
public class class_name { public Record openHeaderRecord() { if (m_recHeader == null) { Record record = this.getMainRecord(); try { m_recHeader = (Record)record.clone(); // Do not add to screen's list - will mix with other file } catch (CloneNotSupportedException ex) { ex.printStackTrace(); } // Do not clone the listeners, while (m_recHeader.getListener() != null) { m_recHeader.removeListener(m_recHeader.getListener(), true); } m_recHeader.addListeners(); // Just use the standard listeners } return m_recHeader; } }
public class class_name { public Record openHeaderRecord() { if (m_recHeader == null) { Record record = this.getMainRecord(); try { m_recHeader = (Record)record.clone(); // Do not add to screen's list - will mix with other file // depends on control dependency: [try], data = [none] } catch (CloneNotSupportedException ex) { ex.printStackTrace(); } // depends on control dependency: [catch], data = [none] // Do not clone the listeners, while (m_recHeader.getListener() != null) { m_recHeader.removeListener(m_recHeader.getListener(), true); // depends on control dependency: [while], data = [(m_recHeader.getListener()] } m_recHeader.addListeners(); // Just use the standard listeners // depends on control dependency: [if], data = [none] } return m_recHeader; } }
public class class_name { public synchronized void notifySSLConfigChangeListener(String alias, String state) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) Tr.entry(tc, "notifySSLConfigChangeListener", new Object[] { alias, state }); if (alias != null) { List<SSLConfigChangeListener> listenerList = sslConfigListenerMap.get(alias); if (listenerList != null && listenerList.size() > 0) { SSLConfigChangeListener[] listenerArray = listenerList.toArray(new SSLConfigChangeListener[listenerList.size()]); for (int i = 0; i < listenerArray.length; i++) { SSLConfigChangeEvent event = null; // get the event associated with the listener event = sslConfigListenerEventMap.get(listenerArray[i]); if (event != null) { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) Tr.debug(tc, "Notifying listener[" + i + "]: " + listenerArray[i].getClass().getName()); event.setState(state); SSLConfig changedConfig = sslConfigMap.get(alias); event.setChangedSSLConfig(changedConfig); listenerArray[i].stateChanged(event); if (state.equals(Constants.CONFIG_STATE_DELETED)) { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) Tr.debug(tc, "Deregistering event for listener."); sslConfigListenerEventMap.remove(listenerArray[i]); } } } if (state.equals(Constants.CONFIG_STATE_DELETED)) { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) Tr.debug(tc, "Deregistering all listeners for this alias due to alias deletion."); sslConfigListenerMap.remove(alias); } } } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) Tr.exit(tc, "notifySSLConfigChangeListener"); } }
public class class_name { public synchronized void notifySSLConfigChangeListener(String alias, String state) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) Tr.entry(tc, "notifySSLConfigChangeListener", new Object[] { alias, state }); if (alias != null) { List<SSLConfigChangeListener> listenerList = sslConfigListenerMap.get(alias); if (listenerList != null && listenerList.size() > 0) { SSLConfigChangeListener[] listenerArray = listenerList.toArray(new SSLConfigChangeListener[listenerList.size()]); for (int i = 0; i < listenerArray.length; i++) { SSLConfigChangeEvent event = null; // get the event associated with the listener event = sslConfigListenerEventMap.get(listenerArray[i]); // depends on control dependency: [for], data = [i] if (event != null) { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) Tr.debug(tc, "Notifying listener[" + i + "]: " + listenerArray[i].getClass().getName()); event.setState(state); // depends on control dependency: [if], data = [none] SSLConfig changedConfig = sslConfigMap.get(alias); event.setChangedSSLConfig(changedConfig); // depends on control dependency: [if], data = [none] listenerArray[i].stateChanged(event); // depends on control dependency: [if], data = [(event] if (state.equals(Constants.CONFIG_STATE_DELETED)) { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) Tr.debug(tc, "Deregistering event for listener."); sslConfigListenerEventMap.remove(listenerArray[i]); // depends on control dependency: [if], data = [none] } } } if (state.equals(Constants.CONFIG_STATE_DELETED)) { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) Tr.debug(tc, "Deregistering all listeners for this alias due to alias deletion."); sslConfigListenerMap.remove(alias); // depends on control dependency: [if], data = [none] } } } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) Tr.exit(tc, "notifySSLConfigChangeListener"); } }
public class class_name { @Override public void writeVectorObject(Vector<Object> vector) { log.debug("writeVectorObject: {}", vector); buf.put(AMF3.TYPE_VECTOR_OBJECT); if (hasReference(vector)) { putInteger(getReferenceId(vector) << 1); return; } storeReference(vector); putInteger(vector.size() << 1 | 1); putInteger(0); buf.put((byte) 0x01); for (Object v : vector) { Serializer.serialize(this, v); } } }
public class class_name { @Override public void writeVectorObject(Vector<Object> vector) { log.debug("writeVectorObject: {}", vector); buf.put(AMF3.TYPE_VECTOR_OBJECT); if (hasReference(vector)) { putInteger(getReferenceId(vector) << 1); // depends on control dependency: [if], data = [none] return; // depends on control dependency: [if], data = [none] } storeReference(vector); putInteger(vector.size() << 1 | 1); putInteger(0); buf.put((byte) 0x01); for (Object v : vector) { Serializer.serialize(this, v); // depends on control dependency: [for], data = [v] } } }
public class class_name { private Text parseText(Node el, Map<String, Scope> scopes) { Text text; if (nodeAttribute(el, TAG_VAR_ATTR_INHERIT, DEFAULT_INHERIT_VALUE)) { text = new Text( nodeAttribute(el, TAG_VAR_ATTR_NAME, Variable.DEFAULT_NAME), null, nodeAttribute(el, TAG_VAR_ATTR_TRANSPARENT, false) ); } else { String scopeName = nodeAttribute(el, TAG_SCOPE, Scope.ROOT); Scope scope = scopes.get(scopeName); if (scope == null) { throw new TextProcessorFactoryException( MessageFormat.format("Scope \"{0}\" not found.", scopeName) ); } text = new Text( nodeAttribute(el, TAG_VAR_ATTR_NAME, Variable.DEFAULT_NAME), scope, nodeAttribute(el, TAG_VAR_ATTR_TRANSPARENT, false) ); } return text; } }
public class class_name { private Text parseText(Node el, Map<String, Scope> scopes) { Text text; if (nodeAttribute(el, TAG_VAR_ATTR_INHERIT, DEFAULT_INHERIT_VALUE)) { text = new Text( nodeAttribute(el, TAG_VAR_ATTR_NAME, Variable.DEFAULT_NAME), null, nodeAttribute(el, TAG_VAR_ATTR_TRANSPARENT, false) ); // depends on control dependency: [if], data = [none] } else { String scopeName = nodeAttribute(el, TAG_SCOPE, Scope.ROOT); Scope scope = scopes.get(scopeName); if (scope == null) { throw new TextProcessorFactoryException( MessageFormat.format("Scope \"{0}\" not found.", scopeName) ); } text = new Text( nodeAttribute(el, TAG_VAR_ATTR_NAME, Variable.DEFAULT_NAME), scope, nodeAttribute(el, TAG_VAR_ATTR_TRANSPARENT, false) ); // depends on control dependency: [if], data = [none] } return text; } }
public class class_name { String createDeletePreparedSQLStatement() { final Set<String> primaryKeyColumnNameSet = getPrimaryColumnNames(); final StringGrabber sgSQL = new StringGrabber(); // Get the table name final DBTable table = mModelClazz.getAnnotation(DBTable.class); final String tableName = table.tableName(); sgSQL.append("DELETE FROM " + tableName + " WHERE "); // Scan all column names in the model class for (String columnName : primaryKeyColumnNameSet) { sgSQL.append(columnName); sgSQL.append(" = ?, "); }// end of for (String columnName : primaryKeyColumnNameSet) { if (sgSQL.length() > 2) { sgSQL.removeTail(2); } final String sql = sgSQL.toString(); log("#createUpdatePreparedSQLStatement sql=" + sql); return sql; } }
public class class_name { String createDeletePreparedSQLStatement() { final Set<String> primaryKeyColumnNameSet = getPrimaryColumnNames(); final StringGrabber sgSQL = new StringGrabber(); // Get the table name final DBTable table = mModelClazz.getAnnotation(DBTable.class); final String tableName = table.tableName(); sgSQL.append("DELETE FROM " + tableName + " WHERE "); // Scan all column names in the model class for (String columnName : primaryKeyColumnNameSet) { sgSQL.append(columnName); // depends on control dependency: [for], data = [columnName] sgSQL.append(" = ?, "); // depends on control dependency: [for], data = [none] }// end of for (String columnName : primaryKeyColumnNameSet) { if (sgSQL.length() > 2) { sgSQL.removeTail(2); // depends on control dependency: [if], data = [2)] } final String sql = sgSQL.toString(); log("#createUpdatePreparedSQLStatement sql=" + sql); return sql; } }
public class class_name { public void marshall(Resource resource, ProtocolMarshaller protocolMarshaller) { if (resource == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(resource.getId(), ID_BINDING); protocolMarshaller.marshall(resource.getEmail(), EMAIL_BINDING); protocolMarshaller.marshall(resource.getName(), NAME_BINDING); protocolMarshaller.marshall(resource.getType(), TYPE_BINDING); protocolMarshaller.marshall(resource.getState(), STATE_BINDING); protocolMarshaller.marshall(resource.getEnabledDate(), ENABLEDDATE_BINDING); protocolMarshaller.marshall(resource.getDisabledDate(), DISABLEDDATE_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
public class class_name { public void marshall(Resource resource, ProtocolMarshaller protocolMarshaller) { if (resource == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(resource.getId(), ID_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(resource.getEmail(), EMAIL_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(resource.getName(), NAME_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(resource.getType(), TYPE_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(resource.getState(), STATE_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(resource.getEnabledDate(), ENABLEDDATE_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(resource.getDisabledDate(), DISABLEDDATE_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 static PlanVersionSummaryBean unmarshallPlanVersionSummary(Map<String, Object> source) { if (source == null) { return null; } PlanVersionSummaryBean bean = new PlanVersionSummaryBean(); bean.setDescription(asString(source.get("planDescription"))); bean.setId(asString(source.get("planId"))); bean.setName(asString(source.get("planName"))); bean.setOrganizationId(asString(source.get("organizationId"))); bean.setOrganizationName(asString(source.get("organizationName"))); bean.setStatus(asEnum(source.get("status"), PlanStatus.class)); bean.setVersion(asString(source.get("version"))); postMarshall(bean); return bean; } }
public class class_name { public static PlanVersionSummaryBean unmarshallPlanVersionSummary(Map<String, Object> source) { if (source == null) { return null; // depends on control dependency: [if], data = [none] } PlanVersionSummaryBean bean = new PlanVersionSummaryBean(); bean.setDescription(asString(source.get("planDescription"))); bean.setId(asString(source.get("planId"))); bean.setName(asString(source.get("planName"))); bean.setOrganizationId(asString(source.get("organizationId"))); bean.setOrganizationName(asString(source.get("organizationName"))); bean.setStatus(asEnum(source.get("status"), PlanStatus.class)); bean.setVersion(asString(source.get("version"))); postMarshall(bean); return bean; } }
public class class_name { @Override public void dispose(final Session session) { if (session != null && session.isConnected()) { logger.trace("Disposing of hibernate session."); session.close(); } } }
public class class_name { @Override public void dispose(final Session session) { if (session != null && session.isConnected()) { logger.trace("Disposing of hibernate session."); // depends on control dependency: [if], data = [none] session.close(); // depends on control dependency: [if], data = [none] } } }
public class class_name { public static void displayVersion(final PrintWriter writer) { for (String line : new VersionProvider().getVersion()) { writer.println(line); } } }
public class class_name { public static void displayVersion(final PrintWriter writer) { for (String line : new VersionProvider().getVersion()) { writer.println(line); // depends on control dependency: [for], data = [line] } } }
public class class_name { void precomputeAngles(D image) { int savecIndex = 0; for (int y = 0; y < image.height; y++) { int pixelIndex = y*image.stride + image.startIndex; for (int x = 0; x < image.width; x++, pixelIndex++, savecIndex++ ) { float spacialDX = imageDerivX.getF(pixelIndex); float spacialDY = imageDerivY.getF(pixelIndex); savedAngle.data[savecIndex] = UtilAngle.domain2PI(Math.atan2(spacialDY,spacialDX)); savedMagnitude.data[savecIndex] = (float)Math.sqrt(spacialDX*spacialDX + spacialDY*spacialDY); } } } }
public class class_name { void precomputeAngles(D image) { int savecIndex = 0; for (int y = 0; y < image.height; y++) { int pixelIndex = y*image.stride + image.startIndex; for (int x = 0; x < image.width; x++, pixelIndex++, savecIndex++ ) { float spacialDX = imageDerivX.getF(pixelIndex); float spacialDY = imageDerivY.getF(pixelIndex); savedAngle.data[savecIndex] = UtilAngle.domain2PI(Math.atan2(spacialDY,spacialDX)); // depends on control dependency: [for], data = [none] savedMagnitude.data[savecIndex] = (float)Math.sqrt(spacialDX*spacialDX + spacialDY*spacialDY); // depends on control dependency: [for], data = [none] } } } }
public class class_name { @Nonnull public final UnifiedResponse disableCaching () { // Remove any eventually set headers removeCaching (); if (m_eHttpVersion.is10 ()) { // Set to expire far in the past for HTTP/1.0. m_aResponseHeaderMap.setHeader (CHttpHeader.EXPIRES, ResponseHelperSettings.EXPIRES_NEVER_STRING); // Set standard HTTP/1.0 no-cache header. m_aResponseHeaderMap.setHeader (CHttpHeader.PRAGMA, "no-cache"); } else { final CacheControlBuilder aCacheControlBuilder = new CacheControlBuilder ().setNoStore (true) .setNoCache (true) .setMustRevalidate (true) .setProxyRevalidate (true); // Set IE extended HTTP/1.1 no-cache headers. // http://aspnetresources.com/blog/cache_control_extensions // Disabled because: // http://blogs.msdn.com/b/ieinternals/archive/2009/07/20/using-post_2d00_check-and-pre_2d00_check-cache-directives.aspx if (false) aCacheControlBuilder.addExtension ("post-check=0").addExtension ("pre-check=0"); setCacheControl (aCacheControlBuilder); } return this; } }
public class class_name { @Nonnull public final UnifiedResponse disableCaching () { // Remove any eventually set headers removeCaching (); if (m_eHttpVersion.is10 ()) { // Set to expire far in the past for HTTP/1.0. m_aResponseHeaderMap.setHeader (CHttpHeader.EXPIRES, ResponseHelperSettings.EXPIRES_NEVER_STRING); // depends on control dependency: [if], data = [none] // Set standard HTTP/1.0 no-cache header. m_aResponseHeaderMap.setHeader (CHttpHeader.PRAGMA, "no-cache"); // depends on control dependency: [if], data = [none] } else { final CacheControlBuilder aCacheControlBuilder = new CacheControlBuilder ().setNoStore (true) .setNoCache (true) .setMustRevalidate (true) .setProxyRevalidate (true); // Set IE extended HTTP/1.1 no-cache headers. // http://aspnetresources.com/blog/cache_control_extensions // Disabled because: // http://blogs.msdn.com/b/ieinternals/archive/2009/07/20/using-post_2d00_check-and-pre_2d00_check-cache-directives.aspx if (false) aCacheControlBuilder.addExtension ("post-check=0").addExtension ("pre-check=0"); setCacheControl (aCacheControlBuilder); // depends on control dependency: [if], data = [none] } return this; } }
public class class_name { public <T> T[] notEmpty(final T[] array, final String message) { if (array == null) { failNull(message); } if (array.length == 0) { fail(message); } return array; } }
public class class_name { public <T> T[] notEmpty(final T[] array, final String message) { if (array == null) { failNull(message); // depends on control dependency: [if], data = [none] } if (array.length == 0) { fail(message); // depends on control dependency: [if], data = [none] } return array; } }
public class class_name { public BoxComment.Info reply(String message) { JsonObject itemJSON = new JsonObject(); itemJSON.add("type", "comment"); itemJSON.add("id", this.getID()); JsonObject requestJSON = new JsonObject(); requestJSON.add("item", itemJSON); if (BoxComment.messageContainsMention(message)) { requestJSON.add("tagged_message", message); } else { requestJSON.add("message", message); } URL url = ADD_COMMENT_URL_TEMPLATE.build(this.getAPI().getBaseURL()); BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "POST"); request.setBody(requestJSON.toString()); BoxJSONResponse response = (BoxJSONResponse) request.send(); JsonObject responseJSON = JsonObject.readFrom(response.getJSON()); BoxComment addedComment = new BoxComment(this.getAPI(), responseJSON.get("id").asString()); return addedComment.new Info(responseJSON); } }
public class class_name { public BoxComment.Info reply(String message) { JsonObject itemJSON = new JsonObject(); itemJSON.add("type", "comment"); itemJSON.add("id", this.getID()); JsonObject requestJSON = new JsonObject(); requestJSON.add("item", itemJSON); if (BoxComment.messageContainsMention(message)) { requestJSON.add("tagged_message", message); // depends on control dependency: [if], data = [none] } else { requestJSON.add("message", message); // depends on control dependency: [if], data = [none] } URL url = ADD_COMMENT_URL_TEMPLATE.build(this.getAPI().getBaseURL()); BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "POST"); request.setBody(requestJSON.toString()); BoxJSONResponse response = (BoxJSONResponse) request.send(); JsonObject responseJSON = JsonObject.readFrom(response.getJSON()); BoxComment addedComment = new BoxComment(this.getAPI(), responseJSON.get("id").asString()); return addedComment.new Info(responseJSON); } }
public class class_name { @Override public Byte convert(final String valueStr, final boolean _caseSensitive, final Object target) { if (valueStr.length() == 1) { if (_caseSensitive) return new Byte((byte) valueStr.charAt(0)); return new Byte((byte) valueStr.toLowerCase().charAt(0)); } for (int b = 0; b < ByteLiteral.length; b++) { if (ByteLiteral[b].equalsIgnoreCase(valueStr)) return (byte) b; } int intValue = 0; try { intValue = Integer.parseInt(valueStr); } catch (final NumberFormatException e) { final StringBuilder errMsg = new StringBuilder(); errMsg.append(valueStr); errMsg.append(" is not a valid byte code. Try one of these codes or the corresponding number: "); for (int b = 0; b < ByteLiteral.length; b++) { errMsg.append(ByteLiteral[b].toUpperCase()); errMsg.append("("); errMsg.append(b); errMsg.append(") "); } throw new NumberFormatException(errMsg.toString()); } if (intValue > 0xff) throw new NumberFormatException(intValue + " is too large, max = 255"); return new Byte((byte) intValue); } }
public class class_name { @Override public Byte convert(final String valueStr, final boolean _caseSensitive, final Object target) { if (valueStr.length() == 1) { if (_caseSensitive) return new Byte((byte) valueStr.charAt(0)); return new Byte((byte) valueStr.toLowerCase().charAt(0)); // depends on control dependency: [if], data = [none] } for (int b = 0; b < ByteLiteral.length; b++) { if (ByteLiteral[b].equalsIgnoreCase(valueStr)) return (byte) b; } int intValue = 0; try { intValue = Integer.parseInt(valueStr); // depends on control dependency: [try], data = [none] } catch (final NumberFormatException e) { final StringBuilder errMsg = new StringBuilder(); errMsg.append(valueStr); errMsg.append(" is not a valid byte code. Try one of these codes or the corresponding number: "); for (int b = 0; b < ByteLiteral.length; b++) { errMsg.append(ByteLiteral[b].toUpperCase()); // depends on control dependency: [for], data = [b] errMsg.append("("); // depends on control dependency: [for], data = [none] errMsg.append(b); // depends on control dependency: [for], data = [b] errMsg.append(") "); // depends on control dependency: [for], data = [none] } throw new NumberFormatException(errMsg.toString()); } // depends on control dependency: [catch], data = [none] if (intValue > 0xff) throw new NumberFormatException(intValue + " is too large, max = 255"); return new Byte((byte) intValue); } }
public class class_name { void initialize(AbstractCompiler compiler) throws Exception { checkState( !Strings.isNullOrEmpty(templateJs), "The template JS must be loaded before the scanner is used. " + "Make sure that the template file is not empty."); Node scriptRoot = new JsAst(SourceFile.fromCode( "template", templateJs)).getAstRoot(compiler); // The before-templates are kept in a LinkedHashMap, to ensure that they are later iterated // over in the order in which they appear in the template JS file. LinkedHashMap<String, Node> beforeTemplates = new LinkedHashMap<>(); Map<String, SortedMap<Integer, Node>> afterTemplates = new HashMap<>(); Set<String> hasChoices = new HashSet<>(); for (Node templateNode : scriptRoot.children()) { if (templateNode.isFunction()) { String fnName = templateNode.getFirstChild().getQualifiedName(); if (fnName.startsWith("before_")) { String templateName = fnName.substring("before_".length()); Preconditions.checkState( !beforeTemplates.containsKey(templateName), "Found existing template with the same name: %s", beforeTemplates.get(templateName)); checkState( templateNode.getLastChild().hasChildren(), "Before templates are not allowed to be empty!"); beforeTemplates.put(templateName, templateNode); } else if (fnName.startsWith("after_option_")) { Matcher m = AFTER_CHOICE_PATTERN.matcher(fnName); checkState(m.matches(), "Template name %s must match pattern after_option_\\d*_", fnName); int optionNumber = Integer.parseInt(m.group(1)); String templateName = m.group(2); if (!afterTemplates.containsKey(templateName)) { afterTemplates.put(templateName, new TreeMap<>()); hasChoices.add(templateName); } checkState( hasChoices.contains(templateName), "Template %s can only be mixed with other after_option_ templates"); checkState( !afterTemplates.get(templateName).containsKey(optionNumber), "Found duplicate template for %s, assign unique indexes for options", fnName); afterTemplates.get(templateName).put(optionNumber, templateNode); } else if (fnName.startsWith("after_")) { String templateName = fnName.substring("after_".length()); Preconditions.checkState( !afterTemplates.containsKey(templateName), "Found existing template with the same name: %s", afterTemplates.get(templateName)); afterTemplates.put(templateName, ImmutableSortedMap.of(0, templateNode)); } else if (fnName.startsWith("do_not_change_")) { String templateName = fnName.substring("do_not_change_".length()); Preconditions.checkState( !beforeTemplates.containsKey(templateName), "Found existing template with the same name: %s", beforeTemplates.get(templateName)); Preconditions.checkState( !afterTemplates.containsKey(templateName), "Found existing template with the same name: %s", afterTemplates.get(templateName)); beforeTemplates.put(templateName, templateNode); afterTemplates.put(templateName, ImmutableSortedMap.of(0, templateNode)); } } } checkState( !beforeTemplates.isEmpty(), "Did not find any RefasterJs templates! Make sure that there are 2 functions defined " + "with the same name, one with a \"before_\" prefix and one with a \"after_\" prefix"); // TODO(bangert): Get ImmutableLinkedMap into Guava? this.templates = new LinkedHashMap<>(); for (String templateName : beforeTemplates.keySet()) { Preconditions.checkState( afterTemplates.containsKey(templateName) && !afterTemplates.get(templateName).isEmpty(), "Found before template without at least one corresponding after " + " template. Make sure there is an after_%s or after_option_1_%s function defined.", templateName, templateName); ImmutableList.Builder<RefasterJsTemplate> builder = ImmutableList.builder(); for (Node afterTemplateOption : afterTemplates.get(templateName).values()) { builder.add( new RefasterJsTemplate( compiler.getTypeRegistry(), typeMatchingStrategy, beforeTemplates.get(templateName), afterTemplateOption)); } ImmutableList<RefasterJsTemplate> afterOptions = builder.build(); this.templates.put(afterOptions.get(0).matcher, afterOptions); } } }
public class class_name { void initialize(AbstractCompiler compiler) throws Exception { checkState( !Strings.isNullOrEmpty(templateJs), "The template JS must be loaded before the scanner is used. " + "Make sure that the template file is not empty."); Node scriptRoot = new JsAst(SourceFile.fromCode( "template", templateJs)).getAstRoot(compiler); // The before-templates are kept in a LinkedHashMap, to ensure that they are later iterated // over in the order in which they appear in the template JS file. LinkedHashMap<String, Node> beforeTemplates = new LinkedHashMap<>(); Map<String, SortedMap<Integer, Node>> afterTemplates = new HashMap<>(); Set<String> hasChoices = new HashSet<>(); for (Node templateNode : scriptRoot.children()) { if (templateNode.isFunction()) { String fnName = templateNode.getFirstChild().getQualifiedName(); if (fnName.startsWith("before_")) { String templateName = fnName.substring("before_".length()); Preconditions.checkState( !beforeTemplates.containsKey(templateName), "Found existing template with the same name: %s", beforeTemplates.get(templateName)); // depends on control dependency: [if], data = [none] checkState( templateNode.getLastChild().hasChildren(), "Before templates are not allowed to be empty!"); beforeTemplates.put(templateName, templateNode); // depends on control dependency: [if], data = [none] } else if (fnName.startsWith("after_option_")) { Matcher m = AFTER_CHOICE_PATTERN.matcher(fnName); checkState(m.matches(), "Template name %s must match pattern after_option_\\d*_", fnName); // depends on control dependency: [if], data = [none] int optionNumber = Integer.parseInt(m.group(1)); String templateName = m.group(2); if (!afterTemplates.containsKey(templateName)) { afterTemplates.put(templateName, new TreeMap<>()); // depends on control dependency: [if], data = [none] hasChoices.add(templateName); // depends on control dependency: [if], data = [none] } checkState( hasChoices.contains(templateName), "Template %s can only be mixed with other after_option_ templates"); // depends on control dependency: [if], data = [none] checkState( !afterTemplates.get(templateName).containsKey(optionNumber), "Found duplicate template for %s, assign unique indexes for options", fnName); // depends on control dependency: [if], data = [none] afterTemplates.get(templateName).put(optionNumber, templateNode); // depends on control dependency: [if], data = [none] } else if (fnName.startsWith("after_")) { String templateName = fnName.substring("after_".length()); Preconditions.checkState( !afterTemplates.containsKey(templateName), "Found existing template with the same name: %s", afterTemplates.get(templateName)); // depends on control dependency: [if], data = [none] afterTemplates.put(templateName, ImmutableSortedMap.of(0, templateNode)); // depends on control dependency: [if], data = [none] } else if (fnName.startsWith("do_not_change_")) { String templateName = fnName.substring("do_not_change_".length()); Preconditions.checkState( !beforeTemplates.containsKey(templateName), "Found existing template with the same name: %s", beforeTemplates.get(templateName)); // depends on control dependency: [if], data = [none] Preconditions.checkState( !afterTemplates.containsKey(templateName), "Found existing template with the same name: %s", afterTemplates.get(templateName)); // depends on control dependency: [if], data = [none] beforeTemplates.put(templateName, templateNode); // depends on control dependency: [if], data = [none] afterTemplates.put(templateName, ImmutableSortedMap.of(0, templateNode)); // depends on control dependency: [if], data = [none] } } } checkState( !beforeTemplates.isEmpty(), "Did not find any RefasterJs templates! Make sure that there are 2 functions defined " + "with the same name, one with a \"before_\" prefix and one with a \"after_\" prefix"); // TODO(bangert): Get ImmutableLinkedMap into Guava? this.templates = new LinkedHashMap<>(); for (String templateName : beforeTemplates.keySet()) { Preconditions.checkState( afterTemplates.containsKey(templateName) && !afterTemplates.get(templateName).isEmpty(), "Found before template without at least one corresponding after " + " template. Make sure there is an after_%s or after_option_1_%s function defined.", templateName, templateName); ImmutableList.Builder<RefasterJsTemplate> builder = ImmutableList.builder(); for (Node afterTemplateOption : afterTemplates.get(templateName).values()) { builder.add( new RefasterJsTemplate( compiler.getTypeRegistry(), typeMatchingStrategy, beforeTemplates.get(templateName), afterTemplateOption)); } ImmutableList<RefasterJsTemplate> afterOptions = builder.build(); this.templates.put(afterOptions.get(0).matcher, afterOptions); } } }
public class class_name { public NumberExpression<Integer> dayOfMonth() { if (dayOfMonth == null) { dayOfMonth = Expressions.numberOperation(Integer.class, Ops.DateTimeOps.DAY_OF_MONTH, mixin); } return dayOfMonth; } }
public class class_name { public NumberExpression<Integer> dayOfMonth() { if (dayOfMonth == null) { dayOfMonth = Expressions.numberOperation(Integer.class, Ops.DateTimeOps.DAY_OF_MONTH, mixin); // depends on control dependency: [if], data = [none] } return dayOfMonth; } }
public class class_name { public short acceptNode(int n) { XPathContext xctxt = getXPathContext(); try { xctxt.pushCurrentNode(n); for (int i = 0; i < m_nodeTests.length; i++) { PredicatedNodeTest pnt = m_nodeTests[i]; XObject score = pnt.execute(xctxt, n); if (score != NodeTest.SCORE_NONE) { // Note that we are assuming there are no positional predicates! if (pnt.getPredicateCount() > 0) { if (pnt.executePredicates(n, xctxt)) return DTMIterator.FILTER_ACCEPT; } else return DTMIterator.FILTER_ACCEPT; } } } catch (javax.xml.transform.TransformerException se) { // TODO: Fix this. throw new RuntimeException(se.getMessage()); } finally { xctxt.popCurrentNode(); } return DTMIterator.FILTER_SKIP; } }
public class class_name { public short acceptNode(int n) { XPathContext xctxt = getXPathContext(); try { xctxt.pushCurrentNode(n); // depends on control dependency: [try], data = [none] for (int i = 0; i < m_nodeTests.length; i++) { PredicatedNodeTest pnt = m_nodeTests[i]; XObject score = pnt.execute(xctxt, n); if (score != NodeTest.SCORE_NONE) { // Note that we are assuming there are no positional predicates! if (pnt.getPredicateCount() > 0) { if (pnt.executePredicates(n, xctxt)) return DTMIterator.FILTER_ACCEPT; } else return DTMIterator.FILTER_ACCEPT; } } } catch (javax.xml.transform.TransformerException se) { // TODO: Fix this. throw new RuntimeException(se.getMessage()); } // depends on control dependency: [catch], data = [none] finally { xctxt.popCurrentNode(); } return DTMIterator.FILTER_SKIP; } }
public class class_name { public String login( String username, String password ) throws DebugWsException { this.logger.finer( "Logging in as " + username ); WebResource path = this.resource.path( UrlConstants.AUTHENTICATION ).path( "e" ); ClientResponse response = path .header( "u", username ) .header( "p", password ) .post( ClientResponse.class ); if( Family.SUCCESSFUL != response.getStatusInfo().getFamily()) { String value = response.getEntity( String.class ); this.logger.finer( response.getStatusInfo() + ": " + value ); throw new DebugWsException( response.getStatusInfo().getStatusCode(), value ); } // Get the session ID from the cookie that should have been returned String sessionId = null; List<NewCookie> cookies = response.getCookies(); if( cookies != null ) { for( NewCookie cookie : cookies ) { if( UrlConstants.SESSION_ID.equals( cookie.getName())) { sessionId = cookie.getValue(); break; } } } // Set the session ID this.wsClient.setSessionId( sessionId ); this.logger.finer( "Session ID: " + sessionId ); return sessionId; } }
public class class_name { public String login( String username, String password ) throws DebugWsException { this.logger.finer( "Logging in as " + username ); WebResource path = this.resource.path( UrlConstants.AUTHENTICATION ).path( "e" ); ClientResponse response = path .header( "u", username ) .header( "p", password ) .post( ClientResponse.class ); if( Family.SUCCESSFUL != response.getStatusInfo().getFamily()) { String value = response.getEntity( String.class ); this.logger.finer( response.getStatusInfo() + ": " + value ); throw new DebugWsException( response.getStatusInfo().getStatusCode(), value ); } // Get the session ID from the cookie that should have been returned String sessionId = null; List<NewCookie> cookies = response.getCookies(); if( cookies != null ) { for( NewCookie cookie : cookies ) { if( UrlConstants.SESSION_ID.equals( cookie.getName())) { sessionId = cookie.getValue(); // depends on control dependency: [if], data = [none] break; } } } // Set the session ID this.wsClient.setSessionId( sessionId ); this.logger.finer( "Session ID: " + sessionId ); return sessionId; } }
public class class_name { private void handleInputQueue() { if (!addedQueue.isEmpty()) { getLogger().debug("Handling queue"); Collection<MemcachedNode> toAdd = new HashSet<MemcachedNode>(); Collection<MemcachedNode> todo = new HashSet<MemcachedNode>(); MemcachedNode qaNode; while ((qaNode = addedQueue.poll()) != null) { todo.add(qaNode); } for (MemcachedNode node : todo) { boolean readyForIO = false; if (node.isActive()) { if (node.getCurrentWriteOp() != null) { readyForIO = true; getLogger().debug("Handling queued write %s", node); } } else { toAdd.add(node); } node.copyInputQueue(); if (readyForIO) { try { if (node.getWbuf().hasRemaining()) { handleWrites(node); } } catch (IOException e) { getLogger().warn("Exception handling write", e); lostConnection(node); } } node.fixupOps(); } addedQueue.addAll(toAdd); } } }
public class class_name { private void handleInputQueue() { if (!addedQueue.isEmpty()) { getLogger().debug("Handling queue"); Collection<MemcachedNode> toAdd = new HashSet<MemcachedNode>(); Collection<MemcachedNode> todo = new HashSet<MemcachedNode>(); MemcachedNode qaNode; while ((qaNode = addedQueue.poll()) != null) { todo.add(qaNode); // depends on control dependency: [while], data = [none] } for (MemcachedNode node : todo) { boolean readyForIO = false; if (node.isActive()) { if (node.getCurrentWriteOp() != null) { readyForIO = true; // depends on control dependency: [if], data = [none] getLogger().debug("Handling queued write %s", node); // depends on control dependency: [if], data = [none] } } else { toAdd.add(node); // depends on control dependency: [if], data = [none] } node.copyInputQueue(); if (readyForIO) { try { if (node.getWbuf().hasRemaining()) { handleWrites(node); // depends on control dependency: [if], data = [none] } } catch (IOException e) { getLogger().warn("Exception handling write", e); lostConnection(node); } } node.fixupOps(); } addedQueue.addAll(toAdd); } } }
public class class_name { @Nullable static Drawable maybeWrapWithMatrix( @Nullable Drawable drawable, @Nullable Matrix matrix) { if (drawable == null || matrix == null) { return drawable; } return new MatrixDrawable(drawable, matrix); } }
public class class_name { @Nullable static Drawable maybeWrapWithMatrix( @Nullable Drawable drawable, @Nullable Matrix matrix) { if (drawable == null || matrix == null) { return drawable; // depends on control dependency: [if], data = [none] } return new MatrixDrawable(drawable, matrix); } }
public class class_name { List createAndExecuteQuery(CouchDBQueryInterpreter interpreter) { EntityMetadata m = interpreter.getMetadata(); List results = new ArrayList(); try { MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel( m.getPersistenceUnit()); StringBuilder q = new StringBuilder(); String _id = CouchDBConstants.URL_SEPARATOR + m.getSchema().toLowerCase() + CouchDBConstants.URL_SEPARATOR + CouchDBConstants.DESIGN + m.getTableName() + CouchDBConstants.VIEW; if ((interpreter.isIdQuery() && !interpreter.isRangeQuery() && interpreter.getOperator() == null) || interpreter.isQueryOnCompositeKey()) { Object object = null; if (metaModel.isEmbeddable(m.getIdAttribute().getBindableJavaType())) { EmbeddableType embeddableType = metaModel.embeddable(m.getIdAttribute().getBindableJavaType()); if (KunderaCoreUtils.countNonSyntheticFields(m.getIdAttribute().getBindableJavaType()) == interpreter .getKeyValues().size()) { Object key = CouchDBObjectMapper.getObjectFromJson(gson.toJsonTree(interpreter.getKeyValues()) .getAsJsonObject(), m.getIdAttribute().getBindableJavaType(), embeddableType .getAttributes()); object = find(m.getEntityClazz(), key); if (object != null) { results.add(object); } return results; } else if (m.getIdAttribute().getName().equals(interpreter.getKeyName()) && interpreter.getKeyValues().size() == 1) { object = find(m.getEntityClazz(), interpreter.getKeyValue()); if (object != null) { results.add(object); } return results; } else { log.error("There should be each and every field of composite key."); throw new QueryHandlerException("There should be each and every field of composite key."); } } object = find(m.getEntityClazz(), interpreter.getKeyValue()); if (object != null) { results.add(object); } return results; } // creating query. _id = createQuery(interpreter, m, q, _id); if (interpreter.getLimit() > 0) { q.append("&limit=" + interpreter.getLimit()); } if (interpreter.isDescending()) { q.append("&descending=" + false); } // execute query. executeQueryAndGetResults(q, _id, m, results, interpreter); } catch (Exception e) { log.error("Error while executing query, Caused by {}.", e); throw new KunderaException(e); } return results; } }
public class class_name { List createAndExecuteQuery(CouchDBQueryInterpreter interpreter) { EntityMetadata m = interpreter.getMetadata(); List results = new ArrayList(); try { MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel( m.getPersistenceUnit()); StringBuilder q = new StringBuilder(); String _id = CouchDBConstants.URL_SEPARATOR + m.getSchema().toLowerCase() + CouchDBConstants.URL_SEPARATOR + CouchDBConstants.DESIGN + m.getTableName() + CouchDBConstants.VIEW; if ((interpreter.isIdQuery() && !interpreter.isRangeQuery() && interpreter.getOperator() == null) || interpreter.isQueryOnCompositeKey()) { Object object = null; if (metaModel.isEmbeddable(m.getIdAttribute().getBindableJavaType())) { EmbeddableType embeddableType = metaModel.embeddable(m.getIdAttribute().getBindableJavaType()); if (KunderaCoreUtils.countNonSyntheticFields(m.getIdAttribute().getBindableJavaType()) == interpreter .getKeyValues().size()) { Object key = CouchDBObjectMapper.getObjectFromJson(gson.toJsonTree(interpreter.getKeyValues()) .getAsJsonObject(), m.getIdAttribute().getBindableJavaType(), embeddableType .getAttributes()); object = find(m.getEntityClazz(), key); // depends on control dependency: [if], data = [none] if (object != null) { results.add(object); // depends on control dependency: [if], data = [(object] } return results; // depends on control dependency: [if], data = [none] } else if (m.getIdAttribute().getName().equals(interpreter.getKeyName()) && interpreter.getKeyValues().size() == 1) { object = find(m.getEntityClazz(), interpreter.getKeyValue()); // depends on control dependency: [if], data = [none] if (object != null) { results.add(object); // depends on control dependency: [if], data = [(object] } return results; // depends on control dependency: [if], data = [none] } else { log.error("There should be each and every field of composite key."); // depends on control dependency: [if], data = [none] throw new QueryHandlerException("There should be each and every field of composite key."); } } object = find(m.getEntityClazz(), interpreter.getKeyValue()); // depends on control dependency: [if], data = [none] if (object != null) { results.add(object); // depends on control dependency: [if], data = [(object] } return results; // depends on control dependency: [if], data = [none] } // creating query. _id = createQuery(interpreter, m, q, _id); // depends on control dependency: [try], data = [none] if (interpreter.getLimit() > 0) { q.append("&limit=" + interpreter.getLimit()); // depends on control dependency: [if], data = [none] } if (interpreter.isDescending()) { q.append("&descending=" + false); // depends on control dependency: [if], data = [none] } // execute query. executeQueryAndGetResults(q, _id, m, results, interpreter); // depends on control dependency: [try], data = [none] } catch (Exception e) { log.error("Error while executing query, Caused by {}.", e); throw new KunderaException(e); } // depends on control dependency: [catch], data = [none] return results; } }
public class class_name { private void evaluateSubtreeReplacement() { if (this.hypothesis.size() == 1) { // skip replacement if only one node is discovered return; } final Set<ReplacementResult<ADTState<I, O>, I, O>> potentialReplacements = this.subtreeReplacer.computeReplacements(this.hypothesis, this.alphabet, this.adt); final List<ReplacementResult<ADTState<I, O>, I, O>> validReplacements = new ArrayList<>(potentialReplacements.size()); final Set<ADTNode<ADTState<I, O>, I, O>> cachedLeaves = potentialReplacements.isEmpty() ? Collections.emptySet() : ADTUtil.collectLeaves(this.adt.getRoot()); for (final ReplacementResult<ADTState<I, O>, I, O> potentialReplacement : potentialReplacements) { final ADTNode<ADTState<I, O>, I, O> proposedReplacement = potentialReplacement.getReplacement(); final ADTNode<ADTState<I, O>, I, O> nodeToReplace = potentialReplacement.getNodeToReplace(); assert this.validateADS(nodeToReplace, proposedReplacement, potentialReplacement.getCutoutNodes()); final ADTNode<ADTState<I, O>, I, O> replacement = this.verifyADS(nodeToReplace, proposedReplacement, cachedLeaves, potentialReplacement.getCutoutNodes()); // verification may have introduced reset nodes final int oldCosts = ADTUtil.computeEffectiveResets(nodeToReplace); final int newCosts = ADTUtil.computeEffectiveResets(replacement); if (newCosts >= oldCosts) { continue; } validReplacements.add(new ReplacementResult<>(nodeToReplace, replacement)); } for (final ReplacementResult<ADTState<I, O>, I, O> potentialReplacement : validReplacements) { final ADTNode<ADTState<I, O>, I, O> replacement = potentialReplacement.getReplacement(); final ADTNode<ADTState<I, O>, I, O> nodeToReplace = potentialReplacement.getNodeToReplace(); this.adt.replaceNode(nodeToReplace, replacement); this.resiftAffectedTransitions(ADTUtil.collectLeaves(replacement), ADTUtil.getStartOfADS(replacement)); } this.closeTransitions(); } }
public class class_name { private void evaluateSubtreeReplacement() { if (this.hypothesis.size() == 1) { // skip replacement if only one node is discovered return; // depends on control dependency: [if], data = [none] } final Set<ReplacementResult<ADTState<I, O>, I, O>> potentialReplacements = this.subtreeReplacer.computeReplacements(this.hypothesis, this.alphabet, this.adt); final List<ReplacementResult<ADTState<I, O>, I, O>> validReplacements = new ArrayList<>(potentialReplacements.size()); final Set<ADTNode<ADTState<I, O>, I, O>> cachedLeaves = potentialReplacements.isEmpty() ? Collections.emptySet() : ADTUtil.collectLeaves(this.adt.getRoot()); for (final ReplacementResult<ADTState<I, O>, I, O> potentialReplacement : potentialReplacements) { final ADTNode<ADTState<I, O>, I, O> proposedReplacement = potentialReplacement.getReplacement(); final ADTNode<ADTState<I, O>, I, O> nodeToReplace = potentialReplacement.getNodeToReplace(); assert this.validateADS(nodeToReplace, proposedReplacement, potentialReplacement.getCutoutNodes()); final ADTNode<ADTState<I, O>, I, O> replacement = this.verifyADS(nodeToReplace, proposedReplacement, cachedLeaves, potentialReplacement.getCutoutNodes()); // verification may have introduced reset nodes final int oldCosts = ADTUtil.computeEffectiveResets(nodeToReplace); final int newCosts = ADTUtil.computeEffectiveResets(replacement); if (newCosts >= oldCosts) { continue; } validReplacements.add(new ReplacementResult<>(nodeToReplace, replacement)); // depends on control dependency: [for], data = [none] } for (final ReplacementResult<ADTState<I, O>, I, O> potentialReplacement : validReplacements) { final ADTNode<ADTState<I, O>, I, O> replacement = potentialReplacement.getReplacement(); final ADTNode<ADTState<I, O>, I, O> nodeToReplace = potentialReplacement.getNodeToReplace(); this.adt.replaceNode(nodeToReplace, replacement); // depends on control dependency: [for], data = [none] this.resiftAffectedTransitions(ADTUtil.collectLeaves(replacement), ADTUtil.getStartOfADS(replacement)); // depends on control dependency: [for], data = [none] } this.closeTransitions(); } }
public class class_name { private void addColumnMethodToCriteria(TopLevelClass topLevelClass, InnerClass innerClass, IntrospectedTable introspectedTable) { // !!!!! Column import比较特殊引入的是外部类 topLevelClass.addImportedType(introspectedTable.getRules().calculateAllFieldsClass()); for (IntrospectedColumn introspectedColumn : introspectedTable.getNonBLOBColumns()) { topLevelClass.addImportedType(introspectedColumn.getFullyQualifiedJavaType()); // EqualTo FormatTools.addMethodWithBestPosition(innerClass, this.generateSingleValueMethod(introspectedTable, introspectedColumn, "EqualTo", "=")); // NotEqualTo FormatTools.addMethodWithBestPosition(innerClass, this.generateSingleValueMethod(introspectedTable, introspectedColumn, "NotEqualTo", "<>")); // GreaterThan FormatTools.addMethodWithBestPosition(innerClass, this.generateSingleValueMethod(introspectedTable, introspectedColumn, "GreaterThan", ">")); // GreaterThanOrEqualTo FormatTools.addMethodWithBestPosition(innerClass, this.generateSingleValueMethod(introspectedTable, introspectedColumn, "GreaterThanOrEqualTo", ">=")); // LessThan FormatTools.addMethodWithBestPosition(innerClass, this.generateSingleValueMethod(introspectedTable, introspectedColumn, "LessThan", "<")); // LessThanOrEqualTo FormatTools.addMethodWithBestPosition(innerClass, this.generateSingleValueMethod(introspectedTable, introspectedColumn, "LessThanOrEqualTo", "<=")); } } }
public class class_name { private void addColumnMethodToCriteria(TopLevelClass topLevelClass, InnerClass innerClass, IntrospectedTable introspectedTable) { // !!!!! Column import比较特殊引入的是外部类 topLevelClass.addImportedType(introspectedTable.getRules().calculateAllFieldsClass()); for (IntrospectedColumn introspectedColumn : introspectedTable.getNonBLOBColumns()) { topLevelClass.addImportedType(introspectedColumn.getFullyQualifiedJavaType()); // depends on control dependency: [for], data = [introspectedColumn] // EqualTo FormatTools.addMethodWithBestPosition(innerClass, this.generateSingleValueMethod(introspectedTable, introspectedColumn, "EqualTo", "=")); // depends on control dependency: [for], data = [introspectedColumn] // NotEqualTo FormatTools.addMethodWithBestPosition(innerClass, this.generateSingleValueMethod(introspectedTable, introspectedColumn, "NotEqualTo", "<>")); // depends on control dependency: [for], data = [introspectedColumn] // GreaterThan FormatTools.addMethodWithBestPosition(innerClass, this.generateSingleValueMethod(introspectedTable, introspectedColumn, "GreaterThan", ">")); // depends on control dependency: [for], data = [introspectedColumn] // GreaterThanOrEqualTo FormatTools.addMethodWithBestPosition(innerClass, this.generateSingleValueMethod(introspectedTable, introspectedColumn, "GreaterThanOrEqualTo", ">=")); // depends on control dependency: [for], data = [introspectedColumn] // LessThan FormatTools.addMethodWithBestPosition(innerClass, this.generateSingleValueMethod(introspectedTable, introspectedColumn, "LessThan", "<")); // depends on control dependency: [for], data = [introspectedColumn] // LessThanOrEqualTo FormatTools.addMethodWithBestPosition(innerClass, this.generateSingleValueMethod(introspectedTable, introspectedColumn, "LessThanOrEqualTo", "<=")); // depends on control dependency: [for], data = [introspectedColumn] } } }
public class class_name { public static <T> ElementMatcher.Junction<T> noneOf(Iterable<?> values) { ElementMatcher.Junction<T> matcher = null; for (Object value : values) { matcher = matcher == null ? ElementMatchers.<T>not(is(value)) : matcher.and(not(is(value))); } return matcher == null ? ElementMatchers.<T>any() : matcher; } }
public class class_name { public static <T> ElementMatcher.Junction<T> noneOf(Iterable<?> values) { ElementMatcher.Junction<T> matcher = null; for (Object value : values) { matcher = matcher == null ? ElementMatchers.<T>not(is(value)) : matcher.and(not(is(value))); // depends on control dependency: [for], data = [none] } return matcher == null ? ElementMatchers.<T>any() : matcher; } }
public class class_name { @Override public String getResourcePath(String requestedPath) { String resourcePath = super.getResourcePath(requestedPath); GeneratorMappingHelper helper = new GeneratorMappingHelper(resourcePath); String fullPath = null; if (StringUtils.isNotEmpty(helper.getBracketsParam())) { // Use the webjars reference stored in the bracket params fullPath = locator.getFullPath(helper.getBracketsParam(), helper.getPath()); } else { fullPath = locator.getFullPath(resourcePath); } if (checkResourcePathForInfo || checkResourcePathForWarning) { checkResourcePath(resourcePath, fullPath); } return fullPath.substring(GeneratorRegistry.WEBJARS_GENERATOR_HELPER_PREFIX.length() - 2); } }
public class class_name { @Override public String getResourcePath(String requestedPath) { String resourcePath = super.getResourcePath(requestedPath); GeneratorMappingHelper helper = new GeneratorMappingHelper(resourcePath); String fullPath = null; if (StringUtils.isNotEmpty(helper.getBracketsParam())) { // Use the webjars reference stored in the bracket params fullPath = locator.getFullPath(helper.getBracketsParam(), helper.getPath()); // depends on control dependency: [if], data = [none] } else { fullPath = locator.getFullPath(resourcePath); // depends on control dependency: [if], data = [none] } if (checkResourcePathForInfo || checkResourcePathForWarning) { checkResourcePath(resourcePath, fullPath); // depends on control dependency: [if], data = [none] } return fullPath.substring(GeneratorRegistry.WEBJARS_GENERATOR_HELPER_PREFIX.length() - 2); } }
public class class_name { protected void validateMessageContent(Message receivedMessage, Message controlMessage, XmlMessageValidationContext validationContext, TestContext context) { if (controlMessage == null || controlMessage.getPayload() == null) { log.debug("Skip message payload validation as no control message was defined"); return; } if (!(controlMessage.getPayload() instanceof String)) { throw new IllegalArgumentException( "DomXmlMessageValidator does only support message payload of type String, " + "but was " + controlMessage.getPayload().getClass()); } String controlMessagePayload = controlMessage.getPayload(String.class); if (receivedMessage.getPayload() == null || !StringUtils.hasText(receivedMessage.getPayload(String.class))) { Assert.isTrue(!StringUtils.hasText(controlMessagePayload), "Unable to validate message payload - received message payload was empty, control message payload is not"); return; } else if (!StringUtils.hasText(controlMessagePayload)) { return; } log.debug("Start XML tree validation ..."); Document received = XMLUtils.parseMessagePayload(receivedMessage.getPayload(String.class)); Document source = XMLUtils.parseMessagePayload(controlMessagePayload); XMLUtils.stripWhitespaceNodes(received); XMLUtils.stripWhitespaceNodes(source); if (log.isDebugEnabled()) { log.debug("Received message:\n" + XMLUtils.serialize(received)); log.debug("Control message:\n" + XMLUtils.serialize(source)); } validateXmlTree(received, source, validationContext, namespaceContextBuilder.buildContext( receivedMessage, validationContext.getNamespaces()), context); } }
public class class_name { protected void validateMessageContent(Message receivedMessage, Message controlMessage, XmlMessageValidationContext validationContext, TestContext context) { if (controlMessage == null || controlMessage.getPayload() == null) { log.debug("Skip message payload validation as no control message was defined"); // depends on control dependency: [if], data = [none] return; // depends on control dependency: [if], data = [none] } if (!(controlMessage.getPayload() instanceof String)) { throw new IllegalArgumentException( "DomXmlMessageValidator does only support message payload of type String, " + "but was " + controlMessage.getPayload().getClass()); } String controlMessagePayload = controlMessage.getPayload(String.class); if (receivedMessage.getPayload() == null || !StringUtils.hasText(receivedMessage.getPayload(String.class))) { Assert.isTrue(!StringUtils.hasText(controlMessagePayload), "Unable to validate message payload - received message payload was empty, control message payload is not"); // depends on control dependency: [if], data = [none] return; // depends on control dependency: [if], data = [none] } else if (!StringUtils.hasText(controlMessagePayload)) { return; // depends on control dependency: [if], data = [none] } log.debug("Start XML tree validation ..."); Document received = XMLUtils.parseMessagePayload(receivedMessage.getPayload(String.class)); Document source = XMLUtils.parseMessagePayload(controlMessagePayload); XMLUtils.stripWhitespaceNodes(received); XMLUtils.stripWhitespaceNodes(source); if (log.isDebugEnabled()) { log.debug("Received message:\n" + XMLUtils.serialize(received)); log.debug("Control message:\n" + XMLUtils.serialize(source)); } validateXmlTree(received, source, validationContext, namespaceContextBuilder.buildContext( receivedMessage, validationContext.getNamespaces()), context); } }
public class class_name { public ApplicationUpdate withCloudWatchLoggingOptionUpdates(CloudWatchLoggingOptionUpdate... cloudWatchLoggingOptionUpdates) { if (this.cloudWatchLoggingOptionUpdates == null) { setCloudWatchLoggingOptionUpdates(new java.util.ArrayList<CloudWatchLoggingOptionUpdate>(cloudWatchLoggingOptionUpdates.length)); } for (CloudWatchLoggingOptionUpdate ele : cloudWatchLoggingOptionUpdates) { this.cloudWatchLoggingOptionUpdates.add(ele); } return this; } }
public class class_name { public ApplicationUpdate withCloudWatchLoggingOptionUpdates(CloudWatchLoggingOptionUpdate... cloudWatchLoggingOptionUpdates) { if (this.cloudWatchLoggingOptionUpdates == null) { setCloudWatchLoggingOptionUpdates(new java.util.ArrayList<CloudWatchLoggingOptionUpdate>(cloudWatchLoggingOptionUpdates.length)); // depends on control dependency: [if], data = [none] } for (CloudWatchLoggingOptionUpdate ele : cloudWatchLoggingOptionUpdates) { this.cloudWatchLoggingOptionUpdates.add(ele); // depends on control dependency: [for], data = [ele] } return this; } }
public class class_name { public Double getValue(GriddedTile griddedTile, int unsignedPixelValue) { Double value = null; if (!isDataNull(unsignedPixelValue)) { value = pixelValueToValue(griddedTile, new Double( unsignedPixelValue)); } return value; } }
public class class_name { public Double getValue(GriddedTile griddedTile, int unsignedPixelValue) { Double value = null; if (!isDataNull(unsignedPixelValue)) { value = pixelValueToValue(griddedTile, new Double( unsignedPixelValue)); // depends on control dependency: [if], data = [none] } return value; } }
public class class_name { public static <T, R, E extends Exception> List<R> map(final Collection<? extends T> c, final int fromIndex, final int toIndex, final Try.Function<? super T, ? extends R, E> func) throws E { checkFromToIndex(fromIndex, toIndex, size(c)); N.checkArgNotNull(func); if (N.isNullOrEmpty(c) && fromIndex == 0 && toIndex == 0) { return new ArrayList<>(); } final List<R> result = new ArrayList<>(toIndex - fromIndex); if (c instanceof List && c instanceof RandomAccess) { final List<T> list = (List<T>) c; for (int i = fromIndex; i < toIndex; i++) { result.add(func.apply(list.get(i))); } } else { int idx = 0; for (T e : c) { if (idx++ < fromIndex) { continue; } result.add(func.apply(e)); if (idx >= toIndex) { break; } } } return result; } }
public class class_name { public static <T, R, E extends Exception> List<R> map(final Collection<? extends T> c, final int fromIndex, final int toIndex, final Try.Function<? super T, ? extends R, E> func) throws E { checkFromToIndex(fromIndex, toIndex, size(c)); N.checkArgNotNull(func); if (N.isNullOrEmpty(c) && fromIndex == 0 && toIndex == 0) { return new ArrayList<>(); } final List<R> result = new ArrayList<>(toIndex - fromIndex); if (c instanceof List && c instanceof RandomAccess) { final List<T> list = (List<T>) c; for (int i = fromIndex; i < toIndex; i++) { result.add(func.apply(list.get(i))); // depends on control dependency: [for], data = [i] } } else { int idx = 0; for (T e : c) { if (idx++ < fromIndex) { continue; } result.add(func.apply(e)); // depends on control dependency: [for], data = [e] if (idx >= toIndex) { break; } } } return result; } }
public class class_name { private static String getHostnamesFromInstances(Iterable<TaskManagerLocation> locations) { StringBuilder bld = new StringBuilder(); boolean successive = false; for (TaskManagerLocation loc : locations) { if (successive) { bld.append(", "); } else { successive = true; } bld.append(loc.getHostname()); } return bld.toString(); } }
public class class_name { private static String getHostnamesFromInstances(Iterable<TaskManagerLocation> locations) { StringBuilder bld = new StringBuilder(); boolean successive = false; for (TaskManagerLocation loc : locations) { if (successive) { bld.append(", "); // depends on control dependency: [if], data = [none] } else { successive = true; // depends on control dependency: [if], data = [none] } bld.append(loc.getHostname()); // depends on control dependency: [for], data = [loc] } return bld.toString(); } }
public class class_name { private void updateInfoButton() { if (m_stateBean.getType().isUser()) { Map<String, String> dataMap = new LinkedHashMap<String, String>(); dataMap.put( CmsVaadinUtils.getMessageText(Messages.GUI_USERMANAGEMENT_COUNT_0), String.valueOf(((Table)m_table).size())); try { int count = getUsersWithoutAdditionalInfo( m_cms, m_stateBean.getType(), m_stateBean.getPath(), true).size(); if (count > ((Table)m_table).size()) { dataMap.put( CmsVaadinUtils.getMessageText(Messages.GUI_USERMANAGEMENT_TOT_COUNT_0), String.valueOf(count)); } } catch (CmsException e) { //; } m_infoButton.replaceData(dataMap); } else { int size = ((Table)m_table).size(); if (m_table instanceof CmsUserTable) { size = ((CmsUserTable)m_table).getVisibleUser().size(); } m_infoButton.replaceData( Collections.singletonMap( CmsVaadinUtils.getMessageText(Messages.GUI_USERMANAGEMENT_COUNT_0), String.valueOf(size))); } } }
public class class_name { private void updateInfoButton() { if (m_stateBean.getType().isUser()) { Map<String, String> dataMap = new LinkedHashMap<String, String>(); dataMap.put( CmsVaadinUtils.getMessageText(Messages.GUI_USERMANAGEMENT_COUNT_0), String.valueOf(((Table)m_table).size())); // depends on control dependency: [if], data = [none] try { int count = getUsersWithoutAdditionalInfo( m_cms, m_stateBean.getType(), m_stateBean.getPath(), true).size(); if (count > ((Table)m_table).size()) { dataMap.put( CmsVaadinUtils.getMessageText(Messages.GUI_USERMANAGEMENT_TOT_COUNT_0), String.valueOf(count)); // depends on control dependency: [if], data = [none] } } catch (CmsException e) { //; } // depends on control dependency: [catch], data = [none] m_infoButton.replaceData(dataMap); // depends on control dependency: [if], data = [none] } else { int size = ((Table)m_table).size(); if (m_table instanceof CmsUserTable) { size = ((CmsUserTable)m_table).getVisibleUser().size(); // depends on control dependency: [if], data = [none] } m_infoButton.replaceData( Collections.singletonMap( CmsVaadinUtils.getMessageText(Messages.GUI_USERMANAGEMENT_COUNT_0), String.valueOf(size))); // depends on control dependency: [if], data = [none] } } }
public class class_name { public void setHeader(String name, String value) { if (headers == null) { headers = new HashMap<String, String>(); } if (value != null) { headers.put(name, value); } else { headers.remove(name); } } }
public class class_name { public void setHeader(String name, String value) { if (headers == null) { headers = new HashMap<String, String>(); // depends on control dependency: [if], data = [none] } if (value != null) { headers.put(name, value); // depends on control dependency: [if], data = [none] } else { headers.remove(name); // depends on control dependency: [if], data = [none] } } }
public class class_name { @Override public List<Form> getFormDescendants( Long electronicFormIdParam, boolean includeFieldDataParam, boolean includeTableFieldsParam, boolean includeTableFieldFormRecordInfoParam) { if(electronicFormIdParam == null) { return null; } List<Long> electronicFormIds = new ArrayList(); electronicFormIds.add(electronicFormIdParam); //Get Form Descendants... return this.getFormDescendants( electronicFormIds, includeFieldDataParam, includeTableFieldsParam, includeTableFieldFormRecordInfoParam); } }
public class class_name { @Override public List<Form> getFormDescendants( Long electronicFormIdParam, boolean includeFieldDataParam, boolean includeTableFieldsParam, boolean includeTableFieldFormRecordInfoParam) { if(electronicFormIdParam == null) { return null; // depends on control dependency: [if], data = [none] } List<Long> electronicFormIds = new ArrayList(); electronicFormIds.add(electronicFormIdParam); //Get Form Descendants... return this.getFormDescendants( electronicFormIds, includeFieldDataParam, includeTableFieldsParam, includeTableFieldFormRecordInfoParam); } }
public class class_name { @Override public void actionCommit() { List<Throwable> errors = new ArrayList<Throwable>(); try { // if new create it first if (!m_searchManager.getSearchIndexesAll().contains(m_index)) { // check the index name for invalid characters CmsStringUtil.checkName( m_index.getName(), INDEX_NAME_CONSTRAINTS, Messages.ERR_SEARCHINDEX_BAD_INDEXNAME_4, Messages.get()); // empty or null name and uniqueness check in add method m_searchManager.addSearchIndex(m_index); } // check if field configuration has been updated, if thus set field configuration to the now used if (!m_index.getFieldConfigurationName().equals(m_index.getFieldConfiguration().getName())) { m_index.setFieldConfiguration( m_searchManager.getFieldConfiguration(m_index.getFieldConfigurationName())); } writeConfiguration(); } catch (Throwable t) { errors.add(t); } // set the list of errors to display when saving failed setCommitErrors(errors); } }
public class class_name { @Override public void actionCommit() { List<Throwable> errors = new ArrayList<Throwable>(); try { // if new create it first if (!m_searchManager.getSearchIndexesAll().contains(m_index)) { // check the index name for invalid characters CmsStringUtil.checkName( m_index.getName(), INDEX_NAME_CONSTRAINTS, Messages.ERR_SEARCHINDEX_BAD_INDEXNAME_4, Messages.get()); // depends on control dependency: [if], data = [none] // empty or null name and uniqueness check in add method m_searchManager.addSearchIndex(m_index); // depends on control dependency: [if], data = [none] } // check if field configuration has been updated, if thus set field configuration to the now used if (!m_index.getFieldConfigurationName().equals(m_index.getFieldConfiguration().getName())) { m_index.setFieldConfiguration( m_searchManager.getFieldConfiguration(m_index.getFieldConfigurationName())); // depends on control dependency: [if], data = [none] } writeConfiguration(); // depends on control dependency: [try], data = [none] } catch (Throwable t) { errors.add(t); } // depends on control dependency: [catch], data = [none] // set the list of errors to display when saving failed setCommitErrors(errors); } }
public class class_name { @NotNull public List<SxGeoResult> getList(@NotNull String ip) { if (!IPV4_COMMA_SEPARATED_PATTERN.matcher(ip).matches()) { throw new IllegalArgumentException("Illegal IP address or list: " + ip); } clientQueriesCount++; List<SxGeoResult> cachedResult = cache == null ? null : cache.getList(ip); if (cachedResult != null) { return cachedResult; } try { NodeList ipNodes = query(ip); ArrayList<SxGeoResult> result = new ArrayList<>(); for (int i = 0; i < ipNodes.getLength(); i++) { result.add(parseIp((Element) ipNodes.item(i))); } if (cache != null) { cache.add(ip, result); } return result; } catch (ParserConfigurationException | SAXException | IOException e) { throw new RuntimeException(e); } } }
public class class_name { @NotNull public List<SxGeoResult> getList(@NotNull String ip) { if (!IPV4_COMMA_SEPARATED_PATTERN.matcher(ip).matches()) { throw new IllegalArgumentException("Illegal IP address or list: " + ip); } clientQueriesCount++; List<SxGeoResult> cachedResult = cache == null ? null : cache.getList(ip); if (cachedResult != null) { return cachedResult; // depends on control dependency: [if], data = [none] } try { NodeList ipNodes = query(ip); ArrayList<SxGeoResult> result = new ArrayList<>(); for (int i = 0; i < ipNodes.getLength(); i++) { result.add(parseIp((Element) ipNodes.item(i))); // depends on control dependency: [for], data = [i] } if (cache != null) { cache.add(ip, result); // depends on control dependency: [if], data = [none] } return result; // depends on control dependency: [try], data = [none] } catch (ParserConfigurationException | SAXException | IOException e) { throw new RuntimeException(e); } // depends on control dependency: [catch], data = [none] } }
public class class_name { private static CmsWorkplaceSettings getWorkplaceSettings(CmsObject cms, HttpSession session) { CmsWorkplaceSettings settings = (CmsWorkplaceSettings)session.getAttribute( CmsWorkplaceManager.SESSION_WORKPLACE_SETTINGS); if (settings == null) { settings = CmsLoginHelper.initSiteAndProject(cms); if (VaadinService.getCurrentRequest() != null) { VaadinService.getCurrentRequest().getWrappedSession().setAttribute( CmsWorkplaceManager.SESSION_WORKPLACE_SETTINGS, settings); } else { session.setAttribute(CmsWorkplaceManager.SESSION_WORKPLACE_SETTINGS, settings); } } return settings; } }
public class class_name { private static CmsWorkplaceSettings getWorkplaceSettings(CmsObject cms, HttpSession session) { CmsWorkplaceSettings settings = (CmsWorkplaceSettings)session.getAttribute( CmsWorkplaceManager.SESSION_WORKPLACE_SETTINGS); if (settings == null) { settings = CmsLoginHelper.initSiteAndProject(cms); // depends on control dependency: [if], data = [none] if (VaadinService.getCurrentRequest() != null) { VaadinService.getCurrentRequest().getWrappedSession().setAttribute( CmsWorkplaceManager.SESSION_WORKPLACE_SETTINGS, settings); // depends on control dependency: [if], data = [none] } else { session.setAttribute(CmsWorkplaceManager.SESSION_WORKPLACE_SETTINGS, settings); // depends on control dependency: [if], data = [none] } } return settings; } }
public class class_name { public static int getWhiteSpaceLineStartAfter( String script, int end ) { int endLine = getLineEnd( script, end ); if( endLine < script.length() - 1 ) { int nextLineStart = endLine + 1; int nextLineEnd = getLineEnd( script, nextLineStart ); boolean whitespace = GosuStringUtil.isWhitespace( script.substring( nextLineStart, nextLineEnd ) ); if( whitespace ) { return nextLineStart; } } return -1; } }
public class class_name { public static int getWhiteSpaceLineStartAfter( String script, int end ) { int endLine = getLineEnd( script, end ); if( endLine < script.length() - 1 ) { int nextLineStart = endLine + 1; int nextLineEnd = getLineEnd( script, nextLineStart ); boolean whitespace = GosuStringUtil.isWhitespace( script.substring( nextLineStart, nextLineEnd ) ); if( whitespace ) { return nextLineStart; // depends on control dependency: [if], data = [none] } } return -1; } }