text:
namespace clblast {
constexpr auto kArgKwg = "KWG";

constexpr auto kArgKwi = "KWI";

constexpr auto kArgMdima = "MDIMA";

constexpr auto kArgMdimc = "MDIMC";

constexpr auto kArgMwg = "MWG";

constexpr auto kArgNdimb = "NDIMB";

constexpr auto kArgNdimc = "NDIMC";

constexpr auto kArgNwg = "NWG";

constexpr auto kArgSa = "SA";

constexpr auto kArgSb = "SB";

constexpr auto kArgStrm = "STRM";

constexpr auto kArgStrn = "STRN";

constexpr auto kArgVwm = "VWM";

constexpr auto kArgVwn = "VWN";

constexpr auto KERNEL_NAME = "kernel_name";

// =================================================================================================

template <typename T>
size_t RunOverrideTestsDvdt(int argc, char *argv[], const bool silent, const std::string &routine_name) {
  auto arguments = RetrieveCommandLineArguments(argc, argv);

  auto errors = size_t{0};
  auto passed = size_t{0};
  auto example_routine = TestDvdt<T>();
  constexpr auto kSeed = 42; // fixed seed for reproducibility

  // Determines the test settings
  const auto kernel_name = std::string{"Xgemm"};
  const auto precision = PrecisionValue<T>();

  // Retrieves the arguments
  auto help = std::string{"Options given/available:\n"};
  const auto platform_id = GetArgument(arguments, help, kArgPlatform, ConvertArgument(std::getenv("CLBLAST_PLATFORM"), size_t{0}));
  const auto device_id = GetArgument(arguments, help, kArgDevice, ConvertArgument(std::getenv("CLBLAST_DEVICE"), size_t{0}));
  auto args = Arguments<T>{};
  args.m = GetArgument(arguments, help, kArgM, size_t{256});
  args.n = GetArgument(arguments, help, kArgN, size_t{256});
  args.k = GetArgument(arguments, help, kArgK, size_t{256});
  args.a_ld = GetArgument(arguments, help, kArgALeadDim, args.k);
  args.b_ld = GetArgument(arguments, help, kArgBLeadDim, args.n);
  args.c_ld = GetArgument(arguments, help, kArgCLeadDim, args.n);
  args.a_offset = GetArgument(arguments, help, kArgAOffset, size_t{0});
  args.b_offset = GetArgument(arguments, help, kArgBOffset, size_t{0});
  args.c_offset = GetArgument(arguments, help, kArgCOffset, size_t{0});
  args.layout = GetArgument(arguments, help, kArgLayout, Layout::kRowMajor);
  args.a_transpose = GetArgument(arguments, help, kArgATransp, Transpose::kNo);
  args.b_transpose = GetArgument(arguments, help, kArgBTransp, Transpose::kNo);
  args.alpha = GetArgument(arguments, help, kArgAlpha, GetScalar<T>());
  args.beta  = GetArgument(arguments, help, kArgBeta, GetScalar<T>());

  auto kwg = GetArgument(arguments, help, kArgKwg, size_t{32});
  auto kwi = GetArgument(arguments, help, kArgKwi, size_t{2});
  auto mdima = GetArgument(arguments, help, kArgMdima, size_t{8});
  auto mdimc = GetArgument(arguments, help, kArgMdimc, size_t{8});
  auto mwg = GetArgument(arguments, help, kArgMwg, size_t{64});
  auto ndimb = GetArgument(arguments, help, kArgNdimb, size_t{16});
  auto ndimc = GetArgument(arguments, help, kArgNdimc, size_t{16});
  auto nwg = GetArgument(arguments, help, kArgNwg, size_t{64});
  auto sa = GetArgument(arguments, help, kArgSa, size_t{1});
  auto sb = GetArgument(arguments, help, kArgSb, size_t{1});
  auto strm = GetArgument(arguments, help, kArgStrm, size_t{0});
  auto strn = GetArgument(arguments, help, kArgStrn, size_t{0});
  auto vwm = GetArgument(arguments, help, kArgVwm, size_t{4});
  auto vwn = GetArgument(arguments, help, kArgVwn, size_t{4});
  auto num_runs = GetArgument(arguments, help, kArgNumRuns, size_t{5});
  std::string k_name = GetStringArgument(arguments,help, KERNEL_NAME, "Xgemm");

  const auto cmdline_settings = std::unordered_map<std::string,size_t>{
   {kArgKwg, kwg}, {kArgKwi, kwi}, {kArgMdima, mdima}, {kArgMdimc, mdimc},
   {kArgMwg, mwg}, {kArgNdimb, ndimb}, {kArgNdimc, ndimc}, {kArgNwg, nwg},
   {kArgSa, sa}, {kArgSb, sb}, {kArgStrm, strm}, {kArgStrn, strn}, {kArgVwm, vwm},
   {kArgVwn,vwn}
 };
  // Prints the help message (command-line arguments)
  if (!silent) { fprintf(stdout, "\n* %s\n", help.c_str()); }

  // Initializes OpenCL
  const auto platform = Platform(platform_id);
  const auto device = Device(platform, device_id);
  const auto context = Context(device);
  auto queue = Queue(context, device);

  // Populate host matrices with some example data
  auto host_a = std::vector<T>(args.m * args.k);
  auto host_b = std::vector<T>(args.n * args.k);
  auto host_c = std::vector<T>(args.m * args.n);
  std::mt19937 mt(kSeed);
  std::uniform_real_distribution<double> dist(kTestDataLowerLimit, kTestDataUpperLimit);
  PopulateVector(host_a, mt, dist);
  PopulateVector(host_b, mt, dist);
  PopulateVector(host_c, mt, dist);

  // Copy the matrices to the device
  auto device_a = Buffer<T>(context, host_a.size());
  auto device_b = Buffer<T>(context, host_b.size());
  auto device_c = Buffer<T>(context, host_c.size());
  device_a.Write(queue, host_a.size(), host_a);
  device_b.Write(queue, host_b.size(), host_b);
  device_c.Write(queue, host_c.size(), host_c);
  auto dummy = Buffer<T>(context, 1);
  auto buffers = Buffers<T>{dummy, dummy, device_a, device_b, device_c, dummy, dummy};

  // Loops over the valid combinations: run before and run afterwards
  fprintf(stdout, "* Testing OverrideParameters for '%s'\n", routine_name.c_str());
  // for (const auto &override_setting : cmdline_settings) {
  const auto status_before = example_routine.RunRoutine(args, buffers, queue);
  if (status_before != StatusCode::kSuccess) { errors++; }

    // Overrides the parameters
  const auto status = OverrideParameters(device(), kernel_name, precision, cmdline_settings);
  if (status != StatusCode::kSuccess) { errors++; fprintf(stderr, "ERROR : %d - %zu\n",status,errors ); } // error shouldn't occur

  const auto status_after = example_routine.RunRoutine(args, buffers, queue);
  if (status_after != StatusCode::kSuccess) { errors++; fprintf(stderr, "%zu\n",errors ); }
  passed++;

  if(!errors)
  {
    auto elapsed_time = std::numeric_limits<float>::max();

    for (auto i = 0; i < num_runs; i++) {
      const auto start_time = std::chrono::steady_clock::now();

      const auto status_after = example_routine.RunRoutine(args, buffers, queue);
       queue.Finish();
      auto cpu_timer = std::chrono::steady_clock::now() - start_time;

      if (status_after != StatusCode::kSuccess) { errors++;}
     const auto cpu_timing = std::chrono::duration<float,std::milli>(cpu_timer).count();
        elapsed_time = std::min(elapsed_time, cpu_timing);

    }
    fprintf(stderr, "Elapsed_time : %.1lf(ms)\n", elapsed_time );
    long long int flops = (long long int) args.m * (long long int) args.n * (long long int) args.k * 2;
    auto gflops = (elapsed_time != 0.0) ? (flops*1e-6)/elapsed_time : 0;
    fprintf(stderr, "GFLOPS : %9.1lf\n",gflops);

    //Print Json
    std::stringstream tmp_filename;
    tmp_filename << "clblast_xgemm_override.json";
    std::string filename = tmp_filename.str();
    FILE * f = fopen(filename.c_str(),"w");
    fprintf(f, "{\n" );
    fprintf(f, "  \"m\" : %u,\n", args.m);
    fprintf(f, "  \"n\" : %u,\n", args.n);
    fprintf(f, "  \"k\" : %u,\n", args.k);
    fprintf(f, "  \"GFLOPS\" : %lf,\n", gflops);
    fprintf(f, "  \"Time(ms)\" : %.4lf,\n", elapsed_time);
    fprintf(f, "  \"kernel_family\" : \"%s\",\n", k_name.c_str());
    fprintf(f, "  \"device\": \"%s\",\n", device.Name().c_str());
    fprintf(f, "  \"device_vendor\": \"%s\",\n", device.Vendor().c_str());
    fprintf(f, "  \"device_type\": \"%s\",\n", device.Type().c_str());
    fprintf(f, "  \"device_core_clock\": \"%zu\",\n", device.CoreClock());
    fprintf(f, "  \"device_compute_units\": \"%zu\"\n", device.ComputeUnits());
    fprintf(f, "}" );

    fclose(f);

  }

  return errors;
}

// =================================================================================================
} // namespace clblast

// Main function (not within the clblast namespace)
int main(int argc, char *argv[]) {
  auto errors = size_t{0};
  errors += clblast::RunOverrideTestsDvdt<float>(argc, argv, false, "SGEMM");
  if (errors > 0) { return 1; } else { return 0; }
}

// =================================================================================================


text:
@interface ServiceCoreDataManager () <ServiceDataSource>

@property (nonatomic, strong) CoreDataStore *dataStore;

@end

@implementation ServiceCoreDataManager

static NSUInteger const kBatchSize = 20;

#pragma mark - Properties

@synthesize dataStore = _dataStore;

- (void)setDataStore:(CoreDataStore *)dataStore {
    if (_dataStore != dataStore) {
        _dataStore = dataStore;
        [_dataStore setupWithCompletion:^(BOOL succeeded, NSError *error) {
            [self didCompleteCoreDataSetup:succeeded withError:error];
        }];
    }
}

#pragma mark - ServiceDataSource

- (id <Service>)objectAtIndexPath:(NSIndexPath *)indexPath {
    return [self.dataSourceDelegate objectAtIndexPath:indexPath];
}

#pragma mark - Private

- (NSFetchedResultsController *)fetchedResultsControllerWithManagedObjectContext:(NSManagedObjectContext *)managedObjectContext {
    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:NSStringFromClass([Service class])];
    request.predicate = nil;
    request.fetchBatchSize = kBatchSize;
    request.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"name"
                                                              ascending:YES
                                                               selector:@selector(localizedStandardCompare:)]];

    NSFetchedResultsController *frc = [[NSFetchedResultsController alloc] initWithFetchRequest:request
                                                                          managedObjectContext:managedObjectContext
                                                                            sectionNameKeyPath:nil
                                                                                cacheName:nil];
    return frc;
}

#pragma mark - Callback handlers

- (void)didCompleteCoreDataSetup:(BOOL)succeeded withError:(NSError *)error {
    if (succeeded) {
        NSFetchedResultsController *frc = [self fetchedResultsControllerWithManagedObjectContext:self.dataStore.mainQueueManagedObjectContext];
        [self.dataSourceDelegate updateFetchedResultsController:frc withCompletion:^(BOOL innerSucceeded, NSError *innerError) {
            [self didUpdateFetchedResultsController:innerSucceeded withError:innerError];
        }];
    } else {
        NSLog(@"Core Data Store setup failed: %@", error);
    }
}
- (void)didUpdateFetchedResultsController:(BOOL)succeeded withError:(NSError *)error {
    if (succeeded) {
        [self.dataFetcher fetchDataWithCompletion:^(id _Nullable collection, NSError * _Nullable innerError) {
            [self didFetchData:collection withError:innerError];
        }];
    } else {
        NSLog(@"Setup Fetched Result Controller failed: %@", error);
    }
}
- (void)didFetchData:(id _Nullable)collection withError:(NSError *)error {
    if (collection && !error) {

    } else if (error) {
        NSLog(@"Fetching services failed: %@", error);
    } else {
        NSLog(@"Fetching services failed, with unknown error");
    }
}

@end

redpajama_set_name: RedPajamaGithub


text:
package br.jus.jfms.jef.imp;

