text:
```js
// using ES6 modules
import { registerAssertions } from 'redux-actions-assertions/expectjs';

// using CommonJS modules
var registerAssertions = require('redux-actions-assertions/expectjs').registerAssertions;

// registration
registerAssertions();
```

## Usage

### .dispatchActions

> `expect(action).to.dispatchActions(expectedActions, callback)`

Asserts that when given `action` is dispatched it will dispatch `expectedActions`. `action` can be plain object (action) or function (action creator). `expectedActions` can be can be plain object (action) or function (action creator) or array of objects/functions.

```js
expect(myActionCreator())
  .to.dispatchActions({ type: 'MY_ACTION_START' }, callback);
```

### .not.dispatchActions

> `expect(action).not.to.dispatchActions(expectedActions, callback)`
> `expect(action).to.not.dispatchActions(expectedActions, callback)`

Asserts that when given `action` is dispatched it will not dispatch `expectedActions`. `action` can be plain object (action) or function (action creator). `expectedActions` can be can be plain object (action) or function (action creator) or array of objects/functions.

```js
expect(myActionCreator())
  .not.to.dispatchActions({ type: 'MY_ACTION_START' }, callback);

expect(myActionCreator())
  .to.not.dispatchActions({ type: 'MY_ACTION_START' }, callback);
```

### .withState

> `expect(action).withState(state).to.dispatchActions(expectedActions, callback)`

Asserts that store initialised with `state` before `action` is dispatched.

```js
expect(myActionCreator())
  .withState({ property: 'value' })
  .to.dispatchActions([{ type: 'MY_ACTION_START' }, finishActionCreator()], callback);
```


text:
namespace url {
class Origin;
}

namespace content {

class AgentSchedulingGroupHost;
class BrowserContext;
class BrowsingInstance;
class SiteInstanceGroup;
class StoragePartitionConfig;
class StoragePartitionImpl;
struct UrlInfo;

class CONTENT_EXPORT SiteInstanceImpl final : public SiteInstance {
 public:
  SiteInstanceImpl(const SiteInstanceImpl&) = delete;
  SiteInstanceImpl& operator=(const SiteInstanceImpl&) = delete;

  // Methods for creating a new SiteInstance in a new BrowsingInstance. The
  // documentation for these methods are on the SiteInstance::Create* methods
  // with the same name.
  static scoped_refptr<SiteInstanceImpl> Create(
      BrowserContext* browser_context);
  static scoped_refptr<SiteInstanceImpl> CreateForGuest(
      BrowserContext* browser_context,
      const StoragePartitionConfig& partition_config);
  static scoped_refptr<SiteInstanceImpl> CreateForFencedFrame(
      SiteInstanceImpl* embedder_site_instance);

  // Similar to above, but creates an appropriate SiteInstance in a new
  // BrowsingInstance for a particular `url_info`. This is a more generic
  // version of SiteInstance::CreateForURL(). `url_info` contains the GURL for
  // which we want to create a SiteInstance, along with other state relevant to
  // making process allocation decisions. `is_guest` specifies whether the
  // newly SiteInstance and BrowsingInstance is for a <webview> guest. This is
  // used in site-isolated guests to support cross-BrowsingInstance navigations
  // within a guest; when true, the guest's StoragePartition information must
  // also be provided in `url_info`. `is_fenced` specifies if the
  // BrowsingInstance is for a fenced frame, and is used to isolate them from
  // non-fenced BrowsingInstances.
  static scoped_refptr<SiteInstanceImpl> CreateForUrlInfo(
      BrowserContext* browser_context,
      const UrlInfo& url_info,
      bool is_guest,
      bool is_fenced);

  // Creates a SiteInstance that will be use for a service worker.
  // `url_info` - The UrlInfo for the service worker. It contains the URL and
  //              other information necessary to take process model decisions.
  //
  //              Note: if `is_guest` is false, the URL is the main script URL.
  //              If `is_guest` is true, it is the <webview> guest site URL.
  //
  //              Note: `url_info`'s web_exposed_isolation_info indicates the
  //              web-exposed isolation state of the main script (note that
  //              ServiceWorker "cross-origin isolation" does not require
  //              Cross-Origin-Opener-Policy to be set).
  //
  // `can_reuse_process` - Set to true if the new SiteInstance can use the
  //                       same process as the renderer for `url_info`.
  // `is_guest` - Set to true if the new SiteInstance is for a <webview>
  // guest.
  // `is_fenced` - Set to true if the new SiteInstance is for a service worker
  // initialized by a fenced frame.
  static scoped_refptr<SiteInstanceImpl> CreateForServiceWorker(
      BrowserContext* browser_context,
      const UrlInfo& url_info,
      bool can_reuse_process = false,
      bool is_guest = false,
      bool is_fenced = false);

  // Creates a SiteInstance for |url| like CreateForUrlInfo() would except the
  // instance that is returned has its process_reuse_policy set to
  // REUSE_PENDING_OR_COMMITTED_SITE and the default SiteInstance will never
  // be returned.
  static scoped_refptr<SiteInstanceImpl> CreateReusableInstanceForTesting(
      BrowserContext* browser_context,
      const GURL& url);

  // Creates a SiteInstance for |url| in a new BrowsingInstance for testing
  // purposes. This works similarly to CreateForUrlInfo() but with default
  // parameters that are suitable for most tests.
  static scoped_refptr<SiteInstanceImpl> CreateForTesting(
      BrowserContext* browser_context,
      const GURL& url);

  static bool ShouldAssignSiteForURL(const GURL& url);

  // Returns the SiteInstanceGroup |this| belongs to.
  // Currently, each SiteInstanceGroup has exactly one SiteInstance, but that
  // will change as the migration continues. See crbug.com/1195535.
  SiteInstanceGroup* group() { return site_instance_group_.get(); }

  // Use this to get a related SiteInstance during navigations, where UrlInfo
  // may be requesting opt-in isolation. Outside of navigations, callers just
  // looking up an existing SiteInstance based on a GURL can use
  // GetRelatedSiteInstance (overridden from SiteInstance).
  scoped_refptr<SiteInstanceImpl> GetRelatedSiteInstanceImpl(
      const UrlInfo& url_info);
  bool IsSameSiteWithURLInfo(const UrlInfo& url_info);

  // Returns an AgentSchedulingGroupHost, or creates one if
  // `site_instance_group_` doesn't have one.
  AgentSchedulingGroupHost& GetOrCreateAgentSchedulingGroup();

  // Resets the `site_instance_group_` refptr, and must be called when its
  // RenderProcessHost goes away. `site_instance_group_` can be reassigned later
  // as needed.
  void ResetSiteInstanceGroup();

  // SiteInstance implementation.
  SiteInstanceId GetId() override;
  BrowsingInstanceId GetBrowsingInstanceId() override;
  bool HasProcess() override;
  RenderProcessHost* GetProcess() override;
  BrowserContext* GetBrowserContext() override;
  const GURL& GetSiteURL() override;
  const StoragePartitionConfig& GetStoragePartitionConfig() override;
  scoped_refptr<SiteInstance> GetRelatedSiteInstance(const GURL& url) override;
  bool IsRelatedSiteInstance(const SiteInstance* instance) override;
  size_t GetRelatedActiveContentsCount() override;
  bool RequiresDedicatedProcess() override;
  bool RequiresOriginKeyedProcess() override;
  bool IsSameSiteWithURL(const GURL& url) override;
  bool IsGuest() override;
  SiteInstanceProcessAssignment GetLastProcessAssignmentOutcome() override;
  void WriteIntoTrace(perfetto::TracedProto<TraceProto> context) override;
  int EstimateOriginAgentClusterOverheadForMetrics() override;

  // This is called every time a renderer process is assigned to a SiteInstance
  // and is used by the content embedder for collecting metrics.
  void set_process_assignment(SiteInstanceProcessAssignment assignment) {
    process_assignment_ = assignment;
  }

  // The policy to apply when selecting a RenderProcessHost for the
  // SiteInstance. If no suitable RenderProcessHost for the SiteInstance exists
  // according to the policy, and there are processes with unmatched service
  // workers for the site, the newest process with an unmatched service worker
  // is reused. If still no RenderProcessHost exists a new RenderProcessHost
  // will be created unless the process limit has been reached. When the limit
  // has been reached, the RenderProcessHost reused will be chosen randomly and
  // not based on the site.
  enum class ProcessReusePolicy {
    // In this mode, all instances of the site will be hosted in the same
    // RenderProcessHost.
    PROCESS_PER_SITE,

    // In this mode, the site will be rendered in a RenderProcessHost that is
    // already in use for the site, either for a pending navigation or a
    // committed navigation. If multiple such processes exist, ones that have
    // foreground frames are given priority, and otherwise one is selected
    // randomly.
    REUSE_PENDING_OR_COMMITTED_SITE,

    // In this mode, SiteInstances don't proactively reuse processes. An
    // existing process with an unmatched service worker for the site is reused
    // only for navigations, not for service workers. When the process limit has
    // been reached, a randomly chosen RenderProcessHost is reused as in the
    // other policies.
    DEFAULT,
  };

  void set_process_reuse_policy(ProcessReusePolicy policy) {
    CHECK(!IsDefaultSiteInstance());
    process_reuse_policy_ = policy;
  }
  ProcessReusePolicy process_reuse_policy() const {
    return process_reuse_policy_;
  }

  // Returns true if |has_site_| is true and |site_info_| indicates that the
  // process-per-site model should be used.
  bool ShouldUseProcessPerSite() const;

  // Checks if |current_process| can be reused for this SiteInstance, and
  // sets |process_| to |current_process| if so.
  void ReuseCurrentProcessIfPossible(RenderProcessHost* current_process);

  // Whether the SiteInstance is created for a service worker. If this flag
  // is true, when a new process is created for this SiteInstance or a randomly
  // chosen existing process is reused because of the process limit, the process
  // will be tracked as having an unmatched service worker until reused by
  // another SiteInstance from the same site.
  bool is_for_service_worker() const { return is_for_service_worker_; }

  // Returns the URL which was used to set the |site_info_| for this
  // SiteInstance. May be empty if this SiteInstance does not have a
  // |site_info_|.
  const GURL& original_url() {
    DCHECK(!IsDefaultSiteInstance());
    return original_url_;
  }

  // This is primarily a helper for RenderFrameHostImpl::IsNavigationSameSite();
  // most callers should use that API.
  //
  // Returns true if navigating a frame with (|last_successful_url| and
  // |last_committed_origin|) to |dest_url_info| should stay in the same
  // SiteInstance to preserve scripting relationships. |dest_url_info| carries
  // additional state, e.g. if the destination url requests origin isolation.
  //
  // |for_outermost_main_frame| is set to true if the caller is interested in an
  // answer for a outermost main frame. This is set to false for subframe or
  // embedded main frame (eg fenced frame) navigations.  Note: In some
  // circumstances, like hosted apps, different answers can be returned if we
  // are navigating an outermost main frame instead of an embedded frame.
  bool IsNavigationSameSite(const GURL& last_successful_url,
                            const url::Origin& last_committed_origin,
                            bool for_outermost_main_frame,
                            const UrlInfo& dest_url_info);

  // Returns true if a navigation to |dest_url| should be allowed to stay in
  // the current process due to effective URLs being involved in the
  // navigation, even if the navigation would normally result in a new process.
  //
  // This is needed to avoid BrowsingInstance swaps in cases where same-site
  // navigations transition from a hosted app to a non-hosted app URL and must
  // be kept in the same process due to scripting requirements.
  bool IsNavigationAllowedToStayInSameProcessDueToEffectiveURLs(
      BrowserContext* browser_context,
      bool for_main_frame,
      const GURL& dest_url);

