text:
package com.ysy.goodtogglebutton;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;

public class OnOffButton extends View
{
	private Bitmap backGroundOn;
	private Bitmap backGroundOff;
	private Bitmap statePot;

	private Paint paint;

	private boolean state;
	private float leftPos;
	private float scaleRatio;

	public OnOffButton(Context context)
	{
		super(context);
		initView();
	}

	public OnOffButton(Context context, AttributeSet attrs)
	{
		super(context, attrs);
		TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.OnOffButton);
		state = typedArray.getBoolean(R.styleable.OnOffButton_current_state, false);
		scaleRatio = typedArray.getFloat(R.styleable.OnOffButton_scale_ratio, 1);
		typedArray.recycle();
		initView();
	}

	private void initView()
	{
		backGroundOn = BitmapFactory.decodeResource(getResources(), R.drawable.skin_switch_track_activited);
		backGroundOff = BitmapFactory.decodeResource(getResources(), R.drawable.skin_switch_track);
		statePot = BitmapFactory.decodeResource(getResources(), R.drawable.skin_pot);

		backGroundOn = decodeBitmap(backGroundOn, scaleRatio, scaleRatio);
		backGroundOff = decodeBitmap(backGroundOff, scaleRatio, scaleRatio);
		statePot = decodeBitmap(statePot, scaleRatio, scaleRatio);

		paint = new Paint();
		paint.setAntiAlias(true);
	}

	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
	{
		setMeasuredDimension(backGroundOn.getWidth(), backGroundOn.getHeight());
	}

	@Override
	protected void onDraw(Canvas canvas)
	{
		if (state)
			canvas.drawBitmap(backGroundOn, 0, 0, paint);
		else
			canvas.drawBitmap(backGroundOff, 0, 0, paint);
		canvas.drawBitmap(statePot, leftPos, 0, paint);
	}

	@Override
	public boolean onTouchEvent(MotionEvent event)
	{
		switch (event.getAction())
		{
			case MotionEvent.ACTION_UP:
				state = !state;
				leftPos = leftPos != 0 ? 0 : backGroundOn.getWidth() - statePot.getWidth();
				invalidate();
				break;
		}
		return super.onTouchEvent(event);
	}

	public boolean getCurrentState()
	{
		return state;
	}

	public void setCurrentState(boolean flag)
	{
		state = flag;
		invalidate();
	}

	private Bitmap decodeBitmap(Bitmap bitmap, float widthScale, float heightScale)
	{
		Matrix matrix = new Matrix();
		matrix.postScale(widthScale, heightScale);
		Bitmap resizeBmp = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
		return resizeBmp;
	}

}


text:
package stream.flarebot.flarebot.commands.secret;

import net.dv8tion.jda.core.JDAInfo;
import net.dv8tion.jda.core.entities.Member;
import net.dv8tion.jda.core.entities.Message;
import net.dv8tion.jda.core.entities.TextChannel;
import net.dv8tion.jda.core.entities.User;
import okhttp3.Response;
import org.json.JSONObject;
import org.json.JSONTokener;
import stream.flarebot.flarebot.api.ApiRequesterBuilder;
import stream.flarebot.flarebot.api.ApiRoute;
import stream.flarebot.flarebot.commands.Command;
import stream.flarebot.flarebot.commands.CommandType;
import stream.flarebot.flarebot.objects.GuildWrapper;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.stream.Collectors;

public class TestCommand implements Command {

    @Override
    public void onCommand(User sender, GuildWrapper guild, TextChannel channel, Message message, String[] args, Member member) {
        channel.sendMessage("Test").queue(aVoid -> System.out.println("Sent the message!"),
                fail -> System.out.println("Failed to send! " + fail.getMessage()));
        System.out.println(JDAInfo.VERSION);
    }

    @Override
    public String getCommand() {
        return "test";
    }

    @Override
    public String getDescription() {
        return null;
    }

    @Override
    public String getUsage() {
        return "{%}test";
    }

    @Override
    public CommandType getType() {
        return CommandType.SECRET;
    }
}

redpajama_set_name: RedPajamaGithub


text:
/*
 * C Implementation: get_product_kind
 *
 * Description: how to process a file containing a mix of messages
 *              and print the kind of product (e.g. GRIB, BUFR etc)
 */
#include "eccodes.h"
void usage(const char *app)
{
    fprintf(stderr,"Usage: %s file\n", app);
}

int main(int argc,char* argv[])
{
    FILE* in = NULL;
    codes_handle* h=NULL;
    char* kind= NULL;
    size_t len=0;
    int err=0, cnt=0;
    char* infile = NULL;

    if (argc != 2) {
        usage(argv[0]);
        return 1;
    }
    infile = argv[1];
    in=fopen(infile,"r");
    if (!in) {
        printf("ERROR: unable to open file %s\n", infile);
        return 1;
    }

    while ((h = codes_handle_new_from_file(NULL,in,PRODUCT_ANY,&err)) != NULL || err != CODES_SUCCESS)
    {
        if (h == NULL) {
            printf("Error: unable to create handle for message %d\n",cnt);
            cnt++;
            continue;
        }
        printf("message: %d\n",cnt);

        CODES_CHECK(codes_get_length(h, "kindOfProduct", &len), 0);
        kind = (char*)malloc(len*sizeof(char));

        codes_get_string(h, "kindOfProduct", kind, &len);
        printf("  product: %s\n", kind);

        free(kind);
        codes_handle_delete(h);
        cnt++;
    }
    fclose(in);
    return 0;
}


text:
from zeit.cms.i18n import MessageFactory as _
import zeit.cms.content.interfaces
import zeit.cms.repository.interfaces
import zeit.cms.workflow.interfaces
import zeit.content.image.interfaces
import zeit.edit.interfaces
import zope.container.interfaces
import zope.interface
import zope.schema.interfaces

DAV_NAMESPACE = 'http://namespaces.zeit.de/CMS/newsletter'

class InvariantViolated(zope.schema.interfaces.ValidationError):

    def doc(self):
        return self.args[0]

class INewsletter(zeit.cms.content.interfaces.IXMLContent,
                  zope.container.interfaces.IReadContainer):

    subject = zope.schema.TextLine(title=_('Subject'))

    def send():
        """Sends emails for this newsletter."""

    def send_test(to):
        """Sends test email to the given address."""

    body = zope.interface.Attribute('The IBody of this newsletter')

class IBody(zeit.edit.interfaces.IArea):
    pass

class IGroup(zeit.edit.interfaces.IArea,
             zeit.edit.interfaces.IBlock):

    title = zope.schema.TextLine(title=_('Title'))

class ITeaser(zeit.edit.interfaces.IBlock):

    reference = zope.schema.Choice(
        source=zeit.cms.content.contentsource.cmsContentSource)

class IAdvertisement(zeit.edit.interfaces.IBlock):

    href = zope.schema.TextLine(title=_('Target URL'))

    title = zope.schema.TextLine(title=_('Title'))

    text = zope.schema.Text(title=_('Text'))

    image = zope.schema.Choice(
        source=zeit.content.image.interfaces.imageSource,
        required=False)

class INewsletterCategory(zeit.cms.repository.interfaces.IDAVContent):

    last_created = zope.schema.Datetime(
        title=_(u'Timestamp when the last newsletter object'
                ' in this category was created'))

    def create():
        """Creates a new newsletter object for this category."""

    subject = zope.schema.TextLine(
        title=_(u'Subject'),
        description=_(u'{today} -> %d.%m.%Y'))

    mandant = zope.schema.Int(
        title=_(u'Optivo Mandant ID'))

    recipientlist = zope.schema.TextLine(
        title=_(u'Name of recipient list'))

    recipientlist_test = zope.schema.TextLine(
        title=_(u'Name of test-recipient list'),
        required=False)

    ressorts = zope.schema.List(
        title=_('Ressorts'),
        value_type=zope.schema.Choice(
            source=zeit.cms.content.sources.RessortSource()),
    )

    video_playlist = zope.schema.TextLine(
        title=_('Unique id of video playlist'),
        required=False)

    ad_middle_groups_above = zope.schema.Int(
        title=_('Number of groups above middle ad'))

    ad_middle_href = zope.schema.TextLine(title=_('Middle ad target URL'))

    ad_middle_title = zope.schema.TextLine(title=_('Middle ad title'))

    ad_middle_text = zope.schema.Text(title=_('Middle ad text'))

    ad_middle_image = zope.schema.Choice(
        title=_('Middle ad image'),
        source=zeit.content.image.interfaces.imageSource,
        required=False)

    ad_thisweeks_groups_above = zope.schema.Int(
        title=_('Number of groups above this week\'s ad'))

    ad_thisweeks_href = zope.schema.TextLine(
        title=_('This week\'s ad target URL'))

    ad_thisweeks_title = zope.schema.TextLine(title=_('This week\'s ad title'))

    ad_thisweeks_text = zope.schema.Text(title=_('This week\'s ad text'))

    ad_thisweeks_image = zope.schema.Choice(
        title=_('This week\'s ad image'),
        source=zeit.content.image.interfaces.imageSource,
        required=False)

    ad_thisweeks_on_0 = zope.schema.Bool(title=_('Monday'))
    ad_thisweeks_on_1 = zope.schema.Bool(title=_('Tuesday'))
    ad_thisweeks_on_2 = zope.schema.Bool(title=_('Wednesday'))
    ad_thisweeks_on_3 = zope.schema.Bool(title=_('Thursday'))
    ad_thisweeks_on_4 = zope.schema.Bool(title=_('Friday'))
    ad_thisweeks_on_5 = zope.schema.Bool(title=_('Saturday'))
    ad_thisweeks_on_6 = zope.schema.Bool(title=_('Sunday'))

    ad_bottom_href = zope.schema.TextLine(title=_('Bottom ad target URL'))

    ad_bottom_title = zope.schema.TextLine(title=_('Bottom ad title'))

    ad_bottom_text = zope.schema.Text(title=_('Bottom ad text'))

    ad_bottom_image = zope.schema.Choice(
        title=_('Bottom ad image'),
        source=zeit.content.image.interfaces.imageSource,
        required=False)

    @zope.interface.invariant
    def middle_ad_above_thisweeks(obj):
        if obj.ad_middle_groups_above < obj.ad_thisweeks_groups_above:
            return
        raise InvariantViolated(
            u'Der Werbeblock "Diese Woche in der aktuellen Zeit" muss an '
            u'einer späteren Position als der Werbeblock "Mitte" erscheinen.')

class IRepositoryCategory(
        INewsletterCategory, zeit.cms.repository.interfaces.IFolder):
    pass

class ILocalCategory(
        INewsletterCategory, zeit.cms.workingcopy.interfaces.ILocalContent):
    """Local version of a newsletter category.

    The local version only holds the metadata, therefore it is not a container.
    """

class IBuild(zope.interface.Interface):
    """Builds a newsletter in a way specific to the category."""

    def __call__(content_list):
        """Selects appropriate content objects and populates the newsletter
        with groups and teasers."""

class INewsletterWorkflow(zeit.cms.workflow.interfaces.IPublishInfo):

    sent = zope.schema.Bool(title=_('Sent'), readonly=True)

class ITestRecipient(zope.interface.Interface):

    # XXX validate email?
    email = zope.schema.TextLine(title=_('Email for test'))

class IRenderer(zope.interface.Interface):

    def __call__(content):
        """Returns a dict with the keys html and text containing the rendered
        newsletter"""


text:
namespace content {
class BrowserContext;
}

namespace network {
class NetworkQualityTracker;
}

namespace ukm {
namespace builders {
class PageLoad;
}
}  // namespace ukm

