text:
/**
 * @class This class is responsible for returning new instances of test view
 * objects.
 *
 * @extends Object
 */
function TestViewFactory() {
	this.constructor();
}

/** @lends TestFactory */
TestViewFactory.prototype = {

	/**
	 * @property {Object} A hash object of views indexed by their rootNodeId
	 */
	instances: null,

	/**
	 * @constructs
	 *
	 * @param {void}
	 * @return {void}
	 */
	constructor: function() {
		this.instances = {};
	},

	/**
	 * Get a new instance of a test view object
	 *
	 * @param {String} type The type of view to instantiate
	 * @param {String} rootNodeId Id of the root node for the new view
	 * @return {Object} A new test view object
	 */
	getInstance: function( type, rootNodeId ) {
		if ( !this.instances[ rootNodeId ] ) {
			if ( "progress" === type ) {
				this.instances[ rootNodeId ] = new TestProgressView( rootNodeId );
			}
			else if ( "summary" === type ) {
				this.instances[ rootNodeId ] = new TestSummaryView( rootNodeId );
			}
			else {
				this.instances[ rootNodeId ] = null;
				throw new Error( "An invalid view type was specified in TestViewFactory.getInstance(). " + type + " given." );
			}
		}

		return this.instances[ rootNodeId ];
	}

};

/**
 * @property {TestViewFactory} The sole instance of this class
 */
TestViewFactory.instance = null;

/**
 * @static
 *
 * Get an instance of this class
 *
 * @param {void}
 * @return {TestViewFactory}
 */
TestViewFactory.getInstance = function() {
	if ( this.instance === null ) {
		this.instance = new this();
	}

	return this.instance;
};

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
    <ru0xdc.rtkgps.settings.widget.PositioningModePreference
        android:dialogTitle="@string/procopt_positioning_mode_dialog_title"
        android:key="positioning_mode"
        android:title="@string/procopt_positioning_mode_title" />
    <ListPreference
        android:dialogTitle="@string/procopt_number_of_freqencies_dialog_title"
        android:entries="@array/procopt_number_of_frequencies_entries"
        android:entryValues="@array/procopt_number_of_frequencies_values"
        android:key="number_of_frequencies"
        android:title="@string/procopt_number_of_freqencies_title" />

    <ru0xdc.rtkgps.settings.widget.MultiSelectListPreferenceWorkaround
        android:dialogTitle="@string/procopt_navigation_system_dialog_title"
        android:key="navigation_system"
        android:title="@string/procopt_navigation_system_title" />

    <ListPreference
        android:dialogTitle="@string/procopt_elevation_mask_dialog_title"
        android:entries="@array/procopt_elevation_mask_entries"
        android:entryValues="@array/procopt_elevation_mask_entries"
        android:key="elevation_mask"
        android:title="@string/procopt_elevation_mask_title" />
    <ListPreference
        android:dialogTitle="@string/procopt_snr_mask_dialog_title"
        android:entries="@array/procopt_snr_entries"
        android:entryValues="@array/procopt_snr_entries"
        android:key="snr_mask"
        android:title="@string/procopt_snr_mask_title" />

    <CheckBoxPreference
        android:key="rec_dynamics"
        android:summary="@string/procopt_rec_dynamics_summary"
        android:title="@string/procopt_rec_dynamics_title" />
    <ru0xdc.rtkgps.settings.widget.EarthTideCorrectionPreference
        android:key="rec_earth_tides_correction"
        android:title="@string/procopt_rec_earth_tides_correction_title" />

    <ru0xdc.rtkgps.settings.widget.IonosphereCorrectionPreference
        android:dialogTitle="@string/procopt_ionosphere_correction_dialog_title"
        android:key="ionosphere_correction"
        android:title="@string/procopt_ionosphere_correction_title" />
    <ru0xdc.rtkgps.settings.widget.TroposphereCorrectionPreference
        android:dialogTitle="@string/procopt_troposphere_correction_dialog_title"
        android:key="troposphere_correction"
        android:title="@string/procopt_troposphere_correction_title" />
    <ru0xdc.rtkgps.settings.widget.EphemerisOptionPreference
        android:dialogTitle="@string/procopt_satellite_ephemeris_clock_dialog_title"
        android:key="satellite_ephemeris_clock"
        android:title="@string/procopt_satellite_ephemeris_clock_title" />

    <CheckBoxPreference
        android:key="sat_antenna_pcv"
        android:summary="@string/procopt_sat_antenna_pcv_summary"
        android:title="@string/procopt_sat_antenna_pcv_title" />
    <CheckBoxPreference
        android:key="receiver_antenna_pcv"
        android:summary="@string/procopt_receiver_antenna_pcv_summary"
        android:title="@string/procopt_receiver_antenna_pcv_title" />
    <CheckBoxPreference
        android:key="phase_windup_correction"
        android:summary="@string/procopt_phase_windup_correction_summary"
        android:title="@string/procopt_phase_windup_correction_title" />
    <CheckBoxPreference
        android:key="exclude_eclipsing_sat_measurements"
        android:summary="@string/procopt_exclude_eclipsing_sat_measurements_summary"
        android:title="@string/procopt_exclude_eclipsing_sat_measurements_title" />
    <CheckBoxPreference
        android:key="raim_fde"
        android:summary="@string/procopt_raim_fde_summary"
        android:title="@string/procopt_raim_fde_title" />
</PreferenceScreen>


text:
const should = require('chai').should();

const sinon = require('sinon');
import AuctionRoom from '../build/auctionRoom.js';
import AuctionRepository from '../build/auctionRepository.js';