  // SiteInfo related functions.

  // Returns the SiteInfo principal identifying all documents and workers within
  // this SiteInstance.
  // TODO(wjmaclean): eventually this function will replace const GURL&
  // GetSiteURL().
  const SiteInfo& GetSiteInfo();

  // Derives a new SiteInfo based on this SiteInstance's current state, and
  // the information provided in `url_info`. This function is slightly different
  // than SiteInfo::Create() because it takes into account information
  // specific to this SiteInstance, like whether it is a guest or not, and
  // changes its behavior accordingly. `is_related` - Controls the SiteInfo
  // returned for non-guest SiteInstances.
  //  Set to true if the caller wants the SiteInfo for an existing related
  //  SiteInstance associated with `url_info`. This is identical to what you
  //  would get from GetRelatedSiteInstanceImpl(url_info)->GetSiteInfo(). This
  //  may return the SiteInfo for the default SiteInstance so callers must be
  //  prepared to deal with that. If set to false, a SiteInfo created with
  //  SiteInfo::Create() is returned.
  //
  // For guest SiteInstances, `site_info_` is returned because guests are not
  // allowed to derive new guest SiteInfos. All guest navigations must stay in
  // the same SiteInstance with the same SiteInfo.
  //
  // Note: Since we're deriving the state of the SiteInfo based on both UrlInfo
  // and SiteInstance, we verify internally that their WebExposedIsolationInfos
  // are compatible.
  SiteInfo DeriveSiteInfo(const UrlInfo& url_info, bool is_related = false);

  // Helper function that returns the storage partition domain for this
  // object.
  // This is a temporary helper function used to verify that
  // the partition domain computed using this SiteInstance's site URL matches
  // the partition domain returned by storage_partition->GetPartitionDomain().
  // If there is a mismatch, we call DumpWithoutCrashing() and return the value
  // computed from the site URL since that is the legacy behavior.
  //
  // TODO(acolwell) : Remove this function and update callers to directly call
  // storage_partition->GetPartitionDomain() once we've verified that this is
  // safe.
  std::string GetPartitionDomain(StoragePartitionImpl* storage_partition);

  // Returns true if this SiteInstance is for a site that has JIT disabled.
  bool IsJitDisabled();

  // Returns true if this SiteInstance is for a site that contains PDF contents.
  bool IsPdf();

  // Set the web site that this SiteInstance is rendering pages for.
  // This includes the scheme and registered domain, but not the port.  If the
  // URL does not have a valid registered domain, then the full hostname is
  // stored. This method does not convert this instance into a default
  // SiteInstance, but the BrowsingInstance will call this method with
  // |url_info| set to GetDefaultSiteURL(), when it is creating its default
  // SiteInstance.
  void SetSite(const UrlInfo& url_info);

  // Same as above, but for SiteInfo. The above version should be used in most
  // cases, unless the UrlInfo is unavailable, such as for sandboxed srcdoc
  // frames.
  void SetSite(const SiteInfo& site_info);

  // Similar to SetSite(), but first attempts to convert this object to a
  // default SiteInstance if |url_info| can be placed inside a default
  // SiteInstance. If conversion is not possible, then the normal SetSite()
  // logic is run.
  void ConvertToDefaultOrSetSite(const UrlInfo& url_info);

  // Returns whether SetSite() has been called.
  bool HasSite() const;

  // Returns whether there is currently a related SiteInstance (registered with
  // BrowsingInstance) for the given SiteInfo.  If so, we should try to avoid
  // dedicating an unused SiteInstance to it (e.g., in a new tab).
  bool HasRelatedSiteInstance(const SiteInfo& site_info);

  // Returns whether this SiteInstance is compatible with and can host the given
  // |url_info|. If not, the browser should force a SiteInstance swap when
  // navigating to the URL in |url_info|.
  bool IsSuitableForUrlInfo(const UrlInfo& url_info);

  // Increase the number of active WebContentses using this SiteInstance. Note
  // that, unlike active_frame_count, this does not count pending RFHs.
  void IncrementRelatedActiveContentsCount();

  // Decrease the number of active WebContentses using this SiteInstance. Note
  // that, unlike active_frame_count, this does not count pending RFHs.
  void DecrementRelatedActiveContentsCount();

  // Whether GetProcess() method (when it needs to find a new process to
  // associate with the current SiteInstanceImpl) can return a spare process.
  bool CanAssociateWithSpareProcess();

  // Has no effect if the SiteInstanceImpl already has a |process_|.
  // Otherwise, prevents GetProcess() from associating this SiteInstanceImpl
  // with the spare RenderProcessHost - instead GetProcess will either need to
  // create a new, not-yet-initialized/spawned RenderProcessHost or will need to
  // reuse one of existing RenderProcessHosts.
  //
  // See also:
  // - https://crbug.com/840409.
  // - WebContents::CreateParams::desired_renderer_state
  // - SiteInstanceImpl::CanAssociateWithSpareProcess().
  void PreventAssociationWithSpareProcess();

  // Returns the special site URL used by the default SiteInstance.
  static const GURL& GetDefaultSiteURL();

  // Get the effective URL for the given actual URL.  This allows the
  // ContentBrowserClient to override the SiteInstance's site for certain URLs.
  // For example, Chrome uses this to replace hosted app URLs with extension
  // hosts.
  // Only public so that we can make a consistent process swap decision in
  // RenderFrameHostManager.
  static GURL GetEffectiveURL(BrowserContext* browser_context, const GURL& url);

  // True if |url| resolves to an effective URL that is different from |url|.
  // See GetEffectiveURL().  This will be true for hosted apps as well as NTP
  // URLs.
  static bool HasEffectiveURL(BrowserContext* browser_context, const GURL& url);

  // Return an ID of the next BrowsingInstance to be created.  This ID is
  // guaranteed to be higher than any ID of an existing BrowsingInstance.
  // This is useful when process model decisions need to be scoped only to
  // future BrowsingInstances.  In particular, this can determine the cutoff in
  // BrowsingInstance IDs when adding a new isolated origin dynamically.
  static BrowsingInstanceId NextBrowsingInstanceId();

  // Return the IsolationContext associated with this SiteInstance.  This
  // specifies context for making process model decisions, such as information
  // about the current BrowsingInstance.
  const IsolationContext& GetIsolationContext();

  // Returns a process suitable for this SiteInstance if the
  // SiteInstanceGroupManager has one available. A null pointer will be returned
  // if this SiteInstance's group does not have a process yet or the
  // SiteInstanceGroupManager does not have a default process that can be reused
  // by this SiteInstance.
  RenderProcessHost* GetSiteInstanceGroupProcessIfAvailable();

  // Returns true if this object was constructed as a default site instance.
  bool IsDefaultSiteInstance() const;

  // Returns true if |site_url| is a site url that the BrowsingInstance has
  // associated with its default SiteInstance.
  bool IsSiteInDefaultSiteInstance(const GURL& site_url) const;

  // Returns true if the SiteInfo for |url_info| matches the SiteInfo for this
  // instance (i.e. GetSiteInfo()). Otherwise returns false.
  bool DoesSiteInfoForURLMatch(const UrlInfo& url_info);

  // Adds |origin| as having the default isolation state within this
  // BrowsingInstance due to an existing instance at the time of opt-in, so that
  // future instances of it here won't be origin isolated.
  void RegisterAsDefaultOriginIsolation(
      const url::Origin& previously_visited_origin);

  // Returns the web-exposed isolation status of the BrowsingInstance this
  // SiteInstance is part of.
  const WebExposedIsolationInfo& GetWebExposedIsolationInfo() const;

  // Simple helper function that returns the is_isolated property of the
  // WebExposedIsolationInfo of this BrowsingInstance.
  bool IsCrossOriginIsolated() const;

  // Finds an existing SiteInstance in this SiteInstance's BrowsingInstance that
  // matches this `url_info` but with the `is_sandboxed_` flag true. It's
  // assumed that `url_info.url` is 'about:srcdoc' here, so the new SiteInstance
  // will use `parent_origin`. If an existing SiteInstance isn't found, a new
  // one is created in the same BrowsingInstance. Note that this SiteInstance
  // must have had its SiteInfo already assigned via SetSite() before calling
  // this function.
  scoped_refptr<SiteInstanceImpl> GetCompatibleSandboxedSiteInstance(
      const UrlInfo& url_info,
      const url::Origin& parent_origin);

  // Returns the process used by non-isolated sites in this SiteInstance's
  // BrowsingInstance.
  RenderProcessHost* GetDefaultProcessForBrowsingInstance();

 private:
  friend class BrowsingInstance;
  friend class SiteInstanceTestBrowserClient;

  // Friend tests that need direct access to IsSameSite().
  friend class SiteInstanceTest;

  // Create a new SiteInstance.  Only BrowsingInstance should call this
  // directly; clients should use Create() or GetRelatedSiteInstance() instead.
  explicit SiteInstanceImpl(BrowsingInstance* browsing_instance);

  ~SiteInstanceImpl() override;

  // Returns true when |this| has a SiteInstanceGroup.
  bool has_group() { return group() != nullptr; }

  // Used to restrict a process' origin access rights. This method gets called
  // when a process gets assigned to this SiteInstance and when the
  // SiteInfo is explicitly set. If the SiteInfo hasn't been set yet and
  // the current process lock is invalid, then this method sets the process
  // to an "allow_any_site" lock. If the SiteInfo gets set to something that
  // restricts access to a specific site, then the lock will be upgraded to a
  // "lock_to_site" lock.
  void LockProcessIfNeeded();

  // If kProcessSharingWithStrictSiteInstances is enabled, this will check
  // whether both a site and a process have been assigned to this SiteInstance,
  // and if this doesn't require a dedicated process, will offer process_ to
  // BrowsingInstance as the default process for SiteInstances that don't need
  // a dedicated process.
  void MaybeSetBrowsingInstanceDefaultProcess();

  // Sets the SiteInfo and other fields so that this instance becomes a
  // default SiteInstance.
  void SetSiteInfoToDefault(
      const StoragePartitionConfig& storage_partition_config);

  // Sets |site_info_| with |site_info| and registers this object with
  // |browsing_instance_|. SetSite() calls this method to set the site and lock
  // for a user provided URL. This method should only be called by code that
  // need to set the site and lock directly without any "url to site URL"
  // transformation.
  void SetSiteInfoInternal(const SiteInfo& site_info);

  // Helper method to set the process of this SiteInstance, only in cases
  // where it is safe. It is not generally safe to change the process of a
  // SiteInstance, unless the RenderProcessHost itself is entirely destroyed and
  // a new one later replaces it.
  void SetProcessInternal(RenderProcessHost* process);

  // Returns true if |original_url()| is the same site as
  // |dest_url_info| or this object is a default SiteInstance and can be
  // considered the same site as |dest_url_info|.
  bool IsOriginalUrlSameSite(const UrlInfo& dest_url_info,
                             bool should_compare_effective_urls);

  // Add |site_info| to the set that tracks what sites have been allowed
  // to be handled by this default SiteInstance.
  void AddSiteInfoToDefault(const SiteInfo& site_info);