import br.jus.jfms.jef.PojoCredentialReader;

public class CustomerAuthenticator extends OtrsAutenticator {
	public CustomerAuthenticator(String login, String password) {
		super(
			new CustomerBrowser(),
			new PojoCredentialReader(login, password)
		);
	}
}


text:
package org.apache.geode.pdx;

/**
 * Marker interface for an object that GemFire creates and returns from
 * {@link PdxReader#readUnreadFields() readUnreadFields}. If you call readUnreadFields then you must
 * also call {@link PdxWriter#writeUnreadFields(PdxUnreadFields) writeUnreadFields} when that object
 * is reserialized. If you do not call {@link PdxWriter#writeUnreadFields(PdxUnreadFields)
 * writeUnreadFields} but you did call {@link PdxReader#readUnreadFields() readUnreadFields} the
 * unread fields will not be written.
 * <p>
 * Unread fields are those that are not explicitly read with a {@link PdxReader} readXXX method.
 * This should only happen when a domain class has changed by adding or removing one or more fields.
 * Unread fields will be preserved automatically (unless you turn this feature off using
 * {@link org.apache.geode.cache.CacheFactory#setPdxIgnoreUnreadFields(boolean)
 * setPdxIgnoreUnreadFields} or
 * {@link org.apache.geode.cache.client.ClientCacheFactory#setPdxIgnoreUnreadFields(boolean) client
 * setPdxIgnoreUnreadFields}) but to reduce the performance and memory overhead of automatic
 * preservation it is recommended that use {@link PdxReader#readUnreadFields() readUnreadFields} if
 * possible.
 *
 * @since GemFire 6.6
 *
 */
public interface PdxUnreadFields {
}


text:
using Mastoom.Shared.ViewModels;
using Xamarin.Forms;

namespace Mastoom.Views
{
    public partial class MainPage : ContentPage
    {
        public MainPage()
        {
            InitializeComponent();
        }
    }
}


text:
static void PrintUsage() {
  printf("run_testserver --doc-root=relpath [--http|--https|--ftp|--sync]\n");
  printf("(NOTE: relpath should be relative to the 'src' directory)\n");
}

int main(int argc, const char* argv[]) {
  base::AtExitManager at_exit_manager;
  MessageLoopForIO message_loop;

  // Process command line
  CommandLine::Init(argc, argv);
  CommandLine* command_line = CommandLine::ForCurrentProcess();

  if (!logging::InitLogging(
          FILE_PATH_LITERAL("testserver.log"),
          logging::LOG_TO_BOTH_FILE_AND_SYSTEM_DEBUG_LOG,
          logging::LOCK_LOG_FILE,
          logging::APPEND_TO_OLD_LOG_FILE,
          logging::DISABLE_DCHECK_FOR_NON_OFFICIAL_RELEASE_BUILDS)) {
    printf("Error: could not initialize logging. Exiting.\n");
    return -1;
  }

  if (command_line->GetSwitchCount() == 0 ||
      command_line->HasSwitch("help")) {
    PrintUsage();
    return -1;
  }

  net::TestServer::Type server_type(net::TestServer::TYPE_HTTP);
  if (command_line->HasSwitch("https")) {
    server_type = net::TestServer::TYPE_HTTPS;
  } else if (command_line->HasSwitch("ftp")) {
    server_type = net::TestServer::TYPE_FTP;
  } else if (command_line->HasSwitch("sync")) {
    server_type = net::TestServer::TYPE_SYNC;
  }

  FilePath doc_root = command_line->GetSwitchValuePath("doc-root");
  if ((server_type != net::TestServer::TYPE_SYNC) && doc_root.empty()) {
    printf("Error: --doc-root must be specified\n");
    PrintUsage();
    return -1;
  }

  net::TestServer test_server(server_type, doc_root);
  if (!test_server.Start()) {
    printf("Error: failed to start test server. Exiting.\n");
    return -1;
  }

  if (!file_util::DirectoryExists(test_server.document_root())) {
    printf("Error: invalid doc root: \"%s\" does not exist!\n",
        UTF16ToUTF8(test_server.document_root().LossyDisplayName()).c_str());
    return -1;
  }

  printf("testserver running at %s (type ctrl+c to exit)\n",
         test_server.host_port_pair().ToString().c_str());

  message_loop.Run();
  return 0;
}


text:
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//-----------------------------------------------------------------------
// </copyright>
// <summary>Tests for the weak dictionary class</summary>
//-----------------------------------------------------------------------

using System.Collections.Generic;
using Microsoft.Build.Collections;
using System;
using Microsoft.Build.Evaluation;
using Microsoft.Build.UnitTests;
using System.Collections;
using Microsoft.Build.Execution;
using Microsoft.Build.Shared;
using Microsoft.Build.Construction;
using Xunit;

namespace Microsoft.Build.UnitTests.OM.Collections
{
    /// <summary>
    /// Tests for the weak dictionary class
    /// </summary>
    public class WeakDictionary_Tests
    {
        /// <summary>
        /// Find with the same key inserted using the indexer
        /// </summary>
        [Fact]
        public void Indexer_ReferenceFound()
        {
            object k1 = new Object();
            object v1 = new Object();

            var dictionary = new WeakDictionary<object, object>();
            dictionary[k1] = v1;

            // Now look for the same key we inserted
            object v2 = dictionary[k1];

            Assert.Equal(true, Object.ReferenceEquals(v1, v2));
            Assert.Equal(true, dictionary.Contains(k1));
        }

        /// <summary>
        /// Find something not present with the indexer
        /// </summary>
        [Fact]
        public void Indexer_NotFound()
        {
            Assert.Throws<KeyNotFoundException>(() =>
            {
                var dictionary = new WeakDictionary<object, object>();
                object value = dictionary[new Object()];
            }
           );
        }
        /// <summary>
        /// Find with the same key inserted using TryGetValue
        /// </summary>
        [Fact]
        public void TryGetValue_ReferenceFound()
        {
            object k1 = new Object();
            object v1 = new Object();

            var dictionary = new WeakDictionary<object, object>();
            dictionary[k1] = v1;

            // Now look for the same key we inserted
            object v2;
            bool result = dictionary.TryGetValue(k1, out v2);

            Assert.Equal(true, result);
            Assert.Equal(true, Object.ReferenceEquals(v1, v2));
        }

        /// <summary>
        /// Find something not present with TryGetValue
        /// </summary>
        [Fact]
        public void TryGetValue_ReferenceNotFound()
        {
            var dictionary = new WeakDictionary<object, object>();

            object v;
            bool result = dictionary.TryGetValue(new Object(), out v);

            Assert.Equal(false, result);
            Assert.Equal(null, v);
            Assert.Equal(false, dictionary.Contains(new Object()));
        }

        /// <summary>
        /// Find a key that wasn't inserted but is equal
        /// </summary>
        [Fact]
        public void EqualityComparer()
        {
            string k1 = String.Concat("ke", "y");
            object v1 = new Object();

            var dictionary = new WeakDictionary<string, object>();
            dictionary[k1] = v1;

            // Now look for a different but equatable key
            // Don't create it with a literal or the compiler will intern it!
            string k2 = String.Concat("k", "ey");

            Assert.Equal(false, Object.ReferenceEquals(k1, k2));

            object v2 = dictionary[k2];

            Assert.Equal(true, Object.ReferenceEquals(v1, v2));
        }

        /// <summary>
        /// If value target has been collected, key should not be present.
        /// (When accessed, if target is null, entry is removed instead of returned.)
        /// </summary>
        [Fact]
        public void IndexerRemovesDeadValue()
        {

            object k = new Object();
            object v = new Object();

            var dictionary = new WeakDictionary<object, object>();
            dictionary[k] = v;

            v = null;
            GC.Collect();

            Assert.Throws<KeyNotFoundException>(() =>
            {
                object value = dictionary[k];
            }
           );
        }

        /// <summary>
        /// If value target has been collected, key should not be present.
        /// (When accessed, if target is null, entry is removed instead of returned.)
        /// </summary>
        [Fact]
        public void ContainsRemovesDeadValue()
        {
            Console.WriteLine("Fixed contains test ..");

            Object k = new Object();
            object v = new Object();

            var dictionary = new WeakDictionary<object, object>();
            dictionary[k] = v;

            // Do not put an assert here! It will cause the test to mysteriously fail
            // as somehow an NUnit Assert can hold onto the value!
            v = null;
            GC.Collect();

            Assert.Equal(false, dictionary.Contains(k));
        }

        /// <summary>
        /// If value target has been collected, key should not be present.
        /// (When accessed, if target is null, entry is removed instead of returned.)
        /// </summary>
        [Fact]
        public void TryGetRemovesDeadValue()
        {
            object k = new Object();
            object v = new Object();

            var dictionary = new WeakDictionary<object, object>();
            dictionary[k] = v;

            // Do not put an assert here! It will cause the test to mysteriously fail
            // as somehow an NUnit Assert can hold onto the value!
            v = null;
            GC.Collect();

            object value;
            Assert.Equal(false, dictionary.TryGetValue(k, out value));
            Assert.Equal(0, dictionary.Count);
        }

        /// <summary>
        /// Verify dictionary doesn't hold onto keys
        /// </summary>
        [Fact]
        public void KeysCollectable()
        {
            string k1 = new string('k', 1000000);
            string v1 = new string('v', 1000000);

            // Each character is 2 bytes, so about 4MB of this should be the strings
            long memory1 = GC.GetTotalMemory(true);

            var dictionary = new WeakDictionary<string, string>();
            dictionary[k1] = v1;

            k1 = null;

            long memory2 = GC.GetTotalMemory(true);

            // Key collected, sould be about 2MB less
            long difference = memory1 - memory2;

            Console.WriteLine("Start {0}, end {1}, diff {2}", memory1, memory2, difference);
            Assert.Equal(true, difference > 1500000); // 2MB minus big noise allowance

            // This line is VERY important, as it keeps the GC from being too smart and collecting
            // the dictionary and its large strings because we never use them again.
            GC.KeepAlive(dictionary);
        }

        /// <summary>
        /// Verify dictionary doesn't hold onto values
        /// </summary>
        [Fact]
        public void ValuesCollectable()
        {
            string k1 = new string('k', 1000000);
            string v1 = new string('v', 1000000);

            // Each character is 2 bytes, so about 4MB of this should be the strings
            long memory1 = GC.GetTotalMemory(true);

            var dictionary = new WeakDictionary<string, string>();
            dictionary[k1] = v1;

            v1 = null;

            long memory2 = GC.GetTotalMemory(true);

            // Value collected, sould be about 2MB less
            long difference = memory1 - memory2;

            Console.WriteLine("Start {0}, end {1}, diff {2}", memory1, memory2, difference);
            Assert.Equal(true, difference > 1500000); // 2MB minus big noise allowance

            // This line is VERY important, as it keeps the GC from being too smart and collecting
            // the dictionary and its large strings because we never use them again.
            GC.KeepAlive(dictionary);
        }

        /// <summary>
        /// Call Scavenge explicitly
        /// </summary>
        [Fact]
        public void ExplicitScavenge()
        {
            object k1 = new Object();
            object v1 = new Object();

            var dictionary = new WeakDictionary<object, object>();
            dictionary[k1] = v1;

            Assert.Equal(1, dictionary.Count);

            k1 = null;
            GC.Collect();

            dictionary.Scavenge();

            Assert.Equal(0, dictionary.Count);
        }

        /// <summary>
        /// Growing should invoke Scavenge
        /// </summary>
        [Fact]
        public void ScavengeOnGrow()
        {
            var dictionary = new WeakDictionary<object, object>();

            for (int i = 0; i < 100; i++)
            {
                dictionary[new Object()] = new Object();

                // Randomly collect some
                if (i == 15)
                {
                    GC.Collect();
                }
            }

            // We should have scavenged at least once
            Console.WriteLine("Count {0}", dictionary.Count);
            Assert.Equal(true, dictionary.Count < 100);

            // Finish with explicit scavenge
            int count1 = dictionary.Count;
            int removed = dictionary.Scavenge();
            int count2 = dictionary.Count;

            Console.WriteLine("Removed {0}", removed);
            Assert.Equal(removed, count1 - count2);
        }
    }
}


text:
package org.elasticsearch.percolator;

