/*
 * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH
 * under one or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information regarding copyright
 * ownership. Camunda licenses this file to you under the Apache License,
 * Version 2.0; you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.camunda.bpm.engine.variable.impl.type;

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

import javax.lang.model.type.NullType;

import org.camunda.bpm.engine.variable.Variables;
import org.camunda.bpm.engine.variable.impl.value.PrimitiveTypeValueImpl.DoubleValueImpl;
import org.camunda.bpm.engine.variable.impl.value.PrimitiveTypeValueImpl.IntegerValueImpl;
import org.camunda.bpm.engine.variable.impl.value.PrimitiveTypeValueImpl.LongValueImpl;
import org.camunda.bpm.engine.variable.impl.value.PrimitiveTypeValueImpl.ShortValueImpl;
import org.camunda.bpm.engine.variable.type.PrimitiveValueType;
import org.camunda.bpm.engine.variable.type.ValueType;
import org.camunda.bpm.engine.variable.value.BooleanValue;
import org.camunda.bpm.engine.variable.value.BytesValue;
import org.camunda.bpm.engine.variable.value.DateValue;
import org.camunda.bpm.engine.variable.value.DoubleValue;
import org.camunda.bpm.engine.variable.value.IntegerValue;
import org.camunda.bpm.engine.variable.value.LongValue;
import org.camunda.bpm.engine.variable.value.NumberValue;
import org.camunda.bpm.engine.variable.value.ShortValue;
import org.camunda.bpm.engine.variable.value.StringValue;
import org.camunda.bpm.engine.variable.value.TypedValue;

/**
 * Implementation of the primitive variable value types
 *
 * @author Daniel Meyer
 *
 */
public abstract class PrimitiveValueTypeImpl extends AbstractValueTypeImpl implements PrimitiveValueType {

  private static final long serialVersionUID = 1L;

  protected Class<?> javaType;

  public PrimitiveValueTypeImpl(Class<?> javaType) {
    this(javaType.getSimpleName().toLowerCase(), javaType);
  }

  public PrimitiveValueTypeImpl(String name, Class<?> javaType) {
    super(name);
    this.javaType = javaType;
  }

  public Class<?> getJavaType() {
    return javaType;
  }

  public boolean isPrimitiveValueType() {
    return true;
  }

  @Override
  public String toString() {
    return "PrimitiveValueType["+getName()+"]";
  }

  public Map<String, Object> getValueInfo(TypedValue typedValue) {
    Map<String, Object> result = new HashMap<String, Object>();
    if (typedValue.isTransient())
      result.put(VALUE_INFO_TRANSIENT, typedValue.isTransient());
    return result;
  }

  // concrete types ///////////////////////////////////////////////////

  public static class BooleanTypeImpl extends PrimitiveValueTypeImpl {

    private static final long serialVersionUID = 1L;

    public BooleanTypeImpl() {
      super(Boolean.class);
    }

    public BooleanValue createValue(Object value, Map<String, Object> valueInfo) {
      return Variables.booleanValue((Boolean) value, isTransient(valueInfo));
    }

  }

  public static class BytesTypeImpl extends PrimitiveValueTypeImpl {

    private static final long serialVersionUID = 1L;

    public BytesTypeImpl() {
      super("bytes", byte[].class);
    }

    public BytesValue createValue(Object value, Map<String, Object> valueInfo) {
      return Variables.byteArrayValue((byte[]) value, isTransient(valueInfo));
    }

  }

  public static class DateTypeImpl extends PrimitiveValueTypeImpl {

    private static final long serialVersionUID = 1L;

    public DateTypeImpl() {
      super(Date.class);
    }

    public DateValue createValue(Object value, Map<String, Object> valueInfo) {
      return Variables.dateValue((Date) value, isTransient(valueInfo));
    }

  }

  public static class DoubleTypeImpl extends PrimitiveValueTypeImpl {

    private static final long serialVersionUID = 1L;

    public DoubleTypeImpl() {
      super(Double.class);
    }

    public DoubleValue createValue(Object value, Map<String, Object> valueInfo) {
      return Variables.doubleValue((Double) value, isTransient(valueInfo));
    }

    @Override
    public ValueType getParent() {
      return ValueType.NUMBER;
    }

    @Override
    public boolean canConvertFromTypedValue(TypedValue typedValue) {
      if (typedValue.getType() != ValueType.NUMBER) {
        return false;
      }

      return true;
    }

    @Override
    public DoubleValue convertFromTypedValue(TypedValue typedValue) {
      if (typedValue.getType() != ValueType.NUMBER) {
        throw unsupportedConversion(typedValue.getType());
      }
      DoubleValueImpl doubleValue = null;
      NumberValue numberValue = (NumberValue) typedValue;
      if (numberValue.getValue() != null) {
        doubleValue = (DoubleValueImpl) Variables.doubleValue(numberValue.getValue().doubleValue());
      } else {
        doubleValue = (DoubleValueImpl) Variables.doubleValue(null);
      }
      doubleValue.setTransient(numberValue.isTransient());
      return doubleValue;
    }
  }

  public static class IntegerTypeImpl extends PrimitiveValueTypeImpl {

    private static final long serialVersionUID = 1L;

    public IntegerTypeImpl() {
      super(Integer.class);
    }

    public IntegerValue createValue(Object value, Map<String, Object> valueInfo) {
      return Variables.integerValue((Integer) value, isTransient(valueInfo));
    }

    @Override
    public ValueType getParent() {
      return ValueType.NUMBER;
    }

    @Override
    public boolean canConvertFromTypedValue(TypedValue typedValue) {
      if (typedValue.getType() != ValueType.NUMBER) {
        return false;
      }

      if (typedValue.getValue() != null) {
        NumberValue numberValue = (NumberValue) typedValue;
        double doubleValue = numberValue.getValue().doubleValue();

        // returns false if the value changes due to conversion (e.g. by overflows
        // or by loss in precision)
        if (numberValue.getValue().intValue() != doubleValue) {
          return false;
        }
      }

      return true;
    }

    @Override
    public IntegerValue convertFromTypedValue(TypedValue typedValue) {
      if (typedValue.getType() != ValueType.NUMBER) {
        throw unsupportedConversion(typedValue.getType());
      }

      IntegerValueImpl integerValue = null;
      NumberValue numberValue = (NumberValue) typedValue;
      if (numberValue.getValue() != null) {
        integerValue = (IntegerValueImpl) Variables.integerValue(numberValue.getValue().intValue());
      } else {
        integerValue = (IntegerValueImpl) Variables.integerValue(null);
      }
      integerValue.setTransient(numberValue.isTransient());
      return integerValue;
    }
  }

  public static class LongTypeImpl extends PrimitiveValueTypeImpl {

    private static final long serialVersionUID = 1L;

    public LongTypeImpl() {
      super(Long.class);
    }

    public LongValue createValue(Object value, Map<String, Object> valueInfo) {
      return Variables.longValue((Long) value, isTransient(valueInfo));
    }

    @Override
    public ValueType getParent() {
      return ValueType.NUMBER;
    }

    @Override
    public boolean canConvertFromTypedValue(TypedValue typedValue) {
      if (typedValue.getType() != ValueType.NUMBER) {
        return false;
      }

      if (typedValue.getValue() != null) {
        NumberValue numberValue = (NumberValue) typedValue;
        double doubleValue = numberValue.getValue().doubleValue();

        // returns false if the value changes due to conversion (e.g. by overflows
        // or by loss in precision)
        if (numberValue.getValue().longValue() != doubleValue) {
          return false;
        }
      }

      return true;
    }

    @Override
    public LongValue convertFromTypedValue(TypedValue typedValue) {
      if (typedValue.getType() != ValueType.NUMBER) {
        throw unsupportedConversion(typedValue.getType());
      }

      LongValueImpl longvalue = null;
      NumberValue numberValue = (NumberValue) typedValue;

      if (numberValue.getValue() != null) {
        longvalue = (LongValueImpl) Variables.longValue(numberValue.getValue().longValue());
      } else {
        longvalue =  (LongValueImpl) Variables.longValue(null);
      }
      longvalue.setTransient(numberValue.isTransient());
      return longvalue;
    }
  }

  public static class NullTypeImpl extends PrimitiveValueTypeImpl {

    private static final long serialVersionUID = 1L;

    public NullTypeImpl() {
      super("null", NullType.class);
    }

    public TypedValue createValue(Object value, Map<String, Object> valueInfo) {
      return Variables.untypedNullValue(isTransient(valueInfo));
    }

  }

  public static class ShortTypeImpl extends PrimitiveValueTypeImpl {

    private static final long serialVersionUID = 1L;

    public ShortTypeImpl() {
      super(Short.class);
    }

    public ShortValue createValue(Object value, Map<String, Object> valueInfo) {
      return Variables.shortValue((Short) value, isTransient(valueInfo));
    }

    @Override
    public ValueType getParent() {
      return ValueType.NUMBER;
    }

    @Override
    public ShortValue convertFromTypedValue(TypedValue typedValue) {
      if (typedValue.getType() != ValueType.NUMBER) {
        throw unsupportedConversion(typedValue.getType());
      }

      ShortValueImpl shortValue = null;
      NumberValue numberValue = (NumberValue) typedValue;
      if (numberValue.getValue() != null) {
        shortValue = (ShortValueImpl) Variables.shortValue(numberValue.getValue().shortValue());
      } else {
        shortValue =  (ShortValueImpl) Variables.shortValue(null);
      }
      shortValue.setTransient(numberValue.isTransient());
      return shortValue;
    }

    @Override
    public boolean canConvertFromTypedValue(TypedValue typedValue) {
      if (typedValue.getType() != ValueType.NUMBER) {
        return false;
      }

      if (typedValue.getValue() != null) {
        NumberValue numberValue = (NumberValue) typedValue;
        double doubleValue = numberValue.getValue().doubleValue();

        // returns false if the value changes due to conversion (e.g. by overflows
        // or by loss in precision)
        if (numberValue.getValue().shortValue() != doubleValue) {
          return false;
        }
      }

      return true;
    }
  }

  public static class StringTypeImpl extends PrimitiveValueTypeImpl {

    private static final long serialVersionUID = 1L;

    public StringTypeImpl() {
      super(String.class);
    }

    public StringValue createValue(Object value, Map<String, Object> valueInfo) {
      return Variables.stringValue((String) value, isTransient(valueInfo));
    }
  }

  public static class NumberTypeImpl extends PrimitiveValueTypeImpl {

    private static final long serialVersionUID = 1L;

    public NumberTypeImpl() {
      super(Number.class);
    }

    public NumberValue createValue(Object value, Map<String, Object> valueInfo) {
      return Variables.numberValue((Number) value, isTransient(valueInfo));
    }

    @Override
    public boolean isAbstract() {
      return true;
    }
  }

}

