text:
package ca.cmput301f13t03.adventure_datetime.view;

import android.app.Activity;
import android.app.Dialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Parcelable;
import android.provider.MediaStore;
import android.util.Log;
import android.view.*;
import android.view.View.OnClickListener;
import android.widget.*;
import ca.cmput301f13t03.adventure_datetime.R;
import ca.cmput301f13t03.adventure_datetime.model.*;
import ca.cmput301f13t03.adventure_datetime.model.Interfaces.ICommentsListener;
import ca.cmput301f13t03.adventure_datetime.model.Interfaces.ICurrentFragmentListener;
import ca.cmput301f13t03.adventure_datetime.model.Interfaces.ICurrentStoryListener;
import ca.cmput301f13t03.adventure_datetime.serviceLocator.Locator;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * Shows comments available for stories & storfragments. Only available for online stories.
 *
 * @author James Finlay
 */
public class CommentsView extends Activity implements ICurrentStoryListener,
									ICurrentFragmentListener, ICommentsListener {
	private static final String TAG = "CommentsView";
	public static final String COMMENT_TYPE = "forStory";
    private static final int PICTURE_REQUEST = 1;

	private ListView _listView;
    private ProgressBar _bar;
	private Story _story;
	private StoryFragment _fragment;
	private List<Comment> _comments;
	private RowArrayAdapter _adapter;
	private boolean forStoryEh;
    private Uri _commentPic;

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

		forStoryEh = getIntent().getBooleanExtra(COMMENT_TYPE, true);

		_listView = (ListView) findViewById(R.id.list_view);
        _bar = (ProgressBar) findViewById(R.id.progressBar);

		setUpView();
	}
	@Override
	protected void onResume() {
		if (forStoryEh)
			Locator.getPresenter().Subscribe((ICurrentStoryListener)this);
		else
			Locator.getPresenter().Subscribe((ICurrentFragmentListener)this);
		super.onResume();
	}
	@Override
	protected void onPause() {
		if (forStoryEh) {
			Locator.getPresenter().Unsubscribe((ICurrentStoryListener)this);
            if (_story != null)	Locator.getPresenter().Unsubscribe(_story.getId());
		} else {
			Locator.getPresenter().Unsubscribe((ICurrentFragmentListener)this);
            if (_fragment != null) Locator.getPresenter().Unsubscribe(_fragment.getFragmentID());
		}

		super.onPause();
	}
	@Override
	public void OnCurrentStoryChange(Story story) {
		_story = story;
		Log.v(TAG, "subscribe story");
		Locator.getPresenter().Subscribe((ICommentsListener) this, _story.getId());
		setUpView();
	}
	@Override
	public void OnCurrentFragmentChange(StoryFragment fragment) {
		_fragment = fragment;
		Log.v(TAG, "subscribe fragment");
		Locator.getPresenter().Subscribe((ICommentsListener)this, _fragment.getFragmentID());
		setUpView();
	}
	@Override
	public void OnCommentsChange(List<Comment> newComments) {
		_comments = newComments;
		Log.v(TAG, "Comments received. Count: " + newComments.size());
		setUpView();
	}
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.comment_menu, menu);
		return true;
	}
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.action_new:
			final Dialog dia = new Dialog(CommentsView.this);
			dia.setTitle("New Comment");
			dia.setContentView(R.layout.comment_add);
			dia.setCancelable(true);

			/** Layout items **/
			final EditText txt = (EditText) dia.findViewById(R.id.content);
			Button okay = (Button) dia.findViewById(R.id.okay);
			Button cancel = (Button) dia.findViewById(R.id.cancel);
            Button photo = (Button) dia.findViewById(R.id.media);
            /* Set image to null in case 2 comments are made */
            _commentPic = null;

			okay.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {

					Comment c = new Comment();
					c.setAuthor(AccountService.getUserName(getContentResolver()));
					c.setContent(txt.getText().toString());
					if (forStoryEh)	c.setTargetId(_story.getId());
					else c.setTargetId(_fragment.getFragmentID());

                    if(_commentPic != null) {
                        try {
                            InputStream is = getContentResolver().openInputStream(_commentPic);
                            Bitmap bit = BitmapFactory.decodeStream(is);
                            c.setImage(Image.compressBitmap(bit, 85));
                        }
                        catch(Exception e) {
                            e.printStackTrace();
                        }
                    }

                    Locator.getUserController().AddComment(c);

					dia.dismiss();
				}
			});
			cancel.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					dia.dismiss();
				}
			});

            photo.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    File picDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
                            "adventure.datetime");
                    if(!picDir.exists()) picDir.mkdirs();
                    File pic = null;
                    try {
                        pic = File.createTempFile("adventure.comment_", "_temp", picDir);
                    }
                    catch(IOException e) {
                        e.printStackTrace();
                    }
                    Uri location = Uri.fromFile(pic);

                    final List<Intent> cameraIntents = new ArrayList<Intent>();
                    final Intent captureIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                    final PackageManager packageManager = getPackageManager();
                    final List<ResolveInfo> listCam = packageManager.queryIntentActivities(captureIntent, 0);
                    for(ResolveInfo res : listCam) {
                        final String packageName = res.activityInfo.packageName;
                        final Intent intent = new Intent(captureIntent);
                        intent.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
                        intent.setPackage(packageName);
                        intent.putExtra(MediaStore.EXTRA_OUTPUT, location);
                        _commentPic = location;
                        cameraIntents.add(intent);
                    }

                    // Filesystem.
                    final Intent galleryIntent = new Intent();
                    galleryIntent.setType("image/*");
                    galleryIntent.setAction(Intent.ACTION_GET_CONTENT);

                    // Chooser of filesystem options.
                    final Intent chooserIntent = Intent.createChooser(galleryIntent, "Select Source");

                    // Add the camera options.
                    chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, cameraIntents.toArray(new Parcelable[]{}));

                    startActivityForResult(chooserIntent, PICTURE_REQUEST);

                }
            });
			dia.show();

			break;
		}
		return true;
	}
	private void setUpView() {
		if (_listView == null) return;
		if (_comments == null) return;
		if (_story == null && forStoryEh) return;
		if (_fragment == null && !forStoryEh) return;

		runOnUiThread(new Runnable() {
			public void run() {
				_adapter = new RowArrayAdapter(getApplicationContext(),
						R.layout.comment_single, _comments.toArray(new Comment[_comments.size()]));
				_listView.setAdapter(_adapter);
                _bar.setVisibility(View.GONE);
			}
		});

	}

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(resultCode == RESULT_OK) {
            if(requestCode == PICTURE_REQUEST) {
                final boolean isCamera;
                if(data == null) {
                    isCamera = true;
                }
                else {
                    final String action = data.getAction();
                    if(action == null) {
                        isCamera = false;
                    }
                    else {
                        isCamera = action.equals(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                    }
                }

                Uri selectedImageUri;
                if(isCamera) {
                    selectedImageUri = _commentPic;
                }
                else {
                    selectedImageUri = data == null ? null : data.getData();
                }
                _commentPic = selectedImageUri;
            }
        }
    }

	private class RowArrayAdapter extends ArrayAdapter<Comment> {

		private Context context;
		private Comment[] values;

		public RowArrayAdapter(Context context, int layoutResourceID, Comment values[]) {
			super(context, layoutResourceID, values);

			this.context = context;
			this.values = values;
		}
		public View getView(int position, View convertView, ViewGroup parent) {
			LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

			View rowView = inflater.  inflate(R.layout.comment_single, parent, false);

			Comment item = values[position];

			/** Layout Items **/
			TextView author = (TextView) rowView.findViewById(R.id.author);
			TextView date = (TextView) rowView.findViewById(R.id.datetime);
			Button btnImage = (Button) rowView.findViewById(R.id.image_button);
			RelativeLayout layImage = (RelativeLayout) rowView.findViewById(R.id.wrapper);
			TextView content = (TextView) rowView.findViewById(R.id.content);
            ImageView image = (ImageView) rowView.findViewById(R.id.image);

			author.setText(item.getAuthor());
			content.setText(item.getContent());
			date.setText(item.getFormattedTimestamp());
            if (item.getImage() == null)
               btnImage.setVisibility(View.GONE);
            else
			    image.setImageBitmap(item.decodeImage());
			layImage.setVisibility(View.GONE);
			btnImage.setOnClickListener(new ShowOnClickListener().
					setUp(layImage, btnImage));

			return rowView;
		}

	}

	private class ShowOnClickListener implements OnClickListener {

		private RelativeLayout _layout;
		private Button _button;

		public OnClickListener setUp(RelativeLayout layout, Button button) {
			_layout = layout;
			_button = button;
			return this;
		}
		@Override
		public void onClick(View v) {
			_layout.setVisibility(View.VISIBLE);
			_button.setText("Hide Image");
			_button.setOnClickListener(new HideOnClickListener().
					setUp(_layout, _button));
		}
	}

	private class HideOnClickListener implements OnClickListener {

		private RelativeLayout _layout;
		private Button _button;

		public OnClickListener setUp(RelativeLayout layout, Button button) {
			_layout = layout;
			_button = button;
			return this;
		}
		@Override
		public void onClick(View v) {
			_layout.setVisibility(View.GONE);
			_button.setText("Show Image");
			_button.setOnClickListener(new ShowOnClickListener().
					setUp(_layout, _button));
		}
	}
}


text:
namespace Sitecore.Ecommerce.DomainModel.Orders
{
  using System;
  using System.Collections.Generic;
  using System.Linq;

  /// <summary>
  /// The order status.
  /// </summary>
  [Serializable]
  public abstract class OrderStatus : IComparable
  {
    /// <summary>
    /// Gets or sets code for the order status
    /// </summary>
    public virtual string Code { get; set; }

    /// <summary>
    /// Gets or sets title for the order status
    /// </summary>
    public virtual string Title { get; set; }

    /// <summary>
    /// Gets the available following statuses.
    /// </summary>
    /// <returns>Collection of the available following statuses</returns>
    public abstract IEnumerable<OrderStatus> GetAvailableFollowingStatuses();

    /// <summary>Compares to instances.</summary>
    /// <param name="obj">The obj.</param>
    /// <exception cref="ArgumentException"><c>ArgumentException</c>.</exception>
    /// <returns>The result of the comparison of the Type names.</returns>
    int IComparable.CompareTo(object obj)
    {
      OrderStatus otherOrderStatus = obj as OrderStatus;
      if (otherOrderStatus != null)
      {
        return this.GetType().Name.CompareTo(otherOrderStatus.GetType().Name);
      }

      throw new ArgumentException("Object is not a OrderStatus");
    }

    /// <summary>
    /// Processes the specified order.
    /// </summary>
    /// <typeparam name="T">The order type.</typeparam>
    /// <param name="order">The order instance.</param>
    protected virtual void Process<T>(T order) where T : Order
    {
      throw new NotImplementedException();
    }
  }
}

redpajama_set_name: RedPajamaGithub


text:
{{question}}

    {{value}}{{unit}}

{{question}}

        		Dein Tipp war
        		{{value}}{{unit}}{{template}}

{{sourcetitle}}


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <title>pymatgen.analysis.diffraction.core module — pymatgen 2019.10.16 documentation</title>
    <link rel="stylesheet" href="_static/proBlue.css" type="text/css" />
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />

    <link rel="index" title="Index" href="genindex.html" />
    <link rel="search" title="Search" href="search.html" />

Navigation

          index

          modules |

pymatgen 2019.10.16 documentation »

pymatgen.analysis.diffraction.core module¶

class AbstractDiffractionPatternCalculator[source]¶

Bases: abc.ABC

Abstract base class for computing the diffraction pattern of a crystal.

SCALED_INTENSITY_TOL = 0.001¶

TWO_THETA_TOL = 1e-05¶

abstract get_pattern(structure, scaled=True, two_theta_range=(0, 90))[source]¶

Calculates the diffraction pattern for a structure.

Parameters

structure (Structure) – Input structure

scaled (bool) – Whether to return scaled intensities. The maximum
peak is set to a value of 100. Defaults to True. Use False if
you need the absolute values to combine XRD plots.

