text:
require 'spec_helper'

describe Category, :type => :model do
  before(:each) do
    @category = FactoryGirl.build(:category)
  end

  it { is_expected.to validate_presence_of(:name) }
  it { is_expected.to validate_uniqueness_of(:name) }

  it { is_expected.to have_many(:equipment_models) }

  # validate numericality for :max_renewal_length, :max_renewal_times, :renewal_days_before_due, :max_per_user, :sort_order, :max_checkout_length
  # this includes integer_only, and greater_than_or_equal_to => 0

  # :max_renewal_length
  it "validates max_renewal_length must be non-negative" do
    @category.max_renewal_length = -1
    expect(@category.save).to be_falsey
    @category.max_renewal_length = 0
    expect(@category.save).to be_truthy
  end
  it "validates max_renewal_length can be nil" do
    @category.max_renewal_length = nil
    expect(@category.save).to be_truthy
  end
  it "validates max_renewal_length must be an integer" do
    @category.max_renewal_length = "not_an_integer"
    expect(@category.save).to be_falsey
    @category.max_renewal_length = 1
    expect(@category.save).to be_truthy
  end

  # :max_renewal_times
  it "validates max_renewal_times must be non-negative" do
    @category.max_renewal_times = -1
    expect(@category.save).to be_falsey
    @category.max_renewal_times = 0
    expect(@category.save).to be_truthy
  end
  it "validates max_renewal_times can be nil" do
    @category.max_renewal_times = nil
    expect(@category.save).to be_truthy
  end
  it "validates max_renewal_times must be an integer" do
    @category.max_renewal_times = "not_an_integer"
    expect(@category.save).to be_falsey
    @category.max_renewal_times = 1
    expect(@category.save).to be_truthy
  end

  # :renewal_days_before_due
  it "validates renewal_days_before_due must be non-negative" do
    @category.renewal_days_before_due = -1
    expect(@category.save).to be_falsey
    @category.renewal_days_before_due = 0
    expect(@category.save).to be_truthy
  end
  it "validates renewal_days_before_due can be nil" do
    @category.renewal_days_before_due = nil
    expect(@category.save).to be_truthy
  end
  it "validates renewal_days_before_due must be an integer" do
    @category.renewal_days_before_due = "not_an_integer"
    expect(@category.save).to be_falsey
    @category.renewal_days_before_due = 1
    expect(@category.save).to be_truthy
  end

  # :sort_order
  it "validates sort_order must be non-negative" do
    @category.sort_order = -1
    expect(@category.save).to be_falsey
    @category.sort_order = 0
    expect(@category.save).to be_truthy
  end
  it "validates sort_order can be nil" do
    @category.sort_order = nil
    expect(@category.save).to be_truthy
  end
  it "validates sort_order must be an integer" do
    @category.sort_order = "not_an_integer"
    expect(@category.save).to be_falsey
    @category.sort_order = 1
    expect(@category.save).to be_truthy
  end

  # :max_per_user
  it "validates max_per_user must be non-negative" do
    @category.max_per_user = -1
    expect(@category.save).to be_falsey
    @category.max_per_user = 0
    expect(@category.save).to be_truthy
  end
  it "validates max_per_user can be nil" do
    @category.max_per_user = nil
    expect(@category.save).to be_truthy
  end
  it "validates max_per_user must be an integer" do
    @category.max_per_user = "not_an_integer"
    expect(@category.save).to be_falsey
    @category.max_per_user = 1
    expect(@category.save).to be_truthy
  end

  # :max_checkout_length
  it "validates max_checkout_length must be non-negative" do
    @category.max_checkout_length = -1
    expect(@category.save).to be_falsey
    @category.max_checkout_length = 0
    expect(@category.save).to be_truthy
  end
  it "validates max_checkout_length can be nil" do
    @category.max_checkout_length = nil
    expect(@category.save).to be_truthy
  end
  it "validates max_checkout_length must be an integer" do
    @category.max_checkout_length = "not_an_integer"
    expect(@category.save).to be_falsey
    @category.max_checkout_length = 1
    expect(@category.save).to be_truthy
  end

  # custom scope to return active categories
  describe ".active" do
    before(:each) do
      @deactivated = FactoryGirl.create(:category, deleted_at: "2013-01-01 00:00:00" )
      @category.save
    end

    it "Should return all active categories" do
      expect(Category.active).to include(@category)
    end

    it "Should not return inactive categories" do
      expect(Category.active).not_to include(@deactivated)
    end
  end

  describe "#maximum_per_user" do
    before(:each) do
      @category.max_per_user = 1
      @category.save
      @unrestrected_category = FactoryGirl.create(:category, max_per_user: nil)
    end
    it "Should return maximum_per_user if defined" do
      expect(@category.maximum_per_user).to eq(1)
    end
    it "Should return Float::INFINITY if not defined" do
      expect(@unrestrected_category.maximum_per_user).to eq(Float::INFINITY)
    end
  end

  describe "#maximum_renewal_length" do
    before(:each) do
      @category.max_renewal_length = 5
      @category.save
      @unrestrected_category = FactoryGirl.create(:category, max_renewal_length: nil)
    end
    it "Should return maximum_renewal_length if defined" do
      expect(@category.maximum_renewal_length).to eq(5)
    end
    it "Default to 0 if not defined" do
      expect(@unrestrected_category.maximum_renewal_length).to eq(0)
    end
  end

  describe "#maximum_renewal_times" do
    before(:each) do
      @category.max_renewal_times = 1
      @category.save
      @unrestrected_category = FactoryGirl.create(:category, max_renewal_times: nil)
    end
    it "Should return maximum_renewal_times if defined" do
      expect(@category.maximum_renewal_times).to eq(1)
    end
    it "Default to infinity if not defined" do
      expect(@unrestrected_category.maximum_renewal_times).to eq(Float::INFINITY)
    end
  end

  describe "#maximum_renewal_days_before_due" do
    before(:each) do
      @category.renewal_days_before_due = 1
      @category.save
      @unrestrected_category = FactoryGirl.create(:category, renewal_days_before_due: nil)
    end
    it "Should return maximum_renewal_days_before_due if defined" do
      expect(@category.maximum_renewal_days_before_due).to eq(1)
    end
    it "Default to infinity if not defined" do
      expect(@unrestrected_category.maximum_renewal_days_before_due).to eq(Float::INFINITY)
    end
  end

  describe "#maximum_checkout_length" do
    before(:each) do
      @category.max_checkout_length = 5
      @category.save
      @unrestrected_category = FactoryGirl.create(:category, max_checkout_length: nil)
    end
    it "Should return maximum_checkout_length if defined" do
      expect(@category.maximum_checkout_length).to eq(5)
    end
    it "Default to infinity if not defined" do
      expect(@unrestrected_category.maximum_checkout_length).to eq(Float::INFINITY)
    end
  end

  describe ".catalog_search" do
    before(:each) do
      @category.name = "Tumblr hipster instagram sustainable"
      @category.save
      @hipster = FactoryGirl.create(:category, name: "Tumblr starbucks PBR slackline music hipster")
    end
    it "Should return names matching all of the query words" do
      expect(Category.catalog_search("Tumblr")).to eq([@category, @hipster])
      expect(Category.catalog_search("Tumblr hipster")).to eq([@category, @hipster])
    end
    it "Should not return any categories without every query word in the name" do
      expect(Category.catalog_search("starbucks")).to eq([@hipster])
      expect(Category.catalog_search("Tumblr instagram sustainable")).to eq([@category])
    end
  end
end


text:
MASKS=('accumbens_l' 'accumbens_r' 'putamen_l' 'putamen_r' 'frontal_orbital_cortex' 'frontal_medial_cortex')
#mkdir -p subject_mask_task_output
#cd subject_mask_task_output
#loop through each mask type
#{1..500}
#loop through each possible subject
for s in {100..500}
do
	#and each possible run
	for r in 1 2
	do
		for m in 'Punish' 'Reward'
		do
			#if we have pre-processed data for this subject*run
	#		/expdata/xfgavin/MSM/sub113/data
			#/expdata/xfgavin/MSM/sub105/analysis/ReversalLearning_Punish_run1_slicetiming_pre.feat
			RUN_DIR="ReversalLearning_${m}_run${r}_pre.feat"
			SUBJECT_INPUT="/expdata/xfgavin/MSM/sub$s/analysis/${RUN_DIR}"
			if [ -e "$SUBJECT_INPUT" ];
			then
			    echo "$SUBJECT_INPUT exists; checking for mask..."
			    for mask in "${MASKS[@]}"
			    do
			      echo "From subject $s run $r $m extracting ROI for $mask"
     		   	MASKFOLDER=/expdata/bensmith/joint-modeling/data/msm/reversallearning/roits/20180720/roi_$mask/
		   	    #make the directory to store if it doesn't exist.
		   	    mkdir -p $MASKFOLDER/
			      # mask_name=`basename ${mask_path%%.*}`
			      mask_path=/expdata/bensmith/joint-modeling/data/msm/reversallearning/masks/harvardoxford_rois/sub${s}_ReversalLearning_${m}_run${r}_pre.feat_${mask}.nii.gz
            #flirt -applyxfm -init ${SUBJECT_INPUT}/reg/standard2example_func.mat -in $mask_path -ref ${SUBJECT_INPUT}/filtered_func_data.nii.gz -out /expdata/bensmith/joint-modeling/data/msm/reversallearning/masks/harvardoxford_rois/sub${s}_${RUN_DIR}_${mask_name}
            fslmeants -i ${SUBJECT_INPUT}/filtered_func_data.nii.gz -m ${mask_path} -o $MASKFOLDER/s${s}r${r}_${m}.txt
          done
			fi
		done
	done
done

redpajama_set_name: RedPajamaGithub


text:
#if !defined( _${library_name_upper_case}_INTERNAL_EXTERN_H )
#define _${library_name_upper_case}_INTERNAL_EXTERN_H

#include <common.h>

/* Define HAVE_LOCAL_${library_name_upper_case} for local use of ${library_name}
 */
#if !defined( HAVE_LOCAL_${library_name_upper_case} )

#include <${library_name}/extern.h>

#if defined( __CYGWIN__ ) || defined( __MINGW32__ )
#define ${library_name_upper_case}_EXTERN_VARIABLE	extern
#else
#define ${library_name_upper_case}_EXTERN_VARIABLE	${library_name_upper_case}_EXTERN
#endif

#else
#define ${library_name_upper_case}_EXTERN		/* extern */
#define ${library_name_upper_case}_EXTERN_VARIABLE	extern

#endif /* !defined( HAVE_LOCAL_${library_name_upper_case} ) */

#endif /* !defined( _${library_name_upper_case}_INTERNAL_EXTERN_H ) */


text:
package commands.viewCommands.turtleCommands;

import java.util.ArrayList;

import application.ViewHandler;

public class GoToLocation extends Move {

	public GoToLocation(ArrayList<Object> p, ViewHandler v) {
		super(p, v);
	}

	public double execute() {
		double x = (Double) super.getParams().get(super.getParams().size() - 2);
		double y = (Double) super.getParams().get(super.getParams().size() - 1);
		return super.goToLocation(x, y);
	}
}


text:
package POJOs;

import java.util.Date;
/**
 *
 * @author Luis
 */
public class Promocion  implements java.io.Serializable {

     private String id;
     private String naturalezaDescuento;
     private String tipoDescuento;
     private long descuento;
     private String descripcion;
     private Date fechaAlta;
     private Date fechaBaja;

    public Promocion() {
    }

    public Promocion(String id, String naturalezaDescuento, String tipoDescuento, long descuento, String descripcion, Date fechaAlta, Date fechaBaja) {
        this.id = id;
        this.naturalezaDescuento = naturalezaDescuento;
        this.tipoDescuento = tipoDescuento;
        this.descuento = descuento;
        this.descripcion = descripcion;
        this.fechaAlta = fechaAlta;
        this.fechaBaja = fechaBaja;
    }

    public String getId() {
        return this.id;
    }

    public void setId(String id) {
        this.id = id;
    }
    public String getNaturalezaDescuento() {
        return this.naturalezaDescuento;
    }