  // Return whether both UrlInfos must share a process to preserve script
  // relationships.  The decision is based on a variety of factors such as
  // the registered domain of the URLs (google.com, bbc.co.uk), the scheme
  // (https, http), and isolated origins.  Note that if the destination is a
  // blank page, we consider that to be part of the same web site for the
  // purposes for process assignment.  |should_compare_effective_urls| allows
  // comparing URLs without converting them to effective URLs first.  This is
  // useful for avoiding OOPIFs when otherwise same-site URLs may look
  // cross-site via their effective URLs.
  // Note: This method is private because it is an internal detail of this class
  // and there is subtlety around how it can be called because of hosted
  // apps. Most code outside this class should call
  // RenderFrameHostImpl::IsNavigationSameSite() instead.
  static bool IsSameSite(const IsolationContext& isolation_context,
                         const UrlInfo& src_url_info,
                         const UrlInfo& dest_url_info,
                         bool should_compare_effective_urls);

  // Returns true if |url| and its |site_url| can be placed inside a default
  // SiteInstance.
  //
  // Note: |url| and |site_info| must be consistent with each other. In contexts
  // where the caller only has |url| it can use
  // SiteInfo::Create() to generate |site_info|. This call is
  // intentionally not set as a default value to encourage the caller to reuse
  // a SiteInfo computation if they already have one.
  static bool CanBePlacedInDefaultSiteInstance(
      const IsolationContext& isolation_context,
      const GURL& url,
      const SiteInfo& site_info);

  // A unique ID for this SiteInstance.
  SiteInstanceId id_;

  // Determines which RenderViewHosts, RenderWidgetHosts, and
  // RenderFrameProxyHosts it uses.
  // `site_instance_group_` is set when a RenderProcessHost is set for this
  // SiteInstance, and will be how `this` gets its RenderProcessHost and
  // AgentSchedulingGroup.
  // If the RenderProcessHost goes away, `site_instance_group_` will get reset.
  // It can be set to another group later on as needed.
  // See the class-level comment of SiteInstanceGroup for more details.
  scoped_refptr<SiteInstanceGroup> site_instance_group_;

  // BrowsingInstance to which this SiteInstance belongs.
  scoped_refptr<BrowsingInstance> browsing_instance_;

  // Describes the desired behavior when GetProcess() method needs to find a new
  // process to associate with the current SiteInstanceImpl.  If |false|, then
  // prevents the spare RenderProcessHost from being taken and stored in
  // |process_|.
  bool can_associate_with_spare_process_;

  // The SiteInfo that this SiteInstance is rendering pages for.
  SiteInfo site_info_;

  // Whether SetSite has been called.
  bool has_site_;

  // The URL which was used to set the |site_info_| for this SiteInstance.
  GURL original_url_;

  // The ProcessReusePolicy to use when creating a RenderProcessHost for this
  // SiteInstance.
  ProcessReusePolicy process_reuse_policy_;

  // Whether the SiteInstance was created for a service worker.
  bool is_for_service_worker_;

  // How |this| was last assigned to a renderer process.
  SiteInstanceProcessAssignment process_assignment_;

  // Contains the state that is only required for default SiteInstances.
  class DefaultSiteInstanceState;
  std::unique_ptr<DefaultSiteInstanceState> default_site_instance_state_;

  // Keeps track of whether we need to verify that the StoragePartition
  // information does not change when `site_info_` is set.
  bool verify_storage_partition_info_ = false;
};

}  // namespace content

#endif  // CONTENT_BROWSER_SITE_INSTANCE_IMPL_H_

redpajama_set_name: RedPajamaGithub


text:
package com.sudicode.fb2gh.github;

import com.sudicode.fb2gh.FB2GHException;

import java.util.List;

/**
 * GitHub repository.
 */
public interface GHRepo {

    /**
     * Create a milestone.
     *
     * @param title The title of the milestone
     * @return The milestone
     * @throws FB2GHException if a GitHub error occurs
     */
    GHMilestone addMilestone(final String title) throws FB2GHException;

    /**
     * Get a single milestone.
     *
     * @param number The number of the milestone
     * @return The milestone
     * @throws FB2GHException if a GitHub error occurs
     */
    GHMilestone getMilestone(int number) throws FB2GHException;

    /**
     * Get all milestones within this repository.
     *
     * @return A list of the milestones.
     * @throws FB2GHException if a GitHub error occurs
     */
    List<GHMilestone> getMilestones() throws FB2GHException;

    /**
     * Create an issue.
     *
     * @param title       Title of the issue
     * @param description Description of the issue
     * @return The created issue
     * @throws FB2GHException if a GitHub error occurs
     */
    GHIssue addIssue(final String title, final String description) throws FB2GHException;

    /**
     * Get an issue by number.
     *
     * @param number Number of the issue
     * @return The issue
     */
    GHIssue getIssue(final int number);

    /**
     * Add a label.
     *
     * @param label The label to add.
     * @throws FB2GHException if a GitHub error occurs
     */
    void addLabel(final GHLabel label) throws FB2GHException;

    /**
     * Get the labels within this repository.
     *
     * @return A list of the labels.
     * @throws FB2GHException if a GitHub error occurs
     */
    List<GHLabel> getLabels() throws FB2GHException;

    /**
     * @return The owner of this repository.
     */
    String getOwner();

    /**
     * @return The name of this repository.
     */
    String getName();

}


text:
namespace Dike.Core.Authorization
{
    using System.ComponentModel.DataAnnotations;
    using System.ComponentModel.DataAnnotations.Schema;

    /// <summary>
    /// Abstract entity class to store permissions for a role or user.
    /// </summary>
    /// <seealso cref="Dike.Core.Domain.Entities.Auditing.CreationAuditedEntity{TPrimaryKey}" />
    /// <seealso cref="Dike.Core.Domain.Entities.IMayHaveTenant" />
    [Table("Permissions")]
    public abstract class PermissionSetting
        : Domain.Entities.Auditing.CreationAuditedEntity<long>, Domain.Entities.IMayHaveTenant
    {
        #region Fields

        /// <summary>
        /// Maximum length of the <see cref="Name"/> field.
        /// </summary>
        public const int MaxNameLength = 128;

        #endregion Fields

        #region Constructors

        /// <summary>
        /// Initializes a new instance of the <see cref="PermissionSetting"/> class.
        /// </summary>
        protected PermissionSetting()
        {
            IsGranted = true;
        }

        #endregion Constructors

        #region Properties

        /// <summary>
        /// Gets or sets a value indicating whether this permission is granted.
        /// </summary>
        /// <value><c>true</c> if this permission is granted; otherwise, <c>false</c>.</value>
        public virtual bool IsGranted
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the permission name.
        /// </summary>
        /// <value>The permission name.</value>
        [Required]
        [MaxLength(MaxNameLength)]
        public virtual string Name
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the tenant identifier for tenant-level permissions.
        /// </summary>
        /// <value>The tenant identifier for tenant-level permissions.</value>
        public virtual int? TenantId
        {
            get;
            set;
        }

        #endregion Properties
    }
}


text:
using System;
using Enigma.ProofOfConcept.Context;

namespace Enigma.ProofOfConcept
{
    public class InstrumentationProfiling : IConsoleCommand
    {
        public void Invoke()
        {
            ContextStressTest.SetupBasicCategoriesAndUsers();

            var beganWriting5000PostsOn1Thread = DateTime.Now;
            Console.WriteLine("Preparing to write 5000 posts on 1 thread");
            using (var context = new CommunityContext()) {
                for (var i = 0; i < 5000; i++)
                    context.Articles.Add(ContextStressTest.CreateUniqueArticle());

                var count = context.SaveChanges();

                Console.WriteLine("Saved {0} additional articles in the database, time taken: {1}", count, DateTime.Now.Subtract(beganWriting5000PostsOn1Thread));
            }
        }
    }
}


text:
Outage Menu

            Outage ID:
            <input ng-model="id" type="text" name="id" />
            <button ng-href="#/outages/{{id}}">Get details</button>

Current outages

All outages

Outages and Service Level Availability

Outages are tracked by OpenNMS by polling services that have been
            provisioned.  If the service does not respond to the poll, a service outage
            is created and service availability levels are impacted.  Service
            outages create notifications.


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
null

#### Original name
Mycogala macrospora Jaap, 1910

### Remarks
null


text:
#ifndef __CC_TRIANGLES_COMMAND__
#define __CC_TRIANGLES_COMMAND__

#include "renderer/CCRenderCommand.h"
#include "renderer/CCGLProgramState.h"

/**
 * @addtogroup renderer
 * @{
 */

NS_CC_BEGIN
/**
 Command used to render one or more Triangles, which is similar to QuadCommand.
 Every TrianglesCommand will have generate material ID by give textureID, glProgramState, Blend function
 if the material id is the same, these TrianglesCommands could be batched to save draw call.
*/
class CC_DLL TrianglesCommand : public RenderCommand
{
public:
    /**The structure of Triangles. */
    struct Triangles
    {
        /**Vertex data pointer.*/
        V3F_C4B_T2F* verts;
        /**Index data pointer.*/
        unsigned short* indices;
        /**The number of vertices.*/
        int vertCount;
        /**The number of indices.*/
        int indexCount;
    };
    /**Constructor.*/
    TrianglesCommand();
    /**Destructor.*/
    ~TrianglesCommand();

    /** Initializes the command.
     @param globalOrder GlobalZOrder of the command.
     @param textureID The openGL handle of the used texture.
     @param glProgramState The specified glProgram and its uniform.
     @param blendType Blend function for the command.
     @param triangles Rendered triangles for the command.
     @param mv ModelView matrix for the command.
     @param flags to indicate that the command is using 3D rendering or not.
     */
    void init(float globalOrder, GLuint textureID, GLProgramState* glProgramState, BlendFunc blendType, const Triangles& triangles,const Mat4& mv, uint32_t flags);
    /**Deprecated function, the params is similar as the upper init function, with flags equals 0.*/
    CC_DEPRECATED_ATTRIBUTE void init(float globalOrder, GLuint textureID, GLProgramState* glProgramState, BlendFunc blendType, const Triangles& triangles,const Mat4& mv);
    void init(float globalOrder, Texture2D* textureID, GLProgramState* glProgramState, BlendFunc blendType, const Triangles& triangles, const Mat4& mv, uint32_t flags);
    /**Apply the texture, shaders, programs, blend functions to GPU pipeline.*/
    void useMaterial() const;
    /**Get the material id of command.*/
    uint32_t getMaterialID() const { return _materialID; }
    /**Get the openGL texture handle.*/
    GLuint getTextureID() const { return _textureID; }
    /**Get a const reference of triangles.*/
    const Triangles& getTriangles() const { return _triangles; }
    /**Get the vertex count in the triangles.*/
    ssize_t getVertexCount() const { return _triangles.vertCount; }
    /**Get the index count of the triangles.*/
    ssize_t getIndexCount() const { return _triangles.indexCount; }
    /**Get the vertex data pointer.*/
    const V3F_C4B_T2F* getVertices() const { return _triangles.verts; }
    /**Get the index data pointer.*/
    const unsigned short* getIndices() const { return _triangles.indices; }
    /**Get the glprogramstate.*/
    GLProgramState* getGLProgramState() const { return _glProgramState; }
    /**Get the blend function.*/
    BlendFunc getBlendType() const { return _blendType; }
    /**Get the model view matrix.*/
    const Mat4& getModelView() const { return _mv; }

protected:
    /**Generate the material ID by textureID, glProgramState, and blend function.*/
    void generateMaterialID();