two_theta_range ([float of length 2]) – Tuple for range of
two_thetas to calculate in degrees. Defaults to (0, 90). Set to
None if you want all diffracted beams within the limiting
sphere of radius 2 / wavelength.

Returns

(DiffractionPattern)

get_plot(structure, two_theta_range=(0, 90), annotate_peaks=True, ax=None, with_labels=True, fontsize=16)[source]¶

Returns the diffraction plot as a matplotlib.pyplot.

Parameters

structure – Input structure

two_theta_range ([float of length 2]) – Tuple for range of
two_thetas to calculate in degrees. Defaults to (0, 90). Set to
None if you want all diffracted beams within the limiting
sphere of radius 2 / wavelength.

annotate_peaks – Whether to annotate the peaks with plane
information.

ax – matplotlib Axes or None if a new figure should be created.

with_labels – True to add xlabels and ylabels to the plot.

fontsize – (int) fontsize for peak labels.

Returns

(matplotlib.pyplot)

plot_structures(structures, fontsize=6, **kwargs)[source]¶

Plot diffraction patterns for multiple structures on the same figure.

Parameters

structures (Structure) – List of structures

two_theta_range ([float of length 2]) – Tuple for range of
two_thetas to calculate in degrees. Defaults to (0, 90). Set to
None if you want all diffracted beams within the limiting
sphere of radius 2 / wavelength.

annotate_peaks (bool) – Whether to annotate the peaks with plane
information.

fontsize – (int) fontsize for peak labels.

Keyword arguments controlling the display of the figure:

<colgroup>
<col style="width: 23%" />
<col style="width: 77%" />
</colgroup>

kwargs

Meaning

title

Title of the plot (Default: None).

show

True to show the figure (default: True).

savefig

"abc.png" or "abc.eps" to save the figure to a file.

size_kwargs

Dictionary with options passed to fig.set_size_inches
e.g. size_kwargs=dict(w=3, h=4)

tight_layout

True to call fig.tight_layout (default: False)

ax_grid

True (False) to add (remove) grid from all axes in fig.
Default: None i.e. fig is left unchanged.

ax_annotate

Add labels to  subplots e.g. (a), (b).
Default: False

show_plot(structure, **kwargs)[source]¶

Shows the diffraction plot.

Parameters

structure (Structure) – Input structure

two_theta_range ([float of length 2]) – Tuple for range of
two_thetas to calculate in degrees. Defaults to (0, 90). Set to
None if you want all diffracted beams within the limiting
sphere of radius 2 / wavelength.

annotate_peaks (bool) – Whether to annotate the peaks with plane
information.

class DiffractionPattern(x, y, hkls, d_hkls)[source]¶

Bases: pymatgen.core.spectrum.Spectrum

A representation of a diffraction pattern

Parameters

x – Two theta angles.

y – Intensities

hkls – [{"hkl": (h, k, l), "multiplicity": mult}],
where {"hkl": (h, k, l), "multiplicity": mult}
is a dict of Miller
indices for all diffracted lattice facets contributing to each
intensity.

d_hkls – List of interplanar spacings.

XLABEL = '$2\\Theta$'¶

YLABEL = 'Intensity'¶

get_unique_families(hkls)[source]¶

Returns unique families of Miller indices. Families must be permutations
of each other.

Parameters

hkls ([h, k, l]) – List of Miller indices.

Returns

multiplicity}: A dict with unique hkl and multiplicity.

Return type

