text:
package org.apache.felix.sigil.eclipse.model.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.jar.JarEntry;
import java.util.jar.JarInputStream;
import java.util.regex.Pattern;

import org.apache.felix.sigil.common.config.Resource;
import org.apache.felix.sigil.common.model.IModelElement;
import org.apache.felix.sigil.common.model.IModelWalker;
import org.apache.felix.sigil.common.model.ModelElementFactory;
import org.apache.felix.sigil.common.model.eclipse.ISigilBundle;
import org.apache.felix.sigil.common.model.osgi.IBundleModelElement;
import org.apache.felix.sigil.common.model.osgi.IPackageExport;
import org.apache.felix.sigil.common.model.osgi.IPackageImport;
import org.apache.felix.sigil.common.model.osgi.IRequiredBundle;
import org.apache.felix.sigil.common.osgi.VersionRange;
import org.apache.felix.sigil.common.repository.IRepositoryManager;
import org.apache.felix.sigil.common.repository.IResolution;
import org.apache.felix.sigil.common.repository.ResolutionConfig;
import org.apache.felix.sigil.common.repository.ResolutionException;
import org.apache.felix.sigil.eclipse.PathUtil;
import org.apache.felix.sigil.eclipse.SigilCore;
import org.apache.felix.sigil.eclipse.model.project.ISigilProjectModel;
import org.apache.felix.sigil.eclipse.progress.ProgressAdapter;
import org.apache.felix.sigil.eclipse.repository.ResolutionMonitorAdapter;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.content.IContentDescription;
import org.eclipse.core.runtime.content.IContentType;
import org.eclipse.core.runtime.content.IContentTypeManager;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.jdt.core.IAccessRule;
import org.eclipse.jdt.core.IAnnotation;
import org.eclipse.jdt.core.IClassFile;
import org.eclipse.jdt.core.IClasspathAttribute;
import org.eclipse.jdt.core.IClasspathEntry;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IField;
import org.eclipse.jdt.core.IImportDeclaration;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaModel;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.ILocalVariable;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.IParent;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.ITypeHierarchy;
import org.eclipse.jdt.core.ITypeRoot;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.Signature;
import org.osgi.framework.Version;

/**
 * @author dave
 *
 */
public class JavaHelper
{

    public static final IAccessRule DENY_RULE = JavaCore.newAccessRule(new Path("**"),
        IAccessRule.K_NON_ACCESSIBLE | IAccessRule.IGNORE_IF_BETTER);

    public static final IAccessRule ALLOW_ALL_RULE = JavaCore.newAccessRule(
        new Path("**"), IAccessRule.K_ACCESSIBLE);

    private static Map<String, Collection<IClasspathEntry>> entryCache = new HashMap<String, Collection<IClasspathEntry>>();

    public static Collection<IClasspathEntry> findClasspathEntries(ISigilBundle bundle)
    {
        LinkedList<IClasspathEntry> cp = new LinkedList<IClasspathEntry>();

        ISigilProjectModel sp = bundle.getAncestor(ISigilProjectModel.class);

        if (sp != null)
        {
            IJavaProject p = sp.getJavaModel();

            for (String enc : bundle.getClasspathEntrys())
            {
                IClasspathEntry e = p.decodeClasspathEntry(enc);
                if (e != null)
                {
                    cp.add(e);
                }
            }
        }

        return cp;
    }

    public static Collection<ICompilationUnit> findCompilationUnits(
        ISigilProjectModel project) throws JavaModelException
    {
        LinkedList<ICompilationUnit> ret = new LinkedList<ICompilationUnit>();

        IJavaProject java = project.getJavaModel();
        for (IClasspathEntry cp : findClasspathEntries(project.getBundle()))
        {
            IPackageFragmentRoot[] roots = java.findPackageFragmentRoots(cp);
            for (IPackageFragmentRoot rt : roots)
            {
                for (IJavaElement j : rt.getChildren())
                {
                    IPackageFragment p = (IPackageFragment) j;
                    ICompilationUnit[] units = p.getCompilationUnits();
                    for (ICompilationUnit u : units)
                    {
                        ret.add(u);
                    }
                }
            }
        }

        return ret;
    }

    /**
     * @param project
     * @param packageName
     * @return
     */
    public static Collection<IPackageExport> findExportsForPackage(
        ISigilProjectModel project, final String packageName)
    {
        final LinkedList<IPackageExport> results = new LinkedList<IPackageExport>();

        project.getRepositoryManager().visit(new IModelWalker()
        {
            public boolean visit(IModelElement element)
            {
                if (element instanceof IPackageExport)
                {
                    IPackageExport e = (IPackageExport) element;
                    if (e.getPackageName().equals(packageName))
                    {
                        results.add(e);
                    }
                }
                return true;
            }
        });

        return results;
    }

    public static String[] findUses(String packageName, ISigilProjectModel projectModel)
        throws CoreException
    {
        ArrayList<String> uses = new ArrayList<String>();

        for (final String dependency : findPackageDependencies(packageName, projectModel))
        {
            if (!dependency.equals(packageName))
            {
                final boolean[] found = new boolean[1];

                projectModel.visit(new IModelWalker()
                {

                    public boolean visit(IModelElement element)
                    {
                        if (element instanceof IPackageImport)
                        {
                            IPackageImport pi = (IPackageImport) element;
                            if (pi.getPackageName().equals(dependency))
                            {
                                found[0] = true;
                            }
                        }
                        return !found[0];
                    }
                });

                if (found[0])
                {
                    uses.add(dependency);
                }
            }
        }

        return uses.toArray(new String[uses.size()]);
    }

    private static String[] findPackageDependencies(String packageName,
        ISigilProjectModel projectModel) throws CoreException
    {
        HashSet<String> imports = new HashSet<String>();

        IPackageFragment p = (IPackageFragment) projectModel.getJavaModel().findElement(
            new Path(packageName.replace('.', '/')));

        if (p == null)
        {
            throw SigilCore.newCoreException("Unknown package " + packageName, null);
        }
        for (ICompilationUnit cu : p.getCompilationUnits())
        {
            scanImports(cu, imports);
        }
        for (IClassFile cf : p.getClassFiles())
        {
            scanImports(cf, imports);
        }

        return imports.toArray(new String[imports.size()]);
    }

    /**
     * @param project
     * @param monitor
     * @return
     */
    public static List<IPackageImport> findRequiredImports(ISigilProjectModel project,
        IProgressMonitor monitor)
    {
        LinkedList<IPackageImport> imports = new LinkedList<IPackageImport>();
        Set<String> names = findJavaImports(project, monitor);
        if ( !monitor.isCanceled() ) {
            for (String packageName : names)
            {
                if (!ProfileManager.isBootDelegate(project, packageName))
                { // these must come from boot classloader
                    try
                    {
                        if (!project.isInClasspath(packageName, monitor))
                        {
                            Collection<IPackageExport> exports = findExportsForPackage(
                                project, packageName);
                            if (!exports.isEmpty())
                            {
                                imports.add(select(exports));
                            }
                        }
                    }
                    catch (CoreException e)
                    {
                        SigilCore.error("Failed to check classpath", e);
                    }
                }
            }
        }
        return imports;
    }

    /**
     * @param project
     * @param monitor
     * @return
     */
    public static Collection<IModelElement> findUnusedReferences(
        final ISigilProjectModel project, final IProgressMonitor monitor)
    {
        final LinkedList<IModelElement> unused = new LinkedList<IModelElement>();

        final Set<String> packages = findJavaImports(project, monitor);

        if (!monitor.isCanceled()) {
            project.visit(new IModelWalker()
            {
                public boolean visit(IModelElement element)
                {
                    if (element instanceof IPackageImport)
                    {
                        IPackageImport pi = (IPackageImport) element;
                        if (!packages.contains(pi.getPackageName()))
                        {
                            unused.add(pi);
                        }
                    }
                    else if (element instanceof IRequiredBundle)
                    {
                        IRequiredBundle rb = (IRequiredBundle) element;
                        IRepositoryManager manager = project.getRepositoryManager();
                        ResolutionConfig config = new ResolutionConfig(
                            ResolutionConfig.INCLUDE_OPTIONAL
                                | ResolutionConfig.IGNORE_ERRORS);
                        try
                        {
                            IResolution r = manager.getBundleResolver().resolve(rb, config,
                                new ResolutionMonitorAdapter(monitor));
                            ISigilBundle bundle = r.getProvider(rb);
                            boolean found = false;
                            for (IPackageExport pe : bundle.getBundleInfo().getExports())
                            {
                                if (packages.contains(pe.getPackageName()))
                                {
                                    found = true;
                                    break;
                                }
                            }

                            if (!found)
                            {
                                unused.add(rb);
                            }
                        }
                        catch (ResolutionException e)
                        {
                            SigilCore.error("Failed to resolve " + rb, e);
                        }
                    }
                    return !monitor.isCanceled();
                }
            });
        }

        return unused;
    }

    public static Collection<IClasspathEntry> resolveClasspathEntrys(
        ISigilProjectModel sigil, IProgressMonitor monitor) throws CoreException
    {
        if (monitor == null)
        {
            monitor = Job.getJobManager().createProgressGroup();
            monitor.beginTask("Resolving classpath for " + sigil.getSymbolicName(), 2);
        }

        ArrayList<IClasspathEntry> entries = new ArrayList<IClasspathEntry>();

        ResolutionConfig config = new ResolutionConfig(ResolutionConfig.INCLUDE_OPTIONAL
            | ResolutionConfig.IGNORE_ERRORS | ResolutionConfig.INDEXED_ONLY
            | ResolutionConfig.LOCAL_ONLY | ResolutionConfig.COMPILE_TIME);

        IResolution resolution;
        try
        {
            resolution = sigil.getRepositoryManager().getBundleResolver().resolve(
                sigil, config, new ResolutionMonitorAdapter(monitor));
        }
        catch (ResolutionException e)
        {
            throw SigilCore.newCoreException("Failed to resolve dependencies", e);
        }

        monitor.worked(1);

        Set<ISigilBundle> bundles = resolution.getBundles();
        for (ISigilBundle bundle : bundles)
        {
            if (!sigil.getSymbolicName().equals(bundle.getBundleInfo().getSymbolicName()))
            { // discard self reference...
                List<IModelElement> matched = resolution.getMatchedRequirements(bundle);
                for (IClasspathEntry cpe : buildClassPathEntry(sigil, bundle, bundles,
                    matched, monitor))
                {
                    entries.add(cpe);
                }
            }
        }

        Collections.sort(entries, new Comparator<IClasspathEntry>()
        {
            public int compare(IClasspathEntry o1, IClasspathEntry o2)
            {
                return o1.toString().compareTo(o2.toString());
            }
        });

        monitor.worked(1);
        monitor.done();

        return entries;
    }

    private static Collection<IClasspathEntry> buildClassPathEntry(
        ISigilProjectModel project, ISigilBundle provider, Set<ISigilBundle> all,
        List<IModelElement> requirements, IProgressMonitor monitor) throws CoreException
    {
        IAccessRule[] rules = buildAccessRules(project, provider, all, requirements);
        IClasspathAttribute[] attrs = new IClasspathAttribute[0];

        ISigilProjectModel other = provider.getAncestor(ISigilProjectModel.class);

        try
        {
            if (other == null)
            {
                provider.synchronize(new ProgressAdapter(monitor));
                return newBundleEntry(provider, rules, attrs, false);
            }
            else
            {
                return newProjectEntry(other, rules, attrs, false);
            }
        }
        catch (IOException e)
        {
            throw SigilCore.newCoreException("Failed to synchronize " + provider, e);
        }
    }

