text:
package com.jmolsmobile.landscapevideocapture.view;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.drawable.Drawable;
import android.support.test.InstrumentationRegistry;
import android.support.test.annotation.UiThreadTest;
import android.support.test.rule.UiThreadTestRule;
import android.support.test.runner.AndroidJUnit4;
import android.view.View;
import android.widget.ImageView;

import com.jmolsmobile.landscapevideocapture.MockitoTestCase;
import com.jmolsmobile.landscapevideocapture.R;

import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;

import static junit.framework.TestCase.assertNotNull;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertTrue;

@RunWith(AndroidJUnit4.class)
public class VideoCaptureViewTest extends MockitoTestCase {

    @Rule
    public final UiThreadTestRule uiThread = new UiThreadTestRule();

    @UiThreadTest
    @Test
    public void initializeClass() {
        Context targetContext = InstrumentationRegistry.getTargetContext();
        new VideoCaptureView(targetContext);
    }

    @UiThreadTest
    @Test
    public void viewShoudlBeInflated() {
        final VideoCaptureView videoCaptureView = new VideoCaptureView(InstrumentationRegistry.getTargetContext());
        final View container = videoCaptureView.findViewById(R.id.videocapture_container_rl);
        assertNotNull(container);
    }

    @UiThreadTest
    @Test
    public void shouldNotCrashWhenListenerIsNull() {
        final VideoCaptureView videoCaptureView = new VideoCaptureView(InstrumentationRegistry.getTargetContext());
        final View recordBtn = videoCaptureView.findViewById(R.id.videocapture_recordbtn_iv);
        recordBtn.performClick();
    }

    @UiThreadTest
    @Test
    public void recordBtnShouldNotifyListener() {
        final RecordingButtonInterface mockBtnInterface = Mockito.mock(RecordingButtonInterface.class);
        performClickOnButton(R.id.videocapture_recordbtn_iv, mockBtnInterface);
        Mockito.verify(mockBtnInterface, Mockito.times(1)).onRecordButtonClicked();
    }

    @UiThreadTest
    @Test
    public void acceptBtnShouldNotifyListener() {
        final RecordingButtonInterface mockBtnInterface = Mockito.mock(RecordingButtonInterface.class);
        performClickOnButton(R.id.videocapture_acceptbtn_iv, mockBtnInterface);
        Mockito.verify(mockBtnInterface, Mockito.times(1)).onAcceptButtonClicked();
    }

    @UiThreadTest
    @Test
    public void declineBtnShouldNotifyListener() {
        final RecordingButtonInterface mockBtnInterface = Mockito.mock(RecordingButtonInterface.class);
        performClickOnButton(R.id.videocapture_declinebtn_iv, mockBtnInterface);
        Mockito.verify(mockBtnInterface, Mockito.times(1)).onDeclineButtonClicked();
    }

    @UiThreadTest
    @Test
    public void uiShouldBeNotRecordingByDefault() {
        final VideoCaptureView videoCaptureView = new VideoCaptureView(InstrumentationRegistry.getTargetContext());
        checkUINotRecording(videoCaptureView);
    }

    @UiThreadTest
    @Test
    public void uiAfterUpdateNotRecording() {
        final VideoCaptureView videoCaptureView = new VideoCaptureView(InstrumentationRegistry.getTargetContext());
        videoCaptureView.updateUINotRecording();
        checkUINotRecording(videoCaptureView);
    }

    @UiThreadTest
    @Test
    public void uiAfterUpdateOngoing() {
        final VideoCaptureView videoCaptureView = new VideoCaptureView(InstrumentationRegistry.getTargetContext());
        videoCaptureView.updateUIRecordingOngoing();
        assertTrue(videoCaptureView.findViewById(R.id.videocapture_recordbtn_iv).isSelected());
        checkVisibility(videoCaptureView, R.id.videocapture_recordbtn_iv, View.VISIBLE);
        checkVisibility(videoCaptureView, R.id.videocapture_acceptbtn_iv, View.GONE);
        checkVisibility(videoCaptureView, R.id.videocapture_declinebtn_iv, View.GONE);
        checkVisibility(videoCaptureView, R.id.videocapture_preview_iv, View.GONE);
        checkVisibility(videoCaptureView, R.id.videocapture_preview_sv, View.VISIBLE);
    }

    @UiThreadTest
    @Test
    public void uiAfterUpdateFinishedBitmapNull() {
        final VideoCaptureView videoCaptureView = new VideoCaptureView(InstrumentationRegistry.getTargetContext());
        videoCaptureView.updateUIRecordingFinished(null);
        checkVisibility(videoCaptureView, R.id.videocapture_recordbtn_iv, View.INVISIBLE);
        checkVisibility(videoCaptureView, R.id.videocapture_acceptbtn_iv, View.VISIBLE);
        checkVisibility(videoCaptureView, R.id.videocapture_declinebtn_iv, View.VISIBLE);
        checkVisibility(videoCaptureView, R.id.videocapture_preview_iv, View.VISIBLE);
        checkVisibility(videoCaptureView, R.id.videocapture_preview_sv, View.GONE);
    }

    @UiThreadTest
    @Test
    public void uiAfterUpdateFinishedBitmapNotNull() {
        final VideoCaptureView videoCaptureView = new VideoCaptureView(InstrumentationRegistry.getTargetContext());
        final ImageView imageView = (ImageView) videoCaptureView.findViewById(R.id.videocapture_preview_iv);
        final Drawable background = imageView.getDrawable();
        videoCaptureView.updateUIRecordingFinished(Bitmap.createBitmap(10, 10, Config.ARGB_4444));
        checkVisibility(videoCaptureView, R.id.videocapture_recordbtn_iv, View.INVISIBLE);
        checkVisibility(videoCaptureView, R.id.videocapture_acceptbtn_iv, View.VISIBLE);
        checkVisibility(videoCaptureView, R.id.videocapture_declinebtn_iv, View.VISIBLE);
        checkVisibility(videoCaptureView, R.id.videocapture_preview_iv, View.VISIBLE);
        checkVisibility(videoCaptureView, R.id.videocapture_preview_sv, View.GONE);
        assertNotSame(background, imageView.getDrawable());
    }

    @UiThreadTest
    @Test
    public void surfaceViewShouldNotBeNull() {
        final VideoCaptureView videoCaptureView = new VideoCaptureView(InstrumentationRegistry.getTargetContext());
        assertNotNull(videoCaptureView.getPreviewSurfaceHolder());
    }

    private void checkUINotRecording(final VideoCaptureView videoCaptureView) {
        assertFalse(videoCaptureView.findViewById(R.id.videocapture_recordbtn_iv).isSelected());
        checkVisibility(videoCaptureView, R.id.videocapture_recordbtn_iv, View.VISIBLE);
        checkVisibility(videoCaptureView, R.id.videocapture_acceptbtn_iv, View.GONE);
        checkVisibility(videoCaptureView, R.id.videocapture_declinebtn_iv, View.GONE);
        checkVisibility(videoCaptureView, R.id.videocapture_preview_iv, View.GONE);
        checkVisibility(videoCaptureView, R.id.videocapture_preview_sv, View.VISIBLE);
    }

    private void checkVisibility(final VideoCaptureView videoCaptureView, int videocaptureRecordbtnIv, int visible) {
        assertTrue(videoCaptureView.findViewById(videocaptureRecordbtnIv).getVisibility() == visible);
    }

    private void performClickOnButton(int btnResourceId, final RecordingButtonInterface mockBtnInterface) {
        final VideoCaptureView videoCaptureView = new VideoCaptureView(InstrumentationRegistry.getTargetContext());
        videoCaptureView.setRecordingButtonInterface(mockBtnInterface);
        final View btn = videoCaptureView.findViewById(btnResourceId);
        btn.performClick();
    }

}


text:
package org.locationtech.geogig.api.plumbing.diff;

import java.util.Stack;

import org.eclipse.jdt.annotation.Nullable;

import org.locationtech.geogig.api.Bounded;
import org.locationtech.geogig.api.Bucket;
import org.locationtech.geogig.api.Node;
import org.locationtech.geogig.api.RevTree;
import org.locationtech.geogig.storage.ObjectDatabase;

import com.google.common.base.Predicate;
import com.google.common.base.Predicates;

/**
 * Provides a means to "walk" the differences between two {@link RevTree trees} in depth-first order
 * and emit diff events to a {@link Consumer}.
 * <p>
 * Skipping whole subtrees can be achieved by passing a {@link Predicate Predicate<Bounded>} that
 * will be evaluated for each pair of tree {@link Node nodes} or {@link Bucket buckets}.
 */
public class PostOrderDiffWalk {
    private static final Predicate<Bounded> ACEPT_ALL = Predicates.alwaysTrue();

    private PreOrderDiffWalk inOrder;

    public PostOrderDiffWalk(RevTree left, RevTree right, ObjectDatabase leftSource,
            ObjectDatabase rightSource) {
        this.inOrder = new PreOrderDiffWalk(left, right, leftSource, rightSource);
    }

    public final void walk(final Consumer consumer) {
        walk(ACEPT_ALL, consumer);
    }

    public final void walk(final Predicate<Bounded> filter, final Consumer consumer) {
        DepthFirstConsumer depthFirstConsumer = new DepthFirstConsumer(filter, consumer);
        inOrder.walk(depthFirstConsumer);
    }

    private static class DepthFirstConsumer implements
            org.locationtech.geogig.api.plumbing.diff.PreOrderDiffWalk.Consumer {

        private static final class Entry {
            private Bounded left;

            private Bounded right;

            private int bucketIndex;

            private int bucketDepth;

            private boolean accepted;

            static Entry tree(Node left, Node right, boolean accepted) {
                Entry e = new Entry();
                e.left = left;
                e.right = right;
                e.accepted = accepted;
                return e;
            }

            static Entry bucket(int bucketIndex, int bucketDepth, Bucket left, Bucket right,
                    boolean accepted) {
                Entry e = new Entry();
                e.left = left;
                e.right = right;
                e.bucketIndex = bucketIndex;
                e.bucketDepth = bucketDepth;
                e.accepted = accepted;
                return e;
            }

            public void apply(Consumer consumer) {
                if (accepted) {
                    if (isNode()) {
                        consumer.tree((Node) left, (Node) right);
                    } else {
                        consumer.bucket(bucketIndex, bucketDepth, (Bucket) left, (Bucket) right);
                    }
                }
            }

            private boolean isNode() {
                return left == null ? right instanceof Node : left instanceof Node;
            }
        }

        private Stack<Entry> stack = new Stack<>();

        private Predicate<Bounded> filter;

        private Consumer consumer;

        public DepthFirstConsumer(Predicate<Bounded> filter, Consumer consumer) {
            this.filter = filter;
            this.consumer = consumer;
        }

        @Override
        public void feature(Node left, Node right) {
            boolean accept = filter.apply(left) || filter.apply(right);
            if (accept) {
                consumer.feature(left, right);
            }
        }

        @Override
        public boolean tree(Node left, Node right) {
            boolean accept = filter.apply(left) || filter.apply(right);
            stack.push(Entry.tree(left, right, accept));
            return accept;
        }

        @Override
        public void endTree(Node left, Node right) {
            Entry entry = stack.pop();
            entry.apply(consumer);
        }

        @Override
        public boolean bucket(int bucketIndex, int bucketDepth, Bucket left, Bucket right) {
            boolean accept = filter.apply(left) || filter.apply(right);
            stack.push(Entry.bucket(bucketIndex, bucketDepth, left, right, accept));
            return accept;
        }

        @Override
        public void endBucket(int bucketIndex, int bucketDepth, Bucket left, Bucket right) {
            Entry entry = stack.pop();
            entry.apply(consumer);
        }
    }

    public static interface Consumer {

        public abstract void feature(@Nullable final Node left, @Nullable final Node right);

        public abstract void tree(@Nullable final Node left, @Nullable final Node right);