    /**Generated material id.*/
    uint32_t _materialID;
    /**OpenGL handle for texture.*/
    GLuint _textureID;
    /**GLprogramstate for the command. encapsulate shaders and uniforms.*/
    GLProgramState* _glProgramState;
    /**Blend function when rendering the triangles.*/
    BlendFunc _blendType;
    /**Rendered triangles.*/
    Triangles _triangles;
    /**Model view matrix when rendering the triangles.*/
    Mat4 _mv;

    GLuint _alphaTextureID; // ANDROID ETC1 ALPHA supports.
};

NS_CC_END
/**
 end of support group
 @}
 */
#endif // defined(__CC_TRIANGLES_COMMAND__)


text:
using System.Collections.Generic;
using System.IO;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace NFleet.Tests
{
    class ResponseReader
    {
        public static Dictionary<string, Response> readResponses(string responsePath)
        {
            var rootdirinfo = new DirectoryInfo(responsePath);
            var responses = new Dictionary<string, Response>();
            var files = rootdirinfo.GetFiles("*.txt");
            foreach (System.IO.FileInfo file in files)
            {
                string key = Path.GetFileNameWithoutExtension(file.FullName);
                bool json = false;
                var resp = new Response();
                string jsontmp = "";
                foreach (var line in System.IO.File.ReadAllLines(file.FullName))
                {
                    var trimmedline = line.Trim();
                    if (trimmedline.Length > 0 && trimmedline[0] == '{') json = true;
                    if (!json)
                    {
                        addHeader(line, resp.headers);
                    }
                    else
                    {
                        jsontmp += line;
                    }
                }
                resp.json = JsonConvert.DeserializeObject<JObject>(jsontmp);

                if (key != null)
                {
                    responses.Add(key, resp);
                }
            }
            return responses;
        }

        public static void addHeader(string headerLine, Dictionary<string, string> headerDict)
        {
            var splitIndex = headerLine.IndexOf(':');
            if (splitIndex > 0)
            {
                var key = headerLine.Substring(0, splitIndex);
                var value = headerLine.Substring(splitIndex).Trim();
                headerDict.Add(key, value);
            }
        }
    }

    class Response
    {
        public Dictionary<string, string> headers = new Dictionary<string, string>();
        public JObject json;
    }
}


text:
//
//  BackgroundLayer.h
//  SpaceVikingX
//
//  Created by Greg Heo on 2013-02-09.
//  Copyright (c) 2013 Ferocious Apps. All rights reserved.
//

#ifndef __SpaceVikingX__BackgroundLayer__
#define __SpaceVikingX__BackgroundLayer__

#include "cocos2d.h"

class BackgroundLayer : public cocos2d::CCLayer
{
public:
  virtual bool init();
  static cocos2d::CCScene* scene();
  CREATE_FUNC(BackgroundLayer);
};

#endif /* defined(__SpaceVikingX__BackgroundLayer__) */


text:
FORMAT:1A

# Patient API
The patient api allows to build OpenTele clients for accessing OpenTele patient data, such as questionnaires, conversations with clinicians etc.

