text:
#include "modules/audio_device/android/audio_manager.h"

#include <utility>

#include "modules/audio_device/android/audio_common.h"
#include BOSS_WEBRTC_U_modules__utility__include__helpers_android_h //original-code:"modules/utility/include/helpers_android.h"
#include BOSS_WEBRTC_U_rtc_base__arraysize_h //original-code:"rtc_base/arraysize.h"
#include BOSS_WEBRTC_U_rtc_base__checks_h //original-code:"rtc_base/checks.h"
#include BOSS_WEBRTC_U_rtc_base__logging_h //original-code:"rtc_base/logging.h"
#include BOSS_WEBRTC_U_rtc_base__platform_thread_h //original-code:"rtc_base/platform_thread.h"

namespace webrtc {

// AudioManager::JavaAudioManager implementation
AudioManager::JavaAudioManager::JavaAudioManager(
    NativeRegistration* native_reg,
    std::unique_ptr<GlobalRef> audio_manager)
    : audio_manager_(std::move(audio_manager)),
      init_(native_reg->GetMethodId("init", "()Z")),
      dispose_(native_reg->GetMethodId("dispose", "()V")),
      is_communication_mode_enabled_(
          native_reg->GetMethodId("isCommunicationModeEnabled", "()Z")),
      is_device_blacklisted_for_open_sles_usage_(
          native_reg->GetMethodId("isDeviceBlacklistedForOpenSLESUsage",
                                  "()Z")) {
  RTC_LOG(INFO) << "JavaAudioManager::ctor";
}

AudioManager::JavaAudioManager::~JavaAudioManager() {
  RTC_LOG(INFO) << "JavaAudioManager::~dtor";
}

bool AudioManager::JavaAudioManager::Init() {
  return audio_manager_->CallBooleanMethod(init_);
}

void AudioManager::JavaAudioManager::Close() {
  audio_manager_->CallVoidMethod(dispose_);
}

bool AudioManager::JavaAudioManager::IsCommunicationModeEnabled() {
  return audio_manager_->CallBooleanMethod(is_communication_mode_enabled_);
}

bool AudioManager::JavaAudioManager::IsDeviceBlacklistedForOpenSLESUsage() {
  return audio_manager_->CallBooleanMethod(
      is_device_blacklisted_for_open_sles_usage_);
}

// AudioManager implementation
AudioManager::AudioManager()
    : j_environment_(JVM::GetInstance()->environment()),
      audio_layer_(AudioDeviceModule::kPlatformDefaultAudio),
      initialized_(false),
      hardware_aec_(false),
      hardware_agc_(false),
      hardware_ns_(false),
      low_latency_playout_(false),
      low_latency_record_(false),
      delay_estimate_in_milliseconds_(0) {
  RTC_LOG(INFO) << "ctor";
  RTC_CHECK(j_environment_);
  JNINativeMethod native_methods[] = {
      {"nativeCacheAudioParameters", "(IIIZZZZZZZIIJ)V",
       reinterpret_cast<void*>(&webrtc::AudioManager::CacheAudioParameters)}};
  j_native_registration_ = j_environment_->RegisterNatives(
      "org/webrtc/voiceengine/WebRtcAudioManager", native_methods,
      arraysize(native_methods));
  j_audio_manager_.reset(
      new JavaAudioManager(j_native_registration_.get(),
                           j_native_registration_->NewObject(
                               "<init>", "(J)V", PointerTojlong(this))));
}

AudioManager::~AudioManager() {
  RTC_LOG(INFO) << "dtor";
  RTC_DCHECK(thread_checker_.CalledOnValidThread());
  Close();
}

void AudioManager::SetActiveAudioLayer(
    AudioDeviceModule::AudioLayer audio_layer) {
  RTC_LOG(INFO) << "SetActiveAudioLayer: " << audio_layer;
  RTC_DCHECK(thread_checker_.CalledOnValidThread());
  RTC_DCHECK(!initialized_);
  // Store the currently utilized audio layer.
  audio_layer_ = audio_layer;
  // The delay estimate can take one of two fixed values depending on if the
  // device supports low-latency output or not. However, it is also possible
  // that the user explicitly selects the high-latency audio path, hence we use
  // the selected |audio_layer| here to set the delay estimate.
  delay_estimate_in_milliseconds_ =
      (audio_layer == AudioDeviceModule::kAndroidJavaAudio)
          ? kHighLatencyModeDelayEstimateInMilliseconds
          : kLowLatencyModeDelayEstimateInMilliseconds;
  RTC_LOG(INFO) << "delay_estimate_in_milliseconds: "
                << delay_estimate_in_milliseconds_;
}

SLObjectItf AudioManager::GetOpenSLEngine() {
  RTC_LOG(INFO) << "GetOpenSLEngine";
  RTC_DCHECK(thread_checker_.CalledOnValidThread());
  // Only allow usage of OpenSL ES if such an audio layer has been specified.
  if (audio_layer_ != AudioDeviceModule::kAndroidOpenSLESAudio &&
      audio_layer_ !=
          AudioDeviceModule::kAndroidJavaInputAndOpenSLESOutputAudio) {
    RTC_LOG(INFO)
        << "Unable to create OpenSL engine for the current audio layer: "
        << audio_layer_;
    return nullptr;
  }
  // OpenSL ES for Android only supports a single engine per application.
  // If one already has been created, return existing object instead of
  // creating a new.
  if (engine_object_.Get() != nullptr) {
    RTC_LOG(WARNING) << "The OpenSL ES engine object has already been created";
    return engine_object_.Get();
  }
  // Create the engine object in thread safe mode.
  const SLEngineOption option[] = {
      {SL_ENGINEOPTION_THREADSAFE, static_cast<SLuint32>(SL_BOOLEAN_TRUE)}};
  SLresult result =
      slCreateEngine(engine_object_.Receive(), 1, option, 0, NULL, NULL);
  if (result != SL_RESULT_SUCCESS) {
    RTC_LOG(LS_ERROR) << "slCreateEngine() failed: "
                      << GetSLErrorString(result);
    engine_object_.Reset();
    return nullptr;
  }
  // Realize the SL Engine in synchronous mode.
  result = engine_object_->Realize(engine_object_.Get(), SL_BOOLEAN_FALSE);
  if (result != SL_RESULT_SUCCESS) {
    RTC_LOG(LS_ERROR) << "Realize() failed: " << GetSLErrorString(result);
    engine_object_.Reset();
    return nullptr;
  }
  // Finally return the SLObjectItf interface of the engine object.
  return engine_object_.Get();
}

bool AudioManager::Init() {
  RTC_LOG(INFO) << "Init";
  RTC_DCHECK(thread_checker_.CalledOnValidThread());
  RTC_DCHECK(!initialized_);
  RTC_DCHECK_NE(audio_layer_, AudioDeviceModule::kPlatformDefaultAudio);
  if (!j_audio_manager_->Init()) {
    RTC_LOG(LS_ERROR) << "Init() failed";
    return false;
  }
  initialized_ = true;
  return true;
}

bool AudioManager::Close() {
  RTC_LOG(INFO) << "Close";
  RTC_DCHECK(thread_checker_.CalledOnValidThread());
  if (!initialized_)
    return true;
  j_audio_manager_->Close();
  initialized_ = false;
  return true;
}

bool AudioManager::IsCommunicationModeEnabled() const {
  RTC_DCHECK(thread_checker_.CalledOnValidThread());
  return j_audio_manager_->IsCommunicationModeEnabled();
}

bool AudioManager::IsAcousticEchoCancelerSupported() const {
  RTC_DCHECK(thread_checker_.CalledOnValidThread());
  return hardware_aec_;
}

bool AudioManager::IsAutomaticGainControlSupported() const {
  RTC_DCHECK(thread_checker_.CalledOnValidThread());
  return hardware_agc_;
}

bool AudioManager::IsNoiseSuppressorSupported() const {
  RTC_DCHECK(thread_checker_.CalledOnValidThread());
  return hardware_ns_;
}

bool AudioManager::IsLowLatencyPlayoutSupported() const {
  RTC_DCHECK(thread_checker_.CalledOnValidThread());
  // Some devices are blacklisted for usage of OpenSL ES even if they report
  // that low-latency playout is supported. See b/21485703 for details.
  return j_audio_manager_->IsDeviceBlacklistedForOpenSLESUsage()
             ? false
             : low_latency_playout_;
}

bool AudioManager::IsLowLatencyRecordSupported() const {
  RTC_DCHECK(thread_checker_.CalledOnValidThread());
  return low_latency_record_;
}

bool AudioManager::IsProAudioSupported() const {
  RTC_DCHECK(thread_checker_.CalledOnValidThread());
  // TODO(henrika): return the state independently of if OpenSL ES is
  // blacklisted or not for now. We could use the same approach as in
  // IsLowLatencyPlayoutSupported() but I can't see the need for it yet.
  return pro_audio_;
}

// TODO(henrika): improve comments...
bool AudioManager::IsAAudioSupported() const {
#if defined(AUDIO_DEVICE_INCLUDE_ANDROID_AAUDIO)
  return a_audio_;
#else
  return false;
#endif
}

bool AudioManager::IsStereoPlayoutSupported() const {
  RTC_DCHECK(thread_checker_.CalledOnValidThread());
  return (playout_parameters_.channels() == 2);
}

bool AudioManager::IsStereoRecordSupported() const {
  RTC_DCHECK(thread_checker_.CalledOnValidThread());
  return (record_parameters_.channels() == 2);
}

int AudioManager::GetDelayEstimateInMilliseconds() const {
  return delay_estimate_in_milliseconds_;
}

JNI_FUNCTION_ALIGN
void JNICALL AudioManager::CacheAudioParameters(JNIEnv* env,
                                                jobject obj,
                                                jint sample_rate,
                                                jint output_channels,
                                                jint input_channels,
                                                jboolean hardware_aec,
                                                jboolean hardware_agc,
                                                jboolean hardware_ns,
                                                jboolean low_latency_output,
                                                jboolean low_latency_input,
                                                jboolean pro_audio,
                                                jboolean a_audio,
                                                jint output_buffer_size,
                                                jint input_buffer_size,
                                                jlong native_audio_manager) {
  webrtc::AudioManager* this_object =
      reinterpret_cast<webrtc::AudioManager*>(native_audio_manager);
  this_object->OnCacheAudioParameters(
      env, sample_rate, output_channels, input_channels, hardware_aec,
      hardware_agc, hardware_ns, low_latency_output, low_latency_input,
      pro_audio, a_audio, output_buffer_size, input_buffer_size);
}

void AudioManager::OnCacheAudioParameters(JNIEnv* env,
                                          jint sample_rate,
                                          jint output_channels,
                                          jint input_channels,
                                          jboolean hardware_aec,
                                          jboolean hardware_agc,
                                          jboolean hardware_ns,
                                          jboolean low_latency_output,
                                          jboolean low_latency_input,
                                          jboolean pro_audio,
                                          jboolean a_audio,
                                          jint output_buffer_size,
                                          jint input_buffer_size) {
  RTC_LOG(INFO)
      << "OnCacheAudioParameters: "
      << "hardware_aec: " << static_cast<bool>(hardware_aec)
      << ", hardware_agc: " << static_cast<bool>(hardware_agc)
      << ", hardware_ns: " << static_cast<bool>(hardware_ns)
      << ", low_latency_output: " << static_cast<bool>(low_latency_output)
      << ", low_latency_input: " << static_cast<bool>(low_latency_input)
      << ", pro_audio: " << static_cast<bool>(pro_audio)
      << ", a_audio: " << static_cast<bool>(a_audio)
      << ", sample_rate: " << static_cast<int>(sample_rate)
      << ", output_channels: " << static_cast<int>(output_channels)
      << ", input_channels: " << static_cast<int>(input_channels)
      << ", output_buffer_size: " << static_cast<int>(output_buffer_size)
      << ", input_buffer_size: " << static_cast<int>(input_buffer_size);
  RTC_DCHECK(thread_checker_.CalledOnValidThread());
  hardware_aec_ = hardware_aec;
  hardware_agc_ = hardware_agc;
  hardware_ns_ = hardware_ns;
  low_latency_playout_ = low_latency_output;
  low_latency_record_ = low_latency_input;
  pro_audio_ = pro_audio;
  a_audio_ = a_audio;
  playout_parameters_.reset(sample_rate, static_cast<size_t>(output_channels),
                            static_cast<size_t>(output_buffer_size));
  record_parameters_.reset(sample_rate, static_cast<size_t>(input_channels),
                           static_cast<size_t>(input_buffer_size));
}

const AudioParameters& AudioManager::GetPlayoutAudioParameters() {
  RTC_CHECK(playout_parameters_.is_valid());
  RTC_DCHECK(thread_checker_.CalledOnValidThread());
  return playout_parameters_;
}

const AudioParameters& AudioManager::GetRecordAudioParameters() {
  RTC_CHECK(record_parameters_.is_valid());
  RTC_DCHECK(thread_checker_.CalledOnValidThread());
  return record_parameters_;
}

}  // namespace webrtc