        public abstract void bucket(final int bucketIndex, final int bucketDepth,
                @Nullable final Bucket left, @Nullable final Bucket right);

    }
}

redpajama_set_name: RedPajamaGithub


text:
#import "NSObject-Protocol.h"

@protocol SKUIItemListTableDelegate <NSObject>

@optional
- (void)itemListWillBeginDragging:(id)arg1;
- (void)itemList:(id)arg1 willDisplayCellForItem:(id)arg2 atIndexPath:(id)arg3;
- (void)itemList:(id)arg1 didRemoveItemAtIndexPath:(id)arg2;
- (id)itemList:(id)arg1 didConfirmItemOfferForItem:(id)arg2 atIndexPath:(id)arg3;
- (void)itemList:(id)arg1 didDeselectItem:(id)arg2 atIndexPath:(id)arg3;
- (void)itemList:(id)arg1 didSelectItem:(id)arg2 atIndexPath:(id)arg3;
@end


text:
import { Component } from '@angular/core';
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';

@Component({
    selector: 'auction-carousel',
    templateUrl: 'carousel.html'
})
export default class CarouselComponent {

    imgHtml: SafeHtml;

    constructor(private sanitizer: DomSanitizer) {
      this.imgHtml = sanitizer.bypassSecurityTrustHtml(`
        <img class="slide-image" src="http://placehold.it/800x300" alt=""/>`);
    }
}


text:
__author__ = 'Traphix'

import os
import time, struct

from vpp_papi import VPP

# vpp = VPP()
# vpp.connect("test")

# def papi_event_handler(name, reply):
#     if name == 'vnet_interface_counters':
#         print "**********************************"
#         print "[+] in papi_event_handler"
#         print "[+] Msg name =", name
#         print reply
#         # print struct.unpack("B", result.data)
#         # index = range(reply.first_sw_if_index, reply.count)
#         # rx_packets = [reply.data[i].packets for i in index]
#         # rx_bytes = [reply.data[i].bytes for i in index]
#         # print rx_packets
#         # print rx_bytes

# vpp.register_event_callback(papi_event_handler)

# vpp.api.want_stats(enable_disable=1, pid=888)

class MSVPP():
    def __init__(self, app=None, msc=None):
        self.app = app
        self.msc = msc
        self.vpp = VPP()
    def connect(self):
        self.vpp.connect('msc')
        self.vpp.register_event_callback(self)
        self.vpp.api.want_stats(enable_disable=1, pid=521)
    def __call__(self, name, reply):
        if name == 'vnet_interface_counters':
            self.refresh_vpp_interface_counter(reply)
    def refresh_vpp_interface_counter(self, reply):
        print reply

# a = MSVPP()

# a.connect()


text:
module Wukong
  module Streamer

    #
    # Bin and order a partitioned subset of keys
    #
    # For each record, appends a
    #
    # * numbering, from 0..(n-1).  Each element gets a distinct numbering based on
    #   the order seen at the reducer; elements with identical keys might have
    #   different numbering on different runs.
    #
    # * rank, a number within 1..n giving the "place" of each value. Each element
    #   receives a successive (and thus unique) numbering, but all elements with
    #   the same key share the same rank. The first element for a given rank has
    #
    #     (rank == numbering + 1)
    #
    # * bin, a number assigning keys by rank into a smaller number of groups.  You
    #   must supply command line arguments
    #
    #     --bins=[number] --total_count=[number]
    #
    #   giving the number of groups and predicting in advance the total number of
    #   records. (Or override the bin assignment method to use your own damn
    #   strategy).
    #
    # If your data looked (in order) as follows, and 4 bins were requested:
    #
    #   data:       1   1   1 2.3   7  69  79  79  80  81  81
    #   numbering:  0   1   2   3   4   5   6   7   8   9  10
    #   rank:       1   1   1   4   5   6   7   7   9  10  10
    #   4-bin:      1   1   1   2   2   3   3   3   4   4   4
    #
    # If instead 100 bins were requested,
    #
    #   data:       1   1   1 2.3   7  69  79  79  80  81  81
    #   numbering:  0   1   2   3   4   5   6   7   8   9  10
    #   rank:       1   1   1   4   5   6   7   7   9  10  10
    #   100-bin:    1   1   1  28  37  46  55  55  73  82  91
    #
    # Note most of the bins are empty, and that the
    #
    # --------------------------------------------------------------------------
    #
    # Note that in this implementation each reducer numbers its own subset of
    # elements from 1..total_count. If you want to number your whole dataset,
    # you'll have to set @:reduce_tasks => 1@ in your Script's
    # Script#default_options.
    #
    # You might feel a bit better about yourself if you can bin several fields
    # (or subsets) at once. The :partition_fields option to Wukong::Script
    # (which requests a KeyFieldBasedPartitioner) can be used to route different
    # subsets to (possibly) distinct reducers.
    #
    # See the [examples/rank_and_bin_fields.rb] example script for an
    # implementation of this. (And note the thing you have to do in case one
    # reducer sees multiple partitions).
    #
    # It would surely be best to use a total sort and supply each reducer with the
    # initial rank of its run.
    #
    class RankAndBinReducer < Wukong::Streamer::Base
      attr_accessor :bin_size
      def initialize options
        super options
        configure_bins! options
        reset_order_params!
      end

      # ===========================================================================
      #
      # Order parameters (numbering, bin and rank)
      #

      #
      # Key used to assign ranking -- elements with identical keys have identical
      # rank.
      #
      def get_key *args
        args.first
      end

      def reset_order_params!
        @last_key  = nil
        @numbering = 0
        @rank      = 1
      end

      #
      # The ranking is the "place" of each value: each element receives a
      # successive (and thus unique) numbering, but all elements with the same key
      # share the same rank. The first element for a given rank has
      #
      #   (rank == numbering + 1)
      #
      def get_rank key
        if @last_key != key
          @rank       = @numbering + 1
          @last_key   = key
        end
        @rank
      end

      #
      # Set the bin from the current rank
      # elements with identical keys land in identical bins.
      #
      def get_bin rank
        ((rank-0.5) / bin_size ).floor + 1
      end

      #
      # Return the numbering, rank and bin for the given key
      #
      def get_order_params key
        numbering   = @numbering # use un-incremented value
        rank        = get_rank key
        bin         = get_bin  rank
        @numbering += 1
        [numbering, rank, bin]
      end

      def configure_bins! options
        case
        when options[:bins]
          total_count = options[:total_count].to_f
          bins        = options[:bins].to_i
          unless total_count && (total_count != 0) then raise "To set the bin (%ile) size using --bins, we need to know the total count in advance. Please supply the total_count option." end
          self.bin_size = (total_count / bins)
          # $stderr.puts "Splitting %s records into %s bins of size %f. First element gets bin %d, last gets bin %d, median gets bin %d/%d" %
          #   [total_count, bins, bin_size, get_bin(1), get_bin(total_count), get_bin(((total_count+1)/2.0).floor), get_bin(((total_count+1)/2.0).ceil)]
        else
          raise "Please specify a number of --bins= and a --total_count= or your own strategy to bin the ranked items."
        end
      end

      def process *fields
        numbering, rank, bin = get_order_params(get_key(*fields))
        yield fields.to_flat + [numbering, rank, bin]
      end
    end

  end
end


text:
using JeffWilcox.Utilities.Silverlight;
using Newtonsoft.Json;
using Q42.HueApi.Interfaces;
using Q42.HueApi.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace Q42.HueApi
{
  /// <summary>
  /// https://developers.meethue.com/develop/hue-api/remote-authentication-oauth/
  /// </summary>
  public class RemoteAuthenticationClient : IRemoteAuthenticationClient
  {
    private readonly string _clientId;
    private readonly string _clientSecret;
    private readonly string _appId;

    private AccessTokenResponse? _lastAuthorizationResponse;
    private HttpClient _httpClient;

    /// <summary>
    ///
    /// </summary>
    /// <param name="clientId">Identifies the client that is making the request. The value passed in this parameter must exactly match the value you receive from hue. Note that the underscore is not used in the clientid name of this parameter.</param>
    /// <param name="clientSecret">The clientsecret you have received from Hue when registering for the Hue Remote API.</param>
    /// <param name="appId">Identifies the app that is making the request. The value passed in this parameter must exactly match the value you receive from hue.</param>
    public RemoteAuthenticationClient(string clientId, string clientSecret, string appId)
    {
      if (string.IsNullOrEmpty(clientId))
        throw new ArgumentNullException(nameof(clientId));
      if (string.IsNullOrEmpty(clientSecret))
        throw new ArgumentNullException(nameof(clientSecret));
      if (string.IsNullOrEmpty(appId))
        throw new ArgumentNullException(nameof(appId));

      _clientId = clientId;
      _clientSecret = clientSecret;
      _appId = appId;
      _httpClient = new HttpClient();
    }

    public void Initialize(AccessTokenResponse accessTokenResponse)
    {
      _lastAuthorizationResponse = accessTokenResponse;
    }

    /// <summary>
    /// Authorization request
    /// </summary>
    /// <param name="state">Provides any state that might be useful to your application upon receipt of the response. The Hue Authorization Server roundtrips this parameter, so your application receives the same value it sent. To mitigate against cross-site request forgery (CSRF), it is strongly recommended to include an anti-forgery token in the state, and confirm it in the response. One good choice for a state token is a string of 30 or so characters constructed using a high-quality random-number generator.</param>
    /// <param name="deviceId">The device identifier must be a unique identifier for the app or device accessing the Hue Remote API.</param>
    /// <param name="deviceName">The device name should be the name of the app or device accessing the remote API. The devicename is used in the user's "My Apps" overview in the Hue Account (visualized as: "<app name> on <devicename>"). If not present, deviceid is also used for devicename. The <app name> is the application name you provided to us the moment you requested access to the remote API.</param>
    /// <param name="responseType">The response_type value must be "code".</param>
    /// <returns></returns>
    public Uri BuildAuthorizeUri(string state, string deviceId, string? deviceName = null, string responseType = "code")
    {
      if (string.IsNullOrEmpty(responseType))
        throw new ArgumentNullException(nameof(responseType));

      string url = string.Format("https://api.meethue.com/v2/oauth2/authorize?client_id={0}&response_type={5}&state={1}&appid={3}&deviceid={2}&devicename={4}", _clientId, state, deviceId, _appId, deviceName, responseType);

      return new Uri(url);
    }

    public RemoteAuthorizeResponse ProcessAuthorizeResponse(string responseData)
    {
      string url = responseData;
      string[] parts = url.Split(new char[] { '?', '&' });

      RemoteAuthorizeResponse result = new RemoteAuthorizeResponse();

      foreach (var part in parts)
      {
        string[] nv = part.Split(new char[] { '=' });
        if (nv.Length == 2)
        {
          if (nv[0].ToLower() == "code")
            result.Code = nv[1];
          if (nv[0].ToLower() == "state")
            result.State = nv[1];
        }
      }

      return result;
    }

    /// <summary>
    /// Get an access token
    /// </summary>
    /// <param name="code">Code retreived using ProcessAuthorizeResponse</param>
    /// <returns></returns>
    public async Task<AccessTokenResponse?> GetToken(string code)
    {
      var requestUri = new Uri($"https://api.meethue.com/v2/oauth2/token");

      var formParameters = new Dictionary<string, string> {
        {"code", code},
        {"grant_type", "authorization_code"}
      };

      var formContent = new FormUrlEncodedContent(formParameters);

      //Do a token request
      var responseTask = await _httpClient.PostAsync(requestUri, formContent).ConfigureAwait(false);
      var responseString = responseTask.Headers.WwwAuthenticate.ToString();
      responseString = responseString.Replace("Digest ", string.Empty);
      string nonce = GetNonce(responseString);

      if (!string.IsNullOrEmpty(nonce))
      {
        //Get token
        var request = new HttpRequestMessage()
        {
          RequestUri = requestUri,
          Method = HttpMethod.Post,
          Content = formContent
        };

        //Build request
        string response = CalculateHash(_clientId, _clientSecret, nonce, "/v2/oauth2/token");
        string param = $"username=\"{_clientId}\", {responseString}, uri=\"/v2/oauth2/token\", response=\"{response}\"";

        request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Digest", param);

        var accessTokenResponse = await _httpClient.SendAsync(request).ConfigureAwait(false);
        var accessTokenResponseString = await accessTokenResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

        var accessToken = JsonConvert.DeserializeObject<AccessTokenResponse>(accessTokenResponseString);

        _lastAuthorizationResponse = accessToken;

        return accessToken;

      }

      return null;
    }

    private static string GetNonce(string r)
    {
      //Find the nonce
      int startNonce = r.IndexOf("nonce=") + 7;
      int endNonce = r.IndexOf("\"", startNonce);
      string nonce = r.Substring(startNonce, endNonce - startNonce);

      return nonce;
    }

    public async Task<AccessTokenResponse?> RefreshToken(string refreshToken)
    {
      var requestUri = new Uri("https://api.meethue.com/v2/oauth2/token");

      var formParameters = new Dictionary<string, string> {
        {"refresh_token", refreshToken},
        {"grant_type", "refresh_token"}
      };

      var formContent = new FormUrlEncodedContent(formParameters);

      //Do a token request
      var responseTask = await _httpClient.PostAsync(requestUri, formContent).ConfigureAwait(false);
      var responseString = responseTask.Headers.WwwAuthenticate.ToString();
      responseString = responseString.Replace("Digest ", string.Empty);
      string nonce = GetNonce(responseString);

      if (!string.IsNullOrEmpty(nonce))
      {
        //Get token
        var request = new HttpRequestMessage()
        {
          RequestUri = requestUri,
          Method = HttpMethod.Post,
          Content = formContent
        };

        //Build request
        string response = CalculateHash(_clientId, _clientSecret, nonce, "/v2/oauth2/token");
        string param = $"username=\"{_clientId}\", {responseString}, uri=\"/v2/oauth2/token\", response=\"{response}\"";

        request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Digest", param);

        var accessTokenResponse = await _httpClient.SendAsync(request).ConfigureAwait(false);
        var accessTokenResponseString = await accessTokenResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

        var accessToken = JsonConvert.DeserializeObject<AccessTokenResponse>(accessTokenResponseString);

        _lastAuthorizationResponse = accessToken;

        return accessToken;
      }

      return null;
    }

    /// <summary>
    /// Calculate hash for token request
    /// </summary>
    /// <param name="clientId"></param>
    /// <param name="clientSecret"></param>
    /// <param name="nonce"></param>
    /// <returns></returns>
    private static string CalculateHash(string clientId, string clientSecret, string nonce, string path)
    {
      var HASH1 = MD5.GetMd5String($"{clientId}:oauth2_client@api.meethue.com:{clientSecret}");
      var HASH2 = MD5.GetMd5String("POST:" + path);
      var response = MD5.GetMd5String(HASH1 + ":" + nonce + ":" + HASH2);

      return response;
    }

    /// <summary>
    /// Refreshes the token if needed
    /// </summary>
    /// <returns></returns>
    public async Task<string?> GetValidToken()
    {
      if (_lastAuthorizationResponse != null)
      {
        if (_lastAuthorizationResponse.AccessTokenExpireTime() > DateTimeOffset.UtcNow.AddMinutes(-5))
        {
          return _lastAuthorizationResponse.Access_token;
        }
        else
        {
          var newToken = await this.RefreshToken(_lastAuthorizationResponse.Refresh_token).ConfigureAwait(false);

          return newToken?.Access_token;
        }
      }

      throw new HueException("Unable to get access token. Access token and Refresh token expired.");
    }
  }
}


