text:
Toggle button
=============

The toogle button is a jQuery widget.

See [demo](http://jqueryui.com/button/#checkbox)

### Usage:

``` php
<?php
// ...
public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        // .....
        ->add('toogle_button', 'thrace_toggle_button', array(
            'configs' => array(
                'checked_label' => 'checked',
                'unchecked_label' => 'unchecked',
                'icons' => array('primary' => 'ui-icon-check'),
            ),
        ))
		// .....
    ;
}
```
**Note:** All configs are passed as json object to the widget.

In the twig template add following code:

``` jinja
{% block stylesheets %}

    {% stylesheets
       'jquery/css/smoothness/jquery-ui.css'
       filter='cssrewrite'
    %}
        <link rel="stylesheet" href="{{ asset_url }}" />
    {% endstylesheets %}

{% endblock %}

{% block javascripts %}

    {% javascripts
        'jquery/js/jquery.js'
        'jquery/js/jquery-ui.js'
        'jquery/i18n/jquery-ui-i18n.js'
        'bundles/thraceform/js/toggle-button.js'

    %}
        <script src="{{ asset_url }}"></script>
	{% endjavascripts %}

{% endblock %}

{% form_theme form with ['ThraceFormBundle:Form:fields.html.twig'] %}

```

Run the following command:

``` bash
$ php app/console assetic:dump
```

That's it.

[back to index](index.md#list)

redpajama_set_name: RedPajamaGithub


text:
class Notifier < ActionMailer::Base
  default_url_options[:host] = "#{default_url_options_host}"

  def password_reset_instructions(user)
    setup(user)
    subject I18n.t("subject.password_reset_instructions")
    body :edit_password_reset_url => edit_password_reset_url(user.perishable_token)
  end

  def welcome_email(user)
    setup(user)
    subject I18n.t("subject.welcome")
    body :user => user
  end

  #{activation_instructions_block}
private

  def setup(user)
    from "#{notifier_email_from}"
    sent_on Time.now
    recipients user.email
  end

end


text:
<?php

require_once dirname(dirname(__FILE__)) . DIRECTORY_SEPARATOR . 'interfaces' . DIRECTORY_SEPARATOR . 'IOauth2Proxy.php';

/**
 * Oauth2Proxy is the OAuth 2.0 proxy class.
 * Redirects requests to the external web resource by OAuth 2.0 protocol.
 *
 * @see http://oauth.net/2/
 * @author Andrey Geonya
 */
class Oauth2Proxy implements IOauth2Proxy
{
	private $_clientId;
	private $_clientSecret;
	private $_dialogUrl;
	private $_redirectUri;
	private $_scope;
	private $_responseType;
	private $_accessTokenUrl;
	private $_accessParams;
	private $_authJson;

	/**
	 * Constructor.
	 *
	 * @param string $clientId id of the client application
	 * @param string $clientSecret application secret key
 	 * @param string $accessTokenUrl access token url
	 * @param string $dialogUrl dialog url
	 * @param string $responseType response type (for example: code)
	 * @param string $redirectUri redirect uri
	 * @param string $scope access scope (for example: friends,video,offline)
	 */
	public function __construct($clientId, $clientSecret, $accessTokenUrl, $dialogUrl, $responseType, $redirectUri = null, $scope = null)
	{
		$this->_clientId = $clientId;
		$this->_clientSecret = $clientSecret;
		$this->_accessTokenUrl = $accessTokenUrl;
		$this->_dialogUrl = $dialogUrl;
		$this->_responseType = $responseType;
		$this->_redirectUri = $redirectUri;
		$this->_scope = $scope;
	}

	/**
	 * Authorize client.
	 */
	public function authorize()
	{
		if(!isset ($_SESSION))
			session_start();

		$result = false;

		if(isset($_SESSION['vkPhpSdk']['authJson'. $this->_clientId]))
		{
			$this->_authJson = $_SESSION['vkPhpSdk']['authJson'. $this->_clientId];
			$result = true;
		}
		else
		{
			if(!(isset($_REQUEST['code']) && $_REQUEST['code']))
			{
				$_SESSION['vkPhpSdk']['state'] = md5(uniqid(rand(), true)); // CSRF protection

				$this->_dialogUrl .= '?client_id=' . $this->_clientId;
				$this->_dialogUrl .= '&redirect_uri=' . $this->_redirectUri;
				$this->_dialogUrl .= '&scope=' . $this->_scope;
				$this->_dialogUrl .= '&response_type=' . $this->_responseType;
				$this->_dialogUrl .= '&state=' . $_SESSION['vkPhpSdk']['state'];

				echo("<script>top.location.href='" . $this->_dialogUrl . "'</script>");
			}
			elseif($_REQUEST['state'] === $_SESSION['vkPhpSdk']['state'])
			{
				$this->_authJson = file_get_contents($this->_accessTokenUrl
				    .'?client_id='.$this->_clientId
				    .'&client_secret='.$this->_clientSecret
				    .'&code='.$_REQUEST['code']
				    .'&redirect_uri='.$this->_redirectUri
				);

				if($this->_authJson !== false)
				{
					$_SESSION['vkPhpSdk']['authJson'. $this->_clientId] = $this->_authJson;
					$result = true;
				}
				else
					$result = false;
			}
		}

		return $result;
	}

	/**
	 * Get access token.
	 *
	 * @return string
	 */
	public function getAccessToken()
	{
		if ($this->_accessParams === null)
			$this->_accessParams = json_decode($this->getAuthJson(), true);
		return $this->_accessParams['access_token'];
	}

	/**
	 * Get expires time.
	 *
	 * @return string
	 */
	public function getExpiresIn()
	{
		if ($this->_accessParams === null)
			$this->_accessParams = json_decode($this->getAuthJson(), true);
		return $this->_accessParams['expires_in'];
	}

	/**
	 * Get user id.
	 *
	 * @return string
	 */
	public function getUserId()
	{
		if ($this->_accessParams === null)
			$this->_accessParams = json_decode($this->getAuthJson(), true);
		return $this->_accessParams['user_id'];
	}

	/**
	 * Get authorization JSON string.
	 *
	 * @return string
	 */
	protected function getAuthJson()
	{
		return $this->_authJson;
	}
}


text:
moxdev.github.io
================

My DBC Phase 0 github pages site!


text:
<?php
	$border_bottom = 'style="border-bottom: 10px solid '.$accent_2.' !important;"';
	$btn_bg = 'style="background-color:'.$accent_1.' !important"';
?>
<?php echo '';?>
<?php echo '';?>
<?php echo '';?>

        <div class='well bm-well' <?php echo $border_bottom?>>

<?php echo (isset($translations[13]['Translation'])?$translations[13]['Translation']:'');?>
			<?php //echo $translations[13]['Translation'];?>

<?php if (isset($customerLanguages['Page1heading'])) { echo ($customerLanguages['Page1heading']); } ?>

              <form>

                  <?php if (isset($translations[0]['Translation'])) { echo strtoupper($translations[0]['Translation']); } ?>
                  <input name='sc1[Orderid]' type="text" class="form-control" id="f2">
                  <?php echo (isset($translations[14]['Translation'])?$translations[14]['Translation']:'');?>
  				<?php //echo $translations[14]['Translation'];?>

                  <?php if (isset($translations[1]['Translation'])) { echo strtoupper($translations[1]['Translation']); } ?>
                  <input type="text" name='sc1[email]' class="form-control" id="f1">
                  <?php echo (isset($translations[28]['Translation'])?$translations[28]['Translation']:'');?>
  				<?php //echo $translations[28]['Translation']?>

                <button type='submit' class='btn btn-raised btn-block btn-success btn-bm' id='button1' <?php echo $btn_bg?>><?php if (isset($translations[7]['Translation'])) { echo strtoupper($translations[7]['Translation']); } ?></button>

                  <?php echo $translations[16]['Translation']?>
                  <?php echo $translations[15]['Translation']?>

              </form>

        <div class='well bm-well' <?php echo $border_bottom?>>

<?php echo (isset($translations[17]['Translation'])?$translations[17]['Translation']:'');?>
			<?php //echo $translations[17]['Translation']?>

<?php echo $customerLanguages['Page2heading']?>

                    	 <?php echo $translations[2]['Translation'];?>
                    <?php echo $translations[3]['Translation'];?>
                    <?php echo $translations[4]['Translation'];?>
                    <?php echo $translations[5]['Translation'];?>

                            <input type="checkbox" value='3444'>

                      VIVALLO COATIGAN_EBONY

                      € 34.44

                            <input type="checkbox" value='3444'>

                      VIVALLO COATIGAN_EBONY

                      € 34.44

                            <input type="checkbox" value='3444'>

                      VIVALLO COATIGAN_EBONY

                      € 34.44

                            <input type="checkbox" value='3444'>

                      VIVALLO COATIGAN_EBONY

                      € 34.44

<?php echo $translations[6]['Translation'];?>: € 0.00

              <button type='submit' class='btn btn-raised btn-block btn-success btn-bm' id='button2' <?php echo $btn_bg?>><?php echo strtoupper($translations[7]['Translation']);?></button>

                Whoops!
                Please select at least one item to return.

                Whoops!
                Please select the return reason.

        <div class='well bm-well' <?php echo $border_bottom?>>

<?php echo $translations[8]['Translation'];?>

<?php echo $customerLanguages['Page3heading']?>

                  <?php echo $translations[9]['Translation'];?>
                  <?php echo $translations[10]['Translation'];?>

                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Print your label

                    Dear Customer

                    You can print your label by following this link: Print label

                    You can read additional instructions for returning your order based on the carrier you chose by following this link: Go to the carriers web-portal

                    Additionally all of this information has been forwarded to your email address.

                    Thank you for using our service.

                    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

              Email
              <input type="text" id='emailConfirm' value='' class="form-control" id="f1">
              Select at email where you would like to recieve your label

            <button type='submit' class='btn btn-raised btn-block btn-success btn-bm' id='button3' <?php echo $btn_bg?>>
            <?php echo (isset($translations[20]['Translation'])?$translations[20]['Translation']:'');?>
            </button>

              <?php echo $translations[21]['Translation']?>
              <?php echo $translations[22]['Translation']?>

              Whoops!
              Something went wrong, please refresh the page and try again.

        <div class='well bm-well' <?php echo $border_bottom?>>

Thank You!

<?php echo $customerLanguages['Page4heading']?>

          Dear Customer

          You can print your label by following this link: Print label

          You can read additional instructions for returning your order based on the carrier you chose by following this link: Go to the carriers web-portal

          Additionally all of this information has been forwarded to your email address.

          Thank you for using our service.

        <div class='well bm-well' <?php echo $border_bottom?>>

Thank You!

<?php echo $customerLanguages['Page4heading']?>

          Dear Customer

          At this moment our servers are too busy to proccess your request. As soon as we are able, we will send you and email confirmation with the label and further instructions on what to do.

        <div class='well bm-well' <?php echo $border_bottom?>>

<?php echo (isset($translations[13]['Translation'])?$translations[13]['Translation']:'');?>

<?php if (isset($customerLanguages['Page1heading'])) { echo ($customerLanguages['Page1heading']); } ?>

              <form id="Form1-Mode1">

                  Whoops!
                  Something went wrong, please refresh the page and try again.

		                        Order ID
		                        <input name="OrderId" id="OrderId" type="text" class="form-control" maxlength="35">
		                        Enter Order Number

                        First Name
                        <input name="Consumername1" id="Consumername1" type="text" class="form-control" maxlength="35">
                        Enter First Name

                        Last Name
                        <input name="Consumername2" id="Consumername2" type="text" class="form-control" maxlength="35">
                        Enter Last Name

                        Email
                        <input name="ConsumerEmail" id="ConsumerEmail" type="email" class="form-control" maxlength="255">
                        Enter email address to send label

                        Street
                        <input name="ConsumerShipStreet1" id="ConsumerShipStreet1" type="text" class="form-control" maxlength="35">
                        Enter Street

                        House Number
                        <input name="ConsumerFromShipHouseNumber" id="ConsumerFromShipHouseNumber" type="text" class="form-control" maxlength="15">
                        Enter House Number

                        PostalCode
                        <input name="ConsumerFromShipPostalCode" id="ConsumerFromShipPostalCode" type="text" class="form-control" maxlength="10">
                        Enter PostalCode

                        City
                        <input name="ConsumerFromShipCity" id="ConsumerFromShipCity" type="text" class="form-control" maxlength="35">
                        Enter City

                        State
                        <input name="Consumershipstate" id="Consumershipstate" type="text" class="form-control" maxlength="35">
                        Enter State

                        Country

                            <?php
                              //echo json_encode($customerCountries);
                              echo '<select class="form-control" id="ConsumerFromShipCountry" name="ConsumerFromShipCountry">';
                              echo '<option value="-1">Select a Country ↓</option>';
                              for ($i=0; $i<count($customerCountries); $i++) {
                                if ( $customerCountries[$i]['IsActive'] ) {
                                  echo '<option value="' . $customerCountries[$i]['CountryCode'].'">' . $customerCountries[$i]['CountryName'] . '</option>';
                                }
                              }
                              echo '</select>';
                            ?>

                <button type='submit' class='btn btn-raised btn-block btn-success btn-bm' id='button1' <?php echo $btn_bg?>>
                  <?php if (isset($translations[7]['Translation'])) { echo strtoupper($translations[7]['Translation']); } ?>
                </button>

              </form>

Operation mode not available. Please contact administrator.

  <?php
    echo "";
    echo "";
    echo "";
        if ( $Mode == 1 ) {
          if ( $om1 == true ) {
            echo "";
          } else {
            echo "";
          }
        }
        if ( $Mode == 2 ) {
          if ( $om2 == true ) {
            echo "";
          } else {
            echo "";
          }
        }
  ?>


text:
function out = nsdims(A)
    % nsdims(A) finds the number of non-singleton dimensions of A
    sizeA = size(A);
    sizeA(sizeA == 1) = [];
    out = length(sizeA);
end


text:
<?php

namespace TerAelis\ForumBundle\Entity;

use Doctrine\ORM\EntityRepository;

/**
 * BaliseRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class BaliseRepository extends EntityRepository
{
    public function getCategorie($idCategorie) {

        return $this->createQueryBuilder('b')
            ->join('b.categorie', 'c')
            ->where('c.id = :id')
            ->setParameter('id', $idCategorie);
    }
}


text:
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.groovy.dsl;

import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiType;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.containers.FList;
import groovy.lang.Closure;
import groovy.lang.GroovyObjectSupport;
import groovy.lang.MetaMethod;
import org.codehaus.groovy.runtime.DefaultGroovyMethods;
import org.codehaus.groovy.runtime.InvokerHelper;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.plugins.groovy.dsl.dsltop.GdslMembersProvider;
import org.jetbrains.plugins.groovy.dsl.holders.CustomMembersHolder;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrMethodCall;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression;
import org.jetbrains.plugins.groovy.lang.psi.util.GroovyPropertyUtils;
import org.jetbrains.plugins.groovy.lang.psi.util.PsiUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static org.jetbrains.plugins.groovy.dsl.DescriptorsKt.*;

/**
 * @author peter
 */
public class CustomMembersGenerator extends GroovyObjectSupport implements GdslMembersHolderConsumer {
  private static final GdslMembersProvider[] PROVIDERS = GdslMembersProvider.EP_NAME.getExtensions();
  public static final @NonNls String THROWS = "throws";
  private FList<@NotNull Descriptor> myDeclarations = FList.emptyList();
  private final List<CustomMembersHolder> myMemberHolders = new ArrayList<>();
  private final GroovyClassDescriptor myDescriptor;
  @Nullable private final Map<String, List> myBindings;

  public CustomMembersGenerator(@NotNull GroovyClassDescriptor descriptor, @Nullable Map<String, List> bindings) {
    myDescriptor = descriptor;
    myBindings = bindings;
  }

  @Override
  public PsiElement getPlace() {
    return myDescriptor.getPlace();
  }

  @Override
  @Nullable
  public PsiClass getClassType() {
    return getPsiClass();
  }

  @Override
  public PsiType getPsiType() {
    return myDescriptor.getPsiType();
  }

  @Nullable
  @Override
  public PsiClass getPsiClass() {
    return myDescriptor.getPsiClass();
  }

  @Override
  public GlobalSearchScope getResolveScope() {
    return myDescriptor.getResolveScope();
  }

  @Override
  public Project getProject() {
    return myDescriptor.getProject();
  }

  @Nullable
  public List<CustomMembersHolder> getMembersHolder() {
    if (!myDeclarations.isEmpty()) {
      addMemberHolder(new CustomMembersHolderImpl(myDeclarations));
    }
    return myMemberHolders;
  }

  @Override
  public void addMemberHolder(CustomMembersHolder holder) {
    myMemberHolders.add(holder);
  }

  private Object[] constructNewArgs(Object[] args) {
    final Object[] newArgs = new Object[args.length + 1];
    //noinspection ManualArrayCopy
    for (int i = 0; i < args.length; i++) {
      newArgs[i] = args[i];
    }
    newArgs[args.length] = this;
    return newArgs;
  }

  /** **********************************************************
   Methods to add new behavior
   *********************************************************** */
  public void property(Map<Object, Object> args) {
    if (args == null) return;

    String name = (String)args.get("name");
    Object type = args.get("type");
    Object doc = args.get("doc");
    Object docUrl = args.get("docUrl");
    Boolean isStatic = (Boolean)args.get("isStatic");

    Map<@NonNls Object, Object> getter = new HashMap<>();
    getter.put("name", GroovyPropertyUtils.getGetterNameNonBoolean(name));
    getter.put("type", type);
    getter.put("isStatic", isStatic);
    getter.put("doc", doc);
    getter.put("docUrl", docUrl);
    method(getter);

    Map<@NonNls Object, @NonNls Object> setter = new HashMap<>();
    setter.put("name", GroovyPropertyUtils.getSetterName(name));
    setter.put("type", "void");
    setter.put("isStatic", isStatic);
    setter.put("doc", doc);
    setter.put("docUrl", docUrl);
    final HashMap<Object, Object> param = new HashMap<>();
    param.put(name, type);
    setter.put("params", param);
    method(setter);
  }

  public void constructor(Map<Object, Object> args) {
    if (args == null) return;

    args.put("constructor", true);
    method(args);
  }

  public NamedParameterDescriptor parameter(Map<?, ?> args) {
    return parseNamedParameter(args);
  }

  public void method(Map<?, ?> args) {
    if (args == null) {
      return;
    }
    myDeclarations = myDeclarations.prepend(parseMethod(args));
  }

  public void methodCall(Closure<Map<Object, Object>> generator) {
    PsiElement place = myDescriptor.getPlace();

    PsiElement parent = place.getParent();
    if (isMethodCall(place, parent)) {
      assert parent instanceof GrMethodCall && place instanceof GrReferenceExpression;

      GrReferenceExpression ref = (GrReferenceExpression)place;

      PsiType[] argTypes = PsiUtil.getArgumentTypes(ref, false);
      if (argTypes == null) return;

      String[] types =
      ContainerUtil.map(argTypes, PsiType::getCanonicalText, new String[argTypes.length]);

      generator.setDelegate(this);

      HashMap<String, Object> args = new HashMap<>();
      args.put("name", ref.getReferenceName());
      args.put("argumentTypes", types);
      generator.call(args);
    }
  }

  private static boolean isMethodCall(PsiElement place, PsiElement parent) {
    return place instanceof GrReferenceExpression &&
        parent instanceof GrMethodCall &&
        ((GrMethodCall)parent).getInvokedExpression() == place;
  }

  @SuppressWarnings("UnusedDeclaration")
  public void closureInMethod(Map<Object, Object> args) {
    if (args == null) {
      return;
    }
    ClosureDescriptor descriptor = parseClosure(args);
    if (descriptor == null) {
      return;
    }
    myDeclarations = myDeclarations.prepend(descriptor);
  }

  public void variable(Map<Object, Object> args) {
    if (args == null) {
      return;
    }
    myDeclarations = myDeclarations.prepend(parseVariable(args));
  }

  @SuppressWarnings("UnusedDeclaration")
  @Nullable
  public Object methodMissing(String name, Object args) {
    final Object[] newArgs = constructNewArgs((Object[])args);

    // Get other DSL methods from extensions
    for (GdslMembersProvider provider : PROVIDERS) {
      final List<MetaMethod> variants = DefaultGroovyMethods.getMetaClass(provider).respondsTo(provider, name, newArgs);
      if (variants.size() == 1) {
        return InvokerHelper.invokeMethod(provider, name, newArgs);
      }
    }
    return null;
  }

  @SuppressWarnings("UnusedDeclaration")
  @Nullable
  public Object propertyMissing(String name) {
    if (myBindings != null) {
      final List list = myBindings.get(name);
      if (list != null) {
        return list;
      }
    }

    return null;
  }
}


text:
                Login

                <form class="form-signin"
                      name="form"
                      ng-submit="login(form)"
                      novalidate>

                            <input type="text"
                                   class="form-control"
                                   placeholder="Email address"
                                   name="email"
                                   ng-model="user.email"
                                   required
                                   autofocus
                                   mongoose-error>

                            {{ errors.email }}

                            <input type="password"
                                   class="form-control"
                                   placeholder="Password"
                                   name="password"
                                   ng-model="user.password"
                                   required
                                   mongoose-error>

                            {{ errors.password }}

{{ error.other }}

                    <button class="btn btn-lg btn-primary btn-block"
                            type="submit"
                            ng-disabled="form.$invalid"> Login </button>

                </form>


text:
@interface ViewController : UIViewController

//Step 15 - Design the View and make a bunch of outlets
@property (weak, nonatomic) IBOutlet UIView *containerView;
@property (weak, nonatomic) IBOutlet UILabel *locationLabel;
@property (weak, nonatomic) IBOutlet UILabel *currentTempLabel;
@property (weak, nonatomic) IBOutlet UILabel *feelsLikeTempLabel;
@property (weak, nonatomic) IBOutlet UILabel *weatherDescriptionLabel;
@property (weak, nonatomic) IBOutlet UILabel *windDescriptionLabel;
@property (weak, nonatomic) IBOutlet UILabel *humidityLabel;
@property (weak, nonatomic) IBOutlet UILabel *dewpointLabel;
@property (weak, nonatomic) IBOutlet UILabel *lastUpdateLabel;

@property (weak, nonatomic) IBOutlet UIImageView *currentConditionImageView;

@property (strong, nonatomic) UIActivityIndicatorView *indicator;

- (void)updateUIWithWeatherObservation:(WeatherObservation *)inWeatherObservation;

@end


text:
package nl.tudelft.watchdog.logic.interval;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

import java.util.ArrayList;
import java.util.Date;

import nl.tudelft.watchdog.core.logic.document.Document;
import nl.tudelft.watchdog.core.logic.interval.intervaltypes.IDEOpenInterval;
import nl.tudelft.watchdog.core.logic.interval.intervaltypes.EditorIntervalBase;
import nl.tudelft.watchdog.core.logic.interval.intervaltypes.IntervalBase;
import nl.tudelft.watchdog.core.logic.interval.intervaltypes.ReadingInterval;
import nl.tudelft.watchdog.core.logic.interval.intervaltypes.TypingInterval;
import nl.tudelft.watchdog.core.logic.network.JsonTransferer;
import nl.tudelft.watchdog.core.ui.wizards.Project;
import nl.tudelft.watchdog.core.ui.wizards.User;
import nl.tudelft.watchdog.core.util.WatchDogGlobals;
import nl.tudelft.watchdog.core.util.WatchDogGlobals.IDE;
import nl.tudelft.watchdog.eclipse.logic.document.EditorWrapper;
import nl.tudelft.watchdog.eclipse.util.WatchDogUtils;

import org.eclipse.ui.texteditor.ITextEditor;
import org.junit.BeforeClass;
import org.junit.Test;
import org.mockito.Mockito;

/**
 * Test the transfer from {@link IInterval}s to JSon.
 */
public class JsonConverterTest {

	private JsonTransferer transferer = new JsonTransferer();

	@BeforeClass
	public static void setUp() {
		WatchDogGlobals.hostIDE = IDE.ECLIPSE;
	}

	public String pasteWDVAndClient() {
		return "\"wdv\":\"" + WatchDogGlobals.CLIENT_VERSION
				+ "\",\"ide\":\"ec\"";
	}

	/** Tests the format of the returned Json representation. */
	@Test
	public void testJsonReadingIntervalRepresentation() {
		ReadingInterval interval = new ReadingInterval(null, new Date());
		ArrayList<IntervalBase> intervals = createSampleIntervals(interval);

		assertEquals(
				"[{\"doc\":{\"pn\":\"f6f4da8d93e88a08220e03b7810451d3ba540a34\",\"fn\":\"90a8834de76326869f3e703cd61513081ad73d3c\",\"sloc\":1,\"dt\":\"pr\"},\"it\":\"re\",\"ts\":1,\"te\":2,\"ss\":\"\","
						+ pasteWDVAndClient() + "}]",
				transferer.toJson(intervals));
	}

	/**
	 * Tests the format of the returned Json representation, if one of the
	 * typing intervals does not have its ending document properly set.
	 */
	@Test
	public void testJsonTypingIntervalMissingDocumentRepresentation() {
		ITextEditor editor = Mockito.mock(ITextEditor.class);
		TypingInterval interval = new TypingInterval(new EditorWrapper(editor), new Date());
		ArrayList<IntervalBase> intervals = createSampleIntervals(interval);

		assertEquals(
				"[{\"doc\":{\"pn\":\"f6f4da8d93e88a08220e03b7810451d3ba540a34\",\"fn\":\"90a8834de76326869f3e703cd61513081ad73d3c\",\"sloc\":1,\"dt\":\"pr\"},\"it\":\"ty\",\"ts\":1,\"te\":2,\"ss\":\"\","
						+ pasteWDVAndClient() + "}]",
				transferer.toJson(intervals));
	}

	/** Tests the format of the returned Json representation. */
	@Test
	public void testJsonTypingIntervalTwoSameIntervalsRepresentation() {
		ITextEditor editor = Mockito.mock(ITextEditor.class);
		TypingInterval interval = new TypingInterval(new EditorWrapper(editor), new Date());
		interval.setDocument(new Document("Project", "filepath",
				"Production.java", "blah-document"));
		interval.setEndingDocument(new Document("Project", "Production.java",
				"filepath", "blah-document"));

		ArrayList<IntervalBase> intervals = createSampleIntervals(interval);

		assertEquals(
				"[{\"endingDocument\":{\"pn\":\"f6f4da8d93e88a08220e03b7810451d3ba540a34\",\"fn\":\"90a8834de76326869f3e703cd61513081ad73d3c\",\"sloc\":1,\"dt\":\"pr\"},\"diff\":0,\"doc\":{\"pn\":\"f6f4da8d93e88a08220e03b7810451d3ba540a34\",\"fn\":\"90a8834de76326869f3e703cd61513081ad73d3c\",\"sloc\":1,\"dt\":\"pr\"},\"it\":\"ty\",\"ts\":1,\"te\":2,\"ss\":\"\","
						+ pasteWDVAndClient() + "}]",
				transferer.toJson(intervals));
	}

	/** Tests the format of the returned Json representation. */
	@Test
	public void testJsonSessionIntervalRepresentation() {
		IntervalBase interval = new IDEOpenInterval(new Date());
		ArrayList<IntervalBase> intervals = createSampleIntervals(interval);

		assertEquals("[{\"it\":\"eo\",\"ts\":1,\"te\":2,\"ss\":\"\","
				+ pasteWDVAndClient() + "}]", transferer.toJson(intervals));
	}

	/**
	 * Tests the format of the returned Json representation, manually setting an
	 * IDE host.
	 */
	@Test
	public void testContainsIDEHost() {
		IntervalBase interval = new IDEOpenInterval(new Date());
		ArrayList<IntervalBase> intervals = createSampleIntervals(interval);

		assertEquals("[{\"it\":\"eo\",\"ts\":1,\"te\":2,\"ss\":\"\","
				+ pasteWDVAndClient() + "}]", transferer.toJson(intervals));
	}

	private ArrayList<IntervalBase> createSampleIntervals(
			EditorIntervalBase interval) {
		interval.setDocument(new Document("Project", "Production.java",
				"filepath", "blah-document"));
		ArrayList<IntervalBase> intervals = createSampleIntervals((IntervalBase) interval);
		return intervals;
	}

	private ArrayList<IntervalBase> createSampleIntervals(IntervalBase interval) {
		ArrayList<IntervalBase> intervals = new ArrayList<IntervalBase>();
		interval.close();
		sleepABit();
		interval.setStartTime(new Date(1));
		interval.setEndTime(new Date(2));
		interval.setSessionSeed("");
		intervals.add(interval);
		return intervals;
	}

	private void sleepABit() {
		Thread.yield();
		WatchDogUtils.sleep(200);
		Thread.yield();
	}

	@Test
	public void testUserHasWatchDogVersion() {
		String gsonRepresentation = WatchDogUtils.convertToJson(new User());
		boolean containsWDVersion = gsonRepresentation.contains("\"wdv\":\""
				+ WatchDogGlobals.CLIENT_VERSION + "\"");
		assertTrue(containsWDVersion);
	}

	@Test
	public void testProjectHasWatchDogVersion() {
		String gsonRepresentation =  WatchDogUtils.convertToJson(new Project(""));
		boolean containsWDVersion = gsonRepresentation.contains("\"wdv\":\""
				+ WatchDogGlobals.CLIENT_VERSION + "\"");
		assertTrue(containsWDVersion);
	}

}


text:
const { sort } = require('./sort');
const { bubbleSort } = require('./bubbleSort');
const { insertionSort } = require('./insertionSort');
const { selectionSort } = require('./selectionSort');
const { radixSort } = require('./radixSort');
const { heapSort } = require('./heapSort');
const { quickSort } = require('./quickSort');
const { mergeSort } = require('./mergeSort');

exports.bubbleSort = (list, compare) => (
  sort(bubbleSort, { list }, compare)
);

exports.insertionSort = (list, compare) => (
  sort(insertionSort, { list }, compare)
);

exports.selectionSort = (list, compare) => (
  sort(selectionSort, { list }, compare)
);

exports.radixSort = (list, order, getNumber) => (
  sort(radixSort, { list, order, getNumber })
);

exports.heapSort = (list, compare) => (
  sort(heapSort, { list }, compare)
);

exports.quickSort = (list, compare) => (
  sort(quickSort, { list }, compare)
);

exports.mergeSort = (list, compare) => (
  sort(mergeSort, { list }, compare)
);


text:
using System.Text.Json;
using Azure.Core;

namespace Azure.ResourceManager.Cdn.Models
{
    public partial class LoadBalancingSettings : IUtf8JsonSerializable
    {
        void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
        {
            writer.WriteStartObject();
            if (Optional.IsDefined(SampleSize))
            {
                writer.WritePropertyName("sampleSize");
                writer.WriteNumberValue(SampleSize.Value);
            }
            if (Optional.IsDefined(SuccessfulSamplesRequired))
            {
                writer.WritePropertyName("successfulSamplesRequired");
                writer.WriteNumberValue(SuccessfulSamplesRequired.Value);
            }
            if (Optional.IsDefined(AdditionalLatencyInMilliseconds))
            {
                writer.WritePropertyName("additionalLatencyInMilliseconds");
                writer.WriteNumberValue(AdditionalLatencyInMilliseconds.Value);
            }
            writer.WriteEndObject();
        }

        internal static LoadBalancingSettings DeserializeLoadBalancingSettings(JsonElement element)
        {
            Optional<int> sampleSize = default;
            Optional<int> successfulSamplesRequired = default;
            Optional<int> additionalLatencyInMilliseconds = default;
            foreach (var property in element.EnumerateObject())
            {
                if (property.NameEquals("sampleSize"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    sampleSize = property.Value.GetInt32();
                    continue;
                }
                if (property.NameEquals("successfulSamplesRequired"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    successfulSamplesRequired = property.Value.GetInt32();
                    continue;
                }
                if (property.NameEquals("additionalLatencyInMilliseconds"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    additionalLatencyInMilliseconds = property.Value.GetInt32();
                    continue;
                }
            }
            return new LoadBalancingSettings(Optional.ToNullable(sampleSize), Optional.ToNullable(successfulSamplesRequired), Optional.ToNullable(additionalLatencyInMilliseconds));
        }
    }
}


text:
<?php

include_once dirname(__FILE__) . '/' . 'renderer.php';
include_once dirname(__FILE__) . '/' . '../env_variables.php';
include_once dirname(__FILE__) . '/' . '../utils/html_utils.php';
include_once dirname(__FILE__) . '/' . '../utils/system_utils.php';

class ViewAllRenderer extends Renderer
{
    public $renderSingleRow;
    private $renderPageNavigator;

    #region Pages

    private function GetPageNavigator1(Page $page) {
        $this->renderPageNavigator = $page->GetShowTopPageNavigator();
        return $this->RenderDef($page->GetPageNavigator(), '', array('PageNavId' => 1));
    }

    private function GetPageNavigator2(Page $page) {
        $this->renderPageNavigator = $page->GetShowBottomPageNavigator();
        if ($page->GetShowBottomPageNavigator()){
            if ($page->GetShowTopPageNavigator())
                return $this->RenderDef($page->GetPageNavigator(), '', array('PageNavId' => 2));
            else
                return $this->RenderDef($page->GetPageNavigator(), '', array('PageNavId' => 1));
        }
        else
            return $this->RenderDef($page->GetPageNavigator(), '', array('PageNavId' => 2));
    }

    /**
     * @param Page $Page
     */
    public function RenderPage(Page $Page) {

        $this->SetHTTPContentTypeByPage($Page);
        $Page->BeforePageRender->Fire(array(&$Page));
        $Grid = $this->Render($Page->GetGrid());

        $layoutTemplate = $Page->GetCustomTemplate(PagePart::Layout, PageMode::ViewAll, 'common/layout.tpl');

        $this->DisplayTemplate('list/page.tpl',
            array(
                'Page' => $Page
            ),
            array(
                // Template override
                'LayoutTemplateName' => $layoutTemplate,

                // View datas
                'Authentication' => $Page->GetAuthenticationViewData(),
                'App' => $Page->GetListViewData(),

                // Rendered controls
                'Grid' => $Grid,
                'PageList' => $this->RenderDef($Page->GetReadyPageList()),
                'HideSideBarByDefault' => $Page->GetHidePageListByDefault(),
                'Variables' => $this->GetPageVariables($Page),

                'PageNavigator' => $this->GetPageNavigator1($Page),
                'PageNavigator2' => $this->GetPageNavigator2($Page)

            )
        );
    }

    /**
     * @inheritdoc
     */
    public function RenderDetailPageEdit($DetailPage)  {
        $this->SetHTTPContentTypeByPage($DetailPage);

        $Grid = $this->Render($DetailPage->GetGrid());

        if ($DetailPage->GetReadyPageList() != null)
            $pageList = $this->Render($DetailPage->GetReadyPageList());
        else
            $pageList = null;

        $isAdvancedSearchActive = false;
        $userFriendlySearchCondition = '';
        if (isset($DetailPage->AdvancedSearchControl)) {
            $isAdvancedSearchActive = $DetailPage->AdvancedSearchControl->IsActive();
            $userFriendlySearchCondition = $DetailPage->AdvancedSearchControl->GetUserFriendlySearchConditions();
            $linkBuilder = $DetailPage->CreateLinkBuilder();
            $linkBuilder->AddParameter(OPERATION_PARAMNAME, OPERATION_ADVANCED_SEARCH);
            $DetailPage->AdvancedSearchControl->SetOpenInNewWindowLink($linkBuilder->GetLink());
        }

        $layoutTemplate = $DetailPage->GetCustomTemplate(PagePart::Layout, PageMode::ViewAll, 'common/layout.tpl');

        $parentPage = $DetailPage->GetParentPage();

        $this->DisplayTemplate('list/detail_page_edit.tpl',
            array(
                'App' => $DetailPage->GetListViewData(),
                'Page' => $DetailPage,
                'DetailPage' => $DetailPage,
                'SiblingDetails' => $parentPage->GetGrid()->GetDetailLinksViewData(),
                'DetailPageName' => $DetailPage->GetHttpHandlerName(),
                'PageList' => $pageList,
                'PageNavigator' => $this->GetPageNavigator1($DetailPage),
                'PageNavigator2' => $this->GetPageNavigator2($DetailPage)
            ),
            array(
                'LayoutTemplateName' => $layoutTemplate,
                'Grid' => $Grid,
                'Authentication' => $DetailPage->GetAuthenticationViewData(),
                'AdvancedSearch' => isset($DetailPage->AdvancedSearchControl) ? $this->Render($DetailPage->AdvancedSearchControl) : '',
                'IsAdvancedSearchActive' => $isAdvancedSearchActive,
                'FriendlyAdvancedSearchCondition' => $userFriendlySearchCondition,
                'HideSideBarByDefault' => $DetailPage->GetHidePageListByDefault(),

                'MasterGrid' => $this->Render($DetailPage->GetMasterGrid()),
                'Variables' => $this->GetPageVariables($DetailPage)
            )
        );
    }

    #endregion

    #region Page parts

    public function RenderGrid(Grid $Grid) {
        $page = $Grid->GetPage();

        // Remove!!!
        if (isset($page->AdvancedSearchControl))
        {
            $linkBuilder = $page->CreateLinkBuilder();
            $linkBuilder->AddParameter(OPERATION_PARAMNAME, OPERATION_ADVANCED_SEARCH);
            $page->AdvancedSearchControl->SetOpenInNewWindowLink($linkBuilder->GetLink());
        }

        $template = $this->renderSingleRow ? 'list/single_row.tpl' : 'list/grid.tpl';
        if (!$this->renderSingleRow)
            $template = $page->GetCustomTemplate(PagePart::Grid, PageMode::ViewAll, $template);
        $this->DisplayTemplate(
            $template,
            array(
                'Grid' => $Grid,
                'Page' => $Grid->GetPage(),
                'DataGrid' => $Grid->GetViewData($this)
            ),
            array(
                'SingleRowTemplate' => $page->GetCustomTemplate(PagePart::GridRow, PageMode::ViewAll, 'list/single_row.tpl'),
                'AdvancedSearchControl' => $page->AdvancedSearchControl,

                // Remove!!!
                'HiddenValues' => $Grid->GetHiddenValues(),
                'TextsForHighlight' =>
                    $page->AdvancedSearchControl ?
                        array_map(Q::L('($v) => StringUtils::JSStringLiteral($v)'),
                            $page->AdvancedSearchControl->GetHighlightedFieldText()
                        ):
                        array(),
                'HighlightOptions' =>
                    $page->AdvancedSearchControl ?
                        $page->AdvancedSearchControl->GetHighlightedFieldOptions() :
                        array(),

                'Authentication' => $page->GetAuthenticationViewData(),

                'Columns' => $Grid->GetViewColumns(),
                'Bands' => $Grid->GetViewBands(),
                'FilterBuilder' => $Grid->GetFilterBuilder()->GetViewData(),
                'ActiveFilterBuilderJson' => $Grid->GetFilterBuilder()->GetActiveFilterAsJson(),
                'ActiveFilterBuilderAsString' => $Grid->GetFilterBuilder()->GetActiveFilterAsString(),
                'IsActiveFilterEmpty' => $Grid->GetFilterBuilder()->IsEmpty()
            )
        );
    }

    public function RenderCustomPageNavigator(CustomPageNavigator $pageNavigator) {
        $templateName = 'custom_page_navigator.tpl'; // here $pageNavigator->GetNavigationStyle() == NS_LIST
        if ($pageNavigator->GetNavigationStyle() == NS_COMBOBOX)
            $templateName = 'combo_box_custom_page_navigator.tpl';

        $this->DisplayTemplate('list/'.$templateName,
            array(
                    'PageNavigator' => $pageNavigator,
                    'PageNavigatorPages' => $pageNavigator->GetPages()),
                array()
                );
    }

    public function RenderCompositePageNavigator($PageNavigator) {
        $this->DisplayTemplate('list/composite_page_navigator.tpl',
            array(
                'PageNavigator' => $PageNavigator
            ),
            array()
        );
    }

    public function RenderPageNavigator($PageNavigator) {
        if ($this->renderPageNavigator) {
            $this->DisplayTemplate('list/page_navigator.tpl',
                array(
                    'PageNavigator' => $PageNavigator,
                    'PageNavigatorPages' => $PageNavigator->GetPages()),
                array()
            );
        }
        else {
            $this->result = '';
        }
    }

    #endregion

    #region Column rendering options

    protected function ShowHtmlNullValue()
    {
        return true;
    }

    #endregion
}

class ErrorStateRenderer extends ViewAllRenderer
{
    /** @var  Exception */
    private $exception;

    public function  __construct($captions, $exception)
    {
        parent::__construct($captions);
        $this->exception = $exception;
    }

    function RenderPage(Page $Page)
    {
        $this->SetHTTPContentTypeByPage($Page);

        $PageList = $Page->GetPageList();
        $PageList = isset($PageList) ? $this->Render($PageList) : '';

        $displayDebugInfo = DebugUtils::GetDebugLevel();

        $inputValues = array(
            'PageList' => $PageList,
            'ErrorMessage' => $this->exception->getMessage(),
            'DisplayDebugInfo' => $displayDebugInfo
        );

        if ($displayDebugInfo == 1) {
            $inputValues['File'] = $this->exception->getFile();
            $inputValues['Line'] = $this->exception->getLine();
            $inputValues['Trace'] = $this->exception->getTraceAsString();
        }

        $this->DisplayTemplate('list/error_page.tpl',
            array('Page' => $Page),
            $inputValues
        );
    }
}


text:
require 'bibmix'

module Bibmix
	class TitleAttributeValidator
		include ReferenceValidatorAbstract

		def self.is_valid_reference(reference)
			reference.title.is_a?(String) && !reference.title.empty?
		end
	end
end


text:
<?php
/**
* ValueObject da classe Client
*
* @example como seria usado a classe
* $sql = "SELECT * FROM usuarios";
*
* $query=$conexao->prepare($sql);
* $query->execute();
* $rs = $query->fetchAll(PDO::FETCH_CLASS,"usuariosVO") or die(print_r($query->errorInfo(), true));
*
* foreach ($rs as $key => $row){
*    //usando os métodos get da classe usuariosVO
*
*    echo $row->getId() . "
\n";
*    echo $row->getNome() . "
\n";
*    echo $row->getLogin() . "
\n";
*    echo $row->getSenha() . "

\n\n";
**/
namespace model;
class ClientesVO
{
    private $id    = 0;
    private $nome  = "";
    private $email = "";

# system
    public function __construct(){}
    private function __clone(){}
    public function __destruct()
    {
        foreach ($this as $key => $value) {
            unset($this->key);
        }
        foreach (array_keys(get_defined_vars()) as $var) {
            unset(${"$var"});
        }
        unset($var); // so para ter certeza
    }
    public function getID(){return $this->id;}
    public function setID($id)
    {
        $this->id = intval($id);
    }
    public function getNome(){return $this->nome;}
    public function setNome($nome)
    {
        $this->nome = $nome;
    }
    public function getEmail(){return $this->email;}
    public function setEmail($email)
    {
        $this->email = $email;
    }
}


text:
#region Usings

using System;
using System.Collections.Generic;

#endregion

namespace de.ahzf.Styx
{

    /// <summary>
    /// The ActionPipe is much like the IdentityPipe, but calls
    /// an Action <S> on every consuming object before
    /// returing them.
    /// </summary>
    /// <typeparam name="S">The type of the consuming objects.</typeparam>
    public class ActionPipe<S> : AbstractPipe<S, S>
    {

        #region Data

        private Action<S> _Action;

        #endregion

        #region Constructor(s)

        #region ActionPipe(myAction)

        /// <summary>
        /// Creates a new ActionPipe using the given Action<S>.
        /// </summary>
        /// <param name="myAction">An Action<S> to be called on every consuming object.</param>
        public ActionPipe(Action<S> myAction)
        {

            if (myAction == null)
                throw new ArgumentNullException("myAction must not be null!");

            _Action = myAction;

        }

        #endregion

        #endregion

        #region MoveNext()

        /// <summary>
        /// Advances the enumerator to the next element of the collection.
        /// </summary>
        /// <returns>
        /// True if the enumerator was successfully advanced to the next
        /// element; false if the enumerator has passed the end of the
        /// collection.
        /// </returns>
        public override Boolean MoveNext()
        {

            if (_InternalEnumerator == null)
                return false;

            if (_InternalEnumerator.MoveNext())
            {
                _CurrentElement = _InternalEnumerator.Current;
                _Action(_CurrentElement);
                return true;
            }

            return false;

        }

        #endregion

    }

}


text:
package org.gradoservice.mapRender.geo.projection;

import org.gradoservice.mapRender.geo.LatLng;
import org.gradoservice.mapRender.geo.LatLngBounds;
import org.gradoservice.mapRender.geometry.Bounds;
import org.gradoservice.mapRender.geometry.Point;

/**
 * Created with IntelliJ IDEA.
 * User: germanosin
 * Date: 19.02.14
 * Time: 17:15
 */
public class SphericalMercator  implements IProjection {
    public static final double R = 6378137.0;

    private static volatile SphericalMercator instance;

    public static SphericalMercator getInstance() {
        SphericalMercator localInstance = instance;
        if (localInstance == null) {
            synchronized (SphericalMercator.class) {
                localInstance = instance;
                if (localInstance == null) {
                    instance = localInstance = new SphericalMercator();
                }
            }
        }
        return localInstance;
    }

    private final Bounds bounds;

    public SphericalMercator() {
        double d = R * Math.PI;
        double[][] defaultBounds = {{-d, -d},{d, d}};
        bounds = new Bounds(defaultBounds);
    }

    @Override
    public Point project(LatLng latLng) {

        double d = Math.PI / 180;
        double max = 1 - 1E-15;
        double sin =  Math.max(Math.min(Math.sin(latLng.getLat() * d), max), -max);

        return new Point(
                R * latLng.getLng() * d,
                R * Math.log((1 + sin) / (1 - sin)) / 2);
    }

    @Override
    public LatLng unproject(Point point) {

        double d = 180 / Math.PI;

        return new LatLng(
                (2 * Math.atan(Math.exp(point.getY() / R)) - (Math.PI / 2)) * d,
                point.getX() * d / R);
    }

    @Override
    public Bounds bounds() {
        return bounds;
    }
}


text:
{% extends "app.html" %}

{% block title %}Dashboard{% endblock %}

{% block content %}

    {% if students %}

                Student
                Applying for

              {% for student in students %}

                    {{ student }}

                  {{ student.matriculation_semester }}

              {% endfor %}

    {% else %}

No students? Inconceivable!

            All interactions with College Conductor stem
            from an individual student.

            Add your first student
            by clicking the "Add student" button
            in the sidebar.

    {% endif %}

{% endblock %}

{% block entry %}

{% endblock %}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Array_Shape_Detection
{
    public class Matrix<T>
    {

        public Matrix()
        {
            Points = new List<List<T>>();
        }

        public Matrix(List<List<T>> data)
        {
            Points = data;
        }

        public List<List<T>> Points { get; private set; }

        public int Length
        {
            get
            {
                return Points.Count;
            }
        }

        public T[] this[int y]
        {
            get
            {
                return GetRowAt(y);
            }
        }

        public T this[Point point]
        {
            get
            {
                return GetItemAt(point);
            }
        }

        public T[] GetRowAt(int y)
        {
            return Points[y].ToArray();
        }

        public T GetItemAt(int x, int y)
        {
            return Points[y][x];
        }

        public T GetItemAt(Point point)
        {
            return Points[point.Y][point.X];
        }

        public T[][] GetAsArray()
        {
            return Points.Select(Enumerable.ToArray).ToArray();
        }

        public void AddRow(T[] row)
        {
            Points.Add(new List<T>(row));
        }

        public void AddRows(T[][] rows)
        {
            for(int i = 0; i < rows.Length; i++)
            {
                Points.Add(new List<T>(rows[i]));
            }
        }

        public void InsertRow(int index, T[] row)
        {
            Points.Insert(index, new List<T>(row));
        }

        public void RemoveRow(int index)
        {
            Points.RemoveAt(index);
        }

        public void ChangeRow(int index, T[] row)
        {
            Points[index] = new List<T>(row);
        }

        public void SetItem(int x, int y, T value)
        {
            Points[y][x] = value;
        }
    }
}


text:
namespace ash {

namespace {

namespace em = ::enterprise_management;

void WaitForShutdownButtonVisibility(bool visible) {
  int ui_update_count = LoginScreenTestApi::GetUiUpdateCount();
  while (LoginScreenTestApi::IsShutdownButtonShown() != visible) {
    LoginScreenTestApi::WaitForUiUpdate(ui_update_count);
    ui_update_count = LoginScreenTestApi::GetUiUpdateCount();
  }
}

}  // namespace

class ShutdownPolicyBaseTest
    : public policy::DevicePolicyCrosBrowserTest,
      public DeviceSettingsService::Observer {
 protected:
  ShutdownPolicyBaseTest() {}
  ~ShutdownPolicyBaseTest() override {}

  // DeviceSettingsService::Observer:
  void DeviceSettingsUpdated() override {
    if (run_loop_)
      run_loop_->Quit();
  }

  // policy::DevicePolicyCrosBrowserTest:
  void SetUpOnMainThread() override {
    policy::DevicePolicyCrosBrowserTest::SetUpOnMainThread();
    tray_test_api_ = SystemTrayTestApi::Create();
  }

  // Updates the device shutdown policy and sets it to |reboot_on_shutdown|.
  void UpdateRebootOnShutdownPolicy(bool reboot_on_shutdown) {
    policy::DevicePolicyBuilder* builder = device_policy();
    ASSERT_TRUE(builder);
    em::ChromeDeviceSettingsProto& proto(builder->payload());
    proto.mutable_reboot_on_shutdown()->set_reboot_on_shutdown(
        reboot_on_shutdown);
  }

  // Refreshes device policy and waits for it to be applied.
  void SyncRefreshDevicePolicy() {
    run_loop_ = std::make_unique<base::RunLoop>();
    DeviceSettingsService::Get()->AddObserver(this);
    RefreshDevicePolicy();
    run_loop_->Run();
    DeviceSettingsService::Get()->RemoveObserver(this);
    run_loop_.reset();
  }

  // Blocks until the OobeUI indicates that the javascript side has been
  // initialized.
  void WaitUntilOobeUIIsReady(OobeUI* oobe_ui) {
    ASSERT_TRUE(oobe_ui);
    base::RunLoop run_loop;
    const bool oobe_ui_ready = oobe_ui->IsJSReady(run_loop.QuitClosure());
    if (!oobe_ui_ready)
      run_loop.Run();
  }

  bool result_;
  std::unique_ptr<base::RunLoop> run_loop_;
  std::unique_ptr<SystemTrayTestApi> tray_test_api_;
};

class ShutdownPolicyInSessionTest
    : public ShutdownPolicyBaseTest {
 public:
  ShutdownPolicyInSessionTest(const ShutdownPolicyInSessionTest&) = delete;
  ShutdownPolicyInSessionTest& operator=(const ShutdownPolicyInSessionTest&) =
      delete;

 protected:
  ShutdownPolicyInSessionTest() {}
  ~ShutdownPolicyInSessionTest() override {}

  // Opens the system tray menu. This creates the tray views.
  void OpenSystemTrayMenu() { tray_test_api_->ShowBubble(); }

  // Closes the system tray menu. This deletes the tray views.
  void CloseSystemTrayMenu() { tray_test_api_->CloseBubble(); }

  // Returns true if the shutdown button's tooltip matches |tooltip|.
  bool HasShutdownButtonTooltip(const std::string& tooltip) {
    std::u16string actual_tooltip =
        tray_test_api_->GetBubbleViewTooltip(VIEW_ID_QS_POWER_BUTTON);
    return base::UTF8ToUTF16(tooltip) == actual_tooltip;
  }
};

// Tests that by default the shutdown button tooltip is "Shut down".
IN_PROC_BROWSER_TEST_F(ShutdownPolicyInSessionTest, TestBasic) {
  OpenSystemTrayMenu();
  EXPECT_TRUE(HasShutdownButtonTooltip("Shut down"));
  CloseSystemTrayMenu();
}

// Tests that enabling the reboot-on-shutdown policy changes the shutdown button
// tooltip to "restart". Note that the tooltip doesn't change dynamically if the
// menu is open during the policy change -- that's a rare condition and
// supporting it would add complexity.
//
// TODO(crbug.com/851208): Disabled test due to flakiness.
IN_PROC_BROWSER_TEST_F(ShutdownPolicyInSessionTest, DISABLED_PolicyChange) {
  // Change the policy to reboot and let it propagate over mojo to ash.
  UpdateRebootOnShutdownPolicy(true);
  SyncRefreshDevicePolicy();
  content::RunAllPendingInMessageLoop();

  OpenSystemTrayMenu();
  EXPECT_TRUE(HasShutdownButtonTooltip("Restart"));
  CloseSystemTrayMenu();

  // Change the policy to shutdown and let it propagate over mojo to ash.
  UpdateRebootOnShutdownPolicy(false);
  SyncRefreshDevicePolicy();
  content::RunAllPendingInMessageLoop();

  OpenSystemTrayMenu();
  EXPECT_TRUE(HasShutdownButtonTooltip("Shut down"));
  CloseSystemTrayMenu();
}

class ShutdownPolicyLockerTest : public ShutdownPolicyBaseTest {
 public:
  ShutdownPolicyLockerTest(const ShutdownPolicyLockerTest&) = delete;
  ShutdownPolicyLockerTest& operator=(const ShutdownPolicyLockerTest&) = delete;

 protected:
  ShutdownPolicyLockerTest() = default;
  ~ShutdownPolicyLockerTest() override = default;

  void SetUpInProcessBrowserTestFixture() override {
    ShutdownPolicyBaseTest::SetUpInProcessBrowserTestFixture();
    zero_duration_mode_ =
        std::make_unique<ui::ScopedAnimationDurationScaleMode>(
            ui::ScopedAnimationDurationScaleMode::ZERO_DURATION);
  }

  void SetUpOnMainThread() override {
    ShutdownPolicyBaseTest::SetUpOnMainThread();

    // Bring up the locker screen.
    ScreenLockerTester().Lock();
  }

  void TearDownOnMainThread() override {
    ScreenLocker::Hide();
    ShutdownPolicyBaseTest::TearDownOnMainThread();
  }

 private:
  std::unique_ptr<ui::ScopedAnimationDurationScaleMode> zero_duration_mode_;
};

IN_PROC_BROWSER_TEST_F(ShutdownPolicyLockerTest, TestBasic) {
  ScreenLockerTester tester;
  EXPECT_FALSE(tester.IsLockRestartButtonShown());
  EXPECT_TRUE(tester.IsLockShutdownButtonShown());
}

IN_PROC_BROWSER_TEST_F(ShutdownPolicyLockerTest, PolicyChange) {
  ScreenLockerTester tester;
  UpdateRebootOnShutdownPolicy(true);
  RefreshDevicePolicy();
  WaitForShutdownButtonVisibility(false);
  EXPECT_TRUE(tester.IsLockRestartButtonShown());

  UpdateRebootOnShutdownPolicy(false);
  RefreshDevicePolicy();
  WaitForShutdownButtonVisibility(true);
  EXPECT_FALSE(tester.IsLockRestartButtonShown());
}

class ShutdownPolicyLoginTest : public ShutdownPolicyBaseTest {
 public:
  ShutdownPolicyLoginTest(const ShutdownPolicyLoginTest&) = delete;
  ShutdownPolicyLoginTest& operator=(const ShutdownPolicyLoginTest&) = delete;

 protected:
  ShutdownPolicyLoginTest() = default;
  ~ShutdownPolicyLoginTest() override = default;

  // ShutdownPolicyBaseTest:
  void SetUpCommandLine(base::CommandLine* command_line) override {
    command_line->AppendSwitch(switches::kLoginManager);
    command_line->AppendSwitch(switches::kForceLoginManagerInTests);
  }

  void SetUpOnMainThread() override {
    ShutdownPolicyBaseTest::SetUpOnMainThread();

    LoginOrLockScreenVisibleWaiter().Wait();
    LoginDisplayHost* host = LoginDisplayHost::default_host();
    ASSERT_TRUE(host);
    ASSERT_TRUE(host->GetOobeWebContents());

    // Wait for the login UI to be ready.
    WaitUntilOobeUIIsReady(host->GetOobeUI());

    // Wait for GAIA screen, as it is the first screen and Shutdown button
    // visibility depends on if it is first sign-in step or not.
    OobeScreenWaiter(GaiaView::kScreenId).Wait();
  }

  void TearDownOnMainThread() override {
    // If the login display is still showing, exit gracefully.
    if (LoginDisplayHost::default_host()) {
      base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
          FROM_HERE, base::BindOnce(&chrome::AttemptExit));
      RunUntilBrowserProcessQuits();
    }
  }
};

IN_PROC_BROWSER_TEST_F(ShutdownPolicyLoginTest, PolicyNotSet) {
  EXPECT_FALSE(LoginScreenTestApi::IsRestartButtonShown());
  EXPECT_TRUE(LoginScreenTestApi::IsShutdownButtonShown());
}

IN_PROC_BROWSER_TEST_F(ShutdownPolicyLoginTest, PolicyChange) {
  UpdateRebootOnShutdownPolicy(true);
  RefreshDevicePolicy();
  WaitForShutdownButtonVisibility(false);
  EXPECT_TRUE(LoginScreenTestApi::IsRestartButtonShown());

  UpdateRebootOnShutdownPolicy(false);
  RefreshDevicePolicy();
  WaitForShutdownButtonVisibility(true);
  EXPECT_FALSE(LoginScreenTestApi::IsRestartButtonShown());
}

}  // namespace ash


text:
import { useEffect } from 'react';

import { useFolderTree } from '../../../../store';
import DriveSidebarFoldersRoot from './DriveSidebarFoldersRoot';
import DriveSidebarSubfolders from './DriveSidebarSubfolders';

interface Props {
    path: string;
    shareId: string;
    linkId: string;
    setSidebarLevel: (level: number) => void;
}

export default function DriveSidebarFolders({ shareId, linkId, path, setSidebarLevel }: Props) {
    const { deepestOpenedLevel, rootFolder, toggleExpand } = useFolderTree(shareId, { rootLinkId: linkId });

    useEffect(() => {
        setSidebarLevel(deepestOpenedLevel);
    }, [deepestOpenedLevel]);

    return (
        <>
            <DriveSidebarFoldersRoot
                path={path}
                shareId={shareId}
                linkId={linkId}
                rootFolder={rootFolder}
                toggleExpand={toggleExpand}
            />
            <DriveSidebarSubfolders shareId={shareId} rootFolder={rootFolder} toggleExpand={toggleExpand} />
        </>
    );
}


text:
{% extends "media/base_videos.html" %}

{% block title %}{{ object.title }}{% endblock %}

{% block content_title %}
  <h2>{{ object.title }}</h2>
{% endblock %}

{% block content %}

{% endblock %}


text:
define({
  "addDistance": "Lägg till längdenhet",
  "addArea": "Lägg till areaenhet",
  "label": "Etikett",
  "abbr": "Förkortning",
  "conversion": "Konvertering",
  "actions": "Åtgärder",
  "areaUnits": "Areaenheter",
  "distanceUnits": "Längdenheter",
  "kilometers": "Kilometer",
  "miles": "Engelska mil",
  "meters": "Meter",
  "feet": "Fot",
  "yards": "Yard",
  "squareKilometers": "Kvadratkilometer",
  "squareMiles": "Square miles",
  "acres": "Tunnland",
  "hectares": "Hektar",
  "squareMeters": "Kvadratmeter",
  "squareFeet": "Square feet",
  "squareYards": "Square yards",
  "distance": "Distanser",
  "area": "Ytor",
  "kilometersAbbreviation": "km",
  "milesAbbreviation": "mi",
  "metersAbbreviation": "m",
  "feetAbbreviation": "ft",
  "yardsAbbreviation": "yd",
  "squareKilometersAbbreviation": "kv.km",
  "squareMilesAbbreviation": "eng. kv.m",
  "acresAbbreviation": "ac",
  "hectaresAbbreviation": "ha",
  "squareMetersAbbreviation": "kv.m",
  "squareFeetAbbreviation": "kv.fot",
  "squareYardsAbbreviation": "kv.yd",
  "defineUnits": "Definiera måttenheterna.",
  "operationalLayer": "Lägg till ritningen som ett funktionslager i kartan."
});


text:
"use strict";

var config = require('../config/config.js');
var env = process.env.NODE_ENV || 'development';
var graph = require('fbgraph');
var async = require('async');
var _ = require('lodash');
var fb = require('ilkkah-fb');

var monq = require('monq');
var client = monq(process.env.MONGODB_URI || config.db, { safe: true });
var queue = client.queue('sna_default');

// var ses = require('node-ses');
// var mailClient = ses.createClient({ key: 'AKIAI2OILVYQHMBBZEZQ', secret: 'AnDX6b7H9rKifsrDK5Q+TGp2qKrdz9E1dNnQs3Pll6xS', algorithm: 'HmacSHA256', amazon: 'https://email-smtp.us-west-2.amazonaws.com' });
var AmazonSES = require('amazon-ses');
// var mailClient = new AmazonSES('', '');
var mailClient = false;

var User = require('../models/user');
var UserPage = require('../models/userpage');
var Page = require('../models/page');
var Post = require('../models/post');
var Rtu = require('../models/rtu');

graph.setVersion('2.3');

var getUser = function(userID, id, cb) {
  var user;
  var query = {}

  async.series({
    getUserById: function(done) {
      query = {fbId: userID}
      if(id) query._id = id;
      User.findOne(query, function(err, me) {
        if(!me) {
          return done();
        }
        user = me;
        done();
      });
    },
    getUserByEmail: function(done) {
      query = {email: userID}
      User.findOne(query, function(err, me) {
        if(!me) {
          return done();
        }
        user = me;
        done();
      });
    }
  }, function() {
    cb(user);
  })
}

exports.deauthorize = function(req, res, next) {
  var request = fb.parseSignedRequest(req.body.signed_request, config.facebook.clientSecret);
  var rtu = new Rtu();
  rtu.body = request;
  rtu.save(function() {
    res.json({status: 'success'});
  });
};

exports.getRtu = function(req, res, next) {
  console.log('get /rtu', req.query);
  if (req.query['hub.verify_token'] === config.facebook.secretKey) {
    res.send(req.query['hub.challenge']);
  }
};

exports.postRtu = function(req, res, next) {
  console.log('post /rtu', req.body);
  var rtu = new Rtu();
  rtu.body = req.body;
  rtu.save(function() {
    res.json({status: 'success'});
  })
};

exports.validateToken = function(req, res) {
  // /debug_token?input_token=CAAUbE6b5y7QBADyjcoxqctVnry9rJBXq2TZATRw0SEAGP3mtNATmZCjUQbFKhnMFq20uzZCgLXLMK15NqLlTBM7YDGqs3ZBFGi6Xrh4VDmcItSk2h2DCIl1cht0iWG4iqgqjM9ri8jkH9a9rx2f6DIyVa3IFWxONF3T40PIuKVmsNik18pomzZA3U3iVqStsZD&access_token=503652836467629|d273b14b2880c092212dfddaa878f375
  // {
  //    "data": {
  //       "app_id": "503652836467629",
  //       "application": "ShopNow - Local Test",
  //       "expires_at": 1440936348,
  //       "is_valid": true,
  //       "issued_at": 1435752348,
  //       "scopes": [
  //          "user_location",
  //          "user_likes",
  //          "user_friends",
  //          "email",
  //          "public_profile"
  //       ],
  //       "user_id": "1119171044763213"
  //    }
  // }
  // Sun, 30 Aug 2015 12:05:48 GMT
  // https://graph.facebook.com/oauth/access_token_info?client_id=APPID&access_token=xxxxxxxxx
  res.json({status: 'success'});
}

exports.user = function(req, res, next) {
  var user = {};
  var query;

  async.series({
    getUser: function(done) {
      getUser(req.query.userID, req.query.token || null, function(me) {
        if(!me) {
          next(new Error('User not found'));
          return;
        }
        user = me;
        done();
      });
    },
  }, function() {
    res.json({status: 'success', data: user.toJSON()});
  })
}

exports.importPosts = function(req, res, next) {
  var appToken = config.facebook.clientID + '|' + config.facebook.clientSecret;
  var page;
  async.series({
    getPage: function(done) {
      Page.findOne({fbId: req.query.pageID}, function(err, me) {
        if(!me) {
          next(new Error('Page not found'));
          return;
        }
        page = me
        done();
      });
    },
    getData: function(done) {
      queue.enqueue('Q_importAllPostsPerPage', {pageID: req.query.pageID, lastImportAt: page.lastImportAt, accessToken: appToken, after: ''}, function (err, job) {
        if(err) {
          next(err);
          return;
        }
        done();
      });
    }
  }, function() {
    res.json({status: 'success'});
  })
}

exports.importPostsBulk = function(req, res, next) {
  var appToken = config.facebook.clientID + '|' + config.facebook.clientSecret;
  queue.enqueue('Q_importAllPostsPerPageBulk', {pageID: req.query.pageID, accessToken: appToken, after: ''}, function (err, job) {
    if(err) {
      next(err);
      return;
    }
    res.json({status: 'success'});
  });
}

exports.posts = function(req, res, next) {
  var pageIds = [];
  var output = [];
  var page = req.query.page || 1;
  var limit = req.query.limit || 30;
  var user = {};
  var query;

  async.series({
    getUser: function(done) {
      getUser(req.query.userID, req.query.token, function(me) {
        if(!me) {
          next(new Error('User not found'));
          return;
        }
        user = me;
        done();
      });
    },
    getAllPageIds: function(done) {
      UserPage.find({user: user.fbId}, function(err, pages) {
        pageIds = _.map(pages, function(page) {return page.page});
        done();
      });
    },
    getPagesDetails: function(done) {
      query = {page: {$in: pageIds}, isVerified: true, isEnabled: true};
      if(req.query.after) query.created_time = {$gte: req.query.after};

      Post.paginate(query, {page: page, limit: limit, sortBy: {created_time: -1}}, function(err, posts) {
        output = posts;
        done();
      });
    }
  }, function() {
    res.json({status: 'success', data: output});
  })
}

// exports.pages = function(req, res) {
//   var pageIds = [];
//   var output = [];

//   async.series({
//     getAllPageIds: function(done) {
//       UserPage.find({user: req.query.userID}, function(err, pages) {
//         pageIds = _.map(pages, function(page) {return page.page});
//         done();
//       });
//     },
//     getPagesDetails: function(done) {
//       Page.find({fbId: {$in: pageIds}, isVerified: true, isEnabled: true}, {id: 1, fbId: 1, name: 1, picture: 1, plan: 1, internal_category: true}, function(err, pages) {
//         output = pages;
//         done();
//       });
//     }
//   }, function() {
//     res.json({status: 'success', data: output});
//   })
// }

exports.pages = function(req, res, next) {
  var accounts = [];
  var pages = [];
  var output = [];
  var ids = [];
  var fields = 'id,category,name,updated_time,created_time,picture,bio,category_list,contact_address,cover,current_location,description,emails,general_info,link,phone,username,website,likes';
  var user = {};

  async.series({
    getUser: function(done) {
      getUser(req.query.userID, req.query.token, function(me) {
        if(!me) {
          next(new Error('User not found'));
          return;
        }
        user = me;
        done();
      });
    },
    getPagesByAdmin: function(done) {
      Page.find({isActivated: true}, function(err, pages) { // , admins: {$in: [req.query.userID]}
        if(!pages) {
          return done();
        }
        ids = _.map(pages, function(item) {
          return item.fbId;
        });
      });
      done();
    },
    getPagesFromGraph: function(done) {
      graph.setAccessToken(user.accessToken);

      graph.get('/' + user.fbId + '/accounts?limit=100' + (fields ? '&fields=' + fields : '') + (req.query.after ? '&after=' + req.query.after : ''), function(err, data) {
        if(data.data) accounts = data.data;
        output = _.map(accounts, function(item) {
          if(ids.indexOf(item.id) > -1) {
            item.isActivated = true;
          } else {
            item.isActivated = false;
          }
          return item;
        });
        done();
      });
    }
  }, function() {
    res.json({status: 'success', data: output, total: output.length});
  })
}

exports.friends = function(req, res, next) {
  var friends = [];
  var fields = 'id,name,picture,link';

  var user = {};
  var output = {};

  async.series({
    getUser: function(done) {
      getUser(req.query.userID, req.query.token, function(me) {
        if(!me) {
          next(new Error('User not found'));
          return;
        }
        user = me;
        done();
      });
    },
    getData: function(done) {
      graph.setAccessToken(user.accessToken);

      graph.get('/' + user.fbId + '/friends?limit=100' + (fields ? '&fields=' + fields : '') + (req.query.after ? '&after=' + req.query.after : ''), function(err, output) {
        if(output.data) friends = output.data;
        done();
      });
    }
  }, function() {
    res.json({status: 'success', data: friends, total: friends.length});
  })
}

exports.importFriends = function(req, res, next) {
  var user = {};
  var output = {};

  async.series({
    getUser: function(done) {
      getUser(req.query.userID, req.query.token, function(me) {
        if(!me) {
          next(new Error('User not found'));
          return;
        }
        user = me;
        done();
      });
    },
    Q_importAllFriendsPerUser: function(done) {
      queue.enqueue('Q_importAllFriendsPerUser', {userID: user.fbId, accessToken: user.accessToken, after: ''}, function (err, job) {
        if(err) {
          next(err);
          return;
        }
        output = job;
        done();
      });
    }
  }, function() {
    res.json({status: 'success'});
  })
}

exports.importLikes = function(req, res, next) {
  var user = {};
  var output = {};

  async.series({
    getUser: function(done) {
      getUser(req.query.userID, req.query.token, function(me) {
        if(!me) {
          next(new Error('User not found'));
          return;
        }
        user = me;
        done();
      });
    },
    Q_importAllLikesPerUser: function(done) {
      queue.enqueue('Q_importAllLikesPerUser', {userID: user.fbId, accessToken: user.accessToken, after: ''}, function (err, job) {
        if(err) {
          next(err);
          return;
        }
        output = job;
        done();
      });
    }
  }, function() {
    res.json({status: 'success'});
  })
}

exports.verifyEmail = function(req, res) {
  if(mailClient && req.query.email) {
    mailClient.verifyEmailAddress(req.query.email, function() {
      res.json({status: 'success'});
    });
  } else {
    res.json({status: 'error'});
  }
}

// TODO: After authorize (isNew = true) send notifications to all my existing friends
exports.authenticate = function(req, res) {
  var user = null;

  graph.setAccessToken(req.body.accessToken);

  async.series({
    getUser: function(done) {
      graph.get('/me?fields=email,first_name,gender,id,last_name,link,locale,name,updated_time,picture,location', function(err, output) {
        User.findOne({fbId: req.body.userID}, function(err, me) {
          if(!me) {
            user = new User();
          } else {
            user = me;
          }

          user.email = output.email;
          user.first_name = output.first_name;
          user.fbId = output.id;
          user.last_name = output.last_name;
          user.link = output.link;
          user.locale = output.locale;
          user.name = output.name;
          user.updated_time = output.updated_time;
          user.accessToken = req.body.accessToken;
          user.signedRequest = req.body.signedRequest;
          if(output.gender) user.gender = output.gender;
          if(output.picture) user.picture = output.picture.data.url;
          if(output.location) user.location = output.location.name;

          done();
        });
      });
    },
    queueImportLikes: function(done) {
      if(user.isNew) {
        queue.enqueue('Q_importAllLikesPerUser', {userID: user.fbId, accessToken: user.accessToken, after: ''}, function (err, job) {
          return done();
        });
      } else {
        done();
      }
    },
    sendWelcomeEmail: function(done) {
      if(user.isNew && user.email && mailClient) {
        console.log('Sending to', user.email);
        mailClient.send({
            from: 'chris.witko@me.com'
          , to: [user.email]
          // , replyTo: ['chris.witko@gmail.com']
          , subject: 'Test subject'
          , body: {
              text: 'This is the text of the message.'
            , html: 'This is the html body of the message.'
          }
        }, function(err, data) {
          done();
        });
      } else {
        done();
      }
    },
    addUserToMailChimp: function(done) {
      done();
    },
    getLongLifeAccessToken: function(done) {
      graph.get('/oauth/access_token?redirect_uri=' + config.host + '&grant_type=fb_exchange_token&client_id=' + config.facebook.clientID + '&client_secret=' + config.facebook.clientSecret + '&fb_exchange_token=' + req.body.accessToken, function(err, token) {
        if(token.access_token) user.accessToken = token.access_token;
        done();
      });
    },
    updateUser: function(done) {
      user.save(function() {
        done();
      });
    }
  }, function() {
    res.json({status: 'success', data: user});
  })

};

exports.getApi = function(req, res) {
  res.json({status: 'success'});
};


text:
function solve(args) {
    'use strict';
}

var args = [];

console.dir(solve(args));


text:
<?php

use Rave\Server;

/**
 * bootstrap.php
 * Bootstrap script for PHPUnit tests
 */
$_basePath = dirname( __DIR__ );
$_vendorPath = $_basePath . '/vendor';

if ( !is_dir( $_vendorPath ) )
{
    echo 'Please run composer install/update before running tests.';
    exit( 1 );
}
//	Composer
$_autoloader = require( $_basePath . '/vendor/autoload.php' );

$_server = new Server();
$_server->run();


text:
echo '<<<EXECUTING ISTANBUL>>>'
istanbul cover node_modules/.bin/_mocha -- -r server.js -R tap app/tests/* > test.tap && istanbul report clover

echo '<<<EXECUTING ESLINT>>>'
eslint -c .eslintrc.js -f checkstyle app/**/*.js > checkstyle-result.xml || echo 'LINTING FAILED... continuing...'


text:
package com.intellij.codeInsight.folding;

import com.intellij.openapi.components.PersistentStateComponent;
import com.intellij.openapi.components.State;
import com.intellij.openapi.components.Storage;
import com.intellij.util.xmlb.XmlSerializerUtil;
import jakarta.inject.Singleton;

/**
 * @author yole
 */
@Singleton
@State(name="CodeFoldingSettings", storages= @Storage("editor.codeinsight.xml"))
public class CodeFoldingSettingsImpl extends CodeFoldingSettings implements PersistentStateComponent<CodeFoldingSettings> {

  @Override
  public CodeFoldingSettings getState() {
    return this;
  }

  @Override
  public void loadState(final CodeFoldingSettings state) {
    XmlSerializerUtil.copyBean(state, this);
  }
}


text:
package no.finn.repoindexer.flows

import java.io.File

import ammonite.ops.Path
import com.jcraft.jsch.{Session, JSch}
import com.typesafe.config.ConfigFactory
import no.finn.repoindexer.{IndexRepo, CloneRepo}
import org.eclipse.jgit.api.{Git, TransportConfigCallback}
import org.eclipse.jgit.internal.storage.file.FileRepository
import org.eclipse.jgit.lib.TextProgressMonitor
import org.eclipse.jgit.transport.{SshTransport, Transport, OpenSshConfig, JschConfigSessionFactory}
import org.eclipse.jgit.util.FS
import org.json4s.DefaultFormats
import akka.stream.scaladsl._
import resource._
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future
import scala.util.{Failure, Success, Try}

object Cloner {
  val config = ConfigFactory.load()
  val privateKeyPath = config.getString("bamboo.privatekey")
  val privateKeyPass = config.getString("bamboo.privatepass")
  val localRepoFolder = config.getString("repo.folder")

  class CustomConfigSessionFactory extends JschConfigSessionFactory {
    override protected def getJSch(hc: OpenSshConfig.Host, fs: FS) : JSch = {
      val jsch = super.getJSch(hc, fs)
      jsch.removeAllIdentity()
      jsch.addIdentity(privateKeyPath, privateKeyPass)
      jsch
    }
    override protected def configure(hc: OpenSshConfig.Host, session: Session): Unit = {

    }
  }
  val progressMonitor = new TextProgressMonitor()

  val transportConfig = new TransportConfigCallback() {
    override def configure(transport: Transport): Unit = {
      val sshTransport = transport.asInstanceOf[SshTransport]
      sshTransport.setSshSessionFactory(sshSessionFactory)
    }
  }
  val sshSessionFactory = new CustomConfigSessionFactory()

  val cloneFlow : Flow[CloneRepo, IndexRepo, akka.NotUsed] = Flow[CloneRepo].mapAsyncUnordered(4) { repo =>
    repo.sshClone match {
      case Some(cloneUrl) => {
        val localPath = new File(localRepoFolder, repo.escapedUrl(cloneUrl))
        Future {
          if (localPath.exists) {
            val git = new Git(new FileRepository(new File(localPath, ".git")))
            try {
              git.pull()
                .setTransportConfigCallback(transportConfig)
                .setProgressMonitor(progressMonitor)
                .call()
            } catch {
              case e: Exception => println("Something went wrong while pulling")
            } finally {
              git.close()
            }
          } else {
            localPath.mkdirs()
            val url = cloneUrl.href
            println(s"Cloning ${repo}")
            for {
              repo <- managed(Git
                .cloneRepository()
                .setURI(url)
                .setDirectory(localPath)
                .setTransportConfigCallback(transportConfig)
                .setProgressMonitor(progressMonitor)
                .call()
              )
            } {

            }
          }
          IndexRepo(Path(localPath), repo.slug, cloneUrl.href)
        }
      }
      case None => Future.failed(new IllegalStateException("No cloneurl"))
    }
  }

  val stashCloningFlow = Stash.cloneCandidatesFlow.via(cloneFlow)
}


text:
from aefat.feeds.models import Feed
from aefat.auth.models import Profile
from aefat.articles.models import Article
from aefat.articles.models import ArticleComment
from django.contrib import admin

admin.site.register(Feed)
admin.site.register(Profile)
admin.site.register(Article)
admin.site.register(ArticleComment)


text:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:layout_centerVertical="true"
        android:padding="20dp">

        <Button
            android:id="@+id/button1"
            android:layout_width="match_parent"
            android:layout_height="100dp"
            android:layout_centerVertical="true"
            android:text="Opción 1 - WebView" />

        <Button
            android:id="@+id/button2"
            android:layout_width="match_parent"
            android:layout_height="100dp"
            android:layout_centerVertical="true"
            android:text="Opción 2 - Abrir navegador" />

    </LinearLayout>

</RelativeLayout>


text:
{%- block htmltitle %}
<!doctype html>
{%- endblock %}

        {%- block head_metatags %}

        <meta charset="{{ encoding }}">

        <meta name="viewport" content="width=device-width, initial-scale=1.0">

        <meta name="description" content="{{ description }}">
        <meta name="keywords" content="">
        <meta name="author" content="{{ author }}">
        {%- endblock %}

        {%- block head_title %}
        <title>{{ title|striptags|e }}{{ titlesuffix }}</title>
        {%- endblock %}

        {%- block head_linktags %}
        <link rel="shortcut icon" href="_static/subcmd.ico">

        {%- endblock %}

        {%- block stylesheets %}
        <link href="_static/bootstrap.css" rel="stylesheet">
        <link href="_static/pygments.css" rel="stylesheet">
        <link href="_static/subcmd.css" rel="stylesheet">
        {%- endblock %}

        {%- block headextra %}
        {%- endblock %}

        {%- block header %}
        {%- endblock %}

            {%- block body %}{%- endblock %}

        {%- block footer %}

Home | Back to top

            Raül Pérez, repejota@gmail.com

        {%- endblock %}

        {%- block scripts %}

        {%- endblock %}


text:
package com.badlogic.gdx.ai.fma;

import com.badlogic.gdx.math.Vector;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.BooleanArray;
import com.badlogic.gdx.utils.GdxRuntimeException;

/** {@code SoftRoleSlotAssignmentStrategy} is a concrete implementation of {@link BoundedSlotAssignmentStrategy} that supports soft
 * roles, i.e. roles that can be broken. Rather than a member having a list of roles it can fulfill, it has a set of values
 * representing how difficult it would find it to fulfill every role. The value is known as the slot cost. To make a slot
 * impossible for a member to fill, its slot cost should be infinite (you can even set a threshold to ignore all slots whose cost
 * is too high; this will reduce computation time when several costs are exceeding). To make a slot ideal for a member, its slot
 * cost should be zero. We can have different levels of unsuitable assignment for one member.
 *

 * Slot costs do not necessarily have to depend only on the member and the slot roles. They can be generalized to include any
 * difficulty a member might have in taking up a slot. If a formation is spread out, for example, a member may choose a slot that
 * is close by over a more distant slot. Distance can be directly used as a slot cost.
 *

 * IMPORTANT NOTES:
 *

 *
In order for the algorithm to work properly the slot costs can not be negative.

 *
This algorithm is often not fast enough to be used regularly. However, slot assignment happens relatively seldom (when the
 * player selects a new pattern, for example, or adds a member to the formation, or a member is removed from the formation).

 *

 *
 * @param <T> Type of vector, either 2D or 3D, implementing the {@link Vector} interface
 *
 * @author davebaol */
public class SoftRoleSlotAssignmentStrategy<T extends Vector<T>> extends BoundedSlotAssignmentStrategy<T> {

	protected SlotCostProvider<T> slotCostProvider;

	protected float costThreshold;

	private BooleanArray filledSlots;

	/** Creates a {@code SoftRoleSlotAssignmentStrategy} with the given slot cost provider and no cost threshold.
	 * @param slotCostProvider the slot cost provider */
	public SoftRoleSlotAssignmentStrategy (SlotCostProvider<T> slotCostProvider) {
		this(slotCostProvider, Float.POSITIVE_INFINITY);
	}

	/** Creates a {@code SoftRoleSlotAssignmentStrategy} with the given slot cost provider and cost threshold.
	 * @param slotCostProvider the slot cost provider
	 * @param costThreshold is a slot-cost limit, beyond which a slot is considered to be too expensive to consider occupying. */
	public SoftRoleSlotAssignmentStrategy (SlotCostProvider<T> slotCostProvider, float costThreshold) {
		this.slotCostProvider = slotCostProvider;
		this.costThreshold = costThreshold;

		this.filledSlots = new BooleanArray();
	}

	@Override
	public void updateSlotAssignments (Array<SlotAssignment<T>> assignments) {

		// Holds a list of member and slot data for each member.
		Array<MemberAndSlots<T>> memberData = new Array<MemberAndSlots<T>>();

		// Compile the member data
		int numberOfAssignments = assignments.size;
		for (int i = 0; i < numberOfAssignments; i++) {
			SlotAssignment<T> assignment = assignments.get(i);

			// Create a new member datum, and fill it
			MemberAndSlots<T> datum = new MemberAndSlots<T>(assignment.member);

			// Add each valid slot to it
			for (int j = 0; j < numberOfAssignments; j++) {

				// Get the cost of the slot
				float cost = slotCostProvider.getCost(assignment.member, j);

				// Make sure the slot is valid
				if (cost >= costThreshold) continue;

				SlotAssignment<T> slot = assignments.get(j);

				// Store the slot information
				CostAndSlot<T> slotDatum = new CostAndSlot<T>(cost, slot.slotNumber);
				datum.costAndSlots.add(slotDatum);

				// Add it to the member's ease of assignment
				datum.assignmentEase += 1f / (1f + cost);
			}

			// Add member datum
			memberData.add(datum);
		}

		// Reset the array to keep track of which slots we have already filled.
		if (numberOfAssignments > filledSlots.size) filledSlots.ensureCapacity(numberOfAssignments - filledSlots.size);
		filledSlots.size = numberOfAssignments;
		for (int i = 0; i < numberOfAssignments; i++)
			filledSlots.set(i, false);

		// Arrange members in order of ease of assignment, with the least easy first.
		memberData.sort();
		MEMBER_LOOP:
		for (int i = 0; i < memberData.size; i++) {
			MemberAndSlots<T> memberDatum = memberData.get(i);

			// Choose the first slot in the list that is still empty (non-filled)
			memberDatum.costAndSlots.sort();
			int m = memberDatum.costAndSlots.size;
			for (int j = 0; j < m; j++) {
				int slotNumber = memberDatum.costAndSlots.get(j).slotNumber;

				// Check if this slot is valid
				if (!filledSlots.get(slotNumber)) {
					// Fill this slot
					SlotAssignment<T> slot = assignments.get(slotNumber);
					slot.member = memberDatum.member;
					slot.slotNumber = slotNumber;

					// Reserve the slot
					filledSlots.set(slotNumber, true);

					// Go to the next member
					continue MEMBER_LOOP;
				}
			}

			// If we reach here, it's because a member has no valid assignment.
			//
			// TODO
			// Some sensible action should be taken, such as reporting to the player.
			throw new GdxRuntimeException("SoftRoleSlotAssignmentStrategy cannot find valid slot assignment for member "
				+ memberDatum.member);
		}

	}

	static class CostAndSlot<T extends Vector<T>> implements Comparable<CostAndSlot<T>> {
		float cost;
		int slotNumber;

		public CostAndSlot (float cost, int slotNumber) {
			this.cost = cost;
			this.slotNumber = slotNumber;
		}

		@Override
		public int compareTo (CostAndSlot<T> other) {
			return cost < other.cost ? -1 : (cost > other.cost ? 1 : 0);
		}
	}

	static class MemberAndSlots<T extends Vector<T>> implements Comparable<MemberAndSlots<T>> {
		FormationMember<T> member;
		float assignmentEase;
		Array<CostAndSlot<T>> costAndSlots;

		public MemberAndSlots (FormationMember<T> member) {
			this.member = member;
			this.assignmentEase = 0f;
			this.costAndSlots = new Array<CostAndSlot<T>>();
		}

		@Override
		public int compareTo (MemberAndSlots<T> other) {
			return assignmentEase < other.assignmentEase ? -1 : (assignmentEase > other.assignmentEase ? 1 : 0);
		}
	}

	public interface SlotCostProvider<T extends Vector<T>> {

		public float getCost (FormationMember<T> member, int slotNumber);

	}
}


text:
<?php

namespace PHPComponent\DI\Tests\Extensions;

use PHPComponent\DI\Compiler;
use PHPComponent\DI\ContainerBuilder;
use PHPComponent\DI\Extensions\Extension;
use PHPComponent\DI\ParametersBag;
use PHPComponent\PhpCodeGenerator\CodeFormatter;

/**
 * @author František Šitner <frantisek.sitner@gmail.com>
 */
class ExtensionTest extends \PHPUnit_Framework_TestCase
{

    public function testExtension()
    {
        /** @var ParametersBag|\PHPUnit_Framework_MockObject_MockObject $parameters_bag */
        $parameters_bag = $this->getMockBuilder(ParametersBag::class)
            ->getMock();
        /** @var ContainerBuilder|\PHPUnit_Framework_MockObject_MockObject $container_builder */
        $container_builder = $this->getMockBuilder(ContainerBuilder::class)
            ->setConstructorArgs(array($parameters_bag))
            ->getMock();
        $code_formatter = $this->getMockBuilder(CodeFormatter::class)
            ->getMock();
        /** @var Compiler|\PHPUnit_Framework_MockObject_MockObject $compiler */
        $compiler = $this->getMockBuilder(Compiler::class)
            ->setConstructorArgs(array($container_builder, $code_formatter))
            ->getMock();

        /** @var \PHPUnit_Framework_MockObject_MockObject|Extension $extension */
        $extension = $this->getMockForAbstractClass(Extension::class);
        $this->assertNull($extension->getCompiler());
        $extension->setCompiler($compiler);
        $this->assertSame($compiler, $extension->getCompiler());
    }

    public function testExtensionName()
    {
        $this->assertSame('Extension', Extension::getExtensionName());
    }
}


text:
import {addPlayerAction, addRandomPlayerAction} from './add-player'
import {ActionTypes} from '../../action-types'

test('it should return add player action', () => {
  const expected = {
    type: ActionTypes.ADD_PLAYER,
    payload: 'John'
  }
  const actual = addPlayerAction('John')
  expect(actual).toEqual(expected)
})

test('addRandomPlayer should return add player action with random player name', () => {
  const actual = addRandomPlayerAction()
  expect(actual.type).toEqual(ActionTypes.ADD_PLAYER)
  expect(typeof actual.payload).toEqual('string')
})


text:
<?hh

require_once 'quizzer/domain/Test.hh';

class TestsDeserializer {

    /**
     * Deserializes the JSON representation received as arguments to a list of Test objects.
     *
     * @param $json JSON representation of Test objects
     * @return array a list containing the tests deserialized
     */
    public static function deserialize(string $json): array {
        $data = json_decode($json);
        $tests = array();

        if (isset($data->tests)) {
            foreach($data->tests as $test) {
                if (isset($test->quizz) && isset($test->assessment) && isset($test->scores)) {
                    $tests[] = new Test($test->quizz, $test->assessment, $test->scores);
                }
            }
        }

        return $tests;
    }
}


text:
Ubuntu 14.04 prerequisites
-----------------------
```sh
sudo apt-get install g++ libncurses5-dev libprocps3-dev autoconf autoconf-archive
```

Initial setup
-------------
```sh
autoreconf -i
make
```


text:
package org.apache.hadoop.hbase.master.procedure;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.HBaseClassTestRule;
import org.apache.hadoop.hbase.HBaseTestingUtility;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.Waiter.ExplainingPredicate;
import org.apache.hadoop.hbase.client.BalanceRequest;
import org.apache.hadoop.hbase.client.ColumnFamilyDescriptorBuilder;
import org.apache.hadoop.hbase.client.Durability;
import org.apache.hadoop.hbase.client.Get;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.client.Table;
import org.apache.hadoop.hbase.client.TableDescriptorBuilder;
import org.apache.hadoop.hbase.coprocessor.CoprocessorHost;
import org.apache.hadoop.hbase.coprocessor.ObserverContext;
import org.apache.hadoop.hbase.coprocessor.RegionCoprocessor;
import org.apache.hadoop.hbase.coprocessor.RegionCoprocessorEnvironment;
import org.apache.hadoop.hbase.coprocessor.RegionObserver;
import org.apache.hadoop.hbase.procedure2.ProcedureExecutor;
import org.apache.hadoop.hbase.regionserver.HRegionServer;
import org.apache.hadoop.hbase.testclassification.LargeTests;
import org.apache.hadoop.hbase.testclassification.MasterTests;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.hbase.util.JVMClusterUtil.RegionServerThread;
import org.apache.hadoop.hbase.wal.WALEdit;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.experimental.categories.Category;

/**
 * Test to ensure that the priority for procedures and stuck checker can partially solve the problem
 * describe in HBASE-19976, that is, RecoverMetaProcedure can finally be executed within a certain
 * period of time.
 */
@Category({ MasterTests.class, LargeTests.class })
public class TestProcedurePriority {

  @ClassRule
  public static final HBaseClassTestRule CLASS_RULE =
    HBaseClassTestRule.forClass(TestProcedurePriority.class);

  private static final HBaseTestingUtility UTIL = new HBaseTestingUtility();

  private static String TABLE_NAME_PREFIX = "TestProcedurePriority-";

  private static byte[] CF = Bytes.toBytes("cf");

  private static byte[] CQ = Bytes.toBytes("cq");

  private static int CORE_POOL_SIZE;

  private static int TABLE_COUNT;

  private static volatile boolean FAIL = false;

  public static final class MyCP implements RegionObserver, RegionCoprocessor {

    @Override
    public Optional<RegionObserver> getRegionObserver() {
      return Optional.of(this);
    }

    @Override
    public void preGetOp(ObserverContext<RegionCoprocessorEnvironment> c, Get get,
      List<Cell> result) throws IOException {
      if (FAIL && c.getEnvironment().getRegionInfo().isMetaRegion()) {
        throw new IOException("Inject error");
      }
    }

    @Override
    public void prePut(ObserverContext<RegionCoprocessorEnvironment> c, Put put, WALEdit edit,
      Durability durability) throws IOException {
      if (FAIL && c.getEnvironment().getRegionInfo().isMetaRegion()) {
        throw new IOException("Inject error");
      }
    }
  }

  @BeforeClass
  public static void setUp() throws Exception {
    UTIL.getConfiguration().setLong(ProcedureExecutor.WORKER_KEEP_ALIVE_TIME_CONF_KEY, 5000);
    UTIL.getConfiguration().setInt(MasterProcedureConstants.MASTER_PROCEDURE_THREADS, 4);
    UTIL.getConfiguration().set(CoprocessorHost.REGION_COPROCESSOR_CONF_KEY, MyCP.class.getName());
    UTIL.startMiniCluster(3);
    CORE_POOL_SIZE =
      UTIL.getMiniHBaseCluster().getMaster().getMasterProcedureExecutor().getCorePoolSize();
    TABLE_COUNT = 50 * CORE_POOL_SIZE;
    List<Future<?>> futures = new ArrayList<>();
    for (int i = 0; i < TABLE_COUNT; i++) {
      futures.add(UTIL.getAdmin().createTableAsync(
        TableDescriptorBuilder.newBuilder(TableName.valueOf(TABLE_NAME_PREFIX + i))
          .setColumnFamily(ColumnFamilyDescriptorBuilder.of(CF)).build()));
    }
    for (Future<?> future : futures) {
      future.get(1, TimeUnit.MINUTES);
    }
    UTIL.getAdmin().balance(BalanceRequest.newBuilder().setIgnoreRegionsInTransition(true).build());
    UTIL.waitUntilNoRegionsInTransition();
  }

  @AfterClass
  public static void tearDown() throws Exception {
    UTIL.shutdownMiniCluster();
  }

  @Test
  public void test() throws Exception {
    RegionServerThread rsWithMetaThread = UTIL.getMiniHBaseCluster().getRegionServerThreads()
      .stream().filter(t -> !t.getRegionServer().getRegions(TableName.META_TABLE_NAME).isEmpty())
      .findAny().get();
    HRegionServer rsNoMeta = UTIL.getOtherRegionServer(rsWithMetaThread.getRegionServer());
    // wait for NS table initialization to avoid our error inject affecting master initialization
    UTIL.waitTableAvailable(TableName.NAMESPACE_TABLE_NAME);
    FAIL = true;
    UTIL.getMiniHBaseCluster().killRegionServer(rsNoMeta.getServerName());
    // wait until all the worker thread are stuck, which means that the stuck checker will start to
    // add new worker thread.
    ProcedureExecutor<?> executor =
      UTIL.getMiniHBaseCluster().getMaster().getMasterProcedureExecutor();
    UTIL.waitFor(60000, new ExplainingPredicate<Exception>() {

      @Override
      public boolean evaluate() throws Exception {
        return executor.getWorkerThreadCount() > CORE_POOL_SIZE;
      }

      @Override
      public String explainFailure() throws Exception {
        return "Stuck checker does not add new worker thread";
      }
    });
    UTIL.getMiniHBaseCluster().killRegionServer(rsWithMetaThread.getRegionServer().getServerName());
    rsWithMetaThread.join();
    FAIL = false;
    // verify that the cluster is back
    UTIL.waitUntilNoRegionsInTransition(480000);
    for (int i = 0; i < TABLE_COUNT; i++) {
      try (Table table = UTIL.getConnection().getTable(TableName.valueOf(TABLE_NAME_PREFIX + i))) {
        table.put(new Put(Bytes.toBytes(i)).addColumn(CF, CQ, Bytes.toBytes(i)));
      }
    }
    UTIL.waitFor(60000, new ExplainingPredicate<Exception>() {

      @Override
      public boolean evaluate() throws Exception {
        return executor.getWorkerThreadCount() == CORE_POOL_SIZE;
      }

      @Override
      public String explainFailure() throws Exception {
        return "The new workers do not timeout";
      }
    });
  }
}


text:
@implementation Socket

@end