text:
package org.apache.activemq.artemis.integration;

import java.lang.management.ManagementFactory;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.activemq.artemis.core.config.CoreAddressConfiguration;
import org.apache.activemq.artemis.core.config.CoreQueueConfiguration;
import org.apache.activemq.artemis.core.config.FileDeploymentManager;
import org.apache.activemq.artemis.core.config.impl.FileConfiguration;
import org.apache.activemq.artemis.core.server.ActiveMQComponent;
import org.apache.activemq.artemis.core.server.ActiveMQServer;
import org.apache.activemq.artemis.api.core.RoutingType;
import org.apache.activemq.artemis.core.server.ServiceComponent;
import org.apache.activemq.artemis.dto.ServerDTO;
import org.apache.activemq.artemis.integration.bootstrap.ActiveMQBootstrapLogger;
import org.apache.activemq.artemis.jms.server.config.JMSQueueConfiguration;
import org.apache.activemq.artemis.jms.server.config.TopicConfiguration;
import org.apache.activemq.artemis.jms.server.config.impl.FileJMSConfiguration;
import org.apache.activemq.artemis.spi.core.security.ActiveMQSecurityManager;

public class FileBroker implements Broker {

   private final String configurationUrl;

   private boolean started;

   private final ActiveMQSecurityManager securityManager;

   private Map<String, ActiveMQComponent> components;

   public FileBroker(ServerDTO broker, ActiveMQSecurityManager security) {
      this.securityManager = security;
      this.configurationUrl = broker.configuration;
   }

   @Override
   public synchronized void start() throws Exception {
      if (started) {
         return;
      }

      //todo if we start to pullout more configs from the main config then we should pull out the configuration objects from factories if available
      FileConfiguration configuration = new FileConfiguration();

      // Keep this as we still want to parse destinations in the <jms> element
      FileJMSConfiguration jmsConfiguration = new FileJMSConfiguration();

      FileDeploymentManager fileDeploymentManager = new FileDeploymentManager(configurationUrl);
      fileDeploymentManager.addDeployable(configuration).addDeployable(jmsConfiguration);
      fileDeploymentManager.readConfiguration();

      /**
       * This is a bit of a hack for backwards config compatibility since we no longer want to start the broker
       * using the JMSServerManager which would normally deploy JMS destinations. Here we take the JMS destination
       * configurations from the parsed JMS configuration and add them to the core configuration.
       *
       * It's also important here that we are adding them to the core ADDRESS configurations as those will be
       * deployed first and therefore their configuration will take precedence over other legacy queue configurations
       * which are deployed later. This is so we can maintain support for configurations like those found in the
       * bridge and divert examples where there are JMS and core queues with the same name (which was itself a bit
       * of a hack).
       *
       * This should be removed when support for the old "jms" configuation element is also removed.
       */
      {
         for (JMSQueueConfiguration jmsQueueConfig : jmsConfiguration.getQueueConfigurations()) {
            List<CoreAddressConfiguration> coreAddressConfigurations = configuration.getAddressConfigurations();
            coreAddressConfigurations.add(new CoreAddressConfiguration()
                                             .setName(jmsQueueConfig.getName())
                                             .addRoutingType(RoutingType.ANYCAST)
                                             .addQueueConfiguration(new CoreQueueConfiguration()
                                                                       .setAddress(jmsQueueConfig.getName())
                                                                       .setName(jmsQueueConfig.getName())
                                                                       .setFilterString(jmsQueueConfig.getSelector())
                                                                       .setRoutingType(RoutingType.ANYCAST)));
         }

         for (TopicConfiguration topicConfig : jmsConfiguration.getTopicConfigurations()) {
            List<CoreAddressConfiguration> coreAddressConfigurations = configuration.getAddressConfigurations();
            coreAddressConfigurations.add(new CoreAddressConfiguration()
                                             .setName(topicConfig.getName())
                                             .addRoutingType(RoutingType.MULTICAST));
         }
      }

      components = fileDeploymentManager.buildService(securityManager, ManagementFactory.getPlatformMBeanServer());

      ArrayList<ActiveMQComponent> componentsByStartOrder = getComponentsByStartOrder(components);
      ActiveMQBootstrapLogger.LOGGER.serverStarting();
      for (ActiveMQComponent component : componentsByStartOrder) {
         component.start();
      }
      started = true;

   }

   @Override
   public void stop() throws Exception {
      stop(false);
   }

   @Override
   public void exit() throws Exception {
      stop(true);
   }

   private void stop(boolean isShutdown) throws Exception {
      if (!started) {
         return;
      }
      ActiveMQComponent[] mqComponents = new ActiveMQComponent[components.size()];
      components.values().toArray(mqComponents);
      for (int i = mqComponents.length - 1; i >= 0; i--) {
         if (mqComponents[i] instanceof ServiceComponent && isShutdown) {
            ((ServiceComponent) mqComponents[i]).exit();
         } else {
            mqComponents[i].stop();
         }
      }
      started = false;
   }

   @Override
   public boolean isStarted() {
      return started;
   }

   public Map<String, ActiveMQComponent> getComponents() {
      return components;
   }

   /*
   * this makes sure the components are started in the correct order. Its simple at the mo as e only have core and jms but
   * will need impproving if we get more.
   * */
   public ArrayList<ActiveMQComponent> getComponentsByStartOrder(Map<String, ActiveMQComponent> components) {
      ArrayList<ActiveMQComponent> activeMQComponents = new ArrayList<>();
      ActiveMQComponent jmsComponent = components.get("jms");
      if (jmsComponent != null) {
         activeMQComponents.add(jmsComponent);
      }
      activeMQComponents.add(components.get("core"));
      return activeMQComponents;
   }

   @Override
   public ActiveMQServer getServer() {
      return (ActiveMQServer) components.get("core");
   }

}


text:
@implementation FTEBook

-(instancetype) initWithBookXML:(NSDictionary *) dict{
    self = [super init];
    if (self) {
        NSDictionary *metaData = [dict objectForKey:@"metadata"];
#warning Check all the Strings below for a possibility of becoming Dictionary
        if ([[metaData objectForKey:@"dc:creator"] isKindOfClass:[NSString class]]) {
            [self setAuthor:[metaData objectForKey:@"dc:creator"]];
        }

        if ([[metaData objectForKey:@"dc:title"] isKindOfClass:[NSString class]]) {
            [self setTitle:[metaData objectForKey:@"dc:title"]];
        }

        NSDictionary *spine = [dict objectForKey:@"spine"];
        NSArray *itemsList = [spine objectForKey:@"itemref"];
        NSMutableArray *tocList = [NSMutableArray array];
        for (int i=0;i<itemsList.count;i++) {
            [tocList addObject:[[itemsList objectAtIndex:i] objectForKey:@"_idref"]];
        }

        NSArray *manifest = [[dict objectForKey:@"manifest"] objectForKey:@"item"];
        NSMutableDictionary *tocItems = [NSMutableDictionary dictionary];
        for (NSDictionary *tItem in manifest) {
            [tocItems setObject:[tItem objectForKey:@"_href"] forKey:[tItem objectForKey:@"_id"]];
        }

        [self setAvailablePages:tocItems];
        [self setToc:tocList];
    }

    return self;
}
-(BOOL)isEqual:(id)object{
    if ([object isKindOfClass:[FTEBook class]]) {
        FTEBook *tObj = (FTEBook *) object;
        return [tObj.bookId isEqualToString:self.bookId];
    }
    return NO;
}

//===========================================================
//  Keyed Archiving
//
//===========================================================
- (void)encodeWithCoder:(NSCoder *)encoder
{
    [encoder encodeObject:self.title forKey:@"title"];
    [encoder encodeObject:self.author forKey:@"author"];
    [encoder encodeObject:self.bookId forKey:@"bookId"];
    [encoder encodeInteger:self.currentPage forKey:@"currentPage"];
    [encoder encodeObject:self.currentLocation forKey:@"currentLocation"];
    [encoder encodeObject:self.toc forKey:@"toc"];
    [encoder encodeObject:self.availablePages forKey:@"availablePages"];
}

- (id)initWithCoder:(NSCoder *)decoder
{
    self = [super init];
    if (self) {
        self.title = [decoder decodeObjectForKey:@"title"];
        self.author = [decoder decodeObjectForKey:@"author"];
        self.bookId = [decoder decodeObjectForKey:@"bookId"];
        self.currentPage = [decoder decodeIntegerForKey:@"currentPage"];
        self.currentLocation = [decoder decodeObjectForKey:@"currentLocation"];
        self.toc = [decoder decodeObjectForKey:@"toc"];
        self.availablePages = [decoder decodeObjectForKey:@"availablePages"];
    }
    return self;
}

@end

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Diagnostics;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Orleans.Runtime;
using TestExtensions;
using UnitTests.GrainInterfaces;
using UnitTests.Grains;
using Xunit;
using Xunit.Abstractions;

namespace UnitTests
{
    // if we parallelize tests, this should run in isolation
    public class TimeoutTests : HostedTestClusterEnsureDefaultStarted, IDisposable
    {
        private readonly ITestOutputHelper output;
        private readonly TimeSpan originalTimeout;
        private readonly IRuntimeClient runtimeClient;

        public TimeoutTests(ITestOutputHelper output, DefaultClusterFixture fixture) : base(fixture)
        {
            this.output = output;
            this.runtimeClient = this.HostedCluster.ServiceProvider.GetRequiredService<IRuntimeClient>();
            originalTimeout = this.runtimeClient.GetResponseTimeout();
        }

        public void Dispose()
        {
            this.runtimeClient.SetResponseTimeout(originalTimeout);
        }

        [Fact, TestCategory("Functional"), TestCategory("Timeout")]
        public void Timeout_LongMethod()
        {
            bool finished = false;
            var grainName = typeof (ErrorGrain).FullName;
            IErrorGrain grain = this.GrainFactory.GetGrain<IErrorGrain>(GetRandomGrainId(), grainName);
            TimeSpan timeout = TimeSpan.FromMilliseconds(1000);
            this.runtimeClient.SetResponseTimeout(timeout);

            Task promise = grain.LongMethod((int)timeout.Multiply(4).TotalMilliseconds);
            //promise = grain.LongMethodWithError(2000);

            // there is a race in the test here. If run in debugger, the invocation can actually finish OK
            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Start();
            try
            {
                finished = promise.Wait(timeout.Multiply(3));
                Assert.True(false, "Should have thrown");
            }
            catch (Exception exc)
            {
                stopwatch.Stop();
                Exception baseExc = exc.GetBaseException();
                if (!(baseExc is TimeoutException))
                {
                    Assert.True(false, "Should not have got here " + exc);
                }
            }
            output.WriteLine("Waited for " + stopwatch.Elapsed);
            Assert.True(!finished);
            Assert.True(stopwatch.Elapsed >= timeout.Multiply(0.9), "Waited less than " + timeout.Multiply(0.9) + ". Waited " + stopwatch.Elapsed);
            Assert.True(stopwatch.Elapsed <= timeout.Multiply(2), "Waited longer than " + timeout.Multiply(2) + ". Waited " + stopwatch.Elapsed);
            Assert.True(promise.Status == TaskStatus.Faulted);

            // try to re-use the promise and should fail immideately.
            try
            {
                stopwatch = new Stopwatch();
                promise.Wait();
                Assert.True(false, "Should have thrown");
            }
            catch (Exception exc)
            {
                stopwatch.Stop();
                Exception baseExc = exc.GetBaseException();
                if (!(baseExc is TimeoutException))
                {
                    Assert.True(false, "Should not have got here " + exc);
                }
            }
            Assert.True(stopwatch.Elapsed <= timeout.Multiply(0.1), "Waited longer than " + timeout.Multiply(0.1) + ". Waited " + stopwatch.Elapsed);
            Assert.True(promise.Status == TaskStatus.Faulted);
        }
    }
}