text:
(function () {
  'use strict';

  var ERROR_MESSAGE = 'Invalid constructor';
  var ERROR_CODE = 'INVALID_CONSTRUCTOR';

  function isValidConstructor(expected, constructor) {
    if (Array.isArray(expected)) {
      var containsConstructor = !!~expected.indexOf(constructor);
      var containsName = !!~expected.indexOf(constructor.name);
      return containsConstructor || containsName;
    }

    return typeof expected === 'string' ?
      expected === constructor.name :
      expected === constructor;
  }

  function constructorDescriptor(expected, val, callback) {
    var constructor = val.constructor;

    if (isValidConstructor(expected, constructor)) {
      callback(null, true);
    } else {
      callback(null, false, {
        message : ERROR_MESSAGE,
        code : ERROR_CODE,
        expected : expected,
        actual : constructor
      });
    }
  }

  exports = module.exports = function (guido) {
    guido.setDescriptor('constructor', constructorDescriptor);
  };
})();


text:
'use strict';

import * as Browser from 'vs/base/browser/browser';
import {IVisibleLineData} from 'vs/editor/browser/view/viewLayer';
import {ILineParts, createLineParts} from 'vs/editor/common/viewLayout/viewLineParts';
import {ClassNames, IViewContext} from 'vs/editor/browser/editorBrowser';
import {IModelDecoration, IConfigurationChangedEvent, HorizontalRange} from 'vs/editor/common/editorCommon';
import {renderLine} from 'vs/editor/common/viewLayout/viewLineRenderer';
import {StyleMutator} from 'vs/base/browser/styleMutator';

export class ViewLine implements IVisibleLineData {

	protected _context:IViewContext;
	private _domNode: HTMLElement;

	private _lineParts: ILineParts;

	private _isInvalid: boolean;
	private _isMaybeInvalid: boolean;

	protected _charOffsetInPart:number[];
	private _lastRenderedPartIndex:number;
	private _cachedWidth: number;

	constructor(context:IViewContext) {
		this._context = context;
		this._domNode = null;
		this._isInvalid = true;
		this._isMaybeInvalid = false;
		this._lineParts = null;
		this._charOffsetInPart = [];
		this._lastRenderedPartIndex = 0;
	}

	// --- begin IVisibleLineData

	public getDomNode(): HTMLElement {
		return this._domNode;
	}
	public setDomNode(domNode:HTMLElement): void {
		this._domNode = domNode;
	}

	public onContentChanged(): void {
		this._isInvalid = true;
	}
	public onLinesInsertedAbove(): void {
		this._isMaybeInvalid = true;
	}
	public onLinesDeletedAbove(): void {
		this._isMaybeInvalid = true;
	}
	public onLineChangedAbove(): void {
		this._isMaybeInvalid = true;
	}
	public onTokensChanged(): void {
		this._isMaybeInvalid = true;
	}
	public onModelDecorationsChanged(): void {
		this._isMaybeInvalid = true;
	}
	public onConfigurationChanged(e:IConfigurationChangedEvent): void {
		this._isInvalid = true;
	}

	public shouldUpdateHTML(lineNumber:number, inlineDecorations:IModelDecoration[]): boolean {
		let newLineParts:ILineParts = null;

		if (this._isMaybeInvalid || this._isInvalid) {
			// Compute new line parts only if there is some evidence that something might have changed
			newLineParts = createLineParts(
				lineNumber,
				this._context.model.getLineContent(lineNumber),
				this._context.model.getLineTokens(lineNumber),
				inlineDecorations,
				this._context.configuration.editor.renderWhitespace
			);
		}

		// Decide if isMaybeInvalid flips isInvalid to true
		if (this._isMaybeInvalid) {
			if (!this._isInvalid) {
				if (!this._lineParts || !this._lineParts.equals(newLineParts)) {
					this._isInvalid = true;
				}
			}
			this._isMaybeInvalid = false;
		}

		if (this._isInvalid) {
			this._lineParts = newLineParts;
		}

		return this._isInvalid;
	}

