text:
import { addDefaultParameter } from '@ovh-ux/ui-kit.core/src/js/component-utils';
import get from 'lodash/get';

export default class {
  constructor($attrs, $element, $scope, $timeout, ouiCriteriaAdderConfiguration) {
    'ngInject';

    this.$attrs = $attrs; // For 'addDefaultParameter'
    this.$element = $element;
    this.$scope = $scope;
    this.$timeout = $timeout;
    this.operators = ouiCriteriaAdderConfiguration.operatorsByType;
    this.translations = ouiCriteriaAdderConfiguration.translations;
    this.valueModel = {};
  }

  getOperatorsByType(type) {
    const operators = this.operators[type] || [];
    return operators.map((operator) => ({
      name: operator,
      title: this.translations[`operator_${type}_${operator}`],
    }));
  }

  onColumnChange() {
    this.resetValueModel();
    this.selectableOperators = this.filterSelectableOperators();

    const [selectableOperators] = this.selectableOperators;
    this.operatorModel = selectableOperators;
  }

  onFormSubmit() {
    if (this.valueModel[this.columnModel.type] !== undefined) {
      const modelValue = {
        title: `${this.columnModel.title} ${this.operatorModel.title} ${this.getCriterionValueLabel()}`,
        property: this.columnModel.name,
        operator: this.operatorModel.name,
        value: this.getCriterionValue(),
      };

      this.onSubmit({ modelValue });
      this.resetValueModel();

      if (this.criteriaContainer) {
        this.criteriaContainer.add(modelValue);
      }
    }
  }

  getCriterionValue() {
    if (['boolean', 'options'].indexOf(this.columnModel.type) < 0) {
      return this.valueModel[this.columnModel.type];
    }

    return this.valueModel[this.columnModel.type].value;
  }

  getCriterionValueLabel() {
    switch (this.columnModel.type) {
      case 'boolean':
        return this.getBooleanLabel(this.valueModel[this.columnModel.type].value);

      case 'options':
        return this.getOptionsLabel(this.valueModel[this.columnModel.type].value);

      default:
        return this.valueModel[this.columnModel.type];
    }
  }

  getBooleanLabel(value) {
    if (value) {
      return get(this.columnModel, 'typeOptions.trueValue') || this.translations.true_label;
    }

    return get(this.columnModel, 'typeOptions.falseValue') || this.translations.false_label;
  }

  initBooleanCriterion() {
    this.booleanChoices = [true, false].map((value) => ({
      name: this.getBooleanLabel(value),
      value,
    }));

    const [booleanChoices] = this.booleanChoices;
    this.valueModel[this.columnModel.type] = booleanChoices;
  }

  getOptionsLabel(value) {
    const options = get(this.columnModel, 'typeOptions.values');
    return options && options[value] ? options[value] : value;
  }

  initOptionsCriterion() {
    const options = get(this.columnModel, 'typeOptions.values');
    if (!options) {
      return;
    }

    this.optionsChoices = Object.keys(options)
      .map((key) => ({
        name: options[key],
        value: key,
      }))
      .sort((a, b) => String(a.name).localeCompare(String(b.name)));

    const [optionsChoices] = this.optionsChoices;
    this.valueModel[this.columnModel.type] = optionsChoices;
  }

  resetValueModel() {
    Object.keys(this.valueModel).forEach((key) => {
      this.valueModel[key] = undefined;
    });

    if (this.columnModel.type === 'boolean') {
      this.initBooleanCriterion();
    } else if (this.columnModel.type === 'options') {
      this.initOptionsCriterion();
    }
  }

  filterSelectableOperators() {
    const { type } = this.columnModel;
    const customOperatorsList = get(this.columnModel, 'typeOptions.operators');
    const operators = customOperatorsList || this.operators[type] || [];
    return operators.map((operator) => ({
      name: operator,
      title: this.translations[`operator_${type}_${operator}`],
    }));
  }

  $onInit() {
    addDefaultParameter(this, 'id', `ouiCriteriaAdder${this.$scope.$id}`);
    addDefaultParameter(this, 'name', `ouiCriteriaAdder${this.$scope.$id}`);
    addDefaultParameter(this, 'placement', 'center');

    this.$timeout(() => {
      const { 0: element } = this.$element;
      this.dropdownContent = element;
    });

    // Auto select first column
    if (this.properties) {
      const [properties] = this.properties;
      this.columnModel = properties;
    }

    this.selectableOperators = this.filterSelectableOperators();
    const [selectableOperators] = this.selectableOperators;
    this.operatorModel = selectableOperators;

    this.resetValueModel();
  }

  $postLink() {
    // Sometimes the digest cycle is done before dom manipulation,
    // So we use $timeout to force the $apply
    this.$timeout(() => {
      this.$element
        .addClass('oui-criteria-adder')
        .removeAttr('id')
        .removeAttr('name');
    });
  }
}


text:
package org.sonatype.flexmojos.compiler.util;

import java.util.List;

public interface FlexCompilerArgumentParser
{

    public abstract <E> String[] parseArguments( E cfg, Class<? extends E> configClass );

    public abstract <E> String[] parseArguments( E cfg, Class<? extends E> configClass, ClassLoader classLoader );

    public abstract <E> List<String> getArgumentsList( E cfg, Class<? extends E> configClass );

    public abstract <E> List<String> getArgumentsList( E cfg, Class<? extends E> configClass, ClassLoader classLoader );

}

redpajama_set_name: RedPajamaGithub


text:
export default {
  sourcePath: './app/assets',
  destPath: './public/assets'
}


text:
require File.expand_path('../../../spec_helper', __FILE__)
require File.expand_path('../../../shared/complex/conjugate', __FILE__)

describe "Complex#conjugate" do
  it_behaves_like(:complex_conjugate, :conjugate)
end


text:
typedef void(^SHURLRequestCompletionHandler)(id data, int status);

@interface SHURLRequest : NSObject

+ (SHURLRequest *)getFromURL:(NSString *)url
               andCompletion:(SHURLRequestCompletionHandler)block;

+ (SHURLRequest *)postToURL:(NSString *)url
                 withParams:(id)params
              andCompletion:(SHURLRequestCompletionHandler)block;

+ (SHURLRequest *)postToURL:(NSString *)url
                 withParams:(id)params
                withHeaders:(id)headers
              andCompletion:(SHURLRequestCompletionHandler)block;

+ (SHURLRequest *)postToURL:(NSString *)url
                 withParams:(id)params
                withHeaders:(id)headers
                withTimeOut:(NSTimeInterval)timeout
              andCompletion:(SHURLRequestCompletionHandler)block;

@end


text:
import sys
from io import InputOutput
from game import Game
from presenter import Presenter
from board_printer import BoardPrinter
from human import Human
from computer import Computer

class GameLoop(object):

    def __init__(self, io):
        self.io = io or InputOutput(sys.stdin, sys.stdout)
        self.presenter = Presenter(io)
        self.create_players(self.choose_player_type("first"), self.choose_player_type("second"))
        self.create_game(self.player1, self.player2)

    def run(self, game):
        self.presenter.welcome_message()
        while not game.is_over():
            BoardPrinter.print_board(self.io, game.board.spots)
            game.place_move(game.get_player_move())
            if game.is_over():
                BoardPrinter.print_board(self.io, game.board.spots)
                break
            game.switch_players()
        if self.play_again():
            self.create_game(self.player1, self.player2)
            self.start_game()

    def start_game(self):
        self.run(self.game)

    def create_game(self, player1, player2):
        self.game = Game(self.presenter, player1, player2)

    def choose_player_type(self, player_turn):
        self.presenter.player_type_prompt(player_turn)
        return self.io.get_input()

    def create_players(self, player1_response, player2_response):
        player1 = player1_response.rstrip().lower()
        player2 = player2_response.rstrip().lower()
        if player1 == "human":
            self.player1 = Human("X", self.io)
        else:
            self.player1 = Computer("X")
        if player2 == "human":
            self.player2 = Human("O", self.io)
        else:
            self.player2 = Computer("O")

    def play_again(self):
        self.presenter.play_again_prompt()
        user_response = self.io.get_input()
        return user_response.rstrip().lower() == "yes"


text:
'''
mysql 数据库线程连接池,每线程一个连接
'''

import _mysql
import time, logging
import threading
from _mysql_exceptions import IntegrityError, OperationalError
from threading import current_thread

def escape(var):
    '''这里假定连接数据库都是使用utf8的。'''
    if var is None:
        return ''
    if isinstance(var, unicode):
        var = var.encode('utf8')
    if not isinstance(var, str):
        var = str(var)
    return _mysql.escape_string(var)

class _SqlConn():
    def __init__(self, conn, owner):
        '''应该由SqlPool的getConn方法去初始化本类'''
        self.conn = conn
        self.owner = owner

    def __del__(self):
        self.close()

    def _affectRows(self):
        '''查看最后一次query影响几行数据.'''
        r = self.conn.affected_rows()
        #TODO 这个值与驱动、系统、硬件CPU位数都可能有关
        if r == 0xFFFFFFFFFFFFFFFF: #64位的-1
            return 0
        return r

    def execute(self, sql):
        '''@return: 成功返回影响行数,失败返回 小于零的整数.-2为主键冲突,其它负数未定义错误类型.'''
        try:
            self.conn.query(sql)
            return self._affectRows()
        except IntegrityError, e:
            return (SqlPool.KEY_ERROR) #发生主键冲突
        except Exception, e:
            logging.error('%s - %s' % (e, sql))
            print e, sql
            raise e # SQL 异常

    def query(self, sql, how = 0):
        '''执行一条查询的SQL语句,返回查询结果,也可以马上调用result方法对能取得. 每次的query对应一次的result.
        @param how:
            0 -- tuples (default), RET_TUPLE
            1 -- dictionaries, key=column or table.column if duplicated
            2 -- dictionaries, key=table.column.'''
        #assert (sql).lower().startswith("select") == True or (sql).lower().startswith("show") == True, 'must readonly query.'
        try:
            self.conn.query(sql)
            res = self.conn.store_result()
            if res:
                return res.fetch_row(res.num_rows(), how)
            else:
                return ()
        except Exception, e:
            logging.error('%s - %s' % (e, sql))
            raise e # SQL 异常

    def close(self):
        '''关闭连接'''
        self.owner.close(self)
        self.conn = None