{hkl

This Page

Show Source

Quick search

    <form class="search" action="search.html" method="get">
      <input type="text" name="q" aria-labelledby="searchlabel" />
      <input type="submit" value="Go" />
    </form>

Navigation

          index

          modules |

pymatgen 2019.10.16 documentation »

        © Copyright 2011, Pymatgen Development Team.
      Created using Sphinx 2.2.0.

This page uses
Google Analytics to collect statistics. You can disable it by blocking
the JavaScript coming from www.google-analytics.com.


text:
package ca.loganspeck.eden.account;

import org.apache.commons.lang3.tuple.Pair;

import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Optional;
import java.util.Queue;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

public abstract class BaseAccountRegistry implements AccountRegistry {

    private Map<UUID, Account> accounts;
    private Map<UUID, String> tempNicknames;

    public BaseAccountRegistry() {
        accounts = new HashMap<>();
        tempNicknames = new HashMap<>();
    }

    @Override
    public boolean isEmpty() {
        return accounts.isEmpty();
    }

    @Override
    public boolean has(UUID uuid) {
        return accounts.containsKey(uuid);
    }

    @Override
    public Optional<Account> getFromUUID(UUID uuid) {
        return Optional.ofNullable(accounts.get(uuid));
    }

    @Override
    public Collection<Account> getFromIPv4(String ipv4) {
        Set<Account> ipv4Matches = new HashSet<>();
        accounts.values().stream().filter(account -> account.getIpHistory().contains(ipv4.trim())).forEach(ipv4Matches::add);
        return ipv4Matches;
    }

    @Override
    public Optional<Account> getFromName(String name) {
        return accounts.values().stream().filter(account -> account.getName().equalsIgnoreCase(name)).findFirst();
    }

    @Override
    public Map<UUID, Account> getAllAccounts() {
        return accounts;
    }

    @Override
    public Optional<Account> register(Account account) {
        Account potentialConflict = accounts.put(account.getUUID(), account);

        if(potentialConflict == null) {
            return Optional.empty();
        }

        return Optional.ofNullable(potentialConflict);
    }

    @Override
    public Optional<Account> unregister(UUID uuid) {
        return Optional.ofNullable(accounts.remove(uuid));
    }

    @Override
    public Optional<String> getPersistentNickname(UUID uuid) {
        return null;
    }

    @Override
    public void setPersistentNickname(UUID uuid, String nickname) {

    }

    @Override
    public Optional<String> getTemporaryNickname(UUID uuid) {
        return null;
    }

    @Override
    public void setTemporaryNickname(UUID uuid, String nickname) {

    }

    @Override
    public Map<UUID, Account> clean() {
        return null;
    }

    @Override
    public Map<UUID, Account> purge() {
        return null;
    }

    @Override
    public boolean isAutoSaving() {
        return false;
    }

    @Override
    public void setAutoSaving(boolean autoSaving) {

    }

    @Override
    public Pair<TimeUnit, Double> getAutoSaveInterval() {
        return null;
    }

    @Override
    public int getSavesPerInterval() {
        return 0;
    }

    @Override
    public void setSavesPerInterval(int savesPerInterval) {

    }

    @Override
    public Queue<UUID> getSaveQueue() {
        return null;
    }

    @Override
    public boolean isQueuedForSave(UUID uuid) {
        return false;
    }

    @Override
    public boolean queueForSave(UUID uuid) {
        return false;
    }

    @Override
    public void flushSaveQueue() {

    }

    @Override
    public Pair<TimeUnit, Double> getPostCacheTimeProperties() {
        return null;
    }

    @Override
    public void setPostCacheTimeProperties(Pair<TimeUnit, Double> postCacheTimeProperties) {

    }

    @Override
    public boolean exists(UUID uuid) {
        return false;
    }

}


text:
package org.apereo.cas.config;

import org.apereo.cas.CentralAuthenticationService;
import org.apereo.cas.audit.AuditTrailConstants;
import org.apereo.cas.audit.AuditTrailRecordResolutionPlan;
import org.apereo.cas.audit.AuditTrailRecordResolutionPlanConfigurer;
import org.apereo.cas.audit.AuditableExecution;
import org.apereo.cas.authentication.AuthenticationSystemSupport;
import org.apereo.cas.authentication.principal.PrincipalFactory;
import org.apereo.cas.authentication.principal.PrincipalFactoryUtils;
import org.apereo.cas.authentication.principal.Service;
import org.apereo.cas.authentication.principal.ServiceFactory;
import org.apereo.cas.configuration.CasConfigurationProperties;
import org.apereo.cas.configuration.support.Beans;
import org.apereo.cas.services.DenyAllAttributeReleasePolicy;
import org.apereo.cas.services.RegexRegisteredService;
import org.apereo.cas.services.ServiceRegistryExecutionPlan;
import org.apereo.cas.services.ServiceRegistryExecutionPlanConfigurer;
import org.apereo.cas.services.ServicesManager;
import org.apereo.cas.support.oauth.OAuth20Constants;
import org.apereo.cas.support.oauth.authenticator.Authenticators;
import org.apereo.cas.support.oauth.authenticator.OAuth20CasAuthenticationBuilder;
import org.apereo.cas.support.oauth.authenticator.OAuth20ClientIdClientSecretAuthenticator;
import org.apereo.cas.support.oauth.authenticator.OAuth20ProofKeyCodeExchangeAuthenticator;
import org.apereo.cas.support.oauth.authenticator.OAuth20UsernamePasswordAuthenticator;
import org.apereo.cas.support.oauth.profile.DefaultOAuth20ProfileScopeToAttributesFilter;
import org.apereo.cas.support.oauth.profile.DefaultOAuth20UserProfileDataCreator;
import org.apereo.cas.support.oauth.profile.OAuth20ProfileScopeToAttributesFilter;
import org.apereo.cas.support.oauth.profile.OAuth20UserProfileDataCreator;
import org.apereo.cas.support.oauth.services.OAuth20ServiceRegistry;
import org.apereo.cas.support.oauth.util.OAuth20Utils;
import org.apereo.cas.support.oauth.validator.authorization.OAuth20AuthorizationCodeResponseTypeAuthorizationRequestValidator;
import org.apereo.cas.support.oauth.validator.authorization.OAuth20AuthorizationRequestValidator;
import org.apereo.cas.support.oauth.validator.authorization.OAuth20IdTokenResponseTypeAuthorizationRequestValidator;
import org.apereo.cas.support.oauth.validator.authorization.OAuth20ProofKeyCodeExchangeResponseTypeAuthorizationRequestValidator;
import org.apereo.cas.support.oauth.validator.authorization.OAuth20TokenResponseTypeAuthorizationRequestValidator;
import org.apereo.cas.support.oauth.validator.token.OAuth20AuthorizationCodeGrantTypeProofKeyCodeExchangeTokenRequestValidator;
import org.apereo.cas.support.oauth.validator.token.OAuth20AuthorizationCodeGrantTypeTokenRequestValidator;
import org.apereo.cas.support.oauth.validator.token.OAuth20ClientCredentialsGrantTypeTokenRequestValidator;
import org.apereo.cas.support.oauth.validator.token.OAuth20DeviceCodeResponseTypeRequestValidator;
import org.apereo.cas.support.oauth.validator.token.OAuth20PasswordGrantTypeTokenRequestValidator;
import org.apereo.cas.support.oauth.validator.token.OAuth20RefreshTokenGrantTypeTokenRequestValidator;
import org.apereo.cas.support.oauth.validator.token.OAuth20TokenRequestValidator;
import org.apereo.cas.support.oauth.web.OAuth20CasCallbackUrlResolver;
import org.apereo.cas.support.oauth.web.audit.AccessTokenGrantRequestAuditResourceResolver;
import org.apereo.cas.support.oauth.web.audit.AccessTokenResponseAuditResourceResolver;
import org.apereo.cas.support.oauth.web.audit.OAuth20UserProfileDataAuditResourceResolver;
import org.apereo.cas.support.oauth.web.endpoints.OAuth20AccessTokenEndpointController;
import org.apereo.cas.support.oauth.web.endpoints.OAuth20AuthorizeEndpointController;
import org.apereo.cas.support.oauth.web.endpoints.OAuth20CallbackAuthorizeEndpointController;
import org.apereo.cas.support.oauth.web.endpoints.OAuth20DeviceUserCodeApprovalEndpointController;
import org.apereo.cas.support.oauth.web.endpoints.OAuth20IntrospectionEndpointController;
import org.apereo.cas.support.oauth.web.endpoints.OAuth20UserProfileEndpointController;
import org.apereo.cas.support.oauth.web.mgmt.OAuth20TokenManagementEndpoint;
import org.apereo.cas.support.oauth.web.response.OAuth20CasClientRedirectActionBuilder;
import org.apereo.cas.support.oauth.web.response.OAuth20DefaultCasClientRedirectActionBuilder;
import org.apereo.cas.support.oauth.web.response.accesstoken.OAuth20DefaultTokenGenerator;
import org.apereo.cas.support.oauth.web.response.accesstoken.OAuth20TokenGenerator;
import org.apereo.cas.support.oauth.web.response.accesstoken.ext.AccessTokenAuthorizationCodeGrantRequestExtractor;
import org.apereo.cas.support.oauth.web.response.accesstoken.ext.AccessTokenClientCredentialsGrantRequestExtractor;
import org.apereo.cas.support.oauth.web.response.accesstoken.ext.AccessTokenDeviceCodeResponseRequestExtractor;
import org.apereo.cas.support.oauth.web.response.accesstoken.ext.AccessTokenGrantAuditableRequestExtractor;
import org.apereo.cas.support.oauth.web.response.accesstoken.ext.AccessTokenGrantRequestExtractor;
import org.apereo.cas.support.oauth.web.response.accesstoken.ext.AccessTokenPasswordGrantRequestExtractor;
import org.apereo.cas.support.oauth.web.response.accesstoken.ext.AccessTokenProofKeyCodeExchangeAuthorizationCodeGrantRequestExtractor;
import org.apereo.cas.support.oauth.web.response.accesstoken.ext.AccessTokenRefreshTokenGrantRequestExtractor;
import org.apereo.cas.support.oauth.web.response.accesstoken.response.OAuth20AccessTokenResponseGenerator;
import org.apereo.cas.support.oauth.web.response.accesstoken.response.OAuth20DefaultAccessTokenResponseGenerator;
import org.apereo.cas.support.oauth.web.response.callback.OAuth20AuthorizationCodeAuthorizationResponseBuilder;
import org.apereo.cas.support.oauth.web.response.callback.OAuth20AuthorizationResponseBuilder;
import org.apereo.cas.support.oauth.web.response.callback.OAuth20ClientCredentialsResponseBuilder;
import org.apereo.cas.support.oauth.web.response.callback.OAuth20ResourceOwnerCredentialsResponseBuilder;
import org.apereo.cas.support.oauth.web.response.callback.OAuth20TokenAuthorizationResponseBuilder;
import org.apereo.cas.support.oauth.web.views.ConsentApprovalViewResolver;
import org.apereo.cas.support.oauth.web.views.OAuth20CallbackAuthorizeViewResolver;
import org.apereo.cas.support.oauth.web.views.OAuth20ConsentApprovalViewResolver;
import org.apereo.cas.support.oauth.web.views.OAuth20DefaultUserProfileViewRenderer;
import org.apereo.cas.support.oauth.web.views.OAuth20UserProfileViewRenderer;
import org.apereo.cas.ticket.ExpirationPolicy;
import org.apereo.cas.ticket.UniqueTicketIdGenerator;
import org.apereo.cas.ticket.accesstoken.AccessTokenFactory;
import org.apereo.cas.ticket.accesstoken.DefaultAccessTokenFactory;
import org.apereo.cas.ticket.accesstoken.OAuthAccessTokenExpirationPolicy;
import org.apereo.cas.ticket.code.DefaultOAuthCodeFactory;
import org.apereo.cas.ticket.code.OAuthCodeExpirationPolicy;
import org.apereo.cas.ticket.code.OAuthCodeFactory;
import org.apereo.cas.ticket.device.DefaultDeviceTokenFactory;
import org.apereo.cas.ticket.device.DeviceTokenFactory;
import org.apereo.cas.ticket.refreshtoken.DefaultRefreshTokenFactory;
import org.apereo.cas.ticket.refreshtoken.OAuthRefreshTokenExpirationPolicy;
import org.apereo.cas.ticket.refreshtoken.RefreshTokenFactory;
import org.apereo.cas.ticket.registry.TicketRegistry;
import org.apereo.cas.ticket.support.HardTimeoutExpirationPolicy;
import org.apereo.cas.util.CollectionUtils;
import org.apereo.cas.util.DefaultUniqueTicketIdGenerator;
import org.apereo.cas.util.RandomUtils;
import org.apereo.cas.web.support.CookieRetrievingCookieGenerator;

import lombok.val;
import org.apereo.inspektr.audit.spi.support.DefaultAuditActionResolver;
import org.pac4j.cas.client.CasClient;
import org.pac4j.cas.config.CasConfiguration;
import org.pac4j.core.config.Config;
import org.pac4j.core.context.session.J2ESessionStore;
import org.pac4j.core.credentials.UsernamePasswordCredentials;
import org.pac4j.core.credentials.authenticator.Authenticator;
import org.pac4j.core.http.url.UrlResolver;
import org.pac4j.http.client.direct.DirectBasicAuthClient;
import org.pac4j.http.client.direct.DirectFormClient;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.actuate.autoconfigure.endpoint.condition.ConditionalOnEnabledEndpoint;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Set;

/**
 * This this {@link CasOAuthConfiguration}.
 *
 * @author Misagh Moayyed
 * @author Dmitriy Kopylenko
 * @since 5.0.0
 */
@Configuration("oauthConfiguration")
@EnableConfigurationProperties(CasConfigurationProperties.class)
public class CasOAuthConfiguration implements AuditTrailRecordResolutionPlanConfigurer, ServiceRegistryExecutionPlanConfigurer {

    @Autowired
    @Qualifier("registeredServiceAccessStrategyEnforcer")
    private AuditableExecution registeredServiceAccessStrategyEnforcer;

    @Autowired
    private ApplicationContext applicationContext;

    @Autowired
    @Qualifier("centralAuthenticationService")
    private CentralAuthenticationService centralAuthenticationService;

    @Autowired
    private CasConfigurationProperties casProperties;

    @Autowired
    @Qualifier("webApplicationServiceFactory")
    private ServiceFactory webApplicationServiceFactory;

    @Autowired
    @Qualifier("servicesManager")
    private ObjectProvider<ServicesManager> servicesManager;

    @Autowired
    @Qualifier("defaultAuthenticationSystemSupport")
    private AuthenticationSystemSupport authenticationSystemSupport;

    @Autowired
    @Qualifier("ticketRegistry")
    private ObjectProvider<TicketRegistry> ticketRegistry;

    @Autowired
    @Qualifier("ticketGrantingTicketCookieGenerator")
    private ObjectProvider<CookieRetrievingCookieGenerator> ticketGrantingTicketCookieGenerator;

    @ConditionalOnMissingBean(name = "accessTokenResponseGenerator")
    @Bean
    public OAuth20AccessTokenResponseGenerator accessTokenResponseGenerator() {
        return new OAuth20DefaultAccessTokenResponseGenerator();
    }

    @ConditionalOnMissingBean(name = "oauthCasClientRedirectActionBuilder")
    @Bean
    public OAuth20CasClientRedirectActionBuilder oauthCasClientRedirectActionBuilder() {
        return new OAuth20DefaultCasClientRedirectActionBuilder();
    }

    @Bean
    public UrlResolver casCallbackUrlResolver() {
        return new OAuth20CasCallbackUrlResolver(OAuth20Utils.casOAuthCallbackUrl(casProperties.getServer().getPrefix()));
    }

    @Bean
    public Config oauthSecConfig() {
        val cfg = new CasConfiguration(casProperties.getServer().getLoginUrl());
        val oauthCasClient = new CasClient(cfg);
        oauthCasClient.setRedirectActionBuilder(webContext -> oauthCasClientRedirectActionBuilder().build(oauthCasClient, webContext));
        oauthCasClient.setName(Authenticators.CAS_OAUTH_CLIENT);
        oauthCasClient.setUrlResolver(casCallbackUrlResolver());

        val authenticator = oAuthClientAuthenticator();
        val basicAuthClient = new DirectBasicAuthClient(authenticator);
        basicAuthClient.setName(Authenticators.CAS_OAUTH_CLIENT_BASIC_AUTHN);

        val directFormClient = new DirectFormClient(authenticator);
        directFormClient.setName(Authenticators.CAS_OAUTH_CLIENT_DIRECT_FORM);
        directFormClient.setUsernameParameter(OAuth20Constants.CLIENT_ID);
        directFormClient.setPasswordParameter(OAuth20Constants.CLIENT_SECRET);

        val pkceAuthnClient = new DirectFormClient(oAuthProofKeyCodeExchangeAuthenticator());
        pkceAuthnClient.setName(Authenticators.CAS_OAUTH_CLIENT_PROOF_KEY_CODE_EXCHANGE_AUTHN);
        pkceAuthnClient.setUsernameParameter(OAuth20Constants.CLIENT_ID);
        pkceAuthnClient.setPasswordParameter(OAuth20Constants.CODE_VERIFIER);

        val userFormClient = new DirectFormClient(oAuthUserAuthenticator());
        userFormClient.setName(Authenticators.CAS_OAUTH_CLIENT_USER_FORM);

        val config = new Config(OAuth20Utils.casOAuthCallbackUrl(casProperties.getServer().getPrefix()),
            oauthCasClient, basicAuthClient, pkceAuthnClient, directFormClient, userFormClient);
        config.setSessionStore(new J2ESessionStore());
        return config;
    }

    @ConditionalOnMissingBean(name = "consentApprovalViewResolver")
    @Bean
    public ConsentApprovalViewResolver consentApprovalViewResolver() {
        return new OAuth20ConsentApprovalViewResolver(casProperties);
    }

    @ConditionalOnMissingBean(name = "callbackAuthorizeViewResolver")
    @Bean
    public OAuth20CallbackAuthorizeViewResolver callbackAuthorizeViewResolver() {
        return new OAuth20CallbackAuthorizeViewResolver() {
        };
    }

    @Bean
    public OAuth20CasClientRedirectActionBuilder defaultOAuthCasClientRedirectActionBuilder() {
        return new OAuth20DefaultCasClientRedirectActionBuilder();
    }

    @ConditionalOnMissingBean(name = "oAuthClientAuthenticator")
    @Bean
    public Authenticator<UsernamePasswordCredentials> oAuthClientAuthenticator() {
        return new OAuth20ClientIdClientSecretAuthenticator(this.servicesManager.getIfAvailable(), webApplicationServiceFactory, registeredServiceAccessStrategyEnforcer);
    }

    @ConditionalOnMissingBean(name = "oAuthProofKeyCodeExchangeAuthenticator")
    @Bean
    public Authenticator<UsernamePasswordCredentials> oAuthProofKeyCodeExchangeAuthenticator() {
        return new OAuth20ProofKeyCodeExchangeAuthenticator(this.servicesManager.getIfAvailable(), webApplicationServiceFactory,
            registeredServiceAccessStrategyEnforcer, ticketRegistry.getIfAvailable());
    }

    @ConditionalOnMissingBean(name = "oAuthUserAuthenticator")
    @Bean
    public Authenticator<UsernamePasswordCredentials> oAuthUserAuthenticator() {
        return new OAuth20UsernamePasswordAuthenticator(authenticationSystemSupport, servicesManager.getIfAvailable(), webApplicationServiceFactory);
    }

    @ConditionalOnMissingBean(name = "oauthAccessTokenResponseGenerator")
    @Bean
    public OAuth20AccessTokenResponseGenerator oauthAccessTokenResponseGenerator() {
        return new OAuth20DefaultAccessTokenResponseGenerator();
    }

    @Bean
    @RefreshScope
    @ConditionalOnMissingBean(name = "defaultAccessTokenFactory")
    public AccessTokenFactory defaultAccessTokenFactory() {
        return new DefaultAccessTokenFactory(accessTokenIdGenerator(), accessTokenExpirationPolicy());
    }

    @Bean
    @RefreshScope
    @ConditionalOnMissingBean(name = "defaultDeviceTokenFactory")
    public DeviceTokenFactory defaultDeviceTokenFactory() {
        return new DefaultDeviceTokenFactory(deviceTokenIdGenerator(), deviceTokenExpirationPolicy(),
            casProperties.getAuthn().getOauth().getDeviceToken().getUserCodeLength());
    }

    @Bean
    @ConditionalOnMissingBean(name = "accessTokenExpirationPolicy")
    public ExpirationPolicy accessTokenExpirationPolicy() {
        val oauth = casProperties.getAuthn().getOauth().getAccessToken();
        if (casProperties.getLogout().isRemoveDescendantTickets()) {
            return new OAuthAccessTokenExpirationPolicy(
                Beans.newDuration(oauth.getMaxTimeToLiveInSeconds()).getSeconds(),
                Beans.newDuration(oauth.getTimeToKillInSeconds()).getSeconds()
            );
        }
        return new OAuthAccessTokenExpirationPolicy.OAuthAccessTokenSovereignExpirationPolicy(
            Beans.newDuration(oauth.getMaxTimeToLiveInSeconds()).getSeconds(),
            Beans.newDuration(oauth.getTimeToKillInSeconds()).getSeconds()
        );
    }

    @Bean
    @ConditionalOnMissingBean(name = "deviceTokenExpirationPolicy")
    public ExpirationPolicy deviceTokenExpirationPolicy() {
        val oauth = casProperties.getAuthn().getOauth().getDeviceToken();
        return new HardTimeoutExpirationPolicy(Beans.newDuration(oauth.getMaxTimeToLiveInSeconds()).getSeconds());
    }

    private ExpirationPolicy oAuthCodeExpirationPolicy() {
        val oauth = casProperties.getAuthn().getOauth();
        return new OAuthCodeExpirationPolicy(oauth.getCode().getNumberOfUses(),
            oauth.getCode().getTimeToKillInSeconds());
    }

    @Bean
    @RefreshScope
    @ConditionalOnMissingBean(name = "oAuthCodeIdGenerator")
    public UniqueTicketIdGenerator oAuthCodeIdGenerator() {
        return new DefaultUniqueTicketIdGenerator();
    }

    @Bean
    @RefreshScope
    @ConditionalOnMissingBean(name = "refreshTokenIdGenerator")
    public UniqueTicketIdGenerator refreshTokenIdGenerator() {
        return new DefaultUniqueTicketIdGenerator();
    }

    @Bean
    @RefreshScope
    @ConditionalOnMissingBean(name = "defaultOAuthCodeFactory")
    public OAuthCodeFactory defaultOAuthCodeFactory() {
        return new DefaultOAuthCodeFactory(oAuthCodeIdGenerator(), oAuthCodeExpirationPolicy());
    }

    @ConditionalOnMissingBean(name = "profileScopeToAttributesFilter")
    @Bean
    public OAuth20ProfileScopeToAttributesFilter profileScopeToAttributesFilter() {
        return new DefaultOAuth20ProfileScopeToAttributesFilter();
    }

    @Bean
    @ConditionalOnMissingBean(name = "callbackAuthorizeController")
    @RefreshScope
    public OAuth20CallbackAuthorizeEndpointController callbackAuthorizeController() {
        return new OAuth20CallbackAuthorizeEndpointController(servicesManager.getIfAvailable(),
            ticketRegistry.getIfAvailable(),
            defaultAccessTokenFactory(),
            oauthPrincipalFactory(),
            webApplicationServiceFactory,
            oauthSecConfig(),
            callbackAuthorizeViewResolver(),
            profileScopeToAttributesFilter(),
            casProperties,
            ticketGrantingTicketCookieGenerator.getIfAvailable());
    }

    @ConditionalOnMissingBean(name = "oauthTokenGenerator")
    @Bean
    @RefreshScope
    public OAuth20TokenGenerator oauthTokenGenerator() {
        return new OAuth20DefaultTokenGenerator(defaultAccessTokenFactory(),
            defaultDeviceTokenFactory(),
            defaultRefreshTokenFactory(),
            ticketRegistry.getIfAvailable(),
            casProperties);
    }

    @Bean
    public Collection<AccessTokenGrantRequestExtractor> accessTokenGrantRequestExtractors() {
        final AccessTokenGrantRequestExtractor pkceExt =
            new AccessTokenProofKeyCodeExchangeAuthorizationCodeGrantRequestExtractor(this.servicesManager.getIfAvailable(), this.ticketRegistry.getIfAvailable(),
                centralAuthenticationService, casProperties.getAuthn().getOauth(),
                webApplicationServiceFactory);

        final AccessTokenGrantRequestExtractor authzCodeExt =
            new AccessTokenAuthorizationCodeGrantRequestExtractor(this.servicesManager.getIfAvailable(), this.ticketRegistry.getIfAvailable(),
                centralAuthenticationService, casProperties.getAuthn().getOauth(),
                webApplicationServiceFactory);

        final AccessTokenGrantRequestExtractor refreshTokenExt =
            new AccessTokenRefreshTokenGrantRequestExtractor(this.servicesManager.getIfAvailable(), this.ticketRegistry.getIfAvailable(),
                centralAuthenticationService, casProperties.getAuthn().getOauth(),
                webApplicationServiceFactory);

        val authenticationBuilder = oauthCasAuthenticationBuilder();
        final AccessTokenGrantRequestExtractor pswExt =
            new AccessTokenPasswordGrantRequestExtractor(this.servicesManager.getIfAvailable(), this.ticketRegistry.getIfAvailable(),
                authenticationBuilder, centralAuthenticationService,
                casProperties.getAuthn().getOauth(), registeredServiceAccessStrategyEnforcer);

        final AccessTokenGrantRequestExtractor credsExt =
            new AccessTokenClientCredentialsGrantRequestExtractor(this.servicesManager.getIfAvailable(), this.ticketRegistry.getIfAvailable(),
                authenticationBuilder, centralAuthenticationService,
                casProperties.getAuthn().getOauth(), registeredServiceAccessStrategyEnforcer);

        final AccessTokenGrantRequestExtractor deviceCodeExt =
            new AccessTokenDeviceCodeResponseRequestExtractor(this.servicesManager.getIfAvailable(), this.ticketRegistry.getIfAvailable(),
                centralAuthenticationService, casProperties.getAuthn().getOauth(),
                authenticationBuilder, registeredServiceAccessStrategyEnforcer);

        return CollectionUtils.wrapList(pkceExt, authzCodeExt, refreshTokenExt, deviceCodeExt, pswExt, credsExt);
    }

    @ConditionalOnMissingBean(name = "introspectionEndpointController")
    @Bean
    public OAuth20IntrospectionEndpointController introspectionEndpointController() {
        return new OAuth20IntrospectionEndpointController(
            servicesManager.getIfAvailable(),
            ticketRegistry.getIfAvailable(),
            defaultAccessTokenFactory(),
            oauthPrincipalFactory(),
            webApplicationServiceFactory,
            profileScopeToAttributesFilter(),
            casProperties,
            ticketGrantingTicketCookieGenerator.getIfAvailable(),
            centralAuthenticationService,
            registeredServiceAccessStrategyEnforcer);
    }

    @ConditionalOnMissingBean(name = "accessTokenController")
    @Bean
    public OAuth20AccessTokenEndpointController accessTokenController() {
        return new OAuth20AccessTokenEndpointController(
            servicesManager.getIfAvailable(),
            ticketRegistry.getIfAvailable(),
            defaultAccessTokenFactory(),
            oauthPrincipalFactory(),
            webApplicationServiceFactory,
            oauthTokenGenerator(),
            accessTokenResponseGenerator(),
            profileScopeToAttributesFilter(),
            casProperties,
            ticketGrantingTicketCookieGenerator.getIfAvailable(),
            accessTokenExpirationPolicy(),
            deviceTokenExpirationPolicy(),
            oauthTokenRequestValidators(),
            accessTokenGrantAuditableRequestExtractor()
        );
    }

    @ConditionalOnMissingBean(name = "accessTokenGrantAuditableRequestExtractor")
    @Bean
    public AuditableExecution accessTokenGrantAuditableRequestExtractor() {
        return new AccessTokenGrantAuditableRequestExtractor(accessTokenGrantRequestExtractors());
    }

    @ConditionalOnMissingBean(name = "deviceUserCodeApprovalEndpointController")
    @Bean
    public OAuth20DeviceUserCodeApprovalEndpointController deviceUserCodeApprovalEndpointController() {
        return new OAuth20DeviceUserCodeApprovalEndpointController(
            servicesManager.getIfAvailable(),
            ticketRegistry.getIfAvailable(),
            defaultAccessTokenFactory(),
            oauthPrincipalFactory(),
            webApplicationServiceFactory,
            profileScopeToAttributesFilter(),
            casProperties,
            ticketGrantingTicketCookieGenerator.getIfAvailable(),
            defaultDeviceTokenFactory()
        );
    }

    @ConditionalOnMissingBean(name = "oauthUserProfileViewRenderer")
    @Bean
    @RefreshScope
    public OAuth20UserProfileViewRenderer oauthUserProfileViewRenderer() {
        return new OAuth20DefaultUserProfileViewRenderer(casProperties.getAuthn().getOauth());
    }

    @ConditionalOnMissingBean(name = "oAuth2UserProfileDataCreator")
    @Bean
    public OAuth20UserProfileDataCreator oAuth2UserProfileDataCreator() {
        return new DefaultOAuth20UserProfileDataCreator(servicesManager.getIfAvailable(), profileScopeToAttributesFilter());
    }

    @ConditionalOnMissingBean(name = "profileController")
    @Bean
    public OAuth20UserProfileEndpointController profileController() {
        return new OAuth20UserProfileEndpointController(
            servicesManager.getIfAvailable(),
            ticketRegistry.getIfAvailable(),
            defaultAccessTokenFactory(),
            oauthPrincipalFactory(),
            webApplicationServiceFactory,
            profileScopeToAttributesFilter(),
            casProperties,
            ticketGrantingTicketCookieGenerator.getIfAvailable(),
            oauthUserProfileViewRenderer(),
            oAuth2UserProfileDataCreator());
    }

    @ConditionalOnMissingBean(name = "oauthAuthorizationResponseBuilders")
    @Bean
    @RefreshScope
    public Set<OAuth20AuthorizationResponseBuilder> oauthAuthorizationResponseBuilders() {
        val builders =
            this.applicationContext.getBeansOfType(OAuth20AuthorizationResponseBuilder.class, false, true);
        return new HashSet<>(builders.values());
    }

    @ConditionalOnMissingBean(name = "oauthAuthorizationRequestValidators")
    @Bean
    @RefreshScope
    public Set<OAuth20AuthorizationRequestValidator> oauthAuthorizationRequestValidators() {
        val validators = new LinkedHashSet<OAuth20AuthorizationRequestValidator>();
        validators.add(oauthProofKeyCodeExchangeResponseTypeAuthorizationRequestValidator());
        validators.add(oauthAuthorizationCodeResponseTypeRequestValidator());
        validators.add(oauthIdTokenResponseTypeRequestValidator());
        validators.add(oauthTokenResponseTypeRequestValidator());
        return validators;
    }

    @Bean
    @ConditionalOnMissingBean(name = "oauth20AuthorizationCodeGrantTypeProofKeyCodeExchangeTokenRequestValidator")
    public OAuth20TokenRequestValidator oauth20AuthorizationCodeGrantTypeProofKeyCodeExchangeTokenRequestValidator() {
        val registry = ticketRegistry.getIfAvailable();
        val svcManager = servicesManager.getIfAvailable();
        return new OAuth20AuthorizationCodeGrantTypeProofKeyCodeExchangeTokenRequestValidator(svcManager,
            registry, registeredServiceAccessStrategyEnforcer, webApplicationServiceFactory);
    }

    @Bean
    @ConditionalOnMissingBean(name = "oauthAuthorizationCodeGrantTypeTokenRequestValidator")
    public OAuth20TokenRequestValidator oauthAuthorizationCodeGrantTypeTokenRequestValidator() {
        val registry = ticketRegistry.getIfAvailable();
        val svcManager = servicesManager.getIfAvailable();
        return new OAuth20AuthorizationCodeGrantTypeTokenRequestValidator(svcManager,
            registry, registeredServiceAccessStrategyEnforcer, webApplicationServiceFactory);
    }

    @Bean
    @ConditionalOnMissingBean(name = "oauthDeviceCodeResponseTypeRequestValidator")
    public OAuth20TokenRequestValidator oauthDeviceCodeResponseTypeRequestValidator() {
        val registry = ticketRegistry.getIfAvailable();
        val svcManager = servicesManager.getIfAvailable();
        return new OAuth20DeviceCodeResponseTypeRequestValidator(svcManager, webApplicationServiceFactory);
    }

    @Bean
    @ConditionalOnMissingBean(name = "oauthRefreshTokenGrantTypeTokenRequestValidator")
    public OAuth20TokenRequestValidator oauthRefreshTokenGrantTypeTokenRequestValidator() {
        val registry = ticketRegistry.getIfAvailable();
        val svcManager = servicesManager.getIfAvailable();
        return new OAuth20RefreshTokenGrantTypeTokenRequestValidator(registeredServiceAccessStrategyEnforcer,
            svcManager, registry, webApplicationServiceFactory);
    }

    @Bean
    @ConditionalOnMissingBean(name = "oauthPasswordGrantTypeTokenRequestValidator")
    public OAuth20TokenRequestValidator oauthPasswordGrantTypeTokenRequestValidator() {
        val registry = ticketRegistry.getIfAvailable();
        val svcManager = servicesManager.getIfAvailable();
        return new OAuth20PasswordGrantTypeTokenRequestValidator(registeredServiceAccessStrategyEnforcer,
            svcManager, webApplicationServiceFactory);
    }

    @Bean
    @ConditionalOnMissingBean(name = "oauthClientCredentialsGrantTypeTokenRequestValidator")
    public OAuth20TokenRequestValidator oauthClientCredentialsGrantTypeTokenRequestValidator() {
        val registry = ticketRegistry.getIfAvailable();
        val svcManager = servicesManager.getIfAvailable();
        return new OAuth20ClientCredentialsGrantTypeTokenRequestValidator(svcManager,
            registeredServiceAccessStrategyEnforcer, webApplicationServiceFactory);
    }

    @ConditionalOnMissingBean(name = "oauthTokenRequestValidators")
    @Bean
    @RefreshScope
    public Collection<OAuth20TokenRequestValidator> oauthTokenRequestValidators() {
        val validators = new ArrayList<OAuth20TokenRequestValidator>();

        validators.add(oauth20AuthorizationCodeGrantTypeProofKeyCodeExchangeTokenRequestValidator());
        validators.add(oauthAuthorizationCodeGrantTypeTokenRequestValidator());
        validators.add(oauthDeviceCodeResponseTypeRequestValidator());
        validators.add(oauthRefreshTokenGrantTypeTokenRequestValidator());
        validators.add(oauthPasswordGrantTypeTokenRequestValidator());
        validators.add(oauthClientCredentialsGrantTypeTokenRequestValidator());

        return validators;
    }

    @ConditionalOnMissingBean(name = "oauthAuthorizationCodeResponseTypeRequestValidator")
    @Bean
    @RefreshScope
    public OAuth20AuthorizationRequestValidator oauthAuthorizationCodeResponseTypeRequestValidator() {
        return new OAuth20AuthorizationCodeResponseTypeAuthorizationRequestValidator(servicesManager.getIfAvailable(),
            webApplicationServiceFactory, registeredServiceAccessStrategyEnforcer);
    }

    @ConditionalOnMissingBean(name = "oauthProofKeyCodeExchangeResponseTypeAuthorizationRequestValidator")
    @Bean
    @RefreshScope
    public OAuth20AuthorizationRequestValidator oauthProofKeyCodeExchangeResponseTypeAuthorizationRequestValidator() {
        return new OAuth20ProofKeyCodeExchangeResponseTypeAuthorizationRequestValidator(servicesManager.getIfAvailable(),
            webApplicationServiceFactory, registeredServiceAccessStrategyEnforcer);
    }

    @ConditionalOnMissingBean(name = "oauthTokenResponseTypeRequestValidator")
    @Bean
    @RefreshScope
    public OAuth20AuthorizationRequestValidator oauthTokenResponseTypeRequestValidator() {
        return new OAuth20TokenResponseTypeAuthorizationRequestValidator(servicesManager.getIfAvailable(),
            webApplicationServiceFactory, registeredServiceAccessStrategyEnforcer);
    }

    @ConditionalOnMissingBean(name = "oauthIdTokenResponseTypeRequestValidator")
    @Bean
    @RefreshScope
    public OAuth20AuthorizationRequestValidator oauthIdTokenResponseTypeRequestValidator() {
        return new OAuth20IdTokenResponseTypeAuthorizationRequestValidator(servicesManager.getIfAvailable(),
            webApplicationServiceFactory, registeredServiceAccessStrategyEnforcer);
    }

    @ConditionalOnMissingBean(name = "oauthResourceOwnerCredentialsResponseBuilder")
    @Bean
    @RefreshScope
    public OAuth20AuthorizationResponseBuilder oauthResourceOwnerCredentialsResponseBuilder() {
        return new OAuth20ResourceOwnerCredentialsResponseBuilder(accessTokenResponseGenerator(), oauthTokenGenerator(),
            accessTokenExpirationPolicy(), casProperties);
    }

    @ConditionalOnMissingBean(name = "oauthClientCredentialsResponseBuilder")
    @Bean
    @RefreshScope
    public OAuth20AuthorizationResponseBuilder oauthClientCredentialsResponseBuilder() {
        return new OAuth20ClientCredentialsResponseBuilder(accessTokenResponseGenerator(),
            oauthTokenGenerator(), accessTokenExpirationPolicy(), casProperties);
    }

    @ConditionalOnMissingBean(name = "oauthTokenResponseBuilder")
    @Bean
    @RefreshScope
    public OAuth20AuthorizationResponseBuilder oauthTokenResponseBuilder() {
        return new OAuth20TokenAuthorizationResponseBuilder(oauthTokenGenerator(), accessTokenExpirationPolicy());
    }

    @ConditionalOnMissingBean(name = "oauthAuthorizationCodeResponseBuilder")
    @Bean
    @RefreshScope
    public OAuth20AuthorizationResponseBuilder oauthAuthorizationCodeResponseBuilder() {
        return new OAuth20AuthorizationCodeAuthorizationResponseBuilder(ticketRegistry.getIfAvailable(), defaultOAuthCodeFactory());
    }

    @ConditionalOnMissingBean(name = "authorizeController")
    @Bean
    @RefreshScope
    public OAuth20AuthorizeEndpointController authorizeController() {
        return new OAuth20AuthorizeEndpointController(
            servicesManager.getIfAvailable(),
            ticketRegistry.getIfAvailable(),
            defaultAccessTokenFactory(),
            oauthPrincipalFactory(),
            webApplicationServiceFactory,
            defaultOAuthCodeFactory(),
            consentApprovalViewResolver(),
            profileScopeToAttributesFilter(),
            casProperties,
            ticketGrantingTicketCookieGenerator.getIfAvailable(),
            oauthCasAuthenticationBuilder(),
            oauthAuthorizationResponseBuilders(),
            oauthAuthorizationRequestValidators(),
            registeredServiceAccessStrategyEnforcer
        );
    }

    @ConditionalOnMissingBean(name = "oauthPrincipalFactory")
    @Bean
    @RefreshScope
    public PrincipalFactory oauthPrincipalFactory() {
        return PrincipalFactoryUtils.newPrincipalFactory();
    }

    @Bean
    @RefreshScope
    @ConditionalOnMissingBean(name = "defaultRefreshTokenFactory")
    public RefreshTokenFactory defaultRefreshTokenFactory() {
        return new DefaultRefreshTokenFactory(refreshTokenIdGenerator(), refreshTokenExpirationPolicy());
    }

    private ExpirationPolicy refreshTokenExpirationPolicy() {
        val rtProps = casProperties.getAuthn().getOauth().getRefreshToken();
        val timeout = Beans.newDuration(rtProps.getTimeToKillInSeconds()).getSeconds();
        if (casProperties.getLogout().isRemoveDescendantTickets()) {
            return new OAuthRefreshTokenExpirationPolicy(timeout);
        }
        return new OAuthRefreshTokenExpirationPolicy.OAuthRefreshTokenSovereignExpirationPolicy(timeout);
    }

    @ConditionalOnMissingBean(name = "oauthCasAuthenticationBuilder")
    @Bean
    @RefreshScope
    public OAuth20CasAuthenticationBuilder oauthCasAuthenticationBuilder() {
        return new OAuth20CasAuthenticationBuilder(oauthPrincipalFactory(), webApplicationServiceFactory,
            profileScopeToAttributesFilter(), casProperties);
    }

    @ConditionalOnMissingBean(name = "accessTokenIdGenerator")
    @Bean
    @RefreshScope
    public UniqueTicketIdGenerator accessTokenIdGenerator() {
        return new DefaultUniqueTicketIdGenerator();
    }

    @ConditionalOnMissingBean(name = "deviceTokenIdGenerator")
    @Bean
    @RefreshScope
    public UniqueTicketIdGenerator deviceTokenIdGenerator() {
        return new DefaultUniqueTicketIdGenerator();
    }

    @Override
    public void configureAuditTrailRecordResolutionPlan(final AuditTrailRecordResolutionPlan plan) {
        plan.registerAuditActionResolver("OAUTH2_USER_PROFILE_DATA_ACTION_RESOLVER",
            new DefaultAuditActionResolver(AuditTrailConstants.AUDIT_ACTION_POSTFIX_CREATED, AuditTrailConstants.AUDIT_ACTION_POSTFIX_CREATED));
        plan.registerAuditResourceResolver("OAUTH2_USER_PROFILE_DATA_RESOURCE_RESOLVER",
            new OAuth20UserProfileDataAuditResourceResolver());

        plan.registerAuditActionResolver("OAUTH2_ACCESS_TOKEN_REQUEST_ACTION_RESOLVER",
            new DefaultAuditActionResolver(AuditTrailConstants.AUDIT_ACTION_POSTFIX_CREATED, AuditTrailConstants.AUDIT_ACTION_POSTFIX_CREATED));
        plan.registerAuditResourceResolver("OAUTH2_ACCESS_TOKEN_REQUEST_RESOURCE_RESOLVER",
            new AccessTokenGrantRequestAuditResourceResolver());

        plan.registerAuditActionResolver("OAUTH2_ACCESS_TOKEN_RESPONSE_ACTION_RESOLVER",
            new DefaultAuditActionResolver(AuditTrailConstants.AUDIT_ACTION_POSTFIX_CREATED, AuditTrailConstants.AUDIT_ACTION_POSTFIX_CREATED));
        plan.registerAuditResourceResolver("OAUTH2_ACCESS_TOKEN_RESPONSE_RESOURCE_RESOLVER",
            new AccessTokenResponseAuditResourceResolver());
    }

    @Bean
    public Service oauthCallbackService() {
        val oAuthCallbackUrl = casProperties.getServer().getPrefix()
            + OAuth20Constants.BASE_OAUTH20_URL + '/' + OAuth20Constants.CALLBACK_AUTHORIZE_URL_DEFINITION;
        return this.webApplicationServiceFactory.createService(oAuthCallbackUrl);
    }

    @Override
    public void configureServiceRegistry(final ServiceRegistryExecutionPlan plan) {
        val service = new RegexRegisteredService();
        service.setId(Math.abs(RandomUtils.getNativeInstance().nextLong()));
        service.setEvaluationOrder(0);
        service.setName(service.getClass().getSimpleName());
        service.setDescription("OAuth Authentication Callback Request URL");
        service.setServiceId(oauthCallbackService().getId());
        service.setAttributeReleasePolicy(new DenyAllAttributeReleasePolicy());
        plan.registerServiceRegistry(new OAuth20ServiceRegistry(service));
    }

    @Bean
    @ConditionalOnEnabledEndpoint
    public OAuth20TokenManagementEndpoint oAuth20TokenManagementEndpoint() {
        return new OAuth20TokenManagementEndpoint(ticketRegistry.getIfAvailable());
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace _2.WordEncounter
{
    class WordEncounter
    {
        public static void Main()
        {
            List<string> result = new List<string>();
            string filter = Console.ReadLine();
            char letter = filter[0];
            int counter = int.Parse(filter.Substring(1));
            string input = Console.ReadLine();

            while (input != "end")
            {
                string pattern1 = @"(^[A-Z]).*([!\.?]$)";
                Match sentence = Regex.Match(input, pattern1);
                string validSentence = sentence.Groups[0].Value;
                string pattern2 = @"\w+";
                MatchCollection words = Regex.Matches(validSentence, pattern2);
                foreach (Match word in words)
                {
                    if (checkWord(word.Value, letter, counter))
                    {
                        result.Add(word.Value);
                    }
                }
                input = Console.ReadLine();
            }
            Console.WriteLine(string.Join(", ", result));
        }

        static bool checkWord(string s, char filter, int countLetter)
        {
            int cnt = 0;
            for (int i = 0; i < s.Length; i++)
            {
                if (s[i] == filter)
                {
                    cnt++;
                }
            }
            if (cnt >= countLetter)
            {
                return true;
            }
            return false;
        }
    }
}


text:
"""
@file
@brief Various function to download data about population
"""
import gzip
import os
import numpy
import pandas
from pyquickhelper.loghelper import noLOG
from pyensae.datasource import download_data
from .data_exceptions import DataFormatException

def population_france_year(url="https://www.insee.fr/fr/statistiques/fichier/1892086/pop-totale-france.xls",
                           sheet_name=0, year=2020):
    """
    Downloads the data for the French population from INSEE website

    @param      url             url
    @param      sheet_name      sheet index
    @param      year            last year to find
    @return                     DataFrame

    The sheet index is 0 for the all France, 1 for metropolitean France.
    The last row aggregates multiple ages ``1914 ou avant``, they will remain
    aggregated but the label will be changed to 1914. ``100 ou plus`` is replaced by 100.

    By default, the data is coming from `INSEE, Bilan Démographique <https://www.insee.fr/fr/statistiques/1892086?sommaire=1912926>`_.

    **2017/01**: pandas does not seem to be able to read the format (old format).
    You should convert the file in txt with Excel.
    """
    try:
        df = pandas.read_excel(url, sheet_name=sheet_name)
        skiprows = 5
    except Exception as e:  # pragma: no cover
        # we try to find a local version
        this = os.path.dirname(__file__)
        name = os.path.join(this, "data_population", url.split(
            "/")[-1].replace(".xls", ".xlsx"))
        if not os.path.exists(name):
            raise FileNotFoundError(
                "Unable to find a replacement for '{0}' as '{1}'".format(url, name)) from e
        df = pandas.read_excel(name, sheet_name=sheet_name)
        url = name
        skiprows = 0
    col = df.columns[0]
    if len(col) == 0:
        raise DataFormatException(  # pragma: no cover
            "Unable to find {0} (year) in table at url '{1}'".format(year, url))
    if skiprows > 0 and str(year) not in col:
        raise DataFormatException(  # pragma: no cover
            "Unable to find {0} (year) in first column name '{1}' at url "
            "'{2}'".format(year, col, url))

    table = pandas.read_excel(url, sheet_name=sheet_name, skiprows=skiprows)
    table.columns = ["naissance", "age", "hommes", "femmes", "ensemble"]
    table = table[(table.naissance != 'Champ : France y c. Mayotte.') &
                  table.naissance.apply(lambda s: "Source" not in str(s))].copy()
    table["naissance"] = table.apply(lambda r: r["naissance"] if isinstance(r["naissance"], (int, float)) else
                                     r["naissance"].replace(" ou avant", ""), axis=1)
    table["age"] = table.apply(lambda r: r["age"] if isinstance(r["age"], (int, float)) else
                               r["age"].replace(" ou plus", "") if isinstance(
                                   r["age"], str) else r["age"],
                               axis=1)
    table = table.dropna(axis=0)
    for c in table.columns:
        table[c] = table[c].astype(int)
    return table

def table_mortalite_france_00_02(homme=None, femme=None):
    """
    Download mortality table for France assuming they
    are available in Excel format.

    @param      homme       table for men
    @param      femme       table for women
    @return                 DataFrame

    The final DataFrame merges both sheets.
    The data is coming from
    `Institut des Actuaires: Reférences de mortalité <http://www.institutdesactuaires.com/gene/main.php?base=2127>`_ or
    `Références techniques <http://www.ressources-actuarielles.net/EXT/ISFA/fp-isfa.nsf/
    34a14c286dfb0903c1256ffd00502d73/d62719e329025b94c12577c100545bb7?OpenDocument>`_.
    """
    this = os.path.join(os.path.abspath(
        os.path.dirname(__file__)), "data_population")
    if homme is None:
        homme = os.path.join(this, "TH00-02_D.xls")
        sheeth = "Table"
    else:
        sheeth = 0
    if femme is None:
        femme = os.path.join(this, "TF00-02_D.xls")
        sheetf = "Table"
    else:
        sheetf = 0
    isexch = os.path.splitext(homme)[-1] in (".xls", ".xlsx")
    dfh = pandas.read_excel(
        homme, sheet_name=sheeth) if isexch else pandas.read_csv(homme, sep=";")
    if dfh.shape[1] > 2:
        dfh = dfh[dfh.columns[:2]]
    isexcf = os.path.splitext(femme)[-1] in (".xls", ".xlsx")
    dff = pandas.read_excel(
        femme, sheet_name=sheetf) if isexcf else pandas.read_csv(femme, sep=";")
    if dff.shape[1] > 2:
        dff = dff[dff.columns[:2]]
    df = dfh.merge(dff, on="Age")
    df.columns = ["Age", "Homme", "Femme"]
    return df.dropna().reset_index(drop=True)

def fecondite_france(url=None):
    """
    download fecondity table for France (Excel format)

    @param      url     source (url or file)
    @return             DataFrame

    By default, the data is coming from a local file
    which is a copy of
    `INSEE: Fécondité selon l'âge détaillé de la mère <https://www.insee.fr/fr/statistiques/2045366?sommaire=2045470&q=fecondite>`_.
    The original file cannot be read by pandas so we convert it first.
    See also `INSEE Bilan Démographique 2016 <https://www.insee.fr/fr/statistiques/1892259?sommaire=1912926>`_.
    """
    if url is None:
        this = os.path.abspath(os.path.dirname(__file__))
        url = os.path.join(this, "data_population", "irsocsd2014_G10.xlsx")
    df = pandas.read_excel(url)
    col = df.columns[0]
    df[col] = df.apply(lambda r: r[col] if isinstance(r[col], int) else
                       r[col].replace(" ou plus", "").replace(" ans", "").replace(" (p)", "") if isinstance(
        r[col], str) else r[col],
        axis=1)
    df = df[df[col].apply(lambda x: "0" <= x[0] <= "9" if isinstance(
        x, str) else (isinstance(x, (int, float))))].copy()
    df[col] = df[col].astype(float)
    cp = df[df[col] == 15]
    if len(cp) == 0:
        ages = [str(_) for _ in set(df[col])]  # pragma: no cover
        raise DataFormatException(  # pragma: no cover
            "Unable to find 15 (age) in table at url: {0}\n{1}".format(
                url, "\n".join(ages)))
    if len(cp) != 1:
        raise DataFormatException(  # pragma: no cover
            "too many values 15 in table at url: " + url)
    cpe = df[df[col] == 50]
    if len(cpe) == 0:
        raise DataFormatException(  # pragma: no cover
            "Unable to find 50 (age) in table at url: " + url)
    if len(cpe) != 1:
        raise DataFormatException(  # pragma: no cover
            "Too many values 50 in table at url: " + url)
    ind = cp.index[0]
    ind2 = cpe.index[0]
    table = df.iloc[ind:ind2, :3].copy()
    table.columns = ["age", "2005", "2015"]
    for c in table.columns:
        table[c] = table[c].astype(float)
    return table

def table_mortalite_euro_stat(url="http://ec.europa.eu/eurostat/estat-navtree-portlet-prod/BulkDownloadListing?file=data/",
                              name="demo_mlifetable.tsv.gz", final_name="mortalite.txt",
                              whereTo=".", stop_at=None, fLOG=noLOG):
    """
    This function retrieves mortality table from `EuroStat <http://ec.europa.eu/eurostat/fr>`_ through
    `table de mortalité <http://www.data-publica.com/opendata/7098--population-et-conditions-sociales-table-de-mortalite-de-1960-a-2010>`_
    (*this link is currently broken, data-publica does not provide such a database anymore, a copy is provided*).

    @param      url         data source
    @param      name        data table name
    @param      final_name  the data is compressed, it needs to be uncompressed
                            into a file, this parameter defines its name
    @param      whereTo     data needs to be downloaded, location of this place
    @param      stop_at     the overall process is quite long, if not None,
                            it only keeps the first rows
    @param      fLOG        logging function
    @return                 data_frame

    The function checks the file final_name exists.
    If it is the case, the data is not downloaded twice.

    The header contains a weird format as coordinates are separated by a comma::

        indic_de,sex,age,geo\time	2013 	2012 	2011 	2010 	2009

    We need to preprocess the data to split this information into columns.
    The overall process takes 4-5 minutes, 10 seconds to download (< 10 Mb),
    4-5 minutes to preprocess the data (it could be improved). The processed data
    contains the following columns::

        ['annee', 'valeur', 'age', 'age_num', 'indicateur', 'genre', 'pays']

    Columns *age* and *age_num* look alike. *age_num* is numeric and is equal
    to *age* except when *age_num* is 85. Everybody above that age fall
    into the same category. The table contains many indicators:

    * PROBSURV: Probabilité de survie entre deux âges exacts (px)
    * LIFEXP: Esperance de vie à l'âge exact (ex)
    * SURVIVORS: Nombre des survivants à l'âge exact (lx)
    * PYLIVED: Nombre d'années personnes vécues entre deux âges exacts (Lx)
    * DEATHRATE: Taux de mortalité à l'âge x (Mx)
    * PROBDEATH: Probabilité de décès entre deux âges exacts (qx)
    * TOTPYLIVED: Nombre total d'années personne vécues après l'âge exact (Tx)
    """
    if os.path.exists(final_name) and os.stat(final_name).st_size > 1e7:
        return final_name

    temp = final_name + ".remove.txt"
    if not os.path.exists(temp) or os.stat(temp).st_size < 1e7:
        local = download_data(name, url=url, whereTo=whereTo)
        local = local[0] + ".gz"
        with gzip.open(local, 'rb') as f:
            file_content = f.read()
        content = str(file_content, encoding="utf8")
        with open(temp, "w", encoding="utf8") as f:
            f.write(content)

    def format_age(s):
        if s.startswith("Y_"):
            if s.startswith("Y_LT"):  # pragma: no cover
                return "YLT" + s[4:]
            if s.startswith("Y_GE"):  # pragma: no cover
                return "YGE" + s[4:]
            raise SyntaxError(s)  # pragma: no cover
        i = int(s.strip("Y"))
        return "Y%02d" % i

    def format_age_num(s):
        if s.startswith("Y_"):
            if s.startswith("Y_LT"):  # pragma: no cover
                return float(s.replace("Y_LT", ""))
            if s.startswith("Y_GE"):  # pragma: no cover
                return float(s.replace("Y_GE", ""))
            raise SyntaxError(s)  # pragma: no cover
        i = int(s.strip("Y"))
        return float(i)

    def format_value(s):
        if s.strip() == ":":
            return numpy.nan
        return float(s.strip(" ebp"))

    fLOG("step 0, reading")
    dff = pandas.read_csv(temp, sep="\t", encoding="utf8")

    if stop_at is not None:
        fLOG("step 0, shortening")
        dfsmall = dff.head(n=stop_at)
        df = dfsmall
    else:
        df = dff

    fLOG("step 1, size=", df.shape)
    dfi = df.reset_index().set_index("indic_de,sex,age,geo\\time")
    dfi = dfi.drop('index', axis=1)
    dfs = dfi.stack()
    dfs = pandas.DataFrame({"valeur": dfs})

    fLOG("step 2, size=", dfs.shape)
    dfs["valeur"] = dfs["valeur"].astype(str)
    dfs["valeur"] = dfs["valeur"].apply(format_value)
    dfs = dfs[dfs.valeur >= 0].copy()
    dfs = dfs.reset_index()
    dfs.columns = ["index", "annee", "valeur"]

    fLOG("step 3, size=", dfs.shape)
    dfs["age"] = dfs["index"].apply(lambda i: format_age(i.split(",")[2]))
    dfs["age_num"] = dfs["index"].apply(
        lambda i: format_age_num(i.split(",")[2]))
    dfs["indicateur"] = dfs["index"].apply(lambda i: i.split(",")[0])
    dfs["genre"] = dfs["index"].apply(lambda i: i.split(",")[1])
    dfs["pays"] = dfs["index"].apply(lambda i: i.split(",")[3])

    fLOG("step 4")
    dfy = dfs.drop('index', axis=1)
    dfy.to_csv(final_name, sep="\t", encoding="utf8", index=False)
    return final_name


text:
package com.jsonstore.exceptions;

/**
 * Thrown if the count operation has failed.
 */
public class JSONStoreChangePasswordException extends JSONStoreException {

	private static final long serialVersionUID = 6571741871017455283L;

	public JSONStoreChangePasswordException(Throwable source) {
		super(source);
	}

}


text:
namespace singleFileMinimalExample {

namespace unit {

template <typename Unit, typename MagnitudeRepresentation = double>
class Quantity {
    template <typename, typename>
    friend class Quantity;

   public:
    using unit = Unit;
    using magnitude_type = MagnitudeRepresentation;
    using classtype = Quantity<unit, magnitude_type>;

    constexpr explicit Quantity() : m_magnitude(0) {}
    constexpr explicit Quantity(magnitude_type const& v) : m_magnitude(v) {}

    constexpr Quantity(classtype const& v) = default;

    template <typename R>
    constexpr Quantity(Quantity<unit, R> const& v) : m_magnitude(v.m_magnitude) {}

    classtype& operator=(classtype const& v) = default;

    constexpr magnitude_type const& magnitude() const { return m_magnitude; }

   private:
    template <typename U, typename L, typename R>
    friend constexpr Quantity<U, L>& operator+=(Quantity<U, L>&, Quantity<U, R> const&);

    template <typename U, typename L, typename R>
    friend constexpr Quantity<U, L>& operator-=(Quantity<U, L>&, Quantity<U, R> const&);

    template <typename U, typename L, typename R>
    friend constexpr Quantity<U, L>& operator*=(Quantity<U, L>&, Quantity<U, R> const&);

    template <typename U, typename L, typename R>
    friend constexpr Quantity<U, L>& operator/=(Quantity<U, L>&, Quantity<U, R> const&);

    magnitude_type m_magnitude;
};

using TExponent = int;
using ExponentIndex = int;
using DimensionIndex = int;

template <TExponent... dimensionExponents>
struct Unit;

namespace helper {

template <typename Unit, ExponentIndex i>
constexpr TExponent exponent() {
    return Unit::template exponent_value<i>();
}

namespace nthElement {

using Index = unsigned int;

template <Index n, TExponent Arg, TExponent... Args>
struct NthElement {
    static constexpr int value() { return NthElement<n - 1, Args...>::value(); }
};

template <TExponent Arg, TExponent... Args>
struct NthElement<0, Arg, Args...> {
    static constexpr int value() { return Arg; }
};
}

namespace baseunit {

template <DimensionIndex it, DimensionIndex index, TExponent... exponents>
struct BaseUnitGen {
    using type = typename BaseUnitGen<it - 1, index, it == index ? 1 : 0, exponents...>::type;
};

template <DimensionIndex index, TExponent... exponents>
struct BaseUnitGen<-1, index, exponents...> {
    using type = Unit<exponents...>;
};
}
}

template <int dimension, int lastDimension>
using BaseUnit = typename helper::baseunit::BaseUnitGen<lastDimension, dimension>::type;

template<TExponent ... dimensionExponents >
struct Unit{

    using classtype = Unit<dimensionExponents...>;

    static constexpr unsigned exponent_count() {return sizeof...(dimensionExponents);}

    template<ExponentIndex i>
    static constexpr TExponent exponent_value() { return helper::nthElement::NthElement<i,dimensionExponents...>::value(); }
};

namespace helper {

namespace op {

template <typename U1, typename U2, int index>
struct sum {
    static constexpr int value() { return U1::template exponent_value<index>() + U2::template exponent_value<index>(); }
};

template <typename U1, typename U2, int index>
struct difference {
    static constexpr int value() { return U1::template exponent_value<index>() - U2::template exponent_value<index>(); }
};

template <typename U1, typename fract, int index>
struct multiply {
    static_assert(helper::exponent<U1, index>() * fract::num % fract::den == 0,
                  "rasing a unit to a fractional-power is not allowed");
    static constexpr int value() { return helper::exponent<U1, index>() * fract::num / fract::den; }
};

template <ExponentIndex it, typename U1, typename U2, template <class, class, int> class Op, TExponent... exponents>
struct UnitOperator {
    using type = typename UnitOperator<it - 1, U1, U2, Op, Op<U1, U2, it>::value(), exponents...>::type;
};

template <typename U1, typename U2, template <class, class, int> class Op, TExponent... exponents>
struct UnitOperator<-1, U1, U2, Op, exponents...> {
    using type = Unit<exponents...>;
};
}
}

template <typename U1, typename U2>
using product_unit = typename helper::op::UnitOperator<U1::exponent_count() - 1, U1, U2, helper::op::sum>::type;

template <typename U1, typename U2>
using quotient_unit = typename helper::op::UnitOperator<U1::exponent_count() - 1, U1, U2, helper::op::difference>::type;

template <typename U1, typename fract>
using raised_unit = typename helper::op::UnitOperator<U1::exponent_count() - 1, U1, fract, helper::op::multiply>::type;

template <typename U>
using sqare_unit = product_unit<U, U>;

template <typename TDst, typename QSrc>
constexpr Quantity<typename QSrc::unit, TDst> static_unit_cast(QSrc const& l) {
    return Quantity<typename QSrc::unit, TDst>{static_cast<TDst>(l.magnitude())};
}

template <typename U, typename LT, typename RT>
constexpr Quantity<U, LT>& operator+=(Quantity<U, LT>& l, Quantity<U, RT> const& r) {
    return l.m_magnitude += r.m_magnitude, l;
}

template <typename U, typename LT, typename RT>
constexpr Quantity<U, LT>& operator-=(Quantity<U, LT>& l, Quantity<U, RT> const& r) {
    return l.m_magnitude -= r.m_magnitude, l;
}

template <typename U, typename LT, typename RT>
constexpr Quantity<U, LT>& operator*=(Quantity<U, LT>& l, Quantity<U, RT> const& r) {
    return l.m_magnitude *= r.m_magnitude, l;
}

template <typename U, typename LT, typename RT>
constexpr Quantity<U, LT>& operator/=(Quantity<U, LT>& l, Quantity<U, RT> const& r) {
    return l.m_magnitude /= r.m_magnitude, l;
}

template <typename LU, typename LT, typename RU, typename RT>
constexpr auto operator*(Quantity<LU, LT> const& l, Quantity<RU, RT> const& r)
    -> Quantity<product_unit<LU, RU>, decltype(l.magnitude() * r.magnitude())> {
    return Quantity<product_unit<LU, RU>, decltype(l.magnitude() * r.magnitude())>{l.magnitude() * r.magnitude()};
}

template <typename LU, typename LT, typename RU, typename RT>
constexpr auto operator/(Quantity<LU, LT> const& l, Quantity<RU, RT> const& r)
    -> Quantity<quotient_unit<LU, RU>, decltype(l.magnitude() / r.magnitude())> {
    return Quantity<quotient_unit<LU, RU>, decltype(l.magnitude() / r.magnitude())>{l.magnitude() / r.magnitude()};
}

template <typename U, typename LT, typename RT>
constexpr auto operator+(Quantity<U, LT> const& l, Quantity<U, RT> const& r)
    -> Quantity<U, decltype(l.magnitude() + r.magnitude())> {
    return Quantity<U, decltype(l.magnitude() + r.magnitude())>{l.magnitude() + r.magnitude()};
}

template <typename U, typename LT, typename RT>
constexpr auto operator-(Quantity<U, LT> const& l, Quantity<U, RT> const& r)
    -> Quantity<U, decltype(l.magnitude() - r.magnitude())> {
    return Quantity<U, decltype(l.magnitude() - r.magnitude())>{l.magnitude() - r.magnitude()};
}

template <typename U, typename LT, typename RT>
constexpr bool operator<(Quantity<U, LT> const& l, Quantity<U, RT> const& r) {
    return l.magnitude() < r.magnitude();
}

template <typename U, typename LT, typename RT>
constexpr bool operator<=(Quantity<U, LT> const& l, Quantity<U, RT> const& r) {
    return l.magnitude() <= r.magnitude();
}

template <typename U, typename LT, typename RT>
constexpr bool operator>(Quantity<U, LT> const& l, Quantity<U, RT> const& r) {
    return l.magnitude() > r.magnitude();
}

template <typename U, typename LT, typename RT>
constexpr bool operator>=(Quantity<U, LT> const& l, Quantity<U, RT> const& r) {
    return l.magnitude() >= r.magnitude();
}

template <typename U, typename LT, typename RT>
constexpr bool operator==(Quantity<U, LT> const& l, Quantity<U, RT> const& r) {
    return l.magnitude() == r.magnitude();
}

template <typename U, typename LT, typename RT>
constexpr bool operator!=(Quantity<U, LT> const& l, Quantity<U, RT> const& r) {
    return l.magnitude() != r.magnitude();
}

template <typename LU, typename LT>
constexpr Quantity<LU, LT> operator-(Quantity<LU, LT> const& l) {
    return Quantity<LU, LT>{-l.magnitude()};
}

template <typename U, typename T>
constexpr auto
abs(Quantity<U, T> const& q)
        -> Quantity<U, decltype(abs(q.magnitude()))>
{
    using std::abs;
    return Quantity<U, decltype(abs(q.magnitude()))>{
                                abs(q.magnitude())};
}

template <typename U, typename T>
constexpr auto
sqrt(Quantity<U, T> const& q)
        -> Quantity<raised_unit<U, std::ratio<1, 2>>, decltype(sqrt(q.magnitude()))>
{
    using std::sqrt;
    return Quantity<raised_unit<U, std::ratio<1, 2>>, decltype(sqrt(q.magnitude()))>{
                                                               sqrt(q.magnitude())};
}

namespace helper {

template <typename power, typename T>
constexpr auto
pow_impl(T const& v)
 -> decltype(pow(v, static_cast<double>(power::num) / static_cast<double>(power::den)))

{
    using std::pow;
    return pow(v, static_cast<double>(power::num) / static_cast<double>(power::den));
}

}

template <typename power, typename U, typename T>
constexpr auto
pow(Quantity<U, T> const& q)
        -> Quantity<raised_unit<U, power>, decltype(helper::pow_impl<power, T>(q.magnitude()))>
{
    return Quantity<raised_unit<U, power>, decltype(helper::pow_impl<power, T>(q.magnitude()))>{
                                                    helper::pow_impl<power, T>(q.magnitude())};
}

template <typename U, typename T>
constexpr auto
cube(Quantity<U, T> const& q)
        -> Quantity<product_unit<product_unit<U, U>, U>, decltype((q.magnitude() * q.magnitude()) * q.magnitude())>
{
    return Quantity<product_unit<product_unit<U, U>, U>, decltype((q.magnitude() * q.magnitude()) * q.magnitude())>{
                                                                  (q.magnitude() * q.magnitude()) * q.magnitude()};
}

template <typename U, typename T>
constexpr auto
square(Quantity<U, T> const& q)
        -> Quantity<product_unit<U, U>, decltype(q.magnitude() * q.magnitude())>
{
    return Quantity<product_unit<U, U>, decltype(q.magnitude() * q.magnitude())>{
                                                 q.magnitude() * q.magnitude()};
}

namespace helper {

template <typename ratioIn, typename ratioOut, typename T>
constexpr T rescale(T const& v) {
    using r = std::ratio_divide<ratioIn, ratioOut>;
    return v * T{r::num} / T{r::den};
}

template <typename ratioIn, typename T>
constexpr T rescaleTo1(T const& v) {
    return rescale<ratioIn, std::ratio<1>, T>(v);
}
}

template<typename T> constexpr T femto(T const& v) { return helper::rescaleTo1<std::femto>(v); }
template<typename T> constexpr T pico(T const& v) { return helper::rescaleTo1<std::pico>(v); }
template<typename T> constexpr T nano(T const& v) { return helper::rescaleTo1<std::nano>(v); }
template<typename T> constexpr T micro(T const& v) { return helper::rescaleTo1<std::micro>(v); }
template<typename T> constexpr T milli(T const& v) { return helper::rescaleTo1<std::milli>(v); }
template<typename T> constexpr T centi(T const& v) { return helper::rescaleTo1<std::centi>(v); }
template<typename T> constexpr T deci(T const& v) { return helper::rescaleTo1<std::deci>(v); }
template<typename T> constexpr T deca(T const& v) { return helper::rescaleTo1<std::deca>(v); }
template<typename T> constexpr T hecto(T const& v) { return helper::rescaleTo1<std::hecto>(v); }
template<typename T> constexpr T kilo(T const& v) { return helper::rescaleTo1<std::kilo>(v); }
template<typename T> constexpr T mega(T const& v) { return helper::rescaleTo1<std::mega>(v); }
template<typename T> constexpr T giga(T const& v) { return helper::rescaleTo1<std::giga>(v); }
template<typename T> constexpr T tera(T const& v) { return helper::rescaleTo1<std::tera>(v); }
template<typename T> constexpr T peta(T const& v) { return helper::rescaleTo1<std::peta>(v); }

namespace u {

using unitless = BaseUnit<-1, 0>;
using foo = BaseUnit<0, 0>;

using foo_inv = quotient_unit<unitless, foo>;
}

namespace t {

using unitless = Quantity<u::unitless>;
using foo = Quantity<u::foo>;

using foo_inv = Quantity<u::foo_inv>;
}

constexpr t::unitless number{1};
constexpr t::foo foo{1};
constexpr t::foo_inv foo_inv{1};

namespace literals {

constexpr t::unitless operator"" _n ( long double v ) {return t::unitless {static_cast<double>(v)};}
constexpr t::foo operator"" _foo ( long double v ) {return t::foo {static_cast<double>(v)};}

}
}

}


text:
package com.peligro.pda.peligro;

import android.app.ActionBar;
import android.app.Activity;
//import android.app.PendingIntent;
import android.content.Intent;
import android.net.Uri;
//import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
//import android.view.Menu;
//import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;

public class MainActivity extends Activity {

    LinearLayout police, fire, ambulance, emergency;
    CommentsDataSource datasource;
    Button alert, exit, reset;
    ActionBar ab;

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

        datasource = new CommentsDataSource(this);
        datasource.open();
        datasource.getData();

        police=(LinearLayout)findViewById(R.id.policeLayout);
        ambulance=(LinearLayout)findViewById(R.id.ambulanceLayout);
        fire=(LinearLayout)findViewById(R.id.fireLayout);
        emergency=(LinearLayout)findViewById(R.id.emergencyLayout);
        alert=(Button)findViewById(R.id.alert);
        exit=(Button)findViewById(R.id.exit);
        reset=(Button)findViewById(R.id.reset);

        police.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent callIntent = new Intent(Intent.ACTION_CALL);
                callIntent.setData(Uri.parse("tel:9701326535"));
                startActivity(callIntent);
            }
        });

        fire.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent callIntent = new Intent(Intent.ACTION_CALL);
                callIntent.setData(Uri.parse("tel:9701326535"));
                startActivity(callIntent);
            }
        });

        ambulance.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent callIntent = new Intent(Intent.ACTION_CALL);
                callIntent.setData(Uri.parse("tel:9701326535"));
                startActivity(callIntent);
            }
        });

        emergency.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent callIntent = new Intent(Intent.ACTION_CALL);
                callIntent.setData(Uri.parse("tel:9701326535"));
                startActivity(callIntent);
            }
        });

        alert.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String request=ConnectionUtility.url+"AlertClass?phone="+userData.phone;
                try {
                    String response = ConnectionUtility.getResponse(request);
                    if (response.equals("success")) {
                        Toast.makeText(MainActivity.this, "Alert sent succesfully", Toast.LENGTH_LONG).show();
                    } else {
                        Toast.makeText(MainActivity.this, "Alert Failed", Toast.LENGTH_LONG).show();
                    }
                }catch (NullPointerException e){
                    e.printStackTrace();
                    Toast.makeText(MainActivity.this, "Connectivity error", Toast.LENGTH_LONG).show();

                }
            }
        });

        exit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(MainActivity.this, userData.phone, Toast.LENGTH_LONG).show();
                finish();
            }
        });

        reset.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String request = ConnectionUtility.url + "logout?phone=" + userData.phone;
                try {
                    String response = ConnectionUtility.getResponse(request);
                    if (response.equals("success")) {
                        Toast.makeText(MainActivity.this, "logout successful", Toast.LENGTH_LONG).show();
                        datasource.clearTable();
                        Toast.makeText(MainActivity.this, "phone table cleared", Toast.LENGTH_LONG).show();
                    } else {
                        Toast.makeText(MainActivity.this, "logout Failed", Toast.LENGTH_LONG).show();
                    }
                } catch (NullPointerException e) {
                    e.printStackTrace();
                    Toast.makeText(MainActivity.this, "Connectivity error", Toast.LENGTH_LONG).show();

                }
            }

        });
    }

}