	public getLineOuterHTML(out:string[], lineNumber:number, deltaTop:number): void {
		out.push('
');
		out.push(this.getLineInnerHTML(lineNumber));
		out.push('
');
	}

	public getLineInnerHTML(lineNumber: number): string {
		this._isInvalid = false;
		return this._render(lineNumber, this._lineParts).join('');
	}

	public layoutLine(lineNumber:number, deltaTop:number): void {
		let desiredLineNumber = String(lineNumber);
		let currentLineNumber = this._domNode.getAttribute('lineNumber');
		if (currentLineNumber !== desiredLineNumber) {
			this._domNode.setAttribute('lineNumber', desiredLineNumber);
		}
		StyleMutator.setTop(this._domNode, deltaTop);
		StyleMutator.setHeight(this._domNode, this._context.configuration.editor.lineHeight);
	}

	// --- end IVisibleLineData

	private _render(lineNumber:number, lineParts:ILineParts): string[] {

		this._cachedWidth = -1;

		let r = renderLine({
			lineContent: this._context.model.getLineContent(lineNumber),
			tabSize: this._context.configuration.getIndentationOptions().tabSize,
			stopRenderingLineAfter: this._context.configuration.editor.stopRenderingLineAfter,
			renderWhitespace: this._context.configuration.editor.renderWhitespace,
			parts: lineParts.getParts()
		});

		this._charOffsetInPart = r.charOffsetInPart;
		this._lastRenderedPartIndex = r.lastRenderedPartIndex;

		return r.output;
	}

	// --- Reading from the DOM methods

	protected _getReadingTarget(): HTMLElement {
		return <HTMLSpanElement>this._domNode.firstChild;
	}

	/**
	 * Width of the line in pixels
	 */
	public getWidth(): number {
		if (this._cachedWidth === -1) {
			this._cachedWidth = this._getReadingTarget().offsetWidth;
		}
		return this._cachedWidth;
	}

	/**
	 * Visible ranges for a model range
	 */
	public getVisibleRangesForRange(startColumn:number, endColumn:number, clientRectDeltaLeft:number, endNode:HTMLElement): HorizontalRange[] {
		let stopRenderingLineAfter = this._context.configuration.editor.stopRenderingLineAfter;

		if (stopRenderingLineAfter !== -1 && startColumn > stopRenderingLineAfter && endColumn > stopRenderingLineAfter) {
			// This range is obviously not visible
			return null;
		}

		if (stopRenderingLineAfter !== -1 && startColumn > stopRenderingLineAfter) {
			startColumn = stopRenderingLineAfter;
		}

		if (stopRenderingLineAfter !== -1 && endColumn > stopRenderingLineAfter) {
			endColumn = stopRenderingLineAfter;
		}

		return this._readVisibleRangesForRange(startColumn, endColumn, clientRectDeltaLeft, endNode);
	}

	protected _readVisibleRangesForRange(startColumn:number, endColumn:number, clientRectDeltaLeft:number, endNode:HTMLElement): HorizontalRange[] {

		let result: HorizontalRange[];
		if (startColumn === endColumn) {
			result = this._readRawVisibleRangesForPosition(startColumn, clientRectDeltaLeft, endNode);
		} else {
			result = this._readRawVisibleRangesForRange(startColumn, endColumn, clientRectDeltaLeft, endNode);
		}

		if (!result || result.length <= 1) {
			return result;
		}

		result.sort(compareVisibleRanges);

		let output: HorizontalRange[] = [];
		let prevRange: HorizontalRange = result[0];

		for (let i = 1, len = result.length; i < len; i++) {
			let currRange = result[i];

			if (prevRange.left + prevRange.width + 0.9 /* account for browser's rounding errors*/ >= currRange.left) {
				prevRange.width = Math.max(prevRange.width, currRange.left + currRange.width - prevRange.left);
			} else {
				output.push(prevRange);
				prevRange = currRange;
			}
		}
		output.push(prevRange);

		return output;
	}

	protected _readRawVisibleRangesForPosition(column:number, clientRectDeltaLeft:number, endNode:HTMLElement): HorizontalRange[] {

		if (this._charOffsetInPart.length === 0) {
			// This line is empty
			return [new HorizontalRange(0, 0)];
		}

		let partIndex = findIndexInArrayWithMax(this._lineParts, column - 1, this._lastRenderedPartIndex);
		let charOffsetInPart = this._charOffsetInPart[column - 1];

		return this._readRawVisibleRangesFrom(this._getReadingTarget(), partIndex, charOffsetInPart, partIndex, charOffsetInPart, clientRectDeltaLeft, endNode);
	}

	private _readRawVisibleRangesForRange(startColumn:number, endColumn:number, clientRectDeltaLeft:number, endNode:HTMLElement): HorizontalRange[] {

		if (startColumn === 1 && endColumn === this._charOffsetInPart.length) {
			// This branch helps IE with bidi text & gives a performance boost to other browsers when reading visible ranges for an entire line

			return [this._readRawVisibleRangeForEntireLine()];
		}

		let startPartIndex = findIndexInArrayWithMax(this._lineParts, startColumn - 1, this._lastRenderedPartIndex);
		let startCharOffsetInPart = this._charOffsetInPart[startColumn - 1];
		let endPartIndex = findIndexInArrayWithMax(this._lineParts, endColumn - 1, this._lastRenderedPartIndex);
		let endCharOffsetInPart = this._charOffsetInPart[endColumn - 1];

		return this._readRawVisibleRangesFrom(this._getReadingTarget(), startPartIndex, startCharOffsetInPart, endPartIndex, endCharOffsetInPart, clientRectDeltaLeft, endNode);
	}

	private _readRawVisibleRangeForEntireLine(): HorizontalRange {
		return new HorizontalRange(0, this._getReadingTarget().offsetWidth);
	}

	private _readRawVisibleRangesFrom(domNode:HTMLElement, startChildIndex:number, startOffset:number, endChildIndex:number, endOffset:number, clientRectDeltaLeft:number, endNode:HTMLElement): HorizontalRange[] {
		let range = RangeUtil.createRange();

		try {
			// Panic check
			let min = 0;
			let max = domNode.children.length - 1;
			if (min > max) {
				return null;
			}
			startChildIndex = Math.min(max, Math.max(min, startChildIndex));
			endChildIndex = Math.min(max, Math.max(min, endChildIndex));

			// If crossing over to a span only to select offset 0, then use the previous span's maximum offset
			// Chrome is buggy and doesn't handle 0 offsets well sometimes.
			if (startChildIndex !== endChildIndex) {
				if (endChildIndex > 0 && endOffset === 0) {
					endChildIndex--;
					endOffset = Number.MAX_VALUE;
				}
			}

			let startElement = domNode.children[startChildIndex].firstChild;
			let endElement = domNode.children[endChildIndex].firstChild;

			if (!startElement || !endElement) {
				return null;
			}

			startOffset = Math.min(startElement.textContent.length, Math.max(0, startOffset));
			endOffset = Math.min(endElement.textContent.length, Math.max(0, endOffset));

			range.setStart(startElement, startOffset);
			range.setEnd(endElement, endOffset);

			let clientRects = range.getClientRects();
			if (clientRects.length === 0) {
				return null;
			}

			return this._createRawVisibleRangesFromClientRects(clientRects, clientRectDeltaLeft);

		} catch (e) {
			// This is life ...
			return null;
		} finally {
			RangeUtil.detachRange(range, endNode);
		}
	}

	protected _createRawVisibleRangesFromClientRects(clientRects:ClientRectList, clientRectDeltaLeft:number): HorizontalRange[] {
		let result:HorizontalRange[] = [];
		for (let i = 0, len = clientRects.length; i < len; i++) {
			let cR = clientRects[i];
			result.push(new HorizontalRange(Math.max(0, cR.left - clientRectDeltaLeft), cR.width));
		}
		return result;
	}

	/**
	 * Returns the column for the text found at a specific offset inside a rendered dom node
	 */
	public getColumnOfNodeOffset(lineNumber:number, spanNode:HTMLElement, offset:number): number {
		let spanIndex = -1;
		while (spanNode) {
			spanNode = <HTMLElement>spanNode.previousSibling;
			spanIndex++;
		}
		let lineParts = this._lineParts.getParts();

		if (spanIndex >= lineParts.length) {
			return this._context.configuration.editor.stopRenderingLineAfter;
		}

		if (offset === 0) {
			return lineParts[spanIndex].startIndex + 1;
		}

		let originalMin = lineParts[spanIndex].startIndex;
		let originalMax:number;
		let originalMaxStartOffset:number;

		if (spanIndex + 1 < lineParts.length) {
			// Stop searching characters at the beginning of the next part
			originalMax = lineParts[spanIndex + 1].startIndex;
			originalMaxStartOffset = this._charOffsetInPart[originalMax - 1] + this._charOffsetInPart[originalMax];
		} else {
			originalMax = this._context.model.getLineMaxColumn(lineNumber) - 1;
			originalMaxStartOffset = this._charOffsetInPart[originalMax];
		}

		let min = originalMin;
		let max = originalMax;

		if (this._context.configuration.editor.stopRenderingLineAfter !== -1) {
			max = Math.min(this._context.configuration.editor.stopRenderingLineAfter - 1, originalMax);
		}

		let nextStartOffset:number;
		let prevStartOffset:number;

		// Here are the variables and their relation plotted on an axis

		// prevStartOffset    a    midStartOffset    b    nextStartOffset
		// ------|------------|----------|-----------|-----------|--------->

		// Everything in (a;b] will match mid

		while (min < max) {
			let mid = Math.floor( (min + max) / 2 );
			let midStartOffset = this._charOffsetInPart[mid];

			if (mid === originalMax) {
				// Using Number.MAX_VALUE to ensure that any offset after midStartOffset will match mid
				nextStartOffset = Number.MAX_VALUE;
			} else if (mid + 1 === originalMax) {
				// mid + 1 is already in next part and might have the _charOffsetInPart = 0
				nextStartOffset = originalMaxStartOffset;
			} else {
				nextStartOffset = this._charOffsetInPart[mid + 1];
			}

			if (mid === originalMin) {
				// Using Number.MIN_VALUE to ensure that any offset before midStartOffset will match mid
				prevStartOffset = Number.MIN_VALUE;
			} else {
				prevStartOffset = this._charOffsetInPart[mid - 1];
			}

			let a = (prevStartOffset + midStartOffset) / 2;
			let b = (midStartOffset + nextStartOffset) / 2;

			if (a < offset && offset <= b) {
				// Hit!
				return mid + 1;
			}

			if (offset <= a) {
				max = mid - 1;
			} else {
				min = mid + 1;
			}
		}

		return min + 1;
	}
}

class IEViewLine extends ViewLine {

	constructor(context:IViewContext) {
		super(context);
	}

	protected _createRawVisibleRangesFromClientRects(clientRects:ClientRectList, clientRectDeltaLeft:number): HorizontalRange[] {
		let ratioX = screen.logicalXDPI / screen.deviceXDPI;
		let result:HorizontalRange[] = [];
		for (let i = 0, len = clientRects.length; i < len; i++) {
			let cR = clientRects[i];
			result[i] = new HorizontalRange(Math.max(0, cR.left * ratioX - clientRectDeltaLeft), cR.width * ratioX);
		}

		return result;
	}
}

class WebKitViewLine extends ViewLine {

	constructor(context:IViewContext) {
		super(context);
	}

	protected _readVisibleRangesForRange(startColumn:number, endColumn:number, clientRectDeltaLeft:number, endNode:HTMLElement): HorizontalRange[] {
		let output = super._readVisibleRangesForRange(startColumn, endColumn, clientRectDeltaLeft, endNode);

		if (this._context.configuration.editor.fontLigatures && output.length === 1 && endColumn > 1 && endColumn === this._charOffsetInPart.length) {
			let lastSpanBoundingClientRect = (<HTMLElement>this._getReadingTarget().lastChild).getBoundingClientRect();
			let lastSpanBoundingClientRectRight = lastSpanBoundingClientRect.right - clientRectDeltaLeft;
			if (startColumn === endColumn) {
				output[0].left = lastSpanBoundingClientRectRight;
				output[0].width = 0;
			} else {
				output[0].width = lastSpanBoundingClientRectRight - output[0].left;
			}
			return output;
		}

		if (!output || output.length === 0 || startColumn === endColumn || (startColumn === 1 && endColumn === this._charOffsetInPart.length)) {
			return output;
		}

		// WebKit is buggy and returns an expanded range (to contain words in some cases)
		// The last client rect is enlarged (I think)

		// This is an attempt to patch things up
		// Find position of previous column
		let beforeEndVisibleRanges = this._readRawVisibleRangesForPosition(endColumn - 1, clientRectDeltaLeft, endNode);
		// Find position of last column
		let endVisibleRanges = this._readRawVisibleRangesForPosition(endColumn, clientRectDeltaLeft, endNode);

		if (beforeEndVisibleRanges && beforeEndVisibleRanges.length > 0 && endVisibleRanges && endVisibleRanges.length > 0) {
			let beforeEndVisibleRange = beforeEndVisibleRanges[0];
			let endVisibleRange = endVisibleRanges[0];
			let isLTR = (beforeEndVisibleRange.left <= endVisibleRange.left);
			let lastRange = output[output.length - 1];

			if (isLTR && lastRange.left < endVisibleRange.left) {
				// Trim down the width of the last visible range to not go after the last column's position
				lastRange.width = endVisibleRange.left - lastRange.left;
			}
		}

		return output;
	}
}

class RangeUtil {

	/**
	 * Reusing the same range here
	 * because IE is buggy and constantly freezes when using a large number
	 * of ranges and calling .detach on them
	 */
	private static _handyReadyRange:Range;

	public static createRange(): Range {
		if (!RangeUtil._handyReadyRange) {
			RangeUtil._handyReadyRange = document.createRange();
		}
		return RangeUtil._handyReadyRange;
	}

	public static detachRange(range:Range, endNode:HTMLElement): void {
		// Move range out of the span node, IE doesn't like having many ranges in
		// the same spot and will act badly for lines containing dashes ('-')
		range.selectNodeContents(endNode);
	}
}

function compareVisibleRanges(a: HorizontalRange, b: HorizontalRange): number {
	return a.left - b.left;
}

function findIndexInArrayWithMax(lineParts:ILineParts, desiredIndex: number, maxResult:number): number {
	let r = lineParts.findIndexOfOffset(desiredIndex);
	return r <= maxResult ? r : maxResult;
}

export let createLine: (context: IViewContext) => ViewLine = (function() {
	if (window.screen && window.screen.deviceXDPI && (navigator.userAgent.indexOf('Trident/6.0') >= 0 || navigator.userAgent.indexOf('Trident/5.0') >= 0)) {
		// IE11 doesn't need the screen.logicalXDPI / screen.deviceXDPI ratio multiplication
		// for TextRange.getClientRects() anymore
		return createIELine;
	} else if (Browser.isWebKit) {
		return createWebKitLine;
	}
	return createNormalLine;
})();

function createIELine(context: IViewContext): ViewLine {
	return new IEViewLine(context);
}

function createWebKitLine(context: IViewContext): ViewLine {
	return new WebKitViewLine(context);
}

function createNormalLine(context: IViewContext): ViewLine {
	return new ViewLine(context);
}


text:
using System;
using System.Reflection;

class T {
	public static unsafe void meth (int a, int* b) {
	}
	static int Main () {
		ParameterInfo[] args = typeof (T).GetMethod ("meth").GetParameters ();
		if (args[0].ParameterType == args[1].ParameterType)
			return 1;

		unsafe {
			if (typeof(int) == typeof (int*))
				return 2;
		}
		if (args[0].ParameterType != typeof(int))
			return 3;

		unsafe {
			if (args[1].ParameterType != typeof(int*))
				return 4;
		}

		return 0;
	}
}


text:
<?php
/**
 * Module Name: JSON API
 * Module Description: Allow applications to securely access your content.
 * Sort Order: 19
 * First Introduced: 1.9
 * Requires Connection: Yes
 * Auto Activate: Public
 * Module Tags: Writing, Developers
 * Feature: General
 * Additional Search Queries: api, rest, develop, developers, json, klout, oauth
 */


text:
const got = require('got');
const fs = require('fs');
const FormData = require('form-data');
const path = require("path");

// method used to upload a file to Openload Servers
module.exports = async (url, filePath, params) => {

    // get sha1 of file
    params.sha1 = await sha1(filePath);

    // make request to get the Upload Agent's URL
    let response = await got(url, {
        method : 'GET',
        json   :  true,
        query  : params,
    });

    // check response status
    if(response.body.status !== 200) {
        throw new Error(response.body.msg);
    }

    // get upload agent url
    let uploadAgentUrl = response.body.result.url;

    const form = new FormData();

    const attachment = fs.createReadStream(filePath);
    const fileName = path.basename(filePath);

    form.append(fileName, attachment, {
        filename: fileName,
    });

    let agentResponse = await got.post(uploadAgentUrl, {
        body : form
    });

    agentResponse.body = JSON.parse(agentResponse.body);

    // check response status
    if(agentResponse.body.status !== 200) {
        throw new Error(agentResponse.body.msg);
    }

    return agentResponse.body.result;

};

const sha1 = path => new Promise((resolve, reject) => {
    const hash = require('crypto').createHash('sha1');
    const rs = fs.createReadStream(path);
    rs.on('error', reject);
    rs.on('data', chunk => hash.update(chunk));
    rs.on('end', () => resolve(hash.digest('hex')));
});


text:
<root>

    <!--  name : The maven artifact name.  Also the project name by convention. -->
    <!--  groupId : The maven group ID -->
    <!--  version : The maven artifact version. -->
    <!--  basePackage : The prefix of any generated package names -->
    <!--  drivers : Boolean indicating whether test/driver projects should also be generated -->
    <component  name=""  groupId=""  version=""  basePackage="" drivers="">

        <!--  name :  -->
        <!--  messageType : The fully qualified name of the message type, or "Long" or "String" -->
        <!--  keyType : The fully qualified name of the key type, or "Long" or "String".  -->
        <!--  partitioner : A true|false value indicating whether or not a partitioner is to be configured  -->
        <!--  partitions : An integer number of partitions -->
        <topic  name=""  messageType=""  keyType=""  partitioner=""  partitions="" />

        <!--  groupId :  -->
        <!--  artifact :  -->
        <!--  version :  -->
        <dependency  groupId=""  artifact=""  version="" />

        <!--  type : A fully-qualified message type or key type  -->
		<bean  type="" >

	        <!--  name : The (variable) name of the attribute -->
	        <!--  type : Yhe java type of the attribute (one of String, Long, Integer, Double Boolean, Date) -->
			<field name=""  type="" 	/>

		</bean>

    </component>

</root>


text: This project showcases a simple hello-world using Greg Young's EventStore.


text:
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('playlist', '0004_playlistentry_playlist'),
    ]

