code
stringlengths
130
281k
code_dependency
stringlengths
182
306k
public class class_name { @Override public void setValueAt(final Object value, final List<Integer> row, final int col) { if (!isEditable()) { throw new IllegalStateException("Attempted to set a value on an uneditable model"); } Object rowBean = getRowBean(row); if (rowBean == null) { return; } int lvlIndex = getLevelIndex(row); LevelDetails level = levels.get(lvlIndex); if (col >= level.getColumnBeanProperties().length) { LOG.warn("Requested a col [" + col + "] that is not defined for level with [" + level.getColumnBeanProperties().length + "] columns"); return; } String property = level.getColumnBeanProperties()[col]; setBeanPropertyValue(property, rowBean, (Serializable) value); } }
public class class_name { @Override public void setValueAt(final Object value, final List<Integer> row, final int col) { if (!isEditable()) { throw new IllegalStateException("Attempted to set a value on an uneditable model"); } Object rowBean = getRowBean(row); if (rowBean == null) { return; // depends on control dependency: [if], data = [none] } int lvlIndex = getLevelIndex(row); LevelDetails level = levels.get(lvlIndex); if (col >= level.getColumnBeanProperties().length) { LOG.warn("Requested a col [" + col + "] that is not defined for level with [" + level.getColumnBeanProperties().length + "] columns"); // depends on control dependency: [if], data = [none] return; // depends on control dependency: [if], data = [none] } String property = level.getColumnBeanProperties()[col]; setBeanPropertyValue(property, rowBean, (Serializable) value); } }
public class class_name { public static void main(String[] args) { try { Twitter twitter = new TwitterFactory().getInstance(); int page = 1; List<User> users; do { users = twitter.getBlocksList(page); for (User user : users) { System.out.println("@" + user.getScreenName()); } page++; // this code ends up in an infinite loop due to the issue 1988 // http://code.google.com/p/twitter-api/issues/detail?id=1988 } while (users.size() > 0 && page <= 10); System.out.println("done."); System.exit(0); } catch (TwitterException te) { te.printStackTrace(); System.out.println("Failed to get blocking users: " + te.getMessage()); System.exit(-1); } } }
public class class_name { public static void main(String[] args) { try { Twitter twitter = new TwitterFactory().getInstance(); int page = 1; List<User> users; do { users = twitter.getBlocksList(page); for (User user : users) { System.out.println("@" + user.getScreenName()); // depends on control dependency: [for], data = [user] } page++; // this code ends up in an infinite loop due to the issue 1988 // http://code.google.com/p/twitter-api/issues/detail?id=1988 } while (users.size() > 0 && page <= 10); System.out.println("done."); // depends on control dependency: [try], data = [none] System.exit(0); // depends on control dependency: [try], data = [none] } catch (TwitterException te) { te.printStackTrace(); System.out.println("Failed to get blocking users: " + te.getMessage()); System.exit(-1); } // depends on control dependency: [catch], data = [none] } }
public class class_name { public static boolean isUDPLower(final Buffer t) { try { return t.capacity() == 3 && t.getByte(0) == 'u' && t.getByte(1) == 'd' && t.getByte(2) == 'p'; } catch (final IOException e) { return false; } } }
public class class_name { public static boolean isUDPLower(final Buffer t) { try { return t.capacity() == 3 && t.getByte(0) == 'u' && t.getByte(1) == 'd' && t.getByte(2) == 'p'; // depends on control dependency: [try], data = [none] } catch (final IOException e) { return false; } // depends on control dependency: [catch], data = [none] } }
public class class_name { protected void init(Context context, AttributeSet attrs, int defStyle) { // Load custom attributes final int layoutId; final CharSequence floatLabelText; final int floatLabelTextAppearance; final int floatLabelTextColor; final float floatLabelTextSize; if (attrs == null) { layoutId = getDefaultLayoutId(); isFloatOnFocusEnabled = true; floatLabelText = null; floatLabelTextAppearance = -1; floatLabelTextColor = 0x66000000; floatLabelTextSize = getResources().getDimensionPixelSize(R.dimen.flw_defaultLabelTextSize); } else { final TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.FloatingLabelWidgetBase, defStyle, 0); layoutId = a.getResourceId(R.styleable.FloatingLabelWidgetBase_android_layout, getDefaultLayoutId()); isFloatOnFocusEnabled = a.getBoolean(R.styleable.FloatingLabelWidgetBase_flw_floatOnFocus, true); floatLabelText = a.getText(R.styleable.FloatingLabelWidgetBase_flw_labelText); floatLabelTextColor = a.getColor(R.styleable.FloatingLabelWidgetBase_flw_labelTextColor, 0x66000000); floatLabelTextAppearance = a.getResourceId(R.styleable.FloatingLabelWidgetBase_flw_labelTextAppearance, -1); floatLabelTextSize = a.getDimension(R.styleable.FloatingLabelWidgetBase_flw_labelTextSize, getResources().getDimensionPixelSize(R.dimen.flw_defaultLabelTextSize)); a.recycle(); } inflateWidgetLayout(context, layoutId); getFloatingLabel().setFocusableInTouchMode(false); getFloatingLabel().setFocusable(false); setLabelAnimator(getDefaultLabelAnimator()); setLabelText(floatLabelText); if (floatLabelTextAppearance != -1) { setLabelTextAppearance(getContext(), floatLabelTextAppearance); } setLabelColor(floatLabelTextColor); setLabelTextSize(TypedValue.COMPLEX_UNIT_PX, floatLabelTextSize); afterLayoutInflated(context, attrs, defStyle); isLaidOut = false; getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { isLaidOut = true; setInitialWidgetState(); if (Build.VERSION.SDK_INT >= 16) { getViewTreeObserver().removeOnGlobalLayoutListener(this); } else { getViewTreeObserver().removeGlobalOnLayoutListener(this); } } }); // Mark init as complete to prevent accidentally breaking the view by // adding children initCompleted = true; onInitCompleted(); } }
public class class_name { protected void init(Context context, AttributeSet attrs, int defStyle) { // Load custom attributes final int layoutId; final CharSequence floatLabelText; final int floatLabelTextAppearance; final int floatLabelTextColor; final float floatLabelTextSize; if (attrs == null) { layoutId = getDefaultLayoutId(); // depends on control dependency: [if], data = [none] isFloatOnFocusEnabled = true; // depends on control dependency: [if], data = [none] floatLabelText = null; // depends on control dependency: [if], data = [none] floatLabelTextAppearance = -1; // depends on control dependency: [if], data = [none] floatLabelTextColor = 0x66000000; // depends on control dependency: [if], data = [none] floatLabelTextSize = getResources().getDimensionPixelSize(R.dimen.flw_defaultLabelTextSize); // depends on control dependency: [if], data = [none] } else { final TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.FloatingLabelWidgetBase, defStyle, 0); layoutId = a.getResourceId(R.styleable.FloatingLabelWidgetBase_android_layout, getDefaultLayoutId()); // depends on control dependency: [if], data = [none] isFloatOnFocusEnabled = a.getBoolean(R.styleable.FloatingLabelWidgetBase_flw_floatOnFocus, true); // depends on control dependency: [if], data = [none] floatLabelText = a.getText(R.styleable.FloatingLabelWidgetBase_flw_labelText); // depends on control dependency: [if], data = [none] floatLabelTextColor = a.getColor(R.styleable.FloatingLabelWidgetBase_flw_labelTextColor, 0x66000000); // depends on control dependency: [if], data = [none] floatLabelTextAppearance = a.getResourceId(R.styleable.FloatingLabelWidgetBase_flw_labelTextAppearance, -1); // depends on control dependency: [if], data = [none] floatLabelTextSize = a.getDimension(R.styleable.FloatingLabelWidgetBase_flw_labelTextSize, getResources().getDimensionPixelSize(R.dimen.flw_defaultLabelTextSize)); // depends on control dependency: [if], data = [none] a.recycle(); // depends on control dependency: [if], data = [none] } inflateWidgetLayout(context, layoutId); getFloatingLabel().setFocusableInTouchMode(false); getFloatingLabel().setFocusable(false); setLabelAnimator(getDefaultLabelAnimator()); setLabelText(floatLabelText); if (floatLabelTextAppearance != -1) { setLabelTextAppearance(getContext(), floatLabelTextAppearance); // depends on control dependency: [if], data = [none] } setLabelColor(floatLabelTextColor); setLabelTextSize(TypedValue.COMPLEX_UNIT_PX, floatLabelTextSize); afterLayoutInflated(context, attrs, defStyle); isLaidOut = false; getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { isLaidOut = true; setInitialWidgetState(); if (Build.VERSION.SDK_INT >= 16) { getViewTreeObserver().removeOnGlobalLayoutListener(this); // depends on control dependency: [if], data = [none] } else { getViewTreeObserver().removeGlobalOnLayoutListener(this); // depends on control dependency: [if], data = [none] } } }); // Mark init as complete to prevent accidentally breaking the view by // adding children initCompleted = true; onInitCompleted(); } }
public class class_name { private ApiDoc getApiDoc(Class<?> controller, MethodDisplay displayMethodAs) { log.debug("Getting JSONDoc for class: " + controller.getName()); ApiDoc apiDoc = initApiDoc(controller); apiDoc.setSupportedversions(JSONDocApiVersionDocBuilder.build(controller)); apiDoc.setAuth(JSONDocApiAuthDocBuilder.getApiAuthDocForController(controller)); apiDoc.setMethods(getApiMethodDocs(controller, displayMethodAs)); if(controller.isAnnotationPresent(Api.class)) { apiDoc = mergeApiDoc(controller, apiDoc); } return apiDoc; } }
public class class_name { private ApiDoc getApiDoc(Class<?> controller, MethodDisplay displayMethodAs) { log.debug("Getting JSONDoc for class: " + controller.getName()); ApiDoc apiDoc = initApiDoc(controller); apiDoc.setSupportedversions(JSONDocApiVersionDocBuilder.build(controller)); apiDoc.setAuth(JSONDocApiAuthDocBuilder.getApiAuthDocForController(controller)); apiDoc.setMethods(getApiMethodDocs(controller, displayMethodAs)); if(controller.isAnnotationPresent(Api.class)) { apiDoc = mergeApiDoc(controller, apiDoc); // depends on control dependency: [if], data = [none] } return apiDoc; } }
public class class_name { public static int compareLexicographically(IntTuple t0, IntTuple t1) { Utils.checkForEqualSize(t0, t1); for (int i=0; i<t0.getSize(); i++) { if (t0.get(i) < t1.get(i)) { return -1; } else if (t0.get(i) > t1.get(i)) { return 1; } } return 0; } }
public class class_name { public static int compareLexicographically(IntTuple t0, IntTuple t1) { Utils.checkForEqualSize(t0, t1); for (int i=0; i<t0.getSize(); i++) { if (t0.get(i) < t1.get(i)) { return -1; // depends on control dependency: [if], data = [none] } else if (t0.get(i) > t1.get(i)) { return 1; // depends on control dependency: [if], data = [none] } } return 0; } }
public class class_name { public static long mediaToEdited(TrakBox trak, long mediaTv, int movieTimescale) { if (trak.getEdits() == null) return mediaTv; long accum = 0; for (Edit edit : trak.getEdits()) { if (mediaTv < edit.getMediaTime()) return accum; long duration = trak.rescale(edit.getDuration(), movieTimescale); if (edit.getMediaTime() != -1 && (mediaTv >= edit.getMediaTime() && mediaTv < edit.getMediaTime() + duration)) { accum += mediaTv - edit.getMediaTime(); break; } accum += duration; } return accum; } }
public class class_name { public static long mediaToEdited(TrakBox trak, long mediaTv, int movieTimescale) { if (trak.getEdits() == null) return mediaTv; long accum = 0; for (Edit edit : trak.getEdits()) { if (mediaTv < edit.getMediaTime()) return accum; long duration = trak.rescale(edit.getDuration(), movieTimescale); if (edit.getMediaTime() != -1 && (mediaTv >= edit.getMediaTime() && mediaTv < edit.getMediaTime() + duration)) { accum += mediaTv - edit.getMediaTime(); // depends on control dependency: [if], data = [none] break; } accum += duration; // depends on control dependency: [for], data = [none] } return accum; } }
public class class_name { public static void loadFromDiskAnd( DataFileManager manager, IndyObjectMapper serializer, StoreKey key, final ChangeSummary summary, Consumer<ArtifactStore> consumer ) { if ( key != null ) // Load a single file { DataFile f = manager.getDataFile( INDY_STORE, key.getPackageType(), key.getType().singularEndpointName(), key.getName() + ".json" ); if ( f.exists() ) { ArtifactStore store; try { String json = f.readString(); store = serializer.readValue( json, key.getType().getStoreClass() ); } catch ( IOException e ) { logger.error( "Failed to read file", e ); return; } consumer.accept( store ); } return; } // Load all DataFile[] packageDirs = manager.getDataFile( INDY_STORE ).listFiles( ( f ) -> true ); for ( DataFile pkgDir : packageDirs ) { for ( StoreType type : StoreType.values() ) { DataFile[] files = pkgDir.getChild( type.singularEndpointName() ).listFiles( f -> true ); if ( files != null ) { for ( final DataFile f : files ) { try { final String json = f.readString(); final ArtifactStore store = serializer.readValue( json, type.getStoreClass() ); if ( store == null ) { f.delete( summary ); } else { consumer.accept( store ); } } catch ( final IOException e ) { logger.error( String.format( "Failed to load %s store: %s. Reason: %s", type, f, e.getMessage() ), e ); try { f.delete( summary ); } catch ( IOException e1 ) { logger.error( "Failed to delete invalid store definition file: " + f, e ); } } } } } } } }
public class class_name { public static void loadFromDiskAnd( DataFileManager manager, IndyObjectMapper serializer, StoreKey key, final ChangeSummary summary, Consumer<ArtifactStore> consumer ) { if ( key != null ) // Load a single file { DataFile f = manager.getDataFile( INDY_STORE, key.getPackageType(), key.getType().singularEndpointName(), key.getName() + ".json" ); if ( f.exists() ) { ArtifactStore store; try { String json = f.readString(); store = serializer.readValue( json, key.getType().getStoreClass() ); // depends on control dependency: [try], data = [none] } catch ( IOException e ) { logger.error( "Failed to read file", e ); return; } // depends on control dependency: [catch], data = [none] consumer.accept( store ); // depends on control dependency: [if], data = [none] } return; // depends on control dependency: [if], data = [none] } // Load all DataFile[] packageDirs = manager.getDataFile( INDY_STORE ).listFiles( ( f ) -> true ); for ( DataFile pkgDir : packageDirs ) { for ( StoreType type : StoreType.values() ) { DataFile[] files = pkgDir.getChild( type.singularEndpointName() ).listFiles( f -> true ); if ( files != null ) { for ( final DataFile f : files ) { try { final String json = f.readString(); final ArtifactStore store = serializer.readValue( json, type.getStoreClass() ); if ( store == null ) { f.delete( summary ); // depends on control dependency: [if], data = [none] } else { consumer.accept( store ); // depends on control dependency: [if], data = [( store] } } catch ( final IOException e ) { logger.error( String.format( "Failed to load %s store: %s. Reason: %s", type, f, e.getMessage() ), e ); try { f.delete( summary ); // depends on control dependency: [try], data = [none] } catch ( IOException e1 ) { logger.error( "Failed to delete invalid store definition file: " + f, e ); } // depends on control dependency: [catch], data = [none] } // depends on control dependency: [catch], data = [none] } } } } } }
public class class_name { @NonNull public static SourceParams createCardParams(@NonNull Card card) { final SourceParams params = new SourceParams().setType(Source.CARD); // Not enforcing all fields to exist at this level. // Instead, the server will return an error for invalid data. final AbstractMap<String, Object> basicInfoMap = new HashMap<>(); basicInfoMap.put(FIELD_NUMBER, card.getNumber()); basicInfoMap.put(FIELD_EXP_MONTH, card.getExpMonth()); basicInfoMap.put(FIELD_EXP_YEAR, card.getExpYear()); basicInfoMap.put(FIELD_CVC, card.getCVC()); removeNullAndEmptyParams(basicInfoMap); params.setApiParameterMap(basicInfoMap); final Map<String, Object> addressMap = new HashMap<>(); addressMap.put(FIELD_LINE_1, card.getAddressLine1()); addressMap.put(FIELD_LINE_2, card.getAddressLine2()); addressMap.put(FIELD_CITY, card.getAddressCity()); addressMap.put(FIELD_COUNTRY, card.getAddressCountry()); addressMap.put(FIELD_STATE, card.getAddressState()); addressMap.put(FIELD_POSTAL_CODE, card.getAddressZip()); removeNullAndEmptyParams(addressMap); // If there are any keys left... final Map<String, Object> ownerMap = new HashMap<>(); ownerMap.put(FIELD_NAME, card.getName()); if (addressMap.keySet().size() > 0) { ownerMap.put(FIELD_ADDRESS, addressMap); } removeNullAndEmptyParams(ownerMap); if (ownerMap.keySet().size() > 0) { params.setOwner(ownerMap); } final Map<String, String> metadata = card.getMetadata(); if (metadata != null) { params.setMetaData(metadata); } return params; } }
public class class_name { @NonNull public static SourceParams createCardParams(@NonNull Card card) { final SourceParams params = new SourceParams().setType(Source.CARD); // Not enforcing all fields to exist at this level. // Instead, the server will return an error for invalid data. final AbstractMap<String, Object> basicInfoMap = new HashMap<>(); basicInfoMap.put(FIELD_NUMBER, card.getNumber()); basicInfoMap.put(FIELD_EXP_MONTH, card.getExpMonth()); basicInfoMap.put(FIELD_EXP_YEAR, card.getExpYear()); basicInfoMap.put(FIELD_CVC, card.getCVC()); removeNullAndEmptyParams(basicInfoMap); params.setApiParameterMap(basicInfoMap); final Map<String, Object> addressMap = new HashMap<>(); addressMap.put(FIELD_LINE_1, card.getAddressLine1()); addressMap.put(FIELD_LINE_2, card.getAddressLine2()); addressMap.put(FIELD_CITY, card.getAddressCity()); addressMap.put(FIELD_COUNTRY, card.getAddressCountry()); addressMap.put(FIELD_STATE, card.getAddressState()); addressMap.put(FIELD_POSTAL_CODE, card.getAddressZip()); removeNullAndEmptyParams(addressMap); // If there are any keys left... final Map<String, Object> ownerMap = new HashMap<>(); ownerMap.put(FIELD_NAME, card.getName()); if (addressMap.keySet().size() > 0) { ownerMap.put(FIELD_ADDRESS, addressMap); // depends on control dependency: [if], data = [none] } removeNullAndEmptyParams(ownerMap); if (ownerMap.keySet().size() > 0) { params.setOwner(ownerMap); // depends on control dependency: [if], data = [none] } final Map<String, String> metadata = card.getMetadata(); if (metadata != null) { params.setMetaData(metadata); // depends on control dependency: [if], data = [(metadata] } return params; } }
public class class_name { private void resolvePackageDependencies() throws IOException { // FIXME: should produce a wy.lock file? Configuration.Schema buildSchema = environment.getBuildSchema(); // Global root is where all dependencies will be stored Path.Root repository = getRepositoryRoot(); // Dig out all the defined dependencies List<Path.ID> deps = configuration.matchAll(Trie.fromString("dependencies/**")); // Resolve each dependencies and add to project roots for (int i = 0; i != deps.size(); ++i) { Path.ID dep = deps.get(i); // Get dependency name String name = dep.get(1); // Get version string UTF8 version = configuration.get(UTF8.class, dep); // Construct path to the config file Trie root = Trie.fromString(name + "-v" + version); // Attempt to resolve it. if (!repository.exists(root, ZipFile.ContentType)) { // TODO: employ a package resolver here // FIXME: handle better error handling. throw new RuntimeException("missing dependency \"" + name + "-" + version + "\""); } else { // Extract entry for ZipFile Path.Entry<ZipFile> zipfile = repository.get(root, ZipFile.ContentType); // Construct root repesenting this ZipFile Path.Root pkgRoot = new ZipFileRoot(zipfile, environment.getContentRegistry()); // Extract configuration from package Path.Entry<ConfigFile> entry = pkgRoot.get(Trie.fromString("wy"),ConfigFile.ContentType); if(entry == null) { throw new RuntimeException("corrupt package (missing wy.toml) \"" + name + "-" + version + "\""); } else { ConfigFile pkgcfg = pkgRoot.get(Trie.fromString("wy"),ConfigFile.ContentType).read(); // Construct a package representation of this root. Build.Package pkg = new Package(pkgRoot,pkgcfg.toConfiguration(buildSchema)); // Add a relative ZipFile root project.getPackages().add(pkg); } } } } }
public class class_name { private void resolvePackageDependencies() throws IOException { // FIXME: should produce a wy.lock file? Configuration.Schema buildSchema = environment.getBuildSchema(); // Global root is where all dependencies will be stored Path.Root repository = getRepositoryRoot(); // Dig out all the defined dependencies List<Path.ID> deps = configuration.matchAll(Trie.fromString("dependencies/**")); // Resolve each dependencies and add to project roots for (int i = 0; i != deps.size(); ++i) { Path.ID dep = deps.get(i); // Get dependency name String name = dep.get(1); // Get version string UTF8 version = configuration.get(UTF8.class, dep); // Construct path to the config file Trie root = Trie.fromString(name + "-v" + version); // Attempt to resolve it. if (!repository.exists(root, ZipFile.ContentType)) { // TODO: employ a package resolver here // FIXME: handle better error handling. throw new RuntimeException("missing dependency \"" + name + "-" + version + "\""); } else { // Extract entry for ZipFile Path.Entry<ZipFile> zipfile = repository.get(root, ZipFile.ContentType); // Construct root repesenting this ZipFile Path.Root pkgRoot = new ZipFileRoot(zipfile, environment.getContentRegistry()); // Extract configuration from package Path.Entry<ConfigFile> entry = pkgRoot.get(Trie.fromString("wy"),ConfigFile.ContentType); if(entry == null) { throw new RuntimeException("corrupt package (missing wy.toml) \"" + name + "-" + version + "\""); } else { ConfigFile pkgcfg = pkgRoot.get(Trie.fromString("wy"),ConfigFile.ContentType).read(); // Construct a package representation of this root. Build.Package pkg = new Package(pkgRoot,pkgcfg.toConfiguration(buildSchema)); // Add a relative ZipFile root project.getPackages().add(pkg); // depends on control dependency: [if], data = [none] } } } } }
public class class_name { protected void setObject(PreparedStatement statement, int i, Object value) throws SQLException { if (value instanceof InParameter || value instanceof OutParameter) { if (value instanceof InParameter) { InParameter in = (InParameter) value; Object val = in.getValue(); if (null == val) { statement.setNull(i, in.getType()); } else { statement.setObject(i, val, in.getType()); } } if (value instanceof OutParameter) { try { OutParameter out = (OutParameter) value; ((CallableStatement) statement).registerOutParameter(i, out.getType()); } catch (ClassCastException e) { throw new SQLException("Cannot register out parameter."); } } } else { try { statement.setObject(i, value); } catch (SQLException e) { if (value == null) { SQLException se = new SQLException("Your JDBC driver may not support null arguments for setObject. Consider using Groovy's InParameter feature." + (e.getMessage() == null ? "" : " (CAUSE: " + e.getMessage() + ")")); se.setNextException(e); throw se; } else { throw e; } } } } }
public class class_name { protected void setObject(PreparedStatement statement, int i, Object value) throws SQLException { if (value instanceof InParameter || value instanceof OutParameter) { if (value instanceof InParameter) { InParameter in = (InParameter) value; Object val = in.getValue(); if (null == val) { statement.setNull(i, in.getType()); // depends on control dependency: [if], data = [none] } else { statement.setObject(i, val, in.getType()); // depends on control dependency: [if], data = [none] } } if (value instanceof OutParameter) { try { OutParameter out = (OutParameter) value; ((CallableStatement) statement).registerOutParameter(i, out.getType()); // depends on control dependency: [try], data = [none] } catch (ClassCastException e) { throw new SQLException("Cannot register out parameter."); } // depends on control dependency: [catch], data = [none] } } else { try { statement.setObject(i, value); // depends on control dependency: [try], data = [none] } catch (SQLException e) { if (value == null) { SQLException se = new SQLException("Your JDBC driver may not support null arguments for setObject. Consider using Groovy's InParameter feature." + (e.getMessage() == null ? "" : " (CAUSE: " + e.getMessage() + ")")); se.setNextException(e); // depends on control dependency: [if], data = [none] throw se; } else { throw e; } } // depends on control dependency: [catch], data = [none] } } }
public class class_name { public static ReferenceBase createFromXsd(XsdAbstractElement element) { String ref = getRef(element); String name = getName(element); if (!(element instanceof XsdNamedElements)){ return new ConcreteElement(element); } if (ref == null){ if (name == null){ return new ConcreteElement(element); } else { return new NamedConcreteElement((XsdNamedElements) element, name); } } else { return new UnsolvedReference((XsdNamedElements) element); } } }
public class class_name { public static ReferenceBase createFromXsd(XsdAbstractElement element) { String ref = getRef(element); String name = getName(element); if (!(element instanceof XsdNamedElements)){ return new ConcreteElement(element); // depends on control dependency: [if], data = [none] } if (ref == null){ if (name == null){ return new ConcreteElement(element); // depends on control dependency: [if], data = [none] } else { return new NamedConcreteElement((XsdNamedElements) element, name); // depends on control dependency: [if], data = [none] } } else { return new UnsolvedReference((XsdNamedElements) element); // depends on control dependency: [if], data = [none] } } }
public class class_name { public void executeTaskIfMatch(long millis) { final Lock readLock = lock.readLock(); try { readLock.lock(); executeTaskIfMatchInternal(millis); } finally { readLock.unlock(); } } }
public class class_name { public void executeTaskIfMatch(long millis) { final Lock readLock = lock.readLock(); try { readLock.lock(); // depends on control dependency: [try], data = [none] executeTaskIfMatchInternal(millis); // depends on control dependency: [try], data = [none] } finally { readLock.unlock(); } } }
public class class_name { public WebSocket recognizeUsingWebSocket(RecognizeOptions recognizeOptions, RecognizeCallback callback) { Validator.notNull(recognizeOptions, "recognizeOptions cannot be null"); Validator.notNull(recognizeOptions.audio(), "audio cannot be null"); Validator.notNull(callback, "callback cannot be null"); HttpUrl.Builder urlBuilder = HttpUrl.parse(getEndPoint() + "/v1/recognize").newBuilder(); if (recognizeOptions.model() != null) { urlBuilder.addQueryParameter("model", recognizeOptions.model()); } if (recognizeOptions.customizationId() != null) { urlBuilder.addQueryParameter("customization_id", recognizeOptions.customizationId()); } if (recognizeOptions.languageCustomizationId() != null) { urlBuilder.addQueryParameter("language_customization_id", recognizeOptions.languageCustomizationId()); } if (recognizeOptions.acousticCustomizationId() != null) { urlBuilder.addQueryParameter("acoustic_customization_id", recognizeOptions.acousticCustomizationId()); } if (recognizeOptions.baseModelVersion() != null) { urlBuilder.addQueryParameter("base_model_version", recognizeOptions.baseModelVersion()); } String url = urlBuilder.toString().replace("https://", "wss://"); Request.Builder builder = new Request.Builder().url(url); setAuthentication(builder); setDefaultHeaders(builder); OkHttpClient client = configureHttpClient(); return client.newWebSocket(builder.build(), new SpeechToTextWebSocketListener(recognizeOptions, callback)); } }
public class class_name { public WebSocket recognizeUsingWebSocket(RecognizeOptions recognizeOptions, RecognizeCallback callback) { Validator.notNull(recognizeOptions, "recognizeOptions cannot be null"); Validator.notNull(recognizeOptions.audio(), "audio cannot be null"); Validator.notNull(callback, "callback cannot be null"); HttpUrl.Builder urlBuilder = HttpUrl.parse(getEndPoint() + "/v1/recognize").newBuilder(); if (recognizeOptions.model() != null) { urlBuilder.addQueryParameter("model", recognizeOptions.model()); // depends on control dependency: [if], data = [none] } if (recognizeOptions.customizationId() != null) { urlBuilder.addQueryParameter("customization_id", recognizeOptions.customizationId()); // depends on control dependency: [if], data = [none] } if (recognizeOptions.languageCustomizationId() != null) { urlBuilder.addQueryParameter("language_customization_id", recognizeOptions.languageCustomizationId()); // depends on control dependency: [if], data = [none] } if (recognizeOptions.acousticCustomizationId() != null) { urlBuilder.addQueryParameter("acoustic_customization_id", recognizeOptions.acousticCustomizationId()); // depends on control dependency: [if], data = [none] } if (recognizeOptions.baseModelVersion() != null) { urlBuilder.addQueryParameter("base_model_version", recognizeOptions.baseModelVersion()); // depends on control dependency: [if], data = [none] } String url = urlBuilder.toString().replace("https://", "wss://"); Request.Builder builder = new Request.Builder().url(url); setAuthentication(builder); setDefaultHeaders(builder); OkHttpClient client = configureHttpClient(); return client.newWebSocket(builder.build(), new SpeechToTextWebSocketListener(recognizeOptions, callback)); } }
public class class_name { public GraphicalModel compileModel() { GraphicalModel compiled = new GraphicalModel(); for (GraphicalModel.Factor factor : model.factors) { compiled.addStaticFactor(factor.neigborIndices, factor.getDimensions(), assign -> factor.getAssignmentValue(assign, weights)); } // Add any metadata for (int var = 0; var < model.numVariables(); ++var) { Map<String, String> metadata = model.getVariableMetaDataByReference(var); if (metadata.containsKey(VARIABLE_OBSERVED_VALUE)) { compiled.getVariableMetaDataByReference(var).put(VARIABLE_OBSERVED_VALUE, metadata.get(VARIABLE_OBSERVED_VALUE)); } } return compiled; } }
public class class_name { public GraphicalModel compileModel() { GraphicalModel compiled = new GraphicalModel(); for (GraphicalModel.Factor factor : model.factors) { compiled.addStaticFactor(factor.neigborIndices, factor.getDimensions(), assign -> factor.getAssignmentValue(assign, weights)); // depends on control dependency: [for], data = [factor] } // Add any metadata for (int var = 0; var < model.numVariables(); ++var) { Map<String, String> metadata = model.getVariableMetaDataByReference(var); if (metadata.containsKey(VARIABLE_OBSERVED_VALUE)) { compiled.getVariableMetaDataByReference(var).put(VARIABLE_OBSERVED_VALUE, metadata.get(VARIABLE_OBSERVED_VALUE)); // depends on control dependency: [if], data = [none] } } return compiled; } }
public class class_name { public static String encode (String string, boolean encodeNewline, boolean encodeSubsequentBlanksToNbsp, boolean encodeNonLatin) { if (string == null) { return ""; } StringBuilder sb = null; //create later on demand String app; char c = ' '; char prevC; int length = string.length(); for (int i = 0; i < length; ++i) { app = null; prevC = c; c = string.charAt(i); // All characters before letters if ((int)c < 0x41) { switch (c) { case '"': app = "&quot;"; break; //" case '&': app = "&amp;"; break; //& case '<': app = "&lt;"; break; //< case '>': app = "&gt;"; break; //> case ' ': if (encodeSubsequentBlanksToNbsp && prevC == ' ') { //Space at beginning or after another space app = "&#160;"; } break; case '\n': if (encodeNewline) { app = "<br/>"; } break; default: break; } // http://www.w3.org/MarkUp/html3/specialchars.html // From C0 extension U+0000-U+001F only U+0009, U+000A and // U+000D are valid control characters if (c <= 0x1F && c != 0x09 && c != 0x0A && c != 0x0D) { // Ignore escape character app = ""; } } else if (encodeNonLatin && (int)c > 0x80) { switch(c) { //german umlauts case '\u00E4' : app = "&auml;"; break; case '\u00C4' : app = "&Auml;"; break; case '\u00F6' : app = "&ouml;"; break; case '\u00D6' : app = "&Ouml;"; break; case '\u00FC' : app = "&uuml;"; break; case '\u00DC' : app = "&Uuml;"; break; case '\u00DF' : app = "&szlig;"; break; //misc //case 0x80: app = "&euro;"; break; sometimes euro symbol is ascii 128, should we suport it? case '\u20AC': app = "&euro;"; break; case '\u00AB': app = "&laquo;"; break; case '\u00BB': app = "&raquo;"; break; case '\u00A0': app = "&#160;"; break; default : //encode all non basic latin characters app = "&#" + ((int)c) + ";"; break; } } if (app != null) { if (sb == null) { sb = new StringBuilder(string.substring(0, i)); } sb.append(app); } else { if (sb != null) { sb.append(c); } } } if (sb == null) { return string; } else { return sb.toString(); } } }
public class class_name { public static String encode (String string, boolean encodeNewline, boolean encodeSubsequentBlanksToNbsp, boolean encodeNonLatin) { if (string == null) { return ""; // depends on control dependency: [if], data = [none] } StringBuilder sb = null; //create later on demand String app; char c = ' '; char prevC; int length = string.length(); for (int i = 0; i < length; ++i) { app = null; // depends on control dependency: [for], data = [none] prevC = c; // depends on control dependency: [for], data = [none] c = string.charAt(i); // depends on control dependency: [for], data = [i] // All characters before letters if ((int)c < 0x41) { switch (c) { case '"': app = "&quot;"; break; //" case '&': app = "&amp;"; break; //& case '<': app = "&lt;"; break; //< case '>': app = "&gt;"; break; //> case ' ': if (encodeSubsequentBlanksToNbsp && prevC == ' ') { //Space at beginning or after another space app = "&#160;"; // depends on control dependency: [if], data = [none] } break; case '\n': if (encodeNewline) { app = "<br/>"; // depends on control dependency: [if], data = [none] } break; default: break; } // http://www.w3.org/MarkUp/html3/specialchars.html // From C0 extension U+0000-U+001F only U+0009, U+000A and // U+000D are valid control characters if (c <= 0x1F && c != 0x09 && c != 0x0A && c != 0x0D) { // Ignore escape character app = ""; // depends on control dependency: [if], data = [none] } } else if (encodeNonLatin && (int)c > 0x80) { switch(c) { //german umlauts case '\u00E4' : app = "&auml;"; break; case '\u00C4' : app = "&Auml;"; break; case '\u00F6' : app = "&ouml;"; break; case '\u00D6' : app = "&Ouml;"; break; case '\u00FC' : app = "&uuml;"; break; case '\u00DC' : app = "&Uuml;"; break; case '\u00DF' : app = "&szlig;"; break; //misc //case 0x80: app = "&euro;"; break; sometimes euro symbol is ascii 128, should we suport it? case '\u20AC': app = "&euro;"; break; case '\u00AB': app = "&laquo;"; break; case '\u00BB': app = "&raquo;"; break; case '\u00A0': app = "&#160;"; break; default : //encode all non basic latin characters app = "&#" + ((int)c) + ";"; break; } } if (app != null) { if (sb == null) { sb = new StringBuilder(string.substring(0, i)); // depends on control dependency: [if], data = [none] } sb.append(app); // depends on control dependency: [if], data = [(app] } else { if (sb != null) { sb.append(c); // depends on control dependency: [if], data = [none] } } } if (sb == null) { return string; // depends on control dependency: [if], data = [none] } else { return sb.toString(); // depends on control dependency: [if], data = [none] } } }
public class class_name { public final void mNS_PREFIX() throws RecognitionException { try { int _type = NS_PREFIX; int _channel = DEFAULT_TOKEN_CHANNEL; // BELScript.g:293:10: ( LETTER ( LETTER | DIGIT )* ':' ) // BELScript.g:294:5: LETTER ( LETTER | DIGIT )* ':' { mLETTER(); // BELScript.g:294:12: ( LETTER | DIGIT )* loop9: do { int alt9=2; int LA9_0 = input.LA(1); if ( ((LA9_0>='0' && LA9_0<='9')||(LA9_0>='A' && LA9_0<='Z')||(LA9_0>='a' && LA9_0<='z')) ) { alt9=1; } switch (alt9) { case 1 : // BELScript.g: { if ( (input.LA(1)>='0' && input.LA(1)<='9')||(input.LA(1)>='A' && input.LA(1)<='Z')||(input.LA(1)>='a' && input.LA(1)<='z') ) { input.consume(); } else { MismatchedSetException mse = new MismatchedSetException(null,input); recover(mse); throw mse;} } break; default : break loop9; } } while (true); match(':'); } state.type = _type; state.channel = _channel; } finally { } } }
public class class_name { public final void mNS_PREFIX() throws RecognitionException { try { int _type = NS_PREFIX; int _channel = DEFAULT_TOKEN_CHANNEL; // BELScript.g:293:10: ( LETTER ( LETTER | DIGIT )* ':' ) // BELScript.g:294:5: LETTER ( LETTER | DIGIT )* ':' { mLETTER(); // BELScript.g:294:12: ( LETTER | DIGIT )* loop9: do { int alt9=2; int LA9_0 = input.LA(1); if ( ((LA9_0>='0' && LA9_0<='9')||(LA9_0>='A' && LA9_0<='Z')||(LA9_0>='a' && LA9_0<='z')) ) { alt9=1; // depends on control dependency: [if], data = [none] } switch (alt9) { case 1 : // BELScript.g: { if ( (input.LA(1)>='0' && input.LA(1)<='9')||(input.LA(1)>='A' && input.LA(1)<='Z')||(input.LA(1)>='a' && input.LA(1)<='z') ) { input.consume(); // depends on control dependency: [if], data = [none] } else { MismatchedSetException mse = new MismatchedSetException(null,input); recover(mse); // depends on control dependency: [if], data = [none] throw mse;} } break; default : break loop9; } } while (true); match(':'); } state.type = _type; state.channel = _channel; } finally { } } }
public class class_name { public void init(byte[] blob, int start, int len) throws SshException { ByteArrayReader bar = new ByteArrayReader(blob, start, len); try { // this.hostKey = hostKey; RSAPublicKeySpec rsaKey; // Extract the key information String header = bar.readString(); if (!header.equals(getAlgorithm())) { throw new SshException("The encoded key is not RSA", SshException.INTERNAL_ERROR); } BigInteger e = bar.readBigInteger(); BigInteger n = bar.readBigInteger(); rsaKey = new RSAPublicKeySpec(n, e); try { KeyFactory kf = JCEProvider .getProviderForAlgorithm(JCEAlgorithms.JCE_RSA) == null ? KeyFactory .getInstance(JCEAlgorithms.JCE_RSA) : KeyFactory .getInstance( JCEAlgorithms.JCE_RSA, JCEProvider .getProviderForAlgorithm(JCEAlgorithms.JCE_RSA)); pubKey = (RSAPublicKey) kf.generatePublic(rsaKey); } catch (Exception ex) { throw new SshException( "Failed to obtain RSA key instance from JCE", SshException.INTERNAL_ERROR, ex); } } catch (IOException ioe) { throw new SshException("Failed to read encoded key data", SshException.INTERNAL_ERROR); } finally { try { bar.close(); } catch (IOException e) { } } } }
public class class_name { public void init(byte[] blob, int start, int len) throws SshException { ByteArrayReader bar = new ByteArrayReader(blob, start, len); try { // this.hostKey = hostKey; RSAPublicKeySpec rsaKey; // Extract the key information String header = bar.readString(); if (!header.equals(getAlgorithm())) { throw new SshException("The encoded key is not RSA", SshException.INTERNAL_ERROR); } BigInteger e = bar.readBigInteger(); BigInteger n = bar.readBigInteger(); rsaKey = new RSAPublicKeySpec(n, e); try { KeyFactory kf = JCEProvider .getProviderForAlgorithm(JCEAlgorithms.JCE_RSA) == null ? KeyFactory .getInstance(JCEAlgorithms.JCE_RSA) : KeyFactory .getInstance( JCEAlgorithms.JCE_RSA, JCEProvider .getProviderForAlgorithm(JCEAlgorithms.JCE_RSA)); pubKey = (RSAPublicKey) kf.generatePublic(rsaKey); // depends on control dependency: [try], data = [none] } catch (Exception ex) { throw new SshException( "Failed to obtain RSA key instance from JCE", SshException.INTERNAL_ERROR, ex); } // depends on control dependency: [catch], data = [none] } catch (IOException ioe) { throw new SshException("Failed to read encoded key data", SshException.INTERNAL_ERROR); } finally { try { bar.close(); // depends on control dependency: [try], data = [none] } catch (IOException e) { } // depends on control dependency: [catch], data = [none] } } }
public class class_name { @Override public void internalWrite(Server server, Query query, ImmutableList<Result> results) throws Exception { checkFile(query); List<String> typeNames = getTypeNames(); for (Result result : results) { String[] keyString = KeyUtils.getKeyString(server, query, result, typeNames, null).split("\\."); if (isNumeric(result.getValue()) && filters.contains(keyString[2])) { int thresholdPos = filters.indexOf(keyString[2]); StringBuilder sb = new StringBuilder(); sb.append("["); sb.append(result.getEpoch()); sb.append("] PROCESS_SERVICE_CHECK_RESULT;"); sb.append(nagiosHost); sb.append(";"); if (prefix != null) { sb.append(prefix); } sb.append(keyString[2]); if (suffix != null) { sb.append(suffix); } sb.append(";"); sb.append(nagiosCheckValue(result.getValue().toString(), thresholds.get(thresholdPos))); sb.append(";"); //Missing the performance information logger.info(sb.toString()); } } } }
public class class_name { @Override public void internalWrite(Server server, Query query, ImmutableList<Result> results) throws Exception { checkFile(query); List<String> typeNames = getTypeNames(); for (Result result : results) { String[] keyString = KeyUtils.getKeyString(server, query, result, typeNames, null).split("\\."); if (isNumeric(result.getValue()) && filters.contains(keyString[2])) { int thresholdPos = filters.indexOf(keyString[2]); StringBuilder sb = new StringBuilder(); sb.append("["); // depends on control dependency: [if], data = [none] sb.append(result.getEpoch()); // depends on control dependency: [if], data = [none] sb.append("] PROCESS_SERVICE_CHECK_RESULT;"); // depends on control dependency: [if], data = [none] sb.append(nagiosHost); // depends on control dependency: [if], data = [none] sb.append(";"); // depends on control dependency: [if], data = [none] if (prefix != null) { sb.append(prefix); // depends on control dependency: [if], data = [(prefix] } sb.append(keyString[2]); // depends on control dependency: [if], data = [none] if (suffix != null) { sb.append(suffix); // depends on control dependency: [if], data = [(suffix] } sb.append(";"); // depends on control dependency: [if], data = [none] sb.append(nagiosCheckValue(result.getValue().toString(), thresholds.get(thresholdPos))); // depends on control dependency: [if], data = [none] sb.append(";"); // depends on control dependency: [if], data = [none] //Missing the performance information logger.info(sb.toString()); // depends on control dependency: [if], data = [none] } } } }
public class class_name { @Override public MultipleObjectsBundle delete(DBIDs ids) { // Prepare bundle to return MultipleObjectsBundle bundle = new MultipleObjectsBundle(); for(Relation<?> relation : relations) { ArrayList<Object> data = new ArrayList<>(ids.size()); for(DBIDIter iter = ids.iter(); iter.valid(); iter.advance()) { data.add(relation.get(iter)); } bundle.appendColumn(relation.getDataTypeInformation(), data); } // remove from db for(DBIDIter iter = ids.iter(); iter.valid(); iter.advance()) { doDelete(iter); } // fire deletion event eventManager.fireObjectsRemoved(ids); return bundle; } }
public class class_name { @Override public MultipleObjectsBundle delete(DBIDs ids) { // Prepare bundle to return MultipleObjectsBundle bundle = new MultipleObjectsBundle(); for(Relation<?> relation : relations) { ArrayList<Object> data = new ArrayList<>(ids.size()); for(DBIDIter iter = ids.iter(); iter.valid(); iter.advance()) { data.add(relation.get(iter)); // depends on control dependency: [for], data = [iter] } bundle.appendColumn(relation.getDataTypeInformation(), data); // depends on control dependency: [for], data = [relation] } // remove from db for(DBIDIter iter = ids.iter(); iter.valid(); iter.advance()) { doDelete(iter); // depends on control dependency: [for], data = [iter] } // fire deletion event eventManager.fireObjectsRemoved(ids); return bundle; } }
public class class_name { void format(StringBuilder sb, Temporal localDate) { //Instant localDate = ClockCurrent.GMT.instant(); int len = _timestamp.length; for (int j = 0; j < len; j++) { _timestamp[j].format(sb, localDate); } } }
public class class_name { void format(StringBuilder sb, Temporal localDate) { //Instant localDate = ClockCurrent.GMT.instant(); int len = _timestamp.length; for (int j = 0; j < len; j++) { _timestamp[j].format(sb, localDate); // depends on control dependency: [for], data = [j] } } }
public class class_name { @MainThread private void handleEventResult(Event event, EventResult result) { if (!activeEvents.contains(event)) { Utils.logE(event.getKey(), "Cannot send result of finished event"); return; } scheduleResultCallbacks(event, result); executeTasks(false); } }
public class class_name { @MainThread private void handleEventResult(Event event, EventResult result) { if (!activeEvents.contains(event)) { Utils.logE(event.getKey(), "Cannot send result of finished event"); // depends on control dependency: [if], data = [none] return; // depends on control dependency: [if], data = [none] } scheduleResultCallbacks(event, result); executeTasks(false); } }
public class class_name { public boolean setPartitions(Collection<Collection<Node>> parts) { if (!isDisjoint(parts)) { return false; } partitions = parts; return true; } }
public class class_name { public boolean setPartitions(Collection<Collection<Node>> parts) { if (!isDisjoint(parts)) { return false; // depends on control dependency: [if], data = [none] } partitions = parts; return true; } }
public class class_name { public static int w(String msg) { // This is a quick check to avoid the expensive stack trace reflection. if (!activated) { return 0; } String caller = LogHelper.getCaller(); if (caller != null) { return w(caller, msg); } return 0; } }
public class class_name { public static int w(String msg) { // This is a quick check to avoid the expensive stack trace reflection. if (!activated) { return 0; // depends on control dependency: [if], data = [none] } String caller = LogHelper.getCaller(); if (caller != null) { return w(caller, msg); // depends on control dependency: [if], data = [(caller] } return 0; } }
public class class_name { public double getCouponPayment(int periodIndex, AnalyticModel model) { ForwardCurve forwardCurve = model.getForwardCurve(forwardCurveName); if(forwardCurve == null && forwardCurveName != null && forwardCurveName.length() > 0) { throw new IllegalArgumentException("No forward curve with name '" + forwardCurveName + "' was found in the model:\n" + model.toString()); } double periodLength = schedule.getPeriodLength(periodIndex); double couponPayment=fixedCoupon ; if(forwardCurve != null ) { couponPayment = floatingSpread+forwardCurve.getForward(model, schedule.getFixing(periodIndex)); } return couponPayment*periodLength; } }
public class class_name { public double getCouponPayment(int periodIndex, AnalyticModel model) { ForwardCurve forwardCurve = model.getForwardCurve(forwardCurveName); if(forwardCurve == null && forwardCurveName != null && forwardCurveName.length() > 0) { throw new IllegalArgumentException("No forward curve with name '" + forwardCurveName + "' was found in the model:\n" + model.toString()); } double periodLength = schedule.getPeriodLength(periodIndex); double couponPayment=fixedCoupon ; if(forwardCurve != null ) { couponPayment = floatingSpread+forwardCurve.getForward(model, schedule.getFixing(periodIndex)); // depends on control dependency: [if], data = [none] } return couponPayment*periodLength; } }
public class class_name { @Override @SuppressWarnings("unchecked") public <V> Iterator<VertexProperty<V>> properties(String... propertyKeys) { Objects.requireNonNull(propertyKeys, "propertyKeys cannot be null"); // check we have properties with key if (!properties.isEmpty()) { // no properties in filter if (propertyKeys.length == 0) { // all properties (return a copy since properties iterator can be modified by calling remove()) return properties.entrySet().stream() .flatMap(entry -> entry.getValue().stream()) .map(item -> (VertexProperty<V>)item) .collect(Collectors.toList()) .iterator(); } // one property in filter if (propertyKeys.length == 1) { // get list for key Collection<?> list = properties.get(propertyKeys[0]); if (list != null) { // all properties (return a copy since properties iterator can be modified by calling remove()) return list.stream() .map(item -> (VertexProperty<V>)item) .collect(Collectors.toList()) .iterator(); } // nothing on key return Collections.emptyIterator(); } // loop property keys (return a copy since properties iterator can be modified by calling remove()) return Arrays.stream(propertyKeys) .flatMap(key -> ((Collection<?>)properties.getOrDefault(key, Collections.EMPTY_LIST)).stream()) .map(item -> (VertexProperty<V>)item) .collect(Collectors.toList()) .iterator(); } // nothing return Collections.emptyIterator(); } }
public class class_name { @Override @SuppressWarnings("unchecked") public <V> Iterator<VertexProperty<V>> properties(String... propertyKeys) { Objects.requireNonNull(propertyKeys, "propertyKeys cannot be null"); // check we have properties with key if (!properties.isEmpty()) { // no properties in filter if (propertyKeys.length == 0) { // all properties (return a copy since properties iterator can be modified by calling remove()) return properties.entrySet().stream() .flatMap(entry -> entry.getValue().stream()) .map(item -> (VertexProperty<V>)item) .collect(Collectors.toList()) .iterator(); // depends on control dependency: [if], data = [none] } // one property in filter if (propertyKeys.length == 1) { // get list for key Collection<?> list = properties.get(propertyKeys[0]); if (list != null) { // all properties (return a copy since properties iterator can be modified by calling remove()) return list.stream() .map(item -> (VertexProperty<V>)item) .collect(Collectors.toList()) .iterator(); // depends on control dependency: [if], data = [none] } // nothing on key return Collections.emptyIterator(); // depends on control dependency: [if], data = [none] } // loop property keys (return a copy since properties iterator can be modified by calling remove()) return Arrays.stream(propertyKeys) .flatMap(key -> ((Collection<?>)properties.getOrDefault(key, Collections.EMPTY_LIST)).stream()) .map(item -> (VertexProperty<V>)item) .collect(Collectors.toList()) .iterator(); // depends on control dependency: [if], data = [none] } // nothing return Collections.emptyIterator(); } }
public class class_name { private void validate(QPath path) throws RepositoryException, AccessDeniedException, ReferentialIntegrityException { List<ItemState> changes = changesLog.getAllStates(); for (ItemState itemState : changes) { if (itemState.isInternallyCreated()) { // skip internally created if (itemState.isMixinChanged()) { // ...except of check of ACL correct size for internally created // items. // If no permissions in the list throw exception. if (itemState.isDescendantOf(path)) { if (((NodeData)itemState.getData()).getACL().getPermissionsSize() < 1) { throw new RepositoryException("Node " + itemState.getData().getQPath().getAsString() + " has wrong formed ACL."); } } validateMandatoryItem(itemState); } } else { if (itemState.isDescendantOf(path)) { validateAccessPermissions(itemState); validateMandatoryItem(itemState); } if (path.isDescendantOf(itemState.getAncestorToSave())) { throw new ConstraintViolationException(path.getAsString() + " is the same or descendant of either Session.move()'s destination or source node only " + path.getAsString()); } } } } }
public class class_name { private void validate(QPath path) throws RepositoryException, AccessDeniedException, ReferentialIntegrityException { List<ItemState> changes = changesLog.getAllStates(); for (ItemState itemState : changes) { if (itemState.isInternallyCreated()) { // skip internally created if (itemState.isMixinChanged()) { // ...except of check of ACL correct size for internally created // items. // If no permissions in the list throw exception. if (itemState.isDescendantOf(path)) { if (((NodeData)itemState.getData()).getACL().getPermissionsSize() < 1) { throw new RepositoryException("Node " + itemState.getData().getQPath().getAsString() + " has wrong formed ACL."); } } validateMandatoryItem(itemState); // depends on control dependency: [if], data = [none] } } else { if (itemState.isDescendantOf(path)) { validateAccessPermissions(itemState); // depends on control dependency: [if], data = [none] validateMandatoryItem(itemState); // depends on control dependency: [if], data = [none] } if (path.isDescendantOf(itemState.getAncestorToSave())) { throw new ConstraintViolationException(path.getAsString() + " is the same or descendant of either Session.move()'s destination or source node only " + path.getAsString()); } } } } }
public class class_name { public ClassRef toInternalReference() { List<TypeRef> arguments = new ArrayList<TypeRef>(); for (TypeParamDef parameter : parameters) { arguments.add(parameter.toReference()); } return new ClassRefBuilder() .withDefinition(this) .withArguments(arguments) .withAttributes(getAttributes()) .build(); } }
public class class_name { public ClassRef toInternalReference() { List<TypeRef> arguments = new ArrayList<TypeRef>(); for (TypeParamDef parameter : parameters) { arguments.add(parameter.toReference()); // depends on control dependency: [for], data = [parameter] } return new ClassRefBuilder() .withDefinition(this) .withArguments(arguments) .withAttributes(getAttributes()) .build(); } }
public class class_name { public static long factorial(int arg) { if (arg <= 0) { throw new IllegalArgumentException("参数必须大于0"); } long result = 1; for (int i = arg; i > 0; i--) { result *= i; } return result; } }
public class class_name { public static long factorial(int arg) { if (arg <= 0) { throw new IllegalArgumentException("参数必须大于0"); } long result = 1; for (int i = arg; i > 0; i--) { result *= i; // depends on control dependency: [for], data = [i] } return result; } }
public class class_name { private double calculateEntropy(MapCount<String> mc) { double totalFrequency = 0.; Set<Map.Entry<String, Double>> entrySet = mc.get().entrySet(); for (Map.Entry<String, Double> entry : entrySet) { totalFrequency += entry.getValue(); } double entropy = 0., p; for (Map.Entry<String, Double> entry : entrySet) { p = entry.getValue() / totalFrequency; entropy += -p * Math.log(p); } return entropy; } }
public class class_name { private double calculateEntropy(MapCount<String> mc) { double totalFrequency = 0.; Set<Map.Entry<String, Double>> entrySet = mc.get().entrySet(); for (Map.Entry<String, Double> entry : entrySet) { totalFrequency += entry.getValue(); // depends on control dependency: [for], data = [entry] } double entropy = 0., p; for (Map.Entry<String, Double> entry : entrySet) { p = entry.getValue() / totalFrequency; // depends on control dependency: [for], data = [entry] entropy += -p * Math.log(p); // depends on control dependency: [for], data = [none] } return entropy; } }
public class class_name { @Override public <T> Provider<T> provider(Key<T> key) { Objects.requireNonNull(key); Provider<T> provider = (Provider) _providerMap.get(key); if (provider == null) { provider = lookupProvider(key); if (provider == null) { provider = autoProvider(key); } _providerMap.putIfAbsent(key, provider); provider = (Provider) _providerMap.get(key); } return provider; } }
public class class_name { @Override public <T> Provider<T> provider(Key<T> key) { Objects.requireNonNull(key); Provider<T> provider = (Provider) _providerMap.get(key); if (provider == null) { provider = lookupProvider(key); // depends on control dependency: [if], data = [none] if (provider == null) { provider = autoProvider(key); // depends on control dependency: [if], data = [none] } _providerMap.putIfAbsent(key, provider); // depends on control dependency: [if], data = [none] provider = (Provider) _providerMap.get(key); // depends on control dependency: [if], data = [none] } return provider; } }
public class class_name { public static CompactHeightfield buildCompactHeightfield(Context ctx, int walkableHeight, int walkableClimb, Heightfield hf) { ctx.startTimer("BUILD_COMPACTHEIGHTFIELD"); CompactHeightfield chf = new CompactHeightfield(); int w = hf.width; int h = hf.height; int spanCount = getHeightFieldSpanCount(ctx, hf); // Fill in header. chf.width = w; chf.height = h; chf.spanCount = spanCount; chf.walkableHeight = walkableHeight; chf.walkableClimb = walkableClimb; chf.maxRegions = 0; copy(chf.bmin, hf.bmin); copy(chf.bmax, hf.bmax); chf.bmax[1] += walkableHeight * hf.ch; chf.cs = hf.cs; chf.ch = hf.ch; chf.cells = new CompactCell[w * h]; chf.spans = new CompactSpan[spanCount]; chf.areas = new int[spanCount]; int MAX_HEIGHT = 0xffff; for (int i = 0; i < chf.cells.length; i++) { chf.cells[i] = new CompactCell(); } for (int i = 0; i < chf.spans.length; i++) { chf.spans[i] = new CompactSpan(); } // Fill in cells and spans. int idx = 0; for (int y = 0; y < h; ++y) { for (int x = 0; x < w; ++x) { Span s = hf.spans[x + y * w]; // If there are no spans at this cell, just leave the data to index=0, count=0. if (s == null) continue; CompactCell c = chf.cells[x + y * w]; c.index = idx; c.count = 0; while (s != null) { if (s.area != RC_NULL_AREA) { int bot = s.smax; int top = s.next != null ? (int) s.next.smin : MAX_HEIGHT; chf.spans[idx].y = RecastCommon.clamp(bot, 0, 0xffff); chf.spans[idx].h = RecastCommon.clamp(top - bot, 0, 0xff); chf.areas[idx] = s.area; idx++; c.count++; } s = s.next; } } } // Find neighbour connections. int MAX_LAYERS = RC_NOT_CONNECTED - 1; int tooHighNeighbour = 0; for (int y = 0; y < h; ++y) { for (int x = 0; x < w; ++x) { CompactCell c = chf.cells[x + y * w]; for (int i = c.index, ni = c.index + c.count; i < ni; ++i) { CompactSpan s = chf.spans[i]; for (int dir = 0; dir < 4; ++dir) { RecastCommon.SetCon(s, dir, RC_NOT_CONNECTED); int nx = x + RecastCommon.GetDirOffsetX(dir); int ny = y + RecastCommon.GetDirOffsetY(dir); // First check that the neighbour cell is in bounds. if (nx < 0 || ny < 0 || nx >= w || ny >= h) continue; // Iterate over all neighbour spans and check if any of the is // accessible from current cell. CompactCell nc = chf.cells[nx + ny * w]; for (int k = nc.index, nk = nc.index + nc.count; k < nk; ++k) { CompactSpan ns = chf.spans[k]; int bot = Math.max(s.y, ns.y); int top = Math.min(s.y + s.h, ns.y + ns.h); // Check that the gap between the spans is walkable, // and that the climb height between the gaps is not too high. if ((top - bot) >= walkableHeight && Math.abs(ns.y - s.y) <= walkableClimb) { // Mark direction as walkable. int lidx = k - nc.index; if (lidx < 0 || lidx > MAX_LAYERS) { tooHighNeighbour = Math.max(tooHighNeighbour, lidx); continue; } RecastCommon.SetCon(s, dir, lidx); break; } } } } } } if (tooHighNeighbour > MAX_LAYERS) { throw new RuntimeException("rcBuildCompactHeightfield: Heightfield has too many layers " + tooHighNeighbour + " (max: " + MAX_LAYERS + ")"); } ctx.stopTimer("BUILD_COMPACTHEIGHTFIELD"); return chf; } }
public class class_name { public static CompactHeightfield buildCompactHeightfield(Context ctx, int walkableHeight, int walkableClimb, Heightfield hf) { ctx.startTimer("BUILD_COMPACTHEIGHTFIELD"); CompactHeightfield chf = new CompactHeightfield(); int w = hf.width; int h = hf.height; int spanCount = getHeightFieldSpanCount(ctx, hf); // Fill in header. chf.width = w; chf.height = h; chf.spanCount = spanCount; chf.walkableHeight = walkableHeight; chf.walkableClimb = walkableClimb; chf.maxRegions = 0; copy(chf.bmin, hf.bmin); copy(chf.bmax, hf.bmax); chf.bmax[1] += walkableHeight * hf.ch; chf.cs = hf.cs; chf.ch = hf.ch; chf.cells = new CompactCell[w * h]; chf.spans = new CompactSpan[spanCount]; chf.areas = new int[spanCount]; int MAX_HEIGHT = 0xffff; for (int i = 0; i < chf.cells.length; i++) { chf.cells[i] = new CompactCell(); // depends on control dependency: [for], data = [i] } for (int i = 0; i < chf.spans.length; i++) { chf.spans[i] = new CompactSpan(); // depends on control dependency: [for], data = [i] } // Fill in cells and spans. int idx = 0; for (int y = 0; y < h; ++y) { for (int x = 0; x < w; ++x) { Span s = hf.spans[x + y * w]; // If there are no spans at this cell, just leave the data to index=0, count=0. if (s == null) continue; CompactCell c = chf.cells[x + y * w]; c.index = idx; // depends on control dependency: [for], data = [none] c.count = 0; // depends on control dependency: [for], data = [none] while (s != null) { if (s.area != RC_NULL_AREA) { int bot = s.smax; int top = s.next != null ? (int) s.next.smin : MAX_HEIGHT; chf.spans[idx].y = RecastCommon.clamp(bot, 0, 0xffff); // depends on control dependency: [if], data = [none] chf.spans[idx].h = RecastCommon.clamp(top - bot, 0, 0xff); // depends on control dependency: [if], data = [none] chf.areas[idx] = s.area; // depends on control dependency: [if], data = [none] idx++; // depends on control dependency: [if], data = [none] c.count++; // depends on control dependency: [if], data = [none] } s = s.next; // depends on control dependency: [while], data = [none] } } } // Find neighbour connections. int MAX_LAYERS = RC_NOT_CONNECTED - 1; int tooHighNeighbour = 0; for (int y = 0; y < h; ++y) { for (int x = 0; x < w; ++x) { CompactCell c = chf.cells[x + y * w]; for (int i = c.index, ni = c.index + c.count; i < ni; ++i) { CompactSpan s = chf.spans[i]; for (int dir = 0; dir < 4; ++dir) { RecastCommon.SetCon(s, dir, RC_NOT_CONNECTED); // depends on control dependency: [for], data = [dir] int nx = x + RecastCommon.GetDirOffsetX(dir); int ny = y + RecastCommon.GetDirOffsetY(dir); // First check that the neighbour cell is in bounds. if (nx < 0 || ny < 0 || nx >= w || ny >= h) continue; // Iterate over all neighbour spans and check if any of the is // accessible from current cell. CompactCell nc = chf.cells[nx + ny * w]; for (int k = nc.index, nk = nc.index + nc.count; k < nk; ++k) { CompactSpan ns = chf.spans[k]; int bot = Math.max(s.y, ns.y); int top = Math.min(s.y + s.h, ns.y + ns.h); // Check that the gap between the spans is walkable, // and that the climb height between the gaps is not too high. if ((top - bot) >= walkableHeight && Math.abs(ns.y - s.y) <= walkableClimb) { // Mark direction as walkable. int lidx = k - nc.index; if (lidx < 0 || lidx > MAX_LAYERS) { tooHighNeighbour = Math.max(tooHighNeighbour, lidx); // depends on control dependency: [if], data = [none] continue; } RecastCommon.SetCon(s, dir, lidx); // depends on control dependency: [if], data = [none] break; } } } } } } if (tooHighNeighbour > MAX_LAYERS) { throw new RuntimeException("rcBuildCompactHeightfield: Heightfield has too many layers " + tooHighNeighbour + " (max: " + MAX_LAYERS + ")"); } ctx.stopTimer("BUILD_COMPACTHEIGHTFIELD"); return chf; } }
public class class_name { protected void destroyConnection(ConnectionHandle conn) { postDestroyConnection(conn); conn.setInReplayMode(true); // we're dead, stop attempting to replay anything try { conn.internalClose(); } catch (SQLException e) { logger.error("Error in attempting to close connection", e); } } }
public class class_name { protected void destroyConnection(ConnectionHandle conn) { postDestroyConnection(conn); conn.setInReplayMode(true); // we're dead, stop attempting to replay anything try { conn.internalClose(); // depends on control dependency: [try], data = [none] } catch (SQLException e) { logger.error("Error in attempting to close connection", e); } // depends on control dependency: [catch], data = [none] } }
public class class_name { private void propagateStatusAndAlert(final ExecutableFlowBase base, final Status status) { if (!Status.isStatusFinished(base.getStatus()) && base.getStatus() != Status.KILLING) { this.logger.info("Setting " + base.getNestedId() + " to " + status); boolean shouldAlert = false; if (base.getStatus() != status) { base.setStatus(status); shouldAlert = true; } if (base.getParentFlow() != null) { propagateStatusAndAlert(base.getParentFlow(), status); } else if (this.azkabanProps.getBoolean(ConfigurationKeys.AZKABAN_POLL_MODEL, false)) { // Alert on the root flow if the first error is encountered. // Todo jamiesjc: Add a new FLOW_STATUS_CHANGED event type and alert on that event. if (shouldAlert && base.getStatus() == Status.FAILED_FINISHING) { ExecutionControllerUtils.alertUserOnFirstError((ExecutableFlow) base, this.alerterHolder); } } } } }
public class class_name { private void propagateStatusAndAlert(final ExecutableFlowBase base, final Status status) { if (!Status.isStatusFinished(base.getStatus()) && base.getStatus() != Status.KILLING) { this.logger.info("Setting " + base.getNestedId() + " to " + status); // depends on control dependency: [if], data = [none] boolean shouldAlert = false; if (base.getStatus() != status) { base.setStatus(status); // depends on control dependency: [if], data = [status)] shouldAlert = true; // depends on control dependency: [if], data = [none] } if (base.getParentFlow() != null) { propagateStatusAndAlert(base.getParentFlow(), status); // depends on control dependency: [if], data = [(base.getParentFlow()] } else if (this.azkabanProps.getBoolean(ConfigurationKeys.AZKABAN_POLL_MODEL, false)) { // Alert on the root flow if the first error is encountered. // Todo jamiesjc: Add a new FLOW_STATUS_CHANGED event type and alert on that event. if (shouldAlert && base.getStatus() == Status.FAILED_FINISHING) { ExecutionControllerUtils.alertUserOnFirstError((ExecutableFlow) base, this.alerterHolder); // depends on control dependency: [if], data = [none] } } } } }
public class class_name { public void setScte35Descriptors(java.util.Collection<Scte35Descriptor> scte35Descriptors) { if (scte35Descriptors == null) { this.scte35Descriptors = null; return; } this.scte35Descriptors = new java.util.ArrayList<Scte35Descriptor>(scte35Descriptors); } }
public class class_name { public void setScte35Descriptors(java.util.Collection<Scte35Descriptor> scte35Descriptors) { if (scte35Descriptors == null) { this.scte35Descriptors = null; // depends on control dependency: [if], data = [none] return; // depends on control dependency: [if], data = [none] } this.scte35Descriptors = new java.util.ArrayList<Scte35Descriptor>(scte35Descriptors); } }
public class class_name { public static ResultSet createGeneratedData(long[] data, Protocol protocol, boolean findColumnReturnsOne) { ColumnInformation[] columns = new ColumnInformation[1]; columns[0] = ColumnInformation.create("insert_id", ColumnType.BIGINT); List<byte[]> rows = new ArrayList<>(); for (long rowData : data) { if (rowData != 0) { rows.add(StandardPacketInputStream.create(String.valueOf(rowData).getBytes())); } } if (findColumnReturnsOne) { return new SelectResultSet(columns, rows, protocol, TYPE_SCROLL_SENSITIVE) { @Override public int findColumn(String name) { return 1; } }; } return new SelectResultSet(columns, rows, protocol, TYPE_SCROLL_SENSITIVE); } }
public class class_name { public static ResultSet createGeneratedData(long[] data, Protocol protocol, boolean findColumnReturnsOne) { ColumnInformation[] columns = new ColumnInformation[1]; columns[0] = ColumnInformation.create("insert_id", ColumnType.BIGINT); List<byte[]> rows = new ArrayList<>(); for (long rowData : data) { if (rowData != 0) { rows.add(StandardPacketInputStream.create(String.valueOf(rowData).getBytes())); // depends on control dependency: [if], data = [(rowData] } } if (findColumnReturnsOne) { return new SelectResultSet(columns, rows, protocol, TYPE_SCROLL_SENSITIVE) { @Override public int findColumn(String name) { return 1; } }; // depends on control dependency: [if], data = [none] } return new SelectResultSet(columns, rows, protocol, TYPE_SCROLL_SENSITIVE); } }
public class class_name { boolean updateCallback(Task<?> task, Activity callback, String annotationId) { if (task == null || callback == null) { return false; } WeakReference<TaskRunnable<?>> reference = mTaskRunnables.get(task.getKey()); if (reference == null) { return false; } TaskRunnable<?> runnable = reference.get(); if (runnable == null || runnable.mPostingResult || runnable.mTask != task) { return false; } task.setCachedActivity(callback); task.setAnnotationId(annotationId); runnable.updateCallbackActivity(callback); return true; } }
public class class_name { boolean updateCallback(Task<?> task, Activity callback, String annotationId) { if (task == null || callback == null) { return false; // depends on control dependency: [if], data = [none] } WeakReference<TaskRunnable<?>> reference = mTaskRunnables.get(task.getKey()); if (reference == null) { return false; // depends on control dependency: [if], data = [none] } TaskRunnable<?> runnable = reference.get(); if (runnable == null || runnable.mPostingResult || runnable.mTask != task) { return false; // depends on control dependency: [if], data = [none] } task.setCachedActivity(callback); task.setAnnotationId(annotationId); runnable.updateCallbackActivity(callback); return true; } }
public class class_name { public String contentsAsString() { if (mResultString == null) { // Has array been requested? Can make a shortcut, if so: if (mResultArray != null) { mResultString = new String(mResultArray); } else { // Do we use shared array? if (mInputStart >= 0) { if (mInputLen < 1) { return (mResultString = ""); } mResultString = new String(mInputBuffer, mInputStart, mInputLen); } else { // nope... need to copy // But first, let's see if we have just one buffer int segLen = mSegmentSize; int currLen = mCurrentSize; if (segLen == 0) { // yup mResultString = (currLen == 0) ? "" : new String(mCurrentSegment, 0, currLen); } else { // no, need to combine StringBuilder sb = new StringBuilder(segLen + currLen); // First stored segments if (mSegments != null) { for (int i = 0, len = mSegments.size(); i < len; ++i) { char[] curr = mSegments.get(i); sb.append(curr, 0, curr.length); } } // And finally, current segment: sb.append(mCurrentSegment, 0, mCurrentSize); mResultString = sb.toString(); } } } } return mResultString; } }
public class class_name { public String contentsAsString() { if (mResultString == null) { // Has array been requested? Can make a shortcut, if so: if (mResultArray != null) { mResultString = new String(mResultArray); // depends on control dependency: [if], data = [(mResultArray] } else { // Do we use shared array? if (mInputStart >= 0) { if (mInputLen < 1) { return (mResultString = ""); // depends on control dependency: [if], data = [none] } mResultString = new String(mInputBuffer, mInputStart, mInputLen); // depends on control dependency: [if], data = [none] } else { // nope... need to copy // But first, let's see if we have just one buffer int segLen = mSegmentSize; int currLen = mCurrentSize; if (segLen == 0) { // yup mResultString = (currLen == 0) ? "" : new String(mCurrentSegment, 0, currLen); // depends on control dependency: [if], data = [0)] } else { // no, need to combine StringBuilder sb = new StringBuilder(segLen + currLen); // First stored segments if (mSegments != null) { for (int i = 0, len = mSegments.size(); i < len; ++i) { char[] curr = mSegments.get(i); sb.append(curr, 0, curr.length); // depends on control dependency: [for], data = [none] } } // And finally, current segment: sb.append(mCurrentSegment, 0, mCurrentSize); // depends on control dependency: [if], data = [none] mResultString = sb.toString(); // depends on control dependency: [if], data = [none] } } } } return mResultString; } }
public class class_name { public void submit(Runnable task) { queue.add(task); while(true) { long cur = combinedState.get(); int shutdown = (int)(cur >> 63) & 1; if (shutdown != 0) { throw new RejectedExecutionException("ThreadExecutor is already shutdown"); } int currentThreads = ((int) (cur >> 32)) & 0x7FFFFFFF; int sizeMinusIdle = (int)(cur & 0xFFFFFFFFL); if (currentThreads < maxThreads && sizeMinusIdle >= 0) { currentThreads++; long next = combineStates(currentThreads, sizeMinusIdle, shutdown); if (combinedState.compareAndSet(cur, next)) { ThreadGroup localThreadGroup = threadGroup; if (localThreadGroup.isDestroyed()) { synchronized (this) { if (this.threadGroup.isDestroyed()) { localThreadGroup = new ThreadGroup(this.name); this.threadGroup = localThreadGroup; } } } new ExecutorThread(name + "-" + poolNumber + "-" + threadId.incrementAndGet()).start(); break; } } else { sizeMinusIdle++; if (trySettingState(cur, currentThreads, sizeMinusIdle, shutdown)) break; } } } }
public class class_name { public void submit(Runnable task) { queue.add(task); while(true) { long cur = combinedState.get(); int shutdown = (int)(cur >> 63) & 1; if (shutdown != 0) { throw new RejectedExecutionException("ThreadExecutor is already shutdown"); } int currentThreads = ((int) (cur >> 32)) & 0x7FFFFFFF; int sizeMinusIdle = (int)(cur & 0xFFFFFFFFL); if (currentThreads < maxThreads && sizeMinusIdle >= 0) { currentThreads++; // depends on control dependency: [if], data = [none] long next = combineStates(currentThreads, sizeMinusIdle, shutdown); if (combinedState.compareAndSet(cur, next)) { ThreadGroup localThreadGroup = threadGroup; if (localThreadGroup.isDestroyed()) { synchronized (this) // depends on control dependency: [if], data = [none] { if (this.threadGroup.isDestroyed()) { localThreadGroup = new ThreadGroup(this.name); // depends on control dependency: [if], data = [none] this.threadGroup = localThreadGroup; // depends on control dependency: [if], data = [none] } } } new ExecutorThread(name + "-" + poolNumber + "-" + threadId.incrementAndGet()).start(); // depends on control dependency: [if], data = [none] break; } } else { sizeMinusIdle++; // depends on control dependency: [if], data = [none] if (trySettingState(cur, currentThreads, sizeMinusIdle, shutdown)) break; } } } }
public class class_name { public void placeFusedRing(IRing ring, IAtomContainer sharedAtoms, Vector2d ringCenterVector, double bondLength) { logger.debug("RingPlacer.placeFusedRing() start"); final IAtom beg = sharedAtoms.getAtom(0); final IAtom end = sharedAtoms.getAtom(1); final Vector2d pBeg = new Vector2d(beg.getPoint2d()); final Vector2d pEnd = new Vector2d(end.getPoint2d()); // fuse the ring perpendicular to the bond, ring center is not // sub-optimal if non-regular/convex polygon (e.g. macro cycle) ringCenterVector = getPerpendicular(pBeg, pEnd, ringCenterVector); double radius = getNativeRingRadius(ring, bondLength); double newRingPerpendicular = Math.sqrt(Math.pow(radius, 2) - Math.pow(bondLength / 2, 2)); ringCenterVector.normalize(); logger.debug("placeFusedRing->: ringCenterVector.length()" + ringCenterVector.length()); ringCenterVector.scale(newRingPerpendicular); final Point2d ringCenter = getMidPoint(pBeg, pEnd); ringCenter.add(ringCenterVector); final Vector2d originRingCenterVector = new Vector2d(ringCenter); pBeg.sub(originRingCenterVector); pEnd.sub(originRingCenterVector); final double occupiedAngle = angle(pBeg, pEnd); final double remainingAngle = (2 * Math.PI) - occupiedAngle; double addAngle = remainingAngle / (ring.getRingSize() - 1); logger.debug("placeFusedRing->occupiedAngle: " + Math.toDegrees(occupiedAngle)); logger.debug("placeFusedRing->remainingAngle: " + Math.toDegrees(remainingAngle)); logger.debug("placeFusedRing->addAngle: " + Math.toDegrees(addAngle)); IAtom startAtom; final double centerX = ringCenter.x; final double centerY = ringCenter.y; final double xDiff = beg.getPoint2d().x - end.getPoint2d().x; final double yDiff = beg.getPoint2d().y - end.getPoint2d().y; double startAngle;; int direction = 1; // if bond is vertical if (xDiff == 0) { logger.debug("placeFusedRing->Bond is vertical"); //starts with the lower Atom if (beg.getPoint2d().y > end.getPoint2d().y) { startAtom = beg; } else { startAtom = end; } //changes the drawing direction if (centerX < beg.getPoint2d().x) { direction = 1; } else { direction = -1; } } // if bond is not vertical else { //starts with the left Atom if (beg.getPoint2d().x > end.getPoint2d().x) { startAtom = beg; } else { startAtom = end; } //changes the drawing direction if (centerY - beg.getPoint2d().y > (centerX - beg.getPoint2d().x) * yDiff / xDiff) { direction = 1; } else { direction = -1; } } startAngle = GeometryUtil.getAngle(startAtom.getPoint2d().x - ringCenter.x, startAtom.getPoint2d().y - ringCenter.y); IAtom currentAtom = startAtom; // determine first bond in Ring // int k = 0; // for (k = 0; k < ring.getElectronContainerCount(); k++) { // if (ring.getElectronContainer(k) instanceof IBond) break; // } IBond currentBond = sharedAtoms.getBond(0); Vector atomsToDraw = new Vector(); for (int i = 0; i < ring.getBondCount() - 2; i++) { currentBond = ring.getNextBond(currentBond, currentAtom); currentAtom = currentBond.getOther(currentAtom); atomsToDraw.addElement(currentAtom); } addAngle = addAngle * direction; logger.debug("placeFusedRing->startAngle: " + Math.toDegrees(startAngle)); logger.debug("placeFusedRing->addAngle: " + Math.toDegrees(addAngle)); logger.debug("placeFusedRing->startAtom is: " + (molecule.indexOf(startAtom) + 1)); logger.debug("AtomsToDraw: " + AtomPlacer.listNumbers(molecule, atomsToDraw)); atomPlacer.populatePolygonCorners(atomsToDraw, ringCenter, startAngle, addAngle, radius); } }
public class class_name { public void placeFusedRing(IRing ring, IAtomContainer sharedAtoms, Vector2d ringCenterVector, double bondLength) { logger.debug("RingPlacer.placeFusedRing() start"); final IAtom beg = sharedAtoms.getAtom(0); final IAtom end = sharedAtoms.getAtom(1); final Vector2d pBeg = new Vector2d(beg.getPoint2d()); final Vector2d pEnd = new Vector2d(end.getPoint2d()); // fuse the ring perpendicular to the bond, ring center is not // sub-optimal if non-regular/convex polygon (e.g. macro cycle) ringCenterVector = getPerpendicular(pBeg, pEnd, ringCenterVector); double radius = getNativeRingRadius(ring, bondLength); double newRingPerpendicular = Math.sqrt(Math.pow(radius, 2) - Math.pow(bondLength / 2, 2)); ringCenterVector.normalize(); logger.debug("placeFusedRing->: ringCenterVector.length()" + ringCenterVector.length()); ringCenterVector.scale(newRingPerpendicular); final Point2d ringCenter = getMidPoint(pBeg, pEnd); ringCenter.add(ringCenterVector); final Vector2d originRingCenterVector = new Vector2d(ringCenter); pBeg.sub(originRingCenterVector); pEnd.sub(originRingCenterVector); final double occupiedAngle = angle(pBeg, pEnd); final double remainingAngle = (2 * Math.PI) - occupiedAngle; double addAngle = remainingAngle / (ring.getRingSize() - 1); logger.debug("placeFusedRing->occupiedAngle: " + Math.toDegrees(occupiedAngle)); logger.debug("placeFusedRing->remainingAngle: " + Math.toDegrees(remainingAngle)); logger.debug("placeFusedRing->addAngle: " + Math.toDegrees(addAngle)); IAtom startAtom; final double centerX = ringCenter.x; final double centerY = ringCenter.y; final double xDiff = beg.getPoint2d().x - end.getPoint2d().x; final double yDiff = beg.getPoint2d().y - end.getPoint2d().y; double startAngle;; int direction = 1; // if bond is vertical if (xDiff == 0) { logger.debug("placeFusedRing->Bond is vertical"); // depends on control dependency: [if], data = [none] //starts with the lower Atom if (beg.getPoint2d().y > end.getPoint2d().y) { startAtom = beg; // depends on control dependency: [if], data = [none] } else { startAtom = end; // depends on control dependency: [if], data = [none] } //changes the drawing direction if (centerX < beg.getPoint2d().x) { direction = 1; // depends on control dependency: [if], data = [none] } else { direction = -1; // depends on control dependency: [if], data = [none] } } // if bond is not vertical else { //starts with the left Atom if (beg.getPoint2d().x > end.getPoint2d().x) { startAtom = beg; // depends on control dependency: [if], data = [none] } else { startAtom = end; // depends on control dependency: [if], data = [none] } //changes the drawing direction if (centerY - beg.getPoint2d().y > (centerX - beg.getPoint2d().x) * yDiff / xDiff) { direction = 1; // depends on control dependency: [if], data = [none] } else { direction = -1; // depends on control dependency: [if], data = [none] } } startAngle = GeometryUtil.getAngle(startAtom.getPoint2d().x - ringCenter.x, startAtom.getPoint2d().y - ringCenter.y); IAtom currentAtom = startAtom; // determine first bond in Ring // int k = 0; // for (k = 0; k < ring.getElectronContainerCount(); k++) { // if (ring.getElectronContainer(k) instanceof IBond) break; // } IBond currentBond = sharedAtoms.getBond(0); Vector atomsToDraw = new Vector(); for (int i = 0; i < ring.getBondCount() - 2; i++) { currentBond = ring.getNextBond(currentBond, currentAtom); // depends on control dependency: [for], data = [none] currentAtom = currentBond.getOther(currentAtom); // depends on control dependency: [for], data = [none] atomsToDraw.addElement(currentAtom); // depends on control dependency: [for], data = [none] } addAngle = addAngle * direction; logger.debug("placeFusedRing->startAngle: " + Math.toDegrees(startAngle)); logger.debug("placeFusedRing->addAngle: " + Math.toDegrees(addAngle)); logger.debug("placeFusedRing->startAtom is: " + (molecule.indexOf(startAtom) + 1)); logger.debug("AtomsToDraw: " + AtomPlacer.listNumbers(molecule, atomsToDraw)); atomPlacer.populatePolygonCorners(atomsToDraw, ringCenter, startAngle, addAngle, radius); } }
public class class_name { public int handleMessage(BaseMessage message) { try { int iMessageType = Integer.parseInt((String)message.get(MessageConstants.MESSAGE_TYPE_PARAM)); if ((iMessageType == Constants.AFTER_UPDATE_TYPE) || (iMessageType == Constants.CACHE_UPDATE_TYPE)) { // Record updated - be very careful, you are running in an independent thread. SwingUtilities.invokeLater(new UpdateScreenRecord(iMessageType)); } } catch (NumberFormatException ex) { // Ignore } return super.handleMessage(message); } }
public class class_name { public int handleMessage(BaseMessage message) { try { int iMessageType = Integer.parseInt((String)message.get(MessageConstants.MESSAGE_TYPE_PARAM)); if ((iMessageType == Constants.AFTER_UPDATE_TYPE) || (iMessageType == Constants.CACHE_UPDATE_TYPE)) { // Record updated - be very careful, you are running in an independent thread. SwingUtilities.invokeLater(new UpdateScreenRecord(iMessageType)); // depends on control dependency: [if], data = [none] } } catch (NumberFormatException ex) { // Ignore } // depends on control dependency: [catch], data = [none] return super.handleMessage(message); } }
public class class_name { @Override public void getAPIConfiguration() { getDispatcher().invokeLater(new AsyncTask(CONFIGURATION, listeners) { @Override public void invoke(List<TwitterListener> listeners) throws TwitterException { TwitterAPIConfiguration apiConf = twitter.getAPIConfiguration(); for (TwitterListener listener : listeners) { try { listener.gotAPIConfiguration(apiConf); } catch (Exception e) { logger.warn("Exception at getAPIConfiguration", e); } } } }); } }
public class class_name { @Override public void getAPIConfiguration() { getDispatcher().invokeLater(new AsyncTask(CONFIGURATION, listeners) { @Override public void invoke(List<TwitterListener> listeners) throws TwitterException { TwitterAPIConfiguration apiConf = twitter.getAPIConfiguration(); for (TwitterListener listener : listeners) { try { listener.gotAPIConfiguration(apiConf); // depends on control dependency: [try], data = [none] } catch (Exception e) { logger.warn("Exception at getAPIConfiguration", e); } // depends on control dependency: [catch], data = [none] } } }); } }
public class class_name { @Override public double integrate(DoubleUnaryOperator integrand) { double lowerBound = getLowerBound(); double upperBound = getUpperBound(); double range = upperBound-lowerBound; int numberOfIntervalls = (int) ((numberOfEvaluationPoints-1) / 2.0); double fullIntervall = range / numberOfIntervalls; double halfIntervall = 0.5 * fullIntervall; IntStream intervals = IntStream.range(1, numberOfIntervalls); if(useParallelEvaluation) { intervals = intervals.parallel(); } double sum = intervals.mapToDouble( new IntToDoubleFunction() { @Override public double applyAsDouble(int i) { return 2 * integrand.applyAsDouble(lowerBound + i * fullIntervall + halfIntervall) + integrand.applyAsDouble(lowerBound + i * fullIntervall); } } ).sum(); sum += 2.0 * integrand.applyAsDouble(lowerBound + halfIntervall); return (integrand.applyAsDouble(lowerBound) + integrand.applyAsDouble(upperBound) + 2.0 * sum) / 6.0 * fullIntervall; } }
public class class_name { @Override public double integrate(DoubleUnaryOperator integrand) { double lowerBound = getLowerBound(); double upperBound = getUpperBound(); double range = upperBound-lowerBound; int numberOfIntervalls = (int) ((numberOfEvaluationPoints-1) / 2.0); double fullIntervall = range / numberOfIntervalls; double halfIntervall = 0.5 * fullIntervall; IntStream intervals = IntStream.range(1, numberOfIntervalls); if(useParallelEvaluation) { intervals = intervals.parallel(); // depends on control dependency: [if], data = [none] } double sum = intervals.mapToDouble( new IntToDoubleFunction() { @Override public double applyAsDouble(int i) { return 2 * integrand.applyAsDouble(lowerBound + i * fullIntervall + halfIntervall) + integrand.applyAsDouble(lowerBound + i * fullIntervall); } } ).sum(); sum += 2.0 * integrand.applyAsDouble(lowerBound + halfIntervall); return (integrand.applyAsDouble(lowerBound) + integrand.applyAsDouble(upperBound) + 2.0 * sum) / 6.0 * fullIntervall; } }
public class class_name { protected void awaitForPushToFinish(Future<?> future, long timeout, TimeUnit unit) { final boolean debugEnabled = log.isDebugEnabled(); try { if (debugEnabled) log.debug("wait for state push to cache loader to finish"); future.get(timeout, unit); } catch (TimeoutException e) { if (debugEnabled) log.debug("timed out waiting for state push to cache loader to finish"); } catch (ExecutionException e) { if (debugEnabled) log.debug("exception reported waiting for state push to cache loader to finish"); } catch (InterruptedException ie) { /* Re-assert the thread's interrupted status */ Thread.currentThread().interrupt(); if (trace) log.trace("wait for state push to cache loader to finish was interrupted"); } } }
public class class_name { protected void awaitForPushToFinish(Future<?> future, long timeout, TimeUnit unit) { final boolean debugEnabled = log.isDebugEnabled(); try { if (debugEnabled) log.debug("wait for state push to cache loader to finish"); future.get(timeout, unit); // depends on control dependency: [try], data = [none] } catch (TimeoutException e) { if (debugEnabled) log.debug("timed out waiting for state push to cache loader to finish"); } catch (ExecutionException e) { // depends on control dependency: [catch], data = [none] if (debugEnabled) log.debug("exception reported waiting for state push to cache loader to finish"); } catch (InterruptedException ie) { // depends on control dependency: [catch], data = [none] /* Re-assert the thread's interrupted status */ Thread.currentThread().interrupt(); if (trace) log.trace("wait for state push to cache loader to finish was interrupted"); } // depends on control dependency: [catch], data = [none] } }
public class class_name { @Override protected void startUp() { long traceId = LoggerHelpers.traceEnterWithContext(log, this.objectId, "startUp"); try { log.info("Starting REST server listening on port: {}", this.restServerConfig.getPort()); if (restServerConfig.isTlsEnabled()) { SSLContextConfigurator contextConfigurator = new SSLContextConfigurator(); contextConfigurator.setKeyStoreFile(restServerConfig.getKeyFilePath()); contextConfigurator.setKeyStorePass(JKSHelper.loadPasswordFrom(restServerConfig.getKeyFilePasswordPath())); httpServer = GrizzlyHttpServerFactory.createHttpServer(baseUri, resourceConfig, true, new SSLEngineConfigurator(contextConfigurator, false, false, false)); } else { httpServer = GrizzlyHttpServerFactory.createHttpServer(baseUri, resourceConfig, true); } } finally { LoggerHelpers.traceLeave(log, this.objectId, "startUp", traceId); } } }
public class class_name { @Override protected void startUp() { long traceId = LoggerHelpers.traceEnterWithContext(log, this.objectId, "startUp"); try { log.info("Starting REST server listening on port: {}", this.restServerConfig.getPort()); // depends on control dependency: [try], data = [none] if (restServerConfig.isTlsEnabled()) { SSLContextConfigurator contextConfigurator = new SSLContextConfigurator(); contextConfigurator.setKeyStoreFile(restServerConfig.getKeyFilePath()); // depends on control dependency: [if], data = [none] contextConfigurator.setKeyStorePass(JKSHelper.loadPasswordFrom(restServerConfig.getKeyFilePasswordPath())); // depends on control dependency: [if], data = [none] httpServer = GrizzlyHttpServerFactory.createHttpServer(baseUri, resourceConfig, true, new SSLEngineConfigurator(contextConfigurator, false, false, false)); // depends on control dependency: [if], data = [none] } else { httpServer = GrizzlyHttpServerFactory.createHttpServer(baseUri, resourceConfig, true); // depends on control dependency: [if], data = [none] } } finally { LoggerHelpers.traceLeave(log, this.objectId, "startUp", traceId); } } }
public class class_name { @SuppressWarnings("unused") public boolean shouldTransform(Class<?> classBeingRedefined) { for (StaticClassTransformer transformer : transformers) { if (transformer.shouldTransform(classBeingRedefined)) { return true; } } return false; } }
public class class_name { @SuppressWarnings("unused") public boolean shouldTransform(Class<?> classBeingRedefined) { for (StaticClassTransformer transformer : transformers) { if (transformer.shouldTransform(classBeingRedefined)) { return true; // depends on control dependency: [if], data = [none] } } return false; } }
public class class_name { private static BooleanNode doesArrayContain(JsonNode subject, JsonNode search) { Iterator<JsonNode> elements = subject.elements(); while (elements.hasNext()) { if (elements.next().equals(search)) { return BooleanNode.TRUE; } } return BooleanNode.FALSE; } }
public class class_name { private static BooleanNode doesArrayContain(JsonNode subject, JsonNode search) { Iterator<JsonNode> elements = subject.elements(); while (elements.hasNext()) { if (elements.next().equals(search)) { return BooleanNode.TRUE; // depends on control dependency: [if], data = [none] } } return BooleanNode.FALSE; } }
public class class_name { private byte getByte(int index) { if (index < initialSize) { return pool.get(0)[index]; } index -= initialSize; return pool.get(index / incrementalSize + 1)[index % incrementalSize]; } }
public class class_name { private byte getByte(int index) { if (index < initialSize) { return pool.get(0)[index]; // depends on control dependency: [if], data = [none] } index -= initialSize; return pool.get(index / incrementalSize + 1)[index % incrementalSize]; } }
public class class_name { public XMLString getStringValue(int nodeHandle) { int type = getNodeType(nodeHandle); Node node = getNode(nodeHandle); // %TBD% If an element only has one text node, we should just use it // directly. if(DTM.ELEMENT_NODE == type || DTM.DOCUMENT_NODE == type || DTM.DOCUMENT_FRAGMENT_NODE == type) { FastStringBuffer buf = StringBufferPool.get(); String s; try { getNodeData(node, buf); s = (buf.length() > 0) ? buf.toString() : ""; } finally { StringBufferPool.free(buf); } return m_xstrf.newstr( s ); } else if(TEXT_NODE == type || CDATA_SECTION_NODE == type) { // If this is a DTM text node, it may be made of multiple DOM text // nodes -- including navigating into Entity References. DOM2DTM // records the first node in the sequence and requires that we // pick up the others when we retrieve the DTM node's value. // // %REVIEW% DOM Level 3 is expected to add a "whole text" // retrieval method which performs this function for us. FastStringBuffer buf = StringBufferPool.get(); while(node!=null) { buf.append(node.getNodeValue()); node=logicalNextDOMTextNode(node); } String s=(buf.length() > 0) ? buf.toString() : ""; StringBufferPool.free(buf); return m_xstrf.newstr( s ); } else return m_xstrf.newstr( node.getNodeValue() ); } }
public class class_name { public XMLString getStringValue(int nodeHandle) { int type = getNodeType(nodeHandle); Node node = getNode(nodeHandle); // %TBD% If an element only has one text node, we should just use it // directly. if(DTM.ELEMENT_NODE == type || DTM.DOCUMENT_NODE == type || DTM.DOCUMENT_FRAGMENT_NODE == type) { FastStringBuffer buf = StringBufferPool.get(); String s; try { getNodeData(node, buf); // depends on control dependency: [try], data = [none] s = (buf.length() > 0) ? buf.toString() : ""; // depends on control dependency: [try], data = [none] } finally { StringBufferPool.free(buf); } return m_xstrf.newstr( s ); // depends on control dependency: [if], data = [none] } else if(TEXT_NODE == type || CDATA_SECTION_NODE == type) { // If this is a DTM text node, it may be made of multiple DOM text // nodes -- including navigating into Entity References. DOM2DTM // records the first node in the sequence and requires that we // pick up the others when we retrieve the DTM node's value. // // %REVIEW% DOM Level 3 is expected to add a "whole text" // retrieval method which performs this function for us. FastStringBuffer buf = StringBufferPool.get(); while(node!=null) { buf.append(node.getNodeValue()); // depends on control dependency: [while], data = [(node] node=logicalNextDOMTextNode(node); // depends on control dependency: [while], data = [(node] } String s=(buf.length() > 0) ? buf.toString() : ""; StringBufferPool.free(buf); return m_xstrf.newstr( s ); // depends on control dependency: [if], data = [none] } else return m_xstrf.newstr( node.getNodeValue() ); } }
public class class_name { @Override public synchronized void recordAllocatedEvaluator(final String id) { if (this.fileSystem != null && this.changeLogLocation != null) { final String entry = ADD_FLAG + id + System.lineSeparator(); this.logContainerChange(entry); } } }
public class class_name { @Override public synchronized void recordAllocatedEvaluator(final String id) { if (this.fileSystem != null && this.changeLogLocation != null) { final String entry = ADD_FLAG + id + System.lineSeparator(); this.logContainerChange(entry); // depends on control dependency: [if], data = [none] } } }
public class class_name { private void handleNoBreadcrumbsIntent(@NonNull final Bundle extras) { if (extras.containsKey(EXTRA_NO_BREAD_CRUMBS)) { hideBreadCrumb(extras.getBoolean(EXTRA_NO_BREAD_CRUMBS)); } } }
public class class_name { private void handleNoBreadcrumbsIntent(@NonNull final Bundle extras) { if (extras.containsKey(EXTRA_NO_BREAD_CRUMBS)) { hideBreadCrumb(extras.getBoolean(EXTRA_NO_BREAD_CRUMBS)); // depends on control dependency: [if], data = [none] } } }
public class class_name { private String waitForPattern(long timeout, TailLogBufferedReader bufferedReader, Pattern pattern, boolean searchWithinLines, long timeoutInSeconds) throws IOException { StringBuilder sb = new StringBuilder(); String result; label: while(true) { while ( bufferedReader.ready() ) { int c = bufferedReader.read(); if ( c != -1 ) { if (c == '\n' || c == '\r') { if (sb.length() > 0) { Matcher m = pattern.matcher(sb); boolean match = searchWithinLines ? m.find() : m.matches(); if (match) { result = sb.toString(); break label; } else { sb.setLength(0); } } } else { sb.append((char) c); } } } //nothing more to read, does the current output match the pattern? if ( sb.length() > 0 && searchWithinLines) { Matcher m = pattern.matcher(sb); if ( m.find() ) { result = m.group(0); break label; } } try { Thread.sleep(10); //avoid a busy loop since we are using nonblocking ready() / read() } catch (InterruptedException e) {} checkTimeout(timeout, timeoutInSeconds); if ( process.isStopped() && ! bufferedReader.ready()) { ChorusAssert.fail( process.isExitWithFailureCode() ? "Process stopped with error code " + process.getExitCode() + " while waiting for match" : "Process stopped while waiting for match" ); } } return result; } }
public class class_name { private String waitForPattern(long timeout, TailLogBufferedReader bufferedReader, Pattern pattern, boolean searchWithinLines, long timeoutInSeconds) throws IOException { StringBuilder sb = new StringBuilder(); String result; label: while(true) { while ( bufferedReader.ready() ) { int c = bufferedReader.read(); if ( c != -1 ) { if (c == '\n' || c == '\r') { if (sb.length() > 0) { Matcher m = pattern.matcher(sb); boolean match = searchWithinLines ? m.find() : m.matches(); if (match) { result = sb.toString(); // depends on control dependency: [if], data = [none] break label; } else { sb.setLength(0); // depends on control dependency: [if], data = [none] } } } else { sb.append((char) c); // depends on control dependency: [if], data = [(c] } } } //nothing more to read, does the current output match the pattern? if ( sb.length() > 0 && searchWithinLines) { Matcher m = pattern.matcher(sb); if ( m.find() ) { result = m.group(0); // depends on control dependency: [if], data = [none] break label; } } try { Thread.sleep(10); //avoid a busy loop since we are using nonblocking ready() / read() // depends on control dependency: [try], data = [none] } catch (InterruptedException e) {} // depends on control dependency: [catch], data = [none] checkTimeout(timeout, timeoutInSeconds); if ( process.isStopped() && ! bufferedReader.ready()) { ChorusAssert.fail( process.isExitWithFailureCode() ? "Process stopped with error code " + process.getExitCode() + " while waiting for match" : "Process stopped while waiting for match" ); // depends on control dependency: [if], data = [none] } } return result; } }
public class class_name { public String toHexString() { char[] chars = new char[OBJECT_ID_LENGTH * 2]; int i = 0; for (byte b : toByteArray()) { chars[i++] = HEX_CHARS[b >> 4 & 0xF]; chars[i++] = HEX_CHARS[b & 0xF]; } return new String(chars); } }
public class class_name { public String toHexString() { char[] chars = new char[OBJECT_ID_LENGTH * 2]; int i = 0; for (byte b : toByteArray()) { chars[i++] = HEX_CHARS[b >> 4 & 0xF]; // depends on control dependency: [for], data = [b] chars[i++] = HEX_CHARS[b & 0xF]; // depends on control dependency: [for], data = [b] } return new String(chars); } }
public class class_name { @Nonnull public Configuration filter(Configuration config) { final Map<String, Object> values = Maps.newHashMap(); for (final ConfigurationField field : fields.values()) { final String name = field.getName(); final String type = field.getFieldType(); switch (type) { case BooleanField.FIELD_TYPE: if (config.booleanIsSet(name)) { values.put(name, config.getBoolean(name)); } break; case NumberField.FIELD_TYPE: if (config.intIsSet(name)) { values.put(name, config.getInt(name)); } break; case TextField.FIELD_TYPE: case DropdownField.FIELD_TYPE: if (config.stringIsSet(name)) { values.put(name, config.getString(name)); } break; default: throw new IllegalStateException("Unknown field type " + type + " for configuration field \"" + name + "\". This is a bug."); } } return new Configuration(values); } }
public class class_name { @Nonnull public Configuration filter(Configuration config) { final Map<String, Object> values = Maps.newHashMap(); for (final ConfigurationField field : fields.values()) { final String name = field.getName(); final String type = field.getFieldType(); switch (type) { case BooleanField.FIELD_TYPE: if (config.booleanIsSet(name)) { values.put(name, config.getBoolean(name)); // depends on control dependency: [if], data = [none] } break; case NumberField.FIELD_TYPE: if (config.intIsSet(name)) { values.put(name, config.getInt(name)); // depends on control dependency: [if], data = [none] } break; case TextField.FIELD_TYPE: case DropdownField.FIELD_TYPE: if (config.stringIsSet(name)) { values.put(name, config.getString(name)); // depends on control dependency: [if], data = [none] } break; default: throw new IllegalStateException("Unknown field type " + type + " for configuration field \"" + name + "\". This is a bug."); } } return new Configuration(values); } }
public class class_name { protected ArrayBufferView getTypedArray(Buffer buffer, int type, int byteSize) { if (!(buffer instanceof HasArrayBufferView)) { throw new RuntimeException("Native buffer required " + buffer); } HasArrayBufferView arrayHolder = (HasArrayBufferView) buffer; int bufferElementSize = arrayHolder.getElementSize(); ArrayBufferView webGLArray = arrayHolder.getTypedArray(); if (byteSize == -1) { byteSize = buffer.remaining() * bufferElementSize; } if (byteSize == buffer.capacity() * bufferElementSize && type == arrayHolder.getElementType()) { return webGLArray; } int byteOffset = webGLArray.byteOffset() + buffer.position() * bufferElementSize; switch (type) { case FLOAT: return TypedArrays.createFloat32Array(webGLArray.buffer(), byteOffset, byteSize / 4); case UNSIGNED_BYTE: return TypedArrays.createUint8Array(webGLArray.buffer(), byteOffset, byteSize); case UNSIGNED_SHORT: return TypedArrays.createUint16Array(webGLArray.buffer(), byteOffset, byteSize / 2); case INT: return TypedArrays.createInt32Array(webGLArray.buffer(), byteOffset, byteSize / 4); case SHORT: return TypedArrays.createInt16Array(webGLArray.buffer(), byteOffset, byteSize / 2); case BYTE: return TypedArrays.createInt8Array(webGLArray.buffer(), byteOffset, byteSize); default: throw new IllegalArgumentException("Type: " + type); } } }
public class class_name { protected ArrayBufferView getTypedArray(Buffer buffer, int type, int byteSize) { if (!(buffer instanceof HasArrayBufferView)) { throw new RuntimeException("Native buffer required " + buffer); } HasArrayBufferView arrayHolder = (HasArrayBufferView) buffer; int bufferElementSize = arrayHolder.getElementSize(); ArrayBufferView webGLArray = arrayHolder.getTypedArray(); if (byteSize == -1) { byteSize = buffer.remaining() * bufferElementSize; // depends on control dependency: [if], data = [none] } if (byteSize == buffer.capacity() * bufferElementSize && type == arrayHolder.getElementType()) { return webGLArray; // depends on control dependency: [if], data = [none] } int byteOffset = webGLArray.byteOffset() + buffer.position() * bufferElementSize; switch (type) { case FLOAT: return TypedArrays.createFloat32Array(webGLArray.buffer(), byteOffset, byteSize / 4); case UNSIGNED_BYTE: return TypedArrays.createUint8Array(webGLArray.buffer(), byteOffset, byteSize); case UNSIGNED_SHORT: return TypedArrays.createUint16Array(webGLArray.buffer(), byteOffset, byteSize / 2); case INT: return TypedArrays.createInt32Array(webGLArray.buffer(), byteOffset, byteSize / 4); case SHORT: return TypedArrays.createInt16Array(webGLArray.buffer(), byteOffset, byteSize / 2); case BYTE: return TypedArrays.createInt8Array(webGLArray.buffer(), byteOffset, byteSize); default: throw new IllegalArgumentException("Type: " + type); } } }
public class class_name { public void add(final EventListener<T> eventListener) { if (eventListener.subscriber()) { if (debug) logger.debug("subscription to channel <> from <> ", name, eventListener); listeners.add(eventListener); stats.recordLevel(eventBusName + "::" + name, listeners.size()); } else { if (debug) logger.debug("consumer to channel <> from <> ", name, eventListener); consumer = eventListener; } } }
public class class_name { public void add(final EventListener<T> eventListener) { if (eventListener.subscriber()) { if (debug) logger.debug("subscription to channel <> from <> ", name, eventListener); listeners.add(eventListener); // depends on control dependency: [if], data = [none] stats.recordLevel(eventBusName + "::" + name, listeners.size()); // depends on control dependency: [if], data = [none] } else { if (debug) logger.debug("consumer to channel <> from <> ", name, eventListener); consumer = eventListener; // depends on control dependency: [if], data = [none] } } }
public class class_name { @Validate public void start() { Boolean enabled = configuration.getBooleanWithDefault("ehcache.enabled", true); if (!enabled) { return; } File config = new File(configuration.getBaseDir(), CUSTOM_CONFIGURATION); final ClassLoader original = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader()); if (config.isFile()) { manager = CacheManager.create(config.getAbsolutePath()); } else { URL url = EhCacheService.class.getClassLoader().getResource(INTERNAL_CONFIGURATION); if (url != null) { manager = CacheManager.create(url); } else { throw new ExceptionInInitializerError("Cannot instantiate EhCache, " + "cannot load " + INTERNAL_CONFIGURATION + " file"); } } manager.addCache(WISDOM_KEY); cache = manager.getCache(WISDOM_KEY); registration = context.registerService(Cache.class, this, new Hashtable<String, Object>()); } finally { Thread.currentThread().setContextClassLoader(original); } } }
public class class_name { @Validate public void start() { Boolean enabled = configuration.getBooleanWithDefault("ehcache.enabled", true); if (!enabled) { return; // depends on control dependency: [if], data = [none] } File config = new File(configuration.getBaseDir(), CUSTOM_CONFIGURATION); final ClassLoader original = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader()); // depends on control dependency: [try], data = [none] if (config.isFile()) { manager = CacheManager.create(config.getAbsolutePath()); // depends on control dependency: [if], data = [none] } else { URL url = EhCacheService.class.getClassLoader().getResource(INTERNAL_CONFIGURATION); if (url != null) { manager = CacheManager.create(url); // depends on control dependency: [if], data = [(url] } else { throw new ExceptionInInitializerError("Cannot instantiate EhCache, " + "cannot load " + INTERNAL_CONFIGURATION + " file"); } } manager.addCache(WISDOM_KEY); // depends on control dependency: [try], data = [none] cache = manager.getCache(WISDOM_KEY); // depends on control dependency: [try], data = [none] registration = context.registerService(Cache.class, this, new Hashtable<String, Object>()); // depends on control dependency: [try], data = [none] } finally { Thread.currentThread().setContextClassLoader(original); } } }
public class class_name { public static synchronized IClient getNamedClient(String name) { if (simpleClientMap.get(name) != null) { return simpleClientMap.get(name); } try { return registerClientFromProperties(name, getNamedConfig(name)); } catch (ClientException e) { throw new RuntimeException("Unable to create client", e); } } }
public class class_name { public static synchronized IClient getNamedClient(String name) { if (simpleClientMap.get(name) != null) { return simpleClientMap.get(name); // depends on control dependency: [if], data = [none] } try { return registerClientFromProperties(name, getNamedConfig(name)); // depends on control dependency: [try], data = [none] } catch (ClientException e) { throw new RuntimeException("Unable to create client", e); } // depends on control dependency: [catch], data = [none] } }
public class class_name { Element getElementById(String name) { for (Attr attr : attributes) { if (attr.isId() && name.equals(attr.getValue())) { return this; } } /* * TODO: Remove this behavior. * The spec explicitly says that this is a bad idea. From * Document.getElementById(): "Attributes with the name "ID" * or "id" are not of type ID unless so defined. */ if (name.equals(getAttribute("id"))) { return this; } for (NodeImpl node : children) { if (node.getNodeType() == Node.ELEMENT_NODE) { Element element = ((ElementImpl) node).getElementById(name); if (element != null) { return element; } } } return null; } }
public class class_name { Element getElementById(String name) { for (Attr attr : attributes) { if (attr.isId() && name.equals(attr.getValue())) { return this; // depends on control dependency: [if], data = [none] } } /* * TODO: Remove this behavior. * The spec explicitly says that this is a bad idea. From * Document.getElementById(): "Attributes with the name "ID" * or "id" are not of type ID unless so defined. */ if (name.equals(getAttribute("id"))) { return this; // depends on control dependency: [if], data = [none] } for (NodeImpl node : children) { if (node.getNodeType() == Node.ELEMENT_NODE) { Element element = ((ElementImpl) node).getElementById(name); if (element != null) { return element; // depends on control dependency: [if], data = [none] } } } return null; } }
public class class_name { public java.lang.String getRuleId() { java.lang.Object ref = ruleId_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); if (bs.isValidUtf8()) { ruleId_ = s; } return s; } } }
public class class_name { public java.lang.String getRuleId() { java.lang.Object ref = ruleId_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; // depends on control dependency: [if], data = [none] } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); if (bs.isValidUtf8()) { ruleId_ = s; // depends on control dependency: [if], data = [none] } return s; // depends on control dependency: [if], data = [none] } } }
public class class_name { @Override public void beginDefinitionList(Map<String, String> parameters) { if (getBlockState().getDefinitionListDepth() == 1 && !getBlockState().isInList()) { printEmptyLine(); } else { print("\n"); } printParameters(parameters); } }
public class class_name { @Override public void beginDefinitionList(Map<String, String> parameters) { if (getBlockState().getDefinitionListDepth() == 1 && !getBlockState().isInList()) { printEmptyLine(); // depends on control dependency: [if], data = [none] } else { print("\n"); // depends on control dependency: [if], data = [none] } printParameters(parameters); } }
public class class_name { public EClass getMetricAdjustment() { if (metricAdjustmentEClass == null) { metricAdjustmentEClass = (EClass)EPackage.Registry.INSTANCE.getEPackage(AfplibPackage.eNS_URI).getEClassifiers().get(521); } return metricAdjustmentEClass; } }
public class class_name { public EClass getMetricAdjustment() { if (metricAdjustmentEClass == null) { metricAdjustmentEClass = (EClass)EPackage.Registry.INSTANCE.getEPackage(AfplibPackage.eNS_URI).getEClassifiers().get(521); // depends on control dependency: [if], data = [none] } return metricAdjustmentEClass; } }
public class class_name { public void parse(final String filename, final File dir) { filePath = stripFragment(filename); dirPath = dir; try { final File f = new File(dir, filePath); reader.setErrorHandler(new DITAOTXMLErrorHandler(f.getAbsolutePath(), logger)); logger.info("Processing " + f.getAbsolutePath()); reader.parse(f.toURI().toString()); } catch (final RuntimeException e) { throw e; } catch (final Exception e) { throw new RuntimeException("Failed to parse " + filename + ": " + e.getMessage(), e); } } }
public class class_name { public void parse(final String filename, final File dir) { filePath = stripFragment(filename); dirPath = dir; try { final File f = new File(dir, filePath); reader.setErrorHandler(new DITAOTXMLErrorHandler(f.getAbsolutePath(), logger)); // depends on control dependency: [try], data = [none] logger.info("Processing " + f.getAbsolutePath()); // depends on control dependency: [try], data = [none] reader.parse(f.toURI().toString()); // depends on control dependency: [try], data = [none] } catch (final RuntimeException e) { throw e; } catch (final Exception e) { // depends on control dependency: [catch], data = [none] throw new RuntimeException("Failed to parse " + filename + ": " + e.getMessage(), e); } // depends on control dependency: [catch], data = [none] } }
public class class_name { public Observable<ServiceResponse<List<Iteration>>> getIterationsWithServiceResponseAsync(UUID projectId) { if (projectId == null) { throw new IllegalArgumentException("Parameter projectId is required and cannot be null."); } if (this.client.apiKey() == null) { throw new IllegalArgumentException("Parameter this.client.apiKey() is required and cannot be null."); } return service.getIterations(projectId, this.client.apiKey(), this.client.acceptLanguage(), this.client.userAgent()) .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<List<Iteration>>>>() { @Override public Observable<ServiceResponse<List<Iteration>>> call(Response<ResponseBody> response) { try { ServiceResponse<List<Iteration>> clientResponse = getIterationsDelegate(response); return Observable.just(clientResponse); } catch (Throwable t) { return Observable.error(t); } } }); } }
public class class_name { public Observable<ServiceResponse<List<Iteration>>> getIterationsWithServiceResponseAsync(UUID projectId) { if (projectId == null) { throw new IllegalArgumentException("Parameter projectId is required and cannot be null."); } if (this.client.apiKey() == null) { throw new IllegalArgumentException("Parameter this.client.apiKey() is required and cannot be null."); } return service.getIterations(projectId, this.client.apiKey(), this.client.acceptLanguage(), this.client.userAgent()) .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<List<Iteration>>>>() { @Override public Observable<ServiceResponse<List<Iteration>>> call(Response<ResponseBody> response) { try { ServiceResponse<List<Iteration>> clientResponse = getIterationsDelegate(response); return Observable.just(clientResponse); // depends on control dependency: [try], data = [none] } catch (Throwable t) { return Observable.error(t); } // depends on control dependency: [catch], data = [none] } }); } }
public class class_name { @Override protected void immediateTimeout() { if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) { Tr.event(this, tc, "immediateTimeout"); } // if we do not have a selector, then there has not been a read yet // on this connection. If we have a selector, it doesn't mean there's // an active read; however, waking up the selector with a false timeout // attempt is not optimal but not a big deal ChannelSelector sel = ((NioSocketIOChannel) getTCPConnLink().getSocketIOChannel()).getChannelSelectorRead(); if (null != sel) { // selector uses granularity of 1 second, so subtract 2 seconds // to guarantee the timeout will fire immediately this.timeoutTime = System.currentTimeMillis() - 2000L; sel.resetTimeout(this.timeoutTime); } else { if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) { Tr.event(tc, "No read selector, ignoring immediate timeout"); } } } }
public class class_name { @Override protected void immediateTimeout() { if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) { Tr.event(this, tc, "immediateTimeout"); // depends on control dependency: [if], data = [none] } // if we do not have a selector, then there has not been a read yet // on this connection. If we have a selector, it doesn't mean there's // an active read; however, waking up the selector with a false timeout // attempt is not optimal but not a big deal ChannelSelector sel = ((NioSocketIOChannel) getTCPConnLink().getSocketIOChannel()).getChannelSelectorRead(); if (null != sel) { // selector uses granularity of 1 second, so subtract 2 seconds // to guarantee the timeout will fire immediately this.timeoutTime = System.currentTimeMillis() - 2000L; // depends on control dependency: [if], data = [none] sel.resetTimeout(this.timeoutTime); // depends on control dependency: [if], data = [none] } else { if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) { Tr.event(tc, "No read selector, ignoring immediate timeout"); // depends on control dependency: [if], data = [none] } } } }
public class class_name { public void rollbackToPosition(short partition, long seqno) { PartitionState ps = partitionStates.get(partition); ps.setStartSeqno(seqno); ps.setSnapshotStartSeqno(seqno); ps.setSnapshotEndSeqno(seqno); List<FailoverLogEntry> failoverLog = ps.getFailoverLog(); Iterator<FailoverLogEntry> flogIterator = failoverLog.iterator(); List<FailoverLogEntry> entriesToRemove = new ArrayList<>(); while (flogIterator.hasNext()) { FailoverLogEntry entry = flogIterator.next(); // check if this entry is has a higher seqno than we need to roll back to if (lessThanUnsigned(seqno, entry.getSeqno())) { entriesToRemove.add(entry); } } failoverLog.removeAll(entriesToRemove); partitionStates.set(partition, ps); } }
public class class_name { public void rollbackToPosition(short partition, long seqno) { PartitionState ps = partitionStates.get(partition); ps.setStartSeqno(seqno); ps.setSnapshotStartSeqno(seqno); ps.setSnapshotEndSeqno(seqno); List<FailoverLogEntry> failoverLog = ps.getFailoverLog(); Iterator<FailoverLogEntry> flogIterator = failoverLog.iterator(); List<FailoverLogEntry> entriesToRemove = new ArrayList<>(); while (flogIterator.hasNext()) { FailoverLogEntry entry = flogIterator.next(); // check if this entry is has a higher seqno than we need to roll back to if (lessThanUnsigned(seqno, entry.getSeqno())) { entriesToRemove.add(entry); // depends on control dependency: [if], data = [none] } } failoverLog.removeAll(entriesToRemove); partitionStates.set(partition, ps); } }
public class class_name { @Override public void prepare(ResponseBuilder rb) throws IOException { // System.out // .println(System.nanoTime() + " - " + Thread.currentThread().getId() // + " - " + rb.req.getParams().getBool(ShardParams.IS_SHARD, false) // + " PREPARE " + rb.stage + " " + rb.req.getParamString()); // always create status initializeRequestHandler(rb); MtasSolrStatus solrStatus = new MtasSolrStatus(rb.req.getOriginalParams().toQueryString(), rb.req.getParams().getBool(ShardParams.IS_SHARD, false), rb.shards, rb.rsp); rb.req.getContext().put(MtasSolrStatus.class, solrStatus); solrStatus.setStage(rb.stage); if (rb.req.getParams().getBool(PARAM_MTAS, false)) { try { // initialize mtasSolrResultMerge = new MtasSolrResultMerge(); // prepare components ComponentFields mtasFields = new ComponentFields(); // get settings version if (rb.req.getParams().getBool(MtasSolrComponentVersion.PARAM_MTAS_VERSION, false)) { searchVersion.prepare(rb, mtasFields); } // get settings status if (rb.req.getParams().getBool(MtasSolrComponentStatus.PARAM_MTAS_STATUS, false)) { searchStatus.prepare(rb, mtasFields); mtasFields.status.handler = requestHandlerName; if (mtasFields.status.key != null) { solrStatus.setKey(mtasFields.status.key); } } // now, register status registerStatus(solrStatus); // get settings document if (rb.req.getParams().getBool(MtasSolrComponentDocument.PARAM_MTAS_DOCUMENT, false)) { searchDocument.prepare(rb, mtasFields); } // get settings kwic if (rb.req.getParams().getBool(MtasSolrComponentKwic.PARAM_MTAS_KWIC, false)) { searchKwic.prepare(rb, mtasFields); } // get settings list if (rb.req.getParams().getBool(MtasSolrComponentList.PARAM_MTAS_LIST, false)) { searchList.prepare(rb, mtasFields); } // get settings group if (rb.req.getParams().getBool(MtasSolrComponentGroup.PARAM_MTAS_GROUP, false)) { searchGroup.prepare(rb, mtasFields); } // get settings termvector if (rb.req.getParams().getBool(MtasSolrComponentTermvector.PARAM_MTAS_TERMVECTOR, false)) { searchTermvector.prepare(rb, mtasFields); } // get settings prefix if (rb.req.getParams().getBool(MtasSolrComponentPrefix.PARAM_MTAS_PREFIX, false)) { searchPrefix.prepare(rb, mtasFields); } // get settings stats if (rb.req.getParams().getBool(MtasSolrComponentStats.PARAM_MTAS_STATS, false)) { searchStats.prepare(rb, mtasFields); } // get settings facet if (rb.req.getParams().getBool(MtasSolrComponentFacet.PARAM_MTAS_FACET, false)) { searchFacet.prepare(rb, mtasFields); } // get settings collection if (rb.req.getParams().getBool(MtasSolrComponentCollection.PARAM_MTAS_COLLECTION, false)) { searchCollection.prepare(rb, mtasFields); } rb.req.getContext().put(ComponentFields.class, mtasFields); } catch (ExitableDirectoryReader.ExitingReaderException e) { solrStatus.setError(e.getMessage()); } catch (IOException e) { solrStatus.setError(e); } finally { checkStatus(solrStatus); } } else { // register and check status registerStatus(solrStatus); checkStatus(solrStatus); } } }
public class class_name { @Override public void prepare(ResponseBuilder rb) throws IOException { // System.out // .println(System.nanoTime() + " - " + Thread.currentThread().getId() // + " - " + rb.req.getParams().getBool(ShardParams.IS_SHARD, false) // + " PREPARE " + rb.stage + " " + rb.req.getParamString()); // always create status initializeRequestHandler(rb); MtasSolrStatus solrStatus = new MtasSolrStatus(rb.req.getOriginalParams().toQueryString(), rb.req.getParams().getBool(ShardParams.IS_SHARD, false), rb.shards, rb.rsp); rb.req.getContext().put(MtasSolrStatus.class, solrStatus); solrStatus.setStage(rb.stage); if (rb.req.getParams().getBool(PARAM_MTAS, false)) { try { // initialize mtasSolrResultMerge = new MtasSolrResultMerge(); // depends on control dependency: [try], data = [none] // prepare components ComponentFields mtasFields = new ComponentFields(); // get settings version if (rb.req.getParams().getBool(MtasSolrComponentVersion.PARAM_MTAS_VERSION, false)) { searchVersion.prepare(rb, mtasFields); // depends on control dependency: [if], data = [none] } // get settings status if (rb.req.getParams().getBool(MtasSolrComponentStatus.PARAM_MTAS_STATUS, false)) { searchStatus.prepare(rb, mtasFields); // depends on control dependency: [if], data = [none] mtasFields.status.handler = requestHandlerName; // depends on control dependency: [if], data = [none] if (mtasFields.status.key != null) { solrStatus.setKey(mtasFields.status.key); // depends on control dependency: [if], data = [(mtasFields.status.key] } } // now, register status registerStatus(solrStatus); // depends on control dependency: [try], data = [none] // get settings document if (rb.req.getParams().getBool(MtasSolrComponentDocument.PARAM_MTAS_DOCUMENT, false)) { searchDocument.prepare(rb, mtasFields); // depends on control dependency: [if], data = [none] } // get settings kwic if (rb.req.getParams().getBool(MtasSolrComponentKwic.PARAM_MTAS_KWIC, false)) { searchKwic.prepare(rb, mtasFields); // depends on control dependency: [if], data = [none] } // get settings list if (rb.req.getParams().getBool(MtasSolrComponentList.PARAM_MTAS_LIST, false)) { searchList.prepare(rb, mtasFields); // depends on control dependency: [if], data = [none] } // get settings group if (rb.req.getParams().getBool(MtasSolrComponentGroup.PARAM_MTAS_GROUP, false)) { searchGroup.prepare(rb, mtasFields); // depends on control dependency: [if], data = [none] } // get settings termvector if (rb.req.getParams().getBool(MtasSolrComponentTermvector.PARAM_MTAS_TERMVECTOR, false)) { searchTermvector.prepare(rb, mtasFields); // depends on control dependency: [if], data = [none] } // get settings prefix if (rb.req.getParams().getBool(MtasSolrComponentPrefix.PARAM_MTAS_PREFIX, false)) { searchPrefix.prepare(rb, mtasFields); // depends on control dependency: [if], data = [none] } // get settings stats if (rb.req.getParams().getBool(MtasSolrComponentStats.PARAM_MTAS_STATS, false)) { searchStats.prepare(rb, mtasFields); // depends on control dependency: [if], data = [none] } // get settings facet if (rb.req.getParams().getBool(MtasSolrComponentFacet.PARAM_MTAS_FACET, false)) { searchFacet.prepare(rb, mtasFields); // depends on control dependency: [if], data = [none] } // get settings collection if (rb.req.getParams().getBool(MtasSolrComponentCollection.PARAM_MTAS_COLLECTION, false)) { searchCollection.prepare(rb, mtasFields); // depends on control dependency: [if], data = [none] } rb.req.getContext().put(ComponentFields.class, mtasFields); // depends on control dependency: [try], data = [none] } catch (ExitableDirectoryReader.ExitingReaderException e) { solrStatus.setError(e.getMessage()); } catch (IOException e) { // depends on control dependency: [catch], data = [none] solrStatus.setError(e); } finally { // depends on control dependency: [catch], data = [none] checkStatus(solrStatus); } } else { // register and check status registerStatus(solrStatus); checkStatus(solrStatus); } } }
public class class_name { public double inverseCumulativeDistribution(double x) { double p = Math.exp(-lambda); double dp = p; int k = 0; while(x > p) { k++; dp *= lambda / k; p += dp; } return k; } }
public class class_name { public double inverseCumulativeDistribution(double x) { double p = Math.exp(-lambda); double dp = p; int k = 0; while(x > p) { k++; // depends on control dependency: [while], data = [none] dp *= lambda / k; // depends on control dependency: [while], data = [none] p += dp; // depends on control dependency: [while], data = [none] } return k; } }
public class class_name { public static void setDnsCache(String host, String... ips) { try { InetAddressCacheUtil.setInetAddressCache(host, ips, NEVER_EXPIRATION); } catch (Exception e) { final String message = String.format("Fail to setDnsCache for host %s ip %s, cause: %s", host, Arrays.toString(ips), e.toString()); throw new DnsCacheManipulatorException(message, e); } } }
public class class_name { public static void setDnsCache(String host, String... ips) { try { InetAddressCacheUtil.setInetAddressCache(host, ips, NEVER_EXPIRATION); // depends on control dependency: [try], data = [none] } catch (Exception e) { final String message = String.format("Fail to setDnsCache for host %s ip %s, cause: %s", host, Arrays.toString(ips), e.toString()); throw new DnsCacheManipulatorException(message, e); } // depends on control dependency: [catch], data = [none] } }
public class class_name { AddIfCluster addIfCluster(Object... objects) { if (addIfCluster == null) { addIfCluster = new AddIfCluster(!getWebServer().isStandalone()); } addIfCluster.ifAdd(objects); return addIfCluster; } }
public class class_name { AddIfCluster addIfCluster(Object... objects) { if (addIfCluster == null) { addIfCluster = new AddIfCluster(!getWebServer().isStandalone()); // depends on control dependency: [if], data = [none] } addIfCluster.ifAdd(objects); return addIfCluster; } }
public class class_name { @Transactional protected synchronized void _checkAlertExistence(boolean enabled) { for (String alertName : new String[] { FILE_DESCRIPTORS_ALERT, PHYSICAL_MEMORY_ALERT, SWAP_SPACE_ALERT }) { if (_alertService.findAlertByNameAndOwner(_constructAlertName(alertName), _adminUser) == null) { String metricExpression = null; TriggerType triggerType = null; String triggerName = null; double triggerThreshold = Double.NaN; switch (alertName) { case FILE_DESCRIPTORS_ALERT: String openFileDescMetricExp = MessageFormat.format("-1h:{0}:{1}'{'host={2}'}':avg", Counter.OPEN_DESCRIPTORS.getScope(), Counter.OPEN_DESCRIPTORS.getMetric(), HOSTNAME); String maxFileDescMetricExp = MessageFormat.format("-1h:{0}:{1}'{'host={2}'}':avg", Counter.MAX_DESCRIPTORS.getScope(), Counter.MAX_DESCRIPTORS.getMetric(), HOSTNAME); metricExpression = MessageFormat.format("{0}({1}, {2})", Function.DIVIDE.getName(), openFileDescMetricExp, maxFileDescMetricExp); triggerType = TriggerType.GREATER_THAN; triggerName = "Open FD > 95% of Max FD"; triggerThreshold = 0.95; break; case PHYSICAL_MEMORY_ALERT: String freeMemMetricExp = MessageFormat.format("-1h:{0}:{1}'{'host={2}'}':avg", Counter.FREE_PHYSICAL_MEM.getScope(), Counter.FREE_PHYSICAL_MEM.getMetric(), HOSTNAME); String maxMemMetricExp = MessageFormat.format("-1h:{0}:{1}'{'host={2}'}':avg", Counter.MAX_PHYSICAL_MEM.getScope(), Counter.MAX_PHYSICAL_MEM.getMetric(), HOSTNAME); metricExpression = MessageFormat.format("{0}({1}, {2})", Function.DIVIDE.getName(), freeMemMetricExp, maxMemMetricExp); triggerType = TriggerType.LESS_THAN; triggerName = "Free Mem < 5% of Tot Mem"; triggerThreshold = 0.05; break; case SWAP_SPACE_ALERT: String freeSSMetricExp = MessageFormat.format("-1h:{0}:{1}'{'host={2}'}':avg", Counter.FREE_SWAP_SPACE.getScope(), Counter.FREE_SWAP_SPACE.getMetric(), HOSTNAME); String maxSSMetricExp = MessageFormat.format("-1h:{0}:{1}'{'host={2}'}':avg", Counter.MAX_SWAP_SPACE.getScope(), Counter.MAX_SWAP_SPACE.getMetric(), HOSTNAME); metricExpression = MessageFormat.format("{0}({1}, {2})", Function.DIVIDE.getName(), freeSSMetricExp, maxSSMetricExp); triggerType = TriggerType.LESS_THAN; triggerName = "Free Swap Space < 5% of Tot Swap Space"; triggerThreshold = 0.05; break; default: throw new SystemException("Attempting to create an unsupported monitoring alert" + alertName); } requireArgument(metricExpression != null && triggerType != null & triggerName != null, "Unsupported monitor alert " + alertName); Alert alert = new Alert(_adminUser, _adminUser, _constructAlertName(alertName), metricExpression, "0 * * * *"); Notification notification = new Notification(NOTIFICATION_NAME, alert, AuditNotifier.class.getName(), new ArrayList<String>(), 60000L); Trigger trigger = new Trigger(alert, triggerType, triggerName, triggerThreshold, 0); List<Trigger> triggers = Arrays.asList(new Trigger[] { trigger }); notification.setTriggers(triggers); alert.setNotifications(Arrays.asList(new Notification[] { notification })); alert.setTriggers(triggers); alert.setEnabled(enabled); _alertService.updateAlert(alert); } else { // end if Alert alert = _alertService.findAlertByNameAndOwner(_constructAlertName(alertName), _adminUser); alert.setEnabled(enabled); _alertService.updateAlert(alert); } // end if-else } // end for } }
public class class_name { @Transactional protected synchronized void _checkAlertExistence(boolean enabled) { for (String alertName : new String[] { FILE_DESCRIPTORS_ALERT, PHYSICAL_MEMORY_ALERT, SWAP_SPACE_ALERT }) { if (_alertService.findAlertByNameAndOwner(_constructAlertName(alertName), _adminUser) == null) { String metricExpression = null; TriggerType triggerType = null; String triggerName = null; double triggerThreshold = Double.NaN; switch (alertName) { case FILE_DESCRIPTORS_ALERT: String openFileDescMetricExp = MessageFormat.format("-1h:{0}:{1}'{'host={2}'}':avg", Counter.OPEN_DESCRIPTORS.getScope(), Counter.OPEN_DESCRIPTORS.getMetric(), HOSTNAME); String maxFileDescMetricExp = MessageFormat.format("-1h:{0}:{1}'{'host={2}'}':avg", Counter.MAX_DESCRIPTORS.getScope(), Counter.MAX_DESCRIPTORS.getMetric(), HOSTNAME); metricExpression = MessageFormat.format("{0}({1}, {2})", Function.DIVIDE.getName(), openFileDescMetricExp, maxFileDescMetricExp); triggerType = TriggerType.GREATER_THAN; triggerName = "Open FD > 95% of Max FD"; triggerThreshold = 0.95; break; case PHYSICAL_MEMORY_ALERT: String freeMemMetricExp = MessageFormat.format("-1h:{0}:{1}'{'host={2}'}':avg", Counter.FREE_PHYSICAL_MEM.getScope(), Counter.FREE_PHYSICAL_MEM.getMetric(), HOSTNAME); String maxMemMetricExp = MessageFormat.format("-1h:{0}:{1}'{'host={2}'}':avg", Counter.MAX_PHYSICAL_MEM.getScope(), Counter.MAX_PHYSICAL_MEM.getMetric(), HOSTNAME); metricExpression = MessageFormat.format("{0}({1}, {2})", Function.DIVIDE.getName(), freeMemMetricExp, maxMemMetricExp); triggerType = TriggerType.LESS_THAN; triggerName = "Free Mem < 5% of Tot Mem"; triggerThreshold = 0.05; break; case SWAP_SPACE_ALERT: String freeSSMetricExp = MessageFormat.format("-1h:{0}:{1}'{'host={2}'}':avg", Counter.FREE_SWAP_SPACE.getScope(), Counter.FREE_SWAP_SPACE.getMetric(), HOSTNAME); String maxSSMetricExp = MessageFormat.format("-1h:{0}:{1}'{'host={2}'}':avg", Counter.MAX_SWAP_SPACE.getScope(), Counter.MAX_SWAP_SPACE.getMetric(), HOSTNAME); metricExpression = MessageFormat.format("{0}({1}, {2})", Function.DIVIDE.getName(), freeSSMetricExp, maxSSMetricExp); triggerType = TriggerType.LESS_THAN; triggerName = "Free Swap Space < 5% of Tot Swap Space"; triggerThreshold = 0.05; break; default: throw new SystemException("Attempting to create an unsupported monitoring alert" + alertName); } requireArgument(metricExpression != null && triggerType != null & triggerName != null, "Unsupported monitor alert " + alertName); // depends on control dependency: [if], data = [none] Alert alert = new Alert(_adminUser, _adminUser, _constructAlertName(alertName), metricExpression, "0 * * * *"); Notification notification = new Notification(NOTIFICATION_NAME, alert, AuditNotifier.class.getName(), new ArrayList<String>(), 60000L); Trigger trigger = new Trigger(alert, triggerType, triggerName, triggerThreshold, 0); // depends on control dependency: [if], data = [none] List<Trigger> triggers = Arrays.asList(new Trigger[] { trigger }); notification.setTriggers(triggers); // depends on control dependency: [if], data = [none] alert.setNotifications(Arrays.asList(new Notification[] { notification })); // depends on control dependency: [if], data = [none] alert.setTriggers(triggers); // depends on control dependency: [if], data = [none] alert.setEnabled(enabled); // depends on control dependency: [if], data = [none] _alertService.updateAlert(alert); // depends on control dependency: [if], data = [none] } else { // end if Alert alert = _alertService.findAlertByNameAndOwner(_constructAlertName(alertName), _adminUser); alert.setEnabled(enabled); // depends on control dependency: [if], data = [none] _alertService.updateAlert(alert); // depends on control dependency: [if], data = [none] } // end if-else } // end for } }
public class class_name { @Override public final Object put(final Object key, final Object value) { try { CellMapKey mkey = new CellMapKey((String) key); if (!mkey.isParseSuccess()) { return null; } Cell poiCell = parent.getCellHelper() .getPoiCellWithRowColFromCurrentPage(mkey.getRowIndex(), mkey.getColIndex()); if (poiCell == null) { return null; } String oldValue = CellUtility .getCellValueWithoutFormat(poiCell); FacesCell facesCell = parent.getCellHelper() .getFacesCellWithRowColFromCurrentPage( mkey.getRowIndex(), mkey.getColIndex()); String newValue = assembleNewValue(value, facesCell); if (newValue != null && !newValue.equals(oldValue)) { CellUtility.setCellValue(poiCell, newValue); if (facesCell.isHasSaveAttr()) { parent.getCellHelper().saveDataInContext(poiCell, newValue); } // patch to avoid not updated downloaded file CellUtility.copyCell(poiCell.getSheet(), poiCell.getRow(), poiCell.getRow(), poiCell.getColumnIndex(),false); parent.getCellHelper().reCalc(); } return value; } catch (Exception ex) { LOG.log(Level.SEVERE, "Save cell data error : " + ex.getLocalizedMessage(), ex); } return null; } }
public class class_name { @Override public final Object put(final Object key, final Object value) { try { CellMapKey mkey = new CellMapKey((String) key); if (!mkey.isParseSuccess()) { return null; // depends on control dependency: [if], data = [none] } Cell poiCell = parent.getCellHelper() .getPoiCellWithRowColFromCurrentPage(mkey.getRowIndex(), mkey.getColIndex()); if (poiCell == null) { return null; // depends on control dependency: [if], data = [none] } String oldValue = CellUtility .getCellValueWithoutFormat(poiCell); FacesCell facesCell = parent.getCellHelper() .getFacesCellWithRowColFromCurrentPage( mkey.getRowIndex(), mkey.getColIndex()); String newValue = assembleNewValue(value, facesCell); if (newValue != null && !newValue.equals(oldValue)) { CellUtility.setCellValue(poiCell, newValue); // depends on control dependency: [if], data = [none] if (facesCell.isHasSaveAttr()) { parent.getCellHelper().saveDataInContext(poiCell, newValue); // depends on control dependency: [if], data = [none] } // patch to avoid not updated downloaded file CellUtility.copyCell(poiCell.getSheet(), poiCell.getRow(), poiCell.getRow(), poiCell.getColumnIndex(),false); // depends on control dependency: [if], data = [none] parent.getCellHelper().reCalc(); // depends on control dependency: [if], data = [none] } return value; // depends on control dependency: [try], data = [none] } catch (Exception ex) { LOG.log(Level.SEVERE, "Save cell data error : " + ex.getLocalizedMessage(), ex); } // depends on control dependency: [catch], data = [none] return null; } }
public class class_name { @SuppressWarnings("unused") public Map<String, Timestamp> getUserContributionMap(final int articleID, String[] groupfilter, boolean onlyRegistered) throws WikiApiException { Map<String, Timestamp> authorTSMap = new HashMap<String, Timestamp>(); try { if (articleID < 1) { throw new IllegalArgumentException(); } PreparedStatement statement = null; ResultSet result = null; try { // Check if necessary index exists if (!indexExists("revisions")) { throw new WikiInitializationException( "Please create an index on revisions(ArticleID) in order to make this query feasible."); } StringBuilder statementStr = new StringBuilder(); if (groupfilter == null || groupfilter.length < 1 || !tableExists("user_groups")) { // create statement WITHOUT filter statementStr .append("SELECT ContributorName, Timestamp FROM revisions WHERE ArticleID=?"); statement = connection.prepareStatement(statementStr.toString()); statement.setInt(1, articleID); } else { // create statement WITH filter statementStr .append("SELECT ContributorName, Timestamp FROM revisions AS rev, user_groups AS ug WHERE ArticleID=?"); statementStr.append(" AND rev.ContributorId=ug.ug_user"); for (String element : groupfilter) { statementStr.append(" AND NOT ug.ug_group=?"); } // and combine with results from unregistered users if (!onlyRegistered) { statementStr.append(" UNION ( SELECT ContributorName, Timestamp FROM revisions AS rev WHERE ArticleID=? AND rev.ContributorId IS NULL)"); } statement = connection.prepareStatement(statementStr.toString()); // insert article id in prepared statement statement.setInt(1, articleID); // insert filtered groups in prepared statement int curPrepStatValueIdx = 2; for (String group : groupfilter) { statement.setString(curPrepStatValueIdx++, group); } if (!onlyRegistered) { // insert article id for second select in prepared statement statement.setInt(curPrepStatValueIdx, articleID); } } result = statement.executeQuery(); if (result == null) { throw new WikiPageNotFoundException("The article with the ID " + articleID + " was not found."); } while (result.next()) { // Write data from current revision to Map authorTSMap.put(result.getString(1), new Timestamp(result.getLong(2))); } } finally { if (statement != null) { statement.close(); } if (result != null) { result.close(); } } return authorTSMap; } catch (WikiApiException e) { throw e; } catch (Exception e) { throw new WikiApiException(e); } } }
public class class_name { @SuppressWarnings("unused") public Map<String, Timestamp> getUserContributionMap(final int articleID, String[] groupfilter, boolean onlyRegistered) throws WikiApiException { Map<String, Timestamp> authorTSMap = new HashMap<String, Timestamp>(); try { if (articleID < 1) { throw new IllegalArgumentException(); } PreparedStatement statement = null; ResultSet result = null; try { // Check if necessary index exists if (!indexExists("revisions")) { throw new WikiInitializationException( "Please create an index on revisions(ArticleID) in order to make this query feasible."); } StringBuilder statementStr = new StringBuilder(); if (groupfilter == null || groupfilter.length < 1 || !tableExists("user_groups")) { // create statement WITHOUT filter statementStr .append("SELECT ContributorName, Timestamp FROM revisions WHERE ArticleID=?"); // depends on control dependency: [if], data = [none] statement = connection.prepareStatement(statementStr.toString()); // depends on control dependency: [if], data = [none] statement.setInt(1, articleID); // depends on control dependency: [if], data = [none] } else { // create statement WITH filter statementStr .append("SELECT ContributorName, Timestamp FROM revisions AS rev, user_groups AS ug WHERE ArticleID=?"); // depends on control dependency: [if], data = [none] statementStr.append(" AND rev.ContributorId=ug.ug_user"); for (String element : groupfilter) { statementStr.append(" AND NOT ug.ug_group=?"); } // and combine with results from unregistered users if (!onlyRegistered) { statementStr.append(" UNION ( SELECT ContributorName, Timestamp FROM revisions AS rev WHERE ArticleID=? AND rev.ContributorId IS NULL)"); } statement = connection.prepareStatement(statementStr.toString()); // insert article id in prepared statement statement.setInt(1, articleID); // insert filtered groups in prepared statement int curPrepStatValueIdx = 2; for (String group : groupfilter) { statement.setString(curPrepStatValueIdx++, group); } if (!onlyRegistered) { // insert article id for second select in prepared statement statement.setInt(curPrepStatValueIdx, articleID); } } result = statement.executeQuery(); if (result == null) { throw new WikiPageNotFoundException("The article with the ID " + articleID + " was not found."); } while (result.next()) { // Write data from current revision to Map authorTSMap.put(result.getString(1), new Timestamp(result.getLong(2))); // depends on control dependency: [if], data = [none] } } finally { if (statement != null) { statement.close(); // depends on control dependency: [if], data = [none] } if (result != null) { result.close(); // depends on control dependency: [if], data = [none] } } return authorTSMap; } catch (WikiApiException e) { throw e; } catch (Exception e) { throw new WikiApiException(e); } } }
public class class_name { public void del(final OnItemSnapshot onItemSnapshot, final OnError onError){ TableMetadata tm = context.getTableMeta(this.table.name); if(tm == null){ this.table.meta(new OnTableMetadata(){ @Override public void run(TableMetadata tableMetadata) { _del(onItemSnapshot, onError); } }, onError); } else { this._del(onItemSnapshot, onError); } return; } }
public class class_name { public void del(final OnItemSnapshot onItemSnapshot, final OnError onError){ TableMetadata tm = context.getTableMeta(this.table.name); if(tm == null){ this.table.meta(new OnTableMetadata(){ @Override public void run(TableMetadata tableMetadata) { _del(onItemSnapshot, onError); } }, onError); // depends on control dependency: [if], data = [none] } else { this._del(onItemSnapshot, onError); // depends on control dependency: [if], data = [none] } return; } }
public class class_name { static MavenResolvedArtifact fromArtifactResult(final ArtifactResult artifactResult) { final Artifact artifact = artifactResult.getArtifact(); final DependencyNode root = artifactResult.getRequest().getDependencyNode(); // SHRINKRES-143 lets ignore invalid scope ScopeType scopeType = ScopeType.RUNTIME; try { scopeType = ScopeType.fromScopeType(root.getDependency().getScope()); } catch (IllegalArgumentException e) { // let scope be RUNTIME log.log(Level.WARNING, "Invalid scope {0} of retrieved dependency {1} will be replaced by <scope>runtime</scope>", new Object[] { root.getDependency().getScope(), root.getDependency().getArtifact() }); } final List<DependencyNode> children = root.getChildren(); final boolean optional = root.getDependency().isOptional(); return new MavenResolvedArtifactImpl(artifact, scopeType, children, optional); } }
public class class_name { static MavenResolvedArtifact fromArtifactResult(final ArtifactResult artifactResult) { final Artifact artifact = artifactResult.getArtifact(); final DependencyNode root = artifactResult.getRequest().getDependencyNode(); // SHRINKRES-143 lets ignore invalid scope ScopeType scopeType = ScopeType.RUNTIME; try { scopeType = ScopeType.fromScopeType(root.getDependency().getScope()); // depends on control dependency: [try], data = [none] } catch (IllegalArgumentException e) { // let scope be RUNTIME log.log(Level.WARNING, "Invalid scope {0} of retrieved dependency {1} will be replaced by <scope>runtime</scope>", new Object[] { root.getDependency().getScope(), root.getDependency().getArtifact() }); } // depends on control dependency: [catch], data = [none] final List<DependencyNode> children = root.getChildren(); final boolean optional = root.getDependency().isOptional(); return new MavenResolvedArtifactImpl(artifact, scopeType, children, optional); } }
public class class_name { public void marshall(CreateBrokerRequest createBrokerRequest, ProtocolMarshaller protocolMarshaller) { if (createBrokerRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(createBrokerRequest.getAutoMinorVersionUpgrade(), AUTOMINORVERSIONUPGRADE_BINDING); protocolMarshaller.marshall(createBrokerRequest.getBrokerName(), BROKERNAME_BINDING); protocolMarshaller.marshall(createBrokerRequest.getConfiguration(), CONFIGURATION_BINDING); protocolMarshaller.marshall(createBrokerRequest.getCreatorRequestId(), CREATORREQUESTID_BINDING); protocolMarshaller.marshall(createBrokerRequest.getDeploymentMode(), DEPLOYMENTMODE_BINDING); protocolMarshaller.marshall(createBrokerRequest.getEngineType(), ENGINETYPE_BINDING); protocolMarshaller.marshall(createBrokerRequest.getEngineVersion(), ENGINEVERSION_BINDING); protocolMarshaller.marshall(createBrokerRequest.getHostInstanceType(), HOSTINSTANCETYPE_BINDING); protocolMarshaller.marshall(createBrokerRequest.getLogs(), LOGS_BINDING); protocolMarshaller.marshall(createBrokerRequest.getMaintenanceWindowStartTime(), MAINTENANCEWINDOWSTARTTIME_BINDING); protocolMarshaller.marshall(createBrokerRequest.getPubliclyAccessible(), PUBLICLYACCESSIBLE_BINDING); protocolMarshaller.marshall(createBrokerRequest.getSecurityGroups(), SECURITYGROUPS_BINDING); protocolMarshaller.marshall(createBrokerRequest.getSubnetIds(), SUBNETIDS_BINDING); protocolMarshaller.marshall(createBrokerRequest.getTags(), TAGS_BINDING); protocolMarshaller.marshall(createBrokerRequest.getUsers(), USERS_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
public class class_name { public void marshall(CreateBrokerRequest createBrokerRequest, ProtocolMarshaller protocolMarshaller) { if (createBrokerRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(createBrokerRequest.getAutoMinorVersionUpgrade(), AUTOMINORVERSIONUPGRADE_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(createBrokerRequest.getBrokerName(), BROKERNAME_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(createBrokerRequest.getConfiguration(), CONFIGURATION_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(createBrokerRequest.getCreatorRequestId(), CREATORREQUESTID_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(createBrokerRequest.getDeploymentMode(), DEPLOYMENTMODE_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(createBrokerRequest.getEngineType(), ENGINETYPE_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(createBrokerRequest.getEngineVersion(), ENGINEVERSION_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(createBrokerRequest.getHostInstanceType(), HOSTINSTANCETYPE_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(createBrokerRequest.getLogs(), LOGS_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(createBrokerRequest.getMaintenanceWindowStartTime(), MAINTENANCEWINDOWSTARTTIME_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(createBrokerRequest.getPubliclyAccessible(), PUBLICLYACCESSIBLE_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(createBrokerRequest.getSecurityGroups(), SECURITYGROUPS_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(createBrokerRequest.getSubnetIds(), SUBNETIDS_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(createBrokerRequest.getTags(), TAGS_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(createBrokerRequest.getUsers(), USERS_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 String unicodeToChinese(String unicode) { StringBuilder out = new StringBuilder(); if (!isEmpty(unicode)) { for (int i = 0; i < unicode.length(); i++) { out.append(unicode.charAt(i)); } } return out.toString(); } }
public class class_name { public static String unicodeToChinese(String unicode) { StringBuilder out = new StringBuilder(); if (!isEmpty(unicode)) { for (int i = 0; i < unicode.length(); i++) { out.append(unicode.charAt(i)); // depends on control dependency: [for], data = [i] } } return out.toString(); } }
public class class_name { public static String transformClassName(String className) { int lastDot = className.lastIndexOf('.'); if (lastDot >= 0) { String pkg = className.substring(0, lastDot); if (!isUnlikelyToBeRenamed(pkg)) { className = className.substring(lastDot + 1); } } return className; } }
public class class_name { public static String transformClassName(String className) { int lastDot = className.lastIndexOf('.'); if (lastDot >= 0) { String pkg = className.substring(0, lastDot); if (!isUnlikelyToBeRenamed(pkg)) { className = className.substring(lastDot + 1); // depends on control dependency: [if], data = [none] } } return className; } }
public class class_name { public final void mWS() throws RecognitionException { try { int _type = WS; int _channel = DEFAULT_TOKEN_CHANNEL; // /home/victor/srec/core/src/main/antlr/srec.g:147:2: ( ( ' ' | '\\t' )+ ) // /home/victor/srec/core/src/main/antlr/srec.g:147:4: ( ' ' | '\\t' )+ { // /home/victor/srec/core/src/main/antlr/srec.g:147:4: ( ' ' | '\\t' )+ int cnt7=0; loop7: do { int alt7=2; int LA7_0 = input.LA(1); if ( (LA7_0=='\t'||LA7_0==' ') ) { alt7=1; } switch (alt7) { case 1 : // /home/victor/srec/core/src/main/antlr/srec.g: { if ( input.LA(1)=='\t'||input.LA(1)==' ' ) { input.consume(); } else { MismatchedSetException mse = new MismatchedSetException(null,input); recover(mse); throw mse;} } break; default : if ( cnt7 >= 1 ) break loop7; EarlyExitException eee = new EarlyExitException(7, input); throw eee; } cnt7++; } while (true); skip(); } state.type = _type; state.channel = _channel; } finally { } } }
public class class_name { public final void mWS() throws RecognitionException { try { int _type = WS; int _channel = DEFAULT_TOKEN_CHANNEL; // /home/victor/srec/core/src/main/antlr/srec.g:147:2: ( ( ' ' | '\\t' )+ ) // /home/victor/srec/core/src/main/antlr/srec.g:147:4: ( ' ' | '\\t' )+ { // /home/victor/srec/core/src/main/antlr/srec.g:147:4: ( ' ' | '\\t' )+ int cnt7=0; loop7: do { int alt7=2; int LA7_0 = input.LA(1); if ( (LA7_0=='\t'||LA7_0==' ') ) { alt7=1; // depends on control dependency: [if], data = [none] } switch (alt7) { case 1 : // /home/victor/srec/core/src/main/antlr/srec.g: { if ( input.LA(1)=='\t'||input.LA(1)==' ' ) { input.consume(); // depends on control dependency: [if], data = [none] } else { MismatchedSetException mse = new MismatchedSetException(null,input); recover(mse); // depends on control dependency: [if], data = [none] throw mse;} } break; default : if ( cnt7 >= 1 ) break loop7; EarlyExitException eee = new EarlyExitException(7, input); throw eee; } cnt7++; } while (true); skip(); } state.type = _type; state.channel = _channel; } finally { } } }
public class class_name { protected void recycleByRenderState(RecyclerView.Recycler recycler, RenderState renderState) { if (renderState.mLayoutDirection == RenderState.LAYOUT_START) { recycleViewsFromEnd(recycler, renderState.mScrollingOffset); } else { recycleViewsFromStart(recycler, renderState.mScrollingOffset); } } }
public class class_name { protected void recycleByRenderState(RecyclerView.Recycler recycler, RenderState renderState) { if (renderState.mLayoutDirection == RenderState.LAYOUT_START) { recycleViewsFromEnd(recycler, renderState.mScrollingOffset); // depends on control dependency: [if], data = [none] } else { recycleViewsFromStart(recycler, renderState.mScrollingOffset); // depends on control dependency: [if], data = [none] } } }
public class class_name { private void readConfig(){ configuration = MoskitoConfigurationHolder.getConfiguration(); ThresholdsConfig config = configuration.getThresholdsConfig(); ThresholdConfig[] tcs = config.getThresholds(); if (tcs!=null && tcs.length>0){ for (ThresholdConfig tc : tcs){ ThresholdDefinition td = new ThresholdDefinition(); td.setName(tc.getName()); td.setIntervalName(tc.getIntervalName()); td.setProducerName(tc.getProducerName()); td.setStatName(tc.getStatName()); td.setTimeUnit(TimeUnit.valueOf(tc.getTimeUnit())); td.setValueName(tc.getValueName()); Threshold newThreshold = createThreshold(td); GuardConfig[] guards = tc.getGuards(); if (guards!=null && guards.length>0){ boolean hasDots = false; for (GuardConfig guard : guards ) { hasDots |= hasDots(guard.getValue()); } for (GuardConfig guard : guards ){ newThreshold.addGuard( hasDots ? new DoubleBarrierPassGuard(ThresholdStatus.valueOf(guard.getStatus()), Double.parseDouble(guard.getValue()), GuardedDirection.valueOf(guard.getDirection())) : new LongBarrierPassGuard(ThresholdStatus.valueOf(guard.getStatus()), Long.parseLong(guard.getValue()), GuardedDirection.valueOf(guard.getDirection())) ); } } } } } }
public class class_name { private void readConfig(){ configuration = MoskitoConfigurationHolder.getConfiguration(); ThresholdsConfig config = configuration.getThresholdsConfig(); ThresholdConfig[] tcs = config.getThresholds(); if (tcs!=null && tcs.length>0){ for (ThresholdConfig tc : tcs){ ThresholdDefinition td = new ThresholdDefinition(); td.setName(tc.getName()); // depends on control dependency: [for], data = [tc] td.setIntervalName(tc.getIntervalName()); // depends on control dependency: [for], data = [tc] td.setProducerName(tc.getProducerName()); // depends on control dependency: [for], data = [tc] td.setStatName(tc.getStatName()); // depends on control dependency: [for], data = [tc] td.setTimeUnit(TimeUnit.valueOf(tc.getTimeUnit())); // depends on control dependency: [for], data = [tc] td.setValueName(tc.getValueName()); // depends on control dependency: [for], data = [tc] Threshold newThreshold = createThreshold(td); GuardConfig[] guards = tc.getGuards(); if (guards!=null && guards.length>0){ boolean hasDots = false; for (GuardConfig guard : guards ) { hasDots |= hasDots(guard.getValue()); // depends on control dependency: [for], data = [guard] } for (GuardConfig guard : guards ){ newThreshold.addGuard( hasDots ? new DoubleBarrierPassGuard(ThresholdStatus.valueOf(guard.getStatus()), Double.parseDouble(guard.getValue()), GuardedDirection.valueOf(guard.getDirection())) : new LongBarrierPassGuard(ThresholdStatus.valueOf(guard.getStatus()), Long.parseLong(guard.getValue()), GuardedDirection.valueOf(guard.getDirection())) ); // depends on control dependency: [for], data = [none] } } } } } }
public class class_name { public LocalDateTime parseLocalDateTime(String text) { InternalParser parser = requireParser(); Chronology chrono = selectChronology(null).withUTC(); // always use UTC, avoiding DST gaps DateTimeParserBucket bucket = new DateTimeParserBucket(0, chrono, iLocale, iPivotYear, iDefaultYear); int newPos = parser.parseInto(bucket, text, 0); if (newPos >= 0) { if (newPos >= text.length()) { long millis = bucket.computeMillis(true, text); if (bucket.getOffsetInteger() != null) { // treat withOffsetParsed() as being true int parsedOffset = bucket.getOffsetInteger(); DateTimeZone parsedZone = DateTimeZone.forOffsetMillis(parsedOffset); chrono = chrono.withZone(parsedZone); } else if (bucket.getZone() != null) { chrono = chrono.withZone(bucket.getZone()); } return new LocalDateTime(millis, chrono); } } else { newPos = ~newPos; } throw new IllegalArgumentException(FormatUtils.createErrorMessage(text, newPos)); } }
public class class_name { public LocalDateTime parseLocalDateTime(String text) { InternalParser parser = requireParser(); Chronology chrono = selectChronology(null).withUTC(); // always use UTC, avoiding DST gaps DateTimeParserBucket bucket = new DateTimeParserBucket(0, chrono, iLocale, iPivotYear, iDefaultYear); int newPos = parser.parseInto(bucket, text, 0); if (newPos >= 0) { if (newPos >= text.length()) { long millis = bucket.computeMillis(true, text); if (bucket.getOffsetInteger() != null) { // treat withOffsetParsed() as being true int parsedOffset = bucket.getOffsetInteger(); DateTimeZone parsedZone = DateTimeZone.forOffsetMillis(parsedOffset); chrono = chrono.withZone(parsedZone); // depends on control dependency: [if], data = [none] } else if (bucket.getZone() != null) { chrono = chrono.withZone(bucket.getZone()); // depends on control dependency: [if], data = [(bucket.getZone()] } return new LocalDateTime(millis, chrono); // depends on control dependency: [if], data = [none] } } else { newPos = ~newPos; // depends on control dependency: [if], data = [none] } throw new IllegalArgumentException(FormatUtils.createErrorMessage(text, newPos)); } }
public class class_name { public String getConfigFolder() { // check if the system property is set and return its value if (CmsStringUtil.isNotEmpty(System.getProperty(CONFIG_FOLDER_PROPERTY))) { return System.getProperty(CONFIG_FOLDER_PROPERTY); } else { return getAbsoluteRfsPathRelativeToWebInf(FOLDER_CONFIG_DEFAULT); } } }
public class class_name { public String getConfigFolder() { // check if the system property is set and return its value if (CmsStringUtil.isNotEmpty(System.getProperty(CONFIG_FOLDER_PROPERTY))) { return System.getProperty(CONFIG_FOLDER_PROPERTY); // depends on control dependency: [if], data = [none] } else { return getAbsoluteRfsPathRelativeToWebInf(FOLDER_CONFIG_DEFAULT); // depends on control dependency: [if], data = [none] } } }
public class class_name { @Override public TransportResult doDelete(URI uri) { HttpDelete request = new HttpDelete(uri); request.setHeader(apiAuthHeaderKey, getApitraryApi().getApiKey()); request.setHeader("Content-Type", contentType); request.setHeader("Accept", contentType); log.debug("DELETE " + request.getURI()); try { HttpResponse response = client.execute(request); return new HttpClientTransportResult(response); } catch (Throwable t) { throw new ApiTransportException(t); } } }
public class class_name { @Override public TransportResult doDelete(URI uri) { HttpDelete request = new HttpDelete(uri); request.setHeader(apiAuthHeaderKey, getApitraryApi().getApiKey()); request.setHeader("Content-Type", contentType); request.setHeader("Accept", contentType); log.debug("DELETE " + request.getURI()); try { HttpResponse response = client.execute(request); return new HttpClientTransportResult(response); // depends on control dependency: [try], data = [none] } catch (Throwable t) { throw new ApiTransportException(t); } // depends on control dependency: [catch], data = [none] } }
public class class_name { public int doRecordChange(FieldInfo field, int iChangeType, boolean bDisplayOption) { AnnivMaster recAnnivMaster = (AnnivMaster)this.getOwner(); if (iChangeType == DBConstants.AFTER_ADD_TYPE) { Object bookmark = recAnnivMaster.getLastModified(DBConstants.BOOKMARK_HANDLE); try { recAnnivMaster.setHandle(bookmark, DBConstants.BOOKMARK_HANDLE); Calendar calStart = ((DateTimeField)this.getCalendarControl().getField(CalendarControl.START_ANNIV_DATE)).getCalendar(); Calendar calEnd = ((DateTimeField)this.getCalendarControl().getField(CalendarControl.END_ANNIV_DATE)).getCalendar(); recAnnivMaster.addAppointments(this.getAnniversary(), calStart, calEnd); recAnnivMaster.addNew(); } catch (DBException ex) { ex.printStackTrace(); } } if (iChangeType == DBConstants.AFTER_UPDATE_TYPE) { Calendar calStart = ((DateTimeField)this.getCalendarControl().getField(CalendarControl.START_ANNIV_DATE)).getCalendar(); Calendar calEnd = ((DateTimeField)this.getCalendarControl().getField(CalendarControl.END_ANNIV_DATE)).getCalendar(); recAnnivMaster.removeAppointments(this.getAnniversary()); recAnnivMaster.addAppointments(this.getAnniversary(), calStart, calEnd); } if (iChangeType == DBConstants.AFTER_DELETE_TYPE) { recAnnivMaster.removeAppointments(this.getAnniversary()); } return super.doRecordChange(field, iChangeType, bDisplayOption); } }
public class class_name { public int doRecordChange(FieldInfo field, int iChangeType, boolean bDisplayOption) { AnnivMaster recAnnivMaster = (AnnivMaster)this.getOwner(); if (iChangeType == DBConstants.AFTER_ADD_TYPE) { Object bookmark = recAnnivMaster.getLastModified(DBConstants.BOOKMARK_HANDLE); try { recAnnivMaster.setHandle(bookmark, DBConstants.BOOKMARK_HANDLE); // depends on control dependency: [try], data = [none] Calendar calStart = ((DateTimeField)this.getCalendarControl().getField(CalendarControl.START_ANNIV_DATE)).getCalendar(); Calendar calEnd = ((DateTimeField)this.getCalendarControl().getField(CalendarControl.END_ANNIV_DATE)).getCalendar(); recAnnivMaster.addAppointments(this.getAnniversary(), calStart, calEnd); // depends on control dependency: [try], data = [none] recAnnivMaster.addNew(); // depends on control dependency: [try], data = [none] } catch (DBException ex) { ex.printStackTrace(); } // depends on control dependency: [catch], data = [none] } if (iChangeType == DBConstants.AFTER_UPDATE_TYPE) { Calendar calStart = ((DateTimeField)this.getCalendarControl().getField(CalendarControl.START_ANNIV_DATE)).getCalendar(); Calendar calEnd = ((DateTimeField)this.getCalendarControl().getField(CalendarControl.END_ANNIV_DATE)).getCalendar(); recAnnivMaster.removeAppointments(this.getAnniversary()); // depends on control dependency: [if], data = [none] recAnnivMaster.addAppointments(this.getAnniversary(), calStart, calEnd); // depends on control dependency: [if], data = [none] } if (iChangeType == DBConstants.AFTER_DELETE_TYPE) { recAnnivMaster.removeAppointments(this.getAnniversary()); // depends on control dependency: [if], data = [none] } return super.doRecordChange(field, iChangeType, bDisplayOption); } }
public class class_name { public EClass getIfcDerivedUnitElement() { if (ifcDerivedUnitElementEClass == null) { ifcDerivedUnitElementEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc2x3tc1Package.eNS_URI) .getEClassifiers().get(146); } return ifcDerivedUnitElementEClass; } }
public class class_name { public EClass getIfcDerivedUnitElement() { if (ifcDerivedUnitElementEClass == null) { ifcDerivedUnitElementEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc2x3tc1Package.eNS_URI) .getEClassifiers().get(146); // depends on control dependency: [if], data = [none] } return ifcDerivedUnitElementEClass; } }
public class class_name { private @Nullable TypeElement findParentType(TypeElement typeElement, Set<TypeElement> parents) { TypeMirror type; while (true) { type = typeElement.getSuperclass(); if (type.getKind() == TypeKind.NONE) { return null; } typeElement = (TypeElement) ((DeclaredType) type).asElement(); if (parents.contains(typeElement)) { return typeElement; } } } }
public class class_name { private @Nullable TypeElement findParentType(TypeElement typeElement, Set<TypeElement> parents) { TypeMirror type; while (true) { type = typeElement.getSuperclass(); // depends on control dependency: [while], data = [none] if (type.getKind() == TypeKind.NONE) { return null; // depends on control dependency: [if], data = [none] } typeElement = (TypeElement) ((DeclaredType) type).asElement(); // depends on control dependency: [while], data = [none] if (parents.contains(typeElement)) { return typeElement; // depends on control dependency: [if], data = [none] } } } }
public class class_name { private static RecursiveDeleteResult recursiveDeleteFiles(HdfsEnvironment hdfsEnvironment, HdfsContext context, Path directory, List<String> filePrefixes, boolean deleteEmptyDirectories) { FileSystem fileSystem; try { fileSystem = hdfsEnvironment.getFileSystem(context, directory); if (!fileSystem.exists(directory)) { return new RecursiveDeleteResult(true, ImmutableList.of()); } } catch (IOException e) { ImmutableList.Builder<String> notDeletedItems = ImmutableList.builder(); notDeletedItems.add(directory.toString() + "/**"); return new RecursiveDeleteResult(false, notDeletedItems.build()); } return doRecursiveDeleteFiles(fileSystem, directory, filePrefixes, deleteEmptyDirectories); } }
public class class_name { private static RecursiveDeleteResult recursiveDeleteFiles(HdfsEnvironment hdfsEnvironment, HdfsContext context, Path directory, List<String> filePrefixes, boolean deleteEmptyDirectories) { FileSystem fileSystem; try { fileSystem = hdfsEnvironment.getFileSystem(context, directory); // depends on control dependency: [try], data = [none] if (!fileSystem.exists(directory)) { return new RecursiveDeleteResult(true, ImmutableList.of()); // depends on control dependency: [if], data = [none] } } catch (IOException e) { ImmutableList.Builder<String> notDeletedItems = ImmutableList.builder(); notDeletedItems.add(directory.toString() + "/**"); return new RecursiveDeleteResult(false, notDeletedItems.build()); } // depends on control dependency: [catch], data = [none] return doRecursiveDeleteFiles(fileSystem, directory, filePrefixes, deleteEmptyDirectories); } }
public class class_name { public T findOne(DBObject query, DBObject fields, ReadPreference readPref) { DBCursor<T> cursor = find(query, fields).setReadPreference(readPref); if (cursor.hasNext()) { return cursor.next(); } else { return null; } } }
public class class_name { public T findOne(DBObject query, DBObject fields, ReadPreference readPref) { DBCursor<T> cursor = find(query, fields).setReadPreference(readPref); if (cursor.hasNext()) { return cursor.next(); // depends on control dependency: [if], data = [none] } else { return null; // depends on control dependency: [if], data = [none] } } }
public class class_name { public void register(Object object) { Class<?> listenerClass = object.getClass(); if(!Modifier.isPublic(listenerClass.getModifiers())){ throw new IllegalArgumentException(String.format(Locale.ENGLISH, "Event Subscriber class %s needs to be public", listenerClass.getName())); } List<SubscriberMethod> methods = new ArrayList<SubscriberMethod>(); // Do loop to traverse the class hierarchy looking for @Subscribe methods. Using // listenerClass.getMethods() seems preferable as it should include inherited public // methods, but it does not seem to work for some of the mock(listener) types used in // the tests (e.g. mock(StrategyListener.class)). do { for (Method m : listenerClass.getDeclaredMethods()) { if (m.isAnnotationPresent(com.cloudant.sync.event.Subscribe.class)) { if (!Modifier.isPublic(m.getModifiers())){ throw new IllegalArgumentException(String.format(Locale.ENGLISH, "Subscriber method %s#%s is required to be public", listenerClass.getName(), m.getName())); } Class[] params = m.getParameterTypes(); if (params.length == 1) { if(!Notification.class.isAssignableFrom(params[0])){ throw new IllegalArgumentException(String.format(Locale.ENGLISH, "Subscriber method %s#%s parameter is required to be assignable %s", listenerClass.getName(), m.getName(), Notification.class.getCanonicalName())); } methods.add(new SubscriberMethod(m, params[0])); } else { throw new IllegalArgumentException(String.format(Locale.ENGLISH, "Subscriber method %s#%s is required to have only 1 parameter", listenerClass.getName(), m.getName())); } } } } while ((listenerClass = listenerClass.getSuperclass()) != null); listeners.put(object, methods); } }
public class class_name { public void register(Object object) { Class<?> listenerClass = object.getClass(); if(!Modifier.isPublic(listenerClass.getModifiers())){ throw new IllegalArgumentException(String.format(Locale.ENGLISH, "Event Subscriber class %s needs to be public", listenerClass.getName())); } List<SubscriberMethod> methods = new ArrayList<SubscriberMethod>(); // Do loop to traverse the class hierarchy looking for @Subscribe methods. Using // listenerClass.getMethods() seems preferable as it should include inherited public // methods, but it does not seem to work for some of the mock(listener) types used in // the tests (e.g. mock(StrategyListener.class)). do { for (Method m : listenerClass.getDeclaredMethods()) { if (m.isAnnotationPresent(com.cloudant.sync.event.Subscribe.class)) { if (!Modifier.isPublic(m.getModifiers())){ throw new IllegalArgumentException(String.format(Locale.ENGLISH, "Subscriber method %s#%s is required to be public", listenerClass.getName(), m.getName())); } Class[] params = m.getParameterTypes(); if (params.length == 1) { if(!Notification.class.isAssignableFrom(params[0])){ throw new IllegalArgumentException(String.format(Locale.ENGLISH, "Subscriber method %s#%s parameter is required to be assignable %s", listenerClass.getName(), m.getName(), Notification.class.getCanonicalName())); } methods.add(new SubscriberMethod(m, params[0])); // depends on control dependency: [if], data = [none] } else { throw new IllegalArgumentException(String.format(Locale.ENGLISH, "Subscriber method %s#%s is required to have only 1 parameter", listenerClass.getName(), m.getName())); } } } } while ((listenerClass = listenerClass.getSuperclass()) != null); listeners.put(object, methods); } }
public class class_name { public static String absolute(String path, ClassLoader klassLoader, String enc) { path = normalize(path, enc); if (Strings.isEmpty(path)) return null; File f = new File(path); if (!f.exists()) { URL url = null; try { url = klassLoader.getResource(path); if (null == url) url = Thread.currentThread().getContextClassLoader().getResource(path); if (null == url) url = ClassLoader.getSystemResource(path); } catch (Throwable e) {} if (null != url) return normalize(url.getPath(), Encoding.UTF8);// 通过URL获取String,一律使用UTF-8编码进行解码 return null; } return path; } }
public class class_name { public static String absolute(String path, ClassLoader klassLoader, String enc) { path = normalize(path, enc); if (Strings.isEmpty(path)) return null; File f = new File(path); if (!f.exists()) { URL url = null; try { url = klassLoader.getResource(path); // depends on control dependency: [try], data = [none] if (null == url) url = Thread.currentThread().getContextClassLoader().getResource(path); if (null == url) url = ClassLoader.getSystemResource(path); } catch (Throwable e) {} // depends on control dependency: [catch], data = [none] if (null != url) return normalize(url.getPath(), Encoding.UTF8);// 通过URL获取String,一律使用UTF-8编码进行解码 return null; // depends on control dependency: [if], data = [none] } return path; } }
public class class_name { private Label pushSuccessors(final Label listOfLabelsToProcess) { Label newListOfLabelsToProcess = listOfLabelsToProcess; Edge outgoingEdge = outgoingEdges; while (outgoingEdge != null) { // By construction, the second outgoing edge of a basic block that ends with a jsr instruction // leads to the jsr target (see {@link #FLAG_SUBROUTINE_CALLER}). boolean isJsrTarget = (flags & Label.FLAG_SUBROUTINE_CALLER) != 0 && outgoingEdge == outgoingEdges.nextEdge; if (!isJsrTarget && outgoingEdge.successor.nextListElement == null) { // Add this successor to the list of blocks to process, if it does not already belong to a // list of labels. outgoingEdge.successor.nextListElement = newListOfLabelsToProcess; newListOfLabelsToProcess = outgoingEdge.successor; } outgoingEdge = outgoingEdge.nextEdge; } return newListOfLabelsToProcess; } }
public class class_name { private Label pushSuccessors(final Label listOfLabelsToProcess) { Label newListOfLabelsToProcess = listOfLabelsToProcess; Edge outgoingEdge = outgoingEdges; while (outgoingEdge != null) { // By construction, the second outgoing edge of a basic block that ends with a jsr instruction // leads to the jsr target (see {@link #FLAG_SUBROUTINE_CALLER}). boolean isJsrTarget = (flags & Label.FLAG_SUBROUTINE_CALLER) != 0 && outgoingEdge == outgoingEdges.nextEdge; if (!isJsrTarget && outgoingEdge.successor.nextListElement == null) { // Add this successor to the list of blocks to process, if it does not already belong to a // list of labels. outgoingEdge.successor.nextListElement = newListOfLabelsToProcess; // depends on control dependency: [if], data = [none] newListOfLabelsToProcess = outgoingEdge.successor; // depends on control dependency: [if], data = [none] } outgoingEdge = outgoingEdge.nextEdge; // depends on control dependency: [while], data = [none] } return newListOfLabelsToProcess; } }
public class class_name { @Override public List<DocumentRevs> getRevisions(String documentId, Collection<String> revisionIds, Collection<String> attsSince, boolean pullAttachmentsInline) { List<OpenRevision> openRevisions = couchClient.getDocWithOpenRevisions(documentId, revisionIds, attsSince, pullAttachmentsInline); // expect all the open revisions return ok, return error is there is any missing List<DocumentRevs> documentRevs = new ArrayList<DocumentRevs>(); for (OpenRevision openRev : openRevisions) { if (openRev instanceof OkOpenRevision) { documentRevs.add(((OkOpenRevision) openRev).getDocumentRevs()); } else { throw new RuntimeException("Missing open revision for document:" + documentId + ", revisions: " + Arrays.asList(revisionIds)); } } return documentRevs; } }
public class class_name { @Override public List<DocumentRevs> getRevisions(String documentId, Collection<String> revisionIds, Collection<String> attsSince, boolean pullAttachmentsInline) { List<OpenRevision> openRevisions = couchClient.getDocWithOpenRevisions(documentId, revisionIds, attsSince, pullAttachmentsInline); // expect all the open revisions return ok, return error is there is any missing List<DocumentRevs> documentRevs = new ArrayList<DocumentRevs>(); for (OpenRevision openRev : openRevisions) { if (openRev instanceof OkOpenRevision) { documentRevs.add(((OkOpenRevision) openRev).getDocumentRevs()); // depends on control dependency: [if], data = [none] } else { throw new RuntimeException("Missing open revision for document:" + documentId + ", revisions: " + Arrays.asList(revisionIds)); } } return documentRevs; } }
public class class_name { public String get(String key) { if(key==null)return null; int idx=0,equal=0,amp=0; while(idx>=0 && (equal = tresp.indexOf('=',idx))>=0) { amp = tresp.indexOf('&',equal); if(key.regionMatches(0, tresp, idx, equal-idx)) { return amp>=0?tresp.substring(equal+1, amp):tresp.substring(equal+1); } idx=amp+(amp>0?1:0); } return null; } }
public class class_name { public String get(String key) { if(key==null)return null; int idx=0,equal=0,amp=0; while(idx>=0 && (equal = tresp.indexOf('=',idx))>=0) { amp = tresp.indexOf('&',equal); // depends on control dependency: [while], data = [none] if(key.regionMatches(0, tresp, idx, equal-idx)) { return amp>=0?tresp.substring(equal+1, amp):tresp.substring(equal+1); // depends on control dependency: [if], data = [none] } idx=amp+(amp>0?1:0); // depends on control dependency: [while], data = [none] } return null; } }
public class class_name { public void removeProperty(final Collection<String> col, final String name) { try { String v = getProperty(col, name); if (v == null) { return; } col.remove(name + "=" + v); } catch (Throwable t) { throw new RuntimeException(t); } } }
public class class_name { public void removeProperty(final Collection<String> col, final String name) { try { String v = getProperty(col, name); if (v == null) { return; // depends on control dependency: [if], data = [none] } col.remove(name + "=" + v); // depends on control dependency: [try], data = [none] } catch (Throwable t) { throw new RuntimeException(t); } // depends on control dependency: [catch], data = [none] } }
public class class_name { public ProvisionedProductPlanDetails withProvisioningParameters(UpdateProvisioningParameter... provisioningParameters) { if (this.provisioningParameters == null) { setProvisioningParameters(new java.util.ArrayList<UpdateProvisioningParameter>(provisioningParameters.length)); } for (UpdateProvisioningParameter ele : provisioningParameters) { this.provisioningParameters.add(ele); } return this; } }
public class class_name { public ProvisionedProductPlanDetails withProvisioningParameters(UpdateProvisioningParameter... provisioningParameters) { if (this.provisioningParameters == null) { setProvisioningParameters(new java.util.ArrayList<UpdateProvisioningParameter>(provisioningParameters.length)); // depends on control dependency: [if], data = [none] } for (UpdateProvisioningParameter ele : provisioningParameters) { this.provisioningParameters.add(ele); // depends on control dependency: [for], data = [ele] } return this; } }
public class class_name { synchronized boolean remove(BlockInfo blockInfo, int priLevel) { INodeFile fileINode = blockInfo.getINode(); if (priLevel == QUEUE_WITH_CORRUPT_BLOCKS && fileINode != null && fileINode.getStorageType().equals(StorageType.RAID_STORAGE)) { RaidCodec codec = ((INodeRaidStorage) fileINode.getStorage()).getCodec(); return raidQueue.remove(blockInfo, codec); } if(priLevel >= 0 && priLevel < LEVEL && priorityQueues.get(priLevel).remove(blockInfo)) { if (NameNode.stateChangeLog.isDebugEnabled()) { NameNode.stateChangeLog.debug( "BLOCK* NameSystem.UnderReplicationBlock.remove: " + "Removing block " + blockInfo + " from priority queue "+ priLevel); } return true; } else { for(int i=0; i<LEVEL; i++) { if(i!=priLevel && priorityQueues.get(i).remove(blockInfo)) { if (NameNode.stateChangeLog.isDebugEnabled()) { NameNode.stateChangeLog.debug( "BLOCK* NameSystem.UnderReplicationBlock.remove: " + "Removing block " + blockInfo + " from priority queue "+ i); } return true; } } } return false; } }
public class class_name { synchronized boolean remove(BlockInfo blockInfo, int priLevel) { INodeFile fileINode = blockInfo.getINode(); if (priLevel == QUEUE_WITH_CORRUPT_BLOCKS && fileINode != null && fileINode.getStorageType().equals(StorageType.RAID_STORAGE)) { RaidCodec codec = ((INodeRaidStorage) fileINode.getStorage()).getCodec(); return raidQueue.remove(blockInfo, codec); // depends on control dependency: [if], data = [none] } if(priLevel >= 0 && priLevel < LEVEL && priorityQueues.get(priLevel).remove(blockInfo)) { if (NameNode.stateChangeLog.isDebugEnabled()) { NameNode.stateChangeLog.debug( "BLOCK* NameSystem.UnderReplicationBlock.remove: " + "Removing block " + blockInfo + " from priority queue "+ priLevel); // depends on control dependency: [if], data = [none] } return true; // depends on control dependency: [if], data = [none] } else { for(int i=0; i<LEVEL; i++) { if(i!=priLevel && priorityQueues.get(i).remove(blockInfo)) { if (NameNode.stateChangeLog.isDebugEnabled()) { NameNode.stateChangeLog.debug( "BLOCK* NameSystem.UnderReplicationBlock.remove: " + "Removing block " + blockInfo + " from priority queue "+ i); // depends on control dependency: [if], data = [none] } return true; // depends on control dependency: [if], data = [none] } } } return false; } }
public class class_name { public static int findUnlinked(int pos, int end, DBIDArrayIter ix, PointerHierarchyRepresentationBuilder builder) { while(pos < end) { if(!builder.isLinked(ix.seek(pos))) { return pos; } ++pos; } return -1; } }
public class class_name { public static int findUnlinked(int pos, int end, DBIDArrayIter ix, PointerHierarchyRepresentationBuilder builder) { while(pos < end) { if(!builder.isLinked(ix.seek(pos))) { return pos; // depends on control dependency: [if], data = [none] } ++pos; // depends on control dependency: [while], data = [none] } return -1; } }
public class class_name { @Override public Map<String, Object> getValues(double evaluationTime, Model model) { Map<String, Object> result = new HashMap<>(); try { double value = getValue((CharacteristicFunctionModel) model); result.put("value", value); } catch (CalculationException e) { result.put("exception", e); } return result; } }
public class class_name { @Override public Map<String, Object> getValues(double evaluationTime, Model model) { Map<String, Object> result = new HashMap<>(); try { double value = getValue((CharacteristicFunctionModel) model); result.put("value", value); // depends on control dependency: [try], data = [none] } catch (CalculationException e) { result.put("exception", e); } // depends on control dependency: [catch], data = [none] return result; } }
public class class_name { private void waitForStarted() { debug("GuestNode#waitForStarted(): Waiting for other clusters started"); while (true) { boolean othersStarted = true; for (Object key : clustersProperties.keySet()) { String clusterName = (String) key; Long startedAt = region.get(createStartedAtKey(clusterName)); debug("GuestNode#waitForStarted(): Checking startedAt: startedAt = " + startedAt + ", processingStartedAt = " + processingStartedAt); if ((startedAt == null) || (startedAt.longValue() < processingStartedAt)) { othersStarted = false; break; } } if (othersStarted) { break; } try { TimeUnit.MILLISECONDS.sleep(CHECK_PERIOD); } catch (InterruptedException e) { } } debug("GuestNode#waitForStarted(): Other clusters started"); } }
public class class_name { private void waitForStarted() { debug("GuestNode#waitForStarted(): Waiting for other clusters started"); while (true) { boolean othersStarted = true; for (Object key : clustersProperties.keySet()) { String clusterName = (String) key; Long startedAt = region.get(createStartedAtKey(clusterName)); debug("GuestNode#waitForStarted(): Checking startedAt: startedAt = " + startedAt + ", processingStartedAt = " + processingStartedAt); // depends on control dependency: [for], data = [none] if ((startedAt == null) || (startedAt.longValue() < processingStartedAt)) { othersStarted = false; // depends on control dependency: [if], data = [none] break; } } if (othersStarted) { break; } try { TimeUnit.MILLISECONDS.sleep(CHECK_PERIOD); // depends on control dependency: [try], data = [none] } catch (InterruptedException e) { } // depends on control dependency: [catch], data = [none] } debug("GuestNode#waitForStarted(): Other clusters started"); } }