{'repo_name': 'camunda/camunda-bpm-platform', 'stars': '1508', 'repo_language': 'Java', 'file_name': 'DmnBusinessRuleTaskTest.java', 'mime_type': 'text/x-java', 'hash': 5115702819518495074, 'source_dataset': 'data'}


<?php

namespace Kraken\Root\Provider;

use Kraken\Container\ContainerInterface;
use Kraken\Container\ServiceProvider;
use Kraken\Container\ServiceProviderInterface;
use Kraken\Filesystem\Filesystem;
use Kraken\Filesystem\FilesystemAdapterFactory;
use Kraken\Filesystem\FilesystemFactory;
use Kraken\Filesystem\FilesystemManager;

class FilesystemProvider extends ServiceProvider implements ServiceProviderInterface
{
    /**
     * @var string[]
     */
    protected $requires = [
        'Kraken\Core\CoreInterface',
        'Kraken\Config\ConfigInterface'
    ];

    /**
     * @var string[]
     */
    protected $provides = [
        'Kraken\Filesystem\FilesystemInterface',
        'Kraken\Filesystem\FilesystemFactoryInterface',
        'Kraken\Filesystem\FilesystemManagerInterface'
    ];

    /**
     * @param ContainerInterface $container
     */
    protected function register(ContainerInterface $container)
    {
        $core   = $container->make('Kraken\Core\CoreInterface');
        $config = $container->make('Kraken\Config\ConfigInterface');

        $factory = new FilesystemAdapterFactory();
        $fsCloud = new FilesystemManager();
        $fsDisk  = new Filesystem(
            $factory->create('Local', [ [ 'path' => $core->getBasePath() ] ])
        );

        $disks = $config->get('filesystem.cloud');

        foreach ($disks as $disk=>$config)
        {
            $fsCloud->mountFilesystem($disk, new Filesystem(
                $factory->create(
                    $config['class'],
                    [ $config['config'] ]
                )
            ));
        }

        $container->instance(
            'Kraken\Filesystem\FilesystemInterface',
            $fsDisk
        );

        $container->instance(
            'Kraken\Filesystem\FilesystemFactoryInterface',
            new FilesystemFactory
        );

        $container->instance(
            'Kraken\Filesystem\FilesystemManagerInterface',
            $fsCloud
        );
    }

    /**
     * @param ContainerInterface $container
     */
    protected function unregister(ContainerInterface $container)
    {
        $container->remove(
            'Kraken\Filesystem\FilesystemInterface'
        );

        $container->remove(
            'Kraken\Filesystem\FilesystemFactoryInterface'
        );

        $container->remove(
            'Kraken\Filesystem\FilesystemManagerInterface'
        );
    }
}

{'repo_name': 'kraken-php/framework', 'stars': '1120', 'repo_language': 'PHP', 'file_name': 'kraken-split-full.sh', 'mime_type': 'text/plain', 'hash': -3927516440983128892, 'source_dataset': 'data'}


// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT License.
using Microsoft.CST.AttackSurfaceAnalyzer.Objects;
using Microsoft.CST.AttackSurfaceAnalyzer.Types;
using Newtonsoft.Json;
using Serilog;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Data.SQLite;
using System.Globalization;
using System.Linq;
using System.Reflection;

namespace Microsoft.CST.AttackSurfaceAnalyzer.Utils
{
    public static class SystemSQLiteDatabaseManager
    {
        public static List<SystemSQLiteSqlConnectionHolder> Connections { get; private set; } = new List<SystemSQLiteSqlConnectionHolder>();
        public static bool FirstRun { get; private set; } = true;

        public static SystemSQLiteSqlConnectionHolder? MainConnection
        {
            get
            {
                if (Connections.Any())
                    return Connections[0];
                return null;
            }
        }

        public static string SQLiteFilename { get; private set; } = "asa.SQLite";

        public static void BeginTransaction()
        {
            Connections.AsParallel().ForAll(cxn => cxn.BeginTransaction());
        }

        public static void CloseDatabase()
        {
            RollBack();
            Connections.AsParallel().ForAll(cxn =>
            {
                cxn.ShutDown();
            });
            Connections.RemoveAll(_ => true);
        }

        public static void Commit()
        {
            Connections.AsParallel().ForAll(x => x.Commit());
        }

        public static void DeleteRun(string runid)
        {
            _ = MainConnection ?? throw new NullReferenceException(Strings.Get("MainConnection"));
            using var truncateRunsTable = new SQLiteCommand(SQL_TRUNCATE_RUN, MainConnection.Connection, MainConnection.Transaction);
            truncateRunsTable.Parameters.AddWithValue("@run_id", runid);
            truncateRunsTable.ExecuteNonQuery();

            Connections.AsParallel().ForAll(cxn =>
            {
                using var truncateCollectTable = new SQLiteCommand(SQL_DELETE_RUN, cxn.Connection, cxn.Transaction);
                truncateCollectTable.Parameters.AddWithValue("@run_id", runid);
                truncateCollectTable.ExecuteNonQuery();
            });
        }

        public static void Destroy()
        {
            Connections.AsParallel().ForAll(x => x.Destroy());
            Connections.RemoveAll(x => true);
        }

        public static List<RESULT_TYPE> GetCommonResultTypes(string baseId, string compareId)
        {
            var runOne = GetRun(baseId);
            var runTwo = GetRun(compareId);

            return runOne?.ResultTypes.Intersect(runTwo?.ResultTypes).ToList() ?? new List<RESULT_TYPE>();
        }

        public static bool GetComparisonCompleted(string firstRunId, string secondRunId)
        {
            if (MainConnection != null)
            {
                using (var cmd = new SQLiteCommand(SQL_CHECK_IF_COMPARISON_PREVIOUSLY_COMPLETED, MainConnection.Connection, MainConnection.Transaction))
                {
                    cmd.Parameters.AddWithValue("@base_run_id", firstRunId);
                    cmd.Parameters.AddWithValue("@compare_run_id", secondRunId);
                    using (var reader = cmd.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            return true;
                        }
                    }
                }
            }
            else
            {
                Log.Debug("Failed to GetComparisonCompleted because MainConnection is null.");
            }

            return false;
        }