import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.ShardOperationFailedException;
import org.elasticsearch.action.percolate.MultiPercolateRequestBuilder;
import org.elasticsearch.action.percolate.MultiPercolateResponse;
import org.elasticsearch.action.percolate.PercolateSourceBuilder;
import org.elasticsearch.client.Requests;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.index.query.Operator;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.test.ESIntegTestCase;

import java.io.IOException;

import static org.elasticsearch.action.percolate.PercolateSourceBuilder.docBuilder;
import static org.elasticsearch.common.settings.Settings.settingsBuilder;
import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;
import static org.elasticsearch.common.xcontent.XContentFactory.smileBuilder;
import static org.elasticsearch.common.xcontent.XContentFactory.yamlBuilder;
import static org.elasticsearch.index.query.QueryBuilders.boolQuery;
import static org.elasticsearch.index.query.QueryBuilders.matchAllQuery;
import static org.elasticsearch.index.query.QueryBuilders.matchQuery;
import static org.elasticsearch.index.query.QueryBuilders.rangeQuery;
import static org.elasticsearch.percolator.PercolatorTestUtil.convertFromTextArray;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertMatchCount;
import static org.hamcrest.Matchers.arrayContaining;
import static org.hamcrest.Matchers.arrayContainingInAnyOrder;
import static org.hamcrest.Matchers.arrayWithSize;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;

/**
 */
public class MultiPercolatorIT extends ESIntegTestCase {
    public void testBasics() throws Exception {
        assertAcked(prepareCreate("test").addMapping("type", "field1", "type=string"));
        ensureGreen();

        logger.info("--> register a queries");
        client().prepareIndex("test", PercolatorService.TYPE_NAME, "1")
                .setSource(jsonBuilder().startObject().field("query", matchQuery("field1", "b")).field("a", "b").endObject())
                .execute().actionGet();
        client().prepareIndex("test", PercolatorService.TYPE_NAME, "2")
                .setSource(jsonBuilder().startObject().field("query", matchQuery("field1", "c")).endObject())
                .execute().actionGet();
        client().prepareIndex("test", PercolatorService.TYPE_NAME, "3")
                .setSource(jsonBuilder().startObject().field("query", boolQuery()
                        .must(matchQuery("field1", "b"))
                        .must(matchQuery("field1", "c"))
                ).endObject())
                .execute().actionGet();
        client().prepareIndex("test", PercolatorService.TYPE_NAME, "4")
                .setSource(jsonBuilder().startObject().field("query", matchAllQuery()).endObject())
                .execute().actionGet();
        refresh();

        MultiPercolateResponse response = client().prepareMultiPercolate()
                .add(client().preparePercolate()
                        .setIndices("test").setDocumentType("type")
                        .setPercolateDoc(docBuilder().setDoc(jsonBuilder().startObject().field("field1", "b").endObject())))
                .add(client().preparePercolate()
                        .setIndices("test").setDocumentType("type")
                        .setPercolateDoc(docBuilder().setDoc(yamlBuilder().startObject().field("field1", "c").endObject())))
                .add(client().preparePercolate()
                        .setIndices("test").setDocumentType("type")
                        .setPercolateDoc(docBuilder().setDoc(smileBuilder().startObject().field("field1", "b c").endObject())))
                .add(client().preparePercolate()
                        .setIndices("test").setDocumentType("type")
                        .setPercolateDoc(docBuilder().setDoc(jsonBuilder().startObject().field("field1", "d").endObject())))
                .add(client().preparePercolate() // non existing doc, so error element
                        .setIndices("test").setDocumentType("type")
                        .setGetRequest(Requests.getRequest("test").type("type").id("5")))
                .execute().actionGet();

        MultiPercolateResponse.Item item = response.getItems()[0];
        assertMatchCount(item.getResponse(), 2l);
        assertThat(item.getResponse().getMatches(), arrayWithSize(2));
        assertThat(item.getErrorMessage(), nullValue());
        assertThat(convertFromTextArray(item.getResponse().getMatches(), "test"), arrayContainingInAnyOrder("1", "4"));

        item = response.getItems()[1];
        assertThat(item.getErrorMessage(), nullValue());

        assertMatchCount(item.getResponse(), 2l);
        assertThat(item.getResponse().getMatches(), arrayWithSize(2));
        assertThat(convertFromTextArray(item.getResponse().getMatches(), "test"), arrayContainingInAnyOrder("2", "4"));

        item = response.getItems()[2];
        assertThat(item.getErrorMessage(), nullValue());
        assertMatchCount(item.getResponse(), 4l);
        assertThat(convertFromTextArray(item.getResponse().getMatches(), "test"), arrayContainingInAnyOrder("1", "2", "3", "4"));

        item = response.getItems()[3];
        assertThat(item.getErrorMessage(), nullValue());
        assertMatchCount(item.getResponse(), 1l);
        assertThat(item.getResponse().getMatches(), arrayWithSize(1));
        assertThat(convertFromTextArray(item.getResponse().getMatches(), "test"), arrayContaining("4"));

        item = response.getItems()[4];
        assertThat(item.getResponse(), nullValue());
        assertThat(item.getErrorMessage(), notNullValue());
        assertThat(item.getErrorMessage(), containsString("document missing"));
    }

    public void testWithRouting() throws Exception {
        assertAcked(prepareCreate("test").addMapping("type", "field1", "type=string"));
        ensureGreen();

        logger.info("--> register a queries");
        client().prepareIndex("test", PercolatorService.TYPE_NAME, "1")
                .setRouting("a")
                .setSource(jsonBuilder().startObject().field("query", matchQuery("field1", "b")).field("a", "b").endObject())
                .execute().actionGet();
        client().prepareIndex("test", PercolatorService.TYPE_NAME, "2")
                .setRouting("a")
                .setSource(jsonBuilder().startObject().field("query", matchQuery("field1", "c")).endObject())
                .execute().actionGet();
        client().prepareIndex("test", PercolatorService.TYPE_NAME, "3")
                .setRouting("a")
                .setSource(jsonBuilder().startObject().field("query", boolQuery()
                                .must(matchQuery("field1", "b"))
                                .must(matchQuery("field1", "c"))
                ).endObject())
                .execute().actionGet();
        client().prepareIndex("test", PercolatorService.TYPE_NAME, "4")
                .setRouting("a")
                .setSource(jsonBuilder().startObject().field("query", matchAllQuery()).endObject())
                .execute().actionGet();
        refresh();

        MultiPercolateResponse response = client().prepareMultiPercolate()
                .add(client().preparePercolate()
                        .setIndices("test").setDocumentType("type")
                        .setRouting("a")
                        .setPercolateDoc(docBuilder().setDoc(jsonBuilder().startObject().field("field1", "b").endObject())))
                .add(client().preparePercolate()
                        .setIndices("test").setDocumentType("type")
                        .setRouting("a")
                        .setPercolateDoc(docBuilder().setDoc(yamlBuilder().startObject().field("field1", "c").endObject())))
                .add(client().preparePercolate()
                        .setIndices("test").setDocumentType("type")
                        .setRouting("a")
                        .setPercolateDoc(docBuilder().setDoc(smileBuilder().startObject().field("field1", "b c").endObject())))
                .add(client().preparePercolate()
                        .setIndices("test").setDocumentType("type")
                        .setRouting("a")
                        .setPercolateDoc(docBuilder().setDoc(jsonBuilder().startObject().field("field1", "d").endObject())))
                .add(client().preparePercolate() // non existing doc, so error element
                        .setIndices("test").setDocumentType("type")
                        .setRouting("a")
                        .setGetRequest(Requests.getRequest("test").type("type").id("5")))
                .execute().actionGet();

        MultiPercolateResponse.Item item = response.getItems()[0];
        assertMatchCount(item.getResponse(), 2l);
        assertThat(item.getResponse().getMatches(), arrayWithSize(2));
        assertThat(item.getErrorMessage(), nullValue());
        assertThat(convertFromTextArray(item.getResponse().getMatches(), "test"), arrayContainingInAnyOrder("1", "4"));

        item = response.getItems()[1];
        assertThat(item.getErrorMessage(), nullValue());

        assertMatchCount(item.getResponse(), 2l);
        assertThat(item.getResponse().getMatches(), arrayWithSize(2));
        assertThat(convertFromTextArray(item.getResponse().getMatches(), "test"), arrayContainingInAnyOrder("2", "4"));

        item = response.getItems()[2];
        assertThat(item.getErrorMessage(), nullValue());
        assertMatchCount(item.getResponse(), 4l);
        assertThat(convertFromTextArray(item.getResponse().getMatches(), "test"), arrayContainingInAnyOrder("1", "2", "3", "4"));

        item = response.getItems()[3];
        assertThat(item.getErrorMessage(), nullValue());
        assertMatchCount(item.getResponse(), 1l);
        assertThat(item.getResponse().getMatches(), arrayWithSize(1));
        assertThat(convertFromTextArray(item.getResponse().getMatches(), "test"), arrayContaining("4"));

        item = response.getItems()[4];
        assertThat(item.getResponse(), nullValue());
        assertThat(item.getErrorMessage(), notNullValue());
        assertThat(item.getErrorMessage(), containsString("document missing"));
    }

    public void testExistingDocsOnly() throws Exception {
        createIndex("test");

        int numQueries = randomIntBetween(50, 100);
        logger.info("--> register a queries");
        for (int i = 0; i < numQueries; i++) {
            client().prepareIndex("test", PercolatorService.TYPE_NAME, Integer.toString(i))
                    .setSource(jsonBuilder().startObject().field("query", matchAllQuery()).endObject())
                    .execute().actionGet();
        }

        client().prepareIndex("test", "type", "1")
                .setSource(jsonBuilder().startObject().field("field", "a"))
                .execute().actionGet();
        refresh();

        MultiPercolateRequestBuilder builder = client().prepareMultiPercolate();
        int numPercolateRequest = randomIntBetween(50, 100);
        for (int i = 0; i < numPercolateRequest; i++) {
            builder.add(
                    client().preparePercolate()
                            .setGetRequest(Requests.getRequest("test").type("type").id("1"))
                            .setIndices("test").setDocumentType("type")
                            .setSize(numQueries)
            );
        }

        MultiPercolateResponse response = builder.execute().actionGet();
        assertThat(response.items().length, equalTo(numPercolateRequest));
        for (MultiPercolateResponse.Item item : response) {
            assertThat(item.isFailure(), equalTo(false));
            assertMatchCount(item.getResponse(), numQueries);
            assertThat(item.getResponse().getMatches().length, equalTo(numQueries));
        }

        // Non existing doc
        builder = client().prepareMultiPercolate();
        for (int i = 0; i < numPercolateRequest; i++) {
            builder.add(
                    client().preparePercolate()
                            .setGetRequest(Requests.getRequest("test").type("type").id("2"))
                            .setIndices("test").setDocumentType("type").setSize(numQueries)
            );
        }

        response = builder.execute().actionGet();
        assertThat(response.items().length, equalTo(numPercolateRequest));
        for (MultiPercolateResponse.Item item : response) {
            assertThat(item.isFailure(), equalTo(true));
            assertThat(item.getErrorMessage(), containsString("document missing"));
            assertThat(item.getResponse(), nullValue());
        }

        // One existing doc
        builder = client().prepareMultiPercolate();
        for (int i = 0; i < numPercolateRequest; i++) {
            builder.add(
                    client().preparePercolate()
                            .setGetRequest(Requests.getRequest("test").type("type").id("2"))
                            .setIndices("test").setDocumentType("type").setSize(numQueries)
            );
        }
        builder.add(
                client().preparePercolate()
                        .setGetRequest(Requests.getRequest("test").type("type").id("1"))
                        .setIndices("test").setDocumentType("type").setSize(numQueries)
        );

        response = builder.execute().actionGet();
        assertThat(response.items().length, equalTo(numPercolateRequest + 1));
        assertThat(response.items()[numPercolateRequest].isFailure(), equalTo(false));
        assertMatchCount(response.items()[numPercolateRequest].getResponse(), numQueries);
        assertThat(response.items()[numPercolateRequest].getResponse().getMatches().length, equalTo(numQueries));
    }