text:
/* TODO: introduce line-wrapping so that it never exceeds the limit. */
/* jscs: disable maximumLineLength */
'use strict';

var configData = require('./speech_client_config');
var extend = require('extend');
var gax = require('google-gax');

var SERVICE_ADDRESS = 'speech.googleapis.com';

var DEFAULT_SERVICE_PORT = 443;

var CODE_GEN_NAME_VERSION = 'gapic/0.1.0';

var STREAM_DESCRIPTORS = {
  streamingRecognize: new gax.StreamDescriptor(gax.StreamType.BIDI_STREAMING)
};

/**
 * The scopes needed to make gRPC calls to all of the methods defined in
 * this service.
 */
var ALL_SCOPES = [
  'https://www.googleapis.com/auth/cloud-platform'
];

/**
 * Service that implements Google Cloud Speech API.
 *
 * This will be created through a builder function which can be obtained by the module.
 * See the following example of how to initialize the module and how to access to the builder.
 * @see {@link speechClient}
 *
 * @example
 * var speechV1beta1 = require('@google-cloud/speech').v1beta1({
 *   // optional auth parameters.
 * });
 * var client = speechV1beta1.speechClient();
 *
 * @class
 */
function SpeechClient(gaxGrpc, grpcClients, opts) {
  opts = extend({
    servicePath: SERVICE_ADDRESS,
    port: DEFAULT_SERVICE_PORT,
    clientConfig: {}
  }, opts);

  var googleApiClient = [
    'gl-node/' + process.versions.node,
    CODE_GEN_NAME_VERSION
  ];
  if (opts.libName && opts.libVersion) {
    googleApiClient.push(opts.libName + '/' + opts.libVersion);
  }
  googleApiClient.push(
    'gax/' + gax.version,
    'grpc/' + gaxGrpc.grpcVersion
  );

  this.operationsClient = new gax.lro({
    auth: gaxGrpc.auth,
    grpc: gaxGrpc.grpc
  }).operationsClient(opts);

  this.longrunningDescriptors = {
    asyncRecognize: new gax.LongrunningDescriptor(
      this.operationsClient,
      grpcClients.google.cloud.speech.v1beta1.AsyncRecognizeResponse.decode,
      grpcClients.google.cloud.speech.v1beta1.AsyncRecognizeMetadata.decode)
  };

  var defaults = gaxGrpc.constructSettings(
      'google.cloud.speech.v1beta1.Speech',
      configData,
      opts.clientConfig,
      {'x-goog-api-client': googleApiClient.join(' ')});

  var self = this;

  this.auth = gaxGrpc.auth;
  var speechStub = gaxGrpc.createStub(
      grpcClients.google.cloud.speech.v1beta1.Speech,
      opts);
  var speechStubMethods = [
    'syncRecognize',
    'asyncRecognize',
    'streamingRecognize'
  ];
  speechStubMethods.forEach(function(methodName) {
    self['_' + methodName] = gax.createApiCall(
      speechStub.then(function(speechStub) {
        return function() {
          var args = Array.prototype.slice.call(arguments, 0);
          return speechStub[methodName].apply(speechStub, args);
        };
      }),
      defaults[methodName],
      STREAM_DESCRIPTORS[methodName] || self.longrunningDescriptors[methodName]);
  });
}

/**
 * Get the project ID used by this class.
 * @aram {function(Error, string)} callback - the callback to be called with
 *   the current project Id.
 */
SpeechClient.prototype.getProjectId = function(callback) {
  return this.auth.getProjectId(callback);
};

// Service calls

/**
 * Perform synchronous speech-recognition: receive results after all audio
 * has been sent and processed.
 *
 * @param {Object} request
 *   The request object that will be sent.
 * @param {Object} request.config
 *   [Required] The `config` message provides information to the recognizer
 *   that specifies how to process the request.
 *
 *   This object should have the same structure as [RecognitionConfig]{@link RecognitionConfig}
 * @param {Object} request.audio
 *   [Required] The audio data to be recognized.
 *
 *   This object should have the same structure as [RecognitionAudio]{@link RecognitionAudio}
 * @param {Object=} options
 *   Optional parameters. You can override the default settings for this call, e.g, timeout,
 *   retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details.
 * @param {function(?Error, ?Object)=} callback
 *   The function which will be called with the result of the API call.
 *
 *   The second parameter to the callback is an object representing [SyncRecognizeResponse]{@link SyncRecognizeResponse}.
 * @return {Promise} - The promise which resolves to an array.
 *   The first element of the array is an object representing [SyncRecognizeResponse]{@link SyncRecognizeResponse}.
 *   The promise has a method named "cancel" which cancels the ongoing API call.
 *
 * @example
 *
 * var client = speechV1beta1.speechClient();
 * var encoding = speechV1beta1.RecognitionConfig.AudioEncoding.FLAC;
 * var sampleRate = 44100;
 * var config = {
 *     encoding : encoding,
 *     sampleRate : sampleRate
 * };
 * var uri = 'gs://bucket_name/file_name.flac';
 * var audio = {
 *     uri : uri
 * };
 * var request = {
 *     config: config,
 *     audio: audio
 * };
 * client.syncRecognize(request).then(function(responses) {
 *     var response = responses[0];
 *     // doThingsWith(response)
 * }).catch(function(err) {
 *     console.error(err);
 * });
 */
SpeechClient.prototype.syncRecognize = function(request, options, callback) {
  if (options instanceof Function && callback === undefined) {
    callback = options;
    options = {};
  }
  if (options === undefined) {
    options = {};
  }

  return this._syncRecognize(request, options, callback);
};

/**
 * Perform asynchronous speech-recognition: receive results via the
 * google.longrunning.Operations interface. Returns either an
 * `Operation.error` or an `Operation.response` which contains
 * an `AsyncRecognizeResponse` message.
 *
 * @param {Object} request
 *   The request object that will be sent.
 * @param {Object} request.config
 *   [Required] The `config` message provides information to the recognizer
 *   that specifies how to process the request.
 *
 *   This object should have the same structure as [RecognitionConfig]{@link RecognitionConfig}
 * @param {Object} request.audio
 *   [Required] The audio data to be recognized.
 *
 *   This object should have the same structure as [RecognitionAudio]{@link RecognitionAudio}
 * @param {Object=} options
 *   Optional parameters. You can override the default settings for this call, e.g, timeout,
 *   retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details.
 * @param {function(?Error, ?Object)=} callback
 *   The function which will be called with the result of the API call.
 *
 *   The second parameter to the callback is a [gax.Operation]{@link https://googleapis.github.io/gax-nodejs/Operation} object.
 * @return {Promise} - The promise which resolves to an array.
 *   The first element of the array is a [gax.Operation]{@link https://googleapis.github.io/gax-nodejs/Operation} object.
 *   The promise has a method named "cancel" which cancels the ongoing API call.
 *
 * @example
 *
 * var client = speechV1beta1.speechClient();
 * var encoding = speechV1beta1.RecognitionConfig.AudioEncoding.FLAC;
 * var sampleRate = 44100;
 * var config = {
 *     encoding : encoding,
 *     sampleRate : sampleRate
 * };
 * var uri = 'gs://bucket_name/file_name.flac';
 * var audio = {
 *     uri : uri
 * };
 * var request = {
 *     config: config,
 *     audio: audio
 * };
 *
 * // Handle the operation using the promise pattern.
 * client.asyncRecognize(request).then(function(responses) {
 *     var operation = responses[0];
 *     var initialApiResponse = responses[1];
 *
 *     // Operation#promise starts polling for the completion of the LRO.
 *     return operation.promise();
 * }).then(function(responses) {
 *     // The final result of the operation.
 *     var result = responses[0];
 *
 *     // The metadata value of the completed operation.
 *     var metadata = responses[1];
 *
 *     // The response of the api call returning the complete operation.
 *     var finalApiResponse = responses[2];
 * }).catch(function(err) {
 *     console.error(err);
 * });
 *
 * // Handle the operation using the event emitter pattern.
 * client.asyncRecognize(request).then(function(responses) {
 *     var operation = responses[0];
 *     var initialApiResponse = responses[1];
 *
 *     // Adding a listener for the "complete" event starts polling for the
 *     // completion of the operation.
 *     operation.on('complete', function(result, metadata, finalApiResponse) {
 *       // doSomethingWith(result);
 *     });
 *
 *     // Adding a listener for the "progress" event causes the callback to be
 *     // called on any change in metadata when the operation is polled.
 *     operation.on('progress', function(metadata, apiResponse) {
 *       // doSomethingWith(metadata)
 *     })
 *
 *     // Adding a listener for the "error" event handles any errors found during polling.
 *     operation.on('error', function(err) {
 *       // throw(err);
 *     })
 * }).catch(function(err) {
 *     console.error(err);
 * });
 */
SpeechClient.prototype.asyncRecognize = function(request, options, callback) {
  if (options instanceof Function && callback === undefined) {
    callback = options;
    options = {};
  }
  if (options === undefined) {
    options = {};
  }

  return this._asyncRecognize(request, options, callback);
};

/**
 * Perform bidirectional streaming speech-recognition: receive results while
 * sending audio. This method is only available via the gRPC API (not REST).
 *
 * @param {Object=} options
 *   Optional parameters. You can override the default settings for this call, e.g, timeout,
 *   retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details.
 * @returns {Stream}
 *   An object stream which is both readable and writable. It accepts objects
 *   representing [StreamingRecognizeRequest]{@link StreamingRecognizeRequest} for write() method, and
 *   will emit objects representing [StreamingRecognizeResponse]{@link StreamingRecognizeResponse} on 'data' event asynchronously.
 *
 * @example
 *
 * var client = speechV1beta1.speechClient();
 * var stream = client.streamingRecognize().on('data', function(response) {
 *     // doThingsWith(response);
 * });
 * var request = {};
 * // Write request objects.
 * stream.write(request);
 */
SpeechClient.prototype.streamingRecognize = function(options) {
  if (options === undefined) {
    options = {};
  }

  return this._streamingRecognize(options);
};

function SpeechClientBuilder(gaxGrpc) {
  if (!(this instanceof SpeechClientBuilder)) {
    return new SpeechClientBuilder(gaxGrpc);
  }

  var speechClient = gaxGrpc.load([{
    root: require('google-proto-files')('..'),
    file: 'google/cloud/speech/v1beta1/cloud_speech.proto'
  }]);
  extend(this, speechClient.google.cloud.speech.v1beta1);

  /**
   * Build a new instance of {@link SpeechClient}.
   *
   * @param {Object=} opts - The optional parameters.
   * @param {String=} opts.servicePath
   *   The domain name of the API remote host.
   * @param {number=} opts.port
   *   The port on which to connect to the remote host.
   * @param {grpc.ClientCredentials=} opts.sslCreds
   *   A ClientCredentials for use with an SSL-enabled channel.
   * @param {Object=} opts.clientConfig
   *   The customized config to build the call settings. See
   *   {@link gax.constructSettings} for the format.
   */
  this.speechClient = function(opts) {
    return new SpeechClient(gaxGrpc, speechClient, opts);
  };
  extend(this.speechClient, SpeechClient);
}
module.exports = SpeechClientBuilder;
module.exports.SERVICE_ADDRESS = SERVICE_ADDRESS;
module.exports.ALL_SCOPES = ALL_SCOPES;


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

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.7"/>
<title>Documentation: readme</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="navtree.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