## Authentication
The **Patient API** uses [basic authentication](http://en.wikipedia.org/wiki/Basic_access_authentication) over HTTPS. All resources except the root resource requires a proper `Authorization` header to be present in the request.

## Hypermedia
Resources can include a *links* property containing absolute URLs to related resources.
This means that clients should not construct the URLs on their own, thus making the maintenance of the URL structure easier.

    "links": {
        "self": "https://<host>/patient",
        "password": "https://<host>/rest/password/update",
        "measurements": "https://<host>/patient/measurements",
        "questionnaires": "https://<host>/rest/questionnaire/listing",
        "reminders": "https://<host>/rest/reminder/next"
    }

The <host> in the example above will be replaced with the real value.

The link relation `self` is the URI pointing the resource being represented.

## Schema
All data is sent and received as JSON. Data sent has the `content-type` header set to `application/json`.

Blank fields are included in responses as null:

    "someEmptyField": null

Timestamps are returned in the format:

    YYYY-MM-DDThh:mm:ss.sTZD

## HTTP Verbs
The following HTPP verbs are used throughout the api:

Verb   |Description
-------|-----------------------
GET    |Used for retrieving resources
POST   |Used for creating new resources

## Client Errors
The common [HTTP Response Status Codes](http://en.wikipedia.org/wiki/List_of_HTTP_status_codes) are used.
The actual status codes used are described in the documentation for the specific resources.

# Resources

# Group Entry Point

## Patient API Root [/]
Entry point for consuming the API.

This resource offers basic information about the API version and links to patient related resources. In addition a link to this documentation is also included in the representation.

### Retrieve the Entry Point [GET]

+ Response 200 (application/json)
    + Body

            {
                "version": "1.0.0",
                "serverEnvironment": "production"
                "links": {
                    "self": "https://<host>/",
                    "patient": "https://<host>/patient",
                    "api-doc": "https://<host>/patient-api.html"
                }
            }

# Group Patient

## Patient [/patient]
The Patient resource is the central resource in the Patient API as it, in addition to information about the patient itself, provides access to the resources a patient can access.

+ Model (application/json)

    JSON representation of Patient resource. In addition to representing its state it offers links to available resources.

    + Body

            {
                "firstName": "Nancy Ann",
                "lastName": "Berggren",
                "passwordExpired": false,
                "links": {
                    "self": "https://<host>/patient",
                    "password": "https://<host>/rest/password/update",
                    "measurements": "https://<host>/patient/measurements",
                    "questionnaires": "https://<host>/rest/questionnaire/listing",
                    "reminders": "https://<host>/rest/reminder/next",
                    "messageThreads": "https://<host>/rest/message/recipients",
                    "unreadMessages": "https://<host>/rest/message/list",
                    "acknowledgements": "https://<host>/rest/questionnaire/acknowledgements"
                }
            }

### Retrieve Patient [GET]
+ Request

    + Headers

            Authorization: Basic <base64 encoded user token>

+ Response 200

    [Patient][]

# Group Measurements

## Measurement Types [/patient/measurements]
For a patient measurements performed as part of answering questionnaires can be retrieved.
The measurements are grouped according to the type of measurement, e.g. blood sugar measurements are grouped as a type.

+ Model (application/json)
    JSON representation of the list of available measurement types a client can retrieve.
    Each measurement type is represented as its own link relation.

    + Body

            {
                "measurements": [{
                    "name": "blood_pressure",
                    "links": {
                        "measurement": "https://<host>/patient/measurements/blood_pressure"
                    }
                }, {
                    "name": "pulse",
                    "links": {
                        "measurement": "https://<host>/patient/measurements/pulse"
                    }
                }, {
                    "name": "weight",
                    "links": {
                        "measurement": "https://<host>/patient/measurements/weight"
                    }
                }, {
                    "name": "bloodsugar",
                    "links": {
                        "measurement": "https://<host>/patient/measurements/bloodsugar"
                    }
                }],
                "links": {
                    "self": "http://<host>/patient/measurements"
                }
            }

### Retrieve available measurement types [GET]
+ Request

    + Headers

            Authorization: Basic <base64 encoded user token>

+ Response 200

    [Measurement Types][]

## Measurements [/patient/measurements/{id}?filter={filter}]
Measurements for a specific measurement type can be retrieved using a time filter (using the {filter} parameter), the default time filter is 'week'.

The representation of measurements differ slightly based on the measurement type requested. The representation variants shown in the table below exist:

Representation|Measurement type(s)
--------------|-------------------
Simple        |pulse, weight, temperature, urine, hemoglobin, crp, saturation, lung_function
Blood sugar   |bloodsugar
Blood pressure|blood_pressure

+ Model (application/json)
    JSON representation of a series of measurements for the requested measurement type in the requested time interval.

    + Body

            Measurement representation = 'Simple'
            {
                "type": "pulse",
                "unit": "BPM",
                "measurements": [{
                    "timestamp": "2014-10-19T00:00:00.000+02:00",
                    "measurement": 57
                }, {
                    "timestamp": "2014-09-19T00:00:00.000+02:00",
                    "measurement": 50
                }, {
                    "timestamp": "2014-08-19T00:00:00.000+02:00",
                    "measurement": 56
                }, {
                    "timestamp": "2014-02-19T00:00:00.000+01:00",
                    "measurement": 57
                }, {
                    "timestamp": "2014-01-19T00:00:00.000+01:00",
                    "measurement": 51
                }, {
                    "timestamp": "2013-12-19T00:00:00.000+01:00",
                    "measurement": 52
                }],
                "links": {
                    "self": "https://<host>/patient/measurements/pulse"
                }
            }

            Measurement representation = 'Blood sugar':
            {
                "type": "bloodsugar",
                "unit": "mmol/L",
                "measurements": [{
                    "timestamp": "2014-10-18T02:00:00.000+02:00",
                    "measurement": {
                        "value": 7.199999809265137,
                        "isAfterMeal": false,
                        "isBeforeMeal": false,
                        "isControlMeasurement": false,
                        "isOutOfBounds": null,
                        "otherInformation": false,
                        "hasTemperatureWarning": null
                    }
                }, {
                    "timestamp": "2013-04-27T15:10:00.000+02:00",
                    "measurement": {
                        "value": 8,
                        "isAfterMeal": false,
                        "isBeforeMeal": false,
                        "isControlMeasurement": false,
                        "isOutOfBounds": null,
                        "otherInformation": false,
                        "hasTemperatureWarning": null
                    }
                }, {
                    "timestamp": "2013-03-28T15:10:00.000+01:00",
                    "measurement": {
                        "value": 8,
                        "isAfterMeal": false,
                        "isBeforeMeal": false,
                        "isControlMeasurement": false,
                        "isOutOfBounds": null,
                        "otherInformation": false,
                        "hasTemperatureWarning": null
                    }
                }, {
                    "timestamp": "2013-02-26T15:10:00.000+01:00",
                    "measurement": {
                        "value": 8,
                        "isAfterMeal": false,
                        "isBeforeMeal": false,
                        "isControlMeasurement": false,
                        "isOutOfBounds": null,
                        "otherInformation": false,
                        "hasTemperatureWarning": null
                    }
                }, {
                    "timestamp": "2013-01-27T15:10:00.000+01:00",
                    "measurement": {
                        "value": 8,
                        "isAfterMeal": false,
                        "isBeforeMeal": false,
                        "isControlMeasurement": false,
                        "isOutOfBounds": null,
                        "otherInformation": false,
                        "hasTemperatureWarning": null
                    }
                }],
                "links": {
                    "self": "https://<host>/patient/measurements/bloodsugar"
                }
            }

            Measurement representation = 'Blood pressure':
            {
                "type": "blood_pressure",
                "unit": "mmHg",
                "measurements": [{
                    "timestamp": "2014-10-27T12:25:12.934+01:00",
                    "measurement": {
                        "systolic": 130,
                        "diastolic": 65
                    }
                }, {
                    "timestamp": "2014-03-19T00:00:00.000+01:00",
                    "measurement": {
                        "systolic": 123,
                        "diastolic": 80
                    }
                }, {
                    "timestamp": "2014-02-19T00:00:00.000+01:00",
                    "measurement": {
                        "systolic": 122,
                        "diastolic": 80
                    }
                }, {
                    "timestamp": "2014-01-19T00:00:00.000+01:00",
                    "measurement": {
                        "systolic": 121,
                        "diastolic": 80
                    }
                }, {
                    "timestamp": "2013-12-19T00:00:00.000+01:00",
                    "measurement": {
                        "systolic": 120,
                        "diastolic": 80
                    }
                }],
                "links": {
                    "self": "https://<host>/patient/measurements/blood_pressure"
                }
            }

### Retrieve Measurements [GET]
+ Parameters

    + filter = `week` (optional, string)

        Time filter specifying for how long back in time to get measurements.

        + Values
            + `week`
            + `month`
            + `quarter`
            + `year`
            + `all`

+ Request

    + Headers

            Authorization: Basic <base64 encoded user token>

+ Response 200

    [Measurements][]

+ Response 422

        {
            "message": "Validation failed",
            "errors": [{
                "resource": "measurements",
                "field": "filter",
                "code": "invalid"
            }]
        }


text:
using System;
using BenchmarkDotNet.Attributes;
using Xunit;
using Xunit.Abstractions;

namespace BenchmarkDotNet.IntegrationTests
{
    public class ParamsTests : BenchmarkTestExecutor
    {
        public ParamsTests(ITestOutputHelper output) : base(output) { }

        [Fact]
        public void ParamsSupportPropertyWithPublicSetter()
        {
            var summary = CanExecute<ParamsTestProperty>();
            var standardOutput = GetCombinedStandardOutput(summary);

            foreach (var param in new[] { 1, 2 })
                Assert.Contains($"// ### New Parameter {param} ###", standardOutput);

            Assert.DoesNotContain($"// ### New Parameter {default(int)} ###", standardOutput);
        }

        public class ParamsTestProperty
        {
            [Params(1, 2)]
            public int ParamProperty { get; set; }

            [Benchmark]
            public void Benchmark() => Console.WriteLine($"// ### New Parameter {ParamProperty} ###");
        }

        [Fact]
        public void ParamsDoesNotSupportPropertyWithoutPublicSetter()
        {
            // System.InvalidOperationException : Property "ParamProperty" must be public and writable if it has the [Params(..)] attribute applied to it
            Assert.Throws<InvalidOperationException>(() => CanExecute<ParamsTestPrivatePropertyError>());
        }

        public class ParamsTestPrivatePropertyError
        {
            [Params(1, 2)]
            public int ParamProperty { get; private set; }

            [Benchmark]
            public void Benchmark() => Console.WriteLine($"// ### New Parameter {ParamProperty} ###");
        }

        [Fact]
        public void ParamsSupportPublicFields()
        {
            var summary = CanExecute<ParamsTestField>();
            var standardOutput = GetCombinedStandardOutput(summary);

            foreach (var param in new[] { 1, 2 })
                Assert.Contains($"// ### New Parameter {param} ###", standardOutput);

            Assert.DoesNotContain($"// ### New Parameter 0 ###", standardOutput);
        }

        public class ParamsTestField
        {
            [Params(1, 2)]
            public int ParamField = 0;

            [Benchmark]
            public void Benchmark() => Console.WriteLine($"// ### New Parameter {ParamField} ###");
        }

        [Fact]
        public void ParamsDoesNotSupportPrivateFields()
        {
            // System.InvalidOperationException : Field "ParamField" must be public if it has the [Params(..)] attribute applied to it
            Assert.Throws<InvalidOperationException>(() => CanExecute<ParamsTestPrivateFieldError>());
        }

        public class ParamsTestPrivateFieldError
        {
            [Params(1, 2)]
            private int ParamField = 0;

            [Benchmark]
            public void Benchmark() => Console.WriteLine($"// ### New Parameter {ParamField} ###");
        }

        public enum NestedOne
        {
            SampleValue = 1234
        }

        [Fact]
        public void NestedEnumsAsParamsAreSupported() => CanExecute<NestedEnumsAsParams>();

        public class NestedEnumsAsParams
        {
            [Params(NestedOne.SampleValue)]
            public NestedOne Field;

            [Benchmark]
            public NestedOne Benchmark() => Field;
        }

        [Fact]
        public void CharactersAsParamsAreSupported() => CanExecute<CharactersAsParams>();

        public class CharactersAsParams
        {
            [Params('*')]
            public char Field;

            [Benchmark]
            public char Benchmark() => Field;
        }

        [Fact]
        public void NullableTypesAsParamsAreSupported() => CanExecute<NullableTypesAsParams>();

        public class NullableTypesAsParams
        {
            [Params(null)]
            public int? Field = 1;

            [Benchmark]
            public void Benchmark()
            {
                if (Field != null) { throw new Exception("Field should be initialized in ctor with 1 and then set to null by Engine"); }
            }
        }

        [Fact]
        public void InvalidFileNamesInParamsAreSupported() => CanExecute<InvalidFileNamesInParams>();

        public class InvalidFileNamesInParams
        {
            [Params("/\\@#$%")]
            public string Field;

            [Benchmark]
            public void Benchmark() => Console.WriteLine("// " + Field);
        }

        [Fact]
        public void SpecialCharactersInStringAreSupported() => CanExecute<CompileSpecialCharactersInString>();

        public class CompileSpecialCharactersInString
        {
            [Params("\0")] public string Null;
            [Params("\t")] public string Tab;
            [Params("\n")] public string NewLine;
            [Params("\\")] public string Slash;
            [Params("\"")] public string Quote;
            [Params("\u0061")] public string Unicode;
            [Params("{")] public string Bracket;

            [Params("\n \0 \n")] public string Combo;

            [Params("C:\\file1.txt")] public string Path1;
            [Params(@"C:\file2.txt")] public string Path2;

            [Benchmark]
            public void Benchmark()
            {
                var isPassedAsSingleCharacter =
                    Null.Length == 1 &&
                    Tab.Length == 1 &&
                    NewLine.Length == 1 &&
                    Slash.Length == 1 &&
                    Quote.Length == 1 &&
                    Unicode.Length == 1 &&
                    Bracket.Length == 1;

                if (!isPassedAsSingleCharacter)
                    throw new InvalidOperationException("Some Param has an invalid escaped string");
            }
        }

        [Fact]
        public void SpecialCharactersInCharAreSupported() => CanExecute<CompileSpecialCharactersInChar>();

        public class CompileSpecialCharactersInChar
        {
            [Params('\0')] public char Null;
            [Params('\t')] public char Tab;
            [Params('\n')] public char NewLine;
            [Params('\\')] public char Slash;
            [Params('\"')] public char Quote;
            [Params('\u0061')] public char Unicode;

            [Benchmark]
            public void Benchmark() { }
        }

        [Fact]
        public void ParamsMustBeEscapedProperly() => CanExecute<NeedEscaping>();

        public class NeedEscaping
        {
            private const string Json = "{ \"message\": \"Hello, World!\" }";

            [Params(Json)]
            public string Field;

            [Benchmark]
            [Arguments(Json)]
            public void Benchmark(string argument)
            {
                if (Field != Json || argument != Json)
                    throw new InvalidOperationException("Wrong character escaping!");
            }
        }

        [Fact]
        public void ArrayCanBeUsedAsParameter() => CanExecute<WithArray>();

        public class WithArray
        {
            [Params(new[] { 0, 1, 2 })]
            public int[] Array;

            [Benchmark]
            public void AcceptingArray()
            {
                if (Array.Length != 3)
                    throw new InvalidOperationException("Incorrect array length");

                for (int i = 0; i < 3; i++)
                    if (Array[i] != i)
                        throw new InvalidOperationException($"Incorrect array element at index {i}, was {Array[i]} instead of {i}");
            }
        }

        [Fact]
        public void StaticFieldsAndPropertiesCanBeParams() => CanExecute<WithStaticParams>();

        public class WithStaticParams
        {
            [Params(1)]
            public static int StaticParamField = 0;

            [Params(2)]
            public static int StaticParamProperty { get; set; } = 0;

            [Benchmark]
            public void Test()
            {
                if (StaticParamField != 1)
                    throw new ArgumentException($"{nameof(StaticParamField)} has wrong value: {StaticParamField}!");
                if (StaticParamProperty != 2)
                    throw new ArgumentException($"{nameof(StaticParamProperty)} has wrong value: {StaticParamProperty}!");
            }
        }

        [Fact]
        public void ParamsPropertiesMustHavePublicSetter()
            => Assert.Throws<InvalidOperationException>(() => CanExecute<WithStaticParamsPropertyWithNoPublicSetter>());

        public class WithStaticParamsPropertyWithNoPublicSetter
        {
            [Params(3)]
            public static int StaticParamProperty { get; private set; }

            [Benchmark]
            public int Benchmark() => StaticParamProperty;
        }

        [Fact]
        public void ParamsFieldsMustBePublic()
            => Assert.Throws<InvalidOperationException>(() => CanExecute<WithStaticPrivateParamsField>());

        public class WithStaticPrivateParamsField
        {
            [Params(4)]
            private static int StaticParamField = 0;

            [Benchmark]
            public int Benchmark() => StaticParamField;
        }
    }
}


text:
form

    <form>

            <input class="form-control" type="text" placeholder="input.form-control">

            <input class="form-control input-lg" type="text" placeholder="input.form-control.input-lg">

            <input class="form-control input-sm" type="text" placeholder="input.form-control.input-sm">

            <textarea class="form-control" rows="3">textarea.form-control</textarea>

            input[type="file"]
            <input id="example-file-input" type="file">

                .help-block: Wrap labels and controls in
                .form-group
                for optimum spacing.

            <button class="btn btn-default" type="submit">Submit</button>

    </form>

form.form-inline

    <form class="form-inline">

            <input class="form-control" id="example-text-input-inline" type="text" placeholder="input.form-control">

                <input type="checkbox">
                .checkbox label input[type="checkbox"]

        <button class="btn btn-default" type="submit">Submit</button>
    </form>

form.form-horizontal

    <form class="form-horizontal">

                label.control-label

                <input class="form-control" id="example-text-input-horizontal" type="text" placeholder="input.form-control">

            Checkboxes

                        <input type="checkbox">
                        .checkbox label input[type="checkbox"]

                    <input type="checkbox" value="option1">
                    label.checkbox-inline Checkbox #1

                    <input type="checkbox" value="option2">
                    Checkbox #2

                    <input type="checkbox" value="option3" disabled>
                    Disabled checkbox

            Radios

                        <input name="optionsRadios" type="radio" value="option1" checked>
                        .radio label input[type="radio"]

                    <input name="optionsRadios2" type="radio" value="option1" checked>
                    label.radio-inline Radio #1

                    <input name="optionsRadios2" type="radio" value="option2">
                    Radio #2

                    <input name="optionsRadios2" type="radio" value="option3" disabled>
                    Disabled radio

            select.form-control

                <select class="form-control">
                    <option>option</option>
                    <option>Option #2</option>
                    <option>Option #3</option>
                </select>

                <select class="form-control" disabled>
                    <option>select[disabled]</option>
                </select>

select.form-control[multiple]

                <select class="form-control" multiple>
                    <option>Option #1</option>
                    <option selected>option[selected]</option>
                    <option>Option #3</option>
                    <option selected>Option #4</option>
                    <option>Option #5</option>
                </select>

            Static control

p.form-control-static

            Disabled input

                <input class="form-control" type="text" placeholder=".form-control[disabled]" disabled>

                <button class="btn btn-default" type="submit">Submit</button>

    </form>

Validation styles on form controls

    <form class="form-horizontal">

                .has-success

                <input class="form-control" id="inputSuccess" type="text" placeholder="input.form-control">

                .has-warning

                <input class="form-control" id="inputWarning" type="text" placeholder="input.form-control">

                .has-error

                <input class="form-control" id="inputError" type="text" placeholder="input.form-control">

    </form>

.form-group .input-group

                .input-group-addon

            <input class="form-control" type="text" placeholder="input.form-control">

                <input type="checkbox">

                <input type="radio">

            <input class="form-control" type="text" placeholder="input.form-control">

                <button class="btn btn-default" type="button">
                    span.input-group-btn button
                </button>

.form-group .input-group.input-group-lg

            .
            <input class="form-control input-lg" type="text" placeholder="input.form-control.input-lg">
            .

.form-group .input-group.input-group-sm

            .
            <input class="form-control input-sm" type="text" placeholder="input.form-control.input-sm">
            .


text:
package vpn

type Vpnvserverstats struct {
	Authenticationloginschemapolicy interface{} `json:"authenticationloginschemapolicy,omitempty"`
	Authenticationoauthidppolicy    interface{} `json:"authenticationoauthidppolicy,omitempty"`
	Authenticationpolicy            interface{} `json:"authenticationpolicy,omitempty"`
	Authenticationsamlidppolicy     interface{} `json:"authenticationsamlidppolicy,omitempty"`
	Cachepolicy                     interface{} `json:"cachepolicy,omitempty"`
	Clearstats                      string      `json:"clearstats,omitempty"`
	Icapolicy                       interface{} `json:"icapolicy,omitempty"`
	Name                            string      `json:"name,omitempty"`
	Primaryipaddress                string      `json:"primaryipaddress,omitempty"`
	Primaryport                     int         `json:"primaryport,omitempty"`
	Requestbytesrate                int         `json:"requestbytesrate,omitempty"`
	Requestsrate                    int         `json:"requestsrate,omitempty"`
	Responderpolicy                 interface{} `json:"responderpolicy,omitempty"`
	Responsebytesrate               int         `json:"responsebytesrate,omitempty"`
	Responsesrate                   int         `json:"responsesrate,omitempty"`
	Rewritepolicy                   interface{} `json:"rewritepolicy,omitempty"`
	State                           string      `json:"state,omitempty"`
	Totalrequestbytes               int         `json:"totalrequestbytes,omitempty"`
	Totalrequests                   int         `json:"totalrequests,omitempty"`
	Totalresponsebytes              int         `json:"totalresponsebytes,omitempty"`
	Totalresponses                  int         `json:"totalresponses,omitempty"`
	Type                            string      `json:"type,omitempty"`
	Vpnurlpolicy                    interface{} `json:"vpnurlpolicy,omitempty"`
}


text:
module Lotus
  module Views
    class DefaultTemplateFinder < View::Rendering::TemplateFinder
      # Template Finder
      #
      # @since 0.2.0
      # @api private
      def initialize(view, root, template_name, format)
        @view    = view
        @root    = root
        @options = { template: template_name, format: format }
      end

      private
      def root
        @root
      end
    end
  end
end


text:
This application runs several examples using the libccv library. Some of them compare the obtained result vs expected result, giving an assertion if the values are different.

The contents of the testFiles folder (data and samples) must be copied to the SD card (/mnt/sdcard/).

## List of examples

1. Canny edge detector.
	- Files required:
		- samples/blackbox.png
		- data/blackbox.canny.bin
	- Output:
		- File: samples/test1.png (1 if border has been detected, 0 if not)

2. Pedestrian cascade detector using Integral Channel Features.
	- Files required:
		- samples/pedestrian.icf
		- samples/pedestrian2.png
	- Output:
		- Text: Number of pedestrians detected. For each detection, classification confidence and x, y, width and height of the rectangle.

3. Matrix addition operation.

4. Sobel operations.
	- Files required:
		- samples/chessbox.bmp
		- data/chessbox.sobel.x.bin
		- data/chessbox.sobel.y.bin
		- data/chessbox.sobel.u.bin
		- data/chessbox.sobel.v.bin
		- data/chessbox.sobel.x.3.bin
		- data/chessbox.sobel.y.3.bin
		- data/chessbox.sobel.x.5.bin
	- Output:
		- samples/test4.png (partial derivative on y within 5x5 window)

5. Otsu threshold calculation.

6. Image contrast modification.
	- Files required:
		- samples/nature.bmp
		- data/nature.contrast.0.5.bin
		- data/nature.contrast.1.5.bin
	- Output:
		- samples/test6_1.png (reducing contrast to 0.5)
		- samples/test6_2.png (increasing contrast 1.5 times)

7. Perspective transform on a picture.
	- Files required:
		- samples/chessbox.bmp
		- data/chessbox.perspective.transform.bin
	- Output:
		- samples/test7.png (picture rotated along y-axis for 30º)

8. Histogram of gradients calculation.
	- Files required:
		- samples/nature.bmp
	- Output:
		- samples/test8.png (values obtained)

9. Scale Invariant Feature Transform.
	- Files required:
		- samples/book.png
	- Output:
		- Text: List of keypoints matching.

10. CBLAS matrix multiplication.

11. Convolutional network of 11x11 on 225x225 with uniform weights.

12. Convolutional network of 5x5 on 27x27 with non-uniform weights.

13. Convolutional network of 5x5x4 on 27x27x8 partitioned by 2.

14. Stroke Width Transform (text detection).
	- Files required:
		- samples/text-detect.png
	- Output:
		- Text: Number of texts detected. For each detection, x, y, width and height of the rectangle.

15. Brightness Binary Feature (face detection).
	- Files required:
		- samples/face (folder with cascade.txt and stage-0.txt to stage-15.txt files)
		- samples/suit.png
	- Output:
		- Text: Number of faces detected. For each detection, classification confidence and x, y, width and height of the rectangle.


text:
package com.BreakingBytes.SifterReader;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class CategoriesActivity extends ListActivity {

	public static final String CATEGORY_NAME = "name";
	public static final String CATEGORY = "category";

	// Members
	private JSONArray mCategoryArray;
	private JSONObject[] mAllCategories;
	private SifterHelper mSifterHelper;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		registerForContextMenu(getListView());

		mSifterHelper = new SifterHelper(this);

		Bundle extras = getIntent().getExtras();
		if (extras == null)
			return;
		try {
			JSONArray categories = new JSONArray(extras.getString(SifterReader.CATEGORIES));
			if (categories != null) {
				mCategoryArray = categories;
				getCategories();
				fillData();
			}
		} catch (JSONException e) {
			e.printStackTrace();
			mSifterHelper.onException(e.toString()); // return not needed
		}
	}

	private void getCategories() {
		int numberCategories = mCategoryArray.length();
		JSONObject[] allCategories = new JSONObject[numberCategories];
		try {
			for (int i = 0; i < numberCategories; i++)
				allCategories[i] = mCategoryArray.getJSONObject(i);
		} catch (JSONException e) {
			e.printStackTrace();
			mSifterHelper.onException(e.toString());
			return;
		}
		mAllCategories = allCategories;
	}

	private void fillData() {
		int cNum = mAllCategories.length;
		String[] c = new String[cNum];
		try {
			for (int j = 0; j < cNum; j++)
				c[j] = mAllCategories[j].getString(CATEGORY_NAME);
		} catch (JSONException e) {
			e.printStackTrace();
			mSifterHelper.onException(e.toString());
			return;
		}
		setListAdapter(new ArrayAdapter<String>(this,
				android.R.layout.simple_list_item_1, c));
	}

	/** start CategoryDetail activity for clicked project in list. */
	@Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        super.onListItemClick(l, v, position, id);
        Intent intent = new Intent(this, CategoryDetail.class);
        intent.putExtra(CATEGORY, mAllCategories[(int)id].toString());
        // TODO use safe long typecast to int
        startActivity(intent);
    }
}