    private static Collection<IClasspathEntry> newProjectEntry(ISigilProjectModel n,
        IAccessRule[] rules, IClasspathAttribute[] attributes, boolean export)
        throws CoreException
    {
        ArrayList<IClasspathEntry> entries = new ArrayList<IClasspathEntry>();
        entries.add(JavaCore.newProjectEntry(n.getProject().getFullPath(), rules, false,
            attributes, export));
        for (IClasspathEntry e : n.getJavaModel().getRawClasspath())
        {
            String encoded = n.getJavaModel().encodeClasspathEntry(e);
            if ( n.getBundle().getClasspathEntrys().contains(encoded) ) {
                switch (e.getEntryKind())
                {
                    case IClasspathEntry.CPE_LIBRARY:
                        entries.add(JavaCore.newLibraryEntry(e.getPath(),
                            e.getSourceAttachmentPath(), e.getSourceAttachmentRootPath(),
                            rules, attributes, export));
                        break;
                    case IClasspathEntry.CPE_VARIABLE:
                        IPath path = JavaCore.getResolvedVariablePath(e.getPath());
                        if (path != null)
                        {
                            IPath spath = e.getSourceAttachmentPath();
                            if (spath != null) {
                                spath = JavaCore.getResolvedVariablePath(spath);
                            }

                            entries.add(JavaCore.newLibraryEntry(path,
                                spath, e.getSourceAttachmentRootPath(),
                                rules, attributes, export));
                        }
                        break;
                }
            }
        }

        return entries;
    }

    private static Collection<IClasspathEntry> newBundleEntry(ISigilBundle bundle,
        IAccessRule[] rules, IClasspathAttribute[] attributes, boolean exported)
        throws CoreException
    {
        String name = bundle.getBundleInfo().getSymbolicName();

        if (bundle.getBundleInfo().getVersion() != null)
        {
            name += "_version_" + bundle.getBundleInfo().getVersion();
        }

        String cacheName = name + rules.toString();

        Collection<IClasspathEntry> entries = null;

        synchronized (entryCache)
        {
            entries = entryCache.get(cacheName);

            if (entries == null)
            {
                IPath path = PathUtil.newPathIfExists(bundle.getLocation());

                if (path == null)
                {
                    SigilCore.error("Found null path for " + bundle.getSymbolicName());
                    entries = Collections.emptyList();
                }
                else
                {
                    entries = buildEntries(path, name, bundle, rules, attributes,
                        exported);
                }

                entryCache.put(cacheName, entries);
            }
        }

        return entries;
    }

    private static IPath bundleCache = SigilCore.getDefault().getStateLocation().append(
        "bundle-cache");

    public static boolean isCachedBundle(String bp)
    {
        return bp.startsWith(bundleCache.toOSString());
    }

    private static Collection<IClasspathEntry> buildEntries(IPath path, String name,
        ISigilBundle bundle, IAccessRule[] rules, IClasspathAttribute[] attributes,
        boolean exported) throws CoreException
    {
        if (path.toFile().isDirectory())
        {
            throw SigilCore.newCoreException("Bundle location cannot be a directory",
                null);
        }
        else
        {
            // ok it's a jar could contain libs etc
            try
            {
                IPath cache = bundleCache.append(name);
                Collection<String> classpath = bundle.getBundleInfo().getClasspaths();
                ArrayList<IClasspathEntry> entries = new ArrayList<IClasspathEntry>(
                    classpath.size());
                IPath source = PathUtil.newPathIfExists(bundle.getSourcePathLocation());
                IPath rootPath = PathUtil.newPathIfNotNull(bundle.getSourceRootPath());

                if (source != null && !source.toFile().exists())
                {
                    source = null;
                }

                if (!classpath.isEmpty())
                {
                    unpack(cache, bundle, classpath);
                    for (String cp : classpath)
                    {
                        IPath p = ".".equals(cp) ? path : cache.append(cp);
                        if (p.toFile().exists())
                        {
                            IClasspathEntry e = JavaCore.newLibraryEntry(p, source,
                                rootPath, rules, attributes, exported);
                            entries.add(e);
                        }
                    }
                }
                else
                { // default classpath is .
                    IClasspathEntry e = JavaCore.newLibraryEntry(path, source, rootPath,
                        rules, attributes, exported);
                    entries.add(e);
                }
                return entries;
            }
            catch (IOException e)
            {
                throw SigilCore.newCoreException("Failed to unpack bundle", e);
            }
        }
    }

    private static HashMap<IPath, Collection<String>> unpacked = new HashMap<IPath, Collection<String>>();

    private static synchronized void unpack(IPath cache, ISigilBundle bundle,
        Collection<String> classpath) throws IOException
    {
        Collection<String> check = unpacked.get(cache);

        if (check == null || !check.equals(classpath))
        {
            if (classpath.size() == 1 && classpath.contains("."))
            {
                unpacked.put(cache, classpath);
            }
            else
            {
                // trim . from path to avoid check later in inClasspath
                check = new HashSet<String>(classpath);
                check.remove(".");

                File dir = createEmptyDir(cache);
                FileInputStream fin = null;
                try
                {
                    fin = new FileInputStream(bundle.getLocation());
                    JarInputStream in = new JarInputStream(fin);
                    JarEntry entry;
                    while ((entry = in.getNextJarEntry()) != null)
                    {
                        if (inClasspath(check, entry))
                        {
                            File f = new File(dir, entry.getName());
                            if (entry.isDirectory())
                            {
                                createDir(f);
                            }
                            else
                            {
                                try
                                {
                                    File p = f.getParentFile();
                                    createDir(p);
                                    streamTo(in, f);
                                }
                                catch (RuntimeException e)
                                {
                                    SigilCore.error("Failed to unpack " + entry, e);
                                }
                            }
                        }
                    }
                    unpacked.put(cache, classpath);
                }
                finally
                {
                    if (fin != null)
                    {
                        fin.close();
                    }
                }
            }
        }
    }

    /**
     * @param classpath
     * @param entry
     * @return
     */
    private static boolean inClasspath(Collection<String> classpath, JarEntry entry)
    {
        for (String s : classpath)
        {
            if (entry.getName().startsWith(s))
            {
                return true;
            }
        }
        return false;
    }

    private static void createDir(File p) throws IOException
    {
        if (!p.exists())
        {
            if (!p.mkdirs())
                throw new IOException("Failed to create directory " + p);
        }
    }

    private static void streamTo(InputStream in, File f) throws IOException
    {
        FileOutputStream fos = new FileOutputStream(f);
        try
        {
            byte[] buf = new byte[1024];
            for (;;)
            {
                int r = in.read(buf);

                if (r == -1)
                    break;

                fos.write(buf, 0, r);
            }

            fos.flush();
        }
        finally
        {
            try
            {
                fos.close();
            }
            catch (IOException e)
            {
                SigilCore.error("Failed to close stream", e);
            }
        }
    }

    private static File createEmptyDir(IPath cache)
    {
        File dir = cache.toFile();
        if (dir.exists())
        {
            deleteAll(dir);
        }

        dir.mkdirs();
        return dir;
    }

    private static void deleteAll(File file)
    {
        File[] sub = file.listFiles();
        if (sub != null)
        {
            for (File f : sub)
            {
                deleteAll(f);
            }
        }
        file.delete();
    }

    private static IAccessRule[] buildAccessRules(ISigilProjectModel project,
        ISigilBundle bundle, Set<ISigilBundle> all, List<IModelElement> requirements)
        throws JavaModelException
    {
        ArrayList<IAccessRule> rules = new ArrayList<IAccessRule>();

        for (IModelElement e : requirements)
        {
            if (e instanceof IRequiredBundle)
            {
                IRequiredBundle host = project.getBundle().getBundleInfo().getFragmentHost();
                if (host != null)
                {
                    if (host.equals(e))
                    {
                        return new IAccessRule[] { ALLOW_ALL_RULE };
                    }
                    else
                    {
                        return buildExportRules(bundle, all, requirements);
                    }
                }
                else
                {
                    return buildExportRules(bundle, all, requirements);
                }
            }
            else if (e instanceof IPackageImport)
            {
                IPackageImport pi = (IPackageImport) e;
                String pckg = pi.getPackageName();
                HashSet<String> pckgs = new HashSet<String>();
                pckgs.add(pckg);
                //findIndirectReferences(pckgs, pckg, project.getJavaModel(), project.getJavaModel());

                for (String p : pckgs)
                {
                    rules.add(newPackageAccess(p));
                }
            }
        }

        rules.add(DENY_RULE);

        return rules.toArray(new IAccessRule[rules.size()]);
    }

    private static IAccessRule[] buildExportRules(ISigilBundle bundle,
        Set<ISigilBundle> all, List<IModelElement> requirements)
    {
        Set<IPackageExport> ex = mergeExports(bundle, all, requirements);

        IAccessRule[] rules = new IAccessRule[ex.size() + 1];

        Iterator<IPackageExport> iter = ex.iterator();
        for (int i = 0; i < rules.length - 1; i++)
        {
            IPackageExport p = iter.next();
            rules[i] = JavaCore.newAccessRule(new Path(p.getPackageName().replace('.',
                '/')).append("*"), IAccessRule.K_ACCESSIBLE);
        }

        rules[rules.length - 1] = DENY_RULE;

        return rules;
    }

    private static Set<IPackageExport> mergeExports(ISigilBundle bundle,
        Set<ISigilBundle> all, List<IModelElement> requirements)
    {
        IBundleModelElement headers = bundle.getBundleInfo();
        // FIXME treeset as PackageExport does not implement equals/hashCode
        TreeSet<IPackageExport> exports = new TreeSet<IPackageExport>(
            headers.getExports());
        IRequiredBundle host = headers.getFragmentHost();
        if (host != null)
        {
            for (ISigilBundle b : all)
            {
                if (host.accepts(b.getBundleCapability()))
                {
                    exports.addAll(b.getBundleInfo().getExports());
                    break;
                }
            }
        }
        return exports;
    }

    /*
     * Searches for C (and D, E, etc) in case:
     * A extends B extends C where A, B and C are in different packages and A is in this bundle
     * and B and C are in one or more external bundles
     */
    private static void findIndirectReferences(Set<String> indirect, String pckg,
        IParent parent, IJavaProject p) throws JavaModelException
    {
        for (IJavaElement e : parent.getChildren())
        {
            boolean skip = false;
            switch (e.getElementType())
            {
                case IJavaElement.PACKAGE_FRAGMENT_ROOT:
                    IPackageFragmentRoot rt = (IPackageFragmentRoot) e;
                    IClasspathEntry ce = rt.getRawClasspathEntry();
                    IPath path = ce.getPath();
                    skip = "org.eclipse.jdt.launching.JRE_CONTAINER".equals(path.toString());
                    break;
                case IJavaElement.CLASS_FILE:
                    IClassFile cf = (IClassFile) e;
                    if (cf.getElementName().startsWith(pckg))
                    {
                        findIndirectReferences(indirect,
                            findPackage(cf.getType().getSuperclassName()), p, p);
                    }
                    break;
                case IJavaElement.COMPILATION_UNIT:
                    ICompilationUnit cu = (ICompilationUnit) e;
                    break;
            }

            if (!skip && e instanceof IParent)
            {
                IParent newParent = (IParent) e;
                findIndirectReferences(indirect, pckg, newParent, p);
            }
        }
    }

    private static IAccessRule newPackageAccess(String packageName)
    {
        return JavaCore.newAccessRule(
            new Path(packageName.replace('.', '/')).append("*"), IAccessRule.K_ACCESSIBLE);
    }

    private static Set<String> findJavaImports(ISigilProjectModel project,
        IProgressMonitor monitor)
    {
        Set<String> imports = new HashSet<String>();

        findJavaModelImports(project, imports, monitor);
        if ( !monitor.isCanceled() ) {
            findTextImports(project, imports, monitor);
        }

        return imports;
    }