Documentation

For Arduino users

Main Page

Related Pages

Modules

Classes

Files

Examples

readme

Generated on Tue Oct 11 2016 14:29:37 for Documentation by

     1.8.7


text:
import {Component, ViewEncapsulation} from '@angular/core';
import {ionicBootstrap} from '../../../../../src';

@Component({template:'hi'})
class E2EPage{}

@Component({
  templateUrl: 'main.html',
  styleUrls: ['styles.css'],
  encapsulation: ViewEncapsulation.None
})
class E2EApp {
  root = E2EPage;
}

ionicBootstrap(E2EApp);


text:
// Copyright 2004-present Facebook. All Rights Reserved.

package com.facebook.stetho.inspector;

import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import android.util.Log;

import com.facebook.stetho.common.LogRedirector;
import com.facebook.stetho.common.Util;
import com.facebook.stetho.inspector.jsonrpc.JsonRpcException;
import com.facebook.stetho.inspector.jsonrpc.JsonRpcPeer;
import com.facebook.stetho.inspector.jsonrpc.PendingRequest;
import com.facebook.stetho.inspector.jsonrpc.protocol.JsonRpcError;
import com.facebook.stetho.inspector.jsonrpc.protocol.JsonRpcRequest;
import com.facebook.stetho.inspector.jsonrpc.protocol.JsonRpcResponse;
import com.facebook.stetho.inspector.protocol.ChromeDevtoolsDomain;
import com.facebook.stetho.json.ObjectMapper;
import com.facebook.stetho.websocket.CloseCodes;
import com.facebook.stetho.websocket.SimpleEndpoint;
import com.facebook.stetho.websocket.SimpleSession;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * Implements a limited version of the Chrome Debugger WebSocket protocol (using JSON-RPC 2.0).
 * The most up-to-date documentation can be found in the Blink source code:
 * protocol.json
 */
public class ChromeDevtoolsServer implements SimpleEndpoint {
  private static final String TAG = "ChromeDevtoolsServer";

  public static final String PATH = "/inspector";

  private final ObjectMapper mObjectMapper;
  private final MethodDispatcher mMethodDispatcher;
  private final Map<SimpleSession, JsonRpcPeer> mPeers =
      Collections.synchronizedMap(
          new HashMap<SimpleSession, JsonRpcPeer>());

  public ChromeDevtoolsServer(Iterable<ChromeDevtoolsDomain> domainModules) {
    mObjectMapper = new ObjectMapper();
    mMethodDispatcher = new MethodDispatcher(mObjectMapper, domainModules);
  }

  @Override
  public void onOpen(SimpleSession session) {
    LogRedirector.d(TAG, "onOpen");
    mPeers.put(session, new JsonRpcPeer(mObjectMapper, session));
  }

  @Override
  public void onClose(SimpleSession session, int code, String reasonPhrase) {
    LogRedirector.d(TAG, "onClose: reason=" + code + " " + reasonPhrase);

    JsonRpcPeer peer = mPeers.remove(session);
    if (peer != null) {
      peer.invokeDisconnectReceivers();
    }
  }

  @Override
  public void onMessage(SimpleSession session, byte[] message, int messageLen) {
    LogRedirector.d(TAG, "Ignoring binary message of length " + messageLen);
  }

  @Override
  public void onMessage(SimpleSession session, String message) {
    if (LogRedirector.isLoggable(TAG, Log.VERBOSE)) {
      LogRedirector.v(TAG, "onMessage: message=" + message);
    }
    try {
      JsonRpcPeer peer = mPeers.get(session);
      Util.throwIfNull(peer);

      handleRemoteMessage(peer, message);
    } catch (IOException e) {
      if (LogRedirector.isLoggable(TAG, Log.VERBOSE)) {
        LogRedirector.v(TAG, "Unexpected I/O exception processing message: " + e);
      }
      closeSafely(session, CloseCodes.UNEXPECTED_CONDITION, e.getClass().getSimpleName());
    } catch (MessageHandlingException e) {
      LogRedirector.i(TAG, "Message could not be processed by implementation: " + e);
      closeSafely(session, CloseCodes.UNEXPECTED_CONDITION, e.getClass().getSimpleName());
    } catch (JSONException e) {
      LogRedirector.v(TAG, "Unexpected JSON exception processing message", e);
      closeSafely(session, CloseCodes.UNEXPECTED_CONDITION, e.getClass().getSimpleName());
    }
  }

  private void closeSafely(SimpleSession session, int code, String reasonPhrase) {
    session.close(code, reasonPhrase);
  }

  private void handleRemoteMessage(JsonRpcPeer peer, String message)
      throws IOException, MessageHandlingException, JSONException {
    // Parse as a generic JSONObject first since we don't know if this is a request or response.
    JSONObject messageNode = new JSONObject(message);
    if (messageNode.has("method")) {
      handleRemoteRequest(peer, messageNode);
    } else if (messageNode.has("result")) {
      handleRemoteResponse(peer, messageNode);
    } else {
      throw new MessageHandlingException("Improper JSON-RPC message: " + message);
    }
  }

  private void handleRemoteRequest(JsonRpcPeer peer, JSONObject requestNode)
      throws MessageHandlingException {
    JsonRpcRequest request;
    request = mObjectMapper.convertValue(
        requestNode,
        JsonRpcRequest.class);

    JSONObject result = null;
    JSONObject error = null;
    try {
      result = mMethodDispatcher.dispatch(peer,
          request.method,
          request.params);
    } catch (JsonRpcException e) {
      logDispatchException(e);
      error = mObjectMapper.convertValue(e.getErrorMessage(), JSONObject.class);
    }
    if (request.id != null) {
      JsonRpcResponse response = new JsonRpcResponse();
      response.id = request.id;
      response.result = result;
      response.error = error;
      JSONObject jsonObject = mObjectMapper.convertValue(response, JSONObject.class);
      String responseString = jsonObject.toString();
      peer.getWebSocket().sendText(responseString);
    }
  }

  private static void logDispatchException(JsonRpcException e) {
    JsonRpcError errorMessage = e.getErrorMessage();
    switch (errorMessage.code) {
      case METHOD_NOT_FOUND:
        LogRedirector.d(TAG, "Method not implemented: " + errorMessage.message);
        break;
      default:
        LogRedirector.w(TAG, "Error processing remote message", e);
    }
  }

  private void handleRemoteResponse(JsonRpcPeer peer, JSONObject responseNode)
      throws MismatchedResponseException {
    JsonRpcResponse response = mObjectMapper.convertValue(
        responseNode,
        JsonRpcResponse.class);
    PendingRequest pendingRequest = peer.getAndRemovePendingRequest(response.id);
    if (pendingRequest == null) {
      throw new MismatchedResponseException(response.id);
    }
    if (pendingRequest.callback != null) {
      pendingRequest.callback.onResponse(peer, response);
    }
  }

  @Override
  public void onError(SimpleSession session, Throwable ex) {
    LogRedirector.e(TAG, "onError: ex=" + ex.toString());
  }
}


text:
ABSPATH=$(cd "$(dirname "$0")"; pwd)
cd $ABSPATH

#create build directory
path=./build/"$(date +%Y-%m%d-%H%M%S)"
mkdir -p $path

#prepare log file names
buildLogPath=../$path/buildLog.txt
testLogPath=../$path/testLog.txt

#build framework
echo "******Build framework************" 2>&1 | tee -a $buildLogPath
cd WindowsAzureMessaging
xcodebuild clean &> /dev/null
xcodebuild -scheme Framework -target Framework -configuration Release BUILD_DIR=./Build | sed '/setenv/d' 2>&1 | tee -a $buildLogPath

#check if build is succeed, zip bins and copy framework to BVT folder
if [ ! -e build/Release-iphonesimulator/WindowsAzureMessaging.framework ] ; then
    echo "****** Build framework failed ************" 2>&1 | tee -a $buildLogPath
    exit 1
fi
cd build/Release-iphonesimulator
ditto WindowsAzureMessaging.framework ../../../BVT/WindowsAzureMessaging.framework/
zip -r ../../../$path/WindowsAzureMessaging.framework.zip WindowsAzureMessaging.framework
cd ../../
echo "******Build framework SUCCEEDED ************" 2>&1 | tee -a $buildLogPath

#build and run CIT
echo "******Build and run CIT************" 2>&1 | tee -a $testLogPath
cd ../WindowsAzureMessagingTest/
xcodebuild -scheme WindowsAzureMessagingTest -destination 'platform=iOS Simulator,name=iPhone 6' test | sed '/Compile/d' | sed '/GenerateDSYMFile/d' | sed '/ProcessInfoPlistFile/d' | sed '/builtin/d' | sed '/Ld/d' | sed '/ld/d' |sed '/CopyStringsFile/d' | sed '/PhaseScript/d' | sed '/cd/d' | sed '/\/bin\/sh/d' | sed '/setenv/d' | sed '/\/Application/d' | sed '/^$/N;/^\n$/D' 2>&1 | tee -a $testLogPath

#check if test is succeed
grep " TEST SUCCEEDED " $testLogPath &> /dev/null
if [ "$?" != "0" ]; then
    echo "******Build or run CIT FAILED ************" 2>&1 | tee -a $testLogPath
    exit 1
fi
echo "******CIT SUCCEEDED ************" 2>&1 | tee -a $testLogPath


text:
using System;

namespace LLVMSharp.Compiler
{
    public class LLVMSharpException : Exception
    {
        public LLVMSharpException() { }

        public LLVMSharpException(string message) : base(message) { }
    }
}


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information

namespace DotNetNuke.Entities.Host
{
    using System.Net;

    /// <summary>
    /// IServerWebRequestAdapter used to get server's info when new server added into server collections.
    /// Also it can process the request when send to a server, like sync cache, detect server etc.
    /// </summary>
    public interface IServerWebRequestAdapter
    {
        /// <summary>
        /// Get the server's endpoint which can access the server directly.
        /// </summary>
        /// <returns></returns>
        string GetServerUrl();

        /// <summary>
        /// Get the server's unique id when server is behind affinity tool.
        /// </summary>
        /// <returns></returns>
        string GetServerUniqueId();

        /// <summary>
        /// Process Request before the request send to server.
        /// </summary>
        /// <param name="request">The Http Request Object.</param>
        /// <param name="server">The Server Info Object.</param>
        void ProcessRequest(HttpWebRequest request, ServerInfo server);

        /// <summary>
        /// Check whether response is return from correct server.
        /// </summary>
        /// <param name="response">The Http Response Object.</param>
        /// <param name="statusCode">Out status code if you think the status need change.</param>
        void CheckResponse(HttpWebResponse response, ServerInfo server, ref HttpStatusCode statusCode);
    }
}


text:
require 'glue/tasks/base_task'
require 'glue/util'
require 'nokogiri'
require 'pathname'