class SqlPool(threading.Thread):
    '''全局线程变量,继承于local类'''
    KEY_ERROR = -2
    RET_TUPLE = 0
    RET_DICT_ROW_FOR_KEY = 1
    RET_DICT_TABLE_ROW_FOR_KEY = 2

    def __init__(self, host, user, passwd, db, port = 18889):
        threading.Thread.__init__(self, target = self._threadChecker, name = 'sqlpool')
        self._db = db
        self._host = host
        self._user = user
        self._passwd = passwd
        self._port = int(port)
        self._chkThread = None
        self._connect_pool = {}
        self.setDaemon(True)

    def _startChkThread(self):
        for thread in threading.enumerate():
            if thread.getName() == self.getName():
                return self
        else:
            self.start()
            return self

    def _threadChecker(self):
        while True:
            for thread in threading.enumerate():
                if self._connect_pool.has_key(thread.ident) \
                    and not thread.isAlive():
                    self._connect_pool.pop(thread.ident)
            time.sleep(30 * 60)

    def _valid_connection(self):
        if self._connect_pool.get(current_thread().ident) is not None:
            try:
                self._connect_pool[current_thread().ident].ping()
                return True
            except:
                self._connect_pool[current_thread().ident].close()
                self._connect_pool[current_thread().ident] = None
        return False

    def reconnect(self):
        self._connect_pool[current_thread().ident] = _mysql.connect(
            db = self._db,
            host = self._host,
            user = self._user,
            passwd = self._passwd,
            port = self._port)
        self._connect_pool[current_thread().ident].set_character_set('utf8')

    def getConn(self):
        '''获取连接'''
        if not self._valid_connection():
            self.reconnect()
        return _SqlConn(self._connect_pool[current_thread().ident], self)

    def close(self, conn):
        '''关闭连接'''

    def execute(self, sql):
        '''执行语句, 返回影响行数'''
        if self._chkThread is None:
            self._chkThread = True
            self._startChkThread()

        conn = self.getConn()
        try:
            return conn.execute(sql)
        except OperationalError, e:
            if e[0] == 2013 or e[0] == 2006:  # (2006, 'MySQL server has gone away')
                self.reconnect()              # (2013, 'Lost connection to MySQL server during query')
                return self.getConn().execute(sql)
            else:
                logging.error('%s - %s' % (e, sql))
                raise e

    def executeReturnInsertId(self, sql):
        '''执行语句, 返回影响行数及LAST_INSERT_ID'''
        if self._chkThread is None:
            self._chkThread = True
            self._startChkThread()

        conn = self.getConn()

        #execute sql
        insertResult = None
        try:
            insertResult = conn.execute(sql)
        except OperationalError, e:
            if e[0] == 2013 or e[0] == 2006:  # (2006, 'MySQL server has gone away')
                self.reconnect()              # (2013, 'Lost connection to MySQL server during query')
                conn = self.getConn()
                insertResult = conn.execute(sql)
            else:
                logging.error('%s - %s' % (e, sql))
                raise e

        if insertResult < 1:
            conn.close()
            return (insertResult, 0)

        # get id
        ''' NOTICE: 必须使用同一个conn调用LAST_INSERT_ID()。
                    为了兼容mysql-proxy, LAST_INSERT_ID和insert语句之间不能插入其他任何语句。
        '''
        try:
            retData = conn.query('SELECT LAST_INSERT_ID()', 0)
        except OperationalError, e:
            logging.error('%s - %s, LAST_INSERT_ID()' % (e, sql))
            raise e

        conn.close()

        # ok
        insertId = retData[0][0]
        return (insertResult, int(insertId))

    def query(self, sql, how = 0):
        '''执行语句,返回查询结果'''
        if self._chkThread is None:
            self._chkThread = True
            self._startChkThread()

        sqlConn = self.getConn()
        try:
            retData = sqlConn.query(sql, how)
        except OperationalError, e:
            if e[0] == 2013 or e[0] == 2006:  # (2006, 'MySQL server has gone away')
                self.reconnect()              # (2013, 'Lost connection to MySQL server during query')
                sqlConn = self.getConn()
                retData = sqlConn.query(sql, how)
            else:
                logging.error('%s - %s' % (e, sql))
                raise e
        sqlConn.close()
        return retData

class SqlUtil:
    @staticmethod
    def getFieldsDefaultValue(sqlPool, table):
        res = sqlPool.query('desc %s;' % table, SqlPool.RET_DICT_ROW_FOR_KEY)
        if res:
            defVals = {}
            for row in res:
                if row['Extra'] == 'auto_increment':
                    continue

                field, defVal, fieldType = row['Field'], row['Default'], row['Type'].lower()
                if defVal != None:
                    res = sqlPool.query('select default(`%s`) as df from %s limit 1;' % (field, table),
                                            SqlPool.RET_DICT_ROW_FOR_KEY)
                    defVal = res[0]['df'] if res else defVal

                # caution ! here may cause bugs ...
                if (defVal is None) and row['Null'] == 'NO' and fieldType.find('char') != 0:
                    defVal = ''
                elif defVal is not None:
                    if fieldType.find('int') != -1: defVal = int(defVal)

                defVals[row['Field']] = defVal

            return defVals

# 每一个Dao都设一个假cache,如果使用memcache,在__initialize__时
class FakeCache(object):
    def get(self, key):
        return None
    def set(self, key, val, time = 0):
        return None
    def delete(self, key):
        return None

class DaoBase():
    def __init__(self, host, username, password, database, table):
        self._table = escape(table)
        self._sqlpool = SqlPool(host, username, password, database)
        self.cache = FakeCache()

    def dropTable(self):
        self._sqlpool.execute('DROP TABLES IF  EXISTS `%s`;' % self._table)

    def deploy(self):
        return self._sqlpool.execute(self._getTableStruct() % self._table)

if __name__ == '__main__':

    pool = SqlPool(
        host = '10.20.188.112',
        port = 3306,
        user = 'qing',
        passwd = 'admin',
        db = 'qing')

    print pool.query('show tables', SqlPool.RET_DICT_ROW_FOR_KEY)

    print pool.query('select * from qing_group limit 1', 1)

    for i in range(0, 1):
        print i


text:
using System;
using System.Collections.Generic;
using PaletteInsightAgent.Output;
using System.Configuration;
using Microsoft.Win32;
using System.IO;
using YamlDotNet.Serialization;
using NLog;
using PaletteInsightAgent.Helpers;
using PaletteInsightAgent.Output.OutputDrivers;
using System.Text.RegularExpressions;
using System.Management;

namespace PaletteInsightAgent
{
    namespace Configuration
    {
        /// <summary>
        /// A class for loading the configuration and converting it to
        /// the legacy PaletteInsightAgentOptions class.
        /// </summary>
        public class Loader
        {
            internal const string LOGFOLDER_DEFAULTS_FILE = "Config/LogFolders.yml";
            internal const string PROCESSES_DEFAULT_FILE = "Config/Processes.yml";
            private const string REPOSITORY_TABLES_FILE = "Config/Repository.yml";
            private const string TABLEAU_SERVER_APPLICATION_SERVICE_NAME = "tabsvc";
            private const int TABLEAU_VERSION_2018_2 = 20182;
            private static readonly Logger Log = LogManager.GetCurrentClassLogger();

            /// <summary>
            /// Do the conversion of config types
            /// </summary>
            /// <param name="conf"></param>
            /// <param name="outConfig">the PaletteInsightAgentOptions instance to update, since its a singleton, we cannot
            /// call its constructor, hence we cannot return it.</param>
            public static void LoadConfigTo(PaletteInsightConfiguration config, string tableauRoot, PaletteInsightAgentOptions options)
            {
                options.PollInterval = config.PollInterval;
                options.LogPollInterval = config.LogPollInterval;
                options.UploadInterval = config.UploadInterval;
                options.RepoTablesPollInterval = config.RepoTablesPollInterval;
                options.StreamingTablesPollInterval = config.StreamingTablesPollInterval;
                options.ThreadInfoPollInterval = config.ThreadInfoPollInterval;

                options.ProcessedFilestTTL = config.ProcessedFilesTTL;
                options.StorageLimit = config.StorageLimit;

                options.AllProcesses = config.AllProcesses;
                options.PreferPassiveRepository = config.PreferPassiveRepository;

                options.AuthToken = config.InsightAuthToken;

                if (config.Webservice != null)
                {
                    // Do not add the username or password here, as they come from the license
                    options.WebserviceConfig = new WebserviceConfiguration
                    {
                        Endpoint = config.Webservice.Endpoint,
                        UseProxy = config.Webservice.UseProxy,
                        ProxyAddress = config.Webservice.ProxyAddress,
                        ProxyUsername = config.Webservice.ProxyUsername,
                        ProxyPassword = config.Webservice.ProxyPassword
                    };
                }
                else
                {
                    // make sure the webservice config is null, so we wont write
                    // to the webservice if its not configured
                    options.WebserviceConfig = null;
                }

                // Load thread monitoring configuration
                options.Processes = new Dictionary<string, ProcessData>();
                foreach (var process in LoadProcessData())
                {
                    options.Processes.Add(process.Name, process);
                }

                options.RepositoryTables = LoadRepositoryTables();

                // Add the log folders based on the Tableau Data path from the registry
                AddLogFoldersToOptions(config, options, tableauRoot);

                // setup the polling options
                options.UseCounterSamples = config.UseCounterSamples;
                options.UseLogPolling = config.UseLogPolling;
                options.UseThreadInfo = config.UseThreadInfo;

                // Polling of Tableau repo and streaming tables needs to be executed only on primary nodes.
                // [...] for the legacy case UseRepoPolling is true by default and RepoTablesPollInterval is 0 to
                // disable repo polling so this would mean different behaviour with the same config file.
                options.UseRepoPolling = config.UseRepoPolling && config.RepoTablesPollInterval > 0;
                // and streaming tables is very similar and related to repo polling
                options.UseStreamingTables = config.UseRepoPolling && config.StreamingTablesPollInterval > 0;
                LoadRepositoryFromConfig(config, options);

                // set the maximum log lines
                options.LogLinesPerBatch = config.LogLinesPerBatch;

                options.StreamingTablesPollLimit = config.StreamingTablesPollLimit;
            }