    private static void findTextImports(ISigilProjectModel project, Set<String> imports,
        IProgressMonitor monitor)
    {
        IContentTypeManager contentTypeManager = Platform.getContentTypeManager();
        IContentType txt = contentTypeManager.getContentType("org.eclipse.core.runtime.text");
        for (Resource p : project.getBundle().getSourcePaths())
        {
            IFile f = project.getProject().getFile(p.getLocalFile());
            if (f.exists())
            {
                try
                {
                    IContentDescription desc = f.getContentDescription();
                    if (desc != null)
                    {
                        IContentType type = desc.getContentType();
                        if (type != null)
                        {
                            if (type.isKindOf(txt))
                            {
                                parseText(f, imports);
                            }
                        }
                    }
                }
                catch (CoreException e)
                {
                    SigilCore.error("Failed to parse text file " + f, e);
                }
            }
        }
    }

    private static void findJavaModelImports(ISigilProjectModel project,
        Set<String> imports, IProgressMonitor monitor)
    {
        try
        {
            for (IPackageFragment root : project.getJavaModel().getPackageFragments())
            {
                if ( monitor.isCanceled() ) {
                    return;
                }

                IPackageFragmentRoot rt = (IPackageFragmentRoot) root.getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT);

                if (isInClassPath(project, rt))
                {
                    for (ICompilationUnit cu : root.getCompilationUnits())
                    {
                        scanImports(cu, imports);
                    }

                    for (IClassFile cf : root.getClassFiles())
                    {
                        scanImports(cf, imports);
                    }
                }
            }
        }
        catch (JavaModelException e)
        {
            SigilCore.error("Failed to parse java model", e);
        }
    }

    // matches word.word.word.word.Word
    private static final Pattern JAVA_CLASS_PATTERN = Pattern.compile("((\\w*\\.\\w*)+?)\\.[A-Z]\\w*");

    private static void parseText(IFile f, Set<String> imports) throws CoreException
    {
        for (String result : Grep.grep(JAVA_CLASS_PATTERN, f))
        {
            findImport(result, imports);
        }
    }

    private static boolean isInClassPath(ISigilProjectModel project,
        IPackageFragmentRoot rt) throws JavaModelException
    {
        String path = encode(project, rt.getRawClasspathEntry());
        return project.getBundle().getClasspathEntrys().contains(path);
    }

    private static String encode(ISigilProjectModel project, IClasspathEntry cp)
    {
        return project.getJavaModel().encodeClasspathEntry(cp).trim();
    }

    private static void scanImports(IParent parent, Set<String> imports)
        throws JavaModelException
    {
        for (IJavaElement e : parent.getChildren())
        {
            switch (e.getElementType())
            {
                case IJavaElement.TYPE:
                    handleType((IType) e, imports);
                    break;
                case IJavaElement.IMPORT_DECLARATION:
                    handleImport((IImportDeclaration) e, imports);
                    break;
                case IJavaElement.FIELD:
                    handleField((IField) e, imports);
                    break;
                case IJavaElement.LOCAL_VARIABLE:
                    handleLocalVariable((ILocalVariable) e, imports);
                    break;
                case IJavaElement.ANNOTATION:
                    handleAnnotation((IAnnotation) e, imports);
                    break;
                case IJavaElement.METHOD:
                    handleMethod((IMethod) e, imports);
                    break;
                default:
                    // no action
                    break;
            }

            if (e instanceof IParent)
            {
                scanImports((IParent) e, imports);
            }
        }
    }

    private static void handleType(IType e, Set<String> imports)
        throws JavaModelException
    {
        findImportFromType(e.getSuperclassTypeSignature(), imports);
        for (String sig : e.getSuperInterfaceTypeSignatures())
        {
            findImportFromType(sig, imports);
        }
        //findImportsForSuperTypes(e, imports);
    }

    /*private static void findImportsForSuperTypes(IType e, Set<String> imports) throws JavaModelException {
    	IJavaProject project = (IJavaProject) e.getAncestor(IJavaModel.JAVA_PROJECT);
    	LinkedList<String> types = new LinkedList<String>();
    	types.add( decodeSignature(e.getSuperclassTypeSignature()) );
    	for ( String sig : e.getSuperInterfaceTypeSignatures() ) {
    		types.add( decodeSignature(sig) );
    	}

    	for ( IPackageFragmentRoot root : project.getPackageFragmentRoots() ) {
    		// only need to search binary files for inheritance as source will automatically be searched
    		if ( root.getKind() == IPackageFragmentRoot.K_BINARY ) {
    			for ( String t : types ) {
    				String pac = findPackage(t);
    				if ( pac != null ) {
    					IPackageFragment fragment = root.getPackageFragment(pac);
    					if ( fragment != null ) {
    						IClassFile c = fragment.getClassFile(findClass(t));
    						if ( c != null ) {
    							findImportsForSuperTypes(c.getType(), imports);
    						}
    					}
    				}
    			}
    		}
    	}
    } */

    private static void handleMethod(IMethod e, Set<String> imports)
        throws JavaModelException
    {
        findImportFromType(e.getReturnType(), imports);

        for (String param : e.getParameterTypes())
        {
            findImportFromType(param, imports);
        }

        for (String ex : e.getExceptionTypes())
        {
            findImportFromType(ex, imports);
        }
    }

    private static void handleAnnotation(IAnnotation e, Set<String> imports)
    {
        findImport(e.getElementName(), imports);
    }

    private static void handleLocalVariable(ILocalVariable e, Set<String> imports)
    {
        findImportFromType(e.getTypeSignature(), imports);
    }

    private static void handleField(IField e, Set<String> imports)
        throws IllegalArgumentException, JavaModelException
    {
        findImportFromType(Signature.getElementType(e.getTypeSignature()), imports);
    }

    private static void handleImport(IImportDeclaration id, Set<String> imports)
    {
        findImport(id.getElementName(), imports);
    }

    private static void findImportFromType(String type, Set<String> imports)
    {
        String element = decodeSignature(type);
        findImport(element, imports);
    }

    private static String decodeSignature(String type)
    {
        return decodeSignature(type, false);
    }

    private static String decodeSignature(String type, boolean resolve)
    {
        if (type == null)
        {
            return null;
        }

        if (type.length() > 0)
        {
            switch (type.charAt(0))
            {
                case Signature.C_ARRAY:
                    return decodeSignature(type.substring(1));
                case Signature.C_UNRESOLVED:
                    return resolve ? resolve(type.substring(1, type.length() - 1)) : null;
                case Signature.C_RESOLVED:
                    return type.substring(1);
            }
        }
        return type;
    }

    private static String resolve(String substring)
    {
        // TODO Auto-generated method stub
        return null;
    }

    private static void findImport(String clazz, Set<String> imports)
    {
        String packageName = findPackage(clazz);
        if (packageName != null)
        {
            imports.add(packageName);
        }
    }

    private static String findPackage(String clazz)
    {
        if (clazz == null)
            return null;
        int pos = clazz.lastIndexOf('.');
        return pos == -1 ? null : clazz.substring(0, pos);
    }

    private static String findClass(String clazz)
    {
        if (clazz == null)
            return null;
        int pos = clazz.lastIndexOf('.');
        return pos == -1 ? null : clazz.substring(pos + 1);
    }

    private static IPackageImport select(Collection<IPackageExport> proposals)
    {
        IPackageExport pe = null;

        for (IPackageExport check : proposals)
        {
            if (pe == null || check.getVersion().compareTo(pe.getVersion()) > 0)
            {
                pe = check;
            }
        }

        String packageName = pe.getPackageName();

        Version version = pe.getVersion();
        VersionRange versions = ModelHelper.getDefaultRange(version);

        IPackageImport pi = ModelElementFactory.getInstance().newModelElement(
            IPackageImport.class);
        pi.setPackageName(packageName);
        pi.setVersions(versions);

        return pi;
    }

    public static Iterable<IJavaElement> findTypes(IParent parent, int... type)
        throws JavaModelException
    {
        LinkedList<IJavaElement> found = new LinkedList<IJavaElement>();
        scanForElement(parent, type, found, false);
        return found;
    }

    public static IJavaElement findType(IParent parent, int... type)
        throws JavaModelException
    {
        LinkedList<IJavaElement> found = new LinkedList<IJavaElement>();
        scanForElement(parent, type, found, true);
        return found.isEmpty() ? null : found.getFirst();
    }

    private static void scanForElement(IParent parent, int[] type,
        List<IJavaElement> roots, boolean thereCanBeOnlyOne) throws JavaModelException
    {
        for (IJavaElement e : parent.getChildren())
        {
            if (isType(type, e))
            {
                roots.add(e);
                if (thereCanBeOnlyOne)
                {
                    break;
                }
            }
            else if (e instanceof IParent)
            {
                scanForElement((IParent) e, type, roots, thereCanBeOnlyOne);
            }
        }
    }

    private static boolean isType(int[] type, IJavaElement e)
    {
        for (int i : type)
        {
            if (i == e.getElementType())
            {
                return true;
            }
        }
        return false;
    }

    public static boolean isAssignableTo(String ifaceOrParentClass, IType type)
        throws JavaModelException
    {
        if (ifaceOrParentClass == null)
            return true;

        ITypeHierarchy h = type.newSupertypeHierarchy(null);

        for (IType superType : h.getAllClasses())
        {
            String name = superType.getFullyQualifiedName();
            if (name.equals(ifaceOrParentClass))
            {
                return true;
            }
        }
        for (IType ifaceType : h.getAllInterfaces())
        {
            String name = ifaceType.getFullyQualifiedName();
            if (name.equals(ifaceOrParentClass))
            {
                return true;
            }
        }

        return false;
    }

    private static IType findType(ITypeRoot root) throws JavaModelException
    {
        // TODO Auto-generated method stub
        for (IJavaElement child : root.getChildren())
        {
            if (child.getElementType() == IJavaElement.TYPE)
            {
                return (IType) child;
            }
        }

        throw new JavaModelException(
            new IllegalStateException("Missing type for " + root), IStatus.ERROR);
    }

    public static Set<String> findLocalPackageDependencies(ISigilProjectModel project,
        String packageName, IProgressMonitor monitor) throws JavaModelException
    {
        Set<String> imports = findJavaImports(project, monitor);
        imports.remove(packageName);
        return imports;
    }

    public static Set<String> findLocalPackageUsers(ISigilProjectModel project,
        String packageName, IProgressMonitor monitor) throws JavaModelException
    {
        Set<String> imports = new HashSet<String>();
        Set<String> check = new HashSet<String>();
        for (IPackageFragment root : project.getJavaModel().getPackageFragments())
        {
            IPackageFragmentRoot rt = (IPackageFragmentRoot) root.getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT);

            if (isInClassPath(project, rt))
            {
                for (ICompilationUnit cu : root.getCompilationUnits())
                {
                    IPackageFragment pack = (IPackageFragment) cu.getAncestor(IJavaModel.PACKAGE_FRAGMENT);
                    if (!pack.getElementName().equals(packageName))
                    {
                        scanImports(cu, check);
                        if (check.contains(packageName))
                        {
                            imports.add(pack.getElementName());
                        }
                    }
                    check.clear();
                }

                for (IClassFile cf : root.getClassFiles())
                {
                    IPackageFragment pack = (IPackageFragment) cf.getAncestor(IJavaModel.PACKAGE_FRAGMENT);
                    if (!pack.getElementName().equals(packageName))
                    {
                        scanImports(cf, check);
                        if (check.contains(packageName))
                        {
                            imports.add(pack.getElementName());
                        }
                    }
                    check.clear();
                }
            }
        }

        return imports;
    }
}


text:
package vision