        public static List<CompareResult> GetComparisonResults(string compareId, RESULT_TYPE exportType)
        {
            List<CompareResult> records = new List<CompareResult>();
            if (MainConnection != null)
            {
                using (var cmd = new SQLiteCommand(GET_COMPARISON_RESULTS, MainConnection.Connection, MainConnection.Transaction))
                {
                    cmd.Parameters.AddWithValue("@comparison_id", compareId);
                    cmd.Parameters.AddWithValue("@result_type", exportType);
                    using (var reader = cmd.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            if (reader["serialized"].ToString() is string serialized)
                            {
                                try
                                {
                                    records.Add(JsonConvert.DeserializeObject<CompareResult>(serialized));
                                }
                                catch (Exception e)
                                {
                                    Log.Debug(e, "Couldn't deserialized into a CompareResult {0}", serialized);
                                }
                            }
                        }
                    }
                }
            }
            return records;
        }

        public static List<CompareResult> GetComparisonResults(string comparisonId, int resultType, int offset, int numResults)
        {
            _ = MainConnection ?? throw new NullReferenceException(Strings.Get("MainConnection"));
            var results = new List<CompareResult>();
            using (var cmd = new SQLiteCommand(GET_COMPARISON_RESULTS_LIMIT, MainConnection.Connection, MainConnection.Transaction))
            {
                cmd.Parameters.AddWithValue("@comparison_id", comparisonId);
                cmd.Parameters.AddWithValue("@result_type", resultType);
                cmd.Parameters.AddWithValue("@offset", offset);
                cmd.Parameters.AddWithValue("@limit", numResults);
                using (var reader = cmd.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        try
                        {
                            var thing = reader["serialized"];
                            if (thing is string result)
                            {
                                var obj = JsonConvert.DeserializeObject<CompareResult>(result);
                                results.Add(obj);
                            }
                        }
                        catch (Exception e)
                        {
                            Log.Debug(e, "Error deserializing {0}", reader["serialized"]);
                        }
                    }
                }
            }

            return results;
        }

        public static int GetComparisonResultsCount(string comparisonId, int resultType)
        {
            _ = MainConnection ?? throw new NullReferenceException(Strings.Get("MainConnection"));
            var result_count = 0;
            using (var cmd = new SQLiteCommand(GET_RESULT_COUNT, MainConnection.Connection, MainConnection.Transaction))
            {
                cmd.Parameters.AddWithValue("@comparison_id", comparisonId);
                cmd.Parameters.AddWithValue("@result_type", resultType);
                using (var reader = cmd.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        if (reader["count(*)"].ToString() is string integer)
                            result_count = int.Parse(integer, CultureInfo.InvariantCulture);
                    }
                }
            }
            return result_count;
        }

        public static List<string> GetLatestRunIds(int numberOfIds, string type)
        {
            List<string> output = new List<string>();
            if (MainConnection != null)
            {
                using (var cmd = new SQLiteCommand(SQL_SELECT_LATEST_N_RUNS, MainConnection.Connection, MainConnection.Transaction))
                {
                    cmd.Parameters.AddWithValue("@type", type);
                    cmd.Parameters.AddWithValue("@limit", numberOfIds);
                    try
                    {
                        using (var reader = cmd.ExecuteReader())
                        {
                            while (reader.Read())
                            {
                                var str = reader["run_id"].ToString();
                                if (!string.IsNullOrEmpty(str))
                                    output.Add(str);
                            }
                        }
                    }
                    catch (SQLiteException)
                    {
                        Log.Debug("Couldn't determine latest {0} run ids.", numberOfIds);
                    }
                }
            }
            else
            {
                Log.Debug("Failed to GetLatestRunIds because MainConnection is null.");
            }
            return output;
        }

        public static ConcurrentBag<WriteObject> GetMissingFromFirst(string firstRunId, string secondRunId)
        {
            var output = new ConcurrentBag<WriteObject>();

            Connections.AsParallel().ForAll(cxn =>
            {
                using var cmd = new SQLiteCommand(SQL_GET_COLLECT_MISSING_IN_B, cxn.Connection, cxn.Transaction);
                cmd.Parameters.AddWithValue("@first_run_id", firstRunId);
                cmd.Parameters.AddWithValue("@second_run_id", secondRunId);
                using (var reader = cmd.ExecuteReader())
                    while (reader.Read())
                    {
                        var runId = reader["run_id"].ToString();
                        var resultTypeString = reader["result_type"].ToString();
                        if (runId != null && resultTypeString != null)
                        {
                            var wo = WriteObject.FromString((string)reader["serialized"], (RESULT_TYPE)Enum.Parse(typeof(RESULT_TYPE), resultTypeString), runId);
                            if (wo is WriteObject WO)
                            {
                                output.Add(WO);
                            }
                        }
                    }
            });

            return output;
        }

        public static ConcurrentBag<(WriteObject, WriteObject)> GetModified(string firstRunId, string secondRunId)
        {
            var output = new ConcurrentBag<(WriteObject, WriteObject)>();

            Connections.AsParallel().ForAll(cxn =>
            {
                using var cmd = new SQLiteCommand(SQL_GET_COLLECT_MODIFIED, cxn.Connection, cxn.Transaction);
                cmd.Parameters.AddWithValue("@first_run_id", firstRunId);
                cmd.Parameters.AddWithValue("@second_run_id", secondRunId);
                using (var reader = cmd.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        var aRunId = reader["a_run_id"].ToString();
                        var bRunId = reader["b_run_id"].ToString();
                        var aResultType = reader["a_result_type"].ToString();
                        var bResultType = reader["b_result_type"].ToString();

                        if (aRunId != null && bRunId != null && aResultType != null && bResultType != null)
                        {
                            var val1 = WriteObject.FromString((string)reader["a_serialized"], (RESULT_TYPE)Enum.Parse(typeof(RESULT_TYPE), aResultType), aRunId);
                            var val2 = WriteObject.FromString((string)reader["b_serialized"], (RESULT_TYPE)Enum.Parse(typeof(RESULT_TYPE), bResultType), bRunId);

                            if (val1 is WriteObject V1 && val2 is WriteObject V2)
                            {
                                output.Add((V1, V2));
                            }
                        }
                    }
                }
            });

            return output;
        }

        public static List<OutputFileMonitorResult> GetMonitorResults(string runId, int offset, int numResults)
        {
            var results = new List<OutputFileMonitorResult>();
            if (MainConnection != null)
            {
                using (var cmd = new SQLiteCommand(GET_MONITOR_RESULTS, MainConnection.Connection, MainConnection.Transaction))
                {
                    cmd.Parameters.AddWithValue("@run_id", runId);
                    cmd.Parameters.AddWithValue("@offset", offset);
                    cmd.Parameters.AddWithValue("@limit", numResults);
                    using (var reader = cmd.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            var path = reader["path"].ToString();
                            if (!string.IsNullOrEmpty(path))
                            {
                                var obj = new OutputFileMonitorResult(path)
                                {
                                    RowKey = reader["row_key"].ToString(),
                                    Timestamp = reader["timestamp"].ToString(),
                                    OldPath = reader["old_path"].ToString(),
                                    Name = reader["path"].ToString(),
                                    OldName = reader["old_path"].ToString(),
                                    ChangeType = (CHANGE_TYPE)int.Parse(reader["change_type"].ToString() ?? "Invalid", CultureInfo.InvariantCulture),
                                };
                                results.Add(obj);
                            }
                        }
                    }
                }
            }
            else
            {
                Log.Debug("Failed to GetMonitorResults. MainConnection was null.");
            }

            return results;
        }

        public static List<string> GetMonitorRuns()
        {
            return GetRuns("monitor");
        }

        public static int GetNumMonitorResults(string runId)
        {
            _ = MainConnection ?? throw new NullReferenceException(Strings.Get("MainConnection"));

            using (var cmd = new SQLiteCommand(GET_RESULT_COUNT_MONITORED, MainConnection.Connection, MainConnection.Transaction))
            {
                cmd.Parameters.AddWithValue("@run_id", runId);
                using (var reader = cmd.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        if (reader["count(*)"].ToString() is string integer)
                            return int.Parse(integer, CultureInfo.InvariantCulture);
                    }
                }
            }

            return 0;
        }

        public static int GetNumResults(RESULT_TYPE ResultType, string runId)
        {
            try
            {
                if (MainConnection != null)
                {
                    using (var cmd = new SQLiteCommand(SQL_GET_NUM_RESULTS, MainConnection.Connection, MainConnection.Transaction))
                    {
                        cmd.Parameters.AddWithValue("@run_id", runId);
                        cmd.Parameters.AddWithValue("@result_type", ResultType.ToString());

                        using (var reader = cmd.ExecuteReader())
                        {
                            while (reader.Read())
                            {
                                return int.Parse(reader["the_count"].ToString() ?? "-1", CultureInfo.InvariantCulture);
                            }
                        }
                    }
                }
            }
            catch (SQLiteException)
            {
                Log.Error(Strings.Get("Err_Sql"), MethodBase.GetCurrentMethod()?.Name);
            }
            return -1;
        }

        public static List<DataRunModel> GetResultModels(RUN_STATUS runStatus)
        {
            var output = new List<DataRunModel>();

            if (MainConnection != null)
            {
                using (var cmd = new SQLiteCommand(SQL_QUERY_ANALYZED, MainConnection.Connection, MainConnection.Transaction))
                {
                    cmd.Parameters.AddWithValue("@status", runStatus);

                    using (var reader = cmd.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            output.Add(new DataRunModel(KeyIn: reader["base_run_id"].ToString() + " vs. " + reader["compare_run_id"].ToString(), TextIn: reader["base_run_id"].ToString() + " vs. " + reader["compare_run_id"].ToString()));
                        }
                    }
                }
            }
            else
            {
                Log.Debug("Failed to GetResultModels, MainConnection is null");
            }
            return output;
        }

        public static IEnumerable<WriteObject> GetResultsByRunid(string runid)
        {
            foreach (var cxn in Connections)
            {
                using var cmd = new SQLiteCommand(SQL_GET_RESULTS_BY_RUN_ID, cxn.Connection, cxn.Transaction);

                cmd.Parameters.AddWithValue("@run_id", runid);
                using (var reader = cmd.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        var runId = reader["run_id"].ToString();
                        var resultTypeString = reader["result_type"].ToString();
                        if (runId != null && resultTypeString != null)
                        {
                            var val = WriteObject.FromString((string)reader["serialized"], (RESULT_TYPE)Enum.Parse(typeof(RESULT_TYPE), resultTypeString), runId);
                            if (val is WriteObject valid)
                                yield return valid;
                        }
                    }
                }
            }
        }

        public static Dictionary<RESULT_TYPE, int> GetResultTypesAndCounts(string runId)
        {
            var outDict = new Dictionary<RESULT_TYPE, int>() { };
            try
            {
                if (MainConnection != null)
                {
                    using (var cmd = new SQLiteCommand(SQL_GET_RESULT_TYPES_COUNTS, MainConnection.Connection, MainConnection.Transaction))
                    {
                        cmd.Parameters.AddWithValue("@run_id", runId);

                        using (var reader = cmd.ExecuteReader())
                        {
                            while (reader.Read())
                            {
                                if (Enum.TryParse(reader["result_type"].ToString(), out RESULT_TYPE result_type))
                                {
                                    outDict.TryAdd(result_type, int.Parse(reader["count"].ToString() ?? "-1", CultureInfo.InvariantCulture));
                                }
                            }
                        }
                    }
                }
            }
            catch (SQLiteException)
            {
                Log.Error(Strings.Get("Err_ResultTypesCounts"));
            }
            return outDict;
        }

        public static AsaRun? GetRun(string RunId)
        {
            _ = MainConnection ?? throw new NullReferenceException(Strings.Get("MainConnection"));

            using (var cmd = new SQLiteCommand(SQL_GET_RUN, MainConnection.Connection, MainConnection.Transaction))
            {
                cmd.Parameters.AddWithValue("@run_id", RunId);
                using (var reader = cmd.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        if (reader["serialized"]?.ToString() is string serialized)
                        {
                            return JsonConvert.DeserializeObject<AsaRun>(serialized);
                        }
                    }
                }
            }
            return null;
        }

        public static List<string> GetRuns(string type)
        {
            _ = MainConnection ?? throw new NullReferenceException(Strings.Get("MainConnection"));

            string Select_Runs = "select distinct run_id from runs where type=@type order by timestamp asc;";

            List<string> Runs = new List<string>();

            using var cmd = new SQLiteCommand(Select_Runs, MainConnection.Connection, MainConnection.Transaction);
            cmd.Parameters.AddWithValue("@type", type);
            using (var reader = cmd.ExecuteReader())
            {
                while (reader.Read())
                {
                    Runs.Add((string)reader["run_id"]);
                }
            }
            return Runs;
        }

        public static List<string> GetRuns()
        {
            return GetRuns("collect");
        }

        public static List<FileMonitorEvent> GetSerializedMonitorResults(string runId)
        {
            List<FileMonitorEvent> records = new List<FileMonitorEvent>();
            if (MainConnection != null)
            {
                using (var cmd = new SQLiteCommand(GET_SERIALIZED_RESULTS, MainConnection.Connection, MainConnection.Transaction))
                {
                    cmd.Parameters.AddWithValue("@run_id", runId);
                    using (var reader = cmd.ExecuteReader())
                    {
                        FileMonitorEvent obj;

                        while (reader.Read())
                        {
                            if (reader["serialized"].ToString() is string serialized)
                            {
                                try
                                {
                                    obj = JsonConvert.DeserializeObject<FileMonitorEvent>(serialized);
                                    obj.ChangeType = (CHANGE_TYPE)int.Parse(reader["change_type"].ToString() ?? "0", CultureInfo.InvariantCulture);
                                    records.Add(obj);
                                }
                                catch (Exception e)
                                {
                                    Log.Debug(e, "Couldn't deserialized into a CompareResult {0}", serialized);
                                }
                            }
                        }
                    }
                }
            }

            return records;
        }

        public static bool GetTelemetryEnabled()
        {
            var settings = GetSettings();
            if (settings != null)
            {
                return settings.TelemetryEnabled;
            }
            return true;
        }

        public static bool HasElements()
        {
            return Connections.Any(x => !x.WriteQueue.IsEmpty);
        }

        public static void InsertAnalyzed(CompareResult objIn)
        {
            if (objIn != null && MainConnection != null)
            {
                using (var cmd = new SQLiteCommand(SQL_INSERT_FINDINGS_RESULT, MainConnection.Connection, MainConnection.Transaction))
                {
                    cmd.Parameters.AddWithValue("@first_run_id", objIn.BaseRunId);
                    cmd.Parameters.AddWithValue("@second_run_id", objIn.CompareRunId);
                    cmd.Parameters.AddWithValue("@result_type", objIn.ResultType);
                    cmd.Parameters.AddWithValue("@level", objIn.Analysis);
                    cmd.Parameters.AddWithValue("@identity", objIn.Identity);
                    cmd.Parameters.AddWithValue("@serialized", JsonConvert.SerializeObject(objIn));
                    cmd.ExecuteNonQuery();
                }
            }
            else
            {
                Log.Debug("Failed to InsertAnalyzed because MainConnection was null");
            }
        }

        public static void InsertCompareRun(string firstRunId, string secondRunId, RUN_STATUS runStatus)
        {
            _ = MainConnection ?? throw new NullReferenceException(Strings.Get("MainConnection"));
            using (var cmd = new SQLiteCommand(INSERT_RUN_INTO_RESULT_TABLE_SQL, MainConnection.Connection, MainConnection.Transaction))
            {
                cmd.Parameters.AddWithValue("@base_run_id", firstRunId);
                cmd.Parameters.AddWithValue("@compare_run_id", secondRunId);
                cmd.Parameters.AddWithValue("@status", runStatus);
                cmd.ExecuteNonQuery();
            }
        }

        public static void InsertRun(AsaRun run)
        {
            if (run == null)
            {
                return;
            }
            if (MainConnection != null)
            {
                using var cmd = new SQLiteCommand(SQL_INSERT_RUN, MainConnection.Connection, MainConnection.Transaction);
                cmd.Parameters.AddWithValue("@run_id", run.RunId);
                cmd.Parameters.AddWithValue("@type", run.Type);
                cmd.Parameters.AddWithValue("@serialized", JsonConvert.SerializeObject(run));

                try
                {
                    cmd.ExecuteNonQuery();
                }
                catch (SQLiteException e)
                {
                    Log.Warning(e.StackTrace);
                    Log.Warning(e.Message);
                    AsaTelemetry.TrackTrace(Microsoft.ApplicationInsights.DataContracts.SeverityLevel.Error, e);
                }
            }
            else
            {
                Log.Debug("Failed to InsertRun because MainConnection is null.");
            }
        }

        public static int ModuloString(string identity, int shardingFactor) => identity.Sum(x => x) % shardingFactor;

        public static int PopulateConnections()
        {
            var connectionsCreated = 0;
            for (int i = Connections.Count; i < dbSettings.ShardingFactor; i++)
            {
                Connections.Add(GenerateSqlConnection(i));
                connectionsCreated++;
            }
            return connectionsCreated;
        }

        public static void RollBack()
        {
            if (Connections != null)
            {
                Connections.AsParallel().ForAll(cxn =>
                {
                    try
                    {
                        cxn.Transaction?.Rollback();
                    }
                    catch (NullReferenceException)
                    { }
                    finally
                    {
                        cxn.Transaction = null;
                    }
                });
            }
        }

        public static PLATFORM RunIdToPlatform(string runid)
        {
            if (MainConnection != null)
            {
                using (var cmd = new SQLiteCommand(SQL_GET_PLATFORM_FROM_RUNID, MainConnection.Connection, MainConnection.Transaction))
                {
                    cmd.Parameters.AddWithValue("@run_id", runid);
                    using (var reader = cmd.ExecuteReader())
                    {
                        reader.Read();
                        var platform = reader["platform"].ToString();
                        if (platform != null)
                        {
                            return (PLATFORM)Enum.Parse(typeof(PLATFORM), platform);
                        }
                    }
                }
            }
            else
            {
                Log.Debug("Failed to get RunIdToPlatform. MainConnection was null.");
            }
            return PLATFORM.UNKNOWN;
        }

        public static void SetTelemetryEnabled(bool Enabled)
        {
            var settings = GetSettings();
            if (settings != null)
            {
                settings.TelemetryEnabled = Enabled;
                SetSettings(settings);
            }
        }

        public static bool Setup(string filename, DBSettings? dbSettingsIn = null)
        {
            dbSettings = (dbSettingsIn == null) ? new DBSettings() : dbSettingsIn;

            if (filename != null)
            {
                if (SQLiteFilename != filename)
                {
                    SQLiteFilename = filename;
                }
            }

            if (Connections.Count > 0)
            {
                CloseDatabase();
            }

            if (Connections == null || Connections.Count == 0)
            {
                Connections = new List<SystemSQLiteSqlConnectionHolder>();

                PopulateConnections();

                var settings = GetSettings();
                if (settings != null)
                {
                    FirstRun = false;

                    if (SCHEMA_VERSION != settings.SchemaVersion)
                    {
                        Log.Fatal("Database has schema version {settings.SchemaVersion} but database has schema version {SCHEMA_VERSION}.");
                        Environment.Exit((int)ASA_ERROR.MATCHING_SCHEMA);
                    }

                    if (dbSettingsIn != null && settings.ShardingFactor != dbSettingsIn.ShardingFactor)
                    {
                        Log.Information($"Requested sharding level of {dbSettingsIn.ShardingFactor} but database was created with {settings.ShardingFactor}. Ignoring request and using {settings.ShardingFactor}.");
                    }

                    dbSettings.ShardingFactor = settings.ShardingFactor;

                    AsaTelemetry.SetEnabled(settings.TelemetryEnabled);
                }
                else
                {
                    FirstRun = true;
                }

                PopulateConnections();

                if (MainConnection == null)
                {
                    Log.Warning("Failed to set up Main Database connection. Cannot set up database.");
                    return false;
                }

                if (FirstRun)
                {
                    try
                    {
                        BeginTransaction();

                        using var cmd2 = new SQLiteCommand(SQL_CREATE_RUNS, MainConnection.Connection, MainConnection.Transaction);
                        cmd2.ExecuteNonQuery();

                        cmd2.CommandText = SQL_CREATE_RESULTS;
                        cmd2.ExecuteNonQuery();

                        cmd2.CommandText = SQL_CREATE_FINDINGS_RESULTS;
                        cmd2.ExecuteNonQuery();

                        cmd2.CommandText = SQL_CREATE_FINDINGS_LEVEL_INDEX;
                        cmd2.ExecuteNonQuery();

                        cmd2.CommandText = SQL_CREATE_FINDINGS_RESULT_TYPE_INDEX;
                        cmd2.ExecuteNonQuery();

                        cmd2.CommandText = SQL_CREATE_FINDINGS_IDENTITY_INDEX;
                        cmd2.ExecuteNonQuery();

                        cmd2.CommandText = SQL_CREATE_FINDINGS_LEVEL_RESULT_TYPE_INDEX;
                        cmd2.ExecuteNonQuery();

                        cmd2.CommandText = SQL_CREATE_FILE_MONITORED;
                        cmd2.ExecuteNonQuery();

                        cmd2.CommandText = SQL_CREATE_PERSISTED_SETTINGS;
                        cmd2.ExecuteNonQuery();

                        SetSettings(new Settings()
                        {
                            SchemaVersion = SCHEMA_VERSION,
                            ShardingFactor = dbSettings.ShardingFactor,
                            TelemetryEnabled = true
                        });

                        Connections.AsParallel().ForAll(cxn =>
                        {
                            using (var innerCmd = new SQLiteCommand(SQL_CREATE_COLLECT_RESULTS, cxn.Connection, cxn.Transaction))
                            {
                                innerCmd.ExecuteNonQuery();

                                innerCmd.CommandText = SQL_CREATE_COLLECT_RUN_ID_INDEX;
                                innerCmd.ExecuteNonQuery();

                                innerCmd.CommandText = SQL_CREATE_COLLECT_RUN_KEY_IDENTITY_COMBINED_INDEX;
                                innerCmd.ExecuteNonQuery();

                                innerCmd.CommandText = SQL_CREATE_COLLECT_RUN_ID_IDENTITY_INDEX;
                                innerCmd.ExecuteNonQuery();
                            }
                        });
                    }
                    catch (SQLiteException e)
                    {
                        Log.Debug(e, "Failed to set up fresh database.");
                        Environment.Exit((int)ASA_ERROR.FAILED_TO_CREATE_DATABASE);
                    }
                    finally
                    {
                        Commit();
                    }
                }

                return true;
            }
            return false;
        }

        public static void TrimToLatest()
        {
            if (MainConnection != null)
            {
                List<string> Runs = new List<string>();
                using var cmd = new SQLiteCommand(GET_RUNS, MainConnection.Connection, MainConnection.Transaction);
                using (var reader = cmd.ExecuteReader())
                {
                    //Skip first row, that is the one we want to keep
                    reader.Read();

                    while (reader.Read())
                    {
                        DeleteRun((string)reader["run_id"]);
                    }
                }
            }
            else
            {
                Log.Debug("Failed to trim. MainConnection is null.");
            }
        }

        public static void UpdateCompareRun(string firstRunId, string secondRunId, RUN_STATUS runStatus)
        {
            _ = MainConnection ?? throw new NullReferenceException(Strings.Get("MainConnection"));
            using (var cmd = new SQLiteCommand(UPDATE_RUN_IN_RESULT_TABLE, MainConnection.Connection, MainConnection.Transaction))
            {
                cmd.Parameters.AddWithValue("@base_run_id", firstRunId);
                cmd.Parameters.AddWithValue("@compare_run_id", secondRunId);
                cmd.Parameters.AddWithValue("@status", runStatus);
                cmd.ExecuteNonQuery();
            }
        }

        public static void Vacuum()
        {
            Connections.AsParallel().ForAll(cxn =>
            {
                using var inner_cmd = new SQLiteCommand(SQL_VACUUM, cxn.Connection, cxn.Transaction);
                inner_cmd.ExecuteNonQuery();
            });
        }

        public static void Write(CollectObject? colObj, string? runId)
        {
            if (colObj != null && runId != null)
            {
                var objIn = new WriteObject(colObj, runId);
                Connections[ModuloString(objIn.Identity, shardingFactor: dbSettings.ShardingFactor)].WriteQueue.Enqueue(objIn);
            }
        }

        public static void WriteFileMonitor(FileMonitorObject fmo, string RunId)
        {
            if (fmo == null)
            {
                return;
            }
            _ = MainConnection ?? throw new NullReferenceException(Strings.Get("MainConnection"));
            using var cmd = new SQLiteCommand(SQL_INSERT, MainConnection.Connection, MainConnection.Transaction);
            cmd.Parameters.AddWithValue("@run_id", RunId);
            cmd.Parameters.AddWithValue("@path", fmo.Path);
            cmd.Parameters.AddWithValue("@timestamp", fmo.Timestamp);
            cmd.Parameters.AddWithValue("@serialized", JsonConvert.SerializeObject(fmo));

            cmd.ExecuteNonQuery();
        }

        private const string GET_COMPARISON_RESULTS = "select * from findings where comparison_id = @comparison_id and result_type=@result_type order by level des;";
        private const string GET_COMPARISON_RESULTS_LIMIT = "select * from findings where comparison_id=@comparison_id and result_type=@result_type order by level desc limit @offset,@limit;";
        private const string GET_MONITOR_RESULTS = "select * from file_system_monitored where run_id=@run_id order by timestamp limit @offset,@limit;";

        //lgtm [cs/literal-as-local]
        private const string GET_RESULT_COUNT = "select count(*) from findings where comparison_id=@comparison_id and result_type=@result_type";

        //lgtm [cs/literal-as-local]
        private const string GET_RESULT_COUNT_MONITORED = "select count(*) from file_system_monitored where run_id=@run_id;";

        private const string GET_RUNS = "select run_id from runs order by timestamp desc;";
        private const string GET_SERIALIZED_RESULTS = "select change_type, Serialized from file_system_monitored where run_id = @run_id";
        private const string INSERT_RUN_INTO_RESULT_TABLE_SQL = "insert into results (base_run_id, compare_run_id, status) values (@base_run_id, @compare_run_id, @status);";
        private const int SCHEMA_VERSION = 8;
        private const string SQL_CHECK_IF_COMPARISON_PREVIOUSLY_COMPLETED = "select * from results where base_run_id=@base_run_id and compare_run_id=@compare_run_id";
        private const string SQL_CREATE_COLLECT_RESULTS = "create table if not exists collect (run_id text, result_type text, identity text, row_key blob, serialized blob)";
        private const string SQL_CREATE_COLLECT_RUN_ID_IDENTITY_INDEX = "create index if not exists i_collect_collect_run_id_identity on collect(run_id, identity)";
        private const string SQL_CREATE_COLLECT_RUN_ID_INDEX = "create index if not exists i_collect_collect_run_id on collect(run_id)";
        private const string SQL_CREATE_COLLECT_RUN_KEY_IDENTITY_COMBINED_INDEX = "create index if not exists i_collect_collect_runid_row_type on collect(run_id, identity, row_key, result_type)";
        private const string SQL_CREATE_FILE_MONITORED = "create table if not exists file_system_monitored (run_id text, row_key text, timestamp text, change_type int, path text, old_path text, name text, old_name text, extended_results text, notify_filters text, serialized text)";
        private const string SQL_CREATE_FINDINGS_IDENTITY_INDEX = "create index if not exists i_findings_identity on findings(identity)";
        private const string SQL_CREATE_FINDINGS_LEVEL_INDEX = "create index if not exists i_findings_level on findings(level)";
        private const string SQL_CREATE_FINDINGS_LEVEL_RESULT_TYPE_INDEX = "create index if not exists i_findings_level_result_type on findings(level, result_type)";
        private const string SQL_CREATE_FINDINGS_RESULT_TYPE_INDEX = "create index if not exists i_findings_result_type on findings(result_type)";
        private const string SQL_CREATE_FINDINGS_RESULTS = "create table if not exists findings (first_run_id text, second_run_id text, level int, result_type int, identity text, serialized text)";
        private const string SQL_CREATE_PERSISTED_SETTINGS = "create table if not exists persisted_settings (id text, serialized text, unique(id))";
        private const string SQL_CREATE_RESULTS = "create table if not exists results (base_run_id text, compare_run_id text, status text);";
        private const string SQL_CREATE_RUNS = "create table if not exists runs (run_id text, serialized blob, unique(run_id))";
        private const string SQL_DELETE_RUN = "delete from collect where run_id=@run_id";
        private const string SQL_GET_COLLECT_MISSING_IN_B = "select * from collect b where b.run_id = @second_run_id and b.identity not in (select identity from collect a where a.run_id = @first_run_id);";

        private const string SQL_GET_COLLECT_MODIFIED = "select a.serialized as 'a_serialized', a.result_type as 'a_result_type', a.run_id as 'a_run_id'," +
                                                            "b.serialized as 'b_serialized', b.result_type as 'b_result_type', b.run_id as 'b_run_id'" +
                                                                " from collect a indexed by i_collect_collect_runid_row_type," +
                                                                    " collect b indexed by i_collect_collect_runid_row_type" +
                                                                        " where a.run_id=@first_run_id and b.run_id=@second_run_id and a.identity = b.identity and a.row_key != b.row_key and a.result_type = b.result_type;";

        private const string SQL_GET_NUM_RESULTS = "select count(*) as the_count from collect where run_id = @run_id and result_type = @result_type";
        private const string SQL_GET_PERSISTED_SETTINGS = "select serialized from persisted_settings where id=@id";
        private const string SQL_GET_PLATFORM_FROM_RUNID = "select platform from runs where run_id = @run_id";
        private const string SQL_GET_RESULT_TYPES_COUNTS = "select count(*) as count,result_type from collect where run_id = @run_id group by result_type";
        private const string SQL_GET_RESULTS_BY_RUN_ID = "select * from collect where run_id = @run_id";
        private const string SQL_GET_RUN = "select * from runs where run_id = @run_id";
        private const string SQL_INSERT = "insert into file_system_monitored (run_id, row_key, timestamp, change_type, path, old_path, name, old_name, extended_results, notify_filters, serialized) values (@run_id, @row_key, @timestamp, @change_type, @path, @old_path, @name, @old_name, @extended_results, @notify_filters, @serialized)";
        private const string SQL_INSERT_FINDINGS_RESULT = "insert into findings (first_run_id, second_run_id, result_type, level, identity, serialized) values (@first_run_id, @second_run_id, @result_type, @level, @identity, @serialized)";
        private const string SQL_INSERT_RUN = "insert into runs (run_id, type, serialized) values (@run_id, @type, @serialized)";
        private const string SQL_QUERY_ANALYZED = "select * from results where status = @status";
        private const string SQL_SELECT_LATEST_N_RUNS = "select run_id from runs where type = @type order by timestamp desc limit 0,@limit;";
        private const string SQL_TRUNCATE_RUN = "delete from runs where run_id=@run_id";
        private const string SQL_UPSERT_PERSISTED_SETTINGS = "insert or replace into persisted_settings (id, serialized) values (@id, @serialized)";
        private const string SQL_VACUUM = "VACUUM";
        private const string UPDATE_RUN_IN_RESULT_TABLE = "update results set status = @status where (base_run_id = @base_run_id and compare_run_id = @compare_run_id)";
        //lgtm [cs/literal-as-local]

        //lgtm [cs/literal-as-local]

        //lgtm [cs/literal-as-local]

        //lgtm [cs/literal-as-local]

        //lgtm [cs/literal-as-local]
        private static DBSettings dbSettings = new DBSettings();

        private static SystemSQLiteSqlConnectionHolder GenerateSqlConnection(int i)
        {
            if (i == 0)
            {
                return new SystemSQLiteSqlConnectionHolder(SQLiteFilename, dbSettings);
            }
            else
            {
                return new SystemSQLiteSqlConnectionHolder($"{SQLiteFilename}_{i}", dbSettings);
            }
        }

        private static Settings? GetSettings()
        {
            try
            {
                using var getSettings = new SQLiteCommand(SQL_GET_PERSISTED_SETTINGS, MainConnection?.Connection, MainConnection?.Transaction);
                getSettings.Parameters.AddWithValue("@id", "Persisted");
                using var reader = getSettings.ExecuteReader();

                // Settings exist, this isn't the first run
                if (reader.HasRows)
                {
                    while (reader.Read())
                    {
                        return JsonConvert.DeserializeObject<Settings>((string)reader["serialized"]);
                    }
                }
            }
            catch (Exception e) when (e is SQLiteException || e is ArgumentNullException || e is NullReferenceException)
            {
                //Expected when the table doesn't exist (first run)
            }

            return null;
        }

        private static void SetSettings(Settings settings)
        {
            try
            {
                using var cmd = new SQLiteCommand(SQL_UPSERT_PERSISTED_SETTINGS, MainConnection?.Connection, MainConnection?.Transaction);
                cmd.Parameters.AddWithValue("@serialized", JsonConvert.SerializeObject(settings));
                cmd.Parameters.AddWithValue("@id", "Persisted");
                cmd.ExecuteNonQuery();
            }
            catch (SQLiteException) { }
            // Main Connection is probably null
            catch (NullReferenceException) { }
        }
    }
}