    operations = [
        migrations.AlterField(
            model_name='playlistentry',
            name='catalogueEntry',
            field=models.ForeignKey(to='playlist.Cdtrack', null=True),
        ),
    ]


text:
pShdaiin ypchdy opchey cKhy dal Sheodaiin Sheokeol ykeeody olaiin opaldy
daiin yteeol choody kechodShey qotedy chtaiin otchdy tedain okain cKhy
Sheody She teoteey oteodaiin ody qoteo l kedy dol odal qotar opchety ldy
tolkeol dain otaiin ykeedy chet ytedy tedy qokdy tShdy chetedy cTheety r
ytchy teol okeody cheocKhy olSheey qoekaiin ocThey chol kar aiin cThar od
alShey lkeedy ytchedy qokedy lotal qotol otal ched okey ykeey dalmy
tocThy qokeol yteedy lolkeol otolches al or ykeeodam okedy okam
otchdain Shol oteol oteoly ykeey dam dr
yteched ar alkey okeoam


text:
/**
 * "First, solve the problem. Then, write the code. -John Johnson"
 * "Or use Vangav M"
 * www.vangav.com
 * */

/**
 * MIT License
 *
 * Copyright (c) 2016 Vangav
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to
 * deal in the Software without restriction, including without limitation the
 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
 * sell copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
 * IN THE SOFTWARE.
 * */

/**
 * Community
 * Facebook Group: Vangav Open Source - Backend
 *   fb.com/groups/575834775932682/
 * Facebook Page: Vangav
 *   fb.com/vangav.f
 *
 * Third party communities for Vangav Backend
 *   - play framework
 *   - cassandra
 *   - datastax
 *
 * Tag your question online (e.g.: stack overflow, etc ...) with
 *   #vangav_backend
 *   to easier find questions/answers online
 * */

package com.vangav.vos_instagram.controllers.logout.request_enums;

/**
 * @author mustapha
 * fb.com/mustapha.abdallah
 */
/**
 * enum LogoutType represents possible logout types
 */
public enum LogoutType {

  THIS_DEVICE,
  OTHER_DEVICES,
  ALL_DEVICES;

  /**
   * getDefaultType
   * @return the default LogoutType
   * @throws Exception
   */
  public static LogoutType getDefaultType () throws Exception {

    return THIS_DEVICE;
  }
}


text:
/*jshint evil: true, shadow: true, wsh: true */
/*global JSHINT: false */

(function() {
	function readFile(path, charset) {
		try {
			var stream = WScript.CreateObject("ADODB.Stream");

			stream.Charset = charset;
			stream.Open();
			stream.LoadFromFile(path);

			var result = stream.ReadText();
			stream.close();

			return result;
		} catch (ex) {
			return null;
		}
	}

	var formatters = {
		errors: function(errors, lines) {
			for (var i = 0; i < errors.length; i++) {
				var error = errors[i];

				if (!error) continue;

				if (i) lines.push("");

				lines.push("Line " + error.line + " character " + error.character + ": " + error.reason);

				if (error.evidence) lines.push("    " + error.evidence.replace(/^\s*((?:[\S\s]*\S)?)\s*$/, "$1"));
			}
		},

		implieds: function(implieds, lines) {
			lines.push("Implied globals:");

			var globals = {};

			for (var i = 0; i < implieds.length; i++) {
				var item = implieds[i];

				if (!(item.name in globals)) globals[item.name] = [];

				globals[item.name].push(item.line);
			}

			for (var name in globals) {
				lines.push("    " + name + ": " + globals[name].join(", "));
			}
		},

		unused: function(unused, lines) {
			lines.push("Unused variables:");

			var func, names = {};

			for (var i = 0; i < unused.length; i++) {
				var item = unused[i];

				func = item["function"];

				if (!(func in names)) names[func] = [];

				names[func].push(item.name + " (" + item.line + ")");
			}

			for (func in names) {
				lines.push("    " + func + ": " + names[func].join(", "));
			}
		}
	};

	var scriptName = WScript.ScriptName;
	var scriptPath = WScript.ScriptFullName;

	scriptPath = scriptPath.substr(0, scriptPath.length - scriptName.length);

	// load JSHint if the two scripts have not been concatenated
	if (typeof JSHINT === "undefined") {
		eval(readFile(scriptPath + "..\\jshint.js", 'utf-8'));

		if (typeof JSHINT === "undefined") {
			WScript.StdOut.WriteLine("ERROR: Could not find 'jshint.js'.");

			WScript.Quit(-2);
		}
	}

	var globals = {};
	var options = {};
	var named = WScript.Arguments.Named;
	var unnamed = WScript.Arguments.Unnamed;

	if (unnamed.length !== 1) {
		WScript.StdOut.WriteLine("    usage: cscript " + scriptName + " [options] <script>");
		WScript.StdOut.WriteLine("");
		WScript.StdOut.WriteLine("Scans the specified script with JSHint and reports any errors encountered.  If");
		WScript.StdOut.WriteLine("the script name is \"-\", it will be read from standard input instead.");
		WScript.StdOut.WriteLine("");
		WScript.StdOut.WriteLine("JSHint configuration options can be passed in via optional, Windows-style");
		WScript.StdOut.WriteLine("arguments.  For example:");
		WScript.StdOut.WriteLine("    cscript " + scriptName + " /jquery:true myscript.js");
		WScript.StdOut.WriteLine("    cscript " + scriptName + " /global:QUnit:false,_:false,foo:true foo.js");
		WScript.StdOut.WriteLine("");
		WScript.StdOut.WriteLine("By default, we assume that your file is encoded if UTF-8. You can change that");
		WScript.StdOut.WriteLine("by providing a custom charset option:");
		WScript.StdOut.WriteLine("    cscript " + scriptName + " /charset:ascii myscript.js");

		WScript.Quit(-1);
	}

	var script = unnamed(0);

	if (script === "-") {
		try {
			script = WScript.StdIn.ReadAll();
		} catch (ex) {
			script = null;
		}
	} else {
		script = readFile(script, named('charset') || 'utf-8');
	}

	if (script === null) {
		WScript.StdOut.WriteLine("ERROR: Could not read target script.");

		WScript.Quit(2);
	}

	for (var etor = new Enumerator(named); !etor.atEnd(); etor.moveNext()) {
		var option = etor.item();
		var value = named(option);

		if (option === "global") {
			value = value.split(",");

			for (var i = 0; i < value.length; i++) {
				var name = value[i].split(":");

				if (name.length === 1 || name[1] === "false") {
					globals[name[0]] = false;
				} else if (name[1] === "true") {
					globals[name[0]] = true;
				} else {
					WScript.StdOut.WriteLine("Unrecognized value for global: " + name[0]);
					WScript.StdOut.WriteLine("Must be \"true\", \"false\", or omitted.");

					WScript.Quit(-1);
				}
			}
		} else {
			options[option] = value === "true" ? true : value === "false" ? false : value;
		}
	}

	JSHINT(script, options, globals);

	var data = JSHINT.data();
	var lines = [];

	for (var formatter in formatters) {
		if (data[formatter]) {
			if (lines.length) lines.push("");

			formatters[formatter](data[formatter], lines);
		}
	}

	if (lines.length) {
		for (var i = 0; i < lines.length; i++) {
			WScript.StdOut.WriteLine(lines[i]);
		}

		WScript.Quit(1);
	} else {
		WScript.Quit(0);
	}
}());


text:
package org.camunda.bpm.webapp.impl.security;

import javax.servlet.ServletException;
import java.io.IOException;
import java.util.List;

import org.camunda.bpm.cockpit.Cockpit;
import org.camunda.bpm.engine.IdentityService;
import org.camunda.bpm.engine.ProcessEngine;
import org.camunda.bpm.webapp.impl.security.auth.Authentication;
import org.camunda.bpm.webapp.impl.security.auth.Authentications;
import org.camunda.bpm.webapp.impl.security.auth.UserAuthentication;

/**
 * @author Daniel Meyer
 *
 */
public class SecurityActions {

  public static <T> T runWithAuthentications(SecurityAction<T> action, Authentications authentications) throws IOException, ServletException {

    List<Authentication> currentAuthentications = authentications.getAuthentications();
    try {
      for (Authentication authentication : currentAuthentications) {
        authenticateProcessEngine(authentication);
      }

      return action.execute();

    } finally {
      for (Authentication authentication : currentAuthentications) {
        clearAuthentication(authentication);
      }
    }
  }

  private static void clearAuthentication(Authentication authentication) {
    ProcessEngine processEngine = Cockpit.getProcessEngine(authentication.getProcessEngineName());
    if(processEngine != null) {
      processEngine.getIdentityService().clearAuthentication();
    }
  }

  private static void authenticateProcessEngine(Authentication authentication) {

    ProcessEngine processEngine = Cockpit.getProcessEngine(authentication.getProcessEngineName());
    if (processEngine != null) {

      String userId = authentication.getIdentityId();
      List<String> groupIds = null;
      List<String> tenantIds = null;

      if (authentication instanceof UserAuthentication) {
        UserAuthentication userAuthentication = (UserAuthentication) authentication;
        groupIds = userAuthentication.getGroupIds();
        tenantIds = userAuthentication.getTenantIds();
      }

      processEngine.getIdentityService().setAuthentication(userId, groupIds, tenantIds);
    }
  }

