text:
/**
 *
 */
package nz.co.senanque.vaadin7demo;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.MessageSource;
import org.springframework.context.MessageSourceAware;
import org.springframework.context.support.MessageSourceAccessor;

import com.vaadin.navigator.View;
import com.vaadin.navigator.ViewChangeListener.ViewChangeEvent;
import com.vaadin.spring.annotation.SpringView;
import com.vaadin.ui.Label;
import com.vaadin.ui.VerticalLayout;

/**
 * @author Roger Parkinson
 *
 */
@SpringView(name = ViewScopedView.VIEW_NAME)
public class ViewScopedView extends VerticalLayout implements View,MessageSourceAware {
    public static final String VIEW_NAME = "view";
    @Value("${nz.co.senanque.vaadin7demo.ViewScopedView.identifier:not-set}")
    private transient String m_identifier;
    private transient MessageSource m_messageSource;

    @PostConstruct
    void init() {
    	MessageSourceAccessor messageSourceAccessor = new MessageSourceAccessor(m_messageSource);
        setMargin(true);
        setSpacing(true);
        addComponent(new Label("This is a view scoped view"));
        addComponent(new Label(m_identifier));
        addComponent(new Label(messageSourceAccessor.getMessage("nz.co.senanque.vaadin7demo.ViewScopedView.identifier2")));
    }

    public void enter(ViewChangeEvent event) {
        // the view is constructed in the init() method()
    	//permissionFactory.getCurrentPermissions();

    }

	@Override
	public void setMessageSource(MessageSource messageSource) {
		m_messageSource = messageSource;

	}
}


text:
<?php

namespace TMSolution\SmsBundle\Service;

use Symfony\Component\DependencyInjection\ContainerInterface;

class Gate2n
{

    /**
     *
     * @type ContainerInterface
     */
    protected $container;
    protected $gates2n;

    /**
     *
     * @param ContainerInterface $container
     */
    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
    }

    protected function getContainer()
    {
        return $this->container;
    }

    protected function preparePDU($phone, $content)
    {
        $pduGenerator = $this->getContainer()->get('pdu.generator');
        $pdu = $pduGenerator->generatePDU($phone, $content);
        return $pdu;
    }

    protected function prepareChecksum($pdu)
    {
        $checksum='';
        return $checksum;
    }

    protected function getModule($gateNumber, $moduleNumber)
    {

        return '00';
    }

    protected function prepareSendCommand($phone, $content)
    {
        $pduObject = $this->preparePDU($phone, $content);
        /* 3 */
        $pdu = $pduObject['pdu'];
        /* 2 */
        $pduLength = $pduObject['cmgslen'];
        /* 1 */
        $module = $this->getModule(1, 1);
        /* 4 */
        $checksum = $this->prepareChecksum($pdu);

        $command = 'AT^SM=' . $module . ',' . $pduLength . ',' . $pdu . ',' . $checksum;
        return $command;
    }

    public function sendMessage($phone, $content)
    {

        $atCommand = $this->prepareSendCommand($phone, $content);

        $this->gates2n = $this->getContainer()->getParameter('sms.gates2n');

        dump( $this->gates2n);
        /*
         * SG login: Admin
          Password: **
          OK
          AT!G=A6
          OK
          AT^SM=00,33,001100098197612044F30000FF16D4F29CFEBEE741F3F61C447E83EEF9799EBD4E03,9B
         * smsout: 0,2,00
          W przypadku błędu wysyłki, brama zwróci komunikat smserr.
         */
    }

}

redpajama_set_name: RedPajamaGithub


text:
' Copyright (c) Microsoft Corporation. All rights reserved.

Public Sub LongTask(ByVal Duration As Single, _
                     ByVal MinimumInterval As Single)
   Dim Threshold As Single
   Dim Start As Single
   Dim blnCancel As Boolean

   ' The Timer property of the DateAndTime object returns the seconds
   ' and milliseconds that have passed since midnight.
   Start = CSng(Timer)
   Threshold = MinimumInterval

   Do While CSng(Timer)< (Start + Duration)
       ' In a real application, some unit of work would
       ' be done here each time through the loop.
       If CSng(Timer)> (Start + Threshold) Then
              RaiseEvent PercentDone( _
              Threshold / Duration, blnCancel)
              ' Check to see if the operation was canceled.
              If blnCancel Then Exit Sub
              Threshold = Threshold + MinimumInterval
       End If
     Loop
End Sub


text:
```
npm install easyflux --save
```

```
bower install easyflux --save
```

## A bit of intro
I'm well aware that at this point, the interwebs is full of solutions, for every particular issue, there is. Lately, React from Facebook emerged, and it brought a full spectrum of issues.
First there's Flux. Hard to get, use and start going. Then there was Reflux, a nice clean way of using Flux principles. Still, in my mind, something was missing: easy to use events.

I don't want to gave in an use some sort of frontend API to simply store data, and respond to changes(Flux) I need more. I need to be able to couple/decouple the events based on my needs.

Enter Easyflux.

## What is this?
Basically, creates buckets of events, that you can use. I've seen something similar in Reflux, but not powerful enough.

```javascript

    var globalEvents = Easyflux([
        'resetData',
        'login',
        'logout'
    ]);

    // Later in code
    // Listening for login
    globalEvents.login.listen(callbackFunction, context);

    // Triggering the login
    globalEvents.login.trigger(data);
```

Now, apply this to React.

## React usage
Maybe the above syntax, did not convince you, hopefully this will.

```javascript

    // Our dull, isolated component
    var MyComponent = React.createClass({

        events: Easyflux([
            'change'
        ]),

        getInitialState: function() {
            return {
                data: 'Initial data'
            }
        },

        componentDidMount: function() {

            // On change event, change the message
            this.events.change.listen(function(newData) {
                this.setState({
                    data: newData
                });
            }, this);
        },

        render: function() {
            return <span className="custom-text">{this.state.data}</span>
        }

    });

    [...]

    // Later in our App
    var App = React.createClass({

        componentDidMount: function() {

            // Change the text in our isolated component
            this.refs.statusText.events.change.trigger('App has loaded');
        },

        render: function() {
            return <MyComponent ref="statusText"/>
        }

    });
```

That line, though, it's a bit hard to write. Below, it's using the `Easyflux.Mixin`

```javascript

    // Our dull, isolated component
    var MyComponent = React.createClass({

        mixins: [Easyflux.Mixin],

        events: Easyflux([
            'change'
        ]),

        getInitialState: function() {
            return {
                data: 'Initial data'
            }
        },

        componentDidMount: function() {

            // On change event, change the message
            this.listenTo('change', function(newData) {
                this.setState({
                    data: newData
                });
            }, this);
        },

        render: function() {
            return <span className="custom-text">{this.state.data}</span>
        }

    });

    [...]

    // Later in our App
    var App = React.createClass({

        componentDidMount: function() {

            // Exactly, Backbone-style method prints
            this.refs.statusText.trigger('change', 'App has loaded');
        },

        render: function() {
            return <MyComponent ref="statusText"/>
        }

    });
```

## Proper scoping the events
At some point you'll end up having difficulties between listening to children events, that are scoped to their own namespace and context. Take a look at the demo.
You can pass to children an `events` object, with `'eventName': this._onEventName` defined keys. This will be triggered whenever the internal event is triggered inside
that children. Pretty useful stuff!

```javascript

    // JSX
    render: function() {
        return <MySuperReusableComponent events={{ 'change': this._onChangeEvent, 'doesSomething': this._onDoesSomething }} />
    }

    // JS
    render: function() {
        return React.createElement(MySuperReusableComponent, {
            events: {
                'change': this._onChangeEvent,
                'doesSomething': this._onDoesSomething
            }
        });
    }
```

## Final thoughts
This should be treated as a simple solution for multi-directional events.

## Feedback
Given that this tries to introduce a simpler way, of listening to events, any feedback is gratefully received.


text:
/*
Hello
*/

class magicconstructor_2
{
	var p = "";

	function magicconstructor_2 (value : String, value2 : String)
	{
		p = value;
	}

	function magicconstructor_2 ()
	{
	}
}

static var once = true;

if (once)
{
	once =  false;
	var m = new magicconstructor_2("Hello", "Unused");
	print(m.p);
}


text:
package griffon.annotations.javafx;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 *
Annotates a property.

 *
This transformation provides a convenient way to register InvalidationListeners
 * on an observable bean by leveraging Groovy's closures and the Groovy cast operator.

 *

 *
The following code exemplifies what must be written by hand in order to register an InvalidationListener.
 *

 * import griffon.annotations.javafx.FXObservable
 * import javafx.beans.InvalidationListener
 *
 * class MyModel {
 *     @FXObservable String name
 *     @FXObservable String lastname
 *
 *     private def snoopAll = { ... }
 *
 *     MyModel() {
 *         nameProperty().addListener(snoopAll as InvalidationListener)
 *         lastnameProperty().addListener({
 *             controller.someAction(it)
 *         } as InvalidationListener)
 *     }
 * }
 *

 *

 *
Applying @InvalidationListener to the previous snippet results in the following code

 *

 * import griffon.annotations.javafx.FXObservable
 * import griffon.annotations.javafx.InvalidationListener
 *
 * class MyModel {
 *     @FXObservable
 *     @InvalidationListener(snoopAll)
 *     String name
 *
 *     @FXObservable
 *     @InvalidationListener({ controller.someAction(it)})
 *     String lastname
 *
 *     private def snoopAll = { ... }
 * }
 *

 *

 * Any closures found as the annotation's value will be either transformed
 * into inner classes that implement InvalidationListener (when the value
 * is a closure defined in place) or be casted as a proxy of InvalidationListener
 * (when the value is a property reference found in the same class).

 * List of closures are also supported.
 *
 * @author Andres Almiray
 */
@Retention(RetentionPolicy.SOURCE)
@Target({ElementType.FIELD})
public @interface InvalidationListener {
    String value();

    /**
     * If the {@code InvalidationListener} should be wrapped with a {@code WeakInvalidationListener} or not
     *
     * @since 2.4.0
     */
    boolean weak() default false;
}


text:
package com.google.cloud.dataflow.sdk.coders;

import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.instanceOf;
import static org.junit.Assert.assertThat;

import com.google.api.client.util.Preconditions;
import com.google.cloud.dataflow.sdk.values.TypeDescriptor;

import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

import java.io.Serializable;
import java.util.List;

/**
 * Tests of Coder defaults.
 */
@RunWith(JUnit4.class)
@SuppressWarnings("serial")
public class DefaultCoderTest {

  @Rule
  public ExpectedException thrown = ExpectedException.none();

  public CoderRegistry registry = new CoderRegistry();

  @Before
  public void registerStandardCoders() {
    registry.registerStandardCoders();
  }