import (
	"context"
	"fmt"
	"reflect"
	"testing"

	"github.com/golang/protobuf/proto"
	pb "google.golang.org/genproto/googleapis/cloud/vision/v1"
	"google.golang.org/genproto/googleapis/rpc/status"
	"google.golang.org/grpc"
	"google.golang.org/grpc/codes"
)

var batchResponse = &pb.BatchAnnotateImagesResponse{
	Responses: []*pb.AnnotateImageResponse{{
		FaceAnnotations: []*pb.FaceAnnotation{
			{RollAngle: 1}, {RollAngle: 2}},
		LandmarkAnnotations:       []*pb.EntityAnnotation{{Mid: "landmark"}},
		LogoAnnotations:           []*pb.EntityAnnotation{{Mid: "logo"}},
		LabelAnnotations:          []*pb.EntityAnnotation{{Mid: "label"}},
		TextAnnotations:           []*pb.EntityAnnotation{{Mid: "text"}},
		FullTextAnnotation:        &pb.TextAnnotation{Text: "full"},
		SafeSearchAnnotation:      &pb.SafeSearchAnnotation{Spoof: pb.Likelihood_POSSIBLE},
		ImagePropertiesAnnotation: &pb.ImageProperties{DominantColors: &pb.DominantColorsAnnotation{}},
		CropHintsAnnotation:       &pb.CropHintsAnnotation{CropHints: []*pb.CropHint{{Confidence: 0.5}}},
		WebDetection:              &pb.WebDetection{WebEntities: []*pb.WebDetection_WebEntity{{EntityId: "web"}}},
	}},
}

// Verify that all the "shortcut" methods use the underlying
// BatchAnnotateImages RPC correctly.
func TestClientMethods(t *testing.T) {
	ctx := context.Background()
	c, err := NewImageAnnotatorClient(ctx, clientOpt)
	if err != nil {
		t.Fatal(err)
	}

	mockImageAnnotator.resps = []proto.Message{batchResponse}
	img := &pb.Image{Source: &pb.ImageSource{ImageUri: "http://foo.jpg"}}
	ictx := &pb.ImageContext{LanguageHints: []string{"en", "fr"}}
	req := &pb.AnnotateImageRequest{
		Image:        img,
		ImageContext: ictx,
		Features: []*pb.Feature{
			{Type: pb.Feature_LABEL_DETECTION, MaxResults: 3},
			{Type: pb.Feature_FACE_DETECTION, MaxResults: 4},
		},
	}

	for i, test := range []struct {
		call         func() (interface{}, error)
		wantFeatures []*pb.Feature
		wantRes      interface{}
	}{
		{
			func() (interface{}, error) { return c.AnnotateImage(ctx, req) },
			req.Features, batchResponse.Responses[0],
		},
		{
			func() (interface{}, error) { return c.DetectFaces(ctx, img, ictx, 2) },
			[]*pb.Feature{{Type: pb.Feature_FACE_DETECTION, MaxResults: 2}},
			batchResponse.Responses[0].FaceAnnotations,
		},
		{
			func() (interface{}, error) { return c.DetectLandmarks(ctx, img, ictx, 2) },
			[]*pb.Feature{{Type: pb.Feature_LANDMARK_DETECTION, MaxResults: 2}},
			batchResponse.Responses[0].LandmarkAnnotations,
		},
		{
			func() (interface{}, error) { return c.DetectLogos(ctx, img, ictx, 2) },
			[]*pb.Feature{{Type: pb.Feature_LOGO_DETECTION, MaxResults: 2}},
			batchResponse.Responses[0].LogoAnnotations,
		},
		{
			func() (interface{}, error) { return c.DetectLabels(ctx, img, ictx, 2) },
			[]*pb.Feature{{Type: pb.Feature_LABEL_DETECTION, MaxResults: 2}},
			batchResponse.Responses[0].LabelAnnotations,
		},
		{
			func() (interface{}, error) { return c.DetectTexts(ctx, img, ictx, 2) },
			[]*pb.Feature{{Type: pb.Feature_TEXT_DETECTION, MaxResults: 2}},
			batchResponse.Responses[0].TextAnnotations,
		},
		{
			func() (interface{}, error) { return c.DetectDocumentText(ctx, img, ictx) },
			[]*pb.Feature{{Type: pb.Feature_DOCUMENT_TEXT_DETECTION, MaxResults: 0}},
			batchResponse.Responses[0].FullTextAnnotation,
		},
		{
			func() (interface{}, error) { return c.DetectSafeSearch(ctx, img, ictx) },
			[]*pb.Feature{{Type: pb.Feature_SAFE_SEARCH_DETECTION, MaxResults: 0}},
			batchResponse.Responses[0].SafeSearchAnnotation,
		},
		{
			func() (interface{}, error) { return c.DetectImageProperties(ctx, img, ictx) },
			[]*pb.Feature{{Type: pb.Feature_IMAGE_PROPERTIES, MaxResults: 0}},
			batchResponse.Responses[0].ImagePropertiesAnnotation,
		},
		{
			func() (interface{}, error) { return c.DetectWeb(ctx, img, ictx) },
			[]*pb.Feature{{Type: pb.Feature_WEB_DETECTION, MaxResults: 0}},
			batchResponse.Responses[0].WebDetection,
		},
		{
			func() (interface{}, error) { return c.CropHints(ctx, img, ictx) },
			[]*pb.Feature{{Type: pb.Feature_CROP_HINTS, MaxResults: 0}},
			batchResponse.Responses[0].CropHintsAnnotation,
		},
		{
			func() (interface{}, error) { return c.LocalizeObjects(ctx, img, ictx) },
			[]*pb.Feature{{Type: pb.Feature_OBJECT_LOCALIZATION, MaxResults: 0}},
			batchResponse.Responses[0].LocalizedObjectAnnotations,
		},
		{
			func() (interface{}, error) { return c.ProductSearch(ctx, img, ictx) },
			[]*pb.Feature{{Type: pb.Feature_PRODUCT_SEARCH, MaxResults: 0}},
			batchResponse.Responses[0].ProductSearchResults,
		},
	} {
		mockImageAnnotator.reqs = nil
		res, err := test.call()
		if err != nil {
			t.Fatal(err)
		}
		got := mockImageAnnotator.reqs[0]
		want := &pb.BatchAnnotateImagesRequest{
			Requests: []*pb.AnnotateImageRequest{{
				Image:        img,
				ImageContext: ictx,
				Features:     test.wantFeatures,
			}},
		}
		if !testEqual(got, want) {
			t.Errorf("#%d:\ngot  %v\nwant %v", i, got, want)
		}
		if got, want := res, test.wantRes; !testEqual(got, want) {
			t.Errorf("#%d:\ngot  %v\nwant %v", i, got, want)
		}
	}

}

func testEqual(a, b interface{}) bool {
	if a == nil && b == nil {
		return true
	}
	if a == nil || b == nil {
		return false
	}
	t := reflect.TypeOf(a)
	if t != reflect.TypeOf(b) {
		return false
	}
	if am, ok := a.(proto.Message); ok {
		return proto.Equal(am, b.(proto.Message))
	}
	if t.Kind() != reflect.Slice {
		panic(fmt.Sprintf("testEqual can only handle proto.Message and slices, got %s", t))
	}
	va := reflect.ValueOf(a)
	vb := reflect.ValueOf(b)
	if va.Len() != vb.Len() {
		return false
	}
	for i := 0; i < va.Len(); i++ {
		if !testEqual(va.Index(i).Interface(), vb.Index(i).Interface()) {
			return false
		}
	}
	return true
}

func TestAnnotateOneError(t *testing.T) {
	ctx := context.Background()
	c, err := NewImageAnnotatorClient(ctx, clientOpt)
	if err != nil {
		t.Fatal(err)
	}
	mockImageAnnotator.resps = []proto.Message{
		&pb.BatchAnnotateImagesResponse{
			Responses: []*pb.AnnotateImageResponse{{
				Error: &status.Status{Code: int32(codes.NotFound), Message: "not found"},
			}},
		},
	}

	_, err = c.annotateOne(ctx,
		&pb.Image{Source: &pb.ImageSource{ImageUri: "http://foo.jpg"}},
		nil, pb.Feature_LOGO_DETECTION, 1, nil)
	if c := grpc.Code(err); c != codes.NotFound {
		t.Errorf("got %v, want NotFound", c)
	}
}

redpajama_set_name: RedPajamaGithub


text:
// Copyright 2014 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "media/cast/test/fake_media_source.h"

#include <memory>
#include <utility>

#include "base/bind.h"
#include "base/files/scoped_file.h"
#include "base/logging.h"
#include "base/rand_util.h"
#include "base/strings/string_number_conversions.h"
#include "build/build_config.h"
#include "media/base/audio_buffer.h"
#include "media/base/audio_bus.h"
#include "media/base/audio_fifo.h"
#include "media/base/audio_timestamp_helper.h"
#include "media/base/media.h"
#include "media/base/video_frame.h"
#include "media/base/video_util.h"
#include "media/cast/cast_sender.h"
#include "media/cast/test/utility/audio_utility.h"
#include "media/cast/test/utility/video_utility.h"
#include "ui/gfx/geometry/size.h"

#if BUILDFLAG(IS_WIN)
#include <direct.h>
#endif  // BUILDFLAG(IS_WIN)
#include "media/ffmpeg/ffmpeg_common.h"
#include "media/ffmpeg/ffmpeg_decoding_loop.h"
#include "media/ffmpeg/ffmpeg_deleters.h"
#include "media/filters/ffmpeg_glue.h"
#include "media/filters/in_memory_url_protocol.h"

namespace {

static const int kSoundFrequency = 440;  // Frequency of sinusoid wave.
static const float kSoundVolume = 0.10f;
static const int kAudioFrameMs = 10;  // Each audio frame is exactly 10ms.
static const int kAudioPacketsPerSecond = 1000 / kAudioFrameMs;

// Bounds for variable frame size mode.
static const int kMinFakeFrameWidth = 60;
static const int kMinFakeFrameHeight = 34;
static const int kStartingFakeFrameWidth = 854;
static const int kStartingFakeFrameHeight = 480;
static const int kMaxFakeFrameWidth = 1280;
static const int kMaxFakeFrameHeight = 720;
static const int kMaxFrameSizeChangeMillis = 5000;

void AVFreeFrame(AVFrame* frame) {
  av_frame_free(&frame);
}

base::TimeDelta PtsToTimeDelta(int64_t pts, const AVRational& time_base) {
  return pts * base::Seconds(1) * time_base.num / time_base.den;
}

int64_t TimeDeltaToPts(base::TimeDelta delta, const AVRational& time_base) {
  return static_cast<int64_t>(
      delta.InSecondsF() * time_base.den / time_base.num + 0.5 /* rounding */);
}

}  // namespace