    public void testWithDocsOnly() throws Exception {
        createIndex("test");
        ensureGreen();

        NumShards test = getNumShards("test");

        int numQueries = randomIntBetween(50, 100);
        logger.info("--> register a queries");
        for (int i = 0; i < numQueries; i++) {
            client().prepareIndex("test", PercolatorService.TYPE_NAME, Integer.toString(i))
                    .setSource(jsonBuilder().startObject().field("query", matchAllQuery()).endObject())
                    .execute().actionGet();
        }
        refresh();

        MultiPercolateRequestBuilder builder = client().prepareMultiPercolate();
        int numPercolateRequest = randomIntBetween(50, 100);
        for (int i = 0; i < numPercolateRequest; i++) {
            builder.add(
                    client().preparePercolate()
                            .setIndices("test").setDocumentType("type")
                            .setSize(numQueries)
                            .setPercolateDoc(docBuilder().setDoc(jsonBuilder().startObject().field("field", "a").endObject())));
        }

        MultiPercolateResponse response = builder.execute().actionGet();
        assertThat(response.items().length, equalTo(numPercolateRequest));
        for (MultiPercolateResponse.Item item : response) {
            assertThat(item.isFailure(), equalTo(false));
            assertMatchCount(item.getResponse(), numQueries);
            assertThat(item.getResponse().getMatches().length, equalTo(numQueries));
        }

        // All illegal json
        builder = client().prepareMultiPercolate();
        for (int i = 0; i < numPercolateRequest; i++) {
            builder.add(
                    client().preparePercolate()
                            .setIndices("test").setDocumentType("type")
                            .setSource("illegal json"));
        }

        response = builder.execute().actionGet();
        assertThat(response.items().length, equalTo(numPercolateRequest));
        for (MultiPercolateResponse.Item item : response) {
            assertThat(item.isFailure(), equalTo(false));
            assertThat(item.getResponse().getSuccessfulShards(), equalTo(0));
            assertThat(item.getResponse().getShardFailures().length, equalTo(test.numPrimaries));
            for (ShardOperationFailedException shardFailure : item.getResponse().getShardFailures()) {
                assertThat(shardFailure.reason(), containsString("Failed to derive xcontent"));
                assertThat(shardFailure.status().getStatus(), equalTo(400));
            }
        }

        // one valid request
        builder = client().prepareMultiPercolate();
        for (int i = 0; i < numPercolateRequest; i++) {
            builder.add(
                    client().preparePercolate()
                            .setIndices("test").setDocumentType("type")
                            .setSource("illegal json"));
        }
        builder.add(
                client().preparePercolate()
                        .setSize(numQueries)
                        .setIndices("test").setDocumentType("type")
                        .setPercolateDoc(docBuilder().setDoc(jsonBuilder().startObject().field("field", "a").endObject())));

        response = builder.execute().actionGet();
        assertThat(response.items().length, equalTo(numPercolateRequest + 1));
        assertThat(response.items()[numPercolateRequest].isFailure(), equalTo(false));
        assertMatchCount(response.items()[numPercolateRequest].getResponse(), numQueries);
        assertThat(response.items()[numPercolateRequest].getResponse().getMatches().length, equalTo(numQueries));
    }

    public void testNestedMultiPercolation() throws IOException {
        initNestedIndexAndPercolation();
        MultiPercolateRequestBuilder mpercolate= client().prepareMultiPercolate();
        mpercolate.add(client().preparePercolate().setPercolateDoc(new PercolateSourceBuilder.DocBuilder().setDoc(getNotMatchingNestedDoc())).setIndices("nestedindex").setDocumentType("company"));
        mpercolate.add(client().preparePercolate().setPercolateDoc(new PercolateSourceBuilder.DocBuilder().setDoc(getMatchingNestedDoc())).setIndices("nestedindex").setDocumentType("company"));
        MultiPercolateResponse response = mpercolate.get();
        assertEquals(response.getItems()[0].getResponse().getMatches().length, 0);
        assertEquals(response.getItems()[1].getResponse().getMatches().length, 1);
        assertEquals(response.getItems()[1].getResponse().getMatches()[0].getId().string(), "Q");
    }

    public void testStartTimeIsPropagatedToShardRequests() throws Exception {
        // See: https://github.com/elastic/elasticsearch/issues/15908
        internalCluster().ensureAtLeastNumDataNodes(2);
        client().admin().indices().prepareCreate("test")
            .setSettings(settingsBuilder()
                .put("index.number_of_shards", 1)
                .put("index.number_of_replicas", 1)
            )
            .addMapping("type", "date_field", "type=date,format=strict_date_optional_time||epoch_millis")
            .get();
        ensureGreen();

        client().prepareIndex("test", ".percolator", "1")
            .setSource(jsonBuilder().startObject().field("query", rangeQuery("date_field").lt("now+90d")).endObject())
            .setRefresh(true)
            .get();

        for (int i = 0; i < 32; i++) {
            MultiPercolateResponse response = client().prepareMultiPercolate()
                .add(client().preparePercolate().setDocumentType("type").setIndices("test")
                    .setPercolateDoc(new PercolateSourceBuilder.DocBuilder().setDoc("date_field", "2015-07-21T10:28:01-07:00")))
                .get();
            assertThat(response.getItems()[0].getResponse().getCount(), equalTo(1L));
            assertThat(response.getItems()[0].getResponse().getMatches()[0].getId().string(), equalTo("1"));
        }
    }

    void initNestedIndexAndPercolation() throws IOException {
        XContentBuilder mapping = XContentFactory.jsonBuilder();
        mapping.startObject().startObject("properties").startObject("companyname").field("type", "string").endObject()
                .startObject("employee").field("type", "nested").startObject("properties")
                .startObject("name").field("type", "string").endObject().endObject().endObject().endObject()
                .endObject();

        assertAcked(client().admin().indices().prepareCreate("nestedindex").addMapping("company", mapping));
        ensureGreen("nestedindex");

        client().prepareIndex("nestedindex", PercolatorService.TYPE_NAME, "Q").setSource(jsonBuilder().startObject()
                .field("query", QueryBuilders.nestedQuery("employee", QueryBuilders.matchQuery("employee.name", "virginia potts").operator(Operator.AND)).scoreMode(ScoreMode.Avg)).endObject()).get();

        refresh();

    }

    XContentBuilder getMatchingNestedDoc() throws IOException {
        XContentBuilder doc = XContentFactory.jsonBuilder();
        doc.startObject().field("companyname", "stark").startArray("employee")
                .startObject().field("name", "virginia potts").endObject()
                .startObject().field("name", "tony stark").endObject()
                .endArray().endObject();
        return doc;
    }

    XContentBuilder getNotMatchingNestedDoc() throws IOException {
        XContentBuilder doc = XContentFactory.jsonBuilder();
        doc.startObject().field("companyname", "notstark").startArray("employee")
                .startObject().field("name", "virginia stark").endObject()
                .startObject().field("name", "tony potts").endObject()
                .endArray().endObject();
        return doc;
    }

}


text:
<!DOCTYPE html>
<title>Layout Instability: shift into viewport in inline direction</title>
<link rel="help" href="https://wicg.github.io/layout-instability/" />


text:
incrementally filled with code examples from http://wkinkeldei.blogspot.de/

 * 04_AkkaHelloWorld: Hello world and behavior example (3rd and 4th Dec)
 * 05_AkkaSupervision: supervision example (5th Dec)
 * 06_RequestReply: simple request-reply example (6th Dec)
 * 07_ActorSelection: selection example (7th Dec)
 * 08_GuessMyNumber: simple guess game (8th Dec)
 * 09_GuessMyNumber: expanded guess game (9th Dec)
 * 10_GuessMyNumber: guess game with supervision (10th Dec)
 * 13_WordCount: word count completed (13th Dec.)
 * 15_PiCalculator: various versions for Pi Calulation (15th Dec.)
 * 19_MapReduce: map reduce examples (20th Dec.)
 * 22_Sudoku_Simple: partially working Sudoku solver (22th Dec.)
 * 23_Sudoku_Improved: fully working Sudoku solver (23th Dec.)
 * 24_XMasTree: flushing Xmas Tree (24th Dec.)


text:
<?php

require_once __DIR__ . '/../../vendor/autoload.php';

use PhpExample\Connection\RabbitFactory;

$rabbit = new RabbitFactory($argv);

function handleMsg($channel)
{
  while (count($channel->callbacks)) {
    $channel->wait();
  }
}

echo "Starting consumer.  Make sure a producer is running so I have messages to read!\n";
$channel = false;
while (true) {
  try {
    if ($channel === false) {
      //connect/reconnect to the 'hello' channel
      $connection = $rabbit->getInstance();

      //get the default queue in the 'hello' channel
      $channel = $connection->channel();
      $channel->exchange_declare('hello', 'fanout', false, false, false);
      $queue_name = $channel->queue_declare("", false, false, true, false);
      $queue_name = array_shift($queue_name);
      $channel->queue_bind($queue_name, 'hello');

      //setup callback to handle messages
      $callback = function ($msg) {
        echo " Received Message: $msg->body\n";
      };
      $channel->basic_consume($queue_name, '', false, true, false, false, $callback);
    }
    //listen for messages
    handleMsg($channel);
  } catch (\Exception $e) {
    echo "Connection lost.  Reconnecting...\n";
    echo $e->getMessage() . "\n";
    $channel = false;
    sleep(1);
  }
}
$channel->close();
$connection->close();


text:
extern "C" {

   // SimObject C interface
   const char *SimObject_GetName(SimObject *so)
   {
      return so->getName();
   }

   U32 SimObject_GetId(SimObject *so)
   {
      return so->getId();
   }

   const char *SimObject_GetClassName(SimObject *so)
   {
      return so->getClassName();
   }

   void *SimObject_GetFieldList(SimObject *so, int &outNumFields)
   {
      const AbstractClassRep::FieldList &fl = so->getFieldList();
      outNumFields = fl.size();
      return fl.address();
   }

   bool SimObject_IsLocked(SimObject *so)
   {
      return so->isLocked();
   }

   void SimObject_SetDataField(SimObject *so, const char *fieldName, const char *arr, const char *val)
   {
      so->setDataField(StringTable->insert(fieldName), arr, val);
   }

   const char *SimObject_GetDataField(SimObject *so, const char *fieldName, const char *arr)
   {
      return so->getDataField(StringTable->insert(fieldName), arr);
   }

   void SimObject_InspectPreApply(SimObject *so)
   {
      so->inspectPreApply();
   }

   void SimObject_InspectPostApply(SimObject *so)
   {
      so->inspectPostApply();
   }

   // Con C interface
   void Con_AddConsumer(ConsumerCallback cb)
   {
      Con::addConsumer(cb);
   }

   void Con_RemoveConsumer(ConsumerCallback cb)
   {
      Con::removeConsumer(cb);
   }

   void Con_AddCommand_String(StringCallback cb, const char *nameSpace, const char *funcName, const char* usage,  S32 minArgs, S32 maxArgs)
   {
      if (!nameSpace || !dStrlen(nameSpace))
         Con::addCommand(funcName, cb, usage, minArgs + 1, maxArgs + 1);
      else
         Con::addCommand(nameSpace, funcName, cb, usage, minArgs + 1, maxArgs + 1);
   }

   // ConsoleBaseType C interface
   ConsoleBaseType *ConsoleBaseType_GetTypeById(const S32 typeId)
   {
      return ConsoleBaseType::getType(typeId);
   }

   S32 ConsoleBaseType_GetTypeId(ConsoleBaseType *cbt)
   {
      return cbt->getTypeID();
   }

   S32 ConsoleBaseType_GetTypeSize(ConsoleBaseType *cbt)
   {
      return cbt->getTypeSize();
   }

   const char *ConsoleBaseType_GetTypeName(ConsoleBaseType *cbt)
   {
      return cbt->getTypeName();
   }

   const char *ConsoleBaseType_GetInspectorFieldType(ConsoleBaseType *cbt)
   {
      return cbt->getInspectorFieldType();
   }

   void ConsoleBaseType_SetData(ConsoleBaseType *cbt, void *dptr, S32 argc, const char **argv, const EnumTable *tbl, BitSet32 flag)
   {
      return cbt->setData(dptr, argc, argv, tbl, flag);
   }

   const char *ConsoleBaseType_GetData(ConsoleBaseType *cbt, void *dptr, const EnumTable *tbl, BitSet32 flag)
   {
      return cbt->getData(dptr, tbl, flag);
   }

   // Abstract Class Rep
   AbstractClassRep *AbstractClassRep_GetCommonParent(AbstractClassRep *acr, AbstractClassRep *otheracr)
   {
      return acr->getCommonParent(otheracr);
   }

   AbstractClassRep *AbstractClassRep_FindClassRep(const char* in_pClassName)
   {
      return AbstractClassRep::findClassRep(in_pClassName);
   }

   U32 AbstractClassRep_GetFieldStructSize()
   {
      return sizeof(AbstractClassRep::Field);
   }

   // Sim C interface
   SimObject *Sim_FindObjectByString(const char *param)
   {
      return Sim::findObject(param);
   }

   SimObject *Sim_FindObjectById(S32 param)
   {
      return Sim::findObject(param);
   }

   // Sim Set
   SimObject **SimSet_Begin(SimObject *simObject)
   {
      return dynamic_cast<SimSet *>(simObject)->begin();
   }

   SimObject **SimSet_End(SimObject *simObject)
   {
      return dynamic_cast<SimSet *>(simObject)->end();
   }

};