text:
<?php

namespace spec\BackupManager\Databases;

use BackupManager\Config\Config;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;

class MysqlDatabaseSpec extends ObjectBehavior {

    function it_is_initializable() {
        $this->shouldHaveType('BackupManager\Databases\MysqlDatabase');
    }

    function it_should_recognize_its_type_with_case_insensitivity() {
        foreach (['mysql', 'MYsql', 'MYSQL'] as $type) {
            $this->handles($type)->shouldBe(true);
        }

        foreach ([null, 'foo'] as $type) {
            $this->handles($type)->shouldBe(false);
        }
    }

    function it_should_generate_a_valid_database_dump_command() {
        $this->configure();
        $this->getDumpCommandLine('outputPath')->shouldBe("mysqldump --routines  --host='foo' --port='3306' --user='bar' --password='baz' 'test' > 'outputPath'");
    }

    function it_should_generate_a_valid_database_dump_command_with_single_transaction() {
        $this->configure('developmentSingleTrans');
        $this->getDumpCommandLine('outputPath')->shouldBe("mysqldump --routines --single-transaction --host='foo' --port='3306' --user='bar' --password='baz' 'test' > 'outputPath'");
    }

    function it_should_generate_a_valid_database_restore_command() {
        $this->configure();
        $this->getRestoreCommandLine('outputPath')->shouldBe("mysql --host='foo' --port='3306' --user='bar' --password='baz'  'test' -e \"source outputPath\"");
    }

    private function configure($db = 'development') {
        $config = Config::fromPhpFile('spec/configs/database.php');
        $this->setConfig($config->get($db));
    }
}

redpajama_set_name: RedPajamaGithub


text:
// Copyright 2014 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.lib.runtime.commands;

import com.google.common.base.Joiner;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.google.common.base.Supplier;
import com.google.common.collect.Iterables;
import com.google.devtools.build.lib.Constants;
import com.google.devtools.build.lib.analysis.BlazeVersionInfo;
import com.google.devtools.build.lib.analysis.config.BuildConfiguration;
import com.google.devtools.build.lib.analysis.config.InvalidConfigurationException;
import com.google.devtools.build.lib.events.Event;
import com.google.devtools.build.lib.packages.Attribute;
import com.google.devtools.build.lib.packages.ProtoUtils;
import com.google.devtools.build.lib.packages.RuleClass;
import com.google.devtools.build.lib.packages.RuleClassProvider;
import com.google.devtools.build.lib.packages.Type;
import com.google.devtools.build.lib.pkgcache.PackageCacheOptions;
import com.google.devtools.build.lib.query2.proto.proto2api.Build.AllowedRuleClassInfo;
import com.google.devtools.build.lib.query2.proto.proto2api.Build.AttributeDefinition;
import com.google.devtools.build.lib.query2.proto.proto2api.Build.BuildLanguage;
import com.google.devtools.build.lib.query2.proto.proto2api.Build.RuleDefinition;
import com.google.devtools.build.lib.runtime.BlazeCommand;
import com.google.devtools.build.lib.runtime.BlazeCommandDispatcher;
import com.google.devtools.build.lib.runtime.BlazeModule;
import com.google.devtools.build.lib.runtime.BlazeRuntime;
import com.google.devtools.build.lib.runtime.Command;
import com.google.devtools.build.lib.util.AbruptExitException;
import com.google.devtools.build.lib.util.ExitCode;
import com.google.devtools.build.lib.util.OsUtils;
import com.google.devtools.build.lib.util.StringUtilities;
import com.google.devtools.build.lib.util.io.OutErr;
import com.google.devtools.common.options.Option;
import com.google.devtools.common.options.OptionsBase;
import com.google.devtools.common.options.OptionsParser;
import com.google.devtools.common.options.OptionsProvider;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.management.GarbageCollectorMXBean;
import java.lang.management.ManagementFactory;
import java.lang.management.MemoryMXBean;
import java.lang.management.MemoryUsage;
import java.nio.charset.StandardCharsets;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

/**
 * Implementation of 'blaze info'.
 */
@Command(name = "info",
         // TODO(bazel-team): this is not really a build command, but needs access to the
         // configuration options to do its job
         builds = true,
         allowResidue = true,
         binaryStdOut = true,
         help = "resource:info.txt",
         shortDescription = "Displays runtime info about the %{product} server.",
         options = { InfoCommand.Options.class },
         completion = "info-key",
         // We have InfoCommand inherit from {@link BuildCommand} because we want all
         // configuration defaults specified in ~/.blazerc for {@code build} to apply to
         // {@code info} too, even though it doesn't actually do a build.
         //
         // (Ideally there would be a way to make {@code info} inherit just the bare
         // minimum of relevant options from {@code build}, i.e. those that affect the
         // values it prints.  But there's no such mechanism.)
         inherits = { BuildCommand.class })
public class InfoCommand implements BlazeCommand {

  public static class Options extends OptionsBase {
    @Option(name = "show_make_env",
            defaultValue = "false",
            category = "misc",
            help = "Include the \"Make\" environment in the output.")
    public boolean showMakeEnvironment;
  }

  /**
   * Unchecked variant of ExitCausingException. Below, we need to throw from the Supplier interface,
   * which does not allow checked exceptions.
   */
  public static class ExitCausingRuntimeException extends RuntimeException {

    private final ExitCode exitCode;

    public ExitCausingRuntimeException(String message, ExitCode exitCode) {
      super(message);
      this.exitCode = exitCode;
    }

    public ExitCausingRuntimeException(ExitCode exitCode) {
      this.exitCode = exitCode;
    }

    public ExitCode getExitCode() {
      return exitCode;
    }
  }

  private static class HardwiredInfoItem implements BlazeModule.InfoItem {
    private final InfoKey key;
    private final BlazeRuntime runtime;
    private final OptionsProvider commandOptions;

    private HardwiredInfoItem(InfoKey key, BlazeRuntime runtime, OptionsProvider commandOptions) {
      this.key = key;
      this.runtime = runtime;
      this.commandOptions = commandOptions;
    }

    @Override
    public String getName() {
      return key.getName();
    }

    @Override
    public String getDescription() {
      return key.getDescription();
    }

    @Override
    public boolean isHidden() {
      return key.isHidden();
    }

    @Override
    public byte[] get(Supplier<BuildConfiguration> configurationSupplier) {
      return print(getInfoItem(runtime, key, configurationSupplier, commandOptions));
    }
  }

  private static class MakeInfoItem implements BlazeModule.InfoItem {
    private final String name;
    private final String value;

    private MakeInfoItem(String name, String value) {
      this.name = name;
      this.value = value;
    }

    @Override
    public String getName() {
      return name;
    }

    @Override
    public String getDescription() {
      return "Make environment variable '" + name + "'";
    }

    @Override
    public boolean isHidden() {
      return false;
    }

    @Override
    public byte[] get(Supplier<BuildConfiguration> configurationSupplier) {
      return print(value);
    }
  }

  @Override
  public void editOptions(BlazeRuntime runtime, OptionsParser optionsParser) { }

  @Override
  public ExitCode exec(final BlazeRuntime runtime, final OptionsProvider optionsProvider) {
    Options infoOptions = optionsProvider.getOptions(Options.class);

    OutErr outErr = runtime.getReporter().getOutErr();
    // Creating a BuildConfiguration is expensive and often unnecessary. Delay the creation until
    // it is needed.
    Supplier<BuildConfiguration> configurationSupplier = new Supplier<BuildConfiguration>() {
      private BuildConfiguration configuration;
      @Override
      public BuildConfiguration get() {
        if (configuration != null) {
          return configuration;
        }
        try {
          // In order to be able to answer configuration-specific queries, we need to setup the
          // package path. Since info inherits all the build options, all the necessary information
          // is available here.
          runtime.setupPackageCache(
              optionsProvider.getOptions(PackageCacheOptions.class),
              runtime.getDefaultsPackageContent(optionsProvider));
          // TODO(bazel-team): What if there are multiple configurations? [multi-config]
          configuration = runtime
              .getConfigurations(optionsProvider)
              .getTargetConfigurations().get(0);
          return configuration;
        } catch (InvalidConfigurationException e) {
          runtime.getReporter().handle(Event.error(e.getMessage()));
          throw new ExitCausingRuntimeException(ExitCode.COMMAND_LINE_ERROR);
        } catch (AbruptExitException e) {
          throw new ExitCausingRuntimeException("unknown error: " + e.getMessage(),
              e.getExitCode());
        } catch (InterruptedException e) {
          runtime.getReporter().handle(Event.error("interrupted"));
          throw new ExitCausingRuntimeException(ExitCode.INTERRUPTED);
        }
      }
    };

    Map<String, BlazeModule.InfoItem> items = getInfoItemMap(runtime, optionsProvider);

    try {
      if (infoOptions.showMakeEnvironment) {
        Map<String, String> makeEnv = configurationSupplier.get().getMakeEnvironment();
        for (Map.Entry<String, String> entry : makeEnv.entrySet()) {
          BlazeModule.InfoItem item = new MakeInfoItem(entry.getKey(), entry.getValue());
          items.put(item.getName(), item);
        }
      }

      List<String> residue = optionsProvider.getResidue();
      if (residue.size() > 1) {
        runtime.getReporter().handle(Event.error("at most one key may be specified"));
        return ExitCode.COMMAND_LINE_ERROR;
      }

      String key = residue.size() == 1 ? residue.get(0) : null;
      if (key != null) { // print just the value for the specified key:
        byte[] value;
        if (items.containsKey(key)) {
          value = items.get(key).get(configurationSupplier);
        } else {
          runtime.getReporter().handle(Event.error("unknown key: '" + key + "'"));
          return ExitCode.COMMAND_LINE_ERROR;
        }
        try {
          outErr.getOutputStream().write(value);
          outErr.getOutputStream().flush();
        } catch (IOException e) {
          runtime.getReporter().handle(Event.error("Cannot write info block: " + e.getMessage()));
          return ExitCode.ANALYSIS_FAILURE;
        }
      } else { // print them all
        configurationSupplier.get();  // We'll need this later anyway
        for (BlazeModule.InfoItem infoItem : items.values()) {
          if (infoItem.isHidden()) {
            continue;
          }
          outErr.getOutputStream().write(
              (infoItem.getName() + ": ").getBytes(StandardCharsets.UTF_8));
          outErr.getOutputStream().write(infoItem.get(configurationSupplier));
        }
      }
    } catch (AbruptExitException e) {
      return e.getExitCode();
    } catch (ExitCausingRuntimeException e) {
      return e.getExitCode();
    } catch (IOException e) {
      return ExitCode.LOCAL_ENVIRONMENTAL_ERROR;
    }
    return ExitCode.SUCCESS;
  }