class Glue::PMD < Glue::BaseTask

  Glue::Tasks.add self
  include Glue::Util

  def initialize(trigger, tracker)
    super(trigger, tracker)
    @name = "PMD"
    @description = "PMD Source Code Analyzer"
    @stage = :code
    @labels << "code"
  end

  def run
    @tracker.options[:pmd_checks] ||= "java-basic,java-sunsecure"
    results_xml = runsystem(true,'bin/run.sh', 'pmd', '-d', "#{@trigger.path}", '-f', 'xml', '-R', "#{@tracker.options[:pmd_checks]}", :chdir => @tracker.options[:pmd_path])
    @results = Nokogiri::XML(results_xml).xpath('//file')
  end

  def analyze
    begin
      @results.each do |result|
        attributes = result.at_xpath('violation').attributes
        description = result.children.children.to_s.strip
        detail = "Ruleset: #{attributes['ruleset']}"
        source = {:scanner => @name, :file => result.attributes['name'].to_s.split(Pathname.new(@trigger.path).cleanpath.to_s)[1][1..-1], :line => attributes['beginline'].to_s, :code => "package: #{attributes['package'].to_s}\nclass: #{attributes['class'].to_s}\nmethod: #{attributes['method'].to_s}" }
        case attributes['priority'].value.to_i
        when 3
          sev = 1
        when 2
          sev = 2
        when 1
          sev = 3
        else
          sev = 0
        end
        fprint = fingerprint("#{description}#{detail}#{source}#{sev}")

        report description, detail, source, sev, fprint
      end
    rescue Exception => e
      Glue.warn e.message
      Glue.warn e.backtrace
    end
  end

  def supported?
    unless @tracker.options.has_key?(:pmd_path) and File.exist?("#{@tracker.options[:pmd_path]}/bin/run.sh")
      Glue.notify "#{@tracker.options[:pmd_path]}"
      Glue.notify "Install PMD from: https://pmd.github.io/"
      return false
    else
      return true
    end
  end

end


text:
require 'spec_helper'

module Sndacs

    describe Service do
        context "#buckets" do
            context "when buckets is empty" do
                before :each do
                    @service_empty = Sndacs::Service.new
                    @response_empty = Net::HTTPOK.new('1.1', '200', 'OK')
                    @buckets_empty_body = <<-EOEmptyBuckets
<?xml version="1.0" encoding="UTF-8"?>\n<ListAllMyBucketsResult xmlns="http://storage.grandcloud.cn/doc/2006-03-01/"><Owner><ID>123u1odhkhfoadf</ID> <DisplayName>JohnDoe</DisplayName></Owner><Buckets></Buckets></ListAllMyBucketsResult>
                    EOEmptyBuckets
                end

                it "should works" do
                    @service_empty.should_receive(:service_request).and_return(@response_empty)
                    @response_empty.should_receive(:body).and_return(@buckets_empty_body)

                    @service_empty.buckets.should == []
                end
            end

            context "when buckets is not empty" do
                before :each do
                    @service = Sndacs::Service.new
                end

                it "should works" do
                    @service.buckets.should be_instance_of(Array)
                end
            end
        end
    end

end


text:
'use strict';
var hapi = require('hapi'),
    pkg = require('./package.json'),
    app = new hapi.Server(),
    path = require('path'),
    fs = require('fs'),
    config = require('./config.json'),
    isUrl = require('is-url'),
    colors = require('colors'),
    ls = require('./lib/ls'),
    current = {name: 'Rock on air!'},
    launch = require('./lib/launch');

if (!isUrl(config.url)) {
    console.log(colors.red('You must set a valid url in config.json file!'));
    process.exit(1);
}

var list = ls(config);

launch.on('new', function (data) {
       current = data;
});

app.connection({ port: config.port });

app.route({
    method: 'GET',
    path: '/api/',
    handler: function (request, reply) {
        reply({
          current: current,
          list: list,
          freq: config.freq
        });
    }
});

app.route({
    method: 'GET',
    path: '/api/refresh/',
    handler: function (request, reply) {
        list = ls(config);
        launch.emit('refresh', list);
        reply(list);
    }
});

app.route({
    method: 'GET',
    path: '/vendor/{param*}',
    handler: {
        directory: {
            path: './vendor/'
        }
    }
});

app.route({
    method: 'GET',
    path: '/',
    handler: function (request, reply) {
        reply.file('index.html');
    }
});

app.route({
    method: 'GET',
    path: '/favicon.ico',
    handler: function (request, reply) {
        reply.file('favicon.ico');
    }
});

app.start(function () {
  launch.emit('start', list);
  require('check-update-github')({
      name: pkg.name,
      currentVersion: pkg.version,
      user: 'cedced19'
  }, function (err, lastestVersion, defaultMessage) {
      if (!err) {
        console.log(defaultMessage);
      }
  });
  console.log('Server running at\n  => ' + colors.green('http://localhost:' + config.port) + '\nCTRL + C to shutdown');
});

var io = require('socket.io').listen(app.listener);
io.sockets.on('connection', function(socket){
    launch.on('new', function (data) {
       socket.emit('new', data);
    });
});


text:
package     # hidden from PAUSE
    TheSchwartz::Schema::Result::Exitstatus;

use strict;
use warnings;

use base 'DBIx::Class';

__PACKAGE__->load_components("Core");
__PACKAGE__->table("exitstatus");
__PACKAGE__->add_columns(
  "jobid",
  {
    data_type => "INTEGER",
    default_value => undef,
    is_nullable => 0,
    size => undef,
  },
  "funcid",
  {
    data_type => "INT UNSIGNED",
    default_value => 0,
    is_nullable => 0,
    size => undef,
  },
  "status",
  {
    data_type => "SMALLINT UNSIGNED",
    default_value => undef,
    is_nullable => 1,
    size => undef,
  },
  "completion_time",
  {
    data_type => "INTEGER UNSIGNED",
    default_value => undef,
    is_nullable => 1,
    size => undef,
  },
  "delete_after",
  {
    data_type => "INTEGER UNSIGNED",
    default_value => undef,
    is_nullable => 1,
    size => undef,
  },
);
__PACKAGE__->set_primary_key("jobid");

# Created by DBIx::Class::Schema::Loader v0.04006 @ 2009-07-28 22:58:22
# DO NOT MODIFY THIS OR ANYTHING ABOVE! md5sum:jNza1JGUzAq+itzsJIT40g

# You can replace this text with custom content, and it will be preserved on regeneration
1;


text:
using System;
using CrossStitch.Stitch.Process.Stitch;

namespace HttpTest.Stitch
{
    public class Program
    {
        private static StitchMessageManager _manager;

        static void Main(string[] args)
        {
            _manager = new StitchMessageManager(args);
            try
            {
                _manager.Start();
                while (true)
                {
                    var msg = _manager.GetNextMessage();
                    if (msg == null)
                        continue;

                    Log($"Message received {msg.ChannelName}, {msg.Id}");
                    _manager.AckMessage(msg.Id);
                }
            }
            catch (Exception e)
            {
                Log(e.ToString());
            }
            Log("Stopped");
        }

        public static void Log(string s)
        {
            _manager.SendLogs(new[] { s });
            //File.AppendAllText("D:\\Test\\StitchStart.Client.txt", s + "\n");
        }
    }
}


text:
package com.joy.app.activity.sample;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;

import com.android.library.ui.fragment.BaseHttpRvFragment2;
import com.android.library.ui.webview.BaseWebViewActivity;
import com.android.library.view.recyclerview.ItemAddAnimator;
import com.android.library.view.recyclerview.ItemDecoration;
import com.joy.app.adapter.sample.RvLoadMoreAdapter;

import javax.inject.Inject;

/**
 * Created by Daisw on 16/6/8.
 */
public class MvpTestRvFragment extends BaseHttpRvFragment2 implements MvpTestRvView {

    @Inject
    MvpTestRvPresenter mPresenter;