    public void setNaturalezaDescuento(String naturalezaDescuento) {
        this.naturalezaDescuento = naturalezaDescuento;
    }
    public String getTipoDescuento() {
        return this.tipoDescuento;
    }

    public void setTipoDescuento(String tipoDescuento) {
        this.tipoDescuento = tipoDescuento;
    }
    public long getDescuento() {
        return this.descuento;
    }

    public void setDescuento(long descuento) {
        this.descuento = descuento;
    }
    public String getDescripcion() {
        return this.descripcion;
    }

    public void setDescripcion(String descripcion) {
        this.descripcion = descripcion;
    }
    public Date getFechaAlta() {
        return this.fechaAlta;
    }

    public void setFechaAlta(Date fechaAlta) {
        this.fechaAlta = fechaAlta;
    }
    public Date getFechaBaja() {
        return this.fechaBaja;
    }

    public void setFechaBaja(Date fechaBaja) {
        this.fechaBaja = fechaBaja;
    }

}


text:
CQChartsOptRectEdit::
CQChartsOptRectEdit(QWidget *parent) :
 CQChartsOptEdit(parent, "Rect")
{
}

void
CQChartsOptRectEdit::
setValue(const CQChartsOptRect &value)
{
  value_ = value;

  valueToWidgets();
}

void
CQChartsOptRectEdit::
setTextValue(const QString &str)
{
  CQChartsOptRect value;

  value.fromString(str);

  if (value.isSet())
    value_ = value;
}

void
CQChartsOptRectEdit::
resetValue()
{
  value_ = CQChartsOptRect();
}

bool
CQChartsOptRectEdit::
isValueSet() const
{
  return value_.isSet();
}

QString
CQChartsOptRectEdit::
valueToText()
{
  const auto &l = value_.rect();

  return l.toString();
}

QVariant
CQChartsOptRectEdit::
toVariant() const
{
  return CQChartsOptRect::toVariant(value());
}

void
CQChartsOptRectEdit::
fromVariant(const QVariant &var)
{
  auto value = CQChartsOptRect::fromVariant(var);

  setValue(value);
}

//------

CQPropertyViewEditorFactory *
CQChartsOptRectPropertyViewType::
getEditor() const
{
  return new CQChartsOptRectPropertyViewEditor;
}

QString
CQChartsOptRectPropertyViewType::
valueString(CQPropertyViewItem *, const QVariant &value, bool &ok) const
{
  auto optRect = CQChartsOptRect::fromVariant(value);

  QString str;

  if (optRect.isSet()) {
    str = optRect.toString();
    ok  = true;
  }
  else {
    str = "Undefined";
    ok  = false;
  }

  return str;
}

//------

QWidget *
CQChartsOptRectPropertyViewEditor::
createEdit(QWidget *parent)
{
  return new CQChartsOptRectEdit(parent);
}


text:
import cv2, rospy, roslib, os, signal, subprocess
roslib.load_manifest('asr')
from std_msgs.msg import String, Bool

motion_detection = False
md_process = False
alert = None

def md_callback(data):
    global motion_detection
    motion_detection = data.data

def alerts_callback(data):
    global alert
    alert = data.data

def state_callback(data):
    if data.data == "Shutdown":
        rospy.signal_shutdown(shutdown_hook())

def shutdown_hook():
    print("\n...MOTION DETECTION CONTROLLER SHUTTING DOWN...")

    if md_process is not False:
        os.killpg(md_process.pid, signal.SIGTERM)

def motion_detection_controller():
    global motion_detection, md_process, alert

    #md_launch = "roslaunch asr asr_motion_detection.launch"
    launched = False
    previous = alert

    rospy.init_node('motion_detection_controller', anonymous=False)

    rospy.Subscriber("current_state", String, state_callback, queue_size=10)
    rospy.Subscriber("md_active", Bool, md_callback, queue_size=10)
    rospy.Subscriber("user_alerts", String, alerts_callback, queue_size=10)

    rate = rospy.Rate(10)  # 10hz

    print("********** [MOTION DETECTION CONTROLLER] **********")

    while not rospy.is_shutdown():
        if motion_detection and not launched:
            print("\nINITIATING MOTION DETECTION\n")
            #md_process = subprocess.Popen(md_launch, stdout=subprocess.PIPE, shell=True, preexec_fn=os.setsid)
            launched = True
        elif not motion_detection and launched:
            print("\nQUITTING MOTION DETECTION")
            #os.killpg(md_process.pid, signal.SIGTERM)
            #md_process = False
            launched = False
        elif motion_detection and previous != alert:
            print("\nALERT!")
            print(alert)
            previous = alert
        else:
            print("\nMOTION DETECTION INACTIVE")

        rate.sleep()

    rospy.spin()

if __name__ == '__main__':
    try:
        motion_detection_controller()
    except rospy.ROSInterruptException:
        pass


text:
import xmlrpclib

from sfa.util.faults import *
from sfa.trust.certificate import Certificate
from sfa.trust.rights import Right,Rights
from sfa.trust.gid import GID

##
# Credential is a tuple:
#     (GIDCaller, GIDObject, LifeTime, Privileges, Delegate)
#
# These fields are encoded using xmlrpc into the subjectAltName field of the
# x509 certificate. Note: Call encode() once the fields have been filled in
# to perform this encoding.

class CredentialLegacy(Certificate):
    gidCaller = None
    gidObject = None
    lifeTime = None
    privileges = None
    delegate = False

    ##
    # Create a Credential object
    #
    # @param create If true, create a blank x509 certificate
    # @param subject If subject!=None, create an x509 cert with the subject name
    # @param string If string!=None, load the credential from the string
    # @param filename If filename!=None, load the credential from the file

    def __init__(self, create=False, subject=None, string=None, filename=None):
        Certificate.__init__(self, create, subject, string, filename)

    ##
    # set the GID of the caller
    #
    # @param gid GID object of the caller

    def set_gid_caller(self, gid):
        self.gidCaller = gid
        # gid origin caller is the caller's gid by default
        self.gidOriginCaller = gid

    ##
    # get the GID of the object

    def get_gid_caller(self):
        if not self.gidCaller:
            self.decode()
        return self.gidCaller

    ##
    # set the GID of the object
    #
    # @param gid GID object of the object

    def set_gid_object(self, gid):
        self.gidObject = gid

    ##
    # get the GID of the object

    def get_gid_object(self):
        if not self.gidObject:
            self.decode()
        return self.gidObject

    ##
    # set the lifetime of this credential
    #
    # @param lifetime lifetime of credential

    def set_lifetime(self, lifeTime):
        self.lifeTime = lifeTime

    ##
    # get the lifetime of the credential

    def get_lifetime(self):
        if not self.lifeTime:
            self.decode()
        return self.lifeTime

    ##
    # set the delegate bit
    #
    # @param delegate boolean (True or False)

    def set_delegate(self, delegate):
        self.delegate = delegate

    ##
    # get the delegate bit

    def get_delegate(self):
        if not self.delegate:
            self.decode()
        return self.delegate

    ##
    # set the privileges
    #
    # @param privs either a comma-separated list of privileges of a Rights object

    def set_privileges(self, privs):
        if isinstance(privs, str):
            self.privileges = Rights(string = privs)
        else:
            self.privileges = privs

    ##
    # return the privileges as a Rights object

    def get_privileges(self):
        if not self.privileges:
            self.decode()
        return self.privileges

    ##
    # determine whether the credential allows a particular operation to be
    # performed
    #
    # @param op_name string specifying name of operation ("lookup", "update", etc)

    def can_perform(self, op_name):
        rights = self.get_privileges()
        if not rights:
            return False
        return rights.can_perform(op_name)

    ##
    # Encode the attributes of the credential into a string and store that
    # string in the alt-subject-name field of the X509 object. This should be
    # done immediately before signing the credential.

    def encode(self):
        dict = {"gidCaller": None,
                "gidObject": None,
                "lifeTime": self.lifeTime,
                "privileges": None,
                "delegate": self.delegate}
        if self.gidCaller:
            dict["gidCaller"] = self.gidCaller.save_to_string(save_parents=True)
        if self.gidObject:
            dict["gidObject"] = self.gidObject.save_to_string(save_parents=True)
        if self.privileges:
            dict["privileges"] = self.privileges.save_to_string()
        str = xmlrpclib.dumps((dict,), allow_none=True)
        self.set_data('URI:http://' + str)

    ##
    # Retrieve the attributes of the credential from the alt-subject-name field
    # of the X509 certificate. This is automatically done by the various
    # get_* methods of this class and should not need to be called explicitly.

    def decode(self):
        data = self.get_data().lstrip('URI:http://')

        if data:
            dict = xmlrpclib.loads(data)[0][0]
        else:
            dict = {}

        self.lifeTime = dict.get("lifeTime", None)
        self.delegate = dict.get("delegate", None)

        privStr = dict.get("privileges", None)
        if privStr:
            self.privileges = Rights(string = privStr)
        else:
            self.privileges = None

        gidCallerStr = dict.get("gidCaller", None)
        if gidCallerStr:
            self.gidCaller = GID(string=gidCallerStr)
        else:
            self.gidCaller = None

        gidObjectStr = dict.get("gidObject", None)
        if gidObjectStr:
            self.gidObject = GID(string=gidObjectStr)
        else:
            self.gidObject = None

    ##
    # Verify that a chain of credentials is valid (see cert.py:verify). In
    # addition to the checks for ordinary certificates, verification also
    # ensures that the delegate bit was set by each parent in the chain. If
    # a delegate bit was not set, then an exception is thrown.
    #
    # Each credential must be a subset of the rights of the parent.

    def verify_chain(self, trusted_certs = None):
        # do the normal certificate verification stuff
        Certificate.verify_chain(self, trusted_certs)

        if self.parent:
            # make sure the parent delegated rights to the child
            if not self.parent.get_delegate():
                raise MissingDelegateBit(self.parent.get_subject())

            # make sure the rights given to the child are a subset of the
            # parents rights
            if not self.parent.get_privileges().is_superset(self.get_privileges()):
                raise ChildRightsNotSubsetOfParent(self.get_subject()
                                                   + " " + self.parent.get_privileges().save_to_string()
                                                   + " " + self.get_privileges().save_to_string())

        return

    ##
    # Dump the contents of a credential to stdout in human-readable format
    #
    # @param dump_parents If true, also dump the parent certificates

    def dump(self, *args, **kwargs):
        print self.dump_string(*args,**kwargs)

    def dump_string(self, dump_parents=False):
        result=""
        result += "CREDENTIAL %s\n" % self.get_subject()

        result += "      privs: %s\n" % self.get_privileges().save_to_string()

        gidCaller = self.get_gid_caller()
        if gidCaller:
            result += "  gidCaller:\n"
            gidCaller.dump(8, dump_parents)

        gidObject = self.get_gid_object()
        if gidObject:
            result += "  gidObject:\n"
            result += gidObject.dump_string(8, dump_parents)

        result += "   delegate: %s" % self.get_delegate()

        if self.parent and dump_parents:
            result += "PARENT\n"
            result += self.parent.dump_string(dump_parents)

        return result


text:
package alluxio.client.block;

import alluxio.Configuration;
import alluxio.PropertyKey;
import alluxio.resource.ResourcePool;

import java.net.InetSocketAddress;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;

import javax.annotation.concurrent.ThreadSafe;
import javax.security.auth.Subject;

/**
 * Class for managing block master clients. After obtaining a client with
 * {@link ResourcePool#acquire()}, {@link ResourcePool#release(Object)} must be called when the
 * thread is done using the client.
 */
@ThreadSafe
public final class BlockMasterClientPool extends ResourcePool<BlockMasterClient> {
  private final InetSocketAddress mMasterAddress;
  private final Queue<BlockMasterClient> mClientList;
  private final Subject mSubject;

  /**
   * Creates a new block master client pool.
   *
   * @param subject the parent subject
   * @param masterAddress the master address
   */
  public BlockMasterClientPool(Subject subject, InetSocketAddress masterAddress) {
    super(Configuration.getInt(PropertyKey.USER_BLOCK_MASTER_CLIENT_THREADS));
    mSubject = subject;
    mMasterAddress = masterAddress;
    mClientList = new ConcurrentLinkedQueue<>();
  }

