text:
<!DOCTYPE HTML>

<title>org.apache.sysds.runtime.instructions.spark.functions Class Hierarchy (Apache SystemDS 2.3.0-SNAPSHOT API)</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style">
<link rel="stylesheet" type="text/css" href="../../../../../../../jquery/jquery-ui.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

All Classes

SEARCH:
<input type="text" id="search" value="search" disabled="disabled">
<input type="reset" id="reset" value="reset" disabled="disabled">

JavaScript is disabled on your browser.

Hierarchy For Package org.apache.sysds.runtime.instructions.spark.functions

Package Hierarchies:

All Packages

Class Hierarchy

java.lang.Object

org.apache.sysds.runtime.instructions.spark.functions.AggregateDropCorrectionFunction (implements org.apache.spark.api.java.function.Function<T1,R>)

org.apache.sysds.runtime.instructions.spark.functions.ComputeBinaryBlockNnzFunction (implements org.apache.spark.api.java.function.Function<T1,R>)

org.apache.sysds.runtime.instructions.spark.functions.ConvertFrameBlockToIJVLines (implements org.apache.spark.api.java.function.FlatMapFunction<T,R>)

org.apache.sysds.runtime.instructions.spark.functions.ConvertMatrixBlockToIJVLines (implements org.apache.spark.api.java.function.FlatMapFunction<T,R>)

org.apache.sysds.runtime.instructions.spark.functions.ConvertStringToLongTextPair (implements org.apache.spark.api.java.function.PairFunction<T,K,V>)

org.apache.sysds.runtime.instructions.spark.functions.CopyBinaryCellFunction (implements org.apache.spark.api.java.function.PairFunction<T,K,V>)

org.apache.sysds.runtime.instructions.spark.functions.CopyFrameBlockFunction (implements org.apache.spark.api.java.function.Function<T1,R>)

org.apache.sysds.runtime.instructions.spark.functions.CopyFrameBlockPairFunction (implements org.apache.spark.api.java.function.PairFunction<T,K,V>)

org.apache.sysds.runtime.instructions.spark.functions.CopyMatrixBlockFunction (implements org.apache.spark.api.java.function.Function<T1,R>)

org.apache.sysds.runtime.instructions.spark.functions.CopyMatrixBlockPairFunction (implements org.apache.spark.api.java.function.PairFlatMapFunction<T,K,V>)

org.apache.sysds.runtime.instructions.spark.functions.CopyTensorBlockFunction (implements org.apache.spark.api.java.function.Function<T1,R>)

org.apache.sysds.runtime.instructions.spark.functions.CopyTensorBlockPairFunction (implements org.apache.spark.api.java.function.PairFlatMapFunction<T,K,V>)

org.apache.sysds.runtime.instructions.spark.functions.CopyTextInputFunction (implements org.apache.spark.api.java.function.PairFunction<T,K,V>)

org.apache.sysds.runtime.instructions.spark.functions.CreateSparseBlockFunction (implements org.apache.spark.api.java.function.Function<T1,R>)

org.apache.sysds.runtime.instructions.spark.functions.ExtractBlockForBinaryReblock (implements org.apache.spark.api.java.function.PairFlatMapFunction<T,K,V>)

org.apache.sysds.runtime.instructions.spark.functions.ExtractGroup (implements java.io.Serializable)

org.apache.sysds.runtime.instructions.spark.functions.ExtractGroup.ExtractGroupBroadcast (implements org.apache.spark.api.java.function.PairFlatMapFunction<T,K,V>)

org.apache.sysds.runtime.instructions.spark.functions.ExtractGroup.ExtractGroupJoin (implements org.apache.spark.api.java.function.PairFlatMapFunction<T,K,V>)

org.apache.sysds.runtime.instructions.spark.functions.ExtractGroupNWeights (implements org.apache.spark.api.java.function.PairFlatMapFunction<T,K,V>)

org.apache.sysds.runtime.instructions.spark.functions.FilterDiagMatrixBlocksFunction (implements org.apache.spark.api.java.function.Function<T1,R>)

org.apache.sysds.runtime.instructions.spark.functions.FilterNonEmptyBlocksFunction (implements org.apache.spark.api.java.function.Function<T1,R>)

org.apache.sysds.runtime.instructions.spark.functions.FilterNonEmptyBlocksFunction2 (implements org.apache.spark.api.java.function.Function<T1,R>)

org.apache.sysds.runtime.instructions.spark.functions.GetMIMBFromRow (implements org.apache.spark.api.java.function.PairFunction<T,K,V>)

org.apache.sysds.runtime.instructions.spark.functions.IsBlockInList (implements org.apache.spark.api.java.function.Function<T1,R>)

org.apache.sysds.runtime.instructions.spark.functions.IsBlockInRange (implements org.apache.spark.api.java.function.Function<T1,R>)

org.apache.sysds.runtime.instructions.spark.functions.IsFrameBlockInRange (implements org.apache.spark.api.java.function.Function<T1,R>)

org.apache.sysds.runtime.instructions.spark.functions.MapInputSignature (implements org.apache.spark.api.java.function.Function<T1,R>)

org.apache.sysds.runtime.instructions.spark.functions.MapJoinSignature (implements org.apache.spark.api.java.function.Function<T1,R>)

org.apache.sysds.runtime.instructions.spark.functions.MatrixMatrixBinaryOpFunction (implements org.apache.spark.api.java.function.Function<T1,R>)

org.apache.sysds.runtime.instructions.spark.functions.MatrixScalarUnaryFunction (implements org.apache.spark.api.java.function.Function<T1,R>)

org.apache.sysds.runtime.instructions.spark.functions.MatrixVectorBinaryOpPartitionFunction (implements org.apache.spark.api.java.function.PairFlatMapFunction<T,K,V>)

org.apache.sysds.runtime.instructions.spark.functions.OuterVectorBinaryOpFunction (implements org.apache.spark.api.java.function.PairFlatMapFunction<T,K,V>)

org.apache.sysds.runtime.instructions.spark.functions.PerformGroupByAggInCombiner (implements org.apache.spark.api.java.function.Function2<T1,T2,R>)

org.apache.sysds.runtime.instructions.spark.functions.PerformGroupByAggInReducer (implements org.apache.spark.api.java.function.Function<T1,R>)

org.apache.sysds.runtime.instructions.spark.functions.ReblockTensorFunction (implements org.apache.spark.api.java.function.PairFlatMapFunction<T,K,V>)

org.apache.sysds.runtime.instructions.spark.functions.RecomputeNnzFunction (implements org.apache.spark.api.java.function.FlatMapFunction<T,R>)

org.apache.sysds.runtime.instructions.spark.functions.ReorgMapFunction (implements org.apache.spark.api.java.function.PairFunction<T,K,V>)

org.apache.sysds.runtime.instructions.spark.functions.ReplicateBlockFunction (implements org.apache.spark.api.java.function.PairFlatMapFunction<T,K,V>)

org.apache.sysds.runtime.instructions.spark.functions.ReplicateTensorFunction (implements org.apache.spark.api.java.function.PairFlatMapFunction<T,K,V>)

org.apache.sysds.runtime.instructions.spark.functions.ReplicateVectorFunction (implements org.apache.spark.api.java.function.PairFlatMapFunction<T,K,V>)

org.apache.sysds.runtime.instructions.spark.functions.TensorTensorBinaryOpFunction (implements org.apache.spark.api.java.function.Function<T1,R>)

org.apache.sysds.runtime.instructions.spark.functions.TensorTensorBinaryOpPartitionFunction (implements org.apache.spark.api.java.function.PairFlatMapFunction<T,K,V>)

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

All Classes

JavaScript is disabled on your browser.

Copyright © 2021 The Apache Software Foundation. All rights reserved.


text:
using System;
using System.Collections.Generic;
using Azure.Core;

namespace Azure.ResourceManager.Cdn.Models
{
    /// <summary> Defines a managed rule group override setting. </summary>
    public partial class ManagedRuleGroupOverrideSetting
    {
        /// <summary> Initializes a new instance of ManagedRuleGroupOverrideSetting. </summary>
        /// <param name="ruleGroupName"> Describes the managed rule group within the rule set to override. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="ruleGroupName"/> is null. </exception>
        public ManagedRuleGroupOverrideSetting(string ruleGroupName)
        {
            Argument.AssertNotNull(ruleGroupName, nameof(ruleGroupName));

            RuleGroupName = ruleGroupName;
            Rules = new ChangeTrackingList<ManagedRuleOverrideSetting>();
        }

        /// <summary> Initializes a new instance of ManagedRuleGroupOverrideSetting. </summary>
        /// <param name="ruleGroupName"> Describes the managed rule group within the rule set to override. </param>
        /// <param name="rules"> List of rules that will be disabled. If none specified, all rules in the group will be disabled. </param>
        internal ManagedRuleGroupOverrideSetting(string ruleGroupName, IList<ManagedRuleOverrideSetting> rules)
        {
            RuleGroupName = ruleGroupName;
            Rules = rules;
        }