  /**
   * Compute and return the info for the given key. Only keys that are not hidden are supported
   * here.
   */
  private static Object getInfoItem(BlazeRuntime runtime, InfoKey key,
      Supplier<BuildConfiguration> configurationSupplier, OptionsProvider options) {
    switch (key) {
      // directories
      case WORKSPACE : return runtime.getWorkspace();
      case INSTALL_BASE : return runtime.getDirectories().getInstallBase();
      case OUTPUT_BASE : return runtime.getOutputBase();
      case EXECUTION_ROOT : return runtime.getExecRoot();
      case OUTPUT_PATH : return runtime.getDirectories().getOutputPath();
      // These are the only (non-hidden) info items that require a configuration, because the
      // corresponding paths contain the short name. Maybe we should recommend using the symlinks
      // or make them hidden by default?
      case BLAZE_BIN : return configurationSupplier.get().getBinDirectory().getPath();
      case BLAZE_GENFILES : return configurationSupplier.get().getGenfilesDirectory().getPath();
      case BLAZE_TESTLOGS : return configurationSupplier.get().getTestLogsDirectory().getPath();

      // logs
      case COMMAND_LOG : return BlazeCommandDispatcher.getCommandLogPath(runtime.getOutputBase());
      case MESSAGE_LOG :
        // NB: Duplicated in EventLogModule
        return runtime.getOutputBase().getRelative("message.log");

      // misc
      case RELEASE : return BlazeVersionInfo.instance().getReleaseName();
      case SERVER_PID : return OsUtils.getpid();
      case PACKAGE_PATH : return getPackagePath(options);

      // memory statistics
      case GC_COUNT :
      case GC_TIME :
        // The documentation is not very clear on what it means to have more than
        // one GC MXBean, so we just sum them up.
        int gcCount = 0;
        int gcTime = 0;
        for (GarbageCollectorMXBean gcBean : ManagementFactory.getGarbageCollectorMXBeans()) {
          gcCount += gcBean.getCollectionCount();
          gcTime += gcBean.getCollectionTime();
        }
        if (key == InfoKey.GC_COUNT) {
          return gcCount + "";
        } else {
          return gcTime + "ms";
        }

      case MAX_HEAP_SIZE :
        return StringUtilities.prettyPrintBytes(getMemoryUsage().getMax());
      case USED_HEAP_SIZE :
      case COMMITTED_HEAP_SIZE :
        return StringUtilities.prettyPrintBytes(key == InfoKey.USED_HEAP_SIZE ?
            getMemoryUsage().getUsed() : getMemoryUsage().getCommitted());

      case USED_HEAP_SIZE_AFTER_GC :
        // Note that this info value is not printed by default, but only when explicitly requested.
        System.gc();
        return StringUtilities.prettyPrintBytes(getMemoryUsage().getUsed());

      case DEFAULTS_PACKAGE:
        return runtime.getDefaultsPackageContent();

      case BUILD_LANGUAGE:
        return getBuildLanguageDefinition(runtime.getRuleClassProvider());

      case DEFAULT_PACKAGE_PATH:
        return Joiner.on(":").join(Constants.DEFAULT_PACKAGE_PATH);

      default:
        throw new IllegalArgumentException("missing implementation for " + key);
    }
  }

  private static MemoryUsage getMemoryUsage() {
    MemoryMXBean memBean = ManagementFactory.getMemoryMXBean();
    return memBean.getHeapMemoryUsage();
  }

  /**
   * Get the package_path variable for the given set of options.
   */
  private static String getPackagePath(OptionsProvider options) {
    PackageCacheOptions packageCacheOptions =
        options.getOptions(PackageCacheOptions.class);
    return Joiner.on(":").join(packageCacheOptions.packagePath);
  }

  private static AllowedRuleClassInfo getAllowedRuleClasses(
      Collection<RuleClass> ruleClasses, Attribute attr) {
    AllowedRuleClassInfo.Builder info = AllowedRuleClassInfo.newBuilder();
    info.setPolicy(AllowedRuleClassInfo.AllowedRuleClasses.ANY);

    if (attr.isStrictLabelCheckingEnabled()) {
      if (attr.getAllowedRuleClassesPredicate() != Predicates.<RuleClass>alwaysTrue()) {
        info.setPolicy(AllowedRuleClassInfo.AllowedRuleClasses.SPECIFIED);
        Predicate<RuleClass> filter = attr.getAllowedRuleClassesPredicate();
        for (RuleClass otherClass : Iterables.filter(
            ruleClasses, filter)) {
          if (otherClass.isDocumented()) {
            info.addAllowedRuleClass(otherClass.getName());
          }
        }
      }
    }

    return info.build();
  }

  /**
   * Returns a byte array containing a proto-buffer describing the build language.
   */
  private static byte[] getBuildLanguageDefinition(RuleClassProvider provider) {
    BuildLanguage.Builder resultPb = BuildLanguage.newBuilder();
    Collection<RuleClass> ruleClasses = provider.getRuleClassMap().values();
    for (RuleClass ruleClass : ruleClasses) {
      if (!ruleClass.isDocumented()) {
        continue;
      }

      RuleDefinition.Builder rulePb = RuleDefinition.newBuilder();
      rulePb.setName(ruleClass.getName());
      for (Attribute attr : ruleClass.getAttributes()) {
        if (!attr.isDocumented()) {
          continue;
        }

        AttributeDefinition.Builder attrPb = AttributeDefinition.newBuilder();
        attrPb.setName(attr.getName());
        // The protocol compiler, in its infinite wisdom, generates the field as one of the
        // integer type and the getTypeEnum() method is missing. WTF?
        attrPb.setType(ProtoUtils.getDiscriminatorFromType(attr.getType()));
        attrPb.setMandatory(attr.isMandatory());

        if (Type.isLabelType(attr.getType())) {
          attrPb.setAllowedRuleClasses(getAllowedRuleClasses(ruleClasses, attr));
        }

        rulePb.addAttribute(attrPb);
      }

      resultPb.addRule(rulePb);
    }

    return resultPb.build().toByteArray();
  }

  private static byte[] print(Object value) {
    if (value instanceof byte[]) {
      return (byte[]) value;
    }
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    PrintWriter writer = new PrintWriter(outputStream);
    writer.print(value + "\n");
    writer.flush();
    return outputStream.toByteArray();
  }

  static Map<String, BlazeModule.InfoItem> getInfoItemMap(
      BlazeRuntime runtime, OptionsProvider commandOptions) {
    Map<String, BlazeModule.InfoItem> result = new TreeMap<>();  // order by key
    for (BlazeModule module : runtime.getBlazeModules()) {
      for (BlazeModule.InfoItem item : module.getInfoItems()) {
        result.put(item.getName(), item);
      }
    }

    for (InfoKey key : InfoKey.values()) {
      BlazeModule.InfoItem item = new HardwiredInfoItem(key, runtime, commandOptions);
      result.put(item.getName(), item);
    }

    return result;
  }
}


text:
@interface CHMailServerTableViewController : UITableViewController

@end


text:
package storable

import (
	"errors"

	"gopkg.in/mgo.v2"
)

var (
	//ErrResultSetClosed is throwed when you are working over a closed ResultSet
	ErrResultSetClosed = errors.New("closed resultset")
	//ErrNotFound document not found
	ErrNotFound = errors.New("document not found")
	// ErrStop if is used on a callback of a ResultSet.ForEach function the loop
	// is stopped
	ErrStop = errors.New("document not found")
)

// ResultSet contains the result of an executed query command.
type ResultSet struct {
	IsClosed bool
	session  *mgo.Session
	mgoQuery *mgo.Query
	mgoIter  *mgo.Iter
}

// Count returns the total number of documents in the ResultSet. Count DON'T
// close the ResultSet after be called.
func (r *ResultSet) Count() (int, error) {
	return r.mgoQuery.Count()
}

// All returns all the documents in the ResultSet and close it. Dont use it
// with large results.
func (r *ResultSet) All(result interface{}) error {
	defer r.Close()
	return r.mgoQuery.All(result)
}

// One return a document from the ResultSet and close it, the following calls
// to One returns ErrResultSetClosed error. If a document is not returned the
// error ErrNotFound is retuned.
func (r *ResultSet) One(doc interface{}) error {
	defer r.Close()
	found, err := r.Next(doc)
	if err != nil {
		return err
	}

	if !found {
		return ErrNotFound
	}

	return nil
}

// Next return a document from the ResultSet, can be called multiple times.
func (r *ResultSet) Next(doc interface{}) (bool, error) {
	if r.mgoIter == nil {
		r.mgoIter = r.mgoQuery.Iter()
	}

	returned := r.mgoIter.Next(doc)
	if !returned {
		r.Close()
	}

	return returned, r.mgoIter.Err()
}

// Close close the ResultSet closing the internal iter.
func (r *ResultSet) Close() error {
	if r.IsClosed {
		return ErrResultSetClosed
	}

	defer func() {
		r.session.Close()
		r.IsClosed = true
	}()

	if r.mgoIter == nil {
		return nil
	}

	return r.mgoIter.Close()
}