  /**
   * Creates a new block master client pool.
   *
   * @param subject the parent subject
   * @param masterAddress the master address
   * @param clientThreads the number of client threads to use
   */
  public BlockMasterClientPool(Subject subject, InetSocketAddress masterAddress,
      int clientThreads) {
    super(clientThreads);
    mSubject = subject;
    mMasterAddress = masterAddress;
    mClientList = new ConcurrentLinkedQueue<>();
  }

  @Override
  public void close() {
    BlockMasterClient client;
    while ((client = mClientList.poll()) != null) {
      client.close();
    }
  }

  @Override
  protected BlockMasterClient createNewResource() {
    return RetryHandlingBlockMasterClient.create(mSubject, mMasterAddress);
  }
}


text:
mgoAdmin.controller('ModalAddUserPass', function($scope, $just) {

    $scope.handleSavePassword = function() {
        var
              login    = $scope.state.userLogin.trim()
            , password = $scope.state.userPass.trim();

        if(login.length && password.length) {
            $scope.state.loading = true;
            $just.auth_register({_id: login, password: password})
                .then(function(result) {
                    $scope.state.loading = false;
                    $scope.handleCloseModal();
                    $scope.handleSelectDataType('Users');
                })
                .catch(function(error) {
                    $scope.state.loading = false;
                    console.error(error);
                    $scope.handleCloseModal();
                });
        }
    };

    $scope.handleCloseModal = function() {
        $scope.state.$value = false;
        $scope.state.userPass = "";
        $scope.state.userLogin = "";
        $scope.state.shouldShowAddUserPassModal = null;

        $scope.$$phase || $scope.$apply();
    }
});


text:
ENV['RAILS_ENV'] = 'test'

require 'simplecov'

SimpleCov.start 'rails' do
  if ENV['CI']
    require 'simplecov-lcov'

    SimpleCov::Formatter::LcovFormatter.config do |c|
      c.report_with_single_file = true
      c.single_report_path = 'coverage/lcov.info'
    end

    formatter SimpleCov::Formatter::LcovFormatter
  end

  add_filter %w[version.rb]
end

require 'minitest/autorun'
require 'minitest/mock'

require 'i18n'

require 'rails'
require 'action_controller/railtie'
require 'action_mailer/railtie'

require 'route_translator'

require 'byebug'

module ActionDispatch
  class TestRequest < Request
    def initialize(env = {})
      super(DEFAULT_ENV.merge(env))

      self.host        = 'test.host'
      self.remote_addr = '0.0.0.0'
      self.user_agent  = 'Rails Testing'
    end
  end
end

Dir[File.expand_path('support/*.rb', __dir__)].sort.each do |helper|
  require helper
end


text:
import random

import fixtures
import mock
import six
import testtools

from sahara import context
from sahara import exceptions as ex

rnd = random.Random()

class ContextTest(testtools.TestCase):
    def setUp(self):
        super(ContextTest, self).setUp()
        self.useFixture(fixtures.FakeLogger('sahara'))
        ctx = context.Context('test_user', 'tenant_1', 'test_auth_token', {},
                              remote_semaphore='123')
        context.set_ctx(ctx)

    def _add_element(self, lst, i):
        context.sleep(rnd.uniform(0, 0.1))
        lst.append(i)

    def _raise_test_exc(self, exc_msg):
        raise TestException(exc_msg)

    def test_thread_group_waits_threads(self):
        # That can fail with some probability, so making 5 attempts
        # Actually it takes around 1 second, so maybe we should
        # just remove it
        for _ in range(5):
            lst = []

            with context.ThreadGroup() as tg:
                for i in range(400):
                    tg.spawn('add %i' % i, self._add_element, lst, i)

            self.assertEqual(len(lst), 400)

    def test_thread_group_waits_threads_if_spawning_exception(self):
        lst = []

        with testtools.ExpectedException(RuntimeError):
            with context.ThreadGroup() as tg:
                for i in range(400):
                    tg.spawn('add %i' % i, self._add_element, lst, i)

                raise RuntimeError()

        self.assertEqual(len(lst), 400)

    def test_thread_group_waits_threads_if_child_exception(self):
        lst = []

        with testtools.ExpectedException(ex.ThreadException):
            with context.ThreadGroup() as tg:
                tg.spawn('raiser', self._raise_test_exc, 'exc')

                for i in range(400):
                    tg.spawn('add %i' % i, self._add_element, lst, i)

        self.assertEqual(len(lst), 400)

    def test_thread_group_handles_spawning_exception(self):
        with testtools.ExpectedException(TestException):
            with context.ThreadGroup():
                raise TestException()

    def test_thread_group_handles_child_exception(self):
        try:
            with context.ThreadGroup() as tg:
                tg.spawn('raiser1', self._raise_test_exc, 'exc1')
        except ex.ThreadException as te:
            self.assertIn('exc1', six.text_type(te))
            self.assertIn('raiser1', six.text_type(te))

    def test_thread_group_prefers_spawning_exception(self):
        with testtools.ExpectedException(RuntimeError):
            with context.ThreadGroup() as tg:
                tg.spawn('raiser1', self._raise_test_exc, 'exc1')
                raise RuntimeError()

    def test_wrapper_does_not_set_exception(self):
        func = mock.MagicMock()

        tg = mock.MagicMock(exc=None, failed_thread=None)

        context._wrapper(None, 'test thread', tg, func)

        self.assertIsNone(tg.exc)
        self.assertIsNone(tg.failed_thread)

    def test_wrapper_catches_base_exception(self):
        func = mock.MagicMock()
        func.side_effect = BaseException()

        tg = mock.MagicMock(exc=None, failed_thread=None)

        context._wrapper(None, 'test thread', tg, func)

        self.assertIsNotNone(tg.exc)
        self.assertEqual(tg.failed_thread, 'test thread')

    def test_is_auth_capable_for_admin_ctx(self):
        ctx = context.ctx()
        self.assertFalse(ctx.is_auth_capable())

    def test_is_auth_capable_for_user_ctx(self):
        existing_ctx = context.ctx()
        try:
            ctx = context.Context('test_user', 'tenant_1', 'test_auth_token',
                                  {"network": "aURL"}, remote_semaphore='123')
            self.assertTrue(ctx.is_auth_capable())
        finally:
            context.set_ctx(existing_ctx)

class TestException(Exception):
    pass


text:
<template name="superGenres">
  {{> posts_list_controller arguments}}
</template>


text:
import { PortalContext } from "../src/components/portal/portal";
import isChromatic from "./isChromatic";

export const withPortalProvider = (Story, context) => {
  return (
    <PortalContext.Provider value={{ renderInRoot: isChromatic() }}>
      <Story {...context} />
    </PortalContext.Provider>
  );
};


text:
module Perspectives
  class Configuration
    delegate :template_path, :template_path=, :raise_on_context_miss?, :raise_on_context_miss, :raise_on_context_miss=, to: 'Mustache'

    CacheNotConfigured = Class.new(StandardError)
    attr_writer :cache
    attr_accessor :caching
    alias_method :caching?, :caching

    def cache
      @cache || (raise CacheNotConfigured, "You must configure a cache")
    end
  end
end


text:
#ifndef __itkFEMPArray_h
#define __itkFEMPArray_h

#include "itkFEMP.h"
#include "itkFEMException.h"
#include <vector>

namespace itk
{
namespace fem
{
/**
 * \class FEMPArray
 * \brief Array for FEMP objects
 *
 * Array class that holds special pointers to objects. Every object must contain
 * a variable member of type int called GN (global number). You can search for
 * an object with specific GN within an array.
 * \ingroup ITKFEM
 */
template <class T>
class FEMPArray : public std::vector<FEMP<T> >
{
public:
  /**
   * Standard Self typedef
   */
  typedef FEMPArray Self;

  /**
   * Standard Superclass typedef
   */
  typedef std::vector<FEMP<T> > Superclass;

  /**
   * Dumb pointer typedef support.
   */
  typedef Self *     Pointer;
  typedef const Self *ConstPointer;

  /**
   * Easy access to the base class of objects inside the array.
   */
  typedef T                                ClassType;
  typedef typename ClassType::Pointer      ClassTypePointer;
  typedef typename ClassType::ConstPointer ClassTypeConstPointer;

  /**
   * Finds and returns a pointer to the object with specific global number
   */
  ClassTypePointer Find(int gn);

  ClassTypeConstPointer Find(int gn) const;

  /**
   * Returns a pointer to i-th object stored in an array (not a pointer to FEMP of that object).
   */
  ClassTypePointer operator()(int i)
  {
    return &( *this->operator[](i) );
  }

  /**
   * Returns a pointer to i-th object stored in an array (not a pointer to FEMP of that object).
   * This function works on the const arrays.
   */
  ClassTypeConstPointer operator()(int i) const
  {
    return &( *this->operator[](i) );
  }

  /**
   * Applies new numbers to objects in array so that they are in order (0,1,2,...).
   * This speeds up finding object by global number a lot. The function returns
   * total number of objects in an array.
   */
  int Renumber();

};

/**
 * Find function for for non-const objects
 */
template <class T>
typename FEMPArray<T>::ClassTypePointer
FEMPArray<T>::Find(int gn)
{
  typedef typename Superclass::iterator Iterator;

  Iterator it   = this->begin();
  Iterator iend = this->end();
  while( it != iend )
    {
    if( ( *it )->GetGlobalNumber() == gn )
      {
      break;
      }
    it++;
    }

  if( it == this->end() )
    {
    /**
     * We din't find an object with that GN...
     */
    throw FEMExceptionObjectNotFound(__FILE__, __LINE__, "FEMPArray::Find() const", typeid( T ).name(), gn);
    }

  /**
   * Return a pointer to the found object.
   */
  return &( *( *it ) );
}

/**
 * Find function for for const objects
 */
template <class T>
typename FEMPArray<T>::ClassTypeConstPointer
FEMPArray<T>::Find(int gn) const
{
  typedef typename Superclass::const_iterator ConstIterator;

  ConstIterator it   = this->begin();
  ConstIterator iend = this->end();
  while( it != iend )
    {
    if( ( *it )->GetGlobalNumber() == gn )
      {
      break;
      }
    it++;
    }

  if( it == this->end() )
    {
    /**
     * We din't find an object with that GN...
     */
    throw FEMExceptionObjectNotFound(__FILE__, __LINE__, "FEMPArray::Find() const", typeid( T ).name(), gn);
    }

  /**
   * Return a pointer to the found object.
   */
  return &( *( *it ) );
}

template <class T>
int FEMPArray<T>::Renumber()
{
  typename Superclass::iterator i;
  int j = 0;
  for( i = this->begin(); i != this->end(); i++ )
    {
    ( *i )->SetGlobalNumber(j);
    j++;
    }

  return j;
}

}
}  // end namespace itk::fem

#endif // #ifndef __itkFEMPArray_h


text:
import random

class Perceptron( object ):

	randomize_w_and_b = False

	def __init__( self ):
		self.w = None
		self.D = 0
		self.b = 0
		self.attrs = None

	# Algorithm Body:
	def perceptronTrain( self, Data, MaxIter ):
		self.w = [ random.uniform( -1, 1 ) if self.randomize_w_and_b else 0 for _ in Data.attributes ]
		self.D = len( self.w )
		self.attrs = Data.attributes
		self.b = random.uniform( -1, 1 ) if self.randomize_w_and_b else 0
		for i in range( MaxIter ):
			changed = False
			for x, y in Data.getRowsTuples():
				a = self.activation( x )
				if ( y * a ) <= 0:
					changed = True
					self.w = [ self.w[d] + ( y * x[d] ) for d in range( self.D ) ]
					self.b += y
			if not changed:
				print( "Nothing changed on this pass, breaking out at", i, "iterations." )
				return

	def perceptronTest( self, row ):
		a = self.activation( row )
		return self.sign( a )

	def perceptronTestAndPrint( self, row ):
		a = self.activation( row )
		print( a )
		return self.sign( a )

	def perceptronPredictions( self, Data, printBool ):
		if self.w is None:
			print( "Perceptron must be trained first with .perceptronTrain( Data, MaxIter )" )
			return
		if printBool:
			return [ self.perceptronTestAndPrint( row ) for row in Data.rows ]
		else:
			return [ self.perceptronTest( row ) for row in Data.rows ]

	def perceptronPredictionResults( self, Data ):
		return Data.compareTrueResultsWith( self.perceptronPredictions( Data, False ) )

	def perceptronPredictionResultsAndPrintActivations( self, Data ):
		return Data.compareTrueResultsWith( self.perceptronPredictions( Data, True ) )

	def activation( self, row ):
		activation = 0
		for d in range( self.D ):
			activation += ( self.w[d] * row[d] )
		return activation + self.b

	# Support Methods:

	def predictionFromRow( self, row ):
		return 1 if self.perceptronTest( row ) == 1 else 0

	def sign( self, a ):
		return 1 if a > 0 else -1

	def forceOneOrZero( self, result ):
		return 1 if result == 1 else 0

	def outputModelToFile( self, filename ):
		with open( filename, 'w+' ) as model_file:
			model_file.write( str( round( self.b, 2 ) ) + "\n" )
			for d in range( self.D ):
				model_file.write( str( self.attrs[d] ) + " " + str( round( self.w[d], 5 ) ) + "\n" )


