text:
# WebRTC Simple Calling API + Mobile

At PubNub we believe simplicity is essential for our SDK usability.
We've taken a simplified approach to WebRTC Peer Connections by creating
and easy-to-use SDK for developers.
The ideas of simplicity should span all platforms and devices too and
that's why we also support **Android** WebRTC mobile calling
with compatibility for iOS native Objective-C based WebRTC SDK.
This simple developer WebRTC SDK is powered by
[PubNub Data Stream Network](http://www.pubnub.com/).

### Supported WebRTC Features

WebRTC SDK offers many rich features and capabilities to enhance the
WebRTC experience.  Here is a list of the options available.

 1. Photo Snap Camera Transmit             *(STUN-less Firewall Ready)*
 1. WebRTC Dialing                         *(STUN-less Firewall Ready)*
 1. WebRTC Call Receiving                  *(STUN-less Firewall Ready)*
 1. JSON App Messaging (chat/signals/etc.) *(STUN-less Firewall Ready)*
 1. Multi-party Calling
 1. Audio only Calls Optional
 1. Broadcasting Mode
 1. Instant Connect Dialing Optional
 1. Security SSL, AES256, ACL Access Control Management
 1. Password Protection via Cipher
 1. Event History and Call Records
 1. Photo History and Recording Static Snapshots of Calls (only stills)
 1. Connectivity Detection and Auto-Recovery
 1. Pre-configured Video Element for Streaming Video/Audio
 1. Pre-configured Local Camera Video Element for Streaming Video/Audio
 1. Network Connectivity Hooks (online/offline)
 1. SDK Level Debug Output

### Supported WebRTC Calling API Mobile Devices and Browser

List of supported WebRTC Calling Clients including Android and Chrome.

 1. Chrome
 2. Firefox
 3. Opera
 4. Mobile Chrome - Android
 5. Mobile Firefox - Android
 6. *iOS Native Objective-C Compatible*
 6. *Android Native Java Compatible*

### The Basic Concepts of WebRTC Calling

##### Making a WebRTC phone Call

```javascript
// Dial Number
var session = phone.dial('123-456');
```

##### Receiving a WebRTC phone Call

```javascript
phone.receive(function(session){
    // On Call Receiving
});
```

##### Adding Video Live Stream

```javascript
phone.receive(function(session){
    session.connected(function(session){
        // Append Live Video Feed
        $('#display-div').append(session.video);
    });
});
```

### Simple WebRTC Walkthrough

Next we will start with a copy/paste example of our SDK.
This Simple Example Comes in **Two WebRTC Calling Sections**.

 1. *Part One* will talk about how you can **Make a WebRTC Call**.
 2. *Part Two* will teach you about **Receiving a WebRTC Call**.

#### Making a WebRTC Calling & Receiving - *Part One and Two*

Make your first html file named `dial.html` and copy/paste the following:

```html
<!-- dial.html -->

<!-- Video Output Zone -->
<div id="video-out"> Making a Call </div>

<!-- Libs and Scripts -->
<script src="https://cdn.pubnub.com/pubnub.min.js"></script>
<script src="http://stephenlb.github.io/webrtc-sdk/js/webrtc.js"></script>
<script>(function(){
    // ~Warning~ You must get your own API Keys for non-demo purposes.
    // ~Warning~ Get your PubNub API Keys: http://www.pubnub.com/get-started/
    // The phone *number* can by any string value
    var phone = PHONE({
        number        : '1234',
        publish_key   : 'pub-c-561a7378-fa06-4c50-a331-5c0056d0163c',
        subscribe_key : 'sub-c-17b7db8a-3915-11e4-9868-02ee2ddab7fe',
        ssl           : true
    });

    // As soon as the phone is ready we can make calls
    phone.ready(function(){

        // Dial a Number and get the Call Session
        // For simplicity the phone number is the same for both caller/receiver.
        // you should use different phone numbers for each user.
        var session = phone.dial('1234');

    });

    // When Call Comes In or is to be Connected
    phone.receive(function(session){

        // Display Your Friend's Live Video
        session.connected(function(session){
            PUBNUB.$('video-out').appendChild(session.video);
        });

    });

})();</script>
```

### Live WebRTC Call Dialer

If you combine both the **WebRTC Dialer** and the **WebRTC Receiver**
you will get a complete working phone.
We have a live running WebRTC Demo which uses our WebRTC SDK.
This demo includes a soft-touch UI for an easy calling experience.

> try the **live WebRTC Dialing**:
[WebRTC Simple Calling API + Mobile](http://stephenlb.github.io/webrtc-sdk/)

[![WebRTC Simple Calling API + Mobile](http://pubnub.s3.amazonaws.com/assets/webrtc-simple-sdk-calling-api-peer-connect.png)](http://stephenlb.github.io/webrtc-sdk/)

You can click the link above to try our live WebRTC Demo
which is powered by our easy to use SDK.

### What Can you build with a WebRTC Simple Calling API?

There are a plethera of important and useful applications which may
be built using the PubNub WebRTC Calling SDK.
I have cataloged a list of ideas for **WebRTC Use Cases**:

 1. Amazon Mayday Help Button
 2. Salesforce SOS Help Button
 3. WebRTC Skype Replica
 4. Traditional Phone Replacement
 5. Chatroulette
 6. VoIP Replacement
 7. Customer Support Calls
 8. In-bound Sales Calls
 9. Easy Remote Meetings
 10. Call Assistant or Specialists
 11. Big Screen Public Announcemnt
 12. Live Presentations

So many different options and even more use cases
that have yet to be discovered.

### What is a WebRTC Session?

A WebRTC `Session` is a reference to a call instance
between two connected parties.
The idea is the session is active as long as the two parties are connected.
Once one party member disconnects or leaves, the session will be terminated.
You have access to several helper methods for
`session.connected()` and `session.ended()` events.

## API Documentation for WebRTC Calling SDK

The WebRTC Simple SDK API Reference will provide to you all the options
available to you as the developer.

### WebRTC Phone Initialization
##### `PHONE({ ... })`

> Initialize the phone object which can send/receive multiple
WebRTC call sessions without limit.
Be careful as your bandwidth is the true limiter.

```javascript
var phone = PHONE({
    number        : '1234567890',
    publish_key   : 'pub-c-561a7378-fa06-4c50-a331-5c0056d0163c',
    subscribe_key : 'sub-c-17b7db8a-3915-11e4-9868-02ee2ddab7fe',
    media         : { audio : true, video : true },
    ssl           : true
})
```

### WebRTC Phone Number

> Your phone number is your true ring-in point of truth.
You can set your phone number at init time from the

```javascript
var phone = PHONE({ number : '1234567890' });
```

### WebRTC Local Camera Video Element

We provide you easy access to your local camera with
a pre-initialized video element that is easy to access.
Simply append the element to your DOM and the feed will
stream automatically.

```javascript
$('#display-div').append(phone.video);
```

### WebRTC Phone SSL Mode

> You can enable SSL signalling mode for the local client device
by setting the `ssl : true` parameter at init.

```javascript
var phone = PHONE({
    ssl : true
    ...
})
```

### WebRTC Cipher AES 256 Crypto Mode

> You can enable AES256 Encryption (essentially password mode)
on your phone for additional security.
You're friends have to know your password to call you.
AES256 option allows you to password protect your phone and
only give access to people you know.
You have to give your friend your password before they can call you.

```javascript
var phone = PHONE({
    cipher_key : 'SUPER-SECRET-PASSWORD-HERE'
    ...
})
```

### WebRTC Phone Audio Only Mode

> You can disable video codec and stream only Audio by setting
the following param in your init code.
Set `video : false` in the media section.

```javascript
var phone = PHONE({
    media : { audio : true, video : false }
    ...
})
```

### WebRTC Phone Mobile Calling on Android

WebRTC calling on Android is web-ready compatible and works
out-of-the-box today without modifications or additional code.
Also WebRTC Calling is supported for Android and iOS Native too.

## WebRTC Photo Sharing *Bonus STUN-less Ready*

You can easily snap a photo from the video stream and
send it to your friends in an instnat.
You can think of this as an **Instagram WebRTC** style.
Also Photo Sharing works through Corprate Enterprise Firewalls.

### WebRTC Camera Photo Sharing Broadcast
##### `phone.snap()`

> Broadcast your camera photo to all connected sessions.
Also get the IMG data as base64 supported format
for local display if desired.

```javascript
phone.ready(function(){
    // Auto Send Camera's Photo to all connected Sessions.
    var photo = phone.snap();
    $('#photo-div').append(photo.image);
});
```

### WebRTC Session Camera Photo Share
##### `session.snap()`

> Send your camera's latest frame as raw IMG to
a specific call session.

```javascript
phone.ready(function(){
    var session = phone.dial('4321');
    var photo   = session.snap();
    $('#photo-div').append(photo.image);
});
```

## WebRTC JSON Messaging *Bonus STUN-less Ready*

Adding extra realtime capabilities between connected parties
is essential for creating collaberative and chat features.
You can do that with PubNub's WebRTC SDK easily without
firewall restrictions from corporate policies.

### Message Broadcasting to All Sessions
##### `phone.send(...)`

> Send a JSON message to all connected sessions.

```javascript
phone.send({ text : 'HI!' });
```

### Receive a JSON message from Any Session
##### `phone.message(function(message){ ... })`

> Get all messages sent from any session.

```javascript
phone.message(function( session, message ) {
    show_chat( session.number, message.text );
} );
```

### Send a JSON Message to One Session
##### `session.send(...)`

> You can send a direct JSON message to one session only.

```javascript
session.send({ text : 'Hi there!' });
```

### Receive a JSON message from One Session
##### `session.message(function(){ ... })`

> You can set callbacks to capture JSON messages
from a specific call session.

```javascript
session.message(function( session, message ) {
    show_chat( session.number, message.text );
} );
```

### WebRTC Phone Ready
##### `phone.ready(function(){ ... })`

> Making calls is easy but you can only do it when the phone is
ready to issue the signals properly and the local interfaces
have been configured such as audio/video media.

```javascript
phone.ready(function(){
    // Ready to make Calls
    var session = phone.dial("my-friend's-number");
});
```

### WebRTC Phone Receiving Calls
##### `phone.receive(function(session){ ... })`

> It's really ease to setup your phone to receive calls using
the `phone.receive()` method.
This method expects a callback function and will pass the
WebRTC Session object as the only parameter.

```javascript
phone.receive(function(session){
    session.connected(function(session){ /* call connected */ });
    session.ended(function(session){     /* call ended     */ });
});
```

### Get Your Phone Number
##### `var num = phone.number()`

> Sometimes you need to access the phone number
that was set during initialization time.
You can do that by calling `phone.number()` method
which returns the setup number.

```javascript
var num = phone.number();
```

### Get Caller Phone Number
##### `var num = session.number`

> To access current caller number, check the session
object number property `session.number`.

```javascript
var num = session.number;
```

### Get Call Start Time
##### `var start = session.started`

> The Session object stores the call start time which
you can use to display call timer on the screen.

```javascript
var start = session.started;
```

### WebRTC Phone Call History via PubNub
##### `phone.history(...)`

> You can get the call history of a phone number by issuing
a PubNub History call on the phne number.

```javascript
phone.history({
    number  : '1234',
    history : function(call_history) {
        console.log(call_history);
    }
});
```

### WebRTC Phone Dialing Numbers
##### `phone.dial(number)`

> You can easily make WebRTC calls by executing the `dial()` method.
The number can be any string value such as `"415-555-5555"`.

```javascript
var session = phone.dial(number);

session.connected(function(session){ /* call connected */ });
session.ended(function(session){     /* call ended     */ });
```

### WebRTC Phone Multi-party Dialing
##### `phone.dial(number)`

> The PubNub WebRTC Phone Dialer and Receiver supports
unlimited party in/out calling.

```javascript
var sessions = [];

sessions.push(phone.dial('friend-one'));
sessions.push(phone.dial('friend-two'));
sessions.push(phone.dial('friend-three'));
sessions.push(phone.dial('friend-four'));
sessions.push(phone.dial('friend-five'));

sessions.forEach(function(friend){
    friend.connected(function(session){ /* call connected */ });
    friend.ended(function(session){     /* call ended     */ });
});
```

### WebRTC Phone Broadcasting Mode
##### `phone.receive(function(session){ ... })`

> You can receive unlimited inbound calls and become a broadcast
beacon stream.
You are limited by your bandwidth upload capacity.

### WebRTC Phone Hangup
##### `phone.hangup()`

> There are two ways to hangup WebRTC calls.
You can use the phone-level method `phone.hangup()`
which will hangup all calls at once.
Or you can use the session-level method `session.hangup()`
which will only hangup that call session.

```javascript
// hangup all calls
phone.hangup();

// hangup single session
session.hangup();
```

### WebRTC Phone Network Events
##### `PHONE.disconnect(function(){ ... })`

> You need to keep track of the connectivity state of your local
network connection. You can do that using these helper methods.

```javascript
PHONE.connect(function(){    console.log('network LIVE.') })
PHONE.disconnect(function(){ console.log('network GONE.') })
PHONE.reconnect(function(){  console.log('network BACK!') })
```

### WebRTC Phone Unable to Initialize
##### `phone.unable(function(details){ ... })`

> Some devices or in certain situations the phone may not initialize.
We give you a simple callback for when the phone startup fails.

```javascript
phone.unable(function(details){
    console.log("Phone is unable to initialize.");
    console.log("Try reloading, or give up.");
});
```

### WebRTC Phone Debugging
##### `phone.debug(function(details){ ... })`

> You might want to see under the covers of WebRTC Calling by
enabling debugging mode on the WebRTC SDK.

```javascript
phone.debug(function(details){
     console.log(details);
});
```

### WebRTC Phone Auto Hangup and Goodbye on Unload

The WebRTC Calling SDK will attempt an automatic `goodbye` upon graceful
disconnection attempts.
This allows the 2nd party on the other end of the phone line to
receive a call `ended` signal.
This happens automatically.

### The WebRTC Session Object

A WebRTC Session represents the connection between two parties with access
to the `session.video` element as well as the place to register
event callbacks as needed such as `session.connected`
and also the ended callback for when the call disconnects or hangs up.

```javascript
session.ended(function(session){})
```

A session object is generated automatically for you upon dialing

```javascript
var session = phone.dial('...')
```

and also inside registered event callbacks.

```javascript
phone.receive(function(session){})
```

### WebRTC Session Number
##### `session.number`

> Returns the 2nd party's (caller/callee)
Phone Number associated with the Call Session.

```javascript
var session = phone.dial('12345');
console.log(session.number == '12345');
```

### WebRTC Session Connected Callback
##### `session.connected(function(session){})`

> Sets the callback for when the session is connected and
the **video** stream is ready to display.

```javascript
session.connected(function(session){
    var body = document.getElementsByTagName('body')[0];
    body.appendChild(session.video);
});
```

### WebRTC Session Ended Callback
##### `session.ended(function(session){})`

> The session has ended by one of the parties.
Any secondary session will continue to stream.

```javascript
session.ended(function(session){
    sounds.play('sound/goodbye');
    console.log("Bye!");
});
```

### WebRTC Session Hangup
##### `session.hangup()`

> End the session right now.
The `ended` callback will fire for both connected parties.

```javascript
$("#hangup").click(function(){
    // End the call
    session.hangup();
});
```

### WebRTC Session Video Element
##### `session.video`

> The Session Video Element is Accessable and Ready
inside the `connected` only.
The Session Video ref is an HTML Video Element `<video>`.

```javascript
session.connected(function(session){
    var body  = document.getElementsByTagName('body')[0];
    var video = session.video;

    body.appendChild(video);
});
```

### WebRTC Session Image Element
##### `session.image`

> The Session Image Element is Accessable and Ready
inside the `thumbnail`, `connected` and `ended` callbacks.
The Session Image ref is an HTML Image Element `<img>`.

```javascript
session.thumbnail(function(session){
    var body  = document.getElementsByTagName('body')[0];
    var image = session.image;

    body.appendChild(image);
});
```

### WebRTC Session RTCPeerConnection Reference
##### `session.pc`

> Reference to WebRTC RTCPeerConnection.

```javascript
var sesionPeerConnection = session.pc;
```

### WebRTC Adding Custom STUN and TURN Servers

> You may desire to add your own custom stun or turn servers by using
the `servers` parameter on initialization.
For example http://xirsys.com/ offers paid-stun solution.

```javascript
var phone = PHONE({
    servers : [
        {"username":"free","url":"turn:127.0.0.1?transport=udp","credential":"free"},
        {"username":"free","url":"turn:127.0.0.1?transport=tcp","credential":"free"}
    ]
    // ...
})
```

## SDK Possible Upgrade Future Patches

    - Race - During Ring/Receive Handshake, a Hangup will create Race
    - Wire-pulled Disconnect Detect via DataChannels Pings
    - 5 Second Timeout to Retry with 30 Second of Retries
    - Auto-reconnect re-SDP/ICE Recovery
    - Custom Message Events
    - Presence
    - Call History
    - User Lists

## Implementation Reference Upgrades

    - Pre-Allow Transmit - Before "allow" fire a PubNub message
    - Chat on Screen
    - Multi-Party Video in GUI
    - Full Screen Mode
    - Controlling an iFrame

### What is Happens Inside the Simple WebRTC SDK

##### Signaling and Exchanging ICE Candidates via PubNub

The goal is to exchange ICE candidate packets between two peers.
`ICE candidate packets` are structured payloads which contain possible
path recommendations between two peers.
You can use a lib which will take care of the nitty gritty such as
[WebRTC Simple Calling API + Mobile](https://github.com/stephenlb/webrtc-sdk)
however below is the general direction that is taken inside the SDK itself.

Note that the demonstration code below is intintionally incomplete.
Note however the PubNub WebRTC Signaling SDK properly covers
most Calling Situations.

#### Signaling Example Code Follows

```html
<script src="http://cdn.pubnub.com/pubnub-3.6.3.min.js"></script>
<script>(function(){

    // INIT P2P Packet Exchanger
    var pubnub = PUBNUB({
        publish_key   : 'demo',
        subscribe_key : 'demo'
    })

    // You need to specify the exchange channel for the peers to
    // exchange ICE Candidates.
    var exchange_channel = "p2p-exchange";

    // LISTEN FOR SDP and ICE CANDIDATES
    pubnub.subscribe({
        channel : exchange_channel,
        message : receive_ice_candidates
    })

    // SDP and ICE CANDIDATES RECEIVER PROCESSOR FUNCTION
    function receive_ice_candidates(ice_candidate) {
        // Attempt peer connection or upgrade route if better route...
        console.log(ice_candidate);
        // ... RTC Peer Connection upgrade/attempt ...
    }

    // SEND SDP and ICE CANDIDATES
    function send_ice_candidate(ice) {
        pubnub.publish({
            channel : exchange_channel,
            message : ice
        })
    }

})();</script>
```

#### Generate ICE Candidates Example Code Follows:

```html
<script>(function(){
    // CREATE ICE CANDIDATES
    var pc = new RTCPeerConnection();
    navigator.getUserMedia( {video: true}, function(stream) {
        pc.onaddstream({stream:stream});
        pc.addStream(stream);
        pc.createOffer( function(offer) {
            pc.setLocalDescription(
                new RTCSessionDescription(offer),
                send_ice_candidate,
                error
            );
        }, error );
    } );

})();</script>
```

### WebRTC Troubleshooting

You may need to force clear your cache on your device, close the app completley, then restart it.
This is uncommon.
You can also enable debugging at the code-level by hooking onto the `phone.unable(fn)` and `phone.debug(fn)`.


text:
package com.androiddvptteam.helpme;

import com.androiddvptteam.helpme.Connection.SendMessageConnection;

import java.net.URL;
import java.util.Calendar;

/**
 * 发送消息
 */
public class SendMessage
{
    public SendMessage(String ID, String pn, String rn, String state, String t)
    {
        final String id = ID;//任务ID
        final String publisherNumber = pn;//发布者的学号
        final String recipientNumber = rn;//接收者的学号
        final String st = state;//任务状态
        final String title = t;//标题
        new Thread(new Runnable()
        {
            @Override
            public void run()
            {
                Calendar c = Calendar.getInstance();
                SendMessageConnection connection;
                String year = String.valueOf(c.get(Calendar.YEAR));
                String month = String.valueOf(c.get(Calendar.MONTH) + 1);
                if (c.get(Calendar.MONTH) + 1 < 10)
                    month = "0" + String.valueOf(c.get(Calendar.MONTH) + 1);
                String day = String.valueOf(c.get(Calendar.DATE));
                if (c.get(Calendar.DATE) < 10)
                    day = "0" + String.valueOf(c.get(Calendar.DATE));
                String hour = String.valueOf(c.get(Calendar.HOUR_OF_DAY));
                if (c.get(Calendar.HOUR_OF_DAY) < 10)
                    hour = "0" + String.valueOf(c.get(Calendar.HOUR_OF_DAY));
                String minute = String.valueOf(c.get(Calendar.MINUTE));
                if (c.get(Calendar.MINUTE) < 10)
                    minute = "0" + String.valueOf(c.get(Calendar.MINUTE));
                String second = String.valueOf(c.get(Calendar.SECOND));
                if (c.get(Calendar.SECOND) < 10)
                    second = "0" + String.valueOf(c.get(Calendar.SECOND));
                try
                {
//                    connection = new SendMessageConnection(new URL("http://172.30.211.84:8080/AndroidServlet/SendMessageServlet"));
                    connection = new SendMessageConnection(new URL("http://123.206.125.166:8080/AndroidServlet/SendMessageServlet"));
                    connection.setAttributes(id, publisherNumber, recipientNumber, st, title, year, month, day, hour, minute, second);
                    connection.connect();
                } catch (Exception e)
                {
                    e.printStackTrace();
                }
            }
        }
        ).start();
    }
}

redpajama_set_name: RedPajamaGithub


text:
module ProjectForksHelper
  def fork_project(project, user = nil, params = {})
    Gitlab::GitalyClient.allow_n_plus_1_calls do
      fork_project_direct(project, user, params)
    end
  end

  def fork_project_direct(project, user = nil, params = {})
    # Load the `fork_network` for the project to fork as there might be one that
    # wasn't loaded yet.
    project.reload unless project.fork_network

    unless user
      user = create(:user)
      project.add_developer(user)
    end

    unless params[:namespace]
      params[:namespace] = create(:group)
      params[:namespace].add_owner(user)
    end

    namespace = params[:namespace]
    create_repository = params.delete(:repository)

    unless params[:target_project] || params[:using_service]
      target_level = [project.visibility_level, namespace.visibility_level].min
      visibility_level = Gitlab::VisibilityLevel.closest_allowed_level(target_level)

      params[:target_project] =
        create(:project,
          (:repository if create_repository),
          visibility_level: visibility_level, creator: user, namespace: namespace)
    end

    service = Projects::ForkService.new(project, user, params)

    # Avoid creating a repository
    unless create_repository
      allow(RepositoryForkWorker).to receive(:perform_async).and_return(true)
      shell = double('gitlab_shell', fork_repository: true)
      allow(service).to receive(:gitlab_shell).and_return(shell)
    end

    forked_project = service.execute(params[:target_project])

    # Reload the both projects so they know about their newly created fork_network
    if forked_project.persisted?
      project.reload
      forked_project.reload
    end

    if create_repository
      # The call to project.repository.after_import in RepositoryForkWorker does
      # not reset the @exists variable of this forked_project.repository
      # so we have to explicitly call this method to clear the @exists variable.
      # of the instance we're returning here.
      forked_project.repository.expire_content_cache
    end

    forked_project
  end

  def fork_project_with_submodules(project, user = nil, params = {})
    Gitlab::GitalyClient.allow_n_plus_1_calls do
      forked_project = fork_project_direct(project, user, params)
      TestEnv.copy_repo(
        forked_project,
        bare_repo: TestEnv.forked_repo_path_bare,
        refs: TestEnv::FORKED_BRANCH_SHA
      )
      forked_project.repository.expire_content_cache

      forked_project
    end
  end
end


text:
package tools;

import gui_system.Menulizable;
import main.IMP;

public class Command
implements Appliable, Menulizable{

	public String name;
	public String action;
	public String category;
	public char key_shortcut;
	public boolean needs_open_image;
	public boolean works_during_other_routines;

	public Command(String name, String action, String category) {
		this.name = name;
		this.action = action;
		this.category = category;
	}

	@Override
	public void apply(){
		IMP.action_informant.broadcast_message(action);
        IMP.apply_action(action);
	}

	@Override
	public void activate() {
		apply();
	}

	@Override
	public void abort() {
		// TODO Auto-generated method stub
	}

	@Override
	public boolean safe_to_activate(){
		return !(needs_open_image && IMP.opened_image == null)
				&& !(IMP.routine_in_process && !works_during_other_routines);
	}

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

	public String get_action() {
		return action;
	}

	@Override
	public String get_category() {
		return category;
	}

	@Override
	public char get_key_shortcut() {
		return key_shortcut;
	}

}


text:
namespace PhysX
{
	public value class XmlParserOptions
	{
	internal:
		static PxSerialization::PxXmlMiscParameter ToUnmanaged(XmlParserOptions managed);

	public:
		property Vector3 UpVector;
		property TolerancesScale Scale;
	};
}


text:
using Microsoft.AspNetCore.Mvc;
using QrF.Core.Admin.Domain;
using QrF.Core.Admin.Dto;
using QrF.Core.Admin.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace QrF.Core.Admin.Controllers
{
    /// <summary>
    ///
    /// </summary>
    [Route("AdminAPI/[controller]")]
    [ApiController]
    public class OrganizeController : ControllerBase
    {
        private readonly IOrganizeBusiness _business;
        public OrganizeController(IOrganizeBusiness business)
        {
            _business = business;
        }
        /// <summary>
        /// 查询分页列表
        /// </summary>
        [HttpGet("GetPageList")]
        public async Task<BasePageQueryOutput<QueryOrganizeDto>> GetPageListAsync([FromQuery] QueryOrganizesInput input)
        {
            return await _business.GetPageList(input);
        }

        /// <summary>
        /// 获取模块级联列表
        /// </summary>
        [HttpGet("GetCascaderList")]
        public async Task<IEnumerable<CascaderItem>> GetCascaderListAsync()
        {
            var list = await _business.GetListAsync(null);
            if (list.Count(o => o.ParentId == null || o.ParentId == Guid.Empty) < 1)
                return null;
            var result = from d in list.Where(o => o.ParentId == null || o.ParentId == Guid.Empty)
                         select new CascaderItem
                         {
                             value = d.KeyId,
                             label = d.Name,
                             children = GetCascaderItem(d.KeyId, list)
                         };
            return result;
        }

        /// <summary>
        /// 编辑
        /// </summary>
        [HttpPost("Edit")]
        public async Task<IActionResult> EditAsync([FromBody] OrgDto input)
        {
            await _business.EditModel(input);
            return Ok(new MsgResultDto { Success = true });
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <returns></returns>
        [HttpPost("Delete")]
        public async Task<IActionResult> DeleteAsync([FromBody] DelInput input)
        {
            if (input == null || !input.KeyId.HasValue) throw new Exception("编号不存在");
            await _business.DelModel(input.KeyId.Value);
            return Ok(new MsgResultDto { Success=true });
        }

        private IEnumerable<CascaderItem> GetCascaderItem(Guid pid, IEnumerable<QueryOrganizeDto> all)
        {
            if (all.Count(o => o.ParentId == pid) < 1)
                return null;
            var result = from d in all.Where(o => o.ParentId == pid)
                         select new CascaderItem
                         {
                             value = d.KeyId,
                             label = d.Name,
                             children = GetCascaderItem(d.KeyId, all)
                         };
            return result;
        }

    }
}


text:
<?php

namespace Omnipay\PayPal\Message;

/**
 * PayPal Pro Purchase Request
 */
class ProPurchaseRequest extends ProAuthorizeRequest
{
    public function getData()
    {
        $data = parent::getData();
        $data['PAYMENTACTION'] = 'Sale';

        return $data;
    }
}


text:
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;

namespace AccountAtAGlance.Model
{
    public class Customer
    {
        public Customer()
        {
            BrokerageAccounts = new HashSet<BrokerageAccount>();
        }

        // Primitive properties
        public int Id { get; set; }

        [StringLength(50)]
        public string FirstName { get; set; }
        [StringLength(50)]
        public string LastName { get; set; }
        [StringLength(250)]
        public string Address { get; set; }
        [StringLength(50)]
        public string City { get; set; }
        [StringLength(2)]
        public string State { get; set; }
        public int Zip { get; set; }
        [StringLength(10)]
        public string CustomerCode { get; set; }
        public string NewPropertyAdded { get; set; }

        // Navigation properties
        public ICollection<BrokerageAccount> BrokerageAccounts { get; set; }
    }
}


text:
class Facility::CategoriesController < ApplicationController
  include Cms::BaseFilter
  include Cms::NodeFilter

  model Facility::Node::Category

  prepend_view_path "app/views/cms/node/nodes"
  navi_view "facility/categories/navi"

  private

  def fix_params
    { cur_user: @cur_user, cur_site: @cur_site, cur_node: @cur_node }
  end

  def pre_params
    { route: "facility/category" }
  end
end


text:
		  <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar-usda-collapse" aria-expanded="false">
			Toggle navigation

		  </button>
		  <a class="navbar-brand" href="<?=base_url()?>">
				<img src="<?=PATH_IMG?>header/logo.png" class="img-responsive" />

						<?=$global['language_list'][$this->session->userdata('language')]?>

						<?
							foreach($global['language_list'] as $language_key => $language_value) {
						?>

<a href="<?=base_url('client/language/'.$language_key)?>?redirect=<?=urlencode(uri_string())?>"><?=$language_value?>

						<?
							}
						?>

			<?
				if ($this->uri->segment(1) == 'apply') {
					if ($this->session->userdata('hide_required') != 1) {
			?>

					*<?=$this->lang->line('nav_required')?>

			<?
					}
				} else {
			?>
				<li class="<?=($global['nav'] == 'faq' ? 'active' : NULL)?>">
					<?/* <a href="<?=base_url('faq')?>"> */?>
					<?=$this->lang->line('nav_faq')?>

			<?
				}
			?>
			<?
				/*
			?>
			<li class="<?=($global['nav'] == 'how-it-works' ? 'active' : NULL)?>">
				<a href="<?=base_url('how-it-works')?>"><?=$this->lang->line('nav_how_it_works')?>

			<li class="<?=($global['nav'] == 'status' ? 'active' : NULL)?>">
				<a href="<?=base_url('status')?>"><?=$this->lang->line('nav_application_status')?>

			<li class="<?=($global['nav'] == 'help' ? 'active' : NULL)?>">
				<a href="<?=base_url('help')?>"><?=$this->lang->line('nav_help')?>

			<li class="<?=($global['nav'] == 'apply' ? 'active' : NULL)?>">
				<a href="<?=base_url('apply')?>">
					<?=$this->lang->line('nav_apply_now')?>

			*/
			?>


text:
import React from 'react-native';

var {
    Text,
    StyleSheet,
    TouchableHighlight
} = React;

export default React.createClass({
    render: function(){
	return (
		<TouchableHighlight
	    style={styles.button}
	    underlayColor={'gray'}
	    onPress={this.props.onPress}
		>
		<Text style={styles.buttonText}>{this.props.text}</Text>
		</TouchableHighlight>
	);
    }
});

var styles = StyleSheet.create({
    buttton: {
	justifyContent: 'center',
	alignItems: 'center',
	borderWidth: 1,
	borderRadius: 5,
	padding: 5,
	borderColor: 'black',
	marginTop: 10
    },
    buttonText: {
	flex: 1,
	alignSelf: 'center',
	fontSize: 20
    }
});


text:
using System;
using System.IO;
using log4net;

namespace NPanday.VisualStudio.Addin
{
    public class WebServicesReferenceWatcher
    {
        public event EventHandler<WebReferenceEventArgs> Renamed;
        public event EventHandler<WebReferenceEventArgs> Created;
        public event EventHandler<WebReferenceEventArgs> Deleted;

        private static readonly ILog log = LogManager.GetLogger(typeof(WebServicesReferenceWatcher));

        FileSystemWatcher watcher;
        string folderPath;

        public WebServicesReferenceWatcher(string folderPath)
        {
            this.folderPath = folderPath;
            this.init();
        }

        public void Start()
        {
            watcher.EnableRaisingEvents = true;
        }

        public void Stop()
        {
            watcher.EnableRaisingEvents = false;
            watcher.Dispose();
        }

        void init()
        {

            watcher = new FileSystemWatcher(folderPath);
            watcher.NotifyFilter = NotifyFilters.DirectoryName;
            watcher.Renamed += new RenamedEventHandler(watcher_Renamed);
            watcher.Deleted += new FileSystemEventHandler(watcher_Deleted);
            watcher.Created += new FileSystemEventHandler(watcher_Created);
            watcher.Error += new ErrorEventHandler(watcher_Error);
            watcher.Changed += new FileSystemEventHandler(watcher_Changed);
            watcher.IncludeSubdirectories = false;

        }

        void watcher_Changed(object sender, FileSystemEventArgs e)
        {
            log.Debug("web service changed: " + e.FullPath);
        }

        void watcher_Error(object sender, ErrorEventArgs e)
        {
            this.Stop();
        }

        void watcher_Created(object sender, FileSystemEventArgs e)
        {
            WebReferenceEventArgs a = new WebReferenceEventArgs(e.ChangeType, e.FullPath, e.Name);

            onCreated(a);
        }

        void watcher_Deleted(object sender, FileSystemEventArgs e)
        {
            WebReferenceEventArgs a = new WebReferenceEventArgs(e.ChangeType, e.FullPath, e.Name);
            onDeleted(a);
        }

        void watcher_Renamed(object sender, RenamedEventArgs e)
        {
            WebReferenceEventArgs a = new WebReferenceEventArgs(e.ChangeType, e.FullPath, e.Name);
            a.OldNamespace = e.OldName;

            onRenamed(a);
        }

        void onRenamed(WebReferenceEventArgs e)
        {
            if (Renamed != null)
            {
                Renamed(this, e);
            }
        }

        void onDeleted(WebReferenceEventArgs e)
        {
            if (Deleted != null)
            {
                Deleted(this, e);
            }
        }

        void onCreated(WebReferenceEventArgs e)
        {
            if (Created != null)
            {
                Created(this, e);
            }
        }

    }
}


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

using Microsoft.CodeAnalysis.CSharp.Syntax;

namespace Microsoft.CodeAnalysis.CSharp.Syntax
{
    public partial class ThrowStatementSyntax
    {
        public ThrowStatementSyntax Update(SyntaxToken throwKeyword, ExpressionSyntax expression, SyntaxToken semicolonToken)
            => Update(attributeLists: default, throwKeyword, expression, semicolonToken);
    }
}

namespace Microsoft.CodeAnalysis.CSharp
{
    public partial class SyntaxFactory
    {
        public static ThrowStatementSyntax ThrowStatement(SyntaxToken throwKeyword, ExpressionSyntax expression, SyntaxToken semicolonToken)
            => ThrowStatement(attributeLists: default, throwKeyword, expression, semicolonToken);
    }
}


text:
'''OFS. See README.rst.'''
from . import base
from .base import OFSException
from .factory import get_impl


text:
package com.twosigma.beaker.sqlsh.utils;

import java.util.ArrayList;
import java.util.List;

public class BeakerParseResult {
  boolean selectInto;
  String resultQuery;
  String selectIntoVar;
  List<BeakerInputVar> inputVars = new ArrayList<>();

  public BeakerParseResult(String resultQuery) {
    this.resultQuery = resultQuery;
  }

  public String getResultQuery() {
    return resultQuery;
  }

  public void setResultQuery(String resultQuery) {
    this.resultQuery = resultQuery;
  }

  public String getSelectIntoVar() {
    return selectIntoVar;
  }

  public void setSelectIntoVar(String selectIntoVar) {
    this.selectIntoVar = selectIntoVar;
  }

  public boolean isSelectInto() {
    return selectInto;
  }

  public void setSelectInto(boolean selectInto) {
    this.selectInto = selectInto;
  }

  public List<BeakerInputVar> getInputVars() {
    return inputVars;
  }

  public void setInputVars(List<BeakerInputVar> inputVars) {
    this.inputVars = inputVars;
  }
}


text:
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Eshopworld.Core;
using JetBrains.Annotations;
using Microsoft.Azure.ServiceBus;
using Microsoft.Azure.ServiceBus.Core;
using Newtonsoft.Json;
using Nito.AsyncEx;
using Polly;
using Polly.Retry;

namespace Eshopworld.Messaging
{
    internal abstract class ServiceBusAdapter<T> : ServiceBusAdapter
        where T : class
    {
        internal readonly IDictionary<T, Message> Messages = new ConcurrentDictionary<T, Message>(ObjectReferenceEqualityComparer<T>.Default);
        internal readonly IDictionary<T, Timer> LockTimers = new ConcurrentDictionary<T, Timer>(ObjectReferenceEqualityComparer<T>.Default);
        internal readonly IObserver<T> MessagesIn;
        internal readonly bool RawMessages;

        internal MessageReceiver Receiver;
        internal AsyncReaderWriterLock ReceiverLock = new AsyncReaderWriterLock();

        internal Timer ReadTimer;
        internal int BatchSize;

        internal long LockInSeconds;
        internal long LockTickInSeconds;

        protected AsyncRetryPolicy SendPolicy = Policy.Handle<Exception>().RetryAsync(1);
        protected AsyncRetryPolicy ReceivePolicy = Policy.Handle<Exception>().RetryAsync(1);

        protected ServiceBusAdapter([NotNull]IObserver<T> messagesIn, int batchSize)
        {
            MessagesIn = messagesIn;
            BatchSize = batchSize;

            RawMessages = typeof(T) == typeof(Message);
        }

        /// <summary>
        /// Releases a message from the Queue by releasing all the specific message resources like lock
        /// renewal timers.
        /// This is called by all the methods that terminate the life of a message like COMPLETE, ABANDON and ERROR.
        /// </summary>
        /// <param name="message">The message that we want to release.</param>
        internal void Release([NotNull]T message)
        {
            lock (Gate)
            {
                if (!RawMessages)
                {
                    Messages.Remove(message);
                }

                // check for a lock renewal timer and release it if it exists
                if (LockTimers.ContainsKey(message))
                {
                    LockTimers[message]?.Dispose();
                    LockTimers.Remove(message);
                }
            }
        }

        /// <inheritdoc />
        internal override Task Complete<T1>(T1 message)
        {
            if (!(message is T tMessage))
                throw new ArgumentException($"{nameof(message)} should be of type {typeof(T)}");

            return Complete(tMessage);
        }

        /// <summary>
        /// Completes a message by doing the actual READ from the queue.
        /// </summary>
        /// <param name="message">The message we want to complete.</param>
        internal async Task Complete(T message)
        {
            var m = RawMessages ? message as Message : Messages[message];

            await ReceivePolicy.ExecuteAsync(
                async () =>
                {
                    try
                    {
                        using (await ReceiverLock.ReaderLockAsync())
                        {
                            await Receiver.CompleteAsync(m?.SystemProperties.LockToken).ConfigureAwait(false);
                        }
                    }
                    catch
                    {
                        await RebuildReceiver().ConfigureAwait(false);
                        throw;
                    }
                }).ConfigureAwait(false);

            Release(message);
        }

        /// <inheritdoc />
        internal override Task Abandon<T1>(T1 message)
        {
            if (!(message is T tMessage))
                throw new ArgumentException($"{nameof(message)} should be of type {typeof(T)}");

            return Abandon(tMessage);
        }

        /// <summary>
        /// Abandons a message by returning it to the queue.
        /// </summary>
        /// <param name="message">The message we want to abandon.</param>
        internal async Task Abandon(T message)
        {
            var m = RawMessages ? message as Message : Messages[message];

            await ReceivePolicy.ExecuteAsync(
                async () =>
                {
                    try
                    {
                        using (await ReceiverLock.ReaderLockAsync())
                        {
                            await Receiver.AbandonAsync(m?.SystemProperties.LockToken).ConfigureAwait(false);
                        }
                    }
                    catch
                    {
                        await RebuildReceiver().ConfigureAwait(false);
                        throw;
                    }
                }).ConfigureAwait(false);

            Release(message);
        }

        /// <inheritdoc />
        internal override Task Error<T1>(T1 message)
        {
            if (!(message is T tMessage))
                throw new ArgumentException($"{nameof(message)} should be of type {typeof(T)}");

            return Error(tMessage);
        }

        /// <summary>
        /// Errors a message by moving it specifically to the error queue.
        /// </summary>
        /// <param name="message">The message that we want to move to the error queue.</param>
        internal async Task Error(T message)
        {
            var m = RawMessages ? message as Message : Messages[message];

            await ReceivePolicy.ExecuteAsync(
                async () =>
                {
                    try
                    {
                        using (await ReceiverLock.ReaderLockAsync())
                        {
                            await Receiver.DeadLetterAsync(m?.SystemProperties.LockToken).ConfigureAwait(false);
                        }
                    }
                    catch
                    {
                        await RebuildReceiver().ConfigureAwait(false);
                        throw;
                    }
                }).ConfigureAwait(false);

            Release(message);
        }

        /// <inheritdoc />
        internal override Task Lock<T1>(T1 message)
        {
            if (!(message is T tMessage))
                throw new ArgumentException($"{nameof(message)} should be of type {typeof(T)}");

            return Lock(tMessage);
        }

        /// <summary>
        /// Creates a perpetual lock on a message by continuously renewing it's lock.
        /// This is usually created at the start of a handler so that we guarantee that we still have a valid lock
        /// and we retain that lock until we finish handling the message.
        /// </summary>
        /// <param name="message">The message that we want to create the lock on.</param>
        internal async Task Lock(T message)
        {
            var m = RawMessages ? message as Message : Messages[message];

            await ReceivePolicy.ExecuteAsync(
                async () =>
                {
                    try
                    {
                        using (await ReceiverLock.ReaderLockAsync())
                        {
                            await Receiver.RenewLockAsync(m).ConfigureAwait(false);
                        }
                    }
                    catch
                    {
                        await RebuildReceiver().ConfigureAwait(false);
                        throw;
                    }
                }).ConfigureAwait(false);

            LockTimers.Add(
                message,
                new Timer(
                    async _ => {
                        using (await ReceiverLock.ReaderLockAsync())
                        {
                            await Receiver.RenewLockAsync(Messages[message]).ConfigureAwait(false);
                        }
                    },
                    null,
                    TimeSpan.FromSeconds(LockTickInSeconds),
                    TimeSpan.FromSeconds(LockTickInSeconds)));
        }

        /// <summary>
        /// [BATCHED] Read message call back.
        /// </summary>
        /// <param name="_">[Ignored]</param>
        internal async Task Read([CanBeNull]object _)
        {
            if (Receiver.IsClosedOrClosing) return;
            IList<Message> messages = null;

            await ReceivePolicy.ExecuteAsync(
                async () =>
                {
                    try
                    {
                        using (await ReceiverLock.ReaderLockAsync())
                        {
                            messages = await Receiver.ReceiveAsync(BatchSize).ConfigureAwait(false);
                        }
                    }
                    catch
                    {
                        await RebuildReceiver().ConfigureAwait(false);
                        throw;
                    }
                }).ConfigureAwait(false);

            if (messages == null) return;

            foreach (var message in messages)
            {
                if (RawMessages)
                {
                    MessagesIn.OnNext(message as T);
                }
                else
                {
                    var messageBody = JsonConvert.DeserializeObject<T>(Encoding.UTF8.GetString(message.Body));
                    Messages[messageBody] = message;
                    MessagesIn.OnNext(messageBody);
                }
            }
        }

        /// <inheritdoc />
        internal override void StopReading()
        {
            ReadTimer.Dispose();
            ReadTimer = null;
        }

        /// <inheritdoc />
        internal override void SetBatchSize(int batchSize)
        {
            BatchSize = batchSize;
            Receiver.PrefetchCount = batchSize;
        }

        /// <inheritdoc />
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                ReadTimer?.Dispose();
                Receiver?.CloseAsync().ConfigureAwait(false).GetAwaiter().GetResult();
            }
        }

        /// <summary>
        /// Rebuild the receiver object used by the adapter implementation.
        ///     Used with retry policies to improve reliability of the receiver:
        ///     - On failure, rebuild and retry again right away
        ///     - If the retry fails -> throw
        /// </summary>
        protected abstract Task RebuildReceiver();

        /// <summary>
        /// Rebuild the sender object used by the adapter implementation.
        ///     Used with retry policies to improve reliability of the sender:
        ///     - On failure, rebuild and retry again right away
        ///     - If the retry fails -> throw
        /// </summary>
        protected abstract Task RebuildSender();
    }

    /// <summary>
    /// Non generic message queue/topic router from <see cref="IObservable{IMessage}"/> through to the ServiceBus entities.
    /// </summary>
    internal abstract class ServiceBusAdapter : IDisposable
    {
        internal readonly object Gate = new object();

        /// <inheritdoc />
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        /// <summary>
        /// Completes a message by doing the actual READ from the queue.
        /// </summary>
        /// <param name="message">The message we want to complete.</param>
        internal abstract Task Complete<T>(T message) where T : class;

        /// <summary>
        /// Abandons a message by returning it to the queue.
        /// </summary>
        /// <param name="message">The message we want to abandon.</param>
        internal abstract Task Abandon<T>(T message);

        /// <summary>
        /// Errors a message by moving it specifically to the error queue.
        /// </summary>
        /// <param name="message">The message that we want to move to the error queue.</param>
        internal abstract Task Error<T>(T message);

        /// <summary>
        /// Sets the size of the message batch during receives.
        /// </summary>
        /// <param name="batchSize">The size of the batch when reading for a queue - used as the pre-fetch parameter of the </param>
        internal abstract void SetBatchSize(int batchSize);

        /// <summary>
        /// Stops pooling the queue for reading messages.
        /// </summary>
        internal abstract void StopReading();

        /// <summary>
        /// Creates a perpetual lock on a message by continuously renewing it's lock.
        /// This is usually created at the start of a handler so that we guarantee that we still have a valid lock
        /// and we retain that lock until we finish handling the message.
        /// </summary>
        /// <param name="message">The message that we want to create the lock on.</param>
        internal abstract Task Lock<T>(T message) where T : class;

        protected abstract void Dispose(bool disposing);
    }

    /// <summary>
    /// Represents the type of transport used within Azure Service Bus.
    /// </summary>
    internal enum MessagingTransport
    {
        Queue,
        Topic
    }
}


text:
var passportLocal = require('passport-local');
var bCrypt = require('bcrypt-nodejs');
/*NOTE: passport middle-ware is case sensitive on username and password fields
  and it requires the form passed to it to be all lowercase else it kicks
  the request to the default redirect page provided before even calling the
  strategy defined for that route*/

var fs = require('fs');
var path = require('path');
var ObjectId = require('mongodb').ObjectId;

module.exports = function(passport  , dbResource){
	//models
	var Users = dbResource.model('Users');

	var isValidPassword = function(user , password){
		 return bCrypt.compareSync(password , user.auth.password);
	};

	var createHash = function(password){
		return bCrypt.hashSync(password , null , null);
	};

	//Tells passport which field uniquely identifies a user
	passport.serializeUser(function(user , done){
		return done(null , user._id);
	});

  //Tells passport how to get users full info
	passport.deserializeUser(function(_id , done){
			//query database or cache for actual data
			Users.find({'_id' : ObjectId(_id)}).toArray(function(err , result){
				if(err){
					return done(err ,false);
				}
				else if(!result[0]){
					return done(null ,false);
				}
				else {
				    return done(null , result[0]);
				}
			});
	});

	//Strategy to use when logging in existing users
	passport.use('login' , new passportLocal.Strategy({passReqToCallback: true} , function(req ,username , password , done){
		//
		if(req.isAuthenticated()){
			  console.log('user already logged in');
				return done(null , req.user);
		}
		else{
			Users.find({'auth.username':username}).toArray(function(err , result){
						if(err){
							return done(null , false);
						}
						else if(!result[0]){
							 return done(null , false);
						}
						else if(!isValidPassword(result[0] , password)){
							return done(null , false);
						}
						else{
							return done(null , result[0]);
						}
				});
		}

	}));

	//Strategy to use when signing up a new user
	passport.use('signup' , new passportLocal.Strategy({passReqToCallback: true},function(req , username , password , done){
		//sign in users in with newly created document

		var newUser = req.body;

		Users.find({'username':username}).toArray(function(err, result){
			if(err){
				return done(err);
			}
			//check if username already exists
			if(result[0]){
				return done(null , false);
			} else {
		    createUser();
			}

		});

		//Add the user in the users collections
		function createUser() {
			Users.insertOne(newUser , function(err,result){
				if(err){
					return done(err);
				} else {
					return done(null , result.ops[0]);
				}
			});
		}

	}));

  //Return the passport object with the local-strategy initialized
  return passport;
};


text:
package com.codecommit.antixml

import org.specs2.mutable._
import org.specs2.ScalaCheck
import org.specs2.matcher.Parameters
import org.scalacheck.{Arbitrary, Prop}
import Prop._
import org.specs2.matcher.ScalaCheckMatchers._

class ZipperPathSpecs extends Specification with ScalaCheck {
  import math._

  //Shaemelessly stolen from VectorCaseSpecs

  val emptyPath = ZipperPath()

  "ZipperPath companion" should {

    "build using apply" in check { (items: List[Int]) =>
      val zp = ZipperPath(items:_*)
      items mustEqual List(zp:_*)
    }

    "build from a ZipperPath using fromSeq" in check { (items: ZipperPath) =>
      val zp = ZipperPath.fromSeq(items)
      List(items:_*) mustEqual List(zp:_*)
    }

    "build from an IndexedSeq using fromSeq" in check { (items: Vector[Int]) =>
      val zp = ZipperPath.fromSeq(items)
      List(items:_*) mustEqual List(zp:_*)
    }

    "build from a LinearSeq using fromSeq" in check { (items: List[Int]) =>
      val zp = ZipperPath.fromSeq(items)
      List(items:_*) mustEqual List(zp:_*)
    }

    "build from a ZipperPath using reversed" in check { (items: ZipperPath) =>
      val zp = ZipperPath.reversed(items)
      List(items:_*).reverse mustEqual List(zp:_*)
    }

    "build from an IndexedSeq using reversed" in check { (items: Vector[Int]) =>
      val zp = ZipperPath.reversed(items)
      List(items:_*).reverse mustEqual List(zp:_*)
    }

    "build from a LinearSeq using reversed" in check { (items: List[Int]) =>
      val zp = ZipperPath.reversed(items)
      List(items:_*).reverse mustEqual List(zp:_*)
    }

    "should have an empty empty" in {
      ZipperPath.empty.length mustEqual 0
    }

    "should produce builders" in check { (items: List[Int]) =>
      val zp = (ZipperPath.newBuilder ++= items).result
      List(items:_*) mustEqual List(zp:_*)
    }

  }

  "ZipperPath" should {
    "store a single element" in {
      val v2 = emptyPath :+ 42
      v2(0) mustEqual 42
    }

    "implement +:" in check { (zp: ZipperPath, i: Int) =>
      val zp2 = i +: zp
      zp2.length mustEqual (zp.length + 1)
      zp2.head mustEqual i
      zp.zipWithIndex forall {
        case (x, i) => zp2(i + 1) mustEqual x
      }
    }

    "implement :+" in check { (zp: ZipperPath, i: Int) =>
      val zp2 = zp :+ i
      zp2.length mustEqual (zp.length + 1)
      zp2.last mustEqual i
      zp.zipWithIndex forall {
        case (x, i) => zp2(i) mustEqual x
      }
    }

    "implement ++" in check { (zp1: ZipperPath, zp2: ZipperPath) =>
      val result1 = zp1 ++ zp2
      val result2 = zp2 ++ zp1

      result1.length mustEqual (zp1.length + zp2.length)
      result1.length mustEqual result2.length

      zp1.zipWithIndex forall {
        case (x, i) => {
          result1(i) mustEqual x
          result2(i + zp2.length) mustEqual x
        }
      }

      zp2.zipWithIndex forall {
        case (x, i) => {
          result2(i) mustEqual x
          result1(i + zp1.length) mustEqual x
        }
      }
    }

    "implement length" in check { list: List[Int] =>
      val zp = list.foldLeft(ZipperPath()) { _ :+ _ }
      zp.length === list.length
    }

    "replace single element" in check { (zp: ZipperPath, i: Int) =>
      (zp.nonEmpty && i > Int.MinValue) ==> {
        val idx = abs(i) % zp.length
        val newVectorCase = zp.updated(idx, "test").updated(idx, "newTest")
        newVectorCase(idx) mustEqual "newTest"
      }
    }
    "fail on apply out-of-bounds" in check { (zp: ZipperPath, i: Int) =>
      !((0 until zp.length) contains i) ==> { zp(i) must throwA[Throwable] }
    }

    "store multiple elements in order" in check { list: List[Int] =>
      val newVectorCase = list.foldLeft(emptyPath) { _ :+ _ }
      val res = for (i <- 0 until list.length) yield newVectorCase(i) == list(i)

      res must not contain (false)
    }

    "store lots of elements" in {
      val LENGTH = 100000
      val emptyPath = (0 until LENGTH).foldLeft(ZipperPath()) { _ :+ _ }

      emptyPath.length mustEqual LENGTH
      ((i:Int) => emptyPath(i) mustEqual i).forall(0 until LENGTH)
    }

    "maintain both old and new versions after conj" in check { zp: ZipperPath =>
      val zp2 = zp :+ 42
      for (i <- 0 until zp.length) {
        zp2(i) aka ("Index " + i + " in derivative") mustEqual zp(i) aka ("Index " + i + " in origin")
      }
      zp2.last mustEqual 42
    }.set(maxSize -> 3000, minTestsOk -> 1000, workers -> numProcessors)

    "maintain both old and new versions after update" in check { (zp: ZipperPath, i: Int) =>
      (!zp.isEmpty && i > Int.MinValue) ==> {
        val idx = abs(i) % zp.length
        val zp2 = zp.updated(idx, 42)
        for (i <- 0 until zp.length if i != idx) {
          zp2(i) aka ("Index " + i + " in derivative") mustEqual zp(i) aka ("Index " + i + " in origin")
        }
        zp2(idx) mustEqual 42
      }
    }

    "implement drop matching Vector semantics (in general case)" in check { (zp: ZipperPath, len: Int) =>
      toVector(zp drop len) mustEqual (toVector(zp) drop len)
    }

    "implement dropRight matching Vector semantics" in check { (zp: ZipperPath, len: Int) =>
      //IndexedSeqOptimized doesn't match Vector for negative lengths
      val l2 = max(0,len)
      toVector(zp dropRight l2) mustEqual (toVector(zp) dropRight l2)
    }

    "implement filter" in check { (zp: ZipperPath, f: (Int)=>Boolean) =>
      val filtered = zp filter f

      var back = filtered forall f
      for (e <- zp) {
        if (f(e)) {
          back &&= filtered.contains(e)
        }
      }
      back
    }

    "implement foldLeft" in check { list: List[Int] =>
      val zp = list.foldLeft(ZipperPath()) { _ :+ _ }
      zp.foldLeft(0) { _ + _ } === list.foldLeft(0) { _ + _ }
    }

    "implement foreach" in check { zp: ZipperPath =>
      val b = Vector.newBuilder[Int]
      for(i <- zp)
        b += i
      val v = b.result()
      v mustEqual zp
    }

    "implement forall" in check { (zp: ZipperPath, f: (Int)=>Boolean) =>
      val bool = zp forall f

      var back = true
      for (e <- zp) {
        back &&= f(e)
      }

      (back && bool) || (!back && !bool)
    }

    "implement flatMap" in check { (zp: ZipperPath, f: (Int)=>ZipperPath) =>
      val mapped = zp flatMap f

      var back = true

      var i = 0
      var n = 0

      while (i < zp.length) {
        val res = f(zp(i))

        var inner = 0
        while (inner < res.length) {
          back &&= mapped(n) == res(inner)

          inner += 1
          n += 1
        }

        i += 1
      }

      back
    }

    "implement init matching Vector semantics" in check { zp: ZipperPath =>
      !zp.isEmpty ==> {
        toVector(zp.init) mustEqual toVector(zp).init
      }
    }

    "implement map" in check { (zp: ZipperPath, f: (Int)=>Int) =>
      val mapped = zp map f

      var back = zp.length == mapped.length
      for (i <- 0 until zp.length) {
        back &&= mapped(i) == f(zp(i))
      }
      back
    }

    "implement reverse" in check { v: ZipperPath =>
      val reversed = v.reverse

      var back = v.length == reversed.length
      for (i <- 0 until v.length) {
        back &&= reversed(i) == v(v.length - i - 1)
      }
      back
    }

    "append to reverse" in check { (v: ZipperPath, n: Int) =>
      val rev = v.reverse
      val add = rev :+ n

      var back = add.length == rev.length + 1
      for (i <- 0 until rev.length) {
        back &&= add(i) == rev(i)
      }
      back && add(rev.length) === n
    }

    "map on reverse" in check { (v: ZipperPath, f: (Int)=>Int) =>
      val rev = v.reverse
      val mapped = rev map f

      var back = mapped.length == rev.length
      for (i <- 0 until rev.length) {
        back &&= mapped(i) == f(rev(i))
      }
      back
    }

    /* "implement slice matching Vector semantics" in check { (zp: ZipperPath, from: Int, until: Int) =>
      // skip("Vector slice semantics are inconsistent with Traversable")
      zp.slice(from, until).toVector mustEqual zp.toVector.slice(from, until)
    } */

    "implement splitAt matching Vector semantics" in check { (zp: ZipperPath, i: Int) =>
      val (left, right) = zp splitAt i
      val (expectLeft, expectRight) = toVector(zp) splitAt i

      toVector(left) mustEqual expectLeft
      toVector(right) mustEqual expectRight
    }

    "implement tail matching Vector semantics" in check { zp: ZipperPath =>
      !zp.isEmpty ==> {
        toVector(zp.tail) mustEqual toVector(zp).tail
      }
    }

    "implement take matching Vector semantics" in check { (zp: ZipperPath, len: Int) =>
      toVector(zp take len) mustEqual (toVector(zp) take len)
    }

    "implement takeRight matching Vector semantics" in check { (zp: ZipperPath, len: Int) =>
      //scala.collection.IndexedSeqOptimized differs from Vector on negative lengths
      val l2 = max(0,len)
      toVector(zp takeRight l2) mustEqual (toVector(zp) takeRight l2)
    }

    "implement zip" in check { (first: ZipperPath, second: ZipperPath) =>
      val zip = first zip second

      var back = zip.length == min(first.length, second.length)
      for (i <- 0 until zip.length) {
        var (left, right) = zip(i)
        back &&= (left == first(i) && right == second(i))
      }
      back
    }

    "implement zipWithIndex" in check { zp: ZipperPath =>
      val zip = zp.zipWithIndex

      var back = zip.length == zp.length
      for (i <- 0 until zip.length) {
        val (elem, index) = zip(i)
        back &&= (index == i && elem == zp(i))
      }
      back
    }

    "implement equals" >> {
      "1." in check { list: List[Int] =>
        val zpA = list.foldLeft(ZipperPath()) { _ :+ _ }
        val zpB = list.foldLeft(ZipperPath()) { _ :+ _ }
        zpA === zpB
      }
      "2." in check { (zpA: ZipperPath, zpB: ZipperPath) =>
        zpA.length != zpB.length ==> (zpA != zpB)
      }
      "3." in check { (listA: List[Int], listB: List[Int]) =>
        val zpA = listA.foldLeft(ZipperPath()) { _ :+ _ }
        val zpB = listB.foldLeft(ZipperPath()) { _ :+ _ }

        listA != listB ==> (zpA != zpB)
      }
      "4." in check { (zp: ZipperPath, data: Int) => zp !== data }
    }

    "implement hashCode" in check { list: List[Int] =>
      val zpA = list.foldLeft(ZipperPath()) { _ :+ _ }
      val zpB = list.foldLeft(ZipperPath()) { _ :+ _ }
      zpA.hashCode === zpB.hashCode
    }
  }

  implicit def arbitraryZipperPath: Arbitrary[ZipperPath] = {
    Arbitrary(for {
      data <- Arbitrary.arbitrary[List[Int]]
    } yield ZipperPath.fromSeq(data))
  }
  implicit def arbitraryVector[A](implicit arb: Arbitrary[A]): Arbitrary[Vector[A]] = {
    Arbitrary(for {
      data <- Arbitrary.arbitrary[List[A]]
    } yield Vector(data:_*))
  }

  def toVector(zp: ZipperPath): Vector[Int] = {
    (Vector[Int]() /: (0 until zp.length)) { (v,i) =>
      v :+ zp(i)
    }
  }

  val numProcessors = Runtime.getRuntime.availableProcessors
  implicit val params: Parameters = set(workers -> numProcessors)
}


text:
package io.cdap.plugin.sfmc.source.util;

import com.custom.fuelsdk.ETNotSentEvent;
import com.exacttarget.fuelsdk.ETBounceEvent;
import com.exacttarget.fuelsdk.ETDataExtensionRow;
import com.exacttarget.fuelsdk.ETEmail;
import com.exacttarget.fuelsdk.ETList;
import com.exacttarget.fuelsdk.ETOpenEvent;
import com.exacttarget.fuelsdk.ETSentEvent;
import com.exacttarget.fuelsdk.ETSoapObject;
import com.exacttarget.fuelsdk.ETUnsubEvent;

import java.util.Arrays;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * Indicates the object for which data to be fetched from MarketingCloud.
 */
public enum SourceObject {

  /**
   * This indicates data to be fetched from Data Extension.
   */
  DATA_EXTENSION("Data Extension", "dataextension", ETDataExtensionRow.class),

  /**
   * This indicates data to be fetched from Email.
   */
  EMAIL("Email", "email", ETEmail.class),

  /**
   * This indicates data to be fetched from Mailing List.
   */
  MAILING_LIST("Mailing List", "mailinglist", ETList.class),

  /**
   * This indicates data to be fetched from Tracking Bounce Events.
   */
  TRACKING_BOUNCE_EVENT("Bounce Event", "bounce", ETBounceEvent.class),

  /**
   * This indicates data to be fetched from Tracking Open Events.
   */
  TRACKING_OPEN_EVENT("Open Event", "open", ETOpenEvent.class),

  /**
   * This indicates data to be fetched from Tracking UnSub Events.
   */
  TRACKING_UNSUB_EVENT("Unsub Event", "unsub", ETUnsubEvent.class),

  /**
   * This indicates data to be fetched from Tracking Sent Events.
   */
  TRACKING_SENT_EVENT("Sent Event", "sent", ETSentEvent.class),

  /**
   * This indicates data to be fetched from Tracking Notsent Events.
   */
  TRACKING_NOTSENT_EVENT("Notsent Event", "notsent", ETNotSentEvent.class);

  private final String value;
  private final String tableName;
  private final Class<? extends ETSoapObject> classRef;
  private String filter = "";

  SourceObject(String value, String tableName, Class<? extends ETSoapObject> classRef) {
    this.value = value;
    this.tableName = tableName;
    this.classRef = classRef;
  }

  /**
   * Converts object string value into {@link SourceObject} enum.
   *
   * @param stringValue object string value
   * @return source object in optional container
   */
  public static Optional<SourceObject> fromValue(String stringValue) {
    return Stream.of(values())
      .filter(keyType -> keyType.value.equalsIgnoreCase(stringValue))
      .findAny();
  }

  public static String getSupportedObjects() {
    return Arrays.stream(SourceObject.values()).map(SourceObject::getValue)
      .collect(Collectors.joining(", "));
  }

  public String getValue() {
    return value;
  }

  public String getTableName() {
    return tableName;
  }

  public Class<? extends ETSoapObject> getClassRef() {
    return classRef;
  }

  public String getFilter() {
    return filter;
  }

  public void setFilter(String filter) {
    this.filter = filter;
  }

}


text:
'use babel';

import { CompositeDisposable } from 'atom';
import { execSync } from 'child_process';
import os from 'os';
import path from 'path';
import clangFormatExecutables from 'clang-format-binaries';

export default class ClangFormat {
  constructor() {
    this.subscriptions = new CompositeDisposable();
    this.subscriptions.add(
      atom.workspace.observeTextEditors(editor => this.handleBufferEvents(editor)),
    );

    this.subscriptions.add(atom.commands.add('atom-workspace', 'clang-format:format', () => {
      const editor = atom.workspace.getActiveTextEditor();
      if (editor) {
        this.format(editor);
      }
    }));
  }

  destroy = () => {
    this.subscriptions.dispose();
  }

  handleBufferEvents = (editor) => {
    const buffer = editor.getBuffer();
    const bufferSavedSubscription = buffer.onWillSave(() => {
      const scope = editor.getRootScopeDescriptor().scopes[0];
      if (this.shouldFormatOnSaveForScope(scope)) {
        buffer.transact(() => this.format(editor));
      }
    });

    const editorDestroyedSubscription = editor.onDidDestroy(() => {
      bufferSavedSubscription.dispose();
      editorDestroyedSubscription.dispose();

      this.subscriptions.remove(bufferSavedSubscription);
      this.subscriptions.remove(editorDestroyedSubscription);
    });

    this.subscriptions.add(bufferSavedSubscription);
    this.subscriptions.add(editorDestroyedSubscription);
  }

  format = (editor) => {
    const buffer = editor.getBuffer();

    let exe = atom.config.get('clang-format.executable');
    if (!exe) {
      const exePackageLocation = path.dirname(clangFormatExecutables.location);
      if (os.platform() === 'win32') {
        exe = path.join(exePackageLocation, '/bin/win32/clang-format.exe');
      } else {
        exe = path.join(exePackageLocation, `/bin/${os.platform()}_${os.arch()}/clang-format`);
      }
    }

    const options = {
      style: atom.config.get('clang-format.style'),
      cursor: this.getCurrentCursorPosition(editor).toString(),
      'fallback-style': atom.config.get('clang-format.fallbackStyle'),
    };

    // Format only selection
    if (this.textSelected(editor)) {
      options.lines = this.getTargetLineNums(editor);
    }

    // Pass file path to clang-format so it can look for .clang-format files
    const filePath = editor.getPath();
    if (filePath) {
      options['assume-filename'] = filePath;
    }

    // Call clang-format synchronously to ensure that save waits for us
    // Don't catch errors to make them visible to users via atom's UI
    // We need to explicitly ignore stderr since there is no parent stderr on
    // windows and node.js will try to write to it - whether it's there or not
    const args = Object.keys(options).reduce((memo, optionKey) => {
      const optionValue = options[optionKey];
      if (optionValue) {
        return `${memo}-${optionKey}="${optionValue}" `;
      }
      return memo;
    }, '');

    const execOptions = { input: editor.getText() };

    if (filePath) {
      execOptions.cwd = path.dirname(filePath);
    }

    try {
      const stdout = execSync(`"${exe}" ${args}`, execOptions).toString();
      // Update buffer with formatted text. setTextViaDiff minimizes re-rendering
      buffer.setTextViaDiff(this.getReturnedFormattedText(stdout));
      // Restore cursor position
      const returnedCursorPos = this.getReturnedCursorPosition(stdout);
      const convertedCursorPos = buffer.positionForCharacterIndex(returnedCursorPos);
      editor.setCursorBufferPosition(convertedCursorPos);
    } catch (error) {
      if (error.message.indexOf('Command failed:') < 0) {
        throw error;
      } else {
        atom.notifications.addError('Clang Format Command Failed', {
          dismissable: true,
          detail: `clang-format failed with the below error. Consider reporting this by creating an issue here: https://github.com/LiquidHelium/atom-clang-format/issues.\nError message: "${error.stderr.toString()}".\nWhen running: "${exe} ${args}".\nStdout was: "${error.stdout.toString()}"`,
        });
      }
    }
  }

  shouldFormatOnSaveForScope = (scope) => {
    if (atom.config.get('clang-format.formatCPlusPlusOnSave') && ['source.c++', 'source.cpp'].includes(scope)) {
      return true;
    }
    if (atom.config.get('clang-format.formatCOnSave') && ['source.c'].includes(scope)) {
      return true;
    }
    if (atom.config.get('clang-format.formatObjectiveCOnSave') && ['source.objc', 'source.objcpp'].includes(scope)) {
      return true;
    }
    if (atom.config.get('clang-format.formatJavascriptOnSave') && ['source.js'].includes(scope)) {
      return true;
    }
    if (atom.config.get('clang-format.formatTypescriptOnSave') && ['source.ts'].includes(scope)) {
      return true;
    }
    if (atom.config.get('clang-format.formatJavaOnSave') && ['source.java'].includes(scope)) {
      return true;
    }
    return false;
  }

  getEndJSONPosition = (text) => {
    for (let i = 0; i < text.length; i += 1) {
      if ((text[i] === '\n') || (text[i] === '\r')) {
        return i + 1;
      }
    }

    return -1;
  }

  getReturnedCursorPosition = (stdout) => {
    if (!stdout) { return 0; }
    const parsed = JSON.parse(stdout.slice(0, this.getEndJSONPosition(stdout)));
    return parsed.Cursor;
  }

  getReturnedFormattedText = stdout => stdout.slice(this.getEndJSONPosition(stdout));

  getCurrentCursorPosition = (editor) => {
    const cursorPosition = editor.getCursorBufferPosition();
    const text = editor.getTextInBufferRange([[0, 0], cursorPosition]);
    return text.length;
  }

  getCursorLineNumber = (editor) => {
    const cursorPosition = editor.getCursorBufferPosition();
    // +1 to get 1-base line number.
    return cursorPosition.toArray()[0] + 1;
  }

  textSelected = (editor) => {
    const range = editor.getSelectedBufferRange();
    return !range.isEmpty();
  }

  getSelectedLineNums = (editor) => {
    const range = editor.getSelectedBufferRange();
    const rows = range.getRows();
    // + 1 to get 1-base line number.
    const startingRow = rows[0] + 1;
    // If 2 lines are selected, the diff between |starting_row| is 1, so -1.
    const endingRow = (startingRow + range.getRowCount()) - 1;
    return [startingRow, endingRow];
  }

  // Returns line numbers recognizable by clang-format, i.e. '<begin>:<end>'.
  getTargetLineNums = (editor) => {
    if (this.textSelected(editor)) {
      const lineNums = this.getSelectedLineNums(editor);
      return `${lineNums[0]}:${lineNums[1]}`;
    }

    const lineNum = this.getCursorLineNumber(editor);
    return `${lineNum}:${lineNum}`;
  }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;

using Xunit;

using JohnChess;
using JohnChess.Moves;
using JohnChess.Pieces;

namespace JohnChess.Tests.Pieces
{
    public class QueenTests
    {
        private readonly Position primaryPos = new Position(File.D, Rank._4);
        private readonly Position friendlyPawnPos = new Position(File.A, Rank._7);
        private readonly Position friendlyKnightPos = new Position(File.D, Rank._6);
        private readonly Position enemyQueenPos = new Position(File.E, Rank._3);
        private readonly Position enemyPawnPos = new Position(File.G, Rank._4);

        private Board CreateBoardWithWhitePieceAt(Position position, PieceType pieceType)
        {
            var board = Board.NewEmptyBoard();
            board.AddPiece(new PieceBuilder(pieceType)
                .As(PieceColor.White)
                .At(position)
                .Create());

            return board;
        }

        [Fact]
        public void HasCorrectMovesWithNoObstacles()
        {
            var d4 = new Position(File.D, Rank._4);

            var rookD4Board = CreateBoardWithWhitePieceAt(d4, PieceType.Rook);
            var bishopD4Board = CreateBoardWithWhitePieceAt(d4, PieceType.Bishop);
            var queenD4Board = CreateBoardWithWhitePieceAt(d4, PieceType.Queen);

            var rookPositions = (from m in rookD4Board.GetPossibleMoves(PieceColor.White)
                             where m.Type == MoveType.NormalPiece
                             select m.NormalPieceMove.NewPosition).ToList();

            var bishopPositions = (from m in bishopD4Board.GetPossibleMoves(PieceColor.White)
                                 where m.Type == MoveType.NormalPiece
                                 select m.NormalPieceMove.NewPosition).ToList();

            var queenPositions = (from m in queenD4Board.GetPossibleMoves(PieceColor.White)
                                 where m.Type == MoveType.NormalPiece
                                 select m.NormalPieceMove.NewPosition).ToList();

            var rookAndBishopPositions = rookPositions.Concat(bishopPositions).ToList();
            rookAndBishopPositions = (from m in rookAndBishopPositions orderby m.ToString() select m).ToList();
            queenPositions = (from m in queenPositions orderby m.ToString() select m).ToList();
            Assert.Equal(rookAndBishopPositions, queenPositions);
            Assert.Equal(queenPositions.Count, 27);
        }

        [Fact]
        public void HasCorrectMovesWithObstacles()
        {
            var rookBoard = ConstructComplexBoardWithPrimaryPiece(PieceType.Rook);
            var bishopBoard = ConstructComplexBoardWithPrimaryPiece(PieceType.Bishop);
            var queenBoard = ConstructComplexBoardWithPrimaryPiece(PieceType.Queen);

            var rookMoves = (from m in rookBoard.GetPossibleMoves(PieceColor.White)
                                 where m.Type == MoveType.NormalPiece &&
                                 m.NormalPieceMove.Piece.Type == PieceType.Rook
                                 select m.NormalPieceMove).ToList();
            var rookPositions = (from m in rookMoves select m.NewPosition).ToList();
            var rookTakesPositions = (from m in rookMoves where m.PieceCaptured select m.NewPosition);

            var bishopMoves = (from m in bishopBoard.GetPossibleMoves(PieceColor.White)
                                   where m.Type == MoveType.NormalPiece &&
                                 m.NormalPieceMove.Piece.Type == PieceType.Bishop
                               select m.NormalPieceMove).ToList();
            var bishopPositions = (from m in bishopMoves select m.NewPosition).ToList();
            var bishopTakesPositions = (from m in bishopMoves where m.PieceCaptured select m.NewPosition);

            var queenMoves = (from m in queenBoard.GetPossibleMoves(PieceColor.White)
                                  where m.Type == MoveType.NormalPiece &&
                                 m.NormalPieceMove.Piece.Type == PieceType.Queen
                              select m.NormalPieceMove).ToList();
            var queenPositions = (from m in queenMoves select m.NewPosition).ToList();
            var queenTakesPositions = (from m in queenMoves where m.PieceCaptured select m.NewPosition);

            var rookAndBishopPositions = rookPositions.Concat(bishopPositions).ToList();
            rookAndBishopPositions = (from m in rookAndBishopPositions orderby m.ToString() select m).ToList();
            queenPositions = (from m in queenPositions orderby m.ToString() select m).ToList();
            Assert.Equal(rookAndBishopPositions, queenPositions);
            Assert.Equal(queenPositions.Count, 20);

            var rookAndBishopTakesPositions = rookTakesPositions.Concat(bishopTakesPositions).ToList();
            rookAndBishopTakesPositions = (from m in rookAndBishopTakesPositions orderby m.ToString() select m).ToList();
            queenTakesPositions = (from m in queenTakesPositions orderby m.ToString() select m).ToList();
            Assert.Equal(rookAndBishopTakesPositions, queenTakesPositions);
            Assert.Equal(queenTakesPositions.Count(), 2);
        }

        private Board ConstructComplexBoardWithPrimaryPiece(PieceType pieceType)
        {
            var boardWithPrimaryPiece = CreateBoardWithWhitePieceAt(primaryPos, pieceType);
            boardWithPrimaryPiece.AddPiece(new PieceBuilder(PieceType.Pawn)
                .As(PieceColor.White)
                .At(friendlyPawnPos)
                .Create());
            boardWithPrimaryPiece.AddPiece(new PieceBuilder(PieceType.Knight)
                .As(PieceColor.White)
                .At(friendlyKnightPos)
                .Create());
            boardWithPrimaryPiece.AddPiece(new PieceBuilder(PieceType.Queen)
                .As(PieceColor.Black)
                .At(enemyQueenPos)
                .Create());
            boardWithPrimaryPiece.AddPiece(new PieceBuilder(PieceType.Pawn)
                .As(PieceColor.Black)
                .At(enemyPawnPos)
                .Create());
            return boardWithPrimaryPiece;
        }
    }
}


text:
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>W28683_text</title>
        <link rel="stylesheet" type="text/css" href="style.css" />

                «

    <p class="styleSans183.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Existing Wells Within Spacing Unit
Continental Resources, Inc. has identified the following wells which currently exist in the spacing unit consisting of: Sec 1, 12, 13 & 24, T159N, R96W Williams County, ND

2140 FSL m5- 810 FNL 660 PH 225 FSL Horizontal
CRI has determined that the identified existing wells in the spacing unit specified above are not within 500' of the proposed Leonard 2-12H wellbore and do not pose any collision threats during drilling or completion operations.