text:
/*!
{
  "name": "ES6 Number",
  "property": "es6number",
  "notes": [{
    "name": "ECMAScript 6 specification",
    "href": "https://www.ecma-international.org/ecma-262/6.0/index.html"
  }, {
    "name": "Last ECMAScript specification",
    "href": "https://www.ecma-international.org/ecma-262/index.html"
  }],
  "polyfills": ["es6shim"],
  "authors": ["Ron Waldon (@jokeyrhyme)"],
  "tags": ["es6"]
}
!*/
/* DOC
Check if browser implements ECMAScript 6 Number per specification.
*/
define(['Modernizr'], function(Modernizr) {
  Modernizr.addTest('es6number', !!(Number.isFinite &&
    Number.isInteger &&
    Number.isSafeInteger &&
    Number.isNaN &&
    Number.parseInt &&
    Number.parseFloat &&
    Number.isInteger(Number.MAX_SAFE_INTEGER) &&
    Number.isInteger(Number.MIN_SAFE_INTEGER) &&
    Number.isFinite(Number.EPSILON)));
});


text:
package lin.leila.week2_nytimesearch.activities;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import lin.leila.week2_nytimesearch.Article;
import lin.leila.week2_nytimesearch.R;

public class ArticleActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_article);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        Article article = (Article) getIntent().getSerializableExtra("article");

        WebView webView = (WebView) findViewById(R.id.wvArticle);

        webView.setWebViewClient(new WebViewClient() {
                                     @Override
                                     public boolean shouldOverrideUrlLoading(WebView view, String url) {
                                        view.loadUrl(url);
                                        return true;
                                     }
                                }
        );
        webView.loadUrl(article.getWebUrl());
    }

}


text:
package p2p

import (
	"context"

	"github.com/goharbor/harbor/src/controller/tag"

	"github.com/goharbor/harbor/src/controller/artifact"
	"github.com/goharbor/harbor/src/controller/artifact/processor/image"
	"github.com/goharbor/harbor/src/controller/event"
	"github.com/goharbor/harbor/src/controller/p2p/preheat"
	"github.com/goharbor/harbor/src/lib/errors"
	"github.com/goharbor/harbor/src/lib/log"
)

// Handler ...
type Handler struct {
}

// Name ...
func (p *Handler) Name() string {
	return "P2PPreheat"
}

// Handle ...
func (p *Handler) Handle(ctx context.Context, value interface{}) error {
	switch value.(type) {
	case *event.PushArtifactEvent:
		pushArtEvent, _ := value.(*event.PushArtifactEvent)
		return p.handlePushArtifact(ctx, pushArtEvent)
	case *event.ScanImageEvent:
		scanImageEvent, _ := value.(*event.ScanImageEvent)
		return p.handleImageScanned(ctx, scanImageEvent)
	case *event.ArtifactLabeledEvent:
		artifactLabeledEvent, _ := value.(*event.ArtifactLabeledEvent)
		return p.handleArtifactLabeled(ctx, artifactLabeledEvent)
	default:
		return errors.New("unsupported type")
	}
}

// IsStateful ...
func (p *Handler) IsStateful() bool {
	return false
}

func (p *Handler) handlePushArtifact(ctx context.Context, event *event.PushArtifactEvent) error {
	if event.Artifact.Type != image.ArtifactTypeImage {
		return nil
	}

	// NOTES: So far, we only support artifact with tags
	if len(event.Tags) == 0 {
		return nil
	}

	log.Debugf("preheat: artifact pushed %s:%s@%s", event.Artifact.RepositoryName, event.Tags, event.Artifact.Digest)

	art, err := artifact.Ctl.Get(ctx, event.Artifact.ID, &artifact.Option{
		WithTag:   true,
		WithLabel: true,
	})
	if err != nil {
		return err
	}

	// Only with the pushed tags, ignore other tags
	pt := make([]*tag.Tag, 0)
	for _, tg := range art.Tags {
		if tg.Name == event.Tags[0] {
			pt = append(pt, tg)
			break
		}
	}
	art.Tags = pt

	_, err = preheat.Enf.PreheatArtifact(ctx, art)
	return err
}

func (p *Handler) handleImageScanned(ctx context.Context, event *event.ScanImageEvent) error {
	// TODO: If the scan is targeting an manifest list, here the artifacts we get are all the children
	//  artifacts of the manifest list. The children artifacts are high probably untagged ones that
	//  will be definitely ignored by the tag filter. We need to find a way to resolve this issue.
	log.Debugf("preheat: image scanned %s:%s", event.Artifact.Repository, event.Artifact.Tag)
	art, err := artifact.Ctl.GetByReference(ctx, event.Artifact.Repository, event.Artifact.Digest,
		&artifact.Option{
			WithTag:   true,
			WithLabel: true,
		})
	if err != nil {
		return err
	}
	_, err = preheat.Enf.PreheatArtifact(ctx, art)
	return err
}

func (p *Handler) handleArtifactLabeled(ctx context.Context, event *event.ArtifactLabeledEvent) error {
	art, err := artifact.Ctl.Get(ctx, event.ArtifactID, &artifact.Option{
		WithTag:   true,
		WithLabel: true,
	})

	if err != nil {
		return err
	}

	// Only care image at this moment
	if art.Type != image.ArtifactTypeImage {
		return nil
	}
	log.Debugf("preheat: artifact labeled %s:%s", art.Artifact.RepositoryName, art.Artifact.Digest)

	_, err = preheat.Enf.PreheatArtifact(ctx, art)
	return err
}


text:
"""
Created on Tue Oct 20 17:40:07 2015

@author: casimp
"""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals

import os
import warnings
import sys
import h5py
import numpy as np
import scipy.io as io

try:
    import fabio
    import pyFAI
    import pyFAI.azimuthalIntegrator
except ModuleNotFoundError:
    warnings.warn(
        "fabIO/pyFAI not installed. Azimuthal Integration not possible within"
        "pyxe.",
        ImportWarning,
    )

from pyxe.data_io import dim_fill, extract_fnames, dimension_fill_pixium10
from pyxe.peak_analysis import PeakAnalysis
from pyxpb.detectors import MonoDetector

class Pilatus(MonoDetector):
    def __init__(self, sample_detector=1000, energy=80, delta_energy=0.1):
        """ Creates instance of Pilatus 2M (area) XRD detector.

        Inherits from pyxpb Rings/Peaks classes, allowing for the
        calculation/estimation and visualisation of intensity profiles and
        Debye-Scherrer rings for materials or combinations of materials/phases.

        Args:
            sample_detector (float): Sample to detector distance (mm).
            energy (float): X-ray energy (keV)
            delta_energy (float): Energy spread i.e. 80keV +- 0.1
        """
        MonoDetector.__init__(self, shape=(1475, 1679), pixel_size=0.172,
                              sample_detector=sample_detector, energy=energy,
                              delta_energy=delta_energy)

class Pixium(MonoDetector):
    def __init__(self, sample_detector=1000, energy=80, delta_energy=0.1):
        """ Creates instance of Pixium RF4343 (area) XRD detector.

        Inherits from pyxpb Rings/Peaks classes, allowing for the
        calculation/estimation and visualisation of intensity profiles and
        Debye-Scherrer rings for materials or combinations of materials/phases.

        Args:
            sample_detector (float): Sample to detector distance (mm).
            energy (float): X-ray energy (keV)
            delta_energy (float): Energy spread i.e. 80keV +- 0.1
        """
        MonoDetector.__init__(self, shape=(2880, 2881), pixel_size=0.148,
                              sample_detector=sample_detector, energy=energy,
                              delta_energy=delta_energy)

detectors = {'Pilatus': Pilatus,
             'Pixium': Pixium}

# DLS Classes

class MonoDLS(PeakAnalysis):

    def __init__(self, fpath,
                 d1='entry/result/ss1_x',
                 d2='entry/result/ss1_y', d3=None,
                 q='entry/result/q',
                 I='entry/result/data',
                 phi='entry/result/azimuthal angle (degrees)',
                 detector=('Pilatus', 1000, 80, 0.1)):

        """ Extract data from pre-processed .nxs/.h5 file.

        Analysis of pre-processed (azimuthally integrated) data from the DLS
        (I12). Should re-arrange and scrape pre-processed data to correct form.

        Args:
            fpath (str): Path to processed datafile (.nxs)
            d1, d2, d3 (str): Path within .nxs file to co-ords
            q, I, phi (str): Path within .nxs file to q, intensity and phi
            detector (tuple, object): pyxpb detector object or dict of detectors
                name and parameters - currently on works for 'Pixium' and
                'Pilatus' detectors (name, sample_detector, energy,
                energy_resolution). If a value is set to None defaults are used.
        """
        self.fpath = fpath
        f = h5py.File(fpath, 'r')

        self.d1 = f[d1][()]
        self.d2 = None if d2 == None else f[d2][()]
        self.d3 = None if d3 == None else f[d3][()]
        self.ndim = sum(x is not None for x in [self.d1, self.d2, self.d3])

        q = f[q][()]
        self.I = f[I][()]
        self.phi = np.pi * f[phi][()] / 180
        self.q = np.repeat(q[None, :], self.phi.size, axis=0)
        self.analysis_state = 'integrated'
        try:
            if isinstance(detector, tuple):
                default = ('Pilatus', 1000, 80, 0.1)
                detector = [i if i is not None else j for i, j in zip(detector, default)]
                self.detector = detectors[detector[0]](*detector[1:])
            else:
                self.detector = detector
        except:
            print('Invalid detector parameters/object, reverting to default')
            self.detector = Pilatus()

class MonoDLS_re(PeakAnalysis):

    def __init__(self, fpath, rpath,
                 d1='entry/result/ss1_x',
                 d2='entry/result/ss1_y', d3=None,
                 q='entry/result/q',
                 I='entry/result/data',
                 phi='entry/result/azimuthal angle (degrees)',
                 detector=('Pilatus', 1000, 80, 0.1)):

        """ Extract intensity profiles from caked data file and the positions
        and parameters from the initial raw data file.

        Analysis of pre-processed (azimuthally integrated) data from the I12
        beamline. Should re-arrange and scrape pre-processed
        data to correct form.

        Args:
            fpath (str): Path to processed datafile (.nxs/.h5)
            rpath (str): Path to raw datafile (.nxs/.h5)
            detector (tuple, object): pyxpb detector object or dict of detectors
                name and parameters - currently on works for 'Pixium' and
                'Pilatus' detectors (name, sample_detector, energy,
                energy_resolution). If a value is set to None defaults are used.
        """
        self.fpath = fpath
        f = h5py.File(fpath, 'r')
        raw = h5py.File(rpath, 'r')

        # Extract position data from raw data file
        self.d1 = raw[d1][()]
        self.d2 = None if d2 == None else raw[d2][()]
        self.d3 = None if d3 == None else raw[d3][()]
        self.ndim = sum(x is not None for x in [self.d1, self.d2, self.d3])

        # Extract processed data from processed file
        q = f[q][()]
        self.I = f[I][()]
        self.phi = np.pi * f[phi][()] / 180
        self.q = np.repeat(q[None, :], self.phi.size, axis=0)
        self.analysis_state = 'integrated'

        # Initiate with Pilatus if no detector is specified
        try:
            if isinstance(detector, dict):
                default = ('Pilatus', 1000, 80, 0.1)
                detector = [i if i is not None else j for i, j in zip(detector, default)]
                name, sample_detector, energy, delta_energy = detector
                self.detector = detectors[detector[0]](*detector[1:])
            else:
                self.detector = detector
        except:
            print('Invalid detector parameters/object, reverting to default')
            self.detector = Pilatus()