text:
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.DataKeys;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.roots.CompilerModuleExtension;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.VirtualFileManager;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiJavaFile;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;

import java.io.File;

/**
 * Created by serical on 2017/3/17.
 */
public class ClassesExportAction extends AnAction {

    @Override
    public void actionPerformed(AnActionEvent e) {
        try {
            com.intellij.openapi.actionSystem.DataContext dataContext = e.getDataContext();
            PsiJavaFile javaFile = (PsiJavaFile) ((PsiFile) DataKeys.PSI_FILE.getData(dataContext)).getContainingFile();
            String sourceName = javaFile.getName();
            Module module = (Module) DataKeys.MODULE.getData(dataContext);
            String compileRoot = CompilerModuleExtension.getInstance(module).getCompilerOutputPath().getPath();
            getVirtualFile(sourceName, CompilerModuleExtension.getInstance(module).getCompilerOutputPath().getChildren(), compileRoot);
            VirtualFileManager.getInstance().syncRefresh();
        } catch (Exception ex) {
            ex.printStackTrace();
            Messages.showErrorDialog("Please build your module or project!!!", "error");
        }
    }

    private void getVirtualFile(String sourceName, VirtualFile virtualFile[], String compileRoot)
            throws Exception {
        if (!ArrayUtils.isEmpty(virtualFile)) {
            VirtualFile arr$[] = virtualFile;
            int len$ = arr$.length;
            for (int i$ = 0; i$ < len$; i$++) {
                VirtualFile vf = arr$[i$];
                String srcName;
                if (StringUtils.indexOf(vf.toString(), "$") != -1)
                    srcName = StringUtils.substring(vf.toString(), StringUtils.lastIndexOf(vf.toString(), "/") + 1, StringUtils.indexOf(vf.toString(), "$"));
                else
                    srcName = StringUtils.substring(vf.toString(), StringUtils.lastIndexOf(vf.toString(), "/") + 1, StringUtils.length(vf.toString()) - 6);
                String dstName = StringUtils.substring(sourceName, 0, StringUtils.length(sourceName) - 5);
                if (StringUtils.equals(srcName, dstName)) {
                    String outRoot = (new StringBuilder()).append(StringUtils.substring(compileRoot, 0, StringUtils.lastIndexOf(compileRoot, "/"))).append("/out").toString();
                    String packagePath = StringUtils.substring(vf.getPath(), StringUtils.length(compileRoot), StringUtils.length(vf.getPath()));
                    File s = new File(vf.getPath());
                    File t = new File((new StringBuilder()).append(outRoot).append(packagePath).toString());
                    FileUtil.copy(s, t);
                }
                if (!ArrayUtils.isEmpty(virtualFile))
                    getVirtualFile(sourceName, vf.getChildren(), compileRoot);
            }

        }
    }
}


text:
  A curated list of shell commands and tools specific to OS X.

   "You don't have to know everything. You simply need to know where to find it when necessary." (John Brunner)

 If you want to contribute, you are highly encouraged to do so. Please read the

  contribution guidelines

 .

 For more terminal shell goodness, please also see this list's sister list

  Awesome Command Line Apps

 .

 Table of Contents

   Appearance

     Transparency

     Wallpaper

   Applications

     App Store

     Apple Remote Desktop

     Contacts

     Google

     iTunes

     Mail

     Safari

     Sketch

     Skim

     TextEdit

   Backup

     Time Machine

   Developer

     App Icons

     Vim

     Xcode

   Disks and Volumes

     Disk Images

   Dock

   Documents

   Finder

     Files and Folders

     Layout

     Metadata Files

     Opening Things

   Fonts

   Functions

   Hardware

     Bluetooth

     Hardware Information

     Infrared Receiver

     Power Management

   Input Devices

     Keyboard

   Media

     Audio

     Video

   Networking

     Bonjour

     DHCP

     DNS

     Hostname

     Network Preferences

     Networking Tools

     SSH

     TCP/IP

     Wi-Fi

   Package Managers

   Printing

   Security

     Application Firewall

     Gatekeeper

     Passwords

     Physical Access

     Wiping Data

   Search

     Find

     Locate

   System

     AirDrop

     AppleScript

     Basics

     Clipboard

     Date and Time

     FileVault

     Information/Reports

     Install OS

     Kernel Extensions

     LaunchAgents

     LaunchServices

     Login Window

     Memory Management

     Notification Center

     QuickLook

     Remote Apple Events

     Root User

     Safe Mode Boot

     Screenshots

     Software Installation

     Software Update

     Spotlight

     System Integrity Protection

   Terminal

     Alternative Terminals

     Shells

     Terminal Fonts

 Appearance

 Transparency

 Transparency in Menu and Windows

 ```bash
</p>
<h1>
 Reduce Transparency
</h1>
<p>
 defaults write com.apple.universalaccess reduceTransparency -bool true
</p>
<h1>
 Restore Default Transparency
</h1>
<p>
 defaults write com.apple.universalaccess reduceTransparency -bool false
```

 Wallpaper

 Set Wallpaper

 ```bash
</p>
<h1>
 Up to Mountain Lion
</h1>
<p>
 osascript -e 'tell application "Finder" to set desktop picture to POSIX file "/path/to/picture.jpg"'
</p>
<h1>
 Since Mavericks
</h1>
<p>
 sqlite3 ~/Library/Application\ Support/Dock/desktoppicture.db "update data set value = '/path/to/picture.jpg'" && killall Dock
```

 Applications

 App Store

 List All Apps Downloaded from App Store

  bash
find /Applications -path '*Contents/_MASReceipt/receipt' -maxdepth 4 -print |\sed 's#.app/Contents/_MASReceipt/receipt#.app#g; s#/Applications/##'

 Show Debug Menu

 ```bash
</p>
<h1>
 Enable
</h1>
<p>
 defaults write com.apple.appstore ShowDebugMenu -bool true
</p>
<h1>
 Disable (Default)
</h1>
<p>
 defaults write com.apple.appstore ShowDebugMenu -bool false
```

 Apple Remote Desktop

 Remove Apple Remote Desktop Settings

  bash
sudo rm -rf /var/db/RemoteManagement ; \
sudo defaults delete /Library/Preferences/com.apple.RemoteDesktop.plist ; \
defaults delete ~/Library/Preferences/com.apple.RemoteDesktop.plist ; \
sudo rm -r /Library/Application\ Support/Apple/Remote\ Desktop/ ; \
rm -r ~/Library/Application\ Support/Remote\ Desktop/ ; \
rm -r ~/Library/Containers/com.apple.RemoteDesktop

 Contacts

 Debug Mode

 ```bash
</p>
<h1>
 Enable
</h1>
<p>
 defaults write com.apple.addressbook ABShowDebugMenu -bool true
</p>
<h1>
 Disable (Default)
</h1>
<p>
 defaults write com.apple.addressbook ABShowDebugMenu -bool false
```

 Google

 Uninstall Google Update

  bash
~/Library/Google/GoogleSoftwareUpdate/GoogleSoftwareUpdate.bundle/Contents/Resources/ksinstall --nuke

 iTunes

 Keyboard Media Keys

 ```bash
</p>
<h1>
 Stop Responding to Key Presses
</h1>
<p>
 launchctl unload -w /System/Library/LaunchAgents/com.apple.rcd.plist
</p>
<h1>
 Respond to Key Presses (Default)
</h1>
<p>
 launchctl load -w /System/Library/LaunchAgents/com.apple.rcd.plist
```

 Mail

 Show Attachments as Icons

  bash
defaults write com.apple.mail DisableInlineAttachmentViewing -bool yes

 Vacuum Mail Index

 The AppleScript code below will quit Mail, vacuum the SQLite index, then re-open Mail. On a large email database that hasn't been optimized for a while, this can provide significant improvements in responsiveness and speed.
```applescript
(*
Speed up Mail.app by vacuuming the Envelope Index
Code from: http://www.hawkwings.net/2007/03/03/scripts-to-automate-the-mailapp-envelope-speed-trick/
Originally by "pmbuko" with modifications by Romulo
Updated by Brett Terpstra 2012
Updated by Mathias Törnblom 2015 to support V3 in El Capitan and still keep backwards compatibility
*)
</p>
<p>
 tell application "Mail" to quit
set os
 <em>
  version to do shell script "sw
 </em>
 vers -productVersion"
set mail
 <em>
  version to "V2"
considering numeric strings
    if "10.10" <= os
 </em>
 version then set mail_version to "V3"
end considering
</p>
<p>
 set sizeBefore to do shell script "ls -lnah ~/Library/Mail/" & mail
 <em>
  version & "/MailData | grep -E 'Envelope Index$' | awk {'print $5'}"
do shell script "/usr/bin/sqlite3 ~/Library/Mail/" & mail
 </em>
 version & "/MailData/Envelope\ Index vacuum"
</p>
<p>
 set sizeAfter to do shell script "ls -lnah ~/Library/Mail/" & mail_version & "/MailData | grep -E 'Envelope Index$' | awk {'print $5'}"
</p>
<p>
 display dialog ("Mail index before: " & sizeBefore & return & "Mail index after: " & sizeAfter & return & return & "Enjoy the new speed!")
</p>
<p>
 tell application "Mail" to activate
```

 Safari

 Enable Develop Menu and Web Inspector

  bash
defaults write com.apple.Safari IncludeInternalDebugMenu -bool true && \
defaults write com.apple.Safari IncludeDevelopMenu -bool true && \
defaults write com.apple.Safari WebKitDeveloperExtrasEnabledPreferenceKey -bool true && \
defaults write com.apple.Safari com.apple.Safari.ContentPageGroupIdentifier.WebKit2DeveloperExtrasEnabled -bool true && \
defaults write NSGlobalDomain WebKitDeveloperExtras -bool true

 Get Current Page Data

 Other options:

  get source

 ,

  get text

 .

  bash
osascript -e 'tell application "Safari" to get URL of current tab of front window'

 Sketch

 Export Compact SVGs

  bash
defaults write com.bohemiancoding.sketch3 exportCompactSVG -bool yes

 Skim

 Turn Off Auto Reload Dialog

 Removes the dialog and defaults to auto reload.

  bash
defaults write -app Skim SKAutoReloadFileUpdate -boolean true

 TextEdit

 Use Plain Text Mode as Default

  bash
defaults write com.apple.TextEdit RichText -int 0

 Backup

 Time Machine

 Change Backup Interval

 This changes the interval to 30 minutes. The integer value is the time in seconds.

  bash
sudo defaults write /System/Library/Launch Daemons/com.apple.backupd-auto StartInterval -int 1800

 Local Backups

 Whether Time Machine performs local backups while the Time Machine backup volume is not available.
```bash
</p>
<h1>
 Disable
</h1>
<p>
 sudo tmutil disablelocal
</p>
<h1>
 Enable (Default)
</h1>
<p>
 sudo tmutil enablelocal
```

 Prevent Time Machine from Prompting to Use New Hard Drives as Backup Volume

  bash
defaults write com.apple.TimeMachine DoNotOfferNewDisksForBackup -bool true

 Set Status

 ```bash
</p>
<h1>
 Disable Local Time Machine Backups
</h1>
<p>
 hash tmutil &> /dev/null && sudo tmutil disablelocal
</p>
<h1>
 Enable Local Time Machine Backups (Default)
</h1>
<p>
 hash tmutil &> /dev/null && sudo tmutil enablelocal
```

 Developer

 Vim

 Compile Sane Vim

 Compiling MacVim via Homebrew with all bells and whistles, including overriding system Vim.

  bash