{'repo_name': 'microsoft/AttackSurfaceAnalyzer', 'stars': '1214', 'repo_language': 'C#', 'file_name': 'AsaAnalyzerTests.cs', 'mime_type': 'text/plain', 'hash': -650380331071895353, 'source_dataset': 'data'}


package test.thread.parallelization.sample;

import org.testng.ITestContext;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Factory;
import org.testng.annotations.Test;
import test.thread.parallelization.TestNgRunStateTracker;

import java.util.Map;
import java.util.concurrent.TimeUnit;

import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.CLASS_INSTANCE;
import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.CLASS_NAME;
import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.DATA_PROVIDER_PARAM;
import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.GROUPS_BELONGING_TO;
import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.GROUPS_DEPENDED_ON;
import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.METHODS_DEPENDED_ON;
import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.METHOD_NAME;
import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.SUITE_NAME;
import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.TEST_NAME;
import static test.thread.parallelization.TestNgRunStateTracker.TestNgRunEvent.TEST_METHOD_EXECUTION;

public class TestClassDThreeMethodsWithFactoryUsingDataProviderAndNoDepsSample {

    private final String suiteName;
    private final String testName;
    private final int sleepFor;
    private final String dpVal;

    @Factory(dataProvider = "data-provider")
    public TestClassDThreeMethodsWithFactoryUsingDataProviderAndNoDepsSample(String suiteName, String testName, String
            sleepFor, String dpVal) {

        this.suiteName = suiteName;
        this.testName = testName;
        this.sleepFor = Integer.parseInt(sleepFor);
        this.dpVal = dpVal;
    }