describe('Auction user test', () => {
  context(`As a potential buyer in an online auction
          I want to be able to bid on an item
          So that I can participate in the auction`, () => {

            context('􀀊􀂋􀂘􀂇􀂐􀀃􀀌􀀃􀂃􀂏􀀃􀂋􀂐􀀃􀂖􀂊􀂇􀀃􀂃􀂗􀂅􀂖􀂋􀂑􀂐􀀃􀂔􀂑􀂑􀂏Given I am in the auction room', () => {
              let auctionRoom = new AuctionRoom();
              let auctionRepository = new AuctionRepository();

              before((done) => {
                auctionRepository.clearAll().then(() => {
                  let item = {code: 'A0001', name:'item one',picture: 'a_picture', description: 'my item',
                  highestBid: {value:100.00, date: '2016-07-18T04:11:47.468Z',
                  user:{name: 'John Doe'}}};
                  auctionRoom.addItem(item).then(done());
                });
              });

              it('Then I see the current item picture, description and name', (done) => {
                let validations = (item) => {
                  should.exist(item.picture);
                  should.exist(item.name);
                  should.exist(item.description);
                  done();
                };

                auctionRepository.findItem({code:'A0001'}).then((item) => {
                  validations(item);
                });

              });

                it('And I see the current highest bid with a button to place a new bid', (done) => {
                auctionRepository.findItem({code:'A0001'}).then((item) => {
                  should.equal(auctionRoom.getHighestBid(item).value,100.00);
                  auctionRoom.canBid({},{}).should.be.true;
                  done();
                });

              });

              context('When I place a bid on an item', () => {
                beforeEach((done) => {
                  auctionRepository.clearAll().then(() => {
                    let item = {code: 'A0001', name:'item one',picture: 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTfwWiOGCFGh_gakXkbQxPn_YvBO40RKat1-JAqAP9_z7Kj1l1c2A', description: 'my item',
                    highestBid: {value:100.00, date: '2016-07-18T04:11:47.468Z',
                    user:{name: 'John Doe'}}};
                    auctionRoom.addItem(item).then(done());
                  });

                });
                describe('And I am the only bidder', () => {
                  it('Then I am the highest bidder', (done) => {
                    let user = {'name':'John Doe'};
                    let item = {code: 'A0001', name:'item one',picture: 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTfwWiOGCFGh_gakXkbQxPn_YvBO40RKat1-JAqAP9_z7Kj1l1c2A', description: 'my item'};
                    let value = 120;

                    auctionRoom.placeBid(item, user, value).then(() => {
                      auctionRepository.findItem(item).then((result) => {
                        should.equal(120, result.highestBid.value);
                        done();
                      });
                    });
                  }).timeout(5000);;
                });
                describe('And I am not the only bidder', () => {
                  describe('And my bid was placed first', () => {
                    it('Then I am the highest bidder', (done) => {
                      let userOne = {'name':'John Doe'};
                      let userTwo = {'name': 'Jane Doe'};
                      let item = {code: 'A0001', name:'item one',picture: 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTfwWiOGCFGh_gakXkbQxPn_YvBO40RKat1-JAqAP9_z7Kj1l1c2A', description: 'my item'};
                      let value = 150;

                      auctionRoom.placeBid(item, userOne, value).then(() => {
                          auctionRoom.placeBid(item, userOne, value).then(() => {
                            auctionRepository.findItem(item).then((result) => {
                              should.equal(result.highestBid.value, 150);
                              done();
                            });
                          });
                      });
                    }).timeout(5000);
                  });

                  describe('And my bid was not placed first', () => {
                    it('Then I am not the highest bidder', (done) => {
                      let userOne = {'name':'james Doe'};
                      let userTwo = {'name': 'Jane Doe'};
                      let item = {code: 'A0001', name:'item one',picture: 'a_picture', description: 'my item'};
                      let value = 200;

                      let secondBid = () => {
                        auctionRoom.placeBid(item, userOne, value).then((response) => {
                          validateUser()
                        });
                      };

                      let validateUser = () => {
                        auctionRepository.findItem(item).then((result) => {
                          should.equal(result.highestBid.user.name, userTwo.name);
                          done();
                        });
                      };

                      auctionRoom.placeBid(item, userTwo, value).then((response) => {

                        secondBid()
                      });

                    }).timeout(5000);
                  });
                });
              });
            });
  });
});


text:
package algo.other.tree.BSTTree;

import algo.other.tree.BTreePrinter;
import algo.other.tree.TreeNode;
import apple.laf.JRSUIUtils;
import org.junit.Test;

import javax.transaction.TransactionRequiredException;
import java.util.Objects;

/**
 * @Author: sunhaijian
 * @Date: 2020/4/26
 * @Description:
 **/
public class TestTree {

    @Test
    public void test(){

        TreeNode treeNode= TreeNode.generateTree();
        BTreePrinter.printTreeNode(treeNode);

    }

    /**
     * 二叉树所有的节点中的值加一
     */
    @Test
    public void test1(){

        TreeNode treeNode= TreeNode.generateTree();
        BTreePrinter.printTreeNode(treeNode);
        treeNodeValPlus(treeNode);
        BTreePrinter.printTreeNode(treeNode);
    }

    public void treeNodeValPlus(TreeNode treeNode){
        if(treeNode==null){
            return ;
        }
        treeNode.val++;
        treeNodeValPlus( treeNode.left);
        treeNodeValPlus( treeNode.right);
    }

}


text:
typedef void (^CallbackBlock)(void);

typedef enum {
	CMActionSheetButtonTypeWhite = 0,
	CMActionSheetButtonTypeBlue,
	CMActionSheetButtonTypeRed,
	CMActionSheetButtonTypeGray
} CMActionSheetButtonType;

@interface CMActionSheet : NSObject

@property (retain) NSString *title;

- (void)addButtonWithTitle:(NSString *)title type:(CMActionSheetButtonType)type block:(CallbackBlock)block;
- (void)addSeparator;

- (void)present;
- (void)dismissWithClickedButtonIndex:(NSUInteger)index animated:(BOOL)animated;

@end


text:
using System;

namespace HomeCinema.Data.Infrastructure
{
    public class Disposable : IDisposable
    {
        private bool isDisposed;

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        ~Disposable()
        {
            Dispose(false);
        }

        private void Dispose(bool disposing)
        {
            if (!isDisposed && disposing)
            {
                DisposeCore();
            }

            isDisposed = true;
        }

        // Ovveride this to dispose custom objects
        protected virtual void DisposeCore()
        {
        }
    }
}


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

    /*
	    Top menu
	*/
	$('.show-menu a, .hide-menu a').tooltip();
	// show/hide menu
	$('.show-menu a').on('click', function(e) {
		e.preventDefault();
		$(this).fadeOut(100, function(){ $('nav').slideDown(); });
	});
	$('.hide-menu a').on('click', function(e) {
		e.preventDefault();
		$('nav').slideUp(function(){ $('.show-menu a').fadeIn(); });
	});
	// navigation
	$('nav a').on('click', function(e) {
		e.preventDefault();
		var element_class = $(this).attr('class');
		var scroll_to = 0;
		var nav_height = $('nav').height();
		if(element_class == 'menu-top') { scroll_to = $(".coming-soon").offset().top; }
		else if(element_class == 'menu-subscribe') { scroll_to = $(".subscribe").offset().top - nav_height - 60; }
		else if(element_class == 'menu-project') { scroll_to = $(".about").offset().top - nav_height - 60; }
		else if(element_class == 'menu-testimonials') { scroll_to = $(".testimonials").offset().top - nav_height - 60; }
		else if(element_class == 'menu-about-us') { scroll_to = $(".whos-behind").offset().top - nav_height - 60; }
		else if(element_class == 'menu-contact') { scroll_to = $(".contact").offset().top - nav_height - 60; }

		if($(window).scrollTop() != scroll_to && element_class !== undefined) {
			$('html, body').animate({scrollTop: scroll_to}, 1000);
		}
	});

    /*
        Background slideshow
    */
    $('.coming-soon').backstretch([
      "uploads/backgrounds/1.jpg"
    , "uploads/backgrounds/2.jpg"
    , "uploads/backgrounds/3.jpg"
    ], {duration: 3000, fade: 750});

    $('.about-container').backstretch("uploads/backgrounds/2.jpg");

    $('.whos-behind-container').backstretch("uploads/backgrounds/4.jpg");

    /*
        Countdown initializer
    */
    var now = new Date(2015,8,20);
    var countTo = now.valueOf();
    $('.timer').countdown(countTo, function(event) {
    	$(this).find('.days').text(event.offset.totalDays);
    	$(this).find('.hours').text(event.offset.hours);
    	$(this).find('.minutes').text(event.offset.minutes);
    	$(this).find('.seconds').text(event.offset.seconds);
    });

    /*
        Testimonials
    */
    $('.testimonial-active').html('
' + $('.testimonial-single:first p').html() + '
');
    $('.testimonial-single:first .testimonial-single-image img').css('opacity', '1');

    $('.testimonial-single-image img').on('click', function() {
    	$('.testimonial-single-image img').css('opacity', '0.5');
    	$(this).css('opacity', '1');
    	var new_testimonial_text = $(this).parent('.testimonial-single-image').siblings('p').html();
    	$('.testimonial-active p').fadeOut(300, function() {
    		$(this).html(new_testimonial_text);
    		$(this).fadeIn(400);
    	});
    });

    /*
	    Show latest tweets
	*/
	$('.latest-tweets .tweets').tweet({
		modpath: 'twitter/',
		username: 'princedominh',
		page: 1,
		count: 5,
		loading_text: 'loading ...'
	});

	$('.latest-tweets .tweets .tweet_list li').append('');
	$('.latest-tweets .tweets .tweet_list li:first .tweet_nav').css('background', '#e8643e');
	$('.latest-tweets .tweets .tweet_list li .tweet_time').hide();
	$('.latest-tweets .tweets .tweet_list li .tweet_text').hide();
	$('.latest-tweets .tweet-active').html($('.latest-tweets .tweets .tweet_list li:first .tweet_text').html());

	$('.latest-tweets .tweets .tweet_list li .tweet_nav').on('click', function() {
		$('.latest-tweets .tweets .tweet_list li .tweet_nav').css('background', 'rgba(255, 255, 255, 0.6)');
		var clicked_tweet_nav = $(this);
    	var new_tweet_text = clicked_tweet_nav.siblings('.tweet_text').html();
    	$('.latest-tweets .tweet-active').fadeOut(300, function() {
    		$(this).html(new_tweet_text);
    		$(this).fadeIn(400, function() {
    			// reload background
    			$('.whos-behind-container').backstretch("resize");
    		});
    	});
    	clicked_tweet_nav.css('background', '#e8643e');
    });

    /*
	    Google maps
	*/
    var position = new google.maps.LatLng(13.798948,109.185476);
    $('.contact-address .map').gmap({'center': position, 'zoom': 16, 'disableDefaultUI':true, 'callback': function() {
            var self = this;
            self.addMarker({'position': this.get('map').getCenter() });
        }
    });

    /*
        Subscription form
    */
    $('.success-message').hide();
    $('.error-message').hide();

    $('.subscribe form').submit(function(e) {
    	e.preventDefault();
        var postdata = $('.subscribe form').serialize();
        $.ajax({
            type: 'POST',
            url: 'assets/subscribe.php',
            data: postdata,
            dataType: 'json',
            success: function(json) {
                if(json.valid == 0) {
                    $('.success-message').hide();
                    $('.error-message').hide();
                    $('.error-message').html(json.message);
                    $('.error-message').fadeIn();
                }
                else {
                    $('.error-message').hide();
                    $('.success-message').hide();
                    $('.subscribe form').hide();
                    $('.success-message').html(json.message);
                    $('.success-message').fadeIn();
                }
            }
        });
    });

    /*
	    Contact form
	*/
    $('.contact-form form input[type="text"], .contact-form form textarea').on('focus', function() {
    	$('.contact-form form input[type="text"], .contact-form form textarea').removeClass('contact-error');
    });
	$('.contact-form form').submit(function(e) {
		e.preventDefault();
	    $('.contact-form form input[type="text"], .contact-form form textarea').removeClass('contact-error');
	    var postdata = $('.contact-form form').serialize();
	    $.ajax({
	        type: 'POST',
	        url: '/contact',
	        data: postdata,
	        dataType: 'json',
	        success: function(json) {
	            if(json.emailMessage != '') {
	                $('.contact-form form .contact-email').addClass('contact-error');
	            }
	            if(json.subjectMessage != '') {
	                $('.contact-form form .contact-subject').addClass('contact-error');
	            }
	            if(json.messageMessage != '') {
	                $('.contact-form form textarea').addClass('contact-error');
	            }
	            if(json.emailMessage == '' && json.subjectMessage == '' && json.messageMessage == '') {
	                $('.contact-form form').fadeOut('fast', function() {
	                    $('.contact-form').append('
Cảm ơn bạn đã liên hệ với chúng tôi! Chúng tôi sẽ sớm xem xet thông tin từ bạn.
');
	                });
	            }
	        }
	    });
	});

});


text:
difficulty 2
description "Optimise how your repository is packaged ensuring that redundant packs are removed."

setup do
  repo.init
  FileUtils.touch("foo")
  repo.add("foo")
  repo.commit_all("Added foo")
end

solution do
  result = `git count-objects -v`
  required = ["count: 0", "prune-packable: 0"];
  required.all? { |r| result.include?(r) }
end

hint do
  puts "You want to research the `git repack` command."
end


text:
import { LRUCache } from "./lru";
import { merge } from "./merge";
import { ConnectFunction, InEnvelope, OutEnvelope } from "./pingingwebsocket";
import { ReconnectingWebSocket } from "./reconnectingwebsocket";
import { MutationSpec } from "./spec";

export const ErrorNotConnected = "not connected";
export const ErrorMutationTimeout = "mutation timed out";
export const ErrorConnectionClosed = "connection closed";

export interface GraphQLData<Result> {
  data: GraphQLResult<Result>;
}

export type GraphQLResult<Result> =
  | {
      state: "error";
      error: GraphQLError;
      value: never;
    }
  | {
      state: "loading";
      value?: Result;
      error: never;
    }
  | {
      state: "subscribed";
      value: Result;
      error: never;
    }
  | {
      state: "cached";
      value: Result;
      error: never;
    };

function dataFromSubscription<Result, Input>(
  subscription: Subscription<Result, Input>,
) {
  return Object.freeze({
    state: subscription.state,
    value: subscription.value,
    error: subscription.error,
  }) as GraphQLResult<Result>;
}

export class GraphQLError extends Error {
  constructor(message: string) {
    super(message);

    // Set the prototype explicitly.
    Object.setPrototypeOf(this, GraphQLError.prototype);
  }
}

// n.b `valid` for graphql subscriptions means "valid for the current query,"
// i.e. "cached" and "subscribed" are both valid, but "previous" is not.
export type SubscriptionState =
  // The current data is valid for this query, but potentially stale.
  | "cached"
  // The current data is being loaded
  | "loading"
  // The current data is valid and current
  | "subscribed"
  // The subscription returned an error from the backend
  | "error";

interface GraphqlQuery<InputVariables> {
  query: string;
  variables: InputVariables;
}

export interface Subscription<Result, InputVariables>
  extends GraphqlQuery<InputVariables> {
  state: SubscriptionState;
  retryDelay: number;
  retryHandle: any;
  observer: (data: GraphQLResult<Result>) => void;
  value: Result | undefined;
  error?: GraphQLError;
}

export interface Mutation<InputVariables> extends GraphqlQuery<InputVariables> {
  resolve: any;
  reject: any;
  timeout: number;
}

export type Observer<Result> = (data: Result) => void;

class Connection {
  nextId = 0;
  subscriptions = new Map<string, Subscription<object, object>>();
  mutations = new Map<string, Mutation<object | undefined>>();
  past = new LRUCache(100);
  initialRetryDelay = 1000;
  maxRetryDelay = 60000;
  mutationTimeoutMs = 10000;
  socket: ReconnectingWebSocket;

  constructor(connectFunction: ConnectFunction) {
    this.socket = new ReconnectingWebSocket(connectFunction, {
      onOpen: this.handleOpen.bind(this),
      onClose: this.handleClose.bind(this),
      onMessage: this.handleMessage.bind(this),
    });
    this.socket.reconnect();
  }

  makeId() {
    return (this.nextId++).toString();
  }

  subscribe<QueryResult extends object, QueryInputVariables extends object>({
    query,
    variables,
    observer,
  }: {
    query: string;
    variables: QueryInputVariables;
    observer: Observer<GraphQLResult<QueryResult>>;
  }) {
    const id = this.makeId();

    const cached = this.past.find({
      query,
      variables,
    }) as QueryResult | undefined;

    const subscription: Subscription<QueryResult, QueryInputVariables> = {
      state: cached ? "cached" : "loading",
      retryDelay: this.initialRetryDelay,
      retryHandle: undefined,
      query,
      variables,
      observer,
      value: cached,
      error: undefined,
    };

    this.subscriptions.set(id, subscription as Subscription<any, any>);

    if (this.socket.state === "connected") {
      this.send({
        id,
        type: "subscribe",
        message: { query, variables },
      });
    }

    return {
      close: () => {
        const sub = this.subscriptions.get(id);
        if (!sub) {
          return;
        }

        if (sub.value !== undefined) {
          this.past.add({ query, variables }, sub.value);
        }

        this.subscriptions.delete(id);
        if (this.socket.state === "connected") {
          this.send({ id, type: "unsubscribe" });
        }
      },
      data: () => {
        return dataFromSubscription(subscription);
      },
    };
  }

  mutate<
    MutationInputVariables extends object | undefined,
    MutationOutput extends object
  >({
    query,
    variables,
  }: MutationInputVariables extends undefined
    ? {
        query: MutationSpec<MutationOutput, MutationInputVariables>;
        variables?: undefined;
      }
    : {
        query: MutationSpec<MutationOutput, MutationInputVariables>;
        variables: MutationInputVariables;
      }): Promise<MutationOutput>;

  mutate<MutationInputVariables extends object | undefined, MutationOutput>({
    query,
    variables,
  }: MutationInputVariables extends undefined
    ? {
        query: string;
        variables?: undefined;
      }
    : {
        query: string;
        variables: MutationInputVariables;
      }): Promise<MutationOutput>;

  mutate<
    MutationInputVariables extends object | undefined,
    MutationOutput extends object
  >({
    query: queryInput,
    variables,
  }: MutationInputVariables extends undefined
    ? {
        query: string | MutationSpec<MutationOutput, MutationInputVariables>;
        variables?: undefined;
      }
    : {
        query: string | MutationSpec<MutationOutput, MutationInputVariables>;
        variables: MutationInputVariables;
      }): Promise<MutationOutput> {
    const id = this.makeId();

    const query =
      typeof queryInput === "string" ? queryInput : queryInput.query;

    if (this.socket.state === "connected") {
      this.send({ id, type: "mutate", message: { query, variables } });
    } else {
      return Promise.reject(new Error(ErrorNotConnected));
    }

    return new Promise((resolve, reject) => {
      const mutation: Mutation<object | undefined> = {
        query,
        variables,
        timeout: setTimeout(
          () => mutation.reject(new Error(ErrorMutationTimeout)),
          this.mutationTimeoutMs,
        ),
        resolve,
        reject,
      };

      this.mutations.set(id, mutation);
    });
  }

  notify(subscription: Subscription<object, object>) {
    subscription.observer(dataFromSubscription(subscription));
  }

  retry(id: string) {
    const subscription = this.subscriptions.get(id);
    if (subscription === undefined) {
      return;
    }

    this.send({
      id,
      type: "subscribe",
      message: { query: subscription.query, variables: subscription.variables },
    });
  }

  open() {
    this.socket.reconnect();
  }

  close() {
    this.socket.close();
  }

  send(message: OutEnvelope) {
    this.socket.send(message);
  }

  handleOpen() {
    for (const [id, subscription] of this.subscriptions) {
      this.send({
        id,
        type: "subscribe",
        message: {
          query: subscription.query,
          variables: subscription.variables,
        },
      });
      if (subscription.retryHandle) {
        clearTimeout(subscription.retryHandle);
        subscription.retryHandle = undefined;
      }
    }
  }

  handleClose() {
    for (const [, subscription] of this.subscriptions) {
      if (subscription.state === "subscribed") {
        subscription.state = "cached";
        this.notify(subscription);
      }
    }

    for (const [, mutation] of this.mutations) {
      mutation.reject(new Error(ErrorConnectionClosed));
    }
    this.mutations.clear();
  }

  handleMessage(envelope: InEnvelope) {
    let subscription: Subscription<object, object> | undefined;
    let mutation: Mutation<object | undefined> | undefined;

    switch (envelope.type) {
      case "update":
        subscription = this.subscriptions.get(envelope.id);
        if (subscription !== undefined) {
          if (subscription.state !== "subscribed") {
            subscription.state = "subscribed";
            subscription.error = undefined;
            subscription.retryDelay = this.initialRetryDelay;
          }

          subscription.value = merge(subscription.value, envelope.message);
          this.notify(subscription);
        }
        break;

      case "result":
        mutation = this.mutations.get(envelope.id);
        if (mutation !== undefined) {
          mutation.resolve(merge(null, envelope.message));
          clearTimeout(mutation.timeout);
          this.mutations.delete(envelope.id);
        }
        break;

      case "error":
        subscription = this.subscriptions.get(envelope.id);
        if (subscription !== undefined) {
          console.error(
            "Subscription failed. Query:\n",
            subscription.query,
            "\nVariables:\n",
            subscription.variables,
            "\nError:\n",
            envelope.message,
          );

          subscription.state = "error";
          subscription.error = new GraphQLError(envelope.message);

          subscription.retryHandle = setTimeout(
            () => this.retry(envelope.id),
            subscription.retryDelay,
          );
          subscription.retryDelay = Math.min(
            this.maxRetryDelay,
            subscription.retryDelay * 2,
          );
          this.notify(subscription);
        }

        mutation = this.mutations.get(envelope.id);
        if (mutation !== undefined) {
          console.error(
            "Mutation failed. Query:\n",
            mutation.query,
            "\nVariables:\n",
            mutation.variables,
            "\nError:\n",
            envelope.message,
          );

          mutation.reject(new GraphQLError(envelope.message));
          clearTimeout(mutation.timeout);
          this.mutations.delete(envelope.id);
        }
        break;

      default:
        break;
    }
  }
}

export { Connection };


text:
@interface ArticleDetailModel : NSObject

@property (copy, nonatomic) NSString *body; //文章body
@property (copy, nonatomic) NSString *image_source; //图片版权声明
@property (copy, nonatomic) NSString *title; //文章标题
@property (copy, nonatomic) NSString *image; //图片url地址
@property (copy, nonatomic) NSString *share_url; //文章分享地址
@property (copy, nonatomic) NSString *js; //文章js(一般没有)
@property (copy, nonatomic) NSString *ga_prefix;
@property (copy, nonatomic) NSString *type;
@property (copy, nonatomic) NSString *articleID;
@property (copy, nonatomic) NSString *css; //文章css

- (instancetype)initWithDict:(NSDictionary *)dict;

@end


text:
#include "usbportability.h"
#include "usbdrv.h"
#include "oddebug.h"

/*
General Description:
This module implements the C-part of the USB driver. See usbdrv.h for a
documentation of the entire driver.
*/

/* ------------------------------------------------------------------------- */

/* raw USB registers / interface to assembler code: */
uchar usbRxBuf[2*USB_BUFSIZE];  /* raw RX buffer: PID, 8 bytes data, 2 bytes CRC */
uchar       usbInputBufOffset;  /* offset in usbRxBuf used for low level receiving */
uchar       usbDeviceAddr;      /* assigned during enumeration, defaults to 0 */
uchar       usbNewDeviceAddr;   /* device ID which should be set after status phase */
uchar       usbConfiguration;   /* currently selected configuration. Administered by driver, but not used */
volatile schar usbRxLen;        /* = 0; number of bytes in usbRxBuf; 0 means free, -1 for flow control */
uchar       usbCurrentTok;      /* last token received or endpoint number for last OUT token if != 0 */
uchar       usbRxToken;         /* token for data we received; or endpont number for last OUT */
volatile uchar usbTxLen = USBPID_NAK;   /* number of bytes to transmit with next IN token or handshake token */
uchar       usbTxBuf[USB_BUFSIZE];/* data to transmit with next IN, free if usbTxLen contains handshake token */
#if USB_COUNT_SOF
volatile uchar  usbSofCount;    /* incremented by assembler module every SOF */
#endif
#if USB_CFG_HAVE_INTRIN_ENDPOINT && !USB_CFG_SUPPRESS_INTR_CODE
usbTxStatus_t  usbTxStatus1;
#   if USB_CFG_HAVE_INTRIN_ENDPOINT3
usbTxStatus_t  usbTxStatus3;
#   endif
#endif
#if USB_CFG_CHECK_DATA_TOGGLING
uchar       usbCurrentDataToken;/* when we check data toggling to ignore duplicate packets */
#endif

/* USB status registers / not shared with asm code */
uchar               *usbMsgPtr;     /* data to transmit next -- ROM or RAM address */
static usbMsgLen_t  usbMsgLen = USB_NO_MSG; /* remaining number of bytes */
static uchar        usbMsgFlags;    /* flag values see below */

#define USB_FLG_MSGPTR_IS_ROM   (1<<6)
#define USB_FLG_USE_USER_RW     (1<<7)

/*
optimizing hints:
- do not post/pre inc/dec integer values in operations
- assign value of USB_READ_FLASH() to register variables and don't use side effects in arg
- use narrow scope for variables which should be in X/Y/Z register
- assign char sized expressions to variables to force 8 bit arithmetics
*/

/* -------------------------- String Descriptors --------------------------- */

#if USB_CFG_DESCR_PROPS_STRINGS == 0

#if USB_CFG_DESCR_PROPS_STRING_0 == 0
#undef USB_CFG_DESCR_PROPS_STRING_0
#define USB_CFG_DESCR_PROPS_STRING_0    sizeof(usbDescriptorString0)
PROGMEM char usbDescriptorString0[] = { /* language descriptor */
    4,          /* sizeof(usbDescriptorString0): length of descriptor in bytes */
    3,          /* descriptor type */
    0x09, 0x04, /* language index (0x0409 = US-English) */
};
#endif

#if USB_CFG_DESCR_PROPS_STRING_VENDOR == 0 && USB_CFG_VENDOR_NAME_LEN
#undef USB_CFG_DESCR_PROPS_STRING_VENDOR
#define USB_CFG_DESCR_PROPS_STRING_VENDOR   sizeof(usbDescriptorStringVendor)
PROGMEM int  usbDescriptorStringVendor[] = {
    USB_STRING_DESCRIPTOR_HEADER(USB_CFG_VENDOR_NAME_LEN),
    USB_CFG_VENDOR_NAME
};
#endif

#if USB_CFG_DESCR_PROPS_STRING_PRODUCT == 0 && USB_CFG_DEVICE_NAME_LEN
#undef USB_CFG_DESCR_PROPS_STRING_PRODUCT
#define USB_CFG_DESCR_PROPS_STRING_PRODUCT   sizeof(usbDescriptorStringDevice)
PROGMEM int  usbDescriptorStringDevice[] = {
    USB_STRING_DESCRIPTOR_HEADER(USB_CFG_DEVICE_NAME_LEN),
    USB_CFG_DEVICE_NAME
};
#endif

#if USB_CFG_DESCR_PROPS_STRING_SERIAL_NUMBER == 0 && USB_CFG_SERIAL_NUMBER_LEN
#undef USB_CFG_DESCR_PROPS_STRING_SERIAL_NUMBER
#define USB_CFG_DESCR_PROPS_STRING_SERIAL_NUMBER    sizeof(usbDescriptorStringSerialNumber)
PROGMEM int usbDescriptorStringSerialNumber[] = {
    USB_STRING_DESCRIPTOR_HEADER(USB_CFG_SERIAL_NUMBER_LEN),
    USB_CFG_SERIAL_NUMBER
};
#endif

#endif  /* USB_CFG_DESCR_PROPS_STRINGS == 0 */

/* --------------------------- Device Descriptor --------------------------- */

#if USB_CFG_DESCR_PROPS_DEVICE == 0
#undef USB_CFG_DESCR_PROPS_DEVICE
#define USB_CFG_DESCR_PROPS_DEVICE  sizeof(usbDescriptorDevice)
PROGMEM char usbDescriptorDevice[] = {    /* USB device descriptor */
    18,         /* sizeof(usbDescriptorDevice): length of descriptor in bytes */
    USBDESCR_DEVICE,        /* descriptor type */
    0x10, 0x01,             /* USB version supported */
    USB_CFG_DEVICE_CLASS,
    USB_CFG_DEVICE_SUBCLASS,
    0,                      /* protocol */
    8,                      /* max packet size */
    /* the following two casts affect the first byte of the constant only, but
     * that's sufficient to avoid a warning with the default values.
     */
    (char)USB_CFG_VENDOR_ID,/* 2 bytes */
    (char)USB_CFG_DEVICE_ID,/* 2 bytes */
    USB_CFG_DEVICE_VERSION, /* 2 bytes */
    USB_CFG_DESCR_PROPS_STRING_VENDOR != 0 ? 1 : 0,         /* manufacturer string index */
    USB_CFG_DESCR_PROPS_STRING_PRODUCT != 0 ? 2 : 0,        /* product string index */
    USB_CFG_DESCR_PROPS_STRING_SERIAL_NUMBER != 0 ? 3 : 0,  /* serial number string index */
    1,          /* number of configurations */
};
#endif

/* ----------------------- Configuration Descriptor ------------------------ */

#if USB_CFG_DESCR_PROPS_HID_REPORT != 0 && USB_CFG_DESCR_PROPS_HID == 0
#undef USB_CFG_DESCR_PROPS_HID
#define USB_CFG_DESCR_PROPS_HID     9   /* length of HID descriptor in config descriptor below */
#endif

#if USB_CFG_DESCR_PROPS_CONFIGURATION == 0
#undef USB_CFG_DESCR_PROPS_CONFIGURATION
#define USB_CFG_DESCR_PROPS_CONFIGURATION   sizeof(usbDescriptorConfiguration)
PROGMEM char usbDescriptorConfiguration[] = {    /* USB configuration descriptor */
    9,          /* sizeof(usbDescriptorConfiguration): length of descriptor in bytes */
    USBDESCR_CONFIG,    /* descriptor type */
    18 + 7 * USB_CFG_HAVE_INTRIN_ENDPOINT + 7 * USB_CFG_HAVE_INTRIN_ENDPOINT3 +
                (USB_CFG_DESCR_PROPS_HID & 0xff), 0,
                /* total length of data returned (including inlined descriptors) */
    1,          /* number of interfaces in this configuration */
    1,          /* index of this configuration */
    0,          /* configuration name string index */
#if USB_CFG_IS_SELF_POWERED
    (1 << 7) | USBATTR_SELFPOWER,       /* attributes */
#else
    (1 << 7),                           /* attributes */
#endif
    USB_CFG_MAX_BUS_POWER/2,            /* max USB current in 2mA units */
/* interface descriptor follows inline: */
    9,          /* sizeof(usbDescrInterface): length of descriptor in bytes */
    USBDESCR_INTERFACE, /* descriptor type */
    0,          /* index of this interface */
    0,          /* alternate setting for this interface */
    USB_CFG_HAVE_INTRIN_ENDPOINT + USB_CFG_HAVE_INTRIN_ENDPOINT3, /* endpoints excl 0: number of endpoint descriptors to follow */
    USB_CFG_INTERFACE_CLASS,
    USB_CFG_INTERFACE_SUBCLASS,
    USB_CFG_INTERFACE_PROTOCOL,
    0,          /* string index for interface */
#if (USB_CFG_DESCR_PROPS_HID & 0xff)    /* HID descriptor */
    9,          /* sizeof(usbDescrHID): length of descriptor in bytes */
    USBDESCR_HID,   /* descriptor type: HID */
    0x01, 0x01, /* BCD representation of HID version */
    0x00,       /* target country code */
    0x01,       /* number of HID Report (or other HID class) Descriptor infos to follow */
    0x22,       /* descriptor type: report */
    USB_CFG_HID_REPORT_DESCRIPTOR_LENGTH, 0,  /* total length of report descriptor */
#endif
#if USB_CFG_HAVE_INTRIN_ENDPOINT    /* endpoint descriptor for endpoint 1 */
    7,          /* sizeof(usbDescrEndpoint) */
    USBDESCR_ENDPOINT,  /* descriptor type = endpoint */
    (char)0x81, /* IN endpoint number 1 */
    0x03,       /* attrib: Interrupt endpoint */
    8, 0,       /* maximum packet size */
    USB_CFG_INTR_POLL_INTERVAL, /* in ms */
#endif
#if USB_CFG_HAVE_INTRIN_ENDPOINT3   /* endpoint descriptor for endpoint 3 */
    7,          /* sizeof(usbDescrEndpoint) */
    USBDESCR_ENDPOINT,  /* descriptor type = endpoint */
    (char)0x83, /* IN endpoint number 1 */
    0x03,       /* attrib: Interrupt endpoint */
    8, 0,       /* maximum packet size */
    USB_CFG_INTR_POLL_INTERVAL, /* in ms */
#endif
};
#endif

/* ------------------------------------------------------------------------- */

static inline void  usbResetDataToggling(void)
{
#if USB_CFG_HAVE_INTRIN_ENDPOINT && !USB_CFG_SUPPRESS_INTR_CODE
    USB_SET_DATATOKEN1(USB_INITIAL_DATATOKEN);  /* reset data toggling for interrupt endpoint */
#   if USB_CFG_HAVE_INTRIN_ENDPOINT3
    USB_SET_DATATOKEN3(USB_INITIAL_DATATOKEN);  /* reset data toggling for interrupt endpoint */
#   endif
#endif
}

static inline void  usbResetStall(void)
{
#if USB_CFG_IMPLEMENT_HALT && USB_CFG_HAVE_INTRIN_ENDPOINT
        usbTxLen1 = USBPID_NAK;
#if USB_CFG_HAVE_INTRIN_ENDPOINT3
        usbTxLen3 = USBPID_NAK;
#endif
#endif
}

/* ------------------------------------------------------------------------- */

#if !USB_CFG_SUPPRESS_INTR_CODE
#if USB_CFG_HAVE_INTRIN_ENDPOINT
static void usbGenericSetInterrupt(uchar *data, uchar len, usbTxStatus_t *txStatus)
{
uchar   *p;
char    i;

#if USB_CFG_IMPLEMENT_HALT
    if(usbTxLen1 == USBPID_STALL)
        return;
#endif
    if(txStatus->len & 0x10){   /* packet buffer was empty */
        txStatus->buffer[0] ^= USBPID_DATA0 ^ USBPID_DATA1; /* toggle token */
    }else{
        txStatus->len = USBPID_NAK; /* avoid sending outdated (overwritten) interrupt data */
    }
    p = txStatus->buffer + 1;
    i = len;
    do{                         /* if len == 0, we still copy 1 byte, but that's no problem */
        *p++ = *data++;
    }while(--i > 0);            /* loop control at the end is 2 bytes shorter than at beginning */
    usbCrc16Append(&txStatus->buffer[1], len);
    txStatus->len = len + 4;    /* len must be given including sync byte */
    DBG2(0x21 + (((int)txStatus >> 3) & 3), txStatus->buffer, len + 3);
}

USB_PUBLIC void usbSetInterrupt(uchar *data, uchar len)
{
    usbGenericSetInterrupt(data, len, &usbTxStatus1);
}
#endif

#if USB_CFG_HAVE_INTRIN_ENDPOINT3
USB_PUBLIC void usbSetInterrupt3(uchar *data, uchar len)
{
    usbGenericSetInterrupt(data, len, &usbTxStatus3);
}
#endif
#endif /* USB_CFG_SUPPRESS_INTR_CODE */

/* ------------------ utilities for code following below ------------------- */

/* Use defines for the switch statement so that we can choose between an
 * if()else if() and a switch/case based implementation. switch() is more
 * efficient for a LARGE set of sequential choices, if() is better in all other
 * cases.
 */
#if USB_CFG_USE_SWITCH_STATEMENT
#   define SWITCH_START(cmd)       switch(cmd){{
#   define SWITCH_CASE(value)      }break; case (value):{
#   define SWITCH_CASE2(v1,v2)     }break; case (v1): case(v2):{
#   define SWITCH_CASE3(v1,v2,v3)  }break; case (v1): case(v2): case(v3):{
#   define SWITCH_DEFAULT          }break; default:{
#   define SWITCH_END              }}
#else
#   define SWITCH_START(cmd)       {uchar _cmd = cmd; if(0){
#   define SWITCH_CASE(value)      }else if(_cmd == (value)){
#   define SWITCH_CASE2(v1,v2)     }else if(_cmd == (v1) || _cmd == (v2)){
#   define SWITCH_CASE3(v1,v2,v3)  }else if(_cmd == (v1) || _cmd == (v2) || (_cmd == v3)){
#   define SWITCH_DEFAULT          }else{
#   define SWITCH_END              }}
#endif

#ifndef USB_RX_USER_HOOK
#define USB_RX_USER_HOOK(data, len)
#endif
#ifndef USB_SET_ADDRESS_HOOK
#define USB_SET_ADDRESS_HOOK()
#endif

/* ------------------------------------------------------------------------- */

/* We use if() instead of #if in the macro below because #if can't be used
 * in macros and the compiler optimizes constant conditions anyway.
 * This may cause problems with undefined symbols if compiled without
 * optimizing!
 */
#define GET_DESCRIPTOR(cfgProp, staticName)         \
    if(cfgProp){                                    \
        if((cfgProp) & USB_PROP_IS_RAM)             \
            flags = 0;                              \
        if((cfgProp) & USB_PROP_IS_DYNAMIC){        \
            len = usbFunctionDescriptor(rq);        \
        }else{                                      \
            len = USB_PROP_LENGTH(cfgProp);         \
            usbMsgPtr = (uchar *)(staticName);      \
        }                                           \
    }

/* usbDriverDescriptor() is similar to usbFunctionDescriptor(), but used
 * internally for all types of descriptors.
 */
static inline usbMsgLen_t usbDriverDescriptor(usbRequest_t *rq)
{
usbMsgLen_t len = 0;
uchar       flags = USB_FLG_MSGPTR_IS_ROM;

    SWITCH_START(rq->wValue.bytes[1])
    SWITCH_CASE(USBDESCR_DEVICE)    /* 1 */
        GET_DESCRIPTOR(USB_CFG_DESCR_PROPS_DEVICE, usbDescriptorDevice)
    SWITCH_CASE(USBDESCR_CONFIG)    /* 2 */
        GET_DESCRIPTOR(USB_CFG_DESCR_PROPS_CONFIGURATION, usbDescriptorConfiguration)
    SWITCH_CASE(USBDESCR_STRING)    /* 3 */
#if USB_CFG_DESCR_PROPS_STRINGS & USB_PROP_IS_DYNAMIC
        if(USB_CFG_DESCR_PROPS_STRINGS & USB_PROP_IS_RAM)
            flags = 0;
        len = usbFunctionDescriptor(rq);
#else   /* USB_CFG_DESCR_PROPS_STRINGS & USB_PROP_IS_DYNAMIC */
        SWITCH_START(rq->wValue.bytes[0])
        SWITCH_CASE(0)
            GET_DESCRIPTOR(USB_CFG_DESCR_PROPS_STRING_0, usbDescriptorString0)
        SWITCH_CASE(1)
            GET_DESCRIPTOR(USB_CFG_DESCR_PROPS_STRING_VENDOR, usbDescriptorStringVendor)
        SWITCH_CASE(2)
            GET_DESCRIPTOR(USB_CFG_DESCR_PROPS_STRING_PRODUCT, usbDescriptorStringDevice)
        SWITCH_CASE(3)
            GET_DESCRIPTOR(USB_CFG_DESCR_PROPS_STRING_SERIAL_NUMBER, usbDescriptorStringSerialNumber)
        SWITCH_DEFAULT
            if(USB_CFG_DESCR_PROPS_UNKNOWN & USB_PROP_IS_DYNAMIC){
                len = usbFunctionDescriptor(rq);
            }
        SWITCH_END
#endif  /* USB_CFG_DESCR_PROPS_STRINGS & USB_PROP_IS_DYNAMIC */
#if USB_CFG_DESCR_PROPS_HID_REPORT  /* only support HID descriptors if enabled */
    SWITCH_CASE(USBDESCR_HID)       /* 0x21 */
        GET_DESCRIPTOR(USB_CFG_DESCR_PROPS_HID, usbDescriptorConfiguration + 18)
    SWITCH_CASE(USBDESCR_HID_REPORT)/* 0x22 */
        GET_DESCRIPTOR(USB_CFG_DESCR_PROPS_HID_REPORT, usbDescriptorHidReport)
#endif
    SWITCH_DEFAULT
        if(USB_CFG_DESCR_PROPS_UNKNOWN & USB_PROP_IS_DYNAMIC){
            len = usbFunctionDescriptor(rq);
        }
    SWITCH_END
    usbMsgFlags = flags;
    return len;
}

/* ------------------------------------------------------------------------- */

/* usbDriverSetup() is similar to usbFunctionSetup(), but it's used for
 * standard requests instead of class and custom requests.
 */
static inline usbMsgLen_t usbDriverSetup(usbRequest_t *rq)
{
uchar   len  = 0, *dataPtr = usbTxBuf + 9;  /* there are 2 bytes free space at the end of the buffer */
uchar   value = rq->wValue.bytes[0];
#if USB_CFG_IMPLEMENT_HALT
uchar   index = rq->wIndex.bytes[0];
#endif

    dataPtr[0] = 0; /* default reply common to USBRQ_GET_STATUS and USBRQ_GET_INTERFACE */
    SWITCH_START(rq->bRequest)
    SWITCH_CASE(USBRQ_GET_STATUS)           /* 0 */
        uchar recipient = rq->bmRequestType & USBRQ_RCPT_MASK;  /* assign arith ops to variables to enforce byte size */
        if(USB_CFG_IS_SELF_POWERED && recipient == USBRQ_RCPT_DEVICE)
            dataPtr[0] =  USB_CFG_IS_SELF_POWERED;
#if USB_CFG_IMPLEMENT_HALT
        if(recipient == USBRQ_RCPT_ENDPOINT && index == 0x81)   /* request status for endpoint 1 */
            dataPtr[0] = usbTxLen1 == USBPID_STALL;
#endif
        dataPtr[1] = 0;
        len = 2;
#if USB_CFG_IMPLEMENT_HALT
    SWITCH_CASE2(USBRQ_CLEAR_FEATURE, USBRQ_SET_FEATURE)    /* 1, 3 */
        if(value == 0 && index == 0x81){    /* feature 0 == HALT for endpoint == 1 */
            usbTxLen1 = rq->bRequest == USBRQ_CLEAR_FEATURE ? USBPID_NAK : USBPID_STALL;
            usbResetDataToggling();
        }
#endif
    SWITCH_CASE(USBRQ_SET_ADDRESS)          /* 5 */
        usbNewDeviceAddr = value;
        USB_SET_ADDRESS_HOOK();
    SWITCH_CASE(USBRQ_GET_DESCRIPTOR)       /* 6 */
        len = usbDriverDescriptor(rq);
        goto skipMsgPtrAssignment;
    SWITCH_CASE(USBRQ_GET_CONFIGURATION)    /* 8 */
        dataPtr = &usbConfiguration;  /* send current configuration value */
        len = 1;
    SWITCH_CASE(USBRQ_SET_CONFIGURATION)    /* 9 */
        usbConfiguration = value;
        usbResetStall();
    SWITCH_CASE(USBRQ_GET_INTERFACE)        /* 10 */
        len = 1;
#if USB_CFG_HAVE_INTRIN_ENDPOINT && !USB_CFG_SUPPRESS_INTR_CODE
    SWITCH_CASE(USBRQ_SET_INTERFACE)        /* 11 */
        usbResetDataToggling();
        usbResetStall();
#endif
    SWITCH_DEFAULT                          /* 7=SET_DESCRIPTOR, 12=SYNC_FRAME */
        /* Should we add an optional hook here? */
    SWITCH_END
    usbMsgPtr = dataPtr;
skipMsgPtrAssignment:
    return len;
}

/* ------------------------------------------------------------------------- */

/* usbProcessRx() is called for every message received by the interrupt
 * routine. It distinguishes between SETUP and DATA packets and processes
 * them accordingly.
 */
static inline void usbProcessRx(uchar *data, uchar len)
{
usbRequest_t    *rq = (void *)data;

/* usbRxToken can be:
 * 0x2d 00101101 (USBPID_SETUP for setup data)
 * 0xe1 11100001 (USBPID_OUT: data phase of setup transfer)
 * 0...0x0f for OUT on endpoint X
 */
    DBG2(0x10 + (usbRxToken & 0xf), data, len + 2); /* SETUP=1d, SETUP-DATA=11, OUTx=1x */
    USB_RX_USER_HOOK(data, len)
#if USB_CFG_IMPLEMENT_FN_WRITEOUT
    if(usbRxToken < 0x10){  /* OUT to endpoint != 0: endpoint number in usbRxToken */
        usbFunctionWriteOut(data, len);
        return;
    }
#endif
    if(usbRxToken == (uchar)USBPID_SETUP){
        if(len != 8)    /* Setup size must be always 8 bytes. Ignore otherwise. */
            return;
        usbMsgLen_t replyLen;
        usbTxBuf[0] = USBPID_DATA0;         /* initialize data toggling */
        usbTxLen = USBPID_NAK;              /* abort pending transmit */
        usbMsgFlags = 0;
        uchar type = rq->bmRequestType & USBRQ_TYPE_MASK;
        if(type != USBRQ_TYPE_STANDARD){    /* standard requests are handled by driver */
            replyLen = usbFunctionSetup(data);
        }else{
            replyLen = usbDriverSetup(rq);
        }
#if USB_CFG_IMPLEMENT_FN_READ || USB_CFG_IMPLEMENT_FN_WRITE
        if(replyLen == USB_NO_MSG){         /* use user-supplied read/write function */
            /* do some conditioning on replyLen, but on IN transfers only */
            if((rq->bmRequestType & USBRQ_DIR_MASK) != USBRQ_DIR_HOST_TO_DEVICE){
                if(sizeof(replyLen) < sizeof(rq->wLength.word)){ /* help compiler with optimizing */
                    replyLen = rq->wLength.bytes[0];
                }else{
                    replyLen = rq->wLength.word;
                }
            }
            usbMsgFlags = USB_FLG_USE_USER_RW;
        }else   /* The 'else' prevents that we limit a replyLen of USB_NO_MSG to the maximum transfer len. */
#endif
        if(sizeof(replyLen) < sizeof(rq->wLength.word)){ /* help compiler with optimizing */
            if(!rq->wLength.bytes[1] && replyLen > rq->wLength.bytes[0])    /* limit length to max */
                replyLen = rq->wLength.bytes[0];
        }else{
            if(replyLen > rq->wLength.word)     /* limit length to max */
                replyLen = rq->wLength.word;
        }
        usbMsgLen = replyLen;
    }else{  /* usbRxToken must be USBPID_OUT, which means data phase of setup (control-out) */
#if USB_CFG_IMPLEMENT_FN_WRITE
        if(usbMsgFlags & USB_FLG_USE_USER_RW){
            uchar rval = usbFunctionWrite(data, len);
            if(rval == 0xff){   /* an error occurred */
                usbTxLen = USBPID_STALL;
            }else if(rval != 0){    /* This was the final package */
                usbMsgLen = 0;  /* answer with a zero-sized data packet */
            }
        }
#endif
    }
}

/* ------------------------------------------------------------------------- */

/* This function is similar to usbFunctionRead(), but it's also called for
 * data handled automatically by the driver (e.g. descriptor reads).
 */
static uchar usbDeviceRead(uchar *data, uchar len)
{
    if(len > 0){    /* don't bother app with 0 sized reads */
#if USB_CFG_IMPLEMENT_FN_READ
        if(usbMsgFlags & USB_FLG_USE_USER_RW){
            len = usbFunctionRead(data, len);
        }else
#endif
        {
            uchar i = len, *r = usbMsgPtr;
            if(usbMsgFlags & USB_FLG_MSGPTR_IS_ROM){    /* ROM data */
                do{
                    uchar c = USB_READ_FLASH(r);    /* assign to char size variable to enforce byte ops */
                    *data++ = c;
                    r++;
                }while(--i);
            }else{  /* RAM data */
                do{
                    *data++ = *r++;
                }while(--i);
            }
            usbMsgPtr = r;
        }
    }
    return len;
}

/* ------------------------------------------------------------------------- */

/* usbBuildTxBlock() is called when we have data to transmit and the
 * interrupt routine's transmit buffer is empty.
 */
static inline void usbBuildTxBlock(void)
{
usbMsgLen_t wantLen;
uchar       len;

    wantLen = usbMsgLen;
    if(wantLen > 8)
        wantLen = 8;
    usbMsgLen -= wantLen;
    usbTxBuf[0] ^= USBPID_DATA0 ^ USBPID_DATA1; /* DATA toggling */
    len = usbDeviceRead(usbTxBuf + 1, wantLen);
    if(len <= 8){           /* valid data packet */
        usbCrc16Append(&usbTxBuf[1], len);
        len += 4;           /* length including sync byte */
        if(len < 12)        /* a partial package identifies end of message */
            usbMsgLen = USB_NO_MSG;
    }else{
        len = USBPID_STALL;   /* stall the endpoint */
        usbMsgLen = USB_NO_MSG;
    }
    usbTxLen = len;
    DBG2(0x20, usbTxBuf, len-1);
}

/* ------------------------------------------------------------------------- */

static inline void usbHandleResetHook(uchar notResetState)
{
#ifdef USB_RESET_HOOK
static uchar    wasReset;
uchar           isReset = !notResetState;

    if(wasReset != isReset){
        USB_RESET_HOOK(isReset);
        wasReset = isReset;
    }
#endif
}

/* ------------------------------------------------------------------------- */

USB_PUBLIC void usbPoll(void)
{
schar   len;
uchar   i;

    len = usbRxLen - 3;
    if(len >= 0){
/* We could check CRC16 here -- but ACK has already been sent anyway. If you
 * need data integrity checks with this driver, check the CRC in your app
 * code and report errors back to the host. Since the ACK was already sent,
 * retries must be handled on application level.
 * unsigned crc = usbCrc16(buffer + 1, usbRxLen - 3);
 */
        usbProcessRx(usbRxBuf + USB_BUFSIZE + 1 - usbInputBufOffset, len);
#if USB_CFG_HAVE_FLOWCONTROL
        if(usbRxLen > 0)    /* only mark as available if not inactivated */
            usbRxLen = 0;
#else
        usbRxLen = 0;       /* mark rx buffer as available */
#endif
    }
    if(usbTxLen & 0x10){    /* transmit system idle */
        if(usbMsgLen != USB_NO_MSG){    /* transmit data pending? */
            usbBuildTxBlock();
        }
    }
    for(i = 20; i > 0; i--){
        uchar usbLineStatus = USBIN & USBMASK;
        if(usbLineStatus != 0)  /* SE0 has ended */
            goto isNotReset;
    }
    /* RESET condition, called multiple times during reset */
    usbNewDeviceAddr = 0;
    usbDeviceAddr = 0;
    usbResetStall();
    DBG1(0xff, 0, 0);
isNotReset:
    usbHandleResetHook(i);
}

/* ------------------------------------------------------------------------- */

USB_PUBLIC void usbInit(void)
{
#if USB_INTR_CFG_SET != 0
    USB_INTR_CFG |= USB_INTR_CFG_SET;
#endif
#if USB_INTR_CFG_CLR != 0
    USB_INTR_CFG &= ~(USB_INTR_CFG_CLR);
#endif
    USB_INTR_ENABLE |= (1 << USB_INTR_ENABLE_BIT);
    usbResetDataToggling();
#if USB_CFG_HAVE_INTRIN_ENDPOINT && !USB_CFG_SUPPRESS_INTR_CODE
    usbTxLen1 = USBPID_NAK;
#if USB_CFG_HAVE_INTRIN_ENDPOINT3
    usbTxLen3 = USBPID_NAK;
#endif
#endif
}

/* ------------------------------------------------------------------------- */


text:
import { POST } from '../../robot-api'
import {
  makeResponseFixtures,
  mockFailureBody,
} from '../../robot-api/__fixtures__'
import { WIFI_CONFIGURE_PATH } from '../constants'

import type { ResponseFixtures } from '../../robot-api/__fixtures__'
import type { WifiConfigureResponse } from '../types'

const {
  successMeta,
  failureMeta,
  success,
  failure,
}: ResponseFixtures<
  WifiConfigureResponse,
  {| message: string |}
> = makeResponseFixtures({
  method: POST,
  path: WIFI_CONFIGURE_PATH,
  successStatus: 200,
  successBody: { ssid: 'network-name', message: 'connected' },
  failureStatus: 500,
  failureBody: mockFailureBody,
})

export {
  successMeta as mockWifiConfigureSuccessMeta,
  failureMeta as mockWifiConfigureFailureMeta,
  success as mockWifiConfigureSuccess,
  failure as mockWifiConfigureFailure,
}


text:
<?php

namespace Sylius\Bundle\RbacBundle\Doctrine\ORM;

use Sylius\Bundle\ResourceBundle\Doctrine\ORM\EntityRepository;
use Sylius\Component\Rbac\Model\RoleInterface;
use Sylius\Component\Rbac\Repository\RoleRepositoryInterface;

/**
 * Role repository.
 *
 * @author Paweł Jędrzejewski <pawel@sylius.org>
 */
class RoleRepository extends EntityRepository implements RoleRepositoryInterface
{
    /**
     * {@inheritdoc}
     */
    public function getChildRoles(RoleInterface $role)
    {
        $queryBuilder = $this->createQueryBuilder('o');

        return $queryBuilder
            ->where($queryBuilder->expr()->lt('o.left', $role->getRight()))
            ->andWhere($queryBuilder->expr()->gt('o.left', $role->getLeft()))
            ->getQuery()
            ->execute()
        ;
    }
}


text:
#ifndef BOOST_SPIRIT_INCLUDE_KARMA_GENERATE
#define BOOST_SPIRIT_INCLUDE_KARMA_GENERATE
#include <boost/spirit/home/karma/generate.hpp>
#endif


text:
<manifest package="com.letv.sarrsdesktop.blockcanaryex.jrt"
          xmlns:android="http://schemas.android.com/apk/res/android">

    <application>
        <activity
            android:name=".ui.DisplayActivity"
            android:process=":blockcanaryex"
            android:enabled="false"
            android:icon="@drawable/block_canary_ex_icon"
            android:label="@string/block_canary_ex_display_activity_label"
            android:taskAffinity="com.letv.sarrsdesktop.blockcanaryex"
            android:theme="@style/block_canary_ex_BlockCanary.Base" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <service
            android:name=".internal.BlockSamplerService"
            android:process=":blockcanaryex"/>

    </application>

</manifest>


text:
require 'intercom/service/base_service'
require 'intercom/api_operations/list'
require 'intercom/api_operations/find'

module Intercom
  module Service
    class Team < BaseService
      include ApiOperations::List
      include ApiOperations::Find

      def collection_class
        Intercom::Team
      end

    end
  end
end


text:
require "kikeru/command"
require "kikeru/container"

class KikeruTest < Test::Unit::TestCase
  def setup
    @command = Kikeru::Command.new
  end

  def test_run_help_option
    arguments = %w(--help)
    mock(@command).write_help_message
    assert_raise SystemExit do
      @command.run(arguments)
    end
  end

  def test_run_help_option_sugar
    arguments = %w(-h)
    mock(@command).write_help_message
    assert_raise SystemExit do
      @command.run(arguments)
    end
  end

  def test_run_version_option
    arguments = %w(--version)
    mock(@command).write_version_message
    assert_raise SystemExit do
      @command.run(arguments)
    end
  end

  def test_run_empty
    arguments = %w(hoge)
    stub(@command).files_from_arguments { arguments }
    mock.instance_of(Kikeru::Container).empty? { true }
    mock(@command).write_empty_message
    assert_raise SystemExit do
      @command.run(arguments)
    end
  end

  def test_files_from_arguments_no_argument
    arguments = %w()
    expected = %w(dir1 file1 dir2)
    mock(Dir).glob("*") { expected }
    files = @command.__send__(:files_from_arguments, arguments)
    assert_equal(files, expected)
  end

  def test_files_from_arguments_deep_option_only
    arguments = %w(--deep)
    expected = %w(dir1 file1 dir2 dir1/file1 dir1/file2 dir2/file1)
    mock(Dir).glob("**/*") { expected }
    files = @command.__send__(:files_from_arguments, arguments)
    assert_equal(files, expected)
  end

  def test_files_from_arguments_deep_option_and_dir
    arguments = %w(--deep dir1 file1 dir2)
    expected_dir1 = %w(dir1/file1 dir1/file2)
    expected_dir2 = %w(dir2/file1)
    expected = [expected_dir1, "file1", expected_dir2].flatten
    mock(File).directory?("dir1") { true }
    mock(File).directory?("file1") { false }
    mock(File).directory?("dir2") { true }
    mock(Dir).glob("dir1/**/*") { expected_dir1 }
    mock(Dir).glob("dir2/**/*") { expected_dir2 }
    files = @command.__send__(:files_from_arguments, arguments)
    assert_equal(files, expected)
  end

  def test_files_from_arguments_all_dir
    arguments = %w(dir1 dir2)
    expected_dir1 = %w(dir1/file1 dir1/file2)
    expected_dir2 = %w(dir2/file1)
    expected = [expected_dir1, expected_dir2].flatten
    mock(File).directory?("dir1") { true }
    mock(File).directory?("dir2") { true }
    mock(Dir).glob("dir1/*") { expected_dir1 }
    mock(Dir).glob("dir2/*") { expected_dir2 }
    files = @command.__send__(:files_from_arguments, arguments)
    assert_equal(files, expected)
  end

  def test_files_from_arguments_else
    arguments = %w(dir1 file1 dir2)
    files = @command.__send__(:files_from_arguments, arguments)
    assert_equal(files, arguments)
  end

  def test_purge_option
    arguments = %w(--deep -f ubuntu dir1 file1 dir2)
    flag = @command.__send__(:purge_option, arguments, /\A(-d|--deep)\z/)
    assert_not_nil(flag)
    assert_equal(%w(-f ubuntu dir1 file1 dir2), arguments)
    value = @command.__send__(:purge_option, arguments, /\A-f\z/, true)
    assert_equal("ubuntu", value)
    assert_equal(%w(dir1 file1 dir2), arguments)
  end
end


text:
var flickr = require('..')(function auth() { /* noop */ });
var assert = require('assert');

describe('flickr.machinetags.getRecentValues', function () {

	it('returns a Request instance', function () {
		var req = flickr.machinetags.getRecentValues({});

		assert.equal(req.method, 'GET');
		assert.equal(req.url, 'https://api.flickr.com/services/rest');
		assert.equal(req.params.format, 'json');
		assert.equal(req.params.nojsoncallback, '1');
		assert.equal(req.params.method, 'flickr.machinetags.getRecentValues');
		assert.equal(req.header['Content-Type'], 'text/plain');
	});

});


text:
require File.join(File.dirname(__FILE__), 'boot')

DaemonKit::Initializer.run do |config|

  # The name of the daemon as reported by process monitoring tools
  config.daemon_name = '<%= daemon_name %>'

  # Force the daemon to be killed after X seconds from asking it to
  # config.force_kill_wait = 30

  # Log backraces when a thread/daemon dies (Recommended)
  # config.backtraces = true

  # Configure the safety net (see DaemonKit::Safety)
  # config.safety_net.handler = :mail # (or :hoptoad )
  # config.safety_net.mail.host = 'localhost'
end


text:
LOG_SETUP(".diskindex.dictionarywordreader");

namespace search::diskindex {

using vespalib::getLastErrorString;
using index::SchemaUtil;

DictionaryWordReader::DictionaryWordReader()
    : _word(),
      _wordNum(noWordNumHigh()),
      _old2newwordfile(),
      _dictFile()
{
}

DictionaryWordReader::~DictionaryWordReader() = default;

bool
DictionaryWordReader::open(const vespalib::string & dictionaryName,
                           const vespalib::string & wordMapName,
                           const TuneFileSeqRead &tuneFileRead)
{
    _old2newwordfile.reset(new Fast_BufferedFile(new FastOS_File));
    _dictFile.reset(new PageDict4FileSeqRead);
    if (!_dictFile->open(dictionaryName, tuneFileRead)) {
        LOG(error, "Could not open dictionary %s: %s",
            dictionaryName.c_str(), getLastErrorString().c_str());
        return false;
    }
    _wordNum = noWordNum();

    // Make a mapping from old to new wordID
    if (tuneFileRead.getWantDirectIO()) {
        _old2newwordfile->EnableDirectIO();
    }
    // no checking possible
    _old2newwordfile->OpenWriteOnly(wordMapName.c_str());
    _old2newwordfile->SetSize(0);

    return true;
}

void
DictionaryWordReader::writeNewWordNum(uint64_t newWordNum) {
    _old2newwordfile->WriteBuf(&newWordNum, sizeof(newWordNum));
}

void
DictionaryWordReader::close()
{
    if (!_dictFile->close()) {
        LOG(error, "Error closing input dictionary");
    }
    bool sync_ok = _old2newwordfile->Sync();
    assert(sync_ok);
    bool close_ok = _old2newwordfile->Close();
    assert(close_ok);
}

}


text:
# Microsoft Azure SDK for Node.js - Data Lake Analytics

This project provides a Node.js package that makes it easy to manage Azure Data Lake Analytics accounts.

Right now it supports:

  *  **Node.js version: 6.x.x or higher**
  *  **REST API version for Account: 2016-11-01**
  *  **REST API version for Catalog: 2016-11-01**
  *  **REST API version for Job: 2016-11-01**

## Features

- Account management: create, get, list, update, and delete.
- Account storage management: add, get, list update and delete Data Lake Store accounts and Azure Storage accounts from an existing Data Lake analytics account.
- Job management: submit, get, list, cancel.
- Catalog management: get, list, create (secrets and credentials), update (secrets and credentials), delete (secrets and credentials).

## How to Install

```bash
npm install azure-arm-datalake-analytics
```

## How to Use

### Authentication, account, job and catalog client creation and listing jobs as an example

### Login and list jobs using promises
 ```javascript
 var msRestAzure = require('ms-rest-azure');
 var adlaManagement = require("azure-arm-datalake-analytics");

 // Interactive Login
 // It provides a url and code that needs to be copied and pasted in a browser and authenticated over there. If successful,
 // the user will get a DeviceTokenCredentials object.
 msRestAzure.interactiveLogin().then((credentials) => {
  var acccountClient = new adlaManagement.DataLakeAnalyticsAccountClient(credentials, 'your-subscription-id');
  var jobClient = new adlaManagement.DataLakeAnalyticsJobClient(credentials, 'azuredatalakeanalytics.net');
  var catalogClient = new adlaManagement.DataLakeAnalyticsCatalogClient(credentials, 'azuredatalakeanalytics.net');
  return jobClient.job.list(accountName);
}).then((jobs) => {
  console.log(result);
  return;
}).catch((err) => {
  console.log('An error occured');
  console.dir(err, {depth: null, colors: true});
});
 ```

### Create a Data Lake Analytics Account using callback pattern
```javascript
var util = require('util');
var resourceGroupName = 'testrg';
var accountName = 'testadlaacct';
var location = 'eastus2';

// A Data Lake Store account must already have been created to create
// a Data Lake Analytics account. See the Data Lake Store readme for
// information on doing so. For now, we assume one exists already.
var datalakeStoreAccountName = 'existingadlsaccount';

// account object to create
var accountToCreate = {
  tags: {
    testtag1: 'testvalue1',
    testtag2: 'testvalue2'
  },
  location: location,
  defaultDataLakeStoreAccount: datalakeStoreAccountName,
  dataLakeStoreAccounts: [
    {
      name: datalakeStoreAccountName
    }
  ]
};

client.account.create(resourceGroupName, accountName, accountToCreate, function (err, result, request, response) {
  if (err) {
    console.log(err);
    /*err has reference to the actual request and response, so you can see what was sent and received on the wire.
      The structure of err looks like this:
      err: {
        code: 'Error Code',
        message: 'Error Message',
        body: 'The response body if any',
        request: reference to a stripped version of http request
        response: reference to a stripped version of the response
      }
    */
  } else {
    console.log('result is: ' + util.inspect(result, {depth: null}));
  }
});
```

### Get a list of jobs using callback pattern

```javascript
var util = require('util');
var accountName = 'testadlaacct';
jobClient.job.list(accountName, function (err, result, request, response) {
  if (err) {
    console.log(err);
  } else {
    console.log('result is: ' + util.inspect(result, {depth: null}));
  }
});
```

### Get a list of databases in the Data Lake Analytics Catalog using Promise that provides the HttpOperationResponse<T> wrapper
```javascript
var util = require('util');
var accountName = 'testadlaacct';
catalogClient.catalog.listDatabasesWithHttpOperationResponse(accountName).then((httpOperationResponse) => {
  console.log('Deserialized Result (list of databases)');
  console.dir(httpOperationResponse.body, {depth: null, colors: true});
  console.log('Actual Request');
  console.dir(httpOperationResponse.request, {depth: null, colors: true});
  console.log('Raw Response');
  console.dir(httpOperationResponse.response, {depth: 3, colors: true});
}).catch((err) => {
  console.log('An error occurred.');
  console.dir(err, {depth: null, colors: true});
});
```

## Related projects

- [Microsoft Azure SDK for Node.js](https://github.com/azure/azure-sdk-for-node)
- [Microsoft Azure SDK for Node.js - Data Lake Store Management](https://github.com/Azure/azure-sdk-for-node/tree/autorest/lib/services/dataLake.Store)


text:
package skinny.controller.feature

import skinny.controller.Flash
import org.scalatra._

/**
 * Easy-to-use Flash support.
 */
trait FlashFeature extends FlashMapSupport {

  self: org.scalatra.ScalatraBase with RequestScopeFeature =>

  // just set Flash object to request scope
  before() {
    if (requestScope(RequestScopeFeature.ATTR_FLASH).isEmpty) {
      set(RequestScopeFeature.ATTR_FLASH, Flash(flash))
    }
  }

}


text:
package org.wso2.siddhi.core.executor.function;

import org.wso2.siddhi.core.config.SiddhiContext;
import org.wso2.siddhi.core.event.AtomicEvent;
import org.wso2.siddhi.core.executor.expression.ExpressionExecutor;
import org.wso2.siddhi.core.extension.EternalReferencedHolder;
import org.wso2.siddhi.query.api.definition.Attribute;

import java.util.List;

public abstract class FunctionExecutor implements ExpressionExecutor, EternalReferencedHolder {

    protected List<ExpressionExecutor> attributeExpressionExecutors;
    protected SiddhiContext siddhiContext;
    protected int attributeSize;
    protected Attribute.Type[] attributeTypes;

    public void setSiddhiContext(SiddhiContext siddhiContext) {
        this.siddhiContext = siddhiContext;
    }

    public void setAttributeExpressionExecutors(List<ExpressionExecutor> attributeExpressionExecutors) {
        this.attributeExpressionExecutors = attributeExpressionExecutors;
        attributeSize = attributeExpressionExecutors.size();
        attributeTypes = new Attribute.Type[attributeExpressionExecutors.size()];
        for (int i = 0; i < attributeExpressionExecutors.size(); i++) {
            attributeTypes[i] = attributeExpressionExecutors.get(i).getReturnType();
        }
    }

    @Override
    public Object execute(AtomicEvent event) {

        if (attributeSize > 1) {
            Object[] data = new Object[attributeExpressionExecutors.size()];
            for (int i = 0, size = data.length; i < size; i++) {
                data[i] = attributeExpressionExecutors.get(i).execute(event);
            }
            return process(data);
        } else {
            return process(attributeExpressionExecutors.get(0).execute(event));
        }
    }

    public void init() {
        init(attributeTypes, siddhiContext);
    }

    /**
     * The initialization method for FunctionExecutor
     *
     * @param attributeTypes are the type if the  attributes to the executor function
     * @param siddhiContext  SiddhiContext
     */
    public abstract void init(Attribute.Type[] attributeTypes, SiddhiContext siddhiContext);

    /**
     * The main executions method which will be called upon event arrival
     *
     * @param data the runtime values of the attributeExpressionExecutors
     * @return the processed object
     */
    protected abstract Object process(Object data);

}


text:
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { NO_ERRORS_SCHEMA } from '@angular/core';

import { SplitDirectiveFixture } from './split.directive.fixture';
import { SplitDirective } from './split.directive';
import { SplitAreaDirective } from './split-area.directive';
import { SplitHandleComponent } from './split-handle.component';

describe('SplitAreaDirective', () => {
  let component: SplitDirectiveFixture;
  let fixture: ComponentFixture<SplitDirectiveFixture>;

  beforeEach(() => {
    TestBed.configureTestingModule({
      schemas: [NO_ERRORS_SCHEMA],
      imports: [],
      declarations: [SplitDirectiveFixture, SplitDirective, SplitAreaDirective, SplitHandleComponent]
    });
  });

  beforeEach(() => {
    fixture = TestBed.createComponent(SplitDirectiveFixture);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should be defined', () => {
    expect(component).toBeTruthy();
  });

  describe('updateBasis', () => {
    it('should update flex style', () => {
      component.splitAreas.first.updateBasis('50%');
      expect(component.splitAreas.first.currentFlexParts).toEqual(['1', '1', '50%']);
      expect(component.splitAreas.first.flex).toEqual('1 1 50%');
    });

    it('should update using number', () => {
      fixture.detectChanges();
      component.splitAreas.first.updateBasis('80px');
      expect(component.splitAreas.first.currentFlexParts).toEqual(['1', '1', '80px']);
      expect(component.splitAreas.first.flex).toEqual('1 1 80px');
    });
  });
});


text:
class User < ActiveRecord::Base
  has_many :posts
  has_many :addresses, :as => :addressable

  named_scope :active, :conditions=>'users.active=1'
  named_scope :has_status, lambda{|status| {:conditions=>["users.status=?", status]}}
  named_scope :has_posts_for_month, lambda{|month|
    {:association=>{:source=>:posts, :scope=>[:published_in_month, month]}}
  }
  named_scope :has_approved_posts, {:association=>{:source=>:posts, :scope=>:approved}}
  named_scope :has_approved_posts_without_source, {:association=>{:scope=>:approved}}
  named_scope :has_approved_posts_without_scope, {:association=>{:source=>:posts}}
end


text:
#ifndef TERMOX_COMMON_TRANFORM_VIEW_HPP
#define TERMOX_COMMON_TRANFORM_VIEW_HPP
#include <cstddef>
#include <type_traits>
#include <utility>

#include <termox/common/transform_iterator.hpp>

namespace ox {

/// Read only Container view that applies transformation to elements at access.
/** Container is assumed to have a vector like interface. Transformation is
 *  applied at iterator dereference and operator[]. This is a non-owning view,
 *  relies on passed in container being alive as long as this view is.\*/
template <typename Container, typename Map_fn>
class Transform_view {
   public:
    using Reference =
        std::invoke_result_t<Map_fn, typename Container::reference>;
    using Reference_const =
        std::invoke_result_t<Map_fn, typename Container::const_reference>;

   public:
    Transform_view(Container& c, Map_fn map_fn)
        : container_{c}, map_fn_{std::move(map_fn)}
    {}

   public:
    [[nodiscard]] auto size() const -> std::size_t { return container_.size(); }

    [[nodiscard]] auto is_empty() const -> bool { return container_.empty(); }

    [[nodiscard]] auto operator[](std::size_t i) const -> Reference_const
    {
        return map_fn_(container_[i]);
    }

    [[nodiscard]] auto operator[](std::size_t i) -> Reference
    {
        return map_fn_(container_[i]);
    }

    [[nodiscard]] auto front() const -> Reference_const
    {
        return map_fn_(container_.front());
    }

    [[nodiscard]] auto front() -> Reference
    {
        return map_fn_(container_.front());
    }

    [[nodiscard]] auto back() const -> Reference_const
    {
        return map_fn_(container_.back());
    }

    [[nodiscard]] auto back() -> Reference
    {
        return map_fn_(container_.back());
    }

    [[nodiscard]] auto begin() const
    {
        return Transform_iterator{std::cbegin(container_), map_fn_};
    }

    [[nodiscard]] auto begin()
    {
        return Transform_iterator{std::begin(container_), map_fn_};
    }

    [[nodiscard]] auto end() const
    {
        return Transform_iterator{std::cend(container_), map_fn_};
    }

    [[nodiscard]] auto end()
    {
        return Transform_iterator{std::end(container_), map_fn_};
    }

   private:
    Container& container_;
    Map_fn map_fn_;
};

}  // namespace ox
#endif  // TERMOX_COMMON_TRANFORM_VIEW_HPP


text:
<?php namespace Dimsav\Exception;

interface ExceptionInterface {}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

package com.microsoft.aad.msal4j;

/**
 * Interface representing an application credential
 * <p>
 * For more details, see https://aka.ms/msal4j-client-credentials
 */
public interface IClientCredential {

}


text:
import os

# *****************************
# Environment specific settings
# *****************************

# DO NOT use "DEBUG = True" in production environments
DEBUG = True

# DO NOT use Unsecure Secrets in production environments
# Generate a safe one with:
#     python -c "import os; print repr(os.urandom(24));"
SECRET_KEY = 'This is an UNSECURE Secret. CHANGE THIS for production environments.'

# SQLAlchemy settings
SQLALCHEMY_DATABASE_URI = 'sqlite:///app.sqlite'

# Flask-Mail settings
# For smtp.gmail.com to work, you MUST set "Allow less secure apps" to ON in Google Accounts.
# Change it in https://myaccount.google.com/security#connectedapps (near the bottom).
MAIL_SERVER = 'smtp.gmail.com'
MAIL_PORT = 587
MAIL_USE_SSL = False
MAIL_USE_TLS = True
MAIL_USERNAME = 'yourname@gmail.com'
MAIL_PASSWORD = 'password'
MAIL_DEFAULT_SENDER = '"Your Name" <yourname@gmail.com>'

ADMINS = [
    '"Admin One" <admin1@gmail.com>',
    ]


text:
#ifndef COMPILER_H
#define COMPILER_H

#include <string>
#include <iostream>
#include <fstream>
#include <vector>
#include <iomanip>
#include <stack>

struct Token {
    std::string token;
    std::string lexeme;
    int lineno = 0;
};

struct Instruction {
    int instaddr;
    std::string oper8r;
    int operand;
};

struct SymbolTable {
    int address;
    Token tok;
    std::string type;
};

int linenumber, instr_address = 1, addr = 0, oprnd_addr = 3000;
std::vector<std::string> keywords = { "while", "if", "int", "fi", "else", "return", "read", "write", "integer", "real", "boolean", "true", "false" };
std::vector<char> separators = { '(', ')', '{', '}', '%', '@', '[', ']', ';', ',', '.' };
std::vector<std::string> multiseparators = { "%%" };
std::vector<char> operators = { '+', '-', '/', '*', '<', '>', '=', ':', '|' };
std::vector<std::string> multioperators = { "+=", "-=", "*=", "/=", "==", "<=", ">=", ":=", "&&", "||" };
std::vector<char> letters = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
                              'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' };
std::vector<char> numbers = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
std::stack<std::string> TDPPstack;
std::string table[38][36][7];
Instruction instrtable[500];
std::vector<SymbolTable> symbol_table;
std::stack<int> jump_stack;

/*Lexical Analyzer function that currently just prints tokens/lexemes*/
Token lexer(std::ifstream& input, char c);
/*Returns whether to go to ID, int/real, or the other states*/
int getstate(char c);
/*Returns whether a number, period, or other character is found and goes to that state*/
int numstate(char c);
/*Returns whether a letter, or '#' is found and goes to that state*/
int idstate(char c);
/*Returns whether a number or other character is found and goes to that state*/
int floatstate(char c);
/*Returns true if character/string is a separator as defined in vectors above*/
bool isseparator(char c);
bool isseparator(std::string s); //Compares string with multiseparator vector
/*Returns true if character/string is a operator as defined in vectors above*/
bool isoperator(char c);
bool isoperator(std::string); //Compares string with multioperator vector
/*Returns true if character is a letter as defined in vector above*/
bool isletter(char c);
/*Returns true if character is a number as defined in vector above*/
bool isnumber(char c);
/*Returns true if string is a keyword*/
bool iskeyword(std::string s);
/*Converts non-terminal character to index in the table*/
int nonterminalindex(std::string nt);
/*Converts terminal character to index in the table*/
int terminalindex(std::string t);
/*Returns whether the string is a non-terminal character or not*/
bool isnonterminal(std::string st);
/*Returns a terminal character from an index*/
std::string getterminal(int index);
/*Fills table with correct values*/
void filltable();
/*Returns the index of the last production rule at [r][c] in the 3D table*/
int lastprodindex(int r, int c);
/*Syntax analyzer driver for Table Driver Predictive Parser*/
void syntaxerdriver(std::string filename);
/*Procedure for ICG*/
void gen_instr(std::string op, int opernd);
/*Gets address of token from Symbol Table*/
int get_address(std::string token);
/*Adds address to jump_stack so it can be back patched*/
void back_patch(int jump_addr);
/*Prints out the instruction table*/
void print_instr_table();
/*Checks if the symbol is in the table, returns it's index*/
int symbol_table_lookup(Token );
/*Prints out the symbol table*/
void print_sym_table();
/*runs the syntaxer*/
int main(int argc, const char * argv[]);

#endif // !COMPILER_H


text:
goog.provide('blk.io.RegionFileCache');

goog.require('blk.io.CompressionFormat');
goog.require('blk.io.RegionFile');
goog.require('gf.io.DirectoryEntry');
goog.require('goog.Disposable');
goog.require('goog.array');
goog.require('goog.asserts');
goog.require('goog.async.Deferred');

/**
 * A simple LRU cache of open region files.
 *
 * This cache does not support multiple outstanding gets.
 * TODO(benvanik): make overlapping region file requests work
 *
 * @constructor
 * @extends {goog.Disposable}
 * @param {number} maxOpenFiles Maximum number of open files to retain.
 * @param {!gf.io.DirectoryEntry} rootEntry Root directory entry for files.
 */
blk.io.RegionFileCache = function(maxOpenFiles, rootEntry) {
  goog.base(this);

  /**
   * Maximum number of open files to retain.
   * @private
   * @type {number}
   */
  this.maxOpenFiles_ = maxOpenFiles;

  /**
   * All opened region files, mapped by name.
   * @private
   * @type {!Object.<!blk.io.RegionFile>}
   */
  this.cache_ = {};

  /**
   * All opened region files in a list.
   * This is used to quickly sort by access time to find files to close.
   * @private
   * @type {!Array.<blk.io.RegionFile>}
   */
  this.list_ = [];

  /**
   * Root directory entry for region files.
   * @private
   * @type {!gf.io.DirectoryEntry}
   */
  this.rootEntry_ = rootEntry;
};
goog.inherits(blk.io.RegionFileCache, goog.Disposable);

/**
 * @override
 */
blk.io.RegionFileCache.prototype.disposeInternal = function() {
  this.clear();
  goog.base(this, 'disposeInternal');
};

/**
 * Gets the region file containing the given chunk coordinates, creating it if
 * required.
 * @param {number} x Chunk coordinate X.
 * @param {number} y Chunk coordinate Y.
 * @param {number} z Chunk coordinate Z.
 * @return {!goog.async.Deferred} A deferred fulfilled when the region file is
 *     ready for access.
 */
blk.io.RegionFileCache.prototype.get = function(x, y, z) {
  var rx = x >> blk.io.RegionFile.SHIFT_XZ;
  var ry = 0;
  var rz = z >> blk.io.RegionFile.SHIFT_XZ;
  var key = [rx, ry, rz, 'blkregion'].join('.');

  var deferred = new goog.async.Deferred();

  // If cached, quickly return
  var regionFile = this.cache_[key];
  if (regionFile) {
    // Don't support overlapping requests yet!
    goog.asserts.assert(regionFile.prepared);

    regionFile.lastAccessTime = goog.now();
    deferred.callback(regionFile);
  } else {
    // Attempt to open
    this.load_(rx, ry, rz, key, deferred);
  }

  return deferred;
};

/**
 * Loads a region file into the cache.
 * @private
 * @param {number} rx Region offset X.
 * @param {number} ry Region offset Y.
 * @param {number} rz Region offset Z.
 * @param {string} key Unique key.
 * @param {!goog.async.Deferred} deferred A deferred to signal when the region
 *     file is ready for use. Expects the region file as its only argument.
 */
blk.io.RegionFileCache.prototype.load_ = function(rx, ry, rz, key, deferred) {
  // This will create the file if required as empty
  this.rootEntry_.getFile(
      key, gf.io.DirectoryEntry.Behavior.CREATE).addCallbacks(
      function(file) {
        // Maintain the cache size by expelling the oldest file
        if (this.list_.length >= this.maxOpenFiles_) {
          this.expel_();
        }

        // Create region file wrapper
        var regionFile = new blk.io.RegionFile(
            rx << blk.io.RegionFile.SHIFT_XZ,
            ry << blk.io.RegionFile.SHIFT_XZ,
            rz << blk.io.RegionFile.SHIFT_XZ,
            key,
            file,
            blk.io.CompressionFormat.UNCOMPRESSED);

        // Add to cache
        this.cache_[key] = regionFile;
        this.list_.push(regionFile);

        // Prepare for accessing (create file backing, etc)
        regionFile.prepare().addCallbacks(
            function() {
              deferred.callback(regionFile);
            },
            function(arg) {
              deferred.errback(arg);
            }, this);
      },
      function(arg) {
        deferred.errback(arg);
      }, this);
};

/**
 * Expels the oldest file from the cache.
 * @private
 */
blk.io.RegionFileCache.prototype.expel_ = function() {
  if (!this.list_.length) {
    return;
  }
  goog.array.sort(
      this.list_, blk.io.RegionFile.accessTimeComparer);
  var regionFile = this.list_[this.list_.length - 1];
  delete this.cache_[regionFile.key];
  goog.dispose(regionFile);
  this.list_.length--;
};

/**
 * Drops all files from the cache.
 */
blk.io.RegionFileCache.prototype.clear = function() {
  goog.array.forEach(this.list_, goog.dispose);
  this.list_.length = 0;
  this.cache_ = {};
};


text:
import jsonfield.encoder
import jsonfield.fields
from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ("mediafiles", "0006_directories_and_permissions_3"),
    ]

    operations = [
        migrations.AddField(
            model_name="mediafile",
            name="filesize",
            field=models.CharField(default="", max_length=255),
        ),
        migrations.AddField(
            model_name="mediafile",
            name="mimetype",
            field=models.CharField(default="", max_length=255),
        ),
        migrations.AddField(
            model_name="mediafile",
            name="pdf_information",
            field=jsonfield.fields.JSONField(
                default=dict,
                dump_kwargs={
                    "cls": jsonfield.encoder.JSONEncoder,
                    "separators": (",", ":"),
                },
                load_kwargs={},
            ),
        ),
    ]


text:
<!doctype html>

    <title>Shopping List Check Off</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="styles/bootstrap.min.css">

Shopping List Check Off

To Buy:

Buy {{item.quantity}} {{item.name}} <button ng-click="toBuy.buyItem($index);" class="btn btn-default"> Bought</button>

Everything is bought!

Already Bought:

Bought {{item.quantity}} {{item.name}}

Nothing bought yet.


text:
from __future__ import print_function

import json
import time

import redis
import tensorflow as tf
from rediscluster import StrictRedisCluster
from tensorflow.core.framework import variable_pb2

import util
from util.config import config
from util.log import log

channel = 'ps'  # change it later

class ParameterServer(object):
    def __init__(self, train_id, worker_id, parallel_count=-1):
        self.train_id = train_id
        self.worker_id = worker_id
        self.iteration_id = -1

        info = config['pubsub']
        self.host = info[0]
        self.port = int(info[1])

        self.channel = channel
        # self.channel = train_id  # later

        self.r = redis.StrictRedis(host=self.host, port=self.port, db=0)
        self.p = self.r.pubsub()
        self.p.subscribe(self.channel)

        rc_address = util.get_redis_cluster_address_randomly()
        startup_nodes = [{'host': rc_address[0], 'port': rc_address[1]}]
        self.rc = StrictRedisCluster(
            startup_nodes=startup_nodes, decode_responses=False)

        self.future_list = []
        self.infra_info = {
            'parallel_count': -1,
        }

        self._log('created')

    def _log(self, msg):
        log.debug('[%s:%s] %s' % (self.worker_id, self.iteration_id, msg))

    def _set_variable_and_publish(self, iteration_id, variable, key):
        v = variable
        s = v.to_proto().SerializeToString()
        # h = ':'.join('{:02x}'.format(ord(c)) for c in s)

        parallel_count = self.infra_info['parallel_count']

        self.rc.set(key, s)

        message = json.dumps({
            'worker_id': self.worker_id,
            'train_id': self.train_id,
            'iteration_id': iteration_id,
            'parallel_count': parallel_count
        })
        self.r.publish(channel=channel, message=message)
        self._log('pub %s' % iteration_id)

        return v, s

    def _check_message(self, message):
        my_iteration_id = self.iteration_id
        worker_id = message['worker_id']
        iteration_id = message['iteration_id']
        if self.worker_id != worker_id:
            if my_iteration_id == iteration_id:
                return 'cur'
            elif my_iteration_id < iteration_id:
                return 'next'
        return 'prev'

    def _wait_until_time_out(self, time_out_sec):
        self._log('_wait_until')
        p = self.p
        start_time = time.time()

        for message in self.future_list:
            prev_cur_next = self._check_message(message)
            if prev_cur_next == 'cur':
                return True

        while True:
            raw_message = p.get_message()
            message = util.extract_json(raw_message)
            if not message:
                time.sleep(0.001)
            else:
                prev_cur_next = self._check_message(message)
                if prev_cur_next == 'next':
                    self._log('future append %s' % message['iteration_id'])
                    self.future_list.append(message)
                elif prev_cur_next == 'cur':
                    self.future_list.append(message)
                    return True
                else:
                    time.sleep(0.001)

            diff = time.time() - start_time
            if diff > time_out_sec:
                return False

    def _collect_message(self):
        messages = []
        messages.extend(self.future_list)
        self.future_list = []
        while True:
            raw_message = self.p.get_message()
            message = util.extract_json(raw_message)
            if message:
                messages.append(message)
            else:
                break
        return messages

    def _calculate_average(self, my_v, messages):
        with tf.Session() as sess:
            sess.run(tf.global_variables_initializer())
            for message in messages:
                prev_cur_next = self._check_message(message)
                if prev_cur_next == 'next':
                    self._log('future append %s' % message['iteration_id'])
                    self.future_list.append(message)
                elif prev_cur_next == 'cur':
                    worker_id = message['worker_id']
                    key = self.get_key(
                        self.train_id, worker_id, self.iteration_id)
                    your_v_raw = self.rc.get(key)
                    var_def = variable_pb2.VariableDef()
                    var_def.ParseFromString(your_v_raw)

                    # TODO
                    v2 = tf.Variable(variable_def=var_def)
                    result = tf.add(my_v, v2) / 2.0
                    print('!!!', sess.run(result))
                    return result

        return my_v

    def get_key(self, train_id, worker_id, iteration_id):
        return '%s_%s_%s' % (worker_id, train_id, iteration_id)

    def set_infra_info(self, infra_info):
        self.infra_info = infra_info

    def change_var_as_average(self, iteration_id, variable, time_out_sec=1):
        self.iteration_id = iteration_id

        train_id = self.train_id
        worker_id = self.worker_id

        key = self.get_key(train_id, worker_id, iteration_id)

        # 1. set variable to redis cluster
        my_v, s = self._set_variable_and_publish(iteration_id, variable, key)

        # 2. get first message until time out
        success = self._wait_until_time_out(time_out_sec)
        if not success:
            self._log('Timeout!')
            return my_v
        else:
            self._log('Have data!')

        # 3. collect messages
        messages = self._collect_message()

        # 4. calculate average
        avg_v = self._calculate_average(my_v, messages)

        return avg_v


text:
class ChromeWebUIDataSource : public ChromeURLDataManager::DataSource {
 public:
  explicit ChromeWebUIDataSource(const std::string& source_name);
  ChromeWebUIDataSource(const std::string& source_name, MessageLoop* loop);

  // Adds a string and its equivalent to our dictionary.
  void AddString(const std::string& name, const string16& value);

  // Adds a name and its equivaled localized string to our dictionary.
  void AddLocalizedString(const std::string& name, int ids);

  // Add strings from |localized_strings| to our dictionary.
  void AddLocalizedStrings(const DictionaryValue& localized_strings);

  // Accessor for |localized_strings_|.
  DictionaryValue* localized_strings() {
    return &localized_strings_;
  }

  // Sets the path which will return the JSON strings.
  void set_json_path(const std::string& path) { json_path_ = path; }

  // Sets the data source to use a slightly different format for json data. Some
  // day this should become the default.
  void set_use_json_js_format_v2() { json_js_format_v2_ = true; }

  // Adds a mapping between a path name and a resource to return.
  void add_resource_path(const std::string &path, int resource_id) {
    path_to_idr_map_[path] = resource_id;
  }

  // Sets the resource to returned when no other paths match.
  void set_default_resource(int resource_id) {
    default_resource_ = resource_id;
  }

 protected:
  virtual ~ChromeWebUIDataSource();

  // Completes a request by sending our dictionary of localized strings.
  void SendLocalizedStringsAsJSON(int request_id);

  // Completes a request by sending the file specified by |idr|.
  void SendFromResourceBundle(int request_id, int idr);

  // ChromeURLDataManager
  virtual std::string GetMimeType(const std::string& path) const OVERRIDE;
  virtual void StartDataRequest(const std::string& path,
                                bool is_incognito,
                                int request_id) OVERRIDE;

 private:
  int default_resource_;
  bool json_js_format_v2_;
  std::string json_path_;
  std::map<std::string, int> path_to_idr_map_;
  DictionaryValue localized_strings_;
  DISALLOW_COPY_AND_ASSIGN(ChromeWebUIDataSource);
};

#endif  // CHROME_BROWSER_UI_WEBUI_CHROME_WEB_UI_DATA_SOURCE_H_


text:
"use strict";

var $ = window.jQuery || require('jquery'),
    Token = require('./token'),
    authPrompt = require('./dialog'),
    redirectHandler = require('./redirect');

function Service(config) {
  config = config || {};
  for (var key in config) { this[key] = config[key]; }
  ["name", "clientID", "redirectURI", "tokenURI"].forEach(function(key) {
    if (this[key] == null) {
      window.console.error("OAuth2 Configuration error: options for initializing a new Service object must include a " + key);
    }
  }, this);
  Object.defineProperty(this, "tokenParams", {
    __proto__: null,
    get: function() {
      return {
        response_type: "token",
        client_id: this.clientID,
        redirect_uri: this.redirectURI
      };
    }
  });
  Object.defineProperty(this, "tokenKey", {
    __proto__: null,
    value: ["oauth2", "token", this.name, this.clientID].join("-")
  });
  Object.defineProperty(this, "userKey", {
    __proto__: null,
    value: ["oauth2", "user", this.name, this.clientID].join("-")
  });
  Object.defineProperty(this, "__cachedToken", {
    enumerable: false,
    configurable: false,
    writable: true,
    value: null
  });
  Object.defineProperty(this, "token", {
    enumerable: true,
    configurable: false,
    get: function() {
      if (!this.__cachedToken) {
        var savedToken = localStorage.getItem(this.tokenKey);
        if (savedToken) {
          this.__cachedToken = new Token(JSON.parse(savedToken));
          this.__cachedToken.service = this;
        }
      }
      return this.__cachedToken;
    },
    set: function(token) {
      token.service = this;
      token.save();
      this.__cachedToken = token;
    },
  });
};

Service.prototype.generateStateToken = function() {
  return Math.random().toString(36).substr(2);
};

Service.prototype.authorize = function(opts, success, error) {
  opts = opts || {};
  var params = this.tokenParams;
  if (opts.scope) { params.scope = opts.scope; }
  params.state = this.generateStateToken();

  var url = this.tokenURI + '?' + $.param(params),
      dialog = authPrompt(url);

  if (dialog) {
    var service = this;
    window.triggerOAuth2Callback = function(hash) {
      dialog.close();
      // the redirectHandler function will handle reject/resolve
      redirectHandler(params.state, success, error).call(service, hash);
    };
  } else {
    var msg = "OAuth Error: could not open authorization dialog";
    console.error(msg);
    if (typeof error === "function") { error(msg); }
  }
};

Service.prototype.clearToken = function() {
  this.__cachedToken = null;
  localStorage.removeItem(this.tokenKey);
  localStorage.removeItem(this.userKey);
};

module.exports = Service;


text:
@protocol PXTDeviceTypeDTO

@end

@interface PXTDeviceTypeDTO : JSONModel

@property (strong, nonatomic) NSString *platform;
@property (strong, nonatomic) NSString *version;
@property (strong, nonatomic) NSString *model;

@end


text:
layout: default
---

Tag: {{ page.title }}

  {% if site.tags[page.slug] %}

    {% for post in site.tags[page.slug] %}
      {% include article.html %}
    {% endfor %}

  {% else %}

There are no articles for the tag: {{ page.title }}

  {% endif %}


text:
using SqlMapper.Common.Models;

namespace SqlMapper.Common.Abstracts
{
    internal interface IMapper
    {
        void Map<T, TMapper>(T model, CommandResult data, Property propData, IMapperMain<TMapper> entryPoint);
    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width initial-scale=1">
    <title>Montar Ext4 en Debian Lenny.</title>
    <link href="/css/bootstrap.min.css" rel="stylesheet">
    <link href="/css/tether.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">

      <button class="navbar-toggler hidden-sm-up" type="button" data-toggle="collapse" data-target="#navbar-header" aria-controls="navbar-header">
        ☰
      </button>

Montar Ext4 en Debian Lenny.

Sat, Apr17, 2010

Debian Lenny no soporta el formato Ext4 oficialmente, por que era experimental en el momento en que Lenny fue lanzada, pero tenia un driver experimental que puedes usar para leer los archivos.

tune2fs -E test_fs /dev/sdax mount -t ext4dev -o ro /dev/sdax /mnt/sdax

         Freebsd /usr/ports: No such file or directory.
      |

         Optimizacion de la velocidad de carga de un website.

Home