namespace media {
namespace cast {

FakeMediaSource::FakeMediaSource(
    scoped_refptr<base::SingleThreadTaskRunner> task_runner,
    const base::TickClock* clock,
    const FrameSenderConfig& audio_config,
    const FrameSenderConfig& video_config,
    bool keep_frames)
    : task_runner_(task_runner),
      output_audio_params_(
          AudioParameters::AUDIO_PCM_LINEAR,
          media::ChannelLayoutConfig::Guess(audio_config.channels),
          audio_config.rtp_timebase,
          audio_config.rtp_timebase / kAudioPacketsPerSecond),
      video_config_(video_config),
      keep_frames_(keep_frames),
      variable_frame_size_mode_(false),
      synthetic_count_(0),
      clock_(clock),
      audio_frame_count_(0),
      video_frame_count_(0),
      av_format_context_(nullptr),
      audio_stream_index_(-1),
      playback_rate_(1.0),
      video_stream_index_(-1),
      video_frame_rate_numerator_(video_config.max_frame_rate),
      video_frame_rate_denominator_(1),
      audio_algo_(&media_log_),
      video_first_pts_(0),
      video_first_pts_set_(false) {
  CHECK(output_audio_params_.IsValid());
  audio_bus_factory_ = std::make_unique<TestAudioBusFactory>(
      audio_config.channels, audio_config.rtp_timebase, kSoundFrequency,
      kSoundVolume);
}

FakeMediaSource::~FakeMediaSource() = default;

void FakeMediaSource::SetSourceFile(const base::FilePath& video_file,
                                    int final_fps) {
  DCHECK(!video_file.empty());

  LOG(INFO) << "Source: " << video_file.value();
  if (!file_data_.Initialize(video_file)) {
    LOG(ERROR) << "Cannot load file.";
    return;
  }
  protocol_ = std::make_unique<InMemoryUrlProtocol>(file_data_.data(),
                                                    file_data_.length(), false);
  glue_ = std::make_unique<FFmpegGlue>(protocol_.get());

  if (!glue_->OpenContext()) {
    LOG(ERROR) << "Cannot open file.";
    return;
  }

  // AVFormatContext is owned by the glue.
  av_format_context_ = glue_->format_context();
  if (avformat_find_stream_info(av_format_context_, NULL) < 0) {
    LOG(ERROR) << "Cannot find stream information.";
    return;
  }

  // Prepare FFmpeg decoders.
  for (unsigned int i = 0; i < av_format_context_->nb_streams; ++i) {
    AVStream* av_stream = av_format_context_->streams[i];
    std::unique_ptr<AVCodecContext, ScopedPtrAVFreeContext> av_codec_context(
        AVStreamToAVCodecContext(av_stream));
    if (!av_codec_context) {
      LOG(ERROR) << "Cannot get a codec context for the codec: "
                 << av_stream->codecpar->codec_id;
      continue;
    }

    const AVCodec* av_codec = avcodec_find_decoder(av_codec_context->codec_id);

    if (!av_codec) {
      LOG(ERROR) << "Cannot find decoder for the codec: "
                 << av_codec_context->codec_id;
      continue;
    }

    // Number of threads for decoding.
    av_codec_context->thread_count = 2;
    av_codec_context->error_concealment = FF_EC_GUESS_MVS | FF_EC_DEBLOCK;
    av_codec_context->request_sample_fmt = AV_SAMPLE_FMT_S16;

    if (avcodec_open2(av_codec_context.get(), av_codec, nullptr) < 0) {
      LOG(ERROR) << "Cannot open AVCodecContext for the codec: "
                 << av_codec_context->codec_id;
      return;
    }

    if (av_codec->type == AVMEDIA_TYPE_AUDIO) {
      if (av_codec_context->sample_fmt == AV_SAMPLE_FMT_S16P) {
        LOG(ERROR) << "Audio format not supported.";
        continue;
      }
      ChannelLayout layout = ChannelLayoutToChromeChannelLayout(
          av_codec_context->channel_layout,
          av_codec_context->channels);
      if (layout == CHANNEL_LAYOUT_UNSUPPORTED) {
        LOG(ERROR) << "Unsupported audio channels layout.";
        continue;
      }
      if (audio_stream_index_ != -1) {
        LOG(WARNING) << "Found multiple audio streams.";
      }
      audio_stream_index_ = static_cast<int>(i);
      av_audio_context_ = std::move(av_codec_context);
      source_audio_params_.Reset(
          AudioParameters::AUDIO_PCM_LINEAR,
          {layout, av_audio_context_->channels}, av_audio_context_->sample_rate,
          av_audio_context_->sample_rate / kAudioPacketsPerSecond);
      CHECK(source_audio_params_.IsValid());
      LOG(INFO) << "Source file has audio.";
      audio_decoding_loop_ =
          std::make_unique<FFmpegDecodingLoop>(av_audio_context_.get());
    } else if (av_codec->type == AVMEDIA_TYPE_VIDEO) {
      VideoPixelFormat format =
          AVPixelFormatToVideoPixelFormat(av_codec_context->pix_fmt);
      if (format != PIXEL_FORMAT_I420) {
        LOG(ERROR) << "Cannot handle non YV12 video format: " << format;
        continue;
      }
      if (video_stream_index_ != -1) {
        LOG(WARNING) << "Found multiple video streams.";
      }
      video_stream_index_ = static_cast<int>(i);
      av_video_context_ = std::move(av_codec_context);
      video_decoding_loop_ =
          std::make_unique<FFmpegDecodingLoop>(av_video_context_.get());
      if (final_fps > 0) {
        // If video is played at a manual speed audio needs to match.
        playback_rate_ = 1.0 * final_fps *
            av_stream->r_frame_rate.den / av_stream->r_frame_rate.num;
        video_frame_rate_numerator_ = final_fps;
        video_frame_rate_denominator_ = 1;
      } else {
        playback_rate_ = 1.0;
        video_frame_rate_numerator_ = av_stream->r_frame_rate.num;
        video_frame_rate_denominator_ = av_stream->r_frame_rate.den;
      }
      LOG(INFO) << "Source file has video.";
    } else {
      LOG(ERROR) << "Unknown stream type; ignore.";
    }
  }

  Rewind();
}

void FakeMediaSource::SetVariableFrameSizeMode(bool enabled) {
  variable_frame_size_mode_ = enabled;
}

void FakeMediaSource::Start(scoped_refptr<AudioFrameInput> audio_frame_input,
                            scoped_refptr<VideoFrameInput> video_frame_input) {
  audio_frame_input_ = audio_frame_input;
  video_frame_input_ = video_frame_input;

  LOG(INFO) << "Max Frame rate: " << video_config_.max_frame_rate;
  LOG(INFO) << "Source Frame rate: "
            << video_frame_rate_numerator_ << "/"
            << video_frame_rate_denominator_ << " fps.";
  LOG(INFO) << "Audio playback rate: " << playback_rate_;

  if (start_time_.is_null())
    start_time_ = clock_->NowTicks();

  if (!is_transcoding_audio() && !is_transcoding_video()) {
    // Send fake patterns.
    task_runner_->PostTask(FROM_HERE,
                           base::BindOnce(&FakeMediaSource::SendNextFakeFrame,
                                          weak_factory_.GetWeakPtr()));
    return;
  }

  // Send transcoding streams.
  bool is_encrypted = false;
  audio_algo_.Initialize(source_audio_params_, is_encrypted);
  audio_algo_.FlushBuffers();
  audio_fifo_input_bus_ = AudioBus::Create(
      source_audio_params_.channels(),
      source_audio_params_.frames_per_buffer());
  // Audio FIFO can carry all data fron AudioRendererAlgorithm.
  audio_fifo_ = std::make_unique<AudioFifo>(source_audio_params_.channels(),
                                            audio_algo_.QueueCapacity());
  audio_converter_ = std::make_unique<media::AudioConverter>(
      source_audio_params_, output_audio_params_, true);
  audio_converter_->AddInput(this);
  task_runner_->PostTask(FROM_HERE,
                         base::BindOnce(&FakeMediaSource::SendNextFrame,
                                        weak_factory_.GetWeakPtr()));
}

void FakeMediaSource::SendNextFakeFrame() {
  UpdateNextFrameSize();
  scoped_refptr<VideoFrame> video_frame =
      VideoFrame::CreateBlackFrame(current_frame_size_);
  PopulateVideoFrame(video_frame.get(), synthetic_count_);
  ++synthetic_count_;

  const base::TimeTicks now = clock_->NowTicks();

  base::TimeDelta video_time = VideoFrameTime(++video_frame_count_);
  video_frame->set_timestamp(video_time);
  if (keep_frames_)
    inserted_video_frame_queue_.push(video_frame);
  video_frame_input_->InsertRawVideoFrame(video_frame,
                                          start_time_ + video_time);

  // Send just enough audio data to match next video frame's time.
  base::TimeDelta audio_time = AudioFrameTime(audio_frame_count_);
  while (audio_time < video_time) {
    if (is_transcoding_audio()) {
      Decode(true);
      CHECK(!audio_bus_queue_.empty()) << "No audio decoded.";
      std::unique_ptr<AudioBus> bus(audio_bus_queue_.front());
      audio_bus_queue_.pop();
      audio_frame_input_->InsertAudio(std::move(bus), start_time_ + audio_time);
    } else {
      audio_frame_input_->InsertAudio(
          audio_bus_factory_->NextAudioBus(base::Milliseconds(kAudioFrameMs)),
          start_time_ + audio_time);
    }
    audio_time = AudioFrameTime(++audio_frame_count_);
  }

  // This is the time since FakeMediaSource was started.
  const base::TimeDelta elapsed_time = now - start_time_;

  // Handle the case when frame generation cannot keep up.
  // Move the time ahead to match the next frame.
  while (video_time < elapsed_time) {
    LOG(WARNING) << "Skipping one frame.";
    video_time = VideoFrameTime(++video_frame_count_);
  }

  task_runner_->PostDelayedTask(
      FROM_HERE,
      base::BindOnce(&FakeMediaSource::SendNextFakeFrame,
                     weak_factory_.GetWeakPtr()),
      video_time - elapsed_time);
}

void FakeMediaSource::UpdateNextFrameSize() {
  if (variable_frame_size_mode_) {
    bool update_size_change_time = false;
    if (current_frame_size_.IsEmpty()) {
      current_frame_size_ = gfx::Size(kStartingFakeFrameWidth,
                                      kStartingFakeFrameHeight);
      update_size_change_time = true;
    } else if (clock_->NowTicks() >= next_frame_size_change_time_) {
      current_frame_size_ = gfx::Size(
          base::RandInt(kMinFakeFrameWidth, kMaxFakeFrameWidth),
          base::RandInt(kMinFakeFrameHeight, kMaxFakeFrameHeight));
      update_size_change_time = true;
    }

    if (update_size_change_time) {
      next_frame_size_change_time_ =
          clock_->NowTicks() +
          base::Milliseconds(base::RandDouble() * kMaxFrameSizeChangeMillis);
    }
  } else {
    current_frame_size_ = gfx::Size(kStartingFakeFrameWidth,
                                    kStartingFakeFrameHeight);
    next_frame_size_change_time_ = base::TimeTicks();
  }
}

bool FakeMediaSource::SendNextTranscodedVideo(base::TimeDelta elapsed_time) {
  if (!is_transcoding_video())
    return false;

  Decode(false);
  if (video_frame_queue_.empty())
    return false;

  const scoped_refptr<VideoFrame> video_frame = video_frame_queue_.front();
  if (elapsed_time < video_frame->timestamp())
    return false;
  video_frame_queue_.pop();

  // Use the timestamp from the file if we're transcoding.
  video_frame->set_timestamp(ScaleTimestamp(video_frame->timestamp()));
  if (keep_frames_)
    inserted_video_frame_queue_.push(video_frame);
  video_frame_input_->InsertRawVideoFrame(
      video_frame, start_time_ + video_frame->timestamp());

  // Make sure queue is not empty.
  Decode(false);
  return true;
}

bool FakeMediaSource::SendNextTranscodedAudio(base::TimeDelta elapsed_time) {
  if (!is_transcoding_audio())
    return false;

  Decode(true);
  if (audio_bus_queue_.empty())
    return false;

  base::TimeDelta audio_time = audio_sent_ts_->GetTimestamp();
  if (elapsed_time < audio_time)
    return false;
  std::unique_ptr<AudioBus> bus(audio_bus_queue_.front());
  audio_bus_queue_.pop();
  audio_sent_ts_->AddFrames(bus->frames());
  audio_frame_input_->InsertAudio(std::move(bus), start_time_ + audio_time);

  // Make sure queue is not empty.
  Decode(true);
  return true;
}

void FakeMediaSource::SendNextFrame() {
  // Send as much as possible. Audio is sent according to
  // system time.
  while (SendNextTranscodedAudio(clock_->NowTicks() - start_time_)) {
  }

  // Video is sync'ed to audio.
  while (SendNextTranscodedVideo(audio_sent_ts_->GetTimestamp())) {
  }

  if (audio_bus_queue_.empty() && video_frame_queue_.empty()) {
    // Both queues are empty can only mean that we have reached
    // the end of the stream.
    LOG(INFO) << "Rewind.";
    Rewind();
  }

  // Send next send.
  task_runner_->PostDelayedTask(FROM_HERE,
                                base::BindOnce(&FakeMediaSource::SendNextFrame,
                                               weak_factory_.GetWeakPtr()),
                                base::Milliseconds(kAudioFrameMs));
}

base::TimeDelta FakeMediaSource::VideoFrameTime(int frame_number) {
  return frame_number * base::Seconds(1) * video_frame_rate_denominator_ /
         video_frame_rate_numerator_;
}

base::TimeDelta FakeMediaSource::ScaleTimestamp(base::TimeDelta timestamp) {
  return timestamp / playback_rate_;
}

base::TimeDelta FakeMediaSource::AudioFrameTime(int frame_number) {
  return frame_number * base::Milliseconds(kAudioFrameMs);
}

void FakeMediaSource::Rewind() {
  CHECK(av_seek_frame(av_format_context_, -1, 0, AVSEEK_FLAG_BACKWARD) >= 0)
      << "Failed to rewind to the beginning.";
}

ScopedAVPacket FakeMediaSource::DemuxOnePacket(bool* audio) {
  auto packet = ScopedAVPacket::Allocate();
  if (av_read_frame(av_format_context_, packet.get()) < 0) {
    VLOG(1) << "Failed to read one AVPacket.";
    return {};
  }

  int stream_index = static_cast<int>(packet->stream_index);
  if (stream_index == audio_stream_index_) {
    *audio = true;
  } else if (stream_index == video_stream_index_) {
    *audio = false;
  } else {
    // Ignore unknown packet.
    LOG(INFO) << "Unknown packet.";
    return {};
  }
  return packet;
}

void FakeMediaSource::DecodeAudio(ScopedAVPacket packet) {
  auto result = audio_decoding_loop_->DecodePacket(
      packet.get(), base::BindRepeating(&FakeMediaSource::OnNewAudioFrame,
                                        base::Unretained(this)));
  CHECK_EQ(result, FFmpegDecodingLoop::DecodeStatus::kOkay)
      << "Failed to decode audio.";

  const int frames_needed_to_scale =
      playback_rate_ * av_audio_context_->sample_rate / kAudioPacketsPerSecond;
  while (frames_needed_to_scale <= audio_algo_.BufferedFrames()) {
    if (!audio_algo_.FillBuffer(audio_fifo_input_bus_.get(), 0,
                                audio_fifo_input_bus_->frames(),
                                playback_rate_)) {
      // Nothing can be scaled. Decode some more.
      return;
    }

    // Prevent overflow of audio data in the FIFO.
    if (audio_fifo_input_bus_->frames() + audio_fifo_->frames() <=
        audio_fifo_->max_frames()) {
      audio_fifo_->Push(audio_fifo_input_bus_.get());
    } else {
      LOG(WARNING) << "Audio FIFO full; dropping samples.";
    }

    // Make sure there's enough data to resample audio.
    if (audio_fifo_->frames() <
        2 * source_audio_params_.sample_rate() / kAudioPacketsPerSecond) {
      continue;
    }

    std::unique_ptr<media::AudioBus> resampled_bus(media::AudioBus::Create(
        output_audio_params_.channels(),
        output_audio_params_.sample_rate() / kAudioPacketsPerSecond));
    audio_converter_->Convert(resampled_bus.get());
    audio_bus_queue_.push(resampled_bus.release());
  }
}

bool FakeMediaSource::OnNewAudioFrame(AVFrame* frame) {
  int frames_read = frame->nb_samples;
  if (frames_read < 0)
    return false;

  if (!audio_sent_ts_) {
    // Initialize the base time to the first packet in the file. This is set to
    // the frequency we send to the receiver. Not the frequency of the source
    // file. This is because we increment the frame count by samples we sent.
    audio_sent_ts_ = std::make_unique<AudioTimestampHelper>(
        output_audio_params_.sample_rate());
    // For some files this is an invalid value.
    base::TimeDelta base_ts;
    audio_sent_ts_->SetBaseTimestamp(base_ts);
  }

  scoped_refptr<AudioBuffer> buffer = AudioBuffer::CopyFrom(
      AVSampleFormatToSampleFormat(av_audio_context_->sample_fmt,
                                   av_audio_context_->codec_id),
      ChannelLayoutToChromeChannelLayout(av_audio_context_->channel_layout,
                                         av_audio_context_->channels),
      av_audio_context_->channels, av_audio_context_->sample_rate, frames_read,
      &frame->data[0],
      PtsToTimeDelta(frame->pts, av_audio_stream()->time_base));
  audio_algo_.EnqueueBuffer(buffer);
  return true;
}

void FakeMediaSource::DecodeVideo(ScopedAVPacket packet) {
  auto result = video_decoding_loop_->DecodePacket(
      packet.get(), base::BindRepeating(&FakeMediaSource::OnNewVideoFrame,
                                        base::Unretained(this)));
  CHECK_EQ(result, FFmpegDecodingLoop::DecodeStatus::kOkay)
      << "Failed to decode video.";
}

bool FakeMediaSource::OnNewVideoFrame(AVFrame* frame) {
  gfx::Size size(av_video_context_->width, av_video_context_->height);

  if (!video_first_pts_set_) {
    video_first_pts_ = frame->pts;
    video_first_pts_set_ = true;
  }
  const AVRational& time_base = av_video_stream()->time_base;
  base::TimeDelta timestamp =
      PtsToTimeDelta(frame->pts - video_first_pts_, time_base);
  if (timestamp < last_video_frame_timestamp_) {
    // Stream has rewound.  Rebase |video_first_pts_|.
    const AVRational& frame_rate = av_video_stream()->r_frame_rate;
    timestamp = last_video_frame_timestamp_ +
                (base::Seconds(1) * frame_rate.den / frame_rate.num);
    const int64_t adjustment_pts = TimeDeltaToPts(timestamp, time_base);
    video_first_pts_ = frame->pts - adjustment_pts;
  }

  AVFrame* shallow_copy = av_frame_clone(frame);
  scoped_refptr<media::VideoFrame> video_frame =
      VideoFrame::WrapExternalYuvData(
          media::PIXEL_FORMAT_I420, size, gfx::Rect(size), size,
          shallow_copy->linesize[0], shallow_copy->linesize[1],
          shallow_copy->linesize[2], shallow_copy->data[0],
          shallow_copy->data[1], shallow_copy->data[2], timestamp);
  if (!video_frame)
    return false;
  video_frame_queue_.push(video_frame);
  video_frame_queue_.back()->AddDestructionObserver(
      base::BindOnce(&AVFreeFrame, shallow_copy));
  last_video_frame_timestamp_ = timestamp;
  return true;
}

void FakeMediaSource::Decode(bool decode_audio) {
  // Read the stream until one video frame can be decoded.
  while (true) {
    if (decode_audio && !audio_bus_queue_.empty())
      return;
    if (!decode_audio && !video_frame_queue_.empty())
      return;

    bool audio_packet = false;
    ScopedAVPacket packet = DemuxOnePacket(&audio_packet);
    if (!packet) {
      VLOG(1) << "End of stream.";
      return;
    }

    if (audio_packet)
      DecodeAudio(std::move(packet));
    else
      DecodeVideo(std::move(packet));
  }
}

double FakeMediaSource::ProvideInput(media::AudioBus* output_bus,
                                     uint32_t frames_delayed) {
  if (audio_fifo_->frames() >= output_bus->frames()) {
    audio_fifo_->Consume(output_bus, 0, output_bus->frames());
    return 1.0;
  } else {
    LOG(WARNING) << "Not enough audio data for resampling.";
    output_bus->Zero();
    return 0.0;
  }
}

scoped_refptr<media::VideoFrame>
FakeMediaSource::PopOldestInsertedVideoFrame() {
  CHECK(!inserted_video_frame_queue_.empty());
  scoped_refptr<media::VideoFrame> video_frame =
      inserted_video_frame_queue_.front();
  inserted_video_frame_queue_.pop();
  return video_frame;
}

AVStream* FakeMediaSource::av_audio_stream() {
  return av_format_context_->streams[audio_stream_index_];
}

AVStream* FakeMediaSource::av_video_stream() {
  return av_format_context_->streams[video_stream_index_];
}

}  // namespace cast
}  // namespace media