# ESRF Classes

def import_from_mat(fpath):
    mat = io.loadmat(fpath, squeeze_me=True)

    counts,unc,exposure,epoch,samplez,sampley,mondio,fnames = [],[],[],[],[],[],[],[]
    for scan in range(len(mat['w'])):
        try:
            q = mat['w'][scan][()][0]
            _counts = mat['w'][scan][()][1]
            _unc = mat['w'][scan][()][2] #error on pixel?
            _exposure = mat['w'][scan][()][3]
            _epoch = mat['w'][scan][()][4]
            _laserz = mat['w'][scan][()][5] #z laser-sample separation - not varied
            _samplez = mat['w'][scan][()][6]
            #_samplez = mat['w'][scan][()][7] #ignore, same as above
            _sampley = mat['w'][scan][()][8] #pp01
            _fnames = mat['w'][scan][()][9]
            _mondio = mat['w'][scan][()][10] #region of interest on
        except:
            pass
            #print('Could not get scan %i'%scan)
        else:
            counts.append(_counts)
            unc.append(_unc)
            exposure.append(_exposure)
            epoch.append(_epoch)
            samplez.append(_samplez)
            sampley.append(_sampley)
            mondio.append(_mondio)
            fnames.append(_fnames)

    counts = np.dstack(counts)
    counts = np.swapaxes(counts, 0, 2)
    unc = np.dstack(unc)
    unc = np.swapaxes(unc, 0, 2)
    exposure = np.hstack(exposure)
    epoch = np.hstack(epoch)
    samplez = np.hstack(samplez)
    sampley = np.hstack(sampley)
    mondio = np.hstack(mondio)
    fnames = np.hstack(fnames)
    del mat

    return dict(q=q,counts=counts,unc=unc,exposure=exposure,epoch=epoch,
                samplez=samplez,sampley=sampley,mondio=mondio,fnames=fnames)

class MonoESRF_mat(PeakAnalysis):

    def __init__(self, fpath, detector=None):
        data = import_from_mat(fpath)
        self.ndim = 2
        self.d1, self. d2, self.d3 = data['samplez'], data['sampley'], None
        self.T = None
        q, self.I = data['q'], data['counts']
        self.phi = np.linspace(-np.pi, np.pi, 36)
        self.q = np.repeat(q[None, :], self.phi.size, axis=0)

        self.analysis_state = 'integrated'

        # Initiate with Pilatus if no detector is specified
        try:
            if isinstance(detector, dict):
                default = ('Pilatus', 1000, 80, 0.1)
                detector = [i if i is not None else j for i, j in zip(detector, default)]
                name, sample_detector, energy, delta_energy = detector
                self.detector = detectors[detector[0]](*detector[1:])
            else:
                self.detector = detector
        except:
            print('Invalid detector parameters/object, reverting to default')
            self.detector = Pilatus()

## Built in azimuthal integration (not recommended)

class MonoPyFAI(PeakAnalysis):

    def __init__(self, folder, co_ords, detector=('Pilatus', 1000, 80, 0.1),
                 wavelength=None, f_ext='.edf', progress=True, npt_rad=1024,
                 npt_az=36, az_range=(-180, 180)):
        """
        Takes a folder containing image files from area detectors and cakes
        the data while associating it with spatial information. The caked data
        can then be analysed (peak_fit/strain calculations).

        Args:
            folder (str): Folder containing the image files for analysis
            co_ords (ndarray): 1D/2D/3D numpy array containing data co-ords
            detector (tuple, object): pyxpb detector object or dict of detectors
                name and parameters - currently on works for 'Pixium' and
                'Pilatus' detectors (name, sample_detector, energy,
                energy_resolution). If a value is set to None defaults are used.
            wavelength (float): Wavelength (nm) (if not defined in pyFAI file)
            f_ext (str): File extension of image files
            progress (bool): Live progress bar
            npt_rad (int): Number of radial bins (approx. half detect width)
            npt_az (int): Number of azimuthal wedges
            az_range (tuple): Azimtuhal range (deg) - default (-180, 180).
                Note that the 0deg is at eastern edge of circle.
        """

        warnings.warn(
            "pyFAI has been upgrading, deprecating certain functions and "
            "likely breaking this class. Testing has been removed.",
            DeprecationWarning
        )

        fname = '{}.h5'.format(os.path.split(folder)[1])
        self.fpath = os.path.join(folder, fname)

        error = 'Azimuthal range must be less than or equal to 360deg'
        assert abs(np.max(az_range) - np.min(az_range)) <= 360, error

        # Allow for use of pyFAI or Fit2D detector params
        # Currently checking if folder string - perhaps not the best method!

        if isinstance(detector, pyFAI.azimuthalIntegrator.AzimuthalIntegrator):
            ai = detector
            if wavelength is None:
                ai.get_wavelength()
            else:
                ai.set_wavelength(wavelength)
        else:
            ai = pyFAI.azimuthalIntegrator.AzimuthalIntegrator()
            ai.setFit2D(*detector)
            ai.set_wavelength(wavelength)
        fnames = extract_fnames(folder, f_ext)

        error = ('Number of positions not equal to number of files (pos = %s,'
                 ' files = %s)' % (co_ords.shape[0], len(fnames)))
        assert co_ords.shape[0] == len(fnames), error
        (self.d1, self.d2, self.d3), self.dims = dim_fill(co_ords)
        self.T = None
        self.ndim = len(self.dims)
        self.I = np.nan * np.ones((co_ords.shape[0], npt_az, npt_rad))

        print('\nLoading files and carrying out azimuthal integration:\n')
        for fidx, fname in enumerate(fnames):
            img = fabio.open(os.path.join(folder, fname)).data
            npt_rad, npt_az = int(npt_rad), int(npt_az)
            I, q_, phi = ai.integrate2d(img, npt_rad=npt_rad, npt_azim=npt_az,
                                        azimuth_range=az_range, unit='q_A^-1')
            self.I[fidx] = I
            if progress:
                sys.stdout.write('\rProgress: [{0:20s}] {1:.0f}%'.format('#' *
                                 int(20*(fidx + 1) / len(fnames)),
                                 100*((fidx + 1)/len(fnames))))
                sys.stdout.flush()

        # Create az_slice 'specific' q values - to work with edxd data
        self.q = np.repeat(q_[None, :], npt_az, axis=0)
        self.phi = phi * np.pi / 180
        self.analysis_state = 'integrated'
        # Should really extract from ai not pyxpb...
        try:
            if isinstance(detector, dict):
                default = ('Pilatus', 1000, 80, 0.1)
                detector = [i if i is not None else j for i, j in zip(detector, default)]
                name, sample_detector, energy, delta_energy = detector
                self.detector = detectors[detector[0]](*detector[1:])
            else:
                self.detector = detector
        except:
            print('Invalid detector parameters/object, reverting to default')
            self.detector = Pilatus()


text:
cat /vagrant/files/vagrant_cluster/hosts > /etc/hosts

# passwordless SSH
cp /vagrant/files/vagrant_cluster/{id_rsa,id_rsa.pub} /home/vagrant/.ssh/
chmod 600 /home/vagrant/.ssh/id_rsa
chown vagrant:vagrant /home/vagrant/.ssh/{id_rsa,id_rsa.pub}
cat /home/vagrant/.ssh/id_rsa.pub >> /home/vagrant/.ssh/authorized_keys

# packages
packages=("bc" "dsh" "sysstat" "wamerican" "build-essential" "curl" "default-jdk" "unzip")
apt-get update
for package in "${packages[@]}"; do
	if ! which $package > /dev/null; then
	  apt-get install $package -y --force-yes
	fi
done

# folders
mkdir -p /scratch/local
chmod 777 /scratch/local
su vagrant <<EOF
mkdir -p /vagrant/workspace/blobs/share
ln -s -f -n /vagrant/workspace/blobs/share /home/vagrant/share
ln -s -f -n /vagrant/workspace /home/vagrant/workspace
EOF

# download external files
su vagrant <<EOF
if [ ! -f /vagrant/workspace/blobs/aplic.tar.bz2 ]; then
	wget -nv -O /vagrant/workspace/blobs/aplic.tar.bz2 http://aloja.bsc.es/public/aplic.tar.bz2
fi
if [ ! -d /vagrant/workspace/blobs/share/aplic ]; then
	tar -xf /vagrant/workspace/blobs/aplic.tar.bz2 -C /vagrant/workspace/blobs/share
fi
EOF


text:
class Script
  include Setup::CenitUnscoped

  build_in_data_type.on_origin(:admin).and(properties: {
    code: {
      contentMediaType: 'text/x-ruby'
    }
  })

  deny :all

  field :name, type: String
  field :description, type: String
  field :code, type: String

  validates_presence_of :name, :description

  before_save do
    errors.add(:code, "can't be blank") if code.blank?
    abort_if_has_errors
  end

  def parameters
    []
  end

  def run(task)
    task.instance_eval(code)
  end
end


text:
from PySide2.QtWidgets import QTreeView, QVBoxLayout, QWidget
from PySide2.QtCore import Qt, QAbstractItemModel, QModelIndex, QSize
from binaryninja.enums import SymbolType, SymbolBinding
import binaryninjaui
from binaryninjaui import ViewFrame, FilterTarget, FilteredView, UIContext, UIActionHandler