  public static <T> T runWithoutAuthentication(SecurityAction<T> action, ProcessEngine processEngine) throws IOException, ServletException {

    final IdentityService identityService = processEngine.getIdentityService();
    org.camunda.bpm.engine.impl.identity.Authentication currentAuth = identityService.getCurrentAuthentication();

    try {
      identityService.clearAuthentication();
      return action.execute();

    } finally {
      identityService.setAuthentication(currentAuth);

    }

  }

  public static interface SecurityAction<T> {
    public T execute() throws IOException, ServletException;
  }

}


text:
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using BudgetAnalyser.Engine.Budget;
using BudgetAnalyser.Engine.Ledger;
using BudgetAnalyser.Engine.Persistence;
using BudgetAnalyser.Engine.Statement;
using JetBrains.Annotations;

namespace BudgetAnalyser.Engine.Services
{
    /// <summary>
    ///     A class that contains references to services that can be used as dependencies for the Dashboard Service.
    /// </summary>
    [AutoRegisterWithIoC(SingleInstance = true)]
    public class MonitorableDependencies
    {
        private readonly IDictionary<Type, object> availableDependencies;
        private readonly Dictionary<Type, long> changesHashes = new Dictionary<Type, long>();

        /// <summary>
        ///     Initializes a new instance of the <see cref="MonitorableDependencies" /> class.
        /// </summary>
        public MonitorableDependencies(LedgerCalculation ledgerCalculator)
        {
            this.availableDependencies = new Dictionary<Type, object>
            {
                [typeof(StatementModel)] = null,
                [typeof(BudgetCollection)] = null,
                [typeof(IBudgetCurrencyContext)] = null,
                [typeof(LedgerBook)] = null,
                [typeof(IBudgetBucketRepository)] = null,
                [typeof(GlobalFilterCriteria)] = null,
                [typeof(LedgerCalculation)] = ledgerCalculator,
                [typeof(ApplicationDatabase)] = null,
                [typeof(ITransactionRuleService)] = null,
                [typeof(IApplicationDatabaseService)] = null
            };
        }

        internal event EventHandler<DependencyChangedEventArgs> DependencyChanged;

        /// <summary>
        ///     Gets a list of supported types
        /// </summary>
        internal virtual IEnumerable<Type> SupportedWidgetDependencyTypes => this.availableDependencies.Keys;

        /// <summary>
        ///     Notifies this service of dependency that has changed.
        /// </summary>
        /// <param name="dependency">The dependency.</param>
        /// <returns>A boolean value indicating if the dependency has significantly change, true if so, otherwise false.</returns>
        [SuppressMessage("Microsoft.Design", "CA1004:GenericMethodsShouldProvideTypeParameter", Justification = "Preferred method of passing type parameter")]
        internal virtual bool NotifyOfDependencyChange<T>([CanBeNull] T dependency)
        {
            return NotifyOfDependencyChange(dependency, typeof(T));
        }

        /// <summary>
        ///     Notifies this service of dependency that has changed.
        /// </summary>
        /// <param name="dependency">The dependency.</param>
        /// <param name="typeKey">The type key.</param>
        /// <returns>A boolean value indicating if the dependency has significantly change, true if so, otherwise false.</returns>
        internal virtual bool NotifyOfDependencyChange([CanBeNull] object dependency, Type typeKey)
        {
            if (dependency == null) return false;
            this.availableDependencies[typeKey] = dependency;
            if (HasDependencySignificantlyChanged(dependency, typeKey))
            {
                DependencyChanged?.Invoke(this, new DependencyChangedEventArgs(typeKey));
                return true;
            }

            return false;
        }

        internal virtual object RetrieveDependency(Type key)
        {
            if (!this.availableDependencies.ContainsKey(key))
            {
                // If you get an exception here first check the Constructor for the types available.
                throw new NotSupportedException(string.Format(CultureInfo.CurrentCulture, "The requested dependency {0} is not supported.", key.Name));
            }

            return this.availableDependencies[key];
        }

        private bool HasDependencySignificantlyChanged(object dependency, Type typeKey)
        {
            var supportsDataChangeDetection = dependency as IDataChangeDetection;
            if (supportsDataChangeDetection == null)
            {
                // Dependency doesn't support change hashes so every change is deemed worthy to trigger an update the UI.
                return true;
            }

            var newHash = supportsDataChangeDetection.SignificantDataChangeHash();
            if (!this.changesHashes.ContainsKey(typeKey))
            {
                this.changesHashes.Add(typeKey, newHash);
                return true;
            }

            var result = this.changesHashes[typeKey] != newHash;
            this.changesHashes[typeKey] = newHash;
            return result;
        }
    }
}


text:
package synergynet.table.apps.controlclient;

import java.awt.Color;
import java.awt.Font;
import java.awt.RenderingHints;

import com.jme.scene.Spatial;
import com.jmex.awt.swingui.ImageGraphics;

import synergynet.contentsystem.ContentSystem;
import synergynet.services.net.localpresence.TableIdentity;
import synergynet.table.gfx.FullScreenCanvas;
import synergyspace.jme.gfx.twod.DrawableSpatialImage;

public class ControlClientView extends FullScreenCanvas implements DrawableSpatialImage {

	private static final long serialVersionUID = 1473078189191810104L;
	private ImageGraphics gfx;
	private Font titleFont = new Font("Arial", Font.BOLD, 36);
	private Font tableIDFont = new Font("Arial", Font.PLAIN, 18);

	public ControlClientView(String name, ContentSystem cs) {
		super(name, cs);
		gfx = getGraphics();
	}

	@Override
	public void cursorDragged(long id, int x, int y) {
	}

	@Override
	public void cursorPressed(long cursorID, int x, int y) {
	}

	@Override
	public void cursorReleased(long cursorID, int x, int y) {
	}

	@Override
	public void cursorClicked(long cursorID, int x, int y) {}

	public void draw() {
		gfx.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
		gfx.setColor(Color.darkGray);
		gfx.fillRect(0, 0, pixelWidth, pixelHeight);
		gfx.setColor(Color.black);
		gfx.setFont(titleFont);
		gfx.drawString("Please wait", 401, 401);
		gfx.setColor(Color.lightGray);
		gfx.drawString("Please wait", 400, 400);
		gfx.setFont(tableIDFont );
		gfx.drawString(TableIdentity.getTableIdentity().toString(), 10, 30);
	}

	public Spatial getSpatial() {
		return null;
	}

}


text:
+++
Talk_date = "2019-11-12"
Title = "DevOps and System Thinking"
Type = "talk"
Speakers = ["chris-rimondi"]
+++

System Thinking has applications on how we organize our work, how we structure our teams, and how we build our services. In this talk we examine  DevOps principles in light of System Thinking fundamentals to discover how we can improve our software product delivery.


text:
namespace Microsoft.Azure.Management.IotHub.Models
{
    using System;
    using System.Linq;
    using System.Collections.Generic;
    using Newtonsoft.Json;
    using Microsoft.Rest;
    using Microsoft.Rest.Serialization;
    using Microsoft.Rest.Azure;

    /// <summary>
    /// The properties of the Job Response object.
    /// </summary>
    public partial class JobResponse
    {
        /// <summary>
        /// Initializes a new instance of the JobResponse class.
        /// </summary>
        public JobResponse() { }

        /// <summary>
        /// Initializes a new instance of the JobResponse class.
        /// </summary>
        /// <param name="jobId">The job identifier.</param>
        /// <param name="startTimeUtc">The start time of the job.</param>
        /// <param name="endTimeUtc">The time the job stopped processing.</param>
        /// <param name="type">The type of the job. Possible values include: 'unknown', 'export', 'import', 'backup', 'readDeviceProperties', 'writeDeviceProperties', 'updateDeviceConfiguration', 'rebootDevice', 'factoryResetDevice', 'firmwareUpdate'</param>
        /// <param name="status">The status of the job. Possible values include: 'unknown', 'enqueued', 'running', 'completed', 'failed', 'cancelled'</param>
        /// <param name="failureReason">If status == failed, this string containing the reason for the failure.</param>
        /// <param name="statusMessage">The status message for the job.</param>
        /// <param name="parentJobId">The job identifier of the parent job, if any.</param>
        public JobResponse(string jobId = default(string), DateTime? startTimeUtc = default(DateTime?), DateTime? endTimeUtc = default(DateTime?), string type = default(string), JobStatus? status = default(JobStatus?), string failureReason = default(string), string statusMessage = default(string), string parentJobId = default(string))
        {
            JobId = jobId;
            StartTimeUtc = startTimeUtc;
            EndTimeUtc = endTimeUtc;
            Type = type;
            Status = status;
            FailureReason = failureReason;
            StatusMessage = statusMessage;
            ParentJobId = parentJobId;
        }

        /// <summary>
        /// Gets the job identifier.
        /// </summary>
        [JsonProperty(PropertyName = "jobId")]
        public string JobId { get; private set; }

        /// <summary>
        /// Gets the start time of the job.
        /// </summary>
        [JsonConverter(typeof(DateTimeRfc1123JsonConverter))]
        [JsonProperty(PropertyName = "startTimeUtc")]
        public DateTime? StartTimeUtc { get; private set; }

        /// <summary>
        /// Gets the time the job stopped processing.
        /// </summary>
        [JsonConverter(typeof(DateTimeRfc1123JsonConverter))]
        [JsonProperty(PropertyName = "endTimeUtc")]
        public DateTime? EndTimeUtc { get; private set; }

        /// <summary>
        /// Gets the type of the job. Possible values include: 'unknown',
        /// 'export', 'import', 'backup', 'readDeviceProperties',
        /// 'writeDeviceProperties', 'updateDeviceConfiguration',
        /// 'rebootDevice', 'factoryResetDevice', 'firmwareUpdate'
        /// </summary>
        [JsonProperty(PropertyName = "type")]
        public string Type { get; private set; }

        /// <summary>
        /// Gets the status of the job. Possible values include: 'unknown',
        /// 'enqueued', 'running', 'completed', 'failed', 'cancelled'
        /// </summary>
        [JsonProperty(PropertyName = "status")]
        public JobStatus? Status { get; private set; }

        /// <summary>
        /// Gets if status == failed, this string containing the reason for
        /// the failure.
        /// </summary>
        [JsonProperty(PropertyName = "failureReason")]
        public string FailureReason { get; private set; }

        /// <summary>
        /// Gets the status message for the job.
        /// </summary>
        [JsonProperty(PropertyName = "statusMessage")]
        public string StatusMessage { get; private set; }

        /// <summary>
        /// Gets the job identifier of the parent job, if any.
        /// </summary>
        [JsonProperty(PropertyName = "parentJobId")]
        public string ParentJobId { get; private set; }

    }
}


text:
package com.ayvytr.easyandroid.tools.withcontext;

import android.annotation.TargetApi;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;

import com.ayvytr.easyandroid.Easy;

import static com.ayvytr.easyandroid.tools.withcontext.Managers.getClipboardManager;

/**
 * 剪贴板操作类,从剪贴板中获取/设置文本,Intent,Uri.
 *

 * 因为剪贴板需要的SDK最小是11,所以设置了 minSdkVersion 为 11.
 *

 * @author Ayvytr 's GitHub
 * @since 1.0.0
 */

public class ClipboardTool
{
    private static final String TEXT = "text";
    private static final String URI = "uri";
    private static final String INTENT = "intent";

    private ClipboardTool()
    {
        throw new UnsupportedOperationException();
    }

    /**
     * 设置文本到剪贴板
     *
     * @param text 文本
     */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    public static void setText(CharSequence text)
    {
        ClipboardManager clipboardManager = getClipboardManager();
        clipboardManager.setPrimaryClip(ClipData.newPlainText(TEXT, text));
    }