text:
{% extends 'base.html' %}

{% block html_title %}{% if page.html_title %}{{ page.html_title }}{% else %}{{ page.title }}{% endif %}{% endblock %}

{% block meta_description %}{{ page.meta_description }}{% endblock %}

{% block meta_keywords %}{{ page.meta_keywords }}{% endblock %}

{% block site_section %}{{ page.site_section.url }}{% endblock %}


text:
package com.ghgande.j2mod.modbus.io;

import com.ghgande.j2mod.modbus.Modbus;
import com.ghgande.j2mod.modbus.ModbusException;
import com.ghgande.j2mod.modbus.ModbusIOException;
import com.ghgande.j2mod.modbus.msg.ModbusRequest;
import com.ghgande.j2mod.modbus.msg.ModbusResponse;

import java.util.Random;

/**
 * Interface defining a ModbusTransaction.
 *

 * A transaction is defined by the sequence of
 * sending a request message and receiving a
 * related response message.
 *
 * @author Dieter Wimberger
 * @author Steve O'Hara (4NG)
 * @version 2.0 (March 2016)
 */
public abstract class ModbusTransaction {

    protected AbstractModbusTransport transport;
    protected ModbusRequest request;
    protected ModbusResponse response;
    boolean validityCheck = Modbus.DEFAULT_VALIDITYCHECK;
    int retries = Modbus.DEFAULT_RETRIES;
    private final Random random = new Random(System.nanoTime());
    static int transactionID = Modbus.DEFAULT_TRANSACTION_ID;

    /**
     * Returns the <tt>ModbusRequest</tt> instance
     * associated with this <tt>ModbusTransaction</tt>.
     *

     *
     * @return the associated <tt>ModbusRequest</tt> instance.
     */
    public ModbusRequest getRequest() {
        return request;
    }

    /**
     * Sets the <tt>ModbusRequest</tt> for this
     * <tt>ModbusTransaction</tt>.

     * The related <tt>ModbusResponse</tt> is acquired
     * from the passed in <tt>ModbusRequest</tt> instance.

     *

     *
     * @param req a <tt>ModbusRequest</tt>.
     */
    public void setRequest(ModbusRequest req) {
        request = req;
        if (req != null) {
            request.setTransactionID(getTransactionID());
        }
    }

    /**
     * Returns the <tt>ModbusResponse</tt> instance
     * associated with this <tt>ModbusTransaction</tt>.
     *

     *
     * @return the associated <tt>ModbusRequest</tt> instance.
     */
    public ModbusResponse getResponse() {
        return response;
    }

    /**
     * Returns the amount of retries for opening
     * the connection for executing the transaction.
     *

     *
     * @return the amount of retries as <tt>int</tt>.
     */
    int getRetries() {
        return retries;
    }

    /**
     * Set the amount of retries for opening
     * the connection for executing the transaction.
     *

     *
     * @param retries the amount of retries as <tt>int</tt>.
     */
    public void setRetries(int retries) {
        this.retries = retries;
    }