    @Test
    public void testMethodA() throws
            InterruptedException {
        long time = System.currentTimeMillis();

        TestNgRunStateTracker.logEvent(
                TestNgRunStateTracker.EventLog.builder()
                        .setEvent(TEST_METHOD_EXECUTION)
                        .setTimeOfEvent(time)
                        .setThread(Thread.currentThread())
                        .addData(METHOD_NAME, "testMethodA")
                        .addData(CLASS_NAME, getClass().getCanonicalName())
                        .addData(CLASS_INSTANCE, this)
                        .addData(TEST_NAME, testName)
                        .addData(SUITE_NAME, suiteName)
                        .addData(DATA_PROVIDER_PARAM, dpVal)
                        .addData(GROUPS_DEPENDED_ON, new String[0])
                        .addData(METHODS_DEPENDED_ON, new String[0])
                        .addData(GROUPS_BELONGING_TO, new String[0])
                        .build()
        );

        TimeUnit.MILLISECONDS.sleep(sleepFor);
    }

    @Test
    public void testMethodB() throws
            InterruptedException {
        long time = System.currentTimeMillis();

        TestNgRunStateTracker.logEvent(
                TestNgRunStateTracker.EventLog.builder()
                        .setEvent(TEST_METHOD_EXECUTION)
                        .setTimeOfEvent(time)
                        .setThread(Thread.currentThread())
                        .addData(METHOD_NAME, "testMethodB")
                        .addData(CLASS_NAME, getClass().getCanonicalName())
                        .addData(CLASS_INSTANCE, this)
                        .addData(TEST_NAME, testName)
                        .addData(SUITE_NAME, suiteName)
                        .addData(DATA_PROVIDER_PARAM, dpVal)
                        .addData(GROUPS_DEPENDED_ON, new String[0])
                        .addData(METHODS_DEPENDED_ON, new String[0])
                        .addData(GROUPS_BELONGING_TO, new String[0])
                        .build()
        );

        TimeUnit.MILLISECONDS.sleep(sleepFor);
    }