text:
SYNONYM

#### According to
Index Fungorum

#### Published in
null

#### Original name
Favolus glaber P. Beauv.

### Remarks
null


text:
package com.datalint.open.client.ui.other;

import com.google.gwt.user.client.TakesValue;

public interface IUserInput<V> extends TakesValue<V> {
	void onBlur(V previousValue);
}


text:
using osu.Framework.Graphics;
using osu.Framework.Input.Events;
using osu.Game.Rulesets.Edit;
using osu.Game.Rulesets.Osu.Edit.Blueprints.Spinners.Components;
using osu.Game.Rulesets.Osu.Objects;
using osu.Game.Rulesets.Osu.UI;
using osuTK;

namespace osu.Game.Rulesets.Osu.Edit.Blueprints.Spinners
{
    public class SpinnerPlacementBlueprint : PlacementBlueprint
    {
        public new Spinner HitObject => (Spinner)base.HitObject;

        private readonly SpinnerPiece piece;

        private bool isPlacingEnd;

        public SpinnerPlacementBlueprint()
            : base(new Spinner { Position = OsuPlayfield.BASE_SIZE / 2 })
        {
            InternalChild = piece = new SpinnerPiece { Alpha = 0.5f };
        }

        protected override void Update()
        {
            base.Update();

            piece.UpdateFrom(HitObject);
        }

        protected override bool OnClick(ClickEvent e)
        {
            if (isPlacingEnd)
            {
                HitObject.EndTime = EditorClock.CurrentTime;
                EndPlacement();
            }
            else
            {
                HitObject.StartTime = EditorClock.CurrentTime;

                isPlacingEnd = true;
                piece.FadeTo(1f, 150, Easing.OutQuint);

                BeginPlacement();
            }

            return true;
        }

        public override void UpdatePosition(Vector2 screenSpacePosition)
        {
        }
    }
}


text:
' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.