            private static void LoadRepositoryFromConfig(PaletteInsightConfiguration config, PaletteInsightAgentOptions options)
            {
                if (!options.UseRepoPolling && !options.UseStreamingTables)
                {
                    return;
                }

                // load the tableau repo properties
                var repoProps = config.TableauRepo;
                if (repoProps == null)
                {
                    // Repository credentials are not filled in Config.yml
                    return;
                }

                try
                {
                    options.RepositoryDatabase = new DbConnectionInfo
                    {
                        Server = repoProps.Host,
                        Port = Convert.ToInt32(repoProps.Port),
                        Username = repoProps.User,
                        Password = repoProps.Password,
                        DatabaseName = repoProps.Database
                    };

                    Log.Info("Found Tableau repo credentials in Config.yml.");
                }
                catch (Exception e)
                {
                    Log.Error(e, "Failed to parse Tableau repository configs! Error:");
                }
            }

            public static PaletteInsightConfiguration LoadConfigFile(string filename)
            {
                try
                {
                    // deserialize the config
                    using (var reader = File.OpenText(filename))
                    {
                        IDeserializer deserializer = YamlDeserializer.Create();
                        var config = deserializer.Deserialize<PaletteInsightConfiguration>(reader);
                        return config;
                    }
                }
                catch (Exception e)
                {
                    Log.Fatal("Error during cofiguration loading: {0} -- {1}", filename, e);
                    return null;
                }
            }

            public static void UpdateWebserviceConfigFromLicense(PaletteInsightAgentOptions options)
            {
                // skip if we arent using the webservice
                if (options.WebserviceConfig == null) return;

                options.WebserviceConfig.AuthToken = options.AuthToken;
            }

            /// <summary>
            /// Add the tableau repo database details to the options.
            /// </summary>
            /// <param name="config"></param>
            /// <param name="options"></param>
            /// <param name="tableauRoot"></param>
            public static bool AddRepoFromWorkgroupYaml(PaletteInsightConfiguration config, string tableauRoot, PaletteInsightAgentOptions options)
            {
                var workgroupYmlPath = GetWorkgroupYmlPath(tableauRoot);
                Workgroup repo = GetRepoFromWorkgroupYaml(workgroupYmlPath, options.PreferPassiveRepository);
                if (repo == null)
                {
                    return false;
                }

                try
                {
                    if (IsEncrypted(repo.Password))
                    {
                        Log.Info("Encrypted readonly password found in workgroup.yml.");
                        // if (Tableau.getVersionNumber() >= TABLEAU_VERSION_2018_2)
                        // {
                        //     Log.Warn("Palette Insight cannot decrypt readonly user's password on Tableau Server 2018.2+! Credentials must be provided in Config.yml!");
                        //     return false;
                        // }

                        Log.Info("Getting readonly password with tabadmin command.");
                        repo.Password = Tableau.tabadminRun("get pgsql.readonly_password");
                    }
                    options.RepositoryDatabase = new DbConnectionInfo
                    {
                        Server = repo.Connection.Host,
                        Port = repo.Connection.Port,
                        Username = repo.Username,
                        Password = repo.Password,
                        DatabaseName = repo.Connection.DatabaseName
                    };

                    if (config.TableauRepo != null)
                    {
                        Log.Warn("Ignoring Tableau repo settings from config.yml.");
                    }
                    return true;
                }
                catch (Exception e)
                {
                    Log.Error(e, "Failed to acquire Tableau repo connection details! Exception: ");
                }

                return false;
            }

            #region log folders

            /// <summary>
            /// The log folders we are interested in, relative from the Tableau Data Root
            /// </summary>
            private static readonly LogFolder[] LOG_PATHS_IN_TABLEAU_DATA_FOLDER = new LogFolder[]
            {
                new LogFolder {Directory = @"tabsvc\vizqlserver\Logs", Filter = "*.txt" },
                new LogFolder {Directory =  @"tabsvc\logs\vizqlserver", Filter = "tabprotosrv*.txt" },
            };

            /// <summary>
            /// Adds a watched folder to the list of watched folders.
            /// </summary>
            /// <returns>If the folder was added</returns>
            private static bool AddFolderToWatched(ICollection<PaletteInsightAgentOptions.LogFolderInfo> logFolders, PaletteInsightAgentOptions.LogFolderInfo folder)
            {
                var folderValueString = folder.ToValueString();
                foreach (var logFolder in logFolders)
                {
                    // Skip if we already have this folder
                    if (String.Equals(logFolder.ToValueString(), folderValueString))
                    {
                        Log.Error("Skipping addition of duplicate watched path: {0}", folderValueString);
                        return false;
                    }
                }

                // If no matches found, add to the list of dirs
                logFolders.Add(folder);
                Log.Info("Watching folder: {0} with filter: {1} with format: {2}", folder.FolderToWatch, folder.DirectoryFilter, folder.LogFormat);
                return true;
            }

            /// <summary>
            /// Adds the log folders from either the config (if no tableau server is installed),
            /// or from the registry
            /// </summary>
            /// <param name="config"></param>
            /// <param name="options"></param>
            /// <param name="tableauRoot"></param>
            private static void AddLogFoldersToOptions(PaletteInsightConfiguration config, PaletteInsightAgentOptions options, string tableauRoot)
            {
                // check and load the log folder paths from the config file, so
                // the folders listed in there will be definitely watched
                if (config.Logs != null)
                {
                    foreach (LogFolder logFolder in config.Logs)
                    {
                        AddFolderToWatched(options.LogFolders,
                            PaletteInsightAgentOptions.LogFolderInfo.Create( logFolder.Directory, logFolder.Filter, logFolder.Format ));
                    }
                }

                if (tableauRoot != null)
                {
                    // otherwise try to add the log folders from the registry setup
                    foreach (var logFolder in LoadDefaultLogFolders())
                    {
                        var fullPath = Path.GetFullPath(Path.Combine(tableauRoot, logFolder.Directory));
                        // we check here so we won't add non-existent folders
                        if (!Directory.Exists(fullPath))
                        {
                            Log.Error("Log folder not found: {0}", fullPath);
                            continue;
                        }

                        AddFolderToWatched(options.LogFolders,
                            PaletteInsightAgentOptions.LogFolderInfo.Create(fullPath, logFolder.Filter, logFolder.Format));
                    }
                }
            }

            /// <summary>
            ///  Tries to load the default log folders from the log folders yaml file.
            ///  Since failing to load these disables parsing any logs, this
            ///  method throws its errors
            /// </summary>
            /// <returns></returns>
            internal static List<LogFolder> LoadDefaultLogFolders()
            {
                // load the defaults from the application
                // since PaletteInsightAgent always sets the current directory to its location,
                // we should always be in the correct folder for this to work
                using (var reader = File.OpenText(LOGFOLDER_DEFAULTS_FILE))
                {
                    IDeserializer deserializer = YamlDeserializer.Create();
                    return deserializer.Deserialize<List<LogFolder>>(reader);
                }
            }

            internal static bool IsEncrypted(string text)
            {
                var pattern = new Regex(@"^ENC\(.*\)$");
                var matched = pattern.Match(text);
                return matched.Success;
            }

            #endregion

            /// <summary>
            /// Helper to create a database configuration
            /// </summary>
            /// <param name="databaseConfig"></param>
            /// <returns></returns>
            private static DbConnectionInfo CreateDbConnectionInfo(DatabaseConfig databaseConfig)
            {
                DbConnectionInfo dbConnInfo = new DbConnectionInfo()
                {
                    Server = databaseConfig.Host,
                    Port = databaseConfig.Port,
                    Username = databaseConfig.User,
                    Password = databaseConfig.Password,
                    DatabaseName = databaseConfig.Database,
                    CommandTimeout = databaseConfig.CommandTimeout
                };

                if (!dbConnInfo.Valid())
                {
                    throw new ConfigurationErrorsException("Missing required database connection information!");
                }

                return dbConnInfo;
            }

            #region Tableau Registry info

            /// <summary>
            /// Retrieve Tableau's data folder path from the registry or figure it out
            /// based on its installation folder or fallback and try the usual path.
            /// </summary>
            /// <returns></returns>
            public static string FindTableauDataFolder()
            {
                // Primary nodes store the data folder location in the registry, except if
                // Tableau Server is installed on C: drive
                string dataFolderPath = SearchRegistryForTableauDataFolder();
                if (dataFolderPath != null)
                {
                    Log.Info("Found Tableau Data folder in registry: {0}", dataFolderPath);
                    return dataFolderPath;
                }

                // Look for it in the Tableau installation folder
                dataFolderPath = SearchDataFolderInInstallationFolder();
                if (dataFolderPath != null)
                {
                    Log.Info("Found Tableau Data folder in installation folder: {0}", dataFolderPath);
                    return dataFolderPath;
                }

                // Try the usual path as a last resort. The data folder is located here if you install
                // Tableau Server on drive C: according to Tableau documentation
                dataFolderPath = @"C:\ProgramData\Tableau\Tableau Server\data";
                if (Directory.Exists(dataFolderPath))
                {
                    Log.Info("Found Tableau Data folder at default location: {0}", dataFolderPath);
                    return dataFolderPath;
                }

                // No luck at all
                Log.Error("Could not find Tableau data folder!");
                return null;
            }

            /// <summary>
            /// Tries to read Tableau's data folder from the registry
            /// NOTE: This function works as long as Tableau versions are in X.X format
            /// </summary>
            /// <returns>null if no Tableau data folder is found in the registry </returns>
            private static string SearchRegistryForTableauDataFolder()
            {
                // Try all versions of tableau from highest to lowest
                using (var localKey = Environment.Is64BitOperatingSystem
                        ? RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64)
                        : RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32))
                {
                    RegistryKey tableauKey = localKey.OpenSubKey(@"Software\Tableau");
                    if (tableauKey == null)
                    {
                        return null;
                    }

                    Version latestTableauVersion = new Version("0.0");
                    string tableauDataFolder = null;

                    foreach (string key in tableauKey.GetSubKeyNames())
                    {
                        var pattern = new Regex(@"^Tableau Server ([0-9]+\.[0-9]+)");
                        var groups = pattern.Match(key).Groups;
                        // groups[0] is the entire match, thus we expect 2
                        if (groups.Count < 2)
                        {
                            continue;
                        }

                        Version version = new Version(groups[1].Value);
                        if (version > latestTableauVersion)
                        {
                            try
                            {
                                string directoriesRegPath = Path.Combine(key, "Directories");
                                using (RegistryKey dataFolderKey = tableauKey.OpenSubKey(directoriesRegPath))
                                {
                                    if (dataFolderKey == null)
                                    {
                                        continue;
                                    }
                                    Object dataValue = dataFolderKey.GetValue("Data");
                                    if (dataValue == null)
                                    {
                                        continue;
                                    }

                                    string possibleDataFolder = dataValue as String;
                                    if (!Directory.Exists(possibleDataFolder))
                                    {
                                        continue;
                                    }
                                    latestTableauVersion = version;
                                    tableauDataFolder = possibleDataFolder;
                                }
                            }
                            catch (Exception)
                            {
                                // no problem, only means this is not our version
                                continue;
                            }
                        }
                    }
                    tableauKey.Close();

                    if (tableauDataFolder == null)
                    {
                        return null;
                    }

                    return tableauDataFolder;
                }
            }