    @Test
    public void testMethodC() throws
            InterruptedException {
        long time = System.currentTimeMillis();

        TestNgRunStateTracker.logEvent(
                TestNgRunStateTracker.EventLog.builder()
                        .setEvent(TEST_METHOD_EXECUTION)
                        .setTimeOfEvent(time)
                        .setThread(Thread.currentThread())
                        .addData(METHOD_NAME, "testMethodC")
                        .addData(CLASS_NAME, getClass().getCanonicalName())
                        .addData(CLASS_INSTANCE, this)
                        .addData(TEST_NAME, testName)
                        .addData(SUITE_NAME, suiteName)
                        .addData(DATA_PROVIDER_PARAM, dpVal)
                        .addData(GROUPS_DEPENDED_ON, new String[0])
                        .addData(METHODS_DEPENDED_ON, new String[0])
                        .addData(GROUPS_BELONGING_TO, new String[0])
                        .build()
        );

        TimeUnit.MILLISECONDS.sleep(sleepFor);
    }

    @DataProvider(name = "data-provider")
    public static Object[][] dataProvider(ITestContext context) {
        Map<String,String> params = context.getCurrentXmlTest().getAllParameters();

        String suiteName = params.get("suiteName");
        String testName = params.get("testName");
        String sleepFor = params.get("sleepFor");

        String dataProviderParam = params.get("dataProviderParam");

        String[] dataProviderVals = null;
        String classNamePattern = TestClassDThreeMethodsWithFactoryUsingDataProviderAndNoDepsSample.class
                .getSimpleName() + "(";

        if(dataProviderParam.contains(classNamePattern)) {
            dataProviderParam = dataProviderParam.substring(dataProviderParam.indexOf(classNamePattern) +
                    classNamePattern.length());
            dataProviderParam = dataProviderParam.substring(0,dataProviderParam.indexOf(")"));
        }

        dataProviderVals = dataProviderParam.split(",");

        Object[][] dataToProvide = new Object[dataProviderVals.length][4];

        for(int i = 0; i < dataProviderVals.length; i ++)  {
            dataToProvide[i][0] = suiteName;
            dataToProvide[i][1] = testName;
            dataToProvide[i][2] = sleepFor;
            dataToProvide[i][3] = dataProviderVals[i];
        }

        return dataToProvide;
    }
}

{'repo_name': 'cbeust/testng', 'stars': '1501', 'repo_language': 'Java', 'file_name': 'Build.kt', 'mime_type': 'text/plain', 'hash': 1142494438770250982, 'source_dataset': 'data'}


import * as React from "react";
import {connect} from "react-redux";
import {RouteComponentProps} from "react-router";
import {bindActionCreators, Dispatch} from "redux";
import {Container, Header} from "semantic-ui-react";
import {DeviceAuthForm, IDeviceAuthFormValues} from "../../components/forms/DeviceAuthForm";
import {RootState} from "../../reducers";
import * as actions from "../../store/configuration/scep_actions";
import {SCEPState} from "../../store/configuration/scep_reducer";

interface ReduxStateProps {
    scep: SCEPState;
}

interface ReduxDispatchProps {
    read: actions.ReadActionRequest;
    post: actions.PostActionRequest;
}

interface OwnProps extends ReduxStateProps, ReduxDispatchProps, RouteComponentProps<{}> {

}

export class UnconnectedDeviceAuthPage extends React.Component<OwnProps, undefined> {

    public componentWillMount?() {
        this.props.read();
    }

    private handleSubmit = (values: IDeviceAuthFormValues): void => {
        this.props.post({
            ...values,
            key_size: values.key_size,
            key_usage: values.key_usage,
        });
    };

    private handleTest = () => {

    };

    public render() {
        const {
            scep,
        } = this.props;

        const stringifiedData = {
            ...scep.data,
            key_size: scep.data ? "" + scep.data.key_size : null,
            key_usage: scep.data ? "" + scep.data.key_usage : null,
        };

        return (
            <Container className="SCEPPage">
                Device Authentication

                    Use this section to configure how your device will securely contact the MDM server.

                <DeviceAuthForm loading={scep.loading} data={scep.data} onSubmit={this.handleSubmit} />
            </Container>
        )
    }

}

export const DeviceAuthPage = connect<ReduxStateProps, ReduxDispatchProps, OwnProps>(
    (state: RootState): ReduxStateProps => ({
        scep: state.configuration.scep,
    }),
    (dispatch: Dispatch) => bindActionCreators({
        post: actions.post,
        read: actions.read,
    }, dispatch),
)(UnconnectedDeviceAuthPage);

{'repo_name': 'cmdmnt/commandment', 'stars': '202', 'repo_language': 'Python', 'file_name': 'config.yml', 'mime_type': 'text/plain', 'hash': 4393865405575425458, 'source_dataset': 'data'}


package logging

import (
	"fmt"
	"os"

	"github.com/go-kit/kit/log"
	"github.com/go-kit/kit/log/level"
)

// NewGoKit creates a new Interface backed by a GoKit logger
func NewGoKit(l Level) Interface {
	logger := log.NewLogfmtLogger(log.NewSyncWriter(os.Stderr))
	logger = level.NewFilter(logger, l.Gokit)
	logger = log.With(logger, "ts", log.DefaultTimestampUTC, "caller", log.DefaultCaller)
	return gokit{logger}
}

// GoKit wraps an existing gokit Logger.
func GoKit(logger log.Logger) Interface {
	return gokit{logger}
}

type gokit struct {
	log.Logger
}

func (g gokit) Debugf(format string, args ...interface{}) {
	level.Debug(g.Logger).Log("msg", fmt.Sprintf(format, args...))
}
func (g gokit) Debugln(args ...interface{}) {
	level.Debug(g.Logger).Log("msg", fmt.Sprintln(args...))
}

func (g gokit) Infof(format string, args ...interface{}) {
	level.Info(g.Logger).Log("msg", fmt.Sprintf(format, args...))
}
func (g gokit) Infoln(args ...interface{}) {
	level.Info(g.Logger).Log("msg", fmt.Sprintln(args...))
}

func (g gokit) Warnf(format string, args ...interface{}) {
	level.Warn(g.Logger).Log("msg", fmt.Sprintf(format, args...))
}
func (g gokit) Warnln(args ...interface{}) {
	level.Warn(g.Logger).Log("msg", fmt.Sprintln(args...))
}

func (g gokit) Errorf(format string, args ...interface{}) {
	level.Error(g.Logger).Log("msg", fmt.Sprintf(format, args...))
}
func (g gokit) Errorln(args ...interface{}) {
	level.Error(g.Logger).Log("msg", fmt.Sprintln(args...))
}

func (g gokit) WithField(key string, value interface{}) Interface {
	return gokit{log.With(g.Logger, key, value)}
}

func (g gokit) WithFields(fields Fields) Interface {
	logger := g.Logger
	for k, v := range fields {
		logger = log.With(logger, k, v)
	}
	return gokit{logger}
}

{'repo_name': 'weaveworks/scope', 'stars': '4447', 'repo_language': 'Go', 'file_name': 'config.yml', 'mime_type': 'text/plain', 'hash': 789733372833137720, 'source_dataset': 'data'}


note_start: 2019-03-19
note_track:
  track_url: https://github.com/ff-notes/ff/issues/138
  track_source: ff-notes/ff
  track_externalId: '138'
  track_provider: github
note_links: []
note_text: "Publish ff on Hackage (?)\n\nto install with just\r\n\r\n    cabal install\r\n\r\nor\r\n\r\n
  \   stack install"
note_end: null
note_status:
  TaskStatus: Active
note_tags:
  B/7euI15E2jb+00P01fLmVG: level_Research
  B/7euI15E31g+00P01fLmVG: type_Idea

{'repo_name': 'ff-notes/ff', 'stars': '139', 'repo_language': 'Haskell', 'file_name': 'Dockerfile', 'mime_type': 'text/plain', 'hash': 362911221192117802, 'source_dataset': 'data'}


/*
 *     Generated by class-dump 3.3.4 (64 bit).
 *
 *     class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2011 by Steve Nygard.
 */

#import "NSObject.h"

@class WebNodeHighlight, WebView;

@interface WebNodeHighlighter : NSObject
{
    WebView *_inspectedWebView;
    WebNodeHighlight *_currentHighlight;
}

- (void)willDetachWebNodeHighlight:(id)arg1;
- (void)didAttachWebNodeHighlight:(id)arg1;
- (void)hideHighlight;
- (void)highlight;
- (void)dealloc;
- (id)initWithInspectedWebView:(id)arg1;

@end

{'repo_name': 'mattlawer/iOS6-Private-Frameworks', 'stars': '107', 'repo_language': 'Objective-C', 'file_name': 'Parser.h', 'mime_type': 'text/x-objective-c', 'hash': 7534050695628066261, 'source_dataset': 'data'}


#!/usr/bin/gawk -f
# SPDX-License-Identifier: GPL-2.0

# Script to check sysctl documentation against source files
#
# Copyright (c) 2020 Stephen Kitt

# Example invocation:
#	scripts/check-sysctl-docs -vtable="kernel" \
#		Documentation/admin-guide/sysctl/kernel.rst \
#		$(git grep -l register_sysctl_)
#
# Specify -vdebug=1 to see debugging information

BEGIN {
    if (!table) {
	print "Please specify the table to look for using the table variable" > "/dev/stderr"
	exit 1
    }
}

# The following globals are used:
# children: maps ctl_table names and procnames to child ctl_table names
# documented: maps documented entries (each key is an entry)
# entries: maps ctl_table names and procnames to counts (so
#          enumerating the subkeys for a given ctl_table lists its
#          procnames)
# files: maps procnames to source file names
# paths: maps ctl_path names to paths
# curpath: the name of the current ctl_path struct
# curtable: the name of the current ctl_table struct
# curentry: the name of the current proc entry (procname when parsing
#           a ctl_table, constructed path when parsing a ctl_path)