    /**
     * 获取剪贴板的文本
     *
     * @return 剪贴板的文本
     */
    public static String getText()
    {
        return getText(null);
    }

    /**
     * 获取剪贴板文本,当获取到是空时,返回默认字符串
     *
     * @param textIfNull 剪贴板文本如果为空,返回这个字符串
     * @return 剪贴板文本
     */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    public static String getText(String textIfNull)
    {
        ClipboardManager clipboardManager = getClipboardManager();
        ClipData clipData = clipboardManager.getPrimaryClip();
        if(clipData != null && clipData.getItemCount() > 0)
        {
            return clipData.getItemAt(0).coerceToText(Easy.getContext()).toString();
        }

        return textIfNull;
    }

    /**
     * 设置uri到剪贴板
     *
     * @param uri uri
     */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    public static void setUri(Uri uri)
    {
        ClipboardManager clipboardManager = Managers.getClipboardManager();
        clipboardManager.setPrimaryClip(
                ClipData.newUri(Easy.getContext().getContentResolver(), URI, uri));
    }

    /**
     * 获取剪贴板的uri
     *
     * @return 剪贴板的uri
     */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    public static Uri getUri()
    {
        ClipboardManager clipboardManager = Managers.getClipboardManager();
        ClipData clipData = clipboardManager.getPrimaryClip();
        if(clipData != null && clipData.getItemCount() > 0)
        {
            return clipData.getItemAt(0).getUri();
        }
        return null;
    }

    /**
     * 设置意图到剪贴板
     *
     * @param intent 意图
     */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    public static void setIntent(Intent intent)
    {
        ClipboardManager clipboardManager = Managers.getClipboardManager();
        clipboardManager.setPrimaryClip(ClipData.newIntent(INTENT, intent));
    }

    /**
     * 获取剪贴板的意图
     *
     * @return 剪贴板的意图
     */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    public static Intent getIntent()
    {
        ClipboardManager clipboardManager = Managers.getClipboardManager();
        ClipData clipData = clipboardManager.getPrimaryClip();
        if(clipData != null && clipData.getItemCount() > 0)
        {
            return clipData.getItemAt(0).getIntent();
        }
        return null;
    }
}


text:
package com.microsoft.azure.management.datafactory.v2018_06_01;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.JsonTypeName;
import com.microsoft.rest.serializer.JsonFlatten;
import com.microsoft.azure.management.datafactory.v2018_06_01.implementation.LinkedServiceInner;

/**
 * Azure Function linked service.
 */
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type", defaultImpl = AzureFunctionLinkedService.class)
@JsonTypeName("AzureFunction")
@JsonFlatten
public class AzureFunctionLinkedService extends LinkedServiceInner {
    /**
     * The endpoint of the Azure Function App. URL will be in the format
     * https://<accountName>.azurewebsites.net.
     */
    @JsonProperty(value = "typeProperties.functionAppUrl", required = true)
    private Object functionAppUrl;

    /**
     * Function or Host key for Azure Function App.
     */
    @JsonProperty(value = "typeProperties.functionKey")
    private SecretBase functionKey;

    /**
     * The encrypted credential used for authentication. Credentials are
     * encrypted using the integration runtime credential manager. Type: string
     * (or Expression with resultType string).
     */
    @JsonProperty(value = "typeProperties.encryptedCredential")
    private Object encryptedCredential;

    /**
     * Get the endpoint of the Azure Function App. URL will be in the format https://<accountName>.azurewebsites.net.
     *
     * @return the functionAppUrl value
     */
    public Object functionAppUrl() {
        return this.functionAppUrl;
    }

    /**
     * Set the endpoint of the Azure Function App. URL will be in the format https://<accountName>.azurewebsites.net.
     *
     * @param functionAppUrl the functionAppUrl value to set
     * @return the AzureFunctionLinkedService object itself.
     */
    public AzureFunctionLinkedService withFunctionAppUrl(Object functionAppUrl) {
        this.functionAppUrl = functionAppUrl;
        return this;
    }

    /**
     * Get function or Host key for Azure Function App.
     *
     * @return the functionKey value
     */
    public SecretBase functionKey() {
        return this.functionKey;
    }

    /**
     * Set function or Host key for Azure Function App.
     *
     * @param functionKey the functionKey value to set
     * @return the AzureFunctionLinkedService object itself.
     */
    public AzureFunctionLinkedService withFunctionKey(SecretBase functionKey) {
        this.functionKey = functionKey;
        return this;
    }

    /**
     * Get the encrypted credential used for authentication. Credentials are encrypted using the integration runtime credential manager. Type: string (or Expression with resultType string).
     *
     * @return the encryptedCredential value
     */
    public Object encryptedCredential() {
        return this.encryptedCredential;
    }