    public static MvpTestRvFragment instantiate(Context context) {

        return (MvpTestRvFragment) Fragment.instantiate(context, MvpTestRvFragment.class.getName(), new Bundle());
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {

        ((TabTestActivity) getActivity()).component().inject(this);
        super.onActivityCreated(savedInstanceState);
        mPresenter.launchRefreshOnly();
    }

    @Override
    protected void initContentView() {

        mPresenter.setPageLimit(10);
        RvLoadMoreAdapter adapter = new RvLoadMoreAdapter();
        adapter.setOnItemClickListener((p, v, t) -> BaseWebViewActivity.startActivity(getActivity(), t.getUrl(), t.getTitle()));
        setAdapter(adapter);
        getRecyclerView().setItemAnimator(new ItemAddAnimator(mPresenter.getPageLimit()));
        getRecyclerView().addItemDecoration(
                new ItemDecoration.Builder(getActivity())
                        .dividerSize(0)
                        .verticalSpace(DP_1_PX * 10)
                        .paddingParent(DP_1_PX * 10)
                        .build());
    }

    @Override
    protected void doOnRetry() {

        mPresenter.launchRefreshOnly();
    }
}


text:
[Full Changelog](https://github.com/Yelp/puppet-uchiwa/compare/v1.0.0...v1.0.1)

**Closed issues:**

- Changelog [\#30](https://github.com/Yelp/puppet-uchiwa/issues/30)

**Merged pull requests:**

- Update apt key id [\#62](https://github.com/Yelp/puppet-uchiwa/pull/62) ([queeno](https://github.com/queeno))

## [v1.0.0](https://github.com/Yelp/puppet-uchiwa/tree/v1.0.0) (2015-12-04)
[Full Changelog](https://github.com/Yelp/puppet-uchiwa/compare/0.3.0...v1.0.0)

**Closed issues:**

- Support the users attribute [\#46](https://github.com/Yelp/puppet-uchiwa/issues/46)
- Duplicate Apt Resource [\#36](https://github.com/Yelp/puppet-uchiwa/issues/36)
- JSON acceptance tests are failing [\#33](https://github.com/Yelp/puppet-uchiwa/issues/33)
- New puppet-uchiwa release? [\#25](https://github.com/Yelp/puppet-uchiwa/issues/25)

**Merged pull requests:**

- Introducing users param in puppet-uchiwa [\#61](https://github.com/Yelp/puppet-uchiwa/pull/61) ([queeno](https://github.com/queeno))
- Update sensu apt repo. [\#59](https://github.com/Yelp/puppet-uchiwa/pull/59) ([liamjbennett](https://github.com/liamjbennett))
- Update apt::source to use puppetlabs-apt 2.0.0+ [\#56](https://github.com/Yelp/puppet-uchiwa/pull/56) ([zxjinn](https://github.com/zxjinn))
- add a test for sensu\_api\_endpoints param [\#54](https://github.com/Yelp/puppet-uchiwa/pull/54) ([somic](https://github.com/somic))
- Changed example code from manage\_repo to install\_repo [\#52](https://github.com/Yelp/puppet-uchiwa/pull/52) ([standaloneSA](https://github.com/standaloneSA))
- Try to cleanup doc and un-nest api definitions [\#51](https://github.com/Yelp/puppet-uchiwa/pull/51) ([solarkennedy](https://github.com/solarkennedy))
- Properly type port number [\#50](https://github.com/Yelp/puppet-uchiwa/pull/50) ([DoriftoShoes](https://github.com/DoriftoShoes))
- fix lint [\#44](https://github.com/Yelp/puppet-uchiwa/pull/44) ([bleuchtang](https://github.com/bleuchtang))
- Fix warning when installing sensu apt repository [\#41](https://github.com/Yelp/puppet-uchiwa/pull/41) ([KoeSystems](https://github.com/KoeSystems))
- apt module 2.0.0 breaks apt::source extensively [\#39](https://github.com/Yelp/puppet-uchiwa/pull/39) ([bobtfish](https://github.com/bobtfish))
- Fixing Erroneous validations [\#37](https://github.com/Yelp/puppet-uchiwa/pull/37) ([magmax](https://github.com/magmax))
- Fix tests [\#35](https://github.com/Yelp/puppet-uchiwa/pull/35) ([pauloconnor](https://github.com/pauloconnor))
- Notify uchiwa service when package changes [\#34](https://github.com/Yelp/puppet-uchiwa/pull/34) ([timmow](https://github.com/timmow))
- Ensure uchiwa.json is not world-readable [\#32](https://github.com/Yelp/puppet-uchiwa/pull/32) ([nhinds](https://github.com/nhinds))
- Fix some issues with 3.7.\* Puppet [\#31](https://github.com/Yelp/puppet-uchiwa/pull/31) ([tayzlor](https://github.com/tayzlor))
- missing default host for sensu API [\#29](https://github.com/Yelp/puppet-uchiwa/pull/29) ([n1tr0g](https://github.com/n1tr0g))

## [0.3.0](https://github.com/Yelp/puppet-uchiwa/tree/0.3.0) (2014-12-11)
[Full Changelog](https://github.com/Yelp/puppet-uchiwa/compare/0.2.7...0.3.0)

**Closed issues:**

- Obscure Datacat errors from Uchiwa module [\#24](https://github.com/Yelp/puppet-uchiwa/issues/24)

**Merged pull requests:**

- Remove artifact of PR \#21 [\#28](https://github.com/Yelp/puppet-uchiwa/pull/28) ([jbussdieker](https://github.com/jbussdieker))
- Add the insecure parameter to the default endpoint [\#27](https://github.com/Yelp/puppet-uchiwa/pull/27) ([jbussdieker](https://github.com/jbussdieker))
- Fix JSON syntax [\#26](https://github.com/Yelp/puppet-uchiwa/pull/26) ([jbussdieker](https://github.com/jbussdieker))
- The refresh param now takes seconds rather than ms [\#23](https://github.com/Yelp/puppet-uchiwa/pull/23) ([queeno](https://github.com/queeno))
- Remove the stats param from the puppet module [\#22](https://github.com/Yelp/puppet-uchiwa/pull/22) ([queeno](https://github.com/queeno))
- Remove uchiwa::api and pass API data via class params [\#21](https://github.com/Yelp/puppet-uchiwa/pull/21) ([queeno](https://github.com/queeno))
- Fix puppet-uchiwa beaker tests [\#20](https://github.com/Yelp/puppet-uchiwa/pull/20) ([queeno](https://github.com/queeno))

## [0.2.7](https://github.com/Yelp/puppet-uchiwa/tree/0.2.7) (2014-11-10)
[Full Changelog](https://github.com/Yelp/puppet-uchiwa/compare/0.2.6...0.2.7)

**Closed issues:**

- Am I being inappropriately redirected? [\#18](https://github.com/Yelp/puppet-uchiwa/issues/18)
- uchiwa is not under the yelp namespace on the forge. [\#16](https://github.com/Yelp/puppet-uchiwa/issues/16)

**Merged pull requests:**

- Add beaker tests [\#17](https://github.com/Yelp/puppet-uchiwa/pull/17) ([petems](https://github.com/petems))

## [0.2.6](https://github.com/Yelp/puppet-uchiwa/tree/0.2.6) (2014-09-25)
[Full Changelog](https://github.com/Yelp/puppet-uchiwa/compare/0.2.5...0.2.6)

**Closed issues:**

- Explanation of  "incompatible with previous versions of the Sensu-Puppet module" [\#14](https://github.com/Yelp/puppet-uchiwa/issues/14)
- Rename to puppet-uchiwa? [\#10](https://github.com/Yelp/puppet-uchiwa/issues/10)

**Merged pull requests:**

- remove unnecessary str2bool in install.pp since input is already validated [\#13](https://github.com/Yelp/puppet-uchiwa/pull/13) ([lreed](https://github.com/lreed))

## [0.2.5](https://github.com/Yelp/puppet-uchiwa/tree/0.2.5) (2014-09-11)
[Full Changelog](https://github.com/Yelp/puppet-uchiwa/compare/0.2.4...0.2.5)

**Closed issues:**

- Duplicate declaration apt [\#11](https://github.com/Yelp/puppet-uchiwa/issues/11)
- setting install\_repo to false breaks module [\#8](https://github.com/Yelp/puppet-uchiwa/issues/8)

**Merged pull requests:**

- use anchor pattern to fix containment of uchiwa class [\#12](https://github.com/Yelp/puppet-uchiwa/pull/12) ([LarsFronius](https://github.com/LarsFronius))
- Fix for issue \#8 with package requiring repo [\#9](https://github.com/Yelp/puppet-uchiwa/pull/9) ([bjwschaap](https://github.com/bjwschaap))

## [0.2.4](https://github.com/Yelp/puppet-uchiwa/tree/0.2.4) (2014-08-11)
[Full Changelog](https://github.com/Yelp/puppet-uchiwa/compare/0.2.3...0.2.4)

## [0.2.3](https://github.com/Yelp/puppet-uchiwa/tree/0.2.3) (2014-08-08)
[Full Changelog](https://github.com/Yelp/puppet-uchiwa/compare/0.2.2...0.2.3)

## [0.2.2](https://github.com/Yelp/puppet-uchiwa/tree/0.2.2) (2014-08-08)
[Full Changelog](https://github.com/Yelp/puppet-uchiwa/compare/0.2.0...0.2.2)

## [0.2.0](https://github.com/Yelp/puppet-uchiwa/tree/0.2.0) (2014-08-07)
[Full Changelog](https://github.com/Yelp/puppet-uchiwa/compare/0.1.1...0.2.0)

**Merged pull requests:**

- Fix template so it generates valid JSON [\#2](https://github.com/Yelp/puppet-uchiwa/pull/2) ([bodgit](https://github.com/bodgit))
- Clean up puppet-lint errors [\#1](https://github.com/Yelp/puppet-uchiwa/pull/1) ([bodgit](https://github.com/bodgit))

## [0.1.1](https://github.com/Yelp/puppet-uchiwa/tree/0.1.1) (2014-08-05)

\* *This Change Log was automatically generated by [github_changelog_generator](https://github.com/skywinder/Github-Changelog-Generator)*


text:
'use strict';

exports.padLength = function (length, multipler) {
  if (multipler === 0) {
    return length;
  }
  var mod = length % multipler;
  return mod === 0 ? length : length + multipler - mod;
};

exports.padBuffer = function (buff, multipler) {
  if (multipler === 0) {
    return buff;
  }

  var length = buff.length;
  var mod = length % multipler;
  if (mod === 0) {
    return buff;
  }

  var newLength = length + multipler - mod;
  var paded = new Buffer(newLength);
  buff.copy(paded, 0);
  paded.fill(0, buff.length, newLength);
  return paded;
};


text:
<img src="https://github.com/intracer/scalawiki/blob/master/resources/scalawiki.png?raw=true"  align="right" width="100" />
ScalaWiki logo is a combination of two images:
* [Scala spiral logo](https://github.com/scala/scala-lang/blob/master/resources/img/scala-spiral-noise-sm.png)
* [W letter](https://commons.wikimedia.org/wiki/File:Wikipedia%27s_W.svg)

Scala logo is subject to [Scala site license](scala-logo-license.md).
W letter image is in public domain


text: declare function require(moduleName: string): any;


text:
package com.github.abstractkim.rxbluetooth.Communication;

import android.bluetooth.BluetoothSocket;
import android.util.Log;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

/**
 * Created by Beomseok on 6/7/2017.
 */

public class CommunicationManager {
  public static final String TAG = CommunicationManager.class.getSimpleName();

  public enum ROLE{
    CLIENT(1, "client"),
    SERVER(2, "server");
    public final int state;
    public final String description;
    ROLE(final int s, final String d){
      state = s;
      description = d;
    }
  }

  public enum TYPE{
    BLUETOOTHCLASSIC(1,"Bluetooth Classic"),
    WIFIP2P(2,"Wi-Fi Direct(P2P)");

    public final int state;
    public final String description;
    TYPE(final int s, final String d){
      state = s;
      description = d;
    }
  }
  /**
   * Properties
   */
  private ROLE mRole = ROLE.CLIENT; //default is client;
  //for group chatting
  private HashMap<String, CommunicationUnit> mConnectedDeviceMap = new HashMap<>();
  private List<CommunicationUnit> mTempList = new ArrayList<>();
  private Disposable mBTServerDisposable;

  /**
   * sets and gets
   */
  public void setRole(ROLE r){
    mRole = r;
  }
  public ROLE getRole(){
    return mRole;
  }
  /*
  public void addCommunicationUnit(CommunicationUnit co){
    if(co != null){
      mConnectedDeviceMap.put(co.getDeviceName(), co);
    }
  }
  */
  /**
   * method related as server
   */
  public void startBluetoothServer(UUID u){
//    final UUID MY_UUID =
//        UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
    mBTServerDisposable = RxPeterBluetooth.createServerObservable("Server", u)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(
            new Consumer<BluetoothSocket>() {
              @Override public void accept(@NonNull BluetoothSocket bluetoothSocket)
                  throws Exception {
                Log.d(TAG, "A device is connecnt:" + bluetoothSocket.toString());
                mTempList.add(
                    new CommunicationUnit(
                        new BtClassicCommunicationStrategy(bluetoothSocket)));
              }
            });
  }

  public void clear(){
    mBTServerDisposable.dispose();
  }
}


text:
---
id: 587d7fb9367417b2b2512c12
title: Encadear auxiliares de consulta para restringir resultados de pesquisa
challengeType: 2
forumTopicId: 301533
dashedName: chain-search-query-helpers-to-narrow-search-results
---

# --description--

Se você não passar o callback como o último argumento para `Model.find()` (ou para outros métodos de pesquisa), a consulta não é executada. Você pode armazenar a consulta em uma variável para uso posterior. Esse tipo de objeto permite que você crie uma consulta usando a sintaxe de encadeamento. A pesquisa real do banco de dados é executada quando você finalmente encadear o método `.exec()`. Você sempre precisa passar seu callback para este último método. Existem muitos auxiliares de consulta. Aqui, usaremos os mais comuns.

# --instructions--

Modifique a função `queryChain` para que encontre pessoas que gostam do alimento especificado pela variável `foodToSearch`. Classifique-os por `name`, limite os resultados a dois documentos e oculte idade deles. Encadeie `.find()`, `.sort()`, `.limit()`, `.select()`e, então, `.exec()`. Passe a callback `done(err, data)` para `exec()`.

# --hints--

Você deve ter sucesso em encadear auxiliares de consulta

```js
(getUserInput) =>
  $.ajax({
    url: getUserInput('url') + '/_api/query-tools',
    type: 'POST',
    contentType: 'application/json',
    data: JSON.stringify([
      { name: 'Pablo', age: 26, favoriteFoods: ['burrito', 'hot-dog'] },
      { name: 'Bob', age: 23, favoriteFoods: ['pizza', 'nachos'] },
      { name: 'Ashley', age: 32, favoriteFoods: ['steak', 'burrito'] },
      { name: 'Mario', age: 51, favoriteFoods: ['burrito', 'prosciutto'] }
    ])
  }).then(
    (data) => {
      assert.isArray(data, 'the response should be an Array');
      assert.equal(
        data.length,
        2,
        'the data array length is not what expected'
      );
      assert.notProperty(
        data[0],
        'age',
        'The returned first item has too many properties'
      );
      assert.equal(
        data[0].name,
        'Ashley',
        'The returned first item name is not what expected'
      );
      assert.notProperty(
        data[1],
        'age',
        'The returned second item has too many properties'
      );
      assert.equal(
        data[1].name,
        'Mario',
        'The returned second item name is not what expected'
      );
    },
    (xhr) => {
      throw new Error(xhr.responseText);
    }
  );
```

# --solutions--

```js
/**
  Backend challenges don't need solutions,
  because they would need to be tested against a full working project.
  Please check our contributing guidelines to learn more.
*/
```


text:
package com.yahoo.validatar.common;

import java.math.BigDecimal;
import java.sql.Timestamp;

import static com.yahoo.validatar.common.TypeSystem.asTypedObject;

/**
 * Contains the various type specific {@link Operations}.
 * <p>
 * In general, we don't want lossy casting, or strange casting like a boolean to a short etc.
 * But we will follow the basic Java widening primitive rules.
 * https://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html
 * </p>
 * Exceptions:
 * Timestamp to and from Long will do a millis since epoch
 */
public class Operators {
    public static class BooleanOperator implements Operations {
        @Override
        public TypedObject or(TypedObject first, TypedObject second) {
            return asTypedObject((Boolean) first.data || (Boolean) second.data);
        }

        @Override
        public TypedObject and(TypedObject first, TypedObject second) {
            return asTypedObject((Boolean) first.data && (Boolean) second.data);
        }

        @Override
        public TypedObject not(TypedObject object) {
            return asTypedObject(!(Boolean) object.data);
        }

        @Override
        public TypedObject cast(TypedObject object) {
            switch (object.type) {
                case STRING:
                    object.data = Boolean.valueOf((String) object.data);
                    break;
                case BOOLEAN:
                    break;
                case LONG:
                case DOUBLE:
                case DECIMAL:
                case TIMESTAMP:
                    return null;
            }
            object.type = TypeSystem.Type.BOOLEAN;
            return object;
        }
    }

    public static class LongOperator implements Operations {
        @Override
        public TypedObject add(TypedObject first, TypedObject second) {
            return asTypedObject((Long) first.data + (Long) second.data);
        }

        @Override
        public TypedObject subtract(TypedObject first, TypedObject second) {
            return asTypedObject((Long) first.data - (Long) second.data);
        }

        @Override
        public TypedObject multiply(TypedObject first, TypedObject second) {
            return asTypedObject((Long) first.data * (Long) second.data);
        }

        @Override
        public TypedObject divide(TypedObject first, TypedObject second) {
            return asTypedObject((Long) first.data / (Long) second.data);
        }

        @Override
        public TypedObject modulus(TypedObject first, TypedObject second) {
            return asTypedObject((Long) first.data % (Long) second.data);
        }

        @Override
        public TypedObject cast(TypedObject object) {
            switch (object.type) {
                case STRING:
                    object.data = Long.valueOf((String) object.data);
                    break;
                case LONG:
                    break;
                case TIMESTAMP:
                    object.data = ((Timestamp) object.data).getTime();
                    break;
                case DOUBLE:
                case DECIMAL:
                case BOOLEAN:
                    return null;
            }
            object.type = TypeSystem.Type.LONG;
            return object;
        }
    }
    public static class DoubleOperator implements Operations {
        @Override
        public TypedObject add(TypedObject first, TypedObject second) {
            return asTypedObject((Double) first.data + (Double) second.data);
        }

        @Override
        public TypedObject subtract(TypedObject first, TypedObject second) {
            return asTypedObject((Double) first.data - (Double) second.data);
        }

        @Override
        public TypedObject multiply(TypedObject first, TypedObject second) {
            return asTypedObject((Double) first.data * (Double) second.data);
        }

        @Override
        public TypedObject divide(TypedObject first, TypedObject second) {
            return asTypedObject((Double) first.data / (Double) second.data);
        }

        @Override
        public TypedObject cast(TypedObject object) {
            switch (object.type) {
                case STRING:
                    object.data = Double.valueOf((String) object.data);
                    break;
                case DOUBLE:
                    break;
                case LONG:
                    object.data = ((Long) object.data).doubleValue();
                    break;
                case DECIMAL:
                case BOOLEAN:
                case TIMESTAMP:
                    return null;
            }
            object.type = TypeSystem.Type.DOUBLE;
            return object;
        }
    }

    public static class StringOperator implements Operations {
        @Override
        public TypedObject add(TypedObject first, TypedObject second) {
            return asTypedObject((String) first.data + (String) second.data);
        }

        @Override
        public TypedObject cast(TypedObject object) {
            switch (object.type) {
                case STRING:
                    break;
                case LONG:
                    object.data = ((Long) object.data).toString();
                    break;
                case DOUBLE:
                    object.data = ((Double) object.data).toString();
                    break;
                case DECIMAL:
                    object.data = ((BigDecimal) object.data).toString();
                    break;
                case BOOLEAN:
                    object.data = ((Boolean) object.data).toString();
                    break;
                case TIMESTAMP:
                    return null;
            }
            object.type = TypeSystem.Type.STRING;
            return object;
        }
    }

    public static class DecimalOperator implements Operations {
        @Override
        public TypedObject add(TypedObject first, TypedObject second) {
            return asTypedObject(((BigDecimal) first.data).add((BigDecimal) second.data));
        }

        @Override
        public TypedObject subtract(TypedObject first, TypedObject second) {
            return asTypedObject(((BigDecimal) first.data).subtract((BigDecimal) second.data));
        }

        @Override
        public TypedObject multiply(TypedObject first, TypedObject second) {
            return asTypedObject(((BigDecimal) first.data).multiply((BigDecimal) second.data));
        }

        @Override
        public TypedObject divide(TypedObject first, TypedObject second) {
            return asTypedObject(((BigDecimal) first.data).divide((BigDecimal) second.data));
        }

        @Override
        public TypedObject modulus(TypedObject first, TypedObject second) {
            return asTypedObject(((BigDecimal) first.data).divideAndRemainder((BigDecimal) second.data)[1]);
        }

        @Override
        public TypedObject cast(TypedObject object) {
            switch (object.type) {
                case STRING:
                    object.data = new BigDecimal((String) object.data);
                    break;
                case LONG:
                    object.data = BigDecimal.valueOf((Long) object.data);
                    break;
                case DOUBLE:
                    object.data = BigDecimal.valueOf((Double) object.data);
                    break;
                case DECIMAL:
                    break;
                case TIMESTAMP:
                    object.data = BigDecimal.valueOf(((Timestamp) object.data).getTime());
                    break;
                case BOOLEAN:
                    return null;
            }
            object.type = TypeSystem.Type.DECIMAL;
            return object;
        }
    }

    public static class TimestampOperator implements Operations {
        @Override
        public TypedObject add(TypedObject first, TypedObject second) {
            return asTypedObject(new Timestamp(((Timestamp) first.data).getTime() + ((Timestamp) second.data).getTime()));
        }

        @Override
        public TypedObject subtract(TypedObject first, TypedObject second) {
            return asTypedObject(new Timestamp(((Timestamp) first.data).getTime() - ((Timestamp) second.data).getTime()));
        }

        @Override
        public TypedObject multiply(TypedObject first, TypedObject second) {
            return asTypedObject(new Timestamp(((Timestamp) first.data).getTime() * ((Timestamp) second.data).getTime()));
        }

        @Override
        public TypedObject divide(TypedObject first, TypedObject second) {
            return asTypedObject(new Timestamp(((Timestamp) first.data).getTime() / ((Timestamp) second.data).getTime()));
        }

        @Override
        public TypedObject modulus(TypedObject first, TypedObject second) {
            return asTypedObject(new Timestamp(((Timestamp) first.data).getTime() % ((Timestamp) second.data).getTime()));
        }

        @Override
        public TypedObject cast(TypedObject object) {
            switch (object.type) {
                case LONG:
                    object.data = new Timestamp((Long) object.data);
                    break;
                case TIMESTAMP:
                    break;
                case STRING:
                case DOUBLE:
                case DECIMAL:
                case BOOLEAN:
                    return null;
            }
            object.type = TypeSystem.Type.TIMESTAMP;
            return object;
        }
    }
}


text:
package com.solace.samples.java.snippets;

import com.solace.messaging.PubSubPlusClientException;
import com.solace.messaging.publisher.DirectMessagePublisher;
import com.solace.messaging.receiver.PersistentMessageReceiver;
import com.solace.messaging.util.LifecycleControl.TerminationNotificationListener;

/**
 * Sampler for handling of receiver and publisher interruption/termination cases
 */

public class HowToHandlePublisherReceiverInterruptions {

  /**
   * Example how to configure persistent receiver with a listener for notifications about
   * unsolicited interruptions/terminations
   *
   * @param receiver message receiver (can be started or not)
   */
  public static void configureTerminationNotificationListenerOnPersistentReceiver(
      PersistentMessageReceiver receiver) {

    final TerminationNotificationListener terminationNotificationListener = (terminationEvent) -> {
      final String message = terminationEvent.getMessage();
      final long timestamp = terminationEvent.getTimestamp();
      final PubSubPlusClientException e = terminationEvent.getCause();
    };

    receiver.setTerminationNotificationListener(terminationNotificationListener);
  }

  /**
   * Example how to configure direct receiver with a listener for notifications about unsolicited
   * interruptions
   *
   * @param receiver message receiver (can be started or not)
   */
  public static void configureTerminationNotificationListenerOnDirectReceiver(
      DirectMessagePublisher receiver) {

    final TerminationNotificationListener terminationNotificationListener = (terminationEvent) -> {
      final String message = terminationEvent.getMessage();
      final long timestamp = terminationEvent.getTimestamp();
      final PubSubPlusClientException e = terminationEvent.getCause();
    };

    receiver.setTerminationNotificationListener(terminationNotificationListener);
  }

}


text:
package org.apache.batik.extension.svg;

import org.apache.batik.dom.AbstractDocument;
import org.apache.batik.dom.svg.SVGOMTextPositioningElement;
import org.w3c.dom.Node;

/**
 * This class implements a regular polygon extension to SVG
 *
 * @author Thomas DeWeese
 * @version $Id$
 */
public class FlowLineElement
    extends    SVGOMTextPositioningElement
    implements BatikExtConstants {

    /**
     * Creates a new BatikRegularPolygonElement object.
     */
    protected FlowLineElement() {
    }

    /**
     * Creates a new BatikRegularPolygonElement object.
     * @param prefix The namespace prefix.
     * @param owner The owner document.
     */
    public FlowLineElement(String prefix, AbstractDocument owner) {
        super(prefix, owner);
    }

    /**
     * DOM: Implements {@link org.w3c.dom.Node#getLocalName()}.
     */
    public String getLocalName() {
        return BATIK_EXT_FLOW_LINE_TAG;
    }

    /**
     * DOM: Implements {@link org.w3c.dom.Node#getNamespaceURI()}.
     */
    public String getNamespaceURI() {
        return BATIK_12_NAMESPACE_URI;
    }

    /**
     * Returns a new uninitialized instance of this object's class.
     */
    protected Node newNode() {
        return new FlowLineElement();
    }
}


text:
<?php defined('SYSPATH') or die('No direct script access.');

class Model_Post extends ORM {
    protected $_table_name = 'posts';

}


text:
package git4idea.ui.branch;

import com.intellij.ide.ui.ToolbarSettings;
import com.intellij.openapi.actionSystem.ActionUpdateThread;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.project.DumbAwareAction;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.registry.Registry;
import git4idea.branch.GitBranchUtil;
import git4idea.repo.GitRepository;
import git4idea.repo.GitRepositoryManager;
import org.jetbrains.annotations.NotNull;

/**
 * <p>
 * Invokes a {@link GitBranchPopup} to checkout and control Git branches.
 * </p>
 */
public class GitBranchesAction extends DumbAwareAction {

  @Override
  public void actionPerformed(@NotNull AnActionEvent e) {
    Project project = e.getRequiredData(CommonDataKeys.PROJECT);
    GitRepository repository = GitBranchUtil.guessRepositoryForOperation(project, e.getDataContext());
    if (repository != null) {
      if (Registry.is("git.branches.popup.tree", false)) {
        GitBranchesTreePopup.show(project, repository);
      }
      else {
        GitBranchPopup.getInstance(project, repository, e.getDataContext()).asListPopup().showCenteredInCurrentWindow(project);
      }
    }
  }

  @Override
  public void update(@NotNull AnActionEvent e) {
    Project project = e.getProject();
    e.getPresentation().setEnabledAndVisible(project != null && !project.isDisposed() &&
                                             !GitRepositoryManager.getInstance(project).getRepositories().isEmpty() &&
                                             !ToolbarSettings.getInstance().isAvailable());
  }

  @Override
  public @NotNull ActionUpdateThread getActionUpdateThread() {
    return ActionUpdateThread.BGT;
  }
}


text:
<!DOCTYPE html>
<html>
<head>
    <title>GH-1275</title>
</head>
<body>
<input id="input1"/>
<input id="input2"/>

<script>
    window.focus();

    const input1 = document.getElementById('input1');
    const input2 = document.getElementById('input2');

    input1.addEventListener('keydown', function () {
        input1.style.display = 'none';

        window.setTimeout(function () {
            input2.focus();
        });
    });

    input1.addEventListener('blur', function (e) {
        if (e.srcElement.tagName && e.srcElement.tagName.toLowerCase() === 'input')
            document.activeElement.blur();
    });

</script>

</body>
</html>


text:
<?php

namespace Drupal\views\Tests\Plugin;

/**
 * Tests the OPML feed style plugin.
 *
 * @group views
 * @see \Drupal\views\Plugin\views\style\Opml
 */
class StyleOpmlTest extends PluginTestBase {

  /**
   * Views used by this test.
   *
   * @var array
   */
  public static $testViews = ['test_style_opml'];

  /**
   * Modules to enable.
   *
   * @var array
   */
  public static $modules = ['aggregator'];

  /**
   * {@inheritdoc}
   */
  protected function setUp() {
    parent::setUp();

    $this->enableViewsTestModule();

    $admin_user = $this->drupalCreateUser(['administer news feeds']);
    $this->drupalLogin($admin_user);
  }

  /**
   * Tests the rendered output.
   */
  public function testOpmlOutput() {
    // Create a test feed.
    $values = [
      'title' => $this->randomMachineName(10),
      'url' => 'http://example.com/rss.xml',
      'refresh' => '900',
    ];
    $feed = $this->container->get('entity.manager')
      ->getStorage('aggregator_feed')
      ->create($values);
    $feed->save();

    $this->drupalGet('test-feed-opml-style');
    $outline = $this->xpath('//outline[1]');
    $this->assertEqual($outline[0]['type'], 'rss', 'The correct type attribute is used for rss OPML.');
    $this->assertEqual($outline[0]['text'], $feed->label(), 'The correct text attribute is used for rss OPML.');
    $this->assertEqual($outline[0]['xmlurl'], $feed->getUrl(), 'The correct xmlUrl attribute is used for rss OPML.');

    $view = $this->container->get('entity.manager')
      ->getStorage('view')
      ->load('test_style_opml');
    $display = &$view->getDisplay('feed_1');
    $display['display_options']['row']['options']['type_field'] = 'link';
    $display['display_options']['row']['options']['url_field'] = 'url';
    $view->save();

    $this->drupalGet('test-feed-opml-style');
    $outline = $this->xpath('//outline[1]');
    $this->assertEqual($outline[0]['type'], 'link', 'The correct type attribute is used for link OPML.');
    $this->assertEqual($outline[0]['text'], $feed->label(), 'The correct text attribute is used for link OPML.');
    $this->assertEqual($outline[0]['url'], $feed->getUrl(), 'The correct URL attribute is used for link OPML.');
    // xmlUrl should not be present when type is link.
    $this->assertNull($outline[0]['xmlUrl'], 'The xmlUrl attribute is not used for link OPML.');
  }

}


text:
import { DOMOutputSpecArray, Mark as ProsemirrorMark } from 'prosemirror-model';
import { EditorCommand } from '@t/spec';
import { clsWithMdPrefix } from '@/utils/dom';
import Mark from '@/spec/mark';
import { encodeMarkdownText, escapeMarkdownText } from '@/utils/encoder';
import { createTextNode } from '@/helper/manipulation';
import { resolveSelectionPos } from '../helper/pos';

type CommandType = 'image' | 'link';

interface Payload {
  linkText: string;
  altText: string;
  linkUrl: string;
  imageUrl: string;
}

export class Link extends Mark {
  get name() {
    return 'link';
  }

  get schema() {
    return {
      attrs: {
        url: { default: false },
        desc: { default: false },
      },
      toDOM({ attrs }: ProsemirrorMark): DOMOutputSpecArray {
        const { url, desc } = attrs;
        let classNames = 'link';

        if (url) {
          classNames += '|link-url|marked-text';
        }
        if (desc) {
          classNames += '|link-desc|marked-text';
        }

        return ['span', { class: clsWithMdPrefix(...classNames.split('|')) }, 0];
      },
    };
  }

  private addLinkOrImage(commandType: CommandType): EditorCommand<Payload> {
    return (payload) => ({ selection, tr, schema }, dispatch) => {
      const [from, to] = resolveSelectionPos(selection);
      const { linkText, altText, linkUrl, imageUrl } = payload!;
      let text = linkText;
      let url = linkUrl;
      let syntax = '';

      if (commandType === 'image') {
        text = altText;
        url = imageUrl;
        syntax = '!';
      }

      text = escapeMarkdownText(text);
      url = encodeMarkdownText(url);
      syntax += `[${text}](${url})`;

      dispatch!(tr.replaceWith(from, to, createTextNode(schema, syntax)));

      return true;
    };
  }

  commands() {
    return {
      addImage: this.addLinkOrImage('image'),
      addLink: this.addLinkOrImage('link'),
    };
  }
}


text:
from django.dispatch import receiver
from django.db import IntegrityError
import logging

from oscar.core.loading import get_class, get_classes
UserSearch, UserRecord, ProductRecord, UserProductView = get_classes(
    'analytics.models', ['UserSearch', 'UserRecord', 'ProductRecord',
                         'UserProductView'])
product_viewed, product_search = get_classes('catalogue.signals',
                                             ['product_viewed',
                                              'product_search'])
basket_addition = get_class('basket.signals', 'basket_addition')
order_placed = get_class('order.signals', 'order_placed')

# Helpers

logger = logging.getLogger('oscar.analytics')

def _record_product_view(product):
    try:
        record, __ = ProductRecord.objects.get_or_create(product=product)
        record.num_views += 1
        record.save()
    except IntegrityError:
        # get_or_create sometimes fails due to MySQL's weird transactions, fail
        # silently
        logger.error("IntegrityError on ProductRecord.objects."
                     "get_or_create(product=product)")

def _record_user_product_view(user, product):
    if user.is_authenticated():
        # Update user record
        try:
            record, __ = UserRecord.objects.get_or_create(user=user)
            record.num_product_views += 1
            record.save()
        except IntegrityError:
            logger.error("IntegrityError on UserRecord.objects."
                         "get_or_create(user=user)")

        # Add user product view record
        UserProductView.objects.create(product=product, user=user)

def _record_basket_addition(product):
    try:
        record, __ = ProductRecord.objects.get_or_create(product=product)
        record.num_basket_additions += 1
        record.save()
    except IntegrityError:
        logger.error("IntegrityError on ProductRecord.objects."
                     "get_or_create(product=product)")

def _record_user_basket_addition(user, product):
    if user.is_authenticated():
        try:
            record, __ = UserRecord.objects.get_or_create(user=user)
            record.num_basket_additions += 1
            record.save()
        except IntegrityError:
            logger.error("IntegrityError on UserRecord.objects."
                         "get_or_create(user=user)")

def _record_products_in_order(order):
    for line in order.lines.all():
        try:
            record, __ = ProductRecord.objects.get_or_create(
                product=line.product)
            record.num_purchases += line.quantity
            record.save()
        except IntegrityError:
            logger.error("IntegrityError on ProductRecord.objects."
                         "get_or_create(product=product)")

def _record_user_order(user, order):
    if user.is_authenticated():
        try:
            record, __ = UserRecord.objects.get_or_create(user=user)
            record.num_orders += 1
            record.num_order_lines += order.num_lines
            record.num_order_items += order.num_items
            record.total_spent += order.total_incl_tax
            record.date_last_order = order.date_placed
            record.save()
        except IntegrityError:
            logger.error("IntegrityError on UserRecord.objects."
                         "get_or_create(user=user)")

def _record_user_product_search(user, query):
    if user.is_authenticated():
        UserSearch._default_manager.create(user=user, query=query)

# Receivers

@receiver(product_viewed)
def receive_product_view(sender, product, user, **kwargs):
    if kwargs.get('raw', False):
        return
    _record_product_view(product)
    _record_user_product_view(user, product)

@receiver(product_search)
def receive_product_search(sender, query, user, **kwargs):
    if kwargs.get('raw', False):
        return
    _record_user_product_search(user, query)

@receiver(basket_addition)
def receive_basket_addition(sender, product, user, **kwargs):
    if kwargs.get('raw', False):
        return
    _record_basket_addition(product)
    _record_user_basket_addition(user, product)

@receiver(order_placed)
def receive_order_placed(sender, order, user, **kwargs):
    if kwargs.get('raw', False):
        return
    _record_products_in_order(order)
    if user:
        _record_user_order(user, order)


text:
package bson

import (
	"bytes"
	"encoding/hex"
	"encoding/json"
	"errors"
	"fmt"
)

// ErrInvalidHex indicates that a hex string cannot be converted to an ObjectID.
var ErrInvalidHex = errors.New("the provided hex string is not a valid ObjectID")

// ObjectID is the BSON ObjectID type.
type ObjectID [12]byte

// NilObjectID is the zero value for ObjectID.
var NilObjectID ObjectID

// Hex returns the hex encoding of the ObjectID as a string.
func (id ObjectID) Hex() string {
	return hex.EncodeToString(id[:])
}

func (id ObjectID) String() string {
	return fmt.Sprintf("ObjectID(%q)", id.Hex())
}

// IsZero returns true if id is the empty ObjectID.
func (id ObjectID) IsZero() bool {
	return bytes.Equal(id[:], NilObjectID[:])
}

// ObjectIDFromHex creates a new ObjectID from a hex string. It returns an error if the hex string is not a
// valid ObjectID.
func ObjectIDFromHex(s string) (ObjectID, error) {
	b, err := hex.DecodeString(s)
	if err != nil {
		return NilObjectID, err
	}

	if len(b) != 12 {
		return NilObjectID, ErrInvalidHex
	}

	var oid [12]byte
	copy(oid[:], b[:])

	return oid, nil
}

// MarshalJSON returns the ObjectID as a string
func (id ObjectID) MarshalJSON() ([]byte, error) {
	return json.Marshal(id.Hex())
}

// UnmarshalJSON populates the byte slice with the ObjectID. If the byte slice is 24 bytes long, it
// will be populated with the hex representation of the ObjectID. If the byte slice is twelve bytes
// long, it will be populated with the BSON representation of the ObjectID. This method also accepts empty strings and
// decodes them as NilObjectID. For any other inputs, an error will be returned.
func (id *ObjectID) UnmarshalJSON(b []byte) error {
	// Ignore "null" to keep parity with the standard library. Decoding a JSON null into a non-pointer ObjectID field
	// will leave the field unchanged. For pointer values, encoding/json will set the pointer to nil and will not
	// enter the UnmarshalJSON hook.
	if string(b) == "null" {
		return nil
	}

	var err error
	switch len(b) {
	case 12:
		copy(id[:], b)
	default:
		// Extended JSON
		var res interface{}
		err := json.Unmarshal(b, &res)
		if err != nil {
			return err
		}
		str, ok := res.(string)
		if !ok {
			m, ok := res.(map[string]interface{})
			if !ok {
				return errors.New("not an extended JSON ObjectID")
			}
			oid, ok := m["$oid"]
			if !ok {
				return errors.New("not an extended JSON ObjectID")
			}
			str, ok = oid.(string)
			if !ok {
				return errors.New("not an extended JSON ObjectID")
			}
		}

		// An empty string is not a valid ObjectID, but we treat it as a special value that decodes as NilObjectID.
		if len(str) == 0 {
			copy(id[:], NilObjectID[:])
			return nil
		}

		if len(str) != 24 {
			return fmt.Errorf("cannot unmarshal into an ObjectID, the length must be 24 but it is %d", len(str))
		}

		_, err = hex.Decode(id[:], []byte(str))
		if err != nil {
			return err
		}
	}

	return err
}


text:
CREATE TABLE Job (id INT AUTO_INCREMENT NOT NULL, title VARCHAR(255) NOT NULL, type VARCHAR(100) NOT NULL, description VARCHAR(255) NOT NULL, createdAt DATETIME NOT NULL, expiresAt DATETIME NOT NULL, PRIMARY KEY(id)) ENGINE = InnoDB;
CREATE TABLE Gallery (id INT AUTO_INCREMENT NOT NULL, title VARCHAR(255) NOT NULL, PRIMARY KEY(id)) ENGINE = InnoDB;
CREATE TABLE StaticContent (id INT AUTO_INCREMENT NOT NULL, name VARCHAR(255) NOT NULL, title VARCHAR(255) NOT NULL, content LONGTEXT NOT NULL, updatedAt DATETIME NOT NULL, PRIMARY KEY(id)) ENGINE = InnoDB;
CREATE TABLE Image (id INT AUTO_INCREMENT NOT NULL, image_id INT DEFAULT NULL, title VARCHAR(255) NOT NULL, filename VARCHAR(255) NOT NULL, thumbname VARCHAR(255) NOT NULL, INDEX IDX_4FC2B5B3DA5256D (image_id), PRIMARY KEY(id)) ENGINE = InnoDB;
CREATE TABLE Download (id INT AUTO_INCREMENT NOT NULL, title VARCHAR(255) NOT NULL, type VARCHAR(100) NOT NULL, description VARCHAR(255) NOT NULL, createdAt DATETIME NOT NULL, serverFileName VARCHAR(255) NOT NULL, mimeType VARCHAR(255) NOT NULL, originalFileName VARCHAR(255) NOT NULL, PRIMARY KEY(id)) ENGINE = InnoDB;
CREATE TABLE BlogPost (id INT AUTO_INCREMENT NOT NULL, title VARCHAR(250) NOT NULL, content VARCHAR(255) NOT NULL, publishedAt DATETIME NOT NULL, createdAt DATETIME NOT NULL, PRIMARY KEY(id)) ENGINE = InnoDB;
CREATE TABLE Member (id INT AUTO_INCREMENT NOT NULL, email VARCHAR(100) NOT NULL, name VARCHAR(100) NOT NULL, password VARCHAR(40) NOT NULL, salt VARCHAR(32) NOT NULL, roles LONGTEXT NOT NULL COMMENT '(DC2Type:array)', registrationKey VARCHAR(32) NOT NULL, forumId INT NOT NULL, wikiId INT NOT NULL, PRIMARY KEY(id)) ENGINE = InnoDB;
CREATE TABLE Email (id INT AUTO_INCREMENT NOT NULL, member_id INT DEFAULT NULL, title VARCHAR(255) NOT NULL, content LONGTEXT NOT NULL, INDEX IDX_265353707597D3FE (member_id), PRIMARY KEY(id)) ENGINE = InnoDB;
ALTER TABLE Image ADD CONSTRAINT FK_4FC2B5B3DA5256D FOREIGN KEY (image_id) REFERENCES Gallery(id);
ALTER TABLE Email ADD CONSTRAINT FK_265353707597D3FE FOREIGN KEY (member_id) REFERENCES Member(id)
;
ALTER TABLE Member ADD paid TINYINT(1) NOT NULL
;
ALTER TABLE Member ADD info VARCHAR(255) NOT NULL, ADD function INT NOT NULL
;
ALTER TABLE Member ADD image INT DEFAULT NULL;
ALTER TABLE Member ADD CONSTRAINT FK_7748FF4EC53D045F FOREIGN KEY (image) REFERENCES Image(id);
CREATE UNIQUE INDEX UNIQ_7748FF4EC53D045F ON Member (image)
;
ALTER TABLE Member DROP FOREIGN KEY FK_7748FF4EC53D045F;
DROP INDEX UNIQ_7748FF4EC53D045F ON Member;
ALTER TABLE Member CHANGE image image_id INT DEFAULT NULL;
ALTER TABLE Member ADD CONSTRAINT FK_7748FF4E3DA5256D FOREIGN KEY (image_id) REFERENCES Image(id);
CREATE UNIQUE INDEX UNIQ_7748FF4E3DA5256D ON Member (image_id)
;
CREATE TABLE MembershipApplication (id INT AUTO_INCREMENT NOT NULL, supporting TINYINT(1) NOT NULL, student TINYINT(1) NOT NULL, male TINYINT(1) NOT NULL, title VARCHAR(255) NOT NULL, surename VARCHAR(255) NOT NULL, lastname VARCHAR(255) NOT NULL, street VARCHAR(255) NOT NULL, postalCode VARCHAR(255) NOT NULL, city VARCHAR(255) NOT NULL, email VARCHAR(255) NOT NULL, phone VARCHAR(255) NOT NULL, comment LONGTEXT NOT NULL, PRIMARY KEY(id)) ENGINE = InnoDB
;
ALTER TABLE MembershipApplication CHANGE title title VARCHAR(255) DEFAULT NULL, CHANGE phone phone VARCHAR(255) DEFAULT NULL, CHANGE comment comment LONGTEXT DEFAULT NULL
;
ALTER TABLE Job CHANGE description description LONGTEXT NOT NULL;
ALTER TABLE BlogPost CHANGE content content LONGTEXT NOT NULL;
ALTER TABLE Member CHANGE info info LONGTEXT NOT NULL
;
ALTER TABLE Member CHANGE info info LONGTEXT DEFAULT NULL
;
ALTER TABLE Gallery ADD description LONGTEXT NOT NULL
;
ALTER TABLE Gallery CHANGE description description LONGTEXT DEFAULT NULL
;
ALTER TABLE Image CHANGE title title VARCHAR(255) DEFAULT NULL
;


text:
package au.gov.amsa.ais.parse;

public final class Util {

    private Util() {

    }

    // decimal focused optimization, digits only
    public static int parseInt(String s) {
        if (s == null) {
            throw new NumberFormatException("null");
        }
        int result = 0;
        for (int i = 0; i < s.length(); i++) {
            int ch = s.charAt(i);
            if (ch < '0' || ch > '9') {
                throw new NumberFormatException("not a digit: " + ch);
            }
            result = result * 10 + ch - '0';
        }
        return result;
    }

    // decimal focused optimization, digits only
    public static long parseLong(String s) {
        if (s == null) {
            throw new NumberFormatException("null");
        }
        long result = 0;
        for (int i = 0; i < s.length(); i++) {
            int ch = s.charAt(i);
            if (ch < '0' || ch > '9') {
                throw new NumberFormatException("not a digit: " + ch);
            }
            result = result * 10 + ch - '0';
        }
        return result;
    }
}


text:
<?php

namespace Google\Ads\GoogleAds\Lib;

use Google\ApiCore\Call;

/**
 * Participant in processing a server request and response.
 *
 * This can be replaced by Psr\Http\Server\MiddlewareInterface (PSR-15) when GAX PHP supports it.
 */
abstract class GoogleAdsMiddlewareAbstract
{
    /** @var callable */
    private $nextHandler;

    /**
     * Creates a new Google Ads middleware.
     *
     * @param callable|null $nextHandler the next handler
     */
    public function __construct(callable $nextHandler = null)
    {
        $this->nextHandler = $nextHandler;
    }

    /**
     * Sets the next handler.
     *
     * @param callable $nextHandler the next handler
     * @return self
     */
    final public function withNextHandler(callable $nextHandler)
    {
        $this->nextHandler = $nextHandler;
        return $this;
    }

    /**
     * Gets the next handler.
     *
     * @return callable|null the next handler
     */
    final protected function getNextHandler()
    {
        return $this->nextHandler;
    }

    /**
     * Processes an incoming server request in order to produce a response.
     *
     * If unable to produce the response itself, it may delegate to the provided
     * request handler to do so.
     *
     * @param Call $call the current request
     * @param array $options the optional parameters
     * @return mixed the response
     */
    abstract public function __invoke(Call $call, array $options);
}


text:
package org.vaadin.vol.client.wrappers.layer;

import org.vaadin.vol.client.wrappers.Bounds;
import org.vaadin.vol.client.wrappers.Size;

public class ImageLayer extends Layer {

    protected ImageLayer() {
    };

    public native final static ImageLayer create(String display, String url,
            Bounds b, Size s, boolean isBaseLayer)
    /*-{
       var options = {};
    	options.isBaseLayer = isBaseLayer;
    	return new $wnd.OpenLayers.Layer.Image(display, url, b, s, options);
    }-*/;

}


text:
var express = require('express'),
  bodyParser = require('body-parser'),
  cookieParser = require('cookie-parser'),
  session = require('express-session'),
  passport = require('passport');

module.exports = function(app, config, router) {
  app.use(cookieParser());

  app.use(bodyParser.urlencoded({
    extended: true
  }));

  app.use(bodyParser.json());

  app.use(session({
    secret: 'riff-raff',
    saveUninitialized: true,
    resave: true
  }));

  app.use(passport.initialize());
  app.use(passport.session());
  app.use(express.static(config.rootPath + '/public'));

  app.use(router);
};