text:
package spet.sbwo.control.action.base;

import org.slf4j.LoggerFactory;
import spet.sbwo.control.ControlError;
import spet.sbwo.control.ControlException;
import spet.sbwo.control.action.Texts;
import spet.sbwo.control.channel.user.UserChannel;
import spet.sbwo.data.DatabaseException;
import spet.sbwo.data.access.IDatabaseExecutor;
import spet.sbwo.data.table.User;

public abstract class BaseUserDatabaseAction<I, O> implements IUserDatabaseAction<I, O> {
    protected final Class<?> channel;
    protected final boolean mandatory;

    protected BaseUserDatabaseAction(Class<?> channel, boolean mandatory) {
        this.channel = channel;
        this.mandatory = mandatory;
    }

    @Override
    public O run(I input, IDatabaseExecutor executor, User user) {
        try {
            if (mandatory && user == null) {
                throw new ControlException(ControlError.ENTITY_NOT_FOUND, UserChannel.class);
            } else {
                return doRun(input, executor, user);
            }
        } catch (DatabaseException e) {
            LoggerFactory.getLogger(this.getClass()).error(Texts.INSTANCE.get(this.getClass()), String.valueOf(input));
            throw new ControlException(e, channel);
        }
    }

    protected abstract O doRun(I input, IDatabaseExecutor executor, User user);

}


text:
import styled from 'styled-components'
import { media } from './media'

export const Cifer = styled.div`
    display: flex;
    flex-direction: row;
    flex: 1;
    align-items: baseline;
    padding: 0 10px;

    ${media.tablet`
            flex-direction: column;
            align-items: center;
        `
    }
`

export const Cont = styled.div`
    display:flex;
    align-items: center;
    height: 100vh;
    ${media.tablet`
        height: initial;
    `}
`


text:
using NUnit.Framework;
using DnDGen.TreasureGen.Tables;
using DnDGen.TreasureGen.Items;

namespace DnDGen.TreasureGen.Tests.Integration.Tables.Items.Magical.Weapons.Major
{
    [TestFixture]
    public class MajorSpecificWeaponsTests : TypeAndAmountPercentileTests
    {
        protected override string tableName
        {
            get { return string.Format(TableNameConstants.Percentiles.Formattable.POWERSpecificITEMTYPEs, PowerConstants.Major, ItemTypeConstants.Weapon); }
        }

        [Test]
        public override void ReplacementStringsAreValid()
        {
            AssertReplacementStringsAreValid();
        }

        [Test]
        public override void TableIsComplete()
        {
            AssertTableIsComplete();
        }

        [TestCase(WeaponConstants.AssassinsDagger, 2, 1, 4)]
        [TestCase(WeaponConstants.ShiftersSorrow, 1, 5, 7)]
        [TestCase(WeaponConstants.TridentOfFishCommand, 1, 8, 9)]
        [TestCase(WeaponConstants.FlameTongue, 1, 10, 13)]
        [TestCase(WeaponConstants.LuckBlade0, 2, 14, 17)]
        [TestCase(WeaponConstants.SwordOfSubtlety, 1, 18, 24)]
        [TestCase(WeaponConstants.SwordOfThePlanes, 1, 25, 31)]
        [TestCase(WeaponConstants.NineLivesStealer, 2, 32, 37)]
        [TestCase(WeaponConstants.SwordOfLifeStealing, 2, 38, 42)]
        [TestCase(WeaponConstants.Oathbow, 2, 43, 46)]
        [TestCase(WeaponConstants.MaceOfTerror, 2, 47, 51)]
        [TestCase(WeaponConstants.LifeDrinker, 1, 52, 57)]
        [TestCase(WeaponConstants.SylvanScimitar, 3, 58, 62)]
        [TestCase(WeaponConstants.RapierOfPuncturing, 2, 63, 67)]
        [TestCase(WeaponConstants.SunBlade, 2, 68, 73)]
        [TestCase(WeaponConstants.FrostBrand, 3, 74, 79)]
        [TestCase(WeaponConstants.DwarvenThrower, 2, 80, 84)]
        [TestCase(WeaponConstants.LuckBlade1, 2, 85, 91)]
        [TestCase(WeaponConstants.MaceOfSmiting, 3, 92, 95)]
        [TestCase(WeaponConstants.LuckBlade2, 2, 96, 97)]
        [TestCase(WeaponConstants.HolyAvenger, 2, 98, 99)]
        public override void TypeAndAmountPercentile(string type, int amount, int lower, int upper)
        {
            base.TypeAndAmountPercentile(type, amount, lower, upper);
        }

        [TestCase(WeaponConstants.LuckBlade3, 2, 100)]
        public override void TypeAndAmountPercentile(string type, int amount, int roll)
        {
            base.TypeAndAmountPercentile(type, amount, roll);
        }
    }
}


text:
<?php
/**
 * My Sites dashboard.
 *
 * @package WordPress
 * @subpackage Multisite
 * @since 3.0.0
 */

require_once( dirname( __FILE__ ) . '/admin.php' );

if ( !is_multisite() )
	wp_die( __( 'Multisite support is not enabled.' ) );

if ( ! current_user_can('read') )
	wp_die( __( 'Sorry, you are not allowed to access this page.' ) );

$action = isset( $_POST['action'] ) ? $_POST['action'] : 'splash';

$blogs = get_blogs_of_user( $current_user->ID );

$updated = false;
if ( 'updateblogsettings' == $action && isset( $_POST['primary_blog'] ) ) {
	check_admin_referer( 'update-my-sites' );

	$blog = get_site( (int) $_POST['primary_blog'] );
	if ( $blog && isset( $blog->domain ) ) {
		update_user_option( $current_user->ID, 'primary_blog', (int) $_POST['primary_blog'], true );
		$updated = true;
	} else {
		wp_die( __( 'The primary site you chose does not exist.' ) );
	}
}

$title = __( 'My Sites' );
$parent_file = 'index.php';

get_current_screen()->add_help_tab( array(
	'id'      => 'overview',
	'title'   => __('Overview'),
	'content' =>
		'
' . __('This screen shows an individual user all of their sites in this network, and also allows that user to set a primary site. They can use the links under each site to visit either the front end or the dashboard for that site.') . '
'
) );

get_current_screen()->set_help_sidebar(
	'
' . __('For more information:') . '
' .
	'
' . __('Documentation on My Sites') . '
' .
	'
' . __('Support Forums') . '
'
);

require_once( ABSPATH . 'wp-admin/admin-header.php' );

if ( $updated ) { ?>

<?php _e( 'Settings saved.' ); ?>

<?php } ?>

<?php
echo esc_html( $title );

if ( in_array( get_site_option( 'registration' ), array( 'all', 'blog' ) ) ) {
	/** This filter is documented in wp-login.php */
	$sign_up_url = apply_filters( 'wp_signup_location', network_site_url( 'wp-signup.php' ) );
	printf( ' %s', esc_url( $sign_up_url ), esc_html_x( 'Add New', 'site' ) );
}
?>

<?php
if ( empty( $blogs ) ) :
	echo '
';
	_e( 'You must be a member of at least one site to use this page.' );
	echo '
';
else :
?>
<form id="myblogs" method="post">
	<?php
	choose_primary_blog();
	/**
	 * Fires before the sites list on the My Sites screen.
	 *
	 * @since 3.0.0
	 */
	do_action( 'myblogs_allblogs_options' );
	?>

	<?php
	/**
	 * Enable the Global Settings section on the My Sites screen.
	 *
	 * By default, the Global Settings section is hidden. Passing a non-empty
	 * string to this filter will enable the section, and allow new settings
	 * to be added, either globally or for specific sites.
	 *
	 * @since MU
	 *
	 * @param string $settings_html The settings HTML markup. Default empty.
	 * @param object $context       Context of the setting (global or site-specific). Default 'global'.
	 */
	$settings_html = apply_filters( 'myblogs_options', '', 'global' );
	if ( $settings_html != '' ) {
		echo '
' . __( 'Global Settings' ) . '
';
		echo $settings_html;
	}
	reset( $blogs );

	foreach ( $blogs as $user_blog ) {
		echo "
";
		echo "
{$user_blog->blogname}
";
		/**
		 * Filters the row links displayed for each site on the My Sites screen.
		 *
		 * @since MU
		 *
		 * @param string $string    The HTML site link markup.
		 * @param object $user_blog An object containing the site data.
		 */
		echo "
" . apply_filters( 'myblogs_blog_actions', "userblog_id ) ). "'>" . __( 'Visit' ) . " | userblog_id ) ) . "'>" . __( 'Dashboard' ) . "", $user_blog ) . "
";
		/** This filter is documented in wp-admin/my-sites.php */
		echo apply_filters( 'myblogs_options', '', $user_blog );
		echo "
";
	}?>

	<?php
	if ( count( $blogs ) > 1 || has_action( 'myblogs_allblogs_options' ) || has_filter( 'myblogs_options' ) ) {
		?><input type="hidden" name="action" value="updateblogsettings" /><?php
		wp_nonce_field( 'update-my-sites' );
		submit_button();
	}
	?>
	</form>
<?php endif; ?>

<?php
include( ABSPATH . 'wp-admin/admin-footer.php' );


text:
# secondsInMonth

> Determine the number of seconds in a month.

## Usage

```javascript
var secondsInMonth = require( '@stdlib/time/seconds-in-month' );
```

#### secondsInMonth( \[month\[, year]] )

Returns the number of seconds in a month.

```javascript
var num = secondsInMonth();
// returns <number>
```

By default, the function returns the number of seconds in the current month of the current year (according to local time). To determine the number of seconds for a particular month and year, provide `month` and `year` arguments.

```javascript
var num = secondsInMonth( 2 );
// returns <number>

num = secondsInMonth( 2, 2016 );
// returns 2505600

num = secondsInMonth( 2, 2017 );
// returns 2419200
```

A `month` may be either a month's integer value, three letter abbreviation, or full name (case insensitive).

```javascript
var num = secondsInMonth( 2, 2016 );
// returns 2505600

num = secondsInMonth( 'feb', 2016 );
// returns 2505600

num = secondsInMonth( 'february', 2016 );
// returns 2505600
```

The function also supports providing a [`Date`][date-object] object.

```javascript
var num = secondsInMonth( new Date() );
// returns <number>
```

## Notes

-   The function's return value is a generalization and does **not** take into account inaccuracies due to daylight savings conventions, crossing timezones, or other complications with time and dates.

## Examples

```javascript
var secondsInMonth = require( '@stdlib/time/seconds-in-month' );

var v;
var i;

for ( i = 0; i < 2021; i++ ) {
    v = secondsInMonth( 'feb', i );
    console.log( 'In the year %d, February has %d seconds.', i, v );
}
```

* * *

## CLI

### Usage

```text
Usage: seconds-in-month [options] [month] [year]

Options:

  -h,    --help                Print this message.
  -V,    --version             Print the package version.
```

### Examples

```bash
$ seconds-in-month
<number>
```

For a specific month,

```bash
$ seconds-in-month 2
<number>
```

For a specific month and year,

```bash
$ seconds-in-month 2 2016
2505600
```

* * *

## See Also