  @DefaultCoder(AvroCoder.class)
  private static class AvroRecord {
  }

  private static class SerializableBase implements Serializable {
  }

  @DefaultCoder(SerializableCoder.class)
  private static class SerializableRecord extends SerializableBase {
  }

  @DefaultCoder(CustomCoder.class)
  private static class CustomRecord extends SerializableBase {
  }

  private static class Unknown {
  }

  private static class CustomCoder extends SerializableCoder<CustomRecord> {
    // Extending SerializableCoder isn't trivial, but it can be done.
    @SuppressWarnings("unchecked")
    public static <T extends Serializable> SerializableCoder<T> of(Class<T> recordType) {
       Preconditions.checkArgument(
           CustomRecord.class.isAssignableFrom(recordType));
       return (SerializableCoder<T>) new CustomCoder();
    }

    protected CustomCoder() {
      super(CustomRecord.class);
    }
  }

  @Test
  public void testDefaultCoderClasses() throws Exception {
    assertThat(registry.getDefaultCoder(AvroRecord.class), instanceOf(AvroCoder.class));
    assertThat(registry.getDefaultCoder(SerializableBase.class),
        instanceOf(SerializableCoder.class));
    assertThat(registry.getDefaultCoder(SerializableRecord.class),
        instanceOf(SerializableCoder.class));
    assertThat(registry.getDefaultCoder(CustomRecord.class), instanceOf(CustomCoder.class));
  }

  @Test
  public void testDefaultCoderInCollection() throws Exception {
    assertThat(registry.getDefaultCoder(new TypeDescriptor<List<AvroRecord>>(){}),
        instanceOf(ListCoder.class));
    assertThat(registry.getDefaultCoder(new TypeDescriptor<List<SerializableRecord>>(){}),
        equalTo((Coder<List<SerializableRecord>>)
            ListCoder.of(SerializableCoder.of(SerializableRecord.class))));
  }

  @Test
  public void testUnknown() throws Exception {
    thrown.expect(CannotProvideCoderException.class);
    registry.getDefaultCoder(Unknown.class);
  }
}


text:
module RailsStackview

  # Fetches from the stackview_call_numbers table with ActiveRecord
  #
  # * Assumes a windowing `search_type:loc_sort_order` in stackview, which
  #   sends query=[X TO Y] in params.
  #
  # * Additionally assumes we get an `origin_sort_key` in params,
  #   which will used as the "zero point" for stackview's query ranges.
  #   It must be an actual normalized sort_key -- if it does not exist in the DB,
  #   we'll just browse from that point in sort order though.
  #
  #   We use this origin_sortkey to try and avoid very deep offsets in our
  #   SQL, which get expensive, although if the user pages a LOT they can
  #   still get there. If this is not good enough, we'll have to contribute
  #   features to stackview to provide alternate windowing based on sortkeys
  #   alone.
  #
  #  Create a path to the StackviewDataController using 'lc' call_number_type,
  #  which uses this fetcher, specifying the origin_sort_key as a query param:
  #
  #     stackview_data_path("lc", :origin_sort_key => some_sort_key)
  class DbWindowFetcher

    def fetch(params)
      @origin_sort_key = params["origin_sort_key"]
      @sort_key_type   = params["sort_key_type"] || "lc"

      unless @origin_sort_key.present?
        raise ArgumentError, "`origin_sort_key` param required, specifying where to start the browse"
      end

      (first, last)  = RailsStackview.parse_query_range(params["query"])
      unless first < last
        raise ArgumentError, "beginning of range must be less than end: #{params["query"]}"
      end

      # Fetch the AR models, then turn em into hashes, which include all
      # columns in the db, excluding some we don't want.
      #
      # Plus we need to turn our single creator into an array, cause
      # that's what stackview wants.
      results = fetch_records(first, last).collect do |record|
        record.attributes.except('id').reject {|k, v| v.blank? }.
          merge("creator" => (record["creator"].present? ? [record['creator']] : record['creator']))
      end

      # Mark the thing at 0 index as origin:true, so it can be auto-selected
      # by browser.
      if (first..last).cover?(0)
        origin_index = [first.abs, results.length - 1].min
        results[origin_index]["is_origin_item"] = true
      end

      return results
    end

    # Returns ActiveRecord StackviewCallNumber objects.
    def fetch_records(first, last)
      if first >= 0 && last >= 0 # all positive
        positive_fetch(first, last)
      elsif first < 0 && last >= 0# cross zero-boundary
        # have to do half first and half last
        negative_fetch(first, -1) + positive_fetch(0, last)
      else # all negative
        negative_fetch(first, last)
      end
    end

    def positive_fetch(first, last)
      StackviewCallNumber.where("sort_key >= ?", @origin_sort_key).
        where(:sort_key_type => @sort_key_type).
        order("sort_key ASC").
        offset(first).limit(last - first + 1)
    end

    def negative_fetch(first, last)
      StackviewCallNumber.where("sort_key < ?", @origin_sort_key).
        where(:sort_key_type => @sort_key_type).
        order("sort_key DESC").
        offset(last.abs - 1).limit(last - first + 1).
        reverse
    end

  end
end


text:
from se34euca.lib.EucaUITestLib_Base import *

class EucaUITestLib_Keypair(EucaUITestLib_Base):
    def test_ui_gotopage_keypairs(self):
        print
        print "Started Test: GotoPage Keypairs"
        print
        self.click_element_by_id("euca-logo")
        print
        print "Test: Received the Page Title -> " + self.driver.title
        self.click_element_by_id("dashboard-netsec-keypair")
        print
        print "Test: Clicked the GoToPage Button"
        self.verify_element_by_id("table-keys-new")
        print
        print "Finished Test: GotoPage Keypairs"
        print
        return 0

    def test_ui_generate_keypair(self):
        print
        print "Started Test: Generate Keypair"
        print
        self.click_element_by_link_text("Dashboard")
        self.verify_element_by_link_text("Launch new instance")
        self.click_element_by_id("dashboard-netsec-keypair")
        print
        print "Test: Clicked the GoToPage Button"
        self.click_element_by_id("table-keys-new")
        print
        print "Test: Generate New Keypair"
        self.set_keys_by_id("key-add-name", "my-sel-gen-key-00")
        self.click_element_by_id("keys-add-btn")
        print
        print "Finished Test: Generate Keypair"
        print
        return 0

    def test_ui_generate_keypair_given_name(self, keypair_name):
        print
        print "Started Test: Generate Keypair Given Name"
        print
        self.click_element_by_link_text("Dashboard")
        self.verify_element_by_link_text("Launch new instance")
        self.click_element_by_id("dashboard-netsec-keypair")
        print
        print "Test: Clicked the GoToPage Button"
        self.click_element_by_id("table-keys-new")
        print
        print "Test: Generate New Keypair"
        self.set_keys_by_id("key-add-name", keypair_name)
        self.click_element_by_id("keys-add-btn")
        print
        print "Finished Test: Generate Keypair Given Name"
        print
        return 0

    def test_ui_import_keypair(self):
        print
        print "Started Test: Import Keypair"
        print
        self.click_element_by_link_text("Dashboard")
        self.verify_element_by_link_text("Launch new instance")
        self.click_element_by_id("dashboard-netsec-keypair")
        print
        print "Test: Clicked the GoToPage Button"
        self.click_element_by_id("table-keys-extra")
        print
        print "Test: Import Keypair"
        self.set_keys_by_id(this_id="key-import-contents",
                            keys="ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDI1x6tEjkBQCCP0ssF69vAgP2xg+N9ScoTrqRqyl5w4qEgsV/AppfHHYRKYr0N/tTyG4/z1XGNrB2SaslnRpgEOsvMZldlOnqsUujL2fgoEg+/gB92+1JhZgTjU8nL5j5BFkVTh93nSHtXHdzYl7SjlXrv26ZbyuDwJmI+s6bJQk5noJ4Q4g7N/0y9pHRvezyhgxkyX7PQoA9WJm8SqlakyhMYa0j/baMhb/ehSI0VvwNodmcaWaS6Z2F4rZS4C2DmCUDXYy/1+0tiRTjHjlPbqRKCVKam8ImWytlZD0zbdV/tpADxDpnhW2cPVpXcjy4sRzUCc8AZW+OE3LQxXild alicehubenko@Alices-MacBook-Pro.local")
        self.set_keys_by_id('key-import-name', "import-key")
        self.click_element_by_id("keys-add-btn")
        print
        print "Finished Test: Import Keypair"
        print
        return 0

    def test_ui_import_keypair_given_name(self, keypair_name):
        print
        print "Started Test: Import Keypair Given Name"
        print
        self.click_element_by_link_text("Dashboard")
        self.verify_element_by_link_text("Launch new instance")
        self.click_element_by_id("dashboard-netsec-keypair")
        print
        print "Test: Clicked the GoToPage Button"
        self.click_element_by_id("table-keys-extra")
        print
        print "Test: Import Keypair " + keypair_name
        self.set_keys_by_id(this_id="key-import-contents",
                            keys="ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDI1x6tEjkBQCCP0ssF69vAgP2xg+N9ScoTrqRqyl5w4qEgsV/AppfHHYRKYr0N/tTyG4/z1XGNrB2SaslnRpgEOsvMZldlOnqsUujL2fgoEg+/gB92+1JhZgTjU8nL5j5BFkVTh93nSHtXHdzYl7SjlXrv26ZbyuDwJmI+s6bJQk5noJ4Q4g7N/0y9pHRvezyhgxkyX7PQoA9WJm8SqlakyhMYa0j/baMhb/ehSI0VvwNodmcaWaS6Z2F4rZS4C2DmCUDXYy/1+0tiRTjHjlPbqRKCVKam8ImWytlZD0zbdV/tpADxDpnhW2cPVpXcjy4sRzUCc8AZW+OE3LQxXild alicehubenko@Alices-MacBook-Pro.local")
        self.set_keys_by_id('key-import-name', keypair_name)
        self.click_element_by_id("keys-add-btn")
        print
        print "Finished Test: Import Keypair Given Name"
        print
        return 0

    #Verifying on Key Pairs landing page by key pair name that key pair is present
    def test_ui_verify_keypair_given_name(self, keypair_name):
        print
        print "Started Test: Verify Keypair Given Name"
        print
        self.click_element_by_link_text(link_text="Dashboard")
        self.verify_element_by_link_text("Launch new instance")
        self.click_element_by_id("dashboard-netsec-keypair")
        print "Verifying that the Keypair " + keypair_name + " exists"
        self.verify_element_by_id(keypair_name)
        print
        print "Finished Test: Verify Keypair Given Name"
        print
        return 0

    def test_ui_verify_delete_keypair_given_name(self, keypair_name):
        print
        print "Started Test: Verify Delete Keypair Given Name"
        print
        self.click_element_by_link_text(link_text="Dashboard")
        self.verify_element_by_link_text("Launch new instance")
        self.click_element_by_id("dashboard-netsec-keypair")
        print "Verifying that the Keypair " + keypair_name + " is deleted"
        self.verify_element_not_present("ID", keypair_name)
        print
        print "Finished Test: Verify Delete Keypair Given Name"
        print
        return 0

    def test_ui_check_keypair_count(self, keys_count):
        print
        print "Started Test: Check Keypair Count"
        print
        self.click_element_by_link_text("Dashboard")
        self.verify_element_by_link_text("Launch new instance")
        print "Verifying that Keypair Count on Dashboard is " + keys_count
        self.verify_text_displayed_by_css("#dashboard-netsec-keypair > span", keys_count)
        print
        print "Finished Test: Check Keypair Count"
        print
        return 0

    def test_ui_delete_keypair(self):
        '''
        Goes to Key Pairs LP and deletes the first key pair from top.
        '''
        print
        print "Started Test: Delete Keypair"
        print
        self.click_element_by_link_text("Dashboard")
        self.verify_element_by_link_text("Launch new instance")
        self.click_element_by_id("dashboard-netsec-keypair")
        print
        print "Test: Clicked the GoToPage Button"
        self.click_element_by_xpath("//table[@id='keys']/tbody/tr/td[2]")
        self.click_element_by_id("more-actions-keys")
        print
        print "Test: Delete Keypair"
        self.click_element_by_link_text("Delete")
        self.click_element_by_id("btn-keys-delete-delete")
        print
        print "Finished Test: Delete Keypair"
        print
        return 0

    def test_ui_delete_keypair_given_name(self, keypair_name):
        print
        print "Started Test: Delete Keypair Given Name"
        print
        self.click_element_by_link_text("Dashboard")
        self.verify_element_by_link_text("Launch new instance")
        self.click_element_by_id("dashboard-netsec-keypair")
        print
        print "Test: Clicked the GoToPage Button"
        self.click_element_by_id(keypair_name)
        self.click_element_by_id("more-actions-keys")
        print
        print "Test: Delete Keypair"
        self.click_element_by_link_text("Delete")
        self.click_element_by_id("btn-keys-delete-delete")
        print
        print "Finished Test: Delete Keypair"
        print
        return 0

    def test_ui_delete_keypair_all(self):
        print
        print "Started Test: Delete Keypair All"
        print
        self.click_element_by_link_text("Dashboard")
        self.verify_element_by_link_text("Launch new instance")
        self.click_element_by_id("dashboard-netsec-keypair")
        print
        print "Test: Clicked the GoToPage Button"
        self.click_element_by_id("keys-check-all")
        self.click_element_by_id("more-actions-keys")
        print
        print "Test: Delete Keypair All"
        self.click_element_by_link_text("Delete")
        self.click_element_by_id("btn-keys-delete-delete")
        print
        print
        print "Finished Test: Delete Keypair All"
        print
        return 0