class GenericExportsModel(QAbstractItemModel):
	def __init__(self, data):
		super(GenericExportsModel, self).__init__()
		self.allEntries = []
		self.addr_col = 0
		self.name_col = 1
		self.ordinal_col = None
		self.total_cols = 2
		self.sortCol = 0
		self.sortOrder = Qt.AscendingOrder
		for sym in data.get_symbols_of_type(SymbolType.FunctionSymbol):
			if sym.binding == SymbolBinding.GlobalBinding:
				self.allEntries.append(sym)
		for sym in data.get_symbols_of_type(SymbolType.DataSymbol):
			if sym.binding == SymbolBinding.GlobalBinding:
				self.allEntries.append(sym)
		if data.view_type == "PE":
			self.ordinal_col = 0
			self.addr_col = 1
			self.name_col = 2
			self.total_cols = 3
		self.entries = list(self.allEntries)

	def columnCount(self, parent):
		return self.total_cols

	def rowCount(self, parent):
		if parent.isValid():
			return 0
		return len(self.entries)

	def data(self, index, role):
		if role != Qt.DisplayRole:
			return None
		if index.row() >= len(self.entries):
			return None
		if index.column() == self.addr_col:
			return "0x%x" % self.entries[index.row()].address
		if index.column() == self.name_col:
			return self.entries[index.row()].full_name
		if index.column() == self.ordinal_col:
			return str(self.entries[index.row()].ordinal)
		return None

	def headerData(self, section, orientation, role):
		if orientation == Qt.Vertical:
			return None
		if role != Qt.DisplayRole:
			return None
		if section == self.addr_col:
			return "Address"
		if section == self.name_col:
			return "Name"
		if section == self.ordinal_col:
			return "Ordinal"
		return None

	def index(self, row, col, parent):
		if parent.isValid():
			return QModelIndex()
		if row >= len(self.entries):
			return QModelIndex()
		if col >= self.total_cols:
			return QModelIndex()
		return self.createIndex(row, col)

	def parent(self, index):
		return QModelIndex()

	def getSymbol(self, index):
		if index.row() >= len(self.entries):
			return None
		return self.entries[index.row()]

	def performSort(self, col, order):
		if col == self.addr_col:
			self.entries.sort(key = lambda sym: sym.address, reverse = order != Qt.AscendingOrder)
		elif col == self.name_col:
			self.entries.sort(key = lambda sym: sym.full_name, reverse = order != Qt.AscendingOrder)
		elif col == self.ordinal_col:
			self.entries.sort(key = lambda sym: sym.ordinal, reverse = order != Qt.AscendingOrder)

	def sort(self, col, order):
		self.beginResetModel()
		self.sortCol = col
		self.sortOrder = order
		self.performSort(col, order)
		self.endResetModel()

	def setFilter(self, filterText):
		self.beginResetModel()
		self.entries = []
		for entry in self.allEntries:
			if FilteredView.match(entry.full_name, filterText):
				self.entries.append(entry)
		self.performSort(self.sortCol, self.sortOrder)
		self.endResetModel()

class ExportsTreeView(QTreeView, FilterTarget):
	def __init__(self, parent, view, data):
		QTreeView.__init__(self, parent)
		FilterTarget.__init__(self)
		self.data = data
		self.parent = parent
		self.view = view

		# Allow view-specific shortcuts when exports are focused
		self.actionHandler = UIActionHandler()
		self.actionHandler.setupActionHandler(self)
		self.actionHandler.setActionContext(lambda: self.view.actionContext())

		self.model = GenericExportsModel(self.data)
		self.setModel(self.model)
		self.setRootIsDecorated(False)
		self.setUniformRowHeights(True)
		self.setSortingEnabled(True)
		self.sortByColumn(0, Qt.AscendingOrder)
		if self.model.ordinal_col is not None:
			self.setColumnWidth(self.model.ordinal_col, 55)

		self.setFont(binaryninjaui.getMonospaceFont(self))

		self.selectionModel().currentChanged.connect(self.exportSelected)
		self.doubleClicked.connect(self.exportDoubleClicked)

	def exportSelected(self, cur, prev):
		sym = self.model.getSymbol(cur)
		if sym is not None:
			self.view.setCurrentOffset(sym.address)

	def exportDoubleClicked(self, cur):
		sym = self.model.getSymbol(cur)
		if sym is not None:
			viewFrame = ViewFrame.viewFrameForWidget(self)
			if len(self.data.get_functions_at(sym.address)) > 0:
				viewFrame.navigate("Graph:" + viewFrame.getCurrentDataType(), sym.address)
			else:
				viewFrame.navigate("Linear:" + viewFrame.getCurrentDataType(), sym.address)

	def setFilter(self, filterText):
		self.model.setFilter(filterText)

	def scrollToFirstItem(self):
		self.scrollToTop()

	def scrollToCurrentItem(self):
		self.scrollTo(self.currentIndex())

	def selectFirstItem(self):
		self.setCurrentIndex(self.model.index(0, 0, QModelIndex()))

	def activateFirstItem(self):
		self.exportDoubleClicked(self.model.index(0, 0, QModelIndex()))

	def closeFilter(self):
		self.setFocus(Qt.OtherFocusReason)

	def keyPressEvent(self, event):
		if (len(event.text()) == 1) and (ord(event.text()[0:1]) > 32) and (ord(event.text()[0:1]) < 127):
			self.parent.filter.showFilter(event.text())
			event.accept()
		elif (event.key() == Qt.Key_Return) or (event.key() == Qt.Key_Enter):
			sel = self.selectedIndexes()
			if len(sel) != 0:
				self.exportDoubleClicked(sel[0])
		super(ExportsTreeView, self).keyPressEvent(event)

class ExportsWidget(QWidget):
	def __init__(self, parent, view, data):
		super(ExportsWidget, self).__init__(parent)
		layout = QVBoxLayout()
		layout.setContentsMargins(0, 0, 0, 0)
		self.imports = ExportsTreeView(self, view, data)
		self.filter = FilteredView(self, self.imports, self.imports)
		layout.addWidget(self.filter, 1)
		self.setLayout(layout)
		self.setMinimumSize(UIContext.getScaledWindowSize(100, 196))


text:
package org.apache.reef.io.network.impl;

import org.apache.reef.exception.evaluator.NetworkException;
import org.apache.reef.io.network.Connection;
import org.apache.reef.wake.Identifier;
import org.apache.reef.wake.remote.transport.Link;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

final class NetworkConnection<T> implements Connection<T> {

  private Link<NetworkConnectionServiceMessage<T>> link;

  private final Identifier destId;
  private final AtomicBoolean closed;
  private final NetworkConnectionFactory<T> connFactory;

  /**
   * Constructs a connection for destination identifier of NetworkConnectionService.
   * @param connFactory a connection factory of this connection.
   * @param destId a destination identifier of NetworkConnectionService.
   */
  NetworkConnection(
      final NetworkConnectionFactory<T> connFactory,
      final Identifier destId) {
    this.connFactory = connFactory;
    this.destId = destId;
    this.closed = new AtomicBoolean();
  }

  @Override
  public void open() throws NetworkException {
    link = connFactory.openLink(destId);
  }

  @Override
  public void write(final List<T> messageList) {
    final NetworkConnectionServiceMessage<T> nsMessage = new NetworkConnectionServiceMessage<>(
        connFactory.getConnectionFactoryId().toString(),
        connFactory.getLocalEndPointId(),
        destId,
        messageList);
    link.write(nsMessage);
  }

  @Override
  public void write(final T message) {
    final List<T> messageList = new ArrayList<>(1);
    messageList.add(message);
    write(messageList);
  }

  @Override
  public void close() {
    if (closed.compareAndSet(false, true)) {
      connFactory.removeConnection(this.destId);
      link = null;
    }
  }

  @Override
  public String toString() {
    final StringBuilder sb = new StringBuilder();
    sb.append("Connection from")
        .append(connFactory.getLocalEndPointId())
        .append(":")
        .append(connFactory.getConnectionFactoryId())
        .append(" to ")
        .append(destId)
        .append(":")
        .append(connFactory.getConnectionFactoryId());
    return sb.toString();
  }
}


text:
package com.mathworks.xzheng.advsearching;

import junit.framework.TestCase;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.core.WhitespaceAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.MultiReader;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.TermRangeQuery;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.RAMDirectory;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.Version;

// From chapter 5
public class MultiSearcherTest extends TestCase {
  private IndexSearcher[] searchers;

  public void setUp() throws Exception {
    String[] animals = { "aardvark", "beaver", "coati",
                       "dog", "elephant", "frog", "gila monster",
                       "horse", "iguana", "javelina", "kangaroo",
                       "lemur", "moose", "nematode", "orca",
                       "python", "quokka", "rat", "scorpion",
                       "tarantula", "uromastyx", "vicuna",
                       "walrus", "xiphias", "yak", "zebra"};

    Analyzer analyzer = new WhitespaceAnalyzer(Version.LUCENE_46);

    Directory aTOmDirectory = new RAMDirectory();     // #1
    Directory nTOzDirectory = new RAMDirectory();     // #1

    IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_46, analyzer);

    IndexWriter aTOmWriter = new IndexWriter(aTOmDirectory, config);
    IndexWriter nTOzWriter = new IndexWriter(nTOzDirectory, config);

    for (int i=animals.length - 1; i >= 0; i--) {
      Document doc = new Document();
      String animal = animals[i];
      doc.add(new Field("animal", animal, Field.Store.YES, Field.Index.NOT_ANALYZED));
      if (animal.charAt(0) < 'n') {
        aTOmWriter.addDocument(doc);                 // #2
      } else {
        nTOzWriter.addDocument(doc);                 // #2
      }
    }

    aTOmWriter.close();
    nTOzWriter.close();

    searchers = new IndexSearcher[2];
    searchers[0] = new IndexSearcher(DirectoryReader.open(aTOmDirectory));
    searchers[1] = new IndexSearcher(DirectoryReader.open(nTOzDirectory));
  }

  public void testMulti() throws Exception {

	  MultiReader multiReader = new MultiReader(searchers[0].getIndexReader(),
			  searchers[1].getIndexReader());
    IndexSearcher searcher = new IndexSearcher(multiReader);

    TermRangeQuery query = new TermRangeQuery("animal",   // #3
                                              new BytesRef("h"),        // #3
                                              new BytesRef("t"),        // #3
                                              true, true);// #3

    TopDocs hits = searcher.search(query, 10);
    assertEquals("tarantula not included", 12, hits.totalHits);
  }

  /*
    #1 Create two directories
    #2 Index halves of the alphabet
    #3 Search both indexes
  */
}


text:
package storm;

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

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.storm.task.OutputCollector;
import org.apache.storm.task.TopologyContext;
import org.apache.storm.topology.OutputFieldsDeclarer;
import org.apache.storm.topology.base.BaseRichBolt;
import org.apache.storm.tuple.Tuple;

public class LoggerBolt extends BaseRichBolt {
    private OutputCollector collector;
    private static final Logger logger = LoggerFactory
              .getLogger(LoggerBolt.class);

    @Override
    public void execute(Tuple tuple) {
        String value = tuple.getString(0);
        logger.info("Tuple value: " + value);

        collector.ack(tuple);
    }

    @Override
    public void prepare(Map map, TopologyContext context, OutputCollector collector) {
        this.collector = collector;
        // this.count = 0;
    }

    @Override
    public void declareOutputFields(OutputFieldsDeclarer declarer) {
        // no output fields
        }

}


text:
import config from './config'
import * as content from './content'

let nextBlockId = 1
const state = {}

export const next = getSibling('nextElementSibling')
export const previous = getSibling('previousElementSibling')

export function init (elem, {normalize, shouldSpellcheck}) {
  setBlockId(elem)

  elem.setAttribute('contenteditable', true)
  elem.setAttribute('spellcheck', Boolean(shouldSpellcheck))

  elem.classList.remove(config.editableDisabledClass)
  elem.classList.add(config.editableClass)

  if (normalize) content.tidyHtml(elem)
}

export function disable (elem) {
  elem.removeAttribute('contenteditable')
  elem.removeAttribute('spellcheck')

  setState(elem, undefined)

  elem.classList.remove(config.editableClass)
  elem.classList.add(config.editableDisabledClass)
}