text:
module.exports = function(crowi, app) {
  'use strict';

  var debug = require('debug')('crowi:routs:attachment')
    , Attachment = crowi.model('Attachment')
    , User = crowi.model('User')
    , Page = crowi.model('Page')
    , Promise = require('bluebird')
    , config = crowi.getConfig()
    , fs = require('fs')
    , fileUploader = require('../util/fileUploader')(crowi, app)
    , actions = {}
    , api = {};

  actions.api = api;

  api.list = function(req, res){
    var id = req.params.pageId;

    Attachment.getListByPageId(id)
    .then(function(attachments) {
      res.json({
        status: true,
        data: {
          attachments: attachments
        }
      });
    });
  };

  /**
   *
   */
  api.add = function(req, res){
    var id = req.params.pageId,
      path = decodeURIComponent(req.body.path),
      pageCreated = false,
      page = {};

    debug('id and path are: ', id, path);

    var tmpFile = req.files.file || null;
    debug('Uploaded tmpFile: ', tmpFile);
    if (!tmpFile) {
      return res.json({
        status: false,
        message: 'File error.'
      });
    }

    new Promise(function(resolve, reject) {
      if (id == 0) {
        debug('Create page before file upload');
        Page.create(path, '# '  + path, req.user, {grant: Page.GRANT_OWNER})
          .then(function(page) {
            pageCreated = true;
            resolve(page);
          })
          .catch(reject);
      } else {
        Page.findPageById(id).then(resolve).catch(reject);
      }
    }).then(function(pageData) {
      page = pageData;
      id = pageData._id;

      var tmpPath = tmpFile.path,
        originalName = tmpFile.originalname,
        fileName = tmpFile.name,
        fileType = tmpFile.mimetype,
        fileSize = tmpFile.size,
        filePath = Attachment.createAttachmentFilePath(id, fileName, fileType),
        tmpFileStream = fs.createReadStream(tmpPath, {flags: 'r', encoding: null, fd: null, mode: '0666', autoClose: true });

      return fileUploader.uploadFile(filePath, fileType, tmpFileStream, {})
        .then(function(data) {
          debug('Uploaded data is: ', data);

          // TODO size
          return Attachment.create(id, req.user, filePath, originalName, fileName, fileType, fileSize);
        }).then(function(data) {
          var imageUrl = fileUploader.generateUrl(data.filePath);
          return res.json({
            status: true,
            filename: imageUrl,
            attachment: data,
            page: page,
            pageCreated: pageCreated,
            message: 'Successfully uploaded.',
          });
        }).catch(function (err) {
          debug('Error on saving attachment data', err);
          // @TODO
          // Remove from S3
          return res.json({
            status: false,
            message: 'Error while uploading.',
          });
        }).finally(function() {
          fs.unlink(tmpPath, function (err) {
            if (err) {
              debug('Error while deleting tmp file.');
            }
          });
        })
      ;
    });
  };

  api.remove = function(req, res){
    var id = req.params.id;
  };

  return actions;
};