            /// <summary>
            /// Try to find the Tableau data folder in the Tableau Installation folder,
            /// which is calculated based on the path of the Tableau Server Application
            /// Manager (tabsvc) service.
            ///
            /// For worker nodes this is the way we can discover Tableau data folder, if
            /// it is not located in the default directory.
            /// </summary>
            /// <returns></returns>
            private static string SearchDataFolderInInstallationFolder()
            {
                string tableauInstallFolder = RetrieveTableauInstallationFolder();
                if (tableauInstallFolder == null)
                {
                    Log.Warn("Could not find Tableau installation folder!");
                    return null;
                }

                string dataFolderPath = Path.Combine(tableauInstallFolder, "data");
                if (!Directory.Exists(dataFolderPath))
                {
                    return null;
                }

                return dataFolderPath;
            }

            private static string RetrieveTableauInstallationFolder()
            {
                string tabsvcPath = GetPathOfService(TABLEAU_SERVER_APPLICATION_SERVICE_NAME);
                return ExtractTableauInstallationFolder(tabsvcPath);
            }

            public static string RetrieveTableauBinFolder()
            {
                string tabsvcPath = GetPathOfService(TABLEAU_SERVER_APPLICATION_SERVICE_NAME);
                return ExtractTableauBinFolder(tabsvcPath);
            }

            // This function is created only for unit testing, since it is pretty difficult
            // to mock static functions in C#
            internal static string ExtractTableauInstallationFolder(string tabsvcPath)
            {
                var matchGroups = ParseTabsvcPath(tabsvcPath);
                if (matchGroups == null)
                {
                    Log.Warn("Failed to extract Tableau installation folder from: {0}", tabsvcPath);
                    return null;
                }

                return matchGroups[1].Value;
            }