    /**
     * Set the encrypted credential used for authentication. Credentials are encrypted using the integration runtime credential manager. Type: string (or Expression with resultType string).
     *
     * @param encryptedCredential the encryptedCredential value to set
     * @return the AzureFunctionLinkedService object itself.
     */
    public AzureFunctionLinkedService withEncryptedCredential(Object encryptedCredential) {
        this.encryptedCredential = encryptedCredential;
        return this;
    }

}


text:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.titanium.news.mapper.NewsMapper" >

</mapper>


text:
.. automodule:: scipy.spatial.distance
   :no-members:
   :no-inherited-members:
   :no-special-members:


text:
package systemd

import (
	"fmt"

	"github.com/coreos/go-semver/semver"

	"github.com/coreos/mantle/kola/cluster"
	"github.com/coreos/mantle/kola/register"
)

func init() {
	register.Register(&register.Test{
		Run:         gshadowParser,
		ClusterSize: 1,
		Name:        "systemd.sysusers.gshadow",
		UserData:    `#cloud-config`,
		MinVersion:  semver.Version{Major: 1095},
	})
}

// Verify that glibc's parsing of /etc/gshadow does not cause systemd-sysusers
// to segfault on specially constructed lines.
//
// One line must fit into the character buffer (1024 bytes, unless a previous
// line was longer) but have enough group members such that
//
//     line length + alignment + sizeof(char *) * (#adm + 1 + #mem + 1) > 1024.
//
// The parser would return early to avoid overflow, leaving the static result
// struct pointing to pointers from the previous line which are now invalid,
// causing segfaults when those pointers are dereferenced.
//
// Tests: https://github.com/coreos/bugs/issues/1394
func gshadowParser(c cluster.TestCluster) error {
	m := c.Machines()[0]

	for _, cmd := range []string{
		`sudo sh -c "echo 'grp0:*::root' >> /etc/gshadow"`,
		`sudo sh -c "echo 'grp1:*::somebody.a1,somebody.a2,somebody.a3,somebody.a4,somebody.a5,somebody.a6,somebody.a7,somebody.a8,somebody.a9,somebody.a10,somebody.a11,somebody.a12,somebody.a13,somebody.a14,somebody.a15,somebody.a16,somebody.a17,somebody.a18,somebody.a19,somebody.a20,somebody.a21,somebody.a22,somebody.a23,somebody.a24,somebody.a25,somebody.a26,somebody.a27,somebody.a28,somebody.a29,somebody.a30,somebody.a31,somebody.a32,somebody.a33,somebody.a34,somebody.a35,somebody.a36,somebody.a37,somebody.a38,somebody.a39,somebody.a40,somebody.a41,somebody.a42,somebody.a43,somebody.a44,somebody.a45,somebody.a46,somebody.a47,a1234' >> /etc/gshadow"`,
		`sudo sh -c "echo 'grp2:*::root' >> /etc/gshadow"`,
		`sudo systemd-sysusers`,
	} {
		output, err := m.SSH(cmd)
		if err != nil {
			return fmt.Errorf("failed to run %q: output: %q status: %v", cmd, output, err)
		}
	}

	return nil
}


text:
module.exports = {
  bind: function (app, assetPath) {
    app.get('/', function (req, res) {
      res.render('index', { 'asset_path': assetPath })
    })

    // Redirect snippets page to the index page
    app.get('/snippets', function (req, res) {
      res.redirect('/')
    })

    // Layout
    app.get('/layout', function (req, res) {
      var pageName = 'Layout'
      res.render('guide_layout', { 'page_name': pageName })
    })

    // Example page: Grid layout
    app.get('/layout/example-grid-layout', function (req, res) {
      var section = 'layout'
      var sectionName = 'Layout'
      var pageName = 'Example: Grid layout'
      res.render('examples/example_grid_layout', { 'section': section, 'section_name': sectionName, 'page_name': pageName })
    })

    // Redirect examples from /examples/ to /section/example-name-of-example
    app.get('/examples/grid-layout', function (req, res) {
      res.redirect('/layout/example-grid-layout')
    })

    // Typography
    app.get('/typography', function (req, res) {
      var pageName = 'Typography'
      res.render('guide_typography', { 'page_name': pageName })
    })

    // Example page: Typography
    app.get('/typography/example-typography', function (req, res) {
      var section = 'typography'
      var sectionName = 'Typography'
      var pageName = 'Example: Typography'
      res.render('examples/example_typography', { 'section': section, 'section_name': sectionName, 'page_name': pageName })
    })

    // Redirect examples from /examples/ to /section/example-name-of-example
    app.get('/examples/typography', function (req, res) {
      res.redirect('/typography/example-typography')
    })

    // Example page: Progressive disclosure
    app.get('/typography/example-details-summary', function (req, res) {
      var section = 'typography'
      var sectionName = 'Typography'
      var pageName = 'Example: Details summary'
      res.render('examples/example_details_summary', { 'section': section, 'section_name': sectionName, 'page_name': pageName })
    })

    // Redirect examples from /patterns/ to /section/example-name-of-example
    app.get('/patterns/details-summary', function (req, res) {
      res.redirect('/typography/example-details-summary')
    })

    // Colour
    app.get('/colour', function (req, res) {
      var pageName = 'Colour'
      res.render('guide_colour', { 'page_name': pageName })
    })

    // Icons and images
    app.get('/icons-images', function (req, res) {
      var pageName = 'Icons and images'
      res.render('guide_icons_images', { 'page_name': pageName })
    })

    // Example page: Icons
    app.get('/icons-images/example-icons', function (req, res) {
      var section = 'icons-images'
      var sectionName = 'Icons and images'
      var pageName = 'Example: Icons'
      res.render('examples/example_icons', { 'section': section, 'section_name': sectionName, 'page_name': pageName })
    })

    // Data
    app.get('/data', function (req, res) {
      var pageName = 'Data'
      res.render('guide_data', { 'page_name': pageName })
    })

    // Buttons
    app.get('/buttons', function (req, res) {
      var pageName = 'Buttons'
      res.render('guide_buttons', { 'page_name': pageName })
    })

    // Forms
    app.get('/form-elements', function (req, res) {
      var pageName = 'Form elements'
      res.render('guide_form_elements', { 'page_name': pageName })
    })

    // Example page: Date pattern
    app.get('/form-elements/example-date', function (req, res) {
      var section = 'form-elements'
      var sectionName = 'Form elements'
      var pageName = 'Example: Date'
      res.render('examples/example_date', { 'section': section, 'section_name': sectionName, 'page_name': pageName })
    })

    // Redirect examples from /patterns/ to /section/example-name-of-example
    app.get('/patterns/date', function (req, res) {
      res.redirect('/form-elements/example-date')
    })

    // Example page: Radio buttons and checkboxes
    app.get('/form-elements/example-radios-checkboxes', function (req, res) {
      var section = 'form-elements'
      var sectionName = 'Form elements'
      var pageName = 'Example: Radio buttons and checkboxes'
      res.render('examples/example_radios_checkboxes', { 'section': section, 'section_name': sectionName, 'page_name': pageName })
    })

    // Redirect examples from /patterns/ to /section/example-name-of-example
    app.get('/patterns/radios-checkboxes', function (req, res) {
      res.redirect('/form-elements/example-radios-checkboxes')
    })

    // Example page: Form elements
    app.get('/form-elements/example-form-elements', function (req, res) {
      var section = 'form-elements'
      var sectionName = 'Form elements'
      var pageName = 'Example: Form elements'
      res.render('examples/example_form_elements', { 'section': section, 'section_name': sectionName, 'page_name': pageName })
    })

    // Errors and validation
    app.get('/errors', function (req, res) {
      var pageName = 'Errors and validation'
      res.render('guide_errors', { 'page_name': pageName })
    })

    // Example page: Form validation
    app.get('/errors/example-form-validation-single-question-more-text', function (req, res) {
      var section = 'errors'
      var sectionName = 'Errors and validation'
      var pageName = 'Example: Form validation - single question with additional guidance'
      res.render('examples/example_form_validation_single_question_more_text', { 'section': section, 'section_name': sectionName, 'page_name': pageName })
    })

    app.post('/errors/example-form-validation-single-question-more-text', function (req, res) {
      var section = 'errors'
      var sectionName = 'Errors and validation'
      var pageName = 'Example: Form validation - single question with additional guidance'
      var recognisable = req.body.recognisable
      var error = false
      if (!recognisable) {
        error = true
      } else {
        error = false
      }
      res.render('examples/example_form_validation_single_question_more_text', { 'section': section, 'section_name': sectionName, 'page_name': pageName, 'recognisable': recognisable, 'error': error })
    })

    // Example page: Form validation
    app.get('/errors/example-form-validation-single-question-radio', function (req, res) {
      var section = 'errors'
      var sectionName = 'Errors and validation'
      var pageName = 'Example: Form validation - single question, radio button'
      res.render('examples/example_form_validation_single_question_radio', { 'section': section, 'section_name': sectionName, 'page_name': pageName })
    })

    app.post('/errors/example-form-validation-single-question-radio', function (req, res) {
      var section = 'errors'
      var sectionName = 'Errors and validation'
      var pageName = 'Example: Form validation - single question, radio button'
      var personalDetails = req.body.personalDetails
      var error = false
      if (!personalDetails) {
        error = true
      } else {
        error = false
      }
      res.render('examples/example_form_validation_single_question_radio', { 'section': section, 'section_name': sectionName, 'page_name': pageName, 'personal_details': personalDetails, 'error': error })
    })

    // Example page: Form validation
    app.get('/errors/example-form-validation-single-question-text', function (req, res) {
      var section = 'errors'
      var sectionName = 'Errors and validation'
      var pageName = 'Example: Form validation - single question, text field'
      res.render('examples/example_form_validation_single_question_text', { 'section': section, 'section_name': sectionName, 'page_name': pageName })
    })

    app.post('/errors/example-form-validation-single-question-text', function (req, res) {
      var section = 'errors'
      var sectionName = 'Errors and validation'
      var pageName = 'Example: Form validation - single question, text field'
      var personalDetails = req.body.personalDetails
      var error = false
      if (!personalDetails) {
        error = true
      } else {
        error = false
      }
      res.render('examples/example_form_validation_single_question_text', { 'section': section, 'section_name': sectionName, 'page_name': pageName, 'personal_details': personalDetails, 'error': error })
    })

    // Redirect examples from /examples/ to /section/example-name-of-example
    app.get('/examples/form-validation-single-question-radio', function (req, res) {
      res.redirect('/errors/example-form-validation-single-question-radio')
    })

    app.get('/errors/example-form-validation-multiple-questions', function (req, res) {
      var section = 'errors'
      var sectionName = 'Errors and validation'
      var pageName = 'Example: Form validation - multiple questions'
      res.render('examples/example_form_validation_multiple_questions', { 'section': section, 'section_name': sectionName, 'page_name': pageName })
    })

    app.post('/errors/example-form-validation-multiple-questions', function (req, res) {
      var section = 'errors'
      var sectionName = 'Errors and validation'
      var pageName = 'Example: Form validation - multiple questions'
      var fullName = req.body.fullName
      var niNo = req.body.niNo
      var error = false
      if (!fullName || !niNo) {
        error = true
      } else {
        error = false
      }
      res.render('examples/example_form_validation_multiple_questions', { 'section': section, 'section_name': sectionName, 'page_name': pageName, 'fullName': fullName, 'niNo': niNo, 'error': error })
    })

    // Redirect examples from /examples/ to /section/example-name-of-example
    app.get('/examples/form-validation-multiple-questions', function (req, res) {
      res.redirect('/errors/example-form-validation-multiple-questions')
    })

    // Alpha and beta banners
    app.get('/alpha-beta-banners', function (req, res) {
      var pageName = 'Alpha and beta banners'
      res.render('guide_alpha_beta', { 'page_name': pageName })
    })
  }
}


text:
"""Module Description: Burrows-Wheeler transform

Copyright (c) 2008 Tao Liu <taoliu@jimmy.harvard.edu>

This code is free software; you can redistribute it and/or modify it
under the terms of the BSD License (see the file COPYING included with
the distribution).

@status:  experimental
@version: $Revision$
@author:  Tao Liu
@contact: taoliu@jimmy.harvard.edu
"""

# ------------------------------------
# python modules
# ------------------------------------

import sys
import re

# ------------------------------------
# constants
# ------------------------------------

# ------------------------------------
# Misc functions
# ------------------------------------
def bwt(s):
    s = s + '\0'
    return ''.join([x[-1] for x in                             # Take last character
                    sorted([s[i:] + s[:i] for i in range(len(s))])])    # Of each sorted row

def ibwt(s):
    L = [''] * len(s)                                          # Make empty table
    for i in range(len(s)):
        L = sorted([s[i] + L[i] for i in range(len(s))])         # Sort rows after adding s as first column
    return [x for x in L if x.endswith('\0')][0][:-1]          # Get row ending with null, [:-1] removes the null


text:
/*jshint globalstrict:false, strict:false, maxlen:4000 */
/*global assertEqual, assertNotEqual, assertTrue, assertFalse, assertNull */

////////////////////////////////////////////////////////////////////////////////
/// @brief tests for dump/reload
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2010-2012 triagens GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
///     http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Jan Steemann
/// @author Wilfried Goesgens
/// @author Copyright 2021, ArangoDB GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////

var internal = require("internal");
var jsunity = require("jsunity");
const deriveTestSuite = require('@arangodb/test-helper').deriveTestSuite;
const base = require("fs").join(
  internal.pathForTesting('server'),
  'dump',
  'dump-test.inc');
const baseTests = require("internal").load(base);

jsunity.run(function dump_single_testsuite() {

  let suite = {};

  deriveTestSuite(
    baseTests(),
    suite,
    "_single",
    [ // <-- Blacklisted Tests
      // Magic Hint: Those tests are tests which you need to additional blacklist in case they are not supported
      // in that specific environment. Those blacklist is separately and manually maintained per test-suite.

      "testUsers",
      // cluster tests:
      "testDatabaseProperties",
      "testShards",
      "testReplicationFactor",

      // enterprise graph tests:
      "testVertices",
      "testVerticesAqlRead",
      "testVerticesAqlInsert",
      "testOrphans",
      "testOrphansAqlRead",
      "testOrphansAqlInsert",
      "testSatelliteCollections",
      "testSatelliteGraph",
      "testHiddenCollectionsOmitted",
      "testShadowCollectionsOmitted",
      "testEEEdges",
      "testEdgesAqlRead",
      "testEdgesAqlInsert",
      "testAqlGraphQueryOutbound",
      "testAqlGraphQueryAny",
      "testSmartGraphSharding",
      "testViewOnSmartEdgeCollection",
      "testSmartGraphAttribute",

      // enterprise sharded graphs on single server tests
      "testEmptySmartGraph",
      "testEmptyEnterpriseGraph",
      "testEmptySatelliteGraph",
      "testEmptyDisjointGraph",
      "testSmartGraphWithoutData",
      "testEnterpriseGraphWithoutData",
      "testSmartGraphSingleServer",
      "testEnterpriseGraphSingleServer",
      "testSatelliteSmartGraphSingleServer",
      "testDisjointGraphSingleServer",
      "testHybridSmartGraphSingleServer",
      "testHybridDisjointSmartGraphSingleServer",

      // Hotbackup tests:
      "testLatestId"
    ]
  );

  return suite;

});

return jsunity.done();


text:
class Caboose::CaboosePlugin

  def self.page_content(str)
    return str
  end

  def self.post_content(post)
    return post
  end

  def self.event_content(event)
    return event
  end

  def self.admin_nav(nav, user, page, site)
    return nav
  end

  def self.login_success(return_url, user_id)
    return return_url
  end

end


text:
/*
 * Misc boot support
 */
#include <common.h>
#include <command.h>
#include <net.h>

#ifdef CONFIG_CMD_BOOTA
#include <fastboot.h>

static unsigned char boot_hdr[512];

extern int do_boota_linux (struct fastboot_boot_img_hdr *hdr);

int do_boota (cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
	ulong	addr;
	unsigned kaddr, raddr;

	if (argc < 2)
		return cmd_usage(cmdtp);

	addr = simple_strtoul(argv[1], NULL, 16);

	struct fastboot_boot_img_hdr *fb_hdr = (struct fastboot_boot_img_hdr *)addr;
	image_header_t *hdr =(image_header_t *)(addr + CFG_FASTBOOT_MKBOOTIMAGE_PAGE_SIZE);
	/* save the image header somewhere */
	memcpy(boot_hdr, (void*) addr, sizeof(*hdr));

	/* add code for signature */
	do_sunxi_boot_signature(NULL, 0, 0, NULL);

	if (memcmp(fb_hdr->magic, FASTBOOT_BOOT_MAGIC, 8)) {
		puts("boota: bad boot image magic, maybe not a boot.img?\n");
		return 1;
	}
#ifdef DEBUG
	printf("---------------------\n");
	printf("kernel size: 0x%x \n", fb_hdr->kernel_size);
	printf("kernel addr: 0x%x \n", fb_hdr->kernel_addr);

	printf("ramdisk size: 0x%x \n", fb_hdr->ramdisk_size);
	printf("ramdisk addr: 0x%x \n", fb_hdr->ramdisk_addr);

	printf("second size: 0x%x \n", fb_hdr->second_size);
	printf("second addr: 0x%x \n", fb_hdr->second_addr);

	printf("name: %s\n", fb_hdr->name);
	printf("cmdline: %s\n", fb_hdr->cmdline);
#endif

	kaddr = addr + fb_hdr->page_size;
	raddr = kaddr + ALIGN(fb_hdr->kernel_size, fb_hdr->page_size);
#ifdef DEBUG
	printf("moving kernel from %x to: %x, size 0x%x\n", kaddr, fb_hdr->kernel_addr, fb_hdr->kernel_size);
	printf("moving ramdisk from %x to: %x, size 0x%x\n", raddr, fb_hdr->ramdisk_addr, fb_hdr->ramdisk_size);
#endif
	//memmove((void*) fb_hdr->kernel_addr, (const void *)kaddr, fb_hdr->kernel_size);
	//memmove((void*) fb_hdr->ramdisk_addr, (const void *)raddr, fb_hdr->ramdisk_size);
	memcpy((void*) fb_hdr->kernel_addr, (const void *)kaddr, fb_hdr->kernel_size);
	memcpy((void*) fb_hdr->ramdisk_addr, (const void *)raddr, fb_hdr->ramdisk_size);

	tick_printf("ready to boot\n");

	do_boota_linux(fb_hdr);

	puts("Boot linux failed, control return to monitor\n");

	return 0;
}

U_BOOT_CMD(
	boota,	3,	1,	do_boota,
	"boota   - boot android bootimg from memory\n",
	"<addr>\n    - boot application image stored in memory\n"
	"\t'addr' should be the address of boot image which is kernel+ramdisk.img\n"
);
#endif