brew install macvim --HEAD --with-cscope --with-lua --with-override-system-vim --with-luajit --with-python

 Neovim

 Install the development version of this modern Vim drop-in alternative via Homebrew.

  bash
brew tap neovim/neovim && \
brew install neovim

 Xcode

 Install Command Line Tools without Xcode

  bash
xcode-select --install

 Remove All Unavailable Simulators

  bash
xcrun simctl delete unavailable

 Disks and Volumes

 Disable Sudden Motion Sensor

 Leaving this turned on is useless when you're using SSDs.

  bash
sudo pmset -a sms 0

 Eject All Mountable Volumes

 The only reliable way to do this is by sending an AppleScript command to Finder.

  bash
osascript -e 'tell application "Finder" to eject (every disk whose ejectable is true)'

 Repair File Permissions

 You don't have to use the Disk Utility GUI for this.

  bash
sudo diskutil repairPermissions /

  Beginning with OS X El Capitan, system file permissions are automatically protected. It's no longer necessary to verify or repair permissions with Disk Utility. (

   Source

  )

 Set Boot Volume

  bash
bless --mount "/path/to/mounted/volume" --setBoot

 Show All Attached Disks and Partitions

  bash
diskutil list

 View File System Usage

 A continuous stream of file system access info.

  bash
sudo fs_usage

 Disk Images

 Create Disk Image From Folder Contents

  bash
hdiutil create -volname "Volume Name" -srcfolder /path/to/folder -ov diskimage.dmg

 If you'd like to encrypt the disk image:

  bash
hdiutil create -encryption -stdinpass -volname "Volume Name" -srcfolder /path/to/folder -ov encrypted.dmg

 By default, you'll be prompted for a password. You can automate that by piping in a password:

  bash
echo -n YourPassword | hdiutil create -encryption -stdinpass -volname "Volume Name" -srcfolder /path/to/folder -ov encrypted.dmg

 Burn Disk Images to DVD

 This command applies to .iso, .img and .dmg images.

  bash
hdiutil burn /path/to/image_file

 Disable Disk Image Verification

  bash
defaults write com.apple.frameworks.diskimages skip-verify -bool true && \
defaults write com.apple.frameworks.diskimages skip-verify-locked -bool true && \
defaults write com.apple.frameworks.diskimages skip-verify-remote -bool true

 Make Volume OS X Bootable

  bash
bless --folder "/path/to/mounted/volume/System/Library/CoreServices" --bootinfo --bootefi

 Mount Disk Image

  bash
hdiutil attach /path/to/diskimage.dmg

 Unmount Disk Image

  bash
hdiutil detach /dev/disk2s1

 Write Disk Image to Volume

 Like the Disk Utility "Restore" function.

  bash
sudo asr -restore -noverify -source /path/to/diskimage.dmg -target /Volumes/VolumeToRestoreTo

 Dock

 Add a Stack with Recent Applications

  bash
defaults write com.apple.dock persistent-others -array-add '{ "tile-data" = { "list-type" = 1; }; "tile-type" = "recents-tile"; }' && \
killall Dock

 Add a Space

  bash
defaults write com.apple.dock persistent-apps -array-add '{"tile-type"="spacer-tile";}' && \
killall Dock

 Icon Bounce

 Global setting whether Dock icons should bounce when the respective application demands your attention.
```bash
</p>
<h1>
 Enable (Default)
</h1>
<p>
 defaults write com.apple.dock no-bouncing -bool true && \
killall Dock
</p>
<h1>
 Disable
</h1>
<p>
 defaults write com.apple.dock no-bouncing -bool false && \
killall Dock
```

 Reset Dock

  bash
defaults delete com.apple.dock && \
killall Dock

 Scroll Gestures

 Use your touchpad or mouse scroll wheel to interact with Dock items. Allows you to use an upward scrolling gesture to open stacks. Using the same gesture on applications that are running invokes Exposé/Mission Control.
```bash
</p>
<h1>
 Enable
</h1>
<p>
 defaults write com.apple.dock scroll-to-open -bool true && \
killall Dock
</p>
<h1>
 Disable (Default)
</h1>
<p>
 defaults write com.apple.dock scroll-to-open -bool false && \
killall Dock
```

 Set Auto Show/Hide Delay

 The float number defines the show/hide delay in ms.

  bash
defaults write com.apple.Dock autohide-delay -float 0 && \
killall Dock

 Show Hidden App Icons

 ```bash
</p>
<h1>
 Enable
</h1>
<p>
 defaults write com.apple.dock showhidden -bool true && \
killall Dock
</p>
<h1>
 Disable
</h1>
<p>
 defaults write com.apple.dock showhidden -bool false && \
killall Dock
```

 Documents

 Convert File to HTML

 Supported formats are plain text, rich text (rtf) and Microsoft Word (doc/docx).

  bash
textutil -convert html file.ext

 Finder

 Files and Folders

 Clear All ACLs

  bash
sudo chmod -RN /path/to/folder

 Hide Folder in Finder

  bash
chflags hidden /path/to/folder/

 Show All File Extensions

  bash
defaults write NSGlobalDomain AppleShowAllExtensions -bool true

 Show Hidden Files

 ```bash
</p>
<h1>
 Show All
</h1>
<p>
 defaults write com.apple.finder AppleShowAllFiles true
</p>
<h1>
 Restore Default File Visibility
</h1>
<p>
 defaults write com.apple.finder AppleShowAllFiles false
```

 Remove Protected Flag

  bash
sudo chflags -R nouchg /path/to/file/or/folder

 Show Full Path in Finder Title

  bash
defaults write com.apple.finder _FXShowPosixPathInTitle -bool true

 Unhide User Library Folder

  bash
chflags nohidden ~/Library

 Increase Number of Recent Places

  bash
defaults write .GlobalPreferences NSNavRecentPlacesLimit -int 10 && \
killall Finder

 Layout

 Show "Quit Finder" Menu Item

 Makes possible to see Finder menu item "Quit Finder" with default shortcut

  Cmd

 +

  Q

 ```bash
</p>
<h1>
 Enable
</h1>
<p>
 defaults write com.apple.finder QuitMenuItem -bool true && \
killall Finder
</p>
<h1>
 Disable (Default)
</h1>
<p>
 defaults write com.apple.finder QuitMenuItem -bool false && \
killall Finder
```

 Smooth Scrolling

 Useful if you're on an older Mac that messes up the animation.
```bash
</p>
<h1>
 Disable
</h1>
<p>
 defaults write NSGlobalDomain NSScrollAnimationEnabled -bool false
</p>
<h1>
 Enable (Default)
</h1>
<p>
 defaults write NSGlobalDomain NSScrollAnimationEnabled -bool true
```

 Rubberband Scrolling

 ```bash
</p>
<h1>
 Disable
</h1>
<p>
 defaults write -g NSScrollViewRubberbanding -bool false
</p>
<h1>
 Enable (Default)
</h1>
<p>
 defaults write -g NSScrollViewRubberbanding -bool true
```

 Expand Save Panel by Default

  bash
defaults write NSGlobalDomain NSNavPanelExpandedStateForSaveMode -bool true && \
defaults write NSGlobalDomain NSNavPanelExpandedStateForSaveMode2 -bool true

 Desktop Icon Visibility

 ```bash
</p>
<h1>
 Hide Icons
</h1>
<p>
 defaults write com.apple.finder CreateDesktop -bool false && \
killall Finder
</p>
<h1>
 Show Icons (Default)
</h1>
<p>
 defaults write com.apple.finder CreateDesktop -bool true && \
killall Finder
```

 Path Bar

 ```bash
</p>
<h1>
 Show
</h1>
<p>
 defaults write com.apple.finder ShowPathbar -bool true
</p>
<h1>
 Hide (Default)
</h1>
<p>
 defaults write com.apple.finder ShowPathbar -bool false
```

 Scrollbar Visibility

 Possible values:

  WhenScrolling

 ,

  Automatic

 and

  Always

 .

  bash
defaults write NSGlobalDomain AppleShowScrollBars -string "Always"

 Status Bar

 ```bash
</p>
<h1>
 Show
</h1>
<p>
 defaults write com.apple.finder ShowStatusBar -bool true
</p>
<h1>
 Hide (Default)
</h1>
<p>
 defaults write com.apple.finder ShowStatusBar -bool false
```

 Save to Disk by Default

 Sets default save target to be a local disk, not iCloud.

  bash
defaults write NSGlobalDomain NSDocumentSaveNewDocumentsToCloud -bool false

 Set Current Folder as Default Search Scope

  bash
defaults write com.apple.finder FXDefaultSearchScope -string "SCcf"

 Set Default Finder Location to Home Folder

  bash
defaults write com.apple.finder NewWindowTarget -string "PfLo" && \
defaults write com.apple.finder NewWindowTargetPath -string "file://${HOME}"

 Set Sidebar Icon Size

 Sets size to 'medium'.

  bash
defaults write NSGlobalDomain NSTableViewDefaultSizeMode -int 2

 Metadata Files

 Disable Creation of Metadata Files on Network Volumes

 Avoids creation of

  .DS_Store

 and AppleDouble files.

  bash
defaults write com.apple.desktopservices DSDontWriteNetworkStores -bool true

 Disable Creation of Metadata Files on USB Volumes

 Avoids creation of

  .DS_Store

 and AppleDouble files.

  bash
defaults write com.apple.desktopservices DSDontWriteUSBStores -bool true

 Opening Things

 Change Working Directory to Finder Path

 If multiple windows are open, it chooses the top-most one.

  bash
cd "$(osascript -e 'tell app "Finder" to POSIX path of (insertion location as alias)')"

 Open URL

  bash
open https://github.com

 Open File

  bash
open README.md

 Open Applications

 You can open applications using

  -a

 .

  bash
open -a "Google Chrome" https://github.com

 Open Folder

  bash
open /path/to/folder/

 Open Current Folder

  bash
open .

 Fonts

 Clear Font Cache for Current User

 To clear font caches for all users, put

  sudo

 in front of this command.

  bash
atsutil databases -removeUser && \
atsutil server -shutdown && \
atsutil server -ping

 Get SF Mono Fonts

 You need to download and install Xcode 8 beta for this to work. Afterwards they should be available in all applications.

  bash
cp -v /Applications/Xcode-beta.app/Contents/SharedFrameworks/DVTKit.framework/Versions/A/Resources/Fonts/SFMono-* ~/Library/Fonts

 Functions

 Please see

  this file

 .

 Hardware

 Bluetooth

 ```bash
</p>
<h1>
 Status
</h1>
<p>
 defaults read /Library/Preferences/com.apple.Bluetooth ControllerPowerState
</p>
<h1>
 Enable (Default)
</h1>
<p>
 sudo defaults write /Library/Preferences/com.apple.Bluetooth ControllerPowerState -int 1
</p>
<h1>
 Disable
</h1>
<p>
 sudo defaults write /Library/Preferences/com.apple.Bluetooth ControllerPowerState -int 0 && \
sudo killall -HUP blued
```

 Hardware Information

 List All Hardware Ports

  bash
networksetup -listallhardwareports

 Remaining Battery Percentage

  bash
pmset -g batt | egrep "([0-9]+\%).*" -o --colour=auto | cut -f1 -d';'

 Remaining Battery Time

  bash
pmset -g batt | egrep "([0-9]+\%).*" -o --colour=auto | cut -f3 -d';'

 Show Connected Device's UDID

  bash
system_profiler SPUSBDataType | sed -n -e '/iPad/,/Serial/p' -e '/iPhone/,/Serial/p'

 Show Current Screen Resolution

  bash
system_profiler SPDisplaysDataType | grep Resolution

 Show CPU Brand String

  bash
sysctl -n machdep.cpu.brand_string

 Infrared Receiver

 ```bash
</p>
<h1>
 Status
</h1>
<p>
 defaults read /Library/Preferences/com.apple.driver.AppleIRController DeviceEnabled
</p>
<h1>
 Enable (Default)
</h1>
<p>
 defaults write /Library/Preferences/com.apple.driver.AppleIRController DeviceEnabled -int 1
</p>
<h1>
 Disable
</h1>
<p>
 defaults write /Library/Preferences/com.apple.driver.AppleIRController DeviceEnabled -int 0
```

 Power Management

 Prevent System Sleep

 Prevent sleep for 1 hour:

  bash
caffeinate -u -t 3600

 Show All Power Management Settings

  bash