-   [`@stdlib/time/seconds-in-year`][@stdlib/time/seconds-in-year]: determine the number of seconds in a year according to the Gregorian calendar.

[date-object]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

[@stdlib/time/seconds-in-year]: https://github.com/stdlib-js/stdlib/tree/develop/lib/node_modules/%40stdlib/time/seconds-in-year


text:
#pragma once
#include <aws/cognito-idp/CognitoIdentityProvider_EXPORTS.h>
#include <aws/cognito-idp/CognitoIdentityProviderRequest.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/cognito-idp/model/UserPoolPolicyType.h>
#include <aws/cognito-idp/model/LambdaConfigType.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <aws/cognito-idp/model/UserPoolMfaType.h>
#include <aws/cognito-idp/model/DeviceConfigurationType.h>
#include <aws/cognito-idp/model/EmailConfigurationType.h>
#include <aws/cognito-idp/model/SmsConfigurationType.h>
#include <aws/cognito-idp/model/AdminCreateUserConfigType.h>
#include <aws/cognito-idp/model/VerifiedAttributeType.h>

namespace Aws
{
namespace CognitoIdentityProvider
{
namespace Model
{

  /**
   *
Represents the request to update the user pool.

   */
  class AWS_COGNITOIDENTITYPROVIDER_API UpdateUserPoolRequest : public CognitoIdentityProviderRequest
  {
  public:
    UpdateUserPoolRequest();
    Aws::String SerializePayload() const override;

    Aws::Http::HeaderValueCollection GetRequestSpecificHeaders() const override;

    /**
     *
The user pool ID for the user pool you want to update.

     */
    inline const Aws::String& GetUserPoolId() const{ return m_userPoolId; }

    /**
     *
The user pool ID for the user pool you want to update.

     */
    inline void SetUserPoolId(const Aws::String& value) { m_userPoolIdHasBeenSet = true; m_userPoolId = value; }

    /**
     *
The user pool ID for the user pool you want to update.

     */
    inline void SetUserPoolId(Aws::String&& value) { m_userPoolIdHasBeenSet = true; m_userPoolId = value; }

    /**
     *
The user pool ID for the user pool you want to update.

     */
    inline void SetUserPoolId(const char* value) { m_userPoolIdHasBeenSet = true; m_userPoolId.assign(value); }

    /**
     *
The user pool ID for the user pool you want to update.

     */
    inline UpdateUserPoolRequest& WithUserPoolId(const Aws::String& value) { SetUserPoolId(value); return *this;}

    /**
     *
The user pool ID for the user pool you want to update.

     */
    inline UpdateUserPoolRequest& WithUserPoolId(Aws::String&& value) { SetUserPoolId(value); return *this;}

    /**
     *
The user pool ID for the user pool you want to update.

     */
    inline UpdateUserPoolRequest& WithUserPoolId(const char* value) { SetUserPoolId(value); return *this;}

    /**
     *
A container with the policies you wish to update in a user pool.

     */
    inline const UserPoolPolicyType& GetPolicies() const{ return m_policies; }

    /**
     *
A container with the policies you wish to update in a user pool.

     */
    inline void SetPolicies(const UserPoolPolicyType& value) { m_policiesHasBeenSet = true; m_policies = value; }

    /**
     *
A container with the policies you wish to update in a user pool.

     */
    inline void SetPolicies(UserPoolPolicyType&& value) { m_policiesHasBeenSet = true; m_policies = value; }

    /**
     *
A container with the policies you wish to update in a user pool.

     */
    inline UpdateUserPoolRequest& WithPolicies(const UserPoolPolicyType& value) { SetPolicies(value); return *this;}

    /**
     *
A container with the policies you wish to update in a user pool.

     */
    inline UpdateUserPoolRequest& WithPolicies(UserPoolPolicyType&& value) { SetPolicies(value); return *this;}

    /**
     *
The AWS Lambda configuration information from the request to update the user
     * pool.

     */
    inline const LambdaConfigType& GetLambdaConfig() const{ return m_lambdaConfig; }

    /**
     *
The AWS Lambda configuration information from the request to update the user
     * pool.

     */
    inline void SetLambdaConfig(const LambdaConfigType& value) { m_lambdaConfigHasBeenSet = true; m_lambdaConfig = value; }

    /**
     *
The AWS Lambda configuration information from the request to update the user
     * pool.

     */
    inline void SetLambdaConfig(LambdaConfigType&& value) { m_lambdaConfigHasBeenSet = true; m_lambdaConfig = value; }

    /**
     *
The AWS Lambda configuration information from the request to update the user
     * pool.

     */
    inline UpdateUserPoolRequest& WithLambdaConfig(const LambdaConfigType& value) { SetLambdaConfig(value); return *this;}

    /**
     *
The AWS Lambda configuration information from the request to update the user
     * pool.

     */
    inline UpdateUserPoolRequest& WithLambdaConfig(LambdaConfigType&& value) { SetLambdaConfig(value); return *this;}

    /**
     *
The attributes that are automatically verified when the Amazon Cognito
     * service makes a request to update user pools.

     */
    inline const Aws::Vector<VerifiedAttributeType>& GetAutoVerifiedAttributes() const{ return m_autoVerifiedAttributes; }

    /**
     *
The attributes that are automatically verified when the Amazon Cognito
     * service makes a request to update user pools.

     */
    inline void SetAutoVerifiedAttributes(const Aws::Vector<VerifiedAttributeType>& value) { m_autoVerifiedAttributesHasBeenSet = true; m_autoVerifiedAttributes = value; }

    /**
     *
The attributes that are automatically verified when the Amazon Cognito
     * service makes a request to update user pools.

     */
    inline void SetAutoVerifiedAttributes(Aws::Vector<VerifiedAttributeType>&& value) { m_autoVerifiedAttributesHasBeenSet = true; m_autoVerifiedAttributes = value; }

    /**
     *
The attributes that are automatically verified when the Amazon Cognito
     * service makes a request to update user pools.

     */
    inline UpdateUserPoolRequest& WithAutoVerifiedAttributes(const Aws::Vector<VerifiedAttributeType>& value) { SetAutoVerifiedAttributes(value); return *this;}

    /**
     *
The attributes that are automatically verified when the Amazon Cognito
     * service makes a request to update user pools.

     */
    inline UpdateUserPoolRequest& WithAutoVerifiedAttributes(Aws::Vector<VerifiedAttributeType>&& value) { SetAutoVerifiedAttributes(value); return *this;}

    /**
     *
The attributes that are automatically verified when the Amazon Cognito
     * service makes a request to update user pools.

     */
    inline UpdateUserPoolRequest& AddAutoVerifiedAttributes(const VerifiedAttributeType& value) { m_autoVerifiedAttributesHasBeenSet = true; m_autoVerifiedAttributes.push_back(value); return *this; }

    /**
     *
The attributes that are automatically verified when the Amazon Cognito
     * service makes a request to update user pools.

     */
    inline UpdateUserPoolRequest& AddAutoVerifiedAttributes(VerifiedAttributeType&& value) { m_autoVerifiedAttributesHasBeenSet = true; m_autoVerifiedAttributes.push_back(value); return *this; }

    /**
     *
A container with information about the SMS verification message.

     */
    inline const Aws::String& GetSmsVerificationMessage() const{ return m_smsVerificationMessage; }

    /**
     *
A container with information about the SMS verification message.

     */
    inline void SetSmsVerificationMessage(const Aws::String& value) { m_smsVerificationMessageHasBeenSet = true; m_smsVerificationMessage = value; }

    /**
     *
A container with information about the SMS verification message.

     */
    inline void SetSmsVerificationMessage(Aws::String&& value) { m_smsVerificationMessageHasBeenSet = true; m_smsVerificationMessage = value; }

    /**
     *
A container with information about the SMS verification message.

     */
    inline void SetSmsVerificationMessage(const char* value) { m_smsVerificationMessageHasBeenSet = true; m_smsVerificationMessage.assign(value); }

    /**
     *
A container with information about the SMS verification message.

     */
    inline UpdateUserPoolRequest& WithSmsVerificationMessage(const Aws::String& value) { SetSmsVerificationMessage(value); return *this;}

    /**
     *
A container with information about the SMS verification message.

     */
    inline UpdateUserPoolRequest& WithSmsVerificationMessage(Aws::String&& value) { SetSmsVerificationMessage(value); return *this;}

    /**
     *
A container with information about the SMS verification message.

     */
    inline UpdateUserPoolRequest& WithSmsVerificationMessage(const char* value) { SetSmsVerificationMessage(value); return *this;}

    /**
     *
The contents of the email verification message.

     */
    inline const Aws::String& GetEmailVerificationMessage() const{ return m_emailVerificationMessage; }

    /**
     *
The contents of the email verification message.

     */
    inline void SetEmailVerificationMessage(const Aws::String& value) { m_emailVerificationMessageHasBeenSet = true; m_emailVerificationMessage = value; }

    /**
     *
The contents of the email verification message.

     */
    inline void SetEmailVerificationMessage(Aws::String&& value) { m_emailVerificationMessageHasBeenSet = true; m_emailVerificationMessage = value; }

    /**
     *
The contents of the email verification message.

     */
    inline void SetEmailVerificationMessage(const char* value) { m_emailVerificationMessageHasBeenSet = true; m_emailVerificationMessage.assign(value); }

    /**
     *
The contents of the email verification message.

     */
    inline UpdateUserPoolRequest& WithEmailVerificationMessage(const Aws::String& value) { SetEmailVerificationMessage(value); return *this;}

    /**
     *
The contents of the email verification message.

     */
    inline UpdateUserPoolRequest& WithEmailVerificationMessage(Aws::String&& value) { SetEmailVerificationMessage(value); return *this;}

    /**
     *
The contents of the email verification message.

     */
    inline UpdateUserPoolRequest& WithEmailVerificationMessage(const char* value) { SetEmailVerificationMessage(value); return *this;}

    /**
     *
The subject of the email verfication message.

     */
    inline const Aws::String& GetEmailVerificationSubject() const{ return m_emailVerificationSubject; }

    /**
     *
The subject of the email verfication message.

     */
    inline void SetEmailVerificationSubject(const Aws::String& value) { m_emailVerificationSubjectHasBeenSet = true; m_emailVerificationSubject = value; }

    /**
     *
The subject of the email verfication message.

     */
    inline void SetEmailVerificationSubject(Aws::String&& value) { m_emailVerificationSubjectHasBeenSet = true; m_emailVerificationSubject = value; }

    /**
     *
The subject of the email verfication message.

     */
    inline void SetEmailVerificationSubject(const char* value) { m_emailVerificationSubjectHasBeenSet = true; m_emailVerificationSubject.assign(value); }

    /**
     *
The subject of the email verfication message.

     */
    inline UpdateUserPoolRequest& WithEmailVerificationSubject(const Aws::String& value) { SetEmailVerificationSubject(value); return *this;}

    /**
     *
The subject of the email verfication message.

     */
    inline UpdateUserPoolRequest& WithEmailVerificationSubject(Aws::String&& value) { SetEmailVerificationSubject(value); return *this;}

    /**
     *
The subject of the email verfication message.

     */
    inline UpdateUserPoolRequest& WithEmailVerificationSubject(const char* value) { SetEmailVerificationSubject(value); return *this;}

    /**
     *
The contents of the SMS authentication message.

     */
    inline const Aws::String& GetSmsAuthenticationMessage() const{ return m_smsAuthenticationMessage; }

    /**
     *
The contents of the SMS authentication message.

     */
    inline void SetSmsAuthenticationMessage(const Aws::String& value) { m_smsAuthenticationMessageHasBeenSet = true; m_smsAuthenticationMessage = value; }

    /**
     *
The contents of the SMS authentication message.

     */
    inline void SetSmsAuthenticationMessage(Aws::String&& value) { m_smsAuthenticationMessageHasBeenSet = true; m_smsAuthenticationMessage = value; }

    /**
     *
The contents of the SMS authentication message.

     */
    inline void SetSmsAuthenticationMessage(const char* value) { m_smsAuthenticationMessageHasBeenSet = true; m_smsAuthenticationMessage.assign(value); }

    /**
     *
The contents of the SMS authentication message.

     */
    inline UpdateUserPoolRequest& WithSmsAuthenticationMessage(const Aws::String& value) { SetSmsAuthenticationMessage(value); return *this;}