// If URL-Keyed-Metrics (UKM) is enabled in the system, this is used to
// populate it with top-level page-load metrics.
class UkmPageLoadMetricsObserver
    : public page_load_metrics::PageLoadMetricsObserver {
 public:
  // Returns a UkmPageLoadMetricsObserver, or nullptr if it is not needed.
  static std::unique_ptr<page_load_metrics::PageLoadMetricsObserver>
  CreateIfNeeded();

  explicit UkmPageLoadMetricsObserver(
      network::NetworkQualityTracker* network_quality_tracker);

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

  ~UkmPageLoadMetricsObserver() override;

  // page_load_metrics::PageLoadMetricsObserver implementation:
  ObservePolicy OnStart(content::NavigationHandle* navigation_handle,
                        const GURL& currently_committed_url,
                        bool started_in_foreground) override;
  ObservePolicy OnFencedFramesStart(
      content::NavigationHandle* navigation_handle,
      const GURL& currently_committed_url) override;
  ObservePolicy OnPrerenderStart(content::NavigationHandle* navigation_handle,
                                 const GURL& currently_committed_url) override;

  ObservePolicy OnRedirect(
      content::NavigationHandle* navigation_handle) override;

  ObservePolicy OnCommit(content::NavigationHandle* navigation_handle) override;

  ObservePolicy ShouldObserveMimeType(
      const std::string& mime_type) const override;

  ObservePolicy FlushMetricsOnAppEnterBackground(
      const page_load_metrics::mojom::PageLoadTiming& timing) override;

  ObservePolicy OnHidden(
      const page_load_metrics::mojom::PageLoadTiming& timing) override;

  ObservePolicy OnShown() override;

  void OnFailedProvisionalLoad(
      const page_load_metrics::FailedProvisionalLoadInfo& failed_load_info)
      override;

  void OnComplete(
      const page_load_metrics::mojom::PageLoadTiming& timing) override;

  void OnResourceDataUseObserved(
      content::RenderFrameHost* content,
      const std::vector<page_load_metrics::mojom::ResourceDataUpdatePtr>&
          resources) override;

  void OnLoadedResource(const page_load_metrics::ExtraRequestCompleteInfo&
                            extra_request_complete_info) override;

  void OnTimingUpdate(
      content::RenderFrameHost* subframe_rfh,
      const page_load_metrics::mojom::PageLoadTiming& timing) override;

  void SetUpSharedMemoryForSmoothness(
      const base::ReadOnlySharedMemoryRegion& shared_memory) override;

  void OnCpuTimingUpdate(
      content::RenderFrameHost* subframe_rfh,
      const page_load_metrics::mojom::CpuTiming& timing) override;

  void DidActivatePortal(base::TimeTicks activation_time) override;

  void OnFirstContentfulPaintInPage(
      const page_load_metrics::mojom::PageLoadTiming& timing) override;

  // Whether the current page load is an Offline Preview. Must be called from
  // OnCommit. Virtual for testing.
  virtual bool IsOfflinePreview(content::WebContents* web_contents) const;

 private:
  void RecordNavigationTimingMetrics();

  // Records page load timing related metrics available in PageLoadTiming, such
  // as first contentful paint.
  void RecordTimingMetrics(
      const page_load_metrics::mojom::PageLoadTiming& timing);

  // Records page load internal timing metrics, which are used for debugging.
  void RecordInternalTimingMetrics(
      const page_load_metrics::ContentfulPaintTimingInfo&
          all_frames_largest_contentful_paint);

  // Records metrics based on the page load information exposed by the observer
  // delegate, as well as updating the URL. |app_background_time| should be set
  // to a timestamp if the app was backgrounded, otherwise it should be set to
  // a null TimeTicks.
  void RecordPageLoadMetrics(base::TimeTicks app_background_time);

  // Records metrics related to how the renderer process was used for the
  // navigation.
  void RecordRendererUsageMetrics();

  // Adds main resource timing metrics to |builder|.
  void ReportMainResourceTimingMetrics(ukm::builders::PageLoad& builder);

  void ReportLayoutStability();

  // Returns the current Core Web Vital definition of Cumulative Layout Shift.
  // Returns nullopt if current value should not be reported to UKM.
  absl::optional<float> GetCoreWebVitalsCLS();

  // Returns the current Core Web Vital definition of Largest Contentful Paint.
  // The caller needs to check whether the value should be reported to UKM based
  // on when the page was backgrounded and other validations.
  const page_load_metrics::ContentfulPaintTimingInfo&
  GetCoreWebVitalsLcpTimingInfo();

  void RecordAbortMetrics(
      const page_load_metrics::mojom::PageLoadTiming& timing,
      base::TimeTicks page_end_time,
      ukm::builders::PageLoad* builder);

  void RecordMemoriesMetrics(
      ukm::builders::PageLoad& builder,
      const page_load_metrics::PageEndReason page_end_reason);

  void RecordInputTimingMetrics();
  void RecordSmoothnessMetrics();
  void RecordResponsivenessMetrics();

  void RecordPageLoadTimestampMetrics(ukm::builders::PageLoad& builder);

  // Captures the site engagement score for the committed URL and
  // returns the score rounded to the nearest 10.
  absl::optional<int64_t> GetRoundedSiteEngagementScore() const;

  // Returns whether third party cookie blocking is enabled for the committed
  // URL. This is only recorded for users who have prefs::kCookieControlsEnabled
  // set to true.
  absl::optional<bool> GetThirdPartyCookieBlockingEnabled() const;

  // Records the metrics for the nostate prefetch to an event with UKM source ID
  // |source_id|.
  void RecordNoStatePrefetchMetrics(
      content::NavigationHandle* navigation_handle,
      ukm::SourceId source_id);

  // Records the metrics related to Generate URLs (Home page, default search
  // engine) for starting URL and committed URL.
  void RecordGeneratedNavigationUKM(ukm::SourceId source_id,
                                    const GURL& committed_url);

  // Records some metrics at the end of a page, even for failed provisional
  // loads.
  void RecordPageEndMetrics(
      const page_load_metrics::mojom::PageLoadTiming* timing,
      base::TimeTicks page_end_time,
      bool app_entered_background);

  // Records a score from the SiteEngagementService. Called when the page
  // becomes hidden, or at the end of the session if the page is never hidden.
  void RecordSiteEngagement() const;

  // Starts an async call to the cookie manager to determine if there are likely
  // to be cookies set on a mainframe request |url|. This is called on
  // navigation start and redirects but should not be called on commit because
  // it'll get cookies from the mainframe response, if any.
  void UpdateMainFrameRequestHadCookie(content::BrowserContext* browser_context,
                                       const GURL& url);

  // Used as a callback for the cookie manager query.
  void OnMainFrameRequestHadCookieResult(
      base::Time query_start_time,
      const net::CookieAccessResultList& cookies,
      const net::CookieAccessResultList& excluded_cookies);

  // Record some experimental cumulative shift metrics that have occurred on
  // the page until the first time the page moves from the foreground to the
  // background.
  void ReportLayoutInstabilityAfterFirstForeground();

  // Record some largest contentful paint metrics that have occurred on the
  // page until the first time the page starts in the foreground and moves to
  // the background.
  void ReportLargestContentfulPaintAfterFirstForeground();

  // Record some Responsiveness metrics that have occurred on the page until
  // the first time the page moves from the foreground to the background.
  void ReportResponsivenessAfterFirstForeground();

  // Guaranteed to be non-null during the lifetime of |this|.
  raw_ptr<network::NetworkQualityTracker> network_quality_tracker_;

  // The ID of this navigation, as recorded at each navigation start.
  int64_t navigation_id_ = -1;

  // The number of body (not header) prefilter bytes consumed by requests for
  // the page.
  int64_t cache_bytes_ = 0;
  int64_t network_bytes_ = 0;

  // Sum of decoded body lengths of JS resources in bytes.
  int64_t js_decoded_bytes_ = 0;

  // Max decoded body length of JS resources in bytes.
  int64_t js_max_decoded_bytes_ = 0;

  // Network data use broken down by resource type.
  int64_t image_total_bytes_ = 0;
  int64_t image_subframe_bytes_ = 0;
  int64_t media_bytes_ = 0;

  // Network quality estimates.
  net::EffectiveConnectionType effective_connection_type_ =
      net::EFFECTIVE_CONNECTION_TYPE_UNKNOWN;
  absl::optional<int32_t> http_response_code_;
  absl::optional<base::TimeDelta> http_rtt_estimate_;
  absl::optional<base::TimeDelta> transport_rtt_estimate_;
  absl::optional<int32_t> downstream_kbps_estimate_;

  // Total CPU wall time used by the page while in the foreground.
  base::TimeDelta total_foreground_cpu_time_;

  // Load timing metrics of the main frame resource request.
  content::NavigationHandleTiming navigation_handle_timing_;
  absl::optional<net::LoadTimingInfo> main_frame_timing_;

  // First contentful paint as reported in OnFirstContentfulPaintInPage.
  absl::optional<base::TimeDelta> first_contentful_paint_;

  // How the SiteInstance for the committed page was assigned a renderer.
  absl::optional<content::SiteInstanceProcessAssignment>
      render_process_assignment_;

  // PAGE_TRANSITION_LINK is the default PageTransition value.
  ui::PageTransition page_transition_ = ui::PAGE_TRANSITION_LINK;

  // True if the page started hidden, or ever became hidden.
  bool was_hidden_ = false;

  // True if the page main resource was served from disk cache.
  bool was_cached_ = false;

  // True if the navigation is a reload after the page has been discarded.
  bool was_discarded_ = false;

  // Whether the first URL in the redirect chain matches the default search
  // engine template.
  bool start_url_is_default_search_ = false;

  // Whether the first URL in the redirect chain matches the user's home page
  // URL.
  bool start_url_is_home_page_ = false;

  // The number of main frame redirects that occurred before commit.
  uint32_t main_frame_request_redirect_count_ = 0;

  // Set to true if any main frame request in the redirect chain had cookies set
  // on the request. Set to false if there were no cookies set. Not set if we
  // didn't get a response from the CookieManager before recording metrics.
  absl::optional<bool> main_frame_request_had_cookies_;

  // The browser context this navigation is operating in.
  raw_ptr<content::BrowserContext> browser_context_ = nullptr;

  // Whether the navigation resulted in the main frame being hosted in
  // a different process.
  bool navigation_is_cross_process_ = false;

  // True if this page was loaded in a portal and never activated. UKMs are
  // not recorded for this page unless the portal is activated.
  bool is_portal_ = false;

  // Difference between indices of the previous and current navigation entries
  // (i.e. item history for the current tab).
  // Typically -1/0/1 for back navigations / reloads / forward navigations.
  // 0 for most of navigations with replacement (e.g. location.replace).
  // 1 for regular navigations (link click / omnibox / etc).
  int navigation_entry_offset_ = 0;

  // Id for the main document, which persists across history navigations to the
  // same document.
  // Unique across the lifetime of the browser process.
  int main_document_sequence_number_ = -1;

  bool currently_in_foreground_ = false;
  // The last time the page became foregrounded, or navigation start if the page
  // started in the foreground and has not been backgrounded.
  base::TimeTicks last_time_shown_;
  base::TimeDelta total_foreground_duration_;

  // The navigation start timestamp.
  base::Time navigation_start_time_;

  // The connection info for the committed URL.
  absl::optional<net::HttpResponseInfo::ConnectionInfo> connection_info_;

  base::ReadOnlySharedMemoryMapping ukm_smoothness_data_;

  // Only true if the page became hidden after the first time it was shown in
  // the foreground, no matter how it started.
  bool was_hidden_after_first_show_in_foreground = false;

  // True if the TemplateURLService has a search engine template for the
  // navigation and a scoped search would have been possible.
  bool was_scoped_search_like_navigation_ = false;

  // True if the refresh rate is capped at 30Hz because of power saver mode when
  // navigation starts. It is possible but very unlikely for this to change mid
  // navigation, for instance due to a change by the user in settings or the
  // battery being recharged above 20%.
  bool refresh_rate_throttled_ = false;

  base::WeakPtrFactory<UkmPageLoadMetricsObserver> weak_factory_{this};
};