# Remove punctuation from the given value
function trimpunct(value) {
    while (value ~ /^["&]/) {
	value = substr(value, 2)
    }
    while (value ~ /[]["&,}]$/) {
	value = substr(value, 1, length(value) - 1)
    }
    return value
}

# Print the information for the given entry
function printentry(entry) {
    seen[entry]++
    printf "* %s from %s", entry, file[entry]
    if (documented[entry]) {
	printf " (documented)"
    }
    print ""
}

# Stage 1: build the list of documented entries
FNR == NR && /^=+$/ {
    if (prevline ~ /Documentation for/) {
	# This is the main title
	next
    }

    # The previous line is a section title, parse it
    $0 = prevline
    if (debug) print "Parsing " $0
    inbrackets = 0
    for (i = 1; i <= NF; i++) {
	if (length($i) == 0) {
	    continue
	}
	if (!inbrackets && substr($i, 1, 1) == "(") {
	    inbrackets = 1
	}
	if (!inbrackets) {
	    token = trimpunct($i)
	    if (length(token) > 0 && token != "and") {
		if (debug) print trimpunct($i)
		documented[trimpunct($i)]++
	    }
	}
	if (inbrackets && substr($i, length($i), 1) == ")") {
	    inbrackets = 0
	}
    }
}

FNR == NR {
    prevline = $0
    next
}

# Stage 2: process each file and find all sysctl tables
BEGINFILE {
    delete children
    delete entries
    delete paths
    curpath = ""
    curtable = ""
    curentry = ""
    if (debug) print "Processing file " FILENAME
}

/^static struct ctl_path/ {
    match($0, /static struct ctl_path ([^][]+)/, tables)
    curpath = tables[1]
    if (debug) print "Processing path " curpath
}

/^static struct ctl_table/ {
    match($0, /static struct ctl_table ([^][]+)/, tables)
    curtable = tables[1]
    if (debug) print "Processing table " curtable
}

/^};$/ {
    curpath = ""
    curtable = ""
    curentry = ""
}

curpath && /\.procname[\t ]*=[\t ]*".+"/ {
    match($0, /.procname[\t ]*=[\t ]*"([^"]+)"/, names)
    if (curentry) {
	curentry = curentry "/" names[1]
    } else {
	curentry = names[1]
    }
    if (debug) print "Setting path " curpath " to " curentry
    paths[curpath] = curentry
}

curtable && /\.procname[\t ]*=[\t ]*".+"/ {
    match($0, /.procname[\t ]*=[\t ]*"([^"]+)"/, names)
    curentry = names[1]
    if (debug) print "Adding entry " curentry " to table " curtable
    entries[curtable][curentry]++
    file[curentry] = FILENAME
}

/\.child[\t ]*=/ {
    child = trimpunct($NF)
    if (debug) print "Linking child " child " to table " curtable " entry " curentry
    children[curtable][curentry] = child
}

/register_sysctl_table\(.*\)/ {
    match($0, /register_sysctl_table\(([^)]+)\)/, tables)
    if (debug) print "Registering table " tables[1]
    if (children[tables[1]][table]) {
	for (entry in entries[children[tables[1]][table]]) {
	    printentry(entry)
	}
    }
}

/register_sysctl_paths\(.*\)/ {
    match($0, /register_sysctl_paths\(([^)]+), ([^)]+)\)/, tables)
    if (debug) print "Attaching table " tables[2] " to path " tables[1]
    if (paths[tables[1]] == table) {
	for (entry in entries[tables[2]]) {
	    printentry(entry)
	}
    }
    split(paths[tables[1]], components, "/")
    if (length(components) > 1 && components[1] == table) {
	# Count the first subdirectory as seen
	seen[components[2]]++
    }
}

END {
    for (entry in documented) {
	if (!seen[entry]) {
	    print "No implementation for " entry
	}
    }
}

{'repo_name': 'intel/gvt-linux', 'stars': '276', 'repo_language': 'C', 'file_name': 'u_os_desc.h', 'mime_type': 'text/x-c', 'hash': 3368286251323071532, 'source_dataset': 'data'}


<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace TestBundle\Sensio\FooBundle\Controller;

/**
 * DefaultController.
 *
 * @author Fabien Potencier <fabien@symfony.com>
 */
class DefaultController
{
}

{'repo_name': 'symfony/framework-bundle', 'stars': '2553', 'repo_language': 'PHP', 'file_name': 'SuggestMissingPackageSubscriber.php', 'mime_type': 'text/x-php', 'hash': -688554693593578818, 'source_dataset': 'data'}


require_once 'Zend/Uri/Http.php';

namespace Location\Web;

interface Factory
{
    static function _factory();
}

abstract class URI extends BaseURI implements Factory
{
    abstract function test();

    public static $st1 = 1;
    const ME = "Yo";
    var $list = NULL;
    private $var;

    /**
     * Returns a URI
     *
     * @return URI
     */
    static public function _factory($stats = array(), $uri = 'http')
    {
        echo __METHOD__;
        $uri = explode(':', $uri, 0b10);
        $schemeSpecific = isset($uri[1]) ? $uri[1] : '';
        $desc = 'Multi
line description';

        // Security check
        if (!ctype_alnum($scheme)) {
            throw new Zend_Uri_Exception('Illegal scheme');
        }

        $this->var = 0 - self::$st;
        $this->list = list(Array("1"=> 2, 2=>self::ME, 3 => \Location\Web\URI::class));

        return [
            'uri'   => $uri,
            'value' => null,
        ];
    }
}

echo URI::ME . URI::$st1;

__halt_compiler () ; datahere
datahere
datahere */
datahere

{'repo_name': 'raspu/Highlightr', 'stars': '965', 'repo_language': 'Swift', 'file_name': 'Info.plist', 'mime_type': 'text/xml', 'hash': 6723151470936072811, 'source_dataset': 'data'}


/*
 *=BEGIN SONGBIRD GPL
 *
 * This file is part of the Songbird web player.
 *
 * Copyright(c) 2005-2010 POTI, Inc.
 * http://www.songbirdnest.com
 *
 * This file may be licensed under the terms of of the
 * GNU General Public License Version 2 (the ``GPL'').
 *
 * Software distributed under the License is distributed
 * on an ``AS IS'' basis, WITHOUT WARRANTY OF ANY KIND, either
 * express or implied. See the GPL for the specific language
 * governing rights and limitations.
 *
 * You should have received a copy of the GPL along with this
 * program. If not, go to http://www.gnu.org/licenses/gpl.html
 * or write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 *=END SONGBIRD GPL
 */

#include "nsISupports.idl"

interface nsISimpleEnumerator;
interface sbIMediaList;

[scriptable, uuid(716ea01c-c6bc-46df-8c29-6687c72617a5)]
interface sbIMediaListDuplicateFilter : nsISupports
{
  void initialize(in nsISimpleEnumerator aSource,
                  in sbIMediaList aDestination,
                  in boolean aRemoveDuplicates);
  readonly attribute PRUint32 totalItems;
  readonly attribute PRUint32 duplicateItems;
};

{'repo_name': 'nightingale-media-player/nightingale-hacking', 'stars': '181', 'repo_language': 'C++', 'file_name': 'sbITabBrowser.idl', 'mime_type': 'text/x-c', 'hash': 3058080899706057585, 'source_dataset': 'data'}


<?php
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
namespace Magento\Framework\View\Test\Unit\Asset;

use Magento\Framework\Filesystem;
use Magento\Framework\View\Asset\LockerProcess;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\Filesystem\Directory\WriteInterface;
use Magento\Framework\App\State;
use Magento\Framework\TestFramework\Unit\Helper\ObjectManager;

/**
 * Class LockerProcessTest
 *
 * @see \Magento\Framework\View\Asset\LockerProcess
 */
class LockerProcessTest extends \PHPUnit\Framework\TestCase
{
    const LOCK_NAME = 'test-lock';

    /**
     * @var string
     */
    private $fileName;

    /**
     * @var LockerProcess
     */
    private $lockerProcess;

    /**
     * @var Filesystem|\PHPUnit_Framework_MockObject_MockObject
     */
    private $filesystemMock;

    /**
     * @var State|\PHPUnit_Framework_MockObject_MockObject
     */
    private $stateMock;

    /**
     * Set up
     */
    protected function setUp()
    {
        $this->fileName = DirectoryList::TMP . DIRECTORY_SEPARATOR . self::LOCK_NAME . LockerProcess::LOCK_EXTENSION;

        $this->filesystemMock = $this->getMockBuilder(\Magento\Framework\Filesystem::class)
            ->disableOriginalConstructor()
            ->getMock();
        $this->stateMock = $this->getMockBuilder(State::class)
            ->disableOriginalConstructor()
            ->getMock();

        $this->lockerProcess = (new ObjectManager($this))->getObject(
            LockerProcess::class,
            [
                'filesystem' => $this->filesystemMock,
                'state' => $this->stateMock,
            ]
        );
    }

    public function testNotLockProcessInProductionMode()
    {
        $this->stateMock->expects(self::once())->method('getMode')->willReturn(State::MODE_PRODUCTION);
        $this->filesystemMock->expects($this->never())->method('getDirectoryWrite');

        $this->lockerProcess->lockProcess(self::LOCK_NAME);
    }

    public function testNotUnlockProcessInProductionMode()
    {
        $this->stateMock->expects(self::exactly(2))->method('getMode')->willReturn(State::MODE_PRODUCTION);
        $this->filesystemMock->expects(self::never())->method('getDirectoryWrite');

        $this->lockerProcess->lockProcess(self::LOCK_NAME);
        $this->lockerProcess->unlockProcess();
    }

    /**
     * @return WriteInterface|\PHPUnit_Framework_MockObject_MockObject
     */
    protected function getTmpDirectoryMockTrue()
    {
        $tmpDirectoryMock = $this->getTmpDirectoryMock();

        $tmpDirectoryMock->expects(self::atLeastOnce())
            ->method('isExist')
            ->with($this->fileName)
            ->willReturn(true);

        $tmpDirectoryMock->expects(self::atLeastOnce())
            ->method('readFile')
            ->with($this->fileName)
            ->willReturn(time() - 25);

        $tmpDirectoryMock->expects(self::once())
            ->method('writeFile')
            ->with($this->fileName, self::matchesRegularExpression('#\d+#'));

        return $tmpDirectoryMock;
    }

    /**
     * @param int $exactly
     * @return WriteInterface|\PHPUnit_Framework_MockObject_MockObject
     */
    protected function getTmpDirectoryMockFalse($exactly = 0)
    {
        $tmpDirectoryMock = $this->getTmpDirectoryMock();

        $tmpDirectoryMock->expects(self::atLeastOnce())
            ->method('isExist')
            ->with($this->fileName)
            ->willReturn(false);

        $tmpDirectoryMock->expects(self::never())
            ->method('readFile');

        $tmpDirectoryMock->expects(self::exactly($exactly))
            ->method('delete')
            ->with($this->fileName);

        $tmpDirectoryMock->expects(self::once())
            ->method('writeFile')
            ->with($this->fileName, self::matchesRegularExpression('#\d+#'));

        return $tmpDirectoryMock;
    }

    /**
     * @return WriteInterface|\PHPUnit_Framework_MockObject_MockObject
     */
    private function getTmpDirectoryMock()
    {
        $tmpDirectoryMock = $this->getMockBuilder(\Magento\Framework\Filesystem\Directory\WriteInterface::class)
            ->getMockForAbstractClass();

        return $tmpDirectoryMock;
    }
}