    /**
     *
The contents of the SMS authentication message.

     */
    inline UpdateUserPoolRequest& WithSmsAuthenticationMessage(Aws::String&& value) { SetSmsAuthenticationMessage(value); return *this;}

    /**
     *
The contents of the SMS authentication message.

     */
    inline UpdateUserPoolRequest& WithSmsAuthenticationMessage(const char* value) { SetSmsAuthenticationMessage(value); return *this;}

    /**
     *
Can be one of the following values:

 OFF - MFA
     * tokens are not required and cannot be specified during user registration.

     *

 ON - MFA tokens are required for all user
     * registrations. You can only specify required when you are initially creating a
     * user pool.

 OPTIONAL - Users have the option when
     * registering to create an MFA token.

     */
    inline const UserPoolMfaType& GetMfaConfiguration() const{ return m_mfaConfiguration; }

    /**
     *
Can be one of the following values:

 OFF - MFA
     * tokens are not required and cannot be specified during user registration.

     *

 ON - MFA tokens are required for all user
     * registrations. You can only specify required when you are initially creating a
     * user pool.

 OPTIONAL - Users have the option when
     * registering to create an MFA token.

     */
    inline void SetMfaConfiguration(const UserPoolMfaType& value) { m_mfaConfigurationHasBeenSet = true; m_mfaConfiguration = value; }

    /**
     *
Can be one of the following values:

 OFF - MFA
     * tokens are not required and cannot be specified during user registration.

     *

 ON - MFA tokens are required for all user
     * registrations. You can only specify required when you are initially creating a
     * user pool.

 OPTIONAL - Users have the option when
     * registering to create an MFA token.

     */
    inline void SetMfaConfiguration(UserPoolMfaType&& value) { m_mfaConfigurationHasBeenSet = true; m_mfaConfiguration = value; }

    /**
     *
Can be one of the following values:

 OFF - MFA
     * tokens are not required and cannot be specified during user registration.

     *

 ON - MFA tokens are required for all user
     * registrations. You can only specify required when you are initially creating a
     * user pool.

 OPTIONAL - Users have the option when
     * registering to create an MFA token.

     */
    inline UpdateUserPoolRequest& WithMfaConfiguration(const UserPoolMfaType& value) { SetMfaConfiguration(value); return *this;}

    /**
     *
Can be one of the following values:

 OFF - MFA
     * tokens are not required and cannot be specified during user registration.

     *

 ON - MFA tokens are required for all user
     * registrations. You can only specify required when you are initially creating a
     * user pool.

 OPTIONAL - Users have the option when
     * registering to create an MFA token.

     */
    inline UpdateUserPoolRequest& WithMfaConfiguration(UserPoolMfaType&& value) { SetMfaConfiguration(value); return *this;}

    /**
     *
Device configuration.

     */
    inline const DeviceConfigurationType& GetDeviceConfiguration() const{ return m_deviceConfiguration; }

    /**
     *
Device configuration.

     */
    inline void SetDeviceConfiguration(const DeviceConfigurationType& value) { m_deviceConfigurationHasBeenSet = true; m_deviceConfiguration = value; }

    /**
     *
Device configuration.

     */
    inline void SetDeviceConfiguration(DeviceConfigurationType&& value) { m_deviceConfigurationHasBeenSet = true; m_deviceConfiguration = value; }

    /**
     *
Device configuration.

     */
    inline UpdateUserPoolRequest& WithDeviceConfiguration(const DeviceConfigurationType& value) { SetDeviceConfiguration(value); return *this;}

    /**
     *
Device configuration.

     */
    inline UpdateUserPoolRequest& WithDeviceConfiguration(DeviceConfigurationType&& value) { SetDeviceConfiguration(value); return *this;}

    /**
     *
Email configuration.

     */
    inline const EmailConfigurationType& GetEmailConfiguration() const{ return m_emailConfiguration; }

    /**
     *
Email configuration.

     */
    inline void SetEmailConfiguration(const EmailConfigurationType& value) { m_emailConfigurationHasBeenSet = true; m_emailConfiguration = value; }

    /**
     *
Email configuration.

     */
    inline void SetEmailConfiguration(EmailConfigurationType&& value) { m_emailConfigurationHasBeenSet = true; m_emailConfiguration = value; }

    /**
     *
Email configuration.

     */
    inline UpdateUserPoolRequest& WithEmailConfiguration(const EmailConfigurationType& value) { SetEmailConfiguration(value); return *this;}

    /**
     *
Email configuration.

     */
    inline UpdateUserPoolRequest& WithEmailConfiguration(EmailConfigurationType&& value) { SetEmailConfiguration(value); return *this;}

    /**
     *
SMS configuration.

     */
    inline const SmsConfigurationType& GetSmsConfiguration() const{ return m_smsConfiguration; }

    /**
     *
SMS configuration.

     */
    inline void SetSmsConfiguration(const SmsConfigurationType& value) { m_smsConfigurationHasBeenSet = true; m_smsConfiguration = value; }

    /**
     *
SMS configuration.

     */
    inline void SetSmsConfiguration(SmsConfigurationType&& value) { m_smsConfigurationHasBeenSet = true; m_smsConfiguration = value; }

    /**
     *
SMS configuration.

     */
    inline UpdateUserPoolRequest& WithSmsConfiguration(const SmsConfigurationType& value) { SetSmsConfiguration(value); return *this;}

    /**
     *
SMS configuration.

     */
    inline UpdateUserPoolRequest& WithSmsConfiguration(SmsConfigurationType&& value) { SetSmsConfiguration(value); return *this;}

    /**
     *
The configuration for AdminCreateUser requests.

     */
    inline const AdminCreateUserConfigType& GetAdminCreateUserConfig() const{ return m_adminCreateUserConfig; }

    /**
     *
The configuration for AdminCreateUser requests.

     */
    inline void SetAdminCreateUserConfig(const AdminCreateUserConfigType& value) { m_adminCreateUserConfigHasBeenSet = true; m_adminCreateUserConfig = value; }

    /**
     *
The configuration for AdminCreateUser requests.

     */
    inline void SetAdminCreateUserConfig(AdminCreateUserConfigType&& value) { m_adminCreateUserConfigHasBeenSet = true; m_adminCreateUserConfig = value; }

    /**
     *
The configuration for AdminCreateUser requests.

     */
    inline UpdateUserPoolRequest& WithAdminCreateUserConfig(const AdminCreateUserConfigType& value) { SetAdminCreateUserConfig(value); return *this;}

    /**
     *
The configuration for AdminCreateUser requests.

     */
    inline UpdateUserPoolRequest& WithAdminCreateUserConfig(AdminCreateUserConfigType&& value) { SetAdminCreateUserConfig(value); return *this;}

  private:
    Aws::String m_userPoolId;
    bool m_userPoolIdHasBeenSet;
    UserPoolPolicyType m_policies;
    bool m_policiesHasBeenSet;
    LambdaConfigType m_lambdaConfig;
    bool m_lambdaConfigHasBeenSet;
    Aws::Vector<VerifiedAttributeType> m_autoVerifiedAttributes;
    bool m_autoVerifiedAttributesHasBeenSet;
    Aws::String m_smsVerificationMessage;
    bool m_smsVerificationMessageHasBeenSet;
    Aws::String m_emailVerificationMessage;
    bool m_emailVerificationMessageHasBeenSet;
    Aws::String m_emailVerificationSubject;
    bool m_emailVerificationSubjectHasBeenSet;
    Aws::String m_smsAuthenticationMessage;
    bool m_smsAuthenticationMessageHasBeenSet;
    UserPoolMfaType m_mfaConfiguration;
    bool m_mfaConfigurationHasBeenSet;
    DeviceConfigurationType m_deviceConfiguration;
    bool m_deviceConfigurationHasBeenSet;
    EmailConfigurationType m_emailConfiguration;
    bool m_emailConfigurationHasBeenSet;
    SmsConfigurationType m_smsConfiguration;
    bool m_smsConfigurationHasBeenSet;
    AdminCreateUserConfigType m_adminCreateUserConfig;
    bool m_adminCreateUserConfigHasBeenSet;
  };

} // namespace Model
} // namespace CognitoIdentityProvider
} // namespace Aws


text:
import { default as Axios } from "axios";
import { ISearchResult, IRole, ISecurityClaim } from "../../model";
import { GlobalConfig } from "../../common";
import { Store, StoreService } from "../../store";

// URL and endpoint constants
const BASE_URL = GlobalConfig.uri.services + "manage/role/";

const SEARCH_URL = BASE_URL + "search";
const CLONE_URL = BASE_URL + "clonerole";
const GET_URL = BASE_URL + "getrole";
const PUT_URL = BASE_URL + "updaterole";
const POST_URL = BASE_URL + "createrole";

export interface IGetRolePayload {
  allowedValuesPattern: string;
  availableClaims: ISecurityClaim[];
  existingRoles: IRole[];
  systemRoles: IRole[];
  role: IRole;
}

export class ManageRoleService extends StoreService {
  constructor(store: Store<{}>) {
    super(store);
  }

  cloneRole(id: string | number) {
    return this.exec<IGetRolePayload>(
      Axios.get(CLONE_URL, { params: { id } })
    ).then(value => this.processPayload(value));
  }

  getRole(id: string | number) {
    return this.exec<IGetRolePayload>(
      Axios.get(GET_URL, { params: { id } })
    ).then(value => this.processPayload(value));
  }

  search(page: number, pageSize: number) {
    return this.exec<ISearchResult<IRole>>(
      Axios.get(SEARCH_URL, { params: { page, pageSize } })
    ).then(value => this.processPayload(value));
  }

  createRole(options: IRole) {
    return this.exec<IRole>(Axios.post(POST_URL, options)).then(value =>
      this.processPayload(value)
    );
  }

  updateRole(options: IRole) {
    return this.exec<IRole>(Axios.put(PUT_URL, options)).then(value =>
      this.processPayload(value)
    );
  }

  updateRoleStatus(options: IRole) {
    const URL = BASE_URL + "updaterolestatus";
    return this.exec<IRole>(Axios.put(URL, options)).then(value =>
      this.processPayload(value)
    );
  }
}


text:
using System;
using System.Collections.Generic;
using System.Management.Automation;