if __name__ == "__main__":
    unittest.main()


text:
*Motivation and Setup Guide*
See [Documentations on Google Docs](https://docs.google.com/document/d/1FFpCPiTY3VmFtMHmYe78jOzpHLY_6ulhfdxJd6v7jXg)

## Motivation

While writing tests with the Python `unittest` library is awesome, writing tests in CodeceptJS is super simple and much more intuitive.

### Code

**Python Login Example**

```Python
driver.get(url)
elem = driver.find_element_by_name("login")
elem.send_keys(username)
elem = driver.find_element_by_name("password")
elem.send_keys(password)
elem.submit()
```

**CodeceptJS Login Example**

```JavaScript
I.amOnPage('/');
I.fillField('login', username);
I.fillField('password', password);
I.click('Submit')
```

### Assertions

Even more importantly, while assertions in Python may sometimes be a source of confusion (we need to find the actual result we're getting and compare it with the result we expected to see), in CodeceptJS we just use `I.see(something)` or `I.dontSee(something)` to check for the expected results. Being the language much more similar to the way we would express the same requirements in English, the code is much less prone to mistakes.

### Searching for Elements

In Python, we need to decide whether we want to search for an element by id, by name, by css selector, or by xpath, while in CodeceptJS, we just provide an element and the element is automatically searched by id, name, css selector, and xpath, and will return an error only if the element cannot be found by any means.

### Works with WebDriverIO by Default (*but also with Selenium WebDriver, Protractor, and NightmareJS*)

The instructions I provided below are setting up the environment to work with WebDriverIO, but other test runner libraries can be used as well (such as Selenium WebDriver, Protractor, and NightmareJS).

### Works with Travis CI and Sauce Labs (*but also with BrowserStack and TestingBot*)

Basically, CodeceptJS can work with the setup we already have in place (see [Setup Sauce Labs](http://webdriver.io/guide/services/sauce.html) for instructions on how to setup Sauce Labs).  However, we can also substitute Sauce Labs with BrowserStack or with TestingBot, if desired.

### PageObjects and Helpers are Easy to Setup

[PageObjects](http://codecept.io/pageobjects/) and [Helpers](http://codecept.io/helpers/) are also very intuitive and easy to setup.

### Interactive Shell

CodeceptJS provides an interactive shell, that allows to insert a `pause()` call within any test, and test any instance of the `I` object interactively (i.e., on a test that fails, we may insert a `pause()` call, and then try various tests, such as `I.doubleClick(this)` or `I.click(that)`, etc. and see immediately what that command would do if it were to be included in the test).

### Test Call Flexibility

We can run all tests simply by typing `codeceptjs run` and one test only (for instance, a test called `login_test.js`) by typing `codeceptjs run . login_test.js`. However, we can also run only tests that contain the word "login" by typing `codeceptjs run --grep "login"`. Even more handy is the easiness with which we can run our tests on a different browser, by just typing `codeceptjs run --override '{ "helpers": {"WebDriverIO": {"browser": "chrome"}}}'`. This way, instead of having to change our configuration, we can just override it momentarily.

### Conclusion

The features outlined above make of CodeceptJS an ideal environment to write tests, especially for virtual interns, who would have the opportunity to learn how to conduct automated testing, abstracting the complications derived by using a complex framework such as Selenium. There would be many more reasons that may make CodeceptJS a quite attractive alternative to Python `unittest` library, not last the consideration of having an environment entirely based on JavaScript, instead of developing in JavaScript and testing in Python.

In conclusion, CodeceptJS deserves a more complete and thorough evaluation, since its introduction in the work-flow may be considered an advantage in term of easiness of adoption and shorter developing times.

## Setting Up a Testing Development Environment

### Install Firefox

The Firefox web browser is recommended for used in automated testing. Firefox should be updated to version 54.0.1 or newer.

### Install Visual Studio Code

(This is not mandatory, but will make writing your code much easier and faster - if you are used to another text editor, that would be fine as well). Go to https://code.visualstudio.com/ and install the appropriate version for your OS.

### Install Node JS

Go to https://nodejs.org/en/ and install the appropriate version for your OS.

### Install Geckodriver

Go to https://github.com/mozilla/geckodriver/releases and install the appropriate version for your OS. Extract geckodriver and add it to the path.

### Install Selenium Server

Download version 3.0.1 from http://www.seleniumhq.org/download/.
On the command line, type `java -jar selenium-server-standalone-3.0.1.jar` to start the server.

### Install CodeceptJS

On the command line, type `npm install -g codeceptjs` or, if needed, `sudo npm install -g codecept.js`

Fork the new repo from https://github.com/aberdean-ole-vi/BeLL-Apps and clone it on your computer (this is temporary, until you troubleshoot the challenges outlined at the end of the file, then the tests can be merged into `ole-vi/BeLL-Apps`).

Go in the tests folder within your repo: `cd BeLL-Apps/tests`

### Initialize CodeceptJS

On the command line, type `codeceptjs init`. Follow these configuration steps:

- Installing to
   - You will see `./*_test.js` - leave it and just press `Enter`
   - Select `WebDriverIO` and press `Enter`
   - You will see `(./output)` - type `./output` and press `Enter`
   - You will see `(Y/n)` - type `Y` and press `Enter`
   - You will see `English (no localization)` - just press `Enter`
   - You will see `(./steps_file.js)` - type `./steps_file.js` and press `Enter`
- Configure helpers.
   - You will see `(http://localhost)` - type `http://127.0.0.1:5981/apps/_design/bell/MyApp/index.html` and press `Enter`
   - You will see `(firefox)` - type `firefox` and press `Enter`

At this point, you'll see a confirmation message listing all the files that were created, and telling you how to create your first test. More importantly, though, you will see `Please install dependent packages globally: [sudo]` - type `sudo npm install -g webdriverio`

### Create New Test

Type `codeceptjs gt`

- You will see `Creating a new test…`
- Type the name of the test you want to create and press `Enter`
- You will see the name you entered above within parentheses and with an uppercase initial - type what you see in parentheses and press `Enter`
**Example**
- To create a `login` test, when you see `Creating a new test…` - type `login`
- When you see `(Login)` - type `Login` and press `Enter`

That's it! Open your test file and write your test.

If you installed Visual Studio Code (or you use another IDE), type `codeceptjs def` to get auto-completion, which would make writing your tests super easy!

You're now all set to start writing your tests.

To run your tests, just type `codeceptjs run --steps`

Awesome!

## Current Challenges

While CodeceptJS works awesomely for most websites, it presents some problems to work with BeLL-Apps. Specifically, when trying to load the homepage, the Selenium Server throws an error stating that jQuery is not loaded, and then it goes on throwing many more errors stating `ReferenceError: $ is not defined`.

Most likely, this depends on the BeLL-Apps codebase and it is not related to CodeceptJS, so it would probably be worth investigating further to find out the root cause of the error.

Another problem is that testing takes a long time in running with Bell-Apps. This leads to some test cases failing because of loading time problems.

## Common Bugs

If you experience some errors, this may be because of the following reasons:

1. Selenium, Firefox, Node JS, geckodriver are not updated to the appropriate version.
2. Bell-Apps take a long time to load.
3. Selenium, or Firefox, or Node JS, or geckodriver are not running in the system yet.

If you face any errors, please contact other interns through _gitter chat_, and may specifically ask for **@lmmrssa** or **@duongdo27**.


text:
.. _serverreplay:

Server-side replay
==================

Server-side replay lets us replay server responses from a saved HTTP
conversation.

Matching requests with responses
--------------------------------

By default, :program:`mitmproxy` excludes request headers when matching incoming
requests with responses from the replay file. This works in most circumstances,
and makes it possible to replay server responses in situations where request
headers would naturally vary, e.g. using a different user agent.
The :option:`--rheader headername` command-line option allows you to override
this behaviour by specifying individual headers that should be included in matching.

Response refreshing
-------------------

Simply replaying server responses without modification will often result in
unexpected behaviour. For example cookie timeouts that were in the future at
the time a conversation was recorded might be in the past at the time it is
replayed. By default, :program:`mitmproxy` refreshes server responses before sending
them to the client. The **date**, **expires** and **last-modified** headers are
all updated to have the same relative time offset as they had at the time of
recording. So, if they were in the past at the time of recording, they will be
in the past at the time of replay, and vice versa. Cookie expiry times are
updated in a similar way.

You can turn off response refreshing using the :option:`--norefresh` argument, or using
the :kbd:`o` options shortcut within :program:`mitmproxy`.

================== =================
command-line       :option:`-S path`
mitmproxy shortcut :kbd:`S`
================== =================


text:
using System.ComponentModel;
using System.Runtime.Serialization;

namespace Rxns.Scheduling
{
    [DataContract]
    public partial class SqlTask
    {
        /// <summary>
        /// The path to the file or directory that will be executed
        /// by the task
        /// </summary>
        [DataMember]
        [DefaultValue(null)]
        public string Path { get; set; }

        /// <summary>
        /// Tells the task to not fail with an error
        /// if a create statement fails because an object of the
        /// same name already exists
        /// </summary>[DataMember]
        [DefaultValue(true)]
        public bool IgnoreCreateErrors { get; set; }

        /// <summary>
        /// Ignores all errors no matter what when executing scripts.
        /// </summary>
        [DataMember]
        [DefaultValue(false)]
        public bool IgnoreAllErrors { get; set; }
        [DataMember]
        [DefaultValue(null)]
        public string ConnectionString { get; set; }
        [DataMember]
        [DefaultValue(true)]
        public bool UseTransactions { get; set; }
        /// <summary>
        /// overrides the default database as specified by the connection string
        /// </summary>
        [DataMember]
        [DefaultValue(null)]
        public string Database { get; set; }
    }
}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.

using System.Collections.Generic;
using UnityEngine;

namespace DataMesh.AR.Anchor
{
    public class MeshSurfaceObserver : SpatialMappingSource
    {
        private GameObject objects;

        [Tooltip("If greater than or equal to zero, surface objects will claim to be updated at this period. This is useful when working with libraries that respond to updates (such as the SpatialUnderstanding library). If negative, surfaces will not claim to be updated.")]
        public float SimulatedUpdatePeriodInSeconds = -1;

        // Use this for initialization.
        private void Start()
        {
        }

        public void SetMeshes(List<Mesh> meshes)
        {
            Cleanup();

            for (int i = 0;i < meshes.Count; i ++)
            {
                Mesh mesh = meshes[i];
                SurfaceObject surface = CreateSurfaceObject(mesh, "storedmesh-" + SurfaceObjects.Count, transform, i);
                AddSurfaceObject(surface);

                GameObject obj = surface.Object;
                Renderer renderer = obj.GetComponent<MeshRenderer>();

                if (SpatialMappingManager.Instance.DrawVisualMeshes == false)
                {
                    renderer.enabled = false;
                }

                if (SpatialMappingManager.Instance.CastShadows == false)
                {
                    renderer.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;
                }

                MeshCollider collider = obj.GetComponent<MeshCollider>();
                collider.sharedMesh = null;
                collider.sharedMesh = obj.GetComponent<MeshFilter>().mesh;
            }

            if (GetMeshFilters().Count > 0)
            {
                SpatialMappingManager.Instance.SetSpatialMappingSource(this);
            }
        }

        private float lastUpdateUnscaledTimeInSeconds = 0;

        private void Update()
        {
            if (SimulatedUpdatePeriodInSeconds >= 0)
            {
                if ((Time.unscaledTime - lastUpdateUnscaledTimeInSeconds) >= SimulatedUpdatePeriodInSeconds)
                {
                    for (int iSurface = 0; iSurface < SurfaceObjects.Count; iSurface++)
                    {
                        UpdateOrAddSurfaceObject(SurfaceObjects[iSurface]);
                    }

                    lastUpdateUnscaledTimeInSeconds = Time.unscaledTime;
                }
            }
        }
    }
}


text:
package pl.panryba.mc.guilds;

import com.avaje.ebean.EbeanServer;
import com.sk89q.worldedit.BlockVector;
import com.sk89q.worldguard.bukkit.WGBukkit;
import com.sk89q.worldguard.protection.ApplicableRegionSet;
import com.sk89q.worldguard.protection.managers.RegionManager;
import com.sk89q.worldguard.protection.regions.ProtectedCuboidRegion;
import org.bukkit.*;
import org.bukkit.block.Block;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.PlayerInventory;
import pl.panryba.mc.guilds.entities.*;
import pl.panryba.mc.guilds.entities.GuildPoint;
import pl.panryba.mc.guilds.teams.BukkitTeams;
import pl.panryba.mc.guilds.teams.FishTeams;

import java.util.*;

/**
 *
 * @author PanRyba.pl
 */
public final class PluginApi {
    public static final int GUILD_LEFT_WIDTH = 50;
    public static final int GUILD_RIGHT_WIDTH = 50;
    public static final int GUILD_TOP_HEIGHT = 50;
    public static final int GUILD_BOTTOM_HEIGHT = 50;
    public static final int GUILD_FROM_Y = 0;
    public static final int GUILD_TO_Y = 255;
    private static PluginApi instance;

    private final FishTeams teams;
    private final static Material GUILD_MARKER = Material.BEDROCK;
    private final GuildRegionManager regions;
    private final GuildManager manager;
    private final HashMap<String, Guild> currentRegionGuild;
    private final Server server;

    private final Logic logic;
    private GuildsConfig config;
    private boolean protection;

    public static PluginApi getInstance() {
        return PluginApi.instance;
    }

    public static void setup(PluginApi instance) {
        PluginApi.instance = instance;
    }

    // API
    public PluginApi(Server server, EbeanServer database) {
        this.config = new GuildsConfig();
        this.server = server;

        this.manager = new GuildManager(database);
        this.regions = new GuildRegionManager(this.server.getWorlds());

        this.currentRegionGuild = new HashMap<>();
        this.logic = new Logic(this);
        this.teams = new BukkitTeams(server.getScoreboardManager().getMainScoreboard());

        refreshGuildsRegions();

        final Collection<Guild> guilds = this.manager.getGuilds();

        logInfo("Protecting regions of " + guilds.size() + " guilds");

        for (Guild guild : guilds) {
            teams.ensureGuildTeam(guild);
            setGuildMarker(guild.getLocation());
            logInfo("Guild " + guild.getTag() + " decls: " + guild.getOwnDeclarations().size());
        }
    }

    public void setConfig(GuildsConfig config) {
        if(config == null) {
            config = new GuildsConfig();
        }

        this.config = config;
    }

    public void disbandExpiredGuilds(long daysAfterExpiration) {
        final Collection<Guild> guilds = this.manager.getGuilds();

        List<Guild> toDisband = new ArrayList<>();
        for(Guild guild : guilds) {
            if(guild.getExpirySeconds() > daysAfterExpiration /* days */ * 24 /*h*/ * 60 /*min*/ * 60 /*sec*/) {
                toDisband.add(guild);
            }
        }

        for(Guild guild : toDisband) {
            Bukkit.getLogger().info("Disbanding expired guild: " + guild.getTagName() + " (expiry seconds: " + guild.getExpirySeconds() + ")");
            this.disbandGuild(guild);
        }

    }

    private void refreshGuildsRegions() {
        Set<GuildRegion> guildRegions = new HashSet<>();

        for(Guild guild : this.manager.getGuilds()) {
            guildRegions.addAll(guild.getRegions());
        }

        this.regions.refresh(guildRegions);
    }

    public void removePlayerInvitations(Player invited) {
        this.manager.clearPlayerInvitations(invited.getName());
    }

    public void invitePlayerToGuild(Player inviter, String invitedName) {
        Guild inviterGuild = this.getPlayerGuild(inviter);
        if (inviterGuild == null) {
            return;
        }

        Set<GuildInvitation> playerInvits = this.manager.getPlayerInvitations(invitedName);

        if (!playerInvits.isEmpty()) {
            // Remove any previously existing invitation of the player to the guild
            removeInvitationToGuild(inviterGuild, playerInvits);
        }

        GuildInvitation invitation = new GuildInvitation();

        invitation.setInviter(inviter.getName());
        invitation.setPlayer(invitedName);
        invitation.setGuild(inviterGuild);
        invitation.setCreated(new Date());

        playerInvits.add(invitation);
    }

    public boolean removeInvitationToGuild(Guild guild, String invitedName) {
        Set<GuildInvitation> playerInvits = this.manager.getPlayerInvitations(invitedName);

        if (playerInvits == null) {
            return false;
        }

        return removeInvitationToGuild(guild, playerInvits);
    }

    public boolean getTagExists(String tag) {
        return this.manager.getGuildByTag(tag) != null;
    }

    public CanCreateGuildResult canCreateGuildAt(Location location) {

        if(!isWorldAllowedForGuilds(location.getWorld())) {
            return CanCreateGuildResult.No(CanCreateGuildReason.WORLD_DISALLOWED);
        }

        GuildRegion region = prepareGuildRegion(location);

        if (willCollideWithOtherGuild(region)) {
            return CanCreateGuildResult.No(CanCreateGuildReason.COLLIDES_WITH_GUILD_REGION);
        }

        if(willCollideWithOtherRegion(region)) {
            return CanCreateGuildResult.No(CanCreateGuildReason.COLLIDES_WITH_OTHER_REGION);
        }

        return CanCreateGuildResult.Yes();
    }

    private boolean isWorldAllowedForGuilds(World world) {
        return this.config.isWorldAllowed(world);
    }

    public Guild createGuild(String tag, String name, Player player, Set<GuildCostItem> costs) {
        Location location = player.getLocation();

        Guild guild = new Guild(tag, name, player.getName(), player.getLocation());
        Date now = new Date();
        guild.setValidUntil(now.getTime() + 60 * 60 * 24 * this.config.getRenewalDays() * 1000);

        addGuild(guild);

        // Add a default region to the new guild
        GuildRegion region = prepareGuildRegion(guild.getLocation());
        addRegionToGuild(region, guild);

        // Owner has an admin role by default in his guild
        addPlayerToGuild(player, guild, GuildRole.ADMIN);

        chargeCosts(player, costs);
        setGuildMarker(location);

        refreshGuildsRegions();

        return guild;
    }

    private void addRegionToGuild(GuildRegion region, Guild guild) {
        this.manager.addGuildRegion(guild, region);
    }

    public boolean getCanAfford(Player player, Set<GuildCostItem> cost) {
        PlayerInventory inv = player.getInventory();

        if (inv == null) {
            return false;
        }

        for (GuildCostItem required : cost) {
            if (!inventoryContains(inv, required)) {
                return false;
            }
        }

        return true;
    }

    public Set<GuildCostItem> getGuildCost() {
        return this.config.getCosts();
    }
    public Set<GuildCostItem> getRenewalCosts() { return this.config.getRenewalCosts(); }
    public int getRenewalDays() { return this.config.getRenewalDays(); }

    public Guild getPlayerGuild(Player player) {
        return this.manager.getPlayerGuild(player.getName());
    }

    public void disbandGuild(Guild guild) {
        GuildMember[] members = new GuildMember[guild.getMembers().size()];
        guild.getMembers().toArray(members);

        this.manager.removeGuild(guild);
        refreshGuildsRegions();

        removeGuildMarker(guild);
        teams.removeGuildTeam(guild);

        for (GuildMember member : members) {
            updatePlayerListName(member.getPlayer(), null);
        }
    }

    public void setAlly(Guild fromGuild, Guild toGuild) {
        this.manager.setDeclarationForGuilds(fromGuild, toGuild, GuildStateType.ALLY);
    }

    public void setWar(Guild fromGuild, Guild toGuild) {
        this.manager.setDeclarationForGuilds(fromGuild, toGuild, GuildStateType.WAR);
    }

    public void sendToNonMembers(Guild guild, String message) {
        Set<String> memberNames = new HashSet<>();
        for (GuildMember member : guild.getMembers()) {
            memberNames.add(member.getPlayer());
        }

        for (Player player : Bukkit.getServer().getOnlinePlayers()) {
            if (!memberNames.contains(player.getName())) {
                player.sendMessage(message);
            }
        }
    }

    public void sendToMembers(Guild guild, String message) {
        for (GuildMember member : guild.getMembers()) {
            Player player = Bukkit.getPlayer(member.getPlayer());

            if (player != null) {
                player.sendMessage(message);
            }
        }
    }

    public void sendToOtherMembers(Guild guild, Player excludedMember, String message) {
        for (GuildMember member : guild.getMembers()) {
            Player player = Bukkit.getPlayer(member.getPlayer());

            if (player != null && !player.getName().equals(excludedMember.getName())) {
                player.sendMessage(message);
            }
        }
    }

    public void kickPlayer(Player kicked) {
        this.removePlayerMember(kicked);
    }

    public GuildMember getPlayerMember(Player player) {
        return getPlayerMember(player.getName());
    }

    public GuildMember getPlayerMember(String name) {
        return this.manager.getPlayerMember(name);
    }

    public void removePlayerMember(Player player) {
        String name = player.getName();
        GuildMember member = this.manager.getPlayerMember(name);

        if (member == null) {
            return;
        }

        removeGuildMember(member);
        updatePlayerListName(player, null);
    }

    public Collection<Guild> getGuilds() {
        return this.manager.getGuilds();
    }

    public Guild getGuild(String guildTag) {
        return this.manager.getGuildByTag(guildTag);
    }

    public void removeGuildMember(Player player, Guild guild) {
        this.removePlayerMember(player);
    }

    private boolean isGuildOwner(Player player, Guild guild) {
        return guild.getOwner().equals(player.getName());
    }

    public CanInteractResult canBreakBlock(Player player, Block block) {
        return canInteractAt(player, block.getLocation());
    }

    public void setCurrentRegionGuild(Player player, Guild guild) {
        setCurrentRegionGuild(player, guild, false);
    }

    public void setCurrentRegionGuild(Player player, Guild guild, boolean forceNotification) {
        String playerName = player.getName();

        if (!forceNotification) {
            boolean hasPrevious = this.currentRegionGuild.containsKey(playerName);

            if (hasPrevious) {
                Guild previous = this.currentRegionGuild.get(playerName);

                if (previous == null && guild == null) {
                    // Still on unclaimed land
                    return;
                }

                if (!forceNotification && previous != null && guild != null && previous.isSameGuild(guild)) {
                    // Still on same guild land
                    return;
                }
            }
        }

        this.currentRegionGuild.put(playerName, guild);

        if (guild == null) {
            player.sendMessage(ChatColor.GRAY + "Znajdujesz sie na terenie, ktory nie nalezy do zadnej gildii.");
        } else {
            Guild playerGuild = getPlayerGuild(player);

            if (playerGuild != null && playerGuild.isSameGuild((guild))) {
                player.sendMessage(ChatColor.AQUA + "Jestes na terenie swojej gildii");
            } else {
                if (playerGuild != null) {
                    GuildStateType state = getGuildState(playerGuild, guild);
                    switch (state) {
                        case ALLY:
                            player.sendMessage(ChatColor.GREEN + "Wszedles na teren zaprzyjaznionej gildii " + guild.getFullName());
                            break;
                        default:
                            player.sendMessage(ChatColor.RED + "Wszedles na teren wrogiej gildii " + guild.getFullName());
                            break;
                    }
                } else {
                    player.sendMessage(ChatColor.YELLOW + "Wszedles na teren gildii " + guild.getFullName());
                }
            }

            if(guild.hasExpired()) {
                player.sendMessage(ChatColor.GRAY + "Ten teren nie jest chroniony, poniewaz gildia wygasla i mozna ja podbic!");
            }
        }
    }

    public void removeCurrentRegionGuild(Player player) {
        this.currentRegionGuild.remove(player.getName());
    }

    public CanInteractResult canInteract(Player player, Block block) {
        return canInteractAt(player, block.getLocation());
    }

    public CanDamageResult canDamage(Player damager, Player damaged) {
        Guild damagerGuild = getPlayerGuild(damager);
        if (damagerGuild == null) {
            return new CanDamageResult(true);
        }

        Guild damagedGuild = getPlayerGuild(damaged);
        if (damagedGuild == null) {
            return new CanDamageResult(true);
        }

        if (damagerGuild.isSameGuild(damagedGuild)) {
            if (damagedGuild.isInternalPvp()) {
                return new CanDamageResult(true, CanDamageReason.PVP_GUILD_MEMBER);
            } else {
                return new CanDamageResult(false, CanDamageReason.NON_PVP_GUILD_MEMBER);
            }
        }

        GuildStateType state = getGuildState(damagerGuild, damagedGuild);
        if (state == GuildStateType.ALLY) {
            return new CanDamageResult(false, CanDamageReason.ALLIED_GUILD_MEMBER);
        }

        return new CanDamageResult(true);
    }

    public boolean isPlayerInvitedToGuild(Player player, String guildTag) {
        Guild guild = this.manager.getGuildByTag(guildTag);
        if(guild == null) {
            return false;
        }

        String playerName = player.getName();
        Set<GuildInvitation> playerInvits = this.manager.getPlayerInvitations(playerName);

        for (GuildInvitation inv : playerInvits) {
            Guild invGuild = inv.getGuild();

            if (invGuild.isSameGuild(guild)) {
                return true;
            }
        }

        return false;
    }

    public Guild getGuildAt(Location location) {
        GuildRegion region = this.regions.getRegionAt(location);

        if (region == null) {
            return null;
        }

        return region.getGuild();
    }

    public void updatePlayerListName(String playerName, Guild guild) {
        Player player = this.server.getPlayerExact(playerName);
        if (player == null) {
            return;
        }

        updatePlayerListName(player, guild);
    }

    public void updatePlayerListName(Player player) {
        Guild guild = getPlayerGuild(player);
        updatePlayerListName(player, guild);
    }

    public void updatePlayerListName(Player player, Guild guild) {
        String newDisplayName;
        String newName;

        if (guild == null) {
            newName = player.getName();
            newDisplayName = newName;

            teams.removePlayerFromTeam(player.getName());
        } else {
            newName = ChatColor.BLUE + guild.getTag() + " " + ChatColor.GRAY + player.getName();
            if (guild.isOwner(player)) {
                newDisplayName = "*" + newName;
            } else {
                newDisplayName = newName;
            }

            teams.addPlayerToGuildTeam(player.getName(), guild);
        }

        player.setDisplayName(newDisplayName);
    }

    public AddPlayerToGuildResult addPlayerToGuild(Player player, Guild guild, GuildRole role) {
        if(!this.manager.addGuildMember(player.getName(), guild, role)) {
            return new AddPlayerToGuildResult(false, AddPlayerToGuildReason.FAILED);
        }

        removeInvitationToGuild(guild, player.getName());
        updatePlayerListName(player, guild);

        return new AddPlayerToGuildResult(true, AddPlayerToGuildReason.ALLOWED);
    }

    private void chargeCosts(Player player, Set<GuildCostItem> cost) {
        PlayerInventory inv = player.getInventory();

        if (inv == null) {
            return;
        }

        List<ItemStack> stacks = new ArrayList<>();
        for(GuildCostItem costItem : cost) {
            ItemStack stack = costItem.produceStack();
            stacks.add(stack);
        }

        ItemStack[] costStacks = new ItemStack[stacks.size()];
        stacks.toArray(costStacks);

        inv.removeItem(costStacks);
    }

    private CanInteractResult canInteractAt(Player player, Location location) {
        if (isGuildMarker(location)) {
            return new CanInteractResult(false, CanInteractReason.GUILD_MARKER);
        }

        // Ops can interact with any guild
        if (player.isOp()) {
            return new CanInteractResult(true, CanInteractReason.OP);
        }

        Guild guild = getGuildAt(location);

        // There is no guild at this location
        if (guild == null) {
            // Can interact - no guild at this location
            return new CanInteractResult(true, CanInteractReason.UNCLAIMED_LAND);
        }

        if(guild.hasExpired()) {
            return new CanInteractResult(true, CanInteractReason.EXPIRED_GUILD_LAND);
        }

        Guild playerGuild = getPlayerGuild(player);

        // Player has no guild and is within another guild region
        if (playerGuild == null) {
            // Can't interact - guild at location and player not in guild
            return new CanInteractResult(false, CanInteractReason.OTHER_GUILD_LAND);
        }

        if (playerGuild.isSameGuild(guild)) {
            // Can interact - own guild
            return new CanInteractResult(true, CanInteractReason.YOUR_GUILD_LAND);
        }

        return new CanInteractResult(false, CanInteractReason.OTHER_GUILD_LAND);
    }

    public GuildStateType getGuildState(Guild otherGuild, Guild guild) {
        GuildDeclaration declarationTo = this.manager.getDeclarationForGuilds(guild, otherGuild);
        if(declarationTo == null || declarationTo.getState() != GuildStateType.ALLY)
            return GuildStateType.WAR;

        GuildDeclaration declarationFrom = this.manager.getDeclarationForGuilds(otherGuild, guild);
        if(declarationFrom == null || declarationFrom.getState() != GuildStateType.ALLY) {
            return GuildStateType.WAR;
        }

        return GuildStateType.ALLY;
    }

    private void addGuild(Guild guild) {
        this.manager.addGuild(guild);
        teams.ensureGuildTeam(guild);
    }

    private void setGuildMarker(Location location) {
        World world = location.getWorld();
        Block block = world.getBlockAt(location);

        block.setType(GUILD_MARKER);
    }

    private void removeGuildMarker(Guild guild) {
        Location location = guild.getLocation();
        World world = location.getWorld();
        Block block = world.getBlockAt(location);

        if (!block.getType().equals(GUILD_MARKER)) {
            return;
        }

        block.setType(Material.AIR);
    }

    private boolean isGuildMarker(Location location) {
        for (Guild guild : this.manager.getGuilds()) {
            if (guild.getLocation().equals(location.getBlock().getLocation())) {
                return true;
            }
        }

        return false;
    }

    private GuildRegion prepareGuildRegion(Location location) {
        GuildPoint from = new GuildPoint(location.getBlockX() - GUILD_LEFT_WIDTH, GUILD_FROM_Y, location.getBlockZ() - GUILD_TOP_HEIGHT);
        GuildPoint to = new GuildPoint(location.getBlockX() + GUILD_RIGHT_WIDTH, GUILD_TO_Y, location.getBlockZ() + GUILD_BOTTOM_HEIGHT);

        GuildRegion region = new GuildRegion(from, to, location.getWorld());
        return region;
    }

    private boolean removeInvitationToGuild(Guild guild, Set<GuildInvitation> removeFrom) {
        for (GuildInvitation invitation : removeFrom) {
            Guild invGuild = invitation.getGuild();

            if (invGuild.isSameGuild(guild)) {
                removeFrom.remove(invitation);
                return true;
            }
        }

        return false;
    }

    private boolean inventoryContains(PlayerInventory inventory, GuildCostItem required) {
        return inventory.containsAtLeast(required.produceStack(), required.getQty());
    }

    private boolean willCollideWithOtherGuild(GuildRegion region) {
        return this.regions.hasIntersectingRegion(region);
    }

    private boolean willCollideWithOtherRegion(GuildRegion region) {
        World world = Bukkit.getWorld(region.getWorld());
        RegionManager wgManager = WGBukkit.getRegionManager(world);

        GuildPoint from = region.getFrom();
        GuildPoint to = region.getTo();

        BlockVector p1 = new BlockVector(from.getX(), from.getY(), from.getZ());
        BlockVector p2 = new BlockVector(to.getX(), to.getY(), to.getZ());

        ProtectedCuboidRegion cuboidRegion = new ProtectedCuboidRegion("__TEST__", p1, p2);

        ApplicableRegionSet set = wgManager.getApplicableRegions(cuboidRegion);
        return set.size() > 0;
    }

    public Guild findGuildWithMarkerNear(Location location, long radius) {
        Iterator<Guild> i = findGuildsWithMarkerAt(location, radius, 1).iterator();
        if(!i.hasNext()) {
            return null;
        }

        return i.next();
    }

    public Set<Guild> findGuildsWithMarkerAt(Location location, long radius, long limit) {
        Set<Guild> result = new HashSet<>();

        if(limit == 0) {
            return result;
        }

        Location from = new Location(location.getWorld(), location.getBlockX() - radius, location.getBlockY() - radius, location.getBlockZ() - radius);
        Location to = new Location(location.getWorld(), location.getBlockX() + radius, location.getBlockY() + radius, location.getBlockZ() + radius);

        for(Guild guild : this.manager.getGuilds()) {
            if(LocationHelper.isWithin(guild.getMarkerLocation(), from, to)) {
                result.add(guild);

                if(result.size() >= limit) {
                    break;
                }
            }
        }

        return result;
    }

    public boolean canSetHome(Player player, Guild guild) {
        return isGuildOwner(player, guild);
    }

    public void setGuildHomeLocation(Guild guild, Location location) {
        this.manager.setGuildHomeLocation(guild, location);
    }

    public void setGuildOwner(Guild guild, Player player) {
        String previousOwnerName = guild.getOwner();
        this.manager.setGuildOwner(guild, player);

        updatePlayerListName(previousOwnerName, guild);
        updatePlayerListName(player, guild);
    }

    public boolean canDisbandGuild(GuildMember member) {
        return isGuildOwner(member);
    }

    public boolean canNominate(Player player, Guild guild) {
        return this.isGuildOwner(player, guild);
    }

    public void switchInternalPvp(Guild guild) {
        this.manager.setInternalPvp(guild, !guild.isInternalPvp());
    }

    public void setGuildName(Guild guild, String name) {
        this.manager.setGuildName(guild, name);
    }

    public void setGuildTag(Guild guild, String tag) {
        this.manager.setGuildTag(guild, tag);
        teams.ensureGuildTeam(guild);

        for (GuildMember member : guild.getMembers()) {
            updatePlayerListName(member.getPlayer(), guild);
        }
    }

    public boolean isValidGuildTag(String tag) {
        return tag.matches("[A-Za-z0-9]{3,4}");
    }

    /*
    public boolean canMoveGuildTo(Guild guild, Location location) {
        GuildRegion currGuildRegion = this.regions.findGuildRegion(guild);
        logInfo("Current guild region: " + currGuildRegion.toString());

        GuildRegion newRegion = prepareGuildRegion(location);
        logInfo("New guild region: " + newRegion.toString());

        boolean result = !this.regions.hasOtherIntersectingRegion(newRegion, currGuildRegion);
        logInfo("Can move: " + result);

        if(willCollideWithOtherRegion(newRegion)) {
            return false;
        }

        return result;
    }

    public void moveGuildTo(Guild guild, Location location) {
        removeGuildMarker(guild);
        this.manager.moveGuild(guild, location);
        setGuildMarker(location);

        refreshGuildsRegions();
    }
    */

    public void setMemberRole(GuildMember targetMember, GuildRole role) {
        this.manager.setMemberRole(targetMember, role);
    }

    public boolean canAdminGuild(GuildMember member) {
        if (member == null) {
            return false;
        }

        return member.hasRole(GuildRole.ADMIN);
    }

    public boolean canModerateGuild(GuildMember member) {
        if (member == null) {
            return false;
        }

        return member.hasRole(GuildRole.MODERATOR);
    }

    public boolean canMoveGuild(GuildMember member) {
        return canAdminGuild(member);
    }

    public boolean canNameGuild(GuildMember member) {
        return canAdminGuild(member);
    }

    public boolean canSetGuildRoles(GuildMember member) {
        return canAdminGuild(member);
    }

    public boolean canTagGuild(GuildMember member) {
        return canAdminGuild(member);
    }

    public boolean canSetAlly(GuildMember member) {
        return canModerateGuild(member);
    }

    public boolean canInvite(GuildMember member) {
        return canModerateGuild(member);
    }

    public boolean canKick(GuildMember member) {
        return canModerateGuild(member);
    }

    public boolean canChangeInternalPvp(GuildMember member) {
        return canModerateGuild(member);
    }

    public boolean canRejectInvitation(GuildMember member) {
        return canModerateGuild(member);
    }

    public boolean canSetGuildHome(GuildMember member) {
        return canModerateGuild(member);
    }

    public boolean canDeclareWar(GuildMember member) {
        return canModerateGuild(member);
    }

    private boolean isGuildOwner(GuildMember member) {
        return member.isOwner();
    }

    public boolean canCreateGuild(Player player) {
        return player.hasPermission("guilds.create");
    }

    public boolean canJoinGuild(Player player) {
        return player.hasPermission("guilds.join");
    }

    public void sendMessage(CommandSender cs, List<String> messages) {
        String[] messagesArray = new String[messages.size()];
        messages.toArray(messagesArray);

        cs.sendMessage(messagesArray);
    }

    private void logInfo(String msg) {
        Bukkit.getLogger().info(msg);
    }

    public GuildRank getGuildRank(Guild guild, String rankName) {
        for(GuildRank rank : guild.getRanks()) {
            if(rank.getName().equalsIgnoreCase(rankName)) {
                return rank;
            }
        }

        return null;
    }

    public boolean createRank(Guild guild, String rankName) {
        GuildRank rank = new GuildRank();
        rank.setGuild(guild);
        rank.setName(rankName);

        return this.manager.addRank(rank);
    }

    /*
    public boolean removeRank(GuildRank rank) {
        return this.manager.removeRank(rank);
    }
    */

    public void setMemberRank(GuildMember member, GuildRank rank) {
        this.manager.setMemberRank(member, rank);
    }

    public void clearMemberRank(GuildMember member) {
        this.manager.setMemberRank(member, null);
    }

    public GuildLimit getGuildMembersLimit(Player inviter) throws Exception {
        if(inviter.hasPermission("guilds.limits.unlimited")) {
            return null;
        }

        GuildLimit currentLimit = null;

        for (GuildLimit limit : this.config.getLimits()) {
            if (currentLimit == null) {
                currentLimit = limit;
                continue;
            }

            if (limit.getLimit() <= currentLimit.getLimit()) {
                continue;
            }

            if (inviter.hasPermission(limit.getPermission())) {
                currentLimit = limit;
            }
        }

        return currentLimit;
    }

    public void removeGuildMember(GuildMember member) {
        Guild guild = member.getGuild();

        this.manager.removeMember(member);

        if (!guild.hasMembers()) {
            disbandGuild(guild);
        }
    }

    public boolean canTeleportTo(Player player, Location to) {
        if(player.hasPermission("guilds.teleport.any")) {
            return true;
        }

        Guild guildAtTarget = getGuildAt(to);
        if(guildAtTarget == null) {
            // No guild at target location so can teleport
            return true;
        }

        if(guildAtTarget.hasExpired()) {
            return true;
        }

        Guild playerGuild = getPlayerGuild(player);
        if(playerGuild == null) {
            // Player has no guild and there is a guild at the target location
            return false;
        }

        if(playerGuild.isSameGuild(guildAtTarget)) {
            // Is in target guild so can teleport
            return true;
        }

        if(!player.hasPermission("guilds.teleport.ally")) {
            return false;
        }

        if(getGuildState(guildAtTarget, playerGuild) == GuildStateType.ALLY) {
            // Is allied guild so can teleport
            return true;
        }

        return false;
    }

    public void renewGuild(Player player, Guild guild, int days, Set<GuildCostItem> costs) {
        Long validUntil = guild.getValidUntil();
        if(validUntil == null) {
            return;
        }

        chargeCosts(player, costs);

        long daysTicks = 60 * 60 * 24 * days * 1000;

        Date now = new Date();
        validUntil = now.getTime() + daysTicks;

        this.manager.setGuildValidity(guild, validUntil);
    }

    void notifyExpiringGuilds() {
        Set<String> handledNames = new HashSet<>();

        String expiringMsg = ChatColor.BLUE + "Twoja gildia wkrotce wygasa. Odnow ja! (zobacz: /gildia)";
        String expiredMsg = ChatColor.BLUE + "Twoja gildia wygasla i jej teren nie jest juz chroniony! Odnow ja szybko! (zobacz: /gildia)";

        for(Player player : Bukkit.getOnlinePlayers()) {
            if(handledNames.contains(player.getName())) {
                continue;
            }

            GuildMember member = getPlayerMember(player);
            if(member == null) {
                continue;
            }

            for(GuildMember guildMember : member.getGuild().getMembers()) {
                handledNames.add(guildMember.getPlayer());
            }

            Long validitySeconds = member.getGuild().getValiditySeconds();
            if(validitySeconds == null || validitySeconds > 60 * 60 * 24) {
                continue;
            }

            if(validitySeconds == 0) {
                sendToMembers(member.getGuild(), expiredMsg);
            } else {
                sendToMembers(member.getGuild(), expiringMsg);
            }
        }
    }

    public void sendGuildChatMessage(Player player, Guild guild, String msg) {
        String finalMsg = ChatColor.DARK_AQUA + "@" + player.getName() + "> " + ChatColor.AQUA + msg;
        Bukkit.getLogger().info("GC: " + finalMsg); // log guild chats

        sendToMembers(guild, finalMsg);
    }

    public void sendGuildAllyChatMessage(Player player, Guild guild, String msg) {
        String finalMsg = ChatColor.DARK_GREEN + "#" + player.getName() + "> " + ChatColor.GREEN + msg;
        Bukkit.getLogger().info("GAC: " + finalMsg); // log guild chats

        Set<Guild> guildsToSend = new HashSet<>();
        guildsToSend.add(guild);

        for(Guild otherGuild : this.getGuilds()) {
            if(otherGuild.isSameGuild(guild)) {
                continue;
            }

            GuildStateType state = getGuildState(otherGuild, guild);
            if(state == GuildStateType.ALLY) {
                guildsToSend.add(otherGuild);
            }
        }

        for(Guild g : guildsToSend) {
            sendToMembers(g, finalMsg);
        }
    }

    public boolean onTntExplosion(Player player, Location location) {
        Guild guild = findGuildWithMarkerNear(location, 3);

        if(guild == null) {
            guild = getGuildAt(location);
            return guild == null || !protection;
        }

        if(!this.logic.canGuildBeConquered(guild)) {
            return true;
        }

        GuildMember playerMember = this.getPlayerMember(player);
        if(!this.logic.canConquerGuild(playerMember, guild)) {
            return true;
        }

        if(protection) {
            String msg =
                    ChatColor.GRAY + "Podbijanie gildii jest niemozliwe w godzinach od " +
                            config.getProtectFrom() + " do " + config.getProtectTo();
            player.sendMessage(msg);
            return true;
        }

        String bcMsg =
                ChatColor.RED + "--- Gildia " +
                ChatColor.YELLOW + guild.getFullName() +
                ChatColor.RED + " zostala PODBITA przez " +
                ChatColor.GREEN + player.getName() +
                ChatColor.RED + " z gildii " +
                ChatColor.YELLOW + playerMember.getGuild().getFullName() +
                ChatColor.RED + "! ---";

        String membersMsg = ChatColor.RED + "--- Twoja gildia zostala PODBITA przez " +
                ChatColor.GREEN + player.getName() +
                ChatColor.RED + " z gildii " +
                ChatColor.YELLOW + playerMember.getGuild().getFullName() + "! ---";

        sendToMembers(guild, membersMsg);
        sendToNonMembers(guild, bcMsg);

        Guild conqueror = playerMember.getGuild();
        int points = this.logic.calculateConquerPoints(conqueror, guild);
        this.manager.changeGuildScore(conqueror, points);

        disbandGuild(guild);
        return true;
    }

    public String getPlayerTag(Player player) {
        GuildMember member = this.getPlayerMember(player);
        if(member == null) {
            // Return null so its not customized
            return null;
        }

        String tag = member.getGuild().getTag() + " " + player.getName();
        return tag;
    }

    public void sendCantAfford(Player player, Set<GuildCostItem> cost, String header) {
        List<String> msgs = new ArrayList<>();
        msgs.add(header);

        for(GuildCostItem required : cost) {
            msgs.add(required.getQty() + " " + required.getName());
        }

        this.sendMessage(player, msgs);
    }

    public void updateRankingScores(Player winner, int winnerPoints, Player loser, int loserPoints) {
        GuildMember winnerMember = this.getPlayerMember(winner);
        GuildMember loserMember = this.getPlayerMember(loser);

        if(winnerMember == null || loserMember == null) {
            // Guild may score only if killed another guild member
            return;
        }

        if(winnerMember.isInSameGuild(loserMember)) {
            // Do not update scores for same guild members
            return;
        }

        Guild winnerGuild = winnerMember.getGuild();
        if(this.logic.canGainPoints(winnerGuild)) {
            this.manager.changeGuildScore(winnerGuild, Math.max(1, winnerPoints));
        }

        this.manager.changeGuildScore(loserMember.getGuild(), Math.min(-1, loserPoints));
    }

    public void expireGuild(Guild guild) {
        this.manager.setGuildValidity(guild, new Date().getTime());
    }

    public void updateProtection() {
        Calendar now = Calendar.getInstance();
        int hour = now.get(Calendar.HOUR_OF_DAY);

        this.protection = this.config.isProtected(hour);
    }
}


text:
	<li id="nav-photos" <?php if($this->utility->isActiveTab('photos')) { ?> class="active" <?php } ?>>
		<a href="<?php $this->url->photosView(); ?>">Photos

	<li id="nav-tags" <?php if($this->utility->isActiveTab('tags')) { ?> class="active" <?php } ?>>
		<a href="<?php $this->url->tagsView(); ?>">Tags

<?php if($this->user->isOwner()) { ?>
	<li id="nav-upload" <?php if($this->utility->isActiveTab('upload')) { ?> class="active" <?php } ?>>
		<a href="<?php $this->url->photosUpload(); ?>">Upload

		<a href="<?php $this->url->userManage(); ?>">Manage

<?php } ?>
<?php if($this->user->isLoggedIn()) { ?>

		<img src="<?php echo $this->user->getAvatarFromEmail(40, $this->session->get('email')); ?>" id="avatar" class="settings-click" />

			<?php echo $this->session->get('email'); ?>

<a href="<?php $this->url->userLogout(); ?>">Logout

<?php } else { ?>

    <?php if($this->plugin->isActive('FacebookConnect')) { ?>
      <img src="<?php $this->theme->asset('image', 'facebook-icon.gif'); ?>" class="login-click facebook" hspace="5" />
    <?php } ?>
    <img src="<?php $this->theme->asset('image', 'browserid.png'); ?>" class="login-click browserid" />

<?php } ?>
	<li id="nav-search" <?php if($this->utility->isActiveTab('search')) { ?> class="active" <?php } ?>>
		<form action="<?php $this->url->photosView(); ?>" method="get" id="form-tag-search">
			<input type="text" name="tags" placeholder="Enter a tag" class="select tags-autocomplete" /><button type="submit" class="search-click" title="Search now">Go</button>
		</form>


text:
AttractField

Creates a field that attracts particles.
--]]
--------------------------------------------------------------------------------

local CBE = require("CBE.CBE")

-- Create the vent
local vent = CBE.newVent({
	positionType = "inRect",
	emitX = 0,
	emitY = 0,
	rectWidth = display.contentWidth,
	rectHeight = display.contentHeight
})

-- Create the field
local field = CBE.newField {
	onCollision = function(p, f)
		p:applyForce((f.x - p.x) * 0.01, (f.y - p.y) * 0.01)
	end
}

-- Link the field to the vent in one of three ways

-- Way #1:
vent:linkField(field)
-- Way #2: field:linkVent(vent) - alias for vent.linkField(field)
-- Way #3: In parameters for the field, put "targetVent = vent"

-- Start both the vent and the field
vent:start()
field:start()


text:
<?php
final class FilePermissions {
	const PUBLIC_ACCESS = 1;
	const RESTRICTED_ACCESS = 2;
	const PRIVATE_ACCESS = 3;

	public static function parse($input) {
		switch($input) {
			case 1:
				return FilePermissions::PUBLIC_ACCESS;

			case 2:
				return FilePermissions::RESTRICTED_ACCESS;

			case 3:
				return FilePermissions::PRIVATE_ACCESS;

			default:
				throw new InvalidArgumentException('$input has wrong format');
		}
	}

	public static function tryParse($input) {
		try {
			$result = self::parse($input);
			return true;
		} catch(InvalidArgumentException $e) {
			return false;
		}
	}

	public static function getAll() {
		return array(
			FilePermissions::PUBLIC_ACCESS => System::getLanguage()->_('PermissionPublic'),
			FilePermissions::RESTRICTED_ACCESS => System::getLanguage()->_('PermissionProtected'),
			FilePermissions::PRIVATE_ACCESS => System::getLanguage()->_('PermissionPrivate')
		);
	}
}
?>


text:
'use strict';

var fs = require("fs");
var mkdirp = require('mkdirp');
var rimraf = require('rimraf');
var request = require('request');
var async = require('async');

var config = require('../../../../config.js');

function checkIfError(error, options, cb, callback) {
	if (error) {
		if (options && options.code) {
			if (typeof (error) === 'object' && error.code) {
				error.code = options.code;
			} else {
				error = {
					code: options.code,
					message: options.message || error
				};
			}
		}

		return cb(error);
	}

	return callback();
}

function requester(options, cb) {
	options.json = true;

	if (!options.headers) {
		options.headers = {};
	}

	options.headers['Content-Type'] = 'application/json';
	request(options, function (error, response, body) {
		return cb(error, body);
	});
}

var bitbucket = {

	getUserRecord: function (data, cb) {
		var options = {
			method: 'GET',
			url: config.gitAccounts.bitbucket.apiDomain + config.gitAccounts.bitbucket.routes.getUserRecord
		};

		if (data.token) {
			options.headers = {
				'Authorization': 'Bearer ' + data.token
			};
		}
		return requester(options, cb);
	},

	getRepoBranches: function (data, cb) {
		var repoInfo;
		if (data.name) {
			repoInfo = data.name.split('/');
		} else {
			repoInfo = [data.owner, data.repo];
		}

		var options = {
			method: 'GET',
			url: config.gitAccounts.bitbucket.apiDomain + config.gitAccounts.bitbucket.routes.getBranches
				.replace('%USERNAME%', repoInfo[0])
				.replace('%REPO_NAME%', repoInfo[1])
		};

		if (data.token) {
			options.headers = {
				authorization: 'Bearer ' + data.token
			};
		}
		return requester(options, cb);
	},

	getContent: function (data, cb) {
		var options = {
			method: 'GET',
			url: config.gitAccounts.bitbucket.apiDomain + config.gitAccounts.bitbucket.routes.getContent
				.replace('%USERNAME%', data.user)
				.replace('%REPO_NAME%', data.repo)
				.replace('%BRANCH%', data.ref)
				.replace('%FILE_PATH%', data.path)
		};

		if (data.token) {
			options.headers = {
				authorization: 'Bearer ' + data.token
			};
		}
		if (!options.headers) {
			options.headers = {};
		}
		request(options, function (error, response, body) {
			return cb(error, body);
		});
	},

	getAllRepos: function (data, cb) {
		var options = {
			method: 'GET'
		};

		options.url = config.gitAccounts.bitbucket.apiDomain + config.gitAccounts.bitbucket.routes.getAllRepos.replace('%USERNAME%', data.owner);
		if (data.token) {
			options.headers = {
				authorization: 'Bearer ' + data.token
			};
		}
		options.qs = {
			"limit": options.per_page ? options.per_page : 100,
			"start": options.page && options.page > 0 ?  options.page - 1 : 0
		};
		if (data.name){
			options.qs.q = `name~"${data.name}"`;
		}
		return requester(options, cb);
	},

	getAllReposWithAccess: function (data, cb) {
		var options = {
			method: 'GET'
		};

		options.url = config.gitAccounts.bitbucket.apiDomain + config.gitAccounts.bitbucket.routes.getAllReposWithAccess;
		if (data.token) {
			options.headers = {
				authorization: 'Bearer ' + data.token
			};
		}
		options.qs = {
			"pagelen": options.per_page ? options.per_page : 100,
			"start": options.page  ?  options.page  : 1
		};
		if (data.name){
			options.qs.q = `repository.name~"${data.name}"`;
		}
		return requester(options, cb);
	},

	getToken: function (data, cb) {
		//generates or refreshes a oauth token
		var formData = {};
		if (data.action === 'generate') {
			formData.grant_type = 'password';
			formData.username = data.owner;
			formData.password = data.password;
		} else if (data.action === 'refresh') {
			formData.grant_type = 'refresh_token';
			formData.refresh_token = data.tokenInfo.refresh_token;
		}

		var options = {
			method: 'POST',
			json: true,
			url: config.gitAccounts.bitbucket.oauth.domain,
			headers: {
				'Content-Type': 'application/x-www-form-urlencoded'
			},
			auth: {
				user: data.tokenInfo.oauthKey,
				pass: data.tokenInfo.oauthSecret
			},
			form: formData
		};

		return requester(options, cb);
	}
};

var lib = {
	"createAuthToken": function (options, cb) {
		options.action = 'generate';

		bitbucket.getToken(options, function (error, authInfo) {
			if (error || authInfo.error) {
				return cb(error || authInfo);
			}

			return cb(null, authInfo);
		});
	},

	"checkAuthToken": function (soajs, options, model, accountRecord, cb) {
		if (!options.tokenInfo) {
			return cb(null, false);
		}

		var expiryDate = options.tokenInfo.created + options.tokenInfo.expires_in - 300000; //5min extra for extra assurance when deploying
		var currentDate = (new Date).getTime();

		if (currentDate > expiryDate) {
			options.action = 'refresh';

			bitbucket.getToken(options, function (error, tokenInfo) {
				if (error || tokenInfo.error) {
					return cb(error || tokenInfo.error);
				}

				accountRecord.token = tokenInfo.access_token;
				accountRecord.tokenInfo.refresh_token = tokenInfo.refresh_token;
				accountRecord.tokenInfo.created = (new Date).getTime();
				accountRecord.tokenInfo.expires_in = tokenInfo.expires_in * 1000;

				var opts = {
					collection: 'git_accounts',
					record: accountRecord
				};
				model.saveEntry(soajs, opts, function (error) {
					if (error) {
						return cb(error);
					}

					var newTokenInfo = {
						token: accountRecord.token,
						tokenInfo: accountRecord.tokenInfo
					};

					return cb(null, true, newTokenInfo);
				});
			});
		} else {
			return cb(null, false);
		}
	},

	checkUserRecord: function (options, cb) {
		bitbucket.getUserRecord(options, function (error, record) {
			if (error) {
				return cb(error);
			}
			if (!record || record === 'None') {
				return cb({message: 'User does not exist'});
			}

			return cb(null, record);
		});
	},

	getAllRepos: function (options, cb) {
		return bitbucket.getAllRepos(options, cb);
	},

	getAllReposWithAccess: function (options, cb) {
		return bitbucket.getAllReposWithAccess(options, cb);
	},

	buildReposArray: function (allRepos) {
		var repos = [];

		if (allRepos && allRepos.values && Array.isArray(allRepos.values)) {
			allRepos.values.forEach(function (oneRepo) {
				repos.push({
					full_name: oneRepo.full_name,
					owner: {
						login: oneRepo.owner.username
					},
					name: oneRepo.slug
				});
			});
		} else {
			repos = [];
		}

		return repos;
	},
	buildReposArrayWithAccess: function (allRepos) {
		var repos = [];

		if (allRepos && allRepos.values && Array.isArray(allRepos.values)) {
			allRepos.values.forEach(function (oneRepo) {
				repos.push({
					full_name: oneRepo.repository.full_name,
					owner: {
						login: oneRepo.repository.full_name.split("/")[0]
					},
					name: oneRepo.repository.full_name.split("/")[1]
				});
			});
		} else {
			repos = [];
		}
		return repos;
	},

	addReposStatus: function (allRepos, activeRepos, cb) {
		if (!Array.isArray(allRepos)) {
			allRepos = [];
		}

		if (!activeRepos || activeRepos.length === 0) {
			return cb(allRepos);
		}

		var found;
		activeRepos.forEach(function (oneRepo) {
			found = false;
			var multi;
			if (oneRepo.type === 'multi' && oneRepo.configSHA && oneRepo.configSHA.length > 0) {
				if (!Array.isArray(multi)) {
					multi = [];
				}
				oneRepo.configSHA.forEach(function (oneSub) {
					multi.push({
						type: oneSub.contentType,
						name: oneSub.contentName
					})
				});
			}

			for (var i = 0; i < allRepos.length; i++) {
				if (allRepos[i].full_name === oneRepo.name) {
					if (oneRepo.status) {
						allRepos[i].status = oneRepo.status;
					} else {
						allRepos[i].status = 'active';
					}

					if (oneRepo.type !== 'multi') {
						if (oneRepo.serviceName) {
							allRepos[i].serviceName = oneRepo.serviceName;
						} else if (oneRepo.name) {
							var name = oneRepo.name;
							if (name.indexOf("/") !== -1) {
								name = name.split("/")[1];
							}
							allRepos[i].serviceName = name;
						}
					}

					allRepos[i].type = oneRepo.type;
					allRepos[i].git = oneRepo.git;
					allRepos[i].configBranch = oneRepo.configBranch;
					if (multi && multi.length > 0) {
						allRepos[i].multi = multi;
					}
					found = true;
					break;
				}
			}
			// if (!found) {
			// 	//USING THE SAME RECORD FORMAT AS GITHUB API RESPONSES
			// 	var repoInfo = oneRepo.name.split('/');
			// 	var newRepo = {
			// 		full_name: oneRepo.name,
			// 		owner: {
			// 			login: repoInfo[0]
			// 		},
			// 		name: repoInfo[1],
			// 		status: 'deleted',
			// 		type: oneRepo.type
			// 	};
			// 	if (oneRepo.configBranch){
			// 		newRepo.configBranch = oneRepo.configBranch;
			// 	}
			// 	if (multi && multi.length > 0) {
			// 		newRepo.multi = multi;
			// 	}
			// 	allRepos.push(newRepo);
			// }
		});

		return cb(allRepos);
	},

	getRepoBranches: function (options, cb) {
		return bitbucket.getRepoBranches(options, cb);
	},

	buildBranchesArray: function (allBranches) {
		var branches = [];
		if (allBranches && allBranches.values) {
			allBranches.values.forEach(function (oneBranch) {
				branches.push({
					name: oneBranch.name,
					commit: {
						sha: oneBranch.target.hash
					}
				});
			});
		}
		return branches;
	},

	getRepoContent: function (options, cb) {
		return bitbucket.getContent(options, cb);
	},

	"writeFile": function (options, cb) {
		fs.exists(options.configDirPath, function (exists) {
			if (exists) {
				lib.clearDir({soajs: options.soajs, repoConfigsFolder: options.configDirPath}, function () {
					write();
				});
			} else {
				write();
			}

			function write() {
				mkdirp(options.configDirPath, function (error) {
					checkIfError(error, {}, cb, function () {
						fs.writeFile(options.configFilePath, options.configFile, function (error) {
							return (error) ? cb(error) : cb();
						});
					});
				});
			}
		});
	},

	"clearDir": function (options, cb) {
		rimraf(options.repoConfigsFolder, function (error) {
			if (error) {
				options.soajs.log.warn("Failed to clean repoConfigs directory, proceeding ...");
				options.soajs.log.error(error);
			}

			return cb();
		});
	}
};

module.exports = lib;


text:
'use strict';

angular.module('mean.mymodule').controller('MymoduleController', ['$scope', 'Global', 'Mymodule',
  function($scope, Global, Mymodule) {
    $scope.global = Global;
    $scope.package = {
      name: 'mymodule'
    };
  }
]);


text:
package ValidateBinarySearchTree;

public class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode(int x) {
        val = x;
    }
}


text:
package com.twitter.meil_mitu.twitter4holo.api.account;

import com.twitter.meil_mitu.twitter4holo.AbsOauth;
import com.twitter.meil_mitu.twitter4holo.AbsPost;
import com.twitter.meil_mitu.twitter4holo.ITwitterJsonConverter;
import com.twitter.meil_mitu.twitter4holo.OauthType;
import com.twitter.meil_mitu.twitter4holo.exception.Twitter4HoloException;

public class UpdateDeliveryDevice extends AbsPost<ITwitterJsonConverter>{

    public UpdateDeliveryDevice(AbsOauth oauth, ITwitterJsonConverter json, String device){
        super(oauth, json);
        addParam("device", device);
    }

    public UpdateDeliveryDevice includeEntities(boolean includeEntities){
        addParam("include_entities", includeEntities);
        return this;
    }

    @Override
    public String url(){
        return "https://api.twitter.com/1.1/account/update_delivery_device.json";
    }

    @Override
    public int allowOauthType(){
        return OauthType.Oauth1;
    }

    @Override
    public boolean isAuthorization(){
        return true;
    }

    @Override
    public Void call() throws Twitter4HoloException{
        // okhttp's connection is called close() in body().string()
        AbsJson.toString(Oauth.post(this).body());
        return null;
    }
}