sudo pmset -g

 Put Display to Sleep after 15 Minutes of Inactivity

  bash
sudo pmset displaysleep 15

 Put Computer to Sleep after 30 Minutes of Inactivity

  bash
sudo pmset sleep 30

 Check System Sleep Idle Time

  bash
sudo systemsetup -getcomputersleep

 Set System Sleep Idle Time to 60 Minutes

  bash
sudo systemsetup -setcomputersleep 60

 Turn Off System Sleep Completely

  bash
sudo systemsetup -setcomputersleep Never

 Automatic Restart on System Freeze

  bash
sudo systemsetup -setrestartfreeze on

 Chime When Charging

 Play iOS charging sound when MagSafe is connected.
```bash
</p>
<h1>
 Enable
</h1>
<p>
 defaults write com.apple.PowerChime ChimeOnAllHardware -bool true && \
open /System/Library/CoreServices/PowerChime.app
</p>
<h1>
 Disable (Default)
</h1>
<p>
 defaults write com.apple.PowerChime ChimeOnAllHardware -bool false && \
killall PowerChime
```

 Input Devices

 Keyboard

 Auto-Correct

 ```bash
</p>
<h1>
 Disable
</h1>
<p>
 defaults write -g NSAutomaticSpellingCorrectionEnabled -bool false
</p>
<h1>
 Enable (Default)
</h1>
<p>
 defaults write -g NSAutomaticSpellingCorrectionEnabled -bool true
</p>
<h1>
 Show Status
</h1>
<p>
 defaults read -g NSAutomaticSpellingCorrectionEnabled
```

 Key Repeat

 Disable the default "press and hold" behavior.
```bash
</p>
<h1>
 Enable Key Repeat
</h1>
<p>
 defaults write -g ApplePressAndHoldEnabled -bool false
</p>
<h1>
 Disable Key Repeat
</h1>
<p>
 defaults write -g ApplePressAndHoldEnabled -bool true
```

 Key Repeat Rate

 Sets a very fast repeat rate, adjust to taste.

  bash
defaults write NSGlobalDomain KeyRepeat -int 0.02

 Media

 Audio

 Convert Audio File to iPhone Ringtone

  bash
afconvert input.mp3 ringtone.m4r -f m4af

 Create Audiobook From Text

 Uses "Alex" voice, a plain UTF-8 encoded text file for input and AAC output.

  bash
say -v Alex -f file.txt -o "output.m4a"

 Disable Sound Effects on Boot

  bash
sudo nvram SystemAudioVolume=" "

 Mute Audio Output

  bash
osascript -e 'set volume output muted true'

 Set Audio Volume

  bash
osascript -e 'set volume 4'

 Play Audio File

 You can play all audio formats that are natively supported by QuickTime.

  bash
afplay -q 1 filename.mp3

 Speak Text with System Default Voice

  bash
say 'All your base are belong to us!'

 Video

 Auto-Play Videos in QuickTime Player

  bash
defaults write com.apple.QuickTimePlayerX MGPlayMovieOnOpen 1

 Networking

 Bonjour

 Bonjour Service

 ```bash
</p>
<h1>
 Disable
</h1>
<p>
 sudo defaults write /System/Library/LaunchDaemons/com.apple.mDNSResponder.plist ProgramArguments -array-add "-NoMulticastAdvertisements"
</p>
<h1>
 Enable (Default)
</h1>
<p>
 sudo defaults write /System/Library/LaunchDaemons/com.apple.mDNSResponder.plist ProgramArguments -array "/usr/sbin/mDNSResponder" "-launchd"
```

 DHCP

 Renew DHCP Lease

  bash
sudo ipconfig set en0 DHCP

 Show DHCP Info

  bash
ipconfig getpacket en0

 DNS

 Clear DNS Cache

  bash
sudo dscacheutil -flushcache && \
sudo killall -HUP mDNSResponder

 Hostname

 Set Computer Name/Host Name

  bash
sudo scutil --set ComputerName "newhostname" && \
sudo scutil --set HostName "newhostname" && \
sudo scutil --set LocalHostName "newhostname" && \
sudo defaults write /Library/Preferences/SystemConfiguration/com.apple.smb.server NetBIOSName -string "newhostname"

 Network Preferences

 Network Locations

 Switch between network locations created in the Network preference pane.
```bash
</p>
<h1>
 Status
</h1>
<p>
 scselect
</p>
<h1>
 Switch Network Location
</h1>
<p>
 scselect LocationNameFromStatus
```

 Networking Tools

 Ping a Host to See Whether It's Available

  bash
ping -o github.com

 Troubleshoot Routing Problems

  bash
traceroute github.com

 SSH

 Remote Login

 ```bash
</p>
<h1>
 Enable remote login
</h1>
<p>
 sudo launchctl load -w /System/Library/LaunchDaemons/ssh.plist
</p>
<h1>
 Disable remote login
</h1>
<p>
 sudo launchctl unload -w /System/Library/LaunchDaemons/ssh.plist
```

 TCP/IP

 Show Application Using a Certain Port

 This outputs all applications currently using port 80.

  bash
sudo lsof -i :80

 Show External IP Address

  bash
dig +short myip.opendns.com @resolver1.opendns.com

 Wi-Fi

 Join a Wi-Fi Network

  bash
networksetup -setairportnetwork en0 WIFI_SSID WIFI_PASSWORD

 Scan Available Access Points

 Create a symbolic link to the airport command for easy access:

  bash
sudo ln -s /System/Library/PrivateFrameworks/Apple80211.framework/Versions/Current/Resources/airport /usr/local/bin/airport

 Run a wireless scan:

  bash
airport -s

 Show Current SSID

  bash
/System/Library/PrivateFrameworks/Apple80211.framework/Versions/Current/Resources/airport -I | awk '/ SSID/ {print substr($0, index($0, $2))}'

 Show Local IP Address

  bash
ipconfig getifaddr en0

 Show Wi-Fi Connection History

  bash
defaults read /Library/Preferences/SystemConfiguration/com.apple.airport.preferences | grep LastConnected -A 7

 Show Wi-Fi Network Passwords

 Exchange SSID with the SSID of the access point you wish to query the password from.

  bash
security find-generic-password -D "AirPort network password" -a "SSID" -gw

 Turn on Wi-Fi Adapter

  bash
networksetup -setairportpower en0 on

 Package Managers

   Fink

  - The full world of Unix Open Source software for Darwin. A little outdated.

   Homebrew

  - The missing package manager for OS X. The most popular choice.

   MacPorts

  - Compile, install and upgrade either command-line, X11 or Aqua based open-source software. Very clean, it's what I use.

 Printing

 Clear Print Queue

  bash
cancel -a -

 Expand Print Panel by Default

  bash
defaults write NSGlobalDomain PMPrintingExpandedStateForPrint -bool true && \
defaults write NSGlobalDomain PMPrintingExpandedStateForPrint2 -bool true

 Quit Printer App After Print Jobs Complete

  bash
defaults write com.apple.print.PrintingPrefs "Quit When Finished" -bool true

 Security

 Application Firewall

 Firewall Service

 ```bash
</p>
<h1>
 Show Status
</h1>
<p>
 sudo /usr/libexec/ApplicationFirewall/socketfilterfw --getglobalstate
</p>
<h1>
 Enable
</h1>
<p>
 sudo /usr/libexec/ApplicationFirewall/socketfilterfw --setglobalstate on
</p>
<h1>
 Disable (Default)
</h1>
<p>
 sudo /usr/libexec/ApplicationFirewall/socketfilterfw --setglobalstate off
```

 Add Application to Firewall

  bash
sudo /usr/libexec/ApplicationFirewall/socketfilterfw --add /path/to/file

 Gatekeeper

 Add Gatekeeper Exception

  bash
spctl --add /path/to/Application.app

 Remove Gatekeeper Exception

  bash
spctl --remove /path/to/Application.app

 Passwords

 Generate Secure Password and Copy to Clipboard

  bash
tr -dc A-Za-z0-9_ < /dev/urandom | head -c 20 | pbcopy

 Physical Access

 Launch Screen Saver

  bash
open /System/Library/Frameworks/ScreenSaver.framework/Versions/A/Resources/ScreenSaverEngine.app

 Lock Screen

  bash
/System/Library/CoreServices/Menu\ Extras/User.menu/Contents/Resources/CGSession -suspend

 Screensaver Immediate Lock

 ```bash
</p>
<h1>
 Status
</h1>
<p>
 defaults read com.apple.screensaver askForPasswordDelay
</p>
<h1>
 Enable (Default)
</h1>
<p>
 defaults write com.apple.screensaver askForPasswordDelay -int 0
</p>
<h1>
 Disable (Integer = lock delay in seconds)
</h1>
<p>
 defaults write com.apple.screensaver askForPasswordDelay -int 10
```

 Screensaver Password

 ```bash
</p>
<h1>
 Status
</h1>
<p>
 defaults read com.apple.screensaver askForPassword
</p>
<h1>
 Enable
</h1>
<p>
 defaults write com.apple.screensaver askForPassword -int 1
</p>
<h1>
 Disable (Default)
</h1>
<p>
 defaults write com.apple.screensaver askForPassword -int 0
```

 Wiping Data

 Securely Remove File

  bash
srm /path/to/file

 Securely Remove Folder

  bash
srm -r /path/to/folder/

 Securely Remove Path (Force)

  bash
srm -rf /path/to/complete/destruction

 Search

 Find

 Recursively Delete .DS_Store Files

  bash
find . -type f -name '*.DS_Store' -ls -delete

 Locate

 Build Locate Database

  bash
sudo launchctl load -w /System/Library/LaunchDaemons/com.apple.locate.plist

 Search via Locate

 The

  -i

 modifier makes the search case insensitive.

  bash
locate -i *.jpg

 System

 AirDrop

 ```bash
</p>
<h1>
 Enable AirDrop over Ethernet and on Unsupported Macs
</h1>
<p>
 defaults write com.apple.NetworkBrowser BrowseAllInterfaces -bool true
</p>
<h1>
 Enable (Default)
</h1>
<p>
 defaults remove com.apple.NetworkBrowser DisableAirDrop
</p>
<h1>
 Disable
</h1>
<p>
 defaults write com.apple.NetworkBrowser DisableAirDrop -bool YES
```

 AppleScript

 Execute AppleScript

  bash
osascript /path/to/script.scpt

 Basics

 Compare Two Folders

  bash
diff -qr /path/to/folder1 /path/to/folder2

 Restore Sane Shell

 In case your shell session went insane (some script or application turned it into a garbled mess).

  bash
stty sane

 Restart

  bash
sudo reboot

 Shutdown

  bash
sudo poweroff

 Show Build Number of OS

  bash
sw_vers

 Uptime

 How long since your last restart.

  bash
uptime

 Clipboard

 Copy data to Clipboard

  bash
cat whatever.txt | pbcopy

 Convert Clipboard to Plain Text

  bash
pbpaste | textutil -convert txt -stdin -stdout -encoding 30 | pbcopy

 Convert Tabs to Spaces for Clipboard Content

  bash
pbpaste | expand | pbcopy

 Copy data from Clipboard

  bash
pbpaste > whatever.txt

 Sort and Strip Duplicate Lines from Clipboard Content

  bash
pbpaste | sort | uniq | pbcopy

 FileVault

 Automatically Unlock FileVault on Restart

 If FileVault is enabled on the current volume, it restarts the system, bypassing the initial unlock. The command may not work on all systems.

  bash
sudo fdesetup authrestart

 FileVault Service

 ```bash
</p>
<h1>
 Status
</h1>
<p>
 sudo fdesetup status
</p>
<h1>
 Enable
</h1>
<p>
 sudo fdesetup enable
</p>
<h1>
 Disable (Default)
</h1>
<p>
 sudo fdestatus disable
```

 Information/Reports

 Generate Advanced System and Performance Report

  bash
sudo sysdiagnose -f ~/Desktop/

 Install OS

 Create Bootable Installer

 ```bash
</p>
<h1>
 El Capitan
</h1>
<p>
 sudo /Applications/Install\ OS\ X\ El\ Capitan.app/Contents/Resources/createinstallmedia --volume /Volumes/MyVolume --applicationpath /Applications/Install\ OS\ X\ El\ Capitan.app
</p>
<h1>
 Yosemite
</h1>
<p>
 sudo /Applications/Install\ OS\ X\ Yosemite.app/Contents/Resources/createinstallmedia --volume /Volumes/MyVolume --applicationpath /Applications/Install\ OS\ X\ Yosemite.app
</p>
<h1>
 Mavericks
</h1>
<p>
 sudo /Applications/Install\ OS\ X\ Mavericks.app/Contents/Resources/createinstallmedia --volume /Volumes/MyVolume --applicationpath /Applications/Install\ OS\ X\ Mavericks.app
```

 Kernel Extensions

 Display Status of Loaded Kernel Extensions

  bash