namespace Microsoft.PowerShell.Commands
{
    /// <summary>
    /// The ConvertFrom-Json command.
    /// This command converts a Json string representation to a JsonObject.
    /// </summary>
    [Cmdlet(VerbsData.ConvertFrom, "Json", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096606", RemotingCapability = RemotingCapability.None)]
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
    public class ConvertFromJsonCommand : Cmdlet
    {
        #region parameters

        /// <summary>
        /// Gets or sets the InputString property.
        /// </summary>
        [Parameter(Mandatory = true, Position = 0, ValueFromPipeline = true)]
        [AllowEmptyString]
        public string InputObject { get; set; }

        /// <summary>
        /// InputObjectBuffer buffers all InputObject contents available in the pipeline.
        /// </summary>
        private readonly List<string> _inputObjectBuffer = new();

        /// <summary>
        /// Returned data structure is a Hashtable instead a CustomPSObject.
        /// </summary>
        [Parameter()]
        public SwitchParameter AsHashtable { get; set; }

        /// <summary>
        /// Gets or sets the maximum depth the JSON input is allowed to have. By default, it is 1024.
        /// </summary>
        [Parameter()]
        [ValidateRange(ValidateRangeKind.Positive)]
        public int Depth { get; set; } = 1024;

        /// <summary>
        /// Gets or sets the switch to prevent ConvertFrom-Json from unravelling collections during deserialization, instead passing them as a single
        /// object through the pipeline.
        /// </summary>
        [Parameter]
        public SwitchParameter NoEnumerate { get; set; }

        #endregion parameters

        #region overrides

        /// <summary>
        /// Buffers InputObjet contents available in the pipeline.
        /// </summary>
        protected override void ProcessRecord()
        {
            _inputObjectBuffer.Add(InputObject);
        }

        /// <summary>
        /// The main execution method for the ConvertFrom-Json command.
        /// </summary>
        protected override void EndProcessing()
        {
            // When Input is provided through pipeline, the input can be represented in the following two ways:
            // 1. Each input in the collection is a complete Json content. There can be multiple inputs of this format.
            // 2. The complete input is a collection which represents a single Json content. This is typically the majority of the case.
            if (_inputObjectBuffer.Count > 0)
            {
                if (_inputObjectBuffer.Count == 1)
                {
                    ConvertFromJsonHelper(_inputObjectBuffer[0]);
                }
                else
                {
                    bool successfullyConverted = false;
                    try
                    {
                        // Try to deserialize the first element.
                        successfullyConverted = ConvertFromJsonHelper(_inputObjectBuffer[0]);
                    }
                    catch (ArgumentException)
                    {
                        // The first input string does not represent a complete Json Syntax.
                        // Hence consider the entire input as a single Json content.
                    }

                    if (successfullyConverted)
                    {
                        for (int index = 1; index < _inputObjectBuffer.Count; index++)
                        {
                            ConvertFromJsonHelper(_inputObjectBuffer[index]);
                        }
                    }
                    else
                    {
                        // Process the entire input as a single Json content.
                        ConvertFromJsonHelper(string.Join(System.Environment.NewLine, _inputObjectBuffer.ToArray()));
                    }
                }
            }
        }

        /// <summary>
        /// ConvertFromJsonHelper is a helper method to convert to Json input to .Net Type.
        /// </summary>
        /// <param name="input">Input string.</param>
        /// <returns>True if successfully converted, else returns false.</returns>
        private bool ConvertFromJsonHelper(string input)
        {
            ErrorRecord error = null;
            object result = JsonObject.ConvertFromJson(input, AsHashtable.IsPresent, Depth, out error);

            if (error != null)
            {
                ThrowTerminatingError(error);
            }

            WriteObject(result, !NoEnumerate.IsPresent);
            return (result != null);
        }

        #endregion overrides
    }
}


text:
"""
    prediction.factory
    ~~~~~~~~~~~~~~~~~~

    Provides the flask application
"""

from flask import Flask

try:
    from .. import config
except ValueError:
    import config

def create_app(config_mode='Production', config_file=None):
    """Flask app creator that accepts configuration modes

    Kwargs:
        config_mode (str): Configuration mode. Must be one of 'Production',
            'Development', or 'Test'. Default: 'Production'. Overridden if
            `config_file` is given.

        config_file (str): Path to a Python configuration file. Overrides
            `config_mode`.

    Returns:
        (obj): A Flask app

    Examples:
        >>> from src.factory import create_app
        >>> app = create_app(config_mode='Test')
    """
    app = Flask('prediction')

    from .views import blueprint

    app.register_blueprint(blueprint)

    if config_file:
        app.config.from_pyfile(config_file)
    elif config_mode:
        try:
            app.config.from_object(getattr(config, config_mode))
        except AttributeError:
            pass
    else:
        app.config.from_envvar('APP_SETTINGS', silent=True)

    return app

app = create_app()


text:
<footer class="tc pa4 mv0">
  <a href="{{site.repo}}" title="MacStadium GitHub" target="_blank" class="no-underline underline-hover black-70">
    {{site.org}}{{site.title | prepend: "/" }}
  </a>
</footer>


text:
package org.sagebionetworks.evaluation.dao;

import static org.sagebionetworks.repo.model.jdo.AuthorizationSqlUtil.ACCESS_TYPE_BIND_VAR;
import static org.sagebionetworks.repo.model.jdo.AuthorizationSqlUtil.AUTHORIZATION_SQL_JOIN;
import static org.sagebionetworks.repo.model.jdo.AuthorizationSqlUtil.AUTHORIZATION_SQL_TABLES;
import static org.sagebionetworks.repo.model.jdo.AuthorizationSqlUtil.BIND_VAR_PREFIX;
import static org.sagebionetworks.repo.model.jdo.AuthorizationSqlUtil.RESOURCE_TYPE_BIND_VAR;
import static org.sagebionetworks.repo.model.query.SQLConstants.COL_EVALUATION_END_TIMESTAMP;
import static org.sagebionetworks.repo.model.query.SQLConstants.COL_EVALUATION_ETAG;
import static org.sagebionetworks.repo.model.query.SQLConstants.COL_EVALUATION_ID;
import static org.sagebionetworks.repo.model.query.SQLConstants.COL_EVALUATION_NAME;
import static org.sagebionetworks.repo.model.query.SQLConstants.COL_EVALUATION_START_TIMESTAMP;
import static org.sagebionetworks.repo.model.query.SQLConstants.LIMIT_PARAM_NAME;
import static org.sagebionetworks.repo.model.query.SQLConstants.OFFSET_PARAM_NAME;
import static org.sagebionetworks.repo.model.query.SQLConstants.TABLE_EVALUATION;
import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.COL_ACL_ID;
import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.COL_ACL_OWNER_ID;
import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.COL_ACL_OWNER_TYPE;
import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.COL_RESOURCE_ACCESS_GROUP_ID;
import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.COL_RESOURCE_ACCESS_OWNER;
import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.COL_RESOURCE_ACCESS_TYPE_ELEMENT;

import java.sql.ResultSet;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.UUID;

import org.sagebionetworks.evaluation.dbo.DBOConstants;
import org.sagebionetworks.evaluation.dbo.EvaluationDBO;
import org.sagebionetworks.evaluation.dbo.EvaluationDBOUtil;
import org.sagebionetworks.evaluation.model.Evaluation;
import org.sagebionetworks.evaluation.util.EvaluationUtils;
import org.sagebionetworks.repo.model.ConflictingUpdateException;
import org.sagebionetworks.repo.model.DatastoreException;
import org.sagebionetworks.repo.model.InvalidModelException;
import org.sagebionetworks.repo.model.NameConflictException;
import org.sagebionetworks.repo.model.ObjectType;
import org.sagebionetworks.repo.model.dbo.DBOBasicDao;
import org.sagebionetworks.repo.model.message.ChangeType;
import org.sagebionetworks.repo.model.query.SQLConstants;
import org.sagebionetworks.repo.transactions.WriteTransaction;
import org.sagebionetworks.repo.web.NotFoundException;
import org.sagebionetworks.util.ValidateArgument;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;

public class EvaluationDAOImpl implements EvaluationDAO {

	@Autowired
	private DBOBasicDao basicDao;

	@Autowired
	private JdbcTemplate jdbcTemplate;

	@Autowired
	private NamedParameterJdbcTemplate namedJdbcTemplate;

	private static final String ID = DBOConstants.PARAM_EVALUATION_ID;
	private static final String NAME = DBOConstants.PARAM_EVALUATION_NAME;
	private static final String CONTENT_SOURCE = DBOConstants.PARAM_EVALUATION_CONTENT_SOURCE;

	private static final String SELECT_AVAILABLE_EVALUATIONS_PAGINATED_PREFIX =
			"SELECT DISTINCT e.* FROM " + AUTHORIZATION_SQL_TABLES+", "+TABLE_EVALUATION+" e ";

	private static final String AUTHORIZATION_SQL_WHERE_1 =
			"where (ra."+COL_RESOURCE_ACCESS_GROUP_ID+
			" in (";

	private static final String AUTHORIZATION_SQL_WHERE_2 =
			")) AND "+AUTHORIZATION_SQL_JOIN+
		    " and acl."+COL_ACL_OWNER_TYPE+"=:"+RESOURCE_TYPE_BIND_VAR+
			" and at."+COL_RESOURCE_ACCESS_TYPE_ELEMENT+"=:"+ACCESS_TYPE_BIND_VAR;

	private static final String SELECT_AVAILABLE_EVALUATIONS_PAGINATED_SUFFIX =
			" and e."+COL_EVALUATION_ID+"=acl."+COL_ACL_OWNER_ID+
			" and acl."+COL_ACL_OWNER_TYPE+"='"+ObjectType.EVALUATION.name()+
			"' and acl."+COL_ACL_ID+"=ra."+COL_RESOURCE_ACCESS_OWNER+
			" ORDER BY e."+COL_EVALUATION_NAME+" LIMIT :"+LIMIT_PARAM_NAME+" OFFSET :"+OFFSET_PARAM_NAME;

	private static final String SELECT_AVAILABLE_EVALUATIONS_FILTER =
			" and e."+COL_EVALUATION_ID+" in (:"+COL_EVALUATION_ID+")";

	private static final String SELECT_AVAILABLE_CONTENT_SOURCE_FILTER =
			" and "+SQLConstants.COL_EVALUATION_CONTENT_SOURCE+"=:"+CONTENT_SOURCE;

	private static final String CURRENT_TIME_PARAM_NAME = "currentTime";

	private static final String SELECT_TIME_RANGE_FILTER =
			" and ("+COL_EVALUATION_START_TIMESTAMP+" IS NULL OR :"+CURRENT_TIME_PARAM_NAME+">="+COL_EVALUATION_START_TIMESTAMP+
			") and ("+COL_EVALUATION_END_TIMESTAMP+" IS NULL OR :"+CURRENT_TIME_PARAM_NAME+"<"+COL_EVALUATION_END_TIMESTAMP+")";

	private static final String SELECT_BY_NAME_SQL =
			"SELECT ID FROM "+ TABLE_EVALUATION +
			" WHERE "+ COL_EVALUATION_NAME + "=:" + NAME;

	private static final String SQL_ETAG_WITHOUT_LOCK = "SELECT " + COL_EVALUATION_ETAG + " FROM " +
														TABLE_EVALUATION +" WHERE ID = ?";

	private static final String SQL_ETAG_FOR_UPDATE = SQL_ETAG_WITHOUT_LOCK + " FOR UPDATE";

	private static final String SQL_SELECT_AVAILABLE = "SELECT " + COL_EVALUATION_ID
			+ " FROM " + TABLE_EVALUATION + " WHERE " + COL_EVALUATION_ID + " IN (:" + ID + ")";

	private static final RowMapper<EvaluationDBO> rowMapper = ((new EvaluationDBO()).getTableMapping());

	private static final String EVALUATION_NOT_FOUND = "Evaluation could not be found with id :";

	@Override
	@WriteTransaction
	public String create(Evaluation dto, Long ownerId) throws DatastoreException {
		EvaluationUtils.ensureNotNull(dto, "Evaluation object");
		EvaluationUtils.ensureNotNull(ownerId, "Owner ID");
		EvaluationUtils.ensureNotNull(dto.getId(), "Evaluation ID");

		// convert to DBO
		EvaluationDBO dbo = new EvaluationDBO();

		// set Owner ID
		dto.setOwnerId(ownerId.toString());

		// Generate a new eTag and CREATE message
		dto.setEtag(UUID.randomUUID().toString());

		// serialize
		EvaluationDBOUtil.copyDtoToDbo(dto, dbo);

		// create DBO
		try {
			dbo = basicDao.createNew(dbo);
			return dbo.getId().toString();
		} catch (Exception e) {
			String message = e.getMessage() + " id=" + dbo.getId() + " name=" + dto.getName();

			// check if a name conflict occurred
			if (e.getClass() == IllegalArgumentException.class) {
				IllegalArgumentException e2 = (IllegalArgumentException) e;
				if (e2.getCause().getClass() == DuplicateKeyException.class)
					message = "An Evaluation already exists with the name '" +
							dto.getName() + "'";
				throw new NameConflictException(message, e);
			}

			throw new DatastoreException(message, e);
		}
	}

	@Override
	public Evaluation get(String id) throws DatastoreException, NotFoundException {
		MapSqlParameterSource param = new MapSqlParameterSource();
		param.addValue(ID, id);
		try {
			EvaluationDBO dbo = basicDao.getObjectByPrimaryKey(EvaluationDBO.class, param);
			Evaluation dto = new Evaluation();
			EvaluationDBOUtil.copyDboToDto(dbo, dto);
			return dto;
		} catch (NotFoundException e) {
			throw new NotFoundException(EVALUATION_NOT_FOUND + id);
		}
	}

	private static final String AUTHORIZATION_SQL_WHERE =
			AUTHORIZATION_SQL_WHERE_1+
			":"+
			BIND_VAR_PREFIX+
			AUTHORIZATION_SQL_WHERE_2;

	@Override
	public List<Evaluation> getAccessibleEvaluations(EvaluationFilter filter, long limit, long offset) throws DatastoreException, NotFoundException {
		ValidateArgument.required(filter, "filter");

		if (filter.getPrincipalIds() == null || filter.getPrincipalIds().isEmpty()) {
			return Collections.emptyList();
		}

		MapSqlParameterSource param = new MapSqlParameterSource();

		param.addValue(BIND_VAR_PREFIX, filter.getPrincipalIds());
		param.addValue(ACCESS_TYPE_BIND_VAR, filter.getAccessType().name());
		param.addValue(OFFSET_PARAM_NAME, offset);
		param.addValue(LIMIT_PARAM_NAME, limit);
		param.addValue(RESOURCE_TYPE_BIND_VAR, ObjectType.EVALUATION.name());

		StringBuilder sql = new StringBuilder(SELECT_AVAILABLE_EVALUATIONS_PAGINATED_PREFIX);
		sql.append(AUTHORIZATION_SQL_WHERE);

		if (filter.getIdsFilter() !=null && !filter.getIdsFilter().isEmpty()) {
			param.addValue(COL_EVALUATION_ID, filter.getIdsFilter());
			sql.append(SELECT_AVAILABLE_EVALUATIONS_FILTER);
		}

		if (filter.getContentSourceFilter() != null) {
			param.addValue(CONTENT_SOURCE, filter.getContentSourceFilter());
			sql.append(SELECT_AVAILABLE_CONTENT_SOURCE_FILTER);
		}

		if (filter.getTimeFilter() != null) {
			sql.append(SELECT_TIME_RANGE_FILTER);
			param.addValue(CURRENT_TIME_PARAM_NAME, filter.getTimeFilter());
		}

		sql.append(SELECT_AVAILABLE_EVALUATIONS_PAGINATED_SUFFIX);

		return namedJdbcTemplate.query(sql.toString(), param, (ResultSet rs, int rowNum) -> {
			EvaluationDBO dbo = rowMapper.mapRow(rs, rowNum);
			Evaluation dto = new Evaluation();
			EvaluationDBOUtil.copyDboToDto(dbo, dto);
			return dto;
		});
	}

	@Override
	@WriteTransaction
	public void update(Evaluation dto)
			throws DatastoreException, InvalidModelException,
			NotFoundException, ConflictingUpdateException {
		// we do this to preserve the EvaluationSubmissions etag
		MapSqlParameterSource param = new MapSqlParameterSource();
		param.addValue(ID, dto.getId());
		String newEtag = lockAndGenerateEtag(dto.getId(), dto.getEtag(), ChangeType.UPDATE);
		dto.setEtag(newEtag);

		EvaluationDBO dbo = new EvaluationDBO();
		EvaluationDBOUtil.copyDtoToDbo(dto, dbo);

		basicDao.update(dbo);
	}

	@Override
	@WriteTransaction
	public void delete(String id) throws DatastoreException {
		MapSqlParameterSource param = new MapSqlParameterSource();
		param.addValue(ID, id);
		basicDao.deleteObjectByPrimaryKey(EvaluationDBO.class, param);
	}

	@Override
	public String lookupByName(String name) throws DatastoreException {
		MapSqlParameterSource param = new MapSqlParameterSource();
		param.addValue(NAME, name);
		try {
			Long id = namedJdbcTemplate.queryForObject(SELECT_BY_NAME_SQL, param, Long.class);
			return id.toString();
		} catch (EmptyResultDataAccessException e) {
			// name is not in use
			return null;
		}
	}

	@Override
	public Set<Long> getAvailableEvaluations(List<Long> ids) {
		ValidateArgument.required(ids, "ids");

		if (ids.isEmpty()) {
			return Collections.emptySet();
		}

		MapSqlParameterSource param = new MapSqlParameterSource(ID, ids);

		Set<Long> result = new HashSet<>(ids.size());

		namedJdbcTemplate.query(SQL_SELECT_AVAILABLE, param, (ResultSet rs) -> {
			result.add(rs.getLong(COL_EVALUATION_ID));
		});

		return result;
	}

	private String lockAndGenerateEtag(String id, String eTag, ChangeType changeType)
			throws NotFoundException, ConflictingUpdateException, DatastoreException {
		String currentTag = lockForUpdate(id);
		// Check the eTags
		if(!currentTag.equals(eTag)){
			throw new ConflictingUpdateException("Evaluation: " + id + " has been updated since " +
					"you last fetched it; please retrieve it again and re-apply the update");
		}
		// Get a new e-tag
		EvaluationDBO dbo = getDBO(id);
		dbo.seteTag(UUID.randomUUID().toString());
		return dbo.getEtag();
	}

	private EvaluationDBO getDBO(String id) throws NotFoundException {
		EvaluationUtils.ensureNotNull(id, "Evaluation id");
		MapSqlParameterSource param = new MapSqlParameterSource();
		param.addValue(DBOConstants.PARAM_EVALUATION_ID, id);
		try {
			EvaluationDBO dbo = basicDao.getObjectByPrimaryKey(EvaluationDBO.class, param);
			return dbo;
		} catch (NotFoundException e) {
			throw new NotFoundException(EVALUATION_NOT_FOUND + id);
		}
	}

	private String lockForUpdate(String id) {
		// Create a Select for update query
		return jdbcTemplate.queryForObject(SQL_ETAG_FOR_UPDATE, String.class, id);
	}

}


text:
var ved = {
  version: '1.1.1',
  data: undefined,
  renderType: 'canvas',
  editor: null
};

ved.params = function() {
  var query = location.search.slice(1);
  if (query.slice(-1) === '/') query = query.slice(0,-1);
  return query
    .split('&')
    .map(function(x) { return x.split('='); })
    .reduce(function(a, b) {
      a[b[0]] = b[1]; return a;
    }, {});
};

ved.select = function(spec) {
  var desc = ved.$d3.select('.spec_desc');

  if (spec) {
    ved.editor.setValue(spec);
    ved.editor.gotoLine(0);
    desc.html('');
    ved.parse();
    return;
  }

  var sel = ved.$d3.select('.sel_spec').node(),
      idx = sel.selectedIndex;
  spec = d3.select(sel.options[idx]).datum();

  if (idx > 0) {
    d3.xhr(ved.uri(spec), function(error, response) {
      ved.editor.setValue(response.responseText);
      ved.editor.gotoLine(0);
      ved.parse(function() { desc.html(spec.desc || ''); });
    });
  } else {
    ved.editor.setValue('');
    ved.editor.gotoLine(0);
    desc.html('');
  }
};

ved.uri = function(entry) {
  return ved.path + 'spec/' + entry.name + '.json';
};

ved.renderer = function() {
  var sel = ved.$d3.select('.sel_render').node(),
      idx = sel.selectedIndex,
      ren = sel.options[idx].value;

  ved.renderType = ren;
  ved.parse();
};

ved.format = function() {
  var spec = JSON.parse(ved.editor.getValue()),
      text = JSON.stringify(spec, null, 2);
  ved.editor.setValue(text);
};

ved.parse = function(callback) {
  var opt, source;
  try {
    opt = JSON.parse(ved.editor.getValue());
  } catch (e) {
    console.log(e);
    return;
  }

  if (!opt.spec && !opt.url && !opt.source) {
    // wrap spec for handoff to vega-embed
    opt = {spec: opt};
  }
  opt.actions = false;
  opt.renderer = opt.renderer || ved.renderType;
  opt.parameter_el = '.mod_params';

  if (ved.view) ved.view.destroy();
  d3.select('.mod_params').html('');
  d3.select('.spec_desc').html('');
  vg.embed('.vis', opt, function(view, spec) {
    ved.spec = spec;
    ved.view = view;
    if (callback) callback(view);
  });
};

ved.resize = function(event) {
  ved.editor.resize();
};

ved.export = function() {
  var ext = ved.renderType === 'canvas' ? 'png' : 'svg',
      url = ved.view.toImageURL(ext);

  var el = d3.select(document.createElement('a'))
    .attr('href', url)
    .attr('target', '_blank')
    .attr('download', (ved.spec.name || 'vega') + '.' + ext)
    .node();

  var evt = document.createEvent('MouseEvents');
  evt.initMouseEvent('click', true, true, document.defaultView, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
  el.dispatchEvent(evt);
};

ved.init = function(el, dir) {
  // Set base directory
  var PATH = dir || 'app/';
  vg.config.load.baseURL = PATH;
  ved.path = PATH;

  el = (ved.$d3 = d3.select(el));

  d3.text(PATH + 'template.html', function(err, text) {
    el.html(text);

    // Specification drop-down menu
    var sel = el.select('.sel_spec');
    sel.on('change', ved.select);
    sel.append('option').text('Custom');
    sel.selectAll('optgroup')
      .data(Object.keys(SPECS))
     .enter().append('optgroup')
      .attr('label', function(key) { return key; })
     .selectAll('option.spec')
      .data(function(key) { return SPECS[key]; })
     .enter().append('option')
      .text(function(d) { return d.name; });

    // Renderer drop-down menu
    var ren = el.select('.sel_render');
    ren.on('change', ved.renderer)
    ren.selectAll('option')
      .data(['Canvas', 'SVG'])
     .enter().append('option')
      .attr('value', function(d) { return d.toLowerCase(); })
      .text(function(d) { return d; });

    // Code Editor
    var editor = ved.editor = ace.edit(ved.$d3.select('.spec').node());
    editor.getSession().setMode('ace/mode/json');
    editor.getSession().setTabSize(2);
    editor.getSession().setUseSoftTabs(true);
    editor.setShowPrintMargin(false);
    editor.on('focus', function() {
      editor.setHighlightActiveLine(true);
      d3.selectAll('.ace_gutter-active-line').style('background', '#DCDCDC');
      d3.selectAll('.ace-tm .ace_cursor').style('visibility', 'visible');
    });
    editor.on('blur', function() {
      editor.setHighlightActiveLine(false);
      d3.selectAll('.ace_gutter-active-line').style('background', 'transparent');
      d3.selectAll('.ace-tm .ace_cursor').style('visibility', 'hidden');
      editor.clearSelection();
    });
    editor.$blockScrolling = Infinity;

    // Initialize application
    el.select('.btn_spec_format').on('click', ved.format);
    el.select('.btn_spec_parse').on('click', ved.parse);
    el.select('.btn_export').on('click', ved.export);
    d3.select(window).on('resize', ved.resize);
    ved.resize();

    ved.specs = Object.keys(SPECS).reduce(function(a, k) {
      return a.concat(SPECS[k].map(function(d) { return d.name; }));
    }, []);

    // Handle application parameters
    var p = ved.params();
    if (p.renderer) {
      ren.node().selectedIndex = p.renderer.toLowerCase() === 'svg' ? 1 : 0;
      ved.renderType = p.renderer;
    }
    if (p.spec) {
      var spec = decodeURIComponent(p.spec),
          idx = ved.specs.indexOf(spec) + 1;

      if (idx > 0) {
        sel.node().selectedIndex = idx;
        ved.select();
      } else {
        try {
          var json = JSON.parse(spec);
          ved.select(spec);
        } catch (err) {
          console.error(err);
          console.error('Specification loading failed: ' + spec);
        }
      }
    }

    // Handle post messages
    window.addEventListener('message', function(evt) {
      var data = evt.data;
      console.log('[Vega-Editor] Received Message', evt.origin, data);

      // send acknowledgement
      if (data.spec || data.file) {
        evt.source.postMessage(true, '*');
      }

      // load spec
      if (data.spec) {
        ved.select(data.spec);
      } else if (data.file) {
        sel.node().selectedIndex = ved.specs.indexOf(data.file) + 1;
        ved.select();
      }
    }, false);
  });
};


text:
copy into t from @stage/;
copy into @stage/ from t;
comment on table t is 's';
commit ;
execute immediate 'select 1';
execute task tsk;
explain select 1 as c;
get @stage/ file://;
grant ownership on table t to role r;
grant all on account to role r;
grant usage on database d to share s;
grant role r to role r2;
list @stage/;
put file:// @stage/;
remove @stage/;
revoke usage on database d from role r1;
revoke usage on database d from share sh;
revoke role r from role t1;
rollback ;
set i=1;
truncate materialized view v;
truncate table t;
unset i;
unset (i,j,k);