export function setBlockId (elem) {
  if (!elem.hasAttribute('data-editable')) {
    elem.setAttribute('data-editable', `id-${nextBlockId}`)
    nextBlockId += 1
  }
}

export function getState (elem) {
  if (elem.hasAttribute('data-editable')) {
    const id = elem.getAttribute('data-editable')
    return state[id]
  }
}

export function setState (elem, data) {
  if (elem.hasAttribute('data-editable')) {
    const id = elem.getAttribute('data-editable')
    state[id] = data
  }
}

// Helpers
// -------

function getSibling (type) {
  return function (element) {
    const sibling = element[type]
    return sibling && sibling.getAttribute('contenteditable')
      ? sibling
      : null
  }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Grains.Redux
{
    public class ReduxGrainStore<TState> : Store<ReduxGrainState<TState>>, IStore<TState>
    {
        public ReduxGrainStore(Reducer<TState> reducer, TState initialState = default(TState), uint initialSerial = 0, params Middleware<TState>[] middlewares)
            : base(new ReduxGrainReducer<TState>((s, a) => reducer(s, a)).Execute, new ReduxGrainState<TState>(initialState, initialSerial))
        {
        }

        public ReduxGrainStore(Reducer<TState> reducer, ReduxGrainState<TState> initialState, params Middleware<TState>[] middlewares)
            : base(new ReduxGrainReducer<TState>((s, a) => reducer(s, a)).Execute, initialState)
        { }

        public TState State { get { return this.GetState().State; } }

        public IDisposable Subscribe(IObserver<TState> observer)
        {
            return ((IObservable<ReduxGrainState<TState>>)this)
                .Select(state => (TState)state.State)
                .DistinctUntilChanged()
                .Subscribe(observer);
        }

        TState IStore<TState>.GetState()
        {
            return ((IStore<TState>)this).GetState();
        }
    }
}


text:
package dk.brics.tajs.analysis.dom.event;

import dk.brics.tajs.analysis.Conversion;
import dk.brics.tajs.analysis.FunctionCalls;
import dk.brics.tajs.analysis.NativeFunctions;
import dk.brics.tajs.analysis.Solver;
import dk.brics.tajs.analysis.State;
import dk.brics.tajs.analysis.dom.*;
import dk.brics.tajs.lattice.ObjectLabel;
import dk.brics.tajs.lattice.Value;
import dk.brics.tajs.util.AnalysisException;

import static dk.brics.tajs.analysis.dom.DOMFunctions.createDOMFunction;
import static dk.brics.tajs.analysis.dom.DOMFunctions.createDOMProperty;

/**
 * The MutationEvent interface provides specific contextual information
 * associated with Mutation events.
 */
public class MutationEvent {

    public static ObjectLabel PROTOTYPE;
    public static ObjectLabel INSTANCES;

    public static void build(State s) {
        PROTOTYPE = new ObjectLabel(DOMObjects.MUTATION_EVENT_PROTOTYPE, ObjectLabel.Kind.OBJECT);
        INSTANCES = new ObjectLabel(DOMObjects.MUTATION_EVENT_INSTANCES, ObjectLabel.Kind.OBJECT);

        // Prototype object.
        s.newObject(PROTOTYPE);
        s.writeInternalPrototype(PROTOTYPE, Value.makeObject(Event.PROTOTYPE));

        // Multiplied object.
        s.newObject(INSTANCES);
        s.writeInternalPrototype(INSTANCES, Value.makeObject(PROTOTYPE));
        s.writeProperty(DOMWindow.WINDOW, "MutationEvent", Value.makeObject(INSTANCES));

        /*
         * Properties.
         */
        createDOMProperty(s, INSTANCES, "relatedNode", Value.makeAnyStr().setReadOnly());
        createDOMProperty(s, INSTANCES, "prevValue", Value.makeAnyStr().setReadOnly());
        createDOMProperty(s, INSTANCES, "newValue", Value.makeAnyStr().setReadOnly());
        createDOMProperty(s, INSTANCES, "attrName", Value.makeAnyStr().setReadOnly());
        createDOMProperty(s, INSTANCES, "attrChange", Value.makeAnyNumUInt().setReadOnly());

        /*
         * Constants (attrChangeType).
         */
        createDOMProperty(s, PROTOTYPE, "MODIFICATION", Value.makeNum(1));
        createDOMProperty(s, PROTOTYPE, "ADDITION", Value.makeNum(2));
        createDOMProperty(s, PROTOTYPE, "REMOVAL", Value.makeNum(3));

        /*
         * Functions.
         */
        createDOMFunction(s, PROTOTYPE, DOMObjects.MUTATION_EVENT_INIT_MUTATION_EVENT, "initMutationEvent", 8);

        // Multiply Object
        s.multiplyObject(INSTANCES);
        INSTANCES = INSTANCES.makeSingleton().makeSummary();

        // DOM Registry
        DOMRegistry.registerMutationEventLabel(INSTANCES);
    }

    public static Value evaluate(DOMObjects nativeObject, FunctionCalls.CallInfo call, State s, Solver.SolverInterface c) {
        switch (nativeObject) {
            case MUTATION_EVENT_INIT_MUTATION_EVENT: {
                NativeFunctions.expectParameters(nativeObject, call, c, 8, 8);
                /* Value typeArg =*/ Conversion.toString(NativeFunctions.readParameter(call, s, 0), c);
                /* Value canBubble =*/ Conversion.toBoolean(NativeFunctions.readParameter(call, s, 1));
                /* Value cancelable =*/ Conversion.toBoolean(NativeFunctions.readParameter(call, s, 2));
                /* Value relatedNode =*/ DOMConversion.toNode(NativeFunctions.readParameter(call, s, 3), c);
                /* Value prevValue =*/ Conversion.toString(NativeFunctions.readParameter(call, s, 4), c);
                /* Value newValue =*/ Conversion.toString(NativeFunctions.readParameter(call, s, 5), c);
                /* Value attrName =*/ Conversion.toString(NativeFunctions.readParameter(call, s, 6), c);
                /* Value attrChange =*/ Conversion.toNumber(NativeFunctions.readParameter(call, s, 7), c);
                return Value.makeUndef();
            }
            default:
                throw new AnalysisException("Unsupported Native Object: " + nativeObject);
        }
    }
}


text:
$(document).ready(function(){

	$("#msg_action").hide();
	$("#msg").hide();

	// exibe modal para edição de valores das opções
	if(document.getElementById("modalValues") !== null){
		$('#modalValues').modal('show');
	}

	// Eduardo Barros Villa
	// Quando o idioma for selecionado busca as categorias relacionadas
	$('select[name=language]').change(function() {
		categories($(this).val());
		categoriesSelect($(this).val());
		technologies($(this).val());
		options($(this).val());
	});

	/*$('#list-category').load(base_url()+'products/loadCategory', { type: 'div' }, function(){
		changeCheckbox();
	});

	$.post(base_url()+'products/loadCategory', { type: 'select' }, function(dataReturn){
		var dataReturnSelect = '<option value="0">--- Categoria principal ---</option>'+dataReturn;

		$('#category_level').html(dataReturnSelect);

		changeSelect();
	});*/

	// validação ações Produtos
    $("#actionProducts").validate({
		rules: {
			action: "required",
			'action_value[]': "required"
		},
		messages: {
			action: "Seleciona uma ação.",
			'action_value[]': ""
		}
	});
	var optionsActionProducts = {
		type: "POST",
		url: base_url()+"products/actionProducts",
		clearForm: true,
		success: function(data){
			if(data == "success"){

				$('#msg_action')
					.removeClass().addClass("alert alert-success")
					.html("
Registro(s) alterado(s) com sucesso!
").show();
				setTimeout("document.location.reload(true);", 2000);

			} else {

				$('#msg_action')
					.removeClass().addClass("alert alert-danger")
					.html("
Erro!

Problemas no cadastramento dos dados!
").show();

			}
		}
	};
	$("#actionProducts").ajaxForm(optionsActionProducts);

	// validação cadastro produto
	$("#productsAddForm").validate({
		rules: {
			title: "required",
			page_content: "required",
			'category[]': "required",
			image: "required"
		},
		messages: {
			title: "Este campo é obrigatório.",
			page_content: "Este campo é obrigatório.",
			'category[]': "",
			image: "Selecione uma imagem."
		}
	});

	// cadastrar produto
	var optionsProductAdd = {
		type: "POST",
		url: base_url()+"products/insertProduct",
		success: function(data){
			var items = data.split('|');
			if(items[0] == "success"){
				// remove exibição de imagem
				btnRemove();

				// limpar textarea descrição
				$('.redactor_editor').html('');

				$('#msg')
					.removeClass().addClass("alert alert-success")
					.html("
Produto cadastrado com sucesso!
").show();
				$(window.document.location).attr('href', base_url()+'products/edit/'+items[1]);

			} else{

				$('#msg')
					.removeClass().addClass("alert alert-danger")
					.html("
Erro!

Problemas no cadastramento dos dados!
").show();
				setTimeout(function() { $('#msg').hide(); }, 2000);

			}
		}
	};
	$("#productsAddForm").ajaxForm(optionsProductAdd);

	// editar produto
	var optionsProductEdit = {
		type: "POST",
		url: base_url()+"products/updateProduct",
		clearForm: false,
		success: function(data){
			if(data == "success"){

				$('#msg')
					.removeClass().addClass("alert alert-success")
					.html("
Produto alterado com sucesso!
").show();
				setTimeout(function() { $('#msg').hide(); }, 2000);

			} else{

				$('#msg')
					.removeClass().addClass("alert alert-danger")
					.html("
Erro!

Problemas no cadastramento dos dados!
").show();
				setTimeout(function() { $('#msg').hide(); }, 2000);

			}
		}
	};
	$("#productsEditForm").ajaxForm(optionsProductEdit);

	// validação cadastro opções
	$("#optionsAddForm").validate({
		rules: {
			name: "required",
		},
		messages: {
			name: "Este campo é obrigatório."
		}
	});

	// cadastrar opção
	var optionsAdd = {
		type: "POST",
		url: base_url()+"products/insertOptions",
		clearForm: true,
		success: function(data){
			if(data == "success"){

				$('#msg')
					.removeClass().addClass("alert alert-success")
					.html("
Opção cadastrada com sucesso!
").show();
				setTimeout("document.location.reload(true);", 2000);

			} else{

				$('#msg')
					.removeClass().addClass("alert alert-danger")
					.html("
Erro!

Problemas no cadastramento dos dados!
").show();
				setTimeout(function() { $('#msg').hide(); }, 2000);

			}
		}
	};
	$("#optionsAddForm").ajaxForm(optionsAdd);

	// editar opção
	var optionsEdit = {
		type: "POST",
		url: base_url()+"products/updateOptions",
		clearForm: false,
		success: function(data){
			if(data == "success"){

				$('#msg')
					.removeClass().addClass("alert alert-success")
					.html("
Opção alterada com sucesso!
").show();
				setTimeout("document.location.reload(true);", 2000);

			} else{

				$('#msg')
					.removeClass().addClass("alert alert-danger")
					.html("
Erro!

Problemas no cadastramento dos dados!
").show();
				setTimeout(function() { $('#msg').hide(); }, 2000);

			}
		}
	};
	$("#optionsEditForm").ajaxForm(optionsEdit);

	// validação cadastro valores opções
	$("#optionsValuesAddForm").validate({
		rules: {
			label: "required",
		},
		messages: {
			label: "Este campo é obrigatório."
		}
	});

	var optionsValuesAdd = {
		type: "POST",
		url: base_url()+"products/insertOptionsValues",
		clearForm: true,
		success: function(data){
			if(data == "success"){
				/*$('#msg').removeClass();
				$('#msg').addClass("alert alert-success");
				$('#msg').html("
Opção cadastrada com sucesso!
");
				$('#msg').show();*/

				document.location.reload();
			} else{

				$('#msg')
					.removeClass().addClass("alert alert-danger")
					.html("
Erro!

Problemas no cadastramento dos dados!
").show();
				setTimeout(function() { $('#msg').hide(); }, 2000);

			}
		}
	};
	$("#optionsValuesAddForm").ajaxForm(optionsValuesAdd);

	/**
     * Categorias
     * Validação formulário de cadastro
     */

    // validação ações Categorias
    $("#actionCategories").validate({
		rules: {
			action: "required",
			'action_value[]': "required"
		},
		messages: {
			action: "Seleciona uma ação.",
			'action_value[]': ""
		}
	});
	var optionsActionCategories = {
		type: "POST",
		url: base_url()+"products/actionCategories",
		clearForm: true,
		success: function(data){
			if(data == "success"){

				$('#msg_action')
					.removeClass().addClass("alert alert-success")
					.html("
Registro(s) alterado(s) com sucesso!
").show();
				setTimeout("document.location.reload(true);", 2000);

			} else {

				$('#msg_action')
					.removeClass().addClass("alert alert-danger")
					.html("
Erro!

Problemas no cadastramento dos dados!
").show();
				setTimeout(function() { $('#msg').hide(); }, 2000);
			}
		}
	};
	$("#actionCategories").ajaxForm(optionsActionCategories);

	// validação cadastro categorias
    $("#categoriesAddForm").validate({
		rules: {
			category:
			{
				required: true
				/*"remote":
                {
                  url: base_url()+'products/checkCategory',
                  type: "post",
                  data:
                  {
                      category: function()
                      {
                          return $('#category').val();
                      }
                  }
                }*/
			}
		},
		messages: {
			category:
			{
				required: "Este campo é obrigatório."
				//remote: "Categoria já cadastrada"
			}
		}
	});

	var optionsCategoriesAdd = {
		type: "POST",
		url: base_url()+"products/insertCategory",
		clearForm: true,
		success: function(data){
			if(data == "success"){

				$('#msg')
					.removeClass().addClass("alert alert-success")
					.html("
Categoria cadastrada com sucesso!
").show();
				setTimeout("document.location.reload(true);", 2000);

			} else {

				$('#msg')
					.removeClass().addClass("alert alert-danger")
					.html("
Erro!

Problemas no cadastramento dos dados!
").show();
				setTimeout(function() { $('#msg').hide(); }, 2000);

			}
		}
	};
	$("#categoriesAddForm").ajaxForm(optionsCategoriesAdd);

	// validação edição categorias
    $("#categoriesEditForm").validate({
		rules: {
			category:
			{
				required: true,
			}
		},
		messages: {
			category:
			{
				required: "Este campo é obrigatório."
			}
		}
	});

	// edição categorias
	var optionsCategoryEdit = {
		type: "POST",
		url: base_url()+"products/updateCategory",
		clearForm: false,
		success: function(data){
			if(data == "success"){

				$('#msg')
					.removeClass().addClass("alert alert-success")
					.html("
Categoria salva com sucesso!
").show();
				setTimeout("document.location.reload(true);", 2000);

			} else {

				$('#msg')
					.removeClass().addClass("alert alert-danger")
					.html("
Erro!

Problemas no cadastramento dos dados!
").show();
				setTimeout(function() { $('#msg').hide(); }, 2000);

			}
		}
	};
	$("#categoriesEditForm").ajaxForm(optionsCategoryEdit);

	/**
     * Tecnologias
     * Validação formulário de cadastro
     */

     // validação ações tecnologias
    $("#actionTechnologies").validate({
		rules: {
			action: "required",
			'action_value[]': "required"
		},
		messages: {
			action: "Seleciona uma ação.",
			'action_value[]': ""
		}
	});

	var optionsActionTechnologies = {
		type: "POST",
		url: base_url()+"products/actionTechnologies",
		clearForm: true,
		success: function(data){
			if(data == "success"){

				$('#msg_action')
					.removeClass().addClass("alert alert-success")
					.html("
Registro(s) alterado(s) com sucesso!
").show();
				setTimeout("document.location.reload(true);", 2000);

			} else {

				$('#msg_action')
					.removeClass().addClass("alert alert-danger")
					.html("
Erro!

Problemas no cadastramento dos dados!
").show();
				setTimeout(function() { $('#msg').hide(); }, 2000);

			}
		}
	};
	$("#actionTechnologies").ajaxForm(optionsActionTechnologies);

    // validação cadastro tecnologias
	$("#technologiesAddForm").validate({
		rules: {
			name: "required",
			description: "required",
			image: "required",
			image_negative: "required",
		},
		messages: {
			name: "Este campo é obrigatório.",
			description: "Este campo é obrigatório.",
			image: "Selecione uma imagem.",
			image_negative: "Selecione uma imagem.",
		}
	});

	// cadastrar tecnologia
	var optionsTechnologiesAdd = {
		type: "POST",
		url: base_url()+"products/insertTechnologies",
		clearForm: true,
		success: function(data){
			if(data == "success"){

				$('#msg')
					.removeClass().addClass("alert alert-success")
					.html("
Tecnologia cadastrada com sucesso!
").show();
				setTimeout("document.location.reload(true);", 2000);

			} else{

				$('#msg')
					.removeClass().addClass("alert alert-danger")
					.html("
Erro!

Problemas no cadastramento dos dados!
").show();
				setTimeout(function() { $('#msg').hide(); }, 2000);

			}
		}
	};
	$("#technologiesAddForm").ajaxForm(optionsTechnologiesAdd);

	// editar tecnologia
	var optionsTechnologiesEdit = {
		type: "POST",
		url: base_url()+"products/updateTechnologies",
		clearForm: false,
		success: function(data){
			if(data == "success"){

				$('#msg')
					.removeClass().addClass("alert alert-success")
					.html("
Tecnologia alterada com sucesso!
").show();
				setTimeout("document.location.reload(true);", 2000);

			} else{

				$('#msg')
					.removeClass().addClass("alert alert-danger")
					.html("
Erro!

Problemas no cadastramento dos dados!
").show();
				setTimeout(function() { $('#msg').hide(); }, 2000);

			}
		}
	};
	$("#technologiesEditForm").ajaxForm(optionsTechnologiesEdit);
});

// função para remover exibição de imagem
function btnRemove()
{
	$('#btnRemove').click();
}

function editValue(id_value,label,value)
{
	$('#id_value').val(id_value);
	$('#label').val(label);
	$('#value').val(value);
}

function uploadImage()
{
	$(".send-load").html(' enviando...');

	var id_product = $('#id_product').val();
	var value = $('#color').val();

	// limpar select cor
	$('#color option:selected').removeAttr('selected');

	$('.file-input-name').html('');

	if(value == 0)
	{
		alert('Selecione uma cor!');
	}
	else
	{
		var file_data = $("#sendImage").prop("files")[0];   // Getting the properties of file from file field
		var form_data = new FormData();                  // Creating object of FormData class
		// nome input file
		form_data.append("color", file_data);

		$.ajax({
	        url: base_url()+'products/addImage/'+id_product+'/'+value,
	        dataType: 'html',
	        cache: false,
	        contentType: false,
	        processData: false,
	        data: form_data,                         // Setting the data attribute of ajax with file_data
	        type: 'post',
	        success: function(dataReturn)
	        {
		    	if(dataReturn == 'success'){

		    		listProductColors(id_product);
		    		$(".send-load").html('');

				} else {
					//alert('falha');
				}

	        }
	   });
	}

}

// lista cores
function listProductColors(id_product)
{
	$("#listProductColors").html('');
	$('#listProductColors').load(base_url()+'products/listProductColors/'+id_product);
}

function deleteProductColors(id_relation)
{
	$.ajax({
        url: base_url()+'products/deleteProductColors/'+id_relation,
        dataType: 'html',
        cache: false,
        contentType: false,
        processData: false,
        //data: form_data,                         // Setting the data attribute of ajax with file_data
        type: 'post',
        success: function(dataReturn)
        {
	    	if(dataReturn != 'error'){

	    		listProductColors(dataReturn);

			} else {
				//alert('falha');
			}

        }
   });
}

/**********************************************************************/
// Eduardo Barros Villa

// lista categorias ao selecionar o idioma
function categories(language_id)
{
	$.post(base_url()+'products/loadCategoryLang', { lang:language_id }, function(dataReturn) {

		$('#list-category').html(dataReturn);

	});
}

// lista de caracteres ao selecionar o idioma (SELECT)
function categoriesSelect(language_id)
{
	$.post(base_url()+'products/loadCategorySelectLang', { lang:language_id }, function(dataReturn) {

		$('#category_level').html(dataReturn);

	});
}

// lista as tecnologias ao selecionar o idioma
function technologies(language_id)
{
	$.post(base_url()+'products/loadTechnologyLang', { lang:language_id }, function(dataReturn) {

		$('#technologies').html(dataReturn);

	});
}

// lista as tecnologias ao selecionar o idioma
function options(language_id)
{
	// Tamanhos
	$.post(base_url()+'products/loadSizeLang', { lang:language_id }, function(dataReturn) {

		$('#sizeOptions').html(dataReturn);
		$('#sizeOptions').multiSelect('refresh');

	});

	// Color
	$.post(base_url()+'products/loadColorLang', { lang:language_id }, function(dataReturn) {

		$('#color').html(dataReturn);

	});
}


text:
NS_ASSUME_NONNULL_BEGIN

@class JXCBaseRequest;

@interface JXCNetworkProxy : NSObject

- (instancetype)init NS_UNAVAILABLE;
+ (instancetype)new NS_UNAVAILABLE;

///  Get the shared agent.
+ (JXCNetworkProxy *)sharedProxy;

///  Add request to session and start it.
- (void)addRequest:(JXCBaseRequest *)request;

///  Cancel a request that was previously added.
- (void)cancelRequest:(JXCBaseRequest *)request;

///  Cancel all requests that were previously added.
- (void)cancelAllRequests;

///  Return the constructed URL of request.
///
///  @param request The request to parse. Should not be nil.
///
///  @return The result URL.
- (NSString *)buildRequestUrl:(JXCBaseRequest *)request;

@end

NS_ASSUME_NONNULL_END