sudo kextstat -l

 Load Kernel Extension

  bash
sudo kextload -b com.apple.driver.ExampleBundle

 Unload Kernel Extensions

  bash
sudo kextunload -b com.apple.driver.ExampleBundle

 LaunchAgents

 Please see

  this file

 .

 LaunchServices

 Rebuild LaunchServices Database

 To be independent of OS X version, this relies on

  locate

 to find

  lsregister

 . If you do not have your

  locate

 database built yet,

  do it

 .

  bash
sudo $(locate lsregister) -kill -seed -r

 Login Window

 Set Login Window Text

  bash
sudo defaults write /Library/Preferences/com.apple.loginwindow LoginwindowText "Your text"

 Memory Management

 Purge memory cache

  bash
sudo purge

 Show Memory Statistics

 ```bash
</p>
<h1>
 One time
</h1>
<p>
 vm_stat
</p>
<h1>
 Table of data, repeat 10 times total, 1 second wait between each poll
</h1>
<p>
 vm_stat -c 10 1
```

 Notification Center

 Notification Center Service

 ```bash
</p>
<h1>
 Disable
</h1>
<p>
 launchctl unload -w /System/Library/LaunchAgents/com.apple.notificationcenterui.plist && \
killall -9 NotificationCenter
</p>
<h1>
 Enable (Default)
</h1>
<p>
 launchctl load -w /System/Library/LaunchAgents/com.apple.notificationcenterui.plist
```

 QuickLook

 Preview via QuickLook

  bash
qlmanage -p /path/to/file

 Remote Apple Events

 ```bash
</p>
<h1>
 Status
</h1>
<p>
 sudo systemsetup -getremoteappleevents
</p>
<h1>
 Enable
</h1>
<p>
 sudo systemsetup -setremoteappleevents on
</p>
<h1>
 Disable (Default)
</h1>
<p>
 sudo systemsetup -setremoteappleevents off
```

 Root User

 ```bash
</p>
<h1>
 Enable
</h1>
<p>
 dsenableroot
</p>
<h1>
 Disable
</h1>
<p>
 dsenableroot -d
```

 Safe Mode Boot

 ```bash
</p>
<h1>
 Status
</h1>
<p>
 nvram boot-args
</p>
<h1>
 Enable
</h1>
<p>
 sudo nvram boot-args="-x"
</p>
<h1>
 Disable
</h1>
<p>
 sudo nvram boot-args=""
```

 Screenshots

 Take Delayed Screenshot

 Takes a screenshot as JPEG after 3 seconds and displays in Preview.

  bash
screencapture -T 3 -t jpg -P delayedpic.jpg

 Save Screenshots to Given Location

 Sets location to

  ~/Desktop

 .

  bash
defaults write com.apple.screencapture location ~/Desktop && \
killall SystemUIServer

 Save Screenshots in Given Format

 Sets format to

  png

 . Other options are

  bmp

 ,

  gif

 ,

  jpg

 ,

  jpeg

 ,

  pdf

 ,

  tiff

 .

  bash
defaults write com.apple.screencapture type -string "png"

 Disable Shadow in Screenshots

  bash
defaults write com.apple.screencapture disable-shadow -bool true && \
killall SystemUIServer

 Set Default Screenshot Name

 Date and time remain unchanged.

  bash
defaults write com.apple.screencapture name "Example name" && \
killall SystemUIServer

 Software Installation

 Install PKG

  bash
installer -pkg /path/to/installer.pkg -target /

 Software Update

 Install All Available Software Updates

  bash
sudo softwareupdate -ia

 Set Software Update Check Interval

 Set to check daily instead of weekly.

  bash
defaults write com.apple.SoftwareUpdate ScheduleFrequency -int 1

 Show Available Software Updates

  bash
sudo softwareupdate -l

 Set Software Update Server

 This should only be done for testing purposes or unmanaged clients. To use network-wide, either correctly set up DNS along with

  Apple SUS service

 and bind your clients via OpenDirectory. Alternatively, use

  Reposado

 together with correct network DNS settings to make resolution transparent.

  Margarita

 looks nice to have as well.
```bash
</p>
<h1>
 Use own SUS
</h1>
<p>
 sudo defaults write /Library/Preferences/com.apple.SoftwareUpdate CatalogURL http://su.example.com:8088/index.sucatalog
</p>
<h1>
 Reset to Apple SUS
</h1>
<p>
 sudo defaults delete /Library/Preferences/com.apple.SoftwareUpdate CatalogURL
```

 Spotlight

 Spotlight Indexing

 ```bash
</p>
<h1>
 Disable
</h1>
<p>
 mdutil -i off -d /path/to/volume
</p>
<h1>
 Enable (Default)
</h1>
<p>
 mdutil -i on /path/to/volume
```

 Erase Spotlight Index and Rebuild

  bash
mdutil -E /path/to/volume

 Search via Spotlight

  bash
mdfind -name 'searchterm'

 Show Spotlight Indexed Metadata

  bash
mdls /path/to/file

 System Integrity Protection

 Disable System Integrity Protection

 Reboot while holding

  Cmd

 +

  R

 , open the Terminal application and enter:

  bash
csrutil disable && reboot

 Enable System Integrity Protection

 Reboot while holding

  Cmd

 +

  R

 , open the Terminal application and enter:

  bash
csrutil enable && reboot

 Date and Time

 List Available Timezones

  bash
sudo systemsetup -listtimezones

 Set Timezone

  bash
sudo systemsetup -settimezone Europe/Berlin

 Set Clock Using Network Time

 ```bash
</p>
<h1>
 Status
</h1>
<p>
 sudo systemsetup getusingnetworktime
</p>
<h1>
 Enable (Default)
</h1>
<p>
 sudo systemsetup setusingnetworktime on
</p>
<h1>
 Disable
</h1>
<p>
 sudo systemsetup setusingnetworktime off
```

 Terminal

 Ring Terminal Bell

 Rings the terminal bell (if enabled) and puts a badge on it.

  bash
tput bel

 Alternative Terminals

   iTerm2

  - A better Terminal.app.

 Shells

 Bash

 Install the latest version and set as current users' default shell:

  bash
brew install bash && \
sudo echo $(brew --prefix)/bin/bash >> /etc/shells && \
chsh -s $(brew --prefix)/bin/bash

   Homepage

  - The default shell for OS X and most other Unix-based operating systems.

   Bash-it

  - Community Bash framework, like Oh My Zsh for Bash.

   &#9733 4477, pushed 129 days ago

 fish

 Install the latest version and set as current users' default shell:

  bash
brew install fish && \
echo $(brew --prefix)/bin/fish | sudo tee -a /etc/shells && \
chsh -s $(brew --prefix)/bin/fish

   Homepage

  - A smart and user-friendly command line
shell for OS X, Linux, and the rest of the family.

   Fisherman

  - A blazing fast, modern plugin manager for Fish.

   The Fishshell Framework

  - Provides core infrastructure to allow you to install packages which extend or modify the look of your shell.

   &#9733 952, pushed 129 days ago

   Installation & Configuration Tutorial

  - How to Setup Fish Shell with Fisherman, Powerline Fonts, iTerm2 and Budspencer Theme on OS X.

 Zsh

 Install the latest version and set as current users' default shell:

  bash
brew install zsh && \
sudo sh -c 'echo $(brew --prefix)/bin/zsh >> /etc/shells' && \
chsh -s $(brew --prefix)/bin/zsh

   Homepage

  - Zsh is a shell designed for interactive use, although it is also a powerful scripting language.

   Oh My Zsh

  - An open source, community-driven framework for managing your Zsh configuration.

   Prezto

  - A speedy Zsh framework. Enriches the command line interface environment with sane defaults, aliases, functions, auto completion, and prompt themes.

   &#9733 6108, pushed 131 days ago

   zgen

  - Another open source framework for managing your zsh configuration. Zgen will load oh-my-zsh compatible plugins and themes and has the advantage of both being faster and automatically cloning any plugins used in your configuration for you.

   &#9733 508, pushed 151 days ago

 Terminal Fonts

   Anonymous Pro

  - A family of four fixed-width fonts designed with coding in mind.

   Codeface

  - A gallery and repository of monospaced fonts for developers.

   &#9733 3139, pushed 153 days ago

   DejaVu Sans Mono

  - A font family based on the Vera Fonts.

   Hack

  - Hack is hand groomed and optically balanced to be your go-to code face.

   Inconsolata

  -  A monospace font, designed for code listings and the like.

   Input

  - A flexible system of fonts designed specifically for code.

   Meslo

  - Customized version of Apple's Menlo font.

   &#9733 1468, pushed 367 days ago

   Powerline Fonts

  - Repo of patched fonts for the Powerline plugin.

   &#9733 5063, pushed 142 days ago

   Source Code Pro

  - A monospaced font family for user interfaces and coding environments.

 License

 This work is licensed under a

  Creative Commons Attribution-ShareAlike 4.0 International License

 .


text:
package scala.meta.internal.parsers

sealed trait SepRegion {
  def indent = -1
  def closeOnNonCase = false
  def indentOnArrow = true
  def isIndented = false
}

case class RegionIndent(override val indent: Int, override val closeOnNonCase: Boolean)
    extends SepRegion {
  override def isIndented: Boolean = true
}

case class RegionParen(canProduceLF: Boolean) extends SepRegion

case object RegionBracket extends SepRegion

case class RegionBrace(override val indent: Int, override val indentOnArrow: Boolean)
    extends SepRegion

case class RegionCase(override val indent: Int) extends SepRegion

case class RegionEnum(override val indent: Int) extends SepRegion

case class RegionIndentEnum(override val indent: Int) extends SepRegion {
  override def isIndented: Boolean = true
}

case object RegionArrow extends SepRegion

// NOTE: Special case for Enum region is needed because parsing of 'case' statement is done differently
case object RegionEnumArtificialMark extends SepRegion


text:
#pragma once
#include <aws/logs/CloudWatchLogs_EXPORTS.h>
#include <aws/logs/CloudWatchLogsRequest.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>

namespace Aws
{
namespace CloudWatchLogs
{
namespace Model
{

  /**
   */
  class AWS_CLOUDWATCHLOGS_API DeleteDestinationRequest : public CloudWatchLogsRequest
  {
  public:
    DeleteDestinationRequest();

    // Service request name is the Operation name which will send this request out,
    // each operation should has unique request name, so that we can get operation's name from this request.
    // Note: this is not true for response, multiple operations may have the same response name,
    // so we can not get operation's name from response.
    inline virtual const char* GetServiceRequestName() const override { return "DeleteDestination"; }

    Aws::String SerializePayload() const override;

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

    /**
     *
The name of the destination.

     */
    inline const Aws::String& GetDestinationName() const{ return m_destinationName; }

    /**
     *
The name of the destination.

     */
    inline void SetDestinationName(const Aws::String& value) { m_destinationNameHasBeenSet = true; m_destinationName = value; }

    /**
     *
The name of the destination.

     */
    inline void SetDestinationName(Aws::String&& value) { m_destinationNameHasBeenSet = true; m_destinationName = std::move(value); }

    /**
     *
The name of the destination.

     */
    inline void SetDestinationName(const char* value) { m_destinationNameHasBeenSet = true; m_destinationName.assign(value); }

    /**
     *
The name of the destination.

     */
    inline DeleteDestinationRequest& WithDestinationName(const Aws::String& value) { SetDestinationName(value); return *this;}

    /**
     *
The name of the destination.

     */
    inline DeleteDestinationRequest& WithDestinationName(Aws::String&& value) { SetDestinationName(std::move(value)); return *this;}

    /**
     *
The name of the destination.

     */
    inline DeleteDestinationRequest& WithDestinationName(const char* value) { SetDestinationName(value); return *this;}

  private:

    Aws::String m_destinationName;
    bool m_destinationNameHasBeenSet;
  };

} // namespace Model
} // namespace CloudWatchLogs
} // namespace Aws