        /// <summary> Describes the managed rule group within the rule set to override. </summary>
        public string RuleGroupName { get; set; }
        /// <summary> List of rules that will be disabled. If none specified, all rules in the group will be disabled. </summary>
        public IList<ManagedRuleOverrideSetting> Rules { get; }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package epic.trees

import java.io.ObjectStreamException

/**
 * Class that turns BinarizedTrees into normal trees. Should
 * replace unary chains in addition to removing intermediates.
 *
 * @author dlwh
 **/
trait Debinarizer[L] extends (BinarizedTree[L] => Tree[L]) with Serializable

object Debinarizer {
  @SerialVersionUID(1L)
  implicit object AnnotatedLabelDebinarizer extends Debinarizer[AnnotatedLabel] {

    def apply(t: BinarizedTree[AnnotatedLabel]): Tree[AnnotatedLabel] = {
      Trees.debinarize(replaceUnaries(t), {(_: AnnotatedLabel).isIntermediate}).map(_.baseAnnotatedLabel)
    }

    def replaceUnaries(t: Tree[AnnotatedLabel]): Tree[AnnotatedLabel] = t match {
      case UnaryTree(a, child, chain, span) if a.label == child.label.label && chain.isEmpty =>
        replaceUnaries(child)
      case UnaryTree(a, child, chain, span) =>
        val deunaried = replaceUnaries(child).asInstanceOf[BinarizedTree[AnnotatedLabel]]
        val withChain = chain.foldRight(deunaried){ (label, child) =>
          UnaryTree(AnnotatedLabel(label), child, IndexedSeq.empty, span)
        }
        UnaryTree(a,withChain, IndexedSeq.empty, t.span)
      case t@BinaryTree(a, lchild, rchild, span) =>
        BinaryTree(a,
          replaceUnaries(lchild).asInstanceOf[BinarizedTree[AnnotatedLabel]],
          replaceUnaries(rchild).asInstanceOf[BinarizedTree[AnnotatedLabel]], t.span)
      case _ => t
    }

  }

  @SerialVersionUID(1L)
  implicit object StringDebinarizer extends Debinarizer[String] {

    def apply(t: BinarizedTree[String]): Tree[String] = {
      Trees.debinarize(Trees.deannotate(replaceUnaries(t)))
    }

    def replaceUnaries(t: Tree[String]): Tree[String] = t match {
      case UnaryTree(a, child, chain, span) if a == child.label && chain.isEmpty =>
        replaceUnaries(child)
      case UnaryTree(a, child, chain, span) =>
        val deunaried = replaceUnaries(child).asInstanceOf[BinarizedTree[String]]
        val withChain = chain.foldRight(deunaried){ (label, child) =>
          UnaryTree(label, child, IndexedSeq.empty, span)
        }
        UnaryTree(a,withChain, IndexedSeq.empty, t.span)
      case t@BinaryTree(a, lchild, rchild, span) =>
        BinaryTree(a,
          replaceUnaries(lchild).asInstanceOf[BinarizedTree[String]],
          replaceUnaries(rchild).asInstanceOf[BinarizedTree[String]], t.span)
      case _ => t
    }
  }

}


text:
package com.xinyiglass.springSample.service;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import xygdev.commons.page.PagePub;
import xygdev.commons.sqlStmt.SqlStmtPub;

@Service
@Transactional(rollbackFor=Exception.class)//指定checked的异常Exception也要回滚!
public class LgInvService {

	@Autowired
	PagePub pagePub;

	@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
	public String findForPage(int pageSize,int pageNo,boolean goLastPage,Map<String,Object> conditionMap,Long loginId) throws Exception{
		Map<String,Object> paramMap=new HashMap<String,Object>();
		StringBuffer sqlBuf=new StringBuffer();
		sqlBuf.append("SELECT * FROM XYG_ALB2B_LG_ONHAND_V WHERE 1=1");
		sqlBuf.append(SqlStmtPub.getAndStmt("ORGANIZATION_ID",conditionMap.get("organizationId"),paramMap));
		sqlBuf.append(SqlStmtPub.getAndStmt("WIDTH",conditionMap.get("width"),paramMap));
		sqlBuf.append(SqlStmtPub.getAndStmt("HEIGHT",conditionMap.get("height"),paramMap));
		sqlBuf.append(SqlStmtPub.getAndStmt("THICKNESS",conditionMap.get("thickness"),paramMap));
		sqlBuf.append(SqlStmtPub.getAndStmt("COATING_TYPE",conditionMap.get("coatingType"),paramMap));
		sqlBuf.append(" ORDER BY "+conditionMap.get("orderBy"));
		return pagePub.qPageForJson(sqlBuf.toString(), paramMap, pageSize, pageNo, goLastPage);
	}
}


text:
using System.IO;

namespace DeveImageOptimizer.Helpers
{
    public static class RandomFileNameHelper
    {
        public static string RandomizeFileName(string fileName, string? desiredExtension = null)
        {
            var nameWithoutExtension = Path.GetFileNameWithoutExtension(fileName);
            if (desiredExtension == null)
            {
                desiredExtension = Path.GetExtension(fileName);
            }
            var newFileName = $"{nameWithoutExtension}_{Path.ChangeExtension(Path.GetRandomFileName(), desiredExtension)}";
            return newFileName;
        }

        public static string RandomFileNameShort(string prefix, string desiredExtension)
        {
            return $"{prefix}_{Path.ChangeExtension(Path.GetRandomFileName(), desiredExtension)}";
        }
    }
}


text:
require 'version'
require 'has_numerous'
require 'preference'


text:
:mod:`windows.com` - Component Object Model
""""""""""""""""""""""""""""""""""""""""""""

.. module:: windows.com

A module to call `COM` interfaces from `Python` or
`COM` vtable in python.

This code is only used in :mod:`windows.winobject.wmi` and :mod:`windows.winobject.network` for the firewall.
The ability to create `COM` vtable is used in the `LKD project <https://github.com/sogeti-esec-lab/LKD/>`_ .

Using a COM interface
'''''''''''''''''''''

It's possible to directly call `COM` interface from python. All you need is the definition of the `COM` interface.

There are three ways to get the definition of the code interface:

    * By using it from :mod:`windows.generated_def.interfaces`
    * By writing it yourself : <https://github.com/sogeti-esec-lab/LKD/blob/ba40727d7d257b00f89fc6ca7296c9833b7b75b2/dbginterface/remote.py#L56>`_
    * By generating it.

To generate a `COM` interface you need its definition from the ".c" file.
Then add thisit to ``PythonForWindows\ctypes_generation\com\MyInterface.txt``.
Finally re-generate the interface using ``generate.py``.

When you have the `COM` interface defintion you can create an instance of it.
Then you need to retrieve the interface by using an API returning an object or :func:`window.com.create_instance`.
You can then use the instance to call whatever method you need.

.. note::

    see samples :ref:`sample_com`

Implementing a COM interface
''''''''''''''''''''''''''''

To create `COM` object you need to:

    1. Create your ``COMImplementation`` with an ``IMPLEMENT`` attribute  that should be a cominterface `CODE 1 <https://github.com/sogeti-esec-lab/LKD/blob/efabf3cc38b94d4180ebe8d2c554da5d76b2fea1/lkd/dbginterface/base.py#L48>`_
    2. Implements the methods of the interface `CODE 2 <https://github.com/sogeti-esec-lab/LKD/blob/efabf3cc38b94d4180ebe8d2c554da5d76b2fea1/lkd/dbginterface/base.py#L55>`_
    3. Create an instance `CODE3 <https://github.com/sogeti-esec-lab/LKD/blob/efabf3cc38b94d4180ebe8d2c554da5d76b2fea1/lkd/dbginterface/base.py#L59>`_
    4. Pass it to whatever native function expects it `CODE4 <https://github.com/sogeti-esec-lab/LKD/blob/efabf3cc38b94d4180ebe8d2c554da5d76b2fea1/lkd/dbginterface/base.py#L272>`_

.. note::