Imports Microsoft.CodeAnalysis.CodeRefactorings
Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeRefactorings
Imports Microsoft.CodeAnalysis.VisualBasic.InvertLogical

Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.InvertLogical
    Partial Public Class InvertLogicalTests
        Inherits AbstractVisualBasicCodeActionTest

        Protected Overrides Function CreateCodeRefactoringProvider(workspace As Workspace, parameters As TestParameters) As CodeRefactoringProvider
            Return New VisualBasicInvertLogicalCodeRefactoringProvider()
        End Function

        <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertLogical)>
        Public Async Function InvertLogical1() As Task
            Await TestInRegularAndScriptAsync(
"class C
    sub M(x as boolean, a as integer, b as integer)
        dim c = a > 10 [||]orelse b < 20
    end sub
end class",
"class C
    sub M(x as boolean, a as integer, b as integer)
        dim c = Not (a <= 10 AndAlso b >= 20)
    end sub
end class")
        End Function

        <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertLogical)>
        Public Async Function InvertLogical2() As Task
            Await TestInRegularAndScriptAsync(
"class C
    sub M(x as boolean, a as integer, b as integer)
        dim c = Not (a <= 10 [||]andalso b >= 20)
    end sub
end class",
"class C
    sub M(x as boolean, a as integer, b as integer)
        dim c = a > 10 OrElse b < 20
    end sub
end class")
        End Function

        <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertLogical)>
        Public Async Function TestTrivia() As Task
            Await TestInRegularAndScriptAsync(
"class C
    sub M(x as boolean, a as integer, b as integer)
        dim c = Not (a <= 10 [||]andalso
                  b >= 20)
    end sub
end class",
"class C
    sub M(x as boolean, a as integer, b as integer)
        dim c = a > 10 OrElse
                  b < 20
    end sub
end class")
        End Function

        <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertLogical)>
        Public Async Function InvertMultiConditional1() As Task
            Await TestInRegularAndScriptAsync(
"class C
    sub M(a as integer, b as integer, c as integer)
        dim x = a > 10 [||]OrElse b < 20 OrElse c = 30
    end sub
end class",
"class C
    sub M(a as integer, b as integer, c as integer)
        dim x = Not (a <= 10 AndAlso b >= 20 AndAlso c <> 30)
    end sub
end class")
        End Function

        <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertLogical)>
        Public Async Function InvertMultiConditional2() As Task
            Await TestInRegularAndScriptAsync(
"class C
    sub M(a as integer, b as integer, c as integer)
        dim x = a > 10 OrElse b < 20 [||]OrElse c = 30
    end sub
end class",
"class C
    sub M(a as integer, b as integer, c as integer)
        dim x = Not (a <= 10 AndAlso b >= 20 AndAlso c <> 30)
    end sub
end class")
        End Function

        <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertLogical)>
        Public Async Function InvertMultiConditional3() As Task
            Await TestInRegularAndScriptAsync(
"class C
    sub M(a as integer, b as integer, c as integer)
        dim x = Not (a <= 10 [||]AndAlso b >= 20 AndAlso c <> 30)
    end sub
end class",
"class C
    sub M(a as integer, b as integer, c as integer)
        dim x = a > 10 OrElse b < 20 OrElse c = 30
    end sub
end class")
        End Function

        <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertLogical)>
        Public Async Function InvertMultiConditional4() As Task
            Await TestInRegularAndScriptAsync(
"class C
    sub M(a as integer, b as integer, c as integer)
        dim x = Not (a <= 10 AndAlso b >= 20 [||]AndAlso c <> 30)
    end sub
end class",
"class C
    sub M(a as integer, b as integer, c as integer)
        dim x = a > 10 OrElse b < 20 OrElse c = 30
    end sub
end class")
        End Function

        <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertLogical)>
        Public Async Function TestMissingOnSimpleOr() As Task
            Await TestMissingAsync(
"class C
    sub M(x as boolean, a as integer, b as integer)
        dim c = a > 10 [||]or b < 20
    end sub
end class")
        End Function

        <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertLogical)>
        Public Async Function TestMissingOnSimpleAnd() As Task
            Await TestMissingAsync(
"class C
    sub M(x as boolean, a as integer, b as integer)
        dim c = a > 10 [||]or b < 20
    end sub
end class")
        End Function

        <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertLogical)>
        Public Async Function TestSelectedOperator() As Task
            Await TestInRegularAndScriptAsync(
"class C
    sub M(x as boolean, a as integer, b as integer)
        dim c = a > 10 [|orelse|] b < 20
    end sub
end class",
"class C
    sub M(x as boolean, a as integer, b as integer)
        dim c = Not (a <= 10 AndAlso b >= 20)
    end sub
end class")
        End Function
    End Class
End Namespace


text:
class Adm::BackersController < Adm::BaseController
  menu I18n.t("adm.backers.index.menu", locale: :es) => Rails.application.routes.url_helpers.adm_backers_path(locale: :es)
  has_scope :by_id, :by_user_id, :by_key, :user_name_contains, :project_name_contains, :confirmed, :credits, :requested_refund, :refunded,
    :by_state, :by_payment_method, :by_value
  has_scope :between_values, using: [ :start_at, :ends_at ], allow_blank: true
  has_scope :pending_to_refund do |controller, scope, value|
    if value.present?
      scope.pending_to_refund
    else
      scope
    end
  end
  before_filter :set_title

  respond_to :xlsx, :only => :index

  def index
    index! do |format|
      format.html
      format.xlsx do
        @backers = end_of_association_chain.not_deleted.order("backers.created_at DESC")
      end
    end
  end

  def self.backer_actions
    %w[confirm pendent refund hide cancel push_to_trash].each do |action|
      define_method action do
        resource.send(action)
        flash[:notice] = I18n.t("adm.backers.messages.successful.#{action}")
        redirect_to adm_backers_path(params[:local_params])
      end
    end
  end
  backer_actions

  def change_reward
    resource.change_reward! params[:reward_id]
    flash[:notice] = I18n.t('adm.backers.messages.successful.change_reward')
    redirect_to adm_backers_path(params[:local_params])
  end

  protected
  def set_title
    @title = t("adm.backers.index.title")
  end

  def collection
    @backers ||= end_of_association_chain.not_deleted.order("backers.created_at DESC").page(params[:page])
  end
end


text:
<form action="/Setting/make" method="post">
	<fieldset>
		<legend>Skapa Inställning</legend>

				Namn
				<input type="text" name="name" />

				Kodnamn
				<input type="text" name="code_name" />

		<input type="submit" value="Skapa ny inställning" />
	</fieldset>
</form>


text:
<?php

namespace Phosphorum\Badges\Badge;

use Phosphorum\Models\Users;
use Phosphorum\Models\UsersBadges;
use Phosphorum\Models\Categories;

use Phosphorum\Models\PostsVotes;
use Phosphorum\Models\PostsRepliesVotes;
use Phosphorum\Badges\BadgeBase;

/**
 * Phosphorum\Badges\Badge\FamousQuestion
 *
 * Asked a question with more than 10000 views
 */
class FamousQuestion extends BadgeBase
{

    protected $name = 'Famous Question';

    protected $description = 'Asked a question with more than 10000 views';

    /**
     * Check whether the user already have this badge
     *
     * @param Users $user
     * @return boolean
     */
    public function has(Users $user)
    {
        $has = false;
        $noBountyCategories = $this->getNoBountyCategories();
        $conditions = 'categories_id NOT IN (' . join(', ', $noBountyCategories) . ') AND number_views >= 10000';
        $posts = $user->getPosts(array($conditions, 'columns' => 'id', 'order' => 'created_at DESC'));
        foreach ($posts as $post) {
            $has |= (UsersBadges::count(array(
                'users_id = ?0 AND badge = ?1 AND type = "P" AND code1 = ?2',
                'bind' => array($user->id, $this->getName(), $post->id)
            )) == 0);
        }
        return !$has;
    }

    /**
     * Check whether the user can have the badge
     *
     * @param  Users $user
     * @return boolean
     */
    public function canHave(Users $user)
    {
        $ids = array();
        $noBountyCategories = $this->getNoBountyCategories();
        $conditions = 'categories_id NOT IN (' . join(', ', $noBountyCategories) . ') AND number_views >= 10000';
        $posts = $user->getPosts(array($conditions, 'columns' => 'id', 'order' => 'created_at DESC'));
        foreach ($posts as $post) {
            $have = UsersBadges::count(array(
                'users_id = ?0 AND badge = ?1 AND type = "P" AND code1 = ?2',
                'bind' => array($user->id, $this->getName(), $post->id)
            ));
            if (!$have) {
                $ids[] = $post->id;
            }
        }
        return $ids;
    }

    /**
     * Add the badge to ther user
     *
     * @param Users $user
     * @param array $extra
     */
    public function add(Users $user, $extra = null)
    {
        $name = $this->getName();
        foreach ($extra as $id) {
            $userBadge = new UsersBadges();
            $userBadge->users_id = $user->id;
            $userBadge->badge    = $name;
            $userBadge->type     = 'P';
            $userBadge->code1    = $id;
            var_dump($userBadge->save());
        }
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<GeocodeResponse>
 <status>OK</status>
 <result>
  <type>locality</type>
  <type>political</type>
  <formatted_address>3350 Haag, Austria</formatted_address>
  <address_component>
   <long_name>Haag</long_name>
   <short_name>Haag</short_name>
   <type>locality</type>
   <type>political</type>
  </address_component>
  <address_component>
   <long_name>Gemeinde Haag</long_name>
   <short_name>Gemeinde Haag</short_name>
   <type>administrative_area_level_3</type>
   <type>political</type>
  </address_component>
  <address_component>
   <long_name>Amstetten</long_name>
   <short_name>Amstetten</short_name>
   <type>administrative_area_level_2</type>
   <type>political</type>
  </address_component>
  <address_component>
   <long_name>Niederösterreich</long_name>
   <short_name>Niederösterreich</short_name>
   <type>administrative_area_level_1</type>
   <type>political</type>
  </address_component>
  <address_component>
   <long_name>Austria</long_name>
   <short_name>AT</short_name>
   <type>country</type>
   <type>political</type>
  </address_component>
  <address_component>
   <long_name>3350</long_name>
   <short_name>3350</short_name>
   <type>postal_code</type>
  </address_component>
  <geometry>
   <location>
    <lat>48.1140568</lat>
    <lng>14.5679032</lng>
   </location>
   <location_type>APPROXIMATE</location_type>
   <viewport>
    <southwest>
     <lat>48.0648499</lat>
     <lng>14.5186299</lng>
    </southwest>
    <northeast>
     <lat>48.1560200</lat>
     <lng>14.6490001</lng>
    </northeast>
   </viewport>
   <bounds>
    <southwest>
     <lat>48.0648499</lat>
     <lng>14.5186299</lng>
    </southwest>
    <northeast>
     <lat>48.1560200</lat>
     <lng>14.6490001</lng>
    </northeast>
   </bounds>
  </geometry>
  <place_id>ChIJt21sLfu1c0cRWGhJeoSJaCI</place_id>
 </result>
</GeocodeResponse>


text:
#define C_LUCY_STANDARDTOKENIZER
#define C_LUCY_TOKEN
#include "Lucy/Util/ToolSet.h"

#include "Lucy/Analysis/StandardTokenizer.h"
#include "Lucy/Analysis/Token.h"
#include "Lucy/Analysis/Inversion.h"

/*
 * We use a modified version of the Word_Break property defined in UAX #29.
 * CR, LF, Newline and all undefined characters map to 0. WB_ASingle
 * designates characters that are Alphabetic but are excluded from ALetter.
 * WB_Extend_Format includes characters in both Extend and Format. The other
 * WB_* values correspond to the standard properties.
 *
 * The tables are in a compressed format that uses a three-stage lookup
 * scheme. They're generated with the perl script gen_word_break_tables.pl
 * in devel/bin. The WB_* constants must match the values used in the script.
 */

#define WB_ASingle          1
#define WB_ALetter          2
#define WB_Hebrew_Letter    3
#define WB_Numeric          4
#define WB_Katakana         5
#define WB_ExtendNumLet     6
#define WB_Extend_Format    7
#define WB_Single_Quote     8
#define WB_Double_Quote     9
#define WB_MidNumLet       10
#define WB_MidLetter       11
#define WB_MidNum          12

#include "WordBreak.tab"

typedef struct lucy_StringIter {
    size_t byte_pos;
    size_t char_pos;
} lucy_StringIter;

static int
S_parse_single(const char *text, size_t len, lucy_StringIter *iter,
               Inversion *inversion);

static int
S_parse_word(const char *text, size_t len, lucy_StringIter *iter,
             int state, Inversion *inversion);

static int
S_wb_lookup(const char *ptr);

static void
S_iter_advance(const char *text, lucy_StringIter *iter);

static int
S_skip_extend_format(const char *text, size_t len, lucy_StringIter *iter);

StandardTokenizer*
StandardTokenizer_new() {
    StandardTokenizer *self = (StandardTokenizer*)Class_Make_Obj(STANDARDTOKENIZER);
    return StandardTokenizer_init(self);
}

StandardTokenizer*
StandardTokenizer_init(StandardTokenizer *self) {
    Analyzer_init((Analyzer*)self);
    return self;
}

Inversion*
StandardTokenizer_Transform_IMP(StandardTokenizer *self, Inversion *inversion) {
    Inversion *new_inversion = Inversion_new(NULL);
    Token *token;

    while (NULL != (token = Inversion_Next(inversion))) {
        TokenIVARS *const token_ivars = Token_IVARS(token);
        StandardTokenizer_Tokenize_Utf8(self, token_ivars->text,
                                        token_ivars->len, new_inversion);
    }

    return new_inversion;
}

Inversion*
StandardTokenizer_Transform_Text_IMP(StandardTokenizer *self, String *text) {
    Inversion *new_inversion = Inversion_new(NULL);
    StandardTokenizer_Tokenize_Utf8(self, Str_Get_Ptr8(text),
                                    Str_Get_Size(text), new_inversion);
    return new_inversion;
}

void
StandardTokenizer_Tokenize_Utf8_IMP(StandardTokenizer *self, const char *text,
                                    size_t len, Inversion *inversion) {
    UNUSED_VAR(self);
    if ((len >= 1 && (uint8_t)text[len - 1] >= 0xC0)
        ||  (len >= 2 && (uint8_t)text[len - 2] >= 0xE0)
        ||  (len >= 3 && (uint8_t)text[len - 3] >= 0xF0)) {
        THROW(ERR, "Invalid UTF-8 sequence");
    }

    lucy_StringIter iter = { 0, 0 };

    while (iter.byte_pos < len) {
        int wb = S_wb_lookup(text + iter.byte_pos);

        while (wb >= WB_ASingle && wb <= WB_ExtendNumLet) {
            if (wb == WB_ASingle) {
                wb = S_parse_single(text, len, &iter, inversion);
            }
            else {
                wb = S_parse_word(text, len, &iter, wb, inversion);
            }
            if (iter.byte_pos >= len) return;
        }

        S_iter_advance(text, &iter);
    }
}

/*
 * Parse a word consisting of a single codepoint followed by extend or
 * format characters. Used for Alphabetic characters that don't have the
 * ALetter word break property: ideographs, Hiragana, and "complex context".
 * Advances the iterator and returns the word break property of the character
 * following the word.
 */
static int
S_parse_single(const char *text, size_t len, lucy_StringIter *iter,
               Inversion *inversion) {
    lucy_StringIter start = *iter;
    int wb = S_skip_extend_format(text, len, iter);

    Token *token
        = Token_new(text + start.byte_pos, iter->byte_pos - start.byte_pos,
                    (uint32_t)start.char_pos, (uint32_t)iter->char_pos,
                    1.0f, 1);
    Inversion_Append(inversion, token);

    return wb;
}

/*
 * Parse a word starting with an ALetter, Hebrew_Letter, Numeric, Katakana, or
 * ExtendNumLet character. Advances the iterator and returns the word break
 * property of the character following the word.
 *
 * TODO: Words consisting only of ExtendNumLet characters (General_Category
 * Pc, typically underscores) should be ignored.
 */
static int
S_parse_word(const char *text, size_t len, lucy_StringIter *iter,
             int state, Inversion *inversion) {
    int wb = -1;
    lucy_StringIter start = *iter;
    S_iter_advance(text, iter);
    lucy_StringIter end = *iter;

    while (iter->byte_pos < len) {
        wb = S_wb_lookup(text + iter->byte_pos);

        switch (wb) {
            case WB_ALetter:
            case WB_Hebrew_Letter:
            case WB_Numeric:
                if (state == WB_Katakana) { goto word_break; }
                // Rules WB5, WB8, WB9, WB10, and WB13b.
                break;
            case WB_Katakana:
                if (state != WB_Katakana && state != WB_ExtendNumLet) {
                    goto word_break;
                }
                // Rules WB13 and WB13b.
                break;
            case WB_ExtendNumLet:
                // Rule WB13a.
                break;
            case WB_Extend_Format:
                // Rule WB4. Keep state.
                wb = state;
                break;
            case WB_Single_Quote:
            case WB_MidNumLet:
            case WB_MidLetter:
            case WB_MidNum:
                if (state == WB_ALetter) {
                    if (wb == WB_MidNum) { goto word_break; }
                    wb = S_skip_extend_format(text, len, iter);
                    if (wb == WB_ALetter || wb == WB_Hebrew_Letter) {
                        // Rules WB6 and WB7.
                        state = wb;
                        break;
                    }
                }
                else if (state == WB_Hebrew_Letter) {
                    if (wb == WB_MidNum) { goto word_break; }
                    if (wb == WB_Single_Quote) {
                        // Rule WB7a.
                        ++end.byte_pos;
                        ++end.char_pos;
                    }
                    wb = S_skip_extend_format(text, len, iter);
                    if (wb == WB_ALetter || wb == WB_Hebrew_Letter) {
                        // Rules WB6 and WB7.
                        state = wb;
                        break;
                    }
                }
                else if (state == WB_Numeric) {
                    if (wb == WB_MidLetter) { goto word_break; }
                    wb = S_skip_extend_format(text, len, iter);
                    if (wb == state) {
                        // Rules WB11 and WB12.
                        break;
                    }
                }
                goto word_break;
            case WB_Double_Quote:
                if (state == WB_Hebrew_Letter) {
                    wb = S_skip_extend_format(text, len, iter);
                    if (wb == state) {
                        // Rules WB7b and WB7c.
                        break;
                    }
                }
                goto word_break;
            default:
                goto word_break;
        }

        state = wb;
        S_iter_advance(text, iter);
        end = *iter;
    }

    Token *token;
word_break:
    token = Token_new(text + start.byte_pos, end.byte_pos - start.byte_pos,
                      (uint32_t)start.char_pos, (uint32_t)end.char_pos,
                      1.0f, 1);
    Inversion_Append(inversion, token);

    return wb;
}

/*
 * Conceptually, the word break property table is split into rows that
 * contain 64 columns and planes that contain 64 rows (not to be confused
 * the 65,536 character Unicode planes). So bits 0-5 of a code point contain
 * the column index into a row, bits 6-11 contain the row index into a plane,
 * and bits 12-20 contain the plane index.
 *
 * To save space, identical rows are merged so the row table contains only
 * unique rows and the plane table contains row indices remapped to row ids.
 * Then, identical planes are merged, and a plane map table is created with
 * plane indices remapped to plane ids.
 *
 * The row and plane tables are simple one-dimensional arrays created by
 * concatenating all unique rows and planes. So looking up an entry can be
 * done by left shifting the id and ORing the index.
 */

#define WB_TABLE_LOOKUP(table, id, index) table [ ((id) << 6) | (index) ]

static int
S_wb_lookup(const char *ptr) {
    unsigned start = *(uint8_t*)ptr++;

    if (start < 0x80) { return wb_ascii[start]; }

    size_t plane_id, row_index;

    if (start < 0xE0) {
        if (start < 0xC0) {
            THROW(ERR, "Invalid UTF-8 sequence");
        }
        // two byte sequence
        // 110rrrrr 10cccccc
        plane_id  = 0;
        row_index = start & 0x1F;
    }
    else {
        size_t plane_index;
        if (start < 0xF0) {
            // three byte sequence
            // 1110pppp 10rrrrrr 10cccccc
            plane_index = start & 0x0F;
        }
        else {
            // four byte sequence
            // 11110ppp 10pppppp 10rrrrrr 10cccccc
            plane_index = ((start & 0x07) << 6) | (*ptr++ & 0x3F);
        }
        if (plane_index >= WB_PLANE_MAP_SIZE) { return 0; }
        plane_id  = wb_plane_map[plane_index];
        row_index = *ptr++ & 0x3F;
    }

    size_t row_id = WB_TABLE_LOOKUP(wb_planes, plane_id, row_index);
    size_t column_index = *ptr++ & 0x3F;
    return WB_TABLE_LOOKUP(wb_rows, row_id, column_index);
}

static void
S_iter_advance(const char *text, lucy_StringIter *iter) {
    iter->byte_pos += StrHelp_UTF8_COUNT[*(uint8_t*)(text + iter->byte_pos)];
    iter->char_pos += 1;
}

/*
 * Advances the iterator skipping over Extend and Format characters.
 * Returns the word break property of the following character.
 */
static int
S_skip_extend_format(const char *text, size_t len, lucy_StringIter *iter) {
    int wb = -1;

    do {
        S_iter_advance(text, iter);
        if (iter->byte_pos >= len) { break; }
        wb = S_wb_lookup(text + iter->byte_pos);
    } while (wb == WB_Extend_Format);

    return wb;
}

bool
StandardTokenizer_Equals_IMP(StandardTokenizer *self, Obj *other) {
    if ((StandardTokenizer*)other == self)   { return true; }
    if (!Obj_is_a(other, STANDARDTOKENIZER)) { return false; }
    return true;
}


text:
CUDA_VISIBLE_DEVICES=0 ./icnn.py --dataset linear  --model picnn --nEpoch 200 &
CUDA_VISIBLE_DEVICES=1 ./icnn.py --dataset moons   --model picnn --nEpoch 200 &
CUDA_VISIBLE_DEVICES=2 ./icnn.py --dataset circles --model picnn --nEpoch 200 &

CUDA_VISIBLE_DEVICES=3 ./icnn.py --dataset linear  --model ficnn --nEpoch 200 &
CUDA_VISIBLE_DEVICES=0 ./icnn.py --dataset moons   --model ficnn --nEpoch 200 &
CUDA_VISIBLE_DEVICES=1 ./icnn.py --dataset circles --model ficnn --nEpoch 200 &

wait

./make-tile.sh


text:
namespace mozart {

struct CoreAtoms {
  inline
  void initialize(VM vm, AtomTable& atomTable);

  // ''
  atom_t empty;

  // nil, '|' and '#'
  atom_t nil;
  atom_t pipe;
  atom_t sharp;

  // Serialization types
  atom_t int_;
  atom_t float_;
  atom_t bool_;
  atom_t unit;
  atom_t atom;
  atom_t cons;
  atom_t tuple;
  atom_t arity;
  atom_t record;
  atom_t builtin;
  atom_t codearea;
  atom_t patmatwildcard;
  atom_t patmatcapture;
  atom_t patmatconjunction;
  atom_t patmatopenrecord;
  atom_t abstraction;
  atom_t chunk;
  atom_t uniquename;
  atom_t name;
  atom_t namedname;
  atom_t unicodeString;

  // Object Orientation
  unique_name_t ooMeth;
  unique_name_t ooFastMeth;
  unique_name_t ooDefaults;
  unique_name_t ooAttr;
  unique_name_t ooFeat;
  unique_name_t ooFreeFeat;
  unique_name_t ooFreeFlag;
  unique_name_t ooMethSrc;
  unique_name_t ooAttrSrc;
  unique_name_t ooFeatSrc;
  unique_name_t ooPrintName;
  unique_name_t ooFallback;

  // Space status
  atom_t succeeded;
  atom_t entailed;
  atom_t stuck;
  atom_t suspended;
  atom_t alternatives;
  atom_t failed;
  atom_t merged;

  // Unicode error types
  atom_t outOfRange;
  atom_t surrogate;
  atom_t invalidUTF8;
  atom_t invalidUTF16;
  atom_t truncated;

  // Exceptions
  atom_t debug;
  atom_t error;
  atom_t system;
  atom_t failure;
  atom_t kernel;
  atom_t illegalFieldSelection;
  atom_t unicodeError;
  atom_t spaceAdmissible;
  atom_t spaceNoChoice;
  atom_t spaceAltRange;
  atom_t spaceMerged;
  atom_t indexOutOfBounds;
};

}

#endif // MOZART_COREATOMS_DECL_H