            // This function is created only for unit testing, since it is pretty difficult
            // to mock static functions in C#
            internal static string ExtractTableauBinFolder(string tabsvcPath)
            {
                if (tabsvcPath == null)
                {
                    Log.Warn("Failed to extract Tableau bin folder as the path to 'tabsvc' service is null!");
                    return null;
                }

                // Extract the installation folder out of the tabsvc path. We are going to
                // chop tabsvc.exe  from the end of the tabsvc path.
                var pattern = new Regex(@"""?(.*[\\\/]+bin[\\\/]+?)tabsvc.exe.*");
                var groups = pattern.Match(tabsvcPath).Groups;
                // groups[0] is the entire match, thus we expect at least 2
                if (groups.Count < 2)
                {
                    Log.Warn("Failed to extract Tableau bin folder from 'tabsvc' path: '{0}'", tabsvcPath);
                    return null;
                }

                return groups[1].Value;
            }

            // This function is acquired from StackOverflow:
            // http://stackoverflow.com/questions/2728578/how-to-get-phyiscal-path-of-windows-service-using-net
            // (with a bit of more careful object disposal)
            public static string GetPathOfService(string serviceName)
            {
                WqlObjectQuery wqlObjectQuery = new WqlObjectQuery(string.Format("SELECT * FROM Win32_Service WHERE Name like '{0}%'", serviceName));
                using (ManagementObjectSearcher managementObjectSearcher = new ManagementObjectSearcher(wqlObjectQuery))
                using (ManagementObjectCollection managementObjectCollection = managementObjectSearcher.Get())
                {
                    foreach (ManagementObject managementObject in managementObjectCollection)
                    {
                        return managementObject.GetPropertyValue("PathName").ToString();
                    }
                }

                return null;
            }
            #endregion

            #region private Repository parts

            /// <summary>
            /// Deserialization struct for the repo config from the workgroup.yml
            /// </summary>
            public class Workgroup
            {
                [YamlMember(Alias = "pgsql.readonly.enabled")]
                public bool ReadonlyEnabled { get; set; }

                [YamlMember(Alias = "pgsql.readonly_username")]
                public string Username { get; set; }

                [YamlMember(Alias = "pgsql.readonly_password")]
                public string Password { get; set; }

                [YamlMember(Alias = "pgsql.connections.yml")]
                public string ConnectionsFile { get; set; }

                [YamlMember(Alias = "pgsql0.host")]
                public string PgHost0 { get; set; }

                [YamlMember(Alias = "pgsql0.port")]
                public int PgPort0 { get; set; }

                [YamlMember(Alias = "pgsql1.host")]
                public string PgHost1 { get; set; }

                [YamlMember(Alias = "pgsql1.port")]
                public int PgPort1 { get; set; }

                public TableauConnectionInfo Connection { get; set; }
            }

            public class TableauConnectionInfo
            {
                [YamlMember(Alias = "pgsql.host")]
                public string Host { get; set; }

                [YamlMember(Alias = "pgsql.port")]
                public int Port { get; set; }

                // It is not possible to change it @Tableau so we hardcode it for now
                public readonly string DatabaseName = "workgroup";
            }

            private static bool IsValidRepoData(Workgroup workgroup)
            {
                if (!workgroup.ReadonlyEnabled)
                {
                    Log.Warn("Readonly user is not enabled! Repo credentials must be entered into Config.yml.");
                    return false;
                }

                if (workgroup.Username == null)
                {
                    Log.Error("Tableau repo username is null! Repo credentials must be entered into Config.yml.");
                    return false;
                }

                if (workgroup.Password == null)
                {
                    Log.Error("Tableau repo password is null! Repo credentials must be entered into Config.yml.");
                    return false;
                }

                if (workgroup.Connection.Host == null)
                {
                    Log.Error("Tableau repo hostname is null! Repo credentials must be entered into Config.yml.");
                    return false;
                }

                return true;
            }

            public static string GetWorkgroupYmlPath(string tableauRoot)
            {
                if (tableauRoot == null)
                {
                    Log.Error("Tableau data folder path must not be null while reading and YAML configs!");
                    return null;
                }
                //Up to Tableau 2018.1
                var workgroupYmlPath = Path.Combine(tableauRoot, "tabsvc", "config", "workgroup.yml");

                //From Tabaleau 2018.2
                if (!File.Exists(workgroupYmlPath))
                {
                    try
                    {
                        string[] configFilePaths = Directory.GetFiles(Path.Combine(tableauRoot, "tabsvc", "config"), "workgroup.yml", SearchOption.AllDirectories);
                        foreach (string configPath in configFilePaths)
                        {
                            // The workgroup.yml files are stored in sub-folders of the tabsvc/data/config folder.
                            // We found that the clustercontroller_* folder exists on every node. Previously we used the
                            // pgsql_* folders, but they exist only on the repository nodes.
                            string pattern = @".*clustercontroller_.*";
                            Match m = Regex.Match(configPath, pattern);
                            if (m.Success)
                            {
                                workgroupYmlPath = configPath;
                                Log.Info("Config file path: {0}", workgroupYmlPath);
                                break;
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        Log.Error(e, "Cannot find workgroup.yml file");
                        return null;
                    }

                }
                return workgroupYmlPath;
            }

            public static Workgroup GetRepoFromWorkgroupYaml(string workgroupYmlPath, bool preferPassiveRepo)
            {
                if (workgroupYmlPath == null)
                {
                    Log.Error("Path for workgroup.yml must not be null while reading configs!");
                    return null;
                }

                try
                {
                    // Get basic info from workgroup yml. Everything else from connections.yml
                    IDeserializer deserializer = YamlDeserializer.Create();

                    Workgroup workgroup = null;
                    using (var workgroupFile = File.OpenText(workgroupYmlPath))
                    {
                        workgroup = deserializer.Deserialize<Workgroup>(workgroupFile);
                        using (var connectionsFile = File.OpenText(workgroup.ConnectionsFile))
                        {
                            workgroup.Connection = deserializer.Deserialize<TableauConnectionInfo>(connectionsFile);
                            // workgroup.Connection.Host always contains the active repo
                            if (preferPassiveRepo)
                            {
                                if (workgroup.PgHost0 != null && workgroup.PgHost1 != null)
                                {
                                    // Use passive repo if possible/exists
                                    if (workgroup.Connection.Host != workgroup.PgHost0)
                                    {
                                        workgroup.Connection.Host = workgroup.PgHost0;
                                        workgroup.Connection.Port = workgroup.PgPort0;
                                    }
                                    else
                                    {
                                        workgroup.Connection.Host = workgroup.PgHost1;
                                        workgroup.Connection.Port = workgroup.PgPort1;
                                    }
                                    Log.Info("Based on workgroup.yml, passive repository host is: '{0}' with port: '{1}'", workgroup.Connection.Host, workgroup.Connection.Port);
                                }
                                else
                                {
                                    Log.Info("Passive repo is preferred as target Tableau repo, but '{0}' does not contain passive repo node information", workgroupYmlPath);
                                }
                            }
                            else
                            {
                                Log.Info("Active Tableau repo is configured to be the target repo");
                            }
                        }
                        if (!IsValidRepoData(workgroup))
                        {
                            return null;
                        }
                    }

                    return workgroup;
                }
                catch (Exception e)
                {
                    Log.Error(e, "Error while trying to load and parse YAML config from '{0}' Exception: ", workgroupYmlPath);
                }
                return null;
            }

            internal static GroupCollection ParseTabsvcPath(string tabsvcPath)
            {
                if (tabsvcPath == null)
                {
                    Log.Warn("Failed to extract Tableau Installation folder as the path to 'tabsvc' service is null!");
                    return null;
                }

                // Extract the installation folder out of the tabsvc path. We are going to
                // chop <one_folder>\bin\tabsvc.exe from the end of the tabsvc path.
                var pattern = new Regex(@"""?(.*?)[\\\/]+[^\\\/]+[\\\/]+bin[\\\/]+tabsvc.exe.*");
                var groups = pattern.Match(tabsvcPath).Groups;
                // groups[0] is the entire match, thus we expect at least 2
                if (groups.Count < 2)
                {
                    // Onwards Tableau Server 2018.2 the tabsvc.exe location is slightly different. In this case
                    // we are going to chop data\tabsvc\services\<tabsvc_version_folder>\tabsvc\tabsvc.exe from the
                    // end of the tabsvc path.
                    pattern = new Regex(@"""?(.*?)[\\\/]+data[\\\/]+tabsvc[\\\/]+services[\\\/]+([^\\\/]+)[\\\/]+tabsvc[\\\/]+tabsvc.exe.*");
                    groups = pattern.Match(tabsvcPath).Groups;
                    if (groups.Count < 3)
                    {
                        Log.Warn("Failed to extract Tableau Installation folder from 'tabsvc' path: '{0}'", tabsvcPath);
                        return null;
                    }
                }

                return groups;
            }

            #endregion

            #region process defaults

            /// <summary>
            ///  Tries to load the default process names from the process names yaml file.
            ///  Since failing to load these disables parsing any processs, this
            ///  method throws its errors
            /// </summary>
            /// <returns></returns>
            internal static List<ProcessData> LoadProcessData()
            {
                // since PaletteInsightAgent always sets the current directory to its location,
                // we should always be in the correct folder for this to work
                using (var reader = File.OpenText(PROCESSES_DEFAULT_FILE))
                {
                    IDeserializer deserializer = YamlDeserializer.Create();
                    return deserializer.Deserialize<List<ProcessData>>(reader);
                }
            }

            private static List<RepoTable> LoadRepositoryTables()
            {
                using (var reader = File.OpenText(REPOSITORY_TABLES_FILE))
                {
                    IDeserializer deserializer = YamlDeserializer.Create();
                    return deserializer.Deserialize<List<RepoTable>>(reader);
                }
            }

            #endregion
        }
    }
}


text:
<!doctype html>

    <title>Stoke2</title>

    <link rel="stylesheet" href="https://manglekuo.com/i-v/styles.css?v=2">

    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">

Stoke's Theorem

                Size of the Surface:
                    2

                    <input id="xController" class="inputs" type="range" value="5" min="0" max="2" step="0.1"/>
                    02

                Shape of the Loop:
                    2

                    <input id="yController" class="inputs" type="range" value="5" min="2" max="8" step="2"/>
                    28
                <input id="animate" class="button-primary" type="submit" value="Play">

 Stoke's Theorem:

Stoke's theorem relates the integral of the curl of a vector field, V, over an open surface S to the path integral of the vector field around a loop C defining the surface boundary.

Mathematically, this can be written as
                            $$ \iint_{S} \nabla \times \vec{V} \cdot \vec{dS} = \oint_C \vec{V} \cdot \vec{dr}$$
                            Where dS is the surface normal vector and dr is the path tangent vector.

                            As the right hand side of the equation is independent of the surface, the integral of the curl of a vector field over a surface is independent of the surface itself, but is only determined by the curve bounding it.

 Therefore, changing the surface by moving the first slider doesn't change the value of the integral, however, modifying the loop by moving the second slider does.


text:
package br.edu.fatecfranca.list6;

public class Tv extends Product {
	private String channel="5";

	public String watch() {
		return this.channel;
	}

	public void changeChannel(String channel) {
		this.channel = channel;
	}

	public String toString() {
		return super.toString() + " Channel: " + this.watch();
	}
}


text:
byteseeker
==========

Sketches for the Byteseeker Jr.


text:
require 'facter'
require 'facter/util/fact'
require 'facter/util/loader'

# Manage which facts exist and how we access them.  Largely just a wrapper
# around a hash of facts.
class Facter::Util::Collection
  # Return a fact object by name.  If you use this, you still have to call
  # 'value' on it to retrieve the actual value.
  def [](name)
    value(name)
  end

  # Add a resolution mechanism for a named fact.  This does not distinguish
  # between adding a new fact and adding a new way to resolve a fact.
  def add(name, options = {}, &block)
    name = canonize(name)

    unless fact = @facts[name]
      fact = Facter::Util::Fact.new(name)

      @facts[name] = fact
    end

    # Set any fact-appropriate options.
    options.each do |opt, value|
      method = opt.to_s + "="
      if fact.respond_to?(method)
        fact.send(method, value)
        options.delete(opt)
      end
    end

    if block_given? and resolve = fact.add(&block)
      # If the resolve was actually added, set any resolve-appropriate options
      options.each do |opt, value|
        method = opt.to_s + "="
        if resolve.respond_to?(method)
          resolve.send(method, value)
          options.delete(opt)
        end
      end
    end

    unless options.empty?
      raise ArgumentError, "Invalid facter option(s) %s" % options.keys.collect { |k| k.to_s }.join(",")
    end

    return fact
  end

  include Enumerable

  # Iterate across all of the facts.
  def each
    @facts.each do |name, fact|
      value = fact.value
      unless value.nil?
        yield name.to_s, value
      end
    end
  end

  # Return a fact by name.
  def fact(name)
    name = canonize(name)

    # Try to load the fact if necessary
    loader.load(name) unless @facts[name]

    # Try HARDER
    loader.load_all unless @facts[name]

    @facts[name]
  end

  # Flush all cached values.
  def flush
    @facts.each { |name, fact| fact.flush }
  end

  def initialize
    @facts = Hash.new
  end

  # Return a list of all of the facts.
  def list
    return @facts.keys
  end

  # Load all known facts.
  def load_all
    loader.load_all
  end

  # The thing that loads facts if we don't have them.
  def loader
    unless defined?(@loader)
      @loader = Facter::Util::Loader.new
    end
    @loader
  end

  # Return a hash of all of our facts.
  def to_hash
    @facts.inject({}) do |h, ary|
      value = ary[1].value
      if ! value.nil?
        # For backwards compatibility, convert the fact name to a string.
        h[ary[0].to_s] = value
      end
      h
    end
  end

  def value(name)
    if fact = fact(name)
      fact.value
    end
  end

  private

  # Provide a consistent means of getting the exact same fact name
  # every time.
  def canonize(name)
    name.to_s.downcase.to_sym
  end
end


text:
<!DOCTYPE html>

    <meta charset="utf-8"/>

    <link rel="stylesheet" href="style.css">

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">

        Trashketball

    <canvas id="game" width="1000" height="600" style="background: url('resources/EmptyBleachers.png'); margin: 20px;">

Your browser doesn't support canvas.

    </canvas>

        <input type="range" id="volume-range" min="0" max="100" step="1" value="75"
            oninput="game.setVolume(this.value);" onchange="game.setVolume(this.value);">

        Directions:

        WASD to Move. SHIFT to run. SPACE to jump. J to kick. K to head. ESCAPE to pause. Get the ball in the trash can!

        Advanced: J+W: Kick up, J+A: Kick left, J+S: Kick down, J+D: Kick right, H+W: Head up, H+A: Head left, H+S: Head down, H+D: Head right.


text:
package lang

import (
	"gojvm/native"
	"unsafe"
)
import "gojvm/rtda"
import "gojvm/rtda/heap"

const jlSystem = "java/lang/System"

func init() {
	native.Register(jlSystem, "arraycopy", "(Ljava/lang/Object;ILjava/lang/Object;II)V", arraycopy)
	native.Register(jlSystem, "identityHashCode", "(Ljava/lang/Object;)I", identityHashCode)
}

// public static native void arraycopy(Object src, int srcPos, Object dest, int destPos, int length)
// (Ljava/lang/Object;ILjava/lang/Object;II)V
func arraycopy(frame *rtda.Frame) {
	vars := frame.LocalVars()
	src := vars.GetRef(0)
	srcPos := vars.GetInt(1)
	dest := vars.GetRef(2)
	destPos := vars.GetInt(3)
	length := vars.GetInt(4)

	if src == nil || dest == nil {
		panic("java.lang.NullPointerException")
	}
	if !checkArrayCopy(src, dest) {
		panic("java.lang.ArrayStoreException")
	}
	if srcPos < 0 || destPos < 0 || length < 0 ||
		srcPos+length > src.ArrayLength() ||
		destPos+length > dest.ArrayLength() {
		panic("java.lang.IndexOutOfBoundsException")
	}

	heap.ArrayCopy(src, dest, srcPos, destPos, length)
}

func checkArrayCopy(src, dest *heap.Object) bool {
	srcClass := src.Class()
	destClass := dest.Class()

	if !srcClass.IsArray() || !destClass.IsArray() {
		return false
	}
	if srcClass.ComponentClass().IsPrimitive() ||
		destClass.ComponentClass().IsPrimitive() {
		return srcClass == destClass
	}
	return true
}

// public static native int identityHashCode(Object x);
// (Ljava/lang/Object;)I
func identityHashCode(frame *rtda.Frame) {
	vars := frame.LocalVars()
	ref := vars.GetRef(0)

	// todo
	hashCode := int32(uintptr(unsafe.Pointer(ref)))
	stack := frame.OperandStack()
	stack.PushInt(hashCode)
}


text:
<?php

/**
 * Channel to a Mercurial "cmdserver" server. Messages sent to the server
 * look like this:
 *
 *   runcommand\n
 *   8                   # Length, as a 4-byte unsigned long.
 *   log\0
 *   -l\0
 *   5
 *
 * In PHP, the format of these messages is an array of arguments:
 *
 *   array(
 *     'runcommand',
 *     'log',
 *     '-l',
 *     '5',
 *   );
 *
 * The server replies with messages that look like this:
 *
 *   o
 *   1234                # Length, as a 4-byte unsigned long.
 *   <data: 1234 bytes>
 *
 * The first character in a message from the server is the "channel". Mercurial
 * channels have nothing to do with Phutil channels; they are more similar to
 * stdout/stderr. Mercurial has four primary channels:
 *
 *   'o'utput, like stdout
 *   'e'rror, like stderr
 *   'r'esult, like return codes
 *   'd'ebug, like an external log file
 *
 * In PHP, the format of these messages is a pair, with the channel and then
 * the data:
 *
 *   array('o', '<data...>');
 *
 * In general, we send "runcommand" requests, and the server responds with
 * a series of messages on the "output" channel and then a single response
 * on the "result" channel to indicate that output is complete.
 *
 * @task protocol Protocol Implementation
 */
final class ArcanistHgServerChannel extends PhutilProtocolChannel {

  const MODE_CHANNEL = 'channel';
  const MODE_LENGTH  = 'length';
  const MODE_BLOCK   = 'block';

  private $mode                   = self::MODE_CHANNEL;
  private $byteLengthOfNextChunk  = 1;
  private $buf                    = '';

/* -(  Protocol Implementation  )-------------------------------------------- */

  /**
   * Encode a message for transmission to the server. The message should be
   * formatted as an array, like this:
   *
   *   array(
   *     'runcommand',
   *     'log',
   *     '-l',
   *     '5',
   *   );
   *
   *
   * We will return the cmdserver version of this:
   *
   *   runcommand\n
   *   8                   # Length, as a 4-byte unsigned long.
   *   log\0
   *   -l\0
   *   5
   *
   * @param list<string> List of command arguments.
   * @return string Encoded string for transmission to the server.
   *
   * @task protocol
   */
  protected function encodeMessage($argv) {
    if (!is_array($argv)) {
      throw new Exception("Message to Mercurial server should be an array.");
    }

    $command = head($argv);
    $args = array_slice($argv, 1);

    $args = implode("\0", $args);

    $len = strlen($args);
    $len = pack('N', $len);

    return "{$command}\n{$len}{$args}";
  }

  /**
   * Decode a message received from the server. The message looks like this:
   *
   *   o
   *   1234                # Length, as a 4-byte unsigned long.
   *   <data: 1234 bytes>
   *
   * ...where 'o' is the "channel" the message is being sent over.
   *
   * We decode into a pair in PHP, which looks like this:
   *
   *   array('o', '<data...>');
   *
   * @param string Bytes from the server.
   * @return list<pair<string,string>> Zero or more complete messages.
   *
   * @task protocol
   */
  protected function decodeStream($data) {
    $this->buf .= $data;

    // We always know how long the next chunk is, so this parser is fairly
    // easy to implement.

    $messages = array();
    while ($this->byteLengthOfNextChunk <= strlen($this->buf)) {
      $chunk = substr($this->buf, 0, $this->byteLengthOfNextChunk);
      $this->buf = substr($this->buf, $this->byteLengthOfNextChunk);

      switch ($this->mode) {
        case self::MODE_CHANNEL:
          // We've received the channel name, one of 'o', 'e', 'r' or 'd' for
          // 'output', 'error', 'result' or 'debug' respectively. This is a
          // single byte long. Next, we'll expect a length.

          $this->channel = $chunk;
          $this->byteLengthOfNextChunk = 4;
          $this->mode = self::MODE_LENGTH;
          break;
        case self::MODE_LENGTH:
          // We've received the length of the data, as a 4-byte big-endian
          // unsigned integer. Next, we'll expect the data itself.

          $this->byteLengthOfNextChunk = head(unpack('N', $chunk));
          $this->mode = self::MODE_BLOCK;
          break;
        case self::MODE_BLOCK:
          // We've received the data itself, which is a block of bytes of the
          // given length. We produce a message from the channel and the data
          // and return it. Next, we expect another channel name.

          $message = array($this->channel, $chunk);

          $this->byteLengthOfNextChunk = 1;
          $this->mode = self::MODE_CHANNEL;
          $this->channel = null;

          $messages[] = $message;
          break;
      }
    }

    // Return zero or more messages, which might look something like this:
    //
    //   array(
    //     array('o', '<...>'),
    //     array('o', '<...>'),
    //     array('r', '<...>'),
    //   );

    return $messages;
  }

}


text:
import Model from 'ember-data/model';
import attr from 'ember-data/attr';
import { belongsTo } from 'ember-data/relationships';

export default Model.extend({
	view: attr('boolean'),
	edit: attr('boolean'),
	play: attr('boolean'),
	record: attr('boolean'),
	topic_id: belongsTo('topic'),
	language_id: belongsTo('language'),
	topic_item_id: belongsTo('topic-item'),
	topic_phrase_id: belongsTo('topic-phrase'),
	lesson_id: belongsTo('lesson')
});


text:
package speciemongo.net.speciemongo;

import android.app.Application;
import android.os.StrictMode;

import com.instabug.library.IBGInvocationEvent;
import com.instabug.library.Instabug;
import com.mapbox.mapboxsdk.MapboxAccountManager;

/**
 * The {@link Application} implementation for the app.
 */
public class SgApplication extends Application {

    @Override
    public void onCreate() {
        super.onCreate();

        // If we are in debug mode,
        if(BuildConfig.DEBUG) {

            // Enable strict mode
            StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
                    .detectAll()
                    .penaltyLog()
                    .build());
            StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
                    .detectAll()
                    .penaltyLog()
                    .build());

        }

        // TODO change handled failure logs to Instabug in beta
        // Initialize Instabug
        new Instabug.Builder(this, this.getString(R.string.keychain_instabug_start_token))
                .setInvocationEvent(IBGInvocationEvent.IBGInvocationEventShake)
                .setShouldShowIntroDialog(false)
                .setDebugEnabled(true)
                .build();

    }
}


text:
using Nethereum.RPC.Infrastructure;
using Newtonsoft.Json.Linq;

namespace Nethereum.Geth.RPC.Debug
{
    public interface IDebugGcStats : IGenericRpcRequestResponseHandlerNoParam<JObject>
    {

    }
}


text:
#pragma once
#include <aws/chime/Chime_EXPORTS.h>
#include <aws/chime/model/ErrorCode.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>

namespace Aws
{
namespace Utils
{
namespace Json
{
  class JsonValue;
  class JsonView;
} // namespace Json
} // namespace Utils
namespace Chime
{
namespace Model
{

  /**
   *
One or more of the resources in the request does not exist in the
   * system.

See Also:
   AWS
   * API Reference

   */
  class AWS_CHIME_API NotFoundException
  {
  public:
    NotFoundException();
    NotFoundException(Aws::Utils::Json::JsonView jsonValue);
    NotFoundException& operator=(Aws::Utils::Json::JsonView jsonValue);
    Aws::Utils::Json::JsonValue Jsonize() const;

    inline const ErrorCode& GetCode() const{ return m_code; }

    inline bool CodeHasBeenSet() const { return m_codeHasBeenSet; }

    inline void SetCode(const ErrorCode& value) { m_codeHasBeenSet = true; m_code = value; }

    inline void SetCode(ErrorCode&& value) { m_codeHasBeenSet = true; m_code = std::move(value); }

    inline NotFoundException& WithCode(const ErrorCode& value) { SetCode(value); return *this;}

    inline NotFoundException& WithCode(ErrorCode&& value) { SetCode(std::move(value)); return *this;}

    inline const Aws::String& GetMessage() const{ return m_message; }

    inline bool MessageHasBeenSet() const { return m_messageHasBeenSet; }

    inline void SetMessage(const Aws::String& value) { m_messageHasBeenSet = true; m_message = value; }

    inline void SetMessage(Aws::String&& value) { m_messageHasBeenSet = true; m_message = std::move(value); }

    inline void SetMessage(const char* value) { m_messageHasBeenSet = true; m_message.assign(value); }

    inline NotFoundException& WithMessage(const Aws::String& value) { SetMessage(value); return *this;}

    inline NotFoundException& WithMessage(Aws::String&& value) { SetMessage(std::move(value)); return *this;}

    inline NotFoundException& WithMessage(const char* value) { SetMessage(value); return *this;}

  private:

    ErrorCode m_code;
    bool m_codeHasBeenSet = false;

    Aws::String m_message;
    bool m_messageHasBeenSet = false;
  };

} // namespace Model
} // namespace Chime
} // namespace Aws


text:
layout: post
unique_id: emperor's_soul
title: Emperor's SOul
categories: []
locations:
---

YESTERDAY:
* finished Emperor's Soul
  * excellent short story
* stayed up late working on a demo
* pork chops for dinner!
  * super tasty
  * also very unhealthy
  * stir-fried veggies didn't really help

TODAY:
* deathnote with thorvald
* finished a bunch of episodes from Brooklyn 99
* ordered takeout from Cooking Papa
  * so heavy xD

LEARNINGS:
* I'm gaining weight :(
* need to eat healthier!


text:
title: "About"
bg: '#80BCA3'
color: white
fa-icon: question-circle
---

***Rice Launch is a student-led organization with the goal of connecting, energizing, and enabling Rice students to initiate and pursue their own entrepreneurial ventures. Rooted in the values of awareness, education, and collaboration within the startup community, Rice Launch is a platform and a central resource for students to turn unconventional wisdom into successful startups.***


text:
"""Test that an async context manager receives a proper object."""
# pylint: disable=missing-docstring, import-error, too-few-public-methods
import contextlib

from ala import Portocala

@contextlib.contextmanager
def ctx_manager():
    yield

class ContextManager(object):
    def __enter__(self):
        pass
    def __exit__(self, *args):
        pass

class PartialAsyncContextManager(object):
    def __aenter__(self):
        pass

class SecondPartialAsyncContextManager(object):
    def __aexit__(self, *args):
        pass

class UnknownBases(Portocala):
    def __aenter__(self):
        pass

class AsyncManagerMixin(object):
    pass

class GoodAsyncManager(object):
    def __aenter__(self):
        pass
    def __aexit__(self, *args):
        pass

class InheritExit(object):
    def __aexit__(self, *args):
        pass

class SecondGoodAsyncManager(InheritExit):
    def __aenter__(self):
        pass

async def bad_coro():
    async with 42: # [not-async-context-manager]
        pass
    async with ctx_manager(): # [not-async-context-manager]
        pass
    async with ContextManager(): # [not-async-context-manager]
        pass
    async with PartialAsyncContextManager(): # [not-async-context-manager]
        pass
    async with SecondPartialAsyncContextManager(): # [not-async-context-manager]
        pass

async def good_coro():
    async with UnknownBases():
        pass
    async with AsyncManagerMixin():
        pass
    async with GoodAsyncManager():
        pass
    async with SecondGoodAsyncManager():
        pass


text:
title: Best Practices of Data Migration in the Shard Merge Scenario
summary: Learn the best practices of data migration in the shard merge scenario.
aliases: ['/docs/tidb-data-migration/dev/shard-merge-best-practices/']
---

# Best Practices of Data Migration in the Shard Merge Scenario

This document describes the features and limitations of [TiDB Data Migration](https://github.com/pingcap/dm) (DM) in the shard merge scenario and provides a data migration best practice guide for your application (the default "pessimistic" mode is used).

## Use a separate data migration task

In the [Merge and Migrate Data from Sharded Tables](/dm/feature-shard-merge-pessimistic.md#principles) document, the definition of "sharding group" is given: A sharding group consists of all upstream tables that need to be merged and migrated into the same downstream table.

The current sharding DDL mechanism has some [usage restrictions](/dm/feature-shard-merge-pessimistic.md#restrictions) to coordinate the schema changes brought by DDL operations in different sharded tables. If these restrictions are violated due to unexpected reasons, you need to [handle sharding DDL locks manually in DM](/dm/manually-handling-sharding-ddl-locks.md), or even redo the entire data migration task.

To mitigate the impact on data migration when an exception occurs, it is recommended to merge and migrate each sharding group as a separate data migration task. **This might enable that only a small number of data migration tasks need to be handled manually while others remain unaffected.**

## Handle sharding DDL locks manually

You can easily conclude from [Merge and Migrate Data from Sharded Tables](/dm/feature-shard-merge-pessimistic.md#principles) that DM's sharding DDL lock is a mechanism for coordinating the execution of DDL operations to the downstream from multiple upstream sharded tables.

Therefore, when you find any sharding DDL lock on `DM-master` through `shard-ddl-lock` command, or any `unresolvedGroups` or `blockingDDLs` on some DM-workers through `query-status` command, do not rush to manually release the sharding DDL lock through `shard-ddl-lock unlock` commands.

Instead, you can:

- Follow the corresponding manual solution to handle the scenario if the failure of automatically releasing the sharding DDL lock is one of the [listed abnormal scenarios](/dm/manually-handling-sharding-ddl-locks.md#supported-scenarios).
- Redo the entire data migration task if it is an unsupported scenario: First, empty the data in the downstream database and the `dm_meta` information associated with the migration task; then, re-execute the full and incremental data replication.

## Handle conflicts between primary keys or unique indexes across multiple sharded tables

Data from multiple sharded tables might cause conflicts between the primary keys or unique indexes. You need to check each primary key or unique index based on the sharding logic of these sharded tables. The following are three cases related to primary keys or unique indexes:

- Shard key: Usually, the same shard key only exists in one sharded table, which means no data conflict is caused on shard key.
- Auto-increment primary key: The auto-increment primary key of each sharded tables counts separately, so their range might overlap. In this case, you need to refer to the next section [Handle conflicts of auto-increment primary key](/dm/shard-merge-best-practices.md#handle-conflicts-of-auto-increment-primary-key) to solve it.
- Other primary keys or unique indexes: you need to analyze them based on the business logic. If data conflict, you can also refer to the next section [Handle conflicts of auto-increment primary key](/dm/shard-merge-best-practices.md#handle-conflicts-of-auto-increment-primary-key) to solve it.

## Handle conflicts of auto-increment primary key

This section introduces two recommended solutions to handle conflicts of auto-increment primary key.

### Remove the `PRIMARY KEY` attribute from the column

Assume that the upstream schemas are as follows:

```sql
CREATE TABLE `tbl_no_pk` (
  `auto_pk_c1` bigint(20) NOT NULL,
  `uk_c2` bigint(20) NOT NULL,
  `content_c3` text,
  PRIMARY KEY (`auto_pk_c1`),
  UNIQUE KEY `uk_c2` (`uk_c2`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
```

If the following requirements are satisfied:

- The `auto_pk_c1` column has no impact on the application and does not depend on the column's `PRIMARY KEY` attribute.
- The `uk_c2` column has the `UNIQUE KEY` attribute, and it is globally unique in all upstream sharded tables.

Then you can perform the following steps to fix the `ERROR 1062 (23000): Duplicate entry '***' for key 'PRIMARY'` error that is possibly caused by the `auto_pk_c1` column when you merge sharded tables.

1. Before the full data migration, create a table in the downstream database for merging and migrating data, and modify the `PRIMARY KEY` attribute of the `auto_pk_c1` column to normal index.

    ```sql
    CREATE TABLE `tbl_no_pk_2` (
      `auto_pk_c1` bigint(20) NOT NULL,
      `uk_c2` bigint(20) NOT NULL,
      `content_c3` text,
      INDEX (`auto_pk_c1`),
      UNIQUE KEY `uk_c2` (`uk_c2`)
    ) ENGINE=InnoDB DEFAULT CHARSET=latin1
    ```

2. Add the following configuration in `task.yaml` to skip the check of auto-increment primary key conflict:

    ```yaml
    ignore-checking-items: ["auto_increment_ID"]
    ```

3. Start the full and incremental data replication task.

4. Run `query-status` to verify whether the data migration task is successfully processed and whether the data from the upstream has already been merged and migrated to the downstream database.

### Use a composite primary key

Assume that the upstream schemas are as follows:

```sql
CREATE TABLE `tbl_multi_pk` (
  `auto_pk_c1` bigint(20) NOT NULL,
  `uuid_c2` bigint(20) NOT NULL,
  `content_c3` text,
  PRIMARY KEY (`auto_pk_c1`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
```

If the following requirements are satisfied:

* The application does not depend on the `PRIMARY KEY` attribute of the `auto_pk_c1` column.
* The composite primary key that consists of the `auto_pk_c1` and `uuid_c2` columns is globally unique.
* It is acceptable to use a composite primary key in the application.

Then you can perform the following steps to fix the `ERROR 1062 (23000): Duplicate entry '***' for key 'PRIMARY'` error that is possibly caused by the `auto_pk_c1` column when you merge sharded tables.

1. Before the full data migration, create a table in the downstream database for merging and migrating data. Do not specify the `PRIMARY KEY` attribute for the `auto_pk_c1` column, but use the `auto_pk_c1` and `uuid_c2` columns to make up a composite primary key.

    ```sql
    CREATE TABLE `tbl_multi_pk_c2` (
      `auto_pk_c1` bigint(20) NOT NULL,
      `uuid_c2` bigint(20) NOT NULL,
      `content_c3` text,
      PRIMARY KEY (`auto_pk_c1`,`uuid_c2`)
    ) ENGINE=InnoDB DEFAULT CHARSET=latin1
    ```

2. Start the full and incremental data migration task.

3. Run `query-status` to verify whether the data migration task is successfully processed and whether the data from upstream has already been merged and migrated to the downstream database.

## Special processing when the upstream RDS contains sharded tables

If the upstream data source is an RDS and it contains sharded tables, the table names in MySQL binlog might be invisible when connecting to a SQL client. For example, if the upstream is a UCloud distributed database, the table name in the binlog might have an extra prefix `_0001`. Therefore, you need to configure [table routing](/dm/dm-key-features.md#table-routing) based on the table names in binlog, instead of those in the SQL client.

## Create/drop tables in the upstream

In [Merge and Migrate Data from Sharded Tables](/dm/feature-shard-merge-pessimistic.md#principles), it is clear that the coordination of sharding DDL lock depends on whether the downstream database receives the DDL statements of all upstream sharded tables. In addition, DM currently **does not support** dynamically creating or dropping sharded tables in the upstream. Therefore, to create or drop sharded tables in the upstream, it is recommended to perform the following steps.

### Create sharded tables in the upstream

If you need to create a new sharded table in the upstream, perform the following steps:

1. Wait for the coordination of all executed sharding DDL in the upstream sharded tables to finish.

2. Run `stop-task` to stop the data migration task.

3. Create a new sharded table in the upstream.

4. Make sure that the configuration in the `task.yaml` file allows the newly added sharded table to be merged in one downstream table with other existing sharded tables.

5. Run `start-task` to start the task.

6. Run `query-status` to verify whether the data migration task is successfully processed and whether the data from upstream has already been merged and migrated to the downstream database.

### Drop sharded tables in the upstream

If you need to drop a sharded table in the upstream, perform the following steps:

1. Drop the sharded table, run [`SHOW BINLOG EVENTS`](https://dev.mysql.com/doc/refman/5.7/en/show-binlog-events.html) to fetch the `End_log_pos` corresponding to the `DROP TABLE` statement in the binlog events, and mark it as *Pos-M*.

2. Run `query-status` to fetch the position (`syncerBinlog`) corresponding to the binlog event that has been processed by DM, and mark it as *Pos-S*.

3. When *Pos-S* is greater than *Pos-M*, it means that DM has processed all of the `DROP TABLE` statements, and the data of the table before dropping has been migrated to the downstream, so the subsequent operation can be performed. Otherwise, wait for DM to finish migrating the data.

4. Run `stop-task` to stop the task.

5. Make sure that the configuration in the `task.yaml` file ignores the dropped sharded table in the upstream.

6. Run `start-task` to start the task.

7. Run `query-status` to verify whether the data migration task is successfully processed.

## Speed limits and traffic flow control

When data from multiple upstream MySQL or MariaDB instances is merged and migrated to the same TiDB cluster in the downstream, every DM-worker corresponding to each upstream instance executes full and incremental data replication concurrently. This means that the default degree of concurrency (`pool-size` in full data migration and `worker-count` in incremental data replication) accumulates as the number of DM-workers increases, which might overload the downstream database. In this case, you need to conduct a preliminary performance analysis based on TiDB and DM monitoring metrics and adjust the value of each concurrency parameter. In the future, DM is expected to support partially automated traffic flow control.


text:
module AssociationMatchers

  class AssociationReflection

    def initialize(type, name)
      @messages = {
        :missing_association =>
          '%s is not associated with %s.',
        :wrong_type =>
          "%s %s %s./nExpected: %s",
        :wrong_options =>
          "Options are incorrect.\nExpected: %s Got: %s",
        :missing_column =>
          "Missing foreign key.\nExpected: %s"
      }
      @name = name
      @expected_type = type
      @expected_options = {}
    end

    def matches?(target)
      Class === target or
        raise ArgumentError, 'class expected'

      @target = target

      unless @assoc = target.reflect_on_association(@name)
        @failure = :missing_association
        return false
      end

      unless @assoc.macro.eql?(@expected_type)
        @failure = :wrong_type
        return false
      end

      if @expected_options.any? { |o| @assoc.options[o.first] != o.last }
        @failure = :wrong_options
        return false
      end

      @column ||= @assoc.primary_key_name || @assoc.klass.name.foreign_key

      @failure = case @assoc.macro.to_s
      when 'belongs_to'
        if @target.column_names.include?(@column.to_s) then nil
        else
          :missing_column
        end
      when /(?:has_many|has_one)/
        if    @assoc.options[:through] then nil
        elsif @assoc.klass.column_names.include?(@column.to_s) then nil
        else
          :missing_column
        end
      end

      return @failure.nil?
    end

    def failure_message
      case @failure
      when :missing_association
        @messages[@failure] % [@target.name, @name]
      when :wrong_type
        @messages[@failure] % [
          @target.name,
          @assoc.macro,
          @name,
          @expected_type
        ]
      when :wrong_options
        @messages[@failure] % [
          @expected_options.inspect,
          @assoc.options.inspect
        ]
      when :missing_column
        @messages[@failure] % @column
      end
    end
    def negative_failure_message
    end

    # ### Generic Options

    def of(class_name)
      class_name = class_name.name if Class === class_name
      @expected_options[:class_name] = class_name
      self
    end
    def for(foreign_key)
        @column = foreign_key
        self
      end
      def due_to(conditions)
        @expected_options[:conditions] = conditions
        self
      end
      def ordered_by(statement)
        @expected_options[:order] = statement
        self
      end
      def including(*models)
        @expected_options[:include] = (models.length == 1)? models.first: models
        self
      end

    end

    class BelongsToReflection < AssociationReflection

      def initialize(name)
        super :belongs_to, name
      end

      def counted(column)
        @expected_options[:counter_cache] = column
        self
      end
      def polymorphic(true_or_false = true)
        @expected_options[:polymorphic] = true_or_false
        self
      end

    end
    class HasOneReflection < AssociationReflection

      def initialize(name)
        super :has_one, name
      end

      def as(interface_name)
        @expected_options[:as] = interface_name
        self
      end
      def depending(dependency = true)
        @expected_options[:dependent] = dependency
        self
      end
      def extended_by(mod)
        @expected_options[:extend] = mod
        self
      end

    end
    class HasManyReflection < AssociationReflection

      def initialize(name)
        super :has_many, name
      end

      def as(interface_name)
        @expected_options[:as] = interface_name
        self
      end
      def depending(dependency = :destroy)
        @expected_options[:dependent] = dependency
        self
      end

    end
    class HasAndBelongsToManyReflection < AssociationReflection

      def initialize(name)
        super :has_and_belongs_to_many, name
      end

    end

    def belong_to(model)
      BelongsToReflection.new model
    end
    def have_one(model)
      HasOneReflection.new model
    end
    def have_many(models)
      HasManyReflection.new models
    end
    def have_and_belong_to_many(models)
      HasAndBelongsToManyReflection.new models
    end
    alias_method :habtm, :have_and_belong_to_many

  end


text:
package org.drools.core.common;

import java.util.Map;

import org.drools.core.marshalling.impl.ActivationKey;
import org.drools.core.reteoo.TerminalNode;
import org.drools.core.spi.Activation;
import org.drools.core.spi.Tuple;

/**
 * A filter interface for agenda activations
 */
public interface ActivationsFilter {

    /**
     * Returns true if a new activation should be created for the given propagation
     * or false otherwise
     */
    boolean accept(Activation activation,
                   ReteEvaluator reteEvaluator,
                   TerminalNode rtn );

    Map<ActivationKey, Tuple> getTuplesCache();

    void fireRNEAs(InternalWorkingMemory wm);
}


text:
import { declare } from "@babel/helper-plugin-utils";
import syntaxPlugin from "@babel/plugin-syntax-private-property-in-object";
import {
  enableFeature,
  FEATURES,
  injectInitialization as injectConstructorInit,
} from "@babel/helper-create-class-features-plugin";
import annotateAsPure from "@babel/helper-annotate-as-pure";

export default declare(({ assertVersion, types: t, template }, { loose }) => {
  assertVersion(7);

  // NOTE: When using the class fields or private methods plugins,
  // they will also take care of '#priv in obj' checks when visiting
  // the ClassExpression or ClassDeclaration nodes.
  // The visitor of this plugin is only effective when not compiling
  // private fields and methods.

  const classWeakSets = new WeakMap();
  const fieldsWeakSets = new WeakMap();

  function unshadow(name, targetScope, scope) {
    while (scope !== targetScope) {
      if (scope.hasOwnBinding(name)) scope.rename(name);
      scope = scope.parent;
    }
  }

  function injectToFieldInit(fieldPath, expr, before = false) {
    if (fieldPath.node.value) {
      if (before) {
        fieldPath.get("value").insertBefore(expr);
      } else {
        fieldPath.get("value").insertAfter(expr);
      }
    } else {
      fieldPath.set("value", t.unaryExpression("void", expr));
    }
  }

  function injectInitialization(classPath, init) {
    let firstFieldPath;
    let consturctorPath;

    for (const el of classPath.get("body.body")) {
      if (
        (el.isClassProperty() || el.isClassPrivateProperty()) &&
        !el.node.static
      ) {
        firstFieldPath = el;
        break;
      }
      if (!consturctorPath && el.isClassMethod({ kind: "constructor" })) {
        consturctorPath = el;
      }
    }

    if (firstFieldPath) {
      injectToFieldInit(firstFieldPath, init, true);
    } else {
      injectConstructorInit(classPath, consturctorPath, [
        t.expressionStatement(init),
      ]);
    }
  }

  function getWeakSetId(weakSets, outerClass, reference, name = "", inject) {
    let id = classWeakSets.get(reference.node);

    if (!id) {
      id = outerClass.scope.generateUidIdentifier(`${name || ""} brandCheck`);
      classWeakSets.set(reference.node, id);

      inject(reference, template.expression.ast`${t.cloneNode(id)}.add(this)`);

      const newExpr = t.newExpression(t.identifier("WeakSet"), []);
      annotateAsPure(newExpr);

      outerClass.insertBefore(template.ast`var ${id} = ${newExpr}`);
    }

    return t.cloneNode(id);
  }

  return {
    name: "proposal-private-property-in-object",
    inherits: syntaxPlugin.default,
    pre() {
      // Enable this in @babel/helper-create-class-features-plugin, so that it
      // can be handled by the private fields and methods transform.
      enableFeature(this.file, FEATURES.privateIn, loose);
    },
    visitor: {
      BinaryExpression(path) {
        const { node } = path;
        if (node.operator !== "in") return;
        if (!t.isPrivateName(node.left)) return;

        const { name } = node.left.id;

        let privateElement;
        const outerClass = path.findParent(path => {
          if (!path.isClass()) return false;

          privateElement = path
            .get("body.body")
            .find(({ node }) => t.isPrivate(node) && node.key.id.name === name);

          return !!privateElement;
        });

        if (outerClass.parentPath.scope.path.isPattern()) {
          outerClass.replaceWith(template.ast`(() => ${outerClass.node})()`);
          // The injected class will be queued and eventually transformed when visited
          return;
        }

        if (privateElement.isMethod()) {
          if (privateElement.node.static) {
            if (outerClass.node.id) {
              unshadow(outerClass.node.id.name, outerClass.scope, path.scope);
            } else {
              outerClass.set("id", path.scope.generateUidIdentifier("class"));
            }
            path.replaceWith(
              template.expression.ast`
                ${t.cloneNode(outerClass.node.id)} === ${path.node.right}
              `,
            );
          } else {
            const id = getWeakSetId(
              classWeakSets,
              outerClass,
              outerClass,
              outerClass.node.id?.name,
              injectInitialization,
            );

            path.replaceWith(
              template.expression.ast`${id}.has(${path.node.right})`,
            );
          }
        } else {
          // Private fields might not all be initialized: see the 'halfConstructed'
          // example at https://v8.dev/features/private-brand-checks.

          const id = getWeakSetId(
            fieldsWeakSets,
            outerClass,
            privateElement,
            privateElement.node.key.id.name,
            injectToFieldInit,
          );

          path.replaceWith(
            template.expression.ast`${id}.has(${path.node.right})`,
          );
        }
      },
    },
  };
});


text:
/* globals _:false */

import BaseStore from '../../../sumo/js/stores/BaseStore.es6.js';
import Dispatcher from '../../../sumo/js/Dispatcher.es6.js';
import {actionTypes, questionEditState} from '../constants/AAQConstants.es6.js';

var question = {
  product: null,
  topic: null,
  title: '',
  content: '',
  images: JSON.parse(document.querySelector('.data[name=images]').innerHTML),
};

var suggestions = [];
var state = questionEditState.INVALID;
var validationErrors = {};

class _QuestionEditStore extends BaseStore {
  getQuestion() {
    return _.clone(question);
  }

  getSuggestions() {
    return _.clone(suggestions);
  }

  getState() {
    return state;
  }

  getValidationErrors() {
    return _.clone(validationErrors);
  }
}

function updateState() {
  if (question.product === null) {
    state = questionEditState.INVALID;
    return;
  }
  if (question.topic === null) {
    state = questionEditState.INVALID;
    return;
  }
  if (question.title.trim() === '') {
    state = questionEditState.INVALID;
    return;
  }
  if (question.content.trim() === '') {
    state = questionEditState.INVALID;
    return;
  }
  state = questionEditState.VALID;
}

// Stores are singletons.
const QuestionEditStore = new _QuestionEditStore();

QuestionEditStore.dispatchToken = Dispatcher.register((action) => {
  switch (action.type) {
    case actionTypes.ADD_IMAGE:
      question.images.push(action.image);
      updateState();
      QuestionEditStore.emitChange();
      break;

    case actionTypes.REMOVE_IMAGE:
      question.images = _.without(question.images, action.image);
      updateState();
      QuestionEditStore.emitChange();
      break;

    case actionTypes.SET_PRODUCT:
      if (question.product !== action.product) {
        question.product = action.product;
        question.topic = null;
        updateState();
        QuestionEditStore.emitChange();
      }
      break;

    case actionTypes.SET_TOPIC:
      if (question.topic !== action.topic) {
        question.topic = action.topic;
        updateState();
        QuestionEditStore.emitChange();
      }
      break;

    case actionTypes.SET_TITLE:
      if (question.title !== action.title) {
        question.title = action.title;
        updateState();
        QuestionEditStore.emitChange();
      }
      break;

    case actionTypes.SET_CONTENT:
      if (question.content !== action.content) {
        question.content = action.content;
        updateState();
        QuestionEditStore.emitChange();
      }
      break;

    case actionTypes.SET_SUGGESTIONS:
      suggestions = action.suggestions;
      QuestionEditStore.emitChange();
      break;

    case actionTypes.QUESTION_SUBMIT_OPTIMISTIC:
      state = questionEditState.PENDING;
      QuestionEditStore.emitChange();
      break;

    case actionTypes.QUESTION_SUBMIT_SUCCESS:
      state = questionEditState.SUBMITTED;
      validationErrors.server = {};
      QuestionEditStore.emitChange();
      break;

    case actionTypes.QUESTION_SUBMIT_FAILURE:
      state = questionEditState.ERROR;
      validationErrors.server = [action.error];
      QuestionEditStore.emitChange();
      break;

    default:
      // do nothing
  }
});

export default QuestionEditStore;