    /**
     * Tests whether the validity of a transaction
     * will be checked.
     *

     *
     * @return true if checking validity, false otherwise.
     */
    public boolean isCheckingValidity() {
        return validityCheck;
    }

    /**
     * Sets the flag that controls whether the
     * validity of a transaction will be checked.
     *

     *
     * @param b true if checking validity, false otherwise.
     */
    public void setCheckingValidity(boolean b) {
        validityCheck = b;
    }

    /**
     * getTransactionID -- get the next transaction ID to use.
     * @return next transaction ID to use
     */
    public synchronized int getTransactionID() {
        /*
         * Ensure that the transaction ID is in the valid range between
         * 0 and MAX_TRANSACTION_ID (65534).  If not, the value will be forced
         * to 0.
         */
        if (transactionID < Modbus.DEFAULT_TRANSACTION_ID && isCheckingValidity()) {
            transactionID = Modbus.DEFAULT_TRANSACTION_ID;
        }
        if (transactionID >= Modbus.MAX_TRANSACTION_ID) {
            transactionID = Modbus.DEFAULT_TRANSACTION_ID;
        }
        return transactionID;
    }

    /**
     * A useful method for getting a random sleep time based on an increment of the retry count and retry sleep time
     *
     * @param count Retry count
     * @return Random sleep time in milliseconds
     */
    long getRandomSleepTime(int count) {
        return (Modbus.RETRY_SLEEP_TIME / 2) + (long) (random.nextDouble() * Modbus.RETRY_SLEEP_TIME * count);
    }

    /**
     * Checks the validity of the transaction, by
     * checking if the values of the response correspond
     * to the values of the request.
     *
     * @throws ModbusException if the transaction is not valid.
     */
    void checkValidity() throws ModbusException {
        if (request != null && response != null) {
            if (request.getUnitID() != response.getUnitID()) {
                throw new ModbusIOException("Unit ID mismatch - Request [%s] Response [%s]", request.getHexMessage(), response.getHexMessage());
            }
            if (request.getFunctionCode() != response.getFunctionCode()) {
                throw new ModbusIOException("Function code mismatch - Request [%s] Response [%s]", request.getHexMessage(), response.getHexMessage());
            }
        }
    }

    /**
     * Executes this <tt>ModbusTransaction</tt>.
     * Locks the <tt>ModbusTransport</tt> for sending
     * the <tt>ModbusRequest</tt> and reading the
     * related <tt>ModbusResponse</tt>.
     * If reconnecting is activated the connection will
     * be opened for the transaction and closed afterwards.
     *

     *
     * @throws ModbusException if an I/O error occurs,
     *                         or the response is a modbus protocol exception.
     */
    public abstract void execute() throws ModbusException;

}


text:
package se.kth.id2212.ex3.bankjpa;

import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.NoResultException;
import javax.persistence.Persistence;

@SuppressWarnings("serial")
public class BankImpl extends UnicastRemoteObject implements Bank
{
    private EntityManagerFactory emFactory;

    public BankImpl() throws RemoteException
    {
        super();
        emFactory = Persistence.createEntityManagerFactory("bank");
    }

    public Account newAccount(String name) throws RejectedException
    {
        EntityManager em = null;
        try
        {
            em = beginTransaction();
            List<Account> existingAccounts = em.createNamedQuery("findAccountWithName", Account.class).
                    setParameter("ownerName", name).getResultList();
            if (existingAccounts.size() != 0)
            {
                // account exists, can not be created.
                throw new RejectedException("Rejected: Account for: " + name + " already exists");
            }

            // create account.
            Account account = new Account(new Owner(name), 0);
            em.persist(account);
            return account;
        } finally
        {
            commitTransaction(em);
        }
    }

    public void deposit(String ownerName, float value) throws RejectedException
    {
        EntityManager em = null;
        try
        {
            em = beginTransaction();

            getAccount(ownerName, em).deposit(value);
        } finally
        {
            commitTransaction(em);
        }
    }

    public void withdraw(String ownerName, float value) throws RejectedException
    {
        EntityManager em = null;
        try
        {
            em = beginTransaction();

            getAccount(ownerName, em).withdraw(value);
        } finally
        {
            commitTransaction(em);
        }
    }

    public Account findAccount(String ownerName)
    {
        EntityManager em = null;
        try
        {
            em = beginTransaction();

            Account account = getAccount(ownerName, em);
            return account;
        } finally
        {
            commitTransaction(em);
        }
    }

    public void deleteAccount(String name)
    {
        EntityManager em = null;
        try
        {
            em = beginTransaction();

            Account account = getAccount(name, em);
            em.remove(account);

        } finally
        {
            commitTransaction(em);
        }
    }

    private Account getAccount(String ownerName, EntityManager em)
    {
        if (ownerName == null)
        {
            return null;
        }

        try
        {
            return (Account) em.createNamedQuery("findAccountWithName").
                    setParameter("ownerName", ownerName).getSingleResult();
        } catch (NoResultException noSuchAccount)
        {
            return null;
        }
    }

    private EntityManager beginTransaction()
    {
        EntityManager em = emFactory.createEntityManager();
        EntityTransaction transaction = em.getTransaction();
        transaction.begin();
        return em;
    }

    private void commitTransaction(EntityManager em)
    {
        em.getTransaction().commit();
    }
}


text:
#region S# License

#endregion S# License
namespace SampleRithmic
{
	using System;
	using System.Collections.Generic;
	using System.ComponentModel;
	using System.Windows.Media;

	using StockSharp.Algo.Candles;
	using StockSharp.Rithmic;
	using StockSharp.Xaml.Charting;

	partial class ChartWindow
	{
		private readonly RithmicTrader _trader;
		private readonly CandleSeries _candleSeries;
		private readonly ChartCandleElement _candleElem;

		public ChartWindow(CandleSeries candleSeries, DateTime from, DateTime to)
		{
			InitializeComponent();

			if (candleSeries == null)
				throw new ArgumentNullException(nameof(candleSeries));

			_candleSeries = candleSeries;
			_trader = MainWindow.Instance.Trader;

			Chart.ChartTheme = "ExpressionDark";

			var area = new ChartArea();
			Chart.Areas.Add(area);

			_candleElem = new ChartCandleElement
			{
				AntiAliasing = false,
				UpFillColor = Colors.White,
				UpBorderColor = Colors.Black,
				DownFillColor = Colors.Black,
				DownBorderColor = Colors.Black,
			};

			area.Elements.Add(_candleElem);

			_trader.NewCandles += ProcessNewCandles;
			_trader.SubscribeCandles(_candleSeries, from, to);

			Title = candleSeries.ToString();
		}

		private void ProcessNewCandles(CandleSeries series, IEnumerable<Candle> candles)
		{
			if (series != _candleSeries)
				return;

			foreach (var timeFrameCandle in candles)
			{
				Chart.Draw(_candleElem, timeFrameCandle);
			}
		}

		protected override void OnClosing(CancelEventArgs e)
		{
			_trader.NewCandles -= ProcessNewCandles;
			base.OnClosing(e);
		}
	}
}


text:
namespace base {
template <typename T>
struct DefaultSingletonTraits;
}  // namespace base

namespace content {
class BrowserContext;
}

class SharingService;

// Factory for SharingService.
class SharingServiceFactory : public ProfileKeyedServiceFactory {
 public:
  // Returns singleton instance of SharingServiceFactory.
  static SharingServiceFactory* GetInstance();

  // Returns the SharingService associated with |context|.
  static SharingService* GetForBrowserContext(content::BrowserContext* context);

  SharingServiceFactory(const SharingServiceFactory&) = delete;
  SharingServiceFactory& operator=(const SharingServiceFactory&) = delete;

 private:
  friend struct base::DefaultSingletonTraits<SharingServiceFactory>;

  SharingServiceFactory();
  ~SharingServiceFactory() override;

  // BrowserContextKeyedServiceFactory overrides:
  KeyedService* BuildServiceInstanceFor(
      content::BrowserContext* context) const override;
  bool ServiceIsNULLWhileTesting() const override;
};

#endif  // CHROME_BROWSER_SHARING_SHARING_SERVICE_FACTORY_H_


text:
@interface NSMutableArray (LoggingAddObject)
-(void)logAddObject:(id)object;
@end


text:
package docker

import (
	"context"
	"crypto/tls"
	"testing"

	"github.com/stretchr/testify/assert"
)

func TestResolver(t *testing.T) {

	ctx := context.Background()

	cfg := Config{}
	cfg.Debug = true

	hostOptions := HostOptions{}
	hostOptions.DefaultScheme = "http"
	//hostOptions.HostDir = HostDirFromRoot(hostDir)
	hostOptions.DefaultTLS = &tls.Config{
		InsecureSkipVerify: true,
	}

	cfg.Hosts = ConfigureHosts(ctx, hostOptions)

	r, err := New(cfg)
	if assert.NotNil(t, err, "create resolver error") {
		return
	}
	if !assert.NotNil(t, r, "resolver can not be nil") {
		return
	}

	reader, err := r.Pull(ctx, "localhost:5000/redis")
	if assert.NotNil(t, err, "pull image failed") {
		return
	}
}


text:
(See [Job Lifecycle](job-lifecycle.md) for an explanation of when post-stop scripts run.)

!!! note
    This feature is available with bosh-release v265+ and only for releases deployed with 3125+ stemcells.

Release job can have a post-stop script that will run when the job is restarted or stopped. This script will run following a monit stop for all jobs on the VM in parallel.

---
## Job Configuration {: #job-configuration }

To add a post-deploy script to a release job:

1. Create a script with any name in the templates directory of a release job.
1. In the `templates` section of the release job spec file, add the script name and the `bin/post-stop` directory as a key value pair.

Example:

```yaml
---
name: cassandra_node
templates:
  post-stop.erb: bin/post-stop
```

---
## Script Implementation {: #script-implementation }

Post-stop script is usually just a regular shell script. Since post-start script is executed in a similar way as other release job scripts (start, stop, drain scripts) you can use job's package dependencies.

Post-stop script should be idempotent. It may be called multiple times after a process is stopped.


text:
package com.cezarykluczynski.stapi.model.comic_collection.query;

import com.cezarykluczynski.stapi.model.comic_collection.entity.ComicCollection;
import com.cezarykluczynski.stapi.model.common.cache.CachingStrategy;
import com.cezarykluczynski.stapi.model.common.query.AbstractQueryBuilderFactory;
import org.springframework.data.jpa.repository.JpaContext;
import org.springframework.stereotype.Service;

@Service
public class ComicCollectionQueryBuilderFactory extends AbstractQueryBuilderFactory<ComicCollection> {

	public ComicCollectionQueryBuilderFactory(JpaContext jpaContext, CachingStrategy cachingStrategy) {
		super(jpaContext, cachingStrategy, ComicCollection.class);
	}

}


text:
/*
 * Generated by XDoclet - Do not edit!
 */
package org.dcm4chex.archive.ejb.interfaces;

/**
 * Local interface for GPPPS.
 * @xdoclet-generated at ${TODAY}
 * @copyright The XDoclet Team
 * @author XDoclet
 * @version 2.19.0-SNAPSHOT
 */