#endif  // CHROME_BROWSER_PAGE_LOAD_METRICS_OBSERVERS_CORE_UKM_PAGE_LOAD_METRICS_OBSERVER_H_


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">
    <link rel="icon" href="Images/68Favicon.png">

    <title>Further Reading</title>

    <link href="dist/css/bootstrap.min.css" rel="stylesheet">

    <link href="starter-template.css" rel="stylesheet">

          <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
            Toggle navigation

          </button>
          User-Friendly 68k

About

Basic Info

Opcode Table

Further Reading

   Further Reading

Wikipedia Article on the 68k Family
 Basic information and history about the 68k and related processors.

EASy68k Home Page
 The EASy68k is a free simulator and development environment, so you can develop programs for the 68k processor on your home computer.

Opcode Chart by Professor Charles Kelly
 This PDF download contains a table of opcodes that was central to the creation of our website.

68k Programmer's Manual
 This PDF download contains the full documentation for the processor. It is an excellent and comprehensive document, though very technical.

   Thank you for contributing to the User-Friendly 68k Project!


text:
(function() {
    angular
        .module('babyApp')
        .factory('resetservices', resetservices);

    resetservices.$inject = ['$resource', '$http'];

    function resetservices($resource, $http) {
        return {

            resetPassword: $resource('/resetPassword', {}, {
                go:{
                    method:'POST'
                }
            }),

        };
    }
})();


text:
DOM 3 XPath 1.0 implemention and helper for JavaScript, with node.js support.