    see samples :ref:`sample_com_icallinterceptor`

API
'''

.. autofunction:: init
.. autofunction:: create_instance
.. autoclass:: COMImplementation


text:
<?php

namespace Phexcore\Plugin\Phextemplate;

class Core
{
    /**
     * プラグイン名
     *
     * @var string
     */
    const PLUGIN_NAME = 'phextemplate';

    /**
     * パラメータ
     *
     * @var array
     */
    protected $parameters = array();

    /**
     * PHP関数有効化フラグ
     *
     * @var boolean
     */
    protected $enablePhpFunctionsFlag = true;

    /**
     * 有効化する関数名
     *
     * @var null|string|array
     */
    protected $restrict = null;

    /**
     * xmlns:php属性除去フラグ
     *
     * @var boolean
     */
    protected $enableDeleteXmlnsPhpAttributeFlag = true;

    /**
     * コンストラクタ
     *
     * @param array $configs
     */
    public function __construct(array $configs = null)
    {
        if (null !== $configs) {
            $this->initConfig($configs);
        }
    }

    /**
     * 設定を初期化する
     *
     * @param array $configs
     */
    public function initConfig(array $configs)
    {
        foreach ($configs as $key => $value) {
            switch ($key) {
                case 'parameters':
                    $this->setParameters($value);
                    break;
                case 'enablePhpFunctionsFlag':
                    $this->setEnablePhpFunctionsFlag($value);
                    break;
                case 'restrict':
                    $this->setRestrict($value);
                    break;
                case 'enableDeleteXmlnsPhpAttributeFlag':
                    $this->setEnableDeleteXmlnsPhpAttributeFlag($value);
                    break;
            }
        }
    }

    /**
     * パラメータを設定する
     *
     * @param array $parameters
     */
    public function setParameters(array $parameters)
    {
        $this->parameters = $parameters;
    }

    /**
     * パラメータを取得する
     *
     * @return array
     */
    public function getParameters()
    {
        return $this->parameters;
    }

    /**
     * PHP関数有効化フラグを設定する
     *
     * @param boolean $enablePhpFunctionsFlag
     */
    public function setEnablePhpFunctionsFlag($enablePhpFunctionsFlag)
    {
        $this->enablePhpFunctionsFlag = (boolean) $enablePhpFunctionsFlag;
    }

    /**
     * PHP関数を有効化するか判定する
     *
     * @return boolean
     */
    public function isEnablePhpFunctions()
    {
        return $this->enablePhpFunctionsFlag;
    }

    /**
     * 有効化するPHP関数名を設定する
     *
     * @param null|string|array $restrict
     */
    public function setRestrict($restrict)
    {
        $this->restrict = $restrict;
    }

    /**
     * 有効化するPHP関数名を取得する
     *
     * @return null|string|array
     */
    public function getRestrict()
    {
        return $this->restrict;
    }

    /**
     * xmlns:php属性除去フラグを設定する
     *
     * @param string $enableDeleteXmlnsPhpAttributeFlag
     */
    public function setEnableDeleteXmlnsPhpAttributeFlag($enableDeleteXmlnsPhpAttributeFlag)
    {
        $this->enableDeleteXmlnsPhpAttributeFlag = (boolean) $enableDeleteXmlnsPhpAttributeFlag;
    }

    /**
     * xmlns:php属性を除去するか判定する
     *
     * @return boolean
     */
    public function isEnableDeleteXmlnsPhpAttribute()
    {
        return $this->enableDeleteXmlnsPhpAttributeFlag;
    }

    /**
     * xmlns:php属性を除去する
     *
     * @param string $htmlString
     * @return string
     */
    public function deleteXmlnsPhpAttribute($htmlString)
    {
        return preg_replace('/ ?xmlns\:php\=\"[^\"]+\"/', '', $htmlString, 1);
    }
}


text:
class MoneyNavigator::Rules::MentalHealth
  include MoneyNavigator::Constants

  def self.all
    {
      # 'Money worries and mental health' section
      section_code: 'S11',
      heading_rules: [
        {
          # ' If money worries are affecting your mental health ' Rules
          heading_code: 'H1',
          content_rules: [
            # Q14A1 or Q14A2
            {
              triggers: [
                { q14: %w[a1 a3] }
              ],
              mask: [MASK_SOME, MASK_ALL],
              article: 'coronavirus-mental-health'
            }
          ]
        }

      ]
    }
  end
end


text:
<?php

namespace Stat\EnseignantBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * MdlCourseCompletionNotify
 *
 * @ORM\Table(name="mdl_course_completion_notify", indexes={@ORM\Index(name="mdl_courcompnoti_cou_ix", columns={"course"})})
 * @ORM\Entity
 */
class MdlCourseCompletionNotify
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="bigint", nullable=false)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private $id;

    /**
     * @var integer
     *
     * @ORM\Column(name="course", type="bigint", nullable=false)
     */
    private $course = '0';

    /**
     * @var integer
     *
     * @ORM\Column(name="role", type="bigint", nullable=false)
     */
    private $role = '0';

    /**
     * @var string
     *
     * @ORM\Column(name="message", type="text", nullable=false)
     */
    private $message;

    /**
     * @var integer
     *
     * @ORM\Column(name="timesent", type="bigint", nullable=false)
     */
    private $timesent = '0';

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set course
     *
     * @param integer $course
     * @return MdlCourseCompletionNotify
     */
    public function setCourse($course)
    {
        $this->course = $course;

        return $this;
    }

    /**
     * Get course
     *
     * @return integer
     */
    public function getCourse()
    {
        return $this->course;
    }

    /**
     * Set role
     *
     * @param integer $role
     * @return MdlCourseCompletionNotify
     */
    public function setRole($role)
    {
        $this->role = $role;

        return $this;
    }

    /**
     * Get role
     *
     * @return integer
     */
    public function getRole()
    {
        return $this->role;
    }

    /**
     * Set message
     *
     * @param string $message
     * @return MdlCourseCompletionNotify
     */
    public function setMessage($message)
    {
        $this->message = $message;

        return $this;
    }

    /**
     * Get message
     *
     * @return string
     */
    public function getMessage()
    {
        return $this->message;
    }

    /**
     * Set timesent
     *
     * @param integer $timesent
     * @return MdlCourseCompletionNotify
     */
    public function setTimesent($timesent)
    {
        $this->timesent = $timesent;

        return $this;
    }

    /**
     * Get timesent
     *
     * @return integer
     */
    public function getTimesent()
    {
        return $this->timesent;
    }
}


text:
package org.wso2.carbon.governance.lcm.tasks;

import org.apache.axiom.om.OMElement;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.governance.api.exception.GovernanceException;
import org.wso2.carbon.governance.lcm.tasks.events.LifecycleNotificationEvent;
import org.wso2.carbon.governance.lcm.util.CommonUtil;
import org.wso2.carbon.governance.lcm.util.LifecycleStateDurationUtils;
import org.wso2.carbon.governance.registry.extensions.aspects.utils.LifecycleConstants;
import org.wso2.carbon.registry.common.AttributeSearchService;
import org.wso2.carbon.registry.common.ResourceData;
import org.wso2.carbon.registry.common.eventing.NotificationService;
import org.wso2.carbon.registry.core.ResourceImpl;
import org.wso2.carbon.registry.core.exceptions.RegistryException;
import org.wso2.carbon.registry.eventing.services.EventingServiceImpl;
import org.wso2.carbon.registry.indexing.IndexingConstants;

import javax.xml.namespace.QName;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;

/**
 * This Util class holds methods to send checkpoint notifications and add schedulers.
 */
public class LCNotificationScheduler {

    private static final Log log = LogFactory.getLog(LCNotificationScheduler.class);

    // Duration of a day 1 * 24 * 60 * 60 * 1000.
    private final long durationOfADay = 86400000;

    // Used to as Qname for checkpoint id.
    private final String checkpointId = "id";

    // Date separator.
    private final String dateSeparator = "-";

    // Date length.
    private final int dateLength = 10;

    // Date format used in MySQL queries.
    private final String dateFormat = "yyyy-M-d";

    // Lifecycle property name to which is used to store.
    private final String lcCheckPointPropertyName = "registry.LCCheckpoints";

    // Super admin username.
    private final String superAdminUsername = "admin";

    // Super tenant domain.
    private final String superTenantDomain = "carbon.super";

    // Super tenant tenant Id.
    private final int superTenantId = -1234;

    // Equals constant used for solar advance search.
    private final String equals = "eq";

    // Not applicable constant used for solar advance search.
    private final String notApplicable = "na";

    /**
     * This method is used to send notifications for checkpoints in lifecycle. This method is called using the
     * scheduler task CheckpointNotificationSchedulerTask.
     */
    public void run() {
        try {
            ArrayList<LCNotification> notifications = getValidNotifications();

            // Send notifications if exists.
            if (notifications.size() > 0) {
                // Parse this for a another method.
                for (LCNotification schedulerBean : notifications) {
                    // Creating a Checkpoint notification event.
                    String notificationMessage = getNotificationMessage(schedulerBean);
                    LifecycleNotificationEvent<String> notificationEvent
                            = new LifecycleNotificationEvent<>(notificationMessage);
                    notificationEvent.setTenantId(superTenantId);
                    notificationEvent.setResourcePath(schedulerBean.getRegPath());
                    // Sending notification using notification service.
                    NotificationService notificationService = new EventingServiceImpl();
                    try {
                        notificationService.notify(notificationEvent);
                        if (log.isDebugEnabled()) {
                            log.debug("Notification '" + notificationMessage + "' sent to notification service.");
                        }
                        // Exception is caught because notificationService.notify method throws the exception from Exception
                        // class. This will be refactored after fixing this JIRA: https://wso2.org/jira/browse/REGISTRY-2433
                    } catch (Exception e) {
                        log.error("Error getting registry while getting scheduler objects to send notifications", e);
                    }
                }
            }
        } catch (RegistryException e) {
            log.error("Error while getting valid notifications on " + getCurrentDate(), e);
        }
    }

    /**
     * This method is used to add checkpoint notification schedulers to the database. These schedulers are used to
     * send notifications when they reaches the checkpoints defined in the attached lifecycle.
     *
     * @param resource              resource which the lifecycle is attached.
     * @param lifecycleName         lifecycle name.
     * @param lifecycleState        new lifecycle state after the state changed.
     * @param isInvokeAspect        is this add scheduler method is called when invoking a lifecycle.
     * @throws GovernanceException  Throws when an error occurred while adding a lifecycle notification scheduler to
     *                              the database.
     */
    public void addScheduler(ResourceImpl resource, String lifecycleName, String lifecycleState, boolean isInvokeAspect)
            throws GovernanceException {
        if (resource != null && StringUtils.isNotEmpty(lifecycleName) && StringUtils.isNotEmpty(lifecycleState)) {

            List checkpointsList = LifecycleStateDurationUtils.getDurationBeans(lifecycleName, lifecycleState);
            if (checkpointsList != null) {
                // Iterate through the checkpoint objects.
                for (Object checkpoint : checkpointsList) {
                    OMElement checkpointElement = (OMElement) checkpoint;
                    OMElement boundary = checkpointElement.getFirstChildWithName(
                            new QName(LifecycleConstants.LIFECYCLE_CONFIGURATION_NAMESPACE_URI,
                                    LifecycleConstants.LIFECYCLE_CHECKPOINT_BOUNDARY));
                    String minTimestamp = boundary
                            .getAttribute(new QName(LifecycleConstants.LIFECYCLE_LOWER_BOUNDARY)).getAttributeValue();
                    String maxTimestamp = boundary
                            .getAttribute(new QName(LifecycleConstants.LIFECYCLE_UPPER_BOUNDARY)).getAttributeValue();

                    long durationDifference = getDurationDifference(minTimestamp, maxTimestamp);

                    // Set scheduler property.
                    String propertyValue = lifecycleName + "." + checkpointElement.getAttribute(new QName(checkpointId))
                            .getAttributeValue() + "." + getNotificationDate(durationDifference);
                    resource.addProperty(lcCheckPointPropertyName, propertyValue);
                    // If the lifecycle is invoke registry.put is need to add the property because when invoke is
                    // triggered registry put method is not called.
                    if (isInvokeAspect) {
                        try {
                            CommonUtil.getRootSystemRegistry().put(resource.getPath(), resource);
                        } catch (RegistryException e) {
                            throw new GovernanceException(
                                    "Error while saving resource when lifecycle is invoked after adding property '"
                                            + propertyValue + "' to " + resource.getPath(), e);
                        }
                    }
                }
            } else {
                if (log.isDebugEnabled()) {
                    log.debug("Invalid arguments supplied as lifecycle name: " + lifecycleName + ", lifecycle state: "
                            + lifecycleState);
                }
            }
        }
    }

    /**
     * This method is used get duration differences using two durations in format dd:hh:mm:ss.
     *
     * @param timeStampOne  lower duration.
     * @param timeStampTwo  higher duration.
     * @return long         duration difference in timestamp format.
     */
    private long getDurationDifference(String timeStampOne, String timeStampTwo) {
        return LifecycleStateDurationUtils.getMillySecondsByDuration(timeStampTwo) - LifecycleStateDurationUtils
                .getMillySecondsByDuration(timeStampOne);
    }

    /**
     * This method is used to calculate notification date of the scheduler.
     *
     * @param durationDifference    duration difference of the lifecycle checkpoint.
     * @return                      notification date in the format of yyyy-MM-dd.
     */
    private String getNotificationDate(long durationDifference) {
        // Getting current time
        long currentTimeInMillySeconds = Calendar.getInstance().getTimeInMillis();

        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(durationDifference + currentTimeInMillySeconds - durationOfADay);
        int mYear = calendar.get(Calendar.YEAR);
        int mMonth = calendar.get(Calendar.MONTH);
        int mDay = calendar.get(Calendar.DAY_OF_MONTH);

        StringBuilder dateBuilder = new StringBuilder(dateLength);
        dateBuilder.append(mYear);
        dateBuilder.append(dateSeparator);
        // +1 is because mMonth is the completed months.
        dateBuilder.append(mMonth + 1);
        dateBuilder.append(dateSeparator);
        dateBuilder.append(mDay);
        return dateBuilder.toString();
    }

    /**
     * This method is used to create notification message.
     *
     * @param schedulerBean     scheduler bean need to create the notification message.
     * @return                  notification message.
     */
    private String getNotificationMessage(LCNotification schedulerBean) {

        String[] pathParams = schedulerBean.getRegPath().split("/");
        // Lifecycle cannot be applied to registry path "/". Hence pathParams.length is always greater than or equals
        // to one. Hence (pathParams.length - 1) cannot be a minus value.
        String resourceName = pathParams[pathParams.length - 1];

        StringBuilder stringBuilder = new StringBuilder("Resource '").append(resourceName).append("'s lifecycle '")
                .append(schedulerBean.getLcName()).append("' is reaching lifecycle checkpoint '")
                .append(schedulerBean.getLcCheckpointId()).append("' on ").append(schedulerBean.getNotificationDate())
                .append(".");
        return stringBuilder.toString();
    }

    /**
     * This method used to get current date in yyyy-M-d format.
     *
     * @return current date in yyyy-M-d format.
     */
    private String getCurrentDate() {
        DateFormat dateFormat = new SimpleDateFormat(this.dateFormat);
        //get current date time with Calendar()
        Calendar cal = Calendar.getInstance();
        return dateFormat.format(cal.getTime());
    }

    /**
     * This method is used to get valid lifecycle checkpoints to be send.
     *
     * @return                      valid lifecycle checkpoint notifications.
     * @throws RegistryException    Throws if an error occurred while getting registry or when getting lifecycle
     *                              checkpoint notification properties.
     */
    private ArrayList<LCNotification> getValidNotifications() throws RegistryException {

        ArrayList<LCNotification> notifications = new ArrayList<>();
        AttributeSearchService attributeSearchService = CommonUtil.getAttributeSearchService();
        Map<String, String> searchAttributes = new HashMap<>();
        searchAttributes.put(IndexingConstants.FIELD_PROPERTY_NAME, lcCheckPointPropertyName);
        searchAttributes.put(IndexingConstants.FIELD_RIGHT_PROPERTY_VAL, "%" + getCurrentDate()
                .replaceAll("-", "\\\\-"));
        searchAttributes.put(IndexingConstants.FIELD_RIGHT_OP, equals);
        searchAttributes.put(IndexingConstants.FIELD_LEFT_OP, notApplicable);

        ResourceData[] resourceDataList = null;
        try {
            PrivilegedCarbonContext.startTenantFlow();
            PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(superTenantDomain);
            PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(superAdminUsername);
            PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(superTenantId);

            resourceDataList = attributeSearchService.search(CommonUtil.getRootSystemRegistry(), searchAttributes);
        } finally {
            PrivilegedCarbonContext.endTenantFlow();
        }

        if (resourceDataList != null) {
            for (ResourceData resourceData : resourceDataList) {
                LCNotification lcNotification = new LCNotification();
                ArrayList propValues = getLcNotificationProperties(resourceData);
                if (propValues.size() > 0) {
                    for (Object propValueObject : propValues) {
                        String propValue = (String) propValueObject;
                        String[] lcCheckpointValues = propValue.split("\\.");
                        lcNotification.setLcName(lcCheckpointValues[0]);
                        lcNotification.setLcCheckpointId(lcCheckpointValues[1]);
                        lcNotification.setNotificationDate(lcCheckpointValues[2]);
                        lcNotification.setRegPath(resourceData.getResourcePath());
                    }
                }
                notifications.add(lcNotification);
            }
        }
        return notifications;
    }

    /**
     * This method is used to get lifecycle notification properties.
     *
     * @param resourceData          search resource data.
     * @return                      lifecycle notification properties.
     * @throws RegistryException    Throws if an error occurred when getting the resource from registry.
     */
    private ArrayList getLcNotificationProperties(ResourceData resourceData) throws RegistryException {
        Properties propertyNameValues = CommonUtil.getRootSystemRegistry().get(resourceData.getResourcePath())
                .getProperties();
        Iterator propIterator = propertyNameValues.entrySet().iterator();
        ArrayList propValues = new ArrayList();
        while (propIterator.hasNext()) {
            Map.Entry entry = (Map.Entry) propIterator.next();
            String propertyName = (String) entry.getKey();
            if (lcCheckPointPropertyName.equals(propertyName)) {
                propValues = (ArrayList) entry.getValue();
            }
        }
        return propValues;
    }
}


text:
import { Meteor } from 'meteor/meteor';
import { _ } from 'meteor/erasaur:meteor-lodash';
import SimpleSchema from 'simpl-schema';
import { Slugs } from '../slug/SlugCollection';
import { Interests } from '../interest/InterestCollection';
import { CourseInstances } from './CourseInstanceCollection';
import { Feeds } from '../feed/FeedCollection';
import BaseSlugCollection from '../base/BaseSlugCollection';
import { isSingleChoice } from '../degree-plan/PlanChoiceUtilities';

/**
 * Represents a specific course, such as "ICS 311".
 * To represent a specific course for a specific semester, use CourseInstance.
 * @memberOf api/course
 * @extends api/base.BaseSlugCollection
 */
class CourseCollection extends BaseSlugCollection {
  /**
   * Creates the Course collection.
   */
  constructor() {
    super('Course', new SimpleSchema({
      name: { type: String },
      shortName: { type: String },
      slugID: { type: SimpleSchema.RegEx.Id },
      number: { type: String },
      description: { type: String },
      creditHrs: { type: Number },
      interestIDs: [SimpleSchema.RegEx.Id],
      // Optional data
      syllabus: { type: String, optional: true },
      prerequisites: [String],
      retired: { type: Boolean, optional: true },
    }));
    this.unInterestingSlug = 'other';
  }

  /**
   * Defines a new Course.
   * @example
   * Courses.define({ name: 'Introduction to the theory and practice of scripting',
   *                  shortName: 'Intro to Scripting',
   *                  slug: 'ics215',
   *                  number: 'ICS 215',
   *                  description: 'Introduction to scripting languages for the integration of applications.',
   *                  creditHrs: 4,
   *                  interests: ['perl', 'javascript', 'ruby'],
   *                  syllabus: 'http://courses.ics.hawaii.edu/syllabuses/ICS215.html',
   *                  prerequisites: ['ics211'] });
   * @param { Object } description Object with keys name, shortName, slug, number, description, creditHrs,
   *                   interests, syllabus, and prerequisites.
   * Name is the official course name.
   * ShortName is an optional abbreviation. Defaults to name.
   * Slug must not be previously defined.
   * CreditHrs is optional and defaults to 3. If supplied, must be a number between 1 and 15.
   * Interests is a (possibly empty) array of defined interest slugs or interestIDs.
   * Syllabus is optional. If supplied, should be a URL.
   * Prerequisites is optional. If supplied, must be an array of previously defined Course slugs or courseIDs.
   * retired is optional defaults to false.
   * @throws {Meteor.Error} If the definition includes a defined slug or undefined interest or invalid creditHrs.
   * @returns The newly created docID.
   */
  define({
    name, shortName = name, slug, number, description, creditHrs = 3,
    interests = [], syllabus, prerequisites = [], retired,
  }) {
    try {
      // Check to see if is defined already.
      return Slugs.getEntityID(slug, this.getType());
    } catch (e) {
      // try to create the Course
    }
    // Get Interests, throw error if any of them are not found.
    const interestIDs = Interests.getIDs(interests);
    // Get SlugID, throw error if found.
    const slugID = Slugs.define({ name: slug, entityName: this.getType() });
    // Make sure creditHrs is a number between 1 and 15.
    if (!(typeof creditHrs) === 'number' || (creditHrs < 1) || (creditHrs > 15)) {
      throw new Meteor.Error(`CreditHrs ${creditHrs} is not a number between 1 and 15.`, '', Error().stack);
    }
    if (!Array.isArray(prerequisites)) {
      throw new Meteor.Error(`Prerequisites ${prerequisites} is not an array.`, '', Error().stack);
    }
    // Currently we don't dump the DB is a way that prevents forward referencing of prereqs, so we
    // can't check the validity of prereqs during a define, such as with:
    //   _.each(prerequisites, (prerequisite) => this.getID(prerequisite));
    // Instead, we check that prereqs are valid as part of checkIntegrity.
    const courseID = this._collection.insert({
      name, shortName, slugID, number, description, creditHrs, interestIDs, syllabus, prerequisites, retired,
    });
    // Connect the Slug to this Interest
    Slugs.updateEntityID(slugID, courseID);
    return courseID;
  }

  /**
   * Update a Course.
   * @param docID The docID (or slug) associated with this course.
   * @param name optional
   * @param shortName optional
   * @param number optional
   * @param description optional
   * @param creditHrs optional
   * @param interests An array of interestIDs or slugs (optional)
   * @param syllabus optional
   * @param prerequisites An array of course slugs. (optional)
   * @param retired boolean (optional)
   */
  update(instance, {
    name, shortName, number, description, creditHrs, interests, prerequisites, syllabus, retired,
  }) {
    const docID = this.getID(instance);
    const updateData = {};
    if (name) {
      updateData.name = name;
    }
    if (description) {
      updateData.description = description;
    }
    if (interests) {
      const interestIDs = Interests.getIDs(interests);
      updateData.interestIDs = interestIDs;
    }
    if (shortName) {
      updateData.shortName = shortName;
    }
    if (_.isNumber(number)) {
      updateData.number = number;
    }
    if (creditHrs) {
      updateData.creditHrs = creditHrs;
    }
    if (syllabus) {
      updateData.syllabus = syllabus;
    }
    if (prerequisites) {
      if (!Array.isArray(prerequisites)) {
        throw new Meteor.Error(`Prerequisites ${prerequisites} is not an Array.`, '', Error().stack);
      }
      _.forEach(prerequisites, prereq => {
        if (!this.hasSlug(prereq)) {
          throw new Meteor.Error(`Prerequisite ${prereq} is not a slug for a course.`, '', Error().stack);
        }
      });
      updateData.prerequisites = prerequisites;
    }
    if (_.isBoolean(retired)) {
      updateData.retired = retired;
    }
    this._collection.update(docID, { $set: updateData });
  }

  /**
   * Remove the Course.
   * @param instance The docID or slug of the entity to be removed.
   * @throws { Meteor.Error } If docID is not a Course, or if this course has any associated course instances.
   */
  removeIt(instance) {
    const docID = this.getID(instance);
    // Check that this is not referenced by any Course Instance.
    CourseInstances.find()
      .map(function (courseInstance) { // eslint-disable-line array-callback-return
        if (courseInstance.courseID === docID) {
          throw new Meteor.Error(`Course ${instance} is referenced by a course instance ${courseInstance}.`,
            '', Error().stack);
        }
      });
    // OK to delete. First remove any Feeds that reference this course.
    Feeds.find({ courseID: docID })
      .map(function (feed) { // eslint-disable-line array-callback-return
        Feeds.removeIt(feed._id);
      });
    // Now remove the Course.
    super.removeIt(docID);
  }

  /**
   * Returns true if Course has the specified interest.
   * @param course The user (docID or slug)
   * @param interest The Interest (docID or slug).
   * @returns {boolean} True if the course has the associated Interest.
   * @throws { Meteor.Error } If course is not a course or interest is not a Interest.
   */
  hasInterest(course, interest) {
    const interestID = Interests.getID(interest);
    const doc = this.findDoc(course);
    return _.includes(doc.interestIDs, interestID);
  }

  getSlug(courseID) {
    this.assertDefined(courseID);
    const courseDoc = this.findDoc(courseID);
    return Slugs.findDoc(courseDoc.slugID).name;
  }

  /**
   * Returns an array of strings, each one representing an integrity problem with this collection.
   * Returns an empty array if no problems were found.
   * Checks slugID and interestIDs.
   * @returns {Array} A (possibly empty) array of strings indicating integrity issues.
   */
  checkIntegrity() {
    const problems = [];
    this.find()
      .forEach(doc => {
        if (!Slugs.isDefined(doc.slugID)) {
          problems.push(`Bad slugID: ${doc.slugID}`);
        }
        _.forEach(doc.interestIDs, interestID => {
          if (!Interests.isDefined(interestID)) {
            problems.push(`Bad interestID: ${interestID}`);
          }
        });
        _.forEach(doc.prerequisites, prereq => {
          if (isSingleChoice(prereq)) {
            if (!this.hasSlug(prereq)) {
              problems.push(`Bad course prerequisite slug: ${prereq}`);
            }
          } else {
            const slugs = prereq.split(',');
            _.forEach(slugs, (slug) => {
              if (!this.hasSlug(slug)) {
                problems.push(`Bad course prerequisite slug: ${slug}`);
              }
            });
          }
        });
      });
    return problems;
  }

  /**
   * Returns an object representing the Course docID in a format acceptable to define().
   * @param docID The docID of a Course.
   * @returns { Object } An object representing the definition of docID.
   */
  dumpOne(docID) {
    const doc = this.findDoc(docID);
    const { name } = doc;
    const { shortName } = doc;
    const slug = Slugs.getNameFromID(doc.slugID);
    const { number } = doc;
    const { description } = doc;
    const { creditHrs } = doc;
    const interests = _.map(doc.interestIDs, interestID => Interests.findSlugByID(interestID));
    const { syllabus } = doc;
    const { prerequisites } = doc;
    const { retired } = doc;
    return {
      name, shortName, slug, number, description, creditHrs, interests, syllabus,
      prerequisites, retired,
    };
  }
}

/**
 * Provides the singleton instance of this class to all other entities.
 * @memberOf api/course
 */
export const Courses = new CourseCollection();


text:
/*
 */

/*
 * (C) Copyright Taligent, Inc. 1996, 1997 - All Rights Reserved
 * (C) Copyright IBM Corp. 1996 - 1998 - All Rights Reserved
 *
 * The original version of this source code and documentation
 * is copyrighted and owned by Taligent, Inc., a wholly-owned
 * subsidiary of IBM. These materials are provided under terms
 * of a License Agreement between Taligent and Sun. This technology
 * is protected by multiple US and International patents.
 *
 * This notice and attribution to Taligent may not be removed.
 * Taligent is a registered trademark of Taligent, Inc.
 *
 */

package sun.text.resources.no;

import java.util.ListResourceBundle;

public class CollationData_no extends ListResourceBundle {

    protected final Object[][] getContents() {
        return new Object[][] {
            { "Rule",
                "& D <\u00D0,\u00F0" +      // eth
                "& ss,\u00DF" +             // s-zet
                "& y , u\u0308" +   // u-umlaut is eq. to y.
                "& y ; U\u0308" +  // u-umlaut is eq. to y.
                "& Z < \u00e6, \u00c6 " +    // z < z-caron
                " < a\u0308, A\u0308" +      // nt : a-umlaut
                "< \u00f8, \u00d8 < o\u0308, O\u0308" + // nt : o-stroke < o-umlaut
                "< o\u030b, O\u030b " +      // nt : o-double-acute
                "< a\u030a, A\u030a" +       // nt : a-ring
                ", aa , aA , Aa , AA " +         // tal : aa ligature sorts after a-ring
                " & V < w, W "
            }
        };
    }
}


text:
// Copyright (C) 2019 MapRoulette contributors (see CONTRIBUTORS.md).
// Licensed under the Apache License, Version 2.0 (see LICENSE).
package org.maproulette.jobs

import java.util.Calendar

import akka.actor.{ActorRef, ActorSystem}
import javax.inject.{Inject, Named}
import org.maproulette.Config
import org.maproulette.jobs.SchedulerActor.RunJob
import org.slf4j.LoggerFactory
import play.api.{Application, Logger}

import scala.concurrent.ExecutionContext
import scala.concurrent.duration._

/**
  * @author cuthbertm
  * @author davis_20
  */
class Scheduler @Inject() (
    val system: ActorSystem,
    @Named("scheduler-actor") val schedulerActor: ActorRef,
    val config: Config
)(implicit application: Application, ec: ExecutionContext) {

  private val logger = LoggerFactory.getLogger(this.getClass)

  schedule("cleanLocks", "Cleaning locks", 1.minute, Config.KEY_SCHEDULER_CLEAN_LOCKS_INTERVAL)
  schedule(
    "cleanClaimLocks",
    "Cleaning review claim locks",
    1.minute,
    Config.KEY_SCHEDULER_CLEAN_CLAIM_LOCKS_INTERVAL
  )
  schedule(
    "runChallengeSchedules",
    "Running challenge Schedules",
    1.minute,
    Config.KEY_SCHEDULER_RUN_CHALLENGE_SCHEDULES_INTERVAL
  )
  schedule(
    "updateLocations",
    "Updating locations",
    1.minute,
    Config.KEY_SCHEDULER_UPDATE_LOCATIONS_INTERVAL
  )
  schedule(
    "cleanOldTasks",
    "Cleaning old tasks",
    1.minute,
    Config.KEY_SCHEDULER_CLEAN_TASKS_INTERVAL
  )
  schedule(
    "cleanExpiredVirtualChallenges",
    "Cleaning up expired Virtual Challenges",
    1.minute,
    Config.KEY_SCHEDULER_CLEAN_VC_INTEVAL
  )
  schedule(
    "OSMChangesetMatcher",
    "Matches OSM changesets to tasks",
    1.minute,
    Config.KEY_SCHEDULER_OSM_MATCHER_INTERVAL
  )
  schedule(
    "cleanDeleted",
    "Deleting Project/Challenges",
    1.minute,
    Config.KEY_SCHEDULER_CLEAN_DELETED
  )
  schedule(
    "KeepRightUpdate",
    "Updating KeepRight Challenges",
    1.minute,
    Config.KEY_SCHEDULER_KEEPRIGHT
  )
  schedule(
    "rebuildChallengesLeaderboard",
    "Rebuilding Challenges Leaderboard",
    1.minute,
    Config.KEY_SCHEDULER_CHALLENGES_LEADERBOARD
  )
  schedule(
    "sendImmediateNotificationEmails",
    "Sending Immediate Notification Emails",
    1.minute,
    Config.KEY_SCHEDULER_NOTIFICATION_IMMEDIATE_EMAIL_INTERVAL
  )
  scheduleAtTime(
    "sendDigestNotificationEmails",
    "Sending Notification Email Digests",
    config.getValue(Config.KEY_SCHEDULER_NOTIFICATION_DIGEST_EMAIL_START),
    Config.KEY_SCHEDULER_NOTIFICATION_DIGEST_EMAIL_INTERVAL
  )

  // Run the rebuild of the country leaderboard at
  scheduleAtTime(
    "rebuildCountryLeaderboard",
    "Rebuilding Country Leaderboard",
    config.getValue(Config.KEY_SCHEDULER_COUNTRY_LEADERBOARD_START),
    Config.KEY_SCHEDULER_COUNTRY_LEADERBOARD
  )

  // Run the user metrics snapshot at
  scheduleAtTime(
    "snapshotUserMetrics",
    "Snapshotting User Metrics",
    config.getValue(Config.KEY_SCHEDULER_SNAPSHOT_USER_METRICS_START),
    Config.KEY_SCHEDULER_SNAPSHOT_USER_METRICS
  )

  // Run the challenge snapshots at
  scheduleAtTime(
    "snapshotChallenges",
    "Snapshotting Challenges",
    config.getValue(Config.KEY_SCHEDULER_SNAPSHOT_CHALLENGES_START),
    Config.KEY_SCHEDULER_SNAPSHOT_CHALLENGES_INTERVAL
  )

  /**
    * Conditionally schedules message event to start at an initial time and run every duration
    *
    * @param name           The message name sent to the SchedulerActor
    * @param action         The action this job is performing for logging
    * @param initialRunTime String time in format "00:00:00"
    * @param intervalKey    Configuration key that, when set, will enable periodic scheduled messages
    */
  def scheduleAtTime(
      name: String,
      action: String,
      initialRunTime: Option[String],
      intervalKey: String
  ): Unit = {
    initialRunTime match {
      case Some(initialRunTime) =>
        val timeValues = initialRunTime.split(":")
        val c          = Calendar.getInstance()
        c.set(Calendar.HOUR_OF_DAY, timeValues(0).toInt)
        c.set(Calendar.MINUTE, timeValues(1).toInt)
        c.set(Calendar.SECOND, timeValues(2).toInt)
        c.set(Calendar.MILLISECOND, 0)

        if (c.getTimeInMillis() < System.currentTimeMillis()) {
          c.add(Calendar.DATE, 1)
        }
        val msBeforeStart = c.getTimeInMillis() - System.currentTimeMillis()

        logger.debug("Scheduling " + action + " to run in " + msBeforeStart + "ms.")
        schedule(name, action, msBeforeStart.milliseconds, intervalKey)

      case _ => logger.error("Invalid start time given for " + action + "!")
    }

  }

  /**
    * Conditionally schedules message event when configured with a valid duration
    *
    * @param name         The message name sent to the SchedulerActor
    * @param action       The action this job is performing for logging
    * @param initialDelay FiniteDuration until the initial message is sent
    * @param intervalKey  Configuration key that, when set, will enable periodic scheduled messages
    */
  def schedule(
      name: String,
      action: String,
      initialDelay: FiniteDuration,
      intervalKey: String
  ): Unit = {
    config.withFiniteDuration(intervalKey) { interval =>
      this.system.scheduler
        .schedule(initialDelay, interval, this.schedulerActor, RunJob(name, action))
      logger.info(s"$action every $interval")
    }
  }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
          "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

    <meta http-equiv="content-type" content="text/html;charset=utf-8" />
    <title>WMSBrowser using a TreePanel and a Ext.ux.StatusBar (example)</title>

    <link rel="stylesheet" type="text/css"
          href="../../../../ext/resources/css/ext-all.css" />
    <link rel="stylesheet" type="text/css"
          href="../../../../ext/examples/shared/examples.css" />
    <link rel="stylesheet" type="text/css"
          href="../../../../ext/examples/ux/statusbar/css/statusbar.css" />
    <link rel="stylesheet" type="text/css"
          href="../resources/css/WMSBrowser.css" />

WMSBrowser using a TreePanel and a Ext.ux.StatusBar (example)

      This widget allows remote WMS service layer browsing and adding to your
      map. See WMSBrowser.js for the source code.

      You can select an url from the top list or enter one, then click
      'connect'. The list of available layers appear on the left. When one is
      checked (selected), more info appear on the right and a small map shows a
      preview of the data selected.  If more than one layer is selected, only
      the last one selected has its info shown, but all layers are merged in
      the preview.

      The name of the layer is automatically generated by a combinaison of the
      selected layers, but it can also be manually set.  Clicking the
      'Add layer' button add the combinaison of the selected layers as a single
      OpenLayers.Layer.WMS layer object to your map.

      Among its features, the widget offers srs and extent validation with your
      map.  The layer list on the left can either be a Tree (default) or a Grid.
      If the StatusBar ux widget (in Ext) source code is loaded, one is
      automatically added to the widget allowing messages to be displayed as
      it executes different tasks or when an error occurs.  If none is provided,
      only the errors are shown in a Ext.Window.  It's also translated in
      French.

      Please note : in order to work properly with external urls, you
      need to setup a proxy.  You can either set the OpenLayers.ProxyHost or
      use the widget local proxy setting.  In this demo, plain local xml files
      are used to avoid the setting of a proxy.  There's a php one located in
      this sample which you can use locally.


text:
Datomic'de veritabanı, bildiğimiz veritabanından farklı anlamda kullanılır. Datomic için veritabanı, "büyük" veritabanının belirli bir alt kümesidir (subset of the facts).

`(d/db conn)` ile sağlanan görünümü (view) kullanarak veritabanının belli bir durumunu çekersin.

Veritabanı sabit (immutable) bir değer olunca, tüm okuma işlemleri saf (pure) hale gelir. Dolayısıyla bu fonksiyonlar referanssal şeffaf (referentially transparent) olurlar.

## Writing Data

Veri yazmak `(d/transact conn)` ile yapılır. Fakat `conn` yani peer connection objesi sabit değildir.

Datomic işlemleri (transaction) ya transactor fonksiyonu çağırlarından veya entity maplerden oluşur. Tüm güncellemeleri tek bir işlem içine koyarız. Bu tek işlemi de tek bir veri yapısına (data structure) koyup göndeririz. Böylece bu tek fonksiyon çağrısı dışındaki tüm işlemler yan etkisiz olur.

### The data processing contract

Veri güncelleyen fonksiyonlar şu işlemleri de genellikle yapar:

- Veri geçerleme (validation)
- Ek veri sorgulama (look up)
- Veri işleme (process)
- Değişiklikleri commit etme

Bu adımlardan birinde sorun çıkması, güncellemeleri iptal edebilir. Dolayısıyla veri güncelleyen fonksiyonların sadece işlem verisini dönmesi yetmez, potansiyel hataları da bildirmesi gerekir. Bunun için bir kontrat tanımlayalım:

```clj
{:command/success? true ;; or false
 :command/validation-data {}
 :command/tx-data []
 :command/error {}}
```

Eğer komut hata dönerse, ya `validation-data` ya da `error` mesajlarından en az birisi olmalı. Eğer başarılı çalışırsa, o zaman `tx-data` olmalı. Bunu da `transact` fonksiyonuna göndeririz: `(d/transact conn tx-data)`

# [Why is Clojure so stable? - Steve Labnik](https://steveklabnik.com/writing/why-is-clojure-so-stable) id=g13340

> Clojure was designed by a thinker, who creates when he is away from the keyboard, not in front of it. When one releases and breaks the code in his head first, very few breaking changes are left for the public releases.

> The Great Man theory was originally proposed in the mid 1800s by Thomas Carlyle, and goes something like this: ""the history of the world is but the biography of great men."

> First of all, Clojure is a Lisp. This has a wide array of reasons why stability is a bit easier than in other languages. Lisps, on the other hand, rarely grow syntactically.

> Another perspective of this is homoiconicity. This property means that "new syntax" for Lisps can be introduced through macros, and not through the base language.

> one area in which dynamically typed languages clearly win out, in my mind, is that they have a wider set of tools at their disposal to make changes without breaking code. This cuts both ways; they also make it much, much harder to know if you've broken code as well

# [Val on Programming: So yeah, about Clojure's syntax...](http://vvvvalvalval.github.io/posts/2018-01-06-so-yeah-about-clojures-syntax.html) id=g13341

> syntax is NEVER a good reason to use or dismiss a programming language. But Syntax matters, because it encourages or inhibits certain programming idioms.

Clojure sentaksı temelde veri yapıları yazmak için bir notasyondur. scalar, collection tipleri yazarsın her bir ifadeyle.

Clojure compiler bir metni derlemez, onun yerine veri yapılarını derler.

İki tane özel kural var bu veri yapılarını işlerken:

- symbols: evaluated to the value that they name
- lists: bir fonksiyon çağrısı olur

## Macros

Bazı list operasyonları diğerlerinden farklı çalışır. Bunlar special formlar ve makrolardır. Dilin içine gömülmüş olanlarına `special form` denir: `def`, `let`, `if`, `fn`.

Makroların özellikleri:

- Kod ifadelerini veri yapıları olarak kabul ederler ve yine veri yapıları dönerler.
- Programın AST'sini dönüştürmene izin verirler derleme zamanında (concrete syntax tree)
- Mecrolar sıfır maliyetli soyutlamalara izin verir. Çünkü makrolar derleme zamanında çalışır.

## Consequences

### Verbosity is a solved problem

Data literalleri sayesinde örneğin, datalog sql'den daha kısa ve programlanabilir olur.

### Separation of concerns: code layout ⊥ program structure

Örnek problem: 1'den 100'e kadar sayıları al. Bunların çift olanlarını al. Bunların karesini al. Bunların toplamını hesapla.

Bu problemi fonksiyonlarla yapabilirsin. Ancak js gibi bir dilde, bunu lineer bir pipeline şeklinde yapmak için Builder pattern kullanman gerekir. Bu ise programa yeni bir mantık eklemeni gerektirir.

```js
_.chain(_.range(100))
 .filter(function(n){return n % 2 === 0;})
 .map(function(n){return n * n;})
 .reduce(function(sum, n){return sum + n;}, 0)
 .value();
```

Halbuki, clojure ile bunu lineer pipeline olarak göstermek için threading macroyu kullanırsın. Yeni bir mantıksal yapı eklemezsin:

```clj
(->> (range 100)
  (filter (fn [n] (= (mod n 2) 0)))
  (map (fn [n] (* n n)))
  (reduce + 0))
```

> What's neat about the above solution is that we haven't compromised at all on program structure in order to make the code pretty. We just composed 2 orthogonal tools, each solving a separate concern:
>
> a syntactic tool (the ->> macro) to solve a syntactic problem (organizing the code visually)
> a semantic tool (the map / filter / reduce functions) to make a correct, well-structured program.

Yani programın lineer çözümünü sağlamak için kullandığın araç, programın mantığında bir değişiklik yaratmaz.

### Code = Data = Data Viz

Code is data. Bunun anlamı, Lisp'in sentaksının, Lisp dili tarafından düzenlenebilir (manipüle edilebilir) bir veri yapısı olduğudur. Yani programın kendisini, aynı bir veriyi işlermiş gibi düzenleyebilirsin makrolarla kolaylıkla.

### Tooling as libraries

> "I don't need macros, they're too complicated and not useful," says the programmer as they use Flow with JSX with Babel with two dozen plugins and maintain two hundred line webpack configs for code with machine-checked comments that parses CSS in template strings at runtime and— -- Alexis King

Makrolarla, destek ve altyapı araçlarının yaptığı işleri yapabilirsin.

### An 'all-tracks' language: embedding paradigms

Clojure sentaksı semantikle ilgili bir kısıtlama getirmez, çünkü bir veri yapısıdır. Bu yüzden farklı programlama paradigmalarını benimser.

> You could however argue that having different syntaxes for different paradigms is beneficial, because using them in separate source files forces programmers to separate concerns. That's not the case in my experience, because in a typical program, different paradigms don't address different concerns, rather different aspects of the same concern.

Example: Web UIs

> For example, one of the biggest lies that are told to novice Web programmers is that HTML, CSS and JavaScript are respectively for content, style and logic. For today's web applications, this is not true at all, and trying to enforce this separation actually creates much more complexity than it eliminates. The reasons for this separation are actually historical; the modern best practice is to separate UI into components, each component having its own DOM templating, styles and logic. In the JavaScript world, inline styles and JSX are approaches for co-locating them in code.


text:
package org.jsmart.zerocode.core.kafka.send;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.google.inject.name.Named;
import org.apache.kafka.clients.producer.Callback;
import org.apache.kafka.clients.producer.Producer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.clients.producer.RecordMetadata;
import org.jsmart.zerocode.core.di.provider.GsonSerDeProvider;
import org.jsmart.zerocode.core.di.provider.ObjectMapperProvider;
import org.jsmart.zerocode.core.engine.preprocessor.ScenarioExecutionState;
import org.jsmart.zerocode.core.engine.preprocessor.ZeroCodeAssertionsProcessorImpl;
import org.jsmart.zerocode.core.kafka.delivery.DeliveryDetails;
import org.jsmart.zerocode.core.kafka.send.message.ProducerJsonRecord;
import org.jsmart.zerocode.core.kafka.send.message.ProducerJsonRecords;
import org.jsmart.zerocode.core.kafka.send.message.ProducerRawRecords;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.net.URL;
import java.util.List;
import java.util.concurrent.ExecutionException;

import static org.jsmart.zerocode.core.constants.ZerocodeConstants.FAILED;
import static org.jsmart.zerocode.core.constants.ZerocodeConstants.OK;
import static org.jsmart.zerocode.core.kafka.KafkaConstants.JSON;
import static org.jsmart.zerocode.core.kafka.KafkaConstants.PROTO;
import static org.jsmart.zerocode.core.kafka.KafkaConstants.RAW;
import static org.jsmart.zerocode.core.kafka.KafkaConstants.RECORD_TYPE_JSON_PATH;
import static org.jsmart.zerocode.core.kafka.helper.KafkaProducerHelper.createProducer;
import static org.jsmart.zerocode.core.kafka.helper.KafkaProducerHelper.prepareJsonRecordToSend;
import static org.jsmart.zerocode.core.kafka.helper.KafkaProducerHelper.prepareRecordToSend;
import static org.jsmart.zerocode.core.kafka.helper.KafkaProducerHelper.readRecordType;
import static org.jsmart.zerocode.core.kafka.helper.KafkaProducerHelper.validateProduceRecord;
import static org.jsmart.zerocode.core.utils.SmartUtils.prettyPrintJson;

@Singleton
public class KafkaSender {
    private static final Logger LOGGER = LoggerFactory.getLogger(KafkaSender.class);

    @Inject(optional = true)
    @Named("kafka.producer.properties")
    private String producerPropertyFile;

    @Inject
    private ZeroCodeAssertionsProcessorImpl zeroCodeAssertionsProcessor;

    private final ObjectMapper objectMapper = new ObjectMapperProvider().get();
    private final Gson gson = new GsonSerDeProvider().get();

    public String send(String brokers, String topicName, String requestJson, ScenarioExecutionState scenarioExecutionState) throws JsonProcessingException {
        Producer<?, ?> producer = createProducer(brokers, producerPropertyFile);
        String deliveryDetails = null;

        ProducerRawRecords rawRecords;
        String recordType = readRecordType(requestJson, RECORD_TYPE_JSON_PATH);

        ProducerJsonRecords jsonRecords;

        try {
            switch (recordType) {
                case RAW:
                    rawRecords = gson.fromJson(requestJson, ProducerRawRecords.class);

                    String fileName = rawRecords.getFile();
                    if (fileName != null) {
                        File file = validateAndGetFile(fileName);
                        try (BufferedReader br = new BufferedReader(new FileReader(file))) {
                            String line;
                            for (int i = 0; (line = br.readLine()) != null; i++) {
                                ProducerRecord record = gson.fromJson(line, ProducerRecord.class);
                                LOGGER.info("From file:'{}', Sending record number: {}\n", fileName, i);
                                deliveryDetails = sendRaw(topicName, producer, record, rawRecords.getAsync());
                            }
                        } catch (Throwable ex) {
                            throw new RuntimeException(ex);
                        }
                    } else {
                        List<ProducerRecord> records = rawRecords.getRecords();
                        validateProduceRecord(records);
                        for (int i = 0; i < records.size(); i++) {
                            LOGGER.info("Sending record number: {}\n", i);
                            deliveryDetails = sendRaw(topicName, producer, records.get(i), rawRecords.getAsync());
                        }
                    }

                    break;
                case PROTO:
                case JSON:
                    jsonRecords = objectMapper.readValue(requestJson, ProducerJsonRecords.class);

                    fileName = jsonRecords.getFile();
                    if (fileName != null) {
                        File file = validateAndGetFile(fileName);
                        try (BufferedReader br = new BufferedReader(new FileReader(file))) {
                            String line;
                            for (int i = 0; (line = br.readLine()) != null; i++) {
                                line = zeroCodeAssertionsProcessor.resolveStringJson(line,
                                        scenarioExecutionState.getResolvedScenarioState());
                                ProducerJsonRecord record = objectMapper.readValue(line, ProducerJsonRecord.class);
                                LOGGER.info("From file:'{}', Sending record number: {}\n", fileName, i);
                                deliveryDetails = sendJson(topicName, producer, record, jsonRecords.getAsync(), recordType, requestJson);
                            }
                        }
                    } else {
                        List<ProducerJsonRecord> records = jsonRecords.getRecords();
                        validateProduceRecord(records);
                        for (int i = 0; i < records.size(); i++) {
                            deliveryDetails = sendJson(topicName, producer, records.get(i), jsonRecords.getAsync(), recordType, requestJson);
                        }
                    }

                    break;
                default:
                    throw new RuntimeException("Unsupported recordType '" + recordType + "'. Chose RAW or JSON");
            }

        } catch (Exception e) {
            LOGGER.error("Error in sending record.", e);
            String failedStatus = objectMapper.writeValueAsString(new DeliveryDetails(FAILED, e.getMessage()));
            return prettyPrintJson(failedStatus);

        } finally {
            producer.close();
        }

        return prettyPrintJson(deliveryDetails);

    }

    private String sendRaw(String topicName,
                           Producer<?, ?> producer,
                           ProducerRecord recordToSend,
                           Boolean isAsync) throws InterruptedException, ExecutionException {
        ProducerRecord qualifiedRecord = prepareRecordToSend(topicName, recordToSend);

        RecordMetadata metadata;
        if (Boolean.TRUE.equals(isAsync)) {
            LOGGER.info("Asynchronous Producer sending record - {}", qualifiedRecord);
            metadata = (RecordMetadata) producer.send(qualifiedRecord, new ProducerAsyncCallback()).get();
        } else {
            LOGGER.info("Synchronous Producer sending record - {}", qualifiedRecord);
            metadata = (RecordMetadata) producer.send(qualifiedRecord).get();
        }

        LOGGER.info("Record was sent to partition- {}, with offset- {} ", metadata.partition(), metadata.offset());

        // --------------------------------------------------------------
        // Logs deliveryDetails, which shd be good enough for the caller
        // TODO- combine deliveryDetails into a list n return (if needed)
        // --------------------------------------------------------------
        String deliveryDetails = gson.toJson(new DeliveryDetails(OK, metadata));
        LOGGER.info("deliveryDetails- {}", deliveryDetails);
        return deliveryDetails;
    }

    private String sendJson(String topicName,
                            Producer<?, ?> producer,
                            ProducerJsonRecord recordToSend,
                            Boolean isAsync,
                            String recordType,
                            String requestJson) throws InterruptedException, ExecutionException {
        ProducerRecord record = prepareJsonRecordToSend(topicName, recordToSend, recordType, requestJson);

        RecordMetadata metadata;
        if (Boolean.TRUE.equals(isAsync)) {
            LOGGER.info("Asynchronous - Producer sending JSON record - {}", record);
            metadata = (RecordMetadata) producer.send(record, new ProducerAsyncCallback()).get();
        } else {
            LOGGER.info("Producer sending JSON record - {}", record);
            metadata = (RecordMetadata) producer.send(record).get();
        }

        LOGGER.info("Record was sent to partition- {}, with offset- {} ", metadata.partition(), metadata.offset());

        // --------------------------------------------------------------
        // Logs deliveryDetails, which shd be good enough for the caller
        // TODO- combine deliveryDetails into a list n return (if needed)
        // --------------------------------------------------------------
        String deliveryDetails = gson.toJson(new DeliveryDetails(OK, metadata));
        LOGGER.info("deliveryDetails- {}", deliveryDetails);

        return deliveryDetails;
    }

    private File validateAndGetFile(String fileName) {
        try {
            URL resource = getClass().getClassLoader().getResource(fileName);
            return new File(resource.getFile());
        } catch (Exception ex) {
            throw new RuntimeException("Error accessing file: `" + fileName + "' - " + ex);
        }
    }

    class ProducerAsyncCallback implements Callback {
        @Override
        public void onCompletion(RecordMetadata recordMetadata, Exception ex) {
            if (ex != null) {
                LOGGER.error("Asynchronous Producer failed with exception - {} ", ex);
            } else {
                LOGGER.info("Asynchronous Producer call was successful");
            }
        }
    }
}


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

// DB just flat items for now
var practiceItemSchema = new mongoose.Schema({
    title: String,
    artist: String,
    progress: Number,
    lastPlayed: Date,
    playCount: Number,
    mediaId: String,
    tabData: String,
    lyricData: String,
    notes: String,
    markDelete: Boolean
});

module.exports = mongoose.model('PracticeItem', practiceItemSchema);