public interface GPPPSLocal
   extends javax.ejb.EJBLocalObject
{
   /**
    * Auto-generated Primary Key
    */
   public java.lang.Long getPk(  ) ;

   public java.sql.Timestamp getCreatedTime(  ) ;

   public java.sql.Timestamp getUpdatedTime(  ) ;

   /**
    * SOP Instance UID
    */
   public java.lang.String getSopIuid(  ) ;

   /**
    * PPS Start Datetime
    */
   public java.sql.Timestamp getPpsStartDateTime(  ) ;

   public void setPpsStartDateTime( java.util.Date date ) ;

   public int getPpsStatusAsInt(  ) ;

   public void setPatient( org.dcm4chex.archive.ejb.interfaces.PatientLocal patient ) ;

   public org.dcm4chex.archive.ejb.interfaces.PatientLocal getPatient(  ) ;

   public void setGpsps( java.util.Collection gpsps ) ;

   public java.util.Collection getGpsps(  ) ;

   public boolean isInProgress(  ) ;

   public boolean isCompleted(  ) ;

   public boolean isDiscontinued(  ) ;

   public java.lang.String getPpsStatus(  ) ;

   public org.dcm4che.data.Dataset getAttributes(  ) ;

   public void setAttributes( org.dcm4che.data.Dataset ds ) ;

}


text:
var express = require('express');
var router = express.Router();
var path = require('path');
/* GET home page. */
router.get('/', function(req, res, next) {

  res.sendFile(path.resolve('./public/index.html'));
});

router.post('/checkAccount',function(req,res,next){
  var loginuser=req.body;

  auth.on('errormsg',function(msg){
    console.log('err',msg);
      res.send(msg);
  });

  auth.on('success',function(data){
    console.log(data);
    res.send(data);
  })
    auth.login(req.body.account,req.body.password);

});

module.exports = router;


text:
@interface MineChatViewController : BaseViewController

@property (nonatomic,copy) NSString *userId;

@end


text:
package madgik.exareme.common.app.engine.scheduler.elasticTree.logger;

import madgik.exareme.common.app.engine.scheduler.elasticTree.TreeQuery;
import madgik.exareme.common.art.PlanSessionStatistics;
import madgik.exareme.utils.units.Metrics;
import org.apache.log4j.Logger;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * @author heraldkllapi
 */
public class ElasticTreeLogger {
    public static final String SEP = "\t";

    private static final long start = System.currentTimeMillis();
    private static final Object lock = new Object();
    private static final Logger log = Logger.getLogger(ElasticTreeLogger.class);
    private static final DecimalFormat DF = new DecimalFormat("#.##");
    private static FileWriter writer = null;
    private static Map<Long, TreeQuery> issuedQueries = null;

    static {
        try {
            issuedQueries = Collections.synchronizedMap(new HashMap<Long, TreeQuery>());
            writer = new FileWriter(new File("TreeLog.log-" + start));
        } catch (IOException e) {
            // Ignore!
        }
    }

    public static void init() {
        write(Code.INIT + SEP + System.currentTimeMillis());
    }

    public static void registerQuery(TreeQuery query) {
        issuedQueries.put(query.id, query);
    }

    private static long time() {
        return System.currentTimeMillis() - start;
    }

    private static void write(String msg) {
        synchronized (lock) {
            try {
                writer.write(time() + "\t" + msg + "\n");
                writer.flush();
            } catch (IOException e) {
                log.error("Cannot write to log: " + msg, e);
            }
        }
    }

    public static void queryIssued(long id, TreeQuery query) {
        log.info("START");
        write(Code.QSTART + SEP + id);
    }

    public static void querySuccess(long id, PlanSessionStatistics stats) {
        log.info("SUCCESS");
        double execTime = 0;
        if (stats != null) {
            execTime = stats.endTime() - stats.startTime();
            execTime /= Metrics.MiliSec;
        } else {
            log.error("STATS IS NULL");
        }
        TreeQuery treeQuery = issuedQueries.get(id);
        write(Code.QSUCCESS + SEP + id + SEP + DF.format(execTime) + SEP +
            DF.format(treeQuery.getSLA().getBudget(execTime)));
    }

    public static void queryError(long id, PlanSessionStatistics stats) {
        log.info("ERROR");
        double execTime = 0;
        if (stats != null) {
            execTime = stats.endTime() - stats.startTime();
        } else {
            log.error("STATS IS NULL");
        }
        write(Code.QERROR + SEP + id);
    }

    public static void elasticTreeLevel(int level, double numCont, double numOps, double cpuLoad,
        double dataLoad, double cpuVar, double dataVar) {
        write(Code.ELASTIC_TREE + SEP + level + SEP +
            DF.format(numCont) + SEP +
            DF.format(numOps) + SEP +
            DF.format(cpuLoad) + SEP + DF.format(cpuVar) + SEP +
            DF.format(dataLoad) + SEP + DF.format(dataVar));
    }

    public static void money(double totalCost, double totalRevenue, double windowCost,
        double windowRevenue) {
        write(Code.MONEY + SEP +
            DF.format(totalCost) + SEP +
            DF.format(totalRevenue) + SEP +
            DF.format(totalRevenue - totalCost) + SEP +
            DF.format(windowCost) + SEP +
            DF.format(windowRevenue));
    }

    public static void queries(int totalQueries, int errorQueries, int runningQueries,
        int queuedQueries) {
        write(Code.QUERIES + SEP +
            totalQueries + SEP +
            errorQueries + SEP +
            runningQueries + SEP +
            queuedQueries);
    }

    public static void close() {
    }

    public static class Code {
        public static String INIT = "INIT";
        // Queries
        public static String QSTART = "QSTART";
        public static String QSUCCESS = "QSUCCESS";
        public static String QERROR = "QERROR";
        public static String QUERIES = "QUERIES";
        // Tree levels
        public static String ELASTIC_TREE = "ELASTIC";
        // Cost and profit
        public static String MONEY = "MONEY";
    }
}


text:
package com.commutestream.sdk;

import android.content.Context;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.ConsoleMessage;
import android.webkit.WebChromeClient;
import android.webkit.WebView;

public class HtmlAdControllerFactory {
    public static AdController create(final Context context, final AdEventListener listener,
                              final AdMetadata metadata, final byte[] content) {
        final String html = new String(content);

        // create a new webview and put the ad in it
        final WebView webView = new AdWebView(context, html);

        // This block allows JS console messages to be transported to LogCat
        webView.setWebChromeClient(new WebChromeClient() {
            public boolean onConsoleMessage(ConsoleMessage cm) {
                Log.v("CS_SDK_WebView",
                        cm.message() + " -- From line " + cm.lineNumber());
                return true;
            }
        });
        double xScale = (double)metadata.viewWidth/(double)metadata.adWidth;
        double yScale = (double)metadata.viewHeight/(double)metadata.adHeight;
        double scale = Math.min(yScale, xScale);
        int width = (int)Math.floor(scale*(double)metadata.adWidth + 0.5);
        int height = (int)Math.floor(scale*(double)metadata.adHeight + 0.5);

        webView.setLayoutParams(new ViewGroup.LayoutParams(width, height));
        webView.setVerticalScrollBarEnabled(false);
        webView.setHorizontalScrollBarEnabled(false);
        webView.getSettings().setJavaScriptEnabled(true);

        webView.getSettings().setUseWideViewPort(true);
        webView.getSettings().setLoadWithOverviewMode(true);
        webView.getSettings().setDomStorageEnabled(true);

        final UrlHandler urlHandler = new UrlHandler(context);
        final AdController adController = new AdController(context, metadata, webView, urlHandler);

        webView.setWebViewClient(new WebClient(urlHandler));
        webView.loadData(html, "text/html", null);
        return adController;
    }
}


text:
package com.sun.jini.test.spec.lookupservice.test_set02;
import com.sun.jini.qa.harness.QAConfig;

import java.util.logging.Level;

import com.sun.jini.qa.harness.TestException;
import net.jini.core.lookup.ServiceRegistrar;
import net.jini.core.lookup.ServiceTemplate;
import java.rmi.RemoteException;

/**
 * This class is used to verify that doing a notify with a negative lease
 * duration results in an IllegalArgumentException.
 */
public class NotifyNegDuration extends NotifyExceptionTest {

    public void run() throws Exception {
	try {
	    getProxy().notify(new ServiceTemplate(null, null, null),
			      ServiceRegistrar.TRANSITION_MATCH_MATCH,
			      listener, null, -500);
	    throw new TestException("notify did not "
				  + "throw IllegalArgumentException");
	} catch (IllegalArgumentException e) {
	}
    }
}


text:
package com.wemote.leo.quickstart.account.domain;

import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheManager;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author : jayon.xu@gmail.com
 */
public class RetryLimitHashedCredentialsMatcher extends HashedCredentialsMatcher {

    private static final String PASSWORD_RETRY_CACHE_NAME = "passwordRetryCache";
    private static final Integer AUTHC_RETRY_COUNT = 5;

    private Cache<String, AtomicInteger> passwordRetryCache;

    public RetryLimitHashedCredentialsMatcher(CacheManager cacheManager) {
        passwordRetryCache = cacheManager.getCache(PASSWORD_RETRY_CACHE_NAME);
    }

    @Override
    public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {
        String username = (String) token.getPrincipal();
        //retry count + 1
        AtomicInteger retryCount = passwordRetryCache.get(username);
        if (retryCount == null) {
            retryCount = new AtomicInteger(0);
            passwordRetryCache.put(username, retryCount);
        }
        if (retryCount.incrementAndGet() > AUTHC_RETRY_COUNT) {
            //if retry count > 5 throw
            throw new ExcessiveAttemptsException("Excessive attempts exception.");
        }

        boolean matches = super.doCredentialsMatch(token, info);
        if (matches) {
            //clear retry count
            passwordRetryCache.remove(username);
        }
        return matches;
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Bull. Jard. Bot. Nat. Belg. 57(3-4): 375 (1987)

#### Original name
Laurera kundaraensis Upreti & Ajay Singh

### Remarks
null


text:
using System;
using Android.Media;
using Xamarin.Forms;

[assembly: Dependency(typeof(MonkeyTapWithSound.Droid.PlatformSoundPlayer))]

namespace MonkeyTapWithSound.Droid
{
    public class PlatformSoundPlayer : IPlatformSoundPlayer
    {
        AudioTrack previousAudioTrack;

        public void PlaySound(int samplingRate, byte[] pcmData)
        {
            if (previousAudioTrack != null)
            {
                previousAudioTrack.Stop();
                previousAudioTrack.Release();
            }

            AudioTrack audioTrack = new AudioTrack(Stream.Music,
                                                   samplingRate,
                                                   ChannelOut.Mono,
                                                   Android.Media.Encoding.Pcm16bit,
                                                   pcmData.Length * sizeof(short),
                                                   AudioTrackMode.Static);

            audioTrack.Write(pcmData, 0, pcmData.Length);
            audioTrack.Play();

            previousAudioTrack = audioTrack;
        }
    }
}


text:
package io.crate.replication.logical.exceptions;

import io.crate.exceptions.ConflictException;
import io.crate.exceptions.UnscopedException;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.common.io.stream.StreamInput;

import java.io.IOException;
import java.util.Locale;

public class PublicationAlreadyExistsException extends ElasticsearchException implements ConflictException, UnscopedException {

    public PublicationAlreadyExistsException(String name) {
        super(String.format(Locale.ENGLISH, "Publication '%s' already exists", name));
    }

    public PublicationAlreadyExistsException(StreamInput in) throws IOException {
        super(in);
    }
}


text:
layout: article
title: "Weekly Word: Reticent"
date: 2007-12-06 18:53
cats: [english]
---
This sounds like an SAT word if I ever memorized one: reticent, an adjective meaning "restrained", "reluctant", or "disposed to be silent or not to speak freely". The noun form is reticence.

Photo by wen@flickr

According to the Online Etymology Dictionary, the word comes from Latin reticere, meaning "keep silent", from the re- prefix and tacere, meaning "be silent". The words tacit and taciturn also stem from that Latin root.

World Wide Words points out that even though some dictionaries define reticent as "reluctant", many believe that it shouldn't be used that way. "Reticent refers to a subset of the meaning of reluctant. Compare 'He