Originally written by Cameron McCormack ([blog](http://mcc.id.au/xpathjs)).

Additional contributions from
Yaron Naveh ([blog](http://webservices20.blogspot.com/))
goto100
Thomas Weinert
Jimmy Rishe
and [others](https://github.com/goto100/xpath/graphs/contributors)

## Install
Install with [npm](http://github.com/isaacs/npm):

    npm install xpath

xpath is xml engine agnostic but I recommend to use [xmldom](https://github.com/jindw/xmldom):

    npm install xmldom

## API Documentation

Can be found [here](https://github.com/goto100/xpath/blob/master/docs/xpath%20methods.md). See below for example usage.

## Your first xpath:
`````javascript
var xpath = require('xpath')
  , dom = require('xmldom').DOMParser

var xml = "<book><title>Harry Potter</title></book>"
var doc = new dom().parseFromString(xml)
var nodes = xpath.select("//title", doc)

console.log(nodes[0].localName + ": " + nodes[0].firstChild.data)
console.log("Node: " + nodes[0].toString())
`````
➡

    title: Harry Potter
    Node: <title>Harry Potter</title>

### Alternatively

Using the same interface you have on modern browsers ([MDN])

`````javascript
var node = null;
var xml = "<book author='J. K. Rowling'><title>Harry Potter</title></book>"
var doc = new dom().parseFromString(xml)
var result = xpath.evaluate(
    "/book/title",            // xpathExpression
    doc,                        // contextNode
    null,                       // namespaceResolver
    xpath.XPathResult.ANY_TYPE, // resultType
    null                        // result
)

node = result.iterateNext();
while (node) {
    console.log(node.localName + ": " + node.firstChild.data);
    console.log("Node: " + node.toString());

    node = result.iterateNext();
}
`````
➡

    title: Harry Potter
    Node: <title>Harry Potter</title>

## Evaluate string values directly:
`````javascript
var xml = "<book><title>Harry Potter</title></book>";
var doc = new dom().parseFromString(xml);
var title = xpath.select("string(//title)", doc);

console.log(title);
`````
➡

    Harry Potter

## Namespaces
`````javascript
var xml = "<book><title xmlns='myns'>Harry Potter</title></book>"
var doc = new dom().parseFromString(xml)
var node = xpath.select("//*[local-name(.)='title' and namespace-uri(.)='myns']", doc)[0]

console.log(node.namespaceURI)
`````
➡

    myns

## Namespaces with easy mappings
`````javascript
var xml = "<book xmlns:bookml='http://example.com/book'><bookml:title>Harry Potter</bookml:title></book>"
var select = xpath.useNamespaces({"bookml": "http://example.com/book"});

console.log(select('//bookml:title/text()', doc)[0].nodeValue);
`````
➡

    Harry Potter

## Default namespace with mapping
`````javascript
var xml = "<book xmlns='http://example.com/book'><title>Harry Potter</title></book>"
var select = xpath.useNamespaces({"bookml": "http://example.com/book"});

console.log(select('//bookml:title/text()', doc)[0].nodeValue);
`````
➡

    Harry Potter

## Attributes
`````javascript
var xml = "<book author='J. K. Rowling'><title>Harry Potter</title></book>"
var doc = new dom().parseFromString(xml)
var author = xpath.select1("/book/@author", doc).value

console.log(author)
`````
➡

    J. K. Rowling

[MDN]: https://developer.mozilla.org/en/docs/Web/API/Document/evaluate

## License
MIT


text:
#Install dependencies
sudo apt-get update
sudo apt-get install -y wget git

wget -qO- https://raw.githubusercontent.com/creationix/nvm/v0.31.1/install.sh | sh
source $HOME/.nvm/nvm.sh
nvm install stable
nvm use stable

#Build and test sort-package-json
git clone https://github.com/keithamus/sort-package-json.git
cd sort-package-json/
npm install
npm audit fix
npm test


text:
package com.jx.androiddemos.dialog;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.text.SpannableStringBuilder;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.jx.androiddemos.R;

public class CustomDialog extends Dialog {

    public CustomDialog(Context context) {
        super(context);
    }

    public CustomDialog(Context context, int theme) {
        super(context, theme);
    }

    public static class Builder {
        private Context context;
        private String title;
        private String message;
        private String positiveButtonText;
        private String negativeButtonText;
        private View contentView;
        private OnClickListener positiveButtonClickListener;
        private OnClickListener negativeButtonClickListener;
        private int mLayoutId=-1;
        public Builder(Context context) {
            this.context = context;
        }

        public Builder setMessage(String message) {
            this.message = message;
            return this;
        }

        /**
         * Set the Dialog message from resource
         *
         * @param message
         * @return
         */
        public Builder setMessage(int message) {
            this.message = (String) context.getText(message);
            return this;
        }

        /**
         * Set the Dialog title from resource
         *
         * @param title
         * @return
         */
        public Builder setTitle(int title) {
            this.title = (String) context.getText(title);
            return this;
        }

        /**
         * Set the Dialog title from String
         *
         * @param title
         * @return
         */

        public Builder setTitle(String title) {
            this.title = title;
            return this;
        }

        public Builder setContentView(View v) {
            this.contentView = v;
            return this;
        }

        /**
         * set the Dialog layout
         * @param id layout id of dialog
         */
        public Builder setDialogLayout(int id){
            this.mLayoutId=id;
            return this;
        }

        /**
         * Set the positive button resource and it's listener
         *
         * @param positiveButtonText
         * @return
         */
        public Builder setPositiveButton(int positiveButtonText,
                                         OnClickListener listener) {
            this.positiveButtonText = (String) context
                    .getText(positiveButtonText);
            this.positiveButtonClickListener = listener;
            return this;
        }

        public Builder setPositiveButton(String positiveButtonText,
                                         OnClickListener listener) {
            this.positiveButtonText = positiveButtonText;
            this.positiveButtonClickListener = listener;
            return this;
        }

        public Builder setNegativeButton(int negativeButtonText,
                                         OnClickListener listener) {
            this.negativeButtonText = (String) context
                    .getText(negativeButtonText);
            this.negativeButtonClickListener = listener;
            return this;
        }

        public Builder setNegativeButton(String negativeButtonText,
                                         OnClickListener listener) {
            this.negativeButtonText = negativeButtonText;
            this.negativeButtonClickListener = listener;
            return this;
        }

        public CustomDialog create() {
            LayoutInflater inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            // instantiate the dialog with the custom Theme
            final CustomDialog dialog = new CustomDialog(context, R.style.AlertDialog);
            if (mLayoutId==-1){
                mLayoutId=R.layout.dialog_custom_layout;
            }
            View layout = inflater.inflate(mLayoutId, null);
            dialog.addContentView(layout, new LayoutParams(
                    LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
            // set the dialog title
            ((TextView) layout.findViewById(R.id.title)).setText(title);
            // set the confirm button
            if (positiveButtonText != null) {
                ((Button) layout.findViewById(R.id.positiveButton))
                        .setText(positiveButtonText);
                if (positiveButtonClickListener != null) {
                    ((Button) layout.findViewById(R.id.positiveButton))
                            .setOnClickListener(new View.OnClickListener() {
                                public void onClick(View v) {
                                    positiveButtonClickListener.onClick(dialog,
                                            DialogInterface.BUTTON_POSITIVE);
                                }
                            });
                }
            } else {
                // if no confirm button just set the visibility to GONE
                layout.findViewById(R.id.positiveButton).setVisibility(
                        View.GONE);
                layout.findViewById(R.id.Spliter).setVisibility(
                        View.GONE);
            }
            // set the cancel button
            if (negativeButtonText != null) {
                ((Button) layout.findViewById(R.id.negativeButton))
                        .setText(negativeButtonText);
                if (negativeButtonClickListener != null) {
                    ((Button) layout.findViewById(R.id.negativeButton))
                            .setOnClickListener(new View.OnClickListener() {
                                public void onClick(View v) {
                                    negativeButtonClickListener.onClick(dialog,
                                            DialogInterface.BUTTON_NEGATIVE);
                                }
                            });
                }
            } else {
                // if no confirm button just set the visibility to GONE
                layout.findViewById(R.id.negativeButton).setVisibility(
                        View.GONE);
                layout.findViewById(R.id.Spliter).setVisibility(
                        View.GONE);
            }
            // set the content message
            if (message != null) {
                ((TextView) layout.findViewById(R.id.message)).setText(SpannableStringBuilder.valueOf(message));
            } else if (contentView != null) {
                // if no message set
                // add the contentView to the dialog body
                ((LinearLayout) layout.findViewById(R.id.content))
                        .removeAllViews();
                ((LinearLayout) layout.findViewById(R.id.content)).addView(
                        contentView, new LayoutParams(
                                LayoutParams.WRAP_CONTENT,
                                LayoutParams.WRAP_CONTENT));
            }
            dialog.getWindow().getAttributes().windowAnimations = R.style.CustomDialogAnimation;
            dialog.setContentView(layout);
            return dialog;
        }

    }
}


text:
module Rack

  class ErrorLogger < RackLogger
    attr_reader :logger

    def initialize(app, logger, *filters)
      super
    end

    def call(env)
      begin
        @app.call(env)
      rescue => e
        logger.error("#{e.message}\r\n#{e.backtrace.join("\r\n")}")
        logger.flush
        raise e
      end
    end

  end
end


text:
package qt_replay

import (
	"bytes"
	"compress/gzip"
	"encoding/json"
	"errors"
	"github.com/watermint/toolbox/essentials/go/es_project"
	"github.com/watermint/toolbox/essentials/log/esl"
	"github.com/watermint/toolbox/essentials/network/nw_replay"
	"io"
	"io/ioutil"
	"path/filepath"
	"strings"
)

func LoadReplay(name string) (rr []nw_replay.Response, err error) {
	l := esl.Default().With(esl.String("name", name))
	root, err := es_project.DetectRepositoryRoot()
	if err != nil {
		l.Warn("Test path not found")
		return nil, err
	}
	tp := filepath.Join(root, "test")
	rp := filepath.Join(tp, "replay", name)

	l.Debug("Loading replay", esl.String("path", rp))
	all, err := ioutil.ReadFile(rp)
	if err != nil {
		l.Debug("Unable to load", esl.Error(err))
		return nil, err
	}

	if strings.HasSuffix(name, ".gz") {
		cr, err := gzip.NewReader(bytes.NewReader(all))
		if err != nil {
			l.Debug("Unable to create gzip reader", esl.Error(err))
			return nil, err
		}
		cbr := new(bytes.Buffer)
		if _, err := io.Copy(cbr, cr); err != nil {
			l.Debug("unable to uncompress", esl.Error(err))
			return nil, err
		}
		all = cbr.Bytes()
	}

	// if an array of Response
	if err := json.Unmarshal(all, &rr); err == nil {
		return rr, nil
	}

	rr = make([]nw_replay.Response, 0)
	chunks := strings.Split(string(all), "\n")
	for _, chunk := range chunks {
		if len(strings.TrimSpace(chunk)) < 1 {
			continue
		}
		res := nw_replay.Response{}
		if err := json.Unmarshal([]byte(chunk), &res); err != nil {
			l.Debug("Unable to unmarshal", esl.Error(err))
			return nil, err
		}
		rr = append(rr, res)
	}

	if len(rr) < 1 {
		l.Error("No replay loaded")
		return nil, errors.New("no replay loaded")
	}

	l.Debug("Replay loaded", esl.Int("numRecords", len(rr)))
	return rr, nil
}


text:
import controller from './edit.controller';

export default
    angular.module('inventoryScriptsEdit', [])
        .controller('InventoryScriptsEditController', controller);


text:
"""
Copyright (c) 2013 Rodrigo Baravalle
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. The name of the author may not be used to endorse or promote products
derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""
from imfractal import *

import time

def do_test():
    #path = '/almacen/members.imaglabs.org/felix.thomsen/Rodrigo/BioAsset/mats/'
    #filename = path + 'BA01_120_1Slices.mat'
    #file_mask = path + 'BA01_120_1Mask.mat'
    #i = MFS_3D()
    #i.setDef(1, 20, 3, filename, file_mask)
    #print "Calculating 3D MFS Multifractal Spectrum (Holder)..."
    #t = time.clock()
    #fds3 = i.getFDs()
    #t = time.clock() - t
    #print "Time 3D MFS: ", t
    #print fds3

    filename = 'images/baguette2.tif'#fractal20Bread.png'
    i = MFS()
    i.setDef(1,20,3)
    print "Calculating MFS Multifractal Spectrum..."
    t =  time.clock()
    fds3 = i.getFDs(filename)
    t =  time.clock()-t
    print "Time MFS: ", t
    print fds3

    i = Singularity(20)

#    print "Calculating Singularity Multifractal Spectrum..."
    #t =  time.clock()
    #fds = i.getFDs(filename)
    #t =  time.clock()-t
    #print "Time Singularity: ", t
    #print fds

    i = Sandbox(14)
    i.setDef(40,1.15, True)

    print "Calculating Sandbox Multifractal Spectrum..."
    t =  time.clock()
    fds2 = i.getFDs(filename)
    t =  time.clock()-t
    print "Time Sandbox: ", t
    print fds2


text:
module Rupt
  class Project
    attr_reader :project

    def initialize(config)
      PivotalTracker::Client.token = config.api_token
      puts config.project_id.inspect
      @project = PivotalTracker::Project.find(config.project_id)
    end

    def story(id)
      Story.new(project.stories.find(id))
    end

    def stories(filter_options = {})
      project.stories.all(filter_options).map(&Story.public_method(:new))
    end

    def current_stories
      project.iterations.current(project).stories.map(&Story.public_method(:new))
    end
  end
end


text:
module Monotony
	# Holds details of a transfer of funds from one entity to another.
	class Transaction
		attr_accessor :from, :to, :amount, :reason, :is_simulation
		attr_reader :reversed, :completed
		@@all = []

		def initialize(opts)
			opts = {
				reason: nil,
				is_simulation: false
			}.merge(opts)

			if opts[:from].respond_to? :account
				@from = opts[:from].account
			else
				@from = opts[:from]
			end

			if opts[:to].respond_to? :account
				@to = opts[:to].account
			else
				@to = opts[:to]
			end

			@amount = opts[:amount]
			@reason = opts[:reason]
			@reversed = false
			@is_simulation = @to.owner.respond_to?(:is_simulation) | @from.owner.respond_to?(:is_simuation)

			@@all << self
			complete unless @is_simulation
			self
		end

		def self.all
			@@all
		end

		# Complete the transaction if possible, otherwise proceed with liquidating assets if required.
		# @return [Boolean] whether or not the transaction was completed in full.
		def complete
			@from.short_of_cash(@amount) if @from.balance < @amount
			amount_to_pay = ( @from.balance >= @amount ? @amount : @from.balance )

			@to.receive(amount_to_pay)
			@from.deduct(amount_to_pay)
			paying_to = @to.owner.name

			if amount_to_pay < amount
				@from.owner.game.log '[%s] Unable to pay £%d to %s%s! Paid £%d instead' % [ @from.owner.name, amount, paying_to, ( @reason ? ' for %s' % @reason : '' ), amount_to_pay ]
				@from.owner.bankrupt!(@to.owner) if @from.owner.respond_to? :bankrupt!
				false
			else
				@from.owner.game.log '[%s] Paid £%d to %s%s (balance: £%d)' % [ @from.owner.name, amount, paying_to, ( @reason ? ' for %s' % @reason : '' ), @from.balance ]
				true
			end

			@completed = true
		end

		# Reverse the transaction.
		# @return [void]
		def reverse
			@to.deduct(amount)
			@from.receive(amount)
			@reversed = true
		end
	end
end


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.

namespace Test.Azure.Management.Logic
{
    using System.Linq;
    using Microsoft.Rest.ClientRuntime.Azure.TestFramework;
    using Xunit;
    using Microsoft.Azure.Management.Logic;
    using Microsoft.Azure.Management.Logic.Models;
    using Microsoft.Rest.Azure;
    using System.IO;

    /// <summary>
    /// Scenario tests for the integration accounts schema.
    /// </summary>
    [Collection("IntegrationAccountSchemaScenarioTests")]
    public class IntegrationAccountSchemaScenarioTests : ScenarioTestsBase
    {
        [Fact]
        public void IntegrationAccountSchemas_Create_OK()
        {
            using (var context = MockContext.Start(this.TestClassName))
            {
                var client = this.GetClient(context);
                this.CleanResourceGroup(client);
                var integrationAccountName = TestUtilities.GenerateName(Constants.IntegrationAccountPrefix);
                var integrationAccount = client.IntegrationAccounts.CreateOrUpdate(Constants.DefaultResourceGroup,
                    integrationAccountName,
                    this.CreateIntegrationAccount(integrationAccountName));

                var schemaName = TestUtilities.GenerateName(Constants.IntegrationAccountSchemaPrefix);
                var schema = this.CreateIntegrationAccountSchema(schemaName);
                var createdSchema = client.IntegrationAccountSchemas.CreateOrUpdate(Constants.DefaultResourceGroup,
                    integrationAccountName,
                    schemaName,
                    schema);

                this.ValidateSchema(schema, createdSchema);

                client.IntegrationAccounts.Delete(Constants.DefaultResourceGroup, integrationAccountName);
            }
        }

        [Fact]
        public void IntegrationAccountSchemas_Get_OK()
        {
            using (var context = MockContext.Start(this.TestClassName))
            {
                var client = this.GetClient(context);
                this.CleanResourceGroup(client);
                var integrationAccountName = TestUtilities.GenerateName(Constants.IntegrationAccountPrefix);
                var integrationAccount = client.IntegrationAccounts.CreateOrUpdate(Constants.DefaultResourceGroup,
                    integrationAccountName,
                    this.CreateIntegrationAccount(integrationAccountName));

                var schemaName = TestUtilities.GenerateName(Constants.IntegrationAccountSchemaPrefix);
                var schema = this.CreateIntegrationAccountSchema(schemaName);
                var createdSchema = client.IntegrationAccountSchemas.CreateOrUpdate(Constants.DefaultResourceGroup,
                    integrationAccountName,
                    schemaName,
                    schema);

                var retrievedSchema = client.IntegrationAccountSchemas.Get(Constants.DefaultResourceGroup,
                    integrationAccountName,
                    schemaName);

                this.ValidateSchema(schema, retrievedSchema);

                client.IntegrationAccounts.Delete(Constants.DefaultResourceGroup, integrationAccountName);
            }
        }

        [Fact]
        public void IntegrationAccountSchemas_List_OK()
        {
            using (var context = MockContext.Start(this.TestClassName))
            {
                var client = this.GetClient(context);
                this.CleanResourceGroup(client);
                var integrationAccountName = TestUtilities.GenerateName(Constants.IntegrationAccountPrefix);
                var integrationAccount = client.IntegrationAccounts.CreateOrUpdate(Constants.DefaultResourceGroup,
                    integrationAccountName,
                    this.CreateIntegrationAccount(integrationAccountName));

                var schemaName1 = TestUtilities.GenerateName(Constants.IntegrationAccountSchemaPrefix);
                var schema1 = this.CreateIntegrationAccountSchema(schemaName1);
                var createdSchema = client.IntegrationAccountSchemas.CreateOrUpdate(Constants.DefaultResourceGroup,
                    integrationAccountName,
                    schemaName1,
                    schema1);

                var schemaName2 = TestUtilities.GenerateName(Constants.IntegrationAccountSchemaPrefix);
                var schema2 = this.CreateIntegrationAccountSchema(schemaName2);
                var createdSchema2 = client.IntegrationAccountSchemas.CreateOrUpdate(Constants.DefaultResourceGroup,
                    integrationAccountName,
                    schemaName2,
                    schema2);

                var schemaName3 = TestUtilities.GenerateName(Constants.IntegrationAccountSchemaPrefix);
                var schema3 = this.CreateIntegrationAccountSchema(schemaName3);
                var createdSchema3 = client.IntegrationAccountSchemas.CreateOrUpdate(Constants.DefaultResourceGroup,
                    integrationAccountName,
                    schemaName3,
                    schema3);

                var schemas = client.IntegrationAccountSchemas.List(Constants.DefaultResourceGroup, integrationAccountName);

                Assert.Equal(3, schemas.Count());
                this.ValidateSchema(schema1, schemas.Single(x => x.Name == schema1.Name));
                this.ValidateSchema(schema2, schemas.Single(x => x.Name == schema2.Name));
                this.ValidateSchema(schema3, schemas.Single(x => x.Name == schema3.Name));

                client.IntegrationAccounts.Delete(Constants.DefaultResourceGroup, integrationAccountName);
            }
        }

        [Fact]
        public void IntegrationAccountSchemas_Update_OK()
        {
            using (var context = MockContext.Start(this.TestClassName))
            {
                var client = this.GetClient(context);
                this.CleanResourceGroup(client);
                var integrationAccountName = TestUtilities.GenerateName(Constants.IntegrationAccountPrefix);
                var integrationAccount = client.IntegrationAccounts.CreateOrUpdate(Constants.DefaultResourceGroup,
                    integrationAccountName,
                    this.CreateIntegrationAccount(integrationAccountName));

                var schemaName = TestUtilities.GenerateName(Constants.IntegrationAccountSchemaPrefix);
                var schema = this.CreateIntegrationAccountSchema(schemaName);
                var createdSchema = client.IntegrationAccountSchemas.CreateOrUpdate(Constants.DefaultResourceGroup,
                    integrationAccountName,
                    schemaName,
                    schema);

                var newSchema = this.CreateIntegrationAccountSchema(schemaName);
                var updatedSchema = client.IntegrationAccountSchemas.CreateOrUpdate(Constants.DefaultResourceGroup,
                    integrationAccountName,
                    schemaName,
                    newSchema);

                this.ValidateSchema(newSchema, updatedSchema);

                client.IntegrationAccounts.Delete(Constants.DefaultResourceGroup, integrationAccountName);
            }
        }

        [Fact]
        public void IntegrationAccountSchemas_Delete_OK()
        {
            using (var context = MockContext.Start(this.TestClassName))
            {
                var client = this.GetClient(context);
                this.CleanResourceGroup(client);
                var integrationAccountName = TestUtilities.GenerateName(Constants.IntegrationAccountPrefix);
                var integrationAccount = client.IntegrationAccounts.CreateOrUpdate(Constants.DefaultResourceGroup,
                    integrationAccountName,
                    this.CreateIntegrationAccount(integrationAccountName));

                var schemaName = TestUtilities.GenerateName(Constants.IntegrationAccountSchemaPrefix);
                var schema = this.CreateIntegrationAccountSchema(schemaName);
                var createdSchema = client.IntegrationAccountSchemas.CreateOrUpdate(Constants.DefaultResourceGroup,
                    integrationAccountName,
                    schemaName,
                    schema);

                client.IntegrationAccountSchemas.Delete(Constants.DefaultResourceGroup, integrationAccountName, schemaName);
                Assert.Throws<CloudException>(() => client.IntegrationAccountSchemas.Get(Constants.DefaultResourceGroup, integrationAccountName, schemaName));

                client.IntegrationAccounts.Delete(Constants.DefaultResourceGroup, integrationAccountName);
            }
        }

        [Fact]
        public void IntegrationAccountSchemas_DeleteWhenDeleteIntegrationAccount_OK()
        {
            using (var context = MockContext.Start(this.TestClassName))
            {
                var client = this.GetClient(context);
                this.CleanResourceGroup(client);
                var integrationAccountName = TestUtilities.GenerateName(Constants.IntegrationAccountPrefix);
                var integrationAccount = client.IntegrationAccounts.CreateOrUpdate(Constants.DefaultResourceGroup,
                    integrationAccountName,
                    this.CreateIntegrationAccount(integrationAccountName));

                var schemaName = TestUtilities.GenerateName(Constants.IntegrationAccountSchemaPrefix);
                var schema = this.CreateIntegrationAccountSchema(schemaName);
                var createdSchema = client.IntegrationAccountSchemas.CreateOrUpdate(Constants.DefaultResourceGroup,
                    integrationAccountName,
                    schemaName,
                    schema);

                client.IntegrationAccounts.Delete(Constants.DefaultResourceGroup, integrationAccountName);
                Assert.Throws<CloudException>(() => client.IntegrationAccountSchemas.Get(Constants.DefaultResourceGroup, integrationAccountName, schemaName));
            }
        }

        [Fact]
        public void IntegrationAccountSchemas_ListContentCallbackUrl_OK()
        {
            using (var context = MockContext.Start(this.TestClassName))
            {
                var client = this.GetClient(context);
                this.CleanResourceGroup(client);
                var integrationAccountName = TestUtilities.GenerateName(Constants.IntegrationAccountPrefix);
                var integrationAccount = client.IntegrationAccounts.CreateOrUpdate(Constants.DefaultResourceGroup,
                    integrationAccountName,
                    this.CreateIntegrationAccount(integrationAccountName));

                var schemaName = TestUtilities.GenerateName(Constants.IntegrationAccountSchemaPrefix);
                var schema = this.CreateIntegrationAccountSchema(schemaName);
                var createdSchema = client.IntegrationAccountSchemas.CreateOrUpdate(Constants.DefaultResourceGroup,
                    integrationAccountName,
                    schemaName,
                    schema);

                var contentCallbackUrl = client.IntegrationAccountSchemas.ListContentCallbackUrl(Constants.DefaultResourceGroup,
                    integrationAccountName,
                    schemaName,
                    new GetCallbackUrlParameters
                    {
                        KeyType = "Primary"
                    });

                Assert.Equal("GET", contentCallbackUrl.Method);
                Assert.Contains(schemaName, contentCallbackUrl.Value);

                client.IntegrationAccounts.Delete(Constants.DefaultResourceGroup, integrationAccountName);
            }
        }

        #region Private

        private void ValidateSchema(IntegrationAccountSchema expected, IntegrationAccountSchema actual)
        {
            Assert.Equal(expected.Name, actual.Name);
            Assert.Equal(expected.SchemaType, actual.SchemaType);
            Assert.Equal(expected.TargetNamespace, actual.TargetNamespace);
            Assert.NotEmpty(actual.ContentLink.Uri);
            Assert.NotNull(actual.ContentLink.ContentSize);
            Assert.NotNull(actual.CreatedTime);
            Assert.NotNull(actual.ChangedTime);
        }

        private IntegrationAccountSchema CreateIntegrationAccountSchema(string schemaName)
        {
            return new IntegrationAccountSchema(
                SchemaType.Xml,
                name: schemaName,
                location: Constants.DefaultLocation,
                targetNamespace: "http://Inbound_EDI.OrderFile",
                content: File.ReadAllText(@"TestData/OrderFile.xsd"),
                contentType: "application/xml");
        }

        #endregion
    }
}


text:
About
=========
Pony ORM is easy to use and powerful object-relational mapper for Python.
Using Pony, developers can create and maintain database-oriented software applications
faster and with less effort. One of the most interesting features of Pony is
its ability to write queries to the database using generator expressions.
Pony then analyzes the abstract syntax tree of a generator and translates it
to its SQL equivalent.

Following is an example of a query in Pony::

    select(p for p in Product if p.name.startswith('A') and p.cost <= 1000)

Such approach simplify the code and allows a programmer to concentrate
on the business logic of the application.

Pony translates queries to SQL using a specific database dialect.
Currently Pony works with SQLite, MySQL, PostgreSQL and Oracle databases.

The package `pony.orm.examples <https://github.com/ponyorm/pony/tree/orm/pony/orm/examples>`_
contains several examples.

Installation
=================
::

    pip install pony

Entity-Relationship Diagram Editor
=============================================
`Pony online ER Diagram Editor <https://editor.ponyorm.com>`_ is a great tool for prototyping.
You can draw your ER diagram online, generate  Pony entity declarations or SQL script for
creating database schema based on the diagram and start working with the database in seconds.

Pony ORM Links:
=================
- Main site: https://ponyorm.com
- Documentation: https://docs.ponyorm.com
- GitHub: https://github.com/ponyorm/pony
- Mailing list:  http://ponyorm-list.ponyorm.com
- ER Diagram Editor: https://editor.ponyorm.com
- Blog: https://blog.ponyorm.com


text:
use std::path::Path;

use parser::{
    common::{eyre::Result, once_cell::sync::Lazy, regex::Regex},
    formats::Format,
    graph_triples::{
        relations,
        resources::{self, ResourceDigest},
        Resource, ResourceInfo,
    },
    utils::apply_tags,
    Parser, ParserTrait,
};

/// A parser for the "Calc" language
pub struct CalcParser {}

impl ParserTrait for CalcParser {
    fn spec() -> Parser {
        Parser {
            language: Format::Calc,
        }
    }

    fn parse(resource: Resource, path: &Path, code: &str) -> Result<ResourceInfo> {
        static ASSIGN_REGEX: Lazy<Regex> = Lazy::new(|| {
            Regex::new(r"\s*([a-zA-Z_][a-zA-Z_0-9]*)\s*=(.*)").expect("Unable to create regex")
        });

        // Although we could parse the expression part of each line using `fasteval` and looking
        // for `EVar` nodes in the parse tree, it seems that walking the `fasteval`
        // parse tree is not trivial. So, this uses regex to get variable names (avoiding function
        // names)
        static VAR_REGEX: Lazy<Regex> = Lazy::new(|| {
            Regex::new(r"(\b[a-zA-Z_][a-zA-Z_0-9]*\b)(\s*\()?").expect("Unable to create regex")
        });

        // The semantic content of the code (includes the language name and ignores comments)
        let mut semantics = Self::spec().language.to_string();
        let mut comments = Vec::new();
        let relations = code
            .split('\n')
            .enumerate()
            .fold(Vec::new(), |mut pairs, (row, line)| {
                // Skip the line if it is blank
                if line.trim().is_empty() {
                    return pairs;
                }

                // Parse comment line
                if line.trim_start().starts_with('#') {
                    comments.push((row, line));
                    return pairs;
                }

                // Parse line for assignments
                let (start, expr) = if let Some(captures) = ASSIGN_REGEX.captures(line) {
                    let symbol = captures.get(1).expect("Should always have group 1");
                    let expr = captures.get(2).expect("Should always have group 2");
                    pairs.push((
                        relations::assigns((row, symbol.start(), row, symbol.end())),
                        resources::symbol(path, symbol.as_str(), "Number"),
                    ));
                    (expr.start(), expr.as_str())
                } else {
                    (0, line)
                };

                // Parse line for uses of variables
                for captures in VAR_REGEX.captures_iter(expr) {
                    if captures.get(2).is_none() {
                        let symbol = captures.get(1).expect("Should always have group 1");
                        pairs.push((
                            relations::uses((
                                row,
                                start + symbol.start(),
                                row,
                                start + symbol.end(),
                            )),
                            resources::symbol(path, symbol.as_str(), "Number"),
                        ))
                    }
                }

                // Add line to semantics
                semantics.push_str(line);
                semantics.push('\n');

                pairs
            });

        let mut resource_info = ResourceInfo::new(
            resource,
            Some(relations),
            None,
            None,
            Some(ResourceDigest::from_strings(code, Some(&semantics))),
            None,
            None,
        );

        // Apply tags from comments (this needs to be done at the end because tags
        // may remove pairs if `only` is specified)
        for (row, line) in comments {
            apply_tags(
                path,
                Self::spec().language,
                row,
                line,
                Some("Number".to_string()),
                &mut resource_info,
            );
        }

        Ok(resource_info)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use test_snaps::{insta::assert_json_snapshot, snapshot_fixtures};
    use test_utils::fixtures;

    #[test]
    fn calc_fragments() {
        snapshot_fixtures("fragments/calc/*.calc", |path| {
            let code = std::fs::read_to_string(path).expect("Unable to read");
            let path = path.strip_prefix(fixtures()).expect("Unable to strip");
            let resource = resources::code(path, "", "SoftwareSourceCode", Format::Calc);
            let resource_info = CalcParser::parse(resource, path, &code).expect("Unable to parse");
            assert_json_snapshot!(resource_info);
        })
    }
}


text:
#include "TimeStepping.hpp"

#include "TimeSteppingCombinedProjection.hpp"
#include "NewtonEulerDS.hpp"
#include "LagrangianDS.hpp"
#include "NewtonEuler1DR.hpp"
#include "OneStepIntegrator.hpp"
#include "MLCPProjectOnConstraints.hpp"
#include "NonSmoothLaw.hpp"
#include "NewtonEulerR.hpp"
#include "NonSmoothDynamicalSystem.hpp"
#include "Topology.hpp"
#include "MoreauJeanOSI.hpp"

//#define TSPROJ_DEBUG_LEVEL1
//#define TSPROJ_WITHOUT_PROJECTION
//#define DEBUG_STDOUT
//#define DEBUG_MESSAGES
//#define DEBUG_WHERE_MESSAGES
#include <debug.h>

TimeSteppingCombinedProjection::TimeSteppingCombinedProjection(
  SP::NonSmoothDynamicalSystem nsds,
  SP::TimeDiscretisation td,
  SP::OneStepIntegrator osi,
  SP::OneStepNSProblem osnspb_velo,
  SP::OneStepNSProblem osnspb_pos,
  unsigned int level)
  : TimeStepping(nsds,td, osi, osnspb_velo)
{
  (*_allNSProblems).resize(SICONOS_NB_OSNSP_TSP);
  insertNonSmoothProblem(osnspb_pos, SICONOS_OSNSP_TS_POS);

  _indexSetLevelForProjection = level;
  if(_indexSetLevelForProjection != 2)
  {
    THROW_EXCEPTION("TimeSteppingCombinedProjection::TimeSteppingCombinedProjection level not equal to 2 is not yet implemented.  ");

  }
  _constraintTol = 1e-08;
  _constraintTolUnilateral = 1e-08;
  _projectionMaxIteration = 50;
  _kIndexSetMax = 50;
  _doCombinedProj = true;
  _doCombinedProjOnEquality = true;
  _isIndexSetsStable = false;
  _maxViolationUnilateral = 0.0;
  _maxViolationEquality = 0.0;
}

// --- Destructor ---
TimeSteppingCombinedProjection::~TimeSteppingCombinedProjection()
{
}

struct TimeSteppingCombinedProjection::_SimulationEffectOnOSNSP : public SiconosVisitor
{

  using SiconosVisitor::visit;

  TimeSteppingCombinedProjection * _parent;

  _SimulationEffectOnOSNSP(TimeSteppingCombinedProjection * p) :
    _parent(p)
  {
    std::cout << "hello" << std::endl;
  };

  void visit(MLCPProjectOnConstraints &   onsnsp)
  {

    bool toto = (bool)_parent->doCombinedProjOnEquality();
    onsnsp.setDoProjOnEquality(toto);
  }
  void visit(MLCPProjectOnConstraints *   onsnsp)
  {
    std::cout << "hello" << std::endl;
  }
  void visit(MLCPProjectOnConstraints   onsnsp)
  {
    std::cout << "hello" << std::endl;
  }

};

void TimeSteppingCombinedProjection::initOSNS()
{
  TimeStepping::initOSNS();

  SP::OneStepNSProblem osnspb_pos = (*_allNSProblems)[SICONOS_OSNSP_TS_POS];

  osnspb_pos->setIndexSetLevel(_indexSetLevelForProjection);
  osnspb_pos->setInputOutputLevel(0);

  (*_allNSProblems)[SICONOS_OSNSP_TS_VELOCITY]->setIndexSetLevel(1);
  (*_allNSProblems)[SICONOS_OSNSP_TS_VELOCITY]->setInputOutputLevel(1);

  // better with visitor but I am not able to fix it.
  //_SimulationEffectOnOSNSP simulationEffectOnOSNSP(this);
  //osnspb_pos->accept(simulationEffectOnOSNSP);
  if(Type::value(*osnspb_pos) ==     Type::MLCPProjectOnConstraints)
  {
    // std::cout << "Type::name(*osnspb_pos) "<< Type::name(*osnspb_pos) <<std::endl;
    MLCPProjectOnConstraints * toto = static_cast<MLCPProjectOnConstraints*>(osnspb_pos.get());
    bool tutu = (bool)_doCombinedProjOnEquality;
    toto -> setDoProjOnEquality(tutu);
  }

}

void TimeSteppingCombinedProjection::advanceToEventOLD()
{

  initialize();

  newtonSolve(_newtonTolerance, _newtonMaxIteration);

  assert(0);
}

void TimeSteppingCombinedProjection::advanceToEvent()
{
  DEBUG_PRINT("================================================");
  DEBUG_PRINT("TimeSteppingCombinedProjection::advanceToEvent()");
  DEBUG_PRINT("================================================\n");

  initialize();

  _isIndexSetsStable = false;
  _maxViolationUnilateral = 0.0;
  _maxViolationEquality = 0.0;

  // Update interactions if a manager was provided
  updateInteractions();

  SP::Topology topo = _nsds->topology();
  if(topo->numberOfIndexSet() > _indexSetLevelForProjection)
  {
    SP::InteractionsGraph indexSet1 = topo->indexSet(1);
    SP::InteractionsGraph indexSet2 = topo->indexSet(2);
    assert(indexSet1);
    assert(indexSet2);

    InteractionsGraph::VIterator ui, uiend, vnext;

    // zeroing the lambda of indexSet1
    std::tie(ui, uiend) = indexSet1->vertices();
    for(vnext = ui; ui != uiend; ui = vnext)
    {
      ++vnext;
      SP::Interaction inter1 = indexSet1->bundle(*ui);
      inter1->lambda(1)->zero();
      indexSet1->eraseProperties(*ui);
      InteractionsGraph::OEIterator oei, oeiend;
      for(std::tie(oei, oeiend) = indexSet1->out_edges(*ui);
          oei != oeiend; ++oei)
      {
        InteractionsGraph::EDescriptor ed1, ed2;
        std::tie(ed1, ed2) = indexSet1->edges(indexSet1->source(*oei), indexSet1->target(*oei));
        if(ed2 != ed1)
        {
          indexSet1->eraseProperties(ed1);
          indexSet1->eraseProperties(ed2);
        }
        else
        {
          indexSet1->eraseProperties(ed1);
        }
      }
    }

    indexSet1->clear();

    std::tie(ui, uiend) = indexSet2->vertices();
    for(vnext = ui; ui != uiend; ui = vnext)
    {
      ++vnext;
      indexSet2->eraseProperties(*ui);
      InteractionsGraph::OEIterator oei, oeiend;
      for(std::tie(oei, oeiend) = indexSet2->out_edges(*ui);
          oei != oeiend; ++oei)
      {
        InteractionsGraph::EDescriptor ed1, ed2;
        std::tie(ed1, ed2) = indexSet2->edges(indexSet2->source(*oei), indexSet2->target(*oei));
        if(ed2 != ed1)
        {
          indexSet2->eraseProperties(ed1);
          indexSet2->eraseProperties(ed2);
        }
        else
        {
          indexSet2->eraseProperties(ed1);
        }
      }
    }

    indexSet2->clear();
  }

  _nbIndexSetsIteration = 0 ;
  _cumulatedNewtonNbIterations = 0 ;
  _nbCumulatedProjectionIteration = 0;

  while(!_isIndexSetsStable)
  {
    _nbIndexSetsIteration++ ;
    InteractionsGraph::VIterator ui, uiend;
    DEBUG_PRINTF("====================== _nbIndexSetsIteration = %i \n ", _nbIndexSetsIteration);

#ifdef TSPROJ_DEBUG_LEVEL1
    SP::InteractionsGraph indexSet0 = topo->indexSet(0);
    std::cout << "indexSet0->size() " << indexSet0->size()   <<std::endl;
    unsigned int level;
    SP::Interaction inter;
#endif

#ifdef TSPROJ_DEBUG_LEVEL2

    if(topo->numberOfIndexSet() > _indexSetLevelForProjection)
    {
      SP::InteractionsGraph indexSet1 = topo->indexSet(1);
      SP::InteractionsGraph indexSet2 = topo->indexSet(2);
      std::cout << "indexSet1->size() " << indexSet1->size()   <<std::endl;
      std::cout << "indexSet2->size() " << indexSet2->size()   <<std::endl;
    }

    for(std::tie(ui, uiend) = indexSet0->vertices(); ui != uiend; ++ui)
    {
      inter = indexSet0->bundle(*ui);

      std::cout << "inter->number()" << inter->number()   << std::endl;

      inter->computeOutput(getTkp1(), indexSet0->properties(*ui), 0);
      inter->computeOutput(getTkp1(), indexSet0->properties(*ui), 1);

      //  inter->swapInMemory();

      level = 0;

      assert(inter->lowerLevelForOutput() <= level);
      assert(inter->upperLevelForOutput() >= level);

      //std::cout << "inter->getSizeOfDS()" << inter->getSizeOfDS()     << std::endl;
      std::cout << "inter->y(" << level << ")"   << std::endl;
      inter->y(level)->display();

      std::cout << "inter->y_k(" << level << ")"   << std::endl;
      inter->y_k(level)->display();

      level = 1;
      assert(inter->lowerLevelForOutput() <= level);
      assert(inter->upperLevelForOutput() >= level);
      //std::cout << "inter->getSizeOfDS()" << inter->getSizeOfDS()     << std::endl;
      std::cout << "inter->y(" << level << ")"   << std::endl;
      inter->y(level)->display();
      std::cout << "inter->y_k(" << level << ")"   << std::endl;
      inter->y_k(level)->display();
    }

#endif

    if(_nbIndexSetsIteration > _kIndexSetMax)
    {
      THROW_EXCEPTION("TimeSteppingCombinedProjection::TimeSteppingCombinedProjection _nbIndexSetsIteration >  _kIndexSetMax ");
    }

    /** First step, Solve the standard velocity formulation.*/
    TimeStepping::newtonSolve(_newtonTolerance, _newtonMaxIteration);
    _cumulatedNewtonNbIterations += getNewtonNbIterations();

#ifdef TSPROJ_DEBUG_LEVEL1

    for(std::tie(ui, uiend) = indexSet0->vertices(); ui != uiend; ++ui)
    {
      inter = indexSet0->bundle(*ui);
      std::cout << "inter->number()" << inter->number()   << std::endl;

      level = 0;

      assert(inter->lowerLevelForOutput() <= level);
      assert(inter->upperLevelForOutput() >= level);

      //   std::cout << "inter->getSizeOfDS()" << inter->getSizeOfDS()     << std::endl;
      std::cout << "inter->y(" << level << ")"   << std::endl;
      inter->y(level)->display();
      std::cout << "inter->y_k(" << level << ")"   << std::endl;
      inter->y_k(level)->display();

      level = 1;
      assert(inter->lowerLevelForOutput() <= level);
      assert(inter->upperLevelForOutput() >= level);
      //std::cout << "inter->getSizeOfDS()" << inter->getSizeOfDS()     << std::endl;
      std::cout << "inter->y(" << level << ")"   << std::endl;
      inter->y(level)->display();
      std::cout << "inter->y_k(" << level << ")"   << std::endl;
      inter->y_k(level)->display();
    }
#endif

    int info = 0;

    // Zeroing Lambda Muliplier of indexSet()

    SP::InteractionsGraph indexSet = _nsds->topology()->indexSet(0);
    for(std::tie(ui, uiend) = indexSet->vertices(); ui != uiend; ++ui)
    {
      SP::Interaction inter = indexSet->bundle(*ui);
      inter->lambda(0)->zero();
    }
    _nsds->updateInput(nextTime(),0);

#ifdef TSPROJ_WITHOUT_PROJECTION

#else
    /** Second step, Perform the projection on constraints.*/
    DEBUG_PRINT("TimeSteppingCombinedProjection::newtonSolve begin projection:\n");

    SP::DynamicalSystemsGraph dsGraph = _nsds->dynamicalSystems();

    bool runningProjection = false;
    _nbProjectionIteration = 0;

    if(_nsds->topology()->numberOfIndexSet() > _indexSetLevelForProjection)
    {
      updateIndexSet(2);
      computeCriteria(&runningProjection);

#ifdef TSPROJ_DEBUG_LEVEL1

      SP::InteractionsGraph indexSet2 = topo->indexSet(2);
      SP::InteractionsGraph indexSet1 = topo->indexSet(1);
      if(indexSet2->size() > 1)
      {
        printf("indexSet2->size() = %i >1 \n", (int)indexSet2->size());
      }
      if(indexSet1->size() > 0)
      {
        printf("indexSet1->size() = %i >0 \n", (int)indexSet1->size());
      }

#endif

    }

    if(!runningProjection)
    {
      // Zeroing Lambda Muliplier of indexSet()

      SP::InteractionsGraph indexSet = _nsds->topology()->indexSet(0);
      InteractionsGraph::VIterator ui, uiend;
      for(std::tie(ui, uiend) = indexSet->vertices(); ui != uiend; ++ui)
      {
        SP::Interaction inter = indexSet->bundle(*ui);
        inter->lambda(0)->zero();
      }
      _nsds->updateInput(nextTime(),0);
    }

    //Store the q vector of each DS.

    for(DynamicalSystemsGraph::VIterator aVi2 = dsGraph->begin(); aVi2 != dsGraph->end(); ++aVi2)
    {
      SP::DynamicalSystem ds = dsGraph->bundle(*aVi2);
      Type::Siconos dsType = Type::value(*ds);
      VectorOfVectors& workVectors = *dsGraph->properties(*aVi2).workVectors;

      if(dsType == Type::NewtonEulerDS)
      {
        SP::NewtonEulerDS neds = std::static_pointer_cast<NewtonEulerDS>(ds);
        *workVectors[MoreauJeanOSI::QTMP] = *neds->q();
      }
      else if(dsType == Type::LagrangianDS || dsType == Type::LagrangianLinearTIDS)
      {
        SP::LagrangianDS d = std::static_pointer_cast<LagrangianDS> (ds);
        *workVectors[MoreauJeanOSI::QTMP] = * d->q();
      }
      else
        THROW_EXCEPTION("TimeSteppingCombinedProjection::advanceToEvent() :: - Ds is not from NewtonEulerDS neither from LagrangianDS.");
    }

    _nbProjectionIteration = 0;

    while((runningProjection && _nbProjectionIteration < _projectionMaxIteration) && _doCombinedProj)
    {
      _nbProjectionIteration++;

      DEBUG_PRINTF("Projection iteration number   %d\t", _nbProjectionIteration);
      DEBUG_PRINT("================================================\n");

      // Zeroing Lambda Muliplier of indexSet()

      SP::InteractionsGraph indexSet = _nsds->topology()->indexSet(0);
      InteractionsGraph::VIterator ui, uiend;
      for(std::tie(ui, uiend) = indexSet->vertices(); ui != uiend; ++ui)
      {
        SP::Interaction inter = indexSet->bundle(*ui);
        inter->lambda(0)->zero();
      }

      info = 0;
#ifdef TSPROJ_DEBUG_LEVEL1
      std::cout << "TimeSteppingCombinedProjection compute OSNSP POS." <<std::endl ;
#endif
      info = computeOneStepNSProblem(SICONOS_OSNSP_TS_POS);

      if(info)
      {
        std::cout << " TimeSteppingCombinedProjection::advanceToEvent() project on constraints. solver failed." <<std::endl ;
        return;
      }

      _nsds->updateInput(nextTime(),0);

      for(DynamicalSystemsGraph::VIterator aVi2 = dsGraph->begin(); aVi2 != dsGraph->end(); ++aVi2)
      {
        SP::DynamicalSystem ds = dsGraph->bundle(*aVi2);
        Type::Siconos dsType = Type::value(*ds);
        VectorOfVectors& workVectors = *dsGraph->properties(*aVi2).workVectors;

        if(dsType == Type::NewtonEulerDS)
        {
          SP::NewtonEulerDS neds = std::static_pointer_cast<NewtonEulerDS>(ds);
          SP::SiconosVector q = neds->q();

          SP::SiconosVector qtmp = workVectors[MoreauJeanOSI::QTMP];
          if(neds->p(0))
          {
            //*q = * qtmp +  *neds->p(0);
            *q +=  *neds->p(0);
          }
          neds->normalizeq();
          //neds->computeT();

#ifdef TSPROJ_DEBUG_LEVEL1
          neds->display();
#endif

        }
        else if(dsType == Type::LagrangianDS || dsType == Type::LagrangianLinearTIDS)
        {
          SP::LagrangianDS d = std::static_pointer_cast<LagrangianDS> (ds);
          SP::SiconosVector q = d->q();
          SP::SiconosVector qtmp = workVectors[MoreauJeanOSI::QTMP];
          if(d->p(0))
          {
            //*q = * qtmp +  *d->p(0);
            *q +=  *d->p(0);
          }
#ifdef TSPROJ_DEBUG_LEVEL1
          std::cout << " q=" << std::endl;
          q->display();
          std::cout << " p(0)=" << std::endl;
          d->p(0)->display();
          std::cout << " p(1)=" << std::endl;
          d->p(1)->display();
#endif
        }
        else
          THROW_EXCEPTION("TimeSteppingCombinedProjection::advanceToEvent() - Ds is not from NewtonEulerDS neither from LagrangianDS.");

      }

      updateWorldFromDS();

      computeCriteria(&runningProjection);

      //cout<<"||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||  Z:"<<endl;
      //(*_allNSProblems)[SICONOS_OSNSP_TS_POS]->display();
      //(std::static_pointer_cast<LinearOSNS>((*_allNSProblems)[SICONOS_OSNSP_TS_POS]))->z()->display();

#ifdef TSPROJ_DEBUG_LEVEL1

      // SP::InteractionsGraph indexSet1 = _nsds->topology()->indexSet(1);
      // std ::cout << "lambda(1) in IndexSet1" << std::endl;
      // for (std::tie(ui, uiend) = indexSet1->vertices(); ui != uiend; ++ui)
      // {
      //   SP::Interaction inter = indexSet1->bundle(*ui);
      //   inter->lambda(1)->display();
      // }
      SP::InteractionsGraph indexSet2 = _nsds->topology()->indexSet(2);
      std ::cout << "lambda(0) in indexSet2" << std::endl;
      for(std::tie(ui, uiend) = indexSet2->vertices(); ui != uiend; ++ui)
      {
        SP::Interaction inter = indexSet2->bundle(*ui);
        inter->lambda(0)->display();
      }

#endif

      //cout<<"during projection before normalizing of q:\n";
      //for (InteractionsIterator it = allInteractions->begin(); it != allInteractions->end(); it++)
      //{
      //  (*it)->relation()->computeh(getTkp1());
      //}
    } // end while ((runningProjection && _nbProjectionIteration < _projectionMaxIteration) && _doCombinedProj)

    DEBUG_PRINTF("TimeSteppingCombinedProjection::Projection end : Number of iterations= %i\n", _nbProjectionIteration);

    _nbCumulatedProjectionIteration += _nbProjectionIteration ;
    if(_nbProjectionIteration == _projectionMaxIteration)
    {
      std::cout << "TimeSteppingCombinedProjection::advanceToEvent() Max number of projection iterations reached (" << _nbProjectionIteration << ")"  <<std::endl ;
      printf("              max criteria equality =  %e.\n", _maxViolationEquality);
      printf("              max criteria unilateral =  %e.\n", _maxViolationUnilateral);
    }

#endif // TSPROJ_WITHOUT_PROJECTION

    DEBUG_PRINT("TimeSteppingCombinedProjection::newtonSolve end projection:\n");

    // We update forces to start the Newton Loop the next tiem step with a correct value in swap
    for(DynamicalSystemsGraph::VIterator aVi2 = dsGraph->begin(); aVi2 != dsGraph->end(); ++aVi2)
    {
      SP::DynamicalSystem ds = dsGraph->bundle(*aVi2);
      Type::Siconos dsType = Type::value(*ds);
      if(dsType == Type::NewtonEulerDS)
      {
        SP::NewtonEulerDS neds = std::static_pointer_cast<NewtonEulerDS>(ds);
        double time = nextTime();
        neds->computeForces(time, neds->q(), neds->twist());
      }
      else if(dsType == Type::LagrangianDS)
      {
        SP::LagrangianDS d = std::static_pointer_cast<LagrangianDS> (ds);
        double time = nextTime();
        d->computeForces(time, d->q(),d->velocity());
      }
      else if(dsType == Type::LagrangianLinearTIDS)
      {
      }
      else
        THROW_EXCEPTION("TimeSteppingCombinedProjection::advanceToEvent() - Ds is not from NewtonEulerDS neither from LagrangianDS.");
    }

    if(_nsds->topology()->numberOfIndexSet() > _indexSetLevelForProjection)
    {
      updateIndexSet(1);
    }
    else
    {
      _isIndexSetsStable = true;
    }
#ifdef TSPROJ_DEBUG_LEVEL1

    if(topo->numberOfIndexSet() > _indexSetLevelForProjection)
    {
      SP::InteractionsGraph indexSet1 = topo->indexSet(1);
      SP::InteractionsGraph indexSet2 = topo->indexSet(2);
      std::cout << "indexSet1->size() " << indexSet1->size()   <<std::endl;
      std::cout << "indexSet2->size() " << indexSet2->size()   <<std::endl;
    }

    level = 0;
    for(std::tie(ui, uiend) = indexSet0->vertices(); ui != uiend; ++ui)
    {
      inter =indexSet0->bundle(*ui);
      assert(inter->lowerLevelForOutput() <= level);
      assert(inter->upperLevelForOutput() >= level);
      inter->computeOutput(getTkp1(), indexSet0->properties(*ui), 0);
      inter->computeOutput(getTkp1(), indexSet0->properties(*ui), 1);

      std::cout << "inter->getSizeOfDS()" << inter->getSizeOfDS()     << std::endl;
      std::cout << "inter->y(" << level << ")"   << std::endl;
      inter->y(level)->display();
      std::cout << "inter->y_k(" << level << ")"   << std::endl;
      inter->y_k(level)->display();
    }
    level = 1;
    for(std::tie(ui, uiend) = indexSet0->vertices(); ui != uiend; ++ui)
    {
      inter =indexSet0->bundle(*ui);
      assert(inter->lowerLevelForOutput() <= level);
      assert(inter->upperLevelForOutput() >= level);
      std::cout << "inter->getSizeOfDS()" << inter->getSizeOfDS()     << std::endl;
      std::cout << "inter->y(" << level << ")"   << std::endl;
      inter->y(level)->display();
      std::cout << "inter->y_k(" << level << ")"   << std::endl;
      inter->y_k(level)->display();
    }

#endif

  }// end  while (!_isIndexSetsStable)

  DEBUG_PRINTF("TimeSteppingCombinedProjection::indexset stable end : Number of iterations= %i \n ",_nbIndexSetsIteration);

  return;
}

void TimeSteppingCombinedProjection::computeCriteria(bool * runningProjection)
{
  DEBUG_PRINT("TimeSteppingCombinedProjection::computeCriteria(bool * runningProjection)\n");
  // SP::InteractionsGraph indexSet = _nsds->topology()->indexSet(_indexSetLevelForProjection);
  SP::InteractionsGraph indexSet = _nsds->topology()->indexSet(_indexSetLevelForProjection);

  InteractionsGraph::VIterator aVi, viend;

  double maxViolationEquality = -1e24;
  double maxViolationUnilateral = -1e24;

  *runningProjection = false;

  for(std::tie(aVi, viend) = indexSet->vertices();
      aVi != viend; ++aVi)
  {
    SP::Interaction interac = indexSet->bundle(*aVi);

    interac->computeOutput(getTkp1(),  0);
    interac->relation()->computeJach(getTkp1(), *interac);

    if(Type::value(*(interac->nonSmoothLaw())) ==  Type::NewtonImpactFrictionNSL ||
        Type::value(*(interac->nonSmoothLaw())) == Type::NewtonImpactNSL)
    {

#ifdef TSPROJ_DEBUG_LEVEL1
      printf("  TimeSteppingCombinedProjection::computeCriteria  Unilateral interac->y(0)->getValue(0) %e.\n", interac->y(0)->getValue(0));
#endif
      if(!_doCombinedProjOnEquality)
      {
        if(maxViolationUnilateral > _constraintTolUnilateral)
        {
          double criteria = std::max(0.0, - interac->y(0)->getValue(0));
          if(criteria > maxViolationUnilateral) maxViolationUnilateral = criteria;

          *runningProjection = true;
#ifdef TSPROJ_DEBUG_LEVEL1
          printf("TSProj newton criteria unilateral true %e.\n", criteria);
#endif
        }
      }
      else
      {
        double criteria = interac->y(0)->getValue(0);
        if(criteria > maxViolationUnilateral) maxViolationUnilateral = criteria;

        if(std::abs(criteria) >=  _constraintTolUnilateral)
        {
          *runningProjection = true;
#ifdef TSPROJ_DEBUG_LEVEL1
          printf("TSProj newton criteria unilateral true %e.\n", criteria);
#endif
        }
      }

    }
    else
    {
      DEBUG_EXPR(interac->y(0)->display(););
      if(interac->y(0)->normInf()  > maxViolationEquality)
      {
        DEBUG_EXPR(interac->y(0)->display(););
        maxViolationEquality = interac->y(0)->normInf() ;
      }
      if(interac->y(0)->normInf() > _constraintTol)
      {
        *runningProjection = true;
#ifdef TSPROJ_DEBUG_LEVEL1
        printf("TSProj  newton criteria equality true %e.\n", interac->y(0)->normInf());
#endif
      }
    }

  }

  _maxViolationUnilateral = maxViolationUnilateral;
  _maxViolationEquality = maxViolationEquality;

  DEBUG_PRINTF("              max criteria equality =  %e.\n", _maxViolationEquality);
  DEBUG_PRINTF("              max criteria unilateral =  %e.\n", _maxViolationUnilateral);

#ifdef TSPROJ_DEBUG_LEVEL1
  printf("TSProj newton min/max criteria projection\n");
  std::cout << "                 runningProjection  "  << *runningProjection << std::endl;
  printf("              max criteria equality =  %e.\n", maxViolationEquality);
  printf("              max criteria unilateral =  %e.\n", maxViolationUnilateral);
  //  printf("              min criteria unilateral =  %e.\n",minViolationUnilateral);
#endif
}

void TimeSteppingCombinedProjection::updateIndexSet(unsigned int i)
{
  // To update IndexSet i: add or remove Interactions from
  // this set, depending on y values.
  // boost::default_color_type is used to organize update in InteractionsGraph:
  // - white_color : undiscovered vertex (Interaction)
  // - gray_color : discovered vertex (Interactions) but searching descendants
  // - black_color : discovered vertex (Interaction) together with the descendants

  assert(_nsds);
  assert(_nsds->topology());

  SP::Topology topo = _nsds->topology();

  assert(i < topo->indexSetsSize() &&
         "TimeStepping::updateIndexSet(i), indexSets[i] does not exist.");
  // IndexSets[0] must not be updated in simulation, since it belongs to Topology.
  assert(i > 0 &&
         "TimeStepping::updateIndexSet(i=0), indexSets[0] cannot be updated.");

  // For all Interactions in indexSet[i-1], compute y[i-1] and
  // update the indexSet[i].

  SP::InteractionsGraph indexSet0 = topo->indexSet(0);
  SP::InteractionsGraph indexSet1 = topo->indexSet(1);
  SP::InteractionsGraph indexSet2 = topo->indexSet(2);
  DynamicalSystemsGraph& DSG0= *nonSmoothDynamicalSystem()->dynamicalSystems();
  assert(indexSet0);
  assert(indexSet1);
  assert(indexSet2);

  topo->setHasChanged(false);

  DEBUG_PRINTF("update indexSets start : indexSet0 size : %i\n", (int)(indexSet0->size()));

  // Check indexSet1

  if(i == 1)
  {
    InteractionsGraph::VIterator ui1, ui1end, v1next;

    std::tie(ui1, ui1end) = indexSet1->vertices();
    _isIndexSetsStable = true ;

    DEBUG_PRINTF("update IndexSets start : indexSet1 size : %i\n", (int)(indexSet1->size()));
    // indexSet1->display();
    //Remove interactions from the indexSet1
    for(v1next = ui1; ui1 != ui1end; ui1 = v1next)
    {
      ++v1next;
      SP::Interaction inter1 = indexSet1->bundle(*ui1);
      if(indexSet0->is_vertex(inter1))
      {
        InteractionsGraph::VDescriptor ur1_descr0 = indexSet0->descriptor(inter1);
        assert((indexSet0->color(ur1_descr0) == boost::white_color));
        indexSet0->color(ur1_descr0) = boost::gray_color;
      }
      // else
      // {
      //   // Interactions is not in indexSet0 anymore.
      //   // ui1 becomes invalid
      //   indexSet1->remove_vertex(inter1);
      //   topo->setHasChanged(true);
      //   _isIndexSetsStable=false;
      // }
    }

    // indexSet0\indexSet1 scan
    InteractionsGraph::VIterator ui0, ui0end;
    //Add interaction in indexSet1
    for(std::tie(ui0, ui0end) = indexSet0->vertices(); ui0 != ui0end; ++ui0)
    {
      if(indexSet0->color(*ui0) == boost::black_color)
      {
        // reset
        indexSet0->color(*ui0) = boost::white_color ;
      }
      else
      {
        if(indexSet0->color(*ui0) == boost::gray_color)
        {
          // reset
          indexSet0->color(*ui0) = boost::white_color;

          assert(indexSet1->is_vertex(indexSet0->bundle(*ui0)));
          /*assert( { !predictorDeactivate(indexSet0->bundle(*ui0),i) ||
            Type::value(*(indexSet0->bundle(*ui0)->interaction()->nonSmoothLaw())) == Type::EqualityConditionNSL ;
            });*/
        }
        else
        {
          assert(indexSet0->color(*ui0) == boost::white_color);

          SP::Interaction inter0 = indexSet0->bundle(*ui0);
          assert(!indexSet1->is_vertex(inter0));

          bool activate = true;
          if(Type::value(*(inter0->nonSmoothLaw())) != Type::EqualityConditionNSL)
          {
            //SP::OneStepIntegrator Osi = indexSet0->properties(*ui0).osi;
            // We assume that the integrator of the ds1 drive the update of the index set
            SP::DynamicalSystem ds1 = indexSet1->properties(*ui0).source;
            OneStepIntegrator& osi = *DSG0.properties(DSG0.descriptor(ds1)).osi;

            activate = osi.addInteractionInIndexSet(inter0, i);
          }
          if(activate)
          {
            assert(!indexSet1->is_vertex(inter0));

            // vertex and edges insertion in indexSet1
            indexSet1->copy_vertex(inter0, *indexSet0);
            topo->setHasChanged(true);
            _isIndexSetsStable = false ;
            assert(indexSet1->is_vertex(inter0));
          }
        }
      }
    }
    indexSet1->update_vertices_indices();
    indexSet1->update_edges_indices();
    assert(indexSet1->size() <= indexSet0->size());
    DEBUG_PRINTF("update indexSets end : indexSet0 size : %i\n", (int)(indexSet0->size()));
    DEBUG_PRINTF("update IndexSets end : indexSet1 size : %i\n", (int)(indexSet1->size()));
  } // i==1

  if(i == 2)
  {
    InteractionsGraph::VIterator ui1, ui1end, v1next;
    std::tie(ui1, ui1end) = indexSet2->vertices();

    for(v1next = ui1; ui1 != ui1end; ui1 = v1next)
    {
      ++v1next;
      indexSet2->eraseProperties(*ui1);
      InteractionsGraph::OEIterator oei, oeiend;
      for(std::tie(oei, oeiend) = indexSet2->out_edges(*ui1);
          oei != oeiend; ++oei)
      {
        InteractionsGraph::EDescriptor ed1, ed2;
        std::tie(ed1, ed2) = indexSet2->edges(indexSet2->source(*oei), indexSet2->target(*oei));
        if(ed2 != ed1)
        {
          indexSet2->eraseProperties(ed1);
          indexSet2->eraseProperties(ed2);
        }
        else
        {
          indexSet2->eraseProperties(ed1);
        }
      }
    }

    indexSet2->clear();
    DEBUG_PRINTF("update IndexSets start : indexSet2 size : %i\n", (int)(indexSet2->size()));

    // Scan indexSet1
    std::tie(ui1, ui1end) = indexSet1->vertices();
    for(v1next = ui1; ui1 != ui1end; ui1 = v1next)
    {
      ++v1next;
      SP::Interaction inter1 = indexSet1->bundle(*ui1);
      bool activate = true;
      if(Type::value(*(inter1->nonSmoothLaw())) != Type::EqualityConditionNSL)
      {
        //SP::OneStepIntegrator Osi = indexSet1->properties(*ui1).osi;
        // We assume that the integrator of the ds1 drive the update of the index set
        SP::DynamicalSystem ds1 = indexSet1->properties(*ui1).source;
        OneStepIntegrator& osi = *DSG0.properties(DSG0.descriptor(ds1)).osi;

        activate = osi.addInteractionInIndexSet(inter1, i);
      }
      if(activate)
      {
        assert(!indexSet2->is_vertex(inter1));

        // vertex and edges insertion in indexSet2
        indexSet2->copy_vertex(inter1, *indexSet1);
        topo->setHasChanged(true);
        assert(indexSet2->is_vertex(inter1));
      }
    }
    DEBUG_PRINTF("update IndexSets end : indexSet0 size : %i\n", (int)(indexSet0->size()));
    DEBUG_PRINTF("update IndexSets end : indexSet2 size : %i\n", (int)(indexSet2->size()));
    indexSet2->update_vertices_indices();
    indexSet2->update_edges_indices();

  }

}


text:
module AssignableTypes
  extend ActiveSupport::Concern

  included do
    validate :validate_type
  end

  def short_type
    @short_type ||= type.split("::").pop
  end

  def validate_type
    errors.add(:type, "cannot be changed once an instance has been created") if type_changed? && !new_record?
    errors.add(:type, "is not a valid type") unless self.class.valid_type?(type)
  end

  module ClassMethods
    def load_types_in(module_name, my_name = module_name.singularize)
      const_set(:MODULE_NAME, module_name)
      const_set(:BASE_CLASS_NAME, my_name)
      const_set(:TYPES, Dir[Rails.root.join("app", "models", module_name.underscore, "*.rb")].map { |path| module_name + "::" + File.basename(path, ".rb").camelize })
    end

    def types
      const_get(:TYPES).map(&:constantize)
    end

    def valid_type?(type)
      const_get(:TYPES).include?(type)
    end

    def build_for_type(type, user, attributes)
      attributes.delete(:type)

      if valid_type?(type)
        type.constantize.new(attributes).tap do |instance|
          instance.user = user if instance.respond_to?(:user=)
        end
      else
        const_get(:BASE_CLASS_NAME).constantize.new(attributes).tap do |instance|
          instance.type = type
          instance.user = user if instance.respond_to?(:user=)
        end
      end
    end
  end
end


text:
package org.biobank.platedecoder.ui.scene.decodersettings;

import org.biobank.platedecoder.ui.ValidatedTextField;

import javafx.scene.image.ImageView;

enum TextFieldData {
   DECODER_DEBUG_LEVEL(
      0,
      9,
      "Decoder debug level:",
      "A non zero value displays debugging information.",
      "Decoder debug level should be a number between "),
   EDGE_MIN(
      0,
      100,
      "Edge minimum",
      "The length of the smallest expected edge in the image as a percentage of the cell width.",
      "Edge minimum factor should be a value between "),
   EDGE_MAX(
      0,
      100,
      "Edge maximum:",
      "The length of the largest expected edge in the image as a percentage of the cell width.",
      "Edge maximum factor should be a value between "),
   SCAN_GAP(
      0,
      100,
      "Scan gap:",
      "The gap between lines in the scan grid used to examine the image"
      + " as a percentage of the cell width.",
      "Scan gap factor should be a value between "),
   EDGE_THRESHOLD(
      0,
      100,
      "Edge threshold:",
      "The minimum edge threshold as a percentage of maximum. For example, an edge between a pure\n"
      + " white and pure black pixel would have an intensity of 100.",
      "Edge threshold should be a a value between "),
   SQUARE_DEVIATION(
      0,
      45,
      "Square deviation:",
      "The maximum deviation, in degrees, from squareness between adjacent barcode sides.\n"
      + "10 degrees is the recommened value for flat images.",
      "Square deviation should be a value between "),
   CORRECTIONS(
      0,
      20,
      "Corrections:",
      "The number of errors to correct per image.",
      "Corrections should be a number between ");

   final long minimum;

   final long maximum;

   final String label;

   final String errorMessage;

   final String description;

   final ValidatedTextField textField;

   private TextFieldData(long minimum,
                         long maximum,
                         String label,
                         String description,
                         String errorMessagePrefix) {
      this.minimum      = minimum;
      this.maximum      = maximum;
      this.label        = label;
      this.description  = description;
      this.textField    = new ValidatedTextField();

      StringBuffer buf = new StringBuffer();
      buf.append(errorMessagePrefix);
      buf.append(minimum);
      buf.append(" and ");
      buf.append(maximum);

      this.errorMessage = buf.toString();
   }

   ImageView getErrorImageView() {
      return textField.getErrorImageView();
   }

   long getValue() {
      return Long.valueOf(textField.getText());
   }

   void setValue(long value) {
      textField.setText(String.valueOf(value));
   }

   void setErrorImageVisible(boolean visible) {
      textField.setErrorImageVisible(visible);
   }

   boolean isValid(int value) {
      return (value >= minimum) && (value <= maximum);
   }
}