text:
package org.apache.camel.component.aws.s3;

import java.io.File;

import com.amazonaws.services.s3.model.PutObjectRequest;

import org.apache.camel.BindToRegistry;
import org.apache.camel.EndpointInject;
import org.apache.camel.Exchange;
import org.apache.camel.ExchangePattern;
import org.apache.camel.Message;
import org.apache.camel.Processor;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.test.junit4.CamelTestSupport;
import org.junit.Test;

public class S3ComponentStringTest extends CamelTestSupport {

    @BindToRegistry("amazonS3Client")
    AmazonS3ClientMock client = new AmazonS3ClientMock();

    @EndpointInject("direct:sendString")
    ProducerTemplate templateSendString;

    @EndpointInject("mock:result")
    MockEndpoint result;

    File testFile;

    String getCamelBucket() {
        return "mycamelbucket";
    }

    @Test
    public void sendString() throws Exception {
        result.expectedMessageCount(1);

        Exchange exchange = templateSendString.send("direct:sendString", ExchangePattern.InOnly, new Processor() {
            public void process(Exchange exchange) throws Exception {
                exchange.getIn().setHeader(S3Constants.KEY, "CamelUnitTest");
                exchange.getIn().setBody("Peppe");
            }
        });

        assertMockEndpointsSatisfied();

        assertResultExchange(result.getExchanges().get(0), true);

        PutObjectRequest putObjectRequest = client.putObjectRequests.get(0);
        assertEquals(getCamelBucket(), putObjectRequest.getBucketName());

        assertResponseMessage(exchange.getIn());
    }