{'repo_name': 'magento/graphql-ce', 'stars': '136', 'repo_language': 'PHP', 'file_name': 'report.phtml', 'mime_type': 'text/x-php', 'hash': -2189693384863862866, 'source_dataset': 'data'}


/*=============================================================================
    Copyright (c) 2001-2011 Joel de Guzman
    Copyright (c) 2005 Eric Niebler

    Distributed under the Boost Software License, Version 1.0. (See accompanying
    file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
==============================================================================*/
#if !defined(FUSION_VALUE_OF_IMPL_07172005_0838)
#define FUSION_VALUE_OF_IMPL_07172005_0838

namespace boost { namespace fusion
{
    struct cons_iterator_tag;

    namespace extension
    {
        template <typename Tag>
        struct value_of_impl;

        template <>
        struct value_of_impl<cons_iterator_tag>
        {
            template <typename Iterator>
            struct apply
            {
                typedef typename Iterator::cons_type cons_type;
                typedef typename cons_type::car_type type;
            };
        };
    }

}}

#endif

{'repo_name': 'google/binexport', 'stars': '491', 'repo_language': 'C++', 'file_name': 'typeof_impl.hpp', 'mime_type': 'text/x-c++', 'hash': -2873709918925179741, 'source_dataset': 'data'}


/**
 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
 * SPDX-License-Identifier: Apache-2.0.
 */

#pragma once
#include <aws/medialive/MediaLive_EXPORTS.h>
#include <aws/medialive/model/ArchiveOutputSettings.h>
#include <aws/medialive/model/FrameCaptureOutputSettings.h>
#include <aws/medialive/model/HlsOutputSettings.h>
#include <aws/medialive/model/MediaPackageOutputSettings.h>
#include <aws/medialive/model/MsSmoothOutputSettings.h>
#include <aws/medialive/model/MultiplexOutputSettings.h>
#include <aws/medialive/model/RtmpOutputSettings.h>
#include <aws/medialive/model/UdpOutputSettings.h>
#include <utility>

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

  /**
   * Output Settings

See Also:
   AWS
   * API Reference

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

    inline const ArchiveOutputSettings& GetArchiveOutputSettings() const{ return m_archiveOutputSettings; }

    inline bool ArchiveOutputSettingsHasBeenSet() const { return m_archiveOutputSettingsHasBeenSet; }

    inline void SetArchiveOutputSettings(const ArchiveOutputSettings& value) { m_archiveOutputSettingsHasBeenSet = true; m_archiveOutputSettings = value; }

    inline void SetArchiveOutputSettings(ArchiveOutputSettings&& value) { m_archiveOutputSettingsHasBeenSet = true; m_archiveOutputSettings = std::move(value); }

    inline OutputSettings& WithArchiveOutputSettings(const ArchiveOutputSettings& value) { SetArchiveOutputSettings(value); return *this;}

    inline OutputSettings& WithArchiveOutputSettings(ArchiveOutputSettings&& value) { SetArchiveOutputSettings(std::move(value)); return *this;}

    inline const FrameCaptureOutputSettings& GetFrameCaptureOutputSettings() const{ return m_frameCaptureOutputSettings; }

    inline bool FrameCaptureOutputSettingsHasBeenSet() const { return m_frameCaptureOutputSettingsHasBeenSet; }

    inline void SetFrameCaptureOutputSettings(const FrameCaptureOutputSettings& value) { m_frameCaptureOutputSettingsHasBeenSet = true; m_frameCaptureOutputSettings = value; }

    inline void SetFrameCaptureOutputSettings(FrameCaptureOutputSettings&& value) { m_frameCaptureOutputSettingsHasBeenSet = true; m_frameCaptureOutputSettings = std::move(value); }

    inline OutputSettings& WithFrameCaptureOutputSettings(const FrameCaptureOutputSettings& value) { SetFrameCaptureOutputSettings(value); return *this;}

    inline OutputSettings& WithFrameCaptureOutputSettings(FrameCaptureOutputSettings&& value) { SetFrameCaptureOutputSettings(std::move(value)); return *this;}

    inline const HlsOutputSettings& GetHlsOutputSettings() const{ return m_hlsOutputSettings; }

    inline bool HlsOutputSettingsHasBeenSet() const { return m_hlsOutputSettingsHasBeenSet; }

    inline void SetHlsOutputSettings(const HlsOutputSettings& value) { m_hlsOutputSettingsHasBeenSet = true; m_hlsOutputSettings = value; }

    inline void SetHlsOutputSettings(HlsOutputSettings&& value) { m_hlsOutputSettingsHasBeenSet = true; m_hlsOutputSettings = std::move(value); }

    inline OutputSettings& WithHlsOutputSettings(const HlsOutputSettings& value) { SetHlsOutputSettings(value); return *this;}

    inline OutputSettings& WithHlsOutputSettings(HlsOutputSettings&& value) { SetHlsOutputSettings(std::move(value)); return *this;}

    inline const MediaPackageOutputSettings& GetMediaPackageOutputSettings() const{ return m_mediaPackageOutputSettings; }

    inline bool MediaPackageOutputSettingsHasBeenSet() const { return m_mediaPackageOutputSettingsHasBeenSet; }

    inline void SetMediaPackageOutputSettings(const MediaPackageOutputSettings& value) { m_mediaPackageOutputSettingsHasBeenSet = true; m_mediaPackageOutputSettings = value; }

    inline void SetMediaPackageOutputSettings(MediaPackageOutputSettings&& value) { m_mediaPackageOutputSettingsHasBeenSet = true; m_mediaPackageOutputSettings = std::move(value); }

    inline OutputSettings& WithMediaPackageOutputSettings(const MediaPackageOutputSettings& value) { SetMediaPackageOutputSettings(value); return *this;}

    inline OutputSettings& WithMediaPackageOutputSettings(MediaPackageOutputSettings&& value) { SetMediaPackageOutputSettings(std::move(value)); return *this;}

    inline const MsSmoothOutputSettings& GetMsSmoothOutputSettings() const{ return m_msSmoothOutputSettings; }

    inline bool MsSmoothOutputSettingsHasBeenSet() const { return m_msSmoothOutputSettingsHasBeenSet; }

    inline void SetMsSmoothOutputSettings(const MsSmoothOutputSettings& value) { m_msSmoothOutputSettingsHasBeenSet = true; m_msSmoothOutputSettings = value; }

    inline void SetMsSmoothOutputSettings(MsSmoothOutputSettings&& value) { m_msSmoothOutputSettingsHasBeenSet = true; m_msSmoothOutputSettings = std::move(value); }

    inline OutputSettings& WithMsSmoothOutputSettings(const MsSmoothOutputSettings& value) { SetMsSmoothOutputSettings(value); return *this;}

    inline OutputSettings& WithMsSmoothOutputSettings(MsSmoothOutputSettings&& value) { SetMsSmoothOutputSettings(std::move(value)); return *this;}

    inline const MultiplexOutputSettings& GetMultiplexOutputSettings() const{ return m_multiplexOutputSettings; }

    inline bool MultiplexOutputSettingsHasBeenSet() const { return m_multiplexOutputSettingsHasBeenSet; }

    inline void SetMultiplexOutputSettings(const MultiplexOutputSettings& value) { m_multiplexOutputSettingsHasBeenSet = true; m_multiplexOutputSettings = value; }

    inline void SetMultiplexOutputSettings(MultiplexOutputSettings&& value) { m_multiplexOutputSettingsHasBeenSet = true; m_multiplexOutputSettings = std::move(value); }

    inline OutputSettings& WithMultiplexOutputSettings(const MultiplexOutputSettings& value) { SetMultiplexOutputSettings(value); return *this;}

    inline OutputSettings& WithMultiplexOutputSettings(MultiplexOutputSettings&& value) { SetMultiplexOutputSettings(std::move(value)); return *this;}

    inline const RtmpOutputSettings& GetRtmpOutputSettings() const{ return m_rtmpOutputSettings; }

    inline bool RtmpOutputSettingsHasBeenSet() const { return m_rtmpOutputSettingsHasBeenSet; }

    inline void SetRtmpOutputSettings(const RtmpOutputSettings& value) { m_rtmpOutputSettingsHasBeenSet = true; m_rtmpOutputSettings = value; }

    inline void SetRtmpOutputSettings(RtmpOutputSettings&& value) { m_rtmpOutputSettingsHasBeenSet = true; m_rtmpOutputSettings = std::move(value); }

    inline OutputSettings& WithRtmpOutputSettings(const RtmpOutputSettings& value) { SetRtmpOutputSettings(value); return *this;}

    inline OutputSettings& WithRtmpOutputSettings(RtmpOutputSettings&& value) { SetRtmpOutputSettings(std::move(value)); return *this;}

    inline const UdpOutputSettings& GetUdpOutputSettings() const{ return m_udpOutputSettings; }

    inline bool UdpOutputSettingsHasBeenSet() const { return m_udpOutputSettingsHasBeenSet; }

    inline void SetUdpOutputSettings(const UdpOutputSettings& value) { m_udpOutputSettingsHasBeenSet = true; m_udpOutputSettings = value; }

    inline void SetUdpOutputSettings(UdpOutputSettings&& value) { m_udpOutputSettingsHasBeenSet = true; m_udpOutputSettings = std::move(value); }

    inline OutputSettings& WithUdpOutputSettings(const UdpOutputSettings& value) { SetUdpOutputSettings(value); return *this;}

    inline OutputSettings& WithUdpOutputSettings(UdpOutputSettings&& value) { SetUdpOutputSettings(std::move(value)); return *this;}

  private:

    ArchiveOutputSettings m_archiveOutputSettings;
    bool m_archiveOutputSettingsHasBeenSet;

    FrameCaptureOutputSettings m_frameCaptureOutputSettings;
    bool m_frameCaptureOutputSettingsHasBeenSet;

    HlsOutputSettings m_hlsOutputSettings;
    bool m_hlsOutputSettingsHasBeenSet;

    MediaPackageOutputSettings m_mediaPackageOutputSettings;
    bool m_mediaPackageOutputSettingsHasBeenSet;

    MsSmoothOutputSettings m_msSmoothOutputSettings;
    bool m_msSmoothOutputSettingsHasBeenSet;

    MultiplexOutputSettings m_multiplexOutputSettings;
    bool m_multiplexOutputSettingsHasBeenSet;

    RtmpOutputSettings m_rtmpOutputSettings;
    bool m_rtmpOutputSettingsHasBeenSet;

    UdpOutputSettings m_udpOutputSettings;
    bool m_udpOutputSettingsHasBeenSet;
  };

} // namespace Model
} // namespace MediaLive
} // namespace Aws

{'repo_name': 'aws/aws-sdk-cpp', 'stars': '1060', 'repo_language': 'C++', 'file_name': 'RunTests.cpp', 'mime_type': 'text/x-c', 'hash': 2025498942744032497, 'source_dataset': 'data'}