    void assertResultExchange(Exchange resultExchange, boolean delete) {
        assertIsInstanceOf(String.class, resultExchange.getIn().getBody());
    }

    void assertResponseMessage(Message message) {
        assertEquals("3a5c8b1ad448bca04584ecb55b836264", message.getHeader(S3Constants.E_TAG));
        assertNull(message.getHeader(S3Constants.VERSION_ID));
    }

    @Override
    protected RouteBuilder createRouteBuilder() throws Exception {
        return new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                String awsEndpoint = "aws-s3://" + getCamelBucket() + "?amazonS3Client=#amazonS3Client";

                from("direct:sendString").to(awsEndpoint + "&deleteAfterWrite=false").to("mock:result");
            }
        };
    }
}


text:
from __future__ import absolute_import
from pychron.core.ui import set_toolkit
set_toolkit('qt4')

from pychron.processing.analyses.view.peak_center_view import PeakCenterView
import unittest

from test.database import isotope_manager_factory

class MyTestCase(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        cls.isotope_man = isotope_manager_factory(name='pychrondata_dev')
        cls.isotope_man.db.connect()
        man = cls.isotope_man
        db = man.db
        with db.session_ctx():
            ans, tc = db.get_sample_analyses(['MB06-674', ], ['Minna Bluff'])

            an = man.make_analysis(ans[4])
            cls._id=ans[4].id
            cls.analysis_no_pc = an
            # print ans[4].id
    def test_load_peakcenter(self):
        pc=PeakCenterView()
        ret=pc.load(self.analysis_no_pc)
        self.assertTrue(ret)

if __name__ == '__main__':
    unittest.main()


text:
var markdox = require('markdox');

markdox.process('./../src/lks/bmputils/BmpOutputOptions.as', './_output.md', function(){
  console.log('"docgen/_output.md" created.');
});


text:
title: Irrational Numbers
localeTitle: Números irracionais
---
## Números irracionais

Um número irracional é um número que não pode ser escrito totalmente na forma decimal. Um exemplo popular é o número _Pi_ , já que não pode ser totalmente escrito. Há um número infinito de decimais e, portanto, é irracional. O mesmo vale para o número _e_ e a raiz quadrada de 2. eles não podem ser escritos, pois têm um número infinito de